commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
a27733f1f65d5d4adf8c3ef0a87e8997bc213f65 | index.js | index.js | window.onload = function() {
sectionShow();
};
function sectionShow() {
var sectionControls = {'home_btn': 'home', 'about_btn': 'about', 'projects_btn': 'projects', 'blog_btn': 'blog'}
document.getElementById('menu').addEventListener('click', function(event) {
event.preventDefault();
document.getElementById(sectionControls[event.target.id]).style.display = 'inline';
});
};
| window.onload = function() {
sectionShow();
};
function sectionShow() {
var sectionControls = {'home_btn': 'home', 'about_btn': 'about', 'projects_btn': 'projects', 'blog_btn': 'blog'}
document.getElementById('menu').addEventListener('click', function(event) {
event.preventDefault();
hideSections(sectionControls);
document.getElementById(sectionControls[event.target.id]).style.display = 'inline';
});
};
function hideSections(sections) {
for (i in sections) {
document.getElementById(sections[i]).style.display = 'none';
};
}; | Add hideSections function to hide unused sections | Index.js: Add hideSections function to hide unused sections
| JavaScript | mit | jorgerc85/jorgerc85.github.io,jorgerc85/jorgerc85.github.io | ---
+++
@@ -6,6 +6,13 @@
var sectionControls = {'home_btn': 'home', 'about_btn': 'about', 'projects_btn': 'projects', 'blog_btn': 'blog'}
document.getElementById('menu').addEventListener('click', function(event) {
event.preventDefault();
+ hideSections(sectionControls);
document.getElementById(sectionControls[event.target.id]).style.display = 'inline';
});
};
+
+function hideSections(sections) {
+ for (i in sections) {
+ document.getElementById(sections[i]).style.display = 'none';
+ };
+}; |
2cf11989576a18d8c8ba63d392a1ce96af13bbeb | index.js | index.js | 'use strict';
var assign = require('object-assign');
var chalk = require('chalk');
var ProgressBar = require('progress');
/**
* Progress bar download plugin
*
* @param {Object} res
* @api public
*/
module.exports = function (opts) {
return function (res, url, cb) {
opts = opts || { info: 'cyan' };
var msg = chalk[opts.info](' downloading') + ' : ' + url;
var info = chalk[opts.info](' progress') + ' : [:bar] :percent :etas';
var len = parseInt(res.headers['content-length'], 10);
var bar = new ProgressBar(info, assign({
complete: '=',
incomplete: ' ',
width: 20,
total: len
}, opts));
console.log(msg);
res.on('data', function (data) {
bar.tick(data.length);
});
res.on('end', function () {
console.log('\n');
cb();
});
};
};
| 'use strict';
var assign = require('object-assign');
var chalk = require('chalk');
var ProgressBar = require('progress');
/**
* Progress bar download plugin
*
* @param {Object} res
* @api public
*/
module.exports = function (opts) {
return function (res, url, cb) {
opts = opts || { info: 'cyan' };
var msg = chalk[opts.info](' downloading') + ' : ' + url;
var info = chalk[opts.info](' progress') + ' : [:bar] :percent :etas';
var len = parseInt(res.headers['content-length'], 10);
var bar = new ProgressBar(info, assign({
complete: '=',
incomplete: ' ',
width: 20,
total: len
}, opts));
console.log(msg);
res.on('data', function (data) {
bar.tick(data.length);
});
res.on('end', function () {
cb();
});
};
};
| Remove line ending on end | Remove line ending on end
| JavaScript | mit | kevva/download-status | ---
+++
@@ -33,7 +33,6 @@
});
res.on('end', function () {
- console.log('\n');
cb();
});
}; |
74e811027648f5157defcefc17cda3340a40bd79 | src/helpers/PropTypes.js | src/helpers/PropTypes.js | import { PropTypes } from 'react';
export function navigatorPropTypes (params) {
return PropTypes.shape({
state: PropTypes.shape({
params: PropTypes.shape(params)
}).isRequired,
navigate: PropTypes.func.isRequired
}).isRequired
} | import { PropTypes } from 'react';
export function navigatorPropTypes (params) {
return PropTypes.shape({
state: PropTypes.shape({
params: PropTypes.shape(params)
}).isRequired,
navigate: PropTypes.func.isRequired
}).isRequired
}
export function categoryPropTypes () {
return PropTypes.shape({
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired
});
}
export function songPropTypes () {
return PropTypes.shape({
id: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
lyrics: PropTypes.string.isRequired,
category_id: PropTypes.number.isRequired
});
} | Add prop type functions for songs and categories | Add prop type functions for songs and categories
| JavaScript | mit | varmais/profitti,varmais/profitti | ---
+++
@@ -8,3 +8,19 @@
navigate: PropTypes.func.isRequired
}).isRequired
}
+
+export function categoryPropTypes () {
+ return PropTypes.shape({
+ id: PropTypes.number.isRequired,
+ name: PropTypes.string.isRequired
+ });
+}
+
+export function songPropTypes () {
+ return PropTypes.shape({
+ id: PropTypes.number.isRequired,
+ title: PropTypes.string.isRequired,
+ lyrics: PropTypes.string.isRequired,
+ category_id: PropTypes.number.isRequired
+ });
+} |
9adae6c57f68b277f1520d14fb353238b63f1f9f | test/BillForward/syntax/Account-test.js | test/BillForward/syntax/Account-test.js | var testBase = require('./_test-base');
var BillForward = testBase.BillForward;
context(testBase.getContext(), function () {
describe('Account', function () {
describe('#new', function () {
context('Blank Entity', function() {
it('should succeed', function () {
var account = new BillForward.Account({});
});
});
context('Nested Entity', function() {
it('should succeed', function () {
var profile = new BillForward.Profile({});
var account = new BillForward.Account({});
account.foo = 'sup';
account.bar = 'yo';
account.profile = profile;
profile.Walpurgisnacht = 'grief seed';
console.log(account.toString());
});
});
});
});
}); | var testBase = require('./_test-base');
var BillForward = testBase.BillForward;
context(testBase.getContext(), function () {
describe('Account', function () {
describe('#new', function () {
context('Blank Entity', function() {
it('should serialize correctly', function () {
var account = new BillForward.Account({});
var testProp = 'sup';
var testVal = 'yo';
account[testProp] = testVal;
var serialized = account.serialize();
account.should.have.property(testProp).that.equals(testVal);
serialized.should.have.property(testProp).that.equals(testVal);
serialized.should.not.have.property('_client').and.
should.not.have.property('_exemptFromSerialization');
});
});
context('Nested Entity', function() {
it('should serialize correctly', function () {
var profile = new BillForward.Profile({});
var account = new BillForward.Account({});
var testProp = 'sup';
var testVal = 'yo';
account[testProp] = testVal;
account.profile = profile;
var nestedTestProp = 'Walpurgisnacht';
var nestedTestVal = 'grief seed';
profile[nestedTestProp] = nestedTestVal;
var serialized = account.serialize();
account.should.have.property(testProp).that.equals(testVal);
serialized.should.have.property(testProp).that.equals(testVal);
account.profile.should.have.property(nestedTestProp).that.equals(nestedTestVal);
serialized.profile.should.have.property(nestedTestProp).that.equals(nestedTestVal);
serialized.should.not.have.property('_client').and.
should.not.have.property('_exemptFromSerialization');
serialized.should.not.have.property('_exemptFromSerialization').and.
should.not.have.property('_client');
});
});
});
});
}); | Test serialization a bit more | Test serialization a bit more
| JavaScript | mit | billforward/bf-node,billforward/bf-node,billforward/bf-node | ---
+++
@@ -6,19 +6,49 @@
describe('Account', function () {
describe('#new', function () {
context('Blank Entity', function() {
- it('should succeed', function () {
+ it('should serialize correctly', function () {
var account = new BillForward.Account({});
+
+ var testProp = 'sup';
+ var testVal = 'yo';
+ account[testProp] = testVal;
+
+ var serialized = account.serialize();
+
+ account.should.have.property(testProp).that.equals(testVal);
+ serialized.should.have.property(testProp).that.equals(testVal);
+
+ serialized.should.not.have.property('_client').and.
+ should.not.have.property('_exemptFromSerialization');
});
});
context('Nested Entity', function() {
- it('should succeed', function () {
+ it('should serialize correctly', function () {
var profile = new BillForward.Profile({});
var account = new BillForward.Account({});
- account.foo = 'sup';
- account.bar = 'yo';
+
+ var testProp = 'sup';
+ var testVal = 'yo';
+ account[testProp] = testVal;
account.profile = profile;
- profile.Walpurgisnacht = 'grief seed';
- console.log(account.toString());
+
+ var nestedTestProp = 'Walpurgisnacht';
+ var nestedTestVal = 'grief seed';
+ profile[nestedTestProp] = nestedTestVal;
+
+ var serialized = account.serialize();
+
+ account.should.have.property(testProp).that.equals(testVal);
+ serialized.should.have.property(testProp).that.equals(testVal);
+
+ account.profile.should.have.property(nestedTestProp).that.equals(nestedTestVal);
+ serialized.profile.should.have.property(nestedTestProp).that.equals(nestedTestVal);
+
+ serialized.should.not.have.property('_client').and.
+ should.not.have.property('_exemptFromSerialization');
+
+ serialized.should.not.have.property('_exemptFromSerialization').and.
+ should.not.have.property('_client');
});
});
}); |
8568259061e5bb5f7523b82521355f7e1802e812 | client/src/boot/buildApolloClient.js | client/src/boot/buildApolloClient.js | import ApolloClient, { createNetworkInterface } from 'apollo-client';
import { printRequest } from 'apollo-client/transport/networkInterface';
import qs from 'qs';
function buildApolloClient(baseUrl) {
const networkInterface = createNetworkInterface({
uri: `${baseUrl}graphql/`,
opts: {
credentials: 'same-origin',
headers: {
accept: 'application/json',
},
},
});
const apolloClient = new ApolloClient({
shouldBatch: true,
addTypename: true,
dataIdFromObject: (o) => {
if (o.id >= 0 && o.__typename) {
return `${o.__typename}:${o.id}`;
}
return null;
},
networkInterface,
});
networkInterface.use([{
applyMiddleware(req, next) {
const entries = printRequest(req.request);
// eslint-disable-next-line no-param-reassign
req.options.headers = Object.assign(
{},
req.options.headers,
{
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
}
);
// eslint-disable-next-line no-param-reassign
req.options.body = qs.stringify(Object.assign(
{},
entries,
{ variables: JSON.stringify(entries.variables) }
));
next();
},
}]);
return apolloClient;
}
export default buildApolloClient;
| import ApolloClient, { createNetworkInterface } from 'apollo-client';
import { printRequest } from 'apollo-client/transport/networkInterface';
import qs from 'qs';
function buildApolloClient(baseUrl) {
const networkInterface = createNetworkInterface({
uri: `${baseUrl}graphql/`,
opts: {
credentials: 'same-origin',
headers: {
accept: 'application/json',
},
},
});
const apolloClient = new ApolloClient({
shouldBatch: true,
addTypename: true,
dataIdFromObject: (o) => {
if ((o.id >= 0 || o.ID >= 0) && o.__typename) {
return `${o.__typename}:${(o.id >= 0) ? o.id : o.ID}`;
}
return null;
},
networkInterface,
});
networkInterface.use([{
applyMiddleware(req, next) {
const entries = printRequest(req.request);
// eslint-disable-next-line no-param-reassign
req.options.headers = Object.assign(
{},
req.options.headers,
{
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
}
);
// eslint-disable-next-line no-param-reassign
req.options.body = qs.stringify(Object.assign(
{},
entries,
{ variables: JSON.stringify(entries.variables) }
));
next();
},
}]);
return apolloClient;
}
export default buildApolloClient;
| Fix id for scaffolded objects | Fix id for scaffolded objects
| JavaScript | bsd-3-clause | silverstripe/silverstripe-admin,silverstripe/silverstripe-admin,silverstripe/silverstripe-admin | ---
+++
@@ -16,8 +16,8 @@
shouldBatch: true,
addTypename: true,
dataIdFromObject: (o) => {
- if (o.id >= 0 && o.__typename) {
- return `${o.__typename}:${o.id}`;
+ if ((o.id >= 0 || o.ID >= 0) && o.__typename) {
+ return `${o.__typename}:${(o.id >= 0) ? o.id : o.ID}`;
}
return null;
}, |
1f9f2401118b8b59134bd238453c3ea7b8164e84 | src/Modules/Prompt/Dnn.PersonaBar.Prompt/admin/personaBar/scripts/Prompt.js | src/Modules/Prompt/Dnn.PersonaBar.Prompt/admin/personaBar/scripts/Prompt.js | define(['jquery'], function ($) {
return {
init: function (wrapper, util, params, callback) {
const vsn = "1.0.0.0";
$.ajax({
dataType: "script",
cache: true,
url: "modules/dnn.prompt/scripts/bundles/prompt-bundle.js",
success: function () {
window.dnnPrompt = new window.DnnPrompt(vsn, wrapper, util, params);
},
});
if (typeof callback === 'function') {
callback();
}
},
load: function (params, callback) {
if (typeof callback === 'function') {
callback();
}
}
};
});
| define(['jquery'], function ($) {
return {
init: function (wrapper, util, params, callback) {
const vsn = "v0.3-alpha";
$.ajax({
dataType: "script",
cache: true,
url: "modules/dnn.prompt/scripts/bundles/prompt-bundle.js",
success: function () {
window.dnnPrompt = new window.DnnPrompt(vsn, wrapper, util, params);
},
});
if (typeof callback === 'function') {
callback();
}
},
load: function (params, callback) {
if (typeof callback === 'function') {
callback();
}
}
};
});
| Change reported vsn from bogus 1.0.0.0 to v0.3-alpha | Change reported vsn from bogus 1.0.0.0 to v0.3-alpha
| JavaScript | mit | nvisionative/Dnn.Platform,RichardHowells/Dnn.Platform,mitchelsellers/Dnn.Platform,nvisionative/Dnn.Platform,bdukes/Dnn.Platform,dnnsoftware/Dnn.AdminExperience.Extensions,EPTamminga/Dnn.Platform,valadas/Dnn.Platform,EPTamminga/Dnn.Platform,robsiera/Dnn.Platform,EPTamminga/Dnn.Platform,bdukes/Dnn.Platform,robsiera/Dnn.Platform,dnnsoftware/Dnn.Platform,RichardHowells/Dnn.Platform,mitchelsellers/Dnn.Platform,RichardHowells/Dnn.Platform,valadas/Dnn.Platform,RichardHowells/Dnn.Platform,bdukes/Dnn.Platform,dnnsoftware/Dnn.Platform,dnnsoftware/Dnn.AdminExperience.Extensions,mitchelsellers/Dnn.Platform,mitchelsellers/Dnn.Platform,dnnsoftware/Dnn.Platform,mitchelsellers/Dnn.Platform,dnnsoftware/Dnn.Platform,nvisionative/Dnn.Platform,valadas/Dnn.Platform,valadas/Dnn.Platform,bdukes/Dnn.Platform,robsiera/Dnn.Platform,dnnsoftware/Dnn.AdminExperience.Extensions,valadas/Dnn.Platform,dnnsoftware/Dnn.Platform | ---
+++
@@ -1,7 +1,7 @@
define(['jquery'], function ($) {
return {
init: function (wrapper, util, params, callback) {
- const vsn = "1.0.0.0";
+ const vsn = "v0.3-alpha";
$.ajax({
dataType: "script",
cache: true, |
7924254ebd28e259d45e7790c2b5412f0ddf6c85 | public/app/project-detail/data-visualization/data-chart-controller.js | public/app/project-detail/data-visualization/data-chart-controller.js | define(function() {
var DataChartController = function($rootScope, $q, HubResource, HubSelectionService) {
var self = this
this.isLoaded = false
// Fake promise to get around ig data source
this.dataChart = HubResource.listDataPoints()
// Load data on selection change
$rootScope.$on('HubSelection', function(e, hub) {
self.dataChart = HubResource.listDataPoints({
user: 'admin',
project: 'adminProject',
hubId: hub._id,
}, function success(dataPoints, headers) {
self.isLoaded = true
})
})
}
DataChartController.$inject = ['$rootScope', '$q', 'HubResource', 'HubSelectionService']
return DataChartController
})
| define(function() {
var DataChartController = function($rootScope, $routeParams, HubResource, HubSelectionService) {
var self = this
this.isLoaded = false
// Fake promise to get around ig data source
this.dataChart = HubResource.listDataPoints()
// Load data on selection change
$rootScope.$on('HubSelection', function(e, hub) {
self.dataChart = HubResource.listDataPoints({
user: $routeParams.user,
project: $routeParams.project,
hubId: hub._id,
}, function success(dataPoints, headers) {
self.isLoaded = true
})
})
}
DataChartController.$inject = ['$rootScope', '$routeParams', 'HubResource', 'HubSelectionService']
return DataChartController
})
| Update data chart controller to use route params | Update data chart controller to use route params
| JavaScript | mit | tenevdev/idiot,tenevdev/idiot | ---
+++
@@ -1,5 +1,5 @@
define(function() {
- var DataChartController = function($rootScope, $q, HubResource, HubSelectionService) {
+ var DataChartController = function($rootScope, $routeParams, HubResource, HubSelectionService) {
var self = this
this.isLoaded = false
@@ -9,8 +9,8 @@
// Load data on selection change
$rootScope.$on('HubSelection', function(e, hub) {
self.dataChart = HubResource.listDataPoints({
- user: 'admin',
- project: 'adminProject',
+ user: $routeParams.user,
+ project: $routeParams.project,
hubId: hub._id,
}, function success(dataPoints, headers) {
self.isLoaded = true
@@ -18,7 +18,7 @@
})
}
- DataChartController.$inject = ['$rootScope', '$q', 'HubResource', 'HubSelectionService']
+ DataChartController.$inject = ['$rootScope', '$routeParams', 'HubResource', 'HubSelectionService']
return DataChartController
}) |
4a241b60ff72311188287730c087d547728bd997 | src/utils/js-hooks.js | src/utils/js-hooks.js | define([], function () {
/**
* Rockabox JSHook class, it will setup custom hooks set in the Placement js
* for Load, Init, View initial, Engagement and Click.
*
* @param {object} advert The Advert class
* @param {object} customHooks Custom hooks set within Placement js
*/
function JSHooks (advert, customHooks) {
var $this = this,
events = advert.utils.events,
hooks = [
'load',
'init',
'viewInitial',
'engagement',
'click'
];
/**
* Initializes the js hooks
*/
function init () {
for (var hook in hooks) {
var hookName = hooks[hook],
hookEvent = 'rb.' + hookName;
events.addListener(advert.getCreative(), hookEvent, customHooks[hookName]);
}
}
init();
}
return JSHooks;
});
| define([
'utils/events'
], function (Events) {
/**
* Rockabox JSHook class, it will setup custom hooks set in the Placement js
* for Load, Init, View initial, Engagement and Click.
*
* @param {object} advert The Advert class
* @param {object} customHooks Custom hooks set within Placement js
*/
function JSHooks (advert, customHooks) {
var $this = this,
events = new Events(),
hooks = [
'load',
'init',
'viewInitial',
'engagement',
'click'
];
/**
* Initializes the js hooks
*/
function init () {
for (var hook in hooks) {
var hookName = hooks[hook],
hookEvent = 'rb.' + hookName;
events.addListener(advert.getCreative(), hookEvent, customHooks[hookName]);
}
}
init();
}
return JSHooks;
});
| Remove Utils events from advert | Remove Utils events from advert
| JavaScript | mit | rockabox/Auxilium.js | ---
+++
@@ -1,4 +1,6 @@
-define([], function () {
+define([
+ 'utils/events'
+], function (Events) {
/**
* Rockabox JSHook class, it will setup custom hooks set in the Placement js
* for Load, Init, View initial, Engagement and Click.
@@ -8,7 +10,7 @@
*/
function JSHooks (advert, customHooks) {
var $this = this,
- events = advert.utils.events,
+ events = new Events(),
hooks = [
'load',
'init', |
cb357b19195bf55c03770b3078d5477080b4c9e2 | imports/ui/components/dashboard/dashboard_user_single.js | imports/ui/components/dashboard/dashboard_user_single.js | import React,{ Component } from 'react';
export default class DashboardUserSingle extends Component {
render() {
return(
<tr>
<td>{this.props.user.emails[0].address}</td>
<td>{this.props.user.username}</td>
<td>{this.props.user.profile.notif_email ? "oui" : "non"}</td>
<td>Button</td>
</tr>
);
}
}
| import React,{ Component } from 'react';
export default class DashboardUserSingle extends Component {
render() {
return(
<tr>
<td>{'emails' in this.props.user ? this.props.user.emails[0].address : "Username only"}</td>
<td>{this.props.user.username}</td>
<td>{this.props.user.profile.notif_email ? "oui" : "non"}</td>
<td>Button</td>
</tr>
);
}
}
| Check if username only in dashboard users screen | Check if username only in dashboard users screen
| JavaScript | agpl-3.0 | maz-dev/sainteJs,maz-dev/sainteJs | ---
+++
@@ -4,7 +4,7 @@
render() {
return(
<tr>
- <td>{this.props.user.emails[0].address}</td>
+ <td>{'emails' in this.props.user ? this.props.user.emails[0].address : "Username only"}</td>
<td>{this.props.user.username}</td>
<td>{this.props.user.profile.notif_email ? "oui" : "non"}</td>
<td>Button</td> |
1102bf41cb7c6f627c91d048b796a8e9f7c26f92 | lib/ember-mocha/mocha-module.js | lib/ember-mocha/mocha-module.js | import { beforeEach, afterEach, describe } from 'mocha';
import Ember from 'ember';
import { getContext } from 'ember-test-helpers';
export function createModule(Constructor, name, description, callbacks, tests, method) {
var module;
if (!tests) {
if (!callbacks) {
tests = description;
callbacks = {};
} else {
tests = callbacks;
callbacks = description;
}
module = new Constructor(name, callbacks);
} else {
module = new Constructor(name, description, callbacks);
}
function moduleBody() {
beforeEach(function() {
var self = this;
return module.setup().then(function() {
var context = getContext();
var keys = Ember.keys(context);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
self[key] = context[key];
}
});
});
afterEach(function() {
return module.teardown();
});
tests = tests || function() {};
tests();
}
if (method) {
describe[method](module.name, moduleBody);
} else {
describe(module.name, moduleBody);
}
}
export function createOnly(Constructor) {
return function(name, description, callbacks, tests) {
createModule(Constructor, name, description, callbacks, tests, "only");
};
}
export function createSkip(Constructor) {
return function(name, description, callbacks, tests) {
createModule(Constructor, name, description, callbacks, tests, "skip");
};
}
| import { beforeEach, afterEach, describe } from 'mocha';
import Ember from 'ember';
import { getContext } from 'ember-test-helpers';
export function createModule(Constructor, name, description, callbacks, tests, method) {
var module;
if (!tests) {
if (!callbacks) {
tests = description;
callbacks = {};
} else {
tests = callbacks;
callbacks = description;
}
module = new Constructor(name, callbacks);
} else {
module = new Constructor(name, description, callbacks);
}
function moduleBody() {
beforeEach(function() {
var self = this;
return module.setup().then(function() {
var context = getContext();
var keys = Object.keys(context);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
self[key] = context[key];
}
});
});
afterEach(function() {
return module.teardown();
});
tests = tests || function() {};
tests();
}
if (method) {
describe[method](module.name, moduleBody);
} else {
describe(module.name, moduleBody);
}
}
export function createOnly(Constructor) {
return function(name, description, callbacks, tests) {
createModule(Constructor, name, description, callbacks, tests, "only");
};
}
export function createSkip(Constructor) {
return function(name, description, callbacks, tests) {
createModule(Constructor, name, description, callbacks, tests, "skip");
};
}
| Remove usage of deprecated `Ember.keys` | Remove usage of deprecated `Ember.keys` | JavaScript | apache-2.0 | alexgb/ember-mocha,Robdel12/ember-mocha,emberjs/ember-mocha,switchfly/ember-mocha,cowboyd/ember-mocha,jeffreybiles/ember-mocha,emberjs/ember-mocha,SaladFork/ember-mocha,jeffreybiles/ember-mocha,jeffreybiles/ember-mocha,alexgb/ember-mocha,switchfly/ember-mocha,SaladFork/ember-mocha,switchfly/ember-mocha,Robdel12/ember-mocha,cowboyd/ember-mocha,cowboyd/ember-mocha,Robdel12/ember-mocha,alexgb/ember-mocha,SaladFork/ember-mocha | ---
+++
@@ -25,7 +25,7 @@
var self = this;
return module.setup().then(function() {
var context = getContext();
- var keys = Ember.keys(context);
+ var keys = Object.keys(context);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
self[key] = context[key]; |
b2b1d12b210f02f8d6c8e327592d58c58926535f | docs/server.js | docs/server.js | /* eslint-disable @typescript-eslint/no-var-requires */
const http = require('http');
const express = require('express');
const url = require('url');
const next = require('next');
const { pathnameToLanguage } = require('./scripts/languageHelpers');
const nextApp = next({
dev: process.env.NODE_ENV !== 'production'
});
const nextHandler = nextApp.getRequestHandler();
async function run() {
await nextApp.prepare();
const app = express();
app.use('/design', express.static('public/design'));
app.get('*', (req, res) => {
const parsedUrl = url.parse(req.url, true);
let { pathname } = parsedUrl;
const { userLanguage, canonical } = pathnameToLanguage(pathname);
pathname = canonical;
if (pathname !== '/') {
pathname = pathname.replace(/\/$/, '');
}
if (userLanguage !== 'zh') {
nextApp.render(req, res, pathname, {
userLanguage,
...parsedUrl.query
});
return;
}
nextHandler(req, res);
});
const server = http.createServer(app);
const port = parseInt(process.env.PORT, 10) || 3000;
server.listen(port, err => {
if (err) {
throw err;
}
});
}
run();
| /* eslint-disable @typescript-eslint/no-var-requires */
const http = require('http');
const express = require('express');
const url = require('url');
const next = require('next');
const { pathnameToLanguage } = require('./scripts/languageHelpers');
const nextApp = next({
dev: process.env.NODE_ENV !== 'production'
});
const nextHandler = nextApp.getRequestHandler();
async function run() {
await nextApp.prepare();
const app = express();
const rootPaths = ['components/', 'extensions/', 'guide/', '/tools'];
app.use('/design', express.static('public/design'));
app.get('*', (req, res) => {
const parsedUrl = url.parse(req.url, true);
let { pathname } = parsedUrl;
const { userLanguage, canonical } = pathnameToLanguage(pathname);
pathname = canonical;
if (pathname !== '/') {
pathname = pathname.replace(/\/$/, '');
}
if (userLanguage !== 'zh' || rootPaths.some(path => ~pathname.indexOf(path))) {
nextApp.render(req, res, pathname, {
userLanguage,
...parsedUrl.query
});
return;
}
nextHandler(req, res, parsedUrl);
});
const server = http.createServer(app);
const port = parseInt(process.env.PORT, 10) || 3000;
server.listen(port, err => {
if (err) {
throw err;
}
});
}
run();
| Fix 404 error on request page | Fix 404 error on request page
| JavaScript | mit | suitejs/suite | ---
+++
@@ -4,7 +4,6 @@
const url = require('url');
const next = require('next');
const { pathnameToLanguage } = require('./scripts/languageHelpers');
-
const nextApp = next({
dev: process.env.NODE_ENV !== 'production'
});
@@ -13,6 +12,8 @@
async function run() {
await nextApp.prepare();
const app = express();
+ const rootPaths = ['components/', 'extensions/', 'guide/', '/tools'];
+
app.use('/design', express.static('public/design'));
app.get('*', (req, res) => {
const parsedUrl = url.parse(req.url, true);
@@ -24,7 +25,7 @@
pathname = pathname.replace(/\/$/, '');
}
- if (userLanguage !== 'zh') {
+ if (userLanguage !== 'zh' || rootPaths.some(path => ~pathname.indexOf(path))) {
nextApp.render(req, res, pathname, {
userLanguage,
...parsedUrl.query
@@ -32,7 +33,7 @@
return;
}
- nextHandler(req, res);
+ nextHandler(req, res, parsedUrl);
});
const server = http.createServer(app); |
9d777cd1caf0456534a0b17bcbbd780d514edba6 | src/js/themes.js | src/js/themes.js | 'use strict';
var themeIcons = null;
var themeLink = null;
var loadTheme = function (src) {
themeLink.href = src;
};
var putIcon = (function () {
var newIcon = function () {
var div = document.createElement('div');
div.className = 'icon';
themeIcons.appendChild(div);
return div;
};
return function (color) {
var icon = newIcon();
icon.style.backgroundColor = color;
return icon;
};
}());
var installTheme = function (theme) {
var icon = putIcon(theme.icon);
icon.title = 'Change theme: ' + theme.name;
icon.addEventListener('click', loadTheme.bind(null, theme.src));
};
exports.init = function () {
themeIcons = document.getElementById('theme-icons');
themeLink = document.getElementById('theme');
var themes = require('../themes.json');
themes.reverse().forEach(installTheme);
};
| 'use strict';
var $themeIcons = null;
var $themeLink = null;
var storage = (function () {
var key = 'theme';
return {
load: function () {
return window.localStorage[key];
},
save: function (name) {
window.localStorage[key] = name;
}
};
}());
var loadTheme = function (theme) {
$themeLink.href = theme.src;
};
var putIcon = (function () {
var newIcon = function () {
var div = document.createElement('div');
div.className = 'icon';
$themeIcons.appendChild(div);
return div;
};
return function (color) {
var icon = newIcon();
icon.style.backgroundColor = color;
return icon;
};
}());
var installTheme = function (theme) {
var icon = putIcon(theme.icon);
icon.title = 'Change theme: ' + theme.name;
icon.addEventListener('click', function () {
loadTheme(theme);
storage.save(theme.name);
});
};
exports.init = function () {
$themeIcons = document.getElementById('theme-icons');
$themeLink = document.getElementById('theme');
var themes = require('../themes.json');
var themeByName = Object.create(null);
themes.reverse().forEach(function (theme) {
installTheme(theme);
themeByName[theme.name] = theme;
});
var savedTheme = storage.load();
if (savedTheme && themeByName[savedTheme]) {
loadTheme(themeByName[savedTheme]);
}
};
| Save selected theme in localStorage | Save selected theme in localStorage
| JavaScript | mit | eush77/html-formulae-app | ---
+++
@@ -1,11 +1,25 @@
'use strict';
-var themeIcons = null;
-var themeLink = null;
+var $themeIcons = null;
+var $themeLink = null;
-var loadTheme = function (src) {
- themeLink.href = src;
+var storage = (function () {
+ var key = 'theme';
+
+ return {
+ load: function () {
+ return window.localStorage[key];
+ },
+ save: function (name) {
+ window.localStorage[key] = name;
+ }
+ };
+}());
+
+
+var loadTheme = function (theme) {
+ $themeLink.href = theme.src;
};
@@ -13,7 +27,7 @@
var newIcon = function () {
var div = document.createElement('div');
div.className = 'icon';
- themeIcons.appendChild(div);
+ $themeIcons.appendChild(div);
return div;
};
@@ -28,14 +42,26 @@
var installTheme = function (theme) {
var icon = putIcon(theme.icon);
icon.title = 'Change theme: ' + theme.name;
- icon.addEventListener('click', loadTheme.bind(null, theme.src));
+ icon.addEventListener('click', function () {
+ loadTheme(theme);
+ storage.save(theme.name);
+ });
};
exports.init = function () {
- themeIcons = document.getElementById('theme-icons');
- themeLink = document.getElementById('theme');
+ $themeIcons = document.getElementById('theme-icons');
+ $themeLink = document.getElementById('theme');
var themes = require('../themes.json');
- themes.reverse().forEach(installTheme);
+ var themeByName = Object.create(null);
+ themes.reverse().forEach(function (theme) {
+ installTheme(theme);
+ themeByName[theme.name] = theme;
+ });
+
+ var savedTheme = storage.load();
+ if (savedTheme && themeByName[savedTheme]) {
+ loadTheme(themeByName[savedTheme]);
+ }
}; |
2140e2ef29ea1a33f78c6f593a08d6aae15e03d7 | tasks/bump-version.js | tasks/bump-version.js | "use strict";
var gulp = require("gulp");
var argv = require("yargs").argv;
var gutil = require("gulp-util");
var bump = require("gulp-bump");
var path = require("path");
var fs = require("fs");
var $ = require("../util.js");
module.exports = function (error, bumpType) {
var bumpParams = {
// Set version type to -t option or version (or if empty, patch)
type: argv.t || bumpType || "patch"
};
// Set version from command line
if (argv.v) {
bumpParams.version = argv.v;
}
var files = $.conf.versionFiles.reduce(function(files, file){
var filePath = path.resolve($.conf.appDir, file);
if(fs.accessSync(filePath)) {
files.push(filePath);
}
return files;
}, []);
return gulp.src(files)
.pipe(bump(bumpParams).on("error", gutil.log))
.pipe(gulp.dest($.conf.appDir));
};
| "use strict";
var gulp = require("gulp");
var argv = require("yargs").argv;
var gutil = require("gulp-util");
var bump = require("gulp-bump");
var path = require("path");
var fs = require("fs");
var $ = require("../util.js");
module.exports = function (error, bumpType) {
var bumpParams = {
// Set version type to -t option or version (or if empty, patch)
type: argv.t || bumpType || "patch"
};
// Set version from command line
if (argv.v) {
bumpParams.version = argv.v;
}
var files = $.conf.versionFiles.reduce(function(files, file){
var filePath = path.resolve($.conf.appDir, file);
if(fs.statSync(filePath)) {
files.push(filePath);
}
return files;
}, []);
return gulp.src(files)
.pipe(bump(bumpParams).on("error", gutil.log))
.pipe(gulp.dest($.conf.appDir));
};
| Change accessSync to statSync, for older nodejs versions compatibility | fix(tasks): Change accessSync to statSync, for older nodejs versions compatibility
| JavaScript | mit | klarkc/gulp-github-automator | ---
+++
@@ -21,12 +21,11 @@
var files = $.conf.versionFiles.reduce(function(files, file){
var filePath = path.resolve($.conf.appDir, file);
- if(fs.accessSync(filePath)) {
+ if(fs.statSync(filePath)) {
files.push(filePath);
}
return files;
}, []);
-
return gulp.src(files)
.pipe(bump(bumpParams).on("error", gutil.log))
.pipe(gulp.dest($.conf.appDir)); |
2273c452a2485a8d14f025bcf475c6a87db41555 | app/passport.js | app/passport.js | var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var config = require('../config.json');
passport.use(new LocalStrategy(function(username, password, done) {
var user = config.users[username];
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (user.pass !== password) {
return done(null, false, { message: 'Incorrect password.' });
}
done(null, user);
}));
// We're using very dumb serialization here because we don't really
// intend on having many users at the moment (probably just admin).
passport.serializeUser(function(user, done) {
done(null, JSON.stringify(user));
});
passport.deserializeUser(function(json, done) {
done(null, JSON.parse(json));
});
module.exports = passport;
| var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var config = require('../config.json');
passport.use(new LocalStrategy(function(username, password, done) {
var user = config.users[username];
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (user.pass !== password) {
return done(null, false, { message: 'Incorrect password.' });
}
user.name = username;
done(null, user);
}));
// We're using very dumb serialization here because we don't really
// intend on having many users at the moment (probably just admin).
passport.serializeUser(function(user, done) {
done(null, JSON.stringify(user));
});
passport.deserializeUser(function(json, done) {
done(null, JSON.parse(json));
});
module.exports = passport;
| Add user.name field to user objects. | Add user.name field to user objects.
| JavaScript | agpl-3.0 | CamiloMM/Noumena,CamiloMM/Noumena,CamiloMM/Noumena | ---
+++
@@ -12,6 +12,8 @@
if (user.pass !== password) {
return done(null, false, { message: 'Incorrect password.' });
}
+
+ user.name = username;
done(null, user);
})); |
1eb308db211b7cea88a8e524605674b01a0d1037 | src/components/AboutUs.js | src/components/AboutUs.js | // Page to create/About Us
import React from 'react';
const AboutUs = (props) => {
return (
<div>
<h1>AboutUs page</h1>
</div>
);
};
export default AboutUs; | // Page to create/About Us
import React from 'react';
import { Link } from 'react-router-dom';
import links from '../constants/links';
const AboutUs = (props) => {
return (
<div>
<h1>AboutUs page</h1>
Check us out on <a href={links.github}>Github</a>!
</div>
);
};
export default AboutUs; | Add link to github on about us page | Add link to github on about us page
| JavaScript | mit | 5-gwoap/adopt-a-family,5-gwoap/adopt-a-family | ---
+++
@@ -1,11 +1,14 @@
// Page to create/About Us
import React from 'react';
+import { Link } from 'react-router-dom';
+import links from '../constants/links';
const AboutUs = (props) => {
return (
<div>
<h1>AboutUs page</h1>
+ Check us out on <a href={links.github}>Github</a>!
</div>
);
}; |
90aa0d7147c48fd2f8ea06e4d211b8c8a3802310 | test/views/Main_spec.js | test/views/Main_spec.js | 'use babel';
let {jsdom} = require('jsdom');
global.document = jsdom('<!doctype html><html><body></body></html>');
global.window = document.defaultView;
global.navigator = window.navigator;
global.location = window.location;
describe('MainView', () => {
let React;
// let ReactDOM;
let ReactTestUtils;
before(() => {
React = require('react');
// ReactDOM = require('react-dom');
ReactTestUtils = require('react-addons-test-utils');
});
it('should be display MainView', () => {
const Main = require('../../app/views/Main');
let component = ReactTestUtils.renderIntoDocument(<Main />);
});
});
| 'use babel';
let {jsdom} = require('jsdom');
const assert = require('power-assert');
global.document = jsdom('<!doctype html><html><body></body></html>');
global.window = document.defaultView;
global.navigator = window.navigator;
global.location = window.location;
describe('MainView', () => {
let React;
let ReactDOM;
let ReactTestUtils;
before(() => {
React = require('react');
ReactDOM = require('react-dom');
ReactTestUtils = require('react-addons-test-utils');
});
it('should display MainView', () => {
const Main = require('../../app/views/Main');
let renderedComponent = ReactTestUtils.renderIntoDocument(<Main />);
let component = ReactTestUtils.findRenderedDOMComponentWithClass(renderedComponent, 'MainView');
let node = ReactDOM.findDOMNode(component);
assert(node.getAttribute('class'), 'MainView');
});
});
| Add test of main view | Add test of main view
| JavaScript | mit | MaxMEllon/comelon,MaxMEllon/comelon | ---
+++
@@ -1,6 +1,7 @@
'use babel';
let {jsdom} = require('jsdom');
+const assert = require('power-assert');
global.document = jsdom('<!doctype html><html><body></body></html>');
global.window = document.defaultView;
@@ -9,18 +10,21 @@
describe('MainView', () => {
let React;
- // let ReactDOM;
+ let ReactDOM;
let ReactTestUtils;
before(() => {
React = require('react');
- // ReactDOM = require('react-dom');
+ ReactDOM = require('react-dom');
ReactTestUtils = require('react-addons-test-utils');
});
- it('should be display MainView', () => {
+ it('should display MainView', () => {
const Main = require('../../app/views/Main');
- let component = ReactTestUtils.renderIntoDocument(<Main />);
+ let renderedComponent = ReactTestUtils.renderIntoDocument(<Main />);
+ let component = ReactTestUtils.findRenderedDOMComponentWithClass(renderedComponent, 'MainView');
+ let node = ReactDOM.findDOMNode(component);
+ assert(node.getAttribute('class'), 'MainView');
});
}); |
8e7a7dff1a0b6e9b9f5dccbf8b6dadd96ff77fc9 | test/test-creation.js | test/test-creation.js | /*global describe, it */
'use strict';
var path = require('path');
var yeoman = require('yeoman-generator');
describe('yui generator', function () {
var TMP_DIR = path.join(__dirname, 'temp');
var APP_DIR = path.join(__dirname, '../app');
it('creates expected files', function (done) {
var expected = [
'BUILD.md',
'README.md',
'Gruntfile.js',
'.editorconfig',
'.gitignore',
'.jshintrc',
'.yeti.json'
];
yeoman.test.run(APP_DIR)
.inDir(TMP_DIR)
.onEnd(function () {
yeoman.assert.file(expected);
done();
});
});
});
| /*global describe, before, it */
'use strict';
var path = require('path');
var yeoman = require('yeoman-generator');
describe('yui generator', function () {
var TMP_DIR = path.join(__dirname, 'temp');
var APP_DIR = path.join(__dirname, '../app');
before(function (done) {
yeoman.test
.run(APP_DIR)
.inDir(TMP_DIR)
.onEnd(done);
});
it('creates expected files', function () {
yeoman.assert.file([
'BUILD.md',
'README.md',
'Gruntfile.js',
'bower.json',
'package.json',
'.editorconfig',
'.gitignore',
'.jshintrc',
'.yeti.json'
]);
});
});
| Move test.run() into before() phase. | Move test.run() into before() phase.
| JavaScript | mit | zillow/generator-yui-library | ---
+++
@@ -1,4 +1,4 @@
-/*global describe, it */
+/*global describe, before, it */
'use strict';
var path = require('path');
var yeoman = require('yeoman-generator');
@@ -7,22 +7,24 @@
var TMP_DIR = path.join(__dirname, 'temp');
var APP_DIR = path.join(__dirname, '../app');
- it('creates expected files', function (done) {
- var expected = [
+ before(function (done) {
+ yeoman.test
+ .run(APP_DIR)
+ .inDir(TMP_DIR)
+ .onEnd(done);
+ });
+
+ it('creates expected files', function () {
+ yeoman.assert.file([
'BUILD.md',
'README.md',
'Gruntfile.js',
+ 'bower.json',
+ 'package.json',
'.editorconfig',
'.gitignore',
'.jshintrc',
'.yeti.json'
- ];
-
- yeoman.test.run(APP_DIR)
- .inDir(TMP_DIR)
- .onEnd(function () {
- yeoman.assert.file(expected);
- done();
- });
+ ]);
});
}); |
a9cd008ca41ec2ac01e1d90ab471de40a781a534 | tests/test_svr_bin.js | tests/test_svr_bin.js | ((req) => {
const { spawn } = req('child_process');
describe('Server Binary Test', () => {
const config = req('./fixtures/karma_single.conf.js');
before(() => {
config.files = config.files.concat([
'tests/fixtures/src/*.js',
'tests/fixtures/tests/*.js',
]);
});
it('Should run tests thru process spawn', function spawnTest(done) {
this.timeout(3000);
const pc = spawn(req.resolve('../bin/server.js'), [], {
stdio: ['pipe', 'inherit', 'pipe'],
});
const err = [];
pc.stderr.on('data', (data) => { err.push(data); });
pc.on('error', done);
pc.on('close', (code, signal) => {
if (code || (signal && signal.length) || err.length) {
done(new Error(
`Karma server exited with Code: ${code}, Signal: ${signal}
STDERR: ${err.join('')}`
));
return;
}
done();
});
pc.stdin.end(JSON.stringify(config));
});
});
})(require);
| ((req) => {
const { spawn } = req('child_process');
describe('Server Binary Test', () => {
const config = req('./fixtures/karma_single.conf.js');
before(() => {
config.files = config.files.concat([
'tests/fixtures/src/*.js',
'tests/fixtures/tests/*.js',
]);
});
it('Should run tests thru process spawn', function spawnTest(done) {
this.timeout(3000);
const pc = spawn('node', [req.resolve('../bin/server.js')], {
stdio: ['pipe', 'inherit', 'pipe'],
});
const err = [];
pc.stderr.on('data', (data) => { err.push(data); });
pc.on('error', done);
pc.on('close', (code, signal) => {
if (code || (signal && signal.length) || err.length) {
done(new Error(
`Karma server exited with Code: ${code}, Signal: ${signal}
STDERR: ${err.join('')}`
));
return;
}
done();
});
pc.stdin.end(JSON.stringify(config));
});
});
})(require);
| Use node command instead of running directly | Use node command instead of running directly
| JavaScript | mit | Forumouth/gulp-karma-runner | ---
+++
@@ -11,7 +11,7 @@
});
it('Should run tests thru process spawn', function spawnTest(done) {
this.timeout(3000);
- const pc = spawn(req.resolve('../bin/server.js'), [], {
+ const pc = spawn('node', [req.resolve('../bin/server.js')], {
stdio: ['pipe', 'inherit', 'pipe'],
});
const err = []; |
38047f6b2e55cfb1c3ca07c940bc8df4d54a0d6a | frontend/app/services/drupal-auth.js | frontend/app/services/drupal-auth.js | "use strict";
import Ember from 'ember';
import config from '../config/environment';
var csrfTokenRequest;
export default Ember.Object.extend({
init: function() {
// Since the CSRF token is used for all other backend requests, we might as
// well fetch it immediately when the service is loaded.
this.getCsrfToken();
},
getCsrfToken: function () {
// If the CSRF request was not already created, create it.
if (!csrfTokenRequest) {
csrfTokenRequest = Ember.$.ajax({
contentType: 'application/json',
dataType: 'json',
type: 'POST',
url: config.bookmeisterServer + 'api/bookmeister/user/token.json'
});
}
// Return the promise so it can be used by the caller.
return csrfTokenRequest;
}
});
| import Ember from 'ember';
import config from '../config/environment';
var csrfTokenRequest;
export default Ember.Object.extend({
getCsrfToken: function () {
// If the CSRF request was not already created, create it.
if (!csrfTokenRequest) {
csrfTokenRequest = Ember.$.ajax({
contentType: 'application/json',
dataType: 'json',
type: 'POST',
url: config.bookmeisterServer + '/api/bookmeister/user/token.json'
});
}
// Return the promise so it can be used by the caller.
return csrfTokenRequest;
}
});
| Stop initial fetch of CSRF token. | Stop initial fetch of CSRF token.
| JavaScript | isc | mikl/bookmeister,mikl/bookmeister | ---
+++
@@ -1,16 +1,9 @@
-"use strict";
import Ember from 'ember';
import config from '../config/environment';
var csrfTokenRequest;
export default Ember.Object.extend({
- init: function() {
- // Since the CSRF token is used for all other backend requests, we might as
- // well fetch it immediately when the service is loaded.
- this.getCsrfToken();
- },
-
getCsrfToken: function () {
// If the CSRF request was not already created, create it.
if (!csrfTokenRequest) {
@@ -18,12 +11,14 @@
contentType: 'application/json',
dataType: 'json',
type: 'POST',
- url: config.bookmeisterServer + 'api/bookmeister/user/token.json'
+ url: config.bookmeisterServer + '/api/bookmeister/user/token.json'
});
}
// Return the promise so it can be used by the caller.
return csrfTokenRequest;
}
+
+
});
|
2d836425e9a2057c71f81cd91ca0da5ca01cd815 | router/index.js | router/index.js | var render = require('../application/render');
var Backbone = require('backbone');
module.exports = Backbone.Router.extend({
/**
* Render the compoennt into the page content.
*/
_pageContent(component, options){
return render(component, '[data-focus="page-content"]', options);
}
});
| var render = require('../application/render');
var Backbone = require('backbone');
var ArgumentNullException = require('../exception/ArgumentNullException');
var message = require('../message');
var userHelper = require('../user');
module.exports = Backbone.Router.extend({
noRoleRoute: 'home',
route(route, name, callback) {
var router = this;
if (!callback){
callback = this[name];
}
if(callback === undefined || callback === null){
throw new ArgumentNullException(`The route callback seems to be undefined, please check your router file for your route: ${name}`);
}
var customWrapperAroundCallback = ()=>{
var currentRoute = route;
//The default route is the noRoleRoute by default
if(currentRoute === ''){
currentRoute = router.noRoleRoute;
}
var routeName = '';//siteDescriptionBuilder.findRouteName(currentRoute);
var routeDescciption = {roles: ['DEFAULT_ROLE']};//siteDescriptionBuilder.getRoute(routeName);
if((routeDescciption === undefined && currentRoute !== '') || !userHelper.hasRole(routeDescciption.roles)){
message.addErrorMessage('application.noRights');
return Backbone.history.navigate('', true);
}else {
//Rendre all the notifications in the stack.
backboneNotification.renderNotifications();
}
//console.log('routeObject', siteDescriptionBuilder.getRoute(n));
callback.apply(router, arguments);
};
return Backbone.Router.prototype.route.call(this, route, name, customWrapperAroundCallback);
},
/**
* Render the compoennt into the page content.
*/
_pageContent(component, options){
return render(component, '[data-focus="page-content"]', options);
}
});
| Add error messages when the route is unknown | [router] Add error messages when the route is unknown
| JavaScript | mit | Jerom138/focus,Jerom138/focus,Jerom138/focus,KleeGroup/focus-core | ---
+++
@@ -1,6 +1,39 @@
var render = require('../application/render');
var Backbone = require('backbone');
+var ArgumentNullException = require('../exception/ArgumentNullException');
+var message = require('../message');
+var userHelper = require('../user');
module.exports = Backbone.Router.extend({
+ noRoleRoute: 'home',
+ route(route, name, callback) {
+ var router = this;
+ if (!callback){
+ callback = this[name];
+ }
+ if(callback === undefined || callback === null){
+ throw new ArgumentNullException(`The route callback seems to be undefined, please check your router file for your route: ${name}`);
+ }
+ var customWrapperAroundCallback = ()=>{
+ var currentRoute = route;
+ //The default route is the noRoleRoute by default
+ if(currentRoute === ''){
+ currentRoute = router.noRoleRoute;
+ }
+ var routeName = '';//siteDescriptionBuilder.findRouteName(currentRoute);
+ var routeDescciption = {roles: ['DEFAULT_ROLE']};//siteDescriptionBuilder.getRoute(routeName);
+ if((routeDescciption === undefined && currentRoute !== '') || !userHelper.hasRole(routeDescciption.roles)){
+ message.addErrorMessage('application.noRights');
+ return Backbone.history.navigate('', true);
+ }else {
+ //Rendre all the notifications in the stack.
+ backboneNotification.renderNotifications();
+ }
+ //console.log('routeObject', siteDescriptionBuilder.getRoute(n));
+ callback.apply(router, arguments);
+
+ };
+ return Backbone.Router.prototype.route.call(this, route, name, customWrapperAroundCallback);
+ },
/**
* Render the compoennt into the page content.
*/ |
df0479c901fcca29511ec3cbb996e827a1d98ea2 | resources/public/js/eval.js | resources/public/js/eval.js | $("#todoSubmitButton").click(function(e) {
e.preventDefault();
$.post("/eval", { evalInput: $("#evalInput").val() } ,
function(response) {
$("#display").html(response);
})
.done(function() {
$("#evalInput").val("");
});
}); | function doEval(e) {
$.post("/eval", { evalInput: $("#evalInput").val() } ,
function(response) {
$("#display").html(response);
})
.done(function() {
$("#evalInput").val("");
});
}
$("#todoSubmitButton").click(function(e) {
e.preventDefault();
doEval(e);
});
$('#evalInput').keydown(function(e) {
if (e.keyCode == 13) {
doEval(e);
return false;
}
}); | Add ability to submit input with Enter key. | Add ability to submit input with Enter key.
| JavaScript | mit | Pance/todo-repl-webapp | ---
+++
@@ -1,5 +1,4 @@
-$("#todoSubmitButton").click(function(e) {
- e.preventDefault();
+function doEval(e) {
$.post("/eval", { evalInput: $("#evalInput").val() } ,
function(response) {
$("#display").html(response);
@@ -7,4 +6,14 @@
.done(function() {
$("#evalInput").val("");
});
+}
+$("#todoSubmitButton").click(function(e) {
+ e.preventDefault();
+ doEval(e);
});
+$('#evalInput').keydown(function(e) {
+ if (e.keyCode == 13) {
+ doEval(e);
+ return false;
+ }
+}); |
9273b2c8332f7c7c16add91bb064a74938dc27f7 | tests/dummy/config/environment.js | tests/dummy/config/environment.js | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'auto',
contentSecurityPolicy: {
'default-src': "'none'",
'script-src': "'self' ",
'font-src': "'self' ",
'connect-src': "'self' ",
'img-src': "'self'",
'style-src': "'self' 'unsafe-inline'",
'media-src': "'self'",
'report-uri': "http://localhost:4200/report"
},
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| Add CSP to stop it whining! | Add CSP to stop it whining!
| JavaScript | mit | mfeckie/ember-cli-indexed-db-adapter,mfeckie/ember-cli-indexed-db-adapter | ---
+++
@@ -6,6 +6,16 @@
environment: environment,
baseURL: '/',
locationType: 'auto',
+ contentSecurityPolicy: {
+ 'default-src': "'none'",
+ 'script-src': "'self' ",
+ 'font-src': "'self' ",
+ 'connect-src': "'self' ",
+ 'img-src': "'self'",
+ 'style-src': "'self' 'unsafe-inline'",
+ 'media-src': "'self'",
+ 'report-uri': "http://localhost:4200/report"
+ },
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build |
0e3fdfc0ca36085086930579ea18297d7c23a164 | packages/strapi-plugin-upload/admin/src/components/InputMedia/InputFilePreview.js | packages/strapi-plugin-upload/admin/src/components/InputMedia/InputFilePreview.js | import React from 'react';
import PropTypes from 'prop-types';
import { get } from 'lodash';
import { prefixFileUrlWithBackendUrl } from 'strapi-helper-plugin';
import CardPreview from '../CardPreview';
import Flex from '../Flex';
import Chevron from './Chevron';
const InputFilePreview = ({ file, onClick, isSlider }) => {
const fileUrl = prefixFileUrlWithBackendUrl(get(file, ['formats', 'thumbnail', 'url'], file.url));
return (
<Flex
key={file.id}
style={{ height: '100%' }}
alignItems="center"
justifyContent="space-between"
>
{isSlider && <Chevron side="left" onClick={() => onClick(false)} />}
<CardPreview hasIcon url={fileUrl} type={file.mime} />
{isSlider && <Chevron side="right" onClick={() => onClick(true)} />}
</Flex>
);
};
InputFilePreview.propTypes = {
file: PropTypes.object,
isSlider: PropTypes.bool,
onClick: PropTypes.func.isRequired,
};
InputFilePreview.defaultProps = {
isSlider: false,
file: null,
};
export default InputFilePreview;
| import React from 'react';
import PropTypes from 'prop-types';
import { get } from 'lodash';
import { prefixFileUrlWithBackendUrl } from 'strapi-helper-plugin';
import CardPreview from '../CardPreview';
import Flex from '../Flex';
import Chevron from './Chevron';
const InputFilePreview = ({ file, onClick, isSlider }) => {
const fileUrl = prefixFileUrlWithBackendUrl(get(file, ['formats', 'small', 'url'], file.url));
return (
<Flex
key={file.id}
style={{ height: '100%' }}
alignItems="center"
justifyContent="space-between"
>
{isSlider && <Chevron side="left" onClick={() => onClick(false)} />}
<CardPreview hasIcon url={fileUrl} type={file.mime} />
{isSlider && <Chevron side="right" onClick={() => onClick(true)} />}
</Flex>
);
};
InputFilePreview.propTypes = {
file: PropTypes.object,
isSlider: PropTypes.bool,
onClick: PropTypes.func.isRequired,
};
InputFilePreview.defaultProps = {
isSlider: false,
file: null,
};
export default InputFilePreview;
| Change format in input file | Change format in input file
Signed-off-by: soupette <0a59f0508aa203bc732745954131d022d9f538a9@gmail.com>
| JavaScript | mit | wistityhq/strapi,wistityhq/strapi | ---
+++
@@ -8,7 +8,7 @@
import Chevron from './Chevron';
const InputFilePreview = ({ file, onClick, isSlider }) => {
- const fileUrl = prefixFileUrlWithBackendUrl(get(file, ['formats', 'thumbnail', 'url'], file.url));
+ const fileUrl = prefixFileUrlWithBackendUrl(get(file, ['formats', 'small', 'url'], file.url));
return (
<Flex |
8f6dfaf2808a48aed8c4fb99731d3bb176b7360b | Resources/public/js/calendar-settings.js | Resources/public/js/calendar-settings.js | $(function () {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar-holder').fullCalendar({
header: {
left: 'prev, next',
center: 'title',
right: 'month,basicWeek,basicDay,'
},
lazyFetching:true,
timeFormat: {
// for agendaWeek and agendaDay
agenda: 'h:mmt', // 5:00 - 6:30
// for all other views
'': 'h:mmt' // 7p
},
eventSources: [
{
url: Routing.generate('fullcalendar_loader'),
type: 'POST',
// A way to add custom filters to your event listeners
data: {
},
error: function() {
//alert('There was an error while fetching Google Calendar!');
}
}
]
});
});
| $(function () {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar-holder').fullCalendar({
header: {
left: 'prev, next',
center: 'title',
right: 'month, basicWeek, basicDay,'
},
lazyFetching: true,
timeFormat: {
// for agendaWeek and agendaDay
agenda: 'h:mmt', // 5:00 - 6:30
// for all other views
'': 'h:mmt' // 7p
},
eventSources: [
{
url: Routing.generate('fullcalendar_loader'),
type: 'POST',
// A way to add custom filters to your event listeners
data: {
},
error: function() {
//alert('There was an error while fetching Google Calendar!');
}
}
]
});
});
| Fix JavaScript file indentation inconsistency. | Fix JavaScript file indentation inconsistency.
| JavaScript | mit | ScienceSoft-Inc/calendar-bundle,buddhikajay/calendar-bundle,ScienceSoft-Inc/calendar-bundle,Th3Mouk/calendar-bundle,adesigns/calendar-bundle,Th3Mouk/calendar-bundle,buddhika-jay/calendar-bundle,adesigns/calendar-bundle,buddhikajay/calendar-bundle,adesigns/calendar-bundle,Toasterson/calendar-bundle,Th3Mouk/calendar-bundle,buddhikajay/calendar-bundle,Toasterson/calendar-bundle,ScienceSoft-Inc/calendar-bundle,buddhika-jay/calendar-bundle,buddhika-jay/calendar-bundle | ---
+++
@@ -1,35 +1,34 @@
$(function () {
- var date = new Date();
- var d = date.getDate();
- var m = date.getMonth();
- var y = date.getFullYear();
-
- $('#calendar-holder').fullCalendar({
- header: {
- left: 'prev, next',
- center: 'title',
- right: 'month,basicWeek,basicDay,'
- },
- lazyFetching:true,
- timeFormat: {
- // for agendaWeek and agendaDay
- agenda: 'h:mmt', // 5:00 - 6:30
+ var date = new Date();
+ var d = date.getDate();
+ var m = date.getMonth();
+ var y = date.getFullYear();
- // for all other views
- '': 'h:mmt' // 7p
- },
- eventSources: [
- {
- url: Routing.generate('fullcalendar_loader'),
- type: 'POST',
- // A way to add custom filters to your event listeners
- data: {
+ $('#calendar-holder').fullCalendar({
+ header: {
+ left: 'prev, next',
+ center: 'title',
+ right: 'month, basicWeek, basicDay,'
+ },
+ lazyFetching: true,
+ timeFormat: {
+ // for agendaWeek and agendaDay
+ agenda: 'h:mmt', // 5:00 - 6:30
- },
- error: function() {
- //alert('There was an error while fetching Google Calendar!');
- }
- }
- ]
- });
+ // for all other views
+ '': 'h:mmt' // 7p
+ },
+ eventSources: [
+ {
+ url: Routing.generate('fullcalendar_loader'),
+ type: 'POST',
+ // A way to add custom filters to your event listeners
+ data: {
+ },
+ error: function() {
+ //alert('There was an error while fetching Google Calendar!');
+ }
+ }
+ ]
+ });
}); |
e1016147596427290bd4297203a99449206f91e9 | scripts/init.js | scripts/init.js | var path = require('path')
var fs = require('fs-extra')
var spawn = require('cross-spawn')
module.exports = function(root, appName) {
var selfPath = path.join(root, 'node_modules', 'jsonnull-project-scripts')
var appPackage = require(path.join(root, 'package.json'))
var templatePackage = require(path.join(selfPath, 'config', 'package.json'))
var packageJson = Object.assign({}, appPackage, templatePackage)
// Copy dependencies
var deps = Object.assign({}, templatePackage.dependencies, appPackage.dependencies)
Object.assign(packageJson, { dependencies: deps })
fs.writeFileSync(
path.join(root, 'package.json'),
JSON.stringify(packageJson, null, 2)
)
fs.copySync(path.join(selfPath, 'template'), root);
var proc = spawn('npm', ['install'], {stdio: 'inherit'})
proc.on('close', function (code) {
if (code !== 0) {
console.error('npm install failed.')
return;
}
})
}
| var path = require('path')
var fs = require('fs-extra')
var spawn = require('cross-spawn')
module.exports = function(root, appName) {
var selfPath = path.join(root, 'node_modules', 'jsonnull-project-scripts')
var appPackage = require(path.join(root, 'package.json'))
var templatePackage = require(path.join(selfPath, 'config', 'package.json'))
var packageJson = Object.assign({}, appPackage, templatePackage)
fs.writeFileSync(
path.join(root, 'package.json'),
JSON.stringify(packageJson, null, 2)
)
fs.copySync(path.join(selfPath, 'template'), root);
var proc = spawn('npm', ['install'], {stdio: 'inherit'})
proc.on('close', function (code) {
if (code !== 0) {
console.error('npm install failed.')
return;
}
})
}
| Revert "Keep project-scripts dependency after adding package.json template data." | Revert "Keep project-scripts dependency after adding package.json template data."
This reverts commit 1ae48aa9a8166b97b5942396cb5b821927f0e513.
| JavaScript | mit | jsonnull/project-scripts | ---
+++
@@ -9,10 +9,6 @@
var templatePackage = require(path.join(selfPath, 'config', 'package.json'))
var packageJson = Object.assign({}, appPackage, templatePackage)
-
- // Copy dependencies
- var deps = Object.assign({}, templatePackage.dependencies, appPackage.dependencies)
- Object.assign(packageJson, { dependencies: deps })
fs.writeFileSync(
path.join(root, 'package.json'), |
3816d80fe0740d7fd2a0bd1e34a5e9ecdf868184 | src/bootStrap.js | src/bootStrap.js | "use strict";
//This JS file simply bootstraps the app from the root component when the window loads
var AppRoot = require('./components/AppRoot.jsx');
var Home = require('./components/Home.jsx');
var React = require('react');
var ReactDOM = require('react-dom');
var Redirect = require('react-router').Redirect;
var Router = require('react-router').Router;
var Route = require('react-router').Route;
var browserHistory = require('react-router').browserHistory;
//Keep references to these outside of the function
var appRootComponent;
//This function executes immediately
(function() {
//This function is attached to execute when the window loads
document.addEventListener('DOMContentLoaded', function() {
ReactDOM.render(
/* jshint ignore:start */
<Router history={browserHistory}>
<Route path="/" component={AppRoot}>
<Route path="/home" component={Home}/>
<Redirect from="*" to="/home"/>
</Route>
</Router>, document.getElementById('app')
/* jshint ignore:end */
);
});
})();
| "use strict";
//This JS file simply bootstraps the app from the root component when the window loads
var AppRoot = require('./components/AppRoot.jsx');
var Home = require('./components/Home.jsx');
var React = require('react');
var ReactDOM = require('react-dom');
var Redirect = require('react-router').Redirect;
var Router = require('react-router').Router;
var Route = require('react-router').Route;
var useRouterHistory = require('react-router').useRouterHistory;
var createHistory = require('history').createHistory;
const history = useRouterHistory(createHistory)({
basename: '/react-bp'
});
//Keep references to these outside of the function
var appRootComponent;
//This function executes immediately
(function() {
//This function is attached to execute when the window loads
document.addEventListener('DOMContentLoaded', function() {
ReactDOM.render(
/* jshint ignore:start */
<Router history={history}>
<Route path="/" component={AppRoot}>
<Route path="/home" component={Home}/>
<Redirect from="*" to="/home"/>
</Route>
</Router>, document.getElementById('app')
/* jshint ignore:end */
);
});
})();
| Add appcontext to router history | Add appcontext to router history
| JavaScript | mit | chad-autry/react-bp,chad-autry/react-bp,chad-autry/react-bp | ---
+++
@@ -8,7 +8,12 @@
var Redirect = require('react-router').Redirect;
var Router = require('react-router').Router;
var Route = require('react-router').Route;
-var browserHistory = require('react-router').browserHistory;
+var useRouterHistory = require('react-router').useRouterHistory;
+var createHistory = require('history').createHistory;
+
+const history = useRouterHistory(createHistory)({
+ basename: '/react-bp'
+});
//Keep references to these outside of the function
var appRootComponent;
@@ -21,7 +26,7 @@
ReactDOM.render(
/* jshint ignore:start */
- <Router history={browserHistory}>
+ <Router history={history}>
<Route path="/" component={AppRoot}>
<Route path="/home" component={Home}/>
<Redirect from="*" to="/home"/> |
680680e60688119fc5fd21258c0a94e19e83774f | scripts/download-nuget.js | scripts/download-nuget.js | const fs = require('fs');
const request = require('request');
const nuget = './nuget.exe';
console.info(`Downloading 'nuget.exe'...`);
console.info();
request
.get('https://dist.nuget.org/win-x86-commandline/latest/nuget.exe')
.on('error', function (err) {
console.error(err);
})
.on('response', function (response) {
if (response.statusCode == 200) {
console.info(`Successfully downloaded 'nuget.exe'.`);
} else {
console.error(`Downloading 'nuget.exe' failed. statusCode '${response.statusCode}'`);
}
})
.pipe(fs.createWriteStream(nuget));
| const fs = require('fs');
const request = require('request');
const nuget = './nuget.exe';
console.info(`Downloading 'nuget.exe'...`);
console.info();
request
.get('https://dist.nuget.org/win-x86-commandline/v3.4.2-rc/nuget.exe')
.on('error', function (err) {
console.error(err);
})
.on('response', function (response) {
if (response.statusCode == 200) {
console.info(`Successfully downloaded 'nuget.exe'.`);
} else {
console.error(`Downloading 'nuget.exe' failed. statusCode '${response.statusCode}'`);
}
})
.pipe(fs.createWriteStream(nuget));
| Update to NuGet v3.4.2 to allow use of environment variables | Update to NuGet v3.4.2 to allow use of environment variables
| JavaScript | mit | TimMurphy/npm-nuget | ---
+++
@@ -7,7 +7,7 @@
console.info();
request
- .get('https://dist.nuget.org/win-x86-commandline/latest/nuget.exe')
+ .get('https://dist.nuget.org/win-x86-commandline/v3.4.2-rc/nuget.exe')
.on('error', function (err) {
console.error(err);
}) |
8ef0e59a97e087857d3ed7e87da5445c151242af | webpack.config.js | webpack.config.js | var webpack = require('webpack');
var poststylus = require('poststylus');
module.exports = {
devtool: 'source-map',
entry: __dirname + '/src',
output: {
path: 'public/builds/',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
include: __dirname + '/src',
query: {
presets: ['es2015'],
plugins: ['mjsx']
},
},
{
test: /\.styl/,
loader: 'style!css!stylus',
},
{
test: /\.html/,
loader: 'html'
}
],
},
stylus: {
use: [
function (stylus) {
stylus.import(__dirname + '/src/stylus/variables');
},
poststylus([ 'autoprefixer' ])
]
},
plugins: [
new webpack.ProvidePlugin({
m: 'mithril'
})
]
}
| var webpack = require('webpack');
var poststylus = require('poststylus');
var path = require('path')
module.exports = {
devtool: 'source-map',
entry: path.resolve(__dirname, 'src'),
output: {
path: 'public/builds/',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
include: path.resolve(__dirname, 'src'),
query: {
presets: ['es2015'],
plugins: ['mjsx']
},
},
{
test: /\.styl/,
loader: 'style!css!stylus',
},
{
test: /\.html/,
loader: 'html'
}
],
},
stylus: {
use: [
function (stylus) {
stylus.import(path.resolve(__dirname, 'src/stylus/variables'));
},
poststylus([ 'autoprefixer' ])
]
},
plugins: [
new webpack.ProvidePlugin({
m: 'mithril'
})
]
}
| Fix webpack builds on windows | Fix webpack builds on windows
| JavaScript | apache-2.0 | orangechat/webapp,orangechat/webapp | ---
+++
@@ -1,9 +1,10 @@
var webpack = require('webpack');
var poststylus = require('poststylus');
+var path = require('path')
module.exports = {
devtool: 'source-map',
- entry: __dirname + '/src',
+ entry: path.resolve(__dirname, 'src'),
output: {
path: 'public/builds/',
filename: 'bundle.js'
@@ -13,7 +14,7 @@
{
test: /\.jsx?$/,
loader: 'babel',
- include: __dirname + '/src',
+ include: path.resolve(__dirname, 'src'),
query: {
presets: ['es2015'],
plugins: ['mjsx']
@@ -32,7 +33,7 @@
stylus: {
use: [
function (stylus) {
- stylus.import(__dirname + '/src/stylus/variables');
+ stylus.import(path.resolve(__dirname, 'src/stylus/variables'));
},
poststylus([ 'autoprefixer' ])
] |
a9a68fcd2b7ff898d93d257b7c65282b57bdaef8 | webpack.config.js | webpack.config.js | const webpack = require('webpack');
const path = require('path');
const fs = require('fs');
const webpackMerge = require('webpack-merge');
const defaultConfig = {
target: 'node',
entry: {
'bundle.node': './src/index.js',
'bundle.node.min': './src/index.js',
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
library: 'maps4news',
libraryTarget: 'amd',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env'],
},
},
},
],
},
devtool: 'source-map',
plugins: [
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/,
minimize: true,
}),
new webpack.BannerPlugin(fs.readFileSync('LICENSE', 'ascii')),
],
};
module.exports = [
defaultConfig,
webpackMerge(defaultConfig, {
target: 'web',
entry: {
'bundle.web': './src/index.js',
'bundle.web.min': './src/index.js',
},
output: {
libraryTarget: 'window',
},
}),
];
| const webpack = require('webpack');
const path = require('path');
const fs = require('fs');
const webpackMerge = require('webpack-merge');
const defaultConfig = {
target: 'node',
entry: {
'bundle.node': './src/index.js',
'bundle.node.min': './src/index.js',
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
library: 'maps4news',
libraryTarget: 'umd',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env'],
},
},
},
],
},
devtool: 'source-map',
plugins: [
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/,
minimize: true,
}),
new webpack.BannerPlugin(fs.readFileSync('LICENSE', 'ascii')),
],
};
module.exports = [
defaultConfig,
webpackMerge(defaultConfig, {
target: 'web',
entry: {
'bundle.web': './src/index.js',
'bundle.web.min': './src/index.js',
},
output: {
libraryTarget: 'window',
},
}),
];
| Change node build target libraryTarget from AMD to UMD | Change node build target libraryTarget from AMD to UMD
| JavaScript | bsd-3-clause | MapCreatorEU/m4n-api,MapCreatorEU/m4n-api | ---
+++
@@ -14,7 +14,7 @@
path: path.resolve(__dirname, 'dist'),
library: 'maps4news',
- libraryTarget: 'amd',
+ libraryTarget: 'umd',
},
module: {
rules: [ |
a33c07ec2b2ad84ae1738ba4dbf1858f21e771bc | setup.js | setup.js | 'use strict';
var exec = require('child_process').exec;
var util = require('util');
var fs = require('fs');
var rimraf = require('rimraf');
var repos = [
'https://github.com/syngan/vim-vimlint',
'https://github.com/ynkdir/vim-vimlparser'
];
function git_clone(url) {
var folder = url.slice(url.lastIndexOf('/') + 1);
rimraf(folder, function (err) {
if (err) {
console.error(err);
return process.exit(1);
}
exec('git clone ' + url + ' ' + folder, function (err, stdout, stderr) {
if (stdout) util.print(stdout);
if (stderr) util.print(stderr);
if (err) {
return process.exit(1);
}
else {
rimraf(folder + '/.git', function (err) {
if (err) {
console.error(err);
return process.exit(1);
}
});
}
});
});
}
function clone_repos(repos) {
repos.forEach(function (repo) {
git_clone(repo);
});
}
switch (process.argv[process.argv.length - 1]) {
case 'postinstall':
clone_repos(repos);
break;
}
| 'use strict';
var exec = require('child_process').exec;
var fs = require('fs');
var rimraf = require('rimraf');
var repos = [
'https://github.com/syngan/vim-vimlint',
'https://github.com/ynkdir/vim-vimlparser'
];
function git_clone(url) {
var folder = url.slice(url.lastIndexOf('/') + 1);
rimraf(folder, function (err) {
if (err) {
console.error(err);
return process.exit(1);
}
exec('git clone ' + url + ' ' + folder, function (err, stdout, stderr) {
if (stdout) process.stdout.write(stdout);
if (stderr) process.stderr.write(stderr);
if (err) {
return process.exit(1);
}
else {
rimraf(folder + '/.git', function (err) {
if (err) {
console.error(err);
return process.exit(1);
}
});
}
});
});
}
function clone_repos(repos) {
repos.forEach(function (repo) {
git_clone(repo);
});
}
switch (process.argv[process.argv.length - 1]) {
case 'postinstall':
clone_repos(repos);
break;
}
| Switch deprecated function from util.print to process.stdout.write | Switch deprecated function from util.print to process.stdout.write
| JavaScript | mit | pine613/node-vimlint | ---
+++
@@ -1,7 +1,6 @@
'use strict';
var exec = require('child_process').exec;
-var util = require('util');
var fs = require('fs');
var rimraf = require('rimraf');
@@ -20,8 +19,8 @@
}
exec('git clone ' + url + ' ' + folder, function (err, stdout, stderr) {
- if (stdout) util.print(stdout);
- if (stderr) util.print(stderr);
+ if (stdout) process.stdout.write(stdout);
+ if (stderr) process.stderr.write(stderr);
if (err) {
return process.exit(1); |
69fd17c26676ba77dc4352a11f059b92df1245c0 | gulpfile.js | gulpfile.js | 'use strict';
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('compile', function () {
return gulp.src('./scss/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./dist/'));
});
gulp.task('watch', function () {
gulp.watch('./scss/*.scss', ['compile']);
});
| 'use strict';
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('compile', function () {
return gulp.src('./scss/*.scss')
.pipe(gulp.dest('./dist/'));
});
gulp.task('watch', function () {
gulp.watch('./scss/*.scss', ['compile']);
});
| Stop gulp from hiding errors during compilation | Stop gulp from hiding errors during compilation
| JavaScript | mit | aoimedia/Amazium,aoimedia/Amazium,OwlyStuff/Amazium,catchamonkey/amazium,OwlyStuff/Amazium,MikeBallan/Amazium | ---
+++
@@ -5,7 +5,6 @@
gulp.task('compile', function () {
return gulp.src('./scss/*.scss')
- .pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./dist/'));
});
|
40450c65322ff2f00a4c6dcc3fc1aeab2b982fcb | gulpfile.js | gulpfile.js | var gulp = require('gulp'),
uglify = require('gulp-uglify'),
prefix = require('gulp-autoprefixer'),
minifyCSS = require('gulp-minify-css'),
umd_wrap = require('gulp-wrap-umd'),
stylus = require('gulp-stylus'),
rename = require('gulp-rename');
gulp.task('build', function() {
gulp.src('source/ouibounce.js')
.pipe(umd_wrap({ namespace: 'ouiBounce' }))
.pipe(gulp.dest('build'));
gulp.src('source/ouibounce.js')
.pipe(umd_wrap({ namespace: 'ouiBounce' }))
.pipe(uglify())
.pipe(rename('ouibounce.min.js'))
.pipe(gulp.dest('build'));
gulp.src('test/ouibounce.styl')
.pipe(stylus())
.pipe(prefix())
.pipe(rename('ouibounce.css'))
.pipe(gulp.dest('test'));
gulp.src('test/ouibounce.styl')
.pipe(stylus())
.pipe(prefix())
.pipe(minifyCSS())
.pipe(rename('ouibounce.min.css'))
.pipe(gulp.dest('test'));
});
// Rerun the task when a file changes
gulp.task('watch', function () {
gulp.watch('test/ouibounce.styl', ['build']);
});
| var gulp = require('gulp'),
uglify = require('gulp-uglify'),
prefix = require('gulp-autoprefixer'),
minifyCSS = require('gulp-minify-css'),
umd_wrap = require('gulp-wrap-umd'),
stylus = require('gulp-stylus'),
rename = require('gulp-rename');
gulp.task('build', function() {
gulp.src('source/ouibounce.js')
.pipe(umd_wrap({ namespace: 'ouiBounce' }))
.pipe(gulp.dest('build'));
gulp.src('source/ouibounce.js')
.pipe(umd_wrap({ namespace: 'ouiBounce' }))
.pipe(uglify())
.pipe(rename('ouibounce.min.js'))
.pipe(gulp.dest('build'));
gulp.src('test/ouibounce.styl')
.pipe(stylus())
.pipe(prefix())
.pipe(rename('ouibounce.css'))
.pipe(gulp.dest('test'));
gulp.src('test/ouibounce.styl')
.pipe(stylus())
.pipe(prefix())
.pipe(minifyCSS())
.pipe(rename('ouibounce.min.css'))
.pipe(gulp.dest('test'));
});
// Rerun the task when a file changes
gulp.task('watch', function () {
gulp.watch('test/ouibounce.styl', ['build']);
gulp.watch('source/ouibounce.js', ['build']);
});
| Fix gulp script to watch src file change | Fix gulp script to watch src file change
| JavaScript | mit | avorio/ouibounce,kevinweber/wbounce,iamlos/ouibounce,olhapi/ouibounce,DavideDaniel/ouibounce,iamlos/wbounce,trishasalas/ouibounce,carlsednaoui/ouibounce,dahal/ouibounce,avorio/ouibounce,haveal/wbounce,sebastien-fauvel/ouibounce,haveal/wbounce,sebastien-fauvel/ouibounce,DavideDaniel/ouibounce,olhapi/ouibounce,anthony-legible/ouibounce,gdseller/ouibounce,gdseller/ouibounce,carlsednaoui/ouibounce,iamlos/wbounce,kevinweber/wbounce,iamlos/ouibounce,trishasalas/ouibounce,anthony-legible/ouibounce,dahal/ouibounce,smokymountains/ouibounce,kevinweber/wbounce | ---
+++
@@ -35,4 +35,5 @@
// Rerun the task when a file changes
gulp.task('watch', function () {
gulp.watch('test/ouibounce.styl', ['build']);
+ gulp.watch('source/ouibounce.js', ['build']);
}); |
4a95bc8f2749d723263ef1980035af96e13b8972 | phantomas.js | phantomas.js | #!/usr/bin/env phantomjs
/**
* PhantomJS-based web performance metrics collector
*
* Usage:
* ./phantomas.js
* --url=<page to check>
* [--format=json|csv|plain]
* [--timeout=5]
* ]--viewport=<width>x<height>]
* [--verbose]
* [--silent]
* [--log=<log file>]
* [--modules=moduleOne,moduleTwo]
* [--user-agent='Custom user agent']
* [--config='JSON config file']
* [--no-externals]
* [--allow-domain='domain,domain']
* [--block-domain='domain,domain']
*/
var args = require('system').args,
// get absolute path (useful when phantomas is installed globally)
dir = require('fs').readLink(args[0]).replace(/phantomas.js$/, '') || '.',
// parse script arguments
params = require(dir + '/lib/args').parse(args),
phantomas = require(dir + '/core/phantomas'),
instance;
// run phantomas
instance = new phantomas(params);
try {
instance.run();
}
catch(ex) {
console.log('phantomas v' + phantomas.version + ' failed with an error:');
console.log(ex);
phantom.exit(1);
}
| #!/usr/bin/env phantomjs
/**
* PhantomJS-based web performance metrics collector
*
* Usage:
* ./phantomas.js
* --url=<page to check>
* [--format=json|csv|plain]
* [--timeout=5]
* ]--viewport=<width>x<height>]
* [--verbose]
* [--silent]
* [--log=<log file>]
* [--modules=moduleOne,moduleTwo]
* [--user-agent='Custom user agent']
* [--config='JSON config file']
* [--cookie='bar=foo;domain=url']
* [--no-externals]
* [--allow-domain='domain,domain']
* [--block-domain='domain,domain']
*/
var args = require('system').args,
// get absolute path (useful when phantomas is installed globally)
dir = require('fs').readLink(args[0]).replace(/phantomas.js$/, '') || '.',
// parse script arguments
params = require(dir + '/lib/args').parse(args),
phantomas = require(dir + '/core/phantomas'),
instance;
// run phantomas
instance = new phantomas(params);
try {
instance.run();
}
catch(ex) {
console.log('phantomas v' + phantomas.version + ' failed with an error:');
console.log(ex);
phantom.exit(1);
}
| Update comment RE: --cookie syntax | Update comment RE: --cookie syntax
| JavaScript | bsd-2-clause | ingoclaro/phantomas,macbre/phantomas,ingoclaro/phantomas,macbre/phantomas,william-p/phantomas,william-p/phantomas,gmetais/phantomas,macbre/phantomas,gmetais/phantomas,ingoclaro/phantomas,gmetais/phantomas,william-p/phantomas | ---
+++
@@ -14,6 +14,7 @@
* [--modules=moduleOne,moduleTwo]
* [--user-agent='Custom user agent']
* [--config='JSON config file']
+ * [--cookie='bar=foo;domain=url']
* [--no-externals]
* [--allow-domain='domain,domain']
* [--block-domain='domain,domain'] |
59ab8f7de70470f4bb7ca4a8cffe42bff83c90ea | modules/common-login-resources/src/main/resources/login/login.spec.js | modules/common-login-resources/src/main/resources/login/login.spec.js | define(['common/login/login.controller'], function() {
describe('Login Module', function() {
var scope, state, controller, AuthMock;
beforeEach(module('ui.router'));
beforeEach(module('app.common.login', function($provide) {
AuthMock = jasmine.createSpyObj('AuthMock', ['isAuthed']);
$provide.value('Auth', AuthMock);
}));
beforeEach(inject( function($rootScope, $controller, $state) {
scope = $rootScope.$new();
controller = $controller;
state = $state;
}));
it('Should load the login state', function() {
var stateName = 'login';
controller('LoginCtrl', {$scope: scope, $state: state});
expect(state.href(stateName, {})).toBe('#/login');
});
});
});
| define(['common/login/login.controller'], function() {
describe('Login Module', function() {
var scope, state, controller, location, _AuthMock;
var url = '/test';
beforeEach(module('ui.router'));
beforeEach(module('app.common.layout'));
beforeEach(module('app.common.login', function($provide) {
AuthMock = {
isAuthed: function() {},
login: function() {}
};
$provide.value('Auth', AuthMock);
}));
beforeEach(inject( function($rootScope, $controller, $state, $location) {
scope = $rootScope.$new();
controller = $controller;
state = $state;
location = $location;
}));
it('Should load the login state', function() {
var stateName = 'login';
controller('LoginCtrl', {$scope: scope, $state: state});
expect(state.href(stateName, {})).toBe('#/login');
});
it('Should redirect any url to login if not logged', function() {
var stateName = 'login';
spyOn(AuthMock,'isAuthed').andReturn(false);
location.url(url);
controller('LoginCtrl', {$scope: scope, $state: state});
state.go('main');
expect(AuthMock.isAuthed).toHaveBeenCalled();
expect(state.is("login"));
expect(location.url()).toEqual('/login');
});
it('Should not redirect if logged', function() {
spyOn(AuthMock,'isAuthed').andReturn(true);
location.url(url);
controller('LoginCtrl', {$scope: scope, $state: state});
state.go('main');
expect(AuthMock.isAuthed).toHaveBeenCalled();
expect(state.is("main"));
expect(location.url()).toEqual(url);
});
it('Should call the Auth module', function() {
spyOn(AuthMock,'login');
controller('LoginCtrl', {$scope: scope, $state: state});
scope.sendLogin();
expect(AuthMock.login).toHaveBeenCalled();
});
});
});
| Increase test coverage: Add unit tests to the login module part 2 | Increase test coverage: Add unit tests to the login module part 2
Change-Id: I02ffbec59100992d709e0de6eb666813fef29f04
Signed-off-by: Maxime Millette-Coulombe <b285d4cbf4325435252f66fa223af3055d88bdb9@inocybe.com>
| JavaScript | epl-1.0 | opendaylight/dlux,opendaylight/dlux,inocybe/odl-dlux,stshtina/ODL,pinaxia/dlux,inocybe/odl-dlux,opendaylight/dlux,stshtina/ODL,inocybe/odl-dlux,pinaxia/dlux,stshtina/ODL,pinaxia/dlux | ---
+++
@@ -1,17 +1,23 @@
define(['common/login/login.controller'], function() {
describe('Login Module', function() {
- var scope, state, controller, AuthMock;
+ var scope, state, controller, location, _AuthMock;
+ var url = '/test';
beforeEach(module('ui.router'));
+ beforeEach(module('app.common.layout'));
beforeEach(module('app.common.login', function($provide) {
- AuthMock = jasmine.createSpyObj('AuthMock', ['isAuthed']);
+ AuthMock = {
+ isAuthed: function() {},
+ login: function() {}
+ };
$provide.value('Auth', AuthMock);
}));
- beforeEach(inject( function($rootScope, $controller, $state) {
+ beforeEach(inject( function($rootScope, $controller, $state, $location) {
scope = $rootScope.$new();
controller = $controller;
state = $state;
+ location = $location;
}));
it('Should load the login state', function() {
@@ -20,5 +26,36 @@
controller('LoginCtrl', {$scope: scope, $state: state});
expect(state.href(stateName, {})).toBe('#/login');
});
+
+ it('Should redirect any url to login if not logged', function() {
+ var stateName = 'login';
+ spyOn(AuthMock,'isAuthed').andReturn(false);
+ location.url(url);
+ controller('LoginCtrl', {$scope: scope, $state: state});
+ state.go('main');
+
+ expect(AuthMock.isAuthed).toHaveBeenCalled();
+ expect(state.is("login"));
+ expect(location.url()).toEqual('/login');
+ });
+
+ it('Should not redirect if logged', function() {
+ spyOn(AuthMock,'isAuthed').andReturn(true);
+ location.url(url);
+ controller('LoginCtrl', {$scope: scope, $state: state});
+ state.go('main');
+
+ expect(AuthMock.isAuthed).toHaveBeenCalled();
+ expect(state.is("main"));
+ expect(location.url()).toEqual(url);
+ });
+
+ it('Should call the Auth module', function() {
+ spyOn(AuthMock,'login');
+ controller('LoginCtrl', {$scope: scope, $state: state});
+
+ scope.sendLogin();
+ expect(AuthMock.login).toHaveBeenCalled();
+ });
});
}); |
21d80a417983b060831e7e3c0b009eec4473be59 | app/assets/javascripts/feeds.js | app/assets/javascripts/feeds.js | (function (Shreds) { 'use strict';
var name = 'feeds';
var container = $('.span-fixed-sidebar');
Shreds.components.push(name);
Shreds[name] = {
init: function () { },
render: function (context, url) {
container.attr('data-template', context);
Shreds.ajax.get(url).done(function (data) {
Shreds.loadModel(context, data);
Shreds.syncView(context);
});
},
events: {
'shreds:feeds:render:index': function (ev, data) {
Shreds.feeds.render('feeds/index', '/i/feeds.json');
},
'shreds:feed:render:show': function (ev, data) {
Shreds.feeds.render('feeds/show', '/i/feeds/' + data.id + '.json');
}
}
};
})(window.Shreds);
| (function (Shreds) { 'use strict';
var name = 'feeds';
var container = $('.span-fixed-sidebar');
Shreds.components.push(name);
Shreds[name] = {
init: function () { },
render: function (context, url) {
container.attr('data-template', context);
Shreds.ajax.get(url).done(function (data) {
Shreds.loadModel(context, data);
Shreds.syncView(context);
document.title = '[shreds] - ' + (data.title || 'Feeds');
});
},
events: {
'shreds:feeds:render:index': function (ev, data) {
Shreds.feeds.render('feeds/index', '/i/feeds.json');
},
'shreds:feed:render:show': function (ev, data) {
Shreds.feeds.render('feeds/show', '/i/feeds/' + data.id + '.json');
}
}
};
})(window.Shreds);
| Set title when route changed | Set title when route changed
| JavaScript | mit | fudanchii/shreds,fudanchii/shreds,fudanchii/shreds | ---
+++
@@ -10,6 +10,7 @@
Shreds.ajax.get(url).done(function (data) {
Shreds.loadModel(context, data);
Shreds.syncView(context);
+ document.title = '[shreds] - ' + (data.title || 'Feeds');
});
},
events: { |
2269784e3711a165c9dbfb52313a07fdfb3e2bfd | src/core/sfx.js | src/core/sfx.js | var Sfx = {
sounds: { },
preload: function() {
this.load('pickup_donut');
this.load('pickup_veggie');
this.load('omnom');
this.load('burp');
this.load('running');
this.load('puke');
},
load: function(soundId) {
console.info('[SFX] Loading sound effect', soundId);
Sfx.sounds[soundId] = new Audio('assets/sfx/' + soundId + '.wav');
Sfx.sounds[soundId].load();
return Sfx.sounds[soundId];
},
play: function(soundId) {
if (typeof Sfx.sounds[soundId] == 'undefined') {
Sfx.load(soundId);
} else {
Sfx.sounds[soundId].load(); // call load() every time to fix Chrome issue where sound only plays first time
}
Sfx.sounds[soundId].play();
},
pickupDonut: function () { this.play('pickup_donut'); },
pickupVeggie: function () { this.play('pickup_veggie'); },
omNom: function() { this.play('omnom'); },
burp: function() { this.play('burp'); },
puke: function() { this.play('puke'); }
}; | var Sfx = {
sounds: { },
preload: function() {
this.load('pickup_donut');
this.load('pickup_veggie');
this.load('omnom');
this.load('burp');
this.load('running');
this.load('puke');
},
load: function(soundId) {
if (typeof Sfx.sounds[soundId] != 'undefined') {
return Sfx.sounds[soundId];
}
console.info('[SFX] Loading sound effect', soundId);
Sfx.sounds[soundId] = new Audio('assets/sfx/' + soundId + '.wav');
Sfx.sounds[soundId].load();
return Sfx.sounds[soundId];
},
play: function(soundId) {
if (typeof Sfx.sounds[soundId] == 'undefined') {
Sfx.load(soundId);
} else {
Sfx.sounds[soundId].load(); // call load() every time to fix Chrome issue where sound only plays first time
}
Sfx.sounds[soundId].play();
},
pickupDonut: function () { this.play('pickup_donut'); },
pickupVeggie: function () { this.play('pickup_veggie'); },
omNom: function() { this.play('omnom'); },
burp: function() { this.play('burp'); },
puke: function() { this.play('puke'); }
}; | Fix issue where sound effects could be loaded more than once | SFX: Fix issue where sound effects could be loaded more than once
| JavaScript | mit | burningtomatoes/DonutAdventure | ---
+++
@@ -11,9 +11,15 @@
},
load: function(soundId) {
+ if (typeof Sfx.sounds[soundId] != 'undefined') {
+ return Sfx.sounds[soundId];
+ }
+
console.info('[SFX] Loading sound effect', soundId);
+
Sfx.sounds[soundId] = new Audio('assets/sfx/' + soundId + '.wav');
Sfx.sounds[soundId].load();
+
return Sfx.sounds[soundId];
},
|
493f77885ca21a669e88e1e91b0249421ac5719c | actions/navigate.js | actions/navigate.js | import {NAVIGATE} from './actions'
import {loadRegionByCode} from './region'
/* Action creators */
export function navigate(match = {}) {
return dispatch => {
const {params} = match
if (params.region) {
dispatch(loadRegionByCode(params.region))
}
dispatch({
type: NAVIGATE,
match
})
}
}
| import {NAVIGATE} from './actions'
import {loadRegionByCode} from './region'
/* Action creators */
export function navigate(match = {}) {
return dispatch => {
const {params} = match
if (params.region) {
const [regionCode] = params.region.split('-')
dispatch(loadRegionByCode(regionCode))
}
dispatch({
type: NAVIGATE,
match
})
}
}
| Allow region name in region part of url | Allow region name in region part of url
| JavaScript | mit | bengler/imdikator,bengler/imdikator | ---
+++
@@ -6,7 +6,8 @@
return dispatch => {
const {params} = match
if (params.region) {
- dispatch(loadRegionByCode(params.region))
+ const [regionCode] = params.region.split('-')
+ dispatch(loadRegionByCode(regionCode))
}
dispatch({
type: NAVIGATE, |
9b4f0e418b60c136dac27644ae95d3f724e74443 | Resources/windows/webview_advanced.js | Resources/windows/webview_advanced.js | W.WebviewAdvanced = function() {
var win = UI.Win({
title:'Better Web View'
});
var webview = Ti.UI.createWebView({
url:'http://www.nytimes.com'
});
return win;
}
| W.WebviewAdvanced = function() {
var win = UI.Win({
title:'Better Web View',
layout:'vertical'
});
var webview = Ti.UI.createWebView({
url:'http://www.nytimes.com',
height:'200',
willHandleTouches:false
});
/**
* Styling of the iOS button bar is somewhat limited.
*/
var buttons = [
{
title:'Back',
enabled:false,
width:100,
},
{
title:'Forward',
enabled:false,
width:100,
},
{
title:'Reload',
enabled:true,
width:100,
}
];
var buttonBar = Ti.UI.createButtonBar({
left:10,
top:30,
labels:buttons,
backgroundColor:'#336699',
style:Ti.UI.iPhone.SystemButtonStyle.PLAIN,
widht:200,
height:25
});
win.add(webview);
win.add(buttonBar);
buttonBar.addEventListener('click', function(e) {
switch (e.index) {
case 0:
if (webview.canGoBack()) {
Ti.API.info('Webview went one page back');
webview.goBack();
}
else {
Ti.API.info('This webview cannot go any further back');
}
break;
case 1:
if (webview.canGoForward()) {
Ti.API.info('Webview went one page forward');
webview.goForward();
}
else {
Ti.API.info('This webview cannot go any further forward');
}
break;
case 2:
webview.url = webview.url; // workaround, @see http://developer.appcelerator.com/question/126916/how-to-luck-url-in-webviewreload
webview.reload();
Ti.API.info('This webview was just reloaded');
break;
}
});
// Change the enabled status of the backwards and forwards
// buttons in the button bar.
webview.addEventListener('load', function(e) {
Ti.API.info(JSON.stringify(this));
buttons[0].enabled = (this.canGoBack()) ? true : false;
buttons[1].enabled = (this.canGoForward()) ? true : false;
buttonBar.setLabels(buttons);
})
return win;
}
| Add advanced example with remote webview, including back, forward, and reload buttons. | Add advanced example with remote webview, including back, forward, and reload buttons.
| JavaScript | apache-2.0 | danielhanold/DannySink | ---
+++
@@ -1,11 +1,84 @@
W.WebviewAdvanced = function() {
var win = UI.Win({
- title:'Better Web View'
+ title:'Better Web View',
+ layout:'vertical'
});
var webview = Ti.UI.createWebView({
- url:'http://www.nytimes.com'
+ url:'http://www.nytimes.com',
+ height:'200',
+ willHandleTouches:false
});
+
+ /**
+ * Styling of the iOS button bar is somewhat limited.
+ */
+ var buttons = [
+ {
+ title:'Back',
+ enabled:false,
+ width:100,
+ },
+ {
+ title:'Forward',
+ enabled:false,
+ width:100,
+ },
+ {
+ title:'Reload',
+ enabled:true,
+ width:100,
+ }
+ ];
+ var buttonBar = Ti.UI.createButtonBar({
+ left:10,
+ top:30,
+ labels:buttons,
+ backgroundColor:'#336699',
+ style:Ti.UI.iPhone.SystemButtonStyle.PLAIN,
+ widht:200,
+ height:25
+ });
+
+ win.add(webview);
+ win.add(buttonBar);
+
+ buttonBar.addEventListener('click', function(e) {
+ switch (e.index) {
+ case 0:
+ if (webview.canGoBack()) {
+ Ti.API.info('Webview went one page back');
+ webview.goBack();
+ }
+ else {
+ Ti.API.info('This webview cannot go any further back');
+ }
+ break;
+ case 1:
+ if (webview.canGoForward()) {
+ Ti.API.info('Webview went one page forward');
+ webview.goForward();
+ }
+ else {
+ Ti.API.info('This webview cannot go any further forward');
+ }
+ break;
+ case 2:
+ webview.url = webview.url; // workaround, @see http://developer.appcelerator.com/question/126916/how-to-luck-url-in-webviewreload
+ webview.reload();
+ Ti.API.info('This webview was just reloaded');
+ break;
+ }
+ });
+
+ // Change the enabled status of the backwards and forwards
+ // buttons in the button bar.
+ webview.addEventListener('load', function(e) {
+ Ti.API.info(JSON.stringify(this));
+ buttons[0].enabled = (this.canGoBack()) ? true : false;
+ buttons[1].enabled = (this.canGoForward()) ? true : false;
+ buttonBar.setLabels(buttons);
+ })
return win;
} |
ec289fd479b68b6236e52d7e130d169fc0c6173a | app/components/Footer.js | app/components/Footer.js | import { h } from 'preact'
import InfoIcon from '../icons/InfoIcon'
import DescriptionIcon from '../icons/DescriptionIcon'
function Footer({
title,
date,
showTitle,
showInfo,
onTitleClick,
onToggleClick
}) {
const footerVisibility = showTitle ? 'show' : ''
let toggleButtonClasses = ['btn']
if (showInfo) toggleButtonClasses.push('active')
return (
<footer class="footer-container">
<div class="footer-icon">
<a class="btn" onClick={onTitleClick}>
<InfoIcon />
</a>
</div>
<div class={`footer ${footerVisibility}`}>
<div class="footer-inner">
<span class="footer-title">{title}</span>
</div>
</div>
<div class="footer-icon">
<a class={toggleButtonClasses.join(' ')} onClick={onToggleClick}>
<DescriptionIcon />
<span class="btn-text">Details</span>
</a>
</div>
</footer>
)
}
export default Footer
| import { h } from 'preact'
import InfoIcon from '../icons/InfoIcon'
import DescriptionIcon from '../icons/DescriptionIcon'
function Footer({
title,
date,
showTitle,
showInfo,
onTitleClick,
onToggleClick
}) {
const footerVisibility = showTitle ? 'show' : ''
let toggleButtonClasses = ['btn']
if (showInfo) toggleButtonClasses.push('active')
return (
<footer class="footer-container">
<div class="footer-icon">
<a class="btn" onClick={onTitleClick}>
<InfoIcon />
<span class="btn-text">Title</span>
</a>
</div>
<div class={`footer ${footerVisibility}`}>
<div class="footer-inner">
<span class="footer-title">{title}</span>
</div>
</div>
<div class="footer-icon">
<a class={toggleButtonClasses.join(' ')} onClick={onToggleClick}>
<DescriptionIcon />
<span class="btn-text">Details</span>
</a>
</div>
</footer>
)
}
export default Footer
| Add button title to the footer "Title" | Add button title to the footer "Title"
| JavaScript | bsd-2-clause | Nafta7/the-pod,Nafta7/the-pod | ---
+++
@@ -20,6 +20,7 @@
<div class="footer-icon">
<a class="btn" onClick={onTitleClick}>
<InfoIcon />
+ <span class="btn-text">Title</span>
</a>
</div>
<div class={`footer ${footerVisibility}`}> |
138557c65691fe80e6d5046a70ad8845af4e8dea | app.js | app.js | /*eslint-env node*/
//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------
// This application uses express as its web server
// for more info, see: http://expressjs.com
var express = require('express');
// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');
// create a new express server
var app = express();
// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();
// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
// print a message when the server starts listening
console.log("server starting on " + appEnv.url);
});
| /*eslint-env node*/
//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------
// This application uses express as its web server
// for more info, see: http://expressjs.com
var express = require('express');
// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');
// create a new express server
var app = express();
// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();
var Botkit = require('botkit')
var controller = Botkit.slackbot({
debug: false
})
var bot = controller.spawn({
token: "xoxb-25814718499-sXqQ27waMvKPtS67uozQQ1mR"
}).startRTM()
controller.hears(['(task|story|epic|defect) (\d*)'],'ambient',function(bot, message){
var matches = message.text.match(/(task|story|epic|defect) (\d*)/i)
var id = matches[2]
bot.reply(message, "https://jazz306.hursley.ibm.com:9443/ccm/resource/itemName/com.ibm.team.workitem.WorkItem/"+id)
})
// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
// print a message when the server starts listening
console.log("server starting on " + appEnv.url);
});
| Add botkit and listener for RTC based messages | Add botkit and listener for RTC based messages
| JavaScript | apache-2.0 | crshnburn/rtc-slack-bot | ---
+++
@@ -21,6 +21,21 @@
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();
+var Botkit = require('botkit')
+var controller = Botkit.slackbot({
+ debug: false
+})
+
+var bot = controller.spawn({
+ token: "xoxb-25814718499-sXqQ27waMvKPtS67uozQQ1mR"
+}).startRTM()
+
+controller.hears(['(task|story|epic|defect) (\d*)'],'ambient',function(bot, message){
+ var matches = message.text.match(/(task|story|epic|defect) (\d*)/i)
+ var id = matches[2]
+ bot.reply(message, "https://jazz306.hursley.ibm.com:9443/ccm/resource/itemName/com.ibm.team.workitem.WorkItem/"+id)
+})
+
// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
|
a4ce6b695e841eb1e3b676408e97614ab80fde9d | app.js | app.js | 'use strict';
require('dotenv').load();
const _ = require('lodash');
const Slack = require('slack-client');
const responses = require('./responses.js');
const slackToken = process.env.SLACK_TOKEN;
const slackChannel = process.env.SLACK_CHANNEL;
const autoReconnect = true;
const autoMark = true;
let slack = new Slack(slackToken, autoReconnect, autoMark);
slack.on('open', function() {
console.log('Connected to ' + slack.team.name + ' as ' + slack.self.name);
});
slack.on('message', function(message) {
console.log('Received: ' + message);
let channel = slack.getChannelGroupOrDMByID(message.channel);
if (!channel) return;
let user = slack.getUserByID(message.user);
if (!user) return;
// Only respond in the specified channel or to individual users
if (!channel.is_channel || channel.name === slackChannel) {
if (message.text.match(/praise koffee/ig)) {
let res = '༼ つ ◕_◕ ༽つ ☕️';
console.log('Response: ' + res);
channel.send(res);
} else if (message.text.match(/c/ig)) {
let res = _.sample(responses)('@' + user.name);
console.log('Response: ' + res);
channel.send(res);
}
}
});
slack.on('error', function(err) {
console.error('Error', err);
});
slack.login();
| 'use strict';
require('dotenv').load();
const _ = require('lodash');
const Slack = require('slack-client');
const responses = require('./responses.js');
const slackToken = process.env.SLACK_TOKEN;
const slackChannel = process.env.SLACK_CHANNEL;
const autoReconnect = true;
const autoMark = true;
let slack = new Slack(slackToken, autoReconnect, autoMark);
function sendResponse(channel, message) {
console.log('Response: ' + message);
channel.send(message);
}
slack.on('open', function() {
console.log('Connected to ' + slack.team.name + ' as ' + slack.self.name);
});
slack.on('message', function(message) {
console.log('Received: ' + message);
let channel = slack.getChannelGroupOrDMByID(message.channel);
if (!channel) return;
let user = slack.getUserByID(message.user);
if (!user) return;
// Only respond in the specified channel or to individual users
if (!channel.is_channel || channel.name === slackChannel) {
if (message.text.match(/praise koffee/ig)) {
sendResponse(channel, '༼ つ ◕_◕ ༽つ ☕️');
} else if (message.text.match(/c/ig)) {
sendResponse(channel, _.sample(responses)('@' + user.name));
}
}
});
slack.on('error', function(err) {
console.error('Error', err);
});
slack.login();
| Refactor sending slack response to its own function | Refactor sending slack response to its own function
| JavaScript | mit | dpca/koffee-kustodian | ---
+++
@@ -11,6 +11,11 @@
const autoMark = true;
let slack = new Slack(slackToken, autoReconnect, autoMark);
+
+function sendResponse(channel, message) {
+ console.log('Response: ' + message);
+ channel.send(message);
+}
slack.on('open', function() {
console.log('Connected to ' + slack.team.name + ' as ' + slack.self.name);
@@ -27,13 +32,9 @@
// Only respond in the specified channel or to individual users
if (!channel.is_channel || channel.name === slackChannel) {
if (message.text.match(/praise koffee/ig)) {
- let res = '༼ つ ◕_◕ ༽つ ☕️';
- console.log('Response: ' + res);
- channel.send(res);
+ sendResponse(channel, '༼ つ ◕_◕ ༽つ ☕️');
} else if (message.text.match(/c/ig)) {
- let res = _.sample(responses)('@' + user.name);
- console.log('Response: ' + res);
- channel.send(res);
+ sendResponse(channel, _.sample(responses)('@' + user.name));
}
}
}); |
8bce467d01b1c4d0c5b35cc3bb707071c92085de | bot.js | bot.js | 'use strict';
var config = {
channels: [ '#kokarn' ],
server: 'irc.freenode.net',
botName: 'KokBot'
},
irc = require( 'irc' ),
bot = new irc.Client( config.server, config.botName, {
channels: config.channels
} ),
dagensMix = new ( require( './DagensMix.botplug.js' ) )(),
gitHub = require( './GitHub.botplug.js' ),
pushbullet = require( './Pushbullet.botplug.js' ),
rss = require( './RSS.botplug.js' ),
urlchecker = require( './Urlchecker.botplug.js' );
dagensMix.addBot( bot );
gitHub.setup( bot );
pushbullet.setup( bot );
urlchecker.setup( bot );
rss.setup( bot );
bot.addListener( 'error', function( message ){
console.log( 'error: ', message );
});
| 'use strict';
var config = {
channels: [ '#kokarn' ],
server: 'irc.freenode.net',
botName: 'BoilBot'
},
irc = require( 'irc' ),
bot = new irc.Client( config.server, config.botName, {
channels: config.channels
} ),
dagensMix = new ( require( './DagensMix.botplug.js' ) )(),
gitHub = require( './GitHub.botplug.js' ),
pushbullet = require( './Pushbullet.botplug.js' ),
rss = require( './RSS.botplug.js' ),
urlchecker = require( './Urlchecker.botplug.js' );
dagensMix.addBot( bot );
gitHub.setup( bot );
pushbullet.setup( bot );
urlchecker.setup( bot );
rss.setup( bot );
bot.addListener( 'error', function( message ){
console.log( 'error: ', message );
});
| Make sure the name is up to date | Make sure the name is up to date
| JavaScript | mit | kokarn/KokBot | ---
+++
@@ -2,7 +2,7 @@
var config = {
channels: [ '#kokarn' ],
server: 'irc.freenode.net',
- botName: 'KokBot'
+ botName: 'BoilBot'
},
irc = require( 'irc' ),
bot = new irc.Client( config.server, config.botName, { |
51fea8ec6bc126fb6d724c76ae84f416e7d51c02 | program.js | program.js | var result = 0;
for (var i = 2; i < process.argv.length; i++) {
result += Number(process.argv[i]);
};
console.log(result) | var fs = require('fs');
var filePath = process.argv[2];
var fileContents = fs.readFileSync(filePath).toString();
var numberOfLines = fileContents.split('\n').length;
console.log(numberOfLines-1);
| Complete Lesson 2 - Read a file | Complete Lesson 2 - Read a file
| JavaScript | apache-2.0 | Ashtonians-Academy/nodeschool.io-learnyounode | ---
+++
@@ -1,6 +1,7 @@
-var result = 0;
-for (var i = 2; i < process.argv.length; i++) {
- result += Number(process.argv[i]);
-};
+var fs = require('fs');
+var filePath = process.argv[2];
+var fileContents = fs.readFileSync(filePath).toString();
-console.log(result)
+var numberOfLines = fileContents.split('\n').length;
+console.log(numberOfLines-1);
+ |
f100c717fe5370c8c04cb57eefebb32710b397b4 | assets/js/components/MediaErrorHandler/index.stories.js | assets/js/components/MediaErrorHandler/index.stories.js | /**
* MediaErrorHandler Component Stories.
*
* Site Kit by Google, Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import MediaErrorHandler from './';
const ErrorComponent = () => {
throw new Error();
};
const Template = () => (
<MediaErrorHandler>
<ErrorComponent />
</MediaErrorHandler>
);
const NoErrorsTemplate = () => (
<MediaErrorHandler>
<div>There are no errors here.</div>
</MediaErrorHandler>
);
export const Default = Template.bind( {} );
Default.storyName = 'Default';
Default.scenario = {
label: 'Global/MediaErrorHandler',
};
export const NoErrors = NoErrorsTemplate.bind( {} );
NoErrors.storyName = 'No Errors';
export default {
title: 'Components/MediaErrorHandler',
component: MediaErrorHandler,
};
| /**
* MediaErrorHandler Component Stories.
*
* Site Kit by Google, Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import MediaErrorHandler from './';
const ErrorComponent = () => {
throw new Error();
};
const Template = ( args ) => (
<MediaErrorHandler { ...args }>
<ErrorComponent />
</MediaErrorHandler>
);
const NoErrorsTemplate = () => (
<MediaErrorHandler>
<div>There are no errors here.</div>
</MediaErrorHandler>
);
export const Default = Template.bind( {} );
Default.storyName = 'Default';
Default.scenario = {
label: 'Global/MediaErrorHandler',
};
export const WithCustomErrorMessage = Template.bind( {} );
WithCustomErrorMessage.storyName = 'With Custom Error Message';
WithCustomErrorMessage.args = {
errorMessage: 'This is a custom error message 🐞',
};
export const NoErrors = NoErrorsTemplate.bind( {} );
NoErrors.storyName = 'No Errors';
export default {
title: 'Components/MediaErrorHandler',
component: MediaErrorHandler,
};
| Add With Custom Error Message story. | Add With Custom Error Message story.
| JavaScript | apache-2.0 | google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp | ---
+++
@@ -25,8 +25,8 @@
throw new Error();
};
-const Template = () => (
- <MediaErrorHandler>
+const Template = ( args ) => (
+ <MediaErrorHandler { ...args }>
<ErrorComponent />
</MediaErrorHandler>
);
@@ -43,6 +43,12 @@
label: 'Global/MediaErrorHandler',
};
+export const WithCustomErrorMessage = Template.bind( {} );
+WithCustomErrorMessage.storyName = 'With Custom Error Message';
+WithCustomErrorMessage.args = {
+ errorMessage: 'This is a custom error message 🐞',
+};
+
export const NoErrors = NoErrorsTemplate.bind( {} );
NoErrors.storyName = 'No Errors';
|
a4bf60559bab0e91e66c4dcc79fbcad3509f9e76 | seava.e4e.impl/src/main/resources/webapp/js/e4e/dc/command/DcEditInCommand.js | seava.e4e.impl/src/main/resources/webapp/js/e4e/dc/command/DcEditInCommand.js | /**
* DNet eBusiness Suite. Copyright: Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
Ext.define("e4e.dc.command.DcEditInCommand", {
extend : "e4e.dc.command.AbstractDcSyncCommand",
dcApiMethod : e4e.dc.DcActionsFactory.EDIT_IN,
onExecute : function(options) {
var dc = this.dc;
if (dc.trackEditMode) {
dc.isEditMode = true;
}
dc.fireEvent("onEditIn", dc, options);
},
isActionAllowed : function() {
if (this.dc.record == null) {
this.dc.warning(Main.msg.NO_CURRENT_RECORD, "msg");
return false;
}
return true;
}
});
| /**
* DNet eBusiness Suite. Copyright: Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
Ext.define("e4e.dc.command.DcEditInCommand", {
extend : "e4e.dc.command.AbstractDcSyncCommand",
dcApiMethod : e4e.dc.DcActionsFactory.EDIT_IN,
onExecute : function(options) {
var dc = this.dc;
if (dc.trackEditMode) {
dc.isEditMode = true;
}
dc.fireEvent("onEditIn", dc, options);
}
});
| Allow edit-in command even without a current record | Allow edit-in command even without a current record | JavaScript | apache-2.0 | seava/seava.lib.e4e | ---
+++
@@ -13,13 +13,5 @@
dc.isEditMode = true;
}
dc.fireEvent("onEditIn", dc, options);
- },
-
- isActionAllowed : function() {
- if (this.dc.record == null) {
- this.dc.warning(Main.msg.NO_CURRENT_RECORD, "msg");
- return false;
- }
- return true;
}
}); |
ffb2d0b4eec9691daced7f48745fc874808ba257 | lib/checker.js | lib/checker.js | var childProcess = require('child_process');
var rimraf = require('rimraf');
var jscs = require('jscs');
var fs = require('fs');
var os = require('os');
var tmpDir = process.cwd() + '/'; //os.tmpDir();
module.exports.check = function (repo) {
var fullPath = tmpDir + repo.name;
var options = {
cwd: tmpDir
};
// Just clone the latest commit since that's all we need
childProcess.exec('git clone --depth 1 ' + repo.clone_url, options, function () {
var config = {};
console.log(config);
rimraf(fullPath, function () {});
});
};
| var childProcess = require('child_process');
var rimraf = require('rimraf');
var jscs = require('jscs');
var fs = require('fs');
var os = require('os');
var tmpDir = os.tmpDir();
module.exports.check = function (repo) {
var fullPath = tmpDir + repo.name;
var options = {
cwd: tmpDir
};
// Just clone the latest commit since that's all we need
childProcess.exec('git clone --depth 1 ' + repo.clone_url, options, function () {
var config = {};
console.log('Cloning ' + repo.clone_url, fullPath);
rimraf(fullPath, function () {});
});
};
| Make it a bit more talkative | Make it a bit more talkative
| JavaScript | mit | jwilsson/cs-checker,jwilsson/cs-checker | ---
+++
@@ -4,7 +4,7 @@
var fs = require('fs');
var os = require('os');
-var tmpDir = process.cwd() + '/'; //os.tmpDir();
+var tmpDir = os.tmpDir();
module.exports.check = function (repo) {
var fullPath = tmpDir + repo.name;
@@ -16,7 +16,7 @@
childProcess.exec('git clone --depth 1 ' + repo.clone_url, options, function () {
var config = {};
- console.log(config);
+ console.log('Cloning ' + repo.clone_url, fullPath);
rimraf(fullPath, function () {});
}); |
e6ec3db66293376c13410d9602878d0b8c835e37 | Website/js/main.js | Website/js/main.js | const BASEURL = "http://0.0.0.0:3000";
$(function(){
$("#get-btn").click(function(){
console.log("GET");
$.get("http://mean-quote-machine.herokuapp.com/get_random_quote", function(data) {
var json = JSON.parse(JSON.stringify(data));
var author = json.quote.author;
var text = json.quote.text;
$("#quote-author").text(author);
$("#quote-text").text(text);
});
});
$("#post-btn").click(function(){
console.log("POST");
});
});
| const BASEURL = "http://0.0.0.0:3000";
$(function(){
$("#get-btn").click(function(){
console.log("GET");
$.ajax({
type: "GET",
url: "http://mean-quote-machine.herokuapp.com/get_random_quote",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function(data) {
var json = JSON.parse(JSON.stringify(data));
var author = json.quote.author;
var text = json.quote.text;
$("#quote-author").text(author);
$("#quote-text").text(text);
},
error: function(error) {
console.error(error);
}
});
});
$("#post-btn").click(function(){
console.log("POST");
var tmp = JSON.stringify({
"author": "Robin Flygare and Anthon Holmqvist",
"text": "Minopt"
});
console.log(tmp);
$.ajax({
type: "POST",
url: "http://localhost:1880/",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
data: tmp,
success: function(data) {
var json = JSON.parse(JSON.stringify(data));
var author = json.quote.author;
var text = json.quote.text;
$("#quote-author").text(author);
$("#quote-text").text(text);
},
error: function(error) {
console.error(error);
}
});
});
});
| Add code for send POST request | Add code for send POST request
| JavaScript | mit | flygare/Minopt,flygare/Minopt,flygare/Minopt | ---
+++
@@ -3,17 +3,51 @@
$(function(){
$("#get-btn").click(function(){
console.log("GET");
- $.get("http://mean-quote-machine.herokuapp.com/get_random_quote", function(data) {
- var json = JSON.parse(JSON.stringify(data));
- var author = json.quote.author;
- var text = json.quote.text;
+ $.ajax({
+ type: "GET",
+ url: "http://mean-quote-machine.herokuapp.com/get_random_quote",
+ contentType: "application/json; charset=utf-8",
+ dataType: "jsonp",
+ success: function(data) {
+ var json = JSON.parse(JSON.stringify(data));
+ var author = json.quote.author;
+ var text = json.quote.text;
- $("#quote-author").text(author);
- $("#quote-text").text(text);
+ $("#quote-author").text(author);
+ $("#quote-text").text(text);
+ },
+ error: function(error) {
+ console.error(error);
+ }
});
});
$("#post-btn").click(function(){
console.log("POST");
+ var tmp = JSON.stringify({
+ "author": "Robin Flygare and Anthon Holmqvist",
+ "text": "Minopt"
+ });
+
+ console.log(tmp);
+
+ $.ajax({
+ type: "POST",
+ url: "http://localhost:1880/",
+ contentType: "application/json; charset=utf-8",
+ dataType: "jsonp",
+ data: tmp,
+ success: function(data) {
+ var json = JSON.parse(JSON.stringify(data));
+ var author = json.quote.author;
+ var text = json.quote.text;
+
+ $("#quote-author").text(author);
+ $("#quote-text").text(text);
+ },
+ error: function(error) {
+ console.error(error);
+ }
+ });
});
}); |
37aa2c5f5f29cad068af525c6a941a76c34829af | tests/helpers/run-gist.js | tests/helpers/run-gist.js | export default function(app, files) {
const login = "Gaurav0";
const gist_id = "35de43cb81fc35ddffb2";
const commit = "f354c6698b02fe3243656c8dc5aa0303cc7ae81c";
files.push({
filename: "initializers.setup-test.js",
content: "import Ember from 'ember';\n\nexport default {\n name: 'setup-test',\n initialize: function(container, app) {\n app.setupForTesting();\n app.injectTestHelpers();\n window.QUnit = window.parent.QUnit;\n }\n};"
});
let gistFiles = {};
files.forEach(function(file) {
let gistFile = server.create('gist-file', {
filename: file.filename,
login: login,
gist_id: gist_id,
commit: commit,
content: file.content
});
gistFiles[gistFile.filename] = gistFile;
});
server.create('user', {login: login});
const owner = server.create('owner', {login: login});
server.create('gist', {
id: gist_id,
owner: owner,
files: gistFiles
});
visit('/35de43cb81fc35ddffb2');
return waitForLoadedIFrame();
}
| export default function(app, files) {
const login = "Gaurav0";
const gist_id = "35de43cb81fc35ddffb2";
const commit = "f354c6698b02fe3243656c8dc5aa0303cc7ae81c";
files.push({
filename: "initializers.setup-test.js",
content: `
import Ember from 'ember';
export default {
name: 'setup-test',
initialize: function() {
var app = arguments[1] || arguments[0];
app.setupForTesting();
app.injectTestHelpers();
window.QUnit = window.parent.QUnit;
}
};
`
});
let gistFiles = {};
files.forEach(function(file) {
let gistFile = server.create('gist-file', {
filename: file.filename,
login: login,
gist_id: gist_id,
commit: commit,
content: file.content
});
gistFiles[gistFile.filename] = gistFile;
});
server.create('user', {login: login});
const owner = server.create('owner', {login: login});
server.create('gist', {
id: gist_id,
owner: owner,
files: gistFiles
});
visit('/35de43cb81fc35ddffb2');
return waitForLoadedIFrame();
}
| Fix initializer warning when testing against Ember 2.1. | Fix initializer warning when testing against Ember 2.1.
| JavaScript | mit | pangratz/ember-twiddle,vikram7/ember-twiddle,vikram7/ember-twiddle,Gaurav0/ember-twiddle,ember-cli/ember-twiddle,ember-cli/ember-twiddle,ember-cli/ember-twiddle,Gaurav0/ember-twiddle,Gaurav0/ember-twiddle,knownasilya/ember-twiddle,knownasilya/ember-twiddle,pangratz/ember-twiddle,knownasilya/ember-twiddle,pangratz/ember-twiddle,vikram7/ember-twiddle | ---
+++
@@ -5,7 +5,21 @@
files.push({
filename: "initializers.setup-test.js",
- content: "import Ember from 'ember';\n\nexport default {\n name: 'setup-test',\n initialize: function(container, app) {\n app.setupForTesting();\n app.injectTestHelpers();\n window.QUnit = window.parent.QUnit;\n }\n};"
+ content: `
+ import Ember from 'ember';
+
+ export default {
+ name: 'setup-test',
+ initialize: function() {
+ var app = arguments[1] || arguments[0];
+
+ app.setupForTesting();
+ app.injectTestHelpers();
+
+ window.QUnit = window.parent.QUnit;
+ }
+ };
+ `
});
let gistFiles = {}; |
6055c542aacf2d4c77d3a69f0dc3cb7dc7a1dca1 | app/itemDatabase.js | app/itemDatabase.js | const logger = require('logger');
const weapon = require('weapon.js');
class ItemDatabase {
constructor(itemType) {
this.itemType = itemType;
this.itemMap = new Map();
fateBus.subscribe(module, 'fate.'+this.itemType+'DataFetched', this.refresh.bind(this));
}
refresh(message, newItemData) {
this.itemMap.clear();
const dataLines = newItemData.split(/[\r\n]+/);
for (let line of dataLines) {
this.createItemFromData(line.split('\t'));
}
logger.log('itemDatabase.js ('+this.itemType+'): Found ('+(dataLines.length-1)+') items');
}
createItemFromData(data) {
// Overidden in subclasses
}
contains(itemName) {
return this.itemMap.has(itemName);
}
get(itemName) {
return this.itemMap.get(itemName);
}
}
exports.ItemDatabase = ItemDatabase;
| const logger = require('logger');
const weapon = require('weapon.js');
class ItemDatabase {
constructor(itemType) {
this.itemType = itemType;
this.itemMap = new Map();
fateBus.subscribe(module, 'fate.'+this.itemType+'DataFetched', this.refresh.bind(this));
}
refresh(message, newItemData) {
this.itemMap.clear();
const dataLines = newItemData.split(/[\r\n]+/);
for (let line of dataLines) {
this.createItemFromData(line.split('\t'));
}
logger.log('itemDatabase.js ('+this.itemType+'): Found ('+(dataLines.length)+') items');
}
createItemFromData(data) {
// Overidden in subclasses
}
contains(itemName) {
return this.itemMap.has(itemName);
}
get(itemName) {
return this.itemMap.get(itemName);
}
}
exports.ItemDatabase = ItemDatabase;
| Correct typo in logging count of items | Correct typo in logging count of items
| JavaScript | mit | rslifka/fate_of_all_fools,rslifka/fate_of_all_fools | ---
+++
@@ -17,7 +17,7 @@
this.createItemFromData(line.split('\t'));
}
- logger.log('itemDatabase.js ('+this.itemType+'): Found ('+(dataLines.length-1)+') items');
+ logger.log('itemDatabase.js ('+this.itemType+'): Found ('+(dataLines.length)+') items');
}
createItemFromData(data) { |
21d14f17981c405437c8b3314f941b0d50e8ce38 | JavaScript/DynamicLoading/scripts/loader.js | JavaScript/DynamicLoading/scripts/loader.js | /* globals Demo, console, require */
Demo = {
input: {},
components: {},
renderer: {}
};
Demo.loader = (function() {
'use strict';
function loadScripts(sources, onComplete, message) {
require(sources, function() {
onComplete(message);
});
}
function inputsComplete() {
loadScripts(['Components/Text'], componentsComplete, 'Components loaded');
}
function componentsComplete() {
loadScripts(['Rendering/core', 'Rendering/Text'], renderingComplete, 'Rendering loaded');
}
function renderingComplete() {
loadScripts(['model'], modelComplete, 'Model loaded');
}
function modelComplete() {
loadScripts(['main'], mainComplete, 'Main loaded');
}
function mainComplete() {
console.log('it is all loaded up');
Demo.main.initialize();
}
//
// Start with the input scripts, the cascade from there
console.log('Starting to dynamically load project scripts');
loadScripts(['Input/Mouse', 'Input/Keyboard'], inputsComplete, 'Inputs loaded');
}());
| /* globals Demo, console, require */
Demo = {
input: {},
components: {},
renderer: {}
};
Demo.loader = (function() {
'use strict';
function loadScripts(sources, onComplete, message) {
require(sources, function() {
console.log(message);
onComplete();
});
}
function inputsComplete() {
loadScripts(['Components/Text'], componentsComplete, 'Components loaded');
}
function componentsComplete() {
loadScripts(['Rendering/core'], coreRenderingComplete, 'Rendering core loaded');
}
function coreRenderingComplete() {
loadScripts(['Rendering/Text'], renderingComplete, 'Rendering loaded');
}
function renderingComplete() {
loadScripts(['model'], modelComplete, 'Model loaded');
}
function modelComplete() {
loadScripts(['main'], mainComplete, 'Main loaded');
}
function mainComplete() {
console.log('it is all loaded up');
Demo.main.initialize();
}
//
// Start with the input scripts, the cascade from there
console.log('Starting to dynamically load project scripts');
loadScripts(['Input/Keyboard'], inputsComplete, 'Inputs loaded');
}());
| Update to the loading dependencies...load the core rendering before the text rendering. | Update to the loading dependencies...load the core rendering before the text rendering.
| JavaScript | mit | ProfPorkins/GameTech,ProfPorkins/GameTech,ProfPorkins/GameTech | ---
+++
@@ -12,7 +12,8 @@
function loadScripts(sources, onComplete, message) {
require(sources, function() {
- onComplete(message);
+ console.log(message);
+ onComplete();
});
}
@@ -21,7 +22,11 @@
}
function componentsComplete() {
- loadScripts(['Rendering/core', 'Rendering/Text'], renderingComplete, 'Rendering loaded');
+ loadScripts(['Rendering/core'], coreRenderingComplete, 'Rendering core loaded');
+ }
+
+ function coreRenderingComplete() {
+ loadScripts(['Rendering/Text'], renderingComplete, 'Rendering loaded');
}
function renderingComplete() {
@@ -40,5 +45,5 @@
//
// Start with the input scripts, the cascade from there
console.log('Starting to dynamically load project scripts');
- loadScripts(['Input/Mouse', 'Input/Keyboard'], inputsComplete, 'Inputs loaded');
+ loadScripts(['Input/Keyboard'], inputsComplete, 'Inputs loaded');
}()); |
117790494171529fb3a742816b626adc6a15baa1 | app/scripts/main.js | app/scripts/main.js | 'use strict';
var m = require('mithril');
var attachFastClick = require('fastclick');
var GameComponent = require('./components/game');
m.mount(document.getElementById('app'), GameComponent);
attachFastClick(document.body);
// Load service worker to enable offline access
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js');
}
| 'use strict';
var m = require('mithril');
var attachFastClick = require('fastclick');
var GameComponent = require('./components/game');
m.mount(document.getElementById('app'), GameComponent);
attachFastClick(document.body);
// Load service worker to enable offline access
if (navigator.serviceWorker) {
navigator.serviceWorker.register('service-worker.js');
}
| Use property access instead of 'in' to detect SW | Use property access instead of 'in' to detect SW
| JavaScript | mit | caleb531/connect-four | ---
+++
@@ -8,6 +8,6 @@
attachFastClick(document.body);
// Load service worker to enable offline access
-if ('serviceWorker' in navigator) {
+if (navigator.serviceWorker) {
navigator.serviceWorker.register('service-worker.js');
} |
173ef9f80ca7a96b6fa8f3435b9c3c53c97466d0 | src/wef.core.js | src/wef.core.js | /*!
* Wef
* Copyright (c) 2011 Pablo Escalada
* MIT Licensed
*/
/**
* wef module
*/
(function(global) {
var wef = {
version: "0.0.1"
};
//registering global variable
if(global.wef) {
throw new Error("wef has already been defined");
} else {
global.wef = wef;
}
})(window);
| /*!
* Wef
* Copyright (c) 2011 Pablo Escalada
* MIT Licensed
*/
/**
* wef module
*/
(function(global) {
var wef = {
version: "0.0.1",
extend: function (receiver, giver) {
var tmp = receiver;
//both must be objects
if (typeof receiver == typeof giver == "object") {
if (tmp == null) {
tmp = {};
}
if (receiver == null) {
return tmp;
}
for (var property in giver) {
tmp.property = giver.property;
}
return tmp
}
throw new Error("InvalidArgumentException: incorrect argument type");
}
};
//registering global variable
if (global.wef) {
throw new Error("wef has already been defined");
} else {
global.wef = wef;
}
})(window);
| Add wef.extend(). Only handle plain objects | Add wef.extend(). Only handle plain objects
| JavaScript | mit | diesire/wef,diesire/wef,diesire/wef | ---
+++
@@ -9,11 +9,28 @@
*/
(function(global) {
var wef = {
- version: "0.0.1"
+ version: "0.0.1",
+ extend: function (receiver, giver) {
+ var tmp = receiver;
+ //both must be objects
+ if (typeof receiver == typeof giver == "object") {
+ if (tmp == null) {
+ tmp = {};
+ }
+ if (receiver == null) {
+ return tmp;
+ }
+ for (var property in giver) {
+ tmp.property = giver.property;
+ }
+ return tmp
+ }
+ throw new Error("InvalidArgumentException: incorrect argument type");
+ }
};
//registering global variable
- if(global.wef) {
+ if (global.wef) {
throw new Error("wef has already been defined");
} else {
global.wef = wef; |
e865434a82098dae8d1ddf089034b549ed0bcd30 | app/javascript/app/constants/index.js | app/javascript/app/constants/index.js | // auth constants
export const AUTH_USER = 'AUTH_USER';
export const UNAUTH_USER = 'UNAUTH_USER';
export const AUTH_ERROR = 'AUTH_ERROR';
export const SET_USER_DATA = 'SET_USER_DATA';
export const SET_CREDIT_CARDS = 'SET_CREDIT_CARDS';
export const SET_DEFAULT_CARD = 'SET_DEFAULT_CARD';
// products constants
export const SELECT_PRODUCT = 'SELECT_PRODUCT';
export const SET_PRODUCTS = 'SET_PRODUCTS';
export const UPDATE_PRODUCT = 'UPDATE_PRODUCT';
export const LOADING = 'LOADING';
export const LOADING_PER_PAGE = 'LOADING_PER_PAGE';
export const SET_PAGES_PRODUCTS = 'SET_PAGES_PRODUCTS';
export const ADD_PRODUCTS_COLLECTION = 'ADD_PRODUCTS_COLLECTION';
export const SET_PAGES_SHOWING = 'SET_PAGES_SHOWING';
export const ERROR_TO_GET_PRODUCT = 'ERROR_TO_GET_PRODUCT';
// categories constants
export const SET_CATEGORIES = 'SET_CATEGORIES';
export const SELECT_CATEGORY = 'SELECT_CATEGORY';
// Shop constants
export const SET_TOKEN_CARD = 'SET_TOKEN_CARD';
export const SELECT_CARD = 'SELECT_CARD';
export const ADD_PRODUCT_TO_CAR = 'ADD_PRODUCT_TO_CAR' | // auth constants
export const AUTH_USER = 'AUTH_USER';
export const UNAUTH_USER = 'UNAUTH_USER';
export const AUTH_ERROR = 'AUTH_ERROR';
export const SET_USER_DATA = 'SET_USER_DATA';
export const SET_CREDIT_CARDS = 'SET_CREDIT_CARDS';
export const SET_DEFAULT_CARD = 'SET_DEFAULT_CARD';
export const ADD_CREDIT_CARD = 'ADD_CREDIT_CARD';
// products constants
export const SELECT_PRODUCT = 'SELECT_PRODUCT';
export const SET_PRODUCTS = 'SET_PRODUCTS';
export const UPDATE_PRODUCT = 'UPDATE_PRODUCT';
export const LOADING = 'LOADING';
export const LOADING_PER_PAGE = 'LOADING_PER_PAGE';
export const SET_PAGES_PRODUCTS = 'SET_PAGES_PRODUCTS';
export const ADD_PRODUCTS_COLLECTION = 'ADD_PRODUCTS_COLLECTION';
export const SET_PAGES_SHOWING = 'SET_PAGES_SHOWING';
export const ERROR_TO_GET_PRODUCT = 'ERROR_TO_GET_PRODUCT';
// categories constants
export const SET_CATEGORIES = 'SET_CATEGORIES';
export const SELECT_CATEGORY = 'SELECT_CATEGORY';
// Shop constants
export const SET_TOKEN_CARD = 'SET_TOKEN_CARD';
export const SELECT_CARD = 'SELECT_CARD';
export const ADD_PRODUCT_TO_CAR = 'ADD_PRODUCT_TO_CAR' | Add new constans for auth-card actions and shop actions | Add new constans for auth-card actions and shop actions
| JavaScript | mit | GiancarlosIO/ecommerce-book-app,GiancarlosIO/ecommerce-book-app,GiancarlosIO/ecommerce-book-app | ---
+++
@@ -5,6 +5,7 @@
export const SET_USER_DATA = 'SET_USER_DATA';
export const SET_CREDIT_CARDS = 'SET_CREDIT_CARDS';
export const SET_DEFAULT_CARD = 'SET_DEFAULT_CARD';
+export const ADD_CREDIT_CARD = 'ADD_CREDIT_CARD';
// products constants
export const SELECT_PRODUCT = 'SELECT_PRODUCT';
export const SET_PRODUCTS = 'SET_PRODUCTS'; |
f9277043dea042872edd74e42965bd59736ce1f4 | stylus_tests.js | stylus_tests.js |
Tinytest.add("stylus - presence", function(test) {
var div = document.createElement('div');
UI.insert(UI.render(Template.stylus_test_presence), div);
div.style.display = 'block';
document.body.appendChild(div);
var p = div.querySelector('p');
var leftBorder = getStyleProperty(p, 'border-left-style');
test.equal(leftBorder, "dashed");
document.body.removeChild(div);
});
Tinytest.add("stylus - @import", function(test) {
var div = document.createElement('div');
UI.insert(UI.render(Template.stylus_test_import), div);
div.style.display = 'block';
document.body.appendChild(div);
var p = div.querySelector('p');
test.equal(getStyleProperty(p, 'font-size'), "20px");
test.equal(getStyleProperty(p, 'border-left-style'), "dashed");
document.body.removeChild(div);
});
|
Tinytest.add("stylus - presence", function(test) {
var div = document.createElement('div');
UI.render(Template.stylus_test_presence, div);
div.style.display = 'block';
document.body.appendChild(div);
var p = div.querySelector('p');
var leftBorder = getStyleProperty(p, 'border-left-style');
test.equal(leftBorder, "dashed");
document.body.removeChild(div);
});
Tinytest.add("stylus - @import", function(test) {
var div = document.createElement('div');
UI.render(Template.stylus_test_import, div);
div.style.display = 'block';
document.body.appendChild(div);
var p = div.querySelector('p');
test.equal(getStyleProperty(p, 'font-size'), "20px");
test.equal(getStyleProperty(p, 'border-left-style'), "dashed");
document.body.removeChild(div);
});
| Kill UI.insert, make UI.render require DOM node | Kill UI.insert, make UI.render require DOM node | JavaScript | mit | oliverhuangchao/meteor-stylus,mgs/meteor-stylus,mquandalle/meteor-stylus | ---
+++
@@ -2,7 +2,7 @@
Tinytest.add("stylus - presence", function(test) {
var div = document.createElement('div');
- UI.insert(UI.render(Template.stylus_test_presence), div);
+ UI.render(Template.stylus_test_presence, div);
div.style.display = 'block';
document.body.appendChild(div);
@@ -15,7 +15,7 @@
Tinytest.add("stylus - @import", function(test) {
var div = document.createElement('div');
- UI.insert(UI.render(Template.stylus_test_import), div);
+ UI.render(Template.stylus_test_import, div);
div.style.display = 'block';
document.body.appendChild(div);
|
134c46f14ba5e3149832c8ac9374ec3acccda93d | next/pages/index.js | next/pages/index.js | const Index = () => (
<div>
<p>Hello Next.js</p>
</div>
)
export default Index
| // This is the Link API
import Link from 'next/link'
const Index = () => (
<div>
<Link href="/about">
<a>About Page</a>
</Link>
<p>Hello Next.js</p>
</div>
)
export default Index
| Add client side link action | Add client side link action
| JavaScript | mit | yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program | ---
+++
@@ -1,5 +1,11 @@
+// This is the Link API
+import Link from 'next/link'
+
const Index = () => (
<div>
+ <Link href="/about">
+ <a>About Page</a>
+ </Link>
<p>Hello Next.js</p>
</div>
) |
e3333f538bdac8d45f755f3a3aa8b9293fa3a6a6 | routes/get_token_metadata.js | routes/get_token_metadata.js | var Token = require('../models/token').model;
var Bitcoin = require('../lib/bitcoin');
var config = require('../lib/config');
module.exports = function(manager, req, res, next) {
var token = req.params.token;
if (!token) {
res.status(400).json({
message: "Must supply contract token to retrieve metadata"
});
return;
}
new Token({token: token}).fetch({
withRelated: ['balance']
}).then(function (model) {
if (!model) {
res.status(404).json({
message: "Token not found"
});
return;
} else {
manager.checkTokenBalance(token).then(function(balance){
res.status(200).json({
token: token,
compute_units: balance,
bitcoin_address: Bitcoin.generateDeterministicWallet(model.related('balance').id),
compute_units_per_bitcoin: config.get('compute_units_per_bitcoin')
});
});
}
});
};
| var Token = require('../models/token').model;
var Bitcoin = require('../lib/bitcoin');
var config = require('../lib/config');
module.exports = function(manager, req, res, next) {
var token = req.params.token;
if (!token) {
res.status(400).json({
message: "Must supply contract token to retrieve metadata"
});
return;
}
new Token({token: token}).fetch({
withRelated: ['balance', 'contract']
}).then(function (model) {
if (!model) {
res.status(404).json({
message: "Token not found"
});
return;
} else {
manager.checkTokenBalance(token).then(function(balance){
res.status(200).json({
token: token,
hash: model.related('contract').get('hash'),
compute_units: balance,
bitcoin_address: Bitcoin.generateDeterministicWallet(model.related('balance').id),
compute_units_per_bitcoin: config.get('compute_units_per_bitcoin')
});
});
}
});
};
| Return hash with contract metadata | [TASK] Return hash with contract metadata
| JavaScript | isc | codius/codius-host,codius/codius-host | ---
+++
@@ -13,7 +13,7 @@
}
new Token({token: token}).fetch({
- withRelated: ['balance']
+ withRelated: ['balance', 'contract']
}).then(function (model) {
if (!model) {
res.status(404).json({
@@ -24,6 +24,7 @@
manager.checkTokenBalance(token).then(function(balance){
res.status(200).json({
token: token,
+ hash: model.related('contract').get('hash'),
compute_units: balance,
bitcoin_address: Bitcoin.generateDeterministicWallet(model.related('balance').id),
compute_units_per_bitcoin: config.get('compute_units_per_bitcoin') |
2a86e3b21722f92b01d845668c2ca1fac716cd49 | api/routes/fintechRoutes.js | api/routes/fintechRoutes.js | 'use strict';
module.exports = function(app) {
var fintech = require('../controllers/fintechController');
// fintech Routes
app.route('/tickers')
.get(fintech.list_ticker_price);
app.route('/testSavePortfolio')
.get(fintech.save_portfolio);
};
| 'use strict';
module.exports = function(app) {
var fintech = require('../controllers/fintechController');
// fintech Routes
app.route('/tickers')
.get(fintech.list_ticker_price);
app.route('/testSavePortfolio')
.get(fintech.save_portfolio_value);
};
| Change to accommodate model change | Change to accommodate model change | JavaScript | mit | sunnyhuang2008/FintechAPI,sunnyhuang2008/FintechAPI | ---
+++
@@ -7,7 +7,7 @@
.get(fintech.list_ticker_price);
app.route('/testSavePortfolio')
- .get(fintech.save_portfolio);
+ .get(fintech.save_portfolio_value);
}; |
889e44327320fb73c7ffa5d5d34f54a8f7d58a97 | app/assets/javascripts/angular/app.js | app/assets/javascripts/angular/app.js | (function(){
'use strict';
angular
.module('secondLead',
['ngDragDrop',
'ui.bootstrap',
'ui.router',
'gridster',
'restangular',
'angularUtils.directives.dirPagination',
'secondLead.common',
'templates'])
.config(function(paginationTemplateProvider) {
paginationTemplateProvider.setPath('/dirPagination.html');
})
.config(['$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('dramas', {
url:'/dramas',
templateUrl: 'dramas-index.html',
controller:'DramasCtrl',
controllerAs: 'dramas'
})
.state('user', {
url:'/users/:userID',
templateUrl: 'user-show.html',
controller:'UserCtrl',
controllerAs: 'user',
resolve: {
user: ['$stateParams','UserModel','Restangular', function($stateParams,UserModel,Restangular) {
return UserModel.getOne($stateParams.userID);
}]
}
});
.state('lists', {
url:'/users/:userId/lists',
templateUrl: 'lists-index.html',
controller:'ListsCtrl',
controllerAs: 'lists'
});
$urlRouterProvider.otherwise('/');
}]);
})();
| (function(){
'use strict';
angular
.module('secondLead',
['ngDragDrop',
'ui.bootstrap',
'ui.router',
'gridster',
'restangular',
'angularUtils.directives.dirPagination',
'secondLead.common',
'templates'])
.config(function(paginationTemplateProvider) {
paginationTemplateProvider.setPath('/dirPagination.html');
})
.config(['$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('dramas', {
url:'/dramas',
templateUrl: 'dramas-index.html',
controller:'DramasCtrl',
controllerAs: 'dramas'
})
.state('user', {
url:'/users/:userID',
templateUrl: 'user-show.html',
controller:'UserCtrl',
controllerAs: 'user',
resolve: {
user: ['$stateParams','UserModel','Restangular', function($stateParams,UserModel,Restangular) {
return UserModel.getOne($stateParams.userID);
}]
}
})
.state('user.lists', {
url:'/lists',
templateUrl: 'lists-index.html',
controller:'ListsCtrl',
controllerAs: 'lists'
});
$urlRouterProvider.otherwise('/');
}]);
})();
| Add lists state to stateProvider | Add lists state to stateProvider
| JavaScript | mit | ac-adekunle/secondlead,ac-adekunle/secondlead,ac-adekunle/secondlead | ---
+++
@@ -38,10 +38,10 @@
return UserModel.getOne($stateParams.userID);
}]
}
- });
+ })
- .state('lists', {
- url:'/users/:userId/lists',
+ .state('user.lists', {
+ url:'/lists',
templateUrl: 'lists-index.html',
controller:'ListsCtrl',
controllerAs: 'lists' |
7669de047ef5a2187f77146d4fb2d29242b2660a | app/scripts/app.js | app/scripts/app.js | 'use strict';
var app = angular
.module('seenitApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
controllerAs: 'main'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
});
| 'use strict';
var app = angular
.module('seenitApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
controllerAs: 'main'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
});
app.factory('reddit', ['$http', '$q', function($http, $q) {
var getJSON = function() {
var deferred = $q.defer();
$http.get('https://www.reddit.com/r/videos.json?limit=100')
.success(function(data) {
var posts = data.data.children;
posts.forEach(function(post, i) {
if (post.data.is_self) {
posts.splice(i, 1);
}
});
deferred.resolve(posts);
})
.error(function(err) {
deferred.reject(err);
});
return deferred.promise;
};
return {
getData: getJSON
};
}]);
app.controller('MainCtrl', ['$scope', 'reddit', function($scope, reddit){
$scope.data = '';
reddit.getData().then(function(data) {
console.log(data);
$scope.data = data;
});
}]);
| Add reddit service, main ctrl | Add reddit service, main ctrl
| JavaScript | mit | kshvmdn/seen-it | ---
+++
@@ -21,3 +21,33 @@
});
$locationProvider.html5Mode(true);
});
+app.factory('reddit', ['$http', '$q', function($http, $q) {
+ var getJSON = function() {
+ var deferred = $q.defer();
+ $http.get('https://www.reddit.com/r/videos.json?limit=100')
+ .success(function(data) {
+ var posts = data.data.children;
+ posts.forEach(function(post, i) {
+ if (post.data.is_self) {
+ posts.splice(i, 1);
+ }
+ });
+ deferred.resolve(posts);
+ })
+ .error(function(err) {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+ return {
+ getData: getJSON
+ };
+}]);
+
+app.controller('MainCtrl', ['$scope', 'reddit', function($scope, reddit){
+ $scope.data = '';
+ reddit.getData().then(function(data) {
+ console.log(data);
+ $scope.data = data;
+ });
+}]); |
f23d310049b20280b88ebd07d7f2eb87d02ab4b3 | node_helper.js | node_helper.js | /* Magic Mirror
* Node Helper: MotionEye
*
* By Cato Antonsen (https://github.com/CatoAntonsen)
* MIT Licensed.
*/
var NodeHelper = require("node_helper");
module.exports = NodeHelper.create({
start: function() {
console.log("Starting module: " + this.name);
},
socketNotificationReceived: function(notification, config) {
var self = this;
if (notification === "CONFIG") {
self.config = config;
if (config.autoHide) {
this.expressApp.get('/motioneye/:id', function (req, res) {
console.log("Motion registered");
res.send('Motion registered: ' + req.params.id);
self.sendSocketNotification("MotionEyeShow", req.params.id);
});
this.expressApp.get('/motioneye/:id/hide', function (req, res) {
console.log("Hide registered");
res.send('Hide registered: ' + req.params.id);
self.sendSocketNotification("MotionEyeHide", req.params.id);
});
} else {
self.sendSocketNotification("MotionEyeShow", undefined);
}
return;
}
},
});
| /* Magic Mirror
* Node Helper: MotionEye
*
* By Cato Antonsen (https://github.com/CatoAntonsen)
* MIT Licensed.
*/
var NodeHelper = require("node_helper");
module.exports = NodeHelper.create({
start: function() {
console.log("Starting module: " + this.name);
},
socketNotificationReceived: function(notification, config) {
var self = this;
if (notification === "CONFIG") {
self.config = config;
if (config.autoHide) {
this.expressApp.get('/motioneye/hide/:id*?', function (req, res) {
console.log("Hide registered");
res.send('Hide registered: ' + req.params.id);
self.sendSocketNotification("MotionEyeHide", req.params.id);
});
this.expressApp.get('/motioneye/:id*?', function (req, res) {
console.log("Motion registered");
res.send('Motion registered: ' + req.params.id);
self.sendSocketNotification("MotionEyeShow", req.params.id);
});
} else {
self.sendSocketNotification("MotionEyeShow", undefined);
}
return;
}
},
});
| Change the hide function to work in a better way to not brake other functionallity. | Change the hide function to work in a better way to not brake other functionallity.
| JavaScript | mit | CatoAntonsen/MMM-MotionEye | ---
+++
@@ -19,15 +19,15 @@
self.config = config;
if (config.autoHide) {
- this.expressApp.get('/motioneye/:id', function (req, res) {
+ this.expressApp.get('/motioneye/hide/:id*?', function (req, res) {
+ console.log("Hide registered");
+ res.send('Hide registered: ' + req.params.id);
+ self.sendSocketNotification("MotionEyeHide", req.params.id);
+ });
+ this.expressApp.get('/motioneye/:id*?', function (req, res) {
console.log("Motion registered");
res.send('Motion registered: ' + req.params.id);
self.sendSocketNotification("MotionEyeShow", req.params.id);
- });
- this.expressApp.get('/motioneye/:id/hide', function (req, res) {
- console.log("Hide registered");
- res.send('Hide registered: ' + req.params.id);
- self.sendSocketNotification("MotionEyeHide", req.params.id);
});
} else {
self.sendSocketNotification("MotionEyeShow", undefined); |
84ab525449f96c842157fc8d437066fa11fc993d | client/src/components/TextCheckboxGroupField/TextCheckboxGroupField.js | client/src/components/TextCheckboxGroupField/TextCheckboxGroupField.js | import React from 'react';
import { InputGroup, InputGroupAddon, InputGroupText } from 'reactstrap';
import fieldHolder from 'components/FieldHolder/FieldHolder';
const TextCheckboxGroupField = (props) => {
const { children } = props;
const childrenWithProps = React.Children.toArray(
React.Children.map(children, child =>
React.cloneElement(child, { noHolder: true })
)
);
if (childrenWithProps.length === 1) {
return childrenWithProps[0];
}
return (
<InputGroup className="text-checkout-group-field">
{childrenWithProps[0]}
<InputGroupAddon addonType="append">
<InputGroupText>{childrenWithProps[1]}</InputGroupText>
</InputGroupAddon>
</InputGroup>
);
};
export default fieldHolder(TextCheckboxGroupField);
| import React from 'react';
import { InputGroup, InputGroupAddon, InputGroupText } from 'reactstrap';
import fieldHolder from 'components/FieldHolder/FieldHolder';
const TextCheckboxGroupField = (props) => {
const { children } = props;
const childrenWithProps = React.Children.toArray(
React.Children.map(children, child =>
React.cloneElement(child, { noHolder: true })
)
);
// If the checkbox has been removed, just render the TextField on its own
if (childrenWithProps.length === 1) {
return childrenWithProps[0];
}
return (
<InputGroup className="text-checkout-group-field">
{childrenWithProps[0]}
<InputGroupAddon addonType="append">
<InputGroupText>{childrenWithProps[1]}</InputGroupText>
</InputGroupAddon>
</InputGroup>
);
};
export default fieldHolder(TextCheckboxGroupField);
| Add comment to explain why we render a single field sometimes | Add comment to explain why we render a single field sometimes
| JavaScript | bsd-3-clause | dnadesign/silverstripe-elemental,dnadesign/silverstripe-elemental | ---
+++
@@ -11,6 +11,7 @@
)
);
+ // If the checkbox has been removed, just render the TextField on its own
if (childrenWithProps.length === 1) {
return childrenWithProps[0];
} |
4577657827d78ddf2d0a30f2952acdcbaa9d0f0b | assets/js/index.js | assets/js/index.js | $("body").backstretch("assets/img/background1.png");
$(document).ready(function() {
$('.faqelem').click(function() {
var faqElement = $(this);
var question = faqElement.find('.question');
var answer = faqElement.find('.answer');
if (!answer.hasClass('activeanswer')) {
question.addClass('flipButton');
answer.css('max-height', answer.height());
answer.addClass('activeanswer');
}
else if (answer.hasClass('activeanswer')) {
question.removeClass('flipButton');
answer.css('max-height', 0);
answer.removeClass('activeanswer');
}
});
});
// Initialize Firebase
/*
*/
var config = {
apiKey: "AIzaSyAfRJWCG5g0EFpYsA3gX2NQIK_jRYttaFY",
authDomain: "hacktech-pre-registration.firebaseapp.com",
databaseURL: "https://hacktech-pre-registration.firebaseio.com",
storageBucket: "hacktech-pre-registration.appspot.com",
};
firebase.initializeApp(config);
function save() {
var eID = document.getElementById("hackerEmail").value;
firebase.database().ref().push({email: eID});
document.getElementById("hackerEmail").value = "Confirmed!";
};
| $("body").backstretch("assets/img/background1.png");
$(document).ready(function() {
$('.faqelem').click(function() {
var faqElement = $(this);
var question = faqElement.find('.question');
var answer = faqElement.find('.answer');
if (!answer.hasClass('activeanswer')) {
question.addClass('flipButton');
answer.css('max-height', 'none');
answer.css('max-height', answer.height());
answer.addClass('activeanswer');
}
else if (answer.hasClass('activeanswer')) {
question.removeClass('flipButton');
answer.css('max-height', 0);
answer.removeClass('activeanswer');
}
});
});
// Initialize Firebase
/*
*/
var config = {
apiKey: "AIzaSyAfRJWCG5g0EFpYsA3gX2NQIK_jRYttaFY",
authDomain: "hacktech-pre-registration.firebaseapp.com",
databaseURL: "https://hacktech-pre-registration.firebaseio.com",
storageBucket: "hacktech-pre-registration.appspot.com",
};
firebase.initializeApp(config);
function save() {
var eID = document.getElementById("hackerEmail").value;
firebase.database().ref().push({email: eID});
document.getElementById("hackerEmail").value = "Confirmed!";
};
| Revert "safari faq bug test" | Revert "safari faq bug test"
This reverts commit face5c813634c1a5b0469943492f7ed16f1061c6.
| JavaScript | apache-2.0 | TheHacktech/TheHacktech.github.io,TheHacktech/TheHacktech.github.io | ---
+++
@@ -7,6 +7,7 @@
var answer = faqElement.find('.answer');
if (!answer.hasClass('activeanswer')) {
question.addClass('flipButton');
+ answer.css('max-height', 'none');
answer.css('max-height', answer.height());
answer.addClass('activeanswer');
} |
6771946d46816e3a6a8f8736a457c427669c78cc | assets/js/racer.js | assets/js/racer.js | function Game(){
this.$track = $('#racetrack');
this.finishLine = this.$track.width() - 54;
}
function Player(id){
this.player = $('.player')[id - 1];
this.position = 10;
}
Player.prototype.move = function(){
this.position += 20;
};
Player.prototype.updatePosition = function(){
$player = $(this.player);
$player.css('margin-left', this.position);
};
function checkWinner(player, game){
if( player.position > game.finishLine ){
alert("Player " + player.player.id + " has won!");
}
}
$(document).ready(function() {
var game = new Game();
var player1 = new Player(1);
var player2 = new Player(2);
$(document).on('keyup', function(keyPress){
if(keyPress.keyCode === 80) {
player1.move();
player1.updatePosition();
} else if (keyPress.keyCode === 81) {
player2.move();
player2.updatePosition();
}
});
}); | function Game(){
this.$track = $('#racetrack');
this.finishLine = this.$track.width() - 54;
}
function Player(id){
this.player = $('.player')[id - 1];
this.position = 10;
}
Player.prototype.move = function(){
this.position += 20;
};
Player.prototype.updatePosition = function(){
$player = $(this.player);
$player.css('margin-left', this.position);
};
function checkWinner(player, game){
if( player.position > game.finishLine ){
window.confirm("Player " + player.player.id + " has won!" + "\n Play Again?");
}
}
$(document).ready(function() {
var game = new Game();
var player1 = new Player(1);
var player2 = new Player(2);
$(document).on('keyup', function(keyPress){
if(keyPress.keyCode === 80) {
player1.move();
player1.updatePosition();
} else if (keyPress.keyCode === 81) {
player2.move();
player2.updatePosition();
}
});
}); | Add newline and request to play again to confirm box | Add newline and request to play again to confirm box
| JavaScript | mit | SputterPuttRedux/basic-javascript-racer,SputterPuttRedux/basic-javascript-racer | ---
+++
@@ -19,7 +19,7 @@
function checkWinner(player, game){
if( player.position > game.finishLine ){
- alert("Player " + player.player.id + " has won!");
+ window.confirm("Player " + player.player.id + " has won!" + "\n Play Again?");
}
}
|
f06f6ec4bd2e0367fdc15f4db216e6979993f064 | src/js/infinite-scroll.js | src/js/infinite-scroll.js | /* ===============================================================================
************ Infinite Scroll ************
=============================================================================== */
function handleInfiniteScroll() {
/*jshint validthis:true */
var inf = this;
var scrollTop = inf.scrollTop;
var scrollHeight = inf.scrollHeight;
var height = inf.offsetHeight;
var distance = inf.getAttribute('data-distance');
if (!distance) distance = 50;
if (distance.indexOf('%') >= 0) {
distance = parseInt(distance, 10) / 100 * height;
}
if (distance > height) distance = height;
if (scrollTop + height >= scrollHeight - distance) {
$(inf).trigger('infinite');
}
}
app.attachInfiniteScroll = function (infiniteContent) {
$(infiniteContent).on('scroll', handleInfiniteScroll);
};
app.detachInfiniteScroll = function (infiniteContent) {
$(infiniteContent).off('scroll', handleInfiniteScroll);
};
app.initInfiniteScroll = function (pageContainer) {
pageContainer = $(pageContainer);
var infiniteContent = pageContainer.find('.infinite-scroll');
app.attachInfiniteScroll(infiniteContent);
function detachEvents() {
app.detachInfiniteScroll(infiniteContent);
pageContainer.off('pageBeforeRemove', detachEvents);
}
pageContainer.on('pageBeforeRemove', detachEvents);
}; | /* ===============================================================================
************ Infinite Scroll ************
=============================================================================== */
function handleInfiniteScroll() {
/*jshint validthis:true */
var inf = this;
var scrollTop = inf.scrollTop;
var scrollHeight = inf.scrollHeight;
var height = inf.offsetHeight;
var distance = inf.getAttribute('data-distance');
if (!distance) distance = 50;
if (typeof distance === 'string' && distance.indexOf('%') >= 0) {
distance = parseInt(distance, 10) / 100 * height;
}
if (distance > height) distance = height;
if (scrollTop + height >= scrollHeight - distance) {
$(inf).trigger('infinite');
}
}
app.attachInfiniteScroll = function (infiniteContent) {
$(infiniteContent).on('scroll', handleInfiniteScroll);
};
app.detachInfiniteScroll = function (infiniteContent) {
$(infiniteContent).off('scroll', handleInfiniteScroll);
};
app.initInfiniteScroll = function (pageContainer) {
pageContainer = $(pageContainer);
var infiniteContent = pageContainer.find('.infinite-scroll');
app.attachInfiniteScroll(infiniteContent);
function detachEvents() {
app.detachInfiniteScroll(infiniteContent);
pageContainer.off('pageBeforeRemove', detachEvents);
}
pageContainer.on('pageBeforeRemove', detachEvents);
}; | Fix for .indexOf on Number | Fix for .indexOf on Number
| JavaScript | mit | hanziwang/Framework7,luistapajos/Lista7,itstar4tech/Framework7,crazyurus/Framework7,wjb12/Framework7,stonegithubs/Framework7-Plus,akio46/Framework7,elma-cao/Framework7,jeremykenedy/Framework7,NichenLg/Framework7,pandoraui/Framework7,Janusorz/Framework7,nolimits4web/Framework7,gagustavo/Framework7,xpyctum/Framework7,makelivedotnet/Framework7,vulcan/Framework7-Plus,microlv/Framework7,Dr1ks/Framework7,framework7io/Framework7,iamxiaoma/Framework7,NichenLg/Framework7,Dr1ks/Framework7,pleshevskiy/Framework7,Liu-Young/Framework7,zhangzuoqiang/Framework7-Plus,pandoraui/Framework7,jvrunion/mercury-seed,pingjiang/Framework7,wjb12/Framework7,RubenDjOn/Framework7,jvrunion/mercury-seed,trunk-studio/demo20151024,AdrianV/Framework7,yucopowo/Framework7,quannt/Framework7,chenbk85/Framework7-Plus,romanticcup/Framework7,pleshevskiy/Framework7,JustAMisterE/Framework7,johnjamesjacoby/Framework7,EhteshamMehmood/Framework7,JustAMisterE/Framework7,wicky-info/Framework7,iamxiaoma/Framework7,xpyctum/Framework7,StudyForFun/Framework7-Plus,StudyForFun/Framework7-Plus,LeoHuiyi/Framework7,stonegithubs/Framework7,ChineseDron/Framework7,trunk-studio/demo20151024,etsb5z/Framework7,wicky-info/Framework7,dingxin/Framework7,lilien1010/Framework7,microlv/Framework7,DrGo/Framework7,Carrotzpc/Framework7,yangfeiloveG/Framework7,romanticcup/Framework7,JustAMisterE/Framework7,vulcan/Framework7-Plus,Janusorz/Framework7,Dr1ks/Framework7,lihongxun945/Framework7,etsb5z/Framework7,megaplan/Framework7,makelivedotnet/Framework7,insionng/Framework7,jvrunion/mercury-seed,zd9027/Framework7-Plus,yangfeiloveG/Framework7,hanziwang/Framework7,zhangzuoqiang/Framework7-Plus,DmitryNek/Framework7,etsb5z/Framework7,Miantang/FrameWrork7-Demo,DrGo/Framework7,ks3dev/Framework7,Liu-Young/Framework7,quietdog/Framework7,stonegithubs/Framework7-Plus,quannt/Framework7,hanziwang/Framework7,pratikbutani/Framework7,johnjamesjacoby/Framework7,yangfeiloveG/Framework7,zhangzuoqiang/Framework7-Plus,stonegithubs/Framework7-Plus,prashen/Framework7,yucopowo/Framework7,Iamlars/Framework7,quietdog/Framework7,ks3dev/Framework7,EhteshamMehmood/Framework7,mgesmundo/Framework7,ina9er/bein,faustinoloeza/Framework7,pingjiang/Framework7,stonegithubs/Framework7,elma-cao/Framework7,iamxiaoma/Framework7,vulcan/Framework7-Plus,thdoan/Framework7,stonegithubs/Framework7,pleshevskiy/Framework7,xpyctum/Framework7,Carrotzpc/Framework7,prashen/Framework7,akio46/Framework7,shuai959980629/Framework7,tranc99/Framework7,EhteshamMehmood/Framework7,zd9027/Framework7-Plus,pratikbutani/Framework7,crazyurus/Framework7,luistapajos/Lista7,microlv/Framework7,jeremykenedy/Framework7,ChineseDron/Framework7,dingxin/Framework7,pandoraui/Framework7,quietdog/Framework7,gagustavo/Framework7,lilien1010/Framework7,ina9er/bein,121595113/Framework7,thdoan/Framework7,tiptronic/Framework7,nolimits4web/Framework7,shuai959980629/Framework7,quannt/Framework7,Logicify/Framework7,elma-cao/Framework7,thdoan/Framework7,chenbk85/Framework7-Plus,Miantang/FrameWrork7-Demo,romanticcup/Framework7,nolimits4web/Framework7,Liu-Young/Framework7,mgesmundo/Framework7,Iamlars/Framework7,jeremykenedy/Framework7,DmitryNek/Framework7,itstar4tech/Framework7,tranc99/Framework7,Logicify/Framework7,Janusorz/Framework7,insionng/Framework7,pingjiang/Framework7,trunk-studio/demo20151024,ina9er/bein,shuai959980629/Framework7,itstar4tech/Framework7,AdrianV/Framework7,Carrotzpc/Framework7,trunk-studio/demo20151024,megaplan/Framework7,RubenDjOn/Framework7,tranc99/Framework7,ks3dev/Framework7,Miantang/FrameWrork7-Demo,domhnallohanlon/Framework7,Iamlars/Framework7,NichenLg/Framework7,LeoHuiyi/Framework7,AdrianV/Framework7,iamxiaoma/Framework7,prashen/Framework7,wjb12/Framework7,luistapajos/Lista7,Logicify/Framework7,crazyurus/Framework7,youprofit/Framework7,pratikbutani/Framework7,johnjamesjacoby/Framework7,LeoHuiyi/Framework7,gank0326/HTMLINIOS,ChineseDron/Framework7,xuyuanxiang/Framework7,lilien1010/Framework7,faustinoloeza/Framework7,lihongxun945/Framework7,faustinoloeza/Framework7,mgesmundo/Framework7,DrGo/Framework7,youprofit/Framework7,tiptronic/Framework7,akio46/Framework7,DmitryNek/Framework7,121595113/Framework7,xuyuanxiang/Framework7,zd9027/Framework7-Plus,gank0326/HTMLINIOS,framework7io/Framework7,xuyuanxiang/Framework7,domhnallohanlon/Framework7,yucopowo/Framework7,makelivedotnet/Framework7,RubenDjOn/Framework7,lihongxun945/Framework7,tiptronic/Framework7,chenbk85/Framework7-Plus,megaplan/Framework7,insionng/Framework7,wicky-info/Framework7,youprofit/Framework7,gagustavo/Framework7,StudyForFun/Framework7-Plus,trunk-studio/demo20151024 | ---
+++
@@ -9,7 +9,7 @@
var height = inf.offsetHeight;
var distance = inf.getAttribute('data-distance');
if (!distance) distance = 50;
- if (distance.indexOf('%') >= 0) {
+ if (typeof distance === 'string' && distance.indexOf('%') >= 0) {
distance = parseInt(distance, 10) / 100 * height;
}
if (distance > height) distance = height; |
4ff9dd275307d6d42ec8dfee579715b1b37d6bb6 | containers/styles/GameplayScreenStyle.js | containers/styles/GameplayScreenStyle.js | import { StyleSheet, Dimensions } from 'react-native';
export default StyleSheet.create({
mainContainer: {
// flex: 3,
width: Dimensions.get('window').width * .97,
height: Dimensions.get('window').height * .95,
marginLeft: Dimensions.get('window').width / 60,
marginTop: Dimensions.get('window').width / 20,
},
actor_image: {
borderWidth:1,
borderColor:'#c0c0c0',
alignItems:'center',
justifyContent:'center',
width: 160,
height: 160,
backgroundColor:'white',
borderRadius: 80,
resizeMode: 'cover'
},
startingActorView: {
flex: 1.6,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
// borderWidth: 1,
},
endingActorView: {
flex: 1.6,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
// borderWidth: 1,
},
pathsView: {
flex: 3,
justifyContent: 'center',
// borderWidth: 1,
// left: 0,
},
path: {
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'space-around',
padding: 5,
// alignItems: 'flex-start',
},
buttonView: {
flex: .11,
flexDirection: 'row',
justifyContent: 'space-between',
},
movieImage: {
borderWidth:1,
borderColor:'#c0c0c0',
alignItems:'center',
justifyContent:'center',
width: 108.92,
height:160.38,
backgroundColor:'white',
borderRadius: 16.5,
resizeMode: 'contain'
},
})
| import { StyleSheet, Dimensions } from 'react-native';
export default StyleSheet.create({
mainContainer: {
// flex: 3,
width: Dimensions.get('window').width * .97,
height: Dimensions.get('window').height * .95,
marginLeft: Dimensions.get('window').width / 60,
marginTop: Dimensions.get('window').width / 20,
},
startingActorView: {
flex: 1.6,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
// borderWidth: 1,
},
endingActorView: {
flex: 1.6,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
// borderWidth: 1,
},
pathsView: {
flex: 3,
justifyContent: 'center',
// borderWidth: 1,
// left: 0,
},
path: {
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'space-around',
padding: 5,
// alignItems: 'flex-start',
},
buttonView: {
flex: .11,
flexDirection: 'row',
justifyContent: 'space-between',
},
})
| Remove actor/movieimage styles, add to staticimagestyle | Remove actor/movieimage styles, add to staticimagestyle
| JavaScript | mit | fridl8/cold-bacon-client,fridl8/cold-bacon-client,fridl8/cold-bacon-client | ---
+++
@@ -7,17 +7,6 @@
height: Dimensions.get('window').height * .95,
marginLeft: Dimensions.get('window').width / 60,
marginTop: Dimensions.get('window').width / 20,
- },
- actor_image: {
- borderWidth:1,
- borderColor:'#c0c0c0',
- alignItems:'center',
- justifyContent:'center',
- width: 160,
- height: 160,
- backgroundColor:'white',
- borderRadius: 80,
- resizeMode: 'cover'
},
startingActorView: {
flex: 1.6,
@@ -51,15 +40,4 @@
flexDirection: 'row',
justifyContent: 'space-between',
},
- movieImage: {
- borderWidth:1,
- borderColor:'#c0c0c0',
- alignItems:'center',
- justifyContent:'center',
- width: 108.92,
- height:160.38,
- backgroundColor:'white',
- borderRadius: 16.5,
- resizeMode: 'contain'
- },
}) |
f4d8a835403b59d909e780d5fe9634a984249478 | lib/label/add-label.js | lib/label/add-label.js | var addTextLabel = require("./add-text-label"),
addHtmlLabel = require("./add-html-label"),
addSVGLabel = require("./add-svg-label");
module.exports = addLabel;
function addLabel(root, node, location) {
var label = node.label;
var labelSvg = root.append("g");
// Allow the label to be a string, a function that returns a DOM element, or
// a DOM element itself.
if (node.labelType === "svg") {
addSVGLabel(labelSvg, node);
} else if (typeof label !== "string" || node.labelType === "html") {
addHtmlLabel(labelSvg, node);
} else {
addTextLabel(labelSvg, node);
}
var labelBBox = labelSvg.node().getBBox();
switch(location) {
case "top":
y = (-node.height / 2);
break;
case "bottom":
y = (node.height / 2) - labelBBox.height;
break;
default:
y = (-labelBBox.height / 2);
}
labelSvg.attr("transform",
"translate(" + (-labelBBox.width / 2) + "," + y + ")");
return labelSvg;
}
| var addTextLabel = require("./add-text-label"),
addHtmlLabel = require("./add-html-label"),
addSVGLabel = require("./add-svg-label");
module.exports = addLabel;
function addLabel(root, node, location) {
var label = node.label;
var labelSvg = root.append("g");
// Allow the label to be a string, a function that returns a DOM element, or
// a DOM element itself.
if (node.labelType === "svg") {
addSVGLabel(labelSvg, node);
} else if (typeof label !== "string" || node.labelType === "html") {
addHtmlLabel(labelSvg, node);
} else {
addTextLabel(labelSvg, node);
}
var labelBBox = labelSvg.node().getBBox();
var y;
switch(location) {
case "top":
y = (-node.height / 2);
break;
case "bottom":
y = (node.height / 2) - labelBBox.height;
break;
default:
y = (-labelBBox.height / 2);
}
labelSvg.attr("transform",
"translate(" + (-labelBBox.width / 2) + "," + y + ")");
return labelSvg;
}
| Add var declaration to avoid global variable scope | Add var declaration to avoid global variable scope | JavaScript | mit | 9n/dagre-d3,dagrejs/dagre-d3,dominiek/dagre-d3,9n/dagre-d3,dagrejs/dagre-d3,cbfx/dagre-d3,cpettitt/dagre-d3,dominiek/dagre-d3,dominiek/dagre-d3,cbfx/dagre-d3,9n/dagre-d3,cpettitt/dagre-d3,cbfx/dagre-d3,cpettitt/dagre-d3 | ---
+++
@@ -19,6 +19,7 @@
}
var labelBBox = labelSvg.node().getBBox();
+ var y;
switch(location) {
case "top":
y = (-node.height / 2); |
833a6225320e5b1fe4cf0d1a8357d9894de1097a | lib/main.js | lib/main.js | import configSchema from './config-schema'
import {toggleQuotes} from './toggle-quotes'
export default {
config: configSchema,
activate: () => {
this.subscription = atom.commands.add('atom-text-editor', 'toggle-quotes:toggle', () => {
let editor = atom.workspace.getActiveTextEditor()
if (editor) {
toggleQuotes(editor)
}
})
}
deactivate: () => {
this.subscription.dispose()
}
}
| 'use babel'
import configSchema from './config-schema'
import {toggleQuotes} from './toggle-quotes'
export default {
config: configSchema,
activate: () => {
this.subscription = atom.commands.add('atom-text-editor', 'toggle-quotes:toggle', () => {
let editor = atom.workspace.getActiveTextEditor()
if (editor) {
toggleQuotes(editor)
}
})
}
deactivate: () => {
this.subscription.dispose()
}
}
| Add missing use babel directive | Add missing use babel directive
| JavaScript | mit | atom/toggle-quotes | ---
+++
@@ -1,3 +1,5 @@
+'use babel'
+
import configSchema from './config-schema'
import {toggleQuotes} from './toggle-quotes'
|
d36102412b0d15f63e0830fff291ce8469f3e7ef | src/server/mongoConfig.js | src/server/mongoConfig.js | export default {
user: process.env.MONGO_USER || '',
password: process.env.MONGO_PASSWORD || '',
host: process.env.MONGO_HOST || 'localhost',
port: process.env.MONGO_PORT || '27017',
database: process.env.MONGO_DB || '',
}
| require('dotenv').load()
export default {
user: process.env.MONGO_USER || '',
password: process.env.MONGO_PASSWORD || '',
host: process.env.MONGO_HOST || 'localhost',
port: process.env.MONGO_PORT || '27017',
database: process.env.MONGO_DB || '',
}
| Load env in mongo config | Load env in mongo config
| JavaScript | mit | cjessett/buoyfeed | ---
+++
@@ -1,3 +1,5 @@
+require('dotenv').load()
+
export default {
user: process.env.MONGO_USER || '',
password: process.env.MONGO_PASSWORD || '', |
576cfdb81a47fb8274cf9059a2f7572f9bdf0f64 | blueprints/flexberry-model/files/__root__/mixins/regenerated/models/__name__.js | blueprints/flexberry-model/files/__root__/mixins/regenerated/models/__name__.js | import Ember from 'ember';
import DS from 'ember-data';
<%if(projections) {%>import { Projection } from 'ember-flexberry-data';<%}%>
export let Model = Ember.Mixin.create({
<%= model %>
});<%if(parentModelName) {%>
export let defineBaseModel = function (modelClass) {
modelClass.reopenClass({
_parentModelName: '<%= parentModelName %>'
});
};<%}%><%if(projections) {%>
export let defineProjections = function (modelClass) {<%}%><%= projections %><%if(projections) {%>};<%}%>
| import Ember from 'ember';
import DS from 'ember-data';
<%if(projections) {%>import { Projection } from 'ember-flexberry-data';<%}%>
export let Model = Ember.Mixin.create({
<%= model %>
});<%if(parentModelName) {%>
export let defineBaseModel = function (modelClass) {
modelClass.reopenClass({
_parentModelName: '<%= parentModelName %>'
});
};
<%}%>
<%if(projections) {%>export let defineProjections = function (modelClass) {<%}%><%= projections %><%if(projections) {%>};
<%}%> | Fix JSCS for generated model's mixin | Fix JSCS for generated model's mixin
| JavaScript | mit | Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry | ---
+++
@@ -8,5 +8,7 @@
modelClass.reopenClass({
_parentModelName: '<%= parentModelName %>'
});
-};<%}%><%if(projections) {%>
-export let defineProjections = function (modelClass) {<%}%><%= projections %><%if(projections) {%>};<%}%>
+};
+<%}%>
+<%if(projections) {%>export let defineProjections = function (modelClass) {<%}%><%= projections %><%if(projections) {%>};
+<%}%> |
bd1d846880a51cb629d487ac4f01e5704612df12 | add_heading_anchors.js | add_heading_anchors.js | var addHeadingAnchors = {
init: function (selector) {
this.target = document.querySelector(selector);
if (this.target) {
this.addAnchorsToHeadings();
}
},
addAnchorsToHeadings: function () {
var headings = this.target.querySelectorAll('h1, h2, h3, h4, h5, h6'),
id;
headings.forEach(function (heading) {
if (id = heading.id) {
var anchor = this.createAnchor(id);
heading.appendChild(anchor);
}
}.bind(this));
},
createAnchor: function (id) {
var anchor = document.createElement('a'),
anchorText = document.createTextNode('¶'),
attributes = {
href: id,
class: 'headerLink',
title: 'Permalink to this headline'
};
anchor.appendChild(anchorText);
for (var attr in attributes) {
anchor.setAttribute(attr, attributes[attr]);
}
return anchor;
}
};
| var addHeadingAnchors = {
init: function (selector) {
this.target = document.querySelector(selector);
if (this.target) {
this.addAnchorsToHeadings();
}
},
addAnchorsToHeadings: function () {
var selectorString = 'h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]',
headings = this.target.querySelectorAll(selectorString)
headings.forEach(function (heading) {
var anchor = this.createAnchor(heading.id);
heading.appendChild(anchor);
}.bind(this));
},
createAnchor: function (id) {
var anchor = document.createElement('a'),
anchorText = document.createTextNode('¶'),
attributes = {
href: id,
class: 'headerLink',
title: 'Permalink to this headline'
};
anchor.appendChild(anchorText);
for (var attr in attributes) {
anchor.setAttribute(attr, attributes[attr]);
}
return anchor;
}
};
| Change selector string so the query only returns headings with ids | Change selector string so the query only returns headings with ids
| JavaScript | mit | PolicyStat/ckeditor-plugin-autoid-headings,PolicyStat/ckeditor-plugin-autoid-headings | ---
+++
@@ -8,14 +8,12 @@
},
addAnchorsToHeadings: function () {
- var headings = this.target.querySelectorAll('h1, h2, h3, h4, h5, h6'),
- id;
+ var selectorString = 'h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]',
+ headings = this.target.querySelectorAll(selectorString)
headings.forEach(function (heading) {
- if (id = heading.id) {
- var anchor = this.createAnchor(id);
- heading.appendChild(anchor);
- }
+ var anchor = this.createAnchor(heading.id);
+ heading.appendChild(anchor);
}.bind(this));
},
@@ -36,5 +34,4 @@
return anchor;
}
-
}; |
6c93d19484c542e3449d6a726ec52f74030bcaf2 | config/seneca-options.js | config/seneca-options.js | 'use strict';
var assert = require('assert');
var LogEntries = require('le_node');
function log () {
// seneca custom log handlers
if (process.env.LOGENTRIES_ENABLED === 'true') {
assert.ok(process.env.LOGENTRIES_DEBUG_TOKEN, 'No LOGENTRIES_DEBUG_TOKEN set');
var led = new LogEntries({
token: process.env.LOGENTRIES_DEBUG_TOKEN,
flatten: true,
flattenArrays: true
});
assert.ok(process.env.LOGENTRIES_ERRORS_TOKEN, 'No LOGENTRIES_ERROR_TOKEN set');
var lee = new LogEntries({
token: process.env.LOGENTRIES_ERRORS_TOKEN,
flatten: true,
flattenArrays: true
});
}
function debugHandler () {
if (process.env.LOGENTRIES_ENABLED === 'true') {
assert.ok(process.env.LOGENTRIES_DEBUG_TOKEN, 'No LOGENTRIES_DEBUG_TOKEN set');
led.log('debug', arguments);
}
}
function errorHandler () {
console.error(JSON.stringify(arguments));
if (process.env.LOGENTRIES_ENABLED === 'true') {
assert.ok(process.env.LOGENTRIES_ERRORS_TOKEN, 'No LOGENTRIES_ERROR_TOKEN set');
lee.log('err', arguments);
}
}
return {
map: [{
level: 'debug', handler: debugHandler
}, {
level: 'error', handler: errorHandler
}]
};
}
var senecaOptions = {
transport: {
type: 'web',
web: {
timeout: 120000,
port: 10305
}
},
apiBaseUrl: process.env.BADGEKIT_API_BASE_URL || 'http://localhost:8080',
apiSecret: process.env.BADGEKIT_API_SECRET || '',
claimCodePrefix: 'code-',
timeout: 120000,
strict: { add: false, result: false },
log: log()
};
module.exports = senecaOptions;
| 'use strict';
var assert = require('assert');
var LogEntries = require('le_node');
var senecaOptions = {
transport: {
type: 'web',
web: {
timeout: 120000,
port: 10305
}
},
apiBaseUrl: process.env.BADGEKIT_API_BASE_URL || 'http://localhost:8080',
apiSecret: process.env.BADGEKIT_API_SECRET || '',
claimCodePrefix: 'code-',
timeout: 120000,
strict: { add: false, result: false },
actcache: { active:false }
};
module.exports = senecaOptions;
| Remove seneca logging (to be like all the other services) | Remove seneca logging (to be like all the other services)
| JavaScript | mit | bmatthews68/cp-badges-service,CoderDojo/cp-badges-service,bmatthews68/cp-badges-service,CoderDojo/cp-badges-service | ---
+++
@@ -1,50 +1,6 @@
'use strict';
var assert = require('assert');
var LogEntries = require('le_node');
-
-function log () {
- // seneca custom log handlers
-
- if (process.env.LOGENTRIES_ENABLED === 'true') {
- assert.ok(process.env.LOGENTRIES_DEBUG_TOKEN, 'No LOGENTRIES_DEBUG_TOKEN set');
- var led = new LogEntries({
- token: process.env.LOGENTRIES_DEBUG_TOKEN,
- flatten: true,
- flattenArrays: true
- });
-
- assert.ok(process.env.LOGENTRIES_ERRORS_TOKEN, 'No LOGENTRIES_ERROR_TOKEN set');
- var lee = new LogEntries({
- token: process.env.LOGENTRIES_ERRORS_TOKEN,
- flatten: true,
- flattenArrays: true
- });
- }
-
- function debugHandler () {
- if (process.env.LOGENTRIES_ENABLED === 'true') {
- assert.ok(process.env.LOGENTRIES_DEBUG_TOKEN, 'No LOGENTRIES_DEBUG_TOKEN set');
- led.log('debug', arguments);
- }
- }
-
- function errorHandler () {
- console.error(JSON.stringify(arguments));
-
- if (process.env.LOGENTRIES_ENABLED === 'true') {
- assert.ok(process.env.LOGENTRIES_ERRORS_TOKEN, 'No LOGENTRIES_ERROR_TOKEN set');
- lee.log('err', arguments);
- }
- }
-
- return {
- map: [{
- level: 'debug', handler: debugHandler
- }, {
- level: 'error', handler: errorHandler
- }]
- };
-}
var senecaOptions = {
transport: {
@@ -59,7 +15,7 @@
claimCodePrefix: 'code-',
timeout: 120000,
strict: { add: false, result: false },
- log: log()
+ actcache: { active:false }
};
module.exports = senecaOptions; |
af7fd6c14c2d32b78e35531d72bee275e2d95eb4 | client/.eslintrc.js | client/.eslintrc.js | const OFF = 0;
const WARN = 1;
const ERROR = 2;
module.exports = {
extends: "../.eslintrc.js",
rules: {
"arrow-parens": [ ERROR, "as-needed" ],
"no-confusing-arrow": [ OFF ],
"no-use-before-define": [ OFF ],
"semi": [ ERROR, "never" ],
},
env: {
"browser": true,
"commonjs": true,
"es6": true,
"mocha": true,
},
parser: "babel-eslint",
};
| const OFF = 0;
const WARN = 1;
const ERROR = 2;
module.exports = {
extends: "../.eslintrc.js",
rules: {
"arrow-parens": [ ERROR, "as-needed" ],
"no-confusing-arrow": [ OFF ],
"no-use-before-define": [ OFF ],
"semi": [ ERROR, "never" ],
"max-len": [ ERROR, 80, 2 ],
},
env: {
"browser": true,
"commonjs": true,
"es6": true,
"mocha": true,
},
parser: "babel-eslint",
};
| Add max len for client | Add max len for client
| JavaScript | mit | rethinkdb/horizon,deadcee/horizon,deadcee/horizon,deadcee/horizon,rethinkdb/horizon,rethinkdb/horizon,rethinkdb/horizon | ---
+++
@@ -9,6 +9,7 @@
"no-confusing-arrow": [ OFF ],
"no-use-before-define": [ OFF ],
"semi": [ ERROR, "never" ],
+ "max-len": [ ERROR, 80, 2 ],
},
env: {
"browser": true, |
06b4f67f2393be80f0c3cd3e4734d325ac15ae9c | bin.js | bin.js | #!/usr/bin/env/node
/*
Provide a command-line interface for `reconfigure`.
___ greeting, usage ___ en_US ___
usage: node.bin.js
___ serve, usage ___ en_US ___
usage: node bin.js reconfigure server
options:
-l, --listen [string] IP and port to bind to.
-i, --id [string] reconfigure instance ID (or IP)
___ ___ ___
*/
require('arguable')(module, require('cadence')(function (async, options) {
switch (options.command[0]) {
case 'serve':
console.log('coming soon')
if ((options.param.listen != null) || (options.param.id != null)) {
console.log('bind:' + options.param.listen + ' id:' + options.param.id)
}
break
case 'greeting':
if (options.param.string != null) {
console.log(options.param.string)
} else {
console.log('Hello, World!')
}
break
}
}))
| #!/usr/bin/env/node
/*
Provide a command-line interface for `reconfigure`.
___ greeting, usage ___ en_US ___
usage: node.bin.js
___ serve, usage ___ en_US ___
usage: node bin.js reconfigure server
options:
-l, --listen [string] IP and port to bind to.
-i, --id [string] reconfigure instance ID (or IP)
___ ___ ___
*/
require('arguable')(module, require('cadence')(function (async, options) {
switch (options.command[0]) {
case 'serve':
var ip, port
console.log('coming soon')
ip = options.param.listen.split(':')
if (ip.length) {
port = ip[1]
ip = ip[0]
} else {
port = '8080'
ip = ip[0]
}
console.log('ip: ' + ip + ' port: ' + port)
break
case 'greeting':
if (options.param.string != null) {
console.log(options.param.string)
} else {
console.log('Hello, World!')
}
break
}
}))
| Split IP and port from input. | Split IP and port from input.
| JavaScript | mit | demarius/reconfigure,bigeasy/reconfigure,demarius/reconfigure,bigeasy/reconfigure | ---
+++
@@ -18,10 +18,17 @@
require('arguable')(module, require('cadence')(function (async, options) {
switch (options.command[0]) {
case 'serve':
+ var ip, port
console.log('coming soon')
- if ((options.param.listen != null) || (options.param.id != null)) {
- console.log('bind:' + options.param.listen + ' id:' + options.param.id)
+ ip = options.param.listen.split(':')
+ if (ip.length) {
+ port = ip[1]
+ ip = ip[0]
+ } else {
+ port = '8080'
+ ip = ip[0]
}
+ console.log('ip: ' + ip + ' port: ' + port)
break
case 'greeting':
if (options.param.string != null) { |
fc346cf5958f310e5d55effcb5228fbcc895a3d1 | lib/node_modules/@stdlib/utils/is-array/lib/is_array.js | lib/node_modules/@stdlib/utils/is-array/lib/is_array.js | 'use strict';
/**
* Tests if a value is an array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an array
*
* @example
* var v = isArray( [] );
* // returns true
* @example
* var v = isArray( {} );
* // returns false
*/
function isArray( value ) {
return Object.prototype.toString.call( value ) === '[object Array]';
} // end FUNCTION isArray()
// EXPORTS //
module.exports = Array.isArray || isArray;
| 'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// IS ARRAY //
/**
* Tests if a value is an array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an array
*
* @example
* var v = isArray( [] );
* // returns true
* @example
* var v = isArray( {} );
* // returns false
*/
function isArray( value ) {
return ( nativeClass( value ) === '[object Array]' );
} // end FUNCTION isArray()
// EXPORTS //
module.exports = Array.isArray || isArray;
| Use utility to get a value's native class | Use utility to get a value's native class
| JavaScript | apache-2.0 | stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib | ---
+++
@@ -1,4 +1,11 @@
'use strict';
+
+// MODULES //
+
+var nativeClass = require( '@stdlib/utils/native-class' );
+
+
+// IS ARRAY //
/**
* Tests if a value is an array.
@@ -14,7 +21,7 @@
* // returns false
*/
function isArray( value ) {
- return Object.prototype.toString.call( value ) === '[object Array]';
+ return ( nativeClass( value ) === '[object Array]' );
} // end FUNCTION isArray()
|
7691059774b41fd7c911865586a9074ab8a285db | backend/timestamp-microservice/src/index.js | backend/timestamp-microservice/src/index.js | const express = require('express');
const app = express();
const manipulateString = require('./stringManipulator');
app.get('/:unix(\\d+)', (req, res) => {
res.send(manipulateString(req.params.unix));
});
app.listen(8000);
| const express = require('express');
const app = express();
const manipulateString = require('./stringManipulator');
app.get('/:string', (req, res) => {
res.send(manipulateString(req.params.string));
});
app.listen(8000, () => console.log('App is running on http://localhost:8000'));
| Implement routing for all strings | Implement routing for all strings
| JavaScript | mit | mkermani144/freecodecamp-projects,mkermani144/freecodecamp-projects | ---
+++
@@ -2,8 +2,8 @@
const app = express();
const manipulateString = require('./stringManipulator');
-app.get('/:unix(\\d+)', (req, res) => {
- res.send(manipulateString(req.params.unix));
+app.get('/:string', (req, res) => {
+ res.send(manipulateString(req.params.string));
});
-app.listen(8000);
+app.listen(8000, () => console.log('App is running on http://localhost:8000')); |
2e06e54041df649e3deff84eb34a193f24795e12 | src/users/usersActions.js | src/users/usersActions.js | /* @flow strict-local */
import differenceInSeconds from 'date-fns/difference_in_seconds';
import type { Dispatch, GetState, Narrow } from '../types';
import * as api from '../api';
import { PRESENCE_RESPONSE } from '../actionConstants';
import { getAuth, tryGetAuth } from '../selectors';
import { isPrivateOrGroupNarrow } from '../utils/narrow';
let lastReportPresence = new Date(0);
let lastTypingStart = new Date();
export const reportPresence = (hasFocus: boolean = true, newUserInput: boolean = false) => async (
dispatch: Dispatch,
getState: GetState,
) => {
const auth = tryGetAuth(getState());
if (!auth) {
return; // not logged in
}
if (differenceInSeconds(new Date(), lastReportPresence) < 60) {
return;
}
lastReportPresence = new Date();
const response = await api.reportPresence(auth, hasFocus, newUserInput);
dispatch({
type: PRESENCE_RESPONSE,
presence: response.presences,
serverTimestamp: response.server_timestamp,
});
};
export const sendTypingEvent = (narrow: Narrow) => async (
dispatch: Dispatch,
getState: GetState,
) => {
if (!isPrivateOrGroupNarrow(narrow)) {
return;
}
if (differenceInSeconds(new Date(), lastTypingStart) > 15) {
const auth = getAuth(getState());
api.typing(auth, narrow[0].operand, 'start');
lastTypingStart = new Date();
}
};
| /* @flow strict-local */
import differenceInSeconds from 'date-fns/difference_in_seconds';
import type { Dispatch, GetState, Narrow } from '../types';
import * as api from '../api';
import { PRESENCE_RESPONSE } from '../actionConstants';
import { getAuth, tryGetAuth } from '../selectors';
import { isPrivateOrGroupNarrow } from '../utils/narrow';
let lastReportPresence = new Date(0);
let lastTypingStart = new Date(0);
export const reportPresence = (hasFocus: boolean = true, newUserInput: boolean = false) => async (
dispatch: Dispatch,
getState: GetState,
) => {
const auth = tryGetAuth(getState());
if (!auth) {
return; // not logged in
}
if (differenceInSeconds(new Date(), lastReportPresence) < 60) {
return;
}
lastReportPresence = new Date();
const response = await api.reportPresence(auth, hasFocus, newUserInput);
dispatch({
type: PRESENCE_RESPONSE,
presence: response.presences,
serverTimestamp: response.server_timestamp,
});
};
export const sendTypingEvent = (narrow: Narrow) => async (
dispatch: Dispatch,
getState: GetState,
) => {
if (!isPrivateOrGroupNarrow(narrow)) {
return;
}
if (differenceInSeconds(new Date(), lastTypingStart) > 15) {
const auth = getAuth(getState());
api.typing(auth, narrow[0].operand, 'start');
lastTypingStart = new Date();
}
};
| Initialize lastTypingStart as "long ago", not "now". | typing-status: Initialize lastTypingStart as "long ago", not "now".
Similarly to the parent commit for presence, this was causing us
not to report the user typing in the first 15 seconds after
starting the app.
| JavaScript | apache-2.0 | vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile | ---
+++
@@ -8,7 +8,7 @@
import { isPrivateOrGroupNarrow } from '../utils/narrow';
let lastReportPresence = new Date(0);
-let lastTypingStart = new Date();
+let lastTypingStart = new Date(0);
export const reportPresence = (hasFocus: boolean = true, newUserInput: boolean = false) => async (
dispatch: Dispatch, |
a54f2261b6e9fb96f1945fb8cfeda86db79afd6d | src/api-umbrella/admin-ui/app/controllers/stats/base.js | src/api-umbrella/admin-ui/app/controllers/stats/base.js | import Ember from 'ember';
export default Ember.Controller.extend({
tz: jstz.determine().name(),
search: null,
interval: 'day',
prefix: '0/',
region: 'world',
start_at: moment().subtract(29, 'days').format('YYYY-MM-DD'),
end_at: moment().format('YYYY-MM-DD'),
query: JSON.stringify({
condition: 'AND',
rules: [{
field: 'gatekeeper_denied_code',
id: 'gatekeeper_denied_code',
input: 'select',
operator: 'is_null',
type: 'string',
value: null,
}],
}),
beta_analytics: false,
actions: {
submit() {
let query = this.get('query');
query.beginPropertyChanges();
if($('#filter_type_advanced').css('display') === 'none') {
query.set('params.search', '');
query.set('params.query', JSON.stringify($('#query_builder').queryBuilder('getRules')));
} else {
query.set('params.query', '');
query.set('params.search', $('#filter_form input[name=search]').val());
}
query.endPropertyChanges();
},
},
});
| import Ember from 'ember';
export default Ember.Controller.extend({
tz: jstz.determine().name(),
search: '',
interval: 'day',
prefix: '0/',
region: 'world',
start_at: moment().subtract(29, 'days').format('YYYY-MM-DD'),
end_at: moment().format('YYYY-MM-DD'),
query: JSON.stringify({
condition: 'AND',
rules: [{
field: 'gatekeeper_denied_code',
id: 'gatekeeper_denied_code',
input: 'select',
operator: 'is_null',
type: 'string',
value: null,
}],
}),
beta_analytics: false,
actions: {
submit() {
if($('#filter_type_advanced').css('display') === 'none') {
this.set('search', '');
this.set('query', JSON.stringify($('#query_builder').queryBuilder('getRules')));
} else {
this.set('query', '');
this.set('search', $('#filter_form input[name=search]').val());
}
},
},
});
| Fix submitting query builder form params. | Fix submitting query builder form params.
| JavaScript | mit | apinf/api-umbrella,apinf/api-umbrella,NREL/api-umbrella,NREL/api-umbrella,apinf/api-umbrella,apinf/api-umbrella,NREL/api-umbrella,NREL/api-umbrella,apinf/api-umbrella | ---
+++
@@ -2,7 +2,7 @@
export default Ember.Controller.extend({
tz: jstz.determine().name(),
- search: null,
+ search: '',
interval: 'day',
prefix: '0/',
region: 'world',
@@ -23,18 +23,13 @@
actions: {
submit() {
- let query = this.get('query');
- query.beginPropertyChanges();
-
if($('#filter_type_advanced').css('display') === 'none') {
- query.set('params.search', '');
- query.set('params.query', JSON.stringify($('#query_builder').queryBuilder('getRules')));
+ this.set('search', '');
+ this.set('query', JSON.stringify($('#query_builder').queryBuilder('getRules')));
} else {
- query.set('params.query', '');
- query.set('params.search', $('#filter_form input[name=search]').val());
+ this.set('query', '');
+ this.set('search', $('#filter_form input[name=search]').val());
}
-
- query.endPropertyChanges();
},
},
}); |
39979ccb430d762171a5c6b13e95470e101618c9 | scripts/parser/parser.js | scripts/parser/parser.js | define(['util'], function(util) {
'use strict';
var Parser = function () {
}
Parser.prototype.parse = function () {
console.log('Error: Pure virtual parse called!');
return {};
}
Parser.prototype.prepare = function (input) {
input = input.split('\n');
util.forEach(input, function (line, l) {
var i;
line = line.split(' ');
i = 0;
while(i < line.length) {
if (line[i] == '') {
line.splice(i, 1);
} else {
++i;
}
}
input[l] = line;
});
return input;
}
return Parser;
});
| define(['util'], function(util) {
'use strict';
var Parser = function () {
}
Parser.prototype.parse = function () {
console.log('Error: Pure virtual parse called!');
return {};
}
Parser.prototype.prepare = function (input) {
var i;
input = input.split('\n');
util.forEach(input, function (line, l) {
line = line.split(' ');
i = 0;
while(i < line.length) {
if (line[i] == '') {
line.splice(i, 1);
} else {
++i;
}
}
input[l] = line;
});
i = 0;
while (i < input.length) {
if (input[i].length == 0) {
input.splice(i, 1);
} else {
++i;
}
}
console.log(input);
return input;
}
return Parser;
});
| Remove empty lines in preprocessing | Remove empty lines in preprocessing
| JavaScript | mit | fumyuun/visualtrace | ---
+++
@@ -10,10 +10,10 @@
}
Parser.prototype.prepare = function (input) {
+ var i;
input = input.split('\n');
util.forEach(input, function (line, l) {
- var i;
line = line.split(' ');
i = 0;
while(i < line.length) {
@@ -26,6 +26,17 @@
input[l] = line;
});
+ i = 0;
+ while (i < input.length) {
+ if (input[i].length == 0) {
+ input.splice(i, 1);
+ } else {
+ ++i;
+ }
+ }
+
+ console.log(input);
+
return input;
}
|
e5cd3df4ec94dd86eea827fbb94f2dd949043958 | controllers/motif-tag.js | controllers/motif-tag.js | const config = require('collections-online/lib/config');
const cip = require('../services/cip');
const CROWD_TAGS = '{73be3a90-a8ef-4a42-aa8f-d16ca4f55e0a}';
function saveToCip(catalog, id, values) {
return cip.setFieldValues(catalog, id, 'web', values)
.then(function(response) {
if (response.statusCode !== 200) {
throw new Error('Failed to set the field values');
}
});
}
module.exports.save = (metadata) => {
var values = {};
values[CROWD_TAGS] = metadata.tags_crowd.join(',');
return saveToCip(metadata.collection, metadata.id, values).then(function() {
return metadata;
});
}
module.exports.updateIndex = (metadata) => {
const es = require('collections-online/lib/services/elasticsearch');
// TODO: Consider that elasticsearch might not be the only way to update the
// document index.
var indexingState = {
es: es,
index: config.types.asset.index
};
var transformations = [
require('../indexing/transformations/tag-hierarchy')
];
// The CIP specific indexing code requires a catalog instead of collection
metadata.catalog = metadata.collection;
const indexAsset = require('../indexing/processing/asset');
return indexAsset(indexingState, metadata, transformations);
}
| const config = require('collections-online/lib/config');
const cip = require('../services/cip');
const CROWD_TAGS = '{73be3a90-a8ef-4a42-aa8f-d16ca4f55e0a}';
function saveToCip(catalog, id, values) {
return cip.setFieldValues(catalog, id, 'web', values)
.then(function(response) {
if (response.statusCode !== 200) {
throw new Error('Failed to set the field values');
}
});
}
module.exports.save = (metadata) => {
// Save it using the CIP
var values = {};
values[CROWD_TAGS] = metadata.tags.join(',');
return saveToCip(metadata.collection, metadata.id, values).then(function() {
return metadata;
});
}
module.exports.updateIndex = (metadata) => {
const es = require('collections-online/lib/services/elasticsearch');
// TODO: Consider that elasticsearch might not be the only way to update the
// document index.
var indexingState = {
es: es,
index: config.types.asset.index
};
var transformations = [
require('../indexing/transformations/tag-hierarchy')
];
// The CIP specific indexing code requires a catalog instead of collection
metadata.catalog = metadata.collection;
const indexAsset = require('../indexing/processing/asset');
return indexAsset(indexingState, metadata, transformations);
}
| Read from the tags array when saving | Read from the tags array when saving
| JavaScript | mit | CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder | ---
+++
@@ -13,8 +13,9 @@
}
module.exports.save = (metadata) => {
+ // Save it using the CIP
var values = {};
- values[CROWD_TAGS] = metadata.tags_crowd.join(',');
+ values[CROWD_TAGS] = metadata.tags.join(',');
return saveToCip(metadata.collection, metadata.id, values).then(function() {
return metadata;
}); |
d2276322b44b06ac8a6a6d0894c2d38aaf155754 | cli.js | cli.js | #!/usr/bin/env node
require("./index.js");
| #!/usr/bin/env node
// Copy over the index.html
var fs = require("fs");
var path = require("path");
fs.createReadStream(path.join(__dirname, "index.html"))
.pipe(fs.createWriteStream("index.html"));
// Launch the server.
require("./index.js");
| Modify CLI to copy index.html | Modify CLI to copy index.html
| JavaScript | mit | curran/example-viewer,curran/example-viewer | ---
+++
@@ -1,2 +1,10 @@
#!/usr/bin/env node
+
+// Copy over the index.html
+var fs = require("fs");
+var path = require("path");
+fs.createReadStream(path.join(__dirname, "index.html"))
+ .pipe(fs.createWriteStream("index.html"));
+
+// Launch the server.
require("./index.js"); |
4567bba78bc90c645e813f88577c6ada3ff7bc5d | cli.js | cli.js | #!/usr/bin/env node
'use strict';
var meow = require('meow');
var sha1Cli = require('./');
var cli = meow([
'Usage',
' $ sha1-cli [input]',
'',
'Options',
' --foo Lorem ipsum. [Default: false]',
'',
'Examples',
' $ sha1-cli',
' unicorns & rainbows',
' $ sha1-cli ponies',
' ponies & rainbows'
]);
console.log(sha1Cli(cli.input[0] || 'unicorns'));
| #!/usr/bin/env node
'use strict';
var meow = require('meow');
var sha1Cli = require('./');
var cli = meow([
'Usage',
' $ sha1-cli [input]',
'',
'Options',
' --sum file to compare sha1 sum. [Default: sha1.txt]',
' --sha1 display sha1 sum of given file.',
'',
'Examples',
' $ sha1-cli ponies --sha1',
' c25db8c82904f163f1148c4a7e0b843601c49c9d',
' $ sha1-cli ponies --sum rainbow.sha1.txt',
' Passed :)'
]);
console.log(sha1Cli(cli));
| Add flags for comparing and displaying | Add flags for comparing and displaying
| JavaScript | mit | niksrc/sha1-cli | ---
+++
@@ -8,13 +8,14 @@
' $ sha1-cli [input]',
'',
'Options',
- ' --foo Lorem ipsum. [Default: false]',
+ ' --sum file to compare sha1 sum. [Default: sha1.txt]',
+ ' --sha1 display sha1 sum of given file.',
'',
'Examples',
- ' $ sha1-cli',
- ' unicorns & rainbows',
- ' $ sha1-cli ponies',
- ' ponies & rainbows'
+ ' $ sha1-cli ponies --sha1',
+ ' c25db8c82904f163f1148c4a7e0b843601c49c9d',
+ ' $ sha1-cli ponies --sum rainbow.sha1.txt',
+ ' Passed :)'
]);
-console.log(sha1Cli(cli.input[0] || 'unicorns'));
+console.log(sha1Cli(cli)); |
4e8a78a944d0435808dafb0caa87533ed0f0d8b8 | config/webpackResolve.js | config/webpackResolve.js | 'use strict'
const path = require('./path')
module.exports = {
alias: {
bemuse: path('src'),
},
extensions: ['.webpack.js', '.web.js', '.js', '.jsx'],
}
| 'use strict'
const path = require('./path')
module.exports = {
alias: {
bemuse: path('src'),
},
extensions: ['.webpack.js', '.web.js', '.js', '.jsx', '.ts', '.tsx'],
}
| Allow webpack to resolve to ts/tsx files | Allow webpack to resolve to ts/tsx files
| JavaScript | agpl-3.0 | bemusic/bemuse,bemusic/bemuse,bemusic/bemuse,bemusic/bemuse,bemusic/bemuse | ---
+++
@@ -6,5 +6,5 @@
alias: {
bemuse: path('src'),
},
- extensions: ['.webpack.js', '.web.js', '.js', '.jsx'],
+ extensions: ['.webpack.js', '.web.js', '.js', '.jsx', '.ts', '.tsx'],
} |
ea7ee71c1ce86ad2528bcf38fbae809927100d71 | appsrc/logger/index.js | appsrc/logger/index.js |
import env from '../env'
const full = (process.type !== 'renderer' && env.name !== 'test')
import pathmaker from '../util/pathmaker'
import mklog from '../util/log'
const loggerOpts = {
sinks: {}
}
if (full) {
loggerOpts.sinks.file = pathmaker.logPath()
}
export const logger = new mklog.Logger(loggerOpts)
export default logger
const log = mklog('itch')
export const opts = {logger}
if (full) {
log(opts, `using electron ${process.versions.electron}`)
}
|
import ospath from 'path'
import mkdirp from 'mkdirp'
import env from '../env'
const full = (process.type !== 'renderer' && env.name !== 'test')
import pathmaker from '../util/pathmaker'
import mklog from '../util/log'
// naughty
try {
mkdirp.sync(ospath.dirname(pathmaker.logPath()))
} catch (e) {
if (e.code !== 'EEXIST') {
console.log(`While creating logs dir: ${e.stack}`)
}
}
const loggerOpts = {
sinks: {}
}
if (full) {
loggerOpts.sinks.file = pathmaker.logPath()
}
export const logger = new mklog.Logger(loggerOpts)
export default logger
const log = mklog('itch')
export const opts = {logger}
if (full) {
log(opts, `using electron ${process.versions.electron}`)
}
| Create logs directory on first launch | Create logs directory on first launch
| JavaScript | mit | itchio/itchio-app,itchio/itch,itchio/itch,itchio/itch,leafo/itchio-app,itchio/itchio-app,itchio/itchio-app,leafo/itchio-app,itchio/itch,itchio/itch,leafo/itchio-app,itchio/itch | ---
+++
@@ -1,9 +1,22 @@
+
+import ospath from 'path'
+import mkdirp from 'mkdirp'
import env from '../env'
const full = (process.type !== 'renderer' && env.name !== 'test')
import pathmaker from '../util/pathmaker'
import mklog from '../util/log'
+
+// naughty
+try {
+ mkdirp.sync(ospath.dirname(pathmaker.logPath()))
+} catch (e) {
+ if (e.code !== 'EEXIST') {
+ console.log(`While creating logs dir: ${e.stack}`)
+ }
+}
+
const loggerOpts = {
sinks: {}
} |
5711d4bb9fa6a4a3bc05a0b666a6923a08461039 | client/prefetch.js | client/prefetch.js | function Prefetch() {
this.hooks();
}
Prefetch.prototype.hooks = function () {
var links = document.querySelectorAll('a');
for (var n = 0; n < links.length; n++) {
links[n].addEventListener('mousedown', function (event) {
// Left mouse click
if (event.which == 1) {
var prefetch = document.createElement('link');
prefetch.rel = 'prefetch';
prefetch.href = this.href;
document.head.appendChild(prefetch);
}
}, false);
}
}; | function Prefetch() {
this.hooks();
}
Prefetch.prototype.hooks = function () {
var links = document.querySelectorAll('a');
var length = links.length;
for (var n = 0; n < length; n++) {
var prefetchFunction = function (event) {
// Left mouse click or Touch
if (event.constructor.name === 'TouchEvent' || event.which === 1) {
var prefetch = document.createElement('link');
prefetch.rel = 'prefetch';
prefetch.href = this.href;
document.head.appendChild(prefetch);
}
};
['touchstart', 'mousedown'].forEach(value => {
links[n].addEventListener(value, prefetchFunction, false);
});
}
}; | Add touchstart to support touch devices | Add touchstart to support touch devices
| JavaScript | apache-2.0 | Jarzon/prefetch.js | ---
+++
@@ -5,11 +5,13 @@
Prefetch.prototype.hooks = function () {
var links = document.querySelectorAll('a');
- for (var n = 0; n < links.length; n++) {
+ var length = links.length;
- links[n].addEventListener('mousedown', function (event) {
- // Left mouse click
- if (event.which == 1) {
+ for (var n = 0; n < length; n++) {
+
+ var prefetchFunction = function (event) {
+ // Left mouse click or Touch
+ if (event.constructor.name === 'TouchEvent' || event.which === 1) {
var prefetch = document.createElement('link');
prefetch.rel = 'prefetch';
@@ -18,6 +20,10 @@
document.head.appendChild(prefetch);
}
- }, false);
+ };
+
+ ['touchstart', 'mousedown'].forEach(value => {
+ links[n].addEventListener(value, prefetchFunction, false);
+ });
}
}; |
9bb3b78061aea385b86ae3c052f596d6b3b4cf78 | app/routes/page/index.js | app/routes/page/index.js | import BaseRoute from '../_base';
export default BaseRoute.extend({
model: function() {
return this.modelFor('page');
},
setupController: function(controller, page) {
this.set('title', [page.get('treatise.title'), page.get('title')].join(' - '));
controller.set('controllers.page.boundsRect', page.get('bounds'));
this._super(controller, page);
},
actions: {
// Hooks the page click event to navigate to the clicked section image
pageClick: function(logicalPoint) {
var sections = this.modelFor('page').get('sections'),
x = logicalPoint.x,
y = logicalPoint.y,
section = sections.find(function(section) {
var bounds = section.get('bounds');
return (x >= bounds.x && x < bounds.x + bounds.width) &&
(y >= bounds.y && y < bounds.y + bounds.height);
});
if(section) {
this.transitionTo('page.section', section.get('page'), section.get('sortOrder'));
}
return false;
}
}
});
| import BaseRoute from '../_base';
export default BaseRoute.extend({
model: function() {
return this.modelFor('page');
},
setupController: function(controller, page) {
this.set('title', [page.get('treatise.title'), page.get('title')].join(' - '));
controller.set('controllers.page.boundsRect', page.get('bounds'));
this._super(controller, page);
},
actions: {
// Hooks the page click event to navigate to the clicked section image
pageClick: function(logicalPoint) {
var sections = this.modelFor('page').get('sections'),
x = logicalPoint.x,
y = logicalPoint.y,
section = sections.find(function(section) {
var bounds = section.get('osBounds');
return (x >= bounds.x && x < bounds.x + bounds.width) &&
(y >= bounds.y && y < bounds.y + bounds.height);
});
if(section) {
this.transitionTo('page.section', section.get('page'), section.get('sortOrder'));
}
return false;
}
}
});
| Fix page boundary hit detection | Fix page boundary hit detection
| JavaScript | mit | artzte/fightbook-app | ---
+++
@@ -16,7 +16,7 @@
x = logicalPoint.x,
y = logicalPoint.y,
section = sections.find(function(section) {
- var bounds = section.get('bounds');
+ var bounds = section.get('osBounds');
return (x >= bounds.x && x < bounds.x + bounds.width) &&
(y >= bounds.y && y < bounds.y + bounds.height);
}); |
7d86f812b768a7a703af6bdc9a762d2b7a8de853 | commands/remove.js | commands/remove.js | 'use strict';
const util = require('util');
const CommandUtil = require('../src/command_util').CommandUtil;
const l10nFile = __dirname + '/../l10n/commands/remove.yml';
const l10n = require('../src/l10n')(l10nFile);
const _ = require('../src/helpers');
exports.command = (rooms, items, players, npcs, Commands) => {
return (args, player, isDead) => {
const target = _.firstWord(args);
if (target === 'all') { return Commands.player_commands.drop('all', player); }
const thing = CommandUtil.findItemInEquipment(items, target, player, true);
if (thing.isEquipped()) {
return remove(thing);
} else {
return player.warn(`${thing.getShortDesc()} is not equipped.`);
}
function remove(item) {
if (!item && !isDead) {
return player.sayL10n(l10n, 'ITEM_NOT_FOUND');
}
util.log(player.getName() + ' removing ' + item.getShortDesc('en'));
const success = player.unequip(item, items, players);
if (!success) { return player.say(`You are unable to unequip ${item.getShortDesc()}.`); }
if (isDead) { return; }
const room = rooms.getAt(player.getLocation());
item.emit('remove', location, room, player, players);
}
};
};
| 'use strict';
const util = require('util');
const CommandUtil = require('../src/command_util').CommandUtil;
const l10nFile = __dirname + '/../l10n/commands/remove.yml';
const l10n = require('../src/l10n')(l10nFile);
const _ = require('../src/helpers');
exports.command = (rooms, items, players, npcs, Commands) => {
return (args, player, isDead) => {
const target = _.firstWord(args);
if (target === 'all') { return Commands.player_commands.drop('all', player); }
const thing = CommandUtil.findItemInEquipment(items, target, player, true);
if (thing.isEquipped()) {
return remove(thing);
} else {
return player.warn(`${thing.getShortDesc()} is not equipped.`);
}
function remove(item) {
if (!item && !isDead) {
return player.sayL10n(l10n, 'ITEM_NOT_FOUND');
}
util.log(player.getName() + ' removing ' + item.getShortDesc('en'));
const location = player.unequip(item, items, players);
if (!location) { return player.say(`You are unable to unequip ${item.getShortDesc()}.`); }
if (isDead) { return; }
const room = rooms.getAt(player.getLocation());
item.emit('remove', location, room, player, players);
}
};
};
| Remove had a bug due to bad reference. | Remove had a bug due to bad reference.
| JavaScript | mit | seanohue/ranviermud,seanohue/ranviermud,shawncplus/ranviermud | ---
+++
@@ -28,9 +28,9 @@
util.log(player.getName() + ' removing ' + item.getShortDesc('en'));
- const success = player.unequip(item, items, players);
- if (!success) { return player.say(`You are unable to unequip ${item.getShortDesc()}.`); }
- if (isDead) { return; }
+ const location = player.unequip(item, items, players);
+ if (!location) { return player.say(`You are unable to unequip ${item.getShortDesc()}.`); }
+ if (isDead) { return; }
const room = rooms.getAt(player.getLocation());
item.emit('remove', location, room, player, players); |
36e5d39271eeed02fce6453a92ef86aa0462880e | demo.js | demo.js | var browserify = require('browserify');
var brfs = require('brfs');
var through = require('through');
var fs = require('fs');
require('browserify/lib/builtins').fs = 'create-webfs.js'; // TODO: find a better way to replace this module
var b = browserify();
var textReplacements = [
[/rfile\('.\/template.js'\)/, JSON.stringify(fs.readFileSync('node_modules//browserify/node_modules/umd/template.js', 'utf8'))],
];
// directly include rfile TODO: use brfs, but it replaces fs.readFileSync
b.transform(function(s) {
var data = '';
return through(write, end);
function write(buf) { data += buf; }
function end() {
for (var i = 0; i < textReplacements.length; i += 1) {
var regex = textReplacements[i][0];
var replacement = textReplacements[i][1];
data = data.replace(regex, replacement);
}
this.queue(data);
this.queue(null);
};
}, { global: true });
b.transform('brfs');
b.add('./webnpm.js');
b.bundle().pipe(process.stdout);
| var browserify = require('browserify');
var brfs = require('brfs');
var through = require('through');
var fs = require('fs');
require('browserify/lib/builtins').fs = 'create-webfs.js'; // TODO: find a better way to replace this module
var b = browserify();
var textReplacements = [
[/rfile\('.\/template.js'\)/, JSON.stringify(fs.readFileSync('node_modules//browserify/node_modules/umd/template.js', 'utf8'))],
[/fs\.readFileSync\(defaultPreludePath, 'utf8'\)/, JSON.stringify(fs.readFileSync('node_modules/browserify/node_modules/browser-pack/_prelude.js', 'utf8'))],
];
// directly include rfile TODO: use brfs, but it replaces fs.readFileSync
b.transform(function(s) {
var data = '';
return through(write, end);
function write(buf) { data += buf; }
function end() {
for (var i = 0; i < textReplacements.length; i += 1) {
var regex = textReplacements[i][0];
var replacement = textReplacements[i][1];
data = data.replace(regex, replacement);
}
this.queue(data);
this.queue(null);
};
}, { global: true });
b.transform('brfs');
b.add('./webnpm.js');
b.bundle().pipe(process.stdout);
| Substitute the default prelude in browser-pack, brfs doesn't seem to pick it up | Substitute the default prelude in browser-pack, brfs doesn't seem to pick it up
| JavaScript | mit | deathcap/webnpm,deathcap/webnpm | ---
+++
@@ -9,6 +9,7 @@
var textReplacements = [
[/rfile\('.\/template.js'\)/, JSON.stringify(fs.readFileSync('node_modules//browserify/node_modules/umd/template.js', 'utf8'))],
+ [/fs\.readFileSync\(defaultPreludePath, 'utf8'\)/, JSON.stringify(fs.readFileSync('node_modules/browserify/node_modules/browser-pack/_prelude.js', 'utf8'))],
];
// directly include rfile TODO: use brfs, but it replaces fs.readFileSync |
0a34860a5b02741f8f869d9d17e88d7a00d8cfb2 | tasks/lint/colors.js | tasks/lint/colors.js | 'use strict';
var gulp = require('gulp'),
config = require('../../config'),
postcss = require('gulp-postcss'),
colorguard = require('colorguard'),
filterstream = require('postcss-filter-stream'),
scss = require('postcss-scss');
module.exports = function () {
return gulp
.src(config.src.styles)
.pipe(postcss([
filterstream('**/node_modules/**', colorguard())
], {syntax: scss}));
};
| 'use strict';
var gulp = require('gulp'),
config = require('../../config'),
postcss = require('gulp-postcss'),
colorguard = require('colorguard');
module.exports = function () {
return gulp
.src(config.src.css)
.pipe(postcss([colorguard()]));
};
| Fix source for task and remove SCSS syntax support | Fix source for task and remove SCSS syntax support
| JavaScript | mit | craigsimps/gulp-wp-toolkit | ---
+++
@@ -3,14 +3,10 @@
var gulp = require('gulp'),
config = require('../../config'),
postcss = require('gulp-postcss'),
- colorguard = require('colorguard'),
- filterstream = require('postcss-filter-stream'),
- scss = require('postcss-scss');
+ colorguard = require('colorguard');
module.exports = function () {
return gulp
- .src(config.src.styles)
- .pipe(postcss([
- filterstream('**/node_modules/**', colorguard())
- ], {syntax: scss}));
+ .src(config.src.css)
+ .pipe(postcss([colorguard()]));
}; |
ec2c1bf9a9573b0d1dd4ca1c1c86a189a22153f4 | generators/polymer-app/templates/server/routes/components.dev.js | generators/polymer-app/templates/server/routes/components.dev.js | const express = require('express');
const path = require('path');
const fs = require('fs');
const router = express.Router();
// Stamp css content into html during development.
router.get('/custom-components/:component/*.html', (req, res) => {
const element = req.params.component;
const elementPath = path.join(__dirname, `../../public/${element}/${element}`);
fs.readFile(`${elementPath}.html`, { encoding: 'utf-8' }, function (err, html) {
if (err) {
throw err;
}
fs.readFile(`${elementPath}.css`, { encoding: 'utf-8' }, function (err, css) {
if (err) {
throw err;
}
// Find the style tag that references the component's css.
const stampLocation = new RegExp(`^[\S\s]+(<link.*href=".*?${element}.css.*?".*?\/>)`);
const taggedCss = `<style>${css}</style>`;
res.send(html.replace(stampLocation, taggedCss));
});
});
});
// Don't send the css file if it has been requested directly.
router.get('/custom-components/**/*.css', (req, res) => {
res.send('');
});
// TODO: Add route to transpile js on request.
//router.get('/custom-components/**/*.js', (req, res) => { });
module.exports = {
mountPath: '/',
router: router
};
| const express = require('express');
const path = require('path');
const fs = require('fs');
const router = express.Router();
// Stamp css content into html during development.
router.get('/custom-components/:component/*.html', (req, res) => {
const element = req.params.component;
const elementPath = path.join(__dirname, `../../public/custom-components/${element}/${element}`);
fs.readFile(`${elementPath}.html`, 'utf-8', (err, html) => {
if (err) {
throw err;
}
fs.readFile(`${elementPath}.css`, 'utf-8', (err, css) => {
if (err) {
throw err;
}
// Find the style tag that references the component's css.
const stampLocation = new RegExp(`<template><link.*href=".*?${element}.css.*?".*?\/?>)`);
const taggedCss = `<template><style>${css}</style>`;
res.send(html.replace(stampLocation, taggedCss));
});
});
});
// Don't send the css file if it has been requested directly.
router.get('/custom-components/**/*.css', (req, res) => {
res.send('');
});
// TODO: Add route to transpile js on request.
//router.get('/custom-components/**/*.js', (req, res) => { });
module.exports = {
mountPath: '/',
router: router
};
| Change regex to find the css import directly after the template. Fix bug in path to custom-component element. | Change regex to find the css import directly after the template.
Fix bug in path to custom-component element.
| JavaScript | bsd-2-clause | KK578/generator-kk578,KK578/generator-kk578 | ---
+++
@@ -7,21 +7,21 @@
// Stamp css content into html during development.
router.get('/custom-components/:component/*.html', (req, res) => {
const element = req.params.component;
- const elementPath = path.join(__dirname, `../../public/${element}/${element}`);
+ const elementPath = path.join(__dirname, `../../public/custom-components/${element}/${element}`);
- fs.readFile(`${elementPath}.html`, { encoding: 'utf-8' }, function (err, html) {
+ fs.readFile(`${elementPath}.html`, 'utf-8', (err, html) => {
if (err) {
throw err;
}
- fs.readFile(`${elementPath}.css`, { encoding: 'utf-8' }, function (err, css) {
+ fs.readFile(`${elementPath}.css`, 'utf-8', (err, css) => {
if (err) {
throw err;
}
// Find the style tag that references the component's css.
- const stampLocation = new RegExp(`^[\S\s]+(<link.*href=".*?${element}.css.*?".*?\/>)`);
- const taggedCss = `<style>${css}</style>`;
+ const stampLocation = new RegExp(`<template><link.*href=".*?${element}.css.*?".*?\/?>)`);
+ const taggedCss = `<template><style>${css}</style>`;
res.send(html.replace(stampLocation, taggedCss));
}); |
02419fb3e5089865fbd9c491cfd4b49d2e1e653d | lib/assets/test/spec/cartodb3/routes/handle-modals-route.spec.js | lib/assets/test/spec/cartodb3/routes/handle-modals-route.spec.js | var handleModalsRoute = require('cartodb3/routes/handle-modals-route');
describe('routes/handleModalsRoute', function () {
it('should handle modals route', function () {
var modals = jasmine.createSpyObj('modals', ['destroy']);
handleModalsRoute(['layer_analyses', 'l1-1', 'a1', null], modals);
expect(modals.destroy).toHaveBeenCalled();
});
});
| var handleModalsRoute = require('cartodb3/routes/handle-modals-route');
describe('routes/handleModalsRoute', function () {
it('should handle modals route', function () {
var modals = jasmine.createSpyObj('modals', ['destroy']);
handleModalsRoute(['layer_analyses', 'l1-1', 'a1', null], modals);
expect(modals.destroy).toHaveBeenCalled();
});
it('should not destroy modals when route changes and `keepOnRouteChange` property is enabled', function () {
var modals = {
keepOnRouteChange: function () { return true },
destroy: jasmine.createSpy('destroy')
};
handleModalsRoute(['layer_analyses', 'l1-1', 'a1', null], modals);
expect(modals.destroy).not.toHaveBeenCalled();
});
});
| Add tests for keepOnRouteChange property | Add tests for keepOnRouteChange property
| JavaScript | bsd-3-clause | CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb | ---
+++
@@ -8,4 +8,15 @@
expect(modals.destroy).toHaveBeenCalled();
});
+
+ it('should not destroy modals when route changes and `keepOnRouteChange` property is enabled', function () {
+ var modals = {
+ keepOnRouteChange: function () { return true },
+ destroy: jasmine.createSpy('destroy')
+ };
+
+ handleModalsRoute(['layer_analyses', 'l1-1', 'a1', null], modals);
+
+ expect(modals.destroy).not.toHaveBeenCalled();
+ });
}); |
67d714821f4d1cf8366673c7e5b3e72d578ce4b6 | test/proxy/common.js | test/proxy/common.js | import http from 'http'
import request from 'request'
import createProxy from '../../src/lib/proxy'
import tap from 'tap'
function setup (options, cb) {
if (typeof options === 'function') {
cb = options
options = {}
}
const server = http.createServer()
const serverStarted = () => {
createProxy(options, proxyStarted)
}
const proxyStarted = (err, proxy) => {
if (err) tap.bailout('can not create proxy...')
server.on('close', proxy.close.bind(proxy))
return cb(null, {
request: request.defaults({'proxy': 'http://127.0.0.1:' + proxy.address().port}),
server
})
}
server.listen(0, serverStarted)
}
export default { setup }
| import http from 'http'
import request from 'request'
import createProxy from '../../src/lib/proxy'
import tap from 'tap'
function setup (options, cb) {
if (typeof options === 'function') {
cb = options
options = {}
}
const server = http.createServer()
const serverStarted = () => {
createProxy(options, proxyStarted)
}
const proxyStarted = (err, proxies) => {
if (err) tap.bailout('can not create proxy...')
server.on('close', proxies[0].close.bind(proxies[0]))
server.on('close', proxies[1].close.bind(proxies[1]))
return cb(null, {
request: request.defaults({'proxy': 'http://127.0.0.1:' + proxies[0].address().port}),
server
})
}
server.listen(0, serverStarted)
}
export default { setup }
| Test - Update proxy tests. | Test - Update proxy tests.
| JavaScript | isc | niklasi/halland-proxy,niklasi/halland-proxy | ---
+++
@@ -15,12 +15,13 @@
createProxy(options, proxyStarted)
}
- const proxyStarted = (err, proxy) => {
+ const proxyStarted = (err, proxies) => {
if (err) tap.bailout('can not create proxy...')
- server.on('close', proxy.close.bind(proxy))
+ server.on('close', proxies[0].close.bind(proxies[0]))
+ server.on('close', proxies[1].close.bind(proxies[1]))
return cb(null, {
- request: request.defaults({'proxy': 'http://127.0.0.1:' + proxy.address().port}),
+ request: request.defaults({'proxy': 'http://127.0.0.1:' + proxies[0].address().port}),
server
})
} |
b4757cbef2d1326ae31c9010c49de70b737b9d5a | lib/task-data/tasks/install-ubuntu.js | lib/task-data/tasks/install-ubuntu.js | // Copyright 2015, EMC, Inc.
'use strict';
module.exports = {
friendlyName: 'Install Ubuntu',
injectableName: 'Task.Os.Install.Ubuntu',
implementsTask: 'Task.Base.Os.Install',
schemaRef: 'rackhd/schemas/v1/tasks/install-os-general',
options: {
osType: 'linux', //readonly options, should avoid change it
profile: 'install-ubuntu.ipxe',
installScript: 'ubuntu-preseed',
installScriptUri: '{{api.templates}}/{{options.installScript}}',
hostname: 'localhost',
comport: 'ttyS0',
completionUri: 'renasar-ansible.pub',
version: 'trusty',
repo: '{{api.server}}/ubuntu',
netImage: '{{api.server}}/ubuntu/install/filesystem.squashfs',
rootPassword: "RackHDRocks!",
rootSshKey: null,
interface: "auto",
users: [],
networkDevices: [],
dnsServers: [],
installDisk: null,
kvm: false
},
properties: {
os: {
linux: {
distribution: 'ubuntu'
}
}
}
};
| // Copyright 2015, EMC, Inc.
'use strict';
module.exports = {
friendlyName: 'Install Ubuntu',
injectableName: 'Task.Os.Install.Ubuntu',
implementsTask: 'Task.Base.Os.Install',
schemaRef: 'rackhd/schemas/v1/tasks/install-os-general',
options: {
osType: 'linux', //readonly options, should avoid change it
profile: 'install-ubuntu.ipxe',
installScript: 'ubuntu-preseed',
installScriptUri: '{{api.templates}}/{{options.installScript}}',
hostname: 'localhost',
comport: 'ttyS0',
completionUri: 'renasar-ansible.pub',
repo: '{{api.server}}/ubuntu',
baseUrl: 'dists/trusty/main/installer-amd64/current/images/netboot/ubuntu-installer/amd64',
rootPassword: "RackHDRocks!",
interface: "auto",
installDisk: "/dev/sda",
kvm: false,
kargs:{}
},
properties: {
os: {
linux: {
distribution: 'ubuntu'
}
}
}
};
| Allow Netimage option to be optional | Allow Netimage option to be optional
| JavaScript | apache-2.0 | bbcyyb/on-tasks,AlaricChan/on-tasks,nortonluo/on-tasks,bbcyyb/on-tasks,AlaricChan/on-tasks,nortonluo/on-tasks | ---
+++
@@ -15,17 +15,13 @@
hostname: 'localhost',
comport: 'ttyS0',
completionUri: 'renasar-ansible.pub',
- version: 'trusty',
repo: '{{api.server}}/ubuntu',
- netImage: '{{api.server}}/ubuntu/install/filesystem.squashfs',
+ baseUrl: 'dists/trusty/main/installer-amd64/current/images/netboot/ubuntu-installer/amd64',
rootPassword: "RackHDRocks!",
- rootSshKey: null,
interface: "auto",
- users: [],
- networkDevices: [],
- dnsServers: [],
- installDisk: null,
- kvm: false
+ installDisk: "/dev/sda",
+ kvm: false,
+ kargs:{}
},
properties: {
os: { |
d84624ec16f82b708e44deb8d5f3172f95dd1764 | src/rules/jsx-no-logical-expression.js | src/rules/jsx-no-logical-expression.js | const createFixer = ({range, left, right, operator}, source) => fixer => {
const [leftStart, leftEnd] = left.range;
const [rightStart] = right.range;
const operatorRange = [leftEnd, rightStart];
const operatorText = source.slice(...operatorRange);
if (operator === '||') {
const leftText = source.slice(leftStart, leftEnd);
return [
fixer.replaceTextRange(operatorRange, operatorText.replace(operator, `? ${leftText} :`))
];
}
return [
fixer.replaceTextRange(operatorRange, operatorText.replace(operator, '?')),
fixer.insertTextAfterRange(range, ' : null')
];
};
const create = context => ({
LogicalExpression: node => {
if (node.right.type === 'JSXElement') {
context.report({
node,
message: 'JSX should not use logical expression',
fix: createFixer(node, context.getSourceCode().getText())
});
}
}
});
module.exports = {
create,
createFixer,
meta: {
docs: {
description: 'Prevent falsy values to be printed'
},
fixable: 'code'
}
};
| const createFixer =
({range, left, right, operator}, source) =>
fixer => {
const [leftStart, leftEnd] = left.range;
const [rightStart] = right.range;
const operatorRange = [leftEnd, rightStart];
const operatorText = source.slice(...operatorRange);
if (operator === '||') {
const leftText = source.slice(leftStart, leftEnd);
return [
fixer.replaceTextRange(operatorRange, operatorText.replace(operator, `? ${leftText} :`))
];
}
return [
fixer.replaceTextRange(operatorRange, operatorText.replace(operator, '?')),
fixer.insertTextAfterRange(range, ' : null')
];
};
const create = context => ({
LogicalExpression: node => {
if (node.right.type === 'JSXElement') {
context.report({
node,
message: 'JSX should not use logical expression',
fix: createFixer(node, context.getSourceCode().getText())
});
}
}
});
module.exports = {
create,
createFixer,
meta: {
docs: {
description: 'Prevent falsy values to be printed'
},
fixable: 'code'
}
};
| Reformat code post prettier update :memo: | Reformat code post prettier update :memo:
| JavaScript | mit | CoorpAcademy/eslint-plugin-coorpacademy | ---
+++
@@ -1,21 +1,23 @@
-const createFixer = ({range, left, right, operator}, source) => fixer => {
- const [leftStart, leftEnd] = left.range;
- const [rightStart] = right.range;
- const operatorRange = [leftEnd, rightStart];
- const operatorText = source.slice(...operatorRange);
+const createFixer =
+ ({range, left, right, operator}, source) =>
+ fixer => {
+ const [leftStart, leftEnd] = left.range;
+ const [rightStart] = right.range;
+ const operatorRange = [leftEnd, rightStart];
+ const operatorText = source.slice(...operatorRange);
- if (operator === '||') {
- const leftText = source.slice(leftStart, leftEnd);
+ if (operator === '||') {
+ const leftText = source.slice(leftStart, leftEnd);
+ return [
+ fixer.replaceTextRange(operatorRange, operatorText.replace(operator, `? ${leftText} :`))
+ ];
+ }
+
return [
- fixer.replaceTextRange(operatorRange, operatorText.replace(operator, `? ${leftText} :`))
+ fixer.replaceTextRange(operatorRange, operatorText.replace(operator, '?')),
+ fixer.insertTextAfterRange(range, ' : null')
];
- }
-
- return [
- fixer.replaceTextRange(operatorRange, operatorText.replace(operator, '?')),
- fixer.insertTextAfterRange(range, ' : null')
- ];
-};
+ };
const create = context => ({
LogicalExpression: node => { |
8c8fcee948c6cf19efc6a361df68067b633ce3e6 | www/javascript/swat-form.js | www/javascript/swat-form.js | function SwatForm(id)
{
this.id = id;
this.form_element = document.getElementById(id);
}
SwatForm.prototype.setDefaultFocus = function(element_id)
{
// TODO: check if another element in this form is already focused
var element = document.getElementById(element_id);
if (element && typeof element.focus == 'function')
element.focus();
}
| function SwatForm(id)
{
this.id = id;
this.form_element = document.getElementById(id);
}
SwatForm.prototype.setDefaultFocus = function(element_id)
{
// TODO: check if another element in this form is already focused
var element = document.getElementById(element_id);
if (element && (typeof element.focus == 'function' ||
typeof element.focus == 'object'))
element.focus();
}
| Make this work in internet explorer. | Make this work in internet explorer.
svn commit r1709
| JavaScript | lgpl-2.1 | silverorange/swat,silverorange/swat | ---
+++
@@ -9,7 +9,8 @@
// TODO: check if another element in this form is already focused
var element = document.getElementById(element_id);
-
- if (element && typeof element.focus == 'function')
- element.focus();
+
+ if (element && (typeof element.focus == 'function' ||
+ typeof element.focus == 'object'))
+ element.focus();
} |
6a2603f2ada763d2d6b6b410b6906fa3bf870d40 | tests/dummy/app/components/contrib-manager/component.js | tests/dummy/app/components/contrib-manager/component.js | import Ember from 'ember';
import layout from './template';
import permissions from 'ember-osf/const/permissions';
export default Ember.Component.extend({
READ: permissions.READ,
WRITE: permissions.WRITE,
ADMIN: permissions.ADMIN,
layout: layout,
permissionChanges: {},
bibliographicChanges: {},
actions: {
addContributor(userId, permission, isBibliographic) {
this.sendAction('addContributor', userId, permission, isBibliographic);
},
removeContributor(contrib) {
this.sendAction('removeContributor', contrib);
},
permissionChange(contributor, permission) {
this.set(`permissionChanges.${contributor.id}`, permission.toLowerCase());
},
bibliographicChange(contributor, isBibliographic) {
this.set(`bibliographicChanges.${contributor.id}`, isBibliographic);
},
updateContributors() {
this.attrs.editContributors(
this.get('contributors'),
this.get('permissionChanges'),
this.get('bibliographicChanges')
);
}
}
});
| import Ember from 'ember';
import layout from './template';
import permissions from 'ember-osf/const/permissions';
export default Ember.Component.extend({
READ: permissions.READ,
WRITE: permissions.WRITE,
ADMIN: permissions.ADMIN,
layout: layout,
permissionChanges: {},
bibliographicChanges: {},
actions: {
addContributor(userId, permission, isBibliographic) {
this.sendAction('addContributor', userId, permission, isBibliographic);
},
removeContributor(contrib) {
this.sendAction('removeContributor', contrib);
},
permissionChange(contributor, permission) {
this.set(`permissionChanges.${contributor.id}`, permission.toLowerCase());
},
bibliographicChange(contributor, isBibliographic) {
this.set(`bibliographicChanges.${contributor.id}`, isBibliographic);
},
updateContributors() {
this.sendAction(
'editContributors',
this.get('contributors'),
this.get('permissionChanges'),
this.get('bibliographicChanges')
);
}
}
});
| Use sendAction when no return value is needed | Use sendAction when no return value is needed
[skip ci]
| JavaScript | apache-2.0 | baylee-d/ember-osf,hmoco/ember-osf,jamescdavis/ember-osf,crcresearch/ember-osf,pattisdr/ember-osf,chrisseto/ember-osf,cwilli34/ember-osf,CenterForOpenScience/ember-osf,hmoco/ember-osf,CenterForOpenScience/ember-osf,pattisdr/ember-osf,crcresearch/ember-osf,binoculars/ember-osf,cwilli34/ember-osf,chrisseto/ember-osf,baylee-d/ember-osf,jamescdavis/ember-osf,binoculars/ember-osf | ---
+++
@@ -24,9 +24,10 @@
this.set(`bibliographicChanges.${contributor.id}`, isBibliographic);
},
updateContributors() {
- this.attrs.editContributors(
- this.get('contributors'),
- this.get('permissionChanges'),
+ this.sendAction(
+ 'editContributors',
+ this.get('contributors'),
+ this.get('permissionChanges'),
this.get('bibliographicChanges')
);
} |
ad5e062d5b87b6a712bc1cce50850760caa63b11 | test/129809_ais_class_b_static_data.js | test/129809_ais_class_b_static_data.js | var chai = require("chai");
chai.Should();
chai.use(require('chai-things'));
chai.use(require('signalk-schema').chaiModule);
var mapper = require("../n2kMapper.js");
describe('129039 Class B Update', function () {
it('complete sentence converts', function () {
var msg = JSON.parse('{"timestamp":"2014-08-15-15:00:04.655","prio":"6","src":"43","dst":"255","pgn":"129809","description":"AIS Class B static data (msg 24 Part A)","fields":{"Message ID":"24","Repeat indicator":"Initial","User ID":"230044160","Name":"LAGUNA"}}');
var delta = mapper.toDelta(msg);
delta.updates.length.should.equal(1);
delta.updates[0].context.should.equal('vessels.230044160');
});
});
| var chai = require("chai");
chai.Should();
chai.use(require('chai-things'));
chai.use(require('signalk-schema').chaiModule);
var mapper = require("../n2kMapper.js");
describe('129809 Class B static data', function () {
it('complete sentence converts', function () {
var msg = JSON.parse('{"timestamp":"2014-08-15-15:00:04.655","prio":"6","src":"43","dst":"255","pgn":"129809","description":"AIS Class B static data (msg 24 Part A)","fields":{"Message ID":"24","Repeat indicator":"Initial","User ID":"230044160","Name":"LAGUNA"}}');
var delta = mapper.toDelta(msg);
delta.updates.length.should.equal(1);
delta.updates[0].context.should.equal('vessels.230044160');
});
});
| Fix error in test title | Fix error in test title
| JavaScript | apache-2.0 | SignalK/n2k-signalk | ---
+++
@@ -6,7 +6,7 @@
var mapper = require("../n2kMapper.js");
-describe('129039 Class B Update', function () {
+describe('129809 Class B static data', function () {
it('complete sentence converts', function () {
var msg = JSON.parse('{"timestamp":"2014-08-15-15:00:04.655","prio":"6","src":"43","dst":"255","pgn":"129809","description":"AIS Class B static data (msg 24 Part A)","fields":{"Message ID":"24","Repeat indicator":"Initial","User ID":"230044160","Name":"LAGUNA"}}');
var delta = mapper.toDelta(msg); |
43f4e0538525cbb9cb1114b150690558a4355f5b | test/data/seeds/lights.js | test/data/seeds/lights.js | 'use strict';
exports.seed = function (knex, Promise) {
return Promise.join(
// Deletes ALL existing entries
knex('lights').del(),
// Inserts seed entries
knex('lights').insert({
id: 1,
name: 'Lounge',
enabled: 1,
device: 1,
instance: 0,
controllerHost: 'localhost',
controllerPort: 8080
}),
knex('lights').insert({
id: 2,
name: 'Front Flood Light',
enabled: 1,
device: 2,
instance: 0,
controllerHost: 'localhost',
controllerPort: 8080
}),
knex('lights').insert({
id: 3,
name: 'Side Passage',
enabled: 1,
device: 3,
instance: 0,
controllerHost: 'otherhost',
controllerPort: 9090
}),
knex('lights').insert({
id: 4,
name: 'Side Entrance',
enabled: 1,
device: 4,
instance: 0,
controllerHost: 'otherhost',
controllerPort: 9090
})
);
};
| 'use strict';
exports.seed = function (knex, Promise) {
return Promise.join(
// Deletes ALL existing entries
knex('lights').del(),
// Inserts seed entries
knex('lights').insert({
id: 1,
name: 'Lounge',
enabled: 1,
device: 1,
instance: 0,
controllerHost: 'localhost',
controllerPort: 8080
}),
knex('lights').insert({
id: 2,
name: 'Front Flood Light',
enabled: 1,
device: 2,
instance: 0,
controllerHost: 'localhost',
controllerPort: 8080
}),
knex('lights').insert({
id: 3,
name: 'Side Passage',
enabled: 1,
device: 3,
instance: 0,
controllerHost: 'otherhost',
controllerPort: 9090
}),
knex('lights').insert({
id: 4,
name: 'Side Entrance',
enabled: 1,
device: 4,
instance: 0,
controllerHost: 'otherhost',
controllerPort: 9090
}),
knex('lights').insert({
id: 5,
name: 'Broken Light',
enabled: 0,
device: 5,
instance: 0,
controllerHost: 'otherhost',
controllerPort: 9090
})
);
};
| Add light service and unit tests | Add light service and unit tests
| JavaScript | apache-2.0 | nobbyknox/hal | ---
+++
@@ -41,6 +41,15 @@
instance: 0,
controllerHost: 'otherhost',
controllerPort: 9090
+ }),
+ knex('lights').insert({
+ id: 5,
+ name: 'Broken Light',
+ enabled: 0,
+ device: 5,
+ instance: 0,
+ controllerHost: 'otherhost',
+ controllerPort: 9090
})
);
}; |
f50abae460558f5a1dd99b4026f68b22fe6e57d0 | public/src/js/controllers/address.js | public/src/js/controllers/address.js | 'use strict';
angular.module('insight.address').controller('AddressController',
function($scope, $rootScope, $routeParams, $location, Global, Address, getSocket) {
$scope.global = Global;
var socket = getSocket($scope);
var _startSocket = function () {
socket.on('bitcoind/addresstxid', function(tx) {
$rootScope.$broadcast('tx', tx);
var beep = new Audio('/sound/transaction.mp3');
beep.play();
});
socket.emit('subscribe', 'bitcoind/addresstxid', [$routeParams.addrStr]);
};
socket.on('connect', function() {
_startSocket();
});
$scope.params = $routeParams;
$scope.findOne = function() {
$rootScope.currentAddr = $routeParams.addrStr;
_startSocket();
Address.get({
addrStr: $routeParams.addrStr
},
function(address) {
$rootScope.titleDetail = address.addrStr.substring(0, 7) + '...';
$rootScope.flashMessage = null;
$scope.address = address;
},
function(e) {
if (e.status === 400) {
$rootScope.flashMessage = 'Invalid Address: ' + $routeParams.addrStr;
} else if (e.status === 503) {
$rootScope.flashMessage = 'Backend Error. ' + e.data;
} else {
$rootScope.flashMessage = 'Address Not Found';
}
$location.path('/');
});
};
});
| 'use strict';
angular.module('insight.address').controller('AddressController',
function($scope, $rootScope, $routeParams, $location, Global, Address, getSocket) {
$scope.global = Global;
var socket = getSocket($scope);
var _startSocket = function () {
socket.on('bitcoind/addresstxid', function(tx) {
$rootScope.$broadcast('tx', tx);
var base = document.querySelector('base');
var baseUrl = base && base.href || '';
var beep = new Audio(baseUrl + '/sound/transaction.mp3');
beep.play();
});
socket.emit('subscribe', 'bitcoind/addresstxid', [$routeParams.addrStr]);
};
socket.on('connect', function() {
_startSocket();
});
$scope.params = $routeParams;
$scope.findOne = function() {
$rootScope.currentAddr = $routeParams.addrStr;
_startSocket();
Address.get({
addrStr: $routeParams.addrStr
},
function(address) {
$rootScope.titleDetail = address.addrStr.substring(0, 7) + '...';
$rootScope.flashMessage = null;
$scope.address = address;
},
function(e) {
if (e.status === 400) {
$rootScope.flashMessage = 'Invalid Address: ' + $routeParams.addrStr;
} else if (e.status === 503) {
$rootScope.flashMessage = 'Backend Error. ' + e.data;
} else {
$rootScope.flashMessage = 'Address Not Found';
}
$location.path('/');
});
};
});
| Fix url to transaciton sound | Fix url to transaciton sound
| JavaScript | mit | bitpay/bitcore,bitpay/bitcore,bitjson/bitcore,bitjson/bitcore,martindale/bitcore,martindale/bitcore,martindale/bitcore,martindale/bitcore,bitjson/bitcore,bitjson/bitcore,bitpay/bitcore,bitpay/bitcore | ---
+++
@@ -10,7 +10,9 @@
var _startSocket = function () {
socket.on('bitcoind/addresstxid', function(tx) {
$rootScope.$broadcast('tx', tx);
- var beep = new Audio('/sound/transaction.mp3');
+ var base = document.querySelector('base');
+ var baseUrl = base && base.href || '';
+ var beep = new Audio(baseUrl + '/sound/transaction.mp3');
beep.play();
});
socket.emit('subscribe', 'bitcoind/addresstxid', [$routeParams.addrStr]); |
ee9addcc11ca70fa6e6487abde14737c506b9dc7 | website/app/application/core/projects/project/files/display-file-contents-directive.js | website/app/application/core/projects/project/files/display-file-contents-directive.js | (function(module) {
module.directive("displayFileContents", displayFileContentsDirective);
function displayFileContentsDirective() {
return {
restrict: "E",
controller: 'DisplayFileContentsDirectiveController',
controllerAs: 'view',
bindToController: true,
scope: {
file: '=file'
},
templateUrl: 'application/core/projects/project/files/display-file-contents.html'
};
}
module.controller("DisplayFileContentsDirectiveController", DisplayFileContentsDirectiveController);
DisplayFileContentsDirectiveController.$inject = ["mcfile"];
/* @ngInject */
function DisplayFileContentsDirectiveController(mcfile) {
var ctrl = this;
ctrl.fileType = determineFileType(ctrl.file.mediatype);
ctrl.fileSrc = mcfile.src(ctrl.file.id);
//////////////
function determineFileType(mediatype) {
if (isImage(mediatype.mime)) {
return "image";
} else {
switch(mediatype.mime) {
case "application/pdf":
return "pdf";
case "application/vnd.ms-excel":
return "excel";
default:
return mediatype.mime;
}
}
}
}
}(angular.module('materialscommons')));
| (function(module) {
module.directive("displayFileContents", displayFileContentsDirective);
function displayFileContentsDirective() {
return {
restrict: "E",
controller: 'DisplayFileContentsDirectiveController',
controllerAs: 'view',
bindToController: true,
scope: {
file: '=file'
},
templateUrl: 'application/core/projects/project/files/display-file-contents.html'
};
}
module.controller("DisplayFileContentsDirectiveController", DisplayFileContentsDirectiveController);
DisplayFileContentsDirectiveController.$inject = ["mcfile"];
/* @ngInject */
function DisplayFileContentsDirectiveController(mcfile) {
var ctrl = this;
ctrl.fileType = determineFileType(ctrl.file.mediatype);
ctrl.fileSrc = mcfile.src(ctrl.file.id);
//////////////
function determineFileType(mediatype) {
if (isImage(mediatype.mime)) {
return "image";
} else {
switch(mediatype.mime) {
case "application/pdf":
return "pdf";
case "application/vnd.ms-excel":
return "xls";
default:
return mediatype.mime;
}
}
}
}
}(angular.module('materialscommons')));
| Return xls as type for application/vnd.ms-excel. | Return xls as type for application/vnd.ms-excel.
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -32,7 +32,7 @@
case "application/pdf":
return "pdf";
case "application/vnd.ms-excel":
- return "excel";
+ return "xls";
default:
return mediatype.mime;
} |
3d115b77de5e15ec005929acb00728d133d82d85 | imports/ui/states/Mongo2Mobx.js | imports/ui/states/Mongo2Mobx.js | import {Meteor} from 'meteor/meteor';
import {autorun, toJS} from 'mobx';
import Movies from '../../api/documents/documents'
export default class Mongo2Mobx {
constructor(store) {
this.moviesSubscription = null;
this.moviesObserver = null;
let moviesDataSync = autorun(() => {
let refreshMovies = (store) => {
let latestMovies = Movies.find().fetch();
store.updateMovies(latestMovies);
};
if (this.moviesSubscription) {
this.moviesSubscription.stop();
}
if (this.moviesObserver) {
this.moviesObserver.stop();
}
store.setMoviesLoading (true);
this.moviesSubscription = Meteor.subscribe("documents.list", {
onReady: () => {
this.moviesObserver = Movies.find().observe({
added: () => {
refreshMovies(store);
},
changed: () => {
refreshMovies(store);
},
removed: () => {
refreshMovies(store);
}
});
store.setMoviesLoading(false);
}
});
})
}
}
| import {Meteor} from 'meteor/meteor';
import {autorun, toJS} from 'mobx';
import Movies from '../../api/documents/documents'
export default class Mongo2Mobx {
constructor(store) {
this.moviesSubscription = null;
this.moviesObserver = null;
let moviesDataSync = autorun(() => {
let refreshMovies = (store) => {
let latestMovies = Movies.find({},{sort:{released:-1}}).fetch();
store.updateMovies(latestMovies);
};
if (this.moviesSubscription) {
this.moviesSubscription.stop();
}
if (this.moviesObserver) {
this.moviesObserver.stop();
}
store.setMoviesLoading (true);
this.moviesSubscription = Meteor.subscribe("documents.list", {
onReady: () => {
this.moviesObserver = Movies.find().observe({
added: () => {
refreshMovies(store);
},
changed: () => {
refreshMovies(store);
},
removed: () => {
refreshMovies(store);
}
});
store.setMoviesLoading(false);
}
});
})
}
}
| Fix sort order for refreshed movies list | Fix sort order for refreshed movies list
| JavaScript | mit | zarazi/movies-listie,zarazi/movies-listie | ---
+++
@@ -10,7 +10,7 @@
let moviesDataSync = autorun(() => {
let refreshMovies = (store) => {
- let latestMovies = Movies.find().fetch();
+ let latestMovies = Movies.find({},{sort:{released:-1}}).fetch();
store.updateMovies(latestMovies);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.