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 |
|---|---|---|---|---|---|---|---|---|---|---|
2200396395d73750261c7900d6c88da19348ae1c | app/components/OrganizationShow/constants.js | app/components/OrganizationShow/constants.js | // @flow
export const PIPELINES_INITIAL_PAGE_SIZE = 2;
export const PIPELINES_PAGE_SIZE = 2;
| // @flow
export const PIPELINES_INITIAL_PAGE_SIZE = 30;
export const PIPELINES_PAGE_SIZE = 50;
| Use proper page sizes again | Use proper page sizes again
| JavaScript | mit | buildkite/frontend,buildkite/frontend | ---
+++
@@ -1,4 +1,4 @@
// @flow
-export const PIPELINES_INITIAL_PAGE_SIZE = 2;
-export const PIPELINES_PAGE_SIZE = 2;
+export const PIPELINES_INITIAL_PAGE_SIZE = 30;
+export const PIPELINES_PAGE_SIZE = 50; |
d22e6c75b22fa5e443dc8f9bf522c85f39a8404c | app/components/controllers/UserController.js | app/components/controllers/UserController.js | (function () {
'use strict';
angular
.module('scrum_retroboard')
.controller('UserController', ['$scope', '$http', 'sessionService', 'userService', UserController]);
function UserController($scope, $http, sessionService, userService) {
var userVm = this;
//scope models
userVm.username = "";
userVm.sessionId = sessionService.getSessionId();
userVm.newSession = sessionService
.sessionExists(userVm.sessionId)
.then(function(result) {
return result.data;
});
console.log(userVm.newSession);
//scope method assignments
userVm.createAndJoinSession = createAndJoinSession;
userVm.joinExistingSession = joinExistingSession;
//scope method definitions
function createAndJoinSession() {
sessionService.createSession();
userService.addUserToSession(userVm.username, userVm.sessionId);
}
function joinExistingSession() {
userService.addUserToSession(userVm.username, userVm.sessionId);
}
}
})();
| (function () {
'use strict';
angular
.module('scrum_retroboard')
.controller('UserController', ['$scope', '$http', 'sessionService', 'userService', UserController]);
function UserController($scope, $http, sessionService, userService) {
var userVm = this;
//scope models
userVm.username = "";
userVm.sessionId = sessionService.getSessionId();
userVm.newSession = sessionService
.sessionExists(userVm.sessionId)
.then(function(result) {
return result.data;
});
console.log(userVm.newSession.value);
//scope method assignments
userVm.createAndJoinSession = createAndJoinSession;
userVm.joinExistingSession = joinExistingSession;
//scope method definitions
function createAndJoinSession() {
sessionService.createSession();
userService.addUserToSession(userVm.username, userVm.sessionId);
}
function joinExistingSession() {
userService.addUserToSession(userVm.username, userVm.sessionId);
}
}
})();
| Test work of API communication | Test work of API communication
| JavaScript | mit | Endava-Interns/ScrumRetroBoardFrontEnd,Endava-Interns/ScrumRetroBoardFrontEnd | ---
+++
@@ -18,7 +18,7 @@
return result.data;
});
- console.log(userVm.newSession);
+ console.log(userVm.newSession.value);
//scope method assignments
userVm.createAndJoinSession = createAndJoinSession; |
3b252fb289c7a767a82b8be9712fd415fdd81687 | bingoo.js | bingoo.js | chrome.tabs.onUpdated.addListener(
function(tabId, changeInfo, tab) {
var url = tab.url;
if (url.indexOf('https://www.bing.com/maps/default.aspx') == 0 && changeInfo.status == 'loading') {
var rtpIndex = url.indexOf("rtp=");
if (rtpIndex >= 0) {
var rtp = url.substr(rtpIndex + 4);
rtp = rtp.substr(0, rtp.indexOf('&'));
var address = rtp.substr(rtp.lastIndexOf('_') + 1);
chrome.tabs.update(tabId, {url: 'https://www.google.com/maps/preview/place/' + address});
}
}
}
)
| chrome.tabs.onUpdated.addListener(
function(tabId, changeInfo, tab) {
var url = tab.url;
if (url.indexOf('://www.bing.com/maps/default.aspx') > 0 && changeInfo.status == 'loading') {
var rtpIndex = url.indexOf("rtp=");
if (rtpIndex >= 0) {
var rtp = url.substr(rtpIndex + 4);
rtp = rtp.substr(0, rtp.indexOf('&'));
var address = rtp.substr(rtp.lastIndexOf('_') + 1);
chrome.tabs.update(tabId, {url: 'https://www.google.com/maps/preview/place/' + address});
}
}
}
)
| Fix handler only checking https protocol | Fix handler only checking https protocol
| JavaScript | mit | iic-ninjas/bingoo,rot-13/bingoo | ---
+++
@@ -1,7 +1,7 @@
chrome.tabs.onUpdated.addListener(
function(tabId, changeInfo, tab) {
var url = tab.url;
- if (url.indexOf('https://www.bing.com/maps/default.aspx') == 0 && changeInfo.status == 'loading') {
+ if (url.indexOf('://www.bing.com/maps/default.aspx') > 0 && changeInfo.status == 'loading') {
var rtpIndex = url.indexOf("rtp=");
if (rtpIndex >= 0) {
var rtp = url.substr(rtpIndex + 4); |
aee94ef6667fdd0d267a2cd1e718756b1c2bb9de | exercises/class_extend/solution/solution.js | exercises/class_extend/solution/solution.js | 'use strict';
class Character {
constructor(x, y) {
this.x = x;
this.y = y;
this.health_ = 100;
}
damage() {
this.health_ -= 10;
}
getHealth() {
return this.health_;
}
toString() {
return "x: " + this.x + " y: " + this.y + " health: " + this.health_;
}
}
class Player extends Character {
constructor(x, y, name) {
super(x, y);
this.name = name;
}
move(dx, dy) {
this.x += dx;
this.y += dy;
}
toString() {
return "name: " + this.name + " " + super.toString();
}
}
var x = process.argv[2];
var y = process.argv[3];
var name = process.argv[4];
var character = new Character(+x, +y);
character.damage();
console.log(character.toString());
var player = new Player(+x, +y, name);
player.damage();
player.move(7, 8);
console.log(player.toString());
| 'use strict';
class Character {
constructor(x, y) {
this.x = x;
this.y = y;
this.health_ = 100;
}
damage() {
this.health_ -= 10;
}
getHealth() {
return this.health_;
}
toString() {
return `x: ${this.x} y: ${this.y} health: ${this.health_}`
}
}
class Player extends Character {
constructor(x, y, name) {
super(x, y);
this.name = name;
}
move(dx, dy) {
this.x += dx;
this.y += dy;
}
toString() {
return `name: ${this.name} ${super.toString()}`;
}
}
var x = process.argv[2];
var y = process.argv[3];
var name = process.argv[4];
var character = new Character(+x, +y);
character.damage();
console.log(character.toString());
var player = new Player(+x, +y, name);
player.damage();
player.move(7, 8);
console.log(player.toString());
| Use string interpolation in toString functions | Use string interpolation in toString functions | JavaScript | mit | yosuke-furukawa/tower-of-babel | ---
+++
@@ -13,7 +13,7 @@
return this.health_;
}
toString() {
- return "x: " + this.x + " y: " + this.y + " health: " + this.health_;
+ return `x: ${this.x} y: ${this.y} health: ${this.health_}`
}
}
@@ -27,7 +27,7 @@
this.y += dy;
}
toString() {
- return "name: " + this.name + " " + super.toString();
+ return `name: ${this.name} ${super.toString()}`;
}
}
|
75aaf57ec8e76f4be3347831693557e9185c4f01 | frontend/admin/ticket/AdminTicketRevokeController.js | frontend/admin/ticket/AdminTicketRevokeController.js | angular.module('billett.admin').controller('AdminTicketRevokeController', function ($http, $modalInstance, order, ticket) {
var ctrl = this;
ctrl.order = order;
ctrl.ticket = ticket;
ctrl.revoke = function () {
ctrl.sending = true;
$http.post('api/ticket/' + ticket.id + '/revoke', {
'paymentgroup_id': ctrl.active_paymentgroup.id
}).then(function () {
$modalInstance.close();
}, function () {
alert("Ukjent feil oppsto");
delete ctrl.sending;
});
};
ctrl.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
| angular.module('billett.admin').controller('AdminTicketRevokeController', function ($http, $modalInstance, order, ticket) {
var ctrl = this;
ctrl.order = order;
ctrl.ticket = ticket;
ctrl.revoke = function () {
ctrl.sending = true;
$http.post('api/ticket/' + ctrl.ticket.id + '/revoke', {
'paymentgroup_id': ctrl.paymentgroup.id
}).then(function () {
$modalInstance.close();
}, function () {
alert("Ukjent feil oppsto");
delete ctrl.sending;
});
};
ctrl.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
| Fix bug in ticket revoke controller. | Fix bug in ticket revoke controller.
| JavaScript | mit | blindernuka/billett,blindernuka/billett | ---
+++
@@ -5,8 +5,8 @@
ctrl.revoke = function () {
ctrl.sending = true;
- $http.post('api/ticket/' + ticket.id + '/revoke', {
- 'paymentgroup_id': ctrl.active_paymentgroup.id
+ $http.post('api/ticket/' + ctrl.ticket.id + '/revoke', {
+ 'paymentgroup_id': ctrl.paymentgroup.id
}).then(function () {
$modalInstance.close();
}, function () { |
40e46880557d770952e6081978dac7413dd2cc37 | server/public/javascripts/frontpage.js | server/public/javascripts/frontpage.js | //
// Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS
// IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
'use strict';
$(function() {
$('input[name="username"]').focus();
$('#login-form').submit(function() {
$('.login-error').empty();
$.post('/login',
$('#login-form').serialize(),
function(data) {
if (data.success === true) {
$.cookie('ProjectEvergreen', data.userId + '-' + data.secret + '-n', {
path: '/',
expires: new Date(data.expires)
});
window.location.pathname = '/app/';
} else {
$('.login-error').text(data.msg);
}
});
return false;
});
});
| //
// Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS
// IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
'use strict';
$(function() {
$('input[name="username"]').focus();
$('#login-form').submit(function() {
$('.login-error').empty();
$('input').keypress(function() {
$('.login-error').empty();
});
$.post('/login',
$('#login-form').serialize(),
function(data) {
if (data.success === true) {
$.cookie('ProjectEvergreen', data.userId + '-' + data.secret + '-n', {
path: '/',
expires: new Date(data.expires)
});
window.location.pathname = '/app/';
} else {
$('.login-error').text(data.msg);
$('input[name="username"]').val('').focus();
$('input[name="password"]').val('');
}
});
return false;
});
});
| Improve login page when wrong password is entered | Improve login page when wrong password is entered
| JavaScript | apache-2.0 | ilkkao/mas,ilkkao/mas,ilkkao/mas,ilkkao/mas | ---
+++
@@ -22,6 +22,10 @@
$('#login-form').submit(function() {
$('.login-error').empty();
+ $('input').keypress(function() {
+ $('.login-error').empty();
+ });
+
$.post('/login',
$('#login-form').serialize(),
function(data) {
@@ -34,6 +38,8 @@
window.location.pathname = '/app/';
} else {
$('.login-error').text(data.msg);
+ $('input[name="username"]').val('').focus();
+ $('input[name="password"]').val('');
}
});
|
1262480306ea633f4a9b4c56e4131113341a896c | src/app/shared/api/baseApi.service.js | src/app/shared/api/baseApi.service.js | export default class BaseApiService {
constructor($http, $log, appConfig, path) {
'ngInject';
this.$http = $http;
this.$log = $log;
this._ = _;
this.host = `${appConfig.host}:3000`;
this.url = `//${this.host}/api/${path}`;
this.$log.info('constructor()', this);
}
create(data) {
this.$log.info('api:create()', data, this);
return this.$http.post(`${this.url}`, data);
}
get(query = '') {
this.$log.info('api:get()', query, this);
return this.$http.get(`${this.url}/${query}`);
}
remove(id) {
this.$log.info('api:remove()', id, this);
return this.$http.delete(`${this.url}/${id}`);
}
update(id, data) {
this.$log.info('api:update()', id, data, this);
return this.$http.post(`${this.url}/${id}`, data);
}
}
| export default class BaseApiService {
constructor($http, $log, appConfig, path) {
'ngInject';
this.$http = $http;
this.$log = $log;
this._ = _;
this.host = `${appConfig.host}:3000`;
this.path = path;
this.url = `//${this.host}/api/${path}`;
this.$log.info('constructor()', this);
}
create(data) {
this.$log.info('api:create()', data, this);
return this.$http.post(`${this.url}`, data);
}
get(query = '') {
let httpObj = {
method: 'GET',
url: `${this.url}/${query}`,
cache: this.path === 'cards' ? true : false
}
this.$log.info('api:get()', query, this);
return this.$http(httpObj);
}
remove(id) {
this.$log.info('api:remove()', id, this);
return this.$http.delete(`${this.url}/${id}`);
}
update(id, data) {
this.$log.info('api:update()', id, data, this);
return this.$http.post(`${this.url}/${id}`, data);
}
}
| Enable cache for 'get' API call to /cards | Enable cache for 'get' API call to /cards
| JavaScript | unlicense | ejwaibel/squarrels,ejwaibel/squarrels | ---
+++
@@ -8,6 +8,7 @@
this._ = _;
this.host = `${appConfig.host}:3000`;
+ this.path = path;
this.url = `//${this.host}/api/${path}`;
this.$log.info('constructor()', this);
@@ -20,9 +21,15 @@
}
get(query = '') {
+ let httpObj = {
+ method: 'GET',
+ url: `${this.url}/${query}`,
+ cache: this.path === 'cards' ? true : false
+ }
+
this.$log.info('api:get()', query, this);
- return this.$http.get(`${this.url}/${query}`);
+ return this.$http(httpObj);
}
remove(id) { |
4052b15906f82214e20782676479141976bfe9e4 | src/foam/swift/refines/AbstractDAO.js | src/foam/swift/refines/AbstractDAO.js | /**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
refines: 'foam.dao.AbstractDAO',
methods: [
// Here to finish implementing the interface.
{ name: 'select_' },
{ name: 'put_' },
{ name: 'remove_' },
{ name: 'find_' },
{ name: 'removeAll_' },
],
})
foam.CLASS({
refines: 'foam.dao.DAOProperty',
properties: [
{
name: 'swiftType',
value: 'DAO',
},
],
});
| /**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
refines: 'foam.dao.AbstractDAO',
methods: [
// Here to finish implementing the interface.
{ name: 'select_' },
{ name: 'put_' },
{ name: 'remove_' },
{ name: 'find_' },
{ name: 'removeAll_' },
],
})
foam.CLASS({
refines: 'foam.dao.DAOProperty',
properties: [
{
name: 'swiftType',
expression: function(required) {
return '(DAO & FObject)' + (required ? '' : '?');
},
},
],
});
| Make swift DAOProperties be of type (DAO & FObject) | Make swift DAOProperties be of type (DAO & FObject)
| JavaScript | apache-2.0 | foam-framework/foam2,jacksonic/vjlofvhjfgm,foam-framework/foam2,jacksonic/vjlofvhjfgm,jacksonic/vjlofvhjfgm,foam-framework/foam2,foam-framework/foam2,foam-framework/foam2 | ---
+++
@@ -21,7 +21,9 @@
properties: [
{
name: 'swiftType',
- value: 'DAO',
+ expression: function(required) {
+ return '(DAO & FObject)' + (required ? '' : '?');
+ },
},
],
}); |
5894eade4ebf9e7c110c5b445e651f5251a9fe62 | server/db.js | server/db.js | var pg = require("pg");
var Config = require("./config");
var Util = require("util");
var conString = Util.format("postgres://%s:%s@%s:%s/%s]", Config.postgres.username, Config.postgres.password, Config.postgres.host, Config.postgres.port, Config.postgres.database);
var db = { connectionString: conString };
module.exports = db;
| var pg = require("pg");
var Config = require("./config");
var Util = require("util");
var conString = Util.format("postgres://%s:%s@%s:%s/%s", Config.postgres.username, Config.postgres.password, Config.postgres.host, Config.postgres.port, Config.postgres.database);
var db = { connectionString: conString };
module.exports = db;
| Remove ] from connection string. | Remove ] from connection string.
| JavaScript | mit | borwahs/natalieandrob.com,borwahs/natalieandrob.com | ---
+++
@@ -2,7 +2,7 @@
var Config = require("./config");
var Util = require("util");
-var conString = Util.format("postgres://%s:%s@%s:%s/%s]", Config.postgres.username, Config.postgres.password, Config.postgres.host, Config.postgres.port, Config.postgres.database);
+var conString = Util.format("postgres://%s:%s@%s:%s/%s", Config.postgres.username, Config.postgres.password, Config.postgres.host, Config.postgres.port, Config.postgres.database);
var db = { connectionString: conString };
|
5ef9ad42974de745d63fd64b16e9c4709964a270 | app/client/lib/config.js | app/client/lib/config.js | // Configure Accounts UI for our specific user schema
import { Accounts } from 'meteor/accounts-base';
Accounts.ui.config({
requestPermissions: {},
extraSignupFields: [{
fieldName: 'username',
fieldLabel: 'Username',
inputType: 'text',
visible: true,
validate: function(value, errorFunction) {
if (!value) {
errorFunction("Please write your username");
return false;
} else {
return true;
}
}
}, {
fieldName: 'first-name',
fieldLabel: 'First name',
inputType: 'text',
visible: true,
validate: function(value, errorFunction) {
if (!value) {
errorFunction("Please write your first name");
return false;
} else {
return true;
}
}
}, {
fieldName: 'last-name',
fieldLabel: 'Last name',
inputType: 'text',
visible: true,
}, {
fieldName: 'terms',
fieldLabel: 'I accept the terms and conditions <span class="compulsory">*</span>',
inputType: 'checkbox',
visible: true,
saveToProfile: false,
validate: function(value, errorFunction) {
if (value) {
return true;
} else {
errorFunction('You must accept the terms and conditions.');
return false;
}
}
}]
});
| // Configure Accounts UI for our specific user schema
import { Accounts } from 'meteor/accounts-base';
Accounts.ui.config({
forceEmailLowercase: true,
forceUsernameLowercase: true,
requestPermissions: {},
extraSignupFields: [{
fieldName: 'username',
fieldLabel: 'Username',
inputType: 'text',
visible: true,
validate: function(value, errorFunction) {
if (!value) {
errorFunction("Please write your username");
return false;
} else {
return true;
}
}
}, {
fieldName: 'first-name',
fieldLabel: 'First name',
inputType: 'text',
visible: true,
validate: function(value, errorFunction) {
if (!value) {
errorFunction("Please write your first name");
return false;
} else {
return true;
}
}
}, {
fieldName: 'last-name',
fieldLabel: 'Last name',
inputType: 'text',
visible: true,
}, {
fieldName: 'terms',
fieldLabel: 'I accept the terms and conditions <span class="compulsory">*</span>',
inputType: 'checkbox',
visible: true,
saveToProfile: false,
validate: function(value, errorFunction) {
if (value) {
return true;
} else {
errorFunction('You must accept the terms and conditions.');
return false;
}
}
}]
});
| Fix settings for username and email | Fix settings for username and email
| JavaScript | agpl-3.0 | openp2pdesign/OpenMetaDesign,openp2pdesign/OpenMetaDesign,openp2pdesign/OpenMetaDesign | ---
+++
@@ -2,6 +2,8 @@
import { Accounts } from 'meteor/accounts-base';
Accounts.ui.config({
+ forceEmailLowercase: true,
+ forceUsernameLowercase: true,
requestPermissions: {},
extraSignupFields: [{
fieldName: 'username', |
669a5e8b19a97fd63d3288ee0754c3fbca1c65ab | app/services/intercom.js | app/services/intercom.js | import { getWithDefault } from '@ember/object';
import IntercomService from 'ember-intercom-io/services/intercom';
import cfg from '../config/environment';
export default IntercomService.extend({
config: getWithDefault(cfg, 'intercom', {})
});
| import { get } from '@ember/object';
import IntercomService from 'ember-intercom-io/services/intercom';
import cfg from '../config/environment';
export default IntercomService.extend({
config: get(cfg, 'intercom') ?? {}
});
| Remove use of deprecated getWithDefault | Remove use of deprecated getWithDefault | JavaScript | mit | mike-north/ember-intercom-io,mike-north/ember-intercom-io | ---
+++
@@ -1,7 +1,7 @@
-import { getWithDefault } from '@ember/object';
+import { get } from '@ember/object';
import IntercomService from 'ember-intercom-io/services/intercom';
import cfg from '../config/environment';
export default IntercomService.extend({
- config: getWithDefault(cfg, 'intercom', {})
+ config: get(cfg, 'intercom') ?? {}
}); |
6a7cb14be69d2776f45f79afd7099398ecede329 | src/client/modules/lib/knockout-plus.js | src/client/modules/lib/knockout-plus.js | define([
'knockout',
'knockout-mapping',
'knockout-arraytransforms',
'knockout-validation'
], function(ko) {
return ko;
}) | define([
'knockout',
'knockout-mapping',
'knockout-arraytransforms',
'knockout-validation'
], function (ko) {
ko.extenders.dirty = function (target, startDirty) {
var cleanValue = ko.observable(ko.mapping.toJSON(target));
var dirtyOverride = ko.observable(ko.utils.unwrapObservable(startDirty));
target.isDirty = ko.computed(function () {
return dirtyOverride() || ko.mapping.toJSON(target) !== cleanValue();
});
target.markClean = function () {
cleanValue(ko.mapping.toJSON(target));
dirtyOverride(false);
};
target.markDirty = function () {
dirtyOverride(true);
};
return target;
};
return ko;
}); | Add dirty-flag extension for knockout | Add dirty-flag extension for knockout
| JavaScript | mit | eapearson/kbase-ui,eapearson/kbase-ui,kbase/kbase-ui,eapearson/kbase-ui,kbase/kbase-ui,kbase/kbase-ui,briehl/kbase-ui,briehl/kbase-ui,kbase/kbase-ui,kbase/kbase-ui,briehl/kbase-ui,eapearson/kbase-ui,eapearson/kbase-ui | ---
+++
@@ -3,6 +3,27 @@
'knockout-mapping',
'knockout-arraytransforms',
'knockout-validation'
-], function(ko) {
+], function (ko) {
+
+
+ ko.extenders.dirty = function (target, startDirty) {
+ var cleanValue = ko.observable(ko.mapping.toJSON(target));
+ var dirtyOverride = ko.observable(ko.utils.unwrapObservable(startDirty));
+
+ target.isDirty = ko.computed(function () {
+ return dirtyOverride() || ko.mapping.toJSON(target) !== cleanValue();
+ });
+
+ target.markClean = function () {
+ cleanValue(ko.mapping.toJSON(target));
+ dirtyOverride(false);
+ };
+ target.markDirty = function () {
+ dirtyOverride(true);
+ };
+
+ return target;
+ };
+
return ko;
-})
+}); |
cef546a8bb537e5ca976045f67d372ccddc36f0b | js/respuesta.js | js/respuesta.js | function createMenuItem(parentSelector,menuData){
var menuListItem=document.createElement('li');
$(menuListItem).addClass(menuData.class).appendTo(parentSelector);
var menuLink=document.createElement('a');
$(menuLink).attr({"href":menuData.link}).html(menuData.name);
$(menuLink).appendTo(menuListItem);
}
function generateJSONMenu(url,menuListSelector) {
$.getJSON(url,function(data) {
for(var dataI=0;dataI<data.length;dataI++) {
createMenuItem(menuListSelector,data[dataI]);
}});
}
function init() {
generateJSONMenu('js/menu.json',".main-list");
}
| function createMenuItem(parentSelector,menuData){
var menuListItem=document.createElement('li');
$(menuListItem).addClass(menuData.class).appendTo(parentSelector);
var menuLink=document.createElement('a');
$(menuLink).attr({"href":menuData.link}).html(menuData.name);
$(menuLink).appendTo(menuListItem);
}
function generateJSONMenu(url,menuListSelector) {
$.getJSON(url,function(data) {
for(var dataI=0;dataI<data.length;dataI++) {
createMenuItem(menuListSelector,data[dataI]);
}});
}
function initialAnimation() {
$("div>div").fadeTo(1,30);
$(".left , .right").animate({"margin-left":0},5000);
}
function init() {
generateJSONMenu('js/menu.json',".main-list");
initialAnimation();
}
| Add layers animation and fadeIn | Add layers animation and fadeIn
| JavaScript | mit | edysanchez/test_json | ---
+++
@@ -11,6 +11,11 @@
createMenuItem(menuListSelector,data[dataI]);
}});
}
+function initialAnimation() {
+ $("div>div").fadeTo(1,30);
+ $(".left , .right").animate({"margin-left":0},5000);
+}
function init() {
generateJSONMenu('js/menu.json',".main-list");
+ initialAnimation();
} |
15f20685ed79148e5f7273287923f2b97dceef50 | lib/at-login.js | lib/at-login.js | 'use babel';
import {component} from './polymer-es6';
import _ from 'lodash';
console.log("AT LOGIN");
@component('at-login')
export class AtomTwitchLogin {
static properties() {
return { };
}
ready() {
const query = {
'response_type': 'token',
'client_id': 'akeo37esgle8e0r3w7r4f6fpt7prj21',
'redirect_uri': 'https://paulcbetts.github.io/atom-twitch/oauth.html',
'scope': 'user_read channel_editor channel_commercial channel_subscriptions user_subscriptions chat_login'
};
let queryString = _.map(Object.keys(query), (x) => `${x}=${encodeURIComponent(query[x])}`).join('&');
this.$.login.src = `https://api.twitch.tv/kraken/oauth2/authorize?${queryString}`;
}
}
| 'use babel';
import {component} from './polymer-es6';
import _ from 'lodash';
import url from 'url';
console.log("AT LOGIN");
@component('at-login')
export class AtomTwitchLogin {
static properties() {
return {
accessToken: {
type: String,
notify: true,
readOnly: true,
reflectToAttribute: true
}
};
}
ready() {
const query = {
'response_type': 'token',
'client_id': 'akeo37esgle8e0r3w7r4f6fpt7prj21',
'redirect_uri': 'https://paulcbetts.github.io/atom-twitch/oauth.html',
'scope': 'user_read channel_editor channel_commercial channel_subscriptions user_subscriptions chat_login'
};
let queryString = _.map(Object.keys(query), (x) => `${x}=${encodeURIComponent(query[x])}`).join('&');
this.$.login.preload = require.resolve('./at-login-preload');
this.$.login.src = `https://api.twitch.tv/kraken/oauth2/authorize?${queryString}`;
this.$.login.addEventListener('ipc-message', (e) => {
let query = url.parse(e.args[0]).hash;
let dict = _.reduce(query.slice(1).split('&'), (acc,part) => {
let [k,v] = part.split('=');
acc[decodeURIComponent(k)] = decodeURIComponent(v);
return acc;
}, {});
this._setAccessToken(dict['access_token']);
this.$.login.style.display = 'none';
});
}
}
| Save off the access token in our property | Save off the access token in our property
| JavaScript | mit | paulcbetts/atom-twitch,paulcbetts/atom-twitch | ---
+++
@@ -2,13 +2,21 @@
import {component} from './polymer-es6';
import _ from 'lodash';
+import url from 'url';
console.log("AT LOGIN");
@component('at-login')
export class AtomTwitchLogin {
static properties() {
- return { };
+ return {
+ accessToken: {
+ type: String,
+ notify: true,
+ readOnly: true,
+ reflectToAttribute: true
+ }
+ };
}
ready() {
@@ -21,6 +29,20 @@
let queryString = _.map(Object.keys(query), (x) => `${x}=${encodeURIComponent(query[x])}`).join('&');
+ this.$.login.preload = require.resolve('./at-login-preload');
this.$.login.src = `https://api.twitch.tv/kraken/oauth2/authorize?${queryString}`;
+
+ this.$.login.addEventListener('ipc-message', (e) => {
+ let query = url.parse(e.args[0]).hash;
+
+ let dict = _.reduce(query.slice(1).split('&'), (acc,part) => {
+ let [k,v] = part.split('=');
+ acc[decodeURIComponent(k)] = decodeURIComponent(v);
+ return acc;
+ }, {});
+
+ this._setAccessToken(dict['access_token']);
+ this.$.login.style.display = 'none';
+ });
}
} |
42318849244779b3513ffd32dc69d54f179a5d55 | source/assets/js/utils/fef-keycodes.js | source/assets/js/utils/fef-keycodes.js | export const KEYCODES = {
'enter': 13,
'tab': 9,
'space': 32,
'escape': 27,
'up': 38,
'down': 40
};
| export const KEYCODES = {
'enter': 13,
'tab': 9,
'space': 32,
'escape': 27,
'up': 38,
'down': 40,
'left': 37,
'right': 39,
'home': 36,
'end': 35
};
| Add more keycodes used in cms | Add more keycodes used in cms
SRFCMSAL-2597
| JavaScript | mit | mmz-srf/srf-frontend-framework,mmz-srf/srf-frontend-framework,mmz-srf/srf-frontend-framework,mmz-srf/srf-frontend-framework | ---
+++
@@ -4,5 +4,9 @@
'space': 32,
'escape': 27,
'up': 38,
- 'down': 40
+ 'down': 40,
+ 'left': 37,
+ 'right': 39,
+ 'home': 36,
+ 'end': 35
}; |
405e806514889bbcece5cf44266885c7e50615c2 | phjs-main.js | phjs-main.js | /* eslint-env phantomjs */
var system = require('system');
var webpage = require('webpage');
var page = webpage.create();
var ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) ' +
'Chrome/56.0.2924.87 Safari/537.36';
var args = JSON.parse(system.args[1]);
var url = args.url;
var viewSize = args.viewSize;
function complete(msg) {
system.stdout.write(JSON.stringify(msg));
phantom.exit();
}
function uponWindowLoad() {
var render = page.renderBase64('PNG');
var msg = {
status: 'ok',
body: render,
};
complete(msg);
}
function uponPageOpen(status) {
if (status !== 'success') {
var msg = {
status: 'error',
body: status,
};
complete(msg);
return;
}
// Wait an extra second for anything else to load
window.setTimeout(uponWindowLoad, 1000);
}
page.settings.userAgent = ua;
page.viewportSize = viewSize;
page.open(url, uponPageOpen);
| /* eslint-env phantomjs */
var system = require('system');
var webpage = require('webpage');
var page = webpage.create();
var ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) ' +
'Chrome/56.0.2924.87 Safari/537.36';
var args = JSON.parse(system.args[1]);
var url = args.url;
var viewSize = args.viewSize;
function complete(msg) {
system.stdout.write(JSON.stringify(msg));
phantom.exit();
}
function renderComplete() {
var render = page.renderBase64('PNG');
var msg = {
status: 'ok',
body: render,
};
complete(msg);
}
function uponPageOpen(status) {
if (status !== 'success') {
var msg = {
status: 'error',
body: status,
};
complete(msg);
return;
}
renderComplete();
}
page.settings.userAgent = ua;
page.viewportSize = viewSize;
page.open(url, uponPageOpen);
| Remove 1000ms wait for page load | Remove 1000ms wait for page load
| JavaScript | mit | tkmcc/stylish | ---
+++
@@ -17,7 +17,7 @@
phantom.exit();
}
-function uponWindowLoad() {
+function renderComplete() {
var render = page.renderBase64('PNG');
var msg = {
status: 'ok',
@@ -38,8 +38,7 @@
return;
}
- // Wait an extra second for anything else to load
- window.setTimeout(uponWindowLoad, 1000);
+ renderComplete();
}
page.settings.userAgent = ua; |
6650d1b9ee9afa29c5316646292cc1227e975f23 | src/index.js | src/index.js | import React from 'react';
import ReactDom from 'react-dom';
import { Route, Router, browserHistory } from 'react-router';
import "./vendor/css/skeleton_css/normalize.css"
import "./vendor/css/skeleton_css/skeleton_css.css"
import Main from './components/Main/Main';
ReactDom.render(
<Router history={browserHistory}>
<Route path="/" component={Main} />
</Router>,
document.getElementById('app'));
| import React from 'react';
import ReactDom from 'react-dom';
import { Route, Router, browserHistory } from 'react-router';
import "./styles/style.css"
import "./vendor/css/skeleton_css/normalize.css"
import "./vendor/css/skeleton_css/skeleton_css.css"
import Main from './components/Main/Main';
ReactDom.render(
<Router history={browserHistory}>
<Route path="/" component={Main} />
</Router>,
document.getElementById('app'));
| Set up skeleton and style css | Set up skeleton and style css
| JavaScript | mit | Decidr/react-decidr,Decidr/react-decidr,Decidr/react-decidr | ---
+++
@@ -2,6 +2,7 @@
import ReactDom from 'react-dom';
import { Route, Router, browserHistory } from 'react-router';
+import "./styles/style.css"
import "./vendor/css/skeleton_css/normalize.css"
import "./vendor/css/skeleton_css/skeleton_css.css"
|
cdd3bbde2eb51db584f67530836a754284de3d7c | src/index.js | src/index.js | import React from 'react';
import ReactDOM from 'react-dom';
import Root from 'components/Root';
import configureStore from './stores';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import initialState from './stores/initial-state';
import {resetAnimation} from './action-creators';
const target = document.getElementById('root');
const store = configureStore(initialState);
store.dispatch(resetAnimation());
const node = <Root routerHistory={createBrowserHistory()} store={store}/>;
ReactDOM.render(node, target);
| import React from 'react';
import ReactDOM from 'react-dom';
import Root from 'components/Root';
import configureStore from './stores';
// import createBrowserHistory from 'history/lib/createBrowserHistory';
import initialState from './stores/initial-state';
import {resetAnimation} from './action-creators';
const target = document.getElementById('root');
const store = configureStore(initialState);
store.dispatch(resetAnimation());
// const node = <Root routerHistory={createBrowserHistory()} store={store}/>;
const node = <Root store={store}/>;
ReactDOM.render(node, target);
| Disable browser history for static site | Disable browser history for static site
| JavaScript | mit | rossta/pathfinder,rossta/pathfinder | ---
+++
@@ -2,7 +2,7 @@
import ReactDOM from 'react-dom';
import Root from 'components/Root';
import configureStore from './stores';
-import createBrowserHistory from 'history/lib/createBrowserHistory';
+// import createBrowserHistory from 'history/lib/createBrowserHistory';
import initialState from './stores/initial-state';
import {resetAnimation} from './action-creators';
@@ -12,5 +12,6 @@
store.dispatch(resetAnimation());
-const node = <Root routerHistory={createBrowserHistory()} store={store}/>;
+// const node = <Root routerHistory={createBrowserHistory()} store={store}/>;
+const node = <Root store={store}/>;
ReactDOM.render(node, target); |
f4143bc419b4cca0d26bbfde5908043fbe8732be | src/index.js | src/index.js | /**
* 24.05.2017
* TCP Chat using NodeJS
* https://github.com/PatrikValkovic/TCPChat
* Created by patri
*/
'use strict'
const net = require('net')
const log = require('./logger')
const config = require('../config.json')
const GroupManager = require('./groupManager')
const Parser = require('./Parser')
const Client = require('./Client')
if (require.main === module) {
GroupManager.createGroup(config.defaultGroups)
const parser = new Parser()
const server = net.createServer()
server.on('connection', (socket) => {
const client = new Client(socket)
log.info('Client connected')
socket.on('close', () => {
log.info('Socket ended')
client.disconnect()
})
socket.once('data', (name) => {
client.name = name.toString().trim()
socket.write('Welcome to chat, type /help for more help\n')
socket.on('data',(content) => {
parser.parse(client, content.toString())
})
})
socket.on('error', () => {
log.warning('Error with socket')
client.disconnect()
})
socket.write('Please enter your name: ')
})
server.listen(config.port, config.host, () => {
const address = server.address()
log.info(`Server running on ${address.address}:${address.port}`)
})
}
| /**
* 24.05.2017
* TCP Chat using NodeJS
* https://github.com/PatrikValkovic/TCPChat
* Created by patri
*/
'use strict'
const net = require('net')
const log = require('./logger')
const config = require('../config.json')
const GroupManager = require('./groupManager')
const Parser = require('./Parser')
const Client = require('./Client')
if (require.main === module) {
GroupManager.createGroup(config.defaultGroups)
const parser = new Parser()
const server = net.createServer()
server.on('connection', (socket) => {
const client = new Client(socket)
log.info('Client connected')
socket.on('close', () => {
log.info('Socket ended')
client.disconnect()
})
socket.once('data', (name) => {
let obtainedName = name.toString().trim()
client.name = obtainedName === '' ? 'anonymous' : obtainedName
socket.write('Welcome to chat, type /help for more help\n')
socket.on('data',(content) => {
parser.parse(client, content.toString())
})
})
socket.on('error', () => {
log.warning('Error with socket')
client.disconnect()
})
socket.write('Please enter your name: ')
})
server.listen(config.port, config.host, () => {
const address = server.address()
log.info(`Server running on ${address.address}:${address.port}`)
})
}
| Set user's name as anonymous if no name is specified | Set user's name as anonymous if no name is specified
| JavaScript | mit | PatrikValkovic/TCPChat | ---
+++
@@ -26,7 +26,8 @@
client.disconnect()
})
socket.once('data', (name) => {
- client.name = name.toString().trim()
+ let obtainedName = name.toString().trim()
+ client.name = obtainedName === '' ? 'anonymous' : obtainedName
socket.write('Welcome to chat, type /help for more help\n')
socket.on('data',(content) => {
parser.parse(client, content.toString()) |
2cb6e1e59632bbce7ead7b78b29c0c4bd5592bb6 | lib/webpack/vue-loader.config.js | lib/webpack/vue-loader.config.js | 'use strict'
import { defaults } from 'lodash'
import { extractStyles, styleLoader } from './helpers'
export default function ({ isClient }) {
let babelOptions = JSON.stringify(defaults(this.options.build.babel, {
presets: ['vue-app'],
babelrc: false,
cacheDirectory: !!this.dev
}))
// https://github.com/vuejs/vue-loader/blob/master/docs/en/configurations
let config = {
postcss: this.options.build.postcss,
loaders: {
'js': 'babel-loader?' + babelOptions,
'css': styleLoader.call(this, 'css'),
'less': styleLoader.call(this, 'less', 'less-loader'),
'sass': styleLoader.call(this, 'sass', 'sass-loader?indentedSyntax'),
'scss': styleLoader.call(this, 'sass', 'sass-loader?sourceMap'),
'stylus': styleLoader.call(this, 'stylus', 'stylus-loader'),
'styl': styleLoader.call(this, 'stylus', 'stylus-loader')
},
preserveWhitespace: false,
extractCSS: extractStyles.call(this)
}
// Return the config
return config
}
| 'use strict'
import { defaults } from 'lodash'
import { extractStyles, styleLoader } from './helpers'
export default function ({ isClient }) {
let babelOptions = JSON.stringify(defaults(this.options.build.babel, {
presets: ['vue-app'],
babelrc: false,
cacheDirectory: !!this.dev
}))
// https://github.com/vuejs/vue-loader/blob/master/docs/en/configurations
let config = {
postcss: this.options.build.postcss,
loaders: {
'js': 'babel-loader?' + babelOptions,
'css': styleLoader.call(this, 'css'),
'less': styleLoader.call(this, 'less', 'less-loader'),
'sass': styleLoader.call(this, 'sass', 'sass-loader?indentedSyntax&?sourceMap'),
'scss': styleLoader.call(this, 'sass', 'sass-loader?sourceMap'),
'stylus': styleLoader.call(this, 'stylus', 'stylus-loader'),
'styl': styleLoader.call(this, 'stylus', 'stylus-loader')
},
preserveWhitespace: false,
extractCSS: extractStyles.call(this)
}
// Return the config
return config
}
| Add source map for SASS | Add source map for SASS
| JavaScript | mit | jfroffice/nuxt.js,mgesmundo/nuxt.js,jfroffice/nuxt.js,mgesmundo/nuxt.js | ---
+++
@@ -17,7 +17,7 @@
'js': 'babel-loader?' + babelOptions,
'css': styleLoader.call(this, 'css'),
'less': styleLoader.call(this, 'less', 'less-loader'),
- 'sass': styleLoader.call(this, 'sass', 'sass-loader?indentedSyntax'),
+ 'sass': styleLoader.call(this, 'sass', 'sass-loader?indentedSyntax&?sourceMap'),
'scss': styleLoader.call(this, 'sass', 'sass-loader?sourceMap'),
'stylus': styleLoader.call(this, 'stylus', 'stylus-loader'),
'styl': styleLoader.call(this, 'stylus', 'stylus-loader') |
ca68678fc52b5a4b46ed1b8e207a827c6b5c07b8 | src/store.js | src/store.js | import {
applyMiddleware,
combineReducers,
compose,
createStore as createReduxStore
} from 'redux'
const makeRootReducer = (reducers, asyncReducers) => {
// Redux + combineReducers always expect at least one reducer, if reducers
// and asyncReducers are empty, we define an useless reducer function
// returning the state
if (!reducers && !asyncReducers) { return (state) => state }
return combineReducers({
...reducers,
...asyncReducers
})
}
export const injectReducer = (store, { key, reducer }) => {
store.asyncReducers[key] = reducer
store.replaceReducer(makeRootReducer(store.reducers, store.asyncReducers))
}
export const createStore = (initialState = {}, reducers = {}, middlewares = {}, enhancers = {}) => {
const store = createReduxStore(
makeRootReducer(reducers),
initialState,
compose(
applyMiddleware(...middlewares),
...enhancers
)
)
store.reducers = reducers
store.asyncReducers = {}
return store
}
| import {
applyMiddleware,
combineReducers,
compose,
createStore as createReduxStore
} from 'redux'
const makeRootReducer = (reducers, asyncReducers) => {
// Redux + combineReducers always expect at least one reducer, if reducers
// and asyncReducers are empty, we define an useless reducer function
// returning the state
if (!reducers && !asyncReducers) { return (state) => state }
return combineReducers({
...reducers,
...asyncReducers
})
}
export const injectReducer = (store, { key, reducer }) => {
store.asyncReducers[key] = reducer
store.replaceReducer(makeRootReducer(store.reducers, store.asyncReducers))
}
export const createStore = (initialState = {}, reducers = {}, middlewares = {}, enhancers = {}) => {
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const store = createReduxStore(
makeRootReducer(reducers),
initialState,
composeEnhancers(
applyMiddleware(...middlewares),
...enhancers
)
)
store.reducers = reducers
store.asyncReducers = {}
return store
}
| Support for Redux DevTools Extension | Support for Redux DevTools Extension
| JavaScript | mit | tseho/react-redux-app-container | ---
+++
@@ -23,10 +23,11 @@
}
export const createStore = (initialState = {}, reducers = {}, middlewares = {}, enhancers = {}) => {
+ const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const store = createReduxStore(
makeRootReducer(reducers),
initialState,
- compose(
+ composeEnhancers(
applyMiddleware(...middlewares),
...enhancers
) |
0e0f29f6d7f816cda8caf647abbe20f04d0b4607 | src/utils.js | src/utils.js | module.exports = {
// Tools for client side
addStyleSheet: function(url) {
if (document) {
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = url;
document.getElementsByTagName("head")[0].appendChild(link);
}
},
existsStyleSheet: function(resourceName) {
if (document) {
var styles = document.styleSheets;
for (var i = 0, len = styles.length; i < len; i++) {
if (styles[i].href.endsWith(resourceName + ".css") || styles[i].href.endsWith(resourceName + ".min.css"))
return true;
}
}
return false;
}
}
| module.exports = {
// Tools for client side
addStyleSheet: function(url) {
if (document) {
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = url;
document.getElementsByTagName("head")[0].appendChild(link);
}
},
existsStyleSheet: function(resourceName) {
if (document) {
var href, styles = document.styleSheets;
for (var i = 0, len = styles.length; i < len; i++) {
href = styles[i].href; // not all style tags have external reference : some are inline !
if (href && href.indexOf(resourceName) !== -1) {
return true;
}
}
}
return false;
}
}
| FIX bug on stylesheets without href | FIX bug on stylesheets without href
| JavaScript | mit | zipang/markdown-bundle,zipang/markdown-bundle | ---
+++
@@ -11,10 +11,12 @@
},
existsStyleSheet: function(resourceName) {
if (document) {
- var styles = document.styleSheets;
+ var href, styles = document.styleSheets;
for (var i = 0, len = styles.length; i < len; i++) {
- if (styles[i].href.endsWith(resourceName + ".css") || styles[i].href.endsWith(resourceName + ".min.css"))
+ href = styles[i].href; // not all style tags have external reference : some are inline !
+ if (href && href.indexOf(resourceName) !== -1) {
return true;
+ }
}
}
return false; |
59ea8bc9c970f873fea7ad16116d98dfa2779568 | src/utils.js | src/utils.js | var shell = require('shelljs');
var parseGitUrl = require('git-url-parse');
module.exports.exec = function exec(command) {
console.log(" executing: " + command);
const options = { silent: true };
const ref = shell.exec(command, options);
if (ref.code === 0) {
return ref.stdout.trim();
}
const message =
'Exec code(' + ref.code + ') on executing: ' + command + '\n' +
shell.stderr;
throw new Error(message);
};
module.exports.getGHPagesUrl = function getGHPagesUrl(ghUrl) {
var parsedUrl = parseGitUrl(ghUrl);
var ghPagesUrl = 'https://' + parsedUrl.owner + '.github.io/' + parsedUrl.name;
return ghPagesUrl;
};
| var shell = require('shelljs');
var parseGitUrl = require('git-url-parse');
module.exports.exec = function exec(command) {
console.log(" executing: " + command);
const options = { silent: true };
const ref = shell.exec(command, options);
if (ref.code === 0) {
return ref.stdout.trim();
}
const message =
'Exec code(' + ref.code + ') on executing: ' + command + '\n' +
shell.stderr;
throw new Error(message);
};
module.exports.getGHPagesUrl = function getGHPagesUrl(ghUrl) {
var parsedUrl = parseGitUrl(ghUrl);
var ghPagesUrl = 'https://' + parsedUrl.owner + '.github.io/' + parsedUrl.name + '/';
return ghPagesUrl;
};
| Add a trailing slash to the URL. | Add a trailing slash to the URL.
| JavaScript | mit | storybooks/storybook-deployer,storybooks/storybook-deployer | ---
+++
@@ -18,6 +18,6 @@
module.exports.getGHPagesUrl = function getGHPagesUrl(ghUrl) {
var parsedUrl = parseGitUrl(ghUrl);
- var ghPagesUrl = 'https://' + parsedUrl.owner + '.github.io/' + parsedUrl.name;
+ var ghPagesUrl = 'https://' + parsedUrl.owner + '.github.io/' + parsedUrl.name + '/';
return ghPagesUrl;
}; |
a4e460b40855d689c90b570ba66b6280f924b2a4 | src/utils.js | src/utils.js | import VNode from 'snabbdom/vnode';
export function createTextVNode(text) {
return VNode(undefined, undefined, undefined, unescape(text));
}
export function transformName(name) {
// Replace -a with A to help camel case style property names.
name = name.replace( /-(\w)/g, function _replace( $1, $2 ) {
return $2.toUpperCase();
});
// Handle properties that start with a -.
const firstChar = name.charAt(0).toLowerCase();
return `${firstChar}${name.substring(1)}`;
}
// Regex for matching HTML entities.
const entityRegex = new RegExp('&[a-z0-9]+;', 'gi')
// Element for setting innerHTML for transforming entities.
const el = document.createElement('div');
function unescape(text) {
return text.replace(entityRegex, (entity) => {
el.innerHTML = entity;
return el.textContent;
});
}
| import VNode from 'snabbdom/vnode';
export function createTextVNode(text, context) {
return VNode(undefined, undefined, undefined, unescape(text, context));
}
export function transformName(name) {
// Replace -a with A to help camel case style property names.
name = name.replace( /-(\w)/g, function _replace( $1, $2 ) {
return $2.toUpperCase();
});
// Handle properties that start with a -.
const firstChar = name.charAt(0).toLowerCase();
return `${firstChar}${name.substring(1)}`;
}
// Regex for matching HTML entities.
const entityRegex = new RegExp('&[a-z0-9]+;', 'gi')
// Element for setting innerHTML for transforming entities.
let el = null;
function unescape(text, context) {
// Create the element using the context if it doesn't exist.
if (!el) {
el = context.createElement('div');
}
return text.replace(entityRegex, (entity) => {
el.innerHTML = entity;
return el.textContent;
});
}
| Add a 'context' parameter to util functions, so we don't rely on a global 'document'. | Add a 'context' parameter to util functions, so we don't rely on a global 'document'.
| JavaScript | mit | appcues/snabbdom-virtualize | ---
+++
@@ -1,7 +1,7 @@
import VNode from 'snabbdom/vnode';
-export function createTextVNode(text) {
- return VNode(undefined, undefined, undefined, unescape(text));
+export function createTextVNode(text, context) {
+ return VNode(undefined, undefined, undefined, unescape(text, context));
}
export function transformName(name) {
@@ -17,9 +17,13 @@
// Regex for matching HTML entities.
const entityRegex = new RegExp('&[a-z0-9]+;', 'gi')
// Element for setting innerHTML for transforming entities.
-const el = document.createElement('div');
+let el = null;
-function unescape(text) {
+function unescape(text, context) {
+ // Create the element using the context if it doesn't exist.
+ if (!el) {
+ el = context.createElement('div');
+ }
return text.replace(entityRegex, (entity) => {
el.innerHTML = entity;
return el.textContent; |
f9cf1298e8d1e924167648be8279a01488a989d4 | javascripts/application.js | javascripts/application.js | $(function () {
VS.init({
remainder : null,
container : $('.visual_search'),
query : '',
unquotable: ['day', 'date'],
callbacks : {
facetMatches: function(callback) {
callback(['day', 'date'])
},
valueMatches: function(facet, searchTerm, callback) {
if (facet == 'day')
callback(['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], { preserveOrder: true })
else if (facet == 'date')
callback([searchTerm])
}
}
})
})
| $(function () {
var displayDatepicker = function (callback) {
var input = $('.search_facet.is_editing input.search_facet_input')
var removeDatepicker = function () {
input.datepicker("destroy")
}
// Put a selected date into the VS autocomplete and trigger click
var setVisualSearch = function (date) {
removeDatepicker()
callback([date])
$("ul.VS-interface:visible li.ui-menu-item a:first").click()
}
input.datepicker({
dateFormat: 'yy-mm-dd',
onSelect: setVisualSearch,
onClose: removeDatepicker
})
input.datepicker('show')
}
VS.init({
remainder : null,
container : $('.visual_search'),
query : '',
unquotable: ['day', 'date'],
callbacks : {
facetMatches: function(callback) {
callback(['day', 'date'])
},
valueMatches: function(facet, searchTerm, callback) {
if (facet == 'day')
callback(['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], { preserveOrder: true })
else if (facet == 'date')
setTimeout(function () { displayDatepicker(callback) }, 0)
}
}
})
})
| Integrate UI Datepicker into VisualSearch.js | Integrate UI Datepicker into VisualSearch.js
| JavaScript | mit | Djo/visualsearch-with-datepicker | ---
+++
@@ -1,4 +1,26 @@
$(function () {
+ var displayDatepicker = function (callback) {
+ var input = $('.search_facet.is_editing input.search_facet_input')
+
+ var removeDatepicker = function () {
+ input.datepicker("destroy")
+ }
+
+ // Put a selected date into the VS autocomplete and trigger click
+ var setVisualSearch = function (date) {
+ removeDatepicker()
+ callback([date])
+ $("ul.VS-interface:visible li.ui-menu-item a:first").click()
+ }
+
+ input.datepicker({
+ dateFormat: 'yy-mm-dd',
+ onSelect: setVisualSearch,
+ onClose: removeDatepicker
+ })
+ input.datepicker('show')
+ }
+
VS.init({
remainder : null,
container : $('.visual_search'),
@@ -12,7 +34,7 @@
if (facet == 'day')
callback(['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], { preserveOrder: true })
else if (facet == 'date')
- callback([searchTerm])
+ setTimeout(function () { displayDatepicker(callback) }, 0)
}
}
}) |
debc7bf35201daa1e0223c0ab37ee496c635406a | app/notes/notes.service.js | app/notes/notes.service.js | (function() {
angular.module('marvelousnote.notes')
.service('NotesService', NotesService);
NotesService.$inject = ['$http'];
function NotesService($http) {
var service = this;
service.getNotes = function() {
$http.get('https://meganote.herokuapp.com/notes')
.success(function(notes) {
console.log(notes);
});
};
}
})();
| (function() {
angular.module('marvelousnote.notes')
.service('NotesService', NotesService);
NotesService.$inject = ['$http'];
function NotesService($http) {
var service = this;
service.getNotes = function() {
$http.get('https://meganote.herokuapp.com/notes')
.then(function(res) {
console.log(res.data);
});
};
}
})();
| Use then instead of success on promise. | Use then instead of success on promise.
| JavaScript | mit | patriciachunk/MarvelousNote,patriciachunk/MarvelousNote | ---
+++
@@ -8,8 +8,8 @@
service.getNotes = function() {
$http.get('https://meganote.herokuapp.com/notes')
- .success(function(notes) {
- console.log(notes);
+ .then(function(res) {
+ console.log(res.data);
});
};
} |
ff7bd17fac5efd1b80d6b36bcbceba9f71b4f154 | src/index.js | src/index.js | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
(function() {
var include = function(path) {
document.write('<script src="' + path + '"></script>');
};
include("/chrome/tracing/overlay.js");
include("/chrome/tracing/timeline_model.js");
include("/chrome/tracing/sorted_array_utils.js");
include("/chrome/tracing/timeline.js");
include("/chrome/tracing/timeline_track.js");
include("/chrome/tracing/fast_rect_renderer.js");
include("/chrome/tracing/timeline_view.js");
var timelineView;
function onDOMContentLoaded() {
timelineView = $('timeline-view');
cr.ui.decorate(timelineView, tracing.TimelineView);
chrome.send('ready');
}
function loadTrace(trace) {
if (timelineView == undefined)
throw Error('timelineview is null');
// some old traces were just arrays without an outer object
if (!trace.traceEvents) {
if (trace instanceof Array)
timelineView.traceEvents = trace;
else
throw Error('trace does not have an events array');
} else {
timelineView.traceEvents = trace.traceEvents;
}
return true;
}
window.loadTrace = loadTrace;
document.addEventListener('DOMContentLoaded', onDOMContentLoaded);
})();
| // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var g_timelineView;
(function() {
var include = function(path) {
document.write('<script src="' + path + '"></script>');
};
include("/chrome/tracing/overlay.js");
include("/chrome/tracing/timeline_model.js");
include("/chrome/tracing/sorted_array_utils.js");
include("/chrome/tracing/timeline.js");
include("/chrome/tracing/timeline_track.js");
include("/chrome/tracing/fast_rect_renderer.js");
include("/chrome/tracing/timeline_view.js");
var timelineView;
function onDOMContentLoaded() {
timelineView = $('timeline-view');
g_timelineView = timelineView;
cr.ui.decorate(timelineView, tracing.TimelineView);
chrome.send('ready');
}
function loadTrace(trace) {
if (timelineView == undefined)
throw Error('timelineview is null');
// some old traces were just arrays without an outer object
if (!trace.traceEvents) {
if (trace instanceof Array)
timelineView.traceEvents = trace;
else
throw Error('trace does not have an events array');
} else {
timelineView.traceEvents = trace.traceEvents;
}
return true;
}
window.loadTrace = loadTrace;
document.addEventListener('DOMContentLoaded', onDOMContentLoaded);
})();
| Make timeline view a global for debugging. | Make timeline view a global for debugging.
| JavaScript | apache-2.0 | natduca/trace_event_viewer,natduca/trace_event_viewer,natduca/trace_event_viewer | ---
+++
@@ -1,6 +1,7 @@
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+var g_timelineView;
(function() {
var include = function(path) {
document.write('<script src="' + path + '"></script>');
@@ -17,6 +18,7 @@
function onDOMContentLoaded() {
timelineView = $('timeline-view');
+ g_timelineView = timelineView;
cr.ui.decorate(timelineView, tracing.TimelineView);
chrome.send('ready');
} |
4d09b36b71853100eda128b4ef50376c3376cd49 | src/index.js | src/index.js | require('dotenv').config()
import {version} from '../package.json'
import path from 'path'
import Koa from 'koa'
import Route from 'koa-route'
import Serve from 'koa-static'
import Octokat from 'octokat'
import Badge from './Badge'
const app = new Koa()
app.context.github = new Octokat({
token: process.env.GITHUB_TOKEN
})
Badge.$app = app.context
Badge.$env = process.env
app.use(Serve(path.join(__dirname, '../public'), {
maxage: 31536000000
}))
app.use(Route.get('/', function * () {
this.body = 'Hireable v' + version
}))
app.use(Route.get('/:user/:repo?', function * show (id, repo) {
yield Badge.show(id, repo).then(src => {
this.redirect(src)
})
}))
app.listen(process.env.APP_PORT)
console.log('Listening on :' + process.env.APP_PORT)
console.log('Visit http://localhost:' + process.env.APP_PORT)
| require('dotenv').config()
import {version} from '../package.json'
import path from 'path'
import Koa from 'koa'
import Route from 'koa-route'
import Serve from 'koa-static'
import Octokat from 'octokat'
import Badge from './Badge'
const app = new Koa()
app.context.github = new Octokat({
token: process.env.GITHUB_TOKEN
})
Badge.$app = app.context
Badge.$env = process.env
app.use(Serve(path.join(__dirname, '../public'), {
maxage: 31536000000
}))
app.use(Route.get('/', function * () {
this.body = 'Hireable v' + version
}))
app.use(Route.get('/p/:user', function * (user) {
this.redirect('https://github.com/' + user)
}))
app.use(Route.get('/:user/:repo?', function * show (id, repo) {
yield Badge.show(id, repo).then(src => {
this.redirect(src)
})
}))
app.listen(process.env.APP_PORT)
console.log('Listening on :' + process.env.APP_PORT)
console.log('Visit http://localhost:' + process.env.APP_PORT)
| Add a profile link which allow users to control the redirection | Add a profile link which allow users to control the redirection
| JavaScript | mit | hiendv/hireable | ---
+++
@@ -27,6 +27,10 @@
this.body = 'Hireable v' + version
}))
+app.use(Route.get('/p/:user', function * (user) {
+ this.redirect('https://github.com/' + user)
+}))
+
app.use(Route.get('/:user/:repo?', function * show (id, repo) {
yield Badge.show(id, repo).then(src => {
this.redirect(src) |
423bd167163010b89a00f871cce83d76f6e52f4e | inst/htmlwidgets/sigma.js | inst/htmlwidgets/sigma.js | HTMLWidgets.widget({
name: "sigma",
type: "output",
initialize: function(el, width, height) {
// create our sigma object and bind it to the element
var sig = new sigma(el.id);
// return it as part of our instance data
return {
sig: sig
};
},
renderValue: function(el, x, instance) {
// parse gexf data
var parser = new DOMParser();
var data = parser.parseFromString(x.data, "application/xml");
// apply settings
for (var name in x.settings)
instance.sig.settings(name, x.settings[name]);
// update the sigma instance
sigma.parsers.gexf(
data, // parsed gexf data
instance.sig, // sigma instance we created in initialize
function() {
// need to call refresh to reflect new settings and data
instance.sig.refresh();
}
);
},
resize: function(el, width, height, instance) {
// forward resize on to sigma renderers
for (var name in instance.sig.renderers)
instance.sig.renderers[name].resize(width, height);
}
}); | HTMLWidgets.widget({
name: "sigma",
type: "output",
initialize: function(el, width, height) {
// create our sigma object and bind it to the element
// force to use canvas - webgl not rendering opacity
// properly consistently
var sig = new sigma({
renderers: [{
container: document.getElementById(el.id),
type: 'canvas'
}]
});
// return it as part of our instance data
return {
sig: sig
};
},
renderValue: function(el, x, instance) {
// parse gexf data
var parser = new DOMParser();
var data = parser.parseFromString(x.data, "application/xml");
// apply settings
for (var name in x.settings)
instance.sig.settings(name, x.settings[name]);
// update the sigma instance
sigma.parsers.gexf(
data, // parsed gexf data
instance.sig, // sigma instance we created in initialize
function() {
// need to call refresh to reflect new settings and data
instance.sig.refresh();
}
);
},
resize: function(el, width, height, instance) {
// forward resize on to sigma renderers
for (var name in instance.sig.renderers)
instance.sig.renderers[name].resize(width, height);
}
}); | Fix for opacity issues on browsers | Fix for opacity issues on browsers
| JavaScript | mit | iankloo/sigma,iankloo/sigma | ---
+++
@@ -7,8 +7,15 @@
initialize: function(el, width, height) {
// create our sigma object and bind it to the element
- var sig = new sigma(el.id);
-
+ // force to use canvas - webgl not rendering opacity
+ // properly consistently
+ var sig = new sigma({
+ renderers: [{
+ container: document.getElementById(el.id),
+ type: 'canvas'
+ }]
+ });
+
// return it as part of our instance data
return {
sig: sig |
498a81fee3dc30432d25fa79bc455bdeeee08b10 | tests/unit/serializers/course-test.js | tests/unit/serializers/course-test.js | import { moduleForModel, test } from 'ember-qunit';
import {a as testgroup} from 'ilios/tests/helpers/test-groups';
moduleForModel('course', 'Unit | Serializer | course ' + testgroup, {
// Specify the other units that are required for this test.
needs: [
'serializer:course',
'model:publish-event',
'model:school',
'model:user',
'model:course',
'model:course-clerkship-type',
'model:session',
'model:offering',
'model:topic',
'model:objective',
'model:cohort',
'model:mesh-descriptor',
'model:course-learning-material'
]
});
test('it serializes records', function(assert) {
var record = this.subject();
var serializedRecord = record.serialize();
assert.ok(serializedRecord);
});
| import { moduleForModel, test } from 'ember-qunit';
import {a as testgroup} from 'ilios/tests/helpers/test-groups';
moduleForModel('course', 'Unit | Serializer | course ' + testgroup, {
// Specify the other units that are required for this test.
needs: [
'serializer:course',
'model:school',
'model:user',
'model:course',
'model:course-clerkship-type',
'model:session',
'model:offering',
'model:topic',
'model:objective',
'model:cohort',
'model:mesh-descriptor',
'model:course-learning-material'
]
});
test('it serializes records', function(assert) {
var record = this.subject();
var serializedRecord = record.serialize();
assert.ok(serializedRecord);
});
| Remove publish-event from course serializer | Remove publish-event from course serializer
| JavaScript | mit | gboushey/frontend,ilios/frontend,dartajax/frontend,djvoa12/frontend,jrjohnson/frontend,stopfstedt/frontend,ilios/frontend,thecoolestguy/frontend,thecoolestguy/frontend,stopfstedt/frontend,gboushey/frontend,gabycampagna/frontend,gabycampagna/frontend,dartajax/frontend,jrjohnson/frontend,djvoa12/frontend | ---
+++
@@ -5,7 +5,6 @@
// Specify the other units that are required for this test.
needs: [
'serializer:course',
- 'model:publish-event',
'model:school',
'model:user',
'model:course',
@@ -27,4 +26,3 @@
assert.ok(serializedRecord);
});
- |
77b1c897a9e23e06006a034a46b18dd3c605e1da | eloquent_js/chapter07/ch07_ex02.js | eloquent_js/chapter07/ch07_ex02.js | function getTurnCount(state, robot, memory) {
for (let turn = 0;; turn++) {
if (state.parcels.length == 0 || turn > 50) {
return turn;
}
let action = robot(state, memory);
state = state.move(action.direction);
memory = action.memory;
}
}
function compareRobots(robot1, memory1, robot2, memory2) {
let total1 = 0, total2 = 0, reps = 10000;
for (let i = 0; i < reps; ++i) {
let initState = VillageState.random();
total1 += getTurnCount(initState, robot1, memory1);
total2 += getTurnCount(initState, robot2, memory2);
}
console.log(`${robot1.name}: ${total1 / reps}\n` +
`${robot2.name}: ${total2 / reps}`);
}
function myRobot({place, parcels}, route) {
if (route.length == 0) {
// Select locations of parcels we current don't carry
let places = parcels.filter(p => p.place != place).map(p => p.place);
// Select addresses of parcels we currently carry
let addresses = parcels.filter(p => p.place == place).map(p => p.address);
let minLen = Infinity;
// Loop over destinations; checking parcels to pick up first guarantees
// that for multiple routes with same length, we'll prefer the one that
// picks up a parcel
for (let destination of places.concat(addresses)) {
parcelRoute = findRoute(roadGraph, place, destination);
if (parcelRoute.length < minLen) {
route = parcelRoute;
minLen = route.length;
}
}
}
return {direction: route[0], memory: route.slice(1)};
}
compareRobots(goalOrientedRobot, [], myRobot, []);
runRobotAnimation(VillageState.random(), myRobot, []);
| function myRobot({place, parcels}, route) {
if (route.length == 0) {
let routes = parcels.map(p => {
if (p.place != place) return {
pickup: true,
route: findRoute(roadGraph, place, p.place)
};
return {
pickup: false,
route: findRoute(roadGraph, place, p.adress)
};
});
route = routes.reduce((prev, cur) => {
if (prev.route.length > cur.route.length) return cur;
if (prev.route.length < cur.route.length) return prev;
return cur.pickup ? cur : prev;
}).route;
}
return {direction: route[0], memory: route.slice(1)};
}
| Add chapter 7, exercise 2 | Add chapter 7, exercise 2
| JavaScript | mit | bewuethr/ctci | ---
+++
@@ -1,48 +1,23 @@
-function getTurnCount(state, robot, memory) {
- for (let turn = 0;; turn++) {
- if (state.parcels.length == 0 || turn > 50) {
- return turn;
- }
- let action = robot(state, memory);
- state = state.move(action.direction);
- memory = action.memory;
- }
+function myRobot({place, parcels}, route) {
+ if (route.length == 0) {
+ let routes = parcels.map(p => {
+ if (p.place != place) return {
+ pickup: true,
+ route: findRoute(roadGraph, place, p.place)
+ };
+
+ return {
+ pickup: false,
+ route: findRoute(roadGraph, place, p.adress)
+ };
+ });
+
+ route = routes.reduce((prev, cur) => {
+ if (prev.route.length > cur.route.length) return cur;
+ if (prev.route.length < cur.route.length) return prev;
+ return cur.pickup ? cur : prev;
+ }).route;
+ }
+
+ return {direction: route[0], memory: route.slice(1)};
}
-
-function compareRobots(robot1, memory1, robot2, memory2) {
- let total1 = 0, total2 = 0, reps = 10000;
- for (let i = 0; i < reps; ++i) {
- let initState = VillageState.random();
- total1 += getTurnCount(initState, robot1, memory1);
- total2 += getTurnCount(initState, robot2, memory2);
- }
- console.log(`${robot1.name}: ${total1 / reps}\n` +
- `${robot2.name}: ${total2 / reps}`);
-}
-
-function myRobot({place, parcels}, route) {
- if (route.length == 0) {
- // Select locations of parcels we current don't carry
- let places = parcels.filter(p => p.place != place).map(p => p.place);
-
- // Select addresses of parcels we currently carry
- let addresses = parcels.filter(p => p.place == place).map(p => p.address);
-
- let minLen = Infinity;
- // Loop over destinations; checking parcels to pick up first guarantees
- // that for multiple routes with same length, we'll prefer the one that
- // picks up a parcel
- for (let destination of places.concat(addresses)) {
- parcelRoute = findRoute(roadGraph, place, destination);
- if (parcelRoute.length < minLen) {
- route = parcelRoute;
- minLen = route.length;
- }
- }
- }
- return {direction: route[0], memory: route.slice(1)};
-}
-
-compareRobots(goalOrientedRobot, [], myRobot, []);
-
-runRobotAnimation(VillageState.random(), myRobot, []); |
cb292522bfaff42b453bf8b1ed7b2dd5fd233e0e | jobs/calc-site-views.js | jobs/calc-site-views.js | 'use strict'
const AV = require('leancloud-storage')
const schedule = require('node-schedule')
const APP_ID = 'yzbpXQpXf1rWVRfAAM8Durgh-gzGzoHsz'
const APP_KEY = '020bjTvbiVinVQ21YtWAJ9t8'
const INTERVAL = 10 * 60 * 1000;
AV.init({
appId: APP_ID,
appKey: APP_KEY
})
const Site = AV.Object.extend('Site')
var j = schedule.scheduleJob('20 * * * *', calc); // every 20 minutes
function calc() {
let counter = {}
let query = new AV.Query('Page')
query.each((page) => {
let d = page.get('domain')
if (counter[d]) counter[d] += page.get('count')
else counter[d] = page.get('count')
}).then(() => {
console.log('Collect all pages.')
for (let domain in counter) {
if (counter.hasOwnProperty(domain)) {
let siteView = counter[domain]
let siteQ = new AV.Query('Site')
siteQ.equalTo('domain', domain)
siteQ.first().then(site => {
if (!site) {
site = new Site()
site.set('domain', domain)
}
site.set('count', siteView).save()
})
}
}
console.log('Done.');
})
}
| 'use strict'
const AV = require('leancloud-storage')
const schedule = require('node-schedule')
const APP_ID = 'yzbpXQpXf1rWVRfAAM8Durgh-gzGzoHsz'
const APP_KEY = '020bjTvbiVinVQ21YtWAJ9t8'
AV.init({
appId: APP_ID,
appKey: APP_KEY
})
const Site = AV.Object.extend('Site')
let j = schedule.scheduleJob('*/20 * * * *', calc); // every 20 minutes
function calc() {
let counter = {}
let query = new AV.Query('Page')
query.each((page) => {
let d = page.get('domain')
if (counter[d]) counter[d] += page.get('count')
else counter[d] = page.get('count')
}).then(() => {
console.log('Collect all pages.')
for (let domain in counter) {
if (counter.hasOwnProperty(domain)) {
let siteView = counter[domain]
let siteQ = new AV.Query('Site')
siteQ.equalTo('domain', domain)
siteQ.first().then(site => {
if (!site) {
site = new Site()
site.set('domain', domain)
}
site.set('count', siteView).save()
})
}
}
console.log('Done.');
})
}
| Fix a mistake about cron jobs | Fix a mistake about cron jobs
| JavaScript | mit | zry656565/Hit-Kounter-LC,zry656565/Hit-Kounter-LC | ---
+++
@@ -5,7 +5,6 @@
const APP_ID = 'yzbpXQpXf1rWVRfAAM8Durgh-gzGzoHsz'
const APP_KEY = '020bjTvbiVinVQ21YtWAJ9t8'
-const INTERVAL = 10 * 60 * 1000;
AV.init({
appId: APP_ID,
@@ -14,7 +13,7 @@
const Site = AV.Object.extend('Site')
-var j = schedule.scheduleJob('20 * * * *', calc); // every 20 minutes
+let j = schedule.scheduleJob('*/20 * * * *', calc); // every 20 minutes
function calc() {
let counter = {} |
ba70a80ee9870d2185734f55349f67ac691a2f20 | app/templates/extension.js | app/templates/extension.js | /*global
define,
require,
window,
console,
_
*/
/*jslint devel:true,
white: true
*/
define([
'jquery',
'underscore',
'./properties',
'./initialproperties',
'./lib/js/extensionUtils',
'text!./lib/css/style.css'
],
function ($, _, props, initProps, extensionUtils, cssContent) {
'use strict';
extensionUtils.addStyleToHeader(cssContent);
return {
definition: props,
initialProperties: initProps,
snapshot: { canTakeSnapshot: true },
resize : function( $element, layout ) {
//do nothing
},
// clearSelectedValues : function($element) {
//
// },
// Angular Template
//template: '',
// (Angular Template)
// Angular Controller
controller: ['$scope', function ($scope) {
}],
// (Angular Controller)
// Paint Method
paint: function ( $element, layout ) {
console.groupCollapsed('Basic Objects');
console.info('$element:');
console.log($element);
console.info('layout:');
console.log(layout);
console.groupEnd();
$element.empty();
var $helloWorld = $(document.createElement('div'));
$helloWorld.addClass('hello-world');
$helloWorld.html('Hello World from the extension "<%= extensionName%>"');
$element.append($helloWorld);
}
// (Paint Method)
};
});
| /*global
define,
require,
window,
console,
_
*/
/*jslint devel:true,
white: true
*/
define([
'jquery',
'underscore',
'./properties',
'./initialproperties',
'./lib/js/extensionUtils',
'text!./lib/css/style.css'
],
function ($, _, props, initProps, extensionUtils, cssContent) {
'use strict';
extensionUtils.addStyleToHeader(cssContent);
return {
definition: props,
initialProperties: initProps,
snapshot: { canTakeSnapshot: true },
resize : function( $element, layout ) {
//do nothing
},
// clearSelectedValues : function($element) {
//
// },
// Angular Support (uncomment to use)
//template: '',
// Angular Controller
//controller: ['$scope', function ($scope) {
//
//}],
// (Angular Controller)
paint: function ( $element, layout ) {
console.groupCollapsed('Basic Objects');
console.info('$element:');
console.log($element);
console.info('layout:');
console.log(layout);
console.groupEnd();
$element.empty();
var $helloWorld = $(document.createElement('div'));
$helloWorld.addClass('hello-world');
$helloWorld.html('Hello World from the extension "<%= extensionName%>"');
$element.append($helloWorld);
}
};
});
| Optimize formatting of main file | Optimize formatting of main file
| JavaScript | mit | cloud9UG/generator-qsExtension,cloud9UG/generator-qsExtension | ---
+++
@@ -25,30 +25,24 @@
definition: props,
initialProperties: initProps,
-
snapshot: { canTakeSnapshot: true },
-
resize : function( $element, layout ) {
//do nothing
},
-
// clearSelectedValues : function($element) {
//
// },
- // Angular Template
+ // Angular Support (uncomment to use)
//template: '',
- // (Angular Template)
-
// Angular Controller
- controller: ['$scope', function ($scope) {
-
- }],
+ //controller: ['$scope', function ($scope) {
+ //
+ //}],
// (Angular Controller)
- // Paint Method
paint: function ( $element, layout ) {
console.groupCollapsed('Basic Objects');
@@ -65,7 +59,6 @@
$element.append($helloWorld);
}
- // (Paint Method)
};
}); |
48b88d4dd154a28106347fa48a83bfd57bf998b3 | server/test/functional/config/configSpec.js | server/test/functional/config/configSpec.js | 'use strict';
var expect = require('chai').expect,
config = require('../../../config/config');
describe('config', function () {
describe('getConfig', function () {
var configDirectory = '../../../config/';
describe('existing configuration', function () {
var testCases = [
{ environment: 'development' },
{ environment: 'integration' },
{ environment: 'production' },
{ environment: 'test' }
];
testCases.forEach(function (testCase) {
it('should successfully load the specified configuration: ' + testCase.environment, function () {
expect(config.getConfig(testCase.environment, configDirectory, require)).to.be.defined;
});
});
});
describe('not existing configuration', function () {
it('should throw an error if the specified configuration does not exist', function () {
var environment = 'any not existing',
expectedErrorMessage = 'Config file for system environment not existing:', environment,
getConfig = config.getConfig;
expect(getConfig.bind(null, environment, configDirectory, require)).to.throw(expectedErrorMessage);
});
});
});
});
| 'use strict';
var expect = require('chai').expect,
config = require('../../../config/config');
describe('config', function () {
describe('getConfig', function () {
var configDirectory = '../../../config/';
describe('existing configuration', function () {
var testCases = [
{ environment: 'development' },
{ environment: 'integration' },
{ environment: 'production' },
{ environment: 'test' }
];
testCases.forEach(function (testCase) {
it('should successfully load the specified configuration: ' + testCase.environment, function () {
expect(config.getConfig(testCase.environment, configDirectory, require)).to.be.defined;
});
});
});
describe('not existing configuration', function () {
it('should throw an error if the specified configuration does not exist', function () {
var environment = 'any not existing',
expectedErrorMessage = 'Config file for system environment not existing:' + environment,
getConfig = config.getConfig;
expect(getConfig.bind(null, environment, configDirectory, require)).to.throw(expectedErrorMessage);
});
});
});
});
| Fix syntax error which causes redeclaration of a variable. | Fix syntax error which causes redeclaration of a variable.
| JavaScript | mit | lxanders/community | ---
+++
@@ -30,7 +30,7 @@
it('should throw an error if the specified configuration does not exist', function () {
var environment = 'any not existing',
- expectedErrorMessage = 'Config file for system environment not existing:', environment,
+ expectedErrorMessage = 'Config file for system environment not existing:' + environment,
getConfig = config.getConfig;
expect(getConfig.bind(null, environment, configDirectory, require)).to.throw(expectedErrorMessage); |
2f1eec32b35cdb0c379ece2837edb95fca13e009 | test/util.js | test/util.js | var EventEmitter = require("events").EventEmitter;
var util = require("util");
var _ = require("lodash");
var express = require("express");
var Network = require("../src/models/network");
function MockClient(opts) {
this.user = {nick: "test-user"};
for (var k in opts) {
this[k] = opts[k];
}
}
util.inherits(MockClient, EventEmitter);
MockClient.prototype.createMessage = function(opts) {
var message = _.extend({
message: "dummy message",
nick: "test-user",
target: "#test-channel"
}, opts);
this.emit("privmsg", message);
};
module.exports = {
createClient: function() {
return new MockClient();
},
createNetwork: function() {
return new Network({
host: "example.com",
channels: [{
name: "#test-channel",
messages: []
}]
});
},
createWebserver: function() {
return express();
}
};
| var EventEmitter = require("events").EventEmitter;
var util = require("util");
var _ = require("lodash");
var express = require("express");
var Network = require("../src/models/network");
var Chan = require("../src/models/chan");
function MockClient(opts) {
this.user = {nick: "test-user"};
for (var k in opts) {
this[k] = opts[k];
}
}
util.inherits(MockClient, EventEmitter);
MockClient.prototype.createMessage = function(opts) {
var message = _.extend({
message: "dummy message",
nick: "test-user",
target: "#test-channel"
}, opts);
this.emit("privmsg", message);
};
module.exports = {
createClient: function() {
return new MockClient();
},
createNetwork: function() {
return new Network({
host: "example.com",
channels: [new Chan({
name: "#test-channel"
})]
});
},
createWebserver: function() {
return express();
}
};
| Create real channel object in tests | Create real channel object in tests
| JavaScript | mit | FryDay/lounge,rockhouse/lounge,libertysoft3/lounge-autoconnect,MaxLeiter/lounge,libertysoft3/lounge-autoconnect,libertysoft3/lounge-autoconnect,metsjeesus/lounge,realies/lounge,rockhouse/lounge,MaxLeiter/lounge,MaxLeiter/lounge,williamboman/lounge,ScoutLink/lounge,ScoutLink/lounge,ScoutLink/lounge,sebastiencs/lounge,williamboman/lounge,realies/lounge,sebastiencs/lounge,williamboman/lounge,metsjeesus/lounge,FryDay/lounge,thelounge/lounge,metsjeesus/lounge,rockhouse/lounge,realies/lounge,FryDay/lounge,sebastiencs/lounge,thelounge/lounge | ---
+++
@@ -3,6 +3,7 @@
var _ = require("lodash");
var express = require("express");
var Network = require("../src/models/network");
+var Chan = require("../src/models/chan");
function MockClient(opts) {
this.user = {nick: "test-user"};
@@ -30,10 +31,9 @@
createNetwork: function() {
return new Network({
host: "example.com",
- channels: [{
- name: "#test-channel",
- messages: []
- }]
+ channels: [new Chan({
+ name: "#test-channel"
+ })]
});
},
createWebserver: function() { |
5cc35c18b5b3eeb5cc78ffb74f4fc893dc39646b | src/controllers/version.js | src/controllers/version.js | const slaveService = require('../services/slave');
const versionService = require('../services/version');
const version = {
currentVersion(req, res) {
const {slaveUID, slaveVersion} = req.params,
remoteAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress,
tag = versionService.getCurrent();
const respondWithTag = () => {
res.json(200, {tag});
};
slaveService.updateSlave(slaveUID, slaveVersion, remoteAddress)
.then(respondWithTag)
.catch(error => {
console.error(`An error occurred when updating ${slaveUID}: ${error}`);
// send back current version regardless
respondWithTag();
});
}
}
module.exports = version; | const slaveService = require('../services/slave');
const versionService = require('../services/version');
const version = {
currentVersion(req, res) {
const {slaveUID, slaveVersion} = req.params,
remoteAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress,
tag = versionService.getCurrent();
const respondWithTag = () => {
res.json(200, {tag});
};
slaveService.updateSlave(slaveUID, slaveVersion, remoteAddress)
.catch(error => {
console.error(`An error occurred when updating ${slaveUID}: ${error}`);
});
// send back current version regardless of success or failure of db entry
respondWithTag();
}
}
module.exports = version; | Send response while database is still updating | Send response while database is still updating
| JavaScript | mit | 4minitz/version-check | ---
+++
@@ -12,13 +12,12 @@
};
slaveService.updateSlave(slaveUID, slaveVersion, remoteAddress)
- .then(respondWithTag)
.catch(error => {
console.error(`An error occurred when updating ${slaveUID}: ${error}`);
+ });
- // send back current version regardless
- respondWithTag();
- });
+ // send back current version regardless of success or failure of db entry
+ respondWithTag();
}
}
|
30c6ae39b53d26eca08ff42e37b58f383d965240 | language_switcher_for_microsoft_docs.user.js | language_switcher_for_microsoft_docs.user.js | // ==UserScript==
// @name Language switcher for Microsoft Docs
// @namespace curipha
// @description Add language menu
// @include https://docs.microsoft.com/*
// @version 0.0.1
// @grant none
// @noframes
// ==/UserScript==
(function() {
'use strict';
const nav = document.getElementById('affixed-left-container');
if (nav) {
const [tolang, label] = location.pathname.substring(0,7) === '/en-us/' ? ['ja-jp', '日本語'] : ['en-us', 'English'];
const anchor = document.createElement('a');
anchor.href = location.pathname.replace(/(?<=^\/)[A-Za-z0-9-]+(?=\/)/, tolang);
anchor.className = 'button is-small is-text has-inner-focus has-margin-bottom-small has-border-top has-border-bottom';
const icon = document.createElement('span');
icon.className = 'icon is-size-8 has-text-subtle';
const iconinner = document.createElement('span');
iconinner.className = 'docon docon-locale-globe';
const text = document.createElement('span');
text.textContent = label;
icon.appendChild(iconinner);
anchor.appendChild(icon);
anchor.appendChild(text);
nav.appendChild(anchor);
const makehref = function() { this.href += location.hash; };
anchor.addEventListener('mousedown', makehref, false);
anchor.addEventListener('keydown', makehref, false);
}
})();
| // ==UserScript==
// @name Language switcher for Microsoft Docs
// @namespace curipha
// @description Add language menu
// @include https://docs.microsoft.com/*
// @version 0.0.1
// @grant none
// @noframes
// ==/UserScript==
(function() {
'use strict';
const nav = document.getElementById('affixed-left-container');
if (nav) {
const [tolang, label] = location.pathname.substring(0,7) === '/en-us/' ? ['ja-jp', '日本語'] : ['en-us', 'English'];
const anchor = document.createElement('a');
anchor.href = location.pathname.replace(/(?<=^\/)[A-Za-z0-9-]+(?=\/)/, tolang) + location.search;
anchor.className = 'button is-small is-text has-inner-focus has-margin-bottom-small has-border-top has-border-bottom';
const icon = document.createElement('span');
icon.className = 'icon is-size-8 has-text-subtle';
const iconinner = document.createElement('span');
iconinner.className = 'docon docon-locale-globe';
const text = document.createElement('span');
text.textContent = label;
icon.appendChild(iconinner);
anchor.appendChild(icon);
anchor.appendChild(text);
nav.appendChild(anchor);
const makehref = function() { this.href += location.hash; };
anchor.addEventListener('mousedown', makehref, false);
anchor.addEventListener('keydown', makehref, false);
}
})();
| Add query strings to the anchor | Add query strings to the anchor
| JavaScript | unlicense | curipha/userscripts,curipha/userscripts | ---
+++
@@ -16,7 +16,7 @@
const [tolang, label] = location.pathname.substring(0,7) === '/en-us/' ? ['ja-jp', '日本語'] : ['en-us', 'English'];
const anchor = document.createElement('a');
- anchor.href = location.pathname.replace(/(?<=^\/)[A-Za-z0-9-]+(?=\/)/, tolang);
+ anchor.href = location.pathname.replace(/(?<=^\/)[A-Za-z0-9-]+(?=\/)/, tolang) + location.search;
anchor.className = 'button is-small is-text has-inner-focus has-margin-bottom-small has-border-top has-border-bottom';
const icon = document.createElement('span'); |
e3503e8cbd9ea13f93b1b40f746ce512e988c60b | extensions/no_right_click/apply.js | extensions/no_right_click/apply.js |
window.oncontextmenu = function() {return false;};
| /**
* Disables context menus, including those initiated by a right click.
*/
function disableRightClick() {
window.addEventListener('oncontextmenu', function() {
return false;
}, true);
}
disableRightClick();
| Add JSDoc and use addEventListener | no_right_click: Add JSDoc and use addEventListener
| JavaScript | apache-2.0 | EndPointCorp/appctl,EndPointCorp/appctl | ---
+++
@@ -1,3 +1,10 @@
+/**
+ * Disables context menus, including those initiated by a right click.
+ */
+function disableRightClick() {
+ window.addEventListener('oncontextmenu', function() {
+ return false;
+ }, true);
+}
-window.oncontextmenu = function() {return false;};
-
+disableRightClick(); |
edba00314d922c1a308c77a5da308f1d522aecd3 | src/js/app/models/trade.js | src/js/app/models/trade.js | define([
'app/models/base',
'app/validations/trade'
], function (BaseModel, validation) {
return BaseModel.extend({
defaults: {
'executionOn': null,
'isBtcSell': false,
'isBtcBuy': false,
'currencyIsoCode': 'usd',
'btcPrice': 0.0,
'btcAmount': 0.0,
'xxxAmount': 0.0,
'btcFee': 0.0,
'xxxFee': 0.0,
'isIgnored': false,
'isDeleted': false,
'serviceName': '',
'serviceIdentifier': null,
'tags': []
},
validation: validation
});
});
| define([
'app/models/base',
'app/validations/trade',
'moment',
'underscore'
], function (BaseModel, validation, moment, _) {
return BaseModel.extend({
validation: validation,
defaults: {
'executionOn': null,
'isBtcSell': false,
'isBtcBuy': false,
'currencyIsoCode': 'usd',
'btcPrice': 0.0,
'btcAmount': 0.0,
'xxxAmount': 0.0,
'btcFee': 0.0,
'xxxFee': 0.0,
'isIgnored': false,
'isDeleted': false,
'serviceName': '',
'serviceIdentifier': null,
'tags': []
},
executionOn: function () {
var setValue, getValue;
if (arguments.length > 0) {
// setter
setValue = arguments[0];
if (_.isNull(setValue))
return this.set('executionOn', null);
if (!_.isNull(setValue) && !moment.isMoment(setValue))
throw new Error('No moment object provided!');
return this.set('executionOn', newValue);
} else {
// getter
getValue = this.get('executionOn');
return moment(getValue);
}
}
});
});
| Add high level getter/setter for executionOn attr | Add high level getter/setter for executionOn attr
| JavaScript | mit | davidknezic/bitcoin-trade-guard | ---
+++
@@ -1,8 +1,11 @@
define([
'app/models/base',
- 'app/validations/trade'
- ], function (BaseModel, validation) {
+ 'app/validations/trade',
+ 'moment',
+ 'underscore'
+ ], function (BaseModel, validation, moment, _) {
return BaseModel.extend({
+ validation: validation,
defaults: {
'executionOn': null,
'isBtcSell': false,
@@ -20,6 +23,26 @@
'tags': []
},
- validation: validation
+ executionOn: function () {
+ var setValue, getValue;
+
+ if (arguments.length > 0) {
+ // setter
+ setValue = arguments[0];
+
+ if (_.isNull(setValue))
+ return this.set('executionOn', null);
+
+ if (!_.isNull(setValue) && !moment.isMoment(setValue))
+ throw new Error('No moment object provided!');
+
+ return this.set('executionOn', newValue);
+ } else {
+ // getter
+ getValue = this.get('executionOn');
+
+ return moment(getValue);
+ }
+ }
});
}); |
0970c167a6df5f48664295cddb6f5f5effaaf8c2 | app/lib/fg/import-web-apis.js | app/lib/fg/import-web-apis.js | import { ipcRenderer } from 'electron'
import rpc from 'pauls-electron-rpc'
// it would be better to import this from package.json
const BEAKER_VERSION = '0.0.1'
// method which will populate window.beaker with the APIs deemed appropriate for the protocol
export default function () {
window.beaker = { version: BEAKER_VERSION }
var webAPIs = ipcRenderer.sendSync('get-web-api-manifests', window.location.protocol)
for (var k in webAPIs) {
window[k] = rpc.importAPI(k, webAPIs[k], { timeout: false })
}
} | import { ipcRenderer, webFrame } from 'electron'
import rpc from 'pauls-electron-rpc'
// it would be better to import this from package.json
const BEAKER_VERSION = '0.0.1'
// method which will populate window.beaker with the APIs deemed appropriate for the protocol
export default function () {
// mark the safe protocol as 'secure' to enable all DOM APIs
webFrame.registerURLSchemeAsSecure('safe');
window.beaker = { version: BEAKER_VERSION }
var webAPIs = ipcRenderer.sendSync('get-web-api-manifests', window.location.protocol)
for (var k in webAPIs) {
window[k] = rpc.importAPI(k, webAPIs[k], { timeout: false })
}
} | Mark safe as a secure protocol | feat/webview: Mark safe as a secure protocol
Chrom(e|ium) exposes many newer DOM APIs and HTML5 features (like User Media or Geolocation)
only over secure connections – primarily https – in order to prevent the user from
accidentially exposing themselves to third parties. For any webpage deliver over an unsecure
protocol those APIs will be flat out denied.
This patch registers our own `safe`-protocol as a secure one, in order to enable said
DOM APIs and HTML5 features.
| JavaScript | mit | joshuef/beaker,joshuef/beaker,joshuef/beaker | ---
+++
@@ -1,4 +1,4 @@
-import { ipcRenderer } from 'electron'
+import { ipcRenderer, webFrame } from 'electron'
import rpc from 'pauls-electron-rpc'
// it would be better to import this from package.json
@@ -6,6 +6,9 @@
// method which will populate window.beaker with the APIs deemed appropriate for the protocol
export default function () {
+
+ // mark the safe protocol as 'secure' to enable all DOM APIs
+ webFrame.registerURLSchemeAsSecure('safe');
window.beaker = { version: BEAKER_VERSION }
var webAPIs = ipcRenderer.sendSync('get-web-api-manifests', window.location.protocol)
for (var k in webAPIs) { |
1d1bb27be03858e431cecd00477a0fb43749a0ac | site/pages/mixins/__samples__/with-update.js | site/pages/mixins/__samples__/with-update.js | import { props, shadow, withUpdate } from 'skatejs';
class WithUpdate extends withUpdate() {
static get props() {
return {
name: props.string
};
}
updated() {
return (shadow(this).innerHTML = `Hello, ${this.name}!`);
}
}
customElements.define('with-update', WithUpdate);
| import { props, shadow, withUpdate } from 'skatejs';
class WithUpdate extends withUpdate() {
static get props() {
return {
name: props.string
};
}
updated() {
shadow(this).innerHTML = `Hello, ${this.name}!`;
}
}
customElements.define('with-update', WithUpdate);
| Remove return value from sample, it's not doing anything | Remove return value from sample, it's not doing anything | JavaScript | mit | chrisdarroch/skatejs,skatejs/skatejs,skatejs/skatejs,chrisdarroch/skatejs,skatejs/skatejs | ---
+++
@@ -7,7 +7,7 @@
};
}
updated() {
- return (shadow(this).innerHTML = `Hello, ${this.name}!`);
+ shadow(this).innerHTML = `Hello, ${this.name}!`;
}
}
|
b02b385adb60e13249e3ae11811100c5ad4a4118 | src/event.js | src/event.js | /**
* Event
*
* @author Rakume Hayashi<i@fake.moe>
*/
Faiash.ise.extend({
on: function() {
if (typeof arguments[0] === 'string') {
for (var i = 0; i < this.length; i++) {
this[i].addEventListener(arguments[0], arguments[1], arguments[2]);
}
} else {
for (var i = 0; i < this.length; i++) {
for (var event in this[i]) {
if (object.hasOwnProperty(event)) {
this[i].addEventListener(event, this[i][event]);
}
}
}
}
}
});
| /**
* Event
*
* @author Rakume Hayashi<i@fake.moe>
*/
Faiash.ise.extend({
bind: function() {
if (typeof arguments[0] === 'string') {
for (var i = 0; i < this.length; i++) {
this[i].addEventListener(arguments[0], arguments[1], arguments[2]);
}
} else {
for (var i = 0; i < this.length; i++) {
for (var event in this[i]) {
if (object.hasOwnProperty(event)) {
this[i].addEventListener(event, this[i][event]);
}
}
}
}
},
unbind: function() {
if (typeof arguments[0] === 'string') {
for (var i = 0; i < this.length; i++) {
this[i].removeEventListener(arguments[0], arguments[1], arguments[2]);
}
} else {
for (var i = 0; i < this.length; i++) {
for (var event in this[i]) {
if (object.hasOwnProperty(event)) {
this[i].removeEventListener(event, this[i][event]);
}
}
}
}
}
});
| Rename on to bind, add unbind | Rename on to bind, add unbind
| JavaScript | mit | Kunr/Faiash | ---
+++
@@ -5,7 +5,7 @@
*/
Faiash.ise.extend({
- on: function() {
+ bind: function() {
if (typeof arguments[0] === 'string') {
for (var i = 0; i < this.length; i++) {
this[i].addEventListener(arguments[0], arguments[1], arguments[2]);
@@ -19,5 +19,21 @@
}
}
}
+ },
+
+ unbind: function() {
+ if (typeof arguments[0] === 'string') {
+ for (var i = 0; i < this.length; i++) {
+ this[i].removeEventListener(arguments[0], arguments[1], arguments[2]);
+ }
+ } else {
+ for (var i = 0; i < this.length; i++) {
+ for (var event in this[i]) {
+ if (object.hasOwnProperty(event)) {
+ this[i].removeEventListener(event, this[i][event]);
+ }
+ }
+ }
+ }
}
}); |
eb8a252ffd5923e328603f0c7c61048a1a2d2e72 | src/index.js | src/index.js | import {Stream} from 'most'
import MulticastSource from './MulticastSource'
function multicast (stream) {
const source = stream.source
return source instanceof MulticastSource
? stream
: new Stream(new MulticastSource(source))
}
export {multicast as default, MulticastSource}
| import MulticastSource from './MulticastSource'
function multicast (stream) {
const source = stream.source
return source instanceof MulticastSource
? stream
: new stream.constructor(new MulticastSource(source))
}
export {multicast as default, MulticastSource}
| Break dep cycle, allow most to use mostjs/multicast | Break dep cycle, allow most to use mostjs/multicast
| JavaScript | mit | mostjs/multicast | ---
+++
@@ -1,11 +1,10 @@
-import {Stream} from 'most'
import MulticastSource from './MulticastSource'
function multicast (stream) {
const source = stream.source
return source instanceof MulticastSource
? stream
- : new Stream(new MulticastSource(source))
+ : new stream.constructor(new MulticastSource(source))
}
export {multicast as default, MulticastSource} |
3231c6bffcffad290e7a900e7a51d5b889f796bf | src/index.js | src/index.js | // Configuration
export {default as configure} from './configure';
export {default as configureRoutes} from './configureRoutes';
// Components
export {default as Card} from './components/Card/Card';
export {default as Span} from './components/Specimen/Span';
// Higher-order component for creating specimens
export {default as Specimen} from './components/Specimen/Specimen';
// Specimens
export {default as AudioSpecimen} from './specimens/Audio';
export {default as ButtonSpecimen} from './specimens/Button';
export {default as CodeSpecimen} from './specimens/Code';
export {default as ColorSpecimen} from './specimens/Color';
export {default as HtmlSpecimen} from './specimens/Html';
export {default as HintSpecimen} from './specimens/Hint';
export {default as ImageSpecimen} from './specimens/Image';
export {default as TypeSpecimen} from './specimens/Type';
export {default as ProjectSpecimen} from './specimens/Project/Project';
export {default as DownloadSpecimen} from './specimens/Download';
export {default as ReactSpecimen} from './specimens/ReactSpecimen/ReactSpecimen';
export {default as VideoSpecimen} from './specimens/Video';
| // Configuration
export {default as render} from './render';
export {default as configure} from './configure';
export {default as configureRoutes} from './configureRoutes';
// Components
export {default as Card} from './components/Card/Card';
export {default as Span} from './components/Specimen/Span';
// Higher-order component for creating specimens
export {default as Specimen} from './components/Specimen/Specimen';
// Specimens
export {default as AudioSpecimen} from './specimens/Audio';
export {default as ButtonSpecimen} from './specimens/Button';
export {default as CodeSpecimen} from './specimens/Code';
export {default as ColorSpecimen} from './specimens/Color';
export {default as HtmlSpecimen} from './specimens/Html';
export {default as HintSpecimen} from './specimens/Hint';
export {default as ImageSpecimen} from './specimens/Image';
export {default as TypeSpecimen} from './specimens/Type';
export {default as ProjectSpecimen} from './specimens/Project/Project';
export {default as DownloadSpecimen} from './specimens/Download';
export {default as ReactSpecimen} from './specimens/ReactSpecimen/ReactSpecimen';
export {default as VideoSpecimen} from './specimens/Video';
| Bring back `render` to module | Bring back `render` to module
| JavaScript | bsd-3-clause | interactivethings/catalog,interactivethings/catalog,interactivethings/catalog,interactivethings/catalog | ---
+++
@@ -1,4 +1,5 @@
// Configuration
+export {default as render} from './render';
export {default as configure} from './configure';
export {default as configureRoutes} from './configureRoutes';
|
b5fb9cadc7ac30f291f7db9e5a692271cc58e2d4 | src/index.js | src/index.js | import React from 'react'
import ReactDOM from 'react-dom'
import {Router, browserHistory} from 'react-router'
import configureStore from './store'
import {Provider} from 'react-redux'
import {syncHistoryWithStore} from 'react-router-redux'
import APIUtils from './utils/APIUtils'
import { AppContainer } from 'react-hot-loader'
import {makeRoutes} from './routes'
// styles are stored separately in production
if (__DEV__)
require('../stylus/index.styl')
// require('bootstrap/dist/css/bootstrap.css')
class Root extends React.Component {
render() {
return (
<Provider store={this.props.store}>
<Router history={browserHistory}>
{this.props.routes}
</Router>
</Provider>
)
}
}
const api = new APIUtils()
const store = configureStore(api)
const history = syncHistoryWithStore(browserHistory, store)
function render(routes) {
console.log('render')
ReactDOM.render(
<AppContainer>
<Provider store={store}>
<Router history={history}>
{routes}
</Router>
</Provider>
</AppContainer>,
document.getElementById('app')
)
}
render(makeRoutes())
if (module.hot)
module.hot.accept('./routes', () => render(makeRoutes()))
| import React from 'react'
import ReactDOM from 'react-dom'
import {Router, browserHistory} from 'react-router'
import configureStore from './store'
import {Provider} from 'react-redux'
import {syncHistoryWithStore} from 'react-router-redux'
import APIUtils from './utils/APIUtils'
import { AppContainer } from 'react-hot-loader'
import {makeRoutes} from './routes'
import '../stylus/index.styl'
class Root extends React.Component {
render() {
return (
<Provider store={this.props.store}>
<Router history={browserHistory}>
{this.props.routes}
</Router>
</Provider>
)
}
}
const api = new APIUtils()
const store = configureStore(api)
const history = syncHistoryWithStore(browserHistory, store)
function render(routes) {
console.log('render')
ReactDOM.render(
<AppContainer>
<Provider store={store}>
<Router history={history}>
{routes}
</Router>
</Provider>
</AppContainer>,
document.getElementById('app')
)
}
render(makeRoutes())
if (module.hot)
module.hot.accept('./routes', () => render(makeRoutes()))
| Fix style loading in production. | Fix style loading in production.
| JavaScript | mit | jsza/tempus-website,jsza/tempus-website | ---
+++
@@ -9,10 +9,7 @@
import {makeRoutes} from './routes'
-// styles are stored separately in production
-if (__DEV__)
- require('../stylus/index.styl')
- // require('bootstrap/dist/css/bootstrap.css')
+import '../stylus/index.styl'
class Root extends React.Component { |
15f0a28bdc86013e07e662c3ef02d8da1e112434 | src/index.js | src/index.js | import Component from './src/component';
import PureComponent from './src/pureComponent';
export default {
Component,
PureComponent,
};
| import Component from './component';
import PureComponent from './pureComponent';
export default {
Component,
PureComponent,
};
| Fix import path after file move. | Fix import path after file move.
| JavaScript | mit | wimpyprogrammer/react-component-update | ---
+++
@@ -1,5 +1,5 @@
-import Component from './src/component';
-import PureComponent from './src/pureComponent';
+import Component from './component';
+import PureComponent from './pureComponent';
export default {
Component, |
b85745c284cbf29372b9caf2d2ea8010d1129ac2 | test/node.js | test/node.js | "use strict";
var assert = require('assert');
var CryptoApi = require('../lib/crypto-api');
var hex = require('../lib/enc.hex');
var md2 = require('../lib/hasher.md2');
var md4 = require('../lib/hasher.md4');
var md5 = require('../lib/hasher.md5');
var sha0 = require('../lib/hasher.sha0');
var sha1 = require('../lib/hasher.sha1');
var sha256 = require('../lib/hasher.sha256');
var TestVectors = require('../test-vectors');
Object.keys(TestVectors).forEach(function(hash) {
describe('Tests for hash ' + hash, function () {
Object.keys(TestVectors[hash]).forEach(function(msg) {
it(msg, function () {
assert.equal(CryptoApi.hash(hash, TestVectors[hash][msg].message, {}).stringify('hex'), TestVectors[hash][msg].hash);
});
});
});
}); | "use strict";
var assert = require('assert');
var CryptoApi = require('../lib/crypto-api');
var hex = require('../lib/enc.hex');
var md2 = require('../lib/hasher.md2');
var md4 = require('../lib/hasher.md4');
var md5 = require('../lib/hasher.md5');
var sha0 = require('../lib/hasher.sha0');
var sha1 = require('../lib/hasher.sha1');
var sha256 = require('../lib/hasher.sha256');
var TestVectors = require('../test-vectors');
Object.keys(TestVectors).forEach(function(hash) {
describe('Tests for hash ' + hash, function () {
Object.keys(TestVectors[hash]).forEach(function(msg) {
it(msg, function () {
assert.equal(CryptoApi.hash(hash, TestVectors[hash][msg].message, {}).stringify('hex'), TestVectors[hash][msg].hash);
});
});
});
});
describe('Test Error handling', function () {
it("CryptoApi.hash('no-hasher')", function () {
var error = '';
try {
CryptoApi.hash('no-hasher', '', {});
} catch(e) {
error = e;
}
assert.equal(error instanceof Error, true);
});
it("CryptoApi.hash('md2').stringify('no-encode')", function () {
var error = '';
try {
CryptoApi.hash('md2', '', {}).stringify('no-encode');
} catch(e) {
error = e;
}
assert.equal(error instanceof Error, true);
});
it("CryptoApi.Hashers.add('undefined', undefined", function () {
var error = '';
try {
CryptoApi.Hashers.add('undefined', undefined);
} catch(e) {
error = e;
}
assert.equal(error instanceof Error, true);
});
it("CryptoApi.Encodes.add('undefined', undefined)", function () {
var error = '';
try {
CryptoApi.Encodes.add('undefined', undefined);
} catch(e) {
error = e;
}
assert.equal(error instanceof Error, true);
});
}); | Add tests for error handling | Add tests for error handling
| JavaScript | mit | nf404/crypto-api,nf404/crypto-api | ---
+++
@@ -21,3 +21,41 @@
});
});
});
+describe('Test Error handling', function () {
+ it("CryptoApi.hash('no-hasher')", function () {
+ var error = '';
+ try {
+ CryptoApi.hash('no-hasher', '', {});
+ } catch(e) {
+ error = e;
+ }
+ assert.equal(error instanceof Error, true);
+ });
+ it("CryptoApi.hash('md2').stringify('no-encode')", function () {
+ var error = '';
+ try {
+ CryptoApi.hash('md2', '', {}).stringify('no-encode');
+ } catch(e) {
+ error = e;
+ }
+ assert.equal(error instanceof Error, true);
+ });
+ it("CryptoApi.Hashers.add('undefined', undefined", function () {
+ var error = '';
+ try {
+ CryptoApi.Hashers.add('undefined', undefined);
+ } catch(e) {
+ error = e;
+ }
+ assert.equal(error instanceof Error, true);
+ });
+ it("CryptoApi.Encodes.add('undefined', undefined)", function () {
+ var error = '';
+ try {
+ CryptoApi.Encodes.add('undefined', undefined);
+ } catch(e) {
+ error = e;
+ }
+ assert.equal(error instanceof Error, true);
+ });
+}); |
cdb29356d47db83b517e053165ef78cfd81ff918 | db/models/beacons.js | db/models/beacons.js | const Sequelize = require('sequelize');
const db = require('../db.js');
const beacon = db.define('beacon', {
currentLocation: {
type: Sequelize.ARRAY(Sequelize.FLOAT),
},
})
module.exports = beacon;
| const Sequelize = require('sequelize');
const db = require('../db.js');
const beacon = db.define('beacon', {
currentLocation: {
type: Sequelize.ARRAY(Sequelize.FLOAT),
},
OS: {
type: Sequelize.STRING,
},
token: {
type: Sequelize.STRING,
},
lastNotification: {
type: Sequelize.DATE,
},
device: {
type: Sequelize.STRING,
}
})
module.exports = beacon;
| Add device info to beacon | refactor(database): Add device info to beacon
Add device info to beacon
| JavaScript | mit | LintLions/Respondr,LintLions/Respondr | ---
+++
@@ -5,6 +5,18 @@
currentLocation: {
type: Sequelize.ARRAY(Sequelize.FLOAT),
},
+ OS: {
+ type: Sequelize.STRING,
+ },
+ token: {
+ type: Sequelize.STRING,
+ },
+ lastNotification: {
+ type: Sequelize.DATE,
+ },
+ device: {
+ type: Sequelize.STRING,
+ }
})
module.exports = beacon; |
3e231f8ada23d4c166facae27933f2f2c9024aea | addon/mixin.js | addon/mixin.js | import Ember from 'ember';
export default Ember.Mixin.create({
init: function() {
this._super();
if(!this.hasAnalytics()) {
Ember.Logger.warn('Segment.io is not loaded yet (window.analytics)');
}
},
hasAnalytics: function() {
return !!(window.analytics && typeof window.analytics === "object");
},
log: function() {
if(this.config && this.config.segment && this.config.segment.LOG_EVENT_TRACKING) {
Ember.Logger.info('[Segment.io] ', arguments);
}
},
trackPageView: function(page) {
if(this.hasAnalytics()) {
window.analytics.page(page);
this.log('trackPageView', page);
}
},
trackEvent: function(event, properties, options, callback) {
if(this.hasAnalytics()) {
window.analytics.track(event, properties, options, callback);
this.log(event, properties, options);
}
},
identifyUser: function(userId, traits, options, callback) {
if(this.hasAnalytics()) {
window.analytics.identify(userId, traits, options, callback);
this.log('identifyUser', traits, options);
}
},
aliasUser: function(userId, previousId, options, callback) {
if(this.hasAnalytics()) {
window.analytics.alias(userId, previousId, options, callback);
this.log('aliasUser', previousId, options);
}
}
});
| import Ember from 'ember';
export default Ember.Mixin.create({
init: function() {
this._super();
if(!this.hasAnalytics()) {
Ember.Logger.warn('Segment.io is not loaded yet (window.analytics)');
}
},
hasAnalytics: function() {
return !!(window.analytics && typeof window.analytics === "object");
},
log: function() {
if(this.config && this.config.segment && this.config.segment.LOG_EVENT_TRACKING) {
Ember.Logger.info('[Segment.io] ', arguments);
}
},
trackPageView: function() {
if(this.hasAnalytics()) {
window.analytics.page.apply(this, arguments);
this.log('trackPageView', arguments);
}
},
trackEvent: function(event, properties, options, callback) {
if(this.hasAnalytics()) {
window.analytics.track(event, properties, options, callback);
this.log(event, properties, options);
}
},
identifyUser: function(userId, traits, options, callback) {
if(this.hasAnalytics()) {
window.analytics.identify(userId, traits, options, callback);
this.log('identifyUser', traits, options);
}
},
aliasUser: function(userId, previousId, options, callback) {
if(this.hasAnalytics()) {
window.analytics.alias(userId, previousId, options, callback);
this.log('aliasUser', previousId, options);
}
}
});
| Allow passing more params to trackPageView | Allow passing more params to trackPageView
| JavaScript | mit | cepko33/ember-cli-analytics,cepko33/ember-cli-analytics,josemarluedke/ember-cli-segment,kmiyashiro/ember-cli-segment,josemarluedke/ember-cli-segment,kmiyashiro/ember-cli-segment | ---
+++
@@ -17,11 +17,11 @@
}
},
- trackPageView: function(page) {
+ trackPageView: function() {
if(this.hasAnalytics()) {
- window.analytics.page(page);
+ window.analytics.page.apply(this, arguments);
- this.log('trackPageView', page);
+ this.log('trackPageView', arguments);
}
},
|
8380f2753ac96953a141e6f393f2829335255dba | lib/services/route53.js | lib/services/route53.js | /**
* Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You
* may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
var AWS = require('../core');
AWS.Route53 = AWS.Service.defineService('route53', ['2012-12-12'], {
setupRequestListeners: function setupRequestListeners(request) {
request.on('build', this.sanitizeUrl);
},
sanitizeUrl: function sanitizeUrl(request) {
var path = request.httpRequest.path;
request.httpRequest.path = path.replace(/\/%2F\w+%2F/, '/');
},
setEndpoint: function setEndpoint(endpoint) {
if (endpoint) {
AWS.Service.prototype.setEndpoint(endpoint);
} else {
var opts = {sslEnabled: true}; // SSL is always enabled for Route53
this.endpoint = new AWS.Endpoint(this.api.globalEndpoint, opts);
}
}
});
module.exports = AWS.Route53;
| /**
* Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You
* may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
var AWS = require('../core');
AWS.Route53 = AWS.Service.defineService('route53', ['2012-12-12'], {
/**
* @api private
*/
setupRequestListeners: function setupRequestListeners(request) {
request.on('build', this.sanitizeUrl);
},
/**
* @api private
*/
sanitizeUrl: function sanitizeUrl(request) {
var path = request.httpRequest.path;
request.httpRequest.path = path.replace(/\/%2F\w+%2F/, '/');
},
/**
* @api private
*/
setEndpoint: function setEndpoint(endpoint) {
if (endpoint) {
AWS.Service.prototype.setEndpoint(endpoint);
} else {
var opts = {sslEnabled: true}; // SSL is always enabled for Route53
this.endpoint = new AWS.Endpoint(this.api.globalEndpoint, opts);
}
}
});
module.exports = AWS.Route53;
| Update documentation for Route53 service | Update documentation for Route53 service
| JavaScript | apache-2.0 | jeskew/aws-sdk-js,chrisradek/aws-sdk-js,Blufe/aws-sdk-js,guymguym/aws-sdk-js,odeke-em/aws-sdk-js,chrisradek/aws-sdk-js,beni55/aws-sdk-js,Blufe/aws-sdk-js,prembasumatary/aws-sdk-js,grimurjonsson/aws-sdk-js,MitocGroup/aws-sdk-js,beni55/aws-sdk-js,dconnolly/aws-sdk-js,grimurjonsson/aws-sdk-js,jmswhll/aws-sdk-js,dconnolly/aws-sdk-js,prestomation/aws-sdk-js,GlideMe/aws-sdk-js,jippeholwerda/aws-sdk-js,prestomation/aws-sdk-js,jmswhll/aws-sdk-js,MitocGroup/aws-sdk-js,aws/aws-sdk-js,mohamed-kamal/aws-sdk-js,AdityaManohar/aws-sdk-js,jeskew/aws-sdk-js,misfitdavidl/aws-sdk-js,j3tm0t0/aws-sdk-js,misfitdavidl/aws-sdk-js,ugie/aws-sdk-js,mohamed-kamal/aws-sdk-js,MitocGroup/aws-sdk-js,j3tm0t0/aws-sdk-js,aws/aws-sdk-js,AdityaManohar/aws-sdk-js,LiuJoyceC/aws-sdk-js,odeke-em/aws-sdk-js,misfitdavidl/aws-sdk-js,LiuJoyceC/aws-sdk-js,jmswhll/aws-sdk-js,AdityaManohar/aws-sdk-js,jeskew/aws-sdk-js,odeke-em/aws-sdk-js,guymguym/aws-sdk-js,michael-donat/aws-sdk-js,mapbox/aws-sdk-js,Blufe/aws-sdk-js,grimurjonsson/aws-sdk-js,jippeholwerda/aws-sdk-js,mapbox/aws-sdk-js,mohamed-kamal/aws-sdk-js,michael-donat/aws-sdk-js,GlideMe/aws-sdk-js,j3tm0t0/aws-sdk-js,jippeholwerda/aws-sdk-js,guymguym/aws-sdk-js,prembasumatary/aws-sdk-js,GlideMe/aws-sdk-js,GlideMe/aws-sdk-js,mapbox/aws-sdk-js,jeskew/aws-sdk-js,dconnolly/aws-sdk-js,chrisradek/aws-sdk-js,chrisradek/aws-sdk-js,guymguym/aws-sdk-js,aws/aws-sdk-js,LiuJoyceC/aws-sdk-js,michael-donat/aws-sdk-js,aws/aws-sdk-js,ugie/aws-sdk-js,prembasumatary/aws-sdk-js,ugie/aws-sdk-js,beni55/aws-sdk-js,prestomation/aws-sdk-js | ---
+++
@@ -16,15 +16,24 @@
var AWS = require('../core');
AWS.Route53 = AWS.Service.defineService('route53', ['2012-12-12'], {
+ /**
+ * @api private
+ */
setupRequestListeners: function setupRequestListeners(request) {
request.on('build', this.sanitizeUrl);
},
+ /**
+ * @api private
+ */
sanitizeUrl: function sanitizeUrl(request) {
var path = request.httpRequest.path;
request.httpRequest.path = path.replace(/\/%2F\w+%2F/, '/');
},
+ /**
+ * @api private
+ */
setEndpoint: function setEndpoint(endpoint) {
if (endpoint) {
AWS.Service.prototype.setEndpoint(endpoint); |
b6c04907f80c9942358dfbaf5bd9d5d40afdb120 | lib/utils/leap-mockhand.js | lib/utils/leap-mockhand.js | 'use strict'
const path = require('path')
const { config } = require(path.join(__dirname, '..', '..', 'main.config.js'))
module.exports = class MockHand {
constructor (normalizedPosition) {
this.normalizedPosition = [...normalizedPosition]
this.target = [...normalizedPosition]
}
update (box) {
this.normalizedPosition.forEach((_, index) => {
const d = this.target[index] - this.normalizedPosition[index]
this.normalizedPosition[index] += d * config.leap.mockHandEasing
})
return {
x: this.normalizedPosition[0] * box[0],
y: this.normalizedPosition[2] * box[1],
z: this.normalizedPosition[1] * box[2]
}
}
}
| 'use strict'
const path = require('path')
const { config } = require(path.join(__dirname, '..', '..', 'main.config.js'))
module.exports = class MockHand {
constructor (normalizedPosition) {
this.normalizedPosition = [...normalizedPosition]
this.target = [...normalizedPosition]
}
update (box) {
this.normalizedPosition.forEach((_, index) => {
const d = this.target[index] - this.normalizedPosition[index]
this.normalizedPosition[index] += d * config.leap.mockHandEasing
})
return {
isMockHand: true,
x: this.normalizedPosition[0] * box[0],
y: this.normalizedPosition[2] * box[1],
z: this.normalizedPosition[1] * box[2]
}
}
}
| Add method to determine if hand is mocked | [leap] Add method to determine if hand is mocked
| JavaScript | mit | chevalvert/stratum,chevalvert/stratum | ---
+++
@@ -16,6 +16,7 @@
})
return {
+ isMockHand: true,
x: this.normalizedPosition[0] * box[0],
y: this.normalizedPosition[2] * box[1],
z: this.normalizedPosition[1] * box[2] |
8531b26b2a71517b3ebabc7659d678a91c8f970e | src/files.js | src/files.js | var fs = require('fs-extra');
exports.newer = function(src, dest) {
var srcTime = 0;
try {
var srcTime = fs.statSync(src).ctime.getTime();
} catch (ex) {
return false;
}
try {
var destTime = fs.statSync(dest).ctime.getTime();
return srcTime > destTime;
} catch (ex) {
return true;
}
};
| var fs = require('fs');
exports.newer = function(src, dest) {
var srcTime = 0;
try {
var srcTime = fs.statSync(src).mtime.getTime();
} catch (ex) {
return false;
}
try {
var destTime = fs.statSync(dest).mtime.getTime();
return srcTime > destTime;
} catch (ex) {
return true;
}
};
| Use modified time instead of creation time when copying folders | Use modified time instead of creation time when copying folders
| JavaScript | mit | rprieto/thumbsup,kremlinkev/thumbsup,thumbsup/thumbsup,thumbsup/node-thumbsup,thumbsup/thumbsup,thumbsup/node-thumbsup,dravenst/thumbsup,kremlinkev/thumbsup,rprieto/thumbsup,dravenst/thumbsup,thumbsup/node-thumbsup | ---
+++
@@ -1,14 +1,14 @@
-var fs = require('fs-extra');
+var fs = require('fs');
exports.newer = function(src, dest) {
var srcTime = 0;
try {
- var srcTime = fs.statSync(src).ctime.getTime();
+ var srcTime = fs.statSync(src).mtime.getTime();
} catch (ex) {
return false;
}
try {
- var destTime = fs.statSync(dest).ctime.getTime();
+ var destTime = fs.statSync(dest).mtime.getTime();
return srcTime > destTime;
} catch (ex) {
return true; |
91c3c0a352c46c885b5dd169ea6c59ce6863337a | app/bundles.js | app/bundles.js | var fs = require('fs'),
_ = require('lodash'),
yaml = require('js-yaml'),
bundles = yaml.safeLoad(fs.readFileSync('bundles.yml', 'utf8')),
settings = require('./config');
function getTag(key, asset) {
if (key.indexOf('_js') > -1) {
return '<script type="text/javascript" src="' + asset + '"></script>';
} else {
return '<link rel="stylesheet" type="text/css" href="' + asset + '" />';
}
}
function production(value, key) {
return [key, getTag(key, value.dest)];
}
function development(value, key) {
var tags = value.src.map(function(asset) {
return getTag(key, asset);
});
return [key, tags.join('')];
}
var map = settings.env === 'production' ? production : development;
module.exports = _.object(_.map(bundles, map));
| var fs = require('fs'),
_ = require('lodash'),
yaml = require('js-yaml'),
bundles = yaml.safeLoad(fs.readFileSync('bundles.yml', 'utf8')),
settings = require('./config');
function getTag(key, asset) {
if (key.indexOf('_js') > -1) {
return '<script type="text/javascript" src="' + asset + '"></script>';
} else {
return '<link rel="stylesheet" type="text/css" href="' + asset + '" />';
}
}
function production(value, key) {
return [key, getTag(key, value.dest)];
}
function development(value, key) {
var tags = value.src.map(function(asset) {
if (asset.indexOf('socket.io.js') > -1) {
asset ='socket.io/socket.io.js';
}
return getTag(key, asset);
});
return [key, tags.join('')];
}
var map = settings.env === 'production' ? production : development;
module.exports = _.object(_.map(bundles, map));
| Fix loading of socket.io.js when in development mode | Fix loading of socket.io.js when in development mode
| JavaScript | mit | cesarmarinhorj/lets-chat,ashwini-angular/lets-chat,nickrobinson/lets-chat,evdevgit/lets-chat,disappearedgod/lets-chat,rlightner/lets-chat,KillianKemps/lets-chat,saitodisse/lets-chat,hzruandd/lets-chat,sdelements/lets-chat,webkaz/lets-chat,aaryn101/lets-chat,e-green/eduChat,jparyani/lets-chat,damoguyan8844/lets-chat,damoguyan8844/lets-chat,linhmtran168/lets-chat,fabianschwarzfritz/lets-chat,cloudnautique/lets-chat,alexisaperez/lets-chat,eetuuuu/lets-chat,robin1liu/lets-chat,neynah/lets-chat,Drooids/lets-chat,fhchina/lets-chat,webbab/lets-chat,ycaihua/lets-chat,heitortsergent/lets-chat,leolujuyi/lets-chat,glomb226/lets-chat,e-green/eduChat,gvmatera/lets-chat,udacity/lets-chat,Stackato-Apps/lets-chat,saranrapjs/lets-chat,nickrobinson/lets-chat,saitodisse/lets-chat,fhchina/lets-chat,CodesScripts/lets-chat,hrwebasst/lets-chat,kaushik94/ama,fabric8io/lets-chat,yangchaogit/lets-chat,qitianchan/lets-chat,galal-hussein/lets-chat,fabianschwarzfritz/lets-chat,cloudnautique/lets-chat,akira1908jp/tachikawapm,eetuuuu/lets-chat,dcode/lets-chat,xdevelsistemas/lets-chat,jparyani/lets-chat,eiriklv/lets-chat,webbab/lets-chat,MOZGIII/lets-chat,beni55/lets-chat,praveenscience/lets-chat,leohmoraes/lets-chat,ashwini-angular/lets-chat,iooly/lets-chat,sitexa/lets-chat,lihuanghai/lets-chat,galal-hussein/lets-chat,lumeet/lets-chat,hzruandd/lets-chat,akira1908jp/tachikawapm,beijinglug/lets-chat,Stackato-Apps/lets-chat,kaushik94/ama,neynah/lets-chat,lumeet/lets-chat,ycaihua/lets-chat,manland/lets-chat,8bitjeremy/velochat,sunnipaul/lets-chat,jparyani/lets-chat,replicat0r/tkcomm,gvmatera/lets-chat,galal-hussein/lets-chat,praveenscience/lets-chat,madnanbashir/stitch1,hrwebasst/lets-chat,ga-wdi-boston/lets-chat,ibuildthecloud/lets-chat,CodesScripts/lets-chat,sdelements/lets-chat,ibuildthecloud/lets-chat,cloudnautique/lets-chat,ga-wdi-boston/lets-chat,gamedevtech/lets-chat,alexisaperez/lets-chat,xdevelsistemas/lets-chat,Tepira/lets-chat,fallacy321/lets-chat,dmbrown/lets-chat,dmbrown/lets-chat,MenZil/lets-chat,stonegithubs/lets-chat,fallacy321/lets-chat,sploadie/lets-chat,madnanbashir/stitch1,manland/lets-chat,cesarmarinhorj/lets-chat,askmeanything-app/askmeanything,MOZGIII/lets-chat,tart/lets-chat,glomb226/lets-chat,hcxiong/lets-chat,rlightner/lets-chat,linhmtran168/lets-chat,heitortsergent/lets-chat,yangchaogit/lets-chat,fabric8io/lets-chat,ibuildthecloud/lets-chat,neynah/lets-chat,gautamkrishnar/lets-chat,thollingsheadesri/lets-chat,jjz/lets-chat,iooly/lets-chat,beni55/lets-chat,sploadie/lets-chat,Drooids/lets-chat,thollingsheadesri/lets-chat,jjz/lets-chat,webkaz/lets-chat,evdevgit/lets-chat,replicat0r/tkcomm,sitexa/lets-chat,hcxiong/lets-chat,leohmoraes/lets-chat,qitianchan/lets-chat,saranrapjs/lets-chat,udacity/lets-chat,adam-nnl/lets-chat,disappearedgod/lets-chat,askmeanything-app/askmeanything,dcode/lets-chat,leolujuyi/lets-chat,MenZil/lets-chat,gamedevtech/lets-chat,Tepira/lets-chat,adam-nnl/lets-chat,aaryn101/lets-chat,sunnipaul/lets-chat,lihuanghai/lets-chat,KillianKemps/lets-chat,ashwini-angular/lets-chat,8bitjeremy/velochat,alawnchen/lets-chat,beijinglug/lets-chat,galal-hussein/lets-chat,gautamkrishnar/lets-chat,alawnchen/lets-chat,stonegithubs/lets-chat,joyhuang-web/lets-chat,robin1liu/lets-chat | ---
+++
@@ -18,6 +18,9 @@
function development(value, key) {
var tags = value.src.map(function(asset) {
+ if (asset.indexOf('socket.io.js') > -1) {
+ asset ='socket.io/socket.io.js';
+ }
return getTag(key, asset);
});
|
b406c7cfd16c1054d2e3d3ccb054990f2d1679e1 | src/index.js | src/index.js | import React from 'react';
import ReactDOM from 'react-dom';
import { setComponentsNames, globalizeComponents, promoteInlineExamples, flattenChildren } from './utils/utils';
import StyleGuide from 'rsg-components/StyleGuide';
import 'highlight.js/styles/tomorrow.css';
import './styles.css';
global.React = React;
if (module.hot) {
module.hot.accept();
}
// Load style guide
let { config, components, sections } = require('styleguide!');
function processComponents(cs) {
cs = flattenChildren(cs);
cs = promoteInlineExamples(cs);
cs = setComponentsNames(cs);
globalizeComponents(cs);
return cs;
}
function processSections(ss) {
return ss.map(section => {
section.components = processComponents(section.components || []);
section.sections = processSections(section.sections || []);
return section;
});
}
// Components are required unless sections are provided
if (sections) {
sections = processSections(sections)
components = []
} else {
components = processComponents(components)
sections = []
}
components = components ? processComponents(components) : [];
sections = sections ? processSections(sections) : [];
ReactDOM.render(<StyleGuide config={config} components={components} sections={sections} />, document.getElementById('app'));
| import React from 'react';
import ReactDOM from 'react-dom';
import { setComponentsNames, globalizeComponents, promoteInlineExamples, flattenChildren } from './utils/utils';
import StyleGuide from 'rsg-components/StyleGuide';
import 'highlight.js/styles/tomorrow.css';
import './styles.css';
global.React = React;
if (module.hot) {
module.hot.accept();
}
// Load style guide
let { config, components, sections } = require('styleguide!');
function processComponents(cs) {
cs = flattenChildren(cs);
cs = promoteInlineExamples(cs);
cs = setComponentsNames(cs);
globalizeComponents(cs);
return cs;
}
function processSections(ss) {
return ss.map(section => {
section.components = processComponents(section.components || []);
section.sections = processSections(section.sections || []);
return section;
});
}
// Components are required unless sections are provided
if (sections) {
sections = processSections(sections);
components = [];
}
else {
components = processComponents(components);
sections = [];
}
ReactDOM.render(<StyleGuide config={config} components={components} sections={sections} />, document.getElementById('app'));
| Fix linting issues and duplicate check for components and sections | Fix linting issues and duplicate check for components and sections
| JavaScript | mit | bluetidepro/react-styleguidist,sapegin/react-styleguidist,sapegin/react-styleguidist,styleguidist/react-styleguidist,styleguidist/react-styleguidist,styleguidist/react-styleguidist | ---
+++
@@ -35,13 +35,12 @@
// Components are required unless sections are provided
if (sections) {
- sections = processSections(sections)
- components = []
-} else {
- components = processComponents(components)
- sections = []
+ sections = processSections(sections);
+ components = [];
}
-components = components ? processComponents(components) : [];
-sections = sections ? processSections(sections) : [];
+else {
+ components = processComponents(components);
+ sections = [];
+}
ReactDOM.render(<StyleGuide config={config} components={components} sections={sections} />, document.getElementById('app')); |
069c586ba2a6a33ce830b383931ce32a958498f0 | src/index.js | src/index.js | import functionalText from "functional-text";
window.addEventListener("DOMContentLoaded", function () {
let inputNode = document.querySelector("#input");
let outputHtmlNode = document.querySelector("#output-html");
let str = `Sample Text for parsing`.trim();
inputNode.value = str;
inputNode.style.height = '200px';
inputNode.style.width = '100%';
function runParser() {
let parsedHtml = functionalText(inputNode.value);
outputHtmlNode.innerHTML = parsedHtml.replace(/</g, "<").replace(/>/g, ">");
}
inputNode.addEventListener("input", runParser, 200);
try {
runParser();
} catch (err) {
console.error(err);
}
}); | import functionalText from "functional-text";
window.addEventListener("DOMContentLoaded", function () {
let inputNode = document.querySelector("#input");
let outputHtmlNode = document.querySelector("#output-html");
let str = `Sample Text for parsing`.trim();
inputNode.value = str;
inputNode.style.height = '200px';
inputNode.style.width = '100%';
function runParser() {
try {
let parsedHtml = functionalText(inputNode.value);
outputHtmlNode.style.borderColor = "black";
outputHtmlNode.innerHTML = parsedHtml.replace(/</g, "<").replace(/>/g, ">");
} catch (error) {
outputHtmlNode.style.borderColor = "red";
outputHtmlNode.innerHTML = error;
}
}
inputNode.addEventListener("input", runParser, 200);
runParser();
}); | Move try-catch into the parsing logic, and display errors into the output. | Move try-catch into the parsing logic, and display errors into the
output.
| JavaScript | mit | measurement-factory/functional-text-sandbox,measurement-factory/functional-text-sandbox,measurement-factory/functional-text-sandbox | ---
+++
@@ -11,14 +11,16 @@
inputNode.style.width = '100%';
function runParser() {
- let parsedHtml = functionalText(inputNode.value);
- outputHtmlNode.innerHTML = parsedHtml.replace(/</g, "<").replace(/>/g, ">");
+ try {
+ let parsedHtml = functionalText(inputNode.value);
+ outputHtmlNode.style.borderColor = "black";
+ outputHtmlNode.innerHTML = parsedHtml.replace(/</g, "<").replace(/>/g, ">");
+ } catch (error) {
+ outputHtmlNode.style.borderColor = "red";
+ outputHtmlNode.innerHTML = error;
+ }
}
inputNode.addEventListener("input", runParser, 200);
- try {
- runParser();
- } catch (err) {
- console.error(err);
- }
+ runParser();
}); |
ec8cc8b69d872fbaf6898e30aa03f96cccbaef92 | src/index.js | src/index.js | import React from 'react';
import { render } from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import App from './components/app';
import rootReducer from './reducers'
const store = createStore(rootReducer);
render(
<Provider store={store}>
<App />
</Provider>, document.getElementById('app'));
| import React from 'react';
import { render } from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import App from './components/app';
import rootReducer from './reducers'
const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
render(
<Provider store={createStoreWithMiddleware(rootReducer)}>
<App />
</Provider>, document.getElementById('app'));
| Update React app entry point: Add middleware to the project Use redux-thunk lib Applies middleware and use it as store | Update React app entry point:
Add middleware to the project
Use redux-thunk lib
Applies middleware and use it as store
| JavaScript | mit | Jesus-Gonzalez/ReactReduxTestNumberTwo,Jesus-Gonzalez/ReactReduxTestNumberTwo | ---
+++
@@ -1,15 +1,16 @@
import React from 'react';
import { render } from 'react-dom';
-import { createStore } from 'redux';
+import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
+import thunk from 'redux-thunk';
import App from './components/app';
import rootReducer from './reducers'
-const store = createStore(rootReducer);
+const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
render(
- <Provider store={store}>
+ <Provider store={createStoreWithMiddleware(rootReducer)}>
<App />
</Provider>, document.getElementById('app')); |
61f4570bd931d2318489661ecf32dd482e008980 | src/index.js | src/index.js | import React from 'react';
import App from './app/App';
React.render(<App />, document.body);
| import React from 'react';
import ReactDOM from 'react-dom';
import App from './app/App';
const appRoot = document.createElement('div');
appRoot.id = 'app';
document.body.appendChild(appRoot);
ReactDOM.render(<App />, appRoot);
| Update App rendering to comply with React 0.14 | Update App rendering to comply with React 0.14
| JavaScript | mit | nkbt/esnext-quickstart,halhenke/life-letters | ---
+++
@@ -1,4 +1,9 @@
import React from 'react';
+import ReactDOM from 'react-dom';
import App from './app/App';
-React.render(<App />, document.body);
+const appRoot = document.createElement('div');
+
+appRoot.id = 'app';
+document.body.appendChild(appRoot);
+ReactDOM.render(<App />, appRoot); |
980fbb4f7f5ca3613a01182d5338d6eae7a98e04 | src/index.js | src/index.js | import glob from 'glob'
import path from 'path'
import Dns from './dns'
import { name as packageName } from '../package.json'
export default () => {
const dns = new Dns()
// Load Plugins
glob(
`./node_modules/${packageName}-plugin-*`,
( err, files ) => {
files
.forEach(
( plugin ) => {
plugin = path.basename( plugin )
const instance = eval('require')( plugin )
if ( instance && instance.default )
new instance.default( dns )
else if ( instance ) {
new instance( dns )
}
}
)
// Finally start the DNS daemon
dns.start()
}
)
} | import { exec } from 'child_process'
import glob from 'glob'
import path from 'path'
import Dns from './dns'
import { name as packageName } from '../package.json'
const dns = new Dns()
function getNodeModulesPath( isGlobal ) {
return new Promise (
( resolve, reject ) => {
if ( isGlobal )
exec(
`npm config get prefix -g`,
( err, stdout, stderr ) => {
if ( err ) reject( err )
else if ( stderr ) reject ( stderr )
else resolve( stdout )
}
)
else
resolve(
`${path.resolve()}/node_modules`
)
}
)
}
function loadPlugins( pluginPath ) {
return new Promise (
( resolve, reject ) => {
// Load Plugins
glob(
`${pluginPath}/${packageName}-plugin-*`,
( err, files ) => {
if ( err ) reject( err )
else {
files
.forEach(
( plugin ) => {
plugin = path.basename( plugin )
const instance = eval('require')( plugin )
if ( instance && instance.default )
new instance.default( dns )
else if ( instance ) {
new instance( dns )
}
}
)
// Finally resolve
resolve()
}
}
)
}
)
}
export default () => {
Promise.resolve()
.catch( err => console.log( err ) )
// Load global plugins
.then( () => getNodeModulesPath( true ) )
.then( path => loadPlugins( path ) )
// Load local plugins
.then( () => getNodeModulesPath() )
.then( path => loadPlugins( path ) )
// Start the DNS
.then( () => dns.start() )
} | Allow loading of local and global plugins | Allow loading of local and global plugins
| JavaScript | mit | dynsdjs/dynsdjs,julianxhokaxhiu/zeroads | ---
+++
@@ -1,32 +1,73 @@
+import { exec } from 'child_process'
import glob from 'glob'
import path from 'path'
import Dns from './dns'
import { name as packageName } from '../package.json'
-export default () => {
- const dns = new Dns()
+const dns = new Dns()
- // Load Plugins
- glob(
- `./node_modules/${packageName}-plugin-*`,
- ( err, files ) => {
- files
- .forEach(
- ( plugin ) => {
- plugin = path.basename( plugin )
-
- const instance = eval('require')( plugin )
-
- if ( instance && instance.default )
- new instance.default( dns )
- else if ( instance ) {
- new instance( dns )
- }
- }
- )
-
- // Finally start the DNS daemon
- dns.start()
+function getNodeModulesPath( isGlobal ) {
+ return new Promise (
+ ( resolve, reject ) => {
+ if ( isGlobal )
+ exec(
+ `npm config get prefix -g`,
+ ( err, stdout, stderr ) => {
+ if ( err ) reject( err )
+ else if ( stderr ) reject ( stderr )
+ else resolve( stdout )
+ }
+ )
+ else
+ resolve(
+ `${path.resolve()}/node_modules`
+ )
}
)
}
+
+function loadPlugins( pluginPath ) {
+ return new Promise (
+ ( resolve, reject ) => {
+ // Load Plugins
+ glob(
+ `${pluginPath}/${packageName}-plugin-*`,
+ ( err, files ) => {
+ if ( err ) reject( err )
+ else {
+ files
+ .forEach(
+ ( plugin ) => {
+ plugin = path.basename( plugin )
+
+ const instance = eval('require')( plugin )
+
+ if ( instance && instance.default )
+ new instance.default( dns )
+ else if ( instance ) {
+ new instance( dns )
+ }
+ }
+ )
+
+ // Finally resolve
+ resolve()
+ }
+ }
+ )
+ }
+ )
+}
+
+export default () => {
+ Promise.resolve()
+ .catch( err => console.log( err ) )
+ // Load global plugins
+ .then( () => getNodeModulesPath( true ) )
+ .then( path => loadPlugins( path ) )
+ // Load local plugins
+ .then( () => getNodeModulesPath() )
+ .then( path => loadPlugins( path ) )
+ // Start the DNS
+ .then( () => dns.start() )
+} |
68d25860580b56f20ed8902917b3a10591d3462d | src/index.js | src/index.js | import R from 'ramda';
import And from './and';
import Or from './or';
import Conjunction from './conjunction';
/**
* Check if the given object is an object-like `And` conjunction.
* @param {Object} obj
* @param {String} obj.type
* @returns {Boolean}
*/
const objectIsAndConjunction = R.compose(
R.equals(And.type()),
R.prop('type')
);
/**
* Check if the given object is an object-like `Or` conjunction.
* @param {Object} obj
* @param {String} obj.type
* @returns {Boolean}
*/
const objectIsOrConjunction = R.compose(
R.equals(Or.type()),
R.prop('type')
);
const create = obj => {
if (objectIsOrConjunction(obj)) {
return new Or(obj.mappings);
} else if (objectIsAndConjunction(obj)) {
return new And(obj.mappings);
} else {
var message = 'Cannot create conjunction based on ' + obj;
throw new Error(message);
}
}
export default {
create,
And,
Or,
Conjunction
};
| import R from 'ramda';
import And from './and';
import Or from './or';
import Conjunction from './conjunction';
/**
* Check if the given object is an object-like `And` conjunction.
* @param {Object} obj
* @param {String} obj.type
* @returns {Boolean}
*/
const objectIsAndConjunction = R.compose(
R.equals(And.type()),
R.prop('type')
);
/**
* Check if the given object is an object-like `Or` conjunction.
* @param {Object} obj
* @param {String} obj.type
* @returns {Boolean}
*/
const objectIsOrConjunction = R.compose(
R.equals(Or.type()),
R.prop('type')
);
const create = obj => {
if (objectIsOrConjunction(obj)) {
return new Or(obj.mappings);
} else if (objectIsAndConjunction(obj)) {
return new And(obj.mappings);
} else {
var message = 'Cannot create conjunction based on ' + obj;
throw new Error(message);
}
}
module.exports = {
create,
And,
Or,
Conjunction
};
export default module.exports
| Add support to old module.exports (webpack has issue with it) | Add support to old module.exports (webpack has issue with it)
| JavaScript | mit | sendyhalim/noes | ---
+++
@@ -37,9 +37,11 @@
}
}
-export default {
+module.exports = {
create,
And,
Or,
Conjunction
};
+
+export default module.exports |
cb406be3b73e381adcd75a2105e2ded4c966380d | tests/acceptance/assignstudents-test.js | tests/acceptance/assignstudents-test.js | import { currentURL, visit } from '@ember/test-helpers';
import { module, test } from 'qunit';
import setupAuthentication from 'ilios/tests/helpers/setup-authentication';
import { percySnapshot } from 'ember-percy';
import { setupApplicationTest } from 'ember-qunit';
import setupMirage from 'ember-cli-mirage/test-support/setup-mirage';
import { getElementText, getText } from 'ilios/tests/helpers/custom-helpers';
module('Acceptance: assign students', function(hooks) {
setupApplicationTest(hooks);
setupMirage(hooks);
hooks.beforeEach(async function () {
const school = this.server.create('school');
await setupAuthentication({ school, administeredSchools: [this.school] });
this.server.create('school');
});
test('visiting /admin/assignstudents', async function(assert) {
await visit('/admin/assignstudents');
assert.equal(await getElementText('.schoolsfilter'), getText('school 0'));
assert.equal(currentURL(), '/admin/assignstudents');
percySnapshot(assert);
});
});
| import { currentURL, visit } from '@ember/test-helpers';
import { module, test } from 'qunit';
import setupAuthentication from 'ilios/tests/helpers/setup-authentication';
import { percySnapshot } from 'ember-percy';
import { setupApplicationTest } from 'ember-qunit';
import setupMirage from 'ember-cli-mirage/test-support/setup-mirage';
import { getElementText, getText } from 'ilios/tests/helpers/custom-helpers';
module('Acceptance: assign students', function(hooks) {
setupApplicationTest(hooks);
setupMirage(hooks);
hooks.beforeEach(async function () {
const school = this.server.create('school');
await setupAuthentication({ school, administeredSchools: [school] });
this.server.create('school');
});
test('visiting /admin/assignstudents', async function(assert) {
await visit('/admin/assignstudents');
assert.equal(await getElementText('.schoolsfilter'), getText('school 0'));
assert.equal(currentURL(), '/admin/assignstudents');
percySnapshot(assert);
});
});
| Fix test to pass model not nothing | Fix test to pass model not nothing
We were passing a value that doesn't exist and we need to pass the model
into administeredSchools.
| JavaScript | mit | dartajax/frontend,djvoa12/frontend,thecoolestguy/frontend,jrjohnson/frontend,ilios/frontend,thecoolestguy/frontend,jrjohnson/frontend,ilios/frontend,djvoa12/frontend,dartajax/frontend | ---
+++
@@ -12,7 +12,7 @@
setupMirage(hooks);
hooks.beforeEach(async function () {
const school = this.server.create('school');
- await setupAuthentication({ school, administeredSchools: [this.school] });
+ await setupAuthentication({ school, administeredSchools: [school] });
this.server.create('school');
});
|
080e9f84d5bc7c1b476b2c41cc3b84fafb9451ca | src/index.js | src/index.js | import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import App from './App';
import Board from './Board';
import './styles/index.css';
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="boards/:abbreviation/" component={Board}>
{/*<Route path="boards/:abbreviation/" component={ThreadList} />*/}
<Route path=":thread/" />
</Route>
</Route>
</Router>,
document.getElementById('root')
);
| import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import App from './App';
import Board from './Board';
import './styles/index.css';
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="boards/:abbreviation/" component={Board}>
<Route path=":threadId" />
</Route>
</Route>
</Router>,
document.getElementById('root')
);
| Fix bug with Board not realizing it's in a thread view | Fix bug with Board not realizing it's in a thread view
| JavaScript | mit | drop-table-ryhmatyo/tekislauta-front,drop-table-ryhmatyo/tekislauta-front | ---
+++
@@ -9,8 +9,7 @@
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="boards/:abbreviation/" component={Board}>
- {/*<Route path="boards/:abbreviation/" component={ThreadList} />*/}
- <Route path=":thread/" />
+ <Route path=":threadId" />
</Route>
</Route>
</Router>, |
fc831cffc40b2a3525bc69549799e221c77e8595 | config/app.js | config/app.js | export default {
name: 'Apollo Starter Kit',
logging: {
level: 'info',
debugSQL: false,
apolloLogging: ['production'].indexOf(process.env.NODE_ENV) < 0
},
// Check here for Windows and Mac OS X: https://code.visualstudio.com/docs/editor/command-line#_opening-vs-code-with-urls
// Use this protocol handler for Linux: https://github.com/sysgears/vscode-handler
stackFragmentFormat: 'vscode://file/{0}:{1}:{2}'
};
| export default {
name: 'Apollo Starter Kit',
logging: {
level: ['production'].indexOf(process.env.NODE_ENV) < 0 ? 'debug' : 'info',
debugSQL: false,
apolloLogging: ['production'].indexOf(process.env.NODE_ENV) < 0
},
// Check here for Windows and Mac OS X: https://code.visualstudio.com/docs/editor/command-line#_opening-vs-code-with-urls
// Use this protocol handler for Linux: https://github.com/sysgears/vscode-handler
stackFragmentFormat: 'vscode://file/{0}:{1}:{2}'
};
| Set log level to info only in production | Set log level to info only in production
| JavaScript | mit | sysgears/apollo-universal-starter-kit,sysgears/apollo-fullstack-starter-kit,sysgears/apollo-universal-starter-kit,sysgears/apollo-universal-starter-kit,sysgears/apollo-universal-starter-kit | ---
+++
@@ -1,7 +1,7 @@
export default {
name: 'Apollo Starter Kit',
logging: {
- level: 'info',
+ level: ['production'].indexOf(process.env.NODE_ENV) < 0 ? 'debug' : 'info',
debugSQL: false,
apolloLogging: ['production'].indexOf(process.env.NODE_ENV) < 0
}, |
558f6a65dac8908376dabaee78e3c590af0d59b8 | exercises/mock-box-view.js | exercises/mock-box-view.js | var extend = require('extend')
var bv, createClient
module.exports.mock = function (mocks) {
var boxview = 'box-view'
bv = require(boxview)
createClient = bv.createClient
bv.createClient = function (token) {
if (token === 'your api token') {
throw new Error('(HINT) remember to replace "your api token" with your Box View token!')
}
var client = createClient(token)
, mock = extend(true, {}, client, mocks)
mock.documents.__ = client.documents
mock.sessions.__ = client.sessions
return mock
}
}
module.exports.restore = function () {
if (bv) {
bv.createClient = createClient
}
}
| var extend = require('extend')
var bv, createClient
module.exports.mock = function (mocks, creator) {
var boxview = 'box-view'
bv = require(boxview)
createClient = bv.createClient
bv.createClient = function (token) {
if (token === 'your api token') {
throw new Error('(HINT) remember to replace "your api token" with your Box View token!')
}
var client = createClient(token)
, mock = extend(true, {}, client, mocks)
mock.documents.__ = client.documents
mock.sessions.__ = client.sessions
client.token = token
mock.documents.__client = client
mock.sessions.__client = client
return creator(mock, token)
}
}
module.exports.restore = function () {
if (bv) {
bv.createClient = createClient
}
}
| Add token and client reference to box-view mock | Add token and client reference to box-view mock
| JavaScript | mit | lakenen/view-school,lakenen/view-school | ---
+++
@@ -2,7 +2,7 @@
var bv, createClient
-module.exports.mock = function (mocks) {
+module.exports.mock = function (mocks, creator) {
var boxview = 'box-view'
bv = require(boxview)
createClient = bv.createClient
@@ -12,9 +12,14 @@
}
var client = createClient(token)
, mock = extend(true, {}, client, mocks)
+
mock.documents.__ = client.documents
mock.sessions.__ = client.sessions
- return mock
+ client.token = token
+ mock.documents.__client = client
+ mock.sessions.__client = client
+
+ return creator(mock, token)
}
}
|
1d6341af12b86001732d0cc06af7bf2880049676 | test/trie.js | test/trie.js | var Trie = require('../app/trie');
describe('Trie', function() {
var trie;
beforeEach(function() {
trie = new Trie();
});
it('should be an object', function() {
expect(trie).to.be.ok;
});
it('should have add method', function() {
expect(trie.add).to.be.an.instanceof(Function);
});
it('should have search method', function() {
expect(trie.search).to.be.an.instanceof(Function);
});
it('should have find method', function() {
expect(trie.find).to.be.an.instanceof(Function);
});
});
| var Trie = require('../app/trie');
describe('Trie', function() {
var trie;
beforeEach(function() {
trie = new Trie();
});
it('should be an object', function() {
expect(trie).to.be.ok;
});
it('should have a root', function() {
expect(trie.root).to.be.ok;
});
it('should have add method', function() {
expect(trie.add).to.be.an.instanceof(Function);
});
it('should have search method', function() {
expect(trie.search).to.be.an.instanceof(Function);
});
it('should have find method', function() {
expect(trie.find).to.be.an.instanceof(Function);
});
});
| Add check for root variable in Trie | Add check for root variable in Trie
| JavaScript | mit | mgarbacz/nordrassil,mgarbacz/nordrassil | ---
+++
@@ -9,6 +9,10 @@
it('should be an object', function() {
expect(trie).to.be.ok;
+ });
+
+ it('should have a root', function() {
+ expect(trie.root).to.be.ok;
});
it('should have add method', function() { |
71af45da5cdceb6e8e377ab2c3641b40dfb8c441 | src/utils.js | src/utils.js | export function extractAttributes(el) {
const map = el.hasAttributes() ? el.attributes : []
const attrs = {}
for (let i = 0; i < map.length; i++) {
const attr = map[i]
if (attr.value) {
attrs[attr.name] = attr.value === '' ? true : attr.value
}
}
let klass, style
if (attrs.class) {
klass = attrs.class
delete attrs.class
}
if (attrs.style) {
style = attrs.style
delete attrs.style
}
const data = {
attrs,
class: klass,
style,
}
return data
}
export function freeze(item) {
if (Array.isArray(item) || typeof item === 'object') {
return Object.freeze(item)
}
return item
}
export function combinePassengers(transports, slotProps = {}) {
return transports.reduce((passengers, transport) => {
let newPassengers = transport.passengers[0]
newPassengers =
typeof newPassengers === 'function'
? newPassengers(slotProps)
: newPassengers
return passengers.concat(newPassengers)
}, [])
}
| export function extractAttributes(el) {
const map = el.hasAttributes() ? el.attributes : []
const attrs = {}
for (let i = 0; i < map.length; i++) {
const attr = map[i]
if (attr.value) {
attrs[attr.name] = attr.value === '' ? true : attr.value
}
}
let klass, style
if (attrs.class) {
klass = attrs.class
delete attrs.class
}
if (attrs.style) {
style = attrs.style
delete attrs.style
}
const data = {
attrs,
class: klass,
style,
}
return data
}
export function freeze(item) {
if (Array.isArray(item) || typeof item === 'object') {
return Object.freeze(item)
}
return item
}
export function combinePassengers(transports, slotProps = {}) {
return transports.reduce((passengers, transport) => {
let newPassengers = transport.passengers[0]
newPassengers =
typeof newPassengers === 'function'
? newPassengers(slotProps)
: transport.passengers
return passengers.concat(newPassengers)
}, [])
}
| Fix bug wher only one element was returned | Fix bug wher only one element was returned
| JavaScript | mit | LinusBorg/portal-vue,LinusBorg/portal-vue,LinusBorg/portal-vue | ---
+++
@@ -37,7 +37,7 @@
newPassengers =
typeof newPassengers === 'function'
? newPassengers(slotProps)
- : newPassengers
+ : transport.passengers
return passengers.concat(newPassengers)
}, [])
} |
636863f5b8fcff8e7cfc000349f5167b51b9544c | public/app/routes/application.js | public/app/routes/application.js | /*
Copyright, 2013, by Tomas Korcak. <korczis@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
(function (global) {
require
(
["ember", "app"], function (Ember, App) {
App.ApplicationRoute = Ember.Route.extend({
title: "Microscratch",
model: function() {
},
setupController: function(controller, model) {
}
});
App.ApplicationController = Ember.Controller.extend({
});
App.ApplicationView = Ember.View.extend({
classNames: ['app-view'],
templateName: "application",
/**
* Called when inserted to DOM.
* @memberof Application.ApplicationView
* @instance
*/
didInsertElement: function () {
console.log("App.ApplicationView.didInsertElement()");
}
});
}
);
})(this); | /*
Copyright, 2013, by Tomas Korcak. <korczis@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
(function (global) {
require
(
["ember", "app"], function (Ember, App) {
App.ApplicationView = Ember.View.extend({
classNames: ['app-view'],
templateName: "application",
/**
* Called when inserted to DOM.
* @memberof Application.ApplicationView
* @instance
*/
didInsertElement: function () {
console.log("App.ApplicationView.didInsertElement()");
}
});
}
);
})(this); | Remove empty route and controller | Remove empty route and controller
| JavaScript | mit | pavelbinar/craftsmen,zadr007/BLUEjs,pavelbinar/craftsmen,zadr007/BLUEjs | ---
+++
@@ -25,19 +25,6 @@
(
["ember", "app"], function (Ember, App) {
- App.ApplicationRoute = Ember.Route.extend({
- title: "Microscratch",
-
- model: function() {
- },
-
- setupController: function(controller, model) {
- }
- });
-
- App.ApplicationController = Ember.Controller.extend({
- });
-
App.ApplicationView = Ember.View.extend({
classNames: ['app-view'],
templateName: "application", |
dfeb8dba44275fc6ac317a862376e8ab0c2f5a8c | lib/routes/admin/index.js | lib/routes/admin/index.js | 'use strict';
var express = require('express');
module.exports = function buildAdminRouter(mediator) {
var router = express.Router();
// TODO: Remove this endpoint when not needed
if (process.env.NODE_ENV !== 'production') {
/**
* Asks for data to be reset to the default list of users
* This is intended only for demonstration/debugging purposes
* and by default only runs on NODE_ENV === 'development'
*/
require('./addResetEndpoint')(router, mediator);
}
return router;
}; | 'use strict';
var express = require('express');
module.exports = function buildAdminRouter(mediator) {
var router = express.Router();
/**
* Asks for data to be reset to the default list of users
* This is intended only for demonstration/debugging purposes.
* TODO: Remove this endpoint in production or when not needed
*/
require('./addResetEndpoint')(router, mediator);
return router;
}; | Remove check for environment to add data reset endpoint | Remove check for environment to add data reset endpoint
| JavaScript | mit | feedhenry-raincatcher/raincatcher-demo-auth | ---
+++
@@ -4,15 +4,12 @@
module.exports = function buildAdminRouter(mediator) {
var router = express.Router();
- // TODO: Remove this endpoint when not needed
- if (process.env.NODE_ENV !== 'production') {
- /**
- * Asks for data to be reset to the default list of users
- * This is intended only for demonstration/debugging purposes
- * and by default only runs on NODE_ENV === 'development'
- */
- require('./addResetEndpoint')(router, mediator);
- }
+ /**
+ * Asks for data to be reset to the default list of users
+ * This is intended only for demonstration/debugging purposes.
+ * TODO: Remove this endpoint in production or when not needed
+ */
+ require('./addResetEndpoint')(router, mediator);
return router;
}; |
3844217c602b329d9a98a620de6576124f94c21b | test/init.js | test/init.js | global.assert = require('assert');
global.chai = require("chai");
global.chaiAsPromised = require("chai-as-promised");
global.jsf = require('json-schema-faker');
global.should = require('should');
global.sinon = require('sinon');
// Load schemas
global.mocks = require('./mocks');
// Run the tests
require('./unit');
| global.assert = require('assert');
global.chai = require("chai");
global.chaiAsPromised = require("chai-as-promised");
global.jsf = require('json-schema-faker');
global.should = require('should');
global.sinon = require('sinon');
global._ = require('lodash');
// Load schemas
global.mocks = require('./mocks');
// Run the tests
require('./unit');
| Add lodash access in global scope | Add lodash access in global scope
| JavaScript | mit | facundovictor/mocha-testing | ---
+++
@@ -4,6 +4,7 @@
global.jsf = require('json-schema-faker');
global.should = require('should');
global.sinon = require('sinon');
+global._ = require('lodash');
// Load schemas
global.mocks = require('./mocks'); |
945adf03719a67d7fe65b9dafcd6a1aa1fe31dcb | app/assets/javascripts/roots/application.js | app/assets/javascripts/roots/application.js | function clearAndHideResultTable() {
var header = $('table.matching-term .header');
$('table.matching-term').html(header);
$('table.matching-term').hide();
}
function hideNoResults() {
$('.no-results').hide();
}
function showNoResults() {
$('.no-results').show();
}
function showResultTable() {
hideNoResults();
$('table.matching-term').show();
}
function searchResults(query) {
clearAndHideResultTable();
var found = $('[data-search*=' + query).parent('tr');
return found;
}
function addToResultTable(result){
showResultTable();
var table = $('.matching-term');
var lastChild = table.find('tr:last');
if(lastChild.length == 0) {
table.html(result);
}
else {
lastChild.after(result);
}
}
$(document).on('ready', function(){
$('input[name=search]').keyup(function(event){
var searchTerm = event.target.value;
if(searchTerm.length > 0) {
hideNoResults();
var results = searchResults(searchTerm.toLowerCase());
if (results.length > 0) {
$.each(results, function(index, value){
addToResultTable($(value).clone());
});
}
else {
showNoResults();
}
}
else {
hideNoResults();
clearAndHideResultTable();
}
});
});
| DomElements = {
matchingTerm: 'table.matching-term'
};
function clearAndHideResultTable() {
var header = $('table.matching-term .header');
$(DomElements.matchingTerm).html(header);
$(DomElements.matchingTerm).hide();
}
function hideNoResults() {
$('.no-results').hide();
}
function showNoResults() {
$('.no-results').show();
}
function showResultTable() {
hideNoResults();
$(DomElements.matchingTerm).show();
}
function searchResults(query) {
clearAndHideResultTable();
var found = $('[data-search*=' + query).parent('tr');
return found;
}
function addToResultTable(result){
showResultTable();
var table = $('.matching-term');
var lastChild = table.find('tr:last');
if(lastChild.length == 0) {
table.html(result);
}
else {
lastChild.after(result);
}
}
$(document).on('ready', function(){
$('input[name=search]').keyup(function(event){
var searchTerm = event.target.value;
if(searchTerm.length > 0) {
hideNoResults();
var results = searchResults(searchTerm.toLowerCase());
if (results.length > 0) {
$.each(results, function(index, value){
addToResultTable($(value).clone());
});
}
else {
showNoResults();
}
}
else {
hideNoResults();
clearAndHideResultTable();
}
});
});
| Add JS lookup to object | Add JS lookup to object
| JavaScript | mit | yez/roots,yez/passages,yez/roots,yez/passages,yez/passages,yez/roots | ---
+++
@@ -1,7 +1,11 @@
+DomElements = {
+ matchingTerm: 'table.matching-term'
+};
+
function clearAndHideResultTable() {
var header = $('table.matching-term .header');
- $('table.matching-term').html(header);
- $('table.matching-term').hide();
+ $(DomElements.matchingTerm).html(header);
+ $(DomElements.matchingTerm).hide();
}
function hideNoResults() {
@@ -14,7 +18,7 @@
function showResultTable() {
hideNoResults();
- $('table.matching-term').show();
+ $(DomElements.matchingTerm).show();
}
function searchResults(query) { |
4d685b2ffe124c2b3e5b3a8187c4b31a56518c13 | packages/mendel-config/src/variation-config.js | packages/mendel-config/src/variation-config.js | const parseVariations = require('../variations');
const createValidator = require('./validator');
const validate = createValidator({
variations: {type: 'array', minLen: 1},
// There can be a user of Mendel who does not want variation but faster build.
allVariationDirs: {type: 'array', minLen: 0},
allDirs: {type: 'array', minLen: 1},
});
function VariationConfig(config) {
const variations = parseVariations(config);
const allVariationDirs = getAllDirs(variations);
const baseVariation = {
id: config.baseConfig.id,
chain: [config.baseConfig.dir],
};
variations.push(baseVariation);
const allDirs = getAllDirs(variations);
const variationConfig = {
variations,
baseVariation,
allDirs,
allVariationDirs,
};
validate(variationConfig);
return variationConfig;
}
function getAllDirs(variationArray) {
return variationArray.reduce((allDirs, variation) => {
variation.chain.forEach(dir => {
if (!allDirs.includes(dir)) allDirs.push(dir);
});
return allDirs;
}, []);
}
module.exports = VariationConfig;
| const parseVariations = require('../variations');
const createValidator = require('./validator');
const validate = createValidator({
variations: {type: 'array', minLen: 1},
// There can be a user of Mendel who does not want variation but faster build.
allVariationDirs: {type: 'array', minLen: 0},
allDirs: {type: 'array', minLen: 1},
});
function VariationConfig(config) {
const variations = parseVariations(config);
const allVariationDirs = getAllDirs(variations);
const baseVariation = {
id: config.baseConfig.id,
chain: [config.baseConfig.dir],
};
// base variation must come first in order to variationMatches to work
variations.unshift(baseVariation);
const allDirs = getAllDirs(variations);
const variationConfig = {
variations,
baseVariation,
allDirs,
allVariationDirs,
};
validate(variationConfig);
return variationConfig;
}
function getAllDirs(variationArray) {
return variationArray.reduce((allDirs, variation) => {
variation.chain.forEach(dir => {
if (!allDirs.includes(dir)) allDirs.push(dir);
});
return allDirs;
}, []);
}
module.exports = VariationConfig;
| Fix base files identified as wrong variation | Fix base files identified as wrong variation
| JavaScript | mit | stephanwlee/mendel,yahoo/mendel,stephanwlee/mendel,yahoo/mendel | ---
+++
@@ -15,7 +15,8 @@
id: config.baseConfig.id,
chain: [config.baseConfig.dir],
};
- variations.push(baseVariation);
+ // base variation must come first in order to variationMatches to work
+ variations.unshift(baseVariation);
const allDirs = getAllDirs(variations);
const variationConfig = { |
0032944eb5893cc732dac3df20a7617f75a027c5 | test/data/sizzle-jquery.js | test/data/sizzle-jquery.js | jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.getText = getText;
jQuery.isXMLDoc = isXML;
jQuery.contains = contains;
| jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
| Make sure that we're not trying to pull in things that don't exist, durr. | Make sure that we're not trying to pull in things that don't exist, durr.
| JavaScript | mit | npmcomponent/cristiandouce-sizzle,mzgol/sizzle | ---
+++
@@ -2,6 +2,3 @@
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
-jQuery.getText = getText;
-jQuery.isXMLDoc = isXML;
-jQuery.contains = contains; |
7d59ca5060f2904df9dcecfccaa6aef53a4137e4 | tests/acceptance/create-new-object-test.js | tests/acceptance/create-new-object-test.js | import { test } from 'qunit';
import moduleForAcceptance from 'dw-collections-manager/tests/helpers/module-for-acceptance';
moduleForAcceptance('Acceptance | create new object');
test('visiting /create-new-object', function(assert) {
visit('/collectionobject/new');
andThen(function() {
assert.equal(currentURL(), '/collectionobject/new');
});
});
| import { test } from 'qunit';
import moduleForAcceptance from 'dw-collections-manager/tests/helpers/module-for-acceptance';
moduleForAcceptance('Acceptance | create new object');
test('visiting /create-new-object', function(assert) {
/*visit('/collectionobject/new');
andThen(function() {
assert.equal(currentURL(), '/collectionobject/new');
});*/
assert.equal('', '');
});
| Update acceptance test to dummy test | Update acceptance test to dummy test
See if it solves issue on Travis
| JavaScript | agpl-3.0 | DINA-Web/collections-ui,DINA-Web/collections-ui,DINA-Web/collections-ui | ---
+++
@@ -4,9 +4,11 @@
moduleForAcceptance('Acceptance | create new object');
test('visiting /create-new-object', function(assert) {
- visit('/collectionobject/new');
+ /*visit('/collectionobject/new');
andThen(function() {
assert.equal(currentURL(), '/collectionobject/new');
- });
+ });*/
+
+ assert.equal('', '');
}); |
abebd9262957895a20c96fb83c322b7f5988a4ec | assets/js/components/autocomplete-email.js | assets/js/components/autocomplete-email.js | KB.onClick('.js-autocomplete-email', function (e) {
var email = KB.dom(e.target).data('email');
var emailField = KB.find('.js-mail-form input[type="email"]');
if (email && emailField) {
emailField.build().value = email;
}
_KB.controllers['Dropdown'].close();
});
KB.onClick('.js-autocomplete-subject', function (e) {
var subject = KB.dom(e.target).data('subject');
var subjectField = KB.find('.js-mail-form input[name="subject"]');
if (subject && subjectField) {
subjectField.build().value = subject;
}
_KB.controllers['Dropdown'].close();
});
| KB.onClick('.js-autocomplete-email', function (e) {
var email = KB.dom(e.target).data('email');
var emailField = KB.find('.js-mail-form input[type="email"]');
if (email && emailField) {
emailField.build().value = email;
}
_KB.controllers.Dropdown.close();
});
KB.onClick('.js-autocomplete-subject', function (e) {
var subject = KB.dom(e.target).data('subject');
var subjectField = KB.find('.js-mail-form input[name="subject"]');
if (subject && subjectField) {
subjectField.build().value = subject;
}
_KB.controllers.Dropdown.close();
});
| Use dot notation in Javascript component | Use dot notation in Javascript component
| JavaScript | mit | libin/kanboard,fguillot/kanboard,stinnux/kanboard,kanboard/kanboard,filhocf/kanboard,renothing/kanboard,BlueTeck/kanboard,stinnux/kanboard,oliviermaridat/kanboard,oliviermaridat/kanboard,thylo/kanboard,Busfreak/kanboard,Busfreak/kanboard,BlueTeck/kanboard,kanboard/kanboard,fguillot/kanboard,renothing/kanboard,thylo/kanboard,filhocf/kanboard,Busfreak/kanboard,thylo/kanboard,oliviermaridat/kanboard,kanboard/kanboard,BlueTeck/kanboard,libin/kanboard,renothing/kanboard,fguillot/kanboard,stinnux/kanboard,filhocf/kanboard | ---
+++
@@ -6,7 +6,7 @@
emailField.build().value = email;
}
- _KB.controllers['Dropdown'].close();
+ _KB.controllers.Dropdown.close();
});
KB.onClick('.js-autocomplete-subject', function (e) {
@@ -17,5 +17,5 @@
subjectField.build().value = subject;
}
- _KB.controllers['Dropdown'].close();
+ _KB.controllers.Dropdown.close();
}); |
4aa5e42ee2e6ce50489f03eb057021ec4087e1ad | packages/easysearch:elasticsearch/package.js | packages/easysearch:elasticsearch/package.js | Package.describe({
name: 'easysearch:elasticsearch',
summary: "Elasticsearch Engine for EasySearch",
version: "2.1.1",
git: "https://github.com/matteodem/meteor-easy-search.git",
documentation: 'README.md'
});
Npm.depends({
'elasticsearch': '8.2.0'
});
Package.onUse(function(api) {
api.versionsFrom('1.4.2');
// Dependencies
api.use(['check', 'ecmascript']);
api.use(['easysearch:core@2.1.0', 'erasaur:meteor-lodash@4.0.0']);
api.addFiles([
'lib/data-syncer.js',
'lib/engine.js',
]);
api.export('EasySearch');
api.mainModule('./lib/main.js');
});
Package.onTest(function(api) {
api.use(['tinytest', 'ecmascript']);
api.use('easysearch:elasticsearch');
api.addFiles(['tests/engine-tests.js']);
});
| Package.describe({
name: 'easysearch:elasticsearch',
summary: "Elasticsearch Engine for EasySearch",
version: "2.1.1",
git: "https://github.com/matteodem/meteor-easy-search.git",
documentation: 'README.md'
});
Npm.depends({
'elasticsearch': '13.0.0'
});
Package.onUse(function(api) {
api.versionsFrom('1.4.2');
// Dependencies
api.use(['check', 'ecmascript']);
api.use(['easysearch:core@2.1.0', 'erasaur:meteor-lodash@4.0.0']);
api.addFiles([
'lib/data-syncer.js',
'lib/engine.js',
]);
api.export('EasySearch');
api.mainModule('./lib/main.js');
});
Package.onTest(function(api) {
api.use(['tinytest', 'ecmascript']);
api.use('easysearch:elasticsearch');
api.addFiles(['tests/engine-tests.js']);
});
| Update ES client to support ES 5.x | Update ES client to support ES 5.x
| JavaScript | mit | bompi88/meteor-easy-search,matteodem/meteor-easy-search,bompi88/meteor-easy-search,matteodem/meteor-easy-search,bompi88/meteor-easy-search,matteodem/meteor-easy-search | ---
+++
@@ -7,7 +7,7 @@
});
Npm.depends({
- 'elasticsearch': '8.2.0'
+ 'elasticsearch': '13.0.0'
});
Package.onUse(function(api) { |
5900f04399c512ff05eb5eb81fa026ce67e32371 | packages/ember-testing/lib/adapters/qunit.js | packages/ember-testing/lib/adapters/qunit.js | import Adapter from './adapter';
import { inspect } from 'ember-metal';
/**
This class implements the methods defined by Ember.Test.Adapter for the
QUnit testing framework.
@class QUnitAdapter
@namespace Ember.Test
@extends Ember.Test.Adapter
@public
*/
export default Adapter.extend({
asyncStart() {
QUnit.stop();
},
asyncEnd() {
QUnit.start();
},
exception(error) {
ok(false, inspect(error));
}
});
| import { inspect } from 'ember-utils';
import Adapter from './adapter';
/**
This class implements the methods defined by Ember.Test.Adapter for the
QUnit testing framework.
@class QUnitAdapter
@namespace Ember.Test
@extends Ember.Test.Adapter
@public
*/
export default Adapter.extend({
asyncStart() {
QUnit.stop();
},
asyncEnd() {
QUnit.start();
},
exception(error) {
ok(false, inspect(error));
}
});
| Refactor ember-utils imports in ember-testing package. | Refactor ember-utils imports in ember-testing package.
| JavaScript | mit | fpauser/ember.js,qaiken/ember.js,rlugojr/ember.js,miguelcobain/ember.js,miguelcobain/ember.js,jasonmit/ember.js,bekzod/ember.js,tsing80/ember.js,karthiick/ember.js,Leooo/ember.js,givanse/ember.js,pixelhandler/ember.js,sivakumar-kailasam/ember.js,jaswilli/ember.js,Turbo87/ember.js,xiujunma/ember.js,cibernox/ember.js,sandstrom/ember.js,Serabe/ember.js,alexdiliberto/ember.js,jherdman/ember.js,mike-north/ember.js,workmanw/ember.js,csantero/ember.js,Leooo/ember.js,thoov/ember.js,tsing80/ember.js,knownasilya/ember.js,thoov/ember.js,chadhietala/ember.js,jherdman/ember.js,chadhietala/ember.js,asakusuma/ember.js,mfeckie/ember.js,duggiefresh/ember.js,cibernox/ember.js,pixelhandler/ember.js,csantero/ember.js,bekzod/ember.js,rlugojr/ember.js,jasonmit/ember.js,sivakumar-kailasam/ember.js,thoov/ember.js,HeroicEric/ember.js,gfvcastro/ember.js,GavinJoyce/ember.js,runspired/ember.js,stefanpenner/ember.js,Gaurav0/ember.js,karthiick/ember.js,mfeckie/ember.js,kennethdavidbuck/ember.js,patricksrobertson/ember.js,mixonic/ember.js,pixelhandler/ember.js,kaeufl/ember.js,pixelhandler/ember.js,xiujunma/ember.js,alexdiliberto/ember.js,Serabe/ember.js,workmanw/ember.js,bantic/ember.js,givanse/ember.js,intercom/ember.js,Leooo/ember.js,jaswilli/ember.js,gfvcastro/ember.js,Serabe/ember.js,kellyselden/ember.js,kaeufl/ember.js,tildeio/ember.js,davidpett/ember.js,givanse/ember.js,karthiick/ember.js,kanongil/ember.js,szines/ember.js,mike-north/ember.js,karthiick/ember.js,runspired/ember.js,cbou/ember.js,kellyselden/ember.js,kaeufl/ember.js,jherdman/ember.js,rfsv/ember.js,rfsv/ember.js,davidpett/ember.js,jaswilli/ember.js,Turbo87/ember.js,miguelcobain/ember.js,kennethdavidbuck/ember.js,jasonmit/ember.js,GavinJoyce/ember.js,chadhietala/ember.js,amk221/ember.js,kellyselden/ember.js,twokul/ember.js,kennethdavidbuck/ember.js,runspired/ember.js,sivakumar-kailasam/ember.js,stefanpenner/ember.js,cbou/ember.js,amk221/ember.js,qaiken/ember.js,Turbo87/ember.js,qaiken/ember.js,johanneswuerbach/ember.js,Gaurav0/ember.js,sly7-7/ember.js,Patsy-issa/ember.js,cibernox/ember.js,HeroicEric/ember.js,emberjs/ember.js,alexdiliberto/ember.js,bantic/ember.js,rfsv/ember.js,tildeio/ember.js,sly7-7/ember.js,kellyselden/ember.js,amk221/ember.js,johanneswuerbach/ember.js,miguelcobain/ember.js,trentmwillis/ember.js,szines/ember.js,knownasilya/ember.js,sandstrom/ember.js,trentmwillis/ember.js,duggiefresh/ember.js,fpauser/ember.js,fpauser/ember.js,csantero/ember.js,gfvcastro/ember.js,tsing80/ember.js,amk221/ember.js,cbou/ember.js,mike-north/ember.js,Turbo87/ember.js,trentmwillis/ember.js,qaiken/ember.js,tildeio/ember.js,bantic/ember.js,Leooo/ember.js,Patsy-issa/ember.js,kanongil/ember.js,HeroicEric/ember.js,johanneswuerbach/ember.js,szines/ember.js,csantero/ember.js,HeroicEric/ember.js,mfeckie/ember.js,fpauser/ember.js,alexdiliberto/ember.js,bantic/ember.js,patricksrobertson/ember.js,trentmwillis/ember.js,davidpett/ember.js,xiujunma/ember.js,thoov/ember.js,nickiaconis/ember.js,Gaurav0/ember.js,Gaurav0/ember.js,tsing80/ember.js,Patsy-issa/ember.js,patricksrobertson/ember.js,sly7-7/ember.js,emberjs/ember.js,patricksrobertson/ember.js,cbou/ember.js,rlugojr/ember.js,GavinJoyce/ember.js,johanneswuerbach/ember.js,nickiaconis/ember.js,knownasilya/ember.js,workmanw/ember.js,workmanw/ember.js,szines/ember.js,bekzod/ember.js,intercom/ember.js,Patsy-issa/ember.js,sivakumar-kailasam/ember.js,mfeckie/ember.js,sivakumar-kailasam/ember.js,davidpett/ember.js,Serabe/ember.js,mike-north/ember.js,jherdman/ember.js,chadhietala/ember.js,duggiefresh/ember.js,kaeufl/ember.js,jasonmit/ember.js,kennethdavidbuck/ember.js,xiujunma/ember.js,cibernox/ember.js,rlugojr/ember.js,jasonmit/ember.js,sandstrom/ember.js,elwayman02/ember.js,kanongil/ember.js,runspired/ember.js,intercom/ember.js,mixonic/ember.js,kanongil/ember.js,twokul/ember.js,GavinJoyce/ember.js,elwayman02/ember.js,asakusuma/ember.js,elwayman02/ember.js,twokul/ember.js,gfvcastro/ember.js,elwayman02/ember.js,twokul/ember.js,jaswilli/ember.js,nickiaconis/ember.js,givanse/ember.js,bekzod/ember.js,rfsv/ember.js,mixonic/ember.js,intercom/ember.js,asakusuma/ember.js,nickiaconis/ember.js,stefanpenner/ember.js,asakusuma/ember.js,duggiefresh/ember.js,emberjs/ember.js | ---
+++
@@ -1,5 +1,5 @@
+import { inspect } from 'ember-utils';
import Adapter from './adapter';
-import { inspect } from 'ember-metal';
/**
This class implements the methods defined by Ember.Test.Adapter for the |
07028ebddcd609b2f468cbd9a3cded102e33204c | client/apis.js | client/apis.js | const API_URL = process.env.API_URL
export default {
GET_TOP_GAMES : () => `${API_URL}/gamess`,
GET_PRICES : appIds => `${API_URL}/games/prices?appIds=${appIds}`,
GET_SUGGESTIONS: name => `${API_URL}/games/suggestions?name=${name}`,
SEARCH_GAMES : name => `${API_URL}/games/search?name=${name}`,
GET_RATES : () => `${API_URL}/rates`
}
| const API_URL = process.env.API_URL
export default {
GET_TOP_GAMES : () => `${API_URL}/games`,
GET_PRICES : appIds => `${API_URL}/games/prices?appIds=${appIds}`,
GET_SUGGESTIONS: name => `${API_URL}/games/suggestions?name=${name}`,
SEARCH_GAMES : name => `${API_URL}/games/search?name=${name}`,
GET_RATES : () => `${API_URL}/rates`
}
| Fix wrong api for games list | Fix wrong api for games list
| JavaScript | mit | hckhanh/games-searcher,hckhanh/games-searcher | ---
+++
@@ -1,7 +1,7 @@
const API_URL = process.env.API_URL
export default {
- GET_TOP_GAMES : () => `${API_URL}/gamess`,
+ GET_TOP_GAMES : () => `${API_URL}/games`,
GET_PRICES : appIds => `${API_URL}/games/prices?appIds=${appIds}`,
GET_SUGGESTIONS: name => `${API_URL}/games/suggestions?name=${name}`,
SEARCH_GAMES : name => `${API_URL}/games/search?name=${name}`, |
24add3a270d101903a573ccd08b70112502c5eea | test/js/properties-test.js | test/js/properties-test.js | module("Text Descendant", {
});
test("Find text descendants in an iframe.", function() {
// Setup fixture
var fixture = document.getElementById('qunit-fixture');
var iframe = document.createElement('iframe');
var html = '<body><div id="foo">bar</div></body>';
fixture.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();
var foo = iframe.contentDocument.getElementById("foo");
equal(axs.properties.hasDirectTextDescendant(foo), true);
});
| module("Text Descendant", {
});
test("Find text descendants in an iframe.", function() {
// Setup fixture
var fixture = document.getElementById('qunit-fixture');
var iframe = document.createElement('iframe');
var html = '<body><div id="foo">bar</div></body>';
fixture.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();
var foo = iframe.contentDocument.getElementById("foo");
equal(axs.properties.hasDirectTextDescendant(foo), true);
});
module("findTextAlternatives", {
setup: function () {
this.fixture_ = document.getElementById('qunit-fixture');
}
});
test("returns the selector text for a nested object with a class attribute", function() {
var targetNode = document.createElement('select');
this.fixture_.appendChild(targetNode);
try {
equal(axs.properties.findTextAlternatives(targetNode, {}, true), "");
return ok(true);
} catch( e ) {
return ok(false, "Threw exception");
}
});
| Test that findTextAlternatives does not raise errors | Test that findTextAlternatives does not raise errors
| JavaScript | apache-2.0 | kristapsmelderis/accessibility-developer-tools,garcialo/accessibility-developer-tools,ckundo/accessibility-developer-tools,japacible/accessibility-developer-tools,GabrielDuque/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools,ckundo/accessibility-developer-tools,t9nf/accessibility-developer-tools,kristapsmelderis/accessibility-developer-tools,GabrielDuque/accessibility-developer-tools,pivotal-cf/accessibility-developer-tools,japacible/accessibility-developer-tools,garcialo/accessibility-developer-tools,kristapsmelderis/accessibility-developer-tools,garcialo/accessibility-developer-tools,t9nf/accessibility-developer-tools,GabrielDuque/accessibility-developer-tools,t9nf/accessibility-developer-tools,pivotal-cf/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools,Khan/accessibility-developer-tools,modulexcite/accessibility-developer-tools,seksanman/accessibility-developer-tools,kublaj/accessibility-developer-tools,ricksbrown/accessibility-developer-tools,kublaj/accessibility-developer-tools,kublaj/accessibility-developer-tools,Khan/accessibility-developer-tools,modulexcite/accessibility-developer-tools,hmrc/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools,ricksbrown/accessibility-developer-tools,japacible/accessibility-developer-tools,ricksbrown/accessibility-developer-tools,ckundo/accessibility-developer-tools,Khan/accessibility-developer-tools,hmrc/accessibility-developer-tools,alice/accessibility-developer-tools,alice/accessibility-developer-tools,modulexcite/accessibility-developer-tools,pivotal-cf/accessibility-developer-tools,seksanman/accessibility-developer-tools,seksanman/accessibility-developer-tools,hmrc/accessibility-developer-tools,alice/accessibility-developer-tools | ---
+++
@@ -16,3 +16,20 @@
equal(axs.properties.hasDirectTextDescendant(foo), true);
});
+
+module("findTextAlternatives", {
+ setup: function () {
+ this.fixture_ = document.getElementById('qunit-fixture');
+ }
+});
+test("returns the selector text for a nested object with a class attribute", function() {
+ var targetNode = document.createElement('select');
+ this.fixture_.appendChild(targetNode);
+
+ try {
+ equal(axs.properties.findTextAlternatives(targetNode, {}, true), "");
+ return ok(true);
+ } catch( e ) {
+ return ok(false, "Threw exception");
+ }
+}); |
4a2f24d114a0239092d705ba96fdc7b9094e8753 | client/main.js | client/main.js | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import 'reflect-metadata'; // here location matters: has to be before import of AppModule
import { AppModule } from './imports/components/app.module';
import 'zone.js'; // here location matters: has to be after import of AppModule
// Note: this import loads 'zone.js' itself but also 'long-stack-trace-zone'
platformBrowserDynamic().bootstrapModule(AppModule)
.then((ref) => console.log("App is running"))
.catch((err) => console.error(err));
| import 'reflect-metadata'; // here location matters: has to be before import of AppModule
// and even before other imports under Windows
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './imports/components/app.module';
import 'zone.js'; // here location matters: has to be after import of AppModule
// Note: this import loads 'zone.js' itself but also 'long-stack-trace-zone'
platformBrowserDynamic().bootstrapModule(AppModule)
.then((ref) => console.log("App is running"))
.catch((err) => console.error(err));
| Move import 'reflect-metadata' before other ones. | Move import 'reflect-metadata' before other ones.
| JavaScript | mit | atao60/meteor-angular4-scss,atao60/meteor-angular4-scss | ---
+++
@@ -1,6 +1,7 @@
+import 'reflect-metadata'; // here location matters: has to be before import of AppModule
+ // and even before other imports under Windows
+
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
-
-import 'reflect-metadata'; // here location matters: has to be before import of AppModule
import { AppModule } from './imports/components/app.module';
|
bc62204ebf9a5c584210d354c78ddae1b9384c73 | demo/UserDAO.js | demo/UserDAO.js | "use strict";
var loki = require('lokijs');
var _ = require('lodash');
var Q = require('q');
// variable to hold the singleton instance, if used in that manner
var userDAOInstance = undefined;
//
// User Data Access Object
//
// Constructor
function UserDAO(dbName) {
// Define database name
dbName = (dbName != '') ? dbName : 'janux.people.db';
// Create db
this._db = new loki(dbName);
// Add users collection
this._users = this._db.addCollection('users');
}
// Get User Object by id
UserDAO.prototype.getUserById = function (userId, callback) {
return Q.when( this._users.findOne( { userId:userId } ) );
};
// Get User Object by username
UserDAO.prototype.getUserByName = function (userName) {
return Q.when( this._users.findOne( { username:userName } ) );
};
// Add new User Object
UserDAO.prototype.addUser = function (aUserObj) {
this._users.insert(aUserObj);
};
exports.createInstance = function() {
return new UserDAO();
};
exports.singleton = function() {
// if the singleton has not yet been instantiated, do so
if ( !_.isObject(userDAOInstance) ) {
userDAOInstance = new UserDAO();
}
return userDAOInstance;
}; | "use strict";
var loki = require('lokijs');
var _ = require('lodash');
var Promise = require('bluebird');
// variable to hold the singleton instance, if used in that manner
var userDAOInstance = undefined;
//
// User Data Access Object
//
// Constructor
function UserDAO(dbName) {
// Define database name
dbName = (dbName != '') ? dbName : 'janux.people.db';
// Create db
this._db = new loki(dbName);
// Add users collection
this._users = this._db.addCollection('users');
}
// Get User Object by id
UserDAO.prototype.findUserById = function (userId, callback) {
var users = this._users.findOne( { userId:userId });
return new Promise(function(resolve){
resolve( users );
}).asCallback(callback);
};
// Get User Object by username
UserDAO.prototype.findUserByName = function (userName, callback) {
var users = this._users.findOne( { username:userName } );
return new Promise(function(resolve){
resolve( users );
}).asCallback(callback);
};
// Add new User Object
UserDAO.prototype.addUser = function (aUserObj) {
this._users.insert(aUserObj);
};
exports.createInstance = function() {
return new UserDAO();
};
exports.singleton = function() {
// if the singleton has not yet been instantiated, do so
if ( !_.isObject(userDAOInstance) ) {
userDAOInstance = new UserDAO();
}
return userDAOInstance;
}; | Implement bluebird instead of Q inside demo userDAO | Implement bluebird instead of Q inside demo userDAO
| JavaScript | mit | janux/janux-people.js,janux/janux-people.js | ---
+++
@@ -2,7 +2,7 @@
var loki = require('lokijs');
var _ = require('lodash');
-var Q = require('q');
+var Promise = require('bluebird');
// variable to hold the singleton instance, if used in that manner
var userDAOInstance = undefined;
@@ -22,13 +22,21 @@
}
// Get User Object by id
-UserDAO.prototype.getUserById = function (userId, callback) {
- return Q.when( this._users.findOne( { userId:userId } ) );
+UserDAO.prototype.findUserById = function (userId, callback) {
+
+ var users = this._users.findOne( { userId:userId });
+ return new Promise(function(resolve){
+ resolve( users );
+ }).asCallback(callback);
};
// Get User Object by username
-UserDAO.prototype.getUserByName = function (userName) {
- return Q.when( this._users.findOne( { username:userName } ) );
+UserDAO.prototype.findUserByName = function (userName, callback) {
+
+ var users = this._users.findOne( { username:userName } );
+ return new Promise(function(resolve){
+ resolve( users );
+ }).asCallback(callback);
};
// Add new User Object |
b230495ada24758b67134011385c47fb9e33cec2 | public/js/cookie-message.js | public/js/cookie-message.js | /* global document */
function setCookie(name, value, options = {}) {
let cookieString = `${name}=${value}; path=/`;
if (options.days) {
const date = new Date();
date.setTime(date.getTime() + (options.days * 24 * 60 * 60 * 1000));
cookieString = `${cookieString}; expires=${date.toGMTString()}`;
}
if (document.location.protocol === 'https:') {
cookieString = `${cookieString}; Secure`;
}
document.cookie = cookieString;
}
function getCookie(name) {
const nameEQ = `${name}=`;
const cookies = document.cookie.split(';');
for (let i = 0, len = cookies.length; i < len; i++) {
let cookie = cookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return decodeURIComponent(cookie.substring(nameEQ.length));
}
}
return null;
}
$(function() {
const banner = document.getElementById('global-cookies-banner');
if (banner && getCookie('nhsuk_seen_cookie_message') === null) {
banner.style.display = 'block';
setCookie('nhsuk_seen_cookie_message', 'yes', { days: 28 });
}
});
| (function(global) {
'use strict'
var $ = global.jQuery;
var document = global.document;
function setCookie(name, value, options) {
options = options || {};
var cookieString = name + '=' + value + '; path=/';
if (options.days) {
var date = new Date();
date.setTime(date.getTime() + (options.days * 24 * 60 * 60 * 1000));
cookieString = cookieString + '; expires=' + date.toGMTString();
}
if (document.location.protocol === 'https:') {
cookieString = cookieString + '; Secure';
}
document.cookie = cookieString;
}
function getCookie(name) {
var nameEQ = name + '=';
var cookies = document.cookie.split(';');
for (var i = 0, len = cookies.length; i < len; i++) {
var cookie = cookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return decodeURIComponent(cookie.substring(nameEQ.length));
}
}
return null;
}
$(function() {
var banner = document.getElementById('global-cookies-banner');
if (banner && getCookie('nhsuk_seen_cookie_message') === null) {
banner.style.display = 'block';
setCookie('nhsuk_seen_cookie_message', 'yes', { days: 28 });
}
});
})(window);
| Update script to be IE7+ compatible | :cookie: Update script to be IE7+ compatible
| JavaScript | mit | nhsuk/gp-finder,nhsuk/gp-finder | ---
+++
@@ -1,44 +1,50 @@
-/* global document */
-function setCookie(name, value, options = {}) {
- let cookieString = `${name}=${value}; path=/`;
+(function(global) {
+ 'use strict'
+ var $ = global.jQuery;
+ var document = global.document;
- if (options.days) {
- const date = new Date();
- date.setTime(date.getTime() + (options.days * 24 * 60 * 60 * 1000));
- cookieString = `${cookieString}; expires=${date.toGMTString()}`;
+ function setCookie(name, value, options) {
+ options = options || {};
+ var cookieString = name + '=' + value + '; path=/';
+
+ if (options.days) {
+ var date = new Date();
+ date.setTime(date.getTime() + (options.days * 24 * 60 * 60 * 1000));
+ cookieString = cookieString + '; expires=' + date.toGMTString();
+ }
+
+ if (document.location.protocol === 'https:') {
+ cookieString = cookieString + '; Secure';
+ }
+
+ document.cookie = cookieString;
}
- if (document.location.protocol === 'https:') {
- cookieString = `${cookieString}; Secure`;
+ function getCookie(name) {
+ var nameEQ = name + '=';
+ var cookies = document.cookie.split(';');
+
+ for (var i = 0, len = cookies.length; i < len; i++) {
+ var cookie = cookies[i];
+
+ while (cookie.charAt(0) === ' ') {
+ cookie = cookie.substring(1, cookie.length);
+ }
+
+ if (cookie.indexOf(nameEQ) === 0) {
+ return decodeURIComponent(cookie.substring(nameEQ.length));
+ }
+ }
+
+ return null;
}
- document.cookie = cookieString;
-}
+ $(function() {
+ var banner = document.getElementById('global-cookies-banner');
-function getCookie(name) {
- const nameEQ = `${name}=`;
- const cookies = document.cookie.split(';');
-
- for (let i = 0, len = cookies.length; i < len; i++) {
- let cookie = cookies[i];
-
- while (cookie.charAt(0) === ' ') {
- cookie = cookie.substring(1, cookie.length);
+ if (banner && getCookie('nhsuk_seen_cookie_message') === null) {
+ banner.style.display = 'block';
+ setCookie('nhsuk_seen_cookie_message', 'yes', { days: 28 });
}
-
- if (cookie.indexOf(nameEQ) === 0) {
- return decodeURIComponent(cookie.substring(nameEQ.length));
- }
- }
-
- return null;
-}
-
-$(function() {
- const banner = document.getElementById('global-cookies-banner');
-
- if (banner && getCookie('nhsuk_seen_cookie_message') === null) {
- banner.style.display = 'block';
- setCookie('nhsuk_seen_cookie_message', 'yes', { days: 28 });
- }
-});
+ });
+})(window); |
86341bb10069eab5f014200d541e03cedf3226bb | __tests__/transform.spec.js | __tests__/transform.spec.js | /* global describe, it, expect */
import { filterByKeys, transform } from '../src/transform'
import * as mocks from './mocks'
describe('Transform suite', () => {
it('should filter by keys two objects', () => {
const keys = Object.keys(mocks.defs.simple)
expect(filterByKeys(keys, mocks.defs.complex)).toEqual(mocks.defs.simple)
})
it('should transform a definition into a fulfilled object', () => {
expect(transform(mocks.defs.simple, mocks.fulfilled)).toEqual(mocks.fulfilled)
})
it('should transform a definition using mutators', () => {
expect(transform(mocks.defs.simple, mocks.fulfilled, mocks.mutators)).toMatchSnapshot()
})
it('should be able to define agent mutators', () => {
transform.mutators = { foo: 'bar' }
expect(transform(mocks.defs.simple, mocks.fulfilled)).toMatchSnapshot()
})
})
| /* global describe, it, expect */
import { filterByKeys, transform } from '../src/transform'
import * as mocks from './mocks'
describe('Transform suite', () => {
const keys = Object.keys(mocks.defs.simple)
it('should filter by keys two objects', () => {
expect(filterByKeys(keys, mocks.defs.complex)).toEqual(mocks.defs.simple)
})
it('should transform a definition into a fulfilled object', () => {
expect(transform(mocks.defs.simple, mocks.fulfilled)).toEqual(mocks.fulfilled)
})
it('should transform a definition using mutators', () => {
expect(transform(mocks.defs.simple, mocks.fulfilled, mocks.mutators)).toMatchSnapshot()
})
it('should be able to define agent mutators', () => {
const mutator = { foo: 'bar' }
transform.mutators = mutator
expect(transform(mocks.defs.simple, mocks.fulfilled)).toMatchSnapshot()
expect(transform.mutators).toEqual(mutator)
})
it('should be able to define keys declaratively', () => {
transform.keys = keys
expect(transform.keys).toEqual(keys)
})
})
| Check transform definitions are well set | test: Check transform definitions are well set
| JavaScript | mit | sospedra/schemative | ---
+++
@@ -3,8 +3,9 @@
import * as mocks from './mocks'
describe('Transform suite', () => {
+ const keys = Object.keys(mocks.defs.simple)
+
it('should filter by keys two objects', () => {
- const keys = Object.keys(mocks.defs.simple)
expect(filterByKeys(keys, mocks.defs.complex)).toEqual(mocks.defs.simple)
})
@@ -17,7 +18,15 @@
})
it('should be able to define agent mutators', () => {
- transform.mutators = { foo: 'bar' }
+ const mutator = { foo: 'bar' }
+ transform.mutators = mutator
+
expect(transform(mocks.defs.simple, mocks.fulfilled)).toMatchSnapshot()
+ expect(transform.mutators).toEqual(mutator)
+ })
+
+ it('should be able to define keys declaratively', () => {
+ transform.keys = keys
+ expect(transform.keys).toEqual(keys)
})
}) |
afb5fb554cc50ac5bece3d1a56877fc2606f9d81 | app/app.js | app/app.js | var app = require('app');
var BrowserWindow = require('browser-window');
var mainWindow = null;
app.on('window-all-closed', function() {
app.quit();
});
app.on('ready', function() {
mainWindow = new BrowserWindow({
"width": 225,
"height": 225,
"transparent": true,
"frame": false,
"always-on-top": true,
"resizable": false
});
mainWindow.loadUrl('file://' + __dirname + '/index.html');
mainWindow.on('closed', function() {
mainWindow = null;
});
});
| var {app} = require('electron');
var {BrowserWindow} = require('electron');
var mainWindow = null;
app.on('window-all-closed', function() {
app.quit();
});
app.on('ready', function() {
mainWindow = new BrowserWindow({
"width": 225,
"height": 225,
"transparent": true,
"frame": false,
"always-on-top": true,
"resizable": false
});
mainWindow.loadURL('file://' + __dirname + '/index.html');
mainWindow.on('closed', function() {
mainWindow = null;
});
});
| Fix problems on the latest electron | Fix problems on the latest electron
| JavaScript | mit | yasuyuky/elmtrn,yasuyuky/elmtrn | ---
+++
@@ -1,5 +1,5 @@
-var app = require('app');
-var BrowserWindow = require('browser-window');
+var {app} = require('electron');
+var {BrowserWindow} = require('electron');
var mainWindow = null;
app.on('window-all-closed', function() {
@@ -15,7 +15,7 @@
"always-on-top": true,
"resizable": false
});
- mainWindow.loadUrl('file://' + __dirname + '/index.html');
+ mainWindow.loadURL('file://' + __dirname + '/index.html');
mainWindow.on('closed', function() {
mainWindow = null;
}); |
6763b2ff8f16681698fc7182d44a512cedf39837 | client/app/scripts/controllers/changelog.js | client/app/scripts/controllers/changelog.js | angular
.module('app')
.controller('changelogController', [
'$rootScope',
'$scope',
'apiService',
function($rootScope, $scope, api) {
api.changelog.then(function(response) {
$scope.changelog = response.data;
});
}
]);
| angular
.module('app')
.controller('changelogController', [
'$rootScope',
'$scope',
'apiService',
function($rootScope, $scope, api) {
api.changelog().then(function(response) {
$scope.changelog = response.data;
});
}
]);
| Fix for change log error | Fix for change log error
| JavaScript | mit | brettshollenberger/mrl001,brettshollenberger/mrl001 | ---
+++
@@ -5,8 +5,8 @@
'$scope',
'apiService',
function($rootScope, $scope, api) {
-
- api.changelog.then(function(response) {
+
+ api.changelog().then(function(response) {
$scope.changelog = response.data;
});
|
cd040ba9f8170ed92f073ff6805476313d2030a5 | fixture/test/open.js | fixture/test/open.js | // Thests for the open method for fs module. This opens a file for reading only.
//
var fs=newFS();
var fileName="hello.txt";
var content="hello";
function testOpen(){
try{
f=fs.open(fileName);
message=f.read();
if(message!=content){
throw "expected "+content+" got "+message;
}
f.close();
}catch(e){
throw e;
}
}
testOpen();
| // Thests for the open method for fs module. This opens a file for reading only.
//
var fs=newFS();
var fileName="hello.txt";
var content="hello";
function testOpen(){
console.log("-- Testing fs.open");
try{
f=fs.open(fileName);
message=f.read();
if(message!=content){
throw "expected "+content+" got "+message;
}
f.close();
}catch(e){
throw e;
}
}
testOpen();
| Add logging information to a test script | Add logging information to a test script
| JavaScript | mit | gernest/wuxia,gernest/wuxia,gernest/wuxia,gernest/wuxia | ---
+++
@@ -4,6 +4,7 @@
var fileName="hello.txt";
var content="hello";
function testOpen(){
+ console.log("-- Testing fs.open");
try{
f=fs.open(fileName);
message=f.read(); |
d277de83db62f68419b7ef93e97ccd9d5f2e8fec | lib/contract/resultMapper/index.js | lib/contract/resultMapper/index.js | 'use strict'
const mapResult = result => {
return {
name: result.contract.name,
consumer: result.contract.consumer,
status: result.err ? 'Fail' : 'Pass',
error: result.err
}
}
module.exports = mapResult
| 'use strict'
const Joi = require('joi')
const mapResult = result => {
return {
name: result.contract.name,
consumer: result.contract.consumer,
status: result.err ? 'Fail' : 'Pass',
error: result.err ? result.err.toString() : null
}
}
module.exports = mapResult
| Tweak to result mapper. Fixed example contract to use new syntax | Tweak to result mapper. Fixed example contract to use new syntax
| JavaScript | apache-2.0 | findmypast-oss/jackal,findmypast-oss/jackal | ---
+++
@@ -1,11 +1,13 @@
'use strict'
+
+const Joi = require('joi')
const mapResult = result => {
return {
name: result.contract.name,
consumer: result.contract.consumer,
status: result.err ? 'Fail' : 'Pass',
- error: result.err
+ error: result.err ? result.err.toString() : null
}
}
|
0467fa7d24391157ab28d6ba61a14b1a61095c72 | lib/core/public/cleanup-plugins.js | lib/core/public/cleanup-plugins.js |
function cleanupPlugins(resolve, reject) {
'use strict';
if (!axe._audit) {
throw new Error('No audit configured');
}
var q = axe.utils.queue();
// If a plugin fails it's cleanup, we still want the others to run
var cleanupErrors = [];
Object.keys(axe.plugins).forEach(function (key) {
q.defer(function (res) {
var rej = function (err) {
cleanupErrors.push(err);
res();
};
try {
axe.plugins[key].cleanup(res, rej);
} catch(err) {
rej(err);
}
});
});
var flattenedTree = axe.utils.getFlattenedTree(document.body)
axe.utils.querySelectorAll(flattenedTree, 'iframe, frame').forEach(function (node) {
q.defer(function (res, rej) {
return axe.utils.sendCommandToFrame(node.actualNode, {
command: 'cleanup-plugin'
}, res, rej);
});
});
q.then(function (results) {
if (cleanupErrors.length === 0) {
resolve(results);
} else {
reject(cleanupErrors);
}
})
.catch(reject);
}
axe.cleanup = cleanupPlugins;
|
function cleanupPlugins(resolve, reject) {
'use strict';
if (!axe._audit) {
throw new Error('No audit configured');
}
var q = axe.utils.queue();
// If a plugin fails it's cleanup, we still want the others to run
var cleanupErrors = [];
Object.keys(axe.plugins).forEach(function (key) {
q.defer(function (res) {
var rej = function (err) {
cleanupErrors.push(err);
res();
};
try {
axe.plugins[key].cleanup(res, rej);
} catch(err) {
rej(err);
}
});
});
var flattenedTree = axe.utils.getFlattenedTree(document.body);
axe.utils.querySelectorAll(flattenedTree, 'iframe, frame').forEach(function (node) {
q.defer(function (res, rej) {
return axe.utils.sendCommandToFrame(node.actualNode, {
command: 'cleanup-plugin'
}, res, rej);
});
});
q.then(function (results) {
if (cleanupErrors.length === 0) {
resolve(results);
} else {
reject(cleanupErrors);
}
})
.catch(reject);
}
axe.cleanup = cleanupPlugins;
| Fix lint problem in cleanup-plugin | chore: Fix lint problem in cleanup-plugin
| JavaScript | mpl-2.0 | dequelabs/axe-core,dequelabs/axe-core,dequelabs/axe-core,dequelabs/axe-core | ---
+++
@@ -23,7 +23,7 @@
});
});
- var flattenedTree = axe.utils.getFlattenedTree(document.body)
+ var flattenedTree = axe.utils.getFlattenedTree(document.body);
axe.utils.querySelectorAll(flattenedTree, 'iframe, frame').forEach(function (node) {
q.defer(function (res, rej) { |
93efa549cdfdd5cad1ffc4528b594075dba2df23 | src/main/webapp/scripts/app/app.constants.js | src/main/webapp/scripts/app/app.constants.js | "use strict";
// DO NOT EDIT THIS FILE, EDIT THE GRUNT TASK NGCONSTANT SETTINGS INSTEAD WHICH GENERATES THIS FILE
angular.module('publisherApp')
.constant('ENV', 'dev')
.constant('VERSION', '1.2.1-SNAPSHOT')
; | "use strict";
// DO NOT EDIT THIS FILE, EDIT THE GRUNT TASK NGCONSTANT SETTINGS INSTEAD WHICH GENERATES THIS FILE
angular.module('publisherApp')
.constant('ENV', 'dev')
.constant('VERSION', '1.2.2-SNAPSHOT')
; | Update ngconstant version after releasing | Update ngconstant version after releasing
| JavaScript | apache-2.0 | GIP-RECIA/esup-publisher-ui,GIP-RECIA/esup-publisher-ui,EsupPortail/esup-publisher,GIP-RECIA/esup-publisher-ui,EsupPortail/esup-publisher,EsupPortail/esup-publisher,EsupPortail/esup-publisher | ---
+++
@@ -4,6 +4,6 @@
.constant('ENV', 'dev')
-.constant('VERSION', '1.2.1-SNAPSHOT')
+.constant('VERSION', '1.2.2-SNAPSHOT')
; |
fd2f91ad644f34e8ee06283fe15a1155b0fee1ea | tests/helpers/start-app.js | tests/helpers/start-app.js | import Ember from 'ember';
import Application from '../../app';
import config from '../../config/environment';
export default function startApp(attrs) {
let application;
let attributes = Ember.assign({}, config.APP);
attributes = Ember.assign(attributes, attrs); // use defaults, but you can override;
Ember.run(() => {
application = Application.create(attributes);
application.setupForTesting();
application.injectTestHelpers();
});
return application;
}
| import Ember from 'ember';
import Application from '../../app';
import config from '../../config/environment';
export default function startApp(attrs) {
let application;
let attributes = (Ember.assign || Ember.merge)({}, config.APP);
attributes = (Ember.assign || Ember.merge)(attributes, attrs); // use defaults, but you can override;
Ember.run(() => {
application = Application.create(attributes);
application.setupForTesting();
application.injectTestHelpers();
});
return application;
}
| Allow for versions of ember that don't have Ember.assign yet | Allow for versions of ember that don't have Ember.assign yet
| JavaScript | mit | mike-north/ember-anchor,mike-north/ember-anchor,mike-north/ember-anchor,truenorth/ember-anchor,truenorth/ember-anchor,truenorth/ember-anchor | ---
+++
@@ -5,8 +5,8 @@
export default function startApp(attrs) {
let application;
- let attributes = Ember.assign({}, config.APP);
- attributes = Ember.assign(attributes, attrs); // use defaults, but you can override;
+ let attributes = (Ember.assign || Ember.merge)({}, config.APP);
+ attributes = (Ember.assign || Ember.merge)(attributes, attrs); // use defaults, but you can override;
Ember.run(() => {
application = Application.create(attributes); |
e60a1487795d94d2b211c33899b43bb915ad9422 | tests/pkgs/nodejs/index.js | tests/pkgs/nodejs/index.js | var nijs = require('nijs');
exports.pkg = function(args) {
return args.stdenv().mkDerivation({
name : "node-0.10.26",
src : args.fetchurl()({
url : new nijs.NixURL("http://nodejs.org/dist/v0.10.26/node-v0.10.26.tar.gz"),
sha256 : "1ahx9cf2irp8injh826sk417wd528awi4l1mh7vxg7k8yak4wppg"
}),
configureFlags : [ "--shared-openssl", "--shared-zlib" ],
buildInputs : [
args.python(),
args.openssl(),
args.zlib(),
args.utillinux()
],
setupHook : new nijs.NixFile({
value : "setup-hook.sh",
module : module
}),
meta : {
homepage : new nijs.NixURL("http://nodejs.org"),
description : "Platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications"
}
});
};
| var nijs = require('nijs');
exports.pkg = function(args) {
return args.stdenv().mkDerivation({
name : "node-0.10.26",
src : args.fetchurl()({
url : new nijs.NixURL("http://nodejs.org/dist/v0.10.26/node-v0.10.26.tar.gz"),
sha256 : "1ahx9cf2irp8injh826sk417wd528awi4l1mh7vxg7k8yak4wppg"
}),
preConfigure : 'sed -i -e "s|#!/usr/bin/env python|#! $(type -p python)|" configure',
configureFlags : [ "--shared-openssl", "--shared-zlib" ],
buildInputs : [
args.python(),
args.openssl(),
args.zlib(),
args.utillinux()
],
setupHook : new nijs.NixFile({
value : "setup-hook.sh",
module : module
}),
meta : {
homepage : new nijs.NixURL("http://nodejs.org"),
description : "Platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications"
}
});
};
| Fix path to python interpreter to make it work with chroot builds | Fix path to python interpreter to make it work with chroot builds
| JavaScript | mit | svanderburg/nijs,svanderburg/nijs | ---
+++
@@ -7,6 +7,8 @@
url : new nijs.NixURL("http://nodejs.org/dist/v0.10.26/node-v0.10.26.tar.gz"),
sha256 : "1ahx9cf2irp8injh826sk417wd528awi4l1mh7vxg7k8yak4wppg"
}),
+
+ preConfigure : 'sed -i -e "s|#!/usr/bin/env python|#! $(type -p python)|" configure',
configureFlags : [ "--shared-openssl", "--shared-zlib" ],
|
1a2d79f4ea21b2fc32461e037ac4882dc7b540d6 | src/components/Gen/GenResults/GenResults.js | src/components/Gen/GenResults/GenResults.js | import React from 'react'
import injectSheet from 'react-jss'
import styles from './styles'
const GenResults = ({ classes, newLine, results, stats }) => {
let joinedResults = Array.prototype.join.call(results, `${newLine ? '\n' : ' '}`).trim()
let words = stats.words
let maxWords = stats.maxWords
let filtered = stats.filtered
const statsText = () => {
if (filtered > 0) {
return `words: ${words} (${filtered} filtered out); maximum different words: ${maxWords}`
} else {
return `words: ${words}; maximum different words: ${maxWords}`
}
}
return (
<div className={classes.results}>
<div className={classes.output}>
<p className={classes.outText}>
{joinedResults}
</p>
</div>
<div className={classes.stats}>
<p className={classes.statsText}>
{statsText()}
</p>
</div>
</div>
)
}
export default injectSheet(styles)(GenResults)
| import React from 'react'
import injectSheet from 'react-jss'
import styles from './styles'
const GenResults = ({ classes, newLine, results, stats }) => {
let joinedResults = Array.prototype.join.call(results, `${newLine ? '\n' : ' '}`).trim()
let words = stats.words
let maxWords = stats.maxWords
let filtered = stats.filtered
const statsText = () => {
if (filtered > 0) {
return `words: ${words.toLocaleString()} (${filtered.toLocaleString()} filtered out); maximum different words: ${maxWords.toLocaleString()}`
} else {
return `words: ${words.toLocaleString()}; maximum different words: ${maxWords.toLocaleString()}`
}
}
return (
<div className={classes.results}>
<div className={classes.output}>
<p className={classes.outText}>
{joinedResults}
</p>
</div>
<div className={classes.stats}>
<p className={classes.statsText}>
{statsText()}
</p>
</div>
</div>
)
}
export default injectSheet(styles)(GenResults)
| Add locale formatting to stats numbers | Add locale formatting to stats numbers
This addresses issue #10.
| JavaScript | agpl-3.0 | nai888/langua,nai888/langua | ---
+++
@@ -11,9 +11,9 @@
const statsText = () => {
if (filtered > 0) {
- return `words: ${words} (${filtered} filtered out); maximum different words: ${maxWords}`
+ return `words: ${words.toLocaleString()} (${filtered.toLocaleString()} filtered out); maximum different words: ${maxWords.toLocaleString()}`
} else {
- return `words: ${words}; maximum different words: ${maxWords}`
+ return `words: ${words.toLocaleString()}; maximum different words: ${maxWords.toLocaleString()}`
}
}
|
5a3e4ca6a95b7dc43fc527929284015cd739628e | logic/subcampaign/readSubcampainModelLogic.js | logic/subcampaign/readSubcampainModelLogic.js | var configuration = require('../../config/configuration.json')
var utility = require('../../public/method/utility')
module.exports = {
getSubcampaignModel: function (redisClient, subcampaignHashID, callback) {
var tableName = configuration.TableMASubcampaignModel + subcampaignHashID
redisClient.hmget(tableName,
configuration.ConstantSCMMinBudget,
configuration.ConstantSCMSubcampaignName,
configuration.ConstantSCMSubcampaignStyle,
configuration.ConstantSCMSubcampaignPlan,
configuration.ConstantSCMSubcampaignPrice,
configuration.ConstantSCMFileURL,
function (err, replies) {
if (err) {
callback(err, null)
return
}
callback(null, replies)
}
)
},
} | var configuration = require('../../config/configuration.json')
var utility = require('../../public/method/utility')
module.exports = {
getSubcampaignModel: function (redisClient, subcampaignHashID, callback) {
var tableName = configuration.TableMASubcampaignModel + subcampaignHashID
redisClient.hmget(tableName,
configuration.ConstantSCMMinBudget,
configuration.ConstantSCMSubcampaignName,
configuration.ConstantSCMSubcampaignStyle,
configuration.ConstantSCMSubcampaignPlan,
configuration.ConstantSCMSubcampaignPrice,
configuration.ConstantSCMFileURL,
function (err, replies) {
if (err) {
callback(err, null)
return
}
callback(null, replies)
}
)
},
getSubcampaignList: function (redisClient, campiagnHashID, filter, callback) {
var filterKeys = Object.keys(filter)
if (filterKeys.length == 0) {
var tableName = configuration.TableMSCampaignModelSubcampaignModel + accountHashID
redisClient.zrange(tableName, '0', '-1', 'WITHSCORES', function (err, replies) {
if (err) {
callback(err, null)
return
}
callback(null, replies)
})
}
else {
var destinationTableName = configuration.TableMACampaignModel + configuration.TableTemporary + utility.generateUniqueHashID()
var result
var args = []
args.push(destinationTableName)
args.push(filterKeys.length)
for (var i = 0; i < filterKeys.length; i++) {
var key = configuration.campaignEnum[filterKeys[i]]
var table = configuration.TableName.general.SubcampaignModel + accountHashID
utility.stringReplace(table, '@', key)
args.push(table)
}
args.push('AGGREGATE')
args.push('MAX')
redisClient.zinterstore(args, function (err, replies) {
if (err) {
callback(err, null)
return
}
redisClient.zrange(destinationTableName, '0', '-1', 'WITHSCORES', function (err, replies) {
if (err) {
callback(err, null)
return
}
result = replies
redisClient.zremrangebyrank(destinationTableName, '0', '-1', function (err, replies) {
if (err) {
callback(err, null)
return
}
callback(null, result)
})
})
})
}
},
} | Implement Get List of Subcampaign HashIDs (By Filter) | Implement Get List of Subcampaign HashIDs (By Filter)
| JavaScript | mit | Flieral/Announcer-Service,Flieral/Announcer-Service | ---
+++
@@ -20,4 +20,53 @@
}
)
},
+
+ getSubcampaignList: function (redisClient, campiagnHashID, filter, callback) {
+ var filterKeys = Object.keys(filter)
+ if (filterKeys.length == 0) {
+ var tableName = configuration.TableMSCampaignModelSubcampaignModel + accountHashID
+ redisClient.zrange(tableName, '0', '-1', 'WITHSCORES', function (err, replies) {
+ if (err) {
+ callback(err, null)
+ return
+ }
+ callback(null, replies)
+ })
+ }
+ else {
+ var destinationTableName = configuration.TableMACampaignModel + configuration.TableTemporary + utility.generateUniqueHashID()
+ var result
+ var args = []
+ args.push(destinationTableName)
+ args.push(filterKeys.length)
+ for (var i = 0; i < filterKeys.length; i++) {
+ var key = configuration.campaignEnum[filterKeys[i]]
+ var table = configuration.TableName.general.SubcampaignModel + accountHashID
+ utility.stringReplace(table, '@', key)
+ args.push(table)
+ }
+ args.push('AGGREGATE')
+ args.push('MAX')
+ redisClient.zinterstore(args, function (err, replies) {
+ if (err) {
+ callback(err, null)
+ return
+ }
+ redisClient.zrange(destinationTableName, '0', '-1', 'WITHSCORES', function (err, replies) {
+ if (err) {
+ callback(err, null)
+ return
+ }
+ result = replies
+ redisClient.zremrangebyrank(destinationTableName, '0', '-1', function (err, replies) {
+ if (err) {
+ callback(err, null)
+ return
+ }
+ callback(null, result)
+ })
+ })
+ })
+ }
+ },
} |
f520c193a2653abe667d4e4ddf23961fbe6b3593 | config.js | config.js | var config = {}
module.exports = config;
config.listen = {}
config.listen.address = '0.0.0.0'
config.listen.port = 3080;
// Margan is used to be logger, visit here to get more info:
// https://github.com/expressjs/morgan
config.logType = 'combined';
config.trust_proxy = 'loopback, 163.13.128.112'; | var config = {}
module.exports = config;
config.listen = {}
config.listen.address = '0.0.0.0'
config.listen.port = 3080;
// Margan is used to be logger, visit here to get more info:
// https://github.com/expressjs/morgan
config.logType = 'combined';
config.trust_proxy = 'loopback, uniquelocal'; | Edit trust_proxy setting of express. | Edit trust_proxy setting of express.
| JavaScript | mit | tom19960222/C-FAR-Website,tom19960222/C-FAR-Website,tom19960222/C-FAR-Website,tom19960222/C-FAR-Website | ---
+++
@@ -9,4 +9,4 @@
// https://github.com/expressjs/morgan
config.logType = 'combined';
-config.trust_proxy = 'loopback, 163.13.128.112';
+config.trust_proxy = 'loopback, uniquelocal'; |
0f9db6601aecc7b01061ec94ba7b8819d38c4473 | src/config.js | src/config.js | import _ from 'lodash'
import mergeDefaults from 'merge-defaults'
_.mergeDefaults = mergeDefaults
class ConfigManager {
constructor() {
this.Riak = {
nodes: ["localhost:8098"]
}
this.GremlinServer = {
port: 8182,
host: "localhost",
options: {}
}
}
setRiakCluster(nodes) {
if(arguments.length === 1 && nodes instanceof Array)
this.Riak.nodes = nodes
else
this.Riak.nodes = [].slice.call(arguments)
}
setGremlinClientConfig(port, host, options) {
this.GremlinServer = _.mergeDefaults({
port: port,
host: host,
options: options
} || {}, this.GremlinServer)
}
}
export default new ConfigManager() | import _ from 'lodash'
import mergeDefaults from 'merge-defaults'
import is from 'is_js'
_.mergeDefaults = mergeDefaults
class ConfigManager {
constructor() {
this.Riak = {
nodes: ["localhost:8098"]
}
this.GremlinServer = {
port: 8182,
host: "localhost",
options: {}
}
}
setRiakCluster(nodes) {
if(arguments.length === 1 && is.array(nodes))
this.Riak.nodes = nodes
else
this.Riak.nodes = [].slice.call(arguments)
}
setGremlinClientConfig(port, host, options) {
this.GremlinServer = _.mergeDefaults({
port: port,
host: host,
options: options
} || {}, this.GremlinServer)
}
}
export default new ConfigManager() | Use is instead of instanceof to determine if it is an array | Use is instead of instanceof to determine if it is an array
| JavaScript | mit | celrenheit/topmodel,celrenheit/topmodel | ---
+++
@@ -1,5 +1,6 @@
import _ from 'lodash'
import mergeDefaults from 'merge-defaults'
+import is from 'is_js'
_.mergeDefaults = mergeDefaults
class ConfigManager {
@@ -16,7 +17,7 @@
}
setRiakCluster(nodes) {
- if(arguments.length === 1 && nodes instanceof Array)
+ if(arguments.length === 1 && is.array(nodes))
this.Riak.nodes = nodes
else
this.Riak.nodes = [].slice.call(arguments) |
891f49bcf60006b3862a48f01b52130655f015ea | config/webpack.dev.conf.js | config/webpack.dev.conf.js | const webpack = require('webpack');
const merge = require('webpack-merge');
const webpackConfig = require('./webpack.base.conf');
const config = require('./index');
const HtmlWebpackPlugin = require('html-webpack-plugin');
// so that everything is absolute
webpackConfig.output.publicPath = `${config.domain}:${config.port}/`;
// add hot-reload related code to entry chunks
Object.keys(webpackConfig.entry).forEach((name) => {
webpackConfig.entry[name] = [
`webpack-dev-server/client?${webpackConfig.output.publicPath}`,
'webpack/hot/dev-server',
].concat(webpackConfig.entry[name]);
});
module.exports = merge(webpackConfig, {
devtool: '#eval-source-map',
devServer: {
outputPath: 'dist/',
inline: true,
},
module: {
rules: [
{
test: /\.s[ac]ss$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
},
],
},
plugins: [
new webpack.DefinePlugin({
'process.env': { NODE_ENV: '"development"' },
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new HtmlWebpackPlugin({
excludeChunks: ['static'],
filename: '../layout/theme.liquid',
template: './layout/theme.liquid',
inject: true,
}),
],
});
| const webpack = require('webpack');
const merge = require('webpack-merge');
const webpackConfig = require('./webpack.base.conf');
const config = require('./index');
const HtmlWebpackPlugin = require('html-webpack-plugin');
// so that everything is absolute
webpackConfig.output.publicPath = `${config.domain}:${config.port}/`;
// add hot-reload related code to entry chunks
Object.keys(webpackConfig.entry).forEach((name) => {
webpackConfig.entry[name] = [
`webpack-dev-server/client?${webpackConfig.output.publicPath}`,
'webpack/hot/dev-server',
].concat(webpackConfig.entry[name]);
});
module.exports = merge(webpackConfig, {
devtool: '#eval-source-map',
devServer: {
outputPath: 'dist/',
inline: true,
},
module: {
rules: [
{
test: /\.s[ac]ss$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader', options: { sourceMap: true } },
{ loader: 'sass-loader', options: { sourceMap: true } },
],
},
],
},
plugins: [
new webpack.DefinePlugin({
'process.env': { NODE_ENV: '"development"' },
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new HtmlWebpackPlugin({
excludeChunks: ['static'],
filename: '../layout/theme.liquid',
template: './layout/theme.liquid',
inject: true,
}),
],
});
| Add sass sourcemaps to dev env | Add sass sourcemaps to dev env
| JavaScript | mit | DynamoMTL/shopify-pipeline | ---
+++
@@ -28,7 +28,11 @@
rules: [
{
test: /\.s[ac]ss$/,
- use: ['style-loader', 'css-loader', 'sass-loader'],
+ use: [
+ { loader: 'style-loader' },
+ { loader: 'css-loader', options: { sourceMap: true } },
+ { loader: 'sass-loader', options: { sourceMap: true } },
+ ],
},
],
}, |
9829d65352cfb5d72c251fc99c601255788327ae | src/gelato.js | src/gelato.js | 'use strict';
if ($ === undefined) {
throw 'Gelato requires jQuery as a dependency.'
} else {
window.jQuery = window.$ = $;
}
if (_ === undefined) {
throw 'Gelato requires Lodash as a dependency.'
} else {
window._ = _;
}
if (Backbone === undefined) {
throw 'Gelato requires Backbone as a dependency.'
} else {
window.Backbone = Backbone;
}
var Gelato = {};
Gelato._BUILD = '{!date!}';
Gelato._VERSION = '{!version!}';
Gelato.isLocalhost = function() {
return location.hostname === 'localhost';
};
Gelato.isWebsite = function() {
return _.includes(location.protocol, 'http');
};
| 'use strict';
if ($ === undefined) {
throw 'Gelato requires jQuery as a dependency.'
} else {
window.jQuery = window.$ = $;
}
if (_ === undefined) {
throw 'Gelato requires Lodash as a dependency.'
} else {
window._ = _;
}
if (Backbone === undefined) {
throw 'Gelato requires Backbone as a dependency.'
} else {
window.Backbone = Backbone;
}
var Gelato = {};
Gelato._BUILD = '{!date!}';
Gelato._VERSION = '{!version!}';
Gelato.isCordova = function() {
return window.cordova !== undefined;
};
Gelato.isLocalhost = function() {
return location.hostname === 'localhost';
};
Gelato.isWebsite = function() {
return _.includes(location.protocol, 'http');
};
| Add method for checking if cordova is being used | Add method for checking if cordova is being used
| JavaScript | mit | mcfarljw/gelato-framework,mcfarljw/gelato-framework,jernung/gelato,mcfarljw/backbone-gelato,mcfarljw/backbone-gelato,jernung/gelato | ---
+++
@@ -24,6 +24,10 @@
Gelato._VERSION = '{!version!}';
+Gelato.isCordova = function() {
+ return window.cordova !== undefined;
+};
+
Gelato.isLocalhost = function() {
return location.hostname === 'localhost';
}; |
75a3af9b6209060cd245f8b2ac37866ba88d4e3b | lib/rules/placeholder-in-extend.js | lib/rules/placeholder-in-extend.js | 'use strict';
var helpers = require('../helpers');
module.exports = {
'name': 'placeholder-in-extend',
'defaults': {},
'detect': function (ast, parser) {
var result = [];
ast.traverseByType('atkeyword', function (keyword, i, parent) {
keyword.forEach(function (item) {
if (item.content === 'extend') {
parent.forEach('simpleSelector', function (selector) {
var placeholder = false;
selector.content.forEach(function (selectorPiece) {
if (selectorPiece.type === 'placeholder') {
placeholder = true;
}
});
if (!placeholder) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'line': selector.start.line,
'column': selector.start.column,
'message': '@extend must be used with a %placeholder',
'severity': parser.severity
});
}
});
}
});
});
return result;
}
};
| 'use strict';
var helpers = require('../helpers');
module.exports = {
'name': 'placeholder-in-extend',
'defaults': {},
'detect': function (ast, parser) {
var result = [];
ast.traverseByType('atkeyword', function (keyword, i, parent) {
keyword.forEach(function (item) {
if (item.content === 'extend') {
parent.forEach('selector', function (selector) {
var placeholder = false;
selector.content.forEach(function (selectorPiece) {
if (selectorPiece.type === 'placeholder') {
placeholder = true;
}
});
if (!placeholder) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'line': selector.start.line,
'column': selector.start.column,
'message': '@extend must be used with a %placeholder',
'severity': parser.severity
});
}
});
}
});
});
return result;
}
};
| Replace deprecated node type simpleSelector with selector | :bug: Replace deprecated node type simpleSelector with selector
| JavaScript | mit | flacerdk/sass-lint,DanPurdy/sass-lint,bgriffith/sass-lint,sktt/sass-lint,srowhani/sass-lint,sasstools/sass-lint,srowhani/sass-lint,sasstools/sass-lint | ---
+++
@@ -12,7 +12,7 @@
keyword.forEach(function (item) {
if (item.content === 'extend') {
- parent.forEach('simpleSelector', function (selector) {
+ parent.forEach('selector', function (selector) {
var placeholder = false;
selector.content.forEach(function (selectorPiece) { |
036946a7ebdc2d4f5628c3e3a446faffe410132e | examples/async-redux/actions/PostsActions.js | examples/async-redux/actions/PostsActions.js | import fetch from 'isomorphic-fetch';
export function invalidateReddit({ reddit }) {}
export function requestPosts({ reddit }) {}
export function receivePosts({ reddit, json }) {
return {
reddit,
posts: json.data.children.map(child => child.data),
receivedAt: Date.now()
};
}
function fetchPosts({ reddit }, { currentActionSet }) {
currentActionSet.requestPosts({ reddit });
fetch(`http://www.reddit.com/r/${reddit}.json`)
.then(response => response.json())
.then(json => currentActionSet.receivePosts({ reddit, json }))
;
}
export const introspection = {
shouldFetchPosts({ reddit }) {}
}
export function fetchPostsIfNeeded({ reddit }, { currentActionSet, getConsensus }) {
if (currentActionSet.getConsensus.shouldFetchPosts({ reddit }).some()) {
fetchPosts({ reddit }, { currentActionSet });
}
}
| import fetch from 'isomorphic-fetch';
export function invalidateReddit({ reddit }) {}
export function requestPosts({ reddit }) {}
export function receivePosts({ reddit, json }) {
return {
reddit,
posts: json.data.children.map(child => child.data),
receivedAt: Date.now()
};
}
function fetchPosts({ reddit }, { currentActionSet }) {
currentActionSet.requestPosts({ reddit });
fetch(`http://www.reddit.com/r/${reddit}.json`)
.then(response => response.json())
.then(json => currentActionSet.receivePosts({ reddit, json }))
;
}
export const introspection = {
shouldFetchPosts({ reddit }) {}
}
export function fetchPostsIfNeeded({ reddit }, { currentActionSet }) {
if (currentActionSet.consensus.shouldFetchPosts({ reddit }).some()) {
fetchPosts({ reddit }, { currentActionSet });
}
}
| Update async-redux example to getConsensus -> consensus | Update async-redux example to getConsensus -> consensus
| JavaScript | apache-2.0 | BurntCaramel/flambeau | ---
+++
@@ -26,8 +26,8 @@
shouldFetchPosts({ reddit }) {}
}
-export function fetchPostsIfNeeded({ reddit }, { currentActionSet, getConsensus }) {
- if (currentActionSet.getConsensus.shouldFetchPosts({ reddit }).some()) {
+export function fetchPostsIfNeeded({ reddit }, { currentActionSet }) {
+ if (currentActionSet.consensus.shouldFetchPosts({ reddit }).some()) {
fetchPosts({ reddit }, { currentActionSet });
}
} |
249a886a7cf4c5583ab31e8ca94b2b1ae169c0a2 | lib/utilities/validate-config.js | lib/utilities/validate-config.js | var Promise = require('ember-cli/lib/ext/promise');
var chalk = require('chalk');
var yellow = chalk.yellow;
var blue = chalk.blue;
function applyDefaultConfigIfNecessary(config, prop, defaultConfig, ui){
if (!config[prop]) {
var value = defaultConfig[prop];
config[prop] = value;
ui.write(blue('| '));
ui.writeLine(yellow('- Missing config: `' + prop + '`, using default: `' + value + '`'));
}
}
module.exports = function(ui, config) {
ui.write(blue('| '));
ui.writeLine(blue('- validating config'));
var defaultConfig = {
filePattern: '**/*.{js,css,png,gif,jpg,map,xml,txt}'
};
applyDefaultConfigIfNecessary(config, 'filePattern', defaultConfig, ui);
return Promise.resolve();
}
| var Promise = require('ember-cli/lib/ext/promise');
var chalk = require('chalk');
var yellow = chalk.yellow;
var blue = chalk.blue;
function applyDefaultConfigIfNecessary(config, prop, defaultConfig, ui){
if (!config[prop]) {
var value = defaultConfig[prop];
config[prop] = value;
ui.write(blue('| '));
ui.writeLine(yellow('- Missing config: `' + prop + '`, using default: `' + value + '`'));
}
}
module.exports = function(ui, config) {
ui.write(blue('| '));
ui.writeLine(blue('- validating config'));
var defaultConfig = {
filePattern: '**/*.{js,css,png,gif,jpg,map,xml,txt,svg,eot,ttf,woff,woff2}'
};
applyDefaultConfigIfNecessary(config, 'filePattern', defaultConfig, ui);
return Promise.resolve();
}
| Include webfont extensions in default filePatterns | Include webfont extensions in default filePatterns
| JavaScript | mit | lukemelia/ember-cli-deploy-gzip,achambers/ember-cli-deploy-gzip,achambers/ember-cli-deploy-gzip,lukemelia/ember-cli-deploy-gzip,ember-cli-deploy/ember-cli-deploy-gzip | ---
+++
@@ -18,7 +18,7 @@
ui.writeLine(blue('- validating config'));
var defaultConfig = {
- filePattern: '**/*.{js,css,png,gif,jpg,map,xml,txt}'
+ filePattern: '**/*.{js,css,png,gif,jpg,map,xml,txt,svg,eot,ttf,woff,woff2}'
};
applyDefaultConfigIfNecessary(config, 'filePattern', defaultConfig, ui);
|
559f6eb262569aaa1ebf4a626dcf549ce997369e | src/app/components/game/gameModel.service.js | src/app/components/game/gameModel.service.js | export default class GameModelService {
constructor($log, $http, $localStorage, _, websocket) {
'ngInject';
this.$log = $log;
this.$http = $http;
this.$localStorage = $localStorage;
this._ = _;
this.ws = websocket;
this.model = {
game: null
};
}
update(data) {
this.model.game = data;
}
}
| export default class GameModelService {
constructor($log, $http, $localStorage, _, websocket) {
'ngInject';
this.$log = $log;
this.$http = $http;
this.$localStorage = $localStorage;
this._ = _;
this.ws = websocket;
this.model = {
game: {}
};
}
isGameStarted() {
return !this._.isEmpty(this.model.game);
}
update(data) {
data.isGameStarted = true;
this.model.isGameStarted = true;
Object.assign(this.model.game, data);
}
}
| Add 'isGameStarted' property to GameModelService | Add 'isGameStarted' property to GameModelService
| JavaScript | unlicense | ejwaibel/squarrels,ejwaibel/squarrels | ---
+++
@@ -10,11 +10,18 @@
this.ws = websocket;
this.model = {
- game: null
+ game: {}
};
}
+ isGameStarted() {
+ return !this._.isEmpty(this.model.game);
+ }
+
update(data) {
- this.model.game = data;
+ data.isGameStarted = true;
+ this.model.isGameStarted = true;
+
+ Object.assign(this.model.game, data);
}
} |
be7eb150654a27ac04d7bf6746f91f3d01834911 | lib/test-runner/mocha/separate/acceptance.js | lib/test-runner/mocha/separate/acceptance.js | function testFeature(feature) {
if (feature.annotations.ignore) {
describe.skip(`Feature: ${feature.title}`, () => {});
} else {
describe(`Feature: ${feature.title}`, function() {
feature.scenarios.forEach(function(scenario) {
if (scenario.annotations.ignore) {
describe.skip(`Scenario: ${scenario.title}`, () => {});
} else {
describe(`Scenario: ${scenario.title}`, function() {
before(function() {
this.application = startApp();
});
after(function() {
destroyApp(this.application);
});
let context = { ctx: {} };
let failed = false;
scenario.steps.forEach(function(step) {
it(step, function() {
if (failed === true) {
this.test.pending = true;
this.skip();
} else {
let self = this;
let promise = new Ember.RSVP.Promise(function(resolve) {
yadda.Yadda(library.default(), self).yadda(step, context, function next(err, result) {
if (err) {
failed = true;
throw err;
}
return result;
});
});
return promise;
}
});
});
});
}
});
});
}
} | function testFeature(feature) {
if (feature.annotations.ignore) {
describe.skip(`Feature: ${feature.title}`, () => {});
} else {
describe(`Feature: ${feature.title}`, function() {
feature.scenarios.forEach(function(scenario) {
if (scenario.annotations.ignore) {
describe.skip(`Scenario: ${scenario.title}`, () => {});
} else {
describe(`Scenario: ${scenario.title}`, function() {
before(function() {
this.application = startApp();
});
after(function() {
destroyApp(this.application);
});
let context = { ctx: {} };
let failed = false;
scenario.steps.forEach(function(step) {
it(step, function() {
if (failed === true) {
this.test.pending = true;
this.skip();
} else {
let self = this;
let promise = new Ember.RSVP.Promise(function(resolve) {
yadda.Yadda(library.default(), self).yadda(step, context, function next(err, result) {
if (err) {
failed = true;
throw err;
}
resolve(result);
});
});
return promise;
}
});
});
});
}
});
});
}
} | Fix hanging promise in mocha | Fix hanging promise in mocha
| JavaScript | mit | curit/ember-cli-yadda,adamjmcgrath/ember-cli-yadda,curit/ember-cli-yadda,adamjmcgrath/ember-cli-yadda | ---
+++
@@ -32,7 +32,7 @@
throw err;
}
- return result;
+ resolve(result);
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.