commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
216f320ddf0feaa33ca478559ae087a687d8541c
source/js/main.js
source/js/main.js
window.$claudia = { imgAddLoadedEvent: function () { var images = document.querySelectorAll('.js-progressive-loading') // TODO: type is image ? // TODO: read data-backdrop function loaded(event) { var image = event.currentTarget var parent = image.parentElement var parentWidth = Math.round(parent.getBoundingClientRect().width) var childImgWidth = Math.round(image.getBoundingClientRect().width) image.style.opacity = 1 var isCovered = parentWidth === childImgWidth var blurImg = parent.previousElementSibling if (isCovered) { blurImg.classList.add('is-hidden') return } blurImg.classList.remove('is-hidden') } function eachImage(noNeedLoadEvt) { images.forEach(function (img) { if (img.complete) { loaded({ currentTarget: img }) return } if (noNeedLoadEvt) return img.addEventListener('load', loaded) }) } // 截流 function throttle(func, time) { var wait = false return function () { if (wait) return wait = true setTimeout(function () { func() wait = false }, time) } } window.addEventListener('resize', throttle(function () { eachImage(true) }, 100)) eachImage() } } document.addEventListener('DOMContentLoaded', function () { $claudia.imgAddLoadedEvent() })
window.$claudia = { throttle: function (func, time) { var wait = false return function () { if (wait) return wait = true setTimeout(function () { func() wait = false }, time || 100) } }, fadeInImage: function(imgs, imageLoadedCallback) { var images = imgs || document.querySelectorAll('.js-img-fadeIn') function loaded(event) { var image = event.currentTarget image.style.transition = 'opacity 320ms' image.style.opacity = 1 imageLoadedCallback && imageLoadedCallback(image) } images.forEach(function (img) { if (img.complete) { return loaded({ currentTarget: img }) } img.addEventListener('load', loaded) }) }, blurBackdropImg: function(image) { if (!image.dataset.backdrop) return var parent = image.parentElement //TODO: Not finish yes, must be a pure function var parentWidth = Math.round(parent.getBoundingClientRect().width) var childImgWidth = Math.round(image.getBoundingClientRect().width) var isCovered = parentWidth === childImgWidth var blurImg = parent.previousElementSibling //TODO: Not finish yes, must be a pure function isCovered ? blurImg.classList.add('is-hidden') : blurImg.classList.remove('is-hidden') }, }
Change the way a method is called
Change the way a method is called
JavaScript
mit
Haojen/Lucy,Haojen/Lucy
--- +++ @@ -1,58 +1,44 @@ window.$claudia = { - imgAddLoadedEvent: function () { - var images = document.querySelectorAll('.js-progressive-loading') + throttle: function (func, time) { + var wait = false + return function () { + if (wait) return + wait = true - // TODO: type is image ? - // TODO: read data-backdrop + setTimeout(function () { + func() + wait = false + }, time || 100) + } + }, + fadeInImage: function(imgs, imageLoadedCallback) { + var images = imgs || document.querySelectorAll('.js-img-fadeIn') + function loaded(event) { var image = event.currentTarget - var parent = image.parentElement - - var parentWidth = Math.round(parent.getBoundingClientRect().width) - var childImgWidth = Math.round(image.getBoundingClientRect().width) - + image.style.transition = 'opacity 320ms' image.style.opacity = 1 - - var isCovered = parentWidth === childImgWidth - var blurImg = parent.previousElementSibling - if (isCovered) { - blurImg.classList.add('is-hidden') - return - } - blurImg.classList.remove('is-hidden') + imageLoadedCallback && imageLoadedCallback(image) } - function eachImage(noNeedLoadEvt) { - images.forEach(function (img) { - if (img.complete) { - loaded({ currentTarget: img }) - return - } + images.forEach(function (img) { + if (img.complete) { + return loaded({ currentTarget: img }) + } - if (noNeedLoadEvt) return - img.addEventListener('load', loaded) - }) - } + img.addEventListener('load', loaded) + }) + }, + blurBackdropImg: function(image) { + if (!image.dataset.backdrop) return - // 截流 - function throttle(func, time) { - var wait = false - return function () { - if (wait) return - wait = true - setTimeout(function () { - func() - wait = false - }, time) - } - } + var parent = image.parentElement //TODO: Not finish yes, must be a pure function + var parentWidth = Math.round(parent.getBoundingClientRect().width) + var childImgWidth = Math.round(image.getBoundingClientRect().width) - window.addEventListener('resize', throttle(function () { eachImage(true) }, 100)) + var isCovered = parentWidth === childImgWidth + var blurImg = parent.previousElementSibling //TODO: Not finish yes, must be a pure function - eachImage() - } + isCovered ? blurImg.classList.add('is-hidden') : blurImg.classList.remove('is-hidden') + }, } - -document.addEventListener('DOMContentLoaded', function () { - $claudia.imgAddLoadedEvent() -})
b35bb87151096260f4d33f4df82fe4afcbfbbcf4
index.js
index.js
'use strict' var window = require('global/window') module.exports = function screenOrientation () { var screen = window.screen if (!screen) return null var orientation = screen.orientation || screen.mozOrientation || screen.msOrientation var parts = orientation.type.split('-') return { direction: parts[0], version: parts[1] } }
'use strict' var window = require('global/window') module.exports = function screenOrientation () { var screen = window.screen if (!screen) return null var orientation = screen.orientation || screen.mozOrientation || screen.msOrientation if (!orientation) return null var parts = orientation.type.split('-') return { direction: parts[0], version: parts[1] } }
Return null when orientation isn't supported
Return null when orientation isn't supported
JavaScript
mit
bendrucker/screen-orientation
--- +++ @@ -6,6 +6,7 @@ var screen = window.screen if (!screen) return null var orientation = screen.orientation || screen.mozOrientation || screen.msOrientation + if (!orientation) return null var parts = orientation.type.split('-') return { direction: parts[0],
b258bc865de4107053b31825d490cb0923cc8fb4
index.js
index.js
var loaderUtils = require('loader-utils'); var MessageFormat = require('messageformat'); module.exports = function(content) { var query = loaderUtils.parseQuery(this.query); var locale = query.locale || 'en'; var messages = this.exec(content); var messageFunctions = new MessageFormat(locale).compile(messages).toString('module.exports'); return messageFunctions; };
var loaderUtils = require('loader-utils'); var MessageFormat = require('messageformat'); module.exports = function(content) { var query = loaderUtils.parseQuery(this.query); var locale = query.locale || 'en'; var messages = typeof this.inputValue === 'object' ? this.inputValue : this.exec(content); var messageFunctions = new MessageFormat(locale).compile(messages); this.cacheable && this.cacheable(); this.value = messageFunctions; return messageFunctions.toString('module.exports'); };
Mark as cacheable and use loader chaining shortcut values
Mark as cacheable and use loader chaining shortcut values
JavaScript
mit
SlexAxton/messageformat.js,SlexAxton/messageformat.js,cletusw/messageformat-loader,messageformat/messageformat.js,messageformat/messageformat.js
--- +++ @@ -4,7 +4,11 @@ module.exports = function(content) { var query = loaderUtils.parseQuery(this.query); var locale = query.locale || 'en'; - var messages = this.exec(content); - var messageFunctions = new MessageFormat(locale).compile(messages).toString('module.exports'); - return messageFunctions; + var messages = typeof this.inputValue === 'object' ? this.inputValue : this.exec(content); + var messageFunctions = new MessageFormat(locale).compile(messages); + + this.cacheable && this.cacheable(); + this.value = messageFunctions; + + return messageFunctions.toString('module.exports'); };
8a5976339815d802005096f194a5811365e595ce
src/keys-driver.js
src/keys-driver.js
import {Observable} from 'rx'; import keycode from 'keycode'; export function makeKeysDriver () { return function keysDriver() { return { presses (key) { let keypress$ = Observable.fromEvent(document.body, 'keypress'); if (key) { const code = keycode(key); keypress$ = keypress$.filter(event => event.keyCode === code); } return keypress$; } } } }
import {Observable} from 'rx'; import keycode from 'keycode'; export function makeKeysDriver () { return function keysDriver() { const methods = {}; const events = ['keypress', 'keyup', 'keydown']; events.forEach(event => { const methodName = event.replace('key', ''); methods[methodName] = (key) => { let event$ = Observable.fromEvent(document.body, event); if (key) { const code = keycode(key); event$ = event$.filter(event => event.keyCode === code); } return event$; } }); return methods; } }
Add new methods to support keyup and keydown events
Add new methods to support keyup and keydown events
JavaScript
mit
raquelxmoss/cycle-keys,raquelxmoss/cycle-keys
--- +++ @@ -3,18 +3,25 @@ export function makeKeysDriver () { return function keysDriver() { - return { - presses (key) { - let keypress$ = Observable.fromEvent(document.body, 'keypress'); + const methods = {}; + const events = ['keypress', 'keyup', 'keydown']; + + events.forEach(event => { + const methodName = event.replace('key', ''); + + methods[methodName] = (key) => { + let event$ = Observable.fromEvent(document.body, event); if (key) { const code = keycode(key); - keypress$ = keypress$.filter(event => event.keyCode === code); + event$ = event$.filter(event => event.keyCode === code); } - return keypress$; + return event$; } - } + }); + + return methods; } }
ef6459b1d599305276116f31adaa0af461ccdeaa
src/lib/dom/xul.js
src/lib/dom/xul.js
import { Localization } from './base'; import { overlayElement } from './overlay'; export { contexts } from './base'; const ns = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; const allowed = { attributes: { global: ['aria-label', 'aria-valuetext', 'aria-moz-hint'], button: ['accesskey'], tab: ['label'], textbox: ['placeholder'], } }; export class XULLocalization extends Localization { overlayElement(element, translation) { return overlayElement(this, element, translation); } isElementAllowed() { return false; } isAttrAllowed(attr, element) { if (element.namespaceURI !== ns) { return false; } const tagName = element.localName; const attrName = attr.name; // is it a globally safe attribute? if (allowed.attributes.global.indexOf(attrName) !== -1) { return true; } // are there no allowed attributes for this element? if (!allowed.attributes[tagName]) { return false; } // is it allowed on this element? // XXX the allowed list should be amendable; https://bugzil.la/922573 if (allowed.attributes[tagName].indexOf(attrName) !== -1) { return true; } return false; } }
import { Localization } from './base'; import { overlayElement } from './overlay'; export { contexts } from './base'; const ns = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; const allowed = { attributes: { global: ['aria-label', 'aria-valuetext', 'aria-moz-hint'], button: ['accesskey'], key: ['key'], menu: ['label', 'accesskey'], menuitem: ['label', 'accesskey'], tab: ['label'], textbox: ['placeholder'], toolbarbutton: ['label', 'tooltiptext'], } }; export class XULLocalization extends Localization { overlayElement(element, translation) { return overlayElement(this, element, translation); } isElementAllowed() { return false; } isAttrAllowed(attr, element) { if (element.namespaceURI !== ns) { return false; } const tagName = element.localName; const attrName = attr.name; // is it a globally safe attribute? if (allowed.attributes.global.indexOf(attrName) !== -1) { return true; } // are there no allowed attributes for this element? if (!allowed.attributes[tagName]) { return false; } // is it allowed on this element? // XXX the allowed list should be amendable; https://bugzil.la/922573 if (allowed.attributes[tagName].indexOf(attrName) !== -1) { return true; } return false; } }
Define localizable attrs for XUL elements
Define localizable attrs for XUL elements Define which attributes are localizable for the following XUL elements: key, menu, menuitem, toolbarbutton
JavaScript
apache-2.0
zbraniecki/fluent.js,zbraniecki/l20n.js,projectfluent/fluent.js,projectfluent/fluent.js,projectfluent/fluent.js,l20n/l20n.js,stasm/l20n.js,zbraniecki/fluent.js
--- +++ @@ -9,8 +9,12 @@ attributes: { global: ['aria-label', 'aria-valuetext', 'aria-moz-hint'], button: ['accesskey'], + key: ['key'], + menu: ['label', 'accesskey'], + menuitem: ['label', 'accesskey'], tab: ['label'], textbox: ['placeholder'], + toolbarbutton: ['label', 'tooltiptext'], } };
0ac83f91ddbf2407d1a5ac38c9d0aa2bd52cba32
src/Label.js
src/Label.js
import React from 'react' import { Text, View } from 'react-native' import styled from 'styled-components/native' import defaultTheme from './theme' const LabelWrapper = styled.View` flex:.5; marginTop: ${props => props.inlineLabel ? 0 : 5}; ` const LabelText = styled.Text` color: ${props => props.theme.Label.color}; font-size: ${props => props.theme.Label.fontSize}; height: ${props => props.inlineLabel ? props.theme.FormGroup.height - props.theme.FormGroup.borderWidth*2 : props.theme.Label.stackedHeight}; line-height: ${props => props.inlineLabel ? props.theme.FormGroup.height - props.theme.FormGroup.borderWidth*2 : props.theme.Label.stackedHeight}; ` LabelText.defaultProps = { theme: defaultTheme } const Label = props => { const { children, inlineLabel } = props return ( <LabelWrapper inlineLabel={inlineLabel}> <LabelText inlineLabel={inlineLabel}>{ children }</LabelText> </LabelWrapper> ) } Label.PropTypes = { children: React.PropTypes.string.isRequired } export default Label
import React from 'react' import { Text, View } from 'react-native' import styled from 'styled-components/native' import defaultTheme from './theme' const LabelWrapper = styled.View` flex: ${props => props.inlineLabel ? 0.5 : 1}; flex-direction: ${props => props.inlineLabel ? 'row' : 'column'}; flex-direction: column; justify-content: center; marginTop: ${props => props.inlineLabel ? 0 : 5}; ` const LabelText = styled.Text` color: ${props => props.theme.Label.color}; font-size: ${props => props.theme.Label.fontSize}; ` LabelText.defaultProps = { theme: defaultTheme } const Label = props => { const { children, inlineLabel } = props return ( <LabelWrapper inlineLabel={inlineLabel}> <LabelText inlineLabel={inlineLabel}>{ children }</LabelText> </LabelWrapper> ) } Label.PropTypes = { children: React.PropTypes.string.isRequired } export default Label
Fix the text alignment for the label
Fix the text alignment for the label
JavaScript
mit
esbenp/react-native-clean-form,esbenp/react-native-clean-form,esbenp/react-native-clean-form
--- +++ @@ -4,15 +4,16 @@ import defaultTheme from './theme' const LabelWrapper = styled.View` - flex:.5; + flex: ${props => props.inlineLabel ? 0.5 : 1}; + flex-direction: ${props => props.inlineLabel ? 'row' : 'column'}; + flex-direction: column; + justify-content: center; marginTop: ${props => props.inlineLabel ? 0 : 5}; ` const LabelText = styled.Text` color: ${props => props.theme.Label.color}; font-size: ${props => props.theme.Label.fontSize}; - height: ${props => props.inlineLabel ? props.theme.FormGroup.height - props.theme.FormGroup.borderWidth*2 : props.theme.Label.stackedHeight}; - line-height: ${props => props.inlineLabel ? props.theme.FormGroup.height - props.theme.FormGroup.borderWidth*2 : props.theme.Label.stackedHeight}; ` LabelText.defaultProps = {
a3abc7b61824c08e3274dcdf7912f67749edb4b7
index.js
index.js
const { getRulesMatcher, getReset, createResetRule } = require("./lib"); function contains(array, item) { return array.indexOf(item) !== -1; } module.exports = (opts = {}) => { opts.rulesMatcher = opts.rulesMatcher || "bem"; opts.reset = opts.reset || "initial"; const rulesMatcher = getRulesMatcher(opts.rulesMatcher); const reset = getReset(opts.reset); return { postcssPlugin: "postcss-autoreset", prepare() { const matchedSelectors = []; return { Rule(rule) { const { selector } = rule; if (/^(-(webkit|moz|ms|o)-)?keyframes$/.test(rule.parent.name)) { return; } if (!contains(matchedSelectors, selector) && rulesMatcher(rule)) { matchedSelectors.push(selector); } }, OnceExit(root) { if (!matchedSelectors.length) { return; } root.prepend(createResetRule(matchedSelectors, reset)); }, }; }, }; }; module.exports.postcss = true;
const { getRulesMatcher, getReset, createResetRule } = require("./lib"); function contains(array, item) { return array.indexOf(item) !== -1; } module.exports = (opts = {}) => { opts.rulesMatcher = opts.rulesMatcher || "bem"; opts.reset = opts.reset || "initial"; const rulesMatcher = getRulesMatcher(opts.rulesMatcher); const reset = getReset(opts.reset); return { postcssPlugin: "postcss-autoreset", prepare() { return { OnceExit(root) { const matchedSelectors = []; root.walkRules(rule => { const { selector } = rule; if (/^(-(webkit|moz|ms|o)-)?keyframes$/.test(rule.parent.name)) { return; } if (!contains(matchedSelectors, selector) && rulesMatcher(rule)) { matchedSelectors.push(selector); } }); if (!matchedSelectors.length) { return; } root.prepend(createResetRule(matchedSelectors, reset)); }, }; }, }; }; module.exports.postcss = true;
Move the selector matcher to OnceExit
Move the selector matcher to OnceExit
JavaScript
mit
maximkoretskiy/postcss-autoreset
--- +++ @@ -12,18 +12,18 @@ return { postcssPlugin: "postcss-autoreset", prepare() { - const matchedSelectors = []; return { - Rule(rule) { - const { selector } = rule; - if (/^(-(webkit|moz|ms|o)-)?keyframes$/.test(rule.parent.name)) { - return; - } - if (!contains(matchedSelectors, selector) && rulesMatcher(rule)) { - matchedSelectors.push(selector); - } - }, OnceExit(root) { + const matchedSelectors = []; + root.walkRules(rule => { + const { selector } = rule; + if (/^(-(webkit|moz|ms|o)-)?keyframes$/.test(rule.parent.name)) { + return; + } + if (!contains(matchedSelectors, selector) && rulesMatcher(rule)) { + matchedSelectors.push(selector); + } + }); if (!matchedSelectors.length) { return; }
3c0d0248ac6f45bcd2ee552f6c34af285003ad64
index.js
index.js
'use strict'; var babel = require('babel-core'); exports.name = 'babel'; exports.inputFormats = ['es6', 'babel', 'js']; exports.outputFormat = 'js'; /** * Babel's available options. */ var availableOptions = Object.keys(babel.options); exports.render = function(str, options, locals) { // Remove any invalid options. var opts = {}; var name = null; options = options || {}; for (var index = 0; index < availableOptions.length; index++) { name = availableOptions[index]; if (name in options) { opts[name] = options[name]; } } // Process the new options with Babel. return babel.transform(str, opts).code; };
'use strict'; var babel = require('babel-core'); exports.name = 'babel'; exports.inputFormats = ['es6', 'babel', 'js']; exports.outputFormat = 'js'; /** * Babel's available options. */ var availableOptions = Object.keys(babel.options); exports.render = function(str, options, locals) { // Remove any invalid options. var opts = {}; var name = null; options = options || {}; for (var index = 0; index < availableOptions.length; index++) { name = availableOptions[index]; if (name in options) { opts[name] = options[name]; } } ['preset', 'plugin'].forEach(function (opt) { var plural = opt + 's'; if (opts[plural]) { opts[plural] = opts[plural].map(function (mod) { try { return require('babel-' + opt + '-' + mod); } catch (err) { return mod; } }); } }); // Process the new options with Babel. return babel.transform(str, opts).code; };
Add a workaround for requiring presets and options in the browser
Add a workaround for requiring presets and options in the browser
JavaScript
mit
jstransformers/jstransformer-babel
--- +++ @@ -23,6 +23,19 @@ } } + ['preset', 'plugin'].forEach(function (opt) { + var plural = opt + 's'; + if (opts[plural]) { + opts[plural] = opts[plural].map(function (mod) { + try { + return require('babel-' + opt + '-' + mod); + } catch (err) { + return mod; + } + }); + } + }); + // Process the new options with Babel. return babel.transform(str, opts).code; };
2cf82552b663002ca7a558ac0cf9ed3daeae3d0d
index.js
index.js
'use strict' require('eslint-plugin-html') module.exports = { settings: [ 'html/html-extensions': ['.vue'], 'html/xml-extensions': [] ], rules: { 'jsx-uses-vars': require('eslint-plugin-react/lib/rules/jsx-uses-vars') } }
'use strict' require('eslint-plugin-html') module.exports = { settings: { 'html/html-extensions': ['.vue'], 'html/xml-extensions': [] }, rules: { 'jsx-uses-vars': require('eslint-plugin-react/lib/rules/jsx-uses-vars') } }
Update to square to curly braces
Update to square to curly braces
JavaScript
mit
armano2/eslint-plugin-vue,armano2/eslint-plugin-vue
--- +++ @@ -3,10 +3,10 @@ require('eslint-plugin-html') module.exports = { - settings: [ + settings: { 'html/html-extensions': ['.vue'], 'html/xml-extensions': [] - ], + }, rules: { 'jsx-uses-vars': require('eslint-plugin-react/lib/rules/jsx-uses-vars') }
6a4c471f73cf52bc323fe93ad3e4f87d136cccc6
grid-packages/ag-grid-docs/src/javascript-charts-legend/legend-position/main.js
grid-packages/ag-grid-docs/src/javascript-charts-legend/legend-position/main.js
var options = { container: document.getElementById('myChart'), data: [ { label: 'Android', value: 56.9 }, { label: 'iOS', value: 22.5 }, { label: 'BlackBerry', value: 6.8 }, { label: 'Symbian', value: 8.5 }, { label: 'Bada', value: 2.6 }, { label: 'Windows', value: 1.9 } ], series: [{ type: 'pie', angleKey: 'value', labelKey: 'label', strokeWidth: 3 }], legend: { position: 'right' } }; var chart = agCharts.AgChart.create(options); function updateLegendPosition(value) { chart.legend.position = value; } function setLegendEnabled(enabled) { chart.legend.enabled = enabled; }
var options = { container: document.getElementById('myChart'), data: [ { label: 'Android', value: 56.9 }, { label: 'iOS', value: 22.5 }, { label: 'BlackBerry', value: 6.8 }, { label: 'Symbian', value: 8.5 }, { label: 'Bada', value: 2.6 }, { label: 'Windows', value: 1.9 } ], series: [{ type: 'pie', angleKey: 'value', labelKey: 'label', strokeWidth: 3 }], legend: { position: 'right' } }; var chart = agCharts.AgChart.create(options); function updateLegendPosition(value) { options.legend.position = value; agCharts.AgChart.update(chart, options); } function setLegendEnabled(enabled) { options.legend.enabled = enabled; agCharts.AgChart.update(chart, options); }
Fix "Legend Position and Visibility" example.
Fix "Legend Position and Visibility" example.
JavaScript
mit
ceolter/angular-grid,ceolter/angular-grid,ceolter/ag-grid,ceolter/ag-grid
--- +++ @@ -22,9 +22,11 @@ var chart = agCharts.AgChart.create(options); function updateLegendPosition(value) { - chart.legend.position = value; + options.legend.position = value; + agCharts.AgChart.update(chart, options); } function setLegendEnabled(enabled) { - chart.legend.enabled = enabled; + options.legend.enabled = enabled; + agCharts.AgChart.update(chart, options); }
efb58791720fd70f578581b4e555c42f0397db04
copy/opt/local/lib/GNUstep/SOGo/WebServerResources/js/CustomModification.js
copy/opt/local/lib/GNUstep/SOGo/WebServerResources/js/CustomModification.js
// custom mods document.addEventListener("DOMContentLoaded", function(event) { // hide email right/sharing menu entries (as they do not work with some imap servers) var hideElements = [ 'body > main > md-sidenav > md-content > section > md-list > md-list-item > div > div.md-secondary-container > button:nth-child(1)', '.md-open-menu-container > md-menu-content > md-menu-item[ng-show*=additional]', '.md-open-menu-container > md-menu-content > md-menu-divider[ng-show*=additional]', ]; var css = hideElements.join(', ') + ' { display: none !important; }\n'; css += 'input[ng-model="$AccountDialogController.account.identities[0].email"] { pointer-events: none; tabindex: -1; color: rgba(0,0,0,0.38);}' // insert styles var head = document.head || document.getElementsByTagName('head')[0]; var style = document.createElement('style'); style.type = 'text/css'; if (style.styleSheet){ style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } head.appendChild(style); });
// custom mods document.addEventListener("DOMContentLoaded", function(event) { // hide email right/sharing menu entries (as they do not work with some imap servers) var hideElements = [ 'body > main > md-sidenav > md-content > section > md-list > md-list-item > div > div.md-secondary-container > button:nth-child(2)', '.md-open-menu-container > md-menu-content > md-menu-item[ng-show*=additional]', '.md-open-menu-container > md-menu-content > md-menu-divider[ng-show*=additional]', '.md-open-menu-container > md-menu-content > md-menu-item[ng-show*="account.id"]', 'md-dialog > md-dialog-content > div > md-autocomplete[md-selected-item-change="acl.addUser(user)"]', 'md-dialog > md-dialog-content > div > md-icon', ]; var css = hideElements.join(', ') + ' { display: none !important; }\n'; css += 'input[ng-model="$AccountDialogController.account.identities[0].email"] { pointer-events: none; tabindex: -1; color: rgba(0,0,0,0.38);}' // insert styles var head = document.head || document.getElementsByTagName('head')[0]; var style = document.createElement('style'); style.type = 'text/css'; if (style.styleSheet){ style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } head.appendChild(style); });
Hide search and delegate options
Hide search and delegate options
JavaScript
mit
skylime/mi-core-sogo,skylime/mi-core-sogo
--- +++ @@ -3,9 +3,12 @@ // hide email right/sharing menu entries (as they do not work with some imap servers) var hideElements = [ - 'body > main > md-sidenav > md-content > section > md-list > md-list-item > div > div.md-secondary-container > button:nth-child(1)', + 'body > main > md-sidenav > md-content > section > md-list > md-list-item > div > div.md-secondary-container > button:nth-child(2)', '.md-open-menu-container > md-menu-content > md-menu-item[ng-show*=additional]', '.md-open-menu-container > md-menu-content > md-menu-divider[ng-show*=additional]', + '.md-open-menu-container > md-menu-content > md-menu-item[ng-show*="account.id"]', + 'md-dialog > md-dialog-content > div > md-autocomplete[md-selected-item-change="acl.addUser(user)"]', + 'md-dialog > md-dialog-content > div > md-icon', ]; var css = hideElements.join(', ') + ' { display: none !important; }\n';
36d98c93af18c4524986252fdf035909666ec457
app/transformers/check-in.js
app/transformers/check-in.js
var Mystique = require('mystique'); var Mystique = require('mystique'); var getIdForModel = function(model, propertyName) { var prop = model.get(propertyName); if (typeof prop === 'string') { return prop; } return prop.id; }; var CheckInTransformer = Mystique.Transformer.extend({ resourceName: 'checkIn', mapOut: function(checkIn) { return { // book: getIdForModel(checkIn, 'book'), book: checkIn.get('book'), checkedInAt: checkIn.checkedInAt, checkedOutAt: checkIn.checkedOutAt, }; }, mapIn(req) { return { book: req.body.checkIn.book, checkedInAt: req.body.checkIn.checkedInAt, checkedOutAt: req.body.checkIn.checkedOutAt, }; }, }); Mystique.registerTransformer('CheckIn', CheckInTransformer);
var Mystique = require('mystique'); var Mongoose = require('mongoose'); var ObjectId = Mongoose.Types.ObjectId; var getIdForModel = function(model, propertyName) { var prop = model.get(propertyName); if (prop instanceof ObjectId) { return prop; } return prop.id; }; var CheckInTransformer = Mystique.Transformer.extend({ resourceName: 'checkIn', mapOut: function(checkIn) { return { book: getIdForModel(checkIn, 'book'), checkedInAt: checkIn.checkedInAt, checkedOutAt: checkIn.checkedOutAt, }; }, mapIn(req) { return { book: req.body.checkIn.book, checkedInAt: req.body.checkIn.checkedInAt, checkedOutAt: req.body.checkIn.checkedOutAt, }; }, }); Mystique.registerTransformer('CheckIn', CheckInTransformer);
Check if ObjectId is type
Check if ObjectId is type
JavaScript
mit
TIY-LR-FEE-2015-Fall/library-api,TIY-LR-FEE-2015-Fall/library-api,TIY-LR-FEE-2015-Fall/library-api
--- +++ @@ -1,9 +1,10 @@ var Mystique = require('mystique'); -var Mystique = require('mystique'); +var Mongoose = require('mongoose'); +var ObjectId = Mongoose.Types.ObjectId; var getIdForModel = function(model, propertyName) { var prop = model.get(propertyName); - if (typeof prop === 'string') { + if (prop instanceof ObjectId) { return prop; } @@ -15,8 +16,7 @@ mapOut: function(checkIn) { return { - // book: getIdForModel(checkIn, 'book'), - book: checkIn.get('book'), + book: getIdForModel(checkIn, 'book'), checkedInAt: checkIn.checkedInAt, checkedOutAt: checkIn.checkedOutAt, };
df6225d98d8ff406a54be343353e3c6550ed0e4a
js/ra.js
js/ra.js
/* remote ajax v 0.1.1 author by XericZephyr */ var rs = "http://ajaxproxy.sohuapps.com/ajax"; (function($) { $.rajax = (function (url, obj) { (typeof(url)=="object")?(obj=url):((obj==undefined)?obj={url:url}:obj.url=url); var d = {"url":obj.url}; (undefined!==obj.data)?(d["data"]=obj.data):false, (undefined!==obj.headers)?(d["headers"]=JSON.stringify(obj.headers),obj.headers={}):false; var r = $.extend(true, {}, obj); r.method = "POST"; r.url = rs; r.data = d; return $.ajax(r); }); })(jQuery);
/* remote ajax v 0.1.1 author by XericZephyr */ var rs = "//ajaxproxy.sohuapps.com/ajax"; (function($) { $.rajax = (function (url, obj) { (typeof(url)=="object")?(obj=url):((obj==undefined)?obj={url:url}:obj.url=url); var d = {"url":obj.url}; (undefined!==obj.data)?(d["data"]=obj.data):false, (undefined!==obj.headers)?(d["headers"]=JSON.stringify(obj.headers),obj.headers={}):false; var r = $.extend(true, {}, obj); r.method = "POST"; r.url = rs; r.data = d; return $.ajax(r); }); })(jQuery);
Make ajax proxy server flexible with HTTP and HTTPs
Make ajax proxy server flexible with HTTP and HTTPs
JavaScript
mit
XericZephyr/helminth,XericZephyr/helminth
--- +++ @@ -1,5 +1,5 @@ /* remote ajax v 0.1.1 author by XericZephyr */ -var rs = "http://ajaxproxy.sohuapps.com/ajax"; +var rs = "//ajaxproxy.sohuapps.com/ajax"; (function($) { $.rajax = (function (url, obj) {
e76a9cca48b2c8f005743c4a5d171052d6548430
src/extensions/core/components/text_property.js
src/extensions/core/components/text_property.js
var $$ = React.createElement; // TextProperty // ---------------- // var TextProperty = React.createClass({ displayName: "TextProperty", render: function() { var text = this.props.doc.get(this.props.path); // TODO: eventually I want to render annotated text here var annotatedText = text; // TODO create annotated html return $$("span", { className: "text-property " + this.props.className || "", contentEditable: true, "data-path": this.props.path.join('.'), dangerouslySetInnerHTML: {__html: annotatedText} }); } }); module.exports = TextProperty;
var $$ = React.createElement; // TextProperty // ---------------- // var TextProperty = React.createClass({ displayName: "TextProperty", render: function() { var text = this.props.doc.get(this.props.path) || ""; // TODO: eventually I want to render annotated text here var annotatedText = text; // TODO create annotated html return $$("span", { className: "text-property " + this.props.className || "", contentEditable: true, "data-path": this.props.path.join('.'), dangerouslySetInnerHTML: {__html: annotatedText} }); } }); module.exports = TextProperty;
Use empty string for not existing properties.
Use empty string for not existing properties.
JavaScript
mit
substance/archivist-composer,substance/archivist-composer
--- +++ @@ -7,7 +7,7 @@ var TextProperty = React.createClass({ displayName: "TextProperty", render: function() { - var text = this.props.doc.get(this.props.path); + var text = this.props.doc.get(this.props.path) || ""; // TODO: eventually I want to render annotated text here var annotatedText = text; // TODO create annotated html return $$("span", {
97f836a21db729eb5b97f4e8ca9e11e0cdd26495
living-with-django/models.js
living-with-django/models.js
define(['backbone'], function(B) { var M = {}; M.Entry = B.Models.extend({}); M.Entries = B.Models.extend({url: 'entries/data.json'}); return M; });
define(['backbone'], function(B) { var M = {}; M.Entry = B.Model.extend({}); M.Entries = B.Collection.extend({ model: M.Entry, url: 'entries/data.json' }); return M; });
Fix definition of collection and model.
Fix definition of collection and model.
JavaScript
mit
astex/living-with-django,astex/living-with-django,astex/living-with-django
--- +++ @@ -1,8 +1,11 @@ define(['backbone'], function(B) { var M = {}; - M.Entry = B.Models.extend({}); - M.Entries = B.Models.extend({url: 'entries/data.json'}); + M.Entry = B.Model.extend({}); + M.Entries = B.Collection.extend({ + model: M.Entry, + url: 'entries/data.json' + }); return M; });
50f102aab1ad52b33711f74f970ef079d0803d91
src/api/api.js
src/api/api.js
module.api = def( [ module.runtime ], function (runtime) { var delegate = function (method) { return function () { runtime[method].apply(null, arguments); }; }; return { configure: delegate('configure'), modulator: delegate('modulator'), define: delegate('define'), require: delegate('require'), demand: delegate('demand'), main: delegate('main') }; } );
module.api = def( [ module.runtime ], function (runtime) { var delegate = function (method) { return function () { return runtime[method].apply(null, arguments); }; }; return { configure: delegate('configure'), modulator: delegate('modulator'), define: delegate('define'), require: delegate('require'), demand: delegate('demand'), main: delegate('main') }; } );
Add wrapping modulators for js and rename amd.
Add wrapping modulators for js and rename amd.
JavaScript
bsd-3-clause
boltjs/bolt,boltjs/bolt,boltjs/bolt,boltjs/bolt
--- +++ @@ -6,7 +6,7 @@ function (runtime) { var delegate = function (method) { return function () { - runtime[method].apply(null, arguments); + return runtime[method].apply(null, arguments); }; };
89f52683ac13863e6f37055642988897e9868712
src/index.js
src/index.js
'use strict'; import backbone from 'backbone'; class Hello extends backbone.View { render() { this.$el.html('Hello, world.'); } } var myView = new Hello({el: document.getElementById('root')}); myView.render();
'use strict'; import backbone from 'backbone'; class Person extends backbone.Model { getFullName() { return this.get('firstName') + ' ' + this.get('lastName'); } } class Hello extends backbone.View { initialize() { this.person = new Person({ firstName: 'George', lastName: 'Washington' }); } render() { this.$el.html('Hello, ' + this.person.getFullName() + '.'); } } var myView = new Hello({el: document.getElementById('root')}); myView.render();
Add model class with method.
Add model class with method.
JavaScript
mit
andrewrota/backbone-with-es6-classes,andrewrota/backbone-with-es6-classes
--- +++ @@ -1,9 +1,21 @@ 'use strict'; import backbone from 'backbone'; +class Person extends backbone.Model { + getFullName() { + return this.get('firstName') + ' ' + this.get('lastName'); + } +} + class Hello extends backbone.View { + initialize() { + this.person = new Person({ + firstName: 'George', + lastName: 'Washington' + }); + } render() { - this.$el.html('Hello, world.'); + this.$el.html('Hello, ' + this.person.getFullName() + '.'); } }
fe104144615abec271cbae8313b63ee093053220
src/index.js
src/index.js
import { render } from 'solid-js/web'; import AsciinemaPlayer from './components/AsciinemaPlayer'; if (window) { window.createAsciinemaPlayer = (props, elem) => { render(() => (<AsciinemaPlayer {...props} />), elem); } }
import { render } from 'solid-js/web'; import AsciinemaPlayer from './components/AsciinemaPlayer'; if (window) { window.createAsciinemaPlayer = (props, elem) => { return render(() => (<AsciinemaPlayer {...props} />), elem); } }
Return cleanup fn from createAsciinemaPlayer
Return cleanup fn from createAsciinemaPlayer
JavaScript
apache-2.0
asciinema/asciinema-player,asciinema/asciinema-player
--- +++ @@ -3,6 +3,6 @@ if (window) { window.createAsciinemaPlayer = (props, elem) => { - render(() => (<AsciinemaPlayer {...props} />), elem); + return render(() => (<AsciinemaPlayer {...props} />), elem); } }
c1acfada01fb655a36ed8b8990babd72f4dff302
app/scripts/stores/GameStore.js
app/scripts/stores/GameStore.js
import Reflux from 'reflux'; import GameActions from '../actions/GameActions'; var GameStore = Reflux.createStore({ init() { getGameFEN() { return this.fen; }, getActivePlayer() { return this.fen.split(' ')[1] === 'w' ? "White" : "Black"; }, getAllValidMoves() { return this.valid_moves; }, getValidMoves(pos) { var valid = []; for (var move in this.valid_moves) { var movement = this.valid_moves[move].Move.substr(1).split('-'); if (movement[0] === pos) { valid.push(movement[1]); } } return valid; }, getGameHistory() { return this.history; } }); export default GameStore;
import Reflux from 'reflux'; import GameActions from '../actions/GameActions'; var GameStore = Reflux.createStore({ init() { getGameFEN() { return this.fen; }, getActivePlayer() { return this.fen.split(' ')[1] === 'w' ? "White" : "Black"; }, getAllValidMoves() { return this.valid_moves; }, getValidMoves(pos) { var valid = []; for (var move in this.valid_moves) { var to_from = this.valid_moves[move].Move.substr(1).replace('x','-').split('-'); if (to_from[0] === pos) { valid.push(to_from[1]); } } return valid; }, getGameHistory() { return this.history; } }); export default GameStore;
Correct for capture in getValidMoves from store
Correct for capture in getValidMoves from store
JavaScript
mit
gnidan/foodtastechess-client,gnidan/foodtastechess-client
--- +++ @@ -17,9 +17,9 @@ getValidMoves(pos) { var valid = []; for (var move in this.valid_moves) { - var movement = this.valid_moves[move].Move.substr(1).split('-'); - if (movement[0] === pos) { - valid.push(movement[1]); + var to_from = this.valid_moves[move].Move.substr(1).replace('x','-').split('-'); + if (to_from[0] === pos) { + valid.push(to_from[1]); } } return valid;
20f505663951000bfaca5416fa7b541802462a09
redux/src/main/browser/main-window.js
redux/src/main/browser/main-window.js
import BaseWindow from './base-window' const key = 'MainWindow'; class MainWindow extends BaseWindow { static KEY = key; constructor(url) { //TODO: implement dummy window buttons super(url, { width: 500, height: 800 , frame: false }); } get key() { return key; } } export default MainWindow
import BaseWindow from './base-window' const key = 'MainWindow'; class MainWindow extends BaseWindow { static KEY = key; constructor(url) { //TODO: implement dummy window buttons super(url, { width: 500, minWidth: 400, height: 800, minHeight: 140, frame: false }); } get key() { return key; } } export default MainWindow
Set minWidth and minHeight to MainWindow
Set minWidth and minHeight to MainWindow
JavaScript
mit
wozaki/twitter-js-apps,wozaki/twitter-js-apps
--- +++ @@ -7,7 +7,7 @@ constructor(url) { //TODO: implement dummy window buttons - super(url, { width: 500, height: 800 , frame: false }); + super(url, { width: 500, minWidth: 400, height: 800, minHeight: 140, frame: false }); } get key() {
4743ac4791130dac36240d150eb5831b945e0bf2
ionic.config.js
ionic.config.js
module.exports = { proxies: null, paths: { html : { src: ['app/**/*.html'], dest: "www/build" }, sass: { src: ['app/theme/app.+(ios|md).scss'], dest: 'www/build/css', include: [ 'node_modules/ionic-framework', 'node_modules/ionicons/dist/scss' ] }, fonts: { src: ['node_modules/ionic-framework/fonts/**/*.+(ttf|woff|woff2)'], dest: "www/build/fonts" }, watch: { sass: ['app/**/*.scss'], html: ['app/**/*.html'], livereload: [ 'www/build/**/*.html', 'www/build/**/*.js', 'www/build/**/*.css' ] } }, autoPrefixerOptions: { browsers: [ 'last 2 versions', 'iOS >= 7', 'Android >= 4', 'Explorer >= 10', 'ExplorerMobile >= 11' ], cascade: false }, // hooks execute before or after all project-related Ionic commands // (so not for start, docs, but serve, run, etc.) and take in the arguments // passed to the command as a parameter // // The format is 'before' or 'after' + commandName (uppercased) // ex: beforeServe, afterRun, beforePrepare, etc. hooks: { beforeServe: function(argv) { //console.log('beforeServe'); } } };
module.exports = { proxies: null, paths: { html : { src: ['app/**/*.html'], dest: "www/build" }, sass: { src: ['app/theme/app.+(ios|md).scss'], dest: 'www/build/css', include: [ 'node_modules/ionic-angular', 'node_modules/ionicons/dist/scss' ] }, fonts: { src: ['node_modules/ionic-angular/fonts/**/*.+(ttf|woff|woff2)'], dest: "www/build/fonts" }, watch: { sass: ['app/**/*.scss'], html: ['app/**/*.html'], livereload: [ 'www/build/**/*.html', 'www/build/**/*.js', 'www/build/**/*.css' ] } }, autoPrefixerOptions: { browsers: [ 'last 2 versions', 'iOS >= 7', 'Android >= 4', 'Explorer >= 10', 'ExplorerMobile >= 11' ], cascade: false }, // hooks execute before or after all project-related Ionic commands // (so not for start, docs, but serve, run, etc.) and take in the arguments // passed to the command as a parameter // // The format is 'before' or 'after' + commandName (uppercased) // ex: beforeServe, afterRun, beforePrepare, etc. hooks: { beforeServe: function(argv) { //console.log('beforeServe'); } } };
Fix forgotten ionic beta.2 changes
Fix forgotten ionic beta.2 changes
JavaScript
mit
zarautz/munoa,zarautz/munoa,zarautz/munoa
--- +++ @@ -10,12 +10,12 @@ src: ['app/theme/app.+(ios|md).scss'], dest: 'www/build/css', include: [ - 'node_modules/ionic-framework', + 'node_modules/ionic-angular', 'node_modules/ionicons/dist/scss' ] }, fonts: { - src: ['node_modules/ionic-framework/fonts/**/*.+(ttf|woff|woff2)'], + src: ['node_modules/ionic-angular/fonts/**/*.+(ttf|woff|woff2)'], dest: "www/build/fonts" }, watch: {
d6adea99b450602bc48aaeed2094f347331b1354
src/result-list.js
src/result-list.js
'use strict'; var bind = require('lodash.bind'); var ResponseHandler = require('./response-handler'); bind.placeholder = '_'; function ResultList(retriever, options) { if (!retriever) { throw new Error('Expected Retriever as an argument'); } options || (options = {}); this._retriever = retriever; this._onFailure = options.onFailure; this._onSuccess = options.onSuccess; this._page = options.page || 1; } ResultList.prototype.next = function() { this._retriever.query({page: this._page}); this._page += 1; return this._get(this._page - 1); }; ResultList.prototype._get = function(page) { return this._retriever .get() .then(bind(this._handleSuccess, this, '_', page)) .fail(bind(this._handleFailure, this, '_', page)); }; ResultList.prototype._handleSuccess = function(res, page) { var resHandler = new ResponseHandler(res, page, this._onSuccess); return resHandler.success(); }; ResultList.prototype._handleFailure = function(res, page) { var resHandler = new ResponseHandler(res, page, this._onFailure); return resHandler.failure(); }; module.exports = ResultList;
'use strict'; var bind = require('lodash.bind'); var ResponseHandler = require('./response-handler'); function ResultList(retriever, options) { if (!retriever) { throw new Error('Expected Retriever as an argument'); } options || (options = {}); this._retriever = retriever; this._onFailure = options.onFailure; this._onSuccess = options.onSuccess; this._page = options.page || 1; } ResultList.prototype.next = function() { this._retriever.query({page: this._page}); this._page += 1; return this._get(this._page - 1); }; ResultList.prototype._get = function(page) { return this._retriever .get() .then(bind(this._handleSuccess, this, page)) .fail(bind(this._handleFailure, this, page)); }; ResultList.prototype._handleSuccess = function(page, res) { var resHandler = new ResponseHandler(res, page, this._onSuccess); return resHandler.success(); }; ResultList.prototype._handleFailure = function(page, res) { var resHandler = new ResponseHandler(res, page, this._onFailure); return resHandler.failure(); }; module.exports = ResultList;
Switch argument order to remove placeholders
Switch argument order to remove placeholders
JavaScript
mit
yola/pixabayjs
--- +++ @@ -2,8 +2,6 @@ var bind = require('lodash.bind'); var ResponseHandler = require('./response-handler'); - -bind.placeholder = '_'; function ResultList(retriever, options) { if (!retriever) { @@ -27,16 +25,16 @@ ResultList.prototype._get = function(page) { return this._retriever .get() - .then(bind(this._handleSuccess, this, '_', page)) - .fail(bind(this._handleFailure, this, '_', page)); + .then(bind(this._handleSuccess, this, page)) + .fail(bind(this._handleFailure, this, page)); }; -ResultList.prototype._handleSuccess = function(res, page) { +ResultList.prototype._handleSuccess = function(page, res) { var resHandler = new ResponseHandler(res, page, this._onSuccess); return resHandler.success(); }; -ResultList.prototype._handleFailure = function(res, page) { +ResultList.prototype._handleFailure = function(page, res) { var resHandler = new ResponseHandler(res, page, this._onFailure); return resHandler.failure(); };
e101502348aff6edfce78ee2537bf718be8f1493
server/app.js
server/app.js
'use strict'; /** * Module dependencies. */ var express = require('express'); var routes = require('./routes'); var memos = require('./routes/memos'); var http = require('http'); var path = require('path'); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(express.favicon()); // app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' === app.get('env')) { app.use(express.errorHandler()); } app.get('/', routes.index); app.get('/memos/*', memos.list); app.get('/memos', memos.list); app.get('/files/*', memos.get); var server = http.createServer(app); server.listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); }); var io = require('socket.io').listen(server, {'log level': 0}); memos.start(io);
'use strict'; /** * Module dependencies. */ var express = require('express'); var routes = require('./routes'); var memos = require('./routes/memos'); var http = require('http'); var path = require('path'); var app = express(); // all environments app.set('port', process.env.PORT || 8000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(express.favicon()); // app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' === app.get('env')) { app.use(express.errorHandler()); } app.get('/', routes.index); app.get('/memos/*', memos.list); app.get('/memos', memos.list); app.get('/files/*', memos.get); var server = http.createServer(app); server.listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); }); var io = require('socket.io').listen(server, {'log level': 0}); memos.start(io);
Change port number to 8000
Change port number to 8000
JavaScript
mit
eqot/memo
--- +++ @@ -13,7 +13,7 @@ var app = express(); // all environments -app.set('port', process.env.PORT || 3000); +app.set('port', process.env.PORT || 8000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(express.favicon());
80dbefed34c99f9fbf521f500ad1db9675d9a6c3
gulp/config.js
gulp/config.js
var dest = "./build"; var src = './src'; module.exports = { browserSync: { open: false, https: true, server: { // We're serving the src folder as well // for sass sourcemap linking baseDir: [dest, src] }, files: [ dest + "/**", // Exclude Map files "!" + dest + "/**.map" ] }, stylus: { src: src + "/stylus/*.styl", dest: dest }, sass: { src: src + "/sass/*.{sass, scss}", dest: dest }, images: { src: src + "/images/**", dest: dest + "/images" }, markup: { src: src + "/htdocs/**", dest: dest }, ghdeploy : { }, browserify: { // Enable source maps debug: false, // Additional file extentions to make optional extensions: ['.coffee', '.hbs'], // A separate bundle will be generated for each // bundle config in the list below bundleConfigs: [ { entries: './src/javascript/app.js', dest: dest, outputName: 'app.js' }, /* { entries: './src/javascript/head.js', dest: dest, outputName: 'head.js' }, */ { entries: './src/javascript/site.js', dest: dest, outputName: 'site.js' } ] } };
var dest = "./build"; var src = './src'; module.exports = { browserSync: { open: false, https: true, port: 2112, server: { // We're serving the src folder as well // for sass sourcemap linking baseDir: [dest, src] }, files: [ dest + "/**", // Exclude Map files "!" + dest + "/**.map" ] }, stylus: { src: src + "/stylus/*.styl", dest: dest }, sass: { src: src + "/sass/*.{sass, scss}", dest: dest }, images: { src: src + "/images/**", dest: dest + "/images" }, markup: { src: src + "/htdocs/**", dest: dest }, ghdeploy : { }, browserify: { // Enable source maps debug: false, // Additional file extentions to make optional extensions: ['.coffee', '.hbs'], // A separate bundle will be generated for each // bundle config in the list below bundleConfigs: [ { entries: './src/javascript/app.js', dest: dest, outputName: 'app.js' }, /* { entries: './src/javascript/head.js', dest: dest, outputName: 'head.js' }, */ { entries: './src/javascript/site.js', dest: dest, outputName: 'site.js' } ] } };
Move dev server to port 2112 because omg collisions
Move dev server to port 2112 because omg collisions
JavaScript
mit
lmorchard/tootr
--- +++ @@ -5,6 +5,7 @@ browserSync: { open: false, https: true, + port: 2112, server: { // We're serving the src folder as well // for sass sourcemap linking
5a4a954662a987058f59dd60a60731152bd47059
src/c/admin-notification-history.js
src/c/admin-notification-history.js
window.c.AdminNotificationHistory = ((m, h, _, models) => { return { controller: (args) => { const notifications = m.prop([]), getNotifications = (user) => { let notification = models.notification; notification.getPageWithToken(m.postgrest.filtersVM({user_id: 'eq'}).user_id(user.id).parameters()).then(function(data){ notifications(data); }); return notifications(); }; getNotifications(args.user); return { notifications: notifications }; }, view: (ctrl) => { return m('.w-col.w-col-4', [ m('.fontweight-semibold.fontsize-smaller.lineheight-tighter.u-marginbottom-20', 'Histórico de notificações'), ctrl.notifications().map(function(cEvent) { return m('.w-row.fontsize-smallest.lineheight-looser.date-event', [ m('.w-col.w-col-24', [ m('.fontcolor-secondary', 'notificação: ', cEvent.template_name, ', ', 'criada em: ', h.momentify(cEvent.created_at, 'DD/MM/YYYY, HH:mm'), ', ', 'enviada em: ', h.momentify(cEvent.sent_at, 'DD/MM/YYYY, HH:mm')) ]), ]); }) ]); } }; }(window.m, window.c.h, window._, window.c.models));
window.c.AdminNotificationHistory = ((m, h, _, models) => { return { controller: (args) => { const notifications = m.prop([]), getNotifications = (user) => { let notification = models.notification; notification.getPageWithToken(m.postgrest.filtersVM({user_id: 'eq', sent_at: 'is.null'}).user_id(user.id).sent_at(!null).order({sent_at: 'desc'}).parameters()).then(function(data){ notifications(data); }); return notifications(); }; getNotifications(args.user); return { notifications: notifications }; }, view: (ctrl) => { return m('.w-col.w-col-4', [ m('.fontweight-semibold.fontsize-smaller.lineheight-tighter.u-marginbottom-20', 'Histórico de notificações'), ctrl.notifications().map(function(cEvent) { return m('.w-row.fontsize-smallest.lineheight-looser.date-event', [ m('.w-col.w-col-24', [ m('.fontcolor-secondary', h.momentify(cEvent.sent_at, 'DD/MM/YYYY, HH:mm'), ' - ', cEvent.template_name) ]), ]); }) ]); } }; }(window.m, window.c.h, window._, window.c.models));
Change template and improve query to NotificationHistory
Change template and improve query to NotificationHistory
JavaScript
mit
sushant12/catarse.js,vicnicius/catarse.js,vicnicius/catarse_admin,catarse/catarse.js,thiagocatarse/catarse.js,mikesmayer/cs2.js,catarse/catarse_admin,adrianob/catarse.js
--- +++ @@ -4,7 +4,7 @@ const notifications = m.prop([]), getNotifications = (user) => { let notification = models.notification; - notification.getPageWithToken(m.postgrest.filtersVM({user_id: 'eq'}).user_id(user.id).parameters()).then(function(data){ + notification.getPageWithToken(m.postgrest.filtersVM({user_id: 'eq', sent_at: 'is.null'}).user_id(user.id).sent_at(!null).order({sent_at: 'desc'}).parameters()).then(function(data){ notifications(data); }); return notifications(); @@ -23,10 +23,8 @@ ctrl.notifications().map(function(cEvent) { return m('.w-row.fontsize-smallest.lineheight-looser.date-event', [ m('.w-col.w-col-24', [ - m('.fontcolor-secondary', - 'notificação: ', cEvent.template_name, ', ', - 'criada em: ', h.momentify(cEvent.created_at, 'DD/MM/YYYY, HH:mm'), ', ', - 'enviada em: ', h.momentify(cEvent.sent_at, 'DD/MM/YYYY, HH:mm')) + m('.fontcolor-secondary', h.momentify(cEvent.sent_at, 'DD/MM/YYYY, HH:mm'), + ' - ', cEvent.template_name) ]), ]); })
05b276b3cde8aa9e9a67c28d4134b38b234f92f9
src/renderer/components/MapFilter/ReportView/PrintButton.js
src/renderer/components/MapFilter/ReportView/PrintButton.js
// @flow import React from 'react' import PrintIcon from '@material-ui/icons/Print' import { defineMessages, FormattedMessage } from 'react-intl' import ToolbarButton from '../internal/ToolbarButton' const messages = defineMessages({ // Button label to print a report print: 'Print' }) type Props = { disabled: boolean, url: string } class PrintButton extends React.Component<Props, State> { download () { var anchor = document.createElement('a') anchor.href = this.url anchor.download = 'report.pdf' anchor.click() } render () { const { disabled } = this.props return ( <React.Fragment> <ToolbarButton onClick={this.download.bind(this)} disabled={disabled}> <PrintIcon /> <FormattedMessage {...messages.print} /> </ToolbarButton> </React.Fragment> ) } } export default PrintButton
// @flow import React from 'react' import PrintIcon from '@material-ui/icons/Print' import { defineMessages, FormattedMessage } from 'react-intl' import ToolbarButton from '../internal/ToolbarButton' const messages = defineMessages({ // Button label to print a report print: 'Print' }) type Props = { disabled: boolean, url: string } const PrintButton = ({ url, disabled }: Props) => ( <React.Fragment> <ToolbarButton component='a' href={url} download='report.pdf' disabled={disabled} > <PrintIcon /> <FormattedMessage {...messages.print} /> </ToolbarButton> </React.Fragment> ) export default PrintButton
Fix print button (still downloads, does not print)
fix: Fix print button (still downloads, does not print) PrintButton was using `this.url` instead of `this.props.url`. However also removed some unnecessary code in this component
JavaScript
mit
digidem/ecuador-map-editor,digidem/ecuador-map-editor
--- +++ @@ -15,27 +15,18 @@ url: string } -class PrintButton extends React.Component<Props, State> { - - download () { - var anchor = document.createElement('a') - anchor.href = this.url - anchor.download = 'report.pdf' - anchor.click() - } - - render () { - const { disabled } = this.props - - return ( - <React.Fragment> - <ToolbarButton onClick={this.download.bind(this)} disabled={disabled}> - <PrintIcon /> - <FormattedMessage {...messages.print} /> - </ToolbarButton> - </React.Fragment> - ) - } -} +const PrintButton = ({ url, disabled }: Props) => ( + <React.Fragment> + <ToolbarButton + component='a' + href={url} + download='report.pdf' + disabled={disabled} + > + <PrintIcon /> + <FormattedMessage {...messages.print} /> + </ToolbarButton> + </React.Fragment> +) export default PrintButton
7655a4481b262f31f8288d533d9746865224fae9
js/addresses.js
js/addresses.js
/*global angular */ (function() { 'use strict'; var QUERY_URL = "https://address.digitalservices.surreyi.gov.uk/addresses?postcode="; var AUTH_TOKEN = "vJiSsulQe-zOobDsAWoUxr9cYfw"; var addressesApp; addressesApp = angular.module('addressesApp', []); addressesApp.config(function($httpProvider) { //Enable cross domain calls $httpProvider.defaults.useXDomain = true; }); addressesApp.controller("AddressesController", [ '$scope', '$http', function($scope, $http) { $scope.addresses = {}; $scope.addresses.data = []; $scope.addresses.isShowMessage = false; $scope.addressSearch = function(item, $event) { var responsePromise; var config = { headers: { 'Authorization': 'Bearer ' + AUTH_TOKEN }, } responsePromise = $http.get(QUERY_URL + $scope.addresses.search, config); responsePromise.then(function(response) { $scope.addresses.data = response.data; $scope.addresses.isShowMessage = (response.data.length == 0); }, function(response) { return $scope.addresses.message = "Error in searching for address data."; }); }; } ]); }());
/*global angular */ (function() { 'use strict'; var QUERY_URL = "https://address.digitalservices.surreyi.gov.uk/addresses?postcode="; var AUTH_TOKEN = "vJiSsulQe-zOobDsAWoUxr9cYfw"; var addressesApp; addressesApp = angular.module('addressesApp', []); addressesApp.config(function($httpProvider) { //Enable cross domain calls $httpProvider.defaults.useXDomain = true; }); addressesApp.controller("AddressesController", [ '$scope', '$http', function($scope, $http) { $scope.addresses = {}; $scope.addresses.data = []; $scope.addresses.isShowMessage = false; $scope.addressSearch = function(item, $event) { var responsePromise; var config = { headers: { 'Authorization': 'Bearer ' + AUTH_TOKEN }, } responsePromise = $http.get(QUERY_URL + $scope.addresses.search, config); responsePromise.then(function(response) { $scope.addresses.data = response.data; $scope.addresses.isShowMessage = (response.data.length == 0); $scope.addresses.message = (response.data.length == 0) ? 'No addresses found for ' + $scope.addresses.query + '.' : ''; }, function(response) { var statusCode = response.status; $scope.addresses.isShowMessage = true; $scope.addresses.messageClass = 'danger'; $scope.addresses.data = []; switch (statusCode) { case 429: $scope.addresses.message = 'Sorry, the maximum number of searches per day has been exceeded.'; break; default: $scope.addresses.message = 'Sorry, there was an error whilst searching. [' + response.statusText + ']'; } }); }; } ]); }());
Add error message when token usage exceeded
Add error message when token usage exceeded
JavaScript
mit
surreydigitalservices/sds-addresses,folklabs/sds-addresses,surreydigitalservices/sds-addresses,surreydigitalservices/sds-addresses,folklabs/sds-addresses,folklabs/sds-addresses
--- +++ @@ -31,8 +31,19 @@ responsePromise.then(function(response) { $scope.addresses.data = response.data; $scope.addresses.isShowMessage = (response.data.length == 0); + $scope.addresses.message = (response.data.length == 0) ? 'No addresses found for ' + $scope.addresses.query + '.' : ''; }, function(response) { - return $scope.addresses.message = "Error in searching for address data."; + var statusCode = response.status; + $scope.addresses.isShowMessage = true; + $scope.addresses.messageClass = 'danger'; + $scope.addresses.data = []; + switch (statusCode) { + case 429: + $scope.addresses.message = 'Sorry, the maximum number of searches per day has been exceeded.'; + break; + default: + $scope.addresses.message = 'Sorry, there was an error whilst searching. [' + response.statusText + ']'; + } }); }; }
585d4c685596764e9f25a5dc988453f8d5197aaf
js/heartbeat.js
js/heartbeat.js
(function($, document, window) { "use strict" window.animationHeartBeat = function (steps) { var max = steps; var delay = 70; var current = 0; var interval; var beat; $(document).bind('animation.stop', function() { console.log('animation.stop event caught'); clearInterval(interval); }); $(document).bind('animation.start', function() { console.log('animation.start event caught'); if (current > max) { $(document).trigger('animation.reset'); } interval = setInterval(beat, delay); }); $(document).bind('animation.reset', function() { console.log('animation.reset event caught'); current = 0; }); beat = function () { $(document).trigger('animation.beat', [{'current': current, 'max': max}]); current++; if (current > max) { $(document).trigger('animation.stop'); } } } })(jQuery, document, window);
(function($, document, window) { "use strict" window.animationHeartBeat = function (steps) { var max = steps; var delay = 70; var current = 0; var interval; var beat; $(document).bind('animation.stop', function() { console.log('animation.stop event caught'); clearInterval(interval); }); $(document).bind('animation.start', function() { console.log('animation.start event caught'); if (current > max) { $(document).trigger('animation.reset'); } interval = setInterval(beat, delay); }); $(document).bind('animation.reset', function() { console.log('animation.reset event caught'); current = 0; }); $(document).bind('animation.beat', function(event, animation) { current = animation.current + 1; }); beat = function () { $(document).trigger('animation.beat', [{'current': current, 'max': max}]); if (current > max) { $(document).trigger('animation.stop'); } } } })(jQuery, document, window);
Allow current frame modifictation by event
[HeartBeat] Allow current frame modifictation by event
JavaScript
mit
marekkalnik/jquery-mdm-animatics
--- +++ @@ -34,10 +34,14 @@ current = 0; }); + $(document).bind('animation.beat', function(event, animation) + { + current = animation.current + 1; + }); + beat = function () { $(document).trigger('animation.beat', [{'current': current, 'max': max}]); - current++; if (current > max) {
6eb45ba6e1a3db0036e829769d059813b16b5df8
server/publications/pinnedMessages.js
server/publications/pinnedMessages.js
Meteor.publish('channelPinnedMessages', function (search) { if (this.userId) { // TODO: checking if the user has access to these messages const channel = Channels.findOne({ $or: [{ _id: search }, { slug: search }] }); return Messages.find({ _id: {$in: channel.pinnedMessageIds} }); } this.ready(); });
Meteor.publish('channelPinnedMessages', function (search) { if (this.userId) { // TODO: checking if the user has access to these messages const channel = Channels.findOne({ $or: [{ _id: search }, { slug: search }] }); if (channel.pinnedMessageIds) { return Messages.find({ _id: {$in: channel.pinnedMessageIds} }); } } this.ready(); });
Fix subscription in error in channelPinnedMessages
Fix subscription in error in channelPinnedMessages
JavaScript
mit
tamzi/SpaceTalk,foysalit/SpaceTalk,MarkBandilla/SpaceTalk,MarkBandilla/SpaceTalk,foysalit/SpaceTalk,lhaig/SpaceTalk,mauricionr/SpaceTalk,bright-sparks/SpaceTalk,mGhassen/SpaceTalk,mGhassen/SpaceTalk,yanisIk/SpaceTalk,anjneymidha/SpaceTalk,SpaceTalk/SpaceTalk,anjneymidha/SpaceTalk,dannypaton/SpaceTalk,dannypaton/SpaceTalk,thesobek/SpaceTalk,bright-sparks/SpaceTalk,tamzi/SpaceTalk,yanisIk/SpaceTalk,redanium/SpaceTalk,syrenio/SpaceTalk,mauricionr/SpaceTalk,lhaig/SpaceTalk,TribeMedia/SpaceTalk,SpaceTalk/SpaceTalk,syrenio/SpaceTalk,thesobek/SpaceTalk,redanium/SpaceTalk,TribeMedia/SpaceTalk
--- +++ @@ -2,9 +2,12 @@ if (this.userId) { // TODO: checking if the user has access to these messages const channel = Channels.findOne({ $or: [{ _id: search }, { slug: search }] }); - return Messages.find({ - _id: {$in: channel.pinnedMessageIds} - }); + + if (channel.pinnedMessageIds) { + return Messages.find({ + _id: {$in: channel.pinnedMessageIds} + }); + } } this.ready(); });
21d6320759b1a78049f52c7052ac36f17a6ee1cc
src/utils/index.js
src/utils/index.js
import * as columnUtils from './columnUtils'; import * as compositionUtils from './compositionUtils'; import * as dataUtils from './dataUtils'; import * as rowUtils from './rowUtils'; import * as sortUtils from './sortUtils'; export default { columnUtils, compositionUtils, dataUtils, rowUtils, sortUtils, };
import * as columnUtils from './columnUtils'; import * as compositionUtils from './compositionUtils'; import * as dataUtils from './dataUtils'; import * as rowUtils from './rowUtils'; import * as sortUtils from './sortUtils'; import { connect } from './griddleConnect'; export default { columnUtils, compositionUtils, dataUtils, rowUtils, sortUtils, connect, };
Add connect to utils out
Add connect to utils out
JavaScript
mit
ttrentham/Griddle,GriddleGriddle/Griddle,GriddleGriddle/Griddle,joellanciaux/Griddle,joellanciaux/Griddle
--- +++ @@ -3,6 +3,7 @@ import * as dataUtils from './dataUtils'; import * as rowUtils from './rowUtils'; import * as sortUtils from './sortUtils'; +import { connect } from './griddleConnect'; export default { columnUtils, @@ -10,4 +11,5 @@ dataUtils, rowUtils, sortUtils, + connect, };
1c76ad5e14992f493a02accb6c753fbd422114ec
src/article/metadata/CollectionEditor.js
src/article/metadata/CollectionEditor.js
import { Component } from 'substance' import CardComponent from '../shared/CardComponent' export default class CollectionEditor extends Component { getActionHandlers () { return { 'remove-item': this._removeCollectionItem } } render ($$) { const model = this.props.model let items = model.getItems() let el = $$('div').addClass('sc-collection-editor') items.forEach(item => { let ItemEditor = this._getItemComponentClass(item) el.append( $$(CardComponent).append( $$(ItemEditor, { model: item, // LEGACY // TODO: try to get rid of this node: item._node }) ) ) }) return el } _getItemComponentClass (item) { let ItemComponent = this.getComponent(item.type, true) if (!ItemComponent) { // try to find a component registered for a parent type if (item._node) { ItemComponent = this._getParentTypeComponent(item._node) } } return ItemComponent || this.getComponent('entity') } _getParentTypeComponent (node) { let superTypes = node.getSchema().getSuperTypes() for (let type of superTypes) { let NodeComponent = this.getComponent(type, true) if (NodeComponent) return NodeComponent } } _removeCollectionItem (item) { const model = this.props.model model.removeItem(item) // TODO: this is only necessary for fake collection models // i.e. models that are only virtual, which I'd like to avoid this.rerender() } }
import { Component } from 'substance' import CardComponent from '../shared/CardComponent' export default class CollectionEditor extends Component { getActionHandlers () { return { 'remove-item': this._removeCollectionItem } } render ($$) { const model = this.props.model let items = model.getItems() let el = $$('div').addClass('sc-collection-editor') items.forEach(item => { let ItemEditor = this._getItemComponentClass(item) el.append( $$(CardComponent).append( $$(ItemEditor, { model: item, // LEGACY // TODO: try to get rid of this node: item._node }).ref(item.id) ) ) }) return el } _getItemComponentClass (item) { let ItemComponent = this.getComponent(item.type, true) if (!ItemComponent) { // try to find a component registered for a parent type if (item._node) { ItemComponent = this._getParentTypeComponent(item._node) } } return ItemComponent || this.getComponent('entity') } _getParentTypeComponent (node) { let superTypes = node.getSchema().getSuperTypes() for (let type of superTypes) { let NodeComponent = this.getComponent(type, true) if (NodeComponent) return NodeComponent } } _removeCollectionItem (item) { const model = this.props.model model.removeItem(item) // TODO: this is only necessary for fake collection models // i.e. models that are only virtual, which I'd like to avoid this.rerender() } }
Put a ref for item editor.
Put a ref for item editor.
JavaScript
mit
substance/texture,substance/texture
--- +++ @@ -21,7 +21,7 @@ // LEGACY // TODO: try to get rid of this node: item._node - }) + }).ref(item.id) ) ) })
f12cd07dabf68b29e6ad05e3609b5f4e2920213a
src/meta/intro.js
src/meta/intro.js
(function(mod) { // CommonJS, Node.js, browserify. if (typeof exports === "object" && typeof module === "object") { module.exports = mod(require('d3'), require('d3.chart'), require('d3.chart.base'), requure('lodash')); return; } // AMD. if (typeof define === "function" && define.amd) { return define(['d3', 'd3.chart', 'd3.chart.base', 'lodash'], mod); } // Plain browser (no strict mode: `this === window`). this.d3ChartBubbleMatrix = mod(this.d3, this.d3Chart, this.d3ChartBase, this._); })(function(d3, d3Chart, d3ChartBase, ld) { "use strict"; var exports = {};
// We should use `grunt-umd` instead of this explicit intro, but the tool does // not camelize lib names containing '.' or '-', making the generated JS // invalid; needs a pull request. (function(mod) { // CommonJS, Node.js, browserify. if (typeof exports === "object" && typeof module === "object") { module.exports = mod(require('d3'), require('d3.chart'), require('d3.chart.base'), requure('lodash')); return; } // AMD. if (typeof define === "function" && define.amd) { return define(['d3', 'd3.chart', 'd3.chart.base', 'lodash'], mod); } // Plain browser (no strict mode: `this === window`). this.d3ChartBubbleMatrix = mod(this.d3, this.d3Chart, this.d3ChartBase, this._); })(function(d3, d3Chart, d3ChartBase, ld) { "use strict"; var exports = {};
Add comment about explicit UMD
Add comment about explicit UMD
JavaScript
mit
benbria/d3.chart.bubble-matrix,leebecker-hapara/d3.chart.heatmap-matrix,benbria/d3.chart.bubble-matrix,leebecker-hapara/d3.chart.heatmap-matrix,leebecker-hapara/d3.chart.heatmap-matrix
--- +++ @@ -1,3 +1,6 @@ +// We should use `grunt-umd` instead of this explicit intro, but the tool does +// not camelize lib names containing '.' or '-', making the generated JS +// invalid; needs a pull request. (function(mod) { // CommonJS, Node.js, browserify. if (typeof exports === "object" && typeof module === "object") {
9eb08435f9c05197d5df424c1be86560bfab7c1a
tests/atms-test.js
tests/atms-test.js
'use strict'; var chai = require('chai'); var supertest = require('supertest'); var api = supertest('https://apis-bank-dev.apigee.net'); // supertest init; chai.should(); describe('/atms', function() { describe('get', function() { it('should respond with 200 OK', function(done) { this.timeout(0); api.get('/apis/v1/locations/atms') .expect(200) .end(function(err, res) { if (err) return done(err); done(); }); }); }); });
'use strict'; var chai = require('chai'); var supertest = require('supertest'); var api = supertest('https://apis-bank-dev.apigee.net'); // supertest init; chai.should(); describe('/atms', function() { describe('get', function() { it('should respond with 200 OK', function(done) { this.timeout(0); api.get('/apis/v1/locations/atms') .expect(400) .end(function(err, res) { if (err) return done(err); done(); }); }); }); });
Change to check build pass in CI
Change to check build pass in CI
JavaScript
apache-2.0
siriscac/apigee-ci-demo
--- +++ @@ -11,7 +11,7 @@ it('should respond with 200 OK', function(done) { this.timeout(0); api.get('/apis/v1/locations/atms') - .expect(200) + .expect(400) .end(function(err, res) { if (err) return done(err); done();
532c17d07761f89158b4be8ea4e3b9c29ff35941
findminmax/src/findminmax.js
findminmax/src/findminmax.js
'use strict' module.exports = { // This function finds the minimum and maximum values in an array of numbers. findMinMax: function(numlist) { numlist.sort( function (a,b) {return a - b} ); return [ numlist[0], numlist[numlist.length - 1] ]; } }
'use strict' module.exports = { // This function finds the minimum and maximum values in an array of numbers. findMinMax: function(numlist) { numlist.sort( function (a,b) {return a - b} ); if (numlist[0] == numlist[numlist.length - 1]) { return [numlist[0]]; } else return [ numlist[0], numlist[numlist.length - 1] ]; } }
Implement functionality for equal min and max values.
Implement functionality for equal min and max values.
JavaScript
mit
princess-essien/andela-bootcamp-slc
--- +++ @@ -5,6 +5,9 @@ findMinMax: function(numlist) { numlist.sort( function (a,b) {return a - b} ); - return [ numlist[0], numlist[numlist.length - 1] ]; + if (numlist[0] == numlist[numlist.length - 1]) { + return [numlist[0]]; + } + else return [ numlist[0], numlist[numlist.length - 1] ]; } }
90518f85616a9ae5c67e3e6fc71a9406c3787724
src/js/views/pro/PlayHistoryView.js
src/js/views/pro/PlayHistoryView.js
/** * View for the room users list * @module views/pro/PlayHistoryView */ var panes = require('./panes'); var PlayHistoryView = Backbone.View.extend({ id: "plugpro-play-history", className: "media-list history", initialize: function(){ var JST = window.plugPro.JST; this.historyHTML = JST['play_history.html']; }, render: function(){ this.$el.html(""); var historyList = API.getHistory(); historyList.forEach( this.appendSong.bind(this) ); }, appendSong: function( songInfo ){ var historyDiv = this.historyHTML( songInfo ); this.$el.append( historyDiv ); }, destroy: function(){ this.remove(); }, reposition: function(){ var windowWidth = $(window).width(); var windowHeight = $(window).height(); var leftPosition = panes.get('userlist'); var height = (windowHeight - 108) / 2; this.$el.css({ "left": leftPosition + "px", "height": height + "px", "width": panes.get('middle')/2 + "px" }); $('#vote').width( this.$el.outerWidth() ); $('#vote').css({ "left": 0 }); } }); module.exports = PlayHistoryView;
/** * View for the room users list * @module views/pro/PlayHistoryView */ var panes = require('./panes'); var PlayHistoryView = Backbone.View.extend({ id: "plugpro-play-history", className: "media-list history", initialize: function(){ var JST = window.plugPro.JST; this.historyHTML = JST['play_history.html']; API.on( API.HISTORY_UPDATE, this.render.bind(this) ); }, render: function(){ this.$el.html(""); var historyList = API.getHistory(); historyList.forEach( this.appendSong.bind(this) ); }, appendSong: function( songInfo ){ var historyDiv = this.historyHTML( songInfo ); this.$el.append( historyDiv ); }, destroy: function(){ this.remove(); }, reposition: function(){ var windowWidth = $(window).width(); var windowHeight = $(window).height(); var leftPosition = panes.get('userlist'); var height = (windowHeight - 108) / 2; this.$el.css({ "left": leftPosition + "px", "height": height + "px", "width": panes.get('middle')/2 + "px" }); $('#vote').width( this.$el.outerWidth() ); $('#vote').css({ "left": 0 }); } }); module.exports = PlayHistoryView;
Make play history stay up to date
Make play history stay up to date
JavaScript
mit
traviswimer/PlugPro,traviswimer/PlugPro,SkyGameRus/PlugPro,SkyGameRus/PlugPro
--- +++ @@ -12,6 +12,8 @@ initialize: function(){ var JST = window.plugPro.JST; this.historyHTML = JST['play_history.html']; + + API.on( API.HISTORY_UPDATE, this.render.bind(this) ); }, render: function(){
6938bbeac68d0764fd0b95baf69481a64fc8aab7
src/components/Members/MembersPreview.js
src/components/Members/MembersPreview.js
import React, { Component } from 'react'; class MembersPreview extends Component { render() { const {displayName, image, intro, slug} = this.props; // TODO: remove inline styles and implement a system return ( <div style={{ height: '200px', }}> <img src={image.uri} style={{ maxHeight: '75px', float: 'left', }} /> <div style={{ float: 'right', width: 'calc(100% - 100px);', }}> <p> <a href={slug}>{displayName}</a> </p> <p>{intro}</p> </div> </div> ); } } MembersPreview.propTypes = { displayName: React.PropTypes.string.isRequired, image: React.PropTypes.shape({ uri: React.PropTypes.string.isRequired, height: React.PropTypes.number, width: React.PropTypes.number, }), intro: React.PropTypes.string, slug: React.PropTypes.string.isRequired, usState: React.PropTypes.string, }; export default MembersPreview;
import React, { Component } from 'react'; class MembersPreview extends Component { render() { const {displayName, image, intro, slug} = this.props; // TODO: remove inline styles and implement a system return ( <div style={{ height: '200px', }}> <img src={image.uri} style={{ maxHeight: '75px', float: 'left', }} /> <div style={{ float: 'right', width: 'calc(100% - 150px);', }}> <p> <a href={slug}>{displayName}</a> </p> <p>{intro}</p> </div> </div> ); } } MembersPreview.propTypes = { displayName: React.PropTypes.string.isRequired, image: React.PropTypes.shape({ uri: React.PropTypes.string.isRequired, height: React.PropTypes.number, width: React.PropTypes.number, }), intro: React.PropTypes.string, slug: React.PropTypes.string.isRequired, usState: React.PropTypes.string, }; export default MembersPreview;
Make image preview slightly wider for mockup
Make image preview slightly wider for mockup
JavaScript
cc0-1.0
cape-io/acf-client,cape-io/acf-client
--- +++ @@ -16,7 +16,7 @@ }} /> <div style={{ float: 'right', - width: 'calc(100% - 100px);', + width: 'calc(100% - 150px);', }}> <p> <a href={slug}>{displayName}</a>
1507d27109ad65abcb115a498ae8bc4b9701286b
src/core/middleware/005-favicon/index.js
src/core/middleware/005-favicon/index.js
import {join} from "path" import favicon from "koa-favicon" // TODO: Rewrite this middleware from scratch because of synchronous favicon // reading. const FAVICON_PATH = join( process.cwd(), "static/assets/img/icns/favicon/twi.ico" ) const configureFavicon = () => favicon(FAVICON_PATH) export default configureFavicon
// Based on koajs/favicon import {resolve, join, isAbsolute} from "path" import {readFile} from "promise-fs" import invariant from "@octetstream/invariant" import isPlainObject from "lodash/isPlainObject" import isString from "lodash/isString" import ms from "ms" import getType from "core/helper/util/getType" const ROOT = process.cwd() const DEFAULT_PATH = join(ROOT, "static/assets/img/icns/favicon/twi.ico") function favicon(path = DEFAULT_PATH, options = {}) { if (isPlainObject(path)) { [options, path] = [path, DEFAULT_PATH] } invariant( !isString(path), TypeError, "Path should be a string. Received %s", getType(path) ) invariant( !isPlainObject(options), TypeError, "Options sohuld be a plain object. Received %s", getType(options) ) if (!isAbsolute(path)) { path = resolve(ROOT, path) } const maxAge = ms(options.maxAge != null ? options.maxAge : "1d") const cacheControl = ( `public, max-age=${maxAge < 1000 ? maxAge / 1000 : 0}` ) let icon = null return async function faviconMiddleware(ctx, next) { if (ctx.path !== "/favicon.ico") { return await next() } if (ctx.method !== "GET" && ctx.method !== "HEAD") { ctx.status = ctx.method === "OPTIONS" ? 200 : 405 ctx.set("Allow", "GET, HEAD, OPTIONS") return } if (!icon) { icon = await readFile(path) } ctx.set("Cache-Control", cacheControl) ctx.type = "image/x-icon" ctx.body = icon } } const configureFavicon = () => favicon() export default configureFavicon
Rewrite favicon middleware from scratch.
Rewrite favicon middleware from scratch.
JavaScript
mit
twi-project/twi-server,octet-stream/ponyfiction-js,octet-stream/ponyfiction-js,octet-stream/twi
--- +++ @@ -1,13 +1,66 @@ -import {join} from "path" +// Based on koajs/favicon +import {resolve, join, isAbsolute} from "path" -import favicon from "koa-favicon" +import {readFile} from "promise-fs" -// TODO: Rewrite this middleware from scratch because of synchronous favicon -// reading. -const FAVICON_PATH = join( - process.cwd(), "static/assets/img/icns/favicon/twi.ico" -) +import invariant from "@octetstream/invariant" +import isPlainObject from "lodash/isPlainObject" +import isString from "lodash/isString" +import ms from "ms" -const configureFavicon = () => favicon(FAVICON_PATH) +import getType from "core/helper/util/getType" + +const ROOT = process.cwd() + +const DEFAULT_PATH = join(ROOT, "static/assets/img/icns/favicon/twi.ico") + +function favicon(path = DEFAULT_PATH, options = {}) { + if (isPlainObject(path)) { + [options, path] = [path, DEFAULT_PATH] + } + + invariant( + !isString(path), TypeError, + "Path should be a string. Received %s", getType(path) + ) + + invariant( + !isPlainObject(options), TypeError, + "Options sohuld be a plain object. Received %s", getType(options) + ) + + if (!isAbsolute(path)) { + path = resolve(ROOT, path) + } + + const maxAge = ms(options.maxAge != null ? options.maxAge : "1d") + + const cacheControl = ( + `public, max-age=${maxAge < 1000 ? maxAge / 1000 : 0}` + ) + + let icon = null + return async function faviconMiddleware(ctx, next) { + if (ctx.path !== "/favicon.ico") { + return await next() + } + + if (ctx.method !== "GET" && ctx.method !== "HEAD") { + ctx.status = ctx.method === "OPTIONS" ? 200 : 405 + ctx.set("Allow", "GET, HEAD, OPTIONS") + return + } + + if (!icon) { + icon = await readFile(path) + } + + ctx.set("Cache-Control", cacheControl) + ctx.type = "image/x-icon" + ctx.body = icon + } +} + +const configureFavicon = () => favicon() export default configureFavicon
4af6210c0aae1b09d754f73b9a5755e5af81dff1
test/unit/dummySpec.js
test/unit/dummySpec.js
describe('Test stuff', function () { it('should just work', function () { angular.mock.module('hdpuzzles'); expect(true).toBe(true); }); });
describe('Test stuff', function () { it('should just work', function () { angular.mock.module('hdpuzzles'); expect(true).toBe(false); }); });
Test if Travis CI reports a failure for failing unit tests.
Test if Travis CI reports a failure for failing unit tests.
JavaScript
mit
ErikNijland/hdpuzzles,ErikNijland/hdpuzzles
--- +++ @@ -2,6 +2,6 @@ it('should just work', function () { angular.mock.module('hdpuzzles'); - expect(true).toBe(true); + expect(true).toBe(false); }); });
0193fceb10b4d266945e00967726ab5549cd77a0
src/Marker.js
src/Marker.js
import Leaflet from "leaflet"; import latlngType from "./types/latlng"; import PopupContainer from "./PopupContainer"; export default class Marker extends PopupContainer { componentWillMount() { super.componentWillMount(); const {map, position, ...props} = this.props; this.leafletElement = Leaflet.marker(position, props); } componentDidUpdate(prevProps) { if (this.props.position !== prevProps.position) { this.leafletElement.setLatLng(this.props.position); } } } Marker.propTypes = { position: latlngType.isRequired };
import Leaflet from "leaflet"; import latlngType from "./types/latlng"; import PopupContainer from "./PopupContainer"; export default class Marker extends PopupContainer { componentWillMount() { super.componentWillMount(); const {map, position, ...props} = this.props; this.leafletElement = Leaflet.marker(position, props); } componentDidUpdate(prevProps) { if (this.props.position !== prevProps.position) { this.leafletElement.setLatLng(this.props.position); } if (this.props.icon !== prevProps.icon) { this.getLeafletElement().setIcon(this.props.icon); } } } Marker.propTypes = { position: latlngType.isRequired };
Implement dynamic changing of marker icon
Implement dynamic changing of marker icon
JavaScript
mit
dantman/react-leaflet,TerranetMD/react-leaflet,marcello3d/react-leaflet,ericsoco/react-leaflet,snario/react-mapbox-gl,yavuzmester/react-leaflet,uniphil/react-leaflet,itoldya/react-leaflet,marcello3d/react-leaflet,snario/react-mapbox-gl,KABA-CCEAC/react-leaflet,yavuzmester/react-leaflet,yavuzmester/react-leaflet,itoldya/react-leaflet,devgateway/react-leaflet,boromisp/react-leaflet,dantman/react-leaflet,TaiwanStat/react-leaflet,lennerd/react-leaflet,TerranetMD/react-leaflet,lennerd/react-leaflet,TaiwanStat/react-leaflet,boromisp/react-leaflet,devgateway/react-leaflet,KABA-CCEAC/react-leaflet,ericsoco/react-leaflet,uniphil/react-leaflet
--- +++ @@ -14,6 +14,10 @@ if (this.props.position !== prevProps.position) { this.leafletElement.setLatLng(this.props.position); } + + if (this.props.icon !== prevProps.icon) { + this.getLeafletElement().setIcon(this.props.icon); + } } }
e86977f2bed532a344b2df4c09ed84a9b04fee17
probes/cpu.js
probes/cpu.js
/* * CPU statistics */ var exec = require('child_process').exec; /* * Unfortunately the majority of systems are en_US based, so we go with * the wrong spelling of 'utilisation' for the least hassle ;) */ function get_cpu_utilization(callback) { switch (process.platform) { case 'linux': exec('mpstat -u -P ALL 1 1', function (err, stdout, stderr) { var capture = 0; stdout.split('\n').forEach(function (line) { var ret = {}; if (line.length === 0) { capture = (capture) ? 0 : 1; return; } if (capture) { var vals = line.split(/\s+/); if (!vals[1].match(/\d+/)) { return; } ret['cpu.utilization.cpu' + vals[1] + '.user'] = vals[2]; ret['cpu.utilization.cpu' + vals[1] + '.system'] = vals[4]; ret['cpu.utilization.cpu' + vals[1] + '.iowait'] = vals[5]; ret['cpu.utilization.cpu' + vals[1] + '.idle'] = vals[10]; callback(ret); } }); }); break; } } module.exports.probes = { 'cpu.utilization': get_cpu_utilization, }
/* * CPU statistics */ var exec = require('child_process').exec; /* * Unfortunately the majority of systems are en_US based, so we go with * the wrong spelling of 'utilisation' for the least hassle ;) */ function get_cpu_utilization(callback) { switch (process.platform) { case 'linux': exec('mpstat -u -P ALL 1 1', function (err, stdout, stderr) { stdout.split('\n\n')[1].split('\n').forEach(function (line) { var ret = {}; var vals = line.split(/\s+/); if (!vals[1].match(/\d+/)) { return; } ret['cpu.utilization.cpu' + vals[1] + '.user'] = vals[2]; ret['cpu.utilization.cpu' + vals[1] + '.system'] = vals[4]; ret['cpu.utilization.cpu' + vals[1] + '.iowait'] = vals[5]; ret['cpu.utilization.cpu' + vals[1] + '.idle'] = vals[10]; callback(ret); }); }); break; } } module.exports.probes = { 'cpu.utilization': get_cpu_utilization, }
Simplify things with better use of split().
Simplify things with better use of split().
JavaScript
isc
jperkin/node-statusmon
--- +++ @@ -13,24 +13,17 @@ switch (process.platform) { case 'linux': exec('mpstat -u -P ALL 1 1', function (err, stdout, stderr) { - var capture = 0; - stdout.split('\n').forEach(function (line) { + stdout.split('\n\n')[1].split('\n').forEach(function (line) { var ret = {}; - if (line.length === 0) { - capture = (capture) ? 0 : 1; + var vals = line.split(/\s+/); + if (!vals[1].match(/\d+/)) { return; } - if (capture) { - var vals = line.split(/\s+/); - if (!vals[1].match(/\d+/)) { - return; - } - ret['cpu.utilization.cpu' + vals[1] + '.user'] = vals[2]; - ret['cpu.utilization.cpu' + vals[1] + '.system'] = vals[4]; - ret['cpu.utilization.cpu' + vals[1] + '.iowait'] = vals[5]; - ret['cpu.utilization.cpu' + vals[1] + '.idle'] = vals[10]; - callback(ret); - } + ret['cpu.utilization.cpu' + vals[1] + '.user'] = vals[2]; + ret['cpu.utilization.cpu' + vals[1] + '.system'] = vals[4]; + ret['cpu.utilization.cpu' + vals[1] + '.iowait'] = vals[5]; + ret['cpu.utilization.cpu' + vals[1] + '.idle'] = vals[10]; + callback(ret); }); }); break;
87396bd2a640d12026ade031340b292ee2ec1c08
src/sandbox.js
src/sandbox.js
/*global __WEBPACK_DEV_SERVER_DEBUG__*/ /*global __WEBPACK_DEV_SERVER_NO_FF__*/ let SAVE; if (__WEBPACK_DEV_SERVER_DEBUG__) { // for webpack-dev-server auto simulate SAVE = require('./webpack-dev-server-util'); if (!__WEBPACK_DEV_SERVER_NO_FF__) require('./webpack-dev-server-fetch'); } window.SAVE2 = { VERSION: '2.0.1', lib: { view: SAVE }, isCAT: () => window._EntityLibrary != null || window.location.hostname === 'save.github.io', simulate: () => { window.SAVE2.lib.view = require('./webpack-dev-server-util'); require('./webpack-dev-server-fetch'); }, };
/*global __WEBPACK_DEV_SERVER_DEBUG__*/ /*global __WEBPACK_DEV_SERVER_NO_FF__*/ let SAVE; let host = window.location.hostname; if (__WEBPACK_DEV_SERVER_DEBUG__) { // for webpack-dev-server auto simulate SAVE = require('./webpack-dev-server-util'); if (!__WEBPACK_DEV_SERVER_NO_FF__) require('./webpack-dev-server-fetch'); } window.SAVE2 = { VERSION: '2.0.1', lib: { view: SAVE }, isCAT: () => window._EntityLibrary != null || host === 'sri-save.github.io' || host === '', simulate: () => { window.SAVE2.lib.view = require('./webpack-dev-server-util'); require('./webpack-dev-server-fetch'); }, };
Fix for host not being correct
Fix for host not being correct
JavaScript
apache-2.0
SRI-SAVE/react-components
--- +++ @@ -2,17 +2,18 @@ /*global __WEBPACK_DEV_SERVER_NO_FF__*/ let SAVE; +let host = window.location.hostname; if (__WEBPACK_DEV_SERVER_DEBUG__) { // for webpack-dev-server auto simulate SAVE = require('./webpack-dev-server-util'); - + if (!__WEBPACK_DEV_SERVER_NO_FF__) require('./webpack-dev-server-fetch'); } window.SAVE2 = { VERSION: '2.0.1', lib: { view: SAVE }, - isCAT: () => window._EntityLibrary != null || window.location.hostname === 'save.github.io', + isCAT: () => window._EntityLibrary != null || host === 'sri-save.github.io' || host === '', simulate: () => { window.SAVE2.lib.view = require('./webpack-dev-server-util'); require('./webpack-dev-server-fetch');
7b44cd38ea5741ebaba29da17aa091c7c8dddf6a
array/#/flatten.js
array/#/flatten.js
// Stack grow safe implementation 'use strict'; var ensureValue = require('../../object/valid-value') , isArray = Array.isArray; module.exports = function () { var input = ensureValue(this), remaining, l, i, result = []; main: //jslint: ignore while (input) { l = input.length; for (i = 0; i < l; ++i) { if (isArray(input[i])) { if (i < (l - 1)) { if (!remaining) remaining = []; remaining.push(input.slice(i + 1)); } input = input[i]; continue main; } result.push(input[i]); } input = remaining ? remaining.pop() : null; } return result; };
// Stack grow safe implementation 'use strict'; var ensureValue = require('../../object/valid-value') , isArray = Array.isArray; module.exports = function () { var input = ensureValue(this), index = 0, remaining, remainingIndexes, l, i, result = []; main: //jslint: ignore while (input) { l = input.length; for (i = index; i < l; ++i) { if (isArray(input[i])) { if (i < (l - 1)) { if (!remaining) { remaining = []; remainingIndexes = []; } remaining.push(input); remainingIndexes.push(i + 1); } input = input[i]; index = 0; continue main; } result.push(input[i]); } if (remaining) { input = remaining.pop(); index = remainingIndexes.pop(); } else { input = null; } } return result; };
Optimize to not use slice
Optimize to not use slice
JavaScript
isc
medikoo/es5-ext
--- +++ @@ -6,22 +6,32 @@ , isArray = Array.isArray; module.exports = function () { - var input = ensureValue(this), remaining, l, i, result = []; + var input = ensureValue(this), index = 0, remaining, remainingIndexes, l, i, result = []; main: //jslint: ignore while (input) { l = input.length; - for (i = 0; i < l; ++i) { + for (i = index; i < l; ++i) { if (isArray(input[i])) { if (i < (l - 1)) { - if (!remaining) remaining = []; - remaining.push(input.slice(i + 1)); + if (!remaining) { + remaining = []; + remainingIndexes = []; + } + remaining.push(input); + remainingIndexes.push(i + 1); } input = input[i]; + index = 0; continue main; } result.push(input[i]); } - input = remaining ? remaining.pop() : null; + if (remaining) { + input = remaining.pop(); + index = remainingIndexes.pop(); + } else { + input = null; + } } return result; };
b119297ac01748e7b91a7e6d8cf3f5ea193e29f6
src/config.js
src/config.js
import fs from 'fs' import rc from 'rc' import ini from 'ini' import path from 'path' import mkdirp from 'mkdirp' import untildify from 'untildify' const conf = rc('tickbin', { api: 'https://api.tickbin.com/', local: '~/.tickbin' }) conf.local = untildify(conf.local) conf.db = path.join(conf.local, 'data') if (!fs.existsSync(conf.local)) { mkdirp.sync(conf.local) } function setConfig(key, value) { let parsed = {} let target = conf.config || untildify('~/.tickbinrc') if (conf.config) parsed = ini.parse(fs.readFileSync(target, 'utf-8')) parsed[key] = value fs.writeFileSync(target, ini.stringify(parsed)) } export { setConfig } export default conf
import fs from 'fs' import rc from 'rc' import ini from 'ini' import path from 'path' import mkdirp from 'mkdirp' import untildify from 'untildify' const conf = rc('tickbin', { api: 'https://api.tickbin.com/', local: '~/.tickbin' }) conf.local = untildify(conf.local) conf.db = path.join(conf.local, 'data') if (!fs.existsSync(conf.local)) { mkdirp.sync(conf.local) } function storeUser(user) { storeKey('remote', user.couch.url) storeKey('user', user.id) } function storeKey(key, value) { let parsed = {} let target = conf.config || untildify('~/.tickbinrc') if (conf.config) parsed = ini.parse(fs.readFileSync(target, 'utf-8')) parsed[key] = value fs.writeFileSync(target, ini.stringify(parsed)) } export { storeUser } export default conf
Add a setUser function and change setConfig to setKey
Add a setUser function and change setConfig to setKey
JavaScript
agpl-3.0
jonotron/tickbin,tickbin/tickbin,chadfawcett/tickbin
--- +++ @@ -17,7 +17,12 @@ mkdirp.sync(conf.local) } -function setConfig(key, value) { +function storeUser(user) { + storeKey('remote', user.couch.url) + storeKey('user', user.id) +} + +function storeKey(key, value) { let parsed = {} let target = conf.config || untildify('~/.tickbinrc') if (conf.config) parsed = ini.parse(fs.readFileSync(target, 'utf-8')) @@ -25,5 +30,5 @@ fs.writeFileSync(target, ini.stringify(parsed)) } -export { setConfig } +export { storeUser } export default conf
f217d11b36613ab49314e8ba9f83ab8a76118ed0
src/config.js
src/config.js
export default { gameWidth: 1080, gameHeight: 1613, images: { 'background-game': './assets/images/background-game.png', 'background-landing': './assets/images/background-landing.png', 'background-face': './assets/images/ui/background-face.png', 'background-game-over': './assets/images/ui/background-face-game-over.png', 'score-bar': './assets/images/ui/score-bar.png', frame: './assets/images/ui/frame.png', 'food-bar': './assets/images/ui/food-bar.png', 'drinks-bar': './assets/images/ui/drinks-bar.png', 'black-background': './assets/images/ui/black-background.png', spit: './assets/images/player/spit.png' }, rules: { drinkDecrementPerTimeUnit: 4, drinkDecrementTimeMilliSeconds: 1000, drinkMinimumAmount: -250, drinkMaximumAmount: 250, foodDecrementPerMove: 2, foodMinimumAmount: -250, foodMaximumAmount: 250, playerInitialMoveSpeed: 500, playerMaxDragMultiplier: 0.4, playerYPosition: 860, minimumSpawnTime: 1200, maximumSpawnTime: 2500, }, gravity: 400, player: { mouthOffset: 180 } };
export default { gameWidth: 1080, gameHeight: 1613, images: { 'background-game': './assets/images/background-game.png', 'background-landing': './assets/images/background-landing.png', 'background-face': './assets/images/ui/background-face.png', 'background-game-over': './assets/images/ui/background-face-game-over.png', 'score-bar': './assets/images/ui/score-bar.png', frame: './assets/images/ui/frame.png', 'food-bar': './assets/images/ui/food-bar.png', 'drinks-bar': './assets/images/ui/drinks-bar.png', 'black-background': './assets/images/ui/black-background.png', spit: './assets/images/player/spit.png' }, rules: { drinkDecrementPerTimeUnit: 2, drinkDecrementTimeMilliSeconds: 500, drinkMinimumAmount: -250, drinkMaximumAmount: 250, foodDecrementPerMove: 4, foodMinimumAmount: -250, foodMaximumAmount: 250, playerInitialMoveSpeed: 500, playerMaxDragMultiplier: 0.4, playerYPosition: 860, minimumSpawnTime: 1200, maximumSpawnTime: 2500, }, gravity: 400, player: { mouthOffset: 180 } };
Tweak difficulty - adjust drink + food decrements
Tweak difficulty - adjust drink + food decrements
JavaScript
mit
MarcL/see-it-off,MarcL/see-it-off
--- +++ @@ -14,11 +14,11 @@ spit: './assets/images/player/spit.png' }, rules: { - drinkDecrementPerTimeUnit: 4, - drinkDecrementTimeMilliSeconds: 1000, + drinkDecrementPerTimeUnit: 2, + drinkDecrementTimeMilliSeconds: 500, drinkMinimumAmount: -250, drinkMaximumAmount: 250, - foodDecrementPerMove: 2, + foodDecrementPerMove: 4, foodMinimumAmount: -250, foodMaximumAmount: 250, playerInitialMoveSpeed: 500,
d517724e6875365ff2e49440b13d01837e748fd6
test/test.js
test/test.js
const request = require('supertest'); const app = require('../app'); describe('name to point', function () { it('should return JSON object with geolocation', function (done) { request(app) .get('/point?name=OldCity&lat=53.66&lon=23.83') .expect(200) .expect({ lat: '53.70177645', lon: '23.8347894179425', display_name: 'OldCity, 17, улица Дубко, Девятовка, Ленинский район,' + ' Гродно, Гродненская область, 230012, Беларусь', }) .end(function (err, res) { if (err) { return done(err); } done(); }); }); it('should respond with Not Found in case of failed name resolution', function (done) { request(app) .get('/point?name=NONAME&lat=53.66&lon=23.83') .expect(404) .end(function (err, res) { if (err) { return done(err); } done(); }); }); });
const request = require('supertest'); const app = require('../app'); describe('name to point', function () { it('should return JSON object with geolocation', function (done) { request(app) .get('/point?name=OldCity&lat=53.66&lon=23.83') .expect(200) .expect({ lat: '53.70177645', lon: '23.8347894179425', display_name: 'OldCity, 17, улица Дубко, Девятовка, Ленинский район,' + ' Гродно, Гродненская область, 230005, Беларусь', }) .end(function (err, res) { if (err) { return done(err); } done(); }); }); it('should respond with Not Found in case of failed name resolution', function (done) { request(app) .get('/point?name=NONAME&lat=53.66&lon=23.83') .expect(404) .end(function (err, res) { if (err) { return done(err); } done(); }); }); });
Write a correct postal address
Write a correct postal address
JavaScript
mit
pub-t/name-to-point
--- +++ @@ -10,7 +10,7 @@ lat: '53.70177645', lon: '23.8347894179425', display_name: 'OldCity, 17, улица Дубко, Девятовка, Ленинский район,' + - ' Гродно, Гродненская область, 230012, Беларусь', + ' Гродно, Гродненская область, 230005, Беларусь', }) .end(function (err, res) { if (err) {
93b9428ad5232974ad73e02941f7b647f2a4a804
content/photography/index.11ty.js
content/photography/index.11ty.js
const { downloadGalleryPhoto } = require("../../gallery-helpers"); const html = require("../../render-string"); const quality = 40; const size = 300; module.exports = class Gallery { data() { return { layout: "photography" }; } async render({ collections }) { return html` <div class="grid" style="--gallery-size: ${size}px;"> ${collections.photo .filter(entry => entry.data.live) .sort((a, b) => new Date(b.data.date) - new Date(a.data.date)) .map(async item => { const { file, page } = item.data; await downloadGalleryPhoto({ file, page }); return html` <a href="${item.url}"> <preview-img src="${file}" width="${size}" height="${size}" quality="${quality}" ></preview-img> </a> `; })} </div> `; } };
const { downloadGalleryPhoto } = require("../../gallery-helpers"); const html = require("../../render-string"); const quality = 40; const size = 300; module.exports = class Gallery { data() { return { layout: "photography" }; } async render({ collections }) { return html` <div class="grid" style="--gallery-size: ${size}px;"> ${collections.photo .filter(entry => entry.data.live) .sort((a, b) => new Date(b.data.date) - new Date(a.data.date)) .map(async item => { const { file, page } = item.data; await downloadGalleryPhoto({ file, page }); return html` <a href="${item.url}"> <preview-img src="${file}" width="${size}" height="${size}" quality="${quality}" loading="lazy" ></preview-img> </a> `; })} </div> `; } };
Use lazy loading attribute on gallery
Use lazy loading attribute on gallery
JavaScript
mit
surma/surma.github.io,surma/surma.github.io
--- +++ @@ -26,6 +26,7 @@ width="${size}" height="${size}" quality="${quality}" + loading="lazy" ></preview-img> </a> `;
3d4d507c75826fd957939fc7c999fd3460aa8cd2
src/asset-picker/AssetPickerFilter.js
src/asset-picker/AssetPickerFilter.js
import React, { PropTypes, PureComponent } from 'react'; import { findDOMNode } from 'react-dom'; import { InputGroup } from 'binary-components'; import { isMobile } from 'binary-utils'; import { actions } from '../_store'; import MarketSubmarketPickerContainer from './MarketSubmarketPickerContainer'; export default class AssetPickerFilter extends PureComponent { static propTypes = { filter: PropTypes.object.isRequired, }; componentDidMount() { const assetSearchNode = findDOMNode(this); if (!isMobile()) { setTimeout(() => assetSearchNode.firstChild.focus(), 300); } } onSearchQueryChange = e => { actions.updateAssetPickerSearchQuery(e.target.value); } onFilterChange = e => { actions.updateAssetPickerFilter(e); } render() { const { filter } = this.props; return ( <div className="asset-picker-filter"> <InputGroup className="asset-search" defaultValue={filter.query} type="search" placeholder="Search for assets" onChange={this.onSearchQueryChange} /> <MarketSubmarketPickerContainer onChange={this.onFilterChange} allOptionShown value={filter.filter} /> </div> ); } }
import React, { PropTypes, PureComponent } from 'react'; import { findDOMNode } from 'react-dom'; import { InputGroup } from 'binary-components'; import { isMobile } from 'binary-utils'; import { actions } from '../_store'; import MarketSubmarketPickerContainer from './MarketSubmarketPickerContainer'; export default class AssetPickerFilter extends PureComponent { static propTypes = { filter: PropTypes.object.isRequired, }; componentDidMount() { const assetSearchNode = findDOMNode(this); if (!isMobile()) { setTimeout(() => assetSearchNode.firstChild && assetSearchNode.firstChild.firstChild && assetSearchNode.firstChild.firstChild.focus(), 100); } } onSearchQueryChange = e => { actions.updateAssetPickerSearchQuery(e.target.value); } onFilterChange = e => { actions.updateAssetPickerFilter(e); } render() { const { filter } = this.props; return ( <div className="asset-picker-filter"> <InputGroup className="asset-search" defaultValue={filter.query} type="search" placeholder="Search for assets" onChange={this.onSearchQueryChange} /> <MarketSubmarketPickerContainer onChange={this.onFilterChange} allOptionShown value={filter.filter} /> </div> ); } }
Fix asset picker input focus
Fix asset picker input focus
JavaScript
mit
nazaninreihani/binary-next-gen,nazaninreihani/binary-next-gen,binary-com/binary-next-gen,nuruddeensalihu/binary-next-gen,nazaninreihani/binary-next-gen,binary-com/binary-next-gen,nuruddeensalihu/binary-next-gen,nuruddeensalihu/binary-next-gen,binary-com/binary-next-gen
--- +++ @@ -14,7 +14,11 @@ componentDidMount() { const assetSearchNode = findDOMNode(this); if (!isMobile()) { - setTimeout(() => assetSearchNode.firstChild.focus(), 300); + setTimeout(() => + assetSearchNode.firstChild && + assetSearchNode.firstChild.firstChild && + assetSearchNode.firstChild.firstChild.focus(), + 100); } }
d55d600d9e3b8fadeabe51445ebac4c04860f808
src/AppBundle/Resources/public/scripts/menu.js
src/AppBundle/Resources/public/scripts/menu.js
$('.nav a').on('click', function(){ $(".navbar-toggle").click(); });
$('.nav a').on('click', function(){ if ($(window).width() <= 767) { $(".navbar-toggle").click(); } });
Hide close animation for non mobile.
Hide close animation for non mobile.
JavaScript
mit
Clastic/clastic-marketing,Clastic/clastic-marketing,Clastic/clastic-marketing,Clastic/clastic-marketing
--- +++ @@ -1,3 +1,5 @@ $('.nav a').on('click', function(){ - $(".navbar-toggle").click(); + if ($(window).width() <= 767) { + $(".navbar-toggle").click(); + } });
f327771057d2ad38c8a7fa8d893c37197c7fde8b
src/HashMap.js
src/HashMap.js
/** * @requires Map.js * @requires ArrayList.js */ /** * @see http://download.oracle.com/javase/6/docs/api/java/util/HashMap.html * * @implements {javascript.util.Map} * @constructor * @export */ javascript.util.HashMap = function() { this.object = {}; }; /** * @type {Object} * @private */ javascript.util.HashMap.prototype.object = null; /** * @override * @export */ javascript.util.HashMap.prototype.get = function(key) { return this.object[key]; }; /** * @override * @export */ javascript.util.HashMap.prototype.put = function(key, value) { this.object[key] = value; return value; }; /** * @override * @export */ javascript.util.HashMap.prototype.values = function() { var arrayList = new javascript.util.ArrayList(); for ( var key in this.object) { if (this.object.hasOwnProperty(key)) { arrayList.add(this.object[key]); } } return arrayList; }; /** * @override * @export */ javascript.util.HashMap.prototype.size = function() { return this.values().size(); };
/** * @requires Map.js * @requires ArrayList.js */ /** * @see http://download.oracle.com/javase/6/docs/api/java/util/HashMap.html * * @implements {javascript.util.Map} * @constructor * @export */ javascript.util.HashMap = function() { this.object = {}; }; /** * @type {Object} * @private */ javascript.util.HashMap.prototype.object = null; /** * @override * @export */ javascript.util.HashMap.prototype.get = function(key) { return this.object[key] || null; }; /** * @override * @export */ javascript.util.HashMap.prototype.put = function(key, value) { this.object[key] = value; return value; }; /** * @override * @export */ javascript.util.HashMap.prototype.values = function() { var arrayList = new javascript.util.ArrayList(); for ( var key in this.object) { if (this.object.hasOwnProperty(key)) { arrayList.add(this.object[key]); } } return arrayList; }; /** * @override * @export */ javascript.util.HashMap.prototype.size = function() { return this.values().size(); };
Fix so that get returns null instead of undefined when key not found.
Fix so that get returns null instead of undefined when key not found.
JavaScript
mit
sshiting/javascript.util,sshiting/javascript.util,bjornharrtell/javascript.util,bjornharrtell/javascript.util
--- +++ @@ -25,7 +25,7 @@ * @export */ javascript.util.HashMap.prototype.get = function(key) { - return this.object[key]; + return this.object[key] || null; }; /**
0ea7667da177e969fe9dc0e04db977db50c9d4fa
src/tap/schema.js
src/tap/schema.js
/** * [schema defines validation schemas for Mongo documents being inserted into db:ibu collection:ibuerrors] * * */ var ibuErrorSchema = new Schema({ filename: { type: String, validate: { validator: function(v){ return /^[^.]+$/.test(v); }, message: 'Filename is not valid!' } }, collection: { type: String }, IMGerrors: { type: Array }, XMLerrors: { type: Array } }); var ibuErrorDoc = mongoose.model('ibuErrorDoc', ibuErrorSchema);
'use strict'; /** * [schema defines validation schemas for Mongo documents being inserted into db:ibu collection:ibuerrors] * * */ // Mongoose connection to MongoDB const mongoose = require('mongoose'); var Schema = mongoose.Schema; var ibuErrorSchema = new Schema({ filename: { type: String, trim: true }, filePathXML: { type: String, unique: true }, filePathIMG: { type: String, unique: true }, extentionName: { type: String, trim: true }, libCollection: { type: String }, IMGerrors: { type: Array }, XMLerrors: { type: Array }, created: { type: Date , default: Date.now } }); //, // validate: { // validator: function(v){ // return /^[^.]+$/.test(v); var ibuErrorDoc = mongoose.model('ibuErrorDoc', ibuErrorSchema); module.exports = ibuErrorDoc;
Add Fields & removed Validate
Add Fields & removed Validate Remove validate until Schema is working on all code. Renamed "collection", conflict with core naming in Mongoose
JavaScript
mit
utkdigitalinitiatives/ibu,utkdigitalinitiatives/ibu
--- +++ @@ -1,20 +1,31 @@ +'use strict'; /** * [schema defines validation schemas for Mongo documents being inserted into db:ibu collection:ibuerrors] * * */ + // Mongoose connection to MongoDB +const mongoose = require('mongoose'); +var Schema = mongoose.Schema; var ibuErrorSchema = new Schema({ filename: { type: String, - validate: { - validator: function(v){ - return /^[^.]+$/.test(v); - }, - message: 'Filename is not valid!' - } + trim: true }, - collection: { + filePathXML: { + type: String, + unique: true + }, + filePathIMG: { + type: String, + unique: true + }, + extentionName: { + type: String, + trim: true + }, + libCollection: { type: String }, IMGerrors: { @@ -22,7 +33,15 @@ }, XMLerrors: { type: Array + }, + created: { + type: Date , default: Date.now } }); +//, +// validate: { +// validator: function(v){ +// return /^[^.]+$/.test(v); var ibuErrorDoc = mongoose.model('ibuErrorDoc', ibuErrorSchema); +module.exports = ibuErrorDoc;
844806fb7bbad77a5b507e0e26519575bbf3124e
js/services/Storage.js
js/services/Storage.js
define(['app'], function (app) { "use strict"; return app.service('storageService', ['$window', function (win) { this.available = 'localStorage' in win; this.get = function (key) { return win.localStorage.getItem(key); }; this.set = function (key, value) { return win.localStorage.setItem(key, value); }; this.setJSON = function (key, value) { return this.set(key, win.JSON.stringify(value)); }; this.getJSON = function (key) { return win.JSON.parse(this.get(key)); }; }]); });
define(['app', 'angular'], function (app, angular) { "use strict"; return app.service('storageService', ['$window', function (win) { this.available = 'localStorage' in win; this.get = function (key) { return win.localStorage.getItem(key); }; this.set = function (key, value) { return win.localStorage.setItem(key, value); }; this.setJSON = function (key, value) { return this.set(key, angular.toJson(value)); }; this.getJSON = function (key) { return angular.fromJson(this.get(key)); }; }]); });
Use angular's JSON lib, since it strips off $hashKey that angular adds to scope objects
Use angular's JSON lib, since it strips off $hashKey that angular adds to scope objects
JavaScript
mit
BrettBukowski/tomatar
--- +++ @@ -1,4 +1,4 @@ -define(['app'], function (app) { +define(['app', 'angular'], function (app, angular) { "use strict"; return app.service('storageService', ['$window', function (win) { @@ -13,11 +13,11 @@ }; this.setJSON = function (key, value) { - return this.set(key, win.JSON.stringify(value)); + return this.set(key, angular.toJson(value)); }; this.getJSON = function (key) { - return win.JSON.parse(this.get(key)); + return angular.fromJson(this.get(key)); }; }]); });
17c826741636990088061d32d2e1ed76beeb3d59
lib/helpers.js
lib/helpers.js
'use babel' import {getPath} from 'consistent-path' export {tempFile} from 'atom-linter' const assign = Object.assign || function(target, source) { for (const key in source) { target[key] = source[key] } return target } export function getEnv() { const env = assign({}, process.env) env.PATH = getPath() return env }
'use babel' import getEnvironment from 'consistent-env' export {tempFile} from 'atom-linter' const assign = Object.assign || function(target, source) { for (const key in source) { target[key] = source[key] } return target } export function getEnv() { return getEnvironment() }
Use consistent-env instead of consistent-path
:new: Use consistent-env instead of consistent-path
JavaScript
mit
steelbrain/autocomplete-swift
--- +++ @@ -1,6 +1,6 @@ 'use babel' -import {getPath} from 'consistent-path' +import getEnvironment from 'consistent-env' export {tempFile} from 'atom-linter' const assign = Object.assign || function(target, source) { @@ -11,7 +11,5 @@ } export function getEnv() { - const env = assign({}, process.env) - env.PATH = getPath() - return env + return getEnvironment() }
692437cd611c8cfc9222ec4cc17b0d852aa26e72
libs/layout.js
libs/layout.js
import { Dimensions } from 'react-native' module.exports = { get visibleHeight() { return Dimensions.get('window').height }, }
import { Dimensions } from 'react-native' module.exports = { get visibleHeight() { return Dimensions.get('screen').height }, }
Use screen dimension as visible height
Use screen dimension as visible height
JavaScript
mit
octopitus/rn-sliding-up-panel
--- +++ @@ -2,6 +2,6 @@ module.exports = { get visibleHeight() { - return Dimensions.get('window').height + return Dimensions.get('screen').height }, }
91beb6edb16bfe61a85c407caaa8bbf56881f366
src/events/console/request_message.js
src/events/console/request_message.js
'use strict'; const { protocolHandlers } = require('../../protocols'); const { rpcHandlers } = require('../../rpc'); // Build message of events of type `request` as: // STATUS [ERROR] - PROTOCOL METHOD RPC /PATH COMMAND... const getRequestMessage = function ({ protocol, rpc, method, path, error = 'SUCCESS', commandpath, summary, }) { const summaryA = error ? commandpath : summary; const { title: protocolTitle } = protocolHandlers[protocol] || {}; const { title: rpcTitle } = rpcHandlers[rpc] || {}; const message = [ error, '-', protocolTitle, method, rpcTitle, path, summaryA, ].filter(val => val) .join(' '); return message; }; module.exports = { getRequestMessage, };
'use strict'; const { protocolHandlers } = require('../../protocols'); const { rpcHandlers } = require('../../rpc'); // Build message of events of type `request` as: // STATUS [ERROR] - PROTOCOL METHOD RPC /PATH COMMAND... const getRequestMessage = function ({ protocol, rpc, method, path, error = 'SUCCESS', commandpath, summary, }) { const summaryA = error === 'SUCCESS' ? summary : commandpath; const { title: protocolTitle } = protocolHandlers[protocol] || {}; const { title: rpcTitle } = rpcHandlers[rpc] || {}; const message = [ error, '-', protocolTitle, method, rpcTitle, path, summaryA, ].filter(val => val) .join(' '); return message; }; module.exports = { getRequestMessage, };
Fix summary not showing up in console logs
Fix summary not showing up in console logs
JavaScript
apache-2.0
autoserver-org/autoserver,autoserver-org/autoserver
--- +++ @@ -14,7 +14,7 @@ commandpath, summary, }) { - const summaryA = error ? commandpath : summary; + const summaryA = error === 'SUCCESS' ? summary : commandpath; const { title: protocolTitle } = protocolHandlers[protocol] || {}; const { title: rpcTitle } = rpcHandlers[rpc] || {};
8bc9e027d6ed0a94ee995893d2cc8dd955550c33
tesla.js
tesla.js
var fs = require('fs'); function getInitialCharge() { var initialCharge = 100, body = fs.readFileSync('tesla.out').toString().split('\n'); for (var i = body.length - 1; i >= 0; i--) { // Pick out valid part of file. if (body[i].indexOf('battery_level:') != -1) { // Pick out the last object. initialCharge = +(body[i].split(':')[1].slice(0, -1)); console.log(initialCharge); return initialCharge; } } return initialCharge; } exports.getInitialCharge = getInitialCharge;
var fs = require('fs'); function getInitialCharge() { var initialCharge = 100, body = fs.readFileSync('tesla.out').toString().split('\n'); for (var i = body.length - 1; i >= 0; i--) { // Pick out valid part of file. if (body[i].indexOf('battery_level:') != -1) { // Pick out the last object. initialCharge = +(body[i].split(':')[1].slice(0, -1)); console.log(initialCharge); return initialCharge; } } return initialCharge; } if (require.main === module) { getInitialCharge(); } exports.getInitialCharge = getInitialCharge;
Check if called from command line.
Check if called from command line.
JavaScript
mit
PrajitR/ChargePlan
--- +++ @@ -14,4 +14,7 @@ return initialCharge; } +if (require.main === module) { + getInitialCharge(); +} exports.getInitialCharge = getInitialCharge;
4a0fa2527ad0a5765a8f846f7723158037e0520a
test/errors.js
test/errors.js
import test from 'ava'; import Canvas from 'canvas'; import mergeImages from '../'; import fixtures from './fixtures'; test('mergeImages rejects Promise if image load errors', async t => { t.plan(1); t.throws(mergeImages([1], { Canvas })); });
import test from 'ava'; import Canvas from 'canvas'; import mergeImages from '../'; import fixtures from './fixtures'; test('mergeImages rejects Promise if node-canvas instance isn\'t passed in', async t => { t.plan(1); t.throws(mergeImages([])); }); test('mergeImages rejects Promise if image load errors', async t => { t.plan(1); t.throws(mergeImages([1], { Canvas })); });
Test mergeImages rejects Promise if node-canvas instance isn\'t passed in
Test mergeImages rejects Promise if node-canvas instance isn\'t passed in
JavaScript
mit
lukechilds/merge-images
--- +++ @@ -3,6 +3,11 @@ import mergeImages from '../'; import fixtures from './fixtures'; +test('mergeImages rejects Promise if node-canvas instance isn\'t passed in', async t => { + t.plan(1); + t.throws(mergeImages([])); +}); + test('mergeImages rejects Promise if image load errors', async t => { t.plan(1); t.throws(mergeImages([1], { Canvas }));
cfdc5729e8b71c88baad96d1b06cafe643600636
test/issues.js
test/issues.js
'use strict'; /*global describe */ describe('Issues.', function () { require('./issues/issue-8.js'); require('./issues/issue-17.js'); require('./issues/issue-19.js'); require('./issues/issue-26.js'); require('./issues/issue-33.js'); require('./issues/issue-46.js'); require('./issues/issue-54.js'); require('./issues/issue-64.js'); require('./issues/issue-85.js'); require('./issues/issue-92.js'); require('./issues/issue-93.js'); require('./issues/issue-95.js'); require('./issues/issue-parse-function-security.js'); require('./issues/issue-skip-invalid.js'); });
'use strict'; /*global describe */ var path = require('path'); var fs = require('fs'); describe('Issues.', function () { var issues = path.resolve(__dirname, 'issues'); fs.readdirSync(issues).forEach(function (file) { if ('.js' === path.extname(file)) { require(path.resolve(issues, file)); } }); });
Automate loading of issue test units.
Automate loading of issue test units.
JavaScript
mit
crissdev/js-yaml,minj/js-yaml,doowb/js-yaml,djchie/js-yaml,joshball/js-yaml,cesarmarinhorj/js-yaml,nodeca/js-yaml,joshball/js-yaml,vogelsgesang/js-yaml,pombredanne/js-yaml,rjmunro/js-yaml,rjmunro/js-yaml,SmartBear/js-yaml,jonnor/js-yaml,SmartBear/js-yaml,bjlxj2008/js-yaml,denji/js-yaml,denji/js-yaml,isaacs/js-yaml,crissdev/js-yaml,djchie/js-yaml,jonnor/js-yaml,pombredanne/js-yaml,doowb/js-yaml,djchie/js-yaml,jonnor/js-yaml,nodeca/js-yaml,vogelsgesang/js-yaml,joshball/js-yaml,denji/js-yaml,minj/js-yaml,pombredanne/js-yaml,crissdev/js-yaml,cesarmarinhorj/js-yaml,bjlxj2008/js-yaml,deltreey/js-yaml,doowb/js-yaml,SmartBear/js-yaml,deltreey/js-yaml,deltreey/js-yaml,isaacs/js-yaml,nodeca/js-yaml,minj/js-yaml,cesarmarinhorj/js-yaml,vogelsgesang/js-yaml,isaacs/js-yaml,rjmunro/js-yaml,bjlxj2008/js-yaml
--- +++ @@ -2,19 +2,16 @@ /*global describe */ +var path = require('path'); +var fs = require('fs'); + + describe('Issues.', function () { - require('./issues/issue-8.js'); - require('./issues/issue-17.js'); - require('./issues/issue-19.js'); - require('./issues/issue-26.js'); - require('./issues/issue-33.js'); - require('./issues/issue-46.js'); - require('./issues/issue-54.js'); - require('./issues/issue-64.js'); - require('./issues/issue-85.js'); - require('./issues/issue-92.js'); - require('./issues/issue-93.js'); - require('./issues/issue-95.js'); - require('./issues/issue-parse-function-security.js'); - require('./issues/issue-skip-invalid.js'); + var issues = path.resolve(__dirname, 'issues'); + + fs.readdirSync(issues).forEach(function (file) { + if ('.js' === path.extname(file)) { + require(path.resolve(issues, file)); + } + }); });
048eb86cd16a0bcff04bf4fe9129131c367ce95e
test/runner.js
test/runner.js
var cp = require('child_process'); var walk = require('walk'); var walker = walk.walk(__dirname + '/spec', {followLinks: false}); walker.on('file', function(root, stat, next) { var filepath = root + '/' + stat.name; cp.fork('node_modules/mocha/bin/_mocha', [filepath]); next(); });
var cp = require('child_process'); var join = require('path').join; var walk = require('walk'); var mochaBin = join(__dirname, '..', 'node_modules', '.bin', 'mocha'); var walker = walk.walk(__dirname + '/spec', {followLinks: false}); walker.on('file', function(root, stat, next) { var filepath = root + '/' + stat.name; cp.spawn(mochaBin, [filepath], {stdio: 'inherit'}); next(); });
Replace child_process.fork with child_process.spawn to correctly handle child's output.
Replace child_process.fork with child_process.spawn to correctly handle child's output.
JavaScript
mit
vogdb/pulsar-rest-api,cargomedia/pulsar-rest-api,cargomedia/pulsar-rest-api,njam/pulsar-rest-api,njam/pulsar-rest-api,cargomedia/pulsar-rest-api,vogdb/pulsar-rest-api,cargomedia/pulsar-rest-api,vogdb/pulsar-rest-api,njam/pulsar-rest-api,njam/pulsar-rest-api
--- +++ @@ -1,11 +1,12 @@ var cp = require('child_process'); +var join = require('path').join; var walk = require('walk'); +var mochaBin = join(__dirname, '..', 'node_modules', '.bin', 'mocha'); var walker = walk.walk(__dirname + '/spec', {followLinks: false}); walker.on('file', function(root, stat, next) { - var filepath = root + '/' + stat.name; - cp.fork('node_modules/mocha/bin/_mocha', [filepath]); + cp.spawn(mochaBin, [filepath], {stdio: 'inherit'}); next(); });
b4b4997ff9b0d9c7ec17021f08d1da74e06225c7
tasks/less.js
tasks/less.js
'use strict' const fs = require('fs') const gulp = require('gulp') const lessModule = require('less') const less = require('gulp-less') const sourcemaps = require('gulp-sourcemaps') const rename = require('gulp-rename') const mkdirp = require('mkdirp') const postcss = require('gulp-postcss') const autoprefixer = require('autoprefixer') const config = require('../config').less const errorHandler = require('../util/error-handler') lessModule.functions.functionRegistry.addMultiple(config.functions) const processors = [ autoprefixer(), ] if (process.env.NODE_ENV === 'production') { const csswring = require('csswring') processors.push(csswring()) } gulp.task('less', () => { mkdirp.sync(config.dest) if (config.suffix) { fs.writeFile(`${config.dest}.json`, JSON.stringify({ suffix: config.suffix })) } let pipe = gulp.src(config.src) .pipe(sourcemaps.init()) .pipe(less(config.options).on('error', errorHandler)) .pipe(postcss(processors)) if (config.suffix) { pipe = pipe.pipe(rename({ suffix: config.suffix })) } return pipe.pipe(sourcemaps.write('./maps')) // .on('error', errorHandler) .pipe(gulp.dest(config.dest)) })
'use strict' const fs = require('fs') const gulp = require('gulp') const lessModule = require('less') const less = require('gulp-less') const sourcemaps = require('gulp-sourcemaps') const rename = require('gulp-rename') const mkdirp = require('mkdirp') const postcss = require('gulp-postcss') const autoprefixer = require('autoprefixer') const config = require('../config').less const errorHandler = require('../util/error-handler') lessModule.functions.functionRegistry.addMultiple(config.functions) const processors = [ autoprefixer(), ] if (process.env.NODE_ENV === 'production') { const csswring = require('csswring') processors.push(csswring()) } gulp.task('less', () => { mkdirp.sync(config.dest) if (config.suffix) { fs.writeFileSync(`${config.dest}.json`, JSON.stringify({ suffix: config.suffix })) } let pipe = gulp.src(config.src) .pipe(sourcemaps.init()) .pipe(less(config.options).on('error', errorHandler)) .pipe(postcss(processors)) if (config.suffix) { pipe = pipe.pipe(rename({ suffix: config.suffix })) } return pipe.pipe(sourcemaps.write('./maps')) // .on('error', errorHandler) .pipe(gulp.dest(config.dest)) })
Use sync fs method (to suppress no callback error)
Use sync fs method (to suppress no callback error)
JavaScript
mit
thebitmill/gulp
--- +++ @@ -31,7 +31,7 @@ mkdirp.sync(config.dest) if (config.suffix) { - fs.writeFile(`${config.dest}.json`, JSON.stringify({ suffix: config.suffix })) + fs.writeFileSync(`${config.dest}.json`, JSON.stringify({ suffix: config.suffix })) } let pipe = gulp.src(config.src)
7ae46169e9383f9bc71bf1715b19441df8e5be30
lib/download-station.js
lib/download-station.js
module.exports = function(syno) { return { }; };
'use strict'; var util = require('util'); function info() { /*jshint validthis:true */ var userParams = typeof arguments[0] === 'object' ? arguments[0] : {}, callback = typeof arguments[1] === 'function' ? arguments[1] : typeof arguments[0] === 'function' ? arguments[0] : null ; var params = { api : 'SYNO.DownloadStation.Info', version: 1, method : 'getinfo' }; util._extend(params, userParams); var query = this.query({ path: '/webapi/DownloadStation/info.cgi', params: params }, callback || null); return query; } function getConfig() { /*jshint validthis:true */ var userParams = typeof arguments[0] === 'object' ? arguments[0] : {}, callback = typeof arguments[1] === 'function' ? arguments[1] : typeof arguments[0] === 'function' ? arguments[0] : null ; var params = { api : 'SYNO.DownloadStation.Info', version: 1, method : 'getconfig' }; util._extend(params, userParams); var query = this.query({ path: '/webapi/DownloadStation/info.cgi', params: params }, callback || null); return query; } function setConfig() { /*jshint validthis:true */ var userParams = typeof arguments[0] === 'object' ? arguments[0] : {}, callback = typeof arguments[1] === 'function' ? arguments[1] : typeof arguments[0] === 'function' ? arguments[0] : null ; var params = { api : 'SYNO.DownloadStation.Info', version: 1, method : 'setserverconfig' }; util._extend(params, userParams); var query = this.query({ path: '/webapi/DownloadStation/info.cgi', params: params }, callback || null); return query; } module.exports = function(syno) { return { info : info.bind(syno), getConfig: getConfig.bind(syno), setConfig: setConfig.bind(syno) }; };
Add Synology.downloadStation.info, Synology.downloadStation.getConfig and Synology.downloadStation.setConfig
Add Synology.downloadStation.info, Synology.downloadStation.getConfig and Synology.downloadStation.setConfig
JavaScript
mit
yannickcr/node-synology
--- +++ @@ -1,4 +1,89 @@ +'use strict'; + +var util = require('util'); + +function info() { + /*jshint validthis:true */ + var + userParams = + typeof arguments[0] === 'object' ? arguments[0] : + {}, + callback = + typeof arguments[1] === 'function' ? arguments[1] : + typeof arguments[0] === 'function' ? arguments[0] : + null + ; + var params = { + api : 'SYNO.DownloadStation.Info', + version: 1, + method : 'getinfo' + }; + util._extend(params, userParams); + + var query = this.query({ + path: '/webapi/DownloadStation/info.cgi', + params: params + }, callback || null); + + return query; +} + +function getConfig() { + /*jshint validthis:true */ + var + userParams = + typeof arguments[0] === 'object' ? arguments[0] : + {}, + callback = + typeof arguments[1] === 'function' ? arguments[1] : + typeof arguments[0] === 'function' ? arguments[0] : + null + ; + var params = { + api : 'SYNO.DownloadStation.Info', + version: 1, + method : 'getconfig' + }; + util._extend(params, userParams); + + var query = this.query({ + path: '/webapi/DownloadStation/info.cgi', + params: params + }, callback || null); + + return query; +} + +function setConfig() { + /*jshint validthis:true */ + var + userParams = + typeof arguments[0] === 'object' ? arguments[0] : + {}, + callback = + typeof arguments[1] === 'function' ? arguments[1] : + typeof arguments[0] === 'function' ? arguments[0] : + null + ; + var params = { + api : 'SYNO.DownloadStation.Info', + version: 1, + method : 'setserverconfig' + }; + util._extend(params, userParams); + + var query = this.query({ + path: '/webapi/DownloadStation/info.cgi', + params: params + }, callback || null); + + return query; +} + module.exports = function(syno) { return { + info : info.bind(syno), + getConfig: getConfig.bind(syno), + setConfig: setConfig.bind(syno) }; };
aa6565b0e3c788e3edd278058092b4ae80063685
lib/dujs/scopefinder.js
lib/dujs/scopefinder.js
/* * Find scopes from AST * @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com) * @lastmodifiedDate 2015-07-27 */ var walkes = require('walkes'); /** * ScopeFinder * @constructor */ function ScopeFinder() { } /** * Find function scopes of AST parsed from source * @param {Object} ast JS parsed AST * @returns {Object} Array of ASTs, each corresponds to global or function scope */ ScopeFinder.prototype.findScopes = function (ast) { 'use strict'; var scopes = []; function handleInnerFunction(astNode, recurse) { scopes.push(astNode); recurse(astNode.body); } walkes(ast, { Program: function (node, recurse) { scopes.push(node); node.body.forEach(function (elem) { recurse(elem); }); }, FunctionDeclaration: handleInnerFunction, FunctionExpression: handleInnerFunction }); return scopes; }; var finder = new ScopeFinder(); module.exports = finder;
/* * Find scopes from AST * @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com) * @lastmodifiedDate 2015-07-27 */ var walkes = require('walkes'); /** * ScopeFinder * @constructor */ function ScopeFinder() { } /** * Find function scopes of AST parsed from source * @param {Object} ast JS parsed AST * @returns {Object} Array of ASTs, each corresponds to global or function scope */ ScopeFinder.prototype.findScopes = function (ast) { 'use strict'; var scopes = []; function handleInnerFunction(astNode, recurse) { scopes.push(astNode); recurse(astNode.body); } walkes(ast, { Program: function (node, recurse) { scopes.push(node); node.body.forEach(function (elem) { recurse(elem); }); }, FunctionDeclaration: handleInnerFunction, FunctionExpression: handleInnerFunction }); return scopes; }; var finder = new ScopeFinder(); module.exports = finder;
Modify default line separator from CRLF to LF
Modify default line separator from CRLF to LF
JavaScript
mit
chengfulin/dujs,chengfulin/dujs
68740b554194b5318eaedc507a285d66ccf1ecd3
test/index.js
test/index.js
global.XMLHttpRequest = require('xhr2'); global.dataLayer = []; var test = require('blue-tape'); var GeordiClient = require('../index'); test('Instantiate a client with default settings', function(t) { var geordi = new GeordiClient(); t.equal(geordi.env, 'staging'); t.equal(geordi.projectToken, 'unspecified'); t.end() }); test('Log without a valid project token', function(t) { var geordi = new GeordiClient({projectToken:''}); geordi.logEvent('test event') .then(function(response){ t.fail('invalid project token should not be logged'); t.end() }) .catch(function(error){ t.pass(error); t.end() }); }); test('Log with valid project token', function(t) { var geordi = new GeordiClient({projectToken: 'test/token'}); geordi.logEvent('test event') .then(function(response){ t.pass('Valid project token will allow logging'); t.end() }) }); test('Update data on Geordi', function(t) { var geordi = new GeordiClient({projectToken: 'test/token'}); geordi.update({projectToken: 'new/token'}) t.equal(geordi.projectToken, 'new/token'); t.end() });
global.XMLHttpRequest = require('xhr2'); global.dataLayer = []; var test = require('blue-tape'); var GeordiClient = require('../index'); test('Instantiate a client with default settings', function(t) { var geordi = new GeordiClient(); t.equal(geordi.env, 'staging'); t.equal(geordi.projectToken, 'unspecified'); t.end(); }); test('Instantiate a client with older settings', function(t) { var geordi = new GeordiClient({server: 'production'}); t.equal(geordi.env, 'production'); t.end(); }); test('Log without a valid project token', function(t) { var geordi = new GeordiClient({projectToken:''}); geordi.logEvent('test event') .then(function(response){ t.fail('invalid project token should not be logged'); t.end(); }) .catch(function(error){ t.pass(error); t.end(); }); }); test('Log with valid project token', function(t) { var geordi = new GeordiClient({projectToken: 'test/token'}); geordi.logEvent('test event') .then(function(response){ t.pass('Valid project token will allow logging'); t.end(); }) }); test('Update data on Geordi', function(t) { var geordi = new GeordiClient({projectToken: 'test/token'}); geordi.update({projectToken: 'new/token'}) t.equal(geordi.projectToken, 'new/token'); t.end(); });
Test that server config hasn't broken
Test that server config hasn't broken
JavaScript
apache-2.0
zooniverse/geordi-client
--- +++ @@ -7,18 +7,23 @@ var geordi = new GeordiClient(); t.equal(geordi.env, 'staging'); t.equal(geordi.projectToken, 'unspecified'); - t.end() + t.end(); +}); +test('Instantiate a client with older settings', function(t) { + var geordi = new GeordiClient({server: 'production'}); + t.equal(geordi.env, 'production'); + t.end(); }); test('Log without a valid project token', function(t) { var geordi = new GeordiClient({projectToken:''}); geordi.logEvent('test event') .then(function(response){ t.fail('invalid project token should not be logged'); - t.end() + t.end(); }) .catch(function(error){ t.pass(error); - t.end() + t.end(); }); }); test('Log with valid project token', function(t) { @@ -26,12 +31,12 @@ geordi.logEvent('test event') .then(function(response){ t.pass('Valid project token will allow logging'); - t.end() + t.end(); }) }); test('Update data on Geordi', function(t) { var geordi = new GeordiClient({projectToken: 'test/token'}); geordi.update({projectToken: 'new/token'}) t.equal(geordi.projectToken, 'new/token'); - t.end() + t.end(); });
d08660202911ad0739d90de24c16614a510df4c0
lib/SymbolShim.js
lib/SymbolShim.js
var objectTypes = { "boolean": false, "function": true, "object": true, "number": false, "string": false, "undefined": false }; /*eslint-disable */ var _root = (objectTypes[typeof self] && self) || (objectTypes[typeof window] && window); var freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { _root = freeGlobal; } /*eslint-enable */ var _id = 0; function ensureSymbol(root) { if (!root.Symbol) { root.Symbol = function symbolFuncPolyfill(description) { return "@@Symbol(" + description + "):" + (_id++) + "}"; }; } return root.Symbol; } function ensureObservable(Symbol) { if (!Symbol.observable) { if (typeof Symbol.for === "function") { Symbol.observable = Symbol.for("observable"); } else { Symbol.observable = "@@observable"; } } } function symbolForPolyfill(key) { return "@@" + key; } function ensureFor(Symbol) { if (!Symbol.for) { Symbol.for = symbolForPolyfill; } } function polyfillSymbol(root) { var Symbol = ensureSymbol(root); ensureObservable(Symbol); ensureFor(Symbol); return Symbol; } module.exports = polyfillSymbol(_root);
var objectTypes = { "boolean": false, "function": true, "object": true, "number": false, "string": false, "undefined": false }; /*eslint-disable */ var _root = (objectTypes[typeof self] && self) || (objectTypes[typeof window] && window); var freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { _root = freeGlobal; } /*eslint-enable */ var _id = 0; function ensureSymbol(root) { if (!root.Symbol) { root.Symbol = function symbolFuncPolyfill(description) { return "@@Symbol(" + description + "):" + (_id++) + "}"; }; } return root.Symbol; } function ensureObservable(Symbol) { /* eslint-disable dot-notation */ if (!Symbol.observable) { if (typeof Symbol.for === "function") { Symbol["observable"] = Symbol.for("observable"); } else { Symbol["observable"] = "@@observable"; } } /* eslint-disable dot-notation */ } function symbolForPolyfill(key) { return "@@" + key; } function ensureFor(Symbol) { /* eslint-disable dot-notation */ if (!Symbol.for) { Symbol["for"] = symbolForPolyfill; } /* eslint-enable dot-notation */ } function polyfillSymbol(root) { var Symbol = ensureSymbol(root); ensureObservable(Symbol); ensureFor(Symbol); return Symbol; } module.exports = polyfillSymbol(_root);
Fix transpilation error to support React Native
Fix transpilation error to support React Native Recent versions of Babel will throw a TransformError in certain runtimes if any property on `Symbol` is assigned a value. This fixes the issue, which is the last remaining issue for React Native support.
JavaScript
apache-2.0
Netflix/falcor,sdesai/falcor,Netflix/falcor,sdesai/falcor
--- +++ @@ -28,13 +28,15 @@ } function ensureObservable(Symbol) { + /* eslint-disable dot-notation */ if (!Symbol.observable) { if (typeof Symbol.for === "function") { - Symbol.observable = Symbol.for("observable"); + Symbol["observable"] = Symbol.for("observable"); } else { - Symbol.observable = "@@observable"; + Symbol["observable"] = "@@observable"; } } + /* eslint-disable dot-notation */ } function symbolForPolyfill(key) { @@ -42,9 +44,11 @@ } function ensureFor(Symbol) { + /* eslint-disable dot-notation */ if (!Symbol.for) { - Symbol.for = symbolForPolyfill; + Symbol["for"] = symbolForPolyfill; } + /* eslint-enable dot-notation */ }
97b03822bb8d700a326417decfb5744a71998d9c
tests/index.js
tests/index.js
var should = require('should'), stylus = require('stylus'), fs = require('fs'); var stylusMatchTest = function() { var files = fs.readdirSync(__dirname + '/fixtures/stylus/styl/'); files.forEach(function(file) { var fileName = file.replace(/.{5}$/, ''); describe(fileName + ' method', function() { it('should match', function(done) { var str = fs.readFileSync(__dirname + '/fixtures/stylus/styl/' + fileName + '.styl', { encoding: 'utf8' }); stylus(str) .import('stylus/jeet') .render(function(err, result) { var expected = fs.readFileSync(__dirname + '/fixtures/stylus/css/' + fileName + '.css', { encoding: 'utf8' }); done(err, expected.should.be.exactly(result)); }); }); }); }); } stylusMatchTest();
var stylus = require('stylus'), fs = require('fs'), should = require('should'); function compare(name, done) { var str = fs.readFileSync(__dirname + '/fixtures/stylus/styl/' + name + '.styl', { encoding: 'utf8' }); stylus(str) .import('stylus/jeet') .render(function(err, result) { fs.readFile(__dirname + '/fixtures/stylus/css/' + name + '.css', { encoding: 'utf8' }, function(e, expected) { done(err, expected.should.be.exactly(result)); }); }); } // Stylus Comparison Tests describe('compiling method', function() { it('should apply a translucent, light-gray background color to all elements', function(done) { compare('edit', done); }); it('should center an element horizontally', function(done) { compare('center', done); }); });
Make testing function more solid
Make testing function more solid
JavaScript
mit
lucasoneves/jeet,jakecleary/jeet,durvalrafael/jeet,ccurtin/jeet,nagyistoce/jeet,pramodrhegde/jeet,mojotech/jeet,rafaelstz/jeet,mojotech/jeet,greyhwndz/jeet,macressler/jeet,travisc5/jeet
--- +++ @@ -1,28 +1,24 @@ -var should = require('should'), - stylus = require('stylus'), - fs = require('fs'); +var stylus = require('stylus'), + fs = require('fs'), + should = require('should'); -var stylusMatchTest = function() { - var files = fs.readdirSync(__dirname + '/fixtures/stylus/styl/'); - - files.forEach(function(file) { - var fileName = file.replace(/.{5}$/, ''); - - describe(fileName + ' method', function() { - it('should match', function(done) { - var str = fs.readFileSync(__dirname + '/fixtures/stylus/styl/' + fileName + '.styl', { encoding: 'utf8' }); - stylus(str) - .import('stylus/jeet') - .render(function(err, result) { - var expected = fs.readFileSync(__dirname + '/fixtures/stylus/css/' + fileName + '.css', { encoding: 'utf8' }); - - done(err, expected.should.be.exactly(result)); - }); +function compare(name, done) { + var str = fs.readFileSync(__dirname + '/fixtures/stylus/styl/' + name + '.styl', { encoding: 'utf8' }); + stylus(str) + .import('stylus/jeet') + .render(function(err, result) { + fs.readFile(__dirname + '/fixtures/stylus/css/' + name + '.css', { encoding: 'utf8' }, function(e, expected) { + done(err, expected.should.be.exactly(result)); }); }); - - }); - } -stylusMatchTest(); +// Stylus Comparison Tests +describe('compiling method', function() { + it('should apply a translucent, light-gray background color to all elements', function(done) { + compare('edit', done); + }); + it('should center an element horizontally', function(done) { + compare('center', done); + }); +});
78a92e702daedff605c76be0eeebaeb10241fcd1
lib/less/less-error.js
lib/less/less-error.js
module.exports = LessError; function LessError(parser, e, env) { var input = parser.getInput(e, env), loc = parser.getLocation(e.index, input), line = loc.line, col = loc.column, callLine = e.call && parser.getLocation(e.call, input).line, lines = input.split('\n'); this.type = e.type || 'Syntax'; this.message = e.message; this.filename = e.filename || env.currentFileInfo.filename; this.index = e.index; this.line = typeof(line) === 'number' ? line + 1 : null; this.callLine = callLine + 1; this.callExtract = lines[callLine]; this.stack = e.stack; this.column = col; this.extract = [ lines[line - 1], lines[line], lines[line + 1] ]; } LessError.prototype = new Error(); LessError.prototype.constructor = LessError;
var LessError = module.exports = function LessError(parser, e, env) { var input = parser.getInput(e, env), loc = parser.getLocation(e.index, input), line = loc.line, col = loc.column, callLine = e.call && parser.getLocation(e.call, input).line, lines = input.split('\n'); this.type = e.type || 'Syntax'; this.message = e.message; this.filename = e.filename || env.currentFileInfo.filename; this.index = e.index; this.line = typeof(line) === 'number' ? line + 1 : null; this.callLine = callLine + 1; this.callExtract = lines[callLine]; this.stack = e.stack; this.column = col; this.extract = [ lines[line - 1], lines[line], lines[line + 1] ]; } LessError.prototype = new Error(); LessError.prototype.constructor = LessError;
Fix LessError being used before being defined
Fix LessError being used before being defined
JavaScript
apache-2.0
bhavyaNaveen/project1,evocateur/less.js,jjj117/less.js,paladox/less.js,Nastarani1368/less.js,waiter/less.js,yuhualingfeng/less.js,SkReD/less.js,SomMeri/less-rhino.js,yuhualingfeng/less.js,mcanthony/less.js,christer155/less.js,royriojas/less.js,cgvarela/less.js,royriojas/less.js,idreamingreen/less.js,ridixcr/less.js,deciament/less.js,demohi/less.js,ridixcr/less.js,waiter/less.js,mishal/less.js,mtscout6/less.js,cypher0x9/less.js,Synchro/less.js,chenxiaoxing1992/less.js,foresthz/less.js,wyfyyy818818/less.js,ahutchings/less.js,pkdevbox/less.js,featurist/less-vars,AlexMeliq/less.js,demohi/less.js,NaSymbol/less.js,angeliaz/less.js,bendroid/less.js,mcanthony/less.js,aichangzhi123/less.js,xiaoyanit/less.js,less/less.js,deciament/less.js,less/less.js,lincome/less.js,idreamingreen/less.js,angeliaz/less.js,foresthz/less.js,christer155/less.js,MrChen2015/less.js,NirViaje/less.js,huzion/less.js,Nastarani1368/less.js,gencer/less.js,cypher0x9/less.js,bhavyaNaveen/project1,egg-/less.js,wjb12/less.js,arusanov/less.js,mishal/less.js,lincome/less.js,NirViaje/less.js,lvpeng/less.js,jdan/less.js,thinkDevDM/less.js,egg-/less.js,wjb12/less.js,NaSymbol/less.js,xiaoyanit/less.js,sqliang/less.js,bammoo/less.js,bammoo/less.js,bendroid/less.js,ahstro/less.js,dyx/less.js,gencer/less.js,AlexMeliq/less.js,nolanlawson/less.js,jdan/less.js,miguel-serrano/less.js,thinkDevDM/less.js,seven-phases-max/less.js,featurist/less-vars,cgvarela/less.js,nolanlawson/less.js,PUSEN/less.js,pkdevbox/less.js,aichangzhi123/less.js,ahutchings/less.js,less/less.js,MrChen2015/less.js,wyfyyy818818/less.js,arusanov/less.js,sqliang/less.js,miguel-serrano/less.js,evocateur/less.js,huzion/less.js,jjj117/less.js,SomMeri/less-rhino.js,Synchro/less.js,seven-phases-max/less.js,chenxiaoxing1992/less.js,paladox/less.js,PUSEN/less.js,dyx/less.js,SkReD/less.js,HossainKhademian/LessJs,ahstro/less.js,lvpeng/less.js
--- +++ @@ -1,6 +1,5 @@ -module.exports = LessError; -function LessError(parser, e, env) { +var LessError = module.exports = function LessError(parser, e, env) { var input = parser.getInput(e, env), loc = parser.getLocation(e.index, input), line = loc.line,
ddb79a63bd6bfd489758db9cb940b4cb9656a754
routes/useCases.js
routes/useCases.js
var app = require('../load'), useCases = app.useCases, h = require('../configHelpers'); exports.index = function(req, res){ res.json(app.useCases); }; exports.create = function(req, res){ h.overwriteConfigWithPath(req.body, app.config().configPath, req.body.name + '.json'); app.useCases.push(req.body); res.json(app.useCases); };
var app = require('../load'), useCases = app.useCases, h = require('../configHelpers'); exports.index = function(req, res){ res.json(app.useCases); }; exports.create = function(req, res){ // TODO: do this check in ember, before hitting the route if (h.loadConfigWithPathConverted(app.config().configPath, req.body.name + '.json')) { res.send(409, 'Conflict: Use Case Already Exists'); } else { h.overwriteConfigWithPath(req.body, app.config().configPath, req.body.name + '.json'); app.useCases.push(req.body); res.json(app.useCases); } };
Return 409 if creating a use case that already exists
Return 409 if creating a use case that already exists
JavaScript
mit
Webkite-Themes/iago
--- +++ @@ -7,8 +7,13 @@ }; exports.create = function(req, res){ - h.overwriteConfigWithPath(req.body, app.config().configPath, req.body.name + '.json'); - app.useCases.push(req.body); - res.json(app.useCases); + // TODO: do this check in ember, before hitting the route + if (h.loadConfigWithPathConverted(app.config().configPath, req.body.name + '.json')) { + res.send(409, 'Conflict: Use Case Already Exists'); + } else { + h.overwriteConfigWithPath(req.body, app.config().configPath, req.body.name + '.json'); + app.useCases.push(req.body); + res.json(app.useCases); + } };
ea0293471dcee31b21b9b3ae5b91276ba95e6aed
src/js/chat.js
src/js/chat.js
/** * Chat Component * $("#chat").chat({ * ruleGroupName: "", * style: ["block"], * template: [1], * environment: "1"|"2"|"3" * }); */ ui.chat = function(conf) { var that = ui.object(); // Inheritance var getDomain = function(n) { switch (n) { case "1": return "mercadolidesa.com.ar"; break; case "2": return "mercadolistage.com.ar"; break; case "3": return "mercadolibre.com.ar"; break; } } if (conf.msg) { conf.ruleGroupName = conf.msg; } that.load = function() { loadChatGZ(conf.ruleGroupName, conf.element.id, conf.style||"block", conf.template||"1",conf.environment||"3"); } ui.get({ method: "component", name: "chat", script: "http://www."+getDomain(conf.environment)+"/org-img/jsapi/chat/chatRBIScript.js", callback: function() { that.load(); } }); that.publish = { uid: conf.uid, element: conf.element, type: conf.type } return that.publish; }
/** * Chat Component * $("#chat").chat({ * ruleGroupName: "", * style: ["block"], * template: [1], * environment: "1"|"2"|"3" * }); */ ui.chat = function(conf) { var that = ui.object(); // Inheritance var getDomain = function(n) { switch (n) { case "1": return "mercadolidesa.com.ar"; break; case "2": return "mercadolistage.com.ar"; break; case "3": return "mercadolibre.com.ar"; break; } } if (conf.msg) { conf.ruleGroupName = conf.msg; } that.load = function() { loadChatGZ(conf.ruleGroupName, conf.element.id, conf.style||"block", conf.template||"1",conf.environment||"3"); } ui.get({ method: "component", name: "chat", script: "https://www."+getDomain(conf.environment)+"/org-img/jsapi/chat/chatRBIScript.js", callback: function() { that.load(); } }); that.publish = { uid: conf.uid, element: conf.element, type: conf.type } return that.publish; }
Change https protocol for Chat component
Change https protocol for Chat component
JavaScript
mit
mercadolibre/chico,atma/chico,vrleonel/chico,atma/chico,vrleonel/ml-test,amireynoso/uxtest,amireynoso/uxtest,vrleonel/chico,vrleonel/ml-test,mercadolibre/chico
--- +++ @@ -32,7 +32,7 @@ ui.get({ method: "component", name: "chat", - script: "http://www."+getDomain(conf.environment)+"/org-img/jsapi/chat/chatRBIScript.js", + script: "https://www."+getDomain(conf.environment)+"/org-img/jsapi/chat/chatRBIScript.js", callback: function() { that.load(); }
6aa9a30b0238a58980897ee83972514400ea2a5c
lib/handlebars.js
lib/handlebars.js
var Handlebars = require("handlebars/base"); module.exports = Handlebars; require("handlebars/utils"); require("handlebars/ast"); require("handlebars/printer"); require("handlebars/visitor"); require("handlebars/compiler"); // BEGIN(BROWSER) // END(BROWSER)
var Handlebars = require("handlebars/base"); module.exports = Handlebars; require("handlebars/utils"); require("handlebars/ast"); require("handlebars/printer"); require("handlebars/visitor"); require("handlebars/compiler/compiler"); require("handlebars/vm"); // BEGIN(BROWSER) // END(BROWSER)
Update node loader for compiler/vm split
Update node loader for compiler/vm split
JavaScript
mit
xiaobai93yue/handlebars.js,shakyShane/hb-fork,xiaobai93yue/handlebars.js,gautamkrishnar/handlebars.js,shakyShane/hb-fork,denniskuczynski/handlebars.js,cgvarela/handlebars.js,code0100fun/handlebars.js,mosoft521/handlebars.js,samokspv/handlebars.js,liudianpeng/handlebars.js,mubassirhayat/handlebars.js,halhenke/handlebars.js,mosoft521/handlebars.js,ThiagoGarciaAlves/handlebars.js,nikolas/handlebars.js,0xack13/handlebars.js,hafeez-syed/handlebars.js,hafeez-syed/handlebars.js,ThiagoGarciaAlves/handlebars.js,palindr0me/handlebars.js,palindr0me/handlebars.js,thechampanurag/handlebars.js,kamalbhatia/handlebars.js,eGood/handlebars,airportyh/ember-handlebars,kingsj/handlebars.js,ThiagoGarciaAlves/handlebars.js,wjb12/handlebars.js,vantage777/handlebars.js,airportyh/ember-handlebars,denniskuczynski/handlebars.js,280455936/handlebars.js,thechampanurag/handlebars.js,chiefninew/handlebars.js,jacqt/handlebars.js,code0100fun/handlebars.js,cgvarela/handlebars.js,ftdebugger/handlebars.js,wycats/handlebars.js,mosoft521/handlebars.js,wycats/handlebars.js,nazhenhuiyi/handlebars.js,machty/handlebars.js,jbboehr/handlebars.js,ianmstew/handlebars.js,handlebars-lang/handlebars.js,xiaobai93yue/handlebars.js,MaxIndu/handlebars.js,mosoft521/handlebars.js,jacqt/handlebars.js,chiefninew/handlebars.js,kuailingmin/handlebars.js,eGood/handlebars,michaellopez/handlebars.js,wycats/handlebars.js,vantage777/handlebars.js,chiefninew/handlebars.js,mubassirhayat/handlebars.js,hafeez-syed/handlebars.js,fpauser/handlebars.js,cgvarela/handlebars.js,ianmstew/handlebars.js,MaxIndu/handlebars.js,nazhenhuiyi/handlebars.js,haveal/handlebars.js,vantage777/handlebars.js,kamalbhatia/handlebars.js,nikolas/handlebars.js,wycats/handlebars.js,kingsj/handlebars.js,ftdebugger/handlebars.js,margaritis/handlebars.js,wjb12/handlebars.js,haveal/handlebars.js,leandono/handlebars.js,kingsj/handlebars.js,leandono/handlebars.js,mosoft521/handlebars.js,code0100fun/handlebars.js,michaellopez/handlebars.js,0xack13/handlebars.js,thechampanurag/handlebars.js,fpauser/handlebars.js,machty/handlebars.js,haveal/handlebars.js,MaxIndu/handlebars.js,ianmstew/handlebars.js,kuailingmin/handlebars.js,flenter/handlebars.js,margaritis/handlebars.js,jacqt/handlebars.js,280455936/handlebars.js,wycats/handlebars.js,handlebars-lang/handlebars.js,handlebars-lang/handlebars.js,0xack13/handlebars.js,liudianpeng/handlebars.js,halhenke/handlebars.js,samokspv/handlebars.js,wjb12/handlebars.js,michaellopez/handlebars.js,ftdebugger/handlebars.js,airportyh/ember-handlebars,gautamkrishnar/handlebars.js,mubassirhayat/handlebars.js,meteor/handlebars.js,kamalbhatia/handlebars.js,handlebars-lang/handlebars.js,nazhenhuiyi/handlebars.js,jbboehr/handlebars.js,gautamkrishnar/handlebars.js,meteor/handlebars.js,jbboehr/handlebars.js,nikolas/handlebars.js,flenter/handlebars.js,handlebars-lang/handlebars.js,flenter/handlebars.js,halhenke/handlebars.js,liudianpeng/handlebars.js,palindr0me/handlebars.js,samokspv/handlebars.js,280455936/handlebars.js
--- +++ @@ -7,7 +7,8 @@ require("handlebars/printer"); require("handlebars/visitor"); -require("handlebars/compiler"); +require("handlebars/compiler/compiler"); +require("handlebars/vm"); // BEGIN(BROWSER)
1ef81c6657121d4aeabfbf6b27b9df63b739e6db
src/App.js
src/App.js
import React, { Component } from 'react'; import "./css/App.css"; import logo from "../public/logo.svg"; import Markdown from "./Markdown"; import TocHeader from "./TocHeader"; class App extends Component { render() { return ( <div> <div className="header"> <img className="logo" src={logo} alt="Logo"/> <div className="logo-text">FredBoat</div> </div> <div className="page-body"> <div className="table-of-contents"> <div className="toc-title"> Contents </div> <TocHeader activePage={this.props.page} page="index" name="Quickstart"/> <TocHeader activePage={this.props.page} page="faq" name="FAQ"/> <TocHeader activePage={this.props.page} page="terms" name="Terms of Service"/> <TocHeader activePage={this.props.page} page="selfhosting" name="Selfhosting"/> <TocHeader activePage={this.props.page} page="systemdservice" name="Selfhosting (systemd)"/> </div> <Markdown name={this.props.page}/> </div> </div> ) } } export default App;
import React, { Component } from 'react'; import "./css/App.css"; import logo from "../public/logo.svg"; import Markdown from "./Markdown"; import TocHeader from "./TocHeader"; class App extends Component { render() { return ( <div> <div className="header"> <img className="logo" src={logo} alt="Logo"/> <div className="logo-text">FredBoat</div> </div> <div className="page-body"> <div className="table-of-contents"> <div className="toc-title"> Contents </div> <TocHeader activePage={this.props.page} page="index" name="Quickstart"/> <TocHeader activePage={this.props.page} page="faq" name="FAQ"/> <TocHeader activePage={this.props.page} page="selfhosting" name="Selfhosting"/> <TocHeader activePage={this.props.page} page="systemdservice" name="Selfhosting (systemd)"/> <TocHeader activePage={this.props.page} page="terms" name="Terms of Service"/> </div> <Markdown name={this.props.page}/> </div> </div> ) } } export default App;
Move ToS to the bottom
Move ToS to the bottom
JavaScript
mit
FredBoat/docs.fredboat.com,FredBoat/fredboat.com,FredBoat/docs.fredboat.com,FredBoat/fredboat.com
--- +++ @@ -20,9 +20,9 @@ </div> <TocHeader activePage={this.props.page} page="index" name="Quickstart"/> <TocHeader activePage={this.props.page} page="faq" name="FAQ"/> - <TocHeader activePage={this.props.page} page="terms" name="Terms of Service"/> <TocHeader activePage={this.props.page} page="selfhosting" name="Selfhosting"/> <TocHeader activePage={this.props.page} page="systemdservice" name="Selfhosting (systemd)"/> + <TocHeader activePage={this.props.page} page="terms" name="Terms of Service"/> </div> <Markdown name={this.props.page}/>
e1d9d0e9f784df298df41967cfba947fa65c2698
commands/access/remove.js
commands/access/remove.js
'use strict'; var Heroku = require('heroku-client'); var co = require('co'); var heroku; module.exports = { topic: 'access', needsAuth: true, needsApp: true, command: 'remove', description: 'Remove users from your app', help: 'heroku access:remove user@email.com --app APP', args: [{name: 'user', optional: false}], run: function (context) { let appName; appName = context.app; co(function* () { heroku = new Heroku({token: context.auth.password}); yield heroku.apps(appName).collaborators(context.args.user).delete(function (err) { if (err) { throw err; } console.log(`Removing ${context.args.user} from application ${cli.color.cyan(appName)}...done`); }); }).catch(function (err) { console.error(err); }); } };
'use strict'; var Heroku = require('heroku-client'); var co = require('co'); var heroku; module.exports = { topic: 'access', needsAuth: true, needsApp: true, command: 'remove', description: 'Remove users from your app', help: 'heroku access:remove user@email.com --app APP', args: [{name: 'user', optional: false}], run: function (context) { let appName; appName = context.app; co(function* () { heroku = new Heroku({token: context.auth.password}); yield heroku.apps(appName).collaborators(context.args.user).delete(function (err) { if (err) { throw err; } console.log(`Removing ${context.args.user} from application appName...done`); }); }).catch(function (err) { console.error(err); }); } };
Remove is not ready yet
Remove is not ready yet
JavaScript
isc
heroku/heroku-access,heroku/heroku-orgs
--- +++ @@ -22,7 +22,7 @@ heroku = new Heroku({token: context.auth.password}); yield heroku.apps(appName).collaborators(context.args.user).delete(function (err) { if (err) { throw err; } - console.log(`Removing ${context.args.user} from application ${cli.color.cyan(appName)}...done`); + console.log(`Removing ${context.args.user} from application appName...done`); }); }).catch(function (err) { console.error(err);
8ca011e17298196dba123b83b02a72e010020291
app/documents/services/SearchService.js
app/documents/services/SearchService.js
module.exports = function($http, $state, $location, $q, DocumentApiService, DocumentRouteService, DocumentService, GlobalService, UserService, MathJaxService) { console.log('SEARCH SERVICE') var deferred = $q.defer(); var apiServer = GlobalService.apiServer() this.query = function(searchText, scope, destination='documents') { if (UserService.accessTokenValid() == false) { searchText += '&public' } return $http.get('http://' + apiServer + '/v1/documents' + '?' + searchText ) .then(function(response){ var jsonData = response.data var documents = jsonData['documents'] if (documents.length == 0) { documents = [GlobalService.defaultDocumentID()] } DocumentService.setDocumentList(documents) var id = documents[0]['id'] DocumentApiService.getDocument(id) DocumentApiService.getDocument(id).then(function(response) { $state.go('documents', {}, {reload: true}) }) }) } }
module.exports = function($http, $state, $location, $q, DocumentApiService, DocumentRouteService, DocumentService, GlobalService, UserService, MathJaxService) { console.log('SEARCH SERVICE') var deferred = $q.defer(); var apiServer = GlobalService.apiServer() this.query = function(searchText, scope, destination='documents') { if (UserService.accessTokenValid() == false) { searchText += '&public' } return $http.get('http://' + apiServer + '/v1/documents' + '?' + searchText ) .then(function(response){ var jsonData = response.data var documents = jsonData['documents'] if ((documents == undefined) || (documents.length == 0)) { documents = [GlobalService.defaultDocumentID()] } DocumentService.setDocumentList(documents) var id = documents[0]['id'] DocumentApiService.getDocument(id) DocumentApiService.getDocument(id).then(function(response) { $state.go('documents', {}, {reload: true}) }) }) } }
Handle case of undefined document list as result of search
Handle case of undefined document list as result of search
JavaScript
mit
jxxcarlson/ns_angular,jxxcarlson/ns_angular
--- +++ @@ -20,7 +20,7 @@ var jsonData = response.data var documents = jsonData['documents'] - if (documents.length == 0) { documents = [GlobalService.defaultDocumentID()] } + if ((documents == undefined) || (documents.length == 0)) { documents = [GlobalService.defaultDocumentID()] } DocumentService.setDocumentList(documents)
8ffc8c6ca7b831278db6e0891409c58ea1fd3daa
app/instance-initializers/ember-a11y.js
app/instance-initializers/ember-a11y.js
// This initializer exists only to make sure that the following // imports happen before the app boots. import { registerKeywords } from 'ember-a11y/ember-internals'; registerKeywords(); import Ember from 'ember'; export function initialize(application) { let startRouting = application.startRouting; application.startRouting = function() { console.log('here'); startRouting.call(application); } } export default { name: 'ember-a11y', initialize };
// This initializer exists only to make sure that the following // imports happen before the app boots. import Ember from 'ember'; import { registerKeywords } from 'ember-a11y/ember-internals'; registerKeywords(); let handlerInfos; Ember.Router.reopen({ didTransition(handlerInfos) { this._super(...arguments); } }); export function initialize(application) {} export default { name: 'ember-a11y', initialize };
Stop monkeypatching all the things. Monkeypatch the right things.
Stop monkeypatching all the things. Monkeypatch the right things.
JavaScript
mit
ember-a11y/ember-a11y,nathanhammond/ember-a11y,ember-a11y/ember-a11y,nathanhammond/ember-a11y
--- +++ @@ -1,17 +1,17 @@ // This initializer exists only to make sure that the following // imports happen before the app boots. +import Ember from 'ember'; import { registerKeywords } from 'ember-a11y/ember-internals'; registerKeywords(); -import Ember from 'ember'; +let handlerInfos; +Ember.Router.reopen({ + didTransition(handlerInfos) { + this._super(...arguments); + } +}); -export function initialize(application) { - let startRouting = application.startRouting; - application.startRouting = function() { - console.log('here'); - startRouting.call(application); - } -} +export function initialize(application) {} export default { name: 'ember-a11y',
3158eb1bbd06d8a7fb8bc9c60e9fed423f3971a4
src/DrawingManager.js
src/DrawingManager.js
var p; var drawings = []; var DrawingManager = function (p5Sketch) { p = p5Sketch; }; DrawingManager.prototype.add = function (drawing) { console.log('Added ' + drawing); drawings.unshift(drawing); } DrawingManager.prototype.drawAll = function () { for (var i = drawings.length - 1; i >= 0; i--) { drawings[i].draw(p); if (drawings[i].done()) { drawings.splice(i, 1); } }; } DrawingManager.prototype.update = function (pulse, config) { for (var i = drawings.length - 1; i >= 0; i--) { if (drawings[i].pulse.name === pulse.name) { drawings[i].update(p, pulse, config); console.log("UPDATED pulse", drawings[i].pulse.name); } } } DrawingManager.prototype.clear = function () { drawings = []; } module.exports = DrawingManager;
var p; var drawings = []; var lowerLayer = []; var DrawingManager = function (p5Sketch) { p = p5Sketch; }; DrawingManager.prototype.add = function (drawing) { if (drawing.pulse.layer) { lowerLayer.unshift(drawing); } else { console.log('Added ' + drawing); drawings.unshift(drawing); } } DrawingManager.prototype.drawAll = function () { for (var i = lowerLayer.length - 1; i >= 0; i--) { lowerLayer[i].draw(p); if (lowerLayer[i].done()) { lowerLayer.splice(i, 1); } }; for (var i = drawings.length - 1; i >= 0; i--) { drawings[i].draw(p); if (drawings[i].done()) { drawings.splice(i, 1); } }; } DrawingManager.prototype.update = function (pulse, config) { for (var i = drawings.length - 1; i >= 0; i--) { if (drawings[i].pulse.name === pulse.name) { drawings[i].update(p, pulse, config); console.log("UPDATED pulse", drawings[i].pulse.name); } } } DrawingManager.prototype.clear = function () { drawings = []; } module.exports = DrawingManager;
Add a lower layer to the drawing manager
Add a lower layer to the drawing manager
JavaScript
mit
Dermah/pulsar,Dermah/pulsar
--- +++ @@ -1,16 +1,29 @@ var p; var drawings = []; +var lowerLayer = []; var DrawingManager = function (p5Sketch) { p = p5Sketch; }; DrawingManager.prototype.add = function (drawing) { - console.log('Added ' + drawing); - drawings.unshift(drawing); + if (drawing.pulse.layer) { + lowerLayer.unshift(drawing); + } else { + console.log('Added ' + drawing); + drawings.unshift(drawing); + } } DrawingManager.prototype.drawAll = function () { + for (var i = lowerLayer.length - 1; i >= 0; i--) { + lowerLayer[i].draw(p); + + if (lowerLayer[i].done()) { + lowerLayer.splice(i, 1); + } + }; + for (var i = drawings.length - 1; i >= 0; i--) { drawings[i].draw(p);
ba54cae1371b15fda7037d930c9353ace6e3c342
lib/plugin/pluginRegistry.js
lib/plugin/pluginRegistry.js
"use strict"; const Registry = require('../util/registry'); /** * TODO: Could this be replaced with an InitRegistry? * @class * @memberOf Defiant.Plugin * @extends Defiant.util.Registry */ class PluginRegistry extends Registry { /** * @function * @param {Defiant.Plugin} obj The plugin to add to the registry. * @param {Defiant.Engine} engine The app engine. * @returns {Defiant.Plugin.PluginRegistry} The plugin registry. */ set(obj, engine) { // Initialize the plugin. return super.set(new obj(engine)); } } module.exports = PluginRegistry;
"use strict"; const Registry = require('../util/registry'); /** * TODO: Could this be replaced with an InitRegistry? * @class * @memberOf Defiant.Plugin * @extends Defiant.util.Registry */ class PluginRegistry extends Registry { /** * @function * @param {Defiant.Plugin} obj * The plugin to add to the registry. * @param {Defiant.Engine} engine * The app engine. * @returns {Defiant.Plugin.PluginRegistry} * The plugin registry. */ set(obj, engine) { // Initialize the plugin. return super.set(new obj(engine)); } } module.exports = PluginRegistry;
Standardize Jsdoc style for Defiant.Plugin.PluginRegistry
Doc: Standardize Jsdoc style for Defiant.Plugin.PluginRegistry
JavaScript
mit
coreyp1/defiant,coreyp1/defiant
--- +++ @@ -11,9 +11,12 @@ class PluginRegistry extends Registry { /** * @function - * @param {Defiant.Plugin} obj The plugin to add to the registry. - * @param {Defiant.Engine} engine The app engine. - * @returns {Defiant.Plugin.PluginRegistry} The plugin registry. + * @param {Defiant.Plugin} obj + * The plugin to add to the registry. + * @param {Defiant.Engine} engine + * The app engine. + * @returns {Defiant.Plugin.PluginRegistry} + * The plugin registry. */ set(obj, engine) { // Initialize the plugin.
099f3ab0f5271e6369eb1b45deade038427922dc
service/metrics.js
service/metrics.js
var Graphite = require('graphite'); var Measured = require('measured'); var reportInterval = 5000; var graphiteHost = process.env.GRAPHITE_HOST || null; var graphitePort = process.env.GRAPHITE_PORT || 2003; var envName = process.env.NODE_ENV || "unknown"; var processIdentifier = 'pid-' + process.pid; var timer = null; var graphite = null; var data = Measured.createCollection('origami.polyfill.' + envName + '.' + processIdentifier); if (graphiteHost) { graphite = Graphite.createClient('plaintext://'+graphiteHost+':'+graphitePort); timer = setInterval(function() { graphite.write(data.toJSON(), function(err) { if (err) { // Ignore timeouts if (err.code === 'ETIMEDOUT') return; console.error(err, err.stack); console.warn('Disabling graphite reporting due to error'); clearTimeout(timer); } }); }, reportInterval); timer.unref(); } module.exports = data;
var Graphite = require('graphite'); var Measured = require('measured'); var reportInterval = 5000; var graphiteHost = process.env.GRAPHITE_HOST || null; var graphitePort = process.env.GRAPHITE_PORT || 2003; var envName = process.env.NODE_ENV || "unknown"; var processIdentifier = 'pid-' + process.pid; var timer = null; var graphite = null; var data = Measured.createCollection('origami.polyfill.' + envName + '.' + processIdentifier); if (graphiteHost) { graphite = Graphite.createClient('plaintext://'+graphiteHost+':'+graphitePort); timer = setInterval(function() { graphite.write(data.toJSON(), function(err) { if (err) { // Ignore timeouts if (err.code === 'ETIMEDOUT') return; console.error(err, err.stack); console.warn('Disabling graphite reporting due to error'); clearInterval(timer); } }); }, reportInterval); timer.unref(); } module.exports = data;
Fix segfault caused by using incorrect clear method
Fix segfault caused by using incorrect clear method
JavaScript
mit
jonathan-fielding/polyfill-service,mcshaz/polyfill-service,jonathan-fielding/polyfill-service,kdzwinel/polyfill-service,mcshaz/polyfill-service,kdzwinel/polyfill-service,JakeChampion/polyfill-service,JakeChampion/polyfill-service,jonathan-fielding/polyfill-service,mcshaz/polyfill-service,kdzwinel/polyfill-service
--- +++ @@ -22,7 +22,7 @@ console.error(err, err.stack); console.warn('Disabling graphite reporting due to error'); - clearTimeout(timer); + clearInterval(timer); } }); }, reportInterval);
6a0aaf2fa2bd52aa77b01a463edf7c8347ae61a9
msisdn-gateway/utils.js
msisdn-gateway/utils.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; /** * Returns a random integer between min and max */ function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } /** * Build a digits code */ function digitsCode(size) { var s = size; var code = ""; while (s > 0) { s--; code += getRandomInt(0, 9); } return code; } module.exports = { digitsCode: digitsCode };
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; var crypto = require("crypto"); /** * Build a digits code */ function digitsCode(size) { var nbBytes = Math.ceil(size/2); return parseInt(crypto.randomBytes(nbBytes).toString("hex"), 16) .toString().substr(0, size); } module.exports = { digitsCode: digitsCode };
Refactor digitCode to use /dev/urandom instead of Math.random. r=Tarek
Refactor digitCode to use /dev/urandom instead of Math.random. r=Tarek
JavaScript
mpl-2.0
mozilla-services/msisdn-gateway,mozilla-services/msisdn-gateway,mozilla-services/msisdn-gateway
--- +++ @@ -4,24 +4,15 @@ "use strict"; -/** - * Returns a random integer between min and max - */ -function getRandomInt(min, max) { - return Math.floor(Math.random() * (max - min + 1)) + min; -} +var crypto = require("crypto"); /** * Build a digits code */ function digitsCode(size) { - var s = size; - var code = ""; - while (s > 0) { - s--; - code += getRandomInt(0, 9); - } - return code; + var nbBytes = Math.ceil(size/2); + return parseInt(crypto.randomBytes(nbBytes).toString("hex"), 16) + .toString().substr(0, size); } module.exports = {
1ab4424effd5f5ca1362e042d26d06911993511f
packages/landing-scripts/scripts/init.js
packages/landing-scripts/scripts/init.js
const fs = require('fs-extra'); const path = require('path'); const chalk = require('chalk'); function copyTemplate(appDir, templatePath) { fs.copySync(templatePath, appDir); fs.moveSync( path.join(appDir, 'gitignore'), path.join(appDir, '.gitignore'), ); } function addPackageScripts(appDir) { const scripts = { start: 'landing-scripts start', build: 'landing-scripts build', }; const packageJson = require(`${appDir}/package.json`); packageJson.scripts = scripts; fs.writeFileSync( path.join(appDir, 'package.json'), JSON.stringify(packageJson, null, 2), ); } function init(appDir, appName, templatePath) { const isUsingYarn = fs.existsSync(path.join(appDir, 'yarn.lock')); const command = isUsingYarn ? 'yarn' : 'npm'; copyTemplate(appDir, templatePath); addPackageScripts(appDir); console.log(chalk.green('Project ready!')); console.log(); console.log('To start the project typing:'); console.log(); console.log(chalk.cyan('cd'), appName); console.log(chalk.cyan(command), 'start'); } module.exports = init;
const fs = require('fs-extra'); const path = require('path'); const chalk = require('chalk'); function copyTemplate(appDir, templatePath) { fs.copySync(templatePath, appDir); fs.removeSync('.gitignore'); fs.moveSync( path.join(appDir, 'gitignore'), path.join(appDir, '.gitignore'), ); } function addPackageScripts(appDir) { const scripts = { start: 'landing-scripts start', build: 'landing-scripts build', }; const packageJson = require(`${appDir}/package.json`); packageJson.scripts = scripts; fs.writeFileSync( path.join(appDir, 'package.json'), JSON.stringify(packageJson, null, 2), ); } function init(appDir, appName, templatePath) { const isUsingYarn = fs.existsSync(path.join(appDir, 'yarn.lock')); const command = isUsingYarn ? 'yarn' : 'npm'; copyTemplate(appDir, templatePath); addPackageScripts(appDir); console.log(chalk.green('Project ready!')); console.log(); console.log('To start the project typing:'); console.log(); console.log(chalk.cyan('cd'), appName); console.log(chalk.cyan(command), 'start'); } module.exports = init;
Remove .gitignore on bootstrap the project
Remove .gitignore on bootstrap the project
JavaScript
mit
kevindantas/create-landing-page,kevindantas/create-landing-page,kevindantas/create-landing-page
--- +++ @@ -4,6 +4,7 @@ function copyTemplate(appDir, templatePath) { fs.copySync(templatePath, appDir); + fs.removeSync('.gitignore'); fs.moveSync( path.join(appDir, 'gitignore'), path.join(appDir, '.gitignore'),
d4c964e13fa20ff609d3b9c0b7d16d5d884cd8cc
database/recall.js
database/recall.js
'use strict'; module.exports = function (mongoose) { var recallSchema = mongoose.Schema({ Year: Number, Make: String, Model: String, Manufacturer: String, Component: String, Summary: String, Consequence: String, Remedy: String, Notes: String, NHTSACampaignNumber: String, ReportReceivedDate: String }); mongoose.model('Recall', recallSchema); };
'use strict'; module.exports = function (mongoose) { var recallSchema = mongoose.Schema({ Year: { type: Number, index: true }, Make: { type: String, index: true }, Model: { type: String, index: true }, Manufacturer: String, Component: String, Summary: String, Consequence: String, Remedy: String, Notes: String, NHTSACampaignNumber: String, ReportReceivedDate: String }); recallSchema.set('autoIndex', false); recallSchema.index({ Year: 1, Make: 1, Model: 1 }); mongoose.model('Recall', recallSchema); };
Add indexes to Recall schema
Add indexes to Recall schema * Sorting the data and attempting to access tail results would result in a buffer overrun error. Indexes were missing from the schema and have now been added.
JavaScript
mit
justinsa/maine-coone,justinsa/maine-coone
--- +++ @@ -2,9 +2,9 @@ module.exports = function (mongoose) { var recallSchema = mongoose.Schema({ - Year: Number, - Make: String, - Model: String, + Year: { type: Number, index: true }, + Make: { type: String, index: true }, + Model: { type: String, index: true }, Manufacturer: String, Component: String, Summary: String, @@ -14,5 +14,7 @@ NHTSACampaignNumber: String, ReportReceivedDate: String }); + recallSchema.set('autoIndex', false); + recallSchema.index({ Year: 1, Make: 1, Model: 1 }); mongoose.model('Recall', recallSchema); };
8ab0eab5c760dc26536e561e7f589709ef2160d1
library/CM/FormField/Text.js
library/CM/FormField/Text.js
/** * @class CM_FormField_Text * @extends CM_FormField_Abstract */ var CM_FormField_Text = CM_FormField_Abstract.extend({ _class: 'CM_FormField_Text', /** @type Boolean */ _skipTriggerChange: false, events: { 'blur input, textarea': function() { this.trigger('blur'); }, 'focus input, textarea': function() { this.trigger('focus'); } }, /** * @param {String} value */ setValue: function(value) { this._skipTriggerChange = true; this.$('input, textarea').val(value); this._skipTriggerChange = false; }, /** * @return {Boolean} */ hasFocus: function() { return this.getInput().is(':focus'); }, enableTriggerChange: function() { var self = this; var $input = this.getInput(); var valueLast = $input.val(); var callback = function() { var value = this.value; if (value != valueLast) { valueLast = value; if (!self._skipTriggerChange) { self.trigger('change'); } } }; // `propertychange` and `keyup` needed for IE9 $input.on('input propertychange keyup', callback); } });
/** * @class CM_FormField_Text * @extends CM_FormField_Abstract */ var CM_FormField_Text = CM_FormField_Abstract.extend({ _class: 'CM_FormField_Text', /** @type Boolean */ _skipTriggerChange: false, events: { 'blur input, textarea': function() { this.trigger('blur'); }, 'focus input, textarea': function() { this.trigger('focus'); }, 'change input, textarea': function() { this.triggerChange(); } }, /** * @param {String} value */ setValue: function(value) { this._skipTriggerChange = true; this.$('input, textarea').val(value); this._skipTriggerChange = false; }, /** * @return {Boolean} */ hasFocus: function() { return this.getInput().is(':focus'); }, triggerChange: function() { if (this._skipTriggerChange) { return; } this.trigger('change'); }, enableTriggerChangeOnInput: function() { var self = this; var $input = this.getInput(); var valueLast = $input.val(); var callback = function() { var value = this.value; if (value != valueLast) { valueLast = value; this.triggerChange(); } }; // `propertychange` and `keyup` needed for IE9 $input.on('input propertychange keyup', callback); } });
Introduce triggerChange, use it on input/textarea change
Introduce triggerChange, use it on input/textarea change
JavaScript
mit
njam/CM,fauvel/CM,zazabe/cm,fvovan/CM,tomaszdurka/CM,fauvel/CM,cargomedia/CM,vogdb/cm,tomaszdurka/CM,tomaszdurka/CM,vogdb/cm,mariansollmann/CM,cargomedia/CM,alexispeter/CM,alexispeter/CM,tomaszdurka/CM,mariansollmann/CM,vogdb/cm,cargomedia/CM,vogdb/cm,fauvel/CM,njam/CM,cargomedia/CM,alexispeter/CM,mariansollmann/CM,tomaszdurka/CM,alexispeter/CM,njam/CM,vogdb/cm,fvovan/CM,zazabe/cm,zazabe/cm,njam/CM,fvovan/CM,mariansollmann/CM,njam/CM,fauvel/CM,fauvel/CM,fvovan/CM,zazabe/cm
--- +++ @@ -14,6 +14,9 @@ }, 'focus input, textarea': function() { this.trigger('focus'); + }, + 'change input, textarea': function() { + this.triggerChange(); } }, @@ -33,7 +36,14 @@ return this.getInput().is(':focus'); }, - enableTriggerChange: function() { + triggerChange: function() { + if (this._skipTriggerChange) { + return; + } + this.trigger('change'); + }, + + enableTriggerChangeOnInput: function() { var self = this; var $input = this.getInput(); var valueLast = $input.val(); @@ -41,9 +51,7 @@ var value = this.value; if (value != valueLast) { valueLast = value; - if (!self._skipTriggerChange) { - self.trigger('change'); - } + this.triggerChange(); } }; // `propertychange` and `keyup` needed for IE9
7fb65123e15dbbcfd236d6a5bc4a5b51da19bb29
functions/chatwork/src/index.js
functions/chatwork/src/index.js
import template from './builder.js'; import kms from './kms.js'; import cw from './post.js'; import auth from './auth.js'; exports.handler = (event, context, callback) => { console.log('Received event:', JSON.stringify(event, null, 2)); // Encrypted Chatwork token const encCwtoken = process.env.CHATWORK_API_TOKEN || ''; // Chatwork Room ID from queryString const roomId = event.pathParameters.room_id || ''; // Payload from GitHub const payload = event.requestParameters; // GitHub Event Name const eventName = event.headers['X-GitHub-Event'] || event.headers['x-github-event'] || ''; // Original API token const token = event.queryParameters.token || ''; // API token key const tokenKey = process.env.API_TOKEN || ''; auth.verify(token, tokenKey).then(() => Promise.all([ kms.decrypt(encCwtoken), new Promise((resolve, reject) => { if (roomId != '') { resolve(roomId); } else { reject('roomId is blank.'); } }), template.build(eventName, payload), ])) .then(payload => cw.message( payload[0], // Raw Chatwork token payload[1], // Chatwork Room ID payload[2], // Chatwork message body )) .then((res) => { context.succeed(res); }) .catch((reason) => { console.log(reason); console.log('Not post to chatwork.'); context.fail(reason); }); };
import template from './builder'; import kms from './kms'; import cw from './post'; import auth from './auth'; exports.handler = (event, context, callback) => { console.log('Received event:', JSON.stringify(event, null, 2)); // Encrypted Chatwork token const encCwtoken = process.env.CHATWORK_API_TOKEN || ''; // Chatwork Room ID from queryString const roomId = event.pathParameters.room_id || ''; // Payload from GitHub const payload = event.requestParameters; // GitHub Event Name const eventName = event.headers['X-GitHub-Event'] || event.headers['x-github-event'] || ''; // Original API token const token = event.queryParameters.token || ''; // API token key const tokenKey = process.env.API_TOKEN || ''; auth.verify(token, tokenKey).then(() => Promise.all([ kms.decrypt(encCwtoken), new Promise((resolve, reject) => { if (roomId != '') { resolve(roomId); } else { reject('roomId is blank.'); } }), template.build(eventName, payload), ])) .then(payload => cw.message( payload[0], // Raw Chatwork token payload[1], // Chatwork Room ID payload[2], // Chatwork message body )) .then((res) => { context.succeed(res); }) .catch((reason) => { console.log(reason); console.log('Not post to chatwork.'); context.fail(reason); }); };
Remove file extension js from import
Remove file extension js from import
JavaScript
mit
Nate-River56/hub2chat,Nate-River56/hub2chat,Nate-River56/hub2chat
--- +++ @@ -1,7 +1,7 @@ -import template from './builder.js'; -import kms from './kms.js'; -import cw from './post.js'; -import auth from './auth.js'; +import template from './builder'; +import kms from './kms'; +import cw from './post'; +import auth from './auth'; exports.handler = (event, context, callback) => { console.log('Received event:', JSON.stringify(event, null, 2));
adc05976c2c7f97d46c214518d448b0b13e377d6
ui/app/utils/classes/rolling-array.js
ui/app/utils/classes/rolling-array.js
// An array with a max length. // // When max length is surpassed, items are removed from // the front of the array. // Using Classes to extend Array is unsupported in Babel so this less // ideal approach is taken: https://babeljs.io/docs/en/caveats#classes export default function RollingArray(maxLength, ...items) { const array = new Array(...items); array.maxLength = maxLength; // Capture the originals of each array method, but // associate them with the array to prevent closures. array._push = array.push; array._splice = array.splice; array._unshift = array.unshift; // All mutable array methods build on top of insertAt array._insertAt = array.insertAt; // Bring the length back down to maxLength by removing from the front array._limit = function() { const surplus = this.length - this.maxLength; if (surplus > 0) { this.splice(0, surplus); } }; array.push = function(...items) { this._push(...items); this._limit(); return this.length; }; array.splice = function(...args) { const returnValue = this._splice(...args); this._limit(); return returnValue; }; array.insertAt = function(...args) { const returnValue = this._insertAt(...args); this._limit(); this.arrayContentDidChange(); return returnValue; }; array.unshift = function() { throw new Error('Cannot unshift onto a RollingArray'); }; return array; }
// An array with a max length. // // When max length is surpassed, items are removed from // the front of the array. // Native array methods let { push, splice } = Array.prototype; // Ember array prototype extension let { insertAt } = Array.prototype; // Using Classes to extend Array is unsupported in Babel so this less // ideal approach is taken: https://babeljs.io/docs/en/caveats#classes export default function RollingArray(maxLength, ...items) { const array = new Array(...items); array.maxLength = maxLength; // Bring the length back down to maxLength by removing from the front array._limit = function() { const surplus = this.length - this.maxLength; if (surplus > 0) { this.splice(0, surplus); } }; array.push = function(...items) { push.apply(this, items); this._limit(); return this.length; }; array.splice = function(...args) { const returnValue = splice.apply(this, args); this._limit(); return returnValue; }; // All mutable array methods build on top of insertAt array.insertAt = function(...args) { const returnValue = insertAt.apply(this, args); this._limit(); this.arrayContentDidChange(); return returnValue; }; array.unshift = function() { throw new Error('Cannot unshift onto a RollingArray'); }; return array; }
Use the prototype instead of "private" property backups
Use the prototype instead of "private" property backups
JavaScript
mpl-2.0
dvusboy/nomad,dvusboy/nomad,hashicorp/nomad,hashicorp/nomad,hashicorp/nomad,dvusboy/nomad,burdandrei/nomad,nak3/nomad,burdandrei/nomad,burdandrei/nomad,nak3/nomad,dvusboy/nomad,dvusboy/nomad,nak3/nomad,hashicorp/nomad,dvusboy/nomad,burdandrei/nomad,nak3/nomad,nak3/nomad,burdandrei/nomad,hashicorp/nomad,nak3/nomad,burdandrei/nomad,hashicorp/nomad,nak3/nomad,dvusboy/nomad,burdandrei/nomad
--- +++ @@ -2,21 +2,18 @@ // // When max length is surpassed, items are removed from // the front of the array. + +// Native array methods +let { push, splice } = Array.prototype; + +// Ember array prototype extension +let { insertAt } = Array.prototype; // Using Classes to extend Array is unsupported in Babel so this less // ideal approach is taken: https://babeljs.io/docs/en/caveats#classes export default function RollingArray(maxLength, ...items) { const array = new Array(...items); array.maxLength = maxLength; - - // Capture the originals of each array method, but - // associate them with the array to prevent closures. - array._push = array.push; - array._splice = array.splice; - array._unshift = array.unshift; - - // All mutable array methods build on top of insertAt - array._insertAt = array.insertAt; // Bring the length back down to maxLength by removing from the front array._limit = function() { @@ -27,19 +24,20 @@ }; array.push = function(...items) { - this._push(...items); + push.apply(this, items); this._limit(); return this.length; }; array.splice = function(...args) { - const returnValue = this._splice(...args); + const returnValue = splice.apply(this, args); this._limit(); return returnValue; }; + // All mutable array methods build on top of insertAt array.insertAt = function(...args) { - const returnValue = this._insertAt(...args); + const returnValue = insertAt.apply(this, args); this._limit(); this.arrayContentDidChange(); return returnValue;
ea95e486f37ad049ca2431ca10b3550c19ca222c
ui/src/admin/components/UsersTable.js
ui/src/admin/components/UsersTable.js
import React, {PropTypes} from 'react' const UsersTable = ({users}) => ( <div className="panel panel-minimal"> <div className="panel-body"> <table className="table v-center"> <thead> <tr> <th>User</th> <th>Roles</th> <th>Permissions</th> </tr> </thead> <tbody> { users.length ? users.map((user) => ( <tr key={user.name}> <td>{user.name}</td> <td>{user.roles.map((r) => r.name).join(', ')}</td> <td>{user.permissions.map((p) => p.scope).join(', ')}</td> </tr> )) : (() => ( <tr className="table-empty-state"> <th colSpan="5"> <p>You don&#39;t have any Users,<br/>why not create one?</p> </th> </tr> ))() } </tbody> </table> </div> </div> ) const { arrayOf, shape, string, } = PropTypes UsersTable.propTypes = { users: arrayOf(shape({ name: string.isRequired, roles: arrayOf(shape({ name: string, })), permissions: arrayOf(shape({ name: string, scope: string.isRequired, })), })), } export default UsersTable
import React, {PropTypes} from 'react' const UsersTable = ({users}) => ( <div className="panel panel-minimal"> <div className="panel-body"> <table className="table v-center"> <thead> <tr> <th>User</th> <th>Roles</th> <th>Permissions</th> </tr> </thead> <tbody> { users.length ? users.map((user) => ( <tr key={user.name}> <td>{user.name}</td> <td>{users.roles && user.roles.map((r) => r.name).join(', ')}</td> <td>{user.permissions.map((p) => p.scope).join(', ')}</td> </tr> )) : (() => ( <tr className="table-empty-state"> <th colSpan="5"> <p>You don&#39;t have any Users,<br/>why not create one?</p> </th> </tr> ))() } </tbody> </table> </div> </div> ) const { arrayOf, shape, string, } = PropTypes UsersTable.propTypes = { users: arrayOf(shape({ name: string.isRequired, roles: arrayOf(shape({ name: string, })), permissions: arrayOf(shape({ name: string, scope: string.isRequired, })), })), } export default UsersTable
Handle no roles on users table
Handle no roles on users table
JavaScript
mit
nooproblem/influxdb,nooproblem/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,influxdb/influxdb,influxdata/influxdb,influxdb/influxdb
--- +++ @@ -16,7 +16,7 @@ users.length ? users.map((user) => ( <tr key={user.name}> <td>{user.name}</td> - <td>{user.roles.map((r) => r.name).join(', ')}</td> + <td>{users.roles && user.roles.map((r) => r.name).join(', ')}</td> <td>{user.permissions.map((p) => p.scope).join(', ')}</td> </tr> )) : (() => (
1ddb89ef8b4d2304a991e3a09e08693b8b84c5e8
src/Oro/Bundle/DataGridBundle/Resources/public/js/datagrid/cell/number-cell.js
src/Oro/Bundle/DataGridBundle/Resources/public/js/datagrid/cell/number-cell.js
define([ 'underscore', 'backgrid', 'orodatagrid/js/datagrid/formatter/number-formatter' ], function(_, Backgrid, NumberFormatter) { 'use strict'; var NumberCell; /** * Number column cell. * * @export oro/datagrid/cell/number-cell * @class oro.datagrid.cell.NumberCell * @extends Backgrid.NumberCell */ NumberCell = Backgrid.NumberCell.extend({ /** @property {orodatagrid.datagrid.formatter.NumberFormatter} */ formatterPrototype: NumberFormatter, /** @property {String} */ style: 'decimal', /** * @inheritDoc */ initialize: function(options) { _.extend(this, options); NumberCell.__super__.initialize.apply(this, arguments); this.formatter = this.createFormatter(); }, /** * Creates number cell formatter * * @return {orodatagrid.datagrid.formatter.NumberFormatter} */ createFormatter: function() { return new this.formatterPrototype({style: this.style}); } }); return NumberCell; });
define([ 'underscore', 'backgrid', 'orodatagrid/js/datagrid/formatter/number-formatter' ], function(_, Backgrid, NumberFormatter) { 'use strict'; var NumberCell; /** * Number column cell. * * @export oro/datagrid/cell/number-cell * @class oro.datagrid.cell.NumberCell * @extends Backgrid.NumberCell */ NumberCell = Backgrid.NumberCell.extend({ /** @property {orodatagrid.datagrid.formatter.NumberFormatter} */ formatterPrototype: NumberFormatter, /** @property {String} */ style: 'decimal', /** * @inheritDoc */ initialize: function(options) { _.extend(this, options); NumberCell.__super__.initialize.apply(this, arguments); this.formatter = this.createFormatter(); }, /** * Creates number cell formatter * * @return {orodatagrid.datagrid.formatter.NumberFormatter} */ createFormatter: function() { return new this.formatterPrototype({style: this.style}); }, /** * @inheritDoc */ render: function() { var render = NumberCell.__super__.render.apply(this, arguments); this.enterEditMode(); return render; }, /** * @inheritDoc */ enterEditMode: function() { if (this.column.get('editable')) { NumberCell.__super__.enterEditMode.apply(this, arguments); } }, /** * @inheritDoc */ exitEditMode: function() { if (!this.column.get('editable')) { NumberCell.__super__.exitEditMode.apply(this, arguments); } } }); return NumberCell; });
Add a grid to popup - added possibility to render number cell as an editable field
COM-212: Add a grid to popup - added possibility to render number cell as an editable field
JavaScript
mit
orocrm/platform,ramunasd/platform,ramunasd/platform,trustify/oroplatform,orocrm/platform,ramunasd/platform,Djamy/platform,trustify/oroplatform,geoffroycochard/platform,orocrm/platform,Djamy/platform,geoffroycochard/platform,geoffroycochard/platform,trustify/oroplatform,Djamy/platform
--- +++ @@ -37,6 +37,35 @@ */ createFormatter: function() { return new this.formatterPrototype({style: this.style}); + }, + + /** + * @inheritDoc + */ + render: function() { + var render = NumberCell.__super__.render.apply(this, arguments); + + this.enterEditMode(); + + return render; + }, + + /** + * @inheritDoc + */ + enterEditMode: function() { + if (this.column.get('editable')) { + NumberCell.__super__.enterEditMode.apply(this, arguments); + } + }, + + /** + * @inheritDoc + */ + exitEditMode: function() { + if (!this.column.get('editable')) { + NumberCell.__super__.exitEditMode.apply(this, arguments); + } } });
0dadb60ecd51ab01d4c804d5c741c795a6ca7b47
app/js/app.js
app/js/app.js
define(function (require) { 'use strict'; var store = require('store'); var items = new Vue({ el: 'body', data: { items: [], domains: store.fetch(), domain: '' }, ready: function () { var timer, that = this; this.$watch('domains', function (domains) { store.save(domains); }); this.$watch('domain', function (value) { that.items = []; for (var i = 0; i < that.domains.length && value; i++) { if (that.domains[i].name.indexOf(value) === 0) { that.items.push(that.domains[i]); } } }); }, methods: { onRemove: function (item) { this.domains.$remove(item.$data); this.domain = ''; }, onHandle: function (e) { var data, value = this.domain.trim(); if (e.keyCode === 13) { this.domains.push({ name: value, active: true }); this.domain = ''; } if (e.keyCode === 27) { this.domain = value = ''; } }, domainFilter: function (self) { return self.name.indexOf(this.domain) === 0; } } }); });
define(function (require) { 'use strict'; var store = require('store'); var items = new Vue({ el: 'body', data: { items: [], domains: store.fetch(), domain: '' }, ready: function () { var timer, that = this; this.$watch('domains', function (domains) { store.save(domains); }); this.$watch('domain', function (value) { that.items = []; for (var i = 0; i < that.domains.length && value; i++) { if (that.domains[i].name.indexOf(value) === 0) { that.items.push(that.domains[i]); } } }); }, methods: { onRemove: function (item) { this.domains.$remove(item.$data); this.domain = ''; }, onHandle: function (e) { var data, value = this.domain.trim(); function parse(input) { var regex = /((?:https?:\/\/)?(?:[^\.]*\.)*?)([^\.]*\.\w+)(\/.*)?$/; return input.replace(regex, function (match, p1, p2, p3) { p1 = p1 || ''; p2 = p2 || ''; p3 = p3 || ''; return p1 + p2.bold() + p3; }); } if (e.keyCode === 13) { this.domains.push({ name: value, active: true }); this.domain = ''; } else if (e.keyCode === 27) { this.domain = value = ''; } else { //this.domain = parse(value); } }, domainFilter: function (self) { return self.name.indexOf(this.domain) === 0; } } }); });
Add domain detect and show bold font of domain
Add domain detect and show bold font of domain
JavaScript
mit
Witcher42/PacManagerVue
--- +++ @@ -41,16 +41,27 @@ var data, value = this.domain.trim(); + function parse(input) { + var regex = /((?:https?:\/\/)?(?:[^\.]*\.)*?)([^\.]*\.\w+)(\/.*)?$/; + + return input.replace(regex, function (match, p1, p2, p3) { + p1 = p1 || ''; + p2 = p2 || ''; + p3 = p3 || ''; + return p1 + p2.bold() + p3; + }); + } + if (e.keyCode === 13) { this.domains.push({ name: value, active: true }); this.domain = ''; - } - - if (e.keyCode === 27) { + } else if (e.keyCode === 27) { this.domain = value = ''; + } else { + //this.domain = parse(value); } },
1154dffa3aa8a714d183d9048fe9381dfdb0a28d
app/server.js
app/server.js
var jadeStream = require('jade-stream') var http = require('http') var st = require('st') var mount = st({ path: 'app/assets', index: 'index.jade' }) var app = http.createServer(function server(req, res) { if (req.url === '/') res.filter = jadeStream() mount(req, res) }) app.listen(process.env.port, function listening() { var info = app.address() console.log('App running on http://%s:%s', info.address, info.port) })
var jadeStream = require('jade-stream') var config = require('rc')('bc-webplayer'); var http = require('http') var st = require('st') var mount = st({ path: 'app/assets', index: 'index.jade', cache: config.cache }) var app = http.createServer(function server(req, res) { if (req.url === '/') res.filter = jadeStream() mount(req, res) }) app.listen(process.env.port, function listening() { var info = app.address() console.log('App running on http://%s:%s', info.address, info.port) })
Add project settings via rc
Add project settings via rc
JavaScript
mit
joshgillies/bc-webplayer
--- +++ @@ -1,10 +1,12 @@ var jadeStream = require('jade-stream') +var config = require('rc')('bc-webplayer'); var http = require('http') var st = require('st') var mount = st({ path: 'app/assets', - index: 'index.jade' + index: 'index.jade', + cache: config.cache }) var app = http.createServer(function server(req, res) {
a33395797ecfc8dfbdad9cc6de5a41c2fd2783fc
webpack.config.js
webpack.config.js
const webpack = require("webpack"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); const ZipPlugin = require("zip-webpack-plugin"); const path = require("path"); const package = require("./package"); const widgetName = package.name; const widgetNameContext = widgetName + "Context"; const widgetVersion = package.version; module.exports = { entry: { [widgetName]: [ "core-js/es/promise", `./src/${widgetName}/widget/${widgetName}.js` ], [widgetNameContext]: [ "core-js/es/promise", `./src/${widgetName}/widget/${widgetNameContext}.js` ], }, output: { path: path.resolve(__dirname, "dist/tmp/src"), filename: `${widgetName}/widget/[name].js`, chunkFilename: `${widgetName}/widget/${widgetName}[id].js`, libraryTarget: "amd", publicPath: "widgets/" }, devtool: false, mode: "production", externals: [ /^mxui\/|^mendix\/|^dojo\/|^dijit\// ], plugins: [ new webpack.LoaderOptionsPlugin({ debug: true }), new CleanWebpackPlugin({ cleanOnceBeforeBuildPatterns: "dist/tmp" }), new CopyWebpackPlugin([ {context: "src", from: "**/*.xml", debug: true} ], { copyUnmodified: true }), new ZipPlugin({ path: `../../${widgetVersion}`, filename: widgetName, extension: "mpk" }) ] };
const webpack = require("webpack"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); const ZipPlugin = require("zip-webpack-plugin"); const path = require("path"); const package = require("./package"); const widgetName = package.name; const widgetNameContext = widgetName + "Context"; const widgetVersion = package.version; module.exports = { entry: { [widgetName]: [ "core-js/es/promise", `./src/${widgetName}/widget/${widgetName}.js` ], [widgetNameContext]: [ "core-js/es/promise", `./src/${widgetName}/widget/${widgetNameContext}.js` ], }, output: { path: path.resolve(__dirname, "dist/tmp/src"), filename: `${widgetName}/widget/[name].js`, chunkFilename: `${widgetName}/widget/${widgetName}[id].js`, libraryTarget: "amd", publicPath: "/widgets/" }, devtool: false, mode: "production", externals: [ /^mxui\/|^mendix\/|^dojo\/|^dijit\// ], plugins: [ new webpack.LoaderOptionsPlugin({ debug: true }), new CleanWebpackPlugin({ cleanOnceBeforeBuildPatterns: "dist/tmp" }), new CopyWebpackPlugin([ {context: "src", from: "**/*.xml", debug: true} ], { copyUnmodified: true }), new ZipPlugin({ path: `../../${widgetVersion}`, filename: widgetName, extension: "mpk" }) ] };
Fix widgets path when using pages that have an ID (e.g. //host/p/Page)
Fix widgets path when using pages that have an ID (e.g. //host/p/Page)
JavaScript
apache-2.0
mendix/HTMLSnippet,mendix/HTMLSnippet,mendix/HTMLSnippet
--- +++ @@ -19,7 +19,7 @@ filename: `${widgetName}/widget/[name].js`, chunkFilename: `${widgetName}/widget/${widgetName}[id].js`, libraryTarget: "amd", - publicPath: "widgets/" + publicPath: "/widgets/" }, devtool: false, mode: "production",
4f48bc9b0c2f475639be917d08cd2583e670ed25
webpack.config.js
webpack.config.js
const webpack = require('webpack'); module.exports = { entry: './src/index.js', output: { filename: './dist/html2canvas.js', library: 'html2canvas' }, module: { loaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }] }, plugins: [ new webpack.DefinePlugin({ '__DEV__': true }) ] };
const webpack = require('webpack'); module.exports = { entry: './src/index.js', output: { filename: './dist/html2canvas.js', library: 'html2canvas', libraryTarget: 'umd' }, module: { loaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }] }, plugins: [ new webpack.DefinePlugin({ '__DEV__': true }) ] };
Define browser build target as umd
Define browser build target as umd
JavaScript
mit
niklasvh/html2canvas,niklasvh/html2canvas,niklasvh/html2canvas
--- +++ @@ -4,7 +4,8 @@ entry: './src/index.js', output: { filename: './dist/html2canvas.js', - library: 'html2canvas' + library: 'html2canvas', + libraryTarget: 'umd' }, module: { loaders: [{
2a58db089a6cf0edc394fe8a036bb51f1a246f94
webpack.config.js
webpack.config.js
var path = require("path") var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') module.exports = { context: __dirname, entry: './webapp/assets/js/index', // entry point of our app. assets/js/index.js should require other js modules and dependencies it needs output: { path: path.resolve('./webapp/assets/bundles/'), filename: "[name]-[hash].js", }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}), ], module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', query: { presets:['react', 'es2015', 'stage-2'] } }, // to transform JSX into JS ], }, resolve: { modulesDirectories: ['node_modules', 'bower_components'], extensions: ['', '.js', '.jsx'] }, watchOptions: { poll: 1000, aggregateTimeout: 1000 }, }
var path = require("path") var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') module.exports = { context: __dirname, entry: './webapp/assets/js/index', // entry point of our app. assets/js/index.js should require other js modules and dependencies it needs output: { path: path.resolve('./webapp/assets/bundles/'), filename: "[name]-[hash].js", }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}), ], module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets:['react', 'es2015', 'stage-2'] } }, // to transform JSX into JS ], }, resolve: { modulesDirectories: ['node_modules', 'bower_components'], extensions: ['', '.js', '.jsx'] }, watchOptions: { poll: 1000, aggregateTimeout: 1000 }, }
Use babel loader instead of babel to production
Use babel loader instead of babel to production
JavaScript
mit
Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_platform
--- +++ @@ -21,7 +21,7 @@ { test: /\.jsx?$/, exclude: /node_modules/, - loader: 'babel', + loader: 'babel-loader', query: { presets:['react', 'es2015', 'stage-2']
f73e07d291144ccc167491c8fbebb466f172e71c
webpack.config.js
webpack.config.js
const config = { entry: './src/index.js' }; module.exports = config;
const path = require('path'); // We can use whatever nodejs package const config = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'build'), //./build filename: 'bundle.js' } }; module.exports = config;
Set name and path of the output file
Set name and path of the output file
JavaScript
mit
debiasej/webpack2-learning,debiasej/webpack2-learning
--- +++ @@ -1,5 +1,11 @@ +const path = require('path'); // We can use whatever nodejs package + const config = { - entry: './src/index.js' + entry: './src/index.js', + output: { + path: path.resolve(__dirname, 'build'), //./build + filename: 'bundle.js' + } }; module.exports = config;
dcd07488f11a0ce089b396b95d880d704f43a985
routes/index.js
routes/index.js
var express = require('express'); var router = express.Router(); var GameModel = require('../models/game'); var model = require('../models'); const _ = require('underscore'); /* GET home page. */ router.get('/', function(req, res, next) { let gameParam = { order: [ ['id', 'desc'] ], include: [ { model: model.Guide, attributes: [ [model.sequelize.fn('COUNT', 'Guide.id'), 'Count'] ] } ], limit: 5 }; let guideParam = { order: [ ['id', 'desc'] ], include: [ { model: model.Game, attributes: ['name', 'url'] }, { model: model.User, attributes: ['name'] } ], limit: 5 }; Promise .all([model.Game.findAll(gameParam), model.Guide.findAll(guideParam)]) .then(values => { let [games, guides] = values; console.info(guides[0]); games = games.map(g => { return _.extend({ guideCount: g.Guides.length > 0 ? g.Guides[0].dataValues.Count : 0 }, g.dataValues); }); res.render('home', { games: games, guides: guides }); }).catch(err => next(err)); }); router.get('/tag/:tag', function(req, res, next) { res.render('index', { title: 'tag' }); }); module.exports = router;
var express = require('express'); var router = express.Router(); var GameModel = require('../models/game'); var model = require('../models'); const _ = require('underscore'); /* GET home page. */ router.get('/', function(req, res, next) { let gameParam = { order: [ ['id', 'desc'] ], include: [ { model: model.Guide, attributes: [ [model.sequelize.fn('COUNT', 'Guide.id'), 'Count'] ] } ], limit: 5 }; let guideParam = { order: [ ['id', 'desc'] ], include: [ { model: model.Game, attributes: ['name', 'url'] }, { model: model.User, attributes: ['name'] } ], limit: 5 }; Promise .all([model.Game.findAll(gameParam), model.Guide.findAll(guideParam)]) .then(values => { let [games, guides] = values; games = games .filter(game => game.id) .map(g => { return _.extend({ guideCount: g.Guides.length > 0 ? g.Guides[0].dataValues.Count : 0 }, g.dataValues); }); res.render('home', { games: games, guides: guides }); }).catch(err => next(err)); }); router.get('/tag/:tag', function(req, res, next) { res.render('index', { title: 'tag' }); }); module.exports = router;
Fix home page. When there are no game, it still show a random entry.
Fix home page. When there are no game, it still show a random entry.
JavaScript
mit
JixunMoe/GameGuide.Node,JixunMoe/GameGuide.Node,JixunMoe/GameGuide.Node,JixunMoe/GameGuide.Node
--- +++ @@ -42,12 +42,15 @@ .all([model.Game.findAll(gameParam), model.Guide.findAll(guideParam)]) .then(values => { let [games, guides] = values; - console.info(guides[0]); - games = games.map(g => { - return _.extend({ - guideCount: g.Guides.length > 0 ? g.Guides[0].dataValues.Count : 0 - }, g.dataValues); - }); + + games = games + .filter(game => game.id) + .map(g => { + return _.extend({ + guideCount: g.Guides.length > 0 ? g.Guides[0].dataValues.Count : 0 + }, g.dataValues); + }); + res.render('home', { games: games, guides: guides
8a370e11dc746ee9d354c21c80ab5fb70722326f
client/components/App.js
client/components/App.js
import React, { PropTypes, Component } from 'react'; import { connect } from 'react-redux'; import actions from '../actions/index.js'; import '../scss/app.scss'; import Nav from './Nav.js'; import Profile from './Profile.js'; import RecipeContainer from './RecipeContainer.js'; class App extends Component { render() { const { profile, recipesOwned, recipesFollowed } = this.props; return ( <div> <Nav /> <Profile profile={profile} /> <h1>Dashboard</h1> <RecipeContainer className="recipes-owned" type="My Owned Recipes" recipes={recipesOwned} /> <RecipeContainer className="recipes-followed" type="My Followed Recipes" recipes={recipesFollowed} /> </div> ); } } const mapStateToProps = function (state) { return { profile: state.profile, recipesOwned: state.recipesOwned, recipesFollowed: state.recipesFollowed, }; }; // const mapDispatchToProps = function (dispatch) { // return { // // fill in any actions here // }; // }; App.propTypes = { recipesOwned: PropTypes.array.isRequired, recipesFollowed: PropTypes.array.isRequired, profile: PropTypes.shape({ avatar: PropTypes.string, username: PropTypes.string, }).isRequired, }; export default connect( mapStateToProps // mapDispatchToProps, )(App);
import React, { PropTypes, Component } from 'react'; import { connect } from 'react-redux'; import actions from '../actions/index.js'; // import '../scss/app.scss'; import Nav from './Nav.js'; import Profile from './Profile.js'; import RecipeContainer from './RecipeContainer.js'; class App extends Component { render() { const { profile, recipesOwned, recipesFollowed } = this.props; return ( <div> <Nav /> <Profile profile={profile} /> <h1>Dashboard</h1> <RecipeContainer className="recipes-owned" type="My Owned Recipes" recipes={recipesOwned} /> <RecipeContainer className="recipes-followed" type="My Followed Recipes" recipes={recipesFollowed} /> </div> ); } } const mapStateToProps = function (state) { return { profile: state.profile, recipesOwned: state.recipesOwned, recipesFollowed: state.recipesFollowed, }; }; // const mapDispatchToProps = function (dispatch) { // return { // // fill in any actions here // }; // }; App.propTypes = { recipesOwned: PropTypes.array.isRequired, recipesFollowed: PropTypes.array.isRequired, profile: PropTypes.shape({ avatar: PropTypes.string, username: PropTypes.string, }).isRequired, }; export default connect( mapStateToProps // mapDispatchToProps, )(App);
Comment out reference to app.scss file
Comment out reference to app.scss file
JavaScript
mit
forkful/forkful,rompingstalactite/rompingstalactite,rompingstalactite/rompingstalactite,forkful/forkful,rompingstalactite/rompingstalactite,forkful/forkful
--- +++ @@ -1,7 +1,7 @@ import React, { PropTypes, Component } from 'react'; import { connect } from 'react-redux'; import actions from '../actions/index.js'; -import '../scss/app.scss'; +// import '../scss/app.scss'; import Nav from './Nav.js'; import Profile from './Profile.js';
e95c90357117c63142d591190b1a74f323e5f108
routes/index.js
routes/index.js
var express = require('express'); var router = express.Router(); var moment = require('moment'); var languageColors = require('../language_colors'); // GET home page languageColors.get(function (languages, updated) { // HTML router.get('/', function(req, res) { res.render('index', { languages: languages, updated: moment(updated).fromNow() }); }); // JSON router.get('/index.json', function(req, res) { res.json(languages); }); }); module.exports = router;
var express = require('express'); var router = express.Router(); var moment = require('moment'); var languageColors = require('../language_colors'); // GET home page languageColors.get(function (languages, updated) { // HTML router.get('/', function(req, res) { res.render('index', { languages: languages, updated: moment(updated).fromNow() }); }); // JSON router.get('/index.json', function(req, res) { res.json({ languages: languages, updated: updated }); }); }); module.exports = router;
Update the API and add the updated time
Update the API and add the updated time
JavaScript
mit
nicolasmccurdy/language-colors,nicolasmccurdy/language-colors
--- +++ @@ -15,7 +15,10 @@ // JSON router.get('/index.json', function(req, res) { - res.json(languages); + res.json({ + languages: languages, + updated: updated + }); }); });
29195eaefde2949134c608771ddfed3fa22677a5
routes/users.js
routes/users.js
const express = require('express'), router = express.Router(), db = require('../models'); router.get('/', function(req, res, next) { res.render('index'); }); router.get('/new', function(req, res, next) { res.render('users/new'); }); router.get('/:username', function(req, res, next) { // db.User.find({username: req.params.username}).then(function(user) { // res.render('users/show', {user}); // }); var user = req.params.username; res.render('users/show', {user}); }); router.get('/:username/edit', function(req, res, next) { db.User.find({username: req.params.username}).then(function(user) { res.render('users/edit', {user}); }); }); router.post('/', function(req, res, next) { db.User.create(req.body).then(function() { res.redirect('/'); }); }); // find not by ID and update router.patch('/:username', function(req, res, next) { db.User.findByIdAndUpdate(req.params.username, req.body.newUsername).then(function() { res.redirect('/:username'); }); }); // find and then remove router.delete('/:username', function(req, res, next) { db.User.findByIdAndRemove(req.params.username).then(function() { res.redirect('/'); }); }); module.exports = router;
const express = require('express'), router = express.Router(), db = require('../models'); router.get('/', function(req, res, next) { res.render('index'); }); router.get('/new', function(req, res, next) { res.render('users/new'); }); router.get('/:username', function(req, res, next) { db.User.find({username: req.params.username}).then(function(user) { res.render('users/show', {user}); }); }); router.get('/:username/edit', function(req, res, next) { db.User.find({username: req.params.username}).then(function(user) { res.render('users/edit', {user}); }); }); router.post('/', function(req, res, next) { db.User.create(req.body).then(function() { res.redirect('/'); }); }); // find not by ID and update router.patch('/:username', function(req, res, next) { db.User.findByIdAndUpdate(req.params.username, req.body.newUsername).then(function() { res.redirect('/:username'); }); }); // find and then remove router.delete('/:username', function(req, res, next) { db.User.findByIdAndRemove(req.params.username).then(function() { res.redirect('/'); }); }); module.exports = router;
Use Mongoose to find user and pass to show page
Use Mongoose to find user and pass to show page
JavaScript
mit
tymeart/mojibox,tymeart/mojibox
--- +++ @@ -11,11 +11,9 @@ }); router.get('/:username', function(req, res, next) { - // db.User.find({username: req.params.username}).then(function(user) { - // res.render('users/show', {user}); - // }); - var user = req.params.username; - res.render('users/show', {user}); + db.User.find({username: req.params.username}).then(function(user) { + res.render('users/show', {user}); + }); }); router.get('/:username/edit', function(req, res, next) {
77452232e9080665355f86082b28fae1a31ee8e4
src/directives/ng-viewport.js
src/directives/ng-viewport.js
ngGridDirectives.directive('ngViewport', [function() { return function($scope, elm) { var isMouseWheelActive; var prevScollLeft; var prevScollTop = 0; elm.bind('scroll', function(evt) { var scrollLeft = evt.target.scrollLeft, scrollTop = evt.target.scrollTop; if ($scope.$headerContainer) { $scope.$headerContainer.scrollLeft(scrollLeft); } $scope.adjustScrollLeft(scrollLeft); $scope.adjustScrollTop(scrollTop); if (!$scope.$root.$$phase) { $scope.$digest(); } prevScollLeft = scrollLeft; prevScollTop = scrollTop; isMouseWheelActive = false; return true; }); elm.bind("mousewheel DOMMouseScroll", function() { isMouseWheelActive = true; if (elm.focus) { elm.focus(); } return true; }); if (!$scope.enableCellSelection) { $scope.domAccessProvider.selectionHandlers($scope, elm); } }; }]);
ngGridDirectives.directive('ngViewport', [function() { return function($scope, elm) { var isMouseWheelActive; var prevScollLeft; var prevScollTop = 0; var ensureDigest = function() { if (!$scope.$root.$$phase) { $scope.$digest(); } }; elm.bind('scroll', function(evt) { var scrollLeft = evt.target.scrollLeft, scrollTop = evt.target.scrollTop; if ($scope.$headerContainer) { $scope.$headerContainer.scrollLeft(scrollLeft); } $scope.adjustScrollLeft(scrollLeft); $scope.adjustScrollTop(scrollTop); ensureDigest(); prevScollLeft = scrollLeft; prevScollTop = scrollTop; isMouseWheelActive = false; return true; }); elm.bind("mousewheel DOMMouseScroll", function() { isMouseWheelActive = true; if (elm.focus) { elm.focus(); } return true; }); if (!$scope.enableCellSelection) { $scope.domAccessProvider.selectionHandlers($scope, elm); } }; }]);
Refactor out function to call digest only when safe
Refactor out function to call digest only when safe
JavaScript
mit
FernCreek/ng-grid,ppossanzini/ui-grid,PeopleNet/ng-grid-fork,FugleMonkey/ng-grid,rightscale/ng-grid,rightscale/ng-grid,FernCreek/ng-grid,angular-ui/ng-grid-legacy,FernCreek/ng-grid,FugleMonkey/ng-grid,PeopleNet/ng-grid-fork,ppossanzini/ui-grid,FugleMonkey/ng-grid,angular-ui/ng-grid-legacy,angular-ui/ng-grid-legacy,ppossanzini/ui-grid
--- +++ @@ -3,6 +3,11 @@ var isMouseWheelActive; var prevScollLeft; var prevScollTop = 0; + var ensureDigest = function() { + if (!$scope.$root.$$phase) { + $scope.$digest(); + } + }; elm.bind('scroll', function(evt) { var scrollLeft = evt.target.scrollLeft, scrollTop = evt.target.scrollTop; @@ -11,9 +16,7 @@ } $scope.adjustScrollLeft(scrollLeft); $scope.adjustScrollTop(scrollTop); - if (!$scope.$root.$$phase) { - $scope.$digest(); - } + ensureDigest(); prevScollLeft = scrollLeft; prevScollTop = scrollTop; isMouseWheelActive = false;
f2539fed876794f065fe096c3816f49103cb1766
src/MenuOptions.js
src/MenuOptions.js
import React from 'react'; import { View } from 'react-native'; const MenuOptions = ({ style, children, onSelect, customStyles }) => ( <View style={[customStyles.optionsWrapper, style]}> { React.Children.map(children, c => React.isValidElement(c) ? React.cloneElement(c, { onSelect: c.props.onSelect || onSelect, customStyles: Object.keys(c.props.customStyles || {}).length ? c.props.customStyles : customStyles }) : c ) } </View> ); MenuOptions.propTypes = { onSelect: React.PropTypes.func, customStyles: React.PropTypes.object, renderOptionsContainer: React.PropTypes.func, optionsContainerStyle: React.PropTypes.oneOfType([ React.PropTypes.object, React.PropTypes.number, ]), }; MenuOptions.defaultProps = { customStyles: {}, }; export default MenuOptions;
import React, { PropTypes } from 'react'; import { View } from 'react-native'; const MenuOptions = ({ style, children, onSelect, customStyles }) => ( <View style={[customStyles.optionsWrapper, style]}> { React.Children.map(children, c => React.isValidElement(c) ? React.cloneElement(c, { onSelect: c.props.onSelect || onSelect, customStyles: Object.keys(c.props.customStyles || {}).length ? c.props.customStyles : customStyles }) : c ) } </View> ); MenuOptions.propTypes = { onSelect: PropTypes.func, customStyles: PropTypes.object, renderOptionsContainer: PropTypes.func, optionsContainerStyle: PropTypes.oneOfType([ PropTypes.object, PropTypes.number, PropTypes.array, ]), }; MenuOptions.defaultProps = { customStyles: {}, }; export default MenuOptions;
Allow also array as style prop type
Allow also array as style prop type
JavaScript
isc
instea/react-native-popup-menu
--- +++ @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { PropTypes } from 'react'; import { View } from 'react-native'; const MenuOptions = ({ style, children, onSelect, customStyles }) => ( @@ -16,12 +16,13 @@ ); MenuOptions.propTypes = { - onSelect: React.PropTypes.func, - customStyles: React.PropTypes.object, - renderOptionsContainer: React.PropTypes.func, - optionsContainerStyle: React.PropTypes.oneOfType([ - React.PropTypes.object, - React.PropTypes.number, + onSelect: PropTypes.func, + customStyles: PropTypes.object, + renderOptionsContainer: PropTypes.func, + optionsContainerStyle: PropTypes.oneOfType([ + PropTypes.object, + PropTypes.number, + PropTypes.array, ]), };
46d8ccf455fa6455520d87b4ac397c9b976b8c78
edwin/client/static/js/components/TeamList.js
edwin/client/static/js/components/TeamList.js
import React from 'react'; import Router from 'react-router'; import ControllerComponent from '../utils/ControllerComponent'; import * as edwinAPI from '../utils/edwinAPI'; import TeamStore from '../stores/TeamStore'; const {Link} = Router; /** * Shows a list of teams. * @class */ export default class TeamList extends ControllerComponent { get stores() { return [TeamStore]; } getNewState() { return { teams: TeamStore.getAll(), }; } /** * On mounting, fetch data from APIs. */ componentDidMount() { super.componentDidMount(); edwinAPI.getTeams(); } render() { return ( <div className="Welcome"> <h1>Teams</h1> <ul> {this.state.teams.map((team) => ( <li key={`team-${team.slug}`}> <Link to="timeline" params={{team: team.get('slug')}}> {team.get('name')} </Link> </li> ))} </ul> </div> ); } }
import React from 'react'; import Router from 'react-router'; import ControllerComponent from '../utils/ControllerComponent'; import * as edwinAPI from '../utils/edwinAPI'; import TeamStore from '../stores/TeamStore'; const {Link} = Router; /** * Shows a list of teams. * @class */ export default class TeamList extends ControllerComponent { get stores() { return [TeamStore]; } getNewState() { return { teams: TeamStore.getAll(), }; } /** * On mounting, fetch data from APIs. */ componentDidMount() { super.componentDidMount(); edwinAPI.getTeams(); } render() { return ( <div className="Welcome"> <h1>Teams</h1> <ul> {this.state.teams.map((team) => ( <li key={`team-${team.get('slug')}`}> <Link to="timeline" params={{team: team.get('slug')}}> {team.get('name')} </Link> </li> ))} </ul> </div> ); } }
Use Immutable-style .get instead of JS style property access on Team list page.
Use Immutable-style .get instead of JS style property access on Team list page. Fixes #35.
JavaScript
mpl-2.0
mythmon/edwin,mythmon/edwin,mythmon/edwin,mythmon/edwin
--- +++ @@ -36,7 +36,7 @@ <h1>Teams</h1> <ul> {this.state.teams.map((team) => ( - <li key={`team-${team.slug}`}> + <li key={`team-${team.get('slug')}`}> <Link to="timeline" params={{team: team.get('slug')}}> {team.get('name')} </Link>
fece5a97acbf07c6d405c5a8bd9f40de60fa5c29
src/kit/ui/StringComponent.js
src/kit/ui/StringComponent.js
import { Component } from 'substance' import TextInput from './TextInput' export default class StringComponent extends Component { render ($$) { let placeholder = this.props.placeholder let model = this.props.model let path = model.getPath() let name = path.join('.') let el = $$('div').addClass(this.getClassNames()) el.append( $$(TextInput, { name, path, placeholder }).ref('input') ) return el } getClassNames () { return 'sc-string' } }
import { Component } from 'substance' import TextInput from './TextInput' export default class StringComponent extends Component { render ($$) { let placeholder = this.props.placeholder let model = this.props.model let path = model.getPath() let name = path.join('.') let el = $$('div').addClass(this.getClassNames()) if (this.props.readOnly) { let doc = this.context.api.getDocument() let TextPropertyComponent = this.getComponent('text-property') el.append( $$(TextPropertyComponent, { doc, tagName: 'div', placeholder, path }).ref('display') ) } else { el.append( $$(TextInput, { name, path, placeholder }).ref('input') ) } return el } getClassNames () { return 'sc-string' } }
Allow to render text or string read-only.
Allow to render text or string read-only.
JavaScript
mit
substance/texture,substance/texture
--- +++ @@ -8,13 +8,26 @@ let path = model.getPath() let name = path.join('.') let el = $$('div').addClass(this.getClassNames()) - el.append( - $$(TextInput, { - name, - path, - placeholder - }).ref('input') - ) + if (this.props.readOnly) { + let doc = this.context.api.getDocument() + let TextPropertyComponent = this.getComponent('text-property') + el.append( + $$(TextPropertyComponent, { + doc, + tagName: 'div', + placeholder, + path + }).ref('display') + ) + } else { + el.append( + $$(TextInput, { + name, + path, + placeholder + }).ref('input') + ) + } return el }
1c19dbe6c8b8b462f86f3d901203e77ef5486cbd
lib/createHeader.js
lib/createHeader.js
var Immutable = require('immutable'); var Draft = require('draft-js'); var TYPES = require('./TYPES'); var createRow = require('./createRow'); /** * Create a new table header * * @param {String} tableKey * @param {Number} countColumns * @return {OrderedMap<String:Draft.ContentBlock>} */ function createHeader(tableKey, countColumns) { var tableHeaderKey = Draft.genNestedKey(tableKey); var tableHeaderBlock = new Draft.ContentBlock({ key: tableHeaderKey, type: TYPES.HEADER }); return Immutable.OrderedMap([ [tableHeaderKey, tableHeaderBlock] ]) .merge( createRow(tableHeaderKey, countColumns) ); } module.exports = createHeader;
var Immutable = require('immutable'); var Draft = require('draft-js'); var TYPES = require('./TYPES'); var createRow = require('./createRow'); /** * Create a new table header * * @param {String} tableKey * @param {Number} countColumns * @return {OrderedMap<String:Draft.ContentBlock>} */ function createHeader(tableKey, countColumns) { var tableHeaderKey = Draft.genNestedKey(tableKey); var tableHeaderBlock = new Draft.ContentBlock({ key: tableHeaderKey, type: TYPES.HEADER, data: Immutable.Map({ align: Array .apply(null, Array(10)) .map(function(){ return TYPES.LEFT; }) }) }); return Immutable.OrderedMap([ [tableHeaderKey, tableHeaderBlock] ]) .merge( createRow(tableHeaderKey, countColumns) ); } module.exports = createHeader;
Create align data when creating table
Create align data when creating table
JavaScript
apache-2.0
SamyPesse/draft-js-table,SamyPesse/draft-js-table
--- +++ @@ -14,8 +14,13 @@ function createHeader(tableKey, countColumns) { var tableHeaderKey = Draft.genNestedKey(tableKey); var tableHeaderBlock = new Draft.ContentBlock({ - key: tableHeaderKey, - type: TYPES.HEADER + key: tableHeaderKey, + type: TYPES.HEADER, + data: Immutable.Map({ + align: Array + .apply(null, Array(10)) + .map(function(){ return TYPES.LEFT; }) + }) }); return Immutable.OrderedMap([
a58013389178b6254eed66983b3d6bac5a2c4ae0
lib/diff-pane-item-component.js
lib/diff-pane-item-component.js
/* @flow */ /** @jsx etch.dom */ import etch from 'etch' // $FlowBug: Yes, we know this isn't a React component :\ import DiffComponent from './diff-component' import type DiffViewModel from './diff-view-model' type DiffPaneItemComponentProps = {diffViewModel: DiffViewModel} export default class DiffPaneItemComponent { diffViewModel: DiffViewModel; element: HTMLElement; refs: {diffComponent: HTMLElement}; constructor (props: DiffPaneItemComponentProps) { this.acceptProps(props) } acceptProps ({diffViewModel}: DiffPaneItemComponentProps): Promise<void> { this.diffViewModel = diffViewModel let updatePromise = Promise.resolve() if (this.element) { updatePromise = etch.update(this) } else { etch.initialize(this) } this.element.addEventListener('focus', () => this.refs.diffComponent.focus()) return updatePromise } update (props: DiffPaneItemComponentProps, children: Array<any>): Promise<void> { return this.acceptProps(props) } render () { return ( <div className='pane-item' tabIndex='-1'>{ <DiffComponent ref='diffComponent' diffViewModel={this.diffViewModel}/> }</div> ) } }
/* @flow */ /** @jsx etch.dom */ import etch from 'etch' import {Disposable, CompositeDisposable} from 'atom' // $FlowBug: Yes, we know this isn't a React component :\ import DiffComponent from './diff-component' import type DiffViewModel from './diff-view-model' type DiffPaneItemComponentProps = {diffViewModel: DiffViewModel} export default class DiffPaneItemComponent { diffViewModel: DiffViewModel; element: HTMLElement; refs: {diffComponent: HTMLElement}; subscriptions: CompositeDisposable; constructor (props: DiffPaneItemComponentProps) { this.subscriptions = new CompositeDisposable() this.acceptProps(props) const onFocus = () => this.refs.diffComponent.focus() this.element.addEventListener('focus', onFocus) this.subscriptions.add(new Disposable(() => this.element.removeEventListener('focus', onFocus))) } acceptProps ({diffViewModel}: DiffPaneItemComponentProps): Promise<void> { this.diffViewModel = diffViewModel let updatePromise = Promise.resolve() if (this.element) { updatePromise = etch.update(this) } else { etch.initialize(this) } return updatePromise } update (props: DiffPaneItemComponentProps, children: Array<any>): Promise<void> { return this.acceptProps(props) } render () { return ( <div className='pane-item' tabIndex='-1'>{ <DiffComponent ref='diffComponent' diffViewModel={this.diffViewModel}/> }</div> ) } destroy (): Promise<void> { this.subscriptions.dispose() return etch.destroy(this) } }
Clean up the focus handler.
Clean up the focus handler.
JavaScript
mit
atom/github,atom/github,atom/github
--- +++ @@ -2,6 +2,7 @@ /** @jsx etch.dom */ import etch from 'etch' +import {Disposable, CompositeDisposable} from 'atom' // $FlowBug: Yes, we know this isn't a React component :\ import DiffComponent from './diff-component' @@ -13,9 +14,16 @@ diffViewModel: DiffViewModel; element: HTMLElement; refs: {diffComponent: HTMLElement}; + subscriptions: CompositeDisposable; constructor (props: DiffPaneItemComponentProps) { + this.subscriptions = new CompositeDisposable() + this.acceptProps(props) + + const onFocus = () => this.refs.diffComponent.focus() + this.element.addEventListener('focus', onFocus) + this.subscriptions.add(new Disposable(() => this.element.removeEventListener('focus', onFocus))) } acceptProps ({diffViewModel}: DiffPaneItemComponentProps): Promise<void> { @@ -27,8 +35,6 @@ } else { etch.initialize(this) } - - this.element.addEventListener('focus', () => this.refs.diffComponent.focus()) return updatePromise } @@ -44,4 +50,10 @@ }</div> ) } + + destroy (): Promise<void> { + this.subscriptions.dispose() + + return etch.destroy(this) + } }
4340850c7b2803002c747f425ef7c3da8bca8fdd
.template-lintrc.js
.template-lintrc.js
/* eslint-env node */ 'use strict'; var defaultAllowedBaseStrings = ['(', ')', ',', '.', '&', '+', '-', '=', '*', '/', '#', '%', '!', '?', ':', '[', ']', '{', '}', '<', '>', '•', '—', ' ', '|']; module.exports = { extends: 'recommended', rules: { 'bare-strings': ['?', '»', '&mdash;'].concat(defaultAllowedBaseStrings), 'block-indentation': true, 'html-comments': true, 'nested-interactive': true, 'self-closing-void-elements': true, 'img-alt-attributes': false, 'link-rel-noopener': true, 'invalid-interactive': false, 'inline-link-to': true, 'style-concatenation': true, 'triple-curlies': false, 'deprecated-each-syntax': true, 'deprecated-inline-view-helper': false, } };
/* eslint-env node */ 'use strict'; var defaultAllowedBaseStrings = ['(', ')', ',', '.', '&', '+', '-', '=', '*', '/', '#', '%', '!', '?', ':', '[', ']', '{', '}', '<', '>', '•', '—', ' ', '|']; module.exports = { extends: 'recommended', rules: { 'bare-strings': ['?', '»', '&mdash;'].concat(defaultAllowedBaseStrings), 'block-indentation': true, 'html-comments': true, 'nested-interactive': true, 'self-closing-void-elements': true, 'img-alt-attributes': false, 'invalid-interactive': false, 'inline-link-to': true, 'triple-curlies': false, 'deprecated-each-syntax': true, 'deprecated-inline-view-helper': false, } };
Remove rules which are now enabled by default
Remove rules which are now enabled by default These template lint rules are now enabled in the 'recommended' configuration so we don't need to override them in our config.
JavaScript
mit
jrjohnson/frontend,ilios/frontend,thecoolestguy/frontend,dartajax/frontend,djvoa12/frontend,dartajax/frontend,djvoa12/frontend,gabycampagna/frontend,jrjohnson/frontend,ilios/frontend,gabycampagna/frontend,thecoolestguy/frontend,gboushey/frontend,gboushey/frontend
--- +++ @@ -12,10 +12,8 @@ 'nested-interactive': true, 'self-closing-void-elements': true, 'img-alt-attributes': false, - 'link-rel-noopener': true, 'invalid-interactive': false, 'inline-link-to': true, - 'style-concatenation': true, 'triple-curlies': false, 'deprecated-each-syntax': true, 'deprecated-inline-view-helper': false,