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 |
|---|---|---|---|---|---|---|---|---|---|---|
0b8a5a18f05eed0c10f357f3f8f7231ff964d087 | tools/scripts/property-regex.js | tools/scripts/property-regex.js | const {
assemble,
writeFile,
unicodeVersion
} = require('./utils.js');
// This includes only the binary properties required by UTS18 RL1.2 for level 1 Unicode regex
// support, minus `Assigned` which has special handling since it is the inverse of Unicode category
// `Unassigned`. To include all binary properties, change this to:
// `const properties = require(`${unicodeVersion}`).Binary_Property;`
const properties = [
'ASCII',
'Alphabetic',
'Any',
'Default_Ignorable_Code_Point',
'Lowercase',
'Noncharacter_Code_Point',
'Uppercase',
'White_Space'
];
const result = [];
for (const property of properties) {
const codePoints = require(`${unicodeVersion}/Binary_Property/${property}/code-points.js`);
result.push(assemble({
name: property,
codePoints
}));
}
writeFile('properties.js', result);
| const {
assemble,
writeFile,
unicodeVersion
} = require('./utils.js');
// This includes only the binary properties required by UTS18 RL1.2 for level 1 Unicode regex
// support, minus `Assigned` which has special handling since it is the inverse of Unicode category
// `Unassigned`. To include all binary properties, change this to:
// `const properties = require(`${unicodeVersion}`).Binary_Property;`
const properties = [
'ASCII',
'Alphabetic',
'Any',
'Default_Ignorable_Code_Point',
'Emoji',
'Lowercase',
'Noncharacter_Code_Point',
'Uppercase',
'White_Space'
];
const result = [];
for (const property of properties) {
const codePoints = require(`${unicodeVersion}/Binary_Property/${property}/code-points.js`);
result.push(assemble({
name: property,
codePoints
}));
}
writeFile('properties.js', result);
| Add Emoji list of `Binary_Property`s | Add Emoji list of `Binary_Property`s
| JavaScript | mit | slevithan/xregexp,slevithan/XRegExp,slevithan/XRegExp,slevithan/xregexp,GerHobbelt/xregexp,GerHobbelt/xregexp,slevithan/xregexp,GerHobbelt/xregexp | ---
+++
@@ -13,6 +13,7 @@
'Alphabetic',
'Any',
'Default_Ignorable_Code_Point',
+ 'Emoji',
'Lowercase',
'Noncharacter_Code_Point',
'Uppercase', |
dce5cf9c470b25f1b6e60d8f5cf710a63ab56afd | service_worker.js | service_worker.js | self.addEventListener('install', function _installHandler(e) {
e.waitUntil(
caches.open('static')
.then(function _addToCache(cache) {
cache.addAll([
'/css/master.css',
'/js/app.js',
'/views/templates.html',
'/'
])
})
);
});
self.addEventListener('fetch', function _fetchHandler(e) {
e.respondWith(
caches.match(e.request)
.then(function (response) {
if (response) {
return response;
}
return fetch(e.request);
})
);
}); | Add a functioning service worker | Add a functioning service worker
| JavaScript | apache-2.0 | vishwaabhinav/xkcd-pwa,vishwaabhinav/xkcd-pwa | ---
+++
@@ -0,0 +1,25 @@
+self.addEventListener('install', function _installHandler(e) {
+ e.waitUntil(
+ caches.open('static')
+ .then(function _addToCache(cache) {
+ cache.addAll([
+ '/css/master.css',
+ '/js/app.js',
+ '/views/templates.html',
+ '/'
+ ])
+ })
+ );
+});
+
+self.addEventListener('fetch', function _fetchHandler(e) {
+ e.respondWith(
+ caches.match(e.request)
+ .then(function (response) {
+ if (response) {
+ return response;
+ }
+ return fetch(e.request);
+ })
+ );
+}); | |
91e539f98821963bb0f6fd35ef188660e6ff01c6 | imports/client/startup/routes.js | imports/client/startup/routes.js | import { Meteor } from 'meteor/meteor';
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import AppContainer from '../containers/AppContainer';
import AboutPage from '../pages/AboutPage';
import NotFoundPage from '../pages/NotFoundPage';
const route = (path, component, onEnter) => (
<Route path={path} component={component} onEnter={onEnter} />
);
const renderRoutes = () => {
render(
<Router onUpdate={() => window.scrollTo(0, 0)} history={browserHistory}>
<Route path="/" component={AppContainer}>
<IndexRoute component={AboutPage} />
{route('home', AboutPage)}
{route('*', NotFoundPage)}
</Route>
</Router>,
document.getElementById('react-root')
);
};
export default renderRoutes;
| import { Meteor } from 'meteor/meteor';
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import AppContainer from '../containers/AppContainer';
import AboutPage from '../pages/AboutPage';
import NotFoundPage from '../pages/NotFoundPage';
const route = (path, component, onEnter) => (
<Route path={path} component={component} onEnter={onEnter} />
);
const renderRoutes = () => {
render(
<Router onUpdate={() => window.scrollTo(0, 0)} history={browserHistory}>
<Route path="/" component={AppContainer}>
<IndexRoute component={AboutPage} />
{route('home', AboutPage)}
</Route>
{route('*', NotFoundPage)}
</Router>,
document.getElementById('react-root')
);
};
export default renderRoutes;
| Remove AppContainer layout from 404 page | Remove AppContainer layout from 404 page
| JavaScript | apache-2.0 | evancorl/skate-scenes,evancorl/skate-scenes,evancorl/portfolio,evancorl/skate-scenes,evancorl/portfolio,evancorl/portfolio | ---
+++
@@ -17,8 +17,8 @@
<Route path="/" component={AppContainer}>
<IndexRoute component={AboutPage} />
{route('home', AboutPage)}
- {route('*', NotFoundPage)}
</Route>
+ {route('*', NotFoundPage)}
</Router>,
document.getElementById('react-root')
); |
e7f43a25af82d8d840ad7765c7f610f7a8e58a5b | test-projects/electron-log-test-webpack/webpack.config.js | test-projects/electron-log-test-webpack/webpack.config.js | module.exports = [
{
mode: "development",
entry: ['./src/main.js'],
output: { filename: 'main.js' },
target: 'electron-main',
module: {
rules: [
{
test: /.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
options: {
presets: [require('babel-preset-latest')]
}
}
]
},
node: {
__dirname: false
}
},
{
mode: "development",
entry: ['./src/renderer.js'],
output: { filename: 'renderer.js' },
target: 'electron-renderer',
module: {
rules: [
{
test: /.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
options: {
presets: [require('babel-preset-latest')]
}
}
]
}
}
];
| 'use strict';
const path = require('path');
module.exports = [
{
mode: "development",
entry: ['./src/main.js'],
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
},
target: 'electron-main',
module: {
rules: [
{
test: /.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
options: {
presets: [require('babel-preset-latest')]
}
}
]
},
node: {
__dirname: false
}
},
{
mode: "development",
entry: ['./src/renderer.js'],
output: {
filename: 'renderer.js',
path: path.resolve(__dirname, 'dist')
},
target: 'electron-renderer',
module: {
rules: [
{
test: /.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
options: {
presets: [require('babel-preset-latest')]
}
}
]
}
}
];
| Fix test-projects install/build: webpack 4 changes | Fix test-projects install/build: webpack 4 changes
| JavaScript | mit | megahertz/electron-log,megahertz/electron-log,megahertz/electron-log | ---
+++
@@ -1,8 +1,15 @@
+'use strict';
+
+const path = require('path');
+
module.exports = [
{
mode: "development",
entry: ['./src/main.js'],
- output: { filename: 'main.js' },
+ output: {
+ filename: 'main.js',
+ path: path.resolve(__dirname, 'dist')
+ },
target: 'electron-main',
module: {
rules: [
@@ -23,7 +30,10 @@
{
mode: "development",
entry: ['./src/renderer.js'],
- output: { filename: 'renderer.js' },
+ output: {
+ filename: 'renderer.js',
+ path: path.resolve(__dirname, 'dist')
+ },
target: 'electron-renderer',
module: {
rules: [ |
666410d49d3aac697200737dea8d19b77d5708a4 | resources/public/javascript/tryclojure.js | resources/public/javascript/tryclojure.js | function eval_clojure(code) {
var data;
$.ajax({
url: "eval.json",
data: { expr : code },
async: false,
success: function(res) { data = res; }
});
return data;
}
function html_escape(val) {
var result = val;
result = result.replace(/\n/g, "<br/>");
result = result.replace(/[<]/g, "<");
result = result.replace(/[>]/g, ">");
return result;
}
function onValidate(input) {
return (input != "");
}
function onHandle(line, report) {
var input = $.trim(line);
// perform evaluation
var data = eval_clojure(input);
// handle error
if (data.error) {
return [{msg: data.message, className: "jquery-console-message-error"}];
}
// display expr results
return [{msg: data.result, className: "jquery-console-message-value"}];
}
var controller;
$(document).ready(function() {
controller = $("#console").console({
welcomeMessage:'',
promptLabel: '> ',
commandValidate: onValidate,
commandHandle: onHandle,
autofocus:true,
animateScroll:true,
promptHistory:true
});
});
| function eval_clojure(code) {
var data;
$.ajax({
url: "eval.json",
data: {
command: {
expr: code,
mode: mode
}
},
async: false,
success: function(res) { data = res; }
});
return data;
}
function html_escape(val) {
var result = val;
result = result.replace(/\n/g, "<br/>");
result = result.replace(/[<]/g, "<");
result = result.replace(/[>]/g, ">");
return result;
}
function onValidate(input) {
return (input != "");
}
function onHandle(line, report) {
var input = $.trim(line);
// perform evaluation
var data = eval_clojure(input);
// handle error
if (data.error) {
return [{msg: data.message, className: "jquery-console-message-error"}];
}
// display expr results
return [{msg: data.result, className: "jquery-console-message-value"}];
}
var controller;
$(document).ready(function() {
controller = $("#console").console({
welcomeMessage:'',
promptLabel: '> ',
commandValidate: onValidate,
commandHandle: onHandle,
autofocus:true,
animateScroll:true,
promptHistory:true
});
});
| Send console mode - code or story. | Send console mode - code or story. | JavaScript | mit | maryrosecook/islaclj | ---
+++
@@ -2,7 +2,12 @@
var data;
$.ajax({
url: "eval.json",
- data: { expr : code },
+ data: {
+ command: {
+ expr: code,
+ mode: mode
+ }
+ },
async: false,
success: function(res) { data = res; }
}); |
525286d37f8fcc29c3ad0a9036f1217b87b4fd81 | website/app/application/core/projects/project/files/file-edit-controller.js | website/app/application/core/projects/project/files/file-edit-controller.js | (function (module) {
module.controller("FileEditController", FileEditController);
FileEditController.$inject = ['file', '$scope'];
/* @ngInject */
function FileEditController(file, $scope) {
console.log('FileEditController');
var ctrl = this;
ctrl.file = file;
$scope.$on('$viewContentLoaded', function(event) {
console.log('$viewContentLoaded', event);
});
}
}(angular.module('materialscommons'))); | (function (module) {
module.controller("FileEditController", FileEditController);
FileEditController.$inject = ['file'];
/* @ngInject */
function FileEditController(file) {
var ctrl = this;
ctrl.file = file;
}
}(angular.module('materialscommons'))); | Remove debug of ui router state changes. | Remove debug of ui router state changes.
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -1,16 +1,11 @@
(function (module) {
module.controller("FileEditController", FileEditController);
- FileEditController.$inject = ['file', '$scope'];
+ FileEditController.$inject = ['file'];
/* @ngInject */
- function FileEditController(file, $scope) {
- console.log('FileEditController');
+ function FileEditController(file) {
var ctrl = this;
ctrl.file = file;
-
- $scope.$on('$viewContentLoaded', function(event) {
- console.log('$viewContentLoaded', event);
- });
}
}(angular.module('materialscommons'))); |
f9ba237e2746b485e062c30749c45927af832424 | src/js/bin4features.js | src/js/bin4features.js | $(document).ready(function() {
var menuUrl = "https://www.bin4burgerlounge.com/our-downtown-menu/";
$.ajax({
url: "http://www.corsmirror.com/v1/cors?url=" + menuUrl,
dataType: "html",
crossDomain: true,
success: writeData
});
function writeData(data, textStatus, jqXHR) {
var root = $($.parseHTML(data));
writeItem(root, "burger");
writeItem(root, "appy");
writeItem(root, "feature cocktail");
writeItem(root, "dessert");
}
function writeItem(root, name) {
var itemElem = root.find(".slide-features .menu-item")
.filter(function(index, elem) {
var text = jQuery(elem).find(".item-label").first().text();
return (text == name);
}).first();
name = name.replace(" ","");
jQuery("#" + name + "_name").text(itemElem.find(".item-title").text());
jQuery("#" + name + "_price").text(itemElem.find(".item-price").text());
jQuery("#" + name + "_description").text(itemElem.find("p").text());
}
});
| $(document).ready(function() {
var menuUrl = "https://www.bin4burgerlounge.com/our-downtown-menu/";
$.ajax({
url: "https://cors-anywhere.herokuapp.com/" + menuUrl,
dataType: "html",
crossDomain: true,
success: writeData
});
function writeData(data, textStatus, jqXHR) {
var root = $($.parseHTML(data));
writeItem(root, "burger");
writeItem(root, "appy");
writeItem(root, "feature cocktail");
writeItem(root, "dessert");
}
function writeItem(root, name) {
var itemElem = root.find(".slide-features .menu-item")
.filter(function(index, elem) {
var text = jQuery(elem).find(".item-label").first().text();
return (text == name);
}).first();
name = name.replace(" ","");
jQuery("#" + name + "_name").text(itemElem.find(".item-title").text());
jQuery("#" + name + "_price").text(itemElem.find(".item-price").text());
jQuery("#" + name + "_description").text(itemElem.find("p").text());
}
});
| Revert "Update CORS provider, again..." | Revert "Update CORS provider, again..."
This reverts commit cdd91c9eca4ea4675296e96c8ede6c8f8d7a3236.
| JavaScript | mit | connor-bracewell/nnorco,connor-bracewell/nnorco,connor-bracewell/nnorco,connor-bracewell/nnorco | ---
+++
@@ -2,7 +2,7 @@
var menuUrl = "https://www.bin4burgerlounge.com/our-downtown-menu/";
$.ajax({
- url: "http://www.corsmirror.com/v1/cors?url=" + menuUrl,
+ url: "https://cors-anywhere.herokuapp.com/" + menuUrl,
dataType: "html",
crossDomain: true,
success: writeData |
91ea8bacfefc231cc18c472bdd11c50e14370cf8 | spec/responseparser_spec.js | spec/responseparser_spec.js | var ResponseParser = require('../lib/responseparser'),
winston = require('winston'),
fs = require('fs'),
path = require('path');
describe('responseparser', function() {
var parser = new ResponseParser({
format: 'xml',
logger: new winston.Logger({ transports: [] })
});
it('should return xml when format is xml', function() {
var callbackSpy = jasmine.createSpy(),
xml = fs.readFileSync(
path.join(__dirname +
'/responses/release-tracks-singletrack.xml'),
'utf8');
parser.parse(callbackSpy, null, xml);
expect(callbackSpy).toHaveBeenCalled();
expect(callbackSpy).toHaveBeenCalledWith(null, xml);
});
});
| var ResponseParser = require('../lib/responseparser'),
winston = require('winston'),
fs = require('fs'),
path = require('path');
describe('responseparser', function() {
var parser = new ResponseParser({
format: 'xml',
logger: new winston.Logger({ transports: [] })
});
it('should return xml when format is xml', function() {
var callbackSpy = jasmine.createSpy(),
xml = fs.readFileSync(
path.join(__dirname +
'/responses/release-tracks-singletrack.xml'),
'utf8');
parser.parse(callbackSpy, null, xml);
expect(callbackSpy).toHaveBeenCalled();
expect(callbackSpy).toHaveBeenCalledWith(null, xml);
});
it('should return xml when format is XML', function() {
var callbackSpy = jasmine.createSpy(),
xml = fs.readFileSync(
path.join(__dirname +
'/responses/release-tracks-singletrack.xml'),
'utf8');
parser.format = 'XML';
parser.parse(callbackSpy, null, xml);
expect(callbackSpy).toHaveBeenCalled();
expect(callbackSpy).toHaveBeenCalledWith(null, xml);
});
});
| Add case sensitive test for format in response parser | Add case sensitive test for format in response parser
| JavaScript | isc | raoulmillais/7digital-api,7digital/7digital-api,raoulmillais/node-7digital-api | ---
+++
@@ -20,4 +20,16 @@
expect(callbackSpy).toHaveBeenCalledWith(null, xml);
});
+ it('should return xml when format is XML', function() {
+ var callbackSpy = jasmine.createSpy(),
+ xml = fs.readFileSync(
+ path.join(__dirname +
+ '/responses/release-tracks-singletrack.xml'),
+ 'utf8');
+
+ parser.format = 'XML';
+ parser.parse(callbackSpy, null, xml);
+ expect(callbackSpy).toHaveBeenCalled();
+ expect(callbackSpy).toHaveBeenCalledWith(null, xml);
+ });
}); |
19fb3ee91715ea8da3a5cb6e1d3dd5e7016ad493 | src/charting/MobileChart.js | src/charting/MobileChart.js | import React, { PropTypes } from 'react';
import EChart from './EChart';
import SizeProvider from '../_common/SizeProvider';
import createOptions from './options/MobileChartOptions';
const theme = {
background: 'white',
line: 'rgba(42, 48, 82, 0.8)',
fill: 'rgba(42, 48, 82, 0.2)',
text: '#999',
grid: '#eee',
axisText: 'rgba(64, 68, 72, .5)',
};
export default class TradeChart extends React.Component {
static propTypes = {
history: PropTypes.array.isRequired,
spot: PropTypes.number,
};
static defaultProps = {
history: [],
spot: 0,
};
render() {
const { history, spot } = this.props;
const options = createOptions({ history, spot: +spot, theme });
return (
<SizeProvider style={{ width: '100%', height: '120px' }}>
<EChart
options={options}
{...this.props}
/>
</SizeProvider>
);
}
}
| import React, { PropTypes } from 'react';
import EChart from './EChart';
import SizeProvider from '../_common/SizeProvider';
import createOptions from './options/MobileChartOptions';
const theme = {
background: 'white',
line: 'rgba(42, 48, 82, 0.8)',
fill: 'rgba(42, 48, 82, 0.2)',
text: '#999',
grid: '#eee',
axisText: 'rgba(64, 68, 72, .5)',
};
export default class TradeChart extends React.Component {
static propTypes = {
history: PropTypes.array.isRequired,
spot: PropTypes.number,
};
static defaultProps = {
spot: 0,
};
render() {
const { history, spot } = this.props;
if (history.length === 0) return null;
const options = createOptions({ history, spot: +spot, theme });
return (
<SizeProvider style={{ width: '100%', height: '120px' }}>
<EChart
options={options}
{...this.props}
/>
</SizeProvider>
);
}
}
| Fix error when tick history is empty | Fix error when tick history is empty
| JavaScript | mit | nazaninreihani/binary-next-gen,qingweibinary/binary-next-gen,binary-com/binary-next-gen,qingweibinary/binary-next-gen,nazaninreihani/binary-next-gen,nuruddeensalihu/binary-next-gen,binary-com/binary-next-gen,nuruddeensalihu/binary-next-gen,nuruddeensalihu/binary-next-gen,nazaninreihani/binary-next-gen,qingweibinary/binary-next-gen,binary-com/binary-next-gen | ---
+++
@@ -20,12 +20,12 @@
};
static defaultProps = {
- history: [],
spot: 0,
};
render() {
const { history, spot } = this.props;
+ if (history.length === 0) return null;
const options = createOptions({ history, spot: +spot, theme });
return (
<SizeProvider style={{ width: '100%', height: '120px' }}> |
7fa60523599a56255cde78a49e848166bd233c6e | src/charts/Chart.Scatter.js | src/charts/Chart.Scatter.js | 'use strict';
module.exports = function(Chart) {
var defaultConfig = {
hover: {
mode: 'single'
},
scales: {
xAxes: [{
type: 'linear', // scatter should not use a category axis
position: 'bottom',
id: 'x-axis-1' // need an ID so datasets can reference the scale
}],
yAxes: [{
type: 'linear',
position: 'left',
id: 'y-axis-1'
}]
},
tooltips: {
callbacks: {
title: function() {
// Title doesn't make sense for scatter since we format the data as a point
return '';
},
label: function(tooltipItem) {
return '(' + tooltipItem.xLabel + ', ' + tooltipItem.yLabel + ')';
}
}
}
};
// Register the default config for this type
Chart.defaults.scatter = defaultConfig;
// Scatter charts use line controllers
Chart.controllers.scatter = Chart.controllers.line;
Chart.Scatter = function(context, config) {
config.type = 'scatter';
return new Chart(context, config);
};
};
| 'use strict';
module.exports = function(Chart) {
var defaultConfig = {
hover: {
mode: 'single'
},
scales: {
xAxes: [{
type: 'linear', // scatter should not use a category axis
position: 'bottom',
id: 'x-axis-1' // need an ID so datasets can reference the scale
}],
yAxes: [{
type: 'linear',
position: 'left',
id: 'y-axis-1'
}]
},
showLines: false,
tooltips: {
callbacks: {
title: function() {
// Title doesn't make sense for scatter since we format the data as a point
return '';
},
label: function(tooltipItem) {
return '(' + tooltipItem.xLabel + ', ' + tooltipItem.yLabel + ')';
}
}
}
};
// Register the default config for this type
Chart.defaults.scatter = defaultConfig;
// Scatter charts use line controllers
Chart.controllers.scatter = Chart.controllers.line;
Chart.Scatter = function(context, config) {
config.type = 'scatter';
return new Chart(context, config);
};
};
| Update scatter chart default config to hide lines | Update scatter chart default config to hide lines
| JavaScript | mit | chartjs/Chart.js,simonbrunel/Chart.js,panzarino/Chart.js,jtcorbett/Chart.js,ldwformat/Chart.js,nnnick/Chart.js,jtcorbett/Chart.js,touletan/Chart.js,supernovel/Chart.js,touletan/Chart.js,chartjs/Chart.js,panzarino/Chart.js,touletan/Chart.js,touletan/Chart.js,chartjs/Chart.js,chartjs/Chart.js,ldwformat/Chart.js,simonbrunel/Chart.js,supernovel/Chart.js | ---
+++
@@ -19,6 +19,7 @@
id: 'y-axis-1'
}]
},
+ showLines: false,
tooltips: {
callbacks: { |
075d06ec62a91543e3d7caa86656e5ea9e50b17d | src/main/webapp/App.js | src/main/webapp/App.js | import * as React from "react";
import {Header} from "./components/Header";
import {Wrapper} from "./components/Wrapper";
import {BuildSnapshotContainer} from "./components/BuildSnapshotContainer";
/**
* Main App that is Rendered to the Page.
*
* @param {*} props arbituary input properties for our application to use
*/
export const App = (props) => {
return (
<Wrapper>
<Header/>
<BuildSnapshotContainer/>
</Wrapper>
);
}
| import * as React from "react";
import {Header} from "./components/Header";
import {Wrapper} from "./components/Wrapper";
import {BuildSnapshotContainer} from "./components/BuildSnapshotContainer";
/**
* Main App that is Rendered to the Page.
*
* @param {*} props arbituary input properties for our application to use.
*/
export const App = (props) => {
return (
<Wrapper>
<Header/>
<BuildSnapshotContainer/>
</Wrapper>
);
}
| Add full stop to comment. | Add full stop to comment.
| JavaScript | apache-2.0 | googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020 | ---
+++
@@ -6,7 +6,7 @@
/**
* Main App that is Rendered to the Page.
*
- * @param {*} props arbituary input properties for our application to use
+ * @param {*} props arbituary input properties for our application to use.
*/
export const App = (props) => {
return ( |
9ce2d3174b07945812805e44a51a0da43c8174a0 | portal/www/portal/join-project.js | portal/www/portal/join-project.js | function handle_lookup(data) {
if (data.code == 0) {
// Project lookup was successful
// redirect to join-this-project.php?project_id=id
// get project from value field, and project_id from that
var project = data.value
var url = "join-this-project.php?project_id=" + project.project_id;
window.location.href = url;
} else {
// Handle error case
$('#finderror').append(data.output);
$('#findname').select();
}
}
function handle_error(jqXHR, textStatus, errorThrown) {
// An unknown error has occurred. Pop up a dialog box.
alert("An unknown error occurred.");
}
function lookup_project(project_name) {
// Clear out any previous errors
$('#finderror').empty();
var lookup_url = "/secure/lookup-project.php"
var data = {name: project_name}
$.post(lookup_url, data, handle_lookup, 'json').fail(handle_error);
}
function do_lookup_project(event) {
event.preventDefault();
lookup_project($('#findname').val());
}
$(document).ready( function () {
/* datatables.net (for sortable/searchable tables) */
$('#projects').DataTable({paging: false});
$('#findbtn').click(do_lookup_project);
} );
| function show_lookup_error(msg) {
$('#finderror').append(msg);
$('#findname').select();
}
function handle_lookup(data) {
if (data.code == 0) {
// Project lookup was successful
// redirect to join-this-project.php?project_id=id
// get project from value field, and project_id from that
var project = data.value
if (project.expired) {
show_lookup_error("Project " + project.project_name + " has expired.");
} else {
var url = "join-this-project.php?project_id=" + project.project_id;
window.location.href = url;
}
} else {
// Handle error case
show_lookup_error(data.output);
}
}
function handle_error(jqXHR, textStatus, errorThrown) {
// An unknown error has occurred. Pop up a dialog box.
alert("An unknown error occurred.");
}
function lookup_project(project_name) {
// Clear out any previous errors
$('#finderror').empty();
var lookup_url = "/secure/lookup-project.php"
var data = {name: project_name}
$.post(lookup_url, data, handle_lookup, 'json').fail(handle_error);
}
function do_lookup_project(event) {
event.preventDefault();
lookup_project($('#findname').val());
}
$(document).ready( function () {
/* datatables.net (for sortable/searchable tables) */
$('#projects').DataTable({paging: false});
$('#findbtn').click(do_lookup_project);
} );
| Handle expired projects in join lookup | Handle expired projects in join lookup
If a project is expired, notify the user but do not carry on to the
join-this-project page.
| JavaScript | mit | tcmitchell/geni-portal,tcmitchell/geni-portal,tcmitchell/geni-portal,tcmitchell/geni-portal,tcmitchell/geni-portal | ---
+++
@@ -1,15 +1,23 @@
+function show_lookup_error(msg) {
+ $('#finderror').append(msg);
+ $('#findname').select();
+}
+
function handle_lookup(data) {
if (data.code == 0) {
// Project lookup was successful
// redirect to join-this-project.php?project_id=id
// get project from value field, and project_id from that
var project = data.value
- var url = "join-this-project.php?project_id=" + project.project_id;
- window.location.href = url;
+ if (project.expired) {
+ show_lookup_error("Project " + project.project_name + " has expired.");
+ } else {
+ var url = "join-this-project.php?project_id=" + project.project_id;
+ window.location.href = url;
+ }
} else {
// Handle error case
- $('#finderror').append(data.output);
- $('#findname').select();
+ show_lookup_error(data.output);
}
}
|
0a078a7649a27614731b15a0f3867f7e025452e3 | website/app/application/core/projects/project/project-controller.js | website/app/application/core/projects/project/project-controller.js | Application.Controllers.controller('projectsProject',
["$scope", "provStep", "ui",
"project", "current", "pubsub", projectsProject]);
function projectsProject ($scope, provStep, ui, project, current, pubsub) {
$scope.isActive = function (tab) {
return tab === $scope.activeTab;
};
current.setProject(project);
pubsub.send("sidebar.project");
provStep.addProject(project.id);
$scope.project = project;
$scope.showTabs = function() {
return ui.showToolbarTabs(project.id);
};
$scope.showFiles = function() {
return ui.showFiles(project.id);
};
}
| Application.Controllers.controller('projectsProject',
["$scope", "provStep", "ui",
"project", "current", "pubsub", "recent",
projectsProject]);
function projectsProject ($scope, provStep, ui, project, current, pubsub, recent) {
recent.resetLast(project.id);
current.setProject(project);
pubsub.send("sidebar.project");
provStep.addProject(project.id);
$scope.project = project;
$scope.showTabs = function() {
return ui.showToolbarTabs(project.id);
};
$scope.showFiles = function() {
return ui.showFiles(project.id);
};
$scope.isActive = function (tab) {
return tab === $scope.activeTab;
};
}
| Move code around to put functions at bottom. | Move code around to put functions at bottom.
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -1,11 +1,10 @@
Application.Controllers.controller('projectsProject',
["$scope", "provStep", "ui",
- "project", "current", "pubsub", projectsProject]);
+ "project", "current", "pubsub", "recent",
+ projectsProject]);
-function projectsProject ($scope, provStep, ui, project, current, pubsub) {
- $scope.isActive = function (tab) {
- return tab === $scope.activeTab;
- };
+function projectsProject ($scope, provStep, ui, project, current, pubsub, recent) {
+ recent.resetLast(project.id);
current.setProject(project);
pubsub.send("sidebar.project");
@@ -20,4 +19,8 @@
$scope.showFiles = function() {
return ui.showFiles(project.id);
};
+
+ $scope.isActive = function (tab) {
+ return tab === $scope.activeTab;
+ };
} |
9884facbb5ebdfefed43a37dcff54896ae99a182 | src/components/search_bar.js | src/components/search_bar.js | import React from 'react';
class SearchBar extends React.Component {
render() {
return <input />;
}
}
export default SearchBar; | import React, { Component } from 'react';
class SearchBar extends Component {
render() {
return <input onChange={this.onInputChange} />;
}
onInputChange(event) {
console.log(event.target.value);
}
}
export default SearchBar; | Add some syntactic sugar to the import command to shorten the class exstension. | Add some syntactic sugar to the import command to shorten the class exstension.
| JavaScript | mit | JosephLeon/redux-simple-starter-tutorial,JosephLeon/redux-simple-starter-tutorial | ---
+++
@@ -1,8 +1,12 @@
-import React from 'react';
+import React, { Component } from 'react';
-class SearchBar extends React.Component {
+class SearchBar extends Component {
render() {
- return <input />;
+ return <input onChange={this.onInputChange} />;
+ }
+
+ onInputChange(event) {
+ console.log(event.target.value);
}
}
|
f266cc41aeb9604393a2b9a2652de609d6d8212a | src/components/viewport/RefreshOnFocus.js | src/components/viewport/RefreshOnFocus.js | const REFRESH_PERIOD = 30 * 60 * 1000 // 30 minutes in microseconds
const focusSupported = typeof document !== 'undefined' &&
typeof document.addEventListener !== 'undefined' &&
typeof document.visibilityState !== 'undefined'
let hiddenAt = null
function onHide() {
hiddenAt = new Date()
}
function onShow() {
const drift = new Date() - hiddenAt
if (hiddenAt && (drift >= REFRESH_PERIOD)) {
document.location.reload()
}
}
function handleChange() {
if (document.visibilityState === 'hidden') {
onHide()
} else if (document.visibilityState === 'visible') {
onShow()
}
}
export const startRefreshTimer = () => {
if (focusSupported) {
document.addEventListener('visibilitychange', handleChange)
}
}
| const REFRESH_PERIOD = 30 * 60 * 1000 // 30 minutes in microseconds
const focusEnabled = ENV.ENABLE_REFRESH_ON_FOCUS
const focusSupported = typeof document !== 'undefined' &&
typeof document.addEventListener !== 'undefined' &&
typeof document.visibilityState !== 'undefined'
let hiddenAt = null
function onHide() {
hiddenAt = new Date()
}
function onShow() {
const drift = new Date() - hiddenAt
if (hiddenAt && (drift >= REFRESH_PERIOD)) {
document.location.reload()
}
}
function handleChange() {
if (document.visibilityState === 'hidden') {
onHide()
} else if (document.visibilityState === 'visible') {
onShow()
}
}
export const startRefreshTimer = () => {
if (focusEnabled && focusSupported) {
document.addEventListener('visibilitychange', handleChange)
}
}
| Enable refresh on focus by env var. | Enable refresh on focus by env var.
So in dev and staging we can try to fix bugs without losing critical
state.
| JavaScript | mit | ello/webapp,ello/webapp,ello/webapp | ---
+++
@@ -1,4 +1,5 @@
const REFRESH_PERIOD = 30 * 60 * 1000 // 30 minutes in microseconds
+const focusEnabled = ENV.ENABLE_REFRESH_ON_FOCUS
const focusSupported = typeof document !== 'undefined' &&
typeof document.addEventListener !== 'undefined' &&
typeof document.visibilityState !== 'undefined'
@@ -25,7 +26,7 @@
}
export const startRefreshTimer = () => {
- if (focusSupported) {
+ if (focusEnabled && focusSupported) {
document.addEventListener('visibilitychange', handleChange)
}
} |
4c7752df347bdb366f00cfad742a5ab799c34b65 | app/assets/javascripts/trln_argon/advanced_search_scope.js | app/assets/javascripts/trln_argon/advanced_search_scope.js | Blacklight.onLoad(function() {
$(window).on('load', function(){
//remove default mast search to fix duplicate IDs
$(".blacklight-catalog-advanced_search #search-navbar").remove();
$(".blacklight-trln-advanced_search #search-navbar").remove();
// change adv search scope
window.location.href.indexOf('advanced_trln') != -1 ? $('#option_trln').attr('checked',true) : $('#option_catalog').attr('checked',true);
$("input[type='radio'][name='option']").change(function() {
var action = $(this).val();
$(".advanced").attr("action", "/" + action);
});
// fix labeling for fields generated by Chosen jquery library (https://harvesthq.github.io/chosen/)
$("[id$='_chosen']").each(function() {
$the_id = $(this).attr('id');
$aria_label = $(this).attr('id').replace('_chosen', '_label');
$('#' + $the_id + ' .chosen-search-input').attr('aria-labelledby', $aria_label);
});
});
}); | Blacklight.onLoad(function() {
$(window).on('load', function(){
//remove default mast search to fix duplicate IDs
$(".blacklight-catalog-advanced_search #search-navbar").remove();
$(".blacklight-trln-advanced_search #search-navbar").remove();
// change adv search scope
$(".blacklight-trln-advanced_search").length > 0 ? $('#option_trln').attr('checked',true) : $('#option_catalog').attr('checked',true);
$("input[type='radio'][name='option']").change(function() {
var action = $(this).val();
$(".advanced").attr("action", "/" + action);
});
// fix labeling for fields generated by Chosen jquery library (https://harvesthq.github.io/chosen/)
$("[id$='_chosen']").each(function() {
$the_id = $(this).attr('id');
$aria_label = $(this).attr('id').replace('_chosen', '_label');
$('#' + $the_id + ' .chosen-search-input').attr('aria-labelledby', $aria_label);
});
});
}); | Remove window.location.href in advanced search js | Remove window.location.href in advanced search js
| JavaScript | mit | trln/trln_argon,trln/trln_argon,trln/trln_argon,trln/trln_argon | ---
+++
@@ -6,7 +6,7 @@
$(".blacklight-trln-advanced_search #search-navbar").remove();
// change adv search scope
- window.location.href.indexOf('advanced_trln') != -1 ? $('#option_trln').attr('checked',true) : $('#option_catalog').attr('checked',true);
+ $(".blacklight-trln-advanced_search").length > 0 ? $('#option_trln').attr('checked',true) : $('#option_catalog').attr('checked',true);
$("input[type='radio'][name='option']").change(function() {
var action = $(this).val(); |
775e2ff03c0be1446def3cb9d815e30e1bac4314 | server/routes/itemRoute.js | server/routes/itemRoute.js | "use strict";
const { Router } = require('express')
const router = Router()
const Item = require('../models/Item')
router.get('/api/items', (req, res, err) =>
Item
.find()
.then(item => res.json( item ))
.catch(err)
)
////////just returning a single id by its id//////////
router.get('/api/items/:_id', (req, res, err) =>
Item
.findById(req.params._id)
.then((item) => res.json( item ))
.catch(err)
)
router.post('/api/items', (req, res, err) => {
Item
.create(req.body)
.then((items) => res.json(items))
.catch(err);
});
// router.put('/api/items/:_id', (req, res, err) => {
// Item
// .update({ _id:req.params.id }, {$set: { name: "lalallalalala" }})
// .then(items => res.json(items))
// .catch(err)
// })
module.exports = router
| "use strict";
const { Router } = require('express')
const router = Router()
const Item = require('../models/Item')
router.get('/api/items', (req, res, err) =>
Item
.find()
.then(item => res.json( item ))
.catch(err)
)
////////just returning a single id by its id//////////
router.get('/api/items/:_id', (req, res, err) =>
Item
.findById(req.params._id)
.then((item) => res.json( item ))
.catch(err)
)
router.post('/api/items', (req, res, err) => {
Item
.create(req.body)
.then((items) => res.json(items))
.catch(err);
});
router.put('/api/items/:_id', (req, res, err) => {
Item
.findOneAndUpdate({ _id:req.params._id }, {$set: { name: "1234566" }})
.then((item) => res.json(item))
.catch(err)
})
module.exports = router
| PUT API route is now working in postman | PUT API route is now working in postman
| JavaScript | mit | mmeadow3/nodEbay,mmeadow3/nodEbay | ---
+++
@@ -27,12 +27,12 @@
.catch(err);
});
-// router.put('/api/items/:_id', (req, res, err) => {
-// Item
-// .update({ _id:req.params.id }, {$set: { name: "lalallalalala" }})
-// .then(items => res.json(items))
-// .catch(err)
-// })
+router.put('/api/items/:_id', (req, res, err) => {
+ Item
+ .findOneAndUpdate({ _id:req.params._id }, {$set: { name: "1234566" }})
+ .then((item) => res.json(item))
+ .catch(err)
+})
module.exports = router |
97da0fe508b4664086d9391308ae9e0c87e6d16d | src/rebase-prod-css.js | src/rebase-prod-css.js | import postcss from 'postcss'
import { readFileSync as slurp } from 'fs'
import { resolve, isAbsolute } from 'path'
import { parse as parseUrl } from 'url'
import { default as rebaseUrl } from 'postcss-url'
export default function rebase(pkg, opts, filename) {
return postcss([
rebaseUrl({
url: (url, decl, from, dirname, to, options, result) => {
let parsed = parseUrl(url, true, true)
if (parsed.host || isAbsolute(parsed.path)) {
return url
} else {
let resolved = pkg.relative(resolve(pkg.root, opts.lib, parsed.path))
return resolved
}
}
})
]).process(slurp(filename, 'utf8'))
} | import postcss from 'postcss'
import { readFileSync as slurp } from 'fs'
import { resolve, isAbsolute } from 'path'
import { parse as parseUrl } from 'url'
import { default as rebaseUrl } from 'postcss-url'
export default function rebase(pkg, opts, filename) {
return postcss([
rebaseUrl({
url: (url, decl, from, dirname, to, options, result) => {
let parsed = parseUrl(url, true, true)
if (parsed.host || isAbsolute(parsed.path)) {
return url
} else {
let resolved = pkg.relative(resolve(pkg.root, opts.lib, parsed.path))
return resolved.replace(/\\/g, '/')
}
}
})
]).process(slurp(filename, 'utf8'))
} | Replace `\` with `/` in resolved path | Replace `\` with `/` in resolved path
This fixes url rebasing on windows. We probably should use something
other than the `path` module for resolving, but that can come at
a later time – this'll do for now.
| JavaScript | mit | zambezi/ez-build,zambezi/ez-build | ---
+++
@@ -14,7 +14,7 @@
return url
} else {
let resolved = pkg.relative(resolve(pkg.root, opts.lib, parsed.path))
- return resolved
+ return resolved.replace(/\\/g, '/')
}
}
}) |
1c1dddffb39767e1a99bb371f2b9a39a089ce86c | src/routes/machines.js | src/routes/machines.js | /**
* @package admiral
* @author Andrew Munsell <andrew@wizardapps.net>
* @copyright 2015 WizardApps
*/
exports = module.exports = function(app, config, fleet) {
/**
* Get the machines in the cluster
*/
app.get('/v1/machines', function(req, res) {
fleet.list_machinesAsync()
.then(function(machines) {
res
.json(machines)
.header('Cache-Control', 'private, max-age=60');
})
.catch(function(err) {
res
.status(500)
.json({
error: 500,
message: 'There was a problem fetching the machines.'
});
})
.finally(function() {
res.end();
});
});
};
exports['@singleton'] = true;
exports['@require'] = ['app', 'config', 'fleet']; | /**
* @package admiral
* @author Andrew Munsell <andrew@wizardapps.net>
* @copyright 2015 WizardApps
*/
exports = module.exports = function(app, config, fleet) {
/**
* Get the machines in the cluster
*/
app.get('/v1/machines', function(req, res) {
fleet.list_machinesAsync()
.then(function(machines) {
res
.header('Cache-Control', 'private, max-age=60')
.json(machines);
})
.catch(function(err) {
res
.status(500)
.json({
error: 500,
message: 'There was a problem fetching the machines.'
});
})
.finally(function() {
res.end();
});
});
};
exports['@singleton'] = true;
exports['@require'] = ['app', 'config', 'fleet']; | Fix order of headers in response | Fix order of headers in response
| JavaScript | mit | andrewmunsell/admiral | ---
+++
@@ -12,8 +12,8 @@
fleet.list_machinesAsync()
.then(function(machines) {
res
- .json(machines)
- .header('Cache-Control', 'private, max-age=60');
+ .header('Cache-Control', 'private, max-age=60')
+ .json(machines);
})
.catch(function(err) {
res |
ea0abf1f9a2000830c2810ccdbe9685ce9aa1f54 | raft/scripts/frames/conclusion.js | raft/scripts/frames/conclusion.js |
"use strict";
/*jslint browser: true, nomen: true*/
/*global define*/
define([], function () {
return function (frame) {
var player = frame.player(),
layout = frame.layout();
frame.after(1, function() {
frame.model().clear();
layout.invalidate();
})
.after(500, function () {
frame.model().title = '<h1 style="visibility:visible">The End</h1>'
+ '<br/>' + frame.model().controls.html();
layout.invalidate();
})
.after(500, function () {
frame.model().controls.show();
})
.after(500, function () {
frame.model().title = '<h2 style="visibility:visible">For more information:</h2>'
+ '<h3 style="visibility:visible"><a href="https://raft.github.io/raft.pdf">The Raft Paper</a></h3>'
+ '<h3 style="visibility:visible"><a href="http://raftconsensus.github.io/">Raft Web Site</a></h3>'
+ '<br/>' + frame.model().controls.html();
layout.invalidate();
})
player.play();
};
});
|
"use strict";
/*jslint browser: true, nomen: true*/
/*global define*/
define([], function () {
return function (frame) {
var player = frame.player(),
layout = frame.layout();
frame.after(1, function() {
frame.model().clear();
layout.invalidate();
})
.after(500, function () {
frame.model().title = '<h1 style="visibility:visible">The End</h1>'
+ '<br/>' + frame.model().controls.html();
layout.invalidate();
})
.after(500, function () {
frame.model().controls.show();
})
.after(500, function () {
frame.model().title = '<h2 style="visibility:visible">For more information:</h2>'
+ '<h3 style="visibility:visible"><a href="https://raft.github.io/raft.pdf">The Raft Paper</a></h3>'
+ '<h3 style="visibility:visible"><a href="https://raft.github.io/">Raft Web Site</a></h3>'
+ '<br/>' + frame.model().controls.html();
layout.invalidate();
})
player.play();
};
});
| Update Raft web site link | Update Raft web site link | JavaScript | mit | benbjohnson/thesecretlivesofdata | ---
+++
@@ -25,7 +25,7 @@
.after(500, function () {
frame.model().title = '<h2 style="visibility:visible">For more information:</h2>'
+ '<h3 style="visibility:visible"><a href="https://raft.github.io/raft.pdf">The Raft Paper</a></h3>'
- + '<h3 style="visibility:visible"><a href="http://raftconsensus.github.io/">Raft Web Site</a></h3>'
+ + '<h3 style="visibility:visible"><a href="https://raft.github.io/">Raft Web Site</a></h3>'
+ '<br/>' + frame.model().controls.html();
layout.invalidate();
}) |
ece2da770d255a2e016a5aea561cee07f6ba89c9 | simul/app/components/profile.js | simul/app/components/profile.js | import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TouchableHighlight,
} from 'react-native';
import I18n from 'react-native-i18n'
class Profile extends Component{
async _onPressAddStory(){
try {
}
}
render() {
return (
<View style={styles.container}>
<Text style={styles.title}>Smeagles {I18n.t('profile')}</Text>
<Text style={styles.body}> {JSON.stringify(this.props.users)}</Text>
<Text style={styles.body}> Temporary for styling Skeleton </Text>
<TouchableHighlight onPress={this._onPressAddStory}.bind(this)} style={styles.button}>
<Text style={styles.buttonText}>
</Text>
</TouchableHighlight>
</View>
)
}
};
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
title: {
marginTop: 25,
fontSize: 20,
alignSelf: 'center',
margin: 40,
},
body: {
flex: 0.1,
}
});
module.exports = Profile;
| import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TouchableHighlight,
} from 'react-native';
import I18n from 'react-native-i18n'
class Profile extends Component{
_onPressAddStory(){
}
render() {
return (
<View style={styles.container}>
<Text style={styles.title}>Smeagles {I18n.t('profile')}</Text>
<Text style={styles.body}> {JSON.stringify(this.props.users)}</Text>
<Text style={styles.body}> Temporary for styling Skeleton </Text>
<TouchableHighlight onPress={this._onPressAddStory.bind(this)} style={styles.button}>
<Text style={styles.buttonText}>
Add Story
</Text>
</TouchableHighlight>
</View>
)
}
};
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
title: {
marginTop: 25,
fontSize: 20,
alignSelf: 'center',
margin: 40,
},
body: {
flex: 0.1,
}
});
module.exports = Profile;
| Fix error, need to add PressAddStory button | Fix error, need to add PressAddStory button
| JavaScript | mit | sf-red-pandas-2016/simul-react-native,sf-red-pandas-2016/simul-react-native,sf-red-pandas-2016/simul-react-native | ---
+++
@@ -12,10 +12,8 @@
class Profile extends Component{
- async _onPressAddStory(){
- try {
-
- }
+_onPressAddStory(){
+
}
render() {
return (
@@ -23,9 +21,10 @@
<Text style={styles.title}>Smeagles {I18n.t('profile')}</Text>
<Text style={styles.body}> {JSON.stringify(this.props.users)}</Text>
<Text style={styles.body}> Temporary for styling Skeleton </Text>
- <TouchableHighlight onPress={this._onPressAddStory}.bind(this)} style={styles.button}>
- <Text style={styles.buttonText}>
- </Text>
+ <TouchableHighlight onPress={this._onPressAddStory.bind(this)} style={styles.button}>
+ <Text style={styles.buttonText}>
+ Add Story
+ </Text>
</TouchableHighlight>
</View>
) |
30e6cf089f7e8aec41d7edd32d71c168c7db116a | string/dashes-to-camel-case.js | string/dashes-to-camel-case.js | export default function dashesToCamelCase(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}; | export default function dashesToCamelCase(str) {
return str.replace(/-([a-z])/g, function (g) {
return g[1].toUpperCase();
});
}; | Add helper for converting dashed words to lower camel case | Add helper for converting dashed words to lower camel case
| JavaScript | mit | complayjs/helpers | ---
+++
@@ -1,4 +1,5 @@
export default function dashesToCamelCase(str) {
-
- return str.charAt(0).toUpperCase() + str.slice(1);
+ return str.replace(/-([a-z])/g, function (g) {
+ return g[1].toUpperCase();
+ });
}; |
fb7cd0f61d5b4cca3c3ba30ad79772fc02418b5b | src/build/webpack.base.config.js | src/build/webpack.base.config.js | const path = require('path')
const ExtractTextPlugin = require("extract-text-webpack-plugin")
const HtmlWebpackPlugin = require('html-webpack-plugin')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: resolve('src/index.js'),
output: {
path: resolve('dist'),
filename: '[name].js'
},
resolve: {
alias: {
'@': resolve('src')
}
},
module: {
rules: [
// general resolve
{
test: /\.js$/,
use: 'babel-loader',
include: resolve('src')
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
}),
include: resolve('src/assets')
}
]
},
plugins: [
// generate index.html based on src/index.html
new HtmlWebpackPlugin({
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
}
})
]
}
| const path = require('path')
const ExtractTextPlugin = require("extract-text-webpack-plugin")
const HtmlWebpackPlugin = require('html-webpack-plugin')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: resolve('src/index.js'),
output: {
path: resolve('dist'),
filename: '[name].js'
},
resolve: {
alias: {
'@': resolve('src')
}
},
module: {
rules: [
// general resolve
{
test: /\.js$/,
use: 'babel-loader',
include: resolve('src')
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
}),
include: resolve('src/assets')
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'index.html',
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
}
})
]
}
| Update HTML Webpack Plugin to use index.html as template | Update HTML Webpack Plugin to use index.html as template
| JavaScript | mit | jocodev1/mithril-cli,jocodev1/mithril-cli | ---
+++
@@ -36,8 +36,8 @@
]
},
plugins: [
- // generate index.html based on src/index.html
new HtmlWebpackPlugin({
+ template: 'index.html',
minify: {
removeComments: true,
collapseWhitespace: true, |
3052dc420f956cdbbf1d2e479287231e40c38308 | source/models/v3/application.js | source/models/v3/application.js | define(
['data/data', 'collections/v3/interactions', 'collections/v3/datasuitcases', 'models/v3/DataSuitcase', 'collections/v3/forms', 'models/v3/form'],
function (Backbone, InteractionCollection, DataSuitcaseCollection, DataSuitcase, FormCollection, Form) {
"use strict";
var Application = Backbone.Model.extend({
initialize: function () {
// Nested interactions
this.interactions = new InteractionCollection();
// Nested Data Suitcases
this.datasuitcases = new DataSuitcaseCollection();
this.on('change', this.update);
},
update: function () {
if (this.has("DataSuitcases")) {
var ds = this.get("DataSuitcases"),
count,
dsmodel;
for (count = 0; count < ds.length; count = count + 1) {
if (this.datasuitcases.where({name: ds[count]}).length === 0) {
dsmodel = new DataSuitcase({
name: ds[count],
siteName: this.get("siteName"),
BICtype: "DataSuitcase"
});
this.datasuitcases.add(dsmodel);
dsmodel.fetch();
}
}
}
}
}),
app;
app = new Application();
return app;
}
);
| define(
['data/data', 'collections/v3/interactions', 'collections/v3/datasuitcases', 'models/v3/DataSuitcase', 'collections/v3/forms', 'models/v3/form'],
function (Backbone, InteractionCollection, DataSuitcaseCollection, DataSuitcase, FormCollection, Form) {
"use strict";
var Application = Backbone.Model.extend({
initialize: function () {
// Nested interactions
this.interactions = new InteractionCollection();
// Nested Data Suitcases
this.datasuitcases = new DataSuitcaseCollection();
this.forms = new FormCollection();
this.on('change', this.update);
},
update: function () {
var modelArray = this.get("DataSuitcases"),
count,
model,
children = {
DataSuitcases: this.datasuitcases,
Forms: this.forms
};
if (this.has("DataSuitcases")) {
modelArray = this.get("DataSuitcases");
for (count = 0; count < modelArray.length; count = count + 1) {
if (this.datasuitcases.where({name: modelArray[count]}).length === 0) {
model = new DataSuitcase({
name: modelArray[count],
siteName: this.get("siteName"),
BICtype: "DataSuitcase"
});
this.datasuitcases.add(model);
model.fetch();
}
}
}
}
}),
app;
app = new Application();
return app;
}
);
| Create a collection for Forms | Create a collection for Forms
| JavaScript | bsd-3-clause | blinkmobile/bic-jqm,blinkmobile/bic-jqm | ---
+++
@@ -10,24 +10,32 @@
// Nested Data Suitcases
this.datasuitcases = new DataSuitcaseCollection();
+ this.forms = new FormCollection();
this.on('change', this.update);
},
update: function () {
+ var modelArray = this.get("DataSuitcases"),
+ count,
+ model,
+ children = {
+ DataSuitcases: this.datasuitcases,
+ Forms: this.forms
+ };
+
+
if (this.has("DataSuitcases")) {
- var ds = this.get("DataSuitcases"),
- count,
- dsmodel;
- for (count = 0; count < ds.length; count = count + 1) {
- if (this.datasuitcases.where({name: ds[count]}).length === 0) {
- dsmodel = new DataSuitcase({
- name: ds[count],
+ modelArray = this.get("DataSuitcases");
+ for (count = 0; count < modelArray.length; count = count + 1) {
+ if (this.datasuitcases.where({name: modelArray[count]}).length === 0) {
+ model = new DataSuitcase({
+ name: modelArray[count],
siteName: this.get("siteName"),
BICtype: "DataSuitcase"
});
- this.datasuitcases.add(dsmodel);
- dsmodel.fetch();
+ this.datasuitcases.add(model);
+ model.fetch();
}
}
} |
5b365981625964aa609f80fa622a0372d558a368 | src/protocol/message/compression/index.js | src/protocol/message/compression/index.js | const { KafkaJSNotImplemented } = require('../../../errors')
const Types = {
None: 0,
GZIP: 1,
Snappy: 2,
LZ4: 3,
}
const Codecs = {
[Types.GZIP]: () => require('./gzip'),
[Types.Snappy]: () => {
throw new KafkaJSNotImplemented('Snappy compression not implemented')
},
[Types.LZ4]: () => {
throw new KafkaJSNotImplemented('LZ4 compression not implemented')
},
}
const lookupCodec = type => (Codecs[type] ? Codecs[type]() : null)
const lookupCodecByAttributes = attributes => {
const codec = Codecs[attributes & 0x3]
return codec ? codec() : null
}
module.exports = {
Types,
Codecs,
lookupCodec,
lookupCodecByAttributes,
}
| const { KafkaJSNotImplemented } = require('../../../errors')
const MESSAGE_CODEC_MASK = 0x3
const RECORD_BATCH_CODEC_MASK = 0x07
const Types = {
None: 0,
GZIP: 1,
Snappy: 2,
LZ4: 3,
}
const Codecs = {
[Types.GZIP]: () => require('./gzip'),
[Types.Snappy]: () => {
throw new KafkaJSNotImplemented('Snappy compression not implemented')
},
[Types.LZ4]: () => {
throw new KafkaJSNotImplemented('LZ4 compression not implemented')
},
}
const lookupCodec = type => (Codecs[type] ? Codecs[type]() : null)
const lookupCodecByAttributes = attributes => {
const codec = Codecs[attributes & MESSAGE_CODEC_MASK]
return codec ? codec() : null
}
const lookupCodecByRecordBatchAttributes = attributes => {
const codec = Codecs[attributes & RECORD_BATCH_CODEC_MASK]
return codec ? codec() : null
}
module.exports = {
Types,
Codecs,
lookupCodec,
lookupCodecByAttributes,
lookupCodecByRecordBatchAttributes,
}
| Add support for Record Batch compression codec flag | Add support for Record Batch compression codec flag
| JavaScript | mit | tulios/kafkajs,tulios/kafkajs,tulios/kafkajs,tulios/kafkajs | ---
+++
@@ -1,4 +1,7 @@
const { KafkaJSNotImplemented } = require('../../../errors')
+
+const MESSAGE_CODEC_MASK = 0x3
+const RECORD_BATCH_CODEC_MASK = 0x07
const Types = {
None: 0,
@@ -19,7 +22,11 @@
const lookupCodec = type => (Codecs[type] ? Codecs[type]() : null)
const lookupCodecByAttributes = attributes => {
- const codec = Codecs[attributes & 0x3]
+ const codec = Codecs[attributes & MESSAGE_CODEC_MASK]
+ return codec ? codec() : null
+}
+const lookupCodecByRecordBatchAttributes = attributes => {
+ const codec = Codecs[attributes & RECORD_BATCH_CODEC_MASK]
return codec ? codec() : null
}
@@ -28,4 +35,5 @@
Codecs,
lookupCodec,
lookupCodecByAttributes,
+ lookupCodecByRecordBatchAttributes,
} |
e0cde4d967ddd9e75d55fbf466f57b4f05e1e07b | chrome/browser/resources/chromeos/wallpaper_manager/js/event_page.js | chrome/browser/resources/chromeos/wallpaper_manager/js/event_page.js | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var WALLPAPER_PICKER_WIDTH = 550;
var WALLPAPER_PICKER_HEIGHT = 420;
var wallpaperPickerWindow;
chrome.app.runtime.onLaunched.addListener(function() {
if (wallpaperPickerWindow && !wallpaperPickerWindow.contentWindow.closed) {
wallpaperPickerWindow.focus();
chrome.wallpaperPrivate.minimizeInactiveWindows();
return;
}
chrome.app.window.create('main.html', {
frame: 'chrome',
width: WALLPAPER_PICKER_WIDTH,
height: WALLPAPER_PICKER_HEIGHT
}, function(w) {
wallpaperPickerWindow = w;
chrome.wallpaperPrivate.minimizeInactiveWindows();
w.onClosed.addListener(function() {
chrome.wallpaperPrivate.restoreMinimizedWindows();
});
});
});
| // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var WALLPAPER_PICKER_WIDTH = 550;
var WALLPAPER_PICKER_HEIGHT = 420;
var wallpaperPickerWindow;
chrome.app.runtime.onLaunched.addListener(function() {
if (wallpaperPickerWindow && !wallpaperPickerWindow.contentWindow.closed) {
wallpaperPickerWindow.focus();
chrome.wallpaperPrivate.minimizeInactiveWindows();
return;
}
chrome.app.window.create('main.html', {
frame: 'chrome',
width: WALLPAPER_PICKER_WIDTH,
height: WALLPAPER_PICKER_HEIGHT,
minWidth: WALLPAPER_PICKER_WIDTH,
maxWidth: WALLPAPER_PICKER_WIDTH,
minHeight: WALLPAPER_PICKER_HEIGHT,
maxHeight: WALLPAPER_PICKER_HEIGHT
}, function(w) {
wallpaperPickerWindow = w;
chrome.wallpaperPrivate.minimizeInactiveWindows();
w.onClosed.addListener(function() {
chrome.wallpaperPrivate.restoreMinimizedWindows();
});
});
});
| Disable resize of wallpaper picker | Disable resize of wallpaper picker
BUG=149937
Review URL: https://codereview.chromium.org/11411244
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@170467 0039d316-1c4b-4281-b951-d872f2087c98
| JavaScript | bsd-3-clause | dednal/chromium.src,hujiajie/pa-chromium,Jonekee/chromium.src,timopulkkinen/BubbleFish,mogoweb/chromium-crosswalk,jaruba/chromium.src,timopulkkinen/BubbleFish,jaruba/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,Jonekee/chromium.src,zcbenz/cefode-chromium,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,M4sse/chromium.src,zcbenz/cefode-chromium,anirudhSK/chromium,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,dednal/chromium.src,Just-D/chromium-1,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,Chilledheart/chromium,dednal/chromium.src,pozdnyakov/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,ltilve/chromium,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,markYoungH/chromium.src,littlstar/chromium.src,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,Chilledheart/chromium,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,ltilve/chromium,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,zcbenz/cefode-chromium,ondra-novak/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,chuan9/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,jaruba/chromium.src,chuan9/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,markYoungH/chromium.src,Chilledheart/chromium,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,ltilve/chromium,ondra-novak/chromium.src,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,patrickm/chromium.src,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,dednal/chromium.src,chuan9/chromium-crosswalk,Just-D/chromium-1,ltilve/chromium,axinging/chromium-crosswalk,patrickm/chromium.src,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,M4sse/chromium.src,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,nacl-webkit/chrome_deps,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,markYoungH/chromium.src,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,dushu1203/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,Chilledheart/chromium,hgl888/chromium-crosswalk,Just-D/chromium-1,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,dushu1203/chromium.src,Jonekee/chromium.src,ondra-novak/chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,ondra-novak/chromium.src,Jonekee/chromium.src,mogoweb/chromium-crosswalk,patrickm/chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,M4sse/chromium.src,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,ondra-novak/chromium.src,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,patrickm/chromium.src,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,anirudhSK/chromium,M4sse/chromium.src,anirudhSK/chromium,markYoungH/chromium.src,anirudhSK/chromium,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,ltilve/chromium,patrickm/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,littlstar/chromium.src,anirudhSK/chromium,anirudhSK/chromium,dednal/chromium.src,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,jaruba/chromium.src,ChromiumWebApps/chromium,hujiajie/pa-chromium,Chilledheart/chromium,chuan9/chromium-crosswalk,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,jaruba/chromium.src,axinging/chromium-crosswalk,littlstar/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,anirudhSK/chromium,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,dednal/chromium.src,ltilve/chromium,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,Jonekee/chromium.src,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,anirudhSK/chromium,patrickm/chromium.src,jaruba/chromium.src,dednal/chromium.src,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,dushu1203/chromium.src,jaruba/chromium.src,Just-D/chromium-1,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,Jonekee/chromium.src,M4sse/chromium.src,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,jaruba/chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,fujunwei/chromium-crosswalk,Just-D/chromium-1,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,M4sse/chromium.src,hgl888/chromium-crosswalk | ---
+++
@@ -17,7 +17,11 @@
chrome.app.window.create('main.html', {
frame: 'chrome',
width: WALLPAPER_PICKER_WIDTH,
- height: WALLPAPER_PICKER_HEIGHT
+ height: WALLPAPER_PICKER_HEIGHT,
+ minWidth: WALLPAPER_PICKER_WIDTH,
+ maxWidth: WALLPAPER_PICKER_WIDTH,
+ minHeight: WALLPAPER_PICKER_HEIGHT,
+ maxHeight: WALLPAPER_PICKER_HEIGHT
}, function(w) {
wallpaperPickerWindow = w;
chrome.wallpaperPrivate.minimizeInactiveWindows(); |
12bb485ef15de677effa7218d5346d3008698dee | lit-config.js | lit-config.js | module.exports = {
"extends": "./index.js",
"parser": "babel-eslint",
"env": {
"browser": true
},
"plugins": [
"lit", "html"
],
"globals": {
"D2L": false
},
"rules": {
"strict": 0,
"lit/no-duplicate-template-bindings": 2,
"lit/no-legacy-template-syntax": 2,
"lit/no-template-bind": 2,
"lit/no-template-map": 0,
"lit/no-useless-template-literals": 2,
"lit/attribute-value-entities": 2,
"lit/binding-positions": 2,
"lit/no-property-change-update": 2,
"lit/no-invalid-html": 2,
"lit/no-value-attribute": 2
}
};
| module.exports = {
"extends": "./index.js",
"parser": "babel-eslint",
"env": {
"browser": true
},
"plugins": [
"lit", "html"
],
"globals": {
"D2L": false
},
"rules": {
"strict": [2, "never"],
"lit/no-duplicate-template-bindings": 2,
"lit/no-legacy-template-syntax": 2,
"lit/no-template-bind": 2,
"lit/no-template-map": 0,
"lit/no-useless-template-literals": 2,
"lit/attribute-value-entities": 2,
"lit/binding-positions": 2,
"lit/no-property-change-update": 2,
"lit/no-invalid-html": 2,
"lit/no-value-attribute": 2
}
};
| Update strict to error if present since it is redundant in modules, and not really necessary in demo pages. | Update strict to error if present since it is redundant in modules, and not really necessary in demo pages.
| JavaScript | apache-2.0 | Brightspace/eslint-config-brightspace | ---
+++
@@ -11,7 +11,7 @@
"D2L": false
},
"rules": {
- "strict": 0,
+ "strict": [2, "never"],
"lit/no-duplicate-template-bindings": 2,
"lit/no-legacy-template-syntax": 2,
"lit/no-template-bind": 2, |
7b3f0423b7cf08b743a8244dd6b376bdedbf32f1 | www/lib/collections/photos.js | www/lib/collections/photos.js | Photo = function (doc) {
_.extend(this, doc);
};
_.extend(Photo.prototype, {
getImgTag: function (dimension) {
return {
'class': 'lazy',
'data-src': _.str.sprintf(
'%s/photos/%s/%s',
Meteor.settings.public.uri.cdn,
dimension,
this.filename
),
'data-src-retina': _.str.sprintf(
'%s/photos/%s@2x/%s',
Meteor.settings.public.uri.cdn,
dimension,
this.filename
),
alt: this.title,
width: dimension,
height: dimension
};
}
});
Photos = new Mongo.Collection('Photos', {
transform: function (doc) { return new Photo(doc); }
});
| Photo = function (doc) {
_.extend(this, doc);
};
_.extend(Photo.prototype, {
getImgTag: function (dimension) {
return {
'class': 'lazy',
'src': 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
'data-src': _.str.sprintf(
'%s/photos/%s/%s',
Meteor.settings.public.uri.cdn,
dimension,
this.filename
),
'data-src-retina': _.str.sprintf(
'%s/photos/%s@2x/%s',
Meteor.settings.public.uri.cdn,
dimension,
this.filename
),
alt: this.title,
width: dimension,
height: dimension
};
}
});
Photos = new Mongo.Collection('Photos', {
transform: function (doc) { return new Photo(doc); }
});
| Use a transparent pixel to hold the height | Use a transparent pixel to hold the height
| JavaScript | mit | nburka/black-white | ---
+++
@@ -6,6 +6,7 @@
getImgTag: function (dimension) {
return {
'class': 'lazy',
+ 'src': 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
'data-src': _.str.sprintf(
'%s/photos/%s/%s',
Meteor.settings.public.uri.cdn, |
0a811b387401255f9c8f5eda40d3e4e20ba6e9d7 | test/transform/noStrictTest.js | test/transform/noStrictTest.js | import createTestHelpers from '../createTestHelpers';
const {expectTransform, expectNoChange} = createTestHelpers(['no-strict']);
describe('Removal of "use strict"', () => {
it('should remove statement with "use strict" string', () => {
expectTransform('"use strict";').toReturn('');
expectTransform('\'use strict\';').toReturn('');
});
it('should remove the whole line where "use strict" used to be', () => {
expectTransform('"use strict";\nfoo();').toReturn('foo();');
expectTransform('foo();\n"use strict";\nbar();').toReturn('foo();\nbar();');
});
it('should not remove comments before "use strict"', () => {
expectTransform('// foo();\n"use strict";\nbar();').toReturn('// foo();\nbar();');
});
it('should keep "use strict" used inside other code', () => {
expectNoChange('x = "use strict";');
expectNoChange('foo("use strict");');
});
});
| import createTestHelpers from '../createTestHelpers';
const {expectTransform, expectNoChange} = createTestHelpers(['no-strict']);
describe('Removal of "use strict"', () => {
it('should remove statement with "use strict" string', () => {
expectTransform('"use strict";').toReturn('');
expectTransform('\'use strict\';').toReturn('');
});
it('should remove the whole line where "use strict" used to be', () => {
expectTransform(
'"use strict";\n' +
'foo();'
).toReturn(
'foo();'
);
expectTransform(
'foo();\n' +
'"use strict";\n' +
'bar();'
).toReturn(
'foo();\n' +
'bar();'
);
});
it('should not remove comments before "use strict"', () => {
expectTransform(
'// comment\n' +
'"use strict";\n' +
'bar();'
).toReturn(
'// comment\n' +
'bar();'
);
});
it('should keep "use strict" used inside other code', () => {
expectNoChange('x = "use strict";');
expectNoChange('foo("use strict");');
});
});
| Split multiline tests to actual multiple lines | Split multiline tests to actual multiple lines
For better readability.
| JavaScript | mit | lebab/lebab,mohebifar/lebab,mohebifar/xto6 | ---
+++
@@ -8,12 +8,32 @@
});
it('should remove the whole line where "use strict" used to be', () => {
- expectTransform('"use strict";\nfoo();').toReturn('foo();');
- expectTransform('foo();\n"use strict";\nbar();').toReturn('foo();\nbar();');
+ expectTransform(
+ '"use strict";\n' +
+ 'foo();'
+ ).toReturn(
+ 'foo();'
+ );
+
+ expectTransform(
+ 'foo();\n' +
+ '"use strict";\n' +
+ 'bar();'
+ ).toReturn(
+ 'foo();\n' +
+ 'bar();'
+ );
});
it('should not remove comments before "use strict"', () => {
- expectTransform('// foo();\n"use strict";\nbar();').toReturn('// foo();\nbar();');
+ expectTransform(
+ '// comment\n' +
+ '"use strict";\n' +
+ 'bar();'
+ ).toReturn(
+ '// comment\n' +
+ 'bar();'
+ );
});
it('should keep "use strict" used inside other code', () => { |
30172c7bc91ae86cb61d79dbcd2328abca09570d | blueprints/component-test/qunit-files/tests/__testType__/__path__/__test__.js | blueprints/component-test/qunit-files/tests/__testType__/__path__/__test__.js | import { moduleForComponent, test } from 'ember-qunit';<% if (testType === 'integration') { %>
import hbs from 'htmlbars-inline-precompile';<% } %>
moduleForComponent('<%= componentPathName %>', '<%= friendlyTestDescription %>', {
<% if (testType === 'integration' ) { %>integration: true<% } else if(testType === 'unit') { %>// Specify the other units that are required for this test
// needs: ['component:foo', 'helper:bar'],
unit: true<% } %>
});
test('it renders', function(assert) {
<% if (testType === 'integration' ) { %>// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{<%= componentPathName %>}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:
this.render(hbs`
{{#<%= componentPathName %>}}
template block text
{{/<%= componentPathName %>}}
`);
assert.equal(this.$().text().trim(), 'template block text');<% } else if(testType === 'unit') { %>
// Creates the component instance
/*let component =*/ this.subject();
// Renders the component to the page
this.render();
assert.equal(this.$().text().trim(), '');<% } %>
});
| import { moduleForComponent, test } from 'ember-qunit';<% if (testType === 'integration') { %>
import hbs from 'htmlbars-inline-precompile';<% } %>
moduleForComponent('<%= componentPathName %>', '<%= friendlyTestDescription %>', {
<% if (testType === 'integration' ) { %>integration: true<% } else if(testType === 'unit') { %>// Specify the other units that are required for this test
// needs: ['component:foo', 'helper:bar'],
unit: true<% } %>
});
test('it renders', function(assert) {
<% if (testType === 'integration' ) { %>
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{<%= componentPathName %>}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:
this.render(hbs`
{{#<%= componentPathName %>}}
template block text
{{/<%= componentPathName %>}}
`);
assert.equal(this.$().text().trim(), 'template block text');<% } else if(testType === 'unit') { %>
// Creates the component instance
/*let component =*/ this.subject();
// Renders the component to the page
this.render();
assert.equal(this.$().text().trim(), '');<% } %>
});
| Remove space from generated unit-tests | Remove space from generated unit-tests
| JavaScript | mit | GavinJoyce/ember.js,jherdman/ember.js,patricksrobertson/ember.js,thoov/ember.js,bantic/ember.js,szines/ember.js,chadhietala/ember.js,thoov/ember.js,xiujunma/ember.js,mfeckie/ember.js,cbou/ember.js,stefanpenner/ember.js,bantic/ember.js,alexdiliberto/ember.js,givanse/ember.js,rlugojr/ember.js,davidpett/ember.js,trentmwillis/ember.js,knownasilya/ember.js,szines/ember.js,karthiick/ember.js,thoov/ember.js,Patsy-issa/ember.js,qaiken/ember.js,intercom/ember.js,jaswilli/ember.js,kennethdavidbuck/ember.js,sivakumar-kailasam/ember.js,GavinJoyce/ember.js,kennethdavidbuck/ember.js,sivakumar-kailasam/ember.js,elwayman02/ember.js,sly7-7/ember.js,mfeckie/ember.js,Serabe/ember.js,jaswilli/ember.js,csantero/ember.js,bekzod/ember.js,patricksrobertson/ember.js,trentmwillis/ember.js,Turbo87/ember.js,emberjs/ember.js,sandstrom/ember.js,fpauser/ember.js,runspired/ember.js,Gaurav0/ember.js,fpauser/ember.js,HeroicEric/ember.js,davidpett/ember.js,tsing80/ember.js,cibernox/ember.js,Leooo/ember.js,qaiken/ember.js,Gaurav0/ember.js,kennethdavidbuck/ember.js,nickiaconis/ember.js,xiujunma/ember.js,trentmwillis/ember.js,Serabe/ember.js,jasonmit/ember.js,jasonmit/ember.js,johanneswuerbach/ember.js,runspired/ember.js,Serabe/ember.js,jaswilli/ember.js,workmanw/ember.js,bantic/ember.js,amk221/ember.js,workmanw/ember.js,csantero/ember.js,fpauser/ember.js,szines/ember.js,xiujunma/ember.js,gfvcastro/ember.js,cibernox/ember.js,davidpett/ember.js,rlugojr/ember.js,rlugojr/ember.js,twokul/ember.js,karthiick/ember.js,tsing80/ember.js,Patsy-issa/ember.js,chadhietala/ember.js,miguelcobain/ember.js,HeroicEric/ember.js,tsing80/ember.js,Patsy-issa/ember.js,mixonic/ember.js,twokul/ember.js,asakusuma/ember.js,sivakumar-kailasam/ember.js,fpauser/ember.js,csantero/ember.js,tildeio/ember.js,sandstrom/ember.js,trentmwillis/ember.js,jasonmit/ember.js,stefanpenner/ember.js,sandstrom/ember.js,knownasilya/ember.js,karthiick/ember.js,asakusuma/ember.js,knownasilya/ember.js,chadhietala/ember.js,mfeckie/ember.js,emberjs/ember.js,givanse/ember.js,jherdman/ember.js,HeroicEric/ember.js,Gaurav0/ember.js,tsing80/ember.js,patricksrobertson/ember.js,mixonic/ember.js,bantic/ember.js,intercom/ember.js,johanneswuerbach/ember.js,intercom/ember.js,alexdiliberto/ember.js,stefanpenner/ember.js,johanneswuerbach/ember.js,jasonmit/ember.js,givanse/ember.js,cbou/ember.js,bekzod/ember.js,szines/ember.js,amk221/ember.js,GavinJoyce/ember.js,duggiefresh/ember.js,jaswilli/ember.js,givanse/ember.js,bekzod/ember.js,Patsy-issa/ember.js,kellyselden/ember.js,mike-north/ember.js,sly7-7/ember.js,kennethdavidbuck/ember.js,mike-north/ember.js,duggiefresh/ember.js,nickiaconis/ember.js,bekzod/ember.js,sivakumar-kailasam/ember.js,Gaurav0/ember.js,Leooo/ember.js,Leooo/ember.js,rlugojr/ember.js,gfvcastro/ember.js,amk221/ember.js,workmanw/ember.js,kanongil/ember.js,elwayman02/ember.js,Leooo/ember.js,jherdman/ember.js,jasonmit/ember.js,emberjs/ember.js,HeroicEric/ember.js,miguelcobain/ember.js,csantero/ember.js,nickiaconis/ember.js,elwayman02/ember.js,cbou/ember.js,runspired/ember.js,kellyselden/ember.js,qaiken/ember.js,mike-north/ember.js,duggiefresh/ember.js,kanongil/ember.js,mfeckie/ember.js,thoov/ember.js,qaiken/ember.js,miguelcobain/ember.js,nickiaconis/ember.js,intercom/ember.js,karthiick/ember.js,twokul/ember.js,asakusuma/ember.js,amk221/ember.js,duggiefresh/ember.js,kellyselden/ember.js,Serabe/ember.js,runspired/ember.js,mixonic/ember.js,davidpett/ember.js,miguelcobain/ember.js,kanongil/ember.js,tildeio/ember.js,kanongil/ember.js,johanneswuerbach/ember.js,Turbo87/ember.js,tildeio/ember.js,cbou/ember.js,Turbo87/ember.js,cibernox/ember.js,mike-north/ember.js,gfvcastro/ember.js,alexdiliberto/ember.js,gfvcastro/ember.js,twokul/ember.js,patricksrobertson/ember.js,workmanw/ember.js,chadhietala/ember.js,xiujunma/ember.js,cibernox/ember.js,elwayman02/ember.js,sivakumar-kailasam/ember.js,jherdman/ember.js,alexdiliberto/ember.js,GavinJoyce/ember.js,sly7-7/ember.js,kellyselden/ember.js,Turbo87/ember.js,asakusuma/ember.js | ---
+++
@@ -8,7 +8,8 @@
});
test('it renders', function(assert) {
- <% if (testType === 'integration' ) { %>// Set any properties with this.set('myProperty', 'value');
+<% if (testType === 'integration' ) { %>
+ // Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{<%= componentPathName %>}}`); |
0bcc5afa1f15315173c60c666e8ba2c1b72731ae | ember/mirage/config.js | ember/mirage/config.js | export default function () {
this.passthrough('/translations/**');
this.get('/api/locale', { locale: 'en' });
}
| export default function () {
this.passthrough('/translations/**');
this.get('/api/locale', { locale: 'en' });
this.get('/api/notifications', { events: [] });
}
| Add basic `GET /api/notifications` route handler | mirage: Add basic `GET /api/notifications` route handler
| JavaScript | agpl-3.0 | skylines-project/skylines,skylines-project/skylines,skylines-project/skylines,skylines-project/skylines | ---
+++
@@ -2,4 +2,6 @@
this.passthrough('/translations/**');
this.get('/api/locale', { locale: 'en' });
+
+ this.get('/api/notifications', { events: [] });
} |
8dd652690386b1dde43e154ab3fb0d48e9b0659a | lib/components/form/mode-button.js | lib/components/form/mode-button.js | import React, {PropTypes, Component} from 'react'
import { getModeIcon } from '../../util/itinerary'
export default class ModeButton extends Component {
static propTypes = {
active: PropTypes.bool,
label: PropTypes.string,
mode: PropTypes.string,
icons: PropTypes.object,
onClick: PropTypes.func
}
render () {
const {active, icons, label, mode, onClick} = this.props
const buttonColor = active ? '#000' : '#bbb'
return (
<div className='mode-button-container'>
<button
className='mode-button'
onClick={onClick}
title={mode}
style={{ borderColor: buttonColor }}
>
<div
className='mode-icon'
style={{ fill: buttonColor }}>
{getModeIcon(mode, icons)}
</div>
</button>
<div className='mode-label' style={{ color: buttonColor }}>{label}</div>
{active && <div>
<div className='mode-check' style={{ color: 'white' }}><i className='fa fa-circle' /></div>
<div className='mode-check' style={{ color: 'red' }}><i className='fa fa-check-circle' /></div>
</div>}
</div>
)
}
}
| import React, {PropTypes, Component} from 'react'
import { getModeIcon } from '../../util/itinerary'
export default class ModeButton extends Component {
static propTypes = {
active: PropTypes.bool,
label: PropTypes.string,
mode: PropTypes.string,
icons: PropTypes.object,
onClick: PropTypes.func
}
render () {
const {active, icons, label, mode, onClick} = this.props
const buttonColor = active ? '#000' : '#bbb'
return (
<div className='mode-button-container'>
<button
className='mode-button'
onClick={onClick}
title={mode}
style={{ borderColor: buttonColor }}
>
<div
className='mode-icon'
style={{ fill: buttonColor }}>
{getModeIcon(mode, icons)}
</div>
</button>
<div className='mode-label' style={{ color: buttonColor }}>{label}</div>
{active && <div>
<div className='mode-check' style={{ color: 'white' }}><i className='fa fa-circle' /></div>
<div className='mode-check' style={{ color: 'green' }}><i className='fa fa-check-circle' /></div>
</div>}
</div>
)
}
}
| Change color of mode button checkboxes to green | feat(form): Change color of mode button checkboxes to green
| JavaScript | mit | opentripplanner/otp-react-redux,opentripplanner/otp-react-redux,opentripplanner/otp-react-redux,opentripplanner/otp-react-redux | ---
+++
@@ -31,7 +31,7 @@
<div className='mode-label' style={{ color: buttonColor }}>{label}</div>
{active && <div>
<div className='mode-check' style={{ color: 'white' }}><i className='fa fa-circle' /></div>
- <div className='mode-check' style={{ color: 'red' }}><i className='fa fa-check-circle' /></div>
+ <div className='mode-check' style={{ color: 'green' }}><i className='fa fa-check-circle' /></div>
</div>}
</div>
) |
d01136d921ec73f2c09d9bb3a748684670a82db4 | src/read/elements/loading.js | src/read/elements/loading.js | 'use strict';
import React from 'react';
import ActivityIndicator from './pure/activityIndicator';
import ui from '../../ui';
class Loading extends React.Component {
static propTypes = {
dispatch: React.PropTypes.func.isRequired,
kind: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.arrayOf(React.PropTypes.string)
]).isRequired,
uri: React.PropTypes.string.isRequired,
where: React.PropTypes.string.isRequired
};
constructor(props) {
super(props);
}
componentDidMount() {
const { dispatch, kind, uri, where, readId } = this.props;
dispatch({type: 'READ_PERFORM', uri, where, kind, readId});
}
render() {
return (
<ActivityIndicator />
);
}
}
ui.register(['__loading'], ({ element, dispatch}) => {
return (
<Loading
kind={element.get('kind').toJS()}
uri={element.get('uri')}
where={element.get('where', 'content')}
dispatch={dispatch}
readId={element.get('readId')}/>
);
});
| 'use strict';
import React from 'react';
import ActivityIndicator from './pure/activityIndicator';
import ui from '../../ui';
class Loading extends React.Component {
static propTypes = {
dispatch: React.PropTypes.func.isRequired,
kind: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.arrayOf(React.PropTypes.string)
]).isRequired,
uri: React.PropTypes.string.isRequired,
where: React.PropTypes.string.isRequired,
readId: React.PropTypes.string.isRequired
};
constructor(props) {
super(props);
}
componentDidMount() {
const { dispatch, kind, uri, where, readId } = this.props;
dispatch({type: 'READ_PERFORM', uri, where, kind, readId});
}
render() {
return (
<ActivityIndicator />
);
}
}
ui.register(['__loading'], ({ element, dispatch}) => {
return (
<Loading
kind={element.get('kind').toJS()}
uri={element.get('uri')}
where={element.get('where', 'content')}
dispatch={dispatch}
readId={element.get('readId')}/>
);
});
| Add missing prop validation for readId | Add missing prop validation for readId
| JavaScript | mit | netceteragroup/girders-elements | ---
+++
@@ -15,7 +15,8 @@
React.PropTypes.arrayOf(React.PropTypes.string)
]).isRequired,
uri: React.PropTypes.string.isRequired,
- where: React.PropTypes.string.isRequired
+ where: React.PropTypes.string.isRequired,
+ readId: React.PropTypes.string.isRequired
};
constructor(props) { |
6495cd006c6ab087f971981873ae7202d4fd73e6 | includes/js/main.js | includes/js/main.js | var mode = 0; //primary
function calc_mode() {
var modes = ["primary", "secondary", "tertiary"];
return modes[mode];
}
$(function() {
$(".add").button();
$(".edit").button();
$(".delete").button().click(function() {
var res = confirm("Are you sure you want to delete this item?");
if (res)
window.location.href=$(this).attr('href');
else
return false;
});
$(".view").button();
$(".submit").button();
$("#ingredients_table table").tablesorter();
$("#effects_table table").tablesorter();
$("#calc_ingredients tbody").find('tr').each(function(){
$(this).click(function(){
$('#'+calc_mode()).html($(this).text());
});
});
});
| var mode = 0; //primary
function calc_mode() {
var modes = ["primary", "secondary", "tertiary"];
return modes[mode];
}
$(function() {
$(".add").button();
$(".edit").button();
$(".delete").button().click(function() {
var res = confirm("Are you sure you want to delete this item?");
if (res)
window.location.href=$(this).attr('href');
else
return false;
});
$(".view").button();
$(".submit").button();
$("#ingredients_table table").tablesorter();
$("#effects_table table").tablesorter();
$("#calc_ingredients tbody").find('tr').each(function(){
$(this).click(function(){
$('#'+calc_mode()).html($(this).text());
});
});
$("#primary").click(function(){
$(this).text('--');
mode = 0;
});
$("#secondary").click(function(){
$(this).text('--');
mode = 1;
});
$("#tertiary").click(function(){
$(this).text('--');
mode = 2;
});
});
| Add events handler on selected ingredients | Add events handler on selected ingredients
| JavaScript | mit | claw68/alchemy,claw68/alchemy,claw68/alchemy,claw68/alchemy | ---
+++
@@ -26,4 +26,19 @@
$('#'+calc_mode()).html($(this).text());
});
});
+
+ $("#primary").click(function(){
+ $(this).text('--');
+ mode = 0;
+ });
+
+ $("#secondary").click(function(){
+ $(this).text('--');
+ mode = 1;
+ });
+
+ $("#tertiary").click(function(){
+ $(this).text('--');
+ mode = 2;
+ });
}); |
77fa21457a7b503d9086b28b480baa8b96d0715f | src/commands/view/OpenAssets.js | src/commands/view/OpenAssets.js | export default {
run(editor, sender, opts = {}) {
const modal = editor.Modal;
const am = editor.AssetManager;
const config = am.getConfig();
const title = opts.modalTitle || editor.t('assetManager.modalTitle') || '';
const types = opts.types;
const accept = opts.accept;
am.setTarget(opts.target);
am.onClick(opts.onClick);
am.onDblClick(opts.onDblClick);
am.onSelect(opts.onSelect);
if (!this.rendered || types) {
let assets = am.getAll().filter(i => i);
if (types && types.length) {
assets = assets.filter(a => types.indexOf(a.get('type')) !== -1);
}
am.render(assets);
this.rendered = am.getContainer();
}
if (accept) {
const uploadEl = this.rendered.querySelector(
`input#${config.stylePrefix}uploadFile`
);
uploadEl && uploadEl.setAttribute('accept', accept);
}
modal.open({ title, content: this.rendered });
return this;
}
};
| export default {
run(editor, sender, opts = {}) {
const modal = editor.Modal;
const am = editor.AssetManager;
const config = am.getConfig();
const title = opts.modalTitle || editor.t('assetManager.modalTitle') || '';
const types = opts.types;
const accept = opts.accept;
am.setTarget(opts.target);
am.onClick(opts.onClick);
am.onDblClick(opts.onDblClick);
am.onSelect(opts.onSelect);
if (!this.rendered || types) {
let assets = am.getAll().filter(i => i);
if (types && types.length) {
assets = assets.filter(a => types.indexOf(a.get('type')) !== -1);
}
am.render(assets);
this.rendered = am.getContainer();
}
if (accept) {
const uploadEl = this.rendered.querySelector(
`input#${config.stylePrefix}uploadFile`
);
uploadEl && uploadEl.setAttribute('accept', accept);
}
modal
.open({ title, content: this.rendered })
.onceClose(() => editor.stopCommand(this.id));
return this;
},
stop(editor) {
const { Modal } = editor;
Modal && Modal.close();
}
};
| Add stop command to openAssets | Add stop command to openAssets
| JavaScript | bsd-3-clause | artf/grapesjs,artf/grapesjs,artf/grapesjs | ---
+++
@@ -30,7 +30,14 @@
uploadEl && uploadEl.setAttribute('accept', accept);
}
- modal.open({ title, content: this.rendered });
+ modal
+ .open({ title, content: this.rendered })
+ .onceClose(() => editor.stopCommand(this.id));
return this;
+ },
+
+ stop(editor) {
+ const { Modal } = editor;
+ Modal && Modal.close();
}
}; |
167aa0bf00f03eba76a432f548885636d8a0b28d | .eslintrc.js | .eslintrc.js | module.exports = {
'root': true,
'parser': 'babel-eslint',
'extends': [
'airbnb',
'plugin:import/errors'
],
'rules': {
'space-before-function-paren': 0,
'comma-dangle': [2, 'never'],
'one-var': 0,
'one-var-declaration-per-line': 0,
'prefer-arrow-callback': 0,
'strict': 0,
'no-use-before-define': [2, {'functions': false}],
'no-underscore-dangle': 0,
'react/wrap-multilines': 0,
'react/prefer-stateless-function': 0,
'react/jsx-first-prop-new-line': 0,
'react/jsx-no-bind': 0,
'react/sort-comp': [2, {
order: [
'displayName',
'propTypes',
'mixins',
'statics',
'getDefaultProps',
'getInitialState',
'constructor',
'render',
'/^_render.+$/', // any auxiliary _render methods
'componentWillMount',
'componentDidMount',
'componentWillReceiveProps',
'shouldComponentUpdate',
'componentWillUpdate',
'componentDidUpdate',
'componentWillUnmount',
'/^on[A-Z].+$/', // event handlers
'everything-else',
'/^_.+$/' // private methods
]
}]
}
}
| module.exports = {
'root': true,
'parser': 'babel-eslint',
'extends': [
'airbnb',
'plugin:import/errors'
],
'rules': {
'space-before-function-paren': 0,
'comma-dangle': [2, 'never'],
'one-var': 0,
'one-var-declaration-per-line': 0,
'prefer-arrow-callback': 0,
'strict': 0,
'no-use-before-define': [2, {'functions': false}],
'no-underscore-dangle': 0,
'react/wrap-multilines': 0,
'react/prefer-stateless-function': 0,
'react/jsx-first-prop-new-line': 0,
'react/jsx-no-bind': 0,
'react/sort-comp': [2, {
order: [
'displayName',
'propTypes',
'mixins',
'statics',
'getDefaultProps',
'defaultProps',
'getInitialState',
'constructor',
'render',
'/^_render.+$/', // any auxiliary _render methods
'componentWillMount',
'componentDidMount',
'componentWillReceiveProps',
'shouldComponentUpdate',
'componentWillUpdate',
'componentDidUpdate',
'componentWillUnmount',
'/^on[A-Z].+$/', // event handlers
'everything-else',
'/^_.+$/' // private methods
]
}]
}
}
| Enforce that defaultProps sit next to statics | Enforce that defaultProps sit next to statics
| JavaScript | mit | NiGhTTraX/react-test-buffet,NiGhTTraX/react-test-buffet,NiGhTTraX/react-test-buffet | ---
+++
@@ -29,6 +29,7 @@
'mixins',
'statics',
'getDefaultProps',
+ 'defaultProps',
'getInitialState',
'constructor',
'render', |
3fff4b7571affcbd95cee4bc8df03598019695a6 | .eslintrc.js | .eslintrc.js | module.exports = {
root: true,
parserOptions: {
ecmaVersion: 2017,
sourceType: "module"
},
plugins: ["ember"],
extends: [
"eslint:recommended",
"plugin:ember/recommended",
"plugin:prettier/recommended"
],
env: {
browser: true
},
rules: {
"prettier/prettier": 2,
"ember/new-module-imports": 2
},
overrides: [
// node files
{
files: [
"index.js",
"testem.js",
"ember-cli-build.js",
"config/**/*.js",
"tests/dummy/config/**/*.js",
"blueprints/**/*.js"
],
excludedFiles: ["app/**", "addon/**", "tests/dummy/app/**"],
parserOptions: {
sourceType: "script",
ecmaVersion: 2015
},
env: {
browser: false,
node: true
},
plugins: ["node"],
rules: Object.assign(
{},
require("eslint-plugin-node").configs.recommended.rules,
{
// add your custom rules and overrides for node files here
}
)
}
]
};
| module.exports = {
root: true,
parserOptions: {
ecmaVersion: 2017,
sourceType: "module"
},
plugins: ["ember", "prettier"],
extends: [
"eslint:recommended",
"plugin:ember/recommended",
"plugin:prettier/recommended"
],
env: {
browser: true
},
rules: {
"prettier/prettier": 2,
"ember/new-module-imports": 2
},
overrides: [
// node files
{
files: [
"index.js",
"testem.js",
"ember-cli-build.js",
"config/**/*.js",
"tests/dummy/config/**/*.js",
"blueprints/**/*.js"
],
excludedFiles: ["app/**", "addon/**", "tests/dummy/app/**"],
parserOptions: {
sourceType: "script",
ecmaVersion: 2015
},
env: {
browser: false,
node: true
},
plugins: ["node"],
rules: Object.assign(
{},
require("eslint-plugin-node").configs.recommended.rules,
{
// add your custom rules and overrides for node files here
}
)
}
]
};
| Add prettier as eslint plugin | Add prettier as eslint plugin
| JavaScript | mit | adfinis-sygroup/ember-validated-form,adfinis-sygroup/ember-validated-form,adfinis-sygroup/ember-validated-form | ---
+++
@@ -4,7 +4,7 @@
ecmaVersion: 2017,
sourceType: "module"
},
- plugins: ["ember"],
+ plugins: ["ember", "prettier"],
extends: [
"eslint:recommended",
"plugin:ember/recommended", |
851ff5f6511117c9122e7f8b97797171d2372502 | example/Button.card.js | example/Button.card.js | import devcards from '../';
import React from 'react';
import Button from './Button';
var devcard = devcards.ns('buttons');
devcard(
'Buttons',
`
A simple display of bootstrap buttons.
* default
* primary
* success
* info
* warning
* danger
* link
`,
(
<div>
<Button kind="default">default</Button>
<Button kind="primary">primary</Button>
<Button kind="success">success</Button>
<Button kind="info">info</Button>
<Button kind="warning">warning</Button>
<Button kind="danger">danger</Button>
<Button kind="link">link</Button>
</div>
)
);
| import devcards from '../';
import React from 'react';
import Button from './Button';
var devcard = devcards.ns('buttons');
devcard(
'Buttons',
`
A simple display of bootstrap buttons.
* default
* primary
* success
* info
* warning
* danger
* link
`,
<div style={{textAlign: 'center'}}>
<Button kind="default">default</Button>
<Button kind="primary">primary</Button>
<Button kind="success">success</Button>
<Button kind="info">info</Button>
<Button kind="warning">warning</Button>
<Button kind="danger">danger</Button>
<Button kind="link">link</Button>
</div>
);
| Align as an option isn't ideal, include inline style example instead | Align as an option isn't ideal, include inline style example instead
There are two ways to center align in CSS, neither work well to
integrate into the card system
1) text-align: center
this cascades into all children, and would force the consumer to
override text-align back to what they wanted on other elements
2) margin-left/right: auto
this only works on components with fixed width
| JavaScript | mit | glenjamin/devboard,glenjamin/devboard,glenjamin/devboard | ---
+++
@@ -17,15 +17,13 @@
* danger
* link
`,
- (
- <div>
- <Button kind="default">default</Button>
- <Button kind="primary">primary</Button>
- <Button kind="success">success</Button>
- <Button kind="info">info</Button>
- <Button kind="warning">warning</Button>
- <Button kind="danger">danger</Button>
- <Button kind="link">link</Button>
- </div>
- )
+ <div style={{textAlign: 'center'}}>
+ <Button kind="default">default</Button>
+ <Button kind="primary">primary</Button>
+ <Button kind="success">success</Button>
+ <Button kind="info">info</Button>
+ <Button kind="warning">warning</Button>
+ <Button kind="danger">danger</Button>
+ <Button kind="link">link</Button>
+ </div>
); |
10577cdf202b955fa855a31a6df961c37b016a73 | src/bot/accountUnlinked.js | src/bot/accountUnlinked.js | import { unlinkUser } from '../lib/postgres';
export default (bot) => {
return async (payload, reply) => {
const page_scoped_id = payload.sender.id;
await unlinkUser(page_scoped_id);
await reply({ text: 'You have successfully logged out' });
console.log(`Unlinked account -> ${page_scoped_id}`);
};
};
| import { unlinkUser } from '../lib/postgres';
export default (bot) => {
return async (payload, reply) => {
const page_scoped_id = payload.sender.id;
await unlinkUser(page_scoped_id);
await reply({ text: 'You have successfully logged out from EBudgie' });
console.log(`Unlinked account -> ${page_scoped_id}`);
};
};
| Change messega for unlinking account | Change messega for unlinking account
| JavaScript | mit | nikolay-radkov/ebudgie-server,nikolay-radkov/ebudgie-server | ---
+++
@@ -5,7 +5,7 @@
const page_scoped_id = payload.sender.id;
await unlinkUser(page_scoped_id);
- await reply({ text: 'You have successfully logged out' });
+ await reply({ text: 'You have successfully logged out from EBudgie' });
console.log(`Unlinked account -> ${page_scoped_id}`);
};
}; |
83f761e1bafa07f1998bb845caa69c95d80a0235 | src/admin/redux/modules/letter.js | src/admin/redux/modules/letter.js | /* @flow */
import { FETCHED_MEMBER } from '../../../shared/redux/modules/member.js'
import { mergeAll, converge, unapply, compose, objOf, prop } from 'ramda'
import type { Action, Reducer } from 'redux'
type State = {}
const reducer: Reducer<State, Action> =
(state = { id: 0, address: [], name: '' }, { type, payload }) => {
switch (type) {
case FETCHED_MEMBER:
return converge
( unapply(mergeAll)
, [ compose(objOf('name'), getName)
, compose(objOf('address'), getAddress)
, compose(objOf('id'), prop('id'))
]
)(payload)
default:
return state
}
}
const getName = ({ title, full_name }) => title + ' ' + full_name
const getAddress = (
{ title
, first_name = ''
, last_name = ''
, address1
, address2
, address3
, address4
, county
, postcode
}
) =>
[ `${title} ${first_name[0] || ''} ${last_name}`, address1, address2,
address3, address4, county, postcode ]
export default reducer
| /* @flow */
import { FETCHED_MEMBER } from '../../../shared/redux/modules/member.js'
import { mergeAll, converge, unapply, compose, objOf, prop } from 'ramda'
import type { Action, Reducer } from 'redux'
type State = {}
const reducer: Reducer<State, Action> =
(state = { id: 0, address: [], name: '' }, { type, payload }) => {
switch (type) {
case FETCHED_MEMBER:
return converge
( unapply(mergeAll)
, [ compose(objOf('name'), getName)
, compose(objOf('address'), getAddress)
, compose(objOf('id'), prop('id'))
]
)(payload)
default:
return state
}
}
const getName = ({ title, full_name }) => title + ' ' + full_name
const getAddress = (
{ title
, first_name = ''
, last_name = ''
, address1
, address2
, address3
, address4
, county
, postcode
}
) =>
[ `${title} ${(first_name && first_name[0]) || ''} ${last_name}`
, address1
, address2
, address3
, address4
, county
, postcode ]
export default reducer
| Fix bug that meant member details not displaying if no first name had been entered. | Fix bug that meant member details not displaying if no first name had been entered.
| JavaScript | mit | foundersandcoders/sail-back,foundersandcoders/sail-back | ---
+++
@@ -36,8 +36,12 @@
, postcode
}
) =>
- [ `${title} ${first_name[0] || ''} ${last_name}`, address1, address2,
- address3, address4, county, postcode ]
+ [ `${title} ${(first_name && first_name[0]) || ''} ${last_name}`
+ , address1
+ , address2
+ , address3
+ , address4
+ , county
+ , postcode ]
export default reducer
- |
11934adf1a17ae9bf549dfddfcc21f71eb28a2a2 | src/app/directives/configModal.js | src/app/directives/configModal.js | define([
'angular'
],
function (angular) {
'use strict';
angular
.module('kibana.directives')
.directive('configModal', function($modal,$q) {
return {
restrict: 'A',
link: function(scope, elem) {
// create a new modal. Can't reuse one modal unforunately as the directive will not
// re-render on show.
elem.bind('click',function(){
var tmpScope = scope.$new();
tmpScope.panel = angular.copy(scope.panel);
tmpScope.editSave = function(panel) {
scope.panel = panel;
};
var panelModal = $modal({
template: './app/partials/paneleditor.html',
persist: true,
show: false,
scope: tmpScope,
keyboard: false
});
// and show it
$q.when(panelModal).then(function(modalEl) {
modalEl.modal('show');
});
scope.$apply();
});
}
};
});
}); | define([
'angular',
'underscore'
],
function (angular,_) {
'use strict';
angular
.module('kibana.directives')
.directive('configModal', function($modal,$q) {
return {
restrict: 'A',
link: function(scope, elem) {
// create a new modal. Can't reuse one modal unforunately as the directive will not
// re-render on show.
elem.bind('click',function(){
// Create a temp scope so we can discard changes to it if needed
var tmpScope = scope.$new();
tmpScope.panel = angular.copy(scope.panel);
tmpScope.editSave = function(panel) {
// Correctly set the top level properties of the panel object
_.each(panel,function(v,k) {
scope.panel[k] = panel[k];
});
};
var panelModal = $modal({
template: './app/partials/paneleditor.html',
persist: true,
show: false,
scope: tmpScope,
keyboard: false
});
// and show it
$q.when(panelModal).then(function(modalEl) {
modalEl.modal('show');
});
scope.$apply();
});
}
};
});
}); | Fix saving of top level panel properties | Fix saving of top level panel properties
| JavaScript | agpl-3.0 | grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana | ---
+++
@@ -1,7 +1,8 @@
define([
- 'angular'
+ 'angular',
+ 'underscore'
],
-function (angular) {
+function (angular,_) {
'use strict';
angular
@@ -15,11 +16,15 @@
// re-render on show.
elem.bind('click',function(){
+ // Create a temp scope so we can discard changes to it if needed
var tmpScope = scope.$new();
tmpScope.panel = angular.copy(scope.panel);
tmpScope.editSave = function(panel) {
- scope.panel = panel;
+ // Correctly set the top level properties of the panel object
+ _.each(panel,function(v,k) {
+ scope.panel[k] = panel[k];
+ });
};
var panelModal = $modal({ |
3c0c8915e6a5590a8d6d0db65a90632bce985c6f | eloquent_js/chapter04/ch04_ex03.js | eloquent_js/chapter04/ch04_ex03.js | function arrayToList(array) {
let list = null;
for (let i = array.length - 1; i >= 0; --i) {
list = {value: array[i], rest: list};
}
return list;
}
function listToArray(list) {
let array = [];
for (let node = list; node; node = node.rest) {
array.push(node.value);
}
return array;
}
function prepend(element, list) {
return {element, rest: list};
}
function nth(list, n) {
// Could check if (!list) here instead or in the return expression
if (n === 0) return list.value;
else return list.rest ? nth(list.rest, n-1) : undefined;
}
| function arrayToList(arr) {
if (arr.length == 0) return null;
let list = null;
for (let i = arr.length - 1; i >= 0; --i) {
list = {value: arr[i], rest: list};
}
return list;
}
function listToArray(list) {
let arr = [];
for (let node = list; node; node = node.rest) {
arr.push(node.value)
}
return arr;
}
function prepend(elem, list) {
return {value: elem, rest: list};
}
function nth(list, n) {
if (n == 0) {
return list.value;
}
if (list.rest == null) {
return undefined;
}
return nth(list.rest, n -1);
}
| Add chapter 4, exercise 3 | Add chapter 4, exercise 3
| JavaScript | mit | bewuethr/ctci | ---
+++
@@ -1,25 +1,36 @@
-function arrayToList(array) {
- let list = null;
- for (let i = array.length - 1; i >= 0; --i) {
- list = {value: array[i], rest: list};
- }
- return list;
+function arrayToList(arr) {
+ if (arr.length == 0) return null;
+
+ let list = null;
+ for (let i = arr.length - 1; i >= 0; --i) {
+ list = {value: arr[i], rest: list};
+ }
+
+ return list;
}
function listToArray(list) {
- let array = [];
- for (let node = list; node; node = node.rest) {
- array.push(node.value);
- }
- return array;
+ let arr = [];
+
+ for (let node = list; node; node = node.rest) {
+ arr.push(node.value)
+ }
+
+ return arr;
}
-function prepend(element, list) {
- return {element, rest: list};
+function prepend(elem, list) {
+ return {value: elem, rest: list};
}
function nth(list, n) {
- // Could check if (!list) here instead or in the return expression
- if (n === 0) return list.value;
- else return list.rest ? nth(list.rest, n-1) : undefined;
+ if (n == 0) {
+ return list.value;
+ }
+
+ if (list.rest == null) {
+ return undefined;
+ }
+
+ return nth(list.rest, n -1);
} |
847f32fb3980cb624e516d8f3052388de5a8ec49 | server/import/import_scripts/category_mapping.js | server/import/import_scripts/category_mapping.js | module.exports = {
"Dagens bedrift": "PRESENTATIONS",
"Fest og moro": "NIGHTLIFE",
"Konsert": "MUSIC",
"Kurs og events": "PRESENTATIONS",
"Revy og teater": "PERFORMANCES",
"Foredrag": "PRESENTATIONS",
"Møte": "DEBATE",
"Happening": "NIGHTLIFE",
"Kurs": "OTHER",
"Show": "PERFORMANCES",
"Fotballkamp": "SPORT",
"Film": "PRESENTATIONS",
"Samfundsmøte": "DEBATE",
"Excenteraften": "DEBATE",
"Temafest": "NIGHTLIFE",
"Bokstavelig talt": "DEBATE",
"Quiz": "OTHER",
"DJ": "MUSIC",
"Teater": "PERFORMANCES",
"Annet": "OTHER",
"Kurs": "PRESENTATIONS",
"Omvising": "PRESENTATIONS",
"Samfunn": "DEBATE",
"Festival": "PERFORMANCES",
"Sport": "SPORT",
"Forestilling": "PERFORMANCES"
};
| module.exports = {
"Dagens bedrift": "PRESENTATIONS",
"Fest og moro": "NIGHTLIFE",
"Konsert": "MUSIC",
"Kurs og events": "PRESENTATIONS",
"Revy og teater": "PERFORMANCES",
"Foredrag": "PRESENTATIONS",
"Møte": "DEBATE",
"Happening": "NIGHTLIFE",
"Kurs": "OTHER",
"Show": "PERFORMANCES",
"Fotballkamp": "SPORT",
"Film": "PRESENTATIONS",
"Samfundsmøte": "DEBATE",
"Excenteraften": "DEBATE",
"Temafest": "NIGHTLIFE",
"Bokstavelig talt": "DEBATE",
"Quiz": "OTHER",
"DJ": "MUSIC",
"Teater": "PERFORMANCES",
"Annet": "OTHER",
"Kurs": "PRESENTATIONS",
"Omvising": "PRESENTATIONS",
"Samfunn": "DEBATE",
"Festival": "PERFORMANCES",
"Sport": "SPORT",
"Forestilling": "PERFORMANCES",
"Utstilling" : "EXHIBITIONS"
};
| Add category mapping for exhibitions | Add category mapping for exhibitions
Too many exhibition events from TRDEvents got the "other"-category
| JavaScript | apache-2.0 | Studentmediene/Barteguiden,Studentmediene/Barteguiden | ---
+++
@@ -24,8 +24,6 @@
"Samfunn": "DEBATE",
"Festival": "PERFORMANCES",
"Sport": "SPORT",
- "Forestilling": "PERFORMANCES"
+ "Forestilling": "PERFORMANCES",
+ "Utstilling" : "EXHIBITIONS"
};
-
-
- |
847fa26ac3e5b60e16d6c03c521ce29bdc709164 | lib/routes/index.js | lib/routes/index.js | function render(viewName, layoutPath) {
if (!layoutPath) {
return function (req, res) {
res.render(viewName);
};
}
else {
return function (req, res) {
res.render(viewName, { layout: layoutPath });
};
}
}
module.exports = {
render: render
};
| function render(viewName, layoutPath) {
return function (req, res) {
if (layoutPath) {
res.locals.layout = layoutPath;
}
res.render(viewName);
};
}
module.exports = {
render: render
};
| Change implementation of `render` route | Change implementation of `render` route
| JavaScript | bsd-3-clause | weigang992003/pure-css-chinese,jamesalley/pure-site,yahoo/pure-site,weigang992003/pure-css-chinese,jamesalley/pure-site,pandoraui/pure-site,yahoo/pure-site,chensy0203/pure-site | ---
+++
@@ -1,15 +1,11 @@
function render(viewName, layoutPath) {
- if (!layoutPath) {
- return function (req, res) {
- res.render(viewName);
- };
- }
- else {
- return function (req, res) {
- res.render(viewName, { layout: layoutPath });
- };
- }
+ return function (req, res) {
+ if (layoutPath) {
+ res.locals.layout = layoutPath;
+ }
+ res.render(viewName);
+ };
}
module.exports = { |
ef93e13a9e22459c8151c36bae520ed80fdb1b5b | lib/server/index.js | lib/server/index.js | var path = require('path');
var url = require('url');
var compression = require('compression');
var express = require('express');
var ssr = require('../index');
var xhr = require('./xhr');
var proxy = require('./proxy');
module.exports = function (config) {
var app = express()
.use(compression())
.use(xhr());
var pkgPath = path.join(config.path, 'package.json');
var pkg = require(pkgPath);
var render = ssr({
config: pkgPath + '!npm',
main: pkg.main
});
if (config.configure) {
config.configure(app);
}
if (config.proxy) {
var apiPath = config.proxyTo || '/api';
app.use(apiPath, proxy(config.proxy));
}
app.use(express.static(path.join(config.path)));
app.use("/", function (req, res) {
const pathname = url.parse(req.url).pathname;
render(pathname).then(res.send.bind(res));
});
return app;
};
| var path = require('path');
var url = require('url');
var compression = require('compression');
var express = require('express');
var ssr = require('../index');
var xhr = require('./xhr');
var proxy = require('./proxy');
var doctype = '<!DOCTYPE html>';
module.exports = function (config) {
var app = express()
.use(compression())
.use(xhr());
var pkgPath = path.join(config.path, 'package.json');
var pkg = require(pkgPath);
var render = ssr({
config: pkgPath + '!npm',
main: pkg.main
});
if (config.configure) {
config.configure(app);
}
if (config.proxy) {
var apiPath = config.proxyTo || '/api';
app.use(apiPath, proxy(config.proxy));
}
app.use(express.static(path.join(config.path)));
app.use("/", function (req, res) {
var pathname = url.parse(req.url).pathname;
render(pathname).then(function(html) {
var dt = config.doctype || doctype;
res.send(dt + '\n' + html);
});
});
return app;
};
| Add HTML5 doctype to all rendered pages. | Add HTML5 doctype to all rendered pages.
| JavaScript | mit | donejs/done-ssr,donejs/done-ssr | ---
+++
@@ -7,6 +7,7 @@
var ssr = require('../index');
var xhr = require('./xhr');
var proxy = require('./proxy');
+var doctype = '<!DOCTYPE html>';
module.exports = function (config) {
var app = express()
@@ -33,9 +34,12 @@
app.use(express.static(path.join(config.path)));
app.use("/", function (req, res) {
- const pathname = url.parse(req.url).pathname;
+ var pathname = url.parse(req.url).pathname;
- render(pathname).then(res.send.bind(res));
+ render(pathname).then(function(html) {
+ var dt = config.doctype || doctype;
+ res.send(dt + '\n' + html);
+ });
});
return app; |
8065830ff2163bf1178b204a5873b7d56b40a228 | src/scripts/commons/d3-utils.js | src/scripts/commons/d3-utils.js | // External
import * as d3 from 'd3';
export function mergeSelections (selections) {
// Create a new empty selection
const mergedSelection = d3.selectAll('.d3-list-graph-not-existent');
function pushSelection (selection) {
selection.each(function pushDomNode () {
mergedSelection[0].push(this);
});
}
for (let i = selections.length; i--;) {
pushSelection(selections[i]);
}
return mergedSelection;
}
export function allTransitionsEnded (transition, callback) {
if (transition.size() === 0) {
callback();
}
let n = 0;
transition
.each(() => ++n)
.on('end', function (...args) {
if (!--n) callback.apply(this, args);
});
}
| // External
import * as d3 from 'd3';
export function mergeSelections (selections) {
// Create a new empty selection
const mergedSelection = d3.selectAll('.d3-list-graph-not-existent');
for (let i = selections.length; i--;) {
mergedSelection._groups = mergedSelection._groups.concat(
selections[i]._groups
);
}
return mergedSelection;
}
export function allTransitionsEnded (transition, callback) {
if (transition.size() === 0) {
callback();
}
let n = 0;
transition
.each(() => ++n)
.on('end', function (...args) {
if (!--n) callback.apply(this, args);
});
}
| Adjust selection merge method to D3 v4. | Adjust selection merge method to D3 v4.
| JavaScript | mit | flekschas/d3-list-graph,flekschas/d3-list-graph | ---
+++
@@ -5,14 +5,10 @@
// Create a new empty selection
const mergedSelection = d3.selectAll('.d3-list-graph-not-existent');
- function pushSelection (selection) {
- selection.each(function pushDomNode () {
- mergedSelection[0].push(this);
- });
- }
-
for (let i = selections.length; i--;) {
- pushSelection(selections[i]);
+ mergedSelection._groups = mergedSelection._groups.concat(
+ selections[i]._groups
+ );
}
return mergedSelection; |
bb8eac7f6c3493a5fb0f644c92bc71229129101c | src/scheduler-assignment.js | src/scheduler-assignment.js | let scheduler = null
export function setScheduler (customScheduler) {
if (customScheduler) {
scheduler = customScheduler
} else {
scheduler = new DefaultScheduler()
}
}
export function getScheduler () {
return scheduler
}
class DefaultScheduler {
constructor () {
this.updateRequests = []
this.frameRequested = false
this.performUpdates = this.performUpdates.bind(this)
}
updateDocument (fn) {
this.updateRequests.push(fn)
if (!this.frameRequested) {
this.frameRequested = true
window.requestAnimationFrame(this.performUpdates)
}
}
performUpdates () {
this.frameRequested = false
while (this.updateRequests.length > 0) {
this.updateRequests.shift()()
}
}
}
| let scheduler = null
export function setScheduler (customScheduler) {
scheduler = customScheduler
}
export function getScheduler () {
if (!scheduler) {
scheduler = new DefaultScheduler()
}
return scheduler
}
class DefaultScheduler {
constructor () {
this.updateRequests = []
this.frameRequested = false
this.performUpdates = this.performUpdates.bind(this)
}
updateDocument (fn) {
this.updateRequests.push(fn)
if (!this.frameRequested) {
this.frameRequested = true
window.requestAnimationFrame(this.performUpdates)
}
}
performUpdates () {
this.frameRequested = false
while (this.updateRequests.length > 0) {
this.updateRequests.shift()()
}
}
}
| Use the DefaultScheduler if none is assigned | Use the DefaultScheduler if none is assigned
Fixes #1 | JavaScript | mit | smashwilson/etch,atom/etch,lee-dohm/etch,nathansobo/etch | ---
+++
@@ -1,14 +1,13 @@
let scheduler = null
export function setScheduler (customScheduler) {
- if (customScheduler) {
- scheduler = customScheduler
- } else {
- scheduler = new DefaultScheduler()
- }
+ scheduler = customScheduler
}
export function getScheduler () {
+ if (!scheduler) {
+ scheduler = new DefaultScheduler()
+ }
return scheduler
}
|
a3a1990d95b3162ecd404610d176e2cb0bccde3b | web/app/store/MapTypes.js | web/app/store/MapTypes.js | /*
* Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com)
*
* 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.
*/
Ext.define('Traccar.store.MapTypes', {
extend: 'Ext.data.Store',
fields: ['key', 'name'],
data: [
{'key': 'osm', 'name': strings.mapOsm},
{'key': 'bingRoad', 'name': strings.mapBingRoad},
{'key': 'bingAerial', 'name': strings.mapBingAerial},
{'key': 'custom', 'name': strings.mapCustom},
]
});
| /*
* Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com)
*
* 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.
*/
Ext.define('Traccar.store.MapTypes', {
extend: 'Ext.data.Store',
fields: ['key', 'name'],
data: [{
key: 'osm',
name: strings.mapOsm
}, {
key: 'bingRoad',
name: strings.mapBingRoad
}, {
key: 'bingAerial',
name: strings.mapBingAerial
}, {
key: 'custom',
name: strings.mapCustom
}]
});
| Fix map types class formatting | Fix map types class formatting
| JavaScript | apache-2.0 | vipien/traccar,joseant/traccar-1,al3x1s/traccar,5of9/traccar,ninioe/traccar,tsmgeek/traccar,ninioe/traccar,jon-stumpf/traccar,renaudallard/traccar,5of9/traccar,tsmgeek/traccar,stalien/traccar_test,duke2906/traccar,jon-stumpf/traccar,orcoliver/traccar,stalien/traccar_test,AnshulJain1985/Roadcast-Tracker,ninioe/traccar,orcoliver/traccar,vipien/traccar,al3x1s/traccar,tananaev/traccar,jssenyange/traccar,jssenyange/traccar,AnshulJain1985/Roadcast-Tracker,renaudallard/traccar,tananaev/traccar,jssenyange/traccar,tananaev/traccar,duke2906/traccar,jon-stumpf/traccar,tsmgeek/traccar,joseant/traccar-1,orcoliver/traccar | ---
+++
@@ -17,10 +17,18 @@
Ext.define('Traccar.store.MapTypes', {
extend: 'Ext.data.Store',
fields: ['key', 'name'],
- data: [
- {'key': 'osm', 'name': strings.mapOsm},
- {'key': 'bingRoad', 'name': strings.mapBingRoad},
- {'key': 'bingAerial', 'name': strings.mapBingAerial},
- {'key': 'custom', 'name': strings.mapCustom},
- ]
+
+ data: [{
+ key: 'osm',
+ name: strings.mapOsm
+ }, {
+ key: 'bingRoad',
+ name: strings.mapBingRoad
+ }, {
+ key: 'bingAerial',
+ name: strings.mapBingAerial
+ }, {
+ key: 'custom',
+ name: strings.mapCustom
+ }]
}); |
4284ec386be6b909362b28aaa2569f93b1a5e696 | t/lib/teamview_check_user.js | t/lib/teamview_check_user.js |
/*
* Exporst function that checks if given emails of users are shown
* on the Teamview page. And if so how they are rendered: as text or link.
*
* It does not check exact emails, just count numbers.
*
* */
'use strict';
var
By = require('selenium-webdriver').By,
expect = require('chai').expect,
open_page_func = require('../lib/open_page'),
bluebird = require("bluebird");
module.exports = bluebird.promisify( function(args, callback){
var
result_callback = callback,
driver = args.driver,
emails = args.emails || [],
is_link = args.is_link || false,
application_host = args.application_host || 'http://localhost:3000/';
if ( ! driver ) {
throw "'driver' was not passed into the teamview_check_user!";
}
return open_page_func({
url : application_host + 'calendar/teamview/',
driver : driver,
})
.then(function(data){
return data.driver
.findElements(By.css( 'tr.teamview-user-list-row > td > ' + (is_link ? 'a' : 'span') ))
.then(function(elements){
expect(elements.length).to.be.equal( emails.length );
return bluebird.resolve(data);
});
})
.then(function(data){
// "export" current driver
result_callback(
null,
{
driver : data.driver,
}
);
});
});
|
/*
* Exporst function that checks if given emails of users are shown
* on the Teamview page. And if so how they are rendered: as text or link.
*
* It does not check exact emails, just count numbers.
*
* */
'use strict';
var
By = require('selenium-webdriver').By,
expect = require('chai').expect,
open_page_func = require('./open_page'),
config = require('./config'),
bluebird = require("bluebird");
module.exports = bluebird.promisify( function(args, callback){
var
result_callback = callback,
driver = args.driver,
emails = args.emails || [],
is_link = args.is_link || false,
application_host = args.application_host || config.get_application_host();
if ( ! driver ) {
throw "'driver' was not passed into the teamview_check_user!";
}
return open_page_func({
url : application_host + 'calendar/teamview/',
driver : driver,
})
.then(function(data){
return data.driver
.findElements(By.css( 'tr.teamview-user-list-row > td > ' + (is_link ? 'a' : 'span') ))
.then(function(elements){
expect(elements.length).to.be.equal( emails.length );
return bluebird.resolve(data);
});
})
.then(function(data){
// "export" current driver
result_callback(
null,
{
driver : data.driver,
}
);
});
});
| Remove hardcoded localhost in one more place. | Remove hardcoded localhost in one more place.
| JavaScript | mit | timeoff-management/application,YulioTech/timeoff,YulioTech/timeoff,timeoff-management/application | ---
+++
@@ -12,7 +12,8 @@
var
By = require('selenium-webdriver').By,
expect = require('chai').expect,
- open_page_func = require('../lib/open_page'),
+ open_page_func = require('./open_page'),
+ config = require('./config'),
bluebird = require("bluebird");
module.exports = bluebird.promisify( function(args, callback){
@@ -22,7 +23,7 @@
driver = args.driver,
emails = args.emails || [],
is_link = args.is_link || false,
- application_host = args.application_host || 'http://localhost:3000/';
+ application_host = args.application_host || config.get_application_host();
if ( ! driver ) {
throw "'driver' was not passed into the teamview_check_user!"; |
7065308e49623e1e54314d9f67fad82600aea00d | tests/unit/models/employee-test.js | tests/unit/models/employee-test.js | import {
moduleForModel,
test
} from 'ember-qunit';
moduleForModel('employee', {
// Specify the other units that are required for this test.
needs: []
});
test('it exists', function(assert) {
var model = this.subject();
// var store = this.store();
assert.ok(!!model);
});
| import DS from 'ember-data';
import Ember from 'ember';
import { test, moduleForModel } from 'ember-qunit';
//import startApp from '../../helpers/start-app';
//var App;
moduleForModel('employee', {
// Specify the other units that are required for this test.
needs: []//,
//setup: function(){
// App = startApp();
//},
//teardown: function(){
// Ember.run(App, 'destroy');
//}
});
test('it exists', function(assert) {
var model = this.subject();
// var store = this.store();
assert.ok(!!model);
});
test('it returns fields', function(assert) {
var model = this.subject({ firstName: "Ivanov", lastName: "Ivan" });
var store = this.store();
assert.ok(model);
assert.ok(model instanceof DS.Model);
assert.equal(model.get('firstName'), "Ivanov");
assert.equal(model.get('lastName'), "Ivan");
// set a relationship
Ember.run(function() {
model.set('reportsTo', store.createRecord('employee', { firstName: "Sidorov", lastName: "Sidor" }));
});
var reportsToEmployee = model.get('reportsTo');
assert.ok(reportsToEmployee);
assert.equal(reportsToEmployee.get('firstName'), "Sidorov");
assert.equal(reportsToEmployee.get('lastName'), "Sidor");
});
| Add simple test on employee relation | Add simple test on employee relation
| JavaScript | mit | Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry | ---
+++
@@ -1,11 +1,20 @@
-import {
- moduleForModel,
- test
-} from 'ember-qunit';
+import DS from 'ember-data';
+import Ember from 'ember';
+import { test, moduleForModel } from 'ember-qunit';
+
+//import startApp from '../../helpers/start-app';
+
+//var App;
moduleForModel('employee', {
// Specify the other units that are required for this test.
- needs: []
+ needs: []//,
+ //setup: function(){
+ // App = startApp();
+ //},
+ //teardown: function(){
+ // Ember.run(App, 'destroy');
+ //}
});
test('it exists', function(assert) {
@@ -13,3 +22,23 @@
// var store = this.store();
assert.ok(!!model);
});
+
+test('it returns fields', function(assert) {
+ var model = this.subject({ firstName: "Ivanov", lastName: "Ivan" });
+ var store = this.store();
+ assert.ok(model);
+ assert.ok(model instanceof DS.Model);
+ assert.equal(model.get('firstName'), "Ivanov");
+ assert.equal(model.get('lastName'), "Ivan");
+
+ // set a relationship
+ Ember.run(function() {
+ model.set('reportsTo', store.createRecord('employee', { firstName: "Sidorov", lastName: "Sidor" }));
+ });
+
+ var reportsToEmployee = model.get('reportsTo');
+ assert.ok(reportsToEmployee);
+ assert.equal(reportsToEmployee.get('firstName'), "Sidorov");
+ assert.equal(reportsToEmployee.get('lastName'), "Sidor");
+});
+ |
1aaa87f7e2fca83ad99cb4ef3e1dbe497e63a899 | js/models/project_specific_mixin.js | js/models/project_specific_mixin.js | "use strict";
var _ = require('underscore')
, Project = require('./project')
/*
* Mixin for models which require a project to be set.
*
* Looks for attribute, collection, and explicit passing in options. Will raise
* an error if no project is found, or if different projects are found.
*/
module.exports = {
constructor: function (attributes, options) {
var candidates, results, slug;
candidates = {
options: options && options.project,
collection: options && options.collection && options.collection.project,
attributes: attributes && attributes.project
}
if (candidates.attributes) {
slug = candidates.attributes.url.match(/[^\/]+/g).slice(-1);
candidates.attributes = new Project({
name: candidates.attributes.name,
slug: slug
});
}
results = _.chain(candidates).filter(function (p) { return p instanceof Project });
if (!results.value().length) {
throw new Error('Must pass a project object, either in options, collection, or attributes.');
}
if (results.map(function (p) { return p.get('slug') }).uniq().value().length > 1) {
throw new Error('Two different projects passed. Not possible.')
}
// Take the first result
this.project = results.first().value();
}
}
| "use strict";
var _ = require('underscore')
, Project = require('./project')
/*
* Mixin for models which require a project to be set.
*
* Looks for attribute, collection, and explicit passing in options. Will raise
* an error if no project is found, or if different projects are found.
*/
module.exports = {
constructor: function (attributes, options) {
var candidates, results, slug;
candidates = {
options: options && options.project,
collection: options && options.collection && options.collection.project,
attributes: attributes && attributes.project
}
if (candidates.attributes) {
slug = candidates.attributes.url.match(/[^\/]+/g).slice(-1);
candidates.attributes = new Project({
name: candidates.attributes.name,
slug: slug
});
}
results = _.chain(candidates).filter(function (p) { return p instanceof Project });
if (!results.value().length) {
throw new Error('Must pass a project object, either in options, collection, or attributes.');
}
if (results.map(function (p) { return p.get('slug') }).flatten().uniq().value().length > 1) {
throw new Error('Two different projects passed.')
}
// Take the first result
this.project = results.first().value();
}
}
| Fix bug in project-specific backbone model mixin | Fix bug in project-specific backbone model mixin
| JavaScript | agpl-3.0 | editorsnotes/editorsnotes-renderer | ---
+++
@@ -34,8 +34,8 @@
}
- if (results.map(function (p) { return p.get('slug') }).uniq().value().length > 1) {
- throw new Error('Two different projects passed. Not possible.')
+ if (results.map(function (p) { return p.get('slug') }).flatten().uniq().value().length > 1) {
+ throw new Error('Two different projects passed.')
}
// Take the first result |
6038661b81a3ae849d854678707c7a0826f85d5b | test/conversion-test.js | test/conversion-test.js | var vows = require('vows'),
assert = require('assert'),
namedColorSamples = require('./samples'),
spaces = [
'rgb',
'hsl',
'hsv'
];
function createTest(bundleFileName) {
var Color = require(bundleFileName),
batch = {};
Object.keys(namedColorSamples).forEach(function (namedColor) {
var sub = batch[namedColor + ': ' + namedColorSamples[namedColor]] = {
topic: Color(namedColorSamples[namedColor])
};
spaces.forEach(function (space) {
sub[space.toUpperCase() + ' hex string comparison'] = function (topic) {
assert.equal(topic[space]().hex(), topic.hex());
};
/*
sub[space.toUpperCase() + ' strict comparison'] = function (topic) {
assert.ok(topic.equals(topic[space]()));
};*/
});
});
return batch;
}
/*
vows.describe('Color').addBatch({
'base, debug': createTest('../one-color-debug'),
'base, minified': createTest('../one-color')
}).export(module);
*/
spaces.push(
'cmyk',
'xyz'/*,
'lab'*/
);
vows.describe('Color-all').addBatch({
//'all, debug': createTest('../one-color-all-debug'),
'all, minified': createTest('../one-color-all')
}).export(module);
| var vows = require('vows'),
assert = require('assert'),
namedColorSamples = require('./samples'),
spaces = [
'rgb',
'hsl',
'hsv'
];
function createTest(bundleFileName) {
var Color = require(bundleFileName),
batch = {};
Object.keys(namedColorSamples).forEach(function (namedColor) {
var sub = batch[namedColor + ': ' + namedColorSamples[namedColor]] = {
topic: Color(namedColorSamples[namedColor])
};
spaces.forEach(function (space) {
sub[space.toUpperCase() + ' hex string comparison'] = function (topic) {
assert.equal(topic[space]().hex(), topic.hex());
};
/*
sub[space.toUpperCase() + ' strict comparison'] = function (topic) {
assert.ok(topic.equals(topic[space]()));
};*/
});
});
return batch;
}
/*
vows.describe('Color').addBatch({
'base, debug': createTest('../one-color-debug'),
'base, minified': createTest('../one-color')
}).export(module);
*/
spaces.push(
'cmyk'/*,
'xyz',
'lab'*/
);
vows.describe('Color-all').addBatch({
//'all, debug': createTest('../one-color-all-debug'),
'all, minified': createTest('../one-color-all')
}).export(module);
| Disable XYZ testing. Unclear if the tests or the implementation is wrong | Disable XYZ testing. Unclear if the tests or the implementation is wrong
| JavaScript | bsd-3-clause | liuhong1happy/one-color,liuhong1happy/one-color | ---
+++
@@ -35,8 +35,8 @@
}).export(module);
*/
spaces.push(
- 'cmyk',
- 'xyz'/*,
+ 'cmyk'/*,
+ 'xyz',
'lab'*/
);
|
4ed0b226782d5b2c8c4ee79112a2735ddf6a8953 | test/specs/createOrUpdate.js | test/specs/createOrUpdate.js | 'use strict';
const assert = require('assert');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const dataSchema = new mongoose.Schema({
'contents': String
});
dataSchema.plugin(require('../../index'));
const dataModel = mongoose.model('data', dataSchema);
describe('createOrUpdate', () => {
let dataId = null;
before(done => {
mongoose.connect('mongodb://localhost/test');
dataModel.find().remove(done);
});
after(done => {
dataModel.find().remove(() => {
mongoose.connection.close(done);
});
});
it('create without document', done => {
dataModel.createOrUpdate({
'_id': dataId
}, {
'contents': 'Lorem ipsum dolor sit amet'
}).then(data => {
dataId = data._id;
done();
}).catch(err => {
console.log(err);
});
});
it('update with existing document', done => {
dataModel.createOrUpdate({
'_id': dataId
}, {
'contents': 'Hello, world!'
}).then(data => {
assert.equal(data._id, dataId);
assert.equal(data.contents, 'Hello, world!');
done();
}).catch(err => {
console.log(err);
});
});
});
| 'use strict';
const assert = require('assert');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const dataSchema = new mongoose.Schema({
'contents': String
});
dataSchema.plugin(require('../../index'));
const dataModel = mongoose.model('data', dataSchema);
describe('createOrUpdate', () => {
let dataId = null;
before(done => {
mongoose.connect('mongodb://localhost/test');
dataModel.find().remove(done);
});
after(done => {
dataModel.find().remove(() => {
mongoose.connection.close(done);
});
});
it('create without document', done => {
dataModel.createOrUpdate({
'_id': dataId
}, {
'contents': 'Lorem ipsum dolor sit amet'
}).then(data => {
dataId = data._id.toString();
done();
}).catch(err => {
console.log(err);
});
});
it('update with existing document', done => {
dataModel.createOrUpdate({
'_id': dataId
}, {
'contents': 'Hello, world!'
}).then(data => {
assert.equal(data._id.toString(), dataId);
assert.equal(data.contents, 'Hello, world!');
done();
}).catch(err => {
console.log(err);
});
});
});
| Test against string version of ID. | Test against string version of ID.
| JavaScript | mit | neogeek/mongoose-create-or-update | ---
+++
@@ -44,7 +44,7 @@
'contents': 'Lorem ipsum dolor sit amet'
}).then(data => {
- dataId = data._id;
+ dataId = data._id.toString();
done();
@@ -64,7 +64,7 @@
'contents': 'Hello, world!'
}).then(data => {
- assert.equal(data._id, dataId);
+ assert.equal(data._id.toString(), dataId);
assert.equal(data.contents, 'Hello, world!');
done(); |
ec27e6fed4b91d6075c702aed69976ec19061eab | test/statici18n_test.js | test/statici18n_test.js | /*global after, before, describe, it*/
'use strict';
var assert = require('assert');
var grunt = require('grunt');
var path = require('path');
var sinon = require('sinon');
var statici18n = require('../tasks/statici18n');
statici18n(grunt);
describe('exists', function() {
after(function() {
grunt.log.warn.restore();
});
it('should nag and filter if the file is missing', function() {
sinon.stub(grunt.log, 'warn');
assert.equal(false, statici18n.exists('some/fake/file.txt'));
sinon.assert.calledOnce(grunt.log.warn);
});
it('returns true with some real file', function() {
var readme = path.join(__dirname, '..', 'README.md');
assert.ok(statici18n.exists(readme));
});
});
| /*global after, before, describe, it*/
'use strict';
var assert = require('assert');
var grunt = require('grunt');
var path = require('path');
var sinon = require('sinon');
var statici18n = require('../tasks/statici18n');
statici18n(grunt);
describe('exists', function() {
after(function() {
grunt.log.warn.restore();
});
it('should nag and filter if the file is missing', function() {
sinon.stub(grunt.log, 'warn');
assert.equal(false, statici18n.exists('some/fake/file.txt'));
sinon.assert.calledOnce(grunt.log.warn);
});
it('returns true with some real file', function() {
var readme = path.join(__dirname, '..', 'README.md');
assert.ok(statici18n.exists(readme));
});
});
describe('static i18n task', function() {
it('should create a file for french', function() {
var i18n = path.join(__dirname, 'fixtures', 'app', 'i18n');
var f = path.join(i18n, 'fr', 'static', 'data.json');
assert.ok(grunt.file.exists(f), 'Not found: ' + f);
});
});
| Test for a french file (fails) | Test for a french file (fails)
| JavaScript | mit | beck/grunt-static-i18n | ---
+++
@@ -22,3 +22,11 @@
assert.ok(statici18n.exists(readme));
});
});
+
+describe('static i18n task', function() {
+ it('should create a file for french', function() {
+ var i18n = path.join(__dirname, 'fixtures', 'app', 'i18n');
+ var f = path.join(i18n, 'fr', 'static', 'data.json');
+ assert.ok(grunt.file.exists(f), 'Not found: ' + f);
+ });
+}); |
631e16f977c65dbd38a532323e10c48dc97b4f50 | rollup.config.umd.js | rollup.config.umd.js | import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import angular from 'rollup-plugin-angular';
import typescript from 'rollup-plugin-typescript';
var sass = require('node-sass');
import {nameLibrary,PATH_SRC,PATH_DIST} from './config-library.js';
export default {
entry: PATH_SRC+nameLibrary+'.ts',
format: 'umd',
moduleName: nameLibrary,
external: [
'@angular/core',
"@angular/platform-browser",
"rxjs/Rx",
"@angular/forms"
],
sourceMap:true,
dest:PATH_DIST+nameLibrary+".umd.js",
plugins: [
angular(
{
preprocessors:{
template:template => template,
style: scss => {
let css;
if(scss){
css = sass.renderSync({ data: scss }).css.toString();
console.log(css);
}else{
css = '';
}
return css;
},
}
}
),
typescript({
typescript:require('typescript')
}),
resolve({
module: true,
main: true
}),
commonjs({
include: 'node_modules/**',
})
],
onwarn: warning => {
const skip_codes = [
'THIS_IS_UNDEFINED',
'MISSING_GLOBAL_NAME'
];
if (skip_codes.indexOf(warning.code) != -1) return;
console.error(warning);
}
}; | import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import angular from 'rollup-plugin-angular';
import typescript from 'rollup-plugin-typescript';
var sass = require('node-sass');
import {nameLibrary,PATH_SRC,PATH_DIST} from './config-library.js';
export default {
input: PATH_SRC+nameLibrary+'.ts',
output: {
name: nameLibrary,
format: 'umd',
file: PATH_DIST+nameLibrary+".umd.js",
sourcemap:true,
},
external: [
'@angular/core',
"@angular/platform-browser",
"rxjs/Rx",
"@angular/forms"
],
plugins: [
angular(
{
preprocessors:{
template:template => template,
style: scss => {
let css;
if(scss){
css = sass.renderSync({ data: scss }).css.toString();
console.log(css);
}else{
css = '';
}
return css;
},
}
}
),
typescript({
typescript:require('typescript')
}),
resolve({
module: true,
main: true
}),
commonjs({
include: 'node_modules/**',
})
],
onwarn: warning => {
const skip_codes = [
'THIS_IS_UNDEFINED',
'MISSING_GLOBAL_NAME'
];
if (skip_codes.indexOf(warning.code) != -1) return;
console.error(warning);
}
};
| Change deprecated config for USM | Change deprecated config for USM | JavaScript | mit | Elecweb/emptytext,Elecweb/emptytext | ---
+++
@@ -5,17 +5,19 @@
var sass = require('node-sass');
import {nameLibrary,PATH_SRC,PATH_DIST} from './config-library.js';
export default {
- entry: PATH_SRC+nameLibrary+'.ts',
- format: 'umd',
- moduleName: nameLibrary,
+ input: PATH_SRC+nameLibrary+'.ts',
+ output: {
+ name: nameLibrary,
+ format: 'umd',
+ file: PATH_DIST+nameLibrary+".umd.js",
+ sourcemap:true,
+ },
external: [
'@angular/core',
"@angular/platform-browser",
"rxjs/Rx",
"@angular/forms"
],
- sourceMap:true,
- dest:PATH_DIST+nameLibrary+".umd.js",
plugins: [
angular(
{ |
d76d4072f34e29310e724da392086932e08ed52b | test/analyzer-result.js | test/analyzer-result.js | import test from 'ava';
import 'babel-core/register';
import AnalyzerResult from '../src/lib/analyzer-result';
test('addMessage adds expected message', t => {
const testMessageType = 'test';
const testMessageText = 'test-message';
const result = new AnalyzerResult();
result.addMessage(testMessageType, testMessageText);
t.is(result.getMessage(testMessageType).text, testMessageText);
// TODO: Add tests for line and column after changing what getMessage returns
});
test('getMessage returns null if message type does not exist', t => {
const result = new AnalyzerResult();
const message = result.getMessage('does-not-exist');
t.is(message, null);
});
test('getMessage returns expected message text if it exists', t => {
const testMessageType = 'test';
const testMessageText = 'test-message';
const result = new AnalyzerResult();
result.addMessage(testMessageType, testMessageText);
const messageText = result.getMessage(testMessageType).text;
t.is(messageText, testMessageText);
});
| import test from 'ava';
import 'babel-core/register';
import AnalyzerResult from '../src/lib/analyzer-result';
test('addMessage adds expected message', t => {
const testMessageType = 'test';
const testMessageText = 'test-message';
const result = new AnalyzerResult();
result.addMessage(testMessageType, testMessageText);
t.is(result.getMessage(testMessageType).text, testMessageText);
});
test('addMessage adds expected line', t => {
const testMessageType = 'test';
const testMessageLine = 3;
const result = new AnalyzerResult();
result.addMessage(testMessageType, 'test-message', testMessageLine);
t.is(result.getMessage(testMessageType).line, testMessageLine);
});
test('addMessage adds expected column', t => {
const testMessageType = 'test';
const testMessageColumn = 7;
const result = new AnalyzerResult();
result.addMessage(testMessageType, 'test-message', 3, testMessageColumn);
t.is(result.getMessage(testMessageType).column, testMessageColumn);
});
test('getMessage returns null if message type does not exist', t => {
const result = new AnalyzerResult();
const message = result.getMessage('does-not-exist');
t.is(message, null);
});
test('getMessage returns expected message text if it exists', t => {
const testMessageType = 'test';
const testMessageText = 'test-message';
const result = new AnalyzerResult();
result.addMessage(testMessageType, testMessageText);
const messageText = result.getMessage(testMessageType).text;
t.is(messageText, testMessageText);
});
| Add tests to implement TODO comment | Add tests to implement TODO comment
| JavaScript | mit | ritterim/markdown-proofing | ---
+++
@@ -11,8 +11,26 @@
result.addMessage(testMessageType, testMessageText);
t.is(result.getMessage(testMessageType).text, testMessageText);
+});
- // TODO: Add tests for line and column after changing what getMessage returns
+test('addMessage adds expected line', t => {
+ const testMessageType = 'test';
+ const testMessageLine = 3;
+ const result = new AnalyzerResult();
+
+ result.addMessage(testMessageType, 'test-message', testMessageLine);
+
+ t.is(result.getMessage(testMessageType).line, testMessageLine);
+});
+
+test('addMessage adds expected column', t => {
+ const testMessageType = 'test';
+ const testMessageColumn = 7;
+ const result = new AnalyzerResult();
+
+ result.addMessage(testMessageType, 'test-message', 3, testMessageColumn);
+
+ t.is(result.getMessage(testMessageType).column, testMessageColumn);
});
test('getMessage returns null if message type does not exist', t => { |
3685283ef4bbff5121146798c16be605ea2a0e2d | packages/presentational-components/src/components/prompt.js | packages/presentational-components/src/components/prompt.js | // @flow
import * as React from "react";
import css from "styled-jsx/css";
const promptStyle = css`
.prompt {
font-family: monospace;
font-size: 12px;
line-height: 22px;
width: var(--prompt-width, 50px);
padding: 9px 0;
text-align: center;
color: var(--theme-cell-prompt-fg, black);
background-color: var(--theme-cell-prompt-bg, #fafafa);
}
`;
// Totally fake component for consistency with indents of the editor area
export function promptText(props: PromptProps) {
if (props.running) {
return "[*]";
}
if (props.queued) {
return "[…]";
}
if (typeof props.counter === "number") {
return `[${props.counter}]`;
}
return "[ ]";
}
type PromptProps = {
counter: number | null,
running: boolean,
queued: boolean
};
export class Prompt extends React.Component<PromptProps, null> {
static defaultProps = {
counter: null,
running: false,
queued: false
};
render() {
return (
<React.Fragment>
<div className="prompt">{promptText(this.props)}</div>
<style jsx>{promptStyle}</style>
</React.Fragment>
);
}
}
export class PromptBuffer extends React.Component<any, null> {
render() {
return (
<React.Fragment>
<div className="prompt" />
<style jsx>{promptStyle}</style>
</React.Fragment>
);
}
}
| // @flow
import * as React from "react";
/**
* Generate what text goes inside the prompt based on the props to the prompt
*/
export function promptText(props: PromptProps): string {
if (props.running) {
return "[*]";
}
if (props.queued) {
return "[…]";
}
if (typeof props.counter === "number") {
return `[${props.counter}]`;
}
return "[ ]";
}
type PromptProps = {
counter: number | null,
running: boolean,
queued: boolean,
blank: boolean
};
export class Prompt extends React.Component<PromptProps, null> {
static defaultProps = {
counter: null,
running: false,
queued: false,
blank: false
};
render() {
return (
<React.Fragment>
<div className="prompt">
{this.props.blank ? null : promptText(this.props)}
</div>
<style jsx>{`
.prompt {
font-family: monospace;
font-size: 12px;
line-height: 22px;
width: var(--prompt-width, 50px);
padding: 9px 0;
text-align: center;
color: var(--theme-cell-prompt-fg, black);
background-color: var(--theme-cell-prompt-bg, #fafafa);
}
`}</style>
</React.Fragment>
);
}
}
export const PromptBuffer = () => <Prompt blank />;
| Make <PromptBuffer> a special case of <Prompt> | Make <PromptBuffer> a special case of <Prompt>
| JavaScript | bsd-3-clause | nteract/nteract,rgbkrk/nteract,nteract/composition,jdfreder/nteract,jdfreder/nteract,nteract/composition,rgbkrk/nteract,rgbkrk/nteract,jdfreder/nteract,rgbkrk/nteract,rgbkrk/nteract,jdfreder/nteract,nteract/nteract,nteract/nteract,nteract/composition,nteract/nteract,nteract/nteract | ---
+++
@@ -1,27 +1,10 @@
// @flow
+import * as React from "react";
-import * as React from "react";
-import css from "styled-jsx/css";
-
-const promptStyle = css`
- .prompt {
- font-family: monospace;
- font-size: 12px;
- line-height: 22px;
-
- width: var(--prompt-width, 50px);
- padding: 9px 0;
-
- text-align: center;
-
- color: var(--theme-cell-prompt-fg, black);
- background-color: var(--theme-cell-prompt-bg, #fafafa);
- }
-`;
-
-// Totally fake component for consistency with indents of the editor area
-
-export function promptText(props: PromptProps) {
+/**
+ * Generate what text goes inside the prompt based on the props to the prompt
+ */
+export function promptText(props: PromptProps): string {
if (props.running) {
return "[*]";
}
@@ -37,33 +20,42 @@
type PromptProps = {
counter: number | null,
running: boolean,
- queued: boolean
+ queued: boolean,
+ blank: boolean
};
export class Prompt extends React.Component<PromptProps, null> {
static defaultProps = {
counter: null,
running: false,
- queued: false
+ queued: false,
+ blank: false
};
render() {
return (
<React.Fragment>
- <div className="prompt">{promptText(this.props)}</div>
- <style jsx>{promptStyle}</style>
+ <div className="prompt">
+ {this.props.blank ? null : promptText(this.props)}
+ </div>
+ <style jsx>{`
+ .prompt {
+ font-family: monospace;
+ font-size: 12px;
+ line-height: 22px;
+
+ width: var(--prompt-width, 50px);
+ padding: 9px 0;
+
+ text-align: center;
+
+ color: var(--theme-cell-prompt-fg, black);
+ background-color: var(--theme-cell-prompt-bg, #fafafa);
+ }
+ `}</style>
</React.Fragment>
);
}
}
-export class PromptBuffer extends React.Component<any, null> {
- render() {
- return (
- <React.Fragment>
- <div className="prompt" />
- <style jsx>{promptStyle}</style>
- </React.Fragment>
- );
- }
-}
+export const PromptBuffer = () => <Prompt blank />; |
8d4782fdefdaa16fc4ae1c24500d910817a8d3d1 | src/models/Feed.js | src/models/Feed.js | const mongoose = require('mongoose')
const middleware = require('./middleware/Feed.js')
const path = require('path')
const fs = require('fs')
const packageVersion = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'))).version
const schema = new mongoose.Schema({
title: {
type: String,
required: true
},
url: {
type: String,
required: true
},
guild: {
type: String,
required: true
},
channel: {
type: String,
required: true
},
webhook: {
id: String,
name: String,
avatar: String
},
split: {
char: String,
prepend: String,
append: String,
maxLength: Number
},
disabled: String,
checkTitles: Boolean,
checkDates: Boolean,
imgPreviews: Boolean,
imgLinksExistence: Boolean,
formatTables: Boolean,
toggleRoleMentions: Boolean,
version: {
type: String,
default: packageVersion
},
addedAt: {
type: Date,
default: Date.now
}
})
schema.pre('findOneAndUpdate', middleware.findOneAndUpdate)
schema.pre('remove', middleware.remove)
schema.pre('save', middleware.save)
exports.schema = schema
exports.model = mongoose.model('Feed', schema)
| const mongoose = require('mongoose')
const middleware = require('./middleware/Feed.js')
const path = require('path')
const fs = require('fs')
const packageVersion = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'))).version
const schema = new mongoose.Schema({
title: {
type: String,
required: true
},
url: {
type: String,
required: true
},
guild: {
type: String,
required: true
},
channel: {
type: String,
required: true
},
webhook: {
id: String,
name: String,
avatar: String
},
split: {
enabled: Boolean,
char: String,
prepend: String,
append: String,
maxLength: Number
},
disabled: String,
checkTitles: Boolean,
checkDates: Boolean,
imgPreviews: Boolean,
imgLinksExistence: Boolean,
formatTables: Boolean,
toggleRoleMentions: Boolean,
version: {
type: String,
default: packageVersion
},
addedAt: {
type: Date,
default: Date.now
}
})
schema.pre('findOneAndUpdate', middleware.findOneAndUpdate)
schema.pre('remove', middleware.remove)
schema.pre('save', middleware.save)
exports.schema = schema
exports.model = mongoose.model('Feed', schema)
| Add enabled key, and if all other keys are empty use default vals | Add enabled key, and if all other keys are empty use default vals
| JavaScript | mit | synzen/Discord.RSS,synzen/Discord.RSS | ---
+++
@@ -27,6 +27,7 @@
avatar: String
},
split: {
+ enabled: Boolean,
char: String,
prepend: String,
append: String, |
1a721d6b1bd32da9f48fb5f3dc0b26eee8bfd095 | test/__snapshots__/show.js | test/__snapshots__/show.js | #!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var chalk = require('chalk')
function show (result) {
Object.keys(result).sort().reverse().forEach(file => {
var test = file.replace(/\.test\.js\.snap$/, '')
result[file].split('exports[`')
.filter(str => str.indexOf('// ') !== 0)
.forEach(str => {
if (str.trim().length === 0) return
var parts = str.replace(/"\s*`;\s*$/, '').split(/`] = `\s*"/)
process.stdout.write(
chalk.gray(`${ test } ${ parts[0].replace(/ 1$/, '') }:\n\n`))
process.stdout.write(parts[1])
})
})
}
fs.readdir(__dirname, (err, list) => {
if (err) throw err
var snaps = list.filter(i => /\.snap$/.test(i))
var result = { }
snaps.forEach(file => {
fs.readFile(path.join(__dirname, file), (err2, content) => {
if (err2) throw err2
result[file] = content.toString()
if (Object.keys(result).length === snaps.length) show(result)
})
})
})
| #!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var chalk = require('chalk')
var filter = process.argv[2]
function show (result) {
Object.keys(result).sort().reverse().forEach(file => {
var test = file.replace(/\.test\.js\.snap$/, '')
result[file].split('exports[`')
.filter(str => str.indexOf('// ') !== 0)
.filter(str => !filter || str.indexOf(filter) !== -1)
.forEach(str => {
if (str.trim().length === 0) return
var parts = str.replace(/"\s*`;\s*$/, '').split(/`] = `\s*"/)
process.stdout.write(
chalk.gray(`${ test } ${ parts[0].replace(/ 1$/, '') }:\n\n`))
process.stdout.write(parts[1])
})
})
}
fs.readdir(__dirname, (err, list) => {
if (err) throw err
var snaps = list.filter(i => /\.snap$/.test(i))
var result = { }
snaps.forEach(file => {
fs.readFile(path.join(__dirname, file), (err2, content) => {
if (err2) throw err2
result[file] = content.toString()
if (Object.keys(result).length === snaps.length) show(result)
})
})
})
| Add filters to snapshot preview | Add filters to snapshot preview
| JavaScript | mit | logux/logux-server | ---
+++
@@ -4,11 +4,14 @@
var path = require('path')
var chalk = require('chalk')
+var filter = process.argv[2]
+
function show (result) {
Object.keys(result).sort().reverse().forEach(file => {
var test = file.replace(/\.test\.js\.snap$/, '')
result[file].split('exports[`')
.filter(str => str.indexOf('// ') !== 0)
+ .filter(str => !filter || str.indexOf(filter) !== -1)
.forEach(str => {
if (str.trim().length === 0) return
var parts = str.replace(/"\s*`;\s*$/, '').split(/`] = `\s*"/) |
bdadb8db1c2ba6c0481fa7fc54d67f762731a3d6 | examples/scribuntoConsole.js | examples/scribuntoConsole.js | var bot = require( 'nodemw' ),
readline = require( 'readline' ),
rl = readline.createInterface( {
input: process.stdin,
output: process.stdout
} ),
client = new Bot( {
protocol: 'https',
server: 'dev.fandom.com',
path: ''
} ),
params = {
action: 'scribunto-console',
title: 'Module:CLI/testcases/title',
clear: true
};
function session( err, content ) {
params.content = content;
rl.on( 'line', cli );
}
function cli( input ) {
params.question = input;
client.api.call( params, call );
}
function call( err, info, next, data ) {
if ( err ) {
console.error( err );
} else if ( data.type === 'error' ) {
console.error( data.message );
} else {
console.log( data.print );
}
}
client.getArticle( params.title, session );
| var Bot = require( 'nodemw' ),
readline = require( 'readline' ),
rl = readline.createInterface( {
input: process.stdin,
output: process.stdout
} ),
client = new Bot( {
protocol: 'https',
server: 'dev.fandom.com',
path: ''
} ),
params = {
action: 'scribunto-console',
title: 'Module:CLI/testcases/title',
clear: true
};
function session( err, content ) {
params.content = content;
rl.on( 'line', cli );
}
function cli( input ) {
params.question = input;
client.api.call( params, call );
}
function call( err, info, next, data ) {
if ( err ) {
console.error( err );
} else if ( data.type === 'error' ) {
console.error( data.message );
} else {
console.log( data.print );
}
}
client.getArticle( params.title, session );
| Fix unused and undefined vars | Fix unused and undefined vars | JavaScript | bsd-2-clause | macbre/nodemw | ---
+++
@@ -1,4 +1,4 @@
-var bot = require( 'nodemw' ),
+var Bot = require( 'nodemw' ),
readline = require( 'readline' ),
rl = readline.createInterface( {
input: process.stdin, |
a95a786d9c0d5b643f2e6b1c51e55853d1750c74 | gulp/config.js | gulp/config.js | module.exports = {
// Autoprefixer
autoprefixer: {
// https://github.com/postcss/autoprefixer#browsers
browsers: [
'Explorer >= 10',
'ExplorerMobile >= 10',
'Firefox >= 30',
'Chrome >= 34',
'Safari >= 7',
'Opera >= 23',
'iOS >= 7',
'Android >= 4.4',
'BlackBerry >= 10'
]
},
// BrowserSync
browserSync: {
browser: 'default', // or ["google chrome", "firefox"]
https: false, // Enable https for localhost development.
notify: false, // The small pop-over notifications in the browser.
port: 9000
},
// GitHub Pages
ghPages: {
branch: 'gh-pages',
domain: 'polymer-starter-kit.startpolymer.org', // change it!
origin: 'origin2' // default is 'origin'
},
// PageSpeed Insights
// Please feel free to use the `nokey` option to try out PageSpeed
// Insights as part of your build process. For more frequent use,
// we recommend registering for your own API key. For more info:
// https://developers.google.com/speed/docs/insights/v1/getting_started
pageSpeed: {
key: '', // need uncomment in task
nokey: true,
site: 'http://polymer-starter-kit.startpolymer.org', // change it!
strategy: 'mobile' // or desktop
}
};
| module.exports = {
// Autoprefixer
autoprefixer: {
// https://github.com/postcss/autoprefixer#browsers
browsers: [
'Explorer >= 10',
'ExplorerMobile >= 10',
'Firefox >= 30',
'Chrome >= 34',
'Safari >= 7',
'Opera >= 23',
'iOS >= 7',
'Android >= 4.4',
'BlackBerry >= 10'
]
},
// BrowserSync
browserSync: {
browser: 'default', // or ["google chrome", "firefox"]
https: false, // Enable https for localhost development.
notify: false, // The small pop-over notifications in the browser.
port: 9000
},
// GitHub Pages
ghPages: {
branch: 'gh-pages',
domain: 'polymer-starter-kit.startpolymer.org', // change it!
origin: 'origin'
},
// PageSpeed Insights
// Please feel free to use the `nokey` option to try out PageSpeed
// Insights as part of your build process. For more frequent use,
// we recommend registering for your own API key. For more info:
// https://developers.google.com/speed/docs/insights/v1/getting_started
pageSpeed: {
key: '', // need uncomment in task
nokey: true,
site: 'http://polymer-starter-kit.startpolymer.org', // change it!
strategy: 'mobile' // or desktop
}
};
| Revert remote origin to 'origin' for deploy github pages | Revert remote origin to 'origin' for deploy github pages
| JavaScript | mit | osr-megha/polymer-starter-kit,StartPolymer/polymer-starter-kit-old,StartPolymer/polymer-static-app,StartPolymer/polymer-starter-kit-old,osr-megha/polymer-starter-kit,StartPolymer/polymer-static-app | ---
+++
@@ -25,7 +25,7 @@
ghPages: {
branch: 'gh-pages',
domain: 'polymer-starter-kit.startpolymer.org', // change it!
- origin: 'origin2' // default is 'origin'
+ origin: 'origin'
},
// PageSpeed Insights
// Please feel free to use the `nokey` option to try out PageSpeed |
eb78a8ff55ffb43880fbba8ff92254c3ddf630c7 | routes/trackOrder.js | routes/trackOrder.js | const utils = require('../lib/utils')
const challenges = require('../data/datacache').challenges
const db = require('../data/mongodb')
module.exports = function trackOrder () {
return (req, res) => {
const id = insecurity.sanitizeProcessExit(utils.trunc(decodeURIComponent(req.params.id), 40))
if (utils.notSolved(challenges.reflectedXssChallenge) && utils.contains(id, '<iframe src="javascript:alert(`xss`)">')) {
utils.solve(challenges.reflectedXssChallenge)
}
db.orders.find({ $where: "this.orderId === '" + id + "'" }).then(order => {
const result = utils.queryResultToJson(order)
if (utils.notSolved(challenges.noSqlOrdersChallenge) && result.data.length > 1) {
utils.solve(challenges.noSqlOrdersChallenge)
}
if (result.data[0] === undefined) {
result.data[0] = { orderId: id }
}
res.json(result)
}, () => {
res.status(400).json({ error: 'Wrong Param' })
})
}
}
| const utils = require('../lib/utils')
const insecurity = require('../lib/insecurity')
const challenges = require('../data/datacache').challenges
const db = require('../data/mongodb')
module.exports = function trackOrder () {
return (req, res) => {
const id = insecurity.sanitizeProcessExit(utils.trunc(decodeURIComponent(req.params.id), 40))
if (utils.notSolved(challenges.reflectedXssChallenge) && utils.contains(id, '<iframe src="javascript:alert(`xss`)">')) {
utils.solve(challenges.reflectedXssChallenge)
}
db.orders.find({ $where: "this.orderId === '" + id + "'" }).then(order => {
const result = utils.queryResultToJson(order)
if (utils.notSolved(challenges.noSqlOrdersChallenge) && result.data.length > 1) {
utils.solve(challenges.noSqlOrdersChallenge)
}
if (result.data[0] === undefined) {
result.data[0] = { orderId: id }
}
res.json(result)
}, () => {
res.status(400).json({ error: 'Wrong Param' })
})
}
}
| Add missing import of insecurity lib | Add missing import of insecurity lib | JavaScript | mit | bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop | ---
+++
@@ -1,4 +1,5 @@
const utils = require('../lib/utils')
+const insecurity = require('../lib/insecurity')
const challenges = require('../data/datacache').challenges
const db = require('../data/mongodb')
|
d688400e75fd5282cc3a5a7ef738711a13617e1b | routes/views/main.js | routes/views/main.js | var keystone = require('keystone'),
_ = require('underscore');
// Load models to allow fetching of slideshow data
var Slideshow = keystone.list('Slideshow'),
SlideshowItems = keystone.list('Slideshow Item');
exports = module.exports = function(req, res) {
'use strict';
var view = new keystone.View(req, res),
locals = res.locals;
Slideshow.model.find()
.where('title', 'Main Page Slideshow')
.exec()
.then(function (slideshow) {
var slideshowId = slideshow[0].get('_id');
SlideshowItems.model.find()
.where('parent', slideshowId)
.exec()
.then(function (slides) {
locals.slides = _.sortBy(slides, function(slide) { return +slide.order; });
console.log(locals.slides);
view.render('main');
});
});//.then(function() {
// view.render('main');
// });
// TODO: Get the featured models
}; | var keystone = require('keystone'),
_ = require('underscore');
// Load models to allow fetching of slideshow data
var Slideshow = keystone.list('Slideshow'),
SlideshowItems = keystone.list('Slideshow Item');
exports = module.exports = function(req, res) {
'use strict';
var view = new keystone.View(req, res),
locals = res.locals;
Slideshow.model.find()
.where('title', 'Main Page Slideshow')
.exec()
.then(function (slideshow) {
var slideshowId = slideshow[0].get('_id');
SlideshowItems.model.find()
.where('parent', slideshowId)
.exec()
.then(function (slides) {
locals.slides = _.sortBy(slides, function(slide) { return +slide.order; });
view.render('main');
});
});//.then(function() {
// view.render('main');
// });
// TODO: Get the featured models
}; | Remove logging messages cluttering the output log. | Remove logging messages cluttering the output log.
| JavaScript | mit | autoboxer/MARE,autoboxer/MARE | ---
+++
@@ -24,7 +24,6 @@
.then(function (slides) {
locals.slides = _.sortBy(slides, function(slide) { return +slide.order; });
- console.log(locals.slides);
view.render('main');
}); |
b4cacf5ed3e4bd98a693cddb2ba48674add19cb6 | website/static/website/js/app.js | website/static/website/js/app.js | import React from "react";
import { Chance }from "chance";
import WriteMessage from "./components/WriteMessage";
import Messages from "./components/Messages";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { user: chance.name(), messages: [] }
}
componentDidMount() {
var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
this.chatsock = new ReconnectingWebSocket(ws_scheme + '://' + window.location.host + "/chat" + window.location.pathname);
this.chatsock.onmessage = (message) => {
console.log(message);
let messages = this.state.messages.slice();
messages.push(JSON.parse(message.data));
this.setState({messages: messages})
};
}
sendMessage(msg) {
const payload = {
handle: this.state.user,
message: msg
};
this.chatsock.send(JSON.stringify(payload));
}
render() {
return (
<div>
<h1>M O O N Y</h1>
<Messages
messages={this.state.messages}
/>
<WriteMessage
sendMessage={this.sendMessage.bind(this)}
/>
</div>
)
}
} | import React from "react";
import { Chance }from "chance";
import WriteMessage from "./components/WriteMessage";
import Messages from "./components/Messages";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { user: chance.name(), messages: [], connected: false }
}
componentDidMount() {
var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
this.chatsock = new ReconnectingWebSocket(ws_scheme + '://' + window.location.host + "/chat" + window.location.pathname);
this.chatsock.onopen = event => {
this.setState({
connected: true
})
console.log(this.chatsock);
};
this.chatsock.onclose = event => {
this.setState({
connected: false
})
};
this.chatsock.onmessage = (message) => {
console.log(message);
let messages = this.state.messages.slice();
messages.push(JSON.parse(message.data));
this.setState({messages: messages})
};
}
sendMessage(msg) {
const payload = {
handle: this.state.user,
message: msg
};
this.chatsock.send(JSON.stringify(payload));
}
render() {
return (
<div>
<h1>M O O N Y (<span>{this.state.connected ? 'connected' : 'disconnected'}</span>)</h1>
<Messages
messages={this.state.messages}
/>
<WriteMessage
sendMessage={this.sendMessage.bind(this)}
/>
</div>
)
}
} | Put a connected visual help | Put a connected visual help
| JavaScript | mit | Frky/moon,Frky/moon,Frky/moon,Frky/moon,Frky/moon | ---
+++
@@ -7,12 +7,25 @@
export default class App extends React.Component {
constructor(props) {
super(props);
- this.state = { user: chance.name(), messages: [] }
+ this.state = { user: chance.name(), messages: [], connected: false }
}
componentDidMount() {
var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
this.chatsock = new ReconnectingWebSocket(ws_scheme + '://' + window.location.host + "/chat" + window.location.pathname);
+
+ this.chatsock.onopen = event => {
+ this.setState({
+ connected: true
+ })
+ console.log(this.chatsock);
+ };
+
+ this.chatsock.onclose = event => {
+ this.setState({
+ connected: false
+ })
+ };
this.chatsock.onmessage = (message) => {
console.log(message);
@@ -33,7 +46,7 @@
render() {
return (
<div>
- <h1>M O O N Y</h1>
+ <h1>M O O N Y (<span>{this.state.connected ? 'connected' : 'disconnected'}</span>)</h1>
<Messages
messages={this.state.messages}
/> |
a305be411f880fa1fdf5c931f562e605c2a208d3 | app/components/Button/index.js | app/components/Button/index.js | import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import './Button.scss';
export default class Button extends Component {
static propTypes = {
onClick: PropTypes.func,
type: PropTypes.oneOf(['button', 'submit', 'reset']),
kind: PropTypes.oneOf(['yes', 'no', 'subtle']),
disabled: PropTypes.bool,
children: PropTypes.oneOfType([PropTypes.object, PropTypes.string]).isRequired,
small: PropTypes.bool,
big: PropTypes.bool,
}
static defaultProps = {
onClick: () => {},
type: 'button',
kind: null,
disabled: false,
small: false,
big: false,
}
render() {
const { kind, type, onClick, disabled, children, small, big } = this.props;
const classes = classnames(
'btn',
{ [`btn--${kind}`]: kind },
{ 'btn--small': small },
{ 'btn--big': big },
);
return (
<button
className={classes}
type={type}
onClick={onClick}
disabled={disabled}
>
{children}
</button>
);
}
}
| import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import './Button.scss';
export default class Button extends Component {
static propTypes = {
onClick: PropTypes.func,
type: PropTypes.oneOf(['button', 'submit', 'reset']),
kind: PropTypes.oneOf(['yes', 'no', 'subtle']),
disabled: PropTypes.bool,
children: PropTypes.oneOfType([PropTypes.object, PropTypes.string]).isRequired,
small: PropTypes.bool,
big: PropTypes.bool,
}
static defaultProps = {
onClick: () => {},
type: 'button',
kind: null,
disabled: false,
small: false,
big: false,
}
render() {
const { kind, type, onClick, disabled, children, small, big } = this.props;
const classes = classnames(
'btn',
{ [`btn--${kind}`]: kind },
{ 'btn--small': small },
{ 'btn--big': big },
);
if (type === 'submit') {
return <input type="submit" disabled={disabled} className={classes} value={children} />;
}
return (
<button
className={classes}
type={type}
onClick={onClick}
disabled={disabled}
>
{children}
</button>
);
}
}
| Improve semantics of submit button | :page_facing_up: Improve semantics of submit button
| JavaScript | mit | JasonEtco/flintcms,JasonEtco/flintcms | ---
+++
@@ -31,6 +31,10 @@
{ 'btn--big': big },
);
+ if (type === 'submit') {
+ return <input type="submit" disabled={disabled} className={classes} value={children} />;
+ }
+
return (
<button
className={classes} |
0b1eecf180c79d6196d796ba786a46b1158abbbc | scripts/objects/2-cleaver.js | scripts/objects/2-cleaver.js | exports.listeners = {
wield: function (l10n) {
return function (location, player, players) {
player.say('You ready the weighty cleaver.');
player.combat.addToHitMod({
name: 'cleaver ' + this.getUuid(),
effect: toHit => toHit + 1
});
}
},
remove: function (l10n) {
return function (player) {
player.say('You place the bulky cleaver in your pack.');
player.combat.deleteAllMods('cleaver' + this.getUuid());
}
},
hit: function (l10n) {
return function (player) {
player.say('<bold>The blade of your cleaver <red>does its job.</red></bold>');
player.combat.addDamageMod({
name: 'cleaver' + this.getUuid(),
effect: damage => damage + .5
});
}
}
};
| exports.listeners = {
wield: function (l10n) {
return function (location, player, players) {
player.say('You ready the weighty cleaver.');
player.combat.addToHitMod({
name: 'cleaver ' + this.getUuid(),
effect: toHit => toHit + 1
});
player.combat.addToDodgeMod({
name: 'cleaver ' + this.getUuid(),
effect: dodge => dodge - 1
});
}
},
remove: function (l10n) {
return function (player) {
player.say('You place the bulky cleaver in your pack.');
player.combat.deleteAllMods('cleaver' + this.getUuid());
}
},
hit: function (l10n) {
return function (player) {
player.say('<bold>The blade of your cleaver <red>does its job.</red></bold>');
player.combat.addDamageMod({
name: 'cleaver' + this.getUuid(),
effect: damage => damage + .5
});
}
},
parry: function(l10n) {
return function (player) {
player.say('<bold><white>The blade of your cleaver halts their attack.</white></bold>');
player.combat.addDamageMod({
name: 'cleaver' + this.getUuid(),
effect: damage => damage - .5
});
}
}
};
| Add balancing for cleaver scripts. | Add balancing for cleaver scripts.
| JavaScript | mit | seanohue/ranviermud,seanohue/ranviermud,shawncplus/ranviermud | ---
+++
@@ -6,6 +6,10 @@
player.combat.addToHitMod({
name: 'cleaver ' + this.getUuid(),
effect: toHit => toHit + 1
+ });
+ player.combat.addToDodgeMod({
+ name: 'cleaver ' + this.getUuid(),
+ effect: dodge => dodge - 1
});
}
},
@@ -25,5 +29,15 @@
effect: damage => damage + .5
});
}
- }
+ },
+
+ parry: function(l10n) {
+ return function (player) {
+ player.say('<bold><white>The blade of your cleaver halts their attack.</white></bold>');
+ player.combat.addDamageMod({
+ name: 'cleaver' + this.getUuid(),
+ effect: damage => damage - .5
+ });
+ }
+ }
}; |
e15b144af678fbbfabe6fac280d869d02bcfb2ce | app/reducers/studentProfile.js | app/reducers/studentProfile.js | const initialState = {
profile: { data: null },
name: { data: null },
image: { data: null },
barcode: { data: null }
}
function studentProfileReducer(state = initialState, action) {
const newState = { ...state }
switch (action.type) {
case 'SET_STUDENT_PROFILE':
newState.profile.data = action.profile
return newState
case 'SET_STUDENT_NAME':
newState.name.data = action.name
return newState
case 'SET_STUDENT_PHOTO':
newState.image.data = action.image
return newState
case 'SET_STUDENT_BARCODE':
newState.barcode.data = action.barcode
return newState
case 'CLEAR_STUDENT_PROFILE_DATA':
return initialState
default:
return state
}
}
module.exports = studentProfileReducer
| const initialState = {
profile: { data: null },
name: { data: null },
image: { data: null },
barcode: { data: null }
}
function studentProfileReducer(state = initialState, action) {
const newState = { ...state }
switch (action.type) {
case 'SET_STUDENT_PROFILE':
newState.profile.data = action.profile
return newState
case 'SET_STUDENT_NAME':
newState.name.data = action.name
return newState
case 'SET_STUDENT_PHOTO':
newState.image.data = action.image
return newState
case 'SET_STUDENT_BARCODE':
newState.barcode.data = action.barcode
return newState
case 'CLEAR_STUDENT_PROFILE_DATA':
return {
profile: { data: null },
name: { data: null },
image: { data: null },
barcode: { data: null }
}
default:
return state
}
}
module.exports = studentProfileReducer
| Fix issue where data was not being cleared upon logout | Fix issue where data was not being cleared upon logout
| JavaScript | mit | UCSD/campus-mobile,UCSD/campus-mobile,UCSD/now-mobile,UCSD/campus-mobile,UCSD/campus-mobile,UCSD/now-mobile,UCSD/campus-mobile,UCSD/now-mobile,UCSD/campus-mobile | ---
+++
@@ -21,7 +21,12 @@
newState.barcode.data = action.barcode
return newState
case 'CLEAR_STUDENT_PROFILE_DATA':
- return initialState
+ return {
+ profile: { data: null },
+ name: { data: null },
+ image: { data: null },
+ barcode: { data: null }
+ }
default:
return state
} |
4109657238be43d0c2e8bc9615d5429e6b69a1b7 | test/tweet-card-content.js | test/tweet-card-content.js | import test from 'ava';
import TweetCardContent from '../lib/tweet-card-content';
const META_SECTION = "Tweet should be about";
test("Test static exports", (t) => {
t.true("TWEET_CONTENT" in TweetCardContent);
t.true("RETWEET" in TweetCardContent);
t.true("SCHEDULED" in TweetCardContent);
});
test("Create card", (t) => {
const meta = "test";
const card = TweetCardContent.createCard(meta);
t.true(card instanceof TweetCardContent);
t.is(meta, card.getSection(META_SECTION));
t.false(card.isRetweet);
t.true(card.hasSection(TweetCardContent.TWEET_CONTENT));
t.false(card.isValid);
});
test("Retweet", (t) => {
const meta = "test";
const card = TweetCardContent.createCard(meta, true);
t.true(card instanceof TweetCardContent);
t.is(meta, card.getSection(META_SECTION));
t.true(card.isRetweet);
t.true(card.hasSection(TweetCardContent.RETWEET));
t.false(card.isValid;
});
test.todo("Test setSection");
test.todo("Test tweet length");
test.todo("Test with valid RT url");
test.todo("Test due date/SCHEDULED");
test.todo("Test error messages");
| import test from 'ava';
import TweetCardContent from '../lib/tweet-card-content';
const META_SECTION = "Tweet should be about";
test("Test static exports", (t) => {
t.true("TWEET_CONTENT" in TweetCardContent);
t.true("RETWEET" in TweetCardContent);
t.true("SCHEDULED" in TweetCardContent);
});
test("Create card", (t) => {
const meta = "test";
const card = TweetCardContent.createCard(meta);
t.true(card instanceof TweetCardContent);
t.is(meta, card.getSection(META_SECTION));
t.false(card.isRetweet);
t.true(card.hasSection(TweetCardContent.TWEET_CONTENT));
t.false(card.isValid);
});
test("Retweet", (t) => {
const meta = "test";
const card = TweetCardContent.createCard(meta, true);
t.true(card instanceof TweetCardContent);
t.is(meta, card.getSection(META_SECTION));
t.true(card.isRetweet);
t.true(card.hasSection(TweetCardContent.RETWEET));
t.false(card.isValid);
});
test.todo("Test setSection");
test.todo("Test tweet length");
test.todo("Test with valid RT url");
test.todo("Test due date/SCHEDULED");
test.todo("Test error messages");
| Add closing ) that got removed by acident2 | Add closing ) that got removed by acident2
| JavaScript | mpl-2.0 | mozillach/gh-projects-content-queue | ---
+++
@@ -28,7 +28,7 @@
t.is(meta, card.getSection(META_SECTION));
t.true(card.isRetweet);
t.true(card.hasSection(TweetCardContent.RETWEET));
- t.false(card.isValid;
+ t.false(card.isValid);
});
test.todo("Test setSection"); |
f672c1cc4b3648303f6a770ccbc9f24be423d8bd | app/src/containers/timeline.js | app/src/containers/timeline.js | import { connect } from 'react-redux';
import Timeline from '../components/map/timeline';
import { updateFilters } from '../actions/filters';
const mapStateToProps = state => {
return {
filters: state.filters
};
};
const mapDispatchToProps = dispatch => {
return {
updateFilters: filters => {
// console.log('t:mapDispatchToProps', filters)
dispatch(updateFilters(filters));
}
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Timeline);
| import { connect } from 'react-redux';
import Timeline from '../components/map/Timeline';
import { updateFilters } from '../actions/filters';
const mapStateToProps = state => {
return {
filters: state.filters
};
};
const mapDispatchToProps = dispatch => {
return {
updateFilters: filters => {
// console.log('t:mapDispatchToProps', filters)
dispatch(updateFilters(filters));
}
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Timeline);
| Fix casing in file import | Fix casing in file import
| JavaScript | mit | Vizzuality/GlobalFishingWatch,Vizzuality/GlobalFishingWatch,Vizzuality/GlobalFishingWatch | ---
+++
@@ -1,5 +1,5 @@
import { connect } from 'react-redux';
-import Timeline from '../components/map/timeline';
+import Timeline from '../components/map/Timeline';
import { updateFilters } from '../actions/filters';
const mapStateToProps = state => { |
0200a9c8123896848792b7f3150fa7a56aa07470 | app/support/DbAdapter/utils.js | app/support/DbAdapter/utils.js | import _ from 'lodash';
export const unexistedUID = '00000000-0000-0000-C000-000000000046';
export function initObject(classDef, attrs, id, params) {
return new classDef({ ...attrs, id, ...params });
}
export function prepareModelPayload(payload, namesMapping, valuesMapping) {
const result = {};
const keys = _.intersection(Object.keys(payload), Object.keys(namesMapping));
for (const key of keys) {
const mappedKey = namesMapping[key];
const mappedVal = valuesMapping[key] ? valuesMapping[key](payload[key]) : payload[key];
result[mappedKey] = mappedVal;
}
return result;
}
| import _ from 'lodash';
import pgFormat from 'pg-format';
import { List } from '../open-lists';
export const unexistedUID = '00000000-0000-0000-C000-000000000046';
export function initObject(classDef, attrs, id, params) {
return new classDef({ ...attrs, id, ...params });
}
export function prepareModelPayload(payload, namesMapping, valuesMapping) {
const result = {};
const keys = _.intersection(Object.keys(payload), Object.keys(namesMapping));
for (const key of keys) {
const mappedKey = namesMapping[key];
const mappedVal = valuesMapping[key] ? valuesMapping[key](payload[key]) : payload[key];
result[mappedKey] = mappedVal;
}
return result;
}
// These helpers allow to use the IN operator with the empty list of values.
// 'IN <empty list>' always returns 'false' and 'NOT IN <empty list>' always returns 'true'.
// We don't escape 'field' here because pgFormat escaping doesn't work properly with dot-joined
// identifiers (as in 'table.field').
// export const sqlIn = (field, list) => list.length === 0 ? 'false' : pgFormat(`${field} in (%L)`, list);
// export const sqlNotIn = (field, list) => list.length === 0 ? 'true' : pgFormat(`${field} not in (%L)`, list);
export function sqlIn(field, list) {
list = List.from(list);
if (list.isEmpty()) {
return 'false';
} else if (list.isEverything()) {
return 'true';
}
return pgFormat(`${field} ${list.inclusive ? 'in' : 'not in'} (%L)`, list.items);
}
export function sqlNotIn(field, list) {
return sqlIn(field, List.difference(List.everything(), list));
}
export function sqlIntarrayIn(field, list) {
list = new List(list);
if (list.isEmpty()) {
return 'false';
} else if (list.isEverything()) {
return 'true';
}
return pgFormat(`(${list.inclusive ? '' : 'not '}${field} && %L)`, `{${list.items.join(',')}}`);
}
| Add helpers functions to generate SQL for 'field [NOT] IN somelist' | Add helpers functions to generate SQL for 'field [NOT] IN somelist'
| JavaScript | mit | FreeFeed/freefeed-server,FreeFeed/freefeed-server | ---
+++
@@ -1,4 +1,7 @@
import _ from 'lodash';
+import pgFormat from 'pg-format';
+
+import { List } from '../open-lists';
export const unexistedUID = '00000000-0000-0000-C000-000000000046';
@@ -19,3 +22,39 @@
return result;
}
+
+// These helpers allow to use the IN operator with the empty list of values.
+// 'IN <empty list>' always returns 'false' and 'NOT IN <empty list>' always returns 'true'.
+// We don't escape 'field' here because pgFormat escaping doesn't work properly with dot-joined
+// identifiers (as in 'table.field').
+
+// export const sqlIn = (field, list) => list.length === 0 ? 'false' : pgFormat(`${field} in (%L)`, list);
+// export const sqlNotIn = (field, list) => list.length === 0 ? 'true' : pgFormat(`${field} not in (%L)`, list);
+
+export function sqlIn(field, list) {
+ list = List.from(list);
+
+ if (list.isEmpty()) {
+ return 'false';
+ } else if (list.isEverything()) {
+ return 'true';
+ }
+
+ return pgFormat(`${field} ${list.inclusive ? 'in' : 'not in'} (%L)`, list.items);
+}
+
+export function sqlNotIn(field, list) {
+ return sqlIn(field, List.difference(List.everything(), list));
+}
+
+export function sqlIntarrayIn(field, list) {
+ list = new List(list);
+
+ if (list.isEmpty()) {
+ return 'false';
+ } else if (list.isEverything()) {
+ return 'true';
+ }
+
+ return pgFormat(`(${list.inclusive ? '' : 'not '}${field} && %L)`, `{${list.items.join(',')}}`);
+} |
e44c9d381503575c441d0de476690e9ba94a6cca | src/api/lib/adminRequired.js | src/api/lib/adminRequired.js | export default function authRequired(req, res, next) {
if (req.user.isAdmin) {
next();
} else {
res.status(403);
res.json({
id: 'AUTH_FORBIDDEN',
message: 'You need admin privilege to run this command.'
});
}
}
| export default function adminRequired(req, res, next) {
if (req.user && req.user.isAdmin) {
next();
} else {
res.status(403);
res.json({
id: 'AUTH_FORBIDDEN',
message: 'You need admin privilege to run this command.'
});
}
}
| Fix admin checking throwing error if not logged in | Fix admin checking throwing error if not logged in
| JavaScript | mit | yoo2001818/shellscripts | ---
+++
@@ -1,5 +1,5 @@
-export default function authRequired(req, res, next) {
- if (req.user.isAdmin) {
+export default function adminRequired(req, res, next) {
+ if (req.user && req.user.isAdmin) {
next();
} else {
res.status(403); |
e762c50fba4e25c6cff3152ab499c6ff310c95ee | src/components/UserVideos.js | src/components/UserVideos.js | import React from 'react'
import {connect} from 'react-redux'
import {Link} from 'react-router-dom'
import {compose} from 'recompose'
import {updateUserVideos} from '../actions/userVideos'
import {withDatabaseSubscribe} from './hocs'
import VideoPreviewsList from './VideoPreviewsList'
const mapStateToProps = ({userVideos}) => ({
userVideos,
})
const enhanceSubs = compose(
connect(mapStateToProps),
withDatabaseSubscribe(
'value',
(props) => (`user-videos/${props.userId}`),
(props) => (snapshot) => {
props.dispatch(updateUserVideos({
userId: props.userId,
userVideosSnapshot: snapshot.val(),
}))
}
),
)
const UserVideos = ({baseUrl, isEditable, userId, userVideos}) => (
<div>
{isEditable ?
<Link to='/videos/new'>New</Link> : ''
}
<VideoPreviewsList videoIds={userVideos[userId] ? Object.keys(userVideos[userId]) : []}/>
</div>
)
export default enhanceSubs(UserVideos)
| import React from 'react'
import {connect} from 'react-redux'
import {compose, withHandlers, withProps} from 'recompose'
import {updateUserVideos} from '../actions/userVideos'
import {createVideo, VideoOwnerTypes} from '../actions/videos'
import {withDatabaseSubscribe} from './hocs'
import VideoPreviewsList from './VideoPreviewsList'
const mapStateToProps = ({userVideos}) => ({
userVideos,
})
const enhanceSubs = compose(
connect(mapStateToProps),
withProps(({match}) => ({
userId: match.params.userId
})),
withHandlers(
{
onNewVideoSubmit: props => event => {
event.preventDefault()
props.dispatch(createVideo(
{
videoOwnerType: VideoOwnerTypes.USER_VIDEO,
ownerId: props.userId
})
)
}
}
),
withDatabaseSubscribe(
'value',
(props) => (`user-videos/${props.userId}`),
(props) => (snapshot) => {
props.dispatch(updateUserVideos(
{
userId: props.userId,
userVideosSnapshot: snapshot.val(),
}))
}
),
)
const UserVideos = ({baseUrl, isEditable, onNewVideoSubmit, userId, userVideos}) => (
<div>
<form onSubmit={onNewVideoSubmit}>
<input
type='submit'
value='submit'
/>
</form>
<VideoPreviewsList videoIds={userVideos[userId] ? Object.keys(userVideos[userId]) : []}/>
</div>
)
export default enhanceSubs(UserVideos)
| Make a user create video button | Make a user create video button
| JavaScript | mit | mg4tv/mg4tv-web,mg4tv/mg4tv-web | ---
+++
@@ -1,11 +1,12 @@
import React from 'react'
import {connect} from 'react-redux'
-import {Link} from 'react-router-dom'
-import {compose} from 'recompose'
+import {compose, withHandlers, withProps} from 'recompose'
import {updateUserVideos} from '../actions/userVideos'
+import {createVideo, VideoOwnerTypes} from '../actions/videos'
import {withDatabaseSubscribe} from './hocs'
import VideoPreviewsList from './VideoPreviewsList'
+
const mapStateToProps = ({userVideos}) => ({
userVideos,
@@ -13,23 +14,43 @@
const enhanceSubs = compose(
connect(mapStateToProps),
+ withProps(({match}) => ({
+ userId: match.params.userId
+ })),
+ withHandlers(
+ {
+ onNewVideoSubmit: props => event => {
+ event.preventDefault()
+ props.dispatch(createVideo(
+ {
+ videoOwnerType: VideoOwnerTypes.USER_VIDEO,
+ ownerId: props.userId
+ })
+ )
+ }
+ }
+ ),
withDatabaseSubscribe(
'value',
(props) => (`user-videos/${props.userId}`),
(props) => (snapshot) => {
- props.dispatch(updateUserVideos({
- userId: props.userId,
- userVideosSnapshot: snapshot.val(),
- }))
+ props.dispatch(updateUserVideos(
+ {
+ userId: props.userId,
+ userVideosSnapshot: snapshot.val(),
+ }))
}
),
)
-const UserVideos = ({baseUrl, isEditable, userId, userVideos}) => (
+const UserVideos = ({baseUrl, isEditable, onNewVideoSubmit, userId, userVideos}) => (
<div>
- {isEditable ?
- <Link to='/videos/new'>New</Link> : ''
- }
+ <form onSubmit={onNewVideoSubmit}>
+ <input
+ type='submit'
+ value='submit'
+ />
+ </form>
<VideoPreviewsList videoIds={userVideos[userId] ? Object.keys(userVideos[userId]) : []}/>
</div>
) |
9af9fd4200ffe08681d42bb131b9559b52073f1b | src/components/katagroups.js | src/components/katagroups.js | import React from 'react';
import {default as KataGroupsData} from '../katagroups.js';
export default class KataGroupsComponent extends React.Component {
static propTypes = {
kataGroups: React.PropTypes.instanceOf(KataGroupsData).isRequired
};
render() {
const {kataGroups} = this.props;
return (
<div id="nav" className="pure-u">
<a href="#" className="nav-menu-button">Menu</a>
<div className="nav-inner">
<div className="pure-menu">
<ul className="pure-menu-list">
<li className="pure-menu-heading">Kata groups</li>
<li className="pure-menu-item">
</li>
{kataGroups.groups.map(kataGroup => <li className="pure-menu-item">
<a href={`#kataGroup=${encodeURIComponent(kataGroup.name)}`} className="pure-menu-link">{kataGroup.name} <span className="email-count">({kataGroup.katasCount})</span></a>
</li>)}
</ul>
</div>
</div>
</div>
);
}
}
| import React from 'react';
import {default as KataGroupsData} from '../katagroups.js';
export default class KataGroupsComponent extends React.Component {
static propTypes = {
kataGroups: React.PropTypes.instanceOf(KataGroupsData).isRequired
};
render() {
const {kataGroups} = this.props;
return (
<div id="nav" className="pure-u">
<a href="#" className="nav-menu-button">Menu</a>
<div className="nav-inner">
<div className="pure-menu">
<ul className="pure-menu-list">
<li className="pure-menu-heading">Kata groups</li>
<li className="pure-menu-item">
</li>
{kataGroups.groups.map(kataGroup => <li className="pure-menu-item">
<a href={kataGroup.url} className="pure-menu-link">{kataGroup.name} <span className="email-count">({kataGroup.katasCount})</span></a>
</li>)}
</ul>
</div>
</div>
</div>
);
}
}
| Use the new `url` property. | Use the new `url` property. | JavaScript | mit | wolframkriesing/es6-react-workshop,wolframkriesing/es6-react-workshop | ---
+++
@@ -20,7 +20,7 @@
<li className="pure-menu-item">
</li>
{kataGroups.groups.map(kataGroup => <li className="pure-menu-item">
- <a href={`#kataGroup=${encodeURIComponent(kataGroup.name)}`} className="pure-menu-link">{kataGroup.name} <span className="email-count">({kataGroup.katasCount})</span></a>
+ <a href={kataGroup.url} className="pure-menu-link">{kataGroup.name} <span className="email-count">({kataGroup.katasCount})</span></a>
</li>)}
</ul>
</div> |
d2dcc04cbcc2b6a19762c4f95e98476b935a29e4 | src/components/style-root.js | src/components/style-root.js | /* @flow */
import React, {Component, PropTypes} from 'react';
import Enhancer from '../enhancer';
import StyleKeeper from '../style-keeper';
import StyleSheet from './style-sheet';
function _getStyleKeeper(instance): StyleKeeper {
if (!instance._radiumStyleKeeper) {
const userAgent = (
instance.props.radiumConfig && instance.props.radiumConfig.userAgent
) || (
instance.context._radiumConfig && instance.context._radiumConfig.userAgent
);
instance._radiumStyleKeeper = new StyleKeeper(userAgent);
}
return instance._radiumStyleKeeper;
}
class StyleRoot extends Component {
constructor() {
super(...arguments);
_getStyleKeeper(this);
}
getChildContext() {
return {_radiumStyleKeeper: _getStyleKeeper(this)};
}
render() {
return (
<div {...this.props}>
{this.props.children}
<StyleSheet />
</div>
);
}
}
StyleRoot.contextTypes = {
_radiumConfig: PropTypes.object,
_radiumStyleKeeper: PropTypes.instanceOf(StyleKeeper)
};
StyleRoot.childContextTypes = {
_radiumStyleKeeper: PropTypes.instanceOf(StyleKeeper)
};
StyleRoot = Enhancer(StyleRoot);
export default StyleRoot;
| /* @flow */
import React, {Component, PropTypes} from 'react';
import Enhancer from '../enhancer';
import StyleKeeper from '../style-keeper';
import StyleSheet from './style-sheet';
function _getStyleKeeper(instance): StyleKeeper {
if (!instance._radiumStyleKeeper) {
const userAgent = (
instance.props.radiumConfig && instance.props.radiumConfig.userAgent
) || (
instance.context._radiumConfig && instance.context._radiumConfig.userAgent
);
instance._radiumStyleKeeper = new StyleKeeper(userAgent);
}
return instance._radiumStyleKeeper;
}
class StyleRoot extends Component {
constructor() {
super(...arguments);
_getStyleKeeper(this);
}
getChildContext() {
return {_radiumStyleKeeper: _getStyleKeeper(this)};
}
render() {
/* eslint-disable no-unused-vars */
// Pass down all props except config to the rendered div.
const {radiumConfig, ...otherProps} = this.props;
/* eslint-enable no-unused-vars */
return (
<div {...otherProps}>
{this.props.children}
<StyleSheet />
</div>
);
}
}
StyleRoot.contextTypes = {
_radiumConfig: PropTypes.object,
_radiumStyleKeeper: PropTypes.instanceOf(StyleKeeper)
};
StyleRoot.childContextTypes = {
_radiumStyleKeeper: PropTypes.instanceOf(StyleKeeper)
};
StyleRoot = Enhancer(StyleRoot);
export default StyleRoot;
| Stop passing radiumConfig prop to div | Stop passing radiumConfig prop to div
| JavaScript | mit | FormidableLabs/radium | ---
+++
@@ -31,8 +31,13 @@
}
render() {
+ /* eslint-disable no-unused-vars */
+ // Pass down all props except config to the rendered div.
+ const {radiumConfig, ...otherProps} = this.props;
+ /* eslint-enable no-unused-vars */
+
return (
- <div {...this.props}>
+ <div {...otherProps}>
{this.props.children}
<StyleSheet />
</div> |
c257e7fd2162131559b0db4c2eb2b1e8d8a1edbc | src/render.js | src/render.js | import Instance from './instance';
import instances from './instances';
export default (node, options = {}) => {
// Stream was passed instead of `options` object
if (typeof options.write === 'function') {
options = {
stdout: options,
stdin: process.stdin
};
}
options = {
stdout: process.stdout,
stdin: process.stdin,
debug: false,
exitOnCtrlC: true,
...options
};
let instance;
if (instances.has(options.stdout)) {
instance = instances.get(options.stdout);
} else {
instance = new Instance(options);
instances.set(options.stdout, instance);
}
instance.render(node);
return {
rerender: instance.render,
unmount: () => instance.unmount(),
waitUntilExit: instance.waitUntilExit,
cleanup: () => instances.delete(options.stdout)
};
};
| import Instance from './instance';
import instances from './instances';
export default (node, options = {}) => {
// Stream was passed instead of `options` object
if (typeof options.write === 'function') {
options = {
stdout: options,
stdin: process.stdin
};
}
options = {
stdout: process.stdout,
stdin: process.stdin,
debug: false,
exitOnCtrlC: true,
experimental: false,
...options
};
let instance;
if (instances.has(options.stdout)) {
instance = instances.get(options.stdout);
} else {
instance = new Instance(options);
instances.set(options.stdout, instance);
}
instance.render(node);
return {
rerender: instance.render,
unmount: () => instance.unmount(),
waitUntilExit: instance.waitUntilExit,
cleanup: () => instances.delete(options.stdout)
};
};
| Add default value for `experimental` option | Add default value for `experimental` option
| JavaScript | mit | vadimdemedes/ink,vadimdemedes/ink | ---
+++
@@ -15,6 +15,7 @@
stdin: process.stdin,
debug: false,
exitOnCtrlC: true,
+ experimental: false,
...options
};
|
84a5ea535a61cd8d608694406c1bdf05a0adf599 | src/router.js | src/router.js | (function(win){
'use strict';
var paramRe = /:([^\/.\\]+)/g;
function Router(){
if(!(this instanceof Router)){
return new Router();
}
this.routes = [];
}
Router.prototype.route = function(path, fn){
paramRe.lastIndex = 0;
var regexp = path + '', match;
while(match = paramRe.exec(path)){
regexp = regexp.replace(match[0], '([^/.\\\\]+)');
}
this.routes.push({
regexp: new RegExp('^' + regexp + '$'),
callback: fn
});
return this;
};
Router.prototype.dispatch = function(path){
path = path || win.location.pathname;
for(var i = 0, len = this.routes.length, route, matches; i < len; i++){
route = this.routes[i];
matches = route.regexp.exec(path);
if(matches && matches[0]){
route.callback.apply(null, matches.slice(1));
return this;
}
}
return this;
};
win.Router = Router;
})(this); | (function(win){
'use strict';
var paramRe = /:([^\/.\\]+)/g;
function Router(){
if(!(this instanceof Router)){
return new Router();
}
this.routes = [];
}
Router.prototype.route = function(path, fn){
paramRe.lastIndex = 0;
var regexp = path + '', match;
while(match = paramRe.exec(path)){
regexp = regexp.replace(match[0], '([^/\\\\]+)');
}
this.routes.push({
regexp: new RegExp('^' + regexp + '$'),
callback: fn
});
return this;
};
Router.prototype.dispatch = function(path){
path = path || win.location.pathname;
for(var i = 0, len = this.routes.length, route, matches; i < len; i++){
route = this.routes[i];
matches = route.regexp.exec(path);
if(matches && matches[0]){
route.callback.apply(null, matches.slice(1));
return this;
}
}
return this;
};
win.Router = Router;
})(this); | Fix params with period not being passed to callback | Fix params with period not being passed to callback
| JavaScript | unlicense | ryanmorr/router | ---
+++
@@ -14,7 +14,7 @@
paramRe.lastIndex = 0;
var regexp = path + '', match;
while(match = paramRe.exec(path)){
- regexp = regexp.replace(match[0], '([^/.\\\\]+)');
+ regexp = regexp.replace(match[0], '([^/\\\\]+)');
}
this.routes.push({
regexp: new RegExp('^' + regexp + '$'), |
b77f1e3bca3e2858ca0c0b85cc3d2d8083cdb199 | 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
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require_tree .
//= require jquery-bramus-progressbar/jquery-bramus-progressbar
//= require general
//= require jquery.history
//= require jquery-warper
//= require layers
//= require unwarped
| // 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
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery.ui.all
//= require_tree .
//= require jquery-bramus-progressbar/jquery-bramus-progressbar
//= require general
//= require jquery.history
//= require jquery-warper
//= require layers
//= require unwarped
| Fix js manifest for older jquery ui | Fix js manifest for older jquery ui
| JavaScript | mit | dfurber/historyforge,timwaters/mapwarper,kartta-labs/mapwarper,dfurber/historyforge,kartta-labs/mapwarper,kartta-labs/mapwarper,dfurber/mapwarper,timwaters/mapwarper,dfurber/historyforge,timwaters/mapwarper,dfurber/mapwarper,dfurber/historyforge,dfurber/mapwarper,dfurber/mapwarper,timwaters/mapwarper,kartta-labs/mapwarper,kartta-labs/mapwarper | ---
+++
@@ -12,7 +12,7 @@
//
//= require jquery
//= require jquery_ujs
-//= require jquery-ui
+//= require jquery.ui.all
//= require_tree .
//= require jquery-bramus-progressbar/jquery-bramus-progressbar
//= require general |
68ad2fe3afc0f674a8424ada83a397d699559bd8 | 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 any plugin's vendor/assets/javascripts directory 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
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require RRSSB
//= require lazyload
//= require image-preview
//= require script
//= require service-worker-cache-rails
| // 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 any plugin's vendor/assets/javascripts directory 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
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require RRSSB
//= require lazyload
//= require image-preview
//= require script
| Remove last of the gem | Remove last of the gem
| JavaScript | mit | tonyedwardspz/westcornwallevents,tonyedwardspz/westcornwallevents,tonyedwardspz/westcornwallevents | ---
+++
@@ -16,4 +16,3 @@
//= require lazyload
//= require image-preview
//= require script
-//= require service-worker-cache-rails |
84a21f18b364bed6249002ff311900f240059b16 | app/assets/javascripts/inspections.js | app/assets/javascripts/inspections.js | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
$(function() {
return console.log($("span").length);
});
$(".status").hover((function() {
console.log(this);
return $(this).children(".details").show();
}), function() {
console.log("bob");
return $(this).children(".details").hide();
});
| $(function() {
console.log($("span").length);
});
$(".status").hover((function() {
console.log(this);
$(this).children(".details").show();
}), function() {
console.log("bob");
$(this).children(".details").hide();
});
| Fix for conversion from coffee->js | Fix for conversion from coffee->js
| JavaScript | mit | nomatteus/dinesafe,jbinto/dinesafe,jbinto/dinesafe-chrome-backend,nomatteus/dinesafe,nomatteus/dinesafe,jbinto/dinesafe-chrome-backend,nomatteus/dinesafe,jbinto/dinesafe,jbinto/dinesafe-chrome-backend,jbinto/dinesafe-chrome-backend,jbinto/dinesafe,jbinto/dinesafe | ---
+++
@@ -1,15 +1,11 @@
-# Place all the behaviors and hooks related to the matching controller here.
-# All this logic will automatically be available in application.js.
-# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
-
$(function() {
- return console.log($("span").length);
+ console.log($("span").length);
});
$(".status").hover((function() {
console.log(this);
- return $(this).children(".details").show();
+ $(this).children(".details").show();
}), function() {
console.log("bob");
- return $(this).children(".details").hide();
+ $(this).children(".details").hide();
});
|
e7933b56614eda1941811bb95e533fceb1eaf907 | app/components/chess-board-square.js | app/components/chess-board-square.js | import React from "react";
import classNames from "classnames";
import { selectPiece } from "store/actions";
class ChessBoardSquare extends React.Component {
constructor(props) {
super(props);
this.selectSquare = this.selectSquare.bind(this);
}
squareCoords() {
return { rank: this.props.rank, file: this.props.file };
}
selectSquare() {
var { store } = this.props;
console.log(`Clicked: ${this.props.file}${this.props.rank}`);
if (this.props.piece != undefined) {
store.dispatch(selectPiece(this.squareCoords()));
}
console.log(store.getState().selectedSquare);
};
isSelectedSquare() {
var { store } = this.props;
return this.squareCoords().rank == store.getState().selectedSquare.rank
&& this.squareCoords().file == store.getState().selectedSquare.file;
}
render() {
if (this.props.piece == undefined) {
var squareClass = "board-square";
}
else {
var squareClass = classNames(
"board-square",
this.props.piece.type,
this.props.piece.colour,
{ "selected": this.isSelectedSquare() }
)
}
return <div className={squareClass} onClick={this.selectSquare} />
}
}
export default ChessBoardSquare;
| import React from "react";
import classNames from "classnames";
import { selectPiece } from "store/actions";
class ChessBoardSquare extends React.Component {
constructor(props) {
super(props);
this.selectSquare = this.selectSquare.bind(this);
}
squareCoords() {
return { rank: this.props.rank, file: this.props.file };
}
selectSquare() {
var { store } = this.props;
console.log(`Clicked: ${this.props.file}${this.props.rank}`);
if (this.props.piece != undefined) {
store.dispatch(selectPiece(this.squareCoords()));
}
console.log(store.getState().selectedSquare);
};
isSelectedSquare() {
var { store } = this.props;
if (store.getState().selectedSquare == null) {
return false;
}
else {
return this.squareCoords().rank == store.getState().selectedSquare.rank
&& this.squareCoords().file == store.getState().selectedSquare.file;
}
}
render() {
if (this.props.piece == undefined) {
var squareClass = "board-square";
}
else {
var squareClass = classNames(
"board-square",
this.props.piece.type,
this.props.piece.colour,
{ "selected": this.isSelectedSquare() }
)
}
return <div className={squareClass} onClick={this.selectSquare} />
}
}
export default ChessBoardSquare;
| Fix problem with null selectedSquare | Fix problem with null selectedSquare
| JavaScript | mit | danbee/chess,danbee/chess,danbee/chess | ---
+++
@@ -28,8 +28,13 @@
isSelectedSquare() {
var { store } = this.props;
- return this.squareCoords().rank == store.getState().selectedSquare.rank
- && this.squareCoords().file == store.getState().selectedSquare.file;
+ if (store.getState().selectedSquare == null) {
+ return false;
+ }
+ else {
+ return this.squareCoords().rank == store.getState().selectedSquare.rank
+ && this.squareCoords().file == store.getState().selectedSquare.file;
+ }
}
render() { |
cc38cd161bf98799a87039cfedea311e76b7ca3f | web/templates/javascript/Entry.js | web/templates/javascript/Entry.js | import Session from "./Session.js";
let session = new Session();
loadPlugins()
.then(() => session.connect());
async function loadPlugins()
{
let pluginEntryScripts = <%- JSON.stringify(entryScripts) %>;
let importPromises = [];
for(let entryScript of pluginEntryScripts) {
let importPromise = import(entryScript).then(loadPlugin);
importPromises.push(importPromise);
}
await Promise.all(importPromises);
}
function loadPlugin(module)
{
module.default(session);
} | import Session from "./Session.js";
<% for(let i = 0; i < entryScripts.length; i++) { -%>
import { default as plugin<%- i %> } from "<%- entryScripts[i] %>";
<% } -%>
let session = new Session();
loadPlugins()
.then(() => session.connect());
async function loadPlugins()
{
<% for(let i = 0; i < entryScripts.length; i++) { -%>
plugin<%- i %>(session);
<% } -%>
}
| Remove dynamic import in client source | Remove dynamic import in client source
| JavaScript | mit | ArthurCose/JoshDevelop,ArthurCose/JoshDevelop | ---
+++
@@ -1,4 +1,7 @@
import Session from "./Session.js";
+<% for(let i = 0; i < entryScripts.length; i++) { -%>
+import { default as plugin<%- i %> } from "<%- entryScripts[i] %>";
+<% } -%>
let session = new Session();
@@ -7,19 +10,7 @@
async function loadPlugins()
{
- let pluginEntryScripts = <%- JSON.stringify(entryScripts) %>;
- let importPromises = [];
-
- for(let entryScript of pluginEntryScripts) {
- let importPromise = import(entryScript).then(loadPlugin);
-
- importPromises.push(importPromise);
- }
-
- await Promise.all(importPromises);
+<% for(let i = 0; i < entryScripts.length; i++) { -%>
+ plugin<%- i %>(session);
+<% } -%>
}
-
-function loadPlugin(module)
-{
- module.default(session);
-} |
7499a6bfd2b91b04724f5c7bd0ad903de5a226ab | sashimi-webapp/test/e2e/specs/fileManager/create-file-folder.spec.js | sashimi-webapp/test/e2e/specs/fileManager/create-file-folder.spec.js | function createDoc(browser, docType) {
const devServer = browser.globals.devServerURL;
browser.url(`${devServer}/`);
browser.expect.element('#app').to.be.visible.before(5000);
browser.execute(() => {
const className = `.${docType}`;
const numDocs = document.querySelectorAll(className).length;
return numDocs;
}, [docType], (numDocs) => {
try {
const createButton = `#button-create-${docType}`;
const numDocsAfterCreate = numDocs.value + 1;
browser
.click(createButton);
browser
.expect(numDocs.value).to.equal(numDocsAfterCreate);
} catch (error) {
console.log(error);
}
});
}
describe('FileManager\'s create file/folder button', function() {
after((browser, done) => {
browser.end(() => done());
});
it('should create a new file', (browser) => {
createDoc(browser, 'file');
});
it('should create a new folder', (browser) => {
createDoc(browser, 'folder');
});
});
| function createDoc(browser, docType) {
const devServer = browser.globals.devServerURL;
browser.url(`${devServer}/`);
browser.expect.element('#app').to.be.visible.before(5000);
browser.execute(() => {
const className = `.${docType}`;
const numDocs = document.querySelectorAll(className).length;
return numDocs;
}, [docType], (numDocs) => {
try {
const createButton = `#button-create-${docType}`;
const numDocsAfterCreate = numDocs.value + 1;
browser
.click(createButton)
.pause(500);
browser
.expect(numDocs.value).to.equal(numDocsAfterCreate);
} catch (error) {
console.log(error);
}
});
}
describe('FileManager\'s create file/folder button', function() {
after((browser, done) => {
browser.end(() => done());
});
it('should create a new file', (browser) => {
createDoc(browser, 'file');
});
it('should create a new folder', (browser) => {
createDoc(browser, 'folder');
});
});
| Add pause after button click to handle delays | Add pause after button click to handle delays
| JavaScript | mit | nus-mtp/sashimi-note,nus-mtp/sashimi-note,nus-mtp/sashimi-note | ---
+++
@@ -15,7 +15,8 @@
const numDocsAfterCreate = numDocs.value + 1;
browser
- .click(createButton);
+ .click(createButton)
+ .pause(500);
browser
.expect(numDocs.value).to.equal(numDocsAfterCreate); |
e32bf7f935f9677847639ce10267830b63b3c2ec | tasks/scss-lint.js | tasks/scss-lint.js | module.exports = function (grunt) {
var _ = require('lodash'),
scsslint = require('./lib/scss-lint').init(grunt);
grunt.registerMultiTask('scsslint', 'Validate `.scss` files with `scss-lint`.', function() {
var done = this.async(),
files = this.filesSrc,
fileCount = this.filesSrc.length,
target = this.target,
opts;
opts = this.options({
config: '.scss-lint.yml',
reporterOutput: null
});
grunt.verbose.writeflags(opts, 'scss-lint options');
grunt.log.writeln('Running scss-lint on ' + target);
scsslint.lint(files, opts, function (results) {
var success = _.isEmpty(results);
if (success) {
grunt.log.oklns(fileCount + ' files are lint free');
} else {
grunt.log.writeln(result);
}
if (opts.reporterOutput) {
grunt.log.writeln('Results have been written to: ' + opts.reporterOutput);
}
done(success);
});
});
};
| module.exports = function (grunt) {
var _ = require('lodash'),
scsslint = require('./lib/scss-lint').init(grunt);
grunt.registerMultiTask('scsslint', 'Validate `.scss` files with `scss-lint`.', function() {
var done = this.async(),
files = this.filesSrc,
fileCount = this.filesSrc.length,
target = this.target,
opts;
opts = this.options({
config: '.scss-lint.yml',
reporterOutput: null
});
grunt.verbose.writeflags(opts, 'scss-lint options');
grunt.log.writeln('Running scss-lint on ' + target);
scsslint.lint(files, opts, function (results) {
var success = _.isEmpty(results);
if (success) {
grunt.log.oklns(fileCount + ' files are lint free');
} else {
grunt.log.writeln(results);
}
if (opts.reporterOutput) {
grunt.log.writeln('Results have been written to: ' + opts.reporterOutput);
}
done(success);
});
});
};
| Fix typo in logging results on error. | Fix typo in logging results on error.
| JavaScript | mit | nick11703/grunt-scss-lint,nick11703/grunt-scss-lint,chrisnicotera/grunt-scss-lint,asev/grunt-scss-lint,DBaker85/grunt-scss-lint-json,meinaart/grunt-scss-lint,asev/grunt-scss-lint,ahmednuaman/grunt-scss-lint,barzik/grunt-scss-lint,ahmednuaman/grunt-scss-lint,DBaker85/grunt-scss-lint-json,cornedor/grunt-scss-lint,cornedor/grunt-scss-lint,barzik/grunt-scss-lint,chrisnicotera/grunt-scss-lint,meinaart/grunt-scss-lint | ---
+++
@@ -24,7 +24,7 @@
if (success) {
grunt.log.oklns(fileCount + ' files are lint free');
} else {
- grunt.log.writeln(result);
+ grunt.log.writeln(results);
}
if (opts.reporterOutput) { |
ac86b98535232756835e0e2b1df0a1c87dfc3529 | webmaker-download-locales.js | webmaker-download-locales.js | var async = require("async");
var path = require("path");
var url = require("url");
var utils = require("./lib/utils");
module.exports = function(options, callback) {
utils.list_files(options, function(err, objects) {
if (err) {
callback(err);
return;
}
var q = async.queue(function(translation, callback) {
var local_path_split = url.parse(translation).pathname.split(path.sep);
var local_path = path.join(options.dir, local_path_split[2], local_path_split[3]);
utils.stream_url_to_file(translation, local_path, callback);
}, 16);
q.push(objects, function(err) {
if (err) {
q.tasks.length = 0;
callback(err);
}
});
q.drain = callback;
});
};
| var async = require("async");
var path = require("path");
var url = require("url");
var utils = require("./lib/utils");
module.exports = function(options, callback) {
utils.list_files(options, function(err, objects) {
if (err) {
callback(err);
return;
}
var q = async.queue(function(translation, callback) {
var local_path_split = url.parse(translation).pathname.split("/");
var local_path = path.join(options.dir, local_path_split[2], local_path_split[3]);
utils.stream_url_to_file(translation, local_path, callback);
}, 16);
q.push(objects, function(err) {
if (err) {
q.tasks.length = 0;
callback(err);
}
});
q.drain = callback;
});
};
| Use / as a separator for urls | Use / as a separator for urls
| JavaScript | mit | mozilla/webmaker-download-locales | ---
+++
@@ -12,7 +12,7 @@
}
var q = async.queue(function(translation, callback) {
- var local_path_split = url.parse(translation).pathname.split(path.sep);
+ var local_path_split = url.parse(translation).pathname.split("/");
var local_path = path.join(options.dir, local_path_split[2], local_path_split[3]);
utils.stream_url_to_file(translation, local_path, callback); |
edda84fefd17426fcdf822fc3fb746f30047085c | lib/template/blocks.js | lib/template/blocks.js | var _ = require('lodash');
module.exports = {
// Return non-parsed html
// since blocks are by default non-parsable, a simple identity method works fine
html: _.identity,
// Highlight a code block
// This block can be replaced by plugins
code: function(blk) {
return {
html: false,
body: blk.body
};
}
};
| var _ = require('lodash');
module.exports = {
// Return non-parsed html
// since blocks are by default non-parsable, a simple identity method works fine
html: _.identity,
// Highlight a code block
// This block can be replaced by plugins
code: function(blk) {
return {
html: false,
body: blk.body
};
},
// Render some markdown to HTML
markdown: function(blk) {
return this.book.renderInline('markdown', blk.body)
.then(function(out) {
return { body: out };
});
},
asciidoc: function(blk) {
return this.book.renderInline('asciidoc', blk.body)
.then(function(out) {
return { body: out };
});
},
markup: function(blk) {
return this.book.renderInline(this.ctx.file.type, blk.body)
.then(function(out) {
return { body: out };
});
}
};
| Add block "markdown", "asciidoc" and "markup" | Add block "markdown", "asciidoc" and "markup"
| JavaScript | apache-2.0 | ryanswanson/gitbook,gencer/gitbook,tshoper/gitbook,gencer/gitbook,GitbookIO/gitbook,strawluffy/gitbook,tshoper/gitbook | ---
+++
@@ -12,5 +12,25 @@
html: false,
body: blk.body
};
+ },
+
+ // Render some markdown to HTML
+ markdown: function(blk) {
+ return this.book.renderInline('markdown', blk.body)
+ .then(function(out) {
+ return { body: out };
+ });
+ },
+ asciidoc: function(blk) {
+ return this.book.renderInline('asciidoc', blk.body)
+ .then(function(out) {
+ return { body: out };
+ });
+ },
+ markup: function(blk) {
+ return this.book.renderInline(this.ctx.file.type, blk.body)
+ .then(function(out) {
+ return { body: out };
+ });
}
}; |
dec054ca7face3467e6beeafdac8772346e8f38c | api/routes/users.js | api/routes/users.js | import {Router} from 'express'
import models from '../models';
import tasks from './tasks'
export default () => {
let app = Router({mergeParams: true})
app.use('/:userId/tasks', tasks())
app.get('/', (req, res) => {
models.User.findAll({
attributes: ['id', 'email']
}).then((users) => {
res.send(users)
})
})
app.get('/new', (req, res) => {
res.render('users/new')
})
app.get('/:id', (req, res) => {
models.User.find({
where: {
id: req.params.id
},
include: [models.Task]
}).then((user) => {
res.render('users/show', {user})
})
})
app.post('/', (req, res) => {
models.User.create(req.body).then((user) => {
req.session.userId = user.dataValues.id
req.app.locals.userId = user.dataValues.id
req.session.save()
// add validations and errors
res.send(user);
})
})
return app
} | import {Router} from 'express'
import models from '../models';
import tasks from './tasks'
export default () => {
let app = Router({mergeParams: true})
app.use('/:userId/tasks', tasks())
app.get('/:id', (req, res) => {
models.User.find(req.params.id).then((users) => {
res.send(users)
})
})
app.get('/new', (req, res) => {
res.render('users/new')
})
app.get('/:id', (req, res) => {
models.User.find({
where: {
id: req.params.id
},
include: [models.Task]
}).then((user) => {
res.render('users/show', {user})
})
})
app.post('/', (req, res) => {
models.User.create(req.body).then((user) => {
req.session.userId = user.dataValues.id
req.app.locals.userId = user.dataValues.id
req.session.save()
// add validations and errors
res.send(user);
})
})
return app
} | Update user POST and GET routes | Update user POST and GET routes
| JavaScript | mit | taodav/MicroSerfs,taodav/MicroSerfs | ---
+++
@@ -7,10 +7,8 @@
app.use('/:userId/tasks', tasks())
- app.get('/', (req, res) => {
- models.User.findAll({
- attributes: ['id', 'email']
- }).then((users) => {
+ app.get('/:id', (req, res) => {
+ models.User.find(req.params.id).then((users) => {
res.send(users)
})
}) |
7e5bc4044748de2130564ded69d3bc3618274b8a | test/test-purge.js | test/test-purge.js | require('./harness').run();
var recvCount = 0;
var body = "hello world";
connection.addListener('ready', function () {
puts("connected to " + connection.serverProperties.product);
var e = connection.exchange('node-purge-fanout', {type: 'fanout'});
var q = connection.queue('node-purge-queue', function() {
q.bind(e, "*")
q.on('queueBindOk', function() {
puts("publishing 1 json messages");
e.publish('ackmessage.json1', { name: 'A' });
puts('Purge queue')
q.purge().addCallback(function(ok){
puts('Deleted '+ok.messageCount+' messages')
assert.equal(1,ok.messageCount)
puts("publishing another json messages");
e.publish('ackmessage.json2', { name: 'B' });
})
q.on('basicConsumeOk', function () {
setTimeout(function () {
// wait one second to receive the message, then quit
connection.end();
}, 1000);
});
q.subscribe({ ack: true }, function (json) {
recvCount++;
puts('Got message ' + JSON.stringify(json));
if (recvCount == 1) {
assert.equal('B', json.name);
q.shift();
} else {
throw new Error('Too many message!');
}
})
})
});
});
process.addListener('exit', function () {
assert.equal(1, recvCount);
});
| require('./harness').run();
var recvCount = 0;
var body = "hello world";
connection.addListener('ready', function () {
puts("connected to " + connection.serverProperties.product);
var e = connection.exchange('node-purge-fanout', {type: 'fanout', confirm: true});
var q = connection.queue('node-purge-queue', function() {
q.bind(e, "*");
q.on('queueBindOk', function() {
puts("publishing 1 json message");
e.publish('ackmessage.json1', { name: 'A' }, {}, function() {
puts('Purge queue');
q.purge().addCallback(function(ok){
puts('Deleted '+ok.messageCount+' message');
assert.equal(1,ok.messageCount);
puts("publishing another json message");
e.publish('ackmessage.json2', { name: 'B' });
});
q.on('basicConsumeOk', function () {
setTimeout(function () {
// wait one second to receive the message, then quit
connection.end();
}, 1000);
});
q.subscribe({ ack: true }, function (json) {
recvCount++;
puts('Got message ' + JSON.stringify(json));
if (recvCount == 1) {
assert.equal('B', json.name);
q.shift();
} else {
throw new Error('Too many message!');
}
});
});
});
});
});
process.addListener('exit', function () {
assert.equal(1, recvCount);
});
| Fix race condition in purge test. | Fix race condition in purge test.
| JavaScript | mit | xebitstudios/node-amqp,albert-lacki/node-amqp,zkochan/node-amqp,postwait/node-amqp,zinic/node-amqp,postwait/node-amqp,xebitstudios/node-amqp,albert-lacki/node-amqp,zinic/node-amqp,zkochan/node-amqp,postwait/node-amqp,remind101/node-amqp,remind101/node-amqp,hinson0/node-amqp,seanahn/node-amqp,seanahn/node-amqp,segmentio/node-amqp,albert-lacki/node-amqp,zkochan/node-amqp,segmentio/node-amqp,hinson0/node-amqp,hinson0/node-amqp,remind101/node-amqp,zinic/node-amqp,xebitstudios/node-amqp | ---
+++
@@ -6,39 +6,44 @@
connection.addListener('ready', function () {
puts("connected to " + connection.serverProperties.product);
- var e = connection.exchange('node-purge-fanout', {type: 'fanout'});
+ var e = connection.exchange('node-purge-fanout', {type: 'fanout', confirm: true});
var q = connection.queue('node-purge-queue', function() {
- q.bind(e, "*")
+ q.bind(e, "*");
q.on('queueBindOk', function() {
- puts("publishing 1 json messages");
- e.publish('ackmessage.json1', { name: 'A' });
+ puts("publishing 1 json message");
- puts('Purge queue')
- q.purge().addCallback(function(ok){
- puts('Deleted '+ok.messageCount+' messages')
- assert.equal(1,ok.messageCount)
- puts("publishing another json messages");
- e.publish('ackmessage.json2', { name: 'B' });
- })
+ e.publish('ackmessage.json1', { name: 'A' }, {}, function() {
- q.on('basicConsumeOk', function () {
- setTimeout(function () {
- // wait one second to receive the message, then quit
- connection.end();
- }, 1000);
+ puts('Purge queue');
+ q.purge().addCallback(function(ok){
+ puts('Deleted '+ok.messageCount+' message');
+ assert.equal(1,ok.messageCount);
+ puts("publishing another json message");
+ e.publish('ackmessage.json2', { name: 'B' });
+ });
+
+ q.on('basicConsumeOk', function () {
+ setTimeout(function () {
+ // wait one second to receive the message, then quit
+ connection.end();
+ }, 1000);
+ });
+
+ q.subscribe({ ack: true }, function (json) {
+ recvCount++;
+ puts('Got message ' + JSON.stringify(json));
+ if (recvCount == 1) {
+ assert.equal('B', json.name);
+ q.shift();
+ } else {
+ throw new Error('Too many message!');
+ }
+ });
+
});
- q.subscribe({ ack: true }, function (json) {
- recvCount++;
- puts('Got message ' + JSON.stringify(json));
- if (recvCount == 1) {
- assert.equal('B', json.name);
- q.shift();
- } else {
- throw new Error('Too many message!');
- }
- })
- })
+
+ });
});
});
|
6831e4787d7fd5a19aef1733e3bb158cb82538dd | resources/framework/dropdown-nav.js | resources/framework/dropdown-nav.js | /* From w3schools */
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
$(function () {
$('.c-dropdown__btn').click(function (event) {
event.preventDefault();
$(this).nextAll(".c-dropdown__cont").toggleClass('c-dropdown__cont--hide');
});
});
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.c-dropdown__btn')) {
$(".c-dropdown__cont").addClass('c-dropdown__cont--hide');
}
} | /* From w3schools */
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
$(function () {
$('.c-site-nav').on('click', '.c-dropdown__btn', function (event) {
event.preventDefault();
$(this).nextAll(".c-dropdown__cont").toggleClass('c-dropdown__cont--hide');
$(this).nextAll(".mean-expand").click();
});
});
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.c-dropdown__btn')) {
$(".c-dropdown__cont").addClass('c-dropdown__cont--hide');
}
} | Fix nav issue when using mean menu | Fix nav issue when using mean menu
When the link only had a dropdown and didnt have a link itself, it wouldnt trigger the dropdown on mobile
| JavaScript | mit | solleer/framework,solleer/framework,solleer/framework | ---
+++
@@ -3,9 +3,10 @@
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
$(function () {
- $('.c-dropdown__btn').click(function (event) {
+ $('.c-site-nav').on('click', '.c-dropdown__btn', function (event) {
event.preventDefault();
$(this).nextAll(".c-dropdown__cont").toggleClass('c-dropdown__cont--hide');
+ $(this).nextAll(".mean-expand").click();
});
});
|
0ad0b316bb699abb9fd554e9bfce32135ca9f421 | webpack.config.babel.js | webpack.config.babel.js | import path from 'path';
import webpack from 'webpack';
import CommonsChunkPlugin from 'webpack/lib/optimize/CommonsChunkPlugin';
const PROD = process.env.NODE_ENV || 0;
module.exports = {
devtool: PROD ? false : 'eval',
entry: {
app: './app/assets/scripts/App.js',
vendor: [
'picturefill',
'./app/assets/_compiled/modernizr'
]
},
output: {
path: __dirname + '/app/assets/_compiled',
publicPath: '/assets/_compiled/',
filename: '[name].js',
chunkFilename: '_chunk/[name]_[chunkhash].js'
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: PROD ? true : false,
output: {
comments: false
}
}),
new CommonsChunkPlugin({
children: true,
minChunks: 2
})
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
}
};
| import path from 'path';
import webpack from 'webpack';
import CommonsChunkPlugin from 'webpack/lib/optimize/CommonsChunkPlugin';
const PROD = process.env.NODE_ENV || 0;
module.exports = {
devtool: PROD ? false : 'eval-cheap-module-source-map',
entry: {
app: './app/assets/scripts/App.js',
vendor: [
'picturefill',
'./app/assets/_compiled/modernizr'
]
},
output: {
path: __dirname + '/app/assets/_compiled',
publicPath: '/assets/_compiled/',
filename: '[name].js',
chunkFilename: '_chunk/[name]_[chunkhash].js'
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: PROD ? true : false,
output: {
comments: false
}
}),
new CommonsChunkPlugin({
children: true,
minChunks: 2
})
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
}
};
| Improve source maps for JS | Improve source maps for JS
| JavaScript | mit | trendyminds/pura,trendyminds/pura | ---
+++
@@ -5,7 +5,7 @@
const PROD = process.env.NODE_ENV || 0;
module.exports = {
- devtool: PROD ? false : 'eval',
+ devtool: PROD ? false : 'eval-cheap-module-source-map',
entry: {
app: './app/assets/scripts/App.js', |
824bd9786602e1af2414438f01dfea9e26842001 | js/src/forum/addTagLabels.js | js/src/forum/addTagLabels.js | import { extend } from 'flarum/extend';
import DiscussionListItem from 'flarum/components/DiscussionListItem';
import DiscussionPage from 'flarum/components/DiscussionPage';
import DiscussionHero from 'flarum/components/DiscussionHero';
import tagsLabel from '../common/helpers/tagsLabel';
import sortTags from '../common/utils/sortTags';
export default function() {
// Add tag labels to each discussion in the discussion list.
extend(DiscussionListItem.prototype, 'infoItems', function(items) {
const tags = this.props.discussion.tags();
if (tags && tags.length) {
items.add('tags', tagsLabel(tags), 10);
}
});
// Include a discussion's tags when fetching it.
extend(DiscussionPage.prototype, 'params', function(params) {
params.include.push('tags');
});
// Restyle a discussion's hero to use its first tag's color.
extend(DiscussionHero.prototype, 'view', function(view) {
const tags = sortTags(this.props.discussion.tags());
if (tags && tags.length) {
const color = tags[0].color();
if (color) {
view.attrs.style = {backgroundColor: color};
view.attrs.className += ' DiscussionHero--colored';
}
}
});
// Add a list of a discussion's tags to the discussion hero, displayed
// before the title. Put the title on its own line.
extend(DiscussionHero.prototype, 'items', function(items) {
const tags = this.props.discussion.tags();
if (tags && tags.length) {
items.add('tags', tagsLabel(tags, {link: true}), 5);
}
});
}
| import { extend } from 'flarum/extend';
import DiscussionListItem from 'flarum/components/DiscussionListItem';
import DiscussionHero from 'flarum/components/DiscussionHero';
import tagsLabel from '../common/helpers/tagsLabel';
import sortTags from '../common/utils/sortTags';
export default function() {
// Add tag labels to each discussion in the discussion list.
extend(DiscussionListItem.prototype, 'infoItems', function(items) {
const tags = this.props.discussion.tags();
if (tags && tags.length) {
items.add('tags', tagsLabel(tags), 10);
}
});
// Restyle a discussion's hero to use its first tag's color.
extend(DiscussionHero.prototype, 'view', function(view) {
const tags = sortTags(this.props.discussion.tags());
if (tags && tags.length) {
const color = tags[0].color();
if (color) {
view.attrs.style = {backgroundColor: color};
view.attrs.className += ' DiscussionHero--colored';
}
}
});
// Add a list of a discussion's tags to the discussion hero, displayed
// before the title. Put the title on its own line.
extend(DiscussionHero.prototype, 'items', function(items) {
const tags = this.props.discussion.tags();
if (tags && tags.length) {
items.add('tags', tagsLabel(tags, {link: true}), 5);
}
});
}
| Remove an obsolete method extension | Remove an obsolete method extension
This method hasn't existed in a while, and its purpose (including
the related tags when loading a discussion via API) has already
been achieved by extending the backend.
| JavaScript | mit | Luceos/flarum-tags,flarum/flarum-ext-tags,flarum/flarum-ext-tags,Luceos/flarum-tags | ---
+++
@@ -1,6 +1,5 @@
import { extend } from 'flarum/extend';
import DiscussionListItem from 'flarum/components/DiscussionListItem';
-import DiscussionPage from 'flarum/components/DiscussionPage';
import DiscussionHero from 'flarum/components/DiscussionHero';
import tagsLabel from '../common/helpers/tagsLabel';
@@ -14,11 +13,6 @@
if (tags && tags.length) {
items.add('tags', tagsLabel(tags), 10);
}
- });
-
- // Include a discussion's tags when fetching it.
- extend(DiscussionPage.prototype, 'params', function(params) {
- params.include.push('tags');
});
// Restyle a discussion's hero to use its first tag's color. |
0c727e568bf61fa89c43f13ed0f413062442297f | js/src/util/load-resource.js | js/src/util/load-resource.js | import req from 'superagent';
import {dispatch} from '../dispatcher';
import {Action} from '../actions';
import meta from '../meta';
const DIR_CONFIG='/resource/config/app/moe/somesim',
DIR_DOC='/resource/markdown/app/moe/somesim';
export default ()=>{
req
.get(DIR_CONFIG+'/somesim.json?='+meta.version)
.end((err,res)=>{
dispatch(Action.RecieveEquipList(res.body));
});
req
.get(DIR_CONFIG+'/flower.json?='+meta.version)
.end((err,res)=>{
dispatch(Action.RecieveFlowerList(res.body));
});
req
.get(DIR_CONFIG+'/pallet.json?='+meta.version)
.end((err,res)=>{
dispatch(Action.RecieveStainList(res.body));
});
req
.get(DIR_DOC+'/readme.md?='+meta.version)
.end((err,res)=>{
dispatch(Action.RecieveReadme(res.text));
});
req
.get(DIR_DOC+'/update.md?='+meta.version)
.end((err,res)=>{
dispatch(Action.RecieveUpdateLog(res.text));
});
}
| import req from 'superagent';
import {dispatch} from '../dispatcher';
import {Action} from '../actions';
import meta from '../meta';
const DIR_CONFIG='/resource/config/app/moe/somesim',
DIR_DOC='/resource/markdown/app/moe/somesim';
export default ()=>{
req
.get(DIR_CONFIG+'/somesim.json?='+meta.version)
.end((err,res)=>{
dispatch(Action.RecieveEquipList(JSON.parse(res.text)));
});
req
.get(DIR_CONFIG+'/flower.json?='+meta.version)
.end((err,res)=>{
dispatch(Action.RecieveFlowerList(JSON.parse(res.text)));
});
req
.get(DIR_CONFIG+'/pallet.json?='+meta.version)
.end((err,res)=>{
dispatch(Action.RecieveStainList(JSON.parse(res.text)));
});
req
.get(DIR_DOC+'/readme.md?='+meta.version)
.end((err,res)=>{
dispatch(Action.RecieveReadme(res.text));
});
req
.get(DIR_DOC+'/update.md?='+meta.version)
.end((err,res)=>{
dispatch(Action.RecieveUpdateLog(res.text));
});
}
| Change property to be access | Change property to be access
| JavaScript | mit | pocka/moe-somesim,pocka/moe-somesim,pocka/moe-somesim | ---
+++
@@ -13,19 +13,19 @@
req
.get(DIR_CONFIG+'/somesim.json?='+meta.version)
.end((err,res)=>{
- dispatch(Action.RecieveEquipList(res.body));
+ dispatch(Action.RecieveEquipList(JSON.parse(res.text)));
});
req
.get(DIR_CONFIG+'/flower.json?='+meta.version)
.end((err,res)=>{
- dispatch(Action.RecieveFlowerList(res.body));
+ dispatch(Action.RecieveFlowerList(JSON.parse(res.text)));
});
req
.get(DIR_CONFIG+'/pallet.json?='+meta.version)
.end((err,res)=>{
- dispatch(Action.RecieveStainList(res.body));
+ dispatch(Action.RecieveStainList(JSON.parse(res.text)));
});
req |
6b7d6db52e3aca121e8ae0d12bc752c290bbad5f | updater/entries.js | updater/entries.js | 'use strict';
const format = require('util').format;
const log = require('util').log;
const Promise = require('bluebird');
const db = require('../shared/db');
module.exports = {
insert: insertEntries,
delete: deleteEntries
};
function deleteEntries(distribution) {
return Promise.using(db(), function(client) {
log(format('Deleting all the entries for %s...', distribution));
return client.queryAsync({
name: 'delete_entries',
text: 'delete from source where distribution = $1',
values: [distribution]
}).then(function() {
log(format('Entries for %s deleted.', distribution));
return distribution;
});
});
}
function insertEntries(sources) {
log(format('Inserting %d entries for %s...', sources.length, sources[0].distribution));
// Pseudo query builder
let params = [];
let chunks = [];
for (let i = 0; i < sources.length; i++) {
let source = sources[i];
let valuesClause = [];
params.push(source.name);
valuesClause.push('$' + params.length);
params.push(source.distribution);
valuesClause.push('$' + params.length);
params.push(source.version);
valuesClause.push('$' + params.length);
chunks.push('(' + valuesClause.join(', ') + ')');
}
return Promise.using(db(), function(client) {
return client.queryAsync({
name: 'insert_sources',
text: 'insert into source(name, distribution, version) values ' +
chunks.join(', '),
values: params
}).then(function() {
log(format('Entries for %s inserted.', sources[0].distribution));
});
});
}
| 'use strict';
const format = require('util').format;
const log = require('util').log;
const Promise = require('bluebird');
const db = require('../shared/db');
module.exports = {
insert: insertEntries,
delete: deleteEntries
};
function deleteEntries(distribution) {
return Promise.using(db(), function(client) {
log(format('Deleting all the entries for %s...', distribution));
return client.queryAsync({
name: 'delete_entries',
text: 'delete from source where distribution = $1',
values: [distribution]
}).then(function() {
log(format('Entries for %s deleted.', distribution));
return distribution;
});
});
}
function insertEntries(sources) {
log(format('Inserting %d entries for %s...', sources.length, sources[0].distribution));
return Promise.map(sources, insertEntry).then(function() {
log(format('Entries for %s inserted.', sources[0].distribution));
});
}
function insertEntry(source) {
return Promise.using(db(), function(client) {
return client.queryAsync({
name: 'insert_source',
text: 'insert into source(name, distribution, version) values ($1, $2, $3)',
values: [source.name, source.distribution, source.version]
});
});
}
| Use one query per source instead of a single query | Use one query per source instead of a single query
This makes the code much much simpler.
| JavaScript | mit | ralt/dpsv,ralt/dpsv | ---
+++
@@ -27,32 +27,17 @@
function insertEntries(sources) {
log(format('Inserting %d entries for %s...', sources.length, sources[0].distribution));
- // Pseudo query builder
- let params = [];
- let chunks = [];
- for (let i = 0; i < sources.length; i++) {
- let source = sources[i];
- let valuesClause = [];
+ return Promise.map(sources, insertEntry).then(function() {
+ log(format('Entries for %s inserted.', sources[0].distribution));
+ });
+}
- params.push(source.name);
- valuesClause.push('$' + params.length);
-
- params.push(source.distribution);
- valuesClause.push('$' + params.length);
-
- params.push(source.version);
- valuesClause.push('$' + params.length);
-
- chunks.push('(' + valuesClause.join(', ') + ')');
- }
+function insertEntry(source) {
return Promise.using(db(), function(client) {
return client.queryAsync({
- name: 'insert_sources',
- text: 'insert into source(name, distribution, version) values ' +
- chunks.join(', '),
- values: params
- }).then(function() {
- log(format('Entries for %s inserted.', sources[0].distribution));
+ name: 'insert_source',
+ text: 'insert into source(name, distribution, version) values ($1, $2, $3)',
+ values: [source.name, source.distribution, source.version]
});
});
} |
cedfb682fbcb4badfd314710c07ad423feac417e | app/routes/media.js | app/routes/media.js | import Ember from 'ember'
import Authenticated from 'ember-simple-auth/mixins/authenticated-route-mixin'
const { get, set } = Ember
export default Ember.Route.extend(Authenticated, {
pageTitle: 'Media',
toggleDropzone () {
$('body').toggleClass('dz-open')
},
actions: {
uploadImage (file) {
const record = this.store.createRecord('file', {
filename: get(file, 'name'),
contentType: get(file, 'type'),
length: get(file, 'size')
})
$('body').removeClass('dz-open')
var settings = {
url: '/api/upload',
headers: {}
}
file.read().then(url => {
if (get(record, 'url') == null) {
set(record, 'url', url)
}
})
this.get('session').authorize('authorizer:token', (headerName, headerValue) => {
settings.headers[headerName] = headerValue
file.upload(settings).then(response => {
//set(record, 'url', response.headers.Location)
console.log(response)
return record.save()
}, () => {
record.rollback()
})
})
},
willTransition () {
$('body').unbind('dragenter dragleave', this.toggleDropzone)
},
didTransition () {
$('body').on('dragenter dragleave', this.toggleDropzone)
}
},
model () {
return this.store.findAll('file')
}
})
| import Ember from 'ember'
import Authenticated from 'ember-simple-auth/mixins/authenticated-route-mixin'
const { get, set } = Ember
export default Ember.Route.extend(Authenticated, {
pageTitle: 'Media',
toggleDropzone () {
$('body').toggleClass('dz-open')
},
actions: {
uploadImage (file) {
const record = this.store.createRecord('file', {
filename: get(file, 'name'),
contentType: get(file, 'type'),
length: get(file, 'size')
})
$('body').removeClass('dz-open')
var settings = {
url: '/api/upload',
headers: {}
}
file.read().then(url => {
if (get(record, 'url') == null) {
set(record, 'url', url)
}
})
this.get('session').authorize('authorizer:token', (headerName, headerValue) => {
settings.headers[headerName] = headerValue
file.upload(settings).then(response => {
for (var property in response.body) {
set(record, property, response.body[property])
}
return record.save()
}, () => {
record.rollback()
})
})
},
willTransition () {
$('body').unbind('dragenter dragleave', this.toggleDropzone)
},
didTransition () {
$('body').on('dragenter dragleave', this.toggleDropzone)
}
},
model () {
return this.store.findAll('file')
}
})
| Add record details after upload | Add record details after upload
| JavaScript | mit | small-cake/client,small-cake/client | ---
+++
@@ -33,8 +33,10 @@
settings.headers[headerName] = headerValue
file.upload(settings).then(response => {
- //set(record, 'url', response.headers.Location)
- console.log(response)
+ for (var property in response.body) {
+ set(record, property, response.body[property])
+ }
+
return record.save()
}, () => {
record.rollback() |
b74b69dc57fdf71e742b19ea22f6311199fe2752 | src/ui/constants/licenses.js | src/ui/constants/licenses.js | export const CC_LICENSES = [
{
value: 'Creative Commons Attribution 4.0 International',
url: 'https://creativecommons.org/licenses/by/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-ShareAlike 4.0 International',
url: 'https://creativecommons.org/licenses/by-sa/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-NoDerivatives 4.0 International',
url: 'https://creativecommons.org/licenses/by-nd/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-NonCommercial 4.0 International',
url: 'https://creativecommons.org/licenses/by-nc/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International',
url: 'https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International',
url: 'https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode',
},
];
export const NONE = 'None';
export const PUBLIC_DOMAIN = 'Public Domain';
export const OTHER = 'other';
export const COPYRIGHT = 'copyright';
| export const CC_LICENSES = [
{
value: 'Creative Commons Attribution 3.0',
url: 'https://creativecommons.org/licenses/by/3.0/legalcode',
},
{
value: 'Creative Commons Attribution 4.0 International',
url: 'https://creativecommons.org/licenses/by/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-ShareAlike 4.0 International',
url: 'https://creativecommons.org/licenses/by-sa/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-NoDerivatives 4.0 International',
url: 'https://creativecommons.org/licenses/by-nd/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-NonCommercial 4.0 International',
url: 'https://creativecommons.org/licenses/by-nc/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International',
url: 'https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International',
url: 'https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode',
},
];
export const NONE = 'None';
export const PUBLIC_DOMAIN = 'Public Domain';
export const OTHER = 'other';
export const COPYRIGHT = 'copyright';
| Add Creative Commons Attribution 3.0 license | Add Creative Commons Attribution 3.0 license
This license is used for many presentation recordings. It would be great
to have the license supported by the application directly and avoid
constantly looking for the license link.
| JavaScript | mit | lbryio/lbry-app,lbryio/lbry-electron,lbryio/lbry-electron,lbryio/lbry-electron,lbryio/lbry-app | ---
+++
@@ -1,4 +1,8 @@
export const CC_LICENSES = [
+ {
+ value: 'Creative Commons Attribution 3.0',
+ url: 'https://creativecommons.org/licenses/by/3.0/legalcode',
+ },
{
value: 'Creative Commons Attribution 4.0 International',
url: 'https://creativecommons.org/licenses/by/4.0/legalcode', |
56f1fce919464363aaf2beff7564de5552d3cf26 | src/configs/extra_colors.js | src/configs/extra_colors.js | export default {
black_pink: ['#36516e', '#f93b58', 0],
pink_black: ['#f93b58', '#36516e', 1],
white_blue: ['#45c0e9', '#efefef', 0],
blue_white: ['#45c0e9', '#efefef', 1],
beige_black: ['#eadaca', '#433947', 1],
black_white: ['#433947', '#efefef', 0]
}; | export default {
black_pink: ['#36516e', '#f93b58', 0],
pink_black: ['#f93b58', '#36516e', 1],
white_blue: ['#45c0e9', '#efefef', 0],
blue_white: ['#efefef', '#45c0e9', 1],
beige_black: ['#eadaca', '#433947', 1],
black_white: ['#433947', '#efefef', 0]
}; | Fix white blue colors for color picker | Fix white blue colors for color picker
| JavaScript | mit | g8extended/Character-Generator,g8extended/Character-Generator | ---
+++
@@ -2,7 +2,7 @@
black_pink: ['#36516e', '#f93b58', 0],
pink_black: ['#f93b58', '#36516e', 1],
white_blue: ['#45c0e9', '#efefef', 0],
- blue_white: ['#45c0e9', '#efefef', 1],
+ blue_white: ['#efefef', '#45c0e9', 1],
beige_black: ['#eadaca', '#433947', 1],
black_white: ['#433947', '#efefef', 0]
}; |
c27a38c04828f3ad670b195982583d6f2f3efdec | static/getMusic.js | static/getMusic.js | function getMusic(element) {
element = $(element);
var info_send = {
//method: 'info', // TODO possible method to get the song data: song 'info' or song 'id'
artist: element.data('artist'),
album: element.data('album'),
title: element.data('title')
};
console.log(info_send);
$.ajax({
type: 'GET',
url: '/api/getMusic',
data: info_send,
dataType: 'json', // The type of data that you're expecting back from the server.
//contentType: 'application/json; charset=utf-8', // Used 'application/json' only when is NOT GETing data with query string.
success: function (data) {
var player = $('#player');
var params = {
sourceType: 'youtube', // TODO, read from server.
source: data.music_path,
infoAlbumArt: data.image_path, // Currently not used.
infoAlbumTitle: data.album,
infoArtist: data.artist,
infoTitle: data.title,
infoLabel: data.label,
infoYear: data.year
};
player.trigger('loadNew', params);
},
error: function (data) {
console.log("Error:");
console.log(data);
}
});
} | function getMusic(element) {
element = $(element);
var info_send = {
//method: 'info', // TODO possible method to get the song data: song 'info' or song 'id'
artist: element.data('artist'),
album: element.data('album'),
title: element.data('title')
};
console.log(info_send);
$.ajax({
type: 'GET',
url: '/api/getMusic',
data: info_send,
dataType: 'json', // The type of data that you're expecting back from the server.
//contentType: 'application/json; charset=utf-8', // Used 'application/json' only when is NOT GETing data with query string.
success: function (data) {
var player = $('#player');
var params = {
sourceType: 'youtube', // TODO, read from server.
source: data.music_path,
infoAlbumArt: data.image_path, // Currently not used.
infoAlbumTitle: data.album,
infoArtist: data.artist,
infoTitle: data.title,
infoLabel: data.label,
infoYear: data.year
};
player.trigger('loadNew', params);
// Reset rating stars color.
$('#rating-1').css('color', '#aaa');
$('#rating-2').css('color', '#aaa');
$('#rating-3').css('color', '#aaa');
$('#rating-4').css('color', '#aaa');
$('#rating-5').css('color', '#aaa');
},
error: function (data) {
console.log("Error:");
console.log(data);
}
});
} | Add reset rating stars color when reload video. | Add reset rating stars color when reload video.
| JavaScript | apache-2.0 | edmundo096/MoodMusic,edmundo096/MoodMusic,edmundo096/MoodMusic | ---
+++
@@ -28,6 +28,13 @@
infoYear: data.year
};
player.trigger('loadNew', params);
+
+ // Reset rating stars color.
+ $('#rating-1').css('color', '#aaa');
+ $('#rating-2').css('color', '#aaa');
+ $('#rating-3').css('color', '#aaa');
+ $('#rating-4').css('color', '#aaa');
+ $('#rating-5').css('color', '#aaa');
},
error: function (data) {
console.log("Error:"); |
b7a3179b2d56e320a922401ecd66f6fcc87296ec | src/client/editor.js | src/client/editor.js | import { component } from "d3-component";
import { select, local } from "d3-selection";
const codeMirrorLocal = local();
// User interface component for the code editor.
export default component("div", "shadow")
.create(function ({ onChange }){
const codeMirror = codeMirrorLocal
.set(this, CodeMirror(this, {
lineNumbers: false,
mode: "htmlmixed"
}));
// Inlet provides the interactive sliders and color pickers.
Inlet(codeMirror);
codeMirror.on("change", function (editor, change){
if(change.origin === "setValue") return;
onChange(codeMirror.getValue());
});
})
.render(function ({ content }){
const codeMirror = codeMirrorLocal.get(this);
if(codeMirror.getValue() !== content){ // TODO use timestamp here?
codeMirror.setValue(content);
}
});
//export default function (dispatch, actions){
// return function (selection, state){
// var editor = selection.selectAll(".editor").data([1]);
// editor = editor.merge(
// editor.enter().append("div")
// .attr("class", "editor shadow")
// .each(function (){
// }));
//
// if(state.html){
// editor.each(function (){
// });
// }
// };
//}
| import { component } from "d3-component";
import { select, local } from "d3-selection";
const codeMirrorLocal = local();
// User interface component for the code editor.
export default component("div", "shadow")
.create(function (){
const my = codeMirrorLocal.set(this, {
codeMirror: CodeMirror(this, {
lineNumbers: false,
mode: "htmlmixed"
}),
onChange: undefined // Will be set in the render hook.
});
my.codeMirror.on("change", function (editor, change){
if(change.origin === "setValue") return;
my.onChange && my.onChange(my.codeMirror.getValue());
});
// Inlet provides the interactive sliders and color pickers.
Inlet(my.codeMirror);
})
.render(function ({ content, onChange }){
const my = codeMirrorLocal.get(this);
if(my.codeMirror.getValue() !== content){ // TODO use timestamp here?
my.codeMirror.setValue(content);
}
my.onChange = onChange;
});
//export default function (dispatch, actions){
// return function (selection, state){
// var editor = selection.selectAll(".editor").data([1]);
// editor = editor.merge(
// editor.enter().append("div")
// .attr("class", "editor shadow")
// .each(function (){
// }));
//
// if(state.html){
// editor.each(function (){
// });
// }
// };
//}
| Use correct listener in CodeMirror callbacks | Use correct listener in CodeMirror callbacks
| JavaScript | mit | curran/example-viewer,curran/example-viewer | ---
+++
@@ -5,26 +5,29 @@
// User interface component for the code editor.
export default component("div", "shadow")
- .create(function ({ onChange }){
- const codeMirror = codeMirrorLocal
- .set(this, CodeMirror(this, {
+ .create(function (){
+ const my = codeMirrorLocal.set(this, {
+ codeMirror: CodeMirror(this, {
lineNumbers: false,
mode: "htmlmixed"
- }));
+ }),
+ onChange: undefined // Will be set in the render hook.
+ });
+
+ my.codeMirror.on("change", function (editor, change){
+ if(change.origin === "setValue") return;
+ my.onChange && my.onChange(my.codeMirror.getValue());
+ });
// Inlet provides the interactive sliders and color pickers.
- Inlet(codeMirror);
-
- codeMirror.on("change", function (editor, change){
- if(change.origin === "setValue") return;
- onChange(codeMirror.getValue());
- });
+ Inlet(my.codeMirror);
})
- .render(function ({ content }){
- const codeMirror = codeMirrorLocal.get(this);
- if(codeMirror.getValue() !== content){ // TODO use timestamp here?
- codeMirror.setValue(content);
+ .render(function ({ content, onChange }){
+ const my = codeMirrorLocal.get(this);
+ if(my.codeMirror.getValue() !== content){ // TODO use timestamp here?
+ my.codeMirror.setValue(content);
}
+ my.onChange = onChange;
});
//export default function (dispatch, actions){ |
a0168c294d72f11e28287434653adbd2970fdf7a | util/debug.js | util/debug.js | "use strict";
const hasDebug = process.argv.indexOf("--debug") > -1;
const debug = (!hasDebug) ?
function() {} :
(message) => console.log(message);
debug.on = function() { return hasDebug; }
module.exports = debug; | "use strict";
const hasDebug = process.argv.indexOf("--debug") > -1;
const debug = (!hasDebug) ?
function() {} :
() => console.log.apply(console, arguments);
debug.on = function() { return hasDebug; };
module.exports = debug; | Debug should output everything pls | Debug should output everything pls
| JavaScript | mit | TeaSeaLancs/train-timeline,TeaSeaLancs/train-timeline | ---
+++
@@ -4,8 +4,8 @@
const debug = (!hasDebug) ?
function() {} :
- (message) => console.log(message);
+ () => console.log.apply(console, arguments);
-debug.on = function() { return hasDebug; }
+debug.on = function() { return hasDebug; };
module.exports = debug; |
fb7e4bc04e0a54e5a08f51e3f12c5982a6a1ca86 | string/compress.js | string/compress.js | // Method that performs basic string compression using the counts of repeated characters
function compressStr(str) {
var output = "", // will return this variable as final compressed string
currChar = "", // represents character we are searching for in string
currCount = "", // counts number of times character is repeated
// maxCount = ""; // maximum count
// iterate through entire string
for (i = 0; i < str.length; i++) {
// if the character we are searching for in string matches the character being looked at
if ( currChar !== str[i]) {
output = output + currChar + currCount; // output is sum of the output we have so far plus the character we have been searching for in our string plus the number of times that character is repeated
// maxCount = Math.max(maxCount, currCount); // choose the larger value between maxCount and currCount
currChar = str[i]; // move on to the next character
currCount = 1; // count resets to 1 since we have moved on to the next character
} else { // if there is a match add to the repeated count
currCount++;
}
output = output + currChar + currCount; // wrap up our final output by doing the same thing to what we did under the scenario where the character we are searching for in string matches the character being looked at
// maxCount = Math.max(maxCount, currCount);
return output;
}
}
| // Method that performs basic string compression using the counts of repeated characters
function compressStr(str) {
var output = "", // will return this variable as final compressed string
currChar = "", // represents character we are searching for in string
currCount = ""; // counts number of times character is repeated
// iterate through entire string
for (i = 0; i < str.length; i++) {
// if the character we are searching for in string matches the character being looked at
if (currChar !== str[i]) {
output = output + currChar + currCount; // output is sum of the output we have so far plus the character we have been searching for in our string plus the number of times that character is repeated
currChar = str[i]; // move on to the next character
currCount = 1; // count resets to 1 since we have moved on to the next character
} else { // if there is a match add to the repeated count
currCount++;
}
}
output = output + currChar + currCount; // wrap up our final output by doing the same thing to what we did under the scenario where currChar does not match the character being looked at
return output;
}
// test cases
compressStr("aaaaaaaa"); // expect to return "a8"
compressStr("abbcccdddd"); // expect to return "a1b2c3d4"
| Debug and add test cases | Debug and add test cases
| JavaScript | mit | derekmpham/interview-prep,derekmpham/interview-prep | ---
+++
@@ -3,30 +3,24 @@
function compressStr(str) {
var output = "", // will return this variable as final compressed string
currChar = "", // represents character we are searching for in string
- currCount = "", // counts number of times character is repeated
- // maxCount = ""; // maximum count
+ currCount = ""; // counts number of times character is repeated
// iterate through entire string
for (i = 0; i < str.length; i++) {
// if the character we are searching for in string matches the character being looked at
- if ( currChar !== str[i]) {
+ if (currChar !== str[i]) {
output = output + currChar + currCount; // output is sum of the output we have so far plus the character we have been searching for in our string plus the number of times that character is repeated
- // maxCount = Math.max(maxCount, currCount); // choose the larger value between maxCount and currCount
currChar = str[i]; // move on to the next character
currCount = 1; // count resets to 1 since we have moved on to the next character
} else { // if there is a match add to the repeated count
currCount++;
}
+ }
+ output = output + currChar + currCount; // wrap up our final output by doing the same thing to what we did under the scenario where currChar does not match the character being looked at
- output = output + currChar + currCount; // wrap up our final output by doing the same thing to what we did under the scenario where the character we are searching for in string matches the character being looked at
- // maxCount = Math.max(maxCount, currCount);
-
- return output;
- }
+ return output;
}
-
-
-
-
-
+// test cases
+compressStr("aaaaaaaa"); // expect to return "a8"
+compressStr("abbcccdddd"); // expect to return "a1b2c3d4" |
d4e5de834aeaee536df0ffd998be1f1660eee2d1 | lib/node_modules/@stdlib/math/base/dist/normal/pdf/examples/index.js | lib/node_modules/@stdlib/math/base/dist/normal/pdf/examples/index.js | 'use strict';
var pdf = require( './../lib' );
var x;
var mu;
var sigma;
var v;
var i;
for ( i = 0; i < 10; i++ ) {
x = Math.random() * 10;
mu = Math.random() * 10 - 5;
sigma = Math.random() * 20;
v = pdf( x, mu, sigma );
console.log( 'x: %d, mu: %d, sigma: %d, f(x;mu,sigma): %d', x, mu, sigma, v );
}
| 'use strict';
var pdf = require( './../lib' );
var sigma;
var mu;
var x;
var v;
var i;
for ( i = 0; i < 10; i++ ) {
x = Math.random() * 10;
mu = Math.random() * 10 - 5;
sigma = Math.random() * 20;
v = pdf( x, mu, sigma );
console.log( 'x: %d, mu: %d, sigma: %d, f(x;mu,sigma): %d', x, mu, sigma, v );
}
| Reorder vars according to length | Reorder vars according to length
| JavaScript | apache-2.0 | stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib | ---
+++
@@ -2,9 +2,9 @@
var pdf = require( './../lib' );
+var sigma;
+var mu;
var x;
-var mu;
-var sigma;
var v;
var i;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.