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 |
|---|---|---|---|---|---|---|---|---|---|---|
5d43ac93264644b0b4821de3df0f3cf6256a6f4f | tests/dummy/app/routes/filtered.js | tests/dummy/app/routes/filtered.js | import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
export default class FilteredRoute extends Route {
@service store;
async beforeModel() {
await this.store.update((t) => {
const moons = [
{ type: 'moon', attributes: { name: 'Blue' } },
{ type: 'moon', attributes: { name: 'New' } }
];
const operations = [];
operations.push(t.addRecord(moons[0]));
operations.push(t.addRecord(moons[1]));
const plutoOperation = t.addRecord({
type: 'planet',
attributes: { name: 'Pluto' }
});
const plutoId = plutoOperation.operation.record.id;
operations.push(plutoOperation);
operations.push(
t.addRecord({ type: 'planet', attributes: { name: 'Mars' } })
);
operations.push(
t.addRecord({ type: 'planet', attributes: { name: 'Filtered' } })
);
operations.push(
t.replaceRelatedRecords({ type: 'planet', id: plutoId }, 'moons', moons)
);
return operations;
});
}
async model() {
return this.store.cache.liveQuery((qb) => qb.findRecords('planet'));
}
}
| import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
export default class FilteredRoute extends Route {
@service store;
async beforeModel() {
await this.store.update((t) => {
const blueMoonId = this.store.schema.generateId('moon');
const newMoonId = this.store.schema.generateId('moon');
const plutoId = this.store.schema.generateId('planet');
return [
t.addRecord({
type: 'moon',
id: blueMoonId,
attributes: { name: 'Blue' }
}),
t.addRecord({
type: 'moon',
id: newMoonId,
attributes: { name: 'New' }
}),
t.addRecord({ type: 'planet', attributes: { name: 'Mars' } }),
t.addRecord({ type: 'planet', attributes: { name: 'Filtered' } }),
t.addRecord({
type: 'planet',
id: plutoId,
attributes: { name: 'Pluto' },
relationships: {
moons: {
data: [
{ type: 'moon', id: blueMoonId },
{ type: 'moon', id: newMoonId }
]
}
}
})
];
});
}
async model() {
return this.store.cache.liveQuery((qb) => qb.findRecords('planet'));
}
}
| Simplify test data creation in dummy app | Simplify test data creation in dummy app
| JavaScript | mit | orbitjs/ember-orbit,orbitjs/ember-orbit,orbitjs/ember-orbit | ---
+++
@@ -6,30 +6,37 @@
async beforeModel() {
await this.store.update((t) => {
- const moons = [
- { type: 'moon', attributes: { name: 'Blue' } },
- { type: 'moon', attributes: { name: 'New' } }
+ const blueMoonId = this.store.schema.generateId('moon');
+ const newMoonId = this.store.schema.generateId('moon');
+ const plutoId = this.store.schema.generateId('planet');
+
+ return [
+ t.addRecord({
+ type: 'moon',
+ id: blueMoonId,
+ attributes: { name: 'Blue' }
+ }),
+ t.addRecord({
+ type: 'moon',
+ id: newMoonId,
+ attributes: { name: 'New' }
+ }),
+ t.addRecord({ type: 'planet', attributes: { name: 'Mars' } }),
+ t.addRecord({ type: 'planet', attributes: { name: 'Filtered' } }),
+ t.addRecord({
+ type: 'planet',
+ id: plutoId,
+ attributes: { name: 'Pluto' },
+ relationships: {
+ moons: {
+ data: [
+ { type: 'moon', id: blueMoonId },
+ { type: 'moon', id: newMoonId }
+ ]
+ }
+ }
+ })
];
- const operations = [];
- operations.push(t.addRecord(moons[0]));
- operations.push(t.addRecord(moons[1]));
-
- const plutoOperation = t.addRecord({
- type: 'planet',
- attributes: { name: 'Pluto' }
- });
- const plutoId = plutoOperation.operation.record.id;
- operations.push(plutoOperation);
- operations.push(
- t.addRecord({ type: 'planet', attributes: { name: 'Mars' } })
- );
- operations.push(
- t.addRecord({ type: 'planet', attributes: { name: 'Filtered' } })
- );
- operations.push(
- t.replaceRelatedRecords({ type: 'planet', id: plutoId }, 'moons', moons)
- );
- return operations;
});
}
|
6bd313d195acc26650c361b8c05365dec0a3af29 | scripts/rectangle.js | scripts/rectangle.js | var rectangle = (function (parent) {
var rectangle = Object.create(parent);
Object.defineProperty(rectangle, 'init', {
value: function (xCoordinate, yCoordinate, fill, stroke) {
parent.init.call(this, xCoordinate, yCoordinate, fill, stroke);
return this;
}
});
Object.defineProperty(rectangle, 'update', {
value: function () {
// TODO: Implement this method to move your circle
// Delete this line!
parent.update.call(this);
}
});
Object.defineProperty(rectangle, 'draw', {
value: function (width, height, canvas) {
var canvas = canvas;
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillRect(this.xCoordinate, this.yCoordinate, width, height);
ctx.clearRect(this.xCoordinate, this.yCoordinate, width, height);
ctx.strokeRect(this.xCoordinate, this.yCoordinate, width, height);
}
}
});
return rectangle;
}(gameObject)); | var rectangle = (function (parent) {
var rectangle = Object.create(parent);
Object.defineProperty(rectangle, 'init', {
value: function (xCoordinate, yCoordinate, width, height, fill, stroke) {
parent.init.call(this, xCoordinate, yCoordinate, fill, stroke);
this.width = width;
this.height = height;
return this;
}
});
Object.defineProperty(rectangle, 'width', {
get: function () {
return this._width;
},
set: function (value) {
validator.validateIfPositiveNumber(value, 'width');
this._width = value;
}
});
Object.defineProperty(rectangle, 'height', {
get: function () {
return this._height;
},
set: function (value) {
validator.validateIfPositiveNumber(value, 'height');
this._height = value;
}
});
Object.defineProperty(rectangle, 'update', {
value: function () {
// TODO: Implement this method to move your circle
// Delete this line!
parent.update.call(this);
}
});
// This method binds rectangle with canvas! The rectangle should not know how to draw itself!
Object.defineProperty(rectangle, 'draw', {
value: function (width, height, canvas) {
var canvas = canvas;
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillRect(this.xCoordinate, this.yCoordinate, width, height);
ctx.clearRect(this.xCoordinate, this.yCoordinate, width, height);
ctx.strokeRect(this.xCoordinate, this.yCoordinate, width, height);
}
}
});
return rectangle;
}(gameObject)); | Add properties width and height to rectngle | Add properties width and height to rectngle
| JavaScript | mit | TeamMoscowMule/MultitaskGame,TeamMoscowMule/MultitaskGame | ---
+++
@@ -2,10 +2,32 @@
var rectangle = Object.create(parent);
Object.defineProperty(rectangle, 'init', {
- value: function (xCoordinate, yCoordinate, fill, stroke) {
+ value: function (xCoordinate, yCoordinate, width, height, fill, stroke) {
parent.init.call(this, xCoordinate, yCoordinate, fill, stroke);
+ this.width = width;
+ this.height = height;
return this;
+ }
+ });
+
+ Object.defineProperty(rectangle, 'width', {
+ get: function () {
+ return this._width;
+ },
+ set: function (value) {
+ validator.validateIfPositiveNumber(value, 'width');
+ this._width = value;
+ }
+ });
+
+ Object.defineProperty(rectangle, 'height', {
+ get: function () {
+ return this._height;
+ },
+ set: function (value) {
+ validator.validateIfPositiveNumber(value, 'height');
+ this._height = value;
}
});
@@ -18,6 +40,7 @@
}
});
+ // This method binds rectangle with canvas! The rectangle should not know how to draw itself!
Object.defineProperty(rectangle, 'draw', {
value: function (width, height, canvas) {
var canvas = canvas; |
aec2dd3853efe31c06373c6b999b4f2a9451debf | src/connect/index.js | src/connect/index.js | import Socket from './socket'
import { actions } from '../store/actions'
import {
supportsWebSockets,
supportsGetUserMedia
} from '../utils/feature-detection'
const {
setToken,
setWebSocketSupport,
setGumSupport,
setAuthenticated
} = actions
function setSupport() {
setWebSocketSupport(supportsWebSockets)
setGumSupport(supportsGetUserMedia)
}
export default function connect(jwt) {
setSupport()
if (supportsWebSockets) {
const socket = new Socket
socket.connect(jwt)
setToken(jwt)
setAuthenticated(true)
return socket
} else {
// console.warn('WebSockets not supported')
}
}
| import Socket from './socket'
import { actions } from '../store/actions'
import {
supportsWebSockets,
supportsGetUserMedia
} from '../utils/feature-detection'
const { setWebSocketSupport, setGumSupport } = actions
function setSupport() {
setWebSocketSupport(supportsWebSockets)
setGumSupport(supportsGetUserMedia)
}
export default function connect(jwt) {
setSupport()
try {
if (!supportsWebSockets) throw 'WebSockets not supported'
const socket = new Socket
socket.connect(jwt)
return socket
}
catch(err) {
console.log(err)
}
}
| Use try/catch for initiating WebSocket | Use try/catch for initiating WebSocket
| JavaScript | mit | onfido/onfido-sdk-core | ---
+++
@@ -5,12 +5,7 @@
supportsGetUserMedia
} from '../utils/feature-detection'
-const {
- setToken,
- setWebSocketSupport,
- setGumSupport,
- setAuthenticated
-} = actions
+const { setWebSocketSupport, setGumSupport } = actions
function setSupport() {
setWebSocketSupport(supportsWebSockets)
@@ -19,13 +14,13 @@
export default function connect(jwt) {
setSupport()
- if (supportsWebSockets) {
+ try {
+ if (!supportsWebSockets) throw 'WebSockets not supported'
const socket = new Socket
socket.connect(jwt)
- setToken(jwt)
- setAuthenticated(true)
return socket
- } else {
- // console.warn('WebSockets not supported')
+ }
+ catch(err) {
+ console.log(err)
}
} |
6d53471a7ba379fb95e5af04fca2a1b7602afd4e | src/lock/renderer.js | src/lock/renderer.js | import ContainerManager from './container_manager';
import { LockModes } from '../control/constants';
import renderCrashed from '../crashed/render';
import renderPasswordlessEmail from '../passwordless-email/render';
import renderPasswordlessSMS from '../passwordless-sms/render';
import React from 'react';
import * as l from './index';
export default class Renderer {
constructor() {
this.containerManager = new ContainerManager();
}
render(locks) {
locks.filter(l.render).forEach(lock => {
const container = this.containerManager.ensure(l.ui.containerID(lock), l.ui.appendContainer(lock));
if (lock.get("show")) {
React.render(this.element(lock), container);
} else if (container) {
React.unmountComponentAtNode(container);
}
});
}
element(lock) {
// TODO: mode specific renderer specs should be passed to the constructor
const mode = lock.get("mode");
switch(mode) {
case LockModes.CRASHED:
return renderCrashed(lock);
case LockModes.PASSWORDLESS_EMAIL:
return renderPasswordlessEmail(lock);
case LockModes.PASSWORDLESS_SMS:
return renderPasswordlessSMS(lock);
default:
throw new Error(`unknown lock mode ${mode}`);
}
}
}
| import ContainerManager from './container_manager';
import { LockModes } from '../control/constants';
import renderCrashed from '../crashed/render';
import renderPasswordlessEmail from '../passwordless-email/render';
import renderPasswordlessSMS from '../passwordless-sms/render';
import React from 'react';
import * as l from './index';
export default class Renderer {
constructor() {
this.containerManager = new ContainerManager();
}
render(locks) {
locks.filter(l.render).forEach(lock => {
const container = this.containerManager.ensure(l.ui.containerID(lock), l.ui.appendContainer(lock));
if (lock.get("show")) {
React.render(this.element(lock), container);
} else if (container) {
React.unmountComponentAtNode(container);
}
});
}
element(lock) {
// TODO: mode specific renderer specs should be passed to the constructor
const mode = lock.get("mode");
switch(mode) {
case LockModes.CRASHED:
return renderCrashed(lock);
case LockModes.PASSWORDLESS_EMAIL:
return renderPasswordlessEmail(lock);
// case LockModes.PASSWORDLESS_SMS:
// return renderPasswordlessSMS(lock);
default:
throw new Error(`unknown lock mode ${mode}`);
}
}
}
| Disable passwordless sms mode for now | Disable passwordless sms mode for now
| JavaScript | mit | mike-casas/lock,auth0/lock-passwordless,mike-casas/lock,auth0/lock-passwordless,mike-casas/lock,auth0/lock-passwordless | ---
+++
@@ -31,8 +31,8 @@
return renderCrashed(lock);
case LockModes.PASSWORDLESS_EMAIL:
return renderPasswordlessEmail(lock);
- case LockModes.PASSWORDLESS_SMS:
- return renderPasswordlessSMS(lock);
+ // case LockModes.PASSWORDLESS_SMS:
+ // return renderPasswordlessSMS(lock);
default:
throw new Error(`unknown lock mode ${mode}`);
} |
2e5a22e1736cfa663dc38f7e3a3851c67e8e56bb | src/marbles/state.js | src/marbles/state.js | //= require ./core
(function () {
"use strict";
/*
* State object mixin
*
* Requires Object `state` and Array `__changeListeners` properties
*/
Marbles.State = {
addChangeListener: function (handler) {
this.__changeListeners.push(handler);
},
removeChangeListener: function (handler) {
this.__changeListeners = this.__changeListeners.filter(function (fn) {
return fn !== handler;
});
},
setState: function (newState) {
var state = this.state;
Object.keys(newState).forEach(function (key) {
state[key] = newState[key];
});
this.handleChange();
},
replaceState: function (newState) {
this.state = newState;
this.handleChange();
},
handleChange: function () {
this.__changeListeners.forEach(function (handler) {
handler();
});
}
};
})();
| //= require ./core
(function () {
"use strict";
/*
* State object mixin
*
* Requires Object `state` and Array `__changeListeners` properties
*/
Marbles.State = {
addChangeListener: function (handler) {
this.__changeListeners.push(handler);
},
removeChangeListener: function (handler) {
this.__changeListeners = this.__changeListeners.filter(function (fn) {
return fn !== handler;
});
},
setState: function (newState) {
this.willUpdate();
var state = this.state;
Object.keys(newState).forEach(function (key) {
state[key] = newState[key];
});
this.handleChange();
this.didUpdate();
},
replaceState: function (newState) {
this.willUpdate();
this.state = newState;
this.handleChange();
this.didUpdate();
},
handleChange: function () {
this.__changeListeners.forEach(function (handler) {
handler();
});
},
willUpdate: function () {},
didUpdate: function () {}
};
})();
| Update Marbles.State: Add willUpdate/didUpdate hooks | Update Marbles.State: Add willUpdate/didUpdate hooks
| JavaScript | bsd-3-clause | jvatic/marbles-js,jvatic/marbles-js | ---
+++
@@ -21,23 +21,31 @@
},
setState: function (newState) {
+ this.willUpdate();
var state = this.state;
Object.keys(newState).forEach(function (key) {
state[key] = newState[key];
});
this.handleChange();
+ this.didUpdate();
},
replaceState: function (newState) {
+ this.willUpdate();
this.state = newState;
this.handleChange();
+ this.didUpdate();
},
handleChange: function () {
this.__changeListeners.forEach(function (handler) {
handler();
});
- }
+ },
+
+ willUpdate: function () {},
+
+ didUpdate: function () {}
};
})(); |
ea6c13ef83ff7d7179ff43d23c71232dc93daf58 | server/controller.js | server/controller.js | var GameInfo = require('module');
'use stricts';
/*
* Render th first page
*/
exports.index = function(req, res){
res.render('index'{
user : req.user || null
});
}
exports.getGame = function(req, res){
var id = req.params.id
Game.findOne({_id:id},function(game,err){
if (err){res.send(err);}
else{res.jsonp(game);}
});
}
exports.createGame = function(req, res){
res.render('game'{
user : req.user || null
});
}
exports.deleteGame = function(req, res){
var id = req.params.id
Game.delete({_id:id},function(game,err){
if (err){res.send(err);}
else{res.jsonp(game);}
});
}
exports.updateGame = function(req, res){
res.render('game'{
user : req.user || null
});
}
exports.displayGame = function(req, res){
var id = req.params.id
Game.findOne({_id:id},function(game,err){
if (err){res.send(err);}
else{res.jsonp(game);}
});
}
exports.showList = function(req, res){
res.render('page'{
user : req.user || null
});
}
| var GameInfo = require('models/game-info.js');
'use stricts';
/*
* Render th first page
*/
exports.index = function(req, res){
res.render('index'{
user : req.user || null
});
}
exports.getGame = function(req, res){
var id = req.params.id
Game.findOne({_id:id},function(game,err){
if (err){res.send(err);}
else{res.jsonp(game);}
});
}
exports.createGame = function(req, res){
res.render('game'{
user : req.user || null
});
}
exports.deleteGame = function(req, res){
var id = req.params.id
Game.delete({_id:id},function(game,err){
if (err){res.send(err);}
else{res.jsonp(game);}
});
}
exports.updateGame = function(req, res){
res.render('game'{
user : req.user || null
});
}
exports.displayGame = function(req, res){
var id = req.params.id
Game.findOne({_id:id},function(game,err){
if (err){res.send(err);}
else{res.jsonp(game);}
});
}
exports.showList = function(req, res){
res.render('page'{
user : req.user || null
});
}
| Correct require to point to models/game-info.js. | Correct require to point to models/game-info.js.
| JavaScript | mit | BerniceChua/landr,BerniceChua/landr,BerniceChua/landr | ---
+++
@@ -1,4 +1,4 @@
-var GameInfo = require('module');
+var GameInfo = require('models/game-info.js');
'use stricts';
|
ec9ab13ec943bc021e7359654f16beea38d896ab | server/static/app.js | server/static/app.js | var maxLength = 20;
var pendingRequest = undefined;
function updateResults(e) {
if (e.which === 0) {
return;
}
var query = $("#query").val();
if (pendingRequest) {
pendingRequest.abort();
}
pendingRequest = $.getJSON(
"/search",
{query: query},
function processQueryResult(data) {
$("#results").html("");
for (var x=0; x<data.length; x++) {
var post = data[x];
showImage(x, post);
if (x >= maxLength) {
showImage(x, {
title: "Refine your search for more results"
});
break;
}
}
$('img.result-img').lazyload({
effect: "fadeIn",
threshold: 1000,
skip_invisible: true
});
}
);
}
function showImage(x, postData) {
var postHTML = '<div id="post' + x + '" class="result">';
postHTML += '<h2>';
if (postData.url) postHTML += '<a href="' + postData.url + '">';
postHTML += postData.title;
if (postData.url) postHTML += '</a></h2>';
if (postData.image) postHTML += '<img data-original="' + postData.image + '" class="result-img" />';
postHTML += '</div>';
$("#results").append(postHTML);
}
$("#query").keypress(updateResults);
| var maxLength = 20;
var pendingRequest = undefined;
function updateResults(e) {
var query = $("#query").val();
if (pendingRequest) {
pendingRequest.abort();
}
pendingRequest = $.getJSON(
"/search",
{query: query},
function processQueryResult(data) {
$("#results").html("");
for (var x=0; x<data.length; x++) {
var post = data[x];
showImage(x, post);
if (x >= maxLength) {
showImage(x, {
title: "Refine your search for more results"
});
break;
}
}
$('img.result-img').lazyload({
effect: "fadeIn",
threshold: 1000,
skip_invisible: true
});
}
);
}
function showImage(x, postData) {
var postHTML = '<div id="post' + x + '" class="result">';
postHTML += '<h2>';
if (postData.url) postHTML += '<a href="' + postData.url + '">';
postHTML += postData.title;
if (postData.url) postHTML += '</a></h2>';
if (postData.image) postHTML += '<img data-original="' + postData.image + '" class="result-img" />';
postHTML += '</div>';
$("#results").append(postHTML);
}
$("#query").on('input', updateResults);
| Make site be more responsive to all changes to input box | Make site be more responsive to all changes to input box
| JavaScript | mit | albertyw/reaction-pics,albertyw/devops-reactions-index,albertyw/reaction-pics,albertyw/reaction-pics,albertyw/devops-reactions-index,albertyw/devops-reactions-index,albertyw/devops-reactions-index,albertyw/reaction-pics | ---
+++
@@ -2,9 +2,6 @@
var pendingRequest = undefined;
function updateResults(e) {
- if (e.which === 0) {
- return;
- }
var query = $("#query").val();
if (pendingRequest) {
pendingRequest.abort();
@@ -44,4 +41,4 @@
$("#results").append(postHTML);
}
-$("#query").keypress(updateResults);
+$("#query").on('input', updateResults); |
586f20a78d81fa6297f5cd1226ec43a827f70346 | PuppyPlayDate/MapScene.js | PuppyPlayDate/MapScene.js | import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TabBarIOS,
Dimensions,
Image,
TouchableHighlight
} from 'react-native';
import MapView from 'react-native-maps';
var { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 37.7;
const LONGITUDE = -122.2;
const LATITUDE_DELTA = 1.2;
const LONGITUDE_DELTA = 1.2;
class MapScene extends Component {
render() {
return (
<View>
<MapView
style={styles.map}
initialRegion={{
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
}}
mapType={'standard'}
>
</MapView>
</View>
)}
}
const styles = StyleSheet.create({
map: {
flex: 1,
width: width,
height: height,
borderWidth: 1,
}
});
module.exports = MapScene;
| import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TabBarIOS,
Dimensions,
Image,
TouchableHighlight
} from 'react-native';
import MapView from 'react-native-maps';
var { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = 0.0421;
class MapScene extends Component {
render() {
var pins = [{
latitude: 37.78482573289199,
longitude: -122.4023278109328
}];
return (
<MapView
annotations={pins}
onRegionChangeComplete={this.onRegionChangeComplete}
style={styles.map}
initialRegion={{
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
}}
mapType={'standard'}
>
</MapView>
)};
onRegionChangeComplete(region) {
console.log(region);
}
};
const styles = StyleSheet.create({
map: {
flex: 1,
width: width,
height: height,
borderWidth: 1,
}
});
module.exports = MapScene;
| Work on placing pins on map | Work on placing pins on map
| JavaScript | mit | Tooconfident/Puppy_PlayDate,Tooconfident/Puppy_PlayDate,Tooconfident/Puppy_PlayDate | ---
+++
@@ -16,29 +16,36 @@
var { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
-const LATITUDE = 37.7;
-const LONGITUDE = -122.2;
-const LATITUDE_DELTA = 1.2;
-const LONGITUDE_DELTA = 1.2;
+const LATITUDE = 37.78825;
+const LONGITUDE = -122.4324;
+const LATITUDE_DELTA = 0.0922;
+const LONGITUDE_DELTA = 0.0421;
class MapScene extends Component {
render() {
+ var pins = [{
+ latitude: 37.78482573289199,
+ longitude: -122.4023278109328
+ }];
return (
- <View>
- <MapView
- style={styles.map}
- initialRegion={{
- latitude: LATITUDE,
- longitude: LONGITUDE,
- latitudeDelta: LATITUDE_DELTA,
- longitudeDelta: LONGITUDE_DELTA,
- }}
- mapType={'standard'}
- >
- </MapView>
- </View>
- )}
-}
+ <MapView
+ annotations={pins}
+ onRegionChangeComplete={this.onRegionChangeComplete}
+ style={styles.map}
+ initialRegion={{
+ latitude: LATITUDE,
+ longitude: LONGITUDE,
+ latitudeDelta: LATITUDE_DELTA,
+ longitudeDelta: LONGITUDE_DELTA,
+ }}
+ mapType={'standard'}
+ >
+ </MapView>
+ )};
+ onRegionChangeComplete(region) {
+ console.log(region);
+ }
+};
const styles = StyleSheet.create({
map: { |
703fc7dfdae14382b5937dee9f51673f8cec8452 | test/support/server_options.js | test/support/server_options.js | var _ = require('underscore');
module.exports = function(opts) {
var config = {
base_url: '/database/:dbname/table/:table',
grainstore: {datasource: global.environment.postgres},
redis: global.environment.redis,
enable_cors: global.environment.enable_cors,
unbuffered_logging: true, // for smoother teardown from tests
req2params: function(req, callback){
// no default interactivity. to enable specify the database column you'd like to interact with
req.params.interactivity = null;
// this is in case you want to test sql parameters eg ...png?sql=select * from my_table limit 10
req.params = _.extend({}, req.params);
_.extend(req.params, req.query);
// send the finished req object on
callback(null,req);
},
beforeTileRender: function(req, res, callback) {
res.header('X-BeforeTileRender', 'called');
callback(null);
},
afterTileRender: function(req, res, tile, headers, callback) {
res.header('X-AfterTileRender','called');
headers['X-AfterTileRender2'] = 'called';
callback(null, tile, headers);
}
}
_.extend(config, opts || {});
return config;
}();
| var _ = require('underscore');
module.exports = function(opts) {
var config = {
base_url: '/database/:dbname/table/:table',
grainstore: {datasource: global.environment.postgres},
redis: global.environment.redis,
enable_cors: global.environment.enable_cors,
unbuffered_logging: true, // for smoother teardown from tests
log_format: null, // do not log anything
req2params: function(req, callback){
// no default interactivity. to enable specify the database column you'd like to interact with
req.params.interactivity = null;
// this is in case you want to test sql parameters eg ...png?sql=select * from my_table limit 10
req.params = _.extend({}, req.params);
_.extend(req.params, req.query);
// send the finished req object on
callback(null,req);
},
beforeTileRender: function(req, res, callback) {
res.header('X-BeforeTileRender', 'called');
callback(null);
},
afterTileRender: function(req, res, tile, headers, callback) {
res.header('X-AfterTileRender','called');
headers['X-AfterTileRender2'] = 'called';
callback(null, tile, headers);
}
}
_.extend(config, opts || {});
return config;
}();
| Disable logging while running tests | Disable logging while running tests
| JavaScript | bsd-3-clause | manueltimita/Windshaft,HydroLogic/Windshaft,CartoDB/Windshaft,CartoDB/Windshaft,wsw0108/Windshaft,CartoDB/Windshaft,manueltimita/Windshaft,HydroLogic/Windshaft,wsw0108/Windshaft,HydroLogic/Windshaft,wsw0108/Windshaft,manueltimita/Windshaft | ---
+++
@@ -8,6 +8,7 @@
redis: global.environment.redis,
enable_cors: global.environment.enable_cors,
unbuffered_logging: true, // for smoother teardown from tests
+ log_format: null, // do not log anything
req2params: function(req, callback){
// no default interactivity. to enable specify the database column you'd like to interact with |
9b7ea9dd8ef731e9c38436bbb58317203b477859 | api/src/hooks/errors.js | api/src/hooks/errors.js | import { UniqueViolationError } from 'objection-db-errors'
import { FeathersError, Conflict, GeneralError } from '@feathersjs/errors'
const errorHandler = (ctx) => {
if (!ctx.error) {
return
}
if (ctx.error instanceof UniqueViolationError) {
const error = new Conflict('Unique Violation Error')
error.errors = ctx.error.columns
throw error
}
if (ctx.error instanceof FeathersError) {
throw ctx.error
}
throw new GeneralError('unknown error', ctx.error.data)
}
export default errorHandler
| import { UniqueViolationError } from 'objection-db-errors'
import { FeathersError, Conflict, GeneralError } from '@feathersjs/errors'
import _ from 'lodash'
const errorHandler = (ctx) => {
if (!ctx.error) {
return
}
// FIXME currently using console.log to display DB errors
// as app.error doesn't display it
// eslint-disable-next-line no-console
console.log(_.omit(ctx.error, ['hook']))
if (ctx.error instanceof UniqueViolationError) {
const error = new Conflict('Unique Violation Error')
error.errors = ctx.error.columns
throw error
}
if (ctx.error instanceof FeathersError) {
throw ctx.error
}
throw new GeneralError('unknown error', ctx.error.data)
}
export default errorHandler
| Add workaround to display DB error log. | Add workaround to display DB error log.
| JavaScript | agpl-3.0 | teikei/teikei,teikei/teikei,teikei/teikei | ---
+++
@@ -1,10 +1,15 @@
import { UniqueViolationError } from 'objection-db-errors'
import { FeathersError, Conflict, GeneralError } from '@feathersjs/errors'
+import _ from 'lodash'
const errorHandler = (ctx) => {
if (!ctx.error) {
return
}
+ // FIXME currently using console.log to display DB errors
+ // as app.error doesn't display it
+ // eslint-disable-next-line no-console
+ console.log(_.omit(ctx.error, ['hook']))
if (ctx.error instanceof UniqueViolationError) {
const error = new Conflict('Unique Violation Error')
error.errors = ctx.error.columns |
5059ee00e4d492de354f0442a5c8293e15a56075 | app/bootstrap/server.js | app/bootstrap/server.js | 'use strict'
const config = require('./config')
const db = require('./db')
const app = require('../http/app')
db.init(config.dbUrl, 'shortlinks').then(() => {
app.listen(config.port, () => {
console.log('Server listening on port ' + config.port + '…')
})
}).catch((error) => {
console.log('>>> Error during database initialization:\n')
console.log(error)
process.exit(1)
})
| 'use strict'
const config = require('./config')
const db = require('./db')
const app = require('../http/app')
console.log('#'.repeat(40))
console.log((new Date()).toUTCString())
db.init(config.dbUrl, 'shortlinks').then(() => {
app.listen(config.port, () => {
console.log('Server listening on port ' + config.port + '…')
})
}).catch((error) => {
console.log('>>> Error during database initialization:\n')
console.log(error)
process.exit(1)
})
| Add separator in logfile and application start time | Add separator in logfile and application start time
| JavaScript | mit | jotaen/j4n.io,jotaen/j4n.io | ---
+++
@@ -3,6 +3,9 @@
const config = require('./config')
const db = require('./db')
const app = require('../http/app')
+
+console.log('#'.repeat(40))
+console.log((new Date()).toUTCString())
db.init(config.dbUrl, 'shortlinks').then(() => {
app.listen(config.port, () => { |
02bc73aac9b1a616dcdcbdcd418254efd0af4ce1 | seeders/20220928200618-subarea.js | seeders/20220928200618-subarea.js | 'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
queryInterface.bulkInsert("Subareas", [{
id: 1,
name: "Alpha",
color: Math.floor(Math.random() * 16777215).toString(16)
}, {
id: 2,
name: "Bravo",
color: Math.floor(Math.random() * 16777215).toString(16)
}, {
id: 3,
name: "Charlie",
color: Math.floor(Math.random() * 16777215).toString(16)
}, {
id: 4,
name: "Delta",
color: Math.floor(Math.random() * 16777215).toString(16)
}, {
id: 5,
name: "Echo",
color: Math.floor(Math.random() * 16777215).toString(16)
}, {
id: 6,
name: "Foxtrot",
color: Math.floor(Math.random() * 16777215).toString(16)
}, {
id: 7,
name: "Onbekend",
color: Math.floor(Math.random() * 16777215).toString(16)
}]);
},
async down(queryInterface, Sequelize) {
/**
* Add commands to revert seed here.
*
* Example:
* await queryInterface.bulkDelete('People', null, {});
*/
await queryInterface.bulkDelete('Subareas', null, {});
}
}; | 'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
queryInterface.bulkInsert("Subareas", [{
id: 1,
name: "Alpha",
color: "DFFF00"
}, {
id: 2,
name: "Bravo",
color: "FFBF00"
}, {
id: 3,
name: "Charlie",
color: "9FE2BF"
}, {
id: 4,
name: "Delta",
color: "FF7F50"
}, {
id: 5,
name: "Echo",
color: "40E0D0"
}, {
id: 6,
name: "Foxtrot",
color: "DE3163"
}, {
id: 7,
name: "Onbekend",
color: Math.floor(Math.random() * 16777215).toString(16)
}]);
},
async down(queryInterface, Sequelize) {
/**
* Add commands to revert seed here.
*
* Example:
* await queryInterface.bulkDelete('People', null, {});
*/
await queryInterface.bulkDelete('Subareas', null, {});
}
}; | Add better visible subarea colors | Add better visible subarea colors
| JavaScript | mit | ScoutingIJsselgroep/Jotihunt,ScoutingIJsselgroep/Jotihunt,ScoutingIJsselgroep/Jotihunt | ---
+++
@@ -6,27 +6,27 @@
queryInterface.bulkInsert("Subareas", [{
id: 1,
name: "Alpha",
- color: Math.floor(Math.random() * 16777215).toString(16)
+ color: "DFFF00"
}, {
id: 2,
name: "Bravo",
- color: Math.floor(Math.random() * 16777215).toString(16)
+ color: "FFBF00"
}, {
id: 3,
name: "Charlie",
- color: Math.floor(Math.random() * 16777215).toString(16)
+ color: "9FE2BF"
}, {
id: 4,
name: "Delta",
- color: Math.floor(Math.random() * 16777215).toString(16)
+ color: "FF7F50"
}, {
id: 5,
name: "Echo",
- color: Math.floor(Math.random() * 16777215).toString(16)
+ color: "40E0D0"
}, {
id: 6,
name: "Foxtrot",
- color: Math.floor(Math.random() * 16777215).toString(16)
+ color: "DE3163"
}, {
id: 7,
name: "Onbekend", |
6702552092059a52ab3ad3bc1c5b7c62a4ddcdcc | Resources/app.js | Resources/app.js | /**
* Copyright (c) 2014 by Center Open Middleware. All Rights Reserved.
* Titanium Appcelerator 3.3.0GA
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*
* App Base Development Framework Team
*
* Alejandro F.Carrera
* Carlos Blanco Vallejo
* Santiago Blanco Ventas
*
*/
"use strict";
// Yaast Framework Init (Global Scope)
var Yaast = {
"Log": function(msg, type, error, extra){
var self = {
'name': 'W4TLog',
'message': msg
};
if(error){
self.details = (extra) ? {
'message': error.message,
'info': extra
} : error.message;
self.source = error.sourceURL;
}
Ti.API[type](self);
return self;
},
"MergeObject": function (obj1, obj2){
var result = null, key;
if (obj1 !== null && obj2 !== null){
for (key in obj2){
obj1[key] = obj2[key];
}
result = obj1;
}
return result;
},
"FontAwesome": require('fonts/FontAwesome4'),
"API": require('lib/API'),
"Sandbox": {
'currentView': null
}
};
(function() {
if (Yaast.API.HW.System.isTablet()) {
var Window = require('ui/window/appWindow');
Window.window.open();
}
else alert("Wirecloud4Tablet has not compatibility with Smartphone's'");
}()); | /**
* Copyright (c) 2014 by Center Open Middleware. All Rights Reserved.
* Titanium Appcelerator 3.3.0GA
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*
* App Base Development Framework Team
*
* Alejandro F.Carrera
* Carlos Blanco Vallejo
* Santiago Blanco Ventas
*
*/
"use strict";
// Yaast Framework Init (Global Scope)
var Yaast = {
"Log": function(msg, type, error, extra) {
var self = {
'name': 'W4TLog',
'message': msg
};
if(error) {
self.details = (extra) ? {
'message': error.message,
'info': extra
} : error.message;
self.source = error.sourceURL;
}
Ti.API[type](self);
return self;
},
"FontAwesome": require('fonts/FontAwesome4'),
"API": require('lib/API'),
"Sandbox": {
'currentView': null
}
};
// Merge shortcut
Yaast["MergeObject"] = Yaast.API.SW.Utils.mergeObject;
(function() {
if (Yaast.API.HW.System.isTablet()) {
var Window = require('ui/window/appWindow');
Window.window.open();
}
else alert("Wirecloud4Tablet has not compatibility with Smartphone's'");
}()); | Use API Deep Merge in all w4t | Use API Deep Merge in all w4t
| JavaScript | apache-2.0 | Wirecloud/wirecloud-mobile,Wirecloud/wirecloud-mobile | ---
+++
@@ -16,12 +16,12 @@
// Yaast Framework Init (Global Scope)
var Yaast = {
- "Log": function(msg, type, error, extra){
+ "Log": function(msg, type, error, extra) {
var self = {
'name': 'W4TLog',
'message': msg
};
- if(error){
+ if(error) {
self.details = (extra) ? {
'message': error.message,
'info': extra
@@ -31,22 +31,14 @@
Ti.API[type](self);
return self;
},
- "MergeObject": function (obj1, obj2){
- var result = null, key;
- if (obj1 !== null && obj2 !== null){
- for (key in obj2){
- obj1[key] = obj2[key];
- }
- result = obj1;
- }
- return result;
- },
"FontAwesome": require('fonts/FontAwesome4'),
"API": require('lib/API'),
"Sandbox": {
'currentView': null
}
};
+// Merge shortcut
+Yaast["MergeObject"] = Yaast.API.SW.Utils.mergeObject;
(function() {
@@ -55,5 +47,5 @@
Window.window.open();
}
else alert("Wirecloud4Tablet has not compatibility with Smartphone's'");
-
+
}()); |
6ba19e069a2a8a7cd4074c8a9d7bda5df3d59faa | public/javascripts/admin.js | public/javascripts/admin.js | /**
* Created by meysamabl on 11/1/14.
*/
$(document).ready(function () {
// $('#picture').change(function () {
// $("#catForm").ajaxForm({ target: "#image_view" }).submit();
// return false;
// });
$("#level2Parent").hide();
$("#level1").change(function (e) {
e.preventDefault();
var form = $(this).closest('form');
var url = form.attr("action");
var id = $("#level1").val();
if ($("#level1").val() != "") {
$("#level2Parent").show();
jsRoutes.controllers.Administration.getSubCategories(id).ajax({
dataType: 'json',
success: function (data) {
$('#level2').empty();
$('#level2').append($('<option>').text(Messages('chooseCategory')).attr('value', null));
console.info(data);
$.each(data, function(i, value) {
$('#level2').append($('<option>').text(value).attr('value', value));
});
},
error: function () {
alert("Error!")
}
})
} else {
$("#level2Parent").hide();
$("#level2").val("");
}
})
});
| /**
* Created by meysamabl on 11/1/14.
*/
$(document).ready(function () {
// $('#picture').change(function () {
// $("#catForm").ajaxForm({ target: "#image_view" }).submit();
// return false;
// });
$("#level2Parent").hide();
$("#level1").change(function (e) {
e.preventDefault();
var id = $("#level1").val();
if (id != "") {
$("#level2Parent").show();
jsRoutes.controllers.Administration.getSubCategories(id).ajax({
dataType: 'json',
success: function (data) {
$('#level2').empty();
$('#level2').append($('<option>').text(Messages('chooseCategory')).attr('value', ""));
$.each(data, function(i, value) {
$('#level2').append($('<option>').text(value).attr('value', i));
});
},
error: function () {
alert("Error!")
}
})
} else {
$("#level2Parent").hide();
$("#level2").val("");
}
})
$("#level2").change(function() {
var id = $("#level2").val();
if(id != "") {
$("#level1").removeAttr("name");
} else {
$("#level1").attr('name', 'parentCategory');
}
})
});
| Fix The bug in createCategory, Now can save subcategories with no problem | Fix The bug in createCategory, Now can save subcategories with no problem
| JavaScript | apache-2.0 | zarest/zarest-commerce,zarest/zarest-commerce | ---
+++
@@ -11,19 +11,16 @@
$("#level2Parent").hide();
$("#level1").change(function (e) {
e.preventDefault();
- var form = $(this).closest('form');
- var url = form.attr("action");
var id = $("#level1").val();
- if ($("#level1").val() != "") {
+ if (id != "") {
$("#level2Parent").show();
jsRoutes.controllers.Administration.getSubCategories(id).ajax({
dataType: 'json',
success: function (data) {
$('#level2').empty();
- $('#level2').append($('<option>').text(Messages('chooseCategory')).attr('value', null));
- console.info(data);
+ $('#level2').append($('<option>').text(Messages('chooseCategory')).attr('value', ""));
$.each(data, function(i, value) {
- $('#level2').append($('<option>').text(value).attr('value', value));
+ $('#level2').append($('<option>').text(value).attr('value', i));
});
},
@@ -37,4 +34,12 @@
$("#level2").val("");
}
})
+ $("#level2").change(function() {
+ var id = $("#level2").val();
+ if(id != "") {
+ $("#level1").removeAttr("name");
+ } else {
+ $("#level1").attr('name', 'parentCategory');
+ }
+ })
}); |
fd29d12c536bc3163b9e28dbde5a4c7cad0671fe | client/templates/post/post_page.js | client/templates/post/post_page.js | Template.postPage.onCreated( () => {
var t = Template.instance();
t.subscribe('listForId',FlowRouter.getParam('id'));
});
Template.postPage.helpers({
post: () => {
return List.findOne();
}
}); | Template.postPage.onCreated( () => {
var t = Template.instance();
t.post_id = FlowRouter.getParam('id');
t.autorun(()=>{
t.subscribe('listForId', t.post_id );
});
});
Template.postPage.helpers({
post() {
return List.findOne();
}
}); | Put subscription on autorun in postPage. | Put subscription on autorun in postPage.
| JavaScript | mit | lnwKodeDotCom/WeCode,lnwKodeDotCom/WeCode | ---
+++
@@ -1,10 +1,13 @@
Template.postPage.onCreated( () => {
var t = Template.instance();
- t.subscribe('listForId',FlowRouter.getParam('id'));
+ t.post_id = FlowRouter.getParam('id');
+ t.autorun(()=>{
+ t.subscribe('listForId', t.post_id );
+ });
});
Template.postPage.helpers({
- post: () => {
+ post() {
return List.findOne();
}
}); |
8f1ca887f0d020cecf9e90777bea49cd18d86551 | js/src/admin/index.js | js/src/admin/index.js | import app from 'flarum/app';
import AkismetSettingsModal from './components/AkismetSettingsModal';
app.initializers.add('flarum-akismet', () => {
app.extensionSettings['flarum-akismet'] = () => app.modal.show(new AkismetSettingsModal());
});
| import app from 'flarum/app';
import AkismetSettingsModal from './components/AkismetSettingsModal';
app.initializers.add('flarum-akismet', () => {
app.extensionSettings['flarum-akismet'] = () => app.modal.show(AkismetSettingsModal);
});
| Fix extension to work with latest state changes | Fix extension to work with latest state changes
| JavaScript | mit | flarum/flarum-ext-akismet,flarum/flarum-ext-akismet | ---
+++
@@ -3,5 +3,5 @@
import AkismetSettingsModal from './components/AkismetSettingsModal';
app.initializers.add('flarum-akismet', () => {
- app.extensionSettings['flarum-akismet'] = () => app.modal.show(new AkismetSettingsModal());
+ app.extensionSettings['flarum-akismet'] = () => app.modal.show(AkismetSettingsModal);
}); |
b771c8eee6f2d607b643bf0231eb967b1f63e1f3 | routing/stores/TimeStore.js | routing/stores/TimeStore.js | /**
* Copyright 2014, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
'use strict';
var createStore = require('fluxible-app/utils/createStore');
var TimeStore = createStore({
storeName: 'TimeStore',
initialize: function (dispatcher) {
this.time = new Date();
},
handleTimeChange: function (payload) {
this.time = new Date();
this.emit('change');
},
handlers: {
'CHANGE_ROUTE_START': 'handleTimeChange',
'UPDATE_TIME': 'handleTimeChange'
},
getState: function () {
return {
time: this.time.toString()
};
},
dehydrate: function () {
return this.getState();
},
rehydrate: function (state) {
this.time = new Date(state.time);
}
});
module.exports = TimeStore;
| /**
* Copyright 2014, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
'use strict';
var createStore = require('fluxible-app/utils/createStore');
var TimeStore = createStore({
storeName: 'TimeStore',
initialize: function (dispatcher) {
this.time = new Date();
},
handleTimeChange: function (payload) {
this.time = new Date();
this.emitChange();
},
handlers: {
'CHANGE_ROUTE_START': 'handleTimeChange',
'UPDATE_TIME': 'handleTimeChange'
},
getState: function () {
return {
time: this.time.toString()
};
},
dehydrate: function () {
return this.getState();
},
rehydrate: function (state) {
this.time = new Date(state.time);
}
});
module.exports = TimeStore;
| Use this.emitChange() instead of old API | Use this.emitChange() instead of old API | JavaScript | bsd-3-clause | jeffreywescott/flux-examples,joshbedo/flux-examples,JonnyCheng/flux-examples,devypt/flux-examples,ybbkrishna/flux-examples,src-code/flux-examples,michaelBenin/flux-examples,eriknyk/flux-examples | ---
+++
@@ -13,7 +13,7 @@
},
handleTimeChange: function (payload) {
this.time = new Date();
- this.emit('change');
+ this.emitChange();
},
handlers: {
'CHANGE_ROUTE_START': 'handleTimeChange', |
0e0defaf7ed906386c0c348b18252e8a308dbc3c | addon/classes/resolve-async-value.js | addon/classes/resolve-async-value.js | import { tracked } from '@glimmer/tracking';
import { Resource } from 'ember-could-get-used-to-this';
export default class ResolveAsyncValueResource extends Resource {
@tracked data;
get value() {
return this.data;
}
async setup() {
this.data = await this.args.positional[0];
}
}
| import { tracked } from '@glimmer/tracking';
import { Resource } from 'ember-could-get-used-to-this';
export default class ResolveAsyncValueResource extends Resource {
@tracked data;
get value() {
return this.data;
}
async setup() {
//when a second value is passed it is the default until the promise gets resolved
if (this.args.positional.length > 1) {
this.data = this.args.positional[1];
}
this.data = await this.args.positional[0];
}
}
| Add a default value to resolve async helper | Add a default value to resolve async helper
This allows passing an array or null in to ensure some expected value
will exist when this is `@use`ed in another component and alleviating the
need for an interim getter.
| JavaScript | mit | ilios/common,ilios/common | ---
+++
@@ -8,6 +8,11 @@
}
async setup() {
+ //when a second value is passed it is the default until the promise gets resolved
+ if (this.args.positional.length > 1) {
+ this.data = this.args.positional[1];
+ }
+
this.data = await this.args.positional[0];
}
} |
56e1a8ebaa5cff84c9a188b0d03cea0074d02bab | spec/feedbackSpec.js | spec/feedbackSpec.js | (function() {
'use strict';
describe('angular-feedback', function() {
beforeEach(module('angular-feedback'));
/*
var feedbackProvider;
beforeEach(function() {
// Here we create a fake module just to intercept and store the provider
// when it's injected, i.e. during the config phase.
angular
.module('fakeModule', function() {})
.config(['feedbackProvider', function(provider) {
feedbackProvider = provider;
}]);
module('angular-feedback', 'fakeModule');
// This actually triggers the injection into fakeModule
inject(function(){});
});
*/
it('should be inactive by default', inject(function(feedback) {
expect( feedback.isActive() ).toBeFalsy();
expect( feedback.isLoading() ).toBeFalsy();
}));
});
})();
| (function() {
'use strict';
describe('angular-feedback', function() {
beforeEach(module('angular-feedback'));
/*
var feedbackProvider;
beforeEach(function() {
// Here we create a fake module just to intercept and store the provider
// when it's injected, i.e. during the config phase.
angular
.module('fakeModule', function() {})
.config(['feedbackProvider', function(provider) {
feedbackProvider = provider;
}]);
module('angular-feedback', 'fakeModule');
// This actually triggers the injection into fakeModule
inject(function(){});
});
*/
it('should be inactive by default', inject(function(feedback) {
expect( feedback.isActive() ).toBeFalsy();
expect( feedback.isLoading() ).toBeFalsy();
}));
it('should set loader', inject(function(feedback) {
feedback.load();
expect( feedback.isActive() ).toBeTruthy();
expect( feedback.isLoading() ).toBeTruthy();
}));
it('should dismiss loader', inject(function(feedback, $timeout) {
feedback.load();
feedback.dismiss();
$timeout.flush();
expect( feedback.isActive() ).toBeFalsy();
expect( feedback.isLoading() ).toBeFalsy();
}));
it('should set default notification to "info"', inject(function(feedback) {
var message = 'Notification message';
feedback.notify( message );
expect( feedback.isActive() ).toBeTruthy();
expect( feedback.isLoading() ).toBeFalsy();
// expect( feedback.getType() ).toBe('info');
expect( feedback.getMessage() ).toBe( message);
}));
});
})();
| Add tests: load(), dismiss(), notify() | Add tests: load(), dismiss(), notify()
| JavaScript | mit | andreipfeiffer/angular-feedback | ---
+++
@@ -30,6 +30,32 @@
expect( feedback.isLoading() ).toBeFalsy();
}));
+ it('should set loader', inject(function(feedback) {
+ feedback.load();
+ expect( feedback.isActive() ).toBeTruthy();
+ expect( feedback.isLoading() ).toBeTruthy();
+ }));
+
+ it('should dismiss loader', inject(function(feedback, $timeout) {
+ feedback.load();
+ feedback.dismiss();
+
+ $timeout.flush();
+
+ expect( feedback.isActive() ).toBeFalsy();
+ expect( feedback.isLoading() ).toBeFalsy();
+ }));
+
+ it('should set default notification to "info"', inject(function(feedback) {
+ var message = 'Notification message';
+ feedback.notify( message );
+
+ expect( feedback.isActive() ).toBeTruthy();
+ expect( feedback.isLoading() ).toBeFalsy();
+ // expect( feedback.getType() ).toBe('info');
+ expect( feedback.getMessage() ).toBe( message);
+ }));
+
});
})(); |
529c1e82de484c1cdc55da76f124a1ab8cca232d | gulp/release-tasks.js | gulp/release-tasks.js | import 'instapromise';
import fs from 'fs';
import logger from 'gulplog';
import path from 'path';
import spawnAsync from '@exponent/spawn-async';
const paths = {
template: path.resolve(__dirname, '../template'),
templateNodeModules: path.resolve(__dirname, '../template/node_modules'),
}
let tasks = {
async archiveTemplate() {
await verifyNodeModulesAsync();
await spawnAsync('zip', ['-rqy9', 'template.zip', 'template'], {
stdio: 'inherit',
cwd: path.resolve(__dirname, '..'),
});
}
};
async function verifyNodeModulesAsync() {
let stats;
try {
stats = await fs.promise.stat(paths.templateNodeModules);
} catch (e) { }
if (stats) {
if (!stats.isDirectory()) {
throw new Error(
`${paths.templateNodeModules} is not a directory; be sure to run ` +
`"npm install" before releasing a new version of XDL`
);
}
} else {
logger.info(`Running "npm install" to set up ${paths.templateNodeModules}...`);
await spawnAsync('npm', ['install'], {
stdio: 'inherit',
cwd: paths.template,
});
}
}
export default tasks;
| import 'instapromise';
import fs from 'fs';
import logger from 'gulplog';
import path from 'path';
import spawnAsync from '@exponent/spawn-async';
const paths = {
template: path.resolve(__dirname, '../template'),
templateNodeModules: path.resolve(__dirname, '../template/node_modules'),
}
let tasks = {
async archiveTemplate() {
await verifyNodeModulesAsync();
await spawnAsync('zip', ['-rq9', 'template.zip', 'template'], {
stdio: 'inherit',
cwd: path.resolve(__dirname, '..'),
});
}
};
async function verifyNodeModulesAsync() {
let stats;
try {
stats = await fs.promise.stat(paths.templateNodeModules);
} catch (e) { }
if (stats) {
if (!stats.isDirectory()) {
throw new Error(
`${paths.templateNodeModules} is not a directory; be sure to run ` +
`"npm install" before releasing a new version of XDL`
);
}
} else {
logger.info(`Running "npm install" to set up ${paths.templateNodeModules}...`);
await spawnAsync('npm', ['install'], {
stdio: 'inherit',
cwd: paths.template,
});
}
}
export default tasks;
| Remove -y option from zip | Remove -y option from zip
| JavaScript | mit | exponentjs/xdl,exponentjs/xdl,exponentjs/xdl | ---
+++
@@ -13,7 +13,7 @@
let tasks = {
async archiveTemplate() {
await verifyNodeModulesAsync();
- await spawnAsync('zip', ['-rqy9', 'template.zip', 'template'], {
+ await spawnAsync('zip', ['-rq9', 'template.zip', 'template'], {
stdio: 'inherit',
cwd: path.resolve(__dirname, '..'),
}); |
790c3d9bcbb8a559f6e36d119369931117a7d9d9 | assets/build/webpack.config.watch.js | assets/build/webpack.config.watch.js | const webpack = require('webpack');
const BrowserSyncPlugin = require('browsersync-webpack-plugin');
const config = require('./config');
module.exports = {
output: {
pathinfo: true,
publicPath: config.proxyUrl + config.publicPath,
},
devtool: '#cheap-module-source-map',
stats: false,
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new BrowserSyncPlugin({
target: config.devUrl,
proxyUrl: config.proxyUrl,
watch: config.watch,
delay: 500,
}),
],
};
| const webpack = require('webpack');
const BrowserSyncPlugin = require('browsersync-webpack-plugin');
const config = require('./config');
module.exports = {
output: {
pathinfo: true,
publicPath: config.proxyUrl + config.publicPath,
},
devtool: '#cheap-module-source-map',
stats: false,
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new BrowserSyncPlugin({
target: process.env.DEVURL || config.devUrl,
proxyUrl: config.proxyUrl,
watch: config.watch,
delay: 500,
}),
],
};
| Add environment variable check for DEVURL | Add environment variable check for DEVURL
| JavaScript | mit | PCHC/pharmacyresidency2017,generoi/sage,kalenjohnson/sage,ChrisLTD/sage,roots/sage,NicBeltramelli/sage,ptrckvzn/sage,democracy-os-fr/sage,agusgarcia/sage9,c50/c50_roots,NicBeltramelli/sage,gkmurray/sage,ChrisLTD/sage,ChrisLTD/sage,kalenjohnson/sage,ChrisLTD/sage,c50/c50_roots,levito/kleineweile-wp-theme,kalenjohnson/sage,PCHC/pharmacyresidency2017,gkmurray/sage,agusgarcia/sage9,levito/kleineweile-wp-theme,sacredwebsite/sage,teaguecnelson/tn-tellis-bds,PCHC/pharmacyresidency2017,generoi/sage,agusgarcia/sage9,gkmurray/sage,democracy-os-fr/sage,JulienMelissas/sage,levito/kleineweile-wp-theme,roots/sage,JulienMelissas/sage,sacredwebsite/sage,teaguecnelson/tn-tellis-bds,gkmurray/sage,generoi/sage,mckelvey/sage,ptrckvzn/sage,teaguecnelson/tn-tellis-bds,JulienMelissas/sage,sacredwebsite/sage,ptrckvzn/sage,mckelvey/sage,mckelvey/sage,NicBeltramelli/sage,democracy-os-fr/sage,c50/c50_roots | ---
+++
@@ -15,7 +15,7 @@
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new BrowserSyncPlugin({
- target: config.devUrl,
+ target: process.env.DEVURL || config.devUrl,
proxyUrl: config.proxyUrl,
watch: config.watch,
delay: 500, |
328d1abab5fd2f21b5c9392d7df23b88a6f8d003 | base-template/server/config/index.js | base-template/server/config/index.js | var Path = require('path')
global.CONFIG = require('./index.json')
CONFIG.projectFile = (path) => Path.resolve(__dirname, '../..', path)
module.exports = function config (router) {
for (var item of CONFIG.routerPipeline) {
require(item).mount(router)
}
}
| var Path = require('path')
global.CONFIG = require('./index.json')
CONFIG.projectFile = (path) => Path.resolve(__dirname, '../..', path)
module.exports = function config (router) {
//
// Foundational config should be seldom used,
// as it has a HIGH priority over the rest.
//
for (var item of (CONFIG.foundational || [])) {
require(item).mount(router)
}
//
// Run the rest of all configuration.
//
for (var item of CONFIG.routerPipeline) {
require(item).mount(router)
}
}
| Add foundational config, for high priority config. | Add foundational config, for high priority config.
This allows setup such as typescript to always be in front,
removing the potential for user errors.
| JavaScript | mit | Concatapult/pult,Concatapult/pult,Concatapult/pult | ---
+++
@@ -4,6 +4,18 @@
module.exports = function config (router) {
+
+ //
+ // Foundational config should be seldom used,
+ // as it has a HIGH priority over the rest.
+ //
+ for (var item of (CONFIG.foundational || [])) {
+ require(item).mount(router)
+ }
+
+ //
+ // Run the rest of all configuration.
+ //
for (var item of CONFIG.routerPipeline) {
require(item).mount(router)
} |
a098d921a11065059f06555074b9d810b2431786 | examples/grepcount.js | examples/grepcount.js | var temp = require('../lib/temp'),
fs = require('fs'),
util = require('util'),
exec = require('child_process').exec;
var myData = "foo\nbar\nfoo\nbaz";
temp.open('myprefix', function(err, info) {
if (err) throw err;
fs.write(info.fd, myData);
fs.close(info.fd, function(err) {
if (err) throw err;
exec("grep foo '" + info.path + "' | wc -l", function(err, stdout) {
if (err) throw err;
util.puts(stdout.trim());
});
});
});
| var temp = require('../lib/temp'),
fs = require('fs'),
util = require('util'),
exec = require('child_process').exec;
var myData = "foo\nbar\nfoo\nbaz";
temp.open('myprefix', function(err, info) {
if (err) throw err;
fs.write(info.fd, myData, function(err) {
if (err) throw err;
fs.close(info.fd, function(err) {
if (err) throw err;
exec("grep foo '" + info.path + "' | wc -l", function(err, stdout) {
if (err) throw err;
util.puts(stdout.trim());
});
});
});
});
| Update example to include callback | Update example to include callback
| JavaScript | mit | hildjj/node-temp,bruce/node-temp | ---
+++
@@ -7,12 +7,14 @@
temp.open('myprefix', function(err, info) {
if (err) throw err;
- fs.write(info.fd, myData);
- fs.close(info.fd, function(err) {
+ fs.write(info.fd, myData, function(err) {
if (err) throw err;
- exec("grep foo '" + info.path + "' | wc -l", function(err, stdout) {
+ fs.close(info.fd, function(err) {
if (err) throw err;
- util.puts(stdout.trim());
+ exec("grep foo '" + info.path + "' | wc -l", function(err, stdout) {
+ if (err) throw err;
+ util.puts(stdout.trim());
+ });
});
});
}); |
e15defc90cff15889c30abe86d8c21221c4736c1 | examples/app.js | examples/app.js | import React from "react";
import ReactDOM from "react-dom";
import YoutubeEmbedVideo from 'youtube-embed-video';
ReactDOM.render(<YoutubeEmbedVideo size="large" videoId="RnDC9MXSqCY" suggestions={false} />, document.getElementById("app"));
| import React from "react";
import ReactDOM from "react-dom";
import YoutubeEmbedVideo from '../dist/youtube';
// import YoutubeEmbedVideo from 'youtube-embed-video';
ReactDOM.render(<YoutubeEmbedVideo size="medium" videoId="RnDC9MXSqCY" className="video-player" style={{ borderWidth: 5, borderColor: '#004ebc' }} suggestions={false} />, document.getElementById("app"));
| Update example with class and style attributes | Update example with class and style attributes
| JavaScript | mit | Tiendq/youtube-embed-video | ---
+++
@@ -1,5 +1,6 @@
import React from "react";
import ReactDOM from "react-dom";
-import YoutubeEmbedVideo from 'youtube-embed-video';
+import YoutubeEmbedVideo from '../dist/youtube';
+// import YoutubeEmbedVideo from 'youtube-embed-video';
-ReactDOM.render(<YoutubeEmbedVideo size="large" videoId="RnDC9MXSqCY" suggestions={false} />, document.getElementById("app"));
+ReactDOM.render(<YoutubeEmbedVideo size="medium" videoId="RnDC9MXSqCY" className="video-player" style={{ borderWidth: 5, borderColor: '#004ebc' }} suggestions={false} />, document.getElementById("app")); |
d661f3e064ceed22990e913af5c71a101825653e | gulp-tasks/testing.js | gulp-tasks/testing.js | // Use the gulp-help plugin which defines a default gulp task
// which lists what tasks are available.
var gulp = require('gulp-help')(require('gulp'));
// Sequential Gulp tasks
var runSequence = require('run-sequence').use(gulp);
var cucumber = require('gulp-cucumber');
// Parse any command line arguments ignoring
// Node and the name of the calling script.
// Extract tag arguments.
var argv = require('minimist')(process.argv.slice(2));
var tags = argv.tags || false;
// Run all the Cucumber features, doesn't start server
// Hidden from gulp-help.
gulp.task('cucumber', 'Run Cucumber directly without starting the server.', function() {
var options = {
support: 'features-support/**/*.js',
// Tags are optional, falsey values are ignored.
tags: tags
}
return gulp.src('features/**/*.feature').pipe(cucumber(options));
}, {
options: {'tags': 'Supports optional tags argument e.g.\n\t\t\t--tags @parsing\n\t\t\t--tags @tag1,orTag2\n\t\t\t--tags @tag1 --tags @andTag2\n\t\t\t--tags @tag1 --tags ~@andNotTag2'}
});
// Default Cucumber run requires server to be running.
gulp.task('test:features', 'Test the features.', function(done) {
runSequence('set-envs:test',
'server:start',
'cucumber',
'server:stop',
done);
});
| // Use the gulp-help plugin which defines a default gulp task
// which lists what tasks are available.
var gulp = require('gulp-help')(require('gulp'));
// Sequential Gulp tasks
var runSequence = require('run-sequence').use(gulp);
var cucumber = require('gulp-cucumber');
// Parse any command line arguments ignoring
// Node and the name of the calling script.
// Extract tag arguments.
var argv = require('minimist')(process.argv.slice(2));
var tags = argv.tags || false;
// Run all the Cucumber features, doesn't start server
// Hidden from gulp-help.
gulp.task('cucumber', 'Run Cucumber directly without starting the server.', function() {
var options = {
support: 'features-support/**/*.js',
// Tags are optional, falsey values are ignored.
tags: tags
}
return gulp.src('features/**/*.feature').pipe(cucumber(options));
}, {
options: {'tags': 'Supports optional tags argument e.g.\n\t\t\t--tags @parsing\n\t\t\t--tags @tag1,orTag2\n\t\t\t--tags @tag1 --tags @andTag2\n\t\t\t--tags @tag1 --tags ~@andNotTag2'}
});
// Default Cucumber run requires server to be running.
gulp.task('test:features', 'Test the features.', function(done) {
runSequence('set-envs:test',
'server:start',
'cucumber',
'server:stop',
done);
}, {
options: {'tags': 'Supports same optional tags arguments as \'Cucumber\' task.'}
});
| Document that the test:features Gulp task also supports tags. | Document that the test:features Gulp task also supports tags.
| JavaScript | mit | oss-specs/specs,oss-specs/specs | ---
+++
@@ -33,4 +33,6 @@
'cucumber',
'server:stop',
done);
+}, {
+ options: {'tags': 'Supports same optional tags arguments as \'Cucumber\' task.'}
}); |
b8d5354c1ca0f06c41b0c3f4c271cdf0f4ca3585 | lib/extension-plugin.js | lib/extension-plugin.js | const Plugin = require('imdone-api')
const _path = require('path')
const { statSync } = require('fs')
module.exports = class ExtensionPlugin extends Plugin {
constructor(project) {
super(project)
console.log('loading extensions')
this.configDir = _path.join(project.path, '.imdone')
this.cardActionsFunction = this.loadExtensionModule(
() => [],
'actions',
'card'
)
this.boardActionsFunction = this.loadExtensionModule(
() => [],
'actions',
'board'
)
this.cardPropertiesFunction = this.loadExtensionModule(
() => {
return {}
},
'properties',
'card'
)
}
getCardProperties(task) {
return this.cardPropertiesFunction(task)
}
getCardActions(task) {
return this.cardActionsFunction(this.project, task)
}
getBoardActions() {
return this.boardActionsFunction(this.project).map(({ title, action }) => ({
name: title,
action,
}))
}
getConfigPath(relativePath) {
return _path.join(this.configDir, ...relativePath)
}
loadExtensionModule(_default, ...path) {
let extension = _default
const extensionPath = this.getConfigPath(path)
try {
statSync(extensionPath + '.js')
delete require.cache[require.resolve(extensionPath)]
extension = require(extensionPath)
} catch (e) {
console.log('No extension found at:', extensionPath)
}
return extension
}
}
| const Plugin = require('imdone-api')
const _path = require('path')
const { statSync } = require('fs')
module.exports = class ExtensionPlugin extends Plugin {
constructor(project) {
super(project)
console.log('loading extensions')
this.configDir = _path.join(project.path, '.imdone')
this.cardActionsFunction = this.loadExtensionModule(
() => [],
'actions',
'card'
).bind(this)
this.boardActionsFunction = this.loadExtensionModule(
() => [],
'actions',
'board'
).bind(this)
this.cardPropertiesFunction = this.loadExtensionModule(
() => {
return {}
},
'properties',
'card'
).bind(this)
}
getCardProperties(task) {
return this.cardPropertiesFunction(task)
}
getCardActions(task) {
return this.cardActionsFunction(task)
}
getBoardActions() {
return this.boardActionsFunction().map(({ title, action }) => ({
name: title,
action,
}))
}
getConfigPath(relativePath) {
return _path.join(this.configDir, ...relativePath)
}
loadExtensionModule(_default, ...path) {
let extension = _default
const extensionPath = this.getConfigPath(path)
try {
statSync(extensionPath + '.js')
delete require.cache[require.resolve(extensionPath)]
extension = require(extensionPath)
} catch (e) {
console.log('No extension found at:', extensionPath)
}
return extension
}
}
| Make actions and properties module conform to plugin-api | Make actions and properties module conform to plugin-api
| JavaScript | mit | imdone/imdone-core,imdone/imdone-core | ---
+++
@@ -12,19 +12,19 @@
() => [],
'actions',
'card'
- )
+ ).bind(this)
this.boardActionsFunction = this.loadExtensionModule(
() => [],
'actions',
'board'
- )
+ ).bind(this)
this.cardPropertiesFunction = this.loadExtensionModule(
() => {
return {}
},
'properties',
'card'
- )
+ ).bind(this)
}
getCardProperties(task) {
@@ -32,11 +32,11 @@
}
getCardActions(task) {
- return this.cardActionsFunction(this.project, task)
+ return this.cardActionsFunction(task)
}
getBoardActions() {
- return this.boardActionsFunction(this.project).map(({ title, action }) => ({
+ return this.boardActionsFunction().map(({ title, action }) => ({
name: title,
action,
})) |
72a8c966ba842baa557524a62f7e82c2b011c634 | lib/policy/authorize.js | lib/policy/authorize.js | const Boom = require('boom');
exports.register = function (server, options, next) {
if (!options) options = {};
const policies = options.policies || [];
// General check function
check = async(user, action, target) => {
if (!user || !action) return false;
try {
// Resolve check function
let check_fn = action;
if (!(check_fn instanceof Function)) check_fn = policies[action];
if (!(check_fn instanceof Function)) {
server.log(['warning', 'authorize'], {message: 'no policy defined for ' + action});
return false
}
// Test against check_fn
let result = check_fn(user, target);
// Support async policies
if (result instanceof Promise) result = await result;
// ensure result is true or false only
return !!result;
} catch (error) {
// Log and reject unhandled errors
server.log(['error', 'authorize'], {action, target, error});
return false;
}
};
// Adds request.can() decorator
function can(action, target) {
return check(this.auth.credentials, action, target);
}
server.decorate('request', 'can', can);
// Adds request.authorize() decorator
async function authorize(action, target) {
let result = await check(this.auth.credentials, action, target);
if (result !== true) throw Boom.unauthorized(action);
return true;
}
server.decorate('request', 'authorize', authorize);
next();
};
exports.register.attributes = {
name: 'bak-policy-authorize'
};
| const Boom = require('boom');
exports.register = function (server, options, next) {
if (!options) options = {};
const policies = options.policies || [];
// General check function
check = async(user, action, target) => {
if (!user || !action) return false;
try {
// Resolve check function
let check_fn = action;
if (!(check_fn instanceof Function)) check_fn = policies[action];
if (!(check_fn instanceof Function)) {
server.log(['warning', 'authorize'], {message: 'no policy defined for ' + action});
return false
}
// Test against check_fn
let result = check_fn(user, target);
// Support async policies
if (result instanceof Promise) result = await result;
// ensure result is true or false only
return !!result;
} catch (error) {
// Log and reject unhandled errors
server.log(['error', 'authorize'], {action, target, error});
return false;
}
};
// Adds request.can() decorator
function can(action, target) {
return check(this.auth.credentials && this.auth.credentials.user, action, target);
}
server.decorate('request', 'can', can);
// Adds request.authorize() decorator
async function authorize(action, target) {
let result = await check(this.auth.credentials && this.auth.credentials.user, action, target);
if (result !== true) throw Boom.unauthorized(action);
return true;
}
server.decorate('request', 'authorize', authorize);
next();
};
exports.register.attributes = {
name: 'bak-policy-authorize'
};
| Use auth.credentials.user for policy checks | Use auth.credentials.user for policy checks
| JavaScript | mit | bakjs/bak,fandogh/bak | ---
+++
@@ -35,14 +35,14 @@
// Adds request.can() decorator
function can(action, target) {
- return check(this.auth.credentials, action, target);
+ return check(this.auth.credentials && this.auth.credentials.user, action, target);
}
server.decorate('request', 'can', can);
// Adds request.authorize() decorator
async function authorize(action, target) {
- let result = await check(this.auth.credentials, action, target);
+ let result = await check(this.auth.credentials && this.auth.credentials.user, action, target);
if (result !== true) throw Boom.unauthorized(action);
return true;
} |
12618aa1792803acc7635451befd13f77faeb3ae | javascript/play.js | javascript/play.js | function render(world) {
var rendering = '';
for (var y = world.boundaries()['y']['min']; y <= world.boundaries()['y']['max']; y++) {
for (var x = world.boundaries()['x']['min']; x <= world.boundaries()['x']['max']; x++) {
var cell = world.cell_at(x, y);
rendering += (cell ? cell.to_char() : ' ').replace(' ', ' ');
}
rendering += "<br />"
}
return rendering;
}
$(document).ready(function() {
var world = new World;
for (var x = 0; x <= 150; x++) {
for (var y = 0; y <= 40; y++) {
world.add_cell(x, y, (Math.random() > 0.2));
}
}
var body = $('body');
body.html(render(world));
setInterval(function() {
var tick_start = new Date();
world._tick();
var tick_finish = new Date();
var tick_time = ((tick_finish-tick_start)/1000).toFixed(3);
var render_start = new Date();
var rendered = render(world);
var render_finish = new Date();
var render_time = ((render_finish-render_start)/1000).toFixed(3);
var output = "#"+world.tick;
output += " - World tick took "+tick_time;
output += " - Rendering took "+render_time;
output += "<br />"+rendered;
body.html(output);
});
});
| function render(world) {
var rendering = '';
for (var y = world.boundaries()['y']['min']; y <= world.boundaries()['y']['max']; y++) {
for (var x = world.boundaries()['x']['min']; x <= world.boundaries()['x']['max']; x++) {
var cell = world.cell_at(x, y);
rendering += (cell ? cell.to_char() : ' ').replace(' ', ' ');
}
rendering += "<br />"
}
return rendering;
}
$(document).ready(function() {
var world = new World;
for (var x = 0; x <= 150; x++) {
for (var y = 0; y <= 40; y++) {
world.add_cell(x, y, (Math.random() > 0.2));
}
}
var body = $('body');
body.html(render(world));
setInterval(function() {
var tick_start = new Date();
world._tick();
var tick_finish = new Date();
var tick_time = ((tick_finish-tick_start)/1000).toFixed(3);
var render_start = new Date();
var rendered = render(world);
var render_finish = new Date();
var render_time = ((render_finish-render_start)/1000).toFixed(3);
var output = "#"+world.tick;
output += " - World tick took "+tick_time;
output += " - Rendering took "+render_time;
output += "<br />"+rendered;
body.html(output);
}, 0);
});
| Fix implementation for SpiderMonkey (firefox) | Fix implementation for SpiderMonkey (firefox)
| JavaScript | mit | KieranP/Game-Of-Life-Implementations,KieranP/Game-Of-Life-Implementations,KieranP/Game-Of-Life-Implementations,KieranP/Game-Of-Life-Implementations,KieranP/Game-Of-Life-Implementations,KieranP/Game-Of-Life-Implementations,KieranP/Game-Of-Life-Implementations,KieranP/Game-Of-Life-Implementations,KieranP/Game-Of-Life-Implementations,KieranP/Game-Of-Life-Implementations,KieranP/Game-Of-Life-Implementations,KieranP/Game-Of-Life-Implementations,KieranP/Game-Of-Life-Implementations | ---
+++
@@ -38,6 +38,6 @@
output += " - Rendering took "+render_time;
output += "<br />"+rendered;
body.html(output);
- });
+ }, 0);
}); |
0089918d2b03b5fb6196861448a393127a92c554 | src/checked.spec.js | src/checked.spec.js | import WrapperBuilder from './wrapper';
import { shallow, mount } from 'enzyme';
import React from 'react';
const CheckedFixture = () => (
<input type="checkbox" defaultChecked value="coffee" />
);
// const NotCheckedFixture = () => (
// <input type="checkbox" value="coffee" />
// );
describe('Checkbox', () => {
const methodNames = ['shallow', 'mount'];
[shallow, mount].forEach((renderMethod, i) => {
let checkedInput;
// notCheckedInput;
before(() => {
checkedInput = WrapperBuilder(renderMethod(<CheckedFixture />));
// notCheckedInput = WrapperBuilder(renderMethod(<NotCheckedFixture />));
});
context(methodNames[i], () => {
it(`should be checked`, () => {
checkedInput.checked().should.be.true();
});
});
});
}); | import WrapperBuilder from './wrapper';
import { shallow, mount } from 'enzyme';
import React from 'react';
const CheckedFixture = () => (
<input type="checkbox" defaultChecked value="coffee" />
);
const NotCheckedFixture = () => (
<input type="checkbox" value="coffee" />
);
describe('Checkbox', () => {
const methodNames = ['shallow', 'mount'];
[shallow, mount].forEach((renderMethod, i) => {
let checkedInput, notCheckedInput;
before(() => {
checkedInput = WrapperBuilder(renderMethod(<CheckedFixture />));
notCheckedInput = WrapperBuilder(renderMethod(<NotCheckedFixture />));
});
context(methodNames[i], () => {
it(`should be checked`, () => {
checkedInput.checked().should.be.true();
});
it(`should NOT be checked`, () => {
notCheckedInput.checked().should.be.false();
});
});
});
}); | Check if checkbox is not checked. | Check if checkbox is not checked.
| JavaScript | mit | rkotze/should-enzyme | ---
+++
@@ -6,24 +6,27 @@
<input type="checkbox" defaultChecked value="coffee" />
);
-// const NotCheckedFixture = () => (
-// <input type="checkbox" value="coffee" />
-// );
+const NotCheckedFixture = () => (
+ <input type="checkbox" value="coffee" />
+);
describe('Checkbox', () => {
const methodNames = ['shallow', 'mount'];
[shallow, mount].forEach((renderMethod, i) => {
- let checkedInput;
- // notCheckedInput;
+ let checkedInput, notCheckedInput;
before(() => {
checkedInput = WrapperBuilder(renderMethod(<CheckedFixture />));
- // notCheckedInput = WrapperBuilder(renderMethod(<NotCheckedFixture />));
+ notCheckedInput = WrapperBuilder(renderMethod(<NotCheckedFixture />));
});
context(methodNames[i], () => {
it(`should be checked`, () => {
checkedInput.checked().should.be.true();
});
+
+ it(`should NOT be checked`, () => {
+ notCheckedInput.checked().should.be.false();
+ });
});
}); |
20f408c3a10d6eb1320f54983cd5fbbb00a63ecd | src/contentChunk.js | src/contentChunk.js |
import mongodb from 'mongodb'
import { config } from './config'
const MongoClient = mongodb.MongoClient
const db = null
// WIP: TODO: Find better way to connect to mongoDB
const getDB = async () => {
if (db) {
return db
}
try {
const client = await MongoClient.connect(config.mongo.url)
return client.db()
} catch (err) {
if (err) throw Error(err)
return
}
}
exports.extractPayloadIntoChunks = async (resource) => {
try {
const db = await getDB()
const bucket = new mongodb.GridFSBucket(db)
const stream = bucket.openUploadStream()
stream.on('error', (err) => {
throw Error(err)
})
.on('finish', (doc) => {
if (!doc) {
throw new Error('GridFS create failed')
}
return doc._id
})
stream.end(resource)
} catch (err) {
if (err) {
console.log('error: ', err)
}
}
}
|
import mongodb from 'mongodb'
import { connectionDefault } from './config'
exports.extractPayloadIntoChunks = (resource) => {
return new Promise((resolve, reject) => {
const bucket = new mongodb.GridFSBucket(connectionDefault.client.db())
const stream = bucket.openUploadStream()
stream.on('error', (err) => {
return reject(err)
})
.on('finish', (doc) => {
if (!doc) {
return reject('GridFS create failed')
}
return resolve(doc._id)
})
stream.end(resource)
})
}
| Refactor function to return a promise instead of a callback | WIP: Refactor function to return a promise instead of a callback
Replaced creation of custom mongo connection with existing mongoose connection object
OHM-762
| JavaScript | mpl-2.0 | jembi/openhim-core-js,jembi/openhim-core-js | ---
+++
@@ -1,48 +1,22 @@
import mongodb from 'mongodb'
-import { config } from './config'
+import { connectionDefault } from './config'
-const MongoClient = mongodb.MongoClient
-
-const db = null
-
-// WIP: TODO: Find better way to connect to mongoDB
-const getDB = async () => {
- if (db) {
- return db
- }
-
- try {
- const client = await MongoClient.connect(config.mongo.url)
- return client.db()
- } catch (err) {
- if (err) throw Error(err)
- return
- }
-}
-
-exports.extractPayloadIntoChunks = async (resource) => {
- try {
- const db = await getDB()
-
- const bucket = new mongodb.GridFSBucket(db)
-
+exports.extractPayloadIntoChunks = (resource) => {
+ return new Promise((resolve, reject) => {
+ const bucket = new mongodb.GridFSBucket(connectionDefault.client.db())
const stream = bucket.openUploadStream()
stream.on('error', (err) => {
- throw Error(err)
+ return reject(err)
})
.on('finish', (doc) => {
if (!doc) {
- throw new Error('GridFS create failed')
+ return reject('GridFS create failed')
}
- return doc._id
+ return resolve(doc._id)
})
stream.end(resource)
- } catch (err) {
- if (err) {
- console.log('error: ', err)
- }
- }
+ })
} |
d6c9063694f3052f5b0270de18667b2b3dc45316 | lib/Accordion/Accordion.stories.js | lib/Accordion/Accordion.stories.js | import React from 'react';
import { storiesOf } from '@storybook/react';
import withReadme from 'storybook-readme/with-readme';
import Readme from './readme.md';
import Accordion from './Accordion';
storiesOf('Accordion', module)
.addDecorator(withReadme(Readme))
.add('with defaults', () => (
<Accordion label="Hello">
Content
</Accordion>
));
| import React from 'react';
import { storiesOf } from '@storybook/react'; // eslint-disable-line import/no-extraneous-dependencies
import withReadme from 'storybook-readme/with-readme'; // eslint-disable-line import/no-extraneous-dependencies
import Readme from './readme.md';
import Accordion from './Accordion';
storiesOf('Accordion', module)
.addDecorator(withReadme(Readme))
.add('with defaults', () => (
<Accordion label="Hello">
Content
</Accordion>
));
| Fix storybook story lint errors | Fix storybook story lint errors
| JavaScript | apache-2.0 | folio-org/stripes-components,folio-org/stripes-components | ---
+++
@@ -1,6 +1,6 @@
import React from 'react';
-import { storiesOf } from '@storybook/react';
-import withReadme from 'storybook-readme/with-readme';
+import { storiesOf } from '@storybook/react'; // eslint-disable-line import/no-extraneous-dependencies
+import withReadme from 'storybook-readme/with-readme'; // eslint-disable-line import/no-extraneous-dependencies
import Readme from './readme.md';
import Accordion from './Accordion'; |
9cdb56f072286f6be2db88c3fe6ec9ec660a1b86 | app/controllers/pingdom.server.controller.js | app/controllers/pingdom.server.controller.js | 'use strict';
/**
* Module dependencies.
*/
var cron = require('cron'),
pingdom = require('pingdom-api');
exports.init = function(){
console.log('initttttttt');
}; | 'use strict';
/**
* Module dependencies.
*/
var CronJob = require('cron').CronJob,
pingdom = require('pingdom-api');
exports.init = function(){
var job = new CronJob({
cronTime: '0 */1 * * * *',
onTick: function() {
console.log('Tick!');
},
start: false,
timeZone: 'Europe/Amsterdam'
});
// job.start();
}; | Add a cronjob that runs every minute but dont start it yet | Add a cronjob that runs every minute but dont start it yet
| JavaScript | mit | rsdebest/pingtool,rsdebest/pingtool,rsdebest/pingtool | ---
+++
@@ -3,9 +3,18 @@
/**
* Module dependencies.
*/
-var cron = require('cron'),
+var CronJob = require('cron').CronJob,
pingdom = require('pingdom-api');
exports.init = function(){
- console.log('initttttttt');
+
+ var job = new CronJob({
+ cronTime: '0 */1 * * * *',
+ onTick: function() {
+ console.log('Tick!');
+ },
+ start: false,
+ timeZone: 'Europe/Amsterdam'
+ });
+ // job.start();
}; |
b5d5b8e446e7ff911c50cef5a1c2ff60a47c4cb0 | src/js/ui/animate.js | src/js/ui/animate.js | var $ = require('wetfish-basic');
var animate =
{
status: false,
init: function()
{
},
start: function()
{
$('.workspace').addClass('highlight-content');
},
stop: function()
{
$('.workspace').removeClass('highlight-content');
}
};
module.exports = animate;
| var $ = require('wetfish-basic');
var storage = require('../app/storage');
var animate =
{
active: false,
element: false,
init: function()
{
// Save the default element notification text
animate.defaultText = $('.menu .animate .element').el[0].textContent;
$('body').on('click', '.workspace .content, .workspace .content *', function()
{
var element = this;
if(!$(element).hasClass('content'))
{
element = $(this).parents('.content').el[0];
}
if(animate.active)
{
animate.element = element;
animate.populate();
animate.menu();
}
});
},
// Populate data from saved object
populate: function()
{
var id = $(animate.element).attr('id');
var object = storage.getObject(id);
var desc = object.desc || 'untitled ' + object.type;
$('.menu .animate .element').text(desc);
},
// Display menu options based on the current animation state
menu: function()
{
if(animate.element)
{
$('.element-selected').removeClass('hidden');
}
else
{
$('.element-selected').addClass('hidden');
}
},
start: function()
{
$('.workspace').addClass('highlight-content');
animate.active = true;
},
stop: function()
{
$('.workspace').removeClass('highlight-content');
animate.active = false;
animate.element = false;
$('.menu .animate .element').text(animate.defaultText);
}
};
module.exports = animate;
| Allow selecting elements for animation | Allow selecting elements for animation
| JavaScript | agpl-3.0 | itsrachelfish/youtube,itsrachelfish/youtube,itsrachelfish/memes,itsrachelfish/memes | ---
+++
@@ -1,22 +1,70 @@
var $ = require('wetfish-basic');
+var storage = require('../app/storage');
var animate =
{
- status: false,
+ active: false,
+ element: false,
init: function()
{
-
+ // Save the default element notification text
+ animate.defaultText = $('.menu .animate .element').el[0].textContent;
+
+ $('body').on('click', '.workspace .content, .workspace .content *', function()
+ {
+ var element = this;
+
+ if(!$(element).hasClass('content'))
+ {
+ element = $(this).parents('.content').el[0];
+ }
+
+ if(animate.active)
+ {
+ animate.element = element;
+ animate.populate();
+ animate.menu();
+ }
+ });
+ },
+
+ // Populate data from saved object
+ populate: function()
+ {
+ var id = $(animate.element).attr('id');
+ var object = storage.getObject(id);
+
+ var desc = object.desc || 'untitled ' + object.type;
+ $('.menu .animate .element').text(desc);
+ },
+
+ // Display menu options based on the current animation state
+ menu: function()
+ {
+ if(animate.element)
+ {
+ $('.element-selected').removeClass('hidden');
+ }
+ else
+ {
+ $('.element-selected').addClass('hidden');
+ }
},
start: function()
{
$('.workspace').addClass('highlight-content');
+ animate.active = true;
},
stop: function()
{
$('.workspace').removeClass('highlight-content');
+ animate.active = false;
+ animate.element = false;
+
+ $('.menu .animate .element').text(animate.defaultText);
}
};
|
deac25ca15e9a2bf31ba207c6f3aec5efc684bd1 | lib/utils/defaults.js | lib/utils/defaults.js | var _ = require('lodash');
/**
* Sets options
* @param {Object} [options]
* @param {String[]} [options.ignoreAttributes]
* @param {String[]} [options.compareAttributesAsJSON]
* @param {Boolean} [options.ignoreWhitespaces=true]
* @param {Boolean} [options.ignoreComments=true]
* @param {Boolean} [options.ignoreClosingTags=false]
* @param {Boolean} [options.ignoreDuplicateAttributes=false]
* returns {Object}
*/
module.exports = function (options) {
if (typeof options === 'string') {
if (options === 'bem') {
options = {
// ignore generated attributes
ignoreAttributes: ['id', 'for', 'aria-labelledby', 'aria-describedby'],
compareAttributesAsJSON: [
'data-bem',
{ name: 'onclick', isFunction: true },
{ name: 'ondblclick', isFunction: true }
]
};
} else {
console.error(options.bold.red + ' is an invalid preset name. Use ' + 'bem'.bold.green + ' instead.');
process.exit(1);
}
}
return _.defaults(options || {}, {
ignoreAttributes: [],
compareAttributesAsJSON: [],
ignoreWhitespaces: true,
ignoreComments: true,
ignoreEndTags: false,
ignoreDuplicateAttributes: false
});
};
| var _ = require('lodash');
/**
* Sets options
* @param {Object} [options]
* @param {String[]} [options.ignoreAttributes]
* @param {String[]} [options.compareAttributesAsJSON]
* @param {Boolean} [options.ignoreWhitespaces=true]
* @param {Boolean} [options.ignoreComments=true]
* @param {Boolean} [options.ignoreClosingTags=false]
* @param {Boolean} [options.ignoreDuplicateAttributes=false]
* returns {Object}
*/
module.exports = function (options) {
if (typeof options === 'string') {
if (options === 'bem') {
options = {
// ignore generated attributes
ignoreAttributes: ['id', 'for', 'aria-labelledby', 'aria-describedby'],
compareAttributesAsJSON: [
'data-bem',
{ name: 'onclick', isFunction: true },
{ name: 'ondblclick', isFunction: true }
],
ignoreComments: false
};
} else {
console.error(options.bold.red + ' is an invalid preset name. Use ' + 'bem'.bold.green + ' instead.');
process.exit(1);
}
}
return _.defaults(options || {}, {
ignoreAttributes: [],
compareAttributesAsJSON: [],
ignoreWhitespaces: true,
ignoreComments: true,
ignoreEndTags: false,
ignoreDuplicateAttributes: false
});
};
| Fix BEM preset; ignoreComments --> false | Fix BEM preset; ignoreComments --> false
| JavaScript | mit | bem/html-differ,bem/html-differ | ---
+++
@@ -21,7 +21,8 @@
'data-bem',
{ name: 'onclick', isFunction: true },
{ name: 'ondblclick', isFunction: true }
- ]
+ ],
+ ignoreComments: false
};
} else {
console.error(options.bold.red + ' is an invalid preset name. Use ' + 'bem'.bold.green + ' instead.'); |
08f7cd695a147bd62324565846047ce68b8fbac6 | local_modules/tresdb-db/indices.js | local_modules/tresdb-db/indices.js | module.exports = [
{
collection: 'attachments',
spec: { key: 1 },
options: { unique: true }
},
{
collection: 'entries',
spec: { locationId: 1 },
options: {}
},
{
collection: 'events',
spec: { time: 1 },
options: {}
},
{
collection: 'events',
spec: { locationId: 1 },
options: {}
},
{
collection: 'locations',
spec: { geom: '2dsphere' },
options: {}
},
{
collection: 'locations',
spec: { layer: 1 },
options: {}
},
{
collection: 'locations',
spec: { status: 1, type: 1 },
options: {}
},
{
// Text index
collection: 'locations',
spec: {
text1: 'text', // primary
text2: 'text' // secondary
},
options: {
weights: {
text1: 3,
text2: 1
},
name: 'TextIndex'
}
},
{
collection: 'users',
spec: { email: 1 },
options: { unique: true }
},
{
collection: 'users',
spec: { name: 1 },
options: { unique: true }
}
]
| module.exports = [
{
collection: 'attachments',
spec: { key: 1 },
options: { unique: true }
},
{
// Ensure same upload is not added twice
collection: 'attachments',
spec: { filepath: 1 },
options: { unique: true }
},
{
collection: 'entries',
spec: { locationId: 1 },
options: {}
},
{
collection: 'events',
spec: { time: 1 },
options: {}
},
{
collection: 'events',
spec: { locationId: 1 },
options: {}
},
{
collection: 'locations',
spec: { geom: '2dsphere' },
options: {}
},
{
collection: 'locations',
spec: { layer: 1 },
options: {}
},
{
collection: 'locations',
spec: { status: 1, type: 1 },
options: {}
},
{
// Text index
collection: 'locations',
spec: {
text1: 'text', // primary
text2: 'text' // secondary
},
options: {
weights: {
text1: 3,
text2: 1
},
name: 'TextIndex'
}
},
{
collection: 'users',
spec: { email: 1 },
options: { unique: true }
},
{
collection: 'users',
spec: { name: 1 },
options: { unique: true }
}
]
| Index for attachment filepath to prevent doubles | Index for attachment filepath to prevent doubles
| JavaScript | mit | axelpale/tresdb,axelpale/tresdb | ---
+++
@@ -2,6 +2,12 @@
{
collection: 'attachments',
spec: { key: 1 },
+ options: { unique: true }
+ },
+ {
+ // Ensure same upload is not added twice
+ collection: 'attachments',
+ spec: { filepath: 1 },
options: { unique: true }
},
{ |
c6e1d1685efe55edb048d3ad34f14239ffe62b85 | api/controllers/DashboardController.js | api/controllers/DashboardController.js | /**
* DashboardController
*
* @description :: Server-side logic for managing Dashboards
* @help :: See http://links.sailsjs.org/docs/controllers
*/
module.exports = {
index: function (req, res) {
if(!req.user.hasPermission('system.dashboard.view')) {
res.forbidden(req.__('Error.Authorization.NoRights'));
} else {
var widgetContents = [];
sails.app.customWidgets.forEach(function(widget) {
var controller = widget.controller;
var action = widget.action;
var result = sails.controllers[controller][action](req);
if(result) {
result.owner = widget;
widgetContents.push(result);
}
});
res.view({ widgets: widgetContents });
}
}
};
| /**
* DashboardController
*
* @description :: Server-side logic for managing Dashboards
* @help :: See http://links.sailsjs.org/docs/controllers
*/
module.exports = {
index: function (req, res) {
if(!req.user.hasPermission('system.dashboard.view')) {
res.forbidden(req.__('Error.Authorization.NoRights'));
} else {
var widgetContents = [];
sails.app.customWidgets.forEach(function(widget) {
var controller = widget.controller.toLowerCase();
var action = widget.action;
var result = sails.controllers[controller][action](req);
if(result) {
result.owner = widget;
widgetContents.push(result);
}
});
res.view({ widgets: widgetContents });
}
}
};
| Use identity instead of global id. | Use identity instead of global id.
| JavaScript | mit | kumpelblase2/modlab,kumpelblase2/modlab | ---
+++
@@ -13,7 +13,7 @@
var widgetContents = [];
sails.app.customWidgets.forEach(function(widget) {
- var controller = widget.controller;
+ var controller = widget.controller.toLowerCase();
var action = widget.action;
var result = sails.controllers[controller][action](req);
if(result) { |
100f297b02149079f3b09bfff267d32be1acb514 | src/backends/createTestBackend.js | src/backends/createTestBackend.js | class TestBackend {
constructor(manager) {
this.actions = manager.getActions();
}
setup() {
this.didCallSetup = true;
}
teardown() {
this.didCallTeardown = true;
}
simulateBeginDrag(sourceIds, options) {
this.actions.beginDrag(sourceIds, options);
}
simulatePublishDragSource() {
this.actions.publishDragSource();
}
simulateHover(targetIds, options) {
this.actions.hover(targetIds, options);
}
simulateDrop() {
this.actions.drop();
}
simulateEndDrag() {
this.actions.endDrag();
}
}
export default function createBackend(manager) {
return new TestBackend(manager);
} | import noop from 'lodash/utility/noop';
class TestBackend {
constructor(manager) {
this.actions = manager.getActions();
}
setup() {
this.didCallSetup = true;
}
teardown() {
this.didCallTeardown = true;
}
connectDragSource() {
return noop;
}
connectDragPreview() {
return noop;
}
connectDropTarget() {
return noop;
}
simulateBeginDrag(sourceIds, options) {
this.actions.beginDrag(sourceIds, options);
}
simulatePublishDragSource() {
this.actions.publishDragSource();
}
simulateHover(targetIds, options) {
this.actions.hover(targetIds, options);
}
simulateDrop() {
this.actions.drop();
}
simulateEndDrag() {
this.actions.endDrag();
}
}
export default function createBackend(manager) {
return new TestBackend(manager);
} | Add noop connect* methods to the test backend | Add noop connect* methods to the test backend
| JavaScript | mit | zetkin/dnd-core,gaearon/dnd-core,randrianov/dnd-core,zetkin/dnd-core,mattiasgronlund/dnd-core | ---
+++
@@ -1,3 +1,5 @@
+import noop from 'lodash/utility/noop';
+
class TestBackend {
constructor(manager) {
this.actions = manager.getActions();
@@ -9,6 +11,18 @@
teardown() {
this.didCallTeardown = true;
+ }
+
+ connectDragSource() {
+ return noop;
+ }
+
+ connectDragPreview() {
+ return noop;
+ }
+
+ connectDropTarget() {
+ return noop;
}
simulateBeginDrag(sourceIds, options) { |
215485b42d4249ac668617fd416dd4b2e154532d | src/builders/text-view-builder.js | src/builders/text-view-builder.js | export function textViewBuilder(node) {
var view = document.createElement("div");
var textView = document.createElement("div");
textView.style.whiteSpace = "pre-wrap";
view.appendChild(textView);
if (node.value === null || node.value === undefined) {
textView.textContent = "";
} else {
textView.textContent = node.value.toString();
}
view.lynxGetValue = function () {
return textView.textContent;
};
return view;
}
| export function textViewBuilder(node) {
var view = document.createElement("div");
var textView = document.createElement("pre");
view.appendChild(textView);
if (node.value === null || node.value === undefined) {
textView.textContent = "";
} else {
textView.textContent = node.value.toString();
}
view.lynxGetValue = function () {
return textView.textContent;
};
return view;
}
| Revert text builder to 'pre' | Revert text builder to 'pre'
| JavaScript | mit | lynx-json/jsua-lynx | ---
+++
@@ -1,7 +1,6 @@
export function textViewBuilder(node) {
var view = document.createElement("div");
- var textView = document.createElement("div");
- textView.style.whiteSpace = "pre-wrap";
+ var textView = document.createElement("pre");
view.appendChild(textView);
|
5be7b88174faa8925223eab62498a9ba61680497 | src/client/initialize-platform.js | src/client/initialize-platform.js | 'use strict';
import emptyFunction from '../utils/empty-function';
function initializeShopifyPlatform(context, currentConfig, hull) {
const { customerId, accessToken, callbackUrl } = currentConfig.get();
if (!customerId && hull.currentUser()) {
hull.api('services/shopify/login', { return_to: document.location.href }).then(function(r) {
// If the platform has multipass enabled and we are NOT inside the customizer
// we can log the customer in without knowing his password.
if (r.auth === 'multipass' && !(callbackUrl || "").match('__hull_proxy__')) {
let l = 'https://' + document.location.host + '/account/login/multipass/' + r.token;
window.location = l;
} else {
hull.logout();
}
});
} else if (/^[0-9]+$/.test(customerId) && !accessToken) {
hull.api('services/shopify/customers/' + customerId, 'put').then(function() {
document.location.reload();
});
}
Hull.on('hull.user.logout', function() {
document.location = '/account/logout';
});
}
function getPlatformInitializer(platform) {
if (platform.type === 'platforms/shopify_shop') {
return initializeShopifyPlatform;
} else {
return emptyFunction;
}
}
function initializePlatform(context, currentConfig, hull) {
const initializer = getPlatformInitializer(context.app);
return initializer(context, currentConfig, hull);
}
export default initializePlatform;
| 'use strict';
import emptyFunction from '../utils/empty-function';
function initializeShopifyPlatform(context, currentConfig, hull) {
const { customerId, accessToken, callbackUrl } = currentConfig.get();
if (!customerId && hull.currentUser()) {
hull.api('services/shopify/login', { return_to: document.location.href }).then(function(r) {
// If the platform has multipass enabled and we are NOT inside the customizer
// we can log the customer in without knowing his password.
if (r.auth === 'multipass') {
if (!(callbackUrl || "").match('__hull_proxy__')) {
let l = 'https://' + document.location.host + '/account/login/multipass/' + r.token;
window.location = l;
}
} else {
hull.logout();
}
});
} else if (/^[0-9]+$/.test(customerId) && !accessToken) {
hull.api('services/shopify/customers/' + customerId, 'put').then(function() {
document.location.reload();
});
}
Hull.on('hull.user.logout', function() {
document.location = '/account/logout';
});
}
function getPlatformInitializer(platform) {
if (platform.type === 'platforms/shopify_shop') {
return initializeShopifyPlatform;
} else {
return emptyFunction;
}
}
function initializePlatform(context, currentConfig, hull) {
const initializer = getPlatformInitializer(context.app);
return initializer(context, currentConfig, hull);
}
export default initializePlatform;
| Fix prevent multipass inside customizer | Fix prevent multipass inside customizer
| JavaScript | mit | hull/hull-js,hull/hull-js,hull/hull-js | ---
+++
@@ -10,9 +10,11 @@
hull.api('services/shopify/login', { return_to: document.location.href }).then(function(r) {
// If the platform has multipass enabled and we are NOT inside the customizer
// we can log the customer in without knowing his password.
- if (r.auth === 'multipass' && !(callbackUrl || "").match('__hull_proxy__')) {
- let l = 'https://' + document.location.host + '/account/login/multipass/' + r.token;
- window.location = l;
+ if (r.auth === 'multipass') {
+ if (!(callbackUrl || "").match('__hull_proxy__')) {
+ let l = 'https://' + document.location.host + '/account/login/multipass/' + r.token;
+ window.location = l;
+ }
} else {
hull.logout();
} |
50ae43f52b8c4fb8c9a65d46fdf10b46359e4035 | src/collection/standard/Strike.js | src/collection/standard/Strike.js | const BasicCard = require('../BasicCard');
class Strike extends BasicCard {
constructor(suit, number) {
super('strike', suit, number);
}
}
module.exports = Strike;
| const BasicCard = require('../BasicCard');
const Phase = require('../../core/Player/Phase');
const DamageStruct = require('../../driver/DamageStruct');
class Strike extends BasicCard {
constructor(suit, number) {
super('strike', suit, number);
}
async isAvailable(source) {
return source && source.getPhase() === Phase.Play;
}
async targetFilter(selected, target, source) {
if (selected.length > 0 || !target) {
return false;
}
const driver = target.getDriver();
if (!driver) {
return false;
}
if (!source) {
return true;
}
if (source === target) {
return false;
}
const inRange = await driver.isInAttackRange(source, target);
return inRange;
}
async targetFeasible(selected) {
return selected.length === 1;
}
async effect(driver, effect) {
const damage = new DamageStruct(effect.from, effect.to, 1);
driver.damage(damage);
}
}
module.exports = Strike;
| Add a simple version of strike | Add a simple version of strike
| JavaScript | agpl-3.0 | takashiro/sanguosha-server,takashiro/sanguosha-server | ---
+++
@@ -1,9 +1,47 @@
const BasicCard = require('../BasicCard');
+const Phase = require('../../core/Player/Phase');
+
+const DamageStruct = require('../../driver/DamageStruct');
class Strike extends BasicCard {
constructor(suit, number) {
super('strike', suit, number);
}
+
+ async isAvailable(source) {
+ return source && source.getPhase() === Phase.Play;
+ }
+
+ async targetFilter(selected, target, source) {
+ if (selected.length > 0 || !target) {
+ return false;
+ }
+
+ const driver = target.getDriver();
+ if (!driver) {
+ return false;
+ }
+
+ if (!source) {
+ return true;
+ }
+
+ if (source === target) {
+ return false;
+ }
+
+ const inRange = await driver.isInAttackRange(source, target);
+ return inRange;
+ }
+
+ async targetFeasible(selected) {
+ return selected.length === 1;
+ }
+
+ async effect(driver, effect) {
+ const damage = new DamageStruct(effect.from, effect.to, 1);
+ driver.damage(damage);
+ }
}
module.exports = Strike; |
faf80832c80b16ed10d3fde70fd2da1475120206 | src/server-connection/server-connection-default-response-interceptors.js | src/server-connection/server-connection-default-response-interceptors.js | 'use strict';
angular.module( 'ngynServerConnection' )
.value( 'defaultResponseInterceptors', {
jsonNetStripper: function( hubName, methodName, response ) {
if ( response.$values ) {
return response.$values;
}
return response;
}
} );
| 'use strict';
angular.module( 'ngynServerConnection' )
.value( 'defaultResponseInterceptors', {
jsonNetStripper: function( hubName, methodName, response ) {
if ( response && response.$values ) {
return response.$values;
}
return response;
}
} );
| Fix issue dealing with empty responses in response interceptor | Fix issue dealing with empty responses in response interceptor | JavaScript | mit | configit/ngyn | ---
+++
@@ -3,7 +3,7 @@
angular.module( 'ngynServerConnection' )
.value( 'defaultResponseInterceptors', {
jsonNetStripper: function( hubName, methodName, response ) {
- if ( response.$values ) {
+ if ( response && response.$values ) {
return response.$values;
}
|
ad167936a67a574addc34d320f229b3417b005b2 | lib/CyclicHeapDump.js | lib/CyclicHeapDump.js | /**
* Created by ronyadgar on 29/11/2015.
*/
var heapdump = require('heapdump');
var logger = require('./logger/logger')(module);
var fs = require('fs');
var config = require('./../common/Configuration');
var path = require('path');
module.exports = (function(){
var timeInterval = config.get('heapDumpParams').timeInterval || '9000000';
var windowSize = config.get('heapDumpParams').windowSize || '3';
var rootFolderPath = config.get('rootFolderPath');
var enabled = config.get('heapDumpParams').enabled;
var listOfHeapDumpFiles = [];
if (enabled) {
setInterval(function () {
var filename = Date.now() + '.heapsnapshot';
heapdump.writeSnapshot(path.join(rootFolderPath, filename), function (err, filename) {
if (err) {
logger.error("Failed to write snapshot in " + filename + ": " + err);
}
else {
if (listOfHeapDumpFiles.length === windowSize) {
var fileToDelete = listOfHeapDumpFiles.shift();
fs.unlink(fileToDelete, function (err) {
if (err) {
logger.error("Failed to delete " + fileToDelete + ": " + err);
}
else {
logger.info("Successfully deleted " + fileToDelete);
}
});
}
listOfHeapDumpFiles.push(filename);
logger.info("Successfully wrote snapshot to " + filename);
}
});
}, timeInterval);
}
})(); | /**
* Created by ronyadgar on 29/11/2015.
*/
var heapdump = require('heapdump');
var logger = require('./logger/logger')(module);
var fs = require('fs');
var config = require('./../common/Configuration');
var path = require('path');
var hostname = require('../common/utils/hostname');
module.exports = (function(){
var timeInterval = config.get('heapDumpParams').timeInterval || '9000000';
var windowSize = config.get('heapDumpParams').windowSize || '3';
var rootFolderPath = config.get('rootFolderPath');
var enabled = config.get('heapDumpParams').enabled;
var listOfHeapDumpFiles = [];
if (enabled) {
setInterval(function () {
var filename = Date.now() + '.heapsnapshot';
heapdump.writeSnapshot(path.join(rootFolderPath, hostname + "_" + filename), function (err, filename) {
if (err) {
logger.error("Failed to write snapshot in " + filename + ": " + err);
}
else {
if (listOfHeapDumpFiles.length === windowSize) {
var fileToDelete = listOfHeapDumpFiles.shift();
fs.unlink(fileToDelete, function (err) {
if (err) {
logger.error("Failed to delete " + fileToDelete + ": " + err);
}
else {
logger.info("Successfully deleted " + fileToDelete);
}
});
}
listOfHeapDumpFiles.push(filename);
logger.info("Successfully wrote snapshot to " + filename);
}
});
}, timeInterval);
}
})(); | Add machine name to heap dump file name | Add machine name to heap dump file name
| JavaScript | agpl-3.0 | kaltura/liveDVR,kaltura/liveDVR,kaltura/liveDVR,kaltura/liveDVR,kaltura/liveDVR | ---
+++
@@ -7,6 +7,7 @@
var fs = require('fs');
var config = require('./../common/Configuration');
var path = require('path');
+var hostname = require('../common/utils/hostname');
module.exports = (function(){
var timeInterval = config.get('heapDumpParams').timeInterval || '9000000';
@@ -17,7 +18,7 @@
if (enabled) {
setInterval(function () {
var filename = Date.now() + '.heapsnapshot';
- heapdump.writeSnapshot(path.join(rootFolderPath, filename), function (err, filename) {
+ heapdump.writeSnapshot(path.join(rootFolderPath, hostname + "_" + filename), function (err, filename) {
if (err) {
logger.error("Failed to write snapshot in " + filename + ": " + err);
} |
73ddb98197c2ca879880efb8d51d168253f380a8 | ui/src/utils/QualityControl.js | ui/src/utils/QualityControl.js | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Responsible for quality control
*/
export class QualityControl {
/**
* Creates an quality control instance
*/
constructor(context, blob) {
this.context = context;
this.blob = blob;
this.audioBuffer;
}
/**
* Checks if sound is of good quality: not too short or silent
*/
async isQualitySound() {
const blobArrayBuffer = await this.blob.arrayBuffer();
this.audioBuffer = await this.context.decodeAudioData(blobArrayBuffer);
const qualityResult = {
success: true,
errorMessage: '',
};
const audioResult = this.soundCheck();
if (this.audioBuffer.duration < 2.0) {
qualityResult.success = false;
qualityResult.errorMessage += 'Audio recording failed: recording was too short. Try again';
} else if (audioResult) {
qualityResult.success = false;
qualityResult.errorMessage += audioResult;
}
return qualityResult;
}
} | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Responsible for quality control
*/
export class QualityControl {
/**
* Creates an quality control instance
*/
constructor(context, blob) {
this.context = context;
this.blob = blob;
this.audioBuffer;
}
/**
* Checks if sound is of good quality: not too short or silent
*/
async isQualitySound() {
const blobArrayBuffer = await this.blob.arrayBuffer();
this.audioBuffer = await this.context.decodeAudioData(blobArrayBuffer);
const qualityResult = {
success: true,
errorMessage: '',
};
if (this.audioBuffer.duration < 2.0) {
qualityResult.success = false;
qualityResult.errorMessage += 'Audio recording failed: recording was too short. Try again';
}
return qualityResult;
}
} | Move audio check code for another pull request | Move audio check code for another pull request
| JavaScript | apache-2.0 | googleinterns/voxetta,googleinterns/voxetta,googleinterns/voxetta | ---
+++
@@ -40,16 +40,11 @@
errorMessage: '',
};
- const audioResult = this.soundCheck();
-
if (this.audioBuffer.duration < 2.0) {
qualityResult.success = false;
qualityResult.errorMessage += 'Audio recording failed: recording was too short. Try again';
- } else if (audioResult) {
- qualityResult.success = false;
- qualityResult.errorMessage += audioResult;
}
-
+
return qualityResult;
}
} |
d8f8bf6fd961de69ff432261b5af8fa10479c2ef | lib/server-impl.js | lib/server-impl.js | 'use strict';
const { EventEmitter } = require('events');
const logger = require('./logger')('server-impl.js');
const migrator = require('../migrator');
const getApp = require('./app');
const { startMonitoring } = require('./metrics');
const { createStores } = require('./db');
const { createOptions } = require('./options');
const User = require('./user');
const AuthenticationRequired = require('./authentication-required');
function createApp(options) {
// Database dependecies (statefull)
const stores = createStores(options);
const eventBus = new EventEmitter();
const config = Object.assign(
{
stores,
eventBus,
},
options
);
const app = getApp(config);
startMonitoring(options.serverMetrics, eventBus);
return new Promise(resolve => {
const server = app.listen(
{ port: options.port, host: options.host },
() => {
logger.info(`Unleash started on port ${server.address().port}`);
resolve({ app, server, eventBus });
}
);
});
}
function start(opts) {
const options = createOptions(opts);
return migrator({ databaseUrl: options.databaseUrl })
.catch(err => logger.error('failed to migrate db', err))
.then(() => createApp(options))
.catch(err => logger.error('failed creating app', err));
}
module.exports = {
start,
User,
AuthenticationRequired,
};
| 'use strict';
const { EventEmitter } = require('events');
const logger = require('./logger')('server-impl.js');
const migrator = require('../migrator');
const getApp = require('./app');
const { startMonitoring } = require('./metrics');
const { createStores } = require('./db');
const { createOptions } = require('./options');
const User = require('./user');
const AuthenticationRequired = require('./authentication-required');
function createApp(options) {
// Database dependecies (statefull)
const stores = createStores(options);
const eventBus = new EventEmitter();
const config = Object.assign(
{
stores,
eventBus,
},
options
);
const app = getApp(config);
startMonitoring(options.serverMetrics, eventBus);
const server = app.listen({ port: options.port, host: options.host }, () =>
logger.info(`Unleash started on port ${server.address().port}`)
);
return new Promise((resolve, reject) => {
server.on('listening', () => resolve({ app, server, eventBus }));
server.on('error', reject);
});
}
function start(opts) {
const options = createOptions(opts);
return migrator({ databaseUrl: options.databaseUrl })
.catch(err => logger.error('failed to migrate db', err))
.then(() => createApp(options));
}
module.exports = {
start,
User,
AuthenticationRequired,
};
| Clean up using servers listening and error events | Clean up using servers listening and error events
| JavaScript | apache-2.0 | finn-no/unleash,Unleash/unleash,Unleash/unleash,Unleash/unleash,finn-no/unleash,Unleash/unleash,finn-no/unleash | ---
+++
@@ -28,14 +28,13 @@
const app = getApp(config);
startMonitoring(options.serverMetrics, eventBus);
- return new Promise(resolve => {
- const server = app.listen(
- { port: options.port, host: options.host },
- () => {
- logger.info(`Unleash started on port ${server.address().port}`);
- resolve({ app, server, eventBus });
- }
- );
+ const server = app.listen({ port: options.port, host: options.host }, () =>
+ logger.info(`Unleash started on port ${server.address().port}`)
+ );
+
+ return new Promise((resolve, reject) => {
+ server.on('listening', () => resolve({ app, server, eventBus }));
+ server.on('error', reject);
});
}
@@ -44,8 +43,7 @@
return migrator({ databaseUrl: options.databaseUrl })
.catch(err => logger.error('failed to migrate db', err))
- .then(() => createApp(options))
- .catch(err => logger.error('failed creating app', err));
+ .then(() => createApp(options));
}
module.exports = { |
d59d22dacd0251ae9f1d833bce2d2c8a01827dae | client/actions/Event.js | client/actions/Event.js | import { createAction } from 'redux-actions'
import { createEvent as createAPI, showEvent as showAPI } from '../api/Event'
import Actions from '../constants/Actions'
import errorUrls from '../constants/ErrorUrls'
import ActionDispatch from '../utils/ActionDispatch'
export const createEvent = createAction(Actions.Event.createEvent, createAPI)
export const showEvent = (id) => {
return ActionDispatch.executeApi(showAPI, id, createEvent, errorUrls.pageNotFound)
}
| import { createAction } from 'redux-actions'
import { createEvent as createAPI, showEvent as showAPI } from '../api/Event'
import Actions from '../constants/Actions'
import errorUrls from '../constants/ErrorUrls'
import ActionDispatch from '../utils/ActionDispatch'
export const createEvent = createAction(Actions.Event.createEvent, createAPI)
export const showEvent = (id) => {
return ActionDispatch.executeApi(showAPI, id, createAction(Actions.Event.createEvent), errorUrls.pageNotFound)
}
| Fix called create API when show API success | Fix called create API when show API success
| JavaScript | mit | shinosakarb/tebukuro-client | ---
+++
@@ -7,5 +7,5 @@
export const createEvent = createAction(Actions.Event.createEvent, createAPI)
export const showEvent = (id) => {
- return ActionDispatch.executeApi(showAPI, id, createEvent, errorUrls.pageNotFound)
+ return ActionDispatch.executeApi(showAPI, id, createAction(Actions.Event.createEvent), errorUrls.pageNotFound)
} |
d48ef82944f27ae9cccf7a12e0d58419da86c561 | mixins/highlighted_stroke.mixin.js | mixins/highlighted_stroke.mixin.js | module.exports = {
borderWidth: 5,
strokeWidth: 0.1,
// in percentage of borderWidth
outlineWidth: 0.2,
outlineStyle: "#FFF",
/**
* Provide a custom stroke function that draws a fat white line THEN a
* narrower colored line on top.
*/
_stroke: function (ctx) {
var myScale = this.scaleX;
var outline = this._outlineWidth();
function scale(x) {
return Math.round(x) / myScale;
}
ctx.lineWidth = scale(this.borderWidth + outline);
ctx.strokeStyle = this.outlineStyle;
ctx.stroke();
ctx.lineWidth = scale(this.borderWidth - outline);
ctx.strokeStyle = this.stroke;
ctx.stroke();
},
_outlineWidth: function () {
return Math.max(1, Math.round(this.borderWidth * this.outlineWidth));
},
/**
* This is primarily used to get a bounding rect for drawing borders and
* doing a hit-test for mouse events. We extend the size by the borderWidth
* cause rectangles and axis lines (horiz or vert) have half their
* borderWidth outside the actual bounding rect of the shape.
*/
_calculateCurrentDimensions: function (shouldTransform) {
var p = this.callParent(shouldTransform);
var b = this.borderWidth + this._outlineWidth();
return { x: p.x + b, y: p.y + b };
},
};
| module.exports = {
borderWidth: 5,
strokeWidth: 0.1,
// in percentage of borderWidth
outlineWidth: 0.2,
outlineStyle: "#FFF",
/**
* Provide a custom stroke function that draws a fat white line THEN a
* narrower colored line on top.
*/
_renderStroke: function (ctx) {
var myScale = this.scaleX;
var outline = this._outlineWidth();
function scale(x) {
return Math.round(x) / myScale;
}
ctx.lineWidth = scale(this.borderWidth + outline);
ctx.strokeStyle = this.outlineStyle;
ctx.stroke();
ctx.lineWidth = scale(this.borderWidth - outline);
ctx.strokeStyle = this.stroke;
ctx.stroke();
},
_outlineWidth: function () {
return Math.max(1, Math.round(this.borderWidth * this.outlineWidth));
},
/**
* This is primarily used to get a bounding rect for drawing borders and
* doing a hit-test for mouse events. We extend the size by the borderWidth
* cause rectangles and axis lines (horiz or vert) have half their
* borderWidth outside the actual bounding rect of the shape.
*/
_calculateCurrentDimensions: function (shouldTransform) {
var p = this.callParent(shouldTransform);
var b = this.borderWidth + this._outlineWidth();
return { x: p.x + b, y: p.y + b };
},
};
| Change custom stroke override method | Change custom stroke override method
Peeking into the fabric source, it looks like the `_stroke` method we're
overriding in the `highlighted_stroke` mixin has been renamed to
`_renderStroke`. Making sure we override the correct method, we start
seeing our customized stroke rendering.
| JavaScript | mit | iFixit/node-markup,iFixit/node-markup,iFixit/node-markup | ---
+++
@@ -9,7 +9,7 @@
* Provide a custom stroke function that draws a fat white line THEN a
* narrower colored line on top.
*/
- _stroke: function (ctx) {
+ _renderStroke: function (ctx) {
var myScale = this.scaleX;
var outline = this._outlineWidth();
function scale(x) { |
9824a59c2a94db807924ffced01fe43cdb036d86 | src/Utils/windowEvents.js | src/Utils/windowEvents.js | var nullEvents = require('./nullEvents.js');
module.exports = createDocumentEvents();
function createDocumentEvents() {
if (typeof window === undefined) {
return nullEvents;
}
return {
on: on,
off: off
};
}
function on(eventName, handler) {
window.addEventListener(eventName, handler);
}
function off(eventName, handler) {
window.removeEventListener(eventName, handler);
}
| var nullEvents = require('./nullEvents.js');
module.exports = createDocumentEvents();
function createDocumentEvents() {
if (typeof window === 'undefined') {
return nullEvents;
}
return {
on: on,
off: off
};
}
function on(eventName, handler) {
window.addEventListener(eventName, handler);
}
function off(eventName, handler) {
window.removeEventListener(eventName, handler);
}
| Correct check for undefined variable | Correct check for undefined variable
The code was comparing the result of `typeof` with a variable named `undefined`
As typeof returns a string it should compare to `'undefined'` | JavaScript | bsd-3-clause | rlugojr/VivaGraphJS,rlugojr/VivaGraphJS | ---
+++
@@ -3,7 +3,7 @@
module.exports = createDocumentEvents();
function createDocumentEvents() {
- if (typeof window === undefined) {
+ if (typeof window === 'undefined') {
return nullEvents;
}
|
06746ed23aee3ab6ff931ea89c90a38893cb4b64 | lib/popupPresenter.js | lib/popupPresenter.js | 'use strict';
var assert = require('assert')
var handlebars = require('handlebars')
var cssInjector = require('../wrappers/cssInjector')
var assetManager = require('./assetManager')
/**
* Class to handle css and html template for a layers popup generation
* Css is injected into the dom and a function is returned via 'present'
* that can be used by the map on a per geosjon feature basis
*/
class PopupPresenter {
/**
* Creates a template function from config and injects given layer css
* file into the dom
*/
constructor(config) {
assert.equal(typeof (config), 'object', '\'config\' arg must be an object')
var templateContent = assetManager.assets.templates[config.template]
this.template = handlebars.compile(templateContent)
var css = assetManager.assets.css[config.css]
cssInjector(css)
}
/**
* Renders properties into a template string using template function
* created in the constructor
* @param {object} properties
* @return {string}
*/
present(properties) {
assert.equal(typeof (properties), 'object', '\'properties\' arg must be an object')
return this.template(properties)
}
}
module.exports = (config) => new PopupPresenter(config)
| 'use strict';
var assert = require('assert')
var handlebars = require('handlebars')
var cssInjector = require('../wrappers/cssInjector')
var assetManager = require('./assetManager')()
/**
* Class to handle css and html template for a layers popup generation
* Css is injected into the dom and a function is returned via 'present'
* that can be used by the map on a per geosjon feature basis
*/
class PopupPresenter {
/**
* Creates a template function from config and injects given layer css
* file into the dom
*/
constructor(config) {
assert.equal(typeof (config), 'object', '\'config\' arg must be an object')
var templateContent = assetManager.assets.templates[config.template]
this.template = handlebars.compile(templateContent)
var css = assetManager.assets.css[config.css]
cssInjector(css)
}
/**
* Renders properties into a template string using template function
* created in the constructor
* @param {object} properties
* @return {string}
*/
present(properties) {
assert.equal(typeof (properties), 'object', '\'properties\' arg must be an object')
return this.template(properties)
}
}
module.exports = (config) => new PopupPresenter(config)
| Fix assetManager not being instantiated | Fix assetManager not being instantiated
| JavaScript | mit | mediasuitenz/mappy,mediasuitenz/mappy | ---
+++
@@ -3,7 +3,7 @@
var assert = require('assert')
var handlebars = require('handlebars')
var cssInjector = require('../wrappers/cssInjector')
-var assetManager = require('./assetManager')
+var assetManager = require('./assetManager')()
/**
* Class to handle css and html template for a layers popup generation |
afdc029605de38f0b70216d9dc41e232f5c93e90 | app/assets/javascripts/inventories.index.js | app/assets/javascripts/inventories.index.js | document.addEventListener("turbolinks:load", function() {
function inventoryButtonClickHandler(e) {
e.preventDefault();
let formInputs = document.getElementById('form-inputs');
time = new Date().getTime()
regexp = new RegExp(inventoryButton.dataset.id, 'g')
formInputs.insertAdjacentHTML('beforebegin', inventoryButton.dataset.fields.replace(regexp, time))
}
let inventoryButton = document.getElementById('add-component-button');
if (inventoryButton) {
inventoryButton.addEventListener('click', inventoryButtonClickHandler, false);
}
})
| document.addEventListener("turbolinks:load", function() {
function inventoryButtonClickHandler(e) {
e.preventDefault();
var formInputs = document.getElementById('form-inputs');
time = new Date().getTime()
regexp = new RegExp(inventoryButton.dataset.id, 'g')
formInputs.insertAdjacentHTML('beforebegin', inventoryButton.dataset.fields.replace(regexp, time))
}
var inventoryButton = document.getElementById('add-component-button');
if (inventoryButton) {
inventoryButton.addEventListener('click', inventoryButtonClickHandler, false);
}
})
| Switch back to ES5 variable syntax. | Switch back to ES5 variable syntax. | JavaScript | mit | enthusiastick/my_crossroads,enthusiastick/my_crossroads,enthusiastick/my_crossroads,enthusiastick/my_crossroads | ---
+++
@@ -1,12 +1,12 @@
document.addEventListener("turbolinks:load", function() {
function inventoryButtonClickHandler(e) {
e.preventDefault();
- let formInputs = document.getElementById('form-inputs');
+ var formInputs = document.getElementById('form-inputs');
time = new Date().getTime()
regexp = new RegExp(inventoryButton.dataset.id, 'g')
formInputs.insertAdjacentHTML('beforebegin', inventoryButton.dataset.fields.replace(regexp, time))
}
- let inventoryButton = document.getElementById('add-component-button');
+ var inventoryButton = document.getElementById('add-component-button');
if (inventoryButton) {
inventoryButton.addEventListener('click', inventoryButtonClickHandler, false);
} |
2f4cf118d5748569acd77d861503a91d24a776e5 | addon/components/gravatar-image.js | addon/components/gravatar-image.js | import Ember from 'ember';
import md5 from 'md5';
export default Ember.Component.extend({
tagName: 'img',
attributeBindings: ['src', 'alt', 'title'],
classNames: ['gravatar-image'],
size: 250,
email: '',
title: '',
defaultImage: '',
secure: true,
src: Ember.computed('email', 'size', 'default', function() {
var email = this.get('email');
var size = this.get('size');
var def = this.get('defaultImage');
var secure = this.get('secure');
var protocol = secure ? 'https' : 'http';
return protocol + '://www.gravatar.com/avatar/' + md5(email) + '?s=' + size + '&d=' + def;
})
});
| import Ember from 'ember';
import md5 from 'md5';
export default Ember.Component.extend({
tagName: 'img',
attributeBindings: ['src', 'alt', 'title'],
classNames: ['gravatar-image'],
size: 250,
email: '',
title: '',
defaultImage: '',
secure: true,
retina: false,
src: Ember.computed('email', 'imageSize', 'default', function() {
var email = this.get('email');
var imageSize = this.get('imageSize');
var def = this.get('defaultImage');
var secure = this.get('secure');
var protocol = secure ? 'https' : 'http';
return protocol + '://www.gravatar.com/avatar/' + md5(email) + '?s=' + imageSize + '&d=' + def;
}),
imageSize: Ember.computed('size', function() {
var size = this.get('size');
return this.get('retina') ? (size * 2) : size;
})
});
| Add support for retina images | Add support for retina images
| JavaScript | mit | johnotander/ember-cli-gravatar,johnotander/ember-cli-gravatar | ---
+++
@@ -10,14 +10,20 @@
title: '',
defaultImage: '',
secure: true,
+ retina: false,
- src: Ember.computed('email', 'size', 'default', function() {
+ src: Ember.computed('email', 'imageSize', 'default', function() {
var email = this.get('email');
- var size = this.get('size');
+ var imageSize = this.get('imageSize');
var def = this.get('defaultImage');
var secure = this.get('secure');
var protocol = secure ? 'https' : 'http';
- return protocol + '://www.gravatar.com/avatar/' + md5(email) + '?s=' + size + '&d=' + def;
+ return protocol + '://www.gravatar.com/avatar/' + md5(email) + '?s=' + imageSize + '&d=' + def;
+ }),
+
+ imageSize: Ember.computed('size', function() {
+ var size = this.get('size');
+ return this.get('retina') ? (size * 2) : size;
})
}); |
ecdb97ae3553772a88afd1cb8d7e9edd3f122a68 | conf/buster-coverage.js | conf/buster-coverage.js | module.exports.unit = {
environment: 'node',
rootPath: process.cwd(),
sources: [
'lib/**/*.js'
],
tests: [
'test/**/*.js'
],
extensions: [
require('buster-istanbul')
],
'buster-istanbul': {
outputDirectory: '.bob/report/coverage/buster-istanbul/'
}
};
| module.exports.unit = {
environment: 'node',
rootPath: process.cwd(),
sources: [
'lib/**/*.js'
],
tests: [
'test/**/*.js'
],
extensions: [
require('buster-istanbul')
],
'buster-istanbul': {
outputDirectory: '.bob/report/coverage/buster-istanbul/',
formats: ['text', 'lcov']
}
};
| Add lcov report to buster-istanbul coverage. | Add lcov report to buster-istanbul coverage.
| JavaScript | mit | cliffano/bob | ---
+++
@@ -11,6 +11,7 @@
require('buster-istanbul')
],
'buster-istanbul': {
- outputDirectory: '.bob/report/coverage/buster-istanbul/'
+ outputDirectory: '.bob/report/coverage/buster-istanbul/',
+ formats: ['text', 'lcov']
}
}; |
644e73734804173a56cc3d7a85e6ed7eb6067782 | ember/tests/acceptance/index-test.js | ember/tests/acceptance/index-test.js | import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { visit, currentURL } from '@ember/test-helpers';
import { setupPretender } from 'skylines/tests/helpers/setup-pretender';
module('Acceptance | index', function(hooks) {
setupApplicationTest(hooks);
setupPretender(hooks);
hooks.beforeEach(async function(assert) {
await visit('/');
assert.equal(currentURL(), '/');
});
test('shows a welcome message', function(assert) {
assert.dom('[data-test-welcome-message]').exists();
});
});
| import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { visit, currentURL } from '@ember/test-helpers';
import { setupPolly } from 'skylines/tests/helpers/setup-polly';
module('Acceptance | index', function(hooks) {
setupApplicationTest(hooks);
setupPolly(hooks, { recordIfMissing: false });
hooks.beforeEach(async function(assert) {
await visit('/');
assert.equal(currentURL(), '/');
});
test('shows a welcome message', function(assert) {
assert.dom('[data-test-welcome-message]').exists();
});
});
| Use Polly.js instead of Pretender | tests/index: Use Polly.js instead of Pretender
| JavaScript | agpl-3.0 | Harry-R/skylines,skylines-project/skylines,Turbo87/skylines,Turbo87/skylines,skylines-project/skylines,skylines-project/skylines,Turbo87/skylines,Harry-R/skylines,RBE-Avionik/skylines,RBE-Avionik/skylines,Harry-R/skylines,RBE-Avionik/skylines,Harry-R/skylines,skylines-project/skylines,Turbo87/skylines,RBE-Avionik/skylines | ---
+++
@@ -2,11 +2,11 @@
import { setupApplicationTest } from 'ember-qunit';
import { visit, currentURL } from '@ember/test-helpers';
-import { setupPretender } from 'skylines/tests/helpers/setup-pretender';
+import { setupPolly } from 'skylines/tests/helpers/setup-polly';
module('Acceptance | index', function(hooks) {
setupApplicationTest(hooks);
- setupPretender(hooks);
+ setupPolly(hooks, { recordIfMissing: false });
hooks.beforeEach(async function(assert) {
await visit('/'); |
547c90c7b2c93c65aa2c6306da36cbc3681fd727 | lib/best-practices.js | lib/best-practices.js |
module.exports = {
extends: [
'eslint-config-airbnb-base/rules/best-practices'
],
rules: {
// Enforce that class methods use `this`
// http://eslint.org/docs/rules/class-methods-use-this
'class-methods-use-this': 'off',
// Enforce a maximum cyclomatic complexity allowed in a program
// http://eslint.org/docs/rules/complexity
complexity: 'off',
// Enforce consistent brace style for all control statements
// http://eslint.org/docs/rules/curly
curly: ['error', 'all'],
// Disallow shorthand type conversions
// http://eslint.org/docs/rules/no-implicit-coercion
'no-implicit-coercion': ['error', {
boolean: false,
number: false,
string: true,
}],
// Disallow `var` and named `function` declarations in the global scope
// http://eslint.org/docs/rules/no-implicit-globals
'no-implicit-globals': 'error',
// Disallow throwing literals as exceptions
// http://eslint.org/docs/rules/no-throw-literal
'no-throw-literal': 'off',
// Disallow unmodified loop conditions
// http://eslint.org/docs/rules/no-unmodified-loop-condition
'no-unmodified-loop-condition': 'error',
},
};
|
module.exports = {
extends: [
'eslint-config-airbnb-base/rules/best-practices'
],
rules: {
// Enforce that class methods use `this`
// http://eslint.org/docs/rules/class-methods-use-this
'class-methods-use-this': 'off',
// Enforce a maximum cyclomatic complexity allowed in a program
// http://eslint.org/docs/rules/complexity
complexity: 'off',
// Enforce consistent brace style for all control statements
// http://eslint.org/docs/rules/curly
curly: ['error', 'all'],
// Disallow shorthand type conversions
// http://eslint.org/docs/rules/no-implicit-coercion
'no-implicit-coercion': ['error', {
boolean: false,
number: false,
string: true,
}],
// Disallow `var` and named `function` declarations in the global scope
// http://eslint.org/docs/rules/no-implicit-globals
'no-implicit-globals': 'error',
// Disallow throwing literals as exceptions
// http://eslint.org/docs/rules/no-throw-literal
'no-throw-literal': 'off',
// Disallow unmodified loop conditions
// http://eslint.org/docs/rules/no-unmodified-loop-condition
'no-unmodified-loop-condition': 'error',
// Disallow Unused Expressions
// http://eslint.org/docs/rules/no-unused-expressions
'no-unused-expressions': ['error', {
allowShortCircuit: false,
allowTernary: false,
allowTaggedTemplates: true,
}],
},
};
| Enable allowTaggedTemplates options in no-unused-expressions rule | Enable allowTaggedTemplates options in no-unused-expressions rule
| JavaScript | mit | njakob/eslint-config | ---
+++
@@ -35,5 +35,13 @@
// Disallow unmodified loop conditions
// http://eslint.org/docs/rules/no-unmodified-loop-condition
'no-unmodified-loop-condition': 'error',
+
+ // Disallow Unused Expressions
+ // http://eslint.org/docs/rules/no-unused-expressions
+ 'no-unused-expressions': ['error', {
+ allowShortCircuit: false,
+ allowTernary: false,
+ allowTaggedTemplates: true,
+ }],
},
}; |
2b3a1d54ff611dc1919282eac0803f83ae4e655e | reviewboard/static/rb/js/resources/models/draftResourceChildModelMixin.js | reviewboard/static/rb/js/resources/models/draftResourceChildModelMixin.js | /*
* Mixin for resources that are children of a draft resource.
*
* This will ensure that the draft is in a proper state before operating
* on the resource.
*/
RB.DraftResourceChildModelMixin = {
/*
* Calls a function when the object is ready to use.
*
* This will ensure the draft is created before ensuring the object
* is ready.
*/
ready: function(options, context) {
this.get('parentObject').ensureCreated({
success: _.bind(_.super(this).ready, this, options, context),
error: options.error
}, context);
}
};
| /*
* Mixin for resources that are children of a draft resource.
*
* This will ensure that the draft is in a proper state before operating
* on the resource.
*/
RB.DraftResourceChildModelMixin = {
/*
* Deletes the object's resource on the server.
*
* This will ensure the draft is created before deleting the object,
* in order to record the deletion as part of the draft.
*/
destroy: function(options, context) {
options = options || {};
this.get('parentObject').ensureCreated({
success: _.bind(_.super(this).destroy, this, options, context),
error: options.error
}, context);
},
/*
* Calls a function when the object is ready to use.
*
* This will ensure the draft is created before ensuring the object
* is ready.
*/
ready: function(options, context) {
options = options || {};
this.get('parentObject').ensureCreated({
success: _.bind(_.super(this).ready, this, options, context),
error: options.error
}, context);
}
};
| Fix deleting file attachments without a draft. | Fix deleting file attachments without a draft.
File attachment deletion was broken without a draft, since destroy()
doesn't call ready() first, causing the draft to never be created. Now
destroy() does an ensureCreated() on the draft.
| JavaScript | mit | bkochendorfer/reviewboard,1tush/reviewboard,reviewboard/reviewboard,custode/reviewboard,1tush/reviewboard,chipx86/reviewboard,KnowNo/reviewboard,KnowNo/reviewboard,sgallagher/reviewboard,brennie/reviewboard,beol/reviewboard,chipx86/reviewboard,davidt/reviewboard,1tush/reviewboard,KnowNo/reviewboard,beol/reviewboard,beol/reviewboard,custode/reviewboard,beol/reviewboard,davidt/reviewboard,bkochendorfer/reviewboard,1tush/reviewboard,1tush/reviewboard,reviewboard/reviewboard,davidt/reviewboard,sgallagher/reviewboard,chipx86/reviewboard,reviewboard/reviewboard,brennie/reviewboard,custode/reviewboard,brennie/reviewboard,chipx86/reviewboard,reviewboard/reviewboard,sgallagher/reviewboard,1tush/reviewboard,custode/reviewboard,bkochendorfer/reviewboard,KnowNo/reviewboard,1tush/reviewboard,davidt/reviewboard,bkochendorfer/reviewboard,1tush/reviewboard,sgallagher/reviewboard,1tush/reviewboard,brennie/reviewboard | ---
+++
@@ -6,12 +6,29 @@
*/
RB.DraftResourceChildModelMixin = {
/*
+ * Deletes the object's resource on the server.
+ *
+ * This will ensure the draft is created before deleting the object,
+ * in order to record the deletion as part of the draft.
+ */
+ destroy: function(options, context) {
+ options = options || {};
+
+ this.get('parentObject').ensureCreated({
+ success: _.bind(_.super(this).destroy, this, options, context),
+ error: options.error
+ }, context);
+ },
+
+ /*
* Calls a function when the object is ready to use.
*
* This will ensure the draft is created before ensuring the object
* is ready.
*/
ready: function(options, context) {
+ options = options || {};
+
this.get('parentObject').ensureCreated({
success: _.bind(_.super(this).ready, this, options, context),
error: options.error |
fbb153862dd281c6f491ba0a93955fe9e6b38157 | src/components/Experiment/Playground/MediaDevices/MediaDevicesControls.js | src/components/Experiment/Playground/MediaDevices/MediaDevicesControls.js | import React from 'react';
import Icon from '../../../Icon';
const MediaDevicesControls = ({ snaps, areMultipleVideoDevices, handleVideoDeviceChange }) => (
<div
className="experiment__playground__content--media-devices__controls"
>
<div
className="experiment__playground__content--media-devices__controls__strip"
>
{
snaps && snaps.map((snap, index) => (
<img
className="experiment__playground__content--media-devices__controls__strip__item"
alt={`Snap ${index}`}
key={index}
src={snap}
/>
))
}
</div>
{areMultipleVideoDevices &&
<button
className="experiment__playground__content__button"
onClick={handleVideoDeviceChange}
>
<Icon
name="switch_camera"
/>
</button>
}
</div>
);
export default MediaDevicesControls;
| import React from 'react';
import Icon from '../../../Icon';
const MediaDevicesControls = ({ snaps, areMultipleVideoDevices, handleVideoDeviceChange }) => (
<div
className="experiment__playground__content--media-devices__controls"
>
<div
className="experiment__playground__content--media-devices__controls__strip"
>
{
snaps && snaps.map((snap, index) => (
<img
className="experiment__playground__content--media-devices__controls__strip__item"
alt={`Snap ${index}`}
key={index}
src={snap}
/>
))
}
</div>
{areMultipleVideoDevices &&
<button
className="experiment__playground__content__button"
onClick={handleVideoDeviceChange}
>
<Icon
name="switch_video"
/>
</button>
}
</div>
);
export default MediaDevicesControls;
| Use clearer icon for camera switching in MediaDevices experiment | Use clearer icon for camera switching in MediaDevices experiment
| JavaScript | mit | soyguijarro/magic-web,soyguijarro/magic-web | ---
+++
@@ -25,7 +25,7 @@
onClick={handleVideoDeviceChange}
>
<Icon
- name="switch_camera"
+ name="switch_video"
/>
</button>
} |
951d3a877b48ee623713f8af7daec9fbfbe6b7ce | app/components/init-foundation.js | app/components/init-foundation.js | import Ember from 'ember';
export default Ember.Component.extend({
foundation: null,
currentClassName: Ember.computed("className", function(){
return this.get("className") ? `.${this.get('className')}` : document;
}),
click() {
if($('.off-canvas-wrap.move-right')[0]) {
$('html').css('overflow', 'auto');
} else {
$('html').css('overflow', 'hidden');
}
},
didInsertElement() {
var className = this.get("currentClassName");
var _this = this;
this._super();
Ember.run.debounce(this, function(){
var clientHeight = $( window ).height();
$('.inner-wrap').css('min-height', clientHeight);
}, 1000);
Ember.run.scheduleOnce('afterRender', this, function(){
var initFoundation = Ember.$(className).foundation({
offcanvas: { close_on_click: true }
});
_this.set("foundation", initFoundation);
});
}
// TODO: Breaks sometime on menu-bar
// willDestroyElement() {
// this.get("foundation").foundation("destroy");
// }
});
| import Ember from 'ember';
export default Ember.Component.extend({
foundation: null,
currentClassName: Ember.computed("className", function(){
return this.get("className") ? `.${this.get('className')}` : document;
}),
didInsertElement() {
var className = this.get("currentClassName");
var _this = this;
this._super();
Ember.run.debounce(this, function(){
var clientHeight = $( window ).height();
$('.inner-wrap').css('min-height', clientHeight);
}, 1000);
Ember.run.scheduleOnce('afterRender', this, function(){
var initFoundation = Ember.$(className).foundation({
offcanvas: { close_on_click: true }
});
_this.set("foundation", initFoundation);
});
}
// TODO: Breaks sometime on menu-bar
// willDestroyElement() {
// this.get("foundation").foundation("destroy");
// }
});
| Revert "GCW-1826 Disable off canvas scroll" | Revert "GCW-1826 Disable off canvas scroll"
| JavaScript | mit | crossroads/shared.goodcity,crossroads/shared.goodcity | ---
+++
@@ -7,14 +7,6 @@
currentClassName: Ember.computed("className", function(){
return this.get("className") ? `.${this.get('className')}` : document;
}),
-
- click() {
- if($('.off-canvas-wrap.move-right')[0]) {
- $('html').css('overflow', 'auto');
- } else {
- $('html').css('overflow', 'hidden');
- }
- },
didInsertElement() {
var className = this.get("currentClassName"); |
9bd0feab475daa578b40d3875e95b01a149165fb | tabist/background.js | tabist/background.js | var extURL = chrome.extension.getURL("tabs.html");
function openMyPage() {
browser.windows.getCurrent({}).then(function(window) {
return browser.tabs.query({windowId: window.id});
}).then(function(tabs) {
//check for a tabist tab first
for(let tab of tabs) {
if(tab.title == "Tabist"){
//open that tab
chrome.tabs.update(tab.id, {active: true});
return;
}
}
//loop through again to see if there is an active new tab to replace
for(let tab of tabs) {
if(tab.title == "New Tab" && tab.active){
chrome.tabs.update(tab.id, {"url": extURL});
return;
}
}
//fallback to making a new tabist tab
chrome.tabs.create({
"url": extURL
//,"pinned": true // TODO: add pinned option
});
return;
}).catch(e => {
console.log(e.message);
});
}
chrome.browserAction.onClicked.addListener(openMyPage);
| var extURL = chrome.extension.getURL("tabs.html");
function openMyPage() {
chrome.windows.getCurrent({}, function(window) {
chrome.tabs.query({windowId: window.id}, function(tabs) {
//check for a tabist tab first
for(let tab of tabs) {
if(tab.title == "Tabist"){
//open that tab
chrome.tabs.update(tab.id, {active: true});
return;
}
}
//loop through again to see if there is an active new tab to replace
for(let tab of tabs) {
if(tab.title == "New Tab" && tab.active){
chrome.tabs.update(tab.id, {"url": extURL});
return;
}
}
//fallback to making a new tabist tab
chrome.tabs.create({
"url": extURL
//,"pinned": true // TODO: add pinned option
});
return;
})
});
}
chrome.browserAction.onClicked.addListener(openMyPage);
| Convert from a promises based callback scheme to a nested callback based scheme to support chrome. | Convert from a promises based callback scheme to a nested callback based scheme to support chrome.
| JavaScript | mit | fiveNinePlusR/tabist,fiveNinePlusR/tabist,fiveNinePlusR/tabist | ---
+++
@@ -1,34 +1,32 @@
var extURL = chrome.extension.getURL("tabs.html");
function openMyPage() {
- browser.windows.getCurrent({}).then(function(window) {
- return browser.tabs.query({windowId: window.id});
- }).then(function(tabs) {
- //check for a tabist tab first
- for(let tab of tabs) {
- if(tab.title == "Tabist"){
- //open that tab
- chrome.tabs.update(tab.id, {active: true});
- return;
+ chrome.windows.getCurrent({}, function(window) {
+ chrome.tabs.query({windowId: window.id}, function(tabs) {
+ //check for a tabist tab first
+ for(let tab of tabs) {
+ if(tab.title == "Tabist"){
+ //open that tab
+ chrome.tabs.update(tab.id, {active: true});
+ return;
+ }
}
- }
- //loop through again to see if there is an active new tab to replace
- for(let tab of tabs) {
- if(tab.title == "New Tab" && tab.active){
- chrome.tabs.update(tab.id, {"url": extURL});
- return;
+ //loop through again to see if there is an active new tab to replace
+ for(let tab of tabs) {
+ if(tab.title == "New Tab" && tab.active){
+ chrome.tabs.update(tab.id, {"url": extURL});
+ return;
+ }
}
- }
- //fallback to making a new tabist tab
- chrome.tabs.create({
- "url": extURL
- //,"pinned": true // TODO: add pinned option
- });
- return;
- }).catch(e => {
- console.log(e.message);
+ //fallback to making a new tabist tab
+ chrome.tabs.create({
+ "url": extURL
+ //,"pinned": true // TODO: add pinned option
+ });
+ return;
+ })
});
}
|
b683a0d862159b376f4f2ee69bb8e9367c21bdb7 | src/components/Drawing.js | src/components/Drawing.js | import React, { Component } from 'react';
import * as d3 from 'd3';
class Drawing extends React.Component {
constructor(props) {
super(props);
this.state = {
drawing: null,
};
}
componentDidMount() {
this.setState({
drawing: document.getElementById('drawing');
});
}
render() {
return (
<div id="drawing"></div>
)
}
}
export default Drawing; | import React, { Component } from 'react';
import * as d3 from 'd3';
class Drawing extends React.Component {
constructor(props) {
super(props);
this.handleMouseDown = this.handleMouseDown(this);
this.handleMouseUp = this.handleMouseUp(this);
this.handleMouseMove = this.handleMouseMove(this);
this.state = {
drawing: null,
line: null
};
}
componentDidMount() {
const drawing = d3.select('#drawing')
.append('svg')
.attr('width', 500)
.attr('height', 500)
.on('mousedown', this.handleMouseDown)
.on('mouseup', this.handleMouseUp);
this.setState({ drawing });
}
handleMouseDown(component) {
return function () {
const d = component.state.drawing;
const m = d3.mouse(this);
const line = d.append('line')
.attr('x1', m[0])
.attr('y1', m[1])
.attr('x2', m[0])
.attr('y2', m[1])
.attr('stroke-width', 2)
.attr('stroke', 'black');
component.setState({ line });
d.on('mousemove', component.handleMouseMove);
};
}
handleMouseUp(component) {
return function () {
component.state.drawing
.on('mousemove', null);
};
}
handleMouseMove(component) {
return function () {
const m = d3.mouse(this);
component.state.line
.attr('x2', m[0])
.attr('y2', m[1]);
};
}
render() {
return (
<div id="drawing" style={{ height: '500px', width: '500px' }} />
);
}
}
export default Drawing;
| Add initial implementation of lines | Add initial implementation of lines
| JavaScript | mit | rjbernaldo/lines,rjbernaldo/lines | ---
+++
@@ -5,21 +5,67 @@
constructor(props) {
super(props);
+ this.handleMouseDown = this.handleMouseDown(this);
+ this.handleMouseUp = this.handleMouseUp(this);
+ this.handleMouseMove = this.handleMouseMove(this);
+
this.state = {
drawing: null,
+ line: null
};
}
componentDidMount() {
- this.setState({
- drawing: document.getElementById('drawing');
- });
+ const drawing = d3.select('#drawing')
+ .append('svg')
+ .attr('width', 500)
+ .attr('height', 500)
+ .on('mousedown', this.handleMouseDown)
+ .on('mouseup', this.handleMouseUp);
+
+ this.setState({ drawing });
+ }
+
+ handleMouseDown(component) {
+ return function () {
+ const d = component.state.drawing;
+ const m = d3.mouse(this);
+
+ const line = d.append('line')
+ .attr('x1', m[0])
+ .attr('y1', m[1])
+ .attr('x2', m[0])
+ .attr('y2', m[1])
+ .attr('stroke-width', 2)
+ .attr('stroke', 'black');
+
+ component.setState({ line });
+
+ d.on('mousemove', component.handleMouseMove);
+ };
+ }
+
+ handleMouseUp(component) {
+ return function () {
+ component.state.drawing
+ .on('mousemove', null);
+ };
+ }
+
+ handleMouseMove(component) {
+ return function () {
+ const m = d3.mouse(this);
+
+ component.state.line
+ .attr('x2', m[0])
+ .attr('y2', m[1]);
+ };
}
render() {
return (
- <div id="drawing"></div>
- )
+ <div id="drawing" style={{ height: '500px', width: '500px' }} />
+ );
}
}
|
fe2157c7e91df36145826e033633bf67df2d4d79 | webpack/dev.server.js | webpack/dev.server.js | process.traceDeprecation = true;
const path = require('path');
const webpack = require('webpack');
const WebpackCommon = require('./webpack.common');
const BundleTracker = require('webpack-bundle-tracker');
var publicPath = 'http://kpi.kobo.local:3000/static/compiled/';
module.exports = WebpackCommon({
mode: "development",
entry: {
app: ['react-hot-loader/patch', './jsapp/js/main.es6'],
tests: path.resolve(__dirname, '../test/index.js')
},
output: {
library: 'KPI',
path: path.resolve(__dirname, '../jsapp/compiled/'),
publicPath: publicPath,
filename: "[name]-[hash].js"
},
devServer: {
publicPath: publicPath,
disableHostCheck: true,
hot: true,
headers: {'Access-Control-Allow-Origin': '*'},
port: 3000,
host: '0.0.0.0'
},
plugins: [
new BundleTracker({path: __dirname, filename: '../webpack-stats.json'}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
]
});
| process.traceDeprecation = true;
const path = require('path');
const webpack = require('webpack');
const WebpackCommon = require('./webpack.common');
const BundleTracker = require('webpack-bundle-tracker');
var isPublicDomainDefined = process.env.KOBOFORM_PUBLIC_SUBDOMAIN &&
process.env.PUBLIC_DOMAIN_NAME;
var publicDomain = isPublicDomainDefined ? process.env.KOBOFORM_PUBLIC_SUBDOMAIN
+ '.' + process.env.PUBLIC_DOMAIN_NAME : 'localhost';
var publicPath = 'http://' + publicDomain + ':3000/static/compiled/';
module.exports = WebpackCommon({
mode: "development",
entry: {
app: ['react-hot-loader/patch', './jsapp/js/main.es6'],
tests: path.resolve(__dirname, '../test/index.js')
},
output: {
library: 'KPI',
path: path.resolve(__dirname, '../jsapp/compiled/'),
publicPath: publicPath,
filename: "[name]-[hash].js"
},
devServer: {
publicPath: publicPath,
disableHostCheck: true,
hot: true,
headers: {'Access-Control-Allow-Origin': '*'},
port: 3000,
host: '0.0.0.0'
},
plugins: [
new BundleTracker({path: __dirname, filename: '../webpack-stats.json'}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
]
});
| Use domain name instead of localhost when it's available to make webpack works with local domain names | Use domain name instead of localhost when it's available to make webpack works with local domain names
| JavaScript | agpl-3.0 | onaio/kpi,onaio/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,onaio/kpi,onaio/kpi,kobotoolbox/kpi | ---
+++
@@ -3,7 +3,11 @@
const webpack = require('webpack');
const WebpackCommon = require('./webpack.common');
const BundleTracker = require('webpack-bundle-tracker');
-var publicPath = 'http://kpi.kobo.local:3000/static/compiled/';
+var isPublicDomainDefined = process.env.KOBOFORM_PUBLIC_SUBDOMAIN &&
+ process.env.PUBLIC_DOMAIN_NAME;
+var publicDomain = isPublicDomainDefined ? process.env.KOBOFORM_PUBLIC_SUBDOMAIN
+ + '.' + process.env.PUBLIC_DOMAIN_NAME : 'localhost';
+var publicPath = 'http://' + publicDomain + ':3000/static/compiled/';
module.exports = WebpackCommon({
mode: "development", |
6d2bfaa51b816843ff038f5502b495328c92e129 | app/components/Separator/styles.js | app/components/Separator/styles.js | import { Platform, StyleSheet } from 'react-native';
import { colors } from '../../styles';
const styles = StyleSheet.create({
root: {
height: 1,
backgroundColor: colors.grey,
opacity: 0.5,
},
shadow: {
backgroundColor: colors.greyOpacity,
...Platform.select({
ios: {
shadowOpacity: 0.9,
shadowRadius: 4,
shadowOffset: {
height: 0,
width: 0,
},
},
android: {
elevation: 0.3,
},
}),
},
opacity: {
opacity: 0.3,
},
});
export default styles;
| import { Platform, StyleSheet } from 'react-native';
import { colors } from '../../styles';
const styles = StyleSheet.create({
root: {
height: 1,
backgroundColor: colors.grey,
opacity: 0.5,
},
shadow: {
backgroundColor: colors.greyOpacity,
...Platform.select({
ios: {
shadowOpacity: 0.9,
shadowRadius: 1,
shadowOffset: {
height: 0.5,
width: 0,
},
},
android: {
elevation: 0.3,
},
}),
},
opacity: {
opacity: 0.3,
},
});
export default styles;
| Change separator with shadow view on ios | Change separator with shadow view on ios
| JavaScript | apache-2.0 | JSSolutions/Perfi | ---
+++
@@ -12,9 +12,9 @@
...Platform.select({
ios: {
shadowOpacity: 0.9,
- shadowRadius: 4,
+ shadowRadius: 1,
shadowOffset: {
- height: 0,
+ height: 0.5,
width: 0,
},
}, |
cb4e0e3a06046d3550a449a6a5716251dc4a60ec | fetch.js | fetch.js | const fs = require('fs');
const path = require('path');
const exec = require('child_process').exec;
const nodepath = process.env._;
const version = process.versions.v8;
const tmpfile = path.join(__dirname, version+'.flags.json');
if (!fs.existsSync(tmpfile)) {
exec(nodepath+' --v8-options', function (execErr, result) {
var flags;
if (execErr) {
throw new Error(execErr);
} else {
flags = result.match(/\s\s--(\w+)/gm).map(function (match) {
return match.substring(2);
});
fs.writeFile(tmpfile, JSON.stringify(flags), { encoding:'utf8' },
function (writeErr) {
if (writeErr) {
throw new Error(writeErr);
} else {
console.log('flags for v8 '+version+' cached.');
}
}
);
}
});
}
module.exports = require.bind(null, tmpfile);
| const fs = require('fs');
const path = require('path');
const exec = require('child_process').exec;
// this is from the env of npm, not node
const nodePath = process.env.NODE;
const version = process.versions.v8;
const tmpfile = path.join(__dirname, version+'.flags.json');
if (!fs.existsSync(tmpfile)) {
exec(nodePath+' --v8-options', function (execErr, result) {
var flags;
if (execErr) {
throw new Error(execErr);
} else {
flags = result.match(/\s\s--(\w+)/gm).map(function (match) {
return match.substring(2);
});
fs.writeFile(tmpfile, JSON.stringify(flags), { encoding:'utf8' },
function (writeErr) {
if (writeErr) {
throw new Error(writeErr);
} else {
console.log('flags for v8 '+version+' cached.');
}
}
);
}
});
}
module.exports = require.bind(null, tmpfile);
| Use process.env.NODE to find node executable | Fix: Use process.env.NODE to find node executable
| JavaScript | mit | js-cli/js-v8flags,tkellen/js-v8flags | ---
+++
@@ -2,12 +2,13 @@
const path = require('path');
const exec = require('child_process').exec;
-const nodepath = process.env._;
+// this is from the env of npm, not node
+const nodePath = process.env.NODE;
const version = process.versions.v8;
const tmpfile = path.join(__dirname, version+'.flags.json');
if (!fs.existsSync(tmpfile)) {
- exec(nodepath+' --v8-options', function (execErr, result) {
+ exec(nodePath+' --v8-options', function (execErr, result) {
var flags;
if (execErr) {
throw new Error(execErr); |
9430f00ad994b192322b2f7ad3063fdaa7af72e6 | templates/manager.js | templates/manager.js | module.exports = function(multiLang){
const MoviePoster = require('./movie-poster')(multiLang);
function selectTemplate(templateName) {
let template = null;
switch (templateName) {
case 'MoviePoster':
template = new MoviePoster();
break;
}
return template;
}
return {
selectTemplate
};
}
| const MoviePoster = require('./movie-poster');
function selectTemplate(templateName, userLang) {
let template = null;
switch (templateName) {
case 'MoviePoster':
template = new MoviePoster(userLang);
break;
}
return template;
}
module.exports.selectTemplate = selectTemplate;
| Send language to templates class on constructor | Send language to templates class on constructor
| JavaScript | mit | newvertex/FreeNightTelegramBot | ---
+++
@@ -1,20 +1,15 @@
-module.exports = function(multiLang){
+const MoviePoster = require('./movie-poster');
- const MoviePoster = require('./movie-poster')(multiLang);
+function selectTemplate(templateName, userLang) {
+ let template = null;
- function selectTemplate(templateName) {
- let template = null;
-
- switch (templateName) {
- case 'MoviePoster':
- template = new MoviePoster();
- break;
- }
-
- return template;
+ switch (templateName) {
+ case 'MoviePoster':
+ template = new MoviePoster(userLang);
+ break;
}
- return {
- selectTemplate
- };
+ return template;
}
+
+module.exports.selectTemplate = selectTemplate; |
cb924f6ae065f5b1aea16710b5b588ca8370b1ec | index.js | index.js | var PassThrough = require('stream').PassThrough
var inherits = require('util').inherits
function SeriesStream () {
PassThrough.apply(this, arguments)
this._current = null
this._queue = []
}
inherits(SeriesStream, PassThrough)
SeriesStream.prototype.on = function (ev, fn) {
var res = PassThrough.prototype.on.call(this, ev, fn)
if (ev === 'data' && !this._current) {
this._next()
}
return res
}
SeriesStream.prototype.pipe = function (dest) {
PassThrough.prototype.pipe.call(this, dest)
if (!this._current) {
this._next()
}
}
SeriesStream.prototype.add = function (src) {
this._queue.push(src)
}
SeriesStream.prototype._next = function () {
this._current = null
if (!this._queue.length) return
var next = this._queue.shift()
this._current = next
next.once('end', this._next.bind(this))
next.pipe(this)
}
SeriesStream.prototype.end = function () {
if (this._current) return // Only end when all streams have ended
PassThrough.prototype.end.apply(this, arguments)
}
module.exports = function (opts) {
return new SeriesStream(opts)
}
module.exports.SeriesStream = SeriesStream
| var PassThrough = require('stream').PassThrough
var inherits = require('util').inherits
function SeriesStream () {
PassThrough.apply(this, arguments)
this._current = null
this._queue = []
}
inherits(SeriesStream, PassThrough)
SeriesStream.prototype.on = function (ev, fn) {
var res = PassThrough.prototype.on.call(this, ev, fn)
if (ev === 'data' && !this._current) {
this._next()
}
return res
}
SeriesStream.prototype.pipe = function (dest) {
PassThrough.prototype.pipe.call(this, dest)
if (!this._current) {
this._next()
}
return dest
}
SeriesStream.prototype.add = function (src) {
this._queue.push(src)
return this
}
SeriesStream.prototype._next = function () {
this._current = null
if (!this._queue.length) return
var next = this._queue.shift()
this._current = next
next.once('end', this._next.bind(this))
next.pipe(this)
}
SeriesStream.prototype.end = function () {
if (this._current) return // Only end when all streams have ended
return PassThrough.prototype.end.apply(this, arguments)
}
module.exports = function (opts) {
return new SeriesStream(opts)
}
module.exports.SeriesStream = SeriesStream
| Fix return dest stream from pipe | Fix return dest stream from pipe
| JavaScript | isc | alanshaw/series-stream | ---
+++
@@ -20,13 +20,17 @@
SeriesStream.prototype.pipe = function (dest) {
PassThrough.prototype.pipe.call(this, dest)
+
if (!this._current) {
this._next()
}
+
+ return dest
}
SeriesStream.prototype.add = function (src) {
this._queue.push(src)
+ return this
}
SeriesStream.prototype._next = function () {
@@ -40,7 +44,7 @@
SeriesStream.prototype.end = function () {
if (this._current) return // Only end when all streams have ended
- PassThrough.prototype.end.apply(this, arguments)
+ return PassThrough.prototype.end.apply(this, arguments)
}
module.exports = function (opts) { |
01eee15a0a1306121a33152d4df8e1c94840cbf0 | src/commands/Command.js | src/commands/Command.js | const Commando = require('discord.js-commando')
module.exports =
class Command extends Commando.Command {
constructor(client, info) {
info.group = 'rover';
info.guildOnly = true;
info.memberName = info.name;
super(client, info);
this.userPermissions = info.userPermissions || ['ADMINISTRATOR'];
this.discordBot = this.client.discordBot;
}
hasPermission(msg) {
return msg.member.hasPermission(this.userPermissions);
}
async run(msg, args, pattern) {
this.server = await this.discordBot.getServer(msg.guild.id);
return await this.fn(msg, args, pattern);
}
} | const Commando = require('discord.js-commando')
module.exports =
class Command extends Commando.Command {
constructor(client, info) {
info.group = 'rover';
info.guildOnly = true;
info.memberName = info.name;
super(client, info);
this.userPermissions = info.userPermissions || ['MANAGE_GUILD'];
this.discordBot = this.client.discordBot;
}
hasPermission(msg) {
return msg.member.hasPermission(this.userPermissions);
}
async run(msg, args, pattern) {
this.server = await this.discordBot.getServer(msg.guild.id);
return await this.fn(msg, args, pattern);
}
} | Change requirement to MANAGE SERVER | Change requirement to MANAGE SERVER
| JavaScript | apache-2.0 | evaera/RoVer | ---
+++
@@ -9,7 +9,7 @@
super(client, info);
- this.userPermissions = info.userPermissions || ['ADMINISTRATOR'];
+ this.userPermissions = info.userPermissions || ['MANAGE_GUILD'];
this.discordBot = this.client.discordBot;
}
|
09b5001145ca91dad561d360404f2bb48c274890 | index.js | index.js | var opener = require('opener');
var http = require('http');
var fs = require('fs');
var url = require('url');
var exec = require('child_process').execSync;
var registry = exec('npm config get registry').toString().trim()
opener(registry + 'oauth/authorize');
fs.readFile('./index.html', function(err, html) {
if (err) {
throw err;
}
http.createServer(function(req, res) {
var query = url.parse(req.url, true).query;
var token = decodeURIComponent(query.token);
var u = url.parse(registry);
var keyBase = '//' + u.host + u.path + ':'
exec('npm config set ' + keyBase + '_authToken "' + token + '"');
exec('npm config set ' + keyBase + 'always-auth true');
res.writeHeader(200, {"Content-Type": "text/html"});
res.end(html, function() {
process.exit(0);
});
}).listen(8239);
})
| var opener = require('opener');
var http = require('http');
var fs = require('fs');
var url = require('url');
var exec = require('child_process').execSync;
var registry = exec('npm config get registry').toString().trim()
if (registry.indexOf('registry.npmjs.org') > -1) {
console.log('It seems you are using the default npm repository.');
console.log('Please update it to your sinopia url by running:');
console.log('');
console.log('npm config set registry <url>');
process.exit(0);
}
opener(registry + 'oauth/authorize');
fs.readFile('./index.html', function(err, html) {
if (err) {
throw err;
}
http.createServer(function(req, res) {
var query = url.parse(req.url, true).query;
var token = decodeURIComponent(query.token);
var u = url.parse(registry);
var keyBase = '//' + u.host + u.path + ':'
exec('npm config set ' + keyBase + '_authToken "' + token + '"');
exec('npm config set ' + keyBase + 'always-auth true');
res.writeHeader(200, {"Content-Type": "text/html"});
res.end(html, function() {
process.exit(0);
});
}).listen(8239);
})
| Exit when using the default npm registry | Exit when using the default npm registry
| JavaScript | mit | soundtrackyourbrand/sinopia-github-oauth-cli,soundtrackyourbrand/sinopia-github-oauth-cli | ---
+++
@@ -5,6 +5,14 @@
var exec = require('child_process').execSync;
var registry = exec('npm config get registry').toString().trim()
+
+if (registry.indexOf('registry.npmjs.org') > -1) {
+ console.log('It seems you are using the default npm repository.');
+ console.log('Please update it to your sinopia url by running:');
+ console.log('');
+ console.log('npm config set registry <url>');
+ process.exit(0);
+}
opener(registry + 'oauth/authorize');
|
5afbebd6633ba70b3ebdef3ce0adec6676a9b40f | client.js | client.js | module.exports = {
init: function() {
var client = this
function isClient(name) {
var agent = window.navigator.userAgent,
index = agent.indexOf(name)
if (index < 0) { return false }
client.version = parseInt(agent.substr(index + name.length + 1))
client.name = name
return true
}
client.isIE = isClient('MSIE')
client.isFirefox = isClient('Firefox')
client.isWebkit = client.isWebKit = isClient('WebKit')
client.isChrome = isClient('Chrome')
client.isSafari = !client.isChrome && isClient('Safari')
},
isQuirksMode: function(doc) {
// in IE, if compatMode is undefined (early ie) or explicitly set to BackCompat, we're in quirks
return this.isIE && (!doc.compatMode || doc.compatMode == 'BackCompat')
}
}
module.exports.init()
| module.exports = {
init: function() {
var client = this
function isClient(name) {
var agent = window.navigator.userAgent,
index = agent.indexOf(name)
if (index < 0) { return false }
client.version = parseInt(agent.substr(index + name.length + 1))
client.name = name
return true
}
client.isIE = isClient('MSIE')
client.isFirefox = isClient('Firefox')
client.isWebkit = client.isWebKit = isClient('WebKit')
client.isChrome = isClient('Chrome')
client.isSafari = !client.isChrome && isClient('Safari')
client.isIPhone = isClient('iPhone')
client.isIPad = isClient('iPad')
client.isIPod = isClient('iPod')
},
isQuirksMode: function(doc) {
// in IE, if compatMode is undefined (early ie) or explicitly set to BackCompat, we're in quirks
return this.isIE && (!doc.compatMode || doc.compatMode == 'BackCompat')
}
}
module.exports.init()
| Check for iPhone, iPad and iPod | Check for iPhone, iPad and iPod
| JavaScript | mit | marcuswestin/std.js,ASAPPinc/std.js | ---
+++
@@ -14,6 +14,9 @@
client.isWebkit = client.isWebKit = isClient('WebKit')
client.isChrome = isClient('Chrome')
client.isSafari = !client.isChrome && isClient('Safari')
+ client.isIPhone = isClient('iPhone')
+ client.isIPad = isClient('iPad')
+ client.isIPod = isClient('iPod')
},
isQuirksMode: function(doc) { |
fd980be3a4251e66157be907123e93c09e173dfe | index.js | index.js | var bridge = require('vigour-native/lib/bridge')
var env = require('vigour-native/lib/env')
// var name = 'plugin'
var id = 'vigour-native-plugin'
var supportedPlatforms = [
'android',
'ios'
]
var supportedDevices = [
'phone',
'tablet'
]
module.exports = exports = {}
exports.usable = ~supportedDevices.indexOf(env.ua.device) &&
~supportedPlatforms.indexOf(env.ua.platform)
exports.act = function (opts, cb) {
// var error
if (!cb) {
cb = opts
opts = null
}
bridge.call(id, 'act', opts, cb)
}
| var bridge = require('vigour-native/lib/bridge')
var pkg = require('./package.json')
var pluginId = pkg.vigour.plugin.id
module.exports = exports = {}
exports.bridgeCall = function (fn, opts, cb) {
if (!cb) {
cb = opts
opts = null
}
bridge.call(pluginId, fn, opts, cb)
}
// TODO Everything above this line feels like boilerplate
// and should probably be moved to lib/bridge somehow
// If plugin requires initialization on the native side
exports.bridgeCall('init', function (err) {
if (!err) {
// Native part is ready
exports.init()
} else {
throw err
}
})
exports.init = function () {
// Do something
}
exports.act = function (opts, cb) {
exports.bridgeCall('act', opts, cb)
}
| Call native initialization from js | Call native initialization from js
| JavaScript | bsd-2-clause | vigour-io/statusbar,vigour-io/statusbar | ---
+++
@@ -1,26 +1,34 @@
var bridge = require('vigour-native/lib/bridge')
-var env = require('vigour-native/lib/env')
-// var name = 'plugin'
-var id = 'vigour-native-plugin'
-var supportedPlatforms = [
- 'android',
- 'ios'
-]
-var supportedDevices = [
- 'phone',
- 'tablet'
-]
+var pkg = require('./package.json')
+var pluginId = pkg.vigour.plugin.id
module.exports = exports = {}
-exports.usable = ~supportedDevices.indexOf(env.ua.device) &&
- ~supportedPlatforms.indexOf(env.ua.platform)
-
-exports.act = function (opts, cb) {
- // var error
+exports.bridgeCall = function (fn, opts, cb) {
if (!cb) {
cb = opts
opts = null
}
- bridge.call(id, 'act', opts, cb)
+ bridge.call(pluginId, fn, opts, cb)
}
+
+// TODO Everything above this line feels like boilerplate
+// and should probably be moved to lib/bridge somehow
+
+// If plugin requires initialization on the native side
+exports.bridgeCall('init', function (err) {
+ if (!err) {
+ // Native part is ready
+ exports.init()
+ } else {
+ throw err
+ }
+})
+
+exports.init = function () {
+ // Do something
+}
+
+exports.act = function (opts, cb) {
+ exports.bridgeCall('act', opts, cb)
+} |
bba1a9b1743826cac147cd6f7d84b9731acf9ddc | index.js | index.js | 'use strict'
var commentMarker = require('mdast-comment-marker')
module.exports = commentconfig
// Modify `processor` to read configuration from comments.
function commentconfig() {
var proto = this.Parser && this.Parser.prototype
var Compiler = this.Compiler
var block = proto && proto.blockTokenizers
var inline = proto && proto.inlineTokenizers
var compiler = Compiler && Compiler.prototype && Compiler.prototype.visitors
if (block && block.html) {
block.html = factory(block.html)
}
if (inline && inline.html) {
inline.html = factory(inline.html)
}
if (compiler && compiler.html) {
compiler.html = factory(compiler.html)
}
}
// Wrapper factory.
function factory(original) {
replacement.locator = original.locator
return replacement
// Replacer for tokeniser or visitor.
function replacement(node) {
var self = this
var result = original.apply(self, arguments)
var marker = commentMarker(result && result.type ? result : node)
if (marker && marker.name === 'remark') {
try {
self.setOptions(marker.parameters)
} catch (error) {
self.file.fail(error.message, marker.node)
}
}
return result
}
}
| 'use strict'
var commentMarker = require('mdast-comment-marker')
module.exports = commentconfig
var origin = 'remark-comment-config:invalid-options'
// Modify `processor` to read configuration from comments.
function commentconfig() {
var proto = this.Parser && this.Parser.prototype
var Compiler = this.Compiler
var block = proto && proto.blockTokenizers
var inline = proto && proto.inlineTokenizers
var compiler = Compiler && Compiler.prototype && Compiler.prototype.visitors
if (block && block.html) {
block.html = factory(block.html)
}
if (inline && inline.html) {
inline.html = factory(inline.html)
}
if (compiler && compiler.html) {
compiler.html = factory(compiler.html)
}
}
// Wrapper factory.
function factory(original) {
replacement.locator = original.locator
return replacement
// Replacer for tokeniser or visitor.
function replacement(node) {
var self = this
var result = original.apply(self, arguments)
var marker = commentMarker(result && result.type ? result : node)
if (marker && marker.name === 'remark') {
try {
self.setOptions(marker.parameters)
} catch (error) {
self.file.fail(error.message, marker.node, origin)
}
}
return result
}
}
| Add origin to option setting failure | Add origin to option setting failure
| JavaScript | mit | wooorm/mdast-comment-config | ---
+++
@@ -3,6 +3,8 @@
var commentMarker = require('mdast-comment-marker')
module.exports = commentconfig
+
+var origin = 'remark-comment-config:invalid-options'
// Modify `processor` to read configuration from comments.
function commentconfig() {
@@ -41,7 +43,7 @@
try {
self.setOptions(marker.parameters)
} catch (error) {
- self.file.fail(error.message, marker.node)
+ self.file.fail(error.message, marker.node, origin)
}
}
|
efcf34f201a88b4f1226eb958d633207024ed422 | index.js | index.js | 'use strict'
const standard = require('standard')
const format = require('util').format
const assign = require('object-assign')
const loaderUtils = require('loader-utils')
module.exports = function standardLoader (text) {
const self = this
const callback = this.async()
const config = assign(
this.options.standard || {},
loaderUtils.parseQuery(this.query)
)
this.cacheable()
standard.lintText(text, config, function (err, result) {
if (err) return callback(err, text)
if (result.errorCount === 0) return callback(err, text)
const warnings = result.results.reduce(function (items, result) {
return items.concat(result.messages.map(function (message) {
return format(
'%s:%d:%d: %s',
result.filePath, message.line || 0, message.column || 0, message.message
)
}))
}, [])
self.emitWarning(warnings.join('\n'))
callback(err, text)
})
}
| 'use strict'
var standard = require('standard')
var format = require('util').format
var assign = require('object-assign')
var loaderUtils = require('loader-utils')
module.exports = function standardLoader (text) {
var self = this
var callback = this.async()
var config = assign(
this.options.standard || {},
loaderUtils.parseQuery(this.query)
)
this.cacheable()
standard.lintText(text, config, function (err, result) {
if (err) return callback(err, text)
if (result.errorCount === 0) return callback(err, text)
var warnings = result.results.reduce(function (items, result) {
return items.concat(result.messages.map(function (message) {
return format(
'%s:%d:%d: %s',
result.filePath, message.line || 0, message.column || 0, message.message
)
}))
}, [])
self.emitWarning(warnings.join('\n'))
callback(err, text)
})
}
| Remove const in strict-mode for 0.10.x. | Remove const in strict-mode for 0.10.x.
| JavaScript | isc | timoxley/standard-loader | ---
+++
@@ -1,15 +1,15 @@
'use strict'
-const standard = require('standard')
-const format = require('util').format
-const assign = require('object-assign')
-const loaderUtils = require('loader-utils')
+var standard = require('standard')
+var format = require('util').format
+var assign = require('object-assign')
+var loaderUtils = require('loader-utils')
module.exports = function standardLoader (text) {
- const self = this
- const callback = this.async()
+ var self = this
+ var callback = this.async()
- const config = assign(
+ var config = assign(
this.options.standard || {},
loaderUtils.parseQuery(this.query)
)
@@ -20,7 +20,7 @@
if (err) return callback(err, text)
if (result.errorCount === 0) return callback(err, text)
- const warnings = result.results.reduce(function (items, result) {
+ var warnings = result.results.reduce(function (items, result) {
return items.concat(result.messages.map(function (message) {
return format(
'%s:%d:%d: %s', |
ab2e545f788854393547b9cf955e2c6ddaf8ddd9 | index.js | index.js | var through2 = require('through2');
var File = require('vinyl');
var path = require('path');
module.exports = function (filename, baseDir) {
var ins = through2()
var out = false
var opts = {
contents: ins
};
if (filename) {
opts.path = path.resolve(baseDir || __dirname, filename);
}
if (baseDir) {
opts.base = baseDir;
}
console.log(opts);
var file = new File(opts);
return through2({
objectMode: true
}, function(chunk, enc, next) {
if (!out) {
this.push(file)
out = true
}
ins.push(chunk)
next()
}, function() {
ins.push(null)
this.push(null)
})
}
| var through2 = require('through2')
var File = require('vinyl')
var path = require('path')
module.exports = function (filename, baseDir) {
var ins = through2()
var out = false
var opts = {
contents: ins
};
if (filename) {
opts.path = path.resolve(baseDir || __dirname, filename)
}
if (baseDir) {
opts.base = baseDir
}
var file = new File(opts)
return through2({
objectMode: true
}, function(chunk, enc, next) {
if (!out) {
this.push(file)
out = true
}
ins.push(chunk)
next()
}, function() {
ins.push(null)
this.push(null)
})
}
| Fix indention - Remove console.log() | Fix indention - Remove console.log() | JavaScript | mit | hughsk/vinyl-source-stream | ---
+++
@@ -1,35 +1,34 @@
-var through2 = require('through2');
-var File = require('vinyl');
-var path = require('path');
+var through2 = require('through2')
+var File = require('vinyl')
+var path = require('path')
module.exports = function (filename, baseDir) {
- var ins = through2()
- var out = false
+ var ins = through2()
+ var out = false
- var opts = {
- contents: ins
- };
- if (filename) {
- opts.path = path.resolve(baseDir || __dirname, filename);
+ var opts = {
+ contents: ins
+ };
+ if (filename) {
+ opts.path = path.resolve(baseDir || __dirname, filename)
+ }
+ if (baseDir) {
+ opts.base = baseDir
+ }
+ var file = new File(opts)
+
+ return through2({
+ objectMode: true
+ }, function(chunk, enc, next) {
+ if (!out) {
+ this.push(file)
+ out = true
}
- if (baseDir) {
- opts.base = baseDir;
- }
- console.log(opts);
- var file = new File(opts);
- return through2({
- objectMode: true
- }, function(chunk, enc, next) {
- if (!out) {
- this.push(file)
- out = true
- }
-
- ins.push(chunk)
- next()
- }, function() {
- ins.push(null)
- this.push(null)
- })
+ ins.push(chunk)
+ next()
+ }, function() {
+ ins.push(null)
+ this.push(null)
+ })
} |
2c3fd0151118a3ab537b6318b2c9aeb839b78c31 | index.js | index.js | var conf = require("./server/conf"),
app = require("./server/app"),
log = conf.log;
app.listen(conf.PORT, function() {
log.info("Server_listening on port %s", conf.PORT);
}); | var conf = require("./server/conf"),
app = require("./server/app"),
log = conf.log;
app.listen(conf.PORT, function() {
log.info("Server_listening on port %s", conf.PORT)
}); | Deploy shouldn't work if other tasks fail | Deploy shouldn't work if other tasks fail
| JavaScript | mit | r3Fuze/base | ---
+++
@@ -5,5 +5,5 @@
app.listen(conf.PORT, function() {
- log.info("Server_listening on port %s", conf.PORT);
+ log.info("Server_listening on port %s", conf.PORT)
}); |
f1e1fa27c073ea9f452abb80b882c2e88f5fbeab | index.js | index.js | var debug = require( 'debug' )( 'wpcom-vip' );
var request = require( './lib/util/request' );
// Modules
function WPCOM_VIP( token ) {
this.req = new Request( this );
this.auth = {};
}
WPCOM_VIP.prototype.API_VERSION = '1';
WPCOM_VIP.prototype.API_TIMEOUT = 10000;
WPCOM_VIP.prototype.get = function() {
return this.req.get.apply( arguments );
};
WPCOM_VIP.prototype.post = function() {
return this.req.post.apply( arguments );
};
WPCOM_VIP.prototype.put = function() {
return this.req.get.apply( arguments );
};
WPCOM_VIP.prototype.delete = function() {
return this.req.delete.apply( arguments );
};
module.exports = WPCOM_VIP;
| var debug = require( 'debug' )( 'wpcom-vip' );
var Request = require( './lib/util/request' );
// Modules
function WPCOM_VIP( token ) {
this.req = new Request( this );
this.auth = {};
}
WPCOM_VIP.prototype.API_VERSION = '1';
WPCOM_VIP.prototype.API_TIMEOUT = 10000;
WPCOM_VIP.prototype.get = function() {
return this.req.get.apply( arguments );
};
WPCOM_VIP.prototype.post = function() {
return this.req.post.apply( arguments );
};
WPCOM_VIP.prototype.put = function() {
return this.req.get.apply( arguments );
};
WPCOM_VIP.prototype.delete = function() {
return this.req.delete.apply( arguments );
};
module.exports = WPCOM_VIP;
| Fix capitalization of included Request module | Fix capitalization of included Request module
| JavaScript | mit | Automattic/vip-js-sdk | ---
+++
@@ -1,5 +1,5 @@
var debug = require( 'debug' )( 'wpcom-vip' );
-var request = require( './lib/util/request' );
+var Request = require( './lib/util/request' );
// Modules
|
98a885bed6d1fde11599d7f44d955339160b0f2c | index.js | index.js | #!/usr/bin/env node
'use strict';
console.log('Hello World!'); | #!/usr/bin/env node
'use strict';
const program = require('commander');
program
.option('-v, --version', 'Software Version')
.option('-u, --uptime', 'Total Uptime')
.option('-g, --gip', 'Gateway IP')
.option('-i, --ip', 'IP Address')
.option('-d, --dns', 'DNS Servers')
.option('-a, --all', 'Display all stats')
.parse(process.argv);
// If no option passed, show help
if (!process.argv.slice(2).length) {
program.help();
} | Add cli options using commander | Add cli options using commander
| JavaScript | mit | joelgeorgev/google-wifi-status | ---
+++
@@ -2,4 +2,18 @@
'use strict';
-console.log('Hello World!');
+const program = require('commander');
+
+program
+ .option('-v, --version', 'Software Version')
+ .option('-u, --uptime', 'Total Uptime')
+ .option('-g, --gip', 'Gateway IP')
+ .option('-i, --ip', 'IP Address')
+ .option('-d, --dns', 'DNS Servers')
+ .option('-a, --all', 'Display all stats')
+ .parse(process.argv);
+
+// If no option passed, show help
+if (!process.argv.slice(2).length) {
+ program.help();
+} |
d75d0c9e4c1c8a948d227cfdeb19925163e111b9 | index.js | index.js | exports.encode = exports.stringify = function (value) {
var values = [value];
var table = [];
for (var v = 0; v < values.length; ++v) {
value = values[v];
if (value && typeof value === "object") {
var copy = table[v] = Array.isArray(value) ? [] : {};
Object.keys(value).forEach(function (key) {
var child = value[key];
var index = values.indexOf(child);
if (index < 0) {
index = values.push(child) - 1;
}
copy[key] = index;
});
} else {
table[v] = value;
}
}
return JSON.stringify(table);
};
exports.decode = exports.parse = function (encoding) {
var table = JSON.parse(encoding);
table.forEach(function (entry) {
if (entry && typeof entry === "object") {
Object.keys(entry).forEach(function (key) {
entry[key] = table[entry[key]];
});
}
});
return table[0];
};
| function encode(value) {
return JSON.stringify(tabulate(value));
}
function tabulate(value) {
var values = [];
var table = [];
var indexMap = typeof Map === "function" && new Map;
function getIndex(value) {
var index;
if (indexMap) {
// If we have Map, use it instead of values.indexOf to accelerate
// object lookups.
index = indexMap.get(value);
if (typeof index === "undefined") {
index = values.push(value) - 1;
indexMap.set(value, index);
}
} else {
index = values.indexOf(value);
if (index < 0) {
index = values.push(value) - 1;
}
}
return index;
}
// Assign the root value to values[0].
getIndex(value);
for (var v = 0; v < values.length; ++v) {
value = values[v];
if (value && typeof value === "object") {
var copy = table[v] = Array.isArray(value) ? [] : {};
Object.keys(value).forEach(function (key) {
copy[key] = getIndex(value[key]);
});
} else {
table[v] = value;
}
}
return table;
}
function decode(encoding) {
var table = JSON.parse(encoding);
table.forEach(function (entry) {
if (entry && typeof entry === "object") {
Object.keys(entry).forEach(function (key) {
entry[key] = table[entry[key]];
});
}
});
return table[0];
}
exports.encode = exports.stringify = encode;
exports.decode = exports.parse = decode;
| Use a Map to accelerate seen object lookups. | Use a Map to accelerate seen object lookups.
| JavaScript | mit | benjamn/arson | ---
+++
@@ -1,28 +1,53 @@
-exports.encode = exports.stringify = function (value) {
- var values = [value];
+function encode(value) {
+ return JSON.stringify(tabulate(value));
+}
+
+function tabulate(value) {
+ var values = [];
var table = [];
+ var indexMap = typeof Map === "function" && new Map;
+
+ function getIndex(value) {
+ var index;
+
+ if (indexMap) {
+ // If we have Map, use it instead of values.indexOf to accelerate
+ // object lookups.
+ index = indexMap.get(value);
+ if (typeof index === "undefined") {
+ index = values.push(value) - 1;
+ indexMap.set(value, index);
+ }
+ } else {
+ index = values.indexOf(value);
+ if (index < 0) {
+ index = values.push(value) - 1;
+ }
+ }
+
+ return index;
+ }
+
+ // Assign the root value to values[0].
+ getIndex(value);
for (var v = 0; v < values.length; ++v) {
value = values[v];
+
if (value && typeof value === "object") {
var copy = table[v] = Array.isArray(value) ? [] : {};
Object.keys(value).forEach(function (key) {
- var child = value[key];
- var index = values.indexOf(child);
- if (index < 0) {
- index = values.push(child) - 1;
- }
- copy[key] = index;
+ copy[key] = getIndex(value[key]);
});
} else {
table[v] = value;
}
}
- return JSON.stringify(table);
-};
+ return table;
+}
-exports.decode = exports.parse = function (encoding) {
+function decode(encoding) {
var table = JSON.parse(encoding);
table.forEach(function (entry) {
@@ -34,4 +59,7 @@
});
return table[0];
-};
+}
+
+exports.encode = exports.stringify = encode;
+exports.decode = exports.parse = decode; |
920dbc6a1de0a8b0715a82d331f4dc9fe2b39611 | index.js | index.js | import {
AppRegistry,
StatusBar,
} from 'react-native';
import Finance from './Finance';
StatusBar.setBarStyle('light-content', true);
AppRegistry.registerComponent('Finance', () => Finance);
| import {
AppRegistry,
StatusBar,
} from 'react-native';
import Finance from './Finance';
console.disableYellowBox = true;
StatusBar.setBarStyle('light-content', true);
AppRegistry.registerComponent('Finance', () => Finance);
| Disable new yellow componentWillMount() lifecycle warnings | Disable new yellow componentWillMount() lifecycle warnings
| JavaScript | mit | 7kfpun/FinanceReactNative,7kfpun/FinanceReactNative,7kfpun/FinanceReactNative | ---
+++
@@ -5,6 +5,7 @@
import Finance from './Finance';
+console.disableYellowBox = true;
StatusBar.setBarStyle('light-content', true);
AppRegistry.registerComponent('Finance', () => Finance); |
a2891c09a90f3cc8682eee869eb2f0cf2bda5c2f | index.js | index.js | /* jshint node: true */
'use strict';
var imagemin = require('broccoli-imagemin');
module.exports = {
name: 'ember-cli-imagemin',
included: function(app) {
this.app = app;
var defaultOptions = {
enabled: this.app.env === 'production'
};
if (this.app.options.imagemin === false) {
this.options = this.app.options.imagemin = { enabled: false };
} else {
this.options = this.app.options.imagemin = this.app.options.imagemin || {};
}
for (var option in defaultOptions) {
if (!this.options.hasOwnProperty(option)) {
this.options[option] = defaultOptions[option];
}
}
},
postprocessTree: function(type, tree) {
if (this.options.enabled) {
tree = imagemin(tree, this.options);
}
return tree;
}
};
| /* jshint node: true */
'use strict';
var imagemin = require('broccoli-imagemin');
module.exports = {
name: 'ember-cli-imagemin',
included: function() {
this._super.included.apply(this, arguments);
// Default options
var defaultOptions = {
enabled: this.app.env === 'production'
};
// If the imagemin options key is set to `false` instead of
// an options object, disable the addon
if (this.app.options.imagemin === false) {
this.options = this.app.options.imagemin = { enabled: false };
} else {
this.options = this.app.options.imagemin = this.app.options.imagemin || {};
}
// Merge the default options with the passed in options
for (var option in defaultOptions) {
if (!this.options.hasOwnProperty(option)) {
this.options[option] = defaultOptions[option];
}
}
},
postprocessTree: function(type, tree) {
if (this.options.enabled) {
tree = imagemin(tree, this.options);
}
return tree;
}
};
| Add comments and call _super | Add comments and call _super
| JavaScript | mit | andybluntish/ember-cli-imagemin,andybluntish/ember-cli-imagemin | ---
+++
@@ -6,19 +6,23 @@
module.exports = {
name: 'ember-cli-imagemin',
- included: function(app) {
- this.app = app;
+ included: function() {
+ this._super.included.apply(this, arguments);
+ // Default options
var defaultOptions = {
enabled: this.app.env === 'production'
};
+ // If the imagemin options key is set to `false` instead of
+ // an options object, disable the addon
if (this.app.options.imagemin === false) {
this.options = this.app.options.imagemin = { enabled: false };
} else {
this.options = this.app.options.imagemin = this.app.options.imagemin || {};
}
+ // Merge the default options with the passed in options
for (var option in defaultOptions) {
if (!this.options.hasOwnProperty(option)) {
this.options[option] = defaultOptions[option]; |
682f05e5b372593a5cee89e651372ad01d3090df | index.js | index.js | var fs = require('fs');
var rest = require(__dirname + "/lib/rest");
var unzip = require("unzip2");
module.exports = {
hello: function() {
return "Hi!"
}
} | var fs = require('fs');
var rest = require(__dirname + "/lib/rest");
var unzip = require("unzip2");
//Globalish
var contract = {
cc: {
read: read,
write: write,
remove: remove,
deploy: deploy,
readNames: readNames,
details:{
host: "",
port: 80,
path: "",
url: "",
name: {},
func: [],
vars: []
}
}
};
module.exports = {
hello: function() {
return "Hi!";
},
network = function(arrayPeers){
if(arrayPeers.constructor !== Array){
console.log('[obc-js] Error - network arg should be array of peer objects');
}
else{
for(var i in arrayPeers){
var pos = arrayPeers[i].id.indexOf('_') + 1;
arrayPeers[i].name = arrayPeers[i].id.substring(pos) + '-' + arrayPeers[i].api_host + ':' + arrayPeers[i].api_port;
console.log(arrayPeers[i].name);
}
var ssl = true;
contract.cc.details.host = arrayPeers[0].api_host;
contract.cc.details.port = arrayPeers[0].api_port;
contract.cc.details.peers = arrayPeers;
if(arrayPeers[0].api_url.indexOf('https') == -1) ssl = false; //not https, no tls
rest.init({ //load default values for rest call to peer
host: contract.cc.details.host,
port: contract.cc.details.port,
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
},
ssl: ssl,
quiet: true
});
}
}
} | Bring in the first function. | Bring in the first function. | JavaScript | apache-2.0 | IBM-Blockchain/ibm-blockchain-js | ---
+++
@@ -2,8 +2,56 @@
var rest = require(__dirname + "/lib/rest");
var unzip = require("unzip2");
+//Globalish
+var contract = {
+ cc: {
+ read: read,
+ write: write,
+ remove: remove,
+ deploy: deploy,
+ readNames: readNames,
+ details:{
+ host: "",
+ port: 80,
+ path: "",
+ url: "",
+ name: {},
+ func: [],
+ vars: []
+ }
+ }
+ };
+
module.exports = {
hello: function() {
- return "Hi!"
- }
+ return "Hi!";
+ },
+ network = function(arrayPeers){
+ if(arrayPeers.constructor !== Array){
+ console.log('[obc-js] Error - network arg should be array of peer objects');
+ }
+ else{
+ for(var i in arrayPeers){
+ var pos = arrayPeers[i].id.indexOf('_') + 1;
+ arrayPeers[i].name = arrayPeers[i].id.substring(pos) + '-' + arrayPeers[i].api_host + ':' + arrayPeers[i].api_port;
+ console.log(arrayPeers[i].name);
+ }
+ var ssl = true;
+ contract.cc.details.host = arrayPeers[0].api_host;
+ contract.cc.details.port = arrayPeers[0].api_port;
+ contract.cc.details.peers = arrayPeers;
+ if(arrayPeers[0].api_url.indexOf('https') == -1) ssl = false; //not https, no tls
+
+ rest.init({ //load default values for rest call to peer
+ host: contract.cc.details.host,
+ port: contract.cc.details.port,
+ headers: {
+ "Content-Type": "application/json",
+ "Accept": "application/json",
+ },
+ ssl: ssl,
+ quiet: true
+ });
+ }
+ }
} |
dcf5407b30d695a25856961555d9fd67b10ca909 | index.js | index.js | const path = require('path');
const fs = require('fs');
function findFile(cwd, pattern, cb) {
fs.readdir(cwd, function(err, files){
if(err) {
console.log("Error in reading dir");
cb(err, null);
} else {
var regex = new RegExp('^' + pattern + "$");
cb(null, files.filter(file => regex.test(file)));
}
})
};
module.exports = findFile;
| const path = require('path');
const fs = require('fs');
function recursiveSearch(cwd, regex, depth) {
if ( depth-- > 0) {
var matchingFiles = [];
var files = fs.readdirSync(cwd)
files.forEach(file => {
var fsStat = fs.statSync(path.join(cwd, file));
if (fsStat.isFile() && regex.test(file)) {
matchingFiles.push({
dir: cwd,
file: file
})
} else if (fsStat.isDirectory()) {
matchingFiles = matchingFiles.concat(recursiveSearch(path.join(cwd, file), regex, depth));
}
})
return matchingFiles;
} else {
return [];
}
}
function findFile(cwd, pattern, recursive, depth, cb) {
if (recursive.constructor == Function) {
cb = recursive;
recursive = false;
depth = 100;
} else if (depth.constructor == Function) {
cb = depth;
depth = 100;
}
var regex = new RegExp('^' + pattern + "$");
if (recursive) {
cb(null, recursiveSearch(cwd, regex, depth));
} else {
fs.readdir(cwd, function(err, files) {
if (err) {
cb(err, null);
} else {
cb(null, files.filter(file => regex.test(file)));
}
})
}
}
module.exports = findFile;
| Support for recursion and depth | Support for recursion and depth
| JavaScript | mit | AkashBabu/file-regex | ---
+++
@@ -2,16 +2,53 @@
const fs = require('fs');
-function findFile(cwd, pattern, cb) {
- fs.readdir(cwd, function(err, files){
- if(err) {
- console.log("Error in reading dir");
- cb(err, null);
+function recursiveSearch(cwd, regex, depth) {
+ if ( depth-- > 0) {
+ var matchingFiles = [];
+ var files = fs.readdirSync(cwd)
+ files.forEach(file => {
+ var fsStat = fs.statSync(path.join(cwd, file));
+ if (fsStat.isFile() && regex.test(file)) {
+ matchingFiles.push({
+ dir: cwd,
+ file: file
+ })
+ } else if (fsStat.isDirectory()) {
+ matchingFiles = matchingFiles.concat(recursiveSearch(path.join(cwd, file), regex, depth));
+ }
+ })
+
+ return matchingFiles;
} else {
- var regex = new RegExp('^' + pattern + "$");
- cb(null, files.filter(file => regex.test(file)));
+ return [];
}
- })
-};
+}
+
+function findFile(cwd, pattern, recursive, depth, cb) {
+
+ if (recursive.constructor == Function) {
+ cb = recursive;
+ recursive = false;
+ depth = 100;
+ } else if (depth.constructor == Function) {
+ cb = depth;
+ depth = 100;
+ }
+
+ var regex = new RegExp('^' + pattern + "$");
+
+ if (recursive) {
+ cb(null, recursiveSearch(cwd, regex, depth));
+
+ } else {
+ fs.readdir(cwd, function(err, files) {
+ if (err) {
+ cb(err, null);
+ } else {
+ cb(null, files.filter(file => regex.test(file)));
+ }
+ })
+ }
+}
module.exports = findFile; |
f0fb357c989f23f21402adc46558e7924d2b710c | index.js | index.js | "use strict";
const pattern = /^\s*(\d+)(?:\s*;(?:\s*url\s*=)?\s*(.+)?)?$/i;
const parseMetaRefresh = content =>
{
const result = { timeout:null, url:null };
content = pattern.exec(content);
if (content !== null)
{
if (content[1] !== undefined)
{
result.timeout = parseInt(content[1], 10);
}
if (content[2] !== undefined)
{
let url = content[2].trim();
const firstChar = url[0];
const lastChar = url[ url.length-1 ];
// Remove a single level of encapsulating quotes
if (firstChar==="'" && lastChar==="'" || firstChar==='"' && lastChar==='"')
{
if (url.length > 2)
{
url = url.substr(1, url.length-2).trim();
}
else
{
url = "";
}
if (url === "")
{
url = null;
}
}
result.url = url;
}
}
return result;
};
module.exports = parseMetaRefresh;
| "use strict";
const pattern = /^\s*(\d+)(?:\s*;(?:\s*url\s*=)?\s*(?:("|')\s*(.+?)?\s*\2|(.+?))?)?\s*$/i;
const parseMetaRefresh = content =>
{
const result = { timeout:null, url:null };
content = pattern.exec(content);
if (content !== null)
{
// pattern gaurantees first matching group
result.timeout = parseInt( content[1] );
result.url = content[3] || content[4] || null;
}
return result;
};
module.exports = parseMetaRefresh;
| Refactor to use a regex pattern that trims the URL and recognizes enclosing single/double quotes. | Refactor to use a regex pattern that trims the URL and recognizes
enclosing single/double quotes.
| JavaScript | mit | stevenvachon/http-equiv-refresh | ---
+++
@@ -1,5 +1,5 @@
"use strict";
-const pattern = /^\s*(\d+)(?:\s*;(?:\s*url\s*=)?\s*(.+)?)?$/i;
+const pattern = /^\s*(\d+)(?:\s*;(?:\s*url\s*=)?\s*(?:("|')\s*(.+?)?\s*\2|(.+?))?)?\s*$/i;
@@ -10,38 +10,10 @@
if (content !== null)
{
- if (content[1] !== undefined)
- {
- result.timeout = parseInt(content[1], 10);
- }
+ // pattern gaurantees first matching group
+ result.timeout = parseInt( content[1] );
- if (content[2] !== undefined)
- {
- let url = content[2].trim();
-
- const firstChar = url[0];
- const lastChar = url[ url.length-1 ];
-
- // Remove a single level of encapsulating quotes
- if (firstChar==="'" && lastChar==="'" || firstChar==='"' && lastChar==='"')
- {
- if (url.length > 2)
- {
- url = url.substr(1, url.length-2).trim();
- }
- else
- {
- url = "";
- }
-
- if (url === "")
- {
- url = null;
- }
- }
-
- result.url = url;
- }
+ result.url = content[3] || content[4] || null;
}
return result; |
6024be16f23c89ed425bc8b9b269859db22bf1bd | index.js | index.js | 'use strict';
const os = require('os');
const toarray = require('lodash/toArray');
const defaults = require('lodash/defaults');
const map = require('lodash/map');
const debug = require('debug')('asset-resolver');
const Bluebird = require('bluebird');
const resolver = require('./lib/resolver');
module.exports.getResource = function(file, opts) {
opts = defaults(opts || {}, {
base: [process.cwd()],
filter() {
return true;
}
});
if (typeof opts.base === 'string') {
opts.base = [opts.base];
}
opts.base = resolver.glob(toarray(opts.base));
return Bluebird.any(
map(opts.base, base => {
return resolver.getResource(base, file, opts);
})
).catch(Bluebird.AggregateError, errs => {
const msg = [
'The file "' + file + '" could not be resolved because of:'
].concat(map(errs, 'message'));
debug(msg);
return Bluebird.reject(new Error(msg.join(os.EOL)));
});
};
| 'use strict';
const os = require('os');
const defaults = require('lodash/defaults');
const map = require('lodash/map');
const debug = require('debug')('asset-resolver');
const Bluebird = require('bluebird');
const resolver = require('./lib/resolver');
module.exports.getResource = function(file, opts) {
opts = defaults(opts || {}, {
base: [process.cwd()],
filter() {
return true;
}
});
if (typeof opts.base === 'string') {
opts.base = [opts.base];
}
opts.base = resolver.glob([...opts.base]);
return Bluebird.any(
map(opts.base, base => {
return resolver.getResource(base, file, opts);
})
).catch(Bluebird.AggregateError, errs => {
const msg = [
'The file "' + file + '" could not be resolved because of:'
].concat(map(errs, 'message'));
debug(msg);
return Bluebird.reject(new Error(msg.join(os.EOL)));
});
};
| Use the spread operator instead of lodash/toArray. | Use the spread operator instead of lodash/toArray.
| JavaScript | mit | bezoerb/asset-resolver | ---
+++
@@ -1,7 +1,6 @@
'use strict';
const os = require('os');
-const toarray = require('lodash/toArray');
const defaults = require('lodash/defaults');
const map = require('lodash/map');
const debug = require('debug')('asset-resolver');
@@ -20,7 +19,7 @@
opts.base = [opts.base];
}
- opts.base = resolver.glob(toarray(opts.base));
+ opts.base = resolver.glob([...opts.base]);
return Bluebird.any(
map(opts.base, base => { |
f86eddce1591dbfae4cc7601bf0f3e18a62b12b3 | src/resolvers/tokens.js | src/resolvers/tokens.js | 'use strict'
const tokens = require('../database/tokens')
const config = require('../utils/config')
const KnownError = require('../utils/KnownError')
const ignoreCookie = require('../utils/ignoreCookie')
const response = (entry) => ({
id: entry.id,
created: entry.created,
updated: entry.updated,
})
module.exports = {
Mutation: {
createToken: async (parent, { input }, { setCookies }) => {
const { username, password } = input
if (config.username == null) throw new KnownError('Ackee username missing in environment')
if (config.password == null) throw new KnownError('Ackee username missing in environment')
if (username !== config.username) throw new KnownError('Username or password incorrect')
if (password !== config.password) throw new KnownError('Username or password incorrect')
const entry = await tokens.add()
// Set cookie to avoid reporting your own visits
setCookies.push(ignoreCookie.on)
return {
success: true,
payload: response(entry),
}
},
deleteToken: async (parent, { id }, { setCookies }) => {
await tokens.del(id)
// Remove cookie to report your own visits, again
setCookies.push(ignoreCookie.off)
return {
success: true,
}
},
},
} | 'use strict'
const tokens = require('../database/tokens')
const config = require('../utils/config')
const KnownError = require('../utils/KnownError')
const ignoreCookie = require('../utils/ignoreCookie')
const response = (entry) => ({
id: entry.id,
created: entry.created,
updated: entry.updated,
})
module.exports = {
Mutation: {
createToken: async (parent, { input }, { setCookies }) => {
const { username, password } = input
if (config.username == null) throw new KnownError('Ackee username missing in environment')
if (config.password == null) throw new KnownError('Ackee password missing in environment')
if (username !== config.username) throw new KnownError('Username or password incorrect')
if (password !== config.password) throw new KnownError('Username or password incorrect')
const entry = await tokens.add()
// Set cookie to avoid reporting your own visits
setCookies.push(ignoreCookie.on)
return {
success: true,
payload: response(entry),
}
},
deleteToken: async (parent, { id }, { setCookies }) => {
await tokens.del(id)
// Remove cookie to report your own visits, again
setCookies.push(ignoreCookie.off)
return {
success: true,
}
},
},
} | Fix error when password is missing | Fix error when password is missing
| JavaScript | mit | electerious/Ackee | ---
+++
@@ -17,7 +17,7 @@
const { username, password } = input
if (config.username == null) throw new KnownError('Ackee username missing in environment')
- if (config.password == null) throw new KnownError('Ackee username missing in environment')
+ if (config.password == null) throw new KnownError('Ackee password missing in environment')
if (username !== config.username) throw new KnownError('Username or password incorrect')
if (password !== config.password) throw new KnownError('Username or password incorrect') |
fea2334c4fe527b6e0d239cb27686bd20922ece5 | index.js | index.js | #! /usr/bin/env node
let program = require('commander')
let configResolver = require('./src/configResolver')
let configWriter = require('./src/configWriter')
let interpolationResolver = require('./src/interpolationResolver')
let configElement = '_default'
// Set up and parse program arguments.
// We only really care about the first positional argument
// giving use the correct config to use
program
.arguments('[configElement]')
.action(_configElement => {
configElement = _configElement
})
.option('-s, --scan', 'Automatically detect interpolatinos from content')
.parse(process.argv)
// Merge regular config file and folder config
let config = Object.assign(
{},
configResolver.resolve(),
configResolver.resolveFolderConfig()
)
// Does it exist?
if (!config[configElement]) {
console.error('Found no recipe named \'' + configElement + '\' in resolved config')
process.exit(1)
}
let resolvedElement = config[configElement]
if (program.scan) {
interpolationResolver.scan(resolvedElement, (result) => {
resolvedElement.__interpolations__ = (resolvedElement.__interpolations__ || []).concat(result)
configWriter.write(resolvedElement)
})
} else {
configWriter.write(resolvedElement)
}
| #! /usr/bin/env node
const program = require('commander')
const colors = require('colors')
const configResolver = require('./src/configResolver')
const configWriter = require('./src/configWriter')
const interpolationResolver = require('./src/interpolationResolver')
let configElement = '_default'
// Set up and parse program arguments.
// We only really care about the first positional argument
// giving use the correct config to use
program
.arguments('[configElement]')
.action(_configElement => {
configElement = _configElement
})
.option('-s, --scan', 'Automatically detect interpolatinos from content')
.option('-l, --list', 'List available typical recipes recipes')
.parse(process.argv)
// Merge regular config file and folder config
let config = Object.assign(
{},
configResolver.resolve(),
configResolver.resolveFolderConfig()
)
// If list is true, we simply list the available recipes
if (program.list) {
console.log(colors.green('Available typical recipes:'))
Object.keys(config).forEach(element => {
console.log(colors.gray(' + ' + element.toString()))
})
process.exit(1)
}
// Does it exist?
if (!config[configElement]) {
console.error('Found no recipe named \'' + configElement + '\' in resolved config')
process.exit(1)
}
let resolvedElement = config[configElement]
if (program.scan) {
interpolationResolver.scan(resolvedElement, (result) => {
resolvedElement.__interpolations__ = (resolvedElement.__interpolations__ || []).concat(result)
configWriter.write(resolvedElement)
})
} else {
configWriter.write(resolvedElement)
}
| Add --list option to typical | Add --list option to typical
The option, when enabled, will print all available recipes from the
current working directory. It will not run any recipes.
| JavaScript | mit | tOgg1/typical | ---
+++
@@ -1,8 +1,9 @@
#! /usr/bin/env node
-let program = require('commander')
-let configResolver = require('./src/configResolver')
-let configWriter = require('./src/configWriter')
-let interpolationResolver = require('./src/interpolationResolver')
+const program = require('commander')
+const colors = require('colors')
+const configResolver = require('./src/configResolver')
+const configWriter = require('./src/configWriter')
+const interpolationResolver = require('./src/interpolationResolver')
let configElement = '_default'
@@ -15,6 +16,7 @@
configElement = _configElement
})
.option('-s, --scan', 'Automatically detect interpolatinos from content')
+ .option('-l, --list', 'List available typical recipes recipes')
.parse(process.argv)
// Merge regular config file and folder config
@@ -23,6 +25,15 @@
configResolver.resolve(),
configResolver.resolveFolderConfig()
)
+
+// If list is true, we simply list the available recipes
+if (program.list) {
+ console.log(colors.green('Available typical recipes:'))
+ Object.keys(config).forEach(element => {
+ console.log(colors.gray(' + ' + element.toString()))
+ })
+ process.exit(1)
+}
// Does it exist?
if (!config[configElement]) { |
f736b118113f781236d6dcb6f44e5a9b838f658d | index.js | index.js | var can = require('can/util/util');
var RBTree = require('./lib/rbtree');
// Add event utilities
can.extend(RBTree.prototype, can.event);
// Trigger a "add" event on successful insert
var _insert = RBTree.prototype.insert;
RBTree.prototype.insert = function (data) {
var insertIndex = _insert.apply(this, arguments);
if (insertIndex >= 0) {
this.dispatch('add', [[data], insertIndex]);
}
return insertIndex;
};
// Trigger a "remove" event on successful insert
var _remove = RBTree.prototype.remove;
RBTree.prototype.remove = function (data) {
// Get the node data before its removed from the tree
var nodeData = this.find(data);
// Remove, and get the index
var removeIndex = _remove.apply(this, arguments);
if (removeIndex >= 0) {
this.dispatch('remove', [[nodeData], removeIndex]);
}
return removeIndex;
};
module.exports = RBTree;
| var can = require('can/util/util');
var Construct = require('can/construct/construct');
var TreeLib = require('./lib/rbtree');
// Save to "can" namespace
can.RedBlackTree = can.Construct.extend(TreeLib.prototype).extend({
// Call the original constructor
init: TreeLib,
// Trigger a "add" event on successful insert
insert: function (data) {
var insertIndex = TreeLib.prototype.insert.apply(this, arguments);
if (insertIndex >= 0) {
this.dispatch('add', [[data], insertIndex]);
}
return insertIndex;
},
// Trigger a "remove" event on successful insert
remove: function (data) {
// Get the node data before its removed from the tree
var nodeData = this.find(data);
// Remove, and get the index
var removeIndex = TreeLib.prototype.remove.apply(this, arguments);
if (removeIndex >= 0) {
this.dispatch('remove', [[nodeData], removeIndex]);
}
return removeIndex;
},
attr: function (index) {
// Return a list all the nodes' data
if (arguments.length === 0) {
var items = [];
this.each(function (item) {
items.push(item);
});
return items;
// Get the data of a node by index
} else if (arguments.length === 1) {
var data = this.getByIndex(index);
// Node.data
return data !== null ? data : undefined;
// Set the data of a node by index
} else if (arguments.length === 2) {
// TODO
}
},
// Add an index to the `each` callback
each: function (callback) {
// Track the index manually rather than having the tree calculate it
var i = 0;
TreeLib.prototype.each.call(this, function (data) {
var result = callback(data, i);
i++;
return result;
});
}
});
// Add event utilities
can.extend(can.RedBlackTree.prototype, can.event);
module.exports = can.RedBlackTree;
| Create an Can abstraction layer over the red-black tree api | Create an Can abstraction layer over the red-black tree api
| JavaScript | mit | canjs/can-binarytree,akagomez/can-binarytree,akagomez/can-binarytree,canjs/can-binarytree | ---
+++
@@ -1,38 +1,84 @@
var can = require('can/util/util');
-var RBTree = require('./lib/rbtree');
+var Construct = require('can/construct/construct');
+var TreeLib = require('./lib/rbtree');
+
+// Save to "can" namespace
+can.RedBlackTree = can.Construct.extend(TreeLib.prototype).extend({
+
+ // Call the original constructor
+ init: TreeLib,
+
+ // Trigger a "add" event on successful insert
+ insert: function (data) {
+ var insertIndex = TreeLib.prototype.insert.apply(this, arguments);
+
+ if (insertIndex >= 0) {
+ this.dispatch('add', [[data], insertIndex]);
+ }
+
+ return insertIndex;
+ },
+
+ // Trigger a "remove" event on successful insert
+ remove: function (data) {
+
+ // Get the node data before its removed from the tree
+ var nodeData = this.find(data);
+
+ // Remove, and get the index
+ var removeIndex = TreeLib.prototype.remove.apply(this, arguments);
+
+ if (removeIndex >= 0) {
+ this.dispatch('remove', [[nodeData], removeIndex]);
+ }
+
+ return removeIndex;
+ },
+
+ attr: function (index) {
+
+ // Return a list all the nodes' data
+ if (arguments.length === 0) {
+ var items = [];
+
+ this.each(function (item) {
+ items.push(item);
+ });
+
+ return items;
+
+ // Get the data of a node by index
+ } else if (arguments.length === 1) {
+ var data = this.getByIndex(index);
+
+ // Node.data
+ return data !== null ? data : undefined;
+
+ // Set the data of a node by index
+ } else if (arguments.length === 2) {
+
+ // TODO
+
+ }
+ },
+
+ // Add an index to the `each` callback
+ each: function (callback) {
+
+ // Track the index manually rather than having the tree calculate it
+ var i = 0;
+
+ TreeLib.prototype.each.call(this, function (data) {
+ var result = callback(data, i);
+ i++;
+ return result;
+ });
+ }
+
+});
// Add event utilities
-can.extend(RBTree.prototype, can.event);
+can.extend(can.RedBlackTree.prototype, can.event);
-// Trigger a "add" event on successful insert
-var _insert = RBTree.prototype.insert;
-RBTree.prototype.insert = function (data) {
- var insertIndex = _insert.apply(this, arguments);
+module.exports = can.RedBlackTree;
- if (insertIndex >= 0) {
- this.dispatch('add', [[data], insertIndex]);
- }
-
- return insertIndex;
-};
-
-// Trigger a "remove" event on successful insert
-var _remove = RBTree.prototype.remove;
-RBTree.prototype.remove = function (data) {
-
- // Get the node data before its removed from the tree
- var nodeData = this.find(data);
-
- // Remove, and get the index
- var removeIndex = _remove.apply(this, arguments);
-
- if (removeIndex >= 0) {
- this.dispatch('remove', [[nodeData], removeIndex]);
- }
-
- return removeIndex;
-
-};
-
-module.exports = RBTree;
- |
5eeb186aab9d5272a4fe9047b5e87c6a28bd2047 | index.js | index.js | var restify = require('restify');
var messenger = require('./lib/messenger');
var session = require('./lib/session');
var server = restify.createServer();
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.authorizationParser());
server.get('/', function (req, res, next) {
res.send(200, {status: 'ok'});
});
server.post('/messages', function (req, res, next) {
console.log(req);
var phoneNumber = req.params.From;
session.get(phoneNumber, function(err, user) {
if (err) {
messenger.send(phoneNumber, 'There was some kind of error.');
res.send(500, {error: 'Something went wrong.'});
}
if (user) {
messenger.send(phoneNumber, 'Hello, old friend.');
} else {
session.set(phoneNumber, 'initial', function () {
messenger.send(phoneNumber, 'Nice to meet you.');
});
}
});
res.send(200, {status: 'ok'});
});
server.listen(process.env.PORT || '3000', function() {
console.log('%s listening at %s', server.name, server.url);
}); | var restify = require('restify');
var messenger = require('./lib/messenger');
var session = require('./lib/session');
var server = restify.createServer();
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.authorizationParser());
server.get('/', function (req, res, next) {
res.send(200, {status: 'ok'});
});
server.post('/messages', function (req, res, next) {
var phoneNumber = req.params.From;
var message = req.params.Body.toLowerCase();
if (message === 'flush') {
session.flushall(function () {
messenger('The database has been flushed.');
});
}
session.get(phoneNumber, function(err, user) {
if (err) {
messenger.send(phoneNumber, 'There was some kind of error.');
res.send(500, {error: 'Something went wrong.'});
}
if (user) {
messenger.send(phoneNumber, 'Hello, old friend.');
} else {
session.set(phoneNumber, 'initial', function () {
messenger.send(phoneNumber, 'Nice to meet you.');
});
}
});
res.send(200, {status: 'ok'});
});
server.listen(process.env.PORT || '3000', function() {
console.log('%s listening at %s', server.name, server.url);
}); | Add command to flush out the database | Add command to flush out the database
| JavaScript | mpl-2.0 | rockawayhelp/emergencybadges,rockawayhelp/emergencybadges | ---
+++
@@ -14,8 +14,14 @@
});
server.post('/messages', function (req, res, next) {
- console.log(req);
var phoneNumber = req.params.From;
+ var message = req.params.Body.toLowerCase();
+
+ if (message === 'flush') {
+ session.flushall(function () {
+ messenger('The database has been flushed.');
+ });
+ }
session.get(phoneNumber, function(err, user) {
if (err) { |
45e4e677b5c9840a8eb03ec8d42bd5cfe2a86f97 | index.js | index.js | type SourceLocation = {
line: number,
column: number
};
export default class LinesAndColumns {
constructor(string: string) {
this.string = string;
const lineLengths = [];
let start = 0;
while (true) {
let end = string.indexOf('\n', start);
if (end < 0) {
end = string.length;
} else {
end += '\n'.length;
}
lineLengths.push(end - start);
if (end === string.length) {
break;
}
start = end;
}
this.lineLengths = lineLengths;
}
locationForIndex(index: number): ?SourceLocation {
if (index < 0 || index >= this.string.length) {
return null;
}
let line = 0;
let column = index;
const lineLengths = this.lineLengths;
while (lineLengths[line] <= column && line + 1 < lineLengths.length) {
column -= lineLengths[line];
line++;
}
return ({ line, column }: SourceLocation);
}
indexForLocation(location: SourceLocation): ?number {
let { line, column } = location;
if (line < 0 || line >= this.lineLengths.length) {
return null;
}
if (column < 0 || column >= this.lineLengths[line]) {
return null;
}
let index = 0;
for (let i = line - 1; i >= 0; i--) {
index += this.lineLengths[i];
}
return index + column;
}
}
| type SourceLocation = {
line: number,
column: number
};
export default class LinesAndColumns {
constructor(string: string) {
this.string = string;
const offsets = [];
let offset = 0;
while (true) {
offsets.push(offset);
let next = string.indexOf('\n', offset);
if (next < 0) {
break;
} else {
next += '\n'.length;
}
offset = next;
}
this.offsets = offsets;
}
locationForIndex(index: number): ?SourceLocation {
if (index < 0 || index >= this.string.length) {
return null;
}
let line = 0;
const offsets = this.offsets;
while (offsets[line + 1] <= index) {
line++;
}
const column = index - offsets[line];
return ({ line, column }: SourceLocation);
}
indexForLocation(location: SourceLocation): ?number {
let { line, column } = location;
if (line < 0 || line >= this.offsets.length) {
return null;
}
if (column < 0 || column >= this._lengthOfLine(line)) {
return null;
}
return this.offsets[line] + column;
}
/**
* @private
*/
_lengthOfLine(line: number): number {
const offset = this.offsets[line];
const nextOffset = line === this.offsets.length - 1 ? this.string.length : this.offsets[line + 1];
return nextOffset - offset;
}
}
| Switch bookkeeping to record line offsets instead of line lengths. | Switch bookkeeping to record line offsets instead of line lengths.
This should be simpler and more efficient.
| JavaScript | mit | eventualbuddha/lines-and-columns,eventualbuddha/lines-and-columns | ---
+++
@@ -7,23 +7,20 @@
constructor(string: string) {
this.string = string;
- const lineLengths = [];
- let start = 0;
+ const offsets = [];
+ let offset = 0;
while (true) {
- let end = string.indexOf('\n', start);
- if (end < 0) {
- end = string.length;
+ offsets.push(offset);
+ let next = string.indexOf('\n', offset);
+ if (next < 0) {
+ break;
} else {
- end += '\n'.length;
+ next += '\n'.length;
}
- lineLengths.push(end - start);
- if (end === string.length) {
- break;
- }
- start = end;
+ offset = next;
}
- this.lineLengths = lineLengths;
+ this.offsets = offsets;
}
locationForIndex(index: number): ?SourceLocation {
@@ -32,32 +29,36 @@
}
let line = 0;
- let column = index;
- const lineLengths = this.lineLengths;
+ const offsets = this.offsets;
- while (lineLengths[line] <= column && line + 1 < lineLengths.length) {
- column -= lineLengths[line];
+ while (offsets[line + 1] <= index) {
line++;
}
+ const column = index - offsets[line];
return ({ line, column }: SourceLocation);
}
indexForLocation(location: SourceLocation): ?number {
let { line, column } = location;
- if (line < 0 || line >= this.lineLengths.length) {
+ if (line < 0 || line >= this.offsets.length) {
return null;
}
- if (column < 0 || column >= this.lineLengths[line]) {
+ if (column < 0 || column >= this._lengthOfLine(line)) {
return null;
}
- let index = 0;
- for (let i = line - 1; i >= 0; i--) {
- index += this.lineLengths[i];
- }
- return index + column;
+ return this.offsets[line] + column;
+ }
+
+ /**
+ * @private
+ */
+ _lengthOfLine(line: number): number {
+ const offset = this.offsets[line];
+ const nextOffset = line === this.offsets.length - 1 ? this.string.length : this.offsets[line + 1];
+ return nextOffset - offset;
}
} |
ddc1a606943b45871c8f7ac669ab2c946fd9b7ac | index.js | index.js | var pbkdf2 = require('crypto').pbkdf2
, randomBytes = require('crypto').randomBytes;
exports.verify = function(password, hash, callback) {
hashParts = hash.split('$');
var iterations = hashParts[2] * 500;
var salt = hashParts[3];
var hashed_password = hashParts[4];
pbkdf2(password, salt, iterations, 24, function(error, derivedKey){
if(error) {
callback(new Error(error));
} else {
callback(null, derivedKey.toString('hex') == hashed_password);
}
});
}
exports.crypt = function(password, cost, callback) {
if (typeof(callback) !== 'function') {
callback = cost;
cost = 2;
}
iterations = cost * 500;
randomBytes(18, function(error, buf) {
if(error) {
callback(new Error(error));
} else {
pbkdf2(password, buf.toString('base64'), iterations, 24, function(error, derivedKey){
if(error) {
callback(new Error(error));
} else {
var hash = '$pbkdf2-256-1$' + cost + '$' + buf.toString('base64') + '$' + derivedKey.toString('hex');
callback(null, hash);
}
});
}
});
} | var pbkdf2 = require('crypto').pbkdf2
, randomBytes = require('crypto').randomBytes;
exports.verify = function(password, hash, callback) {
hashParts = hash.split('$');
var iterations = hashParts[2] * 500;
var salt = hashParts[3];
var hashed_password = hashParts[4];
pbkdf2(password, salt, iterations, 24, function(error, derivedKey){
if(error) {
callback(new Error(error));
} else {
callback(null, derivedKey.toString('hex') == hashed_password);
}
});
}
exports.crypt = function(password, cost, callback) {
if (typeof(callback) !== 'function') {
callback = cost;
cost = 2;
}
iterations = cost * 500;
randomBytes(18, function(error, buf) {
if(error) {
callback(new Error(error));
} else {
try {
pbkdf2(password, buf.toString('base64'), iterations, 24, function(error, derivedKey){
if(error) {
callback(new Error(error));
} else {
var hash = '$pbkdf2-256-1$' + cost + '$' + buf.toString('base64') + '$' + derivedKey.toString('hex');
callback(null, hash);
}
});
} catch(e) {
callback(new Error(error));
}
}
});
}
| Handle errors emitted from PBKDF2 | Handle errors emitted from PBKDF2
| JavaScript | mit | kudos/node-passwords | ---
+++
@@ -6,7 +6,7 @@
var iterations = hashParts[2] * 500;
var salt = hashParts[3];
var hashed_password = hashParts[4];
-
+
pbkdf2(password, salt, iterations, 24, function(error, derivedKey){
if(error) {
callback(new Error(error));
@@ -21,21 +21,25 @@
callback = cost;
cost = 2;
}
-
+
iterations = cost * 500;
randomBytes(18, function(error, buf) {
if(error) {
callback(new Error(error));
} else {
- pbkdf2(password, buf.toString('base64'), iterations, 24, function(error, derivedKey){
- if(error) {
- callback(new Error(error));
- } else {
- var hash = '$pbkdf2-256-1$' + cost + '$' + buf.toString('base64') + '$' + derivedKey.toString('hex');
- callback(null, hash);
- }
- });
+ try {
+ pbkdf2(password, buf.toString('base64'), iterations, 24, function(error, derivedKey){
+ if(error) {
+ callback(new Error(error));
+ } else {
+ var hash = '$pbkdf2-256-1$' + cost + '$' + buf.toString('base64') + '$' + derivedKey.toString('hex');
+ callback(null, hash);
+ }
+ });
+ } catch(e) {
+ callback(new Error(error));
+ }
}
});
} |
8f736cac4c94d4f02c909f3091904eb2ccc47e23 | index.js | index.js | var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
app.get('/sayhello', function (req, res){
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({message: "Hello " + req.query.name}));
});
app.listen(process.env.PORT || 3000);
| var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
app.get('/sayhello', function (req, res){
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({message: "Hello " + req.query.name}));
});
app.listen(process.env.PORT || 3000);
| Allow all cross-origin requests to /sayhello | Allow all cross-origin requests to /sayhello
| JavaScript | mit | codehackdays/HelloWorld | ---
+++
@@ -6,6 +6,7 @@
});
app.get('/sayhello', function (req, res){
+ res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({message: "Hello " + req.query.name}));
}); |
cb29d306bd8be1ba163809c502e7fdbcabe27e0a | index.js | index.js | /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-power-select',
included: function(appOrAddon) {
var app = appOrAddon.app || appOrAddon;
if (!app.__emberPowerSelectIncludedInvoked) {
app.__emberPowerSelectIncludedInvoked = true;
var options = typeof app.options === 'object' ? app.options : {};
var addonConfig = options['ember-power-select'] || {};
// Since ember-power-select styles already `@import` styles of ember-basic-dropdown,
// this flag tells to ember-basic-dropdown to skip importing its styles provided
// we're using a theme (or the default styles)
if (addonConfig.theme !== false) {
app.__skipEmberBasicDropdownStyles = true;
}
this._super.included.apply(this, arguments);
// Don't include the precompiled css file if the user uses ember-cli-sass
if (!app.registry.availablePlugins['ember-cli-sass']) {
if (addonConfig.theme) {
app.import('vendor/ember-power-select-'+addonConfig.theme+'.css');
} else if (addonConfig.theme !== false) {
app.import('vendor/ember-power-select.css');
}
}
}
},
contentFor: function(type, config) {
var emberBasicDropdown = this.addons.filter(function(addon) {
return addon.name === 'ember-basic-dropdown';
})[0]
return emberBasicDropdown.contentFor(type, config);
}
};
| /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-power-select',
included(appOrAddon) {
let app = appOrAddon.app || appOrAddon;
if (!app.__emberPowerSelectIncludedInvoked) {
app.__emberPowerSelectIncludedInvoked = true;
let options = typeof app.options === 'object' ? app.options : {};
let addonConfig = options['ember-power-select'] || {};
// Since ember-power-select styles already `@import` styles of ember-basic-dropdown,
// this flag tells to ember-basic-dropdown to skip importing its styles provided
// we're using a theme (or the default styles)
if (addonConfig.theme !== false) {
app.__skipEmberBasicDropdownStyles = true;
}
this._super.included.apply(this, arguments);
// Don't include the precompiled css file if the user uses ember-cli-sass
if (!app.registry.availablePlugins['ember-cli-sass']) {
if (addonConfig.theme) {
app.import(`vendor/ember-power-select-${addonConfig.theme}.css`);
} else if (addonConfig.theme !== false) {
app.import('vendor/ember-power-select.css');
}
}
}
},
contentFor(type, config) {
let emberBasicDropdown = this.addons.find((a) => a.name === 'ember-basic-dropdown');
return emberBasicDropdown.contentFor(type, config);
}
};
| Use es6 syntax in node | Use es6 syntax in node
| JavaScript | mit | esbanarango/ember-power-select,cibernox/ember-power-select,cibernox/ember-power-select,cibernox/ember-power-select,cibernox/ember-power-select,esbanarango/ember-power-select,esbanarango/ember-power-select | ---
+++
@@ -4,13 +4,13 @@
module.exports = {
name: 'ember-power-select',
- included: function(appOrAddon) {
- var app = appOrAddon.app || appOrAddon;
+ included(appOrAddon) {
+ let app = appOrAddon.app || appOrAddon;
if (!app.__emberPowerSelectIncludedInvoked) {
app.__emberPowerSelectIncludedInvoked = true;
- var options = typeof app.options === 'object' ? app.options : {};
- var addonConfig = options['ember-power-select'] || {};
+ let options = typeof app.options === 'object' ? app.options : {};
+ let addonConfig = options['ember-power-select'] || {};
// Since ember-power-select styles already `@import` styles of ember-basic-dropdown,
// this flag tells to ember-basic-dropdown to skip importing its styles provided
@@ -24,7 +24,7 @@
// Don't include the precompiled css file if the user uses ember-cli-sass
if (!app.registry.availablePlugins['ember-cli-sass']) {
if (addonConfig.theme) {
- app.import('vendor/ember-power-select-'+addonConfig.theme+'.css');
+ app.import(`vendor/ember-power-select-${addonConfig.theme}.css`);
} else if (addonConfig.theme !== false) {
app.import('vendor/ember-power-select.css');
}
@@ -32,10 +32,8 @@
}
},
- contentFor: function(type, config) {
- var emberBasicDropdown = this.addons.filter(function(addon) {
- return addon.name === 'ember-basic-dropdown';
- })[0]
+ contentFor(type, config) {
+ let emberBasicDropdown = this.addons.find((a) => a.name === 'ember-basic-dropdown');
return emberBasicDropdown.contentFor(type, config);
}
}; |
e562f0ed78ddae0603ba1f012c87d34b0c2606d6 | index.js | index.js | /*!
* to-clipboard <https://github.com/jonschlinkert/to-clipboard>
*
* Copyright (c) 2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
'use strict';
var cp = require('child_process');
function toClipboard(args, cb) {
var proc = cp.spawn(program(), {
stdio: ['pipe', 'ignore', 'ignore']
});
if (cb) {
proc.on('error', cb);
proc.on('exit', function() {
cb(null);
});
}
proc.stdin.write(args);
proc.stdin.end();
}
toClipboard.sync = function toClipboardSync(args) {
return cp.execSync(program(), {input: args});
};
function program() {
switch (process.platform) {
case 'win32':
return 'clip';
case 'linux':
return 'xclip -selection clipboard';
case 'android':
return 'termux-clipboard-set'
case 'darwin':
default: {
return 'pbcopy';
}
}
}
/**
* Expose `toClipboard`
*/
module.exports = toClipboard;
| /*!
* to-clipboard <https://github.com/jonschlinkert/to-clipboard>
*
* Copyright (c) 2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
'use strict';
var cp = require('child_process');
function toClipboard(args, cb) {
var proc = cp.spawn(program(), {
stdio: ['pipe', 'ignore', 'ignore']
});
if (cb) {
proc.on('error', cb);
proc.on('exit', function() {
cb(null);
});
}
proc.stdin.write(args);
proc.stdin.end();
}
toClipboard.sync = function toClipboardSync(args) {
return cp.execSync(program(), {input: args});
};
function program() {
switch (process.platform) {
case 'win32':
return 'clip';
case 'linux':
return 'xsel -bi';
case 'android':
return 'termux-clipboard-set'
case 'darwin':
default: {
return 'pbcopy';
}
}
}
/**
* Expose `toClipboard`
*/
module.exports = toClipboard;
| Use xsel instead of xclip | Use xsel instead of xclip
Prevents indefinite hang on linux | JavaScript | mit | jonschlinkert/to-clipboard | ---
+++
@@ -32,7 +32,7 @@
case 'win32':
return 'clip';
case 'linux':
- return 'xclip -selection clipboard';
+ return 'xsel -bi';
case 'android':
return 'termux-clipboard-set'
case 'darwin': |
e2a50a3cf0fda4f78d99b8e3c314077f56ec04cd | index.js | index.js | var package = require('package')
var join = require('path').join
function merge (a, b) {
for(var k in b) {
a[k] = b[k]
}
return a
}
module.exports = function (start, opts) {
start = start || process.cwd()
var p = package({filename: join(start, 'package.json')})
var m = !opts || opts.dev !== false
? merge(p.devDependencies, p.dependencies)
: p.dependencies
var a = []
for(var k in m) a.push(k + '@' + m[k])
return a
}
if(!module.parent)
console.log(module.exports(process.argv[2]))
| var package = require('package')
var join = require('path').join
function merge (a, b) {
var c = a || {}
for(var k in b) {
c[k] = b[k]
}
return c
}
module.exports = function (start, opts) {
start = start || process.cwd()
var p = package({filename: join(start, 'package.json')})
var m = !opts || opts.dev !== false
? merge(p.devDependencies, p.dependencies)
: p.dependencies
var a = []
for(var k in m) a.push(k + '@' + m[k])
return a
}
if(!module.parent)
console.log(module.exports(process.argv[2]))
| Handle undefined destination in merge, target c for immutability | Handle undefined destination in merge, target c for immutability
| JavaScript | mit | dominictarr/get-deps | ---
+++
@@ -2,10 +2,11 @@
var join = require('path').join
function merge (a, b) {
+ var c = a || {}
for(var k in b) {
- a[k] = b[k]
+ c[k] = b[k]
}
- return a
+ return c
}
module.exports = function (start, opts) { |
816551098f9a61bb47b61fffd15a6919e58b2647 | index.js | index.js | /*jslint node:true */
var RequireAll = (function () {
'use strict';
var fs = require('fs'),
excludeDirectory = function (excludeDirs, dirname) {
return excludeDirs && dirname.match(excludeDirs);
},
loadAllModules = function (options) {
var files = fs.readdirSync(options.dirname),
modules = {};
files.forEach(function (file) {
if (excludeDirectory(options.excludeDirs, file)) {
return;
}
var filepath = options.dirname + '/' + file;
if (fs.statSync(filepath).isDirectory()) {
modules[file] = loadAllModules({
dirname : filepath,
filter : options.filter,
excludeDirs : options.excludeDirs,
dependencies : options.dependencies
});
} else {
if (file.match(options.filter)) {
modules[file.split('.')[0]] = require(filepath).apply(this, options.dependencies);
}
}
});
};
return {
loadAllModules : loadAllModules
};
}());
module.exports = RequireAll; | /*jslint node:true */
var RequireAll = (function () {
'use strict';
var fs = require('fs'),
exclude = function (excludeRegexp, name) {
return excludeRegexp && name.match(excludeRegexp);
},
loadAllModules = function (options) {
var files = fs.readdirSync(options.dirname),
modules = {};
files.forEach(function (file) {
if (exclude(options.exclude, file)) {
return;
}
var filepath = options.dirname + '/' + file;
if (fs.statSync(filepath).isDirectory()) {
modules[file] = loadAllModules({
dirname : filepath,
filter : options.filter,
exclude : options.exclude,
dependencies : options.dependencies
});
} else {
if (file.match(options.filter)) {
modules[file.split('.')[0]] = require(filepath).apply(this, options.dependencies);
}
}
});
};
return {
loadAllModules : loadAllModules
};
}());
module.exports = RequireAll; | Allow files to be exlcuded | Allow files to be exlcuded
| JavaScript | mit | jaalfaro/node-require-all | ---
+++
@@ -4,8 +4,8 @@
var fs = require('fs'),
- excludeDirectory = function (excludeDirs, dirname) {
- return excludeDirs && dirname.match(excludeDirs);
+ exclude = function (excludeRegexp, name) {
+ return excludeRegexp && name.match(excludeRegexp);
},
loadAllModules = function (options) {
@@ -13,7 +13,7 @@
modules = {};
files.forEach(function (file) {
- if (excludeDirectory(options.excludeDirs, file)) {
+ if (exclude(options.exclude, file)) {
return;
}
@@ -23,7 +23,7 @@
modules[file] = loadAllModules({
dirname : filepath,
filter : options.filter,
- excludeDirs : options.excludeDirs,
+ exclude : options.exclude,
dependencies : options.dependencies
});
} else { |
8f02cf51d0271361f1406a93234ce3eef8cc185b | ut/mocha.js | ut/mocha.js | var assert = require('assert');
describe('Angularjs', function() {
describe('test', function() {
it('always true', function() {
assert(1)
});
});
});
| var assert = require('assert');
describe('Angularjs', function() {
describe('main', function() {
it('always true', function() {
assert(1)
});
});
});
describe('Angularjs', function() {
describe('fpga', function() {
it('always true', function() {
assert(1)
});
});
});
describe('Angularjs', function() {
describe('db', function() {
it('always true', function() {
assert(1)
});
});
});
| Add test for fpga main db | Add test for fpga main db
| JavaScript | agpl-3.0 | OpenFPGAduino/Arduinojs,OpenFPGAduino/Arduinojs,OpenFPGAduino/Arduinojs,OpenFPGAduino/Arduinojs,OpenFPGAduino/Arduinojs | ---
+++
@@ -1,8 +1,24 @@
var assert = require('assert');
describe('Angularjs', function() {
- describe('test', function() {
+ describe('main', function() {
it('always true', function() {
assert(1)
});
});
});
+
+describe('Angularjs', function() {
+ describe('fpga', function() {
+ it('always true', function() {
+ assert(1)
+ });
+ });
+});
+
+describe('Angularjs', function() {
+ describe('db', function() {
+ it('always true', function() {
+ assert(1)
+ });
+ });
+}); |
a404d8d12abeaeae083368f8b5394ac2f998da32 | index.js | index.js | 'use strict';
module.exports = toMDAST;
var minify = require('rehype-minify-whitespace')();
var xtend = require('xtend');
var one = require('./one');
var handlers = require('./handlers');
h.augment = augment;
function toMDAST(tree, options) {
options = options || {};
h.handlers = xtend(handlers, options.handlers || {});
return one(h, minify(tree), null);
}
function h(node, type, props, children) {
var result;
if (!children && ((typeof props === 'object' && 'length' in props) || typeof props === 'string')) {
children = props;
props = {};
}
result = xtend({type: type}, props);
if (typeof children === 'string') {
result.value = children;
} else if (children) {
result.children = children;
}
return augment(node, result);
}
/* `right` is the finalized MDAST node,
* created from `left`, a HAST node */
function augment(left, right) {
if (left.position) {
right.position = left.position;
}
return right;
}
| 'use strict';
module.exports = toMDAST;
var minify = require('rehype-minify-whitespace')();
var xtend = require('xtend');
var one = require('./one');
var handlers = require('./handlers');
function toMDAST(tree, options) {
var settings = options || {};
h.handlers = xtend(handlers, settings.handlers || {});
h.augment = augment;
return one(h, minify(tree), null);
function h(node, type, props, children) {
var result;
if (!children && ((typeof props === 'object' && 'length' in props) || typeof props === 'string')) {
children = props;
props = {};
}
result = xtend({type: type}, props);
if (typeof children === 'string') {
result.value = children;
} else if (children) {
result.children = children;
}
return augment(node, result);
}
/* `right` is the finalized MDAST node,
* created from `left`, a HAST node */
function augment(left, right) {
if (left.position) {
right.position = left.position;
}
return right;
}
}
| Fix modifying of constant functions | Fix modifying of constant functions
| JavaScript | mit | syntax-tree/hast-util-to-mdast | ---
+++
@@ -7,39 +7,40 @@
var one = require('./one');
var handlers = require('./handlers');
-h.augment = augment;
+function toMDAST(tree, options) {
+ var settings = options || {};
-function toMDAST(tree, options) {
- options = options || {};
- h.handlers = xtend(handlers, options.handlers || {});
+ h.handlers = xtend(handlers, settings.handlers || {});
+ h.augment = augment;
+
return one(h, minify(tree), null);
-}
-function h(node, type, props, children) {
- var result;
+ function h(node, type, props, children) {
+ var result;
- if (!children && ((typeof props === 'object' && 'length' in props) || typeof props === 'string')) {
- children = props;
- props = {};
+ if (!children && ((typeof props === 'object' && 'length' in props) || typeof props === 'string')) {
+ children = props;
+ props = {};
+ }
+
+ result = xtend({type: type}, props);
+
+ if (typeof children === 'string') {
+ result.value = children;
+ } else if (children) {
+ result.children = children;
+ }
+
+ return augment(node, result);
}
- result = xtend({type: type}, props);
+ /* `right` is the finalized MDAST node,
+ * created from `left`, a HAST node */
+ function augment(left, right) {
+ if (left.position) {
+ right.position = left.position;
+ }
- if (typeof children === 'string') {
- result.value = children;
- } else if (children) {
- result.children = children;
+ return right;
}
-
- return augment(node, result);
}
-
-/* `right` is the finalized MDAST node,
- * created from `left`, a HAST node */
-function augment(left, right) {
- if (left.position) {
- right.position = left.position;
- }
-
- return right;
-} |
e7c1d28564d6dacd8e912e7f0251696ccff9dd16 | index.js | index.js | /*
extract url or data-url from css
- value - css value
*/
function urldata(value){
if(!value){
return;
}
var result = [];
var urlCursor = value.indexOf("url");
var start = 0;
var end = 0;
while(urlCursor >= 0){
start = urlCursor + 3;
while(value[start] === " "){ start++; }
if(value[start] === "("){
start ++;
} else {
return result;
}
while(value[start] === " "){ start++; }
var openQuote = value[start];
if(openQuote === "\'" || openQuote === "\""){
start++;
} else {
openQuote = "";
}
if(!openQuote){
while(value[start] === " "){ start++; }
}
end = value.indexOf(")", start);
if(end < 0){
return result;
}
end--;
while(value[end]===" "){
end--;
}
if(!!openQuote){
if(value[end] === openQuote){
end--;
} else {
start--;
}
}
result[result.length] = value.slice(start, end + 1);
urlCursor = value.indexOf("url", end);
}
return result;
}
module.exports = urldata;
| /*
extract url or data-url from css
- value - css value
*/
function urldata(value){
if(!value){
return;
}
var result = [];
var urlCursor = value.indexOf("url");
var start = 0;
var end = 0;
while(urlCursor >= 0){
start = urlCursor + 3;
while(value[start] === " "){ start++; }
if(value[start] === "("){
start ++;
} else {
return result;
}
while(value[start] === " "){ start++; }
var openQuote = value[start];
if(openQuote === "\'" || openQuote === "\""){
start++;
} else {
openQuote = "";
}
if(!openQuote){
while(value[start] === " "){ start++; }
}
if (!openQuote) {
end = value.indexOf(")", start);
} else {
end = start;
while(value[end] !== openQuote) { end++; }
while(value[end] !== ")"){ end++; }
}
if(end < 0){
return result;
}
end--;
while(value[end]===" "){
end--;
}
if(!!openQuote){
if(value[end] === openQuote){
end--;
} else {
start--;
}
}
result[result.length] = value.slice(start, end + 1);
urlCursor = value.indexOf("url", end);
}
return result;
}
module.exports = urldata;
| Fix when the url value contains parentheses | Fix when the url value contains parentheses | JavaScript | mit | lexich/urldata | ---
+++
@@ -34,8 +34,14 @@
while(value[start] === " "){ start++; }
}
-
- end = value.indexOf(")", start);
+ if (!openQuote) {
+ end = value.indexOf(")", start);
+ } else {
+ end = start;
+ while(value[end] !== openQuote) { end++; }
+ while(value[end] !== ")"){ end++; }
+ }
+
if(end < 0){
return result;
}
@@ -55,4 +61,5 @@
}
return result;
}
+
module.exports = urldata; |
bfa6210296d890b02f1f1f7acc7687824d4a1ea2 | index.js | index.js | var dgram = require('dgram');
const PORT = 5050
const PING_PAYLOAD = "dd00000a000000000000000400000002"
const POWER_PAYLOAD = "dd02001300000010"
module.exports = Xbox;
function Xbox(ip, id) {
this.ip = ip;
this.id = id;
return this;
}
Xbox.prototype.powerOn = function(callback) {
callback = callback || function() {};
var message = Buffer.concat([new Buffer(POWER_PAYLOAD, 'hex'), new Buffer(this.id), new Buffer(1).fill(0)]);
var socket = dgram.createSocket('udp4');
socket.send(message, 0, message.length, PORT, this.ip, function(err, bytes) {
if (err) throw err;
socket.close();
callback();
});
}
| var dgram = require('dgram');
const PORT = 5050
const PING_PAYLOAD = "dd00000a000000000000000400000002"
const POWER_PAYLOAD = "dd02001300000010"
module.exports = Xbox;
function Xbox(ip, id) {
this.ip = ip;
this.id = id;
return this;
}
Xbox.prototype.powerOn = function(callback) {
callback = callback || function() {};
// Counter some older node compatibility issues with `new Buffer(1).fill(0)`
var zeroBuffer = new Buffer(1);
zeroBuffer.write('\u0000');
var message = Buffer.concat([new Buffer(POWER_PAYLOAD, 'hex'), new Buffer(this.id), zeroBuffer]);
var socket = dgram.createSocket('udp4');
socket.send(message, 0, message.length, PORT, this.ip, function(err, bytes) {
if (err) throw err;
socket.close();
callback();
});
}
| Fix zero buffer issues for node 0.10.25 | Fix zero buffer issues for node 0.10.25
| JavaScript | mit | arcreative/xbox-on | ---
+++
@@ -14,7 +14,12 @@
Xbox.prototype.powerOn = function(callback) {
callback = callback || function() {};
- var message = Buffer.concat([new Buffer(POWER_PAYLOAD, 'hex'), new Buffer(this.id), new Buffer(1).fill(0)]);
+
+ // Counter some older node compatibility issues with `new Buffer(1).fill(0)`
+ var zeroBuffer = new Buffer(1);
+ zeroBuffer.write('\u0000');
+
+ var message = Buffer.concat([new Buffer(POWER_PAYLOAD, 'hex'), new Buffer(this.id), zeroBuffer]);
var socket = dgram.createSocket('udp4');
socket.send(message, 0, message.length, PORT, this.ip, function(err, bytes) {
if (err) throw err; |
6c6060d667e06db6a2fd51eae924630832c9e9c9 | index.js | index.js | /* jshint node: true */
var PLUGIN_NAME = 'gulp-multi-dest';
var through = require('through2');
var gulp = require('gulp');
var async = require('async');
module.exports = function(paths, options) {
options = options || {};
var files = [];
var dests = paths.map(function(path) {
return gulp.dest(path, options);
});
function writeFilesToMultipleDestinations(file, done) {
async.each(dests, function(dest, wroteOne) {
dest.write(file, wroteOne);
}, done);
}
var holdFile = function(file, encoding, done) {
files.push(file);
done();
};
var flushAllFiles = function(done) {
var transform = this;
function outputFiles() {
files.forEach(function(file) {
transform.push(file);
});
done();
}
async.each(files, writeFilesToMultipleDestinations, outputFiles);
};
return through.obj(holdFile, flushAllFiles);
}; | /* jshint node: true */
var PLUGIN_NAME = 'gulp-multi-dest';
var through = require('through2');
var gulp = require('gulp');
var async = require('async');
module.exports = function(paths, options) {
options = options || {};
var files = [];
if (typeof (paths) === 'string') { paths = [paths]; }
var dests = paths.map(function(path) {
return gulp.dest(path, options);
});
function writeFilesToMultipleDestinations(file, done) {
async.each(dests, function(dest, wroteOne) {
dest.write(file, wroteOne);
}, done);
}
var holdFile = function(file, encoding, done) {
files.push(file);
done();
};
var flushAllFiles = function(done) {
var transform = this;
function outputFiles() {
files.forEach(function(file) {
transform.push(file);
});
done();
}
async.each(files, writeFilesToMultipleDestinations, outputFiles);
};
return through.obj(holdFile, flushAllFiles);
}; | Add support for a single string destination | Add support for a single string destination
| JavaScript | mit | kdelmonte/gulp-multi-dest | ---
+++
@@ -7,6 +7,9 @@
module.exports = function(paths, options) {
options = options || {};
var files = [];
+
+
+ if (typeof (paths) === 'string') { paths = [paths]; }
var dests = paths.map(function(path) {
return gulp.dest(path, options); |
f5873fa7be7d537c68f584706c9ed3ec5d74d83d | app/scripts/controllers/checkout.js | app/scripts/controllers/checkout.js | 'use strict';
app.controller('CheckoutCtrl', function($scope, Basket, Order, AuthenticationService) {
$scope.basket = Basket;
$scope.currentUser = AuthenticationService.currentUser();
var hour = 60 * 60 * 1000; // 1 Hour in ms
$scope.pickupTime = new Date() + (2 * hour);
$scope.createOrder = function() {
console.log('Building the order...');
var orderItems = [];
angular.forEach($scope.basket.get(), function(item) {
orderItems.push({'menu_id': item.menu, 'menu_item': item.id, 'quantity': item.quantity});
});
// var order = null;
var order = {
'order': {
// 'user_id': $scope.currentUser.id,
// 'menu_id': 2,
'order_time': new Date(),
'pickup_time': $scope.pickupTime
},
'order_items': orderItems
};
console.log('Submitting the order...');
console.log(order);
new Order.create(order).then(function (newOrder) {
console.log('The following order was created successfully');
console.log(newOrder);
});
};
});
| 'use strict';
app.controller('CheckoutCtrl', function($scope, Basket, Order, AuthenticationService) {
$scope.basket = Basket;
$scope.currentUser = AuthenticationService.currentUser();
$scope.createOrder = function() {
console.log('Building the order...');
var orderItems = [];
angular.forEach($scope.basket.get(), function(item) {
orderItems.push({'menu_id': item.menu, 'menu_item': item.id, 'quantity': item.quantity});
});
var now = new Date();
var pickupTime = new Date(now.setHours(now.getHours() + 1));
var order = {
'order': {
'order_time': now,
'pickup_time': pickupTime
},
'order_items': orderItems
};
console.log('Submitting the order...');
console.log(order);
new Order.create(order, function (newOrder) {
console.log('The following order was created successfully');
console.log(newOrder);
});
};
});
| Fix issue with date format causing order creation to fail | Fix issue with date format causing order creation to fail
| JavaScript | mit | scootcho/TMA-client,scootcho/TMA-client,diraulo/TMA-client,AgileVentures/TMA-client,AgileVentures/TMA-client,diraulo/TMA-client | ---
+++
@@ -3,9 +3,6 @@
app.controller('CheckoutCtrl', function($scope, Basket, Order, AuthenticationService) {
$scope.basket = Basket;
$scope.currentUser = AuthenticationService.currentUser();
- var hour = 60 * 60 * 1000; // 1 Hour in ms
- $scope.pickupTime = new Date() + (2 * hour);
-
$scope.createOrder = function() {
console.log('Building the order...');
@@ -14,19 +11,19 @@
orderItems.push({'menu_id': item.menu, 'menu_item': item.id, 'quantity': item.quantity});
});
- // var order = null;
+ var now = new Date();
+ var pickupTime = new Date(now.setHours(now.getHours() + 1));
+
var order = {
'order': {
- // 'user_id': $scope.currentUser.id,
- // 'menu_id': 2,
- 'order_time': new Date(),
- 'pickup_time': $scope.pickupTime
+ 'order_time': now,
+ 'pickup_time': pickupTime
},
'order_items': orderItems
};
console.log('Submitting the order...');
console.log(order);
- new Order.create(order).then(function (newOrder) {
+ new Order.create(order, function (newOrder) {
console.log('The following order was created successfully');
console.log(newOrder);
}); |
8e957e055863ade32d8ea115c13d103c96865bc9 | index.js | index.js | var Matcher = require('minimatch').Minimatch;
/**
* Sets the given metadata on the file object
*
* @param file {Object}
* @param metadata {Object}
* @private
*/
function setMetadata(file, rule) {
Object.keys(rule.metadata).forEach(function (key) {
if (rule.preserve && key in file) {
return;
}
file[key] = rule.metadata[key];
});
}
/**
* Sets some metadata on each file depending a pattern
*
* @param rules {Array} array of rules to set the metadata, each item of
* the array should be a literal object containing a `pattern` entry (String)
* and a `metadata` entry (Object)
*
* @return {Function}
*/
module.exports = function (rules) {
var rules = rules || [],
matchers = [];
rules.forEach(function (rule) {
matchers.push({
matcher: new Matcher(rule.pattern),
metadata: rule.metadata,
preserve: rule.preserve,
});
});
return function (files, metalsmith, done) {
var globalMetadata = metalsmith.metadata();
Object.keys(files).forEach(function (file) {
var fileObject = files[file];
matchers.forEach(function (rule) {
if ( rule.matcher.match(file) ) {
if (typeof rule.metadata === 'function') {
rule = Object.assign({}, rule, { metadata: rule.metadata(fileObject, globalMetadata) });
}
setMetadata(fileObject, rule);
}
});
});
done();
};
};
| var Matcher = require('minimatch').Minimatch;
/**
* Sets the given metadata on the file object
*
* @param file {Object}
* @param metadata {Object}
* @private
*/
function setMetadata(file, global, rule) {
if (typeof rule.metadata === 'function') {
rule = Object.assign({}, rule, { metadata: rule.metadata(file, global) });
}
Object.keys(rule.metadata).forEach(function (key) {
if (rule.preserve && key in file) {
return;
}
file[key] = rule.metadata[key];
});
}
/**
* Sets some metadata on each file depending a pattern
*
* @param rules {Array} array of rules to set the metadata, each item of
* the array should be a literal object containing a `pattern` entry (String)
* and a `metadata` entry (Object)
*
* @return {Function}
*/
module.exports = function (rules) {
var rules = rules || [],
matchers = [];
rules.forEach(function (rule) {
matchers.push({
matcher: new Matcher(rule.pattern),
metadata: rule.metadata,
preserve: rule.preserve,
});
});
return function (files, metalsmith, done) {
var globalMetadata = metalsmith.metadata();
Object.keys(files).forEach(function (file) {
var fileObject = files[file];
matchers.forEach(function (rule) {
if ( rule.matcher.match(file) ) {
setMetadata(fileObject, globalMetadata, rule);
}
});
});
done();
};
};
| Move function metadata logic to setMetadata function | Move function metadata logic to setMetadata function
| JavaScript | mit | dpobel/metalsmith-filemetadata | ---
+++
@@ -7,7 +7,10 @@
* @param metadata {Object}
* @private
*/
-function setMetadata(file, rule) {
+function setMetadata(file, global, rule) {
+ if (typeof rule.metadata === 'function') {
+ rule = Object.assign({}, rule, { metadata: rule.metadata(file, global) });
+ }
Object.keys(rule.metadata).forEach(function (key) {
if (rule.preserve && key in file) {
return;
@@ -45,10 +48,7 @@
matchers.forEach(function (rule) {
if ( rule.matcher.match(file) ) {
- if (typeof rule.metadata === 'function') {
- rule = Object.assign({}, rule, { metadata: rule.metadata(fileObject, globalMetadata) });
- }
- setMetadata(fileObject, rule);
+ setMetadata(fileObject, globalMetadata, rule);
}
});
}); |
e9ad2ee5eb506cfeeef01f633916ccfc949d443c | email.js | email.js | //Require Module
var log4js = require('log4js');
var logger = log4js.getLogger('Logging');
function sendAliveMail (connection,opt,callback){
logger.debug('Sending Alive Mail......');
connection.send(opt,callback);
}
function sendWarningMail(connection,opt,callback){
logger.debug('Sending Warning Mail......');
connection.send(opt,callback);
}
module.exports = {
sendAliveMail:sendAliveMail,
sendWarningMail:sendWarningMail
}
| //Require Module
var log4js = require('log4js');
var logger = log4js.getLogger('Logging');
function sendAliveMail (connection,opt,callback){
/**
*Receive the connection of mail server, mail option and callback,
*Then send the alive mail by the these value.
* */
logger.debug('Sending Alive Mail......');
connection.send(opt,callback);
}
function sendWarningMail(connection,opt,callback){
/**
*Receive the connection of mail server, mail option and callback,
*Then send the warning mail by the these value.
* */
logger.debug('Sending Warning Mail......');
connection.send(opt,callback);
}
module.exports = {
sendAliveMail:sendAliveMail,
sendWarningMail:sendWarningMail
}
| Add comment with jsdoc style | Add comment with jsdoc style
| JavaScript | apache-2.0 | dollars0427/SQLwatcher | ---
+++
@@ -3,6 +3,11 @@
var logger = log4js.getLogger('Logging');
function sendAliveMail (connection,opt,callback){
+
+/**
+ *Receive the connection of mail server, mail option and callback,
+ *Then send the alive mail by the these value.
+ * */
logger.debug('Sending Alive Mail......');
@@ -10,6 +15,11 @@
}
function sendWarningMail(connection,opt,callback){
+
+/**
+ *Receive the connection of mail server, mail option and callback,
+ *Then send the warning mail by the these value.
+ * */
logger.debug('Sending Warning Mail......');
|
6b8ad9f04dfcae7fa830f30e82a52590c231a00b | backbone-collection-search-ajax.js | backbone-collection-search-ajax.js | // Backbone.Collection.search-ajax v0.2
// by Joe Vu - joe.vu@homeslicesolutions.com
// For all details and documentation:
// https://github.com/homeslicesolutions/backbone-collection-search
!function(_, Backbone){
// Extending out
_.extend(Backbone.Collection.prototype, {
//@ Search for AJAX version
search: function(keyword, attributes) {
// Closure
var that = this;
// Get new data
this.fetch({
parse: false,
data: {
keyword: keyword,
attributes: attributes
},
success: function( collection ){
// Instantiate new Collection
collection._searchQuery = keyword;
collection.getSearchQuery = function() {
return this._searchQuery;
}
// Cache the recently searched metadata
that._searchResults = collection;
// Fire search event with new collection
that.trigger('search', collection );
}
});
},
//@ Get recent search query
getSearchQuery: function() {
return this.getSearchResults().getSearchQuery();
},
//@ Get recent search results
getSearchResults: function() {
return this._searchResults;
},
//_Cache
_searchResults: null
});
}(_, Backbone); | // Backbone.Collection.search-ajax v0.2
// by Joe Vu - joe.vu@homeslicesolutions.com
// For all details and documentation:
// https://github.com/homeslicesolutions/backbone-collection-search
!function(_, Backbone){
// Extending out
_.extend(Backbone.Collection.prototype, {
//@ Search for AJAX version
search: function(keyword, attributes) {
// Closure
var that = this;
// Get new data
this.fetch({
parse: false,
data: {
keyword: keyword,
attributes: attributes
},
success: function( collection ){
// Instantiate new Collection
collection._searchQuery = keyword;
collection.getSearchQuery = function() {
return this._searchQuery;
}
// Cache the recently searched metadata
that._searchResults = collection;
// Fire search event with new collection
that.trigger('search', collection );
}
});
},
//@ Get recent search query
getSearchQuery: function() {
return this.getSearchResults() && this.getSearchResults().getSearchQuery();
},
//@ Get recent search results
getSearchResults: function() {
return this._searchResults;
},
//_Cache
_searchResults: null
});
}(_, Backbone);
| Check for null exception on getSearchQuery | Check for null exception on getSearchQuery | JavaScript | mit | homeslicesolutions/backbone-collection-search,homeslicesolutions/backbone-collection-search | ---
+++
@@ -40,7 +40,7 @@
//@ Get recent search query
getSearchQuery: function() {
- return this.getSearchResults().getSearchQuery();
+ return this.getSearchResults() && this.getSearchResults().getSearchQuery();
},
//@ Get recent search results |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.