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
eb7b95c92e784c667a42803a6706a93e72155b5f
app/routes/login.js
app/routes/login.js
import Ember from 'ember'; import { inject as service } from '@ember/service'; import config from '../config/environment'; export default Ember.Route.extend({ queryParams: { rd: { refreshModel: true } }, routerService: service('-routing'), model: function(params) { // console.log("In login route"); var http = location.protocol; var slashes = http.concat("//"); var ishttp = (location.port === '') || (location.port === 80) || (location.port === 443); var host = slashes.concat(window.location.hostname) + (ishttp? "": ':'+location.port); var pathSuffix = decodeURIComponent(params.rd) || ""; var redirectUrl = host; // Append return route if one exists, ignore login route if (pathSuffix && pathSuffix.indexOf('/login') === -1) { redirectUrl += pathSuffix } // Append to query string if one exists, otherwise add one if (redirectUrl.indexOf("?") !== -1) { redirectUrl += "&token={girderToken}" } else { redirectUrl += "?token={girderToken}" } let url = config.apiUrl + '/oauth/provider?redirect=' + encodeURIComponent(redirectUrl); return Ember.$.getJSON(url); } });
import Ember from 'ember'; import { inject as service } from '@ember/service'; import config from '../config/environment'; export default Ember.Route.extend({ queryParams: { rd: { refreshModel: true } }, routerService: service('-routing'), model: function(params) { // console.log("In login route"); var http = location.protocol; var slashes = http.concat("//"); var ishttp = (location.port === '') || (location.port === 80) || (location.port === 443); var host = slashes.concat(window.location.hostname) + (ishttp? "": ':'+location.port); var pathSuffix = decodeURIComponent(params.rd || ""); var redirectUrl = host; // Append return route if one exists, ignore login route if (pathSuffix && pathSuffix.indexOf('/login') === -1) { redirectUrl += pathSuffix } // Append to query string if one exists, otherwise add one if (redirectUrl.indexOf("?") !== -1) { redirectUrl += "&token={girderToken}" } else { redirectUrl += "?token={girderToken}" } let url = config.apiUrl + '/oauth/provider?redirect=' + encodeURIComponent(redirectUrl); return Ember.$.getJSON(url); } });
Handle undefined/null rd - encodeURIComponent apparently returns a string in such cases -_-*
Handle undefined/null rd - encodeURIComponent apparently returns a string in such cases -_-*
JavaScript
mit
whole-tale/dashboard,whole-tale/dashboard,whole-tale/dashboard
--- +++ @@ -15,7 +15,7 @@ var slashes = http.concat("//"); var ishttp = (location.port === '') || (location.port === 80) || (location.port === 443); var host = slashes.concat(window.location.hostname) + (ishttp? "": ':'+location.port); - var pathSuffix = decodeURIComponent(params.rd) || ""; + var pathSuffix = decodeURIComponent(params.rd || ""); var redirectUrl = host; // Append return route if one exists, ignore login route if (pathSuffix && pathSuffix.indexOf('/login') === -1) {
d5c9087961757968e0bfadeef4ff21ae6b85d1fc
website/src/app/project/experiments/experiment/components/tasks/mc-experiment-task-details.component.js
website/src/app/project/experiments/experiment/components/tasks/mc-experiment-task-details.component.js
angular.module('materialscommons').component('mcExperimentTaskDetails', { templateUrl: 'app/project/experiments/experiment/components/tasks/mc-experiment-task-details.html', controller: MCExperimentTaskDetailsComponentController, bindings: { task: '=' } }); /*@ngInject*/ function MCExperimentTaskDetailsComponentController($scope, editorOpts, currentTask, templates, template, experimentsService, $stateParams, toast) { let ctrl = this; ctrl.currentTask = currentTask.get(); var t = templates.getTemplate('As Received'); template.set(t); $scope.editorOptions = editorOpts({height: 25, width: 20}); ctrl.selectedTemplate = (templateId, processId) => { console.log('selectedTemplate', templateId, processId); }; ctrl.updateTaskNote = () => { console.log('updateTaskNote'); if (ctrl.task.note === null) { ctrl.task.note = ""; } experimentsService.updateTask($stateParams.project_id, $stateParams.experiment_id, ctrl.task.id, {note: ctrl.task.note}) .then( () => null, () => toast.error('Unable to update task note.') ); }; }
angular.module('materialscommons').component('mcExperimentTaskDetails', { templateUrl: 'app/project/experiments/experiment/components/tasks/mc-experiment-task-details.html', controller: MCExperimentTaskDetailsComponentController, bindings: { task: '=' } }); /*@ngInject*/ function MCExperimentTaskDetailsComponentController($scope, editorOpts, currentTask, templates, template, experimentsService, $stateParams, toast) { let ctrl = this; ctrl.currentTask = currentTask.get(); var t = templates.getTemplate('As Received'); template.set(t); $scope.editorOptions = editorOpts({height: 25, width: 20}); ctrl.selectedTemplate = (templateId, processId) => { console.log('selectedTemplate', templateId, processId); }; ctrl.updateTaskNote = () => { if (ctrl.task.note === null) { return; } experimentsService.updateTask($stateParams.project_id, $stateParams.experiment_id, ctrl.task.id, {note: ctrl.task.note}) .then( () => null, () => toast.error('Unable to update task note.') ); }; }
Return if note is null.
Return if note is null.
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
--- +++ @@ -21,9 +21,8 @@ }; ctrl.updateTaskNote = () => { - console.log('updateTaskNote'); if (ctrl.task.note === null) { - ctrl.task.note = ""; + return; } experimentsService.updateTask($stateParams.project_id, $stateParams.experiment_id, ctrl.task.id,
17f052a0d77ecd2e61d1c57634e73c9c2d47a4ae
server/routes.js
server/routes.js
WebApp.connectHandlers.use("/package", function(request, response) { var url = `https://atmospherejs.com/a/packages/findByNames\ ?names=${request.url.split('/')[1]}`; var opts = {headers: {'Accept': 'application/json'}}; HTTP.get(url, opts, function(err, res) { var name = '', version, pubDate, starCount, installYear; var pl = res.data[0]; if (res.data.length !== 0) { name = pl.name; version = pl.latestVersion.version; pubDate = moment(pl.latestVersion.published.$date).format('MMM Do YYYY'); starCount = pl.starCount || 0; installYear = pl['installs-per-year'] || 0; } SSR.compileTemplate('icon', Assets.getText('icon.svg')); var width = 225 + name.length * 6.305555555555555; var icon = SSR.render('icon', {w: width, totalW: width+2, n: name, v: version, p: pubDate, s: starCount, i: installYear}); response.writeHead(200, {"Content-Type": "image/svg+xml"}); response.end(icon); }); });
WebApp.connectHandlers.use("/package", function(request, response) { var url = `https://atmospherejs.com/a/packages/findByNames\ ?names=${request.url.split('/')[1]}`; var opts = {headers: {'Accept': 'application/json'}}; HTTP.get(url, opts, function(err, res) { var name = '', pl = res.data[0], version, pubDate, starCount, installYear; if (res.data.length !== 0) { name = pl.name; version = pl.latestVersion.version; pubDate = moment(pl.latestVersion.published.$date).format('MMM Do YYYY'); starCount = pl.starCount || 0; installYear = pl['installs-per-year'] || 0; } SSR.compileTemplate('icon', Assets.getText('icon.svg')); var width = 225 + name.length * 6.305555555555555; var icon = SSR.render('icon', {w: width, totalW: width+2, n: name, v: version, p: pubDate, s: starCount, i: installYear}); response.writeHead(200, {"Content-Type": "image/svg+xml"}); response.end(icon); }); });
Use inline variable declartion to save LOC
Use inline variable declartion to save LOC
JavaScript
mit
sungwoncho/meteor-icon,sungwoncho/meteor-icon
--- +++ @@ -3,8 +3,7 @@ ?names=${request.url.split('/')[1]}`; var opts = {headers: {'Accept': 'application/json'}}; HTTP.get(url, opts, function(err, res) { - var name = '', version, pubDate, starCount, installYear; - var pl = res.data[0]; + var name = '', pl = res.data[0], version, pubDate, starCount, installYear; if (res.data.length !== 0) { name = pl.name;
28fa05687b037ff6bbc5c3afdf028224e2f93876
examples/todomvc-es6/webpack.config.js
examples/todomvc-es6/webpack.config.js
var path = require('path'); var webpackSettings = require('../../webpack-helper'); module.exports = webpackSettings({ entry: './js/app', output: { filename: './js/app.min.js', path: path.resolve('./js') }, resolve: { alias: { // Tungsten.js doesn't need jQuery, but backbone needs a subset of jQuery APIs. Backbone.native // implements tha minimum subset of required functionality 'jquery': 'backbone.native', // Aliases for the current version of tungstenjs above the ./examples directory. If // examples dir is run outside of main tungstenjs repo, remove these aliases // and use via normal modules directories (e.g., via NPM) 'tungstenjs/adaptors/backbone': path.join(__dirname, '../../adaptors/backbone'), 'tungstenjs/src/template/template': path.join(__dirname, '../../src/template/template'), 'tungstenjs': '../../src' } }, resolveLoader: { root: path.join(__dirname, 'node_modules'), modulesDirectories: ['node_modules', path.join(__dirname, '../../node_modules/')] }, devtool: '#source-map', loaders: [{test: /\.js$/, loader: 'babel?stage=0', exclude: /node_modules/}] });
var path = require('path'); var webpackSettings = require('../../webpack-helper'); module.exports = webpackSettings({ entry: './js/app', output: { filename: './js/app.min.js', path: path.resolve('./js') }, resolve: { alias: { // Tungsten.js doesn't need jQuery, but backbone needs a subset of jQuery APIs. Backbone.native // implements tha minimum subset of required functionality 'jquery': 'backbone.native', // Aliases for the current version of tungstenjs above the ./examples directory. If // examples dir is run outside of main tungstenjs repo, remove these aliases // and use via normal modules directories (e.g., via NPM) 'tungstenjs/adaptors/backbone': path.join(__dirname, '../../adaptors/backbone'), 'tungstenjs/src/template/template': path.join(__dirname, '../../src/template/template'), 'tungstenjs': '../../src' } }, resolveLoader: { root: path.join(__dirname, 'node_modules'), modulesDirectories: ['node_modules', path.join(__dirname, '../../node_modules/')] }, devtool: '#source-map', module: { loaders: [{test: /\.js$/, loader: 'babel?stage=0', exclude: /node_modules/}] } });
Fix for webpack es6 example loader
Fix for webpack es6 example loader
JavaScript
apache-2.0
cgvarela/tungstenjs,wayfair/tungstenjs,wayfair/tungstenjs
--- +++ @@ -25,7 +25,9 @@ modulesDirectories: ['node_modules', path.join(__dirname, '../../node_modules/')] }, devtool: '#source-map', - loaders: [{test: /\.js$/, loader: 'babel?stage=0', exclude: /node_modules/}] + module: { + loaders: [{test: /\.js$/, loader: 'babel?stage=0', exclude: /node_modules/}] + } });
5a2d909b3a7ec4e05a046d57e83c059061a94fe5
test/in-view.offset.spec.js
test/in-view.offset.spec.js
import test from 'ava'; import inView from '../src/in-view'; test('inView.offset returns the offset', t => { t.deepEqual(inView.offset(0), { top: 0, right: 0, bottom: 0, left: 0 }); }); test('inView.offset accepts a number', t => { t.deepEqual(inView.offset(10), { top: 10, right: 10, bottom: 10, left: 10 }); }); test('inView.offset accepts an object', t => { t.deepEqual(inView.offset({ top: 25, right: 50, bottom: 75, left: 100 }), { top: 25, right: 50, bottom: 75, left: 100 }); });
import test from 'ava'; import inView from '../src/in-view'; test('inView.offset returns the offset', t => { const stub = { top: 0, right: 0, bottom: 0, left: 0 }; t.deepEqual(inView.offset(0), stub); t.deepEqual(inView.offset(), stub); }); test('inView.offset accepts a number', t => { t.deepEqual(inView.offset(10), { top: 10, right: 10, bottom: 10, left: 10 }); }); test('inView.offset accepts an object', t => { t.deepEqual(inView.offset({ top: 25, right: 50, bottom: 75, left: 100 }), { top: 25, right: 50, bottom: 75, left: 100 }); });
Update offset tests for no arg
Update offset tests for no arg
JavaScript
mit
kudago/in-view,camwiegert/in-view
--- +++ @@ -2,12 +2,14 @@ import inView from '../src/in-view'; test('inView.offset returns the offset', t => { - t.deepEqual(inView.offset(0), { + const stub = { top: 0, right: 0, bottom: 0, left: 0 - }); + }; + t.deepEqual(inView.offset(0), stub); + t.deepEqual(inView.offset(), stub); }); test('inView.offset accepts a number', t => {
e58cf6f7719ad54d9f3fdb28e7ab7b03b763688a
troposphere/static/js/components/projects/resources/instance/details/sections/AllocationSourceSection.react.js
troposphere/static/js/components/projects/resources/instance/details/sections/AllocationSourceSection.react.js
import React from 'react'; import SelectMenu from 'components/common/ui/SelectMenu.react'; import stores from 'stores'; export default React.createClass({ // We probably won't keep state here // and instead will be based on the Allocation source // returned by the store given this.props.instance getInitialState: function() { return { current: stores.AllocationSourceStore[1].id } }, // This probably won't set local state // and instead will be passed on to an action onSourceChange: function(option) { this.setState({ current: option.id }); }, render: function() { return ( <div style={{ paddingTop: "20px"}}> <h2 className="t-title"> Allocation Source </h2> <SelectMenu defaultId={ this.state.currentSource } list={ stores.AllocationSourceStore } optionName={ item => item.name } onSelectChange={ this.onSourceChange } /> </div> ); } });
import React from 'react'; import SelectMenu from 'components/common/ui/SelectMenu.react'; import AllocationSourceGraph from 'components/common/AllocationSourceGraph.react'; import stores from 'stores'; export default React.createClass({ // We probably won't keep state here // and instead will be based on the Allocation source // returned by the store given this.props.instance getInitialState: function() { return { current: stores.AllocationSourceStore[1] } }, // This probably won't set local state // and instead will be passed on to an action onSourceChange: function(id) { let current = stores.AllocationSourceStore.find( item => item.id === id ); this.setState({ current }); }, render: function() { return ( <div style={{ paddingTop: "20px"}}> <h2 className="t-title"> Allocation Source </h2> <div style={{ marginBottom: "20px" }}> <SelectMenu defaultId={ this.state.current.id } list={ stores.AllocationSourceStore } optionName={ /* Callback */ item => item.name } onSelectChange={ this.onSourceChange } /> </div> <AllocationSourceGraph allocationSource={ this.state.current } /> </div> ); } });
Add Allocation Graph to Instance Details
Add Allocation Graph to Instance Details
JavaScript
apache-2.0
CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend
--- +++ @@ -1,5 +1,6 @@ import React from 'react'; import SelectMenu from 'components/common/ui/SelectMenu.react'; +import AllocationSourceGraph from 'components/common/AllocationSourceGraph.react'; import stores from 'stores'; export default React.createClass({ @@ -10,14 +11,18 @@ getInitialState: function() { return { - current: stores.AllocationSourceStore[1].id + current: stores.AllocationSourceStore[1] } }, // This probably won't set local state // and instead will be passed on to an action - onSourceChange: function(option) { - this.setState({ current: option.id }); + onSourceChange: function(id) { + let current = stores.AllocationSourceStore.find( + item => item.id === id + ); + + this.setState({ current }); }, render: function() { @@ -26,11 +31,17 @@ <h2 className="t-title"> Allocation Source </h2> + + <div style={{ marginBottom: "20px" }}> <SelectMenu - defaultId={ this.state.currentSource } + defaultId={ this.state.current.id } list={ stores.AllocationSourceStore } - optionName={ item => item.name } + optionName={ /* Callback */ item => item.name } onSelectChange={ this.onSourceChange } + /> + </div> + <AllocationSourceGraph + allocationSource={ this.state.current } /> </div> );
87bb881aa2e9d3f351f05d694e23eeed19e2dbac
app/components/Input.js
app/components/Input.js
import React, { PropTypes } from 'react'; import styles from 'styles/Input'; class Input extends React.Component { constructor(props) { super(props); this.state = { value: props.value }; } render() { const { value } = this.state; return ( <input type='text' className={styles.input} placeholder={this.props.placeholder} value={ value } autoFocus={ true } onChange={ e => { this.setState({ value: e.target.value }); }} onBlur={ () => { this.props.requersHandler(value); }} onKeyPress={ e => { if (e.key === 'Enter') { this.props.requersHandler(value); } }}/> ); } } Input.propsTypes = { value: PropTypes.string.isRequired, placeholder: PropTypes.string }; Input.defaultProps = { placeholder: 'Type query…' }; export default Input;
import React, { PropTypes } from 'react'; import styles from 'styles/Input'; class Input extends React.Component { constructor(props) { super(props); this.state = { value: props.value }; } componentWillReceiveProps({ value }) { this.setState({ value }); } render() { const { value } = this.state; return ( <input type='text' className={styles.input} placeholder={this.props.placeholder} value={ value } autoFocus={ true } onChange={ e => { this.setState({ value: e.target.value }); }} onBlur={ () => { this.props.requersHandler(value); }} onKeyPress={ e => { if (e.key === 'Enter') { this.props.requersHandler(value); } }}/> ); } } Input.propsTypes = { value: PropTypes.string.isRequired, placeholder: PropTypes.string }; Input.defaultProps = { placeholder: 'Type query…' }; export default Input;
Fix bug with broken receiving of values.
Fix bug with broken receiving of values.
JavaScript
mit
denysdovhan/victory-or-betrayal
--- +++ @@ -8,6 +8,10 @@ this.state = { value: props.value }; + } + + componentWillReceiveProps({ value }) { + this.setState({ value }); } render() {
a555611cc61e170731af449dfd695b64af469cb0
puppetboard/static/js/tables.js
puppetboard/static/js/tables.js
// Generated by CoffeeScript 1.4.0 (function() { var $; $ = jQuery; $(function() {}); if ($('th.default-sort').data()) { $('table.sortable').tablesort().data('tablesort').sort($("th.default-sort"), "desc"); } $('thead th.date').data('sortBy', function(th, td, tablesort) { var tdTime = td.text().replace("-", ""); return moment.utc(tdTime).unix(); }); $('input.filter-table').parent('div').removeClass('hide'); $("input.filter-table").on("keyup", function(e) { var ev, rex; rex = new RegExp($(this).val(), "i"); $(".searchable tr").hide(); $(".searchable tr").filter(function() { return rex.test($(this).text()); }).show(); if (e.keyCode === 27) { $(e.currentTarget).val(""); ev = $.Event("keyup"); ev.keyCode = 13; $(e.currentTarget).trigger(ev); return e.currentTarget.blur(); } }); }).call(this);
// Generated by CoffeeScript 1.4.0 (function() { var $; $ = jQuery; $(function() {}); if ($('th.default-sort').data()) { $('table.sortable').tablesort().data('tablesort').sort($("th.default-sort"), "desc"); } $('thead th.date').data('sortBy', function(th, td, tablesort) { var tdTime = td.text().replace("-", ""); return moment.utc(new Date(tdTime)).unix(); }); $('input.filter-table').parent('div').removeClass('hide'); $("input.filter-table").on("keyup", function(e) { var ev, rex; rex = new RegExp($(this).val(), "i"); $(".searchable tr").hide(); $(".searchable tr").filter(function() { return rex.test($(this).text()); }).show(); if (e.keyCode === 27) { $(e.currentTarget).val(""); ev = $.Event("keyup"); ev.keyCode = 13; $(e.currentTarget).trigger(ev); return e.currentTarget.blur(); } }); }).call(this);
Use js instead of moment to parse date to avoid warning
Use js instead of moment to parse date to avoid warning
JavaScript
apache-2.0
grandich/puppetboard,tparkercbn/puppetboard,johnzimm/puppetboard,grandich/puppetboard,tparkercbn/puppetboard,mterzo/puppetboard,puppet-community/puppetboard,puppet-community/puppetboard,johnzimm/puppetboard,voxpupuli/puppetboard,voxpupuli/puppetboard,johnzimm/xx-puppetboard,johnzimm/puppetboard,tparkercbn/puppetboard,voxpupuli/puppetboard,johnzimm/xx-puppetboard,grandich/puppetboard,mterzo/puppetboard,tparkercbn/puppetboard,mterzo/puppetboard,puppet-community/puppetboard,mterzo/puppetboard,johnzimm/xx-puppetboard,grandich/puppetboard,johnzimm/xx-puppetboard
--- +++ @@ -12,7 +12,7 @@ $('thead th.date').data('sortBy', function(th, td, tablesort) { var tdTime = td.text().replace("-", ""); - return moment.utc(tdTime).unix(); + return moment.utc(new Date(tdTime)).unix(); }); $('input.filter-table').parent('div').removeClass('hide');
ed4082d98d9cfeaeb4845bb21bf03fbdb76bee9b
server/vote.js
server/vote.js
// TODO: should the baseScore be stored, and updated at vote time? // This interface should change and become more OO, this'll do for now var Scoring = { // re-run the scoring algorithm on a single object updateObject: function(object) { // just count the number of votes for now var baseScore = MyVotes.find({votedFor: object._id}).count(); // now multiply by 'age' exponentiated // FIXME: timezones <-- set by server or is getTime() ok? var ageInHours = (new Date().getTime() - object.submitted) / (60 * 60 * 1000); object.score = baseScore * Math.pow(ageInHours + 2, -0.1375); }, // rerun all the scoring updateScores: function() { Posts.find().forEach(function(post) { Scoring.updateObject(post); Posts.update(post._id, {$set: {score: post.score}}); }); } } Meteor.methods({ voteForPost: function(post){ var user = this.userId(); if(!user) return false; var myvote = MyVotes.findOne({votedFor: post._id, user: user}); if(myvote) return false; MyVotes.insert({votedFor: post._id, user: user, vote: 1}); Scoring.updateObject(post); Posts.update(post._id, {$set: {score: post.score}}); return true; } });
// TODO: should the baseScore be stored, and updated at vote time? // This interface should change and become more OO, this'll do for now var Scoring = { // re-run the scoring algorithm on a single object updateObject: function(object) { // just count the number of votes for now var baseScore = object.votes; // now multiply by 'age' exponentiated // FIXME: timezones <-- set by server or is getTime() ok? var ageInHours = (new Date().getTime() - object.submitted) / (60 * 60 * 1000); object.score = baseScore * Math.pow(ageInHours + 2, -0.1375); }, // rerun all the scoring updateScores: function() { Posts.find().forEach(function(post) { Scoring.updateObject(post); Posts.update(post._id, {$set: {score: post.score}}); }); } } Meteor.methods({ voteForPost: function(post){ var userId = this.userId(); if(!userId) return false; // atomically update the post's votes var query = {_id: post._id, voters: {$ne: userId}}; var update = {$push: {voters: userId}, $inc: {votes: 1}}; Posts.update(query, update); // now update the post's score post = Posts.findOne(post._id); Scoring.updateObject(post); Posts.update(post._id, {$set: {score: post.score}}); return true; } });
Use an atomic update operation
Use an atomic update operation
JavaScript
mit
vlipco/startupcol-telescope,vlipco/startupcol-telescope
--- +++ @@ -6,7 +6,7 @@ updateObject: function(object) { // just count the number of votes for now - var baseScore = MyVotes.find({votedFor: object._id}).count(); + var baseScore = object.votes; // now multiply by 'age' exponentiated // FIXME: timezones <-- set by server or is getTime() ok? @@ -29,14 +29,16 @@ Meteor.methods({ voteForPost: function(post){ - var user = this.userId(); - if(!user) return false; - - var myvote = MyVotes.findOne({votedFor: post._id, user: user}); - if(myvote) return false; - - MyVotes.insert({votedFor: post._id, user: user, vote: 1}); + var userId = this.userId(); + if(!userId) return false; + // atomically update the post's votes + var query = {_id: post._id, voters: {$ne: userId}}; + var update = {$push: {voters: userId}, $inc: {votes: 1}}; + Posts.update(query, update); + + // now update the post's score + post = Posts.findOne(post._id); Scoring.updateObject(post); Posts.update(post._id, {$set: {score: post.score}});
344d59b373c49d889001c163e0c5f79ef4288807
explode.js
explode.js
HTMLCollection.prototype.eltEach = function(f) { for (var i = 0; i < this.length; i++) f(this[i]); } /* Just create a ton of closures. The background script will only hold on * to the ones representing shortened URLs. This saves us from having to * track which tab a request came from or doing any more DOM searching. */ document.links.eltEach(function(a) { chrome.extension.sendRequest({url: a.href}, function(resp) { a.href = resp['long-url']; if (resp.mungeUrl && a.textContent == resp.mungeUrl) a.textContent = resp['long-url']; if (resp.title && !a.title) a.title = resp.title; }); });
/* Just create a ton of closures. The background script will only hold on * to the ones representing shortened URLs. This saves us from having to * track which tab a request came from or doing any more DOM searching. */ function elts(root, t) { return root.getElementsByTagName(t); } function each(list, f) { for (var i = 0; i < list.length; i++) f(list[i]); } function reqLinks(root) { each(elts(root, 'a'), function(a) { chrome.extension.sendRequest({url: a.href}, function(resp) { a.href = resp['long-url']; if (resp.mungeUrl && a.textContent == resp.mungeUrl) a.textContent = resp['long-url']; if (resp.title && !a.title) a.title = resp.title; }); }); } /* Must do that once on init and again when a new node is inserted (e.g. * twitter.com AJAX updates) */ reqLinks(document); document.body.addEventListener('DOMNodeInserted', function(ev) { if (ev.srcElement.nodeType != 3) reqLinks(ev.srcElement); });
Watch DOMNodeInserted to catch AJAX updates
Watch DOMNodeInserted to catch AJAX updates
JavaScript
mit
decklin/explode
--- +++ @@ -1,17 +1,28 @@ -HTMLCollection.prototype.eltEach = function(f) { - for (var i = 0; i < this.length; i++) f(this[i]); -} - /* Just create a ton of closures. The background script will only hold on * to the ones representing shortened URLs. This saves us from having to * track which tab a request came from or doing any more DOM searching. */ -document.links.eltEach(function(a) { - chrome.extension.sendRequest({url: a.href}, function(resp) { - a.href = resp['long-url']; - if (resp.mungeUrl && a.textContent == resp.mungeUrl) - a.textContent = resp['long-url']; - if (resp.title && !a.title) - a.title = resp.title; +function elts(root, t) { return root.getElementsByTagName(t); } +function each(list, f) { for (var i = 0; i < list.length; i++) f(list[i]); } + +function reqLinks(root) { + each(elts(root, 'a'), function(a) { + chrome.extension.sendRequest({url: a.href}, function(resp) { + a.href = resp['long-url']; + if (resp.mungeUrl && a.textContent == resp.mungeUrl) + a.textContent = resp['long-url']; + if (resp.title && !a.title) + a.title = resp.title; + }); }); +} + +/* Must do that once on init and again when a new node is inserted (e.g. + * twitter.com AJAX updates) */ + +reqLinks(document); + +document.body.addEventListener('DOMNodeInserted', function(ev) { + if (ev.srcElement.nodeType != 3) + reqLinks(ev.srcElement); });
fc333067c2fd4eadfa0e25fa92a21c126c8bce5f
src/CasLogic.js
src/CasLogic.js
/* Copyright 2015 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; var Url = require ('url'); function getServiceUrl() { var parsedUrl = Url.parse(window.location.href); return parsedUrl.protocol + "//" + parsedUrl.host + parsedUrl.pathname; } module.exports = { getServiceUrl: getServiceUrl };
/* Copyright 2015 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; var url = require ('url'); function getServiceUrl() { var parsedUrl = url.parse(window.location.href); return parsedUrl.protocol + "//" + parsedUrl.host + parsedUrl.pathname; } module.exports = { getServiceUrl: getServiceUrl };
Rename required var to match convention
Rename required var to match convention
JavaScript
apache-2.0
matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk,aperezdc/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk
--- +++ @@ -16,10 +16,10 @@ 'use strict'; -var Url = require ('url'); +var url = require ('url'); function getServiceUrl() { - var parsedUrl = Url.parse(window.location.href); + var parsedUrl = url.parse(window.location.href); return parsedUrl.protocol + "//" + parsedUrl.host + parsedUrl.pathname; }
592844122cbf23f8445bd84189ffb365c066c11d
spec-e2e/tree_spec.js
spec-e2e/tree_spec.js
"use strict"; describe('Dependency tree', function(){ beforeEach(function() { browser.get('/app/#/staging2?doc=1&s=1'); }); describe('Sentence 1', function() { beforeEach(function() { }); it('displays a dependency tree (que is above cum)', function() { var nodes = element.all(by.css("div span span")); nodes.map(function(elm, index) { return { index: index, text: elm.getText(), location: elm.getLocation() }; }).then(function(nodeInfos) { var que; var cum; for (var index = 0; index < nodeInfos.length; ++index) { var element = nodeInfos[index]; if (element.text === "que") { que = element; } if (element.text === "Cum") { cum = element; } } expect(que).toBeDefined(); expect(cum).toBeDefined(); expect(que.location.y).toBeGreaterThan(cum.location.y); }); }); }); });
"use strict"; describe('Dependency tree', function(){ beforeEach(function() { browser.get('/app/#/staging2?doc=1&s=1'); }); var que; var cum; beforeEach(function() { var nodes = element.all(by.css("div span span")); nodes.map(function(elm, index) { return { index: index, text: elm.getText(), location: elm.getLocation(), element: elm }; }).then(function(nodeInfos) { for (var index = 0; index < nodeInfos.length; ++index) { var element = nodeInfos[index]; if (element.text === "que") { que = element; } if (element.text === "Cum") { cum = element; } } }); }); it('displays a dependency tree (que is above cum)', function() { expect(que).toBeDefined(); expect(cum).toBeDefined(); expect(que.location.y).toBeGreaterThan(cum.location.y); }); describe('head change', function() { xit('displays a dependency tree (que is above cum)', function() { expect(que).toBeDefined(); expect(cum).toBeDefined(); que.element.click(); cum.element.click(); expect(que.location.y).toBeLessThan(cum.location.y); }); }); });
Add test for head change to e2e tree spec
Add test for head change to e2e tree spec
JavaScript
mit
Masoumeh/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,Masoumeh/arethusa,PonteIneptique/arethusa,alpheios-project/arethusa,PonteIneptique/arethusa,fbaumgardt/arethusa,fbaumgardt/arethusa
--- +++ @@ -5,34 +5,43 @@ browser.get('/app/#/staging2?doc=1&s=1'); }); - describe('Sentence 1', function() { - beforeEach(function() { + var que; + var cum; + beforeEach(function() { + var nodes = element.all(by.css("div span span")); + nodes.map(function(elm, index) { + return { + index: index, + text: elm.getText(), + location: elm.getLocation(), + element: elm + }; + }).then(function(nodeInfos) { + for (var index = 0; index < nodeInfos.length; ++index) { + var element = nodeInfos[index]; + if (element.text === "que") { + que = element; + } + if (element.text === "Cum") { + cum = element; + } + } }); + }); - it('displays a dependency tree (que is above cum)', function() { - var nodes = element.all(by.css("div span span")); - nodes.map(function(elm, index) { - return { - index: index, - text: elm.getText(), - location: elm.getLocation() - }; - }).then(function(nodeInfos) { - var que; - var cum; - for (var index = 0; index < nodeInfos.length; ++index) { - var element = nodeInfos[index]; - if (element.text === "que") { - que = element; - } - if (element.text === "Cum") { - cum = element; - } - } - expect(que).toBeDefined(); - expect(cum).toBeDefined(); - expect(que.location.y).toBeGreaterThan(cum.location.y); - }); + it('displays a dependency tree (que is above cum)', function() { + expect(que).toBeDefined(); + expect(cum).toBeDefined(); + expect(que.location.y).toBeGreaterThan(cum.location.y); + }); + + describe('head change', function() { + xit('displays a dependency tree (que is above cum)', function() { + expect(que).toBeDefined(); + expect(cum).toBeDefined(); + que.element.click(); + cum.element.click(); + expect(que.location.y).toBeLessThan(cum.location.y); }); }); });
fe303bbc206c104c5b16d2f0730e090400a4a74f
gherkin/javascript/test/GherkinTest.js
gherkin/javascript/test/GherkinTest.js
/* eslint-env mocha */ const assert = require('assert') const cm = require('cucumber-messages').io.cucumber.messages const Gherkin = require('../src/Gherkin') describe('Gherkin', () => { it('parses gherkin from the file system', async () => { const messages = await streamToArray( Gherkin.fromPaths(['testdata/good/minimal.feature']) ) assert.strictEqual(messages.length, 3) }) it('parses gherkin from STDIN', async () => { const source = cm.Source.fromObject({ uri: 'test.feature', data: `Feature: Minimal Scenario: minimalistic Given the minimalism `, media: cm.Media.fromObject({ encoding: 'UTF-8', contentType: 'text/x.cucumber.gherkin+plain', }), }) const messages = await streamToArray(Gherkin.fromSources([source])) assert.strictEqual(messages.length, 3) }) }) function streamToArray(readableStream) { return new Promise((resolve, reject) => { const items = [] readableStream.on('data', items.push.bind(items)) readableStream.on('error', reject) readableStream.on('end', () => resolve(items)) }) }
/* eslint-env mocha */ const assert = require('assert') const cm = require('cucumber-messages').io.cucumber.messages const Gherkin = require('../src/Gherkin') describe('Gherkin', () => { it('parses gherkin from the file system', async () => { const messages = await streamToArray( Gherkin.fromPaths(['testdata/good/minimal.feature']) ) assert.strictEqual(messages.length, 3) }) it('parses gherkin from STDIN', async () => { const source = cm.Source.fromObject({ uri: 'test.feature', data: `Feature: Minimal Scenario: minimalistic Given the minimalism `, media: cm.Media.fromObject({ encoding: 'UTF-8', contentType: 'text/x.cucumber.gherkin+plain', }), }) const messages = await streamToArray(Gherkin.fromSources([source])) console.log('Messages', messages) assert.strictEqual(messages.length, 3) }) }) function streamToArray(readableStream) { return new Promise((resolve, reject) => { const items = [] readableStream.on('data', items.push.bind(items)) readableStream.on('error', reject) readableStream.on('end', () => resolve(items)) }) }
Add a bit of logging
Add a bit of logging
JavaScript
mit
cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber
--- +++ @@ -26,6 +26,7 @@ }) const messages = await streamToArray(Gherkin.fromSources([source])) + console.log('Messages', messages) assert.strictEqual(messages.length, 3) }) })
63644f5638a1c42dca779c683df998749fa892eb
ghostjs-examples/test/use_page_test.js
ghostjs-examples/test/use_page_test.js
import ghost from 'ghostjs' import assert from 'assert' import localServer from './fixtures/server.js' describe('ghost#usePage', () => { before(localServer) after(localServer.stop) it('we can switch pages using usePage()', async () => { await ghost.open('http://localhost:8888/basic_content.html') let myElement = await ghost.findElement('#popupLink') await myElement.click() await ghost.wait(5000) await ghost.waitForPage('form.html') // Switch to the popup context ghost.usePage('form.html') // Find an element which is in the new page, but not the first. let checkbox = await ghost.findElement('#checkbox1') assert.equal(await checkbox.isVisible(), true) // Switch back to the main page. ghost.usePage() // The checkbox should not exist let goAwayCheckbox = await ghost.findElement('#checkbox1') assert.equal(goAwayCheckbox, null) }) })
import ghost from 'ghostjs' import assert from 'assert' import localServer from './fixtures/server.js' describe('ghost#usePage', () => { before(localServer) after(localServer.stop) it('we can switch pages using usePage()', async () => { await ghost.open('http://localhost:8888/basic_content.html') let myElement = await ghost.findElement('#popupLink') await myElement.click() await ghost.wait(5000) await ghost.waitForPage('form.html') // Switch to the popup context await ghost.usePage('form.html') // Find an element which is in the new page, but not the first. let checkbox = await ghost.findElement('#checkbox1') assert.equal(await checkbox.isVisible(), true) // Switch back to the main page. await ghost.usePage() // The checkbox should not exist let goAwayCheckbox = await ghost.findElement('#checkbox1') assert.equal(goAwayCheckbox, null) }) })
Update test to use await.
Update test to use await.
JavaScript
mit
KevinGrandon/ghostjs,KevinGrandon/ghostjs
--- +++ @@ -17,14 +17,14 @@ await ghost.waitForPage('form.html') // Switch to the popup context - ghost.usePage('form.html') + await ghost.usePage('form.html') // Find an element which is in the new page, but not the first. let checkbox = await ghost.findElement('#checkbox1') assert.equal(await checkbox.isVisible(), true) // Switch back to the main page. - ghost.usePage() + await ghost.usePage() // The checkbox should not exist let goAwayCheckbox = await ghost.findElement('#checkbox1')
dda1c3d11fce53825c73e6d7e0c43115d57aaf63
django/metadata_categorization/metadata_categorization/static/metadata_categorization/metadata.js
django/metadata_categorization/metadata_categorization/static/metadata_categorization/metadata.js
$(document).ready(function() { var container = document.getElementById("queue"); function plusRenderer (instance, td, row, col, prop, value, cellProperties) { var plusIcon = '<svg class="icon icon--plus" viewBox="0 0 5 5" height="20px" width="20px">' + '<path d="M2 1 h1 v1 h1 v1 h-1 v1 h-1 v-1 h-1 v-1 h1 z" />' + '</svg>'; $(td).empty().append(plusIcon); } var hot = new Handsontable(container, { data: summaryRecords, height: 396, rowHeaders: true, stretchH: 'all', sortIndicator: true, columnSorting: true, contextMenu: true, colHeaders: [ "", "Submitted cell line", "Cell line", "Cell type", "Anatomy", "Species", "Disease" ], columns: [ {data: "", renderer: plusRenderer}, {data: "sourceCellLine"}, {data: "annotCellLine"}, {data: "sourceCellType"}, {data: "sourceCellAnatomy"}, {data: "sourceSpecies"}, {data: "sourceDisease"} ] }); })
$(document).ready(function() { var container = document.getElementById("queue"); function plusRenderer (instance, td, row, col, prop, value, cellProperties) { var plusIcon = '<svg class="icon icon--plus" viewBox="0 0 5 5" height="20px" width="20px">' + '<path d="M2 1 h1 v1 h1 v1 h-1 v1 h-1 v-1 h-1 v-1 h1 z" />' + '</svg>'; $(td).empty().append(plusIcon); } var hot = new Handsontable(container, { data: summaryRecords, height: 396, rowHeaders: true, stretchH: 'all', sortIndicator: true, columnSorting: true, contextMenu: true, colWidths: [8, , , , , ,], colHeaders: [ "", "Submitted cell line", "Cell line", "Cell type", "Anatomy", "Species", "Disease" ], columns: [ {data: "", renderer: plusRenderer}, {data: "sourceCellLine"}, {data: "annotCellLine"}, {data: "sourceCellType"}, {data: "sourceCellAnatomy"}, {data: "sourceSpecies"}, {data: "sourceDisease"} ] }); })
Trim width of toggle icon column
Trim width of toggle icon column
JavaScript
cc0-1.0
NCBI-Hackathons/Metadata_categorization,NCBI-Hackathons/Metadata_categorization,NCBI-Hackathons/Metadata_categorization,NCBI-Hackathons/Metadata_categorization,NCBI-Hackathons/Metadata_categorization,NCBI-Hackathons/Metadata_categorization,NCBI-Hackathons/Metadata_categorization
--- +++ @@ -22,6 +22,7 @@ sortIndicator: true, columnSorting: true, contextMenu: true, + colWidths: [8, , , , , ,], colHeaders: [ "", "Submitted cell line", "Cell line", "Cell type", "Anatomy", "Species", "Disease"
71cbc6c9602234f00279e7ff4eb6a8bb282d23b1
lib/util/getSession.js
lib/util/getSession.js
// Args exports.required = ['jar']; // Define exports.func = function (args) { var cookies = args.jar.getCookies('https://www.roblox.com'); for (var key in cookies) { if (cookies.hasOwnProperty(key) && cookies[key].key === '.ROBLOSECURITY') { return cookies[key].value; } } };
// Includes var settings = require('../../settings.json'); // Args exports.required = ['jar']; // Define exports.func = function (args) { var jar = args.jar; if (settings.session_only) { return jar.session; } else { var cookies = jar.getCookies('https://www.roblox.com'); for (var key in cookies) { if (cookies.hasOwnProperty(key) && cookies[key].key === '.ROBLOSECURITY') { return cookies[key].value; } } } };
Add support for session only cookies
Add support for session only cookies
JavaScript
mit
OnlyTwentyCharacters/roblox-js,sentanos/roblox-js,FroastJ/roblox-js
--- +++ @@ -1,12 +1,20 @@ +// Includes +var settings = require('../../settings.json'); + // Args exports.required = ['jar']; // Define exports.func = function (args) { - var cookies = args.jar.getCookies('https://www.roblox.com'); - for (var key in cookies) { - if (cookies.hasOwnProperty(key) && cookies[key].key === '.ROBLOSECURITY') { - return cookies[key].value; + var jar = args.jar; + if (settings.session_only) { + return jar.session; + } else { + var cookies = jar.getCookies('https://www.roblox.com'); + for (var key in cookies) { + if (cookies.hasOwnProperty(key) && cookies[key].key === '.ROBLOSECURITY') { + return cookies[key].value; + } } } };
cc86bdf49424cfb8a35f3a8f7259897e6dadf6d8
src/assets/js/main.js
src/assets/js/main.js
/*global window */ import BitFlux from './bitflux'; var seed = window.location.search.split('seed=')[1]; if (seed) { Math.seedrandom(seed); } BitFlux.app() .fetchCoinbaseProducts(true) .run('#app-container');
/*global window */ import BitFlux from './bitflux'; // A query string (?seed=) can be added to the URL // to seed the random number generator. // For example: ?seed=yourseed var seed = window.location.search.split('seed=')[1]; if (seed) { Math.seedrandom(seed); } BitFlux.app() .fetchCoinbaseProducts(true) .run('#app-container');
Document usage of query string for seeding random number generator
Document usage of query string for seeding random number generator
JavaScript
mit
jleft/BitFlux,ScottLogic/d3fc-showcase,ScottLogic/BitFlux,ScottLogic/d3fc-showcase,rjmcneill/d3fc-showcase,djmiley/d3fc-showcase,jleft/BitFlux,jdhodges/d3fc-showcase,jdhodges/d3fc-showcase,ScottLogic/d3fc-showcase,jleft/d3fc-showcase,ScottLogic/BitFlux,djmiley/d3fc-showcase,jleft/d3fc-showcase,rjmcneill/d3fc-showcase,djmiley/d3fc-showcase,jleft/d3fc-showcase,rjmcneill/d3fc-showcase,jdhodges/d3fc-showcase
--- +++ @@ -1,6 +1,9 @@ /*global window */ import BitFlux from './bitflux'; +// A query string (?seed=) can be added to the URL +// to seed the random number generator. +// For example: ?seed=yourseed var seed = window.location.search.split('seed=')[1]; if (seed) { Math.seedrandom(seed);
d47412f9beb684e9a8ae7d32b5c50f0b71116c78
docs/webpack.mix.js
docs/webpack.mix.js
const mix = require('laravel-mix') const tailwind = require('./../lib/index.js') const config = require('./tailwind.js') const fs = require('fs') fs.writeFileSync('./tailwind.json', JSON.stringify(config)) mix.setPublicPath('source/') mix .js('source/_assets/js/nav.js', 'source/js') .js('source/_assets/js/app.js', 'source/js') .less('source/_assets/less/main.less', 'css') .options({ postCss: [ tailwind('tailwind.js'), ] }) .version()
const mix = require('laravel-mix') const tailwind = require('./../lib/index.js') const config = require('./tailwind.js') const fs = require('fs') fs.writeFileSync('./tailwind.json', JSON.stringify(config)) mix.setPublicPath('source') mix .js('source/_assets/js/nav.js', 'source/js') .js('source/_assets/js/app.js', 'source/js') .less('source/_assets/less/main.less', 'source/css') .options({ postCss: [ tailwind('tailwind.js'), ] }) .version()
Remove trailing slash in public path to allow consistent output directory format
Remove trailing slash in public path to allow consistent output directory format
JavaScript
mit
tailwindcss/tailwindcss,tailwindlabs/tailwindcss,tailwindlabs/tailwindcss,tailwindlabs/tailwindcss
--- +++ @@ -6,12 +6,12 @@ fs.writeFileSync('./tailwind.json', JSON.stringify(config)) -mix.setPublicPath('source/') +mix.setPublicPath('source') mix .js('source/_assets/js/nav.js', 'source/js') .js('source/_assets/js/app.js', 'source/js') - .less('source/_assets/less/main.less', 'css') + .less('source/_assets/less/main.less', 'source/css') .options({ postCss: [ tailwind('tailwind.js'),
3a84aabc082f26673c25e0b29694df019bbbb644
src/helpers.js
src/helpers.js
// @flow export function roundValue(value: number | string | void): number | string { if (typeof value !== 'number') { return '—'; } const parsedValue = parseFloat(value.toString()); const sizes = ['', ' K', ' M', ' G', ' T', ' P', ' E', ' Z', ' Y']; if (parsedValue === 0) { return '0'; } let x = 0; while (Math.pow(1000, x + 1) < Math.abs(parsedValue)) { x++; } let prefix = (parsedValue / Math.pow(1000, x)).toFixed(2).toString(); if (x === 0) { prefix = value.toFixed(2).toString(); } let tailToCut = 0; while (prefix[prefix.length - (tailToCut + 1)] === '0') { tailToCut++; } if (prefix[prefix.length - (tailToCut + 1)] === '.') { tailToCut++; } return prefix.substring(0, prefix.length - tailToCut) + (sizes[x] || ''); } export function getJSONContent(data: { [key: string]: any }): string { return 'data:text/plain;charset=utf-8,' + encodeURIComponent(JSON.stringify(data, null, 2)); }
// @flow export function roundValue(value: number | string | void, placeholder: boolean | void): number | string { if (typeof value !== 'number') { return placeholder ? '—' : ''; } const parsedValue = parseFloat(value.toString()); const sizes = ['', ' K', ' M', ' G', ' T', ' P', ' E', ' Z', ' Y']; if (parsedValue === 0) { return '0'; } let x = 0; while (Math.pow(1000, x + 1) < Math.abs(parsedValue)) { x++; } let prefix = (parsedValue / Math.pow(1000, x)).toFixed(2).toString(); if (x === 0) { prefix = value.toFixed(2).toString(); } let tailToCut = 0; while (prefix[prefix.length - (tailToCut + 1)] === '0') { tailToCut++; } if (prefix[prefix.length - (tailToCut + 1)] === '.') { tailToCut++; } return prefix.substring(0, prefix.length - tailToCut) + (sizes[x] || ''); } export function getJSONContent(data: { [key: string]: any }): string { return 'data:text/plain;charset=utf-8,' + encodeURIComponent(JSON.stringify(data, null, 2)); }
Add custom placeholder for empty value
Add custom placeholder for empty value
JavaScript
mit
moira-alert/web2.0,moira-alert/web2.0,moira-alert/web2.0,moira-alert/web2.0
--- +++ @@ -1,7 +1,7 @@ // @flow -export function roundValue(value: number | string | void): number | string { +export function roundValue(value: number | string | void, placeholder: boolean | void): number | string { if (typeof value !== 'number') { - return '—'; + return placeholder ? '—' : ''; } const parsedValue = parseFloat(value.toString()); const sizes = ['', ' K', ' M', ' G', ' T', ' P', ' E', ' Z', ' Y'];
08fb39f1ba6c11279755ca883bca57a3760cd5b1
erpnext/accounts/doctype/purchase_taxes_and_charges_template/purchase_taxes_and_charges_template.js
erpnext/accounts/doctype/purchase_taxes_and_charges_template/purchase_taxes_and_charges_template.js
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt cur_frm.cscript.tax_table = "Purchase Taxes and Charges"; {% include "erpnext/public/js/controllers/accounts.js" %} frappe.ui.form.on("Purchase Taxes and Charges", "add_deduct_tax", function(doc, cdt, cdn) { var d = locals[cdt][cdn]; if(!d.category && d.add_deduct_tax) { msgprint(__("Please select Category first")); d.add_deduct_tax = ''; } else if(d.category != 'Total' && d.add_deduct_tax == 'Deduct') { msgprint(__("Cannot deduct when category is for 'Valuation' or 'Valuation and Total'")); d.add_deduct_tax = ''; } refresh_field('add_deduct_tax', d.name, 'taxes'); });
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt cur_frm.cscript.tax_table = "Purchase Taxes and Charges"; {% include "erpnext/public/js/controllers/accounts.js" %} frappe.ui.form.on("Purchase Taxes and Charges", "add_deduct_tax", function(doc, cdt, cdn) { var d = locals[cdt][cdn]; if(!d.category && d.add_deduct_tax) { msgprint(__("Please select Category first")); d.add_deduct_tax = ''; } else if(d.category != 'Total' && d.add_deduct_tax == 'Deduct') { msgprint(__("Cannot deduct when category is for 'Valuation' or 'Valuation and Total'")); d.add_deduct_tax = ''; } refresh_field('add_deduct_tax', d.name, 'taxes'); }); frappe.ui.form.on("Purchase Taxes and Charges", "category", function(doc, cdt, cdn) { var d = locals[cdt][cdn]; if (d.category != 'Total' && d.add_deduct_tax == 'Deduct') { msgprint(__("Cannot deduct when category is for 'Valuation' or 'Vaulation and Total'")); d.add_deduct_tax = ''; } refresh_field('add_deduct_tax', d.name, 'taxes'); })
Validate on changing from Total to Valuation/Valuation&Total when add_deduct_tax is 'Deduct'
Validate on changing from Total to Valuation/Valuation&Total when add_deduct_tax is 'Deduct'
JavaScript
agpl-3.0
indictranstech/erpnext,njmube/erpnext,geekroot/erpnext,geekroot/erpnext,gsnbng/erpnext,gsnbng/erpnext,indictranstech/erpnext,indictranstech/erpnext,indictranstech/erpnext,gsnbng/erpnext,geekroot/erpnext,Aptitudetech/ERPNext,gsnbng/erpnext,geekroot/erpnext,njmube/erpnext,njmube/erpnext,njmube/erpnext
--- +++ @@ -18,3 +18,13 @@ } refresh_field('add_deduct_tax', d.name, 'taxes'); }); + +frappe.ui.form.on("Purchase Taxes and Charges", "category", function(doc, cdt, cdn) { + var d = locals[cdt][cdn]; + + if (d.category != 'Total' && d.add_deduct_tax == 'Deduct') { + msgprint(__("Cannot deduct when category is for 'Valuation' or 'Vaulation and Total'")); + d.add_deduct_tax = ''; + } + refresh_field('add_deduct_tax', d.name, 'taxes'); +})
50cd621ca1ea40bdbb668f79672a106fa079a017
client/models/albums.js
client/models/albums.js
define(function(require, exports, module) { var uuid = require("lib/uuid"); function Album(options) { this.id = options.id || options._id; this._id = options.id || options._id; this.name = options.name; this.artist = options.artist; this.tracks = []; this.artistId = options.artistId || null; } Album.id = uuid; Album.prototype = { }; return { Album: Album }; });
define(function(require, exports, module) { var uuid = require("lib/uuid"); function Album(options) { this.id = options.id || options._id; this._id = options.id || options._id; this.name = options.name; this.artist = options.artist; this.tracks = options.tracks || []; this.artistId = options.artistId || null; } Album.id = uuid; Album.prototype = { }; return { Album: Album }; });
Fix tracks for the Album model
Fix tracks for the Album model
JavaScript
agpl-3.0
tOkeshu/GhettoBlaster,tOkeshu/GhettoBlaster
--- +++ @@ -6,7 +6,7 @@ this._id = options.id || options._id; this.name = options.name; this.artist = options.artist; - this.tracks = []; + this.tracks = options.tracks || []; this.artistId = options.artistId || null; }
ee836603b6753856ee3bb20c38df8482fe2b9508
client/screens/index.js
client/screens/index.js
import React, { PropTypes } from 'react'; const AppWrapper = (props) => ( <div> {props.children} </div> ); AppWrapper.propTypes = { children: PropTypes.any, }; export default AppWrapper;
import React, { PropTypes, Component } from 'react'; class AppWrapper extends Component { componentWillMount(){ // check parse user, if logged in then redirect to app page } componentWillUnmount(){ // unsubscribe from parse updates } componentWillReceiveProps(nextProps) { // if (!this.props.isAuthenticated && nextProps.isAuthenticated) { // true after successful submit // this.props.handleRedirect(); // } } render() { return (<div> {this.props.children} </div>); } } AppWrapper.propTypes = { children: PropTypes.any, }; export default AppWrapper;
Convert wrapper to component where object subscriptions can be handled.
Convert wrapper to component where object subscriptions can be handled.
JavaScript
mit
brewsoftware/hang-ten,brewsoftware/hang-ten
--- +++ @@ -1,11 +1,29 @@ -import React, { PropTypes } from 'react'; +import React, { PropTypes, Component } from 'react'; -const AppWrapper = (props) => ( - <div> - {props.children} - </div> -); +class AppWrapper extends Component { + componentWillMount(){ + // check parse user, if logged in then redirect to app page + + } + componentWillUnmount(){ + // unsubscribe from parse updates + + } + componentWillReceiveProps(nextProps) { + +// if (!this.props.isAuthenticated && nextProps.isAuthenticated) { // true after successful submit +// this.props.handleRedirect(); +// } + } + + render() { + return (<div> + {this.props.children} + </div>); + + } +} AppWrapper.propTypes = { children: PropTypes.any,
8eec7138a327a2e2c98a1c08bab874b518857347
src/app/Hits/index.js
src/app/Hits/index.js
import IconAdd from 'react-icons/lib/md/add-circle' import React from 'react' import Stats from '../Stats' import Hit from '../Hit' import './style.scss' function renderHasMore (refine, searching) { return ( <footer className='tc pv3 ph3 ph4-l'> <a onClick={refine} className='dim link ttu lh-solid cb-ns db dib-l mb2 pb3 ph4 pointer sans-serif normal moon-gray'> <IconAdd size={34} className='db tc w-100 pb2' /> <span className='f6'>Load More</span> </a> </footer> ) } function CustomHits (props) { const {toggle, get, hits, refine, hasMore, searching} = props const hitsProps = { toggle, get } return ( <div data-app='hits' className='hits'> <Stats /> <div className='pa2'> {hits.map((item, key) => <Hit item={item} key={key} {...hitsProps} />)} </div> {hasMore && renderHasMore(refine, searching)} </div> ) } export default CustomHits
import IconAdd from 'react-icons/lib/md/add-circle' import React from 'react' import Stats from '../Stats' import Hit from '../Hit' import './style.scss' function renderHasMore (refine, searching) { return ( <footer className='tc pv3 ph3 ph4-l'> <a onClick={refine} className='dim link ttu lh-solid cb-ns db dib-l mb2 pb3 ph4 pointer sans-serif normal light-silver'> <IconAdd size={34} className='db tc w-100 pb2' /> <span className='f6'>Load More</span> </a> </footer> ) } function CustomHits (props) { const {toggle, get, hits, refine, hasMore, searching} = props const hitsProps = { toggle, get } return ( <div data-app='hits' className='hits'> <Stats /> <div className='pa2'> {hits.map((item, key) => <Hit item={item} key={key} {...hitsProps} />)} </div> {hasMore && renderHasMore(refine, searching)} </div> ) } export default CustomHits
Align load more button style
Align load more button style
JavaScript
mit
windtoday/windtoday-app,windtoday/windtoday-marketplace,windtoday/windtoday-marketplace
--- +++ @@ -11,7 +11,7 @@ <footer className='tc pv3 ph3 ph4-l'> <a onClick={refine} - className='dim link ttu lh-solid cb-ns db dib-l mb2 pb3 ph4 pointer sans-serif normal moon-gray'> + className='dim link ttu lh-solid cb-ns db dib-l mb2 pb3 ph4 pointer sans-serif normal light-silver'> <IconAdd size={34} className='db tc w-100 pb2' /> <span className='f6'>Load More</span> </a>
f2e62ff439097fd2e313f9d3ea25a5992ff904b1
src/components/structures/HomePage.js
src/components/structures/HomePage.js
/* Copyright 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; var React = require("react"); var MatrixClientPeg = require('matrix-react-sdk/lib/MatrixClientPeg'); var sdk = require('matrix-react-sdk'); module.exports = React.createClass({ displayName: 'HomePage', propTypes: { teamToken: React.PropTypes.string.isRequired, collapsedRhs: React.PropTypes.bool, }, render: function() { // const SimpleRoomHeader = sdk.getComponent('rooms.SimpleRoomHeader'); // <SimpleRoomHeader title="Welcome to Riot" collapsedRhs={ this.props.collapsedRhs }/> return ( <div className="mx_HomePage"> <iframe src={`http://localhost:7000/static/${this.props.teamToken}/welcome.html`} style={{width: '100%', border: 'none'}}/> </div> ); } });
/* Copyright 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; var React = require("react"); var MatrixClientPeg = require('matrix-react-sdk/lib/MatrixClientPeg'); var sdk = require('matrix-react-sdk'); module.exports = React.createClass({ displayName: 'HomePage', propTypes: { teamServerUrl: React.PropTypes.string.isRequired, teamToken: React.PropTypes.string.isRequired, collapsedRhs: React.PropTypes.bool, }, render: function() { // const SimpleRoomHeader = sdk.getComponent('rooms.SimpleRoomHeader'); // <SimpleRoomHeader title="Welcome to Riot" collapsedRhs={ this.props.collapsedRhs }/> return ( <div className="mx_HomePage"> <iframe src={`${this.props.teamServerUrl}/static/${this.props.teamToken}/welcome.html`} style={{width: '100%', border: 'none'}}/> </div> ); } });
Use RTS URL passed through
Use RTS URL passed through
JavaScript
apache-2.0
vector-im/vector-web,vector-im/vector-web,vector-im/vector-web,vector-im/riot-web,vector-im/riot-web,vector-im/vector-web,vector-im/riot-web,martindale/vector,vector-im/riot-web,martindale/vector,vector-im/riot-web,vector-im/vector-web,vector-im/riot-web
--- +++ @@ -24,6 +24,7 @@ displayName: 'HomePage', propTypes: { + teamServerUrl: React.PropTypes.string.isRequired, teamToken: React.PropTypes.string.isRequired, collapsedRhs: React.PropTypes.bool, }, @@ -34,7 +35,7 @@ return ( <div className="mx_HomePage"> - <iframe src={`http://localhost:7000/static/${this.props.teamToken}/welcome.html`} style={{width: '100%', border: 'none'}}/> + <iframe src={`${this.props.teamServerUrl}/static/${this.props.teamToken}/welcome.html`} style={{width: '100%', border: 'none'}}/> </div> ); }
89d4767c7e7a8460382ad432b54c99abc8603a57
gulp-utils/index.js
gulp-utils/index.js
var path = require('path'); var del = require('del'); var DISTRIBUTION_DIRECTORY = "lib"; /** * Gets a path relative to the distribution directory * Pass in any number of paths and they will be joined up. */ function getDistPath() { var paths = Array.prototype.slice.call(arguments); paths.unshift(DISTRIBUTION_DIRECTORY); return path.join.apply(null, paths); } /** * Removes the DISTRIBUTION_DIRECTORY and all files inside it */ function removeDistFiles(callback) { return del([DISTRIBUTION_DIRECTORY], callback); } module.exports = { getDistPath, removeDistFiles };
var path = require('path'); var del = require('del'); module.exports = { getDistPath: getDistPath, removeDistFiles: removeDistFiles }; var DISTRIBUTION_DIRECTORY = "lib"; /** * Gets a path relative to the distribution directory * Pass in any number of paths and they will be joined up. */ function getDistPath() { var paths = Array.prototype.slice.call(arguments); paths.unshift(DISTRIBUTION_DIRECTORY); return path.join.apply(null, paths); } /** * Removes the DISTRIBUTION_DIRECTORY and all files inside it */ function removeDistFiles(callback) { return del([DISTRIBUTION_DIRECTORY], callback); }
Revert "coding style" - gulp config is not ES6
Revert "coding style" - gulp config is not ES6 This reverts commit 3073fbb0c140b641122eb6b641e788895e281061.
JavaScript
mit
anyWareSculpture/anyware,anyWareSculpture/anyware
--- +++ @@ -1,5 +1,11 @@ var path = require('path'); var del = require('del'); + +module.exports = { + getDistPath: getDistPath, + removeDistFiles: removeDistFiles +}; + var DISTRIBUTION_DIRECTORY = "lib"; @@ -19,8 +25,3 @@ function removeDistFiles(callback) { return del([DISTRIBUTION_DIRECTORY], callback); } - -module.exports = { - getDistPath, - removeDistFiles -};
57ab3c6f492f6c0d4b0f8ece8b53263c2e0db244
modules/navigation-buttons/favorite.js
modules/navigation-buttons/favorite.js
// @flow import * as React from 'react' import {Platform} from 'react-native' import Icon from 'react-native-vector-icons/Ionicons' import {Touchable} from '@frogpond/touchable' import {rightButtonStyles as styles} from './styles' type Props = { onFavorite: () => mixed, favorited: boolean, } // (ios|md)-heart(-outline) const filled = `${Platform.OS === 'ios' ? 'ios' : 'md'}-heart` const outlined = `${filled}-outline` export function FavoriteButton(props: Props) { const icon = props.favorited ? filled : outlined return ( <Touchable highlight={false} onPress={props.onFavorite} style={styles.button} > <Icon name={icon} style={styles.icon} /> </Touchable> ) }
// @flow import * as React from 'react' import {Platform} from 'react-native' import Icon from 'react-native-vector-icons/Ionicons' import {Touchable} from '@frogpond/touchable' import {rightButtonStyles as styles} from './styles' type Props = { onFavorite: () => mixed, favorited: boolean, } // (ios|md)-heart(|-empty) const filled = `${Platform.OS === 'ios' ? 'ios' : 'md'}-heart` const outlined = `${filled}-empty` export function FavoriteButton(props: Props) { const icon = props.favorited ? filled : outlined return ( <Touchable highlight={false} onPress={props.onFavorite} style={styles.button} > <Icon name={icon} style={styles.icon} /> </Touchable> ) }
Use {...}-empty instead of -outline
FavoriteButton: Use {...}-empty instead of -outline This suffix was changed, and otherwise produces an error. Signed-off-by: Kristofer Rye <1ed31cfd0b53bc3d1689a6fee6dbfc9507dffd22@gmail.com> Tested-by: Kristofer Rye <1ed31cfd0b53bc3d1689a6fee6dbfc9507dffd22@gmail.com>
JavaScript
agpl-3.0
StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native
--- +++ @@ -11,9 +11,9 @@ favorited: boolean, } -// (ios|md)-heart(-outline) +// (ios|md)-heart(|-empty) const filled = `${Platform.OS === 'ios' ? 'ios' : 'md'}-heart` -const outlined = `${filled}-outline` +const outlined = `${filled}-empty` export function FavoriteButton(props: Props) { const icon = props.favorited ? filled : outlined
51f8ecb3b98ace35620fe52419016572845204aa
app/assets/javascripts/lib/requests.js
app/assets/javascripts/lib/requests.js
import Axios from 'axios'; export function request (url, method, data = {}, options = {scroll: true}) { let promise = Axios.post(url, data, { headers: { 'X-HTTP-Method-Override': method, 'X-CSRF-Token': document.querySelector('meta[name=csrf-token]').getAttribute('content') }, }); promise.catch(e => { if (e.response) return e.response; throw e; }) .then(response => { let html = response.data; let location = response.request.responseURL; window.location.replace(location); if (options["modal"]){ options["modal"].destroy(); } }) .done(); return promise; } export var get = (url, data = {}, options = {}) => request(url, 'get', data, options) export var post = (url, data = {}, options = {}) => request(url, 'post', data, options) export var rest_delete = (url, data = {}, options = {}) => request(url, 'delete', data, options) export var patch = (url, data = {}, options = {}) => request(url, 'patch', data, options)
import Axios from 'axios'; export function request (url, method, data = {}, options = {scroll: true}) { let promise = Axios.post(url, data, { headers: { 'X-HTTP-Method-Override': method, 'X-CSRF-Token': document.querySelector('meta[name=csrf-token]').getAttribute('content') }, }); promise.catch(e => { if (e.response) return e.response; throw e; }) .then(response => { let html = response.data; let location = response.request.responseURL; document.location.reload(true); if (options["modal"]){ options["modal"].destroy(); } }) .done(); return promise; } export var get = (url, data = {}, options = {}) => request(url, 'get', data, options) export var post = (url, data = {}, options = {}) => request(url, 'post', data, options) export var rest_delete = (url, data = {}, options = {}) => request(url, 'delete', data, options) export var patch = (url, data = {}, options = {}) => request(url, 'patch', data, options)
Save page location when annotating.
Save page location when annotating.
JavaScript
agpl-3.0
harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o
--- +++ @@ -15,7 +15,7 @@ .then(response => { let html = response.data; let location = response.request.responseURL; - window.location.replace(location); + document.location.reload(true); if (options["modal"]){ options["modal"].destroy(); @@ -26,6 +26,7 @@ return promise; } + export var get = (url, data = {}, options = {}) => request(url, 'get', data, options) export var post = (url, data = {}, options = {}) => request(url, 'post', data, options) export var rest_delete = (url, data = {}, options = {}) => request(url, 'delete', data, options)
0f7e7351c9d34d1ac6866e3cb449f1a7e657926c
tasks/aliases.js
tasks/aliases.js
module.exports = function(grunt) { grunt.registerTask('sniff', ['jscs:main']); grunt.registerTask('lint', ['jshint', 'jscs:main', 'y_u_no_bundle']); grunt.registerTask('test', ['lint', 'karma:single']); grunt.registerTask('js', ['test']); grunt.registerTask('css', ['scsslint']); grunt.registerTask('php', ['phpunit:unit']); };
module.exports = function(grunt) { grunt.registerTask('sniff', ['jscs:main']); grunt.registerTask('lint', ['jshint', 'jscs:main', 'y_u_no_bundle', 'build_lint']); grunt.registerTask('test', ['lint', 'karma:single']); grunt.registerTask('js', ['test']); grunt.registerTask('css', ['scsslint']); grunt.registerTask('php', ['phpunit:unit']); };
Add build_lint to the lint task
Add build_lint to the lint task
JavaScript
mit
hzoo/grunt-behance,mrjoelkemp/grunt-behance
--- +++ @@ -1,6 +1,6 @@ module.exports = function(grunt) { grunt.registerTask('sniff', ['jscs:main']); - grunt.registerTask('lint', ['jshint', 'jscs:main', 'y_u_no_bundle']); + grunt.registerTask('lint', ['jshint', 'jscs:main', 'y_u_no_bundle', 'build_lint']); grunt.registerTask('test', ['lint', 'karma:single']); grunt.registerTask('js', ['test']);
d0821163a059c3a02e7551790346fc56a536a460
spec/simple.spec.js
spec/simple.spec.js
const renderer = require('../renderer') describe ('Renderer', () => { var loadContentCallback beforeEach(() => { loadContentCallback = jasmine.createSpy('loadContentCallback') }) it('converts a markdown file', (done) => { const markdownFilePath = __dirname + '/test_readme.md' const expectedMarkdown = '^[^<>]*<div class="markdown-body"><h1 id="hello">Hello</h1></div>$' renderer.reloadMarkdownFile(markdownFilePath, loadContentCallback).then(() => { expect(loadContentCallback.calls.count()).toEqual(1) expect(loadContentCallback.calls.mostRecent().args[0]).toMatch(expectedMarkdown) done() }, done.fail) }) })
const renderer = require('../src/renderer') describe ('Renderer', () => { var loadContentCallback beforeEach(() => { loadContentCallback = jasmine.createSpy('loadContentCallback') }) it('converts a markdown file', (done) => { const markdownFilePath = __dirname + '/test_readme.md' const expectedMarkdown = '^[^<>]*<div class="markdown-body"><h1 id="hello">Hello</h1></div>$' renderer.reloadMarkdownFile(markdownFilePath, loadContentCallback).then(() => { expect(loadContentCallback.calls.count()).toEqual(1) expect(loadContentCallback.calls.mostRecent().args[0]).toMatch(expectedMarkdown) done() }, done.fail) }) })
Fix tests (use src dir)
Fix tests (use src dir)
JavaScript
unlicense
pfertyk/mauve,pfertyk/mauve
--- +++ @@ -1,4 +1,4 @@ -const renderer = require('../renderer') +const renderer = require('../src/renderer') describe ('Renderer', () => { var loadContentCallback
f1005e94e91f5e0f0417e84409f2e66b550c0145
src/layouts/partial-dev-info.js
src/layouts/partial-dev-info.js
import hass from '../util/home-assistant-js-instance'; import Polymer from '../polymer'; import nuclearObserver from '../util/bound-nuclear-behavior'; require('./partial-base'); const { configGetters, errorLogActions, } = hass; export default new Polymer({ is: 'partial-dev-info', behaviors: [nuclearObserver], properties: { narrow: { type: Boolean, value: false, }, showMenu: { type: Boolean, value: false, }, hassVersion: { type: String, bindNuclear: configGetters.serverVersion, }, polymerVersion: { type: String, value: Polymer.version, }, nuclearVersion: { type: String, value: '1.2.1', }, errorLog: { type: String, value: '', }, }, attached() { this.refreshErrorLog(); }, refreshErrorLog(ev) { if (ev) ev.preventDefault(); this.errorLog = 'Loading error log…'; errorLogActions.fetchErrorLog().then( log => this.errorLog = log || 'No errors have been reported.'); }, });
import hass from '../util/home-assistant-js-instance'; import Polymer from '../polymer'; import nuclearObserver from '../util/bound-nuclear-behavior'; require('./partial-base'); const { configGetters, errorLogActions, } = hass; export default new Polymer({ is: 'partial-dev-info', behaviors: [nuclearObserver], properties: { narrow: { type: Boolean, value: false, }, showMenu: { type: Boolean, value: false, }, hassVersion: { type: String, bindNuclear: configGetters.serverVersion, }, polymerVersion: { type: String, value: Polymer.version, }, nuclearVersion: { type: String, value: '1.3.0', }, errorLog: { type: String, value: '', }, }, attached() { this.refreshErrorLog(); }, refreshErrorLog(ev) { if (ev) ev.preventDefault(); this.errorLog = 'Loading error log…'; errorLogActions.fetchErrorLog().then( log => this.errorLog = log || 'No errors have been reported.'); }, });
Update Nuclear version in about screen
Update Nuclear version in about screen
JavaScript
apache-2.0
sdague/home-assistant-polymer,sdague/home-assistant-polymer
--- +++ @@ -38,7 +38,7 @@ nuclearVersion: { type: String, - value: '1.2.1', + value: '1.3.0', }, errorLog: {
fa0455c7ce3e2fe9155cb62baaa470dfa46a2b8a
src/js/portal/util.js
src/js/portal/util.js
define(["jquery"], function(jquery) { return { // Convert an array to a comma separated string. arrayToString: function(array) { var arrayString; jquery.each(array, function(index, arrayValue) { if (index === 0) { arrayString = arrayValue; } else if (index > 0) { arrayString = arrayString + "," + arrayValue; } }); return arrayString; }, // Clean up common issues with user entered portal URLs. fixUrl: function(portalUrl) { var deferred = jquery.Deferred(); if (portalUrl === "") { // Default to ArcGIS Online. portalUrl = "https://www.arcgis.com/"; } else if (portalUrl.search("/home/") > 0) { // Strip the /home endpoint. portalUrl = portalUrl. substr(0, portalUrl.search("/home/")) + "/"; } else if (portalUrl.search("/sharing/") > 0) { // Strip the /sharing endpoint. portalUrl = portalUrl. substr(0, portalUrl.search("/sharing/")) + "/"; } else if (portalUrl.charAt(portalUrl.length - 1) !== "/") { // Add the trailing slash. portalUrl = portalUrl + "/"; } deferred.resolve(portalUrl); return deferred.promise(); } }; });
define(["jquery"], function(jquery) { return { // Convert an array to a comma separated string. arrayToString: function(array) { var arrayString; jquery.each(array, function(index, arrayValue) { if (index === 0) { arrayString = arrayValue; } else if (index > 0) { arrayString = arrayString + "," + arrayValue; } }); return arrayString; }, // Clean up common issues with user entered portal URLs. fixUrl: function(portalUrl) { var deferred = jquery.Deferred(); if (portalUrl === "") { // Default to ArcGIS Online. portalUrl = "https://www.arcgis.com/"; } else if (portalUrl.search("/home/") > 0) { // Strip the /home endpoint. portalUrl = portalUrl. substr(0, portalUrl.search("/home/")) + "/"; } else if (portalUrl.search("/sharing/") > 0) { // Strip the /sharing endpoint. portalUrl = portalUrl. substr(0, portalUrl.search("/sharing/")) + "/"; } else if (portalUrl.charAt(portalUrl.length - 1) !== "/") { // Add the trailing slash. portalUrl = portalUrl + "/"; } if (portalUrl.indexOf("http://") === 0 && window.location.href.indexOf("https://") === 0) { portalUrl = portalUrl.replace("http://", "https://"); } deferred.resolve(portalUrl); return deferred.promise(); } }; });
Add automatic upgrade portal url from http to https where appropriate
Add automatic upgrade portal url from http to https where appropriate Adding an upgrade of portal urls from http to https in the url validation check whenever the hosting ArcGIS Online Assistant is hosted on https.
JavaScript
apache-2.0
Esri/ago-assistant,ecaldwell/ago-assistant,ecaldwell/ago-assistant,nheminger/ago-assistant,Esri/ago-assistant,nheminger/ago-assistant
--- +++ @@ -33,6 +33,10 @@ portalUrl = portalUrl + "/"; } + if (portalUrl.indexOf("http://") === 0 && window.location.href.indexOf("https://") === 0) { + portalUrl = portalUrl.replace("http://", "https://"); + } + deferred.resolve(portalUrl); return deferred.promise(); }
70be3f4cc8a091da46e886123c7f0f8cb43db9e0
src/modules/ngSharepoint/app.js
src/modules/ngSharepoint/app.js
angular .module('ngSharepoint', []) .run(['$sp', '$spLoader', function($sp, $spLoader) { if ($sp.getAutoload()) { if ($sp.getConnectionMode() === 'JSOM') { $spLoader.loadScript('//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js'); $spLoader.loadScript('SP.Runtime.js'); $spLoader.loadScript('SP.js'); }else if ($sp.getConnectionMode() === 'REST' && !$sp.getAccessToken) { $spLoader.loadScript('SP.RequestExecutor.js'); } } }]);
angular .module('ngSharepoint', []) .run(['$sp', '$spLoader', function($sp, $spLoader) { if ($sp.getAutoload()) { if ($sp.getConnectionMode() === 'JSOM') { $spLoader.loadScripts('SP.Core', ['//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js', 'SP.Runtime.js', 'SP.js']); }else if ($sp.getConnectionMode() === 'REST' && !$sp.getAccessToken) { $spLoader.loadScript('SP.RequestExecutor.js'); } } }]);
Load main JSOM Scripts under one label
Load main JSOM Scripts under one label
JavaScript
apache-2.0
maxjoehnk/ngSharepoint
--- +++ @@ -3,9 +3,7 @@ .run(['$sp', '$spLoader', function($sp, $spLoader) { if ($sp.getAutoload()) { if ($sp.getConnectionMode() === 'JSOM') { - $spLoader.loadScript('//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js'); - $spLoader.loadScript('SP.Runtime.js'); - $spLoader.loadScript('SP.js'); + $spLoader.loadScripts('SP.Core', ['//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js', 'SP.Runtime.js', 'SP.js']); }else if ($sp.getConnectionMode() === 'REST' && !$sp.getAccessToken) { $spLoader.loadScript('SP.RequestExecutor.js'); }
3c2cb3b502e67faccfc7d4576859a07fdf80ab94
src/native-methods.js
src/native-methods.js
/** @license Copyright (c) 2016 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ 'use strict'; export let appendChild = Element.prototype.appendChild; export let insertBefore = Element.prototype.insertBefore; export let removeChild = Element.prototype.removeChild; export let setAttribute = Element.prototype.setAttribute; export let removeAttribute = Element.prototype.removeAttribute; export let cloneNode = Element.prototype.cloneNode; export let importNode = Document.prototype.importNode; export let addEventListener = Element.prototype.addEventListener; export let removeEventListener = Element.prototype.removeEventListener;
/** @license Copyright (c) 2016 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ 'use strict'; export let appendChild = Element.prototype.appendChild; export let insertBefore = Element.prototype.insertBefore; export let removeChild = Element.prototype.removeChild; export let setAttribute = Element.prototype.setAttribute; export let removeAttribute = Element.prototype.removeAttribute; export let cloneNode = Element.prototype.cloneNode; export let importNode = Document.prototype.importNode; export let addEventListener = Element.prototype.addEventListener; export let removeEventListener = Element.prototype.removeEventListener; export let dispatchEvent = Element.prototype.dispatchEvent;
Fix old Safari by using `dispatchEvent` from `Element` rather than `EventTarget`.
Fix old Safari by using `dispatchEvent` from `Element` rather than `EventTarget`.
JavaScript
bsd-3-clause
webcomponents/polyfills,webcomponents/polyfills,webcomponents/polyfills
--- +++ @@ -19,3 +19,4 @@ export let importNode = Document.prototype.importNode; export let addEventListener = Element.prototype.addEventListener; export let removeEventListener = Element.prototype.removeEventListener; +export let dispatchEvent = Element.prototype.dispatchEvent;
dea1a7debcd51c3782f0bbfc9dce0c2d38583e4d
features/apimgt/org.wso2.carbon.apimgt.store.feature/src/main/resources/store/public/theme/defaultTheme.js
features/apimgt/org.wso2.carbon.apimgt.store.feature/src/main/resources/store/public/theme/defaultTheme.js
var Configurations = { /* Blue themed palette */ palette: { primary: { main: '#3F51B5' }, secondary: { main: '#1565C0' }, text: { primary: '#31375a' }, background : { appBar: '#31375a' } }, typography: { title: { fontWeight: 400 } } /* Orange themed palette */ // palette: { // primary: { // main: '#ff5000' // }, // secondary: { // main: '#37474F' // }, // text: { // primary: '#2c3e50' // }, // background : { // appBar: '#2c3e50' // } // }, // typography: { // title: { // fontWeight: 400 // } // } };
var Configurations = { /* Blue themed palette */ palette: { primary: { main: '#3F51B5' }, secondary: { main: '#1565C0' }, /*text: { // TODO: till we migrate to MUI version(v1.0.0-beta.30 or above) with this fix https://github.com/mui-org/material-ui/issues/9750 ~tmkasun primary: '#31375a' },*/ background : { appBar: '#31375a' } }, typography: { title: { fontWeight: 400 } } /* Orange themed palette */ // palette: { // primary: { // main: '#ff5000' // }, // secondary: { // main: '#37474F' // }, // text: { // primary: '#2c3e50' // }, // background : { // appBar: '#2c3e50' // } // }, // typography: { // title: { // fontWeight: 400 // } // } };
Fix store app bar text not visible issue
Fix store app bar text not visible issue
JavaScript
apache-2.0
Minoli/carbon-apimgt,Minoli/carbon-apimgt,Minoli/carbon-apimgt
--- +++ @@ -7,9 +7,9 @@ secondary: { main: '#1565C0' }, - text: { + /*text: { // TODO: till we migrate to MUI version(v1.0.0-beta.30 or above) with this fix https://github.com/mui-org/material-ui/issues/9750 ~tmkasun primary: '#31375a' - }, + },*/ background : { appBar: '#31375a' }
91795ee6ec5ac7e4996e831fa1f13c04e8ba63ef
js/draw.js
js/draw.js
// Create a Paper.js Path to draw a line into it: var path = new Path(); // Give the stroke a color path.strokeColor = 'black'; var start = new Point(100, 100); // Move to start and draw a line from there path.moveTo(start); // Note the plus operator on Point objects. // PaperScript does that for us, and much more! path.lineTo(start + [ 100, -50 ]);
// Create a Paper.js Path to draw a line into it: var path = new Path(); // Give the stroke a color path.strokeColor = 'black'; path.strokeWidth = 4; var start = new Point(100, 100); // Move to start and draw a line from there path.moveTo(start); // Note the plus operator on Point objects. // PaperScript does that for us, and much more! path.lineTo(start + [ 100, -50 ]); // Create a circle shaped path with its center at the center // of the view and a radius of 30: var pathCircle = new Path.Circle({ center: view.center, radius: 30, fillColor: new Color(0.9, 0.5, 0.5), strokeColor: 'red', strokeWidth: 10 }); // rounded rectangle var rectOrigin = new Point(50, 140) var rectHeight = 50 var rectWidth = 200 var rectEnd = new Point(rectOrigin.x + rectWidth, rectOrigin.y + rectHeight); var rect = new Rectangle(rectOrigin, rectEnd); var cornerSize = new Size(20, 20); var roundRect = new Path.RoundRectangle(rect, cornerSize); roundRect.style = { fillColor: 'orange', strokeColor: 'brown', strokeWidth: 6 };
Add circle and rounded rectangle.
Add circle and rounded rectangle.
JavaScript
mit
beepscore/paper_play
--- +++ @@ -2,9 +2,34 @@ var path = new Path(); // Give the stroke a color path.strokeColor = 'black'; +path.strokeWidth = 4; var start = new Point(100, 100); // Move to start and draw a line from there path.moveTo(start); // Note the plus operator on Point objects. // PaperScript does that for us, and much more! path.lineTo(start + [ 100, -50 ]); + +// Create a circle shaped path with its center at the center +// of the view and a radius of 30: +var pathCircle = new Path.Circle({ + center: view.center, + radius: 30, + fillColor: new Color(0.9, 0.5, 0.5), + strokeColor: 'red', + strokeWidth: 10 +}); + +// rounded rectangle +var rectOrigin = new Point(50, 140) +var rectHeight = 50 +var rectWidth = 200 +var rectEnd = new Point(rectOrigin.x + rectWidth, rectOrigin.y + rectHeight); +var rect = new Rectangle(rectOrigin, rectEnd); +var cornerSize = new Size(20, 20); +var roundRect = new Path.RoundRectangle(rect, cornerSize); +roundRect.style = { + fillColor: 'orange', + strokeColor: 'brown', + strokeWidth: 6 +};
5c9ac6776f8d1986a502add7c3f21e29440d127f
tapestry-webresources/src/main/resources/org/apache/tapestry5/webresources/internal/invoke-coffeescript.js
tapestry-webresources/src/main/resources/org/apache/tapestry5/webresources/internal/invoke-coffeescript.js
// Compiles CoffeeScript source to JavaScript. // // input - string containing contents of the file // filename - name of file, used to report errors // // Returns { output: <compiled JavaScript> } or { exception: <exception message> } function compileCoffeeScriptSource(input, filename) { try { return { output: CoffeeScript.compile(input, {header: true}) }; } catch (err) { return { exception: CoffeeScript.helpers.prettyErrorMessage(err, filename, input, false) }; } }
// Compiles CoffeeScript source to JavaScript. // // input - string containing contents of the file // filename - name of file, used to report errors // // Returns { output: <compiled JavaScript> } or { exception: <exception message> } function compileCoffeeScriptSource(input, filename) { try { return { output: CoffeeScript.compile(input, {header: true, filename: filename}) }; } catch (err) { return { exception: err.toString() }; } }
Update shim for invoking CoffeeScript compiler to work with 1.7.1
Update shim for invoking CoffeeScript compiler to work with 1.7.1
JavaScript
apache-2.0
apache/tapestry-5,apache/tapestry-5,apache/tapestry-5,apache/tapestry-5,apache/tapestry-5
--- +++ @@ -5,10 +5,10 @@ // // Returns { output: <compiled JavaScript> } or { exception: <exception message> } function compileCoffeeScriptSource(input, filename) { - try { - return { output: CoffeeScript.compile(input, {header: true}) }; - } - catch (err) { - return { exception: CoffeeScript.helpers.prettyErrorMessage(err, filename, input, false) }; - } + try { + return { output: CoffeeScript.compile(input, {header: true, filename: filename}) }; + } + catch (err) { + return { exception: err.toString() }; + } }
ee6cd3502702c45783545f9f0ac732238ce61ddf
sailr-web/public/js/controllers/items/indexController.js
sailr-web/public/js/controllers/items/indexController.js
app.controller('indexController', ['$scope', '$http', function($scope, $http){ $scope.currency = 'USD'; $scope.codes = currencyCodes; $scope.handleCodeChange = function ($index) { $scope.currency = $scope.codes[$index]; console.log($scope.currency); }; $scope.toggleAdd = function () { $scope.shouldShowAdd = !$scope.shouldShowAdd; $('#addItem').slideToggle(300); console.log('Show pressed'); }; document.scope = $scope; $scope.formSubmit = function () { $scope.posting = true; $scope.formData = {_token: csrfToken, title: $scope.title, currency: $scope.currency, price: $scope.price}; console.log($scope.formData); $http.post('/items', JSON.stringify($scope.formData)) .success(function (data, status, headers, config) { console.log('the data to be sent is ' + JSON.stringify(data)); $scope.responseData = data; console.log($scope.responseData); window.location = $scope.responseData.redirect_url; $scope.posting = false; }) .error(function (data, status, headers, config) { console.log(data); $scope.posting = false; }); }; }]);
app.controller('indexController', ['$scope', '$http', function($scope, $http){ $scope.currency = 'USD'; $scope.codes = currencyCodes; $scope.handleCodeChange = function ($index) { $scope.currency = $scope.codes[$index]; console.log($scope.currency); }; $scope.toggleAdd = function () { $scope.shouldShowAdd = !$scope.shouldShowAdd; $('#addItem').slideToggle(300); console.log('Show pressed'); }; document.scope = $scope; $scope.formSubmit = function () { $scope.posting = true; $scope.formData = {_token: csrfToken, title: $scope.title, currency: $scope.currency, price: $scope.price}; console.log($scope.formData); $http.post('/items', JSON.stringify($scope.formData)) .success(function (data, status, headers, config) { console.log('the data to be sent is ' + JSON.stringify(data)); $scope.responseData = data; console.log($scope.responseData); if (data.message) { $scope.posting = false; humane.log(data.message); } if (data.redirect_url) { window.location = $scope.responseData.redirect_url; } $scope.posting = false; }) .error(function (data, status, headers, config) { console.log(data); $scope.posting = false; }); }; }]);
Handle error message case on product create front end
Handle error message case on product create front end
JavaScript
apache-2.0
nfeiglin/sailr-api
--- +++ @@ -26,7 +26,16 @@ console.log('the data to be sent is ' + JSON.stringify(data)); $scope.responseData = data; console.log($scope.responseData); - window.location = $scope.responseData.redirect_url; + + if (data.message) { + $scope.posting = false; + humane.log(data.message); + } + + if (data.redirect_url) { + window.location = $scope.responseData.redirect_url; + } + $scope.posting = false; })
b38d409a04590d31ceeb5d0b83c55d0892d9e1c8
projects/frontend/deployment/config.js
projects/frontend/deployment/config.js
module.exports.serverCredentials = { host: 'host', port: 1234, username: 'username', password: 'password' }; module.exports.localDirectory = './dist/'; module.exports.remoteDirectory = 'remoteDirectory/';
module.exports.serverCredentials = { host: 'host', port: 1234, username: 'username', password: 'password' }; module.exports.localDirectory = './dist/anselm-kuesters/'; module.exports.remoteDirectory = 'remoteDirectory/';
Update dist directory according to Angular update.
Update dist directory according to Angular update.
JavaScript
mit
carlkuesters/anselm-kuesters,carlkuesters/anselm-kuesters,carlkuesters/anselm-kuesters
--- +++ @@ -4,5 +4,5 @@ username: 'username', password: 'password' }; -module.exports.localDirectory = './dist/'; +module.exports.localDirectory = './dist/anselm-kuesters/'; module.exports.remoteDirectory = 'remoteDirectory/';
3d523320c125701bf7f2adf5b7ad0fe9786a8a12
src/OverlayMixin.js
src/OverlayMixin.js
import React from './react-es6'; export default = { propTypes: { container: React.PropTypes.object.isRequired }, getDefaultProps: function () { return { container: document.body }; }, componentWillUnmount: function () { this._unrenderOverlay(); this.getContainerDOMNode() .removeChild(this._overlayTarget); this._overlayTarget = null; }, componentDidUpdate: function () { this._renderOverlay(); }, componentDidMount: function () { this._renderOverlay(); }, _mountOverlayTarget: function () { this._overlayTarget = document.createElement('div'); this.getContainerDOMNode() .appendChild(this._overlayTarget); }, _renderOverlay: function () { if (!this._overlayTarget) { this._mountOverlayTarget(); } // Save reference to help testing this._overlayInstance = React.renderComponent(this.renderOverlay(), this._overlayTarget); }, _unrenderOverlay: function () { React.unmountComponentAtNode(this._overlayTarget); this._overlayInstance = null; }, getOverlayDOMNode: function() { if (!this.isMounted()) { throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.'); } return this._overlayInstance.getDOMNode(); }, getContainerDOMNode: function() { return React.isValidComponent(this.props.container) ? this.props.container.getDOMNode() : this.props.container; } };
import React from './react-es6'; export default = { propTypes: { container: React.PropTypes.object.isRequired }, getDefaultProps: function () { return { container: typeof document !== 'undefined' ? document.body : null }; }, componentWillUnmount: function () { this._unrenderOverlay(); this.getContainerDOMNode() .removeChild(this._overlayTarget); this._overlayTarget = null; }, componentDidUpdate: function () { this._renderOverlay(); }, componentDidMount: function () { this._renderOverlay(); }, _mountOverlayTarget: function () { this._overlayTarget = document.createElement('div'); this.getContainerDOMNode() .appendChild(this._overlayTarget); }, _renderOverlay: function () { if (!this._overlayTarget) { this._mountOverlayTarget(); } // Save reference to help testing this._overlayInstance = React.renderComponent(this.renderOverlay(), this._overlayTarget); }, _unrenderOverlay: function () { React.unmountComponentAtNode(this._overlayTarget); this._overlayInstance = null; }, getOverlayDOMNode: function() { if (!this.isMounted()) { throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.'); } return this._overlayInstance.getDOMNode(); }, getContainerDOMNode: function() { return React.isValidComponent(this.props.container) ? this.props.container.getDOMNode() : this.props.container; } };
Check for the existence of document before accessing it.
Check for the existence of document before accessing it. Since document is referenced within getDefaultProps which unlike componentDidMount is run in both browser and node environments we need to make sure we check it exists before accessing it.
JavaScript
mit
mengmenglv/react-bootstrap,thealjey/react-bootstrap,aforty/react-bootstrap,react-bootstrap/react-bootstrap,omerts/react-bootstrap,egauci/react-bootstrap,cgvarela/react-bootstrap,cassus/react-bootstrap,zanjs/react-bootstrap,westonplatter/react-bootstrap,insionng/react-bootstrap,pombredanne/react-bootstrap,Sipree/react-bootstrap,albertojacini/react-bootstrap,HPate-Riptide/react-bootstrap,kwnccc/react-bootstrap,react-bootstrap/react-bootstrap,aabenoja/react-bootstrap,sahat/react-bootstrap,aabenoja/react-bootstrap,herojobs/react-bootstrap,nickuraltsev/react-bootstrap,asiniy/react-bootstrap,azmenak/react-bootstrap,justinanastos/react-bootstrap,jamon/react-bootstrap,AlexKVal/react-bootstrap,mxc/react-bootstrap,tonylinyy/react-bootstrap,PeterDaveHello/react-bootstrap,adampickeral/react-bootstrap,BespokeInsights/react-bootstrap,coderstudy/react-bootstrap,Lucifier129/react-bootstrap,gianpaj/react-bootstrap,jakubsikora/react-bootstrap,Firfi/meteor-react-bootstrap,johanneshilden/react-bootstrap,bbc/react-bootstrap,modulexcite/react-bootstrap,zerkms/react-bootstrap,xuorig/react-bootstrap,mcraiganthony/react-bootstrap,glenjamin/react-bootstrap,bvasko/react-bootstrap,Lucifier129/react-bootstrap,blue68/react-bootstrap,leozdgao/react-bootstrap,xiaoking/react-bootstrap,rapilabs/react-bootstrap,react-bootstrap/react-bootstrap,dozoisch/react-bootstrap,collinwu/react-bootstrap,deerawan/react-bootstrap,erictherobot/react-bootstrap,sheep902/react-bootstrap,Cellule/react-bootstrap,aforty/react-bootstrap,chrishoage/react-bootstrap,glenjamin/react-bootstrap,pivotal-cf/react-bootstrap,IveWong/react-bootstrap,roderickwang/react-bootstrap,apisandipas/react-bootstrap,wjb12/react-bootstrap,pandoraui/react-bootstrap,yickli/react-bootstrap,andrew-d/react-bootstrap,tannewt/react-bootstrap,jontewks/react-bootstrap,mmarcant/react-bootstrap,dongtong/react-bootstrap,HorizonXP/react-bootstrap,victorzhang17/react-bootstrap,brynjagr/react-bootstrap,Azerothian/react-bootstrap,mcraiganthony/react-bootstrap,brentertz/react-bootstrap,JimiHFord/react-bootstrap,RichardLitt/react-bootstrap,Azerothian/react-bootstrap,roadmanfong/react-bootstrap,snadn/react-bootstrap,syllog1sm/react-bootstrap,apkiernan/react-bootstrap,pieter-lazzaro/react-bootstrap,chilts/react-bootstrap,natlownes/react-bootstrap,RichardLitt/react-bootstrap,yuche/react-bootstrap,jesenko/react-bootstrap,xsistens/react-bootstrap,laran/react-bootstrap,Terminux/react-bootstrap,lo1tuma/react-bootstrap,aparticka/react-bootstrap
--- +++ @@ -7,7 +7,7 @@ getDefaultProps: function () { return { - container: document.body + container: typeof document !== 'undefined' ? document.body : null }; },
4ba398230741f86580196dd1498c1821ba8e1057
lib/app/components/nuxt-child.js
lib/app/components/nuxt-child.js
import Vue from 'vue' const transitionsKeys = [ 'name', 'mode', 'css', 'type', 'enterClass', 'leaveClass', 'enterActiveClass', 'enterActiveClass', 'leaveActiveClass', 'enterToClass', 'leaveToClass' ] const listenersKeys = [ 'beforeEnter', 'enter', 'afterEnter', 'enterCancelled', 'beforeLeave', 'leave', 'afterLeave', 'leaveCancelled' ] export default { name: 'nuxt-child', functional: true, render (h, { parent, data }) { data.nuxtChild = true const transitions = parent.$nuxt.nuxt.transitions const defaultTransition = parent.$nuxt.nuxt.defaultTransition let depth = 0 while (parent) { if (parent.$vnode && parent.$vnode.data.nuxtChild) { depth++ } parent = parent.$parent } data.nuxtChildDepth = depth const transition = transitions[depth] || defaultTransition let transitionProps = {} transitionsKeys.forEach((key) => { if (typeof transition[key] !== 'undefined') { transitionProps[key] = transition[key] } }) let listeners = {} listenersKeys.forEach((key) => { if (typeof transition[key] === 'function') { listeners[key] = transition[key] } }) return h('transition', { props: transitionProps, on: listeners }, [ h('router-view', data) ]) } }
import Vue from 'vue' const transitionsKeys = [ 'name', 'mode', 'css', 'type', 'duration', 'enterClass', 'leaveClass', 'enterActiveClass', 'enterActiveClass', 'leaveActiveClass', 'enterToClass', 'leaveToClass' ] const listenersKeys = [ 'beforeEnter', 'enter', 'afterEnter', 'enterCancelled', 'beforeLeave', 'leave', 'afterLeave', 'leaveCancelled' ] export default { name: 'nuxt-child', functional: true, render (h, { parent, data }) { data.nuxtChild = true const transitions = parent.$nuxt.nuxt.transitions const defaultTransition = parent.$nuxt.nuxt.defaultTransition let depth = 0 while (parent) { if (parent.$vnode && parent.$vnode.data.nuxtChild) { depth++ } parent = parent.$parent } data.nuxtChildDepth = depth const transition = transitions[depth] || defaultTransition let transitionProps = {} transitionsKeys.forEach((key) => { if (typeof transition[key] !== 'undefined') { transitionProps[key] = transition[key] } }) let listeners = {} listenersKeys.forEach((key) => { if (typeof transition[key] === 'function') { listeners[key] = transition[key] } }) return h('transition', { props: transitionProps, on: listeners }, [ h('router-view', data) ]) } }
Add duration property in transition
Add duration property in transition
JavaScript
mit
jfroffice/nuxt.js,mgesmundo/nuxt.js,mgesmundo/nuxt.js,jfroffice/nuxt.js
--- +++ @@ -5,6 +5,7 @@ 'mode', 'css', 'type', + 'duration', 'enterClass', 'leaveClass', 'enterActiveClass',
e40937082071501d7582edfc3dc95747c1cbed31
src/spawn-strategy.js
src/spawn-strategy.js
'use strict'; class SpawnStrategy { constructor(spawn) { this.spawn = spawn; this.memory = {}; Memory.strategy = this.memory; } isSpawnReady(thresholdEnergy) { if (!this.spawn) { return false; } if (this.spawn.spawning) { return false; } thresholdEnergy = thresholdEnergy || 0; if (thresholdEnergy > this.spawn.energy) { return false; } return true; } createCreep(parts, name, memory) { memory.spawnName = memory.spawnName || this.spawn.name; return this.spawn.createCreep(parts, name, memory); } }
'use strict'; class SpawnStrategy { constructor(spawn) { this.spawn = spawn; this.memory = {}; Memory.strategy = this.memory; } isSpawnReady(thresholdEnergy) { if (!this.spawn) { return false; } if (this.spawn.spawning) { return false; } thresholdEnergy = thresholdEnergy || 0; if (thresholdEnergy > this.spawn.energy) { return false; } return true; } createCreep(parts, name, memory) { memory.spawnName = memory.spawnName || this.spawn.name; return this.spawn.createCreep(parts, name, memory); } } module.exports = SpawnStrategy;
Add spawn strategy missing export.
Add spawn strategy missing export.
JavaScript
mit
boushley/screeps
--- +++ @@ -29,3 +29,5 @@ return this.spawn.createCreep(parts, name, memory); } } + +module.exports = SpawnStrategy;
d8a0e1b9668a177e4e1fd515ff598c81a9254144
lib/reddit/getSubjectReplies.js
lib/reddit/getSubjectReplies.js
module.exports = function getSubjectReplies(reddit,subject){ var opts = {}; if (subject.comment) { opts.comment = subject.comment; opts.depth = 2; opts.context = 0; } else { opts.depth = 1; } return reddit('/comments/'+subject.article).get(opts) .then(function (result) { var combo = { article: result[0].data.children[0].data }; if (subject.comment) { combo.comment = result[1].data.children[0].data; combo.replies = combo.comment.replies.data.children; } else { combo.replies = result[1].data.children; } // TODO: handle morecomments if (combo.replies[combo.replies.length].kind == 'more') combo.replies.pop(); // Unwrap replies for (var i=combo.replies.length; i>=0; i--) { combo.replies[i] = combo.replies[i].data; } return combo; }); };
module.exports = function getSubjectReplies(reddit,subject){ var opts = {}; if (subject.comment) { opts.comment = subject.comment; opts.depth = 2; opts.context = 0; } else { opts.depth = 1; } return reddit('/comments/'+subject.article+'.json').get(opts) .then(function (result) { var combo = { article: result[0].data.children[0].data }; if (subject.comment) { combo.comment = result[1].data.children[0].data; combo.replies = combo.comment.replies.data.children; } else { combo.replies = result[1].data.children; } // TODO: handle morecomments if (combo.replies[combo.replies.length].kind == 'more') combo.replies.pop(); // Unwrap replies for (var i=combo.replies.length; i>=0; i--) { combo.replies[i] = combo.replies[i].data; } return combo; }); };
Add .json suffix to comments API call
Add .json suffix to comments API call
JavaScript
mit
stuartpb/QIKlaxonBot,stuartpb/QIKlaxonBot
--- +++ @@ -7,7 +7,7 @@ } else { opts.depth = 1; } - return reddit('/comments/'+subject.article).get(opts) + return reddit('/comments/'+subject.article+'.json').get(opts) .then(function (result) { var combo = {
4c1099da320fed9aececf66268787d8725bec4d7
src/www/js/position-recorder.js
src/www/js/position-recorder.js
'use strict'; /* global cordova */ define(function(require, exports) { var Bacon = require('./ext/Bacon'); var location = require('./location'); var positionStream = location.streamMultiplePositions(); var PositionRecorder = function() { var recordingFlag = false; var positions = []; /** * Return the status of the recorder * @returns {Boolean} true if recording, false if it not recording. */ var isRecording = function() { return recordingFlag; }; /** * Start to record positions * @returns a copy of the stream */ var startRecording = function() { var stream = new Bacon.Bus(); recordingFlag = true; positionStream .takeWhile(isRecording) //.doLog() .onValue(function(position) { positions.push(position); stream.push(position); }); return stream; }; /** * Stop recording positions */ var stopRecording = function() { recordingFlag = false; }; /** * Get a list of positions recorded * @returns {Array} list of positions recorded */ var getRecordedPositions = function() { return positions; }; return { startRecording: startRecording, stopRecording: stopRecording, isRecording: isRecording, getRecordedPositions: getRecordedPositions }; }; return PositionRecorder; });
'use strict'; /* global cordova */ define(function(require, exports) { var Bacon = require('./ext/Bacon'); var location = require('./location'); var positionStream = location.streamMultiplePositions(); var PositionRecorder = function() { var recordingFlag = false; var positions = []; var recording; var control; var stream; /** * Return the status of the recorder * @returns {Boolean} true if recording, false if it not recording. */ var isRecording = function() { return recordingFlag; }; /** * Start to record positions * @returns a copy of the stream */ var startRecording = function() { control = new Bacon.Bus(); stream = new Bacon.Bus(); recordingFlag = true; positionStream .takeUntil(control) //.doLog() .onValue(function(position) { positions.push(position); stream.push(position); }); return stream; }; /** * Stop recording positions */ var stopRecording = function() { control.push(new Bacon.End()); recordingFlag = false; }; /** * Get a list of positions recorded * @returns {Array} list of positions recorded */ var getRecordedPositions = function() { return positions; }; return { startRecording: startRecording, stopRecording: stopRecording, isRecording: isRecording, getRecordedPositions: getRecordedPositions }; }; return PositionRecorder; });
Fix stop stream even if there is no more positions in the stream
Fix stop stream even if there is no more positions in the stream Add a control stream to signal when to stop taking values from the position stream. This change is due takeWhile evaluates the condition after receiving the next value and in this case there is not guarantee of receiving an extra position.
JavaScript
bsd-3-clause
edina/fieldtrip-position-tracking,edina/fieldtrip-position-tracking
--- +++ @@ -10,6 +10,9 @@ var PositionRecorder = function() { var recordingFlag = false; var positions = []; + var recording; + var control; + var stream; /** * Return the status of the recorder @@ -24,11 +27,12 @@ * @returns a copy of the stream */ var startRecording = function() { - var stream = new Bacon.Bus(); + control = new Bacon.Bus(); + stream = new Bacon.Bus(); recordingFlag = true; positionStream - .takeWhile(isRecording) + .takeUntil(control) //.doLog() .onValue(function(position) { positions.push(position); @@ -42,6 +46,7 @@ * Stop recording positions */ var stopRecording = function() { + control.push(new Bacon.End()); recordingFlag = false; };
e135f96c71ace048e9120d68a4b802154009ddce
lib/fractal/govuk-theme/index.js
lib/fractal/govuk-theme/index.js
'use strict' const path = require('path') /* Fractal theme ----------------------------------------------------------------------------- */ // Require the mandelbrot theme module const mandelbrot = require('@frctl/mandelbrot') // Configure a custom theme const customTheme = mandelbrot({ // Mandelbrot offers a pre-defined set of colour ‘skins’ that you can apply to the UI for quick and easy customisation 'skin': 'black', // The nav sections that should show up in the sidebar (and in which order) 'nav': [ 'docs', 'components' ], // The component info panels that should be displayed in the component browser (and in which order the tabs should be displayed) 'panels': [ 'notes', 'html', 'view', 'context', 'resources', 'info' ], // The URL of a stylesheet to apply the to the UI styles: [ 'default', // link to the default mandelbrot stylesheet '/theme/govuk/css/fractal-govuk-theme.css' // override with a custom stylesheet ], // Virtual path prefix for the theme’s static assets. The value of this is prepended to the generated theme static asset URLs. 'static': { 'mount': 'theme' } }) // Specify a template directory to override any view templates customTheme.addLoadPath(path.join(__dirname, 'views')) // Specify the static assets directory that contains the custom stylesheet customTheme.addStatic(path.join(__dirname, 'assets'), 'theme/govuk') // Export the customised theme instance so it can be used in Fractal projects module.exports = customTheme
'use strict' const path = require('path') /* Fractal theme ----------------------------------------------------------------------------- */ // Require the mandelbrot theme module const mandelbrot = require('@frctl/mandelbrot') // Configure a custom theme const customTheme = mandelbrot({ // Mandelbrot offers a pre-defined set of colour ‘skins’ that you can apply to the UI for quick and easy customisation 'skin': 'black', // The nav sections that should show up in the sidebar (and in which order) 'nav': [ 'docs', 'components' ], // The component info panels that should be displayed in the component browser (and in which order the tabs should be displayed) 'panels': [ 'nunjucks', 'ruby', 'html', 'context' ], // The URL of a stylesheet to apply the to the UI styles: [ 'default', // link to the default mandelbrot stylesheet '/theme/govuk/css/fractal-govuk-theme.css' // override with a custom stylesheet ], // Virtual path prefix for the theme’s static assets. The value of this is prepended to the generated theme static asset URLs. 'static': { 'mount': 'theme' } }) // Specify a template directory to override any view templates customTheme.addLoadPath(path.join(__dirname, 'views')) // Specify the static assets directory that contains the custom stylesheet customTheme.addStatic(path.join(__dirname, 'assets'), 'theme/govuk') // Export the customised theme instance so it can be used in Fractal projects module.exports = customTheme
Change the order of component info tabs to be shown
Change the order of component info tabs to be shown - Nunjucks - Ruby - HTML - Context
JavaScript
mit
alphagov/govuk_frontend_alpha,alphagov/govuk_frontend_alpha,alphagov/govuk_frontend_alpha
--- +++ @@ -18,12 +18,10 @@ ], // The component info panels that should be displayed in the component browser (and in which order the tabs should be displayed) 'panels': [ - 'notes', + 'nunjucks', + 'ruby', 'html', - 'view', - 'context', - 'resources', - 'info' + 'context' ], // The URL of a stylesheet to apply the to the UI styles: [
fe60922b5ebb38a5845a0a2a2778f685155579ab
app/services/message-link-convertor.js
app/services/message-link-convertor.js
import Ember from 'ember'; const { getOwner } = Ember; export default Ember.Service.extend({ i18n: Ember.inject.service(), convert: function(values) { var offerId = values.offer.id; var msg = values.body; var url_with_text = msg.slice(msg.indexOf("[") + 1, msg.indexOf("]")); var url_text_begin = url_with_text.indexOf("|"); var url_text = url_with_text.slice(0, url_text_begin); var url_for = url_with_text.slice(url_text_begin + 1); if(url_for === 'transport_page'){ values.body = msg.replace("["+url_with_text+"]", `<a href='/offers/${offerId}/plan_delivery'>${url_text}</a>`); } } });
import Ember from "ember"; const { getOwner } = Ember; export default Ember.Service.extend({ i18n: Ember.inject.service(), convert: function(values) { var offerId = values.offer.id; var msg = values.body; var url_with_text = msg.slice(msg.indexOf("[") + 1, msg.indexOf("]")); var url_text_begin = url_with_text.indexOf("|"); var url_text = url_with_text.slice(0, url_text_begin); var url_for = url_with_text.slice(url_text_begin + 1); if (url_for === "transport_page") { values.body = msg.replace( "[" + url_with_text + "]", `<a href='/offers/${offerId}/plan_delivery'>${url_text}</a>` ); } if (url_for === "feedback_form") { values.body = msg.replace( "[" + url_with_text + "]", `<a href=' https://crossroads-foundation.formstack.com/forms/goodcity_feedback?OfferId=${offerId}'>${url_text}</a>` ); } } });
Add general text message for feedback form
Add general text message for feedback form
JavaScript
mit
crossroads/shared.goodcity,crossroads/shared.goodcity
--- +++ @@ -1,4 +1,4 @@ -import Ember from 'ember'; +import Ember from "ember"; const { getOwner } = Ember; export default Ember.Service.extend({ @@ -12,8 +12,18 @@ var url_text = url_with_text.slice(0, url_text_begin); var url_for = url_with_text.slice(url_text_begin + 1); - if(url_for === 'transport_page'){ - values.body = msg.replace("["+url_with_text+"]", `<a href='/offers/${offerId}/plan_delivery'>${url_text}</a>`); + if (url_for === "transport_page") { + values.body = msg.replace( + "[" + url_with_text + "]", + `<a href='/offers/${offerId}/plan_delivery'>${url_text}</a>` + ); + } + + if (url_for === "feedback_form") { + values.body = msg.replace( + "[" + url_with_text + "]", + `<a href=' https://crossroads-foundation.formstack.com/forms/goodcity_feedback?OfferId=${offerId}'>${url_text}</a>` + ); } } });
b7044cfae77441bb1c2574709e805f9a88a15f80
lib/node/formatters/withstack.js
lib/node/formatters/withstack.js
var Transform = require('../../common/transform.js'), style = require('./util.js').style; function FormatNpm() {} Transform.mixin(FormatNpm); FormatNpm.prototype.write = function(name, level, args) { var colors = { debug: 'magenta', info: 'cyan', warn: 'yellow', error: 'red' }; function pad(s) { return (s.toString().length == 4? ' '+s : s); } function getStack() { var orig = Error.prepareStackTrace; Error.prepareStackTrace = function (err, stack) { return stack; }; var err = new Error; Error.captureStackTrace(err, arguments.callee); var stack = err.stack; Error.prepareStackTrace = orig; return stack; } var frame = getStack()[4]; this.emit('item', (name ? name + ' ' : '') + (level ? style(pad(level), colors[level]) + ' ' : '') + style( frame.getFileName().replace(new RegExp('^.*/(.+)$'), '/$1') + ":" + frame.getLineNumber() , 'grey') + ' ' + args.join(' ')); }; module.exports = FormatNpm;
var Transform = require('../../common/transform.js'), style = require('./util.js').style; function FormatNpm() {} Transform.mixin(FormatNpm); function noop(a){ return a; } var types = { string: noop, number: noop, default: JSON.stringify.bind(JSON) }; function stringify(args) { return args.map(function(arg) { return (types[typeof arg] || types.default)(arg); }); } FormatNpm.prototype.write = function(name, level, args) { var colors = { debug: 'magenta', info: 'cyan', warn: 'yellow', error: 'red' }; function pad(s) { return (s.toString().length == 4? ' '+s : s); } function getStack() { var orig = Error.prepareStackTrace; Error.prepareStackTrace = function (err, stack) { return stack; }; var err = new Error; Error.captureStackTrace(err, arguments.callee); var stack = err.stack; Error.prepareStackTrace = orig; return stack; } var frame = getStack()[5], fileName = FormatNpm.fullPath ? frame.getFileName() : frame.getFileName().replace(/^.*\/(.+)$/, '/$1'); this.emit('item', (name ? name + ' ' : '') + (level ? style(pad(level), colors[level]) + ' ' : '') + style(fileName + ":" + frame.getLineNumber(), 'grey') + ' ' + stringify(args).join(' ')); }; FormatNpm.fullPath = true; module.exports = FormatNpm;
Change stack formatting in npm
Change stack formatting in npm
JavaScript
mit
mixu/minilog,sachintaware/minilog,mixu/minilog,sachintaware/minilog
--- +++ @@ -4,6 +4,22 @@ function FormatNpm() {} Transform.mixin(FormatNpm); + +function noop(a){ + return a; +} + +var types = { + string: noop, + number: noop, + default: JSON.stringify.bind(JSON) +}; + +function stringify(args) { + return args.map(function(arg) { + return (types[typeof arg] || types.default)(arg); + }); +} FormatNpm.prototype.write = function(name, level, args) { var colors = { debug: 'magenta', info: 'cyan', warn: 'yellow', error: 'red' }; @@ -20,17 +36,17 @@ return stack; } - var frame = getStack()[4]; + var frame = getStack()[5], + fileName = FormatNpm.fullPath ? frame.getFileName() : frame.getFileName().replace(/^.*\/(.+)$/, '/$1'); this.emit('item', (name ? name + ' ' : '') + (level ? style(pad(level), colors[level]) + ' ' : '') - + style( - frame.getFileName().replace(new RegExp('^.*/(.+)$'), '/$1') - + ":" + frame.getLineNumber() - , 'grey') + + style(fileName + ":" + frame.getLineNumber(), 'grey') + ' ' - + args.join(' ')); + + stringify(args).join(' ')); }; + +FormatNpm.fullPath = true; module.exports = FormatNpm;
edc212bb7698099a21e16d540886bbd1f695ce44
tests/dummy/app/routes/application.js
tests/dummy/app/routes/application.js
import Ember from 'ember'; export default Ember.Route.extend({ model: function () { return { "menus": { "services": [ { "name": "Service 1"} ] } }; } });
import Ember from 'ember'; export default Ember.Route.extend({ model: function () { return { "menus": [ { "name": "menu 1", "events": ["click", "hover"], "type": "list", "submenus": [ { "name": "submenu 1", "events": ["click"], "type": "text", "submenus": null }, { "name": "submenu 2", "events": ["click", "check"], "type": "checkbox", "submenus": null } ], "total_submenus": 2 }, { "name": "menu 2", "events": ["click", "hover"], "type": "list", "submenus": [ { "name": "submenu 1", "events": ["click"], "type": "text", "submenus": null }, { "name": "submenu 2", "events": ["click"], "type": "text", "submenus": null } ], "total_submenus": 2 } ] }; } });
Add a better JSON to test in dummy.
Add a better JSON to test in dummy.
JavaScript
mit
rodrigo-morais/ember-json-pretty,zipscene/ember-json-pretty,rodrigo-morais/ember-json-pretty,zipscene/ember-json-pretty
--- +++ @@ -2,13 +2,48 @@ export default Ember.Route.extend({ model: function () { - return { "menus": - { - "services": - [ - { "name": "Service 1"} - ] - } + return { "menus": [ + { + "name": "menu 1", + "events": ["click", "hover"], + "type": "list", + "submenus": [ + { + "name": "submenu 1", + "events": ["click"], + "type": "text", + "submenus": null + }, + { + "name": "submenu 2", + "events": ["click", "check"], + "type": "checkbox", + "submenus": null + } + ], + "total_submenus": 2 + }, + { + "name": "menu 2", + "events": ["click", "hover"], + "type": "list", + "submenus": [ + { + "name": "submenu 1", + "events": ["click"], + "type": "text", + "submenus": null + }, + { + "name": "submenu 2", + "events": ["click"], + "type": "text", + "submenus": null + } + ], + "total_submenus": 2 + } + ] }; } });
d7630bb06c97f40f461ce7f04a22a20237f9f4b7
tests/dummy/config/dependency-lint.js
tests/dummy/config/dependency-lint.js
/* eslint-env node */ 'use strict'; module.exports = { allowedVersions: { 'ember-in-element-polyfill': '*', 'ember-get-config': '0.3.0 || 0.4.0 || 0.5.0', 'ember-modifier': '2.1.2 || 3.0.0', '@embroider/util': '*', '@ember/render-modifiers': '1.0.2 || 2.0.2', }, };
/* eslint-env node */ 'use strict'; module.exports = { allowedVersions: { 'ember-in-element-polyfill': '*', 'ember-get-config': '0.3.0 || 0.4.0 || 0.5.0', 'ember-modifier': '2.1.2 || 3.0.0', '@embroider/util': '*', }, };
Remove no longer needed dependency override
Remove no longer needed dependency override
JavaScript
mit
ilios/common,ilios/common
--- +++ @@ -7,6 +7,5 @@ 'ember-get-config': '0.3.0 || 0.4.0 || 0.5.0', 'ember-modifier': '2.1.2 || 3.0.0', '@embroider/util': '*', - '@ember/render-modifiers': '1.0.2 || 2.0.2', }, };
59f343d1aa3e74fd70fc5b6add9bd248d7676deb
src/unsigned-hyper.js
src/unsigned-hyper.js
import Long from 'long'; import includeIoMixin from './io-mixin'; export class UnsignedHyper extends Long { static read(io) { let high = io.readInt32BE(); let low = io.readInt32BE(); return this.fromBits(low, high); } static write(value, io) { if(!(value instanceof this)) { throw new Error( `XDR Write Error: ${value} is not an UnsignedHyper` ); } io.writeInt32BE(value.high); io.writeInt32BE(value.low); } static fromString(string) { let result = super.fromString(string, true); return new this(result.low, result.high); } static fromBits(low, high) { let result = super.fromBits(low, high, true); return new this(result.low, result.high); } static isValid(value) { return value instanceof this; } constructor(low, high) { super(low, high, false); } } includeIoMixin(UnsignedHyper); UnsignedHyper.MAX_VALUE = new UnsignedHyper( Long.MAX_UNSIGNED_VALUE.low, Long.MAX_UNSIGNED_VALUE.high ); UnsignedHyper.MIN_VALUE = new UnsignedHyper( Long.MIN_VALUE.low, Long.MIN_VALUE.high );
import Long from 'long'; import includeIoMixin from './io-mixin'; export class UnsignedHyper extends Long { static read(io) { let high = io.readInt32BE(); let low = io.readInt32BE(); return this.fromBits(low, high); } static write(value, io) { if(!(value instanceof this)) { throw new Error( `XDR Write Error: ${value} is not an UnsignedHyper` ); } io.writeInt32BE(value.high); io.writeInt32BE(value.low); } static fromString(string) { let result = super.fromString(string, true); return new this(result.low, result.high); } static fromBits(low, high) { let result = super.fromBits(low, high, true); return new this(result.low, result.high); } static isValid(value) { return value instanceof this; } constructor(low, high) { super(low, high, true); } } includeIoMixin(UnsignedHyper); UnsignedHyper.MAX_VALUE = new UnsignedHyper( Long.MAX_UNSIGNED_VALUE.low, Long.MAX_UNSIGNED_VALUE.high ); UnsignedHyper.MIN_VALUE = new UnsignedHyper( Long.MIN_VALUE.low, Long.MIN_VALUE.high );
Mark unsigned hyper as unsigned
Mark unsigned hyper as unsigned
JavaScript
apache-2.0
Jonavin/js-xdr,stellar/js-xdr,Jonavin/js-xdr,stellar/js-xdr
--- +++ @@ -34,18 +34,18 @@ } constructor(low, high) { - super(low, high, false); + super(low, high, true); } } includeIoMixin(UnsignedHyper); UnsignedHyper.MAX_VALUE = new UnsignedHyper( - Long.MAX_UNSIGNED_VALUE.low, + Long.MAX_UNSIGNED_VALUE.low, Long.MAX_UNSIGNED_VALUE.high ); UnsignedHyper.MIN_VALUE = new UnsignedHyper( - Long.MIN_VALUE.low, + Long.MIN_VALUE.low, Long.MIN_VALUE.high );
5487664f1f8f47355e406b60ad1a6cb89c85e55c
tests/parse.js
tests/parse.js
const parse = require('../lib/parse'); const cases = require('postcss-parser-tests'); const expect = require('chai').expect; describe('parse', () => { cases.each((name, css, json) => { it('should parse ' + name, () => { let parsed = cases.jsonify(parse(css, { from: name })); expect(parsed).to.equal(json); }); }); });
const parse = require('../lib/parse'); const cases = require('postcss-parser-tests'); const expect = require('chai').expect; describe('parse', () => { cases.each((name, css, json) => { it('should parse ' + name, () => { let parsed = cases.jsonify(parse(css, { from: name })); expect(parsed).to.equal(json); }); }); }); describe('parse mixins', () => { it('should parse mixins', () => { let root = parse('a { custom(); }'), node = root.first.first; expect(node.type).to.equal('mixin'); expect(node.name).to.equal('custom'); }); it('should parse comma separated values as arguments', () => { let root = parse(".block { mixin(1, bold, url('test.png'), #000, rgb(0, 0, 0)); }"), node = root.first.first; expect(JSON.stringify(node.arguments)).to.equal('["1","bold","url(\'test.png\')","#000","rgb(0, 0, 0)"]'); }); it('should parse key: value pairs as arguments', () => { let root = parse(".block { mixin(padding: 1, weight: bold, background: url('test.png')); }"), node = root.first.first; expect(JSON.stringify(node.arguments[0])).to.equal('{"padding":"1","weight":"bold","background":"url(\'test.png\')"}'); }); });
Add tests for basic mixin syntax
Add tests for basic mixin syntax
JavaScript
mit
weepower/postcss-wee-syntax
--- +++ @@ -11,3 +11,27 @@ }); }); }); + +describe('parse mixins', () => { + it('should parse mixins', () => { + let root = parse('a { custom(); }'), + node = root.first.first; + + expect(node.type).to.equal('mixin'); + expect(node.name).to.equal('custom'); + }); + + it('should parse comma separated values as arguments', () => { + let root = parse(".block { mixin(1, bold, url('test.png'), #000, rgb(0, 0, 0)); }"), + node = root.first.first; + + expect(JSON.stringify(node.arguments)).to.equal('["1","bold","url(\'test.png\')","#000","rgb(0, 0, 0)"]'); + }); + + it('should parse key: value pairs as arguments', () => { + let root = parse(".block { mixin(padding: 1, weight: bold, background: url('test.png')); }"), + node = root.first.first; + + expect(JSON.stringify(node.arguments[0])).to.equal('{"padding":"1","weight":"bold","background":"url(\'test.png\')"}'); + }); +});
0c4bb09e55382144816bb36515f03a8c7b1816d6
test/instrumentation/_client.js
test/instrumentation/_client.js
'use strict' var Instrumentation = require('../../lib/instrumentation') var noop = function () {} module.exports = function mockClient (cb) { var client = { active: true, _httpClient: { request: cb || noop }, logger: require('console-log-level')({ level: 'trace' }) } client._instrumentation = new Instrumentation(client) return client }
'use strict' var Instrumentation = require('../../lib/instrumentation') var noop = function () {} module.exports = function mockClient (cb) { var client = { active: true, _ff_instrument: true, _httpClient: { request: cb || noop }, logger: require('console-log-level')({ level: 'trace' }) } client._instrumentation = new Instrumentation(client) return client }
Enable instrumentation feature flag when testing
Enable instrumentation feature flag when testing
JavaScript
bsd-2-clause
opbeat/opbeat-node,opbeat/opbeat-node
--- +++ @@ -7,6 +7,7 @@ module.exports = function mockClient (cb) { var client = { active: true, + _ff_instrument: true, _httpClient: { request: cb || noop },
28f66518bc3789a51ad6d9321a6ba8866ea39780
test/specs/calculator/config.js
test/specs/calculator/config.js
module.exports = { // get zero () { return browser.element('button*=0)'); }, get zero() { return browser.element('button*=0'); }, get one() { return browser.element('button*=1'); }, get two() { return browser.element('button*=2'); }, get three() { return browser.element('button*=3'); }, get four() { return browser.element('button*=4'); }, get five() { return browser.element('button*=5'); }, get six() { return browser.element('button*=6'); }, get seven() { return browser.element('button*=7'); }, get eight() { return browser.element('button*=8'); }, get nine() { return browser.element('button*=9'); }, get period() { return browser.element('button*=.'); }, get dividedBy() { return browser.element('button*=÷'); }, get times() { return browser.element('button*=×'); }, get minus() { return browser.element('button*=-'); }, get plus() { return browser.element('button*=+'); }, get equals() { return browser.element('button*=='); }, get responsePaneText() { return browser.getText('#response-pane'); }, };
module.exports = { get zero() { return browser.element('button=0'); }, get one() { return browser.element('button=1'); }, get two() { return browser.element('button=2'); }, get three() { return browser.element('button=3'); }, get four() { return browser.element('button=4'); }, get five() { return browser.element('button=5'); }, get six() { return browser.element('button=6'); }, get seven() { return browser.element('button=7'); }, get eight() { return browser.element('button=8'); }, get nine() { return browser.element('button=9'); }, get period() { return browser.element('button=.'); }, get dividedBy() { return browser.element('button=÷'); }, get times() { return browser.element('button=×'); }, get minus() { return browser.element('button=-'); }, get plus() { return browser.element('button=+'); }, get equals() { return browser.element('button=='); }, get responsePaneText() { return browser.getText('#response-pane'); }, };
Improve selector performance, remove comment
Improve selector performance, remove comment
JavaScript
mit
JasonMFry/calculator,JasonMFry/calculator
--- +++ @@ -1,22 +1,21 @@ module.exports = { - // get zero () { return browser.element('button*=0)'); }, - get zero() { return browser.element('button*=0'); }, - get one() { return browser.element('button*=1'); }, - get two() { return browser.element('button*=2'); }, - get three() { return browser.element('button*=3'); }, - get four() { return browser.element('button*=4'); }, - get five() { return browser.element('button*=5'); }, - get six() { return browser.element('button*=6'); }, - get seven() { return browser.element('button*=7'); }, - get eight() { return browser.element('button*=8'); }, - get nine() { return browser.element('button*=9'); }, - get period() { return browser.element('button*=.'); }, + get zero() { return browser.element('button=0'); }, + get one() { return browser.element('button=1'); }, + get two() { return browser.element('button=2'); }, + get three() { return browser.element('button=3'); }, + get four() { return browser.element('button=4'); }, + get five() { return browser.element('button=5'); }, + get six() { return browser.element('button=6'); }, + get seven() { return browser.element('button=7'); }, + get eight() { return browser.element('button=8'); }, + get nine() { return browser.element('button=9'); }, + get period() { return browser.element('button=.'); }, - get dividedBy() { return browser.element('button*=÷'); }, - get times() { return browser.element('button*=×'); }, - get minus() { return browser.element('button*=-'); }, - get plus() { return browser.element('button*=+'); }, - get equals() { return browser.element('button*=='); }, + get dividedBy() { return browser.element('button=÷'); }, + get times() { return browser.element('button=×'); }, + get minus() { return browser.element('button=-'); }, + get plus() { return browser.element('button=+'); }, + get equals() { return browser.element('button=='); }, get responsePaneText() { return browser.getText('#response-pane'); }, };
63575d11f46086d80794c09ac08ca6fec627670c
sw-precache-config.js
sw-precache-config.js
module.exports = { staticFileGlobs: [ '/index.html', '/manifest.json', '/bower_components/webcomponentsjs/webcomponents-lite.min.js' ], navigateFallback: '/index.html' };
module.exports = { staticFileGlobs: [ '/index.html', '/manifest.json', '/bower_components/webcomponentsjs/webcomponents-lite.min.js', 'bower_components/viewport-units-buggyfill/viewport-units-buggyfill.js' ], navigateFallback: '/index.html' };
Include viewport fixer to be cached by service worker
Include viewport fixer to be cached by service worker
JavaScript
apache-2.0
vaadin-kim/stockwatcher-polymer,vaadin-kim/stockwatcher-polymer
--- +++ @@ -2,7 +2,8 @@ staticFileGlobs: [ '/index.html', '/manifest.json', - '/bower_components/webcomponentsjs/webcomponents-lite.min.js' + '/bower_components/webcomponentsjs/webcomponents-lite.min.js', + 'bower_components/viewport-units-buggyfill/viewport-units-buggyfill.js' ], navigateFallback: '/index.html' };
c8277cfe90035777aeea3e1c089ce9aaab4111e5
lib/transferJSON.js
lib/transferJSON.js
var dataSheetConfig = require('../data/dataSheetConfig'); var parseDataSheet = require('../lib/parseDataSheet'); var options = { host: dataSheetConfig.host, port: 443, path: '/feeds/list/' + dataSheetConfig.sheetID + '/' + dataSheetConfig.listID[0] +'/public/values?v=3.0&alt=json', method: 'GET', headers: { 'Content-Type': 'application/json' } }; parseDataSheet.getJSON(options, function (statusCode, result) { console.log("result: " + statusCode); console.log("data " + JSON.stringify(result)); });
var dataSheetConfig = require('../data/dataSheetConfig'); var parseDataSheet = require('../lib/parseDataSheet'); var options = { host: dataSheetConfig.host, port: 443, path: '/feeds/list/' + dataSheetConfig.sheetID + '/' + dataSheetConfig.listID[0] +'/public/values?v=3.0&alt=json', method: 'GET', headers: { 'Content-Type': 'application/json' } }; var eventsData = []; parseDataSheet.getJSON(options, function (statusCode, result) { var timeTmp = result.feed.title.$t; for (var i = 3; i < result.feed.entry.length; i++) { var rowData = result.feed.entry[i]; getTime(timeTmp, rowData.title.$t, function(time) { console.log(time); }); } }); getTime = function (timeTmp, timeTmp2, getResult) { var eventsTmp = new Date(timeTmp + ' ' + timeTmp2); var eventsDate = { full: eventsTmp.getFullYear() + '-' + (eventsTmp.getMonth() + 1) + '-' + eventsTmp.getDate() + 'T' + eventsTmp.toLocaleTimeString() + '+08:00', yyyy: eventsTmp.getFullYear(), mm: eventsTmp.getMonth() + 1, dd: eventsTmp.getDate(), hh: eventsTmp.getHours(), ii: eventsTmp.getMinutes(), ss: eventsTmp.getMilliseconds() }; getResult(eventsDate); }
Add parse Time Format function.
Add parse Time Format function. Signed-off-by: Lee <907de9d2b73011dd426e396ff4243eefbafde16d@gmail.com>
JavaScript
mit
g0v/SunflowerDocumentaryAPI
--- +++ @@ -1,5 +1,5 @@ var dataSheetConfig = require('../data/dataSheetConfig'); -var parseDataSheet = require('../lib/parseDataSheet'); +var parseDataSheet = require('../lib/parseDataSheet'); var options = { host: dataSheetConfig.host, @@ -11,7 +11,31 @@ } }; +var eventsData = []; + parseDataSheet.getJSON(options, function (statusCode, result) { - console.log("result: " + statusCode); - console.log("data " + JSON.stringify(result)); + var timeTmp = result.feed.title.$t; + for (var i = 3; i < result.feed.entry.length; i++) { + var rowData = result.feed.entry[i]; + + getTime(timeTmp, rowData.title.$t, function(time) { + console.log(time); + }); + } }); + +getTime = function (timeTmp, timeTmp2, getResult) { + var eventsTmp = new Date(timeTmp + ' ' + timeTmp2); + var eventsDate = { full: eventsTmp.getFullYear() + '-' + + (eventsTmp.getMonth() + 1) + '-' + + eventsTmp.getDate() + 'T' + + eventsTmp.toLocaleTimeString() + '+08:00', + yyyy: eventsTmp.getFullYear(), + mm: eventsTmp.getMonth() + 1, + dd: eventsTmp.getDate(), + hh: eventsTmp.getHours(), + ii: eventsTmp.getMinutes(), + ss: eventsTmp.getMilliseconds() + }; + getResult(eventsDate); +}
a141af2343e366e7aee48e5adebc10c0d4f7fdab
generators/run/index.js
generators/run/index.js
(function() { 'use strict'; var yeoman = require('yeoman-generator'), scaffold = {}; module.exports = yeoman.generators.Base.extend({ constructor: function() { yeoman.generators.Base.apply(this, arguments); this.option('skip-welcome'); this.argument('runType', { type: String, required: false }); scaffold = require('../../scaffold')(this); this.isBuild = typeof this.runType !== 'undefined' && this.runType.toLowerCase() === 'build'; }, initializing: function() { var message = 'Starting development mode. I will start a server with BrowserSync support. :)'; if (this.isBuild) { message = 'Starting build view. I will start a server with BrowserSync support. :)'; } if (!this.options['skip-welcome']) { scaffold.welcomeMessage(' Running project ', message); } }, install: function() { if (this.isBuild) { this.spawnCommand('grunt', ['serve']); return false; } this.spawnCommand('grunt', ['default']); } }); })();
(function() { 'use strict'; var yeoman = require('yeoman-generator'), scaffold = {}; module.exports = yeoman.generators.Base.extend({ constructor: function() { yeoman.generators.Base.apply(this, arguments); this.option('skip-welcome'); this.argument('runType', { type: String, required: false }); scaffold = require('../../scaffold')(this); this.isBuild = typeof this.runType !== 'undefined' && this.runType.toLowerCase() === 'build'; }, initializing: function() { var message = 'Starting development mode. I will start a server with BrowserSync support. :)'; if (this.isBuild) { message = 'Starting build view. I will start a server with BrowserSync support. :)'; } if (!this.options['skip-welcome']) { scaffold.welcomeMessage(' Running project ', message); } }, install: function() { scaffold.log('Installing Bower dependencies...', 'yellow'); this.bowerInstall('', this.async); }, end: function() { if (this.isBuild) { this.spawnCommand('grunt', ['serve']); return false; } this.spawnCommand('grunt', ['default']); } }); })();
Add install of bower dependencies
Add install of bower dependencies
JavaScript
mit
marcosmoura/generator-scaffold,marcosmoura/generator-scaffold
--- +++ @@ -35,6 +35,12 @@ }, install: function() { + scaffold.log('Installing Bower dependencies...', 'yellow'); + + this.bowerInstall('', this.async); + }, + + end: function() { if (this.isBuild) { this.spawnCommand('grunt', ['serve']);
e5a4fa8e41bae6727e8b2d20abbfbc1fdb417692
app.js
app.js
var fs = require('fs'), log = require('./log'), express = require('express'), app = express(), config = require('./config'); pluginRoot = './plugins'; log.info('[app]', 'Scanning for plugins.'); fs.readdirSync(pluginRoot).forEach(function(folder) { var pluginPath = pluginRoot + '/' + folder; log.verbose('[app]', 'Scanning folder ' + pluginPath); var files = fs.readdirSync(pluginPath); if (files.indexOf('index.js') > -1) { try { var plugin = require(pluginPath); log.info('[app]', 'Initializing ' + plugin.name() + ' v' + plugin.version()); plugin.init(app); } catch(e) { log.error('[app]', e.stack); } } else { log.error('[app]', 'Missing index.js in ' + pluginPath); } }); try { app.listen(config.port); log.info('[app]', 'Server listening at port ' + config.port); } catch(e) { log.error('[app]', e.stack); }
var fs = require('fs'), log = require('./log'), express = require('express'), app = express(), config = require('./config'); pluginRoot = './plugins'; app.use(express.bodyParser()); app.disable('x-powered-by'); log.info('[app]', 'Scanning for plugins.'); fs.readdirSync(pluginRoot).forEach(function(folder) { var pluginPath = pluginRoot + '/' + folder; log.verbose('[app]', 'Scanning folder ' + pluginPath); var files = fs.readdirSync(pluginPath); if (files.indexOf('index.js') > -1) { try { var plugin = require(pluginPath); log.info('[app]', 'Initializing ' + plugin.name() + ' v' + plugin.version()); plugin.init(app); } catch(e) { log.error('[app]', e.stack); } } else { log.error('[app]', 'Missing index.js in ' + pluginPath); } }); try { app.listen(config.port); log.info('[app]', 'Server listening at port ' + config.port); } catch(e) { log.error('[app]', e.stack); }
Use bodyParser() and remove x-powered-by
Use bodyParser() and remove x-powered-by
JavaScript
mit
nilzen/onmote
--- +++ @@ -4,6 +4,9 @@ app = express(), config = require('./config'); pluginRoot = './plugins'; + +app.use(express.bodyParser()); +app.disable('x-powered-by'); log.info('[app]', 'Scanning for plugins.');
ce2b085adeaaa8b07b6e94935acf5a4c6cf0fe6d
app.js
app.js
console.log("Hello world!");
var express = require('express'); var app = express(); app.set('port',3000); var server = app.listen(app.get('port'), function() { var port = server.address().port; console.log('Magic happends on port '+ port ); }); console.log('this is the first')
Add express functionality, listen to a port
Add express functionality, listen to a port
JavaScript
mit
dotanitis/mean-stack-app,dotanitis/mean-stack-app
--- +++ @@ -1 +1,15 @@ -console.log("Hello world!"); +var express = require('express'); + +var app = express(); + +app.set('port',3000); + + + +var server = app.listen(app.get('port'), function() { + var port = server.address().port; + console.log('Magic happends on port '+ port ); +}); + + +console.log('this is the first')
2f7046d95cd1ede8fba9b490dba25cee1c90facf
lib/RegexLibrary.js
lib/RegexLibrary.js
/* * regex-pill * https://github.com/lgoldstien/regex-pill * * Copyright (c) 2014 Lawrence Goldstien * Licensed under the MIT license. */ 'use strict'; var RegexLibraryContents = { "hostnames":{ "databases": { "mongodb": /^(mongodb:\/\/)([a-z0-9]+:[a-z0-9]+@)?([a-zA-Z0-9-_.]+)(:[0-9]+)?(\/[a-z_-]+)?$/g, } } }; var RegexLibrary = function () { }; RegexLibrary.prototype.get = function (name) { this._selectedRegex = name; }; module.exports = RegexLibrary;
/* * regex-pill * https://github.com/lgoldstien/regex-pill * * Copyright (c) 2014 Lawrence Goldstien * Licensed under the MIT license. */ 'use strict'; var RegexLibraryContents = { "hostnames/databases/mongodb": /^(mongodb:\/\/)([a-z0-9]+:[a-z0-9]+@)?([a-zA-Z0-9-_.]+)(:[0-9]+)?(\/[a-z_-]+)?$/g, }; var RegexLibrary = function (value, name) { if (!value) throw new ReferenceError("A value should be passed to this constructor."); this._value = value; if (name) this.setRegex(name); return this; }; RegexLibrary.prototype.isValid = function () { var regex; if (!this._selectedRegex.regex) throw new ReferenceError("Cannot validate against a non-existant regex."); regex = this._selectedRegex.regex; }; RegexLibrary.prototype.setRegex = function (name) { this._selectedRegex = { name: name }; (RegexLibraryContents[this._selectedRegex.name]) ? this._selectedRegex.regex = RegexLibraryContents[this._selectedRegex.name] : this._selectedRegex = {}; }; module.exports = RegexLibrary;
Add some improvements to assigning regex, begin validate method
Add some improvements to assigning regex, begin validate method
JavaScript
mit
lgoldstien/regexpill
--- +++ @@ -9,20 +9,41 @@ 'use strict'; var RegexLibraryContents = { - "hostnames":{ - "databases": { - "mongodb": /^(mongodb:\/\/)([a-z0-9]+:[a-z0-9]+@)?([a-zA-Z0-9-_.]+)(:[0-9]+)?(\/[a-z_-]+)?$/g, - } - } + "hostnames/databases/mongodb": /^(mongodb:\/\/)([a-z0-9]+:[a-z0-9]+@)?([a-zA-Z0-9-_.]+)(:[0-9]+)?(\/[a-z_-]+)?$/g, }; -var RegexLibrary = function () { +var RegexLibrary = function (value, name) { + if (!value) + throw new ReferenceError("A value should be passed to this constructor."); + + this._value = value; + + if (name) + this.setRegex(name); + + return this; +}; + +RegexLibrary.prototype.isValid = function () { + var regex; + + if (!this._selectedRegex.regex) + throw new ReferenceError("Cannot validate against a non-existant regex."); + + regex = this._selectedRegex.regex; + + +}; + +RegexLibrary.prototype.setRegex = function (name) { + this._selectedRegex = { name: name }; + + (RegexLibraryContents[this._selectedRegex.name]) ? + this._selectedRegex.regex = RegexLibraryContents[this._selectedRegex.name] : + this._selectedRegex = {}; + }; -RegexLibrary.prototype.get = function (name) { - this._selectedRegex = name; -}; - module.exports = RegexLibrary;
162b34a5a1125bf90949da47ecfb897253628c86
js/myapp/card-detail.js
js/myapp/card-detail.js
// ---------------------------------------------------------------- // CardDetail Class // ---------------------------------------------------------------- // Model class CardDetailModel extends CommonModel { constructor({ name } = {}) { super({ name: name }); this.NAME = 'Card Detail Model'; this.EVENT = PS.CDE; this.CARD_DETAIL_AREA_SELECTOR = '#card-detail-area'; this.$CARD_DETAIL_AREA_SELECTOR = $(this.CARD_DETAIL_AREA_SELECTOR); this.ID = null; this.HASH = null; this.CARD = null; } } // ---------------------------------------------------------------- // View class CardDetailView extends CommonView { constructor(_model = new CardDetailModel()) { super(_model); this.NAME = 'Card Detail View'; } } // ---------------------------------------------------------------- // Controller class CardDetailController extends CommonController { constructor(_obj) { super(_obj); this.model = new CardDetailModel(_obj); this.view = new CardDetailView(this.model); this.NAME = 'Card Detail Controller'; } } // ---------------------------------------------------------------- // Event class CardDetailEvent extends CommonEvent { constructor({ name = 'Card Detail Event' } = {}) { super({ name: name }); PS.CDE = this; this.NAME = name; this.CONTROLLER = new CardDetailController({ name: 'Card Detail Controller', }); } }
// ---------------------------------------------------------------- // CardDetail Class // ---------------------------------------------------------------- // Model class CardDetailModel extends CommonModel { constructor({ name } = {}) { super({ name: name }); this.NAME = 'Card Detail Model'; this.EVENT = PS.CDE; this.CARD_DETAIL_AREA_SELECTOR = '#card-detail-area'; this.$CARD_DETAIL_AREA_SELECTOR = $(this.CARD_DETAIL_AREA_SELECTOR); this.ID = null; this.HASH = null; this.CARD = null; } } // ---------------------------------------------------------------- // View class CardDetailView extends CommonView { constructor(_model = new CardDetailModel()) { super(_model); this.NAME = 'Card Detail View'; } generateCardDetailArea( _alertType = 'success', _message = null, _close = true ) { this.model.$USER_DETAIL_AREA_SELECTOR.empty(); this.generateAlert(this.model.$USER_DETAIL_AREA_SELECTOR, _alertType, _message, _close); } } // ---------------------------------------------------------------- // Controller class CardDetailController extends CommonController { constructor(_obj) { super(_obj); this.model = new CardDetailModel(_obj); this.view = new CardDetailView(this.model); this.NAME = 'Card Detail Controller'; } } // ---------------------------------------------------------------- // Event class CardDetailEvent extends CommonEvent { constructor({ name = 'Card Detail Event' } = {}) { super({ name: name }); PS.CDE = this; this.NAME = name; this.CONTROLLER = new CardDetailController({ name: 'Card Detail Controller', }); } }
Add function generateCardDetailArea to CardDetailView
Add function generateCardDetailArea to CardDetailView
JavaScript
mit
AyaNakazawa/business_card_bank,AyaNakazawa/business_card_bank,AyaNakazawa/business_card_bank
--- +++ @@ -33,6 +33,16 @@ super(_model); this.NAME = 'Card Detail View'; + } + + generateCardDetailArea( + _alertType = 'success', + _message = null, + _close = true + ) { + this.model.$USER_DETAIL_AREA_SELECTOR.empty(); + this.generateAlert(this.model.$USER_DETAIL_AREA_SELECTOR, _alertType, _message, _close); + } }
61db4e05c6ff0d9bbce43cd48d1e187f0dc0e0c6
test/configuration.js
test/configuration.js
if (!chai) { var chai = require('..'); } var assert = chai.assert; function fooThrows () { assert.equal('foo', 'bar'); } suite('configuration', function () { test('Assertion.includeStack is true', function () { chai.Assertion.includeStack = true; try { fooThrows(); assert.ok(false, 'should not get here because error thrown'); } catch (err) { if (typeof(err.stack) !== 'undefined') { // not all browsers support err.stack assert.include(err.stack, 'at fooThrows', 'should have stack trace in error message'); } } }); test('Assertion.includeStack is false', function () { chai.Assertion.includeStack = false; try { fooThrows(); assert.ok(false, 'should not get here because error thrown'); } catch (err) { assert.ok(!err.stack || err.stack.indexOf('at fooThrows') === -1, 'should not have stack trace in error message'); } }); test('AssertionError Properties', function () { var err = new chai.AssertionError({ message: 'Chai!' }); assert.equal(err.toString(), 'Chai!'); }); });
if (!chai) { var chai = require('..'); } var assert = chai.assert; function fooThrows () { assert.equal('foo', 'bar'); } suite('configuration', function () { test('Assertion.includeStack is true', function () { chai.Assertion.includeStack = true; try { fooThrows(); assert.ok(false, 'should not get here because error thrown'); } catch (err) { if (typeof(err.stack) !== 'undefined') { // not all browsers support err.stack assert.include(err.stack, 'at fooThrows', 'should have stack trace in error message'); } } }); test('Assertion.includeStack is false', function () { chai.Assertion.includeStack = false; try { fooThrows(); assert.ok(false, 'should not get here because error thrown'); } catch (err) { // IE 10 supports err.stack in Chrome format, but without // `Error.captureStackTrace` support that allows tuning of the error // message. if (typeof Error.captureStackTrace !== 'undefined') { assert.ok(!err.stack || err.stack.indexOf('at fooThrows') === -1, 'should not have stack trace in error message'); } } }); test('AssertionError Properties', function () { var err = new chai.AssertionError({ message: 'Chai!' }); assert.equal(err.toString(), 'Chai!'); }); });
Disable "Assertion.includeStack is false" test in IE.
Disable "Assertion.includeStack is false" test in IE. This only manifested in IE 10; IE 9 was fine since it didn't have the `stack` property.
JavaScript
mit
meeber/chai,lucasfcosta/chai,meeber/chai,chaijs/chai,chaijs/chai,lucasfcosta/chai
--- +++ @@ -27,7 +27,12 @@ fooThrows(); assert.ok(false, 'should not get here because error thrown'); } catch (err) { - assert.ok(!err.stack || err.stack.indexOf('at fooThrows') === -1, 'should not have stack trace in error message'); + // IE 10 supports err.stack in Chrome format, but without + // `Error.captureStackTrace` support that allows tuning of the error + // message. + if (typeof Error.captureStackTrace !== 'undefined') { + assert.ok(!err.stack || err.stack.indexOf('at fooThrows') === -1, 'should not have stack trace in error message'); + } } });
ca83db3200e1990345297fe9bc35c57f7b1fdebc
lib/createHeader.js
lib/createHeader.js
var Immutable = require('immutable'); var Draft = require('draft-js'); var TYPES = require('./TYPES'); var createRow = require('./createRow'); /** * Create a new table header * * @param {String} tableKey * @param {Number} countColumns * @return {OrderedMap<String:Draft.ContentBlock>} */ function createHeader(tableKey, countColumns) { var tableHeaderKey = Draft.genNestedKey(tableKey); var tableHeaderBlock = new Draft.ContentBlock({ key: tableHeaderKey, type: TYPES.HEADER, data: Immutable.Map({ align: Array .apply(null, Array(10)) .map(function(){ return TYPES.LEFT; }) }) }); return Immutable.OrderedMap([ [tableHeaderKey, tableHeaderBlock] ]) .merge( createRow(tableHeaderKey, countColumns) ); } module.exports = createHeader;
var Immutable = require('immutable'); var Draft = require('draft-js'); var TYPES = require('./TYPES'); var createRow = require('./createRow'); /** * Create a new table header * * @param {String} tableKey * @param {Number} countColumns * @return {OrderedMap<String:Draft.ContentBlock>} */ function createHeader(tableKey, countColumns) { var tableHeaderKey = Draft.genNestedKey(tableKey); var tableHeaderBlock = new Draft.ContentBlock({ key: tableHeaderKey, type: TYPES.HEADER, data: Immutable.Map({ align: Array .apply(null, Array(countColumns)) .map(function(){ return TYPES.LEFT; }) }) }); return Immutable.OrderedMap([ [tableHeaderKey, tableHeaderBlock] ]) .merge( createRow(tableHeaderKey, countColumns) ); } module.exports = createHeader;
Fix count of column in align in header
Fix count of column in align in header
JavaScript
apache-2.0
SamyPesse/draft-js-table,SamyPesse/draft-js-table
--- +++ @@ -18,7 +18,7 @@ type: TYPES.HEADER, data: Immutable.Map({ align: Array - .apply(null, Array(10)) + .apply(null, Array(countColumns)) .map(function(){ return TYPES.LEFT; }) }) });
2a791b1eec3911176211d45c0a87fb7235e3da53
src/simplerating.js
src/simplerating.js
/** * https://github.com/Taranys/simplerating */ angular.module('SimpleRating', []) .directive('simpleRating', function () { return { restrict: 'A', template: '<ul style="padding: 0">' + '<li ng-repeat="star in stars" style="color: #FFD700; cursor: pointer" class="glyphicon" ng-class="getStarClass($index)" ng-click="click($index)"></li>' + '</ul>', scope: { rating: "=", ratingMax: "=", readOnly: "=" }, link: function ($scope) { $scope.getStarClass = function (index) { return ($scope.rating >= index) ? 'glyphicon-star' : 'glyphicon-star-empty'; }; $scope.$watch('rating', function () { $scope.stars = []; for (var i = 0; i < $scope.ratingMax; i++) { $scope.stars.push({}); } }); $scope.click = function (starRating) { if (!$scope.readOnly) { $scope.rating = starRating; } }; } }; });
/** * https://github.com/Taranys/simplerating */ angular.module('SimpleRating', []) .directive('simpleRating', function () { return { restrict: 'A', template: '<ul style="padding: 0">' + '<li ng-repeat="star in stars" style="color: #FFD700" ng-style="getCursor()" class="glyphicon" ng-class="getStarClass($index)" ng-click="click($index)"></li>' + '</ul>', scope: { rating: "=", ratingMax: "=", readOnly: "=" }, link: function ($scope) { $scope.getStarClass = function (index) { return ($scope.rating >= index) ? 'glyphicon-star' : 'glyphicon-star-empty'; }; $scope.getCursor = function() { return { cursor : ($scope.readOnly?'not-allowed':'pointer') }; }; $scope.$watch('rating', function () { $scope.stars = []; for (var i = 0; i < $scope.ratingMax; i++) { $scope.stars.push({}); } }); $scope.click = function (starRating) { if (!$scope.readOnly) { $scope.rating = starRating; } }; } }; });
Add cursor according to read only state
Add cursor according to read only state
JavaScript
mit
Taranys/simplerating
--- +++ @@ -6,7 +6,7 @@ return { restrict: 'A', template: '<ul style="padding: 0">' + - '<li ng-repeat="star in stars" style="color: #FFD700; cursor: pointer" class="glyphicon" ng-class="getStarClass($index)" ng-click="click($index)"></li>' + + '<li ng-repeat="star in stars" style="color: #FFD700" ng-style="getCursor()" class="glyphicon" ng-class="getStarClass($index)" ng-click="click($index)"></li>' + '</ul>', scope: { rating: "=", @@ -16,6 +16,10 @@ link: function ($scope) { $scope.getStarClass = function (index) { return ($scope.rating >= index) ? 'glyphicon-star' : 'glyphicon-star-empty'; + }; + + $scope.getCursor = function() { + return { cursor : ($scope.readOnly?'not-allowed':'pointer') }; }; $scope.$watch('rating', function () {
c7f6963fea105a18b1a7845401b1c9a6ef71250e
cli.js
cli.js
#!/usr/bin/env node var commander = require('commander'); var proxy = require('./proxy.js'); commander // .version(meta.version) .usage('[options] <endpoint>') .option('-p, --port <n>', 'Local proxy port, default 9200', parseInt) .option('-p, --bindIf <ip>', 'Bind to interface, defaults to 127.0.0.1', /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/, '127.0.0.1') .parse(process.argv); if (commander.args.length != 1) { console.error("Missing endpoint parameter"); commander.outputHelp(); process.exit(1); } var endpoint; if (commander.args[0].startsWith('https://')) { endpoint = commander.args[0]; } else { endpoint = 'https://' + commander.args[0]; } var region; try { region = endpoint.match(/\.([^.]+)\.es\.amazonaws\.com\.?$/)[1]; } catch (e) { console.error('Region cannot be parsed from endpoint address'); process.exit(1); } var config = { endpoint: endpoint, region: region, port: commander.port || 9200, bindAddress: commander.bindIf } proxy.run(config);
#!/usr/bin/env node var commander = require('commander'); var proxy = require('./proxy.js'); commander // .version(meta.version) .usage('[options] <endpoint>') .option('-p, --port <n>', 'Local proxy port, default 9200', parseInt) .option('-b, --bindIf <ip>', 'Bind to interface, defaults to 127.0.0.1', /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/, '127.0.0.1') .parse(process.argv); if (commander.args.length != 1) { console.error("Missing endpoint parameter"); commander.outputHelp(); process.exit(1); } var endpoint; if (commander.args[0].startsWith('https://')) { endpoint = commander.args[0]; } else { endpoint = 'https://' + commander.args[0]; } var region; try { region = endpoint.match(/\.([^.]+)\.es\.amazonaws\.com\.?$/)[1]; } catch (e) { console.error('Region cannot be parsed from endpoint address'); process.exit(1); } var config = { endpoint: endpoint, region: region, port: commander.port || 9200, bindAddress: commander.bindIf } proxy.run(config);
Rename short option to avoid conflicts
Rename short option to avoid conflicts
JavaScript
mit
mikael-lindstrom/amazon-elasticsearch-proxy
--- +++ @@ -6,7 +6,7 @@ // .version(meta.version) .usage('[options] <endpoint>') .option('-p, --port <n>', 'Local proxy port, default 9200', parseInt) - .option('-p, --bindIf <ip>', 'Bind to interface, defaults to 127.0.0.1', /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/, '127.0.0.1') + .option('-b, --bindIf <ip>', 'Bind to interface, defaults to 127.0.0.1', /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/, '127.0.0.1') .parse(process.argv); if (commander.args.length != 1) {
d05bb6bca50945ad4cda1b5dc8aa2c47fe0bd9fa
cli.js
cli.js
#!/usr/bin/env node var colors = require('colors'); var ghlint = require('./index'); var util = require('util'); function printResults(repo, results) { console.log(repo + ':'); results.forEach(function (result) { var mark = result.result ? '✓' : '✖'; var output = util.format(' %s %s', mark, result.message); if (colors.enabled) { output = output[result.result ? 'green' : 'red']; } console.log(output); }); } // Remove --no-color from the args if it is there. process.argv = process.argv.filter(function (arg) { return arg !== '--no-color'; }); var repo = process.argv[2]; if (repo) { if (repo.indexOf('/') > -1) { ghlint.lintRepo(repo, function (err, linters) { if (err) { console.error(err); } else { printResults(repo, linters); } }); } else { ghlint.lintUserRepos(repo, function (err, repos) { if (err) { console.error(err); } else { repos.forEach(function (repoResults) { printResults(repoResults.name, repoResults.results); }); } }); } } else { console.error('Usage: ghlint <repo>'); }
#!/usr/bin/env node var colors = require('colors'); var ghlint = require('./index'); var util = require('util'); function printResults(repo, results) { console.log(repo + ':'); results.forEach(function (result) { var mark = result.result ? '✓' : '✖'; var output = util.format(' %s %s', mark, result.message); if (colors.enabled) { output = output[result.result ? 'green' : 'red']; } console.log(output); }); } // Remove --no-color from the args if it is there. process.argv = process.argv.filter(function (arg) { return arg !== '--no-color'; }); var repo = process.argv[2]; if (repo) { if (repo.indexOf('/') > -1) { ghlint.lintRepo(repo, function (err, linters) { if (err) { console.error(err); } else { printResults(repo, linters); } }); } else { ghlint.lintUserRepos(repo, function (err, repos) { if (err) { console.error(err); } else { repos.forEach(function (repoResults, index) { if (index !== 0) { console.log(); } printResults(repoResults.name, repoResults.results); }); } }); } } else { console.error('Usage: ghlint <repo>'); }
Add empty lines between repos in the results
Add empty lines between repos in the results
JavaScript
mit
nicolasmccurdy/ghlint
--- +++ @@ -35,7 +35,10 @@ if (err) { console.error(err); } else { - repos.forEach(function (repoResults) { + repos.forEach(function (repoResults, index) { + if (index !== 0) { + console.log(); + } printResults(repoResults.name, repoResults.results); }); }
2d4cabde9ca45a6032d1cc02a7530ca4ac3194f4
lib/server/index.js
lib/server/index.js
// allow to require('riot') var riot = module.exports = require(process.env.RIOT || require('path').resolve(__dirname, '../../riot')) var compiler = require('riot-compiler') // allow to require('riot').compile riot.compile = compiler.compile riot.parsers = compiler.parsers // allow to require('some.tag') require.extensions['.tag'] = function(module, filename) { var src = riot.compile(require('fs').readFileSync(filename, 'utf8')) module._compile( 'var riot = require(process.env.RIOT || "riot/riot.js");module.exports =' + src , filename) } // simple-dom helper var sdom = require('./sdom') function createTag(tagName, opts) { var root = document.createElement(tagName), tag = riot.mount(root, opts)[0] return tag } riot.render = function(tagName, opts) { var tag = createTag(tagName, opts), html = sdom.serialize(tag.root) // unmount the tag avoiding memory leaks tag.unmount() return html } riot.render.dom = function(tagName, opts) { return createTag(tagName, opts).root }
// allow to require('riot') var riot = module.exports = require(process.env.RIOT || require('path').resolve(__dirname, '../../riot')) var compiler = require('riot-compiler') // allow to require('riot').compile riot.compile = compiler.compile riot.parsers = compiler.parsers // allow to require('some.tag') require.extensions['.tag'] = function(module, filename) { var src = riot.compile(require('fs').readFileSync(filename, 'utf8')) module._compile( 'var riot = require(process.env.RIOT || "riot/riot.js");module.exports =' + src , filename) } // simple-dom helper var sdom = require('./sdom') riot.render = function(tagName, opts) { var tag = riot.render.tag(tagName, opts), html = sdom.serialize(tag.root) // unmount the tag avoiding memory leaks tag.unmount() return html } riot.render.dom = function(tagName, opts) { return riot.render.tag(tagName, opts).root } riot.render.tag = function(tagName, opts) { var root = document.createElement(tagName), tag = riot.mount(root, opts)[0] return tag }
Add riot.render.tag function to create raw tag
Add riot.render.tag function to create raw tag
JavaScript
mit
crisward/riot,muut/riotjs,crisward/riot,muut/riotjs
--- +++ @@ -20,14 +20,8 @@ // simple-dom helper var sdom = require('./sdom') -function createTag(tagName, opts) { - var root = document.createElement(tagName), - tag = riot.mount(root, opts)[0] - return tag -} - riot.render = function(tagName, opts) { - var tag = createTag(tagName, opts), + var tag = riot.render.tag(tagName, opts), html = sdom.serialize(tag.root) // unmount the tag avoiding memory leaks tag.unmount() @@ -35,5 +29,11 @@ } riot.render.dom = function(tagName, opts) { - return createTag(tagName, opts).root + return riot.render.tag(tagName, opts).root } + +riot.render.tag = function(tagName, opts) { + var root = document.createElement(tagName), + tag = riot.mount(root, opts)[0] + return tag +}
3182ff11b3f720a4fd6a1370c822ae4f8e93717b
lib/server/setup.js
lib/server/setup.js
import { Meteor } from 'meteor/meteor'; import { createGraphQLMethod } from './createGraphQLMethod'; import { createGraphQLPublication } from './createGraphQLPublication'; import { DEFAULT_METHOD, DEFAULT_CREATE_CONTEXT, } from '../common/defaults'; export const DDP_APOLLO_SCHEMA_REQUIRED = 'DDP_APOLLO_SCHEMA_REQUIRED'; export function setup({ schema, method = DEFAULT_METHOD, publication, context, } = {}) { if (!schema) { throw new Error(DDP_APOLLO_SCHEMA_REQUIRED); } let createContext; switch (typeof context) { case 'object': createContext = defaultContext => ({ ...defaultContext, ...context }); break; case 'function': createContext = context; break; default: createContext = DEFAULT_CREATE_CONTEXT; } Meteor.methods({ [method]: createGraphQLMethod(schema, { createContext }), }); createGraphQLPublication({ schema, createContext, publication, }); }
import { Meteor } from 'meteor/meteor'; import { createGraphQLMethod } from './createGraphQLMethod'; import { createGraphQLPublication } from './createGraphQLPublication'; import { DEFAULT_METHOD, DEFAULT_CREATE_CONTEXT, } from '../common/defaults'; export const DDP_APOLLO_SCHEMA_REQUIRED = 'DDP_APOLLO_SCHEMA_REQUIRED'; function contextToFunction(context) { switch (typeof context) { case 'object': return defaultContext => ({ ...defaultContext, ...context }); case 'function': return context; default: return DEFAULT_CREATE_CONTEXT; } } export function setup({ schema, method = DEFAULT_METHOD, publication, context, } = {}) { if (!schema) { throw new Error(DDP_APOLLO_SCHEMA_REQUIRED); } const createContext = contextToFunction(context); Meteor.methods({ [method]: createGraphQLMethod(schema, { createContext }), }); createGraphQLPublication({ schema, createContext, publication, }); }
Move context function creation to own function
Move context function creation to own function
JavaScript
mit
Swydo/ddp-apollo
--- +++ @@ -7,6 +7,17 @@ } from '../common/defaults'; export const DDP_APOLLO_SCHEMA_REQUIRED = 'DDP_APOLLO_SCHEMA_REQUIRED'; + +function contextToFunction(context) { + switch (typeof context) { + case 'object': + return defaultContext => ({ ...defaultContext, ...context }); + case 'function': + return context; + default: + return DEFAULT_CREATE_CONTEXT; + } +} export function setup({ schema, @@ -18,18 +29,7 @@ throw new Error(DDP_APOLLO_SCHEMA_REQUIRED); } - let createContext; - - switch (typeof context) { - case 'object': - createContext = defaultContext => ({ ...defaultContext, ...context }); - break; - case 'function': - createContext = context; - break; - default: - createContext = DEFAULT_CREATE_CONTEXT; - } + const createContext = contextToFunction(context); Meteor.methods({ [method]: createGraphQLMethod(schema, { createContext }),
a0f55eaae91935cae72426477a58e29b797b945e
lib/services/tag.js
lib/services/tag.js
import rp from 'request-promise'; import {Microservices} from '../../configs/microservices'; import {isEmpty, assignToAllById} from '../../common'; export default { // fetches the tags data fetchTagInfo(tags) { if (isEmpty(tags)) return Promise.resolve([]); return rp.get({ uri: `${Microservices.tag.uri}/tags`, qs: { tagType: 'all', tagName: tags.map((t) => t.tagName), paging: false, // this allows for unpaged results }, useQuerystring: true, json: true, }); }, };
import rp from 'request-promise'; import {Microservices} from '../../configs/microservices'; import {isEmpty, assignToAllById} from '../../common'; export default { // fetches the tags data fetchTagInfo(tags) { if (isEmpty(tags)) return Promise.resolve([]); return rp.get({ uri: `${Microservices.tag.uri}/tags`, qs: { tagType: 'any', tagName: tags.map((t) => t.tagName), paging: false, // this allows for unpaged results }, useQuerystring: true, json: true, }); }, };
Fix no topics shown when loading a deck (previous commit broke all)
Fix no topics shown when loading a deck (previous commit broke all)
JavaScript
mpl-2.0
slidewiki/slidewiki-platform,slidewiki/slidewiki-platform,slidewiki/slidewiki-platform
--- +++ @@ -12,7 +12,7 @@ return rp.get({ uri: `${Microservices.tag.uri}/tags`, qs: { - tagType: 'all', + tagType: 'any', tagName: tags.map((t) => t.tagName), paging: false, // this allows for unpaged results },
53f182418e4db346f058d22b2f427efe25fc992a
lib/tools/System.js
lib/tools/System.js
'use strict'; var _ = require('lodash'); var path = require('path'); function System() { var self = this; self.clearCache = clearCache; function clearCache(files) { if (files) { clearCacheForFiles(files); } else { clearAllCache(); } } function clearCacheForFiles(files) { _.forEach(files, function (file) { delete require.cache[path.resolve(file)]; }); } function clearAllCache() { _.forOwn(require.cache, function (value, key) { delete require.cache[key]; }); } } module.exports = System;
'use strict'; var _ = require('lodash'); var path = require('path'); function System() { var self = this; self.clearCache = clearCache; function clearCache(files) { if (files) { clearCacheForFiles(files); } else { clearAllCache(); } } function clearCacheForFiles(files) { _.forEach(files, function (file) { delete require.cache[path.resolve(file)]; }); } function clearAllCache() { _.forOwn(require.cache, function (value, key) { if (/\.js$/.test(key)) { delete require.cache[key]; } }); } } module.exports = System;
Clear cache only clear JS files
Clear cache only clear JS files
JavaScript
mit
arpinum-oss/cluck
--- +++ @@ -23,7 +23,9 @@ function clearAllCache() { _.forOwn(require.cache, function (value, key) { - delete require.cache[key]; + if (/\.js$/.test(key)) { + delete require.cache[key]; + } }); } }
6f96baf5660267704857e38c6ca8b48b9f634ae8
www/js/controllers/auth_ctrl.js
www/js/controllers/auth_ctrl.js
(function() { function showLoading(ionicLoading, text) { ionicLoading.show({ template: text, noBackdrop: true, duration: 2000 }); } angular.module("proBebe.controllers") .controller("AuthCtrl", function($scope, $ionicLoading, $state, $window, Constants, authentication, storage) { $scope.login_info = {}; $scope.signUp = function() { $window.open(Constants.SIGN_UP_URL, '_system'); }; $scope.signIn = function() { var authPromise = authentication.authenticate($scope.login_info.email, $scope.login_info.password); $ionicLoading.show({ templateUrl: 'templates/loading.html' }); return authPromise.then(function(result) { if (result) { showLoading($ionicLoading, "Autenticado com sucesso"); $state.go('messages'); } else { showLoading($ionicLoading, "Credenciais inválidas"); } }).catch(function(error) { showLoading($ionicLoading, "Ocorreu um erro na autenticação"); }); }; $scope.signOut = function() { authentication.signOut(); storage.clear(); $state.go('signin'); }; }); })();
(function() { function showLoading(ionicLoading, text) { ionicLoading.show({ template: text, noBackdrop: true, duration: 2000 }); } angular.module("proBebe.controllers") .controller("AuthCtrl", function($scope, $ionicLoading, $state, $window, Constants, authentication, storage) { $scope.login_info = {}; $scope.signUp = function() { $window.open(Constants.SIGN_UP_URL, '_system'); }; $scope.signIn = function() { var authPromise = authentication.authenticate($scope.login_info.email, $scope.login_info.password); $ionicLoading.show({ templateUrl: 'templates/loading.html' }); return authPromise.then(function(result) { if (result) { showLoading($ionicLoading, "Autenticado com sucesso"); $state.go('messages'); location.reload(); } else { showLoading($ionicLoading, "Credenciais inválidas"); } }).catch(function(error) { showLoading($ionicLoading, "Ocorreu um erro na autenticação"); }); }; $scope.signOut = function() { authentication.signOut(); storage.clear(); $state.go('signin'); }; }); })();
Fix layout rendering errors after login
Fix layout rendering errors after login
JavaScript
mit
InstitutoZeroaSeis/probebe-app,InstitutoZeroaSeis/probebe-app
--- +++ @@ -24,6 +24,7 @@ if (result) { showLoading($ionicLoading, "Autenticado com sucesso"); $state.go('messages'); + location.reload(); } else { showLoading($ionicLoading, "Credenciais inválidas"); }
2dfe5a17e5c9b7eab12eef1cbc90da7b85a2ea87
server/models/index.js
server/models/index.js
import fs from 'fs'; import path from 'path'; import Sequelize from 'sequelize'; import dotenv from 'dotenv'; import dbConfig from '../config/config'; const basename = path.basename(module.filename); const env = process.env.NODE_ENV || 'development'; const config = dbConfig[env]; const db = {}; dotenv.config(); let sequelize; if (config.use_env_variable) { sequelize = new Sequelize(process.env.DATABASE_URL); } else { sequelize = new Sequelize(config.database, config.username, config.password, config); } fs .readdirSync(__dirname) .filter(file => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')).forEach((file) => { const model = sequelize.import(path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach((modelName) => { if (db[modelName].associate) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; export default db;
import fs from 'fs'; import path from 'path'; import Sequelize from 'sequelize'; import dotenv from 'dotenv'; import dbConfig from '../config/config'; const basename = path.basename(module.filename); const env = process.env.NODE_ENV || 'development'; const config = dbConfig[env]; const db = {}; dotenv.config(); let sequelize; if (process.env.DATABASE_URL) { sequelize = new Sequelize(process.env.DATABASE_URL); } else if (process.env.DATABASE_TEST_URL) { sequelize = new Sequelize(process.env.DATABASE_TEST_URL); } else { sequelize = new Sequelize(config.database, config.username, config.password, config); } fs .readdirSync(__dirname) .filter(file => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')).forEach((file) => { const model = sequelize.import(path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach((modelName) => { if (db[modelName].associate) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; export default db;
Fix issue with travis configuration
Fix issue with travis configuration
JavaScript
mit
nosisky/Hello-Books,nosisky/Hello-Books
--- +++ @@ -10,8 +10,11 @@ const db = {}; dotenv.config(); let sequelize; -if (config.use_env_variable) { + +if (process.env.DATABASE_URL) { sequelize = new Sequelize(process.env.DATABASE_URL); +} else if (process.env.DATABASE_TEST_URL) { + sequelize = new Sequelize(process.env.DATABASE_TEST_URL); } else { sequelize = new Sequelize(config.database, config.username, config.password, config); }
899fae869b2137511bd2435dedd9950db861a553
examples/handlebars/message/context.js
examples/handlebars/message/context.js
var context = { name : 'Eric', numPhotos: 1000, takenDate: Date.now() };
var context = { name : 'Annie', numPhotos: 1000, takenDate: Date.now() };
Update photos Handlebars example to use "Annie"
Update photos Handlebars example to use "Annie"
JavaScript
bsd-3-clause
okuryu/formatjs-site,ericf/formatjs-site,ericf/formatjs-site
--- +++ @@ -1,5 +1,5 @@ var context = { - name : 'Eric', + name : 'Annie', numPhotos: 1000, takenDate: Date.now() };
4a00a244030d1684972ee7b366a1ecb18fc07cbc
server/ethereum/services/buySvc.js
server/ethereum/services/buySvc.js
const contractHelper = require('../contracts/contractHelpers.js'); const web3Connection = require('../web3.js'); const loggers = require('../loggers/events.js'); const web3 = web3Connection.web3; const buySvc = { buyTicket: (req, res) => { const contractAddress = req.body.contractAddress; // address of deployed contract; const fromAddress = req.body.fromAddress; const name = req.body.name; const eventContractInstance = web3.eth.contract(contractHelper.contractObj).at(contractAddress); eventContractInstance.buyTicket(name, { from: fromAddress, value: req.body.price, }, (err) => { if (err) { console.log(err); loggers(eventContractInstance).ExceedQuota(); loggers(eventContractInstance).InsufficientEther(); res.sendStatus(500); } else { loggers(eventContractInstance).PurchaseTicket((error, result) => { res.status(200).send(`Number of attendees: ${result.args._numAttendees.toString()}`); }); } }); }, }; module.exports = buySvc;
const contractHelper = require('../contracts/contractHelpers.js'); const web3Connection = require('../web3.js'); const loggers = require('../loggers/events.js'); const web3 = web3Connection.web3; const buySvc = { buyTicket: (req, res) => { const contractAddress = req.body.contractAddress; // address of deployed contract; const fromAddress = req.body.fromAddress; const name = req.body.name; const eventContractInstance = web3.eth.contract(contractHelper.contractObj).at(contractAddress); const opts = { from: fromAddress, value: req.body.price, }; if (req.body.gas) { opts.gas = req.body.gas; } eventContractInstance.buyTicket(name, opts, (err) => { if (err) { console.log(err); loggers(eventContractInstance).ExceedQuota(); loggers(eventContractInstance).InsufficientEther(); res.sendStatus(500); } else { loggers(eventContractInstance).PurchaseTicket((error, result) => { res.status(200).send(`Number of attendees: ${result.args._numAttendees.toString()}`); }); } }); }, }; module.exports = buySvc;
Add option to define amount of gas sent in post request
Add option to define amount of gas sent in post request
JavaScript
mit
kevinbrosamle/ticket-sherpa,chrispicato/ticket-sherpa,andrewk17/ticket-sherpa,digitalsherpas/ticket-sherpa,chrispicato/ticket-sherpa,digitalsherpas/ticket-sherpa,kevinbrosamle/ticket-sherpa,andrewk17/ticket-sherpa
--- +++ @@ -10,10 +10,15 @@ const fromAddress = req.body.fromAddress; const name = req.body.name; const eventContractInstance = web3.eth.contract(contractHelper.contractObj).at(contractAddress); - eventContractInstance.buyTicket(name, { + const opts = { from: fromAddress, value: req.body.price, - }, (err) => { + }; + if (req.body.gas) { + opts.gas = req.body.gas; + } + + eventContractInstance.buyTicket(name, opts, (err) => { if (err) { console.log(err); loggers(eventContractInstance).ExceedQuota();
a6c6d36515ebbd797a6e85d20a54a6c9262641b9
src/blacklist/background/quick-blacklist-confirm.js
src/blacklist/background/quick-blacklist-confirm.js
import db, { normaliseFindResult } from 'src/pouchdb' import { deleteDocs } from 'src/page-storage/deletion' import { addToBlacklist } from '..' /** * Handles confirmation and running of a quick blacklist request from the popup script. * * @param {string} url The URL being blacklisted. */ export default async function quickBlacklistConfirm(url) { const { rows } = await getURLMatchingDocs({ url }) if (window.confirm(`Do you want to delete ${rows.length} matching records to ${url}?`)) { deleteDocs(rows) } addToBlacklist(url) } /** * Get all docs with matching URLs. * * @param {string} {url} Value to use to match against doc URLs. */ const getURLMatchingDocs = async ({ url, selector = {} }) => normaliseFindResult( await db.find({ selector: { ...selector, url: { $regex: url }, // All docs whose URLs contain this value }, fields: ['_id', '_rev'], }) )
import db, { normaliseFindResult } from 'src/pouchdb' import { deleteDocs } from 'src/page-storage/deletion' import { addToBlacklist } from '..' /** * Handles confirmation and running of a quick blacklist request from the popup script. * * @param {string} url The URL being blacklisted. */ export default function quickBlacklistConfirm(url) { if (window.confirm(`Do you want to delete all data matching site:\n${url}`)) { getURLMatchingDocs({ url }) .then(result => deleteDocs(result.rows)) .catch(f => f) // Too bad } addToBlacklist(url) } /** * Get all docs with matching URLs. * * @param {string} {url} Value to use to match against doc URLs. */ const getURLMatchingDocs = async ({ url, selector = {} }) => normaliseFindResult( await db.find({ selector: { ...selector, url: { $regex: url }, // All docs whose URLs contain this value }, fields: ['_id', '_rev'], }) )
Remove docs count for user prompt
Remove docs count for user prompt - it simply took too long to query the DB for when the DB is more full (30+ secs) - put indexes on, however would only with with '_id' + 'url', and then querying per doc type ended up taking minutes even with index :/ - now do it async in the background and remove the count given to user
JavaScript
mit
WorldBrain/WebMemex,WorldBrain/WebMemex
--- +++ @@ -7,11 +7,11 @@ * * @param {string} url The URL being blacklisted. */ -export default async function quickBlacklistConfirm(url) { - const { rows } = await getURLMatchingDocs({ url }) - - if (window.confirm(`Do you want to delete ${rows.length} matching records to ${url}?`)) { - deleteDocs(rows) +export default function quickBlacklistConfirm(url) { + if (window.confirm(`Do you want to delete all data matching site:\n${url}`)) { + getURLMatchingDocs({ url }) + .then(result => deleteDocs(result.rows)) + .catch(f => f) // Too bad } addToBlacklist(url)
7795df0b0347afe59de6af3b81cf92d97a74728d
routes/host_meta.js
routes/host_meta.js
var fs = require('fs') var path = require('path') var config = require('../lib/config') var features = require('../lib/features') module.exports = function(req, res) { fs.readFile(path.join(__dirname+'/../package.json'), function(error, packagejson) { fs.readFile(config.get('SSL_CERT'), function(error, certificate) { var properties = { documentation: "https://codius.org/docs/using-codius/getting-started", version: JSON.parse(packagejson.toString()).version, billing: [], public_key: certificate.toString() } if (features.isEnabled('RIPPLE_BILLING')) { properties.billing.push({ network: 'ripple', cpu_per_xrp: parseFloat(config.get('compute_units_per_drop')) * 1000000 }) } if (features.isEnabled('BITCOIN_BILLING')) { properties.billing.push({ network: 'bitcoin', cpu_per_bitcoin: config.get('compute_units_per_bitcoin') }) } res.status(200).send({ properties: properties }) }) }) }
var fs = require('fs') var path = require('path') var config = require('../lib/config') var features = require('../lib/features') module.exports = function(req, res) { fs.readFile(path.join(__dirname+'/../package.json'), function(error, packagejson) { fs.readFile(config.get('ssl:cert'), function(error, certificate) { var properties = { documentation: "https://codius.org/docs/using-codius/getting-started", version: JSON.parse(packagejson.toString()).version, billing: [], public_key: certificate.toString() } if (features.isEnabled('RIPPLE_BILLING')) { properties.billing.push({ network: 'ripple', cpu_per_xrp: parseFloat(config.get('compute_units_per_drop')) * 1000000 }) } if (features.isEnabled('BITCOIN_BILLING')) { properties.billing.push({ network: 'bitcoin', cpu_per_bitcoin: config.get('compute_units_per_bitcoin') }) } res.status(200).send({ properties: properties }) }) }) }
Use ssl:cert isntead of SSL_CERT from nconf
Use ssl:cert isntead of SSL_CERT from nconf
JavaScript
isc
codius/codius-host,codius/codius-host
--- +++ @@ -5,7 +5,7 @@ module.exports = function(req, res) { fs.readFile(path.join(__dirname+'/../package.json'), function(error, packagejson) { - fs.readFile(config.get('SSL_CERT'), function(error, certificate) { + fs.readFile(config.get('ssl:cert'), function(error, certificate) { var properties = { documentation: "https://codius.org/docs/using-codius/getting-started",
a3df753dac911d14c4765db198bc889b7bb6727d
src/clusterpost-execution/jobdelete.js
src/clusterpost-execution/jobdelete.js
var fs = require('fs'); var path = require('path'); module.exports = function(jobid, conf){ var executionmethods = require('./executionserver.methods')(conf); var cwd = path.join(conf.storagedir, jobid); executionmethods.deleteFolderRecursive(cwd); var compressed = cwd + ".tar.gz"; var compressedstat; try{ compressedstat = fs.statSync(compressed); }catch(e){ //does not exist compressedstat = undefined; } if(compressedstat){ fs.unlinkSync(compressed); } }
var fs = require('fs'); var path = require('path'); module.exports = function(jobid, conf, doc){ var executionmethods = require('./executionserver.methods')(conf); var promdoc; if(doc){ promdoc = Promise.resolve(doc); }else{ promdoc = executionmethods.getDocument(jobid) .catch(function(err){ console.error("Job not found before delete.", jobid) }); } return promdoc .then(function(doc){ return require(path.join(__dirname, "jobkill"))(doc, conf); }) .then(function(){ var cwd = path.join(conf.storagedir, jobid); try{ executionmethods.deleteFolderRecursive(cwd); var compressed = cwd + ".tar.gz"; var compressedstat; try{ compressedstat = fs.statSync(compressed); }catch(e){ //does not exist compressedstat = undefined; } if(compressedstat){ fs.unlinkSync(compressed); } }catch(e){ return { error: e } } return { status: "Folder deleted " + jobid } }); }
Check if the job is running.
ENH: Check if the job is running. if the job is running kill the job
JavaScript
apache-2.0
juanprietob/clusterpost,juanprietob/clusterpost,juanprietob/clusterpost
--- +++ @@ -2,24 +2,52 @@ var fs = require('fs'); var path = require('path'); -module.exports = function(jobid, conf){ +module.exports = function(jobid, conf, doc){ var executionmethods = require('./executionserver.methods')(conf); - var cwd = path.join(conf.storagedir, jobid); + var promdoc; + + if(doc){ + promdoc = Promise.resolve(doc); + }else{ + promdoc = executionmethods.getDocument(jobid) + .catch(function(err){ + console.error("Job not found before delete.", jobid) + }); + } + + return promdoc + .then(function(doc){ + return require(path.join(__dirname, "jobkill"))(doc, conf); + }) + .then(function(){ + var cwd = path.join(conf.storagedir, jobid); - executionmethods.deleteFolderRecursive(cwd); - var compressed = cwd + ".tar.gz"; - var compressedstat; - try{ - compressedstat = fs.statSync(compressed); - }catch(e){ - //does not exist - compressedstat = undefined; - } - if(compressedstat){ - fs.unlinkSync(compressed); - } + try{ + executionmethods.deleteFolderRecursive(cwd); + var compressed = cwd + ".tar.gz"; + var compressedstat; + try{ + compressedstat = fs.statSync(compressed); + }catch(e){ + //does not exist + compressedstat = undefined; + } + if(compressedstat){ + fs.unlinkSync(compressed); + } + }catch(e){ + return { + error: e + } + } + + + return { + status: "Folder deleted " + jobid + } + }); }
404231a6b17227bdce7babccf523b8eed379c828
src/components/common/reaction/Base.js
src/components/common/reaction/Base.js
import React from 'react'; import PropTypes from 'prop-types'; import cn from 'classnames'; import styles from './Base.module.css'; const renderLabel = label => { if (typeof label === 'undefined') { return null; } return <div className={styles.label}>{label}</div>; }; const renderCount = count => { if (typeof count === 'undefined') { return null; } return <div className={styles.count}>{count}</div>; }; const Base = ({ className, style, children, label, count, onClick }) => ( <div className={cn(className, styles.container)} style={style} onClick={onClick} > <div>{children}</div> {renderLabel(label)} {renderCount(count)} </div> ); Base.propTypes = { className: PropTypes.string, children: PropTypes.node.isRequired, label: PropTypes.string, count: PropTypes.number, style: PropTypes.object, onClick: PropTypes.func, }; export default Base;
import React from 'react'; import PropTypes from 'prop-types'; import cn from 'classnames'; import styles from './Base.module.css'; const renderLabel = label => { if (typeof label === 'undefined') { return null; } return <div className={styles.label}>{label}</div>; }; const renderCount = count => { if (typeof count === 'undefined') { return null; } return <div className={styles.count}>{count}</div>; }; const Base = ({ className, style, children, label, count, onClick }) => ( <div className={cn(className, styles.container)} style={style} onClick={onClick} > <div>{children}</div> {renderLabel(label)} {renderCount(count)} </div> ); Base.propTypes = { className: PropTypes.string, children: PropTypes.node, label: PropTypes.string, count: PropTypes.number, style: PropTypes.object, onClick: PropTypes.func, }; export default Base;
Fix warning if children is null
Fix warning if children is null
JavaScript
mit
goodjoblife/GoodJobShare
--- +++ @@ -32,7 +32,7 @@ Base.propTypes = { className: PropTypes.string, - children: PropTypes.node.isRequired, + children: PropTypes.node, label: PropTypes.string, count: PropTypes.number, style: PropTypes.object,
d56b4b9ead00cd2b33113d4d155eef10653b7d30
newless.js
newless.js
(function(global) { "use strict"; // ulta-simple Object.create polyfill (only does half the job) var create = Object.create || (function() { var Maker = function(){}; return function(prototype) { Maker.prototype = prototype; return new Maker(); } }()); var newless = function(constructor) { // in order to preserve constructor name, use the Function constructor var newlessConstructor = Function("constructor, create", "var newlessConstructor = function " + constructor.name + "() {" + "var obj = this;" + // don't create a new object if we've already got one // (e.g. we were called with `new`) "if (!(this instanceof newlessConstructor)) {" + "obj = create(newlessConstructor.prototype);" + "}" + // run the original constructor "var returnValue = constructor.apply(obj, arguments);" + // if we got back an object (and not null), use it as the return value "return (typeof returnValue === 'object' && returnValue) || obj;" + "};" + "return newlessConstructor;")(constructor, create); newlessConstructor.prototype = constructor.prototype; newlessConstructor.prototype.constructor = newlessConstructor; newlessConstructor.displayName = constructor.displayName; return newlessConstructor; }; // support Node and browser if (typeof module !== "undefined") { module.exports = newless; } else { global.newless = newless; } }(this));
(function(global) { "use strict"; // ulta-simple Object.create polyfill (only does half the job) var create = Object.create || (function() { var Maker = function(){}; return function(prototype) { Maker.prototype = prototype; return new Maker(); } }()); var newless = function(constructor) { // in order to preserve constructor name, use the Function constructor var name = constructor.name || ""; var newlessConstructor = Function("constructor, create", "var newlessConstructor = function " + name + "() {" + "var obj = this;" + // don't create a new object if we've already got one // (e.g. we were called with `new`) "if (!(this instanceof newlessConstructor)) {" + "obj = create(newlessConstructor.prototype);" + "}" + // run the original constructor "var returnValue = constructor.apply(obj, arguments);" + // if we got back an object (and not null), use it as the return value "return (typeof returnValue === 'object' && returnValue) || obj;" + "};" + "return newlessConstructor;")(constructor, create); newlessConstructor.prototype = constructor.prototype; newlessConstructor.prototype.constructor = newlessConstructor; newlessConstructor.displayName = constructor.displayName; return newlessConstructor; }; // support Node and browser if (typeof module !== "undefined") { module.exports = newless; } else { global.newless = newless; } }(this));
Handle cases where [anonymous function].name is undefined instead of "".
Handle cases where [anonymous function].name is undefined instead of "".
JavaScript
bsd-3-clause
Mr0grog/newless,Mr0grog/newless
--- +++ @@ -12,8 +12,9 @@ var newless = function(constructor) { // in order to preserve constructor name, use the Function constructor + var name = constructor.name || ""; var newlessConstructor = Function("constructor, create", - "var newlessConstructor = function " + constructor.name + "() {" + + "var newlessConstructor = function " + name + "() {" + "var obj = this;" + // don't create a new object if we've already got one // (e.g. we were called with `new`)
3582cfe60a9aec519cfe329c5872af80247212e3
src/js/components/NewPageHeaderTabs.js
src/js/components/NewPageHeaderTabs.js
import classNames from 'classnames/dedupe'; import {Link} from 'react-router'; import React from 'react'; class PageHeaderTabs extends React.Component { render() { let {props: {tabs}} = this; let tabElements = tabs.map(function (tab, index) { let {isActive, callback} = tab; let classes = classNames('menu-tabbed-item', {active: isActive}); let linkClasses = classNames('menu-tabbed-item-label', {active: isActive}); let innerLinkSpan = <span className="menu-tabbed-item-label-text">{tab.label}</span>; return ( <li className={classes} key={index}> <Link className={linkClasses} to={tab.routePath}> <span className="tab-item-label-text"> {tab.label} </span> </Link> </li> ); }); return ( <div className="page-header-navigation"> <ul className="menu-tabbed"> {tabElements} </ul> </div> ); } } PageHeaderTabs.defaultProps = { tabs: [] }; PageHeaderTabs.propTypes = { tabs: React.PropTypes.arrayOf( React.PropTypes.shape({ isActive: React.PropTypes.bool, label: React.PropTypes.node.isRequired, routePath: React.PropTypes.string.isRequired }) ) }; module.exports = PageHeaderTabs;
import classNames from 'classnames/dedupe'; import {Link} from 'react-router'; import React from 'react'; class PageHeaderTabs extends React.Component { render() { let {props: {tabs}} = this; let tabElements = tabs.map(function (tab, index) { let {isActive, callback} = tab; let classes = classNames('menu-tabbed-item', {active: isActive}); let linkClasses = classNames('menu-tabbed-item-label', {active: isActive}); let innerLinkSpan = <span className="menu-tabbed-item-label-text">{tab.label}</span>; let link = tab.callback == null ? <Link className={linkClasses} to={tab.routePath}>{innerLinkSpan}</Link> : <a className={linkClasses} onClick={callback}>{innerLinkSpan}</a>; return ( <li className={classes} key={index}> {link} </li> ); }); return ( <div className="page-header-navigation"> <ul className="menu-tabbed"> {tabElements} </ul> </div> ); } } PageHeaderTabs.defaultProps = { tabs: [] }; PageHeaderTabs.propTypes = { tabs: React.PropTypes.arrayOf( React.PropTypes.shape({ isActive: React.PropTypes.bool, label: React.PropTypes.node.isRequired, routePath: React.PropTypes.string, callback: React.PropTypes.func }) ) }; module.exports = PageHeaderTabs;
Extend tabs to allow callbacks for unrouted tab navigation
Extend tabs to allow callbacks for unrouted tab navigation
JavaScript
apache-2.0
dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui
--- +++ @@ -12,13 +12,13 @@ let linkClasses = classNames('menu-tabbed-item-label', {active: isActive}); let innerLinkSpan = <span className="menu-tabbed-item-label-text">{tab.label}</span>; + let link = tab.callback == null + ? <Link className={linkClasses} to={tab.routePath}>{innerLinkSpan}</Link> + : <a className={linkClasses} onClick={callback}>{innerLinkSpan}</a>; + return ( <li className={classes} key={index}> - <Link className={linkClasses} to={tab.routePath}> - <span className="tab-item-label-text"> - {tab.label} - </span> - </Link> + {link} </li> ); }); @@ -42,7 +42,8 @@ React.PropTypes.shape({ isActive: React.PropTypes.bool, label: React.PropTypes.node.isRequired, - routePath: React.PropTypes.string.isRequired + routePath: React.PropTypes.string, + callback: React.PropTypes.func }) ) };
e8f0219d73e05cbc53c8b9f9820df1f8be207eb6
client/src/app/components/chart/amcharts/graph.service.js
client/src/app/components/chart/amcharts/graph.service.js
(function() { 'use strict'; angular .module('dowser') .factory('AmChartGraph', AmChartGraphService); /** @ngInject */ function AmChartGraphService() { function AmChartGraph(data, index) { return { "balloonText": "[[value]] " + (data.unit || 'un'), "bullet": "round", "dashLengthField": "dashLength", "id": "AmGraph-" + index, "lineAlpha": 1, "bulletSize": 10, "bulletBorderAlpha": 1, "bulletBorderColor": "#455A64", "lineThickness": 3, "markerType": "square", "title": data.category, "valueAxis": "ValueAxis-" + index, "valueField": data.category }; } return AmChartGraph; } })();
(function() { 'use strict'; angular .module('dowser') .factory('AmChartGraph', AmChartGraphService); /** @ngInject */ function AmChartGraphService() { function AmChartGraph(data, index) { return { "balloonText": "[[value]] " + (data.unit || 'un'), "bullet": "round", "dashLengthField": "dashLength", "id": "AmGraph-" + index, "lineAlpha": !index ? 1 : 0.5, "bulletSize": !index ? 10 : 8, "bulletBorderAlpha": !index ? 1 : 0.5, "bulletBorderColor": "#455A64", "lineThickness": 3, "markerType": "square", "title": data.category, "valueAxis": "ValueAxis-" + index, "valueField": data.category }; } return AmChartGraph; } })();
Add alpha to other graphs
Add alpha to other graphs
JavaScript
mit
mitsuishihidemi/dowser,mitsuishihidemi/dowser,mitsuishihidemi/dowser
--- +++ @@ -13,9 +13,9 @@ "bullet": "round", "dashLengthField": "dashLength", "id": "AmGraph-" + index, - "lineAlpha": 1, - "bulletSize": 10, - "bulletBorderAlpha": 1, + "lineAlpha": !index ? 1 : 0.5, + "bulletSize": !index ? 10 : 8, + "bulletBorderAlpha": !index ? 1 : 0.5, "bulletBorderColor": "#455A64", "lineThickness": 3, "markerType": "square",
f2fe1a4a457fb0fb3021f862783efa68f299d967
src/botPage/bot/TradeEngine/Balance.js
src/botPage/bot/TradeEngine/Balance.js
import { roundBalance } from '../../common/tools'; import { info } from '../broadcast'; import { observer as globalObserver } from '../../../common/utils/observer'; export default Engine => class Balance extends Engine { observeBalance() { this.listen('balance', r => { const { balance: { balance: b, currency }, } = r; const balance = roundBalance({ currency, balance: b }); const balanceStr = `${balance} ${currency}`; globalObserver.setState({ balance, currency }); info({ accountID: this.accountInfo.loginid, balance: balanceStr }); }); } // eslint-disable-next-line class-methods-use-this getBalance(type) { const { scope } = this.store.getState(); const currency = globalObserver.getState('currency'); let balance = globalObserver.getState('balance'); // Deduct trade `amount` in this scope for correct value in `balance`-block if (scope === 'BEFORE_PURCHASE') { balance = roundBalance({ balance: Number(balance) - this.tradeOptions.amount, currency, }); } const balanceStr = `${balance}`; return type === 'STR' ? balanceStr : Number(balance); } };
import { roundBalance } from '../../common/tools'; import { info } from '../broadcast'; import { observer as globalObserver } from '../../../common/utils/observer'; export default Engine => class Balance extends Engine { observeBalance() { this.listen('balance', r => { const { balance: { balance: b, currency }, } = r; const balance = roundBalance({ currency, balance: b }); const balanceStr = `${balance} ${currency}`; globalObserver.setState({ balance, currency }); info({ accountID: this.accountInfo.loginid, balance: balanceStr }); }); } // eslint-disable-next-line class-methods-use-this getBalance(type) { const balance = globalObserver.getState('balance'); const balanceStr = `${balance}`; return type === 'STR' ? balanceStr : Number(balance); } };
Remove deducting trade amount prematurely
Remove deducting trade amount prematurely
JavaScript
mit
binary-com/binary-bot,binary-com/binary-bot,aminmarashi/binary-bot,aminmarashi/binary-bot
--- +++ @@ -20,20 +20,8 @@ } // eslint-disable-next-line class-methods-use-this getBalance(type) { - const { scope } = this.store.getState(); - const currency = globalObserver.getState('currency'); - let balance = globalObserver.getState('balance'); - - // Deduct trade `amount` in this scope for correct value in `balance`-block - if (scope === 'BEFORE_PURCHASE') { - balance = roundBalance({ - balance: Number(balance) - this.tradeOptions.amount, - currency, - }); - } - + const balance = globalObserver.getState('balance'); const balanceStr = `${balance}`; - return type === 'STR' ? balanceStr : Number(balance); } };
d1378799a32cafd23f04221286c0198203d39618
src/main/resources/static/js/routes.js
src/main/resources/static/js/routes.js
angular.module('Mccy.routes', [ 'ngRoute' ]) .config(function ($routeProvider) { $routeProvider .when('/view', { templateUrl: 'views/view-containers.html', controller: 'ViewContainersCtrl' }) .when('/new-server', { templateUrl: 'views/create-container.html', controller: 'NewContainerCtrl' }) .when('/upload-mod', { templateUrl: 'views/upload-mod.html', controller: 'UploadModCtrl' }) .when('/manage-mods', { templateUrl: 'views/manage-mods.html', controller: 'ManageModsCtrl' }) .otherwise('/view') }) .constant('MccyViews', [ { view: '/view', settings: { label: 'Current Containers', icon: 'icon fa fa-heartbeat' } }, { view: '/new-server', settings: { label: 'Create Container', icon: 'icon fa fa-magic' } }, { view: '/upload-mod', settings: { label: 'Upload Mods', icon: 'icon fa fa-upload' } }, { view: '/manage-mods', settings: { label: 'Manage Mods', icon: 'icon fa fa-flask' } } ]) ;
angular.module('Mccy.routes', [ 'ngRoute' ]) .config(function ($routeProvider) { $routeProvider .when('/view', { templateUrl: 'views/view-containers.html', controller: 'ViewContainersCtrl' }) .when('/new-server', { templateUrl: 'views/create-container.html', controller: 'NewContainerCtrl' }) .when('/upload-mod', { templateUrl: 'views/upload-mod.html', controller: 'UploadModCtrl' }) .when('/manage-mods', { templateUrl: 'views/manage-mods.html', controller: 'ManageModsCtrl' }) .otherwise('/view') }) .constant('MccyViews', [ { view: '/view', settings: { label: 'Current Containers', icon: 'icon fa fa-heartbeat' } }, { view: '/new-server', settings: { label: 'Create Container', icon: 'icon fa fa-magic' } }, { view: '/upload-mod', settings: { label: 'Upload Mods', icon: 'icon fa fa-upload' } }, { view: '/manage-mods', settings: { label: 'Manage Mods', icon: 'icon fa fa-flask' } } ]) ;
Revert tabs to spaces due to accidental change
Revert tabs to spaces due to accidental change
JavaScript
apache-2.0
itzg/minecraft-container-yard,itzg/minecraft-container-yard,moorkop/mccy-engine,itzg/minecraft-container-yard,itzg/minecraft-container-yard,moorkop/mccy-engine,moorkop/mccy-engine,moorkop/mccy-engine
--- +++ @@ -1,56 +1,56 @@ angular.module('Mccy.routes', [ - 'ngRoute' + 'ngRoute' ]) .config(function ($routeProvider) { - $routeProvider - .when('/view', { - templateUrl: 'views/view-containers.html', - controller: 'ViewContainersCtrl' - }) - .when('/new-server', { - templateUrl: 'views/create-container.html', - controller: 'NewContainerCtrl' - }) - .when('/upload-mod', { - templateUrl: 'views/upload-mod.html', - controller: 'UploadModCtrl' - }) - .when('/manage-mods', { - templateUrl: 'views/manage-mods.html', - controller: 'ManageModsCtrl' - }) - .otherwise('/view') + $routeProvider + .when('/view', { + templateUrl: 'views/view-containers.html', + controller: 'ViewContainersCtrl' + }) + .when('/new-server', { + templateUrl: 'views/create-container.html', + controller: 'NewContainerCtrl' + }) + .when('/upload-mod', { + templateUrl: 'views/upload-mod.html', + controller: 'UploadModCtrl' + }) + .when('/manage-mods', { + templateUrl: 'views/manage-mods.html', + controller: 'ManageModsCtrl' + }) + .otherwise('/view') }) .constant('MccyViews', [ - { - view: '/view', - settings: { - label: 'Current Containers', - icon: 'icon fa fa-heartbeat' - } - }, - { - view: '/new-server', - settings: { - label: 'Create Container', - icon: 'icon fa fa-magic' - } - }, - { - view: '/upload-mod', - settings: { - label: 'Upload Mods', - icon: 'icon fa fa-upload' - } - }, - { - view: '/manage-mods', - settings: { - label: 'Manage Mods', - icon: 'icon fa fa-flask' - } - } + { + view: '/view', + settings: { + label: 'Current Containers', + icon: 'icon fa fa-heartbeat' + } + }, + { + view: '/new-server', + settings: { + label: 'Create Container', + icon: 'icon fa fa-magic' + } + }, + { + view: '/upload-mod', + settings: { + label: 'Upload Mods', + icon: 'icon fa fa-upload' + } + }, + { + view: '/manage-mods', + settings: { + label: 'Manage Mods', + icon: 'icon fa fa-flask' + } + } ]) ;
463b5e5936079c580aa72700f9e872b816b5409c
src/ui/actions/configurationActions.js
src/ui/actions/configurationActions.js
import { connect } from './wsActions' import { setDashboards, play, } from './dashboardsActions' import { notifySuccess, notifyError, } from './notificationsActions' export const FETCH_CONFIGURATION = 'FETCH_CONFIGURATION' export const FETCH_CONFIGURATION_SUCCESS = 'FETCH_CONFIGURATION_SUCCESS' export const FETCH_CONFIGURATION_FAILURE = 'FETCH_CONFIGURATION_FAILURE' export const fetchConfigurationSuccess = configuration => ({ type: FETCH_CONFIGURATION_SUCCESS, configuration, }) const fetchConfigurationFailure = error => ({ type: FETCH_CONFIGURATION_FAILURE, error, }) export const fetchConfiguration = () => { return dispatch => { dispatch({ type: FETCH_CONFIGURATION }) // http://localhost:5000/config return fetch('/config') .then(res => { if (res.status !== 200) { return Promise.reject(`Unable to fetch configuration: ${res.statusText} (${res.status})`) } return res.json() }) .then(configuration => { dispatch(fetchConfigurationSuccess(configuration)) dispatch(connect(configuration)) dispatch(notifySuccess({ message: 'configuration loaded', ttl: 2000, })) dispatch(setDashboards(configuration.dashboards)) dispatch(play()) }) .catch(err => { dispatch(notifyError({ message: `An error occurred while fetching configuration: ${err.message}`, ttl: -1, })) dispatch(fetchConfigurationFailure(err.message)) }) } }
import { connect } from './wsActions' import { setDashboards, play, } from './dashboardsActions' import { notifySuccess, notifyError, } from './notificationsActions' export const FETCH_CONFIGURATION = 'FETCH_CONFIGURATION' export const FETCH_CONFIGURATION_SUCCESS = 'FETCH_CONFIGURATION_SUCCESS' export const FETCH_CONFIGURATION_FAILURE = 'FETCH_CONFIGURATION_FAILURE' export const fetchConfigurationSuccess = configuration => ({ type: FETCH_CONFIGURATION_SUCCESS, configuration, }) const fetchConfigurationFailure = error => ({ type: FETCH_CONFIGURATION_FAILURE, error, }) export const fetchConfiguration = () => { return dispatch => { dispatch({ type: FETCH_CONFIGURATION }) // http://localhost:5000/config return fetch('/config') .then(res => { if (res.status !== 200) { return Promise.reject(new Error( `Unable to fetch configuration: ${res.statusText} (${res.status})`)) } return res.json() }) .then(configuration => { dispatch(fetchConfigurationSuccess(configuration)) dispatch(connect(configuration)) dispatch(notifySuccess({ message: 'configuration loaded', ttl: 2000, })) dispatch(setDashboards(configuration.dashboards)) dispatch(play()) }) .catch(err => { dispatch(notifyError({ message: `An error occurred while fetching configuration: ${err.message}`, ttl: -1, })) dispatch(fetchConfigurationFailure(err.message)) }) } }
Fix undefined reported as error on fetch configuration
Fix undefined reported as error on fetch configuration
JavaScript
mit
plouc/mozaik,plouc/mozaik
--- +++ @@ -30,7 +30,8 @@ return fetch('/config') .then(res => { if (res.status !== 200) { - return Promise.reject(`Unable to fetch configuration: ${res.statusText} (${res.status})`) + return Promise.reject(new Error( + `Unable to fetch configuration: ${res.statusText} (${res.status})`)) } return res.json()
3e2af6645d21512dc2d63e6002757c5dd6439091
src/lib/worldGenerations/nether.js
src/lib/worldGenerations/nether.js
const Vec3 = require('vec3').Vec3 const rand = require('random-seed') function generation ({ version, seed, level = 50 } = {}) { const Chunk = require('prismarine-chunk')(version) const mcData = require('minecraft-data')(version) function generateChunk (chunkX, chunkZ) { const seedRand = rand.create(seed + ':' + chunkX + ':' + chunkZ) const chunk = new Chunk() for (let x = 0; x < 16; x++) { for (let z = 0; z < 16; z++) { const bedrockheighttop = 1 + seedRand(4) const bedrockheightbottom = 1 + seedRand(4) for (let y = 0; y < 128; y++) { // Nether only goes up to 128 let block let data if (y < bedrockheightbottom) block = 7 else if (y < level) block = seedRand(50) === 0 ? mcData.blocksByName.glowstone.id : mcData.blocksByName.netherrack.id else if (y > 127 - bedrockheighttop) block = mcData.blocksByName.bedrock.id const pos = new Vec3(x, y, z) if (block) chunk.setBlockType(pos, block) if (data) chunk.setBlockData(pos, data) // Don't need to set light data in nether } } } return chunk } return generateChunk } module.exports = generation
const Vec3 = require('vec3').Vec3 const rand = require('random-seed') function generation ({ version, seed, level = 50 } = {}) { const Chunk = require('prismarine-chunk')(version) const mcData = require('minecraft-data')(version) function generateChunk (chunkX, chunkZ) { const seedRand = rand.create(seed + ':' + chunkX + ':' + chunkZ) const chunk = new Chunk() for (let x = 0; x < 16; x++) { for (let z = 0; z < 16; z++) { const bedrockheighttop = 1 + seedRand(4) const bedrockheightbottom = 1 + seedRand(4) for (let y = 0; y < 128; y++) { // Nether only goes up to 128 let block let data if (y < bedrockheightbottom) block = mcData.blocksByName.bedrock.id else if (y < level) block = seedRand(50) === 0 ? mcData.blocksByName.glowstone.id : mcData.blocksByName.netherrack.id else if (y > 127 - bedrockheighttop) block = mcData.blocksByName.bedrock.id const pos = new Vec3(x, y, z) if (block) chunk.setBlockType(pos, block) if (data) chunk.setBlockData(pos, data) // Don't need to set light data in nether } } } return chunk } return generateChunk } module.exports = generation
Use bedrock instead of polished andesite
Use bedrock instead of polished andesite
JavaScript
mit
PrismarineJS/flying-squid,mhsjlw/flying-squid,demipixel/flying-squid
--- +++ @@ -16,7 +16,7 @@ let block let data - if (y < bedrockheightbottom) block = 7 + if (y < bedrockheightbottom) block = mcData.blocksByName.bedrock.id else if (y < level) block = seedRand(50) === 0 ? mcData.blocksByName.glowstone.id : mcData.blocksByName.netherrack.id else if (y > 127 - bedrockheighttop) block = mcData.blocksByName.bedrock.id
eb66a08f8974d7ec907f22780599507b6cc16de0
src/panini-helpers/get-nav-data.js
src/panini-helpers/get-nav-data.js
module.exports = function(page, dataType, navigationData) { var re = /(.*)(-\d+)?$/ var array = re.exec(page) if(array && array[1] && navigationData && navigationData[array[1]]) { return navigationData[array[1]][dataType]; } return null; }
module.exports = function(page, dataType, navigationData) { var re = /(.*?)(\-\d+)?$/ var array = re.exec(page) if(array && array[1] && navigationData && navigationData[array[1]]) { return navigationData[array[1]][dataType]; } return null; }
Fix nav data and pagination bug
Fix nav data and pagination bug
JavaScript
mit
zurb/building-blocks,zurb/building-blocks
--- +++ @@ -1,5 +1,5 @@ module.exports = function(page, dataType, navigationData) { - var re = /(.*)(-\d+)?$/ + var re = /(.*?)(\-\d+)?$/ var array = re.exec(page) if(array && array[1] && navigationData && navigationData[array[1]]) { return navigationData[array[1]][dataType];
c689166c48296bcb65a468eff4c30cd56dce60eb
lib/webrat/selenium/location_strategy_javascript/label.js
lib/webrat/selenium/location_strategy_javascript/label.js
RegExp.escape = function(text) { if (!arguments.callee.sRE) { var specials = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\' ]; arguments.callee.sRE = new RegExp( '(\\' + specials.join('|\\') + ')', 'g' ); } return text.replace(arguments.callee.sRE, '\\$1'); } var allLabels = inDocument.getElementsByTagName("label"); var regExp = new RegExp('^\\W*' + RegExp.escape(locator) + '(\\b|$)', 'i'); var candidateLabels = $A(allLabels).select(function(candidateLabel){ var labelText = getText(candidateLabel).strip(); return (labelText.search(regExp) >= 0); }); if (candidateLabels.length == 0) { return null; } //reverse length sort candidateLabels = candidateLabels.sortBy(function(s) { return s.length * -1; }); var locatedLabel = candidateLabels.first(); var labelFor = locatedLabel.getAttribute('for'); if ((labelFor == null) && (locatedLabel.hasChildNodes())) { // TODO: should find the first form field, not just any node return locatedLabel.firstChild; } return selenium.browserbot.locationStrategies['id'].call(this, labelFor, inDocument, inWindow);
// Credit to: http://simonwillison.net/2006/Jan/20/escape/ RegExp.escape = function(text) { if (!arguments.callee.sRE) { var specials = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\' ]; arguments.callee.sRE = new RegExp( '(\\' + specials.join('|\\') + ')', 'g' ); } return text.replace(arguments.callee.sRE, '\\$1'); } var allLabels = inDocument.getElementsByTagName("label"); var regExp = new RegExp('^\\W*' + RegExp.escape(locator) + '(\\b|$)', 'i'); var candidateLabels = $A(allLabels).select(function(candidateLabel){ var labelText = getText(candidateLabel).strip(); return (labelText.search(regExp) >= 0); }); if (candidateLabels.length == 0) { return null; } //reverse length sort candidateLabels = candidateLabels.sortBy(function(s) { return s.length * -1; }); var locatedLabel = candidateLabels.first(); var labelFor = locatedLabel.getAttribute('for'); if ((labelFor == null) && (locatedLabel.hasChildNodes())) { return locatedLabel.getElementsByTagName('button')[0] || locatedLabel.getElementsByTagName('input')[0] || locatedLabel.getElementsByTagName('textarea')[0] || locatedLabel.getElementsByTagName('select')[0]; } return selenium.browserbot.locationStrategies['id'].call(this, labelFor, inDocument, inWindow);
Fix "element.getAttribute is not a function" Selenium errors when filling in fields
Fix "element.getAttribute is not a function" Selenium errors when filling in fields The root cause was the locator strategy was naively returning an element that was not a form field, causing Selenium's internals to blow up
JavaScript
mit
jacksonfish/webrat,irfanah/webrat,johnbintz/webrat,johnbintz/webrat,brynary/webrat,brynary/webrat,irfanah/webrat,irfanah/webrat,jacksonfish/webrat
--- +++ @@ -1,3 +1,4 @@ +// Credit to: http://simonwillison.net/2006/Jan/20/escape/ RegExp.escape = function(text) { if (!arguments.callee.sRE) { var specials = [ @@ -32,8 +33,10 @@ var labelFor = locatedLabel.getAttribute('for'); if ((labelFor == null) && (locatedLabel.hasChildNodes())) { - // TODO: should find the first form field, not just any node - return locatedLabel.firstChild; + return locatedLabel.getElementsByTagName('button')[0] + || locatedLabel.getElementsByTagName('input')[0] + || locatedLabel.getElementsByTagName('textarea')[0] + || locatedLabel.getElementsByTagName('select')[0]; } return selenium.browserbot.locationStrategies['id'].call(this, labelFor, inDocument, inWindow);
bc5ed20ed2f6c26d3e2053a89a7fdf2dfcb88029
src/ui/examples/inspecting-an-object.js
src/ui/examples/inspecting-an-object.js
// If you try printing the below you would see "[object Object]"" which is not that useful. // Instead, you can click "Inspect it" to see the result in the JavaScript console where you can look inside the object. // That result is not displayed in the editor window -- it is only displayed in the console. // To open the console in various browsers, see: // https://webmasters.stackexchange.com/questions/8525/how-do-i-open-the-javascript-console-in-different-browsers // You can also try selecting just parts of the object (like the array) and use "Inspect It" or "Print it". const myObject = { hello: "world", coding: "is fun!", todo: ["learn Mithril.js", "learn Tachyons.css"], snippetIndex: 3 } myObject
// If you try printing the below you would see "[object Object]"" which is not that useful. // Instead, you can click "Inspect it" to see the result in the JavaScript console where you can look inside the object. // That result is not displayed in the editor window -- it is only displayed in the console. // To open the console in various browsers, see: // https://webmasters.stackexchange.com/questions/8525/how-do-i-open-the-javascript-console-in-different-browsers // In most browsers, you can right-click on part of the web page and pick "Inspect" from the popup menu there // and then when the developer tools open, pick the console tab. // You can also try selecting just parts of the object (like the array) and use "Inspect It" or "Print it". const myObject = { hello: "world", coding: "is fun!", todo: ["learn Mithril.js", "learn Tachyons.css"], snippetIndex: 3 } myObject
Improve instructions in inspecting an object for opening console
Improve instructions in inspecting an object for opening console
JavaScript
mit
pdfernhout/Twirlip7,pdfernhout/Twirlip7,pdfernhout/Twirlip7
--- +++ @@ -1,10 +1,11 @@ // If you try printing the below you would see "[object Object]"" which is not that useful. - // Instead, you can click "Inspect it" to see the result in the JavaScript console where you can look inside the object. // That result is not displayed in the editor window -- it is only displayed in the console. // To open the console in various browsers, see: // https://webmasters.stackexchange.com/questions/8525/how-do-i-open-the-javascript-console-in-different-browsers +// In most browsers, you can right-click on part of the web page and pick "Inspect" from the popup menu there +// and then when the developer tools open, pick the console tab. // You can also try selecting just parts of the object (like the array) and use "Inspect It" or "Print it".
b2bc760cf5877dfc75d0b7989fc7964ba8f1b8eb
test/Array.prototype.contains_holes.js
test/Array.prototype.contains_holes.js
// Copyright (C) 2014 Domenic Denicola. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- description: Array.prototype.contains skips holes, and does not treat them as undefined author: Domenic Denicola ---*/ var arrayWithHoles = [,,,]; var result1 = Array.prototype.contains.call(arrayWithHoles, undefined); if (result1 !== true) { $ERROR('Expected array with many holes to contain undefined'); } var arrayWithASingleHole = ['a', 'b',, 'd']; var result2 = arrayWithASingleHole.contains(undefined); if (result2 !== true) { $ERROR('Expected array with a single hole to contain undefined'); }
// Copyright (C) 2014 Domenic Denicola. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- description: Array.prototype.contains does not skip holes; instead it treates them as undefined author: Domenic Denicola ---*/ var arrayWithHoles = [,,,]; var result1 = Array.prototype.contains.call(arrayWithHoles, undefined); if (result1 !== true) { $ERROR('Expected array with many holes to contain undefined'); } var arrayWithASingleHole = ['a', 'b',, 'd']; var result2 = arrayWithASingleHole.contains(undefined); if (result2 !== true) { $ERROR('Expected array with a single hole to contain undefined'); }
Update holes test description to reflect the actual test
Update holes test description to reflect the actual test Closes #23. Kudos to @kentaromiura for finding this!
JavaScript
bsd-2-clause
tc39/Array.prototype.includes,tc39/Array.prototype.includes,tc39/Array.prototype.includes
--- +++ @@ -2,7 +2,7 @@ // This code is governed by the BSD license found in the LICENSE file. /*--- -description: Array.prototype.contains skips holes, and does not treat them as undefined +description: Array.prototype.contains does not skip holes; instead it treates them as undefined author: Domenic Denicola ---*/
5e2882a1ce4c44d7f6c76168006e9b9c6cb8c034
connectors/v2/yandexradio.js
connectors/v2/yandexradio.js
'use strict'; /* global Connector */ Connector.playerSelector = '.page-station__bar'; Connector.trackArtImageSelector = '.slider__items > div:nth-child(3) .track__cover'; Connector.trackSelector = '.slider__items > div:nth-child(3) .track__title'; Connector.artistSelector = '.slider__items > div:nth-child(3) .track__artists'; Connector.isPlaying = function() { return $('body').hasClass('body_state_playing'); };
'use strict'; /* global Connector */ Connector.trackArtImageSelector = '.slider__items > div:nth-child(3) .track__cover'; Connector.trackSelector = '.slider__items > div:nth-child(3) .track__title'; Connector.artistSelector = '.slider__items > div:nth-child(3) .track__artists'; Connector.isPlaying = function() { return $('body').hasClass('body_state_playing'); }; (function() { var actualObserver; var playerObserver = new MutationObserver(function() { var playerSelector = document.querySelector('.page-station__bar'); if (playerSelector !== null) { if (!actualObserver) { actualObserver = new MutationObserver(Connector.onStateChanged); actualObserver.observe(playerSelector, { subtree: true, childList: true, attributes: true, characterData: true }); } } else { if (actualObserver) { actualObserver.disconnect(); actualObserver = null; } } }); playerObserver.observe(document.body, { subtree: true, childList: true, attributes: false, characterData: false }); })();
Fix non-proper work of Yandex radio connector
Fix non-proper work of Yandex radio connector The problem is that scrobbling doesn't work if user selects radio station from station page. If user opens radio station directly from station url, scrobbling works well. And scrobbling stops working if user begins to browse pages on Yandex radio. The solution is creating two MutationObservers. The first one observes appearing of player controls element; if the element is present in DOM, the second observer starts working. It works directly with song changes.
JavaScript
mit
ex47/web-scrobbler,david-sabata/web-scrobbler,inverse/web-scrobbler,carpet-berlin/web-scrobbler,ex47/web-scrobbler,usdivad/web-scrobbler,alexesprit/web-scrobbler,david-sabata/web-scrobbler,alexsh/web-scrobbler,Paszt/web-scrobbler,galeksandrp/web-scrobbler,fakelbst/Chrome-Last.fm-Scrobbler,Paszt/web-scrobbler,alexesprit/web-scrobbler,fakelbst/Chrome-Last.fm-Scrobbler,inverse/web-scrobbler,carpet-berlin/web-scrobbler,usdivad/web-scrobbler,galeksandrp/web-scrobbler,alexsh/web-scrobbler
--- +++ @@ -2,10 +2,40 @@ /* global Connector */ -Connector.playerSelector = '.page-station__bar'; Connector.trackArtImageSelector = '.slider__items > div:nth-child(3) .track__cover'; Connector.trackSelector = '.slider__items > div:nth-child(3) .track__title'; Connector.artistSelector = '.slider__items > div:nth-child(3) .track__artists'; + Connector.isPlaying = function() { return $('body').hasClass('body_state_playing'); }; + +(function() { + var actualObserver; + var playerObserver = new MutationObserver(function() { + var playerSelector = document.querySelector('.page-station__bar'); + if (playerSelector !== null) { + if (!actualObserver) { + actualObserver = new MutationObserver(Connector.onStateChanged); + actualObserver.observe(playerSelector, { + subtree: true, + childList: true, + attributes: true, + characterData: true + }); + } + } else { + if (actualObserver) { + actualObserver.disconnect(); + actualObserver = null; + } + } + }); + + playerObserver.observe(document.body, { + subtree: true, + childList: true, + attributes: false, + characterData: false + }); +})();
6b2ee84cc67ab88bbee18e7b4f947a60b027badd
data-sources/rest-geocode.js
data-sources/rest-geocode.js
var asteroid = require('asteroid'); module.exports = asteroid.createDataSource({ connector: require('asteroid-connector-rest'), debug: false, operations: [ { name: 'geocode', parameters: ['street', 'city', 'zipcode'], request: { "method": "GET", "url": "http://maps.googleapis.com/maps/api/geocode/{format=json}", "headers": { "accepts": "application/json", "content-type": "application/json" }, "query": { "address": "{street},{city},{zipcode}", "sensor": "{sensor=false}" }, "responsePath": "$.results[0].geometry.location" } } ]});
var asteroid = require("asteroid"); module.exports = asteroid.createDataSource({ connector: require("asteroid-connector-rest"), debug: false, operations: [ { template: { "method": "GET", "url": "http://maps.googleapis.com/maps/api/geocode/{format=json}", "headers": { "accepts": "application/json", "content-type": "application/json" }, "query": { "address": "{street},{city},{zipcode}", "sensor": "{sensor=false}" }, "responsePath": "$.results[0].geometry.location" }, functions: { "geocode": ["street", "city", "zipcode"] } } ]});
Update the rest connector config
Update the rest connector config
JavaScript
mit
sam-github/sls-sample-app,svennam92/loopback-example-app,hacksparrow/loopback-example-app,Joddsson/loopback-example-app,svennam92/loopback-example-app,jewelsjacobs/loopback-example-app,strongloop-bluemix/loopback-example-app,craigcabrey/loopback-example-app,strongloop-bluemix/loopback-example-app,rvennam/loopback-example-app,genecyber/loopback-example-app,rvennam/loopback-example-app,hacksparrow/loopback-example-app,jewelsjacobs/loopback-example-app,rvennam/loopback-example-app,p5150j/loopback-example-app,strongloop-bluemix/loopback-example-app,svennam92/loopback-example-app,imkven/loopback-example-app,syzer/sls-sample-app,p5150j/loopback-example-app,amenadiel/loopback-apidoc-bridge,craigcabrey/loopback-example-app,Joddsson/loopback-example-app
--- +++ @@ -1,13 +1,11 @@ -var asteroid = require('asteroid'); +var asteroid = require("asteroid"); module.exports = asteroid.createDataSource({ - connector: require('asteroid-connector-rest'), + connector: require("asteroid-connector-rest"), debug: false, operations: [ { - name: 'geocode', - parameters: ['street', 'city', 'zipcode'], - request: { + template: { "method": "GET", "url": "http://maps.googleapis.com/maps/api/geocode/{format=json}", "headers": { @@ -19,6 +17,9 @@ "sensor": "{sensor=false}" }, "responsePath": "$.results[0].geometry.location" + }, + functions: { + "geocode": ["street", "city", "zipcode"] } } ]});
444b6f71ef1f90e184383e5d89f336874dbf24c0
src/test/js/test-require-config.js
src/test/js/test-require-config.js
/* * Copyright 2014-2015 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ require.config({ baseUrl: 'src/main/webapp/static/js', paths: { 'js-testing': '../lib/hp-autonomy-js-testing-utils/src/js', 'mock': '../../../../test/js/mock' }, map: { '*': { 'find/lib/backbone/backbone-extensions': 'backbone' }, 'find/app/page/indexes/indexes-view': { 'find/app/model/indexes-collection': 'mock/model/indexes-collection' } } });
/* * Copyright 2014-2015 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ require.config({ baseUrl: 'src/main/webapp/static/js', paths: { 'js-testing': '../lib/hp-autonomy-js-testing-utils/src/js', 'mock': '../../../../test/js/mock' }, map: { '*': { 'find/lib/backbone/backbone-extensions': 'backbone' }, 'find/app/page/service-view': { 'find/app/model/indexes-collection': 'mock/model/indexes-collection' } } });
Fix stubbing to prevent tests from trying to talk to server. [rev: daniel.grayling]
Fix stubbing to prevent tests from trying to talk to server. [rev: daniel.grayling]
JavaScript
mit
hpe-idol/java-powerpoint-report,hpautonomy/find,LinkPowerHK/find,hpe-idol/find,hpautonomy/find,hpautonomy/find,LinkPowerHK/find,hpe-idol/find,hpe-idol/find,hpe-idol/find,LinkPowerHK/find,hpautonomy/find,hpautonomy/find,hpe-idol/find,LinkPowerHK/find,hpe-idol/java-powerpoint-report,LinkPowerHK/find
--- +++ @@ -13,7 +13,7 @@ '*': { 'find/lib/backbone/backbone-extensions': 'backbone' }, - 'find/app/page/indexes/indexes-view': { + 'find/app/page/service-view': { 'find/app/model/indexes-collection': 'mock/model/indexes-collection' } }
48ed3b296cd7efa5542f93abbc6226ea8d06e320
test/javascript/public/test/settings.js
test/javascript/public/test/settings.js
QUnit.config.urlConfig.push({ id: "jquery", label: "jQuery version", value: ["3.1.1", "3.0.0", "2.2.4", "2.1.4", "2.0.3", "1.12.4", "1.11.3"], tooltip: "What jQuery Core version to test against" }); /* Hijacks normal form submit; lets it submit to an iframe to prevent * navigating away from the test suite */ $(document).on('submit', function(e) { if (!e.isDefaultPrevented()) { var form = $(e.target), action = form.attr('action'), name = 'form-frame' + jQuery.guid++, iframe = $('<iframe name="' + name + '" />'); if (action && action.indexOf('iframe') < 0) form.attr('action', action + '?iframe=true') form.attr('target', name); $('#qunit-fixture').append(iframe); form.trigger('iframe:loading'); } });
QUnit.config.urlConfig.push({ id: "jquery", label: "jQuery version", value: ["3.2.1", "3.2.0", "3.1.1", "3.0.0", "2.2.4", "2.1.4", "2.0.3", "1.12.4", "1.11.3"], tooltip: "What jQuery Core version to test against" }); /* Hijacks normal form submit; lets it submit to an iframe to prevent * navigating away from the test suite */ $(document).on('submit', function(e) { if (!e.isDefaultPrevented()) { var form = $(e.target), action = form.attr('action'), name = 'form-frame' + jQuery.guid++, iframe = $('<iframe name="' + name + '" />'); if (action && action.indexOf('iframe') < 0) form.attr('action', action + '?iframe=true') form.attr('target', name); $('#qunit-fixture').append(iframe); form.trigger('iframe:loading'); } });
Test against jQuery 3.2.0 and 3.2.1
Test against jQuery 3.2.0 and 3.2.1
JavaScript
mit
DavyJonesLocker/client_side_validations-simple_form,DavyJonesLocker/client_side_validations-simple_form,DavyJonesLocker/client_side_validations-simple_form
--- +++ @@ -1,7 +1,7 @@ QUnit.config.urlConfig.push({ id: "jquery", label: "jQuery version", - value: ["3.1.1", "3.0.0", "2.2.4", "2.1.4", "2.0.3", "1.12.4", "1.11.3"], + value: ["3.2.1", "3.2.0", "3.1.1", "3.0.0", "2.2.4", "2.1.4", "2.0.3", "1.12.4", "1.11.3"], tooltip: "What jQuery Core version to test against" });
6032a34d584f6d8d43ec56112a1b128d10bda6d0
src/jobs/monitor.js
src/jobs/monitor.js
var ds18b20 = require('../services/ds18b20.js'); var logger = require('../services/logger.js'); var _ = require('lodash'); var sensors; var config; var init = function (cfg) { config = cfg || {}; sensors = _.filter(config.sensors, function (sensor) { return sensor.isActive; }); logger.init(config); }; var run = function () { if (!config) { console.log('MONITOR', 'No configuration present'); return; } sensors.forEach(function (sensor) { if (sensor.type == 'temperature') { ds18b20.read(sensor) .then(function (result) { logger.log('MONITOR\tREADING\t' + result.sensor.displayName + '\t' + result.reading.F + '°F'); if (result.sensor.allowedRange) { if (result.reading.F < result.sensor.allowedRange.low || result.reading.F > result.sensor.allowedRange.high) { logger.warn(result.sensor.displayName + ' is out of allowed range: ' + result.reading.F + '°F'); } } }) .catch(function (error) { logger.error('MONITOR\tERROR\t' + error); }); } }); }; exports.init = init; exports.run = run;
var ds18b20 = require('../services/ds18b20.js'); var logger = require('../services/logger.js'); var _ = require('lodash'); var sensors; var config; var init = function (cfg) { config = cfg || {}; logger.init(config); }; var run = function () { if (!config) { console.log('MONITOR', 'No configuration present'); return; } config.sensors.forEach(function (sensor) { if (!sensor.isActive) return; if (sensor.type == 'temperature') { ds18b20.read(sensor) .then(function (result) { logger.log('MONITOR\tREADING\t' + result.sensor.displayName + '\t' + result.reading.F.toFixed(2) + '°F'); if (result.sensor.allowedRange) { if (result.reading.F < result.sensor.allowedRange.low || result.reading.F > result.sensor.allowedRange.high) { logger.warn(result.sensor.displayName + ' is out of allowed range: ' + result.reading.F.toFixed(2) + '°F'); } } }) .catch(function (error) { logger.error('MONITOR\tERROR\t' + error); }); } }); }; exports.init = init; exports.run = run;
Move filter and set fixed precision
Move filter and set fixed precision
JavaScript
mit
Teagan42/MagratheaGrow.in
--- +++ @@ -8,10 +8,6 @@ var init = function (cfg) { config = cfg || {}; - sensors = _.filter(config.sensors, function (sensor) { - return sensor.isActive; - }); - logger.init(config); }; @@ -21,15 +17,17 @@ return; } - sensors.forEach(function (sensor) { + config.sensors.forEach(function (sensor) { + if (!sensor.isActive) return; + if (sensor.type == 'temperature') { ds18b20.read(sensor) .then(function (result) { - logger.log('MONITOR\tREADING\t' + result.sensor.displayName + '\t' + result.reading.F + '°F'); + logger.log('MONITOR\tREADING\t' + result.sensor.displayName + '\t' + result.reading.F.toFixed(2) + '°F'); if (result.sensor.allowedRange) { if (result.reading.F < result.sensor.allowedRange.low || result.reading.F > result.sensor.allowedRange.high) { - logger.warn(result.sensor.displayName + ' is out of allowed range: ' + result.reading.F + '°F'); + logger.warn(result.sensor.displayName + ' is out of allowed range: ' + result.reading.F.toFixed(2) + '°F'); } } })
92ab1eeb3765ac65516fec2235689d34c1cb7ac6
app/containers/NewRequestPage.js
app/containers/NewRequestPage.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import RequestEditor from '../components/RequestEditor'; import ResponseViewer from '../components/ResponseViewer'; import { Request, addRequest, executeRequest } from '../actions/project'; import { selectRequest } from '../actions/ui'; class NewRequestPage extends Component { constructor(props) { super(props); this.state = {}; } componentDidMount() { this.setState({request: new Request({method: 'GET'})}); } addRequest(request) { const action = addRequest(request, this.props.params.projectId); this.props.dispatch(action); this.props.dispatch(selectRequest(action.request)); } onRequestExecute(request) { this.setState({request: request}); this.props.dispatch(executeRequest(request.method, request.url, request.headers.toJS(), request.body)); } render() { if (!this.state.request) return null; return ( <div className="new-request-page"> <RequestEditor request={ this.state.request } onRequestChange={ this.addRequest.bind(this) } onRequestExecute={ this.onRequestExecute.bind(this) }/> <ResponseViewer response={ this.props.response }/> </div> ); } } function mapStateToProps(state) { return { response: state.response } } export default connect(mapStateToProps)(NewRequestPage);
import React, { Component } from 'react'; import { connect } from 'react-redux'; import RequestEditor from '../components/RequestEditor'; import ResponseViewer from '../components/ResponseViewer'; import { Request, addRequest, executeRequest } from '../actions/project'; import { cancel } from '../actions/response'; import { selectRequest } from '../actions/ui'; class NewRequestPage extends Component { constructor(props) { super(props); this.state = {}; } componentDidMount() { this.setState({request: new Request({method: 'GET'})}); } addRequest(request) { const action = addRequest(request, this.props.params.projectId); this.props.dispatch(action); this.props.dispatch(selectRequest(action.request)); } onRequestExecute(request) { this.setState({request: request}); this.props.dispatch(executeRequest(request.method, request.url, request.headers.toJS(), request.body)); } render() { if (!this.state.request) return null; return ( <div className="new-request-page"> <RequestEditor request={ this.state.request } onRequestChange={ this.addRequest.bind(this) } onRequestExecute={ this.onRequestExecute.bind(this) }/> <ResponseViewer response={ this.props.response } onCancel={() => this.props.dispatch(cancel())}/> </div> ); } } function mapStateToProps(state) { return { response: state.response } } export default connect(mapStateToProps)(NewRequestPage);
Allow request cancellation on new request page as well
Allow request cancellation on new request page as well Can use a bit of refactoring, this shouldn't be duplicated between edit request and new request page.
JavaScript
mpl-2.0
pascalw/gettable,pascalw/gettable
--- +++ @@ -3,6 +3,7 @@ import RequestEditor from '../components/RequestEditor'; import ResponseViewer from '../components/ResponseViewer'; import { Request, addRequest, executeRequest } from '../actions/project'; +import { cancel } from '../actions/response'; import { selectRequest } from '../actions/ui'; class NewRequestPage extends Component { @@ -37,7 +38,7 @@ onRequestChange={ this.addRequest.bind(this) } onRequestExecute={ this.onRequestExecute.bind(this) }/> - <ResponseViewer response={ this.props.response }/> + <ResponseViewer response={ this.props.response } onCancel={() => this.props.dispatch(cancel())}/> </div> ); }
5181e1f5bc4efb1c1dd6682137b3af7079c262a6
app/controllers/questions/new.js
app/controllers/questions/new.js
import Ember from 'ember'; export default Ember.Controller.extend({ needs: ['application'], selectedPerson: Ember.computed.alias('controllers.application.attrs.person'), errorMessage: null, titleIsValid: function() { var title = this.get('model.title'); return (!Ember.isEmpty(title) && title.length > 2); }.property('model.title'), emailIsValid: function() { var email = this.get('model.user.email'), re = new RegExp(/\S+@\S+\.\S+/); return (!Ember.isEmpty(email) && re.test(email)); }.property('model.user.email'), isValid: function() { return (this.get('titleIsValid') && this.get('emailIsValid')); }.property('titleIsValid', 'emailIsValid') });
import Ember from 'ember'; export default Ember.Controller.extend({ needs: ['application'], selectedPerson: Ember.computed.alias('controllers.application.attrs.person'), errorMessage: null, titleIsValid: Ember.computed('model.title', function() { var title = this.get('model.title'); return (!Ember.isEmpty(title) && title.length > 2); }), emailIsValid: Ember.computed('model.user.email', function() { var email = this.get('model.user.email'), re = new RegExp(/\S+@\S+\.\S+/); return (!Ember.isEmpty(email) && re.test(email)); }), isValid: Ember.computed('titleIsValid', 'emailIsValid', function() { return (this.get('titleIsValid') && this.get('emailIsValid')); }) });
Switch computed property syntax via ember-watson
Switch computed property syntax via ember-watson
JavaScript
mit
opengovernment/person-widget,opengovernment/person-widget
--- +++ @@ -4,18 +4,18 @@ needs: ['application'], selectedPerson: Ember.computed.alias('controllers.application.attrs.person'), errorMessage: null, - titleIsValid: function() { + titleIsValid: Ember.computed('model.title', function() { var title = this.get('model.title'); return (!Ember.isEmpty(title) && title.length > 2); - }.property('model.title'), - emailIsValid: function() { + }), + emailIsValid: Ember.computed('model.user.email', function() { var email = this.get('model.user.email'), re = new RegExp(/\S+@\S+\.\S+/); return (!Ember.isEmpty(email) && re.test(email)); - }.property('model.user.email'), - isValid: function() { + }), + isValid: Ember.computed('titleIsValid', 'emailIsValid', function() { return (this.get('titleIsValid') && this.get('emailIsValid')); - }.property('titleIsValid', 'emailIsValid') + }) });
2c759dd22048b855bee5617ec7fc11edb99e94d9
app/components/layout/Banners/index.js
app/components/layout/Banners/index.js
import React from 'react'; import PipelinesBanner from './pipelines'; class Banners extends React.Component { render() { return ( <div className="container mb4"> <PipelinesBanner id="pipelines" onHideClick={this.handleBannerHide} /> </div> ) } handleBannerHide = (id) => { console.log('removing ', id); }; } export default Banners;
import React from 'react'; import PipelinesBanner from './pipelines'; class Banners extends React.Component { state = { hidden: {} }; render() { let nodes = []; if(window._banners) { for(const id of window._banners) { if(!this.state.hidden[id]) { nodes.push(<PipelinesBanner id={id} key={id} onHideClick={this.handleBannerHide} />); } } } if(nodes.length) { return ( <div className="container mb4"> {nodes} </div> ) } else { return null; } } handleBannerHide = (id) => { let hidden = this.state.hidden; hidden[id] = true; this.setState({ hidden: hidden }); }; } export default Banners;
Hide banners when you click the "close" button
Hide banners when you click the "close" button
JavaScript
mit
fotinakis/buildkite-frontend,buildkite/frontend,fotinakis/buildkite-frontend,buildkite/frontend
--- +++ @@ -3,16 +3,36 @@ import PipelinesBanner from './pipelines'; class Banners extends React.Component { + state = { + hidden: {} + }; + render() { - return ( - <div className="container mb4"> - <PipelinesBanner id="pipelines" onHideClick={this.handleBannerHide} /> - </div> - ) + let nodes = []; + if(window._banners) { + for(const id of window._banners) { + if(!this.state.hidden[id]) { + nodes.push(<PipelinesBanner id={id} key={id} onHideClick={this.handleBannerHide} />); + } + } + } + + if(nodes.length) { + return ( + <div className="container mb4"> + {nodes} + </div> + ) + } else { + return null; + } } handleBannerHide = (id) => { - console.log('removing ', id); + let hidden = this.state.hidden; + hidden[id] = true; + + this.setState({ hidden: hidden }); }; }
ffa453412ebe8e6c0ca588d6478138a89c6073dd
client/app/app.js
client/app/app.js
import angular from 'angular'; import uiRouter from 'angular-ui-router'; import ngMaterial from 'angular-material'; import Common from './common/common'; import Components from './components/components'; import AppComponent from './app.component'; import AppMaterial from './app.material'; import 'normalize.css'; import '../../node_modules/angular-material/angular-material.css'; angular.module('app', [ uiRouter, ngMaterial, Common, Components ]).config(($stateProvider, $locationProvider, $urlRouterProvider) => { "ngInject"; $locationProvider.html5Mode(false).hashPrefix('!'); $stateProvider .state('app', { abstract: true, url: '/' }); $urlRouterProvider.otherwise('/login'); }) .config(AppMaterial) .component('app', AppComponent);
import angular from 'angular'; import uiRouter from 'angular-ui-router'; import ngMaterial from 'angular-material'; import Common from './common/common'; import Components from './components/components'; import AppComponent from './app.component'; import AppMaterial from './app.material'; import 'normalize.css'; import '../../node_modules/angular-material/angular-material.css'; angular.module('app', [ uiRouter, ngMaterial, Common, Components ]).config(($stateProvider, $locationProvider, $urlRouterProvider, $httpProvider) => { "ngInject"; $locationProvider.html5Mode(false).hashPrefix('!'); $stateProvider .state('app', { abstract: true, url: '/' }); $urlRouterProvider.otherwise('/login'); $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; }) .config(AppMaterial) .component('app', AppComponent);
Configure angular to use django csrf token
Configure angular to use django csrf token
JavaScript
mit
yunity/karrot-frontend,yunity/foodsaving-frontend,yunity/karrot-frontend,yunity/karrot-frontend,yunity/foodsaving-frontend,yunity/foodsaving-frontend,yunity/karrot-frontend,yunity/foodsaving-frontend
--- +++ @@ -13,7 +13,7 @@ ngMaterial, Common, Components -]).config(($stateProvider, $locationProvider, $urlRouterProvider) => { +]).config(($stateProvider, $locationProvider, $urlRouterProvider, $httpProvider) => { "ngInject"; $locationProvider.html5Mode(false).hashPrefix('!'); $stateProvider @@ -21,7 +21,9 @@ abstract: true, url: '/' }); - $urlRouterProvider.otherwise('/login'); + $urlRouterProvider.otherwise('/login'); + $httpProvider.defaults.xsrfCookieName = 'csrftoken'; + $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; }) .config(AppMaterial) .component('app', AppComponent);
d3e2df79ecf33d7284fbb0d868d866b776dabce1
public/js/script.js
public/js/script.js
$(function () { $('#search_movie').submit(function(){ var $form = $(this); var movieName = $form.children('#movie_name_input').val(); var movieYear = $form.children('#movie_year_input').val(); var apiUrl = $form.attr('action') + "/" + movieYear + "/" + movieName; $.get(apiUrl, function(movie){ var movie_html = ""; movie_html += "<h3>" + movie.name + "(" + movie.info.year + ")</h3>"; movie_html += '<img src="' + movie.info.poster + '">'; movie_html += "<h4>Combined Rating: " + movie.combined_rating + "</h4>"; var movie_ratings = "<h4>Ratings: </h4>"; $.each(movie.ratings, function(rating_site, rating) { movie_ratings += "<h4>" + rating_site + ":</h4>"; $.each(rating, function(key, value) { movie_ratings += "<p>"; movie_ratings += "<b>" + key + "</b>: " + value; }); }); movie_html += movie_ratings; $('#result').html(movie_html); }); return false; }); });
$(function () { $('#search_movie').submit(function(){ var $form = $(this); var movieName = $form.children('#movie_name_input').val(); var movieYear = $form.children('#movie_year_input').val(); var apiUrl = $form.attr('action') + "/" + movieYear + "/" + movieName; $.get(apiUrl, function(movie){ var movie_html = ""; movie_html += "<h3>" + movie.name + " (" + movie.info.year + ")</h3>"; movie_html += '<img src="' + movie.info.poster + '">'; movie_html += "<h4>Combined Rating: " + movie.combined_rating + "</h4>"; var movie_ratings = "<h4>Ratings: </h4>"; $.each(movie.ratings, function(rating_site, rating) { movie_ratings += '<h4><a href="' + rating.url + '">'; movie_ratings += rating_site + '</a>:</h4> ' + rating.score; }); movie_html += movie_ratings; $('#result').html(movie_html); }); return false; }); });
Modify output on index page
Modify output on index page
JavaScript
mit
mrnugget/anygood,mrnugget/anygood,mrnugget/anygood
--- +++ @@ -9,17 +9,14 @@ $.get(apiUrl, function(movie){ var movie_html = ""; - movie_html += "<h3>" + movie.name + "(" + movie.info.year + ")</h3>"; + movie_html += "<h3>" + movie.name + " (" + movie.info.year + ")</h3>"; movie_html += '<img src="' + movie.info.poster + '">'; movie_html += "<h4>Combined Rating: " + movie.combined_rating + "</h4>"; var movie_ratings = "<h4>Ratings: </h4>"; $.each(movie.ratings, function(rating_site, rating) { - movie_ratings += "<h4>" + rating_site + ":</h4>"; - $.each(rating, function(key, value) { - movie_ratings += "<p>"; - movie_ratings += "<b>" + key + "</b>: " + value; - }); + movie_ratings += '<h4><a href="' + rating.url + '">'; + movie_ratings += rating_site + '</a>:</h4> ' + rating.score; }); movie_html += movie_ratings;
ec52eae6fc73d3b38a1d8b06dabd817849306474
src/app/twitter/tweets/index.js
src/app/twitter/tweets/index.js
const ScheduleTweet = require('./ScheduleTweet'); const GearTweet = require('./GearTweet'); const SalmonRunTweet = require('./SalmonRunTweet'); const SalmonRunGearTweet = require('./SalmonRunGearTweet'); const NewWeaponTweet = require('./NewWeaponTweet'); const NewStageTweet = require('./NewStageTweet'); const SplatfestTweet = require('./SplatfestTweet'); module.exports = [ new ScheduleTweet, new GearTweet, new SalmonRunTweet, new SalmonRunGearTweet, new NewWeaponTweet, new NewStageTweet, new SplatfestTweet('na'), new SplatfestTweet('eu'), new SplatfestTweet('jp'), ];
const ScheduleTweet = require('./ScheduleTweet'); const GearTweet = require('./GearTweet'); const SalmonRunTweet = require('./SalmonRunTweet'); // const SalmonRunGearTweet = require('./SalmonRunGearTweet'); const NewWeaponTweet = require('./NewWeaponTweet'); const NewStageTweet = require('./NewStageTweet'); const SplatfestTweet = require('./SplatfestTweet'); module.exports = [ new ScheduleTweet, new GearTweet, new SalmonRunTweet, // new SalmonRunGearTweet, new NewWeaponTweet, new NewStageTweet, new SplatfestTweet('na'), new SplatfestTweet('eu'), new SplatfestTweet('jp'), ];
Disable the new Salmon Run gear tweet for now
Disable the new Salmon Run gear tweet for now
JavaScript
mit
misenhower/splatoon2.ink,misenhower/splatoon2.ink,misenhower/splatoon2.ink
--- +++ @@ -1,7 +1,7 @@ const ScheduleTweet = require('./ScheduleTweet'); const GearTweet = require('./GearTweet'); const SalmonRunTweet = require('./SalmonRunTweet'); -const SalmonRunGearTweet = require('./SalmonRunGearTweet'); +// const SalmonRunGearTweet = require('./SalmonRunGearTweet'); const NewWeaponTweet = require('./NewWeaponTweet'); const NewStageTweet = require('./NewStageTweet'); const SplatfestTweet = require('./SplatfestTweet'); @@ -10,7 +10,7 @@ new ScheduleTweet, new GearTweet, new SalmonRunTweet, - new SalmonRunGearTweet, + // new SalmonRunGearTweet, new NewWeaponTweet, new NewStageTweet, new SplatfestTweet('na'),
160a3b046fd10c898acc8c8761dcf670d96bb4c8
src/components/general/Error.js
src/components/general/Error.js
/** * Error Screen * <Error text={'Server is down'} /> * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ import React, { PropTypes } from 'react'; import { View } from 'react-native'; import Icon from 'react-native-vector-icons/Ionicons'; // Consts and Libs import { AppStyles } from '@theme/'; // Components import { Spacer, Text } from '@ui/'; /* Component ==================================================================== */ const Error = ({ text }) => ( <View style={[AppStyles.container, AppStyles.containerCentered]}> <Icon name={'ios-alert-outline'} size={50} color={'#CCC'} /> <Spacer size={10} /> <Text>{text}</Text> </View> ); Error.propTypes = { text: PropTypes.string }; Error.defaultProps = { text: 'Woops, Something went wrong.' }; Error.componentName = 'Error'; /* Export Component ==================================================================== */ export default Error;
/** * Error Screen * <Error text={'Server is down'} /> * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ import React, { PropTypes } from 'react'; import { View } from 'react-native'; import Icon from 'react-native-vector-icons/Ionicons'; // Consts and Libs import { AppStyles } from '@theme/'; // Components import { Spacer, Text, Button } from '@ui/'; /* Component ==================================================================== */ const Error = ({ text, tryAgain }) => ( <View style={[AppStyles.container, AppStyles.containerCentered]}> <Icon name={'ios-alert-outline'} size={50} color={'#CCC'} /> <Spacer size={10} /> <Text>{text}</Text> <Spacer size={20} /> {!!tryAgain && <Button small outlined title={'Try again'} onPress={() => tryAgain()} /> } </View> ); Error.propTypes = { text: PropTypes.string, tryAgain: PropTypes.func }; Error.defaultProps = { text: 'Woops, Something went wrong.' }; Error.componentName = 'Error'; /* Export Component ==================================================================== */ export default Error;
Add try again button to error screen
Add try again button to error screen
JavaScript
mit
arayi/SLions,b1alpha/Smoothie-Du-Jour,arayi/SLions,arayi/SLions,b1alpha/Smoothie-Du-Jour,b1alpha/Smoothie-Du-Jour
--- +++ @@ -14,22 +14,34 @@ import { AppStyles } from '@theme/'; // Components -import { Spacer, Text } from '@ui/'; +import { Spacer, Text, Button } from '@ui/'; /* Component ==================================================================== */ -const Error = ({ text }) => ( +const Error = ({ text, tryAgain }) => ( <View style={[AppStyles.container, AppStyles.containerCentered]}> <Icon name={'ios-alert-outline'} size={50} color={'#CCC'} /> <Spacer size={10} /> <Text>{text}</Text> + + <Spacer size={20} /> + + {!!tryAgain && + <Button + small + outlined + title={'Try again'} + onPress={() => tryAgain()} + /> + } </View> ); -Error.propTypes = { text: PropTypes.string }; +Error.propTypes = { text: PropTypes.string, tryAgain: PropTypes.func }; Error.defaultProps = { text: 'Woops, Something went wrong.' }; Error.componentName = 'Error'; /* Export Component ==================================================================== */ export default Error; +
2f9a83ad860a2c3dcbe97715f73cd958ddd5afcb
src/javascript/pages/chartapp.js
src/javascript/pages/chartapp.js
(function () { 'use strict'; var isMac = /Mac/i.test(navigator.platform), isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent), isAndroid = /Android/i.test(navigator.userAgent), isWindowsPhone = /Windows Phone/i.test(navigator.userAgent), isJavaInstalled = (deployJava.getJREs().length > 0) && deployJava.versionCheck("1.5+"), isMobile = isIOS || isAndroid || isWindowsPhone, canBeInstalled = isJavaInstalled && !isMobile; $('#install-java').toggle(!isJavaInstalled); $('#download-app').toggle(canBeInstalled); $('#install-java').on('click', function () { deployJava.installLatestJava(); }); $('#download-app').on('click', function () { if (isMac) { alert('You need to change your security preferences!'); return; } if (isMobile) { alert('The charting app is not available on mobile devices!'); } }); })();
(function () { 'use strict'; var isMac = /Mac/i.test(navigator.platform), isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent), isAndroid = /Android/i.test(navigator.userAgent), isWindowsPhone = /Windows Phone/i.test(navigator.userAgent), isJavaInstalled = (deployJava.getJREs().length > 0) && deployJava.versionCheck("1.5+"), isMobile = isIOS || isAndroid || isWindowsPhone, canBeInstalled = isJavaInstalled && !isMobile; $('#install-java').toggle(!isJavaInstalled); $('#download-app').toggle(canBeInstalled); $('#install-java').on('click', function () { deployJava.installLatestJRE(); }); $('#download-app').on('click', function () { if (isMac) { alert('You need to change your security preferences!'); return; } if (isMobile) { alert('The charting app is not available on mobile devices!'); } }); })();
Fix java chart install link broken issue
Fix java chart install link broken issue
JavaScript
apache-2.0
einhverfr/binary-static,junbon/binary-static-www2,massihx/binary-static,animeshsaxena/binary-static,einhverfr/binary-static,borisyankov/binary-static,einhverfr/binary-static,animeshsaxena/binary-static,borisyankov/binary-static,brodiecapel16/binary-static,brodiecapel16/binary-static,borisyankov/binary-static,animeshsaxena/binary-static,massihx/binary-static,einhverfr/binary-static,borisyankov/binary-static,massihx/binary-static,brodiecapel16/binary-static,junbon/binary-static-www2,massihx/binary-static,tfoertsch/binary-static,brodiecapel16/binary-static,animeshsaxena/binary-static,tfoertsch/binary-static
--- +++ @@ -13,7 +13,7 @@ $('#download-app').toggle(canBeInstalled); $('#install-java').on('click', function () { - deployJava.installLatestJava(); + deployJava.installLatestJRE(); }); $('#download-app').on('click', function () {