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 |
|---|---|---|---|---|---|---|---|---|---|---|
8eeeabd0689edff9adaa46f76bae316ba8ba10fb | website/app/application/core/projects/project/files/display-file-contents-directive.js | website/app/application/core/projects/project/files/display-file-contents-directive.js | (function(module) {
module.directive("displayFileContents", displayFileContentsDirective);
function displayFileContentsDirective() {
return {
restrict: "E",
controller: 'DisplayFileContentsDirectiveController',
controllerAs: 'view',
bindToController: true,
scope: {
file: '=file'
},
templateUrl: 'application/core/projects/project/files/display-file-contents.html'
};
}
module.controller("DisplayFileContentsDirectiveController", DisplayFileContentsDirectiveController);
DisplayFileContentsDirectiveController.$inject = ["mcfile"];
/* @ngInject */
function DisplayFileContentsDirectiveController(mcfile) {
var ctrl = this;
ctrl.fileType = determineFileType(ctrl.file.mediatype);
ctrl.fileSrc = mcfile.src(ctrl.file.id);
//////////////
function determineFileType(mediatype) {
if (isImage(mediatype.mime)) {
return "image";
} else {
switch(mediatype.mime) {
case "application/pdf":
return "pdf";
case "application/vnd.ms-excel":
return "excel";
default:
return mediatype.mime;
}
}
}
}
}(angular.module('materialscommons')));
| (function(module) {
module.directive("displayFileContents", displayFileContentsDirective);
function displayFileContentsDirective() {
return {
restrict: "E",
controller: 'DisplayFileContentsDirectiveController',
controllerAs: 'view',
bindToController: true,
scope: {
file: '=file'
},
templateUrl: 'application/core/projects/project/files/display-file-contents.html'
};
}
module.controller("DisplayFileContentsDirectiveController", DisplayFileContentsDirectiveController);
DisplayFileContentsDirectiveController.$inject = ["mcfile"];
/* @ngInject */
function DisplayFileContentsDirectiveController(mcfile) {
var ctrl = this;
ctrl.fileType = determineFileType(ctrl.file.mediatype);
ctrl.fileSrc = mcfile.src(ctrl.file.id);
//////////////
function determineFileType(mediatype) {
if (isImage(mediatype.mime)) {
return "image";
} else {
switch(mediatype.mime) {
case "application/pdf":
return "pdf";
case "application/vnd.ms-excel":
return "xls";
default:
return mediatype.mime;
}
}
}
}
}(angular.module('materialscommons')));
| Return xls as type for application/vnd.ms-excel. | Return xls as type for application/vnd.ms-excel.
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -32,7 +32,7 @@
case "application/pdf":
return "pdf";
case "application/vnd.ms-excel":
- return "excel";
+ return "xls";
default:
return mediatype.mime;
} |
2cb5cd8a7fd3eecb17af879709143afa0977aebb | admin/broadleaf-admin-module/src/main/resources/admin_style/js/admin/catalog/product.js | admin/broadleaf-admin-module/src/main/resources/admin_style/js/admin/catalog/product.js | (function($, BLCAdmin) {
// Add utility functions for products to the BLCAdmin object
BLCAdmin.product = {
refreshSkusGrid : function($container, listGridUrl) {
BLC.ajax({
url : listGridUrl,
type : "GET"
}, function(data) {
BLCAdmin.listGrid.replaceRelatedListGrid($($(data.trim())[0]).find('table'));
});
}
};
})(jQuery, BLCAdmin);
$(document).ready(function() {
$('body').on('click', 'button.generate-skus', function() {
var $container = $(this).closest('div.listgrid-container');
BLC.ajax({
url : $(this).data('actionurl'),
type : "GET"
}, function(data) {
var alertType = data.error ? 'alert' : '';
BLCAdmin.listGrid.showAlert($container, data.message, {
alertType: alertType,
clearOtherAlerts: true
});
if (data.skusGenerated > 0) {
BLCAdmin.product.refreshSkusGrid($container, data.listGridUrl);
}
});
return false;
});
}); | (function($, BLCAdmin) {
// Add utility functions for products to the BLCAdmin object
BLCAdmin.product = {
refreshSkusGrid : function($container, listGridUrl) {
BLC.ajax({
url : listGridUrl,
type : "GET"
}, function(data) {
BLCAdmin.listGrid.replaceRelatedListGrid($(data));
});
}
};
})(jQuery, BLCAdmin);
$(document).ready(function() {
$('body').on('click', 'button.generate-skus', function() {
var $container = $(this).closest('div.listgrid-container');
BLC.ajax({
url : $(this).data('actionurl'),
type : "GET"
}, function(data) {
var alertType = data.error ? 'alert' : '';
BLCAdmin.listGrid.showAlert($container, data.message, {
alertType: alertType,
clearOtherAlerts: true
});
if (data.skusGenerated > 0) {
BLCAdmin.product.refreshSkusGrid($container, data.listGridUrl);
}
});
return false;
});
}); | Fix sku generation not updating list grid properly | Fix sku generation not updating list grid properly
| JavaScript | apache-2.0 | cengizhanozcan/BroadleafCommerce,liqianggao/BroadleafCommerce,cloudbearings/BroadleafCommerce,lgscofield/BroadleafCommerce,wenmangbo/BroadleafCommerce,wenmangbo/BroadleafCommerce,zhaorui1/BroadleafCommerce,zhaorui1/BroadleafCommerce,shopizer/BroadleafCommerce,macielbombonato/BroadleafCommerce,bijukunjummen/BroadleafCommerce,cogitoboy/BroadleafCommerce,trombka/blc-tmp,passion1014/metaworks_framework,jiman94/BroadleafCommerce-BroadleafCommerce2014,TouK/BroadleafCommerce,rawbenny/BroadleafCommerce,shopizer/BroadleafCommerce,trombka/blc-tmp,cengizhanozcan/BroadleafCommerce,caosg/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,alextiannus/BroadleafCommerce,wenmangbo/BroadleafCommerce,udayinfy/BroadleafCommerce,cogitoboy/BroadleafCommerce,sitexa/BroadleafCommerce,caosg/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,gengzhengtao/BroadleafCommerce,cloudbearings/BroadleafCommerce,macielbombonato/BroadleafCommerce,alextiannus/BroadleafCommerce,udayinfy/BroadleafCommerce,rawbenny/BroadleafCommerce,sanlingdd/broadleaf,passion1014/metaworks_framework,gengzhengtao/BroadleafCommerce,cogitoboy/BroadleafCommerce,daniellavoie/BroadleafCommerce,jiman94/BroadleafCommerce-BroadleafCommerce2014,shopizer/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,liqianggao/BroadleafCommerce,alextiannus/BroadleafCommerce,udayinfy/BroadleafCommerce,TouK/BroadleafCommerce,gengzhengtao/BroadleafCommerce,caosg/BroadleafCommerce,sitexa/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,bijukunjummen/BroadleafCommerce,lgscofield/BroadleafCommerce,cloudbearings/BroadleafCommerce,passion1014/metaworks_framework,cengizhanozcan/BroadleafCommerce,macielbombonato/BroadleafCommerce,liqianggao/BroadleafCommerce,lgscofield/BroadleafCommerce,sanlingdd/broadleaf,trombka/blc-tmp,arshadalisoomro/BroadleafCommerce,ljshj/BroadleafCommerce,daniellavoie/BroadleafCommerce,ljshj/BroadleafCommerce,ljshj/BroadleafCommerce,TouK/BroadleafCommerce,zhaorui1/BroadleafCommerce,sitexa/BroadleafCommerce,daniellavoie/BroadleafCommerce,bijukunjummen/BroadleafCommerce,rawbenny/BroadleafCommerce,arshadalisoomro/BroadleafCommerce | ---
+++
@@ -8,7 +8,7 @@
url : listGridUrl,
type : "GET"
}, function(data) {
- BLCAdmin.listGrid.replaceRelatedListGrid($($(data.trim())[0]).find('table'));
+ BLCAdmin.listGrid.replaceRelatedListGrid($(data));
});
}
|
a32d4d156c6e4ec3a3670a9350dc0073f09017f5 | gulpfile.js/tasks/rev/update-html.js | gulpfile.js/tasks/rev/update-html.js | var gulp = require('gulp');
// 5) Update asset references in HTML
gulp.task('update-html', function () {
var config = require('../../config'),
path = require('path'),
revReplace = require('gulp-rev-replace')
var manifest = gulp.src(config.publicDirectory + "/rev-manifest.json");
return gulp.src(path.join(config.root.dest, '/**/*.html'))
.pipe(revReplace({manifest: manifest}))
.pipe(gulp.dest(config.root.dest))
});
| var gulp = require('gulp');
// 5) Update asset references in HTML
gulp.task('update-html', function () {
var config = require('../../config'),
path = require('path'),
revReplace = require('gulp-rev-replace')
var manifest = gulp.src(path.join(config.root.dest, "/rev-manifest.json"))
return gulp.src(path.join(config.root.dest, config.tasks.html.dest, '/**/*.html'))
.pipe(revReplace({manifest: manifest}))
.pipe(gulp.dest(path.join(config.root.dest, config.tasks.html.dest)))
});
| Fix html not updating references | Fix html not updating references
| JavaScript | mit | t2t2/obs-remote-tablet,t2t2/obs-tablet-remote,t2t2/obs-remote-tablet,dx9s/obs-tablet-remote,dx9s/obs-tablet-remote,mikhailswift/obs-tablet-remote,mikhailswift/obs-tablet-remote,t2t2/obs-tablet-remote | ---
+++
@@ -6,10 +6,9 @@
path = require('path'),
revReplace = require('gulp-rev-replace')
- var manifest = gulp.src(config.publicDirectory + "/rev-manifest.json");
+ var manifest = gulp.src(path.join(config.root.dest, "/rev-manifest.json"))
-
- return gulp.src(path.join(config.root.dest, '/**/*.html'))
+ return gulp.src(path.join(config.root.dest, config.tasks.html.dest, '/**/*.html'))
.pipe(revReplace({manifest: manifest}))
- .pipe(gulp.dest(config.root.dest))
+ .pipe(gulp.dest(path.join(config.root.dest, config.tasks.html.dest)))
}); |
60aa9af4245d7f388c8a932f82d4e6b06809e8f7 | ghost/admin/components/gh-tab-pane.js | ghost/admin/components/gh-tab-pane.js | //See gh-tabs-manager.js for use
var TabPane = Ember.Component.extend({
classNameBindings: ['active'],
tabsManager: Ember.computed(function () {
return this.nearestWithProperty('isTabsManager');
}),
tab: Ember.computed('tabsManager.tabs.@each', function () {
var index = this.get('tabsManager.tabPanes').indexOf(this),
tabs = this.get('tabsManager.tabs');
return tabs && tabs.objectAt(index);
}),
active: Ember.computed.alias('tab.active'),
// Register with the tabs manager
registerWithTabs: function () {
this.get('tabsManager').registerTabPane(this);
}.on('didInsertElement'),
unregisterWithTabs: function () {
this.get('tabsManager').unregisterTabPane(this);
}.on('willDestroyElement')
});
export default TabPane;
| //See gh-tabs-manager.js for use
var TabPane = Ember.Component.extend({
classNameBindings: ['active'],
tabsManager: Ember.computed(function () {
return this.nearestWithProperty('isTabsManager');
}),
tab: Ember.computed('tabsManager.tabs.[]', 'tabsManager.tabPanes.[]',
function () {
var index = this.get('tabsManager.tabPanes').indexOf(this),
tabs = this.get('tabsManager.tabs');
return tabs && tabs.objectAt(index);
}),
active: Ember.computed.alias('tab.active'),
// Register with the tabs manager
registerWithTabs: function () {
this.get('tabsManager').registerTabPane(this);
}.on('didInsertElement'),
unregisterWithTabs: function () {
this.get('tabsManager').unregisterTabPane(this);
}.on('willDestroyElement')
});
export default TabPane;
| Fix GhostTab and GhostTabPane array dependencies | Fix GhostTab and GhostTabPane array dependencies
No issue
- TabPanes weren't finding their tab due to not listing all their dependencies in Ember.computed
| JavaScript | mit | TryGhost/Ghost,TryGhost/Ghost,TryGhost/Ghost | ---
+++
@@ -6,7 +6,8 @@
return this.nearestWithProperty('isTabsManager');
}),
- tab: Ember.computed('tabsManager.tabs.@each', function () {
+ tab: Ember.computed('tabsManager.tabs.[]', 'tabsManager.tabPanes.[]',
+ function () {
var index = this.get('tabsManager.tabPanes').indexOf(this),
tabs = this.get('tabsManager.tabs');
|
aec9071070507e2d1951798ecbc74db465a7ea5b | src/examples/schema/ExampleSchema.js | src/examples/schema/ExampleSchema.js | define([
], function (
) {
return {
"id": "schema/ExampleSchema",
"description": "A simple model for testing",
"$schema": "http://json-schema.org/draft-03/schema",
"type": "object",
"properties": {
"num": {
"type": "integer",
"description": "an optional property.",
"maximum": 10,
"required": true
}
}
};
}); | define({
"id": "schema/ExampleSchema",
"description": "A simple model for testing",
"$schema": "http://json-schema.org/draft-03/schema",
"type": "object",
"properties": {
"num": {
"type": "integer",
"description": "an optional property.",
"maximum": 10,
"required": true
}
}
}); | Use shortened AMD form for object definitions. | Use shortened AMD form for object definitions.
| JavaScript | apache-2.0 | atsid/schematic-js,atsid/schematic-js | ---
+++
@@ -1,19 +1,14 @@
-define([
-], function (
-) {
-
- return {
- "id": "schema/ExampleSchema",
- "description": "A simple model for testing",
- "$schema": "http://json-schema.org/draft-03/schema",
- "type": "object",
- "properties": {
- "num": {
- "type": "integer",
- "description": "an optional property.",
- "maximum": 10,
- "required": true
- }
+define({
+ "id": "schema/ExampleSchema",
+ "description": "A simple model for testing",
+ "$schema": "http://json-schema.org/draft-03/schema",
+ "type": "object",
+ "properties": {
+ "num": {
+ "type": "integer",
+ "description": "an optional property.",
+ "maximum": 10,
+ "required": true
}
- };
+ }
}); |
ce141f9d9a235a99db367c6470bea8e3d91ffd8f | src/generator/suggestions/rails41.js | src/generator/suggestions/rails41.js | import { _ } from 'azk';
import { UIProxy } from 'azk/cli/ui';
import { example_system } from 'azk/generator/rules';
export class Suggestion extends UIProxy {
constructor(...args) {
super(...args);
// Readable name for this suggestion
this.name = 'rails';
// Which rules they suggestion is valid
this.ruleNamesList = ['rails41'];
// Initial Azkfile.js suggestion
this.suggestion = _.extend({}, example_system, {
__type : 'rails 4.1',
image : 'rails:4.1',
provision: [
'bundle install --path /azk/bundler',
'bundle exec rake db:create',
'bundle exec rake db:migrate',
],
http : true,
scalable: { default: 2 },
command : 'bundle exec rackup config.ru --port $HTTP_PORT',
mounts : {
'/azk/#{manifest.dir}': {type: 'path', value: '.'},
'/azk/bundler' : {type: 'persistent', value: 'bundler'},
},
envs : {
RAILS_ENV : 'development',
BUNDLE_APP_CONFIG : '/azk/bundler',
}
});
}
suggest() {
return this.suggestion;
}
}
| import { _ } from 'azk';
import { UIProxy } from 'azk/cli/ui';
import { example_system } from 'azk/generator/rules';
export class Suggestion extends UIProxy {
constructor(...args) {
super(...args);
// Readable name for this suggestion
this.name = 'rails';
// Which rules they suggestion is valid
this.ruleNamesList = ['rails41'];
// Initial Azkfile.js suggestion
this.suggestion = _.extend({}, example_system, {
__type : 'rails 4.1',
image : 'rails:4.1',
provision: [
'bundle install --path /azk/bundler',
'bundle exec rake db:create',
'bundle exec rake db:migrate',
],
http : true,
scalable: { default: 2 },
command : 'bundle exec rackup config.ru --pid /tmp/rails.pid --port $HTTP_PORT',
mounts : {
'/azk/#{manifest.dir}': {type: 'path', value: '.'},
'/azk/bundler' : {type: 'persistent', value: 'bundler'},
},
envs : {
RAILS_ENV : 'development',
BUNDLE_APP_CONFIG : '/azk/bundler',
}
});
}
suggest() {
return this.suggestion;
}
}
| Add argument pid at the command in rails suggestion | Add argument pid at the command in rails suggestion
By default the rails stores the `pid` file of service within the `tmp` folder of the project, when working with multiple instances it creates conflict.
| JavaScript | apache-2.0 | agendor/azk,saitodisse/azk,Klaudit/azk,nuxlli/azk,heitortsergent/azk,marcusgadbem/azk,juniorribeiro/azk,teodor-pripoae/azk,gullitmiranda/azk,Klaudit/azk,agendor/azk,saitodisse/azk,juniorribeiro/azk,teodor-pripoae/azk,fearenales/azk,nuxlli/azk,slobo/azk,fearenales/azk,renanmpimentel/azk,marcusgadbem/azk,azukiapp/azk,renanmpimentel/azk,gullitmiranda/azk,slobo/azk,azukiapp/azk,heitortsergent/azk | ---
+++
@@ -23,7 +23,7 @@
],
http : true,
scalable: { default: 2 },
- command : 'bundle exec rackup config.ru --port $HTTP_PORT',
+ command : 'bundle exec rackup config.ru --pid /tmp/rails.pid --port $HTTP_PORT',
mounts : {
'/azk/#{manifest.dir}': {type: 'path', value: '.'},
'/azk/bundler' : {type: 'persistent', value: 'bundler'}, |
32e1ec5ce328aaa405c30714eecbe83812b8657a | src/experiments/hello-world/config.js | src/experiments/hello-world/config.js | export default {
title: 'Hello World',
description: 'Simple Hello World application with common elements for a scene',
tags: 'Cube',
public: false,
scripts: [
// 'http://127.0.0.1:8080/build/three.js', // For three.js dev
'../../libs/three/r87/three.min.js',
'../../libs/three/r87/controls/OrbitControls.js',
'../../libs/threex/THREEx.WindowResize.js',
'../../libs/dat.gui/0.6.2/dat.gui.min.js',
],
styles: [
'../../libs/dat.gui/0.6.2/dat.gui.css',
],
};
| export default {
title: 'Hello World',
description: 'Simple Hello World application with common elements for a scene',
tags: 'Cube',
public: false,
scripts: [
// 'http://127.0.0.1:8080/build/three.js', // For three.js dev
'../../libs/three/r92/three.min.js',
'../../libs/three/r92/controls/OrbitControls.js',
'../../libs/threex/THREEx.WindowResize.js',
'../../libs/dat.gui/0.6.2/dat.gui.min.js',
],
styles: [
'../../libs/dat.gui/0.6.2/dat.gui.css',
],
};
| Update hello world to use r92 | Update hello world to use r92
| JavaScript | unlicense | kevanstannard/three-experiments,kevanstannard/three-experiments,kevanstannard/three,kevanstannard/three,kevanstannard/three-experiments | ---
+++
@@ -5,8 +5,8 @@
public: false,
scripts: [
// 'http://127.0.0.1:8080/build/three.js', // For three.js dev
- '../../libs/three/r87/three.min.js',
- '../../libs/three/r87/controls/OrbitControls.js',
+ '../../libs/three/r92/three.min.js',
+ '../../libs/three/r92/controls/OrbitControls.js',
'../../libs/threex/THREEx.WindowResize.js',
'../../libs/dat.gui/0.6.2/dat.gui.min.js',
], |
aebf4659761dd694dba689430fe22351cda8ccdc | jquery.after-css-transition-1.0.0.js | jquery.after-css-transition-1.0.0.js | var transitionEnd = "webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend";
$.fn.addClassAfter = function(className) {
var that = this;
setTimeout(function(){
that.addClass(className);
},1);
};
$.fn.addClassAfterTransition = function(className) {
var that, transitionEnd;
that = this;
that.bind(transitionEnd, function() {
$(this).addClass(className);
$(this).unbind(transitionEnd);
});
};
$.fn.removeClassAfter = function(className) {
var that = this;
setTimeout(function(){
that.removeClass(className);
},1);
};
$.fn.removeClassAfterTransition = function(className) {
var that, transitionEnd;
that = this;
that.bind(transitionEnd, function() {
$(this).removeClass(className);
$(this).unbind(transitionEnd);
});
}; | var transitionEnd = "webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend";
$.fn.addClassAfter = function(className) {
var $this = this;
setTimeout(function(){
$this.addClass(className);
},1);
};
$.fn.addClassAfterTransition = function(className) {
this.bind(transitionEnd, function() {
$(this).addClass(className);
$(this).unbind(transitionEnd);
});
return this;
};
$.fn.removeClassAfter = function(className) {
var $this = this;
setTimeout(function(){
$this.removeClass(className);
},1);
};
$.fn.removeClassAfterTransition = function(className) {
this.bind(transitionEnd, function() {
$(this).removeClass(className);
$(this).unbind(transitionEnd);
});
return this;
}; | Remove an empty var was blocking correct execution of the transition events | Remove an empty var was blocking correct execution of the transition events
| JavaScript | mit | vitto/jquery-after-css-transition | ---
+++
@@ -1,30 +1,28 @@
var transitionEnd = "webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend";
$.fn.addClassAfter = function(className) {
- var that = this;
+ var $this = this;
setTimeout(function(){
- that.addClass(className);
+ $this.addClass(className);
},1);
};
$.fn.addClassAfterTransition = function(className) {
- var that, transitionEnd;
- that = this;
- that.bind(transitionEnd, function() {
+ this.bind(transitionEnd, function() {
$(this).addClass(className);
$(this).unbind(transitionEnd);
});
+ return this;
};
$.fn.removeClassAfter = function(className) {
- var that = this;
+ var $this = this;
setTimeout(function(){
- that.removeClass(className);
+ $this.removeClass(className);
},1);
};
$.fn.removeClassAfterTransition = function(className) {
- var that, transitionEnd;
- that = this;
- that.bind(transitionEnd, function() {
+ this.bind(transitionEnd, function() {
$(this).removeClass(className);
$(this).unbind(transitionEnd);
});
+ return this;
}; |
c5270a7d130582bda0dc83e64a402d05480d5d8c | test/index_spec.js | test/index_spec.js | "use strict";
var adjAdjAnimal = require("../lib/index");
var expect = require("chai").expect;
describe("the library", function () {
describe("getting a default id", function () {
var result;
before(function () {
return adjAdjAnimal()
.then(function (id) {
result = id;
});
});
it("generates adj-adj-animal", function () {
expect(result, "matches").to.match(/[a-z]+-[a-z]+-[a-z]+/);
});
});
describe("getting an id with specified number of adjectives", function () {
var result;
before(function () {
return adjAdjAnimal(6)
.then(function (id) {
result = id;
});
});
it("generates adj-{6}animal", function () {
expect(result, "matches").to.match(/([a-z]+-){6}[a-z]+/);
});
});
}); | "use strict";
var adjAdjAnimal = require("../lib/index");
var expect = require("chai").expect;
describe("the library", function () {
describe("getting a default id", function () {
var result;
before(function () {
return adjAdjAnimal()
.then(function (id) {
result = id;
});
});
it("generates adj-adj-animal", function () {
expect(result, "matches").to.match(/[A-Z][a-z]+[A-Z][a-z]+[A-Z][a-z]+/);
});
});
describe("getting an id with specified number of adjectives", function () {
var result;
before(function () {
return adjAdjAnimal(6)
.then(function (id) {
result = id;
});
});
it("generates adj-{6}animal", function () {
expect(result, "matches").to.match(/([A-Z][a-z]+){6}[A-Z][a-z]+/);
});
});
}); | Change test to match new word format. | Change test to match new word format.
| JavaScript | mit | a-type/adjective-adjective-animal,gswalden/adjective-adjective-animal,a-type/adjective-adjective-animal | ---
+++
@@ -16,7 +16,7 @@
});
it("generates adj-adj-animal", function () {
- expect(result, "matches").to.match(/[a-z]+-[a-z]+-[a-z]+/);
+ expect(result, "matches").to.match(/[A-Z][a-z]+[A-Z][a-z]+[A-Z][a-z]+/);
});
});
@@ -31,7 +31,7 @@
});
it("generates adj-{6}animal", function () {
- expect(result, "matches").to.match(/([a-z]+-){6}[a-z]+/);
+ expect(result, "matches").to.match(/([A-Z][a-z]+){6}[A-Z][a-z]+/);
});
});
}); |
e4c913fcdfa6f21d2746992d0d3b241971988ae4 | public/js/models/testsuite/TestSuiteModel.js | public/js/models/testsuite/TestSuiteModel.js | define([
'underscore',
'backbone',
'models/core/BaseModel',
], function(_, Backbone, BaseModel) {
var TestSuiteModel = BaseModel.extend({
defaults: {
id: null,
project_id: 1,
name: 'No test suite name',
description: 'No description',
url: '#/404'
},
initialize: function(options) {
_.bindAll(this, 'url', 'parse');
},
url: function() {
var url = '/api/projects/' + this.get('project_id') + '/testsuites';
if (this.get('id') != null) {
url += '/' + this.get('id');
}
if (this.id)
url += '/' + this.id;
return url;
},
parse: function(obj) {
if (typeof(obj.test_suite) != 'undefined')
return obj.test_suite;
return obj;
}
});
return TestSuiteModel;
}); | define([
'underscore',
'backbone',
'models/core/BaseModel',
], function(_, Backbone, BaseModel) {
var TestSuiteModel = BaseModel.extend({
defaults: {
id: null,
project_id: 1,
name: 'No test suite name',
description: 'No description',
url: '#/404'
},
initialize: function(options) {
_.bindAll(this, 'url', 'parse');
},
url: function() {
var url = '/api/projects/' + this.get('project_id') + '/testsuites';
if (this.get('id') != null) {
url += '/' + this.get('id');
} else if (this.id) {
url += '/' + this.id;
}
return url;
},
parse: function(obj) {
if (typeof(obj.test_suite) != 'undefined')
return obj.test_suite;
return obj;
}
});
return TestSuiteModel;
}); | Fix logic for retrieving test suite id | Fix logic for retrieving test suite id
| JavaScript | mit | nestor-qa/nestor,kinow/nestor,nestor-qa/nestor,kinow/nestor,nestor-qa/nestor,nestor-qa/nestor,kinow/nestor,kinow/nestor | ---
+++
@@ -22,9 +22,9 @@
var url = '/api/projects/' + this.get('project_id') + '/testsuites';
if (this.get('id') != null) {
url += '/' + this.get('id');
+ } else if (this.id) {
+ url += '/' + this.id;
}
- if (this.id)
- url += '/' + this.id;
return url;
},
|
bc77ddc6f4bee3327e9b34aec6fa0d2c847a8a34 | resources/public/js/helpers.js | resources/public/js/helpers.js | function setRotation() {
var speed = document.getElementById("test-rot-speed").value;
drawer.api.setRotation(parseInt(speed));
}
function printState() {
drawer.api.addChange(function(state) {
alert(state);
return state;
});
}
| function setRotation() {
var speed = document.getElementById("test-rot-speed").value;
drawer.api.setRotation(parseInt(speed) || 0);
}
function printState() {
drawer.api.addChange(function(state) {
alert(state);
return state;
});
}
| Check if field value is NaN | Check if field value is NaN
| JavaScript | apache-2.0 | maxi-k/drawer | ---
+++
@@ -1,6 +1,6 @@
function setRotation() {
var speed = document.getElementById("test-rot-speed").value;
- drawer.api.setRotation(parseInt(speed));
+ drawer.api.setRotation(parseInt(speed) || 0);
}
function printState() { |
d2238b3625e43fb3065bdb327497112e981e0dff | server/routes/profile.route.js | server/routes/profile.route.js | //----------------------------------------------------------------------------//
var express = require('express');
var router = express.Router();
var pg = require('pg');
var connectionString = require('../modules/db-config.module');
//----------------------------------------------------------------------------//
// Gets a user's profile info and FAQ entries
router.get('/:id', function(req, res) {
var userId = parseInt(req.params.id);
pg.connect(connectionString, function(error, client, done) {
connectionErrorCheck(error);
client.query(
'SELECT * FROM mentors ' +
'JOIN faq ON mentors.id = faq.mentor_id ' +
'WHERE mentors.id = $1', [userId],
function(error, result) {
if(error) {
console.log('Error when searching mentors and FAQ tables: ', error);
res.sendStatus(500);
} else {
res.send(result.rows);
}
}
);
});
});
module.exports = router;
// Checks for errors connecting to the database
function connectionErrorCheck(error) {
if (error) {
console.log('Database connection error: ', error);
res.sendStatus(500);
}
}
| //----------------------------------------------------------------------------//
var express = require('express');
var router = express.Router();
var pg = require('pg');
var connectionString = require('../modules/db-config.module');
//----------------------------------------------------------------------------//
// Gets a user's profile info and FAQ entries
router.get('/:id', function(req, res) {
var userId = parseInt(req.params.id);
pg.connect(connectionString, function(error, client, done) {
connectionErrorCheck(error);
client.query(
'SELECT * FROM mentors ' +
'FULL OUTER JOIN faq ON mentors.id = faq.mentor_id ' +
'WHERE mentors.id = $1', [userId],
function(error, result) {
done();
if(error) {
console.log('Error when searching mentors and FAQ tables: ', error);
res.sendStatus(500);
} else {
res.send(result.rows);
}
}
);
});
});
module.exports = router;
// Checks for errors connecting to the database
function connectionErrorCheck(error) {
if (error) {
console.log('Database connection error: ', error);
res.sendStatus(500);
}
}
| Add done() and modify query | Add done() and modify query
| JavaScript | mit | STEMentor/STEMentor,STEMentor/STEMentor | ---
+++
@@ -14,9 +14,10 @@
client.query(
'SELECT * FROM mentors ' +
- 'JOIN faq ON mentors.id = faq.mentor_id ' +
+ 'FULL OUTER JOIN faq ON mentors.id = faq.mentor_id ' +
'WHERE mentors.id = $1', [userId],
function(error, result) {
+ done();
if(error) {
console.log('Error when searching mentors and FAQ tables: ', error);
res.sendStatus(500); |
6f31dd5920a715e634bce348394f70729378c7fb | src/Engage/Portrayal/rasterize.js | src/Engage/Portrayal/rasterize.js | var fs = require('fs'),
page = new WebPage(),
address, output, size;
page.settings.userAgent = 'Portrayal (https://github.com/engagedc/portrayal) 1.0.0';
if (phantom.args.length < 2 || phantom.args.length > 3) {
console.log('Usage: rasterize.js URL filename');
phantom.exit();
} else {
address = phantom.args[0];
output = phantom.args[1];
page.viewportSize = { width: 1280, height: 600 };
page.onConsoleMessage = function(msg) { console.log(msg); };
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit(1);
} else {
window.setTimeout(function () {
page.render(output);
phantom.exit();
}, 350);
}
});
} | var fs = require('fs'),
page = new WebPage(),
address, output, size;
page.settings.userAgent = 'Portrayal (https://github.com/engagedc/portrayal) 1.0.0';
page.settings.javascriptEnabled = false;
if (phantom.args.length < 2 || phantom.args.length > 3) {
console.log('Usage: rasterize.js URL filename');
phantom.exit();
} else {
address = phantom.args[0];
output = phantom.args[1];
page.viewportSize = { width: 1400, height: 800 };
page.onConsoleMessage = function(msg) { console.log(msg); };
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit(1);
} else {
window.setTimeout(function () {
page.render(output);
phantom.exit();
}, 350);
}
});
}
| Make view-port bigger, disable JavaScript. | Make view-port bigger, disable JavaScript. | JavaScript | mit | nicekiwi/Portrayal,nicekiwi/Portrayal | ---
+++
@@ -3,6 +3,7 @@
address, output, size;
page.settings.userAgent = 'Portrayal (https://github.com/engagedc/portrayal) 1.0.0';
+page.settings.javascriptEnabled = false;
if (phantom.args.length < 2 || phantom.args.length > 3) {
console.log('Usage: rasterize.js URL filename');
@@ -10,7 +11,7 @@
} else {
address = phantom.args[0];
output = phantom.args[1];
- page.viewportSize = { width: 1280, height: 600 };
+ page.viewportSize = { width: 1400, height: 800 };
page.onConsoleMessage = function(msg) { console.log(msg); };
page.open(address, function (status) {
if (status !== 'success') { |
b3978e4368f84ddd97c16d34afca4a32905a8ce8 | src/hyperty-chat/communication.js | src/hyperty-chat/communication.js | /**
* Copyright 2016 PT Inovação e Sistemas SA
* Copyright 2016 INESC-ID
* Copyright 2016 QUOBIS NETWORKS SL
* Copyright 2016 FRAUNHOFER-GESELLSCHAFT ZUR FOERDERUNG DER ANGEWANDTEN FORSCHUNG E.V
* Copyright 2016 ORANGE SA
* Copyright 2016 Deutsche Telekom AG
* Copyright 2016 Apizee
* Copyright 2016 TECHNISCHE UNIVERSITAT BERLIN
*
* 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.
**/
export const CommunicationStatus = {
OPEN: 'open',
PENDING: 'pending',
CLOSED: 'closed',
PAUSED: 'paused',
FAILED: 'failed'
};
let communication = {
id: '',
host: '',
owner: '',
startingTime: '',
lastModified: '',
duration: '',
communicationStatus: '',
communicationQuality: '',
participants: [],
chatMessage: {}
};
export default communication;
| /**
* Copyright 2016 PT Inovação e Sistemas SA
* Copyright 2016 INESC-ID
* Copyright 2016 QUOBIS NETWORKS SL
* Copyright 2016 FRAUNHOFER-GESELLSCHAFT ZUR FOERDERUNG DER ANGEWANDTEN FORSCHUNG E.V
* Copyright 2016 ORANGE SA
* Copyright 2016 Deutsche Telekom AG
* Copyright 2016 Apizee
* Copyright 2016 TECHNISCHE UNIVERSITAT BERLIN
*
* 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.
**/
export const CommunicationStatus = {
OPEN: 'open',
PENDING: 'pending',
CLOSED: 'closed',
PAUSED: 'paused',
FAILED: 'failed'
};
let communication = {
id: '',
name: '',
host: '',
owner: '',
startingTime: '',
lastModified: '',
duration: '',
communicationStatus: '',
communicationQuality: '',
participants: [],
chatMessage: {}
};
export default communication;
| Add name to comunication model; | Add name to comunication model;
| JavaScript | apache-2.0 | reTHINK-project/dev-hyperty-toolkit,reTHINK-project/dev-hyperty-toolkit,reTHINK-project/dev-hyperty-toolkit | ---
+++
@@ -31,6 +31,7 @@
let communication = {
id: '',
+ name: '',
host: '',
owner: '',
startingTime: '', |
f63066d979f9a85f087be3da1c3dedf58a7c4bf3 | js/locales/bootstrap-datepicker.no.js | js/locales/bootstrap-datepicker.no.js | /**
* Norwegian translation for bootstrap-datepicker
**/
;(function($){
$.fn.datepicker.dates['no'] = {
days: ['Søndag','Mandag','Tirsdag','Onsdag','Torsdag','Fredag','Lørdag'],
daysShort: ['Søn','Man','Tir','Ons','Tor','Fre','Lør'],
daysMin: ['Sø','Ma','Ti','On','To','Fr','Lø'],
months: ['Januar','Februar','Mars','April','Mai','Juni','Juli','August','September','Oktober','November','Desember'],
monthsShort: ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Des'],
today: 'I dag',
clear: 'Nullstill',
weekStart: 0
};
}(jQuery));
| /**
* Norwegian translation for bootstrap-datepicker
**/
;(function($){
$.fn.datepicker.dates['no'] = {
days: ['Søndag','Mandag','Tirsdag','Onsdag','Torsdag','Fredag','Lørdag'],
daysShort: ['Søn','Man','Tir','Ons','Tor','Fre','Lør'],
daysMin: ['Sø','Ma','Ti','On','To','Fr','Lø'],
months: ['Januar','Februar','Mars','April','Mai','Juni','Juli','August','September','Oktober','November','Desember'],
monthsShort: ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Des'],
today: 'I dag',
clear: 'Nullstill',
weekStart: 1,
format: 'dd.mm.yyyy'
};
}(jQuery));
| Fix weekStart and format for Norwegian | Fix weekStart and format for Norwegian
Closes #618
| JavaScript | apache-2.0 | kiwiupover/bootstrap-datepicker,menatoric59/bootstrap-datepicker,abnovak/bootstrap-sass-datepicker,keiwerkgvr/bootstrap-datepicker,vsn4ik/bootstrap-datepicker,NFC-DITO/bootstrap-datepicker,rocLv/bootstrap-datepicker,dswitzer/bootstrap-datepicker,i-am-kenny/bootstrap-datepicker,inway/bootstrap-datepicker,janusnic/bootstrap-datepicker,pacozaa/bootstrap-datepicker,nerionavea/bootstrap-datepicker,wearespindle/datepicker-js,rocLv/bootstrap-datepicker,ashleymcdonald/bootstrap-datepicker,vgrish/bootstrap-datepicker,kiwiupover/bootstrap-datepicker,osama9/bootstrap-datepicker,thetimbanks/bootstrap-datepicker,oller/foundation-datepicker-sass,Azaret/bootstrap-datepicker,fabdouglas/bootstrap-datepicker,hemp/bootstrap-datepicker,wulinmengzhu/bootstrap-datepicker,josegomezr/bootstrap-datepicker,stenmuchow/bootstrap-datepicker,jhalak/bootstrap-datepicker,inspur-tobacco/bootstrap-datepicker,ashleymcdonald/bootstrap-datepicker,Azaret/bootstrap-datepicker,defrian8/bootstrap-datepicker,dckesler/bootstrap-datepicker,oller/foundation-datepicker-sass,dswitzer/bootstrap-datepicker,hemp/bootstrap-datepicker,otnavle/bootstrap-datepicker,mfunkie/bootstrap-datepicker,martinRjs/bootstrap-datepicker,janusnic/bootstrap-datepicker,parkeugene/bootstrap-datepicker,inukshuk/bootstrap-datepicker,Invulner/bootstrap-datepicker,nilbus/bootstrap-datepicker,CherryDT/bootstrap-datepicker,defrian8/bootstrap-datepicker,huang-x-h/bootstrap-datepicker,HuBandiT/bootstrap-datepicker,i-am-kenny/bootstrap-datepicker,rstone770/bootstrap-datepicker,Youraiseme/bootstrap-datepicker,jhalak/bootstrap-datepicker,xutongtong/bootstrap-datepicker,zhaoyan158567/bootstrap-datepicker,uxsolutions/bootstrap-datepicker,mreiden/bootstrap-datepicker,1000hz/bootstrap-datepicker,jesperronn/bootstrap-datepicker,cherylyan/bootstrap-datepicker,uxsolutions/bootstrap-datepicker,Invulner/bootstrap-datepicker,josegomezr/bootstrap-datepicker,vegardok/bootstrap-datepicker,riyan8250/bootstrap-datepicker,Doublemedia/bootstrap-datepicker,fabdouglas/bootstrap-datepicker,hebbet/bootstrap-datepicker,wetet2/bootstrap-datepicker,bitzesty/bootstrap-datepicker,oller/foundation-datepicker-sass,TheJumpCloud/bootstrap-datepicker,CheapSk8/bootstrap-datepicker,abnovak/bootstrap-sass-datepicker,aldano/bootstrap-datepicker,huang-x-h/bootstrap-datepicker,aldano/bootstrap-datepicker,SimpleUpdates/bootstrap-datepicker,HNygard/bootstrap-datepicker,xutongtong/bootstrap-datepicker,1000hz/bootstrap-datepicker,nerionavea/bootstrap-datepicker,hebbet/bootstrap-datepicker,keiwerkgvr/bootstrap-datepicker,Tekzenit/bootstrap-datepicker,martinRjs/bootstrap-datepicker,joubertredrat/bootstrap-datepicker,gn0st1k4m/bootstrap-datepicker,Youraiseme/bootstrap-datepicker,WeiLend/bootstrap-datepicker,Sprinkle7/bootstrap-datepicker,HNygard/bootstrap-datepicker,osama9/bootstrap-datepicker,wulinmengzhu/bootstrap-datepicker,inway/bootstrap-datepicker,josegomezr/bootstrap-datepicker,NFC-DITO/bootstrap-datepicker,saurabh27125/bootstrap-datepicker,WeiLend/bootstrap-datepicker,WebbyLab/bootstrap-datepicker,WebbyLab/bootstrap-datepicker,joubertredrat/bootstrap-datepicker,vsn4ik/bootstrap-datepicker,HuBandiT/bootstrap-datepicker,darluc/bootstrap-datepicker,daniyel/bootstrap-datepicker,Habitissimo/bootstrap-datepicker,TheJumpCloud/bootstrap-datepicker,christophercaburog/bootstrap-datepicker,chengky/bootstrap-datepicker,MartijnDwars/bootstrap-datepicker,stenmuchow/bootstrap-datepicker,otnavle/bootstrap-datepicker,inukshuk/bootstrap-datepicker,fabdouglas/bootstrap-datepicker,acrobat/bootstrap-datepicker,christophercaburog/bootstrap-datepicker,jesperronn/bootstrap-datepicker,Habitissimo/bootstrap-datepicker,Habitissimo/bootstrap-datepicker,zhaoyan158567/bootstrap-datepicker,champierre/bootstrap-datepicker,tcrossland/bootstrap-datepicker,rstone770/bootstrap-datepicker,WebbyLab/bootstrap-datepicker,CheapSk8/bootstrap-datepicker,wetet2/bootstrap-datepicker,bitzesty/bootstrap-datepicker,Sprinkle7/bootstrap-datepicker,vegardok/bootstrap-datepicker,Tekzenit/bootstrap-datepicker,kevintvh/bootstrap-datepicker,dckesler/bootstrap-datepicker,menatoric59/bootstrap-datepicker,ibcooley/bootstrap-datepicker,steffendietz/bootstrap-datepicker,darluc/bootstrap-datepicker,acrobat/bootstrap-datepicker,tcrossland/bootstrap-datepicker,nilbus/bootstrap-datepicker,ibcooley/bootstrap-datepicker,mreiden/bootstrap-datepicker,cbryer/bootstrap-datepicker,SimpleUpdates/bootstrap-datepicker,vgrish/bootstrap-datepicker,thetimbanks/bootstrap-datepicker,yangyichen/bootstrap-datepicker,cbryer/bootstrap-datepicker,riyan8250/bootstrap-datepicker,eternicode/bootstrap-datepicker,mfunkie/bootstrap-datepicker,champierre/bootstrap-datepicker,mfunkie/bootstrap-datepicker,CherryDT/bootstrap-datepicker,eternicode/bootstrap-datepicker,chengky/bootstrap-datepicker,kevintvh/bootstrap-datepicker,inspur-tobacco/bootstrap-datepicker,pacozaa/bootstrap-datepicker,Doublemedia/bootstrap-datepicker,MartijnDwars/bootstrap-datepicker,steffendietz/bootstrap-datepicker,daniyel/bootstrap-datepicker,Mteuahasan/bootstrap-datepicker,parkeugene/bootstrap-datepicker,Mteuahasan/bootstrap-datepicker,saurabh27125/bootstrap-datepicker,1000hz/bootstrap-datepicker,yangyichen/bootstrap-datepicker,gn0st1k4m/bootstrap-datepicker,cherylyan/bootstrap-datepicker | ---
+++
@@ -10,6 +10,7 @@
monthsShort: ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Des'],
today: 'I dag',
clear: 'Nullstill',
- weekStart: 0
+ weekStart: 1,
+ format: 'dd.mm.yyyy'
};
}(jQuery)); |
16ea641d1dd2133c8e14a0293c9b6c5034750cd1 | examples/01-basic-usage/src/counter.js | examples/01-basic-usage/src/counter.js | const React = require("react")
const myStyle = {
"color": "blue"
}
export default React.createClass({
getInitialState() {
return {value: 0}
},
componentDidMount() {
const self = this
tick()
function tick() {
const {step, interval} = self.props
self.setState({
value: self.state.value + step,
interval: setTimeout(tick, interval)
})
}
},
componentWillUnmount() {
clearTimeout(this.state.interval)
},
render() {
return (
<h1 style={myStyle}>{this.state.value}</h1>
)
}
})
| const React = require("react")
const myStyle = {
"color": "blue"
}
export default React.createClass({
getInitialState() {
return {value: 0}
},
componentDidMount() {
const self = this
tick()
function tick() {
const {step, interval} = self.props
self.setState({
value: this.state.value + step,
interval: setTimeout(tick, interval)
})
}
},
componentWillUnmount() {
clearTimeout(this.state.interval)
},
render() {
return (
<h1 style={myStyle}>{this.state.value}</h1>
)
}
})
| Fix broken reference from example | Fix broken reference from example | JavaScript | mit | milankinen/livereactload | ---
+++
@@ -17,7 +17,7 @@
function tick() {
const {step, interval} = self.props
self.setState({
- value: self.state.value + step,
+ value: this.state.value + step,
interval: setTimeout(tick, interval)
})
} |
9edd71055cbfaf44e07f344afe135026d23c6cc4 | app/assets/javascripts/application.js | app/assets/javascripts/application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require jquery.purr
//= require best_in_place
//= require twitter/bootstrap
//= require_tree .
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})
jQuery.fn.submitWithAjax = function() {
this.submit(function() {
$.post(this.action, $(this).serialize(), null, "script");
return false;
})
return this;
};
$(document).ready(function() {
$('.new_note').submitWithAjax();
})
$(document).on('ajax:success', '.delete_note', function(e) {
$(e.currentTarget).closest('div.note').fadeOut();
});
| // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require jquery.purr
//= require best_in_place
//= require twitter/bootstrap
//= require_tree .
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});
jQuery.fn.submitWithAjax = function() {
this.submit(function() {
$.post(this.action, $(this).serialize(), null, "script");
return false;
})
return this;
};
$(document).ready(function() {
$('.new_note').submitWithAjax();
$(':input:enabled:visible:first').focus();
});
$(document).on('ajax:success', '.delete_note', function(e) {
$(e.currentTarget).closest('div.note').fadeOut();
});
| Set focus to first input element. | Set focus to first input element.
| JavaScript | mit | lanzanasto/hash_notes,lanzanasto/hash_notes,lanzanasto/hash_notes | ---
+++
@@ -20,7 +20,7 @@
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
-})
+});
jQuery.fn.submitWithAjax = function() {
this.submit(function() {
@@ -32,7 +32,8 @@
$(document).ready(function() {
$('.new_note').submitWithAjax();
-})
+ $(':input:enabled:visible:first').focus();
+});
$(document).on('ajax:success', '.delete_note', function(e) {
$(e.currentTarget).closest('div.note').fadeOut(); |
36324ea46ae1f0fcda44816c3820c255a82aa5a8 | src/app/reducers/entitiesReducer.js | src/app/reducers/entitiesReducer.js | import {createReducer} from "common/utils/reducerUtils";
import {DATA_LOADED} from "features/tools/toolConstants";
import schema from "app/schema"
const initialState = schema.getDefaultState();
export function loadData(state, payload) {
// Create a Redux-ORM session from our entities "tables"
const session = schema.from(state);
// Get a reference to the correct version of model classes for this Session
const {Pilot, MechDesign, Mech} = session;
const {pilots, designs, mechs} = payload;
// Queue up creation commands for each entry
pilots.forEach(pilot => Pilot.parse(pilot));
designs.forEach(design => MechDesign.parse(design));
mechs.forEach(mech => Mech.parse(mech));
// Apply the queued updates and return the updated "tables"
return session.reduce();
}
export default createReducer(initialState, {
[DATA_LOADED] : loadData,
});
| import {createReducer} from "common/utils/reducerUtils";
import {DATA_LOADED} from "features/tools/toolConstants";
import schema from "app/schema"
const initialState = schema.getDefaultState();
export function loadData(state, payload) {
// Create a Redux-ORM session from our entities "tables"
const session = schema.from(state);
// Get a reference to the correct version of model classes for this Session
const {Pilot, MechDesign, Mech} = session;
const {pilots, designs, mechs} = payload;
// Clear out any existing models from state so that we can avoid
// conflicts from the new data coming in if data is reloaded
[Pilot, Mech, MechDesign].forEach(modelType => {
modelType.all().withModels.forEach(model => model.delete());
session.state = session.reduce();
});
// Queue up creation commands for each entry
pilots.forEach(pilot => Pilot.parse(pilot));
designs.forEach(design => MechDesign.parse(design));
mechs.forEach(mech => Mech.parse(mech));
// Apply the queued updates and return the updated "tables"
return session.reduce();
}
export default createReducer(initialState, {
[DATA_LOADED] : loadData,
});
| Clear out existing models on load to avoid conflicts when reloading data | Clear out existing models on load to avoid conflicts when reloading data
| JavaScript | mit | markerikson/project-minimek,markerikson/project-minimek | ---
+++
@@ -14,6 +14,13 @@
const {pilots, designs, mechs} = payload;
+ // Clear out any existing models from state so that we can avoid
+ // conflicts from the new data coming in if data is reloaded
+ [Pilot, Mech, MechDesign].forEach(modelType => {
+ modelType.all().withModels.forEach(model => model.delete());
+ session.state = session.reduce();
+ });
+
// Queue up creation commands for each entry
pilots.forEach(pilot => Pilot.parse(pilot));
designs.forEach(design => MechDesign.parse(design)); |
d0711bc2d3ede5c767f53698cd6011626152af4e | lib/processor/index.js | lib/processor/index.js | (function () {
'use strict';
var extends = require('./extends');
exports = module.exports = function (guido) {
guido.use(extends);
};
})();
| (function () {
'use strict';
var extend = require('./extend');
exports = module.exports = function (guido) {
guido.use(extend);
};
})();
| Fix in default processors setter module | Fix in default processors setter module
| JavaScript | mit | mkretschek/guido | ---
+++
@@ -1,9 +1,9 @@
(function () {
'use strict';
- var extends = require('./extends');
+ var extend = require('./extend');
exports = module.exports = function (guido) {
- guido.use(extends);
+ guido.use(extend);
};
})(); |
45627aeda59a9642f7c5954e79c67d59053b59a3 | src/menu/darwin_menu_templates.js | src/menu/darwin_menu_templates.js | import { app } from "electron";
export default menus => {
if (process.platform !== "darwin") {
menus.unshift({
label: app.getName(),
submenu: [
{ role: "about" },
{ type: "separator" },
{ role: "services", submenu: [] },
{ type: "separator" },
{ role: "hide" },
{ role: "hideothers" },
{ role: "unhide" },
{ type: "separator" },
{ role: "quit" }
]
});
// Edit menu
menus[1].submenu.push(
{ type: "separator" },
{
label: "Speech",
submenu: [{ role: "startspeaking" }, { role: "stopspeaking" }]
}
);
// Window menu
menus[3].submenu = [
{ role: "close" },
{ role: "minimize" },
{ role: "zoom" },
{ type: "separator" },
{ role: "front" }
];
}
return menus;
};
| import { app } from "electron";
export default menus => {
if (process.platform === "darwin") {
menus.unshift({
label: app.getName(),
submenu: [
{ role: "about" },
{ type: "separator" },
{ role: "services", submenu: [] },
{ type: "separator" },
{ role: "hide" },
{ role: "hideothers" },
{ role: "unhide" },
{ type: "separator" },
{ role: "quit" }
]
});
// Edit menu
menus[1].submenu.push(
{ type: "separator" },
{
label: "Speech",
submenu: [{ role: "startspeaking" }, { role: "stopspeaking" }]
}
);
// Window menu
menus[3].submenu = [
{ role: "close" },
{ role: "minimize" },
{ role: "zoom" },
{ type: "separator" },
{ role: "front" }
];
}
return menus;
};
| Fix application menu missing first menu on macOS. | Fix application menu missing first menu on macOS. | JavaScript | mit | BunqCommunity/BunqDesktop,BunqCommunity/BunqDesktop,BunqCommunity/BunqDesktop,BunqCommunity/BunqDesktop | ---
+++
@@ -1,7 +1,7 @@
import { app } from "electron";
export default menus => {
- if (process.platform !== "darwin") {
+ if (process.platform === "darwin") {
menus.unshift({
label: app.getName(),
submenu: [ |
458645b50af285d4dd7a5918685e547bc3604068 | commands/getavatar.js | commands/getavatar.js | module.exports = {
exec: function (msg, args) {
userQuery(args || msg.author.id, msg, true).then(u => {
bot.createMessage(msg.channel.id, {
embed: {
author: {
name: `${u.nick ? u.nick : u.username} (${u.username}#${u.discriminator})'s avatar`,
icon_url: bot.user.staticAvatarURL
},
image: {
url: u.avatarURL
},
description: `[Image not loading?](${u.avatarURL})`
}
});
}).catch(console.error);
},
isCmd: true,
name: "getavatar",
display: true,
category: 1,
description: "Get someone's avatar!"
}; | module.exports = {
exec: function (msg, args) {
userQuery(args || msg.author.id, msg, true).then(u => {
bot.createMessage(msg.channel.id, {
embed: {
author: {
name: `${u.nick ? u.nick : u.username} (${u.username}#${u.discriminator})'s avatar`,
icon_url: bot.user.staticAvatarURL
},
image: {
url: u.avatarURL
},
description: `[Image not loading?](${u.dynamicAvatarURL("png", 2048)})`
}
});
}).catch(console.error);
},
isCmd: true,
name: "getavatar",
display: true,
category: 1,
description: "Get someone's avatar!"
}; | Use PNG for the avatar link | Use PNG for the avatar link
| JavaScript | mit | TTtie/TTtie-Bot,TTtie/TTtie-Bot,TTtie/TTtie-Bot | ---
+++
@@ -10,7 +10,7 @@
image: {
url: u.avatarURL
},
- description: `[Image not loading?](${u.avatarURL})`
+ description: `[Image not loading?](${u.dynamicAvatarURL("png", 2048)})`
}
});
}).catch(console.error); |
28770adb8a68f18c6ba798d332ee7fddc9a65107 | src/frontend/fetchTutorials.js | src/frontend/fetchTutorials.js | /* global fetch */
module.exports = function(callback) {
console.log("Fetch tutorials.");
fetch('/getListOfTutorials')
.then(function(data) {
return data.json();
}).then(function(tutorialPaths) {
console.log("Obtaining list of tutorials successful: " + tutorialPaths);
callback(0, tutorialPaths);
}).catch(function(error) {
console.log("There was an error obtaining the list of tutorial files: " +
error);
});
};
| /* global fetch */
module.exports = function(callback) {
console.log("Fetch tutorials.");
fetch('/getListOfTutorials', {
credentials: 'same-origin'
})
.then(function(data) {
return data.json();
}).then(function(tutorialPaths) {
console.log("Obtaining list of tutorials successful: " + tutorialPaths);
callback(0, tutorialPaths);
}).catch(function(error) {
console.log("There was an error obtaining the list of " +
"tutorial files: " + error);
});
};
| Fix error about tutorials for pasword-restricted use | Fix error about tutorials for pasword-restricted use
| JavaScript | mit | fhinkel/InteractiveShell,antonleykin/InteractiveShell,fhinkel/InteractiveShell,fhinkel/InteractiveShell,antonleykin/InteractiveShell,antonleykin/InteractiveShell,fhinkel/InteractiveShell | ---
+++
@@ -1,14 +1,16 @@
/* global fetch */
module.exports = function(callback) {
console.log("Fetch tutorials.");
- fetch('/getListOfTutorials')
+ fetch('/getListOfTutorials', {
+ credentials: 'same-origin'
+ })
.then(function(data) {
return data.json();
}).then(function(tutorialPaths) {
console.log("Obtaining list of tutorials successful: " + tutorialPaths);
callback(0, tutorialPaths);
}).catch(function(error) {
- console.log("There was an error obtaining the list of tutorial files: " +
- error);
- });
+ console.log("There was an error obtaining the list of " +
+ "tutorial files: " + error);
+ });
}; |
466885629604d1c8d1d6ce3a4a47635199d3ff88 | src/components/HomepagePetitions/index.js | src/components/HomepagePetitions/index.js | import React from 'react';
import TeaserGrid from 'components/TeaserGrid';
import Container from 'components/Container';
import BlockContainer from 'components/BlockContainer';
import Section from 'components/Section';
import Heading2 from 'components/Heading2';
import styles from './homepage-petitions.scss';
import Link from 'components/Link';
const HomepagePetitions = ({ petitions, title, text, linkText }) => (
<section>
<Section>
<Container>
<BlockContainer>
<div className={styles.head}>
<Heading2 text={title} />
<Link href='/petitions'>{linkText}</Link>
</div>
</BlockContainer>
<TeaserGrid petitions={petitions.latest} />
</Container>
</Section>
</section>
);
export default HomepagePetitions;
| import React from 'react';
import TeaserGrid from 'components/TeaserGrid';
import Container from 'components/Container';
import BlockContainer from 'components/BlockContainer';
import Section from 'components/Section';
import Heading2 from 'components/Heading2';
import styles from './homepage-petitions.scss';
import Link from 'components/Link';
const HomepagePetitions = ({ petitions, title, text, linkText }) => (
<section>
<Section>
<Container>
<BlockContainer>
<div className={styles.head}>
<Heading2 text={title} />
<Link href='/petitions'>{linkText}</Link>
</div>
</BlockContainer>
<TeaserGrid petitions={petitions.trending} />
</Container>
</Section>
</section>
);
export default HomepagePetitions;
| Change teaser grid to use trending petitions | Change teaser grid to use trending petitions
| JavaScript | apache-2.0 | iris-dni/iris-frontend,iris-dni/iris-frontend,iris-dni/iris-frontend | ---
+++
@@ -17,7 +17,7 @@
<Link href='/petitions'>{linkText}</Link>
</div>
</BlockContainer>
- <TeaserGrid petitions={petitions.latest} />
+ <TeaserGrid petitions={petitions.trending} />
</Container>
</Section>
</section> |
0c23d02f2bed28dfe8b1f6e3fbc9f5a778e62a5a | src/graphics/color/createTexture.js | src/graphics/color/createTexture.js |
function createColorTextureFromSteps()
const map = ColorRamp.createColorTexture(this.refs.colorbar, (i) =>
ColorRamp.map(this.props.steps, i))
function createColorTexture (canvas, colorFunction = () => 'transparent') {
// const canvas = document.createElement('canvas')
// const canvas = ReactDOM.findDOMNode(canvas)
const context = canvas.getContext('2d')
canvas.width = 256
canvas.height = 16
for (let i = 0; i < canvas.width; i++) {
context.fillStyle = colorFunction(i)
context.fillRect(i, 0, 1, canvas.height)
}
return context.getImageData(0, 0, canvas.width, canvas.height)
}
function map (steps, i) {
const offset = i / 255 * (steps.length - 1.0)
const base = Math.trunc(offset)
let color = ColorRamp.mix(steps[base], steps[base + 1], offset - base)
return 'rgba(' + color.values.rgb.toString() + ', 1.0)'
}
|
const map = ColorRamp.createColorTexture(this.refs.colorbar, (i) =>
ColorRamp.map(this.props.steps, i))
function createColorTexture (canvas, colorFunction = () => 'transparent') {
// const canvas = document.createElement('canvas')
// const canvas = ReactDOM.findDOMNode(canvas)
const context = canvas.getContext('2d')
canvas.width = 256
canvas.height = 16
for (let i = 0; i < canvas.width; i++) {
context.fillStyle = colorFunction(i)
context.fillRect(i, 0, 1, canvas.height)
}
return context.getImageData(0, 0, canvas.width, canvas.height)
}
function map (steps, i) {
const offset = i / 255 * (steps.length - 1.0)
const base = Math.trunc(offset)
let color = ColorRamp.mix(steps[base], steps[base + 1], offset - base)
return 'rgba(' + color.values.rgb.toString() + ', 1.0)'
}
| Fix failing build: Unexpected token, expected { (3:0) | Fix failing build: Unexpected token, expected { (3:0)
| JavaScript | mit | Artsdatabanken/ecomap,Artsdatabanken/ecomap,bjornreppen/ecomap,bjornreppen/ecomap | ---
+++
@@ -1,5 +1,4 @@
-function createColorTextureFromSteps()
const map = ColorRamp.createColorTexture(this.refs.colorbar, (i) =>
ColorRamp.map(this.props.steps, i))
|
532ff6314ad15d8829cc17667ad20348275b5c7c | addon/utils.js | addon/utils.js | import Ember from 'ember';
import { namespace } from './consts';
export function debug() {
Ember.Logger.debug(namespace, ...arguments);
} | import { namespace } from './consts';
export function debug() {
if (console.debug) {
console.debug(namespace, ...arguments);
} else {
console.log(namespace, ...arguments);
}
}
| Move from Ember.Logger to console | Move from Ember.Logger to console
Ember.Logger is deprecated as of Ember 3.2. | JavaScript | mit | rhyek/ember-master-tab,rhyek/ember-master-tab | ---
+++
@@ -1,6 +1,9 @@
-import Ember from 'ember';
import { namespace } from './consts';
export function debug() {
- Ember.Logger.debug(namespace, ...arguments);
+ if (console.debug) {
+ console.debug(namespace, ...arguments);
+ } else {
+ console.log(namespace, ...arguments);
+ }
} |
b9ac71032d03c8606ba39cca1a47d0c8339f6c1f | src/js/WinJS/Core/_BaseCoreUtils.js | src/js/WinJS/Core/_BaseCoreUtils.js | // Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
define([
'./_Global'
], function baseCoreUtilsInit(_Global) {
"use strict";
var hasWinRT = !!_Global.Windows;
function markSupportedForProcessing(func) {
/// <signature helpKeyword="WinJS.Utilities.markSupportedForProcessing">
/// <summary locid="WinJS.Utilities.markSupportedForProcessing">
/// Marks a function as being compatible with declarative processing, such as WinJS.UI.processAll
/// or WinJS.Binding.processAll.
/// </summary>
/// <param name="func" type="Function" locid="WinJS.Utilities.markSupportedForProcessing_p:func">
/// The function to be marked as compatible with declarative processing.
/// </param>
/// <returns type="Function" locid="WinJS.Utilities.markSupportedForProcessing_returnValue">
/// The input function.
/// </returns>
/// </signature>
func.supportedForProcessing = true;
return func;
}
return {
_hasWinRT: hasWinRT,
markSupportedForProcessing: markSupportedForProcessing,
_setImmediate: _Global.setImmediate ? _Global.setImmediate.bind(_Global) : function (handler) {
setTimeout(handler, 0);
}
};
}); | // Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
define([
'./_Global'
], function baseCoreUtilsInit(_Global) {
"use strict";
var hasWinRT = !!_Global.Windows;
function markSupportedForProcessing(func) {
/// <signature helpKeyword="WinJS.Utilities.markSupportedForProcessing">
/// <summary locid="WinJS.Utilities.markSupportedForProcessing">
/// Marks a function as being compatible with declarative processing, such as WinJS.UI.processAll
/// or WinJS.Binding.processAll.
/// </summary>
/// <param name="func" type="Function" locid="WinJS.Utilities.markSupportedForProcessing_p:func">
/// The function to be marked as compatible with declarative processing.
/// </param>
/// <returns type="Function" locid="WinJS.Utilities.markSupportedForProcessing_returnValue">
/// The input function.
/// </returns>
/// </signature>
func.supportedForProcessing = true;
return func;
}
return {
hasWinRT: hasWinRT,
markSupportedForProcessing: markSupportedForProcessing,
_setImmediate: _Global.setImmediate ? _Global.setImmediate.bind(_Global) : function (handler) {
setTimeout(handler, 0);
}
};
}); | Fix small typo with hasWinRT. | Fix small typo with hasWinRT.
| JavaScript | mit | grork/winjs,PaulWells/winjs,ladyinblack/winjs,IveWong/winjs,rigdern/winjs,PaulWells/winjs,PaulWells/winjs,gautamsi/winjs,rigdern/winjs,GREYFOXRGR/winjs,edrohler/winjs,jmptrader/winjs,jmptrader/winjs,gautamsi/winjs,Guadzilah/winjs,KevinTCoughlin/winjs,CensoredUser/winjs,kevinwsbr/winjs,GREYFOXRGR/winjs,edrohler/winjs,edrohler/winjs,KevinTCoughlin/winjs,jmptrader/winjs,ladyinblack/winjs,KevinTCoughlin/winjs,kevinwsbr/winjs,CensoredUser/winjs,CensoredUser/winjs,IveWong/winjs,grork/winjs,Guadzilah/winjs,gautamsi/winjs,grork/winjs,nobuoka/winjs,kevinwsbr/winjs,GREYFOXRGR/winjs,nobuoka/winjs,Guadzilah/winjs,rigdern/winjs,IveWong/winjs,ladyinblack/winjs,nobuoka/winjs | ---
+++
@@ -24,7 +24,7 @@
}
return {
- _hasWinRT: hasWinRT,
+ hasWinRT: hasWinRT,
markSupportedForProcessing: markSupportedForProcessing,
_setImmediate: _Global.setImmediate ? _Global.setImmediate.bind(_Global) : function (handler) {
setTimeout(handler, 0); |
dc16c4385b41a4b4f703196350c0fbb6b9740748 | bb-unique-directive/bbUniqueModule.js | bb-unique-directive/bbUniqueModule.js | (function() {
var app = angular.module('bbUniqueModule', []);
app.directive('bbUnique', ['$q',function($q){
//allows us to cache template before we run link
return {
restrict: 'A',
require: 'ngModel',
link: function(scope,elem,attrs,ngModel){
}
}
}]);
}());
| (function() {
var app = angular.module('bbUniqueModule', []);
//assuming you have a data service you're passing in
app.directive('bbUnique', ['$q', 'dataService' ,function($q, dataService){
return {
restrict: 'A',
require: 'ngModel',
link: function(scope,elem,attrs,ngModel){
ngModel.$asyncValidators.unique = function(modelValue,viewValue){
var deffered = $q.defer(),
currentValue = modelValue || viewValue,//if model value is not there, default to view
key = attrs.bbUniqueKey,
property = attrs.bbUniqueProperty;
if(key && property){
dataService.checkUniqueValue(key,property,currentValue)
.then(function(unique){
if(unique){
deferred.resolve(); //got a unique val
}
else{
deferred.reject();
}
});
return deferred.promise;
}
else{
return $q.when(true);
}
}
}
}
}]);
}());
| Add ng model async validator unique function | Add ng model async validator unique function
| JavaScript | mit | benjaminmbrown/angular-directives-study,benjaminmbrown/angular-directives-study | ---
+++
@@ -2,22 +2,41 @@
var app = angular.module('bbUniqueModule', []);
-
- app.directive('bbUnique', ['$q',function($q){
- //allows us to cache template before we run link
-
+ //assuming you have a data service you're passing in
+ app.directive('bbUnique', ['$q', 'dataService' ,function($q, dataService){
return {
restrict: 'A',
require: 'ngModel',
link: function(scope,elem,attrs,ngModel){
- }
+ ngModel.$asyncValidators.unique = function(modelValue,viewValue){
+ var deffered = $q.defer(),
+ currentValue = modelValue || viewValue,//if model value is not there, default to view
+ key = attrs.bbUniqueKey,
+ property = attrs.bbUniqueProperty;
-
-
+ if(key && property){
+ dataService.checkUniqueValue(key,property,currentValue)
+ .then(function(unique){
+ if(unique){
+ deferred.resolve(); //got a unique val
+ }
+ else{
+ deferred.reject();
+ }
+ });
+
+ return deferred.promise;
+
+ }
+ else{
+ return $q.when(true);
+ }
+
+ }
}
+ }
}]);
-
}()); |
2e4b6c8fdf35d6e827eae2d32823504a28af7cc1 | server/auth/strategies/local-login.js | server/auth/strategies/local-login.js | var DB_USERS = require(process.env.APP_DB_USERS),
passport = require("passport"),
LocalStrategy = require('passport-local').Strategy;
module.exports = function() {
passport.use('local-login', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
function(req, email, password, done) {
DB_USERS.findOne({
email: email.toLowerCase()
})
.then(function(user) {
if (user) {
if (user.compare_password(password)) {
done(null, user);
} else {
done("Username or password is incorrect");
}
} else {
done("Username or password is incorrect");
}
})
.catch(function(err) {
done("Unknown error");
console.trace(err);
});
}));
} | var DB_USERS = require(process.env.APP_DB_USERS),
passport = require("passport"),
LocalStrategy = require('passport-local').Strategy;
module.exports = function() {
passport.use('local-login', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
function(req, email, password, done) {
DB_USERS.findOne({
email: email.toLowerCase()
}, function(err, user) {
if (err) {
done(err);
} else {
if (user) {
if (user.compare_password(password)) {
done(null, user);
} else {
done("Username or password is incorrect");
}
} else {
done("Username or password is incorrect");
}
}
});
}));
} | Fix for login, we can now validate our password and username | Fix for login, we can now validate our password and username
| JavaScript | mit | Chillybyte/GlobalComments,Chillybyte/GlobalComments | ---
+++
@@ -11,9 +11,11 @@
},
function(req, email, password, done) {
DB_USERS.findOne({
- email: email.toLowerCase()
- })
- .then(function(user) {
+ email: email.toLowerCase()
+ }, function(err, user) {
+ if (err) {
+ done(err);
+ } else {
if (user) {
if (user.compare_password(password)) {
done(null, user);
@@ -23,11 +25,9 @@
} else {
done("Username or password is incorrect");
}
- })
- .catch(function(err) {
- done("Unknown error");
- console.trace(err);
- });
+ }
+ });
+
}));
} |
dd5039f72d2c3529f628a4b38f212d4d6a2bc3e6 | src/parsebindings/_processattribute/index.js | src/parsebindings/_processattribute/index.js | import getBindingKey from './_getbindingkey';
import bindNode from '../../bindnode';
import lookForBinder from '../../lookforbinder';
// a binder for instance of Attr
const attributeBinder = {
setValue(value) {
this.value = value;
}
};
// adds binding for an attribute
// its logic is much harder than for text node
// check out imported modules for more info
export default function processAttribute({
node,
attribute,
object,
eventOptions
}) {
const { name, value } = attribute;
const { type } = node;
// get a key which will be actually bound to an attribute
// getBindingKey analyzes given value, creates computable property and returns its key
const key = getBindingKey({
object,
text: value
});
const probablyValueInput = name === 'value' && type !== 'checkbox' && type !== 'radio';
const probablyCheckableInput = name === 'checked' && (type === 'checkbox' || type === 'radio');
let defaultBinder;
if (probablyValueInput || probablyCheckableInput) {
defaultBinder = lookForBinder(node);
}
if (defaultBinder) {
// if deault binder is found then this is default HTML5 form element
// remove the attribute and use found binder
node.setAttribute(name, '');
bindNode(object, key, node, defaultBinder, eventOptions);
} else {
// simply bind an attribute
bindNode(object, key, attribute, attributeBinder, eventOptions);
}
}
| import getBindingKey from './_getbindingkey';
import bindNode from '../../bindnode';
import lookForBinder from '../../lookforbinder';
// a binder for instance of Attr
const attributeBinder = {
setValue(value) {
this.value = value;
}
};
// adds binding for an attribute
// its logic is much harder than for text node
// check out imported modules for more info
export default function processAttribute({
node,
attribute,
object,
eventOptions
}) {
const { name, value } = attribute;
const { type } = node;
// get a key which will be actually bound to an attribute
// getBindingKey analyzes given value, creates computable property and returns its key
const key = getBindingKey({
object,
text: value
});
const probablyValueInput = name === 'value' && type !== 'checkbox' && type !== 'radio';
const probablyCheckableInput = name === 'checked' && (type === 'checkbox' || type === 'radio');
let defaultBinder;
if (probablyValueInput || probablyCheckableInput) {
defaultBinder = lookForBinder(node);
}
if (defaultBinder) {
// if deault binder is found then this is default HTML5 form element
// remove the attribute and use found binder
node.removeAttribute(name);
bindNode(object, key, node, defaultBinder, eventOptions);
} else {
// simply bind an attribute
bindNode(object, key, attribute, attributeBinder, eventOptions);
}
}
| Remove attribute instead of raise it when bindings parser is used on HTML5 form elements | fix: Remove attribute instead of raise it when bindings parser is used on HTML5 form elements
This change fixes a bug which appears when bindings parser is used on 'checked' attribute of a
checkbox and bound property is undefined
| JavaScript | mit | finom/matreshka,matreshkajs/matreshka,matreshkajs/matreshka,finom/matreshka | ---
+++
@@ -38,7 +38,7 @@
if (defaultBinder) {
// if deault binder is found then this is default HTML5 form element
// remove the attribute and use found binder
- node.setAttribute(name, '');
+ node.removeAttribute(name);
bindNode(object, key, node, defaultBinder, eventOptions);
} else {
// simply bind an attribute |
2124f2565a652afe0bfaec590b887786e270350c | webpack.config.dev.js | webpack.config.dev.js | var path = require('path');
var webpack = require('webpack');
module.exports = {
// or devtool: 'eval' to debug issues with compiled output:
devtool: 'cheap-module-eval-source-map',
entry: [
// necessary for hot reloading with IE:
'eventsource-polyfill',
// listen to code updates emitted by hot middleware:
'webpack-hot-middleware/client',
// your code:
'./src/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/dist/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'src')
}]
}
};
| var path = require('path');
var webpack = require('webpack');
module.exports = {
// or devtool: 'eval' to debug issues with compiled output:
devtool: 'cheap-module-eval-source-map',
entry: [
// necessary for hot reloading with IE:
'eventsource-polyfill',
// listen to code updates emitted by hot middleware:
'webpack-hot-middleware/client',
// your code:
'./src/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/dist/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'src')
}]
}
};
| Revert "Remove NoErrorsPlugin until webpack-hot-middleware learns to display syntax error overlay after reload as well" | Revert "Remove NoErrorsPlugin until webpack-hot-middleware learns to display syntax error overlay after reload as well"
This reverts commit c1b0521e5fdcc57066477d6143e74db177e27be3.
| JavaScript | cc0-1.0 | kidylee/Front-end-boilerplate,laere/grocery-app,laere/diversion-2,amitayh/react-redux-test,laere/grocery-app,osener/redux-purescript-example,Neil-G/InspectionLog,laere/scape,gaearon/react-transform-boilerplate,amitayh/react-redux-test,mtomcal/react-transform-boilerplate,breath103/watchmen,JakeElder/m-s,kidylee/Front-end-boilerplate,Neil-G/InspectionLog,JakeElder/m-s,breath103/watchmen,laere/diversion-2,gaearon/react-transform-boilerplate,mtomcal/react-transform-boilerplate,laere/scape,osener/redux-purescript-example | ---
+++
@@ -18,7 +18,8 @@
publicPath: '/dist/'
},
plugins: [
- new webpack.HotModuleReplacementPlugin()
+ new webpack.HotModuleReplacementPlugin(),
+ new webpack.NoErrorsPlugin()
],
module: {
loaders: [{ |
055bd0f5f9c711e28cc7c0bf1dc6c0bcc8b205f8 | client/src/components/footer/index.js | client/src/components/footer/index.js | import BottomNavigation from '@material-ui/core/BottomNavigation';
import BottomNavigationAction from '@material-ui/core/BottomNavigationAction';
import React, { Component } from 'react';
import './index.css'
import kitwareLogo from './Kitware_Full_Logo.png';
import strobeLogo from './strobe.png';
import berkeleyLogo from './berkeley.jpg';
const style = {
height: '5rem'
}
export default class Footer extends Component {
render = () => {
return (
<BottomNavigation style={style}>
<BottomNavigationAction
icon={<img className='bottom-logo' src={kitwareLogo} alt="Kitware" />}
onClick={() => this.select(0)} href="http://www.kitware.com"
target="_blank"
/>
<BottomNavigationAction
icon={<img className='bottom-logo' src={strobeLogo} alt="STROBE" />}
onClick={() => this.select(0)} href="http://strobe.colorado.edu/"
target="_blank"
/>
<BottomNavigationAction
icon={<img className='bottom-logo' src={berkeleyLogo} alt="Berkeley Lab" />}
onClick={() => this.select(0)} href="http://www.lbl.gov/"
target="_blank"
/>
</BottomNavigation>
);
}
}
| import BottomNavigation from '@material-ui/core/BottomNavigation';
import BottomNavigationAction from '@material-ui/core/BottomNavigationAction';
import React, { Component } from 'react';
import './index.css'
import uclaLogo from './ucla.png';
import kitwareLogo from './Kitware_Full_Logo.png';
import strobeLogo from './strobe.png';
import berkeleyLogo from './berkeley.jpg';
const style = {
height: '5rem'
}
export default class Footer extends Component {
render = () => {
return (
<BottomNavigation style={style}>
<BottomNavigationAction
icon={<img className='bottom-logo' src={uclaLogo} alt="UCLA" />}
onClick={() => this.select(0)} href="http://www.ucla.edu/"
target="_blank"
/>
<BottomNavigationAction
icon={<img className='bottom-logo' src={kitwareLogo} alt="Kitware" />}
onClick={() => this.select(0)} href="http://www.kitware.com"
target="_blank"
/>
<BottomNavigationAction
icon={<img className='bottom-logo' src={strobeLogo} alt="STROBE" />}
onClick={() => this.select(0)} href="http://strobe.colorado.edu/"
target="_blank"
/>
<BottomNavigationAction
icon={<img className='bottom-logo' src={berkeleyLogo} alt="Berkeley Lab" />}
onClick={() => this.select(0)} href="http://www.lbl.gov/"
target="_blank"
/>
</BottomNavigation>
);
}
}
| Add the UCLA icon back | Add the UCLA icon back
| JavaScript | bsd-3-clause | OpenChemistry/materialsdatabank,OpenChemistry/materialsdatabank,OpenChemistry/materialsdatabank,OpenChemistry/materialsdatabank | ---
+++
@@ -4,6 +4,7 @@
import React, { Component } from 'react';
import './index.css'
+import uclaLogo from './ucla.png';
import kitwareLogo from './Kitware_Full_Logo.png';
import strobeLogo from './strobe.png';
import berkeleyLogo from './berkeley.jpg';
@@ -17,6 +18,11 @@
render = () => {
return (
<BottomNavigation style={style}>
+ <BottomNavigationAction
+ icon={<img className='bottom-logo' src={uclaLogo} alt="UCLA" />}
+ onClick={() => this.select(0)} href="http://www.ucla.edu/"
+ target="_blank"
+ />
<BottomNavigationAction
icon={<img className='bottom-logo' src={kitwareLogo} alt="Kitware" />}
onClick={() => this.select(0)} href="http://www.kitware.com" |
4d8e07834076a5f4e4d61f775761d73e8f779321 | tests/dummy/config/environment.js | tests/dummy/config/environment.js | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| Make sure base tag is not added | Make sure base tag is not added
| JavaScript | mit | lynnetye/ember-trix-editor,lynnetye/ember-trix-editor | ---
+++
@@ -4,7 +4,6 @@
var ENV = {
modulePrefix: 'dummy',
environment: environment,
- baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: { |
75f5e52178788359d1d5c0307fb5d13b48b068b8 | tests/ref_resolver/test_simple.js | tests/ref_resolver/test_simple.js | 'use strict';
const should = require('should');
const refResolver = require('./../../lib/ref_resolver');
const schema = require('./schema.json');
describe('RefResolver', () => {
it('should resolve refs in schema synchronous', () => {
const resolvedSchema = refResolver(schema);
should(resolvedSchema.string)
.eql('string');
});
});
| 'use strict';
const should = require('should');
const refResolver = require('./../../lib/ref_resolver');
const schema = require('./schema.json');
const resolvedSchema = require('./resolvedSchema.json');
describe('RefResolver', () => {
it('should resolve refs in schema synchronous', () => {
const resolved = refResolver(schema);
should(resolved.string)
.eql('string');
});
it('should work with already resolved schema', () => {
const resolved = refResolver(resolvedSchema);
should(resolved)
.deepEqual(resolvedSchema);
});
});
| Add test for already resolved schema | Add test for already resolved schema
| JavaScript | mit | 5minds/nconfetti | ---
+++
@@ -5,14 +5,22 @@
const refResolver = require('./../../lib/ref_resolver');
const schema = require('./schema.json');
+const resolvedSchema = require('./resolvedSchema.json');
describe('RefResolver', () => {
it('should resolve refs in schema synchronous', () => {
- const resolvedSchema = refResolver(schema);
+ const resolved = refResolver(schema);
- should(resolvedSchema.string)
+ should(resolved.string)
.eql('string');
});
+ it('should work with already resolved schema', () => {
+ const resolved = refResolver(resolvedSchema);
+
+ should(resolved)
+ .deepEqual(resolvedSchema);
+ });
+
}); |
73dc63fc29ccd8eb4efe2ddc09aa29d2931b2c59 | lib/modules/apostrophe-global/index.js | lib/modules/apostrophe-global/index.js | // Always provide req.data.global, a virtual page
// for sitewide content such as a footer displayed on all pages
module.exports = {
construct: function(self, options) {
self.pageServe = function(req, callback) {
return self.apos.docs.find(req, { slug: 'global' })
.permission(false).toObject(function(err, doc) {
if (err) {
return callback(err);
}
req.data.global = doc ? doc : {
slug: 'global',
_edit: true
};
return callback(null);
});
};
}
}
| // Always provide req.data.global, a virtual page
// for sitewide content such as a footer displayed on all pages
var async = require('async');
module.exports = {
afterConstruct: function(self) {
self.enableMiddleware();
},
construct: function(self, options) {
self.slug = options.slug || 'global';
self.findGlobal = function(req, callback) {
return self.apos.docs.find(req, { slug: self.slug })
.permission(false)
.toObject(callback);
};
self.modulesReady = function(callback) {
self.initGlobal(callback);
};
self.initGlobal = function(callback) {
var req = self.apos.tasks.getReq();
var existing;
return async.series({
fetch: function(callback) {
return self.findGlobal(req, function(err, result) {
if (err) {
return callback(err);
}
existing = result;
return callback();
});
},
insert: function(callback) {
if (existing) {
return setImmediate(callback);
}
return self.apos.docs.insert(req, { slug: 'global', published: true }, callback);
}
}, callback)
};
self.enableMiddleware = function(){
self.apos.app.use(self.addGlobalToData);
};
self.addGlobalToData = function(req, res, next) {
return self.findGlobal(req, function(err, result) {
if (err) {
return next(err);
}
req.data.global = result;
return next();
});
};
}
}
| Implement apostrophe-global module properly, as opposed to parked page workaround. | Implement apostrophe-global module properly, as opposed to parked page workaround.
| JavaScript | mit | punkave/apostrophe,punkave/apostrophe | ---
+++
@@ -1,19 +1,60 @@
// Always provide req.data.global, a virtual page
// for sitewide content such as a footer displayed on all pages
+var async = require('async');
+
module.exports = {
+ afterConstruct: function(self) {
+ self.enableMiddleware();
+ },
+
construct: function(self, options) {
- self.pageServe = function(req, callback) {
- return self.apos.docs.find(req, { slug: 'global' })
- .permission(false).toObject(function(err, doc) {
+
+ self.slug = options.slug || 'global';
+
+ self.findGlobal = function(req, callback) {
+ return self.apos.docs.find(req, { slug: self.slug })
+ .permission(false)
+ .toObject(callback);
+ };
+
+ self.modulesReady = function(callback) {
+ self.initGlobal(callback);
+ };
+
+ self.initGlobal = function(callback) {
+ var req = self.apos.tasks.getReq();
+ var existing;
+ return async.series({
+ fetch: function(callback) {
+ return self.findGlobal(req, function(err, result) {
+ if (err) {
+ return callback(err);
+ }
+ existing = result;
+ return callback();
+ });
+ },
+ insert: function(callback) {
+ if (existing) {
+ return setImmediate(callback);
+ }
+ return self.apos.docs.insert(req, { slug: 'global', published: true }, callback);
+ }
+ }, callback)
+ };
+
+ self.enableMiddleware = function(){
+ self.apos.app.use(self.addGlobalToData);
+ };
+
+ self.addGlobalToData = function(req, res, next) {
+ return self.findGlobal(req, function(err, result) {
if (err) {
- return callback(err);
+ return next(err);
}
- req.data.global = doc ? doc : {
- slug: 'global',
- _edit: true
- };
- return callback(null);
+ req.data.global = result;
+ return next();
});
};
} |
b9e1f3e71f276a0a51b5de0c507f26b8ffb2bdbf | src/webroot/js/helpers/organismDetails.js | src/webroot/js/helpers/organismDetails.js | getBestName = function(result){
var bestName = "";
if(typeof result["scientificName"] !== "undefined"){
bestName = result["scientificName"];
}
if(typeof result["vernacularNames"] !== "undefined" && result["vernacularNames"].length > 0){
var preferred = false;
result["vernacularNames"].forEach(function(value){
if(value.language === "en"){
if(typeof value["eol_preferred"] !== "undefined" && value["eol_preferred"]){
preferred = true;
bestName = value.vernacularName;
}
else if(!preferred){
bestName = value.vernacularName;
}
}
});
}
return bestName;
}; | /**
* Selects the best vernacularName from the object returned by the eol pages API.
* It only considers english names (language: en) and preferes those with eol_preferred: true.
* The scientificName is used as fallback.
* @param eolObject {Object} object returned by the eol pages API
* @returns {String} bestName
*/
getBestName = function(eolObject){
var bestName = "";
if(typeof eolObject["scientificName"] !== "undefined"){
bestName = eolObject["scientificName"];
}
if(typeof eolObject["vernacularNames"] !== "undefined" && eolObject["vernacularNames"].length > 0){
var preferred = false;
eolObject["vernacularNames"].forEach(function(value){
if(value.language === "en"){
if(typeof value["eol_preferred"] !== "undefined" && value["eol_preferred"]){
preferred = true;
bestName = value.vernacularName;
}
else if(!preferred){
bestName = value.vernacularName;
}
}
});
}
return bestName;
}; | Add documentation for getBestName function | Add documentation for getBestName function
| JavaScript | mit | molbiodiv/fennec,molbiodiv/fennec,molbiodiv/fennec,molbiodiv/fennec,molbiodiv/fennec | ---
+++
@@ -1,11 +1,18 @@
-getBestName = function(result){
+/**
+ * Selects the best vernacularName from the object returned by the eol pages API.
+ * It only considers english names (language: en) and preferes those with eol_preferred: true.
+ * The scientificName is used as fallback.
+ * @param eolObject {Object} object returned by the eol pages API
+ * @returns {String} bestName
+ */
+getBestName = function(eolObject){
var bestName = "";
- if(typeof result["scientificName"] !== "undefined"){
- bestName = result["scientificName"];
+ if(typeof eolObject["scientificName"] !== "undefined"){
+ bestName = eolObject["scientificName"];
}
- if(typeof result["vernacularNames"] !== "undefined" && result["vernacularNames"].length > 0){
+ if(typeof eolObject["vernacularNames"] !== "undefined" && eolObject["vernacularNames"].length > 0){
var preferred = false;
- result["vernacularNames"].forEach(function(value){
+ eolObject["vernacularNames"].forEach(function(value){
if(value.language === "en"){
if(typeof value["eol_preferred"] !== "undefined" && value["eol_preferred"]){
preferred = true; |
4fcb26b30264fb869f60946b78e58c02c023c925 | test/sagas/push_subscription_test.js | test/sagas/push_subscription_test.js | import { expect } from '../spec_helper'
import { AUTHENTICATION, PROFILE } from '../../src/constants/action_types'
import { pushSubscriptionSaga } from '../../src/sagas/push_subscription'
import { isLoggedInSelector } from '../../src/sagas/selectors'
import {
registerForGCM,
requestPushSubscription,
} from '../../src/actions/profile'
describe.only('push subscription saga', function () {
const regId = 'my awesome registration id'
describe('the saga itself', function () {
it('registers for GCM when logged in', function () {
const pushAction = requestPushSubscription(regId)
const pushHandler = pushSubscriptionSaga()
expect(pushHandler).to.take(PROFILE.REQUEST_PUSH_SUBSCRIPTION)
expect(pushHandler.next(pushAction)).to.select(isLoggedInSelector)
expect(pushHandler.next(true)).to.put(registerForGCM(regId))
})
it('defers registration for GCM until logged in', function () {
const pushAction = requestPushSubscription(regId)
const pushHandler = pushSubscriptionSaga()
expect(pushHandler).to.take(PROFILE.REQUEST_PUSH_SUBSCRIPTION)
expect(pushHandler.next(pushAction)).to.select(isLoggedInSelector)
expect(pushHandler.next(false)).to.take(AUTHENTICATION.USER_SUCCESS)
expect(pushHandler).to.put(registerForGCM(regId))
})
})
})
| import { expect } from '../spec_helper'
import { AUTHENTICATION, PROFILE } from '../../src/constants/action_types'
import pushSubscriptionSaga from '../../src/sagas/push_subscription'
import { isLoggedInSelector } from '../../src/sagas/selectors'
import {
registerForGCM,
requestPushSubscription,
} from '../../src/actions/profile'
describe('push subscription saga', function () {
const regId = 'my awesome registration id'
describe('the saga itself', function () {
it('registers for GCM when logged in', function () {
const pushAction = requestPushSubscription(regId)
const pushHandler = pushSubscriptionSaga()
expect(pushHandler).to.take(PROFILE.REQUEST_PUSH_SUBSCRIPTION)
expect(pushHandler.next(pushAction)).to.select(isLoggedInSelector)
expect(pushHandler.next(true)).to.put(registerForGCM(regId))
})
it('defers registration for GCM until logged in', function () {
const pushAction = requestPushSubscription(regId)
const pushHandler = pushSubscriptionSaga()
expect(pushHandler).to.take(PROFILE.REQUEST_PUSH_SUBSCRIPTION)
expect(pushHandler.next(pushAction)).to.select(isLoggedInSelector)
expect(pushHandler.next(false)).to.take(AUTHENTICATION.USER_SUCCESS)
expect(pushHandler).to.put(registerForGCM(regId))
})
})
})
| Fix the broken test and remove only. | Fix the broken test and remove only.
| JavaScript | mit | ello/webapp,ello/webapp,ello/webapp | ---
+++
@@ -1,13 +1,13 @@
import { expect } from '../spec_helper'
import { AUTHENTICATION, PROFILE } from '../../src/constants/action_types'
-import { pushSubscriptionSaga } from '../../src/sagas/push_subscription'
+import pushSubscriptionSaga from '../../src/sagas/push_subscription'
import { isLoggedInSelector } from '../../src/sagas/selectors'
import {
registerForGCM,
requestPushSubscription,
} from '../../src/actions/profile'
-describe.only('push subscription saga', function () {
+describe('push subscription saga', function () {
const regId = 'my awesome registration id'
describe('the saga itself', function () { |
bb665ff1dfed58ffff56cf6f9281d47d4740221b | src/js/sim/components/NotComponent.js | src/js/sim/components/NotComponent.js | /**
* Copyright: (c) 2017 Max Klein
* License: MIT
*/
define([
'sim/Component',
'lib/extend'
], function (Component, extend) {
function NotComponent() {
Component.call(this, arguments);
this.in = [false];
this.out = [false];
}
extend(NotComponent, Component);
NotComponent.prototype.exec = function () {
this.out[0] = !this.in[0];
};
return NotComponent;
});
| /**
* Copyright: (c) 2017 Max Klein
* License: MIT
*/
define([
'sim/Component',
'lib/extend'
], function (Component, extend) {
function NotComponent() {
Component.call(this, arguments);
this.in = [false];
this.out = [true];
}
extend(NotComponent, Component);
NotComponent.prototype.exec = function () {
this.out[0] = !this.in[0];
};
return NotComponent;
});
| Fix initial output of NOT component | Fix initial output of NOT component
| JavaScript | mpl-2.0 | maxkl/LogicSimulator,maxkl/LogicSimulator | ---
+++
@@ -11,7 +11,7 @@
Component.call(this, arguments);
this.in = [false];
- this.out = [false];
+ this.out = [true];
}
extend(NotComponent, Component); |
4baf45c36ad82b5309a8045afd5b452cbbe481db | app/assets/javascripts/alert.js | app/assets/javascripts/alert.js | (function(){
"use strict";
var POLLING_INTERVAL = 3 * 1000;
var POLLING_URL = "/polling/alerts";
$(function(){
var alert = new Vue({
el: "#alert",
data: {
"alerts": []
},
created: function(){
var self = this;
var fetch = function(){
self.fetchAlertsData().then(function(alerts){
self.alerts = alerts;
});
};
fetch();
setInterval(fetch, POLLING_INTERVAL);
},
computed: {
alertsCount: {
$get: function(){ return this.alerts.length; }
},
hasAlerts: {
$get: function(){ return this.alertsCount > 0; }
}
},
methods: {
fetchAlertsData: function() {
return new Promise(function(resolve, reject) {
$.getJSON(POLLING_URL, resolve).fail(reject);
});
}
}
});
});
})();
| (function(){
"use strict";
var POLLING_INTERVAL = 3 * 1000;
var POLLING_URL = "/polling/alerts";
$(function(){
var alert = new Vue({
el: "#alert",
data: {
"alerts": []
},
created: function(){
var self = this;
var fetch = function(){
self.fetchAlertsData().then(function(alerts){
self.alerts = alerts;
})["catch"](function(xhr){
if(xhr.status === 401) {
clearInterval(timer);
}
});
};
fetch();
var timer = setInterval(fetch, POLLING_INTERVAL);
},
computed: {
alertsCount: {
$get: function(){ return this.alerts.length; }
},
hasAlerts: {
$get: function(){ return this.alertsCount > 0; }
}
},
methods: {
fetchAlertsData: function() {
return new Promise(function(resolve, reject) {
$.getJSON(POLLING_URL, resolve).fail(reject);
});
}
}
});
});
})();
| Stop polling if receive 401 response | Stop polling if receive 401 response
| JavaScript | apache-2.0 | fluent/fluentd-ui,mt0803/fluentd-ui,fluent/fluentd-ui,fluent/fluentd-ui,mt0803/fluentd-ui,mt0803/fluentd-ui | ---
+++
@@ -15,10 +15,14 @@
var fetch = function(){
self.fetchAlertsData().then(function(alerts){
self.alerts = alerts;
+ })["catch"](function(xhr){
+ if(xhr.status === 401) {
+ clearInterval(timer);
+ }
});
};
fetch();
- setInterval(fetch, POLLING_INTERVAL);
+ var timer = setInterval(fetch, POLLING_INTERVAL);
},
computed: { |
50b905a35ed3dac70d7998ba6769d4f1aad781d5 | src/main/javascript/utils/find-thread-url-elements.js | src/main/javascript/utils/find-thread-url-elements.js | /*
* Copyright 2016 the original author or authors.
*
* 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.
*/
module.exports = function findGroupedPlatonThreadUrlElements() {
var groupedElements = {};
function addThreadUrlAndElement(threadUrl, elem) {
if (!(threadUrl in groupedElements)) {
groupedElements[threadUrl] = [elem];
} else if (groupedElements[threadUrl].indexOf(threadUrl) < 0) {
groupedElements[threadUrl].push(elem);
}
}
var linksToCommentThreads = document.querySelectorAll('a[href$="#platon-comment-thread"]');
linksToCommentThreads.forEach(function (linkElem) {
addThreadUrlAndElement(linkElem.pathname, linkElem);
});
var elemsWithThreadIds = document.querySelectorAll('*[data-platon-thread-url]');
elemsWithThreadIds.forEach(function (elem) {
addThreadUrlAndElement(elem.getAttribute('data-platon-thread-url'), elem);
});
return groupedElements;
};
| /*
* Copyright 2016 the original author or authors.
*
* 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.
*/
module.exports = function findGroupedPlatonThreadUrlElements() {
var groupedElements = {};
function addThreadUrlAndElement(threadUrl, elem) {
if (!(threadUrl in groupedElements)) {
groupedElements[threadUrl] = [elem];
} else if (groupedElements[threadUrl].indexOf(threadUrl) < 0) {
groupedElements[threadUrl].push(elem);
}
}
var linksToCommentThreads = document.querySelectorAll('a[href$="#platon-comment-thread"]');
Array.prototype.forEach.call(linksToCommentThreads, function (linkElem) {
addThreadUrlAndElement(linkElem.pathname, linkElem);
});
var elemsWithThreadIds = document.querySelectorAll('*[data-platon-thread-url]');
Array.prototype.forEach.call(elemsWithThreadIds, function (elem) {
addThreadUrlAndElement(elem.getAttribute('data-platon-thread-url'), elem);
});
return groupedElements;
};
| Fix iterarting over NodeList in Firefox | Fix iterarting over NodeList in Firefox
| JavaScript | apache-2.0 | pvorb/platon,pvorb/platon,pvorb/platon | ---
+++
@@ -28,13 +28,13 @@
var linksToCommentThreads = document.querySelectorAll('a[href$="#platon-comment-thread"]');
- linksToCommentThreads.forEach(function (linkElem) {
+ Array.prototype.forEach.call(linksToCommentThreads, function (linkElem) {
addThreadUrlAndElement(linkElem.pathname, linkElem);
});
var elemsWithThreadIds = document.querySelectorAll('*[data-platon-thread-url]');
- elemsWithThreadIds.forEach(function (elem) {
+ Array.prototype.forEach.call(elemsWithThreadIds, function (elem) {
addThreadUrlAndElement(elem.getAttribute('data-platon-thread-url'), elem);
});
|
cc18a6d0fdb83a05a7e47c52fc0405ba63082616 | src/main/web/florence/js/functions/_handleApiError.js | src/main/web/florence/js/functions/_handleApiError.js | function handleApiError(response) {
if(!response || response.status === 200)
return;
if(response.status === 403 || response.status === 401) {
logout();
}
else {
console.log('An error has occurred, please contact an administrator. ' + response.responseText);
alert(response.responseText);
}
}
| function handleApiError(response) {
if(!response || response.status === 200)
return;
if(response.status === 403 || response.status === 401) {
logout();
}
else {
console.log('An error has occurred, please contact an administrator. ' + response.responseText);
alert('An error has occurred, please contact an administrator. ' + response.responseText);
}
}
| Add friendly error in alert box when an error occurs. | Add friendly error in alert box when an error occurs.
| JavaScript | mit | ONSdigital/florence,ONSdigital/florence,ONSdigital/florence,ONSdigital/florence | ---
+++
@@ -8,6 +8,6 @@
}
else {
console.log('An error has occurred, please contact an administrator. ' + response.responseText);
- alert(response.responseText);
+ alert('An error has occurred, please contact an administrator. ' + response.responseText);
}
} |
6070eacc01e93e3dd5eb4662d6be41aa5155f1b3 | test/feature.js | test/feature.js | var assert = require('assert');
var seeds = require('../seeds');
var Feature = require('../feature');
describe('Feature', function () {
before(function (done) {
seeds(done);
});
describe('schema', function () {
it('successfully creates a valid document');
it('fails at creating an invalid document');
});
describe('.search()', function () {
it('performs an empty search, returning all commands', function (done) {
Feature.search('', function (docs) {
assert.equal(7, docs.length);
done();
});
});
it('performs a case-insensitive search for a command', function (done) {
Feature.search('git ADD', function (docs) {
assert.equal(1, docs.length)
done();
});
});
it('performs a search for a command that does not exist', function (done) {
Feature.search('git yolo', function (docs) {
assert.equal(0, docs.length);
done();
});
});
});
});
| var assert = require('assert');
var seeds = require('../seeds');
var Feature = require('../feature');
describe('Feature', function () {
before(function (done) {
seeds(done);
});
describe('schema', function () {
it('successfully creates a valid document');
it('fails at creating an invalid document');
});
describe('.search()', function () {
it('performs an empty search, returning all commands', function (done) {
Feature.search('', function (docs) {
assert.equal(7, docs.length);
done();
});
});
it('performs a case-insensitive search for a command', function (done) {
Feature.search('git ADD', function (docs) {
assert.equal(1, docs.length);
var doc = docs[0];
assert.equal('add files', doc.name);
assert.deepEqual({
Git: 'git add',
Mercurial: 'hg add',
Subversion: 'svn add'
}, doc.examples);
done();
});
});
it('performs a search for a command that does not exist', function (done) {
Feature.search('git yolo', function (docs) {
assert.equal(0, docs.length);
done();
});
});
});
});
| Improve the specs for Feature.search() | Improve the specs for Feature.search()
| JavaScript | mit | nicolasmccurdy/rose,nickmccurdy/rose,nicolasmccurdy/rose,nickmccurdy/rose | ---
+++
@@ -22,7 +22,16 @@
it('performs a case-insensitive search for a command', function (done) {
Feature.search('git ADD', function (docs) {
- assert.equal(1, docs.length)
+ assert.equal(1, docs.length);
+
+ var doc = docs[0];
+ assert.equal('add files', doc.name);
+ assert.deepEqual({
+ Git: 'git add',
+ Mercurial: 'hg add',
+ Subversion: 'svn add'
+ }, doc.examples);
+
done();
});
}); |
af24b81702878965722355b1f4cef63580ea974d | server/controllers/usersController.js | server/controllers/usersController.js | let UserRecipes = require(`${__dirname}/../schemas.js`).UserRecipes;
module.exports = {
signup: (req, res) => {
},
login: (req, res) => {
},
logout: (req, res) => {
},
//Gets all the recipes that belong to that user
getProfile: (req, res) => {
//find user
//userId where username: req.params.username
// .then((userId) => {
// //find recipes by user
// return UserRecipes.findOne({userId: userId});
// }).then(result => {
// res.status(200).send(result);
// }).catch(error => {
// res.status(404).send(error);
// });
}
}; | let UserRecipes = require(`${__dirname}/../schemas.js`).UserRecipes;
module.exports = {
signup: (req, res) => {
},
login: (req, res) => {
},
logout: (req, res) => {
},
//Gets all the recipes that belong to that user
getProfile: (req, res) => {
UserRecipes.findOne({
username: req.params.username
}).then(result => {
res.status(200).send(result);
}).catch(error => {
res.status(404).send(error);
});
}
}; | Update getProfile to utilize username rather than userId | Update getProfile to utilize username rather than userId
| JavaScript | mit | JAC-Labs/SkilletHub,JAC-Labs/SkilletHub | ---
+++
@@ -15,15 +15,12 @@
//Gets all the recipes that belong to that user
getProfile: (req, res) => {
- //find user
- //userId where username: req.params.username
- // .then((userId) => {
- // //find recipes by user
- // return UserRecipes.findOne({userId: userId});
- // }).then(result => {
- // res.status(200).send(result);
- // }).catch(error => {
- // res.status(404).send(error);
- // });
+ UserRecipes.findOne({
+ username: req.params.username
+ }).then(result => {
+ res.status(200).send(result);
+ }).catch(error => {
+ res.status(404).send(error);
+ });
}
}; |
82f07f32b79db3321419854ebfebcf4977f9e0f0 | adapters/generic.js | adapters/generic.js | /**
* Basic engine support.
*/
require('../lib/setModuleDefaults');
var config = require('config');
var engineConfig = config.engines || {};
/**
* Return a function that creates a plugin:
*/
module.exports = function(language){
return {
attach: function (/* options */){
var languageConfig = engineConfig[language] || {};
/**
* If there is a specified engine for this language then use it,
* otherwise just use the provided name:
*/
this.engine = require(languageConfig.module || language);
this.languageConfig = languageConfig;
/**
* Add key methods:
*/
var renderFileMethodName = languageConfig.renderFileMethodName
|| 'renderFile';
this.__express = this.engine.__express || undefined;
this.renderFile = this.engine[renderFileMethodName] || undefined;
this.render = this.engine.render || undefined;
}
, name: 'adapter-' + language
};
};
| /**
* Basic engine support.
*/
require('../lib/setModuleDefaults');
var config = require('config');
var engineConfig = config.engines || {};
/**
* Return a function that creates a plugin:
*/
module.exports = function(language){
return {
attach: function (/* options */){
var languageConfig = engineConfig[language] || {};
/**
* If there is a specified engine for this language then use it,
* otherwise just use the provided name:
*/
var engine = require(languageConfig.module || language);
this.engine = (languageConfig.useConstructor) ? new engine() : engine;
this.languageConfig = languageConfig;
/**
* Add key methods:
*/
var renderFileMethodName = languageConfig.renderFileMethodName
|| 'renderFile';
this.__express = this.engine.__express || undefined;
this.renderFile = this.engine[renderFileMethodName] || undefined;
this.render = this.engine.render || undefined;
}
, name: 'adapter-' + language
};
};
| Allow an engine to be initialised using a constructor. | Allow an engine to be initialised using a constructor.
| JavaScript | mit | markbirbeck/adapter-template | ---
+++
@@ -21,7 +21,9 @@
* otherwise just use the provided name:
*/
- this.engine = require(languageConfig.module || language);
+ var engine = require(languageConfig.module || language);
+
+ this.engine = (languageConfig.useConstructor) ? new engine() : engine;
this.languageConfig = languageConfig;
/** |
6f5328d894252be60458a514fd56b12d5b6144bc | src/react-action-creator-generator.js | src/react-action-creator-generator.js | // @flow
import { actionCreatorName, actionCreatorRequestName, actionCreatorSuccessName, actionCreatorFailedName } from './utils'
import type { Schema } from './types'
export const generateActionCreator = (name: string, type: string) =>
`
export const ${actionCreatorName(name)} = (payload: ${type}) => ({
meta: {
delivery: 'grpc',
successType: '${actionCreatorSuccessName(name)}',
failureType: '${actionCreatorFailedName(name)}'
},
type: '${actionCreatorRequestName(name)}',
payload
})
`.trim()
export const generateFileHeader = () => `// @flow`.trim()
export default (schema: Schema) => {
const fileOutput = []
const output = []
const types = []
schema.services.forEach((service) => {
service.methods.forEach((method) => {
types.push(method.input_type)
output.push(generateActionCreator(method.name, method.input_type))
}, this)
}, this)
fileOutput.push(generateFileHeader())
fileOutput.push(`import { ${types.join(', ')} } from './SpiriGrpcServiceBridgeModule-flow-types'`)
return fileOutput.concat(output).join('\n\n')
}
| // @flow
import { actionCreatorName, actionCreatorRequestName, actionCreatorSuccessName, actionCreatorFailedName } from './utils'
import type { Schema } from './types'
export const generateActionCreator = (name: string, type: string) =>
`
export const ${actionCreatorName(name)} = (payload: ${type}) => ({
meta: {
delivery: 'grpc',
successType: '${actionCreatorSuccessName(name)}',
failureType: '${actionCreatorFailedName(name)}'
},
type: '${actionCreatorRequestName(name)}',
payload
})
`.trim()
export const generateFileHeader = () => `// @flow`.trim()
export default (schema: Schema) => {
const fileOutput = []
const output = []
const types = []
schema.services.forEach((service) => {
service.methods.forEach((method) => {
if (!types.some(type => type === method.input_type)) {
types.push(method.input_type)
}
output.push(generateActionCreator(method.name, method.input_type))
}, this)
}, this)
fileOutput.push(generateFileHeader())
fileOutput.push(`import type { ${types.join(', ')} } from './SpiriGrpcServiceBridgeModule-flow-types'`)
return fileOutput.concat(output).join('\n\n')
}
| Fix multiple import of the same type | :bug: Fix multiple import of the same type
| JavaScript | mit | drivr/react-native-grpc-bridge-generator,drivr/react-native-grpc-bridge-generator | ---
+++
@@ -24,13 +24,16 @@
const types = []
schema.services.forEach((service) => {
service.methods.forEach((method) => {
- types.push(method.input_type)
+ if (!types.some(type => type === method.input_type)) {
+ types.push(method.input_type)
+ }
+
output.push(generateActionCreator(method.name, method.input_type))
}, this)
}, this)
fileOutput.push(generateFileHeader())
- fileOutput.push(`import { ${types.join(', ')} } from './SpiriGrpcServiceBridgeModule-flow-types'`)
+ fileOutput.push(`import type { ${types.join(', ')} } from './SpiriGrpcServiceBridgeModule-flow-types'`)
return fileOutput.concat(output).join('\n\n')
} |
359ff48077d44f2632a8612e009f111b26798403 | ui/src/data_explorer/components/RawQueryEditor.js | ui/src/data_explorer/components/RawQueryEditor.js | import React, {PropTypes} from 'react'
const ENTER = 13
const ESCAPE = 27
const RawQueryEditor = React.createClass({
propTypes: {
query: PropTypes.shape({
rawText: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
}).isRequired,
onUpdate: PropTypes.func.isRequired,
},
getInitialState() {
return {
value: this.props.query.rawText,
}
},
componentWillReceiveProps(nextProps) {
if (nextProps.query.rawText !== this.props.query.rawText) {
this.setState({value: nextProps.query.rawText})
}
},
handleKeyDown(e) {
e.preventDefault()
if (e.keyCode === ENTER) {
this.handleUpdate();
} else if (e.keyCode === ESCAPE) {
this.setState({value: this.props.query.rawText}, () => {
this.editor.blur()
})
}
},
handleChange() {
this.setState({
value: this.editor.value,
})
},
handleUpdate() {
this.props.onUpdate(this.state.value)
},
render() {
const {value} = this.state
return (
<div className="raw-text">
<textarea
className="raw-text--field"
onChange={this.handleChange}
onKeyDown={this.handleKeyDown}
onBlur={this.handleUpdate}
ref={(editor) => this.editor = editor}
value={value}
placeholder="Blank query"
/>
</div>
)
},
})
export default RawQueryEditor
| import React, {PropTypes} from 'react'
const ENTER = 13
const ESCAPE = 27
const RawQueryEditor = React.createClass({
propTypes: {
query: PropTypes.shape({
rawText: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
}).isRequired,
onUpdate: PropTypes.func.isRequired,
},
getInitialState() {
return {
value: this.props.query.rawText,
}
},
componentWillReceiveProps(nextProps) {
if (nextProps.query.rawText !== this.props.query.rawText) {
this.setState({value: nextProps.query.rawText})
}
},
handleKeyDown(e) {
if (e.keyCode === ENTER) {
e.preventDefault()
this.handleUpdate();
} else if (e.keyCode === ESCAPE) {
this.setState({value: this.props.query.rawText}, () => {
this.editor.blur()
})
}
},
handleChange() {
this.setState({
value: this.editor.value,
})
},
handleUpdate() {
this.props.onUpdate(this.state.value)
},
render() {
const {value} = this.state
return (
<div className="raw-text">
<textarea
className="raw-text--field"
onChange={this.handleChange}
onKeyDown={this.handleKeyDown}
onBlur={this.handleUpdate}
ref={(editor) => this.editor = editor}
value={value}
placeholder="Blank query"
/>
</div>
)
},
})
export default RawQueryEditor
| Allow user to type :) | Allow user to type :)
| JavaScript | agpl-3.0 | brianbaker/chronograf,brianbaker/chronograf,brianbaker/chronograf,brianbaker/chronograf,brianbaker/chronograf | ---
+++
@@ -24,9 +24,8 @@
},
handleKeyDown(e) {
- e.preventDefault()
-
if (e.keyCode === ENTER) {
+ e.preventDefault()
this.handleUpdate();
} else if (e.keyCode === ESCAPE) {
this.setState({value: this.props.query.rawText}, () => { |
a3e8dc617849edcbd7ed2c6ca9807c122ef94793 | app/assets/javascripts/application.js | app/assets/javascripts/application.js | $(document).ready(function(){
// var turbolinks = require('turbolinks')
$("#walk-me-home").on("click", function(e){
e.preventDefault();
$.ajax({
url: "http://172.16.50.232:8080/start",
crossDomain : true,
})
.done(function(serverResponse){
$("#walk-me-home").hide();
$("#home-safely").show();
console.log(serverResponse + "This is the server response");
})
// need to add failure response
})
$("#home-safely").on("click", function(e){
console.log("I'm home!!")
e.preventDefault();
$.ajax({
url: "http://172.16.50.232:8080/end",
crossDomain : true,
})
.done(function(serverResponse){
$("#home-safely").hide();
$("#show-events").show();
console.log(serverResponse + "This is the server response");
})
})
});
| $(document).ready(function(){
// var turbolinks = require('turbolinks')
$("#walk-me-home").on("click", function(e){
e.preventDefault();
$.ajax({
url: "/sms/text_friend"
})
.done(function(serverResponse){
console.log(serverResponse + " This is the server response");
})
.fail(function(serverResponse){
console.log("Request failed");
})
$.ajax({
url: "http://172.16.50.232:8080/start",
crossDomain : true,
})
.done(function(serverResponse){
$("#walk-me-home").hide();
$("#home-safely").show();
console.log(serverResponse + "This is the server response");
})
// need to add failure response
})
$("#home-safely").on("click", function(e){
console.log("I'm home!!")
e.preventDefault();
$.ajax({
url: "http://172.16.50.232:8080/end",
crossDomain : true,
})
.done(function(serverResponse){
$("#home-safely").hide();
$("#show-events").show();
console.log(serverResponse + "This is the server response");
})
})
});
| Add ajax call for sms script | Add ajax call for sms script
| JavaScript | mit | ShawnTe/guardian,ShawnTe/guardian,ShawnTe/guardian | ---
+++
@@ -5,6 +5,15 @@
$("#walk-me-home").on("click", function(e){
e.preventDefault();
+ $.ajax({
+ url: "/sms/text_friend"
+ })
+ .done(function(serverResponse){
+ console.log(serverResponse + " This is the server response");
+ })
+ .fail(function(serverResponse){
+ console.log("Request failed");
+ })
$.ajax({
url: "http://172.16.50.232:8080/start",
crossDomain : true,
@@ -28,7 +37,7 @@
$("#home-safely").hide();
$("#show-events").show();
console.log(serverResponse + "This is the server response");
-
+
})
})
|
0786e2f7dfad739ca41ee6a408312fe4dd7e5d26 | app/assets/javascripts/graphs/util.js | app/assets/javascripts/graphs/util.js |
function renderWaiting(element) {
document.getElementById(element).innerHTML = "<i class='icon-spinner icon-spin'>"
}
function unrenderWaiting() {
$(".icon-spinner").hide()
}
function renderError(element, error, detail) {
error_alert = "<div class='alert alert-danger'>"+error
if (detail) { error_alert += "<br/>"+detail }
error_alert += "</div>"
document.getElementById(element).innerHTML = error_alert
}
function metricURL(base, start, stop, step){
return base+"&start="+start+"&stop="+stop+"&step="+step
}
function stopButtonClick() {
stopUpdates()
$("#autoplay_stop").hide()
$("#autoplay_play").show()
}
|
function renderWaiting(element) {
document.getElementById(element).innerHTML = "<i class='icon-spinner icon-spin'>"
}
function unrenderWaiting() {
$(".icon-spinner").hide()
}
function renderError(element, error, detail) {
error_alert = "<div class='alert alert-danger'>"+error
if (detail) { error_alert += "<br/>"+detail }
error_alert += "</div>"
document.getElementById(element).innerHTML = error_alert
}
function metricURL(base, start, stop, step){
return base+"&start="+start+"&stop="+stop+"&step="+step
}
function stopButtonClick() {
stopUpdates()
$("#autoplay_stop").hide()
$("#autoplay_play").show()
}
function stopAll() {
stopUpdates()
stopButtonClick()
unrenderWaiting()
}
| Call all stopping points on error: stop updates, stop button change, and remove 'waiting' button | Call all stopping points on error: stop updates, stop button change, and remove 'waiting' button
pending isolation to stop one graph
| JavaScript | bsd-3-clause | machiavellian/machiavelli,machiavellian/machiavelli,machiavellian/machiavelli,machiavellian/machiavelli,glasnt/machiavelli,glasnt/machiavelli,glasnt/machiavelli,glasnt/machiavelli | ---
+++
@@ -23,4 +23,8 @@
$("#autoplay_stop").hide()
$("#autoplay_play").show()
}
-
+function stopAll() {
+ stopUpdates()
+ stopButtonClick()
+ unrenderWaiting()
+} |
73c2a1d0ae61f1c3e9016782d275640c806289d1 | ui/.eslintrc.js | ui/.eslintrc.js | module.exports = {
parser: "@typescript-eslint/parser",
parserOptions: {
ecmaVersion: 2020,
sourceType: "module",
ecmaFeatures: {
jsx: true
}
},
settings: {
react: {
version: "detect"
}
},
extends: [
"plugin:react/recommended",
"plugin:react-hooks/recommended",
"plugin:@typescript-eslint/recommended",
],
rules: {
"@typescript-eslint/array-type": [
"warn",
{
"default": "array"
}
],
"@typescript-eslint/semi": [ "warn", "always" ],
"@typescript-eslint/no-inferrable-types": 0,
"max-len": [
"warn",
{
"code": 120
}
],
"no-trailing-spaces": [
"warn",
{
"skipBlankLines": true
}
],
"no-multiple-empty-lines": [
"warn",
{
"max": 2
}
],
"quotes": [ "warn", "single" ],
"jsx-quotes": [ "warn", "prefer-double" ]
}
};
| module.exports = {
parser: "@typescript-eslint/parser",
parserOptions: {
ecmaVersion: 2020,
sourceType: "module",
ecmaFeatures: {
jsx: true
}
},
settings: {
react: {
version: "detect"
}
},
extends: [
"plugin:react/recommended",
"plugin:react-hooks/recommended",
"plugin:@typescript-eslint/recommended",
],
rules: {
"@typescript-eslint/array-type": [
"warn",
{
"default": "array"
}
],
"@typescript-eslint/semi": [ "warn", "always" ],
"@typescript-eslint/no-inferrable-types": 0,
"max-len": [
"warn",
{
"code": 120
}
],
"no-trailing-spaces": [
"warn",
{
"skipBlankLines": true
}
],
"no-multiple-empty-lines": [
"warn",
{
"max": 2
}
],
"quotes": [ "warn", "single" ],
"jsx-quotes": [ "warn", "prefer-double" ],
"object-curly-spacing": ["warn", "always"],
"no-multi-spaces": ["warn"]
}
};
| Add eslint rules for spacing | Add eslint rules for spacing
| JavaScript | apache-2.0 | dainst/idai-field-web,dainst/idai-field-web,dainst/idai-field-web | ---
+++
@@ -45,6 +45,8 @@
}
],
"quotes": [ "warn", "single" ],
- "jsx-quotes": [ "warn", "prefer-double" ]
+ "jsx-quotes": [ "warn", "prefer-double" ],
+ "object-curly-spacing": ["warn", "always"],
+ "no-multi-spaces": ["warn"]
}
}; |
728824228d99775ac51cccfef67399930385076d | src/windows/fileOpener2Proxy.js | src/windows/fileOpener2Proxy.js |
var cordova = require('cordova'),
fileOpener2 = require('./FileOpener2');
module.exports = {
open: function (successCallback, errorCallback, args) {
Windows.Storage.StorageFile.getFileFromPathAsync(args[0]).then(function (file) {
var options = new Windows.System.LauncherOptions();
options.displayApplicationPicker = true;
Windows.System.Launcher.launchFileAsync(file, options).then(function (success) {
if (success) {
successCallback();
} else {
errorCallback();
}
});
});
}
};
require("cordova/exec/proxy").add("FileOpener2", module.exports);
|
var cordova = require('cordova'),
fileOpener2 = require('./FileOpener2');
var schemes = [
{ protocol: 'ms-app', getFile: getFileFromApplicationUri },
{ protocol: 'file:///', getFile: getFileFromFileUri }
]
function getFileFromApplicationUri(uri) {
var applicationUri = new Windows.Foundation.Uri(uri);
return Windows.Storage.StorageFile.getFileFromApplicationUriAsync(applicationUri);
}
function getFileFromFileUri(uri) {
var path = Windows.Storage.ApplicationData.current.localFolder.path +
uri.substr(8);
return getFileFromNativePath(path);
}
function getFileFromNativePath(path) {
var nativePath = path.split("/").join("\\");
return Windows.Storage.StorageFile.getFileFromPathAsync(nativePath);
}
function getFileLoaderForScheme(path) {
var fileLoader = getFileFromNativePath;
schemes.some(function (scheme) {
return path.indexOf(scheme.protocol) === 0 ? ((fileLoader = scheme.getFile), true) : false;
});
return fileLoader;
}
module.exports = {
open: function (successCallback, errorCallback, args) {
var path = args[0];
var getFile = getFileLoaderForScheme(path);
getFile(path).then(function (file) {
var options = new Windows.System.LauncherOptions();
options.displayApplicationPicker = true;
Windows.System.Launcher.launchFileAsync(file, options).then(function (success) {
if (success) {
successCallback();
} else {
errorCallback();
}
});
}, function (errror) {
console.log("Error abriendo el archivo");
});
}
};
require("cordova/exec/proxy").add("FileOpener2", module.exports);
| Add suport for Windows Uri Schemes | Add suport for Windows Uri Schemes
| JavaScript | mit | marceldurchholz/bb180scanner,napolitano/cordova-plugin-file-opener3,pwlin/cordova-plugin-file-opener2,pwlin/cordova-plugin-file-opener2,napolitano/cordova-plugin-file-opener3,napolitano/cordova-plugin-file-opener3,marceldurchholz/bb180scanner | ---
+++
@@ -2,13 +2,51 @@
var cordova = require('cordova'),
fileOpener2 = require('./FileOpener2');
+ var schemes = [
+ { protocol: 'ms-app', getFile: getFileFromApplicationUri },
+ { protocol: 'file:///', getFile: getFileFromFileUri }
+ ]
+
+ function getFileFromApplicationUri(uri) {
+ var applicationUri = new Windows.Foundation.Uri(uri);
+
+ return Windows.Storage.StorageFile.getFileFromApplicationUriAsync(applicationUri);
+ }
+
+ function getFileFromFileUri(uri) {
+ var path = Windows.Storage.ApplicationData.current.localFolder.path +
+ uri.substr(8);
+
+ return getFileFromNativePath(path);
+ }
+
+ function getFileFromNativePath(path) {
+ var nativePath = path.split("/").join("\\");
+
+ return Windows.Storage.StorageFile.getFileFromPathAsync(nativePath);
+ }
+
+ function getFileLoaderForScheme(path) {
+ var fileLoader = getFileFromNativePath;
+
+ schemes.some(function (scheme) {
+ return path.indexOf(scheme.protocol) === 0 ? ((fileLoader = scheme.getFile), true) : false;
+ });
+
+ return fileLoader;
+ }
+
module.exports = {
open: function (successCallback, errorCallback, args) {
- Windows.Storage.StorageFile.getFileFromPathAsync(args[0]).then(function (file) {
- var options = new Windows.System.LauncherOptions();
+ var path = args[0];
+
+ var getFile = getFileLoaderForScheme(path);
+
+ getFile(path).then(function (file) {
+ var options = new Windows.System.LauncherOptions();
options.displayApplicationPicker = true;
-
+
Windows.System.Launcher.launchFileAsync(file, options).then(function (success) {
if (success) {
successCallback();
@@ -17,6 +55,8 @@
}
});
+ }, function (errror) {
+ console.log("Error abriendo el archivo");
});
}
|
c42f06a5502bd72d951b6f4258652ae2150aa5e2 | src/app/ui/routes/games/game/route.js | src/app/ui/routes/games/game/route.js | import { set } from "@ember/object";
import Route from "@ember/routing/route";
import InfiniteScrollOffsetMixin from "ui/routes/-mixins/routes/infinite-scroll/offset";
import FilterLanguagesMixin from "ui/routes/-mixins/routes/filter-languages";
import RefreshRouteMixin from "ui/routes/-mixins/routes/refresh";
export default Route.extend( InfiniteScrollOffsetMixin, FilterLanguagesMixin, RefreshRouteMixin, {
itemSelector: ".stream-item-component",
modelName: "twitchStream",
modelPreload: "preview.mediumLatest",
async model({ game }) {
const model = await this._super({ game });
return { game, model };
},
async fetchContent() {
const { model } = await this.model({});
return model;
},
setupController( controller, { game, model }, ...args ) {
this._super( controller, model, ...args );
set( controller, "game", game );
}
});
| import { get, set } from "@ember/object";
import Route from "@ember/routing/route";
import InfiniteScrollOffsetMixin from "ui/routes/-mixins/routes/infinite-scroll/offset";
import FilterLanguagesMixin from "ui/routes/-mixins/routes/filter-languages";
import RefreshRouteMixin from "ui/routes/-mixins/routes/refresh";
export default Route.extend( InfiniteScrollOffsetMixin, FilterLanguagesMixin, RefreshRouteMixin, {
itemSelector: ".stream-item-component",
modelName: "twitchStream",
modelPreload: "preview.mediumLatest",
async model({ game }) {
const model = await this._super({ game });
return { game, model };
},
async fetchContent() {
const game = get( this.controller, "game" );
const { model } = await this.model({ game });
return model;
},
setupController( controller, { game, model }, ...args ) {
this._super( controller, model, ...args );
set( controller, "game", game );
}
});
| Fix fetchContent game parameter in GamesGameRoute | Fix fetchContent game parameter in GamesGameRoute
Fixes #575
Caused by 50d95a1880a30ea697fa7784a85f787e37795493
| JavaScript | mit | bastimeyer/livestreamer-twitch-gui,streamlink/streamlink-twitch-gui,streamlink/streamlink-twitch-gui,chhe/livestreamer-twitch-gui,streamlink/streamlink-twitch-gui,bastimeyer/livestreamer-twitch-gui,bastimeyer/livestreamer-twitch-gui,chhe/livestreamer-twitch-gui,chhe/livestreamer-twitch-gui | ---
+++
@@ -1,4 +1,4 @@
-import { set } from "@ember/object";
+import { get, set } from "@ember/object";
import Route from "@ember/routing/route";
import InfiniteScrollOffsetMixin from "ui/routes/-mixins/routes/infinite-scroll/offset";
import FilterLanguagesMixin from "ui/routes/-mixins/routes/filter-languages";
@@ -17,7 +17,8 @@
},
async fetchContent() {
- const { model } = await this.model({});
+ const game = get( this.controller, "game" );
+ const { model } = await this.model({ game });
return model;
}, |
825e287d9bc7c6f6f7f4fea8d367e138496c18a2 | examples/ide/ide-toolbar.js | examples/ide/ide-toolbar.js | IDEToolbarType = {
parent: Gtk.Toolbar.type,
name: "IDEToolbar",
class_init: function(klass, prototype)
{
},
instance_init: function(klass)
{
this.new_button = actions.get_action("new").create_tool_item();
this.open_button = actions.get_action("open").create_tool_item();
this.save_button = actions.get_action("save").create_tool_item();
this.undo_button = actions.get_action("undo").create_tool_item();
this.redo_button = actions.get_action("redo").create_tool_item();
this.execute_button = actions.get_action("execute").create_tool_item();
this.insert(this.new_button, -1);
this.insert(this.open_button, -1);
this.insert(this.save_button, -1);
this.insert(new Gtk.SeparatorToolItem(), -1);
this.insert(this.undo_button, -1);
this.insert(this.redo_button, -1);
this.insert(new Gtk.SeparatorToolItem(), -1);
this.insert(this.execute_button, -1);
this.show_all();
}};
IDEToolbar = new GType(IDEToolbarType);
| IDEToolbarType = {
parent: Gtk.Toolbar.type,
name: "IDEToolbar",
instance_init: function(klass)
{
this.new_button = actions.get_action("new").create_tool_item();
this.open_button = actions.get_action("open").create_tool_item();
this.save_button = actions.get_action("save").create_tool_item();
this.undo_button = actions.get_action("undo").create_tool_item();
this.redo_button = actions.get_action("redo").create_tool_item();
this.execute_button = actions.get_action("execute").create_tool_item();
this.insert(this.new_button, -1);
this.insert(this.open_button, -1);
this.insert(this.save_button, -1);
this.insert(new Gtk.SeparatorToolItem(), -1);
this.insert(this.undo_button, -1);
this.insert(this.redo_button, -1);
this.insert(new Gtk.SeparatorToolItem(), -1);
this.insert(this.execute_button, -1);
this.show_all();
}};
IDEToolbar = new GType(IDEToolbarType);
| Remove some dead code in examples. | Remove some dead code in examples.
svn path=/trunk/; revision=409
| JavaScript | lgpl-2.1 | danilocesar/seed,danilocesar/seed,danilocesar/seed,danilocesar/seed,danilocesar/seed | ---
+++
@@ -1,10 +1,6 @@
IDEToolbarType = {
parent: Gtk.Toolbar.type,
name: "IDEToolbar",
- class_init: function(klass, prototype)
- {
-
- },
instance_init: function(klass)
{
this.new_button = actions.get_action("new").create_tool_item(); |
86ff4c83bc75b4f0d9892d22c8f4c9361a79871d | frontend/src/components/ResultItem.js | frontend/src/components/ResultItem.js | import React, { Component } from "react";
import ReactDOM from "react-dom";
export default class ResultItem extends Component {
componentDidUpdate() {
if (this.props.selected) {
ReactDOM.findDOMNode(this).scrollIntoView(false);
}
}
render() {
const { result, onClick, selected } = this.props;
return (
<li onClick={() => onClick(result)} className={selected ? 'selected' : ''}>
<img src={result.thumbnail} className="video-thumbnail" />
<div className="details">
<div className="name">
{result.name}
</div>
<div className="author">
{result.author}
</div>
</div>
</li>
);
}
}
| import React, { Component } from "react";
import ReactDOM from "react-dom";
export default class ResultItem extends Component {
componentDidUpdate() {
if (this.props.selected) {
const node = ReactDOM.findDOMNode(this)
if (node.scrollIntoViewIfNeeded) {
node.scrollIntoViewIfNeeded(false)
} else {
node.scrollIntoView();
}
}
}
render() {
const { result, onClick, selected } = this.props;
return (
<li onClick={() => onClick(result)} className={selected ? 'selected' : ''}>
<img src={result.thumbnail} className="video-thumbnail" />
<div className="details">
<div className="name">
{result.name}
</div>
<div className="author">
{result.author}
</div>
</div>
</li>
);
}
}
| Use beautiful scrolling if available | Use beautiful scrolling if available
| JavaScript | mit | cthit/playIT-python,cthit/playIT-python,cthit/playIT-python,cthit/playIT-python | ---
+++
@@ -4,7 +4,12 @@
export default class ResultItem extends Component {
componentDidUpdate() {
if (this.props.selected) {
- ReactDOM.findDOMNode(this).scrollIntoView(false);
+ const node = ReactDOM.findDOMNode(this)
+ if (node.scrollIntoViewIfNeeded) {
+ node.scrollIntoViewIfNeeded(false)
+ } else {
+ node.scrollIntoView();
+ }
}
}
render() { |
4c2cf5d93da371634d93f196ce489f486eea53b0 | app/javascript/app/components/share-menu/share-menu.js | app/javascript/app/components/share-menu/share-menu.js | import { connect } from 'react-redux';
import shareIcon from 'assets/icons/share.svg';
import facebookIcon from 'assets/icons/facebook.svg';
import twitterIcon from 'assets/icons/twitter.svg';
import mailIcon from 'assets/icons/mail.svg';
import linkIcon from 'assets/icons/link.svg';
import copy from 'copy-to-clipboard';
import Component from './share-menu-component';
const mapStateToProps = (state, { path }) => {
const url = location.origin + (path || location.pathname);
const copyUrl = () => copy(url);
const shareMenuOptions = [
{
label: 'Email',
icon: mailIcon,
link: `mailto:?subject=Climate%20Watch&body=${url}`
},
{
label: 'Facebook',
icon: facebookIcon,
link: `https://www.facebook.com/sharer/sharer.php?u=${url}`
},
{
label: 'Twitter',
icon: twitterIcon,
link: `https://twitter.com/intent/tweet?url=${url}`
},
{
label: 'Copy link',
icon: linkIcon,
action: copyUrl
}
];
return {
shareMenuOptions,
shareIcon
};
};
export default connect(mapStateToProps, null)(Component);
| import { connect } from 'react-redux';
import shareIcon from 'assets/icons/share.svg';
import facebookIcon from 'assets/icons/facebook.svg';
import twitterIcon from 'assets/icons/twitter.svg';
import mailIcon from 'assets/icons/mail.svg';
import linkIcon from 'assets/icons/link.svg';
import copy from 'copy-to-clipboard';
import Component from './share-menu-component';
const mapStateToProps = (state, { path }) => {
const url = location.origin + (path || location.pathname) + location.search;
const copyUrl = () => copy(url);
const shareMenuOptions = [
{
label: 'Email',
icon: mailIcon,
link: `mailto:?subject=Climate%20Watch&body=${url}`
},
{
label: 'Facebook',
icon: facebookIcon,
link: `https://www.facebook.com/sharer/sharer.php?u=${url}`
},
{
label: 'Twitter',
icon: twitterIcon,
link: `https://twitter.com/intent/tweet?url=${url}`
},
{
label: 'Copy link',
icon: linkIcon,
action: copyUrl
}
];
return {
shareMenuOptions,
shareIcon
};
};
export default connect(mapStateToProps, null)(Component);
| Add params to share url | Add params to share url
| JavaScript | mit | Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch | ---
+++
@@ -8,7 +8,7 @@
import Component from './share-menu-component';
const mapStateToProps = (state, { path }) => {
- const url = location.origin + (path || location.pathname);
+ const url = location.origin + (path || location.pathname) + location.search;
const copyUrl = () => copy(url);
const shareMenuOptions = [
{ |
2d20ad41e15b6d8f6b6cab2efb34ca3aca2e4058 | app/assets/javascripts/diamond/theses_list.js | app/assets/javascripts/diamond/theses_list.js | //= require diamond/thesis_menu
$(document).ready(function() {
$(".link-export").click(function() {
$(this).attr("href", $.clear_query_params($(this).attr("href"))+window.location.search);
});
$("button.select-all").click(function() {
$("button.button-checkbox", "div.theses-list").trigger("checkbox-change-state");
});
$("button.destroy-all").lazy_form_confirmable_action({
topic: 'confirmation_theses_delete',
success_action: function(obj, key, val) {
$("#thesis-"+key).remove();
}
});
$("button.deny-selected").lazy_form_confirmable_action({
topic: 'confirmation_theses_deny',
success_action: function(obj, key, value) {
$("#thesis-"+key).replaceWith($.parseHTML(value));
}
});
$("button.accept-selected").lazy_form_confirmable_action({
topic: 'confirmation_theses_accept',
success_action: function(obj, key, value) {
$("#thesis-"+key).replaceWith($.parseHTML(value));
}
});
});
$.widget( "core.per_page_paginator", $.core.loader, {
before_state_changed: function(ctxt, e) {
$("input[name='per_page']", ctxt).val($(e.currentTarget).html());
$("input[name='page']", ctxt).val(1);
}
}); | //= require diamond/thesis_menu
$(document).ready(function() {
$(".link-export").click(function() {
$(this).attr("href", $.clear_query_params($(this).attr("href"))+window.location.search);
});
$("button.select-all").click(function() {
$("button.button-checkbox", "div.theses-list").trigger("checkbox-change-state");
});
$("button.destroy-all").lazy_form_confirmable_action({
topic: 'confirmation_theses_delete',
success_action: function(obj, key, val) {
$("#thesis-"+key).remove();
}
});
$("button.deny-selected").lazy_form_confirmable_action({
topic: 'confirmation_theses_deny',
success_action: function(obj, key, value) {
$("#thesis-"+key).replaceWith($.parseHTML(value));
}
});
$("button.accept-selected").lazy_form_confirmable_action({
topic: 'confirmation_theses_accept',
success_action: function(obj, key, value) {
$("#thesis-"+key).replaceWith($.parseHTML(value));
}
});
}); | Remove unused part of code | Remove unused part of code
Change-Id: I2cc8c4b4ef6e4a5b3889edb1dd2fa1a9fc09bd94
| JavaScript | agpl-3.0 | Opensoftware/USI-Diamond,Opensoftware/USI-Diamond,Opensoftware/USI-Diamond | ---
+++
@@ -31,12 +31,3 @@
});
});
-
-$.widget( "core.per_page_paginator", $.core.loader, {
-
- before_state_changed: function(ctxt, e) {
- $("input[name='per_page']", ctxt).val($(e.currentTarget).html());
- $("input[name='page']", ctxt).val(1);
- }
-
-}); |
d9efbb1c15cb38c22d8ab3ba02f1d604a97e1525 | app/assets/javascripts/remote_consoles/vnc.js | app/assets/javascripts/remote_consoles/vnc.js | //= require jquery
//= require novnc-rails
//= require_tree ../locale
//= require gettext/all
$(function() {
var host = window.location.hostname;
var encrypt = window.location.protocol === 'https:';
var port = encrypt ? 443 : 80;
if (window.location.port) {
port = window.location.port;
}
// noVNC requires an empty canvas item
var canvas = document.createElement('canvas');
$('#remote-console').append(canvas);
var vnc = new RFB({
target: canvas,
encrypt: encrypt,
true_color: true,
local_cursor: true,
shared: true,
view_only: false,
onUpdateState: function(_, state, _, msg) {
if (['normal', 'loaded'].includes(state)) {
$('#connection-status').removeClass('label-danger label-warning').addClass('label-success');
$('#connection-status').text(__('Connected'));
} else if (state === 'disconnected') {
$('#connection-status').removeClass('label-success label-warning').addClass('label-danger');
$('#connection-status').text(__('Disconnected'));
console.error('VNC', msg);
}
},
});
$('#ctrlaltdel').click(vnc.sendCtrlAltDel);
vnc.connect(host, port, $('#remote-console').attr('data-secret'), $('#remote-console').attr('data-url'));
});
| //= require jquery
//= require novnc-rails
//= require_tree ../locale
//= require gettext/all
$(function() {
var host = window.location.hostname;
var encrypt = window.location.protocol === 'https:';
var port = encrypt ? 443 : 80;
if (window.location.port) {
port = window.location.port;
}
// noVNC requires an empty canvas item
var canvas = document.createElement('canvas');
$('#remote-console').append(canvas);
var vnc = new RFB({
target: canvas,
encrypt: encrypt,
true_color: true,
local_cursor: true,
shared: true,
view_only: false,
onUpdateState: function(_, state, _, msg) {
if (['normal', 'loaded'].indexOf(state) >= 0) {
$('#connection-status').removeClass('label-danger label-warning').addClass('label-success');
$('#connection-status').text(__('Connected'));
} else if (state === 'disconnected') {
$('#connection-status').removeClass('label-success label-warning').addClass('label-danger');
$('#connection-status').text(__('Disconnected'));
console.error('VNC', msg);
}
},
});
$('#ctrlaltdel').click(vnc.sendCtrlAltDel);
vnc.connect(host, port, $('#remote-console').attr('data-secret'), $('#remote-console').attr('data-url'));
});
| Replace function that IE11 does not support | Replace function that IE11 does not support
https://bugzilla.redhat.com/show_bug.cgi?id=1448104
| JavaScript | apache-2.0 | ManageIQ/manageiq-ui-classic,ManageIQ/manageiq-ui-classic,ManageIQ/manageiq-ui-classic,ManageIQ/manageiq-ui-classic | ---
+++
@@ -23,7 +23,7 @@
shared: true,
view_only: false,
onUpdateState: function(_, state, _, msg) {
- if (['normal', 'loaded'].includes(state)) {
+ if (['normal', 'loaded'].indexOf(state) >= 0) {
$('#connection-status').removeClass('label-danger label-warning').addClass('label-success');
$('#connection-status').text(__('Connected'));
} else if (state === 'disconnected') { |
3fcc239f42e43827f63fc6feddcf1684ef8afeff | ember/app/components/comments-list.js | ember/app/components/comments-list.js | import { inject as service } from '@ember/service';
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { task } from 'ember-concurrency';
export default class CommentsList extends Component {
@service account;
@service ajax;
@tracked addCommentText = '';
@(task(function* () {
let id = this.flightId;
let text = this.addCommentText;
let user = this.get('account.user');
yield this.ajax.request(`/api/flights/${id}/comments`, { method: 'POST', json: { text } });
this.addCommentText = '';
this.comments.pushObject({ text, user });
}).drop())
addCommentTask;
}
| import { inject as service } from '@ember/service';
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { task } from 'ember-concurrency';
export default class CommentsList extends Component {
@service account;
@service ajax;
@tracked addCommentText = '';
@(task(function* () {
let id = this.flightId;
let text = this.addCommentText;
let { user } = this.account;
yield this.ajax.request(`/api/flights/${id}/comments`, { method: 'POST', json: { text } });
this.addCommentText = '';
this.comments.pushObject({ text, user });
}).drop())
addCommentTask;
}
| Fix "this.get is not a function" issue | CommentsList: Fix "this.get is not a function" issue
| JavaScript | agpl-3.0 | skylines-project/skylines,skylines-project/skylines,skylines-project/skylines,skylines-project/skylines | ---
+++
@@ -13,7 +13,7 @@
@(task(function* () {
let id = this.flightId;
let text = this.addCommentText;
- let user = this.get('account.user');
+ let { user } = this.account;
yield this.ajax.request(`/api/flights/${id}/comments`, { method: 'POST', json: { text } });
|
ab565bbcba77a9b00ba1dc0d23ad915616865f26 | combat/js/script.js | combat/js/script.js | $j(document).ready(function(){
G = new Game();
$j("form#gamesetup").submit(function(e){
e.preventDefault(); //prevent submit
gameconfig = {
nbrPlayer: $j('select[name="nbrplayer"]').val()-0,
background_image : $j('select[name="background"]').val(),
plasma_amount : $j('select[name="plasma"]').val()-0,
timePool : $j('select[name="time_pool"]').val()*60,
turnTimePool : $j('select[name="time_turn"]').val()-0,
creaLimitNbr : $j('select[name="active_units"]').val()-0, //DP count as One
};
if( gameconfig.background_image == "random" ){
var index = Math.floor(Math.random() * ($j('select[name="background"] option').length - 1) ) + 2; // nth-child indices start at 1
gameconfig.background_image = $j('select[name="background"] option:nth-child(' + index + ")").attr("value");
}
G.loadGame(gameconfig);
return false; //prevent submit
});
}); | $j(document).ready(function(){
G = new Game();
$j("form#gamesetup").submit(function(e){
e.preventDefault(); //prevent submit
gameconfig = {
nbrPlayer: $j('select[name="nbrplayer"]').val()-0,
background_image : $j('select[name="background"]').val(),
plasma_amount : $j('select[name="plasma"]').val()-0,
timePool : $j('select[name="time_pool"]').val()*60,
turnTimePool : $j('select[name="time_turn"]').val()-0,
creaLimitNbr : $j('select[name="active_units"]').val()+1, //DP count as One
};
if( gameconfig.background_image == "random" ){
var index = Math.floor(Math.random() * ($j('select[name="background"] option').length - 1) ) + 2; // nth-child indices start at 1
gameconfig.background_image = $j('select[name="background"] option:nth-child(' + index + ")").attr("value");
}
G.loadGame(gameconfig);
return false; //prevent submit
});
}); | Change DP count in creature cap limit | Change DP count in creature cap limit
| JavaScript | agpl-3.0 | thamaranth/AncientBeast,FreezingMoon/AncientBeast,ShaneWalsh/AncientBeast,FreezingMoon/AncientBeast,thamaranth/AncientBeast,ShaneWalsh/AncientBeast,FreezingMoon/AncientBeast,FreezingMoon/AncientBeast | ---
+++
@@ -9,7 +9,7 @@
plasma_amount : $j('select[name="plasma"]').val()-0,
timePool : $j('select[name="time_pool"]').val()*60,
turnTimePool : $j('select[name="time_turn"]').val()-0,
- creaLimitNbr : $j('select[name="active_units"]').val()-0, //DP count as One
+ creaLimitNbr : $j('select[name="active_units"]').val()+1, //DP count as One
};
if( gameconfig.background_image == "random" ){ |
201e0f11f6f573f809006ee6eb0e641f156e6f87 | packages/accounts-password/package.js | packages/accounts-password/package.js | Package.describe({
summary: "Password support for accounts",
version: "1.1.8-rc.0"
});
Package.onUse(function(api) {
api.use('npm-bcrypt@=0.7.8_2');
api.use([
'accounts-base',
'srp',
'sha',
'ejson',
'ddp'
], ['client', 'server']);
// Export Accounts (etc) to packages using this one.
api.imply('accounts-base', ['client', 'server']);
api.use('email', ['server']);
api.use('random', ['server']);
api.use('check');
api.use('underscore');
api.use('ecmascript');
api.addFiles('email_templates.js', 'server');
api.addFiles('password_server.js', 'server');
api.addFiles('password_client.js', 'client');
});
Package.onTest(function(api) {
api.use(['accounts-password', 'tinytest', 'test-helpers', 'tracker',
'accounts-base', 'random', 'email', 'underscore', 'check',
'ddp', 'ecmascript']);
api.addFiles('password_tests_setup.js', 'server');
api.addFiles('password_tests.js', ['client', 'server']);
api.addFiles('email_tests_setup.js', 'server');
api.addFiles('email_tests.js', 'client');
});
| Package.describe({
summary: "Password support for accounts",
version: "1.1.8-rc.0"
});
Package.onUse(function(api) {
api.use('npm-bcrypt@0.8.5');
api.use([
'accounts-base',
'srp',
'sha',
'ejson',
'ddp'
], ['client', 'server']);
// Export Accounts (etc) to packages using this one.
api.imply('accounts-base', ['client', 'server']);
api.use('email', ['server']);
api.use('random', ['server']);
api.use('check');
api.use('underscore');
api.use('ecmascript');
api.addFiles('email_templates.js', 'server');
api.addFiles('password_server.js', 'server');
api.addFiles('password_client.js', 'client');
});
Package.onTest(function(api) {
api.use(['accounts-password', 'tinytest', 'test-helpers', 'tracker',
'accounts-base', 'random', 'email', 'underscore', 'check',
'ddp', 'ecmascript']);
api.addFiles('password_tests_setup.js', 'server');
api.addFiles('password_tests.js', ['client', 'server']);
api.addFiles('email_tests_setup.js', 'server');
api.addFiles('email_tests.js', 'client');
});
| Make accounts-password depend on the newest version of npm-bcrypt. | Make accounts-password depend on the newest version of npm-bcrypt.
| JavaScript | mit | mjmasn/meteor,DAB0mB/meteor,jdivy/meteor,DAB0mB/meteor,DAB0mB/meteor,nuvipannu/meteor,lorensr/meteor,chasertech/meteor,Hansoft/meteor,nuvipannu/meteor,chasertech/meteor,4commerce-technologies-AG/meteor,4commerce-technologies-AG/meteor,lorensr/meteor,chasertech/meteor,mjmasn/meteor,mjmasn/meteor,chasertech/meteor,4commerce-technologies-AG/meteor,jdivy/meteor,DAB0mB/meteor,chasertech/meteor,4commerce-technologies-AG/meteor,lorensr/meteor,4commerce-technologies-AG/meteor,Hansoft/meteor,nuvipannu/meteor,4commerce-technologies-AG/meteor,DAB0mB/meteor,Hansoft/meteor,mjmasn/meteor,jdivy/meteor,jdivy/meteor,lorensr/meteor,Hansoft/meteor,nuvipannu/meteor,chasertech/meteor,DAB0mB/meteor,mjmasn/meteor,nuvipannu/meteor,jdivy/meteor,nuvipannu/meteor,jdivy/meteor,jdivy/meteor,Hansoft/meteor,nuvipannu/meteor,mjmasn/meteor,4commerce-technologies-AG/meteor,chasertech/meteor,lorensr/meteor,lorensr/meteor,mjmasn/meteor,Hansoft/meteor,lorensr/meteor,Hansoft/meteor,DAB0mB/meteor | ---
+++
@@ -4,7 +4,7 @@
});
Package.onUse(function(api) {
- api.use('npm-bcrypt@=0.7.8_2');
+ api.use('npm-bcrypt@0.8.5');
api.use([
'accounts-base', |
5176eecf9c95596151e86f173e59f2820b337ec1 | amaranth-chrome-ext/src/content.js | amaranth-chrome-ext/src/content.js | const mlModelPath = chrome.runtime.getURL('assets/model/model.json');
const tokenizerPath = chrome.runtime.getURL('assets/tokenizer.json');
/** The entry point of the Chrome Extension. */
async function main() {
// Load tokenizer dictionary
const response = await fetch(tokenizerPath);
const tokenizerObj = await response.json();
const tokenizer = new Map(Object.entries(tokenizerObj));
// Attempt to load ML model
const model = await tf.loadLayersModel(mlModelPath);
const labeller = new CalorieLabeller(tokenizer, model);
}
main();
| const mlModelPath = chrome.runtime.getURL('assets/model/model.json');
const tokenizerPath = chrome.runtime.getURL('assets/tokenizer.json');
const dishNameSelector = '.menuItem-name';
/** The entry point of the Chrome Extension. */
async function main() {
// Load tokenizer dictionary
const response = await fetch(tokenizerPath);
const tokenizerObj = await response.json();
const tokenizer = new Map(Object.entries(tokenizerObj));
// Attempt to load ML model
const model = await tf.loadLayersModel(mlModelPath);
const labeller = new CalorieLabeller(tokenizer, model);
// Periodically check page to see if it has fully loaded.
// Modern web pages will often "load" in the technical sense, but often
// display a loading animation until dishes are actually populated.
const stateCheck = setInterval(() => {
if (document.querySelectorAll(dishNameSelector).length > 0) {
clearInterval(stateCheck);
for (const dishNameElem of document.querySelectorAll(dishNameSelector)) {
labelDish(dishNameElem, labeller);
}
}
}, 100);
}
/**
* Label a single dish as low, average, or high-calorie. This includes
* processing in the ML model, creating the label, and adding it to the DOM.
*
* The calorie label element will be added as a sibling to `dishNameElem` in the
* DOM, coming directly after it.
* @param {Element} dishNameElem DOM element that contains the dish name
* @param {CalorieLabeller} labeller Determines what labels to give dishes
*/
async function labelDish(dishNameElem, labeller) {
const dishName = dishNameElem.innerHTML;
const calorieLabel = labeller.label(dishName);
const calorieLabelElem = document.createElement('p');
calorieLabelElem.appendChild(document.createTextNode(calorieLabel));
dishNameElem.parentElement.appendChild(calorieLabelElem);
}
main();
| Add labelling for dishes on grubhub | Add labelling for dishes on grubhub
| JavaScript | apache-2.0 | googleinterns/amaranth,googleinterns/amaranth | ---
+++
@@ -1,5 +1,6 @@
const mlModelPath = chrome.runtime.getURL('assets/model/model.json');
const tokenizerPath = chrome.runtime.getURL('assets/tokenizer.json');
+const dishNameSelector = '.menuItem-name';
/** The entry point of the Chrome Extension. */
async function main() {
@@ -10,8 +11,37 @@
// Attempt to load ML model
const model = await tf.loadLayersModel(mlModelPath);
+ const labeller = new CalorieLabeller(tokenizer, model);
- const labeller = new CalorieLabeller(tokenizer, model);
+ // Periodically check page to see if it has fully loaded.
+ // Modern web pages will often "load" in the technical sense, but often
+ // display a loading animation until dishes are actually populated.
+ const stateCheck = setInterval(() => {
+ if (document.querySelectorAll(dishNameSelector).length > 0) {
+ clearInterval(stateCheck);
+ for (const dishNameElem of document.querySelectorAll(dishNameSelector)) {
+ labelDish(dishNameElem, labeller);
+ }
+ }
+ }, 100);
+}
+
+/**
+ * Label a single dish as low, average, or high-calorie. This includes
+ * processing in the ML model, creating the label, and adding it to the DOM.
+ *
+ * The calorie label element will be added as a sibling to `dishNameElem` in the
+ * DOM, coming directly after it.
+ * @param {Element} dishNameElem DOM element that contains the dish name
+ * @param {CalorieLabeller} labeller Determines what labels to give dishes
+ */
+async function labelDish(dishNameElem, labeller) {
+ const dishName = dishNameElem.innerHTML;
+ const calorieLabel = labeller.label(dishName);
+
+ const calorieLabelElem = document.createElement('p');
+ calorieLabelElem.appendChild(document.createTextNode(calorieLabel));
+ dishNameElem.parentElement.appendChild(calorieLabelElem);
}
main(); |
b285713cf6fc5f81f1a211283a95cf17c5801101 | src/components/GithubEditLink/index.js | src/components/GithubEditLink/index.js | import React, { PropTypes } from "react"
const GitHubEditLink = ({ baseUrl, fileName, ...props }) => {
const url = baseUrl + fileName
return (
<section {...props}>
{ "Bài viết sai chính tả? Có điểm chưa rõ ràng?" }
{ ' ' }
<a href={ url } target="_blank">
{ "Sửa bài viết trên Github" }
</a>
</section>
)
}
GitHubEditLink.propTypes = {
baseUrl: PropTypes.string.isRequired,
fileName: PropTypes.string.isRequired,
}
export default GitHubEditLink
| import React, { PropTypes } from "react"
const GitHubEditLink = ({ baseUrl, fileName, ...props }) => {
const url = baseUrl + fileName
return (
<section {...props}>
{ "Spotted typos or incorrect information?" }
{ ' ' }
<a href={ url } target="_blank">
{ "Send me a PR on Github" }
</a>
</section>
)
}
GitHubEditLink.propTypes = {
baseUrl: PropTypes.string.isRequired,
fileName: PropTypes.string.isRequired,
}
export default GitHubEditLink
| Change GIthub PR to English | UI: Change GIthub PR to English
| JavaScript | mit | thangngoc89/blog | ---
+++
@@ -5,10 +5,10 @@
return (
<section {...props}>
- { "Bài viết sai chính tả? Có điểm chưa rõ ràng?" }
+ { "Spotted typos or incorrect information?" }
{ ' ' }
<a href={ url } target="_blank">
- { "Sửa bài viết trên Github" }
+ { "Send me a PR on Github" }
</a>
</section>
) |
c80630704d96379369888252f5258fa5d5f45a32 | addon/components/markdown-to-html.js | addon/components/markdown-to-html.js | /* global showdown */
import Ember from 'ember';
import hbs from 'htmlbars-inline-precompile';
const { computed, get, Handlebars } = Ember;
const ShowdownComponent = Ember.Component.extend({
layout: hbs`{{html}}`,
markdown: '',
extensions: computed(function() {
return [];
}),
defaultOptionKeys: computed(function() {
return Object.keys(showdown.getDefaultOptions());
}).readOnly(),
html: computed('markdown', function() {
let showdownOptions = this.getProperties(get(this, 'defaultOptionKeys'));
for (let option in showdownOptions) {
if (showdownOptions.hasOwnProperty(option)) {
this.converter.setOption(option, showdownOptions[option]);
}
}
return new Handlebars.SafeString(this.converter.makeHtml(get(this, 'markdown')));
}).readOnly(),
didReceiveAttrs() {
this._super(...arguments);
let extensions = get(this, 'extensions');
if (typeof extensions === 'string') {
extensions = extensions.split(' ');
}
this.converter = new showdown.Converter({ extensions });
}
});
ShowdownComponent.reopenClass({
positionalParams: ['markdown']
});
export default ShowdownComponent;
| /* global showdown */
import Ember from 'ember';
import hbs from 'htmlbars-inline-precompile';
const { computed, get, Handlebars } = Ember;
const ShowdownComponent = Ember.Component.extend({
layout: hbs`{{html}}`,
markdown: '',
extensions: computed(function() {
return [];
}),
defaultOptionKeys: computed(function() {
return Object.keys(showdown.getDefaultOptions());
}).readOnly(),
html: computed('markdown', function() {
let showdownOptions = this.getProperties(get(this, 'defaultOptionKeys'));
for (let option in showdownOptions) {
if (showdownOptions.hasOwnProperty(option)) {
this.converter.setOption(option, showdownOptions[option]);
}
}
return new Handlebars.SafeString(this.converter.makeHtml(get(this, 'markdown')));
}).readOnly(),
createConverter() {
let extensions = get(this, 'extensions');
if (typeof extensions === 'string') {
extensions = extensions.split(' ');
}
this.converter = new showdown.Converter({ extensions });
},
didReceiveAttrs() {
this._super(...arguments);
this.createConverter();
}
});
ShowdownComponent.reopenClass({
positionalParams: ['markdown']
});
export default ShowdownComponent;
| Move converter creation into it's own function for easier overriding | Move converter creation into it's own function for easier overriding | JavaScript | mit | gcollazo/ember-cli-showdown,gcollazo/ember-cli-showdown | ---
+++
@@ -27,10 +27,8 @@
return new Handlebars.SafeString(this.converter.makeHtml(get(this, 'markdown')));
}).readOnly(),
-
- didReceiveAttrs() {
- this._super(...arguments);
-
+
+ createConverter() {
let extensions = get(this, 'extensions');
if (typeof extensions === 'string') {
@@ -38,6 +36,12 @@
}
this.converter = new showdown.Converter({ extensions });
+ },
+
+ didReceiveAttrs() {
+ this._super(...arguments);
+
+ this.createConverter();
}
});
|
ec27293afccf0fb5cbd1c1bdafc053cae0b7f3dd | src/core/views/Base.js | src/core/views/Base.js | import Backbone from 'backbone';
import Geppetto from 'backbone.geppetto';
class BaseView extends Backbone.View {
constructor(options) {
super(options);
if (!options.context || !(options.context instanceof Geppetto.Context)) {
throw new Error('Supply the correct context instance.');
}
this.context = options.context;
this.options = options;
}
render() {
return this;
}
destroy() {
this.context = undefined;
this.options = undefined;
delete(this.context);
delete(this.options);
}
}
export default BaseView;
| import Backbone from 'backbone';
import Geppetto from 'backbone.geppetto';
/**
* A generic view which inherits from the Backbone.View. This view is ment to
* be used by all specific views in a project. It stores the references to all
* given constructor options in the `.options` property. It also tests for and
* stores the reference to the Backbone.Geppetto Context instance.
*
* @class Base-View
* @example
* import BaseView from 'picnic/core/views/Base';
*
* new BaseView({
* el: document.body,
* context: app.context
* }).render();
*/
class View extends Backbone.View {
/**
* Creates an instance of this view.
*
* @constructor
* @param {object} options The settings for the view.
* @param {context} options.context The reference to the
* backbone.geppetto context.
* @param {DOMElement|$Element} options.el the element reference for a
* backbone.view.
*/
constructor(options) {
super(options);
if (!options.context || !(options.context instanceof Geppetto.Context)) {
throw new Error('Supply the correct context instance.');
}
this.context = options.context;
this.options = options;
}
/**
* This renders the content of this view and all models of the collection.
*
* @return {view} is the instance of this view.
*/
render() {
return this;
}
/**
* Destroys this view.
*/
destroy() {
this.context = undefined;
this.options = undefined;
delete(this.context);
delete(this.options);
}
}
export default View;
| Add documentation for base view | Add documentation for base view
| JavaScript | mit | moccu/picnic,moccu/picnic | ---
+++
@@ -1,7 +1,34 @@
import Backbone from 'backbone';
import Geppetto from 'backbone.geppetto';
-class BaseView extends Backbone.View {
+
+/**
+ * A generic view which inherits from the Backbone.View. This view is ment to
+ * be used by all specific views in a project. It stores the references to all
+ * given constructor options in the `.options` property. It also tests for and
+ * stores the reference to the Backbone.Geppetto Context instance.
+ *
+ * @class Base-View
+ * @example
+ * import BaseView from 'picnic/core/views/Base';
+ *
+ * new BaseView({
+ * el: document.body,
+ * context: app.context
+ * }).render();
+ */
+class View extends Backbone.View {
+
+ /**
+ * Creates an instance of this view.
+ *
+ * @constructor
+ * @param {object} options The settings for the view.
+ * @param {context} options.context The reference to the
+ * backbone.geppetto context.
+ * @param {DOMElement|$Element} options.el the element reference for a
+ * backbone.view.
+ */
constructor(options) {
super(options);
@@ -13,10 +40,18 @@
this.options = options;
}
+ /**
+ * This renders the content of this view and all models of the collection.
+ *
+ * @return {view} is the instance of this view.
+ */
render() {
return this;
}
+ /**
+ * Destroys this view.
+ */
destroy() {
this.context = undefined;
this.options = undefined;
@@ -25,4 +60,4 @@
}
}
-export default BaseView;
+export default View; |
2c197cc48a9ec51c7456d5fc6e43ae4f65659e8e | client/templates/posts/post_submit.js | client/templates/posts/post_submit.js | Template.postSubmit.events({
'submit form': function (event) {
event.preventDefault();
console.log('submitted');
var post = {
url: $(event.target).find('[name=url]').val(),
title: $(event.target).find('[name=title]').val()
}
post._id = Posts.insert(post);
Router.go('postPage', post);
}
});
| Template.postSubmit.events({
'submit form': function (event) {
event.preventDefault();
console.log('submitted');
var post = {
url: $(event.target).find('[name=url]').val(),
title: $(event.target).find('[name=title]').val()
}
Meteor.call('postInsert', post, function(error, result) {
// display the error to the user and abort
if (error) {
return alert(error.reason):
}
}):
Router.go('postPage', { _id: result._id });
}
});
| Use Meteor method to insert post. | Use Meteor method to insert post.
| JavaScript | mit | meteorcrowd/telescope,meteorcrowd/telescope | ---
+++
@@ -8,7 +8,13 @@
title: $(event.target).find('[name=title]').val()
}
- post._id = Posts.insert(post);
- Router.go('postPage', post);
+ Meteor.call('postInsert', post, function(error, result) {
+ // display the error to the user and abort
+ if (error) {
+ return alert(error.reason):
+ }
+ }):
+
+ Router.go('postPage', { _id: result._id });
}
}); |
8d9a29380eee6060ba16b2a054f22987715871ce | api/batch.api.js | api/batch.api.js | var vow = require('vow');
var ApiMethod = require('../lib/api-method');
var ApiError = require('../lib/api-error');
/**
* @typedef {Object} BatchApiMethod
* @property {String} method Method name.
* @property {Object} params Method params.
*
* @example
* {
* method: 'hello',
* params: {name: 'Master'}
* }
*/
module.exports = new ApiMethod('baby-loris-api-batch')
.setDescription('Executes a set of methods')
.setOption('hiddenOnDocPage', true)
.addParam({
// Methods are passed as an array of BatchApiMethod objects.
name: 'methods',
type: 'Array',
description: 'Set of methods with a data',
required: true
})
.setAction(function (params, api) {
return vow.allResolved(params.methods.map(function (method) {
return api.exec(method.method, method.params);
})).then(function (response) {
return response.map(function (promise) {
var data = promise.valueOf();
if (promise.isFulfilled()) {
return {
data: data
};
} else {
return {
error: {
type: data.type || ApiError.INTERNAL_ERROR,
message: data.message
}
};
}
});
});
});
| var vow = require('vow');
var ApiMethod = require('../lib/api-method');
var ApiError = require('../lib/api-error');
/**
* @typedef {Object} BatchApiMethod
* @property {String} method Method name.
* @property {Object} params Method params.
*
* @example
* {
* method: 'hello',
* params: {name: 'Master'}
* }
*/
module.exports = new ApiMethod('baby-loris-api-batch')
.setDescription('Executes a set of methods')
.setOption('hiddenOnDocPage', true)
.addParam({
// Methods are passed as an array of BatchApiMethod objects.
name: 'methods',
type: 'Array',
description: 'Set of methods with a data',
required: true
})
.setAction(function (params, api) {
return vow.allResolved(params.methods.map(function (method) {
return api.exec(method.method, method.params);
})).then(function (response) {
return response.map(function (promise) {
var data = promise.valueOf();
if (promise.isFulfilled()) {
return {
data: data
};
}
return {
error: {
type: data.type || ApiError.INTERNAL_ERROR,
message: data.message
}
};
});
});
});
| Remove else in batch method | Remove else in batch method
| JavaScript | mit | baby-loris/bla,baby-loris/bla | ---
+++
@@ -31,18 +31,19 @@
})).then(function (response) {
return response.map(function (promise) {
var data = promise.valueOf();
+
if (promise.isFulfilled()) {
return {
data: data
};
- } else {
- return {
- error: {
- type: data.type || ApiError.INTERNAL_ERROR,
- message: data.message
- }
- };
}
+
+ return {
+ error: {
+ type: data.type || ApiError.INTERNAL_ERROR,
+ message: data.message
+ }
+ };
});
});
}); |
e9aef649b1353382de5fea86b4805ae5414f418d | jest.config.js | jest.config.js | module.exports = {
verbose: true,
collectCoverage: true,
collectCoverageFrom: [
'libs/**/*.{js,jsx}',
'source/**/*.{js,jsx}',
],
roots: [
'<rootDir>/tests/',
],
moduleNameMapper: {
'^.+\\.(css|scss)$': 'identity-obj-proxy',
},
setupFiles: ['./tests/jestsetup.js'],
snapshotSerializers: ['enzyme-to-json/serializer'],
};
| module.exports = {
verbose: true,
collectCoverage: true,
collectCoverageFrom: [
'libs/**/*.{js,jsx}',
'source/**/*.{js,jsx}',
'!source/views/index.server.js',
],
roots: [
'<rootDir>/tests/',
],
moduleNameMapper: {
'^.+\\.(css|scss)$': 'identity-obj-proxy',
},
setupFiles: ['./tests/jestsetup.js'],
snapshotSerializers: ['enzyme-to-json/serializer'],
};
| Exclude ssr build from coverage | Exclude ssr build from coverage
| JavaScript | mit | NAlexandrov/yaw,NAlexandrov/yaw | ---
+++
@@ -4,6 +4,7 @@
collectCoverageFrom: [
'libs/**/*.{js,jsx}',
'source/**/*.{js,jsx}',
+ '!source/views/index.server.js',
],
roots: [
'<rootDir>/tests/', |
ace0704df863837929a7e499e20c1530fcdccc4f | js/lowlight.js | js/lowlight.js | "use strict";
/*
NOT a general purpose escaper! Only valid when *content* of a tag, not within an attribute.
*/
function escape(code) {
return code
.replace("&", "&", "g")
.replace("<", "<", "g")
.replace(">", ">", "g");
}
function lowlight(lang, lexer, code) {
var ret = "";
var lex = lexer.CeylonLexer(lexer.StringCharacterStream(code));
var cur;
while ((cur = lex.nextToken()) != null) {
if (cur.type.string == "whitespace") {
/*
don’t put whitespace in a span –
this way, styles can use CSS selectors
based on the immediately previous node
without worrying about whitespace
*/
ret += cur.text;
} else {
ret += "<span class=\"";
ret += cur.type.string;
ret += "\">";
ret += escape(cur.text);
ret += "</span>";
}
}
return ret;
}
| "use strict";
/*
NOT a general purpose escaper! Only valid when *content* of a tag, not within an attribute.
*/
function escape(code) {
return code
.replace("&", "&", "g")
.replace("<", "<", "g")
.replace(">", ">", "g");
}
function lowlight(lang, lexer, code) {
var ret = "";
var lex = lexer.CeylonLexer(lexer.StringCharacterStream(code));
var cur;
while ((cur = lex.nextToken()) != null) {
if (cur.type.string == "whitespace") {
/*
don’t put whitespace in a span –
this way, styles can use CSS selectors
based on the immediately previous node
without worrying about whitespace
*/
ret += cur.text;
} else {
ret += "<span class=\"";
for (var type in cur.type.__proto__.getT$all()) {
if (type === undefined) break;
ret += type.replace(/.*:/, "");
if (type == "ceylon.lexer.core::TokenType") break;
ret += " ";
}
ret += "\">";
ret += escape(cur.text);
ret += "</span>";
}
}
return ret;
}
| Add supertypes of token types to span classes | Add supertypes of token types to span classes
This allows styles to select `.KeywordType` instead of enumerating all
keyword types “manually”.
| JavaScript | apache-2.0 | lucaswerkmeister/ColorTrompon,lucaswerkmeister/ColorTrompon | ---
+++
@@ -25,7 +25,12 @@
ret += cur.text;
} else {
ret += "<span class=\"";
- ret += cur.type.string;
+ for (var type in cur.type.__proto__.getT$all()) {
+ if (type === undefined) break;
+ ret += type.replace(/.*:/, "");
+ if (type == "ceylon.lexer.core::TokenType") break;
+ ret += " ";
+ }
ret += "\">";
ret += escape(cur.text);
ret += "</span>"; |
3c11107f551e703982ebf8e7af2be0b7ccfe3d4e | functions/strings/addslashes.js | functions/strings/addslashes.js | function addslashes (str) {
// http://kevin.vanzonneveld.net
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Ates Goral (http://magnetiq.com)
// + improved by: marrtins
// + improved by: Nate
// + improved by: Onno Marsman
// + input by: Denny Wardhana
// + improved by: Brett Zamir (http://brett-zamir.me)
// + improved by: Oskar Larsson Hgfeldt (http://oskar-lh.name/)
// * example 1: addslashes("kevin's birthday");
// * returns 1: 'kevin\'s birthday'
return (str+'').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
} | function addslashes (str) {
// http://kevin.vanzonneveld.net
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Ates Goral (http://magnetiq.com)
// + improved by: marrtins
// + improved by: Nate
// + improved by: Onno Marsman
// + input by: Denny Wardhana
// + improved by: Brett Zamir (http://brett-zamir.me)
// + improved by: Oskar Larsson Högfeldt (http://oskar-lh.name/)
// * example 1: addslashes("kevin's birthday");
// * returns 1: 'kevin\'s birthday'
return (str+'').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
} | Switch to UTF-8 encoding of file to reflect contributor's name correctly | Switch to UTF-8 encoding of file to reflect contributor's name correctly
| JavaScript | mit | FlorinDragotaExpertvision/phpjs,Mazbaul/phpjs,FlorinDragotaExpertvision/phpjs,janschoenherr/phpjs,janschoenherr/phpjs,mojaray2k/phpjs,hirak/phpjs,w35l3y/phpjs,kvz/phpjs,imshibaji/phpjs,J2TeaM/phpjs,MartinReidy/phpjs,revanthpobala/phpjs,FlorinDragotaExpertvision/phpjs,strrife/phpjs,mojaray2k/phpjs,janschoenherr/phpjs,davidgruebl/phpjs,davidgruebl/phpjs,davidgruebl/phpjs,w35l3y/phpjs,revanthpobala/phpjs,praveenscience/phpjs,davidgruebl/phpjs,ajenkul/phpjs,Mazbaul/phpjs,imshibaji/phpjs,hirak/phpjs,VicAMMON/phpjs,cigraphics/phpjs,praveenscience/phpjs,chand3040/phpjs,praveenscience/phpjs,ajenkul/phpjs,VicAMMON/phpjs,VicAMMON/phpjs,MartinReidy/phpjs,mojaray2k/phpjs,w35l3y/phpjs,J2TeaM/phpjs,strrife/phpjs,w35l3y/phpjs,strrife/phpjs,mojaray2k/phpjs,imshibaji/phpjs,imshibaji/phpjs,J2TeaM/phpjs,MartinReidy/phpjs,revanthpobala/phpjs,strrife/phpjs,janschoenherr/phpjs,cigraphics/phpjs,ajenkul/phpjs,praveenscience/phpjs,J2TeaM/phpjs,hirak/phpjs,FlorinDragotaExpertvision/phpjs,Mazbaul/phpjs,chand3040/phpjs,hirak/phpjs,kvz/phpjs,cigraphics/phpjs,kvz/phpjs,VicAMMON/phpjs,MartinReidy/phpjs,kvz/phpjs,revanthpobala/phpjs,cigraphics/phpjs,Mazbaul/phpjs,ajenkul/phpjs,chand3040/phpjs | ---
+++
@@ -7,7 +7,7 @@
// + improved by: Onno Marsman
// + input by: Denny Wardhana
// + improved by: Brett Zamir (http://brett-zamir.me)
- // + improved by: Oskar Larsson Hgfeldt (http://oskar-lh.name/)
+ // + improved by: Oskar Larsson Högfeldt (http://oskar-lh.name/)
// * example 1: addslashes("kevin's birthday");
// * returns 1: 'kevin\'s birthday'
|
09d29617c57f8c68f2764eec253020d0af0a602a | karma-local.conf.js | karma-local.conf.js | module.exports = function(config) {
'use strict';
require('./karma.conf')({
set: function(base) {
base.browsers = [
'Firefox',
'Opera',
'PhantomJS',
'Safari'
];
config.set(base);
}
});
};
| module.exports = function(config) {
'use strict';
require('./karma.conf')({
set: function(base) {
base.browsers = [
'Firefox',
'Chrome',
'Opera',
'PhantomJS',
'Safari'
];
config.set(base);
}
});
};
| Add Chrome to local test runner. | Add Chrome to local test runner.
| JavaScript | mit | JamieMason/Jasmine-Matchers,JamieMason/Jasmine-Matchers | ---
+++
@@ -8,6 +8,7 @@
base.browsers = [
'Firefox',
+ 'Chrome',
'Opera',
'PhantomJS',
'Safari' |
f06fbb8544144ed44bf83ae0e46d32785876dcf2 | config/appConfig.js | config/appConfig.js | 'use strict';
/*
* All app specific configuration
*/
const config = {};
config.gameLocation = {
country : 'Sweden',
lat : '59.751429',
lon : '15.198645'
};
config.historyLines = 30;
config.chunkLength = 10;
config.userVerify = false;
module.exports = config;
| 'use strict';
/*
* All app specific configuration
*/
const config = {};
config.gameLocation = {
country : 'Sweden',
lat : '59.751429',
lon : '15.198645'
};
config.historyLines = 80;
config.chunkLength = 10;
config.userVerify = false;
module.exports = config;
| Increase of default amount of messages sent in history | Increase of default amount of messages sent in history
| JavaScript | apache-2.0 | yxeri/roleTerminal,stanislavb/roleOOC,yxeri/roleTerminal,yxeri/roleOOC,yxeri/roleOOC,yxeri/roleTerminal,stanislavb/roleOOC,yxeri/roleOOC | ---
+++
@@ -12,7 +12,7 @@
lon : '15.198645'
};
-config.historyLines = 30;
+config.historyLines = 80;
config.chunkLength = 10;
|
5f4d47353b97ccb30c9ade1ab555d959a8037786 | blueprints/initializer-test/index.js | blueprints/initializer-test/index.js | 'use strict';
const testInfo = require('ember-cli-test-info');
const stringUtils = require('ember-cli-string-utils');
const useTestFrameworkDetector = require('../test-framework-detector');
module.exports = useTestFrameworkDetector({
description: 'Generates an initializer unit test.',
locals: function(options) {
return {
friendlyTestName: testInfo.name(options.entity.name, 'Unit', 'Initializer'),
dasherizedModulePrefix: stringUtils.dasherize(options.project.config().modulePrefix)
};
}
});
| 'use strict';
const stringUtils = require('ember-cli-string-utils');
const useTestFrameworkDetector = require('../test-framework-detector');
module.exports = useTestFrameworkDetector({
description: 'Generates an initializer unit test.',
locals: function(options) {
return {
friendlyTestName: ['Unit', 'Initializer', options.entity.name].join(' | '),
dasherizedModulePrefix: stringUtils.dasherize(options.project.config().modulePrefix)
};
}
});
| Use `options.entity-name` for test description | blueprints/initializer-test: Use `options.entity-name` for test description
| JavaScript | mit | sandstrom/ember.js,kennethdavidbuck/ember.js,intercom/ember.js,fpauser/ember.js,cibernox/ember.js,fpauser/ember.js,kellyselden/ember.js,runspired/ember.js,bekzod/ember.js,elwayman02/ember.js,thoov/ember.js,sly7-7/ember.js,Turbo87/ember.js,thoov/ember.js,miguelcobain/ember.js,mike-north/ember.js,karthiick/ember.js,GavinJoyce/ember.js,kellyselden/ember.js,Serabe/ember.js,gfvcastro/ember.js,tildeio/ember.js,mike-north/ember.js,twokul/ember.js,kennethdavidbuck/ember.js,qaiken/ember.js,jaswilli/ember.js,gfvcastro/ember.js,mfeckie/ember.js,sly7-7/ember.js,givanse/ember.js,givanse/ember.js,stefanpenner/ember.js,qaiken/ember.js,xiujunma/ember.js,xiujunma/ember.js,jaswilli/ember.js,mixonic/ember.js,miguelcobain/ember.js,karthiick/ember.js,sly7-7/ember.js,mfeckie/ember.js,Turbo87/ember.js,emberjs/ember.js,stefanpenner/ember.js,xiujunma/ember.js,csantero/ember.js,cibernox/ember.js,runspired/ember.js,Gaurav0/ember.js,elwayman02/ember.js,kennethdavidbuck/ember.js,csantero/ember.js,mixonic/ember.js,Gaurav0/ember.js,mfeckie/ember.js,kanongil/ember.js,gfvcastro/ember.js,Gaurav0/ember.js,kennethdavidbuck/ember.js,Serabe/ember.js,asakusuma/ember.js,runspired/ember.js,tildeio/ember.js,GavinJoyce/ember.js,emberjs/ember.js,asakusuma/ember.js,miguelcobain/ember.js,sandstrom/ember.js,karthiick/ember.js,jaswilli/ember.js,GavinJoyce/ember.js,jaswilli/ember.js,cibernox/ember.js,givanse/ember.js,twokul/ember.js,qaiken/ember.js,bekzod/ember.js,Turbo87/ember.js,xiujunma/ember.js,fpauser/ember.js,intercom/ember.js,givanse/ember.js,Gaurav0/ember.js,runspired/ember.js,twokul/ember.js,mfeckie/ember.js,Serabe/ember.js,intercom/ember.js,fpauser/ember.js,mike-north/ember.js,stefanpenner/ember.js,karthiick/ember.js,elwayman02/ember.js,bekzod/ember.js,csantero/ember.js,asakusuma/ember.js,elwayman02/ember.js,gfvcastro/ember.js,mixonic/ember.js,mike-north/ember.js,cibernox/ember.js,sandstrom/ember.js,thoov/ember.js,Serabe/ember.js,kellyselden/ember.js,thoov/ember.js,intercom/ember.js,kanongil/ember.js,kellyselden/ember.js,bekzod/ember.js,tildeio/ember.js,asakusuma/ember.js,knownasilya/ember.js,knownasilya/ember.js,GavinJoyce/ember.js,twokul/ember.js,miguelcobain/ember.js,kanongil/ember.js,kanongil/ember.js,csantero/ember.js,qaiken/ember.js,knownasilya/ember.js,emberjs/ember.js,Turbo87/ember.js | ---
+++
@@ -1,6 +1,5 @@
'use strict';
-const testInfo = require('ember-cli-test-info');
const stringUtils = require('ember-cli-string-utils');
const useTestFrameworkDetector = require('../test-framework-detector');
@@ -9,7 +8,7 @@
description: 'Generates an initializer unit test.',
locals: function(options) {
return {
- friendlyTestName: testInfo.name(options.entity.name, 'Unit', 'Initializer'),
+ friendlyTestName: ['Unit', 'Initializer', options.entity.name].join(' | '),
dasherizedModulePrefix: stringUtils.dasherize(options.project.config().modulePrefix)
};
} |
abdf308bb9b1309bb8b6dc9fd9afbc64cc790e88 | scripts/build-templates/simple.amd.js | scripts/build-templates/simple.amd.js | define(['jquery', 'underscore', 'backbone'], function($, _, Backbone) {
{{body}}
});
| define(['jquery', 'underscore', 'backbone', 'backbone-forms'], function($, _, Backbone) {
{{body}}
});
| Fix AMD editors that must have backbone forms | Fix AMD editors that must have backbone forms
Without this, there's a race condition
This is how the AMD fixes were originally intended as of https://github.com/powmedia/backbone-forms/pull/89/files
But since this build-template file wasn't properly setup subsequent builds destroyed the changes in the distribution.amd/editors folder
| JavaScript | mit | GabeIsman/backbone-forms,wesvetter/backbone-forms,fonji/backbone-forms,dmil/backbone-forms,ldong/backbone-forms,exussum12/backbone-forms,goodwall/backbone-forms,nareshv/backbone-forms,ldong/backbone-forms,bryce-gibson/backbone-forms,goodwall/backbone-forms,fonji/backbone-forms,nareshv/backbone-forms,CashStar/backbone-forms,bryce-gibson/backbone-forms,Shinobi881/backbone-forms,powmedia/backbone-forms,Shinobi881/backbone-forms,AlJohri/backbone-forms,dmil/backbone-forms,wesvetter/backbone-forms,AlJohri/backbone-forms,exussum12/backbone-forms,iabw/fork_of_backbone-forms,CashStar/backbone-forms,wesvetter/backbone-forms,GabeIsman/backbone-forms,iabw/fork_of_backbone-forms,powmedia/backbone-forms | ---
+++
@@ -1,4 +1,4 @@
-define(['jquery', 'underscore', 'backbone'], function($, _, Backbone) {
+define(['jquery', 'underscore', 'backbone', 'backbone-forms'], function($, _, Backbone) {
{{body}}
|
9898284da8d218449cde9b591cae1b5c3b7ab67d | addon/components/ember-chart.js | addon/components/ember-chart.js | /* global Chart */
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'canvas',
attributeBindings: ['width', 'height'],
didInsertElement() {
this._super(...arguments);
let context = this.get('element');
let data = this.get('data');
let type = this.get('type');
let options = this.get('options');
let chart = new Chart(context, {
type: type,
data: data,
options: options
});
this.set('chart', chart);
},
willDestroyElement() {
this._super(...arguments);
this.get('chart').destroy();
},
didUpdateAttrs() {
this._super(...arguments);
let chart = this.get('chart');
let data = this.get('data');
let options = this.get('options');
let animate = this.get('animate');
if (chart) {
chart.config.data = data;
chart.config.options = options;
if (animate) {
chart.update();
} else {
chart.update(0);
}
}
}
});
| /* global Chart */
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'canvas',
attributeBindings: ['width', 'height'],
didInsertElement() {
this._super(...arguments);
let context = this.get('element');
let data = this.get('data');
let type = this.get('type');
let options = this.get('options');
let chart = new Chart(context, {
type: type,
data: data,
options: options
});
this.set('chart', chart);
},
willDestroyElement() {
this._super(...arguments);
this.get('chart').destroy();
},
didUpdateAttrs() {
this._super(...arguments);
this.updateChart();
},
updateChart() {
let chart = this.get('chart');
let data = this.get('data');
let options = this.get('options');
let animate = this.get('animate');
if (chart) {
chart.config.data = data;
chart.config.options = options;
if (animate) {
chart.update();
} else {
chart.update(0);
}
}
}
});
| Split out update logic into its own method | Split out update logic into its own method
| JavaScript | mit | aomra015/ember-cli-chart,aomran/ember-cli-chart,aomra015/ember-cli-chart,aomran/ember-cli-chart | ---
+++
@@ -27,7 +27,10 @@
didUpdateAttrs() {
this._super(...arguments);
-
+ this.updateChart();
+ },
+
+ updateChart() {
let chart = this.get('chart');
let data = this.get('data');
let options = this.get('options'); |
ae44d3aa4d60eb172199dea1022020435c771bf4 | lib/helpers/upload.js | lib/helpers/upload.js | 'use strict';
var rarity = require('rarity');
/**
* Upload `event` (containing event data) onto AnyFetch.
*
*
* @param {Object} event Event to upload, plus anyfetchClient
* @param {Object} anyfetchClient Client for upload
* @param {Function} cb Callback to call once events has been uploaded.
*/
module.exports = function(event, anyfetchClient, cb) {
console.log("Uploading ", event.identifier);
var eventDocument = {
identifier: event.identifier,
actions: {
show: event.htmlLink
},
creation_date: event.created,
modification_date: event.updated,
metadata: {},
document_type: 'event',
user_access: [anyfetchClient.accessToken]
};
anyfetchClient.postDocument(eventDocument, rarity.slice(1, cb));
};
| 'use strict';
var rarity = require('rarity');
var getDateFromObject = function(obj) {
if (!obj) {
return undefined;
}
if (obj.datetime) {
return new Date(obj.datetime);
}
else if (obj.date) {
return new Date(obj.date);
}
else {
return undefined;
}
};
/**
* Upload `event` (containing event data) onto AnyFetch.
*
*
* @param {Object} event Event to upload, plus anyfetchClient
* @param {Object} anyfetchClient Client for upload
* @param {Function} cb Callback to call once events has been uploaded.
*/
module.exports = function(event, anyfetchClient, cb) {
console.log("Uploading ", event.identifier);
var eventDocument = {
identifier: event.identifier,
actions: {
show: event.htmlLink
},
creation_date: event.created,
modification_date: event.updated,
metadata: {},
document_type: 'event',
user_access: [anyfetchClient.accessToken]
};
eventDocument.metadata.startDate = getDateFromObject(event.start);
eventDocument.metadata.endDate = getDateFromObject(event.end);
eventDocument.metadata.name = event.summary;
eventDocument.metadata.description = event.description;
eventDocument.metadata.location = event.location;
if (event.attendee) {
eventDocument.metadata.attendee = event.attendee.map(function(attendee) {
return {
name: attendee.displayName,
mail: attendee.email
};
});
}
else {
eventDocument.metadata.attendee = [];
}
anyfetchClient.postDocument(eventDocument, rarity.slice(1, cb));
};
| Add a lots of metadata for events | Add a lots of metadata for events
| JavaScript | mit | AnyFetch/gcalendar-provider.anyfetch.com | ---
+++
@@ -1,6 +1,22 @@
'use strict';
var rarity = require('rarity');
+
+var getDateFromObject = function(obj) {
+ if (!obj) {
+ return undefined;
+ }
+
+ if (obj.datetime) {
+ return new Date(obj.datetime);
+ }
+ else if (obj.date) {
+ return new Date(obj.date);
+ }
+ else {
+ return undefined;
+ }
+};
/**
* Upload `event` (containing event data) onto AnyFetch.
@@ -24,6 +40,24 @@
document_type: 'event',
user_access: [anyfetchClient.accessToken]
};
+
+ eventDocument.metadata.startDate = getDateFromObject(event.start);
+ eventDocument.metadata.endDate = getDateFromObject(event.end);
+ eventDocument.metadata.name = event.summary;
+ eventDocument.metadata.description = event.description;
+ eventDocument.metadata.location = event.location;
+
+ if (event.attendee) {
+ eventDocument.metadata.attendee = event.attendee.map(function(attendee) {
+ return {
+ name: attendee.displayName,
+ mail: attendee.email
+ };
+ });
+ }
+ else {
+ eventDocument.metadata.attendee = [];
+ }
anyfetchClient.postDocument(eventDocument, rarity.slice(1, cb));
}; |
c7d18968ded6d09171e0d5729eba47b64c93e1fd | src/uniqueName.spec.js | src/uniqueName.spec.js | import React from 'react'
import {render} from 'react-dom'
import {equal, ok} from 'assert'
import uniqueName from './uniqueName'
describe('uniqueName', () => {
describe('no name specified', () => {
it('has unique id', () => {
const root = document.createElement('div')
function Input ({name}) {
return <input name={name} />
}
const UniquelyNamedInput = uniqueName(Input)
render(
<UniquelyNamedInput />,
root
)
ok(
root.children[0]
.getAttribute('name')
.match(/^Input-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/)
)
})
})
describe('name specified', () => {
it('has the name', () => {
const root = document.createElement('div')
function Input ({name}) {
return <input name={name} />
}
const UniquelyNamedInput = uniqueName(Input)
render(
<UniquelyNamedInput name='actualName' />,
root
)
equal(root.children[0].getAttribute('name'), 'actualName')
})
})
})
| import React from 'react'
import {render} from 'react-dom'
import {equal, ok} from 'assert'
import uniqueName from './uniqueName'
describe('uniqueName', () => {
describe('no name specified', () => {
it('has unique id', () => {
const root = document.createElement('div')
function Input ({name}) {
return <input name={name} />
}
const UniquelyNamedInput = uniqueName(Input)
render(
<div>
<UniquelyNamedInput />
<UniquelyNamedInput />
<UniquelyNamedInput />
</div>,
root
)
const inputList = root.children[0].children
ok(
inputList[0]
.getAttribute('name')
.match(/^Input-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/)
)
ok(
inputList[0].getAttribute('name') !== inputList[1].getAttribute('name')
)
ok(
inputList[1].getAttribute('name') !== inputList[2].getAttribute('name')
)
ok(
inputList[0].getAttribute('name') !== inputList[2].getAttribute('name')
)
})
})
describe('name specified', () => {
it('has the name', () => {
const root = document.createElement('div')
function Input ({name}) {
return <input name={name} />
}
const UniquelyNamedInput = uniqueName(Input)
render(
<UniquelyNamedInput name='actualName' />,
root
)
equal(root.children[0].getAttribute('name'), 'actualName')
})
})
})
| Test uniqueness as well (weak test though) | Test uniqueness as well (weak test though)
| JavaScript | mit | klarna/higher-order-components,klarna/higher-order-components | ---
+++
@@ -15,14 +15,32 @@
const UniquelyNamedInput = uniqueName(Input)
render(
- <UniquelyNamedInput />,
+ <div>
+ <UniquelyNamedInput />
+ <UniquelyNamedInput />
+ <UniquelyNamedInput />
+ </div>,
root
)
+ const inputList = root.children[0].children
+
ok(
- root.children[0]
+ inputList[0]
.getAttribute('name')
.match(/^Input-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/)
+ )
+
+ ok(
+ inputList[0].getAttribute('name') !== inputList[1].getAttribute('name')
+ )
+
+ ok(
+ inputList[1].getAttribute('name') !== inputList[2].getAttribute('name')
+ )
+
+ ok(
+ inputList[0].getAttribute('name') !== inputList[2].getAttribute('name')
)
})
}) |
b21a418df57e5f0e31583859d9d53f6936090187 | models/index.js | models/index.js | "use strict";
var fs = require("fs");
var path = require("path");
var Sequelize = require("sequelize");
var env = /*process.env.NODE_ENV || */"production";
var config = require(path.join(__dirname, '..', 'config', 'config.json'))[env];
var sequelize = new Sequelize(config.database, config.username, config.password, config);
var db = {};
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf(".") !== 0) && (file !== "index.js");
})
.forEach(function(file) {
var model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if ("associate" in db[modelName]) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
/* play.js
"use strict";
module.exports = function(sequelize, DataTypes) {
var Play = sequelize.define("Play", {
}, {
comment : "Play table connect user A and room B so it means A joined B.",
classMethods: {
associate: function(models) {
Play.belongsTo(models.User, {foreignkey: 'username'});
Play.belongsTo(models.Room, {foreignkey: 'roomid'});
}
}
});
return Play;
};
*/
| "use strict";
var fs = require("fs");
var path = require("path");
var Sequelize = require("sequelize");
var env = process.env.NODE_ENV || "production";
var config = require(path.join(__dirname, '..', 'config', 'config.json'))[env];
var sequelize = new Sequelize(config.database, config.username, config.password, config);
var db = {};
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf(".") !== 0) && (file !== "index.js");
})
.forEach(function(file) {
var model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if ("associate" in db[modelName]) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
/* play.js
"use strict";
module.exports = function(sequelize, DataTypes) {
var Play = sequelize.define("Play", {
}, {
comment : "Play table connect user A and room B so it means A joined B.",
classMethods: {
associate: function(models) {
Play.belongsTo(models.User, {foreignkey: 'username'});
Play.belongsTo(models.Room, {foreignkey: 'roomid'});
}
}
});
return Play;
};
*/
| Remove comment because environment variable should be applied. | Remove comment because environment variable should be applied.
| JavaScript | mit | oopartians/oopartsgames,oopartians/oopartsgames | ---
+++
@@ -3,7 +3,7 @@
var fs = require("fs");
var path = require("path");
var Sequelize = require("sequelize");
-var env = /*process.env.NODE_ENV || */"production";
+var env = process.env.NODE_ENV || "production";
var config = require(path.join(__dirname, '..', 'config', 'config.json'))[env];
var sequelize = new Sequelize(config.database, config.username, config.password, config);
var db = {}; |
7f6283352f9f1b9c2579a416c93726355c010356 | spec/fixtures/api/isolated-preload.js | spec/fixtures/api/isolated-preload.js | const {ipcRenderer, webFrame} = require('electron')
window.foo = 3
webFrame.executeJavaScript('window.preloadExecuteJavaScriptProperty = 1234;')
window.addEventListener('message', (event) => {
ipcRenderer.send('isolated-world', {
preloadContext: {
preloadProperty: typeof window.foo,
pageProperty: typeof window.hello,
typeofRequire: typeof require,
typeofProcess: typeof process,
typeofArrayPush: typeof Array.prototype.push,
typeofFunctionApply: typeof Function.prototype.apply
},
pageContext: event.data
})
})
| // Ensure fetch works from isolated world origin
fetch('http://localhost:1234')
fetch('https://localhost:1234')
fetch(`file://${__filename}`)
const {ipcRenderer, webFrame} = require('electron')
window.foo = 3
webFrame.executeJavaScript('window.preloadExecuteJavaScriptProperty = 1234;')
window.addEventListener('message', (event) => {
ipcRenderer.send('isolated-world', {
preloadContext: {
preloadProperty: typeof window.foo,
pageProperty: typeof window.hello,
typeofRequire: typeof require,
typeofProcess: typeof process,
typeofArrayPush: typeof Array.prototype.push,
typeofFunctionApply: typeof Function.prototype.apply
},
pageContext: event.data
})
})
| Add failing spec for fetch from isolated world | Add failing spec for fetch from isolated world
| JavaScript | mit | rajatsingla28/electron,thompsonemerson/electron,brenca/electron,Floato/electron,seanchas116/electron,rajatsingla28/electron,tonyganch/electron,rajatsingla28/electron,renaesop/electron,tonyganch/electron,joaomoreno/atom-shell,twolfson/electron,gerhardberger/electron,bpasero/electron,wan-qy/electron,shiftkey/electron,twolfson/electron,gerhardberger/electron,electron/electron,shiftkey/electron,miniak/electron,shiftkey/electron,rreimann/electron,renaesop/electron,renaesop/electron,tonyganch/electron,rajatsingla28/electron,gerhardberger/electron,thomsonreuters/electron,gerhardberger/electron,Floato/electron,wan-qy/electron,rreimann/electron,biblerule/UMCTelnetHub,brenca/electron,joaomoreno/atom-shell,thomsonreuters/electron,Floato/electron,shiftkey/electron,the-ress/electron,electron/electron,twolfson/electron,thompsonemerson/electron,biblerule/UMCTelnetHub,seanchas116/electron,twolfson/electron,seanchas116/electron,miniak/electron,the-ress/electron,biblerule/UMCTelnetHub,wan-qy/electron,thomsonreuters/electron,the-ress/electron,electron/electron,biblerule/UMCTelnetHub,brenca/electron,biblerule/UMCTelnetHub,thomsonreuters/electron,bpasero/electron,wan-qy/electron,thomsonreuters/electron,joaomoreno/atom-shell,renaesop/electron,tonyganch/electron,bpasero/electron,biblerule/UMCTelnetHub,brenca/electron,miniak/electron,rajatsingla28/electron,seanchas116/electron,gerhardberger/electron,tonyganch/electron,twolfson/electron,joaomoreno/atom-shell,miniak/electron,Floato/electron,gerhardberger/electron,the-ress/electron,wan-qy/electron,shiftkey/electron,joaomoreno/atom-shell,wan-qy/electron,electron/electron,rajatsingla28/electron,gerhardberger/electron,electron/electron,Floato/electron,rreimann/electron,joaomoreno/atom-shell,renaesop/electron,renaesop/electron,rreimann/electron,seanchas116/electron,thompsonemerson/electron,seanchas116/electron,brenca/electron,rreimann/electron,shiftkey/electron,Floato/electron,twolfson/electron,rreimann/electron,brenca/electron,miniak/electron,the-ress/electron,bpasero/electron,thompsonemerson/electron,tonyganch/electron,bpasero/electron,the-ress/electron,electron/electron,electron/electron,thompsonemerson/electron,bpasero/electron,miniak/electron,thompsonemerson/electron,thomsonreuters/electron,the-ress/electron,bpasero/electron | ---
+++
@@ -1,8 +1,14 @@
+// Ensure fetch works from isolated world origin
+fetch('http://localhost:1234')
+fetch('https://localhost:1234')
+fetch(`file://${__filename}`)
+
const {ipcRenderer, webFrame} = require('electron')
window.foo = 3
webFrame.executeJavaScript('window.preloadExecuteJavaScriptProperty = 1234;')
+
window.addEventListener('message', (event) => {
ipcRenderer.send('isolated-world', { |
cdaf0a2b89d4989dbaa3744acf2acb5a659da4b8 | app/scripts.babel/background.js | app/scripts.babel/background.js | 'use strict';
chrome.runtime.onInstalled.addListener(details => {
console.log('previousVersion', details.previousVersion);
});
chrome.tabs.onUpdated.addListener(tabId => {
chrome.pageAction.show(tabId);
});
console.log('\'Allo \'Allo! Event Page for Page Action');
| 'use strict';
chrome.runtime.onInstalled.addListener(details => {
console.log('previousVersion', details.previousVersion);
chrome.storage.sync.set({
columnsToHide: '137, 1057, 1063',
epicsToHide: '213682'
});
});
chrome.tabs.onUpdated.addListener(tabId => {
chrome.pageAction.show(tabId);
});
console.log('\'Allo \'Allo! Event Page for Page Action');
| Set the columns and epics to hide on install | Set the columns and epics to hide on install
| JavaScript | mit | adorableio/version-one-shot,adorableio/version-one-shot | ---
+++
@@ -2,6 +2,10 @@
chrome.runtime.onInstalled.addListener(details => {
console.log('previousVersion', details.previousVersion);
+ chrome.storage.sync.set({
+ columnsToHide: '137, 1057, 1063',
+ epicsToHide: '213682'
+ });
});
chrome.tabs.onUpdated.addListener(tabId => { |
b1bf7a9ddc1d181ce5ac36a37f2815cb90241775 | test/tap/false_name.js | test/tap/false_name.js | var test = require("tap").test
, fs = require("fs")
, path = require("path")
, existsSync = fs.existsSync || path.existsSync
, spawn = require("child_process").spawn
, npm = require("../../")
test("not every pkg.name can be required", function (t) {
t.plan(1)
setup(function () {
npm.install(".", function (err) {
if (err) return t.fail(err)
t.ok(existsSync(__dirname +
"/false_name/node_modules/tap/node_modules/buffer-equal"))
})
})
})
function setup (cb) {
process.chdir(__dirname + "/false_name")
npm.load(function () {
spawn("rm", [ "-rf", __dirname + "/false_name/node_modules" ])
.on("exit", function () {
fs.mkdirSync(__dirname + "/false_name/node_modules")
cb()
})
})
}
| var test = require("tap").test
, fs = require("fs")
, path = require("path")
, existsSync = fs.existsSync || path.existsSync
, spawn = require("child_process").spawn
, npm = require("../../")
, rimraf = require("rimraf")
test("not every pkg.name can be required", function (t) {
t.plan(1)
setup(function () {
npm.install(".", function (err) {
if (err) return t.fail(err)
t.ok(existsSync(__dirname +
"/false_name/node_modules/tap/node_modules/buffer-equal"))
})
})
})
function setup (cb) {
process.chdir(__dirname + "/false_name")
npm.load(function () {
rimraf.sync(__dirname + "/false_name/node_modules")
fs.mkdirSync(__dirname + "/false_name/node_modules")
cb()
})
}
| Use rimraf instead of spawning rm -rf | Use rimraf instead of spawning rm -rf
Thus, it works on Windows!
| JavaScript | artistic-2.0 | kemitchell/npm,evanlucas/npm,chadnickbok/npm,kemitchell/npm,kriskowal/npm,xalopp/npm,cchamberlain/npm,rsp/npm,yibn2008/npm,Volune/npm,evocateur/npm,yodeyer/npm,haggholm/npm,thomblake/npm,kimshinelove/naver-npm,princeofdarkness76/npm,ekmartin/npm,xalopp/npm,lxe/npm,cchamberlain/npm-msys2,yodeyer/npm,rsp/npm,chadnickbok/npm,segmentio/npm,yodeyer/npm,midniteio/npm,yibn2008/npm,segrey/npm,haggholm/npm,princeofdarkness76/npm,midniteio/npm,kimshinelove/naver-npm,DIREKTSPEED-LTD/npm,kriskowal/npm,lxe/npm,TimeToogo/npm,thomblake/npm,DaveEmmerson/npm,DaveEmmerson/npm,evanlucas/npm,evanlucas/npm,segrey/npm,segrey/npm,lxe/npm,misterbyrne/npm,ekmartin/npm,segment-boneyard/npm,evocateur/npm,cchamberlain/npm,segmentio/npm,TimeToogo/npm,thomblake/npm,yyx990803/npm,misterbyrne/npm,cchamberlain/npm-msys2,cchamberlain/npm-msys2,segment-boneyard/npm,segmentio/npm,Volune/npm,haggholm/npm,evocateur/npm,segment-boneyard/npm,rsp/npm,midniteio/npm,princeofdarkness76/npm,DIREKTSPEED-LTD/npm,yyx990803/npm,kimshinelove/naver-npm,yyx990803/npm,TimeToogo/npm,chadnickbok/npm,cchamberlain/npm,misterbyrne/npm,yibn2008/npm,DaveEmmerson/npm,xalopp/npm,ekmartin/npm,kriskowal/npm,kemitchell/npm,Volune/npm,DIREKTSPEED-LTD/npm | ---
+++
@@ -4,6 +4,7 @@
, existsSync = fs.existsSync || path.existsSync
, spawn = require("child_process").spawn
, npm = require("../../")
+ , rimraf = require("rimraf")
test("not every pkg.name can be required", function (t) {
t.plan(1)
@@ -20,10 +21,8 @@
function setup (cb) {
process.chdir(__dirname + "/false_name")
npm.load(function () {
- spawn("rm", [ "-rf", __dirname + "/false_name/node_modules" ])
- .on("exit", function () {
- fs.mkdirSync(__dirname + "/false_name/node_modules")
- cb()
- })
+ rimraf.sync(__dirname + "/false_name/node_modules")
+ fs.mkdirSync(__dirname + "/false_name/node_modules")
+ cb()
})
} |
97adfe5fe4f4fb2c1a874c047ce380dc3f13fcac | context/index.js | context/index.js | define(['./node', './joinId', './imports'], function (
node, joinId, imports) {
return function (requestedFiles, nodes) {
var is = imports(requestedFiles, nodes);
var trees = [];
requestedFiles.forEach(function (file) {
var index = {};
nodes.forEach(function (n) { index[joinId(n.getId())] = n; });
var id = joinId(file.getId());
var children = index[id].getNestedNodes().map(function (c) {
return node(c, index);
});
trees.push({
name : file.getFilename().asString(),
meta : "file",
imports : is[id],
id : id,
nodes : children
});
});
return trees;
};
});
| define(['./node', './joinId', './imports'], function (
node, joinId, imports) {
return function (requestedFiles, nodes) {
var is = imports(requestedFiles, nodes);
var trees = [];
requestedFiles.forEach(function (file) {
var index = {};
nodes.forEach(function (n) { index[joinId(n.getId())] = n; });
var id = joinId(file.getId());
var children = index[id].getNestedNodes().map(function (c) {
return node(c, index);
});
trees.push({
name : file.getFilename().toString(),
meta : "file",
imports : is[id],
id : id,
nodes : children
});
});
return trees;
};
});
| Use toString instead of asString | Use toString instead of asString
| JavaScript | mit | xygroup/node-capnp-plugin | ---
+++
@@ -16,7 +16,7 @@
});
trees.push({
- name : file.getFilename().asString(),
+ name : file.getFilename().toString(),
meta : "file",
imports : is[id],
id : id, |
310cb4a12eab84902166cf8847166c3640d3e60c | src/auto-upgrade/updateBabelConfig.js | src/auto-upgrade/updateBabelConfig.js | import fs from "fs-extra";
import path from "path";
import inquirer from "inquirer";
import sha1 from "sha1";
import readFileSyncStrip from "../lib/readFileSyncStrip";
import logger from "../lib/logger";
import { warn } from "../lib/logsColorScheme";
function doUpdate(from, to) {
logger.info("Updating .babelrc file...");
fs.copySync(from, to);
}
export default function updateBabelConfig() {
return new Promise(resolve => {
const projectConfigPath = path.join(process.cwd(), ".babelrc");
const latestConfigPath = path.join(__dirname, "../..", "new", ".babelrc");
const projectSha = sha1(readFileSyncStrip(projectConfigPath));
const previousSha = sha1(readFileSyncStrip(path.join(__dirname, "previous", ".babelrc")));
const latestSha = sha1(readFileSyncStrip(latestConfigPath));
if (projectSha === latestSha) {
return resolve();
}
else if (projectSha !== previousSha) {
const question = {
type: "confirm",
name: "confirm",
message: `${warn("The format of .babelrc is out of date. Would you like to automatically update it?")}`
};
inquirer.prompt([question], function (answers) {
if (!answers.confirm) {
const latestConfig = fs.readFileSync(latestConfigPath);
logger.info(`It is recommended that you update your .babelrc file. Here is an example file:\n${latestConfig}`);
return resolve();
}
doUpdate(latestConfigPath, projectConfigPath);
resolve();
});
}
});
}
| import fs from "fs-extra";
import path from "path";
import inquirer from "inquirer";
import sha1 from "sha1";
import readFileSyncStrip from "../lib/readFileSyncStrip";
import logger from "../lib/logger";
import { warn } from "../lib/logsColorScheme";
function doUpdate(from, to) {
logger.info("Updating .babelrc file...");
fs.copySync(from, to);
}
export default function updateBabelConfig() {
return new Promise(resolve => {
const projectConfigPath = path.join(process.cwd(), ".babelrc");
const latestConfigPath = path.join(__dirname, "../..", "new", ".babelrc");
const projectSha = sha1(readFileSyncStrip(projectConfigPath));
const previousSha = sha1(readFileSyncStrip(path.join(__dirname, "previous", ".babelrc")));
const latestSha = sha1(readFileSyncStrip(latestConfigPath));
if (projectSha === latestSha) {
return resolve();
}
else if (projectSha !== previousSha) {
const question = {
type: "confirm",
name: "confirm",
message: `${warn("The format of .babelrc is out of date. Would you like to automatically update it?")}`
};
inquirer.prompt([question], function (answers) {
if (!answers.confirm) {
const latestConfig = fs.readFileSync(latestConfigPath);
logger.info(`It is recommended that you update your .babelrc file. Here is an example file:\n${latestConfig}`);
return resolve();
}
doUpdate(latestConfigPath, projectConfigPath);
return resolve();
});
}
doUpdate(latestConfigPath, projectConfigPath);
return resolve();
});
}
| Upgrade if the user's file matches the previous | Upgrade if the user's file matches the previous
| JavaScript | mit | TrueCar/gluestick,TrueCar/gluestick,TrueCar/gluestick | ---
+++
@@ -39,8 +39,10 @@
}
doUpdate(latestConfigPath, projectConfigPath);
- resolve();
+ return resolve();
});
}
+ doUpdate(latestConfigPath, projectConfigPath);
+ return resolve();
});
} |
9a0fed8a0fb6c13b530989fa09091f1ebcad3627 | modifyurl@2ch.user.js | modifyurl@2ch.user.js | // ==UserScript==
// @name Modify URL @2ch
// @namespace curipha
// @description Modify texts starting with "ttp://" to anchor and redirect URIs to direct link
// @include http://*.2ch.net/*
// @include http://*.bbspink.com/*
// @version 0.1.2
// @grant none
// @noframes
// ==/UserScript==
(function(){
'use strict';
var anchor = document.getElementsByTagName('a');
for (var a of anchor) {
if (a.href.indexOf('http://jump.2ch.net/?') === 0) {
a.href = decodeURIComponent(a.href.slice(21)); // 'http://jump.2ch.net/?'.length -> 21
}
else if (a.href.indexOf('http://pinktower.com/?') === 0) {
a.href = decodeURIComponent('http://' + a.href.slice(22)); // 'http://pinktower.com/?'.length -> 22
}
}
var res = document.getElementsByTagName('dd');
if (res.length < 1) res = document.getElementsByClassName('message');
var ttp = /([^h])(ttps?:\/\/[\x21\x23-\x3b\x3d\x3f-\x7E]+)/ig;
for (var d of res) {
d.innerHTML = d.innerHTML.replace(ttp, '$1<a href="h$2">$2</a>');
}
})();
| // ==UserScript==
// @name Modify URL @2ch
// @namespace curipha
// @description Modify texts starting with "ttp://" to anchor and redirect URIs to direct link
// @include http://*.2ch.net/*
// @include http://*.bbspink.com/*
// @version 0.1.2
// @grant none
// @noframes
// ==/UserScript==
(function(){
'use strict';
var anchor = document.getElementsByTagName('a');
for (var a of anchor) {
if (a.href.indexOf('http://jump.2ch.net/?') === 0) {
a.href = decodeURIComponent(a.href.slice(21)); // 'http://jump.2ch.net/?'.length -> 21
}
else if (a.href.indexOf('http://pinktower.com/?') === 0) {
a.href = decodeURIComponent('http://' + a.href.slice(22)); // 'http://pinktower.com/?'.length -> 22
}
}
var res = document.getElementsByTagName('dd');
if (res.length < 1) res = document.getElementsByClassName('message');
var ttp = /([^h]|^)(ttps?:\/\/[\x21\x23-\x3b\x3d\x3f-\x7E]+)/ig;
for (var d of res) {
d.innerHTML = d.innerHTML.replace(ttp, '$1<a href="h$2">$2</a>');
}
})();
| Convert 'ttp' string to link even if it appears at the first position of response | Convert 'ttp' string to link even if it appears at the first position of response
| JavaScript | unlicense | curipha/userscripts,curipha/userscripts | ---
+++
@@ -26,7 +26,7 @@
var res = document.getElementsByTagName('dd');
if (res.length < 1) res = document.getElementsByClassName('message');
- var ttp = /([^h])(ttps?:\/\/[\x21\x23-\x3b\x3d\x3f-\x7E]+)/ig;
+ var ttp = /([^h]|^)(ttps?:\/\/[\x21\x23-\x3b\x3d\x3f-\x7E]+)/ig;
for (var d of res) {
d.innerHTML = d.innerHTML.replace(ttp, '$1<a href="h$2">$2</a>'); |
6d3aa7e45f33006be0aaa2e070a8da7c2417741a | examples/official-storybook/config.js | examples/official-storybook/config.js | /* eslint-disable import/no-extraneous-dependencies, import/no-unresolved, import/extensions */
import { configure } from '@storybook/react';
import { setOptions } from '@storybook/addon-options';
import 'react-chromatic/storybook-addon';
import addHeadWarning from './head-warning';
addHeadWarning('Preview');
setOptions({
hierarchySeparator: /\/|\./,
hierarchyRootSeparator: /\|/,
});
function loadStories() {
let req;
req = require.context('../../lib/ui/src', true, /\.stories\.js$/);
req.keys().forEach(filename => req(filename));
req = require.context('../../lib/components/src', true, /\.stories\.js$/);
req.keys().forEach(filename => req(filename));
req = require.context('./stories', true, /\.stories\.js$/);
req.keys().forEach(filename => req(filename));
}
configure(loadStories, module);
| /* eslint-disable import/no-extraneous-dependencies, import/no-unresolved, import/extensions */
import { configure } from '@storybook/react';
import { setOptions } from '@storybook/addon-options';
import 'react-chromatic/storybook-addon';
import addHeadWarning from './head-warning';
addHeadWarning('Preview');
setOptions({
hierarchySeparator: /\/|\.|\\/,
hierarchyRootSeparator: /\|/,
});
function loadStories() {
let req;
req = require.context('../../lib/ui/src', true, /\.stories\.js$/);
req.keys().forEach(filename => req(filename));
req = require.context('../../lib/components/src', true, /\.stories\.js$/);
req.keys().forEach(filename => req(filename));
req = require.context('./stories', true, /\.stories\.js$/);
req.keys().forEach(filename => req(filename));
}
configure(loadStories, module);
| FIX windows BS paths containing a slash in the freaking wrong direction, total BS | FIX windows BS paths containing a slash in the freaking wrong direction, total BS
| JavaScript | mit | kadirahq/react-storybook,rhalff/storybook,rhalff/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,rhalff/storybook,storybooks/storybook,rhalff/storybook,storybooks/storybook,rhalff/storybook,rhalff/storybook,storybooks/storybook,storybooks/react-storybook | ---
+++
@@ -7,7 +7,7 @@
addHeadWarning('Preview');
setOptions({
- hierarchySeparator: /\/|\./,
+ hierarchySeparator: /\/|\.|\\/,
hierarchyRootSeparator: /\|/,
});
|
77b62d86bc9dc92293db45d5568468407a58c43a | middleware/match.js | middleware/match.js | var metaRouter = require('../');
var DataHolder = require('raptor-async/DataHolder');
module.exports = function match(routes) {
var matcher;
var matcherDataHolder;
if (typeof routes === 'string') {
matcherDataHolder = new DataHolder();
metaRouter.routesLoader.load(routes, function(err, routes) {
if (err) {
return matcherDataHolder.reject(err);
}
matcher = metaRouter.buildMatcher(routes);
matcherDataHolder.resolve(matcher);
});
} else {
matcher = metaRouter.buildMatcher(routes);
}
function go(matcher, req, res, next) {
var match = matcher.match(req.method, req.path);
if (match) {
req.route = match;
}
next();
}
return function(req, res, next) {
if (matcher) {
go(matcher, req, res, next);
} else {
matcherDataHolder.done(function(err, matcher) {
if (err) {
return next(err);
}
go(matcher, req, res, next);
});
}
};
}; | var metaRouter = require('../');
var DataHolder = require('raptor-async/DataHolder');
var nodePath = require('path');
module.exports = function match(routes) {
var matcher;
var matcherDataHolder;
if (typeof routes === 'string') {
routes = nodePath.resolve(process.cwd(), routes);
matcherDataHolder = new DataHolder();
metaRouter.routesLoader.load(routes, function(err, routes) {
if (err) {
return matcherDataHolder.reject(err);
}
matcher = metaRouter.buildMatcher(routes);
matcherDataHolder.resolve(matcher);
});
} else {
matcher = metaRouter.buildMatcher(routes);
}
function go(matcher, req, res, next) {
var match = matcher.match(req.method, req.path);
if (match) {
req.route = match;
}
next();
}
return function(req, res, next) {
if (matcher) {
go(matcher, req, res, next);
} else {
matcherDataHolder.done(function(err, matcher) {
if (err) {
return next(err);
}
go(matcher, req, res, next);
});
}
};
}; | Resolve all paths to CWD | Resolve all paths to CWD
| JavaScript | isc | patrick-steele-idem/meta-router | ---
+++
@@ -1,11 +1,14 @@
var metaRouter = require('../');
var DataHolder = require('raptor-async/DataHolder');
+var nodePath = require('path');
module.exports = function match(routes) {
var matcher;
var matcherDataHolder;
if (typeof routes === 'string') {
+ routes = nodePath.resolve(process.cwd(), routes);
+
matcherDataHolder = new DataHolder();
metaRouter.routesLoader.load(routes, function(err, routes) {
if (err) { |
bac5e65bf28e4645d30ef6620a1d11d98b214e79 | examples/todo/static/assets/js/app.js | examples/todo/static/assets/js/app.js | var loadTodos = function() {
$.ajax({
url: "/graphql?query={todoList{id,text,done}}"
}).done(function(data) {
console.log(data);
var dataParsed = JSON.parse(data);
var todos = dataParsed.data.todoList;
if (!todos.length) {
$('.todo-list-container').append('<p>There are no tasks for you today</p>');
}
$.each(todos, function(i, v) {
var doneHtml = '<input id="' + v.id + '" type="checkbox"' + (v.done ? ' checked="checked"' : '') + '>';
var labelHtml = '<label for="' + v.id + '">' + doneHtml + v.text + '</label>';
var itemHtml = '<div class="todo-item">' + labelHtml + '</div>';
$('.todo-list-container').append(itemHtml);
});
});
};
$(document).ready(function() {
loadTodos();
});
| var handleTodoList = function(object) {
var todos = object;
if (!todos.length) {
$('.todo-list-container').append('<p>There are no tasks for you today</p>');
}
$.each(todos, function(i, v) {
var doneHtml = '<input id="' + v.id + '" type="checkbox"' + (v.done ? ' checked="checked"' : '') + '>';
var labelHtml = '<label for="' + v.id + '">' + doneHtml + v.text + '</label>';
var itemHtml = '<div class="todo-item">' + labelHtml + '</div>';
$('.todo-list-container').append(itemHtml);
});
};
var loadTodos = function() {
$.ajax({
url: "/graphql?query={todoList{id,text,done}}"
}).done(function(data) {
console.log(data);
var dataParsed = JSON.parse(data);
handleTodoList(dataParsed.data.todoList);
});
};
var addTodo = function(todoText) {
if (!todoText || todoText === "") {
alert('Please specify a task');
return;
}
$.ajax({
url: '/graphql?query=mutation+_{createTodo(text:"' + todoText + '"){id,text,done}}'
}).done(function(data) {
console.log(data);
var dataParsed = JSON.parse(data);
var todoList = [dataParsed.data.createTodo];
handleTodoList(todoList);
});
};
$(document).ready(function() {
$('.todo-add-form button').click(function(){
addTodo($('.todo-add-form #task').val());
$('.todo-add-form #task').val('');
});
loadTodos();
});
| Add "Add task" functionality, use the mutation | Add "Add task" functionality, use the mutation
| JavaScript | mit | equinux/graphql,graphql-go/graphql | ---
+++
@@ -1,25 +1,50 @@
+var handleTodoList = function(object) {
+ var todos = object;
+
+ if (!todos.length) {
+ $('.todo-list-container').append('<p>There are no tasks for you today</p>');
+ }
+
+ $.each(todos, function(i, v) {
+ var doneHtml = '<input id="' + v.id + '" type="checkbox"' + (v.done ? ' checked="checked"' : '') + '>';
+ var labelHtml = '<label for="' + v.id + '">' + doneHtml + v.text + '</label>';
+ var itemHtml = '<div class="todo-item">' + labelHtml + '</div>';
+
+ $('.todo-list-container').append(itemHtml);
+ });
+};
+
var loadTodos = function() {
$.ajax({
url: "/graphql?query={todoList{id,text,done}}"
}).done(function(data) {
console.log(data);
var dataParsed = JSON.parse(data);
- var todos = dataParsed.data.todoList;
+ handleTodoList(dataParsed.data.todoList);
+ });
+};
- if (!todos.length) {
- $('.todo-list-container').append('<p>There are no tasks for you today</p>');
- }
+var addTodo = function(todoText) {
+ if (!todoText || todoText === "") {
+ alert('Please specify a task');
+ return;
+ }
- $.each(todos, function(i, v) {
- var doneHtml = '<input id="' + v.id + '" type="checkbox"' + (v.done ? ' checked="checked"' : '') + '>';
- var labelHtml = '<label for="' + v.id + '">' + doneHtml + v.text + '</label>';
- var itemHtml = '<div class="todo-item">' + labelHtml + '</div>';
-
- $('.todo-list-container').append(itemHtml);
- });
+ $.ajax({
+ url: '/graphql?query=mutation+_{createTodo(text:"' + todoText + '"){id,text,done}}'
+ }).done(function(data) {
+ console.log(data);
+ var dataParsed = JSON.parse(data);
+ var todoList = [dataParsed.data.createTodo];
+ handleTodoList(todoList);
});
};
$(document).ready(function() {
+ $('.todo-add-form button').click(function(){
+ addTodo($('.todo-add-form #task').val());
+ $('.todo-add-form #task').val('');
+ });
+
loadTodos();
}); |
0ae3e5ff4cfbd9fa0f23cc56589084beb495e259 | packages/accounts-password/package.js | packages/accounts-password/package.js | Package.describe({
summary: "Password support for accounts",
version: "1.3.6"
});
Package.onUse(function(api) {
api.use('npm-bcrypt', 'server');
api.use([
'accounts-base',
'srp',
'sha',
'ejson',
'ddp'
], ['client', 'server']);
// Export Accounts (etc) to packages using this one.
api.imply('accounts-base', ['client', 'server']);
api.use('email', ['server']);
api.use('random', ['server']);
api.use('check');
api.use('underscore');
api.use('ecmascript');
api.addFiles('email_templates.js', 'server');
api.addFiles('password_server.js', 'server');
api.addFiles('password_client.js', 'client');
});
Package.onTest(function(api) {
api.use(['accounts-password', 'tinytest', 'test-helpers', 'tracker',
'accounts-base', 'random', 'email', 'underscore', 'check',
'ddp', 'ecmascript']);
api.addFiles('password_tests_setup.js', 'server');
api.addFiles('password_tests.js', ['client', 'server']);
api.addFiles('email_tests_setup.js', 'server');
api.addFiles('email_tests.js', 'client');
});
| Package.describe({
summary: "Password support for accounts",
version: "1.3.7"
});
Package.onUse(function(api) {
api.use('npm-bcrypt', 'server');
api.use([
'accounts-base',
'srp',
'sha',
'ejson',
'ddp'
], ['client', 'server']);
// Export Accounts (etc) to packages using this one.
api.imply('accounts-base', ['client', 'server']);
api.use('email', ['server']);
api.use('random', ['server']);
api.use('check');
api.use('underscore');
api.use('ecmascript');
api.addFiles('email_templates.js', 'server');
api.addFiles('password_server.js', 'server');
api.addFiles('password_client.js', 'client');
});
Package.onTest(function(api) {
api.use(['accounts-password', 'tinytest', 'test-helpers', 'tracker',
'accounts-base', 'random', 'email', 'underscore', 'check',
'ddp', 'ecmascript']);
api.addFiles('password_tests_setup.js', 'server');
api.addFiles('password_tests.js', ['client', 'server']);
api.addFiles('email_tests_setup.js', 'server');
api.addFiles('email_tests.js', 'client');
});
| Bump version of `accounts-password` in preparation for publishing. | Bump version of `accounts-password` in preparation for publishing.
| JavaScript | mit | Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor | ---
+++
@@ -1,6 +1,6 @@
Package.describe({
summary: "Password support for accounts",
- version: "1.3.6"
+ version: "1.3.7"
});
Package.onUse(function(api) { |
97572d4223092a75fd9dbd1c72c947d933c6d520 | spec/javascripts/helpers/vue_mount_component_helper.js | spec/javascripts/helpers/vue_mount_component_helper.js | const mountComponent = (Component, props = {}, el = null) =>
new Component({
propsData: props,
}).$mount(el);
export const createComponentWithStore = (Component, store, propsData = {}) =>
new Component({
store,
propsData,
});
export const mountComponentWithStore = (Component, { el, props, store }) =>
new Component({
store,
propsData: props || {},
}).$mount(el);
export const mountComponentWithSlots = (Component, { props, slots }) => {
const component = new Component({
propsData: props || {},
});
component.$slots = slots;
return component.$mount();
};
export default mountComponent;
| import Vue from 'vue';
const mountComponent = (Component, props = {}, el = null) =>
new Component({
propsData: props,
}).$mount(el);
export const createComponentWithStore = (Component, store, propsData = {}) =>
new Component({
store,
propsData,
});
export const mountComponentWithStore = (Component, { el, props, store }) =>
new Component({
store,
propsData: props || {},
}).$mount(el);
export const mountComponentWithSlots = (Component, { props, slots }) => {
const component = new Component({
propsData: props || {},
});
component.$slots = slots;
return component.$mount();
};
/**
* Mount a component with the given render method.
*
* This helps with inserting slots that need to be compiled.
*/
export const mountComponentWithRender = (render, el = null) =>
mountComponent(Vue.extend({ render }), {}, el);
export default mountComponent;
| Create 'mountComponentWithRender' for testing with slots | Create 'mountComponentWithRender' for testing with slots
| JavaScript | mit | iiet/iiet-git,stoplightio/gitlabhq,mmkassem/gitlabhq,axilleas/gitlabhq,jirutka/gitlabhq,jirutka/gitlabhq,stoplightio/gitlabhq,dreampet/gitlab,stoplightio/gitlabhq,axilleas/gitlabhq,iiet/iiet-git,jirutka/gitlabhq,dreampet/gitlab,mmkassem/gitlabhq,jirutka/gitlabhq,iiet/iiet-git,dreampet/gitlab,dreampet/gitlab,axilleas/gitlabhq,axilleas/gitlabhq,iiet/iiet-git,mmkassem/gitlabhq,mmkassem/gitlabhq,stoplightio/gitlabhq | ---
+++
@@ -1,3 +1,5 @@
+import Vue from 'vue';
+
const mountComponent = (Component, props = {}, el = null) =>
new Component({
propsData: props,
@@ -25,4 +27,12 @@
return component.$mount();
};
+/**
+ * Mount a component with the given render method.
+ *
+ * This helps with inserting slots that need to be compiled.
+ */
+export const mountComponentWithRender = (render, el = null) =>
+ mountComponent(Vue.extend({ render }), {}, el);
+
export default mountComponent; |
8e014aa80b2cb546a96a59a5c675cf679f87d05e | lib/components/user/monitored-trip/trip-summary.js | lib/components/user/monitored-trip/trip-summary.js | import coreUtils from '@opentripplanner/core-utils'
import { ClassicLegIcon } from '@opentripplanner/icons'
import React from 'react'
import ItinerarySummary from '../../narrative/default/itinerary-summary'
const { formatDuration, formatTime } = coreUtils.time
const TripSummary = ({ monitoredTrip }) => {
const { itinerary } = monitoredTrip
const { duration, endTime, startTime } = itinerary
// TODO: use the modern itinerary summary built for trip comparison.
return (
<div
className={`otp option default-itin active`}
style={{borderTop: '0px', padding: '0px'}}>
<div className='header'>
<span className='title'>Itinerary</span>{' '}
<span className='duration pull-right'>{formatDuration(duration)}</span>{' '}
<span className='arrivalTime'>{formatTime(startTime)}—{formatTime(endTime)}</span>
<ItinerarySummary itinerary={itinerary} LegIcon={ClassicLegIcon} />
</div>
</div>
)
}
export default TripSummary
| import coreUtils from '@opentripplanner/core-utils'
import { ClassicLegIcon } from '@opentripplanner/icons'
import React from 'react'
import ItinerarySummary from '../../narrative/default/itinerary-summary'
const { formatDuration, formatTime } = coreUtils.time
const TripSummary = ({ monitoredTrip }) => {
const { itinerary } = monitoredTrip
const { duration, endTime, startTime } = itinerary
// TODO: use the modern itinerary summary built for trip comparison.
return (
<div
className={`otp option default-itin`}
style={{borderTop: '0px', padding: '0px'}}>
<div className='header'>
<span className='title'>Itinerary</span>{' '}
<span className='duration pull-right'>{formatDuration(duration)}</span>{' '}
<span className='arrivalTime'>{formatTime(startTime)}—{formatTime(endTime)}</span>
<ItinerarySummary itinerary={itinerary} LegIcon={ClassicLegIcon} />
</div>
</div>
)
}
export default TripSummary
| Remove green bar outside of batch itinerary results. | fix(TripSummary): Remove green bar outside of batch itinerary results.
| JavaScript | mit | opentripplanner/otp-react-redux,opentripplanner/otp-react-redux,opentripplanner/otp-react-redux,opentripplanner/otp-react-redux | ---
+++
@@ -12,7 +12,7 @@
// TODO: use the modern itinerary summary built for trip comparison.
return (
<div
- className={`otp option default-itin active`}
+ className={`otp option default-itin`}
style={{borderTop: '0px', padding: '0px'}}>
<div className='header'>
<span className='title'>Itinerary</span>{' '} |
2fb8530045b89d96457dea50309cbc9c17ae22dc | ui-v2/app/controllers/dc/nodes/show.js | ui-v2/app/controllers/dc/nodes/show.js | import Controller from '@ember/controller';
import { get, set } from '@ember/object';
import WithFiltering from 'consul-ui/mixins/with-filtering';
export default Controller.extend(WithFiltering, {
queryParams: {
s: {
as: 'filter',
replace: true,
},
},
setProperties: function() {
this._super(...arguments);
set(this, 'selectedTab', 'health-checks');
},
filter: function(item, { s = '' }) {
return (
get(item, 'Service')
.toLowerCase()
.indexOf(s.toLowerCase()) !== -1
);
},
actions: {
sortChecksByImportance: function(a, b) {
const statusA = get(a, 'Status');
const statusB = get(b, 'Status');
switch (statusA) {
case 'passing':
// a = passing
// unless b is also passing then a is less important
return statusB === 'passing' ? 0 : 1;
case 'critical':
// a = critical
// unless b is also critical then a is more important
return statusB === 'critical' ? 0 : -1;
case 'warning':
// a = warning
switch (statusB) {
// b is passing so a is more important
case 'passing':
return -1;
// b is critical so a is less important
case 'critical':
return 1;
// a and b are both warning, therefore equal
default:
return 0;
}
}
return 0;
},
},
});
| import Controller from '@ember/controller';
import { get, set } from '@ember/object';
import WithFiltering from 'consul-ui/mixins/with-filtering';
export default Controller.extend(WithFiltering, {
queryParams: {
s: {
as: 'filter',
replace: true,
},
},
setProperties: function() {
this._super(...arguments);
set(this, 'selectedTab', 'health-checks');
},
filter: function(item, { s = '' }) {
const term = s.toLowerCase();
return (
get(item, 'Service')
.toLowerCase()
.indexOf(term) !== -1 ||
get(item, 'Port')
.toString()
.toLowerCase()
.indexOf(term) !== -1
);
},
actions: {
sortChecksByImportance: function(a, b) {
const statusA = get(a, 'Status');
const statusB = get(b, 'Status');
switch (statusA) {
case 'passing':
// a = passing
// unless b is also passing then a is less important
return statusB === 'passing' ? 0 : 1;
case 'critical':
// a = critical
// unless b is also critical then a is more important
return statusB === 'critical' ? 0 : -1;
case 'warning':
// a = warning
switch (statusB) {
// b is passing so a is more important
case 'passing':
return -1;
// b is critical so a is less important
case 'critical':
return 1;
// a and b are both warning, therefore equal
default:
return 0;
}
}
return 0;
},
},
});
| Enable searching by port in the Node > [Service] listing | Enable searching by port in the Node > [Service] listing
| JavaScript | mpl-2.0 | 42wim/consul,hashicorp/consul,youhong316/consul,scalp42/consul,kingland/consul,calgaryscientific/consul,hashicorp/consul,calgaryscientific/consul,calgaryscientific/consul,scalp42/consul,scalp42/consul,vamage/consul,kingland/consul,vamage/consul,vamage/consul,calgaryscientific/consul,vamage/consul,scalp42/consul,hashicorp/consul,42wim/consul,42wim/consul,hashicorp/consul,youhong316/consul,scalp42/consul,youhong316/consul,calgaryscientific/consul,youhong316/consul,kingland/consul,kingland/consul,42wim/consul,youhong316/consul,42wim/consul,vamage/consul,kingland/consul | ---
+++
@@ -14,10 +14,15 @@
set(this, 'selectedTab', 'health-checks');
},
filter: function(item, { s = '' }) {
+ const term = s.toLowerCase();
return (
get(item, 'Service')
.toLowerCase()
- .indexOf(s.toLowerCase()) !== -1
+ .indexOf(term) !== -1 ||
+ get(item, 'Port')
+ .toString()
+ .toLowerCase()
+ .indexOf(term) !== -1
);
},
actions: { |
eefa7ffefa842d9777e08155988f82b284738b38 | twitch-auto-theater.js | twitch-auto-theater.js | // ==UserScript==
// @name Twitch Auto Theater
// @version 1.0.3
// @updateURL https://raw.githubusercontent.com/domosapien/Twitch-Auto-Theater/master/twitch-auto-theater.js
// @downloadURL https://raw.githubusercontent.com/domosapien/Twitch-Auto-Theater/master/twitch-auto-theater.js
// @match www.twitch.tv/*
// @grant none
// ==/UserScript==
/* jshint -W097 jquery:true */
'use strict';
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (!mutation.addedNodes) {
return;
}
for (var i = 0; i < mutation.addedNodes.length; i++) {
// do things to your newly added nodes here
var $node = $(mutation.addedNodes[i]).find('button.player-button--theatre');
if ($node.length) {
$node.trigger('click');
observer.disconnect();
return;
}
}
});
});
function startObserver() {
observer.observe(document.body, {
childList: true,
subtree: true,
attributes: false,
characterData: false
});
}
startObserver();
window.onpopstate = function (event) {
startObserver();
};
| // ==UserScript==
// @name Twitch Auto Theater
// @version 1.0.4
// @updateURL https://raw.githubusercontent.com/domosapien/Twitch-Auto-Theater/master/twitch-auto-theater.js
// @downloadURL https://raw.githubusercontent.com/domosapien/Twitch-Auto-Theater/master/twitch-auto-theater.js
// @match www.twitch.tv/*
// @grant none
// ==/UserScript==
/* jshint -W097 jquery:true */
'use strict';
var observer = new MutationObserver(function (mutations) {
mutations.some(function (mutation) {
if (!mutation.addedNodes) {
return false;
}
for (var i = 0; i < mutation.addedNodes.length; i++) {
// do things to your newly added nodes here
var $node = $(mutation.addedNodes[i]).find('button.player-button--theatre');
if ($node.length) {
$node.trigger('click');
observer.disconnect();
return true;
}
}
});
});
function startObserver() {
observer.observe(document.body, {
childList: true,
subtree: true,
attributes: false,
characterData: false
});
}
startObserver();
window.onpopstate = function (event) {
startObserver();
};
| Switch to Array.some instead of Array.forEach | Switch to Array.some instead of Array.forEach | JavaScript | mit | domosapien/Twitch-Auto-Theater | ---
+++
@@ -1,6 +1,6 @@
// ==UserScript==
// @name Twitch Auto Theater
-// @version 1.0.3
+// @version 1.0.4
// @updateURL https://raw.githubusercontent.com/domosapien/Twitch-Auto-Theater/master/twitch-auto-theater.js
// @downloadURL https://raw.githubusercontent.com/domosapien/Twitch-Auto-Theater/master/twitch-auto-theater.js
// @match www.twitch.tv/*
@@ -12,34 +12,34 @@
'use strict';
var observer = new MutationObserver(function (mutations) {
- mutations.forEach(function (mutation) {
- if (!mutation.addedNodes) {
- return;
- }
+ mutations.some(function (mutation) {
+ if (!mutation.addedNodes) {
+ return false;
+ }
- for (var i = 0; i < mutation.addedNodes.length; i++) {
- // do things to your newly added nodes here
- var $node = $(mutation.addedNodes[i]).find('button.player-button--theatre');
- if ($node.length) {
- $node.trigger('click');
- observer.disconnect();
- return;
- }
- }
- });
+ for (var i = 0; i < mutation.addedNodes.length; i++) {
+ // do things to your newly added nodes here
+ var $node = $(mutation.addedNodes[i]).find('button.player-button--theatre');
+ if ($node.length) {
+ $node.trigger('click');
+ observer.disconnect();
+ return true;
+ }
+ }
+ });
});
function startObserver() {
- observer.observe(document.body, {
- childList: true,
- subtree: true,
- attributes: false,
- characterData: false
- });
+ observer.observe(document.body, {
+ childList: true,
+ subtree: true,
+ attributes: false,
+ characterData: false
+ });
}
startObserver();
window.onpopstate = function (event) {
- startObserver();
+ startObserver();
}; |
fc25bde0a52f59ada7b5dcf34a1db6bbf4f87437 | addon/components/as-calendar/header.js | addon/components/as-calendar/header.js | import Ember from 'ember';
export default Ember.Component.extend({
classNameBindings: [':as-calendar-header'],
tagName: 'header',
isInCurrentWeek: Ember.computed.oneWay('model.isInCurrentWeek'),
model: null,
title: '',
actions: {
navigateWeek: function(index) {
this.get('model').navigateWeek(index);
if (this.attrs['onNavigateWeek']) {
this.attrs['onNavigateWeek'](index);
}
},
goToCurrentWeek: function() {
this.get('model').goToCurrentWeek();
}
}
});
| import Ember from 'ember';
export default Ember.Component.extend({
classNameBindings: [':as-calendar-header'],
tagName: 'header',
isInCurrentWeek: Ember.computed.oneWay('model.isInCurrentWeek'),
model: null,
title: '',
actions: {
navigateWeek: function(index) {
this.get('model').navigateWeek(index);
if (this.attrs['onNavigateWeek']) {
this.attrs['onNavigateWeek'](index);
}
},
goToCurrentWeek: function() {
this.get('model').goToCurrentWeek();
if (this.attrs['onNavigateWeek']) {
this.attrs['onNavigateWeek'](0);
}
}
}
});
| Make 'This week' button trigger onNavigateWeek with index 0 | Make 'This week' button trigger onNavigateWeek with index 0
The onNavigateWeek action can be used to monitor what dates are showing
on the calendar external to the component. Previously however the
calendar did not expose an event that triggers when the ‘This week’
button is clicked.
| JavaScript | mit | Subtletree/ember-calendar,Subtletree/ember-calendar,Subtletree/ember-calendar,Subtletree/ember-calendar | ---
+++
@@ -19,6 +19,10 @@
goToCurrentWeek: function() {
this.get('model').goToCurrentWeek();
+
+ if (this.attrs['onNavigateWeek']) {
+ this.attrs['onNavigateWeek'](0);
+ }
}
}
}); |
9d3d5df2a750d2698c37a37f653b431583becee3 | src/js/services/new-form.js | src/js/services/new-form.js | 'use strict';
angular.module('Teem')
.factory('NewForm', [
'$location', '$window',
function($location, $window) {
var scope,
objectName,
scopeFn = {
isNew () {
return $location.search().form === 'new';
},
cancelNew () {
scope[objectName].delete();
$window.history.back();
},
confirmNew () {
$location.search('form', undefined);
}
};
function initialize(s, o) {
scope = s;
objectName = o;
Object.assign(scope, scopeFn);
}
return {
initialize
};
}]);
| 'use strict';
angular.module('Teem')
.factory('NewForm', [
'$location', '$window',
function($location, $window) {
var scope,
objectName,
scopeFn = {
isNew () {
return $location.search().form === 'new';
},
cancelNew () {
scope[objectName].delete();
$location.search('form', undefined);
$window.history.back();
},
confirmNew () {
$location.search('form', undefined);
}
};
function initialize(s, o) {
scope = s;
objectName = o;
Object.assign(scope, scopeFn);
}
return {
initialize
};
}]);
| Remove search from location on cancel | Remove search from location on cancel
| JavaScript | agpl-3.0 | P2Pvalue/pear2pear,P2Pvalue/teem,P2Pvalue/teem,P2Pvalue/teem,Grasia/teem,P2Pvalue/pear2pear,Grasia/teem,Grasia/teem | ---
+++
@@ -12,6 +12,8 @@
},
cancelNew () {
scope[objectName].delete();
+
+ $location.search('form', undefined);
$window.history.back();
}, |
55c66b7895c6292affa472f6d381ab68781b3b44 | webapp/src/actions/DatapointActions.js | webapp/src/actions/DatapointActions.js | import Reflux from 'reflux'
import api from 'data/api'
const DatapointActions = Reflux.createActions({
'fetchDatapoints': { children: ['completed', 'failed'], asyncResult: true },
'clearDatapoints': 'clearDatapoints'
})
// API CALLS
// ---------------------------------------------------------------------------
DatapointActions.fetchDatapoints.listen(params => {
const query = _prepDatapointsQuery(params)
DatapointActions.fetchDatapoints.promise(api.datapoints(query))
})
// ACTION HELPERS
// ---------------------------------------------------------------------------
const _prepDatapointsQuery = (params) => {
let query = {
indicator__in: params.indicator_ids,
campaign_start: params.start_date,
campaign_end: params.end_date,
chart_type: params.type,
chart_uuid: params.uuid
}
if (params.type === 'ChoroplethMap' || params.type === 'MapChart' || params.type === 'BubbleMap') {
query['parent_location_id__in'] = params.location_ids
} else {
query['location_id__in'] = params.location_ids
}
if (params.indicator_filter) {
query['filter_indicator'] = params.indicator_filter.type
query['filter_value'] = params.indicator_filter.value
}
return query
}
export default DatapointActions
| import Reflux from 'reflux'
import api from 'data/api'
const DatapointActions = Reflux.createActions({
'fetchDatapoints': { children: ['completed', 'failed'], asyncResult: true },
'clearDatapoints': 'clearDatapoints'
})
// API CALLS
// ---------------------------------------------------------------------------
DatapointActions.fetchDatapoints.listen(params => {
const query = _prepDatapointsQuery(params)
DatapointActions.fetchDatapoints.promise(api.datapoints(query))
})
// ACTION HELPERS
// ---------------------------------------------------------------------------
const _prepDatapointsQuery = (params) => {
let query = {
indicator__in: params.indicator_ids,
campaign_start: params.start_date,
campaign_end: params.end_date,
chart_type: params.type,
chart_uuid: params.uuid
}
const type = params.type
const needsChildrenLocations = type === 'ChoroplethMap' || type === 'MapChart' || type === 'BubbleMap' || type === 'TableChart'
if (needsChildrenLocations) {
query['parent_location_id__in'] = params.location_ids
} else {
query['location_id__in'] = params.location_ids
}
if (params.indicator_filter) {
query['filter_indicator'] = params.indicator_filter.type
query['filter_value'] = params.indicator_filter.value
}
return query
}
export default DatapointActions
| Add parent_location_id to TableChart datapoints | Add parent_location_id to TableChart datapoints
| JavaScript | agpl-3.0 | unicef/rhizome,unicef/rhizome,unicef/rhizome,unicef/rhizome | ---
+++
@@ -24,7 +24,10 @@
chart_uuid: params.uuid
}
- if (params.type === 'ChoroplethMap' || params.type === 'MapChart' || params.type === 'BubbleMap') {
+ const type = params.type
+ const needsChildrenLocations = type === 'ChoroplethMap' || type === 'MapChart' || type === 'BubbleMap' || type === 'TableChart'
+
+ if (needsChildrenLocations) {
query['parent_location_id__in'] = params.location_ids
} else {
query['location_id__in'] = params.location_ids |
802d7e0b127f3b8769a2ae41c140624f894e3e84 | src/phantom/bootstrapper.js | src/phantom/bootstrapper.js | /**
* @fileoverview Run the bootstrap service
*/
var port = 3020,
system = require('system'),
page = require('webpage').create(),
server = require('./server').create(port),
util = require('./util'),
module = system.args[1],
config = system.args[2];
if (!module) {
console.error('missing module');
phantom.exit(1);
}
if (!config) {
console.error('missing config');
phantom.exit(1);
}
config = decodeURIComponent(config);
var url = 'http://localhost:' + port + '/' + module + '.html?config=' + config;
page.open(url, function(status) {
if (status !== 'success') {
console.error('Page could not be opened');
phantom.exit(1);
}
// TODO(rrp): Generalize this bit
// Wait for fyre-comment-stream el? (need to ensure 100% loaded somehow)
util.waitFor(function() {
return page.evaluate(function() {
return document.getElementsByClassName('fyre-comment-stream').length > 0;
});
}, function() {
var html = page.evaluate(function() {
return document.getElementById('bs').innerHTML;
});
console.log(html);
phantom.exit();
});
});
| /**
* @fileoverview Run the bootstrap service
*/
var port = 3020,
system = require('system'),
page = require('webpage').create(),
server = require('./server').create(port),
util = require('./util'),
module = system.args[1],
config = system.args[2];
if (!module) {
console.error('missing module');
phantom.exit(1);
}
if (!config) {
console.error('missing config');
phantom.exit(1);
}
config = decodeURIComponent(config);
var url = 'http://localhost:' + port + '/' + module + '.html?config=' + config;
console.log('<!-- html generated by Livefyre -->');
page.open(url, function(status) {
if (status !== 'success') {
console.error('Page could not be opened');
phantom.exit(1);
}
// TODO(rrp): Generalize this bit
// Wait for fyre-comment-stream el? (need to ensure 100% loaded somehow)
util.waitFor(function() {
return page.evaluate(function() {
return document.getElementsByClassName('fyre-comment-stream').length > 0;
});
}, function() {
var html = page.evaluate(function() {
return document.getElementById('bs').innerHTML;
});
console.log(html);
phantom.exit();
});
});
| Add html generated by lf comment in bs documents | Add html generated by lf comment in bs documents
| JavaScript | mit | Livefyre/lfbshtml,Livefyre/lfbshtml,Livefyre/lfbshtml | ---
+++
@@ -22,8 +22,8 @@
config = decodeURIComponent(config);
var url = 'http://localhost:' + port + '/' + module + '.html?config=' + config;
+console.log('<!-- html generated by Livefyre -->');
page.open(url, function(status) {
-
if (status !== 'success') {
console.error('Page could not be opened');
phantom.exit(1); |
b5c84e7b6c87d0c893c4994041f4086206107df1 | frontend/src/constants/messages.js | frontend/src/constants/messages.js | // Default values for form fields.
export const ACTIVITY_TITLE_PLACEHOLDER = 'What will you be doing?';
export const ACTIVITY_DESCRIPTION_PLACEHOLDER = 'Add some details!';
| // Default and placeholder values for form fields.
export const ACTIVITY_TITLE_PLACEHOLDER = 'What will you be doing?';
export const ACTIVITY_DESCRIPTION_PLACEHOLDER = 'Add some details!';
export const TRIPS_TITLE_DEFAULT = 'Untitled Trip';
export const TRIPS_DESTINATION_DEFAULT = 'No Destination';
export const TRIPS_TITLE_PLACEHOLDER = 'Title your trip!';
export const TRIPS_DESCRIPTION_PLACEHOLDER = 'Add some details!';
export const TRIPS_DESTINATION_PLACEHOLDER = 'Where will you be going?';
export const TRIPS_COLLAB_EMAIL_PLACEHOLDER = 'person@email.xyz';
| Add default and placeholder value for save trip modal. | Add default and placeholder value for save trip modal.
| JavaScript | apache-2.0 | googleinterns/SLURP,googleinterns/SLURP,googleinterns/SLURP | ---
+++
@@ -1,3 +1,10 @@
-// Default values for form fields.
+// Default and placeholder values for form fields.
export const ACTIVITY_TITLE_PLACEHOLDER = 'What will you be doing?';
export const ACTIVITY_DESCRIPTION_PLACEHOLDER = 'Add some details!';
+
+export const TRIPS_TITLE_DEFAULT = 'Untitled Trip';
+export const TRIPS_DESTINATION_DEFAULT = 'No Destination';
+export const TRIPS_TITLE_PLACEHOLDER = 'Title your trip!';
+export const TRIPS_DESCRIPTION_PLACEHOLDER = 'Add some details!';
+export const TRIPS_DESTINATION_PLACEHOLDER = 'Where will you be going?';
+export const TRIPS_COLLAB_EMAIL_PLACEHOLDER = 'person@email.xyz'; |
cc41515eea96647107984d81a7faa35f4a5f40f7 | codebrag-ui/src/main/webapp/scripts/auth/authService.js | codebrag-ui/src/main/webapp/scripts/auth/authService.js | angular.module('codebrag.auth')
.factory('authService', function($http, httpRequestsBuffer, $q, $rootScope, events) {
var authService = {
loggedInUser: undefined,
login: function(user) {
var loginRequest = $http.post('rest/users', user, {bypassQueue: true});
return loginRequest.then(function(response) {
authService.loggedInUser = response.data;
httpRequestsBuffer.retryAllRequest();
});
},
logout: function() {
var logoutRequest = $http.get('rest/users/logout');
return logoutRequest.then(function() {
authService.loggedInUser = undefined;
})
},
isAuthenticated: function() {
return !angular.isUndefined(authService.loggedInUser);
},
isNotAuthenticated: function() {
return !authService.isAuthenticated();
},
requestCurrentUser: function() {
if (authService.isAuthenticated()) {
return $q.when(authService.loggedInUser);
}
var promise = $http.get('rest/users');
return promise.then(function(response) {
authService.loggedInUser = response.data;
$rootScope.$broadcast(events.loggedIn);
return $q.when(authService.loggedInUser);
});
}
};
return authService;
}); | angular.module('codebrag.auth')
.factory('authService', function($http, httpRequestsBuffer, $q, $rootScope, events) {
var authService = {
loggedInUser: undefined,
login: function(user) {
var loginRequest = $http.post('rest/users', user, {bypassQueue: true});
return loginRequest.then(function(response) {
authService.loggedInUser = response.data;
$rootScope.$broadcast(events.loggedIn);
httpRequestsBuffer.retryAllRequest();
});
},
logout: function() {
var logoutRequest = $http.get('rest/users/logout');
return logoutRequest.then(function() {
authService.loggedInUser = undefined;
})
},
isAuthenticated: function() {
return !angular.isUndefined(authService.loggedInUser);
},
isNotAuthenticated: function() {
return !authService.isAuthenticated();
},
requestCurrentUser: function() {
if (authService.isAuthenticated()) {
return $q.when(authService.loggedInUser);
}
var promise = $http.get('rest/users');
return promise.then(function(response) {
authService.loggedInUser = response.data;
$rootScope.$broadcast(events.loggedIn);
return $q.when(authService.loggedInUser);
});
}
};
return authService;
}); | Add broadcasting of login event for non-github login | Add broadcasting of login event for non-github login
| JavaScript | agpl-3.0 | cazacugmihai/codebrag,softwaremill/codebrag,softwaremill/codebrag,cazacugmihai/codebrag,softwaremill/codebrag,cazacugmihai/codebrag,softwaremill/codebrag,cazacugmihai/codebrag,cazacugmihai/codebrag | ---
+++
@@ -10,6 +10,7 @@
var loginRequest = $http.post('rest/users', user, {bypassQueue: true});
return loginRequest.then(function(response) {
authService.loggedInUser = response.data;
+ $rootScope.$broadcast(events.loggedIn);
httpRequestsBuffer.retryAllRequest();
});
}, |
a75ce12bd186e13ce9ee335a3f6f17862fe3d51e | plugins/html5video.js | plugins/html5video.js | /*
* CSS Modal Plugin for HTML5 Video (play/pause)
* Author: Anselm Hannemann
* Date: 2014-02-04
*/
(function (global) {
'use strict';
var CSSModal = global.CSSModal;
// If CSS Modal is still undefined, throw an error
if (!CSSModal) {
throw new Error('Error: CSSModal is not loaded.');
}
var videos;
// Enables Auto-Play when calling modal
CSSModal.on('cssmodal:show', document, function (event) {
// Fetch all video elements in active modal
videos = CSSModal.activeElement.querySelectorAll('video');
if (videos.length > 0) {
// Play first video in modal
videos[0].play();
}
});
// If modal is closed, pause all videos
CSSModal.on('cssmodal:hide', document, function (event) {
var i = 0;
if (videos.length > 0) {
// Pause all videos in active modal
for (; i < videos.length; i++) {
videos[i].pause();
}
}
});
}(window));
| /*
* CSS Modal Plugin for HTML5 Video (play/pause)
* Author: Anselm Hannemann
* Date: 2014-02-04
*/
(function (global) {
'use strict';
var CSSModal = global.CSSModal;
var videos;
// If CSS Modal is still undefined, throw an error
if (!CSSModal) {
throw new Error('Error: CSSModal is not loaded.');
}
// Enables Auto-Play when calling modal
CSSModal.on('cssmodal:show', document, function () {
// Fetch all video elements in active modal
videos = CSSModal.activeElement.querySelectorAll('video');
// Play first video in modal
if (videos.length > 0) {
videos[0].play();
}
});
// If modal is closed, pause all videos
CSSModal.on('cssmodal:hide', document, function () {
var i = 0;
// Pause all videos in active modal
if (videos.length > 0) {
for (; i < videos.length; i++) {
videos[i].pause();
}
}
});
}(window));
| Fix HTML5 Video plugin JSHint errors | Fix HTML5 Video plugin JSHint errors
| JavaScript | mit | joerodrig3/css-modal,shawinder/css-modal,0111001101111010/css-modal,joerodrig3/css-modal,ableco/css-modal,shawinder/css-modal,ableco/css-modal,drublic/css-modal,drublic/css-modal | ---
+++
@@ -9,31 +9,31 @@
'use strict';
var CSSModal = global.CSSModal;
+ var videos;
// If CSS Modal is still undefined, throw an error
if (!CSSModal) {
throw new Error('Error: CSSModal is not loaded.');
}
- var videos;
+ // Enables Auto-Play when calling modal
+ CSSModal.on('cssmodal:show', document, function () {
- // Enables Auto-Play when calling modal
- CSSModal.on('cssmodal:show', document, function (event) {
// Fetch all video elements in active modal
videos = CSSModal.activeElement.querySelectorAll('video');
+ // Play first video in modal
if (videos.length > 0) {
- // Play first video in modal
videos[0].play();
}
});
// If modal is closed, pause all videos
- CSSModal.on('cssmodal:hide', document, function (event) {
+ CSSModal.on('cssmodal:hide', document, function () {
var i = 0;
+ // Pause all videos in active modal
if (videos.length > 0) {
- // Pause all videos in active modal
for (; i < videos.length; i++) {
videos[i].pause();
} |
7f7856a5e5d33ea5c771bee72134f274d4f97746 | blueprints/ember-fullcalendar/index.js | blueprints/ember-fullcalendar/index.js | module.exports = {
normalizeEntityName: function() {},
afterInstall: function() {
return this.addBowerPackageToProject('fullcalendar', '^2.7.3').then(function () {
return this.addBowerPackageToProject('fullcalendar-scheduler', '^1.3.2');
});
}
};
| module.exports = {
normalizeEntityName: function() {},
afterInstall: function() {
return this.addBowerPackageToProject('fullcalendar', '^2.7.3').then(() => {
return this.addBowerPackageToProject('fullcalendar-scheduler', '^1.3.2');
});
}
};
| Fix second regression in blueprint. | Fix second regression in blueprint.
| JavaScript | mit | scoutforpets/ember-fullcalendar,scoutforpets/ember-fullcalendar | ---
+++
@@ -2,7 +2,7 @@
normalizeEntityName: function() {},
afterInstall: function() {
- return this.addBowerPackageToProject('fullcalendar', '^2.7.3').then(function () {
+ return this.addBowerPackageToProject('fullcalendar', '^2.7.3').then(() => {
return this.addBowerPackageToProject('fullcalendar-scheduler', '^1.3.2');
});
} |
50531c2c63d4e0291bcbbf2037dd3dae4b3a3115 | src/search/searchresults.js | src/search/searchresults.js | import PropTypes from 'prop-types';
import React, { Fragment } from 'react';
/**
* The Search Results component
*
* @disable-docs
*/
const SearchResults = ( page ) => {
return (
<div className="container-fluid au-body">
<div className="row">
<div className="col-xs-12 searchresults__list">
<h2 className="au-display-xxl">{ page.heading }</h2>
<p><span id="searchresults__count" /> results for [query]</p>
<form className="search__searchbox" role="search" autoComplete="off" action="/search" method="get">
<input type="search" className="au-text-input" name="text-input" id="text-input" placeholder="Digital Guides"/>
<input type="submit" className="au-btn au-btn--light icon icon--search" value="Search" />
</form>
<ul className="searchresults__ul" id="searchresults__resultslist"></ul>
</div>
</div>
</div>
);
}
SearchResults.propTypes = {
/**
* _body: (partials)(4)
*/
_body: PropTypes.node.isRequired,
};
SearchResults.defaultProps = {};
export default SearchResults;
| import PropTypes from 'prop-types';
import React, { Fragment } from 'react';
/**
* The Search Results component
*
* @disable-docs
*/
const SearchResults = ( page ) => {
return (
<div className="container-fluid au-body">
<div className="row">
<div className="col-xs-12 searchresults__list">
<h2 className="au-display-xxl">{ page.heading }</h2>
<p><span id="searchresults__count" /> results for [query]</p>
<form className="search__searchbox" role="search" autoComplete="off" action="/search" method="get">
<input type="search" className="au-text-input" name="q" id="text-input" placeholder="Digital Guides"/>
<input type="submit" className="au-btn au-btn--light icon icon--search" value="Search" />
</form>
<ul className="searchresults__ul" id="searchresults__resultslist"></ul>
</div>
</div>
</div>
);
}
SearchResults.propTypes = {
/**
* _body: (partials)(4)
*/
_body: PropTypes.node.isRequired,
};
SearchResults.defaultProps = {};
export default SearchResults;
| Use name =q (fix the onpage search) | Use name =q (fix the onpage search)
| JavaScript | mit | govau/service-manual | ---
+++
@@ -17,7 +17,7 @@
<p><span id="searchresults__count" /> results for [query]</p>
<form className="search__searchbox" role="search" autoComplete="off" action="/search" method="get">
- <input type="search" className="au-text-input" name="text-input" id="text-input" placeholder="Digital Guides"/>
+ <input type="search" className="au-text-input" name="q" id="text-input" placeholder="Digital Guides"/>
<input type="submit" className="au-btn au-btn--light icon icon--search" value="Search" />
</form>
|
fdee3899be6aa188bea7ccac1b0fc7e3b3df7876 | public/demo/graphics-components/texturemap.js | public/demo/graphics-components/texturemap.js | !function(exports) {
'use strict';
// Gets textures from URLs.
// Keeps LRU cache so that textures are rebound as infrequently as possible.
// How to implement LRU cache:
// * Check if raster texture maps to id in texture slot
// * If yes, awesome
// * If no, rebind to least most recently use texture
// * Implement lru texture as a linked list duh
// * Slots in tex array point to { id, iterator } tuples
function TextureMap() {
}
TextureMap.prototype.fromUrl = function() {};
function normalizeUrl(url) {
}
exports.TextureMap = TextureMap;
}(demo);
| !function(exports) {
'use strict';
// Gets textures from URLs.
// Keeps LRU cache so that textures are rebound as infrequently as possible.
// How to implement LRU cache:
// * Check if raster texture maps to id in texture slot
// * If yes, awesome
// * If no, rebind to least most recently use texture
// * Implement lru texture as a linked list duh
// * Slots in tex array point to { id, iterator } tuples
//
// Note: use a scoring algorithm, NOT strict LRU. Every time something is
// used, it gets its score bumped. The list is the top 32 scoring textures: to
// get into the list, you need to beat the score of the lowest one. Add some
// sort of decay to the algorithm so that previously-hot but now cold textures
// get ejected relatively quickly.
function TextureMap() {
}
TextureMap.prototype.fromUrl = function() {};
function normalizeUrl(url) {
}
exports.TextureMap = TextureMap;
}(demo);
| Add note about scoring algorithms for tex cache | Add note about scoring algorithms for tex cache
| JavaScript | mit | reissbaker/gamekernel,reissbaker/gamekernel | ---
+++
@@ -9,6 +9,12 @@
// * If no, rebind to least most recently use texture
// * Implement lru texture as a linked list duh
// * Slots in tex array point to { id, iterator } tuples
+ //
+ // Note: use a scoring algorithm, NOT strict LRU. Every time something is
+ // used, it gets its score bumped. The list is the top 32 scoring textures: to
+ // get into the list, you need to beat the score of the lowest one. Add some
+ // sort of decay to the algorithm so that previously-hot but now cold textures
+ // get ejected relatively quickly.
function TextureMap() {
}
|
f59505b4453971f6638da581e2961d789cc2a7b4 | app/routes/index.js | app/routes/index.js | 'use strict';
var path = process.cwd();
var Graphriend = require(path + '/app/controllers/Graphriend.server.js');
var sess;
module.exports = function (app) {
function isLoggedIn (req, res, next) {
sess = req.session;
if (sess.user) {
return next();
} else {
res.redirect('/');
}
}
var graPhriend = new Graphriend();
var user = {
isLogged: false,
name: 'Jinme',
username: 'mirabalj'
}
app.route('/')
.get(function (req, res) {
res.render('main', { user: user, page: 'index' });
});
app.post('/api/signup', graPhriend.signUp);
app.post('/api/login', graPhriend.logIn);
/* Example Authenticated verify
app.route('/profile')
.get(isLoggedIn, function (req, res) {
res.render('main', { user: sess.user, page: 'profile' });
});
*/
/* Example REST api
app.route('/friends')
.get(isLoggedIn, graPhriend.getFriend)
.post(isLoggedIn, graPhriend.addFriend)
.delete(isLoggedIn, graPhriend.delFriend);
*/
};
| 'use strict';
var path = process.cwd();
var Graphriend = require(path + '/app/controllers/Graphriend.server.js');
var sess;
module.exports = function (app) {
function isLoggedIn (req, res, next) {
sess = req.session;
if (sess.user || req.url === '/') {
return next();
} else {
res.redirect('/');
}
}
var graPhriend = new Graphriend();
var user = {
isLogged: false,
name: 'Jinme',
username: 'mirabalj'
}
app.route('/')
.get(isLoggedIn, function (req, res) {
res.render('main', { user: sess.user, page: 'index' });
});
app.post('/api/signup', graPhriend.signUp);
app.post('/api/login', graPhriend.logIn);
/* Example Authenticated verify
app.route('/profile')
.get(isLoggedIn, function (req, res) {
res.render('main', { user: sess.user, page: 'profile' });
});
*/
/* Example REST api
app.route('/friends')
.get(isLoggedIn, graPhriend.getFriend)
.post(isLoggedIn, graPhriend.addFriend)
.delete(isLoggedIn, graPhriend.delFriend);
*/
};
| Change main route to get session user | Change main route to get session user
| JavaScript | mit | mirabalj/graphriend,mirabalj/graphriend | ---
+++
@@ -8,7 +8,7 @@
function isLoggedIn (req, res, next) {
sess = req.session;
- if (sess.user) {
+ if (sess.user || req.url === '/') {
return next();
} else {
res.redirect('/');
@@ -24,8 +24,8 @@
}
app.route('/')
- .get(function (req, res) {
- res.render('main', { user: user, page: 'index' });
+ .get(isLoggedIn, function (req, res) {
+ res.render('main', { user: sess.user, page: 'index' });
});
app.post('/api/signup', graPhriend.signUp); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.