commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
b5efd8cd8eeab78442e210ab7d51d4a310a1678d
src/jquery.clone_form_template.js
src/jquery.clone_form_template.js
(function ($) { $.fn.clone_form_template = function (options) { if (!options) { options = {}; } return $(this).map(function () { return update($(this).clone(), options)[0]; }); }; // updates a template clone according to conventions function update($clone, options) { var index = new Date().getTime(); $clone.find('label,input,textarea,select').each(function (i, obj) { update_attrs($(obj), index, options); }); return $clone.removeClass('template').show(); } function update_attrs($element, identifier, options) { if ($element.attr('id')) { $element.attr('id', $element.attr('id').replace(/_-?\d+_/, '_' + identifier + '_') ); } if ($element.attr('for')) { $element.attr('for', $element.attr('for').replace(/_-?\d+_/, '_' + identifier + '_') ); } if ($element.attr('name')) { if (options.copy_values) { $element.val($('[name="' + $element.attr('name') + '"]').val()); } $element.attr('name', $element.attr('name').replace(/\[-?\d+\]/, '[' + identifier + ']') ); } } }(jQuery));
(function ($) { var DEFAULT_PATTERN = '-1'; $.fn.clone_form_template = function (options, cb) { if (!options) { options = {}; } return $(this).map(function () { return update($(this).clone(), options, cb)[0]; }); }; // updates a template clone according to conventions function update($clone, options, cb) { var index = new Date().getTime(); $clone.find('label,input,textarea,select').each(function (i, obj) { update_attrs($(obj), index, options, cb); }); return $clone.removeClass('template').show(); } function update_attrs($element, identifier, options, cb) { var pattern = options.pattern || DEFAULT_PATTERN, underscore_pattern = new RegExp('_' + pattern + '_'), bracket_pattern = new RegExp('\\[' + pattern + '\\]'); if ($element.attr('id')) { $element.attr('id', $element.attr('id').replace(underscore_pattern, '_' + identifier + '_') ); } if ($element.attr('for')) { $element.attr('for', $element.attr('for').replace(underscore_pattern, '_' + identifier + '_') ); } if ($element.attr('name')) { if (options.copy_values) { $element.val($('[name="' + $element.attr('name') + '"]').val()); } $element.attr('name', $element.attr('name').replace(bracket_pattern, '[' + identifier + ']') ); } if (typeof cb === 'function') { cb.apply($element, $element); } } }(jQuery));
Allow customizable pattern and callback
Allow customizable pattern and callback
JavaScript
mit
samuelcole/jquery-livesearch,samuelcole/jquery-livesearch
a8f98d8df125bbfaade27e606d5e75f72b158228
commons/CitationModal.js
commons/CitationModal.js
import { $$ } from '../dom' import { Form, FormRow, Modal, MultiSelect } from '../ui' export default function CitationModal (props) { const { document, node, mode } = props const confirmLabel = mode === 'edit' ? 'Update' : 'Create' const title = mode === 'edit' ? 'Edit Citation' : 'Create Citation' const value = mode === 'edit' ? node.target : [] const root = document.root const referencesList = root.resolve('references') const modalProps = { title, cancelLabel: 'Cancel', confirmLabel, size: 'large' } return $$(Modal, modalProps, $$(Form, {}, $$(FormRow, {}, $$(MultiSelect, { options: referencesList.map(ref => { return { value: ref.id, label: ref.content } }), value, label: 'Add Reference', placeholder: 'Please select one or more references' }).ref('references') ) ) ) }
import { $$, Component } from '../dom' import { Form, FormRow, Modal, MultiSelect } from '../ui' export default class CitationModal extends Component { getInitialState () { const { mode, node } = this.props const value = mode === 'edit' ? node.target : [] return { value } } render () { const { document, mode } = this.props const { value } = this.state const confirmLabel = mode === 'edit' ? 'Update' : 'Create' const title = mode === 'edit' ? 'Edit Citation' : 'Create Citation' const root = document.root const referencesList = root.resolve('references') const disableConfirm = value.length === 0 const modalProps = { title, cancelLabel: 'Cancel', confirmLabel, disableConfirm, size: 'large' } return $$(Modal, modalProps, $$(Form, {}, $$(FormRow, {}, $$(MultiSelect, { options: referencesList.map(ref => { return { value: ref.id, label: ref.content } }), value, label: 'Add Reference', placeholder: 'Please select one or more references', onchange: this._updateReferencess }).ref('references') ) ) ) } _updateReferencess () { const value = this.refs.references.val() this.extendState({ value }) } }
Disable modal confirmation without values.
Disable modal confirmation without values.
JavaScript
mit
michael/substance-1,substance/substance,substance/substance,michael/substance-1
76842f742608a29d5bd1460aeb983265e807d197
src/build/supportedFolders.js
src/build/supportedFolders.js
/* eslint-disable max-len */ exports.extensions = { supported: [ { icon: 'dist', extensions: ['dist', 'out'] }, { icon: 'git', extensions: ['git', 'github'] }, { icon: 'node', extensions: ['node_modules'] }, { icon: 'meteor', extensions: ['meteor'] }, { icon: 'src', extensions: ['src'] }, { icon: 'test', extensions: ['tests', 'test', '__tests__', '__test__'] }, { icon: 'typings', extensions: ['typings'] }, { icon: 'vscode', extensions: ['vscode'] } ], parse: function () { var s = this.replace(/\./g, '_'); if ((/^\d/).test(s)) return 'n' + s; return s; } };
/* eslint-disable max-len */ exports.extensions = { supported: [ { icon: 'dist', extensions: ['dist', 'out'] }, { icon: 'git', extensions: ['git', 'github'] }, { icon: 'node', extensions: ['node_modules'] }, { icon: 'meteor', extensions: ['meteor'] }, { icon: 'src', extensions: ['src', 'source'] }, { icon: 'test', extensions: ['tests', 'test', '__tests__', '__test__'] }, { icon: 'typings', extensions: ['typings'] }, { icon: 'vscode', extensions: ['vscode'] } ], parse: function () { var s = this.replace(/\./g, '_'); if ((/^\d/).test(s)) return 'n' + s; return s; } };
Support "source" as a src folder
Support "source" as a src folder
JavaScript
mit
robertohuertasm/vscode-icons,jens1o/vscode-icons,JimiC/vscode-icons,vscode-icons/vscode-icons,vscode-icons/vscode-icons,JimiC/vscode-icons,olzaragoza/vscode-icons
f2fd025793df508f7980c5c4f21bfc5745cf9d08
src/fs/__tests__/test-base.js
src/fs/__tests__/test-base.js
jest.autoMockOff(); jest.unmock('../base.js'); const base = require('../base.js'); describe('Base', () => { it('does a lot of cool stuff', () => { }); });
jest.autoMockOff(); jest.unmock('../base.js'); const base = require('../base.js'); jest.unmock('node-fetch'); const fetch = require('node-fetch'); global.Response = fetch.Response; describe('Base', () => { it('constructs correctly', () => { let path = Object.create(null); let name = Object.create(null); let options = Object.create(null); expect(path).not.toBe(name); expect(path).not.toBe(options); expect(name).not.toBe(options); let bfs = new base.Base(name, path, options); expect(bfs).toBeDefined(); expect(bfs.path).toBe(path); expect(bfs.name).toBe(name); expect(bfs.options).toBe(options); }); it('does not stat paths', () => { let path = Object.create(null); let name = Object.create(null); let options = Object.create(null); let bfs = new base.Base(name, path, options); let ret = Object.create(null); spyOn(Promise, 'resolve').and.returnValue(ret); let val = bfs.stat(''); expect(Promise.resolve).toHaveBeenCalledWith(new Response(null, {status: 405})); expect(val).toBe(ret); }); it('does not read paths', () => { let path = Object.create(null); let name = Object.create(null); let options = Object.create(null); let bfs = new base.Base(name, path, options); let ret = Object.create(null); spyOn(Promise, 'resolve').and.returnValue(ret); let val = bfs.read(''); expect(Promise.resolve).toHaveBeenCalledWith(new Response(null, {status: 405})); expect(val).toBe(ret); }); it('does not write paths', () => { let path = Object.create(null); let name = Object.create(null); let options = Object.create(null); let bfs = new base.Base(name, path, options); let ret = Object.create(null); spyOn(Promise, 'resolve').and.returnValue(ret); let val = bfs.write('', ''); expect(Promise.resolve).toHaveBeenCalledWith(new Response(null, {status: 405})); expect(val).toBe(ret); }); });
Add tests for Base fs
Add tests for Base fs
JavaScript
mit
LivelyKernel/lively4-core,LivelyKernel/lively4-core
8831374a514314c64f52822c1be393f396bc415f
.eslintrc.js
.eslintrc.js
module.exports = { root: true, parser: "@typescript-eslint/parser", parserOptions: { tsconfigRootDir: __dirname, project: ["./tsconfig.json"] }, plugins: ["@typescript-eslint"], extends: [ "eslint:recommended", "plugin:@typescript-eslint/recommended", "plugin:@typescript-eslint/recommended-requiring-type-checking", "prettier", "prettier/@typescript-eslint" ], rules: { "@typescript-eslint/no-non-null-assertion": 0 } };
module.exports = { root: true, parser: "@typescript-eslint/parser", parserOptions: { tsconfigRootDir: __dirname, project: ["./tsconfig.json"] }, plugins: ["@typescript-eslint"], extends: [ "eslint:recommended", "plugin:@typescript-eslint/recommended", "plugin:@typescript-eslint/recommended-requiring-type-checking", "prettier", "prettier/@typescript-eslint" ], rules: { "@typescript-eslint/no-explicit-any": 0, "@typescript-eslint/no-non-null-assertion": 0, "@typescript-eslint/no-unsafe-assignment": 0, "@typescript-eslint/no-unsafe-call": 0, "@typescript-eslint/no-unsafe-member-access": 0, "@typescript-eslint/no-unsafe-return": 0, } };
Disable eslint rules disallowing `any` to be used
Disable eslint rules disallowing `any` to be used
JavaScript
lgpl-2.1
SoftCreatR/WCF,WoltLab/WCF,SoftCreatR/WCF,Cyperghost/WCF,Cyperghost/WCF,SoftCreatR/WCF,Cyperghost/WCF,SoftCreatR/WCF,WoltLab/WCF,Cyperghost/WCF,WoltLab/WCF,WoltLab/WCF,Cyperghost/WCF
be8ed28b34bcd1b9a7666b9dc9ec0da64ff28a30
js/locales/bootstrap-datepicker.mk.js
js/locales/bootstrap-datepicker.mk.js
/** * Macedonian translation for bootstrap-datepicker * Marko Aleksic <psybaron@gmail.com> */ ;(function($){ $.fn.datepicker.dates['mk'] = { days: ["Недела", "Понеделник", "Вторник", "Среда", "Четврток", "Петок", "Сабота", "Недела"], daysShort: ["Нед", "Пон", "Вто", "Сре", "Чет", "Пет", "Саб", "Нед"], daysMin: ["Не", "По", "Вт", "Ср", "Че", "Пе", "Са", "Не"], months: ["Јануари", "Февруари", "Март", "Април", "Мај", "Јуни", "Јули", "Август", "Септември", "Октомври", "Ноември", "Декември"], monthsShort: ["Јан", "Фев", "Мар", "Апр", "Мај", "Јун", "Јул", "Авг", "Сеп", "Окт", "Ное", "Дек"], today: "Денес" }; }(jQuery));
/** * Macedonian translation for bootstrap-datepicker * Marko Aleksic <psybaron@gmail.com> */ ;(function($){ $.fn.datepicker.dates['mk'] = { days: ["Недела", "Понеделник", "Вторник", "Среда", "Четврток", "Петок", "Сабота", "Недела"], daysShort: ["Нед", "Пон", "Вто", "Сре", "Чет", "Пет", "Саб", "Нед"], daysMin: ["Не", "По", "Вт", "Ср", "Че", "Пе", "Са", "Не"], months: ["Јануари", "Февруари", "Март", "Април", "Мај", "Јуни", "Јули", "Август", "Септември", "Октомври", "Ноември", "Декември"], monthsShort: ["Јан", "Фев", "Мар", "Апр", "Мај", "Јун", "Јул", "Авг", "Сеп", "Окт", "Ное", "Дек"], today: "Денес", format: "dd.MM.yyyy" }; }(jQuery));
Add Macedonian date format (with leading zero).
Add Macedonian date format (with leading zero).
JavaScript
apache-2.0
bitzesty/bootstrap-datepicker,HNygard/bootstrap-datepicker,gn0st1k4m/bootstrap-datepicker,aldano/bootstrap-datepicker,zhaoyan158567/bootstrap-datepicker,acrobat/bootstrap-datepicker,TheJumpCloud/bootstrap-datepicker,cherylyan/bootstrap-datepicker,huang-x-h/bootstrap-datepicker,cherylyan/bootstrap-datepicker,defrian8/bootstrap-datepicker,mreiden/bootstrap-datepicker,xutongtong/bootstrap-datepicker,daniyel/bootstrap-datepicker,Tekzenit/bootstrap-datepicker,vegardok/bootstrap-datepicker,parkeugene/bootstrap-datepicker,Youraiseme/bootstrap-datepicker,Azaret/bootstrap-datepicker,Doublemedia/bootstrap-datepicker,saurabh27125/bootstrap-datepicker,tcrossland/bootstrap-datepicker,hemp/bootstrap-datepicker,Mteuahasan/bootstrap-datepicker,NFC-DITO/bootstrap-datepicker,riyan8250/bootstrap-datepicker,CherryDT/bootstrap-datepicker,josegomezr/bootstrap-datepicker,otnavle/bootstrap-datepicker,jesperronn/bootstrap-datepicker,WebbyLab/bootstrap-datepicker,otnavle/bootstrap-datepicker,Invulner/bootstrap-datepicker,Mteuahasan/bootstrap-datepicker,inukshuk/bootstrap-datepicker,mfunkie/bootstrap-datepicker,dckesler/bootstrap-datepicker,1000hz/bootstrap-datepicker,hebbet/bootstrap-datepicker,osama9/bootstrap-datepicker,keiwerkgvr/bootstrap-datepicker,MartijnDwars/bootstrap-datepicker,kiwiupover/bootstrap-datepicker,jhalak/bootstrap-datepicker,HuBandiT/bootstrap-datepicker,1000hz/bootstrap-datepicker,dswitzer/bootstrap-datepicker,inspur-tobacco/bootstrap-datepicker,stenmuchow/bootstrap-datepicker,christophercaburog/bootstrap-datepicker,CheapSk8/bootstrap-datepicker,chengky/bootstrap-datepicker,bitzesty/bootstrap-datepicker,pacozaa/bootstrap-datepicker,abnovak/bootstrap-sass-datepicker,uxsolutions/bootstrap-datepicker,steffendietz/bootstrap-datepicker,Doublemedia/bootstrap-datepicker,mfunkie/bootstrap-datepicker,nerionavea/bootstrap-datepicker,ashleymcdonald/bootstrap-datepicker,NFC-DITO/bootstrap-datepicker,oller/foundation-datepicker-sass,huang-x-h/bootstrap-datepicker,wetet2/bootstrap-datepicker,jhalak/bootstrap-datepicker,rocLv/bootstrap-datepicker,acrobat/bootstrap-datepicker,champierre/bootstrap-datepicker,inway/bootstrap-datepicker,WebbyLab/bootstrap-datepicker,janusnic/bootstrap-datepicker,parkeugene/bootstrap-datepicker,CheapSk8/bootstrap-datepicker,inway/bootstrap-datepicker,yangyichen/bootstrap-datepicker,rocLv/bootstrap-datepicker,ashleymcdonald/bootstrap-datepicker,dswitzer/bootstrap-datepicker,WeiLend/bootstrap-datepicker,Invulner/bootstrap-datepicker,HNygard/bootstrap-datepicker,inspur-tobacco/bootstrap-datepicker,tcrossland/bootstrap-datepicker,kevintvh/bootstrap-datepicker,TheJumpCloud/bootstrap-datepicker,hemp/bootstrap-datepicker,abnovak/bootstrap-sass-datepicker,martinRjs/bootstrap-datepicker,mfunkie/bootstrap-datepicker,inukshuk/bootstrap-datepicker,menatoric59/bootstrap-datepicker,darluc/bootstrap-datepicker,janusnic/bootstrap-datepicker,Youraiseme/bootstrap-datepicker,oller/foundation-datepicker-sass,thetimbanks/bootstrap-datepicker,cbryer/bootstrap-datepicker,champierre/bootstrap-datepicker,thetimbanks/bootstrap-datepicker,christophercaburog/bootstrap-datepicker,Sprinkle7/bootstrap-datepicker,josegomezr/bootstrap-datepicker,nilbus/bootstrap-datepicker,chengky/bootstrap-datepicker,gn0st1k4m/bootstrap-datepicker,uxsolutions/bootstrap-datepicker,Azaret/bootstrap-datepicker,osama9/bootstrap-datepicker,rstone770/bootstrap-datepicker,defrian8/bootstrap-datepicker,nilbus/bootstrap-datepicker,stenmuchow/bootstrap-datepicker,wulinmengzhu/bootstrap-datepicker,Sprinkle7/bootstrap-datepicker,daniyel/bootstrap-datepicker,joubertredrat/bootstrap-datepicker,xutongtong/bootstrap-datepicker,wetet2/bootstrap-datepicker,hebbet/bootstrap-datepicker,riyan8250/bootstrap-datepicker,zhaoyan158567/bootstrap-datepicker,WebbyLab/bootstrap-datepicker,mreiden/bootstrap-datepicker,i-am-kenny/bootstrap-datepicker,wulinmengzhu/bootstrap-datepicker,Tekzenit/bootstrap-datepicker,oller/foundation-datepicker-sass,vgrish/bootstrap-datepicker,kevintvh/bootstrap-datepicker,joubertredrat/bootstrap-datepicker,vegardok/bootstrap-datepicker,aldano/bootstrap-datepicker,cbryer/bootstrap-datepicker,SimpleUpdates/bootstrap-datepicker,ibcooley/bootstrap-datepicker,steffendietz/bootstrap-datepicker,WeiLend/bootstrap-datepicker,eternicode/bootstrap-datepicker,ibcooley/bootstrap-datepicker,vsn4ik/bootstrap-datepicker,darluc/bootstrap-datepicker,pacozaa/bootstrap-datepicker,eternicode/bootstrap-datepicker,CherryDT/bootstrap-datepicker,wearespindle/datepicker-js,josegomezr/bootstrap-datepicker,dckesler/bootstrap-datepicker,menatoric59/bootstrap-datepicker,i-am-kenny/bootstrap-datepicker,yangyichen/bootstrap-datepicker,rstone770/bootstrap-datepicker,kiwiupover/bootstrap-datepicker,jesperronn/bootstrap-datepicker,nerionavea/bootstrap-datepicker,martinRjs/bootstrap-datepicker,SimpleUpdates/bootstrap-datepicker,vgrish/bootstrap-datepicker,vsn4ik/bootstrap-datepicker,1000hz/bootstrap-datepicker,saurabh27125/bootstrap-datepicker,keiwerkgvr/bootstrap-datepicker,HuBandiT/bootstrap-datepicker,MartijnDwars/bootstrap-datepicker
6c504b7a54518d498d256caa3801df0df49a4a87
server/tests/seed/auth_seed.js
server/tests/seed/auth_seed.js
// auth_seed.js const User = require('./../../database/models').User; module.exports = { emptyDB(done) { User.destroy({ truncate: true }) .then((rows) => { console.log(rows); return done(); }) .catch(err => done(err)); }, setData(fullname, username, email, mobile, password, confirmPassword) { return { fullname, username, email, mobile, password, confirm_password: confirmPassword }; }, addUserToDb(done) { User.create({ fullname: 'jimoh hadi', username: 'ovenje', email: 'ovenje@yahoo.com', mobile: '8163041269', password: '11223344' }) .then((user) => { done(); }) .catch((err) => { done(err); }); } };
// auth_seed.js const User = require('./../../database/models').User; module.exports = { emptyDB(done) { User.destroy({ truncate: true }) .then(() => done()) .catch(err => done(err)); }, setData(fullname, username, email, mobile, password, confirmPassword) { return { fullname, username, email, mobile, password, confirm_password: confirmPassword }; }, addUserToDb(done) { User.create({ fullname: 'jimoh hadi', username: 'ovenje', email: 'ovenje@yahoo.com', mobile: '8163041269', password: '11223344' }) .then((user) => { done(); }) .catch((err) => { done(err); }); } };
Remove unnecessary argument from seeder file
Remove unnecessary argument from seeder file
JavaScript
mit
johadi10/PostIt,johadi10/PostIt
890bdbb025bcf7ec6121c58d6b6882cdbd6dd6ee
src/handlers.js
src/handlers.js
const pkg = require('../package.json'); const Identify = require('./identifyPeople.js'); function handlers() { function index(req, reply) { reply.view('index', { users: [ 'hello' ] }); } function version(req, reply) { reply({version: pkg.version}).code(200); } function identifyPeople(req, reply) { if (!req.payload || !req.payload.url) { reply("Expected 'url' parameter").code(400); return; } let imageUrl = req.payload.url; Identify.findFace(imageUrl) .then((names) => { reply({"Identification results: " : JSON.stringify(names)}).code(200); }) .catch((err) => { console.log(JSON.stringify(err, null, 2)); reply({"Identification results" : []}).code(500); }); } return { index, version, identifyPeople }; } module.exports = handlers;
const pkg = require('../package.json'); const Identify = require('./identifyPeople.js'); function handlers() { function index(req, reply) { reply.view('index', { users: [ 'hello' ] }); } function version(req, reply) { reply({version: pkg.version}).code(200); } function identifyPeople(req, reply) { if (!req.payload || !req.payload.url) { reply("Expected 'url' parameter").code(400); return; } let imageUrl = req.payload.url; Identify.findFace(imageUrl) .then((names) => { reply({"identities" : names}).code(200); }) .catch((err) => { console.log(JSON.stringify(err, null, 2)); reply({"identities" : []}).code(500); }); } return { index, version, identifyPeople }; } module.exports = handlers;
Return names as json array
Return names as json array Now the identify results are returned as json.
JavaScript
mit
alsalo1/walls-have-ears,alsalo1/walls-have-ears
76b57bed027fb3cb16bd24f9bb6fef4011fd9ebd
src/routes/product-group.routes.js
src/routes/product-group.routes.js
import express from 'express'; import * as controller from '../controllers/product-group.controller'; import { createAuthMiddleware } from '../auth'; import { MODERATOR } from '../auth/constants'; const router = express.Router(); router.use(createAuthMiddleware(MODERATOR)); router.get('/', controller.list); router.post('/', controller.create); router.put('/:id', controller.update); router.delete('/:id', controller.destroy); export default router;
import express from 'express'; import * as controller from '../controllers/product-group.controller'; import { createAuthMiddleware } from '../auth'; import { MODERATOR, TOKEN } from '../auth/constants'; const router = express.Router(); router.get('/', createAuthMiddleware(TOKEN), controller.list); router.post('/', createAuthMiddleware(MODERATOR), controller.create); router.put('/:id', createAuthMiddleware(MODERATOR), controller.update); router.delete('/:id', createAuthMiddleware(MODERATOR), controller.destroy); export default router;
Change product group api authentication
Change product group api authentication
JavaScript
mit
abakusbackup/abacash-api,abakusbackup/abacash-api
da2614a96f6e78133ae6e7441557a470dc27fde0
src/components/Editor/index.js
src/components/Editor/index.js
import './index.css'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Viewer from '../Viewer'; class Editor extends Component { render() { const { presId } = this.props; return ( <div className="editor-wrapper"> <Viewer presId={presId}/> </div> ) } } Editor.propTypes = { presId: PropTypes.string.isRequired }; export default Editor;
import './index.css'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Viewer from '../Viewer'; import presentations from '../../data/presentations'; import PreviewPanel from './components/PreviewPanel'; class Editor extends Component { constructor(props) { super(props); this.state = { presentation: null, loading: true, activeSlideIndex: 0, error: null, }; } componentDidMount() { const { presId } = this.props; presentations.get(presId) .then(presentation => { this.setState({ presentation, loading: false, activeSlideIndex: 0, }) }) .catch(err => { this.setState({ error: err, loading: false, }) }) } render() { const { presId } = this.props; const { loading, error, presentation } = this.state; return ( <div className="editor-wrapper"> <Viewer presId={presId}/> </div> ) } } Editor.propTypes = { presId: PropTypes.string.isRequired }; export default Editor;
Add logic to getting the presentation to the editor
Add logic to getting the presentation to the editor
JavaScript
mit
jacobwindsor/pathway-presenter,jacobwindsor/pathway-presenter
c13e26870627291988d144ff9d77f1b1b05ec264
src/config/app-config.index.js
src/config/app-config.index.js
import Config from './app-config.module'; import './base.config'; /** * Optionally include a file */ ((_require) => { if (_require.keys().find(x => x.indexOf('local.config.js') > -1)) { _require('./local.config.js'); } })(require.context('./', false, /local\.config\.js$/)); export default Config;
import Config from './app-config.module'; import './base.config'; /** * Optionally include a file */ ((_require) => { if (_require.keys().indexOf('./local.config.js') > -1) { _require('./local.config.js'); } })(require.context('./', false, /local\.config\.js$/)); export default Config;
Simplify check for local.config.js file
Simplify check for local.config.js file
JavaScript
mit
tijhaart/webpack-foundation,tijhaart/webpack-foundation
f1cd45736986db9362750ac3061ee4113c8ba3f2
test/unit/vdom/incremental-dom.js
test/unit/vdom/incremental-dom.js
import * as IncrementalDOM from 'incremental-dom'; import { vdom } from '../../../src/index'; describe('IncrementalDOM', function () { it('should export all the same members as the incremental-dom we consume', function () { // Ensure we export the element functions. expect(vdom.attr).to.be.a('function'); expect(vdom.elementClose).to.be.a('function'); expect(vdom.elementOpenEnd).to.be.a('function'); expect(vdom.elementOpenStart).to.be.a('function'); expect(vdom.elementVoid).to.be.a('function'); expect(vdom.text).to.be.a('function'); // Ensure they're not the same as Incremental DOM's implementation. expect(vdom.attr).not.to.equal(IncrementalDOM.attr); expect(vdom.elementClose).not.to.equal(IncrementalDOM.elementClose); expect(vdom.elementOpenEnd).not.to.equal(IncrementalDOM.elementOpenEnd); expect(vdom.elementOpenStart).not.to.equal(IncrementalDOM.elementOpenStart); expect(vdom.elementVoid).not.to.equal(IncrementalDOM.elementVoid); expect(vdom.text).not.to.equal(IncrementalDOM.text); }); });
import * as IncrementalDOM from 'incremental-dom'; import { vdom } from '../../../src/index'; function testBasicApi (name) { it('should be a function', () => expect(vdom[name]).to.be.a('function')); it('should not be the same one as in Incremental DOM', () => expect(vdom[name]).not.to.equal(IncrementalDOM[name])); } describe('IncrementalDOM', function () { describe('attr', () => { testBasicApi('attr'); }); describe('elementClose', () => { testBasicApi('elementClose'); }); describe('elementOpen', () => { testBasicApi('elementOpen'); }); describe('elementOpenEnd', () => { testBasicApi('elementOpenEnd'); }); describe('elementOpenStart', () => { testBasicApi('elementOpenStart'); }); describe('elementVoid', () => { testBasicApi('elementVoid'); }); describe('text', () => { testBasicApi('text'); }); });
Add basic tests for all api points that override Incremental DOM.
test(vdom): Add basic tests for all api points that override Incremental DOM.
JavaScript
mit
chrisdarroch/skatejs,skatejs/skatejs,skatejs/skatejs,chrisdarroch/skatejs,skatejs/skatejs
933d14bd3764d570477af932604f8243ff406aa3
index-browser.js
index-browser.js
const assert = require('assert') function createGL (opts) { assert(!opts || (typeof opts === 'object'), 'pex-gl: createGL requires opts argument to be null or an object') if (!opts) opts = {} let canvas = opts.canvas if (!canvas) { canvas = document.createElement('canvas') canvas.width = opts.width || window.innerWidth canvas.height = opts.height || window.innerHeight if (!opts.width && !opts.height) { // fullscreen document.body.style.margin = '0px' } if (document.body) { document.body.appendChild(canvas) } else { // just in case our script is included above <body> document.addEventListener('DOMContentLoaded', () => { document.body.appendChild(canvas) }) } } const gl = canvas.getContext('webgl', opts) return gl } module.exports = createGL
const assert = require('assert') function createGL (opts) { assert(!opts || (typeof opts === 'object'), 'pex-gl: createGL requires opts argument to be null or an object') if (!opts) opts = {} let canvas = opts.canvas if (!canvas) { canvas = document.createElement('canvas') canvas.width = opts.width || window.innerWidth canvas.height = opts.height || window.innerHeight const appendCanvas = () => { if (!opts.width && !opts.height) { // fullscreen document.body.style.margin = '0px' } document.body.appendChild(canvas) } if (document.body) { appendCanvas() } else { // just in case our script is included above <body> document.addEventListener('DOMContentLoaded', appendCanvas) } } const gl = canvas.getContext('webgl', opts) return gl } module.exports = createGL
Change the way properties on document.body are set while loading canvas.
Change the way properties on document.body are set while loading canvas. In the default setup, when no width and height options are passed and `createGL` is called on page load, it throws an error if the script is included before the body element, since `document.body.style` is null. The function already accounts for this fact while appending the canvas to the page, but not while setting `style.margin = '0px'`. This PR changes that.
JavaScript
mit
pex-gl/pex-gl
16479fe5e89eb332f015eaba6344140142a5959f
lib/endpoint/UploadEndpoint.js
lib/endpoint/UploadEndpoint.js
var loadTemplate = require('../loadTemplate') var getRepository = require('./getRepository') function UploadEndpoint(req, res, next) { var repo = getRepository(req) repo.post(req.body, 'application/rdf+xml', (err, callback) => { if(err) { return next(err) } res.status(200).send('ok') }) } module.exports = UploadEndpoint
var loadTemplate = require('../loadTemplate') var getRepository = require('./getRepository') function UploadEndpoint(req, res, next) { var repo = getRepository(req) repo.post(req.body, req.headers['content-type'], (err, callback) => { if(err) { return next(err) } res.status(200).send('ok') }) } module.exports = UploadEndpoint
Use content-type header in upload endpoint
Use content-type header in upload endpoint
JavaScript
bsd-2-clause
ICO2S/sbolstack-api,ICO2S/sbolstack-api,ICO2S/sbolstack-api
d6761e50b6285b3ba0d7371a61be6712cdc6fac3
src/SumoCoders/FrameworkCoreBundle/Resources/assets/js/Framework/Tabs.js
src/SumoCoders/FrameworkCoreBundle/Resources/assets/js/Framework/Tabs.js
export class Tabs { initEventListeners () { this.loadTab() $('.nav-tabs a').on('click', $.proxy(this.changeTab, this)) } changeTab (event) { let $current = $(event.currentTarget) /* if the browser supports history.pushState(), use it to update the URL with the fragment identifier, without triggering a scroll/jump */ if (window.history && window.history.pushState) { /* an empty state object for now — either we implement a proper popstate handler ourselves, or wait for jQuery UI upstream */ window.history.pushState({}, document.title, $current.href) } else { let scrolled = $(window).scrollTop() window.location.hash = '#' + $current.href.split('#')[1] $(window).scrollTop(scrolled) } $current.tab('show') } loadTab () { let url = document.location.toString() if (url.match('#')) { let anchor = '#' + url.split('#')[1] if ($('.nav-tabs a[href=' + anchor + ']').length > 0) { $('.nav-tabs a[href=' + anchor + ']').tab('show') } } } }
export class Tabs { initEventListeners () { this.loadTab() $('.nav-tabs a').on('click', $.proxy(this.changeTab, this)) } changeTab (event) { let $current = $(event.currentTarget) /* if the browser supports history.pushState(), use it to update the URL with the fragment identifier, without triggering a scroll/jump */ if (window.history && window.history.pushState) { /* an empty state object for now — either we implement a proper popstate handler ourselves, or wait for jQuery UI upstream */ window.history.pushState({}, document.title, $current.attr('href')) } else { let scrolled = $(window).scrollTop() window.location.hash = '#' + $current.attr('href').split('#')[1] $(window).scrollTop(scrolled) } $current.tab('show') } loadTab () { let url = document.location.toString() if (url.match('#')) { let anchor = '#' + url.split('#')[1] if ($('.nav-tabs a[href=' + anchor + ']').length > 0) { $('.nav-tabs a[href=' + anchor + ']').tab('show') } } } }
Fix url hash when changing tabs
Fix url hash when changing tabs
JavaScript
mit
sumocoders/Framework,jonasdekeukelaere/Framework,sumocoders/Framework,jonasdekeukelaere/Framework,jonasdekeukelaere/Framework,sumocoders/Framework,sumocoders/Framework,jonasdekeukelaere/Framework
6bce932ca8d3b10cfa00231f0719c92262282dc9
Gruntfile.js
Gruntfile.js
'use strict'; module.exports = function (grunt) { // Show elapsed time at the end require('time-grunt')(grunt); // Load all grunt tasks require('load-grunt-tasks')(grunt); grunt.initConfig({ jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, gruntfile: { src: ['Gruntfile.js'] }, js: { src: ['*.js'] }, test: { src: ['test/**/*.js'] } }, mochacli: { options: { reporter: 'nyan', bail: true }, all: ['test/*.js'] }, watch: { gruntfile: { files: '<%= jshint.gruntfile.src %>', tasks: ['jshint:gruntfile'] }, js: { files: '<%= jshint.js.src %>', tasks: ['jshint:js', 'mochacli'] }, test: { files: '<%= jshint.test.src %>', tasks: ['jshint:test', 'mochacli'] } } }); grunt.registerTask('default', ['jshint', 'mochacli']); };
'use strict'; module.exports = function (grunt) { // Show elapsed time at the end require('time-grunt')(grunt); // Load all grunt tasks require('load-grunt-tasks')(grunt); grunt.initConfig({ jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish'), ignores: 'browser.js' }, gruntfile: { src: ['Gruntfile.js'] }, js: { src: ['*.js'] }, test: { src: ['test/**/*.js'] } }, mochacli: { options: { reporter: 'nyan', bail: true }, all: ['test/*.js'] }, watch: { gruntfile: { files: '<%= jshint.gruntfile.src %>', tasks: ['jshint:gruntfile'] }, js: { files: '<%= jshint.js.src %>', tasks: ['jshint:js', 'mochacli'] }, test: { files: '<%= jshint.test.src %>', tasks: ['jshint:test', 'mochacli'] } } }); grunt.registerTask('default', ['jshint', 'mochacli']); };
Make ignore browser.js from jshint
Make ignore browser.js from jshint
JavaScript
mit
hakatashi/japanese.js,hakatashi/japanese.js
abec1e3b7b21eb8a7fc4ca301050f5703c3b61d7
src/DefaultSpecimens.js
src/DefaultSpecimens.js
import Audio from './specimens/Audio'; import Code from './specimens/Code'; import Color from './specimens/Color'; import Html from './specimens/Html'; import Hint from './specimens/Hint'; import Image from './specimens/Image'; import Type from './specimens/Type'; import Download from './specimens/Download'; import Video from './specimens/Video'; export default { audio: Audio, code: Code, color: Color, html: Html, hint: Hint, image: Image, type: Type, download: Download, video: Video };
import Audio from './specimens/Audio'; import Code from './specimens/Code'; import Color from './specimens/Color'; import Html from './specimens/Html'; import Hint from './specimens/Hint'; import Image from './specimens/Image'; import Type from './specimens/Type'; import Download from './specimens/Download'; import Video from './specimens/Video'; export default { audio: Audio, code: Code, // color: Color, // html: Html, hint: Hint, // image: Image, // type: Type, // download: Download, // video: Video };
Disable specimens which are not upgraded yet
Disable specimens which are not upgraded yet
JavaScript
bsd-3-clause
interactivethings/catalog,interactivethings/catalog,interactivethings/catalog,interactivethings/catalog
59195df3b093746478e0077bddbc913ebb63cb45
pre-build.js
pre-build.js
'use strict'; var Mocha = require('mocha'); var colors = require('colors'); var build = require('./build.js'); var mocha = new Mocha({ui: 'bdd', reporter: 'list'}); mocha.addFile('test/test-optipng-path.js'); mocha.run(function (failures) { if (failures > 0) { build(); } else { console.log('pre-build test passed successfully, skipping build'.green); } });
'use strict'; var Mocha = require('mocha'); var colors = require('colors'); var build = require('./build.js'); var mocha = new Mocha({ui: 'bdd', reporter: 'min'}); mocha.addFile('test/test-optipng-path.js'); mocha.run(function (failures) { if (failures > 0) { console.log('pre-build test failed, compiling from source...'.red); build(); } else { console.log('pre-build test passed successfully, skipping build...'.green); } });
Improve message on prebuild test failure
Improve message on prebuild test failure
JavaScript
mit
jmnarloch/optipng-bin,imagemin/optipng-bin,inversion/optipng-bin
2bbe6c91c53b871e6c2aad0b3c26508db3a0cf3f
Gruntfile.js
Gruntfile.js
module.exports = function(grunt) { 'use strict'; // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // Task configuration. aws: grunt.file.readJSON('.aws-deploy.json'), s3: { options: { accessKeyId: '<%= aws.accessKeyId %>', secretAccessKey: '<%= aws.secretAccessKey %>', bucket: 'gamekeller', region: 'eu-central-1', gzip: false, overwrite: false }, assets: { cwd: 'public/', src: ['assets/**', '!assets/manifest.json'] } } }) // Load local grunt tasks. grunt.loadTasks('grunt') // Load necessary plugins. grunt.loadNpmTasks('grunt-aws') // Production simulating task. grunt.registerTask('prod', ['revupdate', 'precompile']) // Database operation tasks. grunt.registerTask('db', ['dropDB', 'seedDB']) grunt.registerTask('db.drop', ['dropDB']) grunt.registerTask('db.seed', ['seedDB']) // Deploy task. grunt.registerTask('deploy', ['bower', 'precompile', 's3', 'revupdate']) }
module.exports = function(grunt) { 'use strict'; // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // Task configuration. aws: grunt.file.readJSON('.aws-deploy.json'), s3: { options: { accessKeyId: '<%= aws.accessKeyId %>', secretAccessKey: '<%= aws.secretAccessKey %>', bucket: 'gamekeller', region: 'eu-central-1', gzip: false, overwrite: false, access: 'private' }, assets: { cwd: 'public/', src: ['assets/**', '!assets/manifest.json'] } } }) // Load local grunt tasks. grunt.loadTasks('grunt') // Load necessary plugins. grunt.loadNpmTasks('grunt-aws') // Production simulating task. grunt.registerTask('prod', ['revupdate', 'precompile']) // Database operation tasks. grunt.registerTask('db', ['dropDB', 'seedDB']) grunt.registerTask('db.drop', ['dropDB']) grunt.registerTask('db.seed', ['seedDB']) // Deploy task. grunt.registerTask('deploy', ['bower', 'precompile', 's3', 'revupdate']) }
Use private ACL for S3
Grunt/deploy: Use private ACL for S3
JavaScript
mit
gamekeller/next,gamekeller/next
56abe6dc632ece6f1cb2518f654c6da499798a28
Gruntfile.js
Gruntfile.js
/** * Copyright (c) Ajay Sreedhar. All rights reserved. * * Licensed under the MIT License. * Please see LICENSE file located in the project root for more information. */ 'use strict'; const loadTasks = require('load-grunt-tasks'); const {copyConfig, babelConfig} = require('./build/grunt-config'); const {cleanBuild, startRenderer, makeRelease} = require('./build/grunt-task'); module.exports = function (grunt) { loadTasks(grunt, {pattern: ['grunt-contrib-copy', 'grunt-babel']}); grunt.initConfig({ copy: copyConfig, babel: babelConfig }); grunt.registerTask('clean', 'Cleans up the output files.', cleanBuild); grunt.registerTask('render', 'Starts the electron renderer.', startRenderer); grunt.registerTask('release', 'Makes an app release.', makeRelease); grunt.registerTask('dist', ['clean', 'babel', 'copy']); grunt.registerTask('start', ['dist', 'render']); };
/** * Copyright (c) Ajay Sreedhar. All rights reserved. * * Licensed under the MIT License. * Please see LICENSE file located in the project root for more information. */ 'use strict'; const loadTasks = require('load-grunt-tasks'); const {copyConfig, babelConfig} = require('./build/grunt-config'); const {cleanBuild, startRenderer, makeRelease} = require('./build/grunt-task'); module.exports = function (grunt) { loadTasks(grunt, {pattern: ['grunt-contrib-copy', 'grunt-babel']}); grunt.initConfig({ copy: copyConfig, babel: babelConfig }); grunt.registerTask('clean', 'Cleans up the output files.', cleanBuild); grunt.registerTask('render', 'Starts the electron renderer.', startRenderer); grunt.registerTask('dist', 'Makes a distributable release.', makeRelease); grunt.registerTask('compile', ['clean', 'babel', 'copy']); grunt.registerTask('start', ['compile', 'render']); };
Rename dist script as compile
change: Rename dist script as compile
JavaScript
mit
ajaysreedhar/kongdash,ajaysreedhar/kongdash,ajaysreedhar/kongdash
3ab63bdd39ba71a9ad8a7cd0dbb768dc26daec64
Gruntfile.js
Gruntfile.js
module.exports = function (grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ handlebars: { compile: { options: { amd: ['handlebars', 'handlebars.helpers'], namespace: 'templates', partialRegex: /.*/, partialsPathRegex: /\/partials\//, processName: function (path) { return path.match(/([\w]+)\.hbs/)[1]; } }, files: { 'static/templates/compiled.js': ['src/views/**/*.hbs'] } } }, jshint: { server: { options: { jshintrc: true }, src: ['src/**/*.js'] }, client: { options: { jshintrc: true }, src: ['static/js/**/*.js'] }, tests: { options: { jshintrc: true }, src: ['test/**/*.js'] } }, sass: { dist: { files: { 'static/css/styles.css': 'static/css/styles.scss' } } }, watch: { handlebars: { files: ['src/views/**/*.hbs'], tasks: ['handlebars'] }, jshint: { files: ['src/**/*.js', 'static/js/**/*.js', 'test/**/*.js'], tasks: ['jshint'] }, sass: { files: ['static/css/**/*.scss'], tasks: ['sass'] } } }); grunt.registerTask('default', ['handlebars', 'jshint', 'sass']); };
module.exports = function (grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ handlebars: { compile: { options: { amd: ['handlebars', 'handlebars.helpers'], namespace: 'templates', partialRegex: /.*/, partialsPathRegex: /\/partials\//, processName: function (path) { return path.match(/([\w]+)\.hbs/)[1]; } }, files: { 'static/templates/compiled.js': ['src/views/**/*.hbs'] } } }, jshint: { server: { options: { jshintrc: true }, src: ['src/**/*.js'] }, client: { options: { jshintrc: true, ignores: ['static/js/**/*.min.js'] }, src: ['static/js/**/*.js'] }, tests: { options: { jshintrc: true }, src: ['test/**/*.js'] } }, sass: { dist: { files: { 'static/css/styles.css': 'static/css/styles.scss' } } }, watch: { handlebars: { files: ['src/views/**/*.hbs'], tasks: ['handlebars'] }, jshint: { files: ['src/**/*.js', 'static/js/**/*.js', 'test/**/*.js'], tasks: ['jshint'] }, sass: { files: ['static/css/**/*.scss'], tasks: ['sass'] } } }); grunt.registerTask('default', ['handlebars', 'jshint', 'sass']); };
Set jshint to ignore minified files.
Set jshint to ignore minified files.
JavaScript
mit
neogeek/nodejs-starter-kit
0cfe946a2394d1f3def3c55763b856c15ab29892
Gruntfile.js
Gruntfile.js
const zipFileName = 'extension.zip'; module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), webstoreUpload: { accounts: { default: { cli_auth: true, // eslint-disable-line publish: true, client_id: process.env.CLIENT_ID, // eslint-disable-line client_secret: process.env.CLIENT_SECRET, // eslint-disable-line refresh_token: process.env.REFRESH_TOKEN // eslint-disable-line } }, extensions: { refinedGitHub: { appID: 'hlepfoohegkhhmjieoechaddaejaokhf', // App ID from chrome webstore publish: true, zip: zipFileName } } } }); grunt.loadNpmTasks('grunt-webstore-upload'); grunt.registerTask('default', ['webstoreUpload']); };
const zipFileName = 'extension.zip'; module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), webstore_upload: { // eslint-disable-line accounts: { default: { cli_auth: true, // eslint-disable-line publish: true, client_id: process.env.CLIENT_ID, // eslint-disable-line client_secret: process.env.CLIENT_SECRET, // eslint-disable-line refresh_token: process.env.REFRESH_TOKEN // eslint-disable-line } }, extensions: { refinedGitHub: { appID: 'hlepfoohegkhhmjieoechaddaejaokhf', // App ID from chrome webstore publish: true, zip: zipFileName } } } }); grunt.loadNpmTasks('grunt-webstore-upload'); grunt.registerTask('default', ['webstore_upload']); };
Change deploy Grunt taskname to snake case
Change deploy Grunt taskname to snake case
JavaScript
mit
sindresorhus/refined-github,busches/refined-github,jgierer12/refined-github,busches/refined-github,sindresorhus/refined-github,jgierer12/refined-github
1d7088cfae8aa64ff834e1d20911df15af06f745
Gruntfile.js
Gruntfile.js
module.exports = function(grunt) { // load grunt tasks from package.json require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ clean: { dist: [ 'dist', 'robert/**/*.pyc', ] }, compass: { dist: { options: { sassDir: 'robert/static/sass/', cssDir: 'robert/static/css/', outputStyle: 'compressed', } } }, concurrent: { server: { options: { logConcurrentOutput: true, }, tasks: ['watch', 'shell:devserver'] } }, shell: { options: { stdout: true, stderr: true, }, devserver: { command: 'python run_devserver.py', }, freeze: { command: 'python freeze.py', } }, watch: { options: { livereload: true, }, python: { files: ['robert/**/*.py'], tasks: [] }, sass: { files: ['robert/static/sass/*.scss'], tasks: ['compass'], }, templates: { files: ['robert/templates/*.html'], tasks: [], }, articles: { files: ['articles/*.md'], tasks: [], }, }, }); grunt.registerTask('default', [ 'build', 'concurrent:server', ]); grunt.registerTask('build', [ 'clean', 'compass', 'shell:freeze', ]); };
module.exports = function(grunt) { // load grunt tasks from package.json require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ clean: { dist: [ 'dist', 'robert/**/*.pyc', ], postbuild: [ 'dist/static/sass', ], }, compass: { dist: { options: { sassDir: 'robert/static/sass/', cssDir: 'robert/static/css/', outputStyle: 'compressed', } } }, concurrent: { server: { options: { logConcurrentOutput: true, }, tasks: ['watch', 'shell:devserver'] } }, shell: { options: { stdout: true, stderr: true, }, devserver: { command: 'python run_devserver.py', }, freeze: { command: 'python freeze.py', } }, watch: { options: { livereload: true, }, python: { files: ['robert/**/*.py'], tasks: [] }, sass: { files: ['robert/static/sass/*.scss'], tasks: ['compass'], }, templates: { files: ['robert/templates/*.html'], tasks: [], }, articles: { files: ['articles/*.md'], tasks: [], }, }, }); grunt.registerTask('default', [ 'build', 'concurrent:server', ]); grunt.registerTask('build', [ 'clean:dist', 'compass', 'shell:freeze', 'clean:postbuild', ]); };
Add a postbuild task to grunt to remove unnecessary build artifacts
Add a postbuild task to grunt to remove unnecessary build artifacts
JavaScript
mit
thusoy/robertblag,thusoy/robertblag,thusoy/robertblag
0e854b660501e3bcdf01071392b9ab0ec8b9a5f0
src/components/Iframe/index.js
src/components/Iframe/index.js
import React, {PropTypes} from 'react' import injectSheet from '../../utils/jss' function Iframe({src, sheet: {classes}}) { return <iframe src={src} className={classes.iframe} /> } Iframe.propTypes = { src: PropTypes.string.isRequired, sheet: PropTypes.object.isRequired } const styles = { iframe: { width: '100%', height: '100%', border: 0 } } export default injectSheet(styles)(Iframe)
import React, {PropTypes} from 'react' import injectSheet from '../../utils/jss' function Iframe({src, sheet: {classes}}) { return <iframe src={src} className={classes.iframe} /> } Iframe.propTypes = { src: PropTypes.string.isRequired, sheet: PropTypes.object.isRequired } const styles = { iframe: { width: '100%', height: '100vh', minHeight: 50, border: 0, display: 'block' } } export default injectSheet(styles)(Iframe)
Fix iframe height after migration to vh
Fix iframe height after migration to vh
JavaScript
mit
cssinjs/cssinjs
b0fc06384fcddaf293c5c9f66b4a49b8f2f7c56b
app/index.js
app/index.js
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import Routes from './routes' import Store from './store' ReactDOM.render( <Provider store={Store}> <Routes /> </Provider>, document.getElementById('root') )
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import Routes from './routes' import Store from './store' ReactDOM.render( <Provider store={Store}> <Routes /> </Provider>, document.getElementById('application') )
Fix the root component id.
Fix the root component id.
JavaScript
mit
rhberro/the-react-client,rhberro/the-react-client
ccc12a7dae4b01674f9bc76efaefef5f901852e2
src/components/preview/Code.js
src/components/preview/Code.js
// @flow import { PureComponent } from 'react' import Lowlight from 'react-lowlight' import js from 'highlight.js/lib/languages/javascript' import type { Children } from 'react' type Props = { className:string, children: Children, } Lowlight.registerLanguage('js', js) export default class Code extends PureComponent<void, Props, void> { static languageClassNamePattern = /\s*language-([\w-]+)\s*/ // for lint props: Props get language (): string { const match = (this.props.className || '').match(Code.languageClassNamePattern) const lang = (match && match[1]) || '' return Lowlight.hasLanguage(lang) ? lang : '' } get value (): string { return this.props.children[0] } render () { return ( <Lowlight language={this.language} value={this.value} inline /> ) } }
// @flow import { PureComponent } from 'react' import Lowlight from 'react-lowlight' import type { Children } from 'react' import langMap from 'settings/languageNameMap' type Props = { className:string, children: Children, } type State = { language: string, } export default class Code extends PureComponent<void, Props, State> { static languageClassNamePattern = /\s*language-([\w-]+)\s*/ constructor (props: Props) { super(props) this.state = { language: '', } } state: State componentWillMount () { this.registerLanguage(this.props.className) } componentWillReceiveProps ({ className }: Props) { this.registerLanguage(className) } async registerLanguage (className: string) { const match = (className || '').match(Code.languageClassNamePattern) const langName = (match && match[1]) || '' const lang = langMap[langName] if (lang == null) { this.setState({ language: '' }) } else if (Lowlight.hasLanguage(langName)) { this.setState({ language: langName }) } else { Lowlight.registerLanguage(langName, await lang.load()) this.setState({ language: langName }) } } get value (): string { return this.props.children[0] } render () { return ( <Lowlight language={this.state.language} value={this.value} inline /> ) } }
Load language config for highlight.js dynamically
Load language config for highlight.js dynamically
JavaScript
mit
izumin5210/OHP,izumin5210/OHP
92334651e178d2760434e8e1923ba691c69f448c
src/events/mouse-dispatcher.js
src/events/mouse-dispatcher.js
var slice = [].slice exports = function mouseDispatcher(name, fn) { return function(x, y) { var target = document.elementFromPoint(x, y) || document var event = new MouseEvent(name, { bubbles: true, clientX: x, clientY: y }) fn.apply(event, slice.call(arguments, 2)) target.dispatchEvent(event) } }
var slice = [].slice exports = function mouseDispatcher(name, fn) { return function(clientX, clientY, shiftKey, ctrlKey, altKey, metaKey) { var target = document.elementFromPoint(clientX, clientY) || document var event = new MouseEvent(name, { bubbles: true, clientX: clientX, clientY: clientY, shiftKey: shiftKey, ctrlKey: ctrlKey, altKey: altKey, metaKey: metaKey }) fn.apply(event, slice.call(arguments, 6)) target.dispatchEvent(event) } }
Handle modifier keys in mouse dispatcher
Handle modifier keys in mouse dispatcher
JavaScript
unlicense
freedraw/core,freedraw/core
112f786717f405f0b2b708fe67d4b6df780386ea
models/Author.js
models/Author.js
var keystone = require('keystone'); var Types = keystone.Field.Types; /** * Author Model * ========== */ var Author = new keystone.List('Author'); Author.add({ firstName: { type: Types.Text, initial: true, required: true, index: true }, lastName: { type: Types.Text, initial: true, required: true, index: true }, email: { type: Types.Email }, affiliations: { type: Types.Relationship, ref: 'Organization', many: true }, }); /** * Registration */ Author.defaultColumns = 'firstName, lastName'; Author.register();
var keystone = require('keystone'); var Types = keystone.Field.Types; /** * Author Model * ========== */ var Author = new keystone.List('Author'); Author.add({ name: { type: Types.Name, initial: true, required: true, index: true }, email: { type: Types.Email }, affiliations: { type: Types.Relationship, ref: 'Organization', many: true }, }); /** * Registration */ Author.defaultColumns = 'name, affiliations'; Author.register();
Use single name field for authors
Use single name field for authors
JavaScript
mit
zharley/papers,zharley/papers
2ba85374c28132da84e6f7679bb1bb4f487db14d
webpack.config.js
webpack.config.js
var path = require('path'); var webpack = require('webpack'); var Clean = require('clean-webpack-plugin'); var webpackConfig = require("./webpack-base-config"); webpackConfig.entry = path.resolve(__dirname, 'src/main.js'); if (process.env.npm_lifecycle_event === 'release') { webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({ compress: {warnings: false}, output: {comments: false} })); } else { webpackConfig.plugins.push(new Clean(['dist'])); } webpackConfig.output = { path: path.resolve(__dirname, 'dist'), publicPath: '<%=baseUrl%>/', filename: 'clappr.js', library: 'Clappr', libraryTarget: 'umd', }; module.exports = webpackConfig;
var path = require('path'); var webpack = require('webpack'); var Clean = require('clean-webpack-plugin'); var webpackConfig = require("./webpack-base-config"); webpackConfig.entry = path.resolve(__dirname, 'src/main.js'); if (process.env.npm_lifecycle_event === 'release') { webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({ compress: {warnings: false}, output: {comments: false} })); } else { webpackConfig.plugins.push(new Clean(['dist'], {verbose: false})); } webpackConfig.output = { path: path.resolve(__dirname, 'dist'), publicPath: '<%=baseUrl%>/', filename: 'clappr.js', library: 'Clappr', libraryTarget: 'umd', }; module.exports = webpackConfig;
Set verbose to false in webpack clean plugin
Set verbose to false in webpack clean plugin
JavaScript
bsd-3-clause
flavioribeiro/clappr,clappr/clappr,flavioribeiro/clappr,clappr/clappr,clappr/clappr,flavioribeiro/clappr
d341843ff99eeb5b3371e8e13420363366f2d8bf
js/components/games/DeployButton.react.js
js/components/games/DeployButton.react.js
"use strict"; var _ = require('mori'); var Router = require('react-router'); var React = require('react'); var mori = require("mori"); var UnitCell = require('../board/UnitCell.react.js'); var GameStore = require('../../stores/GameStore.js'); var ProfileLink = require('../common/ProfileLink.react.js'); var GameActions = require('../../actions/GameActions.js'); module.exports = React.createClass({ render: function () { var game = this.props.game; var state = _.getIn(game, ["board", "state"]); var stash = _.getIn(game, ["board", "stash", this.props.playerCode]); var originalStash = _.getIn(this.props.originalGame, ["board", "stash", this.props.playerCode]); var css = "btn btn-info"; if("deploy" === state) { if(_.isEmpty(originalStash)) { css = "hide"; } else if(!_.isEmpty(stash)) { css = "btn btn-default disabled"; } } else { css = "hide"; } return ( <a onClick={this.click} className={css}>Deploy</a> ); }, click: function click(ev) { GameActions.deployGame(this.props.game); } });
"use strict"; var _ = require('mori'); var Router = require('react-router'); var React = require('react'); var mori = require("mori"); var UnitCell = require('../board/UnitCell.react.js'); var GameStore = require('../../stores/GameStore.js'); var ProfileLink = require('../common/ProfileLink.react.js'); var GameActions = require('../../actions/GameActions.js'); module.exports = React.createClass({ render: function () { var game = this.props.game; var stash = _.getIn(game, ["board", "stash", this.props.playerCode]); var originalGame = this.props.originalGame; var state = _.getIn(originalGame, ["board", "state"]); var originalStash = _.getIn(originalGame, ["board", "stash", this.props.playerCode]); console.log(state) var css = "btn btn-info"; if("deploy" === state) { if(_.isEmpty(originalStash)) { css = "hide"; } else if(!_.isEmpty(stash)) { css = "btn btn-default disabled"; } } else { css = "hide"; } return ( <a onClick={this.click} className={css}>Deploy</a> ); }, click: function click(ev) { GameActions.deployGame(this.props.game); } });
Fix deploy button for second player
Fix deploy button for second player
JavaScript
mit
orionsbelt-battlegrounds/frontend,orionsbelt-battlegrounds/frontend,orionsbelt-battlegrounds/frontend
4012357932dc0d9acb17076cd321affa6d94cb81
src/ggrc/assets/javascripts/components/assessment/info-pane/info-pane.js
src/ggrc/assets/javascripts/components/assessment/info-pane/info-pane.js
/*! Copyright (C) 2017 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/assessment/info-pane/info-pane.mustache'); /** * Assessment Specific Info Pane View Component */ GGRC.Components('assessmentInfoPane', { tag: 'assessment-info-pane', template: tpl, viewModel: { define: { isLocked: { type: 'htmlbool', value: false } }, instance: {} } }); })(window.can, window.GGRC);
/*! Copyright (C) 2017 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/assessment/info-pane/info-pane.mustache'); /** * Assessment Specific Info Pane View Component */ GGRC.Components('assessmentInfoPane', { tag: 'assessment-info-pane', template: tpl, viewModel: { define: { mappedSnapshots: { value: function () { return []; } }, controls: { get: function () { return this.attr('mappedSnapshots') .filter(function (item) { return item.child_type === 'Control'; }); } }, relatedInformation: { get: function () { return this.attr('mappedSnapshots') .filter(function (item) { return item.child_type !== 'Control'; }); } } }, instance: null, getSnapshotQuery: function () { var relevantFilters = [{ type: this.attr('instance.type'), id: this.attr('instance.id'), operation: 'relevant' }]; return GGRC.Utils.QueryAPI .buildParam('Snapshot', {}, relevantFilters, [], []); }, requestQuery: function (query) { var dfd = can.Deferred(); this.attr('isLoading', true); GGRC.Utils.QueryAPI .batchRequests(query) .done(function (response) { var type = Object.keys(response)[0]; var values = response[type].values; dfd.resolve(values); }) .fail(function () { dfd.resolve([]); }) .always(function () { this.attr('isLoading', false); }.bind(this)); return dfd; }, loadSnapshots: function () { var query = this.getSnapshotQuery(); return this.requestQuery(query); } }, init: function () { this.viewModel.attr('mappedSnapshots') .replace(this.viewModel.loadSnapshots()); }, events: { '{viewModel.instance} related_destinations': function () { console.info('Was related_destinations called!!!!', arguments); } } }); })(window.can, window.GGRC);
Add Extra Loading Logic to Assessment Info Pane Component
Add Extra Loading Logic to Assessment Info Pane Component
JavaScript
apache-2.0
AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core
e2fb55b5ff165df0f58e4cdeffeb1c34f49fe382
angular-toggle-switch.js
angular-toggle-switch.js
angular.module('toggle-switch', ['ng']).directive('toggleSwitch', function() { return { restrict: 'EA', replace: true, scope: { model: '=' }, template: '<div class="switch" ng-click="toggle()"><div class="switch-animate switch-off" ng-class="{\'switch-off\': !model, \'switch-on\': model}"><span class="switch-left">On</span><span class="knob">&nbsp;</span><span class="switch-right">Off</span></div></div>', link: function($scope, element, attrs) { if ($scope.model == null) { $scope.model = false; } return $scope.toggle = function() { return $scope.model = !$scope.model; }; } }; });
angular.module('toggle-switch', ['ng']).directive('toggleSwitch', function() { return { restrict: 'EA', replace: true, scope: { model: '=' }, template: '<div class="switch" ng-click="toggle()"><div class="switch-animate" ng-class="{\'switch-off\': !model, \'switch-on\': model}"><span class="switch-left">On</span><span class="knob">&nbsp;</span><span class="switch-right">Off</span></div></div>', link: function($scope, element, attrs) { if ($scope.model == null) { $scope.model = false; } return $scope.toggle = function() { return $scope.model = !$scope.model; }; } }; });
Remove default class switch-off (fix css bug when a switcher is set to true by default)
Remove default class switch-off (fix css bug when a switcher is set to true by default)
JavaScript
mit
JeromeSadou/angular-toggle-switch,cgarvis/angular-toggle-switch,JumpLink/angular-toggle-switch,nilpath/angular-toggle-switch,razvanz/angular-toggle-switch,zachlysobey/angular-toggle-switch,ProtonMail/angular-toggle-switch,nilpath/angular-toggle-switch,JeromeSadou/angular-toggle-switch,chris110408/angular-toggle-switch,JumpLink/angular-toggle-switch
56733b29e6b79dd0b7b00f7a9fe778b209ceaa73
backend/server/apikey.js
backend/server/apikey.js
// apikey module validates the apikey argument used in the call. It // caches the list of users to make lookups faster. module.exports = function(users) { 'use strict'; let apikeyCache = require('./apikey-cache')(users); let httpStatus = require('http-status'); // whiteList contains paths that don't require // a valid apikey. let whiteList = { "/login": true, "/socket.io/socket.io.js": true, "/socket.io/": true }; // validateAPIKey Looks up the apikey. If none is specified, or a // bad key is passed then abort the calls and send back an 401. return function *validateAPIKey(next) { if (!(this.path in whiteList)) { let UNAUTHORIZED = httpStatus.UNAUTHORIZED; let apikey = this.query.apikey || this.throw(UNAUTHORIZED, 'Not authorized'); let user = yield apikeyCache.find(apikey); if (! user) { this.throw(UNAUTHORIZED, 'Not authorized'); } this.reqctx = { user: user }; } yield next; }; };
// apikey module validates the apikey argument used in the call. It // caches the list of users to make lookups faster. module.exports = function(users) { 'use strict'; let apikeyCache = require('./apikey-cache')(users); let httpStatus = require('http-status'); // whiteList contains paths that don't require // a valid apikey. let whiteList = { "/login": true }; // validateAPIKey Looks up the apikey. If none is specified, or a // bad key is passed then abort the calls and send back an 401. return function *validateAPIKey(next) { if (!(this.path in whiteList)) { let UNAUTHORIZED = httpStatus.UNAUTHORIZED; let apikey = this.query.apikey || this.throw(UNAUTHORIZED, 'Not authorized'); let user = yield apikeyCache.find(apikey); if (! user) { this.throw(UNAUTHORIZED, 'Not authorized'); } this.reqctx = { user: user }; } yield next; }; };
Remove console statement. Cleanup whitelist since socket.io paths will never been seen in route mount point.
Remove console statement. Cleanup whitelist since socket.io paths will never been seen in route mount point.
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
0222a20e870c475b0d3c979ad3d09d0c0ea69706
lib/assets/javascripts/dashboard/data/authenticated-user-model.js
lib/assets/javascripts/dashboard/data/authenticated-user-model.js
var Backbone = require('backbone'); module.exports = Backbone.Model.extend({ defaults: { username: '', avatar_url: '' }, url: function () { return '//' + this.getHost() + '/api/v3/me'; }, getHost: function () { var currentHost = window.location.host; return this.get('host') ? this.get('host') : currentHost; } });
var Backbone = require('backbone'); module.exports = Backbone.Model.extend({ defaults: { username: '', avatar_url: '' }, url: function () { return `//${this.getHost()}/api/v1/get_authenticated_users`; }, getHost: function () { var currentHost = window.location.host; return this.get('host') ? this.get('host') : currentHost; } });
Change AuthenticatedUser URL to query /v1/get_authenticated_users instead of /v3/me
Change AuthenticatedUser URL to query /v1/get_authenticated_users instead of /v3/me
JavaScript
bsd-3-clause
CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb
a939f2794cac08ee94baf53c3fe5587b3f122725
rollup.config.js
rollup.config.js
/** * NOTE: This file must only use node v0.12 features + ES modules. */ import babel from 'rollup-plugin-babel'; import json from 'rollup-plugin-json'; import babelrc from 'babelrc-rollup'; const pkg = require('./package.json'); const external = Object.keys(pkg.dependencies).concat(['path', 'fs']); export default { entry: 'src/index.js', plugins: [ json(), babel(babelrc()) ], external: external, targets: [ { format: 'cjs', dest: pkg['main'] }, { format: 'es6', dest: pkg['jsnext:main'] } ] };
/** * NOTE: This file must only use node v0.12 features + ES modules. */ import babel from 'rollup-plugin-babel'; import json from 'rollup-plugin-json'; import babelrc from 'babelrc-rollup'; var pkg = require('./package.json'); var external = Object.keys(pkg.dependencies).concat(['path', 'fs']); export default { entry: 'src/index.js', plugins: [ json(), babel(babelrc()) ], external: external, targets: [ { format: 'cjs', dest: pkg['main'] }, { format: 'es6', dest: pkg['jsnext:main'] } ] };
Use `var` instead of `const` for node 0.12 support.
Use `var` instead of `const` for node 0.12 support.
JavaScript
mit
alangpierce/decaffeinate,decaffeinate/decaffeinate,alangpierce/decaffeinate,eventualbuddha/decaffeinate,decaffeinate/decaffeinate,alangpierce/decaffeinate,eventualbuddha/decaffeinate
df4079541ec0ca698bbabedf176b164f25833551
rollup.config.js
rollup.config.js
import commonjs from 'rollup-plugin-commonjs'; import babel from 'rollup-plugin-babel'; import uglify from 'rollup-plugin-uglify'; import replace from 'rollup-plugin-replace'; import resolve from 'rollup-plugin-node-resolve'; const env = process.env.NODE_ENV; const config = { output: { name: 'react-uncontrolled-form', format: 'umd', globals: {react: 'React'} }, external: ['react'], plugins: [ resolve({jsnext: true}), commonjs({include: 'node_modules/**'}), babel({exclude: 'node_modules/**'}), replace({'process.env.NODE_ENV': JSON.stringify(env)}) ] }; if (env === 'production') { config.plugins.push( uglify({ compress: { pure_getters: true, unsafe: true, unsafe_proto: true, passes: 2, } }) ); } export default config;
import commonjs from 'rollup-plugin-commonjs'; import babel from 'rollup-plugin-babel'; import uglify from 'rollup-plugin-uglify'; import replace from 'rollup-plugin-replace'; import resolve from 'rollup-plugin-node-resolve'; const env = process.env.NODE_ENV; const config = { output: { name: 'react-uncontrolled-form', format: 'umd', globals: {react: 'React'} }, external: ['react'], plugins: [ resolve({jsnext: true}), commonjs({include: 'node_modules/**'}), babel({exclude: 'node_modules/**'}), replace({'process.env.NODE_ENV': JSON.stringify(env)}) ] }; if (env === 'production') { config.plugins.push( uglify({ compress: { pure_getters: true, unsafe: true, unsafe_proto: true } }) ); } export default config;
Remove unnecessary uglify `passes` property
Remove unnecessary uglify `passes` property
JavaScript
mit
ericvaladas/formwood
e2ce6b77eabc0cfabe06e443298734e8629ad8c2
src/index.js
src/index.js
define([ "text!src/welcome.md" ], function(welcomeMessage) { var commands = codebox.require("core/commands"); var dialogs = codebox.require("utils/dialogs"); var File = codebox.require("models/file"); // About dialog commands.register({ id: "about.show", title: "Application: About", shortcuts: [ "mod+shift+a" ], run: function() { return dialogs.alert("About Codebox"); } }); // Welcome message commands.register({ id: "about.welcome", title: "Application: Welcome", run: function() { return commands.run("file.open", { file: File.buffer("welcome.md", welcomeMessage) }) } }); });a
define([ "text!src/welcome.md" ], function(welcomeMessage) { var commands = codebox.require("core/commands"); var dialogs = codebox.require("utils/dialogs"); var File = codebox.require("models/file"); // About dialog commands.register({ id: "about.show", title: "Application: About", run: function() { return dialogs.alert("About Codebox"); } }); // Welcome message commands.register({ id: "about.welcome", title: "Application: Welcome", run: function() { return commands.run("file.open", { file: File.buffer("welcome.md", welcomeMessage) }) } }); });a
Remove shortcut for about dialog
Remove shortcut for about dialog
JavaScript
apache-2.0
etopian/codebox-package-about,etopian/codebox-package-about,CodeboxIDE/package-about,CodeboxIDE/package-about
22bab20dd6ef60c7a372257c41d8a026c73b477a
src/index.js
src/index.js
/* @flow */ import './vendor'; import ReactDOM from 'react-dom'; import routes from './routes'; setTimeout(() => { ReactDOM.render(routes, document.querySelector('#webedit')); }, 500);
/* @flow */ import './vendor'; import ReactDOM from 'react-dom'; import routes from './routes'; document.addEventListener('DOMContentLoaded', () => { ReactDOM.render(routes, document.querySelector('#webedit')); });
Use a dom ready event instead of timeout speculations
Use a dom ready event instead of timeout speculations
JavaScript
mit
blinkenrocket/webedit-react,blinkenrocket/webedit-react
aabdea65e3187b6b267896464b86333dcc3233d5
src/index.js
src/index.js
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter, Route } from 'react-router-dom'; import './styles/index.css'; import Background from './components/Background'; import Footer from './components/Footer'; import Header from './components/Header'; import ScrollToTop from './components/ScrollToTop'; import Home from './scenes/Home'; import Store from './scenes/Store'; import registerServiceWorker from './registerServiceWorker'; import './i18n'; if (process.env.NODE_ENV === 'production') { window.Raven .config('https://0ddfcefcf922465488c2dde443f9c9d5@sentry.io/230876') .install(); } ReactDOM.render( <BrowserRouter> <ScrollToTop> <Background /> <Header /> <Route exact path="/" component={Home} /> <Route path="/store" component={Store} /> <Footer /> </ScrollToTop> </BrowserRouter>, document.getElementById('root'), ); registerServiceWorker();
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router, Redirect, Route, Switch, } from 'react-router-dom'; import './styles/index.css'; import Background from './components/Background'; import Footer from './components/Footer'; import Header from './components/Header'; import ScrollToTop from './components/ScrollToTop'; import Home from './scenes/Home'; import Store from './scenes/Store'; import registerServiceWorker from './registerServiceWorker'; import './i18n'; if (process.env.NODE_ENV === 'production') { window.Raven .config('https://0ddfcefcf922465488c2dde443f9c9d5@sentry.io/230876') .install(); } ReactDOM.render( <Router> <ScrollToTop> <Background /> <Header /> <Switch> <Route exact path="/" component={Home} /> <Route path="/store" component={Store} /> <Redirect from="*" to="/" /> </Switch> <Footer /> </ScrollToTop> </Router>, document.getElementById('root'), ); registerServiceWorker();
Add Switch and Redirect for Router
Add Switch and Redirect for Router
JavaScript
mit
ELTCOIN/website
ee50f51a89fc140102d3b6d576762d453443299e
src/index.js
src/index.js
// Return Promise const imageMerge = (sources = []) => new Promise(resolve => { // Load sources const images = sources.map(source => new Promise(resolve => { const img = new Image(); img.onload = () => resolve(Object.assign({}, source, {img})); img.src = source.src; })); // Create canvas const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); // When sources have loaded Promise.all(images) .then(images => { // Set canvas dimensions canvas.width = Math.max(...images.map(image => image.img.width)); canvas.height = Math.max(...images.map(image => image.img.height)); // Draw images to canvas images.forEach(image => ctx.drawImage(image.img, image.x || 0, image.y || 0)); // Resolve data uri resolve(canvas.toDataURL()); }); }); module.exports = imageMerge;
// Return Promise const imageMerge = (sources = []) => new Promise(resolve => { // Load sources const images = sources.map(source => new Promise(resolve => { // Convert strings to objects if (typeof source === 'string') { source = {src: source}; } // Resolve source and img when loaded const img = new Image(); img.onload = () => resolve(Object.assign({}, source, {img})); img.src = source.src; })); // Create canvas const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); // When sources have loaded Promise.all(images) .then(images => { // Set canvas dimensions canvas.width = Math.max(...images.map(image => image.img.width)); canvas.height = Math.max(...images.map(image => image.img.height)); // Draw images to canvas images.forEach(image => ctx.drawImage(image.img, image.x || 0, image.y || 0)); // Resolve data uri resolve(canvas.toDataURL()); }); }); module.exports = imageMerge;
Allow array of src strings to be passed in
Allow array of src strings to be passed in
JavaScript
mit
lukechilds/merge-images
5e86a4ba2ebe27b0971d8cb1b569c27dbe3fba37
src/index.js
src/index.js
import { certificates, certificatesAsync } from './certificates'; import { sign, signAsync } from './sign'; import { paramsForDetachedSignature, paramsForDetachedSignatureAsync, } from './params_for_detached_signature'; import { digestValue, digestValueAsync } from './digest_value'; import { cadesplugin } from './constants'; console.log('----', cadesplugin); /** * @class * @name CryptoProProvider * @description Module provide methods for signing requests with Crypto Pro * @author Vitaly Mashanov <vvmashanov@yandex.ru> */ /** * @function * @name isAsync * @description Checking, which method used by browser (Async or NPAPI) * @return {boolean} */ const isAsync = () => (cadesplugin.CreateObjectAsync || false); export default { certificates: isAsync() ? certificatesAsync : certificates, sign: isAsync() ? signAsync : sign, paramsForDetachedSignature: isAsync() ? paramsForDetachedSignatureAsync : paramsForDetachedSignature, digestValue: isAsync() ? digestValueAsync : digestValue, };
import { certificates, certificatesAsync } from './certificates'; import { sign, signAsync } from './sign'; import { paramsForDetachedSignature, paramsForDetachedSignatureAsync, } from './params_for_detached_signature'; import { digestValue, digestValueAsync } from './digest_value'; import { cadesplugin } from './constants'; /** * @class * @name CryptoProProvider * @description Module provide methods for signing requests with Crypto Pro * @author Vitaly Mashanov <vvmashanov@yandex.ru> */ /** * @function * @name isAsync * @description Checking, which method used by browser (Async or NPAPI) * @return {boolean} */ const isAsync = () => (cadesplugin.CreateObjectAsync || false); export default { certificates: isAsync() ? certificatesAsync : certificates, sign: isAsync() ? signAsync : sign, paramsForDetachedSignature: isAsync() ? paramsForDetachedSignatureAsync : paramsForDetachedSignature, digestValue: isAsync() ? digestValueAsync : digestValue, };
Call of console was deleted
Call of console was deleted
JavaScript
mit
VMashanov/crypto-pro-provider,VMashanov/crypto-pro-provider
7d299640acbdb594561f493bd78868a5281e7e4d
app/angular/services/friend_service.js
app/angular/services/friend_service.js
'use strict'; module.exports = function(app) { app.service('FriendService', ['$rootScope', '$http', function($rs, $http) { let allFriends = {}; let getAllFriends = function(emailOrUsername) { return new Promise((resolve, reject) => { let userData = { emailOrUsername: emailOrUsername, }; $http.post(`${$rs.baseUrl}/friends/all`, userData) .then((friends) => { allFriends.friends = friends.data; resolve(); }) .catch((err) => { console.log('error getting all friends'); }); }); } let addFriend = function(friendId) { let friendData = { _id: friendId, }; $http.post(`${$rs.baseUrl}/friends/add`, friendData) .then((res) => { console.log(res.data); }) .catch((err) => { console.log(err.data); }); }; return { getAllFriends: getAllFriends, addFriend: addFriend, data: { allFriends: allFriends, }, } }]); }
'use strict'; module.exports = function(app) { app.service('FriendService', ['$rootScope', '$http', function($rs, $http) { let data = { allFriends: {}, }; let getAllFriends = function(emailOrUsername) { let userData = { emailOrUsername: emailOrUsername, }; return $http.post(`${$rs.baseUrl}/friends/all`, userData) .then((friends) => { data.allFriends.friends = friends.data; }) .catch((err) => { console.log('error getting all friends'); }); } let addFriend = function(friendId) { let friendData = { _id: friendId, }; return $http.post(`${$rs.baseUrl}/friends/add`, friendData) .then((res) => { console.log(res.data); }) .catch((err) => { console.log(err.data); }); }; return { getAllFriends: getAllFriends, addFriend: addFriend, data: data, } }]); }
Remove promises returning data from Friend Service. Unused.
Remove promises returning data from Friend Service. Unused.
JavaScript
mit
sendjmoon/GolfFourFriends,sendjmoon/GolfFourFriends
db8294dc10fb9240bacbdc65e724d884d81b74c7
src/components/GlobalSearch.js
src/components/GlobalSearch.js
import React, { Component, findDOMNode } from 'react'; import styles from './GlobalSearch.scss'; export default class GlobalSearch extends Component { render () { return ( <input ref='searchBox' placeholder={this.props.placeholder} className={styles['gs-input']} onChange={this.props.onChange} onKeyUp={this.props.onKeyUp} onFocus={this.props.onFocus} onClick={() => { findDOMNode(this).select(); }} /> ); }; }; GlobalSearch.propTypes = { placeholder: React.PropTypes.string, onFocus: React.PropTypes.func.isRequired, onChange: React.PropTypes.func.isRequired, onKeyUp: React.PropTypes.func.isRequired, styles: React.PropTypes.object };
import React, { Component } from 'react'; import { findDOMNode } from 'react-dom'; import styles from './GlobalSearch.scss'; export default class GlobalSearch extends Component { render () { return ( <input ref='searchBox' placeholder={this.props.placeholder} className={styles['gs-input']} onChange={this.props.onChange} onKeyUp={this.props.onKeyUp} onFocus={this.props.onFocus} onClick={() => { findDOMNode(this).select(); }} /> ); }; }; GlobalSearch.propTypes = { placeholder: React.PropTypes.string, onFocus: React.PropTypes.func.isRequired, onChange: React.PropTypes.func.isRequired, onKeyUp: React.PropTypes.func.isRequired, styles: React.PropTypes.object };
Swap deprecated findDOMNode to the version from the react-dom module.
Swap deprecated findDOMNode to the version from the react-dom module.
JavaScript
bsd-3-clause
FiviumAustralia/RNSH-Pilot,FiviumAustralia/RNSH-Pilot,FiviumAustralia/RNSH-Pilot
13351bc9c4dc36a27251ed9147ab35b7c771fce5
packages/shared/lib/keys/keyImport.js
packages/shared/lib/keys/keyImport.js
import { getKeys } from 'pmcrypto'; import { readFileAsString } from '../helpers/file'; const PRIVATE_KEY_EXPR = /-----BEGIN PGP PRIVATE KEY BLOCK-----(?:(?!-----)[\s\S])*-----END PGP PRIVATE KEY BLOCK-----/g; export const parseArmoredKeys = (fileString) => { return fileString.match(PRIVATE_KEY_EXPR) || []; }; export const parseKeys = (filesAsStrings = []) => { const armoredKeys = parseArmoredKeys(filesAsStrings.join('\n')); if (!armoredKeys.length) { return []; } return Promise.all(armoredKeys.map(async (armoredPrivateKey) => { try { const [key] = await getKeys(armoredPrivateKey); return key; } catch (e) { // ignore errors } })).then((result) => result.filter(Boolean)); }; export const parseKeyFiles = async (files = []) => { const filesAsStrings = await Promise.all(files.map(readFileAsString)).catch(() => []); return parseKeys(filesAsStrings); };
import { getKeys } from 'pmcrypto'; import { readFileAsString } from '../helpers/file'; const PRIVATE_KEY_EXPR = /-----BEGIN PGP (PRIVATE|PUBLIC) KEY BLOCK-----(?:(?!-----)[\s\S])*-----END PGP (PRIVATE|PUBLIC) KEY BLOCK-----/g; export const parseArmoredKeys = (fileString) => { return fileString.match(PRIVATE_KEY_EXPR) || []; }; export const parseKeys = (filesAsStrings = []) => { const armoredKeys = parseArmoredKeys(filesAsStrings.join('\n')); if (!armoredKeys.length) { return []; } return Promise.all( armoredKeys.map(async (armoredPrivateKey) => { try { const [key] = await getKeys(armoredPrivateKey); return key; } catch (e) { // ignore errors } }) ).then((result) => result.filter(Boolean)); }; export const parseKeyFiles = async (files = []) => { const filesAsStrings = await Promise.all(files.map(readFileAsString)).catch(() => []); return parseKeys(filesAsStrings); };
Update REGEX to accept also public keys
Update REGEX to accept also public keys
JavaScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
31488615c3bd0a3b9ae1399c479dee95d503273e
client/app/validators/messages.js
client/app/validators/messages.js
import Messages from 'ember-cp-validations/validators/messages'; export default Messages.extend({ blank: 'Поле не может быть пустым', email: 'Значение должно быть адресом электронной почты', emailNotFound: 'Адрес не найден', notANumber: 'Значение должно быть числом', notAnInteger: 'Значение должно быть целым числом', positive: 'Значение должно быть положительным числом', invalid: 'Поле заполнено неверно' });
import Messages from 'ember-cp-validations/validators/messages'; export default Messages.extend({ blank: 'Поле не может быть пустым', email: 'Значение должно быть адресом электронной почты', emailNotFound: 'Адрес не найден', notANumber: 'Значение должно быть числом', notAnInteger: 'Значение должно быть целым числом', positive: 'Значение должно быть положительным числом', invalid: 'Поле заполнено неверно', url: 'Значение не является ссылкой' });
Add custom message for invalid url
Add custom message for invalid url
JavaScript
mit
yandex-shri-minsk-2016/yummy-time,yandex-shri-minsk-2016/yummy-time,yandex-shri-minsk-2016/yummy-time
fa117ab8cfa2a82fd20ee9312a8719d604dc010b
test/util/string.js
test/util/string.js
var assert = require('chai').assert; var string = require('../../util/string'); describe('util/string', function () { describe('#isEmpty', function () { it('should return true', function () { assert(true, string.isEmpty()); assert(true, string.isEmpty('')); assert(true, string.isEmpty(' ')); }); it('should return false', function () { assert.isFalse(string.isEmpty('myString')); }); }); });
var assert = require('chai').assert; var string = require('../../util/string'); describe('util/string', function () { describe('#isEmpty', function () { it('should return true', function () { assert.isTrue(string.isEmpty()); assert.isTrue(string.isEmpty('')); assert.isTrue(string.isEmpty(' ')); }); it('should return false', function () { assert.isFalse(string.isEmpty('myString')); }); }); });
Change assert style: use method isTrue
Change assert style: use method isTrue
JavaScript
mit
pmu-tech/grunt-erb
69d8e29ba6c802699c38bec0c9ec65ccdbfa0d95
src/client/StatusBar.js
src/client/StatusBar.js
import React, {Component} from 'react'; import Mousetrap from 'mousetrap'; class StatusBar extends Component { componentDidMount() { Mousetrap.bind(['alt+a'], this.toggleSearchAllWindows); } render() { return ( /* jshint ignore:start */ <label className='status'> <input type='checkbox' checked={this.props.searchAllWindows} onChange={this.onChange} /> <span>Show tabs from <u>a</u>ll windows</span> </label> /* jshint ignore:end */ ); } toggleSearchAllWindows() { this.props.changeSearchAllWindows(!this.props.searchAllWindows); } onChange(evt) { this.props.changeSearchAllWindows(evt.target.checked); } } export default StatusBar;
import React, {Component} from 'react'; import Mousetrap from 'mousetrap'; class StatusBar extends Component { constructor(props) { super(props); this.toggleSearchAllWindows = this.toggleSearchAllWindows.bind(this); this.onChange = this.onChange.bind(this); } componentDidMount() { Mousetrap.bind(['alt+a'], this.toggleSearchAllWindows); } render() { return ( /* jshint ignore:start */ <label className='status'> <input type='checkbox' checked={this.props.searchAllWindows} onChange={this.onChange} /> <span>Show tabs from <u>a</u>ll windows</span> </label> /* jshint ignore:end */ ); } toggleSearchAllWindows() { this.props.changeSearchAllWindows(!this.props.searchAllWindows); } onChange(evt) { this.props.changeSearchAllWindows(evt.target.checked); } } export default StatusBar;
Fix for toggle all windows
Fix for toggle all windows
JavaScript
mit
fewhnhouse/chrome-tab-switcher
878b9eeb01b579bf30ab30d5d8f1e76f34aa4aee
gruntfile.js
gruntfile.js
"use strict"; /*jshint node: true*/ /*eslint-env node*/ module.exports = function (grunt) { require("time-grunt")(grunt); // Since the tasks are split using load-grunt-config, a global object contains the configuration /*global configFile, configuration*/ var ConfigFile = require("./make/configFile.js"); global.configFile = new ConfigFile(); global.configuration = configFile.content; if (configFile.isNew()) { grunt.registerTask("default", function () { var done = this.async(); //eslint-disable-line no-invalid-this grunt.util.spawn({ cmd: "node", args: ["make/config"], opts: { stdio: "inherit" } }, function (error) { if (error) { done(); return; } grunt.util.spawn({ grunt: true, args: ["check", "jsdoc", "default"], opts: { stdio: "inherit" } }, done); }); }); return; } configFile.readSourceFiles(); // Amend the configuration with internal settings configuration.pkg = grunt.file.readJSON("./package.json"); require("load-grunt-config")(grunt); grunt.task.loadTasks("grunt/tasks"); };
"use strict"; /*jshint node: true*/ /*eslint-env node*/ module.exports = function (grunt) { require("time-grunt")(grunt); // Since the tasks are split using load-grunt-config, a global object contains the configuration /*global configFile, configuration*/ var ConfigFile = require("./make/configFile.js"); global.configFile = new ConfigFile(); global.configuration = Object.create(configFile.content); if (configFile.isNew()) { grunt.registerTask("default", function () { var done = this.async(); //eslint-disable-line no-invalid-this grunt.util.spawn({ cmd: "node", args: ["make/config"], opts: { stdio: "inherit" } }, function (error) { if (error) { done(); return; } grunt.util.spawn({ grunt: true, args: ["check", "jsdoc", "default"], opts: { stdio: "inherit" } }, done); }); }); return; } configFile.readSourceFiles(); // Amend the configuration with internal settings configuration.pkg = grunt.file.readJSON("./package.json"); require("load-grunt-config")(grunt); grunt.task.loadTasks("grunt/tasks"); };
Secure content that must not be altered by grunt
Secure content that must not be altered by grunt
JavaScript
mit
ArnaudBuchholz/gpf-js,ArnaudBuchholz/gpf-js
59bdb85cdaa72829024108e3fc1fb71777e389f6
persistance.js
persistance.js
const models = require('./models') const Course = models.Course const path = require('path') const url = require('url') const uri = url.format({ pathname: path.join(__dirname, 'data.db'), protocol: 'nedb:', slashes: true }) const init = function(cb){ models.init(uri, function(err){ if(err){ console.log("Models initialization failed") cb(err) }else{ console.log("Models initialized..") cb() } }) } const saveCourse = function(course, cb){ let c = Course.create(course) c.save().then(function(doc){ cb(null, doc._id) }, function(err){ cb(err) }) } const getCourse = function(course, cb){ Course.findOne(course).then(function(doc){ cb(null, doc) }, function(err){ cb(err) }) } const getCourses = function(course, cb){ Course.find(course).then(function(docs){ cb(null, docs) }, function(err){ cb(err) }) } module.exports = { init, saveCourse, getCourse, getCourses }
const models = require('./models') const Course = models.Course const path = require('path') const url = require('url') const uri = url.format({ pathname: path.join(__dirname, 'data.db'), protocol: 'nedb:', slashes: true }) const init = function(cb){ models.init(uri, function(err){ if(err){ console.log("Models initialization failed") cb(err) }else{ console.log("Models initialized..") cb() } }) } const saveCourse = function(course, cb){ let c = Course.create(course) c.save().then(function(doc){ cb(null, doc._id) }, function(err){ cb(err) }) } const getCourse = function(course, cb){ Course.findOne(course).then(function(doc){ cb(null, doc) }, function(err){ cb(err) }) } const getCourses = function(course, cb){ Course.find(course, {sort: '-startDate'}).then(function(docs){ cb(null, docs) }, function(err){ cb(err) }) } module.exports = { init, saveCourse, getCourse, getCourses }
Sort courses based on startDate
Sort courses based on startDate
JavaScript
mit
nilenso/dhobi-seva-electron,nilenso/dhobi-seva-electron
445300182d2217a85dbb16ca2cee9522ce2c43a0
templates/react-class/index.js
templates/react-class/index.js
import React, { Component } from 'react' class {{file}} extends Component { render () { return ( <div className="{{file}}"> </div> ) } } export default {{file}}
import React, { Component } from 'react' import './{{file}}.css' class {{file}} extends Component { render () { return ( <div className="{{file}}"> </div> ) } } export default {{file}}
Add CSS import to react-class template
Add CSS import to react-class template
JavaScript
isc
tu4mo/teg
5a0f409a488a4a5d3fed358fda6f71cd7dc66676
rollup.config.js
rollup.config.js
import resolve from 'rollup-plugin-node-resolve' import minify from 'rollup-plugin-minify-es' import license from 'rollup-plugin-license' export default { input: 'src/micro-panel-all.js', output: [ { format: 'iife', name: 'codeflask_element', file: 'dist/micro-panel-all.bundle.min.js', sourcemap: true, } ], plugins: [ resolve(), minify(), license({ banner: `@license micro-panel is public domain or available under the Unlicense. lit-element/lit-html/etc. (c) The Polymer Authors under BSD 3-Clause.` }), ], }
import resolve from 'rollup-plugin-node-resolve' import minify from 'rollup-plugin-minify-es' import license from 'rollup-plugin-license' export default { input: 'src/micro-panel-all.js', output: [ { format: 'iife', name: 'codeflask_element', file: 'dist/micro-panel-all.bundle.min.js', sourcemap: true, } ], plugins: [ resolve(), minify(), license({ banner: `@license micro-panel | Unlicense. lit-element/lit-html (c) The Polymer Authors | BSD 3-Clause. CodeFlask (c) Claudio Holanda | MIT. Prism (c) Lea Verou | MIT.` }), ], }
Add codeflask/prism to license banner
Add codeflask/prism to license banner
JavaScript
unlicense
myfreeweb/micro-panel,myfreeweb/micro-panel
c3ebe5ba281de674c18c47130df3aabfac1cd0c8
lib/index.js
lib/index.js
var native = require('../build/Release/dhcurve'), common = require('./common.js'), Promise = require('es6-promises'), _ = require('goal'); function generateKeyPair() { } module.exports = _.mixin({ generateKeyPair: generateKeyPair }, common);
var global = function() { return this; }(); var native = require('../build/Release/dhcurve'), common = require('./common.js'), Promise = global.Promise || require('es6-promises'), _ = require('goal'); function generateKeyPair() { } module.exports = _.mixin({ generateKeyPair: generateKeyPair }, common);
Use Promises in node.js if found.
Use Promises in node.js if found.
JavaScript
mit
mbullington/dhcurve
6e69926de990faac1132b2f434c493750766b101
src/grid-interaction.js
src/grid-interaction.js
import gtr from './global-translation.js' import GraphicsHandler from './graphics-handler.js' import MouseHandler from './mouse-handler.js' import {getIsometricCoordinate} from './isometric-math.js' const CONTAINER = document.querySelector('.graphics-wrapper') export default class GridInteraction { constructor () { this.gh = new GraphicsHandler(CONTAINER) } clear () { this.gh.clearCanvas() } render () { const x = MouseHandler.position().x const y = MouseHandler.position().y if (x !== this.oldX && y !== this.oldY) { this.oldX = x this.oldY = y const gPos = gtr.toGlobal(x, y) const isoCoord = getIsometricCoordinate(gPos.x, gPos.y) this.gh.clearCanvas() this.gh.fillStyle = 'rgba(0, 0, 0, 0.2)' this.gh.drawTriangle(isoCoord.a1, isoCoord.a2, isoCoord.right) } } }
import gtr from './global-translation.js' import GraphicsHandler from './graphics-handler.js' import MouseHandler from './mouse-handler.js' import {getIsometricCoordinate} from './isometric-math.js' const CONTAINER = document.querySelector('.graphics-wrapper') export default class GridInteraction { constructor () { this.gh = new GraphicsHandler(CONTAINER) this.isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints }; } clear () { this.gh.clearCanvas() } render () { const x = MouseHandler.position().x const y = MouseHandler.position().y if (!isTouchDevice && x !== this.oldX && y !== this.oldY) { this.oldX = x this.oldY = y const gPos = gtr.toGlobal(x, y) const isoCoord = getIsometricCoordinate(gPos.x, gPos.y) this.gh.clearCanvas() this.gh.fillStyle = 'rgba(0, 0, 0, 0.2)' this.gh.drawTriangle(isoCoord.a1, isoCoord.a2, isoCoord.right) } } }
Fix that removes hover effect on touch devices
Fix that removes hover effect on touch devices
JavaScript
apache-2.0
drpentagon/isometric-paint,drpentagon/isometric-paint
ac64d509ed40712a7c10c265b642560c0a8a0b6e
scripts/chris.js
scripts/chris.js
var audio = document.getElementById("chris"); function pauseChris() { if (audio.currentTime >= 331000) { audio.pause(); alert(interval); } } function playChris() { audio.currentTime = 952; audio.play(); var interval = setInterval(pauseChris, 1000); } function addChrisButton() { var div = document.getElementById("audioContainer"); var button = document.createElement("BUTTON"); button.setAttribute("type", "button"); button.addEventListener("click", playChris); button.innerText = "Escuchar a Chris"; div.insertBefore(button, audio); } addChrisButton();
var audio = document.getElementById("chris"); function pauseChris() { if (audio.currentTime >= 331000) { audio.pause(); alert(audio.currentTime); } } function playChris() { audio.currentTime = 952; audio.play(); var interval = setInterval(pauseChris, 1000); } function addChrisButton() { var div = document.getElementById("audioContainer"); var button = document.createElement("BUTTON"); button.setAttribute("type", "button"); button.addEventListener("click", playChris); button.innerText = "Escuchar a Chris"; div.insertBefore(button, audio); } addChrisButton();
Check current time after pause
Check current time after pause
JavaScript
mit
nvdaes/nvdaes.github.io,nvdaes/nvdaes.github.io
9adb52b6fd343ca01b4d706a0b87be7fe09b3e7b
src/content_scripts/pivotal_tracker/view/toggle_feature_notifier.js
src/content_scripts/pivotal_tracker/view/toggle_feature_notifier.js
import $ from 'jquery'; export default class ToggleFeatureNotifier { constructor({chromeWrapper}) { this._chromeWrapper = chromeWrapper; this.notify = this.notify.bind(this); } notify() { const optionsUrl = this._chromeWrapper.getURL('src/options/index.html'); prependElementAsChildOf('#tracker', ` <div class="ui message"> <i class="close icon"></i> <div class="header"> WWLTW Extension Update </div> <p>You can enable and disable the WWLTW chrome extension for individual backlogs from the <a href="${optionsUrl}" target="_blank">bottom of the options page.</a></p> </div> `); $('.message .close').on('click', function () { $(this) .closest('.message') .transition('fade') ; }); } } const prependElementAsChildOf = function (parent, html) { let elementContainer = document.createElement('div'); elementContainer.innerHTML = html; $(parent).prepend(elementContainer); };
import $ from 'jquery'; export default class ToggleFeatureNotifier { constructor({chromeWrapper}) { this._chromeWrapper = chromeWrapper; this.notify = this.notify.bind(this); } notify() { const optionsUrl = this._chromeWrapper.getURL('src/options/index.html'); prependElementAsChildOf('#tracker', ` <div class="ui message"> <i class="close icon"></i> <div class="header"> WWLTW Extension Update </div> <p>The WWLTW chrome extension is now disabled by default for all backlogs. You can enable it for any of your backlogs from the <a href="${optionsUrl}" target="_blank">bottom of the options page.</a></p> </div> `); $('.message .close').on('click', function () { $(this) .closest('.message') .transition('fade') ; }); } } const prependElementAsChildOf = function (parent, html) { let elementContainer = document.createElement('div'); elementContainer.innerHTML = html; $(parent).prepend(elementContainer); };
Update copy for toggle feature notification
Update copy for toggle feature notification
JavaScript
isc
oliverswitzer/wwltw-for-pivotal-tracker,oliverswitzer/wwltw-for-pivotal-tracker
931fa47355cb7f5d5bce4d77affb7313211ac043
base.js
base.js
var util = require('util'); module.exports = function (name, defaultMessage, status) { util.inherits(Constructor, Error); return Constructor; function Constructor (message, code) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.name = name; this.message = message || defaultMessage; this.status = status; this.expose = true; if (code !== undefined) this.code = code; } };
var util = require('util'); module.exports = function (name, defaultMessage, status) { util.inherits(Constructor, Error); return Constructor; function Constructor (message, code) { Error.call(this, message || defaultMessage); Error.captureStackTrace(this, arguments.callee); this.name = name; this.status = status; this.expose = true; if (code !== undefined) this.code = code; } };
Set error message using constructor
Set error message using constructor
JavaScript
mit
aantthony/errors
8436bfbd641fd92d85116a4f6683d18fc23282a7
app/common/resourceCache/reducer.js
app/common/resourceCache/reducer.js
import { SET_RESOURCE, MARK_DASHBOARD_DIRTY, RESET_RESOURCE_CACHE } from './actions'; const markAllDirty = (keys, state) => { const dirty = {}; keys.forEach((key) => { dirty[key] = { ...state[key], dirty: true }; }); return dirty; }; const resourceReducer = (state = {}, action) => { switch (action.type) { case MARK_DASHBOARD_DIRTY: return { ...state, ...markAllDirty(action.payload, state), }; case SET_RESOURCE: return { ...state, [action.payload.key]: action.payload.resource, }; case RESET_RESOURCE_CACHE: return {}; default: return state; } }; export default resourceReducer;
import { SET_RESOURCE, MARK_DASHBOARD_DIRTY, RESET_RESOURCE_CACHE } from './actions'; const markAllDirty = (keys, state) => { const dirty = {}; keys.forEach((key) => { if (state[key]) { dirty[key] = { ...state[key], dirty: true }; } }); return dirty; }; const resourceReducer = (state = {}, action) => { switch (action.type) { case MARK_DASHBOARD_DIRTY: return { ...state, ...markAllDirty(action.payload, state), }; case SET_RESOURCE: return { ...state, [action.payload.key]: action.payload.resource, }; case RESET_RESOURCE_CACHE: return {}; default: return state; } }; export default resourceReducer;
Check for the existence of the resource cache key before attempting to make dirty
Check for the existence of the resource cache key before attempting to make dirty
JavaScript
mit
nathanhood/mmdb,nathanhood/mmdb
aea4582982e586365f788ed0d886262da7ab325f
server/controllers/students.js
server/controllers/students.js
//var Teachers = require('../models/teachers'); //var TeacherClasses = require('../models/Teacher_classes'); //var Classes = require('../models/classes'); //var ClassLessons = require('../models/class_lessons'); // var Lessons = require('../models/lessons'); //var RequestedResponses = require('../models/requested_responses'); module.exports = { readyStage : function(io, req, res, next) { // io.on('connection', function(client){ // console.log('Hey, server! A student is ready to learn!'); // client.emit('greeting', 'Hello, student!'); // client.on('responseRecorded', function(data){ // io.sockets.emit('responseRecordedFromStudent', data); // }); // }); res.status(200).send('Hello from the other side'); } };
//var Teachers = require('../models/teachers'); //var TeacherClasses = require('../models/Teacher_classes'); //var Classes = require('../models/classes'); //var ClassLessons = require('../models/class_lessons'); // var Lessons = require('../models/lessons'); //var RequestedResponses = require('../models/requested_responses'); module.exports = { readyStage : function(io, req, res, next) { //var studentInformation = req.body.studentData var pollResponse = { responseId: 1, type: 'thumbs', datetime: new Date(), lessonId: 13, }; io.on('connection', function(student){ student.emit('studentStandby', studentInformation); student.on('teacherConnect', function() { student.emit('teacherConnect'); }); student.on('newPoll', function(data) { student.emit(data); }); setTimeout(function(){ io.sockets.emit('responseFromStudent', pollResponse); }, 5000); }); res.status(200).send('Hello from the other side'); } };
Add student information to connection socket event
Add student information to connection socket event
JavaScript
mit
Jakeyrob/thumbroll,shanemcgraw/thumbroll,Jakeyrob/thumbroll,absurdSquid/thumbroll,shanemcgraw/thumbroll,shanemcgraw/thumbroll,absurdSquid/thumbroll,Jakeyrob/thumbroll
c2c520b16f46f94d9b82251b344f0ef7de158903
app/assets/javascripts/sprangular.js
app/assets/javascripts/sprangular.js
// // General // //= require underscore //= require underscore.string //= require jquery //= require angular //= require angularytics //= require bootstrap-sass-official //= require validity // // Angular specific // //= require angular-translate //= require angular-strap/angular-strap.js //= require angular-strap/angular-strap.tpl.js //= require angular-route //= require angular-sanitize //= require angular-animate //= require sprangular/app
// // General // //= require underscore //= require underscore.string //= require angular //= require angularytics //= require bootstrap-sass-official //= require validity // // Angular specific // //= require angular-translate //= require angular-strap/angular-strap.js //= require angular-strap/angular-strap.tpl.js //= require angular-route //= require angular-sanitize //= require angular-animate //= require sprangular/app
Remove include of jquery, it should be included by host app
Remove include of jquery, it should be included by host app
JavaScript
mit
sprangular/sprangular,sprangular/sprangular,sprangular/sprangular
bee4589cdd421a33aad2d5f25fbd97f777bf2e58
app/assets/javascripts/application.js
app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require tinymce-jquery //= require_tree . //= require_tree ../../../vendor/assets/javascripts/.
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require tinymce-jquery //= require_tree ../../../vendor/assets/javascripts/. //= require_tree .
Move vender js files in manifest so the tree can access them
Move vender js files in manifest so the tree can access them
JavaScript
mit
timmykat/openeffects.org,timmykat/openeffects.org,timmykat/openeffects.org,ofxa/openeffects.org,timmykat/openeffects.org,ofxa/openeffects.org,ofxa/openeffects.org,ofxa/openeffects.org
cbeaf1c062caa2262ab7dc0553069f8708a0d472
app/assets/javascripts/application.js
app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery //= require jquery_ujs //= require jquery.cookie //= require jquery.tools.min //= require knockout //= require superbly-tagfield.min //= require maps //= require map_display //= require map_edit //= require map_popup //= require map_style //= require openlayers_pz //= require ui //= require tags //= require supercool //= require library_message
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery //= require jquery_ujs //= require jquery.cookie //= require jquery.tools.min //= require knockout //= require superbly-tagfield.min //= require maps //= require map_display //= require map_edit //= require map_popup //= require map_style //= require openlayers_pz //= require ui //= require tags //= require library_message
Remove supercool.js from manifest as tag plugin causes errors in IE8.
Remove supercool.js from manifest as tag plugin causes errors in IE8. Looks like the plugin does not support empty jQuery sets for when the field isn't present.
JavaScript
mit
cyclestreets/cyclescape,auto-mat/toolkit,cyclestreets/cyclescape,auto-mat/toolkit,cyclestreets/cyclescape
7db436acaad26f648be77abea89f726e2677434f
app/assets/javascripts/application.js
app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require bootstrap //= require_tree .
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require bootstrap //= require namespace //= require_tree .
Load namespace javascript file before all others
Load namespace javascript file before all others
JavaScript
mit
joshmcarthur/inquest,joshmcarthur/inquest
ae50e4f695c7f68ce839332cc548696d1692e5c0
app/assets/javascripts/districts/controllers/district_modal_controller.js
app/assets/javascripts/districts/controllers/district_modal_controller.js
VtTracker.DistrictModalController = Ember.ObjectController.extend({ needs: ['index'], modalTitle: function() { if (this.get('isNew')) { return 'New District'; } else { return 'Edit District'; } }.property('isNew'), actions: { save: function() { var _self = this; var isNew = _self.get('model.isNew'); _self.get('model').save().then(function() { if (isNew) { _self.set('controllers.index.newDistrict', _self.store.createRecord('district')); } }); } } });
VtTracker.DistrictModalController = Ember.ObjectController.extend({ needs: ['index'], modalTitle: function() { if (this.get('isNew')) { return 'New District'; } else { return 'Edit District'; } }.property('isNew'), actions: { removeModal: function() { this.get('model').rollback(); return true; }, save: function() { var _self = this; var isNew = _self.get('model.isNew'); _self.get('model').save().then(function() { if (isNew) { _self.set('controllers.index.newDistrict', _self.store.createRecord('district')); } }); } } });
Rollback district edit model when modal is closed
Rollback district edit model when modal is closed
JavaScript
mit
bfcoder/vt-ht-tracker,bfcoder/vt-ht-tracker,bfcoder/vt-ht-tracker
b28a11df9533f9fa91945264bb34e51ea977c417
javascripts/extension.js
javascripts/extension.js
$("div.entry").live('click', function( e ) { var item = $(e.target).closest('.entry'); if (!item.find('.entry-actions span.google-plus').length) { item.find(".entry-actions span.tag").after($('<span class="link google-plus">Share to Google+</span>')); } }); $(".entry-actions span.google-plus").live('click', function( e ) { var entry = $(e.target).closest('.entry'); var link = entry.find('a.entry-original').attr('href'); $("#gbg3").trigger('click'); });
$("div.entry").live('click', function( e ) { var link, href, item = $(e.target).closest('.entry'); if (!item.find('.entry-actions span.google-plus').length) { href = 'https://plus.google.com/?status=' + item.find('a.entry-title-link').attr('href'); link = $('<a target="_blank">Share to Google+</a>').attr('href', href); item.find(".entry-actions span.tag").after($('<span class="link google-plus"></span>').html(link)); } });
Create a share link with ?status
Create a share link with ?status
JavaScript
mit
felipeelias/reader_to_plus
3af0ea079e7710f16599de9565c9c9f07f666d4c
lib/ui/views/targetSelector.js
lib/ui/views/targetSelector.js
/* * Copyright 2014 BlackBerry Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var TargetSelectorView, targetSelectorTemplate; TargetSelectorView = Backbone.View.extend({ initialize: function () { // Find the template and save it $.get("pages/targetSelector.html", function (data) { targetSelectorTemplate = data; }); }, render: function () { // Use the template to create the html to display var view = this, showDevices = view.model.get("buildSettings").device, template; if (typeof showDevices === "undefined") { showDevices = true; } this.model.targetFilter(showDevices, function (filteredTargets) { template = _.template(targetSelectorTemplate, { targetNameList: Object.keys(filteredTargets) }); // Put the new html inside of the assigned element view.$el.html(template); }); }, events: { }, display: function (model) { this.model = model; this.render(); } }); module.exports = TargetSelectorView;
/* * Copyright 2014 BlackBerry Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var TargetSelectorView, targetSelectorTemplate; TargetSelectorView = Backbone.View.extend({ initialize: function () { // Find the template and save it $.get("pages/targetSelector.html", function (data) { targetSelectorTemplate = data; }); }, render: function () { // Use the template to create the html to display var view = this, buildSettings = view.model.get("buildSettings"), showDevices = !buildSettings || typeof buildSettings.device === "undefined" || buildSettings.device, template; this.model.targetFilter(showDevices, function (filteredTargets) { template = _.template(targetSelectorTemplate, { targetNameList: Object.keys(filteredTargets) }); // Put the new html inside of the assigned element view.$el.html(template); }); }, events: { }, display: function (model) { this.model = model; this.render(); } }); module.exports = TargetSelectorView;
Fix target selector for imported projects
Fix target selector for imported projects
JavaScript
apache-2.0
blackberry/webworks-gui,blackberry-webworks/webworks-gui,blackberry/webworks-gui,blackberry-webworks/webworks-gui
994654819859ddb726b92d0f4d571bb75bbcbe91
test/support/logger-factory.js
test/support/logger-factory.js
var _ = require('lodash') var assert = require('assert') module.exports = function () { var log = [] return { write: function () { log.push(_(arguments).toArray().join(' ')) }, read: function () { return log }, toString: function () { return log.join('\n') }, assert: function () { var lines = _.toArray(arguments) _.each(lines, function (line, i) { if (line instanceof RegExp) { assert(line.test(log[i]), line.toString() + ' did not match: "' + log[i] + '"') } else { assert.equal(log[i], line) } }) } } }
var _ = require('lodash') var assert = require('assert') module.exports = function () { var log = [] return { write: function () { log.push(_(arguments).toArray().join(' ')) }, read: function () { return log }, toString: function () { return log.join('\n') }, assert: function () { var lines = _.toArray(arguments) try { _.each(lines, function (line, i) { if (line instanceof RegExp) { assert(line.test(log[i]), line.toString() + ' did not match: "' + log[i] + '"') } else { assert.equal(log[i], line) } }) } catch (e) { console.error('Error asserting the log. Full log follows:') console.log(log) throw e } } } }
Make debugging easier by always printing the log
Make debugging easier by always printing the log
JavaScript
mit
testdouble/teenytest,testdouble/teenytest
ed2c390f30ceeb1f5e0ff5618006fb9f1bc778ef
app/users/edit/responsibilities/controller.js
app/users/edit/responsibilities/controller.js
import Controller from '@ember/controller' import { task } from 'ember-concurrency' import QueryParams from 'ember-parachute' import moment from 'moment' const UsersEditResponsibilitiesQueryParams = new QueryParams({}) export default Controller.extend(UsersEditResponsibilitiesQueryParams.Mixin, { setup() { this.get('projects').perform() this.get('supervisees').perform() }, projects: task(function*() { return yield this.store.query('project', { reviewer: this.get('model.id'), include: 'customer', ordering: 'customer__name,name' }) }), supervisees: task(function*() { let supervisor = this.get('model.id') yield this.store.query('worktime-balance', { supervisor, date: moment().format('YYYY-MM-DD') }) return yield this.store.query('user', { supervisor, ordering: 'username' }) }) })
import Controller from '@ember/controller' import { task } from 'ember-concurrency' import QueryParams from 'ember-parachute' import moment from 'moment' const UsersEditResponsibilitiesQueryParams = new QueryParams({}) export default Controller.extend(UsersEditResponsibilitiesQueryParams.Mixin, { setup() { this.get('projects').perform() this.get('supervisees').perform() }, projects: task(function*() { return yield this.store.query('project', { reviewer: this.get('model.id'), include: 'customer', ordering: 'customer__name,name' }) }), supervisees: task(function*() { let supervisor = this.get('model.id') let balances = yield this.store.query('worktime-balance', { supervisor, date: moment().format('YYYY-MM-DD'), include: 'user' }) return balances.mapBy('user') }) })
Use included to fetch supervisees
Use included to fetch supervisees
JavaScript
agpl-3.0
anehx/timed-frontend,adfinis-sygroup/timed-frontend,adfinis-sygroup/timed-frontend,anehx/timed-frontend,adfinis-sygroup/timed-frontend
faa007e535289ee435df9ec4a92f3b229bbd9227
app_server/app/controllers/AdminController.js
app_server/app/controllers/AdminController.js
/** * Admin Controller * @module AdminController */ var rfr = require('rfr'); var Joi = require('joi'); var Boom = require('boom'); var Utility = rfr('app/util/Utility'); var Service = rfr('app/services/Service'); var logger = Utility.createLogger(__filename); function AdminController(server, options) { this.server = server; this.options = options; } var Class = AdminController.prototype; Class.registerRoutes = function () { this.server.route({ method: 'POST', path: '/', config: { auth: false }, handler: this.createAdmin }); }; /* Routes handlers */ Class.createAdmin = function (request, reply) { }; exports.register = function (server, options, next) { var adminController = new AdminController(server, options); server.bind(adminController); adminController.registerRoutes(); next(); }; exports.register.attributes = { name: 'AdminController' };
/** * Admin Controller * @module AdminController */ var rfr = require('rfr'); var Joi = require('joi'); var Boom = require('boom'); var bcrypt = require('bcryptjs'); var Utility = rfr('app/util/Utility'); var Authenticator = rfr('app/policies/Authenticator'); var Service = rfr('app/services/Service'); var logger = Utility.createLogger(__filename); function AdminController(server, options) { this.server = server; this.options = options; } var Class = AdminController.prototype; Class.registerRoutes = function () { this.server.route({ method: 'POST', path: '/', config: { auth: {scope: Authenticator.SCOPE.ADMIN} }, handler: this.createAdmin }); }; /* Routes handlers */ Class.createAdmin = function (request, reply) { var credentials = { username: request.payload.username, password: encrypt(request.payload.password) }; Service.createNewAdmin(credentials) .then(function (admin) { if (!admin || admin instanceof Error) { return reply(Boom.badRequest('Unable to create admin ' + credentials)); } // overwrite with unencrypted password admin.password = request.payload.password; reply(admin).created(); }); }; /* Helpers for everything above */ var encrypt = function (password) { var salt = bcrypt.genSaltSync(10); return bcrypt.hashSync(password, salt); }; exports.register = function (server, options, next) { var adminController = new AdminController(server, options); server.bind(adminController); adminController.registerRoutes(); next(); }; exports.register.attributes = { name: 'AdminController' };
Implement basic create admin with username / password only
Implement basic create admin with username / password only
JavaScript
mit
nus-mtp/worldscope,nus-mtp/worldscope,nus-mtp/worldscope,nus-mtp/worldscope
d01f5941fa4a017d3b4434ba2a4f58b98364ba43
lib/node/nodes/source.js
lib/node/nodes/source.js
'use strict'; var Node = require('../node'); var TYPE = 'source'; var PARAMS = { query: Node.PARAM.STRING() }; var Source = Node.create(TYPE, PARAMS); module.exports = Source; module.exports.TYPE = TYPE; module.exports.PARAMS = PARAMS; Source.prototype.sql = function() { return this.query; }; Source.prototype.setColumnsNames = function(columns) { this.columns = columns; // Makes columns affecting Node.id(). // When a `select * from table` might end in a different set of columns // we want to have a different node. this.setAttributeToModifyId('columns'); }; /** * Source nodes are ready by definition * * @returns {Node.STATUS} */ Source.prototype.getStatus = function() { return Node.STATUS.READY; }; Source.prototype.getAndSetUpdatedAt = function(databaseService, callback) { if (this.updatedAt !== null) { return callback(null, this.updatedAt); } databaseService.getLastUpdatedTimeFromAffectedTables(this.sql(), function(err, lastUpdatedAt) { if (err) { return callback(err); } this.updatedAt = lastUpdatedAt; return callback(null, this.updatedAt); }.bind(this)); };
'use strict'; var Node = require('../node'); var TYPE = 'source'; var PARAMS = { query: Node.PARAM.STRING() }; var Source = Node.create(TYPE, PARAMS, { beforeCreate: function(node) { // Last updated time in source node means data changed so it has to modify node.id node.setAttributeToModifyId('updatedAt'); } }); module.exports = Source; module.exports.TYPE = TYPE; module.exports.PARAMS = PARAMS; Source.prototype.sql = function() { return this.query; }; Source.prototype.setColumnsNames = function(columns) { this.columns = columns; // Makes columns affecting Node.id(). // When a `select * from table` might end in a different set of columns // we want to have a different node. this.setAttributeToModifyId('columns'); }; /** * Source nodes are ready by definition * * @returns {Node.STATUS} */ Source.prototype.getStatus = function() { return Node.STATUS.READY; }; Source.prototype.getAndSetUpdatedAt = function(databaseService, callback) { if (this.updatedAt !== null) { return callback(null, this.updatedAt); } databaseService.getLastUpdatedTimeFromAffectedTables(this.sql(), function(err, lastUpdatedAt) { if (err) { return callback(err); } this.updatedAt = lastUpdatedAt; return callback(null, this.updatedAt); }.bind(this)); };
Make updatedAt modifying node.id in Source nodes
Make updatedAt modifying node.id in Source nodes
JavaScript
bsd-3-clause
CartoDB/camshaft
21cd7291094b7b03a5571287bf3673db3b13006e
lib/panes/output-area.js
lib/panes/output-area.js
/* @flow */ import { CompositeDisposable } from "atom"; import ResizeObserver from "resize-observer-polyfill"; import React from "react"; import { reactFactory, OUTPUT_AREA_URI } from "./../utils"; import typeof store from "../store"; import OutputArea from "./../components/output-area"; export default class OutputPane { element = document.createElement("div"); disposer = new CompositeDisposable(); constructor(store: store) { this.element.classList.add("hydrogen", "watch-sidebar"); // HACK: Dispatch a window resize Event for the slider history to recompute // We should use native ResizeObserver once Atom ships with a newer version of Electron // Or fork react-rangeslider to fix https://github.com/whoisandie/react-rangeslider/issues/62 const resizeObserver = new ResizeObserver(this.resize); resizeObserver.observe(this.element); reactFactory( <OutputArea store={store} />, this.element, null, this.disposer ); } resize = () => { window.dispatchEvent(new Event("resize")); }; getTitle = () => "Hydrogen Output Area"; getURI = () => OUTPUT_AREA_URI; getDefaultLocation = () => "right"; getAllowedLocations = () => ["left", "right", "bottom"]; destroy() { this.disposer.dispose(); this.element.remove(); } }
/* @flow */ import { CompositeDisposable, Disposable } from "atom"; import ResizeObserver from "resize-observer-polyfill"; import React from "react"; import { reactFactory, OUTPUT_AREA_URI } from "./../utils"; import typeof store from "../store"; import OutputArea from "./../components/output-area"; export default class OutputPane { element = document.createElement("div"); disposer = new CompositeDisposable(); constructor(store: store) { this.element.classList.add("hydrogen", "watch-sidebar"); // HACK: Dispatch a window resize Event for the slider history to recompute // We should use native ResizeObserver once Atom ships with a newer version of Electron // Or fork react-rangeslider to fix https://github.com/whoisandie/react-rangeslider/issues/62 const resizeObserver = new ResizeObserver(this.resize); resizeObserver.observe(this.element); this.disposer.add( new Disposable(() => { if (store.kernel) store.kernel.outputStore.clear(); }) ); reactFactory( <OutputArea store={store} />, this.element, null, this.disposer ); } resize = () => { window.dispatchEvent(new Event("resize")); }; getTitle = () => "Hydrogen Output Area"; getURI = () => OUTPUT_AREA_URI; getDefaultLocation = () => "right"; getAllowedLocations = () => ["left", "right", "bottom"]; destroy() { this.disposer.dispose(); this.element.remove(); } }
Reset output store if pane is closed
Reset output store if pane is closed
JavaScript
mit
nteract/hydrogen,nteract/hydrogen,xanecs/hydrogen,rgbkrk/hydrogen
616729f152d9f513bf02ad3b0f41a21fbc89761a
lib/instagram.js
lib/instagram.js
var config = { clientId: '', clientSecret: '', hashTag: 'ruisrock2014' } var getIg = function(){ var ig = require('instagram-node').instagram(); ig.use({ client_id: config.clientId, client_secret: config.clientSecret}); return ig; } var parseIgMediaObject = function(media){ return { link: media.link, title: (media.caption==null)?"":media.caption.text, thumbnail: media.images.thumbnail.url, small_image: media.images.low_resolution.url, image: media.images.standard_resolution.url, likes: media.likes.count, tags: media.tags } } var parseIgMedia = function(medias){ var data = []; medias.forEach(function(media){ data.push(parseIgMediaObject(media)); }); return data; } module.exports = { tagMedia: function(req, res) { try{ getIg().tag_media_recent(config.hashTag, function(err, medias, pagination, limit) { if(err) throw new Error("Virhe"); res.send(JSON.stringify({status: 200, media: parseIgMedia(medias)})); }); }catch(err){ res.send(500, JSON.stringify({status: 500, error: err.message})); } } }
var config = { clientId: '', clientSecret: '', hashTag: 'ruisrock2014' } var getIg = function(){ var ig = require('instagram-node').instagram(); ig.use({ client_id: config.clientId, client_secret: config.clientSecret}); return ig; } var parseIgMediaObject = function(media){ return { link: media.link, title: (media.caption==null)?"":media.caption.text, thumbnail: media.images.thumbnail.url, small_image: media.images.low_resolution.url, image: media.images.standard_resolution.url, likes: media.likes.count, tags: media.tags } } var parseIgMedia = function(medias){ var data = []; medias.forEach(function(media){ data.push(parseIgMediaObject(media)); }); return data; } module.exports = { tagMedia: function(req, res) { try{ getIg().tag_media_recent(config.hashTag, function(err, medias, pagination, limit) { if(err)res.send(500); else res.send(JSON.stringify({media: parseIgMedia(medias)})); }); }catch(err){ res.send(500); } } }
Send 500 every now and then
Send 500 every now and then
JavaScript
mit
futurice/festapp-server,futurice/sec-conference-server,0is1/festapp-server,futurice/sec-conference-server
a5f3d39929b4886ae28711d607c05275bfab74ca
dev/_/components/js/comparisonSetCollection.js
dev/_/components/js/comparisonSetCollection.js
AV.ComparisonSetCollection = Backbone.Collection.extend({ url: AV.URL('set.json'), updateURL: function() { this.url = AV.URL('set.json'); } });
AV.ComparisonSetCollection = Backbone.Collection.extend({ url: AV.URL('set'),//'.json'), updateURL: function() { this.url = AV.URL('set');//'.json'); } });
Remove .json from the set url
Remove .json from the set url
JavaScript
bsd-3-clause
Swarthmore/juxtaphor,Swarthmore/juxtaphor
c488bae8b97a3a9207d1aa0bbea424c92d493df0
lib/handlers/providers/index.js
lib/handlers/providers/index.js
"use strict"; var Anyfetch = require('anyfetch'); module.exports.get = function get(req, res, next) { var anyfetchClient = new Anyfetch(req.accessToken.token); anyfetchClient.getDocuments({ fields: 'facets.providers' }, function updated(err, anyfetchRes) { if(!err) { var providers = anyfetchRes.body.facets.providers; res.send({ 'count': providers.length }); } next(err); }); };
"use strict"; var Anyfetch = require('anyfetch'); module.exports.get = function get(req, res, next) { var anyfetchClient = new Anyfetch(req.accessToken.token); anyfetchClient.getDocuments({ fields: 'facets.providers' }, function updated(err, anyfetchRes) { if(!err) { var providers = anyfetchRes.body.facets.providers; res.send({ 'count': providers ? providers.length || 0 }); } next(err); }); };
Fix for missing providers length
Fix for missing providers length
JavaScript
mit
AnyFetch/companion-server
fea9882a1d77bae8f5710c79af3cd17677e97345
client/js/helpers/rosetexloader.js
client/js/helpers/rosetexloader.js
'use strict'; /** * @note Returns texture immediately, but doesn't load till later. */ var ROSETexLoader = {}; ROSETexLoader.load = function(path, callback) { var tex = DDS.load(path, function() { if (callback) { callback(); } }); tex.minFilter = tex.magFilter = THREE.LinearFilter; return tex; };
'use strict'; /** * @note Returns texture immediately, but doesn't load till later. */ var ROSETexLoader = {}; ROSETexLoader.load = function(path, callback) { var tex = DDS.load(path, function() { if (callback) { callback(); } }); tex.minFilter = tex.magFilter = THREE.LinearFilter; tex.path = path; return tex; };
Set .path in dds textures for debugging.
Set .path in dds textures for debugging.
JavaScript
agpl-3.0
brett19/rosebrowser,Jiwan/rosebrowser,exjam/rosebrowser,exjam/rosebrowser,Jiwan/rosebrowser,brett19/rosebrowser
bb6c53c86c6f9aabf70fd3cd70a885f2083ed790
app.js
app.js
'use strict'; /** * Imports. */ const express = require('express'); /** * Initialize Express. */ const app = express(); // Setup locals variable in config/index.js. app.locals = require('./config'); // Configure express app based on local configuration. app.set('env', app.locals.express.env); /** * Routing. */ // Root: app.get('/', (req, res) => { res.send('Hi, I\'m Blink!'); }); // Api root: app.use('/api', require('./api')); // API Version 1 app.use('/api/v1', require('./api/v1')); /** * Listen. */ app.listen(app.locals.express.port, () => { app.locals.logger.info(`Blink is listening on port:${app.locals.express.port} env:${app.get('env')}`); }); module.exports = app;
'use strict'; /** * Imports. */ const express = require('express'); const http = require('http'); /** * Initialize Express. */ const app = express(); // Setup locals variable in config/index.js. app.locals = require('./config'); // Configure express app based on local configuration. app.set('env', app.locals.express.env); /** * Routing. */ // Root: app.get('/', (req, res) => { res.send('Hi, I\'m Blink!'); }); // Api root: app.use('/api', require('./api')); // API Version 1 app.use('/api/v1', require('./api/v1')); /** * Create server. */ const server = http.createServer(app); server.listen(app.locals.express.port, () => { const address = server.address(); app.locals.logger.info(`Blink is listening on port:${address.port} env:${app.locals.express.env}`); }); module.exports = app;
Print actual port number in server init log
Print actual port number in server init log
JavaScript
mit
DoSomething/blink,DoSomething/blink
650756852a9ff4011afe2e662495066fdce079e8
app.js
app.js
#!/usr/bin/env node /* * SQL API loader * =============== * * node app [environment] * * environments: [development, test, production] * */ var _ = require('underscore'); // sanity check arguments var ENV = process.argv[2]; if (ENV != 'development' && ENV != 'production' && ENV != 'test') { console.error("\n./app [environment]"); console.error("environments: [development, test, production]"); process.exit(1); } // set Node.js app settings and boot global.settings = require(__dirname + '/config/settings'); var env = require(__dirname + '/config/environments/' + ENV); _.extend(global.settings, env); // kick off controller var app = require(global.settings.app_root + '/app/controllers/app'); app.listen(global.settings.node_port, global.settings.node_host, function() { console.log("CartoDB SQL API listening on " + global.settings.node_host + ":" + global.settings.node_port); });
#!/usr/bin/env node /* * SQL API loader * =============== * * node app [environment] * * environments: [development, test, production] * */ var _ = require('underscore'); // sanity check arguments var ENV = process.argv[2]; if (ENV != 'development' && ENV != 'production' && ENV != 'test') { console.error("\n./app [environment]"); console.error("environments: [development, test, production]"); process.exit(1); } // set Node.js app settings and boot global.settings = require(__dirname + '/config/settings'); var env = require(__dirname + '/config/environments/' + ENV); _.extend(global.settings, env); // kick off controller if ( ! global.settings.base_url ) global.settings.base_url = '/api/*'; var app = require(global.settings.app_root + '/app/controllers/app'); app.listen(global.settings.node_port, global.settings.node_host, function() { console.log("CartoDB SQL API listening on " + global.settings.node_host + ":" + global.settings.node_port + " with base_url " + global.settings.base_url); });
Use a default base_url when not specified in config file
Use a default base_url when not specified in config file Also report the base_url at startup
JavaScript
bsd-3-clause
calvinmetcalf/CartoDB-SQL-API,dbirchak/CartoDB-SQL-API,calvinmetcalf/CartoDB-SQL-API,calvinmetcalf/CartoDB-SQL-API,CartoDB/CartoDB-SQL-API,dbirchak/CartoDB-SQL-API,dbirchak/CartoDB-SQL-API,CartoDB/CartoDB-SQL-API,calvinmetcalf/CartoDB-SQL-API,dbirchak/CartoDB-SQL-API
61eb38969435727ff074b1a95253b577c88c4dfb
common/endpoints/endpoints.service.js
common/endpoints/endpoints.service.js
export default [ 'config', 'hs.common.laymanService', function (config, laymanService) { const me = this; function getItemsPerPageConfig(ds) { return angular.isDefined(ds.paging) && angular.isDefined(ds.paging.itemsPerPage) ? ds.paging.itemsPerPage : config.dsPaging || 20; } angular.extend(me, { endpoints: [ ...(config.status_manager_url ? { type: 'statusmanager', title: 'Status manager', url: config.status_manager_url, } : []), ...(config.datasources || []).map((ds) => { return { url: ds.url, type: ds.type, title: ds.title, datasourcePaging: { start: 0, limit: getItemsPerPageConfig(ds), loaded: false, }, compositionsPaging: { start: 0, limit: getItemsPerPageConfig(ds), }, paging: { itemsPerPage: getItemsPerPageConfig(ds), }, user: ds.user, liferayProtocol: ds.liferayProtocol, originalConfiguredUser: ds.user, getCurrentUserIfNeeded: laymanService.getCurrentUserIfNeeded, }; }), ], }); return me; }, ];
export default [ 'config', 'hs.common.laymanService', function (config, laymanService) { const me = this; function getItemsPerPageConfig(ds) { return angular.isDefined(ds.paging) && angular.isDefined(ds.paging.itemsPerPage) ? ds.paging.itemsPerPage : config.dsPaging || 20; } angular.extend(me, { endpoints: [ ...(config.status_manager_url ? [ { type: 'statusmanager', title: 'Status manager', url: config.status_manager_url, }, ] : []), ...(config.datasources || []).map((ds) => { return { url: ds.url, type: ds.type, title: ds.title, datasourcePaging: { start: 0, limit: getItemsPerPageConfig(ds), loaded: false, }, compositionsPaging: { start: 0, limit: getItemsPerPageConfig(ds), }, paging: { itemsPerPage: getItemsPerPageConfig(ds), }, user: ds.user, liferayProtocol: ds.liferayProtocol, originalConfiguredUser: ds.user, getCurrentUserIfNeeded: laymanService.getCurrentUserIfNeeded, }; }), ], }); return me; }, ];
Correct adding of statusmanager to endpoints
Correct adding of statusmanager to endpoints
JavaScript
mit
hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng
c320a3d7430bf3242bd9147ba7c6e95b09c45e52
src/constants.js
src/constants.js
'use strict'; const isClipMediaRef = { $not: { startTime: 0, endTime: null } } const isClipMediaRefWithTitle = { $not: { startTime: 0, endTime: null }, $not: { title: null }, $not: { title: '' } } module.exports = { isClipMediaRef: isClipMediaRef, isClipMediaRefWithTitle: isClipMediaRefWithTitle }
'use strict'; const isClipMediaRef = { $not: { startTime: 0, endTime: null } } const isClipMediaRefWithTitle = { $not: { startTime: 0, endTime: null }, $and: { $not: { title: null } }, $and: { $not: { title: '' } } } module.exports = { isClipMediaRef: isClipMediaRef, isClipMediaRefWithTitle: isClipMediaRefWithTitle }
Fix broken isClipMediaRefWithTitle for real this time (I think)
Fix broken isClipMediaRefWithTitle for real this time (I think)
JavaScript
agpl-3.0
podverse/podverse-web,podverse/podverse-web,podverse/podverse-web,podverse/podverse-web
c3352aa312e75183b629c3fb7b5948ccf4c2d080
spec/javascripts/reports/components/modal_open_name_spec.js
spec/javascripts/reports/components/modal_open_name_spec.js
import Vue from 'vue'; import Vuex from 'vuex'; import component from '~/reports/components/modal_open_name.vue'; import { mountComponentWithStore } from 'spec/helpers/vue_mount_component_helper'; describe('Modal open name', () => { const Component = Vue.extend(component); let vm; const store = new Vuex.Store({ actions: { openModal: () => {}, }, state: {}, mutations: {}, }); beforeEach(() => { vm = mountComponentWithStore(Component, { store, props: { issue: { title: 'Issue', }, status: 'failed', }, }); }); afterEach(() => { vm.$destroy(); }); it('renders the issue name', () => { expect(vm.$el.textContent.trim()).toEqual('Issue'); }); it('calls openModal actions when button is clicked', () => { spyOn(vm, 'openModal'); vm.$el.click(); expect(vm.openModal).toHaveBeenCalled(); }); });
import Vue from 'vue'; import Vuex from 'vuex'; import component from '~/reports/components/modal_open_name.vue'; import { mountComponentWithStore } from 'spec/helpers/vue_mount_component_helper'; Vue.use(Vuex); describe('Modal open name', () => { const Component = Vue.extend(component); let vm; const store = new Vuex.Store({ actions: { openModal: () => {}, }, state: {}, mutations: {}, }); beforeEach(() => { vm = mountComponentWithStore(Component, { store, props: { issue: { title: 'Issue', }, status: 'failed', }, }); }); afterEach(() => { vm.$destroy(); }); it('renders the issue name', () => { expect(vm.$el.textContent.trim()).toEqual('Issue'); }); it('calls openModal actions when button is clicked', () => { spyOn(vm, 'openModal'); vm.$el.click(); expect(vm.openModal).toHaveBeenCalled(); }); });
Add missing Vue.use in test
Add missing Vue.use in test
JavaScript
mit
stoplightio/gitlabhq,stoplightio/gitlabhq,mmkassem/gitlabhq,stoplightio/gitlabhq,mmkassem/gitlabhq,mmkassem/gitlabhq,stoplightio/gitlabhq,mmkassem/gitlabhq
06cea187980cd50fd4699e689b4191ffb2a4d9fc
src/modules/__specs__/AppView.spec.js
src/modules/__specs__/AppView.spec.js
/*eslint-disable max-nested-callbacks*/ import React from 'react'; import {shallow} from 'enzyme'; import {describe, it} from 'mocha'; import {expect} from 'chai'; import Spinner from 'react-native-gifted-spinner'; import AppView from '../AppView'; describe('<AppView />', () => { describe('isReady', () => { it('should render a <Spinner /> if not ready', () => { const fn = () => {}; const wrapper = shallow( <AppView isReady={false} isLoggedIn={false} dispatch={fn} /> ); expect(wrapper.find(Spinner)).to.have.lengthOf(1); }); it('should not render a <Spinner /> if ready', () => { const fn = () => {}; const wrapper = shallow( <AppView isReady={true} isLoggedIn={false} dispatch={fn} /> ); expect(wrapper.find(Spinner)).to.have.lengthOf(0); }); }); });
/*eslint-disable max-nested-callbacks*/ import React from 'react'; import {shallow} from 'enzyme'; import {describe, it} from 'mocha'; import {expect} from 'chai'; import {ActivityIndicator} from 'react-native'; import AppView from '../AppView'; describe('<AppView />', () => { describe('isReady', () => { it('should render a <ActivityIndicator /> if not ready', () => { const fn = () => {}; const wrapper = shallow( <AppView isReady={false} isLoggedIn={false} dispatch={fn} /> ); expect(wrapper.find(ActivityIndicator)).to.have.lengthOf(1); }); it('should not render a <ActivityIndicator /> if ready', () => { const fn = () => {}; const wrapper = shallow( <AppView isReady={true} isLoggedIn={false} dispatch={fn} /> ); expect(wrapper.find(ActivityIndicator)).to.have.lengthOf(0); }); }); });
Fix AppView test to render activity indicator
Fix AppView test to render activity indicator
JavaScript
mit
WWCJSBoulder/DWClient,justinhaaheim/empower-app,BrianJVarley/simple-offset-pro,salokas/barcodebar,ming-cho/react-native-demo,AcademyPgh/Y1S2-ReplayFX-Schedule,keyifadami/CrewCrossCheck,mandlamag/ESXApp,ming-cho/react-native-demo,yogakurniawan/phoney-mobile,mandlamag/ESXApp,apoi/kahvi,WWCJSBoulder/DWClient,chriswohlfarth/mojifi-app,justinhaaheim/empower-app,chriswohlfarth/mojifi-app,mandlamag/ESXApp,keyifadami/CrewCrossCheck,ericmasiello/TrailReporter,justinhaaheim/empower-app,dominictracey/hangboard,3vangelos/reshout,3vangelos/reshout,AcademyPgh/Y1S2-ReplayFX-Schedule,justinhaaheim/empower-app,dominictracey/hangboard,3vangelos/reshout,fabriziomoscon/pepperoni-app-kit,yogakurniawan/phoney-mobile,keyifadami/CrewCrossCheck,salokas/barcodebar,3vangelos/reshout,AcademyPgh/Y1S2-ReplayFX-Schedule,salokas/barcodebar,keyifadami/CrewCrossCheck,apoi/kahvi,BrianJVarley/simple-offset-pro,keyifadami/CrewCrossCheck,Florenz23/sangoo_04,BrianJVarley/simple-offset-pro,fabriziomoscon/pepperoni-app-kit,Florenz23/sangoo_04,mandlamag/ESXApp,ericmasiello/TrailReporter,ming-cho/react-native-demo,Florenz23/sangoo_04,chriswohlfarth/mojifi-app,yogakurniawan/phoney-mobile,mandlamag/ESXApp,fabriziomoscon/pepperoni-app-kit,apoi/kahvi,fabriziomoscon/pepperoni-app-kit,apoi/kahvi,dominictracey/hangboard,ericmasiello/TrailReporter,chriswohlfarth/mojifi-app,BrianJVarley/simple-offset-pro,ming-cho/react-native-demo,dominictracey/hangboard,Florenz23/sangoo_04,yogakurniawan/phoney-mobile,ericmasiello/TrailReporter,AcademyPgh/Y1S2-ReplayFX-Schedule,3vangelos/reshout,chriswohlfarth/mojifi-app,ming-cho/react-native-demo,WWCJSBoulder/DWClient,justinhaaheim/empower-app,apoi/kahvi,salokas/barcodebar,dominictracey/hangboard,ericmasiello/TrailReporter,fabriziomoscon/pepperoni-app-kit,AcademyPgh/Y1S2-ReplayFX-Schedule,WWCJSBoulder/DWClient
e986ee873dd62c0c333aa7530a1753cef09af39f
chartflo/templates/dashboards/app.js
chartflo/templates/dashboards/app.js
function loadDashboard(page, dashboard) { var url = "/dashboards/page/"+dashboard+"/"+page+"/"; console.log("Getting", url); var spinner = '<div class="text-center" style="width:100%;margin-top:5em;opacity:0.6">'; spinner = spinner + '<i class="fa fa-spinner fa-spin fa-5x fa-fw"></i>\n</div>'; $("#content").html(spinner); axios.get(url).then(function (response) { $('#content').html(response.data); }).catch(function (error) { console.log(error); }); $(".sparkline-embeded").each(function () { var $this = $(this); $this.sparkline('html', $this.data()); }); } $(document).ready(function () { loadDashboard("index", "{{ dashboard }}"); $(".sparkline").each(function () { var $this = $(this); $this.sparkline('html', $this.data()); }); });
function loadDashboard(page, dashboard, destination) { var url = "/dashboards/page/"+dashboard+"/"+page+"/"; console.log("Getting", url); var spinner = '<div class="text-center" style="width:100%;margin-top:5em;opacity:0.6">'; spinner = spinner + '<i class="fa fa-spinner fa-spin fa-5x fa-fw"></i>\n</div>'; if ( destination === undefined) { destination = "#content" } $(destination).html(spinner); axios.get(url).then(function (response) { $(destination).html(response.data); }).catch(function (error) { console.log(error); }); $(".sparkline-embeded").each(function () { //console.log("LOAD"); var $this = $(this); $this.sparkline('html', $this.data()); console.log($this.data()) }); } $(document).ready(function () { loadDashboard("index", "{{ dashboard }}"); $(".sparkline").each(function () { //console.log("INIT"); var $this = $(this); $this.sparkline('html', $this.data()); console.log($this.data()) }); });
Improve the js pages loading function
Improve the js pages loading function
JavaScript
mit
synw/django-chartflo,synw/django-chartflo,synw/django-chartflo
5deb018244d0a06f6d3feccb21b1c0e26864321d
app/controllers/application.js
app/controllers/application.js
import Em from 'ember'; import { task, timeout } from 'ember-concurrency'; const { computed } = Em; var applicationController = Em.Controller.extend({ activeNote: null, hideSidePanel: false, init: function() { Em.run.scheduleOnce('afterRender', () => { $('body div').first().addClass('app-container'); }); }, // data sortedNotes: computed('model.[]', 'model.@each.updatedAt', function() { return this.get('model').sortBy('updatedAt', 'createdAt').reverseObjects(); }), deleteNoteTask: task(function *(note) { yield timeout(150); this.get('model').removeObject(note); if (Em.isEmpty(this.get('model'))) { this.send('createNote'); } else { this.send('showNote', this.get('sortedNotes.firstObject')); } yield note.destroyRecord(); }).drop(), actions: { createNote: function() { this.transitionToRoute('new'); }, deleteNote: function(note) { this.get('deleteNoteTask').perform(note); // this.get('model').removeObject(note); // if (Em.isEmpty(this.get('model'))) { // this.send('createNote'); // } else { // this.send('showNote', this.get('model.lastObject')); // } // note.destroyRecord(); }, // deleteAll: function() { // this.get('notes').forEach(function(note) { // note.destroyRecord(); // }); // }, toggleSidePanelHidden: function() { this.toggleProperty('hideSidePanel'); } } }); export default applicationController;
import Em from 'ember'; import { task, timeout } from 'ember-concurrency'; const { computed } = Em; var applicationController = Em.Controller.extend({ activeNote: null, hideSidePanel: false, init: function() { Em.run.scheduleOnce('afterRender', () => { $('body div').first().addClass('app-container'); }); }, // data sortedNotes: computed('model.[]', 'model.@each.updatedAt', function() { return this.get('model').sortBy('updatedAt', 'createdAt').reverseObjects(); }), deleteNote: task(function *(note) { yield timeout(150); this.get('model').removeObject(note); if (Em.isEmpty(this.get('model'))) { this.send('createNote'); } else { this.send('showNote', this.get('sortedNotes.firstObject')); } yield note.destroyRecord(); }).drop(), actions: { createNote() { this.transitionToRoute('new'); }, deleteNote(note) { this.get('deleteNote').perform(note); }, signOut() { this.get('session').close().then(()=> { this.transitionToRoute('signin'); }); }, toggleSidePanelHidden() { this.toggleProperty('hideSidePanel'); } } }); export default applicationController;
Include a `signOut` action. Make `deleteNote` an e-c task. ES6-ify some function syntax.
Include a `signOut` action. Make `deleteNote` an e-c task. ES6-ify some function syntax.
JavaScript
mit
ddoria921/Notes,ddoria921/Notes
82544193853cd0988ee2536d134d1fa451d8fbb4
day3/solution.js
day3/solution.js
let input = require("fs").readFileSync("./data").toString(); let santaPosition = [0, 0]; let roboSantaPosition = [0, 0]; let uniqueSantaPositions = []; function updateUniquePositions() { if (uniqueSantaPositions.indexOf(santaPosition.toString()) === -1) { uniqueSantaPositions.push(santaPosition.toString()); } if (uniqueSantaPositions.indexOf(roboSantaPosition.toString()) === -1) { uniqueSantaPositions.push(roboSantaPosition.toString()); } } updateUniquePositions(); input.split("").forEach((char, index) => { let currentSantaPos = index % 2 === 0 ? santaPosition : roboSantaPosition; // Part 2 if (char === "^") { currentSantaPos[1]++; } else if (char === "v") { currentSantaPos[1]--; } else if (char === ">") { currentSantaPos[0]++; } else if (char === "<") { currentSantaPos[0]--; } updateUniquePositions(); }); console.log("Houses with at least one present:", uniqueSantaPositions.length);
let input = require("fs").readFileSync("./data").toString(); let santaPosition = [0, 0]; let roboSantaPosition = [0, 0]; let uniqueSantaPositions = []; function updateUniquePositions() { let santaPositionStr = santaPosition.toString(); let roboSantaPositionStr = roboSantaPosition.toString(); if (uniqueSantaPositions.indexOf(santaPositionStr) === -1) { uniqueSantaPositions.push(santaPositionStr); } if (uniqueSantaPositions.indexOf(roboSantaPositionStr) === -1) { uniqueSantaPositions.push(roboSantaPositionStr); } } updateUniquePositions(); input.split("").forEach((char, index) => { let currentSantaPos = index % 2 === 0 ? santaPosition : roboSantaPosition; // Part 2 if (char === "^") { currentSantaPos[1]++; } else if (char === "v") { currentSantaPos[1]--; } else if (char === ">") { currentSantaPos[0]++; } else if (char === "<") { currentSantaPos[0]--; } updateUniquePositions(); }); console.log("Houses with at least one present:", uniqueSantaPositions.length);
Move toString conversions to only happen once.
Move toString conversions to only happen once.
JavaScript
mit
Mark-Simulacrum/advent-of-code-2015,Mark-Simulacrum/advent-of-code-2015,Mark-Simulacrum/advent-of-code-2015,Mark-Simulacrum/advent-of-code-2015
1856ce1b2b89d3d708f38e7bde323446864646c9
js/game.js
js/game.js
class Dice extends React.Component { constructor() { super(); this.state = { value: '', words: this.parseInput(decodeURIComponent(location.search.substring(5))), div: document.createElement("div") }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } parseInput(input) { return input.split('\n\r').map(x => x.split('\n').filter(Boolean)); } handleChange(event) { this.setState({value: event.target.value}); } createChild(text) { var p = document.createElement("p"); p.appendChild(document.createTextNode(text)); return p; } handleSubmit() { var div = this.state.div; while (div.hasChildNodes()) { div.removeChild(div.lastChild); } var words = this.state.words; for(var i = 0; i < words.length; i++) { var random = words[i][Math.floor(Math.random()*(words.length-1))]; div.appendChild(this.createChild(random)); } document.body.appendChild(div); } render() { return ( <div> <input type="button" value="Throw dice" onClick={this.handleSubmit}/> </div> ); } } ReactDOM.render( <Dice />, document.getElementById('root') );
class Dice extends React.Component { constructor() { super(); this.state = { words: this.parseInput(decodeURIComponent(location.search.substring(5))), div: document.createElement("div") }; this.handleSubmit = this.handleSubmit.bind(this); } parseInput(input) { return input.split('\n\r').map(x => x.split('\n').filter(Boolean)); } image(word) { } appendWord(text) { var p = document.createElement("p"); p.appendChild(document.createTextNode(text)); return p; } appendImg(src) { var img = document.createElement("img"); img.className = 'img'; img.src = random; } handleSubmit() { var div = this.state.div; while (div.hasChildNodes()) { div.removeChild(div.lastChild); } var words = this.state.words; for(var i = 0; i < words.length; i++) { var random = words[i][Math.floor(Math.random()*(words.length-1))]; if (this.image(random)) { div.appendChild(this.appendImg(random)); } else { div.appendChild(this.appendWord(random)); } } document.body.appendChild(div); } render() { return ( <div> <input type="button" value="Throw dice" onClick={this.handleSubmit}/> </div> ); } } ReactDOM.render( <Dice />, document.getElementById('root') );
Add function to append img on the page
Add function to append img on the page
JavaScript
mit
testlnord/wurfelspiel,testlnord/wurfelspiel,testlnord/wurfelspiel
212033e54f0d4729b0ade59aaaad19074b388cc0
server/main.js
server/main.js
import { Meteor } from 'meteor/meteor'; import { handleMigration } from './migrations'; Meteor.startup(() => { handleMigration(); });
import { Meteor } from 'meteor/meteor'; import { handleMigration } from './migrations'; import '/imports/minutes'; import '/imports/meetingseries'; Meteor.startup(() => { handleMigration(); });
Fix meteor method not found error by initializing meteor methods on the server
Fix meteor method not found error by initializing meteor methods on the server
JavaScript
mit
RobNeXX/4minitz,Huggle77/4minitz,RobNeXX/4minitz,RobNeXX/4minitz,4minitz/4minitz,Huggle77/4minitz,4minitz/4minitz,Huggle77/4minitz,4minitz/4minitz
08517b8cc97af75922ad40704fc333bdd0cba5fa
test/src/main.js
test/src/main.js
requirejs.config({ baseUrl: 'test', paths: { pvcf: '../../lib/pvcf', when: '../test/vendor/when/when', node: '../test/vendor/when/node', callbacks: '../test/vendor/when/callbacks' } }); requirejs(['pvcf'], function run(pvcf) { var definitions = pvcf.definitions; var ViewDefinition = definitions.ViewDefinition; var TabManager = pvcf.TabManager; // ### View list. ### // # Events # var addEvent = new ViewDefinition('test/templates/addEvent.html', ['test/modules/addEvent.js'], true); // # Tab manager # var tabManager = new TabManager(); var startTab = tabManager.openTab(); startTab.openView(addEvent).done(function () { tabManager.closeTab(startTab); }); tabManager.getContainerElement().appendChild(startTab.getContainerElement()); document.body.appendChild(tabManager.getContainerElement()); });
requirejs.config({ baseUrl: 'test', paths: { pvcf: '../../lib/pvcf', when: '../test/vendor/when/when', node: '../test/vendor/when/node', callbacks: '../test/vendor/when/callbacks' } }); requirejs(['pvcf'], function run(pvcf) { var definitions = pvcf.definitions; var ViewDefinition = definitions.ViewDefinition; var PatternDefinition = definitions.PatternDefinition; var PatternManager = pvcf.PatternManager; var TabManager = pvcf.TabManager; // ### View list ### // # Events # var addEvent = new ViewDefinition('test/templates/addEvent.html', ['test/modules/addEvent.js'], true); var showEvent = new ViewDefinition('test/templates/showEvent.html', ['test/modules/showEvent.js'], true); // # Pattern manager # var patternManager = new PatternManager(); // ### Pattern list ### patternManager.addPattern(new PatternDefinition('event/add', addEvent)); patternManager.addPattern(new PatternDefinition('event/show/:id', showEvent)); // # Tab manager # var tabManager = new TabManager(); document.body.appendChild(tabManager.getContainerElement()); function main() { console.log('Appliaction started!'); } // window.onload actions: var startTab = tabManager.openTab(); startTab.openView(addEvent).done(function () { tabManager.closeTab(startTab); }); tabManager.getContainerElement().appendChild(startTab.getContainerElement()); main(); // window.hashchange actions: window.addEventListener('hashchange', main); });
Extend initialize layer by pattern manager.
Extend initialize layer by pattern manager.
JavaScript
mit
rootsher/pvcf,rootsher/pvcf,rootsher/pvcf
3f90b18a50479eff488ee86fa64a2cc0412716b9
http/code.js
http/code.js
var runScraper = function() { $(this).attr('disabled', true) $(this).addClass('loading').html('Scraping&hellip;') var stocks = $('#stocks_input').val() var escaped_stocks = scraperwiki.shellEscape(stocks) scraperwiki.exec('python tool/pandas_finance.py ' + escaped_stocks, getStocksSuccess) } var getStocksSuccess = function(data) { $('#submitBtn').attr('disabled', false) if (data.indexOf('File "tool/pandas_finance.py"') != -1) { scraperwiki.alert('Error in pandas_finance.py', data, true) $('#submitBtn').removeClass('loading').html('<i class="icon-remove"></i> Error') $('#submitBtn').removeClass('btn-primary').addClass('btn-danger') setTimeout(function() { $('#submitBtn').html('Get Stocks') $('#submitBtn').removeClass('btn-danger').addClass('btn-primary') }, 4000) } else { $('#submitBtn').removeClass('loading').html('<i class="icon-ok"></i> Done') scraperwiki.tool.redirect("/dataset/" + scraperwiki.box) } } $(function() { $('#submitBtn').on('click', runScraper) })
var param_from_input = function(css) { return scraperwiki.shellEscape($(css).val()) } var runScraper = function() { $(this).attr('disabled', true) $(this).addClass('loading').html('Scraping&hellip;') var stocks = param_from_input('#stocks_input') var start_date = param_from_input('#start-date') var end_date = param_from_input('#end-date') var command = ['python tool/pandas_finance.py', stocks, start_date, end_date].join(' ') scraperwiki.exec(command, getStocksSuccess) } var getStocksSuccess = function(data) { $('#submitBtn').attr('disabled', false) if (data.indexOf('File "tool/pandas_finance.py"') != -1) { scraperwiki.alert('Error in pandas_finance.py', data, true) $('#submitBtn').removeClass('loading').html('<i class="icon-remove"></i> Error') $('#submitBtn').removeClass('btn-primary').addClass('btn-danger') setTimeout(function() { $('#submitBtn').html('Get Stocks') $('#submitBtn').removeClass('btn-danger').addClass('btn-primary') }, 4000) } else { $('#submitBtn').removeClass('loading').html('<i class="icon-ok"></i> Done') scraperwiki.tool.redirect("/dataset/" + scraperwiki.box) } } $(function() { $('#submitBtn').on('click', runScraper) })
Send command with date range from web UI.
Send command with date range from web UI.
JavaScript
agpl-3.0
scraperwiki/stock-tool,scraperwiki/stock-tool
a8cb21f70f884c5b854b54f1de85d993ef687aaf
index.ios.js
index.ios.js
let React = require('react-native'); let { AppRegistry, StyleSheet, Text, View, StatusBarIOS } = React; class Meowth extends React.Component { componentWillMount() { StatusBarIOS.setStyle('light-content'); } render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to Meowth </Text> <Text style={styles.instructions}> Subtitle </Text> </View> ); } } var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#084265', }, welcome: { color: '#F5FCFF', fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#CCCCCC', marginBottom: 5, }, }); AppRegistry.registerComponent('meowth', () => Meowth);
let React = require('react-native'); let FreshSetup = require('./src/FreshSetup'); let { AppRegistry, NavigatorIOS, StatusBarIOS, StyleSheet, } = React; class Meowth extends React.Component { componentWillMount() { StatusBarIOS.setStyle('light-content'); } render() { return ( <NavigatorIOS style={styles.container} initialRoute={{ component: FreshSetup, title: 'Welcome', backButtonTitle: 'Back', passProps: { pageId: 'welcome', } }} barTintColor="#084265" tintColor="#ffffff" titleTextColor="#ffffff" /> ); } } var styles = StyleSheet.create({ container: { flex: 1, }, }); AppRegistry.registerComponent('meowth', () => Meowth);
Add router navigation Externalise main component to a separate file
Add router navigation Externalise main component to a separate file
JavaScript
apache-2.0
yrezgui/meowth-ios
495d7a008b1621531cdf39f2d74ac22aee42deac
both/routes/authenticated.js
both/routes/authenticated.js
const authenticatedRoutes = FlowRouter.group({ name: 'authenticated' }); authenticatedRoutes.route( '/', { name: 'index', action() { BlazeLayout.render( 'default', { yield: 'index' } ); } }); authenticatedRoutes.route( '/dashboard', { name: 'dashboard', action() { BlazeLayout.render( 'default', { yield: 'dashboard' } ); } }); authenticatedRoutes.route('/wish-detail/:_id', { name: 'wishDetail', action() { BlazeLayout.render( 'default', { yield: 'wishDetail' } ); } });
const authenticatedRoutes = FlowRouter.group({ name: 'authenticated' }); authenticatedRoutes.route( '/', { name: 'index', action() { BlazeLayout.render( 'default', { yield: 'index' } ); } }); authenticatedRoutes.route( '/dashboard', { name: 'dashboard', action() { BlazeLayout.render( 'default', { yield: 'dashboard' } ); } }); authenticatedRoutes.route('/wish/:_id', { name: 'wishDetail', action() { BlazeLayout.render( 'default', { yield: 'wishDetail' } ); } }); authenticatedRoutes.route('/wish/new', { name: 'wishNew', action() { BlazeLayout.render( 'default', { yield: 'wishNew' } ); } });
Refactor wish-detail -> wish, added new route: wishNew.
Refactor wish-detail -> wish, added new route: wishNew.
JavaScript
mit
lnwKodeDotCom/WeWish,lnwKodeDotCom/WeWish
d0c02bdfc462c2f8bc748e44ce3f5d4552fc58db
background.js
background.js
chrome.webRequest.onBeforeRequest.addListener( (details) => { chrome.tabs.sendMessage(details.tabId, { content: "message" }, () => {}); const startTime = new Date().getTime(); let randNumber; while ((new Date().getTime() - startTime) < 5000) { /* prevent errors on empty fn in loop */ randNumber = Math.random(); } return { cancel: (randNumber + 1) > 0 }; }, { urls: [ "*://*.piguiqproxy.com/*", "*://*.amgload.net/*", "*://*.dsn-fishki.ru/*", "*://*.rcdn.pro/*", "*://*.smcheck.org/*", ] }, ["blocking"] );
chrome.webRequest.onBeforeRequest.addListener( (details) => { chrome.tabs.sendMessage(details.tabId, { content: "message" }, () => {}); const startTime = new Date().getTime(); let randNumber; while ((new Date().getTime() - startTime) < 5000) { /* prevent errors on empty fn in loop */ randNumber = Math.random(); } return { cancel: (randNumber + 1) > 0 }; }, { urls: [ "*://*.piguiqproxy.com/*", "*://*.amgload.net/*", "*://*.dsn-fishki.ru/*", "*://*.rcdn.pro/*", "*://*.smcheck.org/*", "*://*.zmctrack.net/*", ] }, ["blocking"] );
Add new one site to filter
Add new one site to filter
JavaScript
mit
VladReshet/no-ads-forever
ff72938231c463ff7d6ac0eb0b38c229f06e6246
components/Cards/PlaceListingCard/PlaceListingCard.js
components/Cards/PlaceListingCard/PlaceListingCard.js
import React, { PropTypes } from 'react'; import DestinationListingCard from '../DestinationListingCard/DestinationListingCard'; import Badge from '../../Badge/Badge'; import css from './PlaceListingCard.css'; const PlaceListingCard = (props) => { const { name, location, spaceDetail, ...rest, } = props; return ( <DestinationListingCard name={ <span> <Badge className={ css.badge } context="primary" hollow>Place</Badge> { name } </span> } information={ [location, spaceDetail] } { ...rest } /> ); }; PlaceListingCard.propTypes = { name: PropTypes.node, location: PropTypes.node, spaceDetail: PropTypes.node, price: PropTypes.node, priceUnit: PropTypes.node, priceFromLabel: PropTypes.node, }; export default PlaceListingCard;
import React, { PropTypes } from 'react'; import DestinationListingCard from '../DestinationListingCard/DestinationListingCard'; import Badge from '../../Badge/Badge'; import css from './PlaceListingCard.css'; const PlaceListingCard = (props) => { const { name, location, spaceDetail, placeBadgeText, ...rest, } = props; return ( <DestinationListingCard name={ <span> <Badge className={ css.badge } context="primary" hollow>{ placeBadgeText }</Badge> { name } </span> } information={ [location, spaceDetail] } { ...rest } /> ); }; PlaceListingCard.propTypes = { name: PropTypes.node, location: PropTypes.node, spaceDetail: PropTypes.node, placeBadgeText: PropTypes.string, price: PropTypes.node, priceUnit: PropTypes.node, priceFromLabel: PropTypes.node, }; PlaceListingCard.defaultProps = { placeBadgeText: 'Place', }; export default PlaceListingCard;
Allow place badge text to be localised
Allow place badge text to be localised
JavaScript
mit
NGMarmaduke/bloom,appearhere/bloom,NGMarmaduke/bloom,rdjpalmer/bloom,appearhere/bloom,rdjpalmer/bloom,appearhere/bloom,rdjpalmer/bloom,NGMarmaduke/bloom
b33be185ba08eef310536b73278aec60a1a3c3db
test/mock-xhr.js
test/mock-xhr.js
function MockXHR() { this.method = null this.url = null this.data = null this.headers = {} this.readyState = 0 this.status = 0 this.responseText = null } MockXHR.responses = {} MockXHR.prototype.open = function(method, url) { this.method = method this.url = url } MockXHR.prototype.setRequestHeader = function (name, value) { this.headers[name] = value } var origin = (function() { var link = document.createElement('a') link.href = '/' return link.href })() MockXHR.prototype.send = function(data) { this.data = data var xhr = this setTimeout(function() { var path = xhr.url.replace(origin, '/') var handle = MockXHR.responses[path] if (handle) { handle(xhr) } else { console.warn('missing mocked response', path) } }, 100); } MockXHR.prototype.respond = function(status, body) { this.readyState = 4 this.status = status this.responseText = body var event = {} this.onload(event) } MockXHR.prototype.abort = function() { // Do nothing. } MockXHR.prototype.slow = function() { var event = {} this.ontimeout(event) } MockXHR.prototype.error = function() { var event = {} this.onerror(event) }
function MockXHR() { this.method = null this.url = null this.data = null this.headers = {} this.readyState = 0 this.status = 0 this.responseText = null } MockXHR.responses = {} MockXHR.prototype.open = function(method, url) { this.method = method this.url = url } MockXHR.prototype.setRequestHeader = function (name, value) { this.headers[name] = value } var origin = (function() { var link = document.createElement('a') link.href = '/' return link.href })() MockXHR.prototype.send = function(data) { this.data = data var xhr = this setTimeout(function() { var path = xhr.url.replace(origin, '/') var handle = MockXHR.responses[path] if (handle) { handle(xhr) } else { throw 'missing mocked response: ' + path } }, 100); } MockXHR.prototype.respond = function(status, body) { this.readyState = 4 this.status = status this.responseText = body var event = {} this.onload(event) } MockXHR.prototype.abort = function() { // Do nothing. } MockXHR.prototype.slow = function() { var event = {} this.ontimeout(event) } MockXHR.prototype.error = function() { var event = {} this.onerror(event) }
Throw instead of console for linter
Throw instead of console for linter
JavaScript
mit
github/include-fragment-element,github/include-fragment-element
dccdf983e68961fd3cd6d87bd207dc7deb02086b
app/assets/javascripts/tinymce/plugins/uploadimage/plugin.js
app/assets/javascripts/tinymce/plugins/uploadimage/plugin.js
(function() { tinymce.PluginManager.requireLangPack('uploadimage'); tinymce.create('tinymce.plugins.UploadImage', { UploadImage: function(ed, url) { var form, iframe, win, editor = ed; function showDialog() { this.win = editor.windowManager.open({ width: 350 + parseInt(editor.getLang('uploadimage.delta_width', 0), 10), height: 180 + parseInt(editor.getLang('uploadimage.delta_height', 0), 10), url: url + '/dialog.html', }, { plugin_url: url }); } ed.addButton('uploadimage', { title: ed.translate('Insert an image from your computer'), onclick: showDialog, image: url + '/img/uploadimage.png', stateSelector: 'img[data-mce-uploadimage]' }); } }); tinymce.PluginManager.add('uploadimage', tinymce.plugins.UploadImage); })();
(function() { tinymce.PluginManager.requireLangPack('uploadimage'); tinymce.create('tinymce.plugins.UploadImage', { UploadImage: function(ed, url) { var form, iframe, win, editor = ed; function showDialog() { this.win = editor.windowManager.open({ width: 350 + parseInt(editor.getLang('uploadimage.delta_width', 0), 10), height: 180 + parseInt(editor.getLang('uploadimage.delta_height', 0), 10), url: url + '/dialog.html', }, { plugin_url: url }); } // Add a button that opens a window editor.addButton('uploadimage', { tooltip: ed.translate('Insert an image from your computer'), icon : 'image', onclick: showDialog }); // Adds a menu item to the tools menu editor.addMenuItem('uploadimage', { text: ed.translate('Insert an image from your computer'), icon : 'image', context: 'insert', onclick: showDialog }); } }); tinymce.PluginManager.add('uploadimage', tinymce.plugins.UploadImage); })();
Use the default TinyMCE4 image icon
Use the default TinyMCE4 image icon
JavaScript
mit
dancingbytes/tinymce-rails-imageupload,CraigJZ/tinymce-rails-imageupload-1,dancingbytes/tinymce-rails-imageupload,PerfectlyNormal/tinymce-rails-imageupload,PerfectlyNormal/tinymce-rails-imageupload,PerfectlyNormal/tinymce-rails-imageupload,ekubal/tinymce-rails-imageupload,ekubal/tinymce-rails-imageupload,ekubal/tinymce-rails-imageupload,CraigJZ/tinymce-rails-imageupload-1,dancingbytes/tinymce-rails-imageupload,CraigJZ/tinymce-rails-imageupload-1
1ff8ffaf7cc89670e9aa35745f52a605157bc934
build/webpack.config.js
build/webpack.config.js
/** * ownCloud - Music app * * This file is licensed under the Affero General Public License version 3 or * later. See the COPYING file. * * @author Pauli Järvinen <pauli.jarvinen@gmail.com> * @copyright 2020 Pauli Järvinen * */ const path = require('path'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const ESLintPlugin = require('eslint-webpack-plugin'); module.exports = { mode: 'production', entry: { app: '../js/config/index.js', files_music_player: '../js/embedded/index.js' }, output: { filename: 'webpack.[name].js', path: path.resolve(__dirname, '../js/public'), }, resolve: { alias: { 'angular': path.resolve(__dirname, '../js/vendor/angular'), 'lodash': path.resolve(__dirname, '../js/vendor/lodash'), } }, plugins: [ new MiniCssExtractPlugin({filename: 'webpack.app.css'}), new ESLintPlugin({ files: '../js' }) ], module: { rules: [ { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', ], }, { test: /\.(png|svg|jpg|gif)$/, use: [ { loader: 'file-loader', options: { outputPath: 'img/' } } ], } ], }, };
/** * ownCloud - Music app * * This file is licensed under the Affero General Public License version 3 or * later. See the COPYING file. * * @author Pauli Järvinen <pauli.jarvinen@gmail.com> * @copyright 2020 Pauli Järvinen * */ const path = require('path'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const ESLintPlugin = require('eslint-webpack-plugin'); module.exports = { mode: 'production', devtool: 'source-map', entry: { app: '../js/config/index.js', files_music_player: '../js/embedded/index.js' }, output: { filename: 'webpack.[name].js', path: path.resolve(__dirname, '../js/public'), }, resolve: { alias: { 'angular': path.resolve(__dirname, '../js/vendor/angular'), 'lodash': path.resolve(__dirname, '../js/vendor/lodash'), } }, plugins: [ new MiniCssExtractPlugin({filename: 'webpack.app.css'}), new ESLintPlugin({ files: '../js' }) ], module: { rules: [ { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', ], }, { test: /\.(png|svg|jpg|gif)$/, use: [ { loader: 'file-loader', options: { outputPath: 'img/' } } ], } ], }, };
Configure webpack so that `eval` is not used in the development mode
Configure webpack so that `eval` is not used in the development mode Using eval is not allowed by the CSP of newer Nextcloud versions.
JavaScript
agpl-3.0
paulijar/music,owncloud/music,owncloud/music,paulijar/music,paulijar/music,owncloud/music,paulijar/music,owncloud/music,owncloud/music,paulijar/music
d6ed0c7bc74b83ea46887c1afa1da3fd0f7f2481
client/packages/core-app-worona/src/app/settings-app-extension-worona/selectorCreators/index.js
client/packages/core-app-worona/src/app/settings-app-extension-worona/selectorCreators/index.js
import { find } from 'lodash'; export const getSettings = namespace => state => state.settings.collection[namespace]; export const getSetting = (namespace, setting) => state => state.settings.collection[namespace][setting]; export const getSettingById = _id => state => find(state.settings.collection, it => it._id === _id);
import { find } from 'lodash'; export const getSettings = namespace => state => state.settings.collection[namespace]; export const getSetting = (namespace, setting) => state => state.settings.collection[namespace][setting]; export const getSettingsById = _id => state => find(state.settings.collection, item => item._id === _id); export const getSettingById = (_id, setting) => state => find(state.settings.collection, item => item._id === _id)[setting];
Add getSettingById and fix getSettingsById.
Add getSettingById and fix getSettingsById.
JavaScript
mit
worona/worona-app,worona/worona-app
e3fde9655ce25219938afcb8d6aa056adbf1c545
src/components/QuestionForm.js
src/components/QuestionForm.js
import React, {Component} from 'react' import Field from './Field.js' import Select from './Select.js' import Input from './Input.js' import Label from './Label.js' export default class QuestionForm extends Component { handleChange = e => { const {name, value} = e.target this.props.onChange({ [name]: value }) } render() { const { id, number } = this.props.question return ( <form onChange={this.handleChange}> <Field> <Label htmlFor="type">Question Type</Label> <Select id="type" name="type" options={['Text', 'Numeric', 'Multiple - Radio', 'Multiple - Checkbox']} /> </Field> <Field> <Label htmlFor="id">Question ID</Label> <Input value={id} id="id" name="id" /> </Field> <Field> <Label htmlFor="number">Question Number</Label> <Input value={number} id="number" name="number" /> </Field> </form> ) } }
import React, {Component} from 'react' import Field from './Field.js' import Select from './Select.js' import Input from './Input.js' import Label from './Label.js' export default class QuestionForm extends Component { handleChange = e => { const {name, value} = e.target this.props.onChange({ [name]: value }) } render() { const { id, number, title } = this.props.question return ( <form onChange={this.handleChange}> <Field> <Label htmlFor="type">Question Type</Label> <Select id="type" name="type" options={['Text', 'Numeric', 'Multiple - Radio', 'Multiple - Checkbox']} /> </Field> <Field> <Label htmlFor="id">Question ID</Label> <Input value={id} id="id" name="id" /> </Field> <Field> <Label htmlFor="number">Question Number</Label> <Input value={number} id="number" name="number" /> </Field> <Field> <Label htmlFor="title">Question Title</Label> <Input value={title} id="question-title" name="title" /> </Field> <Field> <Label htmlFor="guidance-title">Question Guidance Title</Label> <Input value="" id="question-guidance-title" name="guidance-title" /> </Field> </form> ) } }
Add question title and guidance title fields.
Add question title and guidance title fields.
JavaScript
mit
ONSdigital/eq-author,ONSdigital/eq-author,ONSdigital/eq-author
b0b117554055bb0452c02955965627b00841ca94
packages/strapi-plugin-content-type-builder/admin/src/containers/FormModal/utils/reservedNames.js
packages/strapi-plugin-content-type-builder/admin/src/containers/FormModal/utils/reservedNames.js
const JS_BUILT_IN_OBJECTS = [ 'object', 'function', 'boolean', 'symbol', 'error', 'infinity', 'number', 'math', 'date', ]; const RESERVED_NAMES = ['admin', 'series', 'file', ...JS_BUILT_IN_OBJECTS]; export default RESERVED_NAMES;
const JS_BUILT_IN_OBJECTS = [ 'boolean', 'date', 'error', 'function', 'infinity', 'map', 'math', 'number', 'object', 'symbol', ]; const RESERVED_NAMES = [ 'admin', 'series', 'file', 'news', ...JS_BUILT_IN_OBJECTS, ]; export default RESERVED_NAMES;
Add map and series to RESERVED_NAMES
Add map and series to RESERVED_NAMES
JavaScript
mit
wistityhq/strapi,wistityhq/strapi
f9f8f7103cef43417a246414c311b2bcdad686c3
src/framework/util/util.js
src/framework/util/util.js
export function attemptChangeName(obj, name) { if (!canRedefineValue(obj, 'name')) { return; } Object.defineProperty(obj, 'name', { value: name, }); } export function canRedefineValue(obj, property) { const descriptor = Object.getOwnPropertyDescriptor(obj, property); return descriptor.configurable || descriptor.writable; } function suicide() { throw new TypeError('This method does not generate any actions. It cannot be called.'); } export function killMethod(providerClass, propertyName) { replaceMethod(providerClass, propertyName, suicide); } export function replaceMethod(clazz, propertyName, replacement) { if (!canRedefineValue(clazz, propertyName)) { throw new TypeError(`Could not redefine property ${clazz.name}.${propertyName} because it is both non-writable and non-configurable.`); } Object.defineProperty(clazz, propertyName, { value: replacement }); attemptChangeName(replacement, propertyName); }
export function attemptChangeName(obj, name) { if (!canRedefineValue(obj, 'name')) { return; } Object.defineProperty(obj, 'name', { value: name, }); } export function canRedefineValue(obj, property) { const descriptor = Object.getOwnPropertyDescriptor(obj, property); return descriptor.configurable || descriptor.writable; } function suicide() { throw new TypeError('This method cannot be called.'); } Object.freeze(suicide); export function killMethod(Class, propertyName) { replaceMethod(Class, propertyName, suicide); } export function replaceMethod(clazz, propertyName, replacement) { if (!canRedefineValue(clazz, propertyName)) { throw new TypeError(`Could not redefine property ${clazz.name}.${propertyName} because it is both non-writable and non-configurable.`); } Object.defineProperty(clazz, propertyName, { value: replacement }); attemptChangeName(replacement, propertyName); }
Rename generic methods to use generic names
Rename generic methods to use generic names
JavaScript
mit
foobarhq/reworkjs,reworkjs/reworkjs,reworkjs/reworkjs,reworkjs/reworkjs,foobarhq/reworkjs
9c2f44c60b714ac83ba3a1ca38c0898d4d37e07a
src/helpers.js
src/helpers.js
export function isImage(file) { if (file.type.split('/')[0] === 'image') { return true; } } export function convertBytesToMbsOrKbs(filesize) { let size = ''; // I know, not technically correct... if (filesize >= 1000000) { size = (filesize / 1000000) + ' megabytes'; } else if (filesize >= 1000) { size = (filesize / 1000) + ' kilobytes'; } else { size = filesize + ' bytes'; } return size; } export async function createFileFromUrl(url) { const response = await fetch(url); const data = await response.blob(); const metadata = {type: data.type}; const filename = url.replace(/\?.+/, '').split('/').pop(); return new File([data], filename, metadata); } export function readFile(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = (event) => { resolve(event?.target?.result); }; reader.onerror = (event) => { reader.abort(); reject(event); }; reader.readAsDataURL(file); }); }
export function isImage(file) { if (file.type.split('/')[0] === 'image') { return true; } } export function convertBytesToMbsOrKbs(filesize) { let size = ''; if (filesize >= 1048576) { size = (filesize / 1048576) + ' megabytes'; } else if (filesize >= 1024) { size = (filesize / 1024) + ' kilobytes'; } else { size = filesize + ' bytes'; } return size; } export async function createFileFromUrl(url) { const response = await fetch(url); const data = await response.blob(); const metadata = {type: data.type}; const filename = url.replace(/\?.+/, '').split('/').pop(); return new File([data], filename, metadata); } export function readFile(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = (event) => { resolve(event?.target?.result); }; reader.onerror = (event) => { reader.abort(); reject(event); }; reader.readAsDataURL(file); }); }
Use binary system instead of decimal for size error
:bug: Use binary system instead of decimal for size error
JavaScript
mit
Yuvaleros/material-ui-dropzone
594b03ceb00f0ac76ad015a7380a4c9f23903f50
lib/__tests__/ActionCable-test.js
lib/__tests__/ActionCable-test.js
import React from 'react'; import { shallow } from 'enzyme'; import { expect } from 'chai'; import { ActionCableProvider, ActionCable } from '../index'; test('ActionCable render without children', () => { const node = shallow( <ActionCableProvider> <ActionCable /> </ActionCableProvider> ); expect(node.find(ActionCable)).to.have.length(1); }); test('ActionCable render with children', () => { const node = shallow( <ActionCableProvider> <ActionCable> <div>Hello</div> </ActionCable> </ActionCableProvider> ); expect(node.find(ActionCable)).to.have.length(1); const div = node.find('div') expect(div).to.have.length(1); });
import React from 'react'; import { shallow } from 'enzyme'; import { expect } from 'chai'; import Provider, { ActionCableProvider, ActionCable } from '../index'; test('ActionCable render without children', () => { const node = shallow( <ActionCableProvider> <ActionCable /> </ActionCableProvider> ); expect(node.find(ActionCable)).to.have.length(1); }); test('ActionCable render with children', () => { const node = shallow( <ActionCableProvider> <ActionCable> <div>Hello</div> </ActionCable> </ActionCableProvider> ); expect(node.find(ActionCable)).to.have.length(1); const div = node.find('div') expect(div).to.have.length(1); }); test('Default exporting ActionCableProvider works', () => { const node = shallow( <Provider> <ActionCable /> </Provider> ); expect(node.find(ActionCable)).to.have.length(1); });
Add test for default exporting ActionCableProvider
Add test for default exporting ActionCableProvider
JavaScript
mit
cpunion/react-actioncable-provider