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
0e4cebad2acb269667b14ddc58cb3bb172809234
katas/es6/language/block-scoping/let.js
katas/es6/language/block-scoping/let.js
// block scope - let // To do: make all tests pass, leave the asserts unchanged! describe('`let` restricts the scope of the variable to the current block', () => { describe('`let` vs. `var`', () => { it('`var` works as usual', () => { if (true) { var varX = true; } assert.equal(varX, true); }); it('`let` restricts scope to inside the block', () => { if(true) { let letX = true; } assert.throws(() => console.log(letX)); }); }); it('`let` use in `for` loops', () => { let obj = {x: 1}; for (let key in obj) {} assert.throws(() => console.log(key)); }); it('create artifical scope, using curly braces', () => { { let letX = true; } assert.throws(() => console.log(letX)); }); });
// block scope - let // To do: make all tests pass, leave the asserts unchanged! describe('`let` restricts the scope of the variable to the current block', () => { describe('`let` vs. `var`', () => { it('`var` works as usual', () => { if (true) { let varX = true; } assert.equal(varX, true); }); it('`let` restricts scope to inside the block', () => { if (true) { var letX = true; } assert.throws(() => console.log(letX)); }); }); describe('`let` usage', () => { it('`let` use in `for` loops', () => { let obj = {x: 1}; for (var key in obj) {} assert.throws(() => console.log(key)); }); it('create artifical scope, using curly braces', () => { { var letX = true; } assert.throws(() => console.log(letX)); }); }); });
Make it nicer and break it, to be a kata :).
Make it nicer and break it, to be a kata :).
JavaScript
mit
cmisenas/katas,JonathanPrince/katas,cmisenas/katas,rafaelrocha/katas,JonathanPrince/katas,ehpc/katas,cmisenas/katas,rafaelrocha/katas,JonathanPrince/katas,Semigradsky/katas,tddbin/katas,ehpc/katas,tddbin/katas,Semigradsky/katas,Semigradsky/katas,rafaelrocha/katas,tddbin/katas,ehpc/katas
--- +++ @@ -7,31 +7,35 @@ it('`var` works as usual', () => { if (true) { - var varX = true; + let varX = true; } assert.equal(varX, true); }); it('`let` restricts scope to inside the block', () => { - if(true) { - let letX = true; + if (true) { + var letX = true; + } + assert.throws(() => console.log(letX)); + }); + + }); + + describe('`let` usage', () => { + + it('`let` use in `for` loops', () => { + let obj = {x: 1}; + for (var key in obj) {} + assert.throws(() => console.log(key)); + }); + + it('create artifical scope, using curly braces', () => { + { + var letX = true; } assert.throws(() => console.log(letX)); }); }); - it('`let` use in `for` loops', () => { - let obj = {x: 1}; - for (let key in obj) {} - assert.throws(() => console.log(key)); - }); - - it('create artifical scope, using curly braces', () => { - { - let letX = true; - } - assert.throws(() => console.log(letX)); - }); - });
713377318286d72bc7836c0a79d4060f95d163ef
server/_config.js
server/_config.js
let selectENV = (env) => { if (env === 'development') { return 'postgres://localhost:5432/todos'; } else if (env === 'test') { return 'postgres://localhost:5432/todos_test_db'; } } module.exports = { selectENV };
let selectENV = (env) => { if (env === 'development') { return 'postgres://localhost:5432/todos'; } else if (env === 'test') { return 'postgres://localhost:5432/todos_test'; } } module.exports = { selectENV };
Fix typo in setDev func
Fix typo in setDev func
JavaScript
mit
spencerdezartsmith/to-do-list-app,spencerdezartsmith/to-do-list-app
--- +++ @@ -2,7 +2,7 @@ if (env === 'development') { return 'postgres://localhost:5432/todos'; } else if (env === 'test') { - return 'postgres://localhost:5432/todos_test_db'; + return 'postgres://localhost:5432/todos_test'; } }
9fd827df81a400df1577c3405a646e26a1b17c51
src/exampleApp.js
src/exampleApp.js
"use strict"; // For conditions of distribution and use, see copyright notice in LICENSE /* * @author Tapani Jamsa * @author Erno Kuusela * @author Toni Alatalo * Date: 2013 */ var app = new Application(); app.host = "localhost"; // IP to the Tundra server app.port = 2345; // and port to the server app.start(); // app.viewer.useCubes = true; // Use wireframe cube material for all objects app.connect(app.host, app.port);
"use strict"; // For conditions of distribution and use, see copyright notice in LICENSE /* * @author Tapani Jamsa * @author Erno Kuusela * @author Toni Alatalo * Date: 2013 */ var app = new Application(); var host = "localhost"; // IP to the Tundra server var port = 2345; // and port to the server app.start(); // app.viewer.useCubes = true; // Use wireframe cube material for all objects app.connect(host, port);
Make host and port standard variables
Make host and port standard variables
JavaScript
apache-2.0
playsign/WebTundra,AlphaStaxLLC/WebTundra,realXtend/WebTundra,AlphaStaxLLC/WebTundra,playsign/WebTundra,AlphaStaxLLC/WebTundra,realXtend/WebTundra
--- +++ @@ -10,11 +10,11 @@ var app = new Application(); -app.host = "localhost"; // IP to the Tundra server -app.port = 2345; // and port to the server +var host = "localhost"; // IP to the Tundra server +var port = 2345; // and port to the server app.start(); // app.viewer.useCubes = true; // Use wireframe cube material for all objects -app.connect(app.host, app.port); +app.connect(host, port);
7dcb583e7425bff4964b1e3ce52c745c512b1489
src/game/index.js
src/game/index.js
import Phaser from 'phaser-ce'; import { getConfig } from './config'; import TutorialState from './TutorialState'; export default class WreckSam { constructor() { const config = getConfig(); this.game = new Phaser.Game(config); this.game.state.add('tutorial', new TutorialState()); } start(state) { this.game.state.start(state); } pause(){ this.game.lockRender = true; } unpause(){ this.game.lockRender = false; } destroy() { this.game.destroy(); this.game = null; } }
import Phaser from 'phaser-ce'; import { getConfig } from './config'; import TutorialState from './TutorialState'; export default class WreckSam { constructor() { const config = getConfig(); this.game = new Phaser.Game(config); this.game.state.add('tutorial', new TutorialState()); } start(state) { this.game.state.start(state); } pause(){ this.game.paused = true; } unpause(){ this.game.paused = false; } destroy() { this.game.destroy(); this.game = null; } }
Use game paused property instead of lockRender
Use game paused property instead of lockRender
JavaScript
mit
marc1404/WreckSam,marc1404/WreckSam
--- +++ @@ -16,11 +16,11 @@ } pause(){ - this.game.lockRender = true; + this.game.paused = true; } unpause(){ - this.game.lockRender = false; + this.game.paused = false; } destroy() {
ec679a27b227877a5e383af2bf9deabf0a3c2072
loader.js
loader.js
// Loader to create the Ember.js application /*global require */ window.App = require('ghost/app')['default'].create();
// Loader to create the Ember.js application /*global require */ if (!window.disableBoot) { window.App = require('ghost/app')['default'].create(); }
Add initial client unit test.
Add initial client unit test.
JavaScript
mit
kevinansfield/Ghost-Admin,acburdine/Ghost-Admin,airycanon/Ghost-Admin,JohnONolan/Ghost-Admin,airycanon/Ghost-Admin,TryGhost/Ghost-Admin,JohnONolan/Ghost-Admin,TryGhost/Ghost-Admin,dbalders/Ghost-Admin,acburdine/Ghost-Admin,kevinansfield/Ghost-Admin,dbalders/Ghost-Admin
--- +++ @@ -1,4 +1,6 @@ // Loader to create the Ember.js application /*global require */ -window.App = require('ghost/app')['default'].create(); +if (!window.disableBoot) { + window.App = require('ghost/app')['default'].create(); +}
1df9443cf4567a4deef6f708d5f0ed0f8e3858da
lib/less/functions/function-registry.js
lib/less/functions/function-registry.js
function makeRegistry( base ) { return { _data: {}, add: function(name, func) { // precautionary case conversion, as later querying of // the registry by function-caller uses lower case as well. name = name.toLowerCase(); if (this._data.hasOwnProperty(name)) { //TODO warn } this._data[name] = func; }, addMultiple: function(functions) { Object.keys(functions).forEach( function(name) { this.add(name, functions[name]); }.bind(this)); }, get: function(name) { return this._data[name] || ( base && base.get( name )); }, inherit : function() { return makeRegistry( this ); } }; } module.exports = makeRegistry( null );
function makeRegistry( base ) { return { _data: {}, add: function(name, func) { // precautionary case conversion, as later querying of // the registry by function-caller uses lower case as well. name = name.toLowerCase(); if (this._data.hasOwnProperty(name)) { //TODO warn } this._data[name] = func; }, addMultiple: function(functions) { Object.keys(functions).forEach( function(name) { this.add(name, functions[name]); }.bind(this)); }, get: function(name) { return this._data[name] || ( base && base.get( name )); }, getLocalFunctions: function() { return this._data; }, inherit: function() { return makeRegistry( this ); }, create: function(base) { return makeRegistry(base); } }; } module.exports = makeRegistry( null );
Add create() and getLocalFunctions() to function registry so it can be used for plugins
Add create() and getLocalFunctions() to function registry so it can be used for plugins
JavaScript
apache-2.0
foresthz/less.js,foresthz/less.js,less/less.js,less/less.js,less/less.js
--- +++ @@ -20,8 +20,14 @@ get: function(name) { return this._data[name] || ( base && base.get( name )); }, - inherit : function() { + getLocalFunctions: function() { + return this._data; + }, + inherit: function() { return makeRegistry( this ); + }, + create: function(base) { + return makeRegistry(base); } }; }
e8a8fed47acf2a7bb9a72720e7c92fbfa6c94952
src/lintStream.js
src/lintStream.js
import postcss from "postcss" import fs from "fs" import gs from "glob-stream" import rcLoader from "rc-loader" import { Transform } from "stream" import plugin from "./plugin" export default function ({ files, config } = {}) { const stylelintConfig = config || rcLoader("stylelint") if (!stylelintConfig) { throw new Error("No stylelint config found") } const linter = new Transform({ objectMode: true }) linter._transform = function (chunk, enc, callback) { if (files) { const filepath = chunk.path fs.readFile(filepath, "utf8", (err, css) => { if (err) { linter.emit("error", err) } lint({ css, filepath: filepath }, callback) }) } else { lint({ css: chunk }, callback) } } function lint({ css, filepath }, callback) { const processOptions = {} if (filepath) { processOptions.from = filepath } postcss() .use(plugin(stylelintConfig)) .process(css, processOptions) .then(result => { callback(null, result) }) .catch(err => { linter.emit("error", new Error(err)) }) } if (files) { const fileStream = gs.create(files) return fileStream.pipe(linter) } return linter }
import postcss from "postcss" import fs from "fs" import gs from "glob-stream" import { Transform } from "stream" import plugin from "./plugin" export default function ({ files, config } = {}) { const linter = new Transform({ objectMode: true }) linter._transform = function (chunk, enc, callback) { if (files) { const filepath = chunk.path fs.readFile(filepath, "utf8", (err, css) => { if (err) { linter.emit("error", err) } lint({ css, filepath: filepath }, callback) }) } else { lint({ css: chunk }, callback) } } function lint({ css, filepath }, callback) { const processOptions = {} if (filepath) { processOptions.from = filepath } postcss() .use(plugin(config)) .process(css, processOptions) .then(result => { callback(null, result) }) .catch(err => { linter.emit("error", new Error(err)) }) } if (files) { const fileStream = gs.create(files) return fileStream.pipe(linter) } return linter }
Add bin to package.json and move rc-loading to plugin.js
Add bin to package.json and move rc-loading to plugin.js
JavaScript
mit
gaidarenko/stylelint,stylelint/stylelint,hudochenkov/stylelint,heatwaveo8/stylelint,stylelint/stylelint,hudochenkov/stylelint,gucong3000/stylelint,heatwaveo8/stylelint,stylelint/stylelint,gaidarenko/stylelint,stylelint/stylelint,hudochenkov/stylelint,gaidarenko/stylelint,evilebottnawi/stylelint,gucong3000/stylelint,heatwaveo8/stylelint,m-allanson/stylelint,gucong3000/stylelint,evilebottnawi/stylelint
--- +++ @@ -1,16 +1,10 @@ import postcss from "postcss" import fs from "fs" import gs from "glob-stream" -import rcLoader from "rc-loader" import { Transform } from "stream" import plugin from "./plugin" export default function ({ files, config } = {}) { - const stylelintConfig = config || rcLoader("stylelint") - if (!stylelintConfig) { - throw new Error("No stylelint config found") - } - const linter = new Transform({ objectMode: true }) linter._transform = function (chunk, enc, callback) { @@ -31,7 +25,7 @@ processOptions.from = filepath } postcss() - .use(plugin(stylelintConfig)) + .use(plugin(config)) .process(css, processOptions) .then(result => { callback(null, result)
bf04e2c0a7637b0486562167c6046cb8c2a74a26
src/database/DataTypes/TemperatureBreachConfiguration.js
src/database/DataTypes/TemperatureBreachConfiguration.js
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2020 */ import Realm from 'realm'; export class TemperatureBreachConfiguration extends Realm.Object {} TemperatureBreachConfiguration.schema = { name: 'TemperatureBreachConfiguration', primaryKey: 'id', properties: { id: 'string', minimumTemperature: { type: 'double', optional: true }, maximumTemperature: { type: 'double', optional: true }, duration: { type: 'double', optional: true }, description: { type: 'string', optional: true }, colour: { type: 'string', optional: true }, location: { type: 'Location', optional: true }, type: 'string', }, }; export default TemperatureBreachConfiguration;
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2020 */ import Realm from 'realm'; export class TemperatureBreachConfiguration extends Realm.Object { toJSON() { return { id: this.id, minimumTemperature: this.minimumTemperature, maximumTemperature: this.maximumTemperature, duration: this.duration, description: this.description, colour: this.colour, locationID: this.location?.id ?? '', type: this.type, }; } } TemperatureBreachConfiguration.schema = { name: 'TemperatureBreachConfiguration', primaryKey: 'id', properties: { id: 'string', minimumTemperature: { type: 'double', optional: true }, maximumTemperature: { type: 'double', optional: true }, duration: { type: 'double', optional: true }, description: { type: 'string', optional: true }, colour: { type: 'string', optional: true }, location: { type: 'Location', optional: true }, type: 'string', }, }; export default TemperatureBreachConfiguration;
Add breach config adapter method
Add breach config adapter method
JavaScript
mit
sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile
--- +++ @@ -5,7 +5,20 @@ import Realm from 'realm'; -export class TemperatureBreachConfiguration extends Realm.Object {} +export class TemperatureBreachConfiguration extends Realm.Object { + toJSON() { + return { + id: this.id, + minimumTemperature: this.minimumTemperature, + maximumTemperature: this.maximumTemperature, + duration: this.duration, + description: this.description, + colour: this.colour, + locationID: this.location?.id ?? '', + type: this.type, + }; + } +} TemperatureBreachConfiguration.schema = { name: 'TemperatureBreachConfiguration',
f068173deb8aefb9ff0ac55c5fe5e57fd4363288
server/src/app.js
server/src/app.js
const express = require('express') const bodyParser = require('body-parser') const cors = require('cors') const morgan = require('morgan') const {sequelize} = require('./models') const config = require('./config/config') const app = express() // Seting up middleware app.use(morgan('combined')) app.use(bodyParser.json()) app.use(cors()) app.get('/', (req, res) => { res.send('Hello world') }) app.get('/status', (req, res) => { res.send({ message: 'Hello world' }) }) require('./routes.js')(app) sequelize.sync({force: true}).then(() => { app.listen(config.port, () => { console.log(`Server started at http://127.0.0.1:${config.port}`) }); })
const express = require('express') const bodyParser = require('body-parser') const cors = require('cors') const morgan = require('morgan') const {sequelize} = require('./models') const config = require('./config/config') const app = express() // Seting up middleware app.use(morgan('combined')) app.use(bodyParser.json()) app.use(cors()) app.get('/', (req, res) => { res.send('Hello world') }) app.get('/status', (req, res) => { res.send({ message: 'Hello world' }) }) require('./routes.js')(app) sequelize.sync({force: false}).then(() => { app.listen(config.port, () => { console.log(`Server started at http://127.0.0.1:${config.port}`) }); })
Disable migration on start server
Disable migration on start server
JavaScript
mit
rahman541/tab-tracker,rahman541/tab-tracker
--- +++ @@ -23,7 +23,7 @@ require('./routes.js')(app) -sequelize.sync({force: true}).then(() => { +sequelize.sync({force: false}).then(() => { app.listen(config.port, () => { console.log(`Server started at http://127.0.0.1:${config.port}`) });
b2987678c06e7527491984a11e86a63da1d17cb4
src/_fixMobile/EventPath.js
src/_fixMobile/EventPath.js
(function(global){ // For Android 4.3- (included) document.body.addEventListener('click', function(e) { if (!e.path) { e.path = []; var t = e.target; while (t !== document) { e.path.push(t); t = t.parentNode; } e.path.push(document); e.path.push(window); } }, true) })(window);
(function(global){ // For Android 4.3- (included) var pathFill = function() { var e = arguments[0]; if (!e.path) { e.path = []; var t = e.target; while (t !== document) { e.path.push(t); t = t.parentNode; } e.path.push(document); e.path.push(window); } } document.body.addEventListener('click', pathFill); document.body.addEventListener('click', pathFill, true); })(window);
Handle event when bubbles event and catch event.
Handle event when bubbles event and catch event.
JavaScript
mit
zhoukekestar/web-modules,zhoukekestar/modules,zhoukekestar/web-modules,zhoukekestar/modules,zhoukekestar/modules,zhoukekestar/web-modules
--- +++ @@ -1,7 +1,9 @@ (function(global){ // For Android 4.3- (included) - document.body.addEventListener('click', function(e) { + var pathFill = function() { + var e = arguments[0]; + if (!e.path) { e.path = []; var t = e.target; @@ -12,7 +14,10 @@ e.path.push(document); e.path.push(window); } - }, true) + } + + document.body.addEventListener('click', pathFill); + document.body.addEventListener('click', pathFill, true); })(window);
aceeb92a1c71a2bdae0f1ebfce50c2391a20bbe2
models.js
models.js
var orm = require('orm'); var db = orm.connect('sqlite://db.sqlite'); function init(callback) { db.sync(callback); } module.exports = { init: init };
var orm = require('orm'); var db = orm.connect('sqlite://' + __dirname + '/db.sqlite'); function init(callback) { db.sync(callback); } module.exports = { init: init };
Use correct directory for sqlite database
Use correct directory for sqlite database
JavaScript
mit
dashersw/cote-workshop,dashersw/cote-workshop
--- +++ @@ -1,5 +1,5 @@ var orm = require('orm'); -var db = orm.connect('sqlite://db.sqlite'); +var db = orm.connect('sqlite://' + __dirname + '/db.sqlite'); function init(callback) { db.sync(callback);
16162985c41a9cd78e17a76b66de27fe2b7bc31d
src/components/NewEngagementForm.js
src/components/NewEngagementForm.js
import 'react-datepicker/dist/react-datepicker.css' import '../App.css' import React, { Component } from 'react' import { Field, reduxForm } from 'redux-form' import { Form } from 'semantic-ui-react' import DatePicker from 'react-datepicker' import moment from 'moment' import styled from 'styled-components' const StyledForm = styled.div`width: 100%;` class NewEngagementForm extends Component { state = { startDate: moment() } handleChange = date => { this.setState({ startDate: date }) } handleSubmit = () => { this.props.handleSubmit(this.state.startDate) } render() { return ( <Form onSubmit={this.handleSubmit}> <Form.Field width={5}> <StyledForm> <DatePicker onChange={this.handleChange} selected={this.state.startDate} showTimeSelect dateFormat="LLL" /> </StyledForm> </Form.Field> <Form.Field> <Field name="email" component="input" type="text" /> </Form.Field> <input type="submit" /> </Form> ) } } export default reduxForm({ form: 'newEngagement' })(NewEngagementForm)
import 'react-datepicker/dist/react-datepicker.css' import '../App.css' import React, { Component } from 'react' import { Field, reduxForm } from 'redux-form' import { Form } from 'semantic-ui-react' import DatePicker from 'react-datepicker' import moment from 'moment' import styled from 'styled-components' const StyledForm = styled.div`width: 100%;` class NewEngagementForm extends Component { state = { startDate: moment() } handleChange = date => { this.setState({ startDate: date }) } handleSubmit = () => { this.props.handleSubmit(this.state.startDate) } render() { return ( <Form onSubmit={this.handleSubmit}> <Form.Field> <StyledForm> <DatePicker onChange={this.handleChange} selected={this.state.startDate} showTimeSelect dateFormat="LLL" /> </StyledForm> </Form.Field> <input type="submit" /> </Form> ) } } export default reduxForm({ form: 'newEngagement' })(NewEngagementForm)
Remove unneeded input form from new engagement form
Remove unneeded input form from new engagement form
JavaScript
mit
cernanb/personal-chef-react-app,cernanb/personal-chef-react-app
--- +++ @@ -27,7 +27,7 @@ render() { return ( <Form onSubmit={this.handleSubmit}> - <Form.Field width={5}> + <Form.Field> <StyledForm> <DatePicker onChange={this.handleChange} @@ -37,9 +37,7 @@ /> </StyledForm> </Form.Field> - <Form.Field> - <Field name="email" component="input" type="text" /> - </Form.Field> + <input type="submit" /> </Form> )
e518509d82651340e881a638e5279ed6a1be7af1
test/resources/unsubscribe_test.js
test/resources/unsubscribe_test.js
var expect = require('chai').expect; var Unsubscribe = require('../../lib/resources/unsubscribe'); var helper = require('../test_helper'); describe('Unsubscribe', function() { var server; beforeEach(function() { server = helper.server(helper.port, helper.requests); }); afterEach(function() { server.close(); }); describe('#create', function() { it('creates an unsubscribe', function() { var unsubscribe = new Unsubscribe(helper.client); var params = { person_email: 'foo@example.com' }; return unsubscribe.create(params).then(function(response) { expect(response.person_email).to.eq('foo@example.com'); });; }); }); });
var expect = require('chai').expect; var Unsubscribe = require('../../lib/resources/Unsubscribe'); var helper = require('../test_helper'); describe('Unsubscribe', function() { var server; beforeEach(function() { server = helper.server(helper.port, helper.requests); }); afterEach(function() { server.close(); }); describe('#create', function() { it('creates an unsubscribe', function() { var unsubscribe = new Unsubscribe(helper.client); var params = { person_email: 'foo@example.com' }; return unsubscribe.create(params).then(function(response) { expect(response.person_email).to.eq('foo@example.com'); });; }); }); });
Fix case sensitive require for unsubscribes
Fix case sensitive require for unsubscribes
JavaScript
mit
delighted/delighted-node,callemall/delighted-node
--- +++ @@ -1,5 +1,5 @@ var expect = require('chai').expect; -var Unsubscribe = require('../../lib/resources/unsubscribe'); +var Unsubscribe = require('../../lib/resources/Unsubscribe'); var helper = require('../test_helper'); describe('Unsubscribe', function() {
92978a1a24c2b2df4dba8f622c40f34c4fa7ca12
modules/signin.js
modules/signin.js
'use strict'; const builder = require('botbuilder'); const timesheet = require('./timesheet'); module.exports = exports = [(session) => { builder.Prompts.text(session, 'Please tell me your domain user?'); }, (session, results, next) => { session.send('Ok. Searching for your stuff...'); session.sendTyping(); timesheet .searchColleagues(results.response) .then((colleagues) => { session.userData = colleagues[0]; session.userData.impersonated = true; }).catch((ex) => { console.log(ex); }).finally(() => { next(); }); }, (session) => { if (!session.impersonated) { console.log('Oops! Couldn\'t impersonate'); return session.endDialog('Oops! Couldn\'t impersonate'); } session.endDialog('(y)'); }];
'use strict'; const builder = require('botbuilder'); const timesheet = require('./timesheet'); module.exports = exports = [(session) => { builder.Prompts.text(session, 'Please tell me your domain user?'); }, (session, results, next) => { session.send('Ok. Searching for your stuff...'); session.sendTyping(); timesheet .searchColleagues(results.response) .then((colleagues) => { console.log('Found %s', colleagues.length); session.userData = colleagues[0]; session.userData.impersonated = true; }).catch((ex) => { console.log(ex); }).finally(() => { next(); }); }, (session) => { if (!session.userData.impersonated) { return session.endDialog('Oops! Couldn\'t impersonate'); } session.endDialog('(y)'); }];
Fix impersonated user check issue.
Fix impersonated user check issue.
JavaScript
mit
99xt/jira-journal,99xt/jira-journal
--- +++ @@ -15,6 +15,8 @@ timesheet .searchColleagues(results.response) .then((colleagues) => { + console.log('Found %s', colleagues.length); + session.userData = colleagues[0]; session.userData.impersonated = true; }).catch((ex) => { @@ -25,8 +27,7 @@ }, (session) => { - if (!session.impersonated) { - console.log('Oops! Couldn\'t impersonate'); + if (!session.userData.impersonated) { return session.endDialog('Oops! Couldn\'t impersonate'); } session.endDialog('(y)');
6dc8a96b20179bd04a2e24fa4c3b0106d35ebaba
src/main.js
src/main.js
(function(){ "use strict"; xtag.register("sam-tabbar", { lifecycle: { created: function() { if (!this.role) { this.role = "tablist"; } }, inserted: function() { this.activeTabId = this.querySelector("[role='tab'][data-start-active]").id; }, removed: function() {}, attributeChanged: function() {} }, events: { "press": function (event) { var el = event.originalTarget; //Checks if a tab was pressed if (!el || el.getAttribute("role") !== "tab") return; this.setTab(el.id, true); } }, accessors: { role: { attribute: {} } }, methods: { setTab: function (tabid, fireEvent) { var eventName = "tabChange", result = true; //Checks if person is trying to set to currently active tab if (this.activeTabId === tabid) { eventName = "activeTabPress" result = false; } else { document.getElementById(this.activeTabId).dataset.active = false; this.activeTabId = tabid; document.getElementById(this.activeTabId).dataset.active = true; } if (fireEvent) xtag.fireEvent(this, eventName, {detail: this.activeTabId}); return result; } } }); })();
(function(){ "use strict"; xtag.register("sam-tabbar", { lifecycle: { created: function() { if (!this.role) { this.role = "tablist"; } }, inserted: function() { this.activeTabId = this.querySelector("[role='tab'][data-start-active]").id; }, removed: function() {}, attributeChanged: function() {} }, events: { "press": function (event) { var el = event.originalTarget; //Checks if a tab was pressed if (!el || el.getAttribute("role") !== "tab") return; this.setTab(el.id, true); } }, accessors: { role: { attribute: {} } }, methods: { setTab: function (tabid, fireEvent) { var eventName = "tabChange"; if (!this.querySelector("[id='"+tabid+"'][role='tab']")) { console.error("Cannot set to unknown tabid"); return false; } //Checks if person is trying to set to currently active tab if (this.activeTabId === tabid) { eventName = "activeTabPress" } else { document.getElementById(this.activeTabId).dataset.active = false; this.activeTabId = tabid; document.getElementById(this.activeTabId).dataset.active = true; } if (fireEvent) xtag.fireEvent(this, eventName, {detail: this.activeTabId}); return true; } } }); })();
Add handler for when setTab is given a non-exsitant tab id
Add handler for when setTab is given a non-exsitant tab id
JavaScript
apache-2.0
Swissnetizen/sam-tabbar
--- +++ @@ -28,19 +28,21 @@ }, methods: { setTab: function (tabid, fireEvent) { - var eventName = "tabChange", - result = true; + var eventName = "tabChange"; + if (!this.querySelector("[id='"+tabid+"'][role='tab']")) { + console.error("Cannot set to unknown tabid"); + return false; + } //Checks if person is trying to set to currently active tab if (this.activeTabId === tabid) { eventName = "activeTabPress" - result = false; } else { document.getElementById(this.activeTabId).dataset.active = false; this.activeTabId = tabid; document.getElementById(this.activeTabId).dataset.active = true; } if (fireEvent) xtag.fireEvent(this, eventName, {detail: this.activeTabId}); - return result; + return true; } } });
0715d2b60dd1ebd851d4e5ea9ec9073424211012
src/function/lazyLoading.js
src/function/lazyLoading.js
define([ 'jquery' ], function($) { return function() { var self = this; if (!self.sprite && self.lasyEmoji[0]) { var pickerTop = self.picker.offset().top, pickerBottom = pickerTop + self.picker.height() + 20; self.lasyEmoji.each(function() { var e = $(this), top = e.offset().top; if (top > pickerTop && top < pickerBottom) { e.attr("src", e.data("src")).removeClass("lazy-emoji"); } }) self.lasyEmoji = self.lasyEmoji.filter(".lazy-emoji"); } } });
define([ 'jquery' ], function($) { return function() { var self = this; if (!self.sprite && self.lasyEmoji[0] && self.lasyEmoji.eq(0).is(".lazy-emoji")) { var pickerTop = self.picker.offset().top, pickerBottom = pickerTop + self.picker.height() + 20; self.lasyEmoji.each(function() { var e = $(this), top = e.offset().top; if (top > pickerTop && top < pickerBottom) { e.attr("src", e.data("src")).removeClass("lazy-emoji"); } }) self.lasyEmoji = self.lasyEmoji.filter(".lazy-emoji"); } } });
Fix 'disconnected from the document' error
Fix 'disconnected from the document' error ref https://github.com/mervick/emojionearea/pull/240
JavaScript
mit
mervick/emojionearea
--- +++ @@ -4,7 +4,7 @@ function($) { return function() { var self = this; - if (!self.sprite && self.lasyEmoji[0]) { + if (!self.sprite && self.lasyEmoji[0] && self.lasyEmoji.eq(0).is(".lazy-emoji")) { var pickerTop = self.picker.offset().top, pickerBottom = pickerTop + self.picker.height() + 20; self.lasyEmoji.each(function() {
7a328c49ea155df7ff2ae55825aa299c541bf31e
test/index.js
test/index.js
var nocache = require('..') var assert = require('assert') var connect = require('connect') var request = require('supertest') describe('nocache', function () { it('sets headers properly', function (done) { var app = connect() app.use(function (req, res, next) { res.setHeader('ETag', 'abc123') next() }) app.use(nocache()) app.use(function (req, res) { res.end('Hello world!') }) request(app).get('/') .expect('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate') .expect('Pragma', 'no-cache') .expect('Expires', '0') .expect('ETag', 'abc123') .end(done) }) it('names its function and middleware', function () { assert.equal(nocache.name, 'nocache') assert.equal(nocache().name, 'nocache') }) })
var nocache = require('..') var assert = require('assert') var connect = require('connect') var request = require('supertest') describe('nocache', function () { it('sets headers properly', function (done) { var app = connect() app.use(function (req, res, next) { res.setHeader('ETag', 'abc123') next() }) app.use(nocache()) app.use(function (req, res) { res.end('Hello world!') }) request(app).get('/') .expect('Surrogate-Control', 'no-store') .expect('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate') .expect('Pragma', 'no-cache') .expect('Expires', '0') .expect('ETag', 'abc123') .end(done) }) it('names its function and middleware', function () { assert.equal(nocache.name, 'nocache') assert.equal(nocache().name, 'nocache') }) })
Add missing test for `Surrogate-Control` header
Add missing test for `Surrogate-Control` header Fixes #13.
JavaScript
mit
helmetjs/nocache
--- +++ @@ -17,6 +17,7 @@ }) request(app).get('/') + .expect('Surrogate-Control', 'no-store') .expect('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate') .expect('Pragma', 'no-cache') .expect('Expires', '0')
5ac0fccde96dd50007767263c19b1432bb4e41d8
test/index.js
test/index.js
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */ /* eslint-env node, mocha */ import test from 'ava'; import endpoint from '../src/endpoint'; test('happy ponies', () => { const fetch = () => null; api(null, null, { baseUri: 'http://api.example.com/v1', endpoints: [ { endpoint: '/happy/ponies/{id}', method: 'GET', requiredParams: ['id'], optionalParams: ['lastSeenId'], } ] }); }); test.skip('returns a request object with the correct url', (t) => { const testUrl = 'http://api.example.com/v1/'; const Request = (url) => { t.true(url === testUrl); }; endpoint(Request); }); test.skip('should append a trailing slash if one is missing in the given url', (t) => { const testUrl = 'http://api.example.com/v1'; const Request = (url) => { t.true(url === `${testUrl}/`); }; endpoint(Request); });
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */ /* eslint-env node, mocha */ import test from 'ava'; import endpoint from '../src/endpoint'; test('endpoint returns correctly partially applied function', (t) => { const endpointConfig = { uri: 'http://example.com', }; const init = () => {}; const Request = (uriOpt, initOpt) => { t.true(uriOpt === endpointConfig.uri); t.true(initOpt.toString() === init.toString()); }; endpoint(Request, init)(endpointConfig); }); test.skip('returns a request object with the correct url', (t) => { const testUrl = 'http://api.example.com/v1/'; const Request = (url) => { t.true(url === testUrl); }; endpoint(Request); }); test.skip('should append a trailing slash if one is missing in the given url', (t) => { const testUrl = 'http://api.example.com/v1'; const Request = (url) => { t.true(url === `${testUrl}/`); }; endpoint(Request); });
Add spec for endpoints function
Add spec for endpoints function
JavaScript
mit
hughrawlinson/api-client-helper
--- +++ @@ -3,19 +3,16 @@ import test from 'ava'; import endpoint from '../src/endpoint'; -test('happy ponies', () => { - const fetch = () => null; - api(null, null, { - baseUri: 'http://api.example.com/v1', - endpoints: [ - { - endpoint: '/happy/ponies/{id}', - method: 'GET', - requiredParams: ['id'], - optionalParams: ['lastSeenId'], - } - ] - }); +test('endpoint returns correctly partially applied function', (t) => { + const endpointConfig = { + uri: 'http://example.com', + }; + const init = () => {}; + const Request = (uriOpt, initOpt) => { + t.true(uriOpt === endpointConfig.uri); + t.true(initOpt.toString() === init.toString()); + }; + endpoint(Request, init)(endpointConfig); }); test.skip('returns a request object with the correct url', (t) => {
684d9d693b19bc4d09c26627bb16ddcfa6230c63
src/main.js
src/main.js
import './main.sass' import 'babel-core/polyfill' import React from 'react' import thunk from 'redux-thunk' import createLogger from 'redux-logger' import { Router } from 'react-router' import createBrowserHistory from 'history/lib/createBrowserHistory' import { createStore, applyMiddleware, combineReducers } from 'redux' import { Provider } from 'react-redux' import * as reducers from './reducers' import { analytics, uploader, requester } from './middleware' import App from './containers/App' const logger = createLogger({ collapsed: true }) const createStoreWithMiddleware = applyMiddleware(thunk, uploader, requester, analytics, logger)(createStore) const reducer = combineReducers(reducers) const store = createStoreWithMiddleware(reducer) function createRedirect(from, to) { return { path: from, onEnter(nextState, transition) { transition.to(to) }, } } const rootRoute = { path: '/', component: App, childRoutes: [ createRedirect('onboarding', '/onboarding/communities'), require('./routes/Onboarding'), ], } const element = ( <Provider store={store}> {() => <Router history={createBrowserHistory()} routes={rootRoute} /> } </Provider> ) React.render(element, document.getElementById('root'))
import './main.sass' import 'babel-core/polyfill' import React from 'react' import thunk from 'redux-thunk' import createLogger from 'redux-logger' import { Router } from 'react-router' import createBrowserHistory from 'history/lib/createBrowserHistory' import { createStore, applyMiddleware, combineReducers } from 'redux' import { Provider } from 'react-redux' import * as reducers from './reducers' import { analytics, uploader, requester } from './middleware' import App from './containers/App' const logger = createLogger({ collapsed: true }) const createStoreWithMiddleware = applyMiddleware(thunk, uploader, requester, analytics, logger)(createStore) const reducer = combineReducers(reducers) const store = createStoreWithMiddleware(reducer) function createRedirect(from, to) { return { path: from, onEnter(nextState, replaceState) { replaceState(nextState, to) }, } } const rootRoute = { path: '/', component: App, childRoutes: [ createRedirect('onboarding', '/onboarding/communities'), require('./routes/Onboarding'), ], } const element = ( <Provider store={store}> {() => <Router history={createBrowserHistory()} routes={rootRoute} /> } </Provider> ) React.render(element, document.getElementById('root'))
Fix an issue with redirects
Fix an issue with redirects
JavaScript
mit
ello/webapp,ello/webapp,ello/webapp
--- +++ @@ -20,8 +20,8 @@ function createRedirect(from, to) { return { path: from, - onEnter(nextState, transition) { - transition.to(to) + onEnter(nextState, replaceState) { + replaceState(nextState, to) }, } }
18c94b0fcf2fdab6dea4ee0f3c0de11ba6e368f6
test/index.js
test/index.js
var ienoopen = require('..') var assert = require('assert') var connect = require('connect') var request = require('supertest') describe('ienoopen', function () { beforeEach(function () { this.app = connect() this.app.use(ienoopen()) this.app.use(function (req, res) { res.setHeader('Content-Disposition', 'attachment; filename=somefile.txt') res.end('Download this cool file!') }) }) it('sets header properly', function (done) { request(this.app).get('/') .expect('X-Download-Options', 'noopen', done) }) it('names its function and middleware', function () { assert.equal(ienoopen.name, 'ienoopen') assert.equal(ienoopen().name, 'ienoopen') }) })
var ienoopen = require('..') var assert = require('assert') var connect = require('connect') var request = require('supertest') describe('ienoopen', function () { beforeEach(function () { this.app = connect() this.app.use(ienoopen()) this.app.use(function (req, res) { res.setHeader('Content-Disposition', 'attachment; filename=somefile.txt') res.end('Download this cool file!') }) }) it('sets header properly', function () { return request(this.app).get('/') .expect('X-Download-Options', 'noopen') }) it('names its function and middleware', function () { assert.equal(ienoopen.name, 'ienoopen') assert.equal(ienoopen().name, 'ienoopen') }) })
Use promises instead of callbacks in test
Use promises instead of callbacks in test
JavaScript
mit
helmetjs/ienoopen
--- +++ @@ -14,9 +14,9 @@ }) }) - it('sets header properly', function (done) { - request(this.app).get('/') - .expect('X-Download-Options', 'noopen', done) + it('sets header properly', function () { + return request(this.app).get('/') + .expect('X-Download-Options', 'noopen') }) it('names its function and middleware', function () {
5bd8d02a8073fc55560fbc534f840627e81683de
src/main.js
src/main.js
'use strict'; const electron = require('electron'); const { app, BrowserWindow } = electron; let mainWindow; // Ensures garbage collection does not remove the window app.on('ready', () => { // Creates the application window and sets its dimensions to fill the screen const { width, height } = electron.screen.getPrimaryDisplay().workAreaSize; mainWindow = new BrowserWindow({ width, height }); // Loads index.html in as the main application page mainWindow.loadURL(`file://${__dirname}/index.html`); mainWindow.on('closed', () => { mainWindow = null; // allow window to be garbage collected }); });
'use strict'; const electron = require('electron'); const { app, BrowserWindow } = electron; const path = require('path'); const url = require('url'); let mainWindow; // Ensures garbage collection does not remove the window app.on('ready', () => { // Creates the application window and sets its dimensions to fill the screen const { width, height } = electron.screen.getPrimaryDisplay().workAreaSize; mainWindow = new BrowserWindow({ width, height }); // Loads index.html in as the main application page mainWindow.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })); mainWindow.on('closed', () => { mainWindow = null; // allow window to be garbage collected }); });
Change method of loading index.html
Change method of loading index.html
JavaScript
mit
joyceky/interactive-periodic-table,joyceky/interactive-periodic-table,joyceky/interactive-periodic-table
--- +++ @@ -2,6 +2,8 @@ const electron = require('electron'); const { app, BrowserWindow } = electron; +const path = require('path'); +const url = require('url'); let mainWindow; // Ensures garbage collection does not remove the window @@ -14,7 +16,11 @@ }); // Loads index.html in as the main application page - mainWindow.loadURL(`file://${__dirname}/index.html`); + mainWindow.loadURL(url.format({ + pathname: path.join(__dirname, 'index.html'), + protocol: 'file:', + slashes: true + })); mainWindow.on('closed', () => { mainWindow = null; // allow window to be garbage collected
d650050d72d0272a350d26c1f03b2e4534e99b33
test/index.js
test/index.js
'use strict'; var expect = require('chai').expect; var rm = require('../'); describe('1rm', function () { // 400# x 4 var expectations = { brzycki: 436, epley: 453, lander: 441, lombardi: 459, mayhew: 466, oconner: 440, wathan: 451 }; Object.keys(expectations).forEach(function (method) { it('can estimate with the #' + method + ' method', function () { expect(rm[method](400, 4)).to.be.closeTo(expectations[method], 1); }); }); });
'use strict'; var expect = require('chai').expect; var rm = require('../'); describe('1rm', function () { // 400# x 4 var expectations = { epley: 453, brzycki: 436, lander: 441, lombardi: 459, mayhew: 466, oconner: 440, wathan: 451 }; Object.keys(expectations).forEach(function (method) { it('can estimate with the #' + method + ' method', function () { expect(rm[method](400, 4)).to.be.closeTo(expectations[method], 1); }); }); });
Order tests to match source
Order tests to match source
JavaScript
mit
bendrucker/1rm.js
--- +++ @@ -7,8 +7,8 @@ // 400# x 4 var expectations = { + epley: 453, brzycki: 436, - epley: 453, lander: 441, lombardi: 459, mayhew: 466,
10bfd8221e3264d12e6f12470a0d24debc855bd8
test/index.js
test/index.js
var expect = require('chai').expect, hh = require('../index'); describe('#method', function () { it('hh.method is a function', function () { expect(hh.method).a('function'); }); });
var assert = require('chai').assert, hh = require('../index'); describe('#hh.method()', function () { it('should be a function', function () { assert.typeOf(hh.method, 'function', 'hh.method is a function'); }); });
Change tests to assert style
Change tests to assert style
JavaScript
mit
rsp/node-hapi-helpers
--- +++ @@ -1,8 +1,8 @@ -var expect = require('chai').expect, +var assert = require('chai').assert, hh = require('../index'); -describe('#method', function () { - it('hh.method is a function', function () { - expect(hh.method).a('function'); - }); +describe('#hh.method()', function () { + it('should be a function', function () { + assert.typeOf(hh.method, 'function', 'hh.method is a function'); + }); });
3c83c85662300646972a2561db80e26e80432f48
server.js
server.js
const express = require('express') const app = express() const path = require('path') var cors = require('cors') var bodyParser = require('body-parser') // var pg = require('pg') // var format = require('pg-format') // var client = new pg.Client() // var getTimeStamp = require('./get-timestamp.js') // var timestamp = getTimeStamp app.use(bodyParser.urlencoded({extended: false})) app.use(bodyParser.text()) app.use(cors()) app.use(express.static('client/build')) app.get('/', function (req, res) { res.sendFile(path.join(__dirname, '/client/build/index.html')) }) app.post('/', function (req, res) { var thought = req.body.text // var thought = 'cool stuff' console.log('We received this from the client: ' + thought) /* client.connect(function (err) { if (err) throw err var textToDB = format('INSERT INTO thoughtentries (date, thought) VALUES(%L, %L);', timestamp, thought) client.query(textToDB, function (err, result) { if (err) throw err console.log(result.rows[0]) client.end(function (err) { if (err) throw err }) }) */ }) app.listen(3000, function () { console.log('listening on 3000') })
const express = require('express') const app = express() const path = require('path') var cors = require('cors') var bodyParser = require('body-parser') // var pg = require('pg') // var format = require('pg-format') // var client = new pg.Client() // var getTimeStamp = require('./get-timestamp.js') // var timestamp = getTimeStamp app.use(bodyParser.urlencoded({extended: false})) app.use(bodyParser.text()) app.use(cors()) app.use(express.static('client/build')) app.get('/', function (req, res) { res.sendFile(path.join(__dirname, '/client/build/index.html')) }) app.post('/', function (req, res) { var thought = req.body res.end('done') console.log('We received this from the client: ' + thought) /* client.connect(function (err) { if (err) throw err var textToDB = format('INSERT INTO thoughtentries VALUES(%L, %L)', timestamp, thought) client.query(textToDB, function (err, result) { if (err) throw err console.log(result.rows[0]) client.end(function (err) { if (err) throw err }) }) }) */ return }) app.listen(3000, function () { console.log('listening on 3000') })
Add res.end() to end the POST request
Add res.end() to end the POST request @chinedufn Line 24 is where I get the contents of `req.body` in order to get the text from the textbox the problem is I believe it should be `req.body.text` like the example on the 'body-parser' page shows.
JavaScript
mit
acucciniello/notebook-sessions,acucciniello/notebook-sessions
--- +++ @@ -21,22 +21,23 @@ }) app.post('/', function (req, res) { - var thought = req.body.text - // var thought = 'cool stuff' + var thought = req.body + res.end('done') console.log('We received this from the client: ' + thought) /* client.connect(function (err) { if (err) throw err - var textToDB = format('INSERT INTO thoughtentries (date, thought) VALUES(%L, %L);', timestamp, thought) + var textToDB = format('INSERT INTO thoughtentries VALUES(%L, %L)', timestamp, thought) client.query(textToDB, function (err, result) { if (err) throw err console.log(result.rows[0]) client.end(function (err) { if (err) throw err }) - }) */ + }) + }) */ + return }) app.listen(3000, function () { console.log('listening on 3000') }) -
4cf7eb019de9b51505dbf1ba8e2b5f9bc77e0b20
recruit/client/applications.js
recruit/client/applications.js
Meteor.subscribe('regions'); Meteor.subscribe('applications'); Template.applications.helpers({ applications: function() { return Applications.find({}, {limit: 10}); }, formatDate: function(date) { return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear(); }, regionName: function(id) { return Regions.findOne({id: id}).name; }, }); Template.applications.rendered = function() { $('#applications').dataTable({ searching: false, scrollX: true, pagingType: 'full_numbers', language: { decimal: ',', thousands: '.', }, }); };
Meteor.subscribe('regions'); Meteor.subscribe('applications'); Template.applications.helpers({ applications: function() { return Applications.find({}, {limit: 10}); }, formatDate: function(date) { if (typeof date === 'undefined') { return null; } return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear(); }, regionName: function(id) { if (typeof id === 'undefined') { return null; } return Regions.findOne({id: id}).name; }, }); Template.applications.rendered = function() { $('#applications').dataTable({ searching: false, scrollX: true, pagingType: 'full_numbers', language: { decimal: ',', thousands: '.', }, }); };
Fix exceptions when application region or date is undefined
Fix exceptions when application region or date is undefined
JavaScript
apache-2.0
IngloriousCoderz/GetReel,IngloriousCoderz/GetReel
--- +++ @@ -7,10 +7,18 @@ }, formatDate: function(date) { + if (typeof date === 'undefined') { + return null; + } + return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear(); }, regionName: function(id) { + if (typeof id === 'undefined') { + return null; + } + return Regions.findOne({id: id}).name; }, });
b7ea9dc3f4e5bc7b028cf6aa4a5c7529b7d34160
troposphere/static/js/components/providers/Name.react.js
troposphere/static/js/components/providers/Name.react.js
import React from 'react/addons'; import Backbone from 'backbone'; import Router from 'react-router'; export default React.createClass({ displayName: "Name", propTypes: { provider: React.PropTypes.instanceOf(Backbone.Model).isRequired }, render: function () { let provider = this.props.provider; return ( <div className="row"> <h1>{provider.get('name')}</h1> <Router.Link className=" btn btn-default" to = "all-providers" > <span className="glyphico glyphicon-arrow-left"> </span> {" Back to All Providers" } </Router.Link> </div> ); } });
import React from 'react/addons'; import Backbone from 'backbone'; import Router from 'react-router'; export default React.createClass({ displayName: "Name", propTypes: { provider: React.PropTypes.instanceOf(Backbone.Model).isRequired }, render: function () { let provider = this.props.provider; return ( <div className="row"> <h1>{provider.get('name')}</h1> <Router.Link className="btn btn-default" to="all-providers" > <span className="glyphicon glyphicon-arrow-left"> </span> {" Back to All Providers" } </Router.Link> </div> ); } });
Correct CSS class name typo
Correct CSS class name typo
JavaScript
apache-2.0
CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend
--- +++ @@ -14,8 +14,8 @@ return ( <div className="row"> <h1>{provider.get('name')}</h1> - <Router.Link className=" btn btn-default" to = "all-providers" > - <span className="glyphico glyphicon-arrow-left"> </span> + <Router.Link className="btn btn-default" to="all-providers" > + <span className="glyphicon glyphicon-arrow-left"> </span> {" Back to All Providers" } </Router.Link> </div>
df11a29999a30f430162e2a6742903879f4608c4
web/webpack.common.js
web/webpack.common.js
const path = require('path'); const webpack = require('webpack'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { entry: { app: './src/app/app.js' }, module: { rules: [ { test: /\.html$/, use: 'raw-loader' } ] }, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ template: './src/index.html', inject: 'head' }), new CopyWebpackPlugin([ { from: './src/assets/', to: 'assets/' }, { from: './src/styles/', to: 'styles/' }, { from: './src/app/lib/stockfish.js', to: 'lib/stockfish.js' } ]) ], output: { filename: 'app.js', path: path.resolve(__dirname, 'dist') }, };
const path = require('path'); const webpack = require('webpack'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { entry: { app: './src/app/app.js' }, module: { rules: [ { test: /\.html$/, use: 'raw-loader' } ] }, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ template: './src/index.html', inject: 'head' }), new CopyWebpackPlugin({patterns: [ { from: './src/assets/', to: 'assets/' }, { from: './src/styles/', to: 'styles/' }, { from: './src/app/lib/stockfish.js', to: 'lib/stockfish.js' } ]}) ], output: { filename: 'app.js', path: path.resolve(__dirname, 'dist') }, };
Update webpack copy plugin configuration
Update webpack copy plugin configuration
JavaScript
mit
ddugovic/RelayChess,ddugovic/RelayChess,ddugovic/RelayChess
--- +++ @@ -20,14 +20,11 @@ template: './src/index.html', inject: 'head' }), - new CopyWebpackPlugin([ - { from: './src/assets/', - to: 'assets/' }, - { from: './src/styles/', - to: 'styles/' }, - { from: './src/app/lib/stockfish.js', - to: 'lib/stockfish.js' } - ]) + new CopyWebpackPlugin({patterns: [ + { from: './src/assets/', to: 'assets/' }, + { from: './src/styles/', to: 'styles/' }, + { from: './src/app/lib/stockfish.js', to: 'lib/stockfish.js' } + ]}) ], output: { filename: 'app.js',
b9eccecc4a5574ec05e29c55b16e19814b7d2c19
Kinect2Scratch.js
Kinect2Scratch.js
(function(ext) { // Cleanup function when the extension is unloaded ext._shutdown = function() {}; // Status reporting code // Use this to report missing hardware, plugin or unsupported browser ext._getStatus = function() { return {status: 2, msg: 'Ready'}; }; ext.my_first_block = function(callback) { wait = 1; window.setTimeout(function() { callback(); }, wait*1000); }; // Block and block menu descriptions var descriptor = { blocks: [ ['', 'My First Block', 'my_first_block'], ['r', '%n ^ %n', 'power', 2, 3], ] }; // Register the extension ScratchExtensions.register('Kinect2Scratch', descriptor, ext); })({});
(function(ext) { // Cleanup function when the extension is unloaded ext._shutdown = function() {}; // Status reporting code // Use this to report missing hardware, plugin or unsupported browser ext._getStatus = function() { return {status: 2, msg: 'Ready'}; }; ext.my_first_block = function() { }; ext.power = function(base, exponent) { return Math.pow(base, exponent); }; // Block and block menu descriptions var descriptor = { blocks: [ ['', 'My First Block', 'my_first_block'], ['r', '%n ^ %n', 'power', 2, 3], ] }; // Register the extension ScratchExtensions.register('Kinect2Scratch', descriptor, ext); })({});
Stop terrible idea; make reporter block do something
Stop terrible idea; make reporter block do something
JavaScript
bsd-3-clause
visor841/SkelScratch,Calvin-CS/SkelScratch
--- +++ @@ -8,12 +8,14 @@ return {status: 2, msg: 'Ready'}; }; - ext.my_first_block = function(callback) { - wait = 1; - window.setTimeout(function() { - callback(); - }, wait*1000); + ext.my_first_block = function() { + }; + + ext.power = function(base, exponent) { + return Math.pow(base, exponent); + }; + // Block and block menu descriptions var descriptor = {
46f2f3e86783a0b1eeed9be1ac35cd50a3ce1939
src/pkjs/index.js
src/pkjs/index.js
/* global Pebble navigator */ function pebbleSuccess(e) { // do nothing } function pebbleFailure(e) { console.error(e); } var reportPhoneBatt; Pebble.addEventListener('ready', function(e) { if (navigator.getBattery) { navigator.getBattery().then(function (battery) { reportPhoneBatt = function () { Pebble.sendAppMessage({ 'PHONE_BATT_LEVEL': Math.floor(battery.level * 100), 'PHONE_BATT_CHARGING': battery.charging ? 1 : 0 }, pebbleSuccess, pebbleFailure); }; battery.addEventListener('levelchange', function() { console.log('Level change: '+ (battery.level * 100) +'%'); reportPhoneBatt(); }); battery.addEventListener('chargingchange', reportPhoneBatt); reportPhoneBatt(); }); } else { console.error('No navigator.getBattery'); console.error('User agent: '+navigator.userAgent); } }); Pebble.addEventListener('appmessage', function(e) { if (e.payload.QUERY_PHONE_BATT && reportPhoneBatt) { return reportPhoneBatt(); } });
/* global Pebble navigator */ function pebbleSuccess(e) { // do nothing } function pebbleFailure(e) { console.error(e); } var reportPhoneBatt; Pebble.addEventListener('ready', function(e) { if (navigator.getBattery) { navigator.getBattery().then(function (battery) { reportPhoneBatt = function () { Pebble.sendAppMessage({ 'PHONE_BATT_LEVEL': Math.floor(battery.level * 100), 'PHONE_BATT_CHARGING': battery.charging ? 1 : 0 }, pebbleSuccess, pebbleFailure); }; battery.addEventListener('levelchange', function() { console.log('Level change: '+ (battery.level * 100) +'%'); reportPhoneBatt(); }); battery.addEventListener('chargingchange', reportPhoneBatt); reportPhoneBatt(); }); } else if (navigator.userAgent) { console.error('No navigator.getBattery'); console.error('User agent: '+navigator.userAgent); } else { console.log('No navigator.userAgent, probably running in emulator'); } }); Pebble.addEventListener('appmessage', function(e) { if (e.payload.QUERY_PHONE_BATT && reportPhoneBatt) { return reportPhoneBatt(); } });
Add log message about starting in the emulator
Add log message about starting in the emulator
JavaScript
mit
stuartpb/rainpower-watchface,stuartpb/rainpower-watchface,stuartpb/rainpower-watchface
--- +++ @@ -24,9 +24,11 @@ battery.addEventListener('chargingchange', reportPhoneBatt); reportPhoneBatt(); }); - } else { + } else if (navigator.userAgent) { console.error('No navigator.getBattery'); console.error('User agent: '+navigator.userAgent); + } else { + console.log('No navigator.userAgent, probably running in emulator'); } }); Pebble.addEventListener('appmessage', function(e) {
ce1c9f69ab4aec5e1d2a1c15faaeb0a00a954f04
src/Native/Now.js
src/Native/Now.js
Elm.Native.Now = {}; Elm.Native.Now.make = function(localRuntime) { localRuntime.Native = localRuntime.Native || {}; localRuntime.Native.Now = localRuntime.Native.Now || {}; if (localRuntime.Native.Now.values) { return localRuntime.Native.Now.values; } var Result = Elm.Result.make(localRuntime); return localRuntime.Native.Now.values = { loadTime: (new window.Date).getTime() }; };
Elm.Native.Now = {}; Elm.Native.Now.make = function(localRuntime) { localRuntime.Native = localRuntime.Native || {}; localRuntime.Native.Now = localRuntime.Native.Now || {}; if (localRuntime.Native.Now.values) { return localRuntime.Native.Now.values; } var Result = Elm.Result.make(localRuntime); return localRuntime.Native.Now.values = { loadTime: (new Date()).getTime() }; };
Use native Date() instead of window date
Use native Date() instead of window date
JavaScript
mit
chendrix/elm-rogue,chendrix/elm-rogue,chendrix/elm-rogue
--- +++ @@ -14,7 +14,7 @@ var Result = Elm.Result.make(localRuntime); return localRuntime.Native.Now.values = { - loadTime: (new window.Date).getTime() + loadTime: (new Date()).getTime() }; };
a9d67c9f29270b56be21cb71073020f8957374d4
test/client/scripts/arcademode/store/configureStore.spec.js
test/client/scripts/arcademode/store/configureStore.spec.js
'use strict'; /* Unit tests for file client/scripts/arcademode/store/configureStore.js. */ import { expect } from 'chai'; import configureStore from '../../../../../client/scripts/arcademode/store/configureStore'; describe('configureStore()', () => { it('should do return an object', () => { const store = configureStore(); expect(typeof store).to.equal('object'); const state = store.getState(); expect(state).not.to.empty; }); it('should do accept dispatched actions', () => { const store = configureStore(); store.dispatch({ type: 'DUMMY' }); }); });
'use strict'; /* Unit tests for file client/scripts/arcademode/store/configureStore.js. */ import { expect } from 'chai'; import configureStore from '../../../../../client/scripts/arcademode/store/configureStore'; describe('Store: configureStore()', () => { it('should return an object representing the store', () => { const store = configureStore(); expect(typeof store).to.equal('object'); const state = store.getState(); expect(state).not.to.be.empty; }); it('should accept dispatched actions and update its state', () => { const store = configureStore(); store.dispatch({ type: 'MODAL_CLOSE' }); expect(store.getState().getIn(['modal', 'modal'])).to.be.false; }); });
Test store, dispatch, and state
Test store, dispatch, and state
JavaScript
bsd-3-clause
freeCodeCamp/arcade-mode,kevinnorris/arcade-mode,kevinnorris/arcade-mode,kevinnorris/arcade-mode,freeCodeCamp/arcade-mode,freeCodeCamp/arcade-mode,kevinnorris/arcade-mode,freeCodeCamp/arcade-mode
--- +++ @@ -5,17 +5,18 @@ import { expect } from 'chai'; import configureStore from '../../../../../client/scripts/arcademode/store/configureStore'; -describe('configureStore()', () => { - it('should do return an object', () => { +describe('Store: configureStore()', () => { + it('should return an object representing the store', () => { const store = configureStore(); expect(typeof store).to.equal('object'); const state = store.getState(); - expect(state).not.to.empty; + expect(state).not.to.be.empty; }); - it('should do accept dispatched actions', () => { + it('should accept dispatched actions and update its state', () => { const store = configureStore(); - store.dispatch({ type: 'DUMMY' }); + store.dispatch({ type: 'MODAL_CLOSE' }); + expect(store.getState().getIn(['modal', 'modal'])).to.be.false; }); });
be4104b7fa5e985da4970d733231ba2f9f4d1c24
lib/async-to-promise.js
lib/async-to-promise.js
// Return promise for given async function 'use strict'; var f = require('es5-ext/lib/Function/functionalize') , concat = require('es5-ext/lib/List/concat').call , slice = require('es5-ext/lib/List/slice/call') , deferred = require('./deferred') , apply; apply = function (fn, scope, args, resolve) { fn.apply(scope, concat(args, function (error, result) { if (error == null) { resolve((arguments.length > 2) ? slice(arguments, 1) : result); } else { resolve(error); } })); } exports = module.exports = f(function () { var d = deferred(); apply(this, null, arguments, d.resolve); return d.promise; }); exports._apply = apply;
// Return promise for given async function 'use strict'; var f = require('es5-ext/lib/Function/functionalize') , slice = require('es5-ext/lib/List/slice/call') , toArray = require('es5-ext/lib/List/to-array').call , deferred = require('./deferred') , apply; apply = function (fn, scope, args, resolve) { fn.apply(scope, toArray(args).concat(function (error, result) { if (error == null) { resolve((arguments.length > 2) ? slice(arguments, 1) : result); } else { resolve(error); } })); } exports = module.exports = f(function () { var d = deferred(); apply(this, null, arguments, d.resolve); return d.promise; }); exports._apply = apply;
Update up to changes in es5-ext
Update up to changes in es5-ext
JavaScript
isc
medikoo/deferred
--- +++ @@ -2,16 +2,16 @@ 'use strict'; -var f = require('es5-ext/lib/Function/functionalize') - , concat = require('es5-ext/lib/List/concat').call - , slice = require('es5-ext/lib/List/slice/call') +var f = require('es5-ext/lib/Function/functionalize') + , slice = require('es5-ext/lib/List/slice/call') + , toArray = require('es5-ext/lib/List/to-array').call , deferred = require('./deferred') , apply; apply = function (fn, scope, args, resolve) { - fn.apply(scope, concat(args, function (error, result) { + fn.apply(scope, toArray(args).concat(function (error, result) { if (error == null) { resolve((arguments.length > 2) ? slice(arguments, 1) : result); } else {
97b8f1d793341c20acf7eabb9395ee575b7bcb59
app/routes/interestgroups/components/InterestGroupList.js
app/routes/interestgroups/components/InterestGroupList.js
import styles from './InterestGroup.css'; import React from 'react'; import InterestGroup from './InterestGroup'; import Button from 'app/components/Button'; import { Link } from 'react-router'; export type Props = { interestGroups: Array }; const InterestGroupList = (props: Props) => { const groups = props.interestGroups.map((group, key) => ( <InterestGroup group={group} key={key} /> )); return ( <div className={styles.root}> <div className={styles.section}> <div> <h1>Interessegrupper</h1> <p> <strong>Her</strong> finner du all praktisk informasjon knyttet til våre interessegrupper. </p> </div> <Link to={'/interestgroups/create'} className={styles.link}> <Button>Lag ny interessegruppe</Button> </Link> </div> <div className="groups">{groups}</div> </div> ); }; export default InterestGroupList;
import styles from './InterestGroup.css'; import React from 'react'; import InterestGroup from './InterestGroup'; import Button from 'app/components/Button'; import { Link } from 'react-router'; import NavigationTab, { NavigationLink } from 'app/components/NavigationTab'; export type Props = { interestGroups: Array }; const InterestGroupList = (props: Props) => { const groups = props.interestGroups.map((group, key) => ( <InterestGroup group={group} key={key} /> )); const showCreate = props.loggedIn; return ( <div className={styles.root}> <div className={styles.section}> <div> <NavigationTab title="Interessegrupper"> <NavigationLink to={`/`}>Hjem</NavigationLink> </NavigationTab> <p> <strong>Her</strong> finner du all praktisk informasjon knyttet til våre interessegrupper. </p> {showCreate && ( <Link to={'/interestgroups/create'} className={styles.link}> <Button>Lag ny interessegruppe</Button> </Link> )} </div> </div> <div className="groups">{groups}</div> </div> ); }; export default InterestGroupList;
Use NavigationTab in InterestGroup list
Use NavigationTab in InterestGroup list
JavaScript
mit
webkom/lego-webapp,webkom/lego-webapp,webkom/lego-webapp
--- +++ @@ -3,6 +3,7 @@ import InterestGroup from './InterestGroup'; import Button from 'app/components/Button'; import { Link } from 'react-router'; +import NavigationTab, { NavigationLink } from 'app/components/NavigationTab'; export type Props = { interestGroups: Array @@ -12,19 +13,24 @@ const groups = props.interestGroups.map((group, key) => ( <InterestGroup group={group} key={key} /> )); + const showCreate = props.loggedIn; return ( <div className={styles.root}> <div className={styles.section}> <div> - <h1>Interessegrupper</h1> + <NavigationTab title="Interessegrupper"> + <NavigationLink to={`/`}>Hjem</NavigationLink> + </NavigationTab> <p> <strong>Her</strong> finner du all praktisk informasjon knyttet til våre interessegrupper. </p> + {showCreate && ( + <Link to={'/interestgroups/create'} className={styles.link}> + <Button>Lag ny interessegruppe</Button> + </Link> + )} </div> - <Link to={'/interestgroups/create'} className={styles.link}> - <Button>Lag ny interessegruppe</Button> - </Link> </div> <div className="groups">{groups}</div> </div>
64ae5257caf51aa470249561184b7b8c7a4d614c
stylefmt.js
stylefmt.js
'use strict'; var stylefmt = require('stylefmt'); var data = ''; // Get options if needed if (process.argv.length > 2) { var opts = JSON.parse(process.argv[2]); process.chdir(opts.file_path); } process.stdin.on('data', function(css) { data += css; }); process.stdin.on('end', function() { try { process.stdout.write(stylefmt.process(data)); } catch (err) { throw err; } });
'use strict'; var stylefmt = require('stylefmt'); var data = ''; // Get options if needed if (process.argv.length > 2) { var opts = JSON.parse(process.argv[2]); process.chdir(opts.file_path); } process.stdin.on('data', function(css) { data += css; }); process.stdin.on('end', function() { stylefmt.process(data).then(function(result) { try { process.stdout.write(result.css); } catch (err) { throw err; } }); });
Update for new postcss promises
Update for new postcss promises
JavaScript
isc
dmnsgn/sublime-cssfmt,dmnsgn/sublime-cssfmt,dmnsgn/sublime-stylefmt
--- +++ @@ -14,9 +14,11 @@ }); process.stdin.on('end', function() { - try { - process.stdout.write(stylefmt.process(data)); - } catch (err) { - throw err; - } + stylefmt.process(data).then(function(result) { + try { + process.stdout.write(result.css); + } catch (err) { + throw err; + } + }); });
47eb145d096e569254fcc96d1b71925cf0ff631f
src/background.js
src/background.js
'use strict'; /** * Returns a BlockingResponse object with a redirect URL if the request URL * matches a file type extension. * * @param {object} request * @return {object|undefined} the blocking response */ function requestInterceptor(request) { var url = request.url; var hasParamTs = /\?.*ts=/; var hasExtGo = /\.go/; if (!hasParamTs.test(url) && hasExtGo.test(url)) return {redirectUrl: addTabSizeParam(url, 2)}; } /** * Returns a URL with the query param ts=size included. * * @param {string} url * @param {number} size * @return {string} */ function addTabSizeParam(url, size) { var urlWithTs = new Url(url); urlWithTs.query.ts = size; return urlWithTs.toString(); } chrome.webRequest.onBeforeRequest.addListener( requestInterceptor, {urls: ['https://github.com/*']}, ['blocking'] );
'use strict'; var tabSize = 2; /** * Returns a BlockingResponse object with a redirect URL if the request URL * matches a file type extension. * * @param {object} request * @return {object|undefined} the blocking response */ function requestInterceptor(request) { var url = request.url; var hasParamTs = /\?.*ts=/; var hasExtGo = /\.go/; if (!hasParamTs.test(url) && hasExtGo.test(url)) return {redirectUrl: addTabSizeParam(url, tabSize)}; } /** * Returns a URL with the query param ts=size included. * * @param {string} url * @param {number} size * @return {string} */ function addTabSizeParam(url, size) { var urlWithTs = new Url(url); urlWithTs.query.ts = size; return urlWithTs.toString(); } chrome.webRequest.onBeforeRequest.addListener( requestInterceptor, {urls: ['https://github.com/*']}, ['blocking'] ); chrome.storage.sync.get({tabSize: tabSize}, function(items) { tabSize = items.tabSize; }); chrome.storage.onChanged.addListener(function(items) { tabSize = items.tabSize.newValue; });
Use tab size from Chrome storage
Use tab size from Chrome storage
JavaScript
mit
nysa/github-tab-sizer
--- +++ @@ -1,4 +1,6 @@ 'use strict'; + +var tabSize = 2; /** * Returns a BlockingResponse object with a redirect URL if the request URL @@ -13,7 +15,7 @@ var hasExtGo = /\.go/; if (!hasParamTs.test(url) && hasExtGo.test(url)) - return {redirectUrl: addTabSizeParam(url, 2)}; + return {redirectUrl: addTabSizeParam(url, tabSize)}; } /** @@ -34,3 +36,11 @@ {urls: ['https://github.com/*']}, ['blocking'] ); + +chrome.storage.sync.get({tabSize: tabSize}, function(items) { + tabSize = items.tabSize; +}); + +chrome.storage.onChanged.addListener(function(items) { + tabSize = items.tabSize.newValue; +});
6653fcba245b25adc7c20bf982a3d119f2659711
.prettierrc.js
.prettierrc.js
module.exports = { printWidth: 100, tabWidth: 2, useTabs: false, semi: true, singleQuote: true, quoteProps: 'consistent', trailingComma: 'all', bracketSpacing: true, arrowParens: 'always', };
module.exports = { printWidth: 100, tabWidth: 2, useTabs: false, semi: true, singleQuote: true, quoteProps: 'consistent', trailingComma: 'all', bracketSpacing: true, arrowParens: 'always', endOfLine: 'lf', };
Set endOfLine to "lf" in prettier-config
:wrench: Set endOfLine to "lf" in prettier-config
JavaScript
apache-2.0
jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs
--- +++ @@ -8,4 +8,5 @@ trailingComma: 'all', bracketSpacing: true, arrowParens: 'always', + endOfLine: 'lf', };
1b2d9602dade5c599390645bd02e9b066f4f0ef5
cla_frontend/assets-src/javascripts/app/test/protractor.conf.local.js
cla_frontend/assets-src/javascripts/app/test/protractor.conf.local.js
(function () { 'use strict'; var extend = require('extend'), defaults = require('./protractor.conf'); exports.config = extend(defaults.config, { // --- uncomment to use mac mini's --- // seleniumAddress: 'http://clas-mac-mini.local:4444/wd/hub', // baseUrl: 'http://Marcos-MacBook-Pro-2.local:8001/', multiCapabilities: [ { browserName: 'chrome' }, { browserName: 'firefox' } ] }); })();
(function () { 'use strict'; var extend = require('extend'), defaults = require('./protractor.conf'); exports.config = extend(defaults.config, { // --- uncomment to use mac mini's --- // seleniumAddress: 'http://clas-mac-mini.local:4444/wd/hub', // baseUrl: 'http://Marcos-MacBook-Pro-2.local:8001/', multiCapabilities: [ { browserName: 'chrome', 'chromeOptions': { args: ['--test-type'] } }, { browserName: 'firefox' } ] }); })();
Remove chrome warnings during e2e tests
Remove chrome warnings during e2e tests
JavaScript
mit
ministryofjustice/cla_frontend,ministryofjustice/cla_frontend,ministryofjustice/cla_frontend,ministryofjustice/cla_frontend
--- +++ @@ -10,7 +10,10 @@ multiCapabilities: [ { - browserName: 'chrome' + browserName: 'chrome', + 'chromeOptions': { + args: ['--test-type'] + } }, { browserName: 'firefox'
276492033ce2a3048b453d75c0e361bf4ebfd5d7
tests/spec/QueueTwoStacksSpec.js
tests/spec/QueueTwoStacksSpec.js
describe("Implement queue with two stacks", function() { const Queue = new QueueTwoStacks(); Queue.enqueue(1); Queue.enqueue(2); Queue.enqueue(3); describe("enqueue()", function() { it("appends an element to tail", function() { Queue.enqueue(4); const expected = [1,2,3,4]; expect(Queue.inStack).toEqual(expected); }) it("appends an element correctly after dequeing", function() { Queue.dequeue(); Queue.enqueue(5); const expected = [2,3,4,5]; expect(Queue.inStack).toEqual(expected); }) }) describe("dequeue()", function () { it("removes an element from head", function () { Queue.dequeue(); const expected = [3,4,5]; expect(Queue.inStack).toEqual(expected); }) }) describe("when queue is empty", function() { it("throws an error", function() { Queue.dequeue(); Queue.dequeue(); Queue.dequeue(); expect(function() { Queue.dequeue(); }).toThrow(); }) }) })
describe("Implement queue with two stacks", function() { const Queue = new QueueTwoStacks(); Queue.enqueue(1); Queue.enqueue(2); Queue.enqueue(3); describe("enqueue()", function() { it("appends an element to tail", function() { Queue.enqueue(4); const expected = [1,2,3,4]; expect(Queue.inStack).toEqual(expected); }) it("appends an element correctly after dequeing", function() { Queue.dequeue(); Queue.enqueue(5); const expected = [2,3,4,5]; expect(Queue.inStack).toEqual(expected); }) }); describe("dequeue()", function () { it("removes an element from head", function () { Queue.dequeue(); const expected = [3,4,5]; expect(Queue.inStack).toEqual(expected); }); it("throws an error when queue is empty", function() { Queue.dequeue(); Queue.dequeue(); Queue.dequeue(); expect(function() { Queue.dequeue(); }).toThrow(); }) }); })
Move code to correct semantics in spec
Move code to correct semantics in spec
JavaScript
mit
ThuyNT13/algorithm-practice,ThuyNT13/algorithm-practice
--- +++ @@ -16,16 +16,14 @@ const expected = [2,3,4,5]; expect(Queue.inStack).toEqual(expected); }) - }) + }); describe("dequeue()", function () { it("removes an element from head", function () { Queue.dequeue(); const expected = [3,4,5]; expect(Queue.inStack).toEqual(expected); - }) - }) - describe("when queue is empty", function() { - it("throws an error", function() { + }); + it("throws an error when queue is empty", function() { Queue.dequeue(); Queue.dequeue(); Queue.dequeue(); @@ -33,5 +31,5 @@ Queue.dequeue(); }).toThrow(); }) - }) + }); })
009e3a12d21aa5b04acd1f17616a6af2458046b1
src/projects/TicTacToe/TicTacToe.js
src/projects/TicTacToe/TicTacToe.js
import React from 'react'; import './TicTacToe.scss'; import { connect } from 'react-redux'; import ticTacToeActions from 'actions/tictactoe'; import GameBoard from './components/GameBoard'; const mapStateToProps = (state) => { return { playerTurn: state.tictactoe.playerTurn }; }; class TicTacToe extends React.Component { static propTypes = { playerTurn: React.PropTypes.bool, computer_move: React.PropTypes.func } componentWillReceiveProps (propObj) { if (!propObj.playerTurn) { this.props.computer_move(); } if (propObj.winner && propObj.winner.result === 'draw') { // do very cool modal fadein } else if (propObj.winner) { // do very cool modal fadein with computer winning } // nothing else, the player can't win } render () { return ( <div> <h1 className='text-center'>Tic-Tac-Toe</h1> <GameBoard /> </div> ); } } export default connect(mapStateToProps, ticTacToeActions)(TicTacToe);
import React from 'react'; import './TicTacToe.scss'; import { connect } from 'react-redux'; import ticTacToeActions from 'actions/tictactoe'; import GameBoard from './components/GameBoard'; const mapStateToProps = (state) => { return { playerTurn: state.tictactoe.playerTurn, winner: state.tictactoe.winner }; }; class TicTacToe extends React.Component { static propTypes = { playerTurn: React.PropTypes.bool, computer_move: React.PropTypes.func } componentWillReceiveProps (propObj) { if (!propObj.playerTurn) { this.props.computer_move(); } if (propObj.winner && propObj.winner.result === 'draw') { // do very cool modal fadein console.log('DRAW'); } else if (propObj.winner) { // do very cool modal fadein with computer winning console.log('YOU LOST'); } // nothing else, the player can't win } render () { return ( <div> <h1 className='text-center'>Tic-Tac-Toe</h1> <h2 className='text-center'>Open your console to see messages</h2> <h3 className='text-center'>You can't win</h3> <GameBoard /> </div> ); } } export default connect(mapStateToProps, ticTacToeActions)(TicTacToe);
Add console statements for initial notification
Add console statements for initial notification
JavaScript
mit
terakilobyte/terakilobyte.github.io,terakilobyte/terakilobyte.github.io
--- +++ @@ -7,7 +7,8 @@ const mapStateToProps = (state) => { return { - playerTurn: state.tictactoe.playerTurn + playerTurn: state.tictactoe.playerTurn, + winner: state.tictactoe.winner }; }; @@ -24,8 +25,10 @@ } if (propObj.winner && propObj.winner.result === 'draw') { // do very cool modal fadein + console.log('DRAW'); } else if (propObj.winner) { // do very cool modal fadein with computer winning + console.log('YOU LOST'); } // nothing else, the player can't win } @@ -34,6 +37,8 @@ return ( <div> <h1 className='text-center'>Tic-Tac-Toe</h1> + <h2 className='text-center'>Open your console to see messages</h2> + <h3 className='text-center'>You can't win</h3> <GameBoard /> </div> );
520a7ecf81d37df70aefe39efe2e9e1092f25a52
tests/unit/models/canvas-test.js
tests/unit/models/canvas-test.js
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('canvas', 'Unit | Model | canvas', { // Specify the other units that are required for this test. needs: 'model:op model:pulseEvent model:team model:user'.w() }); test('it exists', function(assert) { const model = this.subject(); assert.ok(Boolean(model)); });
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('canvas', 'Unit | Model | canvas', { // Specify the other units that are required for this test. needs: 'model:comment model:op model:pulseEvent model:team model:user'.w() }); test('it exists', function(assert) { const model = this.subject(); assert.ok(Boolean(model)); });
Add missing model dependency for canvas model test
Add missing model dependency for canvas model test
JavaScript
apache-2.0
usecanvas/web-v2,usecanvas/web-v2,usecanvas/web-v2
--- +++ @@ -2,7 +2,7 @@ moduleForModel('canvas', 'Unit | Model | canvas', { // Specify the other units that are required for this test. - needs: 'model:op model:pulseEvent model:team model:user'.w() + needs: 'model:comment model:op model:pulseEvent model:team model:user'.w() }); test('it exists', function(assert) {
7d8ef029b25f4869bf046e6e28fc4bd801614944
src/atom/index.js
src/atom/index.js
class Atom { constructor(state) { this.state = state; this.watches = {}; } reset(state) { return this._change(state); } swap(f, ...args) { return this._change(f(this.state, ...args)); } deref() { return this.state; } addWatch(k, f) { // if (this.watches[key]) { // console.warn(`adding a watch with an already registered key: ${k}`); // } this.watches[k] = f; return this; } removeWatch(k) { // if (!this.watches[key]) { // console.warn(`removing a watch with an unknown key: ${k}`); // } delete this.watches[key]; return this; } _change(newState) { const { state, watches } = this; Object.keys(watches).forEach(k => watches[k](k, state, newState)); this.state = newState; return this.state; } } export default function atom(state) { return new Atom(state); }
class Atom { constructor(state) { this.state = state; this.watches = {}; } reset(state) { return this._change(state); } swap(f, ...args) { return this._change(f(this.state, ...args)); } deref() { return this.state; } addWatch(k, f) { // if (this.watches[key]) { // console.warn(`adding a watch with an already registered key: ${k}`); // } this.watches[k] = f; return this; } removeWatch(k) { // if (!this.watches[key]) { // console.warn(`removing a watch with an unknown key: ${k}`); // } delete this.watches[key]; return this; } _change(newState) { const { state, watches } = this; this.state = newState; Object.keys(watches).forEach(k => watches[k](k, state, newState)); return this.state; } } export default function atom(state) { return new Atom(state); }
Update atom state before calling watches
Update atom state before calling watches
JavaScript
mit
mike-casas/lock,mike-casas/lock,auth0/lock-passwordless,mike-casas/lock,auth0/lock-passwordless,auth0/lock-passwordless
--- +++ @@ -34,8 +34,8 @@ _change(newState) { const { state, watches } = this; + this.state = newState; Object.keys(watches).forEach(k => watches[k](k, state, newState)); - this.state = newState; return this.state; } }
fc4428b965c58dda423f8bd100ccbb0760d44893
spec/case-sensitive/program.js
spec/case-sensitive/program.js
var test = require("test"); require("a"); try { require("A"); test.assert(false, "should fail to require alternate spelling"); } catch (error) { } test.print("DONE", "info");
var test = require("test"); try { require("a"); require("A"); test.assert(false, "should fail to require alternate spelling"); } catch (error) { } test.print("DONE", "info");
Update case sensitivity test to capture errors on first require
Update case sensitivity test to capture errors on first require as this throws on case sensitive systems.
JavaScript
bsd-3-clause
kriskowal/mr,kriskowal/mr
--- +++ @@ -1,6 +1,6 @@ var test = require("test"); -require("a"); try { + require("a"); require("A"); test.assert(false, "should fail to require alternate spelling"); } catch (error) {
ec343008e4db8688acfb383a3b254a86ecfeac29
shared/reducers/favorite.js
shared/reducers/favorite.js
/* @flow */ import * as Constants from '../constants/favorite' import {logoutDone} from '../constants/login' import type {FavoriteAction} from '../constants/favorite' import type {Folder} from '../constants/types/flow-types' type State = { folders: ?Array<Folder> } const initialState = { folders: null } export default function (state: State = initialState, action: FavoriteAction): State { switch (action.type) { case Constants.favoriteList: return { ...state, folders: action.payload && action.payload.folders } case logoutDone: { return { ...state, folders: null } } default: return state } }
/* @flow */ import * as Constants from '../constants/favorite' import {logoutDone} from '../constants/login' import type {FavoriteAction} from '../constants/favorite' import type {Folder} from '../constants/types/flow-types' type State = { folders: ?Array<Folder> } const initialState = { folders: null } export default function (state: State = initialState, action: FavoriteAction): State { switch (action.type) { case Constants.favoriteList: return { ...state, folders: action.payload && action.payload.folders } case logoutDone: { return { ...initialState } } default: return state } }
Use initial state instead of setting folder manually
Use initial state instead of setting folder manually
JavaScript
bsd-3-clause
keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client
--- +++ @@ -22,8 +22,7 @@ } case logoutDone: { return { - ...state, - folders: null + ...initialState } } default:
42be88e329535f7777e0c33da7194d21bf81c6b4
gulp/tasks/html.js
gulp/tasks/html.js
var gulp = require ('gulp'); gulp.task ( 'html', ['css'], function() { gulp.src('src/main/resources/html/**') .pipe ( gulp.dest( './build/') ); gulp.src('src/test/resources/**') .pipe ( gulp.dest('./build/data/')); gulp.src(['node_modules/dat-gui/vendor/dat*.js']) .pipe ( gulp.dest('./build/js/')); // "Vendor" packages // Bootstrap gulp.src(['node_modules/bootstrap/dist/**']) .pipe ( gulp.dest('./build')); // Font Awesome gulp.src(['node_modules/font-awesome/fonts/**']) .pipe( gulp.dest('./build/fonts')); gulp.src(['node_modules/font-awesome/css/**']) .pipe( gulp.dest('./build/css')); // JQuery gulp.src(['node_modules/jquery/dist/**']) .pipe( gulp.dest('./build/js')); // Dropzone file upload gulp.src(['node_modules/dropzone/downloads/*js']) .pipe(gulp.dest('./build/js')); gulp.src(['node_modules/dropzone/downloads/css/**']) .pipe(gulp.dest('./build/css')); gulp.src(['node_modules/dropzone/downloads/images/**']) .pipe(gulp.dest('./build/images')); });
var gulp = require ('gulp'); gulp.task ( 'html', ['css'], function() { gulp.src('src/main/resources/html/**') .pipe ( gulp.dest( './build/') ); gulp.src('src/main/resources/js/**') .pipe ( gulp.dest( './build/js/') ); gulp.src('src/main/resources/images/**') .pipe ( gulp.dest( './build/images/') ); gulp.src('src/test/resources/**') .pipe ( gulp.dest('./build/data/')); gulp.src(['node_modules/dat-gui/vendor/dat*.js']) .pipe ( gulp.dest('./build/js/')); // XTK Local build (if available) // should copy for production gulp.src(['../X/utils/xtk.js']) .pipe ( gulp.dest('./build/js')); // "Vendor" packages // Bootstrap gulp.src(['node_modules/bootstrap/dist/**']) .pipe ( gulp.dest('./build')); // Font Awesome gulp.src(['node_modules/font-awesome/fonts/**']) .pipe( gulp.dest('./build/fonts')); gulp.src(['node_modules/font-awesome/css/**']) .pipe( gulp.dest('./build/css')); // JQuery gulp.src(['node_modules/jquery/dist/**']) .pipe( gulp.dest('./build/js')); // Dropzone file upload gulp.src(['node_modules/dropzone/downloads/*js']) .pipe(gulp.dest('./build/js')); gulp.src(['node_modules/dropzone/downloads/css/**']) .pipe(gulp.dest('./build/css')); gulp.src(['node_modules/dropzone/downloads/images/**']) .pipe(gulp.dest('./build/images')); });
Include JS and XTK in build
Include JS and XTK in build
JavaScript
bsd-3-clause
dblezek/webapp-skeleton,dblezek/webapp-skeleton
--- +++ @@ -5,11 +5,23 @@ gulp.src('src/main/resources/html/**') .pipe ( gulp.dest( './build/') ); + gulp.src('src/main/resources/js/**') + .pipe ( gulp.dest( './build/js/') ); + + gulp.src('src/main/resources/images/**') + .pipe ( gulp.dest( './build/images/') ); + gulp.src('src/test/resources/**') .pipe ( gulp.dest('./build/data/')); gulp.src(['node_modules/dat-gui/vendor/dat*.js']) .pipe ( gulp.dest('./build/js/')); + + + // XTK Local build (if available) + // should copy for production + gulp.src(['../X/utils/xtk.js']) + .pipe ( gulp.dest('./build/js')); // "Vendor" packages // Bootstrap @@ -27,10 +39,10 @@ .pipe( gulp.dest('./build/js')); // Dropzone file upload -gulp.src(['node_modules/dropzone/downloads/*js']) -.pipe(gulp.dest('./build/js')); -gulp.src(['node_modules/dropzone/downloads/css/**']) -.pipe(gulp.dest('./build/css')); -gulp.src(['node_modules/dropzone/downloads/images/**']) -.pipe(gulp.dest('./build/images')); + gulp.src(['node_modules/dropzone/downloads/*js']) + .pipe(gulp.dest('./build/js')); + gulp.src(['node_modules/dropzone/downloads/css/**']) + .pipe(gulp.dest('./build/css')); + gulp.src(['node_modules/dropzone/downloads/images/**']) + .pipe(gulp.dest('./build/images')); });
06a9a7400aedc0985657874c3aba35af6ab6b1fb
app/components/Settings/components/colors-panel.js
app/components/Settings/components/colors-panel.js
import React from 'react'; import PropTypes from 'prop-types'; import { Switch } from '@blueprintjs/core'; import { Themes } from '../../../containers/enums'; const ColorsPanel = ({ theme, setTheme }) => <div className="mt-1"> <h3 className="mb-3">Themes</h3> <Switch label="Dark Theme" checked={theme === Themes.DARK} onChange={() => setTheme(theme === Themes.DARK ? Themes.LIGHT : Themes.DARK)} className="pt-large w-fit-content" /> </div>; ColorsPanel.propTypes = { theme: PropTypes.string.isRequired, setTheme: PropTypes.func.isRequired }; export default ColorsPanel;
import React from 'react'; import PropTypes from 'prop-types'; import { RadioGroup, Radio } from '@blueprintjs/core'; import { Themes } from '../../../containers/enums'; const ColorsPanel = ({ theme, setTheme }) => <div className="mt-1"> <RadioGroup label="Themes" selectedValue={theme} onChange={e => setTheme(e.target.value)} > <Radio label="Dark Mode" value={Themes.DARK} /> <Radio label="Light Mode" value={Themes.LIGHT} /> </RadioGroup> </div>; ColorsPanel.propTypes = { theme: PropTypes.string.isRequired, setTheme: PropTypes.func.isRequired }; export default ColorsPanel;
Select themes as radio buttons
enhancement: Select themes as radio buttons
JavaScript
mit
builtwithluv/ZenFocus,builtwithluv/ZenFocus
--- +++ @@ -1,18 +1,18 @@ import React from 'react'; import PropTypes from 'prop-types'; -import { Switch } from '@blueprintjs/core'; +import { RadioGroup, Radio } from '@blueprintjs/core'; import { Themes } from '../../../containers/enums'; const ColorsPanel = ({ theme, setTheme }) => <div className="mt-1"> - <h3 className="mb-3">Themes</h3> - <Switch - label="Dark Theme" - checked={theme === Themes.DARK} - onChange={() => - setTheme(theme === Themes.DARK ? Themes.LIGHT : Themes.DARK)} - className="pt-large w-fit-content" - /> + <RadioGroup + label="Themes" + selectedValue={theme} + onChange={e => setTheme(e.target.value)} + > + <Radio label="Dark Mode" value={Themes.DARK} /> + <Radio label="Light Mode" value={Themes.LIGHT} /> + </RadioGroup> </div>; ColorsPanel.propTypes = {
d286a3d9d171b77651e6c81fad3970baa5584fdc
src/javascript/binary/common_functions/check_new_release.js
src/javascript/binary/common_functions/check_new_release.js
const url_for_static = require('../base/url').url_for_static; const moment = require('moment'); const check_new_release = function() { // calling this method is handled by GTM tags const last_reload = localStorage.getItem('new_release_reload_time'); // prevent reload in less than 10 minutes if (last_reload && +last_reload + (10 * 60 * 1000) > moment().valueOf()) return; const currect_hash = $('script[src*="binary.min.js"],script[src*="binary.js"]').attr('src').split('?')[1]; const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (+xhttp.readyState === 4 && +xhttp.status === 200) { const latest_hash = xhttp.responseText; if (latest_hash && latest_hash !== currect_hash) { localStorage.setItem('new_release_reload_time', moment().valueOf()); window.location.reload(true); } } }; xhttp.open('GET', url_for_static() + 'version?' + Math.random().toString(36).slice(2), true); xhttp.send(); }; module.exports = { check_new_release: check_new_release, };
const url_for_static = require('../base/url').url_for_static; const moment = require('moment'); const check_new_release = function() { // calling this method is handled by GTM tags const last_reload = localStorage.getItem('new_release_reload_time'); // prevent reload in less than 10 minutes if (last_reload && +last_reload + (10 * 60 * 1000) > moment().valueOf()) return; localStorage.setItem('new_release_reload_time', moment().valueOf()); const currect_hash = $('script[src*="binary.min.js"],script[src*="binary.js"]').attr('src').split('?')[1]; const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (+xhttp.readyState === 4 && +xhttp.status === 200) { const latest_hash = xhttp.responseText; if (latest_hash && latest_hash !== currect_hash) { window.location.reload(true); } } }; xhttp.open('GET', url_for_static() + 'version?' + Math.random().toString(36).slice(2), true); xhttp.send(); }; module.exports = { check_new_release: check_new_release, };
Check for new release in 10 minutes intervals
Check for new release in 10 minutes intervals
JavaScript
apache-2.0
binary-com/binary-static,negar-binary/binary-static,4p00rv/binary-static,ashkanx/binary-static,raunakkathuria/binary-static,raunakkathuria/binary-static,binary-static-deployed/binary-static,binary-static-deployed/binary-static,raunakkathuria/binary-static,binary-com/binary-static,kellybinary/binary-static,ashkanx/binary-static,4p00rv/binary-static,negar-binary/binary-static,binary-com/binary-static,negar-binary/binary-static,kellybinary/binary-static,ashkanx/binary-static,binary-static-deployed/binary-static,4p00rv/binary-static,kellybinary/binary-static
--- +++ @@ -5,13 +5,13 @@ const last_reload = localStorage.getItem('new_release_reload_time'); // prevent reload in less than 10 minutes if (last_reload && +last_reload + (10 * 60 * 1000) > moment().valueOf()) return; + localStorage.setItem('new_release_reload_time', moment().valueOf()); const currect_hash = $('script[src*="binary.min.js"],script[src*="binary.js"]').attr('src').split('?')[1]; const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (+xhttp.readyState === 4 && +xhttp.status === 200) { const latest_hash = xhttp.responseText; if (latest_hash && latest_hash !== currect_hash) { - localStorage.setItem('new_release_reload_time', moment().valueOf()); window.location.reload(true); } }
45731fa369103e32b6b02d6ed5e99997def24e08
app/client/components/Sidebar/Sidebar.js
app/client/components/Sidebar/Sidebar.js
// @flow import React, { Component } from 'react' import { Link } from 'react-router' import s from './Sidebar.scss' export default class Sidebar extends Component { constructor (props) { super(props) this.state = { links: [ { text: 'Dashboard', to: '/admin/dashboard' }, { text: 'Entries', to: '/admin/entries' }, { text: 'Globals', to: '/admin/globals' }, { text: 'Categories', to: '/admin/categories' }, { text: 'Assets', to: '/admin/assets' }, { text: 'Settings', to: '/admin/settings' } ] } } renderLink (link) { return ( <li> <Link className={s.link} activeClassName={s.activeLink} to={link.to}> {link.text} </Link> </li> ) } render () { return ( <header className={s.root}> <nav className={s.nav}> <ul> {this.state.links.map(this.renderLink)} </ul> </nav> </header> ) } }
// @flow import React, { Component } from 'react' import { Link } from 'react-router' import s from './Sidebar.scss' export default class Sidebar extends Component { constructor (props) { super(props) this.state = { links: [ { text: 'Dashboard', to: '/admin/dashboard' }, { text: 'Entries', to: '/admin/entries' }, { text: 'Globals', to: '/admin/globals' }, { text: 'Categories', to: '/admin/categories' }, { text: 'Assets', to: '/admin/assets' }, { text: 'Settings', to: '/admin/settings' } ] } } renderLink (link, index) { return ( <li key={index}> <Link className={s.link} activeClassName={s.activeLink} to={link.to}> {link.text} </Link> </li> ) } render () { return ( <header className={s.root}> <nav className={s.nav}> <ul> {this.state.links.map(this.renderLink)} </ul> </nav> </header> ) } }
Add key to sidebar links
Add key to sidebar links
JavaScript
mit
jmdesiderio/swan-cms,jmdesiderio/swan-cms
--- +++ @@ -20,9 +20,9 @@ } } - renderLink (link) { + renderLink (link, index) { return ( - <li> + <li key={index}> <Link className={s.link} activeClassName={s.activeLink} to={link.to}>
11c4c935d9bb1ab5967a8eba97cd73d6ee9df684
packages/internal-test-helpers/lib/ember-dev/setup-qunit.js
packages/internal-test-helpers/lib/ember-dev/setup-qunit.js
/* globals QUnit */ export default function setupQUnit(assertion, _qunitGlobal) { var qunitGlobal = QUnit; if (_qunitGlobal) { qunitGlobal = _qunitGlobal; } var originalModule = qunitGlobal.module; qunitGlobal.module = function(name, _options) { var options = _options || {}; var originalSetup = options.setup || function() { }; var originalTeardown = options.teardown || function() { }; options.setup = function() { assertion.reset(); assertion.inject(); return originalSetup.apply(this, arguments); }; options.teardown = function() { let result = originalTeardown.apply(this, arguments); assertion.assert(); assertion.restore(); return result; }; return originalModule(name, options); }; }
/* globals QUnit */ export default function setupQUnit(assertion, _qunitGlobal) { var qunitGlobal = QUnit; if (_qunitGlobal) { qunitGlobal = _qunitGlobal; } var originalModule = qunitGlobal.module; qunitGlobal.module = function(name, _options) { var options = _options || {}; var originalSetup = options.setup || options.beforeEach || function() { }; var originalTeardown = options.teardown || options.afterEach || function() { }; delete options.setup; delete options.teardown; options.beforeEach = function() { assertion.reset(); assertion.inject(); return originalSetup.apply(this, arguments); }; options.afterEach = function() { let result = originalTeardown.apply(this, arguments); assertion.assert(); assertion.restore(); return result; }; return originalModule(name, options); }; }
Add support for beforeEach / afterEach to ember-dev assertions.
Add support for beforeEach / afterEach to ember-dev assertions.
JavaScript
mit
kellyselden/ember.js,fpauser/ember.js,thoov/ember.js,kanongil/ember.js,Gaurav0/ember.js,mixonic/ember.js,csantero/ember.js,Gaurav0/ember.js,Turbo87/ember.js,kennethdavidbuck/ember.js,gfvcastro/ember.js,sandstrom/ember.js,csantero/ember.js,xiujunma/ember.js,asakusuma/ember.js,qaiken/ember.js,jasonmit/ember.js,givanse/ember.js,tildeio/ember.js,qaiken/ember.js,sly7-7/ember.js,karthiick/ember.js,kellyselden/ember.js,thoov/ember.js,knownasilya/ember.js,kanongil/ember.js,jaswilli/ember.js,csantero/ember.js,givanse/ember.js,mixonic/ember.js,stefanpenner/ember.js,givanse/ember.js,GavinJoyce/ember.js,jaswilli/ember.js,mike-north/ember.js,sandstrom/ember.js,Turbo87/ember.js,asakusuma/ember.js,emberjs/ember.js,Serabe/ember.js,kanongil/ember.js,cibernox/ember.js,qaiken/ember.js,thoov/ember.js,miguelcobain/ember.js,mike-north/ember.js,kellyselden/ember.js,mike-north/ember.js,runspired/ember.js,gfvcastro/ember.js,knownasilya/ember.js,bekzod/ember.js,intercom/ember.js,twokul/ember.js,GavinJoyce/ember.js,qaiken/ember.js,jasonmit/ember.js,jasonmit/ember.js,fpauser/ember.js,sly7-7/ember.js,bekzod/ember.js,xiujunma/ember.js,mixonic/ember.js,fpauser/ember.js,tildeio/ember.js,twokul/ember.js,stefanpenner/ember.js,kellyselden/ember.js,mfeckie/ember.js,tildeio/ember.js,elwayman02/ember.js,asakusuma/ember.js,twokul/ember.js,runspired/ember.js,miguelcobain/ember.js,karthiick/ember.js,cibernox/ember.js,knownasilya/ember.js,intercom/ember.js,gfvcastro/ember.js,mfeckie/ember.js,emberjs/ember.js,jaswilli/ember.js,mike-north/ember.js,gfvcastro/ember.js,elwayman02/ember.js,asakusuma/ember.js,xiujunma/ember.js,sandstrom/ember.js,kanongil/ember.js,Serabe/ember.js,bekzod/ember.js,bekzod/ember.js,Turbo87/ember.js,jasonmit/ember.js,stefanpenner/ember.js,Gaurav0/ember.js,miguelcobain/ember.js,twokul/ember.js,cibernox/ember.js,kennethdavidbuck/ember.js,runspired/ember.js,karthiick/ember.js,jasonmit/ember.js,kennethdavidbuck/ember.js,fpauser/ember.js,miguelcobain/ember.js,elwayman02/ember.js,jaswilli/ember.js,xiujunma/ember.js,Serabe/ember.js,mfeckie/ember.js,givanse/ember.js,elwayman02/ember.js,Gaurav0/ember.js,GavinJoyce/ember.js,csantero/ember.js,Turbo87/ember.js,intercom/ember.js,cibernox/ember.js,mfeckie/ember.js,emberjs/ember.js,runspired/ember.js,GavinJoyce/ember.js,sly7-7/ember.js,Serabe/ember.js,intercom/ember.js,kennethdavidbuck/ember.js,karthiick/ember.js,thoov/ember.js
--- +++ @@ -11,17 +11,20 @@ qunitGlobal.module = function(name, _options) { var options = _options || {}; - var originalSetup = options.setup || function() { }; - var originalTeardown = options.teardown || function() { }; + var originalSetup = options.setup || options.beforeEach || function() { }; + var originalTeardown = options.teardown || options.afterEach || function() { }; - options.setup = function() { + delete options.setup; + delete options.teardown; + + options.beforeEach = function() { assertion.reset(); assertion.inject(); return originalSetup.apply(this, arguments); }; - options.teardown = function() { + options.afterEach = function() { let result = originalTeardown.apply(this, arguments); assertion.assert();
7dbdff31b9c97fb7eed2420e1e46508dee1797a2
ember-cli-build.js
ember-cli-build.js
/* global require, module */ var EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); module.exports = function (defaults) { var app = new EmberAddon(defaults, { 'ember-cli-babel': { includePolyfill: true }, 'ember-cli-qunit': { useLintTree: false // we use standard instead } }); // we do this because we don't want the addon to bundle it, but we need it for dev app.import('vendor/adapter.js'); /* This build file specifies the options for the dummy test app of this addon, located in `/tests/dummy` This build file does *not* influence how the addon or the app using it behave. You most likely want to be modifying `./index.js` or app's build file */ return app.toTree(); };
/* global require, module */ var EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); const cdnUrl = process.env.CDN_URL || '/'; module.exports = function (defaults) { var app = new EmberAddon(defaults, { 'ember-cli-babel': { includePolyfill: true }, 'ember-cli-qunit': { useLintTree: false // we use standard instead }, fingerprint: { prepend: cdnUrl, extensions: ['js', 'css'] } }); // we do this because we don't want the addon to bundle it, but we need it for dev app.import('vendor/adapter.js'); /* This build file specifies the options for the dummy test app of this addon, located in `/tests/dummy` This build file does *not* influence how the addon or the app using it behave. You most likely want to be modifying `./index.js` or app's build file */ return app.toTree(); };
Add fingerprinting for troubleshooter deployed app
Add fingerprinting for troubleshooter deployed app
JavaScript
mit
MyPureCloud/ember-webrtc-troubleshoot,MyPureCloud/ember-webrtc-troubleshoot,MyPureCloud/ember-webrtc-troubleshoot
--- +++ @@ -1,5 +1,7 @@ /* global require, module */ var EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); + +const cdnUrl = process.env.CDN_URL || '/'; module.exports = function (defaults) { var app = new EmberAddon(defaults, { @@ -8,6 +10,10 @@ }, 'ember-cli-qunit': { useLintTree: false // we use standard instead + }, + fingerprint: { + prepend: cdnUrl, + extensions: ['js', 'css'] } });
294aafacd298a013881f92f7a866a8b07f5a25f5
examples/simple.js
examples/simple.js
"use strict"; const Rectangle = require('../lib/Rectangle'); const cursor = require('kittik-cursor').create().resetTTY(); Rectangle.create({text: 'Text here!', x: 'center', width: 20, background: 'green', foreground: 'black'}).render(cursor); Rectangle.create({x: 'center', y: 'middle', width: '50%', height: '20%', background: 'dark_blue'}).render(cursor); cursor.moveTo(1, process.stdout.rows).flush();
"use strict"; const Rectangle = require('../lib/Rectangle'); const cursor = require('kittik-cursor').create().resetTTY(); Rectangle.create({ text: 'Text here!', x: 'center', y: 2, width: 40, background: 'green', foreground: 'black' }).render(cursor); Rectangle.create({ text: 'Text here', x: 'center', y: 'middle', width: '50%', height: '20%', background: 'dark_blue' }).render(cursor); cursor.moveTo(1, process.stdout.rows).flush();
Update shape-basic to the latest version
fix(shape): Update shape-basic to the latest version
JavaScript
mit
kittikjs/shape-rectangle
--- +++ @@ -3,7 +3,22 @@ const Rectangle = require('../lib/Rectangle'); const cursor = require('kittik-cursor').create().resetTTY(); -Rectangle.create({text: 'Text here!', x: 'center', width: 20, background: 'green', foreground: 'black'}).render(cursor); -Rectangle.create({x: 'center', y: 'middle', width: '50%', height: '20%', background: 'dark_blue'}).render(cursor); +Rectangle.create({ + text: 'Text here!', + x: 'center', + y: 2, + width: 40, + background: 'green', + foreground: 'black' +}).render(cursor); + +Rectangle.create({ + text: 'Text here', + x: 'center', + y: 'middle', + width: '50%', + height: '20%', + background: 'dark_blue' +}).render(cursor); cursor.moveTo(1, process.stdout.rows).flush();
68943423f789993e2ca91cd5f76e94d524a127c8
addon/authenticators/token.js
addon/authenticators/token.js
import Ember from 'ember'; import Base from 'ember-simple-auth/authenticators/base'; import Configuration from '../configuration'; const { get, isEmpty, inject: { service }, RSVP: { resolve, reject } } = Ember; export default Base.extend({ ajax: service(), init() { this._super(...arguments); this.serverTokenEndpoint = Configuration.serverTokenEndpoint; this.tokenAttributeName = Configuration.tokenAttributeName; this.identificationAttributeName = Configuration.identificationAttributeName; }, restore(data) { const token = get(data, this.tokenAttributeName); if (!isEmpty(token)) { return resolve(data); } else { return reject(); } }, authenticate(data) { return get(this, 'ajax').post(this.serverTokenEndpoint, { data: JSON.stringify(data) }).then((response) => { return resolve(response); }).catch((error) => { Ember.Logger.warn(error); return reject(); }); } });
import Ember from 'ember'; import Base from 'ember-simple-auth/authenticators/base'; import Configuration from '../configuration'; const { get, isEmpty, inject: { service }, RSVP: { resolve, reject } } = Ember; export default Base.extend({ ajax: service(), init() { this._super(...arguments); this.serverTokenEndpoint = Configuration.serverTokenEndpoint; this.tokenAttributeName = Configuration.tokenAttributeName; this.identificationAttributeName = Configuration.identificationAttributeName; }, restore(data) { const token = get(data, this.tokenAttributeName); if (!isEmpty(token)) { return resolve(data); } else { return reject(); } }, authenticate(data) { return get(this, 'ajax').post(this.serverTokenEndpoint, { contentType: 'application/json', data: JSON.stringify(data) }).then((response) => { return resolve(response); }).catch((error) => { Ember.Logger.warn(error); return reject(); }); } });
Add JSON content type to authenticate headers
Add JSON content type to authenticate headers
JavaScript
mit
datajohnny/ember-simple-token,datajohnny/ember-simple-token
--- +++ @@ -25,6 +25,7 @@ authenticate(data) { return get(this, 'ajax').post(this.serverTokenEndpoint, { + contentType: 'application/json', data: JSON.stringify(data) }).then((response) => { return resolve(response);
836cf5d5caf8a0cde92a6e018f3ea28aa77eb42e
app/javascript/application.js
app/javascript/application.js
// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails import "@hotwired/turbo-rails" import './controllers'
// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails import "@hotwired/turbo-rails" import 'controllers'
Fix importmap loading on production
Fix importmap loading on production
JavaScript
mit
dncrht/mical,dncrht/mical,dncrht/mical,dncrht/mical
--- +++ @@ -2,4 +2,4 @@ import "@hotwired/turbo-rails" -import './controllers' +import 'controllers'
99fe3b420e9bc14a2d01fd0f3c61bb94ce970a2c
hooks/src/index.js
hooks/src/index.js
import { options } from 'preact'; let currentIndex; let component; options.beforeRender = function (vnode) { component = vnode._component; currentIndex = 0; } const createHook = (create) => (...args) => { if (component == null) return; const list = component.__hooks || (component.__hooks = []); let index = currentIndex++; let hook = list[index]; if (!hook) { hook = list[index] = { index, value: undefined }; hook.run = create(hook, component, ...args); } return (hook.value = hook.run()); }; export const useState = createHook((hook, inst, initialValue) => { const stateId = 'hookstate$' + hook.index; let value = typeof initialValue === 'function' ? initialValue() : initialValue; const setter = {}; setter[stateId] = inst.state[stateId] = value; function set(v) { value = setter[stateId] = typeof v === 'function' ? v(value) : v; inst.setState(setter); } return () => [value, set]; });
import { options } from 'preact'; let currentIndex; let component; let oldBeforeRender = options.beforeRender; options.beforeRender = vnode => { component = vnode._component; currentIndex = 0; if (oldBeforeRender) oldBeforeRender(vnode) } const createHook = (create) => (...args) => { if (component == null) return; const list = component.__hooks || (component.__hooks = []); let index = currentIndex++; let hook = list[index]; if (!hook) { hook = list[index] = { index, value: undefined }; hook.run = create(hook, component, ...args); } return (hook.value = hook.run()); }; export const useState = createHook((hook, inst, initialValue) => { const stateId = 'hookstate$' + hook.index; let value = typeof initialValue === 'function' ? initialValue() : initialValue; const setter = {}; setter[stateId] = inst.state[stateId] = value; function set(v) { value = setter[stateId] = typeof v === 'function' ? v(value) : v; inst.setState(setter); } return () => [value, set]; });
Call any previous beforeRender() once we're done with ours
Call any previous beforeRender() once we're done with ours
JavaScript
mit
developit/preact,developit/preact
--- +++ @@ -2,10 +2,12 @@ let currentIndex; let component; +let oldBeforeRender = options.beforeRender; -options.beforeRender = function (vnode) { +options.beforeRender = vnode => { component = vnode._component; currentIndex = 0; + if (oldBeforeRender) oldBeforeRender(vnode) } const createHook = (create) => (...args) => {
79788a69daa951d85f4600926c464d6fbff9fe5b
assets/javascripts/global.js
assets/javascripts/global.js
$(function () { $('input[type="file"]').on('change', function (e) { if ($(this).val()) { $('input[type="submit"]').prop('disabled', false); } else { $('input[type="submit"]').prop('disabled', true); } }); $('input[name="format"]').on('change', function (e) { var action = $('form').prop('action'), new_action = action.replace(/\.[^.]+$/, '.' + $(this).val()); $('form').prop('action', new_action); }); $('input[name="format"]').trigger('change'); });
$(function () { $('input[type="file"]').on('change', function (e) { if ($(this).val()) { $('input[type="submit"]').prop('disabled', false); } else { $('input[type="submit"]').prop('disabled', true); } }); $('input[name="format"]:checked').on('change', function (e) { var action = $('form').prop('action'), new_action = action.replace(/\.[^.]+$/, '.' + $(this).val()); $('form').prop('action', new_action); }); $('input[name="format"]:checked').trigger('change'); });
Fix ARCSPC-45: Handle radio button form action setting correctly
Fix ARCSPC-45: Handle radio button form action setting correctly
JavaScript
apache-2.0
harvard-library/archivesspace-checker,harvard-library/archivesspace-checker
--- +++ @@ -7,11 +7,11 @@ $('input[type="submit"]').prop('disabled', true); } }); - $('input[name="format"]').on('change', function (e) { + $('input[name="format"]:checked').on('change', function (e) { var action = $('form').prop('action'), new_action = action.replace(/\.[^.]+$/, '.' + $(this).val()); $('form').prop('action', new_action); }); - $('input[name="format"]').trigger('change'); + $('input[name="format"]:checked').trigger('change'); });
30dd01f64e5e7dc98a517c8ff2353ab2cdde0583
lib/assets/javascripts/cartodb3/components/form-components/editors/node-dataset/node-dataset-item-view.js
lib/assets/javascripts/cartodb3/components/form-components/editors/node-dataset/node-dataset-item-view.js
var CustomListItemView = require('cartodb3/components/custom-list/custom-list-item-view'); var _ = require('underscore'); module.exports = CustomListItemView.extend({ render: function () { this.$el.empty(); this.clearSubViews(); this.$el.append( this.options.template( _.extend( { typeLabel: this.options.typeLabel, isSelected: this.model.get('selected'), name: this.model.getName(), val: this.model.getValue() }, this.model.attributes ) ) ); this.$el .attr('data-val', this.model.getValue()) .toggleClass('is-disabled', !!this.model.get('disabled')); return this; } });
var CustomListItemView = require('cartodb3/components/custom-list/custom-list-item-view'); var _ = require('underscore'); module.exports = CustomListItemView.extend({ render: function () { this.$el.empty(); this.clearSubViews(); this.$el.append( this.options.template( _.extend( { typeLabel: this.options.typeLabel, isSelected: this.model.get('selected'), isSourceType: this.model.get('isSourceType'), name: this.model.getName(), val: this.model.getValue() }, this.model.attributes ) ) ); this.$el .attr('data-val', this.model.getValue()) .toggleClass('is-disabled', !!this.model.get('disabled')); return this; } });
Add isSourceType to base template object
Add isSourceType to base template object
JavaScript
bsd-3-clause
CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb
--- +++ @@ -13,6 +13,7 @@ { typeLabel: this.options.typeLabel, isSelected: this.model.get('selected'), + isSourceType: this.model.get('isSourceType'), name: this.model.getName(), val: this.model.getValue() },
36a53309e022f1ad6351756568bcc4d9e0df6940
app/src/common/base-styles.js
app/src/common/base-styles.js
export default function() { return ` html { height: 100%; overflow-y: scroll; } body { font-family: 'Lato', sans-serif; font-size: 14px; color: #000; background: #f6f6f6; } `; }
export default function() { return ` *, *:before, *:after { box-sizing: inherit; } html { height: 100%; overflow-y: scroll; box-sizing: border-box; } body { font-family: 'Lato', sans-serif; font-size: 14px; color: #000; background: #f6f6f6; } `; }
Use 'border-box' as default box sizing
:lipstick: Use 'border-box' as default box sizing
JavaScript
mit
vvasilev-/weatheros,vvasilev-/weatheros
--- +++ @@ -1,8 +1,15 @@ export default function() { return ` + *, + *:before, + *:after { + box-sizing: inherit; + } + html { height: 100%; overflow-y: scroll; + box-sizing: border-box; } body {
b3b18edfa2e964fe76125eb53189d92c48b867d1
src/is-defined.js
src/is-defined.js
define([ ], function () { /** * @exports is-defined * * Helper which checks whether a variable is defined or not. * * @param {*} check The variable to check that is defined * @param {String} type The type your expecting the variable to be defined as. * * @returns {Boolean} When the variable is undefined it will pass back false otherwise pass back true. * * @example * ```js * var barney; * isDefined(barney); * // Returns false * * var barney = 'stinson'; * isDefined(barney); * // Returns true * * isDefined(barney, 'string'); * // Returns true * * isDefined(barney, 'function'); * // Returns false * ``` */ function isDefined (check, type) { // Check that the variable is a specific type if (type) { var regex = new RegExp(/\[object (\w+)]/), string = Object.prototype.toString.call(check).toLowerCase(), matches = string.match(regex); return matches[1] === type; } return (typeof check !== 'undefined'); } return isDefined; });
define([ ], function () { /** * @exports is-defined * * Helper which checks whether a variable is defined or not. * * @param {*} check The variable to check that is defined * @param {String} type The type your expecting the variable to be defined as. * * @returns {Boolean} When the variable is undefined it will pass back false otherwise pass back true. * * @example * ```js * var barney; * isDefined(barney); * // Returns false * * var barney = 'stinson'; * isDefined(barney); * // Returns true * * isDefined(barney, 'string'); * // Returns true * * isDefined(barney, 'function'); * // Returns false * ``` */ function isDefined (check, type) { // Check that the variable is a specific type && not undefined (IE8 reports undefined variables as objects) if (type && typeof check !== 'undefined') { var regex = new RegExp(/\[object (\w+)]/), string = Object.prototype.toString.call(check).toLowerCase(), matches = string.match(regex); return matches[1] === type; } return (typeof check !== 'undefined'); } return isDefined; });
Fix bug in IE8 undefined returns as object
Fix bug in IE8 undefined returns as object
JavaScript
mit
rockabox/Auxilium.js
--- +++ @@ -29,8 +29,8 @@ * ``` */ function isDefined (check, type) { - // Check that the variable is a specific type - if (type) { + // Check that the variable is a specific type && not undefined (IE8 reports undefined variables as objects) + if (type && typeof check !== 'undefined') { var regex = new RegExp(/\[object (\w+)]/), string = Object.prototype.toString.call(check).toLowerCase(), matches = string.match(regex);
7f3804a1da20276ad309fa6554cca329f296ff64
app/assets/javascripts/districts/controllers/sister_modal_controller.js
app/assets/javascripts/districts/controllers/sister_modal_controller.js
VtTracker.SisterModalController = Ember.ObjectController.extend({ needs: ['districtSistersIndex', 'application'], districts: Ember.computed.alias('controllers.application.model'), modalTitle: function() { if (this.get('isNew')) { return 'New Sister'; } else { return 'Edit Sister'; } }.property('isNew'), actions: { save: function() { var _self = this; var isNew = _self.get('model.isNew'); var district = _self.get('model.district'); _self.get('model').save().then(function() { if (isNew) { _self.set('controllers.districtSistersIndex.newSister', _self.store.createRecord('sister', { district: district })); } }); } } });
VtTracker.SisterModalController = Ember.ObjectController.extend({ needs: ['districtSistersIndex', 'application'], districts: Ember.computed.alias('controllers.application.model'), modalTitle: function() { if (this.get('isNew')) { return 'New Sister'; } else { return 'Edit Sister'; } }.property('isNew'), actions: { removeModal: function() { this.get('model').rollback(); return true; }, save: function() { var _self = this; var isNew = _self.get('model.isNew'); var district = _self.get('model.district'); _self.get('model').save().then(function() { if (isNew) { _self.set('controllers.districtSistersIndex.newSister', _self.store.createRecord('sister', { district: district })); } }); } } });
Rollback model when modal is closed
Rollback model when modal is closed
JavaScript
mit
bfcoder/vt-ht-tracker,bfcoder/vt-ht-tracker,bfcoder/vt-ht-tracker
--- +++ @@ -12,6 +12,11 @@ }.property('isNew'), actions: { + removeModal: function() { + this.get('model').rollback(); + return true; + }, + save: function() { var _self = this; var isNew = _self.get('model.isNew');
eb0f5fd8a337ace145c40e9b624738619542033a
Rightmove_Enhancement_Suite.user.js
Rightmove_Enhancement_Suite.user.js
// ==UserScript== // @name Rightmove Enhancement Suite // @namespace https://github.com/chigley/ // @description Keyboard shortcuts // @include http://www.rightmove.co.uk/* // @version 1 // @grant GM_addStyle // @grant GM_getResourceText // @resource style style.css // ==/UserScript== var $ = unsafeWindow.jQuery; GM_addStyle(GM_getResourceText("style")); var listItems = $("[name=summary-list-item]"); // Remove grey background on premium listings. Otherwise, my active item doesn't // stand out against such listings $(".premium").css("background", "white"); listItems.click(function () { listItems.removeClass("RES-active-list-item"); $(this).addClass("RES-active-list-item"); }); $('body').bind('keyup', function(e) { var code = e.keyCode || e.which; if (e.keyCode == 74) { // j alert("j!"); } });
// ==UserScript== // @name Rightmove Enhancement Suite // @namespace https://github.com/chigley/ // @description Keyboard shortcuts // @include http://www.rightmove.co.uk/* // @version 1 // @grant GM_addStyle // @grant GM_getResourceText // @resource style style.css // ==/UserScript== var $ = unsafeWindow.jQuery; GM_addStyle(GM_getResourceText("style")); var listItems = $("[name=summary-list-item]"); var currentlySelected; // Remove grey background on premium listings. Otherwise, my active item doesn't // stand out against such listings $(".premium").css("background", "white"); listItems.click(function () { listItems.removeClass("RES-active-list-item"); $(this).addClass("RES-active-list-item"); currentlySelected = $(this); }); $('body').bind('keyup', function(e) { var code = e.keyCode || e.which; if (e.keyCode == 74) { // j var next = currentlySelected.next("[name=summary-list-item]"); if (next.length == 1) { listItems.removeClass("RES-active-list-item"); next.addClass("RES-active-list-item"); currentlySelected = next; } } });
Select next item with j key
Select next item with j key
JavaScript
mit
chigley/rightmove-enhancement-suite
--- +++ @@ -14,6 +14,7 @@ GM_addStyle(GM_getResourceText("style")); var listItems = $("[name=summary-list-item]"); +var currentlySelected; // Remove grey background on premium listings. Otherwise, my active item doesn't // stand out against such listings @@ -22,12 +23,18 @@ listItems.click(function () { listItems.removeClass("RES-active-list-item"); $(this).addClass("RES-active-list-item"); + currentlySelected = $(this); }); $('body').bind('keyup', function(e) { var code = e.keyCode || e.which; if (e.keyCode == 74) { // j - alert("j!"); + var next = currentlySelected.next("[name=summary-list-item]"); + if (next.length == 1) { + listItems.removeClass("RES-active-list-item"); + next.addClass("RES-active-list-item"); + currentlySelected = next; + } } });
f13ecda8d2a69f455b175d013a2609197f495bb0
src/components/outline/Link.js
src/components/outline/Link.js
// @flow import styled, { css } from 'styled-components' import * as vars from 'settings/styles' import * as colors from 'settings/colors' type Props = { depth: '1' | '2' | '3' | '4' | '5' | '6', } const fn = ({ depth: depthStr }: Props) => { const depth = parseInt(depthStr) return css` padding-left: ${(2 + (depth > 1 ? depth - 2 : 0)) * vars.spacing}px; &:before { content: '${'#'.repeat(depth)}'; } ` } const Link = styled.a` display: block; height: 100%; padding-right: ${2 * vars.spacing}px; border-bottom: 1px solid ${colors.blackForeground200}; text-decoration: none; font-size: 0.9rem; color: white; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; ${fn} &:before { color: ${colors.whiteForeground300}; padding-right: ${vars.spacing}px; font-size: 0.8rem; } &:hover { background-color: ${colors.blackForeground200}; } ` export default Link
// @flow import styled, { css } from 'styled-components' import * as vars from 'settings/styles' import * as colors from 'settings/colors' type Props = { depth: '1' | '2' | '3' | '4' | '5' | '6', } const fn = ({ depth: depthStr }: Props) => { const depth = parseInt(depthStr) return css` padding-left: ${(2 + (depth > 1 ? depth - 2 : 0)) * vars.spacing}px; &:before { content: '${'#'.repeat(depth)}'; } ` } const Link = styled.a` display: block; height: 100%; padding-right: ${2 * vars.spacing}px; border-bottom: 1px solid ${colors.blackForeground200}; text-decoration: none; font-size: 0.9rem; color: white; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; pointer-events: none; ${fn} &:before { color: ${colors.whiteForeground300}; padding-right: ${vars.spacing}px; font-size: 0.8rem; } &:hover { background-color: ${colors.blackForeground200}; } ` export default Link
Disable pointer-events of outline items
Disable pointer-events of outline items
JavaScript
mit
izumin5210/OHP,izumin5210/OHP
--- +++ @@ -31,6 +31,7 @@ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; + pointer-events: none; ${fn}
248b0e54a3bda3271f5735dedf61eda8395d882d
src/helpers/find-root.js
src/helpers/find-root.js
'use babel' /* @flow */ import Path from 'path' import {findCached} from './common' import {CONFIG_FILE_NAME} from '../defaults' export async function findRoot(directory: string): Promise<string> { const configFile = await findCached(directory, CONFIG_FILE_NAME) if (configFile) { return Path.dirname(configFile) } else return directory }
'use babel' /* @flow */ import Path from 'path' import {findCached} from './common' import {CONFIG_FILE_NAME} from '../defaults' export async function findRoot(directory: string): Promise<string> { const configFile = await findCached(directory, CONFIG_FILE_NAME) if (configFile) { return Path.dirname(configFile) } else throw new Error('No configuration found file') }
Throw error if no config is found
:no_entry: Throw error if no config is found
JavaScript
mit
steelbrain/UCompiler
--- +++ @@ -10,5 +10,5 @@ const configFile = await findCached(directory, CONFIG_FILE_NAME) if (configFile) { return Path.dirname(configFile) - } else return directory + } else throw new Error('No configuration found file') }
e78af7ead579d2c91f461734d2bdff5910cf3a5c
server.js
server.js
// Load required modules var http = require('http'), // http server core module port = 8080, timeNow = new Date().toLocaleString('en-US', {hour12: false, timeZone: 'Europe/Kiev'}), express = require('express'), // web framework external module fs = require('fs'), httpApp = express(); // Setup and configure Express http server. Expect a subfolder called 'site' to be the web root. httpApp.use(express.static(__dirname + '/site/')); // Start Express http server on the port console.info(timeNow + ': Starting http server on the port ' + port); console.info(timeNow + ': Ctrl-C to abort'); http.createServer(httpApp).listen(port);
// Load required modules var http = require('http'), // http server core module port = 8080, timeNow = new Date().toLocaleString('en-US', {hour12: false, timeZone: 'Europe/Kiev'}), express = require('express'), // web framework external module fs = require('fs'), httpApp = express(); // Setup and configure Express http server. Expect a subfolder called 'site' to be the web root. httpApp.use(express.static(__dirname + '/site/')); httpApp.get(['/search/*', '/profile/*', '/repo/*'], function(req, res){ res.sendFile(__dirname + '/site/index.html'); }); // Start Express http server on the port console.info(timeNow + ': Starting http server on the port ' + port); console.info(timeNow + ': Ctrl-C to abort'); http.createServer(httpApp).listen(port);
Set reroute to index.html for /search/*, /profile/*, /repo/*
Set reroute to index.html for /search/*, /profile/*, /repo/*
JavaScript
mit
SteveBidenko/github-angular,SteveBidenko/github-angular,SteveBidenko/github-angular
--- +++ @@ -8,6 +8,11 @@ // Setup and configure Express http server. Expect a subfolder called 'site' to be the web root. httpApp.use(express.static(__dirname + '/site/')); + +httpApp.get(['/search/*', '/profile/*', '/repo/*'], function(req, res){ + res.sendFile(__dirname + '/site/index.html'); +}); + // Start Express http server on the port console.info(timeNow + ': Starting http server on the port ' + port); console.info(timeNow + ': Ctrl-C to abort');
cfa1a5e3a4f3e988d3c844c84874a8dabd852822
src/engines/json/validation.js
src/engines/json/validation.js
/** * Validation * * @constructor * @param {object} options */ var Validation = function(options) { // Save a reference to the ‘this’ var self = this; var defaultOptions = { singleError: true, errorMessages: errorMessages, cache: false }; each(defaultOptions, function(key, value) { if (isObject(value) && options[key]) { self[key] = merge(options[key], defaultOptions[key]); } else if (isObject(value) && !options[key]) { self[key] = merge ({}, defaultOptions[key]); } else { self[key] = (isDefined(options[key])) ? options[key] : defaultOptions[key]; } }); this.errors = new ValidationError(); };
/** * Validation * * @constructor * @param {object} options */ var Validation = function(options) { // Save a reference to the ‘this’ var self = this; var defaultOptions = { singleError: true, errorMessages: errorMessages, cache: false }; each(defaultOptions, function(key, value) { if (isObject(value) && options[key]) { self[key] = merge(options[key], defaultOptions[key]); } else if (isObject(value) && !options[key]) { self[key] = merge ({}, defaultOptions[key]); } else { self[key] = (isDefined(options[key])) ? options[key] : defaultOptions[key]; } }); this.errors = new ValidationError(this); };
Initialize the ‘ValidationError’ class as a subclass of the ‘Validation’ class
Initialize the ‘ValidationError’ class as a subclass of the ‘Validation’ class
JavaScript
mit
apiaryio/Amanda,Baggz/Amanda,apiaryio/Amanda
--- +++ @@ -29,6 +29,6 @@ }); - this.errors = new ValidationError(); + this.errors = new ValidationError(this); };
5d309087a7e4cd2931a1c8e29096f9eadb5de188
src/lb.js
src/lb.js
/* * Namespace: lb * Root of Legal Box Scalable JavaScript Application * * Authors: * o Eric Bréchemier <legalbox@eric.brechemier.name> * o Marc Delhommeau <marc.delhommeau@legalbox.com> * * Copyright: * Legal-Box SAS (c) 2010-2011, All Rights Reserved * * License: * BSD License * http://creativecommons.org/licenses/BSD/ * * Version: * 2011-07-04 */ /*jslint white:false, plusplus:false */ /*global define, window */ define(function() { // Note: no methods defined at this level currently var lb = { // public API }; // initialize global variable lb in browser environment, // for backward-compatibility if (window !== undefined){ window.lb = lb; } return lb; });
/* * Namespace: lb * Root of Legal Box Scalable JavaScript Application * * Authors: * o Eric Bréchemier <legalbox@eric.brechemier.name> * o Marc Delhommeau <marc.delhommeau@legalbox.com> * * Copyright: * Legal-Box SAS (c) 2010-2011, All Rights Reserved * * License: * BSD License * http://creativecommons.org/licenses/BSD/ * * Version: * 2011-07-05 */ /*jslint white:false, plusplus:false */ /*global define, window */ define(function(undefined) { // Note: no methods defined at this level currently var lb = { // public API }; // initialize global variable lb in browser environment, // for backward-compatibility if (window !== undefined){ window.lb = lb; } return lb; });
Declare undefined as parameter to make sure it is actually undefined
Declare undefined as parameter to make sure it is actually undefined Since undefined is a property of the global object, its value may be replaced, e.g. due to programming mistakes: if (undefined = myobject){ // programming mistake which assigns undefined // ... }
JavaScript
bsd-3-clause
eric-brechemier/lb_js_scalableApp,eric-brechemier/lb_js_scalableApp,eric-brechemier/lb_js_scalableApp
--- +++ @@ -14,11 +14,11 @@ * http://creativecommons.org/licenses/BSD/ * * Version: - * 2011-07-04 + * 2011-07-05 */ /*jslint white:false, plusplus:false */ /*global define, window */ -define(function() { +define(function(undefined) { // Note: no methods defined at this level currently
a8d2e74163cf71bb811150143089f83aca2c55a0
src/lightbox/LightboxFooter.js
src/lightbox/LightboxFooter.js
/* @flow */ import React, { PureComponent } from 'react'; import { Text, StyleSheet, View } from 'react-native'; import type { Style } from '../types'; import NavButton from '../nav/NavButton'; const styles = StyleSheet.create({ wrapper: { height: 44, flexDirection: 'row', justifyContent: 'space-between', paddingLeft: 16, paddingRight: 8, flex: 1, }, text: { color: 'white', fontSize: 14, alignSelf: 'center', }, icon: { fontSize: 28, }, }); type Props = { style?: Style, displayMessage: string, onOptionsPress: () => void, }; export default class LightboxFooter extends PureComponent<Props> { props: Props; render() { const { displayMessage, onOptionsPress, style } = this.props; return ( <View style={[styles.wrapper, style]}> <Text style={styles.text}>{displayMessage}</Text> <NavButton name="more-vertical" color="white" style={styles.icon} onPress={onOptionsPress} /> </View> ); } }
/* @flow */ import React, { PureComponent } from 'react'; import { Text, StyleSheet, View } from 'react-native'; import type { Style } from '../types'; import Icon from '../common/Icons'; const styles = StyleSheet.create({ wrapper: { height: 44, flexDirection: 'row', justifyContent: 'space-between', paddingLeft: 16, paddingRight: 8, flex: 1, }, text: { color: 'white', fontSize: 14, alignSelf: 'center', }, icon: { fontSize: 28, alignSelf: 'center', }, }); type Props = { style?: Style, displayMessage: string, onOptionsPress: () => void, }; export default class LightboxFooter extends PureComponent<Props> { props: Props; render() { const { displayMessage, onOptionsPress, style } = this.props; return ( <View style={[styles.wrapper, style]}> <Text style={styles.text}>{displayMessage}</Text> <Icon style={styles.icon} color="white" name="more-vertical" onPress={onOptionsPress} /> </View> ); } }
Align option icon in Lightbox screen
layout: Align option icon in Lightbox screen Icon was not properly aligned due to overlay of unreadCount. As there is no need of unreadCount here, Instead of using NavButton, use Icon component directly. Fixes #3003.
JavaScript
apache-2.0
vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile
--- +++ @@ -3,7 +3,7 @@ import { Text, StyleSheet, View } from 'react-native'; import type { Style } from '../types'; -import NavButton from '../nav/NavButton'; +import Icon from '../common/Icons'; const styles = StyleSheet.create({ wrapper: { @@ -21,6 +21,7 @@ }, icon: { fontSize: 28, + alignSelf: 'center', }, }); @@ -38,12 +39,7 @@ return ( <View style={[styles.wrapper, style]}> <Text style={styles.text}>{displayMessage}</Text> - <NavButton - name="more-vertical" - color="white" - style={styles.icon} - onPress={onOptionsPress} - /> + <Icon style={styles.icon} color="white" name="more-vertical" onPress={onOptionsPress} /> </View> ); }
a84b8d2ae8a5abd33936115ef83200fbe8a2d390
docs/config.js
docs/config.js
self.$config = { landing: false, debug: false, repo: 'soruly/whatanime.ga', twitter: 'soruly', url: 'https://whatanime.ga', sidebar: true, disableSidebarToggle: false, nav: { default: [] }, icons: [], plugins: [] }
docute.init({ landing: false, debug: false, repo: 'soruly/whatanime.ga', twitter: 'soruly', url: 'https://whatanime.ga', sidebar: true, disableSidebarToggle: false, nav: { default: [] }, icons: [], plugins: [] });
Update docs for docute v3.0.0
Update docs for docute v3.0.0
JavaScript
mit
soruly/whatanime.ga,soruly/whatanime.ga,soruly/whatanime.ga
--- +++ @@ -1,4 +1,4 @@ -self.$config = { +docute.init({ landing: false, debug: false, repo: 'soruly/whatanime.ga', @@ -11,4 +11,4 @@ }, icons: [], plugins: [] -} +});
2021611229e5b6691297504fc72926b085d70ca3
src/ggrc/assets/javascripts/components/mapped-objects/mapped-objects.js
src/ggrc/assets/javascripts/components/mapped-objects/mapped-objects.js
/*! Copyright (C) 2016 Google Inc., authors, and contributors Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> */ (function (can, GGRC) { 'use strict'; var tpl = can.view(GGRC.mustache_path + '/components/mapped-objects/mapped-objects.mustache'); var tag = 'mapped-objects'; /** * Assessment specific mapped objects view component */ GGRC.Components('mappedObjects', { tag: tag, template: tpl, scope: { isLoading: false, mapping: '@', parentInstance: null, mappedItems: [], setMappedObjects: function (items) { this.attr('isLoading', false); this.attr('mappedItems').replace(items); }, load: function () { this.attr('isLoading', true); this.attr('parentInstance') .get_binding(this.attr('mapping')) .refresh_instances() .then(this.setMappedObjects.bind(this)); } }, init: function () { this.scope.load(); } }); })(window.can, window.GGRC);
/*! Copyright (C) 2016 Google Inc., authors, and contributors Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> */ (function (can, GGRC) { 'use strict'; var tpl = can.view(GGRC.mustache_path + '/components/mapped-objects/mapped-objects.mustache'); var tag = 'mapped-objects'; /** * Mapped objects view component */ GGRC.Components('mappedObjects', { tag: tag, template: tpl, scope: { isLoading: false, mapping: '@', parentInstance: null, selectedItem: null, mappedItems: [], filter: null, setMappedObjects: function (items) { var filterObj = this.attr('filter'); this.attr('isLoading', false); items = filterObj ? GGRC.Utils.filters.applyTypeFilter(items, filterObj.serialize()) : items; this.attr('mappedItems').replace(items); }, load: function () { this.attr('isLoading', true); this.attr('parentInstance') .get_binding(this.attr('mapping')) .refresh_instances() .then(this.setMappedObjects.bind(this)); } }, init: function () { this.scope.load(); } }); })(window.can, window.GGRC);
Add filtering feature to base Mapped Objects component
Add filtering feature to base Mapped Objects component
JavaScript
apache-2.0
josthkko/ggrc-core,kr41/ggrc-core,AleksNeStu/ggrc-core,edofic/ggrc-core,plamut/ggrc-core,andrei-karalionak/ggrc-core,josthkko/ggrc-core,kr41/ggrc-core,AleksNeStu/ggrc-core,edofic/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,kr41/ggrc-core,josthkko/ggrc-core,selahssea/ggrc-core,AleksNeStu/ggrc-core,j0gurt/ggrc-core,selahssea/ggrc-core,andrei-karalionak/ggrc-core,kr41/ggrc-core,VinnieJohns/ggrc-core,j0gurt/ggrc-core,plamut/ggrc-core,josthkko/ggrc-core,VinnieJohns/ggrc-core,edofic/ggrc-core,selahssea/ggrc-core,edofic/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core,andrei-karalionak/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core
--- +++ @@ -10,7 +10,7 @@ '/components/mapped-objects/mapped-objects.mustache'); var tag = 'mapped-objects'; /** - * Assessment specific mapped objects view component + * Mapped objects view component */ GGRC.Components('mappedObjects', { tag: tag, @@ -19,9 +19,15 @@ isLoading: false, mapping: '@', parentInstance: null, + selectedItem: null, mappedItems: [], + filter: null, setMappedObjects: function (items) { + var filterObj = this.attr('filter'); this.attr('isLoading', false); + items = filterObj ? + GGRC.Utils.filters.applyTypeFilter(items, filterObj.serialize()) : + items; this.attr('mappedItems').replace(items); }, load: function () {
cd432d2fd9ef0c76f9673990f4b2c2f8680a1831
lib/global-admin/addon/security/roles/new/route.js
lib/global-admin/addon/security/roles/new/route.js
import Route from '@ember/routing/route'; import { inject as service } from '@ember/service'; import { get } from '@ember/object'; import { hash } from 'rsvp'; export default Route.extend({ globalStore: service(), model() { const store = get(this, 'globalStore'); var role = store.createRecord({ type: `projectRoleTemplate`, name: '', rules: [ { apiGroups: ['*'], type: 'policyRule', resources: [], verbs: [], } ], }); return hash({ roles: store.find('projectRoleTemplate'), policies: store.find('podSecurityPolicyTemplate'), }).then((res) => { res.role = role; return res; }); }, });
import Route from '@ember/routing/route'; import { inject as service } from '@ember/service'; import { get } from '@ember/object'; import { hash } from 'rsvp'; export default Route.extend({ globalStore: service(), model() { const store = get(this, 'globalStore'); var role = store.createRecord({ type: `projectRoleTemplate`, name: '', rules: [], }); return hash({ roles: store.find('projectRoleTemplate'), policies: store.find('podSecurityPolicyTemplate'), }).then((res) => { res.role = role; return res; }); }, });
Remove the default added resource when add a role
Remove the default added resource when add a role
JavaScript
apache-2.0
rancherio/ui,pengjiang80/ui,vincent99/ui,lvuch/ui,rancherio/ui,westlywright/ui,rancher/ui,vincent99/ui,rancherio/ui,pengjiang80/ui,lvuch/ui,vincent99/ui,lvuch/ui,rancher/ui,westlywright/ui,pengjiang80/ui,westlywright/ui,rancher/ui
--- +++ @@ -12,14 +12,7 @@ var role = store.createRecord({ type: `projectRoleTemplate`, name: '', - rules: [ - { - apiGroups: ['*'], - type: 'policyRule', - resources: [], - verbs: [], - } - ], + rules: [], }); return hash({
08a48f04219f01fa3140a17ce6c905cbca9b54a5
spec/arethusa.core/main_ctrl_spec.js
spec/arethusa.core/main_ctrl_spec.js
"use strict"; describe('MainCtrl', function() { beforeEach(module('arethusa')); it('sets scope values', inject(function($controller, $rootScope) { var scope = $rootScope.$new(); var mystate = { init: function() {}, allLoaded: false }; var notifier = { init: function() {}, success: function() {}, info: function() {}, error: function() {} }; var ctrl = $controller('MainCtrl', {$scope:scope, state:mystate, notifier:notifier, configurator: { configurationFor: function(name) { return { plugins: {}, template: "template"}; } }}); expect(scope.state).toBe(mystate); expect(scope.plugins).toBeUndefined(); expect(scope.template).toBe("template"); })); });
"use strict"; describe('MainCtrl', function() { beforeEach(module('arethusa')); it('sets scope values', inject(function($controller, $rootScope) { var scope = $rootScope.$new(); var state = { init: function() {}, allLoaded: false }; var notifier = { init: function() {}, success: function() {}, info: function() {}, error: function() {} }; var configurator = { configurationFor: function(name) { return { plugins: {}, template: "template"}; } }; var saver = { init: function() {} }; var mainCtrlInits = { $scope: scope, configurator: configurator, state: state, notifier: notifier, saver: saver }; var ctrl = $controller('MainCtrl', mainCtrlInits); expect(scope.state).toBe(state); expect(scope.plugins).toBeUndefined(); expect(scope.template).toBe("template"); })); });
Update and refactor MainCtrl spec
Update and refactor MainCtrl spec Whoops, #197 broke that spec. Used the opportunity to refactor the file a bit.
JavaScript
mit
fbaumgardt/arethusa,fbaumgardt/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa,PonteIneptique/arethusa,Masoumeh/arethusa,latin-language-toolkit/arethusa,PonteIneptique/arethusa,Masoumeh/arethusa,alpheios-project/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa
--- +++ @@ -5,7 +5,7 @@ it('sets scope values', inject(function($controller, $rootScope) { var scope = $rootScope.$new(); - var mystate = { + var state = { init: function() {}, allLoaded: false }; @@ -15,13 +15,24 @@ info: function() {}, error: function() {} }; - var ctrl = $controller('MainCtrl', {$scope:scope, state:mystate, notifier:notifier, configurator: { + var configurator = { configurationFor: function(name) { return { plugins: {}, template: "template"}; } - }}); + }; + var saver = { init: function() {} }; - expect(scope.state).toBe(mystate); + var mainCtrlInits = { + $scope: scope, + configurator: configurator, + state: state, + notifier: notifier, + saver: saver + }; + + var ctrl = $controller('MainCtrl', mainCtrlInits); + + expect(scope.state).toBe(state); expect(scope.plugins).toBeUndefined(); expect(scope.template).toBe("template"); }));
0f53f3742abf00c18e14b1ad4ad2da5369586c03
filebrowser_safe/static/filebrowser/js/FB_FileBrowseField.js
filebrowser_safe/static/filebrowser/js/FB_FileBrowseField.js
function FileSubmit(FilePath, FileURL, ThumbURL, FileType) { // var input_id=window.name.split("___").join("."); var input_id=window.name.replace(/____/g,'-').split("___").join("."); var preview_id = 'image_' + input_id; var link_id = 'link_' + input_id; var help_id = 'help_' + input_id; var clear_id = 'clear_' + input_id; input = opener.document.getElementById(input_id); preview = opener.document.getElementById(preview_id); link = opener.document.getElementById(link_id); help = opener.document.getElementById(help_id); clear = opener.document.getElementById(clear_id); // set new value for input field input.value = FilePath; // enable the clear "button" jQuery(clear).css("display", "inline"); if (ThumbURL && FileType != "") { // selected file is an image and thumbnail is available: // display the preview-image (thumbnail) // link the preview-image to the original image link.setAttribute("href", FileURL); link.setAttribute("target", "_blank"); preview.setAttribute("src", ThumbURL); help.setAttribute("style", "display:inline"); jQuery(help).addClass("mezz-fb-thumbnail"); } else { // hide preview elements link.setAttribute("href", ""); link.setAttribute("target", ""); preview.setAttribute("src", ""); help.setAttribute("style", "display:none"); } this.close(); }
function FileSubmit(FilePath, FileURL, ThumbURL, FileType) { // var input_id=window.name.split("___").join("."); var input_id=window.name.replace(/____/g,'-').split("___").join("."); var preview_id = 'image_' + input_id; var link_id = 'link_' + input_id; var help_id = 'help_' + input_id; var clear_id = 'clear_' + input_id; input = opener.document.getElementById(input_id); preview = opener.document.getElementById(preview_id); link = opener.document.getElementById(link_id); help = opener.document.getElementById(help_id); clear = opener.document.getElementById(clear_id); // set new value for input field input.value = FilePath; // enable the clear "button" jQuery(clear).css("display", "inline"); if (ThumbURL && FileType != "") { // selected file is an image and thumbnail is available: // display the preview-image (thumbnail) // link the preview-image to the original image link.setAttribute("href", FileURL); link.setAttribute("target", "_blank"); link.setAttribute("style", "display:inline"); preview.setAttribute("src", ThumbURL); help.setAttribute("style", "display:inline"); jQuery(help).addClass("mezz-fb-thumbnail"); } else { // hide preview elements link.setAttribute("href", ""); link.setAttribute("target", ""); preview.setAttribute("src", ""); help.setAttribute("style", "display:none"); } this.close(); }
Fix regression in displaying a thumbnail for newly selected images on FileBrowseField.
Fix regression in displaying a thumbnail for newly selected images on FileBrowseField.
JavaScript
bsd-3-clause
ryneeverett/filebrowser-safe,ryneeverett/filebrowser-safe,ryneeverett/filebrowser-safe,fawx/filebrowser-safe,ryneeverett/filebrowser-safe,fawx/filebrowser-safe,fawx/filebrowser-safe
--- +++ @@ -24,6 +24,7 @@ // link the preview-image to the original image link.setAttribute("href", FileURL); link.setAttribute("target", "_blank"); + link.setAttribute("style", "display:inline"); preview.setAttribute("src", ThumbURL); help.setAttribute("style", "display:inline"); jQuery(help).addClass("mezz-fb-thumbnail");
4e4ceb2fbb9eeffdd61b1f1bfc022347d4ae46e8
app/components/appearance-verify.js
app/components/appearance-verify.js
import Component from '@ember/component'; import { inject as service } from '@ember/service'; import { task } from 'ember-concurrency'; export default Component.extend({ store: service(), flashMessages: service(), verifyAppearance: task(function *() { try { yield this.model.verify({ 'by': this.get('currentUser.user.id'), }); this.model.reload(); if (this.get('model.varianceReport') == null) { this.flashMessages.success("Verified!"); } else { this.flashMessages.warning("VARIANCE!"); } } catch(e) { this.flashMessages.error(e); } }).drop(), });
import Component from '@ember/component'; import { inject as service } from '@ember/service'; import { task } from 'ember-concurrency'; export default Component.extend({ store: service(), flashMessages: service(), verifyAppearance: task(function *() { try { yield this.model.verify({ 'by': this.get('currentUser.user.id'), }); this.model.reload(); if (this.get('model.varianceReport') == null) { this.flashMessages.success("Verified!"); } else { this.flashMessages.warning("VARIANCE!"); } } catch(e) { this.flashMessages.danger(e.errors.status); } }).drop(), });
Add transition failure to appearance
Add transition failure to appearance
JavaScript
bsd-2-clause
barberscore/barberscore-web,barberscore/barberscore-web,barberscore/barberscore-web
--- +++ @@ -17,7 +17,7 @@ this.flashMessages.warning("VARIANCE!"); } } catch(e) { - this.flashMessages.error(e); + this.flashMessages.danger(e.errors.status); } }).drop(), });
26ca1acc5437a717ec4f622ffb2fc63bdf090aa9
app/components/live/get_services.js
app/components/live/get_services.js
'use strict'; angular.module('adagios.live') .constant('filterSuffixes', { contains: '__contains', has_fields: '__has_field', startswith: '__startswith', endswith: '__endswith', exists: '__exists', in: '__in', isnot: '__isnot', regex: '__regex' }) .factory('getServices', ['$http', 'filterSuffixes', function ($http, filterSuffixes) { return function (columns, filters, apiName) { var filtersQuery = ''; function createFiltersQuery(filters) { var builtQuery = ''; angular.forEach(filters, function (value, key) { var filterType = filterSuffixes[key]; angular.forEach(value, function (fieldValues, fieldName) { var filter = fieldName + filterType; angular.forEach(fieldValues, function (_value) { var filterQuery = '&' + filter + '=' + _value; builtQuery += filterQuery; }); }); }); return builtQuery; } filtersQuery = createFiltersQuery(filters); return $http.get('/rest/status/json/' + apiName + '/?fields=' + columns + filtersQuery) .error(function () { throw new Error('getServices : GET Request failed'); }); }; }]);
'use strict'; angular.module('adagios.live') .constant('filterSuffixes', { contains: '__contains', has_fields: '__has_field', startswith: '__startswith', endswith: '__endswith', exists: '__exists', in: '__in', isnot: '__isnot', regex: '__regex' }) .factory('getServices', ['$http', 'filterSuffixes', function ($http, filterSuffixes) { return function (columns, filters, apiName, additionnalFields) { var filtersQuery = '', additionnalQuery = ''; function createFiltersQuery(filters) { var builtQuery = ''; angular.forEach(filters, function (value, key) { var filterType = filterSuffixes[key]; angular.forEach(value, function (fieldValues, fieldName) { var filter = fieldName + filterType; angular.forEach(fieldValues, function (_value) { var filterQuery = '&' + filter + '=' + _value; builtQuery += filterQuery; }); }); }); return builtQuery; } function createAdditionnalQuery(additionnalFields) { var query = ''; angular.forEach(additionnalFields, function (value, key) { query += '&' + key + '=' + value; }); return query; } filtersQuery = createFiltersQuery(filters); additionnalQuery = createAdditionnalQuery(additionnalFields); return $http.get('/rest/status/json/' + apiName + '/?fields=' + columns + filtersQuery + additionnalQuery) .error(function () { throw new Error('getServices : GET Request failed'); }); }; }]);
Add additinonalFields support to GetServices
Add additinonalFields support to GetServices
JavaScript
agpl-3.0
openstack/bansho,openstack/bansho,Freddrickk/adagios-frontend,stackforge/bansho,stackforge/bansho,Freddrickk/adagios-frontend,stackforge/bansho,openstack/bansho
--- +++ @@ -14,8 +14,9 @@ .factory('getServices', ['$http', 'filterSuffixes', function ($http, filterSuffixes) { - return function (columns, filters, apiName) { - var filtersQuery = ''; + return function (columns, filters, apiName, additionnalFields) { + var filtersQuery = '', + additionnalQuery = ''; function createFiltersQuery(filters) { var builtQuery = ''; @@ -33,9 +34,19 @@ return builtQuery; } + function createAdditionnalQuery(additionnalFields) { + var query = ''; + angular.forEach(additionnalFields, function (value, key) { + query += '&' + key + '=' + value; + }); + + return query; + } + filtersQuery = createFiltersQuery(filters); + additionnalQuery = createAdditionnalQuery(additionnalFields); - return $http.get('/rest/status/json/' + apiName + '/?fields=' + columns + filtersQuery) + return $http.get('/rest/status/json/' + apiName + '/?fields=' + columns + filtersQuery + additionnalQuery) .error(function () { throw new Error('getServices : GET Request failed'); });
2ac1100d313c1bd80c4230dff605c51e39048009
webpack.config.js
webpack.config.js
const path = require('path'); const webpack = require('webpack'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const config = { entry: { 'bundle': './client/js/index.js' }, output: { path: path.join(__dirname, 'dist'), filename: '[name].js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.scss$/, loader: 'style-loader!css-loader!sass-loader' }, { test: /\.(ttf|eot|woff|jpe?g|svg|png)$/, loader: 'url-loader' } ] }, plugins: [ new CopyWebpackPlugin([ { context: 'public', from: '**/*' } ]) ] }; if (process.env.NODE_ENV === 'production') { config.plugins = config.plugins.concat( new webpack.optimize.UglifyJsPlugin({ compress: { warnings: true } }) ); } else { config.devtool = 'sourcemap'; } module.exports = config;
const path = require('path'); const webpack = require('webpack'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const config = { entry: { 'bundle': './client/js/index.js' }, output: { path: path.join(__dirname, 'dist'), filename: '[name].js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.scss$/, loader: 'style-loader!css-loader!sass-loader' }, { test: /\.(ttf|eot|woff|jpe?g|svg|png)$/, loader: 'url-loader' } ] }, plugins: [ new CopyWebpackPlugin([ { context: 'public', from: '**/*' } ]) ] }; if (process.env.NODE_ENV === 'production') { config.plugins = config.plugins.concat( new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: true } }) ); } else { config.devtool = 'sourcemap'; } module.exports = config;
Use production build of React when deploying
Use production build of React when deploying
JavaScript
mit
flammenmensch/proverbs-and-sayings,flammenmensch/proverbs-and-sayings
--- +++ @@ -36,6 +36,11 @@ if (process.env.NODE_ENV === 'production') { config.plugins = config.plugins.concat( + new webpack.DefinePlugin({ + 'process.env': { + NODE_ENV: JSON.stringify('production') + } + }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: true } })
91a006a3795d177d4ed12b380f43f7227d654de7
webpack.config.js
webpack.config.js
var path = require('path'); var webpack = require('webpack'); module.exports = { entry: [ './examples/index' ], output: { path: path.join(__dirname, 'examples'), filename: 'bundle.js', }, resolveLoader: { modulesDirectories: ['node_modules'] }, resolve: { extensions: ['', '.js', '.cjsx', '.coffee'] }, module: { loaders: [ { test: /\.css$/, loaders: ['style', 'css']}, { test: /\.cjsx$/, loaders: ['coffee', 'cjsx']}, { test: /\.coffee$/, loader: 'coffee' } ] } };
var path = require('path'); var webpack = require('webpack'); module.exports = { entry: [ './examples/index' ], output: { path: path.join(__dirname, 'examples'), filename: 'bundle.js', }, resolveLoader: { modulesDirectories: ['node_modules'] }, resolve: { extensions: ['', '.js', '.cjsx', '.coffee'] }, plugins: [ new webpack.DefinePlugin({'process.env.NODE_ENV': '"production"'}) ], module: { loaders: [ { test: /\.css$/, loaders: ['style', 'css']}, { test: /\.cjsx$/, loaders: ['coffee', 'cjsx']}, { test: /\.coffee$/, loader: 'coffee' } ] } };
Build in production mode so React includes less
Build in production mode so React includes less
JavaScript
mit
idolize/react-spinkit,KyleAMathews/react-spinkit,pieter-lazzaro/react-spinkit
--- +++ @@ -16,6 +16,9 @@ resolve: { extensions: ['', '.js', '.cjsx', '.coffee'] }, + plugins: [ + new webpack.DefinePlugin({'process.env.NODE_ENV': '"production"'}) + ], module: { loaders: [ { test: /\.css$/, loaders: ['style', 'css']},
517f1514da2ee5ab1037badc574e1975ec386959
Test/AudioEngineTest.js
Test/AudioEngineTest.js
setTimeout( function() { var util = require( "util" ); process.on('uncaughtException', function (err) { console.error(err); console.log("Node NOT Exiting..."); }); var audioEngineImpl = require( "../Debug/NodeCoreAudio" ); console.log( audioEngineImpl ); var audioEngine = audioEngineImpl.createAudioEngine( function(uSampleFrames, inputBuffer, outputBuffer) { console.log( "aw shit, we got some samples" ); }); // Make sure the audio engine is still active if( audioEngine.isActive() ) console.log( "active" ); else console.log( "not active" ); // Declare our processing function function processAudio( numSamples, incomingSamples ) { for( var iSample = 0; iSample < numSamples; ++iSample ) { incomingSamples[iSample] = iSample/numSamples; } return incomingSamples; } // Start polling the audio engine for data every 2 milliseconds setInterval( function() { audioEngine.processIfNewData( processAudio ); }, 2 ); }, 15000);
setTimeout( function() { var util = require( "util" ); process.on('uncaughtException', function (err) { console.error(err); console.log("Node NOT Exiting..."); }); var audioEngineImpl = require( "../Debug/NodeCoreAudio" ); console.log( audioEngineImpl ); var audioEngine = audioEngineImpl.createAudioEngine( function(uSampleFrames, inputBuffer, outputBuffer) { console.log( "aw shit, we got some samples" ); }); // Make sure the audio engine is still active if( audioEngine.isActive() ) console.log( "active" ); else console.log( "not active" ); // Declare our processing function function processAudio( numSamples, incomingSamples ) { for( var iSample = 0; iSample < numSamples; ++iSample ) { incomingSamples[iSample] = iSample/numSamples; } return incomingSamples; } // Start polling the audio engine for data as fast as we can setInterval( function() { audioEngine.processIfNewData( processAudio ); }, 0 ); }, 0);
Check for new audio data as fast as possible from javascript (may eat CPU)
Check for new audio data as fast as possible from javascript (may eat CPU)
JavaScript
mit
GeorgeStrakhov/node-core-audio,ZECTBynmo/node-core-audio,ZECTBynmo/node-core-audio,ZECTBynmo/node-core-audio,GeorgeStrakhov/node-core-audio,ZECTBynmo/node-core-audio,GeorgeStrakhov/node-core-audio,GeorgeStrakhov/node-core-audio
--- +++ @@ -28,9 +28,9 @@ return incomingSamples; } - // Start polling the audio engine for data every 2 milliseconds + // Start polling the audio engine for data as fast as we can setInterval( function() { audioEngine.processIfNewData( processAudio ); - }, 2 ); + }, 0 ); -}, 15000); +}, 0);
3839cf5bd8fa7b54ec3f06b2c27e97fbe2ccd0ec
src/components/HueResult.js
src/components/HueResult.js
import React, {Component} from 'react'; import Chart from './Chart' class HueResult extends Component { constructor(props) { super(props); } render(){ return ( <div> <h1>Results</h1> <Chart {...this.props}/> </div> ); } } export default HueResult;
import React, {Component} from 'react'; import Chart from './Chart' class HueResult extends Component { constructor(props) { super(props); } render(){ return ( <div className="hue-results"> <h1>Results</h1> <Chart {...this.props}/> <div id="hue-interpretation"> <h2>Results interpretation:</h2> Bla bla bla, blu blu blu, bli bli bli... </div> <div id="hue-about"> <h2>About this test:</h2> This test measures your ability to make color discrimination (color aptitude), rather than detecting color blindness. Color discrimination is a trainable skill that is also affected be external effects such as neurological conditions or aging. </div> </div> ); } } export default HueResult;
Add copy to hue restults page.
Add copy to hue restults page.
JavaScript
mit
FilmonFeMe/coloreyes,FilmonFeMe/coloreyes
--- +++ @@ -8,10 +8,19 @@ render(){ return ( - <div> - <h1>Results</h1> - <Chart {...this.props}/> - </div> + <div className="hue-results"> + <h1>Results</h1> + <Chart {...this.props}/> + <div id="hue-interpretation"> + <h2>Results interpretation:</h2> + Bla bla bla, blu blu blu, bli bli bli... + </div> + <div id="hue-about"> + <h2>About this test:</h2> + This test measures your ability to make color discrimination (color aptitude), rather than detecting color blindness. + Color discrimination is a trainable skill that is also affected be external effects such as neurological conditions or aging. + </div> + </div> ); } }
e905ad177f78ad40a7b8472c5e852ffc2de07471
aura-components/src/main/components/ui/outputText/outputTextRenderer.js
aura-components/src/main/components/ui/outputText/outputTextRenderer.js
/* * Copyright (C) 2013 salesforce.com, inc. * * 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. */ { render: function(cmp, helper) { var value = cmp.get('v.value'); var ret = this.superRender(); var span = cmp.find('span').getElement(); helper.appendTextElements(value, span); return ret; }, rerender: function(cmp, helper) { var value = cmp.getValue('v.value'); if (value.isDirty()) { var span = cmp.find('span').getElement(); helper.removeChildren(span); helper.appendTextElements(value.getValue(), span); } this.superRerender(); } }
/* * Copyright (C) 2013 salesforce.com, inc. * * 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. */ { render: function(cmp, helper) { var value = cmp.get('v.value'); var ret = this.superRender(); var span = cmp.find('span').getElement(); helper.appendTextElements(value, span); return ret; }, rerender: function(cmp, helper) { var value = cmp.getValue('v.value'); var dirty = true; var unwrapped = ""; // // Very careful with value here, if it is unset, we don't want // to fail in an ugly way. // if (value) { dirty = value.isDirty(); if (dirty) { unwrapped = value.getValue(); } } else { $A.warning("Component has v.value unset: "+cmp.getGlobalId()); } if (dirty) { var span = cmp.find('span').getElement(); helper.removeChildren(span); helper.appendTextElements(unwrapped, span); } this.superRerender(); } }
Make output text not die on null value.
Make output text not die on null value. @bug W-@ @rev eric.anderson@
JavaScript
apache-2.0
badlogicmanpreet/aura,madmax983/aura,SalesforceSFDC/aura,TribeMedia/aura,lcnbala/aura,badlogicmanpreet/aura,SalesforceSFDC/aura,madmax983/aura,navyliu/aura,igor-sfdc/aura,DebalinaDey/AuraDevelopDeb,forcedotcom/aura,SalesforceSFDC/aura,madmax983/aura,navyliu/aura,igor-sfdc/aura,TribeMedia/aura,lhong375/aura,igor-sfdc/aura,forcedotcom/aura,SalesforceSFDC/aura,SalesforceSFDC/aura,lhong375/aura,badlogicmanpreet/aura,badlogicmanpreet/aura,DebalinaDey/AuraDevelopDeb,DebalinaDey/AuraDevelopDeb,navyliu/aura,navyliu/aura,lhong375/aura,lcnbala/aura,navyliu/aura,lcnbala/aura,DebalinaDey/AuraDevelopDeb,badlogicmanpreet/aura,TribeMedia/aura,igor-sfdc/aura,madmax983/aura,TribeMedia/aura,forcedotcom/aura,lcnbala/aura,igor-sfdc/aura,DebalinaDey/AuraDevelopDeb,navyliu/aura,TribeMedia/aura,forcedotcom/aura,madmax983/aura,TribeMedia/aura,SalesforceSFDC/aura,DebalinaDey/AuraDevelopDeb,lcnbala/aura,lhong375/aura,madmax983/aura,forcedotcom/aura,lcnbala/aura,badlogicmanpreet/aura
--- +++ @@ -15,24 +15,39 @@ */ { - render: function(cmp, helper) { - var value = cmp.get('v.value'); - var ret = this.superRender(); - var span = cmp.find('span').getElement(); - - helper.appendTextElements(value, span); - - return ret; - }, - - rerender: function(cmp, helper) { - var value = cmp.getValue('v.value'); - if (value.isDirty()) { - var span = cmp.find('span').getElement(); - helper.removeChildren(span); - helper.appendTextElements(value.getValue(), span); - } - this.superRerender(); - } + render: function(cmp, helper) { + var value = cmp.get('v.value'); + var ret = this.superRender(); + var span = cmp.find('span').getElement(); + + helper.appendTextElements(value, span); + + return ret; + }, + + rerender: function(cmp, helper) { + var value = cmp.getValue('v.value'); + var dirty = true; + var unwrapped = ""; + + // + // Very careful with value here, if it is unset, we don't want + // to fail in an ugly way. + // + if (value) { + dirty = value.isDirty(); + if (dirty) { + unwrapped = value.getValue(); + } + } else { + $A.warning("Component has v.value unset: "+cmp.getGlobalId()); + } + if (dirty) { + var span = cmp.find('span').getElement(); + helper.removeChildren(span); + helper.appendTextElements(unwrapped, span); + } + this.superRerender(); + } }
0b03bc33b13dcf1a9deb4f4a7435ec77f3308371
app/components/bd-arrival.js
app/components/bd-arrival.js
import Ember from 'ember'; import moment from 'moment'; import stringToHue from 'bus-detective/utils/string-to-hue'; var inject = Ember.inject; export default Ember.Component.extend({ tagName: 'li', clock: inject.service(), attributeBindings: ['style'], classNames: ['timeline__event'], classNameBindings: ['isPast:arrival--past'], timeFromNow: Ember.computed('clock.time', function() { return moment(this.get('arrival.time')).fromNow('mm'); }), arrivalTime: Ember.computed('clock.time', function () { return moment(this.get('arrival.time')).format('h:mm'); }), isPast: Ember.computed('clock.time', function() { return new Date(this.get('arrival.time')) < new Date(); }), });
import Ember from 'ember'; import moment from 'moment'; import stringToHue from 'bus-detective/utils/string-to-hue'; var inject = Ember.inject; export default Ember.Component.extend({ tagName: 'li', clock: inject.service(), attributeBindings: ['style'], classNames: ['timeline__event'], classNameBindings: ['isPast:event--past'], timeFromNow: Ember.computed('clock.time', function() { return moment(this.get('arrival.time')).fromNow(); }), arrivalTime: Ember.computed('clock.time', function () { return moment(this.get('arrival.time')).format('h:mm'); }), isPast: Ember.computed('clock.time', function() { return new Date(this.get('arrival.time')) < new Date(); }), });
Apply ghosted styles to past arrivals
Apply ghosted styles to past arrivals
JavaScript
mit
bus-detective/web-client,bus-detective/web-client
--- +++ @@ -8,10 +8,10 @@ clock: inject.service(), attributeBindings: ['style'], classNames: ['timeline__event'], - classNameBindings: ['isPast:arrival--past'], + classNameBindings: ['isPast:event--past'], timeFromNow: Ember.computed('clock.time', function() { - return moment(this.get('arrival.time')).fromNow('mm'); + return moment(this.get('arrival.time')).fromNow(); }), arrivalTime: Ember.computed('clock.time', function () {
658812bb2ec2a3423e7c3cb0ff676e1e7b5d1f35
main.js
main.js
require( { paths: { assert: 'src/assert', bunit: 'src/bunit' } }, ['bunit', 'tests/tests'], function(bunit, tests) { require.ready(function() { var r = bunit.runner(); r.defaultUI(); r.run(); }); } );
require( { paths: { assert: 'src/assert', bunit: 'src/bunit' }, urlArgs: "bust=" + (new Date()).getTime() }, ['bunit', 'tests/tests'], function(bunit, tests) { require.ready(function() { var r = bunit.runner(); r.defaultUI(); r.run(); }); } );
Set up cache buster to RequireJS
Set up cache buster to RequireJS
JavaScript
mit
bebraw/bunit.js
--- +++ @@ -3,7 +3,8 @@ paths: { assert: 'src/assert', bunit: 'src/bunit' - } + }, + urlArgs: "bust=" + (new Date()).getTime() }, ['bunit', 'tests/tests'], function(bunit, tests) {
9dfd7d6b5cf4f56b3d2aac4e6f97ff1c2986ee6e
main.js
main.js
var googleapis = require('googleapis'); /* Example of using google apis module to discover the URL shortener module, and shorten a url @param params.url : the URL to shorten */ exports.googleapis = function(params, cb) { googleapis.withOpts({ cache: { path: 'public' }}).discover('urlshortener', 'v1').execute(function(err, client) { console.log('executing'); console.log('dirname is ' + __dirname); var req1 = client.urlshortener.url.insert({ longUrl: params.url || 'https://www.feedhenry.com' }); console.log(req1); req1.withApiKey( << place google API key here >> ); req1.execute(function(err, response) { console.log(err); console.log('Short URL is', response.id); return cb(null, response); }); }); };
var googleapis = require('googleapis'); /* Example of using google apis module to discover the URL shortener module, and shorten a url @param params.url : the URL to shorten */ exports.googleapis = function(params, cb) { // Note that, a folder named 'public' must be present in the same folder for the cache: { path: 'public' } option to work. googleapis.withOpts({ cache: { path: 'public' }}).discover('urlshortener', 'v1').execute(function(err, client) { console.log('executing'); console.log('dirname is ' + __dirname); var req1 = client.urlshortener.url.insert({ longUrl: params.url || 'https://www.feedhenry.com' }); console.log(req1); req1.withApiKey( << place google API key here >> ); req1.execute(function(err, response) { console.log(err); console.log('Short URL is', response.id); return cb(null, response); }); }); };
Add comment before googleapis.discover call
Add comment before googleapis.discover call
JavaScript
mit
RHMAP-Support/URL_shortener,RHMAP-Support/URL_shortener
--- +++ @@ -6,6 +6,7 @@ @param params.url : the URL to shorten */ exports.googleapis = function(params, cb) { + // Note that, a folder named 'public' must be present in the same folder for the cache: { path: 'public' } option to work. googleapis.withOpts({ cache: { path: 'public' }}).discover('urlshortener', 'v1').execute(function(err, client) { console.log('executing'); console.log('dirname is ' + __dirname);
24310a75287aea1947f22c152d7966433d4d0bb3
actions/vmInfo.js
actions/vmInfo.js
const execute = require('../lib/executeCommand'); module.exports = (vm) => { return new Promise((resolve, reject) => { execute(['showvminfo', '"' + vm + '"']).then(stdout => { let info = []; let regex = /^(.*?):\s+(.*)$/gim; let match; while (match = regex.exec(stdout)) { if (match.index === regex.lastIndex) { regex.lastIndex++; } // Trim let varname = match[1].trim().toLowerCase().replace(/ /g, '_'); let value = match[2].trim(); info[varname] = value; } resolve(info); }).catch(reject); }); };
const execute = require('../lib/executeCommand'); module.exports = (vm) => { return new Promise((resolve, reject) => { execute(['showvminfo', '"' + vm + '"']).then(stdout => { let info = {}; let regex = /^(.*?):\s+(.*)$/gim; let match; while (match = regex.exec(stdout)) { if (match.index === regex.lastIndex) { regex.lastIndex++; } // Trim let varname = match[1].trim().toLowerCase().replace(/ /g, '_'); let value = match[2].trim(); info[varname] = value; } resolve(info); }).catch(reject); }); };
Use Object and not array.
Use Object and not array. Instead of using `info = []`. To which if we try to assign properties, doesn't seem to work well. Hence, try to use object representation, which allows us to use `info.name` or assign it another object.
JavaScript
mit
VBoxNode/NodeVBox
--- +++ @@ -7,7 +7,7 @@ execute(['showvminfo', '"' + vm + '"']).then(stdout => { - let info = []; + let info = {}; let regex = /^(.*?):\s+(.*)$/gim; let match;
32db1c929c2a7bf2bd78acf2553cd74a30fde81e
lib/taskManager.js
lib/taskManager.js
var schedule = require('node-schedule'); var syncTask = require('./tasks/sync'); // Update entries every 30 minutes schedule.scheduleJob('0,30 * * * *', syncTask);
var schedule = require('node-schedule'), syncTask = require('./tasks/sync'); // Tasks to run on startup syncTask(); // Update entries every 30 minutes and boot schedule.scheduleJob('0,30 * * * *', syncTask);
Add sync to start up tasks
Add sync to start up tasks
JavaScript
mit
web-audio-components/web-audio-components-service
--- +++ @@ -1,5 +1,9 @@ -var schedule = require('node-schedule'); -var syncTask = require('./tasks/sync'); +var + schedule = require('node-schedule'), + syncTask = require('./tasks/sync'); -// Update entries every 30 minutes +// Tasks to run on startup +syncTask(); + +// Update entries every 30 minutes and boot schedule.scheduleJob('0,30 * * * *', syncTask);
18fe24f19444d24f1b453e6fcd908eddcff4165a
rollup.binary.config.js
rollup.binary.config.js
export default { input: 'bin/capnpc-es.js', output: { file: 'dist/bin/capnpc-es.js', format: 'cjs' } };
export default { input: 'bin/capnpc-es.js', output: { file: 'dist/bin/capnpc-es.js', format: 'cjs', banner: '#! /usr/bin/env node\n' } };
Add shebang to the binary file
Add shebang to the binary file
JavaScript
mit
mattyclarkson/capnp-es
--- +++ @@ -2,6 +2,7 @@ input: 'bin/capnpc-es.js', output: { file: 'dist/bin/capnpc-es.js', - format: 'cjs' + format: 'cjs', + banner: '#! /usr/bin/env node\n' } };
867325b8ffd256a481983966da69edfc0981ef6c
addon/components/bs4/bs-navbar.js
addon/components/bs4/bs-navbar.js
import Ember from 'ember'; import Navbar from 'ember-bootstrap/components/base/bs-navbar'; export default Navbar.extend({ classNameBindings: ['breakpointClass', 'backgroundClass'], /** * Defines the responsive toggle breakpoint size. Options are the standard * two character Bootstrap size abbreviations. Used to set the `navbar-toggleable-*` * class. * * @property toggleBreakpoint * @type String * @default 'md' * @public */ toggleBreakpoint: 'md', /** * Sets the background color for the navbar. Can be any color * in the set that composes the `bg-*` classes. * * @property backgroundColor * @type String * @default 'faded' * @public */ backgroundColor: 'faded', breakpointClass: Ember.computed('toggleBreakpoint', function() { let toggleBreakpoint = this.get('toggleBreakpoint'); return `navbar-toggleable-${toggleBreakpoint}`; }), backgroundClass: Ember.computed('backgroundColor', function() { let backgroundColor = this.get('backgroundColor'); return `bg-${backgroundColor}`; }) });
import Ember from 'ember'; import Navbar from 'ember-bootstrap/components/base/bs-navbar'; export default Navbar.extend({ classNameBindings: ['breakpointClass', 'backgroundClass'], type: 'light', /** * Defines the responsive toggle breakpoint size. Options are the standard * two character Bootstrap size abbreviations. Used to set the `navbar-toggleable-*` * class. * * @property toggleBreakpoint * @type String * @default 'md' * @public */ toggleBreakpoint: 'md', /** * Sets the background color for the navbar. Can be any color * in the set that composes the `bg-*` classes. * * @property backgroundColor * @type String * @default 'faded' * @public */ backgroundColor: 'faded', breakpointClass: Ember.computed('toggleBreakpoint', function() { let toggleBreakpoint = this.get('toggleBreakpoint'); return `navbar-toggleable-${toggleBreakpoint}`; }), backgroundClass: Ember.computed('backgroundColor', function() { let backgroundColor = this.get('backgroundColor'); return `bg-${backgroundColor}`; }) });
Make `navbar-light` the default type class.
Make `navbar-light` the default type class.
JavaScript
mit
kaliber5/ember-bootstrap,kaliber5/ember-bootstrap,jelhan/ember-bootstrap,jelhan/ember-bootstrap
--- +++ @@ -3,6 +3,8 @@ export default Navbar.extend({ classNameBindings: ['breakpointClass', 'backgroundClass'], + + type: 'light', /** * Defines the responsive toggle breakpoint size. Options are the standard
a2eabdfe43c47342201466d0ded6392964bca4cb
src/browser/extension/devtools/index.js
src/browser/extension/devtools/index.js
chrome.devtools.panels.create( 'Redux', null, 'devpanel.html', function(panel) {} );
chrome.devtools.panels.create( 'Redux', 'img/scalable.png', 'devpanel.html', function(panel) {} );
Add the icon to the devtools panel
Add the icon to the devtools panel Related to #95.
JavaScript
mit
zalmoxisus/redux-devtools-extension,zalmoxisus/redux-devtools-extension
--- +++ @@ -1,3 +1,3 @@ chrome.devtools.panels.create( - 'Redux', null, 'devpanel.html', function(panel) {} + 'Redux', 'img/scalable.png', 'devpanel.html', function(panel) {} );
5e5313d8b1659f9fbdee5ff3cf6198c696928005
atom/common/api/lib/shell.js
atom/common/api/lib/shell.js
'use strict'; const bindings = process.atomBinding('shell'); exports.beep = bindings.beep; exports.moveItemToTrash = bindings.moveItemToTrash; exports.openItem = bindings.openItem; exports.showItemInFolder = bindings.showItemInFolder; exports.openExternal = (url, options) => { var activate = true; if (options != null && options.activate != null) { activate = !!options.activate; } bindings._openExternal(url, activate); }
'use strict'; const bindings = process.atomBinding('shell'); exports.beep = bindings.beep; exports.moveItemToTrash = bindings.moveItemToTrash; exports.openItem = bindings.openItem; exports.showItemInFolder = bindings.showItemInFolder; exports.openExternal = (url, options) => { var activate = true; if (options != null && options.activate != null) { activate = !!options.activate; } return bindings._openExternal(url, activate); }
Return value from bindings method
Return value from bindings method
JavaScript
mit
wan-qy/electron,kokdemo/electron,aliib/electron,miniak/electron,minggo/electron,MaxWhere/electron,stevekinney/electron,brave/muon,posix4e/electron,minggo/electron,rajatsingla28/electron,voidbridge/electron,renaesop/electron,MaxWhere/electron,pombredanne/electron,kcrt/electron,wan-qy/electron,Floato/electron,thompsonemerson/electron,Floato/electron,kokdemo/electron,felixrieseberg/electron,brenca/electron,stevekinney/electron,simongregory/electron,twolfson/electron,leethomas/electron,posix4e/electron,tonyganch/electron,preco21/electron,minggo/electron,tonyganch/electron,aichingm/electron,miniak/electron,biblerule/UMCTelnetHub,voidbridge/electron,simongregory/electron,Gerhut/electron,the-ress/electron,MaxWhere/electron,thompsonemerson/electron,tinydew4/electron,thomsonreuters/electron,gerhardberger/electron,twolfson/electron,deed02392/electron,gerhardberger/electron,jhen0409/electron,leethomas/electron,stevekinney/electron,biblerule/UMCTelnetHub,brave/electron,leethomas/electron,minggo/electron,bpasero/electron,kcrt/electron,pombredanne/electron,seanchas116/electron,noikiy/electron,miniak/electron,rreimann/electron,Floato/electron,noikiy/electron,joaomoreno/atom-shell,seanchas116/electron,brave/electron,kcrt/electron,deed02392/electron,electron/electron,thomsonreuters/electron,Floato/electron,voidbridge/electron,jhen0409/electron,thompsonemerson/electron,rreimann/electron,voidbridge/electron,minggo/electron,tonyganch/electron,the-ress/electron,thomsonreuters/electron,rreimann/electron,brave/electron,jhen0409/electron,preco21/electron,posix4e/electron,posix4e/electron,felixrieseberg/electron,the-ress/electron,jhen0409/electron,noikiy/electron,tinydew4/electron,brave/muon,voidbridge/electron,kokdemo/electron,twolfson/electron,stevekinney/electron,posix4e/electron,bbondy/electron,jhen0409/electron,the-ress/electron,preco21/electron,wan-qy/electron,miniak/electron,seanchas116/electron,miniak/electron,preco21/electron,felixrieseberg/electron,thompsonemerson/electron,electron/electron,leethomas/electron,Gerhut/electron,joaomoreno/atom-shell,minggo/electron,shiftkey/electron,seanchas116/electron,tinydew4/electron,brenca/electron,rajatsingla28/electron,rajatsingla28/electron,biblerule/UMCTelnetHub,electron/electron,bbondy/electron,dongjoon-hyun/electron,bbondy/electron,bpasero/electron,thompsonemerson/electron,gabriel/electron,bpasero/electron,noikiy/electron,seanchas116/electron,preco21/electron,pombredanne/electron,gerhardberger/electron,electron/electron,brave/muon,simongregory/electron,brave/electron,twolfson/electron,Floato/electron,pombredanne/electron,aichingm/electron,tonyganch/electron,gabriel/electron,simongregory/electron,Gerhut/electron,rreimann/electron,aliib/electron,aichingm/electron,aliib/electron,bbondy/electron,brenca/electron,renaesop/electron,thomsonreuters/electron,tinydew4/electron,kcrt/electron,joaomoreno/atom-shell,leethomas/electron,rreimann/electron,dongjoon-hyun/electron,bbondy/electron,kokdemo/electron,deed02392/electron,kcrt/electron,felixrieseberg/electron,bpasero/electron,rajatsingla28/electron,shiftkey/electron,tinydew4/electron,aliib/electron,aichingm/electron,wan-qy/electron,kcrt/electron,posix4e/electron,felixrieseberg/electron,gerhardberger/electron,brave/electron,brenca/electron,tinydew4/electron,thompsonemerson/electron,gabriel/electron,seanchas116/electron,dongjoon-hyun/electron,twolfson/electron,renaesop/electron,renaesop/electron,simongregory/electron,Gerhut/electron,rajatsingla28/electron,rreimann/electron,biblerule/UMCTelnetHub,brenca/electron,MaxWhere/electron,electron/electron,brave/muon,renaesop/electron,Gerhut/electron,thomsonreuters/electron,kokdemo/electron,brave/muon,deed02392/electron,brave/electron,biblerule/UMCTelnetHub,pombredanne/electron,noikiy/electron,miniak/electron,the-ress/electron,the-ress/electron,brenca/electron,electron/electron,gerhardberger/electron,tonyganch/electron,shiftkey/electron,simongregory/electron,bpasero/electron,gerhardberger/electron,Gerhut/electron,bbondy/electron,felixrieseberg/electron,gerhardberger/electron,gabriel/electron,the-ress/electron,shiftkey/electron,biblerule/UMCTelnetHub,thomsonreuters/electron,brave/muon,bpasero/electron,MaxWhere/electron,pombredanne/electron,gabriel/electron,Floato/electron,aliib/electron,dongjoon-hyun/electron,joaomoreno/atom-shell,aichingm/electron,shiftkey/electron,leethomas/electron,rajatsingla28/electron,stevekinney/electron,voidbridge/electron,preco21/electron,joaomoreno/atom-shell,wan-qy/electron,renaesop/electron,MaxWhere/electron,gabriel/electron,shiftkey/electron,twolfson/electron,wan-qy/electron,joaomoreno/atom-shell,jhen0409/electron,kokdemo/electron,deed02392/electron,aichingm/electron,dongjoon-hyun/electron,aliib/electron,stevekinney/electron,deed02392/electron,tonyganch/electron,noikiy/electron,dongjoon-hyun/electron,electron/electron,bpasero/electron
--- +++ @@ -13,5 +13,5 @@ activate = !!options.activate; } - bindings._openExternal(url, activate); + return bindings._openExternal(url, activate); }
4197b869b65dba800fbf16c5e96088735a6c4c35
lib/factory_boy.js
lib/factory_boy.js
FactoryBoy = {}; FactoryBoy._factories = []; Factory = function (name, collection, attributes) { this.name = name; this.collection = collection; this.attributes = attributes; }; FactoryBoy.define = function (name, collection, attributes) { var factory = new Factory(name, collection, attributes); for (var i = 0; i < this._factories.length; i++) { if (this._factories[i].name === name) { throw new Error('A factory named ' + name + ' already exists'); } } FactoryBoy._factories.push(factory); }; FactoryBoy._getFactory = function (name) { var factory = _.findWhere(FactoryBoy._factories, {name: name}); if (! factory) { throw new Error('Could not find the factory by that name'); } return factory; }; FactoryBoy.create = function (name, newAttr) { var factory = this._getFactory(name); var collection = factory.collection; // Allow to overwrite the attribute definitions var attr = _.merge({}, factory.attributes, newAttr); var docId = collection.insert(attr); var doc = collection.findOne(docId); return doc; }; FactoryBoy.build = function (name, newAttr) { var factory = this._getFactory(name); var doc = _.merge({}, factory.attributes, newAttr); return doc; };
FactoryBoy = {}; FactoryBoy._factories = []; Factory = function (name, collection, attributes) { this.name = name; this.collection = collection; this.attributes = attributes; }; FactoryBoy.define = function (name, collection, attributes) { var factory = new Factory(name, collection, attributes); for (var i = 0; i < this._factories.length; i++) { if (this._factories[i].name === name) { throw new Error('A factory named ' + name + ' already exists'); } } FactoryBoy._factories.push(factory); }; FactoryBoy._getFactory = function (name) { var factory = _.findWhere(FactoryBoy._factories, {name: name}); if (! factory) { throw new Error('Could not find the factory named ' + name); } return factory; }; FactoryBoy.create = function (name, newAttr) { var factory = this._getFactory(name); var collection = factory.collection; // Allow to overwrite the attribute definitions var attr = _.merge({}, factory.attributes, newAttr); var docId = collection.insert(attr); var doc = collection.findOne(docId); return doc; }; FactoryBoy.build = function (name, newAttr) { var factory = this._getFactory(name); var doc = _.merge({}, factory.attributes, newAttr); return doc; };
Make error message more helpful by providing name
Make error message more helpful by providing name
JavaScript
mit
sungwoncho/factory-boy
--- +++ @@ -23,7 +23,7 @@ var factory = _.findWhere(FactoryBoy._factories, {name: name}); if (! factory) { - throw new Error('Could not find the factory by that name'); + throw new Error('Could not find the factory named ' + name); } return factory;
35ce9b283e9e19bc752a661ca608d5a3dacc292d
src/js/showcase-specials.js
src/js/showcase-specials.js
/** * * * Shows: special features for models * Requires: **/ showcase.specials = {} showcase.specials.inlinespace = 'inlinespace__' showcase.specials.onLoaded = function () { var skin_shape = $('x3d Shape#'+showcase.specials.inlinespace+'headskin_1'); if(skin_shape.length) { $('#tool-list').append($('<li class="navbar-li"/>').append($('<input id="skin-fade-slider"/>')).append($('<b>Fade skin</b>').css('margin', '15px'))) $('#skin-fade-slider').slider({ min: 0 ,max: 100 ,step: 1 ,value: 100 }) .on('slide', function () { var val = $('#skin-fade-slider').slider('getValue') if(val == 100) { showcase.highlighter.setMaterial(skin_shape, $('')); } else { showcase.highlighter.setMaterial(skin_shape, $('<Material/>').attr('transparency', (100-val)/100)); } }) } }; showcase.addEventListener('load', showcase.specials.onLoaded); $(document).ready( function () { });
/** * * * Shows: special features for models * Requires: **/ showcase.specials = {} showcase.specials.inlinespace = 'inlinespace__' showcase.specials.onLoaded = function () { var skin_shape = $('x3d Shape#'+showcase.specials.inlinespace+'headskin_1'); if(skin_shape.length) { $('#tool-list').append($('<li class="navbar-li"/>').append($('<input id="skin-fade-slider"/>')).append($('<b>Fade skin</b>').css('margin', '15px'))) $('#skin-fade-slider').slider({ min: 0 ,max: 100 ,step: 1 ,value: 100 }) .on('slide', function () { var val = $('#skin-fade-slider').slider('getValue') if(val == 100) { showcase.highlighter.setMaterial(skin_shape, $('')); } else { showcase.highlighter.setMaterial(skin_shape, $('<Material/>').attr('transparency', (100-val)/100)); } }) } // reverse material-deletion from highlighting var no_texture_shape = $('x3d Shape#'+showcase.specials.inlinespace+'no_texture') if(no_texture_shape.length) { no_texture_shape.first().prepend('<Appearance><Material></Material></Appearance>') } }; showcase.addEventListener('load', showcase.specials.onLoaded);
Test for a model without texture
Test for a model without texture
JavaScript
apache-2.0
rwth-acis/Anatomy2.0,rwth-acis/Anatomy2.0,rwth-acis/Anatomy2.0,rwth-acis/Anatomy2.0
--- +++ @@ -18,7 +18,7 @@ ,step: 1 ,value: 100 }) - .on('slide', function () { + .on('slide', function () { var val = $('#skin-fade-slider').slider('getValue') if(val == 100) { showcase.highlighter.setMaterial(skin_shape, $('')); @@ -27,10 +27,12 @@ } }) } + + // reverse material-deletion from highlighting + var no_texture_shape = $('x3d Shape#'+showcase.specials.inlinespace+'no_texture') + if(no_texture_shape.length) { + no_texture_shape.first().prepend('<Appearance><Material></Material></Appearance>') + } }; showcase.addEventListener('load', showcase.specials.onLoaded); - -$(document).ready( function () { -}); -
cb8176a827b25f7e148606da45a62a312a1018a1
libs/model/user.js
libs/model/user.js
var mongoose = require('mongoose'), crypto = require('crypto'), Schema = mongoose.Schema, User = new Schema({ username: { type: String, unique: true, required: true }, hashedPassword: { type: String, required: true }, salt: { type: String, required: true }, created: { type: Date, default: Date.now } }); User.methods.encryptPassword = function(password) { return crypto.createHmac('sha1', this.salt).update(password).digest('hex'); //more secure - return crypto.pbkdf2Sync(password, this.salt, 10000, 512).toString('base64').replace(/\//g,'_').replace(/\+/g,'-'); }; User.virtual('userId') .get(function () { return this.id; }); User.virtual('password') .set(function(password) { this._plainPassword = password; this.salt = crypto.randomBytes(32).toString('hex'); //more secure - this.salt = crypto.randomBytes(128).toString('hex'); this.hashedPassword = this.encryptPassword(password); }) .get(function() { return this._plainPassword; }); User.methods.checkPassword = function(password) { return this.encryptPassword(password) === this.hashedPassword; }; module.exports = mongoose.model('User', User);
var mongoose = require('mongoose'), crypto = require('crypto'), Schema = mongoose.Schema, User = new Schema({ username: { type: String, unique: true, required: true }, hashedPassword: { type: String, required: true }, salt: { type: String, required: true }, created: { type: Date, default: Date.now } }); User.methods.encryptPassword = function(password) { return crypto.createHmac('sha1', this.salt).update(password).digest('hex'); //more secure - return crypto.pbkdf2Sync(password, this.salt, 10000, 512).toString('hex'); }; User.virtual('userId') .get(function () { return this.id; }); User.virtual('password') .set(function(password) { this._plainPassword = password; this.salt = crypto.randomBytes(32).toString('hex'); //more secure - this.salt = crypto.randomBytes(128).toString('hex'); this.hashedPassword = this.encryptPassword(password); }) .get(function() { return this._plainPassword; }); User.methods.checkPassword = function(password) { return this.encryptPassword(password) === this.hashedPassword; }; module.exports = mongoose.model('User', User);
Change secure hash example to output hex
Change secure hash example to output hex
JavaScript
mit
MichalTuleja/jdl-backend,ealeksandrov/NodeAPI
--- +++ @@ -25,7 +25,7 @@ User.methods.encryptPassword = function(password) { return crypto.createHmac('sha1', this.salt).update(password).digest('hex'); - //more secure - return crypto.pbkdf2Sync(password, this.salt, 10000, 512).toString('base64').replace(/\//g,'_').replace(/\+/g,'-'); + //more secure - return crypto.pbkdf2Sync(password, this.salt, 10000, 512).toString('hex'); }; User.virtual('userId')
6511caef65366b09792d566fc3184ba88fe6f211
app/core/views/MapBrowseLayout.js
app/core/views/MapBrowseLayout.js
define(['backbone', 'core/views/MapView', 'hbs!core/templates/map-browse'], function(Backbone, MapView, mapBrowseTemplate) { var MapBrowseLayout = Backbone.View.extend({ manage: true, template: mapBrowseTemplate, className: 'map-browse-layout', name: 'MapBrowseLayout', views: { ".content-map": new MapView() } }); return MapBrowseLayout; });
define(['backbone', 'core/views/MapView', 'hbs!core/templates/map-browse'], function(Backbone, MapView, mapBrowseTemplate) { var MapBrowseLayout = Backbone.Layout.extend({ manage: true, template: mapBrowseTemplate, className: 'map-browse-layout', name: 'MapBrowseLayout', beforeRender: function() { this.setView(".content-map", new MapView()); } }); return MapBrowseLayout; });
Create the MapView on beforeRender
Create the MapView on beforeRender This was the source of much confusion. Think of the previous code as having mapView as a class attribute. Meaning it wasn't being correctly removed from the app.
JavaScript
apache-2.0
ox-it/moxie-js-client,ox-it/moxie-js-client,ox-it/moxie-js-client,ox-it/moxie-js-client
--- +++ @@ -1,12 +1,12 @@ define(['backbone', 'core/views/MapView', 'hbs!core/templates/map-browse'], function(Backbone, MapView, mapBrowseTemplate) { - var MapBrowseLayout = Backbone.View.extend({ + var MapBrowseLayout = Backbone.Layout.extend({ manage: true, template: mapBrowseTemplate, className: 'map-browse-layout', name: 'MapBrowseLayout', - views: { - ".content-map": new MapView() + beforeRender: function() { + this.setView(".content-map", new MapView()); } });
2f9172dd0c6a5433592b97e5fc203640869654e6
app/controllers/home.js
app/controllers/home.js
import Ember from 'ember'; import $ from 'jquery'; export default Ember.Controller.extend({ spendingsMeter: 0.00, sumByCategory: null, watchAddSpending: function () { this.updateSpendingsMeter(); }.observes('model.@each'), updateSpendingsMeter () { let sumCounted = 0; let sumByCategory = []; this.get('model').forEach(item => { let sum = item.get('sum'); let category = item.get('category'); if (sumByCategory.findBy('category', category)) { sumByCategory.findBy('category', category).sum += parseFloat(sum); } else { sumByCategory.pushObject({ category, sum: parseFloat(sum) }); } sumCounted += parseFloat(sum); }); this.set('spendingsMeter', sumCounted); this.set('sumByCategory', sumByCategory); return; }, saveRecord (record) { let newExpense = this.store.createRecord('expense', record); newExpense.save(); } } });
import Ember from 'ember'; import $ from 'jquery'; export default Ember.Controller.extend({ spendingsMeter: 0.00, sumByCategory: null, watchAddSpending: function () { this.updateSpendingsMeter(); }.observes('model.@each'), updateSpendingsMeter () { let sumCounted = 0; let sumByCategory = []; this.get('model').forEach(item => { let sum = item.get('sum'); let category = item.get('category'); if (sumByCategory.findBy('category', category)) { sumByCategory.findBy('category', category).sum += parseFloat(sum); } else { sumByCategory.pushObject({ category, sum: parseFloat(sum) }); } sumCounted += parseFloat(sum); }); this.set('spendingsMeter', sumCounted); this.set('sumByCategory', sumByCategory); return; }, formatedChartData: function () { const data = [ ['Category', 'Spendings'] ]; this.get('sumByCategory').forEach(category => { data.push( [category.category, category.sum] ); }); return data; }.property('sumByCategory'), saveRecord (record) { let newExpense = this.store.createRecord('expense', record); newExpense.save(); } } });
Format pie-date to proper format each time model change
feat: Format pie-date to proper format each time model change
JavaScript
mit
pe1te3son/spendings-tracker,pe1te3son/spendings-tracker
--- +++ @@ -31,6 +31,19 @@ return; }, + formatedChartData: function () { + const data = [ + ['Category', 'Spendings'] + ]; + + this.get('sumByCategory').forEach(category => { + data.push( + [category.category, category.sum] + ); + }); + return data; + }.property('sumByCategory'), + saveRecord (record) { let newExpense = this.store.createRecord('expense', record); newExpense.save();
7e9f1de81def0f6e02207edfba35173854f1d6e3
src/template/html_parser.js
src/template/html_parser.js
'use strict'; var DefaultStack = require('./stacks/default'); var entityMap = require('html-tokenizer/entity-map'); // @TODO examine other tokenizers or parsers var Parser = require('html-tokenizer/parser'); module.exports = function(html, stack) { var _stack = stack || new DefaultStack(true); var parser = new Parser({ entities: entityMap }); parser.on('open', function(name, attributes) { _stack.openElement(name, attributes); }); parser.on('comment', function(text) { _stack.createComment(text); }); parser.on('text', function(text) { _stack.createObject(text); }); parser.on('close', function() { var el = _stack.peek(); _stack.closeElement(el); }); parser.parse(html); if (!stack) { return _stack.getOutput(); } };
'use strict'; var DefaultStack = require('./stacks/default'); var entityMap = require('html-tokenizer/entity-map'); // @TODO examine other tokenizers or parsers var Parser = require('html-tokenizer/parser'); var defaultStack = new DefaultStack(true); var _stack; var parser = new Parser({ entities: entityMap }); parser.on('open', function(name, attributes) { _stack.openElement(name, attributes); }); parser.on('comment', function(text) { _stack.createComment(text); }); parser.on('text', function(text) { _stack.createObject(text); }); parser.on('close', function() { var el = _stack.peek(); _stack.closeElement(el); }); module.exports = function(html, stack) { if (stack) { _stack = stack; } else { defaultStack.clear(); _stack = defaultStack; } parser.parse(html); if (!stack) { return _stack.getOutput(); } };
Move parser construction outside parse function to fix performance hit
Move parser construction outside parse function to fix performance hit
JavaScript
apache-2.0
wayfair/tungstenjs,wayfair/tungstenjs
--- +++ @@ -5,25 +5,32 @@ // @TODO examine other tokenizers or parsers var Parser = require('html-tokenizer/parser'); +var defaultStack = new DefaultStack(true); +var _stack; +var parser = new Parser({ + entities: entityMap +}); +parser.on('open', function(name, attributes) { + _stack.openElement(name, attributes); +}); +parser.on('comment', function(text) { + _stack.createComment(text); +}); +parser.on('text', function(text) { + _stack.createObject(text); +}); +parser.on('close', function() { + var el = _stack.peek(); + _stack.closeElement(el); +}); + module.exports = function(html, stack) { - var _stack = stack || new DefaultStack(true); - - var parser = new Parser({ - entities: entityMap - }); - parser.on('open', function(name, attributes) { - _stack.openElement(name, attributes); - }); - parser.on('comment', function(text) { - _stack.createComment(text); - }); - parser.on('text', function(text) { - _stack.createObject(text); - }); - parser.on('close', function() { - var el = _stack.peek(); - _stack.closeElement(el); - }); + if (stack) { + _stack = stack; + } else { + defaultStack.clear(); + _stack = defaultStack; + } parser.parse(html);
a4cb20d83dab1560e42b4ff538b8971245ab20ef
app/users/user-links.directive.js
app/users/user-links.directive.js
{ angular.module('meganote.users') .directive('userLinks', [ 'CurrentUser', (CurrentUser) => { class UserLinksController { user() { return CurrentUser.get(); } signedIn() { return CurrentUser.signedIn(); } } return { scope: {}, controller: UserLinksController, controllerAs: 'vm', bindToController: true, template: ` <div class="user-links"> <span ng-show="vm.signedIn()"> Signed in as {{ vm.user().name }} </span> <span ng-show="!vm.signedIn()"> <a ui-sref="sign-up">Sign up for Meganote today!</a> </span> </div> ` }; } ]); }
{ angular.module('meganote.users') .directive('userLinks', [ 'AuthToken', 'CurrentUser', (AuthToken, CurrentUser) => { class UserLinksController { user() { return CurrentUser.get(); } signedIn() { return CurrentUser.signedIn(); } logout() { CurrentUser.clear(); AuthToken.clear(); } } return { scope: {}, controller: UserLinksController, controllerAs: 'vm', bindToController: true, template: ` <div class="user-links"> <span ng-show="vm.signedIn()"> Signed in as {{ vm.user().name }} | <a ui-sref="sign-up" ng-click="vm.logout()">Logout</a> </span> <span ng-show="!vm.signedIn()"> <a ui-sref="sign-up">Sign up for Meganote today!</a> </span> </div> ` }; } ]); }
Add a working logout link.
Add a working logout link.
JavaScript
mit
xternbootcamp16/meganote,xternbootcamp16/meganote
--- +++ @@ -2,8 +2,9 @@ angular.module('meganote.users') .directive('userLinks', [ + 'AuthToken', 'CurrentUser', - (CurrentUser) => { + (AuthToken, CurrentUser) => { class UserLinksController { user() { @@ -11,6 +12,10 @@ } signedIn() { return CurrentUser.signedIn(); + } + logout() { + CurrentUser.clear(); + AuthToken.clear(); } } @@ -24,6 +29,8 @@ <div class="user-links"> <span ng-show="vm.signedIn()"> Signed in as {{ vm.user().name }} + | + <a ui-sref="sign-up" ng-click="vm.logout()">Logout</a> </span> <span ng-show="!vm.signedIn()"> <a ui-sref="sign-up">Sign up for Meganote today!</a>
2c2acda39035ee78daab8e3bcb658696533b1c36
webpack.config.js
webpack.config.js
var webpack = require("webpack"); var CopyWebpackPlugin = require("copy-webpack-plugin"); var path = require("path"); module.exports = { entry: "./src/com/mendix/widget/badge/Badge.ts", output: { path: __dirname + "/dist/tmp", filename: "src/com/mendix/widget/badge/Badge.js", libraryTarget: "umd", umdNamedDefine: true, library: "com.mendix.widget.badge.Badge" }, resolve: { extensions: [ "", ".ts", ".js", ".json" ] }, errorDetails: true, module: { loaders: [ { test: /\.ts$/, loaders: [ "ts-loader" ] }, { test: /\.json$/, loader: "json" } ] }, devtool: "source-map", externals: [ "mxui/widget/_WidgetBase", "dojo/_base/declare" ], plugins: [ new CopyWebpackPlugin([ { from: "src/**/*.js" }, { from: "src/**/*.xml" }, { from: "src/**/*.css" } ], { copyUnmodified: true }) ], watch: true };
var webpack = require("webpack"); var CopyWebpackPlugin = require("copy-webpack-plugin"); var path = require("path"); module.exports = { entry: "./src/com/mendix/widget/badge/Badge.ts", output: { path: __dirname + "/dist/tmp", filename: "src/com/mendix/widget/badge/Badge.js", libraryTarget: "umd" }, resolve: { extensions: [ "", ".ts", ".js", ".json" ] }, errorDetails: true, module: { loaders: [ { test: /\.ts$/, loaders: [ "ts-loader" ] }, { test: /\.json$/, loader: "json" } ] }, devtool: "source-map", externals: [ "mxui/widget/_WidgetBase", "dojo/_base/declare" ], plugins: [ new CopyWebpackPlugin([ { from: "src/**/*.js" }, { from: "src/**/*.xml" }, { from: "src/**/*.css" } ], { copyUnmodified: true }) ], watch: true };
Remove named define for webpack
Remove named define for webpack
JavaScript
apache-2.0
mendixlabs/badge,mendixlabs/badge
--- +++ @@ -7,9 +7,7 @@ output: { path: __dirname + "/dist/tmp", filename: "src/com/mendix/widget/badge/Badge.js", - libraryTarget: "umd", - umdNamedDefine: true, - library: "com.mendix.widget.badge.Badge" + libraryTarget: "umd" }, resolve: { extensions: [ "", ".ts", ".js", ".json" ]
6da8f2e871e0b3c30debd93fe22df630a5b27db0
webpack.config.js
webpack.config.js
const path = require('path'); const webpack = require('webpack'); module.exports = { entry: { home: path.join(__dirname, 'app/src/home'), }, module: { loaders: [ { test: /\.sass$/, loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'], }, { test: /\.js$/, loader: 'babel-loader', exclude: 'node_modules', query: { presets: ['es2015'] }, }, { test: /\.(ttf|woff|woff2)$/, loader: 'file', query: { name: 'fonts/[name].[ext]' }, }, { test: /\.png$/, loader: 'file', }, { test: /\.html$/, loader: 'file-loader?name=[name].[ext]!extract-loader!html-loader', }, ], }, output: { path: path.join(__dirname, 'app/build'), publicPath: '/', filename: '[name].js', }, plugins: [ new webpack.optimize.UglifyJsPlugin({ minimize: true, compress: { warnings: false } }), ], // -------------------------------------------------------------------------- devServer: { contentBase: path.join(__dirname, 'app/build'), }, };
const path = require('path'); const webpack = require('webpack'); module.exports = { entry: { home: path.join(__dirname, 'app/src/home'), }, module: { loaders: [ { test: /\.sass$/, loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'], }, { test: /\.js$/, loader: 'babel-loader', exclude: 'node_modules', query: { presets: ['es2015'] }, }, { test: /\.(ttf|woff|woff2)$/, loader: 'file', query: { name: 'fonts/[name].[ext]' }, }, { test: /\.png$/, loader: 'file', }, { test: /\.html$/, loader: 'file-loader?name=[name].[ext]!extract-loader!html-loader', }, ], }, output: { path: path.join(__dirname, 'app/build'), publicPath: '/', filename: '[name].js', }, plugins: [ new webpack.optimize.UglifyJsPlugin({ minimize: true, compress: { warnings: false } }), ], // -------------------------------------------------------------------------- devServer: { contentBase: path.join(__dirname, 'app/build'), inline: true, }, };
Add --inline autorefreshing to webpack dev server
Add --inline autorefreshing to webpack dev server
JavaScript
mit
arkis/arkis.io,arkis/arkis.io
--- +++ @@ -50,5 +50,6 @@ devServer: { contentBase: path.join(__dirname, 'app/build'), + inline: true, }, };
9e80530cde993e07333bcdecde6cccf658c52a4a
webpack.config.js
webpack.config.js
/* global require, module, __dirname */ const path = require( 'path' ); module.exports = { entry: { './assets/js/amp-blocks-compiled': './blocks/index.js', './assets/js/amp-block-editor-toggle-compiled': './assets/src/amp-block-editor-toggle.js', './assets/js/amp-validation-error-detail-toggle-compiled': './assets/src/amp-validation-error-detail-toggle.js' }, output: { path: path.resolve( __dirname ), filename: '[name].js' }, externals: { '@wordpress/dom-ready': 'wp.domReady', 'amp-validation-i18n': 'ampValidationI18n' }, devtool: 'cheap-eval-source-map', module: { rules: [ { test: /\.js$/, exclude: /(node_modules)/, use: { loader: 'babel-loader' } } ] } };
/* global require, module, __dirname */ const path = require( 'path' ); module.exports = { entry: { './assets/js/amp-blocks-compiled': './blocks/index.js', './assets/js/amp-block-editor-toggle-compiled': './assets/src/amp-block-editor-toggle.js', './assets/js/amp-validation-error-detail-toggle-compiled': './assets/src/amp-validation-error-detail-toggle.js' }, output: { path: path.resolve( __dirname ), filename: '[name].js' }, externals: { 'amp-validation-i18n': 'ampValidationI18n' }, devtool: 'cheap-eval-source-map', module: { rules: [ { test: /\.js$/, exclude: /(node_modules)/, use: { loader: 'babel-loader' } } ] } };
Implement workaround to fix JS not loading issue
Implement workaround to fix JS not loading issue
JavaScript
apache-2.0
GoogleForCreators/web-stories-wp,GoogleForCreators/web-stories-wp,GoogleForCreators/web-stories-wp,GoogleForCreators/web-stories-wp,GoogleForCreators/web-stories-wp
--- +++ @@ -13,7 +13,6 @@ filename: '[name].js' }, externals: { - '@wordpress/dom-ready': 'wp.domReady', 'amp-validation-i18n': 'ampValidationI18n' }, devtool: 'cheap-eval-source-map',
70bce90b7f1df2bbcbf9bfd4a638a20952b3bc33
webpack.config.js
webpack.config.js
'use strict'; var webpack = require('webpack'); var LodashModuleReplacementPlugin = require('lodash-webpack-plugin'); var env = process.env.NODE_ENV; var reactExternal = { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react' }; var reactDomExternal = { root: 'ReactDOM', commonjs2: 'react-dom', commonjs: 'react-dom', amd: 'react-dom' }; var config = { externals: { react: reactExternal, reactDom: reactDomExternal }, module: { loaders: [ { test: /\.js$/, loaders: ['babel-loader'], exclude: /node_modules/ }, { test: /\.jsx$/, loaders: ['babel-loader'], exclude: /node_modules/ } ] }, output: { library: 'ReactWebAnimation', libraryTarget: 'umd' }, plugins: [ new LodashModuleReplacementPlugin(), new webpack.EnvironmentPlugin([ "NODE_ENV" ]) ] }; if ( env === 'production' ) { config.plugins.push( new webpack.optimize.UglifyJsPlugin({ compressor: { pure_getters: true, unsafe: true, unsafe_comps: true, screw_ie8: true, warnings: false } }) ); } module.exports = config;
'use strict'; var webpack = require('webpack'); var LodashModuleReplacementPlugin = require('lodash-webpack-plugin'); var env = process.env.NODE_ENV; var reactExternal = { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react' }; var reactDomExternal = { root: 'ReactDOM', commonjs2: 'react-dom', commonjs: 'react-dom', amd: 'react-dom' }; var config = { externals: { react: reactExternal, reactDom: reactDomExternal }, module: { loaders: [ { test: /\.js$/, loaders: ['babel-loader'], exclude: /node_modules/ }, { test: /\.jsx$/, loaders: ['babel-loader'], exclude: /node_modules/ } ] }, output: { library: { root: 'ReactWebAnimation', amd: 'react-web-animation', }, libraryTarget: 'umd', umdNamedDefine: true, }, plugins: [ new LodashModuleReplacementPlugin(), new webpack.EnvironmentPlugin([ "NODE_ENV" ]) ] }; if ( env === 'production' ) { config.plugins.push( new webpack.optimize.UglifyJsPlugin({ compressor: { pure_getters: true, unsafe: true, unsafe_comps: true, screw_ie8: true, warnings: false } }) ); } module.exports = config;
Include module name in AMD definition
feat(repo): Include module name in AMD definition RequireJS needs to know which name to register an AMD module under. The name was previously mixing; this PR fixes that.
JavaScript
mit
RinconStrategies/react-web-animation,RinconStrategies/react-web-animation,bringking/react-web-animation
--- +++ @@ -28,8 +28,12 @@ ] }, output: { - library: 'ReactWebAnimation', - libraryTarget: 'umd' + library: { + root: 'ReactWebAnimation', + amd: 'react-web-animation', + }, + libraryTarget: 'umd', + umdNamedDefine: true, }, plugins: [ new LodashModuleReplacementPlugin(),
0ed54d51529f68fda56ad2da8f169e6dea8e5584
troposphere/static/js/components/images/search_results.js
troposphere/static/js/components/images/search_results.js
define(['react'], function(React) { var SearchResults = React.createClass({ render: function() { return React.DOM.div({}, this.props.query); } }); return SearchResults; });
define(['react', 'components/images/search', 'components/page_header', 'components/mixins/loading', 'rsvp', 'controllers/applications'], function(React, SearchBox, PageHeader, LoadingMixin, RSVP, Images) { var Results = React.createClass({ mixins: [LoadingMixin], model: function() { return Images.searchApplications(this.props.query); }, renderContent: function() { return React.DOM.ul({}, this.state.model.map(function(app) { return React.DOM.li({}, app.get('name')); })); } }); var SearchResults = React.createClass({ render: function() { return React.DOM.div({}, PageHeader({title: "Image Search"}), SearchBox({query: this.props.query}), Results({query: this.props.query})) } }); return SearchResults; });
Add search results to, well, search results page
Add search results to, well, search results page
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,8 +1,30 @@ -define(['react'], function(React) { +define(['react', 'components/images/search', +'components/page_header', 'components/mixins/loading', 'rsvp', +'controllers/applications'], function(React, SearchBox, PageHeader, +LoadingMixin, RSVP, Images) { + + var Results = React.createClass({ + mixins: [LoadingMixin], + model: function() { + return Images.searchApplications(this.props.query); + }, + renderContent: function() { + return React.DOM.ul({}, + this.state.model.map(function(app) { + return React.DOM.li({}, app.get('name')); + })); + } + }); + var SearchResults = React.createClass({ render: function() { - return React.DOM.div({}, this.props.query); + return React.DOM.div({}, + PageHeader({title: "Image Search"}), + SearchBox({query: this.props.query}), + Results({query: this.props.query})) } }); + return SearchResults; + });
f0aaff823cec2b5733397f0eff4fd22d14de48e2
test/bitcoind/chain.unit.js
test/bitcoind/chain.unit.js
'use strict'; var should = require('chai').should(); var bitcoinlib = require('../../'); var sinon = require('sinon'); var Chain = bitcoinlib.RPCNode.Chain; describe('Bitcoind Chain', function() { describe('#_writeBlock', function() { it('should update hashes and call putBlock', function(done) { var chain = new Chain(); chain.db = { putBlock: sinon.stub().callsArg(1) }; chain._writeBlock({hash: 'hash', prevHash: 'prevhash'}, function(err) { should.not.exist(err); chain.db.putBlock.callCount.should.equal(1); chain.cache.hashes.hash.should.equal('prevhash'); done(); }); }); }); describe('#_validateBlock', function() { it('should call the callback', function(done) { var chain = new Chain(); chain._validateBlock('block', function(err) { should.not.exist(err); done(); }); }); }); });
'use strict'; var should = require('chai').should(); var bitcoinlib = require('../../'); var sinon = require('sinon'); var Chain = bitcoinlib.BitcoindNode.Chain; describe('Bitcoind Chain', function() { describe('#_writeBlock', function() { it('should update hashes and call putBlock', function(done) { var chain = new Chain(); chain.db = { putBlock: sinon.stub().callsArg(1) }; chain._writeBlock({hash: 'hash', prevHash: 'prevhash'}, function(err) { should.not.exist(err); chain.db.putBlock.callCount.should.equal(1); chain.cache.hashes.hash.should.equal('prevhash'); done(); }); }); }); describe('#_validateBlock', function() { it('should call the callback', function(done) { var chain = new Chain(); chain._validateBlock('block', function(err) { should.not.exist(err); done(); }); }); }); });
Use the correct dep "BitcoindNode"
Use the correct dep "BitcoindNode"
JavaScript
mit
bitpay/chainlib-bitcoin
--- +++ @@ -3,7 +3,7 @@ var should = require('chai').should(); var bitcoinlib = require('../../'); var sinon = require('sinon'); -var Chain = bitcoinlib.RPCNode.Chain; +var Chain = bitcoinlib.BitcoindNode.Chain; describe('Bitcoind Chain', function() {
7700c7c436612517a03f2b7fdc7fabb7b0fd3863
template/app/controllers/application_controller.js
template/app/controllers/application_controller.js
const { ActionController } = require('backrest') class ApplicationController extends ActionController.Base { get before() { return [ { action: this._setHeaders } ] } constructor() { super() } _setHeaders(req, res, next) { // Example headers // res.header("Access-Control-Allow-Origin", "*") // res.header("Access-Control-Allow-Methods", "OPTIONS,GET,HEAD,POST,PUT,DELETE") // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization") next() } } module.exports = ApplicationController
const { ActionController } = require('backrest') class ApplicationController extends ActionController.Base { constructor() { super() this.beforeFilters([ { action: this._setHeaders } ]) } _setHeaders(req, res, next) { // Example headers // res.header("Access-Control-Allow-Origin", "*") // res.header("Access-Control-Allow-Methods", "OPTIONS,GET,HEAD,POST,PUT,DELETE") // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization") next() } } module.exports = ApplicationController
Update controller template for proper filter usage.
Update controller template for proper filter usage.
JavaScript
mit
passabilities/backrest
--- +++ @@ -4,14 +4,12 @@ class ApplicationController extends ActionController.Base { - get before() { - return [ - { action: this._setHeaders } - ] - } - constructor() { super() + + this.beforeFilters([ + { action: this._setHeaders } + ]) } _setHeaders(req, res, next) {