commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
ddedb7d7f88553dfbfcbd494996c2b451997fac2
app/lagniappe/dependencies/Composer.js
app/lagniappe/dependencies/Composer.js
import Dependency from './Dependency' export default class Composer extends Dependency { default() { this.dependencyName = 'PHP Composer' this.required = true } mac() { this.dependencyLink = 'https://github.com/laravel/valet' this.dependencyDocumentation = 'https://laravel.com/docs/5.4/valet' this.dependencyDescription = 'Composer is the defacto package manager for PHP.' this.command = 'composer -V' this.expectedOutput = /Composer version/i this.installCommand = 'brew install composer' this.installRequiresSudo = false this.uninstallCommand = 'brew uninstall composer' this.uninstallRequiresSudo = false } windows() { } linux() { } }
import Dependency from './Dependency' export default class Composer extends Dependency { default() { this.dependencyName = 'PHP Composer' this.required = true } mac() { this.dependencyLink = 'https://getcomposer.org/' this.dependencyDocumentation = 'https://getcomposer.org/doc/' this.dependencyDescription = 'Composer is the defacto package manager for PHP.' this.command = 'composer -V' this.expectedOutput = /Composer version/i this.installCommand = 'brew install composer' this.installRequiresSudo = false this.uninstallCommand = 'brew uninstall composer' this.uninstallRequiresSudo = false } windows() { } linux() { } }
Add proper composer link and docs
Add proper composer link and docs
JavaScript
mit
baublet/lagniappe,baublet/lagniappe
--- +++ @@ -10,8 +10,8 @@ } mac() { - this.dependencyLink = 'https://github.com/laravel/valet' - this.dependencyDocumentation = 'https://laravel.com/docs/5.4/valet' + this.dependencyLink = 'https://getcomposer.org/' + this.dependencyDocumentation = 'https://getcomposer.org/doc/' this.dependencyDescription = 'Composer is the defacto package manager for PHP.' this.command = 'composer -V'
35ca195d9e207577f92e128a70f835949023b29c
test/unit/controllersSpec.js
test/unit/controllersSpec.js
'use strict'; /* jasmine specs for controllers go here */ describe('RootCtrl', function(){ var scope; beforeEach(module('swiftBrowser.controllers')); beforeEach(inject(function($controller) { scope = {}; $controller('RootCtrl', {$scope: scope}); })); it('should list containers', inject(function($httpBackend) { var containers = [ {"count": 10, "bytes": 1234, "name": "foo"}, {"count": 20, "bytes": 2345, "name": "bar"}, ]; $httpBackend.whenGET('/v1/AUTH_abc?format=json') .respond(200, containers); expect(scope.containers).toEqual([]); $httpBackend.flush(); expect(scope.containers).toEqual(containers); })); it('should set sort order', function() { expect(scope.orderProp).toEqual('name'); }); });
'use strict'; /* jasmine specs for controllers go here */ describe('RootCtrl', function(){ var scope; beforeEach(module('swiftBrowser.controllers')); beforeEach(inject(function($controller) { scope = {}; $controller('RootCtrl', {$scope: scope}); })); it('should list containers', inject(function($httpBackend) { var containers = [ {"count": 10, "bytes": 1234, "name": "foo"}, {"count": 20, "bytes": 2345, "name": "bar"}, ]; $httpBackend.whenGET('/v1/AUTH_abc?format=json') .respond(200, containers); expect(scope.containers).toEqual([]); $httpBackend.flush(); expect(scope.containers).toEqual(containers); })); it('should set sort order', function() { expect(scope.orderProp).toEqual('name'); }); }); describe('ContainerCtrl', function(){ var scope; beforeEach(module('swiftBrowser.controllers')); beforeEach(inject(function($controller) { var params = {container: 'cont'}; scope = {}; $controller('ContainerCtrl', {$scope: scope, $routeParams: params}); })); it('should set sort order', function() { expect(scope.orderProp).toEqual('name'); }); it('should set container', function() { expect(scope.container).toEqual('cont'); }); });
Add unit test for ContainerCtrl
Add unit test for ContainerCtrl
JavaScript
apache-2.0
mindware/swift-browser,mgeisler/swift-browser,mindware/swift-browser,zerovm/swift-browser,zerovm/swift-browser,mgeisler/swift-browser
--- +++ @@ -30,3 +30,26 @@ }); }); + + +describe('ContainerCtrl', function(){ + var scope; + + beforeEach(module('swiftBrowser.controllers')); + + beforeEach(inject(function($controller) { + var params = {container: 'cont'}; + scope = {}; + $controller('ContainerCtrl', + {$scope: scope, $routeParams: params}); + })); + + it('should set sort order', function() { + expect(scope.orderProp).toEqual('name'); + }); + + it('should set container', function() { + expect(scope.container).toEqual('cont'); + }); + +});
c6650cbf672b4c5fc2e646e48ced5a0179b0292a
jest.config.js
jest.config.js
module.exports = { testURL: 'http://localhost/', moduleFileExtensions: ['js', 'jsx', 'json', 'styl'], setupFiles: ['<rootDir>/test/jestLib/setup.js'], moduleDirectories: ['src', 'node_modules'], moduleNameMapper: { '^redux-cozy-client$': '<rootDir>/src/lib/redux-cozy-client', '\\.(png|gif|jpe?g|svg)$': '<rootDir>/test/__mocks__/fileMock.js', // identity-obj-proxy module is installed by cozy-scripts '.styl$': 'identity-obj-proxy', '^cozy-client$': 'cozy-client/dist/index' }, transformIgnorePatterns: ['node_modules/(?!cozy-ui|cozy-harvest-lib)'], globals: { __ALLOW_HTTP__: false, __TARGET__: 'browser', __SENTRY_TOKEN__: 'token', cozy: {} } }
module.exports = { testURL: 'http://localhost/', moduleFileExtensions: ['js', 'jsx', 'json', 'styl'], setupFiles: ['<rootDir>/test/jestLib/setup.js'], moduleDirectories: ['src', 'node_modules'], moduleNameMapper: { '^redux-cozy-client$': '<rootDir>/src/lib/redux-cozy-client', '\\.(png|gif|jpe?g|svg)$': '<rootDir>/test/__mocks__/fileMock.js', // identity-obj-proxy module is installed by cozy-scripts '.styl$': 'identity-obj-proxy', '^cozy-client$': 'cozy-client/dist/index' }, transformIgnorePatterns: [ 'node_modules/(?!cozy-ui|cozy-harvest-lib|cozy-keys-lib)' ], globals: { __ALLOW_HTTP__: false, __TARGET__: 'browser', __SENTRY_TOKEN__: 'token', cozy: {} } }
Add cozy-keys-lib exception to transformIgnorePatterns
test: Add cozy-keys-lib exception to transformIgnorePatterns
JavaScript
agpl-3.0
cozy/cozy-home,cozy/cozy-home,cozy/cozy-home
--- +++ @@ -10,7 +10,9 @@ '.styl$': 'identity-obj-proxy', '^cozy-client$': 'cozy-client/dist/index' }, - transformIgnorePatterns: ['node_modules/(?!cozy-ui|cozy-harvest-lib)'], + transformIgnorePatterns: [ + 'node_modules/(?!cozy-ui|cozy-harvest-lib|cozy-keys-lib)' + ], globals: { __ALLOW_HTTP__: false, __TARGET__: 'browser',
243696b8ca118b29a2af95070b613800738b9cc2
app/stores/RendererStore.js
app/stores/RendererStore.js
import EventEmitter from 'events'; import { RESIZE } from '../constants/AppConstants'; class RendererStore extends EventEmitter { constructor(...args) { super(...args); this.data = { width: 0, height: 0, stageWidth: 0, stageHeight: 0, stageCenter: {x: 0,y: 0}, resolution: 1 }; } get(key) { return this.data[key]; } set(key, value) { return this.data[key] = value; } emitChange() { this.emit(RESIZE, this.data); } addChangeListener(callback) { this.on(RESIZE, callback); } } export default new RendererStore();
import EventEmitter from 'events'; import { RESIZE } from '../constants/AppConstants'; class RendererStore extends EventEmitter { constructor(...args) { super(...args); this.data = { width: 0, height: 0, stageWidth: 0, stageHeight: 0, stageCenter: {x: 0,y: 0}, resolution: 1 }; } get(key) { return this.data[key]; } set(key, value) { return this.data[key] = value; } emitChange() { this.emit(RESIZE, this.data); } addChangeListener(callback) { this.on(RESIZE, callback, this.data); } } export default new RendererStore();
Add data to resize callback
Add data to resize callback
JavaScript
mit
edwinwebb/pixi-seed,edwinwebb/pixi-seed,edwinwebb/three-seed
--- +++ @@ -29,7 +29,7 @@ } addChangeListener(callback) { - this.on(RESIZE, callback); + this.on(RESIZE, callback, this.data); } }
68b599377c3906ea90c14957a5601cd57d6276a5
app/templates/_bootstrap.js
app/templates/_bootstrap.js
'use strict'; var sdk = require('flowxo-sdk'), service = require('../'); var credentials = {}; try { credentials = require('../credentials'); } catch(e) {} beforeEach(function() { this.service = service; this.credentials = credentials; this.runner = new sdk.ScriptRunner(service, { credentials: credentials }); });
'use strict'; var sdk = require('flowxo-sdk'), service = require('../'); var credentials = {}; try { credentials = require('../credentials'); } catch(e) {} beforeEach(function() { this.service = service; // Clone the credentials so they can't be globally // overwritten by a test spec this.credentials = JSON.parse(JSON.stringify(credentials)); this.runner = new sdk.ScriptRunner(service, { credentials: this.credentials }); });
Clone credentials on each test run
Clone credentials on each test run
JavaScript
mit
flowxo/generator-flowxo
--- +++ @@ -1,6 +1,7 @@ 'use strict'; + var sdk = require('flowxo-sdk'), - service = require('../'); + service = require('../'); var credentials = {}; try { @@ -9,8 +10,12 @@ beforeEach(function() { this.service = service; - this.credentials = credentials; + + // Clone the credentials so they can't be globally + // overwritten by a test spec + this.credentials = JSON.parse(JSON.stringify(credentials)); + this.runner = new sdk.ScriptRunner(service, { - credentials: credentials + credentials: this.credentials }); });
40e9232ec550c322153e4212344b9d35722cd2e7
blueocean-web/gulpfile.js
blueocean-web/gulpfile.js
// // See https://github.com/jenkinsci/js-builder // var builder = require('@jenkins-cd/js-builder'); // Disable js-builder based linting for now. // Will get fixed with https://github.com/cloudbees/blueocean/pull/55 builder.lint('none'); // Explicitly setting the src paths in order to allow the rebundle task to // watch for changes in the JDL (js, css, icons etc). // See https://github.com/jenkinsci/js-builder#setting-src-and-test-spec-paths builder.src(['src/main/js', 'src/main/less', 'node_modules/@jenkins-cd/design-language']); // // Create the main "App" bundle. // generateNoImportsBundle makes it easier to test with zombie. // builder.bundle('src/main/js/blueocean.js') .withExternalModuleMapping('jquery-detached', 'jquery-detached:jquery2') .inDir('target/classes/io/jenkins/blueocean') .less('src/main/less/blueocean.less') .generateNoImportsBundle();
// // See https://github.com/jenkinsci/js-builder // var builder = require('@jenkins-cd/js-builder'); // Disable js-builder based linting for now. // Will get fixed with https://github.com/cloudbees/blueocean/pull/55 builder.lint('none'); // Explicitly setting the src paths in order to allow the rebundle task to // watch for changes in the JDL (js, css, icons etc). // See https://github.com/jenkinsci/js-builder#setting-src-and-test-spec-paths builder.src(['src/main/js', 'src/main/less', 'node_modules/@jenkins-cd/design-language/dist']); // // Create the main "App" bundle. // generateNoImportsBundle makes it easier to test with zombie. // builder.bundle('src/main/js/blueocean.js') .withExternalModuleMapping('jquery-detached', 'jquery-detached:jquery2') .inDir('target/classes/io/jenkins/blueocean') .less('src/main/less/blueocean.less') .generateNoImportsBundle();
Watch for changes in the JDL package (rebundle)
Watch for changes in the JDL package (rebundle)
JavaScript
mit
jenkinsci/blueocean-plugin,jenkinsci/blueocean-plugin,jenkinsci/blueocean-plugin,ModuloM/blueocean-plugin,kzantow/blueocean-plugin,kzantow/blueocean-plugin,tfennelly/blueocean-plugin,alvarolobato/blueocean-plugin,alvarolobato/blueocean-plugin,kzantow/blueocean-plugin,tfennelly/blueocean-plugin,tfennelly/blueocean-plugin,jenkinsci/blueocean-plugin,kzantow/blueocean-plugin,ModuloM/blueocean-plugin,jenkinsci/blueocean-plugin,alvarolobato/blueocean-plugin,ModuloM/blueocean-plugin,tfennelly/blueocean-plugin,alvarolobato/blueocean-plugin,ModuloM/blueocean-plugin
--- +++ @@ -10,7 +10,7 @@ // Explicitly setting the src paths in order to allow the rebundle task to // watch for changes in the JDL (js, css, icons etc). // See https://github.com/jenkinsci/js-builder#setting-src-and-test-spec-paths -builder.src(['src/main/js', 'src/main/less', 'node_modules/@jenkins-cd/design-language']); +builder.src(['src/main/js', 'src/main/less', 'node_modules/@jenkins-cd/design-language/dist']); // // Create the main "App" bundle.
8ab80e4c485ae19ad63704e3096492dc9426457f
blueprints/route/index.js
blueprints/route/index.js
var ancestralBlueprint = require('../../lib/ancestral-blueprint'); module.exports = { description: 'Generates a route and registers it with the router', availableOptions: [ { name: 'type', type: String, values: ['route', 'resource'], default: 'route', aliases:[ {'route': 'route'}, {'resource': 'resource'} ] }, { name: 'path', type: String, default: '' } ], _fixBlueprint: function(options) { var blueprint = ancestralBlueprint('component', this.project); blueprint.ui = options.ui; return blueprint; }, fileMapTokens: function() { return ancestralBlueprint('component', this.project).fileMapTokens(); }, beforeInstall: function(options) { return ancestralBlueprint('component', this.project).beforeInstall(options); }, shouldTouchRouter: function(name) { return ancestralBlueprint('component', this.project).shouldTouchRouter(name); }, afterInstall: function(options) { return this._fixBlueprint(options).afterInstall(options); }, beforeUninstall: function(options) { return ancestralBlueprint('component', this.project).beforeUninstall(options); }, afterUninstall: function(options) { return this._fixBlueprint(options).afterUninstall(options); } };
var ancestralBlueprint = require('../../lib/ancestral-blueprint'); module.exports = { description: 'Generates a route and registers it with the router', availableOptions: [ { name: 'type', type: String, values: ['route', 'resource'], default: 'route', aliases:[ {'route': 'route'}, {'resource': 'resource'} ] }, { name: 'path', type: String, default: '' } ], _fixBlueprint: function(options) { var blueprint = ancestralBlueprint('route', this.project); blueprint.ui = options.ui; return blueprint; }, fileMapTokens: function() { return ancestralBlueprint('route', this.project).fileMapTokens(); }, beforeInstall: function(options) { return ancestralBlueprint('route', this.project).beforeInstall(options); }, shouldTouchRouter: function(name) { return ancestralBlueprint('route', this.project).shouldTouchRouter(name); }, afterInstall: function(options) { return this._fixBlueprint(options).afterInstall(options); }, beforeUninstall: function(options) { return ancestralBlueprint('route', this.project).beforeUninstall(options); }, afterUninstall: function(options) { return this._fixBlueprint(options).afterUninstall(options); } };
Correct route blueprint mistakenly looking up wrong blueprint
Correct route blueprint mistakenly looking up wrong blueprint
JavaScript
mit
ntippie/ember-cli-emblem,Vestorly/ember-cli-emblem,Vestorly/ember-cli-emblem,ntippie/ember-cli-emblem
--- +++ @@ -22,21 +22,21 @@ ], _fixBlueprint: function(options) { - var blueprint = ancestralBlueprint('component', this.project); + var blueprint = ancestralBlueprint('route', this.project); blueprint.ui = options.ui; return blueprint; }, fileMapTokens: function() { - return ancestralBlueprint('component', this.project).fileMapTokens(); + return ancestralBlueprint('route', this.project).fileMapTokens(); }, beforeInstall: function(options) { - return ancestralBlueprint('component', this.project).beforeInstall(options); + return ancestralBlueprint('route', this.project).beforeInstall(options); }, shouldTouchRouter: function(name) { - return ancestralBlueprint('component', this.project).shouldTouchRouter(name); + return ancestralBlueprint('route', this.project).shouldTouchRouter(name); }, afterInstall: function(options) { @@ -44,7 +44,7 @@ }, beforeUninstall: function(options) { - return ancestralBlueprint('component', this.project).beforeUninstall(options); + return ancestralBlueprint('route', this.project).beforeUninstall(options); }, afterUninstall: function(options) {
953a4fff7b28fb74e3ce862b480d89a675c32e12
js/reducers.js
js/reducers.js
import { SET_SEARCH_TERM } from './actions' const DEFAULT_STATE = { searchTerm: '' } const setSearchTerm = (state, action) => { const newState = {} Object.assign(newState, state, {searchTerm: action.searchTerm}) } const rootReducer = (state = DEFAULT_STATE, action) => { switch (action.type) { case SET_SEARCH_TERM: return setSearchTerm(state, action) default: return state } } export default rootReducer
import { SET_SEARCH_TERM } from './actions' const DEFAULT_STATE = { searchTerm: '' } const setSearchTerm = (state, action) => { const newState = {} Object.assign(newState, state, {searchTerm: action.searchTerm}) return newState } const rootReducer = (state = DEFAULT_STATE, action) => { switch (action.type) { case SET_SEARCH_TERM: return setSearchTerm(state, action) default: return state } } export default rootReducer
Add missing return statement in setSearchTerm
Add missing return statement in setSearchTerm
JavaScript
mit
galaxode/ubiquitous-eureka,galaxode/ubiquitous-eureka
--- +++ @@ -7,6 +7,7 @@ const setSearchTerm = (state, action) => { const newState = {} Object.assign(newState, state, {searchTerm: action.searchTerm}) + return newState } const rootReducer = (state = DEFAULT_STATE, action) => {
5313eb7bce2ebb1b8dae3c2359cc6520465e01c1
ghost/admin/router.js
ghost/admin/router.js
/*global Ember */ // ensure we don't share routes between all Router instances var Router = Ember.Router.extend(); Router.reopen({ //location: 'history', // use HTML5 History API instead of hash-tag based URLs rootURL: '/ghost/ember/' // admin interface lives under sub-directory /ghost }); Router.map(function () { this.resource('posts', { path: '/' }, function () { this.route('post', { path: ':post_id' }); }); this.resource('editor', { path: '/editor/:post_id' }); this.route('new', { path: '/editor' }); }); export default Router;
/*global Ember */ // ensure we don't share routes between all Router instances var Router = Ember.Router.extend(); Router.reopen({ location: 'history', // use HTML5 History API instead of hash-tag based URLs rootURL: '/ghost/ember/' // admin interface lives under sub-directory /ghost }); Router.map(function () { this.resource('posts', { path: '/' }, function () { this.route('post', { path: ':post_id' }); }); this.resource('editor', { path: '/editor/:post_id' }); this.route('new', { path: '/editor' }); }); export default Router;
Add HTML5 pushState support for Ember
Add HTML5 pushState support for Ember - also updates associated route
JavaScript
mit
TryGhost/Ghost,TryGhost/Ghost,TryGhost/Ghost
--- +++ @@ -4,7 +4,7 @@ var Router = Ember.Router.extend(); Router.reopen({ - //location: 'history', // use HTML5 History API instead of hash-tag based URLs + location: 'history', // use HTML5 History API instead of hash-tag based URLs rootURL: '/ghost/ember/' // admin interface lives under sub-directory /ghost });
66cc7304305fc034074b0c63a64437af2c9e3c0d
grunt/buildcontrol.js
grunt/buildcontrol.js
module.exports = { options: { dir: 'dist', commit: true, push: true, message: 'Built %sourceName% from commit %sourceCommit% on branch %sourceBranch%' }, pages: { options: { remote: 'https://github.com/lewisnyman/lewisnyman.github.io.git', branch: 'master' } }, local: { options: { remote: '../', branch: 'app' } } };
module.exports = { options: { dir: 'dist', commit: true, push: true, message: 'Built %sourceName% from commit %sourceCommit% on branch %sourceBranch%' }, pages: { options: { remote: 'https://github.com/lewisnyman/lewisnyman.github.io.git', branch: 'master', config: { 'user.name': 'lewisnyman' }, } }, local: { options: { remote: '../', branch: 'app' } } };
Add username to deploy config
Add username to deploy config
JavaScript
mit
lewisnyman/lewisnyman.co.uk-source,lewisnyman/lewisnyman.co.uk-source,lewisnyman/lewisnyman.co.uk-source
--- +++ @@ -8,7 +8,10 @@ pages: { options: { remote: 'https://github.com/lewisnyman/lewisnyman.github.io.git', - branch: 'master' + branch: 'master', + config: { + 'user.name': 'lewisnyman' + }, } }, local: {
54599eb33226086a80b233fc896785a55b16fa40
src/api/__tests__/Killmail.spec.js
src/api/__tests__/Killmail.spec.js
jest.mock('../../internal/ESIAgent'); const Api = require('../../Api'); let api = new Api(); let agent = api._esiAgent; afterEach(() => { agent.__reset(); }); test('Killmail.get', () => { agent.__expectRoute('get_killmails_killmail_id_killmail_hash', {'killmail_id': 1, 'killmail_hash': 'hash'}); return api.killmail(1, 'hash').then(result => { expect(result).toBeDefined(); }); });
jest.mock('../../internal/ESIAgent'); const Api = require('../../Api'); let api = new Api(); let agent = api._esiAgent; afterEach(() => { agent.__reset(); }); test('Killmail.get', () => { agent.__expectRoute('get_killmails_killmail_id_killmail_hash', { 'killmail_id': 1, 'killmail_hash': 'hash' }); return api.killmail(1, 'hash').then(result => { expect(result).toBeDefined(); }); });
Fix formatting in Killmail test
Fix formatting in Killmail test
JavaScript
bsd-3-clause
lhkbob/eve-swagger-js,lhkbob/eve-swagger-js
--- +++ @@ -10,7 +10,10 @@ }); test('Killmail.get', () => { - agent.__expectRoute('get_killmails_killmail_id_killmail_hash', {'killmail_id': 1, 'killmail_hash': 'hash'}); + agent.__expectRoute('get_killmails_killmail_id_killmail_hash', { + 'killmail_id': 1, + 'killmail_hash': 'hash' + }); return api.killmail(1, 'hash').then(result => { expect(result).toBeDefined(); });
dcfd13351222b68e3647657ed3874ce189c45676
namuhub/static/namuhub.js
namuhub/static/namuhub.js
var ContribBox = React.createClass({ render: function() { return <div />; } }); var SearchBox = React.createClass({ getInitialState: function () { console.log(this.props); return { user: this.props.user || '' }; }, handleSubmit: function() { }, submit: function(e) { var uri = '/' + this.state.user; e.preventDefault(); var ps = window.history.pushState ? 1 : 0; [function(){location.replace(uri)},function(){window.history.pushState(null,null,uri)}][ps](); this.handleSubmit(); }, updateUser: function(e) { this.setState({ user: e.target.value }); }, render: function() { return ( <form className="ui" onSubmit={this.submit}> <div className="ui action center aligned input"> <input type="text" placeholder="나무위키 아이디 입력" defaultValue={this.props.user} onChange={this.updateUser} /> <button className="ui teal button">조회</button> </div> </form> ); } });
var ContribBox = React.createClass({ handleLoad: function(user) { alert(user); }, render: function() { return <div>asdf</div>; } }); var SearchBox = React.createClass({ getInitialState: function() { return { user: this.props.user || '' }; }, submit: function(e) { var uri = '/' + this.state.user; e.preventDefault(); var ps = window.history.pushState ? 1 : 0; [function(){location.replace(uri)},function(){window.history.pushState(null,null,uri)}][ps](); this.props.onSubmit(this.state.user); }, updateUser: function(e) { this.setState({ user: e.target.value }); }, componentDidMount: function() { this.props.onSubmit(this.state.user); }, render: function() { return ( <form className="ui" onSubmit={this.submit}> <div className="ui action center aligned input"> <input type="text" placeholder="나무위키 아이디 입력" defaultValue={this.props.user} onChange={this.updateUser} /> <button className="ui teal button">조회</button> </div> </form> ); } });
Make codes being close to React style
Make codes being close to React style
JavaScript
apache-2.0
ssut/namuhub,ssut/namuhub,ssut/namuhub
--- +++ @@ -1,19 +1,18 @@ var ContribBox = React.createClass({ + handleLoad: function(user) { + alert(user); + }, + render: function() { - return <div />; + return <div>asdf</div>; } }); var SearchBox = React.createClass({ - getInitialState: function () { - console.log(this.props); + getInitialState: function() { return { - user: this.props.user || '' + user: this.props.user || '' }; - }, - - handleSubmit: function() { - }, submit: function(e) { @@ -23,13 +22,17 @@ var ps = window.history.pushState ? 1 : 0; [function(){location.replace(uri)},function(){window.history.pushState(null,null,uri)}][ps](); - this.handleSubmit(); + this.props.onSubmit(this.state.user); }, updateUser: function(e) { this.setState({ user: e.target.value }); + }, + + componentDidMount: function() { + this.props.onSubmit(this.state.user); }, render: function() {
ce6c6d06b71fad04f7909ddf0d5a3fc7f13318cb
app/views/shuttle/ShuttleCard.js
app/views/shuttle/ShuttleCard.js
import React from 'react' import { Text } from 'react-native' import { withNavigation } from 'react-navigation' import ShuttleOverview from './ShuttleOverview' import ScrollCard from '../common/ScrollCard' import Touchable from '../common/Touchable' import css from '../../styles/css' export const ShuttleCard = ({ navigation, stopsData, savedStops, gotoRoutesList, gotoSavedList, updateScroll, lastScroll, }) => { const extraActions = [ { name: 'Manage Stops', action: gotoSavedList } ] return ( <ScrollCard id="shuttle" title="Shuttle" scrollData={savedStops} renderItem={ ({ item: rowData }) => ( <ShuttleOverview onPress={() => navigation.navigate('ShuttleStop', { stopID: rowData.id })} stopData={stopsData[rowData.id]} closest={Object.prototype.hasOwnProperty.call(rowData, 'savedIndex')} /> ) } actionButton={ <Touchable style={css.shuttlecard_addButton} onPress={() => gotoRoutesList()} > <Text style={css.shuttlecard_addText}>Add a Stop</Text> </Touchable> } extraActions={extraActions} updateScroll={updateScroll} lastScroll={lastScroll} /> ) } export default withNavigation(ShuttleCard)
import React from 'react' import { Text } from 'react-native' import { withNavigation } from 'react-navigation' import ShuttleOverview from './ShuttleOverview' import ScrollCard from '../common/ScrollCard' import Touchable from '../common/Touchable' import css from '../../styles/css' export const ShuttleCard = ({ navigation, stopsData, savedStops, gotoRoutesList, gotoSavedList, updateScroll, lastScroll, }) => { const extraActions = [ { name: 'Manage Stops', action: gotoSavedList } ] console.log(savedStops) return ( <ScrollCard id="shuttle" title="Shuttle" scrollData={savedStops} renderItem={ ({ item: rowData }) => ( <ShuttleOverview onPress={() => navigation.navigate('ShuttleStop', { stopID: rowData.id })} stopData={stopsData[rowData.id]} closest={Object.prototype.hasOwnProperty.call(rowData, 'savedIndex')} /> ) } actionButton={ <Touchable style={css.shuttlecard_addButton} onPress={() => gotoRoutesList()} > <Text style={css.shuttlecard_addText}>Add a Stop</Text> </Touchable> } extraActions={extraActions} updateScroll={updateScroll} lastScroll={lastScroll} /> ) } export default withNavigation(ShuttleCard)
Add extra check in keyExtractor to prevent dublicate keys
Add extra check in keyExtractor to prevent dublicate keys
JavaScript
mit
UCSD/campus-mobile,UCSD/campus-mobile,UCSD/now-mobile,UCSD/now-mobile,UCSD/campus-mobile,UCSD/campus-mobile,UCSD/campus-mobile,UCSD/campus-mobile,UCSD/now-mobile
--- +++ @@ -22,7 +22,7 @@ action: gotoSavedList } ] - + console.log(savedStops) return ( <ScrollCard id="shuttle"
0fce5bee89ea2a81a295a80531d42fef675dd02b
components/Footer.js
components/Footer.js
import React from 'react' function Footer() { return ( <div className="fix-bottom"> <p className="tc">All rigths reserved</p> <style jsx>{` .fix-bottom { position: relative; bottom: 0; width: 100%; height: auto; color: #094E62; } `}</style> </div> ) } export default Footer
import React from 'react' function Footer() { return ( <div className="fix-bottom"> <p className="tc f7">© 2017 All rigths reserved</p> <style jsx>{` .fix-bottom { position: absolute; bottom: 0; width: 100%; height: auto; color: #094E62; } `}</style> </div> ) } export default Footer
Replace all rights reserved at the bottom of the screen
Replace all rights reserved at the bottom of the screen
JavaScript
mit
efleurine/alumnus
--- +++ @@ -3,10 +3,10 @@ function Footer() { return ( <div className="fix-bottom"> - <p className="tc">All rigths reserved</p> + <p className="tc f7">© 2017 All rigths reserved</p> <style jsx>{` .fix-bottom { - position: relative; + position: absolute; bottom: 0; width: 100%; height: auto;
7074918dbe7a713898a670b5e3f67441a89ac11a
topcube.js
topcube.js
var spawn = require('child_process').spawn; var path = require('path'); module.exports = function (options) { options = options || {}; options.url = options.url || 'http://nodejs.org'; options.name = options.name || 'nodejs'; var client; switch (process.platform) { case 'win32': client = path.resolve(__dirname + '/cefclient/cefclient'); break; case 'linux': client = path.resolve(__dirname + '/build/default/topcube'); break; default: console.warn(''); return null; break; } var args = []; for (var key in options) { // Omit keys besides name & url for now until options // parsing bugs are resolved. if (process.platform === 'win32' && (key !== 'name' || key !== 'url')) continue; args.push('--' + key + '=' + options[key]); } var child = spawn(client, args); child.on('exit', function(code) { process.exit(code); }); child.stdout.pipe(process.stdout); child.stderr.pipe(process.stderr); return child; };
var spawn = require('child_process').spawn; var path = require('path'); module.exports = function (options) { options = options || {}; options.url = options.url || 'http://nodejs.org'; options.name = options.name || 'nodejs'; var client; switch (process.platform) { case 'win32': client = path.resolve(__dirname + '/cefclient/cefclient'); break; case 'linux': client = path.resolve(__dirname + '/build/default/topcube'); break; default: console.warn(''); return null; break; } var args = []; for (var key in options) args.push('--' + key + '=' + options[key]); var child = spawn(client, args); child.on('exit', function(code) { process.exit(code); }); child.stdout.pipe(process.stdout); child.stderr.pipe(process.stderr); return child; };
Revert "Allow only name, url keys for win32."
Revert "Allow only name, url keys for win32." This reverts commit 9ea03c29ffc1dac7f04f094433c9e47c2ba1c5ad.
JavaScript
mit
creationix/topcube,creationix/topcube,creationix/topcube
--- +++ @@ -21,13 +21,7 @@ } var args = []; - for (var key in options) { - // Omit keys besides name & url for now until options - // parsing bugs are resolved. - if (process.platform === 'win32' && - (key !== 'name' || key !== 'url')) continue; - args.push('--' + key + '=' + options[key]); - } + for (var key in options) args.push('--' + key + '=' + options[key]); var child = spawn(client, args); child.on('exit', function(code) {
046d25e5a18444acc9f745054b772ab5c316717d
server.js
server.js
var AlexaAppServer = require('alexa-app-server'); var MpdInterface = require('./apps/alexa-mpd-control/mpd_interface'); var mpd = new MpdInterface(); AlexaAppServer.start({ // server_root:__dirname, // Path to root // public_html:"public_html", // Static content // app_dir:"apps", // Where alexa-app modules are stored // app_root:"/alexa/", // Service root preRequest: function(json,req,res) { console.log("preRequest fired", json.request.intent && json.request.intent.name); json.userDetails = { "name":"Bob Smith" }; var retPromise = new Promise(function(resolve, reject){ if(json.request.intent && json.request.intent.name === "randalbum"){ mpd.getRandomAlbumName().then(function(albumInfo){ json[json.request.intent.name] = albumInfo; resolve(json); }); }else{ resolve(json); } }); return retPromise; }, port:8092, // What port to use, duh httpsPort:443, httpsEnabled:true, privateKey:'private-key.pem', certificate:'certificate.pem' });
var AlexaAppServer = require('alexa-app-server'); var MpdInterface = require('./apps/alexa-mpd-control/mpd_interface'); var mpd = new MpdInterface(); AlexaAppServer.start({ // server_root:__dirname, // Path to root // public_html:"public_html", // Static content // app_dir:"apps", // Where alexa-app modules are stored // app_root:"/alexa/", // Service root preRequest: function(json,req,res) { console.log("preRequest fired", json.request.intent && json.request.intent.name); json.userDetails = { "name":"Bob Smith" }; var retPromise = new Promise(function(resolve, reject){ if(json.request.intent && json.request.intent.name === "randalbum"){ mpd.getRandomAlbum().then(function(albumInfo){ json[json.request.intent.name] = albumInfo; resolve(json); }); }else{ resolve(json); } }); return retPromise; }, port:8092, // What port to use, duh httpsPort:443, httpsEnabled:true, privateKey:'private-key.pem', certificate:'certificate.pem' });
Fix bad function name call
Fix bad function name call
JavaScript
mit
guikubivan/alexa-mpd-control,guikubivan/alexa-mpd-control
--- +++ @@ -17,7 +17,7 @@ var retPromise = new Promise(function(resolve, reject){ if(json.request.intent && json.request.intent.name === "randalbum"){ - mpd.getRandomAlbumName().then(function(albumInfo){ + mpd.getRandomAlbum().then(function(albumInfo){ json[json.request.intent.name] = albumInfo; resolve(json); });
70ecffab32fb4106bbe8b1056ec864bbf5faf4e2
src/styles/Illustrations/assets/tuttolino/index.js
src/styles/Illustrations/assets/tuttolino/index.js
export Tuttolino404 from "./tuttolino-404.png" export TuttolinoCompetitor from "./tuttolino-competitor.svg" export TuttolinoErrorMobile from "./tuttolino-error-mobile.png" export TuttolinoError from "./tuttolino-error.svg" export TuttolinoFamilySofa from "./tuttolino-family-sofa.svg" export TuttolinoFamily from "./tuttolino-family.svg" export TuttolinoGay from "./tuttolino-gay.svg" export TuttolinoGlasses from "./tuttolino-glasses.svg" export TuttolinoHey from "./tuttolino-hey.svg" export TuttolinoHolmesNoCircle from "./tuttolino-holmes-no_circle.svg" export TuttolinoHolmes from "./tuttolino-holmes.svg" export TuttolinoHolmes from "./tuttolino-holmes-no_circle.svg" export TuttolinoIntroScreens from "./tuttolino-intro-screens.svg" export TuttolinoSergi from "./tuttolino-sergi.svg" export TuttolinoSuccess from "./tuttolino-success.svg" export TuttolinoTablet from "./tuttolino-tablet.svg" export TuttolinoTuttiFan from "./tuttolino-tutti_fan.svg"
export Tuttolino404 from "./tuttolino-404.png" export TuttolinoCompetitor from "./tuttolino-competitor.svg" export TuttolinoErrorMobile from "./tuttolino-error-mobile.png" export TuttolinoError from "./tuttolino-error.svg" export TuttolinoFamilySofa from "./tuttolino-family-sofa.svg" export TuttolinoFamily from "./tuttolino-family.svg" export TuttolinoGay from "./tuttolino-gay.svg" export TuttolinoGlasses from "./tuttolino-glasses.svg" export TuttolinoHey from "./tuttolino-hey.svg" export TuttolinoHolmesNoCircle from "./tuttolino-holmes-no_circle.svg" export TuttolinoHolmes from "./tuttolino-holmes.svg" export TuttolinoIntroScreens from "./tuttolino-intro-screens.svg" export TuttolinoSergi from "./tuttolino-sergi.svg" export TuttolinoSuccess from "./tuttolino-success.svg" export TuttolinoTablet from "./tuttolino-tablet.svg" export TuttolinoTuttiFan from "./tuttolino-tutti_fan.svg"
Deploy to GitHub pages
Deploy to GitHub pages [ci skip]
JavaScript
mit
tutti-ch/react-styleguide,tutti-ch/react-styleguide
--- +++ @@ -9,7 +9,6 @@ export TuttolinoHey from "./tuttolino-hey.svg" export TuttolinoHolmesNoCircle from "./tuttolino-holmes-no_circle.svg" export TuttolinoHolmes from "./tuttolino-holmes.svg" -export TuttolinoHolmes from "./tuttolino-holmes-no_circle.svg" export TuttolinoIntroScreens from "./tuttolino-intro-screens.svg" export TuttolinoSergi from "./tuttolino-sergi.svg" export TuttolinoSuccess from "./tuttolino-success.svg"
88fcafc8839304ca8bc3a77f74f25d5542cec342
src/MessageStore.js
src/MessageStore.js
var Reflux = require('reflux'); var objectAssign = require('object-assign'); var MessageActions = require('./MessageActions'); var _stack = []; // Container for the each object of message var _counter = 0; /** * Registry of all messages, mixin to manage all drawers. * Contains add, flush, and remove to do the mentioned. */ var MessageStore = Reflux.createStore({ listenables: MessageActions, /** * Removes the message with given key * @param {int} id ID/Key of message which would be removed */ onRemove: function(id) { // Index of the message var index = _stack.map(function(message) { return message.id }).indexOf(id); // Throw an exception if there are no results of the given id if ( index == -1 ) throw new Error('The message (id) does not exist in the stack'); _stack.splice(index, 1); this.trigger(_stack); }, /** * Adds a new message to the stack */ onAdd: function(data) { // Message defaults var _defaults = { id: ++_counter, duration: 10000, template: '' }; _stack.push( data ? objectAssign(_defaults, data) : _defaults ); this.trigger(_stack); }, /** * Removes everything in the stack */ onFlush: function() { this.trigger(_stack = []); } }; module.exports = MessageStore;
var Reflux = require('reflux'); var objectAssign = require('object-assign'); var MessageActions = require('./MessageActions'); var _stack = []; // Container for the each object of message var _counter = 0; /** * Registry of all messages, mixin to manage all drawers. * Contains add, flush, and remove to do the mentioned. */ var MessageStore = Reflux.createStore({ listenables: MessageActions, /** * Removes the message with given key * @param {int} id ID/Key of message which would be removed */ onRemove: function(id) { // Index of the message var index = _stack.map(function(message) { return message.id }).indexOf(id); // Throw an exception if there are no results of the given id if ( index == -1 ) throw new Error('The message (id) does not exist in the stack'); _stack.splice(index, 1); this.trigger(_stack); }, /** * Adds a new message to the stack */ onAdd: function(data) { // Message defaults var _defaults = { id: ++_counter, duration: 10000, template: '' }; _stack.push( data ? objectAssign(_defaults, data) : _defaults ); this.trigger(_stack); }, /** * Removes everything in the stack */ onClear: function(filter) { this.trigger(_stack = !!filter ? _stack.filter(function(message) { return filter == message.type }) : [] ); } }; module.exports = MessageStore;
Clear instead of Flush. Clearing now allows for a certain type to be filtered out.
Clear instead of Flush. Clearing now allows for a certain type to be filtered out.
JavaScript
mit
srph/reflux-flash
--- +++ @@ -50,7 +50,12 @@ /** * Removes everything in the stack */ - onFlush: function() { this.trigger(_stack = []); } + onClear: function(filter) { + this.trigger(_stack = !!filter + ? _stack.filter(function(message) { return filter == message.type }) + : [] + ); + } }; module.exports = MessageStore;
60a48a5a5cd959efccc3dfcbed735a1e8fc5e47a
server.js
server.js
var http = require('http') , url = require('url') , express = require('express') , rest = express() , path = require('path') , server = http.createServer(rest) , ap = require('argparse').ArgumentParser , colors = require('colors') , appium = require('./app/appium') , parser = require('./app/parser'); rest.configure(function() { rest.use(express.favicon()); rest.use(express.static(path.join(__dirname, '/app/static'))); rest.use(express.logger('dev')); rest.use(express.bodyParser()); rest.use(express.methodOverride()); rest.use(rest.router); }); // Parse the command line arguments var args = parser().parseArgs(); // Instantiate the appium instance var appium = appium(args.app, args.UDID, args.verbose); // Hook up REST http interface appium.attachTo(rest); // Start the web server that receives all the commands server.listen(args.port, args.address, function() { var logMessage = "Appium REST http interface listener started on "+args.address+":"+args.port; console.log(logMessage.cyan); });
var http = require('http') , url = require('url') , express = require('express') , rest = express() , path = require('path') , server = http.createServer(rest) , ap = require('argparse').ArgumentParser , colors = require('colors') , appium = require('./app/appium') , parser = require('./app/parser'); rest.configure(function() { var bodyParser = express.bodyParser() , parserWrap = function(req, res, next) { // wd.js sends us http POSTs with empty body which will make bodyParser fail. if (parseInt(req.get('content-length'), 10) <= 0) { return next(); } bodyParser(req, res, next); }; rest.use(express.favicon()); rest.use(express.static(path.join(__dirname, '/app/static'))); rest.use(express.logger('dev')); rest.use(parserWrap); rest.use(express.methodOverride()); rest.use(rest.router); }); // Parse the command line arguments var args = parser().parseArgs(); // Instantiate the appium instance var appium = appium(args.app, args.UDID, args.verbose); // Hook up REST http interface appium.attachTo(rest); // Start the web server that receives all the commands server.listen(args.port, args.address, function() { var logMessage = "Appium REST http interface listener started on "+args.address+":"+args.port; console.log(logMessage.cyan); });
Deal with invalid http POST more gracefully.
Deal with invalid http POST more gracefully.
JavaScript
apache-2.0
appium/appium,appium/appium,appium/appium,appium/appium,appium/appium,Sw0rdstream/appium,appium/appium
--- +++ @@ -10,10 +10,19 @@ , parser = require('./app/parser'); rest.configure(function() { + var bodyParser = express.bodyParser() + , parserWrap = function(req, res, next) { + // wd.js sends us http POSTs with empty body which will make bodyParser fail. + if (parseInt(req.get('content-length'), 10) <= 0) { + return next(); + } + bodyParser(req, res, next); + }; + rest.use(express.favicon()); rest.use(express.static(path.join(__dirname, '/app/static'))); rest.use(express.logger('dev')); - rest.use(express.bodyParser()); + rest.use(parserWrap); rest.use(express.methodOverride()); rest.use(rest.router); });
d419673a07062390431dd7ff4f5ac526b1c252bd
tests/content/script/breakpoints/5525/issue5525.js
tests/content/script/breakpoints/5525/issue5525.js
function runTest() { FBTest.sysout("issue5525.START"); FBTest.openNewTab(basePath + "script/breakpoints/5525/issue5525.html", function(win) { FBTest.openFirebug(); FBTest.enableScriptPanel() FBTest.enableConsolePanel() FBTest.selectPanel("console"); var config = {tagName: "div", classes: "logRow logRow-errorMessage"}; FBTest.waitForDisplayedElement("console", config, function(row) { // Verify displayed text. var reTextContent = /ReferenceError\:\s*undefinedVariable is not defined\s*var test = undefinedVariable;\s*issue5525.html\s*\(line 10\)/; FBTest.compare(reTextContent, row.textContent, "Text content must match."); // Create error breakpoint var br = row.getElementsByClassName("errorBreak")[0]; FBTest.click(br); // Switch to the Script and Breakpoints panels. FBTest.selectPanel("script"); var panel = FBTest.selectSidePanel("breakpoints"); // Check content of the Breakpoints panel var panelNode = panel.panelNode; var rows = panelNode.getElementsByClassName("breakpointRow"); FBTest.compare(rows.length, 1, "There must be one breakpoint"); // Finish test FBTest.testDone("console.error.DONE"); }); FBTest.reload(); }); }
function runTest() { FBTest.sysout("issue5525.START"); FBTest.openNewTab(basePath + "script/breakpoints/5525/issue5525.html", function(win) { FBTest.openFirebug(); FBTest.enableScriptPanel() FBTest.enableConsolePanel() FBTest.selectPanel("console"); var config = {tagName: "div", classes: "logRow logRow-errorMessage"}; FBTest.waitForDisplayedElement("console", config, function(row) { // Verify displayed text. var reTextContent = /\s*undefinedVariable is not defined\s*var test = undefinedVariable;\s*issue5525.html\s*\(line 10\)/; FBTest.compare(reTextContent, row.textContent, "Text content must match."); // Create error breakpoint var br = row.getElementsByClassName("errorBreak")[0]; FBTest.click(br); // Switch to the Script and Breakpoints panels. FBTest.selectPanel("script"); var panel = FBTest.selectSidePanel("breakpoints"); // Check content of the Breakpoints panel var panelNode = panel.panelNode; var rows = panelNode.getElementsByClassName("breakpointRow"); FBTest.compare(rows.length, 1, "There must be one breakpoint"); // Finish test FBTest.testDone("console.error.DONE"); }); FBTest.reload(); }); }
Fix test to pass also with Firefox 13
Fix test to pass also with Firefox 13
JavaScript
bsd-3-clause
firebug/tracing-console,firebug/tracing-console
--- +++ @@ -12,7 +12,7 @@ FBTest.waitForDisplayedElement("console", config, function(row) { // Verify displayed text. - var reTextContent = /ReferenceError\:\s*undefinedVariable is not defined\s*var test = undefinedVariable;\s*issue5525.html\s*\(line 10\)/; + var reTextContent = /\s*undefinedVariable is not defined\s*var test = undefinedVariable;\s*issue5525.html\s*\(line 10\)/; FBTest.compare(reTextContent, row.textContent, "Text content must match."); // Create error breakpoint
681dc926bcc021550d8b4fc13fc0136652a43c2c
src/extras/index.js
src/extras/index.js
export * from './controls/FirstPersonControls'; export * from './controls/OrbitControlsModule'; export * from './VirtualMouse';
export * from './controls/FirstPersonControls'; export * from './controls/OrbitControlsModule'; export * from './pass/index'; export * from './shader/index'; export * from './VirtualMouse';
Fix exporting pass & shaders
Fix exporting pass & shaders
JavaScript
mit
WhitestormJS/whitestorm.js,WhitestormJS/whitestorm.js
--- +++ @@ -1,3 +1,5 @@ export * from './controls/FirstPersonControls'; export * from './controls/OrbitControlsModule'; +export * from './pass/index'; +export * from './shader/index'; export * from './VirtualMouse';
3bf56355eee5d7091f1596f10efa404af28bbeb9
src/handleGitHub.js
src/handleGitHub.js
String.prototype.replaceAll = function(search, replace) { //if replace is not sent, return original string otherwise it will //replace search string with 'undefined'. if (replace === undefined) { return this.toString(); } return this.replace(new RegExp('[' + search + ']', 'g'), replace); }; var repoFromLink = window.location.pathname.split("/")[2]; listRepositories(function(repos){ var repo = repos.find(repo => repo.scm == repoFromLink); if(repo){ processRepo(repo); } }); function processRepo(repo){ var commentBody = $(".comment-body, .commit-title, .commit-desc"); var splittedBody = commentBody.text().split(" "); for( var i in splittedBody){ var text = splittedBody[i]; if (splittedBody[i].indexOf(repo.keyword) > -1){ //Clean the link from some symbols usually added to destinguish issue-id from commit message var cleanedText = text.replaceAll("[", "").replaceAll("\\]", "").replaceAll("#", ""); commentBody.html(commentBody.html().replace(text, '<a href="' + repo.targetURL + cleanedText + '">' + text + '</a>')); } } }
String.prototype.replaceAll = function(search, replace) { //if replace is not sent, return original string otherwise it will //replace search string with 'undefined'. if (replace === undefined) { return this.toString(); } return this.replace(new RegExp('[' + search + ']', 'g'), replace); }; var repoFromLink = window.location.pathname.split("/")[2]; listRepositories(function(repos){ var repos = repos.filter(repo => repo.scm == repoFromLink); if(repos){ processRepo(repos); } }); function processRepo(repos){ var commentBody = $(".comment-body, .commit-title, .commit-desc"); var splittedBody = commentBody.text().split(" "); for( var i in splittedBody){ var text = splittedBody[i]; for(var j in repos){ var repo = repos[j]; if (splittedBody[i].indexOf(repo.keyword) > -1){ console.log("here"); //Clean the link from some symbols usually added to destinguish issue-id from commit message var cleanedText = text.replaceAll("[", "").replaceAll("\\]", "").replaceAll("#", ""); commentBody.html(commentBody.html().replace(text, '<a href="' + repo.targetURL + cleanedText + '">' + text + '</a>')); } } } }
Add support for multiple issue keywords in the same repo
Add support for multiple issue keywords in the same repo
JavaScript
mit
NunoPinheiro/commitissuelinker,NunoPinheiro/commitissuelinker
--- +++ @@ -13,21 +13,25 @@ var repoFromLink = window.location.pathname.split("/")[2]; listRepositories(function(repos){ - var repo = repos.find(repo => repo.scm == repoFromLink); - if(repo){ - processRepo(repo); + var repos = repos.filter(repo => repo.scm == repoFromLink); + if(repos){ + processRepo(repos); } }); -function processRepo(repo){ +function processRepo(repos){ var commentBody = $(".comment-body, .commit-title, .commit-desc"); var splittedBody = commentBody.text().split(" "); for( var i in splittedBody){ var text = splittedBody[i]; - if (splittedBody[i].indexOf(repo.keyword) > -1){ - //Clean the link from some symbols usually added to destinguish issue-id from commit message - var cleanedText = text.replaceAll("[", "").replaceAll("\\]", "").replaceAll("#", ""); - commentBody.html(commentBody.html().replace(text, '<a href="' + repo.targetURL + cleanedText + '">' + text + '</a>')); + for(var j in repos){ + var repo = repos[j]; + if (splittedBody[i].indexOf(repo.keyword) > -1){ + console.log("here"); + //Clean the link from some symbols usually added to destinguish issue-id from commit message + var cleanedText = text.replaceAll("[", "").replaceAll("\\]", "").replaceAll("#", ""); + commentBody.html(commentBody.html().replace(text, '<a href="' + repo.targetURL + cleanedText + '">' + text + '</a>')); + } } } }
22b0f1d407cceb44c7736dea7f42c9aa88d72f74
components/date/fields.js
components/date/fields.js
'use strict'; module.exports = key => ({ [`${key}-day`]: { label: 'Day' }, [`${key}-month`]: { label: 'Month' }, [`${key}-year`]: { label: 'Year' } });
'use strict'; module.exports = key => ({ [`${key}-day`]: { label: 'Day', autocomplete: 'bday-day' }, [`${key}-month`]: { label: 'Month', autocomplete: 'bday-month' }, [`${key}-year`]: { label: 'Year', autocomplete: 'bday-year' } });
Add autocomplete to date component to assist with accessibility
Add autocomplete to date component to assist with accessibility
JavaScript
mit
UKHomeOfficeForms/hof-bootstrap,UKHomeOfficeForms/hof,UKHomeOfficeForms/hof-bootstrap,UKHomeOfficeForms/hof
--- +++ @@ -2,12 +2,15 @@ module.exports = key => ({ [`${key}-day`]: { - label: 'Day' + label: 'Day', + autocomplete: 'bday-day' }, [`${key}-month`]: { - label: 'Month' + label: 'Month', + autocomplete: 'bday-month' }, [`${key}-year`]: { - label: 'Year' + label: 'Year', + autocomplete: 'bday-year' } });
d9cc719e8c1eeb1290ba5df986d1b89050a3b12e
src/ie.js
src/ie.js
// Zepto.js // (c) 2010-2013 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. ;(function(){ // __proto__ doesn't exist on IE<11, so redefine // the Z function to use object extension instead if (!('__proto__' in {})) { $.extend($.zepto, { Z: function(dom, selector){ dom = dom || [] $.extend(dom, $.fn) dom.selector = selector || '' dom.__Z = true return dom }, // this is a kludge but works isZ: function(object){ return $.type(object) === 'array' && '__Z' in object } }) } // getComputedStyle shouldn't freak out when called // without a valid element as argument try { getComputedStyle(undefined) } catch(e) { var nativeGetComputedStyle = getComputedStyle; window.getComputedStyle = function(element){ try { return nativeGetComputedStyle(element) } catch(e) { return null } } } })()
// Zepto.js // (c) 2010-2013 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. ;(function($){ // __proto__ doesn't exist on IE<11, so redefine // the Z function to use object extension instead if (!('__proto__' in {})) { $.extend($.zepto, { Z: function(dom, selector){ dom = dom || [] $.extend(dom, $.fn) dom.selector = selector || '' dom.__Z = true return dom }, // this is a kludge but works isZ: function(object){ return $.type(object) === 'array' && '__Z' in object } }) } // getComputedStyle shouldn't freak out when called // without a valid element as argument try { getComputedStyle(undefined) } catch(e) { var nativeGetComputedStyle = getComputedStyle; window.getComputedStyle = function(element){ try { return nativeGetComputedStyle(element) } catch(e) { return null } } } })(Zepto)
Make sure to properly patch the Zepto object in IE, not any global $ object.
Make sure to properly patch the Zepto object in IE, not any global $ object.
JavaScript
mit
xuechunL/zepto,chenruixuan/zepto,zhengdai/zepto,SallyRice/zepto,JimmyVV/zepto,huaziHear/zepto,wyfyyy818818/zepto,yinchuandong/zepto,wanglam/zepto,nerdgore/zepto,zhangbg/zepto,mmcai/zepto,Genie77998/zepto,rayrc/zepto,wubian0517/zepto,alatvanas9/zepto,mscienski/zepto,webcoding/zepto,wubian0517/zepto,GerHobbelt/zepto,huaziHear/zepto,Genie77998/zepto,liyandalmllml/zepto,wanglam/zepto,philip8728/zepto,xueduany/zepto,midare/zepto,vincent1988/zepto,xueduany/zepto,treejames/zepto,assgod/zepto,leolin1229/zepto,GerHobbelt/zepto,afgoulart/zepto,webcoding/zepto,modulexcite/zepto,Jiasm/zepto,fbiz/zepto,evilemon/zepto,alatvanas9/zepto,modulexcite/zepto,alatvanas9/zepto,wanglam/zepto,JimmyVV/zepto,leolin1229/zepto,clearwind/zepto,noikiy/zepto,zhangbg/zepto,evilemon/zepto,nerdgore/zepto,changfengliu/zepto,xuechunL/zepto,fbiz/zepto,liuweifeng/zepto,afgoulart/zepto,midare/zepto,afgoulart/zepto,zhangwei001/zepto,yinchuandong/zepto,vincent1988/zepto,GerHobbelt/zepto,linqingyicen/zepto,clearwind/zepto,nerdgore/zepto,honeinc/zepto,laispace/zepto,dajbd/zepto,baiyanghese/zepto,assgod/zepto,chenruixuan/zepto,liyandalmllml/zepto,dajbd/zepto,treejames/zepto,yubin-huang/zepto,Genie77998/zepto,liuweifeng/zepto,behind2/zepto,honeinc/zepto,vivijiang/zepto,vivijiang/zepto,changfengliu/zepto,eric-seekas/zepto,yuhualingfeng/zepto,zhangwei001/zepto,kolf/zepto,pandoraui/zepto,evilemon/zepto,wyfyyy818818/zepto,vincent1988/zepto,yubin-huang/zepto,leolin1229/zepto,behind2/zepto,eric-seekas/zepto,mscienski/zepto,JimmyVV/zepto,Jiasm/zepto,yinchuandong/zepto,behind2/zepto,wubian0517/zepto,xuechunL/zepto,noikiy/zepto,changfengliu/zepto,rayrc/zepto,midare/zepto,kolf/zepto,fbiz/zepto,mmcai/zepto,waiter/zepto,SallyRice/zepto,wushuyi/zepto,waiter/zepto,modulexcite/zepto,treejames/zepto,Jiasm/zepto,webcoding/zepto,clearwind/zepto,eric-seekas/zepto,YongX/zepto,121595113/zepto,baiyanghese/zepto,liyandalmllml/zepto,121595113/zepto,waiter/zepto,philip8728/zepto,wushuyi/zepto,YongX/zepto,wushuyi/zepto,vivijiang/zepto,laispace/zepto,SlaF/zepto,yubin-huang/zepto,SallyRice/zepto,linqingyicen/zepto,SlaF/zepto,philip8728/zepto,YongX/zepto,huaziHear/zepto,zhengdai/zepto,mscienski/zepto,zhengdai/zepto,honeinc/zepto,rayrc/zepto,chenruixuan/zepto,pandoraui/zepto,pandoraui/zepto,liuweifeng/zepto,yuhualingfeng/zepto,zhangbg/zepto,yuhualingfeng/zepto,linqingyicen/zepto,mmcai/zepto,xueduany/zepto,zhangwei001/zepto,wyfyyy818818/zepto,assgod/zepto,SlaF/zepto,dajbd/zepto,noikiy/zepto,kolf/zepto
--- +++ @@ -2,7 +2,7 @@ // (c) 2010-2013 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. -;(function(){ +;(function($){ // __proto__ doesn't exist on IE<11, so redefine // the Z function to use object extension instead if (!('__proto__' in {})) { @@ -35,4 +35,4 @@ } } } -})() +})(Zepto)
72d15313741b7c06721c9f5638674e43a9a52cb6
src/graphql.js
src/graphql.js
import Item from "./graphql/types/item" import Update from "./graphql/types/update" import { makeExecutableSchema } from "graphql-tools" const RuneScapeQuery = ` type RuneScapeQuery { items: [Item] item(id: Int!): Item updates: [Update] } ` const SchemaDefinition = ` schema { query: RuneScapeQuery } ` export default makeExecutableSchema({ typeDefs: [SchemaDefinition, RuneScapeQuery, Item, Update], resolvers: { RuneScapeQuery: { items: (root, { ids }, { models }) => models.items.find({}, { _id: false, rsbuddy: false }), item: (root, { id }, { models }) => models.items.findOne({ id }, { _id: false, rsbuddy: false }), updates: (root, args, { models }) => models.updates.find({}, { _id: false }) }, Item: { rsbuddy: (root, args, { models }) => models.items.findOne({ id: root.id }, { _id: false, rsbuddy: true }) } } })
import Item from "./graphql/types/item" import Update from "./graphql/types/update" import { makeExecutableSchema } from "graphql-tools" const RuneScapeQuery = ` type RuneScapeQuery { items: [Item] item(id: Int!): Item updates: [Update] } ` const SchemaDefinition = ` schema { query: RuneScapeQuery } ` export default makeExecutableSchema({ typeDefs: [SchemaDefinition, RuneScapeQuery, Item, Update], resolvers: { RuneScapeQuery: { items: (root, { ids }, { models }) => models.items.find({}, { _id: false, rsbuddy: false }), item: (root, { id }, { models }) => models.items.findOne({ id }, { _id: false, rsbuddy: false }), updates: (root, args, { models }) => models.updates.find({}, { _id: false }) }, Item: { rsbuddy: ({ id }, args, { models }) => models.items .findOne({ id }, { _id: false, rsbuddy: true }) .then(tx => tx.rsbuddy) } } })
Fix issue in retrieval of transactions
Fix issue in retrieval of transactions
JavaScript
mit
DevNebulae/ads-pt-api
--- +++ @@ -28,8 +28,10 @@ models.updates.find({}, { _id: false }) }, Item: { - rsbuddy: (root, args, { models }) => - models.items.findOne({ id: root.id }, { _id: false, rsbuddy: true }) + rsbuddy: ({ id }, args, { models }) => + models.items + .findOne({ id }, { _id: false, rsbuddy: true }) + .then(tx => tx.rsbuddy) } } })
af23ebea023e24437457d534c58f45e8ceffaeba
src/js/veturilo.js
src/js/veturilo.js
function findStations(callback) { $.ajax({ type: 'GET', url: 'http://localhost:8765/mockdata/veturilo.xml', dataType: 'xml', success: function (xml) { var stations = []; $(xml).find('place').each(function () { var place = $(this); var station = { name: place.attr('name'), lat: place.attr('lat'), lng: place.attr('lng'), bikes: place.attr('bikes'), racks: place.attr('bike_racks') }; stations.push(station); }); callback(stations); } }); } var distanceSquare = function (pointA, pointB) { var x = pointA.lat - pointB.lat; var y = pointA.lng - pointB.lng; return (x * x) + (y * y); }; function findNearestStation(point, stations) { var nearest = null; var smallestDistanceSquare; $.each(stations, function (i, station) { var distance = distanceSquare(point, station); if ((nearest === null) || ((smallestDistanceSquare > distance) && (stations.bikes != '0'))) { nearest = station; smallestDistanceSquare = distance; } }); return nearest; }
function findStations(callback) { $.ajax({ type: 'GET', url: 'mockdata/veturilo.xml', dataType: 'xml', success: function (xml) { var stations = []; $(xml).find('place').each(function () { var place = $(this); var station = { name: place.attr('name'), lat: place.attr('lat'), lng: place.attr('lng'), bikes: place.attr('bikes'), racks: place.attr('bike_racks') }; stations.push(station); }); callback(stations); } }); } var distanceSquare = function (pointA, pointB) { var x = pointA.lat - pointB.lat; var y = pointA.lng - pointB.lng; return (x * x) + (y * y); }; function findNearestStation(point, stations) { var nearest = null; var smallestDistanceSquare; $.each(stations, function (i, station) { var distance = distanceSquare(point, station); if ((nearest === null) || ((smallestDistanceSquare > distance) && (stations.bikes != '0'))) { nearest = station; smallestDistanceSquare = distance; } }); return nearest; }
Use relative path to mock data
Use relative path to mock data
JavaScript
mit
janisz/bikeday,janisz/bikeday,Freeport-Metrics/bikeday
--- +++ @@ -1,7 +1,7 @@ function findStations(callback) { $.ajax({ type: 'GET', - url: 'http://localhost:8765/mockdata/veturilo.xml', + url: 'mockdata/veturilo.xml', dataType: 'xml', success: function (xml) { var stations = [];
93f5f27fd4c56ffc69be517f0fed021e9fcaefd8
static/index.js
static/index.js
$(function(){ var url = 'https://storage.googleapis.com/rutracker-rss.appspot.com/category_map.json'; var url = 'https://dl.dropboxusercontent.com/u/660127/category_map.json'; // TODO $.getJSON(url, {}, function(data, textStatus){ var tree = $('#ctree').treeview({ data: JSON.stringify(data) }); }); });
$(function(){ var url = 'https://storage.googleapis.com/rutracker-rss.appspot.com/category_map.json'; $.getJSON(url, {}, function(data, textStatus){ var tree = $('#ctree').treeview({ data: JSON.stringify(data) }); }); });
Set correct JSON for production
Set correct JSON for production
JavaScript
apache-2.0
notapresent/rutracker_rss,notapresent/rutracker_rss,notapresent/rutracker_rss
--- +++ @@ -1,6 +1,5 @@ $(function(){ var url = 'https://storage.googleapis.com/rutracker-rss.appspot.com/category_map.json'; - var url = 'https://dl.dropboxusercontent.com/u/660127/category_map.json'; // TODO $.getJSON(url, {}, function(data, textStatus){
7492a1890a216e2cc72a57d7736932c490c21461
src/redux/state/fakeEvents.test.js
src/redux/state/fakeEvents.test.js
/* global test, expect */ import fakeEvents from './fakeEvents'; test('calling fakeEvents should generate an array containing btw. 60 and 120 objects', () => { expect(fakeEvents.length) .toBeGreaterThanOrEqual(60); expect(fakeEvents.length) .toBeLessThanOrEqual(120); });
/* global test, expect */ import fakeEvents from './fakeEvents'; test('calling fakeEvents should generate an array containing btw. 60 and 120 objects', () => { expect(fakeEvents.length) .toBeGreaterThanOrEqual(60); expect(fakeEvents.length) .toBeLessThanOrEqual(120); }); test('events generated with fakeEvents should include 3 major keys: id, data & state', () => { fakeEvents.forEach((event) => expect(Object.keys(event)).toEqual(['id', 'data', 'state']) ); }); test('all events should have a string id', () => { fakeEvents.forEach((event) => { expect(event.id).not.toBeUndefined(); expect(typeof event.id).toBe('string'); }); });
Make sure events have the right keys and an id
Make sure events have the right keys and an id
JavaScript
mit
vogelino/design-timeline,vogelino/design-timeline
--- +++ @@ -7,3 +7,16 @@ expect(fakeEvents.length) .toBeLessThanOrEqual(120); }); + +test('events generated with fakeEvents should include 3 major keys: id, data & state', () => { + fakeEvents.forEach((event) => + expect(Object.keys(event)).toEqual(['id', 'data', 'state']) + ); +}); + +test('all events should have a string id', () => { + fakeEvents.forEach((event) => { + expect(event.id).not.toBeUndefined(); + expect(typeof event.id).toBe('string'); + }); +});
feb0ecd14c35c5694803db38e0d1f5644a5b7d3d
src/node/server.js
src/node/server.js
var http = require("http"); function onRequest(request, response) { console.log("Request received."); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); } http.createServer(onRequest).listen(8888); console.log("Server has started.");
var http = require("http"); function start() { function onRequest(request, response) { console.log("Request received."); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); } http.createServer(onRequest).listen(8888); console.log("Server has started."); } exports.start = start;
Package the script with a `start` function
Package the script with a `start` function
JavaScript
apache-2.0
Rholais/txfs,Rholais/txfs,Rholais/txfs
--- +++ @@ -1,12 +1,15 @@ var http = require("http"); -function onRequest(request, response) { - console.log("Request received."); - response.writeHead(200, {"Content-Type": "text/plain"}); - response.write("Hello World"); - response.end(); +function start() { + function onRequest(request, response) { + console.log("Request received."); + response.writeHead(200, {"Content-Type": "text/plain"}); + response.write("Hello World"); + response.end(); + } + + http.createServer(onRequest).listen(8888); + console.log("Server has started."); } -http.createServer(onRequest).listen(8888); - -console.log("Server has started."); +exports.start = start;
fdc725c500c0fe63a930dcee19d87bfc2831933a
Chapter-2-Exercises/jjhampton-ch2-ex3-chessboard.js
Chapter-2-Exercises/jjhampton-ch2-ex3-chessboard.js
'use strict' // Chess board // Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a “#” character. The characters should form a chess board. // Passing this string to console.log should show something like this: // # # # # // # # # # // # # # # // # # # # // # # # # // # # # # // # # # # // # # # # // When you have a program that generates this pattern, define a variable size = 8 and change the program so that it works for any size, outputting a grid of the given width and height. const size = 8; // this can be changed to any size grid let string = ''; for (let i = 0; i < size; i++) { for (let j = 0; j <= size; j ++) { if (j === size) { string += '\n'; break; } let character = i + j; // toggles the output character on even/odd lines if (character % 2 === 0) string += ' '; else string += '#'; } } console.log(string);
'use strict' // Chess board // Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a “#” character. The characters should form a chess board. // Passing this string to console.log should show something like this: // # # # # // # # # # // # # # # // # # # # // # # # # // # # # # // # # # # // # # # # // When you have a program that generates this pattern, define a variable size = 8 and change the program so that it works for any size, outputting a grid of the given width and height. const size = 8; // this can be changed to any size grid let outputString = ''; for (let i = 0; i < size; i++) { for (let j = 0; j <= size; j ++) { if (j === size) { outputString += '\n'; break; } let character = i + j; // toggles the output character on even/odd lines if (character % 2 === 0) outputString += ' '; else outputString += '#'; } } console.log(outputString);
Rename variable to avoid using reserved word `string`
Rename variable to avoid using reserved word `string`
JavaScript
mit
OperationCode/eloquent-js
--- +++ @@ -17,22 +17,22 @@ const size = 8; // this can be changed to any size grid -let string = ''; +let outputString = ''; for (let i = 0; i < size; i++) { for (let j = 0; j <= size; j ++) { if (j === size) { - string += '\n'; + outputString += '\n'; break; } let character = i + j; // toggles the output character on even/odd lines if (character % 2 === 0) - string += ' '; + outputString += ' '; else - string += '#'; + outputString += '#'; } } -console.log(string); +console.log(outputString);
32f9c800025440756fa63211fc4c0e89c1ae4506
src/store/index.js
src/store/index.js
import Vue from 'vue' import Vuex from 'vuex' import * as actions from './actions' import * as mutations from './mutations' import * as getters from './getters' Vue.use(Vuex) export default new Vuex.Store({ state: { // Authentication state token: sessionStorage.getItem('token') || '', status: '', // end of Authentication state // System state systemInfo: {}, // end system state // Dashboard state isMobile: '', displaySettings: false, displayInfo: false, displayAlerts: false, displayLogout: false, displayThings: false, blur: false, // end of Dashboard state language: 'en', // Settings state systemOpen: false, automationsOpen: false, languagesOpen: false, pluginsOpen: false, rolesOpen: false, usersOpen: false, // end of Settings state advancedMode: false, // API state automationsList: '', commandsList: '', environmentsList: '', marketplaceCategoriesList: '', marketplaceCategoryPluginsList: '', pluginsList: '', rolesList: '', roomsList: '', thingsList: '', thingTemplatesList: '', triggersList: '', usersList: '' }, actions, mutations, getters })
import Vue from 'vue' import Vuex from 'vuex' import * as actions from './actions' import * as mutations from './mutations' import * as getters from './getters' Vue.use(Vuex) export default new Vuex.Store({ state: { // Authentication state token: sessionStorage.getItem('token') || '', status: '', // end of Authentication state // System state systemInfo: {}, // end system state // Dashboard state isMobile: '', displaySettings: false, displayInfo: false, displayAlerts: false, displayLogout: false, displayThings: false, blur: false, // end of Dashboard state language: 'en', // Settings state systemOpen: false, automationsOpen: false, languagesOpen: false, pluginsOpen: false, rolesOpen: false, usersOpen: false, // end of Settings state advancedMode: false, // API state automationsList: '', commandsList: '', environmentsList: '', marketplaceCategoriesList: '', marketplaceCategoryPluginsList: '', pluginsList: '', rolesList: '', roomsList: '', thingsList: [], thingTemplatesList: '', triggersList: '', usersList: '' }, actions, mutations, getters })
Change thinsList type to array
Change thinsList type to array
JavaScript
agpl-3.0
freedomotic/fd-vue-webapp,freedomotic/fd-vue-webapp
--- +++ @@ -43,7 +43,7 @@ pluginsList: '', rolesList: '', roomsList: '', - thingsList: '', + thingsList: [], thingTemplatesList: '', triggersList: '', usersList: ''
65e00c407ad40f279ca25aa0f54b1a753a5f593f
test/buster.js
test/buster.js
var config = module.exports; config["Browser tests"] = { rootPath: "../", environment: "browser", extensions: [require("buster-coffee")], sources: [ "test/ext/*.js", "dist/caman.full.js" ], tests: ["test/browser/*.coffee"] }; config["Node tests"] = { rootPath: "../", environment: "node", extensions: [require("buster-coffee")], tests: ["test/node/*.coffee"] };
var config = module.exports; config["Browser tests"] = { rootPath: "../", environment: "browser", extensions: [require("buster-coffee")], sources: [ "test/ext/*.js", "dist/caman.full.js" ], tests: ["test/browser/*.coffee"] }; // For some reason, Buster doesn't quit when you define two // different testing groups. Fairly certain this is a bug with // the testing framework. // config["Node tests"] = { // rootPath: "../", // environment: "node", // extensions: [require("buster-coffee")], // tests: ["test/node/*.coffee"] // };
Disable node tests for now
Disable node tests for now
JavaScript
bsd-3-clause
prashen/CamanJS,purposeindustries/CamanJS,mcanthony/CamanJS,mcanthony/CamanJS,arschmitz/caman-dist-only,meltingice/CamanJS,ckfinder/CamanJS,rn2dy/CamanJS,rn2dy/CamanJS,purposeindustries/CamanJS,mcanthony/CamanJS,meltingice/CamanJS,prashen/CamanJS,rn2dy/CamanJS,meltingice/CamanJS,ckfinder/CamanJS,prashen/CamanJS,ckfinder/CamanJS
--- +++ @@ -11,9 +11,12 @@ tests: ["test/browser/*.coffee"] }; -config["Node tests"] = { - rootPath: "../", - environment: "node", - extensions: [require("buster-coffee")], - tests: ["test/node/*.coffee"] -}; +// For some reason, Buster doesn't quit when you define two +// different testing groups. Fairly certain this is a bug with +// the testing framework. +// config["Node tests"] = { +// rootPath: "../", +// environment: "node", +// extensions: [require("buster-coffee")], +// tests: ["test/node/*.coffee"] +// };
077e0ac53af3506f4d11d8bd157bf9de89761a9e
lib/adapter.js
lib/adapter.js
(function(karma, window) { var createClojureScriptTest = function (tc, runnerPassedIn) { return function () { if (goog && goog.dependencies_ && goog.dependencies_.nameToPath) { for(var namespace in goog.dependencies_.nameToPath) goog.require(namespace); } circle.karma.run_tests_for_karma(tc); }; }; karma.start = createClojureScriptTest(karma); })(window.__karma__, window);
(function(karma, window) { var createClojureScriptTest = function (tc, runnerPassedIn) { return function () { if ('undefined' !== typeof goog && goog.dependencies_ && goog.dependencies_.nameToPath) { for(var namespace in goog.dependencies_.nameToPath) goog.require(namespace); } circle.karma.run_tests_for_karma(tc); }; }; karma.start = createClojureScriptTest(karma); })(window.__karma__, window);
Fix missing goog issue for real
Fix missing goog issue for real
JavaScript
mit
circleci/karma-cljs.test
--- +++ @@ -1,7 +1,7 @@ (function(karma, window) { var createClojureScriptTest = function (tc, runnerPassedIn) { return function () { - if (goog && goog.dependencies_ && goog.dependencies_.nameToPath) { + if ('undefined' !== typeof goog && goog.dependencies_ && goog.dependencies_.nameToPath) { for(var namespace in goog.dependencies_.nameToPath) goog.require(namespace); }
85d62a542b153523eba52ccf0b869b7c8fd64c87
app/_reducers/marketsReducers.js
app/_reducers/marketsReducers.js
import { Map } from 'immutable'; import { FILTER_MARKETS, UPDATE_MARKETS, SERVER_DATA_ACTIVE_SYMBOLS } from '../_constants/ActionTypes'; const initialState = new Map({ active: [], query: '', shownMarkets: [], }); export default (state = initialState, action) => { const doFilter = (markets = state.allMarkets, query = state.query) => { const queryLc = query.toLowerCase(); return markets.filter(m => queryLc === '' || m.id.toLowerCase().includes(queryLc) || m.name.toLowerCase().includes(queryLc) ); }; switch (action.type) { case SERVER_DATA_ACTIVE_SYMBOLS: { const data = action.serverResponse.data; return state.set('active', data); } case FILTER_MARKETS: return { ...state, shownMarkets: doFilter(state.markets, action.query), query: action.query, }; case UPDATE_MARKETS: return { ...state, shownMarkets: doFilter(state.markets, action.query), query: action.query, }; default: return state; } };
import { Map } from 'immutable'; import { FILTER_MARKETS, UPDATE_MARKETS, SERVER_DATA_ACTIVE_SYMBOLS } from '../_constants/ActionTypes'; const initialState = new Map({ active: [], tree: {}, query: '', shownMarkets: [], }); const generateTree = (symbols) => { const tree = {}; symbols.forEach((sym) => { if (!tree[sym.market_display_name]) tree[sym.market_display_name] = {}; if (!tree[sym.market_display_name][sym.submarket_display_name]) tree[sym.market_display_name][sym.submarket_display_name] = {}; tree[sym.market_display_name][sym.submarket_display_name][sym] = sym.display_name; }); return new Map(tree); }; export default (state = initialState, action) => { const doFilter = (markets = state.allMarkets, query = state.query) => { const queryLc = query.toLowerCase(); return markets.filter(m => queryLc === '' || m.id.toLowerCase().includes(queryLc) || m.name.toLowerCase().includes(queryLc) ); }; switch (action.type) { case SERVER_DATA_ACTIVE_SYMBOLS: { const activeSymbols = action.serverResponse.data; return state .set('active', activeSymbols) .set('tree', generateTree(activeSymbols)); } case FILTER_MARKETS: return { ...state, shownMarkets: doFilter(state.markets, action.query), query: action.query, }; case UPDATE_MARKETS: return { ...state, shownMarkets: doFilter(state.markets, action.query), query: action.query, }; default: return state; } };
Add market tree built from active symbols
Add market tree built from active symbols
JavaScript
mit
nuruddeensalihu/binary-next-gen,binary-com/binary-next-gen,nazaninreihani/binary-next-gen,nazaninreihani/binary-next-gen,nazaninreihani/binary-next-gen,qingweibinary/binary-next-gen,binary-com/binary-next-gen,qingweibinary/binary-next-gen,nuruddeensalihu/binary-next-gen,qingweibinary/binary-next-gen,binary-com/binary-next-gen,nuruddeensalihu/binary-next-gen
--- +++ @@ -3,9 +3,20 @@ const initialState = new Map({ active: [], + tree: {}, query: '', shownMarkets: [], }); + +const generateTree = (symbols) => { + const tree = {}; + symbols.forEach((sym) => { + if (!tree[sym.market_display_name]) tree[sym.market_display_name] = {}; + if (!tree[sym.market_display_name][sym.submarket_display_name]) tree[sym.market_display_name][sym.submarket_display_name] = {}; + tree[sym.market_display_name][sym.submarket_display_name][sym] = sym.display_name; + }); + return new Map(tree); +}; export default (state = initialState, action) => { const doFilter = (markets = state.allMarkets, query = state.query) => { @@ -19,8 +30,10 @@ switch (action.type) { case SERVER_DATA_ACTIVE_SYMBOLS: { - const data = action.serverResponse.data; - return state.set('active', data); + const activeSymbols = action.serverResponse.data; + return state + .set('active', activeSymbols) + .set('tree', generateTree(activeSymbols)); } case FILTER_MARKETS: return {
58366dc23b55c0256633d1d9abb4fba7e475a13c
resource/js/components/UserList.js
resource/js/components/UserList.js
import React from 'react'; import UserPicture from './User/UserPicture'; export default class UserList extends React.Component { render() { const users = this.props.users.map((user) => { return ( <a data-user-id={user._id} href={'/user/' + user.username} title={user.name}> <UserPicture user={user} size="xs" /> </a> ); }); return ( <p className="seen-user-list"> {users} </p> ); } } UserList.propTypes = { users: React.PropTypes.array, }; UserList.defaultProps = { users: [], };
import React from 'react'; import UserPicture from './User/UserPicture'; export default class UserList extends React.Component { render() { const users = this.props.users.map((user) => { return ( <a key={user._id} data-user-id={user._id} href={'/user/' + user.username} title={user.name}> <UserPicture user={user} size="xs" /> </a> ); }); return ( <p className="seen-user-list"> {users} </p> ); } } UserList.propTypes = { users: React.PropTypes.array, }; UserList.defaultProps = { users: [], };
Add unique key to items
Add unique key to items
JavaScript
mit
crow-misia/crowi,crowi/crowi,crowi/crowi,crow-misia/crowi,crowi/crowi
--- +++ @@ -6,7 +6,7 @@ render() { const users = this.props.users.map((user) => { return ( - <a data-user-id={user._id} href={'/user/' + user.username} title={user.name}> + <a key={user._id} data-user-id={user._id} href={'/user/' + user.username} title={user.name}> <UserPicture user={user} size="xs" /> </a> );
3c5cf643d11d44ede31f212a5af683b4785d13bc
app/scenes/SearchScreen/index.js
app/scenes/SearchScreen/index.js
import React, { Component } from 'react'; import { StyleSheet, Text, View } from 'react-native'; export default class SearchScreen extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.js </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, });
import React, { Component } from 'react'; import RepoSearchBar from './components/RepoSearchBar'; export default class SearchScreen extends Component { render() { return ( <RepoSearchBar /> ); } }
Remove boilerplate and render the search bar
Remove boilerplate and render the search bar
JavaScript
mit
msanatan/GitHubProjects,msanatan/GitHubProjects,msanatan/GitHubProjects
--- +++ @@ -1,45 +1,11 @@ import React, { Component } from 'react'; -import { - StyleSheet, - Text, - View -} from 'react-native'; +import RepoSearchBar from './components/RepoSearchBar'; export default class SearchScreen extends Component { render() { return ( - <View style={styles.container}> - <Text style={styles.welcome}> - Welcome to React Native! - </Text> - <Text style={styles.instructions}> - To get started, edit index.js - </Text> - <Text style={styles.instructions}> - Press Cmd+R to reload,{'\n'} - Cmd+D or shake for dev menu - </Text> - </View> + <RepoSearchBar /> ); } } -const styles = StyleSheet.create({ - container: { - flex: 1, - justifyContent: 'center', - alignItems: 'center', - backgroundColor: '#F5FCFF', - }, - welcome: { - fontSize: 20, - textAlign: 'center', - margin: 10, - }, - instructions: { - textAlign: 'center', - color: '#333333', - marginBottom: 5, - }, -}); -
f030906e54e9e569b7a12a05d369746a5fc7024f
app/scripts/hocs/with-pub-sub.js
app/scripts/hocs/with-pub-sub.js
import React from 'react'; import toVoid from '../utils/to-void'; const fake = { __fake__: true, publish: toVoid, subscribe: toVoid, unsubscribe: toVoid }; const { Provider, Consumer } = React.createContext(fake); // Higher order component const withPubSub = Component => props => ( <Consumer> {pubSub => <Component {...props} pubSub={pubSub} />} </Consumer> ); export default withPubSub; export { Provider };
import React from 'react'; import toVoid from '../utils/to-void'; const fake = { __fake__: true, publish: toVoid, subscribe: toVoid, unsubscribe: toVoid }; const { Provider, Consumer } = React.createContext(fake); // Higher order component const withPubSub = Component => React.forwardRef((props, ref) => ( <Consumer> {pubSub => <Component {...props} pubSub={pubSub} />} </Consumer> )); export default withPubSub; export { Provider };
Fix regression (i.e., forward `key`)
Fix regression (i.e., forward `key`)
JavaScript
mit
hms-dbmi/higlass,hms-dbmi/higlass,hms-dbmi/higlass,hms-dbmi/4DN_matrix-viewer,hms-dbmi/4DN_matrix-viewer,hms-dbmi/higlass,hms-dbmi/4DN_matrix-viewer
--- +++ @@ -12,11 +12,11 @@ const { Provider, Consumer } = React.createContext(fake); // Higher order component -const withPubSub = Component => props => ( +const withPubSub = Component => React.forwardRef((props, ref) => ( <Consumer> {pubSub => <Component {...props} pubSub={pubSub} />} </Consumer> -); +)); export default withPubSub;
7069dd332481662adc09252ce65c9796c2d6abed
app/src/services/user.service.js
app/src/services/user.service.js
const logger = require('logger'); const ctRegisterMicroservice = require('ct-register-microservice-node'); class UserService { static async getEmailById(userId) { logger.info('Get user by user id', userId); try { const user = await ctRegisterMicroservice.requestToMicroservice({ uri: '/user/' + userId, method: 'GET', json: true }); if (!user || !user.data) return null; logger.info('Get user by user id', user); return user.data && user.data.attributes.email; } catch (e) { logger.info('Error finding user', e); return null; } } } module.exports = UserService;
const logger = require('logger'); const ctRegisterMicroservice = require('ct-register-microservice-node'); class UserService { static async getEmailById(userId) { logger.info('Get user by user id', userId); try { const user = await ctRegisterMicroservice.requestToMicroservice({ uri: '/user/' + userId, method: 'GET', json: true }); if (!user || !user.data) return null; logger.info('Get user by user id', user); return user.data ? user.data.attributes.email : null; } catch (e) { logger.info('Error finding user', e); return null; } } } module.exports = UserService;
Fix the fix to fix the error
Fix the fix to fix the error
JavaScript
mit
gfw-api/fw-teams,gfw-api/fw-teams
--- +++ @@ -12,7 +12,7 @@ }); if (!user || !user.data) return null; logger.info('Get user by user id', user); - return user.data && user.data.attributes.email; + return user.data ? user.data.attributes.email : null; } catch (e) { logger.info('Error finding user', e);
f320562f84d8e23d8d78d7a01ab8464f69b135fc
apps-builtin/wifi-setup/index.js
apps-builtin/wifi-setup/index.js
var wifiManager = require('../../lib/WifiManager'); var hb = require('handlebars'); var fs = require('fs'); const path = require('path'); var subApp = function(){ this.staticFolder = "assets"; this.setup = function(router, express){ router.get('/', function(req, res) { fs.readFile(path.join(__dirname, './index.html'), 'utf-8', function(error, source){ var template = hb.compile(source); res.send(template()) }); }); router.get('/accesspoints', function(req, res) { wifiManager.listAccessPoints(function(err, list){ res.json({accesspoints: list}); }); }); router.get('/status', function(req, res) { wifiManager.getStatus(function(err, status){ if(!err){ res.json(status); }else{ res.sendStatus(500); } }); }); router.post('/configure', function(req, res) { wifiManager.joinAccessPoint(req.body.ssid, req.body.password); res.sendStatus(200); }); } return this; } module.exports = subApp();
var wifiManager = require('../../lib/WifiManager'); var hb = require('handlebars'); var fs = require('fs'); const path = require('path'); var subApp = function(){ this.staticFolder = "assets"; this.setup = function(router, express){ router.get('/', function(req, res) { fs.readFile(path.join(__dirname, './index.html'), 'utf-8', function(error, source){ var template = hb.compile(source); res.send(template()) }); }); router.get('/accesspoints', function(req, res) { wifiManager.listAccessPoints(function(err, list){ res.json({accesspoints: list}); }); }); router.get('/status', function(req, res) { wifiManager.getStatus(function(err, status){ if(!err){ res.json(status); }else{ res.sendStatus(500); } }); }); router.post('/configure', function(req, res) { if(req.body && req.body.ssid && req.body.password){ wifiManager.joinAccessPoint(req.body.ssid, req.body.password); res.sendStatus(200); }else{ res.sendStatus(500); } }); } return this; } module.exports = subApp();
Add check for wifi details
Add check for wifi details
JavaScript
isc
headlessPi/headlessPi,headlessPi/headlessPi,headlessPi/headlessPi
--- +++ @@ -32,8 +32,12 @@ }); router.post('/configure', function(req, res) { - wifiManager.joinAccessPoint(req.body.ssid, req.body.password); - res.sendStatus(200); + if(req.body && req.body.ssid && req.body.password){ + wifiManager.joinAccessPoint(req.body.ssid, req.body.password); + res.sendStatus(200); + }else{ + res.sendStatus(500); + } }); }
f7c280b693f36b1a797bec51eea6eb139d5f1bc1
lib/dashboard/repl.js
lib/dashboard/repl.js
const repl = require("repl"); class REPL { constructor(options) { this.env = options.env; this.plugins = options.plugins; } start(done) { this.replServer = repl.start({ prompt: "Embark (" + this.env + ") > ", useGlobal: true }); this.replServer.on("exit", () => { process.exit(); }); let self = this; this.replServer.defineCommand('profile', { help: 'Profile a contract', action(contract) { this.clearBufferedCommand(); let pluginCmds = self.plugins.getPluginsProperty('console', 'console'); for (let pluginCmd of pluginCmds) { pluginCmd.call(self, `profile ${contract}`, {}); } this.displayPrompt(); } }); done(); } } module.exports = REPL;
const repl = require("repl"); const Console = require('./console.js'); class REPL { constructor(options) { this.env = options.env; this.plugins = options.plugins; this.events = options.events; this.console = new Console({ events: this.events, plugins: this.plugins, version: options.version }); } enhancedEval(cmd, context, filename, callback) { this.console.executeCmd(cmd.trim(), (result) => { callback(null, result); }); } start(done) { this.replServer = repl.start({ prompt: "Embark (" + this.env + ") > ", useGlobal: true, eval: this.enhancedEval.bind(this) }); this.replServer.on("exit", () => { process.exit(); }); done(); } } module.exports = REPL;
Use console and override evaluator
Use console and override evaluator
JavaScript
mit
iurimatias/embark-framework,iurimatias/embark-framework
--- +++ @@ -1,32 +1,34 @@ const repl = require("repl"); + +const Console = require('./console.js'); class REPL { constructor(options) { this.env = options.env; this.plugins = options.plugins; + this.events = options.events; + this.console = new Console({ + events: this.events, + plugins: this.plugins, + version: options.version + }); + } + + enhancedEval(cmd, context, filename, callback) { + this.console.executeCmd(cmd.trim(), (result) => { + callback(null, result); + }); } start(done) { this.replServer = repl.start({ prompt: "Embark (" + this.env + ") > ", - useGlobal: true + useGlobal: true, + eval: this.enhancedEval.bind(this) }); this.replServer.on("exit", () => { process.exit(); - }); - - let self = this; - this.replServer.defineCommand('profile', { - help: 'Profile a contract', - action(contract) { - this.clearBufferedCommand(); - let pluginCmds = self.plugins.getPluginsProperty('console', 'console'); - for (let pluginCmd of pluginCmds) { - pluginCmd.call(self, `profile ${contract}`, {}); - } - this.displayPrompt(); - } }); done();
c136fb4191a5e9e5052ef778dce1fb0bad785b2a
test/createMockRaf.js
test/createMockRaf.js
/* @flow */ type Callback = (now: number) => void; export default function(): Object { let allCallbacks = []; let prevTime = 0; const now = () => prevTime; const raf = (cb: Callback) => { allCallbacks.push(cb); }; const defaultTimeInterval = 1000 / 60; const _step = ms => { const allCallbacksBefore = allCallbacks; allCallbacks = []; prevTime += ms; allCallbacksBefore.forEach(cb => cb(prevTime)); }; const step = (howMany = 1, ms = defaultTimeInterval) => { for (let i = 0; i < howMany; i++) { _step(ms); } }; return {now, raf, step}; }
/* @flow */ type Callback = (now: number) => void; export default function(): Object { let allCallbacks = []; let prevTime = 0; let id = 0; const now = () => prevTime; const raf = (cb: Callback) => { allCallbacks.push(cb); return id++; }; const defaultTimeInterval = 1000 / 60; const _step = ms => { const allCallbacksBefore = allCallbacks; allCallbacks = []; prevTime += ms; allCallbacksBefore.forEach(cb => cb(prevTime)); }; const step = (howMany = 1, ms = defaultTimeInterval) => { for (let i = 0; i < howMany; i++) { _step(ms); } }; return {now, raf, step}; }
Implement rAF mock return correctly
Implement rAF mock return correctly rAF should return a uuid. Components check the assigned id non-null-ness for some purposes. cc @bsansouci
JavaScript
mit
keyanzhang/react-motion,threepointone/react-motion,chenglou/react-motion,BenoitZugmeyer/preact-motion,BenoitZugmeyer/preact-motion,chenglou/react-motion,threepointone/react-motion,keyanzhang/react-motion
--- +++ @@ -5,11 +5,13 @@ export default function(): Object { let allCallbacks = []; let prevTime = 0; + let id = 0; const now = () => prevTime; const raf = (cb: Callback) => { allCallbacks.push(cb); + return id++; }; const defaultTimeInterval = 1000 / 60;
812910a3916d73e4728bc483312bebe900b1d99c
lib/wrapper.js
lib/wrapper.js
'use strict'; var through = require('through') , loader = require('./loader') , async = require('async'); function angularify() { var buf = ''; return through(function(chunk) { buf += chunk.toString(); }, function () { var rexSingle = new RegExp(/require\('angula[^']+'\)[,;]/g) , rexDouble = new RegExp(/require\("angula[^']+"\)[,;]/g) // , rexModule = new RegExp(/\(.*?\)/) , requires = [] , self = this; requires = requires.concat(buf.match(rexSingle)); requires = requires.concat(buf.match(rexDouble)); async.eachSeries(requires, function (req, callback) { if (req === null) { return callback(); } var modVer = req .replace('require(', '') .replace(/\)[,;]/, '') .replace(/\'|\"/g, '') .split('@'); loader.getModule(modVer[0], modVer[1], function (err, module) { // JavaScript String.replace gives unexpected result with $ chars // replace these temporarily... module = module.replace(/\$/g, '_'); // Insert angular buf = buf.replace(req, module); // Now insert the $ chars again... buf = buf.replace(/_/, '$'); callback(); }); }, function (err) { if (err) { throw err; } self.queue(buf); self.queue(null); }); }); } module.exports = angularify;
'use strict'; var through = require('through') , loader = require('./loader') , async = require('async'); function angularify() { var buf = ''; return through(function(chunk) { buf += chunk.toString(); }, function () { var rexSingle = new RegExp(/require\('angula[^']+'\)[,;]/g) , rexDouble = new RegExp(/require\("angula[^']+"\)[,;]/g) // , rexModule = new RegExp(/\(.*?\)/) , requires = [] , self = this; requires = requires.concat(buf.match(rexSingle)); requires = requires.concat(buf.match(rexDouble)); async.eachSeries(requires, function (req, callback) { if (req === null) { return callback(); } var modVer = req .replace('require(', '') .replace(/\)[,;]/, '') .replace(/\'|\"/g, '') .split('@'); loader.getModule(modVer[0], modVer[1], function (err, module) { module += 'module.exports = window.angular'; // JavaScript String.replace gives unexpected result with $ chars // replace these temporarily... module = module.replace(/\$/g, '_DOLLARBANG_'); // Insert angular buf = buf.replace(req, module); // Now insert the $ chars again... buf = buf.replace(/_DOLLARBANG_/g, '$'); callback(); }); }, function (err) { if (err) { throw err; } self.queue(buf); self.queue(null); }); }); } module.exports = angularify;
Fix dollar sign issue in angular injection
Fix dollar sign issue in angular injection
JavaScript
mit
evanshortiss/angularify
--- +++ @@ -31,15 +31,17 @@ .split('@'); loader.getModule(modVer[0], modVer[1], function (err, module) { + module += 'module.exports = window.angular'; + // JavaScript String.replace gives unexpected result with $ chars // replace these temporarily... - module = module.replace(/\$/g, '_'); + module = module.replace(/\$/g, '_DOLLARBANG_'); // Insert angular buf = buf.replace(req, module); // Now insert the $ chars again... - buf = buf.replace(/_/, '$'); + buf = buf.replace(/_DOLLARBANG_/g, '$'); callback(); });
790c99ea4cca145835d067ffe7c4052122c596fd
lib/composition/parsers/flow-component.js
lib/composition/parsers/flow-component.js
// Dependencies var ParseMethod = require("./method") , Enny = require("enny") , Ul = require("ul") , Typpy = require("typpy") ; module.exports = function (_input, instName) { var input = Ul.clone(_input); if (Typpy(input, String)) { input = [input]; } var output = {} , eP = null , mP = null ; // Load if (input[0] === Enny.TYPES.load.handler) { output.type = Enny.TYPES.load; output.args = input.slice(1); // Emit/link } else if ((eP = ParseMethod(input[0], instName)).method === "flow") { if (Enny.TYPES((mP = ParseMethod(input[1], instName)).type, Enny.TYPES.link)) { output = mP; output.type = Enny.TYPES.link; output.serverMethod = output.method; } else { output = eP; output.type = Enny.TYPES.emit; output.event = input[1]; } } // Stream handler if (!output.type) { output = ParseMethod(input[0], instName); output.args = input.slice(1); } return output; };
// Dependencies var ParseMethod = require("./method") , Enny = require("enny") , Ul = require("ul") , Typpy = require("typpy") ; module.exports = function (_input, instName) { var input = Ul.clone(_input); if (Typpy(input, String)) { input = [input]; } var output = {} , eP = null , mP = null ; // Load if (input[0] === Enny.TYPES.load.handler) { output.type = Enny.TYPES.load; output.args = input.slice(1); // Emit/link } else if ((eP = ParseMethod(input[0], instName)).method === "flow") { if (Enny.TYPES((mP = ParseMethod(input[1], instName)).type, Enny.TYPES.link)) { output = mP; output.type = Enny.TYPES.link; output.serverMethod = output.method; output.event = output.method; } else { output = eP; output.type = Enny.TYPES.emit; output.event = input[1]; } } // Stream handler if (!output.type) { output = ParseMethod(input[0], instName); output.args = input.slice(1); } return output; };
Append the event name in case of server methods too
Append the event name in case of server methods too
JavaScript
mit
jillix/engine-builder
--- +++ @@ -27,6 +27,7 @@ output = mP; output.type = Enny.TYPES.link; output.serverMethod = output.method; + output.event = output.method; } else { output = eP; output.type = Enny.TYPES.emit;
062daaef9cbe78a5f37874237c4f2e36dd43d3e4
lib/EnvironmentPlugin.js
lib/EnvironmentPlugin.js
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Simen Brekken @simenbrekken */ var DefinePlugin = require("./DefinePlugin"); this.keys = Array.isArray(keys) ? keys : Object.keys(keys); this.defaultValues = Array.isArray(keys) ? {} : keys; } EnvironmentPlugin.prototype.apply = function(compiler) { compiler.apply(new DefinePlugin(this.keys.reduce(function(definitions, key) { var value = process.env[key] || this.defaultValues[key]; if(value === undefined && !this.silent) { compiler.plugin("this-compilation", function(compilation) { var error = new Error(key + " environment variable is undefined."); error.name = "EnvVariableNotDefinedError"; compilation.warnings.push(error); }); } definitions["process.env." + key] = value ? JSON.stringify(value) : "undefined"; return definitions; }.bind(this), {}))); }; module.exports = EnvironmentPlugin;
/* MIT License http://www.opensource.org/licenses/mit-license.php Authors Simen Brekken @simenbrekken, Einar Löve @einarlove */ var DefinePlugin = require("./DefinePlugin"); function EnvironmentPlugin(keys) { if (typeof keys === 'string') { throw new Error( "Deprecation notice: EnvironmentPlugin now only takes a single argument." + " Either an array of keys or object with default values." + "\nSee http://webpack.github.io/docs/list-of-plugins.html#environmentplugin for example." ); } this.keys = Array.isArray(keys) ? keys : Object.keys(keys); this.defaultValues = Array.isArray(keys) ? {} : keys; } EnvironmentPlugin.prototype.apply = function(compiler) { compiler.apply(new DefinePlugin(this.keys.reduce(function(definitions, key) { var value = process.env[key] || this.defaultValues[key]; if(value === undefined && !this.silent) { compiler.plugin("this-compilation", function(compilation) { var error = new Error(key + " environment variable is undefined."); error.name = "EnvVariableNotDefinedError"; compilation.warnings.push(error); }); } definitions["process.env." + key] = value ? JSON.stringify(value) : "undefined"; return definitions; }.bind(this), {}))); }; module.exports = EnvironmentPlugin;
Add drepecation notice for multiple arguments of strings
Add drepecation notice for multiple arguments of strings
JavaScript
mit
SimenB/webpack,webpack/webpack,SimenB/webpack,ts-webpack/webpack,SimenB/webpack,webpack/webpack,NekR/webpack,rlugojr/webpack,ts-webpack/webpack,webpack/webpack,webpack/webpack,g0ddish/webpack,jescalan/webpack,ts-webpack/webpack,jescalan/webpack,jescalan/webpack,NekR/webpack,g0ddish/webpack,SimenB/webpack,g0ddish/webpack,rlugojr/webpack,EliteScientist/webpack,rlugojr/webpack,ts-webpack/webpack,EliteScientist/webpack
--- +++ @@ -1,9 +1,17 @@ /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Simen Brekken @simenbrekken + Authors Simen Brekken @simenbrekken, Einar Löve @einarlove */ var DefinePlugin = require("./DefinePlugin"); +function EnvironmentPlugin(keys) { + if (typeof keys === 'string') { + throw new Error( + "Deprecation notice: EnvironmentPlugin now only takes a single argument." + + " Either an array of keys or object with default values." + + "\nSee http://webpack.github.io/docs/list-of-plugins.html#environmentplugin for example." + ); + } this.keys = Array.isArray(keys) ? keys : Object.keys(keys); this.defaultValues = Array.isArray(keys) ? {} : keys;
afcbd88b545b285128ac7f8d4a8cff605edfb3d2
docs/assets/js/docs.ad.js
docs/assets/js/docs.ad.js
var _kmq = _kmq || []; $(function() { // No need to do a timeout for default case, if KM times out just don't show ad. _kmq.push(function(){ // Set up the experiment (this is the meat and potatoes) var type = KM.ab("Foundation Docs Upsell Type", ["question", "directive"]); // TODO: Add alternate between advanced and intro var topic = $('h1.docs-page-title').text(); var header; if (type === 'directive') { header = 'Master ' + topic; } else { header = 'Struggling with ' + topic + '?'; } var body = 'Get up to speed FAST, learn straight from the experts who built Foundation.'; var link = 'http://zurb.com/university/foundation-intro?utm_source=Foundation%20Docs&utm_medium=Docs&utm_content=Struggling&utm_campaign=Docs%20To%20Intro'; var cta = 'Learn More'; var html = '<div class="ad-unit"><h3 class="ad-unit-title">' + header + '</h3>' + '<p class="ad-unit-text">' + body + '</p>' + '<a class="button ad-unit-button" href="' + link+ '">' + cta + '</a></div>'; $('#TOCAdUnit').html(html); }); });
$(function() { // TODO: Add alternate between advanced and intro var topic = $('h1.docs-page-title').text(); var header = 'Master ' + topic; var body = 'Get up to speed FAST, learn straight from the experts who built Foundation.'; var link = 'http://zurb.com/university/foundation-intro?utm_source=Foundation%20Docs&utm_medium=Docs&utm_content=Struggling&utm_campaign=Docs%20To%20Intro'; var cta = 'Learn More'; var html = '<div class="ad-unit"><h3 class="ad-unit-title">' + header + '</h3>' + '<p class="ad-unit-text">' + body + '</p>' + '<a class="button ad-unit-button" href="' + link+ '">' + cta + '</a></div>'; $('#TOCAdUnit').html(html); });
Update language to directive form
Update language to directive form
JavaScript
mit
jeromelebleu/foundation-sites,Owlbertz/foundation,BerndtGroup/TBG-foundation-sites,IamManchanda/foundation-sites,DaSchTour/foundation-sites,jaylensoeur/foundation-sites-6,colin-marshall/foundation-sites,Owlbertz/foundation,zurb/foundation,abdullahsalem/foundation-sites,aoimedia/foundation,dragthor/foundation-sites,zurb/foundation-sites,IamManchanda/foundation-sites,atmmarketing/foundation-sites,atmmarketing/foundation-sites,ucla/foundation-sites,denisahac/foundation-sites,ucla/foundation-sites,colin-marshall/foundation-sites,andycochran/foundation-sites,Owlbertz/foundation,PassKitInc/foundation-sites,zurb/foundation-sites,BerndtGroup/TBG-foundation-sites,Owlbertz/foundation,natewiebe13/foundation-sites,aoimedia/foundation,atmmarketing/foundation-sites,zurb/foundation,zurb/foundation-sites,socketz/foundation-multilevel-offcanvas,jamesstoneco/foundation-sites,natewiebe13/foundation-sites,ucla/foundation-sites,samuelmc/foundation-sites,karland/foundation-sites,karland/foundation-sites,karland/foundation-sites,samuelmc/foundation-sites,BerndtGroup/TBG-foundation-sites,andycochran/foundation-sites,abdullahsalem/foundation-sites,dragthor/foundation-sites,brettsmason/foundation-sites,IamManchanda/foundation-sites,samuelmc/foundation-sites,andycochran/foundation-sites,denisahac/foundation-sites,jamesstoneco/foundation-sites,PassKitInc/foundation-sites,socketz/foundation-multilevel-offcanvas,brettsmason/foundation-sites,denisahac/foundation-sites,jaylensoeur/foundation-sites-6,jeromelebleu/foundation-sites,jamesstoneco/foundation-sites,abdullahsalem/foundation-sites,brettsmason/foundation-sites,sethkane/foundation-sites,DaSchTour/foundation-sites,aoimedia/foundation,PassKitInc/foundation-sites,sethkane/foundation-sites,natewiebe13/foundation-sites,socketz/foundation-multilevel-offcanvas,dragthor/foundation-sites,sethkane/foundation-sites,jeromelebleu/foundation-sites,zurb/foundation,colin-marshall/foundation-sites,jaylensoeur/foundation-sites-6
--- +++ @@ -1,29 +1,16 @@ -var _kmq = _kmq || []; $(function() { - // No need to do a timeout for default case, if KM times out just don't show ad. - _kmq.push(function(){ - // Set up the experiment (this is the meat and potatoes) - var type = KM.ab("Foundation Docs Upsell Type", ["question", "directive"]); + // TODO: Add alternate between advanced and intro + var topic = $('h1.docs-page-title').text(); + var header = 'Master ' + topic; + var body = 'Get up to speed FAST, learn straight from the experts who built Foundation.'; + var link = 'http://zurb.com/university/foundation-intro?utm_source=Foundation%20Docs&utm_medium=Docs&utm_content=Struggling&utm_campaign=Docs%20To%20Intro'; + var cta = 'Learn More'; - // TODO: Add alternate between advanced and intro - var topic = $('h1.docs-page-title').text(); - var header; - if (type === 'directive') { - header = 'Master ' + topic; - } else { - header = 'Struggling with ' + topic + '?'; - } - var body = 'Get up to speed FAST, learn straight from the experts who built Foundation.'; - var link = 'http://zurb.com/university/foundation-intro?utm_source=Foundation%20Docs&utm_medium=Docs&utm_content=Struggling&utm_campaign=Docs%20To%20Intro'; - var cta = 'Learn More'; - - var html = '<div class="ad-unit"><h3 class="ad-unit-title">' + header + '</h3>' + - '<p class="ad-unit-text">' + body + '</p>' + - '<a class="button ad-unit-button" href="' + link+ '">' + - cta + '</a></div>'; - $('#TOCAdUnit').html(html); - - }); + var html = '<div class="ad-unit"><h3 class="ad-unit-title">' + header + '</h3>' + + '<p class="ad-unit-text">' + body + '</p>' + + '<a class="button ad-unit-button" href="' + link+ '">' + + cta + '</a></div>'; + $('#TOCAdUnit').html(html); });
8edfdd9a267d30f667348f4806b330bb9b038b5b
app/assets/javascripts/renalware/behaviours.js
app/assets/javascripts/renalware/behaviours.js
$(document).ready(function() { $("[data-behaviour='highlight'] tbody tr a").click(function(){ $(this).closest("tr").addClass("is-selected").siblings().removeClass("is-selected"); }); $("[data-behaviour='submit']").click(function(e) { e.preventDefault(); $(this).closest('form').submit(); }); });
$(document).ready(function() { $("[data-behaviour='highlight'] tbody tr a").click(function(){ $(this).closest("tr").addClass("is-selected").siblings().removeClass("is-selected"); }); $("[data-behaviour='submit']").click(function(e) { e.preventDefault(); $(this).closest('form').submit(); }); $("[data-behaviour='submit_on_change']").on('change', function(e) { e.preventDefault(); $(this).closest('form').submit(); }); });
Add auto submit on change js behaviour
Add auto submit on change js behaviour For submitting forms via ajax when eg dropdown changes
JavaScript
mit
airslie/renalware-core,airslie/renalware-core,airslie/renalware-core,airslie/renalware-core
--- +++ @@ -7,4 +7,9 @@ e.preventDefault(); $(this).closest('form').submit(); }); + + $("[data-behaviour='submit_on_change']").on('change', function(e) { + e.preventDefault(); + $(this).closest('form').submit(); + }); });
4c0fbae213ddc64943b361ab000c63866a4c4863
app/assets/javascripts/utilities/circular_buffer.js
app/assets/javascripts/utilities/circular_buffer.js
class CircularBuffer { constructor(length){ this.buffer = new Int32Array(length); this.maxSize = length; this.currentSize = 0; this.openIndex = 0; this.lastFilledIndex = -1; } get(index){ return this.buffer[(this.lastFilledIndex+index)%this.maxSize]; } size(){ return this.currentSize; } add(el){ if (this.currentSize< this.maxSize) this.currentSize++; this.buffer[this.openIndex] = el; this.lastFilledIndex = (this.lastFilledIndex+1)%this.maxSize; this.openIndex = (this.lastFilledIndex + 1)%this.maxSize; } } module.exports = CircularBuffer;
class CircularBuffer { constructor(length){ this.buffer = new Int32Array(length); this.maxSize = length; this.currentSize = 0; this.openIndex = 0; this.lastFilledIndex = -1; } get(index){ return this.buffer[(this.lastFilledIndex+index)%this.maxSize]; } size(){ return this.currentSize; } add(el){ if (this.currentSize< this.maxSize) this.currentSize++; this.buffer[this.openIndex] = el; this.lastFilledIndex = (this.lastFilledIndex+1)%this.maxSize; this.openIndex = (this.lastFilledIndex + 1)%this.maxSize; } forEach(callback){ for (let i = 0; i < this.currentSize; i++) { callback(this.get(i)); } } } module.exports = CircularBuffer;
Add custom forEach function to Circular Buffer class
Add custom forEach function to Circular Buffer class
JavaScript
mit
krauzer/canvas-sandbox,krauzer/canvas-sandbox
--- +++ @@ -23,6 +23,12 @@ this.openIndex = (this.lastFilledIndex + 1)%this.maxSize; } + forEach(callback){ + for (let i = 0; i < this.currentSize; i++) { + callback(this.get(i)); + } + } + }
616e06a8e1adacc5738f3ce67c234af20e87e4c0
lib/connection-status.js
lib/connection-status.js
'use strict'; const has = require('has'); function collectPoolStatus(stats, { type, host, pool }) { const poolStats = [ ['_allConnections', 'open'], ['_freeConnections', 'sleeping'], ['_acquiringConnections', 'waiting'] ] .filter(([mysqljsProp]) => has(pool, mysqljsProp) && Array.isArray(pool[mysqljsProp])) .reduce( (stats, [mysqljsProp, floraProp]) => ({ ...stats, [floraProp]: pool[mysqljsProp].length }), {} ); poolStats.open -= poolStats.sleeping; return { ...stats, [type]: { [host]: poolStats } }; } // a cluster contains master/slave pools function collectClusterStatus(stats, [database, poolCluster]) { return { ...stats, [database]: Object.entries(poolCluster._nodes) .map(([identifier, { pool }]) => { const [type, host] = identifier.split('_'); return { type: type.toLowerCase(), host, pool }; }) .reduce(collectPoolStatus, {}) }; } module.exports = (pools) => Object.entries(pools).reduce( (stats, [server, databases]) => ({ ...stats, [server]: Object.entries(databases) .filter(([, poolCluster]) => has(poolCluster, '_nodes') && typeof poolCluster._nodes === 'object') .reduce(collectClusterStatus, {}) }), {} );
'use strict'; const has = require('has'); function collectPoolStatus(stats, { type, host, pool }) { const poolStats = [ ['_allConnections', 'open'], ['_freeConnections', 'sleeping'], ['_acquiringConnections', 'waiting'] ] .filter(([mysqljsProp]) => has(pool, mysqljsProp) && Array.isArray(pool[mysqljsProp])) .reduce( (stats, [mysqljsProp, floraProp]) => ({ ...stats, [floraProp]: pool[mysqljsProp].length }), {} ); poolStats.open -= poolStats.sleeping; return { ...stats, [type]: { [host]: poolStats } }; } // a cluster contains master/slave pools function collectClusterStatus(stats, [database, poolCluster]) { return { ...stats, [database]: Object.entries(poolCluster._nodes) .map(([identifier, { pool }]) => { const [type, host] = identifier.split('_'); return { type: `${type.toLowerCase()}s`, host, pool }; }) .reduce(collectPoolStatus, {}) }; } module.exports = (pools) => Object.entries(pools).reduce( (stats, [server, databases]) => ({ ...stats, [server]: Object.entries(databases) .filter(([, poolCluster]) => has(poolCluster, '_nodes') && typeof poolCluster._nodes === 'object') .reduce(collectClusterStatus, {}) }), {} );
Rename master -> masters and slave -> slaves in server status
Rename master -> masters and slave -> slaves in server status
JavaScript
mit
godmodelabs/flora-mysql,godmodelabs/flora-mysql
--- +++ @@ -29,7 +29,7 @@ [database]: Object.entries(poolCluster._nodes) .map(([identifier, { pool }]) => { const [type, host] = identifier.split('_'); - return { type: type.toLowerCase(), host, pool }; + return { type: `${type.toLowerCase()}s`, host, pool }; }) .reduce(collectPoolStatus, {}) };
e9dc82402fac6e17478f00fff1259b0b3bfe5197
web/config.js
web/config.js
var config = { // For internal server or proxying webserver. url : { configuration : 'up/configuration', update : 'up/world/{world}/{timestamp}', sendmessage : 'up/sendmessage' }, // For proxying webserver through php. // url: { // configuration: 'up.php?path=configuration', // update: 'up.php?path=world/{world}/{timestamp}', // sendmessage: 'up.php?path=sendmessage' // }, // For proxying webserver through aspx. // url: { // configuration: 'up.aspx?path=configuration', // update: 'up.aspx?path=world/{world}/{timestamp}', // sendmessage: 'up.aspx?path=sendmessage' // }, // For standalone (jsonfile) webserver. // url: { // configuration: 'standalone/dynmap_config.json', // update: 'standalone/dynmap_{world}.json', // sendmessage: 'standalone/sendmessage.php' // }, tileUrl : 'tiles/', tileWidth : 128, tileHeight : 128 };
var config = { // For internal server or proxying webserver. url : { configuration : 'up/configuration', update : 'up/world/{world}/{timestamp}', sendmessage : 'up/sendmessage' }, // For proxying webserver through php. // url: { // configuration: 'up.php?path=configuration', // update: 'up.php?path=world/{world}/{timestamp}', // sendmessage: 'up.php?path=sendmessage' // }, // For proxying webserver through aspx. // url: { // configuration: 'up.aspx?path=configuration', // update: 'up.aspx?path=world/{world}/{timestamp}', // sendmessage: 'up.aspx?path=sendmessage' // }, // For standalone (jsonfile) webserver. // url: { // configuration: 'standalone/dynmap_config.json', // update: 'standalone/dynmap_{world}.json?_={timestamp}', // sendmessage: 'standalone/sendmessage.php' // }, tileUrl : 'tiles/', tileWidth : 128, tileHeight : 128 };
Fix caching issue in standalone
Fix caching issue in standalone
JavaScript
apache-2.0
webbukkit/dynmap,webbukkit/dynmap,mg-1999/dynmap,KovuTheHusky/dynmap,webbukkit/dynmap,webbukkit/dynmap
--- +++ @@ -23,7 +23,7 @@ // For standalone (jsonfile) webserver. // url: { // configuration: 'standalone/dynmap_config.json', - // update: 'standalone/dynmap_{world}.json', + // update: 'standalone/dynmap_{world}.json?_={timestamp}', // sendmessage: 'standalone/sendmessage.php' // },
e9483a99ec4ff2b46df813cb3425cc2ef11d07ef
web/g-live.js
web/g-live.js
/** * Keep live updates from service. * @constructor */ g.live = function() { var socket; /** * Open the websocket connection. */ var open = function() { if (g.isEncrypted()) { socket = new WebSocket('wss://' + g.getHost() + '/api/live'); } else { socket = new WebSocket('ws://' + g.getHost() + '/api/live'); } socket.onclose = onclose; socket.onmessage = onmessage; }; /** * onmessage callback. * @param {!MessageEvent} event */ var onmessage = function(event) { var data = JSON.parse(event.data); if (subscriptions.hasOwnProperty(data.type)) { subscriptions[data.type].log(data); } }; /** * Use as onclose callback from websocket, will try to reconnect after * two and a half second. * @param {!CloseEvent} event */ var onclose = function(event) { setTimeout(function() { open(); }, 2500); }; // Open the connection right away. open(); /** * @type {Object.<string, g.Collection>} */ var subscriptions = {}; /** * Subscribe a collection. * @param {!string} id The type id to subscribe to. * @param {!g.Collection} collection The collection to update. */ this.subscribe = function(id, collection) { subscriptions[id] = collection; }; return this; };
/** * Keep live updates from service. * @constructor */ g.live = function() { var socket; /** * Open the websocket connection. */ var open = function() { if (g.isEncrypted()) { socket = new WebSocket('wss://' + g.getHost() + '/api/live'); } else { socket = new WebSocket('ws://' + g.getHost() + '/api/live'); } socket.onclose = onclose; socket.onmessage = onmessage; }; /** * onmessage callback. * @param {!MessageEvent} event */ var onmessage = function(event) { var data = JSON.parse(event.data); if (subscriptions.hasOwnProperty(data.type)) { subscriptions[data.type].forEach(function(collection) { console.log(data, "to", collection); collection.log(data); }); } }; /** * Use as onclose callback from websocket, will try to reconnect after * two and a half second. * @param {!CloseEvent} event */ var onclose = function(event) { setTimeout(function() { open(); }, 2500); }; // Open the connection right away. open(); /** * @type {Object.<string, g.Collection>} */ var subscriptions = {}; /** * Subscribe a collection. * @param {!string} id The type id to subscribe to. * @param {!g.Collection} collection The collection to update. */ this.subscribe = function(id, collection) { if (subscriptions.hasOwnProperty(id)) { subscriptions[id].push(collection); } else { subscriptions[id] = [collection]; } }; return this; };
Support multiple subscribers in g.Live.
Support multiple subscribers in g.Live.
JavaScript
mit
gansoi/gansoi,gansoi/gansoi,gansoi/gansoi,gansoi/gansoi
--- +++ @@ -27,7 +27,10 @@ var data = JSON.parse(event.data); if (subscriptions.hasOwnProperty(data.type)) { - subscriptions[data.type].log(data); + subscriptions[data.type].forEach(function(collection) { + console.log(data, "to", collection); + collection.log(data); + }); } }; @@ -56,7 +59,11 @@ * @param {!g.Collection} collection The collection to update. */ this.subscribe = function(id, collection) { - subscriptions[id] = collection; + if (subscriptions.hasOwnProperty(id)) { + subscriptions[id].push(collection); + } else { + subscriptions[id] = [collection]; + } }; return this;
a24950265ff87515da7bc6a0b306f8569707cabc
lib/experiments/index.js
lib/experiments/index.js
'use strict'; let experiments = { BUILD_INSTRUMENTATION: symbol('build-instrumentation'), INSTRUMENTATION: symbol('instrumentation'), ADDON_TREE_CACHING: symbol('addon-tree-caching'), }; Object.freeze(experiments); module.exports = experiments;
'use strict'; const symbol = require('../utilities/symbol'); let experiments = { BUILD_INSTRUMENTATION: symbol('build-instrumentation'), INSTRUMENTATION: symbol('instrumentation'), ADDON_TREE_CACHING: symbol('addon-tree-caching'), }; Object.freeze(experiments); module.exports = experiments;
Revert "Fix linting issue with beta branch."
Revert "Fix linting issue with beta branch." This reverts commit 8122805c34524ac9ac98bfd5cb17380d9765cbb4.
JavaScript
mit
gfvcastro/ember-cli,rtablada/ember-cli,calderas/ember-cli,elwayman02/ember-cli,thoov/ember-cli,asakusuma/ember-cli,HeroicEric/ember-cli,ef4/ember-cli,kanongil/ember-cli,twokul/ember-cli,kategengler/ember-cli,kanongil/ember-cli,Turbo87/ember-cli,twokul/ember-cli,buschtoens/ember-cli,akatov/ember-cli,mike-north/ember-cli,trentmwillis/ember-cli,seawatts/ember-cli,rtablada/ember-cli,akatov/ember-cli,mike-north/ember-cli,fpauser/ember-cli,patocallaghan/ember-cli,kellyselden/ember-cli,mike-north/ember-cli,fpauser/ember-cli,HeroicEric/ember-cli,asakusuma/ember-cli,balinterdi/ember-cli,gfvcastro/ember-cli,raycohen/ember-cli,seawatts/ember-cli,fpauser/ember-cli,balinterdi/ember-cli,jgwhite/ember-cli,cibernox/ember-cli,calderas/ember-cli,Turbo87/ember-cli,cibernox/ember-cli,seawatts/ember-cli,kellyselden/ember-cli,trentmwillis/ember-cli,fpauser/ember-cli,twokul/ember-cli,jgwhite/ember-cli,mike-north/ember-cli,romulomachado/ember-cli,patocallaghan/ember-cli,thoov/ember-cli,calderas/ember-cli,pzuraq/ember-cli,cibernox/ember-cli,buschtoens/ember-cli,jrjohnson/ember-cli,kellyselden/ember-cli,akatov/ember-cli,romulomachado/ember-cli,patocallaghan/ember-cli,raycohen/ember-cli,Turbo87/ember-cli,akatov/ember-cli,sivakumar-kailasam/ember-cli,jgwhite/ember-cli,patocallaghan/ember-cli,cibernox/ember-cli,HeroicEric/ember-cli,romulomachado/ember-cli,trentmwillis/ember-cli,jgwhite/ember-cli,pzuraq/ember-cli,ember-cli/ember-cli,kanongil/ember-cli,sivakumar-kailasam/ember-cli,ember-cli/ember-cli,gfvcastro/ember-cli,HeroicEric/ember-cli,ef4/ember-cli,rtablada/ember-cli,elwayman02/ember-cli,pzuraq/ember-cli,thoov/ember-cli,sivakumar-kailasam/ember-cli,romulomachado/ember-cli,thoov/ember-cli,ember-cli/ember-cli,sivakumar-kailasam/ember-cli,ef4/ember-cli,Turbo87/ember-cli,kanongil/ember-cli,kellyselden/ember-cli,calderas/ember-cli,jrjohnson/ember-cli,seawatts/ember-cli,twokul/ember-cli,gfvcastro/ember-cli,ef4/ember-cli,trentmwillis/ember-cli,pzuraq/ember-cli,rtablada/ember-cli,kategengler/ember-cli
--- +++ @@ -1,4 +1,5 @@ 'use strict'; +const symbol = require('../utilities/symbol'); let experiments = { BUILD_INSTRUMENTATION: symbol('build-instrumentation'),
27029f760791efd65c0008a9bdc4e13830d4cc1d
app/models/widgets/ticker_widget.js
app/models/widgets/ticker_widget.js
Dashboard.TickerWidget = Dashboard.Widget.extend({ sourceData: "", templateName: 'ticker_widget', classNames: ['widget', 'widget-ticker'], widgetView: function() { var widget = this; return this._super().reopen({ didInsertElement: function() { var scaleFactor = 0.5; var scaleSource = this.$().height(); var fontSize = scaleSource * scaleFactor; var widgetUnitWidth = (DashboardConfig.grid.width - DashboardConfig.widgetMargins) / DashboardConfig.dim[0] - DashboardConfig.widgetMargins; var widgetWidth = widgetUnitWidth * widget.get('sizex') + DashboardConfig.widgetMargins * (widget.get('sizex') - 1) - 5; this.$().css('font-size', fontSize + 'px'); this.$('.marquee').css('max-width', widgetWidth + 'px'); } }); }.property() });
Dashboard.TickerWidget = Dashboard.Widget.extend({ sourceData: "", templateName: 'ticker_widget', classNames: ['widget', 'widget-ticker'], widgetView: function() { var widget = this; return this._super().reopen({ didInsertElement: function() { var scaleFactor = 0.7; var widgetHeight = this.$().height(); var fontSize = widgetHeight * scaleFactor; var widgetUnitWidth = (DashboardConfig.grid.width - DashboardConfig.widgetMargins) / DashboardConfig.dim[0] - DashboardConfig.widgetMargins; var widgetWidth = widgetUnitWidth * widget.get('sizex') + DashboardConfig.widgetMargins * (widget.get('sizex') - 1) - 5; this.$().css('font-size', fontSize + 'px'); this.$('.marquee').css('max-width', widgetWidth + 'px'); } }); }.property() });
Change ticker font scale factor to 0.7
Change ticker font scale factor to 0.7
JavaScript
mit
ShiftForward/mucuchies,kloudsio/mucuchies,ShiftForward/mucuchies,kloudsio/mucuchies
--- +++ @@ -9,10 +9,10 @@ return this._super().reopen({ didInsertElement: function() { - var scaleFactor = 0.5; - var scaleSource = this.$().height(); + var scaleFactor = 0.7; + var widgetHeight = this.$().height(); - var fontSize = scaleSource * scaleFactor; + var fontSize = widgetHeight * scaleFactor; var widgetUnitWidth = (DashboardConfig.grid.width - DashboardConfig.widgetMargins) / DashboardConfig.dim[0] - DashboardConfig.widgetMargins;
729e714347790520e0543d144704113f64aa167e
app/scripts/controllers/contract.js
app/scripts/controllers/contract.js
'use strict'; angular.module('scratchApp') .controller('ContractCtrl', function ($scope, $http, $location) { var serversPublicKey, wallet, paymentTx, refundTx, signedTx; $scope.generate = function () { getServersPublicKey($scope.walet_publicKey); signTransactionAtServer(); } function getServersPublicKey(clientsPublicKey) { $http.post("http://0.0.0.0:3000/wallet/create", {clientsPublicKey:"026477115981fe981a6918a6297d9803c4dc04f328f22041bedff886bbc2962e01"}).success(function (data, status, headers, config) { console.log("Server responded with key: " + data); serversPublicKey = data; createTransactions($scope.wallet_amount, $scope.wallet_duration); }). error(function (data, status, headers, config) { alert("Server returned an error: " + status + " " + data); $location.path('/'); }); serversPublicKey = "ServersPublicKey"; } function createTransactions(amount, duration) { // generate wallet // create payment transaction // create refund transaction } function signTransactionAtServer() { signedTx = "signed transaction"; } });
'use strict'; angular.module('scratchApp') .controller('ContractCtrl', function ($scope, $http, $location) { var serversPublicKey, wallet, paymentTx, refundTx, signedTx; $scope.generate = function () { getServersPublicKey($scope.walet_publicKey); signTransactionAtServer(); } function getServersPublicKey(clientsPublicKey) { var req = { method: 'POST', url: 'http://0.0.0.0:3000/wallet/create', headers: { 'Content-Type': 'application/json' }, data: { userPublicKey:"026477115981fe981a6918a6297d9803c4dc04f328f22041bedff886bbc2962e01" } }; $http(req).success(function (data, status, headers, config) { console.log("Server responded with key: " + data); serversPublicKey = data; createTransactions($scope.wallet_amount, $scope.wallet_duration); }).error(function (data, status, headers, config) { $location.path('/'); }); serversPublicKey = "ServersPublicKey"; } function createTransactions(amount, duration) { // generate wallet // create payment transaction // create refund transaction } function signTransactionAtServer() { signedTx = "signed transaction"; } });
Modify request to add necessary header
Modify request to add necessary header
JavaScript
mit
baleato/bitcoin-hackathon
--- +++ @@ -15,13 +15,23 @@ } function getServersPublicKey(clientsPublicKey) { - $http.post("http://0.0.0.0:3000/wallet/create", {clientsPublicKey:"026477115981fe981a6918a6297d9803c4dc04f328f22041bedff886bbc2962e01"}).success(function (data, status, headers, config) { + var req = { + method: 'POST', + url: 'http://0.0.0.0:3000/wallet/create', + headers: { + 'Content-Type': 'application/json' + }, + data: { + userPublicKey:"026477115981fe981a6918a6297d9803c4dc04f328f22041bedff886bbc2962e01" + } + }; + + $http(req).success(function (data, status, headers, config) { + console.log("Server responded with key: " + data); serversPublicKey = data; createTransactions($scope.wallet_amount, $scope.wallet_duration); - }). - error(function (data, status, headers, config) { - alert("Server returned an error: " + status + " " + data); + }).error(function (data, status, headers, config) { $location.path('/'); }); serversPublicKey = "ServersPublicKey";
412466f9d11f229d5a118028292c69c2b1b3814f
commands/say.js
commands/say.js
var l10n_file = __dirname + '/../l10n/commands/say.yml'; var l10n = require('../src/l10n')(l10n_file); var CommandUtil = require('../src/command_util').CommandUtil; exports.command = function(rooms, items, players, npcs, Commands) { return function(args, player) { if (args) { player.sayL10n(l10n, 'YOU_SAY', args); players.eachIf(function(p) { otherPlayersInRoom(p); }, function(p) { p.sayL10n(l10n, 'THEY_SAY', player.getName(), args); }); return; } player.sayL10n(l10n, 'NOTHING_SAID'); return; } function otherPlayersInRoom(p) { if (p) return (p.getName() !== player.getName() && p.getLocation() === player.getLocation()); }; };
var l10n_file = __dirname + '/../l10n/commands/say.yml'; var l10n = require('../src/l10n')(l10n_file); var CommandUtil = require('../src/command_util').CommandUtil; exports.command = function(rooms, items, players, npcs, Commands) { return function(args, player) { if (args) { player.sayL10n(l10n, 'YOU_SAY', args); players.eachIf(function(p) { return otherPlayersInRoom(p); }, function(p) { if (p.getName() != player.getName()) p.sayL10n(l10n, 'THEY_SAY', player.getName(), args); }); return; } player.sayL10n(l10n, 'NOTHING_SAID'); return; } function otherPlayersInRoom(p) { if (p) return (p.getName() !== player.getName() && p.getLocation() === player.getLocation()); }; };
Add conditional to avoid duplicate messages, fix EachIf block.
Add conditional to avoid duplicate messages, fix EachIf block.
JavaScript
mit
seanohue/ranviermud,seanohue/ranviermud,shawncplus/ranviermud
--- +++ @@ -6,9 +6,10 @@ if (args) { player.sayL10n(l10n, 'YOU_SAY', args); players.eachIf(function(p) { - otherPlayersInRoom(p); + return otherPlayersInRoom(p); }, function(p) { - p.sayL10n(l10n, 'THEY_SAY', player.getName(), args); + if (p.getName() != player.getName()) + p.sayL10n(l10n, 'THEY_SAY', player.getName(), args); }); return; }
0ddb22881705535445aec6258da604278cac75e1
src/modules/ngSharepoint/services/spProvider.js
src/modules/ngSharepoint/services/spProvider.js
angular .module('ngSharepoint') .provider('$sp', function() { var siteUrl = ''; var connMode = 'JSOM'; //possible values: JSOM, REST var token = ''; var autoload = true; return { setSiteUrl: function (newUrl) { siteUrl = newUrl; }, setConnectionMode: function(connMode) { //Only JSOM Supported for now if (connMode === 'JSOM' || connMode === 'REST') { this.connMode = connMode; } }, setAccessToken: function(token) { this.token = token; }, setAutoload: function(autoload) { this.autoload = autoload; }, $get: function() { return ({ getSiteUrl: function() { return siteUrl; }, getConnectionMode: function() { return connMode; }, getAccessToken: function(token) { return token; }, getContext: function() { return new SP.ClientContext(siteUrl); }, getAutoload: function() { return autoload; } }); } }; });
angular .module('ngSharepoint') .provider('$sp', function() { var siteUrl = ''; var connMode = 'JSOM'; //possible values: JSOM, REST var token = false; var autoload = true; return { setSiteUrl: function (newUrl) { siteUrl = newUrl; }, setConnectionMode: function(connMode) { //Only JSOM Supported for now if (connMode === 'JSOM' || connMode === 'REST') { this.connMode = connMode; } }, setAccessToken: function(token) { this.token = token; }, setAutoload: function(autoload) { this.autoload = autoload; }, $get: function() { return ({ getSiteUrl: function() { return siteUrl; }, getConnectionMode: function() { return connMode; }, getAccessToken: function(token) { return token; }, getContext: function() { return new SP.ClientContext(siteUrl); }, getAutoload: function() { return autoload; } }); } }; });
Set token to false by default
Set token to false by default
JavaScript
apache-2.0
maxjoehnk/ngSharepoint
--- +++ @@ -3,7 +3,7 @@ .provider('$sp', function() { var siteUrl = ''; var connMode = 'JSOM'; //possible values: JSOM, REST - var token = ''; + var token = false; var autoload = true; return {
cfd13a2df960ac6421d27651688b6dbd5f5f1030
server/config/environment/index.js
server/config/environment/index.js
var _ = require('lodash'); var all = { // define nodejs runtime environment server: { port : process.env.NODE_IP || 8080, //OPENSHIFT_NODEJS_PORT host : process.env.NODE_PORT || '127.0.0.1', //OPENSHIFT_NODEJS_IP staticDir : '/../../dist' }, //secret encryption key secretKey: process.env.PP_SECRET_KEY, //Facebook oauth implementation facebook: { clientID: process.env.FB_CLIENT_ID, clientSecret: process.env.FB_CLIENT_SEC, callbackURL: (process.env.DOMAIN || '') + '/api/v1/users/facebook/callback' }, // MongoDB connection options mongo: { options: { db: { safe: true } } }, // Should we populate the DB with sample data? seedDB: false }; // Export the config object based on the NODE_ENV // ============================================== module.exports = _.merge( all, require('./' + process.env.NODE_ENV + '.js') || {});
var _ = require('lodash'); var all = { // define nodejs runtime environment server: { port : process.env.OPENSHIFT_NODEJS_PORT || 8080, //OPENSHIFT_NODEJS_PORT //NODE_IP host : process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1', //OPENSHIFT_NODEJS_IP //NODE_PORT staticDir : '/../../dist' }, //secret encryption key secretKey: process.env.PP_SECRET_KEY, //Facebook oauth implementation facebook: { clientID: process.env.FB_CLIENT_ID, clientSecret: process.env.FB_CLIENT_SEC, callbackURL: (process.env.DOMAIN || '') + '/api/v1/users/facebook/callback' }, // MongoDB connection options mongo: { options: { db: { safe: true } } }, // Should we populate the DB with sample data? seedDB: false }; // Export the config object based on the NODE_ENV // ============================================== module.exports = _.merge( all, require('./' + process.env.NODE_ENV + '.js') || {});
Change port and host var
Change port and host var
JavaScript
mit
markoch/dev-news-os,markoch/dev-news-os
--- +++ @@ -3,8 +3,8 @@ var all = { // define nodejs runtime environment server: { - port : process.env.NODE_IP || 8080, //OPENSHIFT_NODEJS_PORT - host : process.env.NODE_PORT || '127.0.0.1', //OPENSHIFT_NODEJS_IP + port : process.env.OPENSHIFT_NODEJS_PORT || 8080, //OPENSHIFT_NODEJS_PORT //NODE_IP + host : process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1', //OPENSHIFT_NODEJS_IP //NODE_PORT staticDir : '/../../dist' },
4adeb41a333ad6218fc8450b765c2afa33b20238
babel.server.js
babel.server.js
require("babel-polyfill"); /** * Configure babel using the require hook * More details here: https://babeljs.io/docs/setup/#babel_register */ require("babel-core/register")({ only: /src/, presets: ["es2015", "react", "stage-0"] }); require('dotenv').load(); /** * Define isomorphic constants. */ global.__CLIENT__ = false; global.__SERVER__ = true; if (process.env.NODE_ENV !== "production") { if (!require("piping")({hook: true, includeModules: false})) { return; } } try { require("./src/server/server"); } catch (error) { console.error(error.stack); }
require("babel-polyfill"); /** * Configure babel using the require hook * More details here: https://babeljs.io/docs/setup/#babel_register */ require("babel-core/register")({ only: /src/, presets: ["es2015", "react", "stage-0"] }); require('dotenv').load({path: process.env.NODE_ENV === "production" ? `.env.${process.env.NODE_ENV}` : '.env'}); /** * Define isomorphic constants. */ global.__CLIENT__ = false; global.__SERVER__ = true; if (process.env.NODE_ENV !== "production") { if (!require("piping")({hook: true, includeModules: false})) { return; } } try { require("./src/server/server"); } catch (error) { console.error(error.stack); }
Load production vars from .env.production
Load production vars from .env.production
JavaScript
mit
alexchiri/minimalistic-blog,alexchiri/minimalistic-blog,alexchiri/minimalistic-blog
--- +++ @@ -9,7 +9,7 @@ presets: ["es2015", "react", "stage-0"] }); -require('dotenv').load(); +require('dotenv').load({path: process.env.NODE_ENV === "production" ? `.env.${process.env.NODE_ENV}` : '.env'}); /** * Define isomorphic constants. */
491dce4e0a8e839ef375017ff77669fb06e482f4
samples/electron/start.js
samples/electron/start.js
var app = require('app'); var BrowserWindow = require('browser-window'); var mainWindow = null; app.on('window-all-closed', function() { if (process.platform != 'darwin') app.quit(); }); app.on('ready', function() { mainWindow = new BrowserWindow({width: 800, height: 600}); mainWindow.loadUrl('file://' + __dirname + '/index.html'); mainWindow.on('closed', function() { mainWindow = null; }); });
const electron = require('electron') // Module to control application life. const app = electron.app // Module to create native browser window. const BrowserWindow = electron.BrowserWindow; var mainWindow = null; app.on('window-all-closed', function() { if (process.platform != 'darwin') app.quit(); }); app.on('ready', function() { mainWindow = new BrowserWindow({width: 800, height: 600}); mainWindow.loadURL('file://' + __dirname + '/index.html'); mainWindow.on('closed', function() { mainWindow = null; }); });
Upgrade to Electron 1.0 API
Upgrade to Electron 1.0 API
JavaScript
mit
greenheartgames/greenworks,greenheartgames/greenworks,greenheartgames/greenworks,greenheartgames/greenworks,greenheartgames/greenworks
--- +++ @@ -1,5 +1,8 @@ -var app = require('app'); -var BrowserWindow = require('browser-window'); +const electron = require('electron') +// Module to control application life. +const app = electron.app +// Module to create native browser window. +const BrowserWindow = electron.BrowserWindow; var mainWindow = null; @@ -10,7 +13,7 @@ app.on('ready', function() { mainWindow = new BrowserWindow({width: 800, height: 600}); - mainWindow.loadUrl('file://' + __dirname + '/index.html'); + mainWindow.loadURL('file://' + __dirname + '/index.html'); mainWindow.on('closed', function() { mainWindow = null; });
e35d2be4041b62ede59bbfd3ff9ea4016fc3582e
src/client/app/components/header/header.template.js
src/client/app/components/header/header.template.js
import { HeaderService } from "./header.service.js"; export class HeaderTemplate { static update(render) { const start = Date.now(); /* eslint-disable indent */ render` <nav class="flex flex-row bt bb tc mw9 center shadow-2"> <div class="flex flex-wrap flex-row justify-around items-center min-w-70 logo"> <span class="b"> <a href="https://github.com/albertosantini/node-conpa">ConPA 5</a> Asset Allocation App </span> </div> <div class="flex flex-wrap flex-row items-center min-w-30> <span class="f7"> <toasts></toasts> <div>${{ any: HeaderService.getStatus().then(({ namespace: status }) => { const end = Date.now(); return `${status.message} (${end - start}ms)`; }), placeholder: "Loading..." }}</div> </span> </div> </nav> `; /* eslint-enable indent */ } }
import { HeaderService } from "./header.service.js"; export class HeaderTemplate { static update(render) { const start = Date.now(); /* eslint-disable indent */ render` <nav class="flex flex-row bt bb mw9 center shadow-2"> <div class="flex flex-wrap flex-row justify-around items-center min-w-70 logo"> <span class="b"> <a href="https://github.com/albertosantini/node-conpa">ConPA 5</a> Asset Allocation App </span> </div> <div class="flex flex-wrap flex-row items-center min-w-30> <span class="f7"> <toasts></toasts> <div>${{ any: HeaderService.getStatus().then(({ namespace: status }) => { const end = Date.now(); return `${status.message} (${end - start}ms)`; }), placeholder: "Loading..." }}</div> </span> </div> </nav> `; /* eslint-enable indent */ } }
Remove text align center from status and toasts in the header.
Remove text align center from status and toasts in the header.
JavaScript
mit
albertosantini/node-conpa,albertosantini/node-conpa
--- +++ @@ -6,7 +6,7 @@ /* eslint-disable indent */ render` - <nav class="flex flex-row bt bb tc mw9 center shadow-2"> + <nav class="flex flex-row bt bb mw9 center shadow-2"> <div class="flex flex-wrap flex-row justify-around items-center min-w-70 logo"> <span class="b">
9bdf5459f7001353f779980ffabc24c470179cdc
example/webpack.config.js
example/webpack.config.js
var path = require('path'); var loader = path.join(__dirname, '..', '..', 'index.js'); var __DEV__ = process.env.NODE_ENV !== 'production'; module.exports = { entry: path.join(__dirname, 'index.js'), output: { path: path.join(__dirname, 'public'), filename: 'bundle.js', publicPath: __DEV__ ? '/public/' : 'https://cdn.example.com/assets/' }, module: { loaders: [ { test: /\.png$/, loader: loader } ] } };
var path = require('path'); var loader = path.join(__dirname, '..', 'index.js'); var __DEV__ = process.env.NODE_ENV !== 'production'; module.exports = { entry: path.join(__dirname, 'index.js'), output: { path: path.join(__dirname, 'public'), filename: 'bundle.js', publicPath: __DEV__ ? '/public/' : 'https://cdn.example.com/assets/' }, module: { loaders: [ { test: /\.png$/, loader: loader } ] } };
Fix example path which occured as a consequence of rename
Fix example path which occured as a consequence of rename
JavaScript
apache-2.0
boopathi/image-size-loader
--- +++ @@ -1,5 +1,5 @@ var path = require('path'); -var loader = path.join(__dirname, '..', '..', 'index.js'); +var loader = path.join(__dirname, '..', 'index.js'); var __DEV__ = process.env.NODE_ENV !== 'production'; module.exports = {
0f1db78ce5ed9370482331b8668aa7057384935c
packages/ember-utils/tests/assign_test.js
packages/ember-utils/tests/assign_test.js
import { assignPolyfill as assign } from '..'; QUnit.module('Ember.assign'); QUnit.test('Ember.assign', function() { let a = { a: 1 }; let b = { b: 2 }; let c = { c: 3 }; let a2 = { a: 4 }; assign(a, b, c, a2); deepEqual(a, { a: 4, b: 2, c: 3 }); deepEqual(b, { b: 2 }); deepEqual(c, { c: 3 }); deepEqual(a2, { a: 4 }); });
import { assignPolyfill as assign } from '..'; QUnit.module('Ember.assign'); QUnit.test('merging objects', function() { let trgt = { a: 1 }; let src1 = { b: 2 }; let src2 = { c: 3 }; assign(trgt, src1, src2); deepEqual(trgt, { a: 1, b: 2, c: 3 }, 'assign copies values from one or more source objects to a target object'); deepEqual(src1, { b: 2 }, 'assign does not change source object 1'); deepEqual(src2, { c: 3 }, 'assign does not change source object 2'); }); QUnit.test('merging objects with same property', function() { let trgt = { a: 1, b: 1 }; let src1 = { a: 2, b: 2 }; let src2 = { a: 3 }; assign(trgt, src1, src2); deepEqual(trgt, { a: 3, b: 2 }, 'properties are overwritten by other objects that have the same properties later in the parameters order'); }); QUnit.test('null', function() { let trgt = { a: 1 }; assign(trgt, null); deepEqual(trgt, { a: 1 }, 'null as a source parameter is ignored'); }); QUnit.test('undefined', function() { let trgt = { a: 1 }; assign(trgt, null); deepEqual(trgt, { a: 1 }, 'undefined as a source parameter is ignored'); });
Add test coverage to Object.assign polyfill
Add test coverage to Object.assign polyfill
JavaScript
mit
amk221/ember.js,qaiken/ember.js,nickiaconis/ember.js,patricksrobertson/ember.js,tildeio/ember.js,thoov/ember.js,amk221/ember.js,bantic/ember.js,nickiaconis/ember.js,jherdman/ember.js,mixonic/ember.js,xiujunma/ember.js,jasonmit/ember.js,thoov/ember.js,mfeckie/ember.js,csantero/ember.js,jherdman/ember.js,sandstrom/ember.js,gfvcastro/ember.js,kennethdavidbuck/ember.js,givanse/ember.js,Serabe/ember.js,intercom/ember.js,amk221/ember.js,intercom/ember.js,kanongil/ember.js,trentmwillis/ember.js,mike-north/ember.js,jasonmit/ember.js,cibernox/ember.js,kennethdavidbuck/ember.js,Gaurav0/ember.js,alexdiliberto/ember.js,sivakumar-kailasam/ember.js,mike-north/ember.js,qaiken/ember.js,kennethdavidbuck/ember.js,stefanpenner/ember.js,cbou/ember.js,kanongil/ember.js,miguelcobain/ember.js,fpauser/ember.js,sly7-7/ember.js,asakusuma/ember.js,runspired/ember.js,sivakumar-kailasam/ember.js,emberjs/ember.js,sandstrom/ember.js,runspired/ember.js,sandstrom/ember.js,cbou/ember.js,cbou/ember.js,jaswilli/ember.js,bekzod/ember.js,bantic/ember.js,bekzod/ember.js,stefanpenner/ember.js,runspired/ember.js,stefanpenner/ember.js,asakusuma/ember.js,runspired/ember.js,karthiick/ember.js,kellyselden/ember.js,xiujunma/ember.js,mixonic/ember.js,qaiken/ember.js,asakusuma/ember.js,emberjs/ember.js,bantic/ember.js,intercom/ember.js,GavinJoyce/ember.js,trentmwillis/ember.js,mixonic/ember.js,gfvcastro/ember.js,knownasilya/ember.js,karthiick/ember.js,davidpett/ember.js,twokul/ember.js,csantero/ember.js,Serabe/ember.js,sivakumar-kailasam/ember.js,Patsy-issa/ember.js,Turbo87/ember.js,jasonmit/ember.js,davidpett/ember.js,sly7-7/ember.js,gfvcastro/ember.js,patricksrobertson/ember.js,twokul/ember.js,jaswilli/ember.js,cibernox/ember.js,xiujunma/ember.js,csantero/ember.js,twokul/ember.js,qaiken/ember.js,jaswilli/ember.js,cibernox/ember.js,patricksrobertson/ember.js,givanse/ember.js,tildeio/ember.js,Patsy-issa/ember.js,kellyselden/ember.js,patricksrobertson/ember.js,knownasilya/ember.js,gfvcastro/ember.js,csantero/ember.js,Turbo87/ember.js,nickiaconis/ember.js,trentmwillis/ember.js,jasonmit/ember.js,Patsy-issa/ember.js,karthiick/ember.js,mfeckie/ember.js,alexdiliberto/ember.js,nickiaconis/ember.js,GavinJoyce/ember.js,elwayman02/ember.js,mike-north/ember.js,knownasilya/ember.js,bekzod/ember.js,Serabe/ember.js,kanongil/ember.js,davidpett/ember.js,fpauser/ember.js,GavinJoyce/ember.js,jasonmit/ember.js,Gaurav0/ember.js,givanse/ember.js,kennethdavidbuck/ember.js,elwayman02/ember.js,bantic/ember.js,jherdman/ember.js,Gaurav0/ember.js,twokul/ember.js,miguelcobain/ember.js,cbou/ember.js,GavinJoyce/ember.js,intercom/ember.js,mfeckie/ember.js,alexdiliberto/ember.js,elwayman02/ember.js,Patsy-issa/ember.js,cibernox/ember.js,thoov/ember.js,fpauser/ember.js,kellyselden/ember.js,givanse/ember.js,xiujunma/ember.js,jaswilli/ember.js,kanongil/ember.js,sivakumar-kailasam/ember.js,emberjs/ember.js,Gaurav0/ember.js,jherdman/ember.js,tildeio/ember.js,thoov/ember.js,sivakumar-kailasam/ember.js,Turbo87/ember.js,miguelcobain/ember.js,davidpett/ember.js,Serabe/ember.js,kellyselden/ember.js,miguelcobain/ember.js,mfeckie/ember.js,asakusuma/ember.js,mike-north/ember.js,karthiick/ember.js,amk221/ember.js,Turbo87/ember.js,alexdiliberto/ember.js,fpauser/ember.js,elwayman02/ember.js,bekzod/ember.js,sly7-7/ember.js,trentmwillis/ember.js
--- +++ @@ -2,16 +2,37 @@ QUnit.module('Ember.assign'); -QUnit.test('Ember.assign', function() { - let a = { a: 1 }; - let b = { b: 2 }; - let c = { c: 3 }; - let a2 = { a: 4 }; +QUnit.test('merging objects', function() { + let trgt = { a: 1 }; + let src1 = { b: 2 }; + let src2 = { c: 3 }; - assign(a, b, c, a2); + assign(trgt, src1, src2); - deepEqual(a, { a: 4, b: 2, c: 3 }); - deepEqual(b, { b: 2 }); - deepEqual(c, { c: 3 }); - deepEqual(a2, { a: 4 }); + deepEqual(trgt, { a: 1, b: 2, c: 3 }, 'assign copies values from one or more source objects to a target object'); + deepEqual(src1, { b: 2 }, 'assign does not change source object 1'); + deepEqual(src2, { c: 3 }, 'assign does not change source object 2'); }); + +QUnit.test('merging objects with same property', function() { + let trgt = { a: 1, b: 1 }; + let src1 = { a: 2, b: 2 }; + let src2 = { a: 3 }; + + assign(trgt, src1, src2); + deepEqual(trgt, { a: 3, b: 2 }, 'properties are overwritten by other objects that have the same properties later in the parameters order'); +}); + +QUnit.test('null', function() { + let trgt = { a: 1 }; + + assign(trgt, null); + deepEqual(trgt, { a: 1 }, 'null as a source parameter is ignored'); +}); + +QUnit.test('undefined', function() { + let trgt = { a: 1 }; + + assign(trgt, null); + deepEqual(trgt, { a: 1 }, 'undefined as a source parameter is ignored'); +});
1c2e692e5770bdf66f6801f90a6f7cbcaf048969
client/assets/js/services/LandingPageService.js
client/assets/js/services/LandingPageService.js
(function () { 'use strict'; angular .module('fusionSeedApp.services.landingPage', []) .factory('LandingPageService', LandingPageService); function LandingPageService($log, Orwell, $window, ConfigService) { 'ngInject'; activate(); var service = { getLandingPagesFromData: getLandingPagesFromData }; return service; ////////////// /** * This activate() is to redirect the window the first landing-page * in case redirect flag in appConfig * is `true`. */ function activate() { var resultsObservable = Orwell.getObservable('queryResults'); resultsObservable.addObserver(function (data) { var landing_pages = service.getLandingPagesFromData(data); $log.debug('landing_pages', landing_pages); if (angular.isArray(landing_pages) && ConfigService.getLandingPageRedirect()) { $window.location.assign(landing_pages[0]); } }); } /** * Extracts landing pages from Fusion response data. */ function getLandingPagesFromData(data) { return _.get(data, 'fusion.landing-pages'); } } })();
(function () { 'use strict'; angular .module('fusionSeedApp.services.landingPage', []) .factory('LandingPageService', LandingPageService); function LandingPageService($log, Orwell, $window, ConfigService) { 'ngInject'; activate(); var service = { getLandingPagesFromData: getLandingPagesFromData }; return service; ////////////// /** * This activate() is to redirect the window the first landing-page * in case redirect flag in appConfig * is `true`. */ function activate() { var resultsObservable = Orwell.getObservable('queryResults'); resultsObservable.addObserver(function (data) { var landing_pages = service.getLandingPagesFromData(data); if (angular.isArray(landing_pages) && ConfigService.getLandingPageRedirect()) { $window.location.assign(landing_pages[0]); } }); } /** * Extracts landing pages from Fusion response data. */ function getLandingPagesFromData(data) { return _.get(data, 'fusion.landing-pages'); } } })();
Remove other landing pages service
Remove other landing pages service
JavaScript
apache-2.0
AlexKolonitsky/lucidworks-view,AlexKolonitsky/lucidworks-view,lucidworks/lucidworks-view,lucidworks/lucidworks-view,lucidworks/lucidworks-view,AlexKolonitsky/lucidworks-view
--- +++ @@ -29,7 +29,6 @@ resultsObservable.addObserver(function (data) { var landing_pages = service.getLandingPagesFromData(data); - $log.debug('landing_pages', landing_pages); if (angular.isArray(landing_pages) && ConfigService.getLandingPageRedirect()) { $window.location.assign(landing_pages[0]); }
4886982fa7108c0cc5aa68c43f75e8cbc3b1903e
getPlannedWork/crawler.js
getPlannedWork/crawler.js
const moment = require('moment'); const plannedWork = require('./plannedWork'); const { baseURL, routes, imgMap } = require('./constants.js'); function buildLink({ route, datetime }) { const date = moment(datetime); return `${baseURL}?tag=${route}&date=${date.format('MM/DD/YYYY')}&time=&method=getstatus4`; } function plannedWorkByDate(datetime) { const pages = routes.map((route) => { const link = buildLink({ route, datetime }); return plannedWork(link); }); // each advisory can have multiple messages const messagesByRoute = {}; return Promise.all(pages) .then((advisories) => { advisories.forEach((advisory, index) => { const route = routes[index]; messagesByRoute[route] = advisory; }); return messagesByRoute; } module.exports = plannedWorkByDate;
const moment = require('moment'); const plannedWork = require('./plannedWork'); const DateRange = require('./DateRange'); const { baseURL, routes, imgMap } = require('./constants.js'); function buildLink({ route, datetime }) { const date = moment(datetime); return `${baseURL}?tag=${route}&date=${date.format('MM/DD/YYYY')}&time=&method=getstatus4`; } function plannedWorkByDate(datetime) { const pages = routes.map((route) => { const link = buildLink({ route, datetime }); return plannedWork(link); }); // each advisory can have multiple messages const messagesByRoute = {}; return Promise.all(pages) .then((advisories) => { advisories.forEach((advisory, index) => { const route = routes[index]; messagesByRoute[route] = advisory; }); return messagesByRoute; }); } /** * Scrapes service advisories across multiple date ranges * * @param Number num - How many results to return * @param Date from - Which date to start with * @return Array[Object] - Batches of work for a specified * date range */ function getWorkBatches(num=3, from=Date.now()) { const batches = []; const start = new DateRange(from); for (let offset = 0; offset < num; offset++) { const dateRange = start.next(offset); const advisories = plannedWorkByDate(dateRange.start); batches.push(Promise.resolve(advisories) .then((plannedWork) => ({ type: dateRange.type, start: dateRange.start, end: dateRange.end, plannedWork, }))) } return Promise.all(batches) } module.exports = getWorkBatches;
Implement crawling by date range
Implement crawling by date range The website will display Service Advisories first by date range, then by train route. Previous commits added methods for scraping all routes for a particular date. This commit adds a method to invoke that method for multiple date ranges.
JavaScript
mit
geoffreyyip/mta-dashboard,geoffreyyip/mta-dashboard
--- +++ @@ -1,6 +1,7 @@ const moment = require('moment'); const plannedWork = require('./plannedWork'); +const DateRange = require('./DateRange'); const { baseURL, routes, imgMap } = require('./constants.js'); function buildLink({ route, datetime }) { @@ -23,6 +24,34 @@ messagesByRoute[route] = advisory; }); return messagesByRoute; + }); } -module.exports = plannedWorkByDate; +/** + * Scrapes service advisories across multiple date ranges + * + * @param Number num - How many results to return + * @param Date from - Which date to start with + * @return Array[Object] - Batches of work for a specified + * date range + */ +function getWorkBatches(num=3, from=Date.now()) { + const batches = []; + const start = new DateRange(from); + + for (let offset = 0; offset < num; offset++) { + const dateRange = start.next(offset); + const advisories = plannedWorkByDate(dateRange.start); + batches.push(Promise.resolve(advisories) + .then((plannedWork) => ({ + type: dateRange.type, + start: dateRange.start, + end: dateRange.end, + plannedWork, + }))) + } + + return Promise.all(batches) +} + +module.exports = getWorkBatches;
5953b9dc1aeb7edc6b8b524870e70b6af83fb776
test/support/assert-paranoid-equal/utilities.js
test/support/assert-paranoid-equal/utilities.js
'use strict'; function isNothing(subject) { return (undefined === subject) || (null === subject); } function isObject(subject) { return ('object' === typeof subject) && (null !== subject); } function isNaNConstant(subject) { // There is not Number.isNaN in Node 0.6.x return ('number' === typeof subject) && isNaN(subject); } function isInstanceOf(constructor /*, subjects... */) { var index, length = arguments.length; if (length < 2) { return false; } for (index = 1; index < length; index += 1) { if (!(arguments[index] instanceof constructor)) { return false; } } return true; } function collectKeys(subject, include, exclude) { var result = Object.getOwnPropertyNames(subject); if (!isNothing(include)) { include.forEach(function (key) { if (0 > result.indexOf(key)) { result.push(key); } }); } if (!isNothing(exclude)) { result = result.filter(function (key) { return 0 > exclude.indexOf(key); }); } return result; } module.exports.isNothing = isNothing; module.exports.isObject = isObject; module.exports.isNaNConstant = isNaNConstant; module.exports.isInstanceOf = isInstanceOf; module.exports.collectKeys = collectKeys;
'use strict'; function isNothing(subject) { return (undefined === subject) || (null === subject); } function isObject(subject) { return ('object' === typeof subject) && (null !== subject); } function isNaNConstant(subject) { if (undefined !== Number.isNaN) { return Number.isNaN(subject); } else { // There is no Number.isNaN in Node 0.6.x return ('number' === typeof subject) && isNaN(subject); } } function isInstanceOf(constructor /*, subjects... */) { var index, length = arguments.length; if (length < 2) { return false; } for (index = 1; index < length; index += 1) { if (!(arguments[index] instanceof constructor)) { return false; } } return true; } function collectKeys(subject, include, exclude) { var result = Object.getOwnPropertyNames(subject); if (!isNothing(include)) { include.forEach(function (key) { if (0 > result.indexOf(key)) { result.push(key); } }); } if (!isNothing(exclude)) { result = result.filter(function (key) { return 0 > exclude.indexOf(key); }); } return result; } module.exports.isNothing = isNothing; module.exports.isObject = isObject; module.exports.isNaNConstant = isNaNConstant; module.exports.isInstanceOf = isInstanceOf; module.exports.collectKeys = collectKeys;
Update the paranoid equal to the lastest version
Update the paranoid equal to the lastest version
JavaScript
mit
cesarmarinhorj/js-yaml,doowb/js-yaml,djchie/js-yaml,jonnor/js-yaml,pombredanne/js-yaml,jonnor/js-yaml,jonnor/js-yaml,deltreey/js-yaml,nodeca/js-yaml,prose/js-yaml,denji/js-yaml,vogelsgesang/js-yaml,vogelsgesang/js-yaml,bjlxj2008/js-yaml,minj/js-yaml,bjlxj2008/js-yaml,denji/js-yaml,djchie/js-yaml,nodeca/js-yaml,doowb/js-yaml,crissdev/js-yaml,pombredanne/js-yaml,cesarmarinhorj/js-yaml,pombredanne/js-yaml,doowb/js-yaml,SmartBear/js-yaml,rjmunro/js-yaml,djchie/js-yaml,rjmunro/js-yaml,deltreey/js-yaml,deltreey/js-yaml,nodeca/js-yaml,crissdev/js-yaml,isaacs/js-yaml,bjlxj2008/js-yaml,denji/js-yaml,isaacs/js-yaml,joshball/js-yaml,SmartBear/js-yaml,minj/js-yaml,minj/js-yaml,vogelsgesang/js-yaml,crissdev/js-yaml,rjmunro/js-yaml,SmartBear/js-yaml,joshball/js-yaml,isaacs/js-yaml,cesarmarinhorj/js-yaml,joshball/js-yaml
--- +++ @@ -12,8 +12,12 @@ function isNaNConstant(subject) { - // There is not Number.isNaN in Node 0.6.x - return ('number' === typeof subject) && isNaN(subject); + if (undefined !== Number.isNaN) { + return Number.isNaN(subject); + } else { + // There is no Number.isNaN in Node 0.6.x + return ('number' === typeof subject) && isNaN(subject); + } }
e8b67dea98931e469a1b1d741abbfbed73b2ec23
app/js/arethusa.core/directives/arethusa_navbar.js
app/js/arethusa.core/directives/arethusa_navbar.js
'use strict'; /* Configurable navbar * * The following variables can be declared in a conf file * disable - Boolean * search - Boolean * navigation - Boolean * notifier - Boolean * template - String * * Example; * * { * "navbar" : { * "search" : true, * "navigation" : true, * "template" : "templates/navbar.html" * } * */ angular.module('arethusa.core').directive('arethusaNavbar', [ 'configurator', function (configurator) { return { restrict: 'AE', scope: true, link: function (scope, element, attrs) { var conf = configurator.configurationFor('navbar'); scope.template = conf.template; scope.disable = conf.disable; scope.showSearch = function () { return conf.search; }; scope.showNavigation = function () { return conf.navigation; }; scope.showNotifier = function () { return conf.notifier; }; }, template: '<div ng-if="! disable" ng-include="template"></div>' }; } ]);
'use strict'; /* Configurable navbar * * The following variables can be declared in a conf file * disable - Boolean * search - Boolean * navigation - Boolean * notifier - Boolean * template - String * * Example; * * { * "navbar" : { * "search" : true, * "navigation" : true, * "template" : "templates/navbar.html" * } * */ angular.module('arethusa.core').directive('arethusaNavbar', [ 'configurator', function (configurator) { return { restrict: 'AE', scope: true, link: function (scope, element, attrs) { var conf = configurator.configurationFor('navbar'); scope.template = conf.template; scope.disable = conf.disable; scope.showSearch = function () { return conf.search; }; scope.showNavigation = function () { return conf.navigation; }; scope.showNotifier = function () { return conf.notifier; }; }, template: '<div ng-if="! disable" ng-include="template"></div>' }; } ]);
Delete an empty line again...
Delete an empty line again...
JavaScript
mit
fbaumgardt/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,PonteIneptique/arethusa,PonteIneptique/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,Masoumeh/arethusa,Masoumeh/arethusa,alpheios-project/arethusa,latin-language-toolkit/arethusa,latin-language-toolkit/arethusa
c3907ccc5aa74b7186f020fa3671a2e66f2ef683
nin/dasBoot/THREENode.js
nin/dasBoot/THREENode.js
class THREENode extends NIN.Node { constructor(id, options) { if(!('render' in options.outputs)) { options.outputs.render = new NIN.TextureOutput(); } super(id, { inputs: options.inputs, outputs: options.outputs, }); this.options = options; this.scene = new THREE.Scene(); this.renderTarget = new THREE.WebGLRenderTarget(640, 360, { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat }); if (options.camera) { this.cameraController = new CameraController(); this.camera = this.cameraController.camera; Loader.loadAjax(options.camera, response => this.initializeCamera(response)); } else { this.camera = new THREE.PerspectiveCamera(45, 16/9, 1, 10000); } } initializeCamera(rawRawPath) { const rawPath = JSON.parse(rawRawPath); this.cameraController.parseCameraPath(rawPath); } resize() { this.renderTarget.setSize(16 * GU, 9 * GU); } render(renderer) { renderer.render(this.scene, this.camera, this.renderTarget, true); this.outputs.render.setValue(this.renderTarget.texture); } update(frame) { if (this.cameraController) { this.cameraController.updateCamera(frame); } } } module.exports = THREENode;
class THREENode extends NIN.Node { constructor(id, options) { if(!('outputs' in options)) { options.outputs = {}; } if(!('render' in options.outputs)) { options.outputs.render = new NIN.TextureOutput(); } super(id, { inputs: options.inputs, outputs: options.outputs, }); this.options = options; this.scene = new THREE.Scene(); this.renderTarget = new THREE.WebGLRenderTarget(640, 360, { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat }); if (options.camera) { this.cameraController = new CameraController(); this.camera = this.cameraController.camera; Loader.loadAjax(options.camera, response => this.initializeCamera(response)); } else { this.camera = new THREE.PerspectiveCamera(45, 16/9, 1, 10000); } } initializeCamera(rawRawPath) { const rawPath = JSON.parse(rawRawPath); this.cameraController.parseCameraPath(rawPath); } resize() { this.renderTarget.setSize(16 * GU, 9 * GU); } render(renderer) { renderer.render(this.scene, this.camera, this.renderTarget, true); this.outputs.render.setValue(this.renderTarget.texture); } update(frame) { if (this.cameraController) { this.cameraController.updateCamera(frame); } } } module.exports = THREENode;
Make sure nodes always have an output property
Make sure nodes always have an output property 4545fcdc1808618723a4f5cd8a228b5c0b121ab7 broke nodes that did not have an output property specified at all, and that relied on NIN.Node to provide the whole output setup for them. This made ninjadev/re stop working, so here's a fix for that.
JavaScript
apache-2.0
ninjadev/nin,ninjadev/nin,ninjadev/nin
--- +++ @@ -1,5 +1,8 @@ class THREENode extends NIN.Node { constructor(id, options) { + if(!('outputs' in options)) { + options.outputs = {}; + } if(!('render' in options.outputs)) { options.outputs.render = new NIN.TextureOutput(); }
92aed6c12583ca9f56dd4bc703193beffed84da5
feature-detects/css/transformstylepreserve3d.js
feature-detects/css/transformstylepreserve3d.js
/*! { "name": "CSS Transform Style preserve-3d", "property": "preserve3d", "authors": ["denyskoch", "aFarkas"], "tags": ["css"], "notes": [{ "name": "MDN Docs", "href": "https://developer.mozilla.org/en-US/docs/Web/CSS/transform-style" },{ "name": "Related Github Issue", "href": "https://github.com/Modernizr/Modernizr/issues/1748" }] } !*/ /* DOC Detects support for `transform-style: preserve-3d`, for getting a proper 3D perspective on elements. */ define(['Modernizr', 'createElement', 'docElement'], function(Modernizr, createElement, docElement) { Modernizr.addTest('preserve3d', function() { var outerDiv = createElement('div'); var innerDiv = createElement('div'); outerDiv.style.cssText = 'transform-style: preserve-3d; transform-origin: right; transform: rotateY(40deg);'; innerDiv.style.cssText = 'width: 9px; height: 1px; background: #000; transform-origin: right; transform: rotateY(40deg);'; outerDiv.appendChild(innerDiv); docElement.appendChild(outerDiv); var result = innerDiv.getBoundingClientRect(); docElement.removeChild(outerDiv); return result.width && result.width < 4; }); });
/*! { "name": "CSS Transform Style preserve-3d", "property": "preserve3d", "authors": ["denyskoch", "aFarkas"], "tags": ["css"], "notes": [{ "name": "MDN Docs", "href": "https://developer.mozilla.org/en-US/docs/Web/CSS/transform-style" },{ "name": "Related Github Issue", "href": "https://github.com/Modernizr/Modernizr/issues/1748" }] } !*/ /* DOC Detects support for `transform-style: preserve-3d`, for getting a proper 3D perspective on elements. */ define(['Modernizr', 'createElement', 'docElement'], function(Modernizr, createElement, docElement) { Modernizr.addTest('preserve3d', function() { var outerDiv, innerDiv; var CSS = window.CSS; var result = true; if (!CSS || !CSS.supports || !CSS.supports('(transform-style: preserve-3d)')) { outerDiv = createElement('div'); innerDiv = createElement('div'); outerDiv.style.cssText = 'transform-style: preserve-3d; transform-origin: right; transform: rotateY(40deg);'; innerDiv.style.cssText = 'width: 9px; height: 1px; background: #000; transform-origin: right; transform: rotateY(40deg);'; outerDiv.appendChild(innerDiv); docElement.appendChild(outerDiv); result = innerDiv.getBoundingClientRect(); docElement.removeChild(outerDiv); result = result.width && result.width < 4; } return result; }); });
Fix preserve3d's IE11/Win10 false positive
Fix preserve3d's IE11/Win10 false positive
JavaScript
mit
Modernizr/Modernizr,Modernizr/Modernizr
--- +++ @@ -18,18 +18,24 @@ */ define(['Modernizr', 'createElement', 'docElement'], function(Modernizr, createElement, docElement) { Modernizr.addTest('preserve3d', function() { - var outerDiv = createElement('div'); - var innerDiv = createElement('div'); + var outerDiv, innerDiv; + var CSS = window.CSS; + var result = true; - outerDiv.style.cssText = 'transform-style: preserve-3d; transform-origin: right; transform: rotateY(40deg);'; - innerDiv.style.cssText = 'width: 9px; height: 1px; background: #000; transform-origin: right; transform: rotateY(40deg);'; + if (!CSS || !CSS.supports || !CSS.supports('(transform-style: preserve-3d)')) { + outerDiv = createElement('div'); + innerDiv = createElement('div'); - outerDiv.appendChild(innerDiv); - docElement.appendChild(outerDiv); + outerDiv.style.cssText = 'transform-style: preserve-3d; transform-origin: right; transform: rotateY(40deg);'; + innerDiv.style.cssText = 'width: 9px; height: 1px; background: #000; transform-origin: right; transform: rotateY(40deg);'; - var result = innerDiv.getBoundingClientRect(); - docElement.removeChild(outerDiv); + outerDiv.appendChild(innerDiv); + docElement.appendChild(outerDiv); - return result.width && result.width < 4; + result = innerDiv.getBoundingClientRect(); + docElement.removeChild(outerDiv); + result = result.width && result.width < 4; + } + return result; }); });
0270da4122605fafc067c72091dc5836f5211f95
src/app/templates.spec.js
src/app/templates.spec.js
describe('templates', function () { beforeEach(module('prx', 'templates', function ($provide) { $provide.decorator('$templateCache', function ($delegate) { var put = $delegate.put; $delegate.toTest = []; $delegate.put = function (uri) { this.toTest.push(uri); return put.apply(this, [].slice.call(arguments)); }; return $delegate; }); })); it ('can compile all templates', inject(function ($rootScope, $compile, $templateCache) { var scope = $rootScope.$new(); angular.forEach($templateCache.toTest, function (uri) { $compile($templateCache.get(uri))(scope); }); })); });
describe('templates', function () { var $scope, $compile; beforeEach(module('prx', 'templates', function ($provide, $stateProvider) { $stateProvider.state('fakeState', {}); $provide.decorator('$templateCache', function ($delegate) { var put = $delegate.put; $delegate.toTest = []; $delegate.put = function (uri) { this.toTest.push(uri); return put.apply(this, [].slice.call(arguments)); }; return $delegate; }); })); beforeEach(inject(function ($state, $rootScope, _$compile_) { var fakeState = $state.get('fakeState'); fakeState.parent = fakeState; $state.$current = fakeState; $scope = $rootScope.$new(); $compile = _$compile_; })); it ('can compile all templates', inject(function ($templateCache) { angular.forEach($templateCache.toTest, function (uri) { $compile($templateCache.get(uri))($scope); }); })); });
Set state context in test for template compilability with infinite lineage.
Set state context in test for template compilability with infinite lineage.
JavaScript
agpl-3.0
PRX/www.prx.org,PRX/www.prx.org,PRX/www.prx.org
--- +++ @@ -1,5 +1,9 @@ describe('templates', function () { - beforeEach(module('prx', 'templates', function ($provide) { + var $scope, $compile; + + beforeEach(module('prx', 'templates', function ($provide, $stateProvider) { + $stateProvider.state('fakeState', {}); + $provide.decorator('$templateCache', function ($delegate) { var put = $delegate.put; $delegate.toTest = []; @@ -11,10 +15,18 @@ }); })); - it ('can compile all templates', inject(function ($rootScope, $compile, $templateCache) { - var scope = $rootScope.$new(); + beforeEach(inject(function ($state, $rootScope, _$compile_) { + var fakeState = $state.get('fakeState'); + fakeState.parent = fakeState; + $state.$current = fakeState; + + $scope = $rootScope.$new(); + $compile = _$compile_; + })); + + it ('can compile all templates', inject(function ($templateCache) { angular.forEach($templateCache.toTest, function (uri) { - $compile($templateCache.get(uri))(scope); + $compile($templateCache.get(uri))($scope); }); })); });
53ff5ddff1c8e95f74405cbbc557e02574c6557e
src/blocks/block-quote.js
src/blocks/block-quote.js
/* Block Quote */ SirTrevor.Blocks.Quote = (function(){ var template = _.template([ '<blockquote class="st-required st-text-block" contenteditable="true"></blockquote>', '<label class="st-input-label"> <%= i18n.t("blocks:quote:credit_field") %></label>', '<input maxlength="140" name="cite" placeholder="<%= i18n.t("blocks:quote:credit_field") %>"', ' class="st-input-string st-required js-cite-input" type="text" />' ].join("\n")); return SirTrevor.Block.extend({ type: "quote", title: function(){ return i18n.t('blocks:quote:title'); }, icon_name: 'quote', editorHTML: function() { return template(this); }, loadData: function(data){ this.getTextBlock().html(SirTrevor.toHTML(data.text, this.type)); this.$('.js-cite-input').val(data.cite); }, toMarkdown: function(markdown) { return markdown.replace(/^(.+)$/mg,"> $1"); } }); })();
/* Block Quote */ SirTrevor.Blocks.Quote = (function(){ var template = _.template([ '<blockquote class="st-required st-text-block" contenteditable="true"></blockquote>', '<label class="st-input-label"> <%= i18n.t("blocks:quote:credit_field") %></label>', '<input maxlength="140" name="cite" placeholder="<%= i18n.t("blocks:quote:credit_field") %>"', ' class="st-input-string st-required js-cite-input" type="text" />' ].join("\n")); return SirTrevor.Block.extend({ type: 'Quote', title: function(){ return i18n.t('blocks:quote:title'); }, icon_name: 'quote', editorHTML: function() { return template(this); }, loadData: function(data){ this.getTextBlock().html(SirTrevor.toHTML(data.text, this.type)); this.$('.js-cite-input').val(data.cite); }, toMarkdown: function(markdown) { return markdown.replace(/^(.+)$/mg,"> $1"); } }); })();
Fix quote block type property
Fix quote block type property They're suppose to be capitalized
JavaScript
mit
Shorthand/sir-trevor-js,Shorthand/sir-trevor-js,Shorthand/sir-trevor-js
--- +++ @@ -13,7 +13,7 @@ return SirTrevor.Block.extend({ - type: "quote", + type: 'Quote', title: function(){ return i18n.t('blocks:quote:title'); },
ff334dfa7d1687a923f476db1166acd47e7ee059
src/javascripts/frigging_bootstrap/components/timepicker.js
src/javascripts/frigging_bootstrap/components/timepicker.js
let React = require("react") let cx = require("classnames") let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js") let {div, input} = React.DOM export default class extends React.Component { static displayName = "Frig.friggingBootstrap.TimePicker" static defaultProps = Object.assign(require("../default_props.js")) _input() { return input(Object.assign({}, this.props.inputHtml, { valueLink: this.props.valueLink, className: cx(this.props.inputHtml.className, "form-control"), }) ) } render() { return div({className: cx(sizeClassNames(this.props))}, div({className: formGroupCx(this.props)}, div({}, label(this.props) ), this._input(), errorList(this.props.errors), ), ) } }
let React = require("react") let cx = require("classnames") let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js") let {div, input} = React.DOM export default class extends React.Component { static displayName = "Frig.friggingBootstrap.TimePicker" static defaultProps = Object.assign(require("../default_props.js")) _input() { return input(Object.assign({}, this.props.inputHtml, { valueLink: { value: this.props.valueLink.value, requestChange: this._onTimeChange, }, className: cx(this.props.inputHtml.className, "form-control"), }) ) } _onTimeChange(newTime) { console.log(`New Time ${newTime}`) } render() { return div({className: cx(sizeClassNames(this.props))}, div({className: formGroupCx(this.props)}, div({}, label(this.props) ), this._input(), errorList(this.props.errors), ), ) } }
Add ValueLink To On Change For Timepicker
Add ValueLink To On Change For Timepicker
JavaScript
mit
frig-js/frig,TouchBistro/frig,frig-js/frig,TouchBistro/frig
--- +++ @@ -11,10 +11,17 @@ _input() { return input(Object.assign({}, this.props.inputHtml, { - valueLink: this.props.valueLink, - className: cx(this.props.inputHtml.className, "form-control"), + valueLink: { + value: this.props.valueLink.value, + requestChange: this._onTimeChange, + }, + className: cx(this.props.inputHtml.className, "form-control"), }) ) + } + + _onTimeChange(newTime) { + console.log(`New Time ${newTime}`) } render() {
16d9bbe0e294d817a6cc6ce8b9db64049b317f75
src/commands/dockerize.js
src/commands/dockerize.js
import { spawn } from "cross-spawn"; import path from "path"; import process from "process"; import commandExists from "command-exists"; module.exports = function (name) { // Check if docker is installed first commandExists("docker", function(err, commandExists) { if(commandExists) { spawn("docker", ["build", "-t", name, "-f", path.join(process.cwd(), "src", "config", ".Dockerfile"), process.cwd()], {stdio: "inherit"}); } else { console.warn("You must install docker before continuing"); } }); };
import { spawn } from "cross-spawn"; import path from "path"; import process from "process"; import commandExists from "command-exists"; import logger from "../lib/logger.js"; module.exports = function (name) { // Check if docker is installed first commandExists("docker", function(err, commandExists) { if(commandExists) { spawn("docker", ["build", "-t", name, "-f", path.join(process.cwd(), "src", "config", ".Dockerfile"), process.cwd()], {stdio: "inherit"}); } else { logger.warn("You must install docker before continuing"); } }); };
Add logger for docker warning
Add logger for docker warning
JavaScript
mit
TrueCar/gluestick,TrueCar/gluestick,TrueCar/gluestick
--- +++ @@ -2,6 +2,7 @@ import path from "path"; import process from "process"; import commandExists from "command-exists"; +import logger from "../lib/logger.js"; module.exports = function (name) { // Check if docker is installed first @@ -9,7 +10,7 @@ if(commandExists) { spawn("docker", ["build", "-t", name, "-f", path.join(process.cwd(), "src", "config", ".Dockerfile"), process.cwd()], {stdio: "inherit"}); } else { - console.warn("You must install docker before continuing"); + logger.warn("You must install docker before continuing"); } }); };
f6793e5fb331d1091702aa2055cb801e133c387f
js/directives/textarea.js
js/directives/textarea.js
webui.directive("textarea", function() { return { restrict: "E", link: function(scope, element) { element.attr( "placeholder", element.attr("placeholder").replace(/\\n/g, "\n") ).bind("keydown keypress", function(event) { if (event.ctrlKey && event.which === 13) { event.preventDefault(); scope.$close(); } }); } }; });
webui.directive("textarea", function() { return { restrict: "E", link: function(scope, element) { element.attr( "placeholder", function(index, placeholder) { if (placeholder !== undefined) { return placeholder.replace(/\\n/g, "\n"); } else { return placeholder; } } ).bind("keydown keypress", function(event) { if (event.ctrlKey && event.which === 13) { event.preventDefault(); scope.$close(); } }); } }; });
Fix "Cannot read property 'replace' of undefined"
Fix "Cannot read property 'replace' of undefined" Signed-off-by: kuoruan <2b8c98b0b69c0b74bfe03cced5a9f738a15f1468@gmail.com>
JavaScript
mit
ziahamza/webui-aria2,ghostry/webui-aria2,ghostry/webui-aria2,kuoruan/webui-aria2,kuoruan/webui-aria2,ziahamza/webui-aria2
--- +++ @@ -4,7 +4,13 @@ link: function(scope, element) { element.attr( "placeholder", - element.attr("placeholder").replace(/\\n/g, "\n") + function(index, placeholder) { + if (placeholder !== undefined) { + return placeholder.replace(/\\n/g, "\n"); + } else { + return placeholder; + } + } ).bind("keydown keypress", function(event) { if (event.ctrlKey && event.which === 13) { event.preventDefault();
ebeeb1a8a0871467b9b7597c3bd82b8b67829364
src/javascript/binary/components/trackjs_onerror.js
src/javascript/binary/components/trackjs_onerror.js
window._trackJs = { onError: function(payload, error) { function itemExistInList(item, list) { for (var i = 0; i < list.length; i++) { if (item.indexOf(list[i]) > -1) { return true; } } return false; } var ignorableErrors = [ // General script error, not actionable "[object Event]", // General script error, not actionable "Script error.", // an error caused by DealPly (http://www.dealply.com/) chrome extension "DealPly", // this error is reported when a post request returns error, i.e. html body // the details provided in this case are completely useless, thus discarded "Unexpected token <" ]; if (itemExistInList(payload.message, ignorableErrors)) { return false; } payload.network = payload.network.filter(function(item) { // ignore random errors from Intercom if (item.statusCode === 403 && payload.message.indexOf("intercom") > -1) { return false; } return true; }); return true; } };
window._trackJs = { onError: function(payload, error) { function itemExistInList(item, list) { for (var i = 0; i < list.length; i++) { if (item.indexOf(list[i]) > -1) { return true; } } return false; } var ignorableErrors = [ // General script error, not actionable "[object Event]", // General script error, not actionable "Script error.", // error when user interrupts script loading, nothing to fix "Error loading script", // an error caused by DealPly (http://www.dealply.com/) chrome extension "DealPly", // this error is reported when a post request returns error, i.e. html body // the details provided in this case are completely useless, thus discarded "Unexpected token <" ]; if (itemExistInList(payload.message, ignorableErrors)) { return false; } payload.network = payload.network.filter(function(item) { // ignore random errors from Intercom if (item.statusCode === 403 && payload.message.indexOf("intercom") > -1) { return false; } return true; }); return true; } };
Add a general 'loading script' to ignore list
Add a general 'loading script' to ignore list
JavaScript
apache-2.0
borisyankov/binary-static,borisyankov/binary-static,einhverfr/binary-static,animeshsaxena/binary-static,brodiecapel16/binary-static,einhverfr/binary-static,animeshsaxena/binary-static,brodiecapel16/binary-static,tfoertsch/binary-static,tfoertsch/binary-static,massihx/binary-static,massihx/binary-static,brodiecapel16/binary-static,brodiecapel16/binary-static,massihx/binary-static,einhverfr/binary-static,borisyankov/binary-static,animeshsaxena/binary-static,junbon/binary-static-www2,animeshsaxena/binary-static,junbon/binary-static-www2,einhverfr/binary-static,borisyankov/binary-static,massihx/binary-static
--- +++ @@ -15,6 +15,8 @@ "[object Event]", // General script error, not actionable "Script error.", + // error when user interrupts script loading, nothing to fix + "Error loading script", // an error caused by DealPly (http://www.dealply.com/) chrome extension "DealPly", // this error is reported when a post request returns error, i.e. html body
3bd270f245b5e98a4784548d40959337dd050625
src/javascript/binary/components/trackjs_onerror.js
src/javascript/binary/components/trackjs_onerror.js
window._trackJs = { onError: function(payload, error) { function itemExistInList(item, list) { for (var i = 0; i < list.length; i++) { if (item.indexOf(list[i]) > -1) { return true; } } return false; } var ignorableErrors = [ // General script error, not actionable "[object Event]", // General script error, not actionable "Script error.", // error when user interrupts script loading, nothing to fix "Error loading script", // an error caused by DealPly (http://www.dealply.com/) chrome extension "DealPly", // this error is reported when a post request returns error, i.e. html body // the details provided in this case are completely useless, thus discarded "Unexpected token <" ]; if (itemExistInList(payload.message, ignorableErrors)) { return false; } payload.network = payload.network.filter(function(item) { // ignore random errors from Intercom if (item.statusCode === 403 && payload.message.indexOf("intercom") > -1) { return false; } return true; }); return true; } };
window._trackJs = { onError: function(payload, error) { function itemExistInList(item, list) { for (var i = 0; i < list.length; i++) { if (item.indexOf(list[i]) > -1) { return true; } } return false; } var ignorableErrors = [ // General script error, not actionable "[object Event]", // General script error, not actionable "Script error.", // error when user interrupts script loading, nothing to fix "Error loading script", // an error caused by DealPly (http://www.dealply.com/) chrome extension "DealPly", // this error is reported when a post request returns error, i.e. html body // the details provided in this case are completely useless, thus discarded "Unexpected token <" ]; if (itemExistInList(payload.message, ignorableErrors)) { return false; } payload.network = payload.network.filter(function(item) { // ignore random errors from Intercom if (item.statusCode === 403 && payload.message.indexOf("intercom") > -1) { return false; } return true; }); return true; } }; // if Track:js is already loaded, we need to initialize it if (typeof trackJs !== 'undefined') trackJs.configure(window._trackJs);
Check for TrackJs already loaded and if yes, reinitialize it. Fixed version.
Check for TrackJs already loaded and if yes, reinitialize it. Fixed version.
JavaScript
apache-2.0
animeshsaxena/binary-static,tfoertsch/binary-static,einhverfr/binary-static,einhverfr/binary-static,tfoertsch/binary-static,borisyankov/binary-static,einhverfr/binary-static,massihx/binary-static,animeshsaxena/binary-static,animeshsaxena/binary-static,brodiecapel16/binary-static,brodiecapel16/binary-static,borisyankov/binary-static,massihx/binary-static,brodiecapel16/binary-static,einhverfr/binary-static,animeshsaxena/binary-static,junbon/binary-static-www2,massihx/binary-static,massihx/binary-static,borisyankov/binary-static,borisyankov/binary-static,brodiecapel16/binary-static,junbon/binary-static-www2
--- +++ @@ -41,3 +41,6 @@ return true; } }; + +// if Track:js is already loaded, we need to initialize it +if (typeof trackJs !== 'undefined') trackJs.configure(window._trackJs);
ee0a0699a9804c485e464f521e5c95d506d0fa29
app/components/audit_log/Export.js
app/components/audit_log/Export.js
import React from 'react'; import PropTypes from 'prop-types'; import Relay from 'react-relay/classic'; const exampleQuery = (slug) => `query { organization(slug: "${slug}") { auditEvents(first: 500) { edges { node { type occurredAt actor { name } subject { name type } data } } } } }`; class AuditLogExport extends React.PureComponent { static propTypes = { organization: PropTypes.shape({ slug: PropTypes.string.isRequired }).isRequired }; render() { const linkClassName = 'text-decoration-none semi-bold lime hover-lime hover-underline'; return ( <div> <p>Your organizationʼs audit log can be queried and exported using the <a href="/docs/graphql-api" className={linkClassName}>GraphQL API</a>.</p> <p>For example:</p> <pre className="border border-gray rounded bg-silver overflow-auto p2 monospace"> {exampleQuery(this.props.organization.slug)} </pre> <p>See the <a href="/docs/graphql-api" className={linkClassName}>GraphQL Documentation</a> for more information.</p> </div> ); } } export default Relay.createContainer(AuditLogExport, { fragments: { organization: () => Relay.QL` fragment on Organization { slug } ` } });
import React from 'react'; import PropTypes from 'prop-types'; import Relay from 'react-relay/classic'; const exampleQuery = (slug) => `query { organization(slug: "${slug}") { auditEvents(first: 500) { edges { node { type occurredAt actor { name } subject { name type } data } } } } }`; class AuditLogExport extends React.PureComponent { static propTypes = { organization: PropTypes.shape({ slug: PropTypes.string.isRequired }).isRequired }; render() { const linkClassName = 'text-decoration-none semi-bold lime hover-lime hover-underline'; return ( <div> <p> Your organizationʼs audit log can be queried and exported using the <a href="/docs/graphql-api" className={linkClassName}>GraphQL API</a>. </p> <p>For example:</p> <pre className="border border-gray rounded bg-silver overflow-auto p2 monospace"> {exampleQuery(this.props.organization.slug)} </pre> <p> See the <a href="/docs/graphql-api" className={linkClassName}>GraphQL Documentation</a> for more information. </p> </div> ); } } export default Relay.createContainer(AuditLogExport, { fragments: { organization: () => Relay.QL` fragment on Organization { slug } ` } });
Tweak layout of export component
Tweak layout of export component
JavaScript
mit
buildkite/frontend,fotinakis/buildkite-frontend,buildkite/frontend,fotinakis/buildkite-frontend
--- +++ @@ -35,12 +35,16 @@ return ( <div> - <p>Your organizationʼs audit log can be queried and exported using the <a href="/docs/graphql-api" className={linkClassName}>GraphQL API</a>.</p> + <p> + Your organizationʼs audit log can be queried and exported using the <a href="/docs/graphql-api" className={linkClassName}>GraphQL API</a>. + </p> <p>For example:</p> <pre className="border border-gray rounded bg-silver overflow-auto p2 monospace"> {exampleQuery(this.props.organization.slug)} </pre> - <p>See the <a href="/docs/graphql-api" className={linkClassName}>GraphQL Documentation</a> for more information.</p> + <p> + See the <a href="/docs/graphql-api" className={linkClassName}>GraphQL Documentation</a> for more information. + </p> </div> ); }
3eed8db76786b5c9441cd76aadbf4f94c61ac421
examples/inject_ol_cesium.js
examples/inject_ol_cesium.js
(function() { const mode = window.location.href.match(/mode=([a-z0-9\-]+)\&?/i); const DIST = false; const isDev = mode && mode[1] === 'dev'; const cs = isDev ? 'CesiumUnminified/Cesium.js' : 'Cesium/Cesium.js'; const ol = (DIST && isDev) ? 'olcesium-debug.js' : '@loader'; if (!window.LAZY_CESIUM) { document.write(`${'<scr' + 'ipt type="text/javascript" src="../node_modules/@camptocamp/cesium/Build/'}${cs}"></scr` + 'ipt>'); } document.write(`${'<scr' + 'ipt type="text/javascript" src="../'}${ol}"></scr` + 'ipt>'); let s; window.lazyLoadCesium = function() { if (!s) { s = document.createElement('script'); s.type = 'text/javascript'; s.src = `../cesium/Build/${cs}`; console.log('loading Cesium...'); document.body.appendChild(s); } return s; }; })();
(function() { const mode = window.location.href.match(/mode=([a-z0-9\-]+)\&?/i); const DIST = false; const isDev = mode && mode[1] === 'dev'; const cs = isDev ? 'CesiumUnminified/Cesium.js' : 'Cesium/Cesium.js'; const ol = (DIST && isDev) ? 'olcesium-debug.js' : '@loader'; if (!window.LAZY_CESIUM) { document.write(`${'<scr' + 'ipt type="text/javascript" src="../node_modules/@camptocamp/cesium/Build/'}${cs}"></scr` + 'ipt>'); } document.write(`${'<scr' + 'ipt type="text/javascript" src="../'}${ol}"></scr` + 'ipt>'); let s; window.lazyLoadCesium = function() { if (!s) { s = document.createElement('script'); s.type = 'text/javascript'; s.src = `../node_modules/@camptocamp/cesium/Build/${cs}`; console.log('loading Cesium...'); document.body.appendChild(s); } return s; }; })();
Fix lazy load of Cesium in examples
Fix lazy load of Cesium in examples
JavaScript
bsd-2-clause
openlayers/ol-cesium,openlayers/ol-cesium,oterral/ol3-cesium,oterral/ol3-cesium,openlayers/ol3-cesium,openlayers/ol3-cesium
--- +++ @@ -15,7 +15,7 @@ if (!s) { s = document.createElement('script'); s.type = 'text/javascript'; - s.src = `../cesium/Build/${cs}`; + s.src = `../node_modules/@camptocamp/cesium/Build/${cs}`; console.log('loading Cesium...'); document.body.appendChild(s); }
db978592bc49e4a1e2ea6a4ebb1921c2d2439db0
src/getFilteredOptions.js
src/getFilteredOptions.js
import {find, isEqual, uniqueId} from 'lodash'; import getOptionLabel from './getOptionLabel'; /** * Filter out options that don't match the input string or, if multiple * selections are allowed, that have already been selected. */ function getFilteredOptions(options=[], text='', selected=[], props={}) { const {allowNew, labelKey, minLength, multiple} = props; if (text.length < minLength) { return []; } let exactMatchFound = false; let filteredOptions = options.filter(option => { const labelString = getOptionLabel(option, labelKey); if (labelString === text) { exactMatchFound = true; } return !( labelString.toLowerCase().indexOf(text.toLowerCase()) === -1 || multiple && find(selected, o => isEqual(o, option)) ); }); if ( allowNew && !!text.trim() && !(filteredOptions.length && exactMatchFound) ) { let newOption = { id: uniqueId('new-id-'), customOption: true, }; newOption[labelKey] = text; filteredOptions.push(newOption); } return filteredOptions; } export default getFilteredOptions;
import {find, isEqual, uniqueId} from 'lodash'; import getOptionLabel from './getOptionLabel'; /** * Filter out options that don't match the input string or, if multiple * selections are allowed, that have already been selected. */ function getFilteredOptions(options=[], text='', selected=[], props={}) { const {allowNew, labelKey, minLength, multiple} = props; if (text.length < minLength) { return []; } let filteredOptions = options.filter(option => { const labelString = getOptionLabel(option, labelKey); return !( labelString.toLowerCase().indexOf(text.toLowerCase()) === -1 || multiple && find(selected, o => isEqual(o, option)) ); }); const exactMatchFound = find(filteredOptions, o => ( getOptionLabel(o, labelKey) === text )); if ( allowNew && !!text.trim() && !(filteredOptions.length && exactMatchFound) ) { let newOption = { id: uniqueId('new-id-'), customOption: true, }; newOption[labelKey] = text; filteredOptions.push(newOption); } return filteredOptions; } export default getFilteredOptions;
Update how exact match is found
Update how exact match is found
JavaScript
mit
ericgio/react-bootstrap-typeahead,Neophy7e/react-bootstrap-typeahead,ericgio/react-bootstrap-typeahead,ericgio/react-bootstrap-typeahead,Neophy7e/react-bootstrap-typeahead,ericgio/react-bootstrap-typeahead,Neophy7e/react-bootstrap-typeahead
--- +++ @@ -12,19 +12,17 @@ return []; } - let exactMatchFound = false; let filteredOptions = options.filter(option => { const labelString = getOptionLabel(option, labelKey); - - if (labelString === text) { - exactMatchFound = true; - } - return !( labelString.toLowerCase().indexOf(text.toLowerCase()) === -1 || multiple && find(selected, o => isEqual(o, option)) ); }); + + const exactMatchFound = find(filteredOptions, o => ( + getOptionLabel(o, labelKey) === text + )); if ( allowNew &&
df5964d6f790513e9b3a8fd9311c1eec13b96b92
Jakefile.js
Jakefile.js
/* globals desc:false, task: false, complete: fase, jake: false */ (function (desc, task, complete, jake) { "use strict"; desc('The default task. Runs tests.'); task('default', ['tests'], function () { }); desc('Run tests'); task('tests', [], function () { jake.exec(["./node_modules/.bin/vows test/debug.test.js", "./node_modules/.bin/vows test/launcher.test.js", "./node_modules/.bin/nodeunit test/site.test.js"], function () { console.log('All tests passed.'); complete(); }, {stdout: true}); }, true); })(desc, task, complete, jake);
/* globals desc:false, task: false, complete: fase, jake: false */ (function (desc, task, complete, jake) { "use strict"; desc('The default task. Runs tests.'); task('default', ['test'], function () { }); desc('Run tests'); task('test', [], function () { jake.exec(["./node_modules/.bin/vows test/debug.test.js", "./node_modules/.bin/vows test/launcher.test.js", "./node_modules/.bin/nodeunit test/site.test.js"], function () { console.log('All tests passed.'); complete(); }, {stdout: true}); }, true); })(desc, task, complete, jake);
Set default jakefile task to 'test' so it gets executed by travis-ci.org
Set default jakefile task to 'test' so it gets executed by travis-ci.org
JavaScript
mit
ustyme/site-manager,jolira/site-manager,ustyme/site-manager
--- +++ @@ -3,11 +3,11 @@ "use strict"; desc('The default task. Runs tests.'); - task('default', ['tests'], function () { + task('default', ['test'], function () { }); desc('Run tests'); - task('tests', [], function () { + task('test', [], function () { jake.exec(["./node_modules/.bin/vows test/debug.test.js", "./node_modules/.bin/vows test/launcher.test.js", "./node_modules/.bin/nodeunit test/site.test.js"], function () {
246e6599f31ef09f5de204f87d6b10d28e15bc58
public/js/application.js
public/js/application.js
var mapSketcherClient; jQuery(function() { jQuery.getJSON('/config.json', function(config) { config.hostname = window.location.hostname mapSketcherClient = new MapSketcherClient(config); mapSketcherClient.launch(); }); $("a[rel]").overlay({ mask: { color: '#ebecff' , loadSpeed: 200 , opacity: 0.9 } }); $('#collaborativeRoomSelection form .cancel').click(function(e) { $('.close').click(); return e.preventDefault(); }); $('#collaborativeRoomSelection form').submit(function(e) { $('.close').click(); mapSketcherClient.joinColaborativeRoom(this.name.value); return e.preventDefault(); }); $('#feedback').githubVoice('sagmor', 'mapsketcher'); $('#personal').touchScrollable(); });
var mapSketcherClient; jQuery(function() { jQuery.getJSON('/config.json', function(config) { config.hostname = window.location.hostname mapSketcherClient = new MapSketcherClient(config); mapSketcherClient.launch(); }); $("a[rel]").overlay({ mask: { color: '#ebecff' , loadSpeed: 200 , opacity: 0.9 } }); $('#collaborativeRoomSelection form .cancel').click(function(e) { $('.close').click(); return e.preventDefault(); }); $('#collaborativeRoomSelection form').submit(function(e) { $('.close').click(); mapSketcherClient.joinColaborativeRoom(this.name.value); return e.preventDefault(); }); $(function() { $("#collaborativeRoomSelection form input").keypress(function (e) { if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) { $('#collaborativeRoomSelection form').submit(); return false; } else { return true; } }); }); $('#feedback').githubVoice('sagmor', 'mapsketcher'); $('#personal').touchScrollable(); });
Fix enter key on Collaborative Room selection.
Fix enter key on Collaborative Room selection.
JavaScript
mit
sagmor/mapsketcher
--- +++ @@ -27,6 +27,23 @@ return e.preventDefault(); }); + $(function() { + $("#collaborativeRoomSelection form input").keypress(function (e) { + if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) { + $('#collaborativeRoomSelection form').submit(); + return false; + } else { + return true; + } + }); + }); + + + $('#feedback').githubVoice('sagmor', 'mapsketcher'); $('#personal').touchScrollable(); + + + + });
aa32378fd966b72ec91fa440ba68c079c98e303b
lib/node/buffer/buffer.js
lib/node/buffer/buffer.js
'use strict'; var Node = require('../node'); var TYPE = 'buffer'; var PARAMS = { source: Node.PARAM.NODE, radio: Node.PARAM.NUMBER }; var Buffer = Node.create(TYPE, PARAMS); module.exports = Buffer; module.exports.TYPE = TYPE; module.exports.PARAMS = PARAMS; module.exports.create = require('./factory').create; // ------------------------------ PUBLIC API ------------------------------ // Buffer.prototype._getQuery = function() { return bufferQuery(this.source.getQuery(), this.columns, this.radio); }; // ---------------------------- END PUBLIC API ---------------------------- // function bufferQuery(inputQuery, columnNames, distance) { return [ 'SELECT ST_Buffer(the_geom::geography, ' + distance + ')::geometry the_geom,', skipColumns(columnNames).join(','), 'FROM (' + inputQuery + ') _camshaft_buffer' ].join('\n'); } var SKIP_COLUMNS = { 'the_geom': true, 'the_geom_webmercator': true }; function skipColumns(columnNames) { return columnNames .filter(function(columnName) { return !SKIP_COLUMNS[columnName]; }); }
'use strict'; var Node = require('../node'); var TYPE = 'buffer'; var PARAMS = { source: Node.PARAM.NODE, radio: Node.PARAM.NUMBER }; var Buffer = Node.create(TYPE, PARAMS); module.exports = Buffer; module.exports.TYPE = TYPE; module.exports.PARAMS = PARAMS; module.exports.create = require('./factory').create; // ------------------------------ PUBLIC API ------------------------------ // Buffer.prototype._getQuery = function() { return bufferQuery(this.source.getQuery(), this.source.getColumns(), this.radio); }; // ---------------------------- END PUBLIC API ---------------------------- // function bufferQuery(inputQuery, columnNames, distance) { return [ 'SELECT ST_Buffer(the_geom::geography, ' + distance + ')::geometry the_geom,', skipColumns(columnNames).join(','), 'FROM (' + inputQuery + ') _camshaft_buffer' ].join('\n'); } var SKIP_COLUMNS = { 'the_geom': true, 'the_geom_webmercator': true }; function skipColumns(columnNames) { return columnNames .filter(function(columnName) { return !SKIP_COLUMNS[columnName]; }); }
Use columns from source node
Use columns from source node
JavaScript
bsd-3-clause
CartoDB/camshaft
--- +++ @@ -18,7 +18,7 @@ // ------------------------------ PUBLIC API ------------------------------ // Buffer.prototype._getQuery = function() { - return bufferQuery(this.source.getQuery(), this.columns, this.radio); + return bufferQuery(this.source.getQuery(), this.source.getColumns(), this.radio); }; // ---------------------------- END PUBLIC API ---------------------------- //
af6a7b20d7332817af15c891d307ff262d886158
core/devMenu.js
core/devMenu.js
"use strict"; const electron = require("electron"); const {app} = electron; const {Menu} = electron; const {BrowserWindow} = electron; module.exports.setDevMenu = function () { var devMenu = Menu.buildFromTemplate([{ label: "Development", submenu: [{ label: "Reload", accelerator: "F5", click: function () { BrowserWindow.getFocusedWindow().reload(); } },{ label: "Toggle DevTools", accelerator: "Alt+CmdOrCtrl+I", click: function () { BrowserWindow.getFocusedWindow().toggleDevTools(); } },{ label: "Quit", accelerator: "CmdOrCtrl+Q", click: function () { app.quit(); } }] }]); Menu.setApplicationMenu(devMenu); };
"use strict"; const electron = require("electron"); const {app} = electron; const {Menu} = electron; const {BrowserWindow} = electron; module.exports.setDevMenu = function () { var devMenu = Menu.buildFromTemplate([{ label: "Development", submenu: [{ label: "Reload", accelerator: "Ctrl+R", click: function () { BrowserWindow.getFocusedWindow().reload(); } },{ label: "Toggle DevTools", accelerator: "Alt+CmdOrCtrl+I", click: function () { BrowserWindow.getFocusedWindow().toggleDevTools(); } },{ label: "Quit", accelerator: "CmdOrCtrl+Q", click: function () { app.quit(); } }] }]); Menu.setApplicationMenu(devMenu); };
Change reload accelerator to Ctrl+R
Change reload accelerator to Ctrl+R
JavaScript
mit
petschekr/Chocolate-Shell,petschekr/Chocolate-Shell
--- +++ @@ -10,7 +10,7 @@ label: "Development", submenu: [{ label: "Reload", - accelerator: "F5", + accelerator: "Ctrl+R", click: function () { BrowserWindow.getFocusedWindow().reload(); }
a96ef266eaf8fe8b1248fe69a6cd51d790f170c0
cypress/integration/list_spec.js
cypress/integration/list_spec.js
describe('The List Page', () => { beforeEach(() => { cy.visit('/list.html') }) it('successfully loads', () => {}) context('navbar', () => { it("the 'Home' link works", () => { cy.contains('Home').click({force: true}) cy.title().should('not.equal', 'Error') }) it("the 'About' link works", () => { cy.contains('About').click({force: true}) cy.title().should('not.equal', 'Error') }) }) context('footer', () => { it("the 'MIT License' link works", () => { cy.contains('MIT License').click() }) it("the 'CC BY-NC-SA 4.0' link works", () => { cy.contains('CC BY-NC-SA 4.0').click() }) }) })
describe('The List Page', () => { beforeEach(() => { cy.visit('/list.html') }) it('successfully loads', () => {}) context('navbar', () => { it("the 'Home' link works", () => { cy.contains('Home').click({force: true}) cy.title().should('not.equal', 'Error') }) it("the 'About' link works", () => { cy.contains('About').click({force: true}) cy.title().should('not.equal', 'Error') }) }) context('footer', () => { it("the 'MIT License' link works", () => { cy.contains('MIT License').click() }) it("the 'CC BY-NC-SA 4.0' link works", () => { cy.contains('CC BY-NC-SA 4.0').click() }) }) context('the list', () => { context('location based', () => { it("the 'TECH404' link works", () => { cy.contains('TECH404').click() }) it("the 'Charleston Tech' link works", () => { cy.contains('Charleston Tech').click() }) it("the 'memtech' link works", () => { cy.contains('memtech').click() }) it("the 'NashDev' link works", () => { cy.contains('NashDev').click() }) }) context('it based', () => { it("the 'APIs You Won't Hate' link works", () => { cy.contains('APIs You Won't Hate').click() }) }) context('programming based', () => { it("the 'Larachat' link works", () => { cy.contains('Larachat').click() }) }) }) })
Add tests for all current list items
Add tests for all current list items
JavaScript
mit
itzsaga/slack-list
--- +++ @@ -2,7 +2,9 @@ beforeEach(() => { cy.visit('/list.html') }) + it('successfully loads', () => {}) + context('navbar', () => { it("the 'Home' link works", () => { cy.contains('Home').click({force: true}) @@ -13,6 +15,7 @@ cy.title().should('not.equal', 'Error') }) }) + context('footer', () => { it("the 'MIT License' link works", () => { cy.contains('MIT License').click() @@ -21,4 +24,34 @@ cy.contains('CC BY-NC-SA 4.0').click() }) }) + + context('the list', () => { + + context('location based', () => { + it("the 'TECH404' link works", () => { + cy.contains('TECH404').click() + }) + it("the 'Charleston Tech' link works", () => { + cy.contains('Charleston Tech').click() + }) + it("the 'memtech' link works", () => { + cy.contains('memtech').click() + }) + it("the 'NashDev' link works", () => { + cy.contains('NashDev').click() + }) + }) + + context('it based', () => { + it("the 'APIs You Won't Hate' link works", () => { + cy.contains('APIs You Won't Hate').click() + }) + }) + + context('programming based', () => { + it("the 'Larachat' link works", () => { + cy.contains('Larachat').click() + }) + }) + }) })
4ea7ec98ad1b490b3a031f183dab0efc2feaa1d7
NotesApp.js
NotesApp.js
function NoteApplication (author) { this.author = author; this.notes = []; this.create = function(note_content) { if (note_content.length > 0) { this.notes.push(note_content); return "You have created a note"; } else { return "You haven't entered a valid note"; } } this.listNotes = function(){ if(this.noteArray.length < 1){ console.log("There are no notes in the collection."); } else{for(let i = 0; i < this.notes.length; i++){ console.log("\nNote ID: " + this.notes[i]); console.log(this.notes[i]); console.log("\n\nBy Author " + this.author + "\n"); } this.get = function(note_id) { return "Note ID: " + this.notes[note_id]; } }
function NoteApplication (author) { this.author = author; this.notes = []; this.create = function(note_content) { if (note_content.length > 0) { this.notes.push(note_content); return "You have created a note"; } else { return "You haven't entered a valid note"; } } this.listNotes = function(){ if (this.noteArray.length < 1){ console.log("There are no notes in the collection."); } else { for(let i = 0; i < this.notes.length; i++) { console.log("\nNote ID: " + this.notes[i]); console.log(this.notes[i]); console.log("\n\nBy Author " + this.author + "\n"); } } } this.get = function(note_id) { return "Note ID: " + this.notes[note_id]; } this.search = function(search_text){ if (this.notes.includes(search_text)){ return "Note ID: " + this.note_id + "\n" + note_content + "\n\n" + "By Author " + this.author; } else { return "search text not found" } this.delete = function(note_id){ delete this.notes[note_id] } this.edit = function(note_id, new_content){ this.notes[note_id] = new_content; } }
Add search, delete and edit methods
Add search, delete and edit methods
JavaScript
mit
Mayowa-Adegbola/NotesApp,Mayowa-Adegbola/NotesApp
--- +++ @@ -14,18 +14,37 @@ } this.listNotes = function(){ - if(this.noteArray.length < 1){ + if (this.noteArray.length < 1){ console.log("There are no notes in the collection."); } - else{for(let i = 0; i < this.notes.length; i++){ + else { + for(let i = 0; i < this.notes.length; i++) { console.log("\nNote ID: " + this.notes[i]); console.log(this.notes[i]); console.log("\n\nBy Author " + this.author + "\n"); - } + } + } + } this.get = function(note_id) { return "Note ID: " + this.notes[note_id]; } + this.search = function(search_text){ + if (this.notes.includes(search_text)){ + return "Note ID: " + this.note_id + "\n" + note_content + "\n\n" + "By Author " + this.author; + } else { + return "search text not found" + } + + this.delete = function(note_id){ + delete this.notes[note_id] + } + + + this.edit = function(note_id, new_content){ + this.notes[note_id] = new_content; + } + }
6e5d872baaa1e4e72bfe95a32e2ebf55ea594dde
public/app/config/translationConfig.js
public/app/config/translationConfig.js
angular.module('app').config(function ($translateProvider) { $translateProvider.useStaticFilesLoader({ prefix: '/locale/locale-', suffix: '.json' }); $translateProvider.preferredLanguage('fr_FR'); });
angular.module('app').config(function ($translateProvider) { $translateProvider.useStaticFilesLoader({ prefix: '/locale/locale-', suffix: '.json' }); $translateProvider.useSanitizeValueStrategy('escape'); $translateProvider.determinePreferredLanguage(); });
Determine preferred language and sanitizy stings
Determine preferred language and sanitizy stings
JavaScript
mit
BenjaminBini/dilemme,BenjaminBini/dilemme
--- +++ @@ -4,5 +4,7 @@ suffix: '.json' }); - $translateProvider.preferredLanguage('fr_FR'); + $translateProvider.useSanitizeValueStrategy('escape'); + + $translateProvider.determinePreferredLanguage(); });
85a03e97fa83d4fbb37c598db4272a5865b90520
app/selectors/containers/reservationDeleteModalSelector.js
app/selectors/containers/reservationDeleteModalSelector.js
import { createSelector } from 'reselect'; import ActionTypes from 'constants/ActionTypes'; import ModalTypes from 'constants/ModalTypes'; import modalIsOpenSelectorFactory from 'selectors/factories/modalIsOpenSelectorFactory'; import requestIsActiveSelectorFactory from 'selectors/factories/requestIsActiveSelectorFactory'; const toDeleteSelector = (state) => state.ui.reservation.toDelete; const resourcesSelector = (state) => state.data.resources; const reservationDeleteModalSelector = createSelector( modalIsOpenSelectorFactory(ModalTypes.DELETE_RESERVATION), requestIsActiveSelectorFactory(ActionTypes.API.RESERVATIONS_DELETE_REQUEST), resourcesSelector, toDeleteSelector, ( deleteReservationModalIsOpen, isDeletingReservations, resources, reservationsToDelete ) => { return { isDeletingReservations, reservationsToDelete, resources, show: deleteReservationModalIsOpen, }; } ); export default reservationDeleteModalSelector;
import { createSelector } from 'reselect'; import ActionTypes from 'constants/ActionTypes'; import ModalTypes from 'constants/ModalTypes'; import modalIsOpenSelectorFactory from 'selectors/factories/modalIsOpenSelectorFactory'; import requestIsActiveSelectorFactory from 'selectors/factories/requestIsActiveSelectorFactory'; const toDeleteSelector = (state) => state.ui.reservation.toDelete; const resourcesSelector = (state) => state.data.resources; const reservationDeleteModalSelector = createSelector( modalIsOpenSelectorFactory(ModalTypes.DELETE_RESERVATION), requestIsActiveSelectorFactory(ActionTypes.API.RESERVATION_DELETE_REQUEST), resourcesSelector, toDeleteSelector, ( deleteReservationModalIsOpen, isDeletingReservations, resources, reservationsToDelete ) => { return { isDeletingReservations, reservationsToDelete, resources, show: deleteReservationModalIsOpen, }; } ); export default reservationDeleteModalSelector;
Fix typo in reservation delete modal selector
Fix typo in reservation delete modal selector
JavaScript
mit
fastmonkeys/respa-ui
--- +++ @@ -10,7 +10,7 @@ const reservationDeleteModalSelector = createSelector( modalIsOpenSelectorFactory(ModalTypes.DELETE_RESERVATION), - requestIsActiveSelectorFactory(ActionTypes.API.RESERVATIONS_DELETE_REQUEST), + requestIsActiveSelectorFactory(ActionTypes.API.RESERVATION_DELETE_REQUEST), resourcesSelector, toDeleteSelector, (
7003aada95cfe06d1a89843de4c09d1e4ceae3f4
test/models/user.js
test/models/user.js
'use strict' let imponderous = require('../../index') class User extends imponderous.Model { static get schema () { return { name: { index: true }, email: { unique: true, required: true, validator: 'email' }, dob: { type: Date } } } } module.exports = User
'use strict' let imponderous = require('../../index') class User extends imponderous.Model { static get schema () { return { name: { index: true }, email: { unique: true, required: true, validator: 'email' }, dob: { type: Date }, spam: { type: String } } } } module.exports = User
Make "spam" property on test User model a String.
Make "spam" property on test User model a String.
JavaScript
mit
benhutchins/imponderous
--- +++ @@ -15,6 +15,9 @@ }, dob: { type: Date + }, + spam: { + type: String } } }
982fb15759b79e9ec91799c0b841fdd65cf8ccc1
examples/cli.js
examples/cli.js
#!/usr/bin/node var convert = require('../'), localProj = require('local-proj'), fs = require('fs'), geojson = JSON.parse(fs.readFileSync(process.argv[2])), mtl = process.argv[3], mtllibs = process.argv.slice(4), options = { projection: localProj.find(geojson), mtllib: mtllibs }; if (mtl) { options.featureMaterial = function(f, cb) { process.nextTick(function() { cb(undefined, mtl); }); }; } convert.toObj(geojson, process.stdout, function(err) { if (err) { process.stderr.write(err + '\n'); } }, options);
#!/usr/bin/env node var convert = require('../'), localProj = require('local-proj'), fs = require('fs'), geojson = JSON.parse(fs.readFileSync(process.argv[2])), mtl = process.argv[3], mtllibs = process.argv.slice(4), options = { projection: localProj.find(geojson), mtllib: mtllibs }; if (mtl) { options.featureMaterial = function(f, cb) { process.nextTick(function() { cb(undefined, mtl); }); }; } convert.toObj(geojson, process.stdout, function(err) { if (err) { process.stderr.write('Error: ' + JSON.stringify(err, null, 2) + '\n'); } }, options);
Use env to find node
Use env to find node
JavaScript
isc
perliedman/geojson2obj
--- +++ @@ -1,4 +1,4 @@ -#!/usr/bin/node +#!/usr/bin/env node var convert = require('../'), localProj = require('local-proj'), @@ -19,6 +19,6 @@ convert.toObj(geojson, process.stdout, function(err) { if (err) { - process.stderr.write(err + '\n'); + process.stderr.write('Error: ' + JSON.stringify(err, null, 2) + '\n'); } }, options);
063bf15bfa562f3708f8608c92095010b12180d5
tests/chat_tests.js
tests/chat_tests.js
var helpers = require('./../helpers.js') module.exports = { 'Test Sending Message' : function (browser) { helpers.setupTest(browser) helpers.enterText('textarea._1eY_aSnr3MDhZqacV8fugZ', 'test', browser) browser.end(); } };
var helpers = require('./../helpers.js') module.exports = { 'Test Sending Message' : function (browser) { helpers.setupTest(browser) helpers.enterText('textarea._1eY_aSnr3MDhZqacV8fugZ', 'test', browser) browser.end(); }, 'Check Sent Message' : function (browser) { helpers.setupTest(browser) helpers.enterText('textarea._1eY_aSnr3MDhZqacV8fugZ', 'test', browser) browser .pause(1000) .assert.containsText("div.XnctIpXq756HWNS1GLwPT", "test") .end(); } };
Create test for checking sent message
Create test for checking sent message
JavaScript
mit
TheLocust3/Drift-Nightwatch
--- +++ @@ -5,5 +5,13 @@ helpers.setupTest(browser) helpers.enterText('textarea._1eY_aSnr3MDhZqacV8fugZ', 'test', browser) browser.end(); + }, + 'Check Sent Message' : function (browser) { + helpers.setupTest(browser) + helpers.enterText('textarea._1eY_aSnr3MDhZqacV8fugZ', 'test', browser) + browser + .pause(1000) + .assert.containsText("div.XnctIpXq756HWNS1GLwPT", "test") + .end(); } };
2445cb9f2d7c216c357943932074c5b23b99ead3
bin/eslint_d.js
bin/eslint_d.js
#!/usr/bin/env node 'use strict'; var net = require('net'); var fs = require('fs'); var eslint = require('eslint'); var engine = new eslint.CLIEngine(); var formatter = engine.getFormatter('compact'); var server = net.createServer({ allowHalfOpen: true }, function (con) { var data = ''; con.on('data', function (chunk) { data += chunk; }); con.on('end', function () { var report = engine.executeOnFiles([data]); con.write(formatter(report.results)); con.end(); }); }); var portFile = process.env.HOME + '/.eslint_d_port'; server.listen(function () { var port = server.address().port; fs.writeFileSync(portFile, String(port)); }); process.on('exit', function () { fs.unlinkSync(portFile); }); process.on('SIGINT', function () { process.exit(); });
#!/usr/bin/env node 'use strict'; var net = require('net'); var fs = require('fs'); var eslint = require('eslint'); var engine = new eslint.CLIEngine(); var formatter = engine.getFormatter('compact'); var server = net.createServer({ allowHalfOpen: true }, function (con) { var data = ''; con.on('data', function (chunk) { data += chunk; }); con.on('end', function () { var report = engine.executeOnFiles([data]); con.write(formatter(report.results)); con.end(); }); }); var portFile = process.env.HOME + '/.eslint_d_port'; server.listen(function () { var port = server.address().port; fs.writeFileSync(portFile, String(port)); }); process.on('exit', function () { fs.unlinkSync(portFile); }); process.on('SIGTERM', function () { process.exit(); }); process.on('SIGINT', function () { process.exit(); });
Remove port file on kill
Remove port file on kill
JavaScript
mit
mantoni/eslint_d.js,mantoni/eslint_d.js,clessg/eslint_d.js,ruanyl/eslint_d.js
--- +++ @@ -31,6 +31,9 @@ process.on('exit', function () { fs.unlinkSync(portFile); }); +process.on('SIGTERM', function () { + process.exit(); +}); process.on('SIGINT', function () { process.exit(); });
617ea4b1ac424daddd02f75727c149b016a26c16
client/tests/integration/components/f-account-test.js
client/tests/integration/components/f-account-test.js
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('f-account', 'Integration | Component | f account', { integration: true }); test('it renders', function(assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); this.render(hbs`{{f-account}}`); assert.equal(this.$().text().trim(), ''); // Template block usage: this.render(hbs` {{#f-account}} template block text {{/f-account}} `); assert.equal(this.$().text().trim(), 'template block text'); });
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('f-account', 'Integration | Component | f account', { integration: true }); const accountStub = Ember.Object.create({ name: 'name', email: 'email', phone: 'phone' }); test('it can be submitted', function(assert) { this.on('submit', () => { assert.ok(true); }) this.render(hbs`{{f-account submit=(action 'submit')}}`); this.$('button').click() }); test('it bound to account model', function(assert) { this.set('account', accountStub); this.on('submit', () => {}); this.render(hbs`{{f-account account=account submit=(action 'submit')}}`); this.$('input').val('new name'); this.$('input').change(); this.$('button').click(); assert.ok(this.get('account.name') == 'new name'); });
Add test suite for f-account component
Add test suite for f-account component
JavaScript
mit
yandex-shri-minsk-2016/yummy-time,yandex-shri-minsk-2016/yummy-time,yandex-shri-minsk-2016/yummy-time
--- +++ @@ -5,20 +5,27 @@ integration: true }); -test('it renders', function(assert) { - // Set any properties with this.set('myProperty', 'value'); - // Handle any actions with this.on('myAction', function(val) { ... }); +const accountStub = Ember.Object.create({ + name: 'name', + email: 'email', + phone: 'phone' +}); - this.render(hbs`{{f-account}}`); +test('it can be submitted', function(assert) { + this.on('submit', () => { assert.ok(true); }) - assert.equal(this.$().text().trim(), ''); + this.render(hbs`{{f-account submit=(action 'submit')}}`); + this.$('button').click() +}); - // Template block usage: - this.render(hbs` - {{#f-account}} - template block text - {{/f-account}} - `); +test('it bound to account model', function(assert) { + this.set('account', accountStub); + this.on('submit', () => {}); - assert.equal(this.$().text().trim(), 'template block text'); + this.render(hbs`{{f-account account=account submit=(action 'submit')}}`); + this.$('input').val('new name'); + this.$('input').change(); + this.$('button').click(); + + assert.ok(this.get('account.name') == 'new name'); });
955bd081bf37c5fd0aa336767766145197b0aeea
client/src/js/views/places-view.js
client/src/js/views/places-view.js
import View from '../base/view'; import Feed from '../models/feed'; import {capfirst} from '../utils'; import FeedView from './feed-view'; import itemTemplate from '../../templates/feed-place.ejs'; export default class PlacesView extends View { constructor({app, model}) { super({app, model}); this.feed = new Feed( '/places/', { categories: 'theatre', fields: 'images,title,id,address', expand: 'images', order_by: '-favorites_count', page_size: 24, }); this.feedView = new FeedView({app, itemTemplate, model: this.feed}); } render() { this.element.innerHTML = ''; this.feedView.render(); this.element.appendChild(this.feedView.element); this.update(); } unbind() { this.feedView.unbind(); super.unbind(); } onModelChange() { this.update(); } update() { this.updateFeedQuery(); this.updateAppState(); } updateFeedQuery() { this.feed.query.set('location', this.model.get('location')); } updateAppState() { const location = this.app.locations.get(this.model.get('location')); this.app.setTitle(`Театры – ${location.name}`); this.app.settings.set('location', location.slug); } }
import View from '../base/view'; import Feed from '../models/feed'; import {capfirst} from '../utils'; import FeedView from './feed-view'; import itemTemplate from '../../templates/feed-place.ejs'; export default class PlacesView extends View { constructor({app, model}) { super({app, model}); this.feed = new Feed( '/places/', { fields: 'images,title,id,address', categories: 'theatre,-cafe', expand: 'images', order_by: '-favorites_count', page_size: 24, }); this.feedView = new FeedView({app, itemTemplate, model: this.feed}); } render() { this.element.innerHTML = ''; this.feedView.render(); this.element.appendChild(this.feedView.element); this.update(); } unbind() { this.feedView.unbind(); super.unbind(); } onModelChange() { this.update(); } update() { this.updateFeedQuery(); this.updateAppState(); } updateFeedQuery() { this.feed.query.set('location', this.model.get('location')); } updateAppState() { const location = this.app.locations.get(this.model.get('location')); this.app.setTitle(`Театры – ${location.name}`); this.app.settings.set('location', location.slug); } }
Exclude cafes from place list
Exclude cafes from place list
JavaScript
mit
despawnerer/theatrics,despawnerer/theatrics,despawnerer/theatrics
--- +++ @@ -13,8 +13,8 @@ this.feed = new Feed( '/places/', { - categories: 'theatre', fields: 'images,title,id,address', + categories: 'theatre,-cafe', expand: 'images', order_by: '-favorites_count', page_size: 24,
197caf952390effc22aaa3c3d11acac23f46a677
api/lib/domain/models/Assessment.js
api/lib/domain/models/Assessment.js
const _ = require('lodash'); const TYPES_OF_ASSESSMENT_NEEDING_USER = ['PLACEMENT', 'CERTIFICATION']; const { ObjectValidationError } = require('../errors'); class Assessment { constructor(attributes) { Object.assign(this, attributes); } isCompleted() { return this.state === 'completed'; } getLastAssessmentResult() { if(this.assessmentResults) { return _(this.assessmentResults).sortBy(['createdAt']).last(); } return null; } getPixScore() { if(this.getLastAssessmentResult()) { return this.getLastAssessmentResult().pixScore; } return null; } getLevel() { if(this.getLastAssessmentResult()) { return this.getLastAssessmentResult().level; } return null; } setCompleted() { this.state = 'completed'; } validate() { if(TYPES_OF_ASSESSMENT_NEEDING_USER.includes(this.type) && typeof this.userId !== 'number') { return Promise.reject(new ObjectValidationError(`Assessment ${this.type} needs an User Id`)); } return Promise.resolve(); } } module.exports = Assessment;
const _ = require('lodash'); const TYPES_OF_ASSESSMENT_NEEDING_USER = ['PLACEMENT', 'CERTIFICATION']; const { ObjectValidationError } = require('../errors'); class Assessment { constructor(attributes) { Object.assign(this, attributes); } isCompleted() { return this.state === 'completed'; } getLastAssessmentResult() { if(this.assessmentResults) { return _(this.assessmentResults).sortBy(['createdAt']).last(); } return null; } getPixScore() { if(this.getLastAssessmentResult()) { return this.getLastAssessmentResult().pixScore; } return null; } getLevel() { if(this.getLastAssessmentResult()) { return this.getLastAssessmentResult().level; } return null; } setCompleted() { this.state = 'completed'; } validate() { console.log('Type of userId'); console.log(typeof this.userId); console.log(this.userId); if(TYPES_OF_ASSESSMENT_NEEDING_USER.includes(this.type) && typeof this.userId !== 'number') { return Promise.reject(new ObjectValidationError(`Assessment ${this.type} needs an User Id`)); } return Promise.resolve(); } } module.exports = Assessment;
Add console.log to logs in RA with staging db
Add console.log to logs in RA with staging db
JavaScript
agpl-3.0
sgmap/pix,sgmap/pix,sgmap/pix,sgmap/pix
--- +++ @@ -38,6 +38,9 @@ } validate() { + console.log('Type of userId'); + console.log(typeof this.userId); + console.log(this.userId); if(TYPES_OF_ASSESSMENT_NEEDING_USER.includes(this.type) && typeof this.userId !== 'number') { return Promise.reject(new ObjectValidationError(`Assessment ${this.type} needs an User Id`)); }
5ddfe279f1e6d097113c303333198a741bf5f0dd
ghost/admin/models/tag.js
ghost/admin/models/tag.js
/*global Ghost */ (function () { 'use strict'; Ghost.Collections.Tags = Ghost.ProgressCollection.extend({ url: Ghost.paths.apiRoot + '/tags/' }); }());
/*global Ghost */ (function () { 'use strict'; Ghost.Collections.Tags = Ghost.ProgressCollection.extend({ url: Ghost.paths.apiRoot + '/tags/', parse: function (resp) { return resp.tags; } }); }());
Tag API: Primary Document Format
Tag API: Primary Document Format Closes #2605 - Change tags browse() response to { tags: [...] } - Update client side collection to use nested tags document - Update test references to use response.tags
JavaScript
mit
TryGhost/Ghost,TryGhost/Ghost,TryGhost/Ghost
--- +++ @@ -3,6 +3,10 @@ 'use strict'; Ghost.Collections.Tags = Ghost.ProgressCollection.extend({ - url: Ghost.paths.apiRoot + '/tags/' + url: Ghost.paths.apiRoot + '/tags/', + + parse: function (resp) { + return resp.tags; + } }); }());
059c261d2b8bdce31133ac9875a59504d89c4f8f
app/routes/courses.server.routes.js
app/routes/courses.server.routes.js
'use strict'; module.exports = function(app) { var users = require('../../app/controllers/users.server.controller'); var courses = require('../../app/controllers/courses.server.controller'); var authorized = ['manager', 'admin']; // Courses Routes app.route('/courses') .get(users.requiresLogin, users.hasAuthorization(authorized), courses.list) .post(users.requiresLogin, users.hasAuthorization(authorized), courses.create); app.route('/list/myCourses') .get(users.requiresLogin, users.hasAuthorization(['teacher']), courses.listMyCourses); app.route('/courses/:courseId') .post(users.requiresLogin, users.hasAuthorization(authorized), courses.create) .get(users.requiresLogin, users.hasAuthorization(authorized), courses.read) .put(users.requiresLogin, users.hasAuthorization(authorized), courses.update) .delete(users.requiresLogin, users.hasAuthorization(authorized), courses.delete); // Finish by binding the Course middleware app.param('courseId', courses.courseByID); };
'use strict'; module.exports = function(app) { var users = require('../../app/controllers/users.server.controller'); var courses = require('../../app/controllers/courses.server.controller'); var authorized = ['manager', 'admin']; // Courses Routes app.route('/courses') .get(users.requiresLogin, users.hasAuthorization(authorized), courses.list) .post(users.requiresLogin, users.hasAuthorization(authorized), courses.create); app.route('/list/myCourses') .get(users.requiresLogin, users.hasAuthorization(['teacher']), courses.listMyCourses); app.route('/courses/:courseId') .post(users.requiresLogin, users.hasAuthorization(authorized), courses.create) .get(users.requiresLogin, users.hasAuthorization(['manager', 'admin', 'teacher']), courses.read) .put(users.requiresLogin, users.hasAuthorization(authorized), courses.update) .delete(users.requiresLogin, users.hasAuthorization(authorized), courses.delete); // Finish by binding the Course middleware app.param('courseId', courses.courseByID); };
Update permission to show course detail for teachers
Update permission to show course detail for teachers
JavaScript
mit
combefis/ECM,combefis/ECM,combefis/ECM
--- +++ @@ -15,7 +15,7 @@ app.route('/courses/:courseId') .post(users.requiresLogin, users.hasAuthorization(authorized), courses.create) - .get(users.requiresLogin, users.hasAuthorization(authorized), courses.read) + .get(users.requiresLogin, users.hasAuthorization(['manager', 'admin', 'teacher']), courses.read) .put(users.requiresLogin, users.hasAuthorization(authorized), courses.update) .delete(users.requiresLogin, users.hasAuthorization(authorized), courses.delete);
6594732058f60b90ebebbdd47070aa72c176b670
src/components/home/HomePage.js
src/components/home/HomePage.js
import React from 'react'; import GithubAPI from '../../api/githubAPI'; class HomePage extends React.Component { constructor(props, context) { super(props, context); this.state = { showResult: "l" }; this.invokeGitHubAPI = this.invokeGitHubAPI.bind(this); } invokeGitHubAPI(){ GithubAPI.testOctokat().then(testResult => { let parsedTestResult = testResult.updatedAt.toDateString(); console.log(testResult); console.log(parsedTestResult); this.setState({showResult: parsedTestResult}); }).catch(error => { throw(error); }); } render() { return ( <div> <h1>GitHub Status API GUI</h1> <h3>Open browser console to see JSON data returned from GitHub API</h3> <div className="row"> <div className="col-sm-3"> <button type="button" className="btn btn-primary" onClick={this.invokeGitHubAPI}>Test GitHub API Call</button> </div> </div> <div className="row"> <div className="col-sm-6"> <span>{this.state.showResult}</span> </div> </div> </div> ); } } export default HomePage;
import React from 'react'; import GithubAPI from '../../api/githubAPI'; class HomePage extends React.Component { constructor(props, context) { super(props, context); this.state = { showResult: "l" }; this.invokeGitHubAPI = this.invokeGitHubAPI.bind(this); } invokeGitHubAPI(){ GithubAPI.testOctokat().then(testResult => { let parsedTestResult = testResult.pushedAt.toTimeString(); console.log(testResult); console.log(parsedTestResult); this.setState({showResult: parsedTestResult}); }).catch(error => { throw(error); }); } render() { return ( <div> <h1>GitHub Status API GUI</h1> <h3>Open browser console to see JSON data returned from GitHub API</h3> <div className="row"> <div className="col-sm-3"> <button type="button" className="btn btn-primary" onClick={this.invokeGitHubAPI}>Test GitHub API Call</button> </div> </div> <div className="row"> <div className="col-sm-6"> <span>{this.state.showResult}</span> </div> </div> </div> ); } } export default HomePage;
Change display from updatedAt.toDateString to pushedAt.toTimeString
Change display from updatedAt.toDateString to pushedAt.toTimeString
JavaScript
mit
compumike08/GitHub_Status_API_GUI,compumike08/GitHub_Status_API_GUI
--- +++ @@ -15,7 +15,7 @@ invokeGitHubAPI(){ GithubAPI.testOctokat().then(testResult => { - let parsedTestResult = testResult.updatedAt.toDateString(); + let parsedTestResult = testResult.pushedAt.toTimeString(); console.log(testResult); console.log(parsedTestResult); this.setState({showResult: parsedTestResult});
f54d70fdd2c28ca99d94eb5e9cb10004418e7338
allcount.js
allcount.js
#!/usr/bin/env node var argv = require('minimist')(process.argv.slice(2)); var injection = require('./services/injection'); var _ = require('lodash'); var port = argv.port || process.env.PORT || 9080; var gitUrl = argv.git || process.env.GIT_URL; var dbUrl = argv.db || process.env.DB_URL; if (!gitUrl || !dbUrl) { console.log('Usage: allcountjs --git <Application Git URL> --db <Application MongoDB URL> -port [Application HTTP port]'); process.exit(0); } require('./allcount-server.js'); injection.bindFactory('port', port); injection.bindFactory('dbUrl', dbUrl); if (dbUrl.indexOf('postgres') !== -1) { injection.bindFactory('storageDriver', require('./services/sql-storage-driver')); injection.bindFactory('dbClient', 'pg'); } injection.bindFactory('gitRepoUrl', gitUrl); injection.installModulesFromPackageJson("package.json"); var server = injection.inject('allcountServerStartup'); server.startup(function (errors) { if (errors) { if (_.isObject(errors)) { throw new Error(errors); } else { throw new Error(errors.join('\n')); } } });
#!/usr/bin/env node var argv = require('minimist')(process.argv.slice(2)); var injection = require('./services/injection'); var _ = require('lodash'); var port = argv.port || process.env.PORT || 9080; var gitUrl = argv.git || process.env.GIT_URL; var dbUrl = argv.db || process.env.DB_URL; if (!gitUrl || !dbUrl) { console.log('Usage: allcountjs --git <Application Git URL> --db <Application MongoDB URL> -port [Application HTTP port]'); process.exit(0); } require('./allcount-server.js'); injection.bindFactory('port', port); injection.bindFactory('dbUrl', dbUrl); if (dbUrl.indexOf('postgres') !== -1) { injection.bindFactory('storageDriver', require('./services/sql-storage-driver')); injection.bindFactory('dbClient', 'pg'); } injection.bindFactory('gitRepoUrl', gitUrl); injection.installModulesFromPackageJson("package.json"); var server = injection.inject('allcountServerStartup'); server.startup(function (errors) { if (errors) { if (_.isArray(errors)) { throw new Error(errors.join('\n')); } else { throw errors; } } });
Fix exception when one error is thrown during startup
Fix exception when one error is thrown during startup
JavaScript
mit
allcount/allcountjs,chikh/allcountjs,allcount/allcountjs,chikh/allcountjs
--- +++ @@ -27,10 +27,10 @@ var server = injection.inject('allcountServerStartup'); server.startup(function (errors) { if (errors) { - if (_.isObject(errors)) { - throw new Error(errors); + if (_.isArray(errors)) { + throw new Error(errors.join('\n')); } else { - throw new Error(errors.join('\n')); + throw errors; } } });
f92e1de51f035f660d7c736e2869d3c9fa9a53f8
build/config.js
build/config.js
module.exports = { assetPath: '{{govukAssetPath}}', afterHeader: '{{$afterHeader}}{{/afterHeader}}', bodyClasses: '{{$bodyClasses}}{{/bodyClasses}}', bodyEnd: '{{$bodyEnd}}{{/bodyEnd}}', content: '{{$main}}{{/main}}', cookieMessage: '{{$cookieMessage}}{{/cookieMessage}}', footerSupportLinks: '{{$footerSupportLinks}}{{/footerSupportLinks}}', footerTop: '{{$footerTop}}{{/footerTop}}', head: '{{$head}}{{/head}}', headerClass: '{{$headerClass}}{{/headerClass}}', insideHeader: '{{$insideHeader}}{{/insideHeader}}', pageTitle: '{{$pageTitle}}{{/pageTitle}}', propositionHeader: '{{$propositionHeader}}{{/propositionHeader}}', skipLinkMessage: '{{$skipLinkMessage}}Skip to main content{{/skipLinkMessage}}', globalHeaderText: '{{$globalHeaderText}}GOV.UK{{/globalHeaderText}}', licenceMessage: '{{$licenceMessage}}<p>All content is available under the <a href="https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/" rel="license">Open Government Licence v3.0</a>, except where otherwise stated</p>{{/licenceMessage}}', crownCopyrightMessage: '{{$crownCopyrightMessage}}© Crown copyright{{/crownCopyrightMessage}}' };
module.exports = { htmlLang: '{{htmlLang}}', assetPath: '{{govukAssetPath}}', afterHeader: '{{$afterHeader}}{{/afterHeader}}', bodyClasses: '{{$bodyClasses}}{{/bodyClasses}}', bodyEnd: '{{$bodyEnd}}{{/bodyEnd}}', content: '{{$main}}{{/main}}', cookieMessage: '{{$cookieMessage}}{{/cookieMessage}}', footerSupportLinks: '{{$footerSupportLinks}}{{/footerSupportLinks}}', footerTop: '{{$footerTop}}{{/footerTop}}', head: '{{$head}}{{/head}}', headerClass: '{{$headerClass}}{{/headerClass}}', insideHeader: '{{$insideHeader}}{{/insideHeader}}', pageTitle: '{{$pageTitle}}{{/pageTitle}}', propositionHeader: '{{$propositionHeader}}{{/propositionHeader}}', skipLinkMessage: '{{$skipLinkMessage}}Skip to main content{{/skipLinkMessage}}', globalHeaderText: '{{$globalHeaderText}}GOV.UK{{/globalHeaderText}}', licenceMessage: '{{$licenceMessage}}<p>All content is available under the <a href="https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/" rel="license">Open Government Licence v3.0</a>, except where otherwise stated</p>{{/licenceMessage}}', crownCopyrightMessage: '{{$crownCopyrightMessage}}© Crown copyright{{/crownCopyrightMessage}}' };
Add local for htmlLang into template
Add local for htmlLang into template
JavaScript
mit
UKHomeOffice/govuk-template-compiler,UKHomeOffice/govuk-template-compiler
--- +++ @@ -1,4 +1,5 @@ module.exports = { + htmlLang: '{{htmlLang}}', assetPath: '{{govukAssetPath}}', afterHeader: '{{$afterHeader}}{{/afterHeader}}', bodyClasses: '{{$bodyClasses}}{{/bodyClasses}}',
25b6749b21e4f4f17b7abb239ce2921d279b0ad3
app/main.js
app/main.js
let http = require('http'); let url = require('url'); let fs = require('fs'); http.createServer(function (req, res) { let q = url.parse(req.url, true); let filename = "app/." + q.pathname; fs.readFile(filename, function (err, data) { if (err) { res.writeHead(404, {'Content-Type': 'text/html'}); return res.end("404 Not Found"); } let mimeType = 'text/html'; if (filename.endsWith(".css")) { mimeType = "text/css"; } else if (filename.endsWith(".js")) { mimeType = "application/javascript"; } res.writeHead(200, {'Content-Type': mimeType}); res.write(data); return res.end(); }); }).listen(8080);
let http = require('http'); let url = require('url'); let fs = require('fs'); http.createServer(function (req, res) { let q = url.parse(req.url, true); let filename = "app/." + q.pathname; fs.readFile(filename, function (err, data) { if (err) { res.writeHead(404, {'Content-Type': 'text/html'}); return res.end("404 Not Found"); } let mimeType = 'text/html'; if (filename.endsWith(".css")) { mimeType = "text/css"; } else if (filename.endsWith(".js")) { mimeType = "application/javascript"; } res.writeHead(200, {'Content-Type': mimeType}); res.write(data); return res.end(); }); }).listen(8080); console.log("Web server is running..."); console.log("URL to access the app: http://localhost:8080/app.html");
Add informational message when running server
Add informational message when running server
JavaScript
mit
adilek/jirtdan,adilek/jirtdan
--- +++ @@ -23,3 +23,6 @@ return res.end(); }); }).listen(8080); + +console.log("Web server is running..."); +console.log("URL to access the app: http://localhost:8080/app.html");
ec0c03368db293ede60115050bd201bfbd9566bc
rules/style.js
rules/style.js
module.exports = { rules: { // enforce spacing inside array brackets 'array-bracket-spacing': [ 'error', 'always', { objectsInArrays: false, arraysInArrays: false, }], // specify the maximum length of a line in your program // https://github.com/eslint/eslint/blob/master/docs/rules/max-len.md 'max-len': [ 'error', 80, 2, { ignoreUrls: true, ignoreComments: false, }], // allow/disallow an empty newline after var statement // https://github.com/eslint/eslint/blob/master/docs/rules/newline-after-var.md 'newline-after-var': [ 'error', 'always' ], // Require newline before return statement // https://github.com/eslint/eslint/tree/master/docs/rules/newline-before-return.md 'newline-before-return': 'error', // disallow multiple empty lines and only one newline at the end // https://github.com/eslint/eslint/blob/master/docs/rules/no-multiple-empty-lines.md 'no-multiple-empty-lines': [ 'error', { max: 2, maxBOF: 0, maxEOF: 1 }], // require or disallow use of semicolons instead of ASI // I use Babel, it takes care of this for me semi: [ 'error', 'never' ], // require or disallow spaces inside parentheses // disabled, because this rule is strange // TODO: write and implement a better rule 'space-in-parens': 'off', }, }
module.exports = { rules: { // enforce spacing inside array brackets 'array-bracket-spacing': [ 'error', 'always', { objectsInArrays: false, arraysInArrays: false, }], // allow/disallow an empty newline after var statement // https://github.com/eslint/eslint/blob/master/docs/rules/newline-after-var.md 'newline-after-var': [ 'error', 'always' ], // Require newline before return statement // https://github.com/eslint/eslint/tree/master/docs/rules/newline-before-return.md 'newline-before-return': 'error', // disallow multiple empty lines and only one newline at the end // https://github.com/eslint/eslint/blob/master/docs/rules/no-multiple-empty-lines.md 'no-multiple-empty-lines': [ 'error', { max: 2, maxBOF: 0, maxEOF: 1 }], // require or disallow use of semicolons instead of ASI // I use Babel, it takes care of this for me semi: [ 'error', 'never' ], // require or disallow spaces inside parentheses // disabled, because this rule is strange // TODO: write and implement a better rule 'space-in-parens': 'off', }, }
Remove `max-len` rule and fall back to AirBnb's (100 char)
Remove `max-len` rule and fall back to AirBnb's (100 char)
JavaScript
mit
wyze/eslint-config-wyze
--- +++ @@ -4,12 +4,6 @@ 'array-bracket-spacing': [ 'error', 'always', { objectsInArrays: false, arraysInArrays: false, - }], - // specify the maximum length of a line in your program - // https://github.com/eslint/eslint/blob/master/docs/rules/max-len.md - 'max-len': [ 'error', 80, 2, { - ignoreUrls: true, - ignoreComments: false, }], // allow/disallow an empty newline after var statement // https://github.com/eslint/eslint/blob/master/docs/rules/newline-after-var.md
b6abcef1e466aa09ab920cf56bfe806e71f727ad
src/javascript/binary/base/__tests__/storage.js
src/javascript/binary/base/__tests__/storage.js
var expect = require('chai').expect; var storage = require('../storage'); var utility = require('../utility'); describe('text.localize', function() { var text = new storage.Localizable({ key1: 'value', key2: 'value [_1]', }); it('should try to return a string from the localised texts', function() { expect(text.localize('key')).to.equal('key'); expect(text.localize('key1')).to.equal('value'); }); it('should only template when required', function() { expect(text.localize('key2')).to.equal('value [_1]'); // inject global template function global.template = utility.template; expect(text.localize('key2', [1])).to.equal('value 1'); delete global.template; }); });
var expect = require('chai').expect; var storage = require('../storage'); var utility = require('../utility'); describe('text.localize', function() { var text = new storage.Localizable({ key1: 'value', key2: 'value [_1]', 'You_can_view_your_[_1]trading_limits_here_': 'Ihre [_1] Handelslimits sind hier ersichtlich.', }); it('should try to return a string from the localised texts', function() { expect(text.localize('key')).to.equal('key'); expect(text.localize('key1')).to.equal('value'); expect(text.localize('You can view your [_1]trading limits here.')) .to.equal('Ihre [_1] Handelslimits sind hier ersichtlich.'); }); it('should only template when required', function() { expect(text.localize('key2')).to.equal('value [_1]'); // inject global template function global.template = utility.template; expect(text.localize('key2', [1])).to.equal('value 1'); expect(text.localize('You can view your [_1]trading limits here.', ['something'])) .to.equal('Ihre something Handelslimits sind hier ersichtlich.'); delete global.template; }); });
Test with data from real localisation
Test with data from real localisation
JavaScript
apache-2.0
negar-binary/binary-static,negar-binary/binary-static,negar-binary/binary-static,4p00rv/binary-static,fayland/binary-static,fayland/binary-static,teo-binary/binary-static,teo-binary/binary-static,4p00rv/binary-static,binary-com/binary-static,binary-static-deployed/binary-static,ashkanx/binary-static,kellybinary/binary-static,ashkanx/binary-static,raunakkathuria/binary-static,kellybinary/binary-static,teo-binary/binary-static,teo-binary/binary-static,binary-static-deployed/binary-static,binary-static-deployed/binary-static,ashkanx/binary-static,raunakkathuria/binary-static,kellybinary/binary-static,binary-com/binary-static,4p00rv/binary-static,raunakkathuria/binary-static,fayland/binary-static,fayland/binary-static,binary-com/binary-static
--- +++ @@ -6,10 +6,13 @@ var text = new storage.Localizable({ key1: 'value', key2: 'value [_1]', + 'You_can_view_your_[_1]trading_limits_here_': 'Ihre [_1] Handelslimits sind hier ersichtlich.', }); it('should try to return a string from the localised texts', function() { expect(text.localize('key')).to.equal('key'); expect(text.localize('key1')).to.equal('value'); + expect(text.localize('You can view your [_1]trading limits here.')) + .to.equal('Ihre [_1] Handelslimits sind hier ersichtlich.'); }); it('should only template when required', function() { @@ -17,6 +20,8 @@ // inject global template function global.template = utility.template; expect(text.localize('key2', [1])).to.equal('value 1'); + expect(text.localize('You can view your [_1]trading limits here.', ['something'])) + .to.equal('Ihre something Handelslimits sind hier ersichtlich.'); delete global.template; }); });