commit
stringlengths 40
40
| old_file
stringlengths 4
264
| new_file
stringlengths 4
264
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
624
| message
stringlengths 15
4.7k
| lang
stringclasses 3
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
---|---|---|---|---|---|---|---|---|---|
8fae4b14a95f17adbefce5a33132c556197cadc1 | riotcontrol.js | riotcontrol.js | var RiotControl = {
_stores: [],
addStore: function(store) {
this._stores.push(store);
}
};
['on','one','off','trigger'].forEach(function(api){
RiotControl[api] = function() {
var args = [].slice.call(arguments);
this._stores.forEach(function(el){
el[api].apply(null, args);
});
};
});
if (typeof(module) !== 'undefined') module.exports = RiotControl;
| var RiotControl = {
_stores: [],
addStore: function(store) {
this._stores.push(store);
}
};
['on','one','off','trigger'].forEach(function(api){
RiotControl[api] = function() {
var args = [].slice.call(arguments);
this._stores.forEach(function(el){
el[api].apply(el, args);
});
};
});
if (typeof(module) !== 'undefined') module.exports = RiotControl;
| Make riot control compatible with other observable systems | Make riot control compatible with other observable systems | JavaScript | mit | jimsparkman/RiotControl,creatorrr/RiotControl,creatorrr/RiotControl,nnjpp/RiotDispatch,geoapi/RiotControl,geoapi/RiotControl,jimsparkman/RiotControl |
e37ab30622a50614f226dc746d7e7b68b2afd792 | lib/index.js | lib/index.js | var Keen = require('keen-tracking');
var extend = require('keen-tracking/lib/utils/extend');
// Accessor methods
function readKey(str){
if (!arguments.length) return this.config.readKey;
this.config.readKey = (str ? String(str) : null);
return this;
}
function queryPath(str){
if (!arguments.length) return this.config.readPath;
if (!this.projectId()) {
this.emit('error', 'Keen is missing a projectId property');
return;
}
this.config.readPath = (str ? String(str) : ('/3.0/projects/' + this.projectId() + '/queries'));
return this;
}
// Query method
function query(){}
// HTTP methods
function get(){}
function post(){}
function put(){}
function del(){}
// Extend client instance
extend(Keen.prototype, {
'readKey' : readKey,
'queryPath' : queryPath,
'query' : query,
'get' : get,
'post' : post,
'put' : put,
'del' : del
});
module.exports = Keen;
| var Keen = require('keen-tracking');
var extend = require('keen-tracking/lib/utils/extend');
// Accessor methods
function readKey(str){
if (!arguments.length) return this.config.readKey;
this.config.readKey = str ? String(str) : null;
return this;
}
function queryPath(str){
if (!arguments.length) return this.config.queryPath;
if (!this.projectId()) {
this.emit('error', 'Keen is missing a projectId property');
return;
}
this.config.queryPath = str ? String(str) : ('/3.0/projects/' + this.projectId() + '/queries');
return this;
}
// Query method
function query(){}
// HTTP methods
function get(){}
function post(){}
function put(){}
function del(){}
// Extend client instance
extend(Keen.prototype, {
'readKey' : readKey,
'queryPath' : queryPath,
'query' : query,
'get' : get,
'post' : post,
'put' : put,
'del' : del
});
// console.log(new Keen({ projectId: '123' }).queryPath('test').queryPath());
module.exports = Keen;
| Clean up method names and internals | Clean up method names and internals
| JavaScript | mit | keen/keen-analysis.js,keen/keen-analysis.js |
d5815ce2b68695a548b0972e6c3f5928ba887673 | lib/index.js | lib/index.js | 'use strict';
var rump = module.exports = require('rump');
var configs = require('./configs');
var originalAddGulpTasks = rump.addGulpTasks;
// TODO remove on next major core update
rump.addGulpTasks = function(options) {
originalAddGulpTasks(options);
require('./gulp');
return rump;
};
rump.on('update:main', function() {
configs.rebuild();
rump.emit('update:scripts');
});
Object.defineProperty(rump.configs, 'uglifyjs', {
get: function() {
return configs.uglifyjs;
}
});
Object.defineProperty(rump.configs, 'webpack', {
get: function() {
return configs.webpack;
}
});
| 'use strict';
var fs = require('fs');
var path = require('path');
var rump = module.exports = require('rump');
var ModuleFilenameHelpers = require('webpack/lib/ModuleFilenameHelpers');
var configs = require('./configs');
var originalAddGulpTasks = rump.addGulpTasks;
var protocol = process.platform === 'win32' ? 'file:///' : 'file://';
// TODO remove on next major core update
rump.addGulpTasks = function(options) {
originalAddGulpTasks(options);
require('./gulp');
return rump;
};
rump.on('update:main', function() {
configs.rebuild();
rump.emit('update:scripts');
});
// Rewrite source map URL for consistency
ModuleFilenameHelpers.createFilename = function(module) {
var url;
if(typeof module === 'string') {
url = module.split('!').pop();
}
else {
url = module.resourcePath || module.identifier().split('!').pop();
}
if(fs.existsSync(url)) {
url = protocol + url.split(path.sep).join('/');
}
else {
return '';
}
return url;
};
Object.defineProperty(rump.configs, 'uglifyjs', {
get: function() {
return configs.uglifyjs;
}
});
Object.defineProperty(rump.configs, 'webpack', {
get: function() {
return configs.webpack;
}
});
| Rewrite source map URLs for consistency | Rewrite source map URLs for consistency
| JavaScript | mit | rumps/scripts,rumps/rump-scripts |
5d674572dcce72f756d5c74704ec1d809ac864cb | lib/index.js | lib/index.js | var config = require('./config.js');
var jsonLdContext = require('./context.json');
var MetadataService = require('./metadata-service.js');
var Organism = require('./organism.js');
var Xref = require('./xref.js');
var BridgeDb = {
getEntityReferenceIdentifiersIri: function(metadataForDbName, dbId, callback) {
var iri = metadataForDbName.linkoutPattern.replace('$id', dbId);
return iri;
},
init: function(options) {
console.log('BridgeDb instance');
console.log(options);
this.config = Object.create(config);
this.config.apiUrlStub = (!!options && options.apiUrlStub) || config.apiUrlStub;
this.organism = Object.create(Organism(this));
this.xref = Object.create(Xref(this));
},
config: config,
organism: Organism(this),
xref: Xref(this)
};
var BridgeDbInstanceCreator = function(options) {
var bridgedbInstance = Object.create(BridgeDb);
bridgedbInstance.init(options);
return bridgedbInstance;
};
module.exports = BridgeDbInstanceCreator;
| var config = require('./config.js');
var jsonLdContext = require('./context.json');
var MetadataService = require('./metadata-service.js');
var Organism = require('./organism.js');
var Xref = require('./xref.js');
var BridgeDb = {
getEntityReferenceIdentifiersIri: function(metadataForDbName, dbId, callback) {
var iri = metadataForDbName.linkoutPattern.replace('$id', dbId);
return iri;
},
init: function(options) {
console.log('BridgeDb instance');
console.log(options);
this.config = Object.create(config);
// TODO loop through properties on options.config, if any, and update the instance config values.
this.config.apiUrlStub = (!!options && options.apiUrlStub) || config.apiUrlStub;
this.config.datasourcesUrl = (!!options && options.datasourcesUrl) || config.datasourcesUrl;
this.organism = Object.create(Organism(this));
this.xref = Object.create(Xref(this));
},
config: config,
organism: Organism(this),
xref: Xref(this)
};
var BridgeDbInstanceCreator = function(options) {
var bridgedbInstance = Object.create(BridgeDb);
bridgedbInstance.init(options);
return bridgedbInstance;
};
module.exports = BridgeDbInstanceCreator;
| Update handling of datasources.txt URL | Update handling of datasources.txt URL
| JavaScript | apache-2.0 | bridgedb/bridgedbjs,bridgedb/bridgedbjs,egonw/bridgedbjs,bridgedb/bridgedbjs |
ecb93921a112556a307505aec1d249b9fcc27f1d | lib/track.js | lib/track.js | var Util = require('./util.js');
module.exports = Track = function(vid, info) {
this.vid = vid;
this.title = info.title;
this.author = info.author;
this.viewCount = info.viewCount || info.view_count;
this.lengthSeconds = info.lengthSeconds || info.length_seconds;
};
Track.prototype.formatViewCount = function() {
return this.viewCount ? this.viewCount.replace(/\B(?=(\d{3})+(?!\d))/g, ',') : 'unknown';
};
Track.prototype.formatTime = function() {
return Util.formatTime(this.lengthSeconds);
};
Track.prototype.prettyPrint = function() {
return `**${this.title}** by **${this.author}** *(${this.formatViewCount()} views)* [${this.formatTime()}]`;
};
Track.prototype.fullPrint = function() {
return `${this.prettyPrint()}, added by <@${this.userId}>`;
};
Track.prototype.saveable = function() {
return {
vid: this.vid,
title: this.title,
author: this.author,
viewCount: this.viewCount,
lengthSeconds: this.lengthSeconds,
};
};
| var Util = require('./util.js');
module.exports = Track = function(vid, info) {
this.vid = vid;
this.title = info.title;
this.author = info.author;
this.viewCount = info.viewCount || info.view_count;
this.lengthSeconds = info.lengthSeconds || info.length_seconds;
};
Track.prototype.formatViewCount = function() {
return this.viewCount ? this.viewCount.replace(/\B(?=(\d{3})+(?!\d))/g, ',') : 'unknown';
};
Track.prototype.formatTime = function() {
return Util.formatTime(this.lengthSeconds);
};
Track.prototype.prettyPrint = function() {
return `**${this.title}** by **${this.author}** *(${this.formatViewCount()} views)* [${this.formatTime()}]`;
};
Track.prototype.fullPrint = function() {
return `${this.prettyPrint()}, added by <@${this.userId}>`;
};
Track.prototype.saveable = function() {
return {
vid: this.vid,
title: this.title,
author: this.author,
viewCount: this.viewCount,
lengthSeconds: this.lengthSeconds,
};
};
Track.prototype.getTime = function() {
return this.lengthSeconds;
};
| Add getTime function to get remaining time | Add getTime function to get remaining time | JavaScript | mit | meew0/Lethe |
5e41bab44fe3cdd1d160198cbe9ec3aeebf1fdcc | jupyter-js-widgets/src/embed-webpack.js | jupyter-js-widgets/src/embed-webpack.js |
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
// This file must be webpacked because it contains .css imports
// Load jquery and jquery-ui
var $ = require('jquery');
require('jquery-ui');
window.$ = window.jQuery = $;
require('jquery-ui');
// Load styling
require('jquery-ui/themes/smoothness/jquery-ui.min.css');
require('../css/widgets.min.css');
const widgets = require('./index');
console.info('jupyter-js-widgets loaded successfully');
const manager = new widgets.EmbedManager();
// Magic global widget rendering function:
function renderInlineWidgets(element) {
var element = element || document;
var tags = element.querySelectorAll('script.jupyter-widgets');
for (var i=0; i!=tags.length; ++i) {
var tag = tags[i];
var widgetStateObject = JSON.parse(tag.innerHTML);
var widgetContainer = document.createElement('div');
widgetContainer.className = 'widget-area';
manager.display_widget_state(widgetStateObject, widgetContainer).then(function() {
tag.parentElement.insertBefore(widgetContainer, tag);
});
}
}
// Module exports
exports.manager = manager;
exports.renderInlineWidgets = renderInlineWidgets;
// Set window globals
window.manager = manager;
window.onload = renderInlineWidgets;
|
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
// This file must be webpacked because it contains .css imports
// Load jquery and jquery-ui
var $ = require('jquery');
require('jquery-ui');
window.$ = window.jQuery = $;
require('jquery-ui');
// Load styling
require('jquery-ui/themes/smoothness/jquery-ui.min.css');
require('../css/widgets.min.css');
const widgets = require('./index');
console.info('jupyter-js-widgets loaded successfully');
const manager = new widgets.EmbedManager();
// Magic global widget rendering function:
function renderInlineWidgets(event) {
var element = event.target || document;
var tags = element.querySelectorAll('script.jupyter-widgets');
for (var i=0; i!=tags.length; ++i) {
var tag = tags[i];
var widgetStateObject = JSON.parse(tag.innerHTML);
var widgetContainer = document.createElement('div');
widgetContainer.className = 'widget-area';
manager.display_widget_state(widgetStateObject, widgetContainer).then(function() {
tag.parentElement.insertBefore(widgetContainer, tag);
});
}
}
// Module exports
exports.manager = manager;
exports.renderInlineWidgets = renderInlineWidgets;
// Set window globals
window.manager = manager;
window.addEventListener('load', renderInlineWidgets);
| Use addEventListener('load' instead of onload | Use addEventListener('load' instead of onload
| JavaScript | bsd-3-clause | cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,ipython/ipywidgets |
18d33de0c54e64693274bc17afb1a08b9fec5ad8 | app/public/panel/controllers/DashCtrl.js | app/public/panel/controllers/DashCtrl.js | var angular = require('angular');
angular.module('DashCtrl', ['chart.js']).controller('DashController', ['$scope', $scope => {
const colorScheme = ['#2a9fd6'];
let weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
for(let i = 0; i < 6 - (new Date()).getDay(); i++) {
const back = weekDays.pop();
weekDays.unshift(back);
}
$scope.uploadColors = colorScheme;
$scope.uploadLabels = weekDays;
$scope.uploadSeries = ['Uploads'];
$scope.uploadData = [[10, 20, 30, 20, 15, 20, 45]];
$scope.uploadOptions = {
title: {
display: true,
text: 'Historical Uploads'
},
};
$scope.viewColors = colorScheme;
$scope.viewLabels = weekDays;
$scope.viewSeries = ['Views'];
$scope.viewData = [[5, 11, 4, 3, 7, 9, 21]];
$scope.viewOptions = {
title: {
display: true,
text: 'Historical Views'
}
};
}]);
{
} | var angular = require('angular');
angular.module('DashCtrl', ['chart.js']).controller('DashController', ['$scope', $scope => {
const colorScheme = ['#2a9fd6'];
// Calculate and format descending dates back one week
const currentDate = new Date();
const oneDay = 1000 * 60 * 60 * 24;
let dates = Array.from({length: 7}, (date, i) => new Date(currentDate - oneDay * (6 - i)));
let labels = dates.map(date => date.toISOString().substr(5, 5));
$scope.uploadColors = colorScheme;
$scope.uploadLabels = labels;
$scope.uploadSeries = ['Uploads'];
$scope.uploadData = [[10, 20, 30, 20, 15, 20, 45]];
$scope.uploadOptions = {
title: {
display: true,
text: 'Historical Uploads'
},
};
$scope.viewColors = colorScheme;
$scope.viewLabels = labels;
$scope.viewSeries = ['Views'];
$scope.viewData = [[5, 11, 4, 3, 7, 9, 21]];
$scope.viewOptions = {
title: {
display: true,
text: 'Historical Views'
}
};
}]);
{
} | Fix date and label calculation | Fix date and label calculation
| JavaScript | mit | Foltik/Shimapan,Foltik/Shimapan |
323b195642bab258001da6b0a85ca998e8697d3d | static/js/submit.js | static/js/submit.js | $(document).ready(function()
{
$("#invite-form").on('submit', function()
{
var inviteeEmail = $("#email").val();
console.log(inviteeEmail)
if (!inviteeEmail || !inviteeEmail.length) {
alert('Please enter an email');
return false;
}
$.ajax({
type: "POST",
url: "/",
headers: {
'X-CSRFToken': csrfToken,
},
data: { email: inviteeEmail},
success: function(data) {
handleResponse(data);
}
});
return false;
});
});
function handleResponse(data) {
document.data = data
if (data.status === 'success') {
console.log('success')
}
if (data.status === 'fail') {
console.log('failed')
}
} | $(document).ready(function()
{
$("#invite-form").on('submit', function()
{
var inviteeEmail = $("#email").val();
console.log(inviteeEmail)
if (!inviteeEmail || !inviteeEmail.length) {
alert('Please enter an email');
return false;
}
$.ajax({
type: "POST",
url: "/",
headers: {
'X-CSRFToken': csrfToken,
},
data: { email: inviteeEmail},
success: function(data) {
handleResponse(data);
}
});
return false;
});
});
function handleResponse(data) {
document.data = data
if (data.status === 'success') {
console.log('success')
Materialize.toast('Success!', 4000)
}
if (data.status === 'fail') {
Materialize.toast(data.error, 4000)
}
} | Use Materialize toasts to show the status | Use Materialize toasts to show the status
| JavaScript | mit | avinassh/slackipy,avinassh/slackipy,avinassh/slackipy |
63618d2180dfc52c922857eb6aabb2e195b637da | lib/helpers/redirect-to-organization.js | lib/helpers/redirect-to-organization.js | 'use strict';
var url = require('url');
var getHost = require('./get-host');
module.exports = function redirectToOrganization(req, res, organization) {
res.redirect(req.protocol + '://' + organization.nameKey + '.' + getHost(req) + url.parse(req.url).pathname);
};
| 'use strict';
var url = require('url');
var getHost = require('./get-host');
module.exports = function redirectToOrganization(req, res, organization) {
var uri = req.protocol
+ '://' + organization.nameKey
+ '.'
+ getHost(req)
+ url.parse(req.url).pathname;
var queryParams = Object.keys(req.query);
if (queryParams.length > 0) {
uri += '?' + queryParams.map(function (param) {
return encodeURIComponent(param)
+ '='
+ encodeURIComponent(req.query[param]);
}).join('&');
}
res.redirect(uri);
};
| Fix behaviour for redirect with query params | Fix behaviour for redirect with query params
| JavaScript | apache-2.0 | stormpath/express-stormpath,stormpath/express-stormpath,stormpath/express-stormpath |
a8e03f01c9b67d6b39c627d94f1f95ee706f7284 | batch/job_queue.js | batch/job_queue.js | 'use strict';
function JobQueue(metadataBackend, jobPublisher) {
this.metadataBackend = metadataBackend;
this.jobPublisher = jobPublisher;
}
module.exports = JobQueue;
var QUEUE = {
DB: 5,
PREFIX: 'batch:queue:'
};
module.exports.QUEUE = QUEUE;
JobQueue.prototype.enqueue = function (user, jobId, callback) {
var self = this;
this.metadataBackend.redisCmd(QUEUE.DB, 'LPUSH', [ QUEUE.PREFIX + user, jobId ], function (err) {
if (err) {
return callback(err);
}
self.jobPublisher.publish(user);
callback();
});
};
JobQueue.prototype.size = function (user, callback) {
this.metadataBackend.redisCmd(QUEUE.DB, 'LLEN', [ QUEUE.PREFIX + user ], callback);
};
JobQueue.prototype.dequeue = function (user, callback) {
this.metadataBackend.redisCmd(QUEUE.DB, 'RPOP', [ QUEUE.PREFIX + user ], callback);
};
JobQueue.prototype.enqueueFirst = function (user, jobId, callback) {
this.metadataBackend.redisCmd(QUEUE.DB, 'RPUSH', [ QUEUE.PREFIX + user, jobId ], callback);
};
| 'use strict';
var debug = require('./util/debug')('queue');
function JobQueue(metadataBackend, jobPublisher) {
this.metadataBackend = metadataBackend;
this.jobPublisher = jobPublisher;
}
module.exports = JobQueue;
var QUEUE = {
DB: 5,
PREFIX: 'batch:queue:'
};
module.exports.QUEUE = QUEUE;
JobQueue.prototype.enqueue = function (user, jobId, callback) {
debug('JobQueue.enqueue user=%s, jobId=%s', user, jobId);
this.metadataBackend.redisCmd(QUEUE.DB, 'LPUSH', [ QUEUE.PREFIX + user, jobId ], function (err) {
if (err) {
return callback(err);
}
this.jobPublisher.publish(user);
callback();
}.bind(this));
};
JobQueue.prototype.size = function (user, callback) {
this.metadataBackend.redisCmd(QUEUE.DB, 'LLEN', [ QUEUE.PREFIX + user ], callback);
};
JobQueue.prototype.dequeue = function (user, callback) {
this.metadataBackend.redisCmd(QUEUE.DB, 'RPOP', [ QUEUE.PREFIX + user ], function(err, jobId) {
debug('JobQueue.dequeued user=%s, jobId=%s', user, jobId);
return callback(err, jobId);
});
};
JobQueue.prototype.enqueueFirst = function (user, jobId, callback) {
debug('JobQueue.enqueueFirst user=%s, jobId=%s', user, jobId);
this.metadataBackend.redisCmd(QUEUE.DB, 'RPUSH', [ QUEUE.PREFIX + user, jobId ], callback);
};
| Add debug information in Jobs Queue | Add debug information in Jobs Queue
| JavaScript | bsd-3-clause | CartoDB/CartoDB-SQL-API,CartoDB/CartoDB-SQL-API |
689b3bc608f4892686b0330f30dca188b59c04a9 | playground/server.js | playground/server.js | import React from 'react';
import Playground from './index.js';
import express from 'express';
import ReactDOMServer from 'react-dom/server';
const app = express();
const port = 8000;
app.get('/', function(req, resp) {
const html = ReactDOMServer.renderToString(
React.createElement(Playground)
);
resp.send(html);
});
app.listen(port, function() {
console.log(`http://localhost:'${port}`); // eslint-disable-line no-console
});
| import React from 'react';
import Playground from './index.js';
import express from 'express';
import ReactDOMServer from 'react-dom/server';
const app = express();
const port = 8000;
app.get('/', function(req, resp) {
const html = ReactDOMServer.renderToString(
React.createElement(Playground)
);
resp.send(html);
});
app.listen(port, function() {
console.log(`http://localhost:${port}`); // eslint-disable-line no-console
});
| Fix typo in playground listen log | Fix typo in playground listen log
| JavaScript | mit | benox3/react-pic |
1c42a6e807b644a246b62c43f1494a906c130447 | spec/server-pure/spec.render_png.js | spec/server-pure/spec.render_png.js | var renderPng = require('../../app/render_png');
describe('renderPng', function () {
describe('getScreenshotPath', function () {
it('creates the URL for the screenshot service call', function () {
renderPng.screenshotServiceUrl = 'http://screenshotservice';
renderPng.screenshotTargetUrl = 'http://spotlight';
var url = '/test/path.png';
var screenshotPath = renderPng.getScreenshotPath(url);
expect(screenshotPath).toEqual('http://screenshotservice?readyExpression=!!document.querySelector(".loaded")&forwardCacheHeaders=true&clipSelector=.visualisation&url=http://spotlight/test/path?raw');
});
});
});
| var renderPng = require('../../app/render_png');
describe('renderPng', function () {
describe('getScreenshotPath', function () {
it('creates the URL for the screenshot service call', function () {
renderPng.screenshotServiceUrl = 'http://screenshotservice';
renderPng.screenshotTargetUrl = 'http://spotlight';
var url = '/test/path.png';
var screenshotPath = renderPng.getScreenshotPath({
url: url,
query: {}
});
expect(screenshotPath).toEqual('http://screenshotservice?readyExpression=!!document.querySelector(".loaded")&forwardCacheHeaders=true&clipSelector=.visualisation-inner figure&url=http://spotlight/test/path');
});
});
});
| Fix qs params in screenshot url tests | Fix qs params in screenshot url tests
| JavaScript | mit | keithiopia/spotlight,alphagov/spotlight,alphagov/spotlight,keithiopia/spotlight,alphagov/spotlight,tijmenb/spotlight,keithiopia/spotlight,tijmenb/spotlight,tijmenb/spotlight |
8ffe7ba8783c85de062299f709a4a8d8a68eeef5 | packages/@sanity/base/src/preview/ReferencePreview.js | packages/@sanity/base/src/preview/ReferencePreview.js | import React, {PropTypes} from 'react'
import resolveRefType from './resolveRefType'
import {resolver as previewResolver} from 'part:@sanity/base/preview'
export default class SanityPreview extends React.PureComponent {
static propTypes = {
value: PropTypes.object,
type: PropTypes.object.isRequired
};
state = {
loading: true,
materialized: null,
refType: null
}
resolveRefType(value, type) {
resolveRefType(value, type).then(refType => {
this.setState({
refType
})
})
}
componentDidMount() {
const {type, value} = this.props
this.resolveRefType(value, type)
}
componentWillReceiveProps(nextProps) {
if (this.props.type !== nextProps.type || this.props.value !== nextProps.value) {
this.resolveRefType(nextProps.value, nextProps.type)
}
}
render() {
const {refType} = this.state
if (!refType) {
return null
}
const Preview = previewResolver(refType)
return (
<Preview {...this.props} type={refType} />
)
}
}
| import React, {PropTypes} from 'react'
import resolveRefType from './resolveRefType'
import {resolver as previewResolver} from 'part:@sanity/base/preview'
export default class SanityPreview extends React.PureComponent {
static propTypes = {
value: PropTypes.object,
type: PropTypes.object.isRequired
};
state = {
loading: true,
materialized: null,
refType: null
}
componentDidMount() {
const {type, value} = this.props
this.subscribeRefType(value, type)
}
componentWillUnmount() {
this.unsubscribe()
}
subscribeRefType(value, type) {
this.unsubscribe()
this.subscription = resolveRefType(value, type)
.subscribe(refType => {
this.setState({refType})
})
}
unsubscribe() {
if (this.subscription) {
this.subscription.unsubscribe()
this.subscription = null
}
}
componentWillReceiveProps(nextProps) {
if (this.props.type !== nextProps.type || this.props.value !== nextProps.value) {
this.subscribeRefType(nextProps.value, nextProps.type)
}
}
render() {
const {refType} = this.state
if (!refType) {
return null
}
const Preview = previewResolver(refType)
return (
<Preview {...this.props} type={refType} />
)
}
}
| Fix wrong resolving of referenced type | [previews] Fix wrong resolving of referenced type
| JavaScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity |
abfd3076f555807bd43fc2733573056afda9d089 | settings/index.js | settings/index.js | import _ from 'lodash';
import React from 'react';
import Settings from '@folio/stripes-components/lib/Settings';
import PermissionSets from './permissions/PermissionSets';
import PatronGroupsSettings from './PatronGroupsSettings';
import AddressTypesSettings from './AddressTypesSettings';
const pages = [
{
route: 'perms',
label: 'Permission sets',
component: PermissionSets,
perm: 'ui-users.editpermsets',
},
{
route: 'groups',
label: 'Patron groups',
component: PatronGroupsSettings,
// No perm needed yet
},
{
route: 'addresstypes',
label: 'Address Types',
component: AddressTypesSettings,
// No perm needed yet
},
];
export default props => <Settings {...props} pages={_.sortBy(pages, ['label'])} paneTitle="Users" />;
| import _ from 'lodash';
import React from 'react';
import Settings from '@folio/stripes-components/lib/Settings';
import PermissionSets from './permissions/PermissionSets';
import PatronGroupsSettings from './PatronGroupsSettings';
import AddressTypesSettings from './AddressTypesSettings';
const pages = [
{
route: 'perms',
label: 'Permission sets',
component: PermissionSets,
perm: 'ui-users.editpermsets',
},
{
route: 'groups',
label: 'Patron groups',
component: PatronGroupsSettings,
// perm: 'settings.usergroups.all',
},
{
route: 'addresstypes',
label: 'Address Types',
component: AddressTypesSettings,
// perm: 'settings.addresstypes.all',
},
];
export default props => <Settings {...props} pages={_.sortBy(pages, ['label'])} paneTitle="Users" />;
| Add commented-out permission guards. Part of UIU-197. | Add commented-out permission guards. Part of UIU-197.
| JavaScript | apache-2.0 | folio-org/ui-users,folio-org/ui-users |
6c3cd606ff1dd948a8a1b51eb5525da4881945d1 | www/Gruntfile.js | www/Gruntfile.js | module.exports = function (grunt) {
var allJSFilesInJSFolder = "js/**/*.js";
var distFolder = '../wikipedia/assets/';
grunt.loadNpmTasks( 'grunt-browserify' );
grunt.loadNpmTasks( 'gruntify-eslint' );
grunt.loadNpmTasks( 'grunt-contrib-copy' );
grunt.loadNpmTasks( 'grunt-contrib-less' );
grunt.initConfig( {
browserify: {
distMain: {
src: ["index-main.js", allJSFilesInJSFolder, "!preview-main.js"],
dest: distFolder + "index.js"
},
distPreview: {
src: ["preview-main.js", "js/utilities.js"],
dest: distFolder + "preview.js"
}
},
less: {
all: {
options: {
compress: true,
yuicompress: true,
optimization: 2
},
files: [
{ src: ["less/**/*.less", "node_modules/wikimedia-page-library/build/wikimedia-page-library-transform.css"], dest: distFolder + "styleoverrides.css"}
]
}
},
eslint: {
src: [allJSFilesInJSFolder]
},
copy: {
main: {
files: [{
src: ["*.html",
"*.css",
"ios.json",
"languages.json",
"mainpages.json",
"*.png"],
dest: distFolder
}]
}
}
} );
grunt.registerTask('default', ['eslint', 'browserify', 'less', 'copy']);
};
| module.exports = function (grunt) {
var allJSFilesInJSFolder = "js/**/*.js";
var distFolder = '../wikipedia/assets/';
grunt.loadNpmTasks( 'grunt-browserify' );
grunt.loadNpmTasks( 'gruntify-eslint' );
grunt.loadNpmTasks( 'grunt-contrib-copy' );
grunt.loadNpmTasks( 'grunt-contrib-less' );
grunt.initConfig( {
browserify: {
distMain: {
src: ["index-main.js", allJSFilesInJSFolder, "!preview-main.js"],
dest: distFolder + "index.js"
},
distPreview: {
src: ["preview-main.js", "js/utilities.js"],
dest: distFolder + "preview.js"
}
},
less: {
all: {
options: {
compress: true,
yuicompress: true,
optimization: 2
},
files: [
{ src: ["less/**/*.less", "node_modules/wikimedia-page-library/build/wikimedia-page-library-transform.css"], dest: distFolder + "styleoverrides.css"}
]
}
},
eslint: {
src: [allJSFilesInJSFolder],
options: {
fix: false
}
},
copy: {
main: {
files: [{
src: ["*.html",
"*.css",
"ios.json",
"languages.json",
"mainpages.json",
"*.png"],
dest: distFolder
}]
}
}
} );
grunt.registerTask('default', ['eslint', 'browserify', 'less', 'copy']);
};
| Add eslint 'fix' flag to config. | Add eslint 'fix' flag to config.
Can be flipped to 'true' to auto-fix linting violations!
| JavaScript | mit | wikimedia/apps-ios-wikipedia,josve05a/wikipedia-ios,julienbodet/wikipedia-ios,montehurd/apps-ios-wikipedia,josve05a/wikipedia-ios,wikimedia/wikipedia-ios,julienbodet/wikipedia-ios,josve05a/wikipedia-ios,wikimedia/apps-ios-wikipedia,josve05a/wikipedia-ios,wikimedia/apps-ios-wikipedia,julienbodet/wikipedia-ios,josve05a/wikipedia-ios,josve05a/wikipedia-ios,wikimedia/wikipedia-ios,montehurd/apps-ios-wikipedia,wikimedia/wikipedia-ios,montehurd/apps-ios-wikipedia,wikimedia/wikipedia-ios,julienbodet/wikipedia-ios,julienbodet/wikipedia-ios,julienbodet/wikipedia-ios,wikimedia/apps-ios-wikipedia,montehurd/apps-ios-wikipedia,josve05a/wikipedia-ios,montehurd/apps-ios-wikipedia,wikimedia/wikipedia-ios,wikimedia/wikipedia-ios,montehurd/apps-ios-wikipedia,wikimedia/apps-ios-wikipedia,julienbodet/wikipedia-ios,montehurd/apps-ios-wikipedia,wikimedia/wikipedia-ios,josve05a/wikipedia-ios,wikimedia/apps-ios-wikipedia,wikimedia/apps-ios-wikipedia,wikimedia/apps-ios-wikipedia,julienbodet/wikipedia-ios,montehurd/apps-ios-wikipedia |
5eb4b643651673dac89f53b5cc016b47ff852157 | src/generator-bin.js | src/generator-bin.js | #!/usr/bin/env node
const generate = require('./generator')
const program = require('commander')
program
.version('1.0.0')
.option('-w, --words [num]', 'number of words [2]', 2)
.option('-n, --numbers', 'use numbers')
.option('-a, --alliterative', 'use alliterative')
.option('-o --output [output]', 'output type', /^(raw|dashed|spaced)$/i)
.parse(process.argv)
let project_name = generate({words: program.words, number: program.numbers, alliterative: program.alliterative});
if (program.output == "dashed"){
console.log(project_name.dashed);
} else if (program.output == "raw") {
console.log(project_name.raw);
} else if (program.output == "spaced") {
console.log(project_name.spaced);
} else {
console.log(project_name);
} | #!/usr/bin/env node
const generate = require('./generator')
const program = require('commander')
program
.version('1.0.0')
.option('-w, --words [num]', 'number of words [2]', 2)
.option('-n, --numbers', 'use numbers')
.option('-a, --alliterative', 'use alliterative')
.option('-o, --output [output]', 'output type [raw|dashed|spaced]', /^(raw|dashed|spaced)$/i)
.parse(process.argv)
let project_name = generate({words: program.words, number: program.numbers, alliterative: program.alliterative});
if (program.output == "dashed"){
console.log(project_name.dashed);
} else if (program.output == "raw") {
console.log(project_name.raw);
} else if (program.output == "spaced") {
console.log(project_name.spaced);
} else {
console.log(project_name);
} | Update README for CLI options. | Update README for CLI options.
| JavaScript | isc | aceakash/project-name-generator |
9e77430c1f309444c1990877d237cdf991d36d72 | src/dform.js | src/dform.js | function dform(formElement) {
var eventEmitter = {
on: function (name, handler) {
this[name] = this[name] || [];
this[name].push(handler);
return this;
},
trigger: function (name, event) {
if (this[name]) {
this[name].map(function (handler) {
handler(event);
});
}
return this;
}
};
var submitElement = formElement.find('[type=submit]');
var inputElements = formElement.find('input, select');
formElement.submit(function (event) {
event.preventDefault();
var formData = {};
$.each(inputElements, function (_, element) {
element = $(element);
var name = element.attr('name');
if (name) {
formData[name] = element.val();
}
});
submitElement.attr('disabled', 'disabled');
eventEmitter.trigger('submit');
$[formElement.attr('method')](formElement.attr('action'), formData)
.always(function () {
submitElement.removeAttr('disabled', 'disabled');
})
.done(function (data) {
eventEmitter.trigger('done', data);
})
.fail(function (jqXHR) {
eventEmitter.trigger('fail', jqXHR);
});
});
submitElement.removeAttr('disabled', 'disabled');
return eventEmitter;
}
| function dform(formElement) {
var eventEmitter = {
on: function (name, handler) {
this[name] = this[name] || [];
this[name].push(handler);
return this;
},
trigger: function (name, event) {
if (this[name]) {
this[name].map(function (handler) {
handler(event);
});
}
return this;
}
};
var submitElement = formElement.find('[type=submit]');
var inputElements = formElement.find('input, select');
formElement.submit(function (event) {
event.preventDefault();
submitElement.attr('disabled', 'disabled');
var formData = {};
$.each(inputElements, function (_, element) {
element = $(element);
var name = element.attr('name');
if (name) {
formData[name] = element.val();
}
});
eventEmitter.trigger('submit');
$[formElement.attr('method')](formElement.attr('action'), formData)
.always(function () {
submitElement.removeAttr('disabled', 'disabled');
})
.done(function (responseData) {
eventEmitter.trigger('done', responseData);
})
.fail(function (jqXHR) {
eventEmitter.trigger('fail', jqXHR);
});
});
submitElement.removeAttr('disabled', 'disabled');
return eventEmitter;
}
| Disable button should be the first thing to do | Disable button should be the first thing to do
| JavaScript | mit | dnode/dform,dnode/dform |
fc617bc90f25c5e7102c0e76c71d4790599ff23b | data-demo/person_udf.js | data-demo/person_udf.js | function transform(line) {
var values = line.split(',');
var obj = new Object();
obj.name = values[0];
obj.surname = values[1];
obj.timestamp = values[2];
var jsonString = JSON.stringify(obj);
return jsonString;
}
| /*
Copyright 2022 Google LLC.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
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 transform(line) {
var values = line.split(',');
var obj = new Object();
obj.name = values[0];
obj.surname = values[1];
obj.timestamp = values[2];
var jsonString = JSON.stringify(obj);
return jsonString;
}
| Add a license header on code files | Add a license header on code files
Signed-off-by: Laurent Grangeau <919068a1571bc1b5deaaf9ac4d631597f8dd629f@gmail.com>
| JavaScript | apache-2.0 | GoogleCloudPlatform/deploystack-gcs-to-bq-with-least-privileges |
f7d9d0a57f691a4d9104ab00c75e1cca8cb2142f | src/history.js | src/history.js | const timetrack = require('./timetrack');
const calculateDuration = require('./calculateDuration');
module.exports = (pluginContext) => {
return (project, env = {}) => {
return new Promise((resolve, reject) => {
timetrack.loadData();
resolve(timetrack.getHistory().map(entry => {
// get the duration of the entry
let duration = 'Running';
if ('stop' in entry) {
duration = calculateDuration(entry.start, entry.stop);
}
// get the project name
const project = entry.project || 'No project';
return {
icon: 'fa-clock-o',
title: `[${duration}] ${project}`,
subtitle: `Nice work bro!`
}
}));
});
}
}
| const timetrack = require('./timetrack');
const Sugar = require('sugar-date');
const calculateDuration = require('./calculateDuration');
module.exports = (pluginContext) => {
return (project, env = {}) => {
return new Promise((resolve, reject) => {
timetrack.loadData();
resolve(timetrack.getHistory().map(entry => {
try {
// get the duration of the entry
let duration = 'Running';
if ('stop' in entry) {
// sugarjs sets it auto on 1 hour, so i'll just subtract 3600000 for now, fix this later
duration = Sugar.Date.format(Sugar.Date.create(entry.stop - entry.start - 3600000), '%H:%M:%S');
}
// get the project name
const project = entry.project || 'No project';
// get the start date
const startDate = Sugar.Date.format(Sugar.Date.create(entry.start), '%c')
return {
icon: 'fa-clock-o',
title: `[${duration}] ${project}`,
subtitle: `started on ${startDate}`
}
} catch (e) {
alert('fount: ' + e);
}
}));
});
}
}
| Use sugarjs for date parsing | Use sugarjs for date parsing
| JavaScript | mit | jnstr/zazu-timetracker |
a39453fdbfcc397839583d1b695e0476962f9879 | src/index.js | src/index.js | 'use strict';
import bunyan from 'bunyan';
import http from 'http';
import { createApp } from './app.js';
const logger = bunyan.createLogger({name: "Graphql-Swapi"});
logger.info('Server initialisation...');
createApp()
.then((app) => {
logger.info('Starting HTTP server');
const server = http.createServer(app);
server.listen(8000, ()=> { logger.info('Server is up and running'); });
})
.catch((err) => { logger.error(err); });
| 'use strict';
import bunyan from 'bunyan';
import http from 'http';
import { createApp } from './app.js';
import eventsToAnyPromise from 'events-to-any-promise';
const logger = bunyan.createLogger({name: "Graphql-Swapi"});
function startServer(port, app) {
logger.info('Starting HTTP server');
const server = http.createServer(app);
server.listen(port);
return eventsToAnyPromise(server, 'listening').then(() => {
logger.info('Server is up and running');
return server;
});
}
logger.info('Server initialisation...');
createApp()
.then((app) => startServer(8000, app))
.catch((err) => { logger.error(err); });
| Use my new lib events-to-any-promise | Use my new lib events-to-any-promise
| JavaScript | mit | franckLdx/GraphqlSwapi,franckLdx/GraphqlSwapi |
c6bb66a01539a85c6011eb1c6bd92fb4b7253ca4 | src/index.js | src/index.js | 'use strict';
const childProcess = require('child-process-promise');
const express = require('express');
const path = require('path');
const fs = require('fs');
const configPath = path.resolve(process.cwd(), process.argv.slice().pop());
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
const app = express();
async function build (target, args) {
const commands = args.commands;
const options = {
cwd: args.path,
};
console.log(`Deploying ${ target }...`);
for (let i = 0; i < commands.length; i++) {
const date = (new Date()).toLocaleDateString('sv-SE', {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
});
console.log(`${ date } Running ${ commands[i] }...`);
await childProcess.exec(commands[i], options);
console.log('Done');
}
}
app.post('/', (req, res) => {
const target = req.query.target;
if (config.repos[target]) {
if(req.get('HTTP_X_GITHUB_EVENT') && req.get('HTTP_X_GITHUB_EVENT') === 'push'){
build(target, config.repos[target]);
res.status(200).send();
} else {
res.status(401).send();
}
} else {
res.status(400).send();
}
});
app.listen(config.port, config.host);
| 'use strict';
const childProcess = require('child-process-promise');
const express = require('express');
const path = require('path');
const fs = require('fs');
const configPath = path.resolve(process.cwd(), process.argv.slice().pop());
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
const app = express();
async function build (target, args) {
const commands = args.commands;
const options = {
cwd: args.path,
};
console.log(`Deploying ${ target }...`);
for (let i = 0; i < commands.length; i++) {
const date = (new Date()).toLocaleDateString('sv-SE', {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
});
console.log(`${ date } Running ${ commands[i] }...`);
await childProcess.exec(commands[i], options);
console.log('Done');
}
}
app.post('/', (req, res) => {
const target = req.query.target;
if (config.repos[target]) {
if (req.get('x-github-event') && req.get('x-github-event') === 'push') {
build(target, config.repos[target]);
res.status(200).send();
} else {
res.status(401).send();
}
} else {
res.status(400).send();
}
});
app.listen(config.port, config.host);
| Use correct GitHub header name when checking requests | Use correct GitHub header name when checking requests
| JavaScript | mit | jwilsson/deployy-mcdeployface |
e68b54812c9245304433d5799252da87db7a4074 | src/reducers/intl.js | src/reducers/intl.js | import {addLocaleData} from 'react-intl';
import {updateIntl as superUpdateIntl} from 'react-intl-redux';
import languages from '../languages.json';
import messages from '../../locale/messages.json';
import {IntlProvider, intlReducer} from 'react-intl-redux';
Object.keys(languages).forEach(locale => {
// TODO: will need to handle locales not in the default intl - see www/custom-locales
// eslint-disable-line import/no-unresolved
import(`react-intl/locale-data/${locale}`).then(data => addLocaleData(data));
});
const intlInitialState = {
intl: {
defaultLocale: 'en',
locale: 'en',
messages: messages.en
}
};
const updateIntl = locale => superUpdateIntl({
locale: locale,
messages: messages[locale] || messages.en
});
export {
intlReducer as default,
IntlProvider,
intlInitialState,
updateIntl
};
| import {addLocaleData} from 'react-intl';
import {updateIntl as superUpdateIntl} from 'react-intl-redux';
import languages from '../languages.json';
import messages from '../../locale/messages.json'; // eslint-disable-line import/no-unresolved
import {IntlProvider, intlReducer} from 'react-intl-redux';
Object.keys(languages).forEach(locale => {
// TODO: will need to handle locales not in the default intl - see www/custom-locales
import(`react-intl/locale-data/${locale}`).then(data => addLocaleData(data));
});
const intlInitialState = {
intl: {
defaultLocale: 'en',
locale: 'en',
messages: messages.en
}
};
const updateIntl = locale => superUpdateIntl({
locale: locale,
messages: messages[locale] || messages.en
});
export {
intlReducer as default,
IntlProvider,
intlInitialState,
updateIntl
};
| Fix eslint-disable for unresolved messages line | Fix eslint-disable for unresolved messages line
| JavaScript | bsd-3-clause | LLK/scratch-gui,cwillisf/scratch-gui,cwillisf/scratch-gui,cwillisf/scratch-gui,LLK/scratch-gui |
85b926b56baa0f29b71b5edea3e83479d1252f69 | saleor/static/js/components/categoryPage/ProductItem.js | saleor/static/js/components/categoryPage/ProductItem.js | import React, { Component, PropTypes } from 'react';
import Relay from 'react-relay';
import ProductPrice from './ProductPrice';
class ProductItem extends Component {
static propTypes = {
product: PropTypes.object
};
render() {
const { product } = this.props;
return (
<div className="col-6 col-md-4 product-list" itemScope itemType="https://schema.org/Product">
<a itemProp="url" href={product.url}>
<div className="text-center">
<div>
<img itemProp="image" className="img-responsive" src={product.thumbnailUrl} alt="" />
<span className="product-list-item-name" itemProp="name" title={product.name}>{product.name}</span>
</div>
<div className="panel-footer">
<ProductPrice price={product.price} availability={product.availability} />
</div>
</div>
</a>
</div>
);
}
}
export default Relay.createContainer(ProductItem, {
fragments: {
product: () => Relay.QL`
fragment on ProductType {
id
name
price {
currency
gross
net
}
availability {
${ProductPrice.getFragment('availability')}
}
thumbnailUrl
url
}
`
}
});
| import React, { Component, PropTypes } from 'react';
import Relay from 'react-relay';
import ProductPrice from './ProductPrice';
class ProductItem extends Component {
static propTypes = {
product: PropTypes.object
};
render() {
const { product } = this.props;
return (
<div className="col-6 col-md-4 product-list" itemScope itemType="https://schema.org/Product">
<a itemProp="url" href={product.url}>
<div className="text-center">
<div>
<img itemProp="image" className="img-responsive" src={product.thumbnailUrl} alt="" />
<span className="product-list-item-name" itemProp="name" title={product.name}>{product.name}</span>
</div>
<div className="panel-footer">
<ProductPrice price={product.price} availability={product.availability} />
</div>
</div>
</a>
</div>
);
}
}
export default Relay.createContainer(ProductItem, {
fragments: {
product: () => Relay.QL`
fragment on ProductType {
id
name
price {
currency
gross
grossLocalized
net
}
availability {
${ProductPrice.getFragment('availability')}
}
thumbnailUrl
url
}
`
}
});
| Add missing field to query | Add missing field to query
| JavaScript | bsd-3-clause | jreigel/saleor,UITools/saleor,tfroehlich82/saleor,UITools/saleor,KenMutemi/saleor,UITools/saleor,tfroehlich82/saleor,HyperManTT/ECommerceSaleor,HyperManTT/ECommerceSaleor,jreigel/saleor,mociepka/saleor,KenMutemi/saleor,mociepka/saleor,maferelo/saleor,car3oon/saleor,maferelo/saleor,mociepka/saleor,maferelo/saleor,UITools/saleor,HyperManTT/ECommerceSaleor,itbabu/saleor,UITools/saleor,car3oon/saleor,jreigel/saleor,itbabu/saleor,tfroehlich82/saleor,itbabu/saleor,car3oon/saleor,KenMutemi/saleor |
5927b98e608128152adafed5435fd2ec47a04237 | src/slide.js | src/slide.js | const DEFAULT_IN = 'fadeIn'
const DEFAULT_OUT = 'fadeOut'
class Slide extends BaseElement {
static get observedAttributes () {
return ['active', 'in', 'out']
}
get active () {
return this.hasAttribute('active')
}
set active (value) {
value ? this.setAttribute('active', '')
: this.removeAttribute('active')
}
get in () {
return this.getAttribute('in') || DEFAULT_IN
}
get out () {
return this.getAttribute('out') || DEFAULT_OUT
}
onConnect() {
this.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
`
this.classList.add('animated')
}
renderCallback () {
if (this.active) {
this.classList.add(this.in)
this.classList.remove(this.out)
} else {
this.classList.add(this.out)
this.classList.remove(this.in)
}
}
}
customElements.define('x-slide', Slide)
| const DEFAULT_IN = 'fadeIn'
const DEFAULT_OUT = 'fadeOut'
class Slide extends BaseElement {
static get observedAttributes () {
return ['active', 'in', 'out']
}
get active () {
return this.hasAttribute('active')
}
set active (value) {
value ? this.setAttribute('active', '')
: this.removeAttribute('active')
}
get in () {
return this.getAttribute('in') || DEFAULT_IN
}
get out () {
return this.getAttribute('out') || DEFAULT_OUT
}
onConnect() {
this.classList.add('animated')
Object.assign(this.style, this.inlineCSS())
}
renderCallback () {
if (this.active) {
this.classList.add(this.in)
this.classList.remove(this.out)
} else {
this.classList.add(this.out)
this.classList.remove(this.in)
}
}
inlineCSS() {
return {
position: 'fixed',
top: 0,
left: 0,
display: 'flex',
width: '100%',
height: '100%',
background: 'black',
fontFamily: 'BlinkMacSystemFont, sans-serif',
borderWidth: '30px',
borderStyle: 'solid',
padding: '100px'
}
}
}
customElements.define('x-slide', Slide)
| Simplify inline styles for inheritance | Simplify inline styles for inheritance
| JavaScript | mit | ricardocasares/using-custom-elements,ricardocasares/using-custom-elements |
b47017282e23be837d469378e5d1ac307f8d99c1 | client/app/scripts/directive/projectQuickView.js | client/app/scripts/directive/projectQuickView.js | angular
.module('app')
.directive('projectQuickView', function() {
return {
restrict: 'EA',
replace: false,
templateUrl: 'app/templates/partials/projectQuickView.html',
link: function(scope, element, attrs) {
scope.completed = attrs.completed;
scope.hasDate = function() {
return scope.item.end_date && scope.item.end_date !== null;
};
scope.isContentFromOldSite = function(item) {
return scope.item.end_date == "2012-10-20T04:00:00.000Z";
};
scope.completedStamp = function(item) {
return scope.completed && !scope.isContentFromOldSite(item);
};
}
};
});
| angular
.module('app')
.directive('projectQuickView', function() {
return {
restrict: 'EA',
replace: false,
templateUrl: 'app/templates/partials/projectQuickView.html',
link: function(scope, element, attrs) {
scope.completed = attrs.completed;
scope.hasDate = function() {
return scope.item && scope.item.end_date && scope.item.end_date !== null;
};
scope.isContentFromOldSite = function(item) {
return item && item.end_date == "2012-10-20T04:00:00.000Z";
};
scope.completedStamp = function(item) {
return scope.completed && !scope.isContentFromOldSite(item);
};
}
};
});
| Make a check if end_date exists on the project in the hasDate function | Make a check if end_date exists on the project in the hasDate function
| JavaScript | mit | brettshollenberger/rootstrikers,brettshollenberger/rootstrikers |
d2ba5543a42f23167628cef002e7df9be8a6b2f0 | app/updateChannel.js | app/updateChannel.js | 'use strict'
const TelegramBot = require('node-telegram-bot-api');
const config = require('../config');
const utils = require('./utils');
const Kinospartak = require('./Kinospartak/Kinospartak');
const bot = new TelegramBot(config.TOKEN);
const kinospartak = new Kinospartak();
/**
* updateSchedule - update schedule and push updates to Telegram channel
*
* @return {Promise}
*/
function updateSchedule() {
return kinospartak.getChanges()
.then(changes =>
changes.length
? utils.formatSchedule(changes)
: undefined)
.then(messages =>
messages
? utils.sendInOrder(bot, config.CHANNEL, messages)
: undefined)
.then(() => kinospartak.commitChanges())
};
/**
* updateNews - update news and push updates to Telegram channel
*
* @return {Promise}
*/
function updateNews() {
return kinospartak.getLatestNews()
.then(news =>
news.length
? utils.formatNews(news)
: undefined)
.then(messages =>
messages
? utils.sendInOrder(bot, config.CHANNEL, messages)
: undefined)
.then(() => kinospartak.setNewsOffset(new Date().toString()))
};
function update() {
return Promise.all([
updateSchedule,
updateNews
]).catch((err) => {
setTimeout(() => {
update();
}, 1000 * 60 * 5);
})
}
update(); | 'use strict'
const TelegramBot = require('node-telegram-bot-api');
const config = require('../config');
const utils = require('./utils');
const Kinospartak = require('./Kinospartak/Kinospartak');
const bot = new TelegramBot(config.TOKEN);
const kinospartak = new Kinospartak();
/**
* updateSchedule - update schedule and push updates to Telegram channel
*
* @return {Promise}
*/
function updateSchedule() {
return kinospartak.getChanges()
.then(changes =>
changes.length
? utils.formatSchedule(changes)
: undefined)
.then(messages =>
messages
? utils.sendInOrder(bot, config.CHANNEL, messages)
: undefined)
.then(() => kinospartak.commitChanges())
};
/**
* updateNews - update news and push updates to Telegram channel
*
* @return {Promise}
*/
function updateNews() {
return kinospartak.getLatestNews()
.then(news =>
news.length
? utils.formatNews(news)
: undefined)
.then(messages =>
messages
? utils.sendInOrder(bot, config.CHANNEL, messages)
: undefined)
.then(() => kinospartak.setNewsOffset(new Date().toString()))
};
function update() {
return Promise.all([
updateSchedule(),
updateNews()
]).catch((err) => {
setTimeout(() => {
update();
}, 1000 * 60 * 5);
})
}
update(); | Fix channel updating (Well, that was dumb) | Fix channel updating
(Well, that was dumb)
| JavaScript | mit | TheBeastOfCaerbannog/kinospartak-bot |
d4f4d7bccfa64881162a1e5ee12bb38223eacbdc | api/websocket/omni-websocket.js | api/websocket/omni-websocket.js | var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
http.listen(1089, function(){
console.log('listening on *:1089');
});
| var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
http.listen(1091, function(){
console.log('listening on *:1091');
});
| Change port of websocket to 1091 | Change port of websocket to 1091
| JavaScript | agpl-3.0 | achamely/omniwallet,habibmasuro/omniwallet,Nevtep/omniwallet,VukDukic/omniwallet,OmniLayer/omniwallet,achamely/omniwallet,OmniLayer/omniwallet,habibmasuro/omniwallet,habibmasuro/omniwallet,achamely/omniwallet,achamely/omniwallet,VukDukic/omniwallet,habibmasuro/omniwallet,OmniLayer/omniwallet,Nevtep/omniwallet,VukDukic/omniwallet,OmniLayer/omniwallet,Nevtep/omniwallet,Nevtep/omniwallet |
b0924f63b065016bfe073797c7bba4ed844268ab | packages/ember-model/lib/attr.js | packages/ember-model/lib/attr.js | var get = Ember.get,
set = Ember.set,
meta = Ember.meta;
Ember.attr = function(type) {
return Ember.computed(function(key, value) {
var data = get(this, 'data'),
dataValue = data && get(data, key),
beingCreated = meta(this).proto === this;
if (arguments.length === 2) {
if (beingCreated) {
if (!data) {
data = {};
set(this, 'data', data);
data[key] = value;
}
return value;
}
var isEqual;
if (type && type.isEqual) {
isEqual = type.isEqual(dataValue, value);
} else {
isEqual = dataValue === value;
}
if (!isEqual) {
if (!this._dirtyAttributes) { this._dirtyAttributes = Ember.A(); }
this._dirtyAttributes.push(key);
} else {
if (this._dirtyAttributes) { this._dirtyAttributes.removeObject(key); }
}
return value;
}
if (typeof dataValue === 'object') {
dataValue = Object.create(dataValue);
}
return dataValue;
}).property('data').meta({isAttribute: true, type: type});
}; | var get = Ember.get,
set = Ember.set,
meta = Ember.meta;
Ember.attr = function(type) {
return Ember.computed(function(key, value) {
var data = get(this, 'data'),
dataValue = data && get(data, key),
beingCreated = meta(this).proto === this;
if (arguments.length === 2) {
if (beingCreated) {
if (!data) {
data = {};
set(this, 'data', data);
data[key] = value;
}
return value;
}
var isEqual;
if (type && type.isEqual) {
isEqual = type.isEqual(dataValue, value);
} else {
isEqual = dataValue === value;
}
if (!isEqual) {
if (!this._dirtyAttributes) { this._dirtyAttributes = Ember.A(); }
this._dirtyAttributes.push(key);
} else {
if (this._dirtyAttributes) { this._dirtyAttributes.removeObject(key); }
}
return value;
}
if (typeof dataValue === 'object') {
dataValue = Ember.create(dataValue);
}
return dataValue;
}).property('data').meta({isAttribute: true, type: type});
}; | Use Ember.create vs Object.create for polyfill fix | Use Ember.create vs Object.create for polyfill fix
| JavaScript | mit | julkiewicz/ember-model,ipavelpetrov/ember-model,ckung/ember-model,zenefits/ember-model,c0achmcguirk/ember-model,sohara/ember-model,GavinJoyce/ember-model,Swrve/ember-model,asquet/ember-model,gmedina/ember-model,CondeNast/ember-model,igorgoroshit/ember-model,asquet/ember-model,juggy/ember-model,greyhwndz/ember-model,ebryn/ember-model,ipavelpetrov/ember-model,intercom/ember-model |
ae93a807f90a0b59101443d28a88cf934e536e4e | src/Calibrator.js | src/Calibrator.js | import {VM} from 'vm2'
import SensorData from './SensorData'
export default class Calibrator {
calibrate (data, cb) {
if ( ! (data instanceof SensorData)) return cb('Invalid SensorData given.')
var meta = data.getMetadata()
meta.getAttributes().forEach(function (attr) {
attr.getProperties().forEach(function (prop) {
if (prop.name !== 'calibrate') return
var vm = new VM({
timeout: 1000,
sandbox: {
val: data.getValue(attr.getName())
},
})
var value = vm.run('(' + decodeURI(prop.value) + ')(val)')
data.setValue(attr.getName(), value)
})
})
cb()
}
}
| import {VM} from 'vm2'
import SensorData from './SensorData'
export default class Calibrator {
calibrate (data, cb) {
if ( ! (data instanceof SensorData)) return cb('Invalid SensorData given.')
var meta = data.getMetadata()
meta.getAttributes().forEach(function (attr) {
attr.getProperties().forEach(function (prop) {
if (prop.name !== 'calibrate') return
var vm = new VM({
timeout: 1000,
sandbox: {
Math: Math,
val: data.getValue(attr.getName())
},
})
var value = vm.run('(' + decodeURI(prop.value.toString()) + ')(val)')
data.setValue(attr.getName(), value)
})
})
cb()
}
}
| Add Math to calibrator VM and allow use of functions (not only function strings). | Add Math to calibrator VM and allow use of functions (not only function strings).
| JavaScript | mit | kukua/concava |
769ceb537eec6642fd039ea7ad0fa074029759b1 | share/spice/arxiv/arxiv.js | share/spice/arxiv/arxiv.js | (function (env) {
"use strict";
env.ddg_spice_arxiv = function(api_result){
if (!api_result) {
return Spice.failed('arxiv');
}
Spice.add({
id: "arxiv",
name: "Reference",
data: api_result,
meta: {
sourceName: "arxiv.org",
sourceUrl: api_result.feed.entry.link[0].href
},
normalize: function(item) {
return {
title: item.feed.entry.title.text,
url: item.feed.entry.link[0].href,
subtitle: item.feed.entry.author.map( function(e) {
return e.name.text;
} ).join(', '),
description: item.feed.entry.summary.text
};
},
templates: {
group: 'info',
options: {
moreAt: true
}
}
});
};
}(this));
| (function (env) {
"use strict";
env.ddg_spice_arxiv = function(api_result){
if (!api_result) {
return Spice.failed('arxiv');
}
Spice.add({
id: "arxiv",
name: "Reference",
data: api_result,
meta: {
sourceName: "arxiv.org",
sourceUrl: api_result.feed.entry.link[0].href
},
normalize: function(item) {
return {
title: sprintf( "%s (%s)",
item.feed.entry.title.text,
item.feed.entry.published.text.replace( /^(\d{4}).*/, "$1" )
),
url: item.feed.entry.link[0].href,
subtitle: item.feed.entry.author.map( function(e) {
return e.name.text;
} ).join(', '),
description: item.feed.entry.summary.text
};
},
templates: {
group: 'info',
options: {
moreAt: true
}
}
});
};
}(this));
| Add published year to title | Add published year to title
| JavaScript | apache-2.0 | bigcurl/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,levaly/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,imwally/zeroclickinfo-spice,soleo/zeroclickinfo-spice,P71/zeroclickinfo-spice,soleo/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,lerna/zeroclickinfo-spice,imwally/zeroclickinfo-spice,lernae/zeroclickinfo-spice,deserted/zeroclickinfo-spice,soleo/zeroclickinfo-spice,lerna/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,lernae/zeroclickinfo-spice,soleo/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,lerna/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,soleo/zeroclickinfo-spice,levaly/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,levaly/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,P71/zeroclickinfo-spice,imwally/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,levaly/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,deserted/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,deserted/zeroclickinfo-spice,soleo/zeroclickinfo-spice,P71/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,imwally/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,deserted/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,P71/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,lerna/zeroclickinfo-spice,imwally/zeroclickinfo-spice,lernae/zeroclickinfo-spice,lerna/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,lernae/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,levaly/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,lernae/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,lernae/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,levaly/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,deserted/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,deserted/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice |
2897631e9330289d95ddbab0aa3b13f5d24d1d81 | web/js/calendar-template.js | web/js/calendar-template.js | function cookieValueHandler() {
Cookies.set(this.name, this.value, 365)
window.location.reload()
}
function registerSpecialInputs() {
$$("input").each(function(input) {
if (input.getAttribute("special") == "cookie") {
Event.observe(input, "click", cookieValueHandler)
if (input.type == "radio" && Cookies.get(input.name) == input.value) {
input.checked = true
}
}
});
}
Event.observe(window, 'load', registerSpecialInputs)
| function cookieValueHandler(event) {
var src = Event.element(event)
Cookies.set(src.name, src.value, 365)
window.location.reload()
}
function registerSpecialInputs() {
$$("input").each(function(input) {
if (input.getAttribute("special") == "cookie") {
Event.observe(input, "click", cookieValueHandler)
if (input.type == "radio" && Cookies.get(input.name) == input.value) {
input.checked = true
}
}
});
}
Event.observe(window, 'load', registerSpecialInputs)
| Fix cookieValueHandler to work with IE | Fix cookieValueHandler to work with IE
git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@406 0d517254-b314-0410-acde-c619094fa49f
| JavaScript | bsd-3-clause | NUBIC/psc-mirror,NUBIC/psc-mirror,NUBIC/psc-mirror,NUBIC/psc-mirror |
3ee8995af1835156d7c94a3f6480d48396884f5c | dashboard/src/store/store.js | dashboard/src/store/store.js | import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {},
mutations: {},
actions: {},
modules: {}
});
| import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
strict: process.env.NODE_ENV !== "production", //see https://vuex.vuejs.org/guide/strict.html
state: {},
mutations: {},
actions: {},
modules: {}
});
| Enable VueX strict mode in dev | Enable VueX strict mode in dev
| JavaScript | agpl-3.0 | napstr/wolfia,napstr/wolfia,napstr/wolfia |
39e587b52c92c8b71bb3eed4824c2cfc10b37306 | apps/files_sharing/js/public.js | apps/files_sharing/js/public.js | // Override download path to files_sharing/public.php
function fileDownloadPath(dir, file) {
var url = $('#downloadURL').val();
if (url.indexOf('&path=') != -1) {
url += '/'+file;
}
return url;
}
$(document).ready(function() {
if (typeof FileActions !== 'undefined') {
var mimetype = $('#mimetype').val();
// Show file preview if previewer is available, images are already handled by the template
if (mimetype.substr(0, mimetype.indexOf('/')) != 'image') {
// Trigger default action if not download TODO
var action = FileActions.getDefault(mimetype, 'file', OC.PERMISSION_READ);
if (typeof action === 'undefined') {
$('#noPreview').show();
} else {
action($('#filename').val());
}
}
FileActions.register('dir', 'Open', OC.PERMISSION_READ, '', function(filename) {
var tr = $('tr').filterAttr('data-file', filename)
if (tr.length > 0) {
window.location = $(tr).find('a.name').attr('href');
}
});
}
}); | // Override download path to files_sharing/public.php
function fileDownloadPath(dir, file) {
var url = $('#downloadURL').val();
if (url.indexOf('&path=') != -1) {
url += '/'+file;
}
return url;
}
$(document).ready(function() {
if (typeof FileActions !== 'undefined') {
var mimetype = $('#mimetype').val();
// Show file preview if previewer is available, images are already handled by the template
if (mimetype.substr(0, mimetype.indexOf('/')) != 'image') {
// Trigger default action if not download TODO
var action = FileActions.getDefault(mimetype, 'file', OC.PERMISSION_READ);
if (typeof action === 'undefined') {
$('#noPreview').show();
if (mimetype != 'httpd/unix-directory') {
// NOTE: Remove when a better file previewer solution exists
$('#content').remove();
$('table').remove();
}
} else {
action($('#filename').val());
}
}
FileActions.register('dir', 'Open', OC.PERMISSION_READ, '', function(filename) {
var tr = $('tr').filterAttr('data-file', filename)
if (tr.length > 0) {
window.location = $(tr).find('a.name').attr('href');
}
});
}
}); | Remove the content and table to prevent covering the download link | Remove the content and table to prevent covering the download link
| JavaScript | agpl-3.0 | pollopolea/core,andreas-p/nextcloud-server,phil-davis/core,andreas-p/nextcloud-server,michaelletzgus/nextcloud-server,jbicha/server,owncloud/core,owncloud/core,whitekiba/server,owncloud/core,bluelml/core,nextcloud/server,pmattern/server,IljaN/core,lrytz/core,pmattern/server,sharidas/core,sharidas/core,Ardinis/server,andreas-p/nextcloud-server,pmattern/server,michaelletzgus/nextcloud-server,nextcloud/server,pixelipo/server,michaelletzgus/nextcloud-server,IljaN/core,pollopolea/core,bluelml/core,xx621998xx/server,endsguy/server,IljaN/core,andreas-p/nextcloud-server,jbicha/server,Ardinis/server,xx621998xx/server,pixelipo/server,whitekiba/server,endsguy/server,lrytz/core,xx621998xx/server,bluelml/core,pixelipo/server,bluelml/core,nextcloud/server,owncloud/core,IljaN/core,pmattern/server,pixelipo/server,michaelletzgus/nextcloud-server,jbicha/server,Ardinis/server,jbicha/server,pollopolea/core,pmattern/server,whitekiba/server,whitekiba/server,lrytz/core,owncloud/core,sharidas/core,endsguy/server,cernbox/core,xx621998xx/server,Ardinis/server,sharidas/core,nextcloud/server,endsguy/server,xx621998xx/server,whitekiba/server,IljaN/core,pollopolea/core,andreas-p/nextcloud-server,lrytz/core,sharidas/core,pixelipo/server,jbicha/server,Ardinis/server,bluelml/core,cernbox/core,cernbox/core,cernbox/core,pollopolea/core,lrytz/core,endsguy/server,cernbox/core |
b33316dba3ce7ab8dc2c99d4ba17c700c3f4da74 | js/src/index.js | js/src/index.js | import $ from 'jquery'
import Alert from './alert'
import Button from './button'
import Carousel from './carousel'
import Collapse from './collapse'
import Dropdown from './dropdown'
import Modal from './modal'
import Popover from './popover'
import Scrollspy from './scrollspy'
import Tab from './tab'
import Tooltip from './tooltip'
import Util from './util'
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-alpha.6): index.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
(($) => {
if (typeof $ === 'undefined') {
throw new TypeError('Bootstrap\'s JavaScript requires jQuery. jQuery must be included before Bootstrap\'s JavaScript.')
}
const version = $.fn.jquery.split(' ')[0].split('.')
const minMajor = 1
const ltMajor = 2
const minMinor = 9
const minPatch = 1
const maxMajor = 4
if (version[0] < ltMajor && version[1] < minMinor || version[0] === minMajor && version[1] === minMinor && version[2] < minPatch || version[0] >= maxMajor) {
throw new Error('Bootstrap\'s JavaScript requires at least jQuery v1.9.1 but less than v4.0.0')
}
})($)
export {
Util,
Alert,
Button,
Carousel,
Collapse,
Dropdown,
Modal,
Popover,
Scrollspy,
Tab,
Tooltip
}
| import $ from 'jquery'
import Alert from './alert'
import Button from './button'
import Carousel from './carousel'
import Collapse from './collapse'
import Dropdown from './dropdown'
import Modal from './modal'
import Popover from './popover'
import Scrollspy from './scrollspy'
import Tab from './tab'
import Tooltip from './tooltip'
import Util from './util'
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0): index.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
(($) => {
if (typeof $ === 'undefined') {
throw new TypeError('Bootstrap\'s JavaScript requires jQuery. jQuery must be included before Bootstrap\'s JavaScript.')
}
const version = $.fn.jquery.split(' ')[0].split('.')
const minMajor = 1
const ltMajor = 2
const minMinor = 9
const minPatch = 1
const maxMajor = 4
if (version[0] < ltMajor && version[1] < minMinor || version[0] === minMajor && version[1] === minMinor && version[2] < minPatch || version[0] >= maxMajor) {
throw new Error('Bootstrap\'s JavaScript requires at least jQuery v1.9.1 but less than v4.0.0')
}
})($)
export {
Util,
Alert,
Button,
Carousel,
Collapse,
Dropdown,
Modal,
Popover,
Scrollspy,
Tab,
Tooltip
}
| Fix leftover reference to v4.0.0-alpha.6 | Fix leftover reference to v4.0.0-alpha.6
Running `./build/change-version.js v4.0.0-alpha.6 v4.0.0` fixed this,
so the version change script works fine. I'm presuming instead this
change was just omitted from 35f80bb12e4e, and then wouldn't have
been caught by subsequent runs of `change-version`, since it only
ever replaces the exact old version string specified.
| JavaScript | mit | creativewebjp/bootstrap,seanwu99/bootstrap,coliff/bootstrap,Hemphill/bootstrap-docs,stanwmusic/bootstrap,Lyricalz/bootstrap,GerHobbelt/bootstrap,peterblazejewicz/bootstrap,inway/bootstrap,stanwmusic/bootstrap,inway/bootstrap,tagliala/bootstrap,yuyokk/bootstrap,kvlsrg/bootstrap,creativewebjp/bootstrap,GerHobbelt/bootstrap,m5o/bootstrap,bardiharborow/bootstrap,creativewebjp/bootstrap,nice-fungal/bootstrap,Lyricalz/bootstrap,seanwu99/bootstrap,creativewebjp/bootstrap,bardiharborow/bootstrap,bardiharborow/bootstrap,m5o/bootstrap,Hemphill/bootstrap-docs,seanwu99/bootstrap,bootstrapbrasil/bootstrap,gijsbotje/bootstrap,twbs/bootstrap,zalog/bootstrap,nice-fungal/bootstrap,kvlsrg/bootstrap,bootstrapbrasil/bootstrap,yuyokk/bootstrap,GerHobbelt/bootstrap,bootstrapbrasil/bootstrap,joblocal/bootstrap,stanwmusic/bootstrap,fschumann1211/bootstrap,gijsbotje/bootstrap,Hemphill/bootstrap-docs,nice-fungal/bootstrap,tagliala/bootstrap,peterblazejewicz/bootstrap,Hemphill/bootstrap-docs,bardiharborow/bootstrap,zalog/bootstrap,joblocal/bootstrap,twbs/bootstrap,yuyokk/bootstrap,Lyricalz/bootstrap,fschumann1211/bootstrap,seanwu99/bootstrap,gijsbotje/bootstrap,joblocal/bootstrap,joblocal/bootstrap,tjkohli/bootstrap,fschumann1211/bootstrap,tagliala/bootstrap,coliff/bootstrap,fschumann1211/bootstrap,gijsbotje/bootstrap,inway/bootstrap,peterblazejewicz/bootstrap,Lyricalz/bootstrap,stanwmusic/bootstrap,tjkohli/bootstrap,zalog/bootstrap,yuyokk/bootstrap,kvlsrg/bootstrap |
1bc6d05e92432dbf503483e3f74d8a3fd456b4a6 | gulpfile.js | gulpfile.js | var gulp = require('gulp');
var $ = require('gulp-load-plugins')({ lazy: false });
var source = require('vinyl-source-stream2');
var browserify = require('browserify');
var path = require('path');
var pkg = require('./package.json');
var banner = ['/**',
' * <%= pkg.name %> - <%= pkg.description %>',
' * @version v<%= pkg.version %>',
' * @author <%= pkg.author %>',
' * @link <%= pkg.homepage %>',
' * @license <%= pkg.license %>',
' */',
''].join('\n');
gulp.task('test', function() {
return gulp.src('test/**/*.test.js', { read: false })
.pipe($.mocha({
reporter: 'mocha-better-spec-reporter'
}));
});
gulp.task('script', function () {
var bundleStream = browserify({
entries: './lib/should.js',
builtins: ['util', 'assert']
})
.bundle({
insertGlobals: false,
detectGlobals: false,
standalone: 'Should'
});
return bundleStream
.pipe(source('should.js'))
.pipe($.header(banner, { pkg : pkg } ))
.pipe(gulp.dest('./'))
.pipe($.uglify())
.pipe($.header(banner, { pkg : pkg } ))
.pipe($.rename('should.min.js'))
.pipe(gulp.dest('./'));
}); | var gulp = require('gulp');
var $ = require('gulp-load-plugins')({ lazy: false });
var source = require('vinyl-source-stream2');
var browserify = require('browserify');
var path = require('path');
var pkg = require('./package.json');
var banner = ['/**',
' * <%= pkg.name %> - <%= pkg.description %>',
' * @version v<%= pkg.version %>',
' * @author <%= pkg.author %>',
' * @link <%= pkg.homepage %>',
' * @license <%= pkg.license %>',
' */',
''].join('\n');
gulp.task('test', function() {
return gulp.src('test/**/*.test.js', { read: false })
.pipe($.mocha({
reporter: 'mocha-better-spec-reporter'
}));
});
gulp.task('script', function () {
var bundleStream = browserify({
entries: './lib/should.js',
builtins: ['util', 'assert'],
insertGlobals: false,
detectGlobals: false,
standalone: 'Should'
})
.bundle();
return bundleStream
.pipe(source('should.js'))
.pipe($.header(banner, { pkg : pkg } ))
.pipe(gulp.dest('./'))
.pipe($.uglify())
.pipe($.header(banner, { pkg : pkg } ))
.pipe($.rename('should.min.js'))
.pipe(gulp.dest('./'));
});
| Fix bundle arguments for latest browserify | Fix bundle arguments for latest browserify
| JavaScript | mit | ngot/should.js,Lucifier129/should.js,Qix-/should.js,shouldjs/should.js,shouldjs/should.js,hakatashi/wa.js,enicholson/should.js |
4156b07d63af7e23ac8138bc233747727310d407 | gulpfile.js | gulpfile.js | 'use strict';
var gulp = require('gulp');
var shell = require('gulp-shell')
var sass = require('gulp-sass');
var electron = require('electron-connect').server.create();
gulp.task('serve', function () {
// Compile the sass
gulp.start('sass');
// Start browser process
electron.start();
// Restart browser process
gulp.watch('main.js', electron.restart);
// Reload renderer process
gulp.watch(['index.js', 'index.html', 'index.scss'], function(){
gulp.start('sass');
electron.reload()
});
});
gulp.task('build', shell.task([
'electron-packager . --overwrite --platform=darwin --icon=assets/icons/mac/icon.icns --arch=x64 --prune=true --out=release_builds'
]))
gulp.task('sass', function () {
return gulp.src('./*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./'));
});
| 'use strict';
var gulp = require('gulp');
var shell = require('gulp-shell')
var sass = require('gulp-sass');
var electron = require('electron-connect').server.create();
var package_info = require('./package.json')
gulp.task('serve', function () {
// Compile the sass
gulp.start('sass');
// Start browser process
electron.start();
// Restart browser process
gulp.watch('main.js', electron.restart);
// Reload renderer process
gulp.watch(['index.js', 'index.html', 'index.scss'], function(){
gulp.start('sass');
electron.reload()
});
});
gulp.task('build-all', shell.task([
'electron-packager . --overwrite --platform=all --arch=all --prune=true --out=release_builds'
]));
gulp.task('build-mac', shell.task([
'electron-packager . --overwrite --platform=darwin --icon=assets/icons/mac/icon.icns --arch=x64 --prune=true --out=release_builds'
]));
gulp.task('zip', shell.task([
`zip -FSr release_builds/opsdroid-desktop-darwin-x64/opsdroid-desktop-${package_info.version}-macos-x64.zip release_builds/opsdroid-desktop-darwin-x64/opsdroid-desktop.app`
]));
gulp.task('sass', function () {
return gulp.src('./*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./'));
});
| Make builds platform specific and add zipping | Make builds platform specific and add zipping
| JavaScript | apache-2.0 | opsdroid/opsdroid-desktop,opsdroid/opsdroid-desktop |
f7bd0b4865f0dadc77a33c1168c5239916b05614 | gulpfile.js | gulpfile.js | var gulp = require('gulp'),
coffee = require('gulp-coffee'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
del = require('del');
var paths = {
scripts: ['source/**/*.coffee']
};
gulp.task('clean', function (cb) {
del(['build'], cb);
});
// Compiles coffee to js
gulp.task('scripts', ['clean'], function () {
return gulp.src(paths.scripts)
.pipe(sourcemaps.init())
.pipe(coffee({bare: true}))
//.pipe(uglify())
.pipe(concat('all.min.js'))
.pipe(sourcemaps.write())
.pipe(gulp.dest('build'));
});
gulp.task('watch', function () {
gulp.watch(paths.scripts, ['scripts']);
});
gulp.task('default', ['watch', 'scripts']);
| var gulp = require('gulp'),
coffee = require('gulp-coffee'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
del = require('del'),
karma = require('karma').server;
var paths = {
scripts: ['source/**/*.coffee']
};
gulp.task('clean', function (cb) {
del(['build'], cb);
});
// Compiles coffee to js
gulp.task('scripts', ['clean'], function () {
return gulp.src(paths.scripts)
.pipe(sourcemaps.init())
.pipe(coffee({bare: true}))
//.pipe(uglify())
.pipe(concat('all.min.js'))
.pipe(sourcemaps.write())
.pipe(gulp.dest('build'));
});
gulp.task('watch', function () {
gulp.watch(paths.scripts, ['scripts']);
});
// Run test once and exit
gulp.task('test', function (done) {
karma.start({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done);
});
// Watch for file changes and re-run tests on each change
gulp.task('tdd', function (done) {
karma.start({
configFile: __dirname + '/karma.conf.js'
}, done);
});
gulp.task('default', ['tdd']);
| Add tasks test and tdd | Add tasks test and tdd
| JavaScript | mit | mkawalec/latte-art |
b7d67f8a8581df15bf526f0e493b9ab626cab924 | Resources/public/js/select24entity.js | Resources/public/js/select24entity.js | $(document).ready(function () {
$.fn.select24entity = function (action) {
// Create the parameters array with basic values
var select24entityParam = {
ajax: {
data: function (params) {
return {
q: params.term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true,
tags: false
}
};
// Extend the parameters array with the one in arguments
$.extend(select24entityParam, action);
// Activate the select2 field
this.select2(select24entityParam);
// If we have tag support activated, add a listener to add "new_" in front of new entries.
if (select24entityParam.tags === true) {
this.on('select2:selecting', function (e) {
if (e.params.args.data.id === e.params.args.data.text) {
e.params.args.data.id = 'new_' + e.params.args.data.id;
}
});
}
// Return current field
return this;
};
}); | $(document).ready(function () {
$.fn.select24entity = function (action) {
// Create the parameters array with basic values
var select24entityParam = {
ajax: {
data: function (params) {
return {
q: params.term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
tags: false
};
// Extend the parameters array with the one in arguments
$.extend(select24entityParam, action);
// Activate the select2 field
this.select2(select24entityParam);
// If we have tag support activated, add a listener to add "new_" in front of new entries.
if (select24entityParam.tags === true) {
this.on('select2:selecting', function (e) {
if (e.params.args.data.id === e.params.args.data.text) {
e.params.args.data.id = 'new_' + e.params.args.data.id;
}
});
}
// Return current field
return this;
};
});
| Fix place of "tags" option in the default options | Fix place of "tags" option in the default options | JavaScript | mit | sharky98/select24entity-bundle,sharky98/select24entity-bundle,sharky98/select24entity-bundle |
b46ae05b9622867dfdbfe30402f2848b2770fee8 | test/DOM/main.js | test/DOM/main.js | // This is a simple test that is meant to demonstrate the ability
// interact with the 'document' instance from the global scope.
//
// Thus, the line: `exports.document = document;`
// or something similar should be done in your main module.
module.load('./DOM', function(DOM) {
// A wrapper for 'document.createElement()'
var foo = new (DOM.Element)('h1');
// Sets the 'innerHTML'
foo.update('It Works! <a href="..">Go Back</a>');
// Appends to the <body> tag
DOM.insert(foo);
});
| // This is a simple test that is meant to demonstrate the ability
// interact with the 'document' instance from the global scope.
//
// Thus, the line: `exports.document = document;`
// or something similar should be done in your main module.
module.load('./DOM', function(DOM) {
// A wrapper for 'document.createElement()'
var foo = new (DOM.Element)('h1');
// Sets the 'innerHTML'
foo.update('It Works! <a href="../index.html">Go Back</a>');
// Appends to the <body> tag
DOM.insert(foo);
});
| Make the link work from a "file://" URI. | Make the link work from a "file://" URI.
| JavaScript | mit | TooTallNate/ModuleJS |
5f8631362875b2cafe042c7121cc293615cfffe0 | test/test-app.js | test/test-app.js | /*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
var os = require('os');
describe('hubot:app', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../app'))
.inDir(path.join(os.tmpdir(), './temp-test'))
.withOptions({ 'skip-install': true })
.withPrompt({
someOption: true
})
.on('end', done);
});
it('creates files', function () {
assert.file([
'bower.json',
'package.json',
'.editorconfig',
'.jshintrc'
]);
});
});
| /*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
var os = require('os');
describe('hubot:app', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../app'))
.inDir(path.join(os.tmpdir(), './temp-test'))
.withOptions({ 'skip-install': true })
.withPrompt({
someOption: true
})
.on('end', done);
});
it('creates files', function () {
assert.file([
'bin/hubot',
'bin/hubot.cmd',
'Procfile',
'README.md',
'external-scripts.json',
'hubot-scripts.json',
'.gitignore',
'package.json',
'scripts/example.coffee',
'.editorconfig',
]);
});
});
| Fix assertion for not existing files | Fix assertion for not existing files
| JavaScript | mit | ArLEquiN64/generator-hubot-gulp,m-seldin/generator-hubot-enterprise,eedevops/generator-hubot-enterprise,eedevops/generator-hubot-enterprise,ArLEquiN64/generator-hubot-gulp,zarqin/generator-hubot,github/generator-hubot,mal/generator-hubot,zarqin/generator-hubot,mal/generator-hubot,m-seldin/generator-hubot-enterprise,ClaudeBot/generator-hubot,ClaudeBot/generator-hubot,github/generator-hubot |
66b15d29269455a5cf24164bd1982f7f01c323f3 | src/parse/expr.js | src/parse/expr.js | var expr = require('vega-expression'),
args = ['datum', 'event', 'signals'];
module.exports = expr.compiler(args, {
idWhiteList: args,
fieldVar: args[0],
globalVar: args[2],
functions: function(codegen) {
var fn = expr.functions(codegen);
fn.item = function() { return 'event.vg.item'; };
fn.group = 'event.vg.getGroup';
fn.mouseX = 'event.vg.getX';
fn.mouseY = 'event.vg.getY';
fn.mouse = 'event.vg.getXY';
return fn;
}
});
| var expr = require('vega-expression'),
args = ['datum', 'event', 'signals'];
module.exports = expr.compiler(args, {
idWhiteList: args,
fieldVar: args[0],
globalVar: args[2],
functions: function(codegen) {
var fn = expr.functions(codegen);
fn.eventItem = function() { return 'event.vg.item'; };
fn.eventGroup = 'event.vg.getGroup';
fn.eventX = 'event.vg.getX';
fn.eventY = 'event.vg.getY';
return fn;
}
});
| Update to revised event methods. | Update to revised event methods.
| JavaScript | bsd-3-clause | chiu/vega,smclements/vega,seyfert/vega,mathisonian/vega-browserify,carabina/vega,mcanthony/vega,shaunstanislaus/vega,Jerrythafast/vega,Jerrythafast/vega,cesine/vega,shaunstanislaus/vega,lgrammel/vega,Applied-Duality/vega,smclements/vega,smartpcr/vega,smartpcr/vega,mcanthony/vega,mathisonian/vega-browserify,pingjiang/vega,timelyportfolio/vega,jsanch/vega,uwdata/vega,smclements/vega,nyurik/vega,pingjiang/vega,nyurik/vega,gdseller/vega,jsanch/vega,carabina/vega,gdseller/vega,cesine/vega,Jerrythafast/vega,cesine/vega,mcanthony/vega,gdseller/vega,Applied-Duality/vega,seyfert/vega,shaunstanislaus/vega,uwdata/vega,vega/vega,smartpcr/vega,carabina/vega,pingjiang/vega,timelyportfolio/vega,linearregression/vega,nyurik/vega,mathisonian/vega-browserify,jsanch/vega,vega/vega,linearregression/vega,linearregression/vega,chiu/vega,seyfert/vega,Applied-Duality/vega,vega/vega,vega/vega,chiu/vega |
02475ac2b8ca9832733bbf01fbf49c80c8f5c66a | src/lang-proto.js | src/lang-proto.js | // Copyright (C) 2006 Google Inc.
//
// 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.
/**
* @fileoverview
* Registers a language handler for Protocol Buffers as described at
* http://code.google.com/p/protobuf/.
*
* Based on the lexical grammar at
* http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc202383715
*
* @author mikesamuel@gmail.com
*/
PR['registerLangHandler'](PR['sourceDecorator']({
keywords: (
'bool bytes default double enum extend extensions false fixed32 '
+ 'fixed64 float group import int32 int64 max message option '
+ 'optional package repeated required returns rpc service '
+ 'sfixed32 sfixed64 sint32 sint64 string syntax to true uint32 '
+ 'uint64'),
cStyleComments: true
}), ['proto']);
| // Copyright (C) 2006 Google Inc.
//
// 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.
/**
* @fileoverview
* Registers a language handler for Protocol Buffers as described at
* http://code.google.com/p/protobuf/.
*
* Based on the lexical grammar at
* http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc202383715
*
* @author mikesamuel@gmail.com
*/
PR['registerLangHandler'](PR['sourceDecorator']({
'keywords': (
'bytes,default,double,enum,extend,extensions,false,'
+ 'group,import,max,message,option,'
+ 'optional,package,repeated,required,returns,rpc,service,'
+ 'syntax,to,true'),
'types': /^(bool|(double|s?fixed|[su]?int)(32|64)|float|string)\b/,
'cStyleComments': true
}), ['proto']);
| Fix proto lang handler to work minified and to use the type style for types like uint32. | Fix proto lang handler to work minified and to use the type style for types like uint32.
| JavaScript | apache-2.0 | ebidel/google-code-prettify,tcollard/google-code-prettify,tcollard/google-code-prettify,ebidel/google-code-prettify,tcollard/google-code-prettify |
e89d777b928d212b95ce639256de4e38c1788a77 | src/routes/api.js | src/routes/api.js | // Api Routes --
// RESTful API cheat sheet : http://ricostacruz.com/cheatsheets/rest-api.html
var express = require('express'),
router = express.Router(),
db = require('../modules/database');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.json({
message: 'Hello world!'
});
});
router.get('/users', function(req, res, next) {
db.select('first_name', 'last_name', 'username').from('User').where({active: true}).all()
.then(function (users) {
res.json({
users
});
});
});
module.exports = router;
| // Api Routes --
// RESTful API cheat sheet : http://ricostacruz.com/cheatsheets/rest-api.html
var express = require('express'),
router = express.Router(),
db = require('../modules/database');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.json({
message: 'Hello world!'
});
});
router.get('/users', function(req, res, next) {
db.select('first_name', 'last_name', 'username').from('User').where({active: true}).all()
.then(function (users) {
res.json({
users
});
});
});
router.get('/users/:username', function (req, res) {
db.select().from('User').where({active: true, 'username': req.param('username')}).all()
.then(function (user) {
res.json({
user
});
});
});
module.exports = router;
| Add get one user in API | Add get one user in API
| JavaScript | mit | AnimalTracker/AnimalTracker,AnimalTracker/AnimalTracker |
53a27ad98440fb40c5d13f0415ee0ac348289ca1 | app/extension-scripts/main.js | app/extension-scripts/main.js | (function() {
chrome.browserAction.onClicked.addListener(function() {
var newURL = "chrome-extension://" + chrome.runtime.id + "/index.html";
chrome.tabs.create({ url: newURL });
});
})();
| (function() {
chrome.browserAction.onClicked.addListener(function() {
var appUrl = chrome.extension.getURL('index.html');
chrome.tabs.create({ url: appUrl });
});
})();
| Use builtin to build url | Use builtin to build url
| JavaScript | mit | chrisfried/DIM,bhollis/DIM,DestinyItemManager/DIM,48klocs/DIM,bhollis/DIM,delphiactual/DIM,chrisfried/DIM,bhollis/DIM,DestinyItemManager/DIM,LouisFettet/DIM,48klocs/DIM,delphiactual/DIM,bhollis/DIM,LouisFettet/DIM,DestinyItemManager/DIM,chrisfried/DIM,48klocs/DIM,delphiactual/DIM,chrisfried/DIM,delphiactual/DIM,DestinyItemManager/DIM |
5f336dc64d8d7137e22e30e8799be6215fd9d45e | packages/custom-elements/tests/safari-gc-bug-workaround.js | packages/custom-elements/tests/safari-gc-bug-workaround.js | export function safariGCBugWorkaround() {
if (customElements.polyfillWrapFlushCallback === undefined) {
console.warn('The custom elements polyfill was reinstalled.');
window.__CE_installPolyfill();
}
}
| /**
* @license
* Copyright (c) 2019 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
// Some distributions of Safari 10 and 11 contain a bug where non-native
// properties added to certain globals very early in the lifetime of the page
// are not considered reachable and might be garbage collected. This happens
// randomly and appears to affect not only the `customElements` global but also
// the wrapper functions it attaches to other globals, like `Node.prototype`,
// effectively removing the polyfill. To work around this, this function checks
// if the polyfill is missing before running the tests. If so, it uses a
// special global function added by the polyfill during tests (which doesn't
// get collected) to reinstall it.
//
// https://bugs.webkit.org/show_bug.cgi?id=172575
export function safariGCBugWorkaround() {
if (customElements.polyfillWrapFlushCallback === undefined) {
window.__CE_installPolyfill();
console.warn('The custom elements polyfill was reinstalled.');
}
}
| Add license and comment describing the Safari GC bug workaround. | Add license and comment describing the Safari GC bug workaround.
| JavaScript | bsd-3-clause | webcomponents/polyfills,webcomponents/polyfills,webcomponents/polyfills |
b7f05eeb90ceeb53ce14d2a23ee73300cce61f92 | lib/querystring.js | lib/querystring.js | // based on the qs module, but handles null objects as expected
// fixes by Tomas Pollak.
function stringify(obj, prefix) {
if (prefix && (obj === null || typeof obj == 'undefined')) {
return prefix + '=';
} else if (obj.constructor == Array) {
return stringifyArray(obj, prefix);
} else if (obj !== null && typeof obj == 'object') {
return stringifyObject(obj, prefix);
} else if (prefix) { // string inside array or hash
return prefix + '=' + encodeURIComponent(String(obj));
} else if (String(obj).indexOf('=') !== -1) { // string with equal sign
return String(obj);
} else {
throw new TypeError('Cannot build a querystring out of: ' + obj);
}
};
function stringifyArray(arr, prefix) {
var ret = [];
for (var i = 0, len = arr.length; i < len; i++) {
if (prefix)
ret.push(stringify(arr[i], prefix + '[' + i + ']'));
else
ret.push(stringify(arr[i]));
}
return ret.join('&');
}
function stringifyObject(obj, prefix) {
var ret = [];
Object.keys(obj).forEach(function(key) {
ret.push(stringify(obj[key], prefix
? prefix + '[' + encodeURIComponent(key) + ']'
: encodeURIComponent(key)));
})
return ret.join('&');
}
exports.build = stringify;
| // based on the qs module, but handles null objects as expected
// fixes by Tomas Pollak.
var toString = Object.prototype.toString;
function stringify(obj, prefix) {
if (prefix && (obj === null || typeof obj == 'undefined')) {
return prefix + '=';
} else if (toString.call(obj) == '[object Array]') {
return stringifyArray(obj, prefix);
} else if (toString.call(obj) == '[object Object]') {
return stringifyObject(obj, prefix);
} else if (toString.call(obj) == '[object Date]') {
return obj.toISOString();
} else if (prefix) { // string inside array or hash
return prefix + '=' + encodeURIComponent(String(obj));
} else if (String(obj).indexOf('=') !== -1) { // string with equal sign
return String(obj);
} else {
throw new TypeError('Cannot build a querystring out of: ' + obj);
}
};
function stringifyArray(arr, prefix) {
var ret = [];
for (var i = 0, len = arr.length; i < len; i++) {
if (prefix)
ret.push(stringify(arr[i], prefix + '[' + i + ']'));
else
ret.push(stringify(arr[i]));
}
return ret.join('&');
}
function stringifyObject(obj, prefix) {
var ret = [];
Object.keys(obj).forEach(function(key) {
ret.push(stringify(obj[key], prefix
? prefix + '[' + encodeURIComponent(key) + ']'
: encodeURIComponent(key)));
})
return ret.join('&');
}
exports.build = stringify;
| Add support for Dates to stringify, also improve stringify Object and Array | Add support for Dates to stringify, also improve stringify Object and Array
| JavaScript | mit | tomas/needle,tomas/needle |
7b6f45b5970766e1ce85c51c0e3d471b41f6a7d6 | app/helpers/takeScreenshot.js | app/helpers/takeScreenshot.js | import { remote } from 'electron'
export default async function takeScreenshot (html, deviceWidth) {
return new Promise(resolve => {
const win = new remote.BrowserWindow({
width: deviceWidth,
show: false,
})
win.loadURL(`data:text/html, ${html}`)
win.webContents.on('did-finish-load', () => {
// Window is not fully loaded after this event, hence setTimeout()...
win.webContents.executeJavaScript('document.querySelector(\'body\').getBoundingClientRect().height', (height) => {
win.setSize(deviceWidth, height)
setTimeout(() => {
win.webContents.capturePage((img) => { // eslint-disable-line
win.close()
resolve(img.toPng())
})
}, 500)
})
})
})
}
| import { remote } from 'electron'
import path from 'path'
import os from 'os'
import { fsWriteFile } from 'helpers/fs'
const TMP_DIR = os.tmpdir()
export default async function takeScreenshot (html, deviceWidth) {
return new Promise(async resolve => {
const win = new remote.BrowserWindow({
width: deviceWidth,
show: false,
})
const tmpFileName = path.join(TMP_DIR, 'tpm-mjml-preview.html')
await fsWriteFile(tmpFileName, html)
win.loadURL(`file://${tmpFileName}`)
win.webContents.on('did-finish-load', () => {
// Window is not fully loaded after this event, hence setTimeout()...
win.webContents.executeJavaScript('document.querySelector(\'body\').getBoundingClientRect().height', (height) => {
win.setSize(deviceWidth, height)
setTimeout(() => {
win.webContents.capturePage((img) => { // eslint-disable-line
win.close()
resolve(img.toPng())
})
}, 500)
})
})
})
}
| Use file to generate screenshot | Use file to generate screenshot
| JavaScript | mit | mjmlio/mjml-app,mjmlio/mjml-app,mjmlio/mjml-app |
ca3c29206187ec6a892e36c649602f39648b445c | src/decode/objectify.js | src/decode/objectify.js | var Struct = require('../base/Struct');
var Data = require('../base/Data');
var Text = require('../base/Text');
var List = require('../base/List');
var AnyPointer = require('../base/AnyPointer');
/*
* Primary use case is testing. AnyPointers map to `'[AnyPointer]'` not a nice
* dump for general use, but good for testing. Circular reference will bring
* this crashing down too.
*/
var objectify = function (reader) {
var object = {};
for (var key in reader) {
var v = reader[key];
if (v instanceof Struct) {
object[key] = objectify(v);
} else if (v instanceof List) {
if (v instanceof Data) {
object[key] = v.raw;
} else if (v instanceof Text) {
object[key] = v.string;
} else {
/* TODO: map for list types. */
object[key] = v.map(objectify);
}
} else if (v instanceof AnyPointer) {
object[key] = '[AnyPointer]';
} else {
object[key] = v;
}
}
return object;
};
module.exports = objectify;
| var Struct = require('../base/Struct');
var Data = require('./list/Data');
var Text = require('./list/Text');
var List = require('../base/List');
var AnyPointer = require('../base/AnyPointer');
/*
* Primary use case is testing. AnyPointers map to `'[AnyPointer]'` not a nice
* dump for general use, but good for testing. Circular reference will bring
* this crashing down too.
*/
var objectify = function (reader) {
var object = {};
for (var key in reader) {
if (key[0] !== '$') continue;
var v = reader[key];
if (v instanceof Struct) {
object[key] = objectify(v);
} else if (v instanceof List) {
if (v instanceof Data) {
object[key] = v.raw;
} else if (v instanceof Text) {
object[key] = v.string;
} else {
/* TODO: map for list types. */
object[key] = v.map(objectify);
}
} else if (v instanceof AnyPointer) {
object[key] = '[AnyPointer]';
} else {
object[key] = v;
}
}
return object;
};
module.exports = objectify;
| Determine enumerability by $ prefix | Determine enumerability by $ prefix
| JavaScript | mit | xygroup/node-capnp-plugin |
2106cfa5b5905945ae2899441995c6c6451717ab | src/apps/interactions/macros/kind-form.js | src/apps/interactions/macros/kind-form.js | module.exports = function ({
returnLink,
errors = [],
}) {
return {
buttonText: 'Continue',
errors,
children: [
{
macroName: 'MultipleChoiceField',
type: 'radio',
label: 'What would you like to record?',
name: 'kind',
options: [{
value: 'interaction',
label: 'A standard interaction',
hint: 'For example, an email, phone call or meeting',
}, {
value: 'service_delivery',
label: 'A service that you have provided',
hint: 'For example, account management, a significant assist or an event',
},
/*, {
value: 'policy_feedback',
label: 'Policy feedback',
hint: 'For example, when a company wants to give UK government policy feedback',
} */
],
},
],
}
}
| module.exports = function ({
returnLink,
errors = [],
}) {
return {
buttonText: 'Continue',
errors,
children: [{
macroName: 'MultipleChoiceField',
type: 'radio',
label: 'What would you like to record?',
name: 'kind',
options: [{
value: 'interaction',
label: 'A standard interaction',
hint: 'For example, an email, phone call or meeting',
}, {
value: 'service_delivery',
label: 'A service that you have provided',
hint: 'For example, account management, a significant assist or an event',
},
{
value: 'policy_feedback',
label: 'Capture policy feedback',
hint: 'For example, and issue or comment on government policy from a company',
}],
}],
}
}
| Enable policy feedback in interaction creation selection | Enable policy feedback in interaction creation selection | JavaScript | mit | uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend |
0734e87bfa82d268366a46b29d3f54f14754d09d | js/swipe.js | js/swipe.js | $(document).ready(function(){
$('.swipeGal').each(function(i, obj){
});
});
| flickrParser = function(json){
var imageList = []
$(json.items).each(function(i, image){
imageList.push({
'title':image.title,
'artist':image.author,
'url':image.link,
'image':image.media.m});
})
return imageList;
}
$(document).ready(function(){
$('.swipeGal').each(function(i, obj){
var feedid = $(obj).data('feed-id');
var url = 'http://ycpi.api.flickr.com/services/feeds/groups_pool.gne?id='+feedid+'&jsoncallback=?';
$.getJSON(url, {format: "json"})
.done(function(data){
parsedImages = flickrParser(data);
//console.log(parsedImages);
});
});
});
| Make request to flickr for group images and parse results into a standard json format. | Make request to flickr for group images and parse results into a standard json format.
| JavaScript | mit | neilvallon/Swipe-Gallery,neilvallon/Swipe-Gallery |
0ceb155aad0bad3d343194227b82fa8e074f7b07 | src/js/collections/pool.js | src/js/collections/pool.js | define(['backbone', '../models/dataset/connection'],
function(Backbone, Connection) {
'use strict';
var ConnectionPool = Backbone.Collection.extend({
model: Connection,
initialize: function(models, options) {
this.dataset = options['dataset'];
this.defaultCut = options['defaultCut'];
},
getConnection: function(opts) {
var id = this.getConnectionId(opts),
conn = this.get(id);
if (_.isUndefined(conn)) {
var defaults = {
id: id,
dataset: this.dataset,
cut: this.defaultCut
};
conn = new Connection(_.extend(defaults, opts));
this.add(conn);
}
return conn;
},
getConnectionId: function(opts) {
switch(opts['type']) {
case 'dimensions':
return opts['type'] + ':' + opts['dimension'];
case 'observations':
return opts['type'] + ':' + opts['dimension'] + ':' + opts['measure'];
default:
return _.uniqueId('conn_');
}
}
});
return ConnectionPool;
});
| define(['backbone', '../models/dataset/connection'],
function(Backbone, Connection) {
'use strict';
var ConnectionPool = Backbone.Collection.extend({
model: Connection,
initialize: function(models, options) {
this.dataset = options['dataset'];
this.defaultCut = options['defaultCut'];
},
getConnection: function(opts) {
var id = this.getConnectionId(opts),
conn = this.get(id);
if (_.isUndefined(conn)) {
var defaults = {
id: id,
dataset: this.dataset,
cut: this.defaultCut
};
conn = new Connection(_.extend(defaults, opts));
this.add(conn);
}
return conn;
},
getConnectionId: function(opts) {
switch(opts['type']) {
case 'dimensions':
return opts['type'] + ':' + opts['dimension'];
case 'observations':
return opts['type'] + ':' + opts['dimension'] + ':' + opts['measure'] + ':' + opts['aggregation'];
default:
return _.uniqueId('conn_');
}
}
});
return ConnectionPool;
});
| Use aggregation to namespace the connection id | Use aggregation to namespace the connection id
re #506
| JavaScript | agpl-3.0 | dataseed/dataseed-visualisation.js,dataseed/dataseed-visualisation.js |
1ec78af6c450fabb206e4da6035d1b69696c9e77 | src/js/apis/todo-api.js | src/js/apis/todo-api.js | var $ = require('jquery');
var _ = require('lodash');
var BASE_URL = '/api/todos/';
var TodoApi = {
destroy: function(_id, success, failure) {
$.ajax({
url: BASE_URL + _id,
type: 'DELETE',
dataType: 'json',
success: function() {
success();
},
error: function(xhr, status, error) {
failure(error);
}
});
},
getAll: function(success, failure) {
$.ajax({
url: BASE_URL,
dataType: 'json',
success: function(data) {
success(data);
},
error: function(xhr, status, error) {
failure(error);
}
});
},
get: function(_id, success, failure) {
$.ajax({
url: BASE_URL + _id,
dataType: 'json',
success: function(data) {
success(data);
},
error: function(xhr, status, error) {
failure(error);
}
});
},
update: function(_id, props, success, failure) {
$.ajax({
url: BASE_URL + _id,
type: 'PUT',
dataType: 'json',
data: props,
success: function() {
success();
},
error: function(xhr, status, error) {
failure(error);
}
});
},
};
module.exports = TodoApi; | var $ = require('jquery');
var _ = require('lodash');
var BASE_URL = '/api/todos/';
var TodoApi = {
create: function(todo, success, failure) {
$.ajax({
url: BASE_URL,
type: 'POST',
dataType: 'json',
data: todo,
success: function() {
success();
},
error: function() {
failure();
}
});
},
destroy: function(_id, success, failure) {
$.ajax({
url: BASE_URL + _id,
type: 'DELETE',
dataType: 'json',
success: function() {
success();
},
error: function(xhr, status, error) {
failure(error);
}
});
},
getAll: function(success, failure) {
$.ajax({
url: BASE_URL,
dataType: 'json',
success: function(data) {
success(data);
},
error: function(xhr, status, error) {
failure(error);
}
});
},
get: function(_id, success, failure) {
$.ajax({
url: BASE_URL + _id,
dataType: 'json',
success: function(data) {
success(data);
},
error: function(xhr, status, error) {
failure(error);
}
});
},
update: function(_id, props, success, failure) {
$.ajax({
url: BASE_URL + _id,
type: 'PUT',
dataType: 'json',
data: props,
success: function() {
success();
},
error: function(xhr, status, error) {
failure(error);
}
});
},
};
module.exports = TodoApi; | Add create method to Todo Api | Add create method to Todo Api
| JavaScript | mit | haner199401/React-Node-Project-Seed,mattpetrie/React-Node-Project-Seed,mattpetrie/React-Node-Project-Seed,haner199401/React-Node-Project-Seed |
46ca249428c86877ee515c89ccfc6bdf81a43f79 | vis/Code/Remotery.js | vis/Code/Remotery.js |
//
// TODO: Window resizing needs finer-grain control
// TODO: Take into account where user has moved the windows
// TODO: Controls need automatic resizing within their parent windows
//
Remotery = (function()
{
function Remotery()
{
this.WindowManager = new WM.WindowManager();
this.Server = new WebSocketConnection();
// Create the console up front as everything reports to it
this.Console = new Console(this.WindowManager, this.Server);
// Create required windows
this.TitleWindow = new TitleWindow(this.WindowManager, this.Server);
// Kick-off the auto-connect loop
AutoConnect(this);
// Hook up resize event handler
DOM.Event.AddHandler(window, "resize", Bind(OnResizeWindow, this));
OnResizeWindow(this);
}
function AutoConnect(self)
{
// Only attempt to connect if there isn't already a connection or an attempt to connect
if (!self.Server.Connected())
self.Server.Connect("ws://127.0.0.1:17815/remotery");
// Always schedule another check
window.setTimeout(Bind(AutoConnect, self), 5000);
}
function OnResizeWindow(self)
{
// Resize windows
var w = window.innerWidth;
var h = window.innerHeight;
self.Console.WindowResized(w, h);
self.TitleWindow.WindowResized(w, h);
}
return Remotery;
})(); |
//
// TODO: Window resizing needs finer-grain control
// TODO: Take into account where user has moved the windows
// TODO: Controls need automatic resizing within their parent windows
//
Remotery = (function()
{
function Remotery()
{
this.WindowManager = new WM.WindowManager();
this.Server = new WebSocketConnection();
// Create the console up front as everything reports to it
this.Console = new Console(this.WindowManager, this.Server);
// Create required windows
this.TitleWindow = new TitleWindow(this.WindowManager, this.Server);
// Kick-off the auto-connect loop
AutoConnect(this);
// Hook up resize event handler
DOM.Event.AddHandler(window, "resize", Bind(OnResizeWindow, this));
OnResizeWindow(this);
}
function AutoConnect(self)
{
// Only attempt to connect if there isn't already a connection or an attempt to connect
if (!self.Server.Connected())
self.Server.Connect("ws://127.0.0.1:17815/remotery");
// Always schedule another check
window.setTimeout(Bind(AutoConnect, self), 2000);
}
function OnResizeWindow(self)
{
// Resize windows
var w = window.innerWidth;
var h = window.innerHeight;
self.Console.WindowResized(w, h);
self.TitleWindow.WindowResized(w, h);
}
return Remotery;
})(); | Reduce auto-connect loop to 2 seconds. | Reduce auto-connect loop to 2 seconds.
| JavaScript | apache-2.0 | nil-ableton/Remotery,floooh/Remotery,dougbinks/Remotery,nil-ableton/Remotery,island-org/Remotery,nil-ableton/Remotery,dougbinks/Remotery,Celtoys/Remotery,floooh/Remotery,island-org/Remotery,Celtoys/Remotery,island-org/Remotery,barrettcolin/Remotery,dougbinks/Remotery,island-org/Remotery,barrettcolin/Remotery,dougbinks/Remotery,floooh/Remotery,barrettcolin/Remotery,Celtoys/Remotery,nil-ableton/Remotery,barrettcolin/Remotery,floooh/Remotery |
a0501d86dcee4ef1ddad9e7e65db93b7e0b8b10b | src/events.js | src/events.js | var domElementValue = require('dom-element-value');
var EventManager = require('dom-event-manager');
var eventManager;
function eventHandler(name, e) {
var element = e.delegateTarget, eventName = 'on' + name;
if (!element.domLayerNode || !element.domLayerNode.events || !element.domLayerNode.events[eventName]) {
return;
}
var value;
if (/^(?:input|select|textarea|button)$/i.test(element.tagName)) {
value = domElementValue(element);
}
return element.domLayerNode.events[eventName](e, value, element.domLayerNode);
}
function getManager() {
if (eventManager) {
return eventManager;
}
return eventManager = new EventManager(eventHandler);
}
function init() {
var em = getManager();
em.bindDefaultEvents();
return em;
}
module.exports = {
EventManager: EventManager,
getManager: getManager,
init: init
};
| var domElementValue = require('dom-element-value');
var EventManager = require('dom-event-manager');
var eventManager;
function eventHandler(name, e) {
var element = e.delegateTarget;
if (!element.domLayerNode || !element.domLayerNode.events) {
return;
}
var events = []
var mouseClickEventName;
var bail = false;
if (name.substr(name.length - 5) === 'click') {
mouseClickEventName = 'onmouse' + name;
if (element.domLayerNode.events[mouseClickEventName]) {
events.push(mouseClickEventName);
}
// Do not call the `click` handler if it's not a left click.
if (e.button !== 0) {
bail = true;
}
}
var eventName;
if (!bail) {
eventName = 'on' + name;
if (element.domLayerNode.events[eventName]) {
events.push(eventName);
}
}
if (!events.length) {
return;
}
var value;
if (/^(?:input|select|textarea|button)$/i.test(element.tagName)) {
value = domElementValue(element);
}
for (var i = 0, len = events.length; i < len ; i++) {
element.domLayerNode.events[events[i]](e, value, element.domLayerNode);
}
}
function getManager() {
if (eventManager) {
return eventManager;
}
return eventManager = new EventManager(eventHandler);
}
function init() {
var em = getManager();
em.bindDefaultEvents();
return em;
}
module.exports = {
EventManager: EventManager,
getManager: getManager,
init: init
};
| Change the event handler, the `click` handler is only called on left clicks, use the fake `mouseclick` event to catch any kind of click. | Change the event handler, the `click` handler is only called on left clicks, use the fake `mouseclick` event to catch any kind of click.
| JavaScript | mit | crysalead-js/dom-layer,crysalead-js/dom-layer |
b9e61516e633e79909371d6c185818e3579085d2 | languages.js | languages.js | module.exports = [
{name:'C++', mode:'c_cpp'},
{name:'CSS', mode:'css'},
{name:'HTML', mode:'html'},
{name:'JavaScript', mode:'javascript'},
{name:'Perl', mode:'perl'},
{name:'Python', mode:'python'},
{name:'Ruby', mode:'ruby'},
{name:'Shell', mode:'sh'},
{name:'SQL', mode:'sql'},
{name:'Text', mode:'text'}
];
| module.exports = [
{name:'C++', mode:'c_cpp'},
{name:'CSS', mode:'css'},
{name:'HTML', mode:'html'},
{name:'JavaScript', mode:'javascript'},
{name:'JSON', mode:'json'},
{name:'Perl', mode:'perl'},
{name:'Python', mode:'python'},
{name:'Ruby', mode:'ruby'},
{name:'Shell', mode:'sh'},
{name:'SQL', mode:'sql'},
{name:'Text', mode:'text'},
{name:'XML', mode:'xml'}
];
| Add XML and JSON modes | Add XML and JSON modes
| JavaScript | unlicense | briangreenery/gist |
94a0a48971adbd1583707bd4ed9f874db0b82385 | test/dispose.js | test/dispose.js | describe('asking if a visible div scrolled', function() {
require('./fixtures/bootstrap.js');
beforeEach(h.clean);
afterEach(h.clean);
var visible = false;
var element;
var watcher;
beforeEach(function(done) {
element = h.createTest({
style: {
top: '10000px'
}
});
h.insertTest(element);
watcher = inViewport(element, function() {
scrolled = true;
done();
});
});
describe('when the watcher is not active', function() {
beforeEach(watcher.dispose());
beforeEach(h.scroller(0, 10000));
beforeEach(h.scroller(0, 0));
it('cb not called', function() {
assert.strictEqual(calls.length, 0);
});
});
describe('when the watcher is active', function() {
beforeEach(watcher.watch());
beforeEach(h.scroller(0, 10000));
beforeEach(h.scroller(0, 0));
it('cb called', function() {
assert.strictEqual(calls.length, 1);
});
});
}); | describe('using the watcher API to dispose and watch again', function() {
require('./fixtures/bootstrap.js');
beforeEach(h.clean);
afterEach(h.clean);
var visible = false;
var element;
var watcher;
beforeEach(function(done) {
element = h.createTest({
style: {
top: '10000px'
}
});
h.insertTest(element);
watcher = inViewport(element, function() {
scrolled = true;
done();
});
});
describe('when the watcher is not active', function() {
beforeEach(watcher.dispose());
beforeEach(h.scroller(0, 10000));
beforeEach(h.scroller(0, 0));
it('cb not called', function() {
assert.strictEqual(calls.length, 0);
});
});
describe('when the watcher is active', function() {
beforeEach(watcher.watch());
beforeEach(h.scroller(0, 10000));
beforeEach(h.scroller(0, 0));
it('cb called', function() {
assert.strictEqual(calls.length, 1);
});
});
}); | Rename the test on watcher API to have something more specific | Rename the test on watcher API to have something more specific
| JavaScript | mit | tzi/in-viewport,tzi/in-viewport,vvo/in-viewport,vvo/in-viewport,fasterize/in-viewport,fasterize/in-viewport,ipy/in-viewport,ipy/in-viewport |
5cb52c0c7d5149048fdc0f36c18e033a48f33fad | src/scripts/browser/components/auto-launcher/impl-win32.js | src/scripts/browser/components/auto-launcher/impl-win32.js | import manifest from '../../../../package.json';
import filePaths from '../../utils/file-paths';
import Winreg from 'winreg';
import BaseAutoLauncher from './base';
class Win32AutoLauncher extends BaseAutoLauncher {
static REG_KEY = new Winreg({
hive: Winreg.HKCU,
key: '\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'
});
enable(callback) {
const updateExePath = filePaths.getSquirrelUpdateExe();
const cmd = `"${updateExePath}" --processStart ` +
`"${manifest.productName}.exe" --process-start-args "--os-startup"`;
log('setting registry key for', manifest.productName, 'value', cmd);
Win32AutoLauncher.REG_KEY.set(manifest.productName, Winreg.REG_SZ, cmd, callback);
}
disable(callback) {
log('removing registry key for', manifest.productName);
Win32AutoLauncher.REG_KEY.remove(manifest.productName, callback);
}
isEnabled(callback) {
log('querying registry key for', manifest.productName);
Win32AutoLauncher.REG_KEY.get(manifest.productName, function(err, item) {
const enabled = !!item;
log('registry value for', manifest.productName, 'is', enabled);
callback(err, enabled);
});
}
}
export default Win32AutoLauncher;
| import manifest from '../../../../package.json';
import filePaths from '../../utils/file-paths';
import Winreg from 'winreg';
import BaseAutoLauncher from './base';
class Win32AutoLauncher extends BaseAutoLauncher {
static REG_KEY = new Winreg({
hive: Winreg.HKCU,
key: '\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'
});
enable(callback) {
const updateExePath = filePaths.getSquirrelUpdateExe();
const cmd = `"${updateExePath}" --processStart ` +
`"${manifest.productName}.exe" --process-start-args "--os-startup"`;
log('setting registry key for', manifest.productName, 'value', cmd);
Win32AutoLauncher.REG_KEY.set(manifest.productName, Winreg.REG_SZ, cmd, callback);
}
disable(callback) {
log('removing registry key for', manifest.productName);
Win32AutoLauncher.REG_KEY.remove(manifest.productName, (err) => {
const notFound = err.message == 'The system was unable to find the specified registry key or value.';
if (notFound) {
callback();
} else {
callback(err);
}
});
}
isEnabled(callback) {
log('querying registry key for', manifest.productName);
Win32AutoLauncher.REG_KEY.get(manifest.productName, function(err, item) {
const enabled = !!item;
log('registry value for', manifest.productName, 'is', enabled);
callback(err, enabled);
});
}
}
export default Win32AutoLauncher;
| Handle not found error in win32 auto launcher | Handle not found error in win32 auto launcher
| JavaScript | mit | Hadisaeed/test-build,Aluxian/Messenger-for-Desktop,Aluxian/Facebook-Messenger-Desktop,Aluxian/Facebook-Messenger-Desktop,Aluxian/Messenger-for-Desktop,Aluxian/Facebook-Messenger-Desktop,Hadisaeed/test-build,Hadisaeed/test-build,rafael-neri/whatsapp-webapp,rafael-neri/whatsapp-webapp,rafael-neri/whatsapp-webapp,Aluxian/Messenger-for-Desktop |
b989f178fe4fa05a7422a5f36a0b8291d35bb621 | src/mailer.js | src/mailer.js | var email = require('emailjs')
, debug = require('debug')('wifi-chat:mailer')
var config = null
, server = null
var connect = function() {
debug('Connecting to mail server', config.email.connection)
server = email.server.connect(config.email.connection)
}
var setConfig = function(configuration) {
config = configuration
connect()
}
var sendMail = function(to, subject, template, substitutions, callback) {
var content = template.replace(new RegExp('%url%', 'g'), config.url)
Object.keys(substitutions || {}).forEach(function(key) {
content = content.replace(new RegExp('%' + key + '%', 'g'), substitutions[key])
})
var message = {
text: content,
from: config.email.sendAddress,
to: to,
subject: subject
}
debug('Sending password reset email', message)
server.send(message, callback)
}
module.exports = {
setConfig: setConfig,
sendMail: sendMail
} | var email = require('emailjs')
, debug = require('debug')('wifi-chat:mailer')
var config = null
, server = null
var connect = function() {
debug('Connecting to mail server', config.email.connection)
server = email.server.connect(config.email.connection)
}
var setConfig = function(configuration) {
config = configuration
connect()
}
var sendMail = function(to, subject, template, substitutions, callback) {
var content = template.replace(new RegExp('%url%', 'g'), config.url)
Object.keys(substitutions || {}).forEach(function(key) {
content = content.replace(new RegExp('%' + key + '%', 'g'), substitutions[key])
})
var message = {
text: content,
from: config.email.sendAddress,
to: to,
subject: subject
}
debug('Sending email', message)
server.send(message, callback)
}
module.exports = {
setConfig: setConfig,
sendMail: sendMail
} | Update debug message to be less incorrect | Update debug message to be less incorrect
| JavaScript | apache-2.0 | project-isizwe/wifi-chat,webhost/wifi-chat,project-isizwe/wifi-chat,project-isizwe/wifi-chat,webhost/wifi-chat,webhost/wifi-chat |
099d30fdb02e4e69edc07529b9630f51b9e2dc4e | www/script.js | www/script.js | HandlebarsIntl.registerWith(Handlebars);
$(function() {
window.state = {};
var source = $("#stats-template").html();
var template = Handlebars.compile(source);
refreshStats(template);
setInterval(function() {
refreshStats(template);
}, 5000)
});
function refreshStats(template) {
$.getJSON("/stats", function(stats) {
$("#alert").addClass('hide');
// Sort miners by ID
if (stats.miners) {
stats.miners = stats.miners.sort(compare)
}
var epochOffset = (30000 - (stats.height % 30000)) * 1000 * 15
stats.nextEpoch = stats.now + epochOffset
// Repaint stats
var html = template(stats);
$('#stats').html(html);
}).fail(function() {
$("#alert").removeClass('hide');
});
}
function compare(a, b) {
if (a.name < b.name)
return -1;
if (a.name > b.name)
return 1;
return 0;
}
| HandlebarsIntl.registerWith(Handlebars);
$(function() {
window.state = {};
var source = $("#stats-template").html();
var template = Handlebars.compile(source);
refreshStats(template);
setInterval(function() {
refreshStats(template);
}, 5000)
});
function refreshStats(template) {
$.getJSON("/stats", function(stats) {
$("#alert").addClass('hide');
// Sort miners by ID
if (stats.miners) {
stats.miners = stats.miners.sort(compare)
}
var epochOffset = (30000 - (stats.height % 30000)) * 1000 * 14.4
stats.nextEpoch = stats.now + epochOffset
// Repaint stats
var html = template(stats);
$('#stats').html(html);
}).fail(function() {
$("#alert").removeClass('hide');
});
}
function compare(a, b) {
if (a.name < b.name)
return -1;
if (a.name > b.name)
return 1;
return 0;
}
| Adjust block time to 14.4 seconds | Adjust block time to 14.4 seconds
| JavaScript | mit | sammy007/ether-proxy,sammy007/ether-proxy,sammy007/ether-proxy,sammy007/ether-proxy |
3e89abf57c2242f8bef493eb0dc8fa053bec9e48 | lib/index.js | lib/index.js | /**
* Comma number formatter
* @param {Number} number Number to format
* @param {String} [separator=','] Value used to separate numbers
* @returns {String} Comma formatted number
*/
module.exports = function commaNumber (number, separator) {
separator = typeof separator === 'undefined' ? ',' : ('' + separator)
// Convert to number if it's a non-numeric value
if (typeof number !== 'number')
number = Number(number)
// NaN => 0
if (isNaN(number))
number = 0
// Return Infinity immediately
if (!isFinite(number))
return '' + number
var stringNumber = ('' + Math.abs(number))
.split('')
.reverse()
var result = []
for (var i = 0; i < stringNumber.length; i++) {
if (i && i % 3 === 0)
result.push(separator)
result.push(stringNumber[i])
}
// Handle negative numbers
if (number < 0)
result.push('-')
return result
.reverse()
.join('')
}
| /**
* Comma number formatter
* @param {Number} number Number to format
* @param {String} [separator=','] Value used to separate numbers
* @returns {String} Comma formatted number
*/
module.exports = function commaNumber (number, separator) {
separator = typeof separator === 'undefined' ? ',' : ('' + separator)
// Convert to number if it's a non-numeric value
if (typeof number !== 'number') {
number = Number(number)
}
// NaN => 0
if (isNaN(number)) {
number = 0
}
// Return Infinity immediately
if (!isFinite(number)) {
return '' + number
}
var stringNumber = ('' + Math.abs(number))
.split('')
.reverse()
var result = []
for (var i = 0; i < stringNumber.length; i++) {
if (i && i % 3 === 0) {
result.push(separator)
}
result.push(stringNumber[i])
}
// Handle negative numbers
if (number < 0) {
result.push('-')
}
return result
.reverse()
.join('')
}
| Update code to follow standard style | Update code to follow standard style
| JavaScript | mit | cesarandreu/comma-number |
2a1121c856f387c164e5239e6a7dacf2d2f29330 | test/test-main.js | test/test-main.js | 'use strict';
if (!Function.prototype.bind) {
// PhantomJS doesn't support bind yet
Function.prototype.bind = Function.prototype.bind || function(thisp) {
var fn = this;
return function() {
return fn.apply(thisp, arguments);
};
};
}
var tests = Object.keys(window.__karma__.files).filter(function(file) {
return /-spec\.js$/.test(file);
});
requirejs.config({
// Karma serves files from '/base'
baseUrl: '/base/src',
paths: {
'jquery': '../lib/jquery/jquery',
'extend': '../lib/gextend/extend'
},
// ask Require.js to load these files (all our tests)
deps: tests,
// start test run, once Require.js is done
callback: window.__karma__.start
}); | 'use strict';
if (!Function.prototype.bind) {
// PhantomJS doesn't support bind yet
Function.prototype.bind = Function.prototype.bind || function(thisp) {
var fn = this;
return function() {
return fn.apply(thisp, arguments);
};
};
}
var tests = Object.keys(window.__karma__.files).filter(function(file) {
return /-spec\.js$/.test(file);
});
requirejs.config({
// Karma serves files from '/base'
baseUrl: '/base/src',
paths: {
'extend': '../lib/gextend/extend'
},
// ask Require.js to load these files (all our tests)
deps: tests,
// start test run, once Require.js is done
callback: window.__karma__.start
}); | Remove jQuery dependency, not used | TEST: Remove jQuery dependency, not used
| JavaScript | mit | goliatone/gsocket |
7e71970b1cb76c8a916e365491ca07252a61a208 | src/server.js | src/server.js | import express from 'express';
import ReactDOMServer from 'react-dom/server'
import {Router} from 'react-router';
import MemoryHistory from 'react-router/lib/MemoryHistory';
import React from 'react';
import routes from './routing';
let app = express();
//app.engine('html', require('ejs').renderFile);
//app.set('view engine', 'html');
app.use(function (req, res, next) {
let history = new MemoryHistory([req.url]);
let html = ReactDOMServer.renderToString(
<Router history={history}>
{routes}
</Router>
);
return res.send(html);
/*var router = Router.create({location: req.url, routes: routes})
router.run(function(Handler, state) {
var html = ReactDOMServer.renderToString(<Handler/>)
return res.render('react_page', {html: html})
})*/
});
let server = app.listen(8000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
| import express from 'express';
import ReactDOMServer from 'react-dom/server'
import {Router} from 'react-router';
import MemoryHistory from 'react-router/lib/MemoryHistory';
import React from 'react';
import routes from './routing';
let app = express();
//app.engine('html', require('ejs').renderFile);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static('../public'));
app.use(function (req, res, next) {
let history = new MemoryHistory([req.url]);
let html = ReactDOMServer.renderToString(
<Router history={history}>
{routes}
</Router>
);
return res.render('index', {html: html});
});
let server = app.listen(8000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
| Handle initial page laod via express | Handle initial page laod via express
| JavaScript | agpl-3.0 | voidxnull/libertysoil-site,Lokiedu/libertysoil-site,voidxnull/libertysoil-site,Lokiedu/libertysoil-site |
14e97545ba507765cd186b549981e0ebc55f1dff | javascript/NocaptchaField.js | javascript/NocaptchaField.js | var _noCaptchaFields=_noCaptchaFields || [];
function noCaptchaFieldRender() {
for(var i=0;i<_noCaptchaFields.length;i++) {
var field=document.getElementById('Nocaptcha-'+_noCaptchaFields[i]);
var options={
'sitekey': field.getAttribute('data-sitekey'),
'theme': field.getAttribute('data-theme'),
'type': field.getAttribute('data-type'),
'size': field.getAttribute('data-size'),
'callback': (field.getAttribute('data-callback') ? verifyCallback : undefined )
};
grecaptcha.render(field, options);
}
}
| var _noCaptchaFields=_noCaptchaFields || [];
function noCaptchaFieldRender() {
for(var i=0;i<_noCaptchaFields.length;i++) {
var field=document.getElementById('Nocaptcha-'+_noCaptchaFields[i]);
var options={
'sitekey': field.getAttribute('data-sitekey'),
'theme': field.getAttribute('data-theme'),
'type': field.getAttribute('data-type'),
'size': field.getAttribute('data-size'),
'callback': (field.getAttribute('data-callback') ? verifyCallback : undefined )
};
var widget_id = grecaptcha.render(field, options);
field.setAttribute("data-widgetid", widget_id);
}
}
| Store widget_id on field element | Store widget_id on field element
This allows the captcha element to be targeted via the js api in situations where there is more than one nocaptcha widget on the page. See examples referencing `opt_widget_id` here https://developers.google.com/recaptcha/docs/display#js_api | JavaScript | bsd-3-clause | UndefinedOffset/silverstripe-nocaptcha,UndefinedOffset/silverstripe-nocaptcha |
2ebe898d9f2284ee0f25d8ac927bef4e7bb730de | lib/store.js | lib/store.js | var Store = module.exports = function () {
};
Store.prototype.hit = function (req, configuration, callback) {
var self = this;
var ip = req.ip;
var path;
if (configuration.pathLimiter) {
path = (req.baseUrl) ? req.baseUrl.replace(req.path, '') : '';
ip += configuration.path || path;
}
var now = Date.now();
self.get(ip, function (err, limit) {
if (err) {
callback(err, undefined, now);
return;
};
if (limit) {
//Existing user
var limitDate = limit.date;
var timeLimit = limitDate + configuration.innerTimeLimit;
var resetInner = now > timeLimit;
limit.date = now;
self.decreaseLimits(ip, limit, resetInner, configuration, function (error, result) {
callback(error, result, limitDate);
});
} else {
//New User
var outerReset = Math.floor((now + configuration.outerTimeLimit) / 1000);
limit = {
date: now,
inner: configuration.innerLimit,
outer: configuration.outerLimit,
firstDate: now,
outerReset: outerReset
};
self.create(ip, limit, configuration, function (error, result) {
callback(error, result, now);
});
}
}, configuration);
}
| var Store = module.exports = function () {
};
Store.prototype.hit = function (req, configuration, callback) {
var self = this;
var ip = req.ip;
var path;
if (configuration.pathLimiter) {
path = (req.baseUrl) ? req.baseUrl.replace(req.path, '') : '';
ip += configuration.path || path;
}
var now = Date.now();
self.get(ip, function (err, limit) {
if (err) {
callback(err, undefined, now);
return;
};
if (limit) {
//Existing user
var limitDate = limit.date;
var timeLimit = limitDate + configuration.innerTimeLimit;
var resetInner = now > timeLimit;
if (resetInner) {
limit.date = now;
}
self.decreaseLimits(ip, limit, resetInner, configuration, function (error, result) {
callback(error, result, limitDate);
});
} else {
//New User
var outerReset = Math.floor((now + configuration.outerTimeLimit) / 1000);
limit = {
date: now,
inner: configuration.innerLimit,
outer: configuration.outerLimit,
firstDate: now,
outerReset: outerReset
};
self.create(ip, limit, configuration, function (error, result) {
callback(error, result, now);
});
}
}, configuration);
}
| Fix bug with inner reset time | Fix bug with inner reset time | JavaScript | mit | StevenThuriot/express-rate-limiter |
df1807f823332d076a0dff7e6ec0b49b8a42e8ad | config-SAMPLE.js | config-SAMPLE.js | /* Magic Mirror Config Sample
*
* By Michael Teeuw http://michaelteeuw.nl
* MIT Licensed.
*/
var config = {
port: 8080,
language: 'en',
timeFormat: 12,
units: 'imperial',
modules: [
{
module: 'clock',
position: 'top_left',
config: {
displaySeconds: false
}
},
{
module: 'hurst/weather',
position: 'top_right',
config: {
}
}
]
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== 'undefined') {module.exports = config;}
| /* Magic Mirror Config Sample
*
* By Michael Teeuw http://michaelteeuw.nl
* MIT Licensed.
*/
var config = {
port: 8080,
language: 'en',
timeFormat: 12,
units: 'imperial',
modules: [
{
module: 'clock',
position: 'top_left',
config: {
displaySeconds: false
}
},
{
module: 'hurst/muni',
position: 'top_left',
config: {
stops: ['48|3463']
}
},
{
module: 'hurst/weather',
position: 'top_right',
config: {
apiKey: 'MUST_PUT_KEY_HERE',
latLng: '37.700000,-122.400000'
}
}
]
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== 'undefined') {module.exports = config;}
| Update sample config for new modules. | Update sample config for new modules.
| JavaScript | apache-2.0 | jhurstus/mirror,jhurstus/mirror |
ead9142a9701300da3021e79155a9717ec4c3683 | app/src/components/RobotSettings/AttachedInstrumentsCard.js | app/src/components/RobotSettings/AttachedInstrumentsCard.js | // @flow
// RobotSettings card for wifi status
import * as React from 'react'
import {type StateInstrument} from '../../robot'
import InstrumentInfo from './InstrumentInfo'
import {Card} from '@opentrons/components'
type Props = {
left: StateInstrument,
right: StateInstrument
}
const TITLE = 'Pipettes'
export default function AttachedInstrumentsCard (props: Props) {
// TODO (ka 2018-3-14): not sure where this will be comining from in state so mocking it up for styling purposes
// here I am assuming they key and mount will always exist and some sort of presence of a pipette indicator will affect InstrumentInfo
// delete channels and volume in either elft or right to view value and button message change
// apologies for the messy logic, hard to anticipate what is returned just yet
const attachedInstruments = {
left: {
mount: 'left',
channels: 8,
volume: 300
},
right: {
mount: 'right',
channels: 1,
volume: 10
}
}
return (
<Card title={TITLE} >
<InstrumentInfo {...attachedInstruments.left}/>
<InstrumentInfo {...attachedInstruments.right} />
</Card>
)
}
| // RobotSettings card for wifi status
import * as React from 'react'
import InstrumentInfo from './InstrumentInfo'
import {Card} from '@opentrons/components'
const TITLE = 'Pipettes'
export default function AttachedInstrumentsCard (props) {
// TODO (ka 2018-3-14): not sure where this will be comining from in state so mocking it up for styling purposes
// here I am assuming they key and mount will always exist and some sort of presence of a pipette indicator will affect InstrumentInfo
// delete channels and volume in either elft or right to view value and button message change
// apologies for the messy logic, hard to anticipate what is returned just yet
const attachedInstruments = {
left: {
mount: 'left',
channels: 8,
volume: 300
},
right: {
mount: 'right',
channels: 1,
volume: 10
}
}
return (
<Card title={TITLE} >
<InstrumentInfo {...attachedInstruments.left}/>
<InstrumentInfo {...attachedInstruments.right} />
</Card>
)
}
| Remove flow typchecking from InstrumentCard | Remove flow typchecking from InstrumentCard
- Removed typchecking from AttachedInstrumentCard since mock data is currently being used.
| JavaScript | apache-2.0 | OpenTrons/opentrons-api,OpenTrons/opentrons-api,OpenTrons/opentrons-api,OpenTrons/opentrons-api,OpenTrons/opentrons-api,Opentrons/labware,OpenTrons/opentrons_sdk |
761977b9c98bd5f92d6c90981fff16fec2df4893 | src/components/svg/SVGComponents.js | src/components/svg/SVGComponents.js | import React, { PropTypes } from 'react'
import classNames from 'classnames'
export const SVGComponent = ({ children, ...rest }) =>
<svg {...rest}>
{children}
</svg>
SVGComponent.propTypes = {
children: PropTypes.node.isRequired,
}
export const SVGIcon = ({ children, className, onClick }) =>
<SVGComponent
className={classNames(className, 'SVGIcon')}
onClick={onClick}
width="20"
height="20"
>
{children}
</SVGComponent>
SVGIcon.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string.isRequired,
onClick: PropTypes.func,
}
SVGIcon.defaultProps = {
onClick: null,
}
export const SVGBox = ({ children, className, size = '40' }) =>
<SVGComponent
className={classNames(className, 'SVGBox')}
width={size}
height={size}
>
{children}
</SVGComponent>
SVGBox.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string.isRequired,
size: PropTypes.string,
}
SVGBox.defaultProps = {
size: null,
}
| import React, { PropTypes } from 'react'
import classNames from 'classnames'
export const SVGComponent = ({ children, ...rest }) =>
<svg {...rest}>
{children}
</svg>
SVGComponent.propTypes = {
children: PropTypes.node.isRequired,
}
export const SVGIcon = ({ children, className, onClick }) =>
<SVGComponent
className={classNames(className, 'SVGIcon')}
onClick={onClick}
width="20"
height="20"
>
{children}
</SVGComponent>
SVGIcon.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string.isRequired,
onClick: PropTypes.func,
}
SVGIcon.defaultProps = {
onClick: null,
}
export const SVGBox = ({ children, className, size }) =>
<SVGComponent
className={classNames(className, 'SVGBox')}
width={size}
height={size}
>
{children}
</SVGComponent>
SVGBox.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string.isRequired,
size: PropTypes.string,
}
SVGBox.defaultProps = {
size: 40,
}
| Set the default size to 40 on SVGBoxes | Set the default size to 40 on SVGBoxes
The null value was causing some weird rendering issues on a few icons
| JavaScript | mit | ello/webapp,ello/webapp,ello/webapp |
904ec5fd379bf47f66794af36ffcd5ecbf5d3ec5 | blueprints/ember-flexberry/index.js | blueprints/ember-flexberry/index.js | /* globals module */
module.exports = {
afterInstall: function () {
this.addBowerPackageToProject('git://github.com/BreadMaker/semantic-ui-daterangepicker.git#5d46ed2e6e5a0bf398bb6a5df82e06036dfc46be');
this.addBowerPackageToProject('datatables');
},
normalizeEntityName: function () {}
}; | /* globals module */
module.exports = {
afterInstall: function () {
return this.addBowerPackagesToProject([
{ name: 'semantic-ui-daterangepicker', target: '5d46ed2e6e5a0bf398bb6a5df82e06036dfc46be' },
{ name: 'datatables', target: '~1.10.8' }
]);
},
normalizeEntityName: function () {}
}; | Fix bower packages installation for addon | Fix bower packages installation for addon
| JavaScript | mit | Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry |
ae5d7724d279e3d1feb1c696d70f6a030407053e | test/patch.js | test/patch.js | var patch = require("../lib/patch")
, net = require("net")
, https = require("https")
, fs = require("fs");
// This is probably THE most ugliest code I've ever written
var responseRegExp = /^([0-9a-z-]{36}) (.*)$/i;
var host = net.createServer(function(socket) {
var i = 0;
socket.setEncoding("utf8");
socket.on("data", function(data) {
switch(i) {
case 0: socket.write("SUCCESS"); break;
default: socket.write(data.match(responseRegExp)[1] + " " + JSON.stringify({
peername: { address: "peer-address", port: 1234 },
sockname: { address: "sock-address", port: 1234 }
}));
}
i++;
});
}).listen(0).address().port;
var ssl = {
cert: fs.readFileSync(__dirname + "/ssl/cert.pem"),
key: fs.readFileSync(__dirname + "/ssl/key.pem")
};
// The utlimate test: HTTPS (and therefore SPDY too)
var server = https.createServer(ssl, function(req, res) {
console.log(req.socket.remoteAddress + ":" + req.socket.remotePort);
res.end("Fuck yeah!");
});
patch(host, server, true).listen("address"); | var patch = require("../lib/patch")
, net = require("net")
, https = require("https")
, fs = require("fs");
// This is probably THE most ugliest code I've ever written
var responseRegExp = /^([0-9a-z-]{36}) (.*)$/i;
var host = net.createServer(function(socket) {
var i = 0;
socket.setEncoding("utf8");
socket.on("data", function(data) {
switch(i) {
case 0: socket.write("SUCCESS"); break;
default: socket.write(data.match(responseRegExp)[1] + " " + JSON.stringify({
peername: { address: "peer-address", port: 1234 },
sockname: { address: "sock-address", port: 1234 }
}));
}
i++;
});
}).listen(0).address().port;
var ssl = {
cert: fs.readFileSync(__dirname + "/ssl/cert.pem"),
key: fs.readFileSync(__dirname + "/ssl/key.pem")
};
// The utlimate test: HTTPS (and therefore SPDY too)
var server = https.createServer(ssl, function(req, res) {
console.log(req.socket.remoteAddress + ":" + req.socket.remotePort);
res.end("Fuck yeah!");
}).on("error", console.log);
patch(host, server, true).listen("address"); | Add error listener to test | Add error listener to test
| JavaScript | mit | buschtoens/distroy |
a7b3e2edaa8f1f2791f3cf8c88d210ca7f3b06c1 | webpack.config.js | webpack.config.js | 'use strict';
const path = require('path');
const webpack = require('webpack');
module.exports = {
cache: true,
devtool: '#source-map',
entry: [
path.resolve(__dirname, 'src', 'index.js')
],
module: {
rules: [
{
enforce: 'pre',
include: [
path.resolve(__dirname, 'src')
],
loader: 'eslint-loader',
options: {
configFile: '.eslintrc',
failOnError: true,
failOnWarning: false,
formatter: require('eslint-friendly-formatter')
},
test: /\.js$/
}, {
include: [
path.resolve(__dirname, 'src')
],
options: {
babelrc: false,
plugins: [
'syntax-flow',
'transform-flow-strip-types'
],
presets: [
['env', {
loose: true,
modules: false
}],
'stage-2'
]
},
test: /\.js$/,
loader: 'babel-loader'
}
]
},
output: {
filename: 'moize.js',
library: 'moize',
libraryTarget: 'umd',
path: path.resolve(__dirname, 'dist'),
umdNamedDefine: true
},
plugins: [
new webpack.EnvironmentPlugin([
'NODE_ENV'
])
],
resolve: {
modules: [
path.join(__dirname, 'src'),
'node_modules'
]
}
};
| 'use strict';
const path = require('path');
const webpack = require('webpack');
module.exports = {
cache: true,
devtool: '#source-map',
entry: [
path.resolve(__dirname, 'src', 'index.js')
],
module: {
rules: [
{
enforce: 'pre',
include: [
path.resolve(__dirname, 'src')
],
loader: 'eslint-loader',
options: {
cache: true,
configFile: '.eslintrc',
failOnError: true,
failOnWarning: false,
fix: true,
formatter: require('eslint-friendly-formatter')
},
test: /\.js$/
}, {
include: [
path.resolve(__dirname, 'src')
],
options: {
babelrc: false,
plugins: [
'syntax-flow',
'transform-flow-strip-types'
],
presets: [
['env', {
loose: true,
modules: false
}],
'stage-2'
]
},
test: /\.js$/,
loader: 'babel-loader'
}
]
},
output: {
filename: 'moize.js',
library: 'moize',
libraryTarget: 'umd',
path: path.resolve(__dirname, 'dist'),
umdNamedDefine: true
},
plugins: [
new webpack.EnvironmentPlugin([
'NODE_ENV'
])
],
resolve: {
modules: [
path.join(__dirname, 'src'),
'node_modules'
]
}
};
| Improve ESLint options for Webpack | Improve ESLint options for Webpack | JavaScript | mit | planttheidea/moize,planttheidea/moize |
fcaba4d5f8df8562dabeacbdcdb4f20abe9fcafd | webpack.config.js | webpack.config.js | const path = require('path');
const webpack = require("webpack");
const DEBUG = process.argv.includes('--debug'); // `webpack --debug` or NOT
const plugins = [
new webpack.optimize.OccurrenceOrderPlugin(),
];
if (!DEBUG) {
plugins.push(
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
);
}
module.exports = {
entry: "./src/js/ipcalc.js",
output: {
filename: "bundle.js",
path: path.join(__dirname, "public/js")
},
plugins: plugins,
devtool: DEBUG ? "#cheap-module-eval-source-map" : "#cheap-module-source-map",
resolve: {
alias: {
vue: 'vue/dist/vue.js'
}
}
}
| const path = require('path');
const webpack = require("webpack");
const DEBUG = process.argv.includes('--debug'); // `webpack --debug` or NOT
const plugins = [
new webpack.optimize.OccurrenceOrderPlugin(),
];
if (!DEBUG) {
plugins.push(
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.DefinePlugin({
'process.env': { NODE_ENV: '"production"' }
})
);
}
module.exports = {
entry: "./src/js/ipcalc.js",
output: {
filename: "bundle.js",
path: path.join(__dirname, "public/js")
},
plugins: plugins,
devtool: DEBUG ? "#cheap-module-eval-source-map" : "#cheap-module-source-map",
resolve: {
alias: {
vue: 'vue/dist/vue.js'
}
}
}
| Add vue.js release build option | Add vue.js release build option
| JavaScript | mit | stereocat/ipcalc_js,stereocat/ipcalc_js |
06296e083225aab969d009cb0bf312872a18e504 | blueprints/ember-table/index.js | blueprints/ember-table/index.js | module.exports = {
normalizeEntityName: function() {},
afterInstall: function(options) {
// We assume that handlebars, ember, and jquery already exist
// FIXME(azirbel): Do we need to install lodash too?
return this.addBowerPackagesToProject([
{
'name': 'git@github.com:azirbel/antiscroll.git#90391fb371c7be769bc32e7287c5271981428356'
},
{
'name': 'jquery-mousewheel',
'target': '~3.1.4'
},
{
'name': 'jquery-ui',
// FIXME(azirbel): Can we use a newer version?
'target': '1.10.1'
}
]);
}
};
| module.exports = {
normalizeEntityName: function() {},
afterInstall: function(options) {
// We assume that handlebars, ember, and jquery already exist
// FIXME(azirbel): Do we need to install lodash too?
return this.addBowerPackagesToProject([
{
'name': 'git://github.com/azirbel/antiscroll.git#90391fb371c7be769bc32e7287c5271981428356'
},
{
'name': 'jquery-mousewheel',
'target': '~3.1.4'
},
{
'name': 'jquery-ui',
// FIXME(azirbel): Can we use a newer version?
'target': '1.10.1'
}
]);
}
};
| Use more general bower syntax to import antiscroll | Use more general bower syntax to import antiscroll
| JavaScript | mit | zenefits/ember-table-addon,Addepar/ember-table-addon,zenefits/ember-table-addon,Addepar/ember-table-addon |
349bad1afc06c0af44ff42ab7358e393f3ec4fd9 | lib/ipc-helpers/dump-node.js | lib/ipc-helpers/dump-node.js | #!/usr/bin/env node
process.on('exit', function sendCoverage() {
process.send({'coverage': global.__coverage__});
});
| #!/usr/bin/env node
process.on('beforeExit', function sendCovereageBeforeExit() {
process.send({'coverage': global.__coverage__});
});
| Use beforeExit event to send coverage | Use beforeExit event to send coverage
| JavaScript | mit | rtsao/unitest |
7d8145fce09a92004fbf302953d37863d2bc202b | lib/matrices.js | lib/matrices.js |
function Matrix(options) {
options = options || {};
var values;
if (options.values)
values = options.values;
if (options.rows && options.columns && !values) {
values = [];
for (var k = 0; k < options.rows; k++) {
var row = [];
for (var j = 0; j < options.columns; j++)
row[j] = 0;
values.push(row);
}
}
this.nrows = function () {
if (!values)
return 0;
return values.length;
};
this.ncolumns = function () {
if (!values)
return 0;
return values[0].length;
};
this.element = function (r, c) {
if (!values) return 0;
var row = values[r];
if (!row) return 0;
var element = values[r][c];
return element == null ? 0 : element;
};
}
Matrix.prototype.isMatrix = function () { return true; }
Matrix.prototype.isVector = function () { return false; }
function createMatrix(options) {
return new Matrix(options);
}
module.exports = {
createMatrix: createMatrix
}
|
function Matrix(options) {
options = options || {};
var values;
if (options.values) {
values = options.values.slice();
for (var k = 0; k < values.length; k++)
values[k] = values[k].slice();
}
if (options.rows && options.columns && !values) {
values = [];
for (var k = 0; k < options.rows; k++) {
var row = [];
for (var j = 0; j < options.columns; j++)
row[j] = 0;
values.push(row);
}
}
this.nrows = function () {
if (!values)
return 0;
return values.length;
};
this.ncolumns = function () {
if (!values)
return 0;
return values[0].length;
};
this.element = function (r, c) {
if (!values) return 0;
var row = values[r];
if (!row) return 0;
var element = values[r][c];
return element == null ? 0 : element;
};
}
Matrix.prototype.isMatrix = function () { return true; }
Matrix.prototype.isVector = function () { return false; }
function createMatrix(options) {
return new Matrix(options);
}
module.exports = {
createMatrix: createMatrix
}
| Refactor matrix creation to use values slice | Refactor matrix creation to use values slice
| JavaScript | mit | ajlopez/MathelJS |
61f575559be7c973e2fa4bb816221dc63112bffd | test/TestServer/config/UnitTest.js | test/TestServer/config/UnitTest.js | 'use strict';
// Default amount of devices required to run tests.
module.exports = {
devices: {
// This is a list of required platforms.
// All required platform should have minDevices entry.
// So all required platforms should be listed in desired platform list.
ios: -1,
android: -1,
desktop: -1
},
minDevices: {
// This is a list of desired platforms.
ios: 2,
android: 0,
desktop: 0
},
// if 'devices[platform]' is -1 we wont limit the amount of devices.
// We will wait some amount of time before tests.
waiting_for_devices_timeout: 5 * 1000
};
| 'use strict';
// Default amount of devices required to run tests.
module.exports = {
devices: {
// This is a list of required platforms.
// All required platform should have minDevices entry.
// So all required platforms should be listed in desired platform list.
ios: -1,
android: -1,
desktop: -1
},
minDevices: {
// This is a list of desired platforms.
ios: 3,
android: 3,
desktop: 3
},
// if 'devices[platform]' is -1 we wont limit the amount of devices.
// We will wait some amount of time before tests.
waiting_for_devices_timeout: 5 * 1000
};
| Revert "Reduce the min number of devices to test." | Revert "Reduce the min number of devices to test."
This reverts commit 90e5494b3212350d7cb7ef946c5b9d8fa62189d5.
| JavaScript | mit | thaliproject/Thali_CordovaPlugin,thaliproject/Thali_CordovaPlugin,thaliproject/Thali_CordovaPlugin,thaliproject/Thali_CordovaPlugin,thaliproject/Thali_CordovaPlugin |
c29d3a670722b2f4d0a394e6a72ecb647687893a | .storybook/main.js | .storybook/main.js | module.exports = {
addons: ['@storybook/addon-backgrounds', '@storybook/addon-knobs'],
};
| module.exports = {
stories: ['../**/*.stories.js'],
addons: ['@storybook/addon-backgrounds', '@storybook/addon-knobs'],
};
| Define where to find the component stories | Define where to find the component stories
| JavaScript | mit | teamleadercrm/teamleader-ui |
ade0cebb2c7edcacb2f0e83a103e55529fa024cc | lib/user-data.js | lib/user-data.js | //
// This file talks to the main process by fetching the path to the user data.
// It also writes updates to the user-data file.
//
var ipc = require('electron').ipcRenderer
var fs = require('fs')
var getData = function () {
var data = {}
data.path = ipc.sendSync('getUserDataPath', null)
data.contents = JSON.parse(fs.readFileSync(data.path))
return data
}
var getSavedDir = function () {
var savedDir = {}
data.path = ipc.sendSync('getUserSavedDir', null)
data.contents = JSON.parse(fs.readFileSync(data.path))
return savedDir
}
var writeData = function (data) {
fs.writeFile(data.path, JSON.stringify(data.contents, null, ' '), function updatedUserData (err) {
if (err) return console.log(err)
})
}
// this could take in a boolean on compelte status
// and be named better in re: to updating ONE challenge, not all
var updateData = function (challenge) {
var data = getData()
data.contents[challenge].completed = true
writeData(data)
}
var updateCurrentDirectory = function (path) {
var data = getSavedDir()
data.contents.savedDir = path
writeData(data)
}
module.exports.getData = getData
module.exports.updateData = updateData
module.exports.updateCurrentDirectory = updateCurrentDirectory
| //
// This file talks to the main process by fetching the path to the user data.
// It also writes updates to the user-data file.
//
var ipc = require('electron').ipcRenderer
var fs = require('fs')
var getData = function () {
var data = {}
data.path = ipc.sendSync('getUserDataPath', null)
data.contents = JSON.parse(fs.readFileSync(data.path))
return data
}
var getSavedDir = function () {
var savedDir = {}
savedDir.path = ipc.sendSync('getUserSavedDir', null)
savedDir.contents = JSON.parse(fs.readFileSync(savedDir.path))
return savedDir
}
var writeData = function (data) {
fs.writeFile(data.path, JSON.stringify(data.contents, null, ' '), function updatedUserData (err) {
if (err) return console.log(err)
})
}
// this could take in a boolean on compelte status
// and be named better in re: to updating ONE challenge, not all
var updateData = function (challenge) {
var data = getData()
data.contents[challenge].completed = true
writeData(data)
}
var updateCurrentDirectory = function (path) {
var data = getSavedDir()
data.contents.savedDir = path
writeData(data)
}
module.exports.getData = getData
module.exports.getSavedDir = getSavedDir
module.exports.updateData = updateData
module.exports.updateCurrentDirectory = updateCurrentDirectory
| Fix having not set this up correctly | Fix having not set this up correctly
| JavaScript | bsd-2-clause | jlord/git-it-electron,jlord/git-it-electron,shiftkey/git-it-electron,vongola12324/git-it-electron,vongola12324/git-it-electron,shiftkey/git-it-electron,shiftkey/git-it-electron,vongola12324/git-it-electron,vongola12324/git-it-electron,vongola12324/git-it-electron,vongola12324/git-it-electron,shiftkey/git-it-electron,jlord/git-it-electron,shiftkey/git-it-electron,shiftkey/git-it-electron,jlord/git-it-electron,shiftkey/git-it-electron,jlord/git-it-electron,vongola12324/git-it-electron,jlord/git-it-electron |
b1da47403f4871313e0759a21091ace04151cb84 | src/renderer/actions/connections.js | src/renderer/actions/connections.js | import { sqlectron } from '../../browser/remote';
export const CONNECTION_REQUEST = 'CONNECTION_REQUEST';
export const CONNECTION_SUCCESS = 'CONNECTION_SUCCESS';
export const CONNECTION_FAILURE = 'CONNECTION_FAILURE';
export const dbSession = sqlectron.db.createSession();
export function connect (id, database) {
return async (dispatch, getState) => {
const { servers } = getState();
const [ server, config ] = await* [
servers.items.find(srv => srv.id === id),
sqlectron.config.get(),
];
dispatch({ type: CONNECTION_REQUEST, server, database });
try {
await dbSession.connect(server, database);
dispatch({ type: CONNECTION_SUCCESS, server, database, config });
} catch (error) {
dispatch({ type: CONNECTION_FAILURE, server, database, error });
}
};
}
| import { sqlectron } from '../../browser/remote';
export const CONNECTION_REQUEST = 'CONNECTION_REQUEST';
export const CONNECTION_SUCCESS = 'CONNECTION_SUCCESS';
export const CONNECTION_FAILURE = 'CONNECTION_FAILURE';
export const dbSession = sqlectron.db.createSession();
export function connect (id, database) {
return async (dispatch, getState) => {
const { servers } = getState();
const server = servers.items.find(srv => srv.id === id);
dispatch({ type: CONNECTION_REQUEST, server, database });
try {
const [, config ] = await Promise.all([
dbSession.connect(server, database),
sqlectron.config.get(),
]);
dispatch({ type: CONNECTION_SUCCESS, server, database, config });
} catch (error) {
dispatch({ type: CONNECTION_FAILURE, server, database, error });
}
};
}
| Use promise all at the right place in the server connecting action | Use promise all at the right place in the server connecting action | JavaScript | mit | sqlectron/sqlectron-gui,sqlectron/sqlectron-gui,sqlectron/sqlectron-gui,sqlectron/sqlectron-gui |
0ebb23201bc8364368cb77c5b502a345d3144f0e | www/pg-plugin-fb-connect.js | www/pg-plugin-fb-connect.js | PG = ( typeof PG == 'undefined' ? {} : PG );
PG.FB = {
init: function(apiKey) {
PhoneGap.exec(function(e) {
console.log("init: " + e);
}, null, 'com.facebook.phonegap.Connect', 'init', [apiKey]);
},
login: function(a, b) {
try {
b = b || { perms: '' };
PhoneGap.exec(function(e) { // login
//FB.Auth.setSession(e.session, 'connected'); // never gets called because the plugin spawns Mobile Safari/Facebook app
if (a) a(e);
}, null, 'com.facebook.phonegap.Connect', 'login', b.perms.split(',') );
} catch (e) {
alert(e);
}
},
logout: function(cb) {
try {
PhoneGap.exec(function(e) {
FB.Auth.setSession(null, 'notConnected');
if (cb) cb(e);
}, null, 'com.facebook.phonegap.Connect', 'logout', []);
} catch (e) {
alert(e);
}
},
getLoginStatus: function(cb) {
try {
PhoneGap.exec(function(e) {
if (cb) cb(e);
console.log("getLoginStatus: " + e);
}, null, 'com.facebook.phonegap.Connect', 'getLoginStatus', []);
} catch (e) {
alert(e);
}
}
};
| PG = ( typeof PG == 'undefined' ? {} : PG );
PG.FB = {
init: function(apiKey) {
PhoneGap.exec(null, null, 'com.facebook.phonegap.Connect', 'init', [apiKey]);
},
login: function(a, b) {
b = b || { perms: '' };
PhoneGap.exec(function(e) { // login
FB.Auth.setSession(e.session, 'connected');
if (a) a(e);
}, null, 'com.facebook.phonegap.Connect', 'login', b.perms.split(',') );
},
logout: function(cb) {
PhoneGap.exec(function(e) {
FB.Auth.setSession(null, 'notConnected');
if (cb) cb(e);
}, null, 'com.facebook.phonegap.Connect', 'logout', []);
},
getLoginStatus: function(cb) {
PhoneGap.exec(function(e) {
if (cb) cb(e);
}, null, 'com.facebook.phonegap.Connect', 'getLoginStatus', []);
}
}; | Update the JS to remove alerts etc and login now has to have its success method called | Update the JS to remove alerts etc and login now has to have its success method called
| JavaScript | mit | barfight/phonegap-plugin-facebook-connect,irnc/phonegap-plugin-facebook-connect,AntonDobrev/phonegap-plugin-facebook-connect,totoo74/phonegap-plugin-facebook-connect,AntonDobrev/phonegap-plugin-facebook-connect,irnc/phonegap-plugin-facebook-connect,totoo74/phonegap-plugin-facebook-connect,barfight/phonegap-plugin-facebook-connect,MingxuanLi/phonegap-plugin-facebook-connect,MingxuanLi/phonegap-plugin-facebook-connect,barfight/phonegap-plugin-facebook-connect,irnc/phonegap-plugin-facebook-connect,AntonDobrev/phonegap-plugin-facebook-connect,barfight/phonegap-plugin-facebook-connect,MingxuanLi/phonegap-plugin-facebook-connect,AntonDobrev/phonegap-plugin-facebook-connect,totoo74/phonegap-plugin-facebook-connect,MingxuanLi/phonegap-plugin-facebook-connect,barfight/phonegap-plugin-facebook-connect,totoo74/phonegap-plugin-facebook-connect,AntonDobrev/phonegap-plugin-facebook-connect |
a7dd9961d9350fc38ad2ad679c6e6b1d1e85e6e9 | packages/core/lib/commands/help.js | packages/core/lib/commands/help.js | var command = {
command: "help",
description:
"List all commands or provide information about a specific command",
help: {
usage: "truffle help [<command>]",
options: [
{
option: "<command>",
description: "Name of the command to display information for."
}
]
},
builder: {},
run: function(options, callback) {
var commands = require("./index");
if (options._.length === 0) {
this.displayCommandHelp("help");
return callback();
}
var selectedCommand = options._[0];
if (commands[selectedCommand]) {
this.displayCommandHelp(selectedCommand);
return callback();
} else {
console.log(`\n Cannot find the given command '${selectedCommand}'`);
console.log(" Please ensure your command is one of the following: ");
Object.keys(commands)
.sort()
.forEach(command => console.log(` ${command}`));
console.log("");
return callback();
}
},
displayCommandHelp: function(selectedCommand) {
var commands = require("./index");
var commandHelp = commands[selectedCommand].help;
console.log(`\n Usage: ${commandHelp.usage}`);
console.log(` Description: ${commands[selectedCommand].description}`);
if (commandHelp.options.length > 0) {
console.log(` Options: `);
commandHelp.options.forEach(option => {
console.log(` ${option.option}`);
console.log(` ${option.description}`);
});
}
console.log("");
}
};
module.exports = command;
| var command = {
command: "help",
description:
"List all commands or provide information about a specific command",
help: {
usage: "truffle help [<command>]",
options: [
{
option: "<command>",
description: "Name of the command to display information for."
}
]
},
builder: {},
run: function (options, callback) {
var commands = require("./index");
if (options._.length === 0) {
this.displayCommandHelp("help");
return callback();
}
var selectedCommand = options._[0];
if (commands[selectedCommand]) {
this.displayCommandHelp(selectedCommand);
return callback();
} else {
console.log(`\n Cannot find the given command '${selectedCommand}'`);
console.log(" Please ensure your command is one of the following: ");
Object.keys(commands)
.sort()
.forEach(command => console.log(` ${command}`));
console.log("");
return callback();
}
},
displayCommandHelp: function (selectedCommand) {
var commands = require("./index");
var commandHelp = commands[selectedCommand].help;
console.log(`\n Usage: ${commandHelp.usage}`);
console.log(` Description: ${commands[selectedCommand].description}`);
if (commandHelp.options.length > 0) {
console.log(` Options: `);
for (const option of commandHelp.options) {
if (option.internal) {
continue;
}
console.log(` ${option.option}`);
console.log(` ${option.description}`);
}
}
console.log("");
}
};
module.exports = command;
| Allow commands to define internal options | Allow commands to define internal options
So those options don't appear in the help output
| JavaScript | mit | ConsenSys/truffle |
00d07f1f24af00950908b79e8670697d3b8f3a17 | webpack.config.js | webpack.config.js | var webpack = require('webpack')
, glob = require('glob').sync
, ExtractTextPlugin = require('extract-text-webpack-plugin');
// Find all the css files but sort the common ones first
var cssFiles = glob('./src/common/**/*.css').concat(glob('./src/!(common)/**/*.css'));
module.exports = {
entry: {
'sir-trevor-blocks.js' : './src/entry.js',
'sir-trevor-blocks.css' : cssFiles
},
output: {
path: __dirname,
filename: '[name]'
},
module: {
loaders: [
{ test: /\.html$/, loader: 'html' },
{ test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') },
]
},
plugins: [
new ExtractTextPlugin('[name]'),
],
externals: {
'lodash': 'lodash',
'jquery': 'jQuery',
'sir-trevor-js': 'SirTrevor',
'i18n': 'i18n',
'highlightjs': 'hljs',
'ckeditor': 'CKEDITOR'
}
}; | var webpack = require('webpack')
, glob = require('glob').sync
, ExtractTextPlugin = require('extract-text-webpack-plugin');
// Find all the css files but sort the common ones first
var cssFiles = glob('./src/common/**/*.css').concat(glob('./src/!(common)/**/*.css'));
module.exports = {
entry: {
'sir-trevor-blocks.js' : './src/entry.js',
'sir-trevor-blocks.css' : cssFiles
},
output: {
path: __dirname,
filename: '[name]'
},
module: {
loaders: [
{ test: /\.html$/, loader: 'html' },
{ test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') },
]
},
plugins: [
new ExtractTextPlugin('[name]'),
],
externals: {
'lodash': '_',
'jquery': 'jQuery',
'sir-trevor-js': 'SirTrevor',
'i18n': 'i18n',
'highlightjs': 'hljs',
'ckeditor': 'CKEDITOR'
}
}; | Fix webpack lodash external require | Fix webpack lodash external require
| JavaScript | mit | Upplication/sir-trevor-blocks,Upplication/sir-trevor-blocks |
d2eeb477b2925e6e83e63f75b497cc2b24d5e9d5 | webpack.config.js | webpack.config.js | const path = require('path')
module.exports = {
context: __dirname,
entry: './js/ClientApp.js',
devtool: 'source-map',
output: {
path: path.join(__dirname, '/public'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.json']
},
stats: {
colors: true,
reasons: true,
chunks: false
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader'
}
]
}
} | const path = require('path')
module.exports = {
context: __dirname,
entry: './js/ClientApp.js',
devtool: 'source-map',
output: {
path: path.join(__dirname, '/public'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.json']
},
stats: {
colors: true,
reasons: true,
chunks: false
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
url: false
}
}
]
}
]
}
} | Add style to Webpack rules. | Add style to Webpack rules.
| JavaScript | mit | sheamunion/fem_intro_react_code_along,sheamunion/fem_intro_react_code_along |
e1495b4a57c88e50ad1cb817372502f59c51b596 | lib/MultiSelection/OptionsListWrapper.js | lib/MultiSelection/OptionsListWrapper.js | import React from 'react';
import PropTypes from 'prop-types';
import Popper from '../Popper';
const OptionsListWrapper = React.forwardRef(({
useLegacy,
children,
controlRef,
isOpen,
renderToOverlay,
menuPropGetter,
modifiers,
...props
}, ref) => {
if (useLegacy) {
return <div {...menuPropGetter()} {...props} ref={ref} hidden={!isOpen}>{children}</div>;
}
const {
overlayRef,
...menuRest
} = menuPropGetter({ ref, refKey: 'overlayRef' });
let portal;
if (renderToOverlay) {
portal = document.getElementById('OverlayContainer');
}
return (
<Popper
anchorRef={controlRef}
overlayProps={{ ...menuRest, ...props }}
overlayRef={overlayRef}
isOpen={isOpen}
portal={portal}
placement="bottom-start"
modifiers={modifiers}
hideIfClosed
>
{children}
</Popper>
);
});
OptionsListWrapper.displayName = 'OptionsListWrapper';
OptionsListWrapper.propTypes = {
children: PropTypes.node,
controlRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
isOpen: PropTypes.bool,
menuPropGetter: PropTypes.func,
modifiers: PropTypes.object,
renderToOverlay: PropTypes.bool,
useLegacy: PropTypes.bool,
};
export default OptionsListWrapper;
| import React from 'react';
import PropTypes from 'prop-types';
import Popper from '../Popper';
const OptionsListWrapper = React.forwardRef(({
useLegacy,
children,
controlRef,
isOpen,
renderToOverlay,
menuPropGetter,
modifiers,
...props
}, ref) => {
if (useLegacy) {
return <div {...menuPropGetter({ ref })} {...props} hidden={!isOpen}>{children}</div>;
}
const {
overlayRef,
...menuRest
} = menuPropGetter({ ref, refKey: 'overlayRef' });
let portal;
if (renderToOverlay) {
portal = document.getElementById('OverlayContainer');
}
return (
<Popper
anchorRef={controlRef}
overlayProps={{ ...menuRest, ...props }}
overlayRef={overlayRef}
isOpen={isOpen}
portal={portal}
placement="bottom-start"
modifiers={modifiers}
hideIfClosed
>
{children}
</Popper>
);
});
OptionsListWrapper.displayName = 'OptionsListWrapper';
OptionsListWrapper.propTypes = {
children: PropTypes.node,
controlRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
isOpen: PropTypes.bool,
menuPropGetter: PropTypes.func,
modifiers: PropTypes.object,
renderToOverlay: PropTypes.bool,
useLegacy: PropTypes.bool,
};
export default OptionsListWrapper;
| Fix ref on downshift element | Fix ref on downshift element
| JavaScript | apache-2.0 | folio-org/stripes-components,folio-org/stripes-components |
3b4ee7102882f6e629828ac1e3e44d8f343d4012 | src/features/home/redux/initialState.js | src/features/home/redux/initialState.js | const initialState = {
count: 0,
redditReactjsList: [],
// navTreeData: null,
// projectData: null,
elementById: {},
fileContentById: {},
features: null,
projectDataNeedReload: false,
projectFileChanged: false,
fetchProjectDataPending: false,
fetchProjectDataError: null,
fetchFileContentPending: false,
fetchFileContentError: null,
demoAlertVisible: true,
};
export default initialState;
| const initialState = {
count: 0,
redditReactjsList: [],
elementById: {},
fileContentById: {},
features: null,
projectDataNeedReload: false,
projectFileChanged: false,
fetchProjectDataPending: false,
fetchProjectDataError: null,
fetchFileContentPending: false,
fetchFileContentError: null,
demoAlertVisible: false,
};
export default initialState;
| Hide demo alert by default. | Hide demo alert by default.
| JavaScript | mit | supnate/rekit-portal,supnate/rekit-portal |
35c3457c31087a85103c9729279343775511c7e4 | packages/lesswrong/lib/reactRouterWrapper.js | packages/lesswrong/lib/reactRouterWrapper.js | /*import * as reactRouter3 from 'react-router';
export const Link = reactRouter3.Link;
export const withRouter = reactRouter3.withRouter;*/
import React from 'react';
import * as reactRouter from 'react-router';
import * as reactRouterDom from 'react-router-dom';
import { parseQuery } from './routeUtil'
import qs from 'qs'
export const withRouter = (WrappedComponent) => {
const WithRouterWrapper = (props) => {
return <WrappedComponent
routes={[]}
location={{pathname:""}}
router={{location: {query:"", pathname:""}}}
{...props}
/>
}
return reactRouter.withRouter(WithRouterWrapper);
}
export const Link = (props) => {
if (!(typeof props.to === "string" || typeof props.to === "function")) {
// eslint-disable-next-line no-console
console.error("Props 'to' for Link components only accepts strings or functions, passed type: ", typeof props.to)
return <span>Broken Link</span>
}
return <reactRouterDom.Link {...props}/>
}
export const QueryLink = reactRouter.withRouter(({query, location, staticContext, merge=false, ...rest}) => {
// Merge determines whether we do a shallow merge with the existing query parameters, or replace them completely
const newSearchString = merge ? qs.stringify({...parseQuery(location), ...query}) : qs.stringify(query)
return <reactRouterDom.Link
{...rest}
to={{search: newSearchString}}
/>
}) | /*import * as reactRouter3 from 'react-router';
export const Link = reactRouter3.Link;
export const withRouter = reactRouter3.withRouter;*/
import React from 'react';
import * as reactRouter from 'react-router';
import * as reactRouterDom from 'react-router-dom';
import { parseQuery } from './routeUtil'
import qs from 'qs'
export const withRouter = (WrappedComponent) => {
const WithRouterWrapper = (props) => {
return <WrappedComponent
routes={[]}
location={{pathname:""}}
router={{location: {query:"", pathname:""}}}
{...props}
/>
}
return reactRouter.withRouter(WithRouterWrapper);
}
export const Link = (props) => {
if (!(typeof props.to === "string" || typeof props.to === "object")) {
// eslint-disable-next-line no-console
console.error("Props 'to' for Link components only accepts strings or objects, passed type: ", typeof props.to)
return <span>Broken Link</span>
}
return <reactRouterDom.Link {...props}/>
}
export const QueryLink = reactRouter.withRouter(({query, location, staticContext, merge=false, ...rest}) => {
// Merge determines whether we do a shallow merge with the existing query parameters, or replace them completely
const newSearchString = merge ? qs.stringify({...parseQuery(location), ...query}) : qs.stringify(query)
return <reactRouterDom.Link
{...rest}
to={{search: newSearchString}}
/>
}) | Fix dumb bug in link-props handling | Fix dumb bug in link-props handling
| JavaScript | mit | Discordius/Telescope,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Lesswrong2 |
0e1e23a2754c56869c9abf1ec058f69ac047905b | FrontEndCreator/questions.js | FrontEndCreator/questions.js | //must have a blank option one for question of type dropdown
standard('qTypes',["","Drop Down", "Multidrop-down", "Number Fillin", "Essay", "Code"]);
standard('qTypes2',["","dropdowns", "multidropdowns", "numfillins", "essays", "codes"]);
standard('correct',["Correct","Incorrect"]);
standard('incorrect',["Incorrect","Correct"]);
quiz([
question("dropdown","Type of Question:",choices['qTypes'],'Choose a type...',choices['qTypes2']),
question("essay","Question Text:",3,30,'Your text here...'),
questionSet("dropdowns multidropdowns",[
question("essay","Placeholder Text:",3,30,'Your text here...'),
question("multiquestion","",[
question("essay","Answer Choice 1:",3,30,'Your text here...'),
question("dropdown","",choices['correct'])
]),
question("multiquestion","",[
question("essay","Answer Choice 2:",3,30,'Your text here...'),
question("dropdown","",choices['incorrect'])
]),
question("multiquestion","",[
question("essay","Answer Choice 3:",3,30,'Your text here...'),
question("dropdown","",choices['incorrect'])
])
]),
questionSet("codes",[
question("essay","Base Code:",3,30,'Your base code here...')
]),
questionSet("numfillins essays",[
question("essay","Placeholder Text:",3,30,'Your placeholder text here...')
])
]);
| var config = {
'.chosen-select' : {},
};
for (var selector in config) {
$(selector).chosen(config[selector]);
}
for(var k = 0; k < showHideList.length; k++){
// alert(showHide);
var showHide=showHideList[k];
for(var i = 0; i < showHide.length; i++){
// alert(showHide[i]);
if(showHide[i].length>0)
$("."+showHide[i]).hide();
}
}
function SUBMIT_ONE_QUIZ(quiz){
var i = 0;
var allSend = "";
$(quiz).find(".question").each(function(){
if(!$(this).hasClass("nonquestion")){
if(i>0)
allSend+=",\n";
var val = $(this).val();
if(val==null){
val = "No Answer";
}
if(val.length < 1){
val = "No Answer";
}
//BTW we will escape the val of each answer so that students can't mess server parsing up
allSend+=("{q"+i+": "+val+"}");
i++;
}
});
alert(allSend);
}
/*Will send all quizes if need be
$("#sendAll").on("click",function(){
var i = 0;
$(".quiz").find(".question").each(function(){
var val = $(this).val();
if(val==null){
val = "No Answer";
}
if(val.length < 1){
val = "No Answer";
}
alert("q"+i+": "+val);
i++;
});
});
*/
| Update methods to send object params | Update methods to send object params | JavaScript | mit | stephenjoro/QuizEngine |
618bef5d2607cf6bc854c94fcea5095f31844d71 | preset/index.js | preset/index.js | /* eslint-env commonjs */
/* eslint-disable global-require */
module.exports = function buildPreset () {
return {
presets: [
require('babel-preset-env').default(null, {
targets: {
browsers: ['last 2 versions', 'ie 11'],
node: '6.8',
},
}),
require('babel-preset-react'),
],
plugins: [
require('babel-plugin-transform-object-rest-spread'),
require('babel-plugin-transform-class-properties'),
require('babel-plugin-transform-export-extensions'),
],
};
};
| /* eslint-env commonjs */
/* eslint-disable global-require */
module.exports = function buildPreset () {
return {
presets: [
require('babel-preset-env').default(null, {
targets: {
browsers: ['last 2 versions', 'ie 11'],
node: '8.9.4',
},
}),
require('babel-preset-react'),
],
plugins: [
require('babel-plugin-transform-object-rest-spread'),
require('babel-plugin-transform-class-properties'),
require('babel-plugin-transform-export-extensions'),
],
};
};
| Update node version in babel preset | Update node version in babel preset
| JavaScript | bsd-3-clause | salesforce/design-system-react,salesforce/design-system-react,salesforce/design-system-react |
b56a1cc01d007d1221c3ec5ac66cbd2fc50fc601 | public/index.js | public/index.js | import restate from 'regular-state';
import { Component } from 'nek-ui';
import App from './modules/app';
import Home from './modules/home';
import Detail from './modules/detail';
import Setting from './modules/setting';
const stateman = restate({ Component });
stateman
.state('app', App, '')
.state('app.home', Home, '')
.state('app.detail', Detail, 'detail')
.state('app.setting', Setting, 'setting')
.on('notfound', () => {
this.go('app.home', { replace: true });
})
.start({ html5: false, root: '/', prefix: '!' });
| import restate from 'regular-state';
import { Component } from 'nek-ui';
import App from './modules/app';
import Home from './modules/home';
import Detail from './modules/detail';
import Setting from './modules/setting';
const stateman = restate({ Component });
stateman
.state('app', App, '')
.state('app.home', Home, '')
.state('app.detail', Detail, 'detail')
.state('app.setting', Setting, 'setting')
.on('notfound', () => {
stateman.go('app.home', { replace: true });
})
.start({ html5: false, root: '/', prefix: '!' });
| Fix <this> is not valid | Fix <this> is not valid
| JavaScript | mit | kaola-fed/nek-server,kaola-fed/nek-server |
fa48474a1860ab76a38cb0de737e48262dcd1bef | api/routes/auth.js | api/routes/auth.js | const url = require('url');
const express = require('express');
const router = express.Router();
module.exports = (app, auth) => {
router.post('/', auth.authenticate('saml', {
failureFlash: true,
failureRedirect: app.get('configureUrl'),
}), (req, res) => {
const arns = req.user['https://aws.amazon.com/SAML/Attributes/Role'].split(',');
/* eslint-disable no-param-reassign */
req.session.passport.samlResponse = req.body.SAMLResponse;
req.session.passport.roleArn = arns[0];
req.session.passport.principalArn = arns[1];
req.session.passport.accountId = arns[0].split(':')[4]; // eslint-disable-line rapid7/static-magic-numbers
/* eslint-enable no-param-reassign */
let frontend = process.env.ELECTRON_START_URL || app.get('baseUrl');
frontend = new url.URL(frontend);
frontend.searchParams.set('auth', 'true');
res.redirect(frontend);
});
return router;
};
| const url = require('url');
const express = require('express');
const router = express.Router();
module.exports = (app, auth) => {
router.post('/', auth.authenticate('saml', {
failureFlash: true,
failureRedirect: app.get('configureUrl'),
}), (req, res) => {
roles = req.user['https://aws.amazon.com/SAML/Attributes/Role']
if (!Array.isArray(roles)) {
roles = [roles]
}
const arns = roles[0].split(',');
/* eslint-disable no-param-reassign */
req.session.passport.samlResponse = req.body.SAMLResponse;
req.session.passport.roleArn = arns[0];
req.session.passport.principalArn = arns[1];
req.session.passport.accountId = arns[0].split(':')[4]; // eslint-disable-line rapid7/static-magic-numbers
/* eslint-enable no-param-reassign */
let frontend = process.env.ELECTRON_START_URL || app.get('baseUrl');
frontend = new url.URL(frontend);
frontend.searchParams.set('auth', 'true');
res.redirect(frontend);
});
return router;
};
| Add support for multiple role assertions | Add support for multiple role assertions
The `https://aws.amazon.com/SAML/Attributes/Role` attribute supports
single or multiple values. This fixes Awsaml to work when a
multiple-value attribute is passed.
Currently, the first role is always used. Support for selecting from
the roles may be added later.
GH-105
| JavaScript | mit | rapid7/awsaml,rapid7/awsaml,rapid7/awsaml |
37822557c035ca41a6e9243f77d03a69351fc65c | examples/simple.js | examples/simple.js | var jerk = require( '../lib/jerk' ), sys=require('sys');
var options =
{ server: 'localhost'
, port: 6667
, nick: 'Bot9121'
, channels: [ '#jerkbot' ]
};
jerk( function( j ) {
j.watch_for( 'soup', function( message ) {
message.say( message.user + ': soup is good food!' )
});
j.watch_for( /^(.+) are silly$/, function( message ) {
message.say( message.user + ': ' + message.match_data[1] + ' are NOT SILLY. Don\'t joke!' )
});
j.user_join(function(message) {
message.say(message.user + ": Hey, welcome!");
});
j.user_leave(function(message) {
sys.puts("User: " + message.user + " has left");
});
}).connect( options );
| var jerk = require( '../lib/jerk' ), util = require('util');
var options =
{ server: 'localhost'
, port: 6667
, nick: 'Bot9121'
, channels: [ '#jerkbot' ]
};
jerk( function( j ) {
j.watch_for( 'soup', function( message ) {
message.say( message.user + ': soup is good food!' )
});
j.watch_for( /^(.+) are silly$/, function( message ) {
message.say( message.user + ': ' + message.match_data[1] + ' are NOT SILLY. Don\'t joke!' )
});
j.user_join(function(message) {
message.say(message.user + ": Hey, welcome!");
});
j.user_leave(function(message) {
util.puts("User: " + message.user + " has left");
});
}).connect( options );
| Use util instead of sys in example. | Use util instead of sys in example.
Make sure the example Jerk script continues to work in future node.js
releases. The node.js `sys` library has been a pointer to `util` since
0.3 and has now been removed completely in the node.js development
branch.
| JavaScript | unlicense | gf3/Jerk |
20fbda8f219d58a64380841ddd972e59b0eb416e | app/scripts/app.js | app/scripts/app.js | 'use strict'
angular
.module('serinaApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngMaterial'
])
.config(function ($routeProvider) {
$routeProvider
.when('/hub', {
templateUrl: 'views/hub/hub.html',
controller: 'HubCtrl'
})
.when('/lang/:lang', {
templateUrl: 'views/lang/lang.html',
controller: 'LangCtrl'
})
.when('/lang/:lang/:group*', {
templateUrl: 'views/lang/lang.html',
controller: 'LangCtrl'
})
.otherwise({
redirectTo: '/hub'
})
})
.run(function ($rootScope, $mdSidenav) {
$rootScope.endPoint = 'http://localhost:3000/api'
$rootScope.toggleLeft = buildToggler('left')
function buildToggler (componentId) {
return function () {
$mdSidenav(componentId).toggle()
}
}
window.i18next.use(window.i18nextXHRBackend)
window.i18next.init({
debug: true,
lng: 'fr', // If not given, i18n will detect the browser language.
fallbackLng: '', // Default is dev
backend: {
loadPath: '../locales/{{lng}}/{{ns}}.json'
},
useCookie: false,
useLocalStorage: false
}, function (err, t) {
console.log('resources loaded')
})
})
| 'use strict'
angular
.module('serinaApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngMaterial'
])
.config(function ($routeProvider) {
$routeProvider
.when('/hub', {
templateUrl: 'views/hub/hub.html',
controller: 'HubCtrl'
})
.when('/lang/:lang', {
templateUrl: 'views/lang/lang.html',
controller: 'LangCtrl'
})
.when('/lang/:lang/:group*', {
templateUrl: 'views/lang/lang.html',
controller: 'LangCtrl'
})
.otherwise({
redirectTo: '/hub'
})
})
.run(function ($rootScope, $mdSidenav) {
$rootScope.endPoint = 'http://localhost:3000/api'
$rootScope.toggleLeft = buildToggler('left')
function buildToggler (componentId) {
return function () {
$mdSidenav(componentId).toggle()
}
}
window.i18next.use(window.i18nextXHRBackend)
window.i18next.init({
debug: true,
lng: 'en', // If not given, i18n will detect the browser language.
fallbackLng: '', // Default is dev
backend: {
loadPath: '../locales/{{lng}}/{{ns}}.json'
},
useCookie: false,
useLocalStorage: false
}, function (err, t) {
console.log('resources loaded')
})
})
| Change default language : en | Change default language : en
| JavaScript | mit | foxdog05000/serina,foxdog05000/serina |
c671f90b3877273d18ba22351e1e8b9a63a925c3 | shp/concat.js | shp/concat.js | export default function(a, b) {
var ab = new a.constructor(a.length + b.length);
ab.set(a, 0);
ab.set(b, a.length);
return ab;
}
| export default function(a, b) {
var ab = new Uint8Array(a.length + b.length);
ab.set(a, 0);
ab.set(b, a.length);
return ab;
}
| Fix for older versions of Node. | Fix for older versions of Node.
Older versions of Node had a conflicting implementation of buffer.set.
| JavaScript | bsd-3-clause | mbostock/shapefile |
1dfde5055467da45665db268a68e72866aef60e2 | lib/networking/ws/BaseSocket.js | lib/networking/ws/BaseSocket.js | "use strict";
const WebSocket = require("ws");
const Constants = require("../../Constants");
const heartbeat = new WeakMap();
class BaseSocket extends WebSocket {
constructor(url) {
super(url);
this.readyState = Constants.ReadyState.CONNECTING;
this.on("open", () => this.readyState = Constants.ReadyState.OPEN);
const close = () => {
heartbeat.delete(this);
this.readyState = Constants.ReadyState.CLOSED;
};
this.on("close", close);
this.on("error", close);
}
get connected() {
return this.readyState == Constants.ReadyState.OPEN;
}
get connecting() {
return this.readyState == Constants.ReadyState.CONNECTING;
}
send(op, data) {
let m = {op: op, d: data};
try {
super.send(JSON.stringify(m));
} catch (e) { console.error(e.stack); }
}
setHeartbeat(opcode, msec) {
if (!this.connected)
return;
heartbeat.set(this, setInterval(() => {
if (!this.connected)
return this.close();
this.send(opcode, new Date().getTime());
}, msec));
}
}
module.exports = BaseSocket;
| "use strict";
const WebSocket = require("ws");
const Constants = require("../../Constants");
const heartbeat = new WeakMap();
class BaseSocket extends WebSocket {
constructor(url) {
super(url);
this.readyState = Constants.ReadyState.CONNECTING;
this.on("open", () => this.readyState = Constants.ReadyState.OPEN);
const close = () => {
this.unsetHeartbeat();
this.readyState = Constants.ReadyState.CLOSED;
};
this.on("close", close);
this.on("error", close);
}
get connected() {
return this.readyState == Constants.ReadyState.OPEN;
}
get connecting() {
return this.readyState == Constants.ReadyState.CONNECTING;
}
send(op, data) {
let m = {op: op, d: data};
try {
super.send(JSON.stringify(m));
} catch (e) { console.error(e.stack); }
}
setHeartbeat(opcode, msec) {
if (!this.connected)
return;
heartbeat.set(this, setInterval(() => {
if (!this.connected)
return this.close();
this.send(opcode, new Date().getTime());
}, msec));
}
unsetHeartbeat() {
var handle = heartbeat.get(this);
if (handle !== undefined) clearInterval(handle);
heartbeat.delete(this);
}
close() {
super.close();
this.unsetHeartbeat();
// release websocket resources without waiting for close frame from Discord
if (this._closeTimer && this._closeTimer._onTimeout)
this._closeTimer._onTimeout();
clearTimeout(this._closeTimer);
}
}
module.exports = BaseSocket;
| Fix heartbeat sender timer handle cleanup | Fix heartbeat sender timer handle cleanup
| JavaScript | bsd-2-clause | qeled/discordie |
e1c49c2c2c1e8e8661a079b6e7acd598bd6123d3 | pliers-npm-security-check.js | pliers-npm-security-check.js | var fs = require('fs')
, request = require('request')
module.exports = function (pliers) {
pliers('npmSecurityCheck', function (done) {
fs.createReadStream('./npm-shrinkwrap.json').pipe(
request.post('https://nodesecurity.io/validate/shrinkwrap', function (error, res) {
if (error) done(new Error('Problem contacting nodesecurity.io web service'))
if (JSON.parse(res.body).length !== 0) {
pliers.logger.error('NPM packages with security warnings found')
JSON.parse(res.body).forEach(function (module) {
pliers.logger.error('module:', module.dependencyOf.join(' -> '), '->', module.module + '@' + module.version
, 'https://nodesecurity.io/advisories/' + module.advisory.url)
})
}
}))
})
}
| var fs = require('fs')
, request = require('request')
module.exports = function (pliers, name) {
pliers(name || 'npmSecurityCheck', function (done) {
fs.createReadStream('./npm-shrinkwrap.json').pipe(
request.post('https://nodesecurity.io/validate/shrinkwrap', function (error, res) {
if (error) done(new Error('Problem contacting nodesecurity.io web service'))
if (JSON.parse(res.body).length !== 0) {
pliers.logger.error('NPM packages with security warnings found')
JSON.parse(res.body).forEach(function (module) {
pliers.logger.error('module:', module.dependencyOf.join(' -> '), '->', module.module + '@' + module.version
, 'https://nodesecurity.io/advisories/' + module.advisory.url)
})
}
}))
})
}
| Add task name override functionality | Add task name override functionality
| JavaScript | bsd-3-clause | pliersjs/pliers-npm-security-check |
8031a913ef64945e15d6cd4e06c91dfbfa16e27c | routes/trips.js | routes/trips.js | var express = require('express');
var router = express.Router();
var trip = require('../lib/trip')
router.post('/', function(req, res, next) {
var trip_path = trip.generate_trip(req.body.startPoint, req.body.endPoint);
res.send(trip_path);
});
| var express = require('express');
var router = express.Router();
var trip = require('../lib/trip')
router.post('/', function(req, res, next) {
var trip_path = trip.generate_trip(req.body.startPoint, req.body.endPoint);
res.send(trip_path);
});
module.exports = router;
| Fix trip router (forget to export module) | Fix trip router (forget to export module)
| JavaScript | mit | Ecotaco/bumblebee-bot,Ecotaco/bumblebee-bot |
42a81f023f954e4eb01f5c0b32e3575dc22d7654 | routes/users.js | routes/users.js | var
express = require('express'),
router = express.Router();
router.get('/', function (req, res, next) {
res.json(["users"]);
return next();
});
module.exports = router;
| var
express = require('express'),
router = express.Router();
// GET /users
router.get('/', function (req, res, next) {
res.json(["users"]);
return next();
});
// GET /users/:id
router.get('/:id', function (req, res, next) {
res.json({id: req.params.id, name: "John Doe"});
return next();
})
module.exports = router;
| Add simple sample for user router | Add simple sample for user router
| JavaScript | mit | givery-technology/bloom-backend |
7e5e14847e2232fd89e2dcd18cce2c16b05e88fc | app/navbar/navbar.js | app/navbar/navbar.js | angular.module('h54sNavbar', ['sasAdapter', 'h54sDebugWindow'])
.controller('NavbarCtrl', ['$scope', 'sasAdapter', '$rootScope', '$sce', function($scope, sasAdapter, $rootScope, $sce) {
$scope.openDebugWindow = function() {
$rootScope.showDebugWindow = true;
};
$scope.toggleDebugging = function() {
sasAdapter.toggleDebugMode();
};
$scope.debug = sasAdapter.isDebugMode();
sasAdapter.onRemoteConfigUpdate(function() {
$scope.debug = sasAdapter.isDebugMode();
});
}]);
| angular.module('h54sNavbar', ['sasAdapter', 'h54sDebugWindow'])
.controller('NavbarCtrl', ['$scope', 'sasAdapter', '$rootScope', '$sce', function($scope, sasAdapter, $rootScope, $sce) {
$scope.openDebugWindow = function() {
$rootScope.showDebugWindow = true;
};
$scope.toggleDebugging = function() {
sasAdapter.toggleDebugMode();
};
$scope.debug = sasAdapter.isDebugMode();
sasAdapter.onRemoteConfigUpdate(function() {
$scope.$apply(function() {
$scope.debug = sasAdapter.isDebugMode();
});
});
}]);
| Debug mode not set sometimes issue fixed | Debug mode not set sometimes issue fixed
| JavaScript | mit | Boemska/sas-hot-editor,Boemska/sas-hot-editor |
bcad6341b9d6bf85712de73bbe8e19990d174633 | sampleConfig.js | sampleConfig.js | var global = {
host: 'http://subdomain.yourdomain.com',
port: 8461,
secretUrlSuffix: 'putSomeAlphanumericSecretCharsHere'
};
var projects = [
{
repo: {
owner: 'yourbitbucketusername',
slug: 'your-bitbucket-source-repo-name',
sshPrivKeyPath: '/home/youruser/.ssh/id_rsa'
},
dest: {
host: 'yourstaticwebhost.com',
username: 'yourusername',
password: 'yourpassword',
path: '/home/youruser/html_dest/'
}
}
];
module.exports = {
global: global,
projects: projects
};
| var global = {
host: 'http://subdomain.yourdomain.com',
port: 8461,
secretUrlSuffix: 'putSomeAlphanumericSecretCharsHere'
};
var projects = [
{
repo: {
owner: 'yourbitbucketusername',
slug: 'your-bitbucket-private-repo-name',
url: 'git@bitbucket.org:yourbitbucketusername/your-bitbucket-private-repo-name.git',
sshPrivKeyPath: '/home/youruser/.ssh/id_rsa'
},
dest: {
host: 'yourstaticwebhost.com',
username: 'yourusername',
password: 'yourpassword',
path: '/home/youruser/html_dest/'
}
},
{
repo: {
owner: 'yourbitbucketusername',
slug: 'your-bitbucket-public-repo-name',
url: 'git@bitbucket.org:yourbitbucketusername/your-bitbucket-public-repo-name.git',
},
dest: {
host: 'yourstaticwebhost.com',
username: 'yourusername',
password: 'yourpassword',
path: '/home/youruser/html_dest/'
}
}
];
module.exports = {
global: global,
projects: projects
};
| Add a public repo example | Add a public repo example
| JavaScript | mit | mplewis/statichook |
c8d5aeca835d8ddd53c8026620561f6568d29041 | BrowserExtension/scripts/steamdb.js | BrowserExtension/scripts/steamdb.js | 'use strict';
var CurrentAppID,
GetCurrentAppID = function()
{
if( !CurrentAppID )
{
CurrentAppID = location.pathname.match( /\/([0-9]{1,6})(?:\/|$)/ );
if( CurrentAppID )
{
CurrentAppID = parseInt( CurrentAppID[ 1 ], 10 );
}
else
{
CurrentAppID = -1;
}
}
return CurrentAppID;
},
GetHomepage = function()
{
return 'https://steamdb.info/';
},
GetOption = function( items, callback )
{
if( typeof chrome !== 'undefined' )
{
chrome.storage.local.get( items, callback );
}
else if( typeof self.options.firefox !== 'undefined' )
{
for( var item in items )
{
items[ item ] = self.options.preferences[ item ];
}
callback( items );
}
},
GetLocalResource = function( res )
{
if( typeof chrome !== 'undefined' )
{
return chrome.extension.getURL( res );
}
else if( typeof self.options.firefox !== 'undefined' )
{
return self.options[ res ];
}
return res;
};
| 'use strict';
var CurrentAppID,
GetCurrentAppID = function()
{
if( !CurrentAppID )
{
CurrentAppID = location.pathname.match( /\/(app|sub)\/([0-9]{1,7})/ );
if( CurrentAppID )
{
CurrentAppID = parseInt( CurrentAppID[ 1 ], 10 );
}
else
{
CurrentAppID = -1;
}
}
return CurrentAppID;
},
GetHomepage = function()
{
return 'https://steamdb.info/';
},
GetOption = function( items, callback )
{
if( typeof chrome !== 'undefined' )
{
chrome.storage.local.get( items, callback );
}
else if( typeof self.options.firefox !== 'undefined' )
{
for( var item in items )
{
items[ item ] = self.options.preferences[ item ];
}
callback( items );
}
},
GetLocalResource = function( res )
{
if( typeof chrome !== 'undefined' )
{
return chrome.extension.getURL( res );
}
else if( typeof self.options.firefox !== 'undefined' )
{
return self.options[ res ];
}
return res;
};
| Improve regex for getting appid | Improve regex for getting appid
| JavaScript | bsd-3-clause | GoeGaming/SteamDatabase,i3ongmeester/SteamDatabase,GoeGaming/SteamDatabase,SteamDatabase/SteamDatabase,SteamDatabase/SteamDatabase,i3ongmeester/SteamDatabase,i3ongmeester/SteamDatabase,GoeGaming/SteamDatabase,SteamDatabase/SteamDatabase |
a72cc8137b0159b1d0246eb0e5aecf338cbd19f0 | input/_relation.js | input/_relation.js | 'use strict';
var Db = require('dbjs')
, relation = module.exports = require('dbjs/lib/_relation');
require('./base');
relation.set('toDOMInputBox', function (document/*, options*/) {
var box, options = arguments[1];
box = this.ns.toDOMInputBox(document, options);
box.set(this.objectValue);
box.setAttribute('name', this._id_);
if (this.required && (!options || (options.type !== 'checkbox'))) {
box.setAttribute('required', true);
}
this.on('change', function () { box.set(this.objectValue); });
return box;
});
relation.set('toDOMInput', Db.Base.prototype.toDOMInput);
relation.get('fieldHint').ns = Db.String;
relation.set('DOMId', function () {
return this._id_.replace(/:/g, '-');
});
| 'use strict';
var Db = require('dbjs')
, relation = module.exports = require('dbjs/lib/_relation');
require('./base');
relation.set('toDOMInputBox', function (document/*, options*/) {
var box, options = Object(arguments[1]);
box = this.ns.toDOMInputBox(document, options);
box.set(this.objectValue);
box.setAttribute('name', this._id_);
if (this.required && ((options.type !== 'checkbox') && !options.required)) {
box.setAttribute('required', true);
}
this.on('change', function () { box.set(this.objectValue); });
return box;
});
relation.set('toDOMInput', Db.Base.prototype.toDOMInput);
relation.get('fieldHint').ns = Db.String;
relation.set('DOMId', function () {
return this._id_.replace(/:/g, '-');
});
| Allow to override 'required' value | Allow to override 'required' value
| JavaScript | mit | medikoo/dbjs-dom |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.