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 |
|---|---|---|---|---|---|---|---|---|---|---|
58dd0255dc16aea48eedc2bee64da922a9e8d394 | src/server/action/Executor.js | src/server/action/Executor.js | import ExecutorBase from '../../action/Executor';
import types from '../../action/types';
export default class Executor extends ExecutorBase {
_onAttack(action, world) {
}
} | import ExecutorBase from '../../action/Executor';
export default class Executor extends ExecutorBase {
}
| Remove empty code to prevent jslint errors | Remove empty code to prevent jslint errors
| JavaScript | mit | DirtyHairy/mayrogue-deathmatch,DirtyHairy/mayrogue-deathmatch | ---
+++
@@ -1,10 +1,5 @@
import ExecutorBase from '../../action/Executor';
-import types from '../../action/types';
export default class Executor extends ExecutorBase {
- _onAttack(action, world) {
-
- }
-
} |
571376913b7b8c9d8ea329c6865cd8869c954b25 | karma.conf.js | karma.conf.js | // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client:{
clearContext: false, // leave Jasmine Spec Runner output visible in browser
jasmine: {
random: false
}
},
coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
| // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client:{
clearContext: false, // leave Jasmine Spec Runner output visible in browser
jasmine: {
random: false
}
},
coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
browserNoActivityTimeout: 30000
});
};
| Increase browser inactivity timeout for test runs. | Increase browser inactivity timeout for test runs.
| JavaScript | mpl-2.0 | thehyve/glowing-bear,thehyve/glowing-bear,thehyve/glowing-bear,thehyve/glowing-bear | ---
+++
@@ -31,6 +31,7 @@
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
- singleRun: false
+ singleRun: false,
+ browserNoActivityTimeout: 30000
});
}; |
7be59a49cb351dcfa4874c885ba017277027849b | karma.conf.js | karma.conf.js | /* eslint-env node */
module.exports = function (config) {
config.set({
basePath: 'public',
browsers: ['ChromeHeadlessCustom'],
files: [
'styles/index.css',
'scripts/mithril.min.js',
'scripts/underscore-min.js',
'scripts/tinyemitter.min.js',
'scripts/sw-update-manager.js',
'scripts/socket.io.slim.js',
'scripts/clipboard.min.js',
'scripts/test.js'
],
reporters: ['dots'].concat(process.env.COVERAGE ? ['coverage'] : []),
frameworks: ['mocha', 'chai-dom', 'sinon-chai'],
preprocessors: {
'**/*.js': ['sourcemap'],
'scripts/test.js': process.env.COVERAGE ? ['coverage'] : []
},
coverageReporter: {
type: 'json',
dir: '../coverage/',
subdir: '.',
file: 'coverage-unmapped.json'
},
customLaunchers: {
ChromeHeadlessCustom: {
base: 'ChromeHeadless',
flags: ['--no-sandbox']
}
}
});
};
| /* eslint-env node */
module.exports = function (config) {
config.set({
basePath: 'public',
browsers: ['ChromeHeadlessCustom'],
files: [
'styles/index.css',
'scripts/mithril.min.js',
'scripts/underscore-min.js',
'scripts/tinyemitter.min.js',
'scripts/sw-update-manager.js',
'scripts/socket.io.min.js',
'scripts/clipboard.min.js',
'scripts/test.js'
],
reporters: ['dots'].concat(process.env.COVERAGE ? ['coverage'] : []),
frameworks: ['mocha', 'chai-dom', 'sinon-chai'],
preprocessors: {
'**/*.js': ['sourcemap'],
'scripts/test.js': process.env.COVERAGE ? ['coverage'] : []
},
coverageReporter: {
type: 'json',
dir: '../coverage/',
subdir: '.',
file: 'coverage-unmapped.json'
},
customLaunchers: {
ChromeHeadlessCustom: {
base: 'ChromeHeadless',
flags: ['--no-sandbox']
}
}
});
};
| Correct SocketIO path for Karma tests | Correct SocketIO path for Karma tests
The tests should no longer be erroring out.
| JavaScript | mit | caleb531/connect-four | ---
+++
@@ -10,7 +10,7 @@
'scripts/underscore-min.js',
'scripts/tinyemitter.min.js',
'scripts/sw-update-manager.js',
- 'scripts/socket.io.slim.js',
+ 'scripts/socket.io.min.js',
'scripts/clipboard.min.js',
'scripts/test.js'
], |
050359c7399b9e8905d114a2438fa7e374da9811 | tests/collect.test.js | tests/collect.test.js | 'use strict';
(function () {
var expect = require('chai').expect;
var collect = require('../src/collect');
describe('collect.js', function () {
it('should exist', function () {
expect(collect).to.be.ok;
expect(typeof collect).to.equal('function');
});
});
})();
| 'use strict';
(function () {
var expect = require('chai').expect;
var collect = require('../src/collect');
var Jarg = require('../src/jarg');
var Command = require('../src/command');
describe('collect.js', function () {
it('should exist', function () {
expect(collect).to.be.ok;
expect(typeof collect).to.equal('function');
});
it('should return a Jarg instance', function () {
var boundCollect = collect.bind(null, 'node', 'npm', ['install', 'jargs', '--save']);
var result = boundCollect(
Command(
'npm'
)
);
expect(result instanceof Jarg).to.be.true;
});
});
})();
| Test that collect returns a Jarg instance | Test that collect returns a Jarg instance
| JavaScript | mit | JakeSidSmith/jargs | ---
+++
@@ -5,6 +5,8 @@
var expect = require('chai').expect;
var collect = require('../src/collect');
+ var Jarg = require('../src/jarg');
+ var Command = require('../src/command');
describe('collect.js', function () {
@@ -13,6 +15,18 @@
expect(typeof collect).to.equal('function');
});
+ it('should return a Jarg instance', function () {
+ var boundCollect = collect.bind(null, 'node', 'npm', ['install', 'jargs', '--save']);
+
+ var result = boundCollect(
+ Command(
+ 'npm'
+ )
+ );
+
+ expect(result instanceof Jarg).to.be.true;
+ });
+
});
})(); |
ebdaf4dd46279ee1650fd4fc1a5128f0c404ee79 | tests/compile/main.js | tests/compile/main.js | goog.provide('Main');
// Core
// Either require 'Blockly.requires', or just the components you use:
goog.require('Blockly');
goog.require('Blockly.FieldDropdown');
goog.require('Blockly.FieldImage');
goog.require('Blockly.FieldNumber');
goog.require('Blockly.FieldTextInput');
goog.require('Blockly.FieldVariable');
goog.require('Blockly.geras.Renderer');
// Blocks
goog.require('Blockly.Constants.Logic');
goog.require('Blockly.Constants.Loops');
goog.require('Blockly.Constants.Math');
goog.require('Blockly.Constants.Text');
goog.require('Blockly.Constants.Lists');
goog.require('Blockly.Constants.Colour');
goog.require('Blockly.Constants.Variables');
goog.require('Blockly.Constants.VariablesDynamic');
goog.require('Blockly.Blocks.procedures');
Main.init = function() {
Blockly.inject('blocklyDiv', {
'toolbox': document.getElementById('toolbox')
});
};
window.addEventListener('load', Main.init);
| goog.provide('Main');
// Core
// Either require 'Blockly.requires', or just the components you use:
goog.require('Blockly');
goog.require('Blockly.geras.Renderer');
// Blocks
goog.require('Blockly.Constants.Logic');
goog.require('Blockly.Constants.Loops');
goog.require('Blockly.Constants.Math');
goog.require('Blockly.Constants.Text');
goog.require('Blockly.Constants.Lists');
goog.require('Blockly.Constants.Colour');
goog.require('Blockly.Constants.Variables');
goog.require('Blockly.Constants.VariablesDynamic');
goog.require('Blockly.Blocks.procedures');
Main.init = function() {
Blockly.inject('blocklyDiv', {
'toolbox': document.getElementById('toolbox')
});
};
window.addEventListener('load', Main.init);
| Remove now unneeded requires from compile test. | Remove now unneeded requires from compile test.
| JavaScript | apache-2.0 | mark-friedman/blockly,picklesrus/blockly,google/blockly,picklesrus/blockly,mark-friedman/blockly,mark-friedman/blockly,google/blockly,mark-friedman/blockly,mark-friedman/blockly,mark-friedman/blockly,google/blockly,rachel-fenichel/blockly,rachel-fenichel/blockly,google/blockly,rachel-fenichel/blockly,google/blockly,rachel-fenichel/blockly,google/blockly,google/blockly,rachel-fenichel/blockly,picklesrus/blockly,rachel-fenichel/blockly,rachel-fenichel/blockly | ---
+++
@@ -2,11 +2,6 @@
// Core
// Either require 'Blockly.requires', or just the components you use:
goog.require('Blockly');
-goog.require('Blockly.FieldDropdown');
-goog.require('Blockly.FieldImage');
-goog.require('Blockly.FieldNumber');
-goog.require('Blockly.FieldTextInput');
-goog.require('Blockly.FieldVariable');
goog.require('Blockly.geras.Renderer');
// Blocks
goog.require('Blockly.Constants.Logic'); |
3c21402775b39586d62cc137f4832c3397192aac | public/javascripts/documents.js | public/javascripts/documents.js | $(document).ready(function(){
var i=0;
var $td;
var state;
function checkDocumentsStatuses(){
$.getJSON("/api/documents_states", function(data){
var $bars = $(".bar");
for(i=0;i<$bars.length;i++){
$($bars[i]).css("width", data[i] + "%");
}
});
setTimeout(checkDocumentsStatuses, 15000 );
}
$(".link a").popover();
$(".link a").click(function(event){
event.preventDefault();
var $this = $(this);
$.get($this.attr("href"),
null,
function(data){
$this.parent().siblings(".content").html(data.p);
},
'json');
});
$("#stillProcessing").alert().css("display", "block");
setTimeout(checkDocumentsStatuses, 15000 );
if($(".tablesorter").length !== 0) {
$(".tablesorter").tablesorter();
}
$(".documents tbody tr").click(function() {
$(this).siblings().removeClass("selected");
$(this).addClass("selected");
var url = "/api/" + $(this).data("id") + "/context";
var template = $("#documentContext").html();
$("#document").html("").spin();
$.getJSON(url, null, function(data) {
$("#document").html(Mustache.render(template, data));
}).error(function() {
$("#document").html(Mustache.render($("#documentContextError").html()));
});
return false;
});
});
| $(document).ready(function(){
var i=0;
var $td;
var state;
function checkDocumentsStatuses(){
$.getJSON("/api/documents_states", function(data){
var $bars = $(".bar");
for(i=0;i<$bars.length;i++){
$($bars[i]).css("width", data[i] + "%");
}
});
setTimeout(checkDocumentsStatuses, 15000 );
}
$(".link a").popover();
$(".link a").click(function(event){
event.preventDefault();
var $this = $(this);
$.get($this.attr("href"),
null,
function(data){
$this.parent().siblings(".content").html(data.p);
},
'json');
});
$("#stillProcessing").alert().css("display", "block");
setTimeout(checkDocumentsStatuses, 15000 );
if($(".tablesorter").length !== 0) {
$(".tablesorter").tablesorter();
}
$(".documents tbody tr").click(function(e) {
$(this).siblings().removeClass("selected");
$(this).addClass("selected");
var url = "/api/" + $(this).data("id") + "/context";
var template = $("#documentContext").html();
$("#document").html("").spin();
$.getJSON(url, null, function(data) {
$("#document").html(Mustache.render(template, data));
}).error(function() {
$("#document").html(Mustache.render($("#documentContextError").html()));
});
});
$(".documents .tools a").click(function(e) {
e.stopPropagation();
});
});
| Stop event bubbling when clicking on document toolbar | Stop event bubbling when clicking on document toolbar
| JavaScript | mit | analiceme/chaos | ---
+++
@@ -30,7 +30,7 @@
if($(".tablesorter").length !== 0) {
$(".tablesorter").tablesorter();
}
- $(".documents tbody tr").click(function() {
+ $(".documents tbody tr").click(function(e) {
$(this).siblings().removeClass("selected");
$(this).addClass("selected");
var url = "/api/" + $(this).data("id") + "/context";
@@ -41,7 +41,8 @@
}).error(function() {
$("#document").html(Mustache.render($("#documentContextError").html()));
});
- return false;
+ });
+ $(".documents .tools a").click(function(e) {
+ e.stopPropagation();
});
});
- |
b6988ddfadcc5636fcdfff772715cd5199954f04 | tasks/lib/sigint-hook.js | tasks/lib/sigint-hook.js | var sigintHooked = false;
module.exports = function sigintHook( fn ) {
if ( sigintHooked ) {
return;
}
sigintHooked = true;
// ctrl+c should stop this task and quit grunt gracefully
// (process.on("SIGINT", fn) doesn't behave correctly on Windows):
var rl = require( "readline" ).createInterface( {
input: process.stdin,
output: process.stdout
} );
rl.on( "SIGINT", function() {
fn();
rl.close();
} );
}; | var sigintHooked = false;
module.exports = function sigintHook( fn ) {
if ( sigintHooked ) {
return;
}
sigintHooked = true;
// ctrl+c should stop this task and quit grunt gracefully
// (process.on("SIGINT", fn) doesn't behave correctly on Windows):
var rl = require( "readline" ).createInterface( {
input: process.stdin,
output: process.stdout
} );
rl.on( "SIGINT", function() {
fn();
rl.close();
sigintHooked = false;
} );
}; | Reset sigint hook when readline closes. | Reset sigint hook when readline closes.
| JavaScript | mit | peol/grunt-surveil | ---
+++
@@ -14,5 +14,6 @@
rl.on( "SIGINT", function() {
fn();
rl.close();
+ sigintHooked = false;
} );
}; |
6eb0da204f11a2396f1f663675c0e5406554ca9b | declarative-shadow-dom.js | declarative-shadow-dom.js | customElements.define('declarative-shadow-dom', class extends HTMLTemplateElement {
static get observedAttributes() {
return [];
}
constructor(self) {
// assignment required by polyfill
self = super(self);
}
connectedCallback(){
this.appendToParentsShadowRoot();
}
appendToParentsShadowRoot(){
const parentElement = this.parentElement;
if(!parentElement){
throw 'declarative-shadow-dom needs a perentElement to stamp to';
}
if(!parentElement.shadowRoot){
parentElement.attachShadow({mode: 'open'});
}
let fragment = document.importNode(this.content, true);
this.stampedNodes = Array.prototype.slice.call(fragment.childNodes);
parentElement.shadowRoot.appendChild(fragment);
// debugger
ShadyCSS && ShadyCSS.styleElement(parentElement);
parentElement.dispatchEvent(new CustomEvent('declarative-shadow-dom-stamped', {detail: {stampedNodes: this.stampedNodes}}));
this.parentNode.removeChild(this);
}
}, {
extends: 'template'
});
| customElements.define('declarative-shadow-dom', class extends HTMLTemplateElement {
static get observedAttributes() {
return [];
}
constructor(self) {
// assignment required by polyfill
self = super(self);
}
connectedCallback(){
this.appendToParentsShadowRoot();
}
appendToParentsShadowRoot(){
const parentElement = this.parentElement;
if(!parentElement){
throw 'declarative-shadow-dom needs a perentElement to stamp to';
}
if(!parentElement.shadowRoot){
parentElement.attachShadow({mode: 'open'});
}
let fragment = document.importNode(this.content, true);
this.stampedNodes = Array.prototype.slice.call(fragment.childNodes);
parentElement.shadowRoot.appendChild(fragment);
// debugger
typeof ShadyCSS !== 'undefined' && ShadyCSS.styleElement(parentElement);
parentElement.dispatchEvent(new CustomEvent('declarative-shadow-dom-stamped', {detail: {stampedNodes: this.stampedNodes}}));
this.parentNode.removeChild(this);
}
}, {
extends: 'template'
});
| Fix check for ShadyCSS polyfill | Fix check for ShadyCSS polyfill
| JavaScript | mit | tomalec/declarative-shadow-dom,tomalec/declarative-shadow-dom | ---
+++
@@ -22,7 +22,7 @@
this.stampedNodes = Array.prototype.slice.call(fragment.childNodes);
parentElement.shadowRoot.appendChild(fragment);
// debugger
- ShadyCSS && ShadyCSS.styleElement(parentElement);
+ typeof ShadyCSS !== 'undefined' && ShadyCSS.styleElement(parentElement);
parentElement.dispatchEvent(new CustomEvent('declarative-shadow-dom-stamped', {detail: {stampedNodes: this.stampedNodes}}));
this.parentNode.removeChild(this);
} |
bd77652a50eb0feab274d65ed45a127ddf2402c7 | src/components/chat/AddChatMessage.js | src/components/chat/AddChatMessage.js | import React from 'react'
import PropTypes from 'prop-types'
/* Component with a state */
export default class AddChatMessage extends React.Component {
constructor(props) {
super(props)
this.state = {message: ''}
}
onChangeMessage = (e) => {
this.setState({message: e.target.value})
}
onSendCick = () => {
this.props.onClick({message: this.state.message})
this.setState({message:''})
}
handleKeyPress = (e) => {
if (e.key === 'Enter'){
e.preventDefault()
this.onSendCick()
return false
}
}
render() {
return (
<div>
<textarea onChange={this.onChangeMessage} onKeyPress={this.handleKeyPress} value={this.state.message}/>
<button onClick={this.onSendCick}>Send</button>
</div>
)
}
}
AddChatMessage.propTypes = {
onClick: PropTypes.func
} | import React from 'react'
import PropTypes from 'prop-types'
/* Component with a state */
export default class AddChatMessage extends React.Component {
constructor(props) {
super(props)
this.state = {message: ''}
}
onChangeMessage = (e) => {
this.setState({message: e.target.value})
}
onSendCick = () => {
this.props.onClick({message: this.state.message})
this.setState({message:''})
this.textInput.focus()
}
handleKeyPress = (e) => {
if (e.key === 'Enter'){
e.preventDefault()
this.onSendCick()
return false
}
}
render() {
return (
<div>
<textarea ref={(e) => { this.textInput = e }} onChange={this.onChangeMessage} onKeyPress={this.handleKeyPress} value={this.state.message}/>
<button onClick={this.onSendCick}>Send</button>
</div>
)
}
}
AddChatMessage.propTypes = {
onClick: PropTypes.func
} | Set focus back to textarea after button was pressed | Set focus back to textarea after button was pressed
| JavaScript | mit | axax/lunuc,axax/lunuc,axax/lunuc | ---
+++
@@ -14,6 +14,7 @@
onSendCick = () => {
this.props.onClick({message: this.state.message})
this.setState({message:''})
+ this.textInput.focus()
}
handleKeyPress = (e) => {
@@ -27,7 +28,7 @@
render() {
return (
<div>
- <textarea onChange={this.onChangeMessage} onKeyPress={this.handleKeyPress} value={this.state.message}/>
+ <textarea ref={(e) => { this.textInput = e }} onChange={this.onChangeMessage} onKeyPress={this.handleKeyPress} value={this.state.message}/>
<button onClick={this.onSendCick}>Send</button>
</div>
) |
594ece2b5001d39a2cd255c2a25829a1291cb75f | test/compare-versions.js | test/compare-versions.js | import test from 'ava';
import fn from '../source/libs/compare-versions';
test('Compare versions', t => {
t.is(-1, fn('1', '2'));
t.is(-1, fn('v1', '2'));
t.is(-1, fn('1.1', '1.2'));
t.is(-1, fn('1', '1.1'));
t.is(-1, fn('1', '1.0.1'));
t.is(-1, fn('2.0', '10.0'));
t.is(-1, fn('1.2.3', '1.22.3'));
t.is(-1, fn('1.1.1.1.1', '1.1.1.1.2'));
t.is(-1, fn('r1', 'r2'));
t.is(-1, fn('1.0-beta', '1.0'));
t.is(-1, fn('v0.11-M4', 'v0.20'));
});
| import test from 'ava';
import fn from '../source/libs/compare-versions';
test('Compare versions', t => {
t.is(-1, fn('1', '2'));
t.is(-1, fn('v1', '2'));
t.is(-1, fn('1.1', '1.2'));
t.is(-1, fn('1', '1.1'));
t.is(-1, fn('1', '1.0.1'));
t.is(-1, fn('2.0', '10.0'));
t.is(-1, fn('1.2.3', '1.22.3'));
t.is(-1, fn('1.1.1.1.1', '1.1.1.1.2'));
t.is(-1, fn('r1', 'r2'));
});
test.failing('Support beta versions', t => {
t.is(-1, fn('1.0-beta', '1.0'));
t.is(-1, fn('v2.0-RC4', 'v2.0'));
});
| Add failing beta version test | Add failing beta version test
| JavaScript | mit | busches/refined-github,busches/refined-github,sindresorhus/refined-github,sindresorhus/refined-github | ---
+++
@@ -11,6 +11,9 @@
t.is(-1, fn('1.2.3', '1.22.3'));
t.is(-1, fn('1.1.1.1.1', '1.1.1.1.2'));
t.is(-1, fn('r1', 'r2'));
+});
+
+test.failing('Support beta versions', t => {
t.is(-1, fn('1.0-beta', '1.0'));
- t.is(-1, fn('v0.11-M4', 'v0.20'));
+ t.is(-1, fn('v2.0-RC4', 'v2.0'));
}); |
ee8ab3561b9722c327bac0b1ea082ab510156977 | test/mithril.withAttr.js | test/mithril.withAttr.js | describe("m.withAttr()", function () {
"use strict"
it("calls the handler with the right value/context without callbackThis", function () { // eslint-disable-line
var spy = sinon.spy()
var object = {}
m.withAttr("test", spy).call(object, {currentTarget: {test: "foo"}})
expect(spy).to.be.calledOn(object).and.calledWith("foo")
})
it("calls the handler with the right value/context with callbackThis", function () { // eslint-disable-line
var spy = sinon.spy()
var object = {}
m.withAttr("test", spy, object)({currentTarget: {test: "foo"}})
expect(spy).to.be.calledOn(object).and.calledWith("foo")
})
})
| describe("m.withAttr()", function () {
"use strict"
it("calls the handler with the right value/context without callbackThis", function () { // eslint-disable-line
var spy = sinon.spy()
var object = {}
m.withAttr("test", spy).call(object, {currentTarget: {test: "foo"}})
expect(spy).to.be.calledOn(object).and.calledWith("foo")
})
it("calls the handler with the right value/context with callbackThis", function () { // eslint-disable-line
var spy = sinon.spy()
var object = {}
m.withAttr("test", spy, object)({currentTarget: {test: "foo"}})
expect(spy).to.be.calledOn(object).and.calledWith("Ofoo")
})
})
| Break a test of the new suite | Break a test of the new suite
| JavaScript | mit | MithrilJS/mithril.js,tivac/mithril.js,lhorie/mithril.js,impinball/mithril.js,barneycarroll/mithril.js,impinball/mithril.js,tivac/mithril.js,pygy/mithril.js,MithrilJS/mithril.js,pygy/mithril.js,barneycarroll/mithril.js,lhorie/mithril.js | ---
+++
@@ -12,6 +12,6 @@
var spy = sinon.spy()
var object = {}
m.withAttr("test", spy, object)({currentTarget: {test: "foo"}})
- expect(spy).to.be.calledOn(object).and.calledWith("foo")
+ expect(spy).to.be.calledOn(object).and.calledWith("Ofoo")
})
}) |
67b66b5568f264a9ed4b0940de406ed26797fd4e | test/specificity.test.js | test/specificity.test.js | var path = require('path'),
assert = require('assert'),
fs = require('fs');
var carto = require('../lib/carto');
var tree = require('../lib/carto').tree;
var helper = require('./support/helper');
function cleanupItem(key, value) {
if (key === 'rules') return;
else if (key === 'ruleIndex') return;
else if (key === 'elements') return value.map(function(item) { return item.value; });
else if (key === 'filters') {
var arr = [];
for (var id in value.filters) arr.push(id + value.filters[id].val);
if (arr.length) return arr;
}
else if (key === 'attachment' && value === '__default__') return;
else if (key === 'zoom') {
if (value != tree.Zoom.all) return tree.Zoom.toString(value);
}
else return value;
}
describe('Specificity', function() {
helper.files('specificity', 'mss', function(file) {
it('should handle spec correctly in ' + file, function(done) {
helper.file(file, function(content) {
var tree = (new carto.Parser({
paths: [ path.dirname(file) ],
filename: file
})).parse(content);
var mss = tree.toList({});
mss = helper.makePlain(mss, cleanupItem);
helper.compareToFile(mss, file, helper.resultFile(file));
done();
});
});
});
});
| var path = require('path'),
assert = require('assert'),
fs = require('fs');
var carto = require('../lib/carto');
var tree = require('../lib/carto').tree;
var helper = require('./support/helper');
function cleanupItem(key, value) {
if (key === 'rules') return;
else if (key === 'ruleIndex') return;
else if (key === 'elements') return value.map(function(item) { return item.value; });
else if (key === 'filters') {
var arr = [];
for (var id in value.filters) arr.push(id + value.filters[id].val);
if (arr.length) return arr;
}
else if (key === 'attachment' && value === '__default__') return;
else if (key === 'zoom') {
if (value != tree.Zoom.all) return (new tree.Zoom()).setZoom(value).toString();
}
else return value;
}
describe('Specificity', function() {
helper.files('specificity', 'mss', function(file) {
it('should handle spec correctly in ' + file, function(done) {
helper.file(file, function(content) {
var tree = (new carto.Parser({
paths: [ path.dirname(file) ],
filename: file
})).parse(content);
var mss = tree.toList({});
mss = helper.makePlain(mss, cleanupItem);
helper.compareToFile(mss, file, helper.resultFile(file));
done();
});
});
});
});
| Fix zoom interpretation in helper | Fix zoom interpretation in helper
| JavaScript | apache-2.0 | pnorman/carto,clhenrick/carto,CartoDB/carto,CartoDB/carto,gravitystorm/carto,stefanklug/carto,tomhughes/carto,whitelynx/carto,mapbox/carto,midnightcomm/carto,madeinqc/carto,1ec5/carto | ---
+++
@@ -17,7 +17,7 @@
}
else if (key === 'attachment' && value === '__default__') return;
else if (key === 'zoom') {
- if (value != tree.Zoom.all) return tree.Zoom.toString(value);
+ if (value != tree.Zoom.all) return (new tree.Zoom()).setZoom(value).toString();
}
else return value;
} |
e65b54770e47356e2aba9afc46b1551fa7ece6b0 | build/tasks/dev.js | build/tasks/dev.js | import gulp from 'gulp'
import path from 'path'
import BrowserSync from 'browser-sync'
import { compiler, handleWebpackResults } from '../webpack/compiler'
const browserSync = BrowserSync.create()
const args = global.__args
const themeDir = path.resolve(__pkg._themepath)
const themeRelPath = themeDir.replace(process.cwd()+'/', '')
gulp.task('dev', ['build'], ()=> {
compiler.watch({}, handleWebpackResults(true))
gulp.watch(`${themeRelPath}/scss/**/*.scss`, ['styles'])
gulp.watch(`${themeRelPath}/images/**/*`, ['images'])
gulp.watch(`${themeRelPath}/fonts/**/*`, ['static'])
if (args.sync) {
browserSync.init({
proxy: __pkg._criticalUrl,
files: [
`${themeRelPath}/assets/js/*.js`,
`${themeRelPath}/**/*.php`
]
})
}
})
| import gulp from 'gulp'
import path from 'path'
import BrowserSync from 'browser-sync'
import { compiler, handleWebpackResults } from '../webpack/compiler'
const browserSync = BrowserSync.create()
const args = global.__args
const themeDir = path.resolve(__pkg._themepath)
const themeRelPath = themeDir.replace(process.cwd()+'/', '')
gulp.task('dev', ['build'], ()=> {
compiler.watch({}, handleWebpackResults(true))
gulp.watch(`${themeRelPath}/scss/**/*.scss`, ['styles'])
gulp.watch(`${themeRelPath}/images/**/*`, ['images'])
gulp.watch(`${themeRelPath}/fonts/**/*`, ['static'])
if (args.sync) {
browserSync.init({
proxy: __pkg._criticalUrl,
files: [
`${themeRelPath}/assets/js/*.js`,
`${themeRelPath}/assets/css/*.css`,
`${themeRelPath}/**/*.php`
]
})
}
})
| Make sure CSS files are watched | Make sure CSS files are watched
| JavaScript | mit | 3five/Rudiments-Stack,3five/Rudiments-Stack,3five/Rudiments-Stack,3five/Rudiments-Stack,3five/Rudiments-Stack | ---
+++
@@ -19,6 +19,7 @@
proxy: __pkg._criticalUrl,
files: [
`${themeRelPath}/assets/js/*.js`,
+ `${themeRelPath}/assets/css/*.css`,
`${themeRelPath}/**/*.php`
]
}) |
03217724b92da3636e1e8b81acd35d652a21bc57 | packages/expo/bin/commands/add-hook.js | packages/expo/bin/commands/add-hook.js | const prompts = require('prompts')
const addHook = require('../lib/add-hook')
const { onCancel } = require('../lib/utils')
const { blue, yellow } = require('kleur')
module.exports = async (argv, globalOpts) => {
const res = await prompts({
type: 'confirm',
name: 'addHook',
message: `This will modify your app.json. Is that ok?`,
initial: true
}, { onCancel })
if (res.addHook) {
console.log(blue(`> Inserting hook config into app.json`))
const msg = await addHook(globalOpts['project-root'])
if (msg) console.log(yellow(` ${msg}`))
}
}
| const prompts = require('prompts')
const addHook = require('../lib/add-hook')
const { onCancel } = require('../lib/utils')
const { blue, yellow } = require('kleur')
module.exports = async (argv, globalOpts) => {
const res = await prompts({
type: 'confirm',
name: 'addHook',
message,
initial: true
}, { onCancel })
if (res.addHook) {
console.log(blue(`> Inserting hook config into app.json`))
const msg = await addHook(globalOpts['project-root'])
if (msg) console.log(yellow(` ${msg}`))
}
}
const message = `Do you want to automatically upload source maps to Bugsnag? (this will modify your app.json)`
| Add API hook command should say what it's going to do | fix(expo-cli): Add API hook command should say what it's going to do
| JavaScript | mit | bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js | ---
+++
@@ -7,7 +7,7 @@
const res = await prompts({
type: 'confirm',
name: 'addHook',
- message: `This will modify your app.json. Is that ok?`,
+ message,
initial: true
}, { onCancel })
if (res.addHook) {
@@ -16,3 +16,5 @@
if (msg) console.log(yellow(` ${msg}`))
}
}
+
+const message = `Do you want to automatically upload source maps to Bugsnag? (this will modify your app.json)` |
2fbf834731d37d53d81238f58866ff90edca5cbb | src/editor/components/RefComponent.js | src/editor/components/RefComponent.js | import { NodeComponent } from 'substance'
import { renderEntity } from '../../entities/entityHelpers'
export default class RefComponent extends NodeComponent {
render($$) {
const db = this.context.pubMetaDbSession.getDocument()
const ref = this.props.node
let label = _getReferenceLabel(ref)
let entityHtml = renderEntity(_getEntity(ref, db))
// TODO: do we want to display something like this
// if so, use the label provider
entityHtml = entityHtml || '<i>Not available</i>'
return $$('div').addClass('sc-ref-component').append(
$$('div').addClass('se-label').append(label),
$$('div').addClass('se-text').html(entityHtml)
)
}
}
function _getReferenceLabel(ref) {
if (ref.state && ref.state.label) {
return ref.state.label
}
return '?'
}
function _getEntity(ref, db) {
if (ref.state && ref.state.entity) {
return ref.state.entity
}
return db.get(ref.id)
}
| import { NodeComponent } from 'substance'
import { renderEntity } from '../../entities/entityHelpers'
export default class RefComponent extends NodeComponent {
render($$) {
const db = this.context.pubMetaDbSession.getDocument()
const ref = this.props.node
let label = _getReferenceLabel(ref)
let entityHtml = renderEntity(_getEntity(ref, db))
// TODO: do we want to display something like this
// if so, use the label provider
entityHtml = entityHtml || '<i>Not available</i>'
return $$('div').addClass('sc-ref-component').append(
$$('div').addClass('se-label').append(label),
$$('div').addClass('se-text').html(entityHtml)
).attr('data-id', ref.id)
}
}
function _getReferenceLabel(ref) {
if (ref.state && ref.state.label) {
return ref.state.label
}
return '?'
}
function _getEntity(ref, db) {
if (ref.state && ref.state.entity) {
return ref.state.entity
}
return db.get(ref.id)
}
| Set data-id on ref component. | Set data-id on ref component.
| JavaScript | mit | substance/texture,substance/texture | ---
+++
@@ -16,7 +16,7 @@
return $$('div').addClass('sc-ref-component').append(
$$('div').addClass('se-label').append(label),
$$('div').addClass('se-text').html(entityHtml)
- )
+ ).attr('data-id', ref.id)
}
}
|
eb3035ffcf0d68ad7477c0b25021fa46cbe32ab1 | templates/src/scripts/main.js | templates/src/scripts/main.js | var words = 'Hello Camp JS'.split(' ');
words.forEach((word) => document.body.innerHTML += '<p>' + word + '</p>');
| var words = 'Hello Camp JS'.split(' ');
words.forEach(word => document.body.innerHTML += '<p>' + word + '</p>');
| Drop parens for arrow function | Drop parens for arrow function
| JavaScript | mit | markdalgleish/slush-campjs-gulp | ---
+++
@@ -1,2 +1,2 @@
var words = 'Hello Camp JS'.split(' ');
-words.forEach((word) => document.body.innerHTML += '<p>' + word + '</p>');
+words.forEach(word => document.body.innerHTML += '<p>' + word + '</p>'); |
67098dc24693d31a34ac2fd78d9b145b4e8aee9a | bin/avails.js | bin/avails.js | #!/usr/bin/env node
var packageJson = require('../package.json');
var program = require('commander');
program
.version(packageJson.version)
.description(packageJson.description)
.command('convert', 'convert Avails between various formats', {
isDefault: true
})
.parse(process.argv);
| #!/usr/bin/env node
var packageJson = require('../package.json');
var program = require('commander');
program
.version(packageJson.version)
.description(packageJson.description)
.command('convert', 'convert Avails between various formats')
.command('merge', 'merge historical Avails into one')
.parse(process.argv);
| Remove default setting for Avails command | Remove default setting for Avails command
| JavaScript | mit | pivotshare/avails | ---
+++
@@ -7,7 +7,6 @@
program
.version(packageJson.version)
.description(packageJson.description)
- .command('convert', 'convert Avails between various formats', {
- isDefault: true
- })
+ .command('convert', 'convert Avails between various formats')
+ .command('merge', 'merge historical Avails into one')
.parse(process.argv); |
225f12f2527e9d8d7d6d4b65da642375d31ffbcc | src/javascript/binary/static_pages/video_facility.js | src/javascript/binary/static_pages/video_facility.js | const BinaryPjax = require('../base/binary_pjax');
const Client = require('../base/client');
const defaultRedirectUrl = require('../base/url').defaultRedirectUrl;
const getLoginToken = require('../common_functions/common_functions').getLoginToken;
const DeskWidget = require('../common_functions/attach_dom/desk_widget');
const BinarySocket = require('../websocket_pages/socket');
const VideoFacility = (() => {
const onLoad = () => {
BinarySocket.send({ get_account_status: 1 }).then((response) => {
if (response.error) {
$('#error_message').setVisibility(1).text(response.error.message);
} else {
const status = response.get_account_status.status;
if (/authenticated/.test(status)) {
BinaryPjax.load(defaultRedirectUrl());
} else {
DeskWidget.showDeskLink('', '#facility_content');
if (!Client.isFinancial()) {
$('#not_authenticated').setVisibility(1);
}
$('.msg_authenticate').setVisibility(1);
$('#generated_token').text(getLoginToken().slice(-4));
}
}
});
};
return {
onLoad: onLoad,
};
})();
module.exports = VideoFacility;
| const BinaryPjax = require('../base/binary_pjax');
const Client = require('../base/client');
const localize = require('../base/localize').localize;
const defaultRedirectUrl = require('../base/url').defaultRedirectUrl;
const getLoginToken = require('../common_functions/common_functions').getLoginToken;
const DeskWidget = require('../common_functions/attach_dom/desk_widget');
const BinarySocket = require('../websocket_pages/socket');
const VideoFacility = (() => {
const onLoad = () => {
if (Client.get('loginid_array').find(obj => obj.id === Client.get('loginid')).non_financial) {
$('#loading').replaceWith($('<p/>', { class: 'notice-msg center-text', text: localize('Sorry, this feature is not available in your jurisdiction.') }));
return;
}
BinarySocket.send({ get_account_status: 1 }).then((response) => {
if (response.error) {
$('#error_message').setVisibility(1).text(response.error.message);
} else {
const status = response.get_account_status.status;
if (/authenticated/.test(status)) {
BinaryPjax.load(defaultRedirectUrl());
} else {
DeskWidget.showDeskLink('', '#facility_content');
if (!Client.isFinancial()) {
$('#not_authenticated').setVisibility(1);
}
$('.msg_authenticate').setVisibility(1);
$('#generated_token').text(getLoginToken().slice(-4));
}
}
});
};
return {
onLoad: onLoad,
};
})();
module.exports = VideoFacility;
| Hide video facility contents from non-financial clients | Hide video facility contents from non-financial clients
| JavaScript | apache-2.0 | negar-binary/binary-static,binary-static-deployed/binary-static,ashkanx/binary-static,4p00rv/binary-static,ashkanx/binary-static,binary-com/binary-static,raunakkathuria/binary-static,binary-static-deployed/binary-static,kellybinary/binary-static,kellybinary/binary-static,4p00rv/binary-static,binary-com/binary-static,binary-static-deployed/binary-static,raunakkathuria/binary-static,raunakkathuria/binary-static,negar-binary/binary-static,ashkanx/binary-static,4p00rv/binary-static,binary-com/binary-static,negar-binary/binary-static,kellybinary/binary-static | ---
+++
@@ -1,5 +1,6 @@
const BinaryPjax = require('../base/binary_pjax');
const Client = require('../base/client');
+const localize = require('../base/localize').localize;
const defaultRedirectUrl = require('../base/url').defaultRedirectUrl;
const getLoginToken = require('../common_functions/common_functions').getLoginToken;
const DeskWidget = require('../common_functions/attach_dom/desk_widget');
@@ -7,6 +8,11 @@
const VideoFacility = (() => {
const onLoad = () => {
+ if (Client.get('loginid_array').find(obj => obj.id === Client.get('loginid')).non_financial) {
+ $('#loading').replaceWith($('<p/>', { class: 'notice-msg center-text', text: localize('Sorry, this feature is not available in your jurisdiction.') }));
+ return;
+ }
+
BinarySocket.send({ get_account_status: 1 }).then((response) => {
if (response.error) {
$('#error_message').setVisibility(1).text(response.error.message); |
2e4976b3515f7afda8275fe89b2ac16b3e2c4f2c | sections/faqs/when-to-use-attrs.js | sections/faqs/when-to-use-attrs.js | import md from 'components/md'
const WhenToUseAttrs = () => md`
## When to use attrs?
You can pass in attributes to styled components using \`attrs\`, but
it is not always sensible to do so.
The rule of thumb is to use \`attrs\` when you want every instance of a styled
component to have that prop, and pass props directly when every instance needs a
different one:
\`\`\`js
const PasswordInput = styled.input.attrs({
// Every <PasswordInput /> should be type="password"
type: 'password'
})\`\`
// This specific one is hidden, so let's set aria-hidden
<PasswordInput aria-hidden="true" />
\`\`\`
`
export default WhenToUseAttrs
| import md from 'components/md'
const WhenToUseAttrs = () => md`
## When to use attrs?
You can pass in attributes to styled components using [attrs](/docs/basics#attaching-additional-props), but
it is not always sensible to do so.
The rule of thumb is to use \`attrs\` when you want every instance of a styled
component to have that prop, and pass props directly when every instance needs a
different one:
\`\`\`js
const PasswordInput = styled.input.attrs({
// Every <PasswordInput /> should be type="password"
type: 'password'
})\`\`
// This specific one is hidden, so let's set aria-hidden
<PasswordInput aria-hidden="true" />
\`\`\`
`
export default WhenToUseAttrs
| Add a link to attrs in the docs | Add a link to attrs in the docs
| JavaScript | mit | styled-components/styled-components-website,styled-components/styled-components-website | ---
+++
@@ -3,7 +3,7 @@
const WhenToUseAttrs = () => md`
## When to use attrs?
- You can pass in attributes to styled components using \`attrs\`, but
+ You can pass in attributes to styled components using [attrs](/docs/basics#attaching-additional-props), but
it is not always sensible to do so.
The rule of thumb is to use \`attrs\` when you want every instance of a styled |
cb68c4e32710ae8963df5f1b60d0b3bda6a61404 | server/controllers/eventPreview.js | server/controllers/eventPreview.js | import {
DEFAULT_LIMIT,
DEFAULT_OFFSET,
} from './base'
import {
EventBelongsToManyImage,
EventBelongsToPlace,
EventHasManySlots,
} from '../database/associations'
import Event from '../models/event'
export default {
findAll: (req, res, next) => {
const {
limit = DEFAULT_LIMIT,
offset = DEFAULT_OFFSET,
} = req.query
return Event.findAndCountAll({
include: [
EventBelongsToManyImage,
EventHasManySlots, {
association: EventBelongsToPlace,
required: true,
where: {
isPublic: true,
},
},
],
limit,
offset,
where: {
isPublic: true,
},
order: [
[
EventHasManySlots,
'from',
'ASC',
],
],
})
.then(result => {
res.json({
data: result.rows,
limit: parseInt(limit, 10),
offset: parseInt(offset, 10),
total: result.count,
})
})
.catch(err => next(err))
},
}
| import {
DEFAULT_LIMIT,
DEFAULT_OFFSET,
} from './base'
import {
EventBelongsToManyImage,
EventBelongsToPlace,
EventHasManySlots,
} from '../database/associations'
import Event from '../models/event'
export default {
findAll: (req, res, next) => {
const {
limit = DEFAULT_LIMIT,
offset = DEFAULT_OFFSET,
} = req.query
return Event.findAndCountAll({
distinct: true,
include: [
EventBelongsToManyImage,
EventHasManySlots, {
association: EventBelongsToPlace,
required: true,
where: {
isPublic: true,
},
},
],
limit,
offset,
where: {
isPublic: true,
},
order: [
[
EventHasManySlots,
'from',
'ASC',
],
],
})
.then(result => {
res.json({
data: result.rows,
limit: parseInt(limit, 10),
offset: parseInt(offset, 10),
total: result.count,
})
})
.catch(err => next(err))
},
}
| Enable distinct results for calendar preview | Enable distinct results for calendar preview
| JavaScript | agpl-3.0 | adzialocha/hoffnung3000,adzialocha/hoffnung3000 | ---
+++
@@ -19,6 +19,7 @@
} = req.query
return Event.findAndCountAll({
+ distinct: true,
include: [
EventBelongsToManyImage,
EventHasManySlots, { |
69f93bb91f57900f337b6ba7c5d0602e6846cdd8 | lib/addMethod/validateRESTInput.js | lib/addMethod/validateRESTInput.js | var _ = require('lodash');
module.exports = function (methodName, config) {
// Ensure the minimum parameters have been passed
if (!methodName || !_.isString(methodName)) {
throw new Error('The first parameter passed to `addMethod` should be a string.');
}
// If a function is inputted as the `config`, then just return - there's
// really not much to validate.
if (_.isFunction(config)) {
return;
}
if (!config || !_.isObject(config)) {
throw new Error('The `config` object should be an object.');
}
// Check to see if the method has already been declared
if (!_.isUndefined(this[methodName])) {
throw new Error('Method `'+methodName+'` has already been declared.');
}
// Ensure the config parameters have been specified correctly
if (!config.url) {
throw new Error('The `url` config parameter should be declared.');
}
if (!config.method || !_.isString(config.method)) {
throw new Error('The `method` config parameter should be declared as string.');
}
var method = config.method.toLowerCase();
var allowedMethods = [ 'get', 'put', 'post', 'delete', 'head', 'patch' ];
if (allowedMethods.indexOf(method) === -1) {
throw new Error('The `method` "'+method+'" is not a valid method. Allowed methods are: '+allowedMethods.join(', '));
}
}; | var _ = require('lodash');
module.exports = function (methodName, config) {
// Ensure the minimum parameters have been passed
if (!methodName || !_.isString(methodName)) {
throw new Error('The first parameter passed to `addMethod` should be a string.');
}
// If a function is inputted as the `config`, then just return - there's
// really not much to validate.
if (_.isFunction(config)) {
return;
}
if (!config || !_.isObject(config)) {
throw new Error('The `config` object should be an object.');
}
// Check to see if the method has already been declared
if (!_.isUndefined(this[methodName])) {
throw new Error('Method `'+methodName+'` has already been declared.');
}
// Ensure the config parameters have been specified correctly
if (!config.url && config.url !== '') {
throw new Error('The `url` config parameter should be declared.');
}
if (!config.method || !_.isString(config.method)) {
throw new Error('The `method` config parameter should be declared as string.');
}
var method = config.method.toLowerCase();
var allowedMethods = [ 'get', 'put', 'post', 'delete', 'head', 'patch' ];
if (allowedMethods.indexOf(method) === -1) {
throw new Error('The `method` "'+method+'" is not a valid method. Allowed methods are: '+allowedMethods.join(', '));
}
};
| Allow method URL to be an empty string | Allow method URL to be an empty string
| JavaScript | mit | trayio/threadneedle | ---
+++
@@ -21,7 +21,7 @@
}
// Ensure the config parameters have been specified correctly
- if (!config.url) {
+ if (!config.url && config.url !== '') {
throw new Error('The `url` config parameter should be declared.');
}
if (!config.method || !_.isString(config.method)) { |
be394881923665df48a9d9b82c290e2c8a03a41a | server/entities/team/team.model.js | server/entities/team/team.model.js | 'use strict';
let mongoose = require('mongoose');
let Schema = mongoose.Schema;
let teamSchema = new Schema({
name : {
type: String,
required: true,
unique: true
},
email : {
type: String,
required: true,
unique: true
},
description : {
type: String
},
logisticsRequirements : {
type: String
},
openForApplications : {
type: Boolean,
default: true
},
members : {
leader : {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
list : [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}]
},
cremiRoom : {
type: String
},
data : mongoose.Schema.Types.Mixed
});
require('./team.controller')(teamSchema);
module.exports = mongoose.model('Team', teamSchema);
| 'use strict';
let mongoose = require('mongoose');
let Schema = mongoose.Schema;
let teamSchema = new Schema({
name : {
type: String,
required: true,
unique: true
},
email : {
type: String,
required: true
},
description : {
type: String
},
logisticsRequirements : {
type: String
},
openForApplications : {
type: Boolean,
default: true
},
members : {
leader : {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
list : [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}]
},
cremiRoom : {
type: String
},
data : mongoose.Schema.Types.Mixed
});
require('./team.controller')(teamSchema);
module.exports = mongoose.model('Team', teamSchema);
| Remove unique emails for teams | fix(server): Remove unique emails for teams
| JavaScript | apache-2.0 | asso-labeli/nuitinfo,asso-labeli/nuitinfo,asso-labeli/nuitinfo | ---
+++
@@ -11,8 +11,7 @@
},
email : {
type: String,
- required: true,
- unique: true
+ required: true
},
description : {
type: String |
16fa91c15f27843b8d947ca47fac4e50bd765d2f | lib/controllers/list_controller.js | lib/controllers/list_controller.js | ListController = RouteController.extend({
layoutTemplate: 'Layout',
subscriptions: function () {
this.subscribe('hosts');
},
action: function () {
this.render('HostList');
}
});
| ListController = RouteController.extend({
layoutTemplate: 'Layout',
subscriptions: function () {
this.subscribe('hosts', {
sort: {sort: 1}
});
},
action: function () {
this.render('HostList');
}
});
| Add sort for host list subscription. | Add sort for host list subscription.
| JavaScript | mit | steyep/syrinx,hb5co/syrinx,mikebarkas/syrinx,bfodeke/syrinx,bfodeke/syrinx,hb5co/syrinx,steyep/syrinx,shrop/syrinx,shrop/syrinx,mikebarkas/syrinx | ---
+++
@@ -2,7 +2,9 @@
layoutTemplate: 'Layout',
subscriptions: function () {
- this.subscribe('hosts');
+ this.subscribe('hosts', {
+ sort: {sort: 1}
+ });
},
action: function () { |
0889452062f149dbba5ce8acf005908fd7355b34 | app/assets/javascripts/_analytics.js | app/assets/javascripts/_analytics.js | (function() {
"use strict";
GOVUK.Tracker.load();
var cookieDomain = (document.domain === 'www.beta.digitalmarketplace.service.gov.uk') ? '.digitalmarketplace.service.gov.uk' : document.domain;
GOVUK.analytics = new GOVUK.Tracker({
universalId: 'UA-49258698-3',
cookieDomain: cookieDomain
});
GOVUK.analytics.trackPageview();
})();
| (function() {
"use strict";
GOVUK.Tracker.load();
var cookieDomain = (document.domain === 'www.beta.digitalmarketplace.service.gov.uk') ? '.digitalmarketplace.service.gov.uk' : document.domain;
var property = (document.domain === 'www.digitalmarketplace.service.gov.uk') ? 'UA-49258698-1' : 'UA-49258698-3';
GOVUK.analytics = new GOVUK.Tracker({
universalId: property,
cookieDomain: cookieDomain
});
GOVUK.analytics.trackPageview();
})();
| Use correct analytics properties for live/other | Use correct analytics properties for live/other
This commit makes the app select different Google analytics properties to track
against depending on which domain the user is browsing.
This will ensure continuity of analytics when we switch the DNS.
| JavaScript | mit | alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend | ---
+++
@@ -2,8 +2,9 @@
"use strict";
GOVUK.Tracker.load();
var cookieDomain = (document.domain === 'www.beta.digitalmarketplace.service.gov.uk') ? '.digitalmarketplace.service.gov.uk' : document.domain;
+ var property = (document.domain === 'www.digitalmarketplace.service.gov.uk') ? 'UA-49258698-1' : 'UA-49258698-3';
GOVUK.analytics = new GOVUK.Tracker({
- universalId: 'UA-49258698-3',
+ universalId: property,
cookieDomain: cookieDomain
});
GOVUK.analytics.trackPageview(); |
ea87c51a6de416f083d9015166db9008b800da61 | assets/js/components/Chip.stories.js | assets/js/components/Chip.stories.js | /**
* Chip Component Stories.
*
* Site Kit by Google, Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import Chip from './Chip';
const Template = ( args ) => <Chip { ...args } />;
export const DefaultButton = Template.bind( {} );
DefaultButton.storyName = 'Default Chip';
DefaultButton.args = {
id: 'default',
label: 'Default Chip',
};
export default {
title: 'Components/Chip',
component: Chip,
};
| /**
* Chip Component Stories.
*
* Site Kit by Google, Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import Chip from './Chip';
const Template = ( args ) => <Chip { ...args } />;
export const DefaultChip = Template.bind( {} );
DefaultChip.storyName = 'Default Chip';
DefaultChip.args = {
id: 'default',
label: 'Default Chip',
};
export const SelectedChip = Template.bind( {} );
SelectedChip.storyName = 'Selected Chip';
SelectedChip.args = {
id: 'selected',
label: 'Selected Chip',
selected: true,
};
export default {
title: 'Components/Chip',
component: Chip,
};
| Add story for a selected chip. | Add story for a selected chip.
| JavaScript | apache-2.0 | google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp | ---
+++
@@ -23,11 +23,19 @@
const Template = ( args ) => <Chip { ...args } />;
-export const DefaultButton = Template.bind( {} );
-DefaultButton.storyName = 'Default Chip';
-DefaultButton.args = {
+export const DefaultChip = Template.bind( {} );
+DefaultChip.storyName = 'Default Chip';
+DefaultChip.args = {
id: 'default',
label: 'Default Chip',
+};
+
+export const SelectedChip = Template.bind( {} );
+SelectedChip.storyName = 'Selected Chip';
+SelectedChip.args = {
+ id: 'selected',
+ label: 'Selected Chip',
+ selected: true,
};
export default { |
cacebb76a7554c5713d4f88a8060969c0eea7d7c | app/scripts/filters/previewfilter.js | app/scripts/filters/previewfilter.js | 'use strict';
/**
* @ngdoc filter
* @name dockstore.ui.filter:PreviewFilter
* @function
* @description
* # PreviewFilter
* Filter in the dockstore.ui.
*/
angular.module('dockstore.ui')
.filter('PreviewFilter', [function () {
return function (containers, contLimit) {
if (!contLimit) return containers;
var sortedByBuildTime = containers.sort(function(a, b) {
if (!a.lastBuild) a.lastBuild.lastBuild = Number.MAX_VALUE;
if (!b.lastBuild) b.lastBuild = Number.MAX_VALUE;
return a.lastBuild - b.lastBuild;
});
return sortedByBuildTime.slice(0, contLimit - 1);
};
}]);
| 'use strict';
/**
* @ngdoc filter
* @name dockstore.ui.filter:PreviewFilter
* @function
* @description
* # PreviewFilter
* Filter in the dockstore.ui.
*/
angular.module('dockstore.ui')
.filter('PreviewFilter', [function () {
return function (containers, contLimit) {
if (!contLimit) return containers;
var sortedByBuildTime = containers.sort(function(a, b) {
if (!a.lastBuild) a.lastBuild = Number.MAX_VALUE;
if (!b.lastBuild) b.lastBuild = Number.MAX_VALUE;
return a.lastBuild - b.lastBuild;
});
return sortedByBuildTime.slice(0, contLimit - 1);
};
}]);
| Update PreviewFilter for invalid/non-returned timestamps (v3). | Update PreviewFilter for invalid/non-returned timestamps (v3).
| JavaScript | apache-2.0 | ga4gh/dockstore-ui,ga4gh/dockstore-ui,ga4gh/dockstore-ui | ---
+++
@@ -13,7 +13,7 @@
return function (containers, contLimit) {
if (!contLimit) return containers;
var sortedByBuildTime = containers.sort(function(a, b) {
- if (!a.lastBuild) a.lastBuild.lastBuild = Number.MAX_VALUE;
+ if (!a.lastBuild) a.lastBuild = Number.MAX_VALUE;
if (!b.lastBuild) b.lastBuild = Number.MAX_VALUE;
return a.lastBuild - b.lastBuild;
}); |
4ec65ebe85d0a1f74373840b5d3418888b30caf6 | lib/ext/function/promisify-sync.js | lib/ext/function/promisify-sync.js | // Promisify synchronous function
'use strict';
var callable = require('es5-ext/lib/Object/valid-callable')
, deferred = require('../../deferred')
, isPromise = require('../../is-promise')
, processArguments = require('../_process-arguments')
, apply = Function.prototype.apply
, applyFn;
applyFn = function (fn, args, resolve) {
var value;
try {
value = apply.call(fn, this, args);
} catch (e) {
value = e;
}
resolve(value);
};
module.exports = function (length) {
var fn, result;
fn = callable(this);
if (fn.returnsPromise) {
return fn;
}
if (length != null) {
length = length >>> 0;
}
result = function () {
var args, def;
args = processArguments(arguments, length);
if (isPromise(args)) {
if (args.failed) {
return args;
}
def = deferred();
args.end(function (args) {
apply.call(this, fn, args, def.resolve);
}.bind(this), def.resolve);
} else {
def = deferred();
applyFn.call(this, fn, args, def.resolve);
}
return def.promise;
};
result.returnsPromise = true;
return result;
};
| // Promisify synchronous function
'use strict';
var callable = require('es5-ext/lib/Object/valid-callable')
, deferred = require('../../deferred')
, isPromise = require('../../is-promise')
, processArguments = require('../_process-arguments')
, apply = Function.prototype.apply
, applyFn;
applyFn = function (fn, args, resolve) {
var value;
try {
value = apply.call(fn, this, args);
} catch (e) {
value = e;
}
resolve(value);
};
module.exports = function (length) {
var fn, result;
fn = callable(this);
if (fn.returnsPromise) {
return fn;
}
if (length != null) {
length = length >>> 0;
}
result = function () {
var args, def;
args = processArguments(arguments, length);
if (isPromise(args)) {
if (args.failed) {
return args;
}
def = deferred();
args.end(function (args) {
applyFn.call(this, fn, args, def.resolve);
}.bind(this), def.resolve);
} else {
def = deferred();
applyFn.call(this, fn, args, def.resolve);
}
return def.promise;
};
result.returnsPromise = true;
return result;
};
| Fix promisifySync case of promise arguments | Fix promisifySync case of promise arguments
| JavaScript | isc | medikoo/deferred | ---
+++
@@ -40,7 +40,7 @@
}
def = deferred();
args.end(function (args) {
- apply.call(this, fn, args, def.resolve);
+ applyFn.call(this, fn, args, def.resolve);
}.bind(this), def.resolve);
} else {
def = deferred(); |
a55921bc5ee2fa74ce11f8936121ec914240ee56 | createTest.js | createTest.js | var ACCEPTANCE_TESTS_ENDPOINT = 'http://paie.sgmap.fr/tests/api/acceptance-tests',
ACCEPTANCE_TESTS_GUI_URL = 'http://paie.sgmap.fr/tests/';
function createTest() {
var formattedResults = Object.keys(window.lastResult).map(function(key) {
return {
code: key,
expectedValue: window.lastResult[key]
}
});
var form = document.getElementsByTagName('form')[0];
var data = {
expectedResults: formattedResults,
scenario: form.action + '?' + serialize(form)
}
var request = new XMLHttpRequest();
request.withCredentials = true;
request.open('POST', ACCEPTANCE_TESTS_ENDPOINT);
request.onload = function() {
if (request.status >= 300)
throw request;
var data = JSON.parse(request.responseText);
document.location = [ ACCEPTANCE_TESTS_GUI_URL, data._id, 'edit' ].join('/');
};
request.onerror = function() {
throw request;
}
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify(data));
}
| var ACCEPTANCE_TESTS_ENDPOINT = 'http://paie.sgmap.fr/tests/api/public/acceptance-tests',
ACCEPTANCE_TESTS_GUI_URL = 'http://paie.sgmap.fr/tests/';
function createTest() {
var formattedResults = Object.keys(window.lastResult).map(function(key) {
return {
code: key,
expectedValue: window.lastResult[key]
}
});
var form = document.getElementsByTagName('form')[0];
var data = {
expectedResults: formattedResults,
scenario: form.action + '?' + serialize(form)
}
var request = new XMLHttpRequest();
request.open('POST', ACCEPTANCE_TESTS_ENDPOINT);
request.onload = function() {
if (request.status >= 300)
throw request;
var data = JSON.parse(request.responseText);
document.location = [ ACCEPTANCE_TESTS_GUI_URL, data._id, 'edit' ].join('/');
};
request.onerror = function() {
throw request;
}
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify(data));
}
| Use public API route to add tests | Use public API route to add tests
Avoid sending credentials | JavaScript | agpl-3.0 | sgmap/cout-embauche,sandcha/cout-embauche,sandcha/cout-embauche,sgmap/cout-embauche | ---
+++
@@ -1,4 +1,4 @@
-var ACCEPTANCE_TESTS_ENDPOINT = 'http://paie.sgmap.fr/tests/api/acceptance-tests',
+var ACCEPTANCE_TESTS_ENDPOINT = 'http://paie.sgmap.fr/tests/api/public/acceptance-tests',
ACCEPTANCE_TESTS_GUI_URL = 'http://paie.sgmap.fr/tests/';
function createTest() {
@@ -18,8 +18,6 @@
var request = new XMLHttpRequest();
- request.withCredentials = true;
-
request.open('POST', ACCEPTANCE_TESTS_ENDPOINT);
request.onload = function() { |
b7648a75e3fa793aedcbf902b11c64133b34a893 | auto-updater.js | auto-updater.js | const autoUpdater = require('electron').autoUpdater
const Menu = require('electron').Menu
var state = 'checking'
exports.initialize = function () {
autoUpdater.on('checking-for-update', function () {
state = 'checking'
exports.updateMenu()
})
autoUpdater.on('update-available', function () {
state = 'checking'
exports.updateMenu()
})
autoUpdater.on('update-downloaded', function () {
state = 'installed'
exports.updateMenu()
})
autoUpdater.on('update-not-available', function () {
state = 'no-update'
exports.updateMenu()
})
autoUpdater.on('error', function () {
state = 'no-update'
exports.updateMenu()
})
autoUpdater.setFeedURL('https://electron-api-demos.githubapp.com/updates')
autoUpdater.checkForUpdates()
}
exports.updateMenu = function () {
var menu = Menu.getApplicationMenu()
if (!menu) return
menu.items.forEach(function (item) {
if (item.submenu) {
item.submenu.items.forEach(function (item) {
switch (item.key) {
case 'checkForUpdate':
item.visible = state === 'no-update'
break
case 'checkingForUpdate':
item.visible = state === 'checking'
break
case 'restartToUpdate':
item.visible = state === 'installed'
break
}
})
}
})
}
| const app = require('electron').app
const autoUpdater = require('electron').autoUpdater
const Menu = require('electron').Menu
var state = 'checking'
exports.initialize = function () {
autoUpdater.on('checking-for-update', function () {
state = 'checking'
exports.updateMenu()
})
autoUpdater.on('update-available', function () {
state = 'checking'
exports.updateMenu()
})
autoUpdater.on('update-downloaded', function () {
state = 'installed'
exports.updateMenu()
})
autoUpdater.on('update-not-available', function () {
state = 'no-update'
exports.updateMenu()
})
autoUpdater.on('error', function () {
state = 'no-update'
exports.updateMenu()
})
autoUpdater.setFeedURL(`https://electron-api-demos.githubapp.com/updates?version=${app.getVersion()}`)
autoUpdater.checkForUpdates()
}
exports.updateMenu = function () {
var menu = Menu.getApplicationMenu()
if (!menu) return
menu.items.forEach(function (item) {
if (item.submenu) {
item.submenu.items.forEach(function (item) {
switch (item.key) {
case 'checkForUpdate':
item.visible = state === 'no-update'
break
case 'checkingForUpdate':
item.visible = state === 'checking'
break
case 'restartToUpdate':
item.visible = state === 'installed'
break
}
})
}
})
}
| Add version to update url | Add version to update url
| JavaScript | mit | blep/electron-api-demos,blep/electron-api-demos,PanCheng111/XDF_Personal_Analysis,blep/electron-api-demos,PanCheng111/XDF_Personal_Analysis,electron/electron-api-demos,blep/electron-api-demos,PanCheng111/XDF_Personal_Analysis,electron/electron-api-demos,electron/electron-api-demos | ---
+++
@@ -1,3 +1,4 @@
+const app = require('electron').app
const autoUpdater = require('electron').autoUpdater
const Menu = require('electron').Menu
@@ -29,7 +30,7 @@
exports.updateMenu()
})
- autoUpdater.setFeedURL('https://electron-api-demos.githubapp.com/updates')
+ autoUpdater.setFeedURL(`https://electron-api-demos.githubapp.com/updates?version=${app.getVersion()}`)
autoUpdater.checkForUpdates()
}
|
854644f46cdc10387ef27399bbde7a61f835e9bf | scripts/grunt/default_task.js | scripts/grunt/default_task.js | // Lint and build CSS
module.exports = function (grunt) {
'use strict';
grunt.registerTask('default', [
'clean:build',
'phantomjs',
'webpack:dev',
]);
grunt.registerTask('test', [
'sasslint',
'tslint',
'typecheck',
"exec:jest",
'no-only-tests'
]);
grunt.registerTask('tslint', [
'newer:exec:tslintPackages',
'newer:exec:tslintRoot',
]);
grunt.registerTask('typecheck', [
'newer:exec:typecheckPackages',
'newer:exec:typecheckRoot',
]);
grunt.registerTask('precommit', [
'newer:sasslint',
'typecheck',
'tslint',
'no-only-tests'
]);
grunt.registerTask('no-only-tests', function () {
var files = grunt.file.expand('public/**/*_specs\.ts', 'public/**/*_specs\.js');
files.forEach(function (spec) {
var rows = grunt.file.read(spec).split('\n');
rows.forEach(function (row) {
if (row.indexOf('.only(') > 0) {
grunt.log.errorlns(row);
grunt.fail.warn('found only statement in test: ' + spec)
}
});
});
});
};
| // Lint and build CSS
module.exports = function (grunt) {
'use strict';
grunt.registerTask('default', [
'clean:build',
'phantomjs',
'webpack:dev',
]);
grunt.registerTask('test', [
'sasslint',
'tslint',
'typecheck',
"exec:jest",
'no-only-tests'
]);
grunt.registerTask('tslint', [
'newer:exec:tslintPackages',
'newer:exec:tslintRoot',
]);
grunt.registerTask('typecheck', [
'newer:exec:typecheckPackages',
'newer:exec:typecheckRoot',
]);
grunt.registerTask('precommit', [
'newer:sasslint',
'typecheck',
'tslint',
'no-only-tests'
]);
grunt.registerTask('no-only-tests', function () {
var files = grunt.file.expand(
'public/**/*@(_specs|\.test)\.@(ts|js|tsx|jsx)',
'packages/grafana-ui/**/*@(_specs|\.test)\.@(ts|js|tsx|jsx)'
);
files.forEach(function (spec) {
var rows = grunt.file.read(spec).split('\n');
rows.forEach(function (row) {
if (row.indexOf('.only(') > 0) {
grunt.log.errorlns(row);
grunt.fail.warn('found only statement in test: ' + spec);
}
});
});
});
};
| Add more patterns to no-only-test task | Add more patterns to no-only-test task
| JavaScript | agpl-3.0 | grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana | ---
+++
@@ -34,14 +34,17 @@
]);
grunt.registerTask('no-only-tests', function () {
- var files = grunt.file.expand('public/**/*_specs\.ts', 'public/**/*_specs\.js');
+ var files = grunt.file.expand(
+ 'public/**/*@(_specs|\.test)\.@(ts|js|tsx|jsx)',
+ 'packages/grafana-ui/**/*@(_specs|\.test)\.@(ts|js|tsx|jsx)'
+ );
files.forEach(function (spec) {
var rows = grunt.file.read(spec).split('\n');
rows.forEach(function (row) {
if (row.indexOf('.only(') > 0) {
grunt.log.errorlns(row);
- grunt.fail.warn('found only statement in test: ' + spec)
+ grunt.fail.warn('found only statement in test: ' + spec);
}
});
}); |
8d7f9f021d8fbd1469bd812591ff07be1262ac8e | .storybook/config.js | .storybook/config.js | import { configure, addDecorator } from '@storybook/react';
import { setDefaults } from '@storybook/addon-info';
import { setOptions } from '@storybook/addon-options';
import backgroundColor from 'react-storybook-decorator-background';
// addon-info
setDefaults({
header: false,
inline: true,
source: true,
propTablesExclude: [],
});
setOptions({
name: `Version ${process.env.__VERSION__}`,
url: 'https://teamleader.design'
});
addDecorator(backgroundColor(['#ffffff', '#e6f2ff', '#ffeecc', '#d3f3f3', '#ffe3d9', '#e1edfa', '#f1f0ff', '#2a3b4d']));
const req = require.context('../stories', true, /\.js$/);
configure(() => {
req.keys().forEach(filename => req(filename));
}, module);
| import { configure, addDecorator } from '@storybook/react';
import { setDefaults } from '@storybook/addon-info';
import { setOptions } from '@storybook/addon-options';
import backgroundColor from 'react-storybook-decorator-background';
// addon-info
setDefaults({
header: true,
inline: true,
source: true,
propTablesExclude: [],
});
setOptions({
name: `Version ${process.env.__VERSION__}`,
url: 'https://teamleader.design'
});
addDecorator(backgroundColor(['#ffffff', '#e6f2ff', '#ffeecc', '#d3f3f3', '#ffe3d9', '#e1edfa', '#f1f0ff', '#2a3b4d']));
const req = require.context('../stories', true, /\.js$/);
configure(() => {
req.keys().forEach(filename => req(filename));
}, module);
| Enable header for every story | Enable header for every story
| JavaScript | mit | teamleadercrm/teamleader-ui | ---
+++
@@ -5,7 +5,7 @@
// addon-info
setDefaults({
- header: false,
+ header: true,
inline: true,
source: true,
propTablesExclude: [], |
e1cbf4dbc5186e87a81d40b987f4944ddecfbee6 | babel.config.js | babel.config.js | const presets = [
[
"@babel/env",
{
targets: {
edge: "18",
firefox: "66",
chrome: "73",
safari: "12",
ie: "9"
}
},
],
];
module.exports = {presets};
| const presets = [
[
"@babel/env",
{
targets: {
edge: "18",
firefox: "66",
chrome: "73",
safari: "12",
ie: "11"
}
},
],
];
module.exports = {presets};
| Update babel IE target version to 11 | Update babel IE target version to 11
| JavaScript | mit | defunctzombie/commonjs-assert | ---
+++
@@ -7,7 +7,7 @@
firefox: "66",
chrome: "73",
safari: "12",
- ie: "9"
+ ie: "11"
}
},
], |
b79deb524fe24ae0e82bb1cf377b497657bba459 | public/scripts/run/visibilityEvents.js | public/scripts/run/visibilityEvents.js | "use strict";
angular
.module('app')
.run([
'$document',
'$rootScope',
function($document, $rootScope) {
function visibilitychanged() {
var d = $document[0],
isHidden = d.hidden || d.webkitHidden || d.mozHidden || d.msHidden;
$rootScope.$emit('visibility:change', isHidden);
}
$document.on('visibilitychange',visibilitychanged);
$document.on('webkitvisibilitychange', visibilitychanged);
$document.on('msvisibilitychange', visibilitychanged);
}
]); | "use strict";
angular
.module('app')
.run([
'$document',
'$rootScope',
function($document, $rootScope) {
var last;
function visibilitychanged() {
var d = $document[0],
isHidden = d.hidden || d.webkitHidden || d.mozHidden || d.msHidden;
if (isHidden !== last) {
$rootScope.$emit('visibility:change', isHidden);
last = isHidden;
}
}
$document.on('visibilitychange',visibilitychanged);
$document.on('webkitvisibilitychange', visibilitychanged);
$document.on('msvisibilitychange', visibilitychanged);
}
]); | Fix doubled event of visibility change | Fix doubled event of visibility change
| JavaScript | mit | xemle/spop-web,Schnouki/spop-web,Schnouki/spop-web,xemle/spop-web | ---
+++
@@ -6,10 +6,15 @@
'$document',
'$rootScope',
function($document, $rootScope) {
+ var last;
+
function visibilitychanged() {
var d = $document[0],
isHidden = d.hidden || d.webkitHidden || d.mozHidden || d.msHidden;
- $rootScope.$emit('visibility:change', isHidden);
+ if (isHidden !== last) {
+ $rootScope.$emit('visibility:change', isHidden);
+ last = isHidden;
+ }
}
$document.on('visibilitychange',visibilitychanged); |
892a30519995cbbbb05beb80c405fae2c1ccf155 | webpack.config.js | webpack.config.js | const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
app: './app.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
context: path.resolve(__dirname, 'src'),
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [['env', {modules: false}], 'stage-3'],
plugins: ['transform-runtime', 'check-es2015-constants']
}
}
},
{
test: /\.sass$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
},
{
test: /\.pug$/,
use: ['html-loader', 'pug-html-loader']
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
loader: 'file-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'app.pug',
filename: 'app.html'
}),
new ExtractTextPlugin({
filename: '[name].bundle.css',
})
],
devServer: {
publicPath: '/',
contentBase: path.join(__dirname, 'dist')
}
}
| const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
app: './app.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
context: path.resolve(__dirname, 'src'),
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [['env', {modules: false}], 'stage-3'],
plugins: ['transform-runtime', 'check-es2015-constants']
}
}
},
{
test: /\.sass$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
},
{
test: /\.pug$/,
use: ['html-loader', 'pug-html-loader']
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
loader: 'file-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'app.pug',
filename: 'app.html'
}),
new ExtractTextPlugin({
filename: '[name].bundle.css',
})
],
devServer: {
publicPath: '/',
contentBase: path.join(__dirname, 'dist')
},
devtool: "source-map"
}
| Add source maps to get better debugging in the browser | Add source maps to get better debugging in the browser
| JavaScript | mit | javierportillo/webpack-starter,javierportillo/webpack-starter | ---
+++
@@ -59,5 +59,7 @@
devServer: {
publicPath: '/',
contentBase: path.join(__dirname, 'dist')
- }
+ },
+
+ devtool: "source-map"
} |
96d65ebacf80370c36ac80407ae38c3823294a0e | webpack.config.js | webpack.config.js | var webpack = require('webpack');
var fs = require('fs');
var config = {
entry: {
'app': './app/index.js'
},
devtool: 'source-map',
output: {
path: __dirname + '/dist',
filename: `[name].[hash].js`,
publicPath: __dirname + '/dist'
},
module: {
loaders: [
{
test: /(\.js)$/,
loader: 'babel',
exclude: /(node_modules)/,
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins: [
function() {
this.plugin("done", function(stats) {
const hash = stats.toJson().hash;
fs.readFile('./index.html', 'utf8', function (err,data) {
if (err) {
return console.log('ERR', err);
}
var result = data.replace(/dist\/app.*.js/g, `dist/app.${hash}.js`);
fs.writeFile('./index.html', result, 'utf8', function (err) {
if (err) return console.log('ERR', err);
});
});
});
}
]
};
module.exports = config;
| var webpack = require('webpack');
var fs = require('fs');
var config = {
entry: {
'app': './app/index.js'
},
devtool: 'source-map',
output: {
path: __dirname + '/dist',
filename: `[name].[hash].js`,
publicPath: __dirname + '/dist'
},
module: {
loaders: [
{
test: /(\.js)$/,
loader: 'babel',
exclude: /(node_modules)/,
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins: [
function() {
this.plugin("compile", function() {
require( 'child_process' ).exec('rm -rf ./dist');
});
this.plugin("done", function(stats) {
const hash = stats.toJson().hash;
fs.readFile('./index.html', 'utf8', function (err,data) {
if (err) {
return console.log('ERR', err);
}
var result = data.replace(/dist\/app.*.js/g, `dist/app.${hash}.js`);
fs.writeFile('./index.html', result, 'utf8', function (err) {
if (err) return console.log('ERR', err);
});
});
});
}
]
};
module.exports = config;
| Clear dist on every build | Clear dist on every build
| JavaScript | mit | bsingr/mastermind,bsingr/mastermind | ---
+++
@@ -25,6 +25,9 @@
},
plugins: [
function() {
+ this.plugin("compile", function() {
+ require( 'child_process' ).exec('rm -rf ./dist');
+ });
this.plugin("done", function(stats) {
const hash = stats.toJson().hash;
fs.readFile('./index.html', 'utf8', function (err,data) { |
d0758e87e20d9a8996a648fa197c10aec62480ca | lib/server-factory-https.js | lib/server-factory-https.js | module.exports = ServerFactory => class HttpsServerFactory extends ServerFactory {
create (options) {
const fs = require('fs')
const https = require('https')
const t = require('typical')
const serverOptions = {}
if (options.pfx) {
serverOptions.pfx = fs.readFileSync(options.pfx)
} else {
if (!(options.key && options.cert)) {
serverOptions.key = this.getDefaultKeyPath()
serverOptions.cert = this.getDefaultCertPath()
}
serverOptions.key = fs.readFileSync(serverOptions.key, 'utf8')
serverOptions.cert = fs.readFileSync(serverOptions.cert, 'utf8')
}
if (t.isDefined(options.maxConnections)) serverOptions.maxConnections = options.maxConnections
if (t.isDefined(options.keepAliveTimeout)) serverOptions.keepAliveTimeout = options.keepAliveTimeout
this.emit('verbose', 'server.config', serverOptions)
return https.createServer(serverOptions)
}
}
| module.exports = ServerFactory => class HttpsServerFactory extends ServerFactory {
create (options) {
const fs = require('fs')
const https = require('https')
const t = require('typical')
const serverOptions = {}
if (options.pfx) {
serverOptions.pfx = fs.readFileSync(options.pfx)
} else {
if (!(options.key && options.cert)) {
serverOptions.key = this.getDefaultKeyPath()
serverOptions.cert = this.getDefaultCertPath()
} else {
serverOptions.key = fs.readFileSync(options.key, 'utf8')
serverOptions.cert = fs.readFileSync(options.cert, 'utf8')
}
}
if (t.isDefined(options.maxConnections)) serverOptions.maxConnections = options.maxConnections
if (t.isDefined(options.keepAliveTimeout)) serverOptions.keepAliveTimeout = options.keepAliveTimeout
this.emit('verbose', 'server.config', serverOptions)
return https.createServer(serverOptions)
}
}
| Fix key and cert file params when using personal version | Fix key and cert file params when using personal version
| JavaScript | mit | lwsjs/lws | ---
+++
@@ -10,9 +10,10 @@
if (!(options.key && options.cert)) {
serverOptions.key = this.getDefaultKeyPath()
serverOptions.cert = this.getDefaultCertPath()
+ } else {
+ serverOptions.key = fs.readFileSync(options.key, 'utf8')
+ serverOptions.cert = fs.readFileSync(options.cert, 'utf8')
}
- serverOptions.key = fs.readFileSync(serverOptions.key, 'utf8')
- serverOptions.cert = fs.readFileSync(serverOptions.cert, 'utf8')
}
if (t.isDefined(options.maxConnections)) serverOptions.maxConnections = options.maxConnections
if (t.isDefined(options.keepAliveTimeout)) serverOptions.keepAliveTimeout = options.keepAliveTimeout |
d8d9d6772e72e4d52245a233b1fa40f01d923b44 | webpack.config.js | webpack.config.js | const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const Dotenv = require('dotenv-webpack');
module.exports = {
entry: {
'facebook-messenger/handler': './src/facebook-messenger/handler.js',
},
target: 'node',
externals: [
'aws-sdk'
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
},
{ test: /\.json/, loader: 'json-loader' }
]
},
plugins: [
new CopyWebpackPlugin([
{ from: '.env' }
]),
new Dotenv({
safe: true
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
unused: true,
dead_code: true,
warnings: false,
drop_debugger: true
}
})
],
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, '.webpack'),
filename: '[name].js'
},
devtool: "cheap-module-source-map"
};
| const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const Dotenv = require('dotenv-webpack');
module.exports = {
entry: {
'facebook-messenger/handler': './src/facebook-messenger/handler.js',
},
target: 'node',
externals: [
'aws-sdk'
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
},
{ test: /\.json/, loader: 'json-loader' }
]
},
plugins: [
new CopyWebpackPlugin([
{ from: '.env' }
]),
new Dotenv({
safe: true
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
unused: true,
dead_code: true,
warnings: false,
drop_debugger: true
}
})
],
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, '.webpack'),
filename: '[name].js'
},
devtool: "source-map"
};
| Use full source map in production | Use full source map in production
| JavaScript | mit | kehitysto/coaching-chatbot,kehitysto/coaching-chatbot | ---
+++
@@ -49,5 +49,5 @@
path: path.join(__dirname, '.webpack'),
filename: '[name].js'
},
- devtool: "cheap-module-source-map"
+ devtool: "source-map"
}; |
112aec851eb4c6f85ee4c365f663adc2bc80cb0b | dangerfile.js | dangerfile.js | import { message, danger } from "danger"
message(":tada:, this worked @" + danger.github.pr.user.login)
| import { message, danger } from "danger";
import prettier from 'prettier';
const srcDir = `${__dirname}/src/**/*.js`;
const options = {
singleQuote: true,
printWidth: 100
};
if (prettier.check(srcDir, options)) {
message(':tada: Your code is formatted correctly');
} else {
warn('You haven\'t formated the code using prettier. Please run `npm run format` before merging the PR');
} | Check if src dir has been formatted | Check if src dir has been formatted
| JavaScript | mit | ldabiralai/simulado | ---
+++
@@ -1,2 +1,14 @@
-import { message, danger } from "danger"
-message(":tada:, this worked @" + danger.github.pr.user.login)
+import { message, danger } from "danger";
+import prettier from 'prettier';
+
+const srcDir = `${__dirname}/src/**/*.js`;
+const options = {
+ singleQuote: true,
+ printWidth: 100
+};
+
+if (prettier.check(srcDir, options)) {
+ message(':tada: Your code is formatted correctly');
+} else {
+ warn('You haven\'t formated the code using prettier. Please run `npm run format` before merging the PR');
+} |
a2940a6db57615f745b59e8e061ef48993de9918 | addon/index.js | addon/index.js | // this Proxy handler will be used to preserve the unaltered behavior of the window global by default
const doNothingHandler = {
get(target, prop) {
const value = Reflect.get(target, prop);
// make sure the function receives the original window as the this context! (e.g. alert will throw an invalid invocation error)
if (typeof window[prop] === 'function') {
return new Proxy(value, {
apply(t, _thisArg, argumentsList) {
return Reflect.apply(value, target, argumentsList);
}
});
}
return value;
},
set: Reflect.set,
has: Reflect.has,
deleteProperty: Reflect.deleteProperty
}
let currentHandler = doNothingHandler;
// private function to replace the default handler in tests
export function _setCurrentHandler(handler = doNothingHandler) {
currentHandler = handler;
}
const proxyHandler = {
get() {
return currentHandler.get(...arguments);
},
set() {
return currentHandler.set(...arguments);
},
has() {
return currentHandler.has(...arguments);
},
deleteProperty() {
return currentHandler.deleteProperty(...arguments);
},
}
export default new Proxy(window, proxyHandler);
| import { DEBUG } from '@glimmer/env';
let exportedWindow;
let _setCurrentHandler;
if (DEBUG) {
// this Proxy handler will be used to preserve the unaltered behavior of the window global by default
const doNothingHandler = {
get(target, prop) {
const value = Reflect.get(target, prop);
// make sure the function receives the original window as the this context! (e.g. alert will throw an invalid invocation error)
if (typeof value === 'function') {
return new Proxy(value, {
apply(t, _thisArg, argumentsList) {
return Reflect.apply(value, target, argumentsList);
}
});
}
return value;
},
set: Reflect.set,
has: Reflect.has,
deleteProperty: Reflect.deleteProperty
}
let currentHandler = doNothingHandler;
// private function to replace the default handler in tests
_setCurrentHandler = (handler = doNothingHandler) => currentHandler = handler;
const proxyHandler = {
get() {
return currentHandler.get(...arguments);
},
set() {
return currentHandler.set(...arguments);
},
has() {
return currentHandler.has(...arguments);
},
deleteProperty() {
return currentHandler.deleteProperty(...arguments);
},
}
exportedWindow = new Proxy(window, proxyHandler);
} else {
exportedWindow = window;
}
export default exportedWindow;
export { _setCurrentHandler };
| Exclude Proxy code from production build | Exclude Proxy code from production build
| JavaScript | mit | kaliber5/ember-window-mock,kaliber5/ember-window-mock | ---
+++
@@ -1,46 +1,54 @@
-// this Proxy handler will be used to preserve the unaltered behavior of the window global by default
-const doNothingHandler = {
- get(target, prop) {
- const value = Reflect.get(target, prop);
+import { DEBUG } from '@glimmer/env';
- // make sure the function receives the original window as the this context! (e.g. alert will throw an invalid invocation error)
- if (typeof window[prop] === 'function') {
- return new Proxy(value, {
- apply(t, _thisArg, argumentsList) {
- return Reflect.apply(value, target, argumentsList);
- }
- });
- }
+let exportedWindow;
+let _setCurrentHandler;
- return value;
- },
- set: Reflect.set,
- has: Reflect.has,
- deleteProperty: Reflect.deleteProperty
+if (DEBUG) {
+ // this Proxy handler will be used to preserve the unaltered behavior of the window global by default
+ const doNothingHandler = {
+ get(target, prop) {
+ const value = Reflect.get(target, prop);
+
+ // make sure the function receives the original window as the this context! (e.g. alert will throw an invalid invocation error)
+ if (typeof value === 'function') {
+ return new Proxy(value, {
+ apply(t, _thisArg, argumentsList) {
+ return Reflect.apply(value, target, argumentsList);
+ }
+ });
+ }
+
+ return value;
+ },
+ set: Reflect.set,
+ has: Reflect.has,
+ deleteProperty: Reflect.deleteProperty
+ }
+
+ let currentHandler = doNothingHandler;
+
+ // private function to replace the default handler in tests
+ _setCurrentHandler = (handler = doNothingHandler) => currentHandler = handler;
+
+ const proxyHandler = {
+ get() {
+ return currentHandler.get(...arguments);
+ },
+ set() {
+ return currentHandler.set(...arguments);
+ },
+ has() {
+ return currentHandler.has(...arguments);
+ },
+ deleteProperty() {
+ return currentHandler.deleteProperty(...arguments);
+ },
+ }
+
+ exportedWindow = new Proxy(window, proxyHandler);
+} else {
+ exportedWindow = window;
}
-
-let currentHandler = doNothingHandler;
-
-// private function to replace the default handler in tests
-export function _setCurrentHandler(handler = doNothingHandler) {
- currentHandler = handler;
-}
-
-
-const proxyHandler = {
- get() {
- return currentHandler.get(...arguments);
- },
- set() {
- return currentHandler.set(...arguments);
- },
- has() {
- return currentHandler.has(...arguments);
- },
- deleteProperty() {
- return currentHandler.deleteProperty(...arguments);
- },
-}
-
-export default new Proxy(window, proxyHandler);
+export default exportedWindow;
+export { _setCurrentHandler }; |
876827176d608677adce254c9cc3c957abbcb5f2 | bin/sass-lint.js | bin/sass-lint.js | #!/usr/bin/env node
'use strict';
var program = require('commander'),
meta = require('../package.json'),
lint = require('../index');
var detects;
program
.version(meta.version)
.usage('[options] \'<file or glob>\'')
.option('-q, --no-exit', 'do not exit on errors')
.parse(process.argv);
detects = lint.lintFiles(program.args[0]);
detects = lint.format(detects);
lint.outputResults(detects);
if (program.exit) {
lint.failOnError(detects);
}
| #!/usr/bin/env node
'use strict';
var program = require('commander'),
meta = require('../package.json'),
lint = require('../index');
var detects,
formatted;
program
.version(meta.version)
.usage('[options] \'<file or glob>\'')
.option('-q, --no-exit', 'do not exit on errors')
.parse(process.argv);
detects = lint.lintFiles(program.args[0]);
formatted = lint.format(detects);
lint.outputResults(formatted);
if (program.exit) {
lint.failOnError(detects);
}
| Fix fail on error for CLI | :bug: Fix fail on error for CLI
| JavaScript | mit | skovhus/sass-lint,benthemonkey/sass-lint,zallek/sass-lint,sasstools/sass-lint,MethodGrab/sass-lint,donabrams/sass-lint,zaplab/sass-lint,joshuacc/sass-lint,srowhani/sass-lint,sktt/sass-lint,carsonmcdonald/sass-lint,Snugug/sass-lint,bgriffith/sass-lint,DanPurdy/sass-lint,srowhani/sass-lint,sasstools/sass-lint,alansouzati/sass-lint,ngryman/sass-lint,flacerdk/sass-lint,Dru89/sass-lint | ---
+++
@@ -5,7 +5,8 @@
meta = require('../package.json'),
lint = require('../index');
-var detects;
+var detects,
+ formatted;
program
.version(meta.version)
@@ -15,9 +16,9 @@
detects = lint.lintFiles(program.args[0]);
-detects = lint.format(detects);
+formatted = lint.format(detects);
-lint.outputResults(detects);
+lint.outputResults(formatted);
if (program.exit) {
lint.failOnError(detects); |
11a17e6f8655275a75fd0c9be796440e3a2d43c2 | browser/conn.js | browser/conn.js | const MuxDemux = require('mux-demux')
const debug = require('../debug').sub('shoe')
const pull = require('pull-stream')
const stps = require('stream-to-pull-stream')
const psts = require('pull-stream-to-stream')
const EE = require('events').EventEmitter
exports = module.exports = new EE
const conn = require('reconnect-core')(require('shoe'))(require('client-reloader')(function(stream) {
const mx = MuxDemux()
stream.pipe(mx).pipe(stream)
mx.source = function(meta) {
return stps.source(mx.createReadStream(meta))
}
mx.sink = function(meta) {
return stps.sink(mx.createWriteStream(meta))
}
mx.duplex = function(meta) {
const stream = mx.createStream(meta)
return {
sink: stps.sink(stream),
source: stps.source(stream)
}
}
mx.through = pull.Through(function(read, meta) {
const stream = mx.createStream(meta)
psts(read).pipe(stream)
return stps.source(stream)
})
exports.emit('connect', mx)
})).connect('/shoe') | const MuxDemux = require('mux-demux')
const debug = require('../debug').sub('shoe')
const pull = require('pull-stream')
const stps = require('stream-to-pull-stream')
const psts = require('pull-stream-to-stream')
const EE = require('events').EventEmitter
exports = module.exports = new EE
const conn = require('reconnect-core')(require('shoe'))(require('client-reloader')(function(stream) {
const mx = MuxDemux()
stream.pipe(mx).pipe(stream)
mx.source = function(meta) {
return stps.source(mx.createReadStream(meta))
}
mx.sink = function(meta) {
return stps.sink(mx.createWriteStream(meta))
}
mx.duplex = function(meta) {
const stream = mx.createStream(meta)
return {
sink: stps.sink(stream),
source: stps.source(stream)
}
}
mx.through = pull.Through(function(read, meta) {
const stream = mx.createStream(meta)
psts(read).pipe(stream)
return stps.source(stream)
})
pull(
mx.source('reset'),
pull.drain(function() {
window.location.reload()
})
)
exports.emit('connect', mx)
})).connect('/shoe') | Make the client use the reset channel (Let the server reload the client) | Make the client use the reset channel (Let the server reload the client)
| JavaScript | mit | CoderPuppy/movie-voting.js,CoderPuppy/movie-voting.js,CoderPuppy/movie-voting.js | ---
+++
@@ -33,5 +33,12 @@
return stps.source(stream)
})
+ pull(
+ mx.source('reset'),
+ pull.drain(function() {
+ window.location.reload()
+ })
+ )
+
exports.emit('connect', mx)
})).connect('/shoe') |
5cd8fcfc08aa1f68a3e7b07654bf9647e8b46032 | app/assets/javascripts/angular/services/url_config.js | app/assets/javascripts/angular/services/url_config.js | angular.module("Prometheus.services").factory('UrlConfigDecoder', function($location) {
return function(defaultHash) {
var hash = $location.hash() || defaultHash;
if (!hash) {
return {};
}
// Decodes UTF-8
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64.btoa#Unicode_Strings
var configJSON = unescape(decodeURIComponent(window.atob(hash)));
var config = JSON.parse(configJSON);
return config;
};
});
angular.module("Prometheus.services").factory('UrlHashEncoder', ["UrlConfigDecoder", function(UrlConfigDecoder) {
return function(config) {
var urlConfig = UrlConfigDecoder();
for (var o in config) {
urlConfig[o] = config[o];
}
var configJSON = JSON.stringify(urlConfig);
// Encodes UTF-8
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64.btoa#Unicode_Strings
return window.btoa(encodeURIComponent(escape(configJSON)));
};
}]);
angular.module("Prometheus.services").factory('UrlConfigEncoder', ["$location", "UrlHashEncoder", function($location, UrlHashEncoder) {
return function(config) {
$location.hash(UrlHashEncoder(config));
};
}]);
angular.module("Prometheus.services").factory('UrlVariablesDecoder', function($location) {
return function() {
return $location.search();
};
});
| angular.module("Prometheus.services").factory('UrlConfigDecoder', function($location) {
return function(defaultHash) {
var hash = $location.hash() || defaultHash;
if (!hash) {
return {};
}
// Decodes UTF-8.
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64.btoa#Unicode_Strings
var configJSON = unescape(decodeURIComponent(window.atob(hash)));
var config = JSON.parse(configJSON);
return config;
};
});
angular.module("Prometheus.services").factory('UrlHashEncoder', ["UrlConfigDecoder", function(UrlConfigDecoder) {
return function(config) {
var urlConfig = UrlConfigDecoder();
for (var o in config) {
urlConfig[o] = config[o];
}
var configJSON = JSON.stringify(urlConfig);
// Encodes UTF-8.
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64.btoa#Unicode_Strings
return window.btoa(encodeURIComponent(escape(configJSON)));
};
}]);
angular.module("Prometheus.services").factory('UrlConfigEncoder', ["$location", "UrlHashEncoder", function($location, UrlHashEncoder) {
return function(config) {
$location.hash(UrlHashEncoder(config));
};
}]);
angular.module("Prometheus.services").factory('UrlVariablesDecoder', function($location) {
return function() {
return $location.search();
};
});
| Add periods to end of encode/decode comments. | Add periods to end of encode/decode comments.
| JavaScript | apache-2.0 | thooams/promdash,alonpeer/promdash,lborguetti/promdash,jonnenauha/promdash,juliusv/promdash,jmptrader/promdash,alonpeer/promdash,prometheus/promdash,jonnenauha/promdash,thooams/promdash,thooams/promdash,jonnenauha/promdash,juliusv/promdash,thooams/promdash,jmptrader/promdash,alonpeer/promdash,juliusv/promdash,juliusv/promdash,jmptrader/promdash,prometheus/promdash,jonnenauha/promdash,lborguetti/promdash,jmptrader/promdash,lborguetti/promdash,prometheus/promdash,prometheus/promdash,alonpeer/promdash,lborguetti/promdash | ---
+++
@@ -4,7 +4,7 @@
if (!hash) {
return {};
}
- // Decodes UTF-8
+ // Decodes UTF-8.
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64.btoa#Unicode_Strings
var configJSON = unescape(decodeURIComponent(window.atob(hash)));
var config = JSON.parse(configJSON);
@@ -19,7 +19,7 @@
urlConfig[o] = config[o];
}
var configJSON = JSON.stringify(urlConfig);
- // Encodes UTF-8
+ // Encodes UTF-8.
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64.btoa#Unicode_Strings
return window.btoa(encodeURIComponent(escape(configJSON)));
}; |
dfb21cd44ae2c0d1dd70b4a2253839c98daa1683 | src/clusterpost-auth/index.js | src/clusterpost-auth/index.js | var Boom = require('boom');
exports.register = function (server, conf, next) {
const validate = function(req, decodedToken, callback){
var exs = server.methods.executionserver.getExecutionServer(decodedToken.executionserver);
if(exs){
exs.scope = ['executionserver'];
callback(undefined, true, exs);
}else{
callback(Boom.unauthorized(exs));
}
}
conf.validate = validate;
return require('hapi-jwt-couch').register(server, conf, next);
};
exports.register.attributes = {
pkg: require('./package.json')
}; | var Boom = require('boom');
exports.register = function (server, conf, next) {
const validate = function(req, decodedToken, callback){
var exs = server.methods.executionserver.getExecutionServer(decodedToken.executionserver);
if(exs){
exs.scope = ['executionserver'];
callback(undefined, true, exs);
}else{
callback(Boom.unauthorized(exs));
}
}
conf.validate = validate;
server.register({
register: require('hapi-jwt-couch'),
options: conf
}, function(err){
if(err){
throw err;
}
server.method({
name: 'clusterpostauth.verify',
method: server.methods.jwtauth.verify,
options: {}
});
});
return next();
};
exports.register.attributes = {
pkg: require('./package.json')
}; | Use the register function from server when discovering the hapi-jwt-couch plugin | STYLE: Use the register function from server when discovering the hapi-jwt-couch plugin
| JavaScript | apache-2.0 | juanprietob/clusterpost,juanprietob/clusterpost,juanprietob/clusterpost | ---
+++
@@ -14,7 +14,24 @@
conf.validate = validate;
- return require('hapi-jwt-couch').register(server, conf, next);
+ server.register({
+ register: require('hapi-jwt-couch'),
+ options: conf
+ }, function(err){
+
+ if(err){
+ throw err;
+ }
+
+ server.method({
+ name: 'clusterpostauth.verify',
+ method: server.methods.jwtauth.verify,
+ options: {}
+ });
+
+ });
+
+ return next();
};
|
0719710c9d5c34be3a236028848db437269baf03 | server/plugins/bookmarks/validators.js | server/plugins/bookmarks/validators.js | // Validation for bookmark payloads.
'use strict';
var Hoek = require('hoek');
var Joi = require('joi');
var validators = {};
validators.bookmarkID = Joi.string().guid();
// Bookmark without ID. Used for the update and save payloads.
validators.bookmarkWithoutID = {
id: validators.bookmarkID.allow(null),
url: Joi.string()
.required()
.max(200, 'utf-8'),
title: Joi.string()
.max(200, 'utf-8')
.allow(null),
description: Joi.string().allow(null),
added_at: Joi.string().allow(null),
created_at: Joi.string().allow(null),
updated_at: Joi.string().allow(null),
};
// The full bookmark payload, requiring the ID.
validators.bookmark = Hoek.clone(validators.bookmarkWithoutID);
validators.bookmark.id = validators.bookmarkID.required();
module.exports = validators;
| // Validation for bookmark payloads.
'use strict';
var Hoek = require('hoek');
var Joi = require('joi');
var validators = {};
validators.bookmarkID = Joi.string().guid();
// Bookmark without ID. Used for the update and save payloads.
validators.bookmarkWithoutID = {
id: validators.bookmarkID.allow(null),
url: Joi.string()
.required()
.max(200, 'utf-8'),
title: Joi.string()
.max(200, 'utf-8')
.allow(null),
description: Joi.string().allow(null),
added_at: Joi.date().iso().allow(null),
created_at: Joi.date().iso().allow(null),
updated_at: Joi.date().iso().allow(null),
};
// The full bookmark payload, requiring the ID.
validators.bookmark = Hoek.clone(validators.bookmarkWithoutID);
validators.bookmark.id = validators.bookmarkID.required();
module.exports = validators;
| Validate date fields as ISO-format dates. | Validate date fields as ISO-format dates.
| JavaScript | isc | mikl/bookmeister,mikl/bookmeister | ---
+++
@@ -18,9 +18,9 @@
.max(200, 'utf-8')
.allow(null),
description: Joi.string().allow(null),
- added_at: Joi.string().allow(null),
- created_at: Joi.string().allow(null),
- updated_at: Joi.string().allow(null),
+ added_at: Joi.date().iso().allow(null),
+ created_at: Joi.date().iso().allow(null),
+ updated_at: Joi.date().iso().allow(null),
};
// The full bookmark payload, requiring the ID. |
8382d5c2147188eea4c1a78971a91abbfce32ef9 | src/app/auth/auth.controller.js | src/app/auth/auth.controller.js | (function() {
'use strict';
angular
.module('app.auth')
.controller('AuthController', AuthController);
AuthController.$inject = ['$location', 'authService'];
function AuthController($location, authService) {
var vm = this;
vm.user = {
email: '',
password: ''
};
vm.register = register;
vm.login = login;
function register(user) {
return authService.register(user)
.then(function() {
return vm.login(user);
})
.then(function() {
return authService.sendWelcomeEmail(user.email);
})
.catch(function(error) {
console.log(error);
});
}
function login(user) {
return authService.login(user)
.then(function(loggedInUser) {
console.log(loggedInUser);
$location.path('/waitlist');
})
.catch(function(error) {
console.log(error);
});
}
}
})(); | (function() {
'use strict';
angular
.module('app.auth')
.controller('AuthController', AuthController);
AuthController.$inject = ['$location', 'authService'];
function AuthController($location, authService) {
var vm = this;
vm.user = {
email: '',
password: ''
};
vm.error = null;
vm.register = register;
vm.login = login;
function register(user) {
return authService.register(user)
.then(function() {
return vm.login(user);
})
.then(function() {
return authService.sendWelcomeEmail(user.email);
})
.catch(function(error) {
vm.error = error;
});
}
function login(user) {
return authService.login(user)
.then(function() {
$location.path('/waitlist');
})
.catch(function(error) {
vm.error = error;
});
}
}
})(); | Set vm.error in register and login on AuthController. | Set vm.error in register and login on AuthController.
| JavaScript | mit | anthonybrown/angular-course-demo-app-v2,anthonybrown/angular-course-demo-app-v2 | ---
+++
@@ -14,6 +14,7 @@
email: '',
password: ''
};
+ vm.error = null;
vm.register = register;
vm.login = login;
@@ -27,18 +28,17 @@
return authService.sendWelcomeEmail(user.email);
})
.catch(function(error) {
- console.log(error);
+ vm.error = error;
});
}
function login(user) {
return authService.login(user)
- .then(function(loggedInUser) {
- console.log(loggedInUser);
+ .then(function() {
$location.path('/waitlist');
})
.catch(function(error) {
- console.log(error);
+ vm.error = error;
});
}
} |
b71557376bb31512ba96a81621b5051166b01f60 | public/js/channel.js | public/js/channel.js | $(function() {
var $loadMore = $('#load-more');
if ($loadMore.length) {
var $spinner = $('#spinner');
function init() {
$spinner.hide();
$.ajaxPrefilter(function(options, _, xhr) {
if (!xhr.crossDomain) {
xhr.setRequestHeader('X-CSRF-Token', securityToken);
}
});
}
function updateUI() {
$(this).hide();
$spinner.show();
}
$loadMore.on('click', function() {
updateUI.call(this);
// $.ajax({
// url: '/api/videos',
// type: 'POST',
// dataType: 'json',
// complete: function() {
// $('#spinner').hide();
// }
// });
});
init();
}
});
| $(function() {
var $loadMore = $('#load-more');
if ($loadMore.length) {
var $spinner = $('#spinner');
var init = function() {
$spinner.hide();
$.ajaxPrefilter(function(options, _, xhr) {
if (!xhr.crossDomain) {
xhr.setRequestHeader('X-CSRF-Token', securityToken);
}
});
};
var updateUI = function() {
$(this).hide();
$spinner.show();
};
$loadMore.on('click', function() {
updateUI.call(this);
// $.ajax({
// url: '/api/videos',
// type: 'POST',
// dataType: 'json',
// complete: function() {
// $('#spinner').hide();
// }
// });
});
init();
}
});
| Change function declaration to function expression | Change function declaration to function expression
| JavaScript | mit | CreaturePhil/Usub,CreaturePhil/Usub | ---
+++
@@ -5,19 +5,19 @@
var $spinner = $('#spinner');
- function init() {
+ var init = function() {
$spinner.hide();
$.ajaxPrefilter(function(options, _, xhr) {
if (!xhr.crossDomain) {
xhr.setRequestHeader('X-CSRF-Token', securityToken);
}
});
- }
+ };
- function updateUI() {
+ var updateUI = function() {
$(this).hide();
$spinner.show();
- }
+ };
$loadMore.on('click', function() {
updateUI.call(this);
@@ -34,3 +34,4 @@
init();
}
});
+ |
d5855f3e4fc63f120af56a94f0842fae2ffd4871 | src/components/posts_index.js | src/components/posts_index.js | import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions';
class PostsIndex extends Component {
componentDidMount() {
this.props.fetchPosts();
}
renderPosts() {
return _.map(this.props.posts, post => {
return (
<li className="list-group-item">
{post.title}
</li>
);
});
}
render() {
return (
<div>
<h3>Posts</h3>
<ul className="list-group">
{this.renderPosts()}
</ul>
</div>
);
}
}
function mapStateToProps(state) {
return { posts: state.posts };
}
export default connect(mapStateToProps, { fetchPosts })(PostsIndex); | import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions';
import { Link } from 'react-router-dom';
class PostsIndex extends Component {
componentDidMount() {
this.props.fetchPosts();
}
renderPosts() {
return _.map(this.props.posts, post => {
return (
<li className="list-group-item">
{post.title}
</li>
);
});
}
render() {
return (
<div>
<div className="text-xs-right">
<Link className="btn btn-primary" to="/posts/new">
Add a Post
</Link>
</div>
<h3>Posts</h3>
<ul className="list-group">
{this.renderPosts()}
</ul>
</div>
);
}
}
function mapStateToProps(state) {
return { posts: state.posts };
}
export default connect(mapStateToProps, { fetchPosts })(PostsIndex); | Add button to new post page | Add button to new post page
| JavaScript | mit | heatherpark/blog,heatherpark/blog | ---
+++
@@ -2,6 +2,7 @@
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions';
+import { Link } from 'react-router-dom';
class PostsIndex extends Component {
componentDidMount() {
@@ -21,6 +22,11 @@
render() {
return (
<div>
+ <div className="text-xs-right">
+ <Link className="btn btn-primary" to="/posts/new">
+ Add a Post
+ </Link>
+ </div>
<h3>Posts</h3>
<ul className="list-group">
{this.renderPosts()} |
de48510fa5b038cbdda7d2386bba0419af1b8542 | src/client/reducers/BoardReducer.js | src/client/reducers/BoardReducer.js | import initialState from './initialState';
import {
BOARD_REQUESTED,
BOARD_LOADED,
BOARD_DESTROYED,
BOARD_SCROLLED_BOTTOM
} from '../constants'
export default function (state = initialState.board, action) {
switch (action.type) {
case BOARD_REQUESTED:
return Object.assign({}, state, {
isFetching: true,
requestType: action.type // for logging error to user...?
})
case BOARD_LOADED:
return Object.assign({}, state, {
posts: action.payload,
isFetching: false
})
case BOARD_DESTROYED:
return Object.assign({}, state, {
posts: []
})
case BOARD_SCROLLED_BOTTOM:
return Object.assign({}, state, {
limit: action.payload
})
default:
return state
}
}
| import initialState from './initialState';
import {
BOARD_REQUESTED,
BOARD_LOADED,
BOARD_DESTROYED,
BOARD_SCROLLED_BOTTOM,
BOARD_FILTER
} from '../constants'
export default function (state = initialState.board, action) {
switch (action.type) {
case BOARD_REQUESTED:
return Object.assign({}, state, {
isFetching: true,
requestType: action.type // for logging error to user...?
})
case BOARD_LOADED:
return Object.assign({}, state, {
posts: action.payload,
isFetching: false
})
case BOARD_DESTROYED:
return Object.assign({}, state, {
posts: []
})
case BOARD_SCROLLED_BOTTOM:
return Object.assign({}, state, {
limit: action.payload
})
case BOARD_FILTER:
return Object.assign({}, state, {
filterWord: action.payload || null
})
default:
return state
}
}
| Add board reducer case for filtering | Add board reducer case for filtering
| JavaScript | mit | AdamSalma/Lurka,AdamSalma/Lurka | ---
+++
@@ -3,7 +3,8 @@
BOARD_REQUESTED,
BOARD_LOADED,
BOARD_DESTROYED,
- BOARD_SCROLLED_BOTTOM
+ BOARD_SCROLLED_BOTTOM,
+ BOARD_FILTER
} from '../constants'
export default function (state = initialState.board, action) {
@@ -31,6 +32,11 @@
limit: action.payload
})
+ case BOARD_FILTER:
+ return Object.assign({}, state, {
+ filterWord: action.payload || null
+ })
+
default:
return state
} |
9a9c348c05850beb1f3ad7a73bde54eb2d45bab1 | service/load-schemas.js | service/load-schemas.js | // This module loads and exposes an object of all available schemas, using
// the schema key as the object key.
//
// The schemas are loaded from the extension plugin directory. We therefore need
// to have a checkout of the extension alongside the web service in order to use
// this module.
'use strict';
let jsonfile = require('jsonfile');
let fs = require('fs');
let path = require('path');
let pluginDir = '../extension/src/plugins';
let dirs = getDirectories(pluginDir);
let schemas = {};
for (let dir of dirs) {
try {
let schema = jsonfile.readFileSync(`${pluginDir}/${dir}/schema.json`);
if (schema.hasOwnProperty('schema') && schema.schema.hasOwnProperty('key')) {
schemas[schema.schema.key] = schema;
} else {
console.log(`schema.json for plugin "${dir}" does not have a valid schema header. Skipping.`);
}
} catch (e) {
console.log(`Problem reading schema.json for plugin "${dir}". Skipping.`);
}
}
function getDirectories(srcpath) {
return fs.readdirSync(srcpath).filter(function(file) {
return fs.statSync(path.join(srcpath, file)).isDirectory();
});
}
module.exports = schemas;
| // This module loads and exposes an object of all available schemas, using
// the schema key as the object key. It adds the site metadata to the schema
// header for convenient access.
//
// The schemas and site metadata are loaded from the extension plugin directory.
// We therefore need to have a checkout of the extension alongside the web
// service in order to use this module.
'use strict';
let jsonfile = require('jsonfile');
let sitesDir = '../extension';
let pluginDir = '../extension/src/plugins';
let sites = jsonfile.readFileSync(`${sitesDir}/sites.json`);
let schemas = {};
for (let site of sites) {
try {
let schema = jsonfile.readFileSync(`${pluginDir}/${site.plugin}/schema.json`);
if (schema.hasOwnProperty('schema') && schema.schema.hasOwnProperty('key')) {
schemas[schema.schema.key] = schema;
schema.schema.site = site;
} else {
console.log(`schema.json for plugin "${site.plugin}" does not have a valid schema header. Skipping.`);
}
} catch (e) {
console.log(`Problem reading schema.json for plugin "${site.plugin}". Skipping. Error was: ${e}`);
}
}
module.exports = schemas;
| Use site metadata to find registered plugins/schemas. | Use site metadata to find registered plugins/schemas.
This simplifies loading schemas, and eliminates some dependencies.
We also stash site metadata in the schema object, since it's useful
for tests.
| JavaScript | cc0-1.0 | eloquence/freeyourstuff.cc,eloquence/freeyourstuff.cc | ---
+++
@@ -1,33 +1,27 @@
// This module loads and exposes an object of all available schemas, using
-// the schema key as the object key.
+// the schema key as the object key. It adds the site metadata to the schema
+// header for convenient access.
//
-// The schemas are loaded from the extension plugin directory. We therefore need
-// to have a checkout of the extension alongside the web service in order to use
-// this module.
+// The schemas and site metadata are loaded from the extension plugin directory.
+// We therefore need to have a checkout of the extension alongside the web
+// service in order to use this module.
'use strict';
let jsonfile = require('jsonfile');
-let fs = require('fs');
-let path = require('path');
+let sitesDir = '../extension';
let pluginDir = '../extension/src/plugins';
-let dirs = getDirectories(pluginDir);
+let sites = jsonfile.readFileSync(`${sitesDir}/sites.json`);
let schemas = {};
-for (let dir of dirs) {
- try {
- let schema = jsonfile.readFileSync(`${pluginDir}/${dir}/schema.json`);
- if (schema.hasOwnProperty('schema') && schema.schema.hasOwnProperty('key')) {
- schemas[schema.schema.key] = schema;
- } else {
- console.log(`schema.json for plugin "${dir}" does not have a valid schema header. Skipping.`);
+for (let site of sites) {
+ try {
+ let schema = jsonfile.readFileSync(`${pluginDir}/${site.plugin}/schema.json`);
+ if (schema.hasOwnProperty('schema') && schema.schema.hasOwnProperty('key')) {
+ schemas[schema.schema.key] = schema;
+ schema.schema.site = site;
+ } else {
+ console.log(`schema.json for plugin "${site.plugin}" does not have a valid schema header. Skipping.`);
+ }
+ } catch (e) {
+ console.log(`Problem reading schema.json for plugin "${site.plugin}". Skipping. Error was: ${e}`);
}
- } catch (e) {
- console.log(`Problem reading schema.json for plugin "${dir}". Skipping.`);
- }
}
-
-function getDirectories(srcpath) {
- return fs.readdirSync(srcpath).filter(function(file) {
- return fs.statSync(path.join(srcpath, file)).isDirectory();
- });
-}
-
module.exports = schemas; |
e53a2b05fc41bf36e85cc4a2fa297d77d29ed1d8 | app/assets/javascripts/home.js | app/assets/javascripts/home.js | <!--[if lt IE 9]>
document.createElement('video');
<!--[endif]-->
$(window).unload(function() {
$.rails.enableFormElements($($.rails.formSubmitSelector));
});
// Cool title effect for "community favorites"
$(window).load(function() {
// get the height of the hero
var pageHeight = $($('.hero')[0]).height();
// get the height including margins of the featured crops title
var titleHeight = $($('.explore-community-favorites')[0]).outerHeight(true);
// On resize, recalculate the above values
$(window).resize(function() {
pageHeight = $($('.hero')[0]).height();
titleHeight = $($('.explore-community-favorites')[0]).outerHeight(true);
})
$(window).scroll(function() {
updateTitleBackground($(window).scrollTop(), pageHeight, titleHeight);
})
});
// Darken the title background when the user scrolls to the featured crops header
function updateTitleBackground(scrollPos, pageHeight, titleHeight) {
$exploreCommunityFavoritesTitle = $($('.explore-community-favorites')[0]);
// The extra 1px lets smooth scrolling still trigger the change
if (scrollPos >= (pageHeight - titleHeight - 1)) {
$exploreCommunityFavoritesTitle.addClass('full-black');
}
else {
$exploreCommunityFavoritesTitle.removeClass('full-black');
}
}
| <!--[if lt IE 9]>
document.createElement('video');
<!--[endif]-->
$(window).unload(function() {
$.rails.enableFormElements($($.rails.formSubmitSelector));
});
// Cool title effect for "community favorites"
$(window).load(function() {
// get the height of the hero
var pageHeight = $($('.hero')[0]).height();
// get the height including margins of the featured crops title
var titleHeight = $($('.explore-community-favorites')[0]).outerHeight(true);
// On resize, recalculate the above values
$(window).resize(function() {
pageHeight = $($('.hero')[0]).height();
titleHeight = $($('.explore-community-favorites')[0]).outerHeight(true);
})
$(window).scroll(function() {
updateTitleBackground($(window).scrollTop(), pageHeight, titleHeight);
})
});
// Darken the title background when the user scrolls to the featured crops header
function updateTitleBackground(scrollPos, pageHeight, titleHeight) {
var exploreCommunityFavoritesTitle = $($('.explore-community-favorites')[0]);
// The extra 1px lets smooth scrolling still trigger the change
if (scrollPos >= (pageHeight - titleHeight - 1)) {
exploreCommunityFavoritesTitle.addClass('full-black');
}
else {
exploreCommunityFavoritesTitle.removeClass('full-black');
}
}
| Change var from jquery to normal js var | Change var from jquery to normal js var
| JavaScript | mit | tomazin/OpenFarm,tomazin/OpenFarm,roryaronson/OpenFarm,simonv3/OpenFarm,RickCarlino/OpenFarm,slacker87/OpenFarm,openfarmcc/OpenFarm,CloCkWeRX/OpenFarm,roryaronson/OpenFarm,tomazin/OpenFarm,roryaronson/OpenFarm,slacker87/OpenFarm,CloCkWeRX/OpenFarm,CloCkWeRX/OpenFarm,simonv3/OpenFarm,openfarmcc/OpenFarm,RickCarlino/OpenFarm,CloCkWeRX/OpenFarm,openfarmcc/OpenFarm,RickCarlino/OpenFarm,tomazin/OpenFarm,simonv3/OpenFarm,openfarmcc/OpenFarm,RickCarlino/OpenFarm,slacker87/OpenFarm | ---
+++
@@ -26,13 +26,13 @@
// Darken the title background when the user scrolls to the featured crops header
function updateTitleBackground(scrollPos, pageHeight, titleHeight) {
- $exploreCommunityFavoritesTitle = $($('.explore-community-favorites')[0]);
+ var exploreCommunityFavoritesTitle = $($('.explore-community-favorites')[0]);
// The extra 1px lets smooth scrolling still trigger the change
if (scrollPos >= (pageHeight - titleHeight - 1)) {
- $exploreCommunityFavoritesTitle.addClass('full-black');
+ exploreCommunityFavoritesTitle.addClass('full-black');
}
else {
- $exploreCommunityFavoritesTitle.removeClass('full-black');
+ exploreCommunityFavoritesTitle.removeClass('full-black');
}
}
|
69b467a039b0b8e9ae21d1d06025a793f6f7f865 | src/components/editor/EmbedBlock.js | src/components/editor/EmbedBlock.js | /* eslint-disable react/no-danger */
import React, { Component, PropTypes } from 'react'
import Block from './Block'
export function reloadPlayers() {
if (typeof window !== 'undefined' && window.embetter) {
window.embetter.reloadPlayers()
}
}
class EmbedBlock extends Component {
static propTypes = {
data: PropTypes.object,
}
static defaultProps = {
data: {},
}
componentDidMount() {
reloadPlayers()
}
componentDidUpdate() {
reloadPlayers()
}
render() {
const { data: { service, url, thumbnailLargeUrl, id } } = this.props
const children = typeof window !== 'undefined' ?
window.embetter.utils.playerHTML(
window.embetter.services[service],
url,
thumbnailLargeUrl,
id,
) :
null
return (
<Block {...this.props}>
<div
className="editable embed"
dangerouslySetInnerHTML={{ __html: children }}
/>
</Block>
)
}
}
export default EmbedBlock
| /* eslint-disable react/no-danger */
import React, { Component, PropTypes } from 'react'
import Block from './Block'
export function reloadPlayers() {
if (typeof window !== 'undefined' && window.embetter) {
window.embetter.reloadPlayers()
}
}
class EmbedBlock extends Component {
static propTypes = {
data: PropTypes.object,
}
static defaultProps = {
data: {},
}
componentDidMount() {
reloadPlayers()
}
componentDidUpdate() {
reloadPlayers()
}
render() {
const dataJS = this.props.data.toJS()
const { service, url, thumbnailLargeUrl, id } = dataJS
const children = typeof window !== 'undefined' ?
window.embetter.utils.playerHTML(
window.embetter.services[service],
url,
thumbnailLargeUrl,
id,
) :
null
return (
<Block {...this.props}>
<div
className="editable embed"
dangerouslySetInnerHTML={{ __html: children }}
/>
</Block>
)
}
}
export default EmbedBlock
| Fix an issue with embed previews. | Fix an issue with embed previews.
[Fixes #137488987](https://www.pivotaltracker.com/story/show/137488987)
[Fixes #137491203](https://www.pivotaltracker.com/story/show/137491203)
| JavaScript | mit | ello/webapp,ello/webapp,ello/webapp | ---
+++
@@ -28,7 +28,8 @@
}
render() {
- const { data: { service, url, thumbnailLargeUrl, id } } = this.props
+ const dataJS = this.props.data.toJS()
+ const { service, url, thumbnailLargeUrl, id } = dataJS
const children = typeof window !== 'undefined' ?
window.embetter.utils.playerHTML(
window.embetter.services[service], |
1dcacbc8a960279db61610185b7155719f5046d5 | find-core/src/main/public/static/js/find/app/pages.js | find-core/src/main/public/static/js/find/app/pages.js | /*
* Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define([
'find/app/find-pages',
'find/app/page/find-search',
'find/app/page/find-settings-page',
'i18n!find/nls/bundle'
], function(FindPages, FindSearch, SettingsPage) {
return FindPages.extend({
initializePages: function() {
this.pages = [
{
constructor: SettingsPage
, pageName: 'settings'
, classes: 'hide-from-non-useradmin'
}
];
}
});
});
| /*
* Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define([
'find/app/find-pages',
'find/app/page/find-settings-page',
'i18n!find/nls/bundle'
], function(FindPages, SettingsPage) {
return FindPages.extend({
initializePages: function() {
this.pages = [
{
constructor: SettingsPage
, pageName: 'settings'
, classes: 'hide-from-non-useradmin'
}
];
}
});
});
| Remove unnecessary import [rev: minor] | Remove unnecessary import [rev: minor]
| JavaScript | mit | hpautonomy/find,hpautonomy/find,LinkPowerHK/find,hpe-idol/find,hpe-idol/find,LinkPowerHK/find,hpe-idol/find,hpautonomy/find,LinkPowerHK/find,LinkPowerHK/find,hpe-idol/find,hpautonomy/find,hpe-idol/java-powerpoint-report,hpe-idol/java-powerpoint-report,LinkPowerHK/find,hpautonomy/find,hpe-idol/find | ---
+++
@@ -5,10 +5,9 @@
define([
'find/app/find-pages',
- 'find/app/page/find-search',
'find/app/page/find-settings-page',
'i18n!find/nls/bundle'
-], function(FindPages, FindSearch, SettingsPage) {
+], function(FindPages, SettingsPage) {
return FindPages.extend({
initializePages: function() { |
2e4fa079ee4b0a870ce3e1a530ffcfccecac7dfd | src/js/tael_sizing.js | src/js/tael_sizing.js | function resizeTaelContainer() {
$('.tael-container').css('bottom', 16);
}
$(document).ready(function () {
var header_bbox = $('.header')[0].getBoundingClientRect();
$('.tael-container').css('top', header_bbox.bottom + 8);
resizeTaelContainer();
$(window).resize(resizeTaelContainer);
});
| function resizeTaelContainer() {
var
header_bbox = $('.header')[0].getBoundingClientRect(),
tael_container = $('.tael-container');
tael_container.css('top', header_bbox.bottom);
tael_container.css('bottom', 16);
}
$(document).ready(function () {
resizeTaelContainer();
$(window).resize(resizeTaelContainer);
});
| Fix Tael container top resizing | Fix Tael container top resizing
| JavaScript | mit | hinsley-it/maestro,hinsley-it/maestro | ---
+++
@@ -1,10 +1,12 @@
function resizeTaelContainer() {
- $('.tael-container').css('bottom', 16);
+ var
+ header_bbox = $('.header')[0].getBoundingClientRect(),
+ tael_container = $('.tael-container');
+ tael_container.css('top', header_bbox.bottom);
+ tael_container.css('bottom', 16);
}
$(document).ready(function () {
- var header_bbox = $('.header')[0].getBoundingClientRect();
- $('.tael-container').css('top', header_bbox.bottom + 8);
resizeTaelContainer();
$(window).resize(resizeTaelContainer);
}); |
c9ecf996edac66be9997fccd353419a8e7f07235 | app/services/me.js | app/services/me.js | import Service from '@ember/service';
import { computed } from '@ember/object';
import { inject as service } from '@ember/service';
export default Service.extend({
session: service(),
init() {
let routeName = window.location.href.split('/').pop();
if (routeName == 'logout') {
if (this.get('session.isAuthenticated')) {
return this.get('session').invalidate();
}
}
this.set('data', computed('session.session.content.authenticated', function() {
// console.log('session', this.get('session.session.content.authenticated'));
return this.get('session.session.content.authenticated');
}));
}
});
| import Service from '@ember/service';
import { computed } from '@ember/object';
import { inject as service } from '@ember/service';
import ENV from '../config/environment';
import RSVP from 'rsvp';
export default Service.extend({
session: service(),
ajax: service(),
endpoint: `${ENV.APP.apiHost}/account/login`,
details: computed('data', function() {
let options = {
headers: {
'Authorization': this.get('data').access_token
},
method: 'GET'
};
let self = this;
return new RSVP.Promise((resolve, reject) => {
fetch(this.get('endpoint'), options).then((response) => {
return self.set('user', response);
}).catch(reject);
});
}),
init() {
let routeName = window.location.href.split('/').pop();
if (routeName == 'logout') {
if (this.get('session.isAuthenticated')) {
return this.get('session').invalidate();
}
}
this.set('data', computed('session.session.content.authenticated', function() {
// console.log('session', this.get('session.session.content.authenticated'));
let data = this.get('session.session.content.authenticated');
return data;
}));
}
});
| Add logged in user details | Add logged in user details
| JavaScript | agpl-3.0 | tenders-exposed/elvis-ember,tenders-exposed/elvis-ember | ---
+++
@@ -1,9 +1,29 @@
import Service from '@ember/service';
import { computed } from '@ember/object';
import { inject as service } from '@ember/service';
+import ENV from '../config/environment';
+import RSVP from 'rsvp';
export default Service.extend({
session: service(),
+ ajax: service(),
+ endpoint: `${ENV.APP.apiHost}/account/login`,
+
+ details: computed('data', function() {
+ let options = {
+ headers: {
+ 'Authorization': this.get('data').access_token
+ },
+ method: 'GET'
+ };
+
+ let self = this;
+ return new RSVP.Promise((resolve, reject) => {
+ fetch(this.get('endpoint'), options).then((response) => {
+ return self.set('user', response);
+ }).catch(reject);
+ });
+ }),
init() {
let routeName = window.location.href.split('/').pop();
@@ -15,7 +35,11 @@
this.set('data', computed('session.session.content.authenticated', function() {
// console.log('session', this.get('session.session.content.authenticated'));
- return this.get('session.session.content.authenticated');
+ let data = this.get('session.session.content.authenticated');
+ return data;
}));
+
+
+
}
}); |
73cf297ca3b83bbdc73f8122423fba7d2ea95926 | src/containers/BoardSetContainer.js | src/containers/BoardSetContainer.js | import { connect } from 'react-redux';
import { buildJKFPlayerFromState } from "../playerUtils";
import { inputMove, changeComments } from '../actions';
import BoardSet from '../components/BoardSet';
const mapStateToProps = (state) => {
console.log(state);
const player = buildJKFPlayerFromState(state);
return {
player: player,
reversed: state.reversed,
}
};
const mapDispatchToProps = {
onInputMove: inputMove,
onChangeComments: changeComments,
};
const BoardSetContainer = connect(
mapStateToProps,
mapDispatchToProps
)(BoardSet);
export default BoardSetContainer;
| import { connect } from 'react-redux';
import { buildJKFPlayerFromState } from "../playerUtils";
import { inputMove, changeComments } from '../actions';
import BoardSet from '../components/BoardSet';
const mapStateToProps = (state) => {
//console.log(state);
const player = buildJKFPlayerFromState(state);
return {
player: player,
reversed: state.reversed,
}
};
const mapDispatchToProps = {
onInputMove: inputMove,
onChangeComments: changeComments,
};
const BoardSetContainer = connect(
mapStateToProps,
mapDispatchToProps
)(BoardSet);
export default BoardSetContainer;
| Comment out console.log for debug | Comment out console.log for debug
| JavaScript | mit | orangain/kifu-notebook,orangain/kifu-notebook,orangain/kifu-notebook,orangain/kifu-notebook,orangain/kifu-notebook | ---
+++
@@ -5,7 +5,7 @@
import BoardSet from '../components/BoardSet';
const mapStateToProps = (state) => {
- console.log(state);
+ //console.log(state);
const player = buildJKFPlayerFromState(state);
return { |
8e0c34795e11dc229a87277379de9b8da4afa9f4 | src-server/socket.io-wrapper/server.js | src-server/socket.io-wrapper/server.js | import SocketIONamespace from "./namespace";
export default class SocketIOServer {
constructor(io) {
this._io = io;
this._sockets = this.of("/");
this._nsps = Object.create(null);
}
get rawServer() {
return this._io;
}
//
// Delegation methods
//
of(name, fn) {
var nsp = this._nsps[name];
if (! nsp) {
nsp = new SocketIONamespace(this._io.of(name, fn));
this._nsps[name] = nsp;
}
return nsp;
}
}
// pass through methods
[
"serveClient", "set", "path", "adapter", "origins",
"listen", "attach", "bind", "onconnection",
/* "of", */ "close"
].forEach(methodName => {
SocketIOServer.prototype[methodName] = function (...args) {
this._io[methodName](...args);
return this;
};
});
[
/* "on" */, "to", "in", "use", "emit", "send",
"write", "clients", "compress",
// mayajs-socketio-wrapper methods
"on", "off", "receive", "offReceive"
].forEach(methodName => {
SocketIOServer.prototype[methodName] = function (...args) {
return this._sockets[methodName](...args);
}
});
| import SocketIONamespace from "./namespace";
export default class SocketIOServer {
constructor(io) {
this._io = io;
this._nsps = Object.create(null);
this._sockets = this.of("/");
}
get rawServer() {
return this._io;
}
//
// Delegation methods
//
of(name, fn) {
var nsp = this._nsps[name];
if (! nsp) {
nsp = new SocketIONamespace(this._io.of(name, fn));
this._nsps[name] = nsp;
}
return nsp;
}
}
// pass through methods
[
"serveClient", "set", "path", "adapter", "origins",
"listen", "attach", "bind", "onconnection",
/* "of", */ "close"
].forEach(methodName => {
SocketIOServer.prototype[methodName] = function (...args) {
this._io[methodName](...args);
return this;
};
});
[
/* "on" */, "to", "in", "use", "emit", "send",
"write", "clients", "compress",
// mayajs-socketio-wrapper methods
"on", "off", "receive", "offReceive"
].forEach(methodName => {
SocketIOServer.prototype[methodName] = function (...args) {
return this._sockets[methodName](...args);
}
});
| Fix annot read property '/' of undefined | Fix annot read property '/' of undefined
| JavaScript | mit | Ragg-/rektia,Ragg-/maya.js,Ragg-/rektia,Ragg-/rektia,Ragg-/maya.js | ---
+++
@@ -3,8 +3,8 @@
export default class SocketIOServer {
constructor(io) {
this._io = io;
+ this._nsps = Object.create(null);
this._sockets = this.of("/");
- this._nsps = Object.create(null);
}
|
37e4796c4fd9e7ac3c81f4e75ddebb29ad85c680 | tasks/register/linkAssetsBuildProd.js | tasks/register/linkAssetsBuildProd.js | /**
* `linkAssetsBuildProd`
*
* ---------------------------------------------------------------
*
* This Grunt tasklist is not designed to be used directly-- rather
* it is a helper called by the `buildProd` tasklist.
*
* For more information see:
* http://sailsjs.org/documentation/anatomy/my-app/tasks/register/link-assets-build-prod-js
*
*/
module.exports = function(grunt) {
grunt.registerTask('linkAssetsBuildProd', [
'sails-linker:prodJsRelative',
'sails-linker:prodStylesRelative',
'sails-linker:devTpl',
'sails-linker:prodJsRelativeJade',
'sails-linker:prodStylesRelativeJade',
'sails-linker:devTplJade'
]);
};
| /**
* `linkAssetsBuildProd`
*
* ---------------------------------------------------------------
*
* This Grunt tasklist is not designed to be used directly-- rather
* it is a helper called by the `buildProd` tasklist.
*
* For more information see:
* http://sailsjs.org/documentation/anatomy/my-app/tasks/register/link-assets-build-prod-js
*
*/
module.exports = function(grunt) {
grunt.registerTask('linkAssetsBuildProd', [
'sails-linker:prodJsRelative',
'sails-linker:prodStylesRelative',
// 'sails-linker:devTpl',
'sails-linker:prodJsRelativeJade',
// 'sails-linker:prodStylesRelativeJade',
// 'sails-linker:devTplJade'
]);
};
| Clean up some prod tasks | Clean up some prod tasks
| JavaScript | mit | pantsel/konga,pantsel/konga,pantsel/konga | ---
+++
@@ -14,9 +14,9 @@
grunt.registerTask('linkAssetsBuildProd', [
'sails-linker:prodJsRelative',
'sails-linker:prodStylesRelative',
- 'sails-linker:devTpl',
+ // 'sails-linker:devTpl',
'sails-linker:prodJsRelativeJade',
- 'sails-linker:prodStylesRelativeJade',
- 'sails-linker:devTplJade'
+ // 'sails-linker:prodStylesRelativeJade',
+ // 'sails-linker:devTplJade'
]);
}; |
12be4f8e9b60a9577246ed0fce6b5c47f28f01d3 | src/redux-dialog.js | src/redux-dialog.js | import React, { Component } from 'react';
import { connect } from 'react-redux'
import Modal from 'react-modal'
import { closeDialog } from './actions';
const reduxDialog = (dialogProps) => {
const {
name,
onAfterOpen = () => {},
onRequestClose = () => {}
} = dialogProps;
return((WrappedComponent) => {
class ReduxDialog extends Component {
render () {
return (
<Modal {...dialogProps} {...this.props}>
<WrappedComponent {...this.props} />
</Modal>
);
}
}
const mapStateToProps = (state) => ({
isOpen: (state.dialogs.dialogs
&& state.dialogs.dialogs[name]
&& state.dialogs.dialogs[name].isOpen) || false
})
const mapDispatchToProps = (dispatch) => ({
onAfterOpen: () => {
onAfterOpen();
},
onRequestClose: () => {
onRequestClose();
dispatch(closeDialog(name))
}
})
return connect(mapStateToProps, mapDispatchToProps)(ReduxDialog);
});
}
export default reduxDialog;
| import React, { Component } from 'react';
import { connect } from 'react-redux'
import Modal from 'react-modal'
import { closeDialog } from './actions';
const reduxDialog = (defaults) => {
const {
name,
onAfterOpen = () => {},
onRequestClose = () => {}
} = defaults;
return((WrappedComponent) => {
class ReduxDialog extends Component {
render () {
return (
<Modal {...defaults} {...this.props}>
<WrappedComponent {...this.props} />
</Modal>
);
}
}
const mapStateToProps = (state) => {
let isOpen = defaults.isOpen;
const {
dialogReducer: { dialogs }
} = state;
if (dialogs && dialogs[name].isOpen !== undefined)
isOpen = dialogs[name].isOpen;
return { isOpen };
};
const mapDispatchToProps = (dispatch) => ({
onAfterOpen: () => {
onAfterOpen();
},
onRequestClose: () => {
onRequestClose();
dispatch(closeDialog(name))
}
})
return connect(mapStateToProps, mapDispatchToProps)(ReduxDialog);
});
}
export default reduxDialog;
| Allow an initial isOpen property to be set | Allow an initial isOpen property to be set
| JavaScript | mit | JakeDluhy/redux-dialog,JakeDluhy/redux-dialog | ---
+++
@@ -3,30 +3,37 @@
import Modal from 'react-modal'
import { closeDialog } from './actions';
-const reduxDialog = (dialogProps) => {
+const reduxDialog = (defaults) => {
const {
name,
onAfterOpen = () => {},
onRequestClose = () => {}
- } = dialogProps;
+ } = defaults;
return((WrappedComponent) => {
class ReduxDialog extends Component {
render () {
return (
- <Modal {...dialogProps} {...this.props}>
+ <Modal {...defaults} {...this.props}>
<WrappedComponent {...this.props} />
</Modal>
);
}
}
- const mapStateToProps = (state) => ({
- isOpen: (state.dialogs.dialogs
- && state.dialogs.dialogs[name]
- && state.dialogs.dialogs[name].isOpen) || false
- })
+ const mapStateToProps = (state) => {
+ let isOpen = defaults.isOpen;
+
+ const {
+ dialogReducer: { dialogs }
+ } = state;
+
+ if (dialogs && dialogs[name].isOpen !== undefined)
+ isOpen = dialogs[name].isOpen;
+
+ return { isOpen };
+ };
const mapDispatchToProps = (dispatch) => ({
onAfterOpen: () => { |
38b3c5224a33328a433d881a97be232c78983370 | database.js | database.js | var MongoClient = require('mongodb').MongoClient;
var URICS = "mongodb://tonyli139:RDyMScAWKpj0Fl1O@p2cluster-shard-00-00-ccvtw.mongodb.net:27017,p2cluster-shard-00-01-ccvtw.mongodb.net:27017,p2cluster-shard-00-02-ccvtw.mongodb.net:27017/<DATABASE>?ssl=true&replicaSet=p2Cluster-shard-0&authSource=admin";
var db;
connectDb = function(callback) {
MongoClient.connect(URICS, function(err, database) {
if (err) throw err;
db = database;
console.log('connected');
return callback(err);
});
}
getDb = function() {
return db;
}
var ObjectID = require('mongodb').ObjectID;
getID = function(id) {
return new ObjectID(id);
}
module.exports = {
connectDb,
getDb,
getID
}
| var MongoClient = require('mongodb').MongoClient;
var URICS = "mongodb://tonyli139:RDyMScAWKpj0Fl1O@p2cluster-shard-00-00-ccvtw.mongodb.net:27017,p2cluster-shard-00-01-ccvtw.mongodb.net:27017,p2cluster-shard-00-02-ccvtw.mongodb.net:27017/<DATABASE>?ssl=true&replicaSet=p2Cluster-shard-0&authSource=admin";
var db;
connectDb = function(callback) {
MongoClient.connect(URICS, function(err, database) {
if (err) throw err;
db = database;
//console.log('connected');
return callback(err);
});
}
getDb = function() {
return db;
}
var ObjectID = require('mongodb').ObjectID;
getID = function(id) {
return new ObjectID(id);
}
module.exports = {
connectDb,
getDb,
getID
}
| Disable console log for server connection | Disable console log for server connection
| JavaScript | bsd-3-clause | aXises/portfolio-2,aXises/portfolio-2,aXises/portfolio-2 | ---
+++
@@ -6,7 +6,7 @@
MongoClient.connect(URICS, function(err, database) {
if (err) throw err;
db = database;
- console.log('connected');
+ //console.log('connected');
return callback(err);
});
} |
1bd8b3e2ac19e6f0dc36a0a1666b0a451e9d78c7 | js/src/forum/addFlagControl.js | js/src/forum/addFlagControl.js | import { extend } from 'flarum/extend';
import app from 'flarum/app';
import PostControls from 'flarum/utils/PostControls';
import Button from 'flarum/components/Button';
import FlagPostModal from './components/FlagPostModal';
export default function() {
extend(PostControls, 'userControls', function(items, post) {
if (post.isHidden() || post.contentType() !== 'comment' || !post.canFlag()) return;
items.add('flag',
<Button icon="fas fa-flag" onclick={() => app.modal.show(new FlagPostModal({post}))}>{app.translator.trans('flarum-flags.forum.post_controls.flag_button')}</Button>
);
});
}
| import { extend } from 'flarum/extend';
import app from 'flarum/app';
import PostControls from 'flarum/utils/PostControls';
import Button from 'flarum/components/Button';
import FlagPostModal from './components/FlagPostModal';
export default function() {
extend(PostControls, 'userControls', function(items, post) {
if (post.isHidden() || post.contentType() !== 'comment' || !post.canFlag()) return;
items.add('flag',
<Button icon="fas fa-flag" onclick={() => app.modal.show(FlagPostModal, {post})}>{app.translator.trans('flarum-flags.forum.post_controls.flag_button')}</Button>
);
});
}
| Fix extension to work with latest state changes | Fix extension to work with latest state changes
| JavaScript | mit | flarum/flags,flarum/flags,flarum/flags | ---
+++
@@ -10,7 +10,7 @@
if (post.isHidden() || post.contentType() !== 'comment' || !post.canFlag()) return;
items.add('flag',
- <Button icon="fas fa-flag" onclick={() => app.modal.show(new FlagPostModal({post}))}>{app.translator.trans('flarum-flags.forum.post_controls.flag_button')}</Button>
+ <Button icon="fas fa-flag" onclick={() => app.modal.show(FlagPostModal, {post})}>{app.translator.trans('flarum-flags.forum.post_controls.flag_button')}</Button>
);
});
} |
e5f246b56bb3efe9567c587739dbb0c65032a57a | index.js | index.js | // Karme Edge Launcher
// =================
// Dependencies
// ------------
var urlparse = require('url').parse
var urlformat = require('url').format
var exec = require('child_process').exec
// Constants
// ---------
var PROCESS_NAME = 'spartan.exe'
var EDGE_COMMAND = [
'powershell',
'start',
'shell:AppsFolder\\Microsoft.Windows.Spartan_cw5n1h2txyewy!Microsoft.Spartan.Spartan'
]
// Constructor
function EdgeBrowser (baseBrowserDecorator, logger) {
baseBrowserDecorator(this)
var log = logger.create('launcher')
this._getOptions = function (url) {
var urlObj = urlparse(url, true)
// url.format does not want search attribute
delete urlObj.search
url = urlformat(urlObj)
return EDGE_COMMAND.splice(1).concat(url)
}
}
EdgeBrowser.prototype = {
name: 'Edge',
DEFAULT_CMD: {
win32: EDGE_COMMAND[0]
},
ENV_CMD: 'EDGE_BIN'
}
EdgeBrowser.$inject = ['baseBrowserDecorator', 'logger']
// Publish di module
// -----------------
module.exports = {
'launcher:Edge': ['type', EdgeBrowser]
}
| // Karme Edge Launcher
// =================
// Dependencies
// ------------
var urlparse = require('url').parse
var urlformat = require('url').format
// Constants
// ---------
var EDGE_COMMAND = [
'powershell',
'start',
'shell:AppsFolder\\Microsoft.Windows.Spartan_cw5n1h2txyewy!Microsoft.Spartan.Spartan'
]
// Constructor
function EdgeBrowser (baseBrowserDecorator) {
baseBrowserDecorator(this)
this._getOptions = function (url) {
var urlObj = urlparse(url, true)
// url.format does not want search attribute
delete urlObj.search
url = urlformat(urlObj)
return EDGE_COMMAND.splice(1).concat(url)
}
}
EdgeBrowser.prototype = {
name: 'Edge',
DEFAULT_CMD: {
win32: EDGE_COMMAND[0]
},
ENV_CMD: 'EDGE_BIN'
}
EdgeBrowser.$inject = ['baseBrowserDecorator']
// Publish di module
// -----------------
module.exports = {
'launcher:Edge': ['type', EdgeBrowser]
}
| Remove variables that are defined but never used | Remove variables that are defined but never used
| JavaScript | mit | nicolasmccurdy/karma-edge-launcher,karma-runner/karma-edge-launcher | ---
+++
@@ -6,12 +6,9 @@
var urlparse = require('url').parse
var urlformat = require('url').format
-var exec = require('child_process').exec
// Constants
// ---------
-
-var PROCESS_NAME = 'spartan.exe'
var EDGE_COMMAND = [
'powershell',
@@ -20,10 +17,8 @@
]
// Constructor
-function EdgeBrowser (baseBrowserDecorator, logger) {
+function EdgeBrowser (baseBrowserDecorator) {
baseBrowserDecorator(this)
-
- var log = logger.create('launcher')
this._getOptions = function (url) {
var urlObj = urlparse(url, true)
@@ -44,7 +39,7 @@
ENV_CMD: 'EDGE_BIN'
}
-EdgeBrowser.$inject = ['baseBrowserDecorator', 'logger']
+EdgeBrowser.$inject = ['baseBrowserDecorator']
// Publish di module
// ----------------- |
0bc5a286de1afefc26b32599bfec8ff550a73cf8 | index.js | index.js | function renderCat(catGifId) {
var container = document.getElementById('cat');
container.innerHTML =
"<img " +
"src='http://iconka.com/wp-content/uploads/edd/2015/10/" + catGifId +".gif' " +
"style='width:90%'>";
}
Dashboard.registerWidget(function (dashboardAPI, registerWidgetAPI) {
dashboardAPI.setTitle('Keep calm and purrrrr...');
renderCat("purr");
registerWidgetAPI({
onConfigure: function() {
renderCat("meal");
},
onRefresh: function() {
renderCat("knead");
}
});
}); | var listOfCatIds = ["purr", "meal", "knead"];
function renderCat(catGifId) {
var container = document.getElementById('cat');
container.innerHTML =
"<img " +
"src='http://iconka.com/wp-content/uploads/edd/2015/10/" + catGifId +".gif' " +
"style='width:90%'>";
}
function renderSelector(dashboardAPI) {
var container = document.getElementById('cat');
container.innerHTML =
"<select>" +
"<option value='random'>Random Cat</option>" +
"<option value='purr'>Purr</option>" +
"<option value='meal'>Meal</option>" +
"<option value='knead'>Knead</option>" +
"</select>" +
"<input type='button' value='Save' id='save'>";
var button = document.getElementById('save');
button.onclick = function() {
dashboardAPI.storeConfig({
cat: 'random'
});
dashboardAPI.exitConfigMode();
}
}
function drawCatFromConfig(dashboardAPI) {
dashboardAPI.readConfig().then(function(config) {
var catId = config.cat || 'purr';
if (catId === 'random') {
catId = listOfCatIds[Math.floor(Math.random() * listOfCatIds.length)];
}
renderCat(catId);
});
}
Dashboard.registerWidget(function (dashboardAPI, registerWidgetAPI) {
dashboardAPI.setTitle('Keep calm and purrrrr...');
drawCatFromConfig(dashboardAPI);
registerWidgetAPI({
onConfigure: function() {
renderSelector(dashboardAPI);
},
onRefresh: function() {
drawCatFromConfig(dashboardAPI);
}
});
}); | Save random; load random cat on 'random' option | Save random; load random cat on 'random' option
| JavaScript | apache-2.0 | mariyadavydova/youtrack-cats-widget,mariyadavydova/youtrack-cats-widget | ---
+++
@@ -1,3 +1,5 @@
+var listOfCatIds = ["purr", "meal", "knead"];
+
function renderCat(catGifId) {
var container = document.getElementById('cat');
container.innerHTML =
@@ -6,16 +8,46 @@
"style='width:90%'>";
}
+function renderSelector(dashboardAPI) {
+ var container = document.getElementById('cat');
+ container.innerHTML =
+ "<select>" +
+ "<option value='random'>Random Cat</option>" +
+ "<option value='purr'>Purr</option>" +
+ "<option value='meal'>Meal</option>" +
+ "<option value='knead'>Knead</option>" +
+ "</select>" +
+ "<input type='button' value='Save' id='save'>";
+
+ var button = document.getElementById('save');
+ button.onclick = function() {
+ dashboardAPI.storeConfig({
+ cat: 'random'
+ });
+ dashboardAPI.exitConfigMode();
+ }
+}
+
+function drawCatFromConfig(dashboardAPI) {
+ dashboardAPI.readConfig().then(function(config) {
+ var catId = config.cat || 'purr';
+ if (catId === 'random') {
+ catId = listOfCatIds[Math.floor(Math.random() * listOfCatIds.length)];
+ }
+ renderCat(catId);
+ });
+}
+
Dashboard.registerWidget(function (dashboardAPI, registerWidgetAPI) {
dashboardAPI.setTitle('Keep calm and purrrrr...');
- renderCat("purr");
+ drawCatFromConfig(dashboardAPI);
registerWidgetAPI({
onConfigure: function() {
- renderCat("meal");
+ renderSelector(dashboardAPI);
},
onRefresh: function() {
- renderCat("knead");
+ drawCatFromConfig(dashboardAPI);
}
});
}); |
65ea3439f67a9081ff4fddd573f3505c01461253 | index.js | index.js | 'use strict';
/**
* Module dependenices
*/
const clone = require('shallow-clone');
const typeOf = require('kind-of');
function cloneDeep(val, instanceClone) {
switch (typeOf(val)) {
case 'object':
return cloneObjectDeep(val, instanceClone);
case 'array':
return cloneArrayDeep(val, instanceClone);
default: {
return clone(val);
}
}
}
function cloneObjectDeep(val, instanceClone) {
if (typeof instanceClone === 'function') {
return instanceClone(val);
}
if (typeOf(val) === 'object') {
const res = new val.constructor();
for (const key in val) {
res[key] = cloneDeep(val[key], instanceClone);
}
return res;
}
return val;
}
function cloneArrayDeep(val, instanceClone) {
const res = new val.constructor(val.length);
for (let i = 0; i < val.length; i++) {
res[i] = cloneDeep(val[i], instanceClone);
}
return res;
}
/**
* Expose `cloneDeep`
*/
module.exports = cloneDeep;
| 'use strict';
/**
* Module dependenices
*/
const clone = require('shallow-clone');
const typeOf = require('kind-of');
function cloneDeep(val, instanceClone) {
switch (typeOf(val)) {
case 'object':
return cloneObjectDeep(val, instanceClone);
case 'array':
return cloneArrayDeep(val, instanceClone);
default: {
return clone(val);
}
}
}
function cloneObjectDeep(val, instanceClone) {
if (typeof instanceClone === 'function') {
return instanceClone(val);
}
if (typeOf(val) === 'object') {
const res = new val.constructor();
for (let key in val) {
res[key] = cloneDeep(val[key], instanceClone);
}
return res;
}
return val;
}
function cloneArrayDeep(val, instanceClone) {
const res = new val.constructor(val.length);
for (let i = 0; i < val.length; i++) {
res[i] = cloneDeep(val[i], instanceClone);
}
return res;
}
/**
* Expose `cloneDeep`
*/
module.exports = cloneDeep;
| FIX - IE11 does not support inside loops | FIX - IE11 does not support inside loops
| JavaScript | mit | jonschlinkert/clone-deep | ---
+++
@@ -25,7 +25,7 @@
}
if (typeOf(val) === 'object') {
const res = new val.constructor();
- for (const key in val) {
+ for (let key in val) {
res[key] = cloneDeep(val[key], instanceClone);
}
return res; |
f65c93b109e2005bea1daaac1494a93f6fc5205b | index.js | index.js | #!/usr/bin/env iojs
var program = require('commander'),
fs = require('fs'),
sequoria = require('sequoria'),
createBot = require('./lib').createBot;
function main() {
program
.version(require('./package').version)
.usage('[configFile]')
.action(function(configFile){
// this module is being directly run.
var configFile = configFile || 'config.json';
if (!configFile.startsWith('/')) {
// hack: should use proper path joining package
configFile = [
process.cwd(),
configFile
].join('/');
}
var config = JSON.parse(fs.readFileSync(configFile));
var bot = createBot(config);
bot.start();
})
.parse(process.argv);
}
if (require.main === module) {
main();
}
module.exports = createBot;
| #!/usr/bin/env iojs
var path = require('path'),
program = require('commander'),
fs = require('fs'),
sequoria = require('sequoria'),
createBot = require('./lib').createBot;
function main() {
program
.version(require('./package').version)
.usage('[configFile]')
.action(function(configFile){
// this module is being directly run.
var configFile = path.resolve(configFile || 'config.json');
var config = JSON.parse(fs.readFileSync(configFile));
var bot = createBot(config);
bot.start();
})
.parse(process.argv);
}
if (require.main === module) {
main();
}
module.exports = createBot;
| Use path.resolve to resolve path | Use path.resolve to resolve path
| JavaScript | mit | elvinyung/botstrap,lvn/botstrap | ---
+++
@@ -1,6 +1,7 @@
#!/usr/bin/env iojs
-var program = require('commander'),
+var path = require('path'),
+ program = require('commander'),
fs = require('fs'),
sequoria = require('sequoria'),
createBot = require('./lib').createBot;
@@ -11,14 +12,7 @@
.usage('[configFile]')
.action(function(configFile){
// this module is being directly run.
- var configFile = configFile || 'config.json';
- if (!configFile.startsWith('/')) {
- // hack: should use proper path joining package
- configFile = [
- process.cwd(),
- configFile
- ].join('/');
- }
+ var configFile = path.resolve(configFile || 'config.json');
var config = JSON.parse(fs.readFileSync(configFile));
var bot = createBot(config); |
89aa3813432083bc4bc192a27167f7a48d3a482f | index.js | index.js | module.exports = reviewersEditionCompare
var ordinal = require('number-to-words').toWordsOrdinal
var parse = require('reviewers-edition-parse')
var numbers = require('reviewers-edition-parse/numbers')
function reviewersEditionCompare (edition) {
var parsed = parse(edition)
if (parsed) {
return (
(parsed.draft ? (ordinal(parsed.draft) + ' draft of ') : '') +
numbers
.filter(function (number) {
return number !== 'draft'
})
.reduce(function (components, number) {
return parsed.hasOwnProperty(number)
? components.concat(ordinal(parsed[number]) + ' ' + number)
: components
}, [])
.join(', ')
)
} else {
return false
}
}
| var ordinal = require('number-to-words').toWordsOrdinal
var parse = require('reviewers-edition-parse')
var numbers = require('reviewers-edition-parse/numbers')
module.exports = function reviewersEditionCompare (edition) {
var parsed = parse(edition)
if (parsed) {
return (
(parsed.draft ? (ordinal(parsed.draft) + ' draft of ') : '') +
numbers
.filter(function (number) {
return number !== 'draft'
})
.reduce(function (components, number) {
return parsed.hasOwnProperty(number)
? components.concat(ordinal(parsed[number]) + ' ' + number)
: components
}, [])
.join(', ')
)
} else {
return false
}
}
| Put module.exports and function on same line | Put module.exports and function on same line
| JavaScript | mit | kemitchell/reviewers-edition-spell.js | ---
+++
@@ -1,10 +1,8 @@
-module.exports = reviewersEditionCompare
-
var ordinal = require('number-to-words').toWordsOrdinal
var parse = require('reviewers-edition-parse')
var numbers = require('reviewers-edition-parse/numbers')
-function reviewersEditionCompare (edition) {
+module.exports = function reviewersEditionCompare (edition) {
var parsed = parse(edition)
if (parsed) {
return ( |
9310026c8cbc4af5f4326a27cfc27121e5636323 | index.js | index.js | var es = require('event-stream'),
clone = require('clone'),
path = require('path');
module.exports = function(opt){
// clone options
opt = opt ? clone(opt) : {};
if (!opt.splitter && opt.splitter !== "") opt.splitter = '\r\n';
if (!opt.fileName) throw new Error("Missing fileName option for gulp-concat");
var buffer = [];
function bufferContents(file){
// clone the file so we arent mutating stuff
buffer.push(clone(file));
}
function endStream(){
if (buffer.length === 0) return this.emit('end');
var joinedContents = buffer.map(function(file){
return file.contents;
}).join(opt.splitter);
var joinedPath = path.join(path.dirname(buffer[0].path), opt.fileName);
var joinedFile = {
shortened: opt.fileName,
path: joinedPath,
contents: joinedContents
};
this.emit('data', joinedFile);
this.emit('end');
}
return es.through(bufferContents, endStream);
};
| var es = require('event-stream'),
clone = require('clone'),
path = require('path');
module.exports = function(opt){
// clone options
opt = opt ? clone(opt) : {};
if (typeof opt.splitter === 'undefined') opt.splitter = '\r\n';
if (!opt.fileName) throw new Error("Missing fileName option for gulp-concat");
var buffer = [];
function bufferContents(file){
// clone the file so we arent mutating stuff
buffer.push(clone(file));
}
function endStream(){
if (buffer.length === 0) return this.emit('end');
var joinedContents = buffer.map(function(file){
return file.contents;
}).join(opt.splitter);
var joinedPath = path.join(path.dirname(buffer[0].path), opt.fileName);
var joinedFile = {
shortened: opt.fileName,
path: joinedPath,
contents: joinedContents
};
this.emit('data', joinedFile);
this.emit('end');
}
return es.through(bufferContents, endStream);
};
| Adjust opt.splitter to compare against undefined for the default value. | Adjust opt.splitter to compare against undefined for the default value.
| JavaScript | mit | wearefractal/gulp-concat,queckezz/gulp-concat,KenanY/gulp-concat,BinaryMuse/gulp-concat,contra/gulp-concat,colynb/gulp-concat,stevelacy/gulp-concat,callumacrae/gulp-concat,abdurrachman-habibi/gulp-concat | ---
+++
@@ -5,7 +5,7 @@
module.exports = function(opt){
// clone options
opt = opt ? clone(opt) : {};
- if (!opt.splitter && opt.splitter !== "") opt.splitter = '\r\n';
+ if (typeof opt.splitter === 'undefined') opt.splitter = '\r\n';
if (!opt.fileName) throw new Error("Missing fileName option for gulp-concat");
|
4021d99786f51646633cf9d15fead8c3a58bef7c | index.js | index.js | var rimraf = require('rimraf')
var path = require('path');
var join = path.join;
function Plugin(paths) {
// determine webpack root
this.context = path.dirname(module.parent.filename);
// allows for a single string entry
if (typeof paths == 'string' || paths instanceof String){
paths = [paths];
}
// store paths
this.paths = paths;
}
Plugin.prototype.apply = function(compiler) {
var self = this;
// preform an rm -rf on each path
self.paths.forEach(function(path){
var path = join(self.context, path);
rimraf.sync(path);
});
}
module.exports = Plugin;
| var rimraf = require('rimraf')
var path = require('path');
var join = path.join;
function Plugin(paths, context) {
// determine webpack root
this.context = context || path.dirname(module.parent.filename);
// allows for a single string entry
if (typeof paths == 'string' || paths instanceof String){
paths = [paths];
}
// store paths
this.paths = paths;
}
Plugin.prototype.apply = function(compiler) {
var self = this;
// preform an rm -rf on each path
self.paths.forEach(function(path){
var path = join(self.context, path);
rimraf.sync(path);
});
}
module.exports = Plugin;
| Add opportunity pass webpack root (context) | Add opportunity pass webpack root (context)
| JavaScript | mit | chrisblossom/clean-webpack-plugin,mhuggins/clean-webpack-plugin,johnagan/clean-webpack-plugin,chrisblossom/clean-webpack-plugin,johnagan/clean-webpack-plugin | ---
+++
@@ -2,9 +2,9 @@
var path = require('path');
var join = path.join;
-function Plugin(paths) {
+function Plugin(paths, context) {
// determine webpack root
- this.context = path.dirname(module.parent.filename);
+ this.context = context || path.dirname(module.parent.filename);
// allows for a single string entry
if (typeof paths == 'string' || paths instanceof String){ |
f4d7e0d0917f7af388c75b4b4816591c4f7410b5 | src/utils/config.js | src/utils/config.js | import _ from 'lodash'
import defaultConfig from '../config/defaults'
let globalConfig = _.assign({}, _.cloneDeep(defaultConfig))
export default class Config {
static load(cfg) {
globalConfig = _.cloneDeep(cfg)
}
static get(item, defaultValue) {
if(item === '*') {
return _.cloneDeep(globalConfig)
}
return _.get(globalConfig, item, defaultValue)
}
static set(path, item) {
_.set(globalConfig, path, item)
}
}
| import _ from 'lodash'
import defaultConfig from '../config/defaults'
let globalConfig = _.assign({}, _.cloneDeep(defaultConfig))
export default class Config {
static load(cfg) {
globalConfig = _.merge(globalConfig, _.cloneDeep(cfg))
}
static overwrite(cfg) {
globalConfig = _.cloneDeep(cfg)
}
static get(item, defaultValue) {
if(item === '*') {
return _.cloneDeep(globalConfig)
}
return _.get(globalConfig, item, defaultValue)
}
static set(path, item) {
_.set(globalConfig, path, item)
}
}
| Add loading/merging methods to Config utility | Add loading/merging methods to Config utility
| JavaScript | mit | thinktopography/reframe,thinktopography/reframe | ---
+++
@@ -5,6 +5,10 @@
export default class Config {
static load(cfg) {
+ globalConfig = _.merge(globalConfig, _.cloneDeep(cfg))
+ }
+
+ static overwrite(cfg) {
globalConfig = _.cloneDeep(cfg)
}
|
73707d6455b0f4758c61a5c573aec6ad987259de | index.js | index.js | 'use strict';
module.exports = {
name: 'ember-cli-uglify',
included(app) {
this._super.included.apply(this, arguments);
const defaults = require('lodash.defaultsdeep');
let defaultOptions = {
enabled: app.env === 'production',
uglify: {
compress: {
// this is adversely affects heuristics for IIFE eval
'negate_iife': false,
// limit sequences because of memory issues during parsing
sequences: 30,
},
output: {
// no difference in size and much easier to debug
semicolons: false,
},
}
};
if (app.options.sourcemaps && !this._sourceMapsEnabled(app.options.sourcemaps)) {
defaultOptions.uglify.sourceMap = false;
}
this._options = defaults(app.options['ember-cli-uglify'] || {}, defaultOptions);
},
_sourceMapsEnabled(options) {
if (options.enabled === false) {
return false;
}
let extensions = options.extensions || [];
if (extensions.indexOf('js') === -1) {
return false;
}
return true;
},
postprocessTree(type, tree) {
if (this._options.enabled === true && type === 'all') {
return require('broccoli-uglify-sourcemap')(tree, this._options);
} else {
return tree;
}
}
};
| 'use strict';
module.exports = {
name: 'ember-cli-uglify',
included(app) {
this._super.included.apply(this, arguments);
const defaults = require('lodash.defaultsdeep');
let defaultOptions = {
enabled: app.env === 'production',
uglify: {
compress: {
// this is adversely affects heuristics for IIFE eval
'negate_iife': false,
// limit sequences because of memory issues during parsing
sequences: 30,
},
mangle: {
safari10: true
},
output: {
// no difference in size and much easier to debug
semicolons: false,
},
}
};
if (app.options.sourcemaps && !this._sourceMapsEnabled(app.options.sourcemaps)) {
defaultOptions.uglify.sourceMap = false;
}
this._options = defaults(app.options['ember-cli-uglify'] || {}, defaultOptions);
},
_sourceMapsEnabled(options) {
if (options.enabled === false) {
return false;
}
let extensions = options.extensions || [];
if (extensions.indexOf('js') === -1) {
return false;
}
return true;
},
postprocessTree(type, tree) {
if (this._options.enabled === true && type === 'all') {
return require('broccoli-uglify-sourcemap')(tree, this._options);
} else {
return tree;
}
}
};
| Add a fix for Safari to the default config | Add a fix for Safari to the default config
Uglifying ES6 doesn't work currently with Safari due to a webkit bug.
Adding this mangle option fixes that.
| JavaScript | mit | ember-cli/ember-cli-uglify,ember-cli/ember-cli-uglify | ---
+++
@@ -17,6 +17,9 @@
'negate_iife': false,
// limit sequences because of memory issues during parsing
sequences: 30,
+ },
+ mangle: {
+ safari10: true
},
output: {
// no difference in size and much easier to debug |
628a1e56241fd82104d69ac7e8e4b751ff85e34b | index.js | index.js | var addElevation = require('geojson-elevation').addElevation,
TileSet = require('node-hgt').TileSet,
express = require('express'),
bodyParser = require('body-parser'),
app = express(),
tiles = new TileSet('./data');
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.contentType('application/json');
next();
});
app.post('/geojson', function(req, res) {
var geojson = req.body;
if (!geojson || Object.keys(geojson).length === 0) {
res.status(400).send('Error: invalid geojson.');
return;
}
addElevation(geojson, tiles, function(err) {
if (err) {
res.status(500).send(err);
} else {
res.send(JSON.stringify(geojson));
}
});
});
var server = app.listen(5001, function() {
var host = server.address().address;
var port = server.address().port;
console.log('elevation-server listening at http://%s:%s', host, port);
}); | var addElevation = require('geojson-elevation').addElevation,
TileSet = require('node-hgt').TileSet,
ImagicoElevationDownloader = require('node-hgt').ImagicoElevationDownloader,
express = require('express'),
bodyParser = require('body-parser'),
app = express(),
tiles,
tileDownloader,
tileDirectory = process.env.TILE_DIRECTORY;
if(!tileDirectory) {
tileDirectory = "./data";
}
if(process.env.TILE_DOWNLOADER) {
if(process.env.TILE_DOWNLOADER == "imagico") {
tileDownloader = new ImagicoElevationDownloader();
}
}
tiles = new TileSet(tileDirectory, {downloader:tileDownloader});
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.contentType('application/json');
next();
});
app.post('/geojson', function(req, res) {
var geojson = req.body;
if (!geojson || Object.keys(geojson).length === 0) {
res.status(400).send('Error: invalid geojson.');
return;
}
addElevation(geojson, tiles, function(err) {
if (err) {
res.status(500).send(err);
} else {
res.send(JSON.stringify(geojson));
}
});
});
var server = app.listen(5001, function() {
var host = server.address().address;
var port = server.address().port;
console.log('elevation-server listening at http://%s:%s', host, port);
}); | Read environment variables for data directory and tile downloader | Read environment variables for data directory and tile downloader
| JavaScript | isc | perliedman/elevation-service,JesseCrocker/elevation-service | ---
+++
@@ -1,9 +1,24 @@
var addElevation = require('geojson-elevation').addElevation,
TileSet = require('node-hgt').TileSet,
+ ImagicoElevationDownloader = require('node-hgt').ImagicoElevationDownloader,
express = require('express'),
bodyParser = require('body-parser'),
app = express(),
- tiles = new TileSet('./data');
+ tiles,
+ tileDownloader,
+ tileDirectory = process.env.TILE_DIRECTORY;
+
+if(!tileDirectory) {
+ tileDirectory = "./data";
+}
+
+if(process.env.TILE_DOWNLOADER) {
+ if(process.env.TILE_DOWNLOADER == "imagico") {
+ tileDownloader = new ImagicoElevationDownloader();
+ }
+}
+
+tiles = new TileSet(tileDirectory, {downloader:tileDownloader});
app.use(bodyParser.json());
app.use(function(req, res, next) { |
4bf4680c186dd7e21292e7efc2431547f51ac11b | index.js | index.js | function Alternate() {
this.values = arguments;
this.index = 0;
}
Alternate.prototype.next = function() {
var returnValue = this.values[this.index];
if (this.index < this.values.length) {
this.index++;
} else {
this.index = 0;
}
return returnValue;
};
Alternate.prototype.peek = function() {
return this.values[this.index];
};
module.exports = Alternate;
| function Alternate() {
this.values = arguments;
this.index = 0;
}
Alternate.prototype.next = function() {
var returnValue = this.values[this.index];
if (this.index < this.values.length - 1) {
this.index++;
} else {
this.index = 0;
}
return returnValue;
};
Alternate.prototype.peek = function() {
return this.values[this.index];
};
module.exports = Alternate;
| Fix off by one bug | Fix off by one bug
| JavaScript | mit | sgnh/alternate | ---
+++
@@ -6,7 +6,7 @@
Alternate.prototype.next = function() {
var returnValue = this.values[this.index];
- if (this.index < this.values.length) {
+ if (this.index < this.values.length - 1) {
this.index++;
} else {
this.index = 0; |
43204c269a394d1805d9ddc208ea6a524729c7cf | index.js | index.js | /*!
* tweensy - Copyright (c) 2017 Jacob Buck
* https://github.com/jacobbuck/tweensy
* Licensed under the terms of the MIT license.
*/
'use strict';
var assign = require('lodash/assign');
var now = require('performance-now');
var rafq = require('rafq')();
var defaultOptions = {
duration: 0,
easing: function linear(t) { return t; },
from: 0,
loop: 1,
onComplete: function() {},
onProgress: function() {},
to: 1
};
module.exports = function tween(instanceOptions) {
var options = assign({}, defaultOptions, instanceOptions);
var isFinished = false;
var iteration = 1;
var startTime = null;
function tick() {
var time = now();
if (!startTime) {
startTime = time;
}
var progress = isFinished ?
1 :
(time - (startTime * iteration)) / options.duration;
options.onProgress(
options.easing(progress) *
(options.to - options.from) +
options.from
);
if (progress === 1) {
if (iteration < options.loop) {
iteration += 1;
} else {
isFinished = true;
}
}
if (isFinished) {
options.onComplete();
} else {
rafq.add(tick);
}
}
function stop(finish) {
isFinished = true;
if (!finish) {
rafq.remove(tick);
}
}
tick();
return stop;
};
| /*!
* tweensy - Copyright (c) 2017 Jacob Buck
* https://github.com/jacobbuck/tweensy
* Licensed under the terms of the MIT license.
*/
'use strict';
var assign = require('lodash/assign');
var now = require('performance-now');
var rafq = require('rafq')();
var defaultOptions = {
duration: 0,
easing: function linear(t) { return t; },
from: 0,
onComplete: function() {},
onProgress: function() {},
to: 1
};
module.exports = function tween(instanceOptions) {
var options = assign({}, defaultOptions, instanceOptions);
var isFinished = false;
var fromToMultiplier = (options.to - options.from) + options.from;
var startTime = null;
function tick() {
var time = now();
if (!startTime) {
startTime = time;
}
var progress = isFinished ? 1 : (time - startTime) / options.duration;
options.onProgress(options.easing(progress) * fromToMultiplier);
if (progress === 1) {
isFinished = true;
}
if (isFinished) {
options.onComplete(time);
} else {
rafq.add(tick);
}
}
function stop(finish) {
isFinished = true;
if (!finish) {
rafq.remove(tick);
}
}
tick();
return stop;
};
| Remove loop to keep scope small. Simplify some code, and pre calculate some things for perf | Remove loop to keep scope small. Simplify some code, and pre calculate some things for perf
| JavaScript | mit | jacobbuck/tweensy,jacobbuck/tweenie | ---
+++
@@ -13,7 +13,6 @@
duration: 0,
easing: function linear(t) { return t; },
from: 0,
- loop: 1,
onComplete: function() {},
onProgress: function() {},
to: 1
@@ -22,7 +21,7 @@
module.exports = function tween(instanceOptions) {
var options = assign({}, defaultOptions, instanceOptions);
var isFinished = false;
- var iteration = 1;
+ var fromToMultiplier = (options.to - options.from) + options.from;
var startTime = null;
function tick() {
@@ -32,26 +31,16 @@
startTime = time;
}
- var progress = isFinished ?
- 1 :
- (time - (startTime * iteration)) / options.duration;
+ var progress = isFinished ? 1 : (time - startTime) / options.duration;
- options.onProgress(
- options.easing(progress) *
- (options.to - options.from) +
- options.from
- );
+ options.onProgress(options.easing(progress) * fromToMultiplier);
if (progress === 1) {
- if (iteration < options.loop) {
- iteration += 1;
- } else {
- isFinished = true;
- }
+ isFinished = true;
}
if (isFinished) {
- options.onComplete();
+ options.onComplete(time);
} else {
rafq.add(tick);
} |
7c953aa414ea16fd831a11b3be4d74f5c52b5653 | src/database/utilities/constants.js | src/database/utilities/constants.js | /* eslint-disable import/prefer-default-export */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
const HOURS_PER_DAY = 24;
const MINUTES_PER_HOUR = 60;
const SECONDS_PER_MINUTE = 60;
const MILLISECONDS_PER_SECOND = 1000;
export const MILLISECONDS_PER_MINUTE = MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE;
export const MILLISECONDS_PER_HOUR = MILLISECONDS_PER_MINUTE * MINUTES_PER_HOUR;
export const MILLISECONDS_PER_DAY = MILLISECONDS_PER_HOUR * HOURS_PER_DAY;
export const NUMBER_SEQUENCE_KEYS = {
CUSTOMER_INVOICE_NUMBER: 'customer_invoice_serial_number',
INVENTORY_ADJUSTMENT_SERIAL_NUMBER: 'inventory_adjustment_serial_number',
REQUISITION_SERIAL_NUMBER: 'requisition_serial_number',
REQUISITION_REQUESTER_REFERENCE: 'requisition_requester_reference',
STOCKTAKE_SERIAL_NUMBER: 'stocktake_serial_number',
SUPPLIER_INVOICE_NUMBER: 'supplier_invoice_serial_number',
};
| /* eslint-disable import/prefer-default-export */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
const HOURS_PER_DAY = 24;
const MINUTES_PER_HOUR = 60;
const SECONDS_PER_MINUTE = 60;
const MILLISECONDS_PER_SECOND = 1000;
export const MILLISECONDS_PER_MINUTE = MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE;
export const MILLISECONDS_PER_HOUR = MILLISECONDS_PER_MINUTE * MINUTES_PER_HOUR;
export const MILLISECONDS_PER_DAY = MILLISECONDS_PER_HOUR * HOURS_PER_DAY;
export const NUMBER_SEQUENCE_KEYS = {
CUSTOMER_INVOICE_NUMBER: 'customer_invoice_serial_number',
INVENTORY_ADJUSTMENT_SERIAL_NUMBER: 'inventory_adjustment_serial_number',
REQUISITION_SERIAL_NUMBER: 'requisition_serial_number',
REQUISITION_REQUESTER_REFERENCE: 'requisition_requester_reference',
STOCKTAKE_SERIAL_NUMBER: 'stocktake_serial_number',
SUPPLIER_INVOICE_NUMBER: 'supplier_invoice_serial_number',
PATIENT_CODE: 'patient_code',
};
| Add patient code number sequence | Add patient code number sequence
| JavaScript | mit | sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile | ---
+++
@@ -20,4 +20,5 @@
REQUISITION_REQUESTER_REFERENCE: 'requisition_requester_reference',
STOCKTAKE_SERIAL_NUMBER: 'stocktake_serial_number',
SUPPLIER_INVOICE_NUMBER: 'supplier_invoice_serial_number',
+ PATIENT_CODE: 'patient_code',
}; |
a4acc1c3dbd3d77104f39c957051f2f38884224c | server/app.js | server/app.js | var bodyParser = require('body-parser');
var express = require('express');
var app = express();
var router = express.Router();
var Sequelize = require('sequelize');
var sequelize = new Sequelize(process.env.DATABASE_URL);
var matchmaker = require('./controllers/Matchmaker');
var playController = require('./controllers/Play');
var turnController = require('./controllers/Turn');
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
router.route('/play')
.post(matchmaker.startGame);
router.route('/fire')
.post(playController.fire);
router.route('/cancel/:username')
.post(matchmaker.cancel);
router.route('/turn/:username')
.get(turnController.nextPlayer);
app.use('/api', router);
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'));
});
| var bodyParser = require('body-parser');
var express = require('express');
var app = express();
var router = express.Router();
var Sequelize = require('sequelize');
var sequelize = new Sequelize(process.env.DATABASE_URL);
var matchmaker = require('./controllers/Matchmaker');
var playController = require('./controllers/Play');
var turnController = require('./controllers/Turn');
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
router.route('/play')
.post(matchmaker.startGame);
router.route('/fire')
.post(playController.fire);
router.route('/cancel')
.post(matchmaker.cancel);
router.route('/turn/:username')
.get(turnController.nextPlayer);
app.use('/api', router);
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'));
});
| Edit server route url to match client request | Edit server route url to match client request
| JavaScript | mit | andereld/progark,andereld/progark | ---
+++
@@ -19,7 +19,7 @@
router.route('/fire')
.post(playController.fire);
-router.route('/cancel/:username')
+router.route('/cancel')
.post(matchmaker.cancel);
router.route('/turn/:username') |
7af80538c9232f5bf0d929d4164076a44cb2b704 | render-mustache.js | render-mustache.js | /**
* render-mustache
*
* This module implements support for rendering [Mustache](http://mustache.github.com/)
* templates using [mustache.js](https://github.com/janl/mustache.js).
*/
define(['mustache'],
function(Mustache) {
/**
* Setup Mustache template engine.
*
* When rendering, this engine returns a compiled template function which can
* be cached for performance optimization.
*
* Examples:
*
* render.engine('text/template', mustache());
*
* @return {Function}
* @api public
*/
return function() {
return function(str) {
return Mustache.compile(str);
}
}
});
| /**
* render-mustache
*
* This module implements support for rendering [Mustache](http://mustache.github.com/)
* templates using [mustache.js](https://github.com/janl/mustache.js).
*/
define(['mustache'],
function(Mustache) {
/**
* Setup Mustache template engine.
*
* When rendering, this engine returns a compiled template function which can
* be cached for performance optimization.
*
* Examples:
*
* render.engine('text/x-mustache-template', mustache());
*
* A Note on MIME Types:
*
* It has become common convention to include templates within HTML by
* enclosing them within script tags:
*
* <script type=“text/template”>...</script>
*
* Recommended practice for Sail.js applications is to be more specific when
* indicating the MIME type, both as a way to communicate explicitly with
* other developers and as a means to use multiple template engines within an
* application.
*
* While no standard exists, the following list of MIME types are used to
* indicate Mustache templates in practice:
*
* * text/x-mustache-template
* [Announcing Handlebars.js](http://yehudakatz.com/2010/09/09/announcing-handlebars-js/)
*
* @return {Function}
* @api public
*/
return function() {
return function(str) {
return Mustache.compile(str);
}
}
});
| Add documentation regarding MIME types. | Add documentation regarding MIME types.
| JavaScript | mit | sailjs/render-mustache | ---
+++
@@ -15,7 +15,25 @@
*
* Examples:
*
- * render.engine('text/template', mustache());
+ * render.engine('text/x-mustache-template', mustache());
+ *
+ * A Note on MIME Types:
+ *
+ * It has become common convention to include templates within HTML by
+ * enclosing them within script tags:
+ *
+ * <script type=“text/template”>...</script>
+ *
+ * Recommended practice for Sail.js applications is to be more specific when
+ * indicating the MIME type, both as a way to communicate explicitly with
+ * other developers and as a means to use multiple template engines within an
+ * application.
+ *
+ * While no standard exists, the following list of MIME types are used to
+ * indicate Mustache templates in practice:
+ *
+ * * text/x-mustache-template
+ * [Announcing Handlebars.js](http://yehudakatz.com/2010/09/09/announcing-handlebars-js/)
*
* @return {Function}
* @api public |
91e5e219929c894cb48391261cc38780c728b0d9 | src/cmd/main/music/handlers/YouTubeHandler.js | src/cmd/main/music/handlers/YouTubeHandler.js | /**
* @file Music handler for YouTube videos. Does not support livestreams.
* @author Ovyerus
*/
const ytdl = require('ytdl-core');
const got = require('got');
const ITAG = '251'; // Preferred iTag quality to get. Default: 251.
class YouTubeHandler {
constructor() {}
async getInfo(url) {
if (typeof url !== 'string') throw new TypeError('url is not a string.');
let info = await ytdl.getInfo(url);
let res = {
url,
title: info.title,
uploader: info.author.name,
thumbnail: info.thumbnail_url.replace('default.jpg', 'hqdefault.jpg'),
length: Number(info.length_seconds),
type: 'YouTubeVideo'
};
return res;
}
async getStream(url) {
if (typeof url !== 'string') throw new TypeError('url is not a string.');
let info = await ytdl.getInfo(url);
return got.stream(info.formats.find(f => f.itag === ITAG).url);
}
}
module.exports = YouTubeHandler; | /**
* @file Music handler for YouTube videos. Does not support livestreams.
* @author Ovyerus
*/
const ytdl = require('ytdl-core');
const got = require('got');
// List of all itag qualities can be found here: https://en.wikipedia.org/w/index.php?title=YouTube&oldid=800910021#Quality_and_formats.
const ITAG = '140'; // Preferred itag quality to get. Default: 140.
const ITAG_FALLBACK = '22'; // In the event that the previous itag could not be found, try finding this one. Should probably be a lower value.
class YouTubeHandler {
constructor() {}
async getInfo(url) {
if (typeof url !== 'string') throw new TypeError('url is not a string.');
let info = await ytdl.getInfo(url);
let res = {
url,
title: info.title,
uploader: info.author.name,
thumbnail: info.thumbnail_url.replace('default.jpg', 'hqdefault.jpg'),
length: Number(info.length_seconds),
type: 'YouTubeVideo'
};
return res;
}
async getStream(url) {
if (typeof url !== 'string') throw new TypeError('url is not a string.');
let info = await ytdl.getInfo(url);
let format = info.formats.find(f => f.itag === ITAG) || info.formats.find(f => f.itag === ITAG_FALLBACK);
format = format ? format.url : info.url; // Fallback to default URL if the wanted itags could not be found;
return got.stream(format);
}
}
module.exports = YouTubeHandler; | Change requested itag for YouTube music to a M4A+AAC stream, instead of a WebM+Opus stream in an attempt to fix issues | Change requested itag for YouTube music to a M4A+AAC stream, instead of a WebM+Opus stream in an attempt to fix issues
| JavaScript | unknown | awau/owo-whats-this,sr229/owo-whats-this,ClarityMoe/Clara,awau/Clara,owo-dev-team/owo-whats-this | ---
+++
@@ -6,7 +6,9 @@
const ytdl = require('ytdl-core');
const got = require('got');
-const ITAG = '251'; // Preferred iTag quality to get. Default: 251.
+// List of all itag qualities can be found here: https://en.wikipedia.org/w/index.php?title=YouTube&oldid=800910021#Quality_and_formats.
+const ITAG = '140'; // Preferred itag quality to get. Default: 140.
+const ITAG_FALLBACK = '22'; // In the event that the previous itag could not be found, try finding this one. Should probably be a lower value.
class YouTubeHandler {
constructor() {}
@@ -31,7 +33,10 @@
if (typeof url !== 'string') throw new TypeError('url is not a string.');
let info = await ytdl.getInfo(url);
- return got.stream(info.formats.find(f => f.itag === ITAG).url);
+ let format = info.formats.find(f => f.itag === ITAG) || info.formats.find(f => f.itag === ITAG_FALLBACK);
+ format = format ? format.url : info.url; // Fallback to default URL if the wanted itags could not be found;
+
+ return got.stream(format);
}
}
|
3f96581aa2df3892d673a3ef175bf8e76f321075 | renderer/middleware/index.js | renderer/middleware/index.js | // @flow
import type {Store, Dispatch, Action} from 'redux';
export const save = (store: Store) => (next: Dispatch) => (action: Action) => {
setImmediate(() => {
localStorage.setItem('store', JSON.stringify(store.getState()));
});
next(action);
};
| // @flow
import type {Store, Dispatch, Action} from 'redux';
export const save = (store: Store) => (next: Dispatch) => (action: Action) => {
if (action.id) {
setImmediate(() => {
localStorage.setItem('store', JSON.stringify(store.getState()));
});
}
next(action);
};
| Update store at Only import change | Update store at Only import change
| JavaScript | mit | akameco/PixivDeck,akameco/PixivDeck | ---
+++
@@ -2,8 +2,10 @@
import type {Store, Dispatch, Action} from 'redux';
export const save = (store: Store) => (next: Dispatch) => (action: Action) => {
- setImmediate(() => {
- localStorage.setItem('store', JSON.stringify(store.getState()));
- });
+ if (action.id) {
+ setImmediate(() => {
+ localStorage.setItem('store', JSON.stringify(store.getState()));
+ });
+ }
next(action);
}; |
546e2733e51106975f7b167f3b690771ebd6dcfb | lib/gcli/test/testFail.js | lib/gcli/test/testFail.js | /*
* Copyright 2012, Mozilla Foundation and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var helpers = require('./helpers');
exports.testBasic = function(options) {
return helpers.audit(options, [
{
setup: 'tsfail reject',
exec: {
output: 'rejected promise',
type: 'error',
error: true
}
},
{
setup: 'tsfail rejecttyped',
exec: {
output: '54',
type: 'number',
error: true
}
},
{
setup: 'tsfail throwerror',
exec: {
output: 'thrown error',
type: 'error',
error: true
}
},
{
setup: 'tsfail throwstring',
exec: {
output: 'thrown string',
type: 'error',
error: true
}
},
{
setup: 'tsfail noerror',
exec: {
output: 'no error',
type: 'string',
error: false
}
}
]);
};
| /*
* Copyright 2012, Mozilla Foundation and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var helpers = require('./helpers');
exports.testBasic = function(options) {
return helpers.audit(options, [
{
setup: 'tsfail reject',
exec: {
output: 'rejected promise',
type: 'error',
error: true
}
},
{
setup: 'tsfail rejecttyped',
exec: {
output: '54',
type: 'number',
error: true
}
},
{
setup: 'tsfail throwerror',
exec: {
output: /thrown error$/,
type: 'error',
error: true
}
},
{
setup: 'tsfail throwstring',
exec: {
output: 'thrown string',
type: 'error',
error: true
}
},
{
setup: 'tsfail noerror',
exec: {
output: 'no error',
type: 'string',
error: false
}
}
]);
};
| Allow wider set of messages in exception tests | spawn-1007006: Allow wider set of messages in exception tests
If Task.spawn catches an exception message then it adds "Error: " onto
the front, so allow a slightly wider set of error messages when testing.
Signed-off-by: Joe Walker <7a17872fbb32c7d760c9a16ee3076daead11efcf@mozilla.com>
| JavaScript | apache-2.0 | mozilla/gcli,mozilla/gcli,joewalker/gcli,joewalker/gcli,mozilla/gcli | ---
+++
@@ -39,7 +39,7 @@
{
setup: 'tsfail throwerror',
exec: {
- output: 'thrown error',
+ output: /thrown error$/,
type: 'error',
error: true
} |
6288e418a248e997f1e6830d8bfa4e09d33a3717 | src/modules/getPrice/index.js | src/modules/getPrice/index.js | import module from '../../module'
import command from '../../components/command'
import axios from 'axios'
import humanize from '../../utils/humanize'
export default module(
command('getprice', 'Gets the Jita price of a given item.', async (state, message, args) => {
try {
const esiURL = 'https://esi.tech.ccp.is/latest/';
const {data: itemData} = await axios.get(
`${esiURL}search/?categories=inventorytype&datasource=tranquility&language=en-us&search=${args}`
);
const itemid = itemData.inventorytype[0];
const {data: priceData} = await axios.get(
`http://api.eve-central.com/api/marketstat/json?typeid=${itemid}&usesystem=30000142`
);
const sellFivePercent = humanize(priceData[0].sell.fivePercent);
const buyFivePercent = humanize(priceData[0].buy.fivePercent);
message.channel.sendMessage(
`__Price of **${args}** (or nearest match) in Jita__:\n` +
`**Sell**: ${sellFivePercent} ISK\n` +
`**Buy**: ${buyFivePercent} ISK`
)
} catch(e) {
console.error(e);
throw e
}
})
) | import module from '../../module'
import command from '../../components/command'
import axios from 'axios'
import humanize from '../../utils/humanize'
export default module(
command('getprice', 'Gets the Jita price of a given item.', async (state, message, args) => {
try {
const esiURL = 'https://esi.tech.ccp.is/latest/';
const {data: itemData} = await axios.get(
`${esiURL}search/?categories=inventorytype&datasource=tranquility&language=en-us&search=${args}`
);
const itemid = itemData.inventorytype[0];
const [{data: [priceData]}, {data: {name: itemName}}] = await Promise.all([
axios.get(`http://api.eve-central.com/api/marketstat/json?typeid=${itemid}&usesystem=30000142`),
axios.get(`${esiURL}universe/types/${itemid}/?datasource=tranquility&language=en-us`)
]);
const sellFivePercent = humanize(priceData.sell.fivePercent);
const buyFivePercent = humanize(priceData.buy.fivePercent);
message.channel.sendMessage(
`__Price of **${itemName}** in Jita__:\n` +
`**Sell**: ${sellFivePercent} ISK\n` +
`**Buy**: ${buyFivePercent} ISK`
)
} catch(e) {
console.error(e);
throw e
}
})
) | Modify getPrice to report name of item actually queried | Modify getPrice to report name of item actually queried
| JavaScript | mit | emensch/thonk9k | ---
+++
@@ -14,15 +14,16 @@
const itemid = itemData.inventorytype[0];
- const {data: priceData} = await axios.get(
- `http://api.eve-central.com/api/marketstat/json?typeid=${itemid}&usesystem=30000142`
- );
+ const [{data: [priceData]}, {data: {name: itemName}}] = await Promise.all([
+ axios.get(`http://api.eve-central.com/api/marketstat/json?typeid=${itemid}&usesystem=30000142`),
+ axios.get(`${esiURL}universe/types/${itemid}/?datasource=tranquility&language=en-us`)
+ ]);
- const sellFivePercent = humanize(priceData[0].sell.fivePercent);
- const buyFivePercent = humanize(priceData[0].buy.fivePercent);
+ const sellFivePercent = humanize(priceData.sell.fivePercent);
+ const buyFivePercent = humanize(priceData.buy.fivePercent);
message.channel.sendMessage(
- `__Price of **${args}** (or nearest match) in Jita__:\n` +
+ `__Price of **${itemName}** in Jita__:\n` +
`**Sell**: ${sellFivePercent} ISK\n` +
`**Buy**: ${buyFivePercent} ISK`
) |
56e76553bb5a4f6e44a4739fb4f9eb46dfbfa463 | src/plugins/FileVersioningPlugin.js | src/plugins/FileVersioningPlugin.js | let chokidar = require('chokidar');
let glob = require('glob');
/**
* Create a new plugin instance.
*
* @param {Array} files
*/
function FileVersioningPlugin(files = []) {
this.files = files;
}
/**
* Apply the plugin.
*/
FileVersioningPlugin.prototype.apply = function () {
if (this.files && Mix.isWatching()) {
this.watch(this.files);
}
Mix.listen('files-concatenated', file => {
file = new File(file);
// Find and delete all matching versioned files in the directory.
glob(path.join(file.base(), '**'), (err, files) => {
files.filter(file => {
return /\.(\w{20}|\w{32})(\..+)/.test(file);
}).forEach(file => new File(file).delete());
});
// Then create a fresh versioned file.
this.reversion(file.path());
});
};
/**
* Watch all relevant files for changes.
*
* @param {Object} files
* @param {Object} destination
*/
FileVersioningPlugin.prototype.watch = function (files, destination) {
chokidar.watch(files, { persistent: true })
.on('change', this.reversion);
};
/**
* Re-version the updated file.
*
* @param {string} updatedFile
*/
FileVersioningPlugin.prototype.reversion = function (updatedFile) {
let name = new File(updatedFile).version(false).pathFromPublic();
try { File.find(Mix.manifest.get(updatedFile)).delete(); }
catch (e) {}
Mix.manifest.add(name).refresh();
};
module.exports = FileVersioningPlugin;
| let chokidar = require('chokidar');
let glob = require('glob');
/**
* Create a new plugin instance.
*
* @param {Array} files
*/
function FileVersioningPlugin(files = []) {
this.files = files;
}
/**
* Apply the plugin.
*/
FileVersioningPlugin.prototype.apply = function () {
if (this.files && Mix.isWatching()) {
this.watch(this.files);
}
Mix.listen('files-concatenated', this.reversion);
};
/**
* Watch all relevant files for changes.
*
* @param {Object} files
* @param {Object} destination
*/
FileVersioningPlugin.prototype.watch = function (files, destination) {
chokidar.watch(files, { persistent: true })
.on('change', this.reversion);
};
/**
* Re-version the updated file.
*
* @param {string} updatedFile
*/
FileVersioningPlugin.prototype.reversion = function (updatedFile) {
updatedFile = new File(updatedFile);
try { File.find(Mix.manifest.get(updatedFile.pathFromPublic())).delete(); }
catch (e) {}
let name = updatedFile.version(false).pathFromPublic();
Mix.manifest.add(name).refresh();
};
module.exports = FileVersioningPlugin;
| Clean up file versioning handler | Clean up file versioning handler
| JavaScript | mit | JeffreyWay/laravel-mix | ---
+++
@@ -19,19 +19,7 @@
this.watch(this.files);
}
- Mix.listen('files-concatenated', file => {
- file = new File(file);
-
- // Find and delete all matching versioned files in the directory.
- glob(path.join(file.base(), '**'), (err, files) => {
- files.filter(file => {
- return /\.(\w{20}|\w{32})(\..+)/.test(file);
- }).forEach(file => new File(file).delete());
- });
-
- // Then create a fresh versioned file.
- this.reversion(file.path());
- });
+ Mix.listen('files-concatenated', this.reversion);
};
@@ -53,10 +41,12 @@
* @param {string} updatedFile
*/
FileVersioningPlugin.prototype.reversion = function (updatedFile) {
- let name = new File(updatedFile).version(false).pathFromPublic();
+ updatedFile = new File(updatedFile);
- try { File.find(Mix.manifest.get(updatedFile)).delete(); }
+ try { File.find(Mix.manifest.get(updatedFile.pathFromPublic())).delete(); }
catch (e) {}
+
+ let name = updatedFile.version(false).pathFromPublic();
Mix.manifest.add(name).refresh();
}; |
ad1554d353a332c2eed047b86c3ddbe5f4e3a6c4 | src/components/CenteredMap.js | src/components/CenteredMap.js | import React from 'react'
import PropTypes from 'prop-types'
import { Map, TileLayer, GeoJSON } from 'react-leaflet'
class CenteredMap extends React.PureComponent {
static propTypes = {
vectors: PropTypes.object.isRequired,
className: PropTypes.string,
frozen: PropTypes.bool,
lat: PropTypes.number,
lon: PropTypes.number,
zoom: PropTypes.number
}
static defaultProps = {
frozen: false,
lat: 47,
lon: 1,
zoom: 5
}
componentDidMount() {
if (this.vectors) {
this.setState({
bounds: this.vectors.leafletElement.getBounds()
})
}
}
render() {
const { vectors, className, frozen, lat, lon, zoom } = this.props
const { bounds } = this.state
return (
<Map
className={className}
center={[lat, lon]}
bounds={bounds}
minZoom={zoom}
dragging={!frozen}
scrollWheelZoom={false}
doubleClickZoom={false}
zoomControl={!frozen}
>
<TileLayer
attribution='© Contributeurs <a href="http://osm.org/copyright">OpenStreetMap</a>'
url='https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png'
/>
<GeoJSON
color='blue'
fillOpacity={0.1}
weight={2}
ref={vectors => { this.vectors = vectors }}
data={vectors}
/>
</Map>
)
}
}
export default CenteredMap
| import React from 'react'
import PropTypes from 'prop-types'
import { Map, TileLayer, GeoJSON } from 'react-leaflet'
class CenteredMap extends React.PureComponent {
static propTypes = {
vectors: PropTypes.object.isRequired,
className: PropTypes.string,
frozen: PropTypes.bool,
lat: PropTypes.number,
lon: PropTypes.number,
zoom: PropTypes.number
}
static defaultProps = {
frozen: false,
lat: 47,
lon: 1,
zoom: 5
}
componentDidMount() {
if (this.vectors) {
this.setState({
bounds: this.vectors.leafletElement.getBounds()
})
}
}
render() {
const { vectors, className, frozen, lat, lon, zoom } = this.props
const { bounds } = this.state
return (
<Map
className={className}
center={[lat, lon]}
bounds={bounds}
minZoom={zoom}
dragging={!frozen}
scrollWheelZoom={false}
doubleClickZoom={!frozen}
zoomControl={!frozen}
>
<TileLayer
attribution='© Contributeurs <a href="http://osm.org/copyright">OpenStreetMap</a>'
url='https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png'
/>
<GeoJSON
color='blue'
fillOpacity={0.1}
weight={2}
ref={vectors => { this.vectors = vectors }}
data={vectors}
/>
</Map>
)
}
}
export default CenteredMap
| Allow double click zoom when map is not frozen | Allow double click zoom when map is not frozen
| JavaScript | mit | sgmap/inspire,sgmap/inspire | ---
+++
@@ -40,7 +40,7 @@
minZoom={zoom}
dragging={!frozen}
scrollWheelZoom={false}
- doubleClickZoom={false}
+ doubleClickZoom={!frozen}
zoomControl={!frozen}
>
<TileLayer |
6e95c2af465fc296984e86b73192eca1c32c8f9d | lib/rules/load-average.js | lib/rules/load-average.js | var util = require('util');
var Duplex = require('stream').Duplex;
var LoadAverage = module.exports = function LoadAverage(options) {
this.warn = options.warn;
this.critical = options.critical;
Duplex.call(this, { objectMode: true });
};
util.inherits(LoadAverage, Duplex);
LoadAverage.prototype._write = function(chunk, _, cb) {
var split = chunk.name.split('.');
if (split[0] !== 'load-average') return cb();
var period = parseInt(split[1], 10);
if (!this.warn[period] || !this.critical[period]) return cb();
var nprocs = chunk.meta.nprocs;
var value = chunk.value.toFixed(2) + '/' + nprocs + ' CPUs';
var message = period + ' minute load average (' + value + ') on host ' + chunk.host;
if (chunk.value > this.critical[period] * nprocs)
{
this.push(
{
name: 'load-average',
host: chunk.host,
message: message,
status: 'critical',
value: value
});
}
else if (chunk.value > this.warn[period] * nprocs)
{
this.push(
{
name: 'load-average',
host: chunk.host,
message: message,
status: 'warning',
value: value
});
}
cb();
};
LoadAverage.prototype._read = function(){};
| var util = require('util');
var Duplex = require('stream').Duplex;
var LoadAverage = module.exports = function LoadAverage(options) {
this.warn = options.warn;
this.critical = options.critical;
Duplex.call(this, { objectMode: true });
};
util.inherits(LoadAverage, Duplex);
LoadAverage.prototype._write = function(chunk, _, cb) {
var split = chunk.name.split('.');
if (split[0] !== 'load-average') return cb();
var period = parseInt(split[1], 10);
if (!this.warn[period] || !this.critical[period]) return cb();
var nprocs = chunk.meta.nprocs;
var value = chunk.value.toFixed(2) + '/' + nprocs + ' CPUs';
var message = period + ' minute load average (' + value + ') on host ' + chunk.host;
if (chunk.value > this.critical[period] * nprocs)
{
this.push(
{
name: chunk.name,
host: chunk.host,
message: message,
status: 'critical',
value: value
});
}
else if (chunk.value > this.warn[period] * nprocs)
{
this.push(
{
name: chunk.name,
host: chunk.host,
message: message,
status: 'warning',
value: value
});
}
cb();
};
LoadAverage.prototype._read = function(){};
| Use event name for incident name | Use event name for incident name
| JavaScript | isc | numbat-metrics/numbat-analyzer,ceejbot/numbat-analyzer | ---
+++
@@ -25,7 +25,7 @@
{
this.push(
{
- name: 'load-average',
+ name: chunk.name,
host: chunk.host,
message: message,
status: 'critical',
@@ -36,7 +36,7 @@
{
this.push(
{
- name: 'load-average',
+ name: chunk.name,
host: chunk.host,
message: message,
status: 'warning', |
fff63aaf393903aa0830f1cf521b3edc775a152e | sdk/src/Constants.js | sdk/src/Constants.js | export default class Constants {
static get USER_ACCOUNT_KEY() { return btoa('blipSdkUAccount'); }
static get IFRAMEURL_LOCAL() { return 'http://localhost:3000/'; }
static get IFRAMEURL_HMG() { return 'https://hmg-sdkcommon.blip.ai/'; }
static get IFRAMEURL_PRD() { return 'https://sdkcommon.blip.ai/'; }
static get COOKIE_DATA_CODE() { return 'BlipSdkCookieData'; }
static get SEND_MESSAGE_CODE() { return 'SendMessage'; }
static get SDK_DEFAULT_TITLE() { return 'Estamos online'; }
static get SDK_DEFAULT_ICON_PATH() { return 'https://takenetomni.blob.core.windows.net/media-db/blip-app-white.png'; }
static get SDK_DEFAULT_WIDGET_COLOR() { return '#546E7A'; }
static get SDK_DEFAULT_Z_INDEX() { return 16000001; }
static get SDK_DEFAULT_HIDE_MENU() { return false; }
static get REQUEST_POST_MESSAGE_CODE() { return 'RequestPostMessage'; }
static get COOKIES_EXPIRATION() { return 365; }
static get MENU_VISIBILITY_CODE() { return 'BlipSdkMenuVisibility' }
} | export default class Constants {
static get USER_ACCOUNT_KEY() { return btoa('blipSdkUAccount'); }
static get IFRAMEURL_LOCAL() { return 'http://localhost:3000/'; }
static get IFRAMEURL_HMG() { return 'https://hmg-sdkcommon.blip.ai/'; }
static get IFRAMEURL_PRD() { return 'https://sdkcommon.blip.ai/'; }
static get COOKIE_DATA_CODE() { return 'BlipSdkCookieData'; }
static get SEND_MESSAGE_CODE() { return 'SendMessage'; }
static get SDK_DEFAULT_TITLE() { return 'Estamos online'; }
static get SDK_DEFAULT_ICON_PATH() { return 'https://takenetomni.blob.core.windows.net/media-db/blip-app-white.png'; }
static get SDK_DEFAULT_WIDGET_COLOR() { return '#546E7A'; }
static get SDK_DEFAULT_Z_INDEX() { return 16000001; }
static get SDK_DEFAULT_HIDE_MENU() { return false; }
static get REQUEST_POST_MESSAGE_CODE() { return 'RequestCookie'; }
static get COOKIES_EXPIRATION() { return 365; }
static get MENU_VISIBILITY_CODE() { return 'BlipSdkMenuVisibility' }
} | Change constant value for backward compatibility | Change constant value for backward compatibility
| JavaScript | apache-2.0 | takenet/blip-chat-web,takenet/blip-chat-web,takenet/blip-sdk-web,takenet/blip-sdk-web | ---
+++
@@ -10,7 +10,7 @@
static get SDK_DEFAULT_WIDGET_COLOR() { return '#546E7A'; }
static get SDK_DEFAULT_Z_INDEX() { return 16000001; }
static get SDK_DEFAULT_HIDE_MENU() { return false; }
- static get REQUEST_POST_MESSAGE_CODE() { return 'RequestPostMessage'; }
+ static get REQUEST_POST_MESSAGE_CODE() { return 'RequestCookie'; }
static get COOKIES_EXPIRATION() { return 365; }
static get MENU_VISIBILITY_CODE() { return 'BlipSdkMenuVisibility' }
} |
8a970c6b9bf037c10cdc55dc7fa27bcf20d393dc | test/config.spec.js | test/config.spec.js | 'use strict';
/*
config
->read from file, holds values and supplies as needed
*/
require('chai').should()
var config = require('../lib/config')()
describe('Config', () => {
describe('#getLayers', () => {
it('should return layers config array', () => {
//Given
//When
var layers = config.getLayers()
//Then
layers.should.be.an('array')
layers[0].name.should.be.a('string')
})
})
describe('#getMap', () => {
it('should return map config object', () => {
//Given
//When
var map = config.getMap()
//Then
map.should.be.an('object')
map.tileLayers.should.be.an('array')
})
})
})
| 'use strict';
/*
config
->read from file, holds values and supplies as needed
*/
require('chai').should()
var config = require('../lib/config')()
describe('Config', () => {
describe('#getLayers', () => {
it('should return layers config array', () => {
//Given
//When
var layers = config.getLayers()
//Then
layers.should.be.an('array')
layers[0].name.should.be.a('string')
})
})
describe('#getMap', () => {
it('should return map config object', () => {
//Given
//When
var map = config.getMap()
//Then
map.should.be.an('object')
map.tileLayers.should.be.an('object')
})
})
})
| Update test to reflect config file change | Update test to reflect config file change
| JavaScript | mit | mediasuitenz/mappy,mediasuitenz/mappy | ---
+++
@@ -32,7 +32,7 @@
//Then
map.should.be.an('object')
- map.tileLayers.should.be.an('array')
+ map.tileLayers.should.be.an('object')
})
})
|
60fbc2e4405a2168223266f950488dfacb8b2f0a | Player.js | Player.js | /* global Entity */
(function() {
'use strict';
function Player(x, y, speed) {
this.base = Entity;
this.base(
x,
y,
Player.width,
Player.height,
'public/images/sprites/heroes.png',
56,
12,
speed || 150
);
}
Player.width = 32;
Player.height = 52;
Player.prototype = new Entity();
// Make Player available globally
window.Player = Player;
}());
| /* global Entity */
(function() {
'use strict';
function Player(x, y, speed) {
this.base = Entity;
this.base(
x,
y,
Player.width,
Player.height,
'public/images/sprites/heroes.png',
105,
142,
speed || 150
);
}
Player.width = 32;
Player.height = 48;
Player.prototype = new Entity();
// Make Player available globally
window.Player = Player;
}());
| Change player sprite to show hero facing the zombies | Change player sprite to show hero facing the zombies
| JavaScript | mit | handrus/zombies-game,brunops/zombies-game,brunops/zombies-game | ---
+++
@@ -10,14 +10,14 @@
Player.width,
Player.height,
'public/images/sprites/heroes.png',
- 56,
- 12,
+ 105,
+ 142,
speed || 150
);
}
Player.width = 32;
- Player.height = 52;
+ Player.height = 48;
Player.prototype = new Entity();
|
dc9a45d38a5857472b7d9a72f7c2363276cc4efc | tdd/server/palindrome/test/palindrome-test.js | tdd/server/palindrome/test/palindrome-test.js | var expect = require('chai').expect;
var isPalindrome = require('../src/palindrome');
describe('palindrome-test', function() {
it('should pass the canary test', function() {
expect(true).to.be.true;
});
it('should return true when passed "mom"', function() {
expect(isPalindrome('mom')).to.be.true;
});
});
| /*
* Test ideas
*
* 'dad' is a palindrome
* 'dude' is not a palindrome
* 'mom mom' is a palindrome
* 'dad dae' is a palindrome'
*/
var expect = require('chai').expect;
var isPalindrome = require('../src/palindrome');
describe('palindrome-test', function() {
it('should pass the canary test', function() {
expect(true).to.be.true;
});
it('should return true when passed "mom"', function() {
expect(isPalindrome('mom')).to.be.true;
});
it('should return true when passed "dad"', function() {
expect(isPalindrome('dad')).to.be.true;
});
});
| Add test: 'dad' is a palindrome | Add test: 'dad' is a palindrome
| JavaScript | apache-2.0 | mrwizard82d1/tdjsa | ---
+++
@@ -1,3 +1,12 @@
+/*
+ * Test ideas
+ *
+ * 'dad' is a palindrome
+ * 'dude' is not a palindrome
+ * 'mom mom' is a palindrome
+ * 'dad dae' is a palindrome'
+ */
+
var expect = require('chai').expect;
var isPalindrome = require('../src/palindrome');
@@ -9,4 +18,8 @@
it('should return true when passed "mom"', function() {
expect(isPalindrome('mom')).to.be.true;
});
+
+ it('should return true when passed "dad"', function() {
+ expect(isPalindrome('dad')).to.be.true;
+ });
}); |
aa9717b62f1a0c0e41f06e9f54393d8cd55769f9 | templates/demo/config/namesystem.js | templates/demo/config/namesystem.js | module.exports = {
default: {
available_providers: ["ens", "ipns"],
provider: "ens",
register: {
rootDomain: "embark.eth",
subdomains: {
'status': '0x1a2f3b98e434c02363f3dac3174af93c1d690914'
}
}
}
};
| module.exports = {
default: {
available_providers: ["ens", "ipns"],
provider: "ens"
},
development: {
register: {
rootDomain: "embark.eth",
subdomains: {
'status': '0x1a2f3b98e434c02363f3dac3174af93c1d690914'
}
}
}
};
| Move name config to development | [CHORES] Move name config to development
| JavaScript | mit | iurimatias/embark-framework,iurimatias/embark-framework | ---
+++
@@ -1,7 +1,10 @@
module.exports = {
default: {
available_providers: ["ens", "ipns"],
- provider: "ens",
+ provider: "ens"
+ },
+
+ development: {
register: {
rootDomain: "embark.eth",
subdomains: { |
2d14e852c9c833eeec7b63a76102ce4dc29bd2cb | angular/app-foundation.module.js | angular/app-foundation.module.js | /**
* Created by anonymous on 13/12/15 11:09.
*/
(function() {
'use strict';
angular
.module('appFoundation', [
/* Angularjs */
'ngMaterial',
'ngMessages',
'ngResource',
/* 3rd-party */
'ui.router',
'satellizer',
'restangular',
'ngStorage',
'angular-loading-bar',
'ngMdIcons',
'toastr',
'vAccordion',
'md.data.table',
/* Intra-services */
'inServices.exception',
'inServices.logger',
'inServices.routes'
]);
angular.module('widgets', []);
angular.module('inServices.exception', []);
angular.module('inServices.logger', []);
angular.module('inServices.routes', []);
})(); | /**
* Created by anonymous on 13/12/15 11:09.
*/
(function() {
'use strict';
angular
.module('appFoundation', [
/* Angularjs */
'ngMaterial',
'ngMessages',
'ngResource',
/* 3rd-party */
'ui.router',
'satellizer',
'restangular',
'ngStorage',
'angular-loading-bar',
'ngMdIcons',
'toastr',
'vAccordion',
/* Intra-services */
'inServices.exception',
'inServices.logger',
'inServices.routes'
]);
angular.module('widgets', []);
angular.module('inServices.exception', []);
angular.module('inServices.logger', []);
angular.module('inServices.routes', []);
})(); | Update bower @ Uninstall angular-material-data-table | Update bower @ Uninstall angular-material-data-table
| JavaScript | mit | onderdelen/app-foundation,componeint/app-foundation,onderdelen/app-foundation,onderdelen/app-foundation,componeint/app-foundation,componeint/app-foundation,consigliere/app-foundation,consigliere/app-foundation,consigliere/app-foundation | ---
+++
@@ -21,7 +21,6 @@
'ngMdIcons',
'toastr',
'vAccordion',
- 'md.data.table',
/* Intra-services */
'inServices.exception', |
fa449ed86a6bfde93654bba283a8c7cc4788bc61 | test/journals-getDokumenter-test.js | test/journals-getDokumenter-test.js | 'use strict'
const tap = require('tap')
const getDokumenter = require('../lib/journals/getDokumenter')
tap.test('Requires options to be specified', function (test) {
const options = false
const expectedErrorMessage = 'Missing required input: options object'
getDokumenter(options, function (error, data) {
tap.equal(error.message, expectedErrorMessage, expectedErrorMessage)
test.done()
})
})
tap.test('Requires options.host to be specified', function (test) {
const options = {
host: false
}
const expectedErrorMessage = 'Missing required input: options.host'
getDokumenter(options, function (error, data) {
tap.equal(error.message, expectedErrorMessage, expectedErrorMessage)
test.done()
})
})
tap.test('Requires options.journalpostid to be specified', function (test) {
const options = {
host: true,
journalpostid: false
}
const expectedErrorMessage = 'Missing required input: options.journalpostid'
getDokumenter(options, function (error, data) {
tap.equal(error.message, expectedErrorMessage, expectedErrorMessage)
test.done()
})
})
| 'use strict'
const tap = require('tap')
const getDokumenter = require('../lib/journals/getDokumenter')
tap.test('Requires options to be specified', function (test) {
const options = false
const expectedErrorMessage = 'Missing required input: options object'
getDokumenter(options, function (error, data) {
tap.equal(error.message, expectedErrorMessage, expectedErrorMessage)
test.end()
})
})
tap.test('Requires options.host to be specified', function (test) {
const options = {
host: false
}
const expectedErrorMessage = 'Missing required input: options.host'
getDokumenter(options, function (error, data) {
tap.equal(error.message, expectedErrorMessage, expectedErrorMessage)
test.end()
})
})
tap.test('Requires options.journalpostid to be specified', function (test) {
const options = {
host: true,
journalpostid: false
}
const expectedErrorMessage = 'Missing required input: options.journalpostid'
getDokumenter(options, function (error, data) {
tap.equal(error.message, expectedErrorMessage, expectedErrorMessage)
test.end()
})
})
| Replace test.done with test.end (patch) | Replace test.done with test.end (patch)
| JavaScript | mit | zrrrzzt/edemokrati | ---
+++
@@ -8,7 +8,7 @@
const expectedErrorMessage = 'Missing required input: options object'
getDokumenter(options, function (error, data) {
tap.equal(error.message, expectedErrorMessage, expectedErrorMessage)
- test.done()
+ test.end()
})
})
@@ -19,7 +19,7 @@
const expectedErrorMessage = 'Missing required input: options.host'
getDokumenter(options, function (error, data) {
tap.equal(error.message, expectedErrorMessage, expectedErrorMessage)
- test.done()
+ test.end()
})
})
@@ -31,6 +31,6 @@
const expectedErrorMessage = 'Missing required input: options.journalpostid'
getDokumenter(options, function (error, data) {
tap.equal(error.message, expectedErrorMessage, expectedErrorMessage)
- test.done()
+ test.end()
})
}) |
0492af81a8140b89347ea721f46fcc71088466d8 | test/lib/api-util/api-util-test.js | test/lib/api-util/api-util-test.js | 'use strict';
const preq = require('preq');
const assert = require('../../utils/assert');
const mwapi = require('../../../lib/mwapi');
const logger = require('bunyan').createLogger({
name: 'test-logger',
level: 'warn'
});
logger.log = function(a, b) {};
describe('lib:apiUtil', function() {
this.timeout(20000); // eslint-disable-line no-invalid-this
it('checkForQueryPagesInResponse should return 504 when query.pages are absent', () => {
return preq.post({
uri: 'https://commons.wikimedia.org/w/api.php',
body: {
action: 'query',
format: 'json',
formatversion: 2,
generator: 'images',
prop: 'imageinfo|revisions',
iiextmetadatafilter: 'ImageDescription',
iiextmetadatamultilang: true,
iiprop: 'url|extmetadata|dimensions',
iiurlwidth: 1024,
rawcontinue: '',
titles: `Template:Potd/1980-07-06`
}
}).then((response) => {
assert.throws(() => {
mwapi.checkForQueryPagesInResponse({ logger }, response);
}, /api_error/);
});
});
});
| 'use strict';
const assert = require('../../utils/assert');
const mwapi = require('../../../lib/mwapi');
const logger = require('bunyan').createLogger({
name: 'test-logger',
level: 'warn'
});
logger.log = function(a, b) {};
describe('lib:apiUtil', () => {
it('checkForQueryPagesInResponse should return 504 when query.pages are absent', () => {
return new Promise((resolve) => {
return resolve({});
}).then((response) => {
assert.throws(() => {
mwapi.checkForQueryPagesInResponse({ logger }, response);
}, /api_error/);
});
});
});
| Remove unnecessary API call in unit test | Remove unnecessary API call in unit test
We do not need to hit the API in this test. It's unnecessary and makes
the test harder to comprehend.
Instead of testing this way, simulate a promise that resolves without
pages.
(npm run test:unit should work without an internet connection)
Change-Id: Iee834114890a64c96ccf255601503a25efd884bc
| JavaScript | apache-2.0 | wikimedia/mediawiki-services-mobileapps,wikimedia/mediawiki-services-mobileapps,wikimedia/mediawiki-services-mobileapps,wikimedia/mediawiki-services-mobileapps,wikimedia/mediawiki-services-mobileapps,wikimedia/mediawiki-services-mobileapps | ---
+++
@@ -1,6 +1,5 @@
'use strict';
-const preq = require('preq');
const assert = require('../../utils/assert');
const mwapi = require('../../../lib/mwapi');
@@ -11,26 +10,11 @@
logger.log = function(a, b) {};
-describe('lib:apiUtil', function() {
-
- this.timeout(20000); // eslint-disable-line no-invalid-this
+describe('lib:apiUtil', () => {
it('checkForQueryPagesInResponse should return 504 when query.pages are absent', () => {
- return preq.post({
- uri: 'https://commons.wikimedia.org/w/api.php',
- body: {
- action: 'query',
- format: 'json',
- formatversion: 2,
- generator: 'images',
- prop: 'imageinfo|revisions',
- iiextmetadatafilter: 'ImageDescription',
- iiextmetadatamultilang: true,
- iiprop: 'url|extmetadata|dimensions',
- iiurlwidth: 1024,
- rawcontinue: '',
- titles: `Template:Potd/1980-07-06`
- }
+ return new Promise((resolve) => {
+ return resolve({});
}).then((response) => {
assert.throws(() => {
mwapi.checkForQueryPagesInResponse({ logger }, response); |
9eaa53c31ddb5170a9cd3d81e4fc4846a370b6ba | addon/change-gate.js | addon/change-gate.js | import Em from 'ember';
var get = Em.get;
var defaultFilter = function(value) { return value; };
export default function(dependentKey, filter) {
filter = filter || defaultFilter;
var computed = Em.computed(function handler(key) {
var meta = computed.meta();
meta.hasObserver = false;
meta.lastValue = null;
var isFirstRun = !meta.hasObserver;
if(isFirstRun) { //setup an observer which is responsible for notifying property changes
var value = filter(get(this, dependentKey));
meta.hasObserver = true;
meta.lastValue = value;
this.addObserver(dependentKey, function() {
var newValue = filter(get(this, dependentKey));
var lastValue = meta.lastValue;
if(newValue !== lastValue) {
meta.lastValue = value;
this.notifyPropertyChange(key);
}
});
return value;
} else {
return meta.lastValue;
}
});
return computed;
}
| import Em from 'ember';
var get = Em.get,
getMeta = Em.getMeta,
setMeta = Em.setMeta;
var defaultFilter = function(value) { return value; };
export default function(dependentKey, filter) {
filter = filter || defaultFilter;
return Em.computed(function(key) {
var hasObserverKey = '_changeGate:%@:hasObserver'.fmt(key);
var lastValueKey = '_changeGate:%@:lastValue'.fmt(key);
var isFirstRun = !getMeta(this, hasObserverKey);
if(isFirstRun) { //setup an observer which is responsible for notifying property changes
var value = filter(get(this, dependentKey));
setMeta(this, hasObserverKey, true);
setMeta(this, lastValueKey, value);
this.addObserver(dependentKey, function() {
var newValue = filter(get(this, dependentKey));
var lastValue = getMeta(this, lastValueKey);
if(newValue !== lastValue) {
setMeta(this, lastValueKey, newValue);
this.notifyPropertyChange(key);
}
});
return value;
} else {
return getMeta(this, lastValueKey);
}
});
}
| Revert "Refactored macro to use ComputedProperty meta instead of object's meta" | Revert "Refactored macro to use ComputedProperty meta instead of object's meta"
| JavaScript | mit | givanse/ember-computed-change-gate,GavinJoyce/ember-computed-change-gate,givanse/ember-computed-change-gate,GavinJoyce/ember-computed-change-gate | ---
+++
@@ -1,39 +1,38 @@
import Em from 'ember';
-var get = Em.get;
+var get = Em.get,
+ getMeta = Em.getMeta,
+ setMeta = Em.setMeta;
var defaultFilter = function(value) { return value; };
export default function(dependentKey, filter) {
filter = filter || defaultFilter;
- var computed = Em.computed(function handler(key) {
- var meta = computed.meta();
- meta.hasObserver = false;
- meta.lastValue = null;
- var isFirstRun = !meta.hasObserver;
+ return Em.computed(function(key) {
+ var hasObserverKey = '_changeGate:%@:hasObserver'.fmt(key);
+ var lastValueKey = '_changeGate:%@:lastValue'.fmt(key);
+ var isFirstRun = !getMeta(this, hasObserverKey);
if(isFirstRun) { //setup an observer which is responsible for notifying property changes
var value = filter(get(this, dependentKey));
- meta.hasObserver = true;
- meta.lastValue = value;
+ setMeta(this, hasObserverKey, true);
+ setMeta(this, lastValueKey, value);
this.addObserver(dependentKey, function() {
var newValue = filter(get(this, dependentKey));
- var lastValue = meta.lastValue;
+ var lastValue = getMeta(this, lastValueKey);
if(newValue !== lastValue) {
- meta.lastValue = value;
+ setMeta(this, lastValueKey, newValue);
this.notifyPropertyChange(key);
}
});
return value;
} else {
- return meta.lastValue;
+ return getMeta(this, lastValueKey);
}
});
-
- return computed;
} |
daf08f7840abf24d076c604fb58ca0771c79a25c | snippets/device.js | snippets/device.js | const {TextView, device, ui} = require('tabris');
// Display available device information
['platform', 'version', 'model', 'language', 'orientation'].forEach((property) => {
new TextView({
id: property,
left: 10, right: 10, top: 'prev() 10',
text: property + ': ' + device[property]
}).appendTo(ui.contentView);
});
device.on('orientationChanged', ({value: orientation}) => {
ui.contentView.find('#orientation').set('text', 'orientation: ' + orientation);
});
| const {TextView, device, ui} = require('tabris');
// Display available device information
['platform', 'version', 'model', 'vendor', 'language', 'orientation'].forEach((property) => {
new TextView({
id: property,
left: 10, right: 10, top: 'prev() 10',
text: property + ': ' + device[property]
}).appendTo(ui.contentView);
});
device.on('orientationChanged', ({value: orientation}) => {
ui.contentView.find('#orientation').set('text', 'orientation: ' + orientation);
});
| Add "vendor" to list of printed properties | Add "vendor" to list of printed properties
| JavaScript | bsd-3-clause | eclipsesource/tabris-js,eclipsesource/tabris-js,eclipsesource/tabris-js | ---
+++
@@ -2,7 +2,7 @@
// Display available device information
-['platform', 'version', 'model', 'language', 'orientation'].forEach((property) => {
+['platform', 'version', 'model', 'vendor', 'language', 'orientation'].forEach((property) => {
new TextView({
id: property,
left: 10, right: 10, top: 'prev() 10', |
ced91cef769326b288b6741f3e1474ee9cb89a29 | core/providers/totalwind/extractor.js | core/providers/totalwind/extractor.js | 'use strict'
var extract = require('../../extract')
var lodash = require('lodash')
var CONST = {
SOURCE_NAME: 'totalwind',
IGNORE_LOG_PROPS: ['updatedAt', 'createdAt', 'link', 'title', 'provider']
}
function createExtractor (type, category) {
function extractor (data) {
data.type = type
data.provider = CONST.SOURCE_NAME
data.category = category
var raw = lodash.lowerCase(data.title)
var dataExtract = {
price: extract.price(raw),
year: extract.year(raw)
}
if (lodash.isEqual(category, 'sails'))
lodash.assign(dataExtract, extract.sail(raw))
lodash.merge(data, dataExtract)
var self = this
this.validate(data, function (validationError, instance) {
++self.stats.total
if (!validationError) {
self.log.info(lodash.omit(instance, CONST.IGNORE_LOG_PROPS))
++self.stats.valid
var category = instance.category
if (self.db[category]) {
++self.stats.add
self.db[category].addObject(instance)
}
} else {
self.log.debug(validationError)
}
})
}
return extractor
}
module.exports = createExtractor
| 'use strict'
var isBlacklisted = require('../../schema/is-blacklisted')
var extract = require('../../extract')
var lodash = require('lodash')
var CONST = {
SOURCE_NAME: 'totalwind',
IGNORE_LOG_PROPS: ['updatedAt', 'createdAt', 'link', 'title', 'provider']
}
function createExtractor (type, category) {
function extractor (data) {
if (isBlacklisted(data.title)) return
data.type = type
data.provider = CONST.SOURCE_NAME
data.category = category
var raw = lodash.lowerCase(data.title)
var dataExtract = {
price: extract.price(raw),
year: extract.year(raw)
}
if (lodash.isEqual(category, 'sails'))
lodash.assign(dataExtract, extract.sail(raw))
lodash.merge(data, dataExtract)
var self = this
this.validate(data, function (validationError, instance) {
++self.stats.total
if (!validationError) {
self.log.info(lodash.omit(instance, CONST.IGNORE_LOG_PROPS))
++self.stats.valid
var category = instance.category
if (self.db[category]) {
++self.stats.add
self.db[category].addObject(instance)
}
} else {
self.log.debug(validationError)
}
})
}
return extractor
}
module.exports = createExtractor
| Check first censure words before analyze | Check first censure words before analyze
| JavaScript | mit | windtoday/windtoday-core,windtoday/windtoday-core | ---
+++
@@ -1,5 +1,6 @@
'use strict'
+var isBlacklisted = require('../../schema/is-blacklisted')
var extract = require('../../extract')
var lodash = require('lodash')
@@ -10,6 +11,8 @@
function createExtractor (type, category) {
function extractor (data) {
+ if (isBlacklisted(data.title)) return
+
data.type = type
data.provider = CONST.SOURCE_NAME
data.category = category |
ea7bb1e48593306441da54337b82ba9b10452703 | bin/siteshooter.js | bin/siteshooter.js | #! /usr/bin/env node
'use strict';
var chalk = require('chalk'),
pkg = require('../package.json');
var nodeVersion = process.version.replace('v',''),
nodeVersionRequired = pkg.engines.node.replace('>=','');
// check node version compatibility
if(nodeVersion <= nodeVersionRequired){
console.log();
console.error(chalk.red.bold('✗ '), chalk.red.bold('Siteshooter requires node version ' + pkg.engines.node));
console.log();
process.exit(1);
}
var siteshooter = require('../index'),
args = [].slice.call(process.argv, 2);
var exitCode = 0,
isDebug = args.indexOf('--debug') !== -1;
siteshooter.cli(args).then(function() {
if (isDebug) {
console.log('CLI promise complete');
}
process.exit(exitCode);
}).catch(function(err) {
exitCode = 1;
if (!isDebug) {
console.error(err.stack);
}
process.exit(exitCode);
});
process.on('exit', function() {
if (isDebug) {
console.log('EXIT', arguments);
}
process.exit(exitCode);
});
| #! /usr/bin/env node
'use strict';
var chalk = require('chalk'),
pkg = require('../package.json');
var nodeVersion = process.version.replace('v',''),
nodeVersionRequired = pkg.engines.node.replace('>=','');
// check node version compatibility
if(nodeVersion <= nodeVersionRequired){
console.log();
console.error(chalk.red.bold('✗ '), chalk.red.bold('NODE ' + process.version + ' was detected. Siteshooter requires node version ' + pkg.engines.node));
console.log();
process.exit(1);
}
else{
// check for new version of Siteshooter
var updater = require('update-notifier');
updater({pkg: pkg}).notify({defer: true});
}
var siteshooter = require('../index'),
args = [].slice.call(process.argv, 2);
var exitCode = 0,
isDebug = args.indexOf('--debug') !== -1;
siteshooter.cli(args).then(function() {
if (isDebug) {
console.log('CLI promise complete');
}
process.exit(exitCode);
}).catch(function(err) {
exitCode = 1;
if (!isDebug) {
console.error(err.stack);
}
process.exit(exitCode);
});
process.on('exit', function() {
if (isDebug) {
console.log('EXIT', arguments);
}
process.exit(exitCode);
});
| Move update notifier to bin | Move update notifier to bin
| JavaScript | mpl-2.0 | devopsgroup-io/siteshooter | ---
+++
@@ -7,14 +7,20 @@
var nodeVersion = process.version.replace('v',''),
nodeVersionRequired = pkg.engines.node.replace('>=','');
+
// check node version compatibility
if(nodeVersion <= nodeVersionRequired){
+ console.log();
+ console.error(chalk.red.bold('✗ '), chalk.red.bold('NODE ' + process.version + ' was detected. Siteshooter requires node version ' + pkg.engines.node));
+ console.log();
+ process.exit(1);
+}
+else{
- console.log();
- console.error(chalk.red.bold('✗ '), chalk.red.bold('Siteshooter requires node version ' + pkg.engines.node));
- console.log();
+ // check for new version of Siteshooter
+ var updater = require('update-notifier');
- process.exit(1);
+ updater({pkg: pkg}).notify({defer: true});
}
var siteshooter = require('../index'), |
8506adb0cd6e8dc13a2deefcd349a1826be6f567 | src/aspects/equality.js | src/aspects/equality.js | // @flow
import { Record } from 'immutable';
import { Type } from './tm';
import EvaluationResult from './evaluation';
const EqualityShape = Record({
of: null, // Tm
type: Type.singleton,
}, 'equality');
// Propositional Equality type
export class Equality extends EqualityShape {
static arity = [0];
map(): Equality {
throw new Error('unimplemented - Equality.map');
}
step(): EvaluationResult {
throw new Error('unimplemented - Equality.step');
}
}
const ReflShape = Record({
left: null, // Tm
right: null, // Tm
type: Type.singleton,
}, 'refl');
// TODO come up with appropriate name for this
export class Refl extends ReflShape {
static arity = [0, 0];
map(): Equality {
throw new Error('unimplemented - Refl.map');
}
step(): EvaluationResult {
throw new Error('unimplemented - Refl.step');
}
}
| // @flow
import { Record } from 'immutable';
import { Type } from '../theory/tm';
import { EvaluationResult } from '../theory/evaluation';
const EqualityShape = Record({
of: null, // Tm
type: Type.singleton,
}, 'equality');
// Propositional Equality type
export class Equality extends EqualityShape {
static arity = [0];
map(): Equality {
throw new Error('unimplemented - Equality.map');
}
step(): EvaluationResult {
throw new Error('unimplemented - Equality.step');
}
}
const ReflShape = Record({
left: null, // Tm
right: null, // Tm
type: Type.singleton,
}, 'refl');
// TODO come up with appropriate name for this
export class Refl extends ReflShape {
static arity = [0, 0];
map(): Equality {
throw new Error('unimplemented - Refl.map');
}
step(): EvaluationResult {
throw new Error('unimplemented - Refl.step');
}
}
| Fix import errors flow found. | Fix import errors flow found.
| JavaScript | mit | joelburget/pigment | ---
+++
@@ -1,8 +1,8 @@
// @flow
import { Record } from 'immutable';
-import { Type } from './tm';
-import EvaluationResult from './evaluation';
+import { Type } from '../theory/tm';
+import { EvaluationResult } from '../theory/evaluation';
const EqualityShape = Record({ |
9ad30d7fb666403f0a74e5905ef928be13547a7b | gulpfile.js | gulpfile.js | 'use strict';
const path = require('path');
const gulp = require('gulp');
const eslint = require('gulp-eslint');
const spawn = require('cross-spawn');
const excludeGitignore = require('gulp-exclude-gitignore');
const nsp = require('gulp-nsp');
gulp.task('nsp', nodeSecurityProtocol);
gulp.task('watch', watch);
gulp.task('static', eslintCheck);
gulp.task('test', gulp.series([avaTest, nycReport]));
gulp.task('prepublish', gulp.series('nsp'));
gulp.task('default', gulp.series('static', 'test'));
function nodeSecurityProtocol(cb) {
nsp({package: path.resolve('package.json')}, cb);
}
function eslintCheck() {
return gulp.src(['**/*.js', '!**/templates/**'])
.pipe(excludeGitignore())
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
}
function avaTest() {
return spawn('./node_modules/.bin/nyc', ['--all', '--reporter=lcov', './node_modules/.bin/ava'], {stdio: 'inherit'});
}
function nycReport() {
return spawn('./node_modules/.bin/nyc', ['report', '--colors'], {stdio: 'inherit'});
}
function watch() {
return spawn('./node_modules/.bin/nyc', ['--all', '--reporter=lcov', './node_modules/.bin/ava', '--watch'], {stdio: 'inherit'});
}
| 'use strict';
const path = require('path');
const gulp = require('gulp');
const eslint = require('gulp-eslint');
const spawn = require('cross-spawn');
const excludeGitignore = require('gulp-exclude-gitignore');
const nsp = require('gulp-nsp');
gulp.task('nsp', nodeSecurityProtocol);
gulp.task('watch', watch);
gulp.task('static', eslintCheck);
gulp.task('test', gulp.series([avaTest, nycReport]));
gulp.task('prepublish', gulp.series('nsp'));
gulp.task('default', gulp.series('static', 'test'));
function nodeSecurityProtocol(cb) {
nsp({package: path.resolve('package.json')}, cb);
}
function eslintCheck() {
return gulp.src(['**/*.js', '!**/templates/**', '!test/assets/**'])
.pipe(excludeGitignore())
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
}
function avaTest() {
return spawn('./node_modules/.bin/nyc', ['--all', '--reporter=lcov', './node_modules/.bin/ava'], {stdio: 'inherit'});
}
function nycReport() {
return spawn('./node_modules/.bin/nyc', ['report', '--colors'], {stdio: 'inherit'});
}
function watch() {
return spawn('./node_modules/.bin/nyc', ['--all', '--reporter=lcov', './node_modules/.bin/ava', '--watch'], {stdio: 'inherit'});
}
| Disable lint for test assets | Disable lint for test assets
| JavaScript | mit | FountainJS/generator-fountain-systemjs,FountainJS/generator-fountain-systemjs | ---
+++
@@ -20,7 +20,7 @@
}
function eslintCheck() {
- return gulp.src(['**/*.js', '!**/templates/**'])
+ return gulp.src(['**/*.js', '!**/templates/**', '!test/assets/**'])
.pipe(excludeGitignore())
.pipe(eslint())
.pipe(eslint.format()) |
c62191bfcb066f9f544f3df019db32da48dbbeee | test/examples/Counter-test.js | test/examples/Counter-test.js | /** @jsx createElement */
const {createElement, createEventHandler, render} = Yolk
function Counter () {
const handlePlus = createEventHandler(1, 0)
const handleMinus = createEventHandler(-1, 0)
const count = handlePlus.merge(handleMinus).scan((x, y) => x+y, 0)
return (
<div>
<button id="plus" onClick={handlePlus}>+</button>
<button id="minus" onClick={handleMinus}>-</button>
<span>{count}</span>
</div>
)
}
describe(`A simple counter`, () => {
it(`increments and decrements a number`, () => {
const component = <Counter />
const node = document.createElement(`div`)
render(component, node)
assert.equal(node.innerHTML, `<div><button id="plus">+</button><button id="minus">-</button><span>0</span></div>`)
const plus = node.querySelector(`#plus`)
const minus = node.querySelector(`#minus`)
plus.click()
plus.click()
plus.click()
minus.click()
assert.equal(node.innerHTML, `<div><button id="plus">+</button><button id="minus">-</button><span>2</span></div>`)
})
})
| /** @jsx createElement */
const {createElement, createEventHandler, render} = Yolk
function Counter () {
const handlePlus = createEventHandler(1)
const handleMinus = createEventHandler(-1)
const count = handlePlus.merge(handleMinus).scan((x, y) => x+y, 0).startWith(0)
return (
<div>
<button id="plus" onClick={handlePlus}>+</button>
<button id="minus" onClick={handleMinus}>-</button>
<span>{count}</span>
</div>
)
}
describe(`A simple counter`, () => {
it(`increments and decrements a number`, () => {
const component = <Counter />
const node = document.createElement(`div`)
render(component, node)
assert.equal(node.innerHTML, `<div><button id="plus">+</button><button id="minus">-</button><span>0</span></div>`)
const plus = node.querySelector(`#plus`)
const minus = node.querySelector(`#minus`)
plus.click()
plus.click()
plus.click()
minus.click()
assert.equal(node.innerHTML, `<div><button id="plus">+</button><button id="minus">-</button><span>2</span></div>`)
})
})
| Update Counter test to no relying on initial values for event handlers | Update Counter test to no relying on initial values for event handlers
| JavaScript | mit | StateFarmIns/yolk,garbles/yolk,KenPowers/yolk,yolkjs/yolk,jadbox/yolk,brandonpayton/yolk,kamilogorek/yolk,BrewhouseTeam/yolk,knpwrs/yolk | ---
+++
@@ -3,9 +3,9 @@
const {createElement, createEventHandler, render} = Yolk
function Counter () {
- const handlePlus = createEventHandler(1, 0)
- const handleMinus = createEventHandler(-1, 0)
- const count = handlePlus.merge(handleMinus).scan((x, y) => x+y, 0)
+ const handlePlus = createEventHandler(1)
+ const handleMinus = createEventHandler(-1)
+ const count = handlePlus.merge(handleMinus).scan((x, y) => x+y, 0).startWith(0)
return (
<div> |
1ed8856f1a4861213c73b857582a18e6c836a7ef | gulpfile.js | gulpfile.js | var gulp = require('gulp'),
jsdoc = require('gulp-jsdoc'),
docsSrcDir = './assets/js/**/*.js',
docsDestDir = './docs/js',
jsDocTask;
jsDocTask = function() {
return gulp.src(docsSrcDir)
.pipe(
jsdoc(docsDestDir,
{
path: './node_modules/jaguarjs-jsdoc',
applicationName: 'Dough JavaScript',
cleverLinks: true,
copyright: 'Copyright Money Advice Service ©',
linenums: true,
collapseSymbols: false
},
{
plugins: ['plugins/markdown'],
}
)
);
};
gulp.task('default', ['jsdoc']);
gulp.task('jsdoc', jsDocTask);
gulp.task('watch', function() {
jsDocTask();
gulp.watch(docsSrcDir, ['jsdoc']);
});
| var gulp = require('gulp'),
jsdoc = require('gulp-jsdoc'),
ghPages = require('gulp-gh-pages'),
docsSrcDir = './assets/js/**/*.js',
docsDestDir = './docs/js',
jsDocTask;
jsDocTask = function() {
return gulp.src(docsSrcDir)
.pipe(
jsdoc(docsDestDir,
{
path: './node_modules/jaguarjs-jsdoc',
applicationName: 'Dough JavaScript',
cleverLinks: true,
copyright: 'Copyright Money Advice Service ©',
linenums: true,
collapseSymbols: false
},
{
plugins: ['plugins/markdown'],
}
)
);
};
gulp.task('deploy', function() {
return gulp.src(docsDestDir + '/**/*')
.pipe(ghPages());
});
gulp.task('default', ['jsdoc']);
gulp.task('build', ['jsdoc', 'deploy']);
gulp.task('jsdoc', jsDocTask);
gulp.task('watch', function() {
jsDocTask();
gulp.watch(docsSrcDir, ['jsdoc']);
});
| Add gulp task to deploy jsDocs | Add gulp task to deploy jsDocs
| JavaScript | mit | moneyadviceservice/dough,moneyadviceservice/dough,moneyadviceservice/dough,moneyadviceservice/dough | ---
+++
@@ -1,5 +1,6 @@
var gulp = require('gulp'),
jsdoc = require('gulp-jsdoc'),
+ ghPages = require('gulp-gh-pages'),
docsSrcDir = './assets/js/**/*.js',
docsDestDir = './docs/js',
jsDocTask;
@@ -23,8 +24,17 @@
);
};
+gulp.task('deploy', function() {
+ return gulp.src(docsDestDir + '/**/*')
+ .pipe(ghPages());
+});
+
gulp.task('default', ['jsdoc']);
+
+gulp.task('build', ['jsdoc', 'deploy']);
+
gulp.task('jsdoc', jsDocTask);
+
gulp.task('watch', function() {
jsDocTask();
gulp.watch(docsSrcDir, ['jsdoc']); |
af37455fed835172c2e533a60f2e65f3833058a9 | gulpfile.js | gulpfile.js | var gulp = require("gulp");
var sass = require("gulp-sass");
var postcss = require("gulp-postcss");
var autoprefixer = require("autoprefixer");
var cssnano = require("cssnano");
var uglify = require("gulp-uglify");
var rename = require("gulp-rename");
var browserSync = require("browser-sync");
gulp.task("serve", ["css", "js"], function () {
browserSync.init({
server: "./"
});
gulp.watch("css/main.scss", ["css"]);
gulp.watch("index.html").on("change", browserSync.reload);
gulp.watch("js/main.js", ["js"]);
gulp.watch("js/main.min.js").on("change", browserSync.reload);
});
gulp.task("css", function () {
gulp.src("css/main.scss")
.pipe(sass().on("error", sass.logError))
.pipe(postcss([
autoprefixer(),
cssnano()
]))
.pipe(rename({
suffix: ".min"
}))
.pipe(gulp.dest("css"))
.pipe(browserSync.stream());
});
gulp.task("js", function () {
gulp.src("js/main.js")
.pipe(uglify())
.pipe(rename({
suffix: ".min"
}))
.pipe(gulp.dest("js"));
});
gulp.task("default", ["serve"]); | const gulp = require('gulp');
const sass = require('gulp-sass');
const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const browserSync = require('browser-sync');
gulp.task('serve', ['css', 'js'], () => {
browserSync.init({
server: './'
});
gulp.watch('css/main.scss', ['css']);
gulp.watch('index.html').on('change', browserSync.reload);
gulp.watch('js/main.js', ['js']);
gulp.watch('js/main.min.js').on('change', browserSync.reload);
});
gulp.task('css', () => {
gulp
.src('css/main.scss')
.pipe(sass().on('error', sass.logError))
.pipe(postcss([autoprefixer(), cssnano()]))
.pipe(
rename({
suffix: '.min'
})
)
.pipe(gulp.dest('css'))
.pipe(browserSync.stream());
});
gulp.task('js', () => {
gulp
.src('js/main.js')
.pipe(uglify())
.pipe(
rename({
suffix: '.min'
})
)
.pipe(gulp.dest('js'));
});
gulp.task('default', ['serve']);
| Update Gulp file to use es6 syntax. | Update Gulp file to use es6 syntax. | JavaScript | mit | mohouyizme/minimado,mohouyizme/minimado | ---
+++
@@ -1,43 +1,46 @@
-var gulp = require("gulp");
-var sass = require("gulp-sass");
-var postcss = require("gulp-postcss");
-var autoprefixer = require("autoprefixer");
-var cssnano = require("cssnano");
-var uglify = require("gulp-uglify");
-var rename = require("gulp-rename");
-var browserSync = require("browser-sync");
+const gulp = require('gulp');
+const sass = require('gulp-sass');
+const postcss = require('gulp-postcss');
+const autoprefixer = require('autoprefixer');
+const cssnano = require('cssnano');
+const uglify = require('gulp-uglify');
+const rename = require('gulp-rename');
+const browserSync = require('browser-sync');
-gulp.task("serve", ["css", "js"], function () {
- browserSync.init({
- server: "./"
- });
- gulp.watch("css/main.scss", ["css"]);
- gulp.watch("index.html").on("change", browserSync.reload);
- gulp.watch("js/main.js", ["js"]);
- gulp.watch("js/main.min.js").on("change", browserSync.reload);
+gulp.task('serve', ['css', 'js'], () => {
+ browserSync.init({
+ server: './'
+ });
+ gulp.watch('css/main.scss', ['css']);
+ gulp.watch('index.html').on('change', browserSync.reload);
+ gulp.watch('js/main.js', ['js']);
+ gulp.watch('js/main.min.js').on('change', browserSync.reload);
});
-gulp.task("css", function () {
- gulp.src("css/main.scss")
- .pipe(sass().on("error", sass.logError))
- .pipe(postcss([
- autoprefixer(),
- cssnano()
- ]))
- .pipe(rename({
- suffix: ".min"
- }))
- .pipe(gulp.dest("css"))
- .pipe(browserSync.stream());
+gulp.task('css', () => {
+ gulp
+ .src('css/main.scss')
+ .pipe(sass().on('error', sass.logError))
+ .pipe(postcss([autoprefixer(), cssnano()]))
+ .pipe(
+ rename({
+ suffix: '.min'
+ })
+ )
+ .pipe(gulp.dest('css'))
+ .pipe(browserSync.stream());
});
-gulp.task("js", function () {
- gulp.src("js/main.js")
- .pipe(uglify())
- .pipe(rename({
- suffix: ".min"
- }))
- .pipe(gulp.dest("js"));
+gulp.task('js', () => {
+ gulp
+ .src('js/main.js')
+ .pipe(uglify())
+ .pipe(
+ rename({
+ suffix: '.min'
+ })
+ )
+ .pipe(gulp.dest('js'));
});
-gulp.task("default", ["serve"]);
+gulp.task('default', ['serve']); |
ac04ecd69e559d018f7d9e24d7f6de617aac3a26 | src/apis/Dimensions/index.js | src/apis/Dimensions/index.js | /**
* Copyright (c) 2015-present, Nicolas Gallagher.
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* @flow
*/
import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment'
import invariant from 'fbjs/lib/invariant'
const win = ExecutionEnvironment.canUseDOM ? window : { screen: {} }
const dimensions = {
screen: {
fontScale: 1,
get height() { return win.screen.height },
scale: win.devicePixelRatio || 1,
get width() { return win.screen.width }
},
window: {
fontScale: 1,
get height() { return win.innerHeight },
scale: win.devicePixelRatio || 1,
get width() { return win.innerWidth }
}
}
class Dimensions {
static get(dimension: string): Object {
invariant(dimensions[dimension], 'No dimension set for key ' + dimension)
return dimensions[dimension]
}
}
module.exports = Dimensions
| /**
* Copyright (c) 2015-present, Nicolas Gallagher.
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* @flow
*/
import debounce from 'lodash.debounce'
import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment'
import invariant from 'fbjs/lib/invariant'
const win = ExecutionEnvironment.canUseDOM ? window : { screen: {} }
const dimensions = {}
class Dimensions {
static get(dimension: string): Object {
invariant(dimensions[dimension], 'No dimension set for key ' + dimension)
return dimensions[dimension]
}
static set(): void {
dimensions.window = {
fontScale: 1,
height: win.innerHeight,
scale: win.devicePixelRatio || 1,
width: win.innerWidth
}
dimensions.screen = {
fontScale: 1,
height: win.screen.height,
scale: win.devicePixelRatio || 1,
width: win.screen.width
}
}
}
Dimensions.set();
ExecutionEnvironment.canUseDOM && window.addEventListener('resize', debounce(Dimensions.set, 50))
module.exports = Dimensions
| Update Dimensions when window resizes | Update Dimensions when window resizes
| JavaScript | mit | necolas/react-native-web,necolas/react-native-web,necolas/react-native-web | ---
+++
@@ -6,31 +6,38 @@
* @flow
*/
+import debounce from 'lodash.debounce'
import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment'
import invariant from 'fbjs/lib/invariant'
const win = ExecutionEnvironment.canUseDOM ? window : { screen: {} }
-const dimensions = {
- screen: {
- fontScale: 1,
- get height() { return win.screen.height },
- scale: win.devicePixelRatio || 1,
- get width() { return win.screen.width }
- },
- window: {
- fontScale: 1,
- get height() { return win.innerHeight },
- scale: win.devicePixelRatio || 1,
- get width() { return win.innerWidth }
- }
-}
+const dimensions = {}
class Dimensions {
static get(dimension: string): Object {
invariant(dimensions[dimension], 'No dimension set for key ' + dimension)
return dimensions[dimension]
}
+
+ static set(): void {
+ dimensions.window = {
+ fontScale: 1,
+ height: win.innerHeight,
+ scale: win.devicePixelRatio || 1,
+ width: win.innerWidth
+ }
+
+ dimensions.screen = {
+ fontScale: 1,
+ height: win.screen.height,
+ scale: win.devicePixelRatio || 1,
+ width: win.screen.width
+ }
+ }
}
+Dimensions.set();
+ExecutionEnvironment.canUseDOM && window.addEventListener('resize', debounce(Dimensions.set, 50))
+
module.exports = Dimensions |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.