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 |
|---|---|---|---|---|---|---|---|---|---|---|
5cf609be1c1e1691e82cbce5e25c7a952eb03d1c | index.js | index.js | var elixir = require('laravel-elixir');
var compile = require('./ingredients/commands/CompileCSS');
var _ = require('underscore');
elixir.extend('compass', function (src, output, options) {
options = _.extend({
config_file: './config.rb',
sass: './resources/assets/compass',
css: './public/css'
}, options);
return compile({
compiler: 'Compass',
pluginName: 'compass',
pluginOptions: options,
src: src,
output: output,
search: '**/*.+(sass|scss)'
});
}); | var elixir = require('laravel-elixir');
var compile = require('./ingredients/commands/CompileCSS');
var _ = require('underscore');
elixir.extend('compass', function (src, output, options) {
options = _.extend({
config_file: './config.rb',
sass: './resources/assets/compass',
css: './public/css',
sourcemaps: elixir.config.sourcemaps
}, options);
return compile({
compiler: 'Compass',
pluginName: 'compass',
pluginOptions: options,
src: src,
output: output,
search: '**/*.+(sass|scss)'
});
}); | Use sourcemaps from elixir config | Use sourcemaps from elixir config
| JavaScript | mit | morrislaptop/laravel-elixir-compass | ---
+++
@@ -7,7 +7,8 @@
options = _.extend({
config_file: './config.rb',
sass: './resources/assets/compass',
- css: './public/css'
+ css: './public/css',
+ sourcemaps: elixir.config.sourcemaps
}, options);
return compile({ |
afeb2bd8caf4aefc188cbd4271cddee03dbea97a | light.js | light.js | HueLight = function(bridge, id, params) {
this.bridge = bridge;
this.id = id;
this.params = params;
}
HueLight.prototype = {
updateState: function(key, val) {
let state = {};
state[key] = val;
this.bridge._apiCall("PUT", `/lights/${this.id}/state`, state);
},
setOn: function() {
this.updateState("on", true);
},
setOff: function() {
this.updateState("on", false);
},
setBrightness: function(value) {
if (value < 0 || value > 255 || value !== parseInt(value, 10)) {
throw new Meteor.Error(500, value + " is not a valid brightness value. Should be an integer between 0 and 255.");
}
this.updateState("bri", value);
},
}
| HueLight = function(bridge, id, params) {
this.bridge = bridge;
this.id = id;
this.params = params;
}
HueLight.prototype = {
updateState: function(key, val) {
let state = {};
state[key] = val;
this.bridge._apiCall("PUT", `/lights/${this.id}/state`, state);
},
/**
* Turns on the light
*/
setOn: function() {
this.updateState("on", true);
},
/**
* Turns off the light
*/
setOff: function() {
this.updateState("on", false);
},
/**
* Set the light's brightness
* @param {int} value : the light's brightness from 1 to 254
*/
setBrightness: function(value) {
if (value < 1 || value > 254 || value !== parseInt(value, 10)) {
throw new Meteor.Error(500, value + ` is not a valid brightness value. Should be an integer between 1 and 254.`);
}
this.updateState("bri", value);
},
/**
* Set the light's hue (0: red, 25500: green, 46920: blue)
* @param {int} value : the light's hue from 0 to 65535
*/
setHue: function(value) {
if (value < 0 || value > 65535 || value !== parseInt(value, 10)) {
throw new Meteor.Error(500, value + " is not a valid hue value. Should be an integer between 0 and 65535.");
}
this.updateState("hue", value);
},
/**
* Set the light's saturation
* @param {int} value : the light's saturation from 0 (white) to 254 (colored)
*/
setSaturation: function(value) {
if (value < 0 || value > 254 || value !== parseInt(value, 10)) {
throw new Meteor.Error(500, value + " is not a valid hue value. Should be an integer between 0 and 254.");
}
this.updateState("sat", value);
},
}
| Add setHue and setSaturation methods | Add setHue and setSaturation methods
| JavaScript | mit | iwazaru/meteor-hue | ---
+++
@@ -12,18 +12,50 @@
this.bridge._apiCall("PUT", `/lights/${this.id}/state`, state);
},
+ /**
+ * Turns on the light
+ */
setOn: function() {
this.updateState("on", true);
},
+ /**
+ * Turns off the light
+ */
setOff: function() {
this.updateState("on", false);
},
+ /**
+ * Set the light's brightness
+ * @param {int} value : the light's brightness from 1 to 254
+ */
setBrightness: function(value) {
- if (value < 0 || value > 255 || value !== parseInt(value, 10)) {
- throw new Meteor.Error(500, value + " is not a valid brightness value. Should be an integer between 0 and 255.");
+ if (value < 1 || value > 254 || value !== parseInt(value, 10)) {
+ throw new Meteor.Error(500, value + ` is not a valid brightness value. Should be an integer between 1 and 254.`);
}
this.updateState("bri", value);
},
+
+ /**
+ * Set the light's hue (0: red, 25500: green, 46920: blue)
+ * @param {int} value : the light's hue from 0 to 65535
+ */
+ setHue: function(value) {
+ if (value < 0 || value > 65535 || value !== parseInt(value, 10)) {
+ throw new Meteor.Error(500, value + " is not a valid hue value. Should be an integer between 0 and 65535.");
+ }
+ this.updateState("hue", value);
+ },
+
+ /**
+ * Set the light's saturation
+ * @param {int} value : the light's saturation from 0 (white) to 254 (colored)
+ */
+ setSaturation: function(value) {
+ if (value < 0 || value > 254 || value !== parseInt(value, 10)) {
+ throw new Meteor.Error(500, value + " is not a valid hue value. Should be an integer between 0 and 254.");
+ }
+ this.updateState("sat", value);
+ },
} |
4fe628f4f2bb48905423581081351d3e9a89406e | spec/app.js | spec/app.js | const express = require('express');
const app = express();
const opn = require('opn')
const { execSync } = require('child_process')
// Can't use __dirname while /spec is a symlink
const cwd = execSync('pwd').toString().trim()
app.use(express.static(cwd))
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || 'localhost';
app.listen(PORT, HOST, function(){
console.log("Unpoly specs serving on http://localhost:3000.")
console.log("Press CTRL+C to quit.")
opn('http://localhost:3000')
});
app.get('/', function(req, res){
res.sendFile(cwd + '/spec/menu.html');
});
app.get('/specs', function(req, res){
res.sendFile(cwd + '/spec/runner.html');
});
| const express = require('express');
const app = express();
const opn = require('opn')
const { execSync } = require('child_process')
// Can't use __dirname while /spec is a symlink
const cwd = execSync('pwd').toString().trim()
app.use(express.static(cwd))
const PORT = process.env.PORT || 4000;
const HOST = process.env.HOST || 'localhost';
const URL = `http://${HOST}:${PORT}`
app.listen(PORT, HOST, function(){
console.log(`Unpoly specs serving on ${URL}.`)
console.log("Press CTRL+C to quit.")
opn(URL)
});
app.get('/', function(req, res){
res.sendFile(cwd + '/spec/menu.html');
});
app.get('/specs', function(req, res){
res.sendFile(cwd + '/spec/runner.html');
});
| Test server boots on port 4000 | Test server boots on port 4000
| JavaScript | mit | unpoly/unpoly,unpoly/unpoly,unpoly/unpoly | ---
+++
@@ -8,13 +8,14 @@
app.use(express.static(cwd))
-const PORT = process.env.PORT || 3000;
+const PORT = process.env.PORT || 4000;
const HOST = process.env.HOST || 'localhost';
+const URL = `http://${HOST}:${PORT}`
app.listen(PORT, HOST, function(){
- console.log("Unpoly specs serving on http://localhost:3000.")
+ console.log(`Unpoly specs serving on ${URL}.`)
console.log("Press CTRL+C to quit.")
- opn('http://localhost:3000')
+ opn(URL)
});
app.get('/', function(req, res){ |
7b52da206551aa78798ff20560ad47407a62331b | index.js | index.js | var inquirer = require('inquirer');
inquirer.prompt([
{
name: 'q1',
message: 'Which author details would you like to use with this repository?',
type: 'list',
choices: [
'Jane Doe <jane.doe@example.com>',
'Jane Doe <jdoe@business.com>',
new inquirer.Separator(),
'Add new author...',
'Remove author...'
]
}
]).then(console.log).catch(console.error);
| const
inquirer = require('inquirer');
const
fakeAuthorLs = [
{
email: 'jane.doe@example.com',
name: 'Jane Doe'
},
{
alias: 'Work',
email: 'jdoe@business.com',
name: 'Jane Doe'
}
],
choices = fakeAuthorLs.map(author => {
return {
name: author.alias || `${author.name} <${author.email}>`,
value: {
email: author.email,
name: author.name
}
}
}).concat(
[
new inquirer.Separator(),
'Add new author...',
'Remove author...'
]
);
inquirer.prompt([
{
name: 'q1',
message: 'Which author details would you like to use with this repository?',
type: 'list',
choices
}
]).then(console.log).catch(console.error);
| Move inquirer choices into own const | Move inquirer choices into own const
| JavaScript | mit | dannycjones/git-chauthor | ---
+++
@@ -1,16 +1,40 @@
-var inquirer = require('inquirer');
+const
+ inquirer = require('inquirer');
+
+const
+ fakeAuthorLs = [
+ {
+ email: 'jane.doe@example.com',
+ name: 'Jane Doe'
+ },
+ {
+ alias: 'Work',
+ email: 'jdoe@business.com',
+ name: 'Jane Doe'
+ }
+ ],
+ choices = fakeAuthorLs.map(author => {
+ return {
+ name: author.alias || `${author.name} <${author.email}>`,
+ value: {
+ email: author.email,
+ name: author.name
+ }
+ }
+ }).concat(
+ [
+ new inquirer.Separator(),
+ 'Add new author...',
+ 'Remove author...'
+ ]
+ );
+
inquirer.prompt([
{
name: 'q1',
message: 'Which author details would you like to use with this repository?',
type: 'list',
- choices: [
- 'Jane Doe <jane.doe@example.com>',
- 'Jane Doe <jdoe@business.com>',
- new inquirer.Separator(),
- 'Add new author...',
- 'Remove author...'
- ]
+ choices
}
]).then(console.log).catch(console.error); |
0466df310c5f496873a913cc4cba71de10024490 | js/plot-dots.js | js/plot-dots.js | // Initial dot attributes
function dot_init (selection, scales) {
selection
.style("fill", "rgb(31, 119, 180)")
.attr("class", function(d,i) {
return "dot";
});
// tooltips when hovering points
var tooltip = d3.select(".tooltip");
selection.on("mouseover", function(d, i){
d3.select(this)
.transition().duration(150)
.attr("d", d3.symbol().size(450));
tooltip.style("visibility", "visible")
.html(tooltip_content(d));
});
selection.on("mousemove", function(){
tooltip.style("top", (d3.event.pageY+15)+"px").style("left",(d3.event.pageX+15)+"px");
});
selection.on("mouseout", function(){
d3.select(this)
.transition().duration(150)
.attr("d", d3.symbol().size(100));
tooltip.style("visibility", "hidden");
});
}
// Apply format to dot
function dot_formatting(selection, scales, settings) {
var sel = selection
.attr("transform", function(d) { return translation(d, scales); })
// fill color
.style("opacity", settings.points_opacity)
// symbol and size
.attr("d", d3.symbol().size(settings.points_size));
return sel;
}
| // Initial dot attributes
function dot_init (selection, scales, settings) {
selection
.style("fill", "rgb(31, 119, 180)");
// tooltips when hovering points
var tooltip = d3.select(".tooltip");
selection.on("mouseover", function(d, i){
d3.select(this)
.transition().duration(150)
.attr("d", d3.symbol().size(600));
tooltip.style("visibility", "visible")
.html(tooltip_content(d));
});
selection.on("mousemove", function(){
tooltip.style("top", (d3.event.pageY+15)+"px").style("left",(d3.event.pageX+15)+"px");
});
selection.on("mouseout", function(){
d3.select(this)
.transition().duration(150)
.attr("d", d3.symbol().size(settings.points_size));
tooltip.style("visibility", "hidden");
});
}
// Apply format to dot
function dot_formatting(selection, scales, settings) {
var sel = selection
.attr("transform", function(d) { return translation(d, scales); })
// fill color
.style("opacity", settings.points_opacity)
// symbol and size
.attr("d", d3.symbol().size(settings.points_size));
return sel;
}
| Fix points color and hover size | Fix points color and hover size
| JavaScript | mit | juba/uniquanti,juba/uniquanti | ---
+++
@@ -1,16 +1,13 @@
// Initial dot attributes
-function dot_init (selection, scales) {
+function dot_init (selection, scales, settings) {
selection
- .style("fill", "rgb(31, 119, 180)")
- .attr("class", function(d,i) {
- return "dot";
- });
+ .style("fill", "rgb(31, 119, 180)");
// tooltips when hovering points
var tooltip = d3.select(".tooltip");
selection.on("mouseover", function(d, i){
d3.select(this)
.transition().duration(150)
- .attr("d", d3.symbol().size(450));
+ .attr("d", d3.symbol().size(600));
tooltip.style("visibility", "visible")
.html(tooltip_content(d));
});
@@ -20,7 +17,7 @@
selection.on("mouseout", function(){
d3.select(this)
.transition().duration(150)
- .attr("d", d3.symbol().size(100));
+ .attr("d", d3.symbol().size(settings.points_size));
tooltip.style("visibility", "hidden");
});
} |
98c6022c6fdcd5d52b2d2cb14438f20f69bf62c1 | js/src/index.js | js/src/index.js | function load_ipython_extension() {
var extensionLoaded = false;
function loadScript( host, name ) {
var script = document.createElement( 'script' );
script.src = name
? host + `/juno/${name}.js`
: host;
document.head.appendChild( script );
return script;
}
function loadJuno( host ) {
if ( extensionLoaded ) { return; }
var reqReact = window.requirejs.config({
paths: {
'react': host + '/juno/react',
'react-dom': host + '/juno/react-dom'
}
});
reqReact([ 'react', 'react-dom' ], () => {
reqReact([ host + '/juno/vendor.js'], () => {
reqReact([ host + '/juno/nbextension.js'], () => {});
});
});
}
requirejs( [
"base/js/namespace",
"base/js/events"
], function( Jupyter, Events ) {
// On new kernel session create new comm managers
if ( Jupyter.notebook && Jupyter.notebook.kernel ) {
loadJuno( '//' + window.location.host )
}
Events.on( 'kernel_created.Kernel kernel_created.Session', ( event, data ) => {
handleKernel( data.kernel );
});
});
}
module.exports = {
load_ipython_extension: load_ipython_extension
};
| function load_ipython_extension() {
var extensionLoaded = false;
function loadScript( host, name ) {
var script = document.createElement( 'script' );
script.src = name
? host + `/juno/${name}.js`
: host;
document.head.appendChild( script );
return script;
}
function loadJuno( host ) {
if ( extensionLoaded ) { return; }
var reqReact = window.requirejs.config({
paths: {
'react': host + '/juno/react',
'react-dom': host + '/juno/react-dom'
}
});
reqReact([ 'react', 'react-dom' ], () => {
reqReact([ host + '/juno/vendor.js'], () => {
reqReact([ host + '/juno/nbextension.js'], () => {});
});
});
}
requirejs( [
"base/js/namespace",
"base/js/events"
], function( Jupyter, Events ) {
// On new kernel session create new comm managers
if ( Jupyter.notebook && Jupyter.notebook.kernel ) {
loadJuno( '//' + window.location.host )
}
Events.on( 'kernel_created.Kernel kernel_created.Session', ( event, data ) => {
loadJuno( '//' + window.location.host );
});
});
}
module.exports = {
load_ipython_extension: load_ipython_extension
};
| FIX calling loadJuno in place of handleKernel on kernel, session creation | FIX calling loadJuno in place of handleKernel on kernel, session creation
| JavaScript | mit | DigitalGlobe/juno-magic,timbr-io/juno-magic,DigitalGlobe/juno-magic,timbr-io/juno-magic | ---
+++
@@ -37,7 +37,7 @@
loadJuno( '//' + window.location.host )
}
Events.on( 'kernel_created.Kernel kernel_created.Session', ( event, data ) => {
- handleKernel( data.kernel );
+ loadJuno( '//' + window.location.host );
});
});
} |
90eb9249ed074bf6c0b5fdd3fa8583ff8092a73d | .storybook/preview.js | .storybook/preview.js | import './global.css';
import './fonts.css';
| import { addParameters } from '@storybook/react';
import { INITIAL_VIEWPORTS } from '@storybook/addon-viewport';
import './global.css';
import './fonts.css';
addParameters({
viewport: {
viewports: INITIAL_VIEWPORTS,
},
});
| Use more granular list of devices in viewports addon | [WEB-589] Storybook: Use more granular list of devices in viewports addon
| JavaScript | bsd-2-clause | tidepool-org/blip,tidepool-org/blip,tidepool-org/blip | ---
+++
@@ -1,2 +1,11 @@
+import { addParameters } from '@storybook/react';
+import { INITIAL_VIEWPORTS } from '@storybook/addon-viewport';
+
import './global.css';
import './fonts.css';
+
+addParameters({
+ viewport: {
+ viewports: INITIAL_VIEWPORTS,
+ },
+}); |
7d9d87b9b275c0dc4b59855481999a84db55fd64 | js/view/view.js | js/view/view.js | function create_VIM_VIEW(environment, messager, context) {
var executor = environment.executor;
// ignores ids that listenTo returns (no need to remove listening ever)
messager.listenTo('interpreter_initialized', receiveMessage);
messager.listenTo('cursor_changed', receiveMessage);
messager.listenTo('interpreter_interpreted', receiveMessage);
messager.listenTo('updated_mode', receiveMessage);
messager.listenTo('updated_searchtext', updatedSearchText);
messager.listenTo('searchbar_visible', searchbarVisible);
function updatedSearchText(text) { $('.searchText', context).text(text); }
function searchbarVisible(isVisible) {
if(isVisible)
$('.searchbar', context).show();
else
$('.searchbar', context).hide();
}
function update() {
if(environment.isCommandMode()) {
$('.statustext', context).text("mode: COMMAND");
$('.insert-mode', context).hide();
$('.command-mode', context).show();
} else {
$('.insert-mode', context).show();
$('.command-mode', context).hide();
$('.statustext', context).text("mode: INSERT");
}
var row = 1 + executor.currentRowIndex();
var col = 1 + executor.currentColumnIndex();
$('.cursorlocation').text(row + ", " + col);
}
function receiveMessage(message) {
// ignore message
update();
}
return {
'update': update
}
}
| function create_VIM_VIEW(environment, messager, context) {
var executor = environment.executor;
// ignores ids that listenTo returns (no need to remove listening ever)
messager.listenTo('interpreter_initialized', receiveMessage);
messager.listenTo('cursor_changed', receiveMessage);
messager.listenTo('interpreter_interpreted', receiveMessage);
messager.listenTo('updated_mode', receiveMessage);
messager.listenTo('updated_searchtext', updatedSearchText);
messager.listenTo('searchbar_visible', searchbarVisible);
function updatedSearchText(text) { $('.searchText', context).text(text); }
function searchbarVisible(isVisible) {
if(isVisible)
$('.searchbar', context).show();
else
$('.searchbar', context).hide();
}
function update() {
if(environment.isCommandMode()) {
$('.statustext', context).text("mode: NORMAL");
$('.insert-mode', context).hide();
$('.command-mode', context).show();
} else {
$('.insert-mode', context).show();
$('.command-mode', context).hide();
$('.statustext', context).text("mode: INSERT");
}
var row = 1 + executor.currentRowIndex();
var col = 1 + executor.currentColumnIndex();
$('.cursorlocation').text(row + ", " + col);
}
function receiveMessage(message) {
// ignore message
update();
}
return {
'update': update
}
}
| Fix mode naming in status bar | Fix mode naming in status bar
Thanks S.N. for spotting this.
| JavaScript | mit | egaga/openvim,egaga/openvim,egaga/openvim | ---
+++
@@ -20,7 +20,7 @@
function update() {
if(environment.isCommandMode()) {
- $('.statustext', context).text("mode: COMMAND");
+ $('.statustext', context).text("mode: NORMAL");
$('.insert-mode', context).hide();
$('.command-mode', context).show();
} else { |
22d502d795be79e6231eafdc014d645d4548133a | src/adhocracy_frontend/adhocracy_frontend/tests/acceptance/UserPageSpec.js | src/adhocracy_frontend/adhocracy_frontend/tests/acceptance/UserPageSpec.js | "use strict";
var shared = require("./shared.js");
var UserPages = require("./UserPages.js");
var fs = require("fs");
var exec = require("sync-exec");
var EC = protractor.ExpectedConditions;
var _ = require("lodash");
describe("user page", function() {
var currentDate = Date.now().toString();
var subject = "title" + currentDate;
var content = "content" + currentDate;
it("is possible to send a message", function(done) {
shared.loginOtherParticipant();
var annotatorPage = new UserPages.UserPage().get("0000005");
annotatorPage.sendMessage(subject, content);
// expect the message widget to disappear
var dropdown = element(by.css(".dropdown"));
browser.wait(EC.elementToBeClickable(dropdown), 5000);
expect(EC.elementToBeClickable(dropdown)).toBeTruthy();
done();
});
it("backend sends message as email", function(done) {
var newMails = fs.readdirSync(browser.params.mail.queue_path + "/new");
var lastMail = newMails.length - 1
var mailpath = browser.params.mail.queue_path + "/new/" + newMails[lastMail];
shared.parseEmail(mailpath, function(mail) {
expect(mail.text).toContain(content);
expect(mail.subject).toContain(subject);
expect(mail.from[0].address).toContain("noreply");
expect(mail.to[0].address).toContain("participant");
done();
});
});
});
| "use strict";
var shared = require("./shared.js");
var UserPages = require("./UserPages.js");
var fs = require("fs");
var exec = require("sync-exec");
var EC = protractor.ExpectedConditions;
var _ = require("lodash");
describe("user page", function() {
var currentDate = Date.now().toString();
var subject = "title" + currentDate;
var content = "content" + currentDate;
it("is possible to send a message", function(done) {
shared.loginOtherParticipant();
var annotatorPage = new UserPages.UserPage().get("0000000");
annotatorPage.sendMessage(subject, content);
// expect the message widget to disappear
var dropdown = element(by.css(".dropdown"));
browser.wait(EC.elementToBeClickable(dropdown), 5000);
expect(EC.elementToBeClickable(dropdown)).toBeTruthy();
done();
});
it("backend sends message as email", function(done) {
var newMails = fs.readdirSync(browser.params.mail.queue_path + "/new");
var lastMail = newMails.length - 1
var mailpath = browser.params.mail.queue_path + "/new/" + newMails[lastMail];
shared.parseEmail(mailpath, function(mail) {
expect(mail.text).toContain(content);
expect(mail.subject).toContain(subject);
expect(mail.from[0].address).toContain("noreply");
expect(mail.to[0].address).toContain("sysadmin");
done();
});
});
});
| Send message to user with fixed id | Send message to user with fixed id
| JavaScript | agpl-3.0 | liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator | ---
+++
@@ -15,7 +15,7 @@
it("is possible to send a message", function(done) {
shared.loginOtherParticipant();
- var annotatorPage = new UserPages.UserPage().get("0000005");
+ var annotatorPage = new UserPages.UserPage().get("0000000");
annotatorPage.sendMessage(subject, content);
@@ -34,7 +34,7 @@
expect(mail.text).toContain(content);
expect(mail.subject).toContain(subject);
expect(mail.from[0].address).toContain("noreply");
- expect(mail.to[0].address).toContain("participant");
+ expect(mail.to[0].address).toContain("sysadmin");
done();
});
}); |
34431d548557a520b91bdaa19e17e4343eb90e26 | index.js | index.js | 'use strict';
var React = require('react');
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var Range = React.createClass({
displayName: 'Range',
propTypes: {
onChange: React.PropTypes.func,
onMouseMove: React.PropTypes.func
},
getDefaultProps: function() {
return {
type: 'range',
onMouseMove: function(){},
onKeyDown: function(){},
onChange: function(){}
};
},
onRangeChange: function(e) {
this.props.onMouseMove(e);
if (e.buttons !== 1) return;
if (this.props.onChange) this.props.onChange(e);
},
onRangeKeyDown: function(e) {
this.props.onKeyDown(e);
this.props.onChange(e);
},
componentWillReceiveProps: function(props) {
React.findDOMNode(this).value = props.value;
},
render: function() {
var props = _extends({}, this.props, {
defaultValue: this.props.value,
onMouseMove: this.onRangeChange,
onKeyDown: this.onRangeKeyDown,
onChange: function() {}
});
delete props.value;
return React.createElement(
'input',
props
);
}
});
module.exports = Range;
| 'use strict';
var React = require('react');
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var Range = React.createClass({
displayName: 'Range',
propTypes: {
onChange: React.PropTypes.func,
onMouseMove: React.PropTypes.func
},
getDefaultProps: function() {
return {
type: 'range',
onMouseMove: function(){},
onKeyDown: function(){},
onChange: function(){}
};
},
onRangeChange: function(e) {
this.props.onMouseMove(e);
if (e.buttons !== 1) return;
this.props.onChange(e);
},
onRangeKeyDown: function(e) {
this.props.onKeyDown(e);
this.props.onChange(e);
},
componentWillReceiveProps: function(props) {
React.findDOMNode(this).value = props.value;
},
render: function() {
var props = _extends({}, this.props, {
defaultValue: this.props.value,
onMouseMove: this.onRangeChange,
onKeyDown: this.onRangeKeyDown,
onChange: function() {}
});
delete props.value;
return React.createElement(
'input',
props
);
}
});
module.exports = Range;
| Remove onChange check. this is taken care of in getDefaultProps. | Remove onChange check. this is taken care of in getDefaultProps. | JavaScript | isc | mapbox/react-range | ---
+++
@@ -20,7 +20,7 @@
onRangeChange: function(e) {
this.props.onMouseMove(e);
if (e.buttons !== 1) return;
- if (this.props.onChange) this.props.onChange(e);
+ this.props.onChange(e);
},
onRangeKeyDown: function(e) {
this.props.onKeyDown(e); |
ec3582492bee170a3569555a02a1ae5506fd47bc | plugins/strings.js | plugins/strings.js | 'use strict'
exports.init = (bot, prefs) => {
bot.register.command('echo', {
format: true,
fn: message => {
var response = message.text.replace('/echo', "");
if (!response)
return "Supply some text to echo in markdown. (For example: <code>/echo *bold text*</code>.)";
bot.api.sendMessage(message.chat.id, response, {
parseMode: 'markdown',
reply: (message.reply_to_message || message).message_id
}).catch(e =>
e.description.includes('entity')
? message.tag(response)
: message.error(e.error_code, e.description)
);
}
});
}
| 'use strict'
const {unformat} = require('./unformat')
exports.init = (bot, prefs) => {
bot.register.command('echo', {
format: true,
fn: message => {
if (!message.args) {
return "Supply some text to echo in markdown. (For example: <code>/echo *bold text*</code>.)";
}
const cut = message.entities[0].length + 1;
// we run unformat with the command intact, to not mess up entity offsets,
// only after that we get rid of command
let response = unformat(message).slice(cut);
bot.api.sendMessage(message.chat.id, response, {
parseMode: 'markdown',
reply: (message.reply_to_message || message).message_id
}).catch(e =>
e.description.includes('entity')
? message.tag(response)
: message.error(e.error_code, e.description)
);
}
});
}
| Add support for formated text to /echo | Add support for formated text to /echo
Runs unformat aka tomd before echoing to replace formatting
with markdown producing that formatting,
which allows the bot to reproduce that formatting.
| JavaScript | bsd-3-clause | lkd70/the-engine | ---
+++
@@ -1,4 +1,6 @@
'use strict'
+
+const {unformat} = require('./unformat')
exports.init = (bot, prefs) => {
@@ -7,10 +9,15 @@
format: true,
fn: message => {
- var response = message.text.replace('/echo', "");
+ if (!message.args) {
+ return "Supply some text to echo in markdown. (For example: <code>/echo *bold text*</code>.)";
+ }
- if (!response)
- return "Supply some text to echo in markdown. (For example: <code>/echo *bold text*</code>.)";
+ const cut = message.entities[0].length + 1;
+
+ // we run unformat with the command intact, to not mess up entity offsets,
+ // only after that we get rid of command
+ let response = unformat(message).slice(cut);
bot.api.sendMessage(message.chat.id, response, {
parseMode: 'markdown', |
70bc487276e3f848e17cceddc50d76708720f43b | check/javascript.standard.check.js | check/javascript.standard.check.js | 'use strict'
const path = require('path')
const {spawnSync} = require('child_process')
const {
env: {
STANDARDJS_EXECUTABLE,
STANDARDJS_ARGV,
SKIP_CODE_STYLE_CHECKING
}
} = require('process')
const wdir = path.resolve(__dirname, '..')
test('JavaScript Code Style: StandardJS', () => {
if (SKIP_CODE_STYLE_CHECKING === 'true') return
const argv = STANDARDJS_ARGV
? JSON.parse(STANDARDJS_ARGV)
: []
expect(argv).toBeInstanceOf(Array)
const {stdout, stderr, status} = spawnSync(STANDARDJS_EXECUTABLE || 'standard', argv, {cwd: wdir})
if (status) {
if (stdout === null) console.warn('standard.stdout is null')
if (stderr === null) console.warn('standard.stderr is null')
throw new Error(stderr + '\n' + stdout)
}
})
| 'use strict'
const path = require('path')
const {spawnSync} = require('child_process')
const {
env: {
STANDARDJS_EXECUTABLE,
STANDARDJS_ARGV,
SKIP_CODE_STYLE_CHECKING
}
} = require('process')
const wdir = path.resolve(__dirname, '..')
test('JavaScript Code Style: StandardJS', () => {
if (SKIP_CODE_STYLE_CHECKING === 'true') return
const argv = STANDARDJS_ARGV
? JSON.parse(STANDARDJS_ARGV)
: []
expect(argv).toBeInstanceOf(Array)
const {stdout, stderr, status} = spawnSync(STANDARDJS_EXECUTABLE || 'standard', argv, {cwd: wdir})
if (stdout === null) console.warn('standard.stdout is null')
if (stderr === null) console.warn('standard.stderr is null')
if (status) {
throw new Error(stderr + '\n' + stdout)
}
})
| Move stdout/stderr null warning out | Move stdout/stderr null warning out
| JavaScript | mit | KSXGitHub/react-hello-world,KSXGitHub/react-hello-world,KSXGitHub/react-hello-world | ---
+++
@@ -22,9 +22,10 @@
const {stdout, stderr, status} = spawnSync(STANDARDJS_EXECUTABLE || 'standard', argv, {cwd: wdir})
+ if (stdout === null) console.warn('standard.stdout is null')
+ if (stderr === null) console.warn('standard.stderr is null')
+
if (status) {
- if (stdout === null) console.warn('standard.stdout is null')
- if (stderr === null) console.warn('standard.stderr is null')
throw new Error(stderr + '\n' + stdout)
}
}) |
1acb3efc8dca76641449e79d6741204e730c77b5 | examples/workflow.js | examples/workflow.js |
var async = require('async');
var timetree = require('../');
var util = require('util');
var timer = timetree('example');
return async.waterfall(
[
function(callback) {
var subTimer = timer.split('task1');
return setTimeout(function() {
subTimer.end();
return callback();
}, 40);
},
function(callback) {
var subTimer = timer.split('task2');
return setTimeout(function() {
subTimer.end();
return callback();
}, 40);
},
function(callback) {
var subTimer = timer.split('task3');
return async.each([1, 2, 3],
function(item, callback) {
var itemTimer = subTimer.split('item' + item);
setTimeout(function() {
itemTimer.end();
return callback();
}, 10);
},
function() {
subTimer.end();
return callback();
}
);
}
],
function() {
timer.end();
console.log(util.inspect(timer.getResult(), false, 4));
}
); |
var async = require('async');
var timetree = require('../');
var util = require('util');
function somethingSynchronous() {
var i = 100000, numbers = [];
while (i--) {
numbers.push(i);
}
return numbers.reduce(function(a,b) { return a * b; })
}
function databaseLookup(id, callback) {
setTimeout(function() {
callback(null, {
id: id,
data: 'Some Data about ' + id
});
}, 30 + Math.random() * 50)
}
var timer = timetree('example');
return async.waterfall(
[
function(callback) {
var subTimer = timer.split('task1');
return setTimeout(subTimer.done(callback), 40);
},
function(callback) {
var subTimer = timer.split('task2');
somethingSynchronous();
subTimer.end();
return callback();
},
function(callback) {
var subTimer = timer.split('task3');
return async.map(
[1, 2, 3],
function(item, next) {
var itemTimer = subTimer.split('item' + item);
databaseLookup(item, itemTimer.done(next));
},
function(err, results) {
subTimer.end();
var data = results.map(function(a) { return a.data; });
return callback(err, data);
}
);
}
],
function(err, data) {
timer.end();
console.log(util.inspect(timer.getResult(), false, 4));
}
);
| Expand example to use done() | Expand example to use done()
| JavaScript | mit | skybet/time-tree | ---
+++
@@ -2,6 +2,22 @@
var async = require('async');
var timetree = require('../');
var util = require('util');
+
+function somethingSynchronous() {
+ var i = 100000, numbers = [];
+ while (i--) {
+ numbers.push(i);
+ }
+ return numbers.reduce(function(a,b) { return a * b; })
+}
+function databaseLookup(id, callback) {
+ setTimeout(function() {
+ callback(null, {
+ id: id,
+ data: 'Some Data about ' + id
+ });
+ }, 30 + Math.random() * 50)
+}
var timer = timetree('example');
@@ -9,36 +25,31 @@
[
function(callback) {
var subTimer = timer.split('task1');
- return setTimeout(function() {
- subTimer.end();
- return callback();
- }, 40);
+ return setTimeout(subTimer.done(callback), 40);
},
function(callback) {
var subTimer = timer.split('task2');
- return setTimeout(function() {
- subTimer.end();
- return callback();
- }, 40);
+ somethingSynchronous();
+ subTimer.end();
+ return callback();
},
function(callback) {
var subTimer = timer.split('task3');
- return async.each([1, 2, 3],
- function(item, callback) {
+ return async.map(
+ [1, 2, 3],
+ function(item, next) {
var itemTimer = subTimer.split('item' + item);
- setTimeout(function() {
- itemTimer.end();
- return callback();
- }, 10);
+ databaseLookup(item, itemTimer.done(next));
},
- function() {
+ function(err, results) {
subTimer.end();
- return callback();
+ var data = results.map(function(a) { return a.data; });
+ return callback(err, data);
}
);
}
],
- function() {
+ function(err, data) {
timer.end();
console.log(util.inspect(timer.getResult(), false, 4));
} |
16bff549746a78303d3b74206d81c2b5b6fc8a73 | index.js | index.js | const chalk = require('chalk')
const format = require('./lib/format')
const game = require('./lib/game')
const input = require('./lib/input')
const log = console.log
const output = require('./lib/output')
const validation = require('./lib/validation')
try {
const cards = input[2]
const formattedCards = format(cards)
validation.validateCards(cards)
log(
chalk.green(
'The hand of',
output(formattedCards),
'is',
game.identifyHand(formattedCards)
)
)
} catch (err) {
log(
chalk.red(
err.message
)
)
}
| const chalk = require('chalk')
const format = require('./lib/format')
const game = require('./lib/game')
const input = require('./lib/input')
const log = console.log
const output = require('./lib/output')
const validation = require('./lib/validation')
try {
const cards = input[2]
validation.validateCards(cards)
const formattedCards = format(cards)
log(
chalk.green(
'The hand of',
output(formattedCards),
'is',
game.identifyHand(formattedCards)
)
)
} catch (err) {
log(
chalk.red(
err.message
)
)
}
| Change location of value assignment | Change location of value assignment
| JavaScript | mit | notmessenger/poker-analysis | ---
+++
@@ -8,9 +8,10 @@
try {
const cards = input[2]
- const formattedCards = format(cards)
validation.validateCards(cards)
+
+ const formattedCards = format(cards)
log(
chalk.green( |
7030b915522e63dcbd5f3863ab29c9c18c6bd522 | src/utils/dateTimeHelper.js | src/utils/dateTimeHelper.js | /* eslint-disable radix */
// eslint-disable-next-line import/prefer-default-export
export const getTimeStringMinutes = (timeStr) => {
const parts = timeStr.split(':');
const hours = parseInt(parts[0]);
const minutes = parseInt(parts[1]);
const totalMin = hours * 60 + minutes;
return totalMin;
};
export const getTimeStringFromMinutes = (totalMinutes) => {
if (totalMinutes > 24 * 60) totalMinutes -= 24 * 60;
const hours = Math.floor(totalMinutes / 60);
const minutes = totalMinutes - hours * 60;
return `${hours < 10 ? `0${hours}` : hours}:${minutes < 10 ? `0${minutes}` : minutes}`;
};
| /* eslint-disable radix */
// eslint-disable-next-line import/prefer-default-export
export const getTimeStringMinutes = (timeStr) => {
const parts = timeStr.split(':');
const hours = parseInt(parts[0]);
const minutes = parseInt(parts[1]);
const totalMin = hours * 60 + minutes;
return totalMin;
};
export const getTimeStringFromMinutes = (totalMinutes) => {
if (totalMinutes > 24 * 60) totalMinutes -= 24 * 60;
let hours = Math.floor(totalMinutes / 60);
const minutes = totalMinutes - hours * 60;
if (hours === 24) hours = 0;
return `${hours < 10 ? `0${hours}` : hours}:${minutes < 10 ? `0${minutes}` : minutes}`;
};
| Replace "24" by "0" in timestrings | Replace "24" by "0" in timestrings
| JavaScript | mit | TobitSoftware/chayns-components,TobitSoftware/chayns-components,TobitSoftware/chayns-components | ---
+++
@@ -13,8 +13,10 @@
export const getTimeStringFromMinutes = (totalMinutes) => {
if (totalMinutes > 24 * 60) totalMinutes -= 24 * 60;
- const hours = Math.floor(totalMinutes / 60);
+ let hours = Math.floor(totalMinutes / 60);
const minutes = totalMinutes - hours * 60;
+
+ if (hours === 24) hours = 0;
return `${hours < 10 ? `0${hours}` : hours}:${minutes < 10 ? `0${minutes}` : minutes}`;
}; |
2e0cd847e13278e0565561882233dbe9255b2868 | addon/initialize.js | addon/initialize.js | import Ember from 'ember';
import ValidatorsMessages from 'ember-cp-validations/validators/messages';
const { Logger:logger } = Ember;
export default function() {
ValidatorsMessages.reopen({
intl: Ember.inject.service(),
prefix: 'errors',
getDescriptionFor(attribute, context = {}) {
let key = `${this.get('prefix')}.description`;
let intl = this.get('intl');
if (intl && intl.exists(key)) {
return intl.formatMessage(intl.findTranslationByKey(key), context);
}
return this._super(...arguments);
},
getMessageFor(type, context = {}) {
let key = `${this.get('prefix')}.${type}`;
let intl = this.get('intl');
if (intl && intl.exists(key)) {
return this.formatMessage(intl.formatMessage(intl.findTranslationByKey(key), context));
}
logger.warn(`[ember-intl-cp-validations] Missing translation for validation key: ${key}\nhttp://offirgolan.github.io/ember-cp-validations/docs/messages/index.html`);
return this._super(...arguments);
}
});
}
| import Ember from 'ember';
import ValidatorsMessages from 'ember-cp-validations/validators/messages';
const { Logger:logger } = Ember;
export default function() {
ValidatorsMessages.reopen({
intl: Ember.inject.service(),
prefix: 'errors',
getDescriptionFor(attribute, context = {}) {
let key = `${this.get('prefix')}.description`;
let intl = this.get('intl');
if (intl && intl.exists(key)) {
return intl.t(key, context);
}
return this._super(...arguments);
},
getMessageFor(type, context = {}) {
let key = `${this.get('prefix')}.${type}`;
let intl = this.get('intl');
if (intl && intl.exists(key)) {
return this.formatMessage(intl.t(key, context));
}
logger.warn(`[ember-intl-cp-validations] Missing translation for validation key: ${key}\nhttp://offirgolan.github.io/ember-cp-validations/docs/messages/index.html`);
return this._super(...arguments);
}
});
}
| Replace usage of `formatMessage(findTranslationByKey` with `t` | Replace usage of `formatMessage(findTranslationByKey` with `t`
| JavaScript | mit | ember-intl/ember-intl-cp-validations,jasonmit/ember-intl-cp-validations,ember-intl/ember-intl-cp-validations,jasonmit/ember-intl-cp-validations | ---
+++
@@ -13,7 +13,7 @@
let intl = this.get('intl');
if (intl && intl.exists(key)) {
- return intl.formatMessage(intl.findTranslationByKey(key), context);
+ return intl.t(key, context);
}
return this._super(...arguments);
@@ -24,7 +24,7 @@
let intl = this.get('intl');
if (intl && intl.exists(key)) {
- return this.formatMessage(intl.formatMessage(intl.findTranslationByKey(key), context));
+ return this.formatMessage(intl.t(key, context));
}
logger.warn(`[ember-intl-cp-validations] Missing translation for validation key: ${key}\nhttp://offirgolan.github.io/ember-cp-validations/docs/messages/index.html`); |
429765336837523743824a11c15d2697b650a987 | index.js | index.js | var Core = require('./libs/core');
var Members = require('./libs/members');
var Topics = require('./libs/topics');
var Posts = require('./libs/posts');
module.exports = Ipboard;
function Ipboard(apiUrl, apiKey) {
if (!apiUrl || !apiKey) throw new error('one or few paramaters are missing');
this.options = {};
this.options.apiUrl = apiUrl;
this.options.apiKey = new Buffer(apiKey).toString('base64');
this.core = new Core(this.options);
this.members = new Members(this.options);
this.topics = new Topics(this.options);
this.posts = new Posts(this.options);
}
| var Core = require('./libs/core');
var Members = require('./libs/members');
var Topics = require('./libs/topics');
var Posts = require('./libs/posts');
module.exports = Ipboard;
function Ipboard(apiUrl, apiKey) {
if (!apiUrl || !apiKey) throw new error('one or few paramaters are missing');
this.options = {};
this.options.apiUrl = apiUrl;
this.options.apiKey = new Buffer(apiKey).toString('base64');
this.native = require('./libs/utils');
this.core = new Core(this.options);
this.members = new Members(this.options);
this.topics = new Topics(this.options);
this.posts = new Posts(this.options);
}
| Add access to native methods | Add access to native methods
| JavaScript | mit | Raesta/ipboard-api | ---
+++
@@ -12,6 +12,7 @@
this.options.apiUrl = apiUrl;
this.options.apiKey = new Buffer(apiKey).toString('base64');
+ this.native = require('./libs/utils');
this.core = new Core(this.options);
this.members = new Members(this.options);
this.topics = new Topics(this.options); |
328e7087162d18ad17b8be080cff5651ecf38dfc | index.js | index.js | var denodeify = require('es6-denodeify')(Promise)
var tough = require('tough-cookie')
module.exports = function fetchCookieDecorator (fetch, jar) {
fetch = fetch || window.fetch
jar = jar || new tough.CookieJar()
var getCookieString = denodeify(jar.getCookieString.bind(jar))
var setCookie = denodeify(jar.setCookie.bind(jar))
return function fetchCookie (url, opts) {
opts = opts || {}
return getCookieString(url)
.then(function (cookie) {
return fetch(url, Object.assign(opts, {
headers: Object.assign(opts.headers || {}, { cookie: cookie })
}))
})
.then(function (res) {
var cookies = res.headers.getAll('set-cookie')
if (!cookies.length) {
return res
}
return Promise.all(cookies.map(function (cookie) {
return setCookie(cookie, url)
})).then(function () {
return res
})
})
}
}
| var denodeify = require('es6-denodeify')(Promise)
var tough = require('tough-cookie')
module.exports = function fetchCookieDecorator (fetch, jar) {
fetch = fetch || window.fetch
jar = jar || new tough.CookieJar()
var getCookieString = denodeify(jar.getCookieString.bind(jar))
var setCookie = denodeify(jar.setCookie.bind(jar))
return function fetchCookie (url, opts) {
opts = opts || {}
return getCookieString(url)
.then(function (cookie) {
return fetch(url, Object.assign(opts, {
headers: Object.assign(opts.headers || {}, { cookie: cookie })
}))
})
.then(function (res) {
var cookies = res.headers.getAll('set-cookie')
if (!cookies.length) {
return res
}
return Promise.all(cookies.map(function (cookie) {
return setCookie(cookie, res.url)
})).then(function () {
return res
})
})
}
}
| Use final URL (i.e. URL after redirects) when storing cookies. | Use final URL (i.e. URL after redirects) when storing cookies. | JavaScript | unlicense | valeriangalliat/fetch-cookie,valeriangalliat/fetch-cookie | ---
+++
@@ -25,7 +25,7 @@
}
return Promise.all(cookies.map(function (cookie) {
- return setCookie(cookie, url)
+ return setCookie(cookie, res.url)
})).then(function () {
return res
}) |
5036e91352cd194ca8f6fd50f2b659a4eb49a0fc | index.js | index.js | "use strict"
const express = require('express');
const HTTPStatus = require('http-status-codes');
var scraper = require('./app/routes/scraper');
const app = express();
// This middleware will be executed for every request to the app
// The api produces application/json only
app.use(function (req, res, next) {
res.header('Content-Type','application/json');
next();
});
app.use('/', scraper);
// Final catch any route middleware used to raise 404
app.get('*', (req, res, next) => {
const err = new Error();
err.statusCode = HTTPStatus.NOT_FOUND;
next(err);
});
// Error response handler
app.use((err, req, res, next) => {
res.status(err.statusCode);
res.send(err.message || HTTPStatus.getStatusText(err.statusCode));
});
app.listen(3000, function () {
console.log('Junkan server is running on port 3000!');
});
module.exports = app;
| "use strict"
const express = require('express');
const HTTPStatus = require('http-status-codes');
var scraper = require('./app/routes/scraper');
const app = express();
// This middleware will be executed for every request to the app
// The api produces application/json only
app.use(function (req, res, next) {
res.header('Content-Type','application/json');
res.header('Content-Language', 'en');
next();
});
app.use('/', scraper);
// Final catch any route middleware used to raise 404
app.get('*', (req, res, next) => {
const err = new Error();
err.statusCode = HTTPStatus.NOT_FOUND;
next(err);
});
// Error response handler
app.use((err, req, res, next) => {
res.status(err.statusCode);
res.send(err.message || HTTPStatus.getStatusText(err.statusCode));
});
app.listen(3000, function () {
console.log('Junkan server is running on port 3000!');
});
module.exports = app;
| Add Content-Language header, always 'en' | feat: Add Content-Language header, always 'en'
| JavaScript | mit | C3-TKO/junkan-server | ---
+++
@@ -11,6 +11,7 @@
// The api produces application/json only
app.use(function (req, res, next) {
res.header('Content-Type','application/json');
+ res.header('Content-Language', 'en');
next();
});
|
1f35f69760ef27b4aea1101daa39fefbfa70a2f8 | index.js | index.js | // Requires
var Q = require('q');
var _ = require('underscore');
var qClass = require('qpatch').qClass;
// Etcd client
var Etcd = qClass(require('node-etcd'), ['watcher']);
// Since etcd create the dir keys automatically
// transform the tree of keys
// to contain only a flat array of leaves
function cleanDump(obj) {
// Is a leaf
if(!_.has(obj, 'kvs')) {
// We don't want the modifiedIndex attr in our dumps/restores
return _.pick(obj, 'key', 'value');
}
return _.flatten(_.map(obj.kvs, cleanDump));
}
function Dumper(etcd) {
// ETCD client
this.store = new Etcd();
_.bindAll(this);
}
// Get a JS object of the DB
Dumper.prototype.dump = function() {
return this.store.get('', {
recursive: true
})
.then(cleanDump);
};
// Restore a list of keys
Dumper.prototype.restore = function(entries) {
var self = this;
return Q.all(_.map(entries, function(entry) {
return this.store.set(entry.key, entry.value);
}));
};
// Restore the database from input data
function createDumper() {
return new Dumper();
}
// Exports
module.exports = createDumper;
| // Requires
var Q = require('q');
var _ = require('underscore');
var qClass = require('qpatch').qClass;
// Etcd client
var Etcd = qClass(require('node-etcd'), ['watcher']);
// Since etcd create the dir keys automatically
// transform the tree of keys
// to contain only a flat array of leaves
function cleanDump(obj) {
// Is a leaf
if(!_.has(obj, 'kvs')) {
// We don't want the modifiedIndex attr in our dumps/restores
return _.pick(obj, 'key', 'value');
}
return _.flatten(_.map(obj.kvs, cleanDump));
}
function Dumper(etcd) {
// ETCD client
this.store = new Etcd();
_.bindAll(this);
}
// Get a JS object of the DB
Dumper.prototype.dump = function() {
return this.store.get('', {
recursive: true
})
.then(cleanDump);
};
// Restore a list of keys
Dumper.prototype.restore = function(entries) {
var self = this;
return Q.all(_.map(entries, function(entry) {
return self.store.set(entry.key, entry.value);
}));
};
// Restore the database from input data
function createDumper() {
return new Dumper();
}
// Exports
module.exports = createDumper;
| Fix typo "this" => "self" | Fix typo "this" => "self"
| JavaScript | apache-2.0 | AaronO/etcd-dump | ---
+++
@@ -41,7 +41,7 @@
var self = this;
return Q.all(_.map(entries, function(entry) {
- return this.store.set(entry.key, entry.value);
+ return self.store.set(entry.key, entry.value);
}));
};
|
e2776808661246c2ad1848b87477a06d0dbd3756 | src/io/DataRedirectRequestType.js | src/io/DataRedirectRequestType.js | var ByteBuffer = require('bytebuffer');
var ProtoBuf = require('protobufjs');
var path = require('path');
var ChunkData =
ProtoBuf
.loadProtoFile(path.join(__dirname, 'ChunkData.proto'))
.build('ChunkData');
var DataRedirectRequestType = {
isBinary: true,
getRequestURL: function(props) {
return props.url;
},
parseResponseBody: function(rsp) {
var buf = ByteBuffer.wrap(rsp);
var chunks = [];
while(buf.remaining()) {
var size = buf.readUint32();
var slice = buf.slice(buf.offset, buf.offset + size);
buf.skip(size);
chunks.push(ChunkData.decode(slice.toBuffer()));
}
return chunks;
}
};
module.exports = DataRedirectRequestType;
| var ByteBuffer = require('bytebuffer');
var ProtoBuf = require('protobufjs');
var path = require('path');
var ChunkData =
ProtoBuf
.loadProtoFile(path.join(__dirname, 'ChunkData.proto'))
.build('ChunkData');
var DataRedirectRequestType = {
isBinary: true,
getRequestURL: function(props) {
return props.url;
},
parseResponseBody: function(rsp) {
var buf = ByteBuffer.wrap(rsp);
var chunks = [];
while (buf.remaining() > 0) {
var size = buf.readUint32();
var slice = buf.slice(buf.offset, buf.offset + size);
buf.skip(size);
chunks.push(ChunkData.decode(slice.toBuffer()));
}
return chunks;
}
};
module.exports = DataRedirectRequestType;
| Switch to more robust remaining semantic. | Switch to more robust remaining semantic.
| JavaScript | mit | hellojwilde/node-safebrowsing | ---
+++
@@ -19,7 +19,7 @@
var buf = ByteBuffer.wrap(rsp);
var chunks = [];
- while(buf.remaining()) {
+ while (buf.remaining() > 0) {
var size = buf.readUint32();
var slice = buf.slice(buf.offset, buf.offset + size);
buf.skip(size); |
5d19685eb229aa510b9ca0b79d093f6eb6f2f5ef | app/services/passwordCheckService.js | app/services/passwordCheckService.js | var app = angular.module("AdmissionsApp");
app.service("PasswordCheckService", ["$http", function ($http) {
var submitBaseUrl = "http://localhost:8001/part";
this.checkPassword = function (password, partNumber) {
var submitData = {answer: password};
return $http.post(submitBaseUrl + "/" + partNumber, submitData)
.then(function (response) {
return response.data;
});
}
}]); | var app = angular.module("AdmissionsApp");
app.service("PasswordCheckService", ["$http", function ($http) {
var submitBaseUrl = "http://admissions-project.codingcamp.us/part";
this.checkPassword = function (password, partNumber) {
var submitData = {answer: password};
return $http.post(submitBaseUrl + "/" + partNumber, submitData)
.then(function (response) {
return response.data;
});
}
}]); | Change baseurl from angular to admissions-project.codingcamp.us | Change baseurl from angular to admissions-project.codingcamp.us
| JavaScript | mit | bobziroll/admissions,bobziroll/admissions | ---
+++
@@ -1,7 +1,7 @@
var app = angular.module("AdmissionsApp");
app.service("PasswordCheckService", ["$http", function ($http) {
- var submitBaseUrl = "http://localhost:8001/part";
+ var submitBaseUrl = "http://admissions-project.codingcamp.us/part";
this.checkPassword = function (password, partNumber) {
var submitData = {answer: password}; |
49c001670c4ec12041c5a39767879d0cb1f3a76e | index.js | index.js | var katex = require("katex");
var cheerio = require("cheerio");
module.exports = {
book: {
assets: "./book",
js: []
},
hooks: {
page: function(page) {
for (var i in page.sections) {
section = page.sections[i];
if ( section.type != "normal" ) continue;
var $ = cheerio.load(section.content);
$("script").each(function() {
// Check is math
var type = $(this).attr("type") || "";
if (type.indexOf("math/tex") < 0) return;
var math = $(this).html();
$(this).replaceWith(katex.renderToString(math));
});
// Replace by transform
section.content = $.html();
}
return page;
}
}
};
| var katex = require("katex");
var cheerio = require("cheerio");
module.exports = {
book: {
assets: "./book",
js: [],
css: [
"https://khan.github.io/KaTeX/lib/katex/katex.min.css"
]
},
hooks: {
page: function(page) {
for (var i in page.sections) {
section = page.sections[i];
if ( section.type != "normal" ) continue;
var $ = cheerio.load(section.content);
$("script").each(function() {
// Check is math
var type = $(this).attr("type") || "";
if (type.indexOf("math/tex") < 0) return;
var math = $(this).html();
$(this).replaceWith(katex.renderToString(math));
});
// Replace by transform
section.content = $.html();
}
return page;
}
}
};
| Add css file for katex fonts | Add css file for katex fonts
| JavaScript | apache-2.0 | GitbookIO/plugin-katex | ---
+++
@@ -4,7 +4,10 @@
module.exports = {
book: {
assets: "./book",
- js: []
+ js: [],
+ css: [
+ "https://khan.github.io/KaTeX/lib/katex/katex.min.css"
+ ]
},
hooks: {
page: function(page) { |
dd302f6145e34a2cb796011b7b4b568158ed6ec1 | lib/index.js | lib/index.js | import parser from "./parser";
export {default as Token} from "./lexer/token";
export {default as Node} from "./lexer/node";
export default {
parse: parser
};
| import parser from "./parser";
export {default as Token} from "./lexer/token";
export {default as Node} from "./parser/node";
export default {
parse: parser
};
| Remove lexer from the public API | Remove lexer from the public API
| JavaScript | mit | coryroloff/dustjs-ast | ---
+++
@@ -1,7 +1,7 @@
import parser from "./parser";
export {default as Token} from "./lexer/token";
-export {default as Node} from "./lexer/node";
+export {default as Node} from "./parser/node";
export default {
parse: parser |
d1e80ed5aa35827b3d91db596209f71975ce7549 | index.js | index.js | 'use strict';
var amazon = require('amazon-product-api');
var client = amazon.createClient({
awsId: process.env.AWS_ID,
awsSecret: process.env.AWS_SECRET,
awsTag: process.env.AWS_TAG
});
module.exports = function(title, cb) {
client.itemSearch({
keywords: title,
searchIndex: 'Books',
responseGroup: 'ItemAttributes'
}, function(err, results) {
if(err) {
return cb(err);
}
var originalUrl = results[0].DetailPageURL[0];
var fullTitle = results[0].ItemAttributes[0].Title[0];
var authors = results[0].ItemAttributes[0].Author;
var url = originalUrl.split('%3FSubscriptionId')[0].trim();
var hasSubtitle = (fullTitle.indexOf(':') !== -1);
var title = hasSubtitle ? fullTitle.split(':')[0].trim() : fullTitle;
var subtitle = hasSubtitle ? fullTitle.split(':')[1].trim() : void 0;
var markdownString = ['[', title, '](', url, ')'];
if(subtitle){
markdownString.push(' - *', subtitle, '*');
}
cb(null, {
url: url,
authors: authors,
title: title,
subtitle: subtitle,
markdown: markdownString.join('')
});
});
};
| 'use strict';
var amazon = require('amazon-product-api');
var client = amazon.createClient({
awsId: process.env.AWS_ID,
awsSecret: process.env.AWS_SECRET,
awsTag: process.env.AWS_TAG
});
module.exports = function(title, cb) {
client.itemSearch({
keywords: title,
searchIndex: 'Books',
responseGroup: 'ItemAttributes'
})
.then(function(results) {
var originalUrl = results[0].DetailPageURL[0];
var fullTitle = results[0].ItemAttributes[0].Title[0];
var authors = results[0].ItemAttributes[0].Author;
var url = originalUrl.split('%3FSubscriptionId')[0].trim();
var hasSubtitle = (fullTitle.indexOf(':') !== -1);
var title = hasSubtitle ? fullTitle.split(':')[0].trim() : fullTitle;
var subtitle = hasSubtitle ? fullTitle.split(':')[1].trim() : void 0;
var markdownString = ['[', title, '](', url, ')'];
if(subtitle){
markdownString.push(' - *', subtitle, '*');
}
cb(null, {
url: url,
authors: authors,
title: title,
subtitle: subtitle,
markdown: markdownString.join('')
});
})
.catch(cb);
};
| Switch amazon-product-api to use promises | Switch amazon-product-api to use promises
| JavaScript | mit | matiassingers/shelfies-amazon-linker | ---
+++
@@ -12,32 +12,30 @@
keywords: title,
searchIndex: 'Books',
responseGroup: 'ItemAttributes'
- }, function(err, results) {
- if(err) {
- return cb(err);
- }
+ })
+ .then(function(results) {
+ var originalUrl = results[0].DetailPageURL[0];
+ var fullTitle = results[0].ItemAttributes[0].Title[0];
+ var authors = results[0].ItemAttributes[0].Author;
- var originalUrl = results[0].DetailPageURL[0];
- var fullTitle = results[0].ItemAttributes[0].Title[0];
- var authors = results[0].ItemAttributes[0].Author;
+ var url = originalUrl.split('%3FSubscriptionId')[0].trim();
- var url = originalUrl.split('%3FSubscriptionId')[0].trim();
+ var hasSubtitle = (fullTitle.indexOf(':') !== -1);
+ var title = hasSubtitle ? fullTitle.split(':')[0].trim() : fullTitle;
+ var subtitle = hasSubtitle ? fullTitle.split(':')[1].trim() : void 0;
- var hasSubtitle = (fullTitle.indexOf(':') !== -1);
- var title = hasSubtitle ? fullTitle.split(':')[0].trim() : fullTitle;
- var subtitle = hasSubtitle ? fullTitle.split(':')[1].trim() : void 0;
+ var markdownString = ['[', title, '](', url, ')'];
+ if(subtitle){
+ markdownString.push(' - *', subtitle, '*');
+ }
- var markdownString = ['[', title, '](', url, ')'];
- if(subtitle){
- markdownString.push(' - *', subtitle, '*');
- }
-
- cb(null, {
- url: url,
- authors: authors,
- title: title,
- subtitle: subtitle,
- markdown: markdownString.join('')
- });
- });
+ cb(null, {
+ url: url,
+ authors: authors,
+ title: title,
+ subtitle: subtitle,
+ markdown: markdownString.join('')
+ });
+ })
+ .catch(cb);
}; |
138fdeef3eef86aeb629b64e69c523fe0aa62db4 | index.js | index.js | var pkg = require("./package.json");
module.exports = {
build: require("./lib/build"),
create: require("./lib/create"),
compiler: require("truffle-compile"),
config: require("./lib/config"),
console: require("./lib/repl"),
contracts: require("./lib/contracts"),
require: require("truffle-require"),
init: require("./lib/init"),
migrate: require("truffle-migrate"),
package: require("./lib/package"),
serve: require("./lib/serve"),
sources: require("truffle-contract-sources"),
test: require("./lib/test"),
version: pkg.version
};
| var pkg = require("./package.json");
module.exports = {
build: require("./lib/build"),
create: require("./lib/create"),
config: require("./lib/config"),
console: require("./lib/repl"),
contracts: require("./lib/contracts"),
init: require("./lib/init"),
package: require("./lib/package"),
serve: require("./lib/serve"),
test: require("./lib/test"),
version: pkg.version
};
| Remove references to items that have been pulled out into their own modules. | Remove references to items that have been pulled out into their own
modules.
| JavaScript | mit | DigixGlobal/truffle,prashantpawar/truffle | ---
+++
@@ -3,16 +3,12 @@
module.exports = {
build: require("./lib/build"),
create: require("./lib/create"),
- compiler: require("truffle-compile"),
config: require("./lib/config"),
console: require("./lib/repl"),
contracts: require("./lib/contracts"),
- require: require("truffle-require"),
init: require("./lib/init"),
- migrate: require("truffle-migrate"),
package: require("./lib/package"),
serve: require("./lib/serve"),
- sources: require("truffle-contract-sources"),
test: require("./lib/test"),
version: pkg.version
}; |
7e468b98aed7cff07595739fbfc4b0e2db3e5d4c | ui/src/utils/ajax.js | ui/src/utils/ajax.js | import axios from 'axios'
let links
export default async function AJAX({
url,
resource,
id,
method = 'GET',
data = {},
params = {},
headers = {},
}) {
try {
const basepath = window.basepath || ''
let response
url = `${basepath}${url}`
if (!links) {
const linksRes = (response = await axios({
url: `${basepath}/chronograf/v1`,
method: 'GET',
}))
links = linksRes.data
}
const {auth} = links
if (resource) {
url = id
? `${basepath}${links[resource]}/${id}`
: `${basepath}${links[resource]}`
}
response = await axios({
url,
method,
data,
params,
headers,
})
return {
auth,
...response,
}
} catch (error) {
const {response} = error
const {auth} = links
throw {...response, auth: {links: auth}} // eslint-disable-line no-throw-literal
}
}
| import axios from 'axios'
let links
export default async function AJAX({
url,
resource,
id,
method = 'GET',
data = {},
params = {},
headers = {},
}) {
try {
const basepath = window.basepath || ''
let response
url = `${basepath}${url}`
if (!links) {
const linksRes = (response = await axios({
url: `${basepath}/chronograf/v1`,
method: 'GET',
}))
links = linksRes.data
}
if (resource) {
url = id
? `${basepath}${links[resource]}/${id}`
: `${basepath}${links[resource]}`
}
response = await axios({
url,
method,
data,
params,
headers,
})
const {auth} = links
return {
...response,
auth: {links: auth},
}
} catch (error) {
const {response} = error
const {auth} = links
throw {...response, auth: {links: auth}} // eslint-disable-line no-throw-literal
}
}
| Fix links assignment on some AJAX requests | Fix links assignment on some AJAX requests
| JavaScript | agpl-3.0 | brianbaker/chronograf,brianbaker/chronograf,brianbaker/chronograf,brianbaker/chronograf,brianbaker/chronograf | ---
+++
@@ -25,8 +25,6 @@
links = linksRes.data
}
- const {auth} = links
-
if (resource) {
url = id
? `${basepath}${links[resource]}/${id}`
@@ -41,9 +39,11 @@
headers,
})
+ const {auth} = links
+
return {
- auth,
...response,
+ auth: {links: auth},
}
} catch (error) {
const {response} = error |
e5803bc13cdcf0d21bd13486bbe3b05eda4004f5 | index.js | index.js | 'use strict';
const CssImport = require('postcss-import');
const PresetEnv = require('postcss-preset-env');
const broccoliPostCSS = require('broccoli-postcss')
const mergeTrees = require('broccoli-merge-trees');
const funnel = require('broccoli-funnel');
const get = require('lodash.get');
const { join } = require('path');
module.exports = {
name: require('./package').name,
treeForAddon() {
var tree = this._super(...arguments);
const addonWithoutStyles = funnel(tree, {
exclude: ['**/*.css'],
});
const addonStyles = funnel(tree, {
include: ['**/*.css']
});
// I don't know exactly why targets is private so I am using `get()` to make
// sure that it isn't missing
let overrideBrowserslist = get(this, 'app.project._targets.browsers');
let processedStyles = broccoliPostCSS(addonStyles, {
plugins: [
CssImport({
path: join(__dirname, 'addon', 'styles'),
}),
PresetEnv({
stage: 3,
features: { 'nesting-rules': true },
overrideBrowserslist,
})
]});
return mergeTrees([addonWithoutStyles, processedStyles]);
},
};
| 'use strict';
const CssImport = require('postcss-import');
const PresetEnv = require('postcss-preset-env');
const broccoliPostCSS = require('broccoli-postcss');
const mergeTrees = require('broccoli-merge-trees');
const funnel = require('broccoli-funnel');
const get = require('lodash.get');
const { join } = require('path');
const pkg = require('./package.json');
module.exports = {
name: require('./package').name,
treeForAddon() {
let tree = this._super(...arguments);
let app = this._findHost();
let options = typeof app.options === 'object' ? app.options : {};
let addonConfig = options[pkg.name] || {};
const addonWithoutStyles = funnel(tree, {
exclude: ['**/*.css'],
});
if (addonConfig.excludeCSS === true) {
return addonWithoutStyles;
}
const addonStyles = funnel(tree, {
include: ['**/*.css'],
});
// I don't know exactly why targets is private so I am using `get()` to make
// sure that it isn't missing
let overrideBrowserslist = get(this, 'app.project._targets.browsers');
let processedStyles = broccoliPostCSS(addonStyles, {
plugins: [
CssImport({
path: join(__dirname, 'addon', 'styles'),
}),
PresetEnv({
stage: 3,
features: { 'nesting-rules': true },
overrideBrowserslist,
}),
],
});
return mergeTrees([addonWithoutStyles, processedStyles]);
},
};
| Add configuration option to exclude all CSS | Add configuration option to exclude all CSS
This can be used together with PostCSS or other processors which support importing from node_modules to consume the unmangled CSS, which can be useful in modern environments.
| JavaScript | mit | stonecircle/ember-cli-notifications,stonecircle/ember-cli-notifications,Blooie/ember-cli-notifications,Blooie/ember-cli-notifications | ---
+++
@@ -2,24 +2,32 @@
const CssImport = require('postcss-import');
const PresetEnv = require('postcss-preset-env');
-const broccoliPostCSS = require('broccoli-postcss')
+const broccoliPostCSS = require('broccoli-postcss');
const mergeTrees = require('broccoli-merge-trees');
const funnel = require('broccoli-funnel');
const get = require('lodash.get');
const { join } = require('path');
+const pkg = require('./package.json');
module.exports = {
name: require('./package').name,
treeForAddon() {
- var tree = this._super(...arguments);
+ let tree = this._super(...arguments);
+ let app = this._findHost();
+ let options = typeof app.options === 'object' ? app.options : {};
+ let addonConfig = options[pkg.name] || {};
const addonWithoutStyles = funnel(tree, {
exclude: ['**/*.css'],
});
+ if (addonConfig.excludeCSS === true) {
+ return addonWithoutStyles;
+ }
+
const addonStyles = funnel(tree, {
- include: ['**/*.css']
+ include: ['**/*.css'],
});
// I don't know exactly why targets is private so I am using `get()` to make
@@ -35,8 +43,9 @@
stage: 3,
features: { 'nesting-rules': true },
overrideBrowserslist,
- })
- ]});
+ }),
+ ],
+ });
return mergeTrees([addonWithoutStyles, processedStyles]);
}, |
70269a8689c2ff1bd140441da183cc993b51fa8b | src/pages/data/primary-dataset.js | src/pages/data/primary-dataset.js | import React, { PropTypes } from 'react'
import Map from '../home/map'
import LayerKey from './layer-key'
const PrimaryDataset = ({ dataset, lngLat }) => {
if (!dataset) return null
const { name, provider, description, url } = dataset
const selectedLayers = [dataset]
return (
<article className='cf'>
<div className='fl w-40-ns'>
<h1 className='f6 black-40 ttu tracked'>{name}</h1>
<p className='f6 black-40 ttu tracked'>{provider}</p>
<p className='lh-copy'>{description}</p>
<p className='mb4'>
<a href={url} target='_blank' className='green'>Find out more</a>
</p>
<LayerKey dataset={dataset} />
</div>
<div className='fl w-60-ns pl3'>
<Map datasets={selectedLayers} selectedLayers={selectedLayers} lngLat={lngLat} zoom={10} minZoom={8} />
</div>
</article>
)
}
PrimaryDataset.propTypes = {
dataset: PropTypes.shape({
name: PropTypes.string.isRequired,
provider: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
url: PropTypes.string.isRequired,
source: PropTypes.shape({
type: PropTypes.string.isRequired,
url: PropTypes.string.isRequired
}),
layers: PropTypes.array
}),
lngLat: PropTypes.shape({
lng: PropTypes.number.isRequired,
lat: PropTypes.number.isRequired
})
}
export default PrimaryDataset
| import React, { PropTypes } from 'react'
import Map from '../home/map'
import LayerKey from './layer-key'
const PrimaryDataset = ({ dataset, lngLat }) => {
if (!dataset) return null
const { name, provider, description, url } = dataset
const selectedLayers = [dataset]
return (
<article className='cf'>
<div className='fl w-40-ns'>
<h1 className='f6 black-40 ttu tracked'>{name}</h1>
<p className='f6 black-40 ttu tracked'>{provider}</p>
<p className='lh-copy'>{description}</p>
<p className='mb4'>
<a href={url} target='_blank' className='green'>Find out more</a>
</p>
<LayerKey dataset={dataset} />
</div>
<div className='fl w-60-ns pl3'>
<Map datasets={selectedLayers} selectedLayers={selectedLayers} lngLat={lngLat} zoom={11} minZoom={8} />
</div>
</article>
)
}
PrimaryDataset.propTypes = {
dataset: PropTypes.shape({
name: PropTypes.string.isRequired,
provider: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
url: PropTypes.string.isRequired,
source: PropTypes.shape({
type: PropTypes.string.isRequired,
url: PropTypes.string.isRequired
}),
layers: PropTypes.array
}),
lngLat: PropTypes.shape({
lng: PropTypes.number.isRequired,
lat: PropTypes.number.isRequired
})
}
export default PrimaryDataset
| Make data zoom match place zoom | Make data zoom match place zoom
| JavaScript | agpl-3.0 | tableflip/landexplorer,tableflip/landexplorer | ---
+++
@@ -18,7 +18,7 @@
<LayerKey dataset={dataset} />
</div>
<div className='fl w-60-ns pl3'>
- <Map datasets={selectedLayers} selectedLayers={selectedLayers} lngLat={lngLat} zoom={10} minZoom={8} />
+ <Map datasets={selectedLayers} selectedLayers={selectedLayers} lngLat={lngLat} zoom={11} minZoom={8} />
</div>
</article>
) |
1ba4ed884ae724944e186f8a729e06d16b6ace24 | index.js | index.js | var solarflare = function (rays) {
var $element = document.createElement('div');
if (Array.isArray(rays)) {
rays.forEach(function (e, i) {
if (i === 0 && typeof e === 'string') {
if (e.length > 0) {
$element = document.createElement(e);
}
return;
}
if (typeof e === 'string') {
$element.innerHTML += e;
}
if (e.nodeType) {
$element.appendChild(e);
}
if (typeof e === 'object') {
if (Array.isArray(e)) {
$element.appendChild(solarflare(e));
} else {
Object.keys(e).filter(function (key) {
$element.setAttribute(key, e[key]);
});
}
}
});
}
return $element;
};
module.exports = solarflare;
| var solarflare = function (rays) {
var $element = document.createElement('div');
if (Array.isArray(rays)) {
rays.forEach(function (e, i) {
if (i === 0 && typeof e === 'string') {
if (e.length > 0) {
$element = document.createElement(e);
}
return;
}
if (typeof e === 'string') {
$element.innerHTML += e;
}
if (e.nodeType) {
$element.appendChild(e);
}
if (typeof e === 'object') {
if (Array.isArray(e)) {
$element.appendChild(solarflare(e));
} else if (e.view && typeof e.view === 'function') {
$element.appendChild(e.view());
} else {
Object.keys(e).filter(function (key) {
$element.setAttribute(key, e[key]);
});
}
}
});
}
return $element;
};
module.exports = solarflare;
| Check for view function in objects. | Check for view function in objects.
| JavaScript | mit | thirdstrongestguardian/solarflare | ---
+++
@@ -22,6 +22,8 @@
if (typeof e === 'object') {
if (Array.isArray(e)) {
$element.appendChild(solarflare(e));
+ } else if (e.view && typeof e.view === 'function') {
+ $element.appendChild(e.view());
} else {
Object.keys(e).filter(function (key) {
$element.setAttribute(key, e[key]); |
e4ff593f3b474ace3df94fb42f4a666a14e94759 | index.js | index.js | import {
cacheClient,
jsonCodec
} from '@scola/api';
import Server from './src/server';
export {
Server,
cacheClient,
jsonCodec
};
| import {
cacheClient,
jsonCodec,
jsonFilter
} from '@scola/api';
import Server from './src/server';
export {
Server,
cacheClient,
jsonCodec,
jsonFilter
};
| Add jsonFilter in export for HTTP setup | Add jsonFilter in export for HTTP setup
| JavaScript | mit | scola84/node-app-server | ---
+++
@@ -1,6 +1,7 @@
import {
cacheClient,
- jsonCodec
+ jsonCodec,
+ jsonFilter
} from '@scola/api';
import Server from './src/server';
@@ -8,5 +9,6 @@
export {
Server,
cacheClient,
- jsonCodec
+ jsonCodec,
+ jsonFilter
}; |
a5b2703306889221297e896f0f64134923882204 | index.js | index.js | const tmp = require('tmp');
const fs = require('fs');
function isReactComponent(source = '') {
return source.indexOf('(_react.Component)') > -1;
}
function WebpackAccessibilityPlugin(options) {
this.createElement = options.createElement;
this.renderMarkup = options.renderMarkup;
}
WebpackAccessibilityPlugin.prototype.apply = (compiler) => {
compiler.plugin('emit', (compilation, callback) => {
// Explore each chunk (build output):
compilation.chunks.forEach((chunk) => {
// Start with application specific modules
chunk.modules
.filter(module => module.resource && module.resource.indexOf('node_modules') === -1 && module.resource.match(/\.(js|jsx)$/))
.map(module => module._source._value)
.filter(isReactComponent)
.forEach((source) => {
// Write to temporary file
tmp.file({ postfix: '.js', dir: './tmp' }, (tmpErr, path, fd, cleanupCallback) => {
if (tmpErr) throw tmpErr;
const self = this;
fs.writeFile(path, source, (err) => {
if (err) throw err;
const component = require(path).default;
const element = self.createElement(component);
const markup = self.renderMarkup(element);
// Run a11y report on markup!
console.log(markup);
cleanupCallback();
});
});
}, this);
}, this);
callback();
});
};
module.exports = WebpackAccessibilityPlugin;
| const tmp = require('tmp');
const fs = require('fs');
function isReactComponent(source = '') {
return source.indexOf('(_react.Component)') > -1;
}
function WebpackAccessibilityPlugin(options) {
this.createElement = options.createElement;
this.renderMarkup = options.renderMarkup;
}
WebpackAccessibilityPlugin.prototype.apply = (compiler) => {
compiler.plugin('emit', (compilation, callback) => {
// Explore each chunk (build output):
compilation.chunks.forEach((chunk) => {
// Start with application specific modules
chunk.modules
.filter(module => module.resource && module.resource.indexOf('node_modules') === -1 && module.resource.match(/\.(js|jsx)$/))
.map(module => module._source._value) // eslint-disable-line no-underscore-dangle
.filter(isReactComponent)
.forEach((source) => {
// Write to temporary file
tmp.file({ postfix: '.js', dir: `${__dirname}/tmp` }, (tmpErr, path, fd, cleanupCallback) => {
if (tmpErr) throw tmpErr;
fs.writeFile(path, source, (err) => {
if (err) throw err;
const component = require(path).default; // eslint-disable-line
const element = this.createElement(component);
const markup = this.renderMarkup(element);
// Run a11y report on markup!
console.log(markup); // eslint-disable-line
cleanupCallback();
});
});
}, this);
}, this);
callback();
});
};
module.exports = WebpackAccessibilityPlugin;
| Fix path issues and this scoping issues. | Fix path issues and this scoping issues.
| JavaScript | mit | evcohen/accessibility-webpack-plugin | ---
+++
@@ -17,23 +17,22 @@
// Start with application specific modules
chunk.modules
.filter(module => module.resource && module.resource.indexOf('node_modules') === -1 && module.resource.match(/\.(js|jsx)$/))
- .map(module => module._source._value)
+ .map(module => module._source._value) // eslint-disable-line no-underscore-dangle
.filter(isReactComponent)
.forEach((source) => {
// Write to temporary file
- tmp.file({ postfix: '.js', dir: './tmp' }, (tmpErr, path, fd, cleanupCallback) => {
+ tmp.file({ postfix: '.js', dir: `${__dirname}/tmp` }, (tmpErr, path, fd, cleanupCallback) => {
if (tmpErr) throw tmpErr;
- const self = this;
fs.writeFile(path, source, (err) => {
if (err) throw err;
- const component = require(path).default;
- const element = self.createElement(component);
- const markup = self.renderMarkup(element);
+ const component = require(path).default; // eslint-disable-line
+ const element = this.createElement(component);
+ const markup = this.renderMarkup(element);
// Run a11y report on markup!
- console.log(markup);
+ console.log(markup); // eslint-disable-line
cleanupCallback();
}); |
20150d63e25f99d1f06b4c35116152760e722aca | index.js | index.js | 'use strict';
var EventEmitter = require('events').EventEmitter;
var Console = require('./console');
var hostname = require('os').hostname();
var pid = process.pid;
var emitter = new EventEmitter();
var _console = new Console(process.stdout);
module.exports = factory;
factory.on = function (event, listener) {
emitter.on(event, listener);
};
factory.removeListener = function (event, listener) {
emitter.removeListener(event, listener);
};
factory.setOutputStream = function (stream) {
if (!stream) {
_console = null;
return;
}
_console = new Console(stream);
};
function factory (componentName) {
return new LoggingContext(componentName);
}
function LoggingContext(componentName) {
this._name = componentName;
}
LoggingContext.prototype.chalk = require('chalk');
LoggingContext.prototype._write = function (level, message, data) {
var payload = {
component : this._name,
time : new Date(),
hostname : hostname,
level : level,
message : message,
pid : pid,
data : data
};
emitter.emit('data', payload);
if (_console) {
_console.write(payload);
}
};
['log', 'warn', 'info', 'error', 'debug']
.forEach(function (level) {
LoggingContext.prototype[level] = function (message, metadata) {
this._write(level, message, metadata);
};
});
| 'use strict';
var EventEmitter = require('events').EventEmitter;
var Console = require('./console');
var hostname = require('os').hostname();
var pid = process.pid;
var emitter = new EventEmitter();
var _console = new Console(process.stderr);
module.exports = factory;
factory.on = function (event, listener) {
emitter.on(event, listener);
};
factory.removeListener = function (event, listener) {
emitter.removeListener(event, listener);
};
factory.setOutputStream = function (stream) {
if (!stream) {
_console = null;
return;
}
_console = new Console(stream);
};
function factory (componentName) {
return new LoggingContext(componentName);
}
function LoggingContext(componentName) {
this._name = componentName;
}
LoggingContext.prototype.chalk = require('chalk');
LoggingContext.prototype._write = function (level, message, data) {
var payload = {
component : this._name,
time : new Date(),
hostname : hostname,
level : level,
message : message,
pid : pid,
data : data
};
emitter.emit('data', payload);
if (_console) {
_console.write(payload);
}
};
['log', 'warn', 'info', 'error', 'debug']
.forEach(function (level) {
LoggingContext.prototype[level] = function (message, metadata) {
this._write(level, message, metadata);
};
});
| Use stderr.isTTY instead of stdout.isTTY | Use stderr.isTTY instead of stdout.isTTY
| JavaScript | mit | aantthony/logger | ---
+++
@@ -7,7 +7,7 @@
var pid = process.pid;
var emitter = new EventEmitter();
-var _console = new Console(process.stdout);
+var _console = new Console(process.stderr);
module.exports = factory;
|
f9d7d9eb13c8f48e36012c063fce41382408a04b | index.js | index.js | var PostcssCompiler = require('broccoli-postcss');
var checker = require('ember-cli-version-checker');
function PostCSSPlugin (plugins, options) {
this.name = 'ember-cli-postcss';
options = options || {};
options.inputFile = options.inputFile || 'app.css';
options.outputFile = options.outputFile || 'app.css';
this.options = options;
this.plugins = plugins;
}
PostCSSPlugin.prototype.toTree = function (tree, inputPath, outputPath) {
var trees = [tree];
if (this.options.includePaths) {
trees = trees.concat(this.options.includePaths);
}
inputPath += '/' + this.options.inputFile;
outputPath += '/' + this.options.outputFile;
return new PostcssCompiler(trees, inputPath, outputPath, this.plugins);
};
module.exports = {
name: 'Ember CLI Postcss',
shouldSetupRegistryInIncluded: function() {
return !checker.isAbove(this, '0.2.0');
},
included: function included (app) {
this.app = app;
var options = app.options.postcssOptions || {};
var plugins = this.plugins = options.plugins || [];
options.outputFile = options.outputFile || this.project.name() + '.css';
app.registry.add('css', new PostCSSPlugin(plugins, options));
if (this.shouldSetupRegistryInIncluded()) {
this.setupPreprocessorRegistry('parent', app.registry);
}
}
};
| var PostcssCompiler = require('broccoli-postcss');
var checker = require('ember-cli-version-checker');
// PostCSSPlugin constructor
function PostCSSPlugin (options) {
this.name = 'ember-cli-postcss';
this.options = options;
this.plugins = options.plugins;
this.map = options.map;
}
PostCSSPlugin.prototype.toTree = function (tree, inputPath, outputPath) {
var trees = [tree];
if (this.options.includePaths) {
trees = trees.concat(this.options.includePaths);
}
inputPath += '/' + this.options.inputFile;
outputPath += '/' + this.options.outputFile;
return new PostcssCompiler(trees, inputPath, outputPath, this.plugins, this.map);
};
module.exports = {
name: 'Ember CLI Postcss',
shouldSetupRegistryInIncluded: function() {
return !checker.isAbove(this, '0.2.0');
},
included: function included (app) {
this.app = app;
// Initialize options if none were passed
var options = app.options.postcssOptions || {};
// Set defaults if none were passed
options.map = options.map || {};
options.plugins = options.plugins || [];
options.inputFile = options.inputFile || 'app.css';
options.outputFile = options.outputFile || this.project.name() + '.css';
// Add to registry and pass options
app.registry.add('css', new PostCSSPlugin(options));
if (this.shouldSetupRegistryInIncluded()) {
this.setupPreprocessorRegistry('parent', app.registry);
}
}
};
| Add map argument to PostCSSPlugin constructor | Add map argument to PostCSSPlugin constructor
And simplify the default options
| JavaScript | mit | jeffjewiss/ember-cli-postcss,jeffjewiss/ember-cli-postcss | ---
+++
@@ -1,13 +1,12 @@
var PostcssCompiler = require('broccoli-postcss');
var checker = require('ember-cli-version-checker');
-function PostCSSPlugin (plugins, options) {
+// PostCSSPlugin constructor
+function PostCSSPlugin (options) {
this.name = 'ember-cli-postcss';
- options = options || {};
- options.inputFile = options.inputFile || 'app.css';
- options.outputFile = options.outputFile || 'app.css';
this.options = options;
- this.plugins = plugins;
+ this.plugins = options.plugins;
+ this.map = options.map;
}
PostCSSPlugin.prototype.toTree = function (tree, inputPath, outputPath) {
@@ -20,7 +19,7 @@
inputPath += '/' + this.options.inputFile;
outputPath += '/' + this.options.outputFile;
- return new PostcssCompiler(trees, inputPath, outputPath, this.plugins);
+ return new PostcssCompiler(trees, inputPath, outputPath, this.plugins, this.map);
};
module.exports = {
@@ -30,12 +29,17 @@
},
included: function included (app) {
this.app = app;
+ // Initialize options if none were passed
var options = app.options.postcssOptions || {};
- var plugins = this.plugins = options.plugins || [];
+ // Set defaults if none were passed
+ options.map = options.map || {};
+ options.plugins = options.plugins || [];
+ options.inputFile = options.inputFile || 'app.css';
options.outputFile = options.outputFile || this.project.name() + '.css';
- app.registry.add('css', new PostCSSPlugin(plugins, options));
+ // Add to registry and pass options
+ app.registry.add('css', new PostCSSPlugin(options));
if (this.shouldSetupRegistryInIncluded()) {
this.setupPreprocessorRegistry('parent', app.registry); |
3400709119be37c6f2a9be6efba3c2a00de4e349 | index.js | index.js |
try {
module.exports = require('./build/Release/node_sleep.node');
} catch (e) {
console.log('sleep: using busy loop fallback');
module.exports = {
sleep: function(s) {
var e = new Date().getTime() + (s * 1000);
while (new Date().getTime() <= e) {
;
}
},
usleep: function(s) {
var e = new Date().getTime() + (s / 1000);
while (new Date().getTime() <= e) {
;
}
}
};
}
|
try {
module.exports = require('./build/Release/node_sleep.node');
} catch (e) {
console.error('sleep: using busy loop fallback');
module.exports = {
sleep: function(s) {
var e = new Date().getTime() + (s * 1000);
while (new Date().getTime() <= e) {
;
}
},
usleep: function(s) {
var e = new Date().getTime() + (s / 1000);
while (new Date().getTime() <= e) {
;
}
}
};
}
| Print fallback warning to stderr rather than stdout | Print fallback warning to stderr rather than stdout | JavaScript | mit | ErikDubbelboer/node-sleep,ErikDubbelboer/node-sleep,ErikDubbelboer/node-sleep | ---
+++
@@ -2,7 +2,7 @@
try {
module.exports = require('./build/Release/node_sleep.node');
} catch (e) {
- console.log('sleep: using busy loop fallback');
+ console.error('sleep: using busy loop fallback');
module.exports = {
sleep: function(s) { |
7169b95291a24c69d5bacbf501f2e3f4a7413048 | index.js | index.js | 'use strict';
/**
* Export all prototypes.
* (C) 2013 Alex Fernández.
*/
// requires
require('./lib/string.js');
require('./lib/array.js');
var mathLib = require('./lib/math.js');
var objectLib = require('./lib/object.js');
// exports
exports.overwriteWith(objectLib);
exports.overwriteWith(mathLib);
| 'use strict';
/**
* Export all prototypes.
* (C) 2013 Alex Fernández.
*/
// requires
require('./lib/string.js');
require('./lib/array.js');
var mathLib = require('./lib/math.js');
var objectLib = require('./lib/object.js');
// exports
exports={...objectLib, ...mathLib }
| Fix jest error: undefined overwriteWith(). | Fix jest error: undefined overwriteWith().
| JavaScript | mit | alexfernandez/prototypes | ---
+++
@@ -12,5 +12,4 @@
var objectLib = require('./lib/object.js');
// exports
-exports.overwriteWith(objectLib);
-exports.overwriteWith(mathLib);
+exports={...objectLib, ...mathLib } |
df98deda70f2e53aae5fff219b8e24f946c511e8 | index.js | index.js | /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-nouislider',
included: function(app) {
this._super.included(app);
app.import({
development: app.bowerDirectory + '/nouislider/distribute/nouislider.js',
production: app.bowerDirectory + '/nouislider/distribute/nouislider.min.js'
});
app.import(app.bowerDirectory + '/nouislider/distribute/nouislider.min.css');
app.import('vendor/nouislider/shim.js', {
exports: { 'noUiSlider': ['default'] }
});
}
};
| /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-nouislider',
included: function(app) {
this._super.included(app);
if(!process.env.EMBER_CLI_FASTBOOT) {
app.import({
development: app.bowerDirectory + '/nouislider/distribute/nouislider.js',
production: app.bowerDirectory + '/nouislider/distribute/nouislider.min.js'
});
app.import(app.bowerDirectory + '/nouislider/distribute/nouislider.min.css');
app.import('vendor/nouislider/shim.js', {
exports: { 'noUiSlider': ['default'] }
});
}
}
};
| Put fastboot guard into correct file | Put fastboot guard into correct file
| JavaScript | mit | kennethkalmer/ember-cli-nouislider,kennethkalmer/ember-cli-nouislider,kennethkalmer/ember-cli-nouislider | ---
+++
@@ -6,15 +6,16 @@
included: function(app) {
this._super.included(app);
+ if(!process.env.EMBER_CLI_FASTBOOT) {
+ app.import({
+ development: app.bowerDirectory + '/nouislider/distribute/nouislider.js',
+ production: app.bowerDirectory + '/nouislider/distribute/nouislider.min.js'
+ });
+ app.import(app.bowerDirectory + '/nouislider/distribute/nouislider.min.css');
- app.import({
- development: app.bowerDirectory + '/nouislider/distribute/nouislider.js',
- production: app.bowerDirectory + '/nouislider/distribute/nouislider.min.js'
- });
- app.import(app.bowerDirectory + '/nouislider/distribute/nouislider.min.css');
-
- app.import('vendor/nouislider/shim.js', {
- exports: { 'noUiSlider': ['default'] }
- });
+ app.import('vendor/nouislider/shim.js', {
+ exports: { 'noUiSlider': ['default'] }
+ });
+ }
}
}; |
f4d42dce73a5d300cf2b87ba5caac9f0b356a3cd | index.js | index.js | // dependencies
var jipics = "http://jipics.net/"
, Request = require("request")
, fs = require("fs")
;
/**
* Upload method
*
* Arguments
* @options: a string representing the image path or an
* object contanining the following fields:
* - path: the path to the image
* - deleteAfterUpload: if true, the image will be deleted after a sucessful upload
*
* */
exports.upload = function (options, callback) {
// get the image from the request
if (typeof options === "string") {
options = {
path: options
}
}
// force options to be an object
options = Object (options);
// validate path
if (!options.path) {
return callback ("The path to the image must be provided.");
}
// upload the image to jipics.net
Request.post(jipics, function (err, res) {
// handle error
if (err) { return callback (err); }
// delete image
if (options.deleteAfterUpload) {
return fs.unlink(absoluteImagePath, callback);
}
callback (null, res);
// create the read stream from image file
}).form().append("image", fs.createReadStream(absoluteImagePath));
};
| // dependencies
var jipics = "http://jipics.net/"
, Request = require("request")
, fs = require("fs")
;
/**
* Upload method
*
* Arguments
* @options: a string representing the image path or an
* object contanining the following fields:
* - path: the path to the image
* - deleteAfterUpload: if true, the image will be deleted after a sucessful upload
*
* */
exports.upload = function (options, callback) {
// get the image from the request
if (typeof options === "string") {
options = {
path: options
}
}
// force options to be an object
options = Object (options);
// validate path
if (!options.path) {
return callback ("The path to the image must be provided.");
}
// upload the image to jipics.net
Request.post(jipics, function (err, res) {
// handle error
if (err) { return callback (err); }
// delete image
if (options.deleteAfterUpload) {
return fs.unlink(absoluteImagePath, callback);
}
callback (null, res);
// create the read stream from image file
}).form().append("image", fs.createReadStream(options.path));
};
| Use options.path instead of absoluteImagePath | Use options.path instead of absoluteImagePath
| JavaScript | mit | jillix/node-jipics | ---
+++
@@ -44,5 +44,5 @@
callback (null, res);
// create the read stream from image file
- }).form().append("image", fs.createReadStream(absoluteImagePath));
+ }).form().append("image", fs.createReadStream(options.path));
}; |
15328712460ab20f3544b1b73e4a305790f555fc | lib/cliutils.js | lib/cliutils.js |
/* jshint esnext: true, node: true */
'use strict';
var rollbar = require('rollbar');
var log = require('loglevel');
rollbar.init(process.env.ROLLBAR_TOKEN, {environment: process.env.ROLLBAR_ENVIRONMENT});
exports.rejectHandler = function (err) {
rollbar.handleError(err);
log.error(err);
log.error(err.message);
log.error(err.stack);
log.error("Aborting run.");
process.exit(1);
};
|
/* jshint esnext: true, node: true */
'use strict';
var rollbar = require('rollbar');
var log = require('loglevel');
var moment = require('moment');
rollbar.init(process.env.ROLLBAR_TOKEN, {environment: process.env.ROLLBAR_ENVIRONMENT});
exports.rejectHandler = function (err) {
rollbar.handleError(err);
log.error(err);
log.error(err.message);
log.error(err.stack);
log.error("Aborting run.");
process.exit(1);
};
exports.runCompleteHandler = function(startTime, exitCode) {
let durationString = moment.utc(moment.utc() - startTime).format("HH:mm:ss.SSS");
log.info(`Run complete. Took ${durationString}`);
process.exit(exitCode || 0);
};
| Add common handler for run completion messages | Add common handler for run completion messages
| JavaScript | mit | heroku/awsdetailedbilling | ---
+++
@@ -4,6 +4,7 @@
var rollbar = require('rollbar');
var log = require('loglevel');
+var moment = require('moment');
rollbar.init(process.env.ROLLBAR_TOKEN, {environment: process.env.ROLLBAR_ENVIRONMENT});
@@ -15,3 +16,9 @@
log.error("Aborting run.");
process.exit(1);
};
+
+exports.runCompleteHandler = function(startTime, exitCode) {
+ let durationString = moment.utc(moment.utc() - startTime).format("HH:mm:ss.SSS");
+ log.info(`Run complete. Took ${durationString}`);
+ process.exit(exitCode || 0);
+}; |
432b8e18fc5b173d524d83616b8d8fcd1d624600 | index.js | index.js | const Assert = require('assert')
const Child = require('child_process')
const Fs = require('fs')
const Path = require('path')
const packagePath = Path.join(process.cwd(), 'package.json')
let keys = []
let out = {}
module.exports = (options, done) => {
if (typeof options === 'function') {
done = options
options = {}
}
Assert.equal(typeof options, 'object', 'Options must be an object')
Assert.equal(typeof done, 'function', 'Must pass in a callback function')
options = Object.assign({ node: 'node -v', npm: 'npm -v' }, options)
keys = Object.keys(options)
Fs.readFile(packagePath, 'utf8', (err, packageJson) => {
if (err) return done(err)
packageJson = JSON.parse(packageJson)
out = {
name: packageJson.name,
version: packageJson.version,
env: process.env.NODE_ENV
}
return execute(options, done)
})
}
const execute = (options, done) => {
var key = keys.shift()
if (!key) return done(null, out)
Child.exec(options[key], function (err, stdout) {
out[key] = err ? err.toString() : stdout.replace(/\n/g, '')
return execute(options, done)
})
}
| const Assert = require('assert')
const Child = require('child_process')
const Fs = require('fs')
const Path = require('path')
let keys = []
let out = {}
module.exports = (options, done) => {
if (typeof options === 'function') {
done = options
options = {}
}
Assert.equal(typeof options, 'object', 'Options must be an object')
Assert.equal(typeof done, 'function', 'Must pass in a callback function')
options = Object.assign({ node: 'node -v', npm: 'npm -v' }, options)
keys = Object.keys(options)
out = { env: process.env.NODE_ENV }
packageDetails((err, data) => {
if (err) return done(err)
Object.assign(out, data)
return execute(options, done)
})
}
const packageDetails = (done) => {
const packagePath = Path.join(process.cwd(), 'package.json')
Fs.readFile(packagePath, 'utf8', (err, data) => {
if (err) return done(err)
const { name, version } = JSON.parse(data)
done(null, { name, version })
})
}
const execute = (options, done) => {
var key = keys.shift()
if (!key) return done(null, out)
Child.exec(options[key], function (err, stdout) {
out[key] = err ? err.toString() : stdout.replace(/\n/g, '')
return execute(options, done)
})
}
| Move package details to more function | refactor: Move package details to more function
| JavaScript | mit | onmodulus/knock-knock,jackboberg/knock-knock | ---
+++
@@ -2,8 +2,6 @@
const Child = require('child_process')
const Fs = require('fs')
const Path = require('path')
-
-const packagePath = Path.join(process.cwd(), 'package.json')
let keys = []
let out = {}
@@ -20,17 +18,26 @@
options = Object.assign({ node: 'node -v', npm: 'npm -v' }, options)
keys = Object.keys(options)
- Fs.readFile(packagePath, 'utf8', (err, packageJson) => {
+ out = { env: process.env.NODE_ENV }
+
+ packageDetails((err, data) => {
if (err) return done(err)
- packageJson = JSON.parse(packageJson)
- out = {
- name: packageJson.name,
- version: packageJson.version,
- env: process.env.NODE_ENV
- }
+ Object.assign(out, data)
return execute(options, done)
+ })
+}
+
+const packageDetails = (done) => {
+ const packagePath = Path.join(process.cwd(), 'package.json')
+
+ Fs.readFile(packagePath, 'utf8', (err, data) => {
+ if (err) return done(err)
+
+ const { name, version } = JSON.parse(data)
+
+ done(null, { name, version })
})
}
|
8107e3ece5669a940e449a0accecafbe6119a19e | index.js | index.js | /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-keyboard-shortcuts',
included: function(app, parentAddon) {
let target = (parentAddon || app);
target.import(app.bowerDirectory + '/mousetrap/mousetrap.js');
target.import(
app.bowerDirectory +
'/mousetrap/plugins/global-bind/mousetrap-global-bind.js'
);
}
};
| /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-keyboard-shortcuts',
included: function(app, parentAddon) {
let target = (parentAddon || app);
target.import(app.bowerDirectory + '/mousetrap/mousetrap.js');
}
};
| Remove import of mousetrap global plugin | Remove import of mousetrap global plugin
| JavaScript | mit | Skalar/ember-keyboard-shortcuts,Skalar/ember-keyboard-shortcuts | ---
+++
@@ -7,10 +7,5 @@
included: function(app, parentAddon) {
let target = (parentAddon || app);
target.import(app.bowerDirectory + '/mousetrap/mousetrap.js');
-
- target.import(
- app.bowerDirectory +
- '/mousetrap/plugins/global-bind/mousetrap-global-bind.js'
- );
}
}; |
4bab1cdf0074a95f6251d71662409bdaf0643640 | index.js | index.js | const express = require('express');
const helmet = require('helmet');
const winston = require('winston');
const bodyParser = require('body-parser');
const env = require('./src/env');
var server = express();
var router = require('./src/router');
var PORT = env.PORT || 8000;
server.use(bodyParser.json());
server.use(helmet());
server.use('/', router);
function _get() {
return server;
}
function run(fn) {
fn = fn || function _defaultStart() {
winston.info('Listening at ' + PORT);
};
return server.listen(PORT, fn);
}
if (require.main === module) {
run();
}
module.exports = {
_get: _get,
run: run
};
| const express = require('express');
const helmet = require('helmet');
const winston = require('winston');
const bodyParser = require('body-parser');
const env = require('./src/env');
const q = require('q');
var mongoose = require('mongoose');
var server = express();
var router = require('./src/router');
var PORT = env.PORT || 8000;
// Built-in Promise support is deprecated
mongoose.Promise = q.Promise;
server.use(bodyParser.json());
server.use(helmet());
server.use('/', router);
function _get() {
return server;
}
function run(fn) {
fn = fn || function _defaultStart() {
winston.info('Listening at ' + PORT);
};
return server.listen(PORT, fn);
}
if (require.main === module) {
run();
}
module.exports = {
_get: _get,
run: run
};
| Replace Mongoose promise support with another Q's | fix: Replace Mongoose promise support with another Q's
| JavaScript | mit | NSAppsTeam/nickel-bot | ---
+++
@@ -3,10 +3,15 @@
const winston = require('winston');
const bodyParser = require('body-parser');
const env = require('./src/env');
+const q = require('q');
+var mongoose = require('mongoose');
var server = express();
var router = require('./src/router');
var PORT = env.PORT || 8000;
+
+// Built-in Promise support is deprecated
+mongoose.Promise = q.Promise;
server.use(bodyParser.json());
server.use(helmet()); |
cd8f440db7c1edb9b788f8af0ba6a276a8986b9c | index.js | index.js | var BufferList = require('bl');
var onFinished = require('on-finished');
module.exports = function bufferResponse(res, cb) {
var write = res.write;
var end = res.end;
var buf = new BufferList();
res.write = function(data, enc) {
if (data != undefined) bufferAdd(buf, data, enc)
write.bind(res)(data, enc);
};
res.end = function(data, enc) {
if (data != undefined) bufferAdd(buf, data, enc)
end.bind(res)(data, enc);
};
onFinished(res, function(err) {
res.write = write;
res.end = end;
var len = parseInt(res.get('Content-Length'));
if (!isNaN(len)) buf = buf.slice(0, len);
cb(err, buf);
});
};
function bufferAdd(buf, data, enc) {
if (typeof data == "string") buf.append(new Buffer(data, enc));
else if (data) buf.append(data);
}
| var BufferList = require('bl');
var onFinished = require('on-finished');
module.exports = function bufferResponse(res, cb) {
var write = res.write;
var end = res.end;
var buf = new BufferList();
res.write = function(data, enc) {
if (data != undefined) bufferAdd(buf, data, enc)
write.bind(res)(data, enc);
};
res.end = function(data, enc) {
if (data != undefined) bufferAdd(buf, data, enc)
end.bind(res)(data, enc);
};
onFinished(res, function(err) {
res.write = write;
res.end = end;
var len = parseInt(res.get('Content-Length'));
if (!isNaN(len)) {
buf = buf.slice(0, len);
}
if (!err && res.req.connection.destroyed) {
res.statusCode = 0;
buf = null;
}
cb(err, buf);
});
};
function bufferAdd(buf, data, enc) {
if (typeof data == "string") buf.append(new Buffer(data, enc));
else if (data) buf.append(data);
}
| Return statusCode 0 if request was aborted | Return statusCode 0 if request was aborted
| JavaScript | mit | kapouer/express-buffer-response | ---
+++
@@ -17,7 +17,13 @@
res.write = write;
res.end = end;
var len = parseInt(res.get('Content-Length'));
- if (!isNaN(len)) buf = buf.slice(0, len);
+ if (!isNaN(len)) {
+ buf = buf.slice(0, len);
+ }
+ if (!err && res.req.connection.destroyed) {
+ res.statusCode = 0;
+ buf = null;
+ }
cb(err, buf);
});
}; |
092c6b70b8ac25351df941bd2099549541c42976 | website/app/application/core/projects/project/files/file-edit-controller.js | website/app/application/core/projects/project/files/file-edit-controller.js | (function (module) {
module.controller("FileEditController", FileEditController);
FileEditController.$inject = ['file', '$scope'];
/* @ngInject */
function FileEditController(file, $scope) {
console.log('FileEditController');
var ctrl = this;
ctrl.file = file;
$scope.$on('$viewContentLoaded', function(event) {
console.log('$viewContentLoaded', event);
});
}
}(angular.module('materialscommons'))); | (function (module) {
module.controller("FileEditController", FileEditController);
FileEditController.$inject = ['file'];
/* @ngInject */
function FileEditController(file) {
var ctrl = this;
ctrl.file = file;
}
}(angular.module('materialscommons'))); | Remove debug of ui router state changes. | Remove debug of ui router state changes.
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -1,16 +1,11 @@
(function (module) {
module.controller("FileEditController", FileEditController);
- FileEditController.$inject = ['file', '$scope'];
+ FileEditController.$inject = ['file'];
/* @ngInject */
- function FileEditController(file, $scope) {
- console.log('FileEditController');
+ function FileEditController(file) {
var ctrl = this;
ctrl.file = file;
-
- $scope.$on('$viewContentLoaded', function(event) {
- console.log('$viewContentLoaded', event);
- });
}
}(angular.module('materialscommons'))); |
823928a2015e373e0bc4c4628182517f48a5ca11 | client/src/components/TextEditor.js | client/src/components/TextEditor.js | import React, {Component} from 'react'
import AlloyEditor from 'alloyeditor/dist/alloy-editor/alloy-editor-no-react'
import 'alloyeditor/dist/alloy-editor/assets/alloy-editor-atlas.css'
AlloyEditor.Selections[3].buttons.splice(4, 2)
const ALLOY_CONFIG = {
toolbars: {
styles: { selections: AlloyEditor.Selections },
add: { buttons: ['ul', 'ol', 'hline', 'table'] },
}
}
export default class TextEditor extends Component {
componentWillUnmount() {
this.editor && this.editor.destroy()
}
componentWillReceiveProps(newProps) {
if (newProps.value != this.container.innerHTML) {
this.container.innerHTML = newProps.value
}
if (newProps.value && !this.editor) {
this.editor = AlloyEditor.editable(this.container, ALLOY_CONFIG)
this.editor.get('nativeEditor').on('change', () => {
this.props.onChange(this.container.innerHTML)
})
}
}
render() {
return <div className="text-editor" ref={(el) => { this.container = el }} />
}
}
| import React, {Component} from 'react'
import AlloyEditor from 'alloyeditor/dist/alloy-editor/alloy-editor-no-react'
import 'alloyeditor/dist/alloy-editor/assets/alloy-editor-atlas.css'
// this just removes a number of features we don't want from the Alloy toolbar
AlloyEditor.Selections[3].buttons.splice(4, 2)
const ALLOY_CONFIG = {
toolbars: {
styles: { selections: AlloyEditor.Selections },
add: { buttons: ['ul', 'ol', 'hline', 'table'] },
}
}
export default class TextEditor extends Component {
componentDidMount() {
if (!this.editor) {
this.editor = AlloyEditor.editable(this.container, ALLOY_CONFIG)
this.nativeEditor = this.editor.get('nativeEditor')
this.nativeEditor.on('change', () => {
this.props.onChange(this.nativeEditor.getData())
})
}
this.componentWillReceiveProps(this.props)
}
componentWillUnmount() {
this.editor && this.editor.destroy()
}
componentWillReceiveProps(newProps) {
let html = newProps.value
if (html !== this.nativeEditor.getData()) {
this.nativeEditor.setData(html)
}
}
render() {
return <div className="text-editor" ref={(el) => { this.container = el }} />
}
}
| Make Alloy initialization work on blank and existing values | Make Alloy initialization work on blank and existing values
| JavaScript | mit | NCI-Agency/anet,NCI-Agency/anet,NCI-Agency/anet,NCI-Agency/anet,NCI-Agency/anet | ---
+++
@@ -3,6 +3,7 @@
import AlloyEditor from 'alloyeditor/dist/alloy-editor/alloy-editor-no-react'
import 'alloyeditor/dist/alloy-editor/assets/alloy-editor-atlas.css'
+// this just removes a number of features we don't want from the Alloy toolbar
AlloyEditor.Selections[3].buttons.splice(4, 2)
const ALLOY_CONFIG = {
@@ -13,20 +14,27 @@
}
export default class TextEditor extends Component {
+ componentDidMount() {
+ if (!this.editor) {
+ this.editor = AlloyEditor.editable(this.container, ALLOY_CONFIG)
+ this.nativeEditor = this.editor.get('nativeEditor')
+
+ this.nativeEditor.on('change', () => {
+ this.props.onChange(this.nativeEditor.getData())
+ })
+ }
+
+ this.componentWillReceiveProps(this.props)
+ }
+
componentWillUnmount() {
this.editor && this.editor.destroy()
}
componentWillReceiveProps(newProps) {
- if (newProps.value != this.container.innerHTML) {
- this.container.innerHTML = newProps.value
- }
-
- if (newProps.value && !this.editor) {
- this.editor = AlloyEditor.editable(this.container, ALLOY_CONFIG)
- this.editor.get('nativeEditor').on('change', () => {
- this.props.onChange(this.container.innerHTML)
- })
+ let html = newProps.value
+ if (html !== this.nativeEditor.getData()) {
+ this.nativeEditor.setData(html)
}
}
|
ffe085496a8b2b4663740593ba7eb04d8cabe458 | public/javascripts/eag_home/app.js | public/javascripts/eag_home/app.js | var app = angular.module("EAG_Home", ["Controllers"]);
| var app = angular.module("EAG_Home", ["Controllers"]);
app.directive('ngEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13 || event.which == 9) {
scope.$apply(function (){
scope.$eval(attrs.ngEnter);
});
if(event.which != 9)
event.preventDefault();
}
});
};
}); | Support for enter/tab key to add new property line. | Support for enter/tab key to add new property line.
| JavaScript | mit | manthanhd/flow2-api-manager,manthanhd/flow2-api-manager | ---
+++
@@ -1 +1,15 @@
var app = angular.module("EAG_Home", ["Controllers"]);
+
+app.directive('ngEnter', function () {
+ return function (scope, element, attrs) {
+ element.bind("keydown keypress", function (event) {
+ if(event.which === 13 || event.which == 9) {
+ scope.$apply(function (){
+ scope.$eval(attrs.ngEnter);
+ });
+ if(event.which != 9)
+ event.preventDefault();
+ }
+ });
+ };
+}); |
1ae694e934965b2d02bd9e0a8c34aba18e9767fa | src/ui/providers/open.provider.js | src/ui/providers/open.provider.js | angular.module('proxtop').service('open', ['ipc', 'settings', '$state', function(ipc, settings, $state) {
const self = this;
['Anime', 'Manga'].forEach(function(name) {
const lower = name.toLowerCase();
self['open' + name] = function(id, ep, sub) {
const actualSettings = settings.get(lower);
// TODO refactor this, this looks hacky
if(actualSettings && (actualSettings.open_with === 'internal' || (lower === 'anime' && actualSettings.pass_raw_url))) {
$state.go('watch', {
id: id,
ep: ep,
sub: sub
});
} else {
ipc.send('open', lower, id, ep, sub);
}
};
});
this.openLink = function(link) {
ipc.send('open-link', link);
};
}]);
| angular.module('proxtop').service('open', ['ipc', 'settings', '$state', function(ipc, settings, $state) {
const self = this;
['Anime', 'Manga'].forEach(function(name) {
const lower = name.toLowerCase();
self['open' + name] = function(id, ep, sub) {
const actualSettings = settings.get(lower);
// TODO refactor this, this looks hacky
if(actualSettings && (actualSettings.open_with === 'internal' || (lower === 'anime' && actualSettings.open_with === 'external' && actualSettings.pass_raw_url))) {
$state.go('watch', {
id: id,
ep: ep,
sub: sub
});
} else {
ipc.send('open', lower, id, ep, sub);
}
};
});
this.openLink = function(link) {
ipc.send('open-link', link);
};
}]);
| Fix not opening watchlist entries in browser | Fix not opening watchlist entries in browser
| JavaScript | mit | kumpelblase2/proxtop,kumpelblase2/proxtop,kumpelblase2/proxtop,kumpelblase2/proxtop | ---
+++
@@ -6,7 +6,7 @@
const actualSettings = settings.get(lower);
// TODO refactor this, this looks hacky
- if(actualSettings && (actualSettings.open_with === 'internal' || (lower === 'anime' && actualSettings.pass_raw_url))) {
+ if(actualSettings && (actualSettings.open_with === 'internal' || (lower === 'anime' && actualSettings.open_with === 'external' && actualSettings.pass_raw_url))) {
$state.go('watch', {
id: id,
ep: ep, |
0a299476bd7ae926cd13f57034baaab58bdd5fe9 | test/spec/utils_spec.js | test/spec/utils_spec.js | /* global describe, it, before */
var requirejs = require("requirejs");
var assert = require("assert");
var should = require("should");
var jsdom = require('mocha-jsdom');
var skill = require('fs').readFileSync('./test/spec/links_test.json', 'utf8');
requirejs.config({
baseUrl: 'app/',
nodeRequire: require
});
describe('Utils', function () {
var Utils;
jsdom();
before(function (done) {
requirejs(['scripts/Utils'],
function (Utils_Class) {
Utils = Utils_Class;
done();
});
});
var all_skills = JSON.parse(skill);
describe('D3 Links Test', function () {
it('should return correct d3 links info', function () {
Utils.parseDepends(all_skills.skills).toString().should.equal([{source: 1, target: 0}].toString())
});
});
});
| /* global describe, it, before */
var requirejs = require("requirejs");
var assert = require("assert");
var should = require("should");
var jsdom = require('mocha-jsdom');
var skill = require('fs').readFileSync('./test/spec/links_test.json', 'utf8');
requirejs.config({
baseUrl: 'app/',
nodeRequire: require
});
describe('Utils', function () {
var Utils;
jsdom();
before(function (done) {
requirejs(['scripts/Utils'],
function (Utils_Class) {
Utils = Utils_Class;
done();
});
});
var all_skills = JSON.parse(skill);
describe('D3 Links Test', function () {
it('should return correct d3 links info', function () {
Utils.parseDepends(all_skills.skills).toString().should.equal([{source: 1, target: 0}].toString())
});
});
describe('Get Skill By id', function () {
it('should return correct skill information by id', function () {
Utils.getSkillById(all_skills.skills, 1).toString().should.equal({ id: 1, name: 'Web' }.toString())
});
});
});
| Add test for get skill by id | Add test for get skill by id
| JavaScript | mit | phodal/sherlock,Bobjoy/sherlock,Bobjoy/sherlock,ivanyang1984/sherlock,ivanyang1984/sherlock,phodal/sherlock | ---
+++
@@ -28,4 +28,9 @@
Utils.parseDepends(all_skills.skills).toString().should.equal([{source: 1, target: 0}].toString())
});
});
+ describe('Get Skill By id', function () {
+ it('should return correct skill information by id', function () {
+ Utils.getSkillById(all_skills.skills, 1).toString().should.equal({ id: 1, name: 'Web' }.toString())
+ });
+ });
}); |
e65b931e2c9be0df35103c94963ff9cbd67bead9 | static/js/homepage-map.js | static/js/homepage-map.js |
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
|
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
var myLatlng = new google.maps.LatLng(43.663277,-79.396992);
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//TODO: replace mock data with API call
var buildingList = [
{
"lat" : 43.667576,
"lng" : -79.391868,
"id" : "1",
"title" : "building1"
},
{
"lat" : 43.663991,
"lng" : -79.398580,
"id" : "2",
"title" : "building2"
},
{
"lat" : 43.651230,
"lng" : -79.409866,
"id" : "3",
"title" : "building3"
},
{
"lat" : 43.665326,
"lng" : -79.411154,
"id" : "4",
"title" : "building4"
},
{
"lat" : 43.775326,
"lng" : -79.411154,
"id" : "5",
"title" : "building5"
}
];
$.each(buildingList, function(index, value) {
var latLong = new google.maps.LatLng(value.lat, value.lng);
bounds.extend(latLong);
new google.maps.Marker({
position: latLong,
map: map,
title: value.title
});
});
map.fitBounds(bounds);
map.panToBounds(bounds);
}
| Add markers with mock data to the map on home page | Add markers with mock data to the map on home page
| JavaScript | mit | CSC301H-Fall2013/healthyhome,CSC301H-Fall2013/healthyhome | ---
+++
@@ -1,14 +1,61 @@
- google.maps.event.addDomListener(window, 'load', initialize);
+google.maps.event.addDomListener(window, 'load', initialize);
- function initialize() {
- var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
- var mapOptions = {
- zoom: 4,
- center: myLatlng,
- mapTypeId: google.maps.MapTypeId.ROADMAP
- }
+function initialize() {
- var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
+ var myLatlng = new google.maps.LatLng(43.663277,-79.396992);
+ var bounds = new google.maps.LatLngBounds();
+ var mapOptions = {
+ zoom: 13,
+ center: myLatlng,
+ mapTypeId: google.maps.MapTypeId.ROADMAP
+ }
- }
+ var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
+
+ //TODO: replace mock data with API call
+ var buildingList = [
+ {
+ "lat" : 43.667576,
+ "lng" : -79.391868,
+ "id" : "1",
+ "title" : "building1"
+ },
+ {
+ "lat" : 43.663991,
+ "lng" : -79.398580,
+ "id" : "2",
+ "title" : "building2"
+ },
+ {
+ "lat" : 43.651230,
+ "lng" : -79.409866,
+ "id" : "3",
+ "title" : "building3"
+ },
+ {
+ "lat" : 43.665326,
+ "lng" : -79.411154,
+ "id" : "4",
+ "title" : "building4"
+ },
+ {
+ "lat" : 43.775326,
+ "lng" : -79.411154,
+ "id" : "5",
+ "title" : "building5"
+ }
+ ];
+
+ $.each(buildingList, function(index, value) {
+ var latLong = new google.maps.LatLng(value.lat, value.lng);
+ bounds.extend(latLong);
+ new google.maps.Marker({
+ position: latLong,
+ map: map,
+ title: value.title
+ });
+ });
+ map.fitBounds(bounds);
+ map.panToBounds(bounds);
+} |
ac9c6dc87213afd0bb368b781db807884d6bc0eb | src/endpoints/Namespaces.js | src/endpoints/Namespaces.js | "use strict";
const RequestResults = require("../constants/RequestResults");
const Utils = require("../utils/Utils");
let _token = null;
let _requester = null;
module.exports = {
initialize: function(token, requester) {
Utils.assertValidToken(token);
Utils.assertValidRequester(requester);
_token = token;
_requester = requester;
},
query: function(projectId, callback, opts = {}) {
Utils.assertValidToken(_token);
let endpoint = "/namespaces/";
const context = {
projectId: projectId,
options: opts
};
const req = _requester.getRequest(URL, _token);
if (opts.name) {
req.query({name: opts.name});
} else if (opts.namespaceID) {
endpoint = endpoint + opts.namespaceID;
}
const URL = _requester.getFullEndpoint(endpoint);
const bodyHandler = function(resp, body, status) {
if (status === RequestResults.SUCCESS) {
resp.body = body;
} else if (body && body.errors) {
resp.error = body.errors[0].message;
}
};
const innerCb = Utils.createInnerCb(callback, context, bodyHandler);
_requester.execute(req, innerCb);
}
};
| "use strict";
const RequestResults = require("../constants/RequestResults");
const Utils = require("../utils/Utils");
let _token = null;
let _requester = null;
module.exports = {
initialize: function(token, requester) {
Utils.assertValidToken(token);
Utils.assertValidRequester(requester);
_token = token;
_requester = requester;
},
query: function(projectId, callback, opts = {}) {
Utils.assertValidToken(_token);
let endpoint = "/namespaces/";
const context = {
projectId: projectId,
options: opts
};
const URL = _requester.getFullEndpoint(endpoint);
const req = _requester.getRequest(URL, _token);
if (opts.name) {
req.query({name: opts.name});
} else if (opts.namespaceID) {
endpoint = endpoint + opts.namespaceID;
}
const bodyHandler = function(resp, body, status) {
if (status === RequestResults.SUCCESS) {
resp.body = body;
} else if (body && body.errors) {
resp.error = body.errors[0].message;
}
};
const innerCb = Utils.createInnerCb(callback, context, bodyHandler);
_requester.execute(req, innerCb);
}
};
| Fix location of URL definition | Fix location of URL definition
| JavaScript | apache-2.0 | iobeam/iobeam-client-node | ---
+++
@@ -21,6 +21,7 @@
projectId: projectId,
options: opts
};
+ const URL = _requester.getFullEndpoint(endpoint);
const req = _requester.getRequest(URL, _token);
if (opts.name) {
@@ -28,7 +29,6 @@
} else if (opts.namespaceID) {
endpoint = endpoint + opts.namespaceID;
}
- const URL = _requester.getFullEndpoint(endpoint);
const bodyHandler = function(resp, body, status) {
if (status === RequestResults.SUCCESS) { |
860e2e10ba8d66ddd79a4c6005758c3ceeabc1e8 | rules/plugins/html.js | rules/plugins/html.js | // Rules from eslint-plugin-html
module.exports = {
"plugins": ["html"],
"settings": {
"html": {
// "html-extensions": [],
// "xml-extensions": [],
"indent": "+4",
"report-bad-indent": 1
// "javascript-mime-types": []
}
}
};
| // Rules from eslint-plugin-html
module.exports = {
"plugins": ["html"],
"settings": {
// Consider files ending with these extensions as HTML
// "html/html-extensions": [],
// Consider files ending with these extensions as XML
// "html/xml-extensions": [],
// Ensure that every script tags follow an uniform indentation
"html/indent": "+4",
// By default, this plugin won't warn if it encounters a problematic indentation, use in conjunction with the indent rule
"html/report-bad-indent": 1
// Customize the types that should be considered as JavaScript by providing one or multiple MIME types. If a MIME type starts with a /, it will be considered as RegExp
// "html/javascript-mime-types": []
}
};
| Add doc comments for HTML rules | Add doc comments for HTML rules
| JavaScript | mit | TrebleFM/eslint-config | ---
+++
@@ -2,12 +2,15 @@
module.exports = {
"plugins": ["html"],
"settings": {
- "html": {
- // "html-extensions": [],
- // "xml-extensions": [],
- "indent": "+4",
- "report-bad-indent": 1
- // "javascript-mime-types": []
- }
+ // Consider files ending with these extensions as HTML
+ // "html/html-extensions": [],
+ // Consider files ending with these extensions as XML
+ // "html/xml-extensions": [],
+ // Ensure that every script tags follow an uniform indentation
+ "html/indent": "+4",
+ // By default, this plugin won't warn if it encounters a problematic indentation, use in conjunction with the indent rule
+ "html/report-bad-indent": 1
+ // Customize the types that should be considered as JavaScript by providing one or multiple MIME types. If a MIME type starts with a /, it will be considered as RegExp
+ // "html/javascript-mime-types": []
}
}; |
f8c0d43c341c3bdf2f9664c162bb1375354e2e4d | js/src/forum/pages/labels/recipientLabel.js | js/src/forum/pages/labels/recipientLabel.js | import extract from 'flarum/common/utils/extract';
import username from 'flarum/common/helpers/username';
import User from 'flarum/common/models/User';
import Group from 'flarum/common/models/Group';
import LinkButton from 'flarum/common/components/LinkButton';
export default function recipientLabel(recipient, attrs = {}) {
attrs.style = attrs.style || {};
attrs.className = 'RecipientLabel ' + (attrs.className || '');
attrs.href = extract(attrs, 'link');
let label;
if (recipient instanceof User) {
label = username(recipient);
if (attrs.href) {
attrs.title = recipient.username() || '';
attrs.href = app.route.user(recipient);
}
} else if (recipient instanceof Group) {
label = recipient.namePlural();
} else {
attrs.className += ' none';
label = app.translator.trans('fof-byobu.forum.labels.user_deleted');
}
return LinkButton.component(attrs, label);
}
| import extract from 'flarum/common/utils/extract';
import username from 'flarum/common/helpers/username';
import User from 'flarum/common/models/User';
import Group from 'flarum/common/models/Group';
import LinkButton from 'flarum/common/components/LinkButton';
export default function recipientLabel(recipient, attrs = {}) {
attrs.style = attrs.style || {};
attrs.className = 'RecipientLabel ' + (attrs.className || '');
attrs.href = extract(attrs, 'link');
let label;
if (recipient instanceof User) {
label = username(recipient);
if (attrs.href) {
attrs.title = recipient.username() || '';
attrs.href = app.route.user(recipient);
}
} else if (recipient instanceof Group) {
return <span class={attrs.className}>{recipient.namePlural()}</span>
} else {
attrs.className += ' none';
label = app.translator.trans('fof-byobu.forum.labels.user_deleted');
}
return LinkButton.component(attrs, label);
}
| Address group recipient link issue | Address group recipient link issue
| JavaScript | mit | flagrow/byobu,flagrow/byobu | ---
+++
@@ -19,7 +19,7 @@
attrs.href = app.route.user(recipient);
}
} else if (recipient instanceof Group) {
- label = recipient.namePlural();
+ return <span class={attrs.className}>{recipient.namePlural()}</span>
} else {
attrs.className += ' none';
label = app.translator.trans('fof-byobu.forum.labels.user_deleted'); |
3220c99552f868ed37b3e809c645bac6482e6fdc | client/templates/posts/posts_list.js | client/templates/posts/posts_list.js | Template.postsList.helpers({
posts: function() {
return Posts.find();
}
}); | Template.postsList.helpers({
posts: function() {
return Posts.find({}, {sort: {submitted: -1}});
}
}); | Sort posts by submitted timestamp. | Sort posts by submitted timestamp.
chapter7-8
| JavaScript | mit | mangeshnanoti/Microscope,svalaer/immersive-microscope,forrestbe/Microscope,parkeasz/Microscope,Ian-Oliver/Microscope,bjedrzejewski/Microscope,oivvio/Microscope,nsuh/Microscope,finnbuster/meteor_microscope,Antoine-C/microscope,surfer77/microscope,dmc2015/microscope-compare,bjedrzejewski/Microscope,Jiantastic/Microscope,svalaer/immersive-microscope,exsodus3249/Microscope,oivvio/Microscope,finnbuster/meteor_microscope,Antoine-C/microscope,surfer77/microscope,tjbo/Microscope,dmc2015/microscope-compare,tjbo/Microscope,benjahmin/Microscope,fuzzybabybunny/microscope-orionjs,nickbasile/Microscope-1,chenfay/Microscope,tsongas/Microscope,svalaer/Microscope,exsodus3249/Microscope,jedrus07/Microscope,Ian-Oliver/Microscope,lucyyu24/Microscope,forrestbe/Microscope,lucyyu24/Microscope,tsongas/Microscope,Jiantastic/Microscope,chenfay/Microscope,RoystonS/microscope,mangeshnanoti/Microscope,nicolaslopezj/microscope-orionjs,nicolaslopezj/microscope-orionjs,dmc2015/Microscope-1,RoystonS/microscope,cooloney/Microscope,cooloney/Microscope,jedrus07/Microscope,zdd910/Microscope,zdd910/Microscope,dmc2015/Microscope-1,nickbasile/Microscope-1,fuzzybabybunny/microscope-orionjs,benjahmin/Microscope,svalaer/Microscope,nsuh/Microscope,parkeasz/Microscope | ---
+++
@@ -1,5 +1,5 @@
Template.postsList.helpers({
posts: function() {
- return Posts.find();
+ return Posts.find({}, {sort: {submitted: -1}});
}
}); |
6c25da5552413ad22ef64d5f2cd38d6f8aa1abd2 | client/src/pi.js | client/src/pi.js |
/**
* Load all external dependencies
* We use var so it's global available : ) ( not let,const)
*/
var fs = require('fs');
var _ = require('lodash');
/**
* Load all internal dependencies
*/
const cfg = require('../config.js');
var pkg = require('../package.json');
var piJS = require('./modules/pi-js-module');
let pi = new piJS(cfg);
var io = require('socket.io')(9090);
io.on('connection', function(socket) {
console.info('socket connected. (' + socket.id + ')');
socket.on('forward', function() {
pi.handleAnswer('move forward');
socket.emit('forward');
console.info('forward');
});
socket.on('backward', function() {
pi.handleAnswer('move backward');
socket.emit('backward');
console.info('backward');
});
socket.on('left', function() {
pi.handleAnswer('move left');
socket.emit('left');
console.info('left');
});
socket.on('right', function() {
pi.handleAnswer('move right');
socket.emit('right');
console.info('right');
});
socket.on('stop', function() {
pi.handleAnswer('move stop');
socket.emit('stop');
console.info('stop');
});
});
|
/**
* Load all external dependencies
* We use var so it's global available : ) ( not let,const)
*/
var fs = require('fs');
var _ = require('lodash');
/**
* Load all internal dependencies
*/
const cfg = require('../config.js');
var pkg = require('../package.json');
var piJS = require('./modules/pi-js-module');
let pi = new piJS(cfg);
var io = require('socket.io')(9090);
io.on('connection', function(socket) {
console.info('socket connected. (' + socket.id + ')');
socket.on('forward', function() {
pi.handleAnswer('move forward');
socket.emit('forward');
console.info('forward');
});
socket.on('backward', function() {
pi.handleAnswer('move backward');
socket.emit('backward');
console.info('backward');
});
socket.on('left', function() {
pi.handleAnswer('move left');
socket.emit('left');
console.info('left');
});
socket.on('right', function() {
pi.handleAnswer('move right');
socket.emit('right');
console.info('right');
});
socket.on('stop', function() {
pi.handleAnswer('stop');
socket.emit('stop');
console.info('stop');
});
});
| Stop is not called "move stop". Woops. | Stop is not called "move stop". Woops.
| JavaScript | mit | Windmolders/piJS,Windmolders/piJS | ---
+++
@@ -47,7 +47,7 @@
});
socket.on('stop', function() {
- pi.handleAnswer('move stop');
+ pi.handleAnswer('stop');
socket.emit('stop');
console.info('stop');
}); |
7e2f1110699d07c796bd2b63704fecce5ca7f053 | index.js | index.js | var fs = require('fs');
var path = require('path');
var xec = require('xbmc-event-client');
var keyboard = require('./lib/keyboard');
var kodikeys = function(opt) {
var defaults = {
port: 9777
}
opt = Object.assign({}, defaults, opt);
var kodi = new xec.XBMCEventClient('kodikeys', opt)
kodi.connect(function(errors, bytes) {
if (errors.length) {
console.error(`Connection failed to Kodi on $(opt.host), port ${opt.port}`)
console.error(errors[0].toString());
process.exit(1);
}
// init keyboard interactivity
keyboard.init(kodi);
console.log(`connected to ${opt.host} port ${opt.port}`);
});
}
module.exports = kodikeys;
| var fs = require('fs');
var path = require('path');
var xec = require('xbmc-event-client');
var keyboard = require('./lib/keyboard');
var kodikeys = function(opt) {
var defaults = {
port: 9777
}
opt = Object.assign({}, defaults, opt);
var kodi = new xec.XBMCEventClient('kodikeys', opt)
kodi.connect(function(errors, bytes) {
if (errors.length) {
console.error(`Connection failed to Kodi on $(opt.host), port ${opt.port}`)
console.error(errors[0].toString());
process.exit(1);
}
// init keyboard interactivity
keyboard.init(kodi);
// ping to keep connection alive
setInterval(kodi.ping.bind(kodi), 55 * 1000);
console.log(`connected to ${opt.host} port ${opt.port}`);
});
}
module.exports = kodikeys;
| Add ping to keep connection alive | Add ping to keep connection alive
| JavaScript | mit | bartels/kodikeys | ---
+++
@@ -24,6 +24,9 @@
// init keyboard interactivity
keyboard.init(kodi);
+ // ping to keep connection alive
+ setInterval(kodi.ping.bind(kodi), 55 * 1000);
+
console.log(`connected to ${opt.host} port ${opt.port}`);
});
} |
2cf4de63acf4d04d81ffda59864fb094c7b06e68 | index.js | index.js | 'use strict'
const ExtDate = require('./src/date')
const Bitmask = require('./src/bitmask')
const { parse } = require('./src/parser')
const types = [
'Date', 'Year', 'Season', 'Interval', 'Set', 'List', 'Century', 'Decade'
]
function edtf(...args) {
const res = parse(...args)
return new ExtDate(res)
//return new this[res.type](res)
}
module.exports = Object.assign(edtf, {
Date: ExtDate,
Bitmask,
parse,
types
})
| 'use strict'
const ExtDate = require('./src/date')
const Bitmask = require('./src/bitmask')
const { parse } = require('./src/parser')
const types = [
'Date', 'Year', 'Season', 'Interval', 'Set', 'List', 'Century', 'Decade'
]
function edtf(...args) {
if (!args.length) return new ExtDate()
const res = parse(...args)
return new ExtDate(res)
//return new this[res.type](res)
}
module.exports = Object.assign(edtf, {
Date: ExtDate,
Bitmask,
parse,
types
})
| Return new date by default | Return new date by default
| JavaScript | bsd-2-clause | inukshuk/edtf.js | ---
+++
@@ -10,6 +10,8 @@
]
function edtf(...args) {
+ if (!args.length) return new ExtDate()
+
const res = parse(...args)
return new ExtDate(res)
//return new this[res.type](res) |
1321057d416297a63447381fdfa9fdd4e1701300 | index.js | index.js | 'use strict';
/**
* Dependencies.
*/
var phonetics;
phonetics = require('double-metaphone');
/**
* Define `doubleMetaphone`.
*/
function doubleMetaphone() {}
/**
* Change handler.
*
* @this {WordNode}
*/
function onchange() {
var data,
value;
data = this.data;
value = this.toString();
data.phonetics = value ? phonetics(value) : null;
if ('stem' in data) {
data.stemmedPhonetics = value ? phonetics(data.stem) : null;
}
}
/**
* Define `attach`.
*
* @param {Retext} retext
*/
function attach(retext) {
var WordNode = retext.TextOM.WordNode;
WordNode.on('changetextinside', onchange);
WordNode.on('removeinside', onchange);
WordNode.on('insertinside', onchange);
}
/**
* Expose `attach`.
*/
doubleMetaphone.attach = attach;
/**
* Expose `doubleMetaphone`.
*/
module.exports = doubleMetaphone;
| 'use strict';
/**
* Dependencies.
*/
var phonetics;
phonetics = require('double-metaphone');
/**
* Change handler.
*
* @this {WordNode}
*/
function onchange() {
var data,
value;
data = this.data;
value = this.toString();
data.phonetics = value ? phonetics(value) : null;
if ('stem' in data) {
data.stemmedPhonetics = value ? phonetics(data.stem) : null;
}
}
/**
* Define `doubleMetaphone`.
*
* @param {Retext} retext
*/
function doubleMetaphone(retext) {
var WordNode = retext.TextOM.WordNode;
WordNode.on('changetextinside', onchange);
WordNode.on('removeinside', onchange);
WordNode.on('insertinside', onchange);
}
/**
* Expose `doubleMetaphone`.
*/
module.exports = doubleMetaphone;
| Refactor for changes in retext | Refactor for changes in retext
| JavaScript | mit | wooorm/retext-double-metaphone | ---
+++
@@ -7,12 +7,6 @@
var phonetics;
phonetics = require('double-metaphone');
-
-/**
- * Define `doubleMetaphone`.
- */
-
-function doubleMetaphone() {}
/**
* Change handler.
@@ -35,12 +29,12 @@
}
/**
- * Define `attach`.
+ * Define `doubleMetaphone`.
*
* @param {Retext} retext
*/
-function attach(retext) {
+function doubleMetaphone(retext) {
var WordNode = retext.TextOM.WordNode;
WordNode.on('changetextinside', onchange);
@@ -49,12 +43,6 @@
}
/**
- * Expose `attach`.
- */
-
-doubleMetaphone.attach = attach;
-
-/**
* Expose `doubleMetaphone`.
*/
|
5452f6291db4e49247b364bd50baa8dfd9f80309 | index.js | index.js | var actionpack = {
Action: require('./lib/action'),
Route: require('./lib/route')
};
module.exports = actionpack; | var actionpack = {
Action: require(__dirname + '/lib/action'),
Route: require(__dirname + '/lib/route')
};
module.exports = actionpack; | Fix lib file reference in main actionpack file | Fix lib file reference in main actionpack file
| JavaScript | mit | alexparker/actionpack | ---
+++
@@ -1,6 +1,6 @@
var actionpack = {
- Action: require('./lib/action'),
- Route: require('./lib/route')
+ Action: require(__dirname + '/lib/action'),
+ Route: require(__dirname + '/lib/route')
};
module.exports = actionpack; |
21cb52e63c4017fc4b2406705ea492d083c7b670 | index.js | index.js | 'use strict'
var toArray = require('stream-to-array')
var Promise = require('bluebird')
module.exports = streamToPromise
function streamToPromise (stream) {
if (stream.readable) return fromReadable(stream)
if (stream.writable) return fromWritable(stream)
return Promise.resolve()
}
function fromReadable (stream) {
var promise = toArray(stream)
// Ensure stream is in flowing mode
stream.resume()
return promise
.then(function concat (parts) {
return Buffer.concat(parts.map(bufferize))
})
}
function fromWritable (stream) {
return new Promise(function (resolve, reject) {
stream.once('finish', resolve)
stream.once('error', reject)
})
}
function bufferize (chunk) {
return Buffer.isBuffer(chunk) ? chunk : new Buffer(chunk)
}
| 'use strict'
var toArray = require('stream-to-array')
var Promise = require('bluebird')
module.exports = streamToPromise
function streamToPromise (stream) {
if (stream.readable) return fromReadable(stream)
if (stream.writable) return fromWritable(stream)
return Promise.resolve()
}
function fromReadable (stream) {
var promise = toArray(stream)
// Ensure stream is in flowing mode
if (stream.resume) stream.resume()
return promise
.then(function concat (parts) {
return Buffer.concat(parts.map(bufferize))
})
}
function fromWritable (stream) {
return new Promise(function (resolve, reject) {
stream.once('finish', resolve)
stream.once('error', reject)
})
}
function bufferize (chunk) {
return Buffer.isBuffer(chunk) ? chunk : new Buffer(chunk)
}
| Handle streams without a resume method | Handle streams without a resume method
Closes #9
| JavaScript | mit | bendrucker/stream-to-promise | ---
+++
@@ -15,7 +15,7 @@
var promise = toArray(stream)
// Ensure stream is in flowing mode
- stream.resume()
+ if (stream.resume) stream.resume()
return promise
.then(function concat (parts) { |
c21124fc272b9ac469f8994da000ebda9d3e9b1b | index.js | index.js | var path = require('path'),
fs = require('fs');
function AssetManifestPlugin(output, keyRoot) {
this.output = output;
this.keyRoot = keyRoot;
}
AssetManifestPlugin.prototype.apply = function(compiler) {
var assets = {},
output = this.output,
keyRoot = this.keyRoot;
var outputPath = compiler.options.output.path,
publicPath = compiler.options.output.publicPath;
function publicRelative(url) {
return path.join(publicPath, url.replace(outputPath, ''));
}
function removeLeadSlash(path) {
if(path[0] === '/') {
return path.slice(1);
}
return path;
}
function formatKey(path) {
var keyRootPath = path.replace(keyRoot, '');
return removeLeadSlash(keyRootPath);
}
compiler.plugin('compilation', function(compilation) {
compilation.plugin('module-asset', function(module, file) {
assets[formatKey(module.userRequest)] = publicRelative(file);
});
});
compiler.plugin('done', function() {
fs.writeFileSync(output, JSON.stringify(assets, null, 2));
});
};
module.exports = AssetManifestPlugin;
| var path = require('path'),
fs = require('fs');
function AssetManifestPlugin(output) {
this.output = output;
}
AssetManifestPlugin.prototype.apply = function(compiler) {
var assets = {},
output = this.output;
var outputPath = compiler.options.output.path,
publicPath = compiler.options.output.publicPath;
function publicRelative(url) {
return path.join(publicPath, url.replace(outputPath, ''));
}
function keyForModule(module) {
return Object.keys(module.assets)[0];
}
compiler.plugin('compilation', function(compilation) {
compilation.plugin('module-asset', function(module, file) {
assets[keyForModule(module)] = publicRelative(file);
});
});
compiler.plugin('done', function() {
fs.writeFileSync(output, JSON.stringify(assets, null, 2));
});
};
module.exports = AssetManifestPlugin;
| Use Assets key as Manifest Key Instead | Use Assets key as Manifest Key Instead
| JavaScript | mit | rentpath/webpack-asset-manifest | ---
+++
@@ -1,15 +1,13 @@
var path = require('path'),
fs = require('fs');
-function AssetManifestPlugin(output, keyRoot) {
+function AssetManifestPlugin(output) {
this.output = output;
- this.keyRoot = keyRoot;
}
AssetManifestPlugin.prototype.apply = function(compiler) {
var assets = {},
- output = this.output,
- keyRoot = this.keyRoot;
+ output = this.output;
var outputPath = compiler.options.output.path,
publicPath = compiler.options.output.publicPath;
@@ -18,22 +16,13 @@
return path.join(publicPath, url.replace(outputPath, ''));
}
- function removeLeadSlash(path) {
- if(path[0] === '/') {
- return path.slice(1);
- }
-
- return path;
- }
-
- function formatKey(path) {
- var keyRootPath = path.replace(keyRoot, '');
- return removeLeadSlash(keyRootPath);
+ function keyForModule(module) {
+ return Object.keys(module.assets)[0];
}
compiler.plugin('compilation', function(compilation) {
compilation.plugin('module-asset', function(module, file) {
- assets[formatKey(module.userRequest)] = publicRelative(file);
+ assets[keyForModule(module)] = publicRelative(file);
});
});
|
2951f66c823a5c9104ac93e17b3635461f9cf8e4 | index.js | index.js | /*!
* docdown v0.3.0
* Copyright 2011-2016 John-David Dalton <http://allyoucanleet.com/>
* Available under MIT license <http://mths.be/mit>
*/
'use strict';
var _ = require('lodash'),
fs = require('fs'),
path = require('path'),
generator = require('./lib/generator.js');
/**
* Generates Markdown documentation based on JSDoc comments.
*
* @name docdown
* @param options The options to use to generate documentation.
* @returns {string} The generated Markdown code.
*/
function docdown(options) {
options = _.defaults(options, {
'hash': 'default',
'lang': 'js',
'sort': true,
'title': path.basename(options.path) + ' API documentation',
'toc': 'properties'
});
if (!options.path || !options.url) {
throw new Error('Path and URL must be specified');
}
return generator(fs.readFileSync(options.path, 'utf8'), options);
}
module.exports = docdown;
| /*!
* docdown v0.3.0
* Copyright 2011-2016 John-David Dalton <http://allyoucanleet.com/>
* Available under MIT license <https://mths.be/mit>
*/
'use strict';
var _ = require('lodash'),
fs = require('fs'),
path = require('path'),
generator = require('./lib/generator.js');
/**
* Generates Markdown documentation based on JSDoc comments.
*
* @name docdown
* @param options The options to use to generate documentation.
* @returns {string} The generated Markdown code.
*/
function docdown(options) {
options = _.defaults(options, {
'hash': 'default',
'lang': 'js',
'sort': true,
'title': path.basename(options.path) + ' API documentation',
'toc': 'properties'
});
if (!options.path || !options.url) {
throw new Error('Path and URL must be specified');
}
return generator(fs.readFileSync(options.path, 'utf8'), options);
}
module.exports = docdown;
| Use https for license link. | Use https for license link.
| JavaScript | mit | jdalton/docdown,DannyNemer/docdown | ---
+++
@@ -1,7 +1,7 @@
/*!
* docdown v0.3.0
* Copyright 2011-2016 John-David Dalton <http://allyoucanleet.com/>
- * Available under MIT license <http://mths.be/mit>
+ * Available under MIT license <https://mths.be/mit>
*/
'use strict';
|
229a4a770a3d6675355584449da0c9dec86a215d | index.js | index.js | 'use strict';
/**
* @description
* A tool that downloads a given number of pug images to the directory where it is run.
*
* @example
* node pugbalm 5 // download 5 pugs
*/
var request = require('request'),
_ = require('lodash'),
apiKey = 'dc6zaTOxFJmzC',
params;
/*
* @jsdoc function
* @name serializeParams
* @param {object}
* Object containing request parameters.
* @returns {string}
* Accepts a params object and returns a serialized string to be appended to a base URL.
*/
params = {
q: 'pugs',
api_key: apiKey,
};
function serializeParams(params) {
return _.reduce(params, function(result, n, key) {
return result + key + n;
},'');
}
console.log(serializeParams(params));
| 'use strict';
/**
* @description
* A tool that downloads a given number of pug images to the directory where it is run.
*
* @example
* node pugbalm 5 // download 5 pugs
*/
var request = require('request'),
_ = require('lodash'),
baseUrl = 'http://api.giphy.com/v1/gifs/search',
apiKey = 'dc6zaTOxFJmzC',
params;
/*
* @jsdoc function
* @name serializeParams
* @param {object}
* Object containing request parameters.
* @returns {string}
* Accepts a params object and returns a serialized string to be appended to a base URL.
*/
params = {
q: 'pugs',
api_key: apiKey,
};
function serializeParams(params) {
var first = true;
return _.reduce(params, function(result, n, key) {
if (first) {
first = false;
return result + '?' + key + '=' + n;
} else {
return result + '&' + key + '=' + n;
}
},'');
}
request(baseUrl + serializeParams(params), function(error, response, body) {
if (!error && response.statusCode === 200) {
debugger;
}
});
| Use request library to hit the giphy api, passing serialized params object. | Use request library to hit the giphy api, passing serialized params object.
| JavaScript | mit | wbprice/pugbalm | ---
+++
@@ -10,6 +10,7 @@
var request = require('request'),
_ = require('lodash'),
+ baseUrl = 'http://api.giphy.com/v1/gifs/search',
apiKey = 'dc6zaTOxFJmzC',
params;
@@ -29,12 +30,26 @@
function serializeParams(params) {
+ var first = true;
+
return _.reduce(params, function(result, n, key) {
- return result + key + n;
+ if (first) {
+ first = false;
+ return result + '?' + key + '=' + n;
+ } else {
+ return result + '&' + key + '=' + n;
+ }
},'');
}
-console.log(serializeParams(params));
+request(baseUrl + serializeParams(params), function(error, response, body) {
+
+ if (!error && response.statusCode === 200) {
+
+ debugger;
+
+ }
+}); |
0809ccb437162bb2eaf761107d24f7f46022ae36 | index.js | index.js | 'use strict'
const markdownIt = require('markdown-it')
exports.name = 'markdown-it'
exports.outputFormat = 'html'
exports.inputFormats = ['markdown-it', 'markdown', 'md']
exports.render = function (str, options) {
options = Object.assign({}, options || {})
// Copy render rules from options, and remove them from options, since
// they're invalid.
var renderRules = Object.assign({}, options.renderRules || {})
delete options.renderRules
var md = markdownIt(options)
// Enable render rules.
Object.assign(md.renderer.rules, renderRules);
// Parse the plugins.
(options.plugins || []).forEach(plugin => {
if (!Array.isArray(plugin)) {
plugin = [plugin]
}
if (typeof plugin[0] === 'string') {
// eslint-disable-next-line import/no-dynamic-require
plugin[0] = require(plugin[0])
}
md.use.apply(md, plugin)
});
// Parse enable/disable rules.
(options.enable || []).forEach(rule => {
md.enable.apply(md, Array.isArray(rule) ? rule : [rule])
});
(options.disable || []).forEach(rule => {
md.disable.apply(md, Array.isArray(rule) ? rule : [rule])
})
// Render the markdown.
if (options.inline) {
return md.renderInline(str)
}
return md.render(str)
}
| 'use strict'
const markdownIt = require('markdown-it')
exports.name = 'markdown-it'
exports.outputFormat = 'html'
exports.inputFormats = ['markdown-it', 'markdown', 'md']
exports.render = function (str, options) {
options = Object.assign({}, options || {})
// Copy render rules from options, and remove them from options, since
// they're invalid.
let renderRules = Object.assign({}, options.renderRules || {})
delete options.renderRules
const md = markdownIt(options)
// Enable render rules.
Object.assign(md.renderer.rules, renderRules);
// Parse the plugins.
(options.plugins || []).forEach(plugin => {
if (!Array.isArray(plugin)) {
plugin = [plugin]
}
if (typeof plugin[0] === 'string') {
// eslint-disable-next-line import/no-dynamic-require
plugin[0] = require(plugin[0])
}
md.use.apply(md, plugin)
});
// Parse enable/disable rules.
(options.enable || []).forEach(rule => {
md.enable.apply(md, Array.isArray(rule) ? rule : [rule])
});
(options.disable || []).forEach(rule => {
md.disable.apply(md, Array.isArray(rule) ? rule : [rule])
})
// Render the markdown.
if (options.inline) {
return md.renderInline(str)
}
return md.render(str)
}
| Fix unexpected var, use let or const instead | Fix unexpected var, use let or const instead | JavaScript | mit | jstransformers/jstransformer-markdown-it,jstransformers/jstransformer-markdown-it | ---
+++
@@ -11,10 +11,10 @@
// Copy render rules from options, and remove them from options, since
// they're invalid.
- var renderRules = Object.assign({}, options.renderRules || {})
+ let renderRules = Object.assign({}, options.renderRules || {})
delete options.renderRules
- var md = markdownIt(options)
+ const md = markdownIt(options)
// Enable render rules.
Object.assign(md.renderer.rules, renderRules); |
9f9ae6226b34ebbbcb2bac022c4dd7184ae4e6c9 | index.js | index.js | var path = require('path');
module.exports = class BowerResolvePlugin {
constructor(options) {
this.options = options;
}
apply(resolver) {
resolver.plugin('existing-directory', function (request, callback) {
if (request.path !== request.descriptionFileRoot) {
return callback();
}
var mainModule = null;
if (request.descriptionFilePath.endsWith('bower.json')) {
var source = request.descriptionFileData;
var modules = typeof source['main'] == 'string'
? [source['main']]
: source['main'];
mainModule = modules.find(module => { return module.endsWith('.js') });
}
if (! mainModule) {
return callback();
}
var obj = Object.assign({}, request, {
path: path.resolve(request.path, mainModule)
});
return resolver.doResolve('undescribed-raw-file', obj, 'using path: ' + mainModule, callback);
});
}
} | 'use strict';
var path = require('path');
module.exports = class BowerResolvePlugin {
constructor(options) {
this.options = options;
}
apply(resolver) {
resolver.plugin('existing-directory', function (request, callback) {
if (request.path !== request.descriptionFileRoot) {
return callback();
}
var mainModule = null;
if (request.descriptionFilePath.endsWith('bower.json')) {
var source = request.descriptionFileData;
var modules = typeof source['main'] == 'string'
? [source['main']]
: source['main'];
mainModule = modules.find(module => { return module.endsWith('.js') });
}
if (! mainModule) {
return callback();
}
var obj = Object.assign({}, request, {
path: path.resolve(request.path, mainModule)
});
return resolver.doResolve('undescribed-raw-file', obj, 'using path: ' + mainModule, callback);
});
}
}
| Make it work for node <= 5 | Make it work for node <= 5 | JavaScript | mit | codewizz/bower-resolve-webpack-plugin | ---
+++
@@ -1,3 +1,5 @@
+'use strict';
+
var path = require('path');
module.exports = class BowerResolvePlugin { |
8a6133d252d62d88ae65f166cd270013d093b018 | index.js | index.js | var path = require('path')
var meta = require(path.join(__dirname, 'lib', 'meta.js'))
module.exports = Dat
// new Dat(cb)
// new Dat({foo: bar})
// new Dat({foo: bar}, cb)
// new Dat('./foo)
// new Dat('./foo', cb)
// new Dat('./foo', {foo: bar})
// new Dat('./foo', {foo: bar}, cb)
function Dat(dir, opts, onReady) {
var self = this
// if 'new' was not used
if (!(this instanceof Dat)) return new Dat(dir, opts)
if (typeof dir === 'function') {
onReady = dir
opts = {}
dir = process.cwd()
}
if (typeof opts === 'function') {
onReady = opts
opts = {}
}
if (typeof dir === 'object') {
onReady = opts
opts = dir
dir = process.cwd()
}
if (!onReady) onReady = function(){}
this.dir = dir
this.opts = opts
this.meta = meta(this.dir, function(err) {
if (err) return onReady()
self._storage(opts, onReady)
})
}
Dat.prototype = require(path.join(__dirname, 'lib', 'commands'))
| var path = require('path')
var meta = require(path.join(__dirname, 'lib', 'meta.js'))
var commands = require(path.join(__dirname, 'lib', 'commands'))
module.exports = Dat
// new Dat(cb)
// new Dat({foo: bar})
// new Dat({foo: bar}, cb)
// new Dat('./foo)
// new Dat('./foo', cb)
// new Dat('./foo', {foo: bar})
// new Dat('./foo', {foo: bar}, cb)
function Dat(dir, opts, onReady) {
var self = this
// if 'new' was not used
if (!(this instanceof Dat)) return new Dat(dir, opts)
if (typeof dir === 'function') {
onReady = dir
opts = {}
dir = process.cwd()
}
if (typeof opts === 'function') {
onReady = opts
opts = {}
}
if (typeof dir === 'object') {
onReady = opts
opts = dir
dir = process.cwd()
}
if (!onReady) onReady = function(){}
this.dir = dir
this.opts = opts
this.meta = meta(this.dir, function(err) {
if (err) return onReady()
commands._ensureExists(opts, function (err) {
if (err) {
console.error(err)
process.exit(1)
}
self._storage(opts, onReady)
})
})
}
Dat.prototype = commands
| Handle case where package.json exists but not .dat | Handle case where package.json exists but not .dat
| JavaScript | bsd-3-clause | mafintosh/dat,yetone/dat,vfulco/dat,ajschumacher/dat,bmpvieira/dat,waldoj/dat,stamhe/dat,delkyd/dat,eayoungs/dat,rjsteinert/dat,RichardLitt/dat,bmpvieira/dat,FLGMwt/dat,maxogden/dat,flyingzumwalt/dat,LinusU/dat,adriagalin/dat,captainsafia/dat,mattknox/dat,jbenet/dat,jqnatividad/dat,jbenet/dat,karissa/dat,mcanthony/dat,mafintosh/dat | ---
+++
@@ -1,5 +1,6 @@
var path = require('path')
var meta = require(path.join(__dirname, 'lib', 'meta.js'))
+var commands = require(path.join(__dirname, 'lib', 'commands'))
module.exports = Dat
@@ -41,8 +42,15 @@
this.meta = meta(this.dir, function(err) {
if (err) return onReady()
- self._storage(opts, onReady)
+ commands._ensureExists(opts, function (err) {
+ if (err) {
+ console.error(err)
+ process.exit(1)
+ }
+
+ self._storage(opts, onReady)
+ })
})
}
-Dat.prototype = require(path.join(__dirname, 'lib', 'commands'))
+Dat.prototype = commands |
13db7d2de7a1c870c4fc495b37707e3d57a5293e | index.js | index.js | var models = require('./lib/models');
var config = require('./config/gateway.config');
var dirty = require('dirty');
var db = dirty(config.datasource || './data/messages.db');
var storedMessages = new models.Messages();
db.on('load', function() {
storedMessages = new models.Messages(db.get('messages') || []);
});
var Reader = module.exports.reader = {
readMessages: function (callback) {
if (storedMessages) {
callback(storedMessages);
} else {
db.on('load', function() {
storedMessages = new models.Messages(db.get('messages') || []);
callback(storedMessages);
});
}
},
registerCommand: function (command, callback) {
db.on('load', function() {
var listener = db.get("listener");
listener.push( command );
db.set("listener", listener, function listenerSaved (){
if (callback) {
callback();
}
});
});
}
};
| var models = require('./lib/models');
var config = require('./config/gateway.config');
var dirty = require('dirty');
var db = dirty(config.datasource || './data/messages.db');
var sms = require('./lib/sms');
var storedMessages = new models.Messages();
db.on('load', function() {
storedMessages = new models.Messages(db.get('messages') || []);
});
var Reader = module.exports.reader = {
readMessages: function (callback) {
if (storedMessages) {
callback(storedMessages);
} else {
db.on('load', function() {
storedMessages = new models.Messages(db.get('messages') || []);
callback(storedMessages);
});
}
},
registerCommand: function (command, callback) {
db.on('load', function() {
var listener = db.get("listener");
listener.push( command );
db.set("listener", listener, function listenerSaved (){
if (callback) {
callback();
}
});
});
}
};
var Sender = module.exports.sender = {
sendMessage: function (messageObj) {
// messageObj has attributes: to (phone number), message (text), success (callback)
sms.send({
to: messageObj.to, // Recipient Phone Number
text: messageObj.message // Text to send
}, function(err, result) {
// error message in String and result information in JSON
if (err) {
console.log(err);
}
messageObj.success(result);
});
}
};
| Add sender method to library | Add sender method to library
| JavaScript | mit | marcusbaer/node-sms | ---
+++
@@ -2,6 +2,7 @@
var config = require('./config/gateway.config');
var dirty = require('dirty');
var db = dirty(config.datasource || './data/messages.db');
+var sms = require('./lib/sms');
var storedMessages = new models.Messages();
@@ -35,3 +36,21 @@
}
};
+
+var Sender = module.exports.sender = {
+
+ sendMessage: function (messageObj) {
+ // messageObj has attributes: to (phone number), message (text), success (callback)
+ sms.send({
+ to: messageObj.to, // Recipient Phone Number
+ text: messageObj.message // Text to send
+ }, function(err, result) {
+ // error message in String and result information in JSON
+ if (err) {
+ console.log(err);
+ }
+ messageObj.success(result);
+ });
+ }
+
+}; |
edf0663395e5bb7ffd33724c4e15f6f1e86757e3 | index.js | index.js | var fs = require("fs")
var isJavascript = /\.js$/
module.exports = allFiles
function allFiles(uri, regex) {
var stat = fs.statSync(uri)
regex = regex || isJavascript
if (stat.isFile()) {
if (!regex.test(uri)) {
return []
}
return [uri]
}
var files = fs.readdirSync(uri)
return files.filter(function (uri) {
return regex.test(uri)
}).reduce(function (acc, uri) {
return acc.concat(allFiles(uri))
}, [])
}
| var fs = require("fs")
var path = require("path")
var isJavascript = /\.js$/
module.exports = allFiles
function allFiles(uri, regex) {
var stat = fs.statSync(uri)
regex = regex || isJavascript
if (stat.isFile()) {
if (!regex.test(uri)) {
return []
}
return [uri]
}
var files = fs.readdirSync(uri)
return files.filter(function (uri) {
return regex.test(uri)
}).reduce(function (acc, fileName) {
return acc.concat(allFiles(path.join(uri, fileName)))
}, [])
}
| Return full paths not file names | Return full paths not file names | JavaScript | mit | Raynos/all-files | ---
+++
@@ -1,4 +1,5 @@
var fs = require("fs")
+var path = require("path")
var isJavascript = /\.js$/
@@ -19,7 +20,7 @@
var files = fs.readdirSync(uri)
return files.filter(function (uri) {
return regex.test(uri)
- }).reduce(function (acc, uri) {
- return acc.concat(allFiles(uri))
+ }).reduce(function (acc, fileName) {
+ return acc.concat(allFiles(path.join(uri, fileName)))
}, [])
} |
0ba7ac2dcf74a9faf81ba4bbfb8385b9238e03d1 | index.js | index.js | var bodyParser = require('body-parser')
var dataUriToBuffer = require('data-uri-to-buffer')
var express = require('express')
var app = express()
/**
* This is your custom transform function
* move it wherever, call it whatever
*/
var transform = require("./transformer")
// Set up some Express settings
app.use(bodyParser.json({ limit: '1mb' }))
app.use(express.static(__dirname + '/public'))
/**
* Home route serves index.html file, and
* responds with 200 by default for revisit
*/
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html')
})
/**
* Service route is where the magic happens.
*/
app.post('/service', function(req, res) {
var imgBuff = dataUriToBuffer(req.body.content.data)
// Transform the image
var transformed = transform(imgBuff)
var dataUri = 'data:' + imgBuff.type + ';base64,' + transformed.toString('base64')
req.body.content.data = dataUri
req.body.content.type = imgBuff.type
res.json(req.body)
})
var port = 8000
app.listen(port)
console.log('server running on port: ', port)
| var nconf = require("nconf");
var bodyParser = require('body-parser')
var dataUriToBuffer = require('data-uri-to-buffer')
var express = require('express')
var app = express()
nconf.argv().env().file({ file: 'local.json'});
/**
* This is your custom transform function
* move it wherever, call it whatever
*/
var transform = require("./transformer")
// Set up some Express settings
app.use(bodyParser.json({ limit: '1mb' }))
app.use(express.static(__dirname + '/public'))
/**
* Home route serves index.html file, and
* responds with 200 by default for revisit
*/
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html')
})
/**
* Service route is where the magic happens.
*/
app.post('/service', function(req, res) {
var imgBuff = dataUriToBuffer(req.body.content.data)
// Transform the image
var transformed = transform(imgBuff)
var dataUri = 'data:' + imgBuff.type + ';base64,' + transformed.toString('base64')
req.body.content.data = dataUri
req.body.content.type = imgBuff.type
res.json(req.body)
})
var port = nconf.get("port");
app.listen(port)
console.log('server running on port: ', port)
| Adjust port to use nconf | Adjust port to use nconf
| JavaScript | mit | jasonrhodes/revisit-gifplay,revisitors/revisit.link-quickstart | ---
+++
@@ -1,7 +1,10 @@
+var nconf = require("nconf");
var bodyParser = require('body-parser')
var dataUriToBuffer = require('data-uri-to-buffer')
var express = require('express')
var app = express()
+
+nconf.argv().env().file({ file: 'local.json'});
/**
* This is your custom transform function
@@ -38,6 +41,6 @@
})
-var port = 8000
+var port = nconf.get("port");
app.listen(port)
console.log('server running on port: ', port) |
4a54f47e0ba30a18bc14acb853fe029e1adbc448 | index.js | index.js | var parseUrl = require('url').parse;
var isSecure = function(req) {
if (req.secure) {
return true;
} else if (
req.get('X-Forwarded-Proto') &&
req.get('X-Forwarded-Proto').toLowerCase &&
req.get('X-Forwarded-Proto').toLowerCase() === 'https'
) {
return true;
}
return false;
};
exports = module.exports = function(req, res, next){
if(!isSecure(req)){
if(req.method === "GET"){
var httpsPort = req.app.get('httpsPort') || 443;
var fullUrl = parseUrl('http://' + req.header('Host') + req.url);
res.redirect(301, 'https://' + fullUrl.hostname + ':' + httpsPort + req.url);
} else {
res.status(403).send('SSL Required.');
}
} else {
next();
}
};
| var parseUrl = require('url').parse;
var isSecure = function(req) {
if (req.secure) {
return true;
} else if (
req.get('X-Forwarded-Proto') &&
req.get('X-Forwarded-Proto').toLowerCase &&
req.get('X-Forwarded-Proto').toLowerCase() === 'https'
) {
return true;
}
return false;
};
exports = module.exports = function(req, res, next){
if(!isSecure(req)){
if(req.method === "GET"){
var httpsPort = req.app.get('httpsPort') || 443;
var fullUrl = parseUrl(req.protocol + '://' + req.header('Host') + req.originalUrl);
res.redirect(301, 'https://' + fullUrl.hostname + ':' + httpsPort + req.url);
} else {
res.status(403).send('SSL Required.');
}
} else {
next();
}
};
| Replace req.url with req.originalUrl to fix trim bug | Replace req.url with req.originalUrl to fix trim bug
| JavaScript | mit | fatfisz/express-force-ssl,battlejj/express-force-ssl | ---
+++
@@ -15,7 +15,7 @@
if(!isSecure(req)){
if(req.method === "GET"){
var httpsPort = req.app.get('httpsPort') || 443;
- var fullUrl = parseUrl('http://' + req.header('Host') + req.url);
+ var fullUrl = parseUrl(req.protocol + '://' + req.header('Host') + req.originalUrl);
res.redirect(301, 'https://' + fullUrl.hostname + ':' + httpsPort + req.url);
} else {
res.status(403).send('SSL Required.'); |
34d5cbdc59e187cc01d59e1da4f5d6ebfb7fbf8b | index.js | index.js | import Dexie from 'dexie'
const Promise = Dexie.Promise
export default class DexieBatch {
constructor(opts = { batchSize: 20 }) {
this.opts = opts
}
each(collection, callback) {
return this.eachBatch(collection, a => {
return Promise.all(a.map(callback))
})
}
eachBatch(collection, callback) {
const delegate = this.opts.limit ? 'eachBatchParallel' : 'eachBatchSerial'
return this[delegate](collection, callback)
}
eachBatchParallel(collection, callback) {
const batchSize = this.opts.batchSize
const batchPromises = []
for (let i = 0; i * batchSize < this.opts.limit; i++) {
const batchPromise = collection
.clone()
.offset(i * batchSize)
.limit(batchSize)
.toArray()
.then(a => callback(a, i))
batchPromises.push(batchPromise)
}
return Dexie.Promise.all(batchPromises).then(batches => batches.length)
}
eachBatchSerial(collection, callback) {
const batchSize = this.opts.batchSize
const batchPromise = collection.clone().limit(batchSize).toArray()
batchPromise.then(callback)
return batchPromise.then(batch => {
return batch.length
? this.eachBatch(collection.clone().offset(batchSize), callback)
: undefined
})
}
}
| const Promise = require('dexie').Promise
module.exports = class DexieBatch {
constructor(opts = { batchSize: 20 }) {
this.opts = opts
}
each(collection, callback) {
return this.eachBatch(collection, a => {
return Promise.all(a.map(callback))
})
}
eachBatch(collection, callback) {
const delegate = this.opts.limit ? 'eachBatchParallel' : 'eachBatchSerial'
return this[delegate](collection, callback)
}
eachBatchParallel(collection, callback) {
const batchSize = this.opts.batchSize
const batchPromises = []
for (let i = 0; i * batchSize < this.opts.limit; i++) {
const batchPromise = collection
.clone()
.offset(i * batchSize)
.limit(batchSize)
.toArray()
.then(a => callback(a, i))
batchPromises.push(batchPromise)
}
return Promise.all(batchPromises).then(batches => batches.length)
}
eachBatchSerial(collection, callback) {
const batchSize = this.opts.batchSize
const batchPromise = collection.clone().limit(batchSize).toArray()
batchPromise.then(callback)
return batchPromise.then(batch => {
return batch.length
? this.eachBatch(collection.clone().offset(batchSize), callback)
: undefined
})
}
}
| Use CommonJS module style for improved compatibility | Use CommonJS module style for improved compatibility
| JavaScript | mit | raphinesse/dexie-batch | ---
+++
@@ -1,8 +1,6 @@
-import Dexie from 'dexie'
+const Promise = require('dexie').Promise
-const Promise = Dexie.Promise
-
-export default class DexieBatch {
+module.exports = class DexieBatch {
constructor(opts = { batchSize: 20 }) {
this.opts = opts
}
@@ -31,7 +29,7 @@
.then(a => callback(a, i))
batchPromises.push(batchPromise)
}
- return Dexie.Promise.all(batchPromises).then(batches => batches.length)
+ return Promise.all(batchPromises).then(batches => batches.length)
}
eachBatchSerial(collection, callback) { |
6596ba740494d50acb87db49a7f82581461ade49 | index.js | index.js | /**
* Module dependencies
*/
var crypto = require('crypto');
/**
* The size ratio between a base64 string and the equivalent byte buffer
*/
var ratio = Math.log(64) / Math.log(256);
/**
* Generate an Unique Id
*
* @param {Number} length The number of chars of the uid
* @param {Number} cb (optional) Callback for async uid generation
* @api public
*/
function uid(length, cb) {
var numbytes = Math.ceil(length * ratio);
if (typeof cb === 'undefined') {
return crypto.randomBytes(numbytes).toString('base64').slice(0, length);
} else {
crypto.randomBytes(numbytes, function(err, bytes) {
if (err) return cb(err);
cb(null, bytes.toString('base64').slice(0, length));
})
}
}
/**
* Exports
*/
module.exports = uid;
| /**
* Module dependencies
*/
var crypto = require('crypto');
/**
* The size ratio between a base64 string and the equivalent byte buffer
*/
var ratio = Math.log(64) / Math.log(256);
/**
* Make a Base64 string ready for use in URLs
*
* @param {String}
* @returns {String}
* @api private
*/
function urlReady(str) {
return str.replace(/\+/g, '_').replace(/\//g, '-');
}
/**
* Generate an Unique Id
*
* @param {Number} length The number of chars of the uid
* @param {Number} cb (optional) Callback for async uid generation
* @api public
*/
function uid(length, cb) {
var numbytes = Math.ceil(length * ratio);
if (typeof cb === 'undefined') {
return urlReady(crypto.randomBytes(numbytes).toString('base64').slice(0, length));
} else {
crypto.randomBytes(numbytes, function(err, bytes) {
if (err) return cb(err);
cb(null, urlReady(bytes.toString('base64').slice(0, length)));
})
}
}
/**
* Exports
*/
module.exports = uid;
| Make uids valid for use in URLs | Make uids valid for use in URLs
| JavaScript | mit | coreh/uid2 | ---
+++
@@ -11,6 +11,18 @@
var ratio = Math.log(64) / Math.log(256);
/**
+ * Make a Base64 string ready for use in URLs
+ *
+ * @param {String}
+ * @returns {String}
+ * @api private
+ */
+
+function urlReady(str) {
+ return str.replace(/\+/g, '_').replace(/\//g, '-');
+}
+
+/**
* Generate an Unique Id
*
* @param {Number} length The number of chars of the uid
@@ -21,11 +33,11 @@
function uid(length, cb) {
var numbytes = Math.ceil(length * ratio);
if (typeof cb === 'undefined') {
- return crypto.randomBytes(numbytes).toString('base64').slice(0, length);
+ return urlReady(crypto.randomBytes(numbytes).toString('base64').slice(0, length));
} else {
crypto.randomBytes(numbytes, function(err, bytes) {
if (err) return cb(err);
- cb(null, bytes.toString('base64').slice(0, length));
+ cb(null, urlReady(bytes.toString('base64').slice(0, length)));
})
}
} |
791848044248b9c044e18fe034955e093cf0fb1f | index.js | index.js | const FileSystemBackend = require('./src/backend/FileSystemBackend')
const FileSystemBuffer = require('./src/backend/FileSystemBuffer')
const host = require('./src/host/singletonHost')
const util = require('./src/util')
// Various shortuct functions and variables providing a similar interface
// to the package as in other Stencila language packages
// e.g. https://github.com/stencila/r/blob/master/R/main.R
const version = require('./package').version
const install = function () {
return host.install()
}
const environ = function () {
return console.log(JSON.stringify(host.environ(), null, ' ')) // eslint-disable-line no-console
}
const start = function (address='127.0.0.1', port=2000) {
return host.start(address, port)
}
const stop = function () {
return host.stop()
}
const run = function () {
return host.run()
}
module.exports = {
FileSystemBackend,
FileSystemBuffer,
host: host,
util: util,
version: version,
install: install,
environ: environ,
start: start,
stop: stop,
run: run
}
| const FileSystemBackend = require('./src/backend/FileSystemBackend')
const FileSystemBuffer = require('./src/backend/FileSystemBuffer')
const host = require('./src/host/singletonHost')
const util = require('./src/util')
// Various shortuct functions and variables providing a similar interface
// to the package as in other Stencila language packages
// e.g. https://github.com/stencila/r/blob/master/R/main.R
const version = require('./package').version
const install = function () {
return host.install()
}
const environ = function () {
return console.log(JSON.stringify(host.environ(), null, ' ')) // eslint-disable-line no-console
}
const start = function (address='127.0.0.1', port=2000) {
return host.start(address, port)
}
const stop = function () {
return host.stop()
}
const run = function (address='127.0.0.1', port=2000) {
return host.run(address, port)
}
module.exports = {
FileSystemBackend,
FileSystemBuffer,
host: host,
util: util,
version: version,
install: install,
environ: environ,
start: start,
stop: stop,
run: run
}
| Add address and port parameters to run() | Add address and port parameters to run()
| JavaScript | apache-2.0 | stencila/node,stencila/node | ---
+++
@@ -22,8 +22,8 @@
const stop = function () {
return host.stop()
}
-const run = function () {
- return host.run()
+const run = function (address='127.0.0.1', port=2000) {
+ return host.run(address, port)
}
module.exports = { |
a622e46cfa037f77dda4d2f958fc25994ac1db1b | index.js | index.js | 'use strict';
var stylus = require('stylus'),
gutil = require('gulp-util'),
PluginError = gutil.PluginError,
log = gutil.log,
Transform = require('stream').Transform,
defaults = require('lodash.defaults'),
PLUGIN_NAME = 'gulp-stylus';
function gulpstylus(options) {
var stream = new Transform({ objectMode: true }),
opts = defaults(options, {
compress: false,
silent: false
});
stream._transform = function(file, unused, done) {
// Pass through if null
if (file.isNull()) {
stream.push(file);
done();
return;
}
if (file.isStream()) {
return done(new PluginError(PLUGIN_NAME, 'Streaming not supported'));
}
var s = stylus(file.contents.toString('utf8'))
.set('filename', file.path)
.set('compress', opts.compress);
try {
s.render(function(err, css) {
if (err) throw err;
file.path = gutil.replaceExtension(file.path, '.css');
file.contents = new Buffer(css);
stream.push(file);
done();
});
} catch(err) {
if (opts.silent) {
log(String(new PluginError(PLUGIN_NAME, err)));
return done();
}
done(new PluginError(PLUGIN_NAME, err));
}
};
return stream;
}
module.exports = gulpstylus;
| 'use strict';
var stylus = require('stylus'),
gutil = require('gulp-util'),
PluginError = gutil.PluginError,
log = gutil.log,
Transform = require('stream').Transform,
defaults = require('lodash.defaults'),
PLUGIN_NAME = 'gulp-stylus';
function formatException(e) {
return e.name+' in plugin \''+gutil.colors.cyan(PLUGIN_NAME)+'\''+': '+e.message
}
function gulpstylus(options) {
var stream = new Transform({ objectMode: true }),
opts = defaults({}, options ,{
compress: false,
silent: false
});
stream._transform = function(file, unused, done) {
if (file.isNull()) {
stream.push(file);
return done();
}
if (file.isStream()) {
return done(new PluginError(PLUGIN_NAME, 'Streaming not supported'));
}
var s = stylus(file.contents.toString('utf8'))
.set('filename', file.path)
.set('compress', opts.compress);
try {
var css = s.render();
file.path = gutil.replaceExtension(file.path, '.css');
file.contents = new Buffer(css);
stream.push(file);
done();
} catch (e) {
if (opts.silent) {
log(formatException(e));
file.path = gutil.replaceExtension(file.path, '.css');
file.contents = new Buffer('');
stream.push(file);
return done();
}
done(new PluginError(PLUGIN_NAME, e));
}
};
return stream;
}
module.exports = gulpstylus;
| Fix late throwed exception in stylus when silent mode enabled | Fix late throwed exception in stylus when silent mode enabled
| JavaScript | mit | polovi/gulp-stylus | ---
+++
@@ -9,21 +9,22 @@
PLUGIN_NAME = 'gulp-stylus';
+function formatException(e) {
+ return e.name+' in plugin \''+gutil.colors.cyan(PLUGIN_NAME)+'\''+': '+e.message
+}
function gulpstylus(options) {
var stream = new Transform({ objectMode: true }),
- opts = defaults(options, {
+ opts = defaults({}, options ,{
compress: false,
silent: false
});
stream._transform = function(file, unused, done) {
- // Pass through if null
if (file.isNull()) {
stream.push(file);
- done();
- return;
+ return done();
}
if (file.isStream()) {
@@ -35,20 +36,22 @@
.set('compress', opts.compress);
try {
- s.render(function(err, css) {
- if (err) throw err;
+ var css = s.render();
+ file.path = gutil.replaceExtension(file.path, '.css');
+ file.contents = new Buffer(css);
+ stream.push(file);
+ done();
+ } catch (e) {
+ if (opts.silent) {
+ log(formatException(e));
file.path = gutil.replaceExtension(file.path, '.css');
- file.contents = new Buffer(css);
+ file.contents = new Buffer('');
stream.push(file);
- done();
- });
- } catch(err) {
- if (opts.silent) {
- log(String(new PluginError(PLUGIN_NAME, err)));
return done();
}
- done(new PluginError(PLUGIN_NAME, err));
+
+ done(new PluginError(PLUGIN_NAME, e));
}
}; |
0ccd76579d0be07a5ee894462d66815fb7fe8b2e | index.js | index.js | #!/usr/bin/env node
var http = require('http')
var opn = require('opn')
var rc = module.require('rc')
var argv = require('optimist').argv
var config = rc('hcat', {}, argv)
if (argv.usage) {
console.log(require('./usage.js'))
process.exit(0)
}
function handler(request, response) {
var contentType = 'text/html'
var stream = process.stdin
response.setHeader('Content-Type', contentType)
stream.pipe(response)
response.on('finish', function() {
process.exit(0)
})
}
var server = http.createServer(handler)
server.on('listening', function() {
opn('http://localhost:' + server.address().port)
})
server.listen(config.port || 0, 'localhost')
| #!/usr/bin/env node
var http = require('http')
var opn = require('opn')
var rc = module.require('rc')
var argv = require('optimist').argv
var config = rc('hcat', {}, argv)
if (argv.usage) {
console.log(require('./usage.js'))
process.exit(0)
}
function handler(request, response) {
// Only accept one request
server.close();
var contentType = 'text/html'
var stream = process.stdin
response.setHeader('Content-Type', contentType)
stream.pipe(response)
}
var server = http.createServer(handler)
server.on('listening', function() {
opn('http://localhost:' + server.address().port)
})
server.listen(config.port || 0, 'localhost')
| Allow process to exit naturally | Allow process to exit naturally
| JavaScript | mit | kessler/node-hcat,noffle/node-hcat,noffle/node-hcat,kessler/node-hcat | ---
+++
@@ -13,6 +13,9 @@
}
function handler(request, response) {
+ // Only accept one request
+ server.close();
+
var contentType = 'text/html'
var stream = process.stdin
@@ -20,10 +23,6 @@
response.setHeader('Content-Type', contentType)
stream.pipe(response)
-
- response.on('finish', function() {
- process.exit(0)
- })
}
var server = http.createServer(handler) |
aabd1c398661c01b8cb37985ec618697b28fb648 | index.js | index.js | 'use strict';
var mustache = require('mustache');
exports.name = 'mustache';
exports.outputFormat = 'xml';
exports.render = function (str, options, locals) {
return mustache.render(str, locals);
};
| 'use strict';
var mustache = require('mustache');
exports.name = 'mustache';
exports.outputFormat = 'html';
exports.render = function (str, options, locals) {
return mustache.render(str, locals);
};
| Use `'html'` as output format | Use `'html'` as output format
Per jstransformers/jstransformer#3.
| JavaScript | mit | jstransformers/jstransformer-mustache,jstransformers/jstransformer-mustache | ---
+++
@@ -3,7 +3,7 @@
var mustache = require('mustache');
exports.name = 'mustache';
-exports.outputFormat = 'xml';
+exports.outputFormat = 'html';
exports.render = function (str, options, locals) {
return mustache.render(str, locals);
}; |
32251d41d59301cbe95c3508f1836bae33d8c867 | index.js | index.js | 'use strict';
var fs = require('fs');
function reset() {
exports.out = [];
exports.xmlEmitter = null;
exports.opts = {};
} reset();
/**
* Load a formatter
* @param {String} formatterPath
* @return
*/
function loadFormatter(formatterPath) {
return require('./lib/' + formatterPath + '_emitter');
}
/**
* Write out a XML file for the encountered results
* @param {Array} results
* @param {Array} data
* @param {Object} opts
*/
exports.reporter = function (results) {
exports.out.push(results);
};
exports.writeFile = function (opts) {
opts = opts || {};
opts.filePath = opts.filePath || 'jshint.xml';
opts.format = opts.format || 'checkstyle';
exports.xmlEmitter = loadFormatter(opts.format);
return function () {
if (!exports.out.length) {
reset();
return;
}
var outStream = fs.createWriteStream(opts.filePath);
outStream.write(exports.xmlEmitter.getHeader());
exports.out.forEach(function (item) {
outStream.write(exports.xmlEmitter.formatContent(item));
});
outStream.write(exports.out.join('\n'));
outStream.write(exports.xmlEmitter.getFooter());
reset();
};
};
| 'use strict';
var fs = require('fs');
function reset() {
exports.out = [];
exports.xmlEmitter = null;
exports.opts = {};
} reset();
/**
* Load a formatter
* @param {String} formatterPath
* @return
*/
function loadFormatter(formatterPath) {
return require('./lib/' + formatterPath + '_emitter');
}
/**
* Write out a XML file for the encountered results
* @param {Array} results
* @param {Array} data
* @param {Object} opts
*/
exports.reporter = function (results) {
exports.out.push(results);
};
exports.writeFile = function (opts) {
opts = opts || {};
opts.filePath = opts.filePath || 'jshint.xml';
opts.format = opts.format || 'checkstyle';
exports.xmlEmitter = loadFormatter(opts.format);
return function () {
if (!exports.out.length) {
reset();
return;
}
var outStream = fs.createWriteStream(opts.filePath);
outStream.write(exports.xmlEmitter.getHeader());
exports.out.forEach(function (item) {
outStream.write(exports.xmlEmitter.formatContent(item));
});
outStream.write(exports.xmlEmitter.getFooter());
reset();
};
};
| Remove bug that was generating invalid XML | Remove bug that was generating invalid XML
| JavaScript | mit | cleydsonjr/gulp-jshint-xml-file-reporter,lourenzo/gulp-jshint-xml-file-reporter | ---
+++
@@ -42,7 +42,6 @@
exports.out.forEach(function (item) {
outStream.write(exports.xmlEmitter.formatContent(item));
});
- outStream.write(exports.out.join('\n'));
outStream.write(exports.xmlEmitter.getFooter());
reset();
}; |
84dc0d3bfc19870898701a584ceafaad37bcb2da | index.js | index.js | /*
Copyright (c) 2015-2018 Claude Petit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
"use strict";
module.exports = (['dev', 'development'].indexOf(process.env.NODE_ENV) >= 0 ? require('./src/npc.js') : require('./build/npc.js'));
| /*
Copyright (c) 2015-2018 Claude Petit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
"use strict";
try {
module.exports = (['dev', 'development'].indexOf(process.env.NODE_ENV) >= 0 ? require('./src/npc.js') : require('./build/npc.js'));
} catch(ex) {
if (ex.code !== 'MODULE_NOT_FOUND') {
throw ex;
};
// Fall back to source code
module.exports = require('./src/npc.js');
};
| Add fall back to source code when built code is not available. | Add fall back to source code when built code is not available.
| JavaScript | mit | sickle2/package-config | ---
+++
@@ -25,5 +25,13 @@
"use strict";
+try {
+ module.exports = (['dev', 'development'].indexOf(process.env.NODE_ENV) >= 0 ? require('./src/npc.js') : require('./build/npc.js'));
+} catch(ex) {
+ if (ex.code !== 'MODULE_NOT_FOUND') {
+ throw ex;
+ };
-module.exports = (['dev', 'development'].indexOf(process.env.NODE_ENV) >= 0 ? require('./src/npc.js') : require('./build/npc.js'));
+ // Fall back to source code
+ module.exports = require('./src/npc.js');
+}; |
340af16870161abce00a6635fe7355f31449fe7f | index.js | index.js | import { randomBytes } from 'crypto';
// Crockford's Base32
// https://en.wikipedia.org/wiki/Base32
const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
function strongRandomNumber() {
return randomBytes(4).readUInt32LE() / 0xFFFFFFFF
}
function encodeTime(now, len) {
let arr = []
for (let x = len; x > 0; x--) {
let mod = now % ENCODING.length
arr[x] = ENCODING.charAt(mod)
now = (now - mod) / ENCODING.length
}
return arr
}
function encodeRandom(len) {
let arr = []
for (let x = len; x > 0; x--) {
let rando = Math.floor(ENCODING.length * strongRandomNumber())
arr[x] = ENCODING.charAt(rando)
}
return arr
}
function ulid() {
return []
.concat(encodeTime(Date.now(), 10))
.concat(encodeRandom(16))
.join('')
}
export {
strongRandomNumber,
encodeTime,
encodeRandom
}
export default ulid
| var crypto = require('crypto')
// Crockford's Base32
// https://en.wikipedia.org/wiki/Base32
var ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
function strongRandomNumber() {
return crypto.randomBytes(4).readUInt32LE() / 0xFFFFFFFF
}
function encodeTime(now, len) {
var arr = []
for (var x = len; x > 0; x--) {
var mod = now % ENCODING.length
arr[x] = ENCODING.charAt(mod)
now = (now - mod) / ENCODING.length
}
return arr
}
function encodeRandom(len) {
var rand
var arr = []
for (var x = len; x > 0; x--) {
rand = Math.floor(ENCODING.length * strongRandomNumber())
arr[x] = ENCODING.charAt(rando)
}
return arr
}
function ulid() {
return []
.concat(encodeTime(Date.now(), 10))
.concat(encodeRandom(16))
.join('')
}
module.exports = {
"strongRandomNumber": strongRandomNumber,
"encodeTime": encodeTime,
"encodeRandom": encodeRandom,
"ulid": ulid
}
| Convert to ES5 compatible code | Convert to ES5 compatible code
| JavaScript | mit | alizain/ulid,alizain/ulid | ---
+++
@@ -1,17 +1,17 @@
-import { randomBytes } from 'crypto';
+var crypto = require('crypto')
// Crockford's Base32
// https://en.wikipedia.org/wiki/Base32
-const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
+var ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
function strongRandomNumber() {
- return randomBytes(4).readUInt32LE() / 0xFFFFFFFF
+ return crypto.randomBytes(4).readUInt32LE() / 0xFFFFFFFF
}
function encodeTime(now, len) {
- let arr = []
- for (let x = len; x > 0; x--) {
- let mod = now % ENCODING.length
+ var arr = []
+ for (var x = len; x > 0; x--) {
+ var mod = now % ENCODING.length
arr[x] = ENCODING.charAt(mod)
now = (now - mod) / ENCODING.length
}
@@ -19,9 +19,10 @@
}
function encodeRandom(len) {
- let arr = []
- for (let x = len; x > 0; x--) {
- let rando = Math.floor(ENCODING.length * strongRandomNumber())
+ var rand
+ var arr = []
+ for (var x = len; x > 0; x--) {
+ rand = Math.floor(ENCODING.length * strongRandomNumber())
arr[x] = ENCODING.charAt(rando)
}
return arr
@@ -34,10 +35,9 @@
.join('')
}
-export {
- strongRandomNumber,
- encodeTime,
- encodeRandom
+module.exports = {
+ "strongRandomNumber": strongRandomNumber,
+ "encodeTime": encodeTime,
+ "encodeRandom": encodeRandom,
+ "ulid": ulid
}
-
-export default ulid |
a344ebe9ea0894f6b963600be0223d6e4712241a | index.js | index.js | var excludeMethods = [
/^constructor$/,
/^render$/,
/^component[A-Za-z]+$/,
/^shouldComponentUpdate$/
];
var displayNameReg = /^function\s+([a-zA-Z]+)/;
function isExcluded(methodName) {
return excludeMethods.some(function (reg) {
return reg.test(methodName) === false;
});
}
function bindToClass(scope, methods) {
var componentName = scope.constructor.toString().match(displayNameReg)[1];
methods = Array.isArray(methods) ? methods : [];
methods.forEach(function(methodName) {
if (methodName in scope) {
scope[methodName] = scope[methodName].bind(scope);
} else {
throw new Error('Method "' + methodName + '" does not exists in "' + componentName + '"');
}
});
// for debugging purposes only?
// if (process.env.NODE_ENV != 'production') {
if (Object.getOwnPropertyNames) {
var proto = scope.constructor.prototype;
Object.getOwnPropertyNames(proto).forEach(function(methodName) {
var original = scope[methodName];
if (typeof original === 'function' && isExcluded(methodName) && methods.indexOf(methodName) === -1) {
scope[methodName] = function () {
// test whether the scope is different
if (this !== scope) {
var e = 'Warning: Method "' + methodName + '" of "' + componentName + '" is not bound. Bad you!';
console.error(e);
}
return original.apply(scope, arguments);
};
}
});
}
// }
}
module.exports = bindToClass;
| var excludeMethods = [
/^constructor$/,
/^render$/,
/^component[A-Za-z]+$/,
/^shouldComponentUpdate$/
];
var displayNameReg = /^function\s+(_?[a-zA-Z]+)/;
function isExcluded(methodName) {
return excludeMethods.some(function (reg) {
return reg.test(methodName) === false;
});
}
function bindToClass(scope, methods) {
var componentName = scope.constructor.toString().match(displayNameReg)[1];
methods = Array.isArray(methods) ? methods : [];
methods.forEach(function(methodName) {
if (methodName in scope) {
scope[methodName] = scope[methodName].bind(scope);
} else {
throw new Error('Method "' + methodName + '" does not exists in "' + componentName + '"');
}
});
// for debugging purposes only?
// if (process.env.NODE_ENV != 'production') {
if (Object.getOwnPropertyNames) {
var proto = scope.constructor.prototype;
Object.getOwnPropertyNames(proto).forEach(function(methodName) {
var original = scope[methodName];
if (typeof original === 'function' && isExcluded(methodName) && methods.indexOf(methodName) === -1) {
scope[methodName] = function () {
// test whether the scope is different
if (this !== scope) {
var e = 'Warning: Method "' + methodName + '" of "' + componentName + '" is not bound. Bad you!';
console.error(e);
}
return original.apply(scope, arguments);
};
}
});
}
// }
}
module.exports = bindToClass;
| Add optional _ character to displayNameReg. | Add optional _ character to displayNameReg.
Babel, at least in my configuration, transpiles to "function _class", so we need to catch that too. | JavaScript | mit | nemisj/react-bind-to-class | ---
+++
@@ -5,7 +5,7 @@
/^shouldComponentUpdate$/
];
-var displayNameReg = /^function\s+([a-zA-Z]+)/;
+var displayNameReg = /^function\s+(_?[a-zA-Z]+)/;
function isExcluded(methodName) {
return excludeMethods.some(function (reg) { |
1e79060197f4aa803c1a0328c027ef755d6db500 | index.js | index.js | var path = require('path')
// Export function to create new config (builder is passed in from outside)
module.exports = function (builder) {
var bootstrapLess = require.resolve('bootstrap/less/bootstrap.less')
return builder.merge({
handlebars: {
templates: path.resolve(__dirname, 'handlebars', 'templates'),
partials: path.resolve(__dirname, 'handlebars', 'partials'),
helpers: require.resolve('./handlebars/helpers.js'),
/**
* A preprocessor that may return a modified json before entering the rendering process.
* Access the inherited preprocessor is possible via <code>this.previous(json)</code>
* @param obj the input object
* @return a modified object or a promise for a modified object.
*/
preprocessor: function (obj) {
return obj
}
},
less: {
main: [
bootstrapLess,
require.resolve('./less/main.less')
],
paths: [
path.dirname(bootstrapLess)
]
}
})
}
// Add "package" to be used by bootprint-doc-generator
module.exports.package = require('./package')
| var path = require('path')
// Export function to create new config (builder is passed in from outside)
module.exports = function (builder) {
var bootstrapLess = require.resolve('bootstrap/less/bootstrap.less')
return builder.merge({
handlebars: {
templates: path.resolve(__dirname, 'handlebars', 'templates'),
partials: path.resolve(__dirname, 'handlebars', 'partials'),
helpers: require.resolve('./handlebars/helpers.js'),
/**
* A preprocessor that may return a modified json before entering the rendering process.
* Access the inherited preprocessor is possible via <code>this.previous(json)</code>
* @param obj the input object
* @return a modified object or a promise for a modified object.
*/
preprocessor: function (obj) {
return obj
}
},
less: {
main: [
bootstrapLess,
require.resolve('highlight.js/styles/default.css'),
require.resolve('./less/main.less')
],
paths: [
path.dirname(bootstrapLess)
]
}
})
}
// Add "package" to be used by bootprint-doc-generator
module.exports.package = require('./package')
| Include `highlight.js`-styles into less file. | Include `highlight.js`-styles into less file.
Fixes bootprint/bootprint#16
This commit ensures that the styling of examples in bootprint-openapi is
visible.
| JavaScript | mit | nknapp/bootprint-base,bootprint/bootprint-base,bootprint/bootprint-base,nknapp/bootprint-base | ---
+++
@@ -22,6 +22,7 @@
less: {
main: [
bootstrapLess,
+ require.resolve('highlight.js/styles/default.css'),
require.resolve('./less/main.less')
],
paths: [ |
5c461bbcbb1e79108c03d1f90035203de53b682e | index.js | index.js | /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-virtual-scrollkit',
included: function(app) {
app.import('vendor/zynga-scroller/Animate.js');
app.import('vendor/zynga-scroller/Scroller.js');
}
};
| /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-virtual-scrollkit',
included: function(app) {
this._super.included.apply(this, arguments);
// see: https://github.com/ember-cli/ember-cli/issues/3718
if (typeof app.import !== 'function' && app.app) {
app = app.app;
}
app.import('vendor/zynga-scroller/Animate.js');
app.import('vendor/zynga-scroller/Scroller.js');
}
};
| Support usage as nested addon | Support usage as nested addon
| JavaScript | mit | yapplabs/ember-virtual-scrollkit,yapplabs/ember-virtual-scrollkit | ---
+++
@@ -4,6 +4,13 @@
module.exports = {
name: 'ember-virtual-scrollkit',
included: function(app) {
+ this._super.included.apply(this, arguments);
+
+ // see: https://github.com/ember-cli/ember-cli/issues/3718
+ if (typeof app.import !== 'function' && app.app) {
+ app = app.app;
+ }
+
app.import('vendor/zynga-scroller/Animate.js');
app.import('vendor/zynga-scroller/Scroller.js');
} |
89b14395900423d75ca4b388c693d6aca56fd51f | index.js | index.js | var path = require('path');
var root = __dirname.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
var escape = function (str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};
var regexp = ['lib', 'test'].map(function (i) {
return escape(path.join(__dirname, i));
}).join('|');
require('6to5/register')({ only: new RegExp(regexp) });
module.exports = require('./lib/postcss');
| var path = require('path');
var root = __dirname.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
var escape = function (str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};
var regexp = ['lib', 'test'].map(function (i) {
return '^' + escape(path.join(__dirname, i) + path.sep);
}).join('|');
require('6to5/register')({
only: new RegExp('(' + regexp + ')'),
ignore: false,
ignoreRegex: false
});
module.exports = require('./lib/postcss');
| Fix ES6 hook to work in node_modules | Fix ES6 hook to work in node_modules
| JavaScript | mit | bezoerb/postcss,longdog/postcss,himynameisdave/postcss,ashelley/postcss,whitneyit/postcss,eprincev-egor/postcss,MadLittleMods/postcss,andrepolischuk/postcss,jonathantneal/postcss,webdev1001/postcss,pazams/postcss,bendtherules/postcss,admdh/postcss,f/postcss,justim/postcss,ajoslin/postcss,omeripek/postcss,johnie/postcss,postcss/postcss,webdev1001/postcss,Paddy-Hamilton/postcss,postcss/postcss,zhuojiteam/postcss,OEvgeny/postcss,KivyGogh/postcss,maximkoretskiy/postcss,asan/postcss,wjb12/postcss,Semigradsky/postcss,c2ye/postcss,gitkiselev/postcss,mdegoo/postcss,greyhwndz/postcss,chengky/postcss,sandralundgren/postcss,alanev/postcss,MohammadYounes/postcss,alexmchardy/postcss,nicksheffield/postcss,cbas/postcss,marek-saji/postcss,dpostigo/postcss,geminiyellow/postcss,cnbin/postcss,mahtd/postcss,dmsanchez86/postcss,pascalduez/postcss,notacouch/postcss,CapeSepias/postcss,mxstbr/postcss,smagic39/postcss,marcustisater/postcss,qiucanghuai/postcss,jedmao/postcss,XOP/postcss,morishitter/postcss,LucasFrecia/postcss,mshahidkhan/postcss,kk9599/postcss,rtsao/postcss,dpiatek/postcss,phillipalexander/postcss,harrykiselev/postcss,Shugar/postcss,morishitter/postcss,dehuszar/postcss,johnotander/postcss | ---
+++
@@ -6,8 +6,12 @@
};
var regexp = ['lib', 'test'].map(function (i) {
- return escape(path.join(__dirname, i));
+ return '^' + escape(path.join(__dirname, i) + path.sep);
}).join('|');
-require('6to5/register')({ only: new RegExp(regexp) });
+require('6to5/register')({
+ only: new RegExp('(' + regexp + ')'),
+ ignore: false,
+ ignoreRegex: false
+});
module.exports = require('./lib/postcss'); |
6703a04ee5aef02d03a67db2b53cda19bef0893b | index.js | index.js | 'use strict';
var
platform = require('enyo/platform'),
dispatcher = require('enyo/dispatcher'),
gesture = require('enyo/gesture');
exports = module.exports = require('./lib/options');
exports.version = '2.6.0-pre';
// Override the default holdpulse config to account for greater delays between keydown and keyup
// events in Moonstone with certain input devices.
gesture.drag.configureHoldPulse({
frequency: 200,
events: [{name: 'hold', time: 400}],
resume: false,
moveTolerance: 1500,
endHold: 'onMove'
});
/**
* Registers key mappings for webOS-specific device keys related to media control.
*
* @private
*/
if (platform.webos >= 4) {
// Table of default keyCode mappings for webOS device
dispatcher.registerKeyMap({
415 : 'play',
413 : 'stop',
19 : 'pause',
412 : 'rewind',
417 : 'fastforward',
461 : 'back'
});
}
// ensure that these are registered
require('./lib/resolution');
require('./lib/fonts'); | 'use strict';
var
platform = require('enyo/platform'),
dispatcher = require('enyo/dispatcher'),
gesture = require('enyo/gesture');
exports = module.exports = require('./lib/options');
exports.version = '2.6.0-pre';
// Override the default holdpulse config to account for greater delays between keydown and keyup
// events in Moonstone with certain input devices.
gesture.drag.configureHoldPulse({
frequency: 200,
events: [{name: 'hold', time: 400}],
resume: false,
moveTolerance: 16,
endHold: 'onLeave'
});
/**
* Registers key mappings for webOS-specific device keys related to media control.
*
* @private
*/
if (platform.webos >= 4) {
// Table of default keyCode mappings for webOS device
dispatcher.registerKeyMap({
415 : 'play',
413 : 'stop',
19 : 'pause',
412 : 'rewind',
417 : 'fastforward',
461 : 'back'
});
}
// ensure that these are registered
require('./lib/resolution');
require('./lib/fonts'); | Change endHold from onMove to onLeave in configureHoldPulse | ENYO-1648: Change endHold from onMove to onLeave in configureHoldPulse
Issue:
- The onHoldPulse event is canceled too early when user move mouse abound.
Fix:
- We are using onLeave instead of onMove.
- Now it is cancel hold when it leaves control.
DCO-1.1-Signed-Off-By: Kunmyon Choi kunmyon.choi@lge.com
| JavaScript | apache-2.0 | enyojs/moonstone | ---
+++
@@ -14,8 +14,8 @@
frequency: 200,
events: [{name: 'hold', time: 400}],
resume: false,
- moveTolerance: 1500,
- endHold: 'onMove'
+ moveTolerance: 16,
+ endHold: 'onLeave'
});
/** |
5f2ed649ff35563a00e09b8edbcb55c8d2e25416 | index.js | index.js | import Cycle from '@cycle/core';
import {makeDOMDriver} from '@cycle/dom';
import slides from './src/slides';
const drivers = {
DOM: makeDOMDriver('.app')
};
if (module.hot) module.hot.accept();
Cycle.run(slides, drivers);
| import Cycle from '@cycle/core';
import {makeDOMDriver} from '@cycle/dom';
import slides from './src/slides';
const drivers = {
DOM: makeDOMDriver('.app')
};
const [sinks, sources] = Cycle.run(slides, drivers);
if (module.hot) {
module.hot.accept();
module.hot.dispose(() => {
sinks.dispose();
sources.dispose();
});
}
| Fix hotloading by correctly disposing of the Cycle app | Fix hotloading by correctly disposing of the Cycle app
| JavaScript | mit | Widdershin/cycle-talk,Widdershin/cycle-talk | ---
+++
@@ -7,6 +7,14 @@
DOM: makeDOMDriver('.app')
};
-if (module.hot) module.hot.accept();
+const [sinks, sources] = Cycle.run(slides, drivers);
-Cycle.run(slides, drivers);
+if (module.hot) {
+ module.hot.accept();
+
+ module.hot.dispose(() => {
+ sinks.dispose();
+ sources.dispose();
+ });
+}
+ |
6e74f4e97d65ed57c0ab0d8e67eb96d545973889 | index.js | index.js | var express = require('express');
var haml = require('hamljs');
var path = require('path');
var fs = require('fs');
var bodyParser = require('body-parser');
var engine = require('./libs/words_finder_engine');
engine.initialize();
// setup
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use( bodyParser.json() );
// routes
app.get('/', function(req, res) {
var hamlView = fs.readFileSync('views/main.haml', 'utf8');
res.send( haml.render(hamlView) );
});
app.post('/find-words', function(req, res) {
res.json( engine.findWords(req.body) );
});
app.listen(process.env.PORT || 3000, '127.0.0.1');
| var express = require('express');
var haml = require('hamljs');
var path = require('path');
var fs = require('fs');
var bodyParser = require('body-parser');
var engine = require('./libs/words_finder_engine');
engine.initialize();
// setup
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use( bodyParser.json() );
// routes
app.get('/', function(req, res) {
var hamlView = fs.readFileSync('views/main.haml', 'utf8');
res.send( haml.render(hamlView) );
});
app.post('/find-words', function(req, res) {
res.json( engine.findWords(req.body) );
});
app.listen(process.env.PORT || 3000);
| Revert "server: ensures we are not listening on the public interface" | Revert "server: ensures we are not listening on the public interface"
This reverts commit 272b9fdec7eadfa83ec57b7563788611ecdc5534.
| JavaScript | unlicense | cawel/words-finder,cawel/words-finder,cawel/words-finder | ---
+++
@@ -25,4 +25,4 @@
res.json( engine.findWords(req.body) );
});
-app.listen(process.env.PORT || 3000, '127.0.0.1');
+app.listen(process.env.PORT || 3000); |
8a7c1e89a7029b6fcb97edff62987ae2618944fa | index.js | index.js | function r() {
var strings = arguments[0];
var values = Array.prototype.slice.call(arguments, 1);
var str = str = strings.raw.reduce(function(prev, cur, idx) {
return prev + values[idx-1] + cur;
});
str = str.replace(/\r\n/g, '\n');
var newlineAndTabs = str.match(/^\n[\t]*/);
if( newlineAndTabs != null ) {
var matched = newlineAndTabs[0];
str = str.replace(new RegExp(matched, 'g'), '\n').substr(1);
}
else {
var matched = str.match(/^[\t]*/)[0];
str = str.substr(matched.length).replace(new RegExp('\n'+matched, 'g'), '\n');
}
return str;
}
module.exports = r; | function r() {
var strings = arguments[0];
var values = Array.prototype.slice.call(arguments, 1);
// concentrate strings and interpolations
var str = strings.raw.reduce(function(prev, cur, idx) {
return prev + values[idx-1] + cur;
})
.replace(/\r\n/g, '\n');
var newlineAndTabs = str.match(/^\n[\t]*/);
if( newlineAndTabs != null ) {
var matched = newlineAndTabs[0];
str = str.replace(new RegExp(matched, 'g'), '\n').substr(1);
}
else {
var matched = str.match(/^[\t]*/)[0];
str = str.substr(matched.length).replace(new RegExp('\n'+matched, 'g'), '\n');
}
return str;
}
module.exports = r; | Fix a mistake.(repeated variable assign; var str = str = ...) Concentrate unnecessary line to another. | Fix a mistake.(repeated variable assign; var str = str = ...) Concentrate unnecessary line to another.
| JavaScript | mit | Wooooo/remove-tabs | ---
+++
@@ -2,12 +2,12 @@
var strings = arguments[0];
var values = Array.prototype.slice.call(arguments, 1);
- var str = str = strings.raw.reduce(function(prev, cur, idx) {
+ // concentrate strings and interpolations
+ var str = strings.raw.reduce(function(prev, cur, idx) {
return prev + values[idx-1] + cur;
- });
+ })
+ .replace(/\r\n/g, '\n');
-
- str = str.replace(/\r\n/g, '\n');
var newlineAndTabs = str.match(/^\n[\t]*/);
|
24d4cabb6ddcd36218c75f9127c6e459cc070005 | index.js | index.js | // Entry point of data fetching
| // Entry point of data fetching
const request = require('superagent');
const path = require('path');
const url = require('url');
const DOMAIN = 'https://api.stackexchange.com';
const API_VERSION = '2.2';
// API Url
const apiUrl = {
questions: `${DOMAIN}/${API_VERSION}/questions`
};
// Simple URL fetching using superagent module
request
.get(apiUrl.questions)
.query('order=desc&sort=activity&site=stackoverflow')
.set('Accept', 'application/json')
.end((err,res) => {
console.log(res.body);
// TODO Find an online database server (use question_id as the key)
// TODO Think about handling time-series data
// TODO Filter unused data
// TODO Add the fetching timestamp (For another interesting questions in weekly/festival bias)
});
| Add a state-of-art API all | Add a state-of-art API all
| JavaScript | apache-2.0 | tngan/node-stackexchange | ---
+++
@@ -1,2 +1,25 @@
// Entry point of data fetching
+const request = require('superagent');
+const path = require('path');
+const url = require('url');
+const DOMAIN = 'https://api.stackexchange.com';
+const API_VERSION = '2.2';
+
+// API Url
+const apiUrl = {
+ questions: `${DOMAIN}/${API_VERSION}/questions`
+};
+
+// Simple URL fetching using superagent module
+request
+.get(apiUrl.questions)
+.query('order=desc&sort=activity&site=stackoverflow')
+.set('Accept', 'application/json')
+.end((err,res) => {
+ console.log(res.body);
+ // TODO Find an online database server (use question_id as the key)
+ // TODO Think about handling time-series data
+ // TODO Filter unused data
+ // TODO Add the fetching timestamp (For another interesting questions in weekly/festival bias)
+}); |
75ddb13451a346c431af5b7af8a017a555bca4a6 | index.js | index.js | // Requires
var Q = require('q');
var _ = require('underscore');
var qClass = require('qpatch').qClass;
// Etcd client
var Etcd = qClass(require('node-etcd'), ['watcher']);
// Since etcd create the dir keys automatically
// transform the tree of keys
// to contain only a flat array of leaves
function cleanDump(obj) {
// Is a leaf
if(!_.has(obj, 'kvs')) {
// We don't want the modifiedIndex attr in our dumps/restores
return _.pick(obj, 'key', 'value');
}
return _.flatten(_.map(obj.kvs, cleanInput));
}
function Dumper(etcd) {
// ETCD client
this.store = new Etcd();
_.bindAll(this);
}
// Get a JS object of the DB
Dumper.prototype.dump = function() {
return this.store.get('', {
recusrive: true
})
.then(cleanDump);
};
// Restore a list of keys
Dumper.prototype.restore = function(entries) {
var self = this;
return Q.all(_.map(entries, function(entry) {
return this.store.set(entry.key, entry.value);
}));
};
// Restore the database from input data
function createDumper() {
return new Dumper();
}
// Exports
module.exports = createDumper;
| // Requires
var Q = require('q');
var _ = require('underscore');
var qClass = require('qpatch').qClass;
// Etcd client
var Etcd = qClass(require('node-etcd'), ['watcher']);
// Since etcd create the dir keys automatically
// transform the tree of keys
// to contain only a flat array of leaves
function cleanDump(obj) {
// Is a leaf
if(!_.has(obj, 'kvs')) {
// We don't want the modifiedIndex attr in our dumps/restores
return _.pick(obj, 'key', 'value');
}
return _.flatten(_.map(obj.kvs, cleanDump));
}
function Dumper(etcd) {
// ETCD client
this.store = new Etcd();
_.bindAll(this);
}
// Get a JS object of the DB
Dumper.prototype.dump = function() {
return this.store.get('', {
recusrive: true
})
.then(cleanDump);
};
// Restore a list of keys
Dumper.prototype.restore = function(entries) {
var self = this;
return Q.all(_.map(entries, function(entry) {
return this.store.set(entry.key, entry.value);
}));
};
// Restore the database from input data
function createDumper() {
return new Dumper();
}
// Exports
module.exports = createDumper;
| Fix typo cleanInput => cleanDump | Fix typo cleanInput => cleanDump
| JavaScript | apache-2.0 | AaronO/etcd-dump | ---
+++
@@ -17,7 +17,7 @@
// We don't want the modifiedIndex attr in our dumps/restores
return _.pick(obj, 'key', 'value');
}
- return _.flatten(_.map(obj.kvs, cleanInput));
+ return _.flatten(_.map(obj.kvs, cleanDump));
}
|
2753b27b569ee1e07bf8177d3cea4ce688a88799 | index.js | index.js | /* Copyright (c) 2014 Chico Charlesworth, MIT License */
'use strict';
var sharder = require('sharder');
var async = require('async');
var name = 'seneca-shard-cache';
module.exports = function( options ) {
var seneca = this;
var shards = sharder(options);
var role = 'cache';
seneca.add({role: role, cmd: 'set'}, act);
seneca.add({role: role, cmd: 'get'}, act);
seneca.add({role: role, cmd: 'add'}, act);
seneca.add({role: role, cmd: 'delete'}, act);
seneca.add({role: role, cmd: 'incr'}, act);
seneca.add({role: role, cmd: 'decr'}, act);
function act(args, done) {
var toact = Object.create(args)
toact.shard = shards.resolve(args.key);
seneca.act(toact, function(err, result) {
if (err) {return done(err);}
done(null, result);
});
}
return {
name:name
};
}
| /* Copyright (c) 2014 Chico Charlesworth, MIT License */
'use strict';
var sharder = require('sharder');
var async = require('async');
var name = 'seneca-shard-cache';
module.exports = function( options ) {
var seneca = this;
var shards = sharder(options);
var role = 'cache';
seneca.add({role: role, cmd: 'set'}, act);
seneca.add({role: role, cmd: 'get'}, act);
seneca.add({role: role, cmd: 'add'}, act);
seneca.add({role: role, cmd: 'delete'}, act);
seneca.add({role: role, cmd: 'incr'}, act);
seneca.add({role: role, cmd: 'decr'}, act);
function act(args, done) {
var toact = Object.create(args)
toact.shard = shards.resolve('' + args.key);
seneca.act(toact, function(err, result) {
if (err) {return done(err);}
done(null, result);
});
}
return {
name:name
};
}
| Make sure shard key is a string | Make sure shard key is a string
| JavaScript | mit | chico/seneca-shard-cache | ---
+++
@@ -24,7 +24,7 @@
function act(args, done) {
var toact = Object.create(args)
- toact.shard = shards.resolve(args.key);
+ toact.shard = shards.resolve('' + args.key);
seneca.act(toact, function(err, result) {
if (err) {return done(err);} |
153e99b80da12a3a704ad0aad97ec499ceefab4d | index.js | index.js | var gulp = require('gulp'),
Elixir = require('laravel-elixir'),
livereload = require('gulp-livereload'),
config = Elixir.config;
Elixir.extend('livereload', function (src) {
defaultSrc = [
'app/**/*',
'public/**/*',
'resources/views/**/*'
];
src = src || defaultSrc;
gulp.on('task_start', function (e) {
if (e.task === 'watch') {
gulp.watch(src)
.on('change', function (event) {
livereload.changed(event.path);
});
livereload.listen();
}
});
});
| var gulp = require('gulp'),
Elixir = require('laravel-elixir'),
livereload = require('gulp-livereload'),
config = Elixir.config;
Elixir.extend('livereload', function (src) {
defaultSrc = [
config.appPath + '/**/*',
config.publicPath + '/**/*',
'resources/views/**/*'
];
src = src || defaultSrc;
gulp.on('task_start', function (e) {
if (e.task === 'watch') {
gulp.watch(src)
.on('change', function (event) {
livereload.changed(event.path);
});
livereload.listen();
}
});
});
| Use config for default paths. | Use config for default paths.
| JavaScript | mit | EHLOVader/laravel-elixir-livereload | ---
+++
@@ -7,8 +7,8 @@
Elixir.extend('livereload', function (src) {
defaultSrc = [
- 'app/**/*',
- 'public/**/*',
+ config.appPath + '/**/*',
+ config.publicPath + '/**/*',
'resources/views/**/*'
];
|
d8d1afb8d3e1a9c1c2b5b29a3d212ccb1244078e | index.js | index.js | /*!
* global-prefix <https://github.com/jonschlinkert/global-prefix>
*
* Copyright (c) 2015 Jon Schlinkert.
* Licensed under the MIT license.
*/
'use strict';
/**
* This is the code used internally by npm to
* resolve the global prefix.
*/
var isWindows = require('is-windows');
var path = require('path');
var prefix;
if (process.env.PREFIX) {
prefix = process.env.PREFIX;
} else if (isWindows === true || isWindows()) {
// c:\node\node.exe --> prefix=c:\node\
prefix = path.dirname(process.execPath);
} else {
// /usr/local/bin/node --> prefix=/usr/local
prefix = path.dirname(path.dirname(process.execPath));
// destdir only is respected on Unix
if (process.env.DESTDIR) {
prefix = path.join(process.env.DESTDIR, prefix);
}
}
module.exports = prefix;
| /*!
* global-prefix <https://github.com/jonschlinkert/global-prefix>
*
* Copyright (c) 2015 Jon Schlinkert.
* Licensed under the MIT license.
*/
'use strict';
/**
* This is the code used internally by npm to
* resolve the global prefix.
*/
var isWindows = require('is-windows');
var path = require('path');
var prefix;
if (process.env.PREFIX) {
prefix = process.env.PREFIX;
} else if (isWindows === true || isWindows()) {
// c:\node\node.exe --> prefix=c:\node\
prefix = process.env.APPDATA
? path.join(process.env.APPDATA, 'npm')
: path.dirname(process.execPath);
} else {
// /usr/local/bin/node --> prefix=/usr/local
prefix = path.dirname(path.dirname(process.execPath));
// destdir only is respected on Unix
if (process.env.DESTDIR) {
prefix = path.join(process.env.DESTDIR, prefix);
}
}
module.exports = prefix;
| Fix path to global node_modules on Windows | Fix path to global node_modules on Windows
| JavaScript | mit | jonschlinkert/global-prefix | ---
+++
@@ -20,7 +20,9 @@
prefix = process.env.PREFIX;
} else if (isWindows === true || isWindows()) {
// c:\node\node.exe --> prefix=c:\node\
- prefix = path.dirname(process.execPath);
+ prefix = process.env.APPDATA
+ ? path.join(process.env.APPDATA, 'npm')
+ : path.dirname(process.execPath);
} else {
// /usr/local/bin/node --> prefix=/usr/local
prefix = path.dirname(path.dirname(process.execPath)); |
9188e3a5ab852e9a0cd9e8ed1433c7a841232e20 | index.js | index.js | (function(root, factory) {
// Basbosa registry should be loaded once
if (typeof exports !== 'undefined') {
// Node.js
module.exports = factory(root);
} else if (typeof define === 'function' && define.amd) {
// AMD
define(function() {
if (typeof Basbosa !== 'undefined') return;
root.Basbosa = factory(root);
return root.Basbosa;
});
} else {
// Browser globals
root.Basbosa = factory(root);
}
}(this, function(root) {
var Basbosa = function Basbosa(className) {
if (!className) return Basbosa;
if (Basbosa.classes[className]) {
return Basbosa.classes[className];
} else {
new Error('Class ' + className + ' not defined or loaded yet');
}
};
Basbosa.add = function(className, instance) {
Basbosa.classes = Basbosa.classes || [];
return Basbosa.classes[className] = instance;
};
return Basbosa;
})); | (function(root, factory) {
// Basbosa registry should be loaded once
if (typeof exports !== 'undefined') {
// Node.js
module.exports = factory(root);
} else if (typeof define === 'function' && define.amd) {
// AMD
define(function() {
if (typeof Basbosa !== 'undefined') return;
root.Basbosa = factory(root);
return root.Basbosa;
});
} else {
// Browser globals
root.Basbosa = factory(root);
}
}(this, function(root) {
var Basbosa = function Basbosa(className, cb) {
var results = [];
if (!className) return Basbosa;
// Returning list of classes
if (className instanceof RegExp) {
for (var registeredClassName in Basbosa.classes) {
if (className.test(registeredClassName)) results.push(Basbosa(registeredClassName));
}
return results;
}
// TODO: Add this functionality!
// If the class is a model class, check if we can create if if AutoModels is loaded and
// a callback function was provided
// if (!Basbosa.added(className)
// && /Model$/.test(className)
// && !Basbosa.added(className)
// && typeof cb === 'function') {
// return Basbosa('AutoModel').createModelClass(className, {}, {}, cb);
// }
if (typeof Basbosa.classes[className] !== 'undefined') {
return Basbosa.classes[className];
} else {
throw new Error('Class ' + className + ' not defined or loaded yet');
}
};
Basbosa.classes = {};
Basbosa.add = function(className, instance) {
return Basbosa.classes[className] = instance;
};
Basbosa.added = function(className) {
return Basbosa.classes[className] !== 'undefined';
};
return Basbosa;
})); | Enable reg expression fetching of classes | Enable reg expression fetching of classes
| JavaScript | mit | ygaras/basbosa-registry | ---
+++
@@ -17,19 +17,48 @@
root.Basbosa = factory(root);
}
}(this, function(root) {
- var Basbosa = function Basbosa(className) {
- if (!className) return Basbosa;
- if (Basbosa.classes[className]) {
+ var Basbosa = function Basbosa(className, cb) {
+ var results = [];
+ if (!className) return Basbosa;
+
+ // Returning list of classes
+ if (className instanceof RegExp) {
+ for (var registeredClassName in Basbosa.classes) {
+ if (className.test(registeredClassName)) results.push(Basbosa(registeredClassName));
+ }
+
+ return results;
+ }
+
+ // TODO: Add this functionality!
+ // If the class is a model class, check if we can create if if AutoModels is loaded and
+ // a callback function was provided
+// if (!Basbosa.added(className)
+// && /Model$/.test(className)
+// && !Basbosa.added(className)
+// && typeof cb === 'function') {
+// return Basbosa('AutoModel').createModelClass(className, {}, {}, cb);
+// }
+
+
+ if (typeof Basbosa.classes[className] !== 'undefined') {
return Basbosa.classes[className];
} else {
- new Error('Class ' + className + ' not defined or loaded yet');
+ throw new Error('Class ' + className + ' not defined or loaded yet');
}
};
+ Basbosa.classes = {};
+
Basbosa.add = function(className, instance) {
- Basbosa.classes = Basbosa.classes || [];
return Basbosa.classes[className] = instance;
};
+
+ Basbosa.added = function(className) {
+ return Basbosa.classes[className] !== 'undefined';
+ };
+
+
return Basbosa;
})); |
0e359034e3fd80d26493991f18bacf318f422df3 | index.js | index.js | /*
*/
var hash;
var exec = require('child_process').exec;
exports.version = function(major, minor, cb) {
if (hash) {
cb (null, hash);
} else {
var child = exec('git rev-parse --short HEAD', {cwd: __dirname} ,
function (error, stdout, stderr) {
hash = [major, minor, stdout.replace(/\s/g, '')].join('.');
cb(error, hash);
});
}
}; | /*
*/
var githash;
var exec = require('child_process').exec;
/**
* Generate the formatted key given the major, minor and hash versions.
* @param {number|string} major
* @param {number|string} minor
* @param {string} githash
*
* @param {string} the version key
*/
var _makeKey = function (major, minor, githash) {
return [major, minor, githash.replace(/\s/g, '')].join('.');
};
/**
* Generate a version number that encodes the git hash.
*
* @param {number|string} major
* @param {number|string} minor
* @param {function (error, string)} cb - callback with the result
* @param {boolean=false} force - force the recomputation of the git hash
*/
exports.version = function(major, minor, cb, force) {
if (githash && force !== true) {
cb(null, _makeKey(major, minor, githash));
} else {
var child = exec('git rev-parse --short HEAD', {cwd: __dirname},
function (error, stdout, stderr) {
cb(error, _makeKey(major, minor, stdout));
}
);
}
};
| Allow the caller to force the recomputation of the version | Allow the caller to force the recomputation of the version
The flag is added to permit users to always get the latest version.
This is important in scenarios where a server is monitoring a file
system and automatically reloading when the contents change. With
the force flag, the server can ensure it has the latest version
of the git hash.
| JavaScript | mit | Reregistered/version-git | ---
+++
@@ -1,16 +1,37 @@
/*
*/
-var hash;
+var githash;
var exec = require('child_process').exec;
-exports.version = function(major, minor, cb) {
- if (hash) {
- cb (null, hash);
+
+/**
+ * Generate the formatted key given the major, minor and hash versions.
+ * @param {number|string} major
+ * @param {number|string} minor
+ * @param {string} githash
+ *
+ * @param {string} the version key
+ */
+var _makeKey = function (major, minor, githash) {
+ return [major, minor, githash.replace(/\s/g, '')].join('.');
+};
+
+/**
+ * Generate a version number that encodes the git hash.
+ *
+ * @param {number|string} major
+ * @param {number|string} minor
+ * @param {function (error, string)} cb - callback with the result
+ * @param {boolean=false} force - force the recomputation of the git hash
+ */
+exports.version = function(major, minor, cb, force) {
+ if (githash && force !== true) {
+ cb(null, _makeKey(major, minor, githash));
} else {
- var child = exec('git rev-parse --short HEAD', {cwd: __dirname} ,
+ var child = exec('git rev-parse --short HEAD', {cwd: __dirname},
function (error, stdout, stderr) {
- hash = [major, minor, stdout.replace(/\s/g, '')].join('.');
- cb(error, hash);
- });
+ cb(error, _makeKey(major, minor, stdout));
+ }
+ );
}
}; |
dcd0ec0371f64fe5e9452b020c7e69e4393cf1cd | js/ai.js | js/ai.js | var ai = ai || {}; //!< @namespace ai
ai.init = function(){
setInterval("ai._mainLoop();", 1000 / 120);
setInterval("api.keepPlay();", 1000 / 60);
}
ai._mainLoop = function(){
obs = api.getObstacles();
if (obs.length != 0){
var bound = 280 * (api.getCurrentSpeed() / Runner.config.MAX_SPEED);
var distance = (obs[0].xPos + obs[0].width) - api.getPlayer().xPos;
var player = api.getPlayer();
if (0 < distance && distance < bound && obs[0].yPos != 50 && obs[0].yPos != 75 && player.status != 'JUMPING'){
api.duckStop();
api.jump();
}
else if (player.status == 'JUMPING'){
if (player.xPos > obs[0].xPos + obs[0].width){
api.speedDrop();
}
}
else{
api.duck();
}
}
} | var ai = ai || {}; //!< @namespace ai
ai.init = function(){
setInterval("ai._mainLoop();", 1000 / 120);
setInterval("api.keepPlay();", 1000 / 60);
ai.speedDroping = false;
}
ai._mainLoop = function(){
obs = api.getObstacles();
if (obs.length != 0){
var bound = 280 * (api.getCurrentSpeed() / Runner.config.MAX_SPEED);
var distance = (obs[0].xPos + obs[0].width) - api.getPlayer().xPos;
var player = api.getPlayer();
if (0 < distance && distance < bound && obs[0].yPos != 50 && obs[0].yPos != 75 && player.status != 'JUMPING'){
api.duckStop();
api.jump();
}
else if (player.status == 'JUMPING'){
if (player.xPos > obs[0].xPos + obs[0].width && !this.speedDroping){
api.speedDrop();
this.speedDroping = true;
}
}
else{
this.speedDroping = false;
api.duck();
}
}
} | Fix bug: Call speedDrop too many times | Fix bug: Call speedDrop too many times
Use a boolean to record if it is speedDroping
| JavaScript | bsd-3-clause | NTU223/Dino,NTU223/Dino | ---
+++
@@ -3,6 +3,7 @@
ai.init = function(){
setInterval("ai._mainLoop();", 1000 / 120);
setInterval("api.keepPlay();", 1000 / 60);
+ ai.speedDroping = false;
}
@@ -17,11 +18,13 @@
api.jump();
}
else if (player.status == 'JUMPING'){
- if (player.xPos > obs[0].xPos + obs[0].width){
+ if (player.xPos > obs[0].xPos + obs[0].width && !this.speedDroping){
api.speedDrop();
+ this.speedDroping = true;
}
}
else{
+ this.speedDroping = false;
api.duck();
}
} |
412c00ad137a9b5c8f6d8af8783cd26f23aa9eec | app/middlewares/interpret-agent.js | app/middlewares/interpret-agent.js | var Agent = require( '../models/agent' ),
NotAuthorizedError = require( '../errors/not-authorized' );
module.exports = function( req, res, next ) {
if ( 'string' !== typeof req.body.secret ) {
throw new NotAuthorizedError( 'The `secret` parameter was missing from the request' );
}
new Agent()
.where({ secret: req.body.secret })
.fetch({ require: true })
.then(function( agent ) {
req.body.agent_id = agent.id;
next();
})
.catch(function() {
next( new NotAuthorizedError( 'The `secret` parameter was invalid' ) );
});
}; | var Agent = require( '../models/agent' ),
NotAuthorizedError = require( '../errors/not-authorized' );
module.exports = function( req, res, next ) {
if ( 'string' !== typeof req.body.secret ) {
require( './auth' )( req, res, next );
} else {
new Agent()
.where({ secret: req.body.secret })
.fetch({ require: true })
.then(function( agent ) {
req.body.agent_id = agent.id;
next();
})
.catch(function() {
next( new NotAuthorizedError( 'The `secret` parameter was invalid' ) );
});
}
}; | Use authorization middleware as fallback to agent secret | Use authorization middleware as fallback to agent secret
| JavaScript | mit | myact/myact-api | ---
+++
@@ -3,17 +3,17 @@
module.exports = function( req, res, next ) {
if ( 'string' !== typeof req.body.secret ) {
- throw new NotAuthorizedError( 'The `secret` parameter was missing from the request' );
+ require( './auth' )( req, res, next );
+ } else {
+ new Agent()
+ .where({ secret: req.body.secret })
+ .fetch({ require: true })
+ .then(function( agent ) {
+ req.body.agent_id = agent.id;
+ next();
+ })
+ .catch(function() {
+ next( new NotAuthorizedError( 'The `secret` parameter was invalid' ) );
+ });
}
-
- new Agent()
- .where({ secret: req.body.secret })
- .fetch({ require: true })
- .then(function( agent ) {
- req.body.agent_id = agent.id;
- next();
- })
- .catch(function() {
- next( new NotAuthorizedError( 'The `secret` parameter was invalid' ) );
- });
}; |
6dd4d4e8e02148e73bffacc7bc1b75e24f81734d | test/integration/helpers/index.js | test/integration/helpers/index.js | var _ = require('lodash');
exports.formatNumber = function(dialect) {
return {
mysql: _.identity,
sqlite3: _.identity,
postgresql: function(count) { return count.toString() }
}[dialect];
}
exports.countModels = function countModels(Model, options) {
return function() {
return Model.forge().count(options).then(function(count) {
if (typeof count === 'string') return parseInt(count);
return count;
});
}
}
| var _ = require('lodash');
exports.formatNumber = function(dialect) {
return {
mysql: _.identity,
sqlite3: _.identity,
postgresql: function(count) { return count.toString() }
}[dialect];
}
exports.countModels = function countModels(Model, options) {
return function() {
return Model.forge().count(options).then(function(count) {
if (typeof count === 'string') return parseInt(count);
return count;
});
}
}
exports.sort = function sort(model) {
var sorted = {}
for (var attribute in model) {
sorted[attribute] = this.sortCollection(model[attribute])
}
return sorted
}
exports.sortCollection = function sortCollection(collection) {
if (!Array.isArray(collection)) return collection
collection.sort(function(model1, model2) {
return model1.id - model2.id
})
return collection.map(this.sort, exports)
}
| Add sort and sortCollection test helper methods | Add sort and sortCollection test helper methods
| JavaScript | mit | bookshelf/bookshelf,bookshelf/bookshelf,tgriesser/bookshelf,tgriesser/bookshelf | ---
+++
@@ -16,3 +16,23 @@
});
}
}
+
+exports.sort = function sort(model) {
+ var sorted = {}
+
+ for (var attribute in model) {
+ sorted[attribute] = this.sortCollection(model[attribute])
+ }
+
+ return sorted
+}
+
+exports.sortCollection = function sortCollection(collection) {
+ if (!Array.isArray(collection)) return collection
+
+ collection.sort(function(model1, model2) {
+ return model1.id - model2.id
+ })
+
+ return collection.map(this.sort, exports)
+} |
5980bfc6e570f913ee210fd08770906a8e81ca5a | lib/messages/replies/not-on-channel.js | lib/messages/replies/not-on-channel.js |
var
extend = req('/lib/utilities/extend'),
ReplyMessage = req('/lib/messages/reply'),
Replies = req('/lib/constants/replies'),
NotOnChannelError = req('/lib/errors/not-on-channel');
class NotOnChannelMessage extends ReplyMessage {
getValuesForParameters() {
return {
channel_name: this.getChannelName()
};
}
setValuesFromParameters(parameters) {
this.setChannelName(parameters.get('channel_name'));
}
toError() {
return new NotOnChannelError(this.getChannelName());
}
}
extend(NotOnChannelMessage.prototype, {
reply: Replies.ERR_NOTONCHANNEL,
abnf: '<channel-name> " :You\'re not on that channel"'
});
module.exports = NotOnChannelMessage;
|
var
extend = req('/lib/utilities/extend'),
ReplyMessage = req('/lib/messages/reply'),
Replies = req('/lib/constants/replies'),
NotOnChannelError = req('/lib/errors/not-on-channel');
class NotOnChannelMessage extends ReplyMessage {
setChannelName(channel_name) {
this.channel_name = channel_name;
return this;
}
getChannelName() {
return this.channel_name;
}
getValuesForParameters() {
return {
channel_name: this.getChannelName()
};
}
setValuesFromParameters(parameters) {
this.setChannelName(parameters.get('channel_name'));
}
toError() {
return new NotOnChannelError(this.getChannelName());
}
}
extend(NotOnChannelMessage.prototype, {
reply: Replies.ERR_NOTONCHANNEL,
abnf: '<channel-name> " :You\'re not on that channel"',
channel_name: null
});
module.exports = NotOnChannelMessage;
| Allow setting channel name parameter on ERR_NOTONCHANNEL | Allow setting channel name parameter on ERR_NOTONCHANNEL
| JavaScript | isc | burninggarden/pirc,burninggarden/pirc | ---
+++
@@ -7,6 +7,15 @@
class NotOnChannelMessage extends ReplyMessage {
+
+ setChannelName(channel_name) {
+ this.channel_name = channel_name;
+ return this;
+ }
+
+ getChannelName() {
+ return this.channel_name;
+ }
getValuesForParameters() {
return {
@@ -25,8 +34,9 @@
}
extend(NotOnChannelMessage.prototype, {
- reply: Replies.ERR_NOTONCHANNEL,
- abnf: '<channel-name> " :You\'re not on that channel"'
+ reply: Replies.ERR_NOTONCHANNEL,
+ abnf: '<channel-name> " :You\'re not on that channel"',
+ channel_name: null
});
module.exports = NotOnChannelMessage; |
f119348d9cda7d764a35165984775cc6e0fb06d7 | examples/parties/server/server.js | examples/parties/server/server.js | // XXX autopublish warning is printed on each restart. super spammy!
Meteor.publish("directory", function () {
// XXX too easy to accidentally publish the list of validation tokens
return Meteor.users.find({}, {fields: {"emails.address": 1}});
});
Meteor.publish("parties", function () {
return Parties.find(
{$or: [{"public": true}, {invited: this.userId}, {owner: this.userId}]});
});
| // XXX autopublish warning is printed on each restart. super spammy!
Meteor.publish("directory", function () {
return Meteor.users.find({}, {fields: {emails: 1}});
});
Meteor.publish("parties", function () {
return Parties.find(
{$or: [{"public": true}, {invited: this.userId}, {owner: this.userId}]});
});
| Remove addressed XXX comment: verification tokens are now separate. | Remove addressed XXX comment: verification tokens are now separate.
| JavaScript | mit | luohuazju/meteor,skarekrow/meteor,Quicksteve/meteor,l0rd0fwar/meteor,daslicht/meteor,Puena/meteor,kencheung/meteor,yiliaofan/meteor,HugoRLopes/meteor,Urigo/meteor,meteor-velocity/meteor,brettle/meteor,juansgaitan/meteor,kengchau/meteor,somallg/meteor,DAB0mB/meteor,jg3526/meteor,chmac/meteor,ashwathgovind/meteor,Hansoft/meteor,daslicht/meteor,PatrickMcGuinness/meteor,calvintychan/meteor,chengxiaole/meteor,DCKT/meteor,Puena/meteor,elkingtonmcb/meteor,jenalgit/meteor,l0rd0fwar/meteor,sunny-g/meteor,EduShareOntario/meteor,benjamn/meteor,williambr/meteor,newswim/meteor,D1no/meteor,servel333/meteor,lieuwex/meteor,benstoltz/meteor,rabbyalone/meteor,mirstan/meteor,eluck/meteor,brettle/meteor,namho102/meteor,kidaa/meteor,lawrenceAIO/meteor,aramk/meteor,sclausen/meteor,Eynaliyev/meteor,jagi/meteor,yalexx/meteor,qscripter/meteor,emmerge/meteor,kengchau/meteor,elkingtonmcb/meteor,alphanso/meteor,SeanOceanHu/meteor,PatrickMcGuinness/meteor,Profab/meteor,henrypan/meteor,LWHTarena/meteor,chengxiaole/meteor,cbonami/meteor,kencheung/meteor,HugoRLopes/meteor,dfischer/meteor,devgrok/meteor,sclausen/meteor,steedos/meteor,Prithvi-A/meteor,kencheung/meteor,deanius/meteor,chasertech/meteor,lpinto93/meteor,iman-mafi/meteor,rabbyalone/meteor,Puena/meteor,servel333/meteor,devgrok/meteor,ljack/meteor,fashionsun/meteor,aldeed/meteor,servel333/meteor,chiefninew/meteor,shadedprofit/meteor,youprofit/meteor,Eynaliyev/meteor,ericterpstra/meteor,aramk/meteor,nuvipannu/meteor,alexbeletsky/meteor,vjau/meteor,lieuwex/meteor,lassombra/meteor,neotim/meteor,yonas/meteor-freebsd,LWHTarena/meteor,guazipi/meteor,Theviajerock/meteor,daltonrenaldo/meteor,vjau/meteor,lieuwex/meteor,saisai/meteor,codedogfish/meteor,l0rd0fwar/meteor,yinhe007/meteor,DAB0mB/meteor,luohuazju/meteor,paul-barry-kenzan/meteor,udhayam/meteor,allanalexandre/meteor,vacjaliu/meteor,colinligertwood/meteor,AnthonyAstige/meteor,GrimDerp/meteor,alexbeletsky/meteor,ericterpstra/meteor,jirengu/meteor,Jonekee/meteor,rozzzly/meteor,emmerge/meteor,sdeveloper/meteor,arunoda/meteor,Paulyoufu/meteor-1,tdamsma/meteor,planet-training/meteor,cbonami/meteor,Ken-Liu/meteor,arunoda/meteor,ericterpstra/meteor,ljack/meteor,whip112/meteor,katopz/meteor,colinligertwood/meteor,elkingtonmcb/meteor,EduShareOntario/meteor,whip112/meteor,lassombra/meteor,sunny-g/meteor,akintoey/meteor,judsonbsilva/meteor,papimomi/meteor,imanmafi/meteor,oceanzou123/meteor,fashionsun/meteor,Hansoft/meteor,ljack/meteor,D1no/meteor,chengxiaole/meteor,skarekrow/meteor,calvintychan/meteor,lorensr/meteor,chasertech/meteor,sdeveloper/meteor,qscripter/meteor,DCKT/meteor,tdamsma/meteor,shadedprofit/meteor,lawrenceAIO/meteor,dandv/meteor,planet-training/meteor,chasertech/meteor,baysao/meteor,karlito40/meteor,namho102/meteor,judsonbsilva/meteor,somallg/meteor,msavin/meteor,cog-64/meteor,devgrok/meteor,chinasb/meteor,msavin/meteor,ashwathgovind/meteor,dboyliao/meteor,benjamn/meteor,dboyliao/meteor,imanmafi/meteor,modulexcite/meteor,baysao/meteor,Eynaliyev/meteor,baysao/meteor,skarekrow/meteor,chmac/meteor,paul-barry-kenzan/meteor,benjamn/meteor,qscripter/meteor,vacjaliu/meteor,alexbeletsky/meteor,lorensr/meteor,yinhe007/meteor,GrimDerp/meteor,papimomi/meteor,saisai/meteor,Hansoft/meteor,judsonbsilva/meteor,TribeMedia/meteor,jirengu/meteor,sitexa/meteor,newswim/meteor,Quicksteve/meteor,bhargav175/meteor,cherbst/meteor,LWHTarena/meteor,namho102/meteor,IveWong/meteor,youprofit/meteor,vacjaliu/meteor,cherbst/meteor,lawrenceAIO/meteor,shadedprofit/meteor,ericterpstra/meteor,shadedprofit/meteor,jagi/meteor,wmkcc/meteor,juansgaitan/meteor,imanmafi/meteor,eluck/meteor,LWHTarena/meteor,namho102/meteor,meteor-velocity/meteor,chinasb/meteor,dfischer/meteor,chasertech/meteor,arunoda/meteor,shadedprofit/meteor,jagi/meteor,benjamn/meteor,pandeysoni/meteor,kencheung/meteor,mjmasn/meteor,codingang/meteor,eluck/meteor,akintoey/meteor,mubassirhayat/meteor,saisai/meteor,dev-bobsong/meteor,shrop/meteor,jeblister/meteor,HugoRLopes/meteor,steedos/meteor,SeanOceanHu/meteor,colinligertwood/meteor,baysao/meteor,Theviajerock/meteor,lawrenceAIO/meteor,Jeremy017/meteor,newswim/meteor,jirengu/meteor,mubassirhayat/meteor,jrudio/meteor,msavin/meteor,mjmasn/meteor,guazipi/meteor,aramk/meteor,Profab/meteor,Profab/meteor,chinasb/meteor,baysao/meteor,chiefninew/meteor,queso/meteor,williambr/meteor,chinasb/meteor,esteedqueen/meteor,somallg/meteor,cherbst/meteor,JesseQin/meteor,meteor-velocity/meteor,dandv/meteor,framewr/meteor,jdivy/meteor,yinhe007/meteor,kengchau/meteor,JesseQin/meteor,Prithvi-A/meteor,AlexR1712/meteor,daslicht/meteor,daslicht/meteor,johnthepink/meteor,4commerce-technologies-AG/meteor,brdtrpp/meteor,cbonami/meteor,whip112/meteor,justintung/meteor,wmkcc/meteor,michielvanoeffelen/meteor,udhayam/meteor,neotim/meteor,steedos/meteor,emmerge/meteor,stevenliuit/meteor,sitexa/meteor,IveWong/meteor,DAB0mB/meteor,emmerge/meteor,wmkcc/meteor,dev-bobsong/meteor,paul-barry-kenzan/meteor,mjmasn/meteor,h200863057/meteor,brdtrpp/meteor,justintung/meteor,chiefninew/meteor,Jonekee/meteor,yonglehou/meteor,AnthonyAstige/meteor,shmiko/meteor,JesseQin/meteor,Quicksteve/meteor,karlito40/meteor,tdamsma/meteor,rabbyalone/meteor,AnjirHossain/meteor,chmac/meteor,meonkeys/meteor,codedogfish/meteor,Urigo/meteor,PatrickMcGuinness/meteor,Jonekee/meteor,modulexcite/meteor,brdtrpp/meteor,vjau/meteor,h200863057/meteor,jdivy/meteor,judsonbsilva/meteor,lassombra/meteor,whip112/meteor,michielvanoeffelen/meteor,aldeed/meteor,queso/meteor,joannekoong/meteor,brdtrpp/meteor,baysao/meteor,hristaki/meteor,yonas/meteor-freebsd,jg3526/meteor,codingang/meteor,lpinto93/meteor,guazipi/meteor,Quicksteve/meteor,karlito40/meteor,vjau/meteor,shrop/meteor,eluck/meteor,jeblister/meteor,mirstan/meteor,lieuwex/meteor,oceanzou123/meteor,dfischer/meteor,karlito40/meteor,kencheung/meteor,joannekoong/meteor,brdtrpp/meteor,servel333/meteor,oceanzou123/meteor,shrop/meteor,sunny-g/meteor,steedos/meteor,oceanzou123/meteor,mauricionr/meteor,justintung/meteor,tdamsma/meteor,rabbyalone/meteor,EduShareOntario/meteor,Urigo/meteor,Quicksteve/meteor,4commerce-technologies-AG/meteor,lorensr/meteor,rozzzly/meteor,esteedqueen/meteor,framewr/meteor,esteedqueen/meteor,calvintychan/meteor,udhayam/meteor,mjmasn/meteor,Theviajerock/meteor,jenalgit/meteor,henrypan/meteor,zdd910/meteor,l0rd0fwar/meteor,codingang/meteor,imanmafi/meteor,yonas/meteor-freebsd,qscripter/meteor,judsonbsilva/meteor,pjump/meteor,sdeveloper/meteor,DCKT/meteor,jrudio/meteor,elkingtonmcb/meteor,hristaki/meteor,SeanOceanHu/meteor,karlito40/meteor,sdeveloper/meteor,stevenliuit/meteor,aldeed/meteor,udhayam/meteor,alphanso/meteor,h200863057/meteor,guazipi/meteor,daltonrenaldo/meteor,daslicht/meteor,evilemon/meteor,joannekoong/meteor,yyx990803/meteor,lpinto93/meteor,chinasb/meteor,Hansoft/meteor,yinhe007/meteor,joannekoong/meteor,paul-barry-kenzan/meteor,ericterpstra/meteor,udhayam/meteor,AnthonyAstige/meteor,allanalexandre/meteor,arunoda/meteor,nuvipannu/meteor,mauricionr/meteor,PatrickMcGuinness/meteor,somallg/meteor,brdtrpp/meteor,ashwathgovind/meteor,youprofit/meteor,cog-64/meteor,framewr/meteor,jg3526/meteor,LWHTarena/meteor,yanisIk/meteor,dboyliao/meteor,AnjirHossain/meteor,jenalgit/meteor,iman-mafi/meteor,zdd910/meteor,queso/meteor,kidaa/meteor,chmac/meteor,mauricionr/meteor,evilemon/meteor,alexbeletsky/meteor,imanmafi/meteor,hristaki/meteor,dev-bobsong/meteor,Jeremy017/meteor,jg3526/meteor,mubassirhayat/meteor,stevenliuit/meteor,dfischer/meteor,Profab/meteor,Jonekee/meteor,youprofit/meteor,chiefninew/meteor,yalexx/meteor,AnthonyAstige/meteor,chengxiaole/meteor,vjau/meteor,michielvanoeffelen/meteor,TechplexEngineer/meteor,akintoey/meteor,zdd910/meteor,sclausen/meteor,Prithvi-A/meteor,emmerge/meteor,vjau/meteor,Puena/meteor,PatrickMcGuinness/meteor,JesseQin/meteor,luohuazju/meteor,lawrenceAIO/meteor,deanius/meteor,lieuwex/meteor,servel333/meteor,benstoltz/meteor,meonkeys/meteor,bhargav175/meteor,codedogfish/meteor,saisai/meteor,baysao/meteor,ashwathgovind/meteor,elkingtonmcb/meteor,chiefninew/meteor,youprofit/meteor,alphanso/meteor,chengxiaole/meteor,TechplexEngineer/meteor,deanius/meteor,namho102/meteor,henrypan/meteor,SeanOceanHu/meteor,mubassirhayat/meteor,JesseQin/meteor,yyx990803/meteor,aldeed/meteor,jdivy/meteor,Paulyoufu/meteor-1,mauricionr/meteor,henrypan/meteor,queso/meteor,Prithvi-A/meteor,dboyliao/meteor,Theviajerock/meteor,dboyliao/meteor,papimomi/meteor,williambr/meteor,iman-mafi/meteor,servel333/meteor,Eynaliyev/meteor,fashionsun/meteor,Jeremy017/meteor,codedogfish/meteor,yiliaofan/meteor,lassombra/meteor,Jeremy017/meteor,mubassirhayat/meteor,Quicksteve/meteor,meteor-velocity/meteor,baiyunping333/meteor,baiyunping333/meteor,iman-mafi/meteor,msavin/meteor,aramk/meteor,shmiko/meteor,jagi/meteor,cherbst/meteor,sdeveloper/meteor,guazipi/meteor,sclausen/meteor,neotim/meteor,SeanOceanHu/meteor,dev-bobsong/meteor,planet-training/meteor,Urigo/meteor,shrop/meteor,yonglehou/meteor,pjump/meteor,ljack/meteor,yalexx/meteor,sdeveloper/meteor,Eynaliyev/meteor,pjump/meteor,Eynaliyev/meteor,ljack/meteor,pandeysoni/meteor,yyx990803/meteor,yiliaofan/meteor,Hansoft/meteor,PatrickMcGuinness/meteor,shmiko/meteor,AnthonyAstige/meteor,saisai/meteor,meonkeys/meteor,juansgaitan/meteor,skarekrow/meteor,Ken-Liu/meteor,johnthepink/meteor,whip112/meteor,allanalexandre/meteor,Ken-Liu/meteor,Jonekee/meteor,esteedqueen/meteor,JesseQin/meteor,AlexR1712/meteor,DCKT/meteor,codingang/meteor,elkingtonmcb/meteor,eluck/meteor,somallg/meteor,ndarilek/meteor,colinligertwood/meteor,yanisIk/meteor,hristaki/meteor,imanmafi/meteor,IveWong/meteor,lassombra/meteor,cherbst/meteor,williambr/meteor,colinligertwood/meteor,brettle/meteor,TribeMedia/meteor,dfischer/meteor,jdivy/meteor,shrop/meteor,guazipi/meteor,LWHTarena/meteor,jenalgit/meteor,calvintychan/meteor,aramk/meteor,pandeysoni/meteor,cherbst/meteor,LWHTarena/meteor,jeblister/meteor,codedogfish/meteor,lorensr/meteor,deanius/meteor,sitexa/meteor,arunoda/meteor,hristaki/meteor,daslicht/meteor,h200863057/meteor,sunny-g/meteor,papimomi/meteor,sclausen/meteor,michielvanoeffelen/meteor,aldeed/meteor,aleclarson/meteor,yiliaofan/meteor,meonkeys/meteor,dfischer/meteor,AnjirHossain/meteor,mubassirhayat/meteor,GrimDerp/meteor,allanalexandre/meteor,steedos/meteor,daltonrenaldo/meteor,fashionsun/meteor,servel333/meteor,lorensr/meteor,lawrenceAIO/meteor,yyx990803/meteor,yyx990803/meteor,mirstan/meteor,AnjirHossain/meteor,Theviajerock/meteor,michielvanoeffelen/meteor,pjump/meteor,daltonrenaldo/meteor,queso/meteor,cbonami/meteor,4commerce-technologies-AG/meteor,judsonbsilva/meteor,mjmasn/meteor,newswim/meteor,baiyunping333/meteor,brdtrpp/meteor,karlito40/meteor,yanisIk/meteor,evilemon/meteor,joannekoong/meteor,benjamn/meteor,sitexa/meteor,yiliaofan/meteor,l0rd0fwar/meteor,yalexx/meteor,rozzzly/meteor,jagi/meteor,rozzzly/meteor,kengchau/meteor,Hansoft/meteor,Paulyoufu/meteor-1,planet-training/meteor,wmkcc/meteor,michielvanoeffelen/meteor,planet-training/meteor,GrimDerp/meteor,katopz/meteor,katopz/meteor,wmkcc/meteor,lpinto93/meteor,jirengu/meteor,D1no/meteor,evilemon/meteor,whip112/meteor,somallg/meteor,papimomi/meteor,D1no/meteor,dandv/meteor,framewr/meteor,ljack/meteor,jagi/meteor,kidaa/meteor,akintoey/meteor,cbonami/meteor,wmkcc/meteor,TechplexEngineer/meteor,4commerce-technologies-AG/meteor,guazipi/meteor,brettle/meteor,Paulyoufu/meteor-1,Ken-Liu/meteor,planet-training/meteor,juansgaitan/meteor,TechplexEngineer/meteor,sclausen/meteor,tdamsma/meteor,HugoRLopes/meteor,williambr/meteor,shrop/meteor,neotim/meteor,Theviajerock/meteor,vjau/meteor,ericterpstra/meteor,cog-64/meteor,kengchau/meteor,fashionsun/meteor,kidaa/meteor,DAB0mB/meteor,queso/meteor,eluck/meteor,eluck/meteor,dfischer/meteor,mubassirhayat/meteor,bhargav175/meteor,Jeremy017/meteor,hristaki/meteor,katopz/meteor,ljack/meteor,chiefninew/meteor,benstoltz/meteor,newswim/meteor,namho102/meteor,stevenliuit/meteor,msavin/meteor,TribeMedia/meteor,lorensr/meteor,shmiko/meteor,iman-mafi/meteor,papimomi/meteor,alexbeletsky/meteor,bhargav175/meteor,aldeed/meteor,yanisIk/meteor,AnthonyAstige/meteor,yonglehou/meteor,stevenliuit/meteor,kidaa/meteor,stevenliuit/meteor,juansgaitan/meteor,HugoRLopes/meteor,cbonami/meteor,aldeed/meteor,AlexR1712/meteor,jeblister/meteor,daltonrenaldo/meteor,yonglehou/meteor,jrudio/meteor,somallg/meteor,Hansoft/meteor,jg3526/meteor,sunny-g/meteor,deanius/meteor,newswim/meteor,zdd910/meteor,deanius/meteor,SeanOceanHu/meteor,benstoltz/meteor,kengchau/meteor,TechplexEngineer/meteor,pandeysoni/meteor,chasertech/meteor,Paulyoufu/meteor-1,lieuwex/meteor,Prithvi-A/meteor,katopz/meteor,lassombra/meteor,modulexcite/meteor,newswim/meteor,EduShareOntario/meteor,akintoey/meteor,tdamsma/meteor,emmerge/meteor,D1no/meteor,Jeremy017/meteor,modulexcite/meteor,lorensr/meteor,l0rd0fwar/meteor,zdd910/meteor,AnjirHossain/meteor,kengchau/meteor,steedos/meteor,brettle/meteor,shmiko/meteor,jeblister/meteor,chengxiaole/meteor,meonkeys/meteor,daltonrenaldo/meteor,oceanzou123/meteor,ndarilek/meteor,luohuazju/meteor,DCKT/meteor,dandv/meteor,williambr/meteor,emmerge/meteor,baiyunping333/meteor,GrimDerp/meteor,yanisIk/meteor,aleclarson/meteor,dboyliao/meteor,esteedqueen/meteor,jrudio/meteor,jenalgit/meteor,yonas/meteor-freebsd,shmiko/meteor,alphanso/meteor,brdtrpp/meteor,AnjirHossain/meteor,allanalexandre/meteor,dboyliao/meteor,modulexcite/meteor,cog-64/meteor,oceanzou123/meteor,chiefninew/meteor,esteedqueen/meteor,sunny-g/meteor,h200863057/meteor,ndarilek/meteor,johnthepink/meteor,alexbeletsky/meteor,cbonami/meteor,jg3526/meteor,ashwathgovind/meteor,yonas/meteor-freebsd,lawrenceAIO/meteor,joannekoong/meteor,Jeremy017/meteor,johnthepink/meteor,juansgaitan/meteor,Profab/meteor,johnthepink/meteor,benjamn/meteor,nuvipannu/meteor,devgrok/meteor,mirstan/meteor,Urigo/meteor,AnthonyAstige/meteor,mauricionr/meteor,eluck/meteor,qscripter/meteor,katopz/meteor,rabbyalone/meteor,benstoltz/meteor,dboyliao/meteor,neotim/meteor,vacjaliu/meteor,henrypan/meteor,yiliaofan/meteor,Prithvi-A/meteor,neotim/meteor,akintoey/meteor,kidaa/meteor,mirstan/meteor,alphanso/meteor,pjump/meteor,mirstan/meteor,ndarilek/meteor,GrimDerp/meteor,rozzzly/meteor,IveWong/meteor,Urigo/meteor,youprofit/meteor,paul-barry-kenzan/meteor,jirengu/meteor,TribeMedia/meteor,jenalgit/meteor,yalexx/meteor,baiyunping333/meteor,qscripter/meteor,D1no/meteor,AlexR1712/meteor,framewr/meteor,SeanOceanHu/meteor,TribeMedia/meteor,planet-training/meteor,AnjirHossain/meteor,mirstan/meteor,zdd910/meteor,baiyunping333/meteor,alexbeletsky/meteor,cog-64/meteor,deanius/meteor,katopz/meteor,kidaa/meteor,benjamn/meteor,luohuazju/meteor,meteor-velocity/meteor,skarekrow/meteor,chmac/meteor,modulexcite/meteor,kencheung/meteor,pjump/meteor,mubassirhayat/meteor,meonkeys/meteor,sunny-g/meteor,kencheung/meteor,calvintychan/meteor,sitexa/meteor,mjmasn/meteor,allanalexandre/meteor,alphanso/meteor,mauricionr/meteor,saisai/meteor,chengxiaole/meteor,mjmasn/meteor,yonas/meteor-freebsd,ashwathgovind/meteor,juansgaitan/meteor,lpinto93/meteor,iman-mafi/meteor,yiliaofan/meteor,brettle/meteor,yonglehou/meteor,framewr/meteor,daltonrenaldo/meteor,EduShareOntario/meteor,yanisIk/meteor,ericterpstra/meteor,jirengu/meteor,arunoda/meteor,Jonekee/meteor,udhayam/meteor,luohuazju/meteor,Puena/meteor,chasertech/meteor,ashwathgovind/meteor,pandeysoni/meteor,4commerce-technologies-AG/meteor,h200863057/meteor,meteor-velocity/meteor,yyx990803/meteor,cog-64/meteor,yonglehou/meteor,namho102/meteor,steedos/meteor,h200863057/meteor,jenalgit/meteor,shrop/meteor,Urigo/meteor,HugoRLopes/meteor,Quicksteve/meteor,Paulyoufu/meteor-1,yonglehou/meteor,rabbyalone/meteor,nuvipannu/meteor,stevenliuit/meteor,Prithvi-A/meteor,yonas/meteor-freebsd,esteedqueen/meteor,ljack/meteor,benstoltz/meteor,skarekrow/meteor,sitexa/meteor,codingang/meteor,JesseQin/meteor,colinligertwood/meteor,codedogfish/meteor,qscripter/meteor,lieuwex/meteor,tdamsma/meteor,johnthepink/meteor,sunny-g/meteor,servel333/meteor,jdivy/meteor,judsonbsilva/meteor,yyx990803/meteor,TribeMedia/meteor,jirengu/meteor,meteor-velocity/meteor,michielvanoeffelen/meteor,youprofit/meteor,elkingtonmcb/meteor,jdivy/meteor,yinhe007/meteor,AlexR1712/meteor,yanisIk/meteor,dandv/meteor,bhargav175/meteor,PatrickMcGuinness/meteor,justintung/meteor,AnthonyAstige/meteor,shadedprofit/meteor,henrypan/meteor,EduShareOntario/meteor,nuvipannu/meteor,saisai/meteor,yalexx/meteor,bhargav175/meteor,arunoda/meteor,shmiko/meteor,rabbyalone/meteor,colinligertwood/meteor,luohuazju/meteor,codingang/meteor,rozzzly/meteor,SeanOceanHu/meteor,Eynaliyev/meteor,Ken-Liu/meteor,yinhe007/meteor,framewr/meteor,nuvipannu/meteor,D1no/meteor,ndarilek/meteor,Puena/meteor,fashionsun/meteor,yalexx/meteor,sclausen/meteor,GrimDerp/meteor,joannekoong/meteor,D1no/meteor,nuvipannu/meteor,chmac/meteor,dev-bobsong/meteor,allanalexandre/meteor,queso/meteor,evilemon/meteor,DAB0mB/meteor,daslicht/meteor,karlito40/meteor,Profab/meteor,codedogfish/meteor,TechplexEngineer/meteor,zdd910/meteor,pjump/meteor,msavin/meteor,neotim/meteor,Paulyoufu/meteor-1,dandv/meteor,jagi/meteor,papimomi/meteor,somallg/meteor,tdamsma/meteor,AlexR1712/meteor,Puena/meteor,msavin/meteor,Profab/meteor,Eynaliyev/meteor,Ken-Liu/meteor,Theviajerock/meteor,codingang/meteor,justintung/meteor,Ken-Liu/meteor,ndarilek/meteor,vacjaliu/meteor,jeblister/meteor,IveWong/meteor,aleclarson/meteor,sdeveloper/meteor,devgrok/meteor,bhargav175/meteor,hristaki/meteor,shadedprofit/meteor,benstoltz/meteor,alexbeletsky/meteor,DAB0mB/meteor,4commerce-technologies-AG/meteor,calvintychan/meteor,aramk/meteor,mauricionr/meteor,chiefninew/meteor,HugoRLopes/meteor,vacjaliu/meteor,TechplexEngineer/meteor,vacjaliu/meteor,planet-training/meteor,jrudio/meteor,jdivy/meteor,iman-mafi/meteor,lpinto93/meteor,chinasb/meteor,justintung/meteor,meonkeys/meteor,sitexa/meteor,jrudio/meteor,cherbst/meteor,chmac/meteor,johnthepink/meteor,devgrok/meteor,Jonekee/meteor,daltonrenaldo/meteor,imanmafi/meteor,lpinto93/meteor,baiyunping333/meteor,fashionsun/meteor,aramk/meteor,paul-barry-kenzan/meteor,akintoey/meteor,4commerce-technologies-AG/meteor,cog-64/meteor,chinasb/meteor,DCKT/meteor,wmkcc/meteor,dev-bobsong/meteor,rozzzly/meteor,brettle/meteor,karlito40/meteor,justintung/meteor,calvintychan/meteor,l0rd0fwar/meteor,DAB0mB/meteor,dev-bobsong/meteor,pandeysoni/meteor,AlexR1712/meteor,allanalexandre/meteor,jg3526/meteor,skarekrow/meteor,lassombra/meteor,udhayam/meteor,williambr/meteor,modulexcite/meteor,HugoRLopes/meteor,DCKT/meteor,henrypan/meteor,oceanzou123/meteor,EduShareOntario/meteor,evilemon/meteor,chasertech/meteor,evilemon/meteor,pandeysoni/meteor,dandv/meteor,jeblister/meteor,paul-barry-kenzan/meteor,alphanso/meteor,ndarilek/meteor,whip112/meteor,ndarilek/meteor,devgrok/meteor,IveWong/meteor,yinhe007/meteor,yanisIk/meteor,TribeMedia/meteor,IveWong/meteor | ---
+++
@@ -1,8 +1,7 @@
// XXX autopublish warning is printed on each restart. super spammy!
Meteor.publish("directory", function () {
- // XXX too easy to accidentally publish the list of validation tokens
- return Meteor.users.find({}, {fields: {"emails.address": 1}});
+ return Meteor.users.find({}, {fields: {emails: 1}});
});
Meteor.publish("parties", function () { |
c53802d7edb53148e6449d75b293e6d6ff3af4b0 | core/actions/slackPreviewRelease.js | core/actions/slackPreviewRelease.js | 'use strict';
const { waterfall, mapSeries } = require('async');
const logger = require('../../lib/logger');
module.exports = function createPreviewRelease(getConfig, getReleasePreview, notify, repos) {
return ({ verbose = false }, cb) => {
waterfall([
(next) => getConfigForEachRepo(repos, next),
(reposInfo, next) => getReleasePreview(reposInfo, next),
(reposInfo, next) => notifyPreviewInSlack(reposInfo, verbose, next)
], cb);
};
function getConfigForEachRepo(repos, cb) {
mapSeries(repos, (repo, nextRepo) => {
getConfig(repo, (err, config) => {
if (err) {
logger.error('Error getting repo config', repo, err);
return nextRepo(null, { repo, failReason: 'INVALID_REPO_CONFIG' });
}
nextRepo(null, { repo, config });
});
}, cb);
}
function notifyPreviewInSlack(reposInfo, verbose, cb) {
notify(reposInfo, 'preview', verbose, cb);
}
};
| 'use strict';
const { waterfall, mapSeries } = require('async');
const logger = require('../../lib/logger');
module.exports = function createPreviewRelease(getConfig, getReleasePreview, notify, repos) {
return ({ verbose = false }, cb) => {
waterfall([
(next) => getConfigForEachRepo(repos, next),
(reposInfo, next) => getReleasePreview(reposInfo, next),
(reposInfo, next) => notifyPreviewInSlack(reposInfo, verbose, next)
], cb);
};
function getConfigForEachRepo(repos, cb) {
logger.debug('getConfigForEachRepo', { repos });
mapSeries(repos, (repo, nextRepo) => {
getConfig(repo, (err, config) => {
if (err) {
logger.error('Error getting repo config', repo, err);
return nextRepo(null, { repo, failReason: 'INVALID_REPO_CONFIG' });
}
nextRepo(null, { repo, config });
});
}, cb);
}
function notifyPreviewInSlack(reposInfo, verbose, cb) {
logger.debug('notifyPreviewInSlack', { reposInfo, verbose });
notify(reposInfo, 'preview', verbose, cb);
}
};
| Add debug logs to preview release | Add debug logs to preview release
| JavaScript | mit | AudienseCo/monorail,AudienseCo/monorail | ---
+++
@@ -14,6 +14,7 @@
};
function getConfigForEachRepo(repos, cb) {
+ logger.debug('getConfigForEachRepo', { repos });
mapSeries(repos, (repo, nextRepo) => {
getConfig(repo, (err, config) => {
if (err) {
@@ -26,6 +27,7 @@
}
function notifyPreviewInSlack(reposInfo, verbose, cb) {
+ logger.debug('notifyPreviewInSlack', { reposInfo, verbose });
notify(reposInfo, 'preview', verbose, cb);
}
}; |
a2e65ca5a422133cdb7b0d183029b4b9a21ac6d2 | game/static/game/js/GameLoader.js | game/static/game/js/GameLoader.js | function onDownloadFinished(duration)
{
console.log("Finished download in: " + duration + "ms");
initGame();
initDebugger();
}
/*
* Called on a resource download finish
* Params :
* downloadedAmount : Amount of resource downloaded
* totalAmount : Total amount resource to download
*/
function onDownloadUpdate(downloadedAmount, totalAmount)
{
console.log("Downloaded file : " + downloadedAmount + " / " + totalAmount + "(" + parseInt((downloadedAmount / totalAmount) * 100) + "%)");
}
/*
* Called on a resource download error
* Params :
* error : Error returned by JQuery
*/
function onDownloadError(error)
{
console.error("Failed to download resources :");
console.error(error);
}
// Game Start
$(function()
{
console.log("Game Starting...");
console.log("Download game resources...");
ResourceLoader.downloadGameResources(onDownloadFinished, onDownloadUpdate, onDownloadError);
initGame();
initDebugger();
});
| function onDownloadFinished(duration)
{
console.log("Finished download in: " + duration + "ms");
initGame();
initDebugger();
}
/*
* Called on a resource download finish
* Params :
* downloadedAmount : Amount of resource downloaded
* totalAmount : Total amount resource to download
*/
function onDownloadUpdate(downloadedAmount, totalAmount)
{
console.log("Downloaded file : " + downloadedAmount + " / " + totalAmount + "(" + parseInt((downloadedAmount / totalAmount) * 100) + "%)");
}
/*
* Called on a resource download error
* Params :
* error : Error returned by JQuery
*/
function onDownloadError(error)
{
console.error("Failed to download resources :");
console.error(error);
}
// Game Start
$(function()
{
console.log("Game Starting...");
console.log("Download game resources...");
ResourceLoader.downloadGameResources(onDownloadFinished, onDownloadUpdate, onDownloadError);
});
| Fix double call to map rendering and debugger | Fix double call to map rendering and debugger
| JavaScript | mit | DanAurea/Django-RPG,DanAurea/Trisdanvalwen,DanAurea/Trisdanvalwen,DanAurea/Django-RPG,DanAurea/Trisdanvalwen,DanAurea/Trisdanvalwen,DanAurea/Django-RPG,DanAurea/Django-RPG | ---
+++
@@ -33,6 +33,4 @@
console.log("Game Starting...");
console.log("Download game resources...");
ResourceLoader.downloadGameResources(onDownloadFinished, onDownloadUpdate, onDownloadError);
- initGame();
- initDebugger();
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.