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 |
|---|---|---|---|---|---|---|---|---|---|---|
0d56522d9ae59d9d62c6787421cfcc4daf489a92 | src/util/define-properties.js | src/util/define-properties.js | export default function (obj, props) {
Object.keys(props).forEach(function (name) {
const desc = Object.getOwnPropertyDescriptor(obj, name);
if (!desc || desc.configurable) {
Object.defineProperty(obj, name, props[name]);
}
});
} | export default function (obj, props) {
Object.keys(props).forEach(function (name) {
const prop = props[name];
const descrptor = Object.getOwnPropertyDescriptor(obj, name);
const isDinosaurBrowser = name !== 'arguments' && name !== 'caller' && 'value' in prop;
const isConfigurable = !descrptor || descrptor.configurable;
if (isConfigurable) {
Object.defineProperty(obj, name, prop);
} else if (isDinosaurBrowser) {
obj[name] = prop.value;
}
});
}
| Make defining properties more robust for opera 12 or any browser that thinks things are non-configurable. | Make defining properties more robust for opera 12 or any browser that thinks things are non-configurable.
| JavaScript | mit | chrisdarroch/skatejs,skatejs/skatejs,chrisdarroch/skatejs,skatejs/skatejs,skatejs/skatejs | ---
+++
@@ -1,8 +1,14 @@
export default function (obj, props) {
Object.keys(props).forEach(function (name) {
- const desc = Object.getOwnPropertyDescriptor(obj, name);
- if (!desc || desc.configurable) {
- Object.defineProperty(obj, name, props[name]);
+ const prop = props[name];
+ const descrptor = Object.getOwnPropertyDescriptor(obj, name);
+ const isDinosaurBrowser = name !== 'arguments' && name !== 'caller' && 'value' in prop;
+ const isConfigurable = !descrptor || descrptor.configurable;
+
+ if (isConfigurable) {
+ Object.defineProperty(obj, name, prop);
+ } else if (isDinosaurBrowser) {
+ obj[name] = prop.value;
}
});
} |
117802c072678f1eab4fd12474b22e3d12226678 | GitEventChecker/routes/index.js | GitEventChecker/routes/index.js | var express = require('express'),
router = express.Router(),
net = require('net'),
fs = require('fs'),
socketPath = '/tmp/haproxy';
/* GET home page. */
router.post('/', function(req, res) {
// console.log(req.body);
// you can get commit information from request body
var client = net.createConnection(socketPath);
client.on('connect', function () {
client.write('show health');
});
client.on('data', function (data) {
winston.debug('DATA: '+data);
});
/*
fs.stat(socketPath, function (err) {
if (!err) {
fs.unlinkSync(socketPath);
return;
}
var unixServer = net.createServer(function (sock) {
sock.write('show health');
sock.on('data', function (data) {
winston.debug('DATA: '+data);
sock.destroy();
});
}).listen(socketPath);
});
*/
res.send('complete');
});
module.exports = router;
| var express = require('express'),
router = express.Router(),
net = require('net'),
fs = require('fs'),
socketPath = '/tmp/haproxy';
/* GET home page. */
router.post('/', function(req, res) {
// console.log(req.body);
// you can get commit information from request body
var client = net.createConnection(socketPath);
client.on('connect', function () {
client.write('show health');
client.on('data', function (data) {
winston.debug('DATA: '+data);
});
});
/*
fs.stat(socketPath, function (err) {
if (!err) {
fs.unlinkSync(socketPath);
return;
}
var unixServer = net.createServer(function (sock) {
sock.write('show health');
sock.on('data', function (data) {
winston.debug('DATA: '+data);
sock.destroy();
});
}).listen(socketPath);
});
*/
res.send('complete');
});
module.exports = router;
| Change command result receive part | Change command result receive part
| JavaScript | mit | PontoServerSide/LiveUpdater | ---
+++
@@ -14,12 +14,13 @@
client.on('connect', function () {
client.write('show health');
+
+ client.on('data', function (data) {
+ winston.debug('DATA: '+data);
+ });
});
- client.on('data', function (data) {
- winston.debug('DATA: '+data);
-
- });
+
/*
fs.stat(socketPath, function (err) { |
65b9ec6e02399db66b51a4a15f3c52fe2ee04b9a | src/app/main/main.controller.js | src/app/main/main.controller.js | class MainController {
constructor(_, $scope, $state, $log, SocketService) {
'ngInject';
this._ = _;
this.$log = $log;
this.$state = $state;
this.$scope = $scope;
this.SocketService = SocketService;
this.name = '';
this.password = '';
this.errorMessage = '';
this.processing = false;
if(this.SocketService.playerName !== '') {
this.name = this.SocketService.playerName;
}
}
canPlay() {
const _ = this._;
return !_.isEmpty(this.name) && this.password.length === 6;
}
play() {
this.processing = true;
this.SocketService.connect().then((result) => {
this.$log.log('success');
this.SocketService.extendedHandler = (message) => {
if (message.type === 'join_room') {
this.$log.log('join room message');
if (message.result === true) {
this.$state.go('lobby', {roomName: this.password});
} else {
this.$log.log('result is false');
this.errorMessage = message.reason;
this.processing = false;
this.$scope.$apply(() => {
this.$scope.errorMessage = this.errorMessage;
this.$scope.processing = this.processing;
})
}
}
};
this.SocketService.joinRoom(this.password, this.name);
});
}
}
export default MainController;
| class MainController {
constructor(_, $scope, $state, $log, SocketService) {
'ngInject';
this._ = _;
this.$log = $log;
this.$state = $state;
this.$scope = $scope;
this.SocketService = SocketService;
this.name = '';
this.password = '';
this.errorMessage = '';
this.processing = false;
if(this.SocketService.playerName !== '') {
this.name = this.SocketService.playerName;
}
}
canPlay() {
const _ = this._;
return !_.isEmpty(this.name) && this.password.length === 6;
}
play() {
this.processing = true;
this.SocketService.connect().then((result) => {
this.$log.log('success');
this.SocketService.extendedHandler = (message) => {
if (message.type === 'join_room') {
this.$log.log('join room message');
if (message.result === true) {
this.SocketService.game_id = message.game_id;
this.$state.go('lobby', {roomName: this.password});
} else {
this.$log.log('result is false');
this.errorMessage = message.reason;
this.processing = false;
this.$scope.$apply(() => {
this.$scope.errorMessage = this.errorMessage;
this.$scope.processing = this.processing;
})
}
}
};
this.SocketService.joinRoom(this.password, this.name);
});
}
}
export default MainController;
| Save game_id when joining game | Save game_id when joining game
| JavaScript | mit | hendryl/Famous-Places-Mobile,hendryl/Famous-Places-Mobile | ---
+++
@@ -33,6 +33,7 @@
this.$log.log('join room message');
if (message.result === true) {
+ this.SocketService.game_id = message.game_id;
this.$state.go('lobby', {roomName: this.password});
} else { |
b42d2aa652b987865d3a6f55f601b98f21a76137 | lib/assets/javascripts/builder/editor/layers/layer-content-views/legend/size/legend-size-types.js | lib/assets/javascripts/builder/editor/layers/layer-content-views/legend/size/legend-size-types.js | var _ = require('underscore');
var LegendTypes = require('builder/editor/layers/layer-content-views/legend/legend-types');
module.exports = [
{
value: LegendTypes.NONE,
tooltipTranslationKey: 'editor.legend.tooltips.style.none',
legendIcon: require('builder/editor/layers/layer-content-views/legend/carousel-icons/none.tpl'),
label: _t('editor.legend.types.none')
}, {
value: LegendTypes.BUBBLE,
tooltipTranslationKey: 'editor.legend.tooltips.style.bubble',
legendIcon: require('builder/editor/layers/layer-content-views/legend/carousel-icons/bubble.tpl'),
label: _t('editor.legend.types.bubble'),
isStyleCompatible: function (styleModel) {
var fill = styleModel.get('fill');
var stroke = styleModel.get('stroke');
var size;
if (!fill && !stroke || _.isEmpty(fill) && _.isEmpty(stroke)) return false;
size = fill && fill.size || stroke && stroke.size;
return size && size.attribute !== undefined;
}
}
];
| var _ = require('underscore');
var LegendTypes = require('builder/editor/layers/layer-content-views/legend/legend-types');
var styleHelper = require('builder/helpers/style');
module.exports = [
{
value: LegendTypes.NONE,
tooltipTranslationKey: 'editor.legend.tooltips.style.none',
legendIcon: require('builder/editor/layers/layer-content-views/legend/carousel-icons/none.tpl'),
label: _t('editor.legend.types.none')
}, {
value: LegendTypes.BUBBLE,
tooltipTranslationKey: 'editor.legend.tooltips.style.bubble',
legendIcon: require('builder/editor/layers/layer-content-views/legend/carousel-icons/bubble.tpl'),
label: _t('editor.legend.types.bubble'),
isStyleCompatible: function (styleModel) {
var size = styleHelper.getSize(styleModel);
if (size == null) return false;
return size && size.attribute !== undefined;
}
}
];
| Refactor bubble legend compatibility rules with styles for clarity | Refactor bubble legend compatibility rules with styles for clarity
| JavaScript | bsd-3-clause | CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb | ---
+++
@@ -1,5 +1,6 @@
var _ = require('underscore');
var LegendTypes = require('builder/editor/layers/layer-content-views/legend/legend-types');
+var styleHelper = require('builder/helpers/style');
module.exports = [
{
@@ -13,13 +14,9 @@
legendIcon: require('builder/editor/layers/layer-content-views/legend/carousel-icons/bubble.tpl'),
label: _t('editor.legend.types.bubble'),
isStyleCompatible: function (styleModel) {
- var fill = styleModel.get('fill');
- var stroke = styleModel.get('stroke');
- var size;
+ var size = styleHelper.getSize(styleModel);
+ if (size == null) return false;
- if (!fill && !stroke || _.isEmpty(fill) && _.isEmpty(stroke)) return false;
-
- size = fill && fill.size || stroke && stroke.size;
return size && size.attribute !== undefined;
}
} |
86e0ecae9697c9a7a10eddff320fb3679f5b22a2 | lib/api/search.js | lib/api/search.js | function select(database, options, callback) {
var results = [];
database.command('select', options, function(error, data) {
if (error) {
callback(error);
} else {
var columnNames = [];
var i, j;
for (j = 0; j < data[0][1].length; j++) {
columnNames[j] = data[0][1][j][0];
}
for (i = 0; i < data[0].length - 2; i++) {
var row = data[0][i + 2];
var object = {};
for (j = 0; j < columnNames.length; j++) {
object[columnNames[j]] = row[j];
}
results[i] = object;
}
callback(null, results);
}
});
}
exports.createHandler = function(database) {
return function(request, response) {
var domain = request.query.DomainName || '';
var expr = request.query.q;
var options = {
table: domain,
query: expr,
match_columns: 'address' // FIXME
};
select(database, options, function(error, data) {
if (error) {
throw error;
}
var info = {};
var result = {
rank: '-text_relevance', // FIXME
'match-expr': expr,
hits: {
found: data.length,
start: 0,
hit: data
},
info: info
};
response.json(result);
});
};
};
| var resolver = require('../resolver');
function select(database, options, callback) {
var results = [];
database.command('select', options, function(error, data) {
if (error) {
callback(error);
} else {
var columnNames = [];
var i, j;
for (j = 0; j < data[0][1].length; j++) {
columnNames[j] = data[0][1][j][0];
}
for (i = 0; i < data[0].length - 2; i++) {
var row = data[0][i + 2];
var object = {};
for (j = 0; j < columnNames.length; j++) {
object[columnNames[j]] = row[j];
}
results[i] = object;
}
callback(null, results);
}
});
}
exports.createHandler = function(database) {
return function(request, response) {
var domain = request.query.DomainName || '';
var expr = request.query.q;
var options = {
table: resolver.getTableNameFromDomain(domain),
query: expr,
match_columns: 'address' // FIXME
};
select(database, options, function(error, data) {
if (error) {
throw error;
}
var info = {};
var result = {
rank: '-text_relevance', // FIXME
'match-expr': expr,
hits: {
found: data.length,
start: 0,
hit: data
},
info: info
};
response.json(result);
});
};
};
| Use resolver to resolve the table name | Use resolver to resolve the table name
| JavaScript | mit | groonga/gcs,groonga/gcs | ---
+++
@@ -1,3 +1,5 @@
+var resolver = require('../resolver');
+
function select(database, options, callback) {
var results = [];
database.command('select', options, function(error, data) {
@@ -29,7 +31,7 @@
var domain = request.query.DomainName || '';
var expr = request.query.q;
var options = {
- table: domain,
+ table: resolver.getTableNameFromDomain(domain),
query: expr,
match_columns: 'address' // FIXME
}; |
52c04555ff2c5c7e4f41eaa3cd422e9d386dfdee | lib/index.js | lib/index.js |
var math = require('mathjs');
var ERROR_RESPONSE = 'I can\'t calculate that!';
module.exports = function(argv, response) {
var respBody;
try {
var expression = argv.slice(1).join('');
respBody = math.eval(expression).toString();
} catch(e) {
console.error(e);
respBody = ERROR_RESPONSE;
}
response.end(respBody);
}
|
var math = require('mathjs');
var ERROR_RESPONSE = 'I can\'t calculate that!';
module.exports = function(argv, response) {
var respBody = ERROR_RESPONSE;
try {
var expression = argv.slice(1).join('');
var result = math.eval(expression);
if (typeof result === 'function') {
console.error('Somehow got a function in a scalk eval');
}
else {
respBody = math.eval(expression).toString();
}
} catch(e) {
console.error(e);
}
response.end(respBody);
}
| Check for weird function results | Check for weird function results
| JavaScript | mit | elvinyung/scalk | ---
+++
@@ -4,14 +4,20 @@
var ERROR_RESPONSE = 'I can\'t calculate that!';
module.exports = function(argv, response) {
- var respBody;
+ var respBody = ERROR_RESPONSE;
try {
var expression = argv.slice(1).join('');
- respBody = math.eval(expression).toString();
+ var result = math.eval(expression);
+
+ if (typeof result === 'function') {
+ console.error('Somehow got a function in a scalk eval');
+ }
+ else {
+ respBody = math.eval(expression).toString();
+ }
} catch(e) {
console.error(e);
- respBody = ERROR_RESPONSE;
}
response.end(respBody); |
e2ede78fcf2076a40835909e9c5e01a76fdf1424 | js/markdown-toc.js | js/markdown-toc.js | /**
* User: powerumc
* Date: 2014. 5. 18.
*/
$(function() {
$(function () {
$.ajax({
url: "Requirements.md",
type: "GET",
success: function (data) {
var html = marked(data);
$("#preview").html(html);
var toc = $("#toc").tocify({
context: "#preview",
selectors: "h1, h2, h3, h4, h5, h6",
showEffect: "slideDown",
hideEffect: "slideUp",
scrollTo: 55,
theme: "jqueryui",
hashGenerator: "pretty",
highlightOffset: 40});
$("code").addClass("prettyprint");
prettyPrint();
$(document).ready(function () {
$('[data-toggle=offcanvas]').click(function () {
$('.row-offcanvas').toggleClass('active');
});
});
$("#title").text($("#preview h1:first").text());
}
});
});
});
| /**
* User: powerumc
* Date: 2014. 5. 18.
*/
$(function() {
$(function () {
$.ajax({
url: "Requirements.md",
type: "GET",
success: function (data) {
var html = marked(data);
$("#preview").html(html);
var toc = $("#toc").tocify({
context: "#preview",
selectors: "h1, h2, h3, h4",
showEffect: "slideDown",
hideEffect: "slideUp",
scrollTo: 55,
theme: "jqueryui",
hashGenerator: "pretty",
highlightOffset: 40});
$("code").addClass("prettyprint");
prettyPrint();
$(document).ready(function () {
$('[data-toggle=offcanvas]').click(function () {
$('.row-offcanvas').toggleClass('active');
});
});
$("#title").text($("#preview h1:first").text());
}
});
});
});
| Remove h5, h6 from tocify configuration parameters | Remove h5, h6 from tocify configuration parameters
| JavaScript | mit | ernstki/TeamMachine-Docs,ernstki/TeamMachine-Docs,ernstki/TeamMachine-Docs | ---
+++
@@ -15,7 +15,7 @@
var toc = $("#toc").tocify({
context: "#preview",
- selectors: "h1, h2, h3, h4, h5, h6",
+ selectors: "h1, h2, h3, h4",
showEffect: "slideDown",
hideEffect: "slideUp",
scrollTo: 55, |
71b158d08ea4ba715d3054da430c93e91dfcedbf | lib/index.js | lib/index.js | "use strict";
// Dependencies
const readJson = require("r-json")
, writeJson = require("w-json")
, mapO = require("map-o")
, ul = require("ul")
, findValue = require("find-value")
;
/**
* packy
* Sets the default fields in the package.json file.
*
* @name packy
* @function
* @param {String} path The path to the `package.json` file.
* @param {Object} def An object containing the fields that should be merged in the package.json.
* @param {Function} fn The callback function.
*/
module.exports = function packy(path, def, fn) {
readJson(path, (err, data) => {
if (err) { return fn(err); }
var merged = ul.deepMerge(def, data);
let merge = (current, parents) => {
return mapO(current, function (v, n) {
var p = parents.concat([n])
if (typeof v === "object") {
return merge(v, p);
}
if (typeof v === "function") {
return v(findValue(data, p.join(".")));
}
return v;
});
};
merge(merged, []);
writeJson(path, merged, fn);
});
};
| "use strict";
// Dependencies
const readJson = require("r-json")
, writeJson = require("w-json")
, mapO = require("map-o")
, ul = require("ul")
, findValue = require("find-value")
;
/**
* packy
* Sets the default fields in the package.json file.
*
* @name packy
* @function
* @param {String} path The path to the `package.json` file.
* @param {Object} def An object containing the fields that should be merged in the package.json.
* @param {Function} fn The callback function.
*/
module.exports = function packy(path, def, fn) {
readJson(path, (err, data) => {
if (err) { return fn(err); }
var merged = ul.deepMerge(def, data);
let merge = (current, parents) => {
return mapO(current, function (v, n) {
var p = parents.concat([n])
if (typeof v === "object") {
return merge(v, p);
}
if (typeof v === "function") {
return v(findValue(data, p.join(".")), data);
}
return v;
});
};
merge(merged, []);
writeJson(path, merged, fn);
});
};
| Send the data in the functions | Send the data in the functions
| JavaScript | mit | IonicaBizau/packy | ---
+++
@@ -29,7 +29,7 @@
return merge(v, p);
}
if (typeof v === "function") {
- return v(findValue(data, p.join(".")));
+ return v(findValue(data, p.join(".")), data);
}
return v;
}); |
3b53fc0ff2a2ecb022f35926d37a1a0f140ae640 | lib/utils.js | lib/utils.js | 'use strict';
module.exports = {
getAuthorizedAclMethods,
};
function getAuthorizedAclMethods(Model) {
let authorizedMethods = [];
let acls = Model.definition.settings.acls || [];
acls.forEach((acl) => {
if (acl.permission === 'ALLOW' && acl.property) {
if (!Array.isArray(acl.property)) {
acl.property = [acl.property];
}
authorizedMethods = authorizedMethods.concat(acl.property);
}
});
return authorizedMethods;
}
| 'use strict';
module.exports = {
getAuthorizedAclMethods,
};
function getAuthorizedAclMethods(Model) {
let authorizedMethods = [];
let acls = Model.settings.acls || [];
acls.forEach((acl) => {
if (acl.permission === 'ALLOW' && acl.property) {
if (!Array.isArray(acl.property)) {
acl.property = [acl.property];
}
authorizedMethods = authorizedMethods.concat(acl.property);
}
});
return authorizedMethods;
}
| Use Model.settings.acls to get the acls | Use Model.settings.acls to get the acls
Use `Model.settings.acls` to get the acls instead of `Model.definition.settings.acl`. `Model.definition` is an artifact created by datasource-juggler, but it wouldn't exists if you just use `loopback.createModel()`. | JavaScript | mit | devsu/loopback-setup-remote-methods-mixin | ---
+++
@@ -6,7 +6,7 @@
function getAuthorizedAclMethods(Model) {
let authorizedMethods = [];
- let acls = Model.definition.settings.acls || [];
+ let acls = Model.settings.acls || [];
acls.forEach((acl) => {
if (acl.permission === 'ALLOW' && acl.property) { |
ff5f0558be982d50aa74991051b676ec4c263482 | src/main/webapp/resources/js/pages/samples/edit.js | src/main/webapp/resources/js/pages/samples/edit.js | $(document).ready(function(){
/**
* Serialize metadata to json for submission
*/
$("#edit-form").submit(function(){
var metadata = {};
$("#other-metadata").find(".metadata-entry").each(function(){
var entry = $(this);
var key = entry.find(".metadata-key").val();
var value = entry.find(".metadata-value").val();
metadata[key] = value;
});
// paste the json into a hidden text field for submission
$("#metadata").val(JSON.stringify(metadata));
});
/**
* Remove a metadata term
*/
$(".delete-metadata").on("click", function(){
$(this).closest(".metadata-entry").remove();
});
/**
* Add a metadata term from the template
*/
$("#add-metadata").on("click", function(){
var newMetadata = $("#metadata-template").clone(true);
newMetadata.removeAttr("id");
$("#metadata-fields").append(newMetadata);
});
}); | $(document).ready(function(){
/**
* Serialize metadata to json for submission
*/
$("#edit-form").submit(function(){
var metadata = {};
$("#other-metadata").find(".metadata-entry").each(function(){
var entry = $(this);
var key = entry.find(".metadata-key").val();
var value = entry.find(".metadata-value").val();
metadata[key] = value;
});
// paste the json into a hidden text field for submission
if (Object.keys(metadata).length > 0) {
$("#metadata").val(JSON.stringify(metadata));
}
});
/**
* Remove a metadata term
*/
$(".delete-metadata").on("click", function(){
$(this).closest(".metadata-entry").remove();
});
/**
* Add a metadata term from the template
*/
$("#add-metadata").on("click", function(){
var newMetadata = $("#metadata-template").clone(true);
newMetadata.removeAttr("id");
$("#metadata-fields").append(newMetadata);
});
}); | Check to see if there is actually metadata to add. | Check to see if there is actually metadata to add.
| JavaScript | apache-2.0 | phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida | ---
+++
@@ -12,7 +12,9 @@
});
// paste the json into a hidden text field for submission
+ if (Object.keys(metadata).length > 0) {
$("#metadata").val(JSON.stringify(metadata));
+ }
});
/** |
494ecc627106cb7f9532f88db97b5d2f45fa23dc | src/main/webapp/components/BuilderDataTable.js | src/main/webapp/components/BuilderDataTable.js | import * as React from 'react';
const HEADERS = ['no', 'text', 'log'];
/**
* Table responsible for storing the data for a builder.
*
* @param {Object[]} props.buildSteps - The build steps for a given builder.
* @param {string} props.buildSteps[].step_number - The relative order of the build step.
* @param {string} props.buildSteps[].text - Output text related to the build step.
* @param {string} props.buildSteps[].log - A URL pointing to the log file.
*/
export const BuilderDataTable = props => {
return (
<table className='data-table'>
<thead>
<tr>{HEADERS.map(header => <th>{header}</th>)}</tr>
</thead>
<tbody>
{props.buildSteps.map(datapoint =>
<tr>
{HEADERS.forEach(header => <td>{datapoint[header]}</td>)}
</tr>
)}
</tbody>
</table>
);
}
| import * as React from 'react';
import {getFields} from './utils/getFields';
// The target fields to be extracted from each build step
// and displayed on each row.
const BUILD_STEP_FIELDS = ['step_number', 'text', 'logs'];
// Headers to display at the top of the table.
const HEADERS = ['no.', 'text', 'log'];
/**
* Table responsible for storing the data for a builder.
*
* @param {Object[]} props.buildSteps - The build steps for a given builder.
* @param {string} props.buildSteps[].step_number - The relative order of the build step.
* @param {string} props.buildSteps[].text - Output text related to the build step.
* @param {string} props.buildSteps[].logs - A URL pointing to the log file.
*/
export const BuilderDataTable = props => {
return (
<table className='data-table'>
<thead>
<tr>{HEADERS.map(header => <th>{header}</th>)}</tr>
</thead>
<tbody>
{props.buildSteps.map(datapoint =>
<tr>
{BUILD_STEP_FIELDS.forEach(field => <td>{datapoint[field]}</td>)}
</tr>
)}
</tbody>
</table>
);
}
| Read build step fields from array, Update comments | Read build step fields from array, Update comments
| JavaScript | apache-2.0 | googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020 | ---
+++
@@ -1,6 +1,12 @@
import * as React from 'react';
+import {getFields} from './utils/getFields';
-const HEADERS = ['no', 'text', 'log'];
+// The target fields to be extracted from each build step
+// and displayed on each row.
+const BUILD_STEP_FIELDS = ['step_number', 'text', 'logs'];
+
+// Headers to display at the top of the table.
+const HEADERS = ['no.', 'text', 'log'];
/**
* Table responsible for storing the data for a builder.
@@ -8,7 +14,7 @@
* @param {Object[]} props.buildSteps - The build steps for a given builder.
* @param {string} props.buildSteps[].step_number - The relative order of the build step.
* @param {string} props.buildSteps[].text - Output text related to the build step.
- * @param {string} props.buildSteps[].log - A URL pointing to the log file.
+ * @param {string} props.buildSteps[].logs - A URL pointing to the log file.
*/
export const BuilderDataTable = props => {
return (
@@ -19,7 +25,7 @@
<tbody>
{props.buildSteps.map(datapoint =>
<tr>
- {HEADERS.forEach(header => <td>{datapoint[header]}</td>)}
+ {BUILD_STEP_FIELDS.forEach(field => <td>{datapoint[field]}</td>)}
</tr>
)}
</tbody> |
a658a63b42244b826fbe2daee2b7509749681623 | src/dialog-action-directives.js | src/dialog-action-directives.js | function dialogClose() {
return {
restrict: 'EA',
require: '^dialog',
scope: {
returnValue: '=?return'
},
link(scope, element, attrs, dialog) {
element.on('click', function() {
scope.$apply(() => {
dialog.close(scope.returnValue);
});
});
}
};
}
function showDialogButton() {
return {
restrict: 'EA',
scope: {
dialogName: '@for',
modal: '=?',
anchorSelector: '@?anchor'
},
link(scope, element) {
scope.modal = scope.modal !== undefined ? scope.modal : true;
element.on('click', function() {
let dialog = dialogRegistry.getDialog(scope.dialogName);
if (dialog) {
dialog.show(scope.modal, document.querySelector(scope.anchorSelector));
}
});
}
};
}
export {dialogClose, showDialogButton}; | function dialogClose() {
return {
restrict: 'EA',
require: '^dialog',
scope: {
returnValue: '=?return'
},
link(scope, element, attrs, dialog) {
element.on('click', function() {
scope.$apply(() => {
dialog.close(scope.returnValue);
});
});
}
};
}
function showDialogButton(dialogRegistry) {
return {
restrict: 'EA',
scope: {
dialogName: '@for',
modal: '=?',
anchorSelector: '@?anchor'
},
link(scope, element) {
scope.modal = scope.modal !== undefined ? scope.modal : true;
element.on('click', function() {
let dialog = dialogRegistry.getDialog(scope.dialogName);
if (dialog) {
dialog.show(scope.modal, document.querySelector(scope.anchorSelector));
}
});
}
};
}
export {dialogClose, showDialogButton}; | Fix injection in show dialog button directive | Fix injection in show dialog button directive
| JavaScript | mit | olympicsoftware/oly-dialog,olympicsoftware/oly-dialog | ---
+++
@@ -15,7 +15,7 @@
};
}
-function showDialogButton() {
+function showDialogButton(dialogRegistry) {
return {
restrict: 'EA',
scope: { |
5bbc62fe150789c63b557fab36b56781ba329f0b | app/components/Feed/context.js | app/components/Feed/context.js | // @flow
import React from 'react';
import { Link } from 'react-router';
import type { AggregatedActivity } from './types';
export function lookupContext(
aggregatedActivity: AggregatedActivity,
key: string
) {
return aggregatedActivity.context[key];
}
export const contextRender = {
'users.user': (context: Object) => (
<Link to={`/users/${context.username}/`}>
{`${context.firstName} ${context.lastName}`}
</Link>
),
'events.event': (context: Object) => (
<Link to={`/events/${context.id}/`}>{`${context.title}`}</Link>
),
'meetings.meetinginvitation': (context: Object) => (
<Link to={`/meetings/${context.meeting.id}/`}>{context.meeting.title}</Link>
),
'articles.article': (context: Object) => (
<Link to={`/articles/${context.id}/`}>{context.title}</Link>
),
'notifications.announcement': (context: Object) => <p>{context.message}</p>
};
| // @flow
import React from 'react';
import { Link } from 'react-router';
import type { AggregatedActivity } from './types';
export function lookupContext(
aggregatedActivity: AggregatedActivity,
key: string
) {
return aggregatedActivity.context[key];
}
export const contextRender = {
'users.user': (context: Object) => (
<Link to={`/users/${context.username}/`}>
{`${context.firstName} ${context.lastName}`}
</Link>
),
'events.event': (context: Object) => (
<Link to={`/events/${context.id}/`}>{`${context.title}`}</Link>
),
'meetings.meetinginvitation': (context: Object) => (
<Link to={`/meetings/${context.meeting.id}/`}>{context.meeting.title}</Link>
),
'articles.article': (context: Object) => (
<Link to={`/articles/${context.id}/`}>{context.title}</Link>
),
'notifications.announcement': (context: Object) => <p>{context.message}</p>,
'gallery.gallerypicture': (context: Object) => (
<Link to={`/photos/${context.gallery.id}/picture/${context.id}`}>
{context.gallery.title}-#{context.id}
</Link>
)
};
| Add support for notifications on gallery.gallerypicture | Add support for notifications on gallery.gallerypicture
| JavaScript | mit | webkom/lego-webapp,webkom/lego-webapp,webkom/lego-webapp | ---
+++
@@ -25,5 +25,10 @@
'articles.article': (context: Object) => (
<Link to={`/articles/${context.id}/`}>{context.title}</Link>
),
- 'notifications.announcement': (context: Object) => <p>{context.message}</p>
+ 'notifications.announcement': (context: Object) => <p>{context.message}</p>,
+ 'gallery.gallerypicture': (context: Object) => (
+ <Link to={`/photos/${context.gallery.id}/picture/${context.id}`}>
+ {context.gallery.title}-#{context.id}
+ </Link>
+ )
}; |
c0002c7f3a62e90b62e9f821b4f13c80bdbae324 | chat.js | chat.js | var chat = angular.module('chat', ['btford.socket-io']);
var channel = new Channel('hellas');
var me = null;
chat.factory('chatServer', function (socketFactory) {
var url = '/';
if (location.port != '') {
url = ':' + location.port + '/';
}
return socketFactory({ioSocket: io.connect(url)})
});
chat.controller('MessagesCtrl', MessagesCtrl);
chat.controller('NicklistCtrl', NicklistCtrl);
chat.run(function(chatServer) {
var nickname;
if (!localStorage['nickname']) {
nickname = prompt('Πληκτρολόγησε το όνομά σου:');
localStorage['nickname'] = nickname;
}
else {
nickname = localStorage['nickname'];
}
me = new User(nickname);
$('#chat').show();
chatServer.emit('register', me);
chatServer.emit('join', channel);
});
| var chat = angular.module('chat', ['btford.socket-io']);
var channel = new Channel('hellas');
var me = null;
chat.factory('chatServer', function (socketFactory) {
var url = '/';
if (location.port != '') {
url = ':' + location.port + '/';
}
return socketFactory({ioSocket: io.connect(url)})
});
chat.controller('MessagesCtrl', MessagesCtrl);
chat.controller('NicklistCtrl', NicklistCtrl);
chat.run(function(chatServer) {
var nickname;
if (!localStorage['nickname']) {
nickname = prompt('Πληκτρολόγησε το όνομά σου:');
localStorage['nickname'] = nickname;
}
else {
nickname = localStorage['nickname'];
}
me = new User(nickname);
$('#chat').show();
chatServer.on('connect', function() {
chatServer.emit('register', me);
chatServer.emit('join', channel);
});
});
| Join channel and register on reconnect | Join channel and register on reconnect
| JavaScript | mit | gtklocker/ting,odyvarv/ting-1,odyvarv/ting-1,sirodoht/ting,gtklocker/ting,odyvarv/ting-1,dionyziz/ting,dionyziz/ting,mbalamat/ting,sirodoht/ting,sirodoht/ting,mbalamat/ting,mbalamat/ting,dionyziz/ting,gtklocker/ting,VitSalis/ting,gtklocker/ting,dionyziz/ting,sirodoht/ting,VitSalis/ting,VitSalis/ting,odyvarv/ting-1,VitSalis/ting,mbalamat/ting | ---
+++
@@ -30,6 +30,8 @@
$('#chat').show();
- chatServer.emit('register', me);
- chatServer.emit('join', channel);
+ chatServer.on('connect', function() {
+ chatServer.emit('register', me);
+ chatServer.emit('join', channel);
+ });
}); |
3f855c3b1e7b0a6ce546fa9e422fd478a5eb1f1c | modules/recent-activity/server/controllers/recent-activity.controller.js | modules/recent-activity/server/controllers/recent-activity.controller.js | 'use strict';
// =========================================================================
//
// Controller for orgs
//
// =========================================================================
var path = require('path');
var DBModel = require (path.resolve('./modules/core/server/controllers/core.dbmodel.controller'));
var _ = require ('lodash');
var mongoose = require ('mongoose');
var Model = mongoose.model ('RecentActivity');
module.exports = DBModel.extend ({
name : 'RecentActivity',
plural : 'recentactivities',
// -------------------------------------------------------------------------
//
// get activities which are active, sorted by Public Comment period, then
// subsorted on type
//
// -------------------------------------------------------------------------
getRecentActivityActive: function () {
var p = Model.find ({active:true},
{},
{}).limit(10); // Quick hack to limit the front page loads.
return new Promise (function (resolve, reject) {
p.then(function (doc) {
var pcSort = _.partition(doc, { type: "Public Comment Period" });
var pcp = pcSort[0];
var news = pcSort[1];
var pcSortPriority = _.sortBy(pcp, function (o) {
return o.priority;
});
var newsSortPriority = _.sortBy(news, function (o) {
return o.priority;
});
resolve(pcSortPriority.concat(newsSortPriority));
}, reject);
});
}
});
| 'use strict';
// =========================================================================
//
// Controller for orgs
//
// =========================================================================
var path = require('path');
var DBModel = require (path.resolve('./modules/core/server/controllers/core.dbmodel.controller'));
var _ = require ('lodash');
var mongoose = require ('mongoose');
var Model = mongoose.model ('RecentActivity');
module.exports = DBModel.extend ({
name : 'RecentActivity',
plural : 'recentactivities',
// -------------------------------------------------------------------------
//
// get activities which are active, sorted by Public Comment period, then
// subsorted on type
//
// -------------------------------------------------------------------------
getRecentActivityActive: function () {
var p = Model.find ({active:true},
{},
{}).sort({dateUpdated: -1}).limit(10); // Quick hack to limit the front page loads.
return new Promise (function (resolve, reject) {
p.then(function (doc) {
var pcSort = _.partition(doc, { type: "Public Comment Period" });
var pcp = pcSort[0];
var news = pcSort[1];
var pcSortPriority = _.sortBy(pcp, function (o) {
return o.priority;
});
var newsSortPriority = _.sortBy(news, function (o) {
return o.priority;
});
resolve(pcSortPriority.concat(newsSortPriority));
}, reject);
});
}
});
| Fix news & announcements to be reverse sorted. | Fix news & announcements to be reverse sorted.
| JavaScript | apache-2.0 | logancodes/esm-server,logancodes/esm-server,logancodes/esm-server | ---
+++
@@ -22,7 +22,7 @@
getRecentActivityActive: function () {
var p = Model.find ({active:true},
{},
- {}).limit(10); // Quick hack to limit the front page loads.
+ {}).sort({dateUpdated: -1}).limit(10); // Quick hack to limit the front page loads.
return new Promise (function (resolve, reject) {
p.then(function (doc) {
var pcSort = _.partition(doc, { type: "Public Comment Period" }); |
9d1ce946bb52111a738fac77d1512f0c4127f4c3 | src/pages/page-2.js | src/pages/page-2.js | import React from "react"
import Link from "gatsby-link"
import Helmet from "react-helmet"
export default class Index extends React.Component {
render() {
return (
<div>
<h1>Hi people</h1>
<p>Welcome to page 2</p>
<Link to="/">Go back to the homepage</Link>
</div>
)
}
}
| import React from "react"
import Link from "gatsby-link"
import Helmet from "react-helmet"
export default class Page2 extends React.Component {
render() {
return (
<div>
<h1>Hi people</h1>
<p>Welcome to page 2</p>
<Link to="/">Go back to the homepage</Link>
</div>
)
}
}
| Use more sensible class name | Use more sensible class name
| JavaScript | mit | TasGuerciMaia/tasguercimaia.github.io,benruehl/gatsby-kruemelkiste | ---
+++
@@ -2,7 +2,7 @@
import Link from "gatsby-link"
import Helmet from "react-helmet"
-export default class Index extends React.Component {
+export default class Page2 extends React.Component {
render() {
return (
<div> |
b2a119f8d4685e96a2bf338ab1a933b9bba13b27 | unit/poller/index.js | unit/poller/index.js | var mqtt = require('mqtt');
var SensorTag = require('sensortag');
var client = mqtt.connect('mqtt://tree:tree@m11.cloudmqtt.com:19539');
client.on('connect', function () {
client.publish('sensor', "foo");
SensorTag.discoverAll(function (sensorTag) {
console.log('Sensor found: ' + sensorTag);
sensorTag.connectAndSetUp(function (error) {
if (error)
console.log("setup:" + error);
setTimeout(function() {
sensorTag.enableIrTemperature(function (error) {
if (error)
console.log("enableIrTemp" + error);
setInterval(function() {
console.log('polling');
sensorTag.readIrTemperature(function (error, objectTemperature, ambientTemperature) {
console.log(ambientTemperature);
});
}, 1000);
});
}, 3000);
});
});
});
| var mqtt = require('mqtt');
var SensorTag = require('sensortag');
var client = mqtt.connect('mqtt://tree:tree@m11.cloudmqtt.com:19539');
client.on('connect', function () {
SensorTag.discoverAll(function (sensorTag) {
console.log('Sensor found: ' + sensorTag);
sensorTag.connectAndSetUp(function (error) {
if (error)
console.log("setup:" + error);
setTimeout(function() {
sensorTag.enableHumidity(function (error) {
if (error)
console.log("enableIrTemp" + error);
setInterval(function() {
var data = {
'uuid': 0,
'temperature': 0,
'humidity': 0
};
console.log('polling');
sensorTag.readHumidity(function (error, temperature, humidity) {
console.log("temp: " + temperature);
data['temperature'] = temperature;
console.log("humidity :" + humidity);
data['humidity'] = humidity;
client.publish('sensor', JSON.stringify(data));
console.log(JSON.stringify(data));
});
}, 6000);
});
}, 3000);
});
});
});
| Send temperature, humidity to server | Send temperature, humidity to server
| JavaScript | mit | jphacks/KB_12,jphacks/KB_12,jphacks/KB_12,jphacks/KB_12,mikoim/mori,mikoim/mori,jphacks/KB_12,mikoim/mori,mikoim/mori,mikoim/mori | ---
+++
@@ -4,22 +4,31 @@
var client = mqtt.connect('mqtt://tree:tree@m11.cloudmqtt.com:19539');
client.on('connect', function () {
- client.publish('sensor', "foo");
SensorTag.discoverAll(function (sensorTag) {
console.log('Sensor found: ' + sensorTag);
sensorTag.connectAndSetUp(function (error) {
if (error)
console.log("setup:" + error);
setTimeout(function() {
- sensorTag.enableIrTemperature(function (error) {
+ sensorTag.enableHumidity(function (error) {
if (error)
console.log("enableIrTemp" + error);
setInterval(function() {
+ var data = {
+ 'uuid': 0,
+ 'temperature': 0,
+ 'humidity': 0
+ };
console.log('polling');
- sensorTag.readIrTemperature(function (error, objectTemperature, ambientTemperature) {
- console.log(ambientTemperature);
+ sensorTag.readHumidity(function (error, temperature, humidity) {
+ console.log("temp: " + temperature);
+ data['temperature'] = temperature;
+ console.log("humidity :" + humidity);
+ data['humidity'] = humidity;
+ client.publish('sensor', JSON.stringify(data));
+ console.log(JSON.stringify(data));
});
- }, 1000);
+ }, 6000);
});
}, 3000);
}); |
da5e854055509992103561f5134dea0ef094bec9 | test/components/Posts.spec.js | test/components/Posts.spec.js | import { expect } from 'chai';
import { shallow } from 'enzyme';
import React from 'react';
import Posts from '../../src/js/components/Posts';
import PostPreview from '../../src/js/components/PostPreview';
describe('<Posts/>', () => {
const posts = [
{ id: 0, title: 'First Post' },
{ id: 1, title: 'Second Post' },
];
it('renders list of posts', () => {
const result = shallow(<Posts posts={posts} />);
expect(result.find(PostPreview).length).to.eq(2);
});
it('renders message when there are no posts', () => {
const result = shallow(<Posts posts={[]} />);
expect(result.contains(<p>No posts found.</p>)).to.eq(true);
});
});
| import { expect } from 'chai';
import { shallow, mount } from 'enzyme';
import React from 'react';
import { MemoryRouter as Router } from 'react-router-dom';
import Posts from '../../src/js/components/Posts';
import PostPreview from '../../src/js/components/PostPreview';
describe('<Posts/>', () => {
const posts = [
{ id: 0, title: 'First Post', tags: ['js'] },
{ id: 1, title: 'Second Post' },
];
it('renders list of posts', () => {
const result = shallow(<Posts posts={posts} />);
expect(result.find(PostPreview).length).to.eq(2);
});
it('passes tag to <PostPreview>', () => {
const result = mount(<Router><Posts tag="js" posts={posts} /></Router>);
expect(result.find('.tags__tag_active').text()).to.eq('js');
});
it('renders message when there are no posts', () => {
const result = shallow(<Posts posts={[]} />);
expect(result.contains(<p>No posts found.</p>)).to.eq(true);
});
});
| Test passing tag to <Posts> | Test passing tag to <Posts>
| JavaScript | mit | slavapavlutin/pavlutin-node,slavapavlutin/pavlutin-node | ---
+++
@@ -1,12 +1,13 @@
import { expect } from 'chai';
-import { shallow } from 'enzyme';
+import { shallow, mount } from 'enzyme';
import React from 'react';
+import { MemoryRouter as Router } from 'react-router-dom';
import Posts from '../../src/js/components/Posts';
import PostPreview from '../../src/js/components/PostPreview';
describe('<Posts/>', () => {
const posts = [
- { id: 0, title: 'First Post' },
+ { id: 0, title: 'First Post', tags: ['js'] },
{ id: 1, title: 'Second Post' },
];
@@ -15,6 +16,11 @@
expect(result.find(PostPreview).length).to.eq(2);
});
+ it('passes tag to <PostPreview>', () => {
+ const result = mount(<Router><Posts tag="js" posts={posts} /></Router>);
+ expect(result.find('.tags__tag_active').text()).to.eq('js');
+ });
+
it('renders message when there are no posts', () => {
const result = shallow(<Posts posts={[]} />);
expect(result.contains(<p>No posts found.</p>)).to.eq(true); |
37eae0ebce6e466319ac991a2b810b7a260ffb7d | src/views/Browse.js | src/views/Browse.js | import React from 'react';
import { connect } from 'react-redux';
import { fetchRecipes, setSearchTerm } from '../actions/';
import Header from '../components/Header';
import SearchHeader from '../components/SearchHeader';
import Card from '../components/Card';
class Browse extends React.Component {
constructor(props) {
super(props);
this.setSearchTerm = this.setSearchTerm.bind(this);
}
componentDidMount() {
if (this.props.recipes.length === 0) {
this.props.dispatchFetchRecipes();
}
}
setSearchTerm(e) {
this.props.dispatchSetSearchTerm(e.target.value);
}
render() {
return (
<main className="browse">
<Header page={'browse'}>
<SearchHeader
handleSearchTermChange={this.setSearchTerm}
searchTerm={this.props.searchTerm}
page={'browse'}
/>
</Header>
<div className="container">
<div className="row">
{this.props.recipes.map(recipe => <Card
key={recipe.id}
name={recipe.name}
desc={recipe.desc}
img={recipe.img}
id={recipe.id}
/>)}
</div>
</div>
</main>
);
}
}
const mapStateToProps = state => ({
recipes: state.recipes,
searchTerm: state.searchTerm
});
export default connect(
mapStateToProps,
{
dispatchFetchRecipes: fetchRecipes,
dispatchSetSearchTerm: setSearchTerm
}
)(Browse);
| import React from 'react';
import { connect } from 'react-redux';
import { fetchRecipes, setSearchTerm } from '../actions/';
import Header from '../components/Header';
import SearchHeader from '../components/SearchHeader';
import Card from '../components/Card';
class Browse extends React.Component {
constructor(props) {
super(props);
this.setSearchTerm = this.setSearchTerm.bind(this);
}
componentDidMount() {
if (this.props.recipes.length === 0) {
this.props.dispatchFetchRecipes();
}
}
setSearchTerm(e) {
this.props.dispatchSetSearchTerm(e.target.value);
}
render() {
return (
<main className="browse">
<Header page={'browse'}>
<SearchHeader
handleSearchTermChange={this.setSearchTerm}
searchTerm={this.props.searchTerm}
page={'browse'}
/>
</Header>
<div className="container">
{this.props.recipes.map(recipe => <Card
key={recipe.id}
name={recipe.name}
desc={recipe.desc}
img={recipe.img}
id={recipe.id}
/>)}
</div>
</main>
);
}
}
const mapStateToProps = state => ({
recipes: state.recipes,
searchTerm: state.searchTerm
});
export default connect(
mapStateToProps,
{
dispatchFetchRecipes: fetchRecipes,
dispatchSetSearchTerm: setSearchTerm
}
)(Browse);
| Change the browse page layout temporarily | Change the browse page layout temporarily
| JavaScript | mit | hihuz/meny,hihuz/meny | ---
+++
@@ -29,15 +29,13 @@
/>
</Header>
<div className="container">
- <div className="row">
- {this.props.recipes.map(recipe => <Card
- key={recipe.id}
- name={recipe.name}
- desc={recipe.desc}
- img={recipe.img}
- id={recipe.id}
- />)}
- </div>
+ {this.props.recipes.map(recipe => <Card
+ key={recipe.id}
+ name={recipe.name}
+ desc={recipe.desc}
+ img={recipe.img}
+ id={recipe.id}
+ />)}
</div>
</main>
); |
930326fafe7a14b472fece345572c184de542a6e | lib/auths/index.js | lib/auths/index.js | const gatherResources = require('../utils/gatherResources')
const auth = [
'options',
'token'
]
module.exports = gatherResources(auth, __dirname)
| const gatherResources = require('../utils/gatherResources')
const auth = [
'options',
'token',
'oauth2',
'couchdb'
]
module.exports = gatherResources(auth, __dirname)
| Include oauth2 and couchdb auth in `integreat.auths()` | Include oauth2 and couchdb auth in `integreat.auths()`
| JavaScript | isc | kjellmorten/integreat | ---
+++
@@ -2,7 +2,9 @@
const auth = [
'options',
- 'token'
+ 'token',
+ 'oauth2',
+ 'couchdb'
]
module.exports = gatherResources(auth, __dirname) |
1563437daf745c6ba5dcc3b732241c7a9b9c523b | transformers/lib/child_proc.js | transformers/lib/child_proc.js | var spawn = require('child_process').spawn;
var which = require('which');
module.exports.transformer = childProcTransformer;
module.exports.transform = childProcTransform;
function childProcTransformer(prog, transformer) {
var cmd = which.sync(prog);
if (!cmd) return noopTransformer;
return subTransformer;
function subTransformer(options) {
options.cmd = cmd;
return transformer(options);
}
}
function childProcTransform(argv, stream, callback) {
var child = spawn(argv[0], argv.slice(1));
if (stream) {
stream.pipe(child.stdin);
}
child.on('exit', exited);
child.on('error', passError);
child.stdin.on('error', passError);
function exited(code) {
if (code !== 0) {
console.error(
'child exited abnormally (code %j): %s',
code, argv.join(' ') // TODO: quote better
);
}
}
function passError(err) {
if (err.errno !== 'EPIPE') {
child.stdout.emit('error', err);
}
}
callback(null, child.stdout);
}
function noopTransformer() {
return noopTransform;
}
function noopTransform(info, stream, callback) {
callback(null);
}
| var spawn = require('child_process').spawn;
var _which = require('which');
function which (prog) {
try {
return _which.sync(prog);
} catch (err) {
if (err.message === 'not found: ' + prog) {
return null;
} else {
throw err;
}
}
}
module.exports.transformer = childProcTransformer;
module.exports.transform = childProcTransform;
function childProcTransformer(prog, transformer) {
var cmd = which(prog);
if (!cmd) return noopTransformer;
return subTransformer;
function subTransformer(options) {
options.cmd = cmd;
return transformer(options);
}
}
function childProcTransform(argv, stream, callback) {
var child = spawn(argv[0], argv.slice(1));
if (stream) {
stream.pipe(child.stdin);
}
child.on('exit', exited);
child.on('error', passError);
child.stdin.on('error', passError);
function exited(code) {
if (code !== 0) {
console.error(
'child exited abnormally (code %j): %s',
code, argv.join(' ') // TODO: quote better
);
}
}
function passError(err) {
if (err.errno !== 'EPIPE') {
child.stdout.emit('error', err);
}
}
callback(null, child.stdout);
}
function noopTransformer() {
return noopTransform;
}
function noopTransform(info, stream, callback) {
callback(null);
}
| Correct which to not through... | Correct which to not through...
...this was the whole point of it.
| JavaScript | mit | jcorbin/lesspipe.js | ---
+++
@@ -1,11 +1,23 @@
var spawn = require('child_process').spawn;
-var which = require('which');
+var _which = require('which');
+
+function which (prog) {
+ try {
+ return _which.sync(prog);
+ } catch (err) {
+ if (err.message === 'not found: ' + prog) {
+ return null;
+ } else {
+ throw err;
+ }
+ }
+}
module.exports.transformer = childProcTransformer;
module.exports.transform = childProcTransform;
function childProcTransformer(prog, transformer) {
- var cmd = which.sync(prog);
+ var cmd = which(prog);
if (!cmd) return noopTransformer;
return subTransformer;
function subTransformer(options) { |
098185af723d83e2ace531d0644b1cda414d8bcd | lib/tasks/serve.js | lib/tasks/serve.js | 'use strict';
module.exports = function(gulp, $, config, _) {
var proxyTarget = _.get(config, 'proxy.url', config.consts.proxy.url);
var proxyPrefixes = _.get(config, 'proxy.prefixes', config.consts.proxy.prefixes);
var proxy = $.httpProxy.createProxyServer({
target: proxyTarget
});
function isProxiedPrefix(url) {
return _.some(proxyPrefixes, function (expression) {
return expression.test(url);
});
}
function proxyMiddleware(req, res, next) {
if (isProxiedPrefix(req.url)) {
proxy.web(req, res, function (err) {
next(err);
});
} else {
next();
}
}
function server(filesToWatch, filesToServe) {
return $.browserSync({
files: filesToWatch,
notify: false,
server: {
baseDir: filesToServe,
middleware: proxyMiddleware
}
});
}
gulp.task('serve', function () {
return server([
config.paths.app.base,
config.paths.build.tmp.base,
], _.union([
config.paths.build.tmp.base,
config.paths.base
], config.paths.app.base));
});
gulp.task('serve:dist', ['build'], function () {
return server(config.paths.build.dist.base, config.paths.build.dist.base);
});
};
| 'use strict';
module.exports = function(gulp, $, config, _) {
var proxyTarget = _.get(config, 'proxy.url', config.consts.proxy.url);
var proxyPrefixes = _.get(config, 'proxy.prefixes', config.consts.proxy.prefixes);
var proxy = $.httpProxy.createProxyServer({
target: proxyTarget
});
function isProxiedPrefix(url) {
return _.some(proxyPrefixes, function (expression) {
return expression.test(url);
});
}
function proxyMiddleware(req, res, next) {
if (isProxiedPrefix(req.url)) {
proxy.web(req, res, function (err) {
next(err);
});
} else {
next();
}
}
function server(filesToWatch, filesToServe) {
return $.browserSync({
files: filesToWatch,
notify: false,
server: {
baseDir: filesToServe,
middleware: config.consts.browserSync.middleware || proxyMiddlewares
}
});
}
gulp.task('serve', function () {
return server([
config.paths.app.base,
config.paths.build.tmp.base,
], _.union([
config.paths.build.tmp.base,
config.paths.base
], config.paths.app.base));
});
gulp.task('serve:dist', ['build'], function () {
return server(config.paths.build.dist.base, config.paths.build.dist.base);
});
};
| Set middleware function to be definable | Set middleware function to be definable
| JavaScript | mit | akullpp/akGulp,akullpp/myGulp | ---
+++
@@ -29,7 +29,7 @@
notify: false,
server: {
baseDir: filesToServe,
- middleware: proxyMiddleware
+ middleware: config.consts.browserSync.middleware || proxyMiddlewares
}
});
} |
2223e83d7ea673bad92f89df32da4ee72bdac360 | backend/src/routes/users/index.js | backend/src/routes/users/index.js | const express = require('express')
const ERRORS = require('../../errors')
const User = require('../../models/User')
const utils = require('../../utils')
const router = express.Router()
router.post('/', register)
function register(req, res, next) {
const { body: { username, password } } = req
if (!username || !password) {
next(ERRORS.MISSING_PARAMETERS(['username', 'password']))
} else {
User.register(username, password)
.then(user => ({
id: user.id,
username: user.username,
token: utils.genToken(user.id),
createdAt: user.createdAt
}))
.then(data => {
res.status(201)
res.json(data)
})
.catch(err => next(ERRORS.REGISTRATION_FAILED(err)))
}
}
module.exports = router
| const express = require('express')
const ERRORS = require('../../errors')
const User = require('../../models/User')
const utils = require('../../utils')
const router = express.Router()
/*
* Endpoint: [POST] /users
* Header:
* <None>
* Body: {username, password}
* Response:
* 201 (JSON) The created user with a valid auth token
* 400 Bad Request: invalid parameters
*/
router.post('/', register)
function register(req, res, next) {
const { body: { username, password } } = req
if (!username || !password) {
next(ERRORS.MISSING_PARAMETERS(['username', 'password']))
} else {
User.register(username, password)
.then(user => ({
id: user.id,
username: user.username,
token: utils.genToken(user.id),
createdAt: user.createdAt
}))
.then(data => {
res.status(201)
res.json(data)
})
.catch(err => next(ERRORS.REGISTRATION_FAILED(err)))
}
}
/*
* Endpoint: [GET] /users/authenticate?username:username
* Header:
* Authorization: password=<password>
* Body: <None>
* Response:
* 200 (JSON) A valid auth token
* 403 Unauthorized: Wrong credentials
*/
router.get('/authenticate', authenticate)
function authenticate(req, res) {
res.json({ notImplemented: "yet" })
}
module.exports = router
| Add meta-comments + backbone of authenticate method | Add meta-comments + backbone of authenticate method
| JavaScript | mit | 14Plumes/Hexode,KtorZ/Hexode,KtorZ/Hexode,14Plumes/Hexode,KtorZ/Hexode,14Plumes/Hexode | ---
+++
@@ -4,6 +4,16 @@
const utils = require('../../utils')
const router = express.Router()
+
+/*
+ * Endpoint: [POST] /users
+ * Header:
+ * <None>
+ * Body: {username, password}
+ * Response:
+ * 201 (JSON) The created user with a valid auth token
+ * 400 Bad Request: invalid parameters
+ */
router.post('/', register)
function register(req, res, next) {
const { body: { username, password } } = req
@@ -25,4 +35,19 @@
}
}
+/*
+ * Endpoint: [GET] /users/authenticate?username:username
+ * Header:
+ * Authorization: password=<password>
+ * Body: <None>
+ * Response:
+ * 200 (JSON) A valid auth token
+ * 403 Unauthorized: Wrong credentials
+ */
+router.get('/authenticate', authenticate)
+function authenticate(req, res) {
+ res.json({ notImplemented: "yet" })
+}
+
+
module.exports = router |
3b3f61946d2c8bc79fbccc171035612293209c58 | functions/strings/hex2bin.js | functions/strings/hex2bin.js | function hex2bin(s) {
// discuss at: http://phpjs.org/functions/hex2bin/
// original by: Dumitru Uzun (http://duzun.me)
// example 1: bin2hex('44696d61');
// returns 1: 'Dima'
// example 2: bin2hex('00');
// returns 2: '\x00'
var ret = [], i = 0, l;
s += '';
for ( l = s.length ; i < l; i+=2 ) {
ret.push(parseInt(s.substr(i, 2), 16));
}
return String.fromCharCode.apply(String, ret);
}
| function hex2bin(s) {
// discuss at: http://phpjs.org/functions/hex2bin/
// original by: Dumitru Uzun (http://duzun.me)
// example 1: bin2hex('44696d61');
// returns 1: 'Dima'
// example 2: bin2hex('00');
// returns 2: '\x00'
// example 3: bin2hex('2f1q')
// returns 3: false
var ret = [], i = 0, l;
s += '';
for ( l = s.length ; i < l; i+=2 ) {
var c = parseInt(s.substr(i, 1), 16);
var k = parseInt(s.substr(i+1, 1), 16);
if(isNaN(c) || isNaN(k)) return false;
ret.push( (c << 4) | k );
}
return String.fromCharCode.apply(String, ret);
}
| Return FALSE if non-hex char detected | Return FALSE if non-hex char detected
Return FALSE if non-hex char detected - same behaviour as PHP version of hex2bin(). | JavaScript | mit | revanthpobala/phpjs,praveenscience/phpjs,strrife/phpjs,davidgruebl/phpjs,w35l3y/phpjs,VicAMMON/phpjs,Mazbaul/phpjs,J2TeaM/phpjs,cigraphics/phpjs,praveenscience/phpjs,janschoenherr/phpjs,VicAMMON/phpjs,ajenkul/phpjs,cigraphics/phpjs,VicAMMON/phpjs,ajenkul/phpjs,mojaray2k/phpjs,imshibaji/phpjs,Mazbaul/phpjs,FlorinDragotaExpertvision/phpjs,revanthpobala/phpjs,kvz/phpjs,FlorinDragotaExpertvision/phpjs,revanthpobala/phpjs,hirak/phpjs,Mazbaul/phpjs,praveenscience/phpjs,kvz/phpjs,w35l3y/phpjs,imshibaji/phpjs,davidgruebl/phpjs,w35l3y/phpjs,FlorinDragotaExpertvision/phpjs,janschoenherr/phpjs,w35l3y/phpjs,cigraphics/phpjs,MartinReidy/phpjs,kvz/phpjs,mojaray2k/phpjs,imshibaji/phpjs,cigraphics/phpjs,hirak/phpjs,J2TeaM/phpjs,davidgruebl/phpjs,praveenscience/phpjs,imshibaji/phpjs,MartinReidy/phpjs,Mazbaul/phpjs,J2TeaM/phpjs,kvz/phpjs,J2TeaM/phpjs,strrife/phpjs,ajenkul/phpjs,janschoenherr/phpjs,MartinReidy/phpjs,MartinReidy/phpjs,mojaray2k/phpjs,VicAMMON/phpjs,FlorinDragotaExpertvision/phpjs,hirak/phpjs,ajenkul/phpjs,hirak/phpjs,janschoenherr/phpjs,revanthpobala/phpjs,davidgruebl/phpjs,strrife/phpjs,mojaray2k/phpjs,strrife/phpjs | ---
+++
@@ -5,13 +5,18 @@
// returns 1: 'Dima'
// example 2: bin2hex('00');
// returns 2: '\x00'
+ // example 3: bin2hex('2f1q')
+ // returns 3: false
var ret = [], i = 0, l;
s += '';
for ( l = s.length ; i < l; i+=2 ) {
- ret.push(parseInt(s.substr(i, 2), 16));
+ var c = parseInt(s.substr(i, 1), 16);
+ var k = parseInt(s.substr(i+1, 1), 16);
+ if(isNaN(c) || isNaN(k)) return false;
+ ret.push( (c << 4) | k );
}
return String.fromCharCode.apply(String, ret); |
805a979307583490d89197c8a82e7ba9fcae27ce | client/common/actions/index.js | client/common/actions/index.js | import types from '../constants/ActionTypes'
import utils from '../../shared/utils'
function replaceUserInfo(userInfo) {
return {
type: types.REPLACE_USER_INFO,
userInfo
}
}
function clearUserInfo() {
return {type: types.CLEAR_USER_INFO}
}
function fetchUserInfo() {
return dispatch => {
utils.ajax({url: '/api/user/getUserInfo'}).then(res => {
dispatch(replaceUserInfo(res))
})
}
}
export default {
replaceUserInfo,
fetchUserInfo,
clearUserInfo
}
| import types from '../constants/ActionTypes'
import utils from '../../shared/utils'
function replaceUserInfo(userInfo) {
return {
type: types.REPLACE_USER_INFO,
userInfo
}
}
function clearUserInfo() {
return {type: types.CLEAR_USER_INFO}
}
function fetchUserInfo() {
return dispatch => {
utils.ajax({
url: '/api/user/getUserInfo',
type: 'get'
}).then(res => {
dispatch(replaceUserInfo(res))
})
}
}
export default {
replaceUserInfo,
fetchUserInfo,
clearUserInfo
}
| Update action fetchUserInfo ajax type to get | Update action fetchUserInfo ajax type to get
| JavaScript | mit | qiuye1027/screenInteraction,qiuye1027/screenInteraction,chikara-chan/react-isomorphic-boilerplate,chikara-chan/react-isomorphic-boilerplate | ---
+++
@@ -14,7 +14,10 @@
function fetchUserInfo() {
return dispatch => {
- utils.ajax({url: '/api/user/getUserInfo'}).then(res => {
+ utils.ajax({
+ url: '/api/user/getUserInfo',
+ type: 'get'
+ }).then(res => {
dispatch(replaceUserInfo(res))
})
} |
3480bf8a6de2c0dd46b7b5e0a1e2a968ae4e603c | client/js/util/eventemitter.js | client/js/util/eventemitter.js | 'use strict';
/**
* @constructor
*/
function EventEmitter() {
this.eventHandlers = {};
}
EventEmitter.prototype.emit = function(event) {
if (!this.eventHandlers[event]) {
return;
}
var argsOut = [];
for (var i = 1; i < arguments.length; ++i) {
argsOut.push(arguments[i]);
}
for (var j = 0; j < this.eventHandlers[event].length; ++j) {
this.eventHandlers[event][j].apply(this, argsOut);
}
};
EventEmitter.prototype.addEventListener = function(event, handler) {
if (!this.eventHandlers[event]) {
this.eventHandlers[event] = [];
}
this.eventHandlers[event].push(handler);
};
EventEmitter.prototype.on = EventEmitter.prototype.addEventListener;
EventEmitter.prototype.removeEventListener = function(event, handler) {
if (!this.eventHandlers[event]) {
return false;
}
var handlerIdx = this.eventHandlers[event].indexOf(handler);
if (handlerIdx !== -1) {
this.eventHandlers[event].splice(handlerIdx, 1);
return true;
}
return false;
};
EventEmitter.prototype.once = function(event, handler) {
var onceHandler = function() {
this.removeEventListener(event, onceHandler);
handler.apply(this, arguments);
}.bind(this);
this.addEventListener(event, onceHandler);
};
| 'use strict';
/**
* @constructor
*/
function EventEmitter() {
this.eventHandlers = {};
}
EventEmitter.prototype.emit = function(event) {
if (!this.eventHandlers[event]) {
return;
}
var argsOut = [];
for (var i = 1; i < arguments.length; ++i) {
argsOut.push(arguments[i]);
}
for (var j = 0; j < this.eventHandlers[event].length; ++j) {
this.eventHandlers[event][j].apply(this, argsOut);
}
};
EventEmitter.prototype.addEventListener = function(event, handler) {
if (!this.eventHandlers[event]) {
this.eventHandlers[event] = [];
}
this.eventHandlers[event].push(handler);
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addEventListener;
EventEmitter.prototype.removeEventListener = function(event, handler) {
if (!this.eventHandlers[event]) {
return false;
}
var handlerIdx = this.eventHandlers[event].indexOf(handler);
if (handlerIdx !== -1) {
this.eventHandlers[event].splice(handlerIdx, 1);
return true;
}
return false;
};
EventEmitter.prototype.once = function(event, handler) {
var onceHandler = function() {
this.removeEventListener(event, onceHandler);
handler.apply(this, arguments);
}.bind(this);
this.addEventListener(event, onceHandler);
return this;
};
| Make addEventListener return this for function chaining. | Make addEventListener return this for function chaining.
| JavaScript | agpl-3.0 | exjam/rosebrowser,exjam/rosebrowser,brett19/rosebrowser,brett19/rosebrowser | ---
+++
@@ -11,10 +11,12 @@
if (!this.eventHandlers[event]) {
return;
}
+
var argsOut = [];
for (var i = 1; i < arguments.length; ++i) {
argsOut.push(arguments[i]);
}
+
for (var j = 0; j < this.eventHandlers[event].length; ++j) {
this.eventHandlers[event][j].apply(this, argsOut);
}
@@ -24,19 +26,24 @@
if (!this.eventHandlers[event]) {
this.eventHandlers[event] = [];
}
+
this.eventHandlers[event].push(handler);
+ return this;
};
+
EventEmitter.prototype.on = EventEmitter.prototype.addEventListener;
EventEmitter.prototype.removeEventListener = function(event, handler) {
if (!this.eventHandlers[event]) {
return false;
}
+
var handlerIdx = this.eventHandlers[event].indexOf(handler);
if (handlerIdx !== -1) {
this.eventHandlers[event].splice(handlerIdx, 1);
return true;
}
+
return false;
};
@@ -45,5 +52,7 @@
this.removeEventListener(event, onceHandler);
handler.apply(this, arguments);
}.bind(this);
+
this.addEventListener(event, onceHandler);
+ return this;
}; |
b7d6033ada80ac9979c084cc357e2c541a05ee62 | server/config/config.units.js | server/config/config.units.js | var units = {
datacenter: {
unitName: 'adminsys',
unitStats: {
attack: 10,
security: 50,
power: 5
}
},
personal_computer: {
unitName: 'zombie_computer',
unitStats: {
attack: 50,
security: 0,
power: 2
}
},
cave: {
unitName: 'hackers',
unitStats: {
attack: 100,
security: 30,
power: 4
}
}
};
module.exports = units; | var units = {
datacenter: {
unitStats: {
name: 'SysAdmin',
attack: 0,
security: 25,
power: 500,
price: 2000
}
},
personal_computer: {
unitStats: {
name: 'Zombie computer',
attack: 10,
security: 0,
power: 10,
price: 300
}
},
cave: {
unitStats: {
name: 'Hacker',
attack: 25,
security: 0,
power: 0,
price: 2000
}
}
};
module.exports = units;
| Change unit object format (server side) | Change unit object format (server side)
| JavaScript | mit | romain-grelet/HackersWars,romain-grelet/HackersWars | ---
+++
@@ -1,26 +1,29 @@
var units = {
datacenter: {
- unitName: 'adminsys',
unitStats: {
- attack: 10,
- security: 50,
- power: 5
+ name: 'SysAdmin',
+ attack: 0,
+ security: 25,
+ power: 500,
+ price: 2000
}
},
personal_computer: {
- unitName: 'zombie_computer',
unitStats: {
- attack: 50,
+ name: 'Zombie computer',
+ attack: 10,
security: 0,
- power: 2
+ power: 10,
+ price: 300
}
},
cave: {
- unitName: 'hackers',
unitStats: {
- attack: 100,
- security: 30,
- power: 4
+ name: 'Hacker',
+ attack: 25,
+ security: 0,
+ power: 0,
+ price: 2000
}
}
}; |
0fc62a076bf8d9afb215c386688ef35cc4b8e559 | server/res/strings/english.js | server/res/strings/english.js | module.exports = {
'responses': {
'GREET': 'Hello! How are you doing today :\)',
'HELP': 'I can help you with a bunch of things around your house.\n\n'
+ 'You can check in on your security cameras, ask me the temperature, and much more!\n'
+ 'I will also notify you during events such as a visitor at your door.',
'TFLUK': 'Okay. Thanks for letting me know.'
},
'words': {
'DISPLAY': ['tell', 'give', 'show', 'what', 'what\'s', 'display', 'how'],
'TEMPERATURE': ['temperature', 'temp', 'heat', 'hot', 'warm', 'cold'],
'GREET': ['hello', 'hi', 'hey', 'good day', 'what\'s up', 'whats up', 'sup', 'good morning', 'good evening'],
'STATE': ['i am', 'i\'m', 'im '],
'CAM': ['cam', 'camera', 'pic', 'picture', 'see', 'film']
}
}
| module.exports = {
'responses': {
'GREET': 'Hello! How are you doing today :\)',
'HELP': 'I can help you with a bunch of things around your house.\n\n'
+ 'You can check in on your security cameras, ask me the temperature, and much more!\n'
+ 'I will also notify you during events such as a visitor at your door.',
'TFLUK': 'Okay. Thanks for letting me know.'
},
'words': {
'DISPLAY': ['tell', 'give', 'show', 'what', 'what\'s', 'display', 'how', 'is it'],
'TEMPERATURE': ['temperature', 'temp', 'heat', 'hot', 'warm', 'cold'],
'GREET': ['hello', 'hi', 'hey', 'good day', 'what\'s up', 'whats up', 'sup', 'good morning', 'good evening'],
'STATE': ['i am', 'i\'m', 'im '],
'CAM': ['cam', 'camera', 'pic', 'picture', 'see', 'film']
}
}
| Add "is it" as option to ask for temperature | Add "is it" as option to ask for temperature
| JavaScript | mit | Eaton-Software/messenger-home | ---
+++
@@ -7,7 +7,7 @@
'TFLUK': 'Okay. Thanks for letting me know.'
},
'words': {
- 'DISPLAY': ['tell', 'give', 'show', 'what', 'what\'s', 'display', 'how'],
+ 'DISPLAY': ['tell', 'give', 'show', 'what', 'what\'s', 'display', 'how', 'is it'],
'TEMPERATURE': ['temperature', 'temp', 'heat', 'hot', 'warm', 'cold'],
'GREET': ['hello', 'hi', 'hey', 'good day', 'what\'s up', 'whats up', 'sup', 'good morning', 'good evening'],
'STATE': ['i am', 'i\'m', 'im '], |
1d7da8b90ffc9d685a247e426c696d85b38201c4 | assets/js/racer.js | assets/js/racer.js | function Game(){
this.$track = $('#racetrack');
this.finishLine = this.$track.width() - 54;
}
function Player(id){
this.player = $('.player')[id - 1];
this.position = 10;
}
Player.prototype.move = function(){
this.position += 20;
};
Player.prototype.updatePosition = function(){
$player = $(this.player);
$player.css('margin-left', this.position);
};
Player.prototype.checkWinner = function(){
};
$(document).ready(function() {
var game = new Game();
var player1 = new Player(1);
var player2 = new Player(2);
$(document).on('keyup', function(keyPress){
if(keyPress.keyCode === 80) {
player1.move();
player1.updatePosition();
} else if (keyPress.keyCode === 81) {
player2.move();
player2.updatePosition();
}
});
}); | function Game(){
this.$track = $('#racetrack');
this.finishLine = this.$track.width() - 54;
}
function Player(id){
this.player = $('.player')[id - 1];
this.position = 10;
}
Player.prototype.move = function(){
this.position += 20;
};
Player.prototype.updatePosition = function(){
$player = $(this.player);
$player.css('margin-left', this.position);
};
function checkWinner(player, game){
if( player.position > game.finishLine ){
alert("somebody won!");
}
}
$(document).ready(function() {
var game = new Game();
var player1 = new Player(1);
var player2 = new Player(2);
$(document).on('keyup', function(keyPress){
if(keyPress.keyCode === 80) {
player1.move();
player1.updatePosition();
} else if (keyPress.keyCode === 81) {
player2.move();
player2.updatePosition();
}
});
}); | Create checkWinner Function that alerts when a player has reached the finish line | Create checkWinner Function that alerts when a player has reached the finish line
| JavaScript | mit | SputterPuttRedux/basic-javascript-racer,SputterPuttRedux/basic-javascript-racer | ---
+++
@@ -17,9 +17,11 @@
$player.css('margin-left', this.position);
};
-Player.prototype.checkWinner = function(){
-
-};
+function checkWinner(player, game){
+ if( player.position > game.finishLine ){
+ alert("somebody won!");
+ }
+}
$(document).ready(function() { |
0c467864aa4bac65bae58116b150020a074d091f | admin/client/App/sagas/index.js | admin/client/App/sagas/index.js | import { takeLatest, delay } from 'redux-saga';
import { fork, select, put, take } from 'redux-saga/effects';
import * as actions from '../screens/List/constants';
import updateParams from './updateParams';
import { loadItems } from '../screens/List/actions';
/**
* Load the items
*/
function * loadTheItems () {
yield put(loadItems());
}
/**
* Debounce the search loading new items by 500ms
*/
function * debouncedSearch () {
const searchString = yield select((state) => state.active.search);
if (searchString) {
yield delay(500);
}
yield updateParams();
}
function * rootSaga () {
yield take(actions.INITIAL_LIST_LOAD);
yield put(loadItems());
yield fork(takeLatest, actions.SET_ACTIVE_SEARCH, debouncedSearch);
yield fork(takeLatest, [actions.SET_ACTIVE_SORT, actions.SET_ACTIVE_COLUMNS, actions.SET_CURRENT_PAGE], updateParams);
yield fork(takeLatest, [actions.ADD_FILTER, actions.CLEAR_FILTER, actions.CLEAR_ALL_FILTERS], loadTheItems);
}
export default rootSaga;
| import { takeLatest, delay } from 'redux-saga';
import { fork, select, put, take } from 'redux-saga/effects';
import * as actions from '../screens/List/constants';
import updateParams from './updateParams';
import { loadItems } from '../screens/List/actions';
/**
* Load the items
*/
function * loadTheItems () {
yield put(loadItems());
}
/**
* Debounce the search loading new items by 500ms
*/
function * debouncedSearch () {
const searchString = yield select((state) => state.active.search);
if (searchString) {
yield delay(500);
}
yield updateParams();
}
function * rootSaga () {
// Block loading on all items until the first load comes in
yield take(actions.INITIAL_LIST_LOAD);
yield put(loadItems());
// Search debounced
yield fork(takeLatest, actions.SET_ACTIVE_SEARCH, debouncedSearch);
// If one of the other active properties changes, update the query params and load the new items
yield fork(takeLatest, [actions.SET_ACTIVE_SORT, actions.SET_ACTIVE_COLUMNS, actions.SET_CURRENT_PAGE], updateParams);
// Whenever the filters change or another list is loaded, load the items
yield fork(takeLatest, [actions.INITIAL_LIST_LOAD, actions.ADD_FILTER, actions.CLEAR_FILTER, actions.CLEAR_ALL_FILTERS], loadTheItems);
}
export default rootSaga;
| Fix list not loading on second open | Fix list not loading on second open
Closes #3369
| JavaScript | mit | danielmahon/keystone,benkroeger/keystone,linhanyang/keystone,naustudio/keystone,Pop-Code/keystone,naustudio/keystone,danielmahon/keystone,trentmillar/keystone,jstockwin/keystone,matthewstyers/keystone,ONode/keystone,w01fgang/keystone,alobodig/keystone,frontyard/keystone,jstockwin/keystone,trentmillar/keystone,vokal/keystone,brianjd/keystone,naustudio/keystone,vokal/keystone,Yaska/keystone,benkroeger/keystone,andrewlinfoot/keystone,Pop-Code/keystone,snowkeeper/keystone,alobodig/keystone,Adam14Four/keystone,Yaska/keystone,cermati/keystone,andrewlinfoot/keystone,dryna/keystone-twoje-urodziny,danielmahon/keystone,matthewstyers/keystone,sendyhalim/keystone,benkroeger/keystone,matthewstyers/keystone,ONode/keystone,andrewlinfoot/keystone,Adam14Four/keystone,cermati/keystone,snowkeeper/keystone,concoursbyappointment/keystoneRedux,Yaska/keystone,dryna/keystone-twoje-urodziny,rafmsou/keystone,ratecity/keystone,concoursbyappointment/keystoneRedux,vokal/keystone,ratecity/keystone,frontyard/keystone,trentmillar/keystone,rafmsou/keystone,frontyard/keystone,sendyhalim/keystone,brianjd/keystone,w01fgang/keystone | ---
+++
@@ -24,11 +24,15 @@
}
function * rootSaga () {
+ // Block loading on all items until the first load comes in
yield take(actions.INITIAL_LIST_LOAD);
yield put(loadItems());
+ // Search debounced
yield fork(takeLatest, actions.SET_ACTIVE_SEARCH, debouncedSearch);
+ // If one of the other active properties changes, update the query params and load the new items
yield fork(takeLatest, [actions.SET_ACTIVE_SORT, actions.SET_ACTIVE_COLUMNS, actions.SET_CURRENT_PAGE], updateParams);
- yield fork(takeLatest, [actions.ADD_FILTER, actions.CLEAR_FILTER, actions.CLEAR_ALL_FILTERS], loadTheItems);
+ // Whenever the filters change or another list is loaded, load the items
+ yield fork(takeLatest, [actions.INITIAL_LIST_LOAD, actions.ADD_FILTER, actions.CLEAR_FILTER, actions.CLEAR_ALL_FILTERS], loadTheItems);
}
export default rootSaga; |
6c4bab22ae449af235ea33499061113a140b7595 | src/eorzea-time.js | src/eorzea-time.js | import padStart from './polyfill/padStart';
const THREE_MINUTES = 3 * 60 * 1000;
const privateDateProperty = typeof Symbol !== 'function' ?
Symbol('privateDateProperty') : '_privateDateProperty';
function computeEorzeaDate(date) {
const eorzeaTime = new Date();
const unixTime = Math.floor(date.getTime() * 1440 / 70 - THREE_MINUTES);
eorzeaTime.setTime(unixTime);
return eorzeaTime;
}
export default class EorzeaTime {
constructor(date = new Date()) {
this[privateDateProperty] = computeEorzeaDate(date);
}
getHours() {
return this[privateDateProperty].getUTCHours();
}
getMinutes() {
return this[privateDateProperty].getUTCMinutes();
}
getSeconds() {
return this[privateDateProperty].getUTCSeconds();
}
toString() {
return [
padStart.call(this.getHours(), 2, 0),
padStart.call(this.getMinutes(), 2, 0),
padStart.call(this.getSeconds(), 2, 0)
].join(':');
}
toJSON() {
return toString();
}
}
| import padStart from './polyfill/padStart';
const THREE_MINUTES = 3 * 60 * 1000;
const privateDateProperty = typeof Symbol === 'function' ?
Symbol('privateDateProperty') : '_privateDateProperty';
function computeEorzeaDate(date) {
const eorzeaTime = new Date();
const unixTime = Math.floor(date.getTime() * 1440 / 70 - THREE_MINUTES);
eorzeaTime.setTime(unixTime);
return eorzeaTime;
}
export default class EorzeaTime {
constructor(date = new Date()) {
this[privateDateProperty] = computeEorzeaDate(date);
}
getHours() {
return this[privateDateProperty].getUTCHours();
}
getMinutes() {
return this[privateDateProperty].getUTCMinutes();
}
getSeconds() {
return this[privateDateProperty].getUTCSeconds();
}
toString() {
return [
padStart.call(this.getHours(), 2, 0),
padStart.call(this.getMinutes(), 2, 0),
padStart.call(this.getSeconds(), 2, 0)
].join(':');
}
toJSON() {
return toString();
}
}
| Fix a presence check of Symbol function | :bug: Fix a presence check of Symbol function | JavaScript | mit | flowercartelet/eorzea-time | ---
+++
@@ -1,7 +1,7 @@
import padStart from './polyfill/padStart';
const THREE_MINUTES = 3 * 60 * 1000;
-const privateDateProperty = typeof Symbol !== 'function' ?
+const privateDateProperty = typeof Symbol === 'function' ?
Symbol('privateDateProperty') : '_privateDateProperty';
function computeEorzeaDate(date) { |
3934fbf1024d52b8b8429a5d073b7b8526521d25 | src/hello-world.js | src/hello-world.js | // ./src/hello-world.js
var console = require('gulp-messenger');
console.success('Hello World!'); | // ./src/hello-world.js
var console = require('gulp-messenger');
console.success('Hello World!');
console.log('This is added in master branch') | Create merge conflict in master branch | Create merge conflict in master branch
| JavaScript | mit | mikeerickson/gitflow | ---
+++
@@ -3,3 +3,5 @@
var console = require('gulp-messenger');
console.success('Hello World!');
+
+console.log('This is added in master branch') |
f658e382b0974c53edc828efac5d4f182fbd3c08 | app/assets/javascripts/users.js | app/assets/javascripts/users.js | $( ".users-show, .users-sample" ).ready( function() {
$( "#stats-area" ).tabs({
// Ajax request stuff, mostly pulled from jQuery UI's docs.
beforeLoad: function( event, ui ) {
// There's no need to do a fresh Ajax request each time the tab
// is clicked. If the tab has been loaded already, skip the request
// and display the pre-existing data.
if ( ui.tab.data( "loaded" ) ) {
event.preventDefault();
return;
}
ui.panel.html( "Retrieving data - one moment please..." );
ui.jqXHR.success( function() {
ui.tab.data( "loaded", true );
});
ui.jqXHR.fail( function() {
ui.panel.html(
"Couldn't load this tab. Please try again later." );
});
}
});
// Make "Games" table sortable. Initialize default sort to
// [ leftmost column, descending ]. Prevent meaningless attempts
// to sort by "Actions" column (currently in position 6).
$( "#gameTable" ).tablesorter({
sortList: [[0,1]],
headers: {
6: { sorter: false }
}
});
$( "#gameTable" ).stickyTableHeaders({
scrollableArea: $( '#stats-area' )
});
});
| $( ".users-show, .users-sample" ).ready( function() {
$( "#stats-area" ).tabs({
// Ajax request stuff, mostly pulled from jQuery UI's docs.
beforeLoad: function( event, ui ) {
// There's no need to do a fresh Ajax request each time the tab
// is clicked. If the tab has been loaded already (or is currently
// loading), skip the request and display the pre-existing data
// (or continue with the current request).
if ( ui.tab.data( "loaded" ) || ui.tab.data( "loading" ) ) {
event.preventDefault();
return;
}
ui.tab.data( "loading", true );
ui.panel.html( "Retrieving data - one moment please..." );
ui.jqXHR.success( function() {
ui.tab.data( "loading", false );
ui.tab.data( "loaded", true );
});
ui.jqXHR.fail( function() {
ui.tab.data( "loading", false );
ui.panel.html(
"Couldn't load this tab. Please try again later." );
});
}
});
// Make "Games" table sortable. Initialize default sort to
// [ leftmost column, descending ]. Prevent meaningless attempts
// to sort by "Actions" column (currently in position 6).
$( "#gameTable" ).tablesorter({
sortList: [[0,1]],
headers: {
6: { sorter: false }
}
});
$( "#gameTable" ).stickyTableHeaders({
scrollableArea: $( '#stats-area' )
});
// Set the topics tab (currently in position 2) to load in the background
// as soon as everything else is done.
$( "#stats-area" ).tabs( "load", 2 );
});
| Load Topics in background when stats page opens | Load Topics in background when stats page opens
| JavaScript | mit | steve-mcclellan/j-scorer,steve-mcclellan/j-scorer,steve-mcclellan/j-scorer | ---
+++
@@ -4,20 +4,24 @@
beforeLoad: function( event, ui ) {
// There's no need to do a fresh Ajax request each time the tab
- // is clicked. If the tab has been loaded already, skip the request
- // and display the pre-existing data.
- if ( ui.tab.data( "loaded" ) ) {
+ // is clicked. If the tab has been loaded already (or is currently
+ // loading), skip the request and display the pre-existing data
+ // (or continue with the current request).
+ if ( ui.tab.data( "loaded" ) || ui.tab.data( "loading" ) ) {
event.preventDefault();
return;
}
+ ui.tab.data( "loading", true );
ui.panel.html( "Retrieving data - one moment please..." );
ui.jqXHR.success( function() {
+ ui.tab.data( "loading", false );
ui.tab.data( "loaded", true );
});
ui.jqXHR.fail( function() {
+ ui.tab.data( "loading", false );
ui.panel.html(
"Couldn't load this tab. Please try again later." );
});
@@ -38,4 +42,7 @@
scrollableArea: $( '#stats-area' )
});
+ // Set the topics tab (currently in position 2) to load in the background
+ // as soon as everything else is done.
+ $( "#stats-area" ).tabs( "load", 2 );
}); |
3a4aae6cfb1f664afd8943a1a49d3de0062eb2b9 | app/js/helpers.js | app/js/helpers.js | function filter(arr) {
var filteredArray = [], prev;
arr.sort();
for (var i = 0; i < arr.length; i++) {
if (arr[i] !== prev) {
filteredArray.push(arr[i]);
}
prev = arr[i];
}
return filteredArray
}
function rarefy(pattern) {
arr = [];
matches = [];
merged = [];
str = text.doc;
elements = xml.doc.querySelectorAll("[category=" + pattern + "]")
for (var i = 0; i < elements.length; i++) {
arr.push(elements[i].textContent.replace(/(\r\n|\n|\r)/gm,"").trim());
}
filteredArray = filter(arr);
return filteredArray
}
function countMatches(pattern) {
filteredArray = rarefy(pattern);
for (var i = 0; i < filteredArray.length; i++) {
pattern = filteredArray[i];
regex = new RegExp(pattern, 'gi');
if (str.match(regex)) {
matches.push(str.match(regex));
}
}
merged = merged.concat.apply(merged, matches); // For unnesting nested arrays
return merged.length;
}
| function filter(arr) {
var filteredArray = [], prev;
arr.sort();
for (var i = 0; i < arr.length; i++) {
if (arr[i] !== prev) {
filteredArray.push(arr[i]);
}
prev = arr[i];
}
return filteredArray
}
function rarefyXMLTextContent(pattern) {
arr = [];
matches = [];
merged = [];
str = text.doc;
elements = xml.doc.querySelectorAll("[category=" + pattern + "]")
for (var i = 0; i < elements.length; i++) {
arr.push(elements[i].textContent.replace(/(\r\n|\n|\r)/gm,"").trim());
}
filteredArray = filter(arr);
return filteredArray
}
function countMatches(pattern) {
filteredArray = rarefyXMLTextContent(pattern);
for (var i = 0; i < filteredArray.length; i++) {
pattern = filteredArray[i];
regex = new RegExp(pattern, 'gi');
if (str.match(regex)) {
matches.push(str.match(regex));
}
}
merged = merged.concat.apply(merged, matches); // For unnesting nested arrays
return merged.length;
}
| Rename helper methods for clarity | Rename helper methods for clarity
| JavaScript | mit | bdfinlayson/annotation-tool,bdfinlayson/annotation-tool | ---
+++
@@ -10,7 +10,7 @@
return filteredArray
}
-function rarefy(pattern) {
+function rarefyXMLTextContent(pattern) {
arr = [];
matches = [];
merged = [];
@@ -24,7 +24,7 @@
}
function countMatches(pattern) {
- filteredArray = rarefy(pattern);
+ filteredArray = rarefyXMLTextContent(pattern);
for (var i = 0; i < filteredArray.length; i++) {
pattern = filteredArray[i];
regex = new RegExp(pattern, 'gi'); |
bcb666e596c694f432340e780aff05530b0df40a | src/series/line.js | src/series/line.js | (function(d3, fc) {
'use strict';
fc.series.line = function() {
// convenience functions that return the x & y screen coords for a given point
var x = function(d) { return line.xScale.value(line.xValue.value(d)); };
var y = function(d) { return line.yScale.value(line.yValue.value(d)); };
var lineData = d3.svg.line()
.defined(function(d) {
return !isNaN(y(d));
})
.x(x)
.y(y);
var line = function(selection) {
selection.each(function(data) {
var path = d3.select(this)
.selectAll('path.line')
.data([data]);
path.enter()
.append('path')
.attr('class', 'line');
path.attr('d', lineData);
line.decorate.value(path);
});
};
line.decorate = fc.utilities.property(fc.utilities.fn.noop);
line.xScale = fc.utilities.property(d3.time.scale());
line.yScale = fc.utilities.property(d3.scale.linear());
line.yValue = fc.utilities.property(function(d) { return d.close; });
line.xValue = fc.utilities.property(function(d) { return d.date; });
return line;
};
}(d3, fc)); | (function(d3, fc) {
'use strict';
fc.series.line = function() {
// convenience functions that return the x & y screen coords for a given point
var x = function(d) { return line.xScale.value(line.xValue.value(d)); };
var y = function(d) { return line.yScale.value(line.yValue.value(d)); };
var lineData = d3.svg.line()
.defined(function(d) {
return !isNaN(y(d));
})
.x(x)
.y(y);
var line = function(selection) {
selection.each(function(data) {
var path = d3.select(this)
.selectAll('path.line')
.data([data]);
path.enter()
.append('path')
.attr('class', 'line');
path.attr('d', lineData);
line.decorate.value(path);
});
};
line.decorate = fc.utilities.property(fc.utilities.fn.noop);
line.xScale = fc.utilities.property(d3.time.scale());
line.yScale = fc.utilities.property(d3.scale.linear());
line.yValue = fc.utilities.property(function(d) { return d.close; });
line.xValue = fc.utilities.property(function(d) { return d.date; });
return d3.rebind(line, lineData, 'interpolate');
};
}(d3, fc)); | Add interpolation support to the Line series component | Add interpolation support to the Line series component
| JavaScript | mit | alisd23/d3fc-d3v4,bjedrzejewski/d3fc,fxcebx/d3fc,djmiley/d3fc,fxcebx/d3fc,janakerman/d3-financial-components,alisd23/d3fc-d3v4,djmiley/d3fc,fxcebx/d3fc,bjedrzejewski/d3fc,janakerman/d3-financial-components,djmiley/d3fc,bjedrzejewski/d3fc,alisd23/d3fc-d3v4 | ---
+++
@@ -38,6 +38,6 @@
line.yValue = fc.utilities.property(function(d) { return d.close; });
line.xValue = fc.utilities.property(function(d) { return d.date; });
- return line;
+ return d3.rebind(line, lineData, 'interpolate');
};
}(d3, fc)); |
f54167b6ce911acd2a4ecd05db25f11558ed870f | IoradWebWidget/scripts/app.js | IoradWebWidget/scripts/app.js | if (ioradWebWidget.util.common.isFreshdeskKnowledgebase()) {
ioradWebWidget.freshdesk.runApp(jQuery, window);
}
if (ioradWebWidget.util.common.isDeskKnowledgebase()) {
ioradWebWidget.desk.runApp(jQuery, window);
}
| //if (ioradWebWidget.util.common.isFreshdeskKnowledgebase()) {
// ioradWebWidget.freshdesk.runApp(jQuery, window);
//}
ioradWebWidget.freshdesk.runApp(jQuery, window); | Make freshdesk widget run on customized domain support portals. | Make freshdesk widget run on customized domain support portals.
| JavaScript | mit | iorad/integrations,iorad/integrations,iorad/integrations | ---
+++
@@ -1,7 +1,5 @@
-if (ioradWebWidget.util.common.isFreshdeskKnowledgebase()) {
- ioradWebWidget.freshdesk.runApp(jQuery, window);
-}
+//if (ioradWebWidget.util.common.isFreshdeskKnowledgebase()) {
+// ioradWebWidget.freshdesk.runApp(jQuery, window);
+//}
-if (ioradWebWidget.util.common.isDeskKnowledgebase()) {
- ioradWebWidget.desk.runApp(jQuery, window);
-}
+ioradWebWidget.freshdesk.runApp(jQuery, window); |
2aecea32c53f551069b43ac6e2e9da3831a9b667 | client/packages/settings-dashboard-extension-worona/src/dashboard/reducers/index.js | client/packages/settings-dashboard-extension-worona/src/dashboard/reducers/index.js | import { isDev, getDevelopmentPackages } from 'worona-deps';
import { map } from 'lodash';
import { combineReducers } from 'redux';
import * as deps from '../deps';
const env = isDev ? 'dev' : 'prod';
const mapPkg = pkg => ({ ...pkg, main: pkg.cdn && pkg.cdn.dashboard[env].main.file });
const create = collection => combineReducers({
collection: deps.reducerCreators.collectionCreator(collection, mapPkg),
isReady: deps.reducerCreators.isReadyCreator(collection),
});
const devPkgs = map(getDevelopmentPackages(), pkg => pkg.woronaInfo);
export const devPackages = () => devPkgs;
export const collections = () => combineReducers({
live: create('settings-live'),
preview: create('settings-preview'),
packages: create('packages'),
devPackages: combineReducers({ collection: devPackages }),
});
export default () => combineReducers({
collections: collections(),
});
| import { isDev, getDevelopmentPackages } from 'worona-deps';
import { map } from 'lodash';
import { combineReducers } from 'redux';
import * as deps from '../deps';
const env = isDev ? 'dev' : 'prod';
const mapPkg = pkg => ({ ...pkg, main: pkg.cdn && pkg.cdn.dashboard[env].main.file });
const createSetting = collection => combineReducers({
collection: deps.reducerCreators.collectionCreator(collection),
isReady: deps.reducerCreators.isReadyCreator(collection),
});
const createPkg = collection => combineReducers({
collection: deps.reducerCreators.collectionCreator(collection, mapPkg),
isReady: deps.reducerCreators.isReadyCreator(collection),
});
const devPkgs = map(getDevelopmentPackages(), pkg => pkg.woronaInfo);
export const devPackages = () => devPkgs;
export const collections = () => combineReducers({
live: createSetting('settings-live'),
preview: createSetting('settings-preview'),
packages: createPkg('packages'),
devPackages: combineReducers({ collection: devPackages }),
});
export default () => combineReducers({
collections: collections(),
});
| Remove mapPkg from settings collections. | Remove mapPkg from settings collections.
| JavaScript | mit | worona/worona-dashboard,worona/worona-dashboard,worona/worona,worona/worona,worona/worona-core,worona/worona,worona/worona-core | ---
+++
@@ -6,7 +6,12 @@
const env = isDev ? 'dev' : 'prod';
const mapPkg = pkg => ({ ...pkg, main: pkg.cdn && pkg.cdn.dashboard[env].main.file });
-const create = collection => combineReducers({
+const createSetting = collection => combineReducers({
+ collection: deps.reducerCreators.collectionCreator(collection),
+ isReady: deps.reducerCreators.isReadyCreator(collection),
+});
+
+const createPkg = collection => combineReducers({
collection: deps.reducerCreators.collectionCreator(collection, mapPkg),
isReady: deps.reducerCreators.isReadyCreator(collection),
});
@@ -15,9 +20,9 @@
export const devPackages = () => devPkgs;
export const collections = () => combineReducers({
- live: create('settings-live'),
- preview: create('settings-preview'),
- packages: create('packages'),
+ live: createSetting('settings-live'),
+ preview: createSetting('settings-preview'),
+ packages: createPkg('packages'),
devPackages: combineReducers({ collection: devPackages }),
});
|
d0e3a74be246e9b43189d1c2d3a39fce357a146d | src/states/Game.js | src/states/Game.js | /* globals __DEV__ */
import Phaser from 'phaser'
import Mushroom from '../sprites/Ship'
export default class extends Phaser.State {
init () {}
preload () {}
create () {
game.physics.startSystem(Phaser.Physics.ARCADE)
// Set up game input.
game.cursors = game.input.keyboard.createCursorKeys()
game.input.keyboard.addKeyCapture([ Phaser.Keyboard.SPACEBAR ])
this.mushroom = new Mushroom({
game: this,
x: this.world.centerX,
y: this.world.centerY,
asset: 'mushroom'
})
this.game.add.existing(this.mushroom)
}
render () {
if (__DEV__) {
this.game.debug.spriteInfo(this.mushroom, 32, 32)
}
}
}
| /* globals __DEV__ */
import Phaser from 'phaser'
import Ship from '../sprites/Ship'
export default class extends Phaser.State {
init () {}
preload () {}
create () {
game.physics.startSystem(Phaser.Physics.ARCADE)
// Set up game input.
game.cursors = game.input.keyboard.createCursorKeys()
game.input.keyboard.addKeyCapture([ Phaser.Keyboard.SPACEBAR ])
this.player = new Ship({
game: this,
x: this.world.centerX,
y: this.world.centerY,
asset: 'mushroom'
})
this.game.add.existing(this.player)
}
render () {
if (__DEV__) {
this.game.debug.spriteInfo(this.player, 32, 32)
}
}
}
| Rename mushroom to ship / player | Rename mushroom to ship / player
| JavaScript | mit | killer-robots/killer-robots,killer-robots/killer-robots | ---
+++
@@ -1,6 +1,6 @@
/* globals __DEV__ */
import Phaser from 'phaser'
-import Mushroom from '../sprites/Ship'
+import Ship from '../sprites/Ship'
export default class extends Phaser.State {
init () {}
@@ -13,19 +13,19 @@
game.cursors = game.input.keyboard.createCursorKeys()
game.input.keyboard.addKeyCapture([ Phaser.Keyboard.SPACEBAR ])
- this.mushroom = new Mushroom({
+ this.player = new Ship({
game: this,
x: this.world.centerX,
y: this.world.centerY,
asset: 'mushroom'
})
- this.game.add.existing(this.mushroom)
+ this.game.add.existing(this.player)
}
render () {
if (__DEV__) {
- this.game.debug.spriteInfo(this.mushroom, 32, 32)
+ this.game.debug.spriteInfo(this.player, 32, 32)
}
}
} |
f1aa082977ee0679cfa1e96d3fa3a2e3fdefa8fe | src/actions/sessionActions.js | src/actions/sessionActions.js | import fetch from 'isomorphic-fetch'
export function signUpUser(register, history) {
return(dispatch) => {
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
user: {
first_name: register.name,
email: register.email,
password: register.password,
password_confirmation: register.password,
}
}),
};
return fetch('api/v1/register', options)
.then(response => response.json())
.then(token => {
sessionStorage.setItem('jwt', token.jwt);
history.push("/");
dispatch({ type: 'SIGN_UP_SUCCESS' });
});
}
}
export function signInUser(credentials, history) {
return(dispatch) => {
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
auth: {
email: credentials.email,
password: credentials.password,
}
}),
};
return fetch('api/v1/signin', options)
.then(response => response.json())
.then(token => {
sessionStorage.setItem('jwt', token.jwt);
history.push("/");
dispatch({ type: 'SIGN_IN_SUCCESS' });
});
}
}
export function signOutUser() {
sessionStorage.removeItem('jwt');
return(dispatch) => {
dispatch({ type: 'CLEAR_CURRENT_ROUTINE' });
dispatch({ type: 'SIGN_OUT' });
}
}
| import fetch from 'isomorphic-fetch'
export function signUpUser(register, history) {
return(dispatch) => {
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
user: {
first_name: register.name,
email: register.email,
password: register.password,
password_confirmation: register.password,
}
}),
};
return fetch('api/v1/register', options)
.then(response => response.json())
.then(token => {
localStorage.setItem('jwt', token.jwt);
history.push("/");
dispatch({ type: 'SIGN_UP_SUCCESS' });
});
}
}
export function signInUser(credentials, history) {
return(dispatch) => {
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
auth: {
email: credentials.email,
password: credentials.password,
}
}),
};
return fetch('api/v1/signin', options)
.then(response => response.json())
.then(token => {
localStorage.setItem('jwt', token.jwt);
history.push("/");
dispatch({ type: 'SIGN_IN_SUCCESS' });
});
}
}
export function signOutUser() {
localStorage.removeItem('jwt');
return(dispatch) => {
dispatch({ type: 'CLEAR_CURRENT_ROUTINE' });
dispatch({ type: 'SIGN_OUT' });
}
}
| Change jwt storage from session to local | Change jwt storage from session to local
| JavaScript | mit | snsavage/timer-react,snsavage/timer-react | ---
+++
@@ -19,7 +19,7 @@
return fetch('api/v1/register', options)
.then(response => response.json())
.then(token => {
- sessionStorage.setItem('jwt', token.jwt);
+ localStorage.setItem('jwt', token.jwt);
history.push("/");
dispatch({ type: 'SIGN_UP_SUCCESS' });
});
@@ -43,7 +43,7 @@
return fetch('api/v1/signin', options)
.then(response => response.json())
.then(token => {
- sessionStorage.setItem('jwt', token.jwt);
+ localStorage.setItem('jwt', token.jwt);
history.push("/");
dispatch({ type: 'SIGN_IN_SUCCESS' });
});
@@ -51,7 +51,7 @@
}
export function signOutUser() {
- sessionStorage.removeItem('jwt');
+ localStorage.removeItem('jwt');
return(dispatch) => {
dispatch({ type: 'CLEAR_CURRENT_ROUTINE' }); |
b3f449dace39b99aca7046b4eddc9dd7ae81c141 | bin/generators/scopes/create.js | bin/generators/scopes/create.js | const eg = require('../../eg');
module.exports = class extends eg.Generator {
constructor (args, opts) {
super(args, opts);
this.configureCommand({
command: 'create [options] <scope..>',
desc: 'Create a scope',
builder: yargs =>
yargs
.usage(`Usage: $0 ${process.argv[2]} create [options] <scope..>`)
.example(`$0 ${process.argv[2]} create scope_name`)
});
}
prompting () {
const argv = this.argv;
const scopes = Array.isArray(argv.scope)
? argv.scope
: [argv.scope];
return this.admin.scopes.create(scopes)
.then(res => {
if (argv.q) {
this.stdout(`${scopes}`);
} else {
this.log.ok(`Created ${scopes}`);
}
})
.catch(err => {
this.log.error(err.message);
});
};
};
| const eg = require('../../eg');
module.exports = class extends eg.Generator {
constructor (args, opts) {
super(args, opts);
this.configureCommand({
command: 'create [options] <scope..>',
desc: 'Create a scope',
builder: yargs =>
yargs
.usage(`Usage: $0 ${process.argv[2]} create [options] <scope..>`)
.example(`$0 ${process.argv[2]} create scope_name`)
});
}
prompting () {
const argv = this.argv;
const scopes = Array.isArray(argv.scope)
? argv.scope
: [argv.scope];
return this.admin.scopes.create(scopes)
.then(res => {
if (argv.q) {
this.stdout(`${scopes}`);
} else {
this.log.ok(`Created ${scopes}`);
}
})
.catch(err => {
this.log.error(err.response.text);
});
};
};
| Print the returned error message. | Print the returned error message.
| JavaScript | apache-2.0 | ExpressGateway/express-gateway | ---
+++
@@ -28,7 +28,7 @@
}
})
.catch(err => {
- this.log.error(err.message);
+ this.log.error(err.response.text);
});
};
}; |
943282e096fe7a36e035fccd069eb8f843b686b0 | src/animate.js | src/animate.js | // A bit of pseudo-code
//
// tickModel
// var dt
// for each canvas
// canvasParticles = canvasParticles.filterOut(particlesOutsideOrTimeout)
//
// for each particle in canvasParticles
// tick(particle)
//
// for each startOptions
// var newParticles = createParticles(imageUrls, startOptions, dt)
// canvasParticles = [].concat(canvasParticles, newParticles)
//
// tickView
// drawCanvas(canvasId, loadedImages, canvasParticles)
//
var tickState = require('./tickState')
var render = require('./view/render')
// To indicate if started.
// Maybe to pause the animation in the future.
var running = false
// number, unix timestamp milliseconds of most recent frame.
var past = null
var animationLoop = function (state) {
var present, dtms
// Time difference from previous frame in milliseconds
present = Date.now()
dtms = (past === null) ? 0 : present - past
past = present
// Update Model
tickState(state, dtms / 1000) // secs
// DEBUG
// console.log('num of particles', state.canvases.reduce(function (acc, c) {
// return c.waves.reduce((ac, w) => {
// return ac + w.particles.length
// }, acc)
// }, 0))
// Draw; View current model
render(state)
// Recursion
// Allow only one viewLoop recursion at a time.
if (running) {
window.requestAnimationFrame(function () {
animationLoop(state)
})
}
}
module.exports = function (state) {
if (!running) {
running = true
animationLoop(state)
}
}
| // Animate: call model update and view render at each animation frame.
//
var tickState = require('./tickState')
var render = require('./view/render')
// To indicate if started.
// Maybe to pause the animation in the future.
var running = false
// number, unix timestamp milliseconds of most recent frame.
var past = null
var animationLoop = function (state) {
var present, dtms
// Time difference from previous frame in milliseconds
present = Date.now()
dtms = (past === null) ? 0 : present - past
past = present
// Update Model
tickState(state, dtms / 1000) // secs
// DEBUG
// console.log('num of particles', state.canvases.reduce(function (acc, c) {
// return c.waves.reduce((ac, w) => {
// return ac + w.particles.length
// }, acc)
// }, 0))
// Draw; View current model
render(state)
// Recursion
// Allow only one viewLoop recursion at a time.
if (running) {
window.requestAnimationFrame(function () {
animationLoop(state)
})
}
}
module.exports = function (state) {
if (!running) {
running = true
animationLoop(state)
}
}
| Replace pseudo-code sketch with accurate comment | Replace pseudo-code sketch with accurate comment
| JavaScript | mit | axelpale/sprinkler | ---
+++
@@ -1,19 +1,4 @@
-// A bit of pseudo-code
-//
-// tickModel
-// var dt
-// for each canvas
-// canvasParticles = canvasParticles.filterOut(particlesOutsideOrTimeout)
-//
-// for each particle in canvasParticles
-// tick(particle)
-//
-// for each startOptions
-// var newParticles = createParticles(imageUrls, startOptions, dt)
-// canvasParticles = [].concat(canvasParticles, newParticles)
-//
-// tickView
-// drawCanvas(canvasId, loadedImages, canvasParticles)
+// Animate: call model update and view render at each animation frame.
//
var tickState = require('./tickState')
var render = require('./view/render') |
6e1b30ca8028d016fc2a566141f6cabbe1acaaa4 | .stylelintrc.js | .stylelintrc.js | const declarationBlockPropertiesOrder = require(`./.csscomb.json`)[`sort-order`][0];
module.exports = {
extends: `stylelint-config-modularis`,
rules: {
'declaration-block-properties-order': declarationBlockPropertiesOrder,
'no-indistinguishable-colors': [true, { threshold: 1 }],
'string-no-newline': false,
},
};
| const declarationBlockPropertiesOrder = require(`./.csscomb.json`)[`sort-order`][0];
module.exports = {
extends: `stylelint-config-modularis`,
rules: {
'declaration-block-properties-order': declarationBlockPropertiesOrder,
'no-indistinguishable-colors': [true, { threshold: 1 }],
'string-no-newline': null,
},
};
| Use null instead of false to override the string-no-newline setting from the modularis stylelint config. | Use null instead of false to override the string-no-newline setting from the modularis stylelint config.
| JavaScript | mit | avalanchesass/avalanche-website,avalanchesass/avalanche-website | ---
+++
@@ -5,6 +5,6 @@
rules: {
'declaration-block-properties-order': declarationBlockPropertiesOrder,
'no-indistinguishable-colors': [true, { threshold: 1 }],
- 'string-no-newline': false,
+ 'string-no-newline': null,
},
}; |
88f0989207c048b60a72cca136bc5d912c77ebd3 | src/App.js | src/App.js | import DicewareOptions from './DicewareOptions'
import React, { PureComponent } from 'react'
export default class App extends PureComponent {
state = {
length: 6
}
handleLengthChange = event => this.setState({ length: parseInt(event.target.value, 10) })
handlePossibleItemsChange = possibleItems => this.setState({ possibleItems })
render () {
const possiblePasswords = this.state.possibleItems ** this.state.length
return (
<form>
<h1>Password Entropy</h1>
<label>
<h2>Length</h2>
<input value={this.state.length} onChange={this.handleLengthChange} type="number" min="1" required/>
</label>
<h2>Options</h2>
<DicewareOptions onChange={this.handlePossibleItemsChange}/>
<h2>Possible Passwords</h2>
Roughly {possiblePasswords.toPrecision(4)} ({Math.floor(Math.log2(possiblePasswords)) + 1} bits of entropy)
</form>
)
}
}
| import DicewareOptions from './DicewareOptions'
import React, { PureComponent } from 'react'
export default class App extends PureComponent {
state = {
length: 6
}
handleLengthChange = event => this.setState({ length: parseInt(event.target.value, 10) })
handlePossibleItemsChange = possibleItems => this.setState({ possibleItems })
render () {
const possiblePasswords = this.state.possibleItems ** this.state.length
const approximatePrefix = possiblePasswords > Number.MAX_SAFE_INTEGER && '~ '
return (
<form>
<h1>Password Entropy</h1>
<label>
<h2>Length</h2>
<input value={this.state.length} onChange={this.handleLengthChange} type="number" min="1" required/>
</label>
<h2>Options</h2>
<DicewareOptions onChange={this.handlePossibleItemsChange}/>
<h2>Possible Passwords</h2>
{approximatePrefix}{possiblePasswords.toLocaleString()} ({approximatePrefix}{Math.log2(possiblePasswords).toFixed(2)} bits of entropy)
</form>
)
}
}
| Clean up result math and notation | Clean up result math and notation
| JavaScript | isc | nickmccurdy/password-entropy,nickmccurdy/password-entropy | ---
+++
@@ -11,6 +11,7 @@
render () {
const possiblePasswords = this.state.possibleItems ** this.state.length
+ const approximatePrefix = possiblePasswords > Number.MAX_SAFE_INTEGER && '~ '
return (
<form>
@@ -25,7 +26,7 @@
<DicewareOptions onChange={this.handlePossibleItemsChange}/>
<h2>Possible Passwords</h2>
- Roughly {possiblePasswords.toPrecision(4)} ({Math.floor(Math.log2(possiblePasswords)) + 1} bits of entropy)
+ {approximatePrefix}{possiblePasswords.toLocaleString()} ({approximatePrefix}{Math.log2(possiblePasswords).toFixed(2)} bits of entropy)
</form>
)
} |
962dd6226d16428acf12993eb35c6b90d29bc109 | js/bitazza.js | js/bitazza.js | 'use strict';
// Bitazza uses Alphapoint, also used by ndax
// In order to use private endpoints, the following are required:
// - 'apiKey'
// - 'secret',
// - 'uid' (userId in the api info)
// - 'login' (the email address used to log into the UI)
const ndax = require ('./ndax.js');
// ---------------------------------------------------------------------------
module.exports = class bitazza extends ndax {
describe () {
return this.deepExtend (super.describe (), {
'id': 'bitazza',
'name': 'Bitazza',
'countries': [ 'THA' ],
'certified': false,
'pro': false,
'urls': {
'test': undefined,
'api': {
'public': 'https://apexapi.bitazza.com:8443/AP',
'private': 'https://apexapi.bitazza.com:8443/AP',
},
'www': 'https://bitazza.com/',
'referral': '',
'fees': 'https://bitazza.com/fees.html',
'doc': [
'https://api-doc.bitazza.com/',
],
},
'fees': {
'trading': {
'tierBased': true,
'percentage': true,
'taker': this.parseNumber ('0.0025'),
'maker': this.parseNumber ('0.0025'),
},
},
});
}
};
| 'use strict';
// Bitazza uses Alphapoint, also used by ndax
// In order to use private endpoints, the following are required:
// - 'apiKey'
// - 'secret',
// - 'uid' (userId in the api info)
// - 'login' (the email address used to log into the UI)
// - 'password' (the password used to log into the UI)
const ndax = require ('./ndax.js');
// ---------------------------------------------------------------------------
module.exports = class bitazza extends ndax {
describe () {
return this.deepExtend (super.describe (), {
'id': 'bitazza',
'name': 'Bitazza',
'countries': [ 'THA' ],
'certified': false,
'pro': false,
'urls': {
'test': undefined,
'api': {
'public': 'https://apexapi.bitazza.com:8443/AP',
'private': 'https://apexapi.bitazza.com:8443/AP',
},
'www': 'https://bitazza.com/',
'referral': '',
'fees': 'https://bitazza.com/fees.html',
'doc': [
'https://api-doc.bitazza.com/',
],
},
'fees': {
'trading': {
'tierBased': true,
'percentage': true,
'taker': this.parseNumber ('0.0025'),
'maker': this.parseNumber ('0.0025'),
},
},
});
}
};
| Add 'password' to comment on required credentials | Add 'password' to comment on required credentials
| JavaScript | mit | ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt | ---
+++
@@ -6,6 +6,7 @@
// - 'secret',
// - 'uid' (userId in the api info)
// - 'login' (the email address used to log into the UI)
+// - 'password' (the password used to log into the UI)
const ndax = require ('./ndax.js');
|
2b65809bc9b134d281a5552387e385fda7b63b84 | src/app.js | src/app.js | import React from 'react'
import ReactDOM from 'react-dom'
class App extends React.Component { // eslint-disable-line no-unused-vars
render () {
return (
<div className="container-fluid">
<div className="row">
<div className="jumbotron text-center">
<h1>Login Screen</h1>
<h3>TODO: Add login screen components here</h3>
</div>
</div>
</div>
)
}
}
ReactDOM.render(
<App></App>,
document.getElementById('react-app')
) | import React from 'react'
import ReactDOM from 'react-dom'
class App extends React.Component { // eslint-disable-line no-unused-vars
render () {
return (
<div className="container-fluid">
<div className="row">
<div className="jumbotron text-center">
<h1>Login Screen</h1>
</div>
</div>
<div className="row">
<h3 className="text-center">TODO: Add login screen components here</h3>
</div>
</div>
)
}
}
ReactDOM.render(
<App></App>,
document.getElementById('react-app')
) | Refactor TODO to be below the jumbotron | Refactor TODO to be below the jumbotron
| JavaScript | mit | cpwilkerson/login-server,cpwilkerson/login-server | ---
+++
@@ -8,8 +8,10 @@
<div className="row">
<div className="jumbotron text-center">
<h1>Login Screen</h1>
- <h3>TODO: Add login screen components here</h3>
</div>
+ </div>
+ <div className="row">
+ <h3 className="text-center">TODO: Add login screen components here</h3>
</div>
</div>
) |
dbaaef857da2f402700e254f0ee0d63bb56b6870 | karma.conf.js | karma.conf.js | module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['mocha', 'sinon-chrome', 'karma-typescript'],
files: [
'src/ts/**/*.ts'
],
exclude: [
'src/ts/constants.ts'
],
preprocessors: {
'src/ts/**/*.ts': ['karma-typescript']
},
client: {
captureConsole: false,
mocha: {
opts: 'mocha.opts'
}
},
reporters: ['mocha'],
karmaTypescriptConfig: {
bundlerOptions: {
entrypoints: /\.spec\.ts$/,
},
compilerOptions: {
target: 'es2015'
},
reports: {
'html': 'coverage',
'text': ''
}
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['ChromeHeadless'],
singleRun: true,
concurrency: Infinity
});
};
| module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['mocha', 'sinon-chrome', 'karma-typescript'],
files: [
'src/ts/**/*.ts'
],
exclude: [
'src/ts/constants.ts'
],
preprocessors: {
'src/ts/**/*.ts': ['karma-typescript']
},
client: {
captureConsole: false,
mocha: {
opts: 'mocha.opts'
}
},
reporters: ['mocha'],
karmaTypescriptConfig: {
bundlerOptions: {
entrypoints: /\.spec\.ts$/
},
compilerOptions: require('./tsconfig').compilerOptions,
reports: {
'html': 'coverage',
'text': ''
}
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['ChromeHeadless'],
singleRun: true,
concurrency: Infinity
});
};
| Use common ts compiler options in karma test and webpack build | chore(test): Use common ts compiler options in karma test and webpack build
| JavaScript | mit | xtangle/ZoundCloud,xtangle/ZoundCloud | ---
+++
@@ -20,11 +20,9 @@
reporters: ['mocha'],
karmaTypescriptConfig: {
bundlerOptions: {
- entrypoints: /\.spec\.ts$/,
+ entrypoints: /\.spec\.ts$/
},
- compilerOptions: {
- target: 'es2015'
- },
+ compilerOptions: require('./tsconfig').compilerOptions,
reports: {
'html': 'coverage',
'text': '' |
a7591058f6fe14412ea645703695b2ebad987083 | test/index.spec.js | test/index.spec.js | import expect from 'expect.js';
import constantMirror from '../src';
describe('constantMirror', () => {
it('exports a function', () => {
expect(constantMirror).to.be.a('function');
});
it('creates a mirrored hash from a list of strings', () => {
expect(constantMirror('HELLO', 'WORLD')).to.eql({
HELLO: 'HELLO',
WORLD: 'WORLD'
});
});
});
| import expect from 'expect.js';
import constantMirror from '..';
describe('constantMirror', () => {
it('exports a function', () => {
expect(constantMirror).to.be.a('function');
});
it('creates a mirrored hash from a list of strings', () => {
expect(constantMirror('HELLO', 'WORLD')).to.eql({
HELLO: 'HELLO',
WORLD: 'WORLD'
});
});
});
| Test compiled JS, not ES6 source | Test compiled JS, not ES6 source
| JavaScript | mit | tough-griff/constant-mirror | ---
+++
@@ -1,6 +1,6 @@
import expect from 'expect.js';
-import constantMirror from '../src';
+import constantMirror from '..';
describe('constantMirror', () => {
it('exports a function', () => { |
6e6a449ddda27c2471a72b436fb7074ac5ae7403 | lib/loaders/utils/to-code.js | lib/loaders/utils/to-code.js | /* eslint-disable no-use-before-define */
function toCodeArray(array) {
return `[${array.map(item => toCode(item)).join(",")}]`
}
function toCodeObject(object) {
return `{${Object.keys(object).map(key => `"${key}": ${toCode(object[key])}`).join(",")}}`
}
function toCode(values) {
if (Array.isArray(values)) {
return toCodeArray(values)
}
if (typeof values === "object") {
return toCodeObject(values)
}
if (typeof values === "string" && !/require(.+)/.test(values)) {
return `"${values}"`
}
return `${values}`
}
module.exports = toCode
| /* eslint-disable no-use-before-define */
function toCodeArray(array) {
return `[${array.map(item => toCode(item)).join(",")}]`
}
function toCodeObject(object) {
return `{${Object.keys(object).map(key => `"${key}": ${toCode(object[key])}`).join(",")}}`
}
// Convert an arbitrary object, array, or primitive into a string representation. Special
// consideration is given to `require` statements, which are inserted into the string _without_
// being escaped. This ensures that the `require` statements are actually executed at runtime.
function toCode(values) {
if (Array.isArray(values)) {
return toCodeArray(values)
}
if (typeof values === "object") {
return toCodeObject(values)
}
if (typeof values === "string" && !/require(.+)/.test(values)) {
return `"${values}"`
}
return `${values}`
}
module.exports = toCode
| Add comment our `toCode` function | Add comment our `toCode` function
| JavaScript | mit | mavenlink/mavenlink-ui-concept,ahuth/mavenlink-ui-concept | ---
+++
@@ -8,6 +8,9 @@
return `{${Object.keys(object).map(key => `"${key}": ${toCode(object[key])}`).join(",")}}`
}
+// Convert an arbitrary object, array, or primitive into a string representation. Special
+// consideration is given to `require` statements, which are inserted into the string _without_
+// being escaped. This ensures that the `require` statements are actually executed at runtime.
function toCode(values) {
if (Array.isArray(values)) {
return toCodeArray(values) |
2d839b07c96bbfc38588bb3e32aece3e6d9be6d6 | js/js-engine.js | js/js-engine.js | $(document).ready(function() {
// Add class to all inputs (input's type attribute value)
$('input').each(function() {$(this).addClass(this.type)});
// put all your jQuery code here
}); | $(document).ready(function() {
// Add class to all inputs (input's type attribute value)
$('input').each(function() {$(this).addClass(this.type)});
// put all your jQuery code here
}); | Add class to all inputs | Add class to all inputs
| JavaScript | mit | maciejsmolinski/html-go | ---
+++
@@ -2,6 +2,7 @@
// Add class to all inputs (input's type attribute value)
$('input').each(function() {$(this).addClass(this.type)});
-
+
// put all your jQuery code here
+
}); |
f4489c9b6cc45d41bd0ee41c7988af369dc249d9 | src/majesty.js | src/majesty.js | (function($) {
$.fn.majesty = function() {
var findDependents = function(rootElement) {
return rootElement.find('[data-depends-on]');
};
var findMatches = function(searchValue, elements) {
searchValue = $.trim(searchValue);
if(searchValue === '') {
return $([]);
}
// Hack for now. Probably use regex later
filtered = elements.filter(function() {
var dependsValue = $(this).data('depends-value');
if (dependsValue === '*') {
return true;
}
var values = dependsValue.split(',');
for(var i=0; i < values.length; i++) {
if($.trim(values[i]) == searchValue) {
return true;
}
}
});
return filtered;
};
return this.each(function() {
self = $(this);
dependents = findDependents(self);
dependents.hide();
self.on('change', 'select, input:radio', function(e) {
target = $(e.currentTarget);
name = target.attr('name');
val = target.val();
potential = dependents.filter('[data-depends-on=' + name + ']');
matched = findMatches(val, potential);
potential.hide();
matched.show();
});
});
};
})(jQuery);
| (function($) {
var findDependents = function(rootElement) {
return rootElement.find('[data-depends-on]');
};
var findMatches = function(searchValue, elements) {
searchValue = $.trim(searchValue);
if(searchValue === '') {
return $([]);
}
// Hack for now. Probably use regex later
filtered = elements.filter(function() {
var dependsValue = $(this).data('depends-value');
if (dependsValue === '*') {
return true;
}
var values = dependsValue.split(',');
for(var i=0; i < values.length; i++) {
if($.trim(values[i]) == searchValue) {
return true;
}
}
});
return filtered;
};
$.fn.majesty = function() {
return this.each(function() {
self = $(this);
dependents = findDependents(self);
dependents.hide();
self.on('change', 'select, input:radio', function(e) {
target = $(e.currentTarget);
name = target.attr('name');
val = target.val();
potential = dependents.filter('[data-depends-on=' + name + ']');
matched = findMatches(val, potential);
potential.hide();
matched.show();
});
});
};
})(jQuery);
| Move functions outside of plugin block | Move functions outside of plugin block
| JavaScript | mit | craigerm/majesty-js | ---
+++
@@ -1,38 +1,38 @@
(function($) {
- $.fn.majesty = function() {
+ var findDependents = function(rootElement) {
+ return rootElement.find('[data-depends-on]');
+ };
- var findDependents = function(rootElement) {
- return rootElement.find('[data-depends-on]');
- };
+ var findMatches = function(searchValue, elements) {
- var findMatches = function(searchValue, elements) {
+ searchValue = $.trim(searchValue);
- searchValue = $.trim(searchValue);
+ if(searchValue === '') {
+ return $([]);
+ }
- if(searchValue === '') {
- return $([]);
+ // Hack for now. Probably use regex later
+ filtered = elements.filter(function() {
+
+ var dependsValue = $(this).data('depends-value');
+
+ if (dependsValue === '*') {
+ return true;
}
- // Hack for now. Probably use regex later
- filtered = elements.filter(function() {
+ var values = dependsValue.split(',');
- var dependsValue = $(this).data('depends-value');
-
- if (dependsValue === '*') {
+ for(var i=0; i < values.length; i++) {
+ if($.trim(values[i]) == searchValue) {
return true;
}
+ }
+ });
+ return filtered;
+ };
- var values = dependsValue.split(',');
-
- for(var i=0; i < values.length; i++) {
- if($.trim(values[i]) == searchValue) {
- return true;
- }
- }
- });
- return filtered;
- };
+ $.fn.majesty = function() {
return this.each(function() {
|
7106e052ff1e92dd7792908798c595b4bc4f6410 | lib/server.js | lib/server.js | var connections = {};
var expire = function(id) {
Presences.remove(id);
delete connections[id];
};
var tick = function(id) {
connections[id].lastSeen = Date.now();
};
Meteor.startup(function() {
Presences.remove({});
});
Meteor.onConnection(function(connection) {
// console.log('connectionId: ' + connection.id);
Presences.insert({ _id: connection.id });
connections[connection.id] = {};
tick(connection.id);
connection.onClose(function() {
// console.log('connection closed: ' + connection.id);
expire(connection.id);
});
});
Meteor.methods({
presenceTick: function() {
check(arguments, [Match.Any]);
if (this.connection && connections[this.connection.id])
tick(this.connection.id);
}
});
Meteor.setInterval(function() {
_.each(connections, function(connection, id) {
if (connection.lastSeen < (Date.now() - 10000))
expire(id);
});
}, 5000);
| var connections = {};
var presenceExpiration = 10000;
var expire = function(id) {
Presences.remove(id);
delete connections[id];
};
var tick = function(id) {
connections[id].lastSeen = Date.now();
};
Meteor.startup(function() {
Presences.remove({});
});
Meteor.onConnection(function(connection) {
// console.log('connectionId: ' + connection.id);
Presences.insert({ _id: connection.id });
connections[connection.id] = {};
tick(connection.id);
connection.onClose(function() {
// console.log('connection closed: ' + connection.id);
expire(connection.id);
});
});
Meteor.methods({
presenceTick: function() {
check(arguments, [Match.Any]);
if (this.connection && connections[this.connection.id])
tick(this.connection.id);
}
});
Meteor.methods({
setPresenceExpiration: function(time) {
presenceExpiration = time;
}
});
Meteor.setInterval(function() {
_.each(connections, function(connection, id) {
if (connection.lastSeen < (Date.now() - presenceExpiration))
expire(id);
});
}, 5000);
| Set presenceExpiration outside of package | Set presenceExpiration outside of package
| JavaScript | mit | minden/meteor-presence | ---
+++
@@ -1,4 +1,6 @@
var connections = {};
+
+var presenceExpiration = 10000;
var expire = function(id) {
Presences.remove(id);
@@ -34,9 +36,15 @@
}
});
+Meteor.methods({
+ setPresenceExpiration: function(time) {
+ presenceExpiration = time;
+ }
+});
+
Meteor.setInterval(function() {
_.each(connections, function(connection, id) {
- if (connection.lastSeen < (Date.now() - 10000))
+ if (connection.lastSeen < (Date.now() - presenceExpiration))
expire(id);
});
}, 5000); |
9b9a73c31eddf1c7e70bb89352c3cf84edededea | client/intercom-shim.js | client/intercom-shim.js | (function() {
/* globals define */
'use strict';
function l(config) {
var i = function() {
i.c(arguments);
};
i.q = [];
i.c = function(args) {
i.q.push(args);
};
window.Intercom = i;
var d = document;
var s = d.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'https://widget.intercom.io/widget/' + config.intercom.appId;
var x = d.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
}
var ic = window.Intercom;
if (typeof ic === 'function') {
ic('reattach_activator');
ic('update', {});
}
function generateModule(name, values) {
define(name, [], function() {
'use strict'; // jshint ignore:line
return values;
});
}
generateModule('intercom', {
default: function() {
if (window.Intercom && typeof window.Intercom === 'function') {
return window.Intercom.apply(null, arguments);
}
},
_setup: l
});
})();
| (function() {
/* globals define */
'use strict';
function l(config) {
var i = function() {
i.c(arguments);
};
i.q = [];
i.c = function(args) {
i.q.push(args);
};
window.Intercom = i;
var d = document;
var s = d.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'https://widget.intercom.io/widget/' + config.intercom.appId;
var x = d.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
}
var ic = window.Intercom;
if (typeof ic === 'function') {
ic('reattach_activator');
ic('update', {});
}
function generateModule(name, values) {
define(name, [], function() {
'use strict'; // jshint ignore:line
return values;
});
}
generateModule('intercom', {
default: function() {
if (window.Intercom && typeof window.Intercom.apply === 'function') {
return window.Intercom.apply(null, arguments);
}
},
_setup: l
});
})();
| Make sure we are checking that apply exists | Make sure we are checking that apply exists
| JavaScript | mit | mike-north/ember-intercom-io,levanto-financial/ember-intercom-io,seawatts/ember-intercom-io,seawatts/ember-intercom-io,levanto-financial/ember-intercom-io,mike-north/ember-intercom-io | ---
+++
@@ -38,7 +38,7 @@
generateModule('intercom', {
default: function() {
- if (window.Intercom && typeof window.Intercom === 'function') {
+ if (window.Intercom && typeof window.Intercom.apply === 'function') {
return window.Intercom.apply(null, arguments);
}
}, |
649509ca76845e45825ee75f6841d1cb894ff1e4 | scripts/transform/comments.js | scripts/transform/comments.js | 'use strict';
function makeFrontMatter(ast, dependencies) {
var value = [
'es6id: ',
'description: >'
];
var includes;
if (dependencies.length) {
includes = dependencies.map(function(file) {
return file + '.js';
}).join(', ');
value.push('includes: [' + includes + ']');
}
value = '---\n' + value.join('\n') + '\n---';
return {
type: 'Block',
value: value,
leading: true,
trailing: false
};
}
module.exports = function(ast, options) {
ast.program.comments.push(makeFrontMatter(ast, options.dependencies));
};
| 'use strict';
var licenseYearPattern = /\bcopyright (\d{4})\b/i;
function makeFrontMatter(ast, dependencies) {
var value = [
'es6id: ',
'description: >'
];
var includes;
if (dependencies.length) {
includes = dependencies.map(function(file) {
return file + '.js';
}).join(', ');
value.push('includes: [' + includes + ']');
}
value = '---\n' + value.join('\n') + '\n---';
return {
type: 'Block',
value: value,
leading: true,
trailing: false
};
}
function makeLicense(ast) {
var commentText = ast.program.comments.map(function(node) {
return node.value;
}).join(' ');
var match = licenseYearPattern.exec(commentText);
if (!match) {
throw new Error('Could not infer license year.');
}
return [
{
type: 'Line',
value: ' Copyright (C) ' + match[0] + ' the V8 project authors. ' +
'All rights reserved.',
leading: true,
trailing: false
},
{
type: 'Line',
value: ' This code is governed by the BSD license found in the ' +
'LICENSE file.',
leading: true,
trailing: false
}
];
}
module.exports = function(ast, options) {
var comments = ast.program.comments;
var license = makeLicense(ast);
var frontMatter = makeFrontMatter(ast, options.dependencies);
comments.push.apply(comments, license);
comments.push(frontMatter);
};
| Include license in transformed file | Include license in transformed file
Infer the year from the source file's code comments.
| JavaScript | mit | bocoup/test262-v8-machinery,bocoup/test262-v8-machinery | ---
+++
@@ -1,4 +1,6 @@
'use strict';
+
+var licenseYearPattern = /\bcopyright (\d{4})\b/i;
function makeFrontMatter(ast, dependencies) {
var value = [
@@ -23,6 +25,39 @@
};
}
+function makeLicense(ast) {
+ var commentText = ast.program.comments.map(function(node) {
+ return node.value;
+ }).join(' ');
+ var match = licenseYearPattern.exec(commentText);
+
+ if (!match) {
+ throw new Error('Could not infer license year.');
+ }
+
+ return [
+ {
+ type: 'Line',
+ value: ' Copyright (C) ' + match[0] + ' the V8 project authors. ' +
+ 'All rights reserved.',
+ leading: true,
+ trailing: false
+ },
+ {
+ type: 'Line',
+ value: ' This code is governed by the BSD license found in the ' +
+ 'LICENSE file.',
+ leading: true,
+ trailing: false
+ }
+ ];
+}
+
module.exports = function(ast, options) {
- ast.program.comments.push(makeFrontMatter(ast, options.dependencies));
+ var comments = ast.program.comments;
+ var license = makeLicense(ast);
+ var frontMatter = makeFrontMatter(ast, options.dependencies);
+
+ comments.push.apply(comments, license);
+ comments.push(frontMatter);
}; |
986faef86b65b9ab7471077da321020ee5164cf8 | src/set-env.js | src/set-env.js | const {webpack} = require('@webpack-blocks/webpack2');
/**
* Sets environment variables with all possible ways.
*/
module.exports = (options = {}) => {
const {
nodeEnv = 'development',
babelEnv = 'development',
} = options;
process.env.NODE_ENV = nodeEnv;
process.env.BABEL_ENV = babelEnv;
return () => ({
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(nodeEnv),
BABEL_ENV: JSON.stringify(babelEnv),
},
}),
new webpack.EnvironmentPlugin(['NODE_ENV', 'BABEL_ENV']),
],
});
};
| const {webpack} = require('@webpack-blocks/webpack2');
/**
* Sets environment variables with all possible ways.
*/
module.exports = (options = {}) => {
const {
nodeEnv,
babelEnv,
} = options;
process.env.NODE_ENV = nodeEnv;
process.env.BABEL_ENV = babelEnv;
return () => ({
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(nodeEnv),
BABEL_ENV: JSON.stringify(babelEnv),
},
}),
new webpack.EnvironmentPlugin(['NODE_ENV', 'BABEL_ENV']),
],
});
};
| Set setEnv defaults to undefined | Set setEnv defaults to undefined
| JavaScript | mit | fugr-ru/webpack-custom-blocks | ---
+++
@@ -6,8 +6,8 @@
*/
module.exports = (options = {}) => {
const {
- nodeEnv = 'development',
- babelEnv = 'development',
+ nodeEnv,
+ babelEnv,
} = options;
process.env.NODE_ENV = nodeEnv; |
9df8d7dca7a9f881eca551551b856f8cdf5ae6a4 | simul/app/components/login.js | simul/app/components/login.js | import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
TouchableHighlight,
} from 'react-native';
class Login extends Component{
constructor(){
super();
this.state = {
name: "",
username: "",
password_digest: "",
location: "",
bio: "",
preferred_contact: "",
skills: "",
seeking: "",
errors: [],
}
}
render() {
return (
<View style={styles.container}>
<Text>
Login
</Text>
<TextInput
onChangeText={ (val)=> this.setState({username: val}) }
style={styles.input} placeholder='Username'
/>
<TextInput
onChangeText={ (val)=> this.setState({password_digest: val}) }
style={styles.input} placeholder="Password"
/>
</View>
)
}
};
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
title: {
fontSize: 20,
alignSelf: 'center',
margin: 40
},
input: {
height: 50,
marginTop: 10,
padding: 4,
fontSize: 15,
borderWidth: 1,
borderColor: '#48bbec'
},
});
module.exports = Login;
| import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
TouchableHighlight,
} from 'react-native';
class Login extends Component{
constructor(){
super();
this.state = {
name: "",
username: "",
password_digest: "",
location: "",
bio: "",
preferred_contact: "",
skills: "",
seeking: "",
errors: [],
}
}
async onLoginPressed(){
}
render() {
return (
<View style={styles.container}>
<Text>
Login
</Text>
<TextInput
onChangeText={ (val)=> this.setState({username: val}) }
style={styles.input} placeholder='Username'
/>
<TextInput
onChangeText={ (val)=> this.setState({password_digest: val}) }
style={styles.input} placeholder="Password"
/>
<TouchableHighlight onPress={this.onRegisterPressed.bind(this)} style={styles.button}>
<Text style={styles.buttonText}>
Register
</Text>
</TouchableHighlight>
</View>
)
}
};
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
title: {
fontSize: 20,
alignSelf: 'center',
margin: 40
},
input: {
height: 50,
marginTop: 10,
padding: 4,
fontSize: 15,
borderWidth: 1,
borderColor: '#48bbec'
},
});
module.exports = Login;
| Create onLoginPressed function and add to render function | Create onLoginPressed function and add to render function
| JavaScript | mit | sf-red-pandas-2016/simul-react-native,sf-red-pandas-2016/simul-react-native,sf-red-pandas-2016/simul-react-native | ---
+++
@@ -25,6 +25,11 @@
}
}
+ async onLoginPressed(){
+
+
+ }
+
render() {
return (
@@ -43,6 +48,13 @@
onChangeText={ (val)=> this.setState({password_digest: val}) }
style={styles.input} placeholder="Password"
/>
+
+ <TouchableHighlight onPress={this.onRegisterPressed.bind(this)} style={styles.button}>
+ <Text style={styles.buttonText}>
+ Register
+ </Text>
+ </TouchableHighlight>
+
</View>
) |
94a9cefb34e1adcdae67a9402e8a6745f9e85496 | klets-server/routes/messages/messages-controller.js | klets-server/routes/messages/messages-controller.js | var HttpError = require('../../lib/http-error');
var messageRepo = require('../../repository/message-repo');
module.exports.create = function (req, res, next) {
var message = req.body.message;
checkDefined(message, 'message');
checkDefined(message._id, 'message._id');
checkDefined(message.userName, 'message.userName');
checkDefined(message.roomName, 'message.roomName');
checkDefined(message.text, 'message.text');
messageRepo.save(message);
res.sendStatus(201);
};
function checkDefined(value, fieldName) {
if (typeof value === 'undefined')
throw new HttpError(400, 'Missing field: ' + fieldName);
return value;
} | var HttpError = require('../../lib/http-error');
var messageRepo = require('../../repository/message-repo');
module.exports.create = function (req, res, next) {
var message = req.body.message;
checkDefined(message, 'message');
checkDefined(message._id, 'message._id');
checkDefined(message.userName, 'message.userName');
checkDefined(message.roomName, 'message.roomName');
checkDefined(message.text, 'message.text');
messageRepo.save(message);
res.set('Access-Control-Allow-Origin', '*').sendStatus(201);
};
function checkDefined(value, fieldName) {
if (typeof value === 'undefined')
throw new HttpError(400, 'Missing field: ' + fieldName);
return value;
} | Allow Cross Origin requests on create message endpoint | Allow Cross Origin requests on create message endpoint
| JavaScript | mit | rhmeeuwisse/KletsApp,rhmeeuwisse/KletsApp | ---
+++
@@ -11,7 +11,7 @@
messageRepo.save(message);
- res.sendStatus(201);
+ res.set('Access-Control-Allow-Origin', '*').sendStatus(201);
};
function checkDefined(value, fieldName) { |
4c2067c2609ad7af84e0384c39b0452341fb0358 | config/configuration.js | config/configuration.js | /**
* @file Defines the provider settings.
*
* Will set the path to Mongo, and applications id
* Most of the configuration can be done using system environment variables.
*/
// Load environment variables from .env file
var dotenv = require('dotenv');
dotenv.load();
// node_env can either be "development" or "production"
var node_env = process.env.NODE_ENV || "development";
// Port to run the app on. 8000 for development
// (Vagrant syncs this port)
// 80 for production
var default_port = 8000;
if(node_env === "production") {
default_port = 80;
}
// Exports configuration for use by app.js
module.exports = {
env: node_env,
port: process.env.PORT || default_port,
workers: process.env.WORKERS || 1,
googleId: process.env.GCONTACTS_ID,
googleSecret: process.env.GCONTACTS_SECRET,
appId: process.env.GCONTACTS_ANYFETCH_ID,
appSecret: process.env.GCONTACTS_ANYFETCH_SECRET,
providerUrl: process.env.PROVIDER_URL,
testRefreshToken: process.env.GCONTACTS_TEST_REFRESH_TOKEN
};
| /**
* @file Defines the provider settings.
*
* Will set the path to Mongo, and applications id
* Most of the configuration can be done using system environment variables.
*/
// Load environment variables from .env file
var dotenv = require('dotenv');
dotenv.load();
// node_env can either be "development" or "production"
var node_env = process.env.NODE_ENV || "development";
// Port to run the app on. 8000 for development
// (Vagrant syncs this port)
// 80 for production
var default_port = 8000;
if(node_env === "production") {
default_port = 80;
}
// Exports configuration for use by app.js
module.exports = {
env: node_env,
port: process.env.PORT || default_port,
mongoUrl: process.env.MONGOLAB_URI,
redisUrl: process.env.REDISCLOUD_URL,
googleId: process.env.GCONTACTS_ID,
googleSecret: process.env.GCONTACTS_SECRET,
appId: process.env.GCONTACTS_ANYFETCH_ID,
appSecret: process.env.GCONTACTS_ANYFETCH_SECRET,
providerUrl: process.env.PROVIDER_URL,
testRefreshToken: process.env.GCONTACTS_TEST_REFRESH_TOKEN
};
| Add redis and mongo URL in config | Add redis and mongo URL in config
| JavaScript | mit | AnyFetch/gcontacts-provider.anyfetch.com | ---
+++
@@ -24,7 +24,8 @@
module.exports = {
env: node_env,
port: process.env.PORT || default_port,
- workers: process.env.WORKERS || 1,
+ mongoUrl: process.env.MONGOLAB_URI,
+ redisUrl: process.env.REDISCLOUD_URL,
googleId: process.env.GCONTACTS_ID,
googleSecret: process.env.GCONTACTS_SECRET, |
d47521a1d9281c2a89cf78bd8902c112ae16e38e | live-examples/js-examples/classes/classes-static.js | live-examples/js-examples/classes/classes-static.js | class ClassWithStaticMethod {
static staticMethod() {
return 'static method has been called.';
}
}
console.log(ClassWithStaticMethod.staticMethod());
// expected output: "static method has been called."
| class ClassWithStaticMethod {
static staticProperty = "someValue";
static staticMethod() {
return 'static method has been called.';
}
}
console.log(ClassWithStaticMethod.staticProperty);
// output: "someValue"
console.log(ClassWithStaticMethod.staticMethod());
// output: "static method has been called."
| Update example to include static property | Update example to include static property
| JavaScript | cc0-1.0 | mdn/interactive-examples,mdn/interactive-examples,mdn/interactive-examples | ---
+++
@@ -1,8 +1,13 @@
class ClassWithStaticMethod {
+
+ static staticProperty = "someValue";
static staticMethod() {
return 'static method has been called.';
}
+
}
+console.log(ClassWithStaticMethod.staticProperty);
+// output: "someValue"
console.log(ClassWithStaticMethod.staticMethod());
-// expected output: "static method has been called."
+// output: "static method has been called." |
287c5ef21117352df8cde5eaa4592ce15c01031c | client/src/reducers/sourcesReducer.js | client/src/reducers/sourcesReducer.js | import initialState from './initialState'
export default function sourcesReducer(state = initialState.sources, action) {
switch (action.type) {
case 'GET_SOURCES':
return action.payload.map (source => (
{...source, selected: true}
))
default:
return state;
}
}
| import initialState from './initialState'
export default function sourcesReducer(state = initialState.sources, action) {
switch (action.type) {
case 'GET_SOURCES':
return action.payload.map (source => (
{...source, selected: false}
))
default:
return state;
}
}
| Change GET_SOURCES action to default to selected:false | Change GET_SOURCES action to default to selected:false
| JavaScript | mit | kevinladkins/newsfeed,kevinladkins/newsfeed,kevinladkins/newsfeed | ---
+++
@@ -4,7 +4,7 @@
switch (action.type) {
case 'GET_SOURCES':
return action.payload.map (source => (
- {...source, selected: true}
+ {...source, selected: false}
))
default:
return state; |
8dc31229b164225e2aa8d84f499b7bc0ef9be9f2 | ui/main.js | ui/main.js |
// Blank the document so the 404 page doesn't show up visibly.
document.documentElement.style.display = 'none';
// Can't use DOMContentLoaded, calling document.write or document.close inside it from
// inside an extension causes a crash.
onload = function() {
document.write(
"<!DOCTYPE html>" +
"<meta name=viewport content='width=device-width, user-scalable=no'>" +
"<script src='" + resolveUrl("bower_components/platform/platform.js") + "'></script>" +
"<cr-app></cr-app>"
);
document.close();
document.documentElement.style.display = '';
document.head.appendChild(createLink("import", "bower_components/polymer/polymer.html"));
document.head.appendChild(createLink("import", "ui/components/cr-app.html"));
document.head.appendChild(createLink("stylesheet", "ui/style.css"));
};
|
// Blank the document so the 404 page doesn't show up visibly.
document.documentElement.style.display = 'none';
// Can't use DOMContentLoaded, calling document.write or document.close inside it from
// inside an extension causes a crash.
onload = function() {
document.write(
"<!DOCTYPE html>" +
"<meta name=viewport content='width=device-width, user-scalable=no'>" +
"<title>Chromium Code Review</title>" +
"<script src='" + resolveUrl("bower_components/platform/platform.js") + "'></script>" +
"<cr-app></cr-app>"
);
document.close();
document.documentElement.style.display = '';
document.head.appendChild(createLink("import", "bower_components/polymer/polymer.html"));
document.head.appendChild(createLink("import", "ui/components/cr-app.html"));
document.head.appendChild(createLink("stylesheet", "ui/style.css"));
};
| Add a <title>. We should make it dynamic eventually so history works. | Add a <title>. We should make it dynamic eventually so history works.
| JavaScript | bsd-3-clause | esprehn/chromium-codereview,esprehn/chromium-codereview | ---
+++
@@ -8,6 +8,7 @@
document.write(
"<!DOCTYPE html>" +
"<meta name=viewport content='width=device-width, user-scalable=no'>" +
+ "<title>Chromium Code Review</title>" +
"<script src='" + resolveUrl("bower_components/platform/platform.js") + "'></script>" +
"<cr-app></cr-app>"
); |
22c91010c17691aceb15523cfa052b60cdc47d23 | app.js | app.js | var pg = require('pg');
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 3000 });
server.start(function () {
console.log('Server running at:', server.info.uri);
});
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply('Hello from SpotScore API!');
}
});
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply('Hello from SpotScore API!');
}
});
server.route({
method: 'GET',
path: '/objects',
handler: function (request, reply) {
var location = request.params.location;
var address = request.params.address;
var categories = request.params.categories;
var bbox = request.params.bbox;
var radius = request.params.radius;
var nearest = request.params.nearest;
// Make actual request to database
// Compile the JSON response
reply();
}
});
| var pg = require('pg');
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 3000 });
server.start(function () {
console.log('Server running at:', server.info.uri);
});
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply('Hello from SpotScore API!');
}
});
server.route({
method: 'GET',
path: '/objects',
handler: function (request, reply) {
var location = request.params.location;
var address = request.params.address;
var categories = request.params.categories;
var bbox = request.params.bbox;
var radius = request.params.radius;
var nearest = request.params.nearest;
// Make actual request to database
// Compile the JSON response
reply();
}
});
| Remove duplicate route for / | Remove duplicate route for /
| JavaScript | bsd-2-clause | SpotScore/spotscore | ---
+++
@@ -19,13 +19,6 @@
}
});
-server.route({
- method: 'GET',
- path: '/',
- handler: function (request, reply) {
- reply('Hello from SpotScore API!');
- }
-});
server.route({
method: 'GET', |
e76026335f7d999168fa377bc6b9f76295f4c7f1 | cli.js | cli.js | #!/usr/bin/env node
'use strict';
var chalk = require('chalk');
var meow = require('meow');
var process = require('process');
var allPrograms = [
'atom',
'bash',
'bin',
'git',
'gnome-terminal',
'vim',
'vscode'
];
var cli = meow({
help: [
'Usage: dotfiles install [<program>]',
'',
'where <program> is one of:',
' ' + allPrograms.join(', '),
'',
'Specify no <program> to install everything'
]
});
if (cli.input.length === 0) {
console.error('Error: No command specified');
cli.showHelp();
process.exit(1);
}
var commands = {
'install': install
};
if (cli.input[0] in commands) {
commands[cli.input[0]].apply(undefined, cli.input.slice(1));
}
function install(programList) {
if (programList === undefined) {
allPrograms.forEach(installProgram);
} else {
installProgram(programList);
}
}
function installProgram(program) {
if (allPrograms.indexOf(program) === -1) {
console.error('Error: tried to install non-existing program "' + program + '"');
return;
}
require('./' + program).install();
}
| #!/usr/bin/env node
'use strict';
var chalk = require('chalk');
var meow = require('meow');
var process = require('process');
var allPrograms = [
'atom',
'bash',
'bin',
'git',
'gnome-terminal',
'vim',
'vscode'
];
var cli = meow({
help: [
'Usage: dotfiles install [<program>...]',
'',
'where <program> is one or more of of:',
' ' + allPrograms.join(', '),
'',
'Specify no <program> to install everything'
]
});
if (cli.input.length === 0) {
console.error('Error: No command specified');
cli.showHelp();
process.exit(1);
}
var commands = {
'install': install
};
if (cli.input[0] in commands) {
commands[cli.input[0]].call(undefined, cli.input.splice(1));
}
function install(programList) {
if (programList.length === 0) {
allPrograms.forEach(installProgram);
} else {
programList.forEach(installProgram);
}
}
function installProgram(program) {
if (allPrograms.indexOf(program) === -1) {
console.error('Error: tried to install non-existing program "' + program + '"');
return;
}
require('./' + program).install();
}
| Allow install of multiple programs | Allow install of multiple programs
Fixes #26
| JavaScript | mit | Tyriar/dotfiles,Tyriar/tyr-tools,Tyriar/tyr-tools,Tyriar/dotfiles,Tyriar/dotfiles | ---
+++
@@ -17,9 +17,9 @@
var cli = meow({
help: [
- 'Usage: dotfiles install [<program>]',
+ 'Usage: dotfiles install [<program>...]',
'',
- 'where <program> is one of:',
+ 'where <program> is one or more of of:',
' ' + allPrograms.join(', '),
'',
'Specify no <program> to install everything'
@@ -37,14 +37,14 @@
};
if (cli.input[0] in commands) {
- commands[cli.input[0]].apply(undefined, cli.input.slice(1));
+ commands[cli.input[0]].call(undefined, cli.input.splice(1));
}
function install(programList) {
- if (programList === undefined) {
+ if (programList.length === 0) {
allPrograms.forEach(installProgram);
} else {
- installProgram(programList);
+ programList.forEach(installProgram);
}
}
|
581b9393ac0e0c6a505bedaaf6cbb7d30c0e4f4f | app/components/application/emoji-react-demo.js | app/components/application/emoji-react-demo.js | const script = String.raw`<script type="text/javascript">
var emojis = "tada, fire, grinning"
var selector = "body"
var url = window.location.href.replace(/(http:\/\/|https:\/\/)/gi, '').replace(/^\/|\/$/g, '');
var iframe = document.createElement("iframe")
iframe.src = "https://emojireact.com/embed?emojis=" + emojis.replace(/\s/g, "") + "&url=" + url
iframe.scrolling = "no"
iframe.frameBorder = "0"
iframe.style = "border:none; overflow:hidden; height:35px;"
var container = document.querySelector(selector)
container.insertBefore(iframe, container.firstChild || container)
</script>`
export default function runDemo(app) {
const {embedCodeInput} = app.refs
embedCodeInput.autofocus = false
embedCodeInput.value = script
app.parseInput()
const {option_2} = app.entities
option_2.title = "Comma separated list of emoji names"
app.toggleEntityTracking(option_2.element)
app.route = "embed-code"
}
| import autosize from "autosize"
const script = String.raw`<script type="text/javascript">
var emojis = "tada, fire, grinning"
var selector = "body"
var url = window.location.href.replace(/(http:\/\/|https:\/\/)/gi, '').replace(/^\/|\/$/g, '');
var iframe = document.createElement("iframe")
iframe.src = "https://emojireact.com/embed?emojis=" + emojis.replace(/\s/g, "") + "&url=" + url
iframe.scrolling = "no"
iframe.frameBorder = "0"
iframe.style = "border:none; overflow:hidden; height:35px;"
var container = document.querySelector(selector)
container.insertBefore(iframe, container.firstChild || container)
</script>`
export default function runDemo(app) {
const {embedCodeInput} = app.refs
embedCodeInput.autofocus = false
embedCodeInput.value = script
autosize.update(embedCodeInput)
app.parseInput()
const {option_2} = app.entities
option_2.title = "Comma separated list of emoji names"
app.toggleEntityTracking(option_2.element)
app.route = "embed-code"
}
| Fix issue where demo text does not autosize textarea. | Fix issue where demo text does not autosize textarea.
Closes #8
| JavaScript | mit | EagerIO/InstantPlugin,EagerIO/InstantPlugin | ---
+++
@@ -1,3 +1,5 @@
+import autosize from "autosize"
+
const script = String.raw`<script type="text/javascript">
var emojis = "tada, fire, grinning"
var selector = "body"
@@ -19,6 +21,7 @@
embedCodeInput.autofocus = false
embedCodeInput.value = script
+ autosize.update(embedCodeInput)
app.parseInput()
const {option_2} = app.entities |
41aece86398d40e173f6ed14a633a66b90f804b2 | test/specs/server_spec.js | test/specs/server_spec.js | import test from 'tape';
import { Database, Router, Server } from '../../src';
//
// TODO: Check the same with XHR
//
export const serverSpec = () => {
// @TODO Test Server's config
test('Server # use database', (assert) => {
const myDB = new Database();
const router = new Router();
const server = new Server();
router.get('/posts', (request, db) => {
assert.ok(db == myDB, 'The passed db is the correct one');
assert.end();
});
server.use(myDB);
server.use(router);
fetch('/posts');
});
test('Server # use router', (assert) => {
const router = new Router();
const server = new Server();
router.get('/comments', _ => {
assert.fail('Should not reach this handler since the request is fired before "server.use"');
});
router.get('/users', _ => {
assert.ok(true, 'It must only enter in this handler since the request has been triggered after the registration');
assert.end();
});
fetch('/comments');
server.use(router);
fetch('/users');
});
};
| // @TODO Test Server's config
import test from 'tape';
import { Database, Router, Server } from '../../src';
const xhrRequest = (url) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.send();
}
export const serverSpec = () => {
test('Server # use database', (assert) => {
assert.plan(2);
const myDB = new Database();
const router = new Router();
const server = new Server();
router.get('/posts', (request, db) => {
assert.ok(db == myDB, 'The passed db is the correct one');
});
server.use(myDB);
server.use(router);
fetch('/posts');
xhrRequest('/posts');
});
test('Server # use router', (assert) => {
const router = new Router();
const server = new Server();
router.get('/comments', _ => {
assert.fail('Should not reach this handler since the request is fired before "server.use"');
});
router.get('/users', _ => {
assert.ok(true, 'It must only enter in this handler since the request has been triggered after the registration');
assert.end();
});
fetch('/comments');
server.use(router);
fetch('/users');
});
};
| Check that scenarios works with xhr | Check that scenarios works with xhr
| JavaScript | mit | devlucky/Kakapo.js,devlucky/Kakapo.js | ---
+++
@@ -1,27 +1,31 @@
+// @TODO Test Server's config
import test from 'tape';
import { Database, Router, Server } from '../../src';
-//
-// TODO: Check the same with XHR
-//
+const xhrRequest = (url) => {
+ const xhr = new XMLHttpRequest();
+ xhr.open('GET', url, true);
+ xhr.send();
+}
export const serverSpec = () => {
- // @TODO Test Server's config
+ test('Server # use database', (assert) => {
+ assert.plan(2);
- test('Server # use database', (assert) => {
const myDB = new Database();
const router = new Router();
const server = new Server();
router.get('/posts', (request, db) => {
assert.ok(db == myDB, 'The passed db is the correct one');
- assert.end();
});
server.use(myDB);
server.use(router);
+
fetch('/posts');
+ xhrRequest('/posts');
});
test('Server # use router', (assert) => { |
9702cf0a66e26860102b2a091bc1d1600d200e57 | app/instance-initializers/in-app-livereload.js | app/instance-initializers/in-app-livereload.js | import Ember from 'ember';
const { run } = Ember;
export function initialize(app) {
let config = app.container.lookupFactory('config:environment');
let env = config.environment;
if (config.cordova && config.cordova.reloadUrl &&
(env === 'development' || env === 'test')) {
let url = config.cordova.reloadUrl;
if (window.location.href.indexOf('file://') > -1) {
run.later(function() {
window.location.replace(url);
}, 50);
}
}
}
export default {
name: 'cordova:in-app-livereload',
initialize: initialize
};
| import Ember from 'ember';
const { run } = Ember;
export function initialize(app) {
let config = app.resolveRegistration('config:environment');
let env = config.environment;
if (config.cordova && config.cordova.reloadUrl &&
(env === 'development' || env === 'test')) {
let url = config.cordova.reloadUrl;
if (window.location.href.indexOf('file://') > -1) {
run.later(function() {
window.location.replace(url);
}, 50);
}
}
}
export default {
name: 'cordova:in-app-livereload',
initialize: initialize
};
| Use resolveRegistration rather than container.lookupFactory to lookup the environment. | Use resolveRegistration rather than container.lookupFactory to lookup the environment.
| JavaScript | mit | isleofcode/ember-cordova,isleofcode/corber,isleofcode/ember-cordova,isleofcode/corber | ---
+++
@@ -3,7 +3,7 @@
const { run } = Ember;
export function initialize(app) {
- let config = app.container.lookupFactory('config:environment');
+ let config = app.resolveRegistration('config:environment');
let env = config.environment;
if (config.cordova && config.cordova.reloadUrl && |
e3adf790c0b87f32b83f9b1199268ab8374c9eb8 | src/components/DeviceChart.js | src/components/DeviceChart.js | import React, { PropTypes } from 'react';
import rd3 from 'rd3';
const BarChart = rd3.BarChart;
const barData = [
{
name: 'Series A',
values: [
{ x: 1, y: 91 },
{ x: 2, y: 290 },
{ x: 3, y: 30 },
{ x: 4, y: 50 },
{ x: 5, y: 90 },
{ x: 6, y: 100 },
],
},
];
export class DeviceChart extends React.Component {
componentWillMount() {
console.log(JSON.stringify(this.props.transactions));
}
render() {
return (
<div>
<BarChart
data={barData}
width={700}
height={200}
fill={'#3182bd'}
title="Bar Chart"
xAxisLabel="Recent Transactions"
yAxisLabel="Amount Spent"
/>
</div>
);
}
}
DeviceChart.propTypes = {
transactions: PropTypes.array.isRequired,
};
| import React, { PropTypes } from 'react';
import rd3 from 'rd3';
const BarChart = rd3.BarChart;
export class DeviceChart extends React.Component {
constructor(props) {
super(props);
this.state = {
barData: [
{
values: [
{ x: 1, y: 91 },
{ x: 2, y: 290 },
{ x: 3, y: 30 },
],
},
],
};
}
componentWillMount() {
const length = Math.min(this.props.transactions.length, 6);
const values = [];
for (let i = 0; i < length; i++) {
const newObj = {};
newObj.x = this.props.transactions[i].timestamp;
newObj.y = this.props.transactions[i].amountspent;
values.push(newObj);
}
this.setState({
barData: [
{
values,
},
],
});
}
render() {
return (
<div>
<BarChart
data={this.state.barData}
width={700}
height={200}
fill={'#3182bd'}
title="Bar Chart"
xAxisLabel="Recent Transactions"
yAxisLabel="Amount Spent"
/>
</div>
);
}
}
DeviceChart.propTypes = {
transactions: PropTypes.array.isRequired,
};
| Add data to bar chart | Add data to bar chart
| JavaScript | mit | Bucko13/kinects-it,brnewby602/kinects-it,brnewby602/kinects-it,Kinectsit/kinects-it,Bucko13/kinects-it,Kinectsit/kinects-it | ---
+++
@@ -2,31 +2,47 @@
import rd3 from 'rd3';
const BarChart = rd3.BarChart;
-const barData = [
- {
- name: 'Series A',
- values: [
- { x: 1, y: 91 },
- { x: 2, y: 290 },
- { x: 3, y: 30 },
- { x: 4, y: 50 },
- { x: 5, y: 90 },
- { x: 6, y: 100 },
- ],
- },
-];
export class DeviceChart extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ barData: [
+ {
+ values: [
+ { x: 1, y: 91 },
+ { x: 2, y: 290 },
+ { x: 3, y: 30 },
+ ],
+ },
+ ],
+ };
+ }
+
componentWillMount() {
- console.log(JSON.stringify(this.props.transactions));
+ const length = Math.min(this.props.transactions.length, 6);
+ const values = [];
+ for (let i = 0; i < length; i++) {
+ const newObj = {};
+ newObj.x = this.props.transactions[i].timestamp;
+ newObj.y = this.props.transactions[i].amountspent;
+ values.push(newObj);
+ }
+ this.setState({
+ barData: [
+ {
+ values,
+ },
+ ],
+ });
}
render() {
return (
<div>
<BarChart
- data={barData}
+ data={this.state.barData}
width={700}
height={200}
fill={'#3182bd'} |
d0eace4d14f980d2afd1d8967b0cc9a9cd9a4468 | lib/core/config.js | lib/core/config.js | var async = require('async');
var _ = require('lodash');
var readTOML = require('./utils').readTOML;
var fileExists = require('./utils').fileExists;
var defaults = {
account: {
username: 'admin',
password: 'password',
channel: '#riotgames'
},
irc: {
address: '199.9.253.199'
},
server: {
port: 6667
}
};
function Config(options) {
this['account'] = _.defaults(defaults['account'], options['account']);
this['irc'] = _.defaults(defaults['irc'], options['irc']);
this['server'] = _.defaults(defaults['server'], options['server']);
}
Config.fromFile = function(path, callback) {
async.waterfall([
function(cb) {
fileExists(path, function(exists) {
if (exists) {
readTOML(path, cb);
} else {
cb(new Error("Config file at '" + path + "' does not exist."));
}
});
}, function(options, cb) {
var config = new Config(options);
config.__filename = path;
cb(null, config);
}
], callback);
};
module.exports.Config = Config; | var async = require('async');
var _ = require('lodash');
var readTOML = require('./utils').readTOML;
var fileExists = require('./utils').fileExists;
var defaults = {
account: {
username: 'admin',
password: 'password',
channel: '#riotgames'
},
irc: {
address: '199.9.253.199'
},
server: {
port: 6667
}
};
function Config(options) {
this['account'] = _.defaults(options['account'], defaults['account']);
this['irc'] = _.defaults(options['irc'], defaults['irc']);
this['server'] = _.defaults(options['server'], defaults['server']);
}
Config.fromFile = function(path, callback) {
async.waterfall([
function(cb) {
fileExists(path, function(exists) {
if (exists) {
readTOML(path, cb);
} else {
cb(new Error("Config file at '" + path + "' does not exist."));
}
});
}, function(options, cb) {
var config = new Config(options);
config.__filename = path;
cb(null, config);
}
], callback);
};
module.exports.Config = Config; | Fix incorrect use of `_.defaults` | Fix incorrect use of `_.defaults`
| JavaScript | mit | KenanY/nwitch | ---
+++
@@ -19,9 +19,9 @@
};
function Config(options) {
- this['account'] = _.defaults(defaults['account'], options['account']);
- this['irc'] = _.defaults(defaults['irc'], options['irc']);
- this['server'] = _.defaults(defaults['server'], options['server']);
+ this['account'] = _.defaults(options['account'], defaults['account']);
+ this['irc'] = _.defaults(options['irc'], defaults['irc']);
+ this['server'] = _.defaults(options['server'], defaults['server']);
}
Config.fromFile = function(path, callback) { |
2b86f1e677ff9630159f264d4d89ca73b9fbfd9f | apps/federatedfilesharing/js/settings-admin.js | apps/federatedfilesharing/js/settings-admin.js | $(document).ready(function() {
$('#fileSharingSettings input').change(function() {
var value = 'no';
if (this.checked) {
value = 'yes';
}
OC.AppConfig.setValue('files_sharing', $(this).attr('name'), value);
});
$('.section .icon-info').tipsy({gravity: 'w'});
});
| $(document).ready(function() {
$('#fileSharingSettings input').change(function() {
var value = 'no';
if (this.checked) {
value = 'yes';
}
OC.AppConfig.setValue('files_sharing', $(this).attr('name'), value);
});
});
| Remove unneeded usage of tipsy | Remove unneeded usage of tipsy
* tooltip is already initialized
| JavaScript | agpl-3.0 | jbicha/server,endsguy/server,Ardinis/server,pmattern/server,pixelipo/server,andreas-p/nextcloud-server,pmattern/server,endsguy/server,pixelipo/server,Ardinis/server,michaelletzgus/nextcloud-server,nextcloud/server,xx621998xx/server,whitekiba/server,Ardinis/server,nextcloud/server,jbicha/server,xx621998xx/server,pmattern/server,whitekiba/server,nextcloud/server,xx621998xx/server,nextcloud/server,andreas-p/nextcloud-server,jbicha/server,whitekiba/server,michaelletzgus/nextcloud-server,michaelletzgus/nextcloud-server,whitekiba/server,michaelletzgus/nextcloud-server,Ardinis/server,xx621998xx/server,pixelipo/server,andreas-p/nextcloud-server,Ardinis/server,andreas-p/nextcloud-server,jbicha/server,pixelipo/server,jbicha/server,pmattern/server,endsguy/server,whitekiba/server,pmattern/server,pixelipo/server,endsguy/server,andreas-p/nextcloud-server,xx621998xx/server,endsguy/server | ---
+++
@@ -8,5 +8,4 @@
OC.AppConfig.setValue('files_sharing', $(this).attr('name'), value);
});
- $('.section .icon-info').tipsy({gravity: 'w'});
}); |
566b86d0c11e8def2e018c0bfcae1ca8c7efb4f4 | lib/getGeoFiles.js | lib/getGeoFiles.js | 'use strict';
var fs = require('fs');
var path = require('path');
var nodedir = require('node-dir');
var unzipGeoStream = require('./unzipGeoStream');
function discover(input, counter, callback, silent, afterProcessingCb){
var ext = path.extname(input);
if(ext){
if(ext === '.zip') return unzipGeoStream(input, fs.createReadStream(input), counter, discover, callback);
if(ext === '.gdb'|| ext === '.shp'|| ext === '.json'){
counter.incr();
return callback(null, input, afterProcessingCb);
}
if(silent) return;
return callback(new Error('File type "' + ext + '" unsupported.'), null, afterProcessingCb);
}
return nodedir.files(input, function(err, files){
if(err) callback(err, null, afterProcessingCb);
files.forEach(function(file){
discover(file, counter, callback, 1, afterProcessingCb);
});
});
}
module.exports = discover;
| 'use strict';
var fs = require('fs');
var path = require('path');
var nodedir = require('node-dir');
var unzipGeoStream = require('./unzipGeoStream');
function discover(input, counter, callback, silent, afterProcessingCb){
var ext = path.extname(input);
if(ext){
if(ext === '.zip') return unzipGeoStream(input, fs.createReadStream(input), counter, discover, callback);
if(ext === '.json'|| ext === '.csv' || ext === '.gdb' || ext === '.shp'){
counter.incr();
return callback(null, input, afterProcessingCb);
}
if(silent) return;
return callback(new Error('File type "' + ext + '" unsupported.'), null, afterProcessingCb);
}
return nodedir.files(input, function(err, files){
if(err) callback(err, null, afterProcessingCb);
files.forEach(function(file){
discover(file, counter, callback, 1, afterProcessingCb);
});
});
}
module.exports = discover;
| Allow .csvs to be processed | Allow .csvs to be processed
| JavaScript | cc0-1.0 | awolfe76/grasshopper-loader,awolfe76/grasshopper-loader,cfpb/grasshopper-loader,cfpb/grasshopper-loader | ---
+++
@@ -12,7 +12,7 @@
if(ext){
if(ext === '.zip') return unzipGeoStream(input, fs.createReadStream(input), counter, discover, callback);
- if(ext === '.gdb'|| ext === '.shp'|| ext === '.json'){
+ if(ext === '.json'|| ext === '.csv' || ext === '.gdb' || ext === '.shp'){
counter.incr();
return callback(null, input, afterProcessingCb);
} |
952b351d8a7be859c22f79ea5d2225acf87b3ccb | rng.js | rng.js | function get(i){
return document.getElementById(i)
}
function random_number(){
if(value('repeat')<1){
get('repeat').value=1
}
i=value('repeat')-1;
range=parseInt(value('range'))+1;
do{
result+=Math.floor(Math.random()*range+value('base'))+' '
}while(i--);
get('result').innerHTML=result;
result=''
}
function reset(){
if(confirm('Reset settings?')){
get('base').value=0;
get('range').value=10;
get('repeat').value=1;
get('result').innerHTML=''
}
}
function value(i){
return get(i).value
}
var i=range=2,
result='';
window.onkeydown=function(e){
i=window.event?event:e;
i=i.charCode?i.charCode:i.keyCode;
if(i==72){
random_number()
}
}
| function random_number(){
save();
i=value('repeat')-1;
range=parseInt(value('range'))+1;
do{
result+=Math.floor(Math.random()*range+value('base'))+' '
}while(i--);
get('result').innerHTML=result;
result=''
}
function reset(){
if(confirm('Reset settings?')){
get('base').value=0;
get('range').value=10;
get('repeat').value=1;
get('result').innerHTML='';
save()
}
}
function save(){
if(value('repeat')<1){
get('repeat').value=1
}
i=2;
j=['base','range','repeat'];
do{
if(isNaN(value(j[i]))||value(j[i])==[0,10,1][i]){
get(j[i]).value=[0,10,1][i];
ls.removeItem('rng'+i)
}else{
ls.setItem('rng'+i,value(j[i]))
}
}while(i--);
j=''
}
function get(i){
return document.getElementById(i)
}
function value(i){
return get(i).value
}
var i=range=2,
ls=window.localStorage,
j=result='';
get('base').value=ls.getItem('rng0')==null?0:ls.getItem('rng0');
get('range').value=ls.getItem('rng1')==null?10:ls.getItem('rng1');
get('repeat').value=ls.getItem('rng2')==null?1:ls.getItem('rng2');
window.onkeydown=function(e){
i=window.event?event:e;
i=i.charCode?i.charCode:i.keyCode;
if(i==72){
random_number()
}
}
| Save input values to localStorage | Save input values to localStorage
| JavaScript | cc0-1.0 | iterami/RNG.htm,iterami/RNG.htm | ---
+++
@@ -1,10 +1,5 @@
-function get(i){
- return document.getElementById(i)
-}
function random_number(){
- if(value('repeat')<1){
- get('repeat').value=1
- }
+ save();
i=value('repeat')-1;
range=parseInt(value('range'))+1;
do{
@@ -18,14 +13,41 @@
get('base').value=0;
get('range').value=10;
get('repeat').value=1;
- get('result').innerHTML=''
+ get('result').innerHTML='';
+ save()
}
+}
+function save(){
+ if(value('repeat')<1){
+ get('repeat').value=1
+ }
+ i=2;
+ j=['base','range','repeat'];
+ do{
+ if(isNaN(value(j[i]))||value(j[i])==[0,10,1][i]){
+ get(j[i]).value=[0,10,1][i];
+ ls.removeItem('rng'+i)
+ }else{
+ ls.setItem('rng'+i,value(j[i]))
+ }
+ }while(i--);
+ j=''
+}
+function get(i){
+ return document.getElementById(i)
}
function value(i){
return get(i).value
}
+
var i=range=2,
-result='';
+ls=window.localStorage,
+j=result='';
+
+get('base').value=ls.getItem('rng0')==null?0:ls.getItem('rng0');
+get('range').value=ls.getItem('rng1')==null?10:ls.getItem('rng1');
+get('repeat').value=ls.getItem('rng2')==null?1:ls.getItem('rng2');
+
window.onkeydown=function(e){
i=window.event?event:e;
i=i.charCode?i.charCode:i.keyCode; |
79adb264ac417a93ca252e66750076fd937142f1 | lib/request-jwt.js | lib/request-jwt.js | var TokenCache = require('./token-cache'),
tokens = new TokenCache();
/**
* Returns a JWT-enabled request module.
* @param request The request instance to modify to enable JWT.
* @returns {Function} The JWT-enabled request module.
*/
exports.requestWithJWT = function (request) {
if (!request) {
// use the request module from our dependency
request = require('request');
}
return function (uri, options, callback) {
if (typeof uri === 'undefined') throw new Error('undefined is not a valid uri or options object.');
if ((typeof options === 'function') && !callback) callback = options;
if (options && typeof options === 'object') {
options.uri = uri;
} else if (typeof uri === 'string') {
options = {uri: uri};
} else {
options = uri;
}
if (callback) options.callback = callback;
// look for a request with JWT requirement
if (options.jwt) {
return tokens.get(options.jwt, function (err, token) {
if (err) return callback(err);
// TODO: for now the token is only passed using the query string
options.qs = options.qs || {};
options.qs.access_token = token;
return request(uri, options, callback);
});
} else {
return request(uri, options, callback);
}
};
};
/**
* Resets the token cache, clearing previously requested tokens.
*/
exports.resetCache = function () {
tokens.clear();
};
| var TokenCache = require('./token-cache'),
tokens = new TokenCache();
/**
* Returns a JWT-enabled request module.
* @param request The request instance to modify to enable JWT.
* @returns {Function} The JWT-enabled request module.
*/
exports.requestWithJWT = function (request) {
if (!request) {
// use the request module from our dependency
request = require('request');
}
return function (uri, options, callback) {
if (typeof uri === 'undefined') throw new Error('undefined is not a valid uri or options object.');
if ((typeof options === 'function') && !callback) callback = options;
if (options && typeof options === 'object') {
options.uri = uri;
} else if (typeof uri === 'string') {
options = {uri: uri};
} else {
options = uri;
}
if (callback) options.callback = callback;
// look for a request with JWT requirement
if (options.jwt) {
return tokens.get(options.jwt, function (err, token) {
if (err) return callback(err);
options.headers = options.headers || {};
options.headers.authorization = 'Bearer ' + token;
return request(uri, options, callback);
});
} else {
return request(uri, options, callback);
}
};
};
/**
* Resets the token cache, clearing previously requested tokens.
*/
exports.resetCache = function () {
tokens.clear();
};
| Use the Authorization request header field to send the token. | Use the Authorization request header field to send the token.
Per http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-14#section-2.1
this is the recommended approach which must be supported by all servers.
| JavaScript | mit | extrabacon/google-oauth-jwt,0xPIT/google-oauth-jwt | ---
+++
@@ -32,9 +32,8 @@
if (err) return callback(err);
- // TODO: for now the token is only passed using the query string
- options.qs = options.qs || {};
- options.qs.access_token = token;
+ options.headers = options.headers || {};
+ options.headers.authorization = 'Bearer ' + token;
return request(uri, options, callback);
}); |
1634fe192df5994ce9ce4b323de89f5351fbfffb | htdocs/components/00_jquery_togglebutton.js | htdocs/components/00_jquery_togglebutton.js | /*
* Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function($) {
$(function() {
$.fn.toggleButtons = function () {
return this.each(function () {
var $this = $(this);
$this.click(function() {
$this.toggleClass('off');
var url = $this.attr('href');
if(url) {
$.ajax({
url: url,
type: 'POST',
traditional: true,
cache: false,
context: this
}).fail(function() {
$this.toggleClass('off');
});
}
return false;
});
});
};
});
})(jQuery);
| /*
* Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function($) {
$(function() {
$.fn.toggleButtons = function () {
return this.each(function () {
var $this = $(this);
$this.click(function() {
$this.toggleClass('off');
var url = $this.attr('href');
if(url) {
$.ajax({
url: url,
type: 'POST',
traditional: true,
cache: false,
context: this,
data: {
state: $this.hasClass('off')?0:1
}
}).fail(function() {
$this.toggleClass('off');
});
}
return false;
});
});
};
});
})(jQuery);
| Send button state for toggle buttons. | Send button state for toggle buttons.
| JavaScript | apache-2.0 | Ensembl/ensembl-webcode,Ensembl/ensembl-webcode,Ensembl/ensembl-webcode,Ensembl/ensembl-webcode,Ensembl/ensembl-webcode | ---
+++
@@ -28,7 +28,10 @@
type: 'POST',
traditional: true,
cache: false,
- context: this
+ context: this,
+ data: {
+ state: $this.hasClass('off')?0:1
+ }
}).fail(function() {
$this.toggleClass('off');
}); |
7e894bf4593a3ce542ae8bfd9af05835712497e7 | src/Our.Umbraco.Nexu.Web/App_Plugins/Nexu/controllers/related-links-app-controller.js | src/Our.Umbraco.Nexu.Web/App_Plugins/Nexu/controllers/related-links-app-controller.js | (function () {
'use strict';
function RelatedLinksAppController($scope) {
var vm = this;
vm.relations = $scope.model.viewModel;
var currentVariant = _.find($scope.content.variants, function(v) { return v.active });
vm.culture = currentVariant.language.culture;
vm.cultureRelations = _.filter(vm.relations, function (r) { return r.Culture.toLowerCase() === vm.culture.toLowerCase() });
vm.ungrouped = [];
for (var i = 0; i < vm.cultureRelations.length; i++) {
var relation = vm.cultureRelations[i];
for (var j = 0; j < relation.Properties.length; j++) {
vm.ungrouped.push({
id: relation.Id,
name: relation.Name,
propertyname: relation.Properties[j].PropertyName,
tabname: relation.Properties[j].TabName
});
}
}
}
angular.module('umbraco').controller('Our.Umbraco.Nexu.Controllers.RelatedLinksAppController',
[
'$scope',
'editorState',
'localizationService',
RelatedLinksAppController
]);
})(); | (function () {
'use strict';
function RelatedLinksAppController($scope) {
var vm = this;
vm.relations = $scope.model.viewModel;
var currentVariant = _.find($scope.content.variants, function (v) { return v.active });
if (currentVariant.language) {
vm.culture = currentVariant.language.culture;
vm.cultureRelations = _.filter(vm.relations,
function(r) { return r.Culture.toLowerCase() === vm.culture.toLowerCase() });
} else {
vm.cultureRelations = vm.relations;
}
vm.ungrouped = [];
for (var i = 0; i < vm.cultureRelations.length; i++) {
var relation = vm.cultureRelations[i];
for (var j = 0; j < relation.Properties.length; j++) {
vm.ungrouped.push({
id: relation.Id,
name: relation.Name,
propertyname: relation.Properties[j].PropertyName,
tabname: relation.Properties[j].TabName
});
}
}
}
angular.module('umbraco').controller('Our.Umbraco.Nexu.Controllers.RelatedLinksAppController',
[
'$scope',
'editorState',
'localizationService',
RelatedLinksAppController
]);
})(); | Make sure content app works when there are no variants | Make sure content app works when there are no variants
| JavaScript | mit | dawoe/umbraco-nexu,dawoe/umbraco-nexu,dawoe/umbraco-nexu | ---
+++
@@ -5,9 +5,17 @@
var vm = this;
vm.relations = $scope.model.viewModel;
- var currentVariant = _.find($scope.content.variants, function(v) { return v.active });
- vm.culture = currentVariant.language.culture;
- vm.cultureRelations = _.filter(vm.relations, function (r) { return r.Culture.toLowerCase() === vm.culture.toLowerCase() });
+ var currentVariant = _.find($scope.content.variants, function (v) { return v.active });
+
+ if (currentVariant.language) {
+ vm.culture = currentVariant.language.culture;
+ vm.cultureRelations = _.filter(vm.relations,
+ function(r) { return r.Culture.toLowerCase() === vm.culture.toLowerCase() });
+ } else {
+ vm.cultureRelations = vm.relations;
+ }
+
+
vm.ungrouped = [];
|
89a9146eb112386279c5bfb54845e93a571b62a7 | www/mobitorSecure.js | www/mobitorSecure.js | module.exports = {
isSecure: function (successCallback, errorCallback) {
cordova.exec(successCallback, errorCallback, "MobitorSecure", "isSecure", [null]);
}
}; | module.exports = {
isSecure: function (successCallback, errorCallback) {
cordova.exec(successCallback, errorCallback, "MobitorSecure", "isSecured", [null]);
}
}; | Fix method and add d to isSecure | Fix method and add d to isSecure
| JavaScript | mit | jmoore6364/mobitor-cordova-secure,jmoore6364/mobitor-cordova-secure | ---
+++
@@ -1,5 +1,5 @@
module.exports = {
isSecure: function (successCallback, errorCallback) {
- cordova.exec(successCallback, errorCallback, "MobitorSecure", "isSecure", [null]);
+ cordova.exec(successCallback, errorCallback, "MobitorSecure", "isSecured", [null]);
}
}; |
f95cf530a32f0637536e606d864139d0cde80372 | test/compressJavaScript-test.js | test/compressJavaScript-test.js | var vows = require('vows'),
assert = require('assert'),
AssetGraph = require('../lib/AssetGraph');
vows.describe('transforms.compressJavaScript').addBatch(function () {
var test = {};
[undefined, 'uglifyJs', 'yuicompressor', 'closurecompiler'].forEach(function (compressorName) {
test[String(compressorName)] = {
topic: function () {
var assetGraph = new AssetGraph();
assetGraph.addAsset(new AssetGraph.JavaScript({text: "var foo = 123;"}));
assetGraph.compressJavaScript({type: 'JavaScript'}, compressorName).run(this.callback);
},
'should yield a compressed JavaScript': function (assetGraph) {
var javaScripts = assetGraph.findAssets({type: 'JavaScript'});
assert.equal(javaScripts.length, 1);
assert.matches(javaScripts[0].text, /^var foo=123;?\n?$/);
}
};
});
return test;
}())['export'](module);
| var vows = require('vows'),
assert = require('assert'),
AssetGraph = require('../lib/AssetGraph');
vows.describe('transforms.compressJavaScript').addBatch(function () {
var test = {};
// The YUICompressor and ClosureCompiler tests fail intermittently on Travis
[undefined, 'uglifyJs'/*, 'yuicompressor', 'closurecompiler'*/].forEach(function (compressorName) {
test[String(compressorName)] = {
topic: function () {
var assetGraph = new AssetGraph();
assetGraph.addAsset(new AssetGraph.JavaScript({text: "var foo = 123;"}));
assetGraph.compressJavaScript({type: 'JavaScript'}, compressorName).run(this.callback);
},
'should yield a compressed JavaScript': function (assetGraph) {
var javaScripts = assetGraph.findAssets({type: 'JavaScript'});
assert.equal(javaScripts.length, 1);
assert.matches(javaScripts[0].text, /^var foo=123;?\n?$/);
}
};
});
return test;
}())['export'](module);
| Disable the YUICompressor and closure compiler tests | Disable the YUICompressor and closure compiler tests
They're annoying because the fail on Travis half of the time. | JavaScript | bsd-3-clause | jscinoz/assetgraph,jscinoz/assetgraph,papandreou/assetgraph,papandreou/assetgraph,assetgraph/assetgraph,jscinoz/assetgraph,papandreou/assetgraph | ---
+++
@@ -4,7 +4,8 @@
vows.describe('transforms.compressJavaScript').addBatch(function () {
var test = {};
- [undefined, 'uglifyJs', 'yuicompressor', 'closurecompiler'].forEach(function (compressorName) {
+ // The YUICompressor and ClosureCompiler tests fail intermittently on Travis
+ [undefined, 'uglifyJs'/*, 'yuicompressor', 'closurecompiler'*/].forEach(function (compressorName) {
test[String(compressorName)] = {
topic: function () {
var assetGraph = new AssetGraph(); |
801e990ae4b3433ab1800bbdfd6d8c9921fc2029 | controllers/api.js | controllers/api.js | 'use strict';
/**
* GET /api/challenges
* List of challenges.
*/
exports.getChallenges = function getChallenges(req, res) {
res.json({ challenges: [] });
};
/**
* POST /api/challenges
* Create new challenges.
*/
exports.postChallenges = function postChallenges(req, res) {
res.status(201).send("Created new challenge");
}
| 'use strict';
/**
* GET /api/challenges
* List of challenges.
*/
exports.getChallenges = function get(req, res) {
res.json({ challenges: [] });
};
/**
* POST /api/challenges/:challengeId
* Created a new challenge.
*/
exports.postChallenge = function post(req, res) {
res.status(201).send("Created new challenge");
}
/**
* PUT /api/challenges/:challengeId
* Updated a new challenge.
*/
exports.putChallenge = function put(req, res) {
res.status(201).send("Update challenge");
}
/**
* DELETE /api/challenges/:challengeId
* Delete a challenge.
*/
exports.deleteChallenge = function deleteChallenge(req, res) {
res.status(204).send("Delete challenge");
}
/**
* GET /api/teams
* List of teams.
*/
exports.getTeams = function get(req, res) {
res.json({ teams: [] });
};
/**
* POST /api/teams/:teamId
* Create new challenges.
*/
exports.postTeam = function post(req, res) {
res.status(201).send("Created new team");
}
/**
* POST /api/teams
* Create new team.
*/
exports.putTeam = function put(req, res) {
res.status(201).send("Updated a team");
}
/**
* POST /api/teams/:teamId
* Delete a team by id.
*/
exports.deleteTeam = function deleteTeam(req, res) {
res.status(204).send("Deleted a team");
}
| Update API controller with team and challenge routes | Update API controller with team and challenge routes
| JavaScript | mit | lostatseajoshua/Challenger | ---
+++
@@ -1,17 +1,65 @@
'use strict';
/**
- * GET /api/challenges
- * List of challenges.
- */
-exports.getChallenges = function getChallenges(req, res) {
+* GET /api/challenges
+* List of challenges.
+*/
+exports.getChallenges = function get(req, res) {
res.json({ challenges: [] });
};
/**
- * POST /api/challenges
- * Create new challenges.
- */
-exports.postChallenges = function postChallenges(req, res) {
+* POST /api/challenges/:challengeId
+* Created a new challenge.
+*/
+exports.postChallenge = function post(req, res) {
res.status(201).send("Created new challenge");
}
+
+/**
+* PUT /api/challenges/:challengeId
+* Updated a new challenge.
+*/
+exports.putChallenge = function put(req, res) {
+ res.status(201).send("Update challenge");
+}
+
+/**
+* DELETE /api/challenges/:challengeId
+* Delete a challenge.
+*/
+exports.deleteChallenge = function deleteChallenge(req, res) {
+ res.status(204).send("Delete challenge");
+}
+
+/**
+* GET /api/teams
+* List of teams.
+*/
+exports.getTeams = function get(req, res) {
+ res.json({ teams: [] });
+};
+
+/**
+* POST /api/teams/:teamId
+* Create new challenges.
+*/
+exports.postTeam = function post(req, res) {
+ res.status(201).send("Created new team");
+}
+
+/**
+* POST /api/teams
+* Create new team.
+*/
+exports.putTeam = function put(req, res) {
+ res.status(201).send("Updated a team");
+}
+
+/**
+* POST /api/teams/:teamId
+* Delete a team by id.
+*/
+exports.deleteTeam = function deleteTeam(req, res) {
+ res.status(204).send("Deleted a team");
+} |
015f87577e6296419fcf3747629cf095681a2e8f | app/javascript/app/components/compare/compare-ndc-content-overview/compare-ndc-content-overview-selectors.js | app/javascript/app/components/compare/compare-ndc-content-overview/compare-ndc-content-overview-selectors.js | import { createSelector } from 'reselect';
import isEmpty from 'lodash/isEmpty';
import {
parseSelectedLocations,
getSelectedLocationsFilter,
addSelectedNameToLocations
} from 'selectors/compare';
// values from search
const getSelectedLocations = state => state.selectedLocations || null;
const getContentOverviewData = state => state.ndcContentOverviewData || null;
const getCountriesData = state => state.countriesData || null;
const parseLocations = parseSelectedLocations(getSelectedLocations);
export const getLocationsFilter = getSelectedLocationsFilter(
getSelectedLocations
);
export const addNameToLocations = addSelectedNameToLocations(
getCountriesData,
parseLocations
);
export const getSummaryText = createSelector(
[addNameToLocations, getContentOverviewData],
(selectedLocations, data) => {
if (!selectedLocations || !data || isEmpty(data)) return null;
return selectedLocations.map(l => {
const d = data[l.iso_code3];
const text =
d && d.values && d.values.find(v => v.slug === 'indc_summary').value;
return { ...l, text };
});
}
);
export default {
getSummaryText,
getLocationsFilter
};
| import { createSelector } from 'reselect';
import isEmpty from 'lodash/isEmpty';
import {
parseSelectedLocations,
getSelectedLocationsFilter,
addSelectedNameToLocations
} from 'selectors/compare';
// values from search
const getSelectedLocations = state => state.selectedLocations || null;
const getContentOverviewData = state => state.ndcContentOverviewData || null;
const getCountriesData = state => state.countriesData || null;
const parseLocations = parseSelectedLocations(getSelectedLocations);
export const getLocationsFilter = getSelectedLocationsFilter(
getSelectedLocations
);
export const addNameToLocations = addSelectedNameToLocations(
getCountriesData,
parseLocations
);
export const getSummaryText = createSelector(
[addNameToLocations, getContentOverviewData],
(selectedLocations, data) => {
if (!selectedLocations || !data || isEmpty(data)) return null;
return selectedLocations.map(l => {
const d = data[l.iso_code3];
const text =
d && d.values && d.values.find(v => v.slug === 'indc_summary');
return { ...l, text: text && text.value };
});
}
);
export default {
getSummaryText,
getLocationsFilter
};
| Fix crashing bug: Compare Libya | Fix crashing bug: Compare Libya
| JavaScript | mit | Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch | ---
+++
@@ -27,8 +27,8 @@
return selectedLocations.map(l => {
const d = data[l.iso_code3];
const text =
- d && d.values && d.values.find(v => v.slug === 'indc_summary').value;
- return { ...l, text };
+ d && d.values && d.values.find(v => v.slug === 'indc_summary');
+ return { ...l, text: text && text.value };
});
}
); |
c554a2b89f64b9f522a16d3080d8c81990b09d82 | app.js | app.js | /**
* App Dependencies.
*/
var loopback = require('loopback')
, app = module.exports = loopback()
, fs = require('fs')
, path = require('path')
, request = require('request')
, TaskEmitter = require('sl-task-emitter');
// expose a rest api
app.use(loopback.rest());
// Add static files
app.use(loopback.static(path.join(__dirname, 'public')));
// require models
fs
.readdirSync('./models')
.filter(function (m) {
return path.extname(m) === '.js';
})
.forEach(function (m) {
// expose model over rest
app.model(require('./models/' + m));
});
// enable docs
app.docs({basePath: 'http://localhost:3000'});
// start the server
app.listen(3000);
| /**
* App Dependencies.
*/
var loopback = require('loopback')
, app = module.exports = loopback()
, fs = require('fs')
, path = require('path')
, request = require('request')
, TaskEmitter = require('sl-task-emitter');
// expose a rest api
app.use(loopback.rest());
// Add static files
app.use(loopback.static(path.join(__dirname, 'public')));
// require models
fs
.readdirSync(path.join(__dirname, './models'))
.filter(function (m) {
return path.extname(m) === '.js';
})
.forEach(function (m) {
// expose model over rest
app.model(require('./models/' + m));
});
// enable docs
app.docs({basePath: 'http://localhost:3000'});
// start the server
app.listen(3000);
| Make it working directory independent | Make it working directory independent
| JavaScript | mit | strongloop-bluemix/loopback-example-app,svennam92/loopback-example-app,hacksparrow/loopback-example-app,sam-github/sls-sample-app,jewelsjacobs/loopback-example-app,jewelsjacobs/loopback-example-app,rvennam/loopback-example-app,svennam92/loopback-example-app,rvennam/loopback-example-app,Joddsson/loopback-example-app,rvennam/loopback-example-app,p5150j/loopback-example-app,svennam92/loopback-example-app,strongloop-bluemix/loopback-example-app,hacksparrow/loopback-example-app,craigcabrey/loopback-example-app,amenadiel/loopback-apidoc-bridge,syzer/sls-sample-app,craigcabrey/loopback-example-app,Joddsson/loopback-example-app,imkven/loopback-example-app,strongloop-bluemix/loopback-example-app,p5150j/loopback-example-app,genecyber/loopback-example-app | ---
+++
@@ -17,7 +17,7 @@
// require models
fs
- .readdirSync('./models')
+ .readdirSync(path.join(__dirname, './models'))
.filter(function (m) {
return path.extname(m) === '.js';
}) |
6a1d280e8a0f576b4129b7fe5ca71ba93a1095b6 | components/Fork.js | components/Fork.js | import React from 'react'
import { makeStyles } from '@material-ui/core/styles'
import Fab from '@material-ui/core/Fab'
import Badge from '@material-ui/core/Badge'
const useStyles = makeStyles(() => ({
fork: {
position: 'absolute',
right: 30,
top: 30
}
}))
const Fork = ({ stars }) => {
const classes = useStyles()
return (
<div className={classes.fork}>
<Badge badgeContent={stars || 0} max={999} color="primary">
<Fab
variant="extended"
href="https://github.com/ooade/NextSimpleStarter"
target="_blank"
>
Fork me
</Fab>
</Badge>
</div>
)
}
export default Fork
| import React from 'react'
import { makeStyles } from '@material-ui/core/styles'
import Fab from '@material-ui/core/Fab'
import Badge from '@material-ui/core/Badge'
const useStyles = makeStyles(() => ({
fork: {
position: 'absolute',
right: 30,
top: 30
}
}))
const Fork = ({ stars }) => {
const classes = useStyles()
return (
<div className={classes.fork}>
<Badge badgeContent={stars || 0} max={999} color="primary">
<Fab
target="_blank"
variant="extended"
rel="noreferrer noopener"
href="https://github.com/ooade/NextSimpleStarter"
>
Fork me
</Fab>
</Badge>
</div>
)
}
export default Fork
| Add rel on fork link | Add rel on fork link
| JavaScript | mit | ooade/NextSimpleStarter | ---
+++
@@ -17,9 +17,10 @@
<div className={classes.fork}>
<Badge badgeContent={stars || 0} max={999} color="primary">
<Fab
+ target="_blank"
variant="extended"
+ rel="noreferrer noopener"
href="https://github.com/ooade/NextSimpleStarter"
- target="_blank"
>
Fork me
</Fab> |
2d94f56750717d4a6479b8eed940b103b53a0f61 | rollup.config.js | rollup.config.js | import sourcemaps from 'rollup-plugin-sourcemaps';
export const globals = {
// Apollo
'apollo-client': 'apollo.core',
'apollo-link': 'apolloLink.core',
'apollo-link-batch': 'apolloLink.batch',
'apollo-utilities': 'apollo.utilities',
'zen-observable-ts': 'apolloLink.zenObservable',
//GraphQL
'graphql/language/printer': 'printer',
'zen-observable': 'Observable',
};
export default name => ({
input: 'lib/index.js',
output: {
file: 'lib/bundle.umd.js',
format: 'umd',
name: `apolloLink.${name}`,
globals,
sourcemap: true,
exports: 'named',
},
external: Object.keys(globals),
onwarn,
plugins: [sourcemaps()],
});
export function onwarn(message) {
const suppressed = ['UNRESOLVED_IMPORT', 'THIS_IS_UNDEFINED'];
if (!suppressed.find(code => message.code === code)) {
return console.warn(message.message);
}
}
| import sourcemaps from 'rollup-plugin-sourcemaps';
export const globals = {
// Apollo
'apollo-client': 'apollo.core',
'apollo-link': 'apolloLink.core',
'apollo-link-batch': 'apolloLink.batch',
'apollo-utilities': 'apollo.utilities',
'apollo-link-http-common': 'apolloLink.utilities',
'zen-observable-ts': 'apolloLink.zenObservable',
//GraphQL
'graphql/language/printer': 'printer',
'zen-observable': 'Observable',
};
export default name => ({
input: 'lib/index.js',
output: {
file: 'lib/bundle.umd.js',
format: 'umd',
name: `apolloLink.${name}`,
globals,
sourcemap: true,
exports: 'named',
},
external: Object.keys(globals),
onwarn,
plugins: [sourcemaps()],
});
export function onwarn(message) {
const suppressed = ['UNRESOLVED_IMPORT', 'THIS_IS_UNDEFINED'];
if (!suppressed.find(code => message.code === code)) {
return console.warn(message.message);
}
}
| Add missing global Rollup alias for apollo-link-http-common | Add missing global Rollup alias for apollo-link-http-common
This fixes #521, making it so that the apollo-link-http bundle resolves
apollo-link-http-common to global.apolloLink.utilities instead of
global.apolloLinkHttpCommon (which does not exist).
| JavaScript | mit | apollographql/apollo-link,apollographql/apollo-link | ---
+++
@@ -6,6 +6,7 @@
'apollo-link': 'apolloLink.core',
'apollo-link-batch': 'apolloLink.batch',
'apollo-utilities': 'apollo.utilities',
+ 'apollo-link-http-common': 'apolloLink.utilities',
'zen-observable-ts': 'apolloLink.zenObservable',
//GraphQL |
b52476d5f5c59cc2f0d5df2270b4f35b86b166c0 | core/src/action.js | core/src/action.js | const elements = document.querySelectorAll('bracket-less');
function doAction(e) {
if (e.target.tagName !== 'BRACKET-LESS') return;
e.target.classList.toggle('bracket-less');
e.stopPropagation();
}
document.body.addEventListener('click', doAction);
function toggleCollapse(state) {
if (state.collapse) { // play -> text collapsed
elements.forEach(el => el.classList.add('bracket-less'));
} else { // pause -> text displayed
elements.forEach(el => el.classList.remove('bracket-less'));
}
}
chrome.runtime.onMessage.addListener(state => toggleCollapse(state));
| const elements = document.querySelectorAll('bracket-less');
function doAction(e) {
e.stopPropagation();
if (e.target.tagName !== 'BRACKET-LESS') return;
e.target.classList.toggle('bracket-less');
}
document.body.addEventListener('click', doAction);
function toggleCollapse(state) {
if (state.collapse) { // play -> text collapsed
elements.forEach(el => el.classList.add('bracket-less'));
} else { // pause -> text displayed
elements.forEach(el => el.classList.remove('bracket-less'));
}
}
chrome.runtime.onMessage.addListener(state => toggleCollapse(state));
| Stop propogation in any case | Stop propogation in any case
| JavaScript | isc | mrv1k/bracketless,mrv1k/bracketless | ---
+++
@@ -1,9 +1,11 @@
const elements = document.querySelectorAll('bracket-less');
function doAction(e) {
+ e.stopPropagation();
+
if (e.target.tagName !== 'BRACKET-LESS') return;
+
e.target.classList.toggle('bracket-less');
- e.stopPropagation();
}
document.body.addEventListener('click', doAction); |
dd1fa20110373e12ac2b9a67ace0d6cf4dabea0c | pages/_document.js | pages/_document.js | import React from 'react'
import Document, { Head, Main, NextScript } from 'next/document'
import stylesheet from 'pages/styles.scss'
export default class MyDocument extends Document {
render () {
return (
<html>
<Head>
<meta charSet='utf-8' />
<meta name='viewport' content='width=device-width, initial-scale=1' />
<link rel='preload' href='https://fonts.googleapis.com/css?family=Lato' as='style' />
</Head>
<body>
<style dangerouslySetInnerHTML={{ __html: stylesheet }} />
<Main />
<NextScript />
</body>
</html>
)
}
}
| import React from 'react'
import Document, { Head, Main, NextScript } from 'next/document'
import stylesheet from './styles.scss'
export default class MyDocument extends Document {
render () {
return (
<html>
<Head>
<meta charSet='utf-8' />
<meta name='viewport' content='width=device-width, initial-scale=1' />
<style dangerouslySetInnerHTML={{ __html: stylesheet }} />
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
)
}
}
| Move base style in the header | Move base style in the header
| JavaScript | mit | bmagic/acdh-client | ---
+++
@@ -1,6 +1,6 @@
import React from 'react'
import Document, { Head, Main, NextScript } from 'next/document'
-import stylesheet from 'pages/styles.scss'
+import stylesheet from './styles.scss'
export default class MyDocument extends Document {
render () {
@@ -9,10 +9,9 @@
<Head>
<meta charSet='utf-8' />
<meta name='viewport' content='width=device-width, initial-scale=1' />
- <link rel='preload' href='https://fonts.googleapis.com/css?family=Lato' as='style' />
+ <style dangerouslySetInnerHTML={{ __html: stylesheet }} />
</Head>
<body>
- <style dangerouslySetInnerHTML={{ __html: stylesheet }} />
<Main />
<NextScript />
</body> |
a5429590312ce43effd710e22d8892c33b571d85 | app/lib/main.js | app/lib/main.js | 'use strict';
/*jshint unused:false, newcap:false*/
/**
* Enable dubug mode
* This allow to console.log in a firefox default configuration
*/
require('sdk/preferences/service').set('extensions.sdk.console.logLevel', 'debug');
var data = require('sdk/self').data;
var { PageMod } = require('sdk/page-mod');
// Create a content script
var pageMod = PageMod({
include: ['*.github.com'], // Work only on Github URLs
contentScriptFile: [data.url('contentscript.js')],
contentScriptWhen: 'end'
});
| 'use strict';
/*jshint unused:false, newcap:false*/
/**
* Enable dubug mode
* This allow to console.log in a firefox default configuration
*/
require('sdk/preferences/service').set('extensions.sdk.console.logLevel', 'debug');
var data = require('sdk/self').data;
var { PageMod } = require('sdk/page-mod');
// Work only on Github URLs
var matchPatterns = [ '*.github.com' ];
// Create a content script
var scriptMod = PageMod({
include : matchPatterns,
contentScriptFile : [data.url('contentscript.js')],
contentScriptWhen : 'end'
});
// Load the CSS file at document start
var cssMod = PageMod({
include : matchPatterns,
contentStyleFile : [data.url('style.css')],
contentScriptWhen : 'start'
});
| Load the style file in Firefox version as well. | Load the style file in Firefox version as well.
| JavaScript | mpl-2.0 | musically-ut/github-forks-addon,musically-ut/lovely-forks,musically-ut/lovely-forks | ---
+++
@@ -10,9 +10,19 @@
var data = require('sdk/self').data;
var { PageMod } = require('sdk/page-mod');
+// Work only on Github URLs
+var matchPatterns = [ '*.github.com' ];
+
// Create a content script
-var pageMod = PageMod({
- include: ['*.github.com'], // Work only on Github URLs
- contentScriptFile: [data.url('contentscript.js')],
- contentScriptWhen: 'end'
+var scriptMod = PageMod({
+ include : matchPatterns,
+ contentScriptFile : [data.url('contentscript.js')],
+ contentScriptWhen : 'end'
});
+
+// Load the CSS file at document start
+var cssMod = PageMod({
+ include : matchPatterns,
+ contentStyleFile : [data.url('style.css')],
+ contentScriptWhen : 'start'
+}); |
0b49d0bb7a4dc577c0664775f2c53d86c3c6f486 | greasemonkey-endomondo-design.user.js | greasemonkey-endomondo-design.user.js | // ==UserScript==
// @name Greasemonkey EndomondoDesign
// @namespace https://github.com/JanisE
// @include *www.endomondo.com/*
// @version 1
// @grant none
// ==/UserScript==
var css = document.createElement('style');
css.type = 'text/css';
css.innerHTML = ".feedItem-footer .eoAvatar-image {visibility: hidden} .eoFeedWorkout-right {display: none}";
document.head.appendChild(css);
| // ==UserScript==
// @name Greasemonkey EndomondoDesign
// @namespace https://github.com/JanisE
// @description Project URL: https://github.com/JanisE/greasemonkey-endomondo-design
// @include *www.endomondo.com/*
// @version 1
// @grant none
// ==/UserScript==
var css = document.createElement('style');
css.type = 'text/css';
css.innerHTML = ".feedItem-footer .eoAvatar-image {visibility: hidden} .eoFeedWorkout-right {display: none}";
document.head.appendChild(css);
| Add a back-reference to the repository. | Add a back-reference to the repository.
| JavaScript | mit | JanisE/greasemonkey-endomondo-design | ---
+++
@@ -1,6 +1,7 @@
// ==UserScript==
// @name Greasemonkey EndomondoDesign
// @namespace https://github.com/JanisE
+// @description Project URL: https://github.com/JanisE/greasemonkey-endomondo-design
// @include *www.endomondo.com/*
// @version 1
// @grant none |
01526d30ab470b2872ac98f62d6a8712d78eddbc | tools/main-transpile-wrapper.js | tools/main-transpile-wrapper.js | // This file exists because it is the file in the tool that is not automatically
// transpiled by Babel
function babelRegister() {
require("meteor-babel/register")({
babelOptions: require("meteor-babel").getDefaultOptions(
require("./babel-features.js")
)
});
}
babelRegister(); // #RemoveInProd this line is removed in isopack.js
// Install a global ES2015-compliant Promise constructor that knows how to
// run all its callbacks in Fibers.
global.Promise = require("meteor-promise");
// Globally install ES2015-complaint Symbol, Map, and Set, patching the
// native implementations if they are available.
require("core-js/es6/symbol");
require("core-js/es6/map");
require("core-js/es6/set");
// Include helpers from NPM so that the compiler doesn't need to add boilerplate
// at the top of every file
require("meteor-babel").installRuntime();
// Installs source map support with a hook to add functions to look for source
// maps in custom places
require('./source-map-retriever-stack.js');
// Run the Meteor command line tool
require('./main.js');
| // This file exists because it is the file in the tool that is not automatically
// transpiled by Babel
function babelRegister() {
require("meteor-babel/register")({
babelOptions: require("meteor-babel").getDefaultOptions(
require("./babel-features.js")
)
});
}
babelRegister(); // #RemoveInProd this line is removed in isopack.js
// Install a global ES2015-compliant Promise constructor that knows how to
// run all its callbacks in Fibers.
global.Promise = require("meteor-promise");
// Install ES2015-complaint polyfills for Symbol, Map, Set, and String,
// patching the native implementations if they are available.
require("core-js/es6/symbol");
require("core-js/es6/map");
require("core-js/es6/set");
require("core-js/es6/string");
// Include helpers from NPM so that the compiler doesn't need to add boilerplate
// at the top of every file
require("meteor-babel").installRuntime();
// Installs source map support with a hook to add functions to look for source
// maps in custom places
require('./source-map-retriever-stack.js');
// Run the Meteor command line tool
require('./main.js');
| Install ES2015 String polyfills in tool code, too. | Install ES2015 String polyfills in tool code, too.
| JavaScript | mit | cherbst/meteor,jeblister/meteor,kengchau/meteor,cherbst/meteor,deanius/meteor,karlito40/meteor,h200863057/meteor,Jonekee/meteor,guazipi/meteor,Puena/meteor,planet-training/meteor,deanius/meteor,namho102/meteor,chiefninew/meteor,TechplexEngineer/meteor,allanalexandre/meteor,baiyunping333/meteor,jeblister/meteor,katopz/meteor,johnthepink/meteor,jirengu/meteor,GrimDerp/meteor,Paulyoufu/meteor-1,meonkeys/meteor,iman-mafi/meteor,msavin/meteor,kencheung/meteor,modulexcite/meteor,qscripter/meteor,chiefninew/meteor,GrimDerp/meteor,cherbst/meteor,jeblister/meteor,D1no/meteor,shrop/meteor,dboyliao/meteor,modulexcite/meteor,baiyunping333/meteor,jenalgit/meteor,yonglehou/meteor,chengxiaole/meteor,h200863057/meteor,eluck/meteor,daltonrenaldo/meteor,Theviajerock/meteor,chiefninew/meteor,dev-bobsong/meteor,fashionsun/meteor,Hansoft/meteor,ericterpstra/meteor,sdeveloper/meteor,AnjirHossain/meteor,oceanzou123/meteor,williambr/meteor,brdtrpp/meteor,baiyunping333/meteor,Ken-Liu/meteor,DCKT/meteor,Jeremy017/meteor,hristaki/meteor,yalexx/meteor,michielvanoeffelen/meteor,sdeveloper/meteor,codedogfish/meteor,wmkcc/meteor,williambr/meteor,nuvipannu/meteor,framewr/meteor,Eynaliyev/meteor,LWHTarena/meteor,sunny-g/meteor,kencheung/meteor,justintung/meteor,yonas/meteor-freebsd,Eynaliyev/meteor,dfischer/meteor,lassombra/meteor,Theviajerock/meteor,rabbyalone/meteor,michielvanoeffelen/meteor,somallg/meteor,cog-64/meteor,karlito40/meteor,ericterpstra/meteor,luohuazju/meteor,devgrok/meteor,benstoltz/meteor,ashwathgovind/meteor,brdtrpp/meteor,SeanOceanHu/meteor,johnthepink/meteor,chmac/meteor,Ken-Liu/meteor,AlexR1712/meteor,Jonekee/meteor,juansgaitan/meteor,TechplexEngineer/meteor,steedos/meteor,shrop/meteor,meteor-velocity/meteor,lassombra/meteor,baiyunping333/meteor,imanmafi/meteor,IveWong/meteor,chmac/meteor,HugoRLopes/meteor,judsonbsilva/meteor,PatrickMcGuinness/meteor,newswim/meteor,lieuwex/meteor,Jonekee/meteor,eluck/meteor,yyx990803/meteor,allanalexandre/meteor,ljack/meteor,servel333/meteor,Eynaliyev/meteor,kengchau/meteor,justintung/meteor,esteedqueen/meteor,shmiko/meteor,steedos/meteor,imanmafi/meteor,esteedqueen/meteor,cherbst/meteor,rabbyalone/meteor,chasertech/meteor,PatrickMcGuinness/meteor,michielvanoeffelen/meteor,mubassirhayat/meteor,daltonrenaldo/meteor,msavin/meteor,brettle/meteor,rabbyalone/meteor,esteedqueen/meteor,hristaki/meteor,emmerge/meteor,sitexa/meteor,cbonami/meteor,dev-bobsong/meteor,evilemon/meteor,eluck/meteor,Eynaliyev/meteor,paul-barry-kenzan/meteor,alexbeletsky/meteor,chmac/meteor,saisai/meteor,devgrok/meteor,h200863057/meteor,justintung/meteor,mirstan/meteor,deanius/meteor,chmac/meteor,IveWong/meteor,shmiko/meteor,Ken-Liu/meteor,karlito40/meteor,jirengu/meteor,yyx990803/meteor,Jeremy017/meteor,sclausen/meteor,iman-mafi/meteor,ndarilek/meteor,DAB0mB/meteor,allanalexandre/meteor,juansgaitan/meteor,benstoltz/meteor,mubassirhayat/meteor,dev-bobsong/meteor,AnthonyAstige/meteor,rabbyalone/meteor,baysao/meteor,chengxiaole/meteor,chasertech/meteor,rozzzly/meteor,yanisIk/meteor,tdamsma/meteor,D1no/meteor,henrypan/meteor,sdeveloper/meteor,johnthepink/meteor,shmiko/meteor,evilemon/meteor,lorensr/meteor,akintoey/meteor,kengchau/meteor,lorensr/meteor,lorensr/meteor,yinhe007/meteor,katopz/meteor,Urigo/meteor,dandv/meteor,allanalexandre/meteor,D1no/meteor,LWHTarena/meteor,yyx990803/meteor,newswim/meteor,elkingtonmcb/meteor,LWHTarena/meteor,Hansoft/meteor,brettle/meteor,cog-64/meteor,mubassirhayat/meteor,jg3526/meteor,LWHTarena/meteor,papimomi/meteor,brettle/meteor,elkingtonmcb/meteor,DAB0mB/meteor,karlito40/meteor,whip112/meteor,yinhe007/meteor,arunoda/meteor,jg3526/meteor,modulexcite/meteor,jg3526/meteor,steedos/meteor,rabbyalone/meteor,aramk/meteor,evilemon/meteor,ljack/meteor,luohuazju/meteor,juansgaitan/meteor,AnjirHossain/meteor,lieuwex/meteor,DCKT/meteor,hristaki/meteor,TechplexEngineer/meteor,lieuwex/meteor,dandv/meteor,AnthonyAstige/meteor,jirengu/meteor,namho102/meteor,nuvipannu/meteor,Hansoft/meteor,yyx990803/meteor,allanalexandre/meteor,benstoltz/meteor,ericterpstra/meteor,Hansoft/meteor,cog-64/meteor,neotim/meteor,Profab/meteor,calvintychan/meteor,calvintychan/meteor,DAB0mB/meteor,HugoRLopes/meteor,hristaki/meteor,youprofit/meteor,4commerce-technologies-AG/meteor,qscripter/meteor,yonas/meteor-freebsd,Hansoft/meteor,meonkeys/meteor,emmerge/meteor,sitexa/meteor,mjmasn/meteor,williambr/meteor,codedogfish/meteor,yonas/meteor-freebsd,baysao/meteor,guazipi/meteor,aldeed/meteor,AnthonyAstige/meteor,Prithvi-A/meteor,paul-barry-kenzan/meteor,Jonekee/meteor,tdamsma/meteor,ndarilek/meteor,Jeremy017/meteor,PatrickMcGuinness/meteor,Jeremy017/meteor,4commerce-technologies-AG/meteor,planet-training/meteor,joannekoong/meteor,shadedprofit/meteor,joannekoong/meteor,planet-training/meteor,guazipi/meteor,rabbyalone/meteor,arunoda/meteor,arunoda/meteor,vjau/meteor,lassombra/meteor,chiefninew/meteor,HugoRLopes/meteor,GrimDerp/meteor,yonas/meteor-freebsd,baiyunping333/meteor,codedogfish/meteor,vjau/meteor,LWHTarena/meteor,msavin/meteor,cherbst/meteor,Paulyoufu/meteor-1,katopz/meteor,Puena/meteor,mauricionr/meteor,daslicht/meteor,papimomi/meteor,DAB0mB/meteor,planet-training/meteor,kidaa/meteor,whip112/meteor,daslicht/meteor,HugoRLopes/meteor,luohuazju/meteor,michielvanoeffelen/meteor,framewr/meteor,alexbeletsky/meteor,wmkcc/meteor,joannekoong/meteor,allanalexandre/meteor,Profab/meteor,karlito40/meteor,paul-barry-kenzan/meteor,msavin/meteor,dev-bobsong/meteor,iman-mafi/meteor,AlexR1712/meteor,jdivy/meteor,planet-training/meteor,imanmafi/meteor,shrop/meteor,rozzzly/meteor,udhayam/meteor,allanalexandre/meteor,4commerce-technologies-AG/meteor,sdeveloper/meteor,devgrok/meteor,aldeed/meteor,meonkeys/meteor,shadedprofit/meteor,Urigo/meteor,ashwathgovind/meteor,youprofit/meteor,yanisIk/meteor,mubassirhayat/meteor,udhayam/meteor,sclausen/meteor,udhayam/meteor,DCKT/meteor,benstoltz/meteor,henrypan/meteor,paul-barry-kenzan/meteor,planet-training/meteor,wmkcc/meteor,henrypan/meteor,yalexx/meteor,steedos/meteor,baysao/meteor,tdamsma/meteor,lawrenceAIO/meteor,shrop/meteor,williambr/meteor,yanisIk/meteor,yanisIk/meteor,lassombra/meteor,juansgaitan/meteor,daltonrenaldo/meteor,juansgaitan/meteor,D1no/meteor,AnjirHossain/meteor,colinligertwood/meteor,cbonami/meteor,sclausen/meteor,mauricionr/meteor,justintung/meteor,4commerce-technologies-AG/meteor,ericterpstra/meteor,ericterpstra/meteor,sunny-g/meteor,justintung/meteor,D1no/meteor,servel333/meteor,ashwathgovind/meteor,meonkeys/meteor,AnthonyAstige/meteor,neotim/meteor,emmerge/meteor,AnthonyAstige/meteor,papimomi/meteor,emmerge/meteor,chengxiaole/meteor,AnthonyAstige/meteor,esteedqueen/meteor,lassombra/meteor,chasertech/meteor,EduShareOntario/meteor,evilemon/meteor,bhargav175/meteor,newswim/meteor,shmiko/meteor,akintoey/meteor,fashionsun/meteor,fashionsun/meteor,HugoRLopes/meteor,saisai/meteor,somallg/meteor,oceanzou123/meteor,chiefninew/meteor,yiliaofan/meteor,shmiko/meteor,yiliaofan/meteor,jdivy/meteor,yinhe007/meteor,qscripter/meteor,aleclarson/meteor,kencheung/meteor,michielvanoeffelen/meteor,meonkeys/meteor,Puena/meteor,dboyliao/meteor,akintoey/meteor,Paulyoufu/meteor-1,lawrenceAIO/meteor,HugoRLopes/meteor,alexbeletsky/meteor,jdivy/meteor,cog-64/meteor,yinhe007/meteor,karlito40/meteor,servel333/meteor,AlexR1712/meteor,yyx990803/meteor,meteor-velocity/meteor,luohuazju/meteor,dboyliao/meteor,rozzzly/meteor,namho102/meteor,luohuazju/meteor,yalexx/meteor,bhargav175/meteor,iman-mafi/meteor,rabbyalone/meteor,sunny-g/meteor,IveWong/meteor,newswim/meteor,codingang/meteor,ljack/meteor,saisai/meteor,SeanOceanHu/meteor,youprofit/meteor,aldeed/meteor,GrimDerp/meteor,PatrickMcGuinness/meteor,AnjirHossain/meteor,vjau/meteor,Theviajerock/meteor,jg3526/meteor,cog-64/meteor,planet-training/meteor,deanius/meteor,Ken-Liu/meteor,ndarilek/meteor,daslicht/meteor,wmkcc/meteor,modulexcite/meteor,dev-bobsong/meteor,imanmafi/meteor,hristaki/meteor,neotim/meteor,Quicksteve/meteor,jenalgit/meteor,ericterpstra/meteor,yonas/meteor-freebsd,williambr/meteor,chasertech/meteor,alexbeletsky/meteor,jg3526/meteor,codingang/meteor,Quicksteve/meteor,katopz/meteor,whip112/meteor,aleclarson/meteor,jirengu/meteor,4commerce-technologies-AG/meteor,baysao/meteor,lpinto93/meteor,LWHTarena/meteor,bhargav175/meteor,akintoey/meteor,DAB0mB/meteor,shadedprofit/meteor,Eynaliyev/meteor,johnthepink/meteor,jg3526/meteor,elkingtonmcb/meteor,chmac/meteor,ndarilek/meteor,SeanOceanHu/meteor,lawrenceAIO/meteor,yonglehou/meteor,saisai/meteor,shadedprofit/meteor,shadedprofit/meteor,dboyliao/meteor,chasertech/meteor,IveWong/meteor,deanius/meteor,yalexx/meteor,shrop/meteor,meonkeys/meteor,steedos/meteor,qscripter/meteor,D1no/meteor,elkingtonmcb/meteor,yanisIk/meteor,mauricionr/meteor,mauricionr/meteor,dboyliao/meteor,Jeremy017/meteor,ljack/meteor,daslicht/meteor,chengxiaole/meteor,akintoey/meteor,Prithvi-A/meteor,devgrok/meteor,Prithvi-A/meteor,AnjirHossain/meteor,vacjaliu/meteor,tdamsma/meteor,henrypan/meteor,lpinto93/meteor,cbonami/meteor,colinligertwood/meteor,allanalexandre/meteor,Urigo/meteor,yinhe007/meteor,cbonami/meteor,shmiko/meteor,rozzzly/meteor,yinhe007/meteor,guazipi/meteor,Ken-Liu/meteor,lieuwex/meteor,brettle/meteor,esteedqueen/meteor,cbonami/meteor,joannekoong/meteor,Jeremy017/meteor,nuvipannu/meteor,sclausen/meteor,codedogfish/meteor,jdivy/meteor,dfischer/meteor,lawrenceAIO/meteor,yinhe007/meteor,ljack/meteor,yyx990803/meteor,modulexcite/meteor,yalexx/meteor,sclausen/meteor,guazipi/meteor,msavin/meteor,calvintychan/meteor,lassombra/meteor,arunoda/meteor,rozzzly/meteor,brdtrpp/meteor,elkingtonmcb/meteor,judsonbsilva/meteor,kidaa/meteor,servel333/meteor,evilemon/meteor,cog-64/meteor,arunoda/meteor,mirstan/meteor,kidaa/meteor,emmerge/meteor,codingang/meteor,IveWong/meteor,jeblister/meteor,meteor-velocity/meteor,yanisIk/meteor,brdtrpp/meteor,kidaa/meteor,udhayam/meteor,TechplexEngineer/meteor,Jonekee/meteor,daslicht/meteor,AlexR1712/meteor,aramk/meteor,cherbst/meteor,lassombra/meteor,TechplexEngineer/meteor,h200863057/meteor,aramk/meteor,yonglehou/meteor,D1no/meteor,meteor-velocity/meteor,paul-barry-kenzan/meteor,tdamsma/meteor,nuvipannu/meteor,dev-bobsong/meteor,henrypan/meteor,Hansoft/meteor,codingang/meteor,codedogfish/meteor,DCKT/meteor,mirstan/meteor,fashionsun/meteor,EduShareOntario/meteor,baysao/meteor,Prithvi-A/meteor,johnthepink/meteor,juansgaitan/meteor,mjmasn/meteor,dboyliao/meteor,dandv/meteor,somallg/meteor,LWHTarena/meteor,sitexa/meteor,dfischer/meteor,ashwathgovind/meteor,johnthepink/meteor,dfischer/meteor,sdeveloper/meteor,vjau/meteor,mubassirhayat/meteor,yiliaofan/meteor,iman-mafi/meteor,EduShareOntario/meteor,kidaa/meteor,aleclarson/meteor,papimomi/meteor,mubassirhayat/meteor,chiefninew/meteor,whip112/meteor,williambr/meteor,steedos/meteor,vacjaliu/meteor,framewr/meteor,joannekoong/meteor,zdd910/meteor,alexbeletsky/meteor,jdivy/meteor,HugoRLopes/meteor,meteor-velocity/meteor,planet-training/meteor,Prithvi-A/meteor,SeanOceanHu/meteor,fashionsun/meteor,GrimDerp/meteor,cog-64/meteor,somallg/meteor,lieuwex/meteor,AnthonyAstige/meteor,Quicksteve/meteor,deanius/meteor,dandv/meteor,ndarilek/meteor,yonas/meteor-freebsd,chengxiaole/meteor,neotim/meteor,evilemon/meteor,lpinto93/meteor,colinligertwood/meteor,daslicht/meteor,iman-mafi/meteor,framewr/meteor,vacjaliu/meteor,AnjirHossain/meteor,namho102/meteor,msavin/meteor,ashwathgovind/meteor,oceanzou123/meteor,newswim/meteor,PatrickMcGuinness/meteor,lpinto93/meteor,yanisIk/meteor,dandv/meteor,aramk/meteor,ashwathgovind/meteor,meteor-velocity/meteor,benstoltz/meteor,dandv/meteor,jenalgit/meteor,benstoltz/meteor,eluck/meteor,udhayam/meteor,Puena/meteor,lorensr/meteor,Eynaliyev/meteor,sunny-g/meteor,kencheung/meteor,brettle/meteor,yyx990803/meteor,newswim/meteor,chengxiaole/meteor,Theviajerock/meteor,bhargav175/meteor,mjmasn/meteor,esteedqueen/meteor,wmkcc/meteor,yonglehou/meteor,servel333/meteor,calvintychan/meteor,jeblister/meteor,zdd910/meteor,youprofit/meteor,evilemon/meteor,neotim/meteor,msavin/meteor,juansgaitan/meteor,servel333/meteor,neotim/meteor,bhargav175/meteor,michielvanoeffelen/meteor,chmac/meteor,wmkcc/meteor,h200863057/meteor,4commerce-technologies-AG/meteor,AlexR1712/meteor,Paulyoufu/meteor-1,Quicksteve/meteor,zdd910/meteor,johnthepink/meteor,vacjaliu/meteor,sunny-g/meteor,codedogfish/meteor,hristaki/meteor,sitexa/meteor,EduShareOntario/meteor,yiliaofan/meteor,dfischer/meteor,mirstan/meteor,emmerge/meteor,kengchau/meteor,lorensr/meteor,lpinto93/meteor,udhayam/meteor,chasertech/meteor,judsonbsilva/meteor,Jonekee/meteor,colinligertwood/meteor,Prithvi-A/meteor,brdtrpp/meteor,ndarilek/meteor,sitexa/meteor,calvintychan/meteor,chengxiaole/meteor,somallg/meteor,PatrickMcGuinness/meteor,michielvanoeffelen/meteor,elkingtonmcb/meteor,zdd910/meteor,cbonami/meteor,nuvipannu/meteor,Quicksteve/meteor,dfischer/meteor,kencheung/meteor,HugoRLopes/meteor,saisai/meteor,luohuazju/meteor,codingang/meteor,Paulyoufu/meteor-1,dboyliao/meteor,rozzzly/meteor,mjmasn/meteor,somallg/meteor,emmerge/meteor,sunny-g/meteor,youprofit/meteor,mirstan/meteor,wmkcc/meteor,bhargav175/meteor,lawrenceAIO/meteor,yonglehou/meteor,h200863057/meteor,framewr/meteor,papimomi/meteor,colinligertwood/meteor,shadedprofit/meteor,fashionsun/meteor,yonas/meteor-freebsd,sdeveloper/meteor,whip112/meteor,papimomi/meteor,udhayam/meteor,daltonrenaldo/meteor,shrop/meteor,mjmasn/meteor,mjmasn/meteor,brettle/meteor,Paulyoufu/meteor-1,Profab/meteor,Puena/meteor,jenalgit/meteor,vjau/meteor,joannekoong/meteor,ljack/meteor,yonglehou/meteor,cbonami/meteor,brdtrpp/meteor,ljack/meteor,henrypan/meteor,kengchau/meteor,aramk/meteor,Urigo/meteor,eluck/meteor,shmiko/meteor,ndarilek/meteor,AnthonyAstige/meteor,yonglehou/meteor,lpinto93/meteor,PatrickMcGuinness/meteor,eluck/meteor,rozzzly/meteor,devgrok/meteor,D1no/meteor,brettle/meteor,codingang/meteor,guazipi/meteor,daltonrenaldo/meteor,namho102/meteor,mauricionr/meteor,karlito40/meteor,kidaa/meteor,meonkeys/meteor,yalexx/meteor,judsonbsilva/meteor,DCKT/meteor,h200863057/meteor,yiliaofan/meteor,DCKT/meteor,judsonbsilva/meteor,Eynaliyev/meteor,guazipi/meteor,devgrok/meteor,dboyliao/meteor,whip112/meteor,deanius/meteor,vacjaliu/meteor,Prithvi-A/meteor,kengchau/meteor,sitexa/meteor,tdamsma/meteor,brdtrpp/meteor,mubassirhayat/meteor,aldeed/meteor,katopz/meteor,shadedprofit/meteor,aramk/meteor,katopz/meteor,sunny-g/meteor,lawrenceAIO/meteor,Urigo/meteor,TechplexEngineer/meteor,vacjaliu/meteor,williambr/meteor,kencheung/meteor,mirstan/meteor,namho102/meteor,mauricionr/meteor,sdeveloper/meteor,vjau/meteor,colinligertwood/meteor,DAB0mB/meteor,shrop/meteor,lieuwex/meteor,alexbeletsky/meteor,EduShareOntario/meteor,AlexR1712/meteor,brdtrpp/meteor,daslicht/meteor,kidaa/meteor,IveWong/meteor,lorensr/meteor,sclausen/meteor,qscripter/meteor,meteor-velocity/meteor,karlito40/meteor,daltonrenaldo/meteor,jg3526/meteor,oceanzou123/meteor,iman-mafi/meteor,Profab/meteor,jeblister/meteor,elkingtonmcb/meteor,aldeed/meteor,4commerce-technologies-AG/meteor,sclausen/meteor,Theviajerock/meteor,akintoey/meteor,henrypan/meteor,Theviajerock/meteor,Quicksteve/meteor,imanmafi/meteor,sunny-g/meteor,DCKT/meteor,aramk/meteor,whip112/meteor,mauricionr/meteor,qscripter/meteor,jenalgit/meteor,luohuazju/meteor,nuvipannu/meteor,fashionsun/meteor,kencheung/meteor,SeanOceanHu/meteor,Profab/meteor,hristaki/meteor,baiyunping333/meteor,codingang/meteor,katopz/meteor,Paulyoufu/meteor-1,lpinto93/meteor,Quicksteve/meteor,Ken-Liu/meteor,newswim/meteor,justintung/meteor,judsonbsilva/meteor,DAB0mB/meteor,daltonrenaldo/meteor,eluck/meteor,aldeed/meteor,esteedqueen/meteor,dev-bobsong/meteor,baysao/meteor,dfischer/meteor,tdamsma/meteor,akintoey/meteor,Hansoft/meteor,ljack/meteor,Profab/meteor,Urigo/meteor,lawrenceAIO/meteor,alexbeletsky/meteor,baiyunping333/meteor,steedos/meteor,jdivy/meteor,chiefninew/meteor,chiefninew/meteor,namho102/meteor,ndarilek/meteor,zdd910/meteor,daltonrenaldo/meteor,joannekoong/meteor,kengchau/meteor,youprofit/meteor,somallg/meteor,servel333/meteor,AnjirHossain/meteor,modulexcite/meteor,somallg/meteor,GrimDerp/meteor,Urigo/meteor,Puena/meteor,jenalgit/meteor,EduShareOntario/meteor,Puena/meteor,paul-barry-kenzan/meteor,judsonbsilva/meteor,bhargav175/meteor,yalexx/meteor,nuvipannu/meteor,devgrok/meteor,framewr/meteor,codedogfish/meteor,GrimDerp/meteor,calvintychan/meteor,chmac/meteor,jenalgit/meteor,mjmasn/meteor,alexbeletsky/meteor,papimomi/meteor,dandv/meteor,SeanOceanHu/meteor,framewr/meteor,modulexcite/meteor,jdivy/meteor,baysao/meteor,oceanzou123/meteor,paul-barry-kenzan/meteor,arunoda/meteor,justintung/meteor,yiliaofan/meteor,benstoltz/meteor,ashwathgovind/meteor,youprofit/meteor,servel333/meteor,aldeed/meteor,imanmafi/meteor,mubassirhayat/meteor,qscripter/meteor,EduShareOntario/meteor,yiliaofan/meteor,jirengu/meteor,Theviajerock/meteor,AlexR1712/meteor,saisai/meteor,jeblister/meteor,lieuwex/meteor,sitexa/meteor,mirstan/meteor,vjau/meteor,Jeremy017/meteor,cherbst/meteor,TechplexEngineer/meteor,oceanzou123/meteor,ericterpstra/meteor,zdd910/meteor,Ken-Liu/meteor,chasertech/meteor,eluck/meteor,lorensr/meteor,jirengu/meteor,tdamsma/meteor,saisai/meteor,Profab/meteor,colinligertwood/meteor,calvintychan/meteor,zdd910/meteor,neotim/meteor,imanmafi/meteor,IveWong/meteor,oceanzou123/meteor,SeanOceanHu/meteor,Eynaliyev/meteor,yanisIk/meteor,arunoda/meteor,Jonekee/meteor,SeanOceanHu/meteor,vacjaliu/meteor,jirengu/meteor | ---
+++
@@ -15,11 +15,12 @@
// run all its callbacks in Fibers.
global.Promise = require("meteor-promise");
-// Globally install ES2015-complaint Symbol, Map, and Set, patching the
-// native implementations if they are available.
+// Install ES2015-complaint polyfills for Symbol, Map, Set, and String,
+// patching the native implementations if they are available.
require("core-js/es6/symbol");
require("core-js/es6/map");
require("core-js/es6/set");
+require("core-js/es6/string");
// Include helpers from NPM so that the compiler doesn't need to add boilerplate
// at the top of every file |
76f211a93cba95050f5fcbcdada228f9e3c42936 | d3/test/spec/test_wgaPipeline.js | d3/test/spec/test_wgaPipeline.js | describe('The constructor is supposed a proper WgaPipeline object', function(){
it('Constructor wgaPipeline exists', function(){
expect(WgaPipeline).toBeDefined();
});
var svg = $('<svg></svg>');
var wga = new WgaPipeline(svg);
it('WgaPipelie object is not null', function(){
expect(wga).not.toBeNull();
});
it('the svg property is properly set', function(){
expect(wga.svg).toEqual(svg);
});
it('the data property is initialized as empty object', function(){
expect(wga.data).toEqual({});
});
});
describe('The setData method of WgaPipeline objects is supposed to set the data', function(){
var svg = $('<svg></svg>');
var wga = new WgaPipeline(svg);
it('setData method is supposed to be a function', function(){
expect(typeof wga.setData).toEqual('function');
});
});
| describe('The constructor is supposed a proper WgaPipeline object', function(){
it('Constructor wgaPipeline exists', function(){
expect(WgaPipeline).toBeDefined();
});
var svg = $('<svg></svg>');
var wga = new WgaPipeline(svg);
it('WgaPipelie object is not null', function(){
expect(wga).not.toBeNull();
});
it('the svg property is properly set', function(){
expect(wga.svg).toEqual(svg);
});
it('the data property is initialized as empty object', function(){
expect(wga.data).toEqual({});
});
});
describe('The setData method of WgaPipeline objects is supposed to set the data', function(){
var svg = $('<svg></svg>');
var wga = new WgaPipeline(svg);
it('setData method is supposed to be a function', function(){
expect(typeof wga.setData).toEqual('function');
});
var karyo = {
'order': ['c1', 'c2'],
'chromosomes': {
'c1': {'genome_id': 0, 'length': 2000, 'rc': false, 'seq': null},
'c2': {'genome_id': 1, 'length': 1000, 'rc': false, 'seq': null}
}
};
var features = {
'f1': {'karyo': 'c1', 'start': 300, 'end': 800},
'f2': {'karyo': 'c2', 'start': 100, 'end': 600}
};
var links = [
{'source': 'f1', 'target': 'f2', 'identity': 90}
];
var data = {'karyo': karyo, 'features': features, 'links': links};
wga.setData(data);
it('setData method is supposed to set the data variable', function(){
expect(wga.data).toEqual(data);
});
});
| Test for functionality of setData method fails | Test for functionality of setData method fails
| JavaScript | mit | AliTVTeam/AliTV,BioInf-Wuerzburg/AliTV,AliTVTeam/AliTV,BioInf-Wuerzburg/AliTV,BioInf-Wuerzburg/AliTV,BioInf-Wuerzburg/AliTV,BioInf-Wuerzburg/AliTV,BioInf-Wuerzburg/AliTV | ---
+++
@@ -21,4 +21,23 @@
it('setData method is supposed to be a function', function(){
expect(typeof wga.setData).toEqual('function');
});
+ var karyo = {
+ 'order': ['c1', 'c2'],
+ 'chromosomes': {
+ 'c1': {'genome_id': 0, 'length': 2000, 'rc': false, 'seq': null},
+ 'c2': {'genome_id': 1, 'length': 1000, 'rc': false, 'seq': null}
+ }
+ };
+ var features = {
+ 'f1': {'karyo': 'c1', 'start': 300, 'end': 800},
+ 'f2': {'karyo': 'c2', 'start': 100, 'end': 600}
+ };
+ var links = [
+ {'source': 'f1', 'target': 'f2', 'identity': 90}
+ ];
+ var data = {'karyo': karyo, 'features': features, 'links': links};
+ wga.setData(data);
+ it('setData method is supposed to set the data variable', function(){
+ expect(wga.data).toEqual(data);
+ });
}); |
4b956b5e7fb6206f17fdaf9f770afe6734827455 | packages/idyll-editor/src/renderer.js | packages/idyll-editor/src/renderer.js | const components = require('idyll-components');
const IdyllDocument = require('idyll-document');
const React = require('react');
class Renderer extends React.PureComponent {
render() {
const { idyllMarkup, ast, idyllHash } = this.props;
return (
<div className={"renderer"}>
<div className={"renderer-container"}>
<IdyllDocument
ast={ast}
componentClasses={components}
key={idyllHash}
datasets={{}}
/>
</div>
</div>
);
}
}
module.exports = Renderer;
| const components = require('idyll-components');
const IdyllDocument = require('../../idyll-document/src');
const React = require('react');
class Renderer extends React.PureComponent {
render() {
const { idyllMarkup, ast, idyllHash } = this.props;
return (
<div className={"renderer"}>
<div className={"renderer-container"}>
<IdyllDocument
ast={ast}
componentClasses={components}
key={idyllHash}
datasets={{}}
/>
</div>
</div>
);
}
}
module.exports = Renderer;
| Use relative path until published | Use relative path until published
| JavaScript | mit | idyll-lang/idyll,idyll-lang/idyll | ---
+++
@@ -1,5 +1,5 @@
const components = require('idyll-components');
-const IdyllDocument = require('idyll-document');
+const IdyllDocument = require('../../idyll-document/src');
const React = require('react');
class Renderer extends React.PureComponent { |
b9f34201ddb64378f10320b7a0f9e4ef1d29bb5e | packages/mobile-status-bar/package.js | packages/mobile-status-bar/package.js | Package.describe({
summary: "Good defaults for the mobile status bar",
version: "1.0.14"
});
Cordova.depends({
'cordova-plugin-statusbar': '2.3.0'
});
| Package.describe({
summary: "Good defaults for the mobile status bar",
version: "1.0.14"
});
Cordova.depends({
'cordova-plugin-statusbar': '2.4.3'
});
| Update cordova-plugin-statusbar from 2.3.0 to 2.4.3. | Update cordova-plugin-statusbar from 2.3.0 to 2.4.3.
Included by mobile-experience > mobile-status-bar.
| JavaScript | mit | Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor | ---
+++
@@ -4,5 +4,5 @@
});
Cordova.depends({
- 'cordova-plugin-statusbar': '2.3.0'
+ 'cordova-plugin-statusbar': '2.4.3'
}); |
8b96e99cb55204088d239e2ec63e5af535068786 | server/routes.js | server/routes.js | var f = "MMM Do YYYY";
function calcWidth(name) {
return 250 + name.length * 6.305555555555555;
}
WebApp.connectHandlers.use("/package", function(request, response) {
if(request.url.split('/')[1] != ''){
var url = `https://atmospherejs.com/a/packages/findByNames\
?names=${request.url.split('/')[1]}`;
HTTP.get(url, {headers: {'Accept': 'application/json'}}, function(err, res) {
var name,version,pubdate,starCount,installyear = '';
if (res.data.length != 0) {
name = res.data[0].name;
version = res.data[0].latestVersion.version;
pubdate = moment(res.data[0].latestVersion.published.$date).format(f);
starCount = res.data[0].starCount.toLocaleString();
installyear = res.data[0]['installs-per-year'].toLocaleString();
}
SSR.compileTemplate('icon', Assets.getText('icon.svg'));
var width = calcWidth(name);
var params = {w: width, totalW: width+2, n: name, v: version, p: pubdate,
s: starCount, i: installyear};
var icon = SSR.render('icon', params);
response.writeHead(200, {"Content-Type": "image/svg+xml"});
response.end(icon);
});
}
});
| function calcWidth(name) {
return 250 + name.length * 6.305555555555555;
}
WebApp.connectHandlers.use("/package", function(request, response) {
if(request.url.split('/')[1] != ''){
var url = `https://atmospherejs.com/a/packages/findByNames\
?names=${request.url.split('/')[1]}`;
HTTP.get(url, {headers: {'Accept': 'application/json'}}, function(err, res) {
var name = '';
var f = "MMM Do YYYY";
var payload = res.data[0];
if (res.data.length != 0) {
var name = payload.name;
var version = payload.latestVersion.version;
var pubdate = moment(payload.latestVersion.published.$date).format(f);
var starCount = payload.starCount.toLocaleString();
var installyear = payload['installs-per-year'].toLocaleString();
}
SSR.compileTemplate('icon', Assets.getText('icon.svg'));
var width = calcWidth(name);
var params = {w: width, totalW: width+2, n: name, v: version, p: pubdate,
s: starCount, i: installyear};
var icon = SSR.render('icon', params);
response.writeHead(200, {"Content-Type": "image/svg+xml"});
response.end(icon);
});
}
});
| Fix undefined name and scope variables | Fix undefined name and scope variables
| JavaScript | mit | sungwoncho/meteor-icon,sungwoncho/meteor-icon | ---
+++
@@ -1,5 +1,3 @@
-var f = "MMM Do YYYY";
-
function calcWidth(name) {
return 250 + name.length * 6.305555555555555;
}
@@ -9,13 +7,16 @@
var url = `https://atmospherejs.com/a/packages/findByNames\
?names=${request.url.split('/')[1]}`;
HTTP.get(url, {headers: {'Accept': 'application/json'}}, function(err, res) {
- var name,version,pubdate,starCount,installyear = '';
+ var name = '';
+ var f = "MMM Do YYYY";
+ var payload = res.data[0];
+
if (res.data.length != 0) {
- name = res.data[0].name;
- version = res.data[0].latestVersion.version;
- pubdate = moment(res.data[0].latestVersion.published.$date).format(f);
- starCount = res.data[0].starCount.toLocaleString();
- installyear = res.data[0]['installs-per-year'].toLocaleString();
+ var name = payload.name;
+ var version = payload.latestVersion.version;
+ var pubdate = moment(payload.latestVersion.published.$date).format(f);
+ var starCount = payload.starCount.toLocaleString();
+ var installyear = payload['installs-per-year'].toLocaleString();
}
SSR.compileTemplate('icon', Assets.getText('icon.svg')); |
fb3508a81f101d1c376deff610d7f93af5d426ba | ghpages/js/stationary-track.js | ghpages/js/stationary-track.js | var playlist = WaveformPlaylist.init({
samplesPerPixel: 3000,
mono: true,
waveHeight: 100,
container: document.getElementById("playlist"),
state: 'cursor',
waveOutlineColor: '#E0EFF1',
colors: {
waveOutlineColor: '#E0EFF1',
timeColor: 'grey',
fadeColor: 'black'
},
controls: {
show: true, //whether or not to include the track controls
width: 200 //width of controls in pixels
}
});
playlist.load([
{
"src": "media/audio/Vocals30.mp3",
"name": "Vocals",
"states": {
"shift": false
}
},
{
"src": "media/audio/BassDrums30.mp3",
"name": "Drums",
"start": 30
}
]).then(function() {
//can do stuff with the playlist.
});
| var playlist = WaveformPlaylist.init({
samplesPerPixel: 3000,
zoomLevels: [500, 1000, 3000, 5000],
mono: true,
waveHeight: 100,
container: document.getElementById("playlist"),
state: 'cursor',
waveOutlineColor: '#E0EFF1',
colors: {
waveOutlineColor: '#E0EFF1',
timeColor: 'grey',
fadeColor: 'black'
},
controls: {
show: true, //whether or not to include the track controls
width: 200 //width of controls in pixels
}
});
playlist.load([
{
"src": "media/audio/Vocals30.mp3",
"name": "Vocals",
"states": {
"shift": false
}
},
{
"src": "media/audio/BassDrums30.mp3",
"name": "Drums",
"start": 30
}
]).then(function() {
//can do stuff with the playlist.
});
| Fix zoom levels for example. | Fix zoom levels for example.
| JavaScript | mit | naomiaro/waveform-playlist,naomiaro/waveform-playlist | ---
+++
@@ -1,5 +1,6 @@
var playlist = WaveformPlaylist.init({
samplesPerPixel: 3000,
+ zoomLevels: [500, 1000, 3000, 5000],
mono: true,
waveHeight: 100,
container: document.getElementById("playlist"), |
18b70b1dfc2e258215596e561cf37369fc467a9d | stories/Interactions.story.js | stories/Interactions.story.js | import React from 'react'
import {withInfo} from '@storybook/addon-info'
import {storiesOf} from '@storybook/react'
import Board from '../src'
const data = {
lanes: [
{
id: 'lane1',
title: 'Planned Tasks',
cards: [
{id: 'Card1', title: 'Card1', description: 'foo card', metadata: {id: 'Card1'}},
{id: 'Card2', title: 'Card2', description: 'bar card', metadata: {id: 'Card2'}}
]
},
{
id: 'lane2',
title: 'Executing',
cards: []
}
]
}
storiesOf('React Trello', module).add(
'Event Handling',
withInfo('Adding event handlers to cards')(() =>
<Board
draggable={true}
data={data}
onCardClick={(cardId, metadata, laneId) => alert(`Card with id:${cardId} clicked. Has metadata.id: ${metadata.id}. Card in lane: ${laneId}`)}
onLaneClick={(laneId) => alert(`Lane with id:${laneId} clicked`)}
/>
)
)
| import React from 'react'
import {withInfo} from '@storybook/addon-info'
import {storiesOf} from '@storybook/react'
import Board from '../src'
const data = {
lanes: [
{
id: 'lane1',
title: 'Planned Tasks',
cards: [
{id: 'Card1', title: 'Card1', description: 'foo card', metadata: {id: 'Card1'}},
{id: 'Card2', title: 'Card2', description: 'bar card', metadata: {id: 'Card2'}}
]
},
{
id: 'lane2',
title: 'Executing',
cards: [
{id: 'Card3', title: 'Card3', description: 'foobar card', metadata: {id: 'Card3'}}
]
}
]
}
storiesOf('React Trello', module).add(
'Event Handling',
withInfo('Adding event handlers to cards')(() =>
<Board
draggable={true}
data={data}
onCardClick={(cardId, metadata, laneId) => alert(`Card with id:${cardId} clicked. Has metadata.id: ${metadata.id}. Card in lane: ${laneId}`)}
onLaneClick={(laneId) => alert(`Lane with id:${laneId} clicked`)}
/>
)
)
| Allow laneId to be passed as param to onCardClick handler | fix: Allow laneId to be passed as param to onCardClick handler
https://github.com/rcdexta/react-trello/issues/34
| JavaScript | mit | rcdexta/react-trello,rcdexta/react-trello | ---
+++
@@ -17,7 +17,9 @@
{
id: 'lane2',
title: 'Executing',
- cards: []
+ cards: [
+ {id: 'Card3', title: 'Card3', description: 'foobar card', metadata: {id: 'Card3'}}
+ ]
}
]
} |
0605be68fa516a167f6519c238952a23e005bc4d | templates/app/routes/index.js | templates/app/routes/index.js | var path = require('path'),
fs = require('fs');
var routes = function (app) {
fs.readdirSync(__dirname).filter(function (file) {
return path.join(__dirname, file) != __filename;
}).forEach(function (file) {
require('./' + path.basename(file))(app);
});
}
module.exports = routes;
| var path = require('path'),
fs = require('fs');
var routes = function(app) {
fs.readdirSync(__dirname).filter(function(file) {
return path.join(__dirname, file) != __filename;
}).forEach(function(file) {
require('./' + path.basename(file))(app);
});
}
module.exports = routes;
| Indent by 4 spaces instead of 2 | Indent by 4 spaces instead of 2
| JavaScript | mit | saintedlama/bumm,saintedlama/bumm,the-diamond-dogs-group-oss/bumm | ---
+++
@@ -1,11 +1,11 @@
var path = require('path'),
- fs = require('fs');
+ fs = require('fs');
-var routes = function (app) {
- fs.readdirSync(__dirname).filter(function (file) {
- return path.join(__dirname, file) != __filename;
- }).forEach(function (file) {
- require('./' + path.basename(file))(app);
+var routes = function(app) {
+ fs.readdirSync(__dirname).filter(function(file) {
+ return path.join(__dirname, file) != __filename;
+ }).forEach(function(file) {
+ require('./' + path.basename(file))(app);
});
}
|
bc1ab08e8f40fd8586cfb91e18e2c28868700a21 | src/configureRefreshFetch.js | src/configureRefreshFetch.js | // @flow
type Configuration = {
refreshToken: () => Promise<void>,
shouldRefreshToken: (error: any) => boolean,
fetch: (url: any, options: Object) => Promise<any>
}
function configureRefreshFetch (configuration: Configuration) {
const { refreshToken, shouldRefreshToken, fetch } = configuration
let refreshingTokenPromise = null
return (url: any, options: Object) => {
if (refreshingTokenPromise !== null) {
return (
refreshingTokenPromise
.then(() => fetch(url, options))
// Even if the refreshing fails, do the fetch so we reject with
// error of that request
.catch(() => fetch(url, options))
)
}
return fetch(url, options).catch(error => {
if (shouldRefreshToken(error)) {
if (refreshingTokenPromise === null) {
refreshingTokenPromise = new Promise((resolve, reject) => {
refreshToken()
.then(() => {
refreshingTokenPromise = null
resolve()
})
.catch(refreshTokenError => {
refreshingTokenPromise = null
reject(refreshTokenError)
})
})
}
return refreshingTokenPromise
.then(() => fetch(url, options))
.catch(() => {
// If refreshing fails, continue with original error
throw error
})
} else {
throw error
}
})
}
}
export default configureRefreshFetch
| // @flow
type Configuration = {
refreshToken: () => Promise<void>,
shouldRefreshToken: (error: any) => boolean,
fetch: (url: any, options: Object) => Promise<any>
}
function configureRefreshFetch (configuration: Configuration) {
const { refreshToken, shouldRefreshToken, fetch } = configuration
let refreshingTokenPromise = null
return (url: any, options: Object) => {
if (refreshingTokenPromise !== null) {
return (
refreshingTokenPromise
.then(() => fetch(url, options))
// Even if the refreshing fails, do the fetch so we reject with
// error of that request
.catch(() => fetch(url, options))
)
}
return fetch(url, options).catch(error => {
if (shouldRefreshToken(error)) {
if (refreshingTokenPromise === null) {
refreshingTokenPromise = new Promise((resolve, reject) => {
refreshToken()
.then(() => {
refreshingTokenPromise = null
resolve()
})
.catch(refreshTokenError => {
refreshingTokenPromise = null
reject(refreshTokenError)
})
})
}
return refreshingTokenPromise
.catch(() => {
// If refreshing fails, continue with original error
throw error
})
.then(() => fetch(url, options))
} else {
throw error
}
})
}
}
export default configureRefreshFetch
| Throw the right error from failing second request | Throw the right error from failing second request
Fixes #4. | JavaScript | mit | vlki/refresh-fetch | ---
+++
@@ -39,11 +39,11 @@
}
return refreshingTokenPromise
- .then(() => fetch(url, options))
.catch(() => {
// If refreshing fails, continue with original error
throw error
})
+ .then(() => fetch(url, options))
} else {
throw error
} |
025bc068d8e681661b740d206db87fbb2da1afeb | src/es6/Machete.js | src/es6/Machete.js | export class Machete {
// TODO: Implement polyfills
}
| export class Machete {
// TODO: Implement polyfills
/**
* Utility function to get an element from the DOM.
* It is needed because everytime we get an element from the DOM,
* we reset its style to make sure code works as needed.
* @param string selector CSS selector
* @return Element Selected element
*/
static getDOMElement(selector) {
let element = document.querySelector(selector),
style = window.getComputedStyle(element);
element.style.left = style.left;
element.style.top = style.top;
element.style.width = style.width;
element.style.height = style.height;
return element;
}
}
| Add function for retrieving DOM elements | core: Add function for retrieving DOM elements
| JavaScript | mpl-2.0 | Technohacker/machete | ---
+++
@@ -1,3 +1,20 @@
export class Machete {
// TODO: Implement polyfills
+
+ /**
+ * Utility function to get an element from the DOM.
+ * It is needed because everytime we get an element from the DOM,
+ * we reset its style to make sure code works as needed.
+ * @param string selector CSS selector
+ * @return Element Selected element
+ */
+ static getDOMElement(selector) {
+ let element = document.querySelector(selector),
+ style = window.getComputedStyle(element);
+ element.style.left = style.left;
+ element.style.top = style.top;
+ element.style.width = style.width;
+ element.style.height = style.height;
+ return element;
+ }
} |
fd626a11bcb51fd499cab6aa24ba3c1ac1f4603a | src/js/settings.js | src/js/settings.js | this.mmooc = this.mmooc || {};
// Course ID for selected course, which frontend page
// will be swapped with All Courses list
const allCoursesFrontpageCourseID = 14;
this.mmooc.settings = {
CanvaBadgeProtocolAndHost: 'https://canvabadges-beta-iktsenteret.bibsys.no',
useCanvaBadge: false,
defaultNumberOfReviews: 1, // Default number of peer reviews per student in power function
disablePeerReviewButton: true,
removeGlobalGradesLink: true,
removeGroupsLink: true,
privacyPolicyLink: 'http://matematikk-mooc.github.io/privacypolicy.html',
platformName: 'matematikk.mooc.no',
allCoursesFrontpageCourseID,
feideEnrollRefferers: [
'/search/all_courses',
`/courses/${allCoursesFrontpageCourseID}`,
],
};
| this.mmooc = this.mmooc || {};
// Course ID for selected course, which frontend page
// will be swapped with All Courses list
const allCoursesFrontpageCourseID = 1;
this.mmooc.settings = {
CanvaBadgeProtocolAndHost: 'https://canvabadges-beta-iktsenteret.bibsys.no',
useCanvaBadge: false,
defaultNumberOfReviews: 1, // Default number of peer reviews per student in power function
disablePeerReviewButton: true,
removeGlobalGradesLink: true,
removeGroupsLink: true,
privacyPolicyLink: 'http://matematikk-mooc.github.io/privacypolicy.html',
platformName: 'matematikk.mooc.no',
allCoursesFrontpageCourseID,
feideEnrollRefferers: [
'/search/all_courses',
`/courses/${allCoursesFrontpageCourseID}`,
],
};
| Set allCoursesFrontpageCourseID to 1 as default. | Set allCoursesFrontpageCourseID to 1 as default.
| JavaScript | mit | matematikk-mooc/frontend,matematikk-mooc/frontend | ---
+++
@@ -2,7 +2,7 @@
// Course ID for selected course, which frontend page
// will be swapped with All Courses list
-const allCoursesFrontpageCourseID = 14;
+const allCoursesFrontpageCourseID = 1;
this.mmooc.settings = {
CanvaBadgeProtocolAndHost: 'https://canvabadges-beta-iktsenteret.bibsys.no', |
626ce2749810d9386c1ae8454796c0ee7cafc23c | src/link_engine.js | src/link_engine.js | var performImage = function() {
var t=[];
function prepareString(withUrl) {
return '<a href="' + withUrl + '"><img title="'+ withUrl +'" src="' + withUrl + '"></a>';
}
// Image tags are the easiest to do. Loop thru the set, and pull up the images out
Array.prototype.slice.call(document.getElementsByTagName('img')).forEach(function(imgTag) {
t.push(prepareString(imgTag));
});
// now inspect elements that are applied to background elements
var reImg = /^url\(\"/;
Array.prototype.slice.call(document.querySelectorAll('body *')).filter(function(element) {
// check for cases where no image is defined
return window.getComputedStyle(element).backgroundImage !== 'none';
}).filter(function(element) {
// find elements that are inline images
return reImg.test(window.getComputedStyle(element).backgroundImage);
}).map(function(element) {
// trim CSS wrapping for URLs
return window.getComputedStyle(element).backgroundImage.split('url("')[1].slice(0, -2);
}).forEach(function(url) {
// push to result array
t.push(prepareString(url));
});
return t.length ? t.join('') : '<h1>No Images Present</h1>';
};
| var performImage = function() {
var t=[];
function prepareString(withUrl) {
return '<a href="' + withUrl + '"><img title="'+ withUrl +'" src="' + withUrl + '"></a>';
}
// Image tags are the easiest to do. Loop thru the set, and pull up the images out
Array.prototype.slice.call(document.getElementsByTagName('img')).forEach(function(imgTag) {
t.push(prepareString(imgTag.src));
});
// now inspect elements that are applied to background elements
var reImg = /^url\(\"/;
Array.prototype.slice.call(document.querySelectorAll('body *')).filter(function(element) {
// check for cases where no image is defined
return window.getComputedStyle(element).backgroundImage !== 'none';
}).filter(function(element) {
// find elements that are inline images
return reImg.test(window.getComputedStyle(element).backgroundImage);
}).map(function(element) {
// trim CSS wrapping for URLs
return window.getComputedStyle(element).backgroundImage.split('url("')[1].slice(0, -2);
}).forEach(function(url) {
// push to result array
t.push(prepareString(url));
});
return t.length ? t.join('') : '<h1>No Images Present</h1>';
};
| Fix handling of image tag sources | Fix handling of image tag sources
| JavaScript | mit | booc0mtaco/image-sourcer,booc0mtaco/image-sourcer,booc0mtaco/image-sourcer | ---
+++
@@ -6,7 +6,7 @@
// Image tags are the easiest to do. Loop thru the set, and pull up the images out
Array.prototype.slice.call(document.getElementsByTagName('img')).forEach(function(imgTag) {
- t.push(prepareString(imgTag));
+ t.push(prepareString(imgTag.src));
});
// now inspect elements that are applied to background elements |
871c29ed5273a08ca0f4a3413a62ac513c574974 | client/test/reducer.spec.js | client/test/reducer.spec.js | import React from 'react';
import { expect } from 'chai';
import { List as ImmutableList, Map } from 'immutable';
import reducer from '../src/reducer';
describe('reducer', () => {
it('should return the initial state', () => {
const actual = reducer(undefined, {});
const expected = ImmutableList.of();
expect(actual).to.eql(expected);
});
it('should handle ADD_STICKER', () => {
const sticker = new Map({ id: 100, image: 'foo.png' });
const actual = reducer(ImmutableList.of(), { type: 'ADD_STICKER', sticker });
const expected = ImmutableList.of(new Map({ id: 100, image: 'foo.png' }));
expect(actual).to.eql(expected);
});
});
| import React from 'react';
import { expect } from 'chai';
import { List as ImmutableList, Map } from 'immutable';
import reducer from '../src/reducer';
describe('reducer', () => {
it('should return the initial state', () => {
const actual = reducer(undefined, {});
const expected = ImmutableList.of();
expect(actual).to.eql(expected);
});
it('should handle ADD_STICKER', () => {
const sticker = new Map({ id: 100, image: 'foo.png' });
const actual = reducer(ImmutableList.of(), { type: 'ADD_STICKER', sticker });
const expected = ImmutableList.of(new Map({ id: 100, image: 'foo.png' }));
expect(actual).to.eql(expected);
});
describe('CLEAR_CUSTOMIZATION', () => {
it('should return an empty list', () => {
const sticker = new Map({ id: 100, image: 'foo.png' });
const actual = reducer(
ImmutableList.of(sticker, sticker),
{ type: 'CLEAR_CUSTOMIZATION' }
);
const expected = ImmutableList.of();
expect(actual).to.eql(expected);
});
})
});
| Add missing test for reducer action CLEAR_CUSTOMIZATION | Add missing test for reducer action CLEAR_CUSTOMIZATION
| JavaScript | mit | marlonbernardes/coding-stickers,marlonbernardes/coding-stickers | ---
+++
@@ -18,4 +18,18 @@
expect(actual).to.eql(expected);
});
+ describe('CLEAR_CUSTOMIZATION', () => {
+ it('should return an empty list', () => {
+ const sticker = new Map({ id: 100, image: 'foo.png' });
+ const actual = reducer(
+ ImmutableList.of(sticker, sticker),
+ { type: 'CLEAR_CUSTOMIZATION' }
+ );
+
+ const expected = ImmutableList.of();
+ expect(actual).to.eql(expected);
+ });
+ })
+
+
}); |
bb5b1ebe76361ccf064f96d4c0036e29017946e9 | frontend/app/assets/javascripts/spree/frontend/views/spree/home/product_carousels.js | frontend/app/assets/javascripts/spree/frontend/views/spree/home/product_carousels.js | //= require spree/frontend/viewport
Spree.fetchProductCarousel = function (taxonId, htmlContainer) {
return $.ajax({
url: Spree.routes.product_carousel(taxonId)
}).done(function (data) {
htmlContainer.html(data);
htmlContainer.find('.carousel').carouselBootstrap4()
})
}
Spree.loadCarousel = function (element, div) {
var container = $(element)
var productCarousel = $(div)
var carouselLoaded = productCarousel.attr('data-product-carousel-loaded')
if (container.length && !carouselLoaded && container.isInViewport()) {
var taxonId = productCarousel.attr('data-product-carousel-taxon-id')
productCarousel.attr('data-product-carousel-loaded', 'true')
Spree.fetchProductCarousel(taxonId, container)
}
}
Spree.loadsCarouselElements = function () {
$('div[data-product-carousel').each(function (_index, element) { Spree.loadCarousel(element, this) })
}
document.addEventListener('turbolinks:load', function () {
var homePage = $('body#home')
if (homePage.length) {
// load Carousels straight away if they are in the viewport
Spree.loadsCarouselElements()
// load additional Carousels when scrolling down
$(window).on('resize scroll', function () {
Spree.loadsCarouselElements()
})
}
})
| //= require spree/frontend/viewport
Spree.fetchProductCarousel = function (taxonId, htmlContainer) {
return $.ajax({
url: Spree.routes.product_carousel(taxonId)
}).done(function (data) {
htmlContainer.html(data);
htmlContainer.find('.carousel').carouselBootstrap4()
})
}
Spree.loadCarousel = function (element, div) {
var container = $(element)
var productCarousel = $(div)
var carouselLoaded = productCarousel.attr('data-product-carousel-loaded')
if (container.length && !carouselLoaded && container.isInViewport()) {
var taxonId = productCarousel.attr('data-product-carousel-taxon-id')
productCarousel.attr('data-product-carousel-loaded', 'true')
Spree.fetchProductCarousel(taxonId, container)
}
}
Spree.loadsCarouselElements = function () {
$('div[data-product-carousel]').each(function (_index, element) { Spree.loadCarousel(element, this) })
}
document.addEventListener('turbolinks:load', function () {
var homePage = $('body#home')
if (homePage.length) {
// load Carousels straight away if they are in the viewport
Spree.loadsCarouselElements()
// load additional Carousels when scrolling down
$(window).on('resize scroll', function () {
Spree.loadsCarouselElements()
})
}
})
| Fix homepage carousels on iOS | [SD-770] Fix homepage carousels on iOS
| JavaScript | bsd-3-clause | imella/spree,imella/spree,ayb/spree,imella/spree,ayb/spree,ayb/spree,ayb/spree | ---
+++
@@ -23,7 +23,7 @@
}
Spree.loadsCarouselElements = function () {
- $('div[data-product-carousel').each(function (_index, element) { Spree.loadCarousel(element, this) })
+ $('div[data-product-carousel]').each(function (_index, element) { Spree.loadCarousel(element, this) })
}
document.addEventListener('turbolinks:load', function () { |
1b5f10b9c975b8a055d830e8ac5e112dd059c7d5 | electron/index.js | electron/index.js | var menubar = require('menubar');
var ipc = require('ipc');
var shell = require('shell')
var mb = menubar({
dir: __dirname,
width: 280,
height: 87
});
mb.on('ready', function ready () {
require('../server');
})
ipc.on('browser', function browser (ev) {
shell.openExternal('http://localhost:3000')
})
ipc.on('terminate', function terminate (ev) {
canQuit = true
mb.app.terminate()
})
ipc.on('homepage', function homepage (ev) {
shell.openExternal('http://lightning-viz.org')
}) | var menubar = require('menubar');
var ipc = require('ipc');
var shell = require('shell')
var mb = menubar({
dir: __dirname,
width: 280,
height: 87,
icon: __dirname + '/Icon.png'
});
mb.on('ready', function ready () {
require('../server');
})
ipc.on('browser', function browser (ev) {
shell.openExternal('http://localhost:3000')
})
ipc.on('terminate', function terminate (ev) {
canQuit = true
mb.app.terminate()
})
ipc.on('homepage', function homepage (ev) {
shell.openExternal('http://lightning-viz.org')
}) | Fix for updated default icon name | Fix for updated default icon name
| JavaScript | mit | origingod/lightning,karissa/lightning,lightning-viz/lightning,cournape/lightning,cournape/lightning,lightning-viz/lightning,origingod/lightning,karissa/lightning | ---
+++
@@ -5,7 +5,8 @@
var mb = menubar({
dir: __dirname,
width: 280,
- height: 87
+ height: 87,
+ icon: __dirname + '/Icon.png'
});
mb.on('ready', function ready () { |
c8f91cf8b2d5b1d0c59e80b3c0fb9f25a49d935e | src/api/index.js | src/api/index.js | import moment from 'moment';
import { maxPages } from '../../data/config';
// Prevent webpack window problem
const isBrowser = () => typeof window !== 'undefined';
const isPage = () => (isBrowser() ? window.location.pathname.indexOf('page') === -1 : false);
const getCurrentPage = () => {
if (isBrowser() === true) {
const str = window.location.pathname;
if (str.indexOf('page') !== -1) {
// Return the last pathname in number
return +window.location.pathname.match(/page[/](\d)/)[1];
}
}
return 0;
};
const getPath = () => (isBrowser() ? window.location.href : '');
const getMaxPages = () => maxPages;
const overflow = () => getCurrentPage() === getMaxPages();
const parseDate = date => moment(date).locale('zh-hk').format('YYYY/MM/DD');
const parseChineseDate = date => moment(date).locale('zh-hk').format('L');
const isFirstPage = () => (isBrowser() ? isPage() : false);
const isLastPage = () => (isBrowser() ? overflow() : false);
export {
isBrowser, isPage,
getCurrentPage, getMaxPages,
overflow, parseDate,
isFirstPage, isLastPage,
parseChineseDate,
getPath,
};
| import moment from 'moment';
import { maxPages } from '../../data/config';
// Prevent webpack window problem
const isBrowser = () => typeof window !== 'undefined';
const isPage = () => (isBrowser() ? window.location.pathname.indexOf('page') === -1 : false);
const getCurrentPage = () => {
if (isBrowser() === true) {
const str = window.location.pathname;
if (str.indexOf('page') !== -1) {
// Return the last pathname in number
return +window.location.pathname.match(/page[/](\d)/)[1];
}
}
return 0;
};
const getPath = () => (isBrowser() ? window.location.href : '');
const getMaxPages = () => maxPages;
const overflow = () => getCurrentPage() === getMaxPages();
const parseDate = date => moment(date).locale('zh-hk').format('YYYY/MM/DD');
const parseChineseDate = date => moment(date).locale('zh-hk').format('DD/MM/YYYY');
const isFirstPage = () => (isBrowser() ? isPage() : false);
const isLastPage = () => (isBrowser() ? overflow() : false);
export {
isBrowser, isPage,
getCurrentPage, getMaxPages,
overflow, parseDate,
isFirstPage, isLastPage,
parseChineseDate,
getPath,
};
| Fix date bug in moment.js | Fix date bug in moment.js
| JavaScript | mit | calpa/blog | ---
+++
@@ -26,7 +26,7 @@
const parseDate = date => moment(date).locale('zh-hk').format('YYYY/MM/DD');
-const parseChineseDate = date => moment(date).locale('zh-hk').format('L');
+const parseChineseDate = date => moment(date).locale('zh-hk').format('DD/MM/YYYY');
const isFirstPage = () => (isBrowser() ? isPage() : false);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.