commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
70ab2782beb1065d4845604a7e2507895680fb7b
fix algo
src/objects/Room.js
src/objects/Room.js
import { SpriteWidth, SpriteHeight, SpriteRatioX, SpriteRatioY } from "../Constants.js"; import { Wall } from "../SpriteConstants"; class Room extends Phaser.Group { constructor(game, parent, name) { super(game, parent, name, false, false, Phaser.Physics.ARCADE); let sprite = this.create(100, 30, Wall); sprite.scale.setTo(SpriteRatioX, SpriteRatioY); } createLine(x1, y1, x2, y2) { const xBegin = Math.min(x1, x2); const xEnd = Math.max(x1, x2); const yBegin = Math.min(y1, y2); const yEnd = Math.max(y1, y2); const xStep = Math.trunc((x2-x1) / SpriteWidth); const yStep = Math.trunc((y2-y1) / SpriteHeight); if (xStep === 0) { this.createVerticalLine(x, yBegin, yEnd, yStep); } if (yStep === 0) { this.createHorizontalLine(xBegin, xEnd, y, xStep); } } createHorizontalLine(x, y1, y2, yStep) { for(let y = y1; y < y2; y += yStep) { this.create(x, y, Wall); } } createVerticalLine(x1, x2, y, xStep) { for(let x = x1; x < x2; x += xStep) { this.create(x, y, Wall); } } createSquare() { } } export default Room;
JavaScript
0.998381
@@ -269,105 +269,8 @@ E);%0A - let sprite = this.create(100, 30, Wall);%0A sprite.scale.setTo(SpriteRatioX, SpriteRatioY);%0A %7D%0A @@ -468,94 +468,41 @@ p = -Math.trunc((x2-x1) / SpriteWidth);%0A const yStep = Math.trunc((y2-y1) / SpriteHeight +(x2-x1);%0A const yStep = (y2-y1 );%0A%0A @@ -516,32 +516,48 @@ (xStep === 0) %7B%0A + //x1 = x2%0A this.creat @@ -571,16 +571,17 @@ alLine(x +1 , yBegin @@ -586,23 +586,16 @@ in, yEnd -, yStep );%0A %7D @@ -615,24 +615,40 @@ ep === 0) %7B%0A + //y1 = y2%0A this.c @@ -682,23 +682,17 @@ xEnd, y -, xStep +1 );%0A %7D @@ -702,32 +702,30 @@ %7D%0A%0A create -Horizont +Vertic alLine(x, y1 @@ -732,15 +732,8 @@ , y2 -, yStep ) %7B%0A @@ -765,21 +765,28 @@ 2; y += -yStep +SpriteHeight ) %7B%0A @@ -794,35 +794,35 @@ this.create -(x, y, Wall +Sprite(x, y );%0A %7D%0A %7D @@ -823,38 +823,40 @@ %7D%0A %7D%0A%0A create -Vertic +Horizont alLine(x1, x2, y @@ -859,15 +859,8 @@ 2, y -, xStep ) %7B%0A @@ -896,53 +896,180 @@ += -xStep) %7B%0A this.create(x, y, Wall);%0A %7D +SpriteWidth) %7B%0A this.createSprite(x, y);%0A %7D%0A %7D%0A%0A createSprite(x,y) %7B%0A let sprite = this.create(x, y, Wall);%0A sprite.scale.setTo(SpriteRatioX, SpriteRatioY); %0A %7D
e6ec50e8841f259ae08b2c3a1a415a95f9e4f504
add space between terms for readability
static-text/research-static-text.js
static-text/research-static-text.js
module.exports = { "research.brazilian_data_set_link": "Dataset on Brazilian Participatory Budgeting: 1989 to 2012", "research.data_repository.header": "Data Repository", "research.data_repository.p1": "A great deal of research on democratic innovations is not publicly available. This includes large datasets, graduate and postgraduate dissertations, and practitioner evaluations and reports. We aim to find a home for such research in an accessible data repository.", "research.header": "Research", "research.methodology.header": "Methodology", "research.methodology.p1": "The strategy is simple: crowdsource data on democratic innovations from around the world and then aggregate this into a public database that continually updates with new contributions. All of Participedia’s content and data is open source.", "research.methodology.p2": "For an in-depth explanation of the history, aspirations, theory and analytical approach of Participedia, see [needs-link]The Participedia Project: An Introduction [/needs-link], by the two founders of Participedia, Archon Fung and Mark E. Warren.", "research.surveys.header": "Surveys", "research.surveys.p1": "Surveys are supplementary to Participedia’s current data and narrative descriptions and are intended to gain further insight on the outcomes and effects of cases.", "research.surveys.p2": "The participant survey will capture the experience of participants directly involved in a participatory process. It could be delivered by organizers at the location of a particular process, or participants could be asked to complete the survey after the event.", "research.surveys.p3": "The observer survey will capture views pertaining to the broader impact of a particular case. ‘Observers’ include practitioners, participants or researchers with particular knowledge of that case.", "research.surveys.p4": "Participedia's surveys are undergoing testing, and will be available for download soon.", "research.tagline": "Participedia is guided by the research question: What kinds of participatory processes work best, for what purposes, and under what conditions?", };
JavaScript
0.041028
@@ -112,16 +112,17 @@ 2012%22,%0A +%0A %22resea @@ -165,24 +165,25 @@ epository%22,%0A +%0A %22research. @@ -467,24 +467,25 @@ pository.%22,%0A +%0A %22research. @@ -505,16 +505,17 @@ earch%22,%0A +%0A %22resea @@ -554,16 +554,17 @@ ology%22,%0A +%0A %22resea @@ -823,24 +823,25 @@ n source.%22,%0A +%0A %22research. @@ -1103,24 +1103,25 @@ . Warren.%22,%0A +%0A %22research. @@ -1148,16 +1148,17 @@ rveys%22,%0A +%0A %22resea @@ -1336,24 +1336,25 @@ of cases.%22,%0A +%0A %22research. @@ -1626,24 +1626,25 @@ he event.%22,%0A +%0A %22research. @@ -1852,24 +1852,25 @@ hat case.%22,%0A +%0A %22research. @@ -1973,16 +1973,17 @@ soon.%22,%0A +%0A %22resea
5ba3d8eaefcc2281c8a400b1113413301917b526
Remove unnecessary watch on less task.
build/configs/watch.js
build/configs/watch.js
module.exports = function (grunt) { var src = 'src/{*,**/*}.{js,less}'; var test = 'test/{*,**/*}.{js,less}'; return { dist: { files: [src], tasks: ['less:dist', 'shell:dist', 'uglify:dist'] }, test: { files: [src, test], tasks: ['shell:test'] } }; };
JavaScript
0
@@ -169,21 +169,8 @@ s: %5B -'less:dist', 'she
2cd537015cf112ab3b206e24dd8d30176075ae2a
use platform variable in the app name
bin/package.js
bin/package.js
#!/usr/bin/env node var path = require('path'); var packager = require('electron-packager'); var rimraf = require('rimraf'); var shell = require('shelljs'); var packageJson = require('./../package.json'); var productName = packageJson.productName; var appVersion = packageJson.version; var electronVersion = packageJson.devDependencies['electron-prebuilt']; var outputFolder = 'package'; var platform = 'darwin'; var arch = 'x64'; var icon = 'resources/icon.icns'; if (process.argv[2] === '--win32') { platform = 'win32'; arch = 'ia32'; icon = 'resources/icon.ico'; } var options = { dir: '.', name: productName, overwrite: true, out: outputFolder, platform: platform, arch: arch, version: electronVersion, prune: true, icon: icon, ignore: [ '/src($|/)', '/bin($|/)', '/style($|/)' ] }; rimraf(path.join('.', outputFolder), function(removeErr) { if(removeErr) { console.log('Failed to remove files'); console.log(removeErr); process.exit(1); } packager(options, function(error, appPaths) { var appPath = appPaths[0]; if(error) { console.log('electron-packager failed with the following error:'); console.log(error); process.exit(1); } else { console.log('electron-packager finished packaging ' + productName); console.log('App path: ' + appPath); console.log('Platform: ' + platform); console.log('Arch: ' + arch); if(platform === 'darwin') { createOsxPackage(appPath); } else if(platform === 'win32') { createWindowsPackage(); } } }); }); function createOsxPackage(appPath) { process.chdir(path.join('.', appPath)); var zipName = productName + '-v' + appVersion + '-osx.zip'; var appName = productName + '.app'; var dittoCommand = 'ditto -c -k --sequesterRsrc --keepParent ' + appName + ' ' + zipName; shell.exec(dittoCommand, function(code) { console.log('Ditto command exit code:', code); }); } function createWindowsPackage() { process.chdir(path.join('.', outputFolder)); var folderName = productName + '-' + platform + '-' + arch; var appName = productName + '-v' + appVersion + '-win32'; var zipName = appName + '.zip'; shell.exec('rename ' + folderName + ' ' + appName, function(renameExitCode) { console.log('Rename exit code:', renameExitCode); // assumes 7z.exe is in PATH shell.exec('7z a ' + zipName + ' ' + appName + ' > nul', function(zipExitCode) { console.log('7zip exit code: ' + zipExitCode); }); }); }
JavaScript
0.000001
@@ -2168,22 +2168,28 @@ ion + '- -win32' +' + platform ;%0A var
3ad9b386b872413462be1bcc04a7031a098b9a3f
Update Premium page to point to the buttons
src/Interface/Premium/LoginPanel.js
src/Interface/Premium/LoginPanel.js
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { CSSTransitionGroup } from 'react-transition-group'; import Textfit from 'react-textfit'; import PatreonIcon from 'Interface/Icons/PatreonTiny'; import GitHubMarkIcon from 'Interface/Icons/GitHubMarkLarge'; import LogoutIcon from 'Interface/Icons/Logout'; import CyclingVideo from 'Interface/common/CyclingVideo'; import { logout } from 'Interface/actions/user'; import { getUser } from 'Interface/selectors/user'; const INITIAL_BACKGROUNDS = [ '7TqE3VIAU2odkmneHU', // human salute https://giphy.com/gifs/warcraft-video-games-7TqE3VIAU2odkmneHU '5kFzxK6ENfjrcoMgt1', // orc salute https://giphy.com/gifs/warcraft-video-games-5kFzxK6ENfjrcoMgt1 'PoCoePEEB1EC6buvFU', // blood elf salute https://giphy.com/gifs/warcraft-video-games-PoCoePEEB1EC6buvFU '8cv2DoGyUClMuCKalT', // human bow https://giphy.com/gifs/warcraft-video-games-8cv2DoGyUClMuCKalT 'fUZW0LIJhtbDnBtqkX', // orc bow https://giphy.com/gifs/warcraft-video-games-fUZW0LIJhtbDnBtqkX '2erqKiXvYpXeGH9XJ5', // gnome bow https://giphy.com/gifs/warcraft-video-games-2erqKiXvYpXeGH9XJ5 ].map(code => `https://media.giphy.com/media/${code}/giphy.mp4`); // const LOGIN_SUCCESSFUL_BACKGROUNDS = [ // '1AdZe53o36pL2ifJrW', // approve https://giphy.com/gifs/warcraft-video-games-1AdZe53o36pL2ifJrW // '12gdy23jcbqdvqID9D', // human cheer https://giphy.com/gifs/warcraft-video-games-12gdy23jcbqdvqID9D // '2fRB16C8fbWsHTogzJ', // orc cheer https://giphy.com/gifs/warcraft-video-games-2fRB16C8fbWsHTogzJ // '55kiNDmHdIkd2NJ9L1', // ...gnome cheer https://giphy.com/gifs/warcraft-video-games-55kiNDmHdIkd2NJ9L1 // 'cQ29kUD2CstrP0Cyyz', // blood elf dh cheer https://giphy.com/gifs/warcraft-video-games-cQ29kUD2CstrP0Cyyz // ]; // const LOGIN_UNSUCCESSFUL_BACKGROUNDS = [ // '4N1IhWlgeurYEqBpbd', // no https://giphy.com/gifs/warcraft-video-games-4N1IhWlgeurYEqBpbd // 'fdGbKBJRylAQ3Gj1f8', // please https://giphy.com/gifs/warcraft-video-games-fdGbKBJRylAQ3Gj1f8 // '1zgvoYwvgm7LnHpYp4', // blood elf dh no https://giphy.com/gifs/warcraft-video-games-1zgvoYwvgm7LnHpYp4 // '8h0dtWORphvPgH4O20', // orc no https://giphy.com/gifs/warcraft-video-games-8h0dtWORphvPgH4O20 // '4a4w6CzSj1t2Hl6gYy', // orc please https://giphy.com/gifs/warcraft-video-games-4a4w6CzSj1t2Hl6gYy // ]; export class LoginPanel extends React.PureComponent { static propTypes = { user: PropTypes.shape({ name: PropTypes.string, avatar: PropTypes.string, premium: PropTypes.bool, }), logout: PropTypes.func, }; constructor() { super(); this.handleClickLogout = this.handleClickLogout.bind(this); } handleClickLogout(e) { e.preventDefault(); this.props.logout(); } renderLoggedIn() { const { user } = this.props; const hasPremium = user.premium; const platform = user.github && user.github.premium ? 'github' : 'patreon'; return ( <div className={`logged-in ${platform}`}> <div> <div className="logo"> {platform === 'github' && <GitHubMarkIcon style={{ marginTop: 0 }} />} {platform === 'patreon' && <PatreonIcon style={{ marginTop: 0 }} />} </div> <div className="text"> <h1> <Textfit mode="single"> Hello {user.name}. </Textfit> </h1> {hasPremium ? ( <div className="description"> Super thank you for your support! We hope you'll enjoy WoWAnalyzer Premium. </div> ) : ( <div className="description"> You haven't unlocked Premium yet. See the panel to the right for more info. </div> )} <div className="logout"> <a href="/logout" onClick={this.handleClickLogout}> <LogoutIcon /> Logout </a> </div> </div> </div> </div> ); } render() { const { user } = this.props; return ( <div className="panel" style={{ overflow: 'hidden' }}> <div className="panel-body" style={{ padding: '0 15px', position: 'relative' }}> <CSSTransitionGroup transitionName="logged-in" transitionEnterTimeout={1000} transitionLeaveTimeout={1000} > {user && this.renderLoggedIn()} </CSSTransitionGroup> <div className="row image-background" style={{ position: 'relative', paddingTop: 300, paddingBottom: 15 }} > <div style={{ position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, pointerEvents: 'none', overflow: 'hidden' }}> <CyclingVideo videos={INITIAL_BACKGROUNDS} style={{ objectFit: 'cover', width: '100%', height: '100%' }} /> </div> <div className="col-md-12"> <h1>Premium sign in</h1> <div className="description"> Sign in with your Patreon or GitHub account. </div> </div> </div> <div className="row"> <div className="col-lg-6" style={{ padding: 0 }}> <a href={`${process.env.REACT_APP_SERVER_BASE}login/patreon`} className="btn btn-block patreon-login" > <PatreonIcon /> Patreon </a> </div> <div className="col-lg-6" style={{ padding: 0 }}> <a href={`${process.env.REACT_APP_SERVER_BASE}login/github`} className="btn btn-block github-login" > <GitHubMarkIcon /> GitHub </a> </div> </div> </div> </div> ); } } const mapStateToProps = state => ({ user: getUser(state), }); export default connect(mapStateToProps, { logout, })(LoginPanel);
JavaScript
0
@@ -5129,16 +5129,40 @@ account + using the buttons below .%0A
470f06de4c42fad23b9a30084095f6cc98a1eafe
Change order of middlewares. #154
src/redux/create.js
src/redux/create.js
import { createStore, combineReducers, applyMiddleware, compose } from 'redux' import createMiddleware from './clientMiddleware' import thunk from 'redux-thunk' export default function createApiClientStore(client, initialState) { const middleware = createMiddleware(client) let finalCreateStore if (__DEVELOPMENT__ && __CLIENT__ && __DEVTOOLS__) { const { devTools, persistState } = require('redux-devtools') finalCreateStore = compose( applyMiddleware(middleware), applyMiddleware(thunk), devTools(), persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)), )(createStore) } else { finalCreateStore = compose( applyMiddleware(middleware), applyMiddleware(thunk) )(createStore) } const rootReducer = require('../ducks/reducer') const store = finalCreateStore(rootReducer, initialState) store.client = client if (__DEVELOPMENT__ && module.hot) { module.hot.accept('../ducks/reducer', () => { store.replaceReducer(require('../ducks/reducer')) }) } return store }
JavaScript
0.000001
@@ -463,34 +463,29 @@ yMiddleware( -middleware +thunk ),%0A app @@ -489,37 +489,42 @@ applyMiddleware( -thunk +middleware ),%0A devTool @@ -687,34 +687,29 @@ yMiddleware( -middleware +thunk ),%0A app @@ -721,21 +721,26 @@ dleware( -thunk +middleware )%0A )(
b1e5d1145c23a44404221a70111698478466ac56
add "documentation" instead of empty comments
app/assets/javascripts/fae/mobilemenu.js
app/assets/javascripts/fae/mobilemenu.js
var MobileMenu = { mobile_container: "#main_nav", trigger_selector: "#main_nav-menu_button", header_selector: ".main_nav-header", sub_header_selector: ".main_nav-sub-header-mobile", sub_header_section_selector: ".main_nav-sub-nav", toggle_class: "js-menu-active", toggle_level_class: "js-menu-level-active", drawer_closed: true, default_screen_width: 1024, init: function(){ this.open_drawer(); this.header_clicks(); this.resizer(); this.sub_header_clicks(); this.link_clicks(); //get a reference to the trigger this.$trigger = $(this.trigger_selector); }, open_drawer: function() { var that = this; $(this.trigger_selector).click(function(e){ e.preventDefault(); var $html = $("html"); // check to see if the html has the toggle class...which means it's opened if ($html.hasClass(that.toggle_class)) { that.close_all(); } else { $("html").addClass(that.toggle_class); } }); }, close_all: function() { // remove the HTML class which closes the first level $("html").removeClass(this.toggle_class); // remove the class if a second level item is opened $(this.header_selector).closest("li").removeClass(this.toggle_level_class); }, link_clicks: function() { var that = this; $(this.mobile_container).find("a").click(function(){ that.close_all(); }); }, header_clicks: function() { var that = this; // close the menus if clicked on an actual link $(this.header_selector).click(function(e){ if (!$(this).hasClass("js-menu-header-active") && $(window).width() < that.default_screen_width) { e.preventDefault(); var $parent = $(this).closest("li"); var link_url = $(this).data("link"); // $parent.addClass(that.toggle_level_class); if ($parent.find(that.sub_header_section_selector).length === 0 && typeof link_url !== "undefined") { location.href = link_url; } } }); }, sub_header_clicks: function() { var that = this; $(this.sub_header_selector).click(function(e){ e.preventDefault(); $("." + that.toggle_level_class).removeClass(that.toggle_level_class); }); }, resizer: function() { var that = this; // use smart resizer so it doesn't happen at every pixel $(window).smartresize(function(){ if ($(window).width() >= that.default_screen_width){ that.close_all(); } }); }, }; $(function() { MobileMenu.init(); });
JavaScript
0.000001
@@ -1798,16 +1798,35 @@ // +Add JS toggle class %0A @@ -1866,24 +1866,102 @@ el_class);%0A%0A + // If the element does not have sublinks, then go to the desired page%0A if (
0b36c6109e9a96403d6c779c56c1b1482df0a48f
Add reaction while fetching logs
app/assets/javascripts/vue/fluent_log.js
app/assets/javascripts/vue/fluent_log.js
(function(){ "use strict"; $(function(){ if($('#fluent-log').length === 0) return; new Vue({ el: "#fluent-log", paramAttributes: ["logUrl"], data: { "autoFetch": false, "logs": [], "limit": 30 }, created: function(){ this.fetchLogs(); var self = this; var timer; this.$watch("autoFetch", function(newValue){ if(newValue === true) { timer = setInterval(function(){ self.fetchLogs(); var $log = $(".log", self.$el); $log.scrollTop($log[0].scrollHeight); }, 1000); } else { clearInterval(timer); } }); }, methods: { fetchLogs: function() { var self = this; new Promise(function(resolve, reject) { $.getJSON(self.logUrl + "?limit=" + self.limit, resolve).fail(reject); }).then(function(logs){ self.logs = logs; }); }, } }); }); })();
JavaScript
0.000001
@@ -241,16 +241,45 @@ mit%22: 30 +,%0A %22processing%22: false %0A %7D @@ -794,24 +794,96 @@ unction() %7B%0A + if(this.processing) return;%0A this.processing = true;%0A va @@ -1094,16 +1094,152 @@ = logs;%0A + setTimeout(function()%7B%0A self.processing = false;%0A %7D, 256); // delay to reduce flicking loading icon%0A
e3f1002f908b94e55650580a9577408f879d4b8e
fix linting
bin/webpack.js
bin/webpack.js
#!/usr/bin/env node let webpackCliInstalled = false; try { require.resolve("webpack-cli"); webpackCliInstalled = true; } catch(e) { webpackCliInstalled = false; } if(webpackCliInstalled) { require("webpack-cli"); // eslint-disable-line node/no-unpublished-require } else { console.error("The CLI moved into a separate package: webpack-cli."); console.error("Please install 'webpack-cli' in addition to webpack itself to use the CLI."); console.error("-> When using npm: npm install webpack-cli -D"); console.error("-> When using yarn: yarn add webpack-cli -D"); process.exitCode = 1; }
JavaScript
0.000003
@@ -211,17 +211,17 @@ k-cli%22); - +%09 // eslin @@ -234,16 +234,69 @@ ble-line + node/no-missing-require, node/no-extraneous-require, node/no
fb6fa0c6312d8aeb9cc00f7dde8fb7c372f25a5f
Reorder properties for readability [skip ci]
app/components/keyboard-select-picker.js
app/components/keyboard-select-picker.js
import Ember from 'ember'; import SelectPicker from './select-picker'; import KeyboardShortcutsMixin from 'ember-keyboard-shortcuts/mixins/component'; var KeyboardSelectPickerComponent = SelectPicker.extend( KeyboardShortcutsMixin, { layoutName: 'components/select-picker', nativeMobile: true, activeCursor: null, classNames: ['select-picker', 'keyboard-select-picker'], activeIndex: Ember.computed( 'activeCursor', 'contentList.length', function() { var cursor = this.get('activeCursor'); if (Ember.isNone(cursor)) { return null; } var len = this.get('contentList.length'); return (cursor % len + len) % len; } ), activeItem: Ember.computed( 'activeIndex', 'contentList.[]', function() { return this.get('contentList').objectAt(this.get('activeIndex')); } ), keyboardShortcuts: { 'enter': function() { this.send('selectItem', this.get('activeItem')); return false; }, 'up': 'activePrev', 'down': 'activeNext', 'shift+tab': 'activePrev', 'tab': 'activeNext', 'esc': 'closeDropdown' }, groupedContentList: Ember.computed( 'groupedContentListWithoutActive', 'activeIndex', function() { var activeIndex = this.get('activeIndex'); var result = Ember.A(this.get('groupedContentListWithoutActive')); result.forEach(function(item, index) { item.set('active', index === activeIndex); }); return result; } ), actions: { activeNext: function() { if (Ember.isNone(this.get('activeCursor'))) { this.set('activeCursor', 0); } else { this.incrementProperty('activeCursor'); } }, activePrev: function() { if (Ember.isNone(this.get('activeCursor'))) { this.set('activeCursor', -1); } else { this.decrementProperty('activeCursor'); } } } }); export default KeyboardSelectPickerComponent;
JavaScript
0
@@ -380,16 +380,386 @@ ker'%5D,%0A%0A + groupedContentList: Ember.computed(%0A 'groupedContentListWithoutActive', 'activeIndex',%0A function() %7B%0A var activeIndex = this.get('activeIndex');%0A var result = Ember.A(this.get('groupedContentListWithoutActive'));%0A result.forEach(function(item, index) %7B%0A item.set('active', index === activeIndex);%0A %7D);%0A return result;%0A %7D%0A ),%0A%0A active @@ -1491,378 +1491,8 @@ %7D,%0A%0A - groupedContentList: Ember.computed(%0A 'groupedContentListWithoutActive', 'activeIndex',%0A function() %7B%0A var activeIndex = this.get('activeIndex');%0A var result = Ember.A(this.get('groupedContentListWithoutActive'));%0A result.forEach(function(item, index) %7B%0A item.set('active', index === activeIndex);%0A %7D);%0A return result;%0A %7D%0A ),%0A%0A ac
c779d856751813c185f4cde518d90d4423828c86
use username when no display name available
app/controllers/userController.client.js
app/controllers/userController.client.js
'use strict'; (function () { var profileId = document.querySelector('#profile-id') || null; var profileUsername = document.querySelector('#profile-username') || null; var profileRepos = document.querySelector('#profile-repos') || null; var displayName = document.querySelector('#display-name'); var apiUrl = appUrl + '/api/:id'; function updateHtmlElement (data, element, userProperty) { element.innerHTML = data[userProperty]; } ajaxFunctions.ready(ajaxFunctions.ajaxRequest('GET', apiUrl, function (data) { var userObject = JSON.parse(data); updateHtmlElement(userObject, displayName, 'displayName'); if (profileId !== null) { updateHtmlElement(userObject, profileId, 'id'); } if (profileUsername !== null) { updateHtmlElement(userObject, profileUsername, 'username'); } if (profileRepos !== null) { updateHtmlElement(userObject, profileRepos, 'publicRepos'); } })); })();
JavaScript
0.000002
@@ -574,24 +574,72 @@ rse(data);%0A%0A + if (userObject.displayName !== null) %7B%0A update @@ -690,16 +690,104 @@ yName'); +%0A %7D else %7B%0A updateHtmlElement(userObject, displayName, 'username');%0A %7D %0A%0A
ba28ecb2247a0af16afe7aae8be94c0fb257ad9c
remove logs
src/schema/index.js
src/schema/index.js
import Joi from 'joi' const contactSchema = Joi.object().keys({ name: Joi.string(), email: Joi.string().email() }) const alarmSchema = Joi.object().keys({ action: Joi.string().regex(/audio|display|email/).required(), trigger: Joi.array().required(), description: Joi.string(), duration: Joi.array(), repeat: Joi.number(), attach: Joi.string().uri(), summary: Joi.string(), attendee: contactSchema, 'x-prop': Joi.any(), 'iana-prop': Joi.any() }) const schema = Joi.object().keys({ title: Joi.string(), productId: Joi.string(), uid: Joi.string().required(), start: Joi.array().required(), startType: Joi.string(), // TODO test end: Joi.string(), // TODO test description: Joi.string(), url: Joi.string().uri(), geolocation: Joi.object().keys({ lat: Joi.number(), lon: Joi.number() }), location: Joi.string(), status: Joi.string().regex(/tentative|cancelled|confirmed/), categories: Joi.array().items(Joi.string()), organizer: contactSchema, attendees: Joi.array().items(contactSchema), alarms: Joi.array().items(alarmSchema) }) export default function validateEvent(candidate) { const { error, value } = Joi.validate(candidate, schema) // console.log(error) // console.log(value) return { error, value } }
JavaScript
0.000001
@@ -1191,56 +1191,8 @@ ma)%0A - // console.log(error)%0A // console.log(value)%0A re
aa36194eb06daf5a2e62108993ed90fb836de4b3
Fix broken test
packages/ember-runtime/tests/suites/array/lastIndexOf.js
packages/ember-runtime/tests/suites/array/lastIndexOf.js
import { SuiteModuleBuilder } from '../suite'; const suite = SuiteModuleBuilder.create(); suite.module('lastIndexOf'); suite.test('should return index of object\'s last occurrence', function() { let expected = this.newFixture(3); let obj = this.newObject(expected); let len = 3; for (let idx = 0; idx < len; idx++) { equal(obj.lastIndexOf(expected[idx]), idx, `obj.lastIndexOf(${expected[idx]}) should match idx`); } }); suite.test('should return index of object\'s last occurrence even startAt search location is equal to length', function() { let expected = this.newFixture(3); let obj = this.newObject(expected); let len = 3; for (let idx = 0; idx < len; idx++) { equal(obj.lastIndexOf(expected[idx], len), idx, `obj.lastIndexOfs(${expected[idx]}) should match idx`); } }); suite.test('should return index of object\'s last occurrence even startAt search location is greater than length', function() { let expected = this.newFixture(3); let obj = this.newObject(expected); let len = 3; for (let idx = 0; idx < len; idx++) { equal(obj.lastIndexOf(expected[idx], len + 1), idx, `obj.lastIndexOf(${expected[idx]}) should match idx`); } }); suite.test('should return -1 when no match is found', function() { let obj = this.newObject(this.newFixture(3)); let foo = {}; equal(obj.lastIndexOf(foo), -1, 'obj.lastIndexOf(foo) should be -1'); }); suite.test('should return -1 when no match is found even startAt search location is equal to length', function() { let obj = this.newObject(this.newFixture(3)); let foo = {}; equal(obj.lastIndexOf(foo, obj.length), -1, 'obj.lastIndexOf(foo) should be -1'); }); suite.test('should return -1 when no match is found even startAt search location is greater than length', function() { let obj = this.newObject(this.newFixture(3)); let foo = {}; equal(obj.lastIndexOf(foo, obj.length + 1), -1, 'obj.lastIndexOf(foo) should be -1'); }); export default suite;
JavaScript
0
@@ -1,8 +1,43 @@ +import %7B get %7D from 'ember-metal';%0A import %7B @@ -1667,26 +1667,34 @@ Of(foo, -obj. +get(obj, ' length +') ), -1, ' @@ -1952,18 +1952,26 @@ oo, -obj. +get(obj, ' length +') + 1
4144d94c5ea9197c9221106c4a0377d4c37a548a
Add papix
src/scripts/dark.js
src/scripts/dark.js
// Description: // misc // // Commands: // hubot poem - オサレポエム // hubot 炎上 <text> <text> - ババーン // なんだと・・・ // hubot goma - やればわかる // hubot isao - やればわかる // "use strict" const uuid = require("node-uuid"); const json = require('../../settings/poems.json') const Levenshtein = require("levenshtein"); const gomas = [ () => `http://yamiga.waka.ru.com/images/goma/01.jpg?cb=${uuid.v4()}`, () => `http://yamiga.waka.ru.com/images/goma/02.jpg?cb=${uuid.v4()}`, () => `http://yamiga.waka.ru.com/images/goma/03.jpg?cb=${uuid.v4()}`, () => `http://yamiga.waka.ru.com/images/goma/04.jpg?cb=${uuid.v4()}`, () => `http://yamiga.waka.ru.com/images/goma/05.jpg?cb=${uuid.v4()}`, () => "```\n   CH \n   /\ \n  / \\ \nHC/   \\CH \n ||C6H6  | \n || ´д`| \nHC\   //CH \n  \ // \n   \/ \n   CH\n```" ]; const isaos = [ () => `https://36.media.tumblr.com/3df68abdd9a1eb7a0fbda4dacb9930af/tumblr_ns5chdb0Vm1un4u6lo1_1280.jpg?cb=${uuid.v4()}`, () => `https://camo.githubusercontent.com/4a011f97909b89a26822ee21e921eb7012e9df18/68747470733a2f2f34302e6d656469612e74756d626c722e636f6d2f31346231333736396364336238303235623163653338626238626238626261352f74756d626c725f6e75313538697269536c31756e3475366c6f315f313238302e6a7067?cb=${uuid.v4()}` ]; module.exports = (robot) => { robot.respond(/poem$/i, (res) => { res.send(res.random(json.poem)) }) robot.hear(/なん(\.|。|・)*だと(\.|。|・)*$/i, (res) => { res.send(`http://yamiga.waka.ru.com/images/nandato.png?cb=${uuid.v4()}`); }) robot.respond(/炎上 (.+) (.+)/i, (res) => { const text1 = encodeURIComponent(res.match[1]) const text2 = encodeURIComponent(res.match[2]) res.send(`https://enjo-generator.herokuapp.com/api/create-enjo?text1=${text1}&text2=${text2}`); }) robot.respond(/距離 (.+) (.+)/i, (res) => { const l = new Levenshtein(res.match[1],res.match[2]); res.send(`距離: ${l.distance}`); }); robot.respond(/goma$/i, (res) => { res.send((res.random(gomas))()) }) robot.respond(/isao$/i, (res) => { res.send((res.random(isaos))()) }) }
JavaScript
0.999478
@@ -2118,10 +2118,339 @@ %7D)%0A%0A + robot.respond(/PAPIX$/i, (res) =%3E %7B%0A const req = robot.http(%22https://ngineerxiv-dark.appspot.com/api/v1/kusokora%22).get();%0A req((err, response, body) =%3E %7B%0A err && hubot.logger.error(err);%0A const json = JSON.parse(body);%0A res.send(res.random(json.kusokora));%0A %7D);%0A %7D);%0A%0A %7D%0A
ef23b046942b23c0a580cd82ea890e32df8cc756
Refresh challenges on answer.
static/js/controllers/challenges.js
static/js/controllers/challenges.js
/** * Copyright 2014 David Tomaschik <david@systemoverlord.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var challengeCtrls = angular.module('challengeCtrls', [ 'ngResource', 'ngRoute', 'challengeServices', 'globalServices', 'sessionServices', ]); challengeCtrls.controller('CategoryMenuCtrl', [ '$scope', '$interval', 'categoryService', 'sessionService', function($scope, $interval, categoryService, sessionService) { var updateCategories = function() { categoryService.getList(function(data) { $scope.categories = data.categories; }); }; var update; var startUpdate = function() { updateCategories(); update = $interval(updateCategories, 60*1000); }; sessionService.requireLogin(startUpdate, true); $scope.$on('sessionLogin', startUpdate); $scope.$on('sessionLogout', function() { $scope.categories = []; $interval.cancel(update); }); $scope.$on('correctAnswer', updateCategories); }]); challengeCtrls.controller('ChallengeCtrl', [ '$scope', '$resource', '$routeParams', 'answerService', 'categoryService', 'errorService', 'sessionService', 'loadingService', function($scope, $resource, $routeParams, answerService, categoryService, errorService, sessionService, loadingService) { errorService.clearErrors(); $scope.filterUnlocked = function(chall) { return chall.unlocked == true; }; var slug = $routeParams.slug; if (slug) { $scope.submitChallenge = function(chall) { errorService.clearErrors(); answerService.create({cid: chall.cid, answer: chall.answer}, function(resp) { chall.answered = true; errorService.error( 'Congratulations, ' + resp.points + ' points awarded!', 'success'); }, function(resp) { errorService.error(resp); }); }; $scope.invalidForm = function(idx) { var form = $(document.getElementsByName('submitForm['+idx+']')); return form.hasClass('ng-invalid'); }; $scope.unlockHintDialog = function(hint) { errorService.clearErrors(); $scope.hint = hint; $('#hint-modal').modal('show'); }; $scope.unlockHint = function(hint) { $resource('/api/unlock_hint').save({hid: hint.hid}, function(data) { hint.hint = data.hint; errorService.error( 'Unlocked hint for ' + hint.cost + ' points.', 'success'); $('#hint-modal').modal('hide'); }, function(data) { errorService.error(data); $('#hint-modal').modal('hide'); }); }; // Load challenges sessionService.requireLogin(function() { var found = false; categoryService.getList(function(data) { angular.forEach(data.categories, function(c) { if (c.slug == slug){ categoryService.get({cid: c.cid}, function(cat) { $scope.category = cat; $scope.category.answers = {}; $scope.challenges = cat.challenges; loadingService.stop(); }); found = true; } }); if (!found) { errorService.error('Category not found.'); loadingService.stop(); } }); }); } else { loadingService.stop(); } }]);
JavaScript
0
@@ -1996,16 +1996,314 @@ ors();%0A%0A + var refresh = function(cid) %7B%0A categoryService.get(%7Bcid: cid%7D,%0A function(cat) %7B%0A $scope.category = cat;%0A $scope.category.answers = %7B%7D;%0A $scope.challenges = cat.challenges;%0A loadingService.stop();%0A %7D);%0A %7D;%0A%0A $s @@ -2334,32 +2334,32 @@ nction(chall) %7B%0A - return c @@ -2488,32 +2488,66 @@ nction(chall) %7B%0A + loadingService.start();%0A errorS @@ -2831,32 +2831,67 @@ 'success');%0A + refresh($scope.cid);%0A %7D,%0A @@ -2910,32 +2910,32 @@ unction(resp) %7B%0A - er @@ -2958,16 +2958,53 @@ (resp);%0A + loadingService.stop();%0A @@ -4172,287 +4172,57 @@ -categoryService.get(%7Bcid: +$scope.cid = c.cid -%7D,%0A function(cat) %7B%0A $scope.category = cat;%0A $scope.category.answers = %7B%7D;%0A $scope.challenges = cat.challenges;%0A loadingService.stop();%0A %7D +;%0A refresh(c.cid );%0A
1ffe4052e64d3f9db498e7a00b6ae2c93c714d25
update files
static/js/terminal/lib/blankLine.js
static/js/terminal/lib/blankLine.js
/** * Created by nuintun on 2015/11/24. */ 'use strict'; module.exports = function (Terminal){ Terminal.prototype.blankLine = function (cur){ var attr = cur ? this.curAttr : this.defAttr; var ch = [attr, ' ']; var line = []; var i = 0; for (; i < this.cols; i++) { line[i] = ch; } return line; }; };
JavaScript
0.000001
@@ -212,17 +212,16 @@ %5Battr, ' - '%5D;%0A
fb38cc629f041bd2db5b6a6118e84c7c8c39ab6f
Empty fields should say N/A
src/app/views/map/building_layer.js
src/app/views/map/building_layer.js
define([ 'jquery', 'underscore', 'backbone', 'collections/city_buildings', 'models/building_color_bucket_calculator', 'text!templates/map/building_info.html' ], function($, _, Backbone, CityBuildings, BuildingColorBucketCalculator, BuildingInfoTemplate){ var baseCartoCSS = [ '{marker-fill: #CCC;' + 'marker-fill-opacity: 0.9;' + 'marker-line-color: #FFF;' + 'marker-line-width: 0.5;' + 'marker-line-opacity: 1;' + 'marker-placement: point;' + 'marker-multi-policy: largest;' + 'marker-type: ellipse;' + 'marker-allow-overlap: true;' + 'marker-clip: false;}' ]; var CartoStyleSheet = function(tableName, bucketCalculator) { this.tableName = tableName; this.bucketCalculator = bucketCalculator; } CartoStyleSheet.prototype.toCartoCSS = function(){ var bucketCSS = this.bucketCalculator.toCartoCSS(), styles = baseCartoCSS.concat(bucketCSS), tableName = this.tableName; styles = _.reject(styles, function(s) { return !s; }); styles = _.map(styles, function(s) { return "#" + tableName + " " + s; }); return styles.join("\n"); }; var BuildingInfoPresenter = function(city, allBuildings, buildingId){ this.city = city; this.allBuildings = allBuildings; this.buildingId = buildingId; }; BuildingInfoPresenter.prototype.toLatLng = function() { return {lat: this.toBuilding().get('lat'), lng: this.toBuilding().get('lng')}; }; BuildingInfoPresenter.prototype.toBuilding = function() { return this.allBuildings.find(function(building) { return building.get(this.city.get('property_id')) == this.buildingId }, this); }; BuildingInfoPresenter.prototype.toPopulatedLabels = function() { return _.map(this.city.get('popup_fields'), function(field) { return _.extend({ value: this.toBuilding().get(field.field) }, field); }, this); }; var LayerView = Backbone.View.extend({ initialize: function(options){ this.state = options.state; this.leafletMap = options.leafletMap; this.allBuildings = new CityBuildings(null, {}); this.listenTo(this.state, 'change:layer', this.onStateChange); this.listenTo(this.state, 'change:filters', this.onStateChange); this.listenTo(this.state, 'change:categories', this.onStateChange); this.listenTo(this.state, 'change:tableName', this.onStateChange); this.listenTo(this.state, 'change:building', this.onBuildingChange); this.listenTo(this.allBuildings, 'sync', this.render); this.onStateChange(); }, onBuildingChange: function() { var template = _.template(BuildingInfoTemplate), presenter = new BuildingInfoPresenter(this.state.get('city'), this.allBuildings, this.state.get('building')); L.popup() .setLatLng(presenter.toLatLng()) .setContent(template({labels: presenter.toPopulatedLabels()})) .openOn(this.leafletMap); }, onFeatureClick: function(event, latlng, _unused, data){ var propertyId = this.state.get('city').get('property_id'), buildingId = data[propertyId]; this.state.set({building: buildingId}); }, onFeatureOver: function(){ $('#map').css('cursor', "help"); }, onFeatureOut: function(){ $('#map').css('cursor', ''); }, onStateChange: function(){ _.extend(this.allBuildings, this.state.pick('tableName', 'cartoDbUser')); this.allBuildings.fetch(); }, toCartoSublayer: function(){ var buildings = this.allBuildings, state = this.state, city = state.get('city'), fieldName = state.get('layer'), cityLayer = _.findWhere(city.get('map_layers'), {field_name: fieldName}), buckets = cityLayer.range_slice_count colorStops = cityLayer.color_range, calculator = new BuildingColorBucketCalculator(buildings, fieldName, buckets, colorStops), stylesheet = new CartoStyleSheet(buildings.tableName, calculator); return { sql: buildings.toSql(state.get('categories'), state.get('filters')), cartocss: stylesheet.toCartoCSS(), interactivity: this.state.get('city').get('property_id') } }, render: function(){ if(this.cartoLayer) { this.cartoLayer.getSubLayer(0).set(this.toCartoSublayer()).show(); return this; } cartodb.createLayer(this.leafletMap, { user_name: 'cityenergy-slc', type: 'cartodb', sublayers: [this.toCartoSublayer()] }).addTo(this.leafletMap).on('done', this.onCartoLoad, this); return this; }, onCartoLoad: function(layer) { var sub = layer.getSubLayer(0); this.cartoLayer = layer; sub.setInteraction(true); sub.on('featureClick', this.onFeatureClick, this); sub.on('featureOver', this.onFeatureOver, this); sub.on('featureOut', this.onFeatureOut, this); this.onBuildingChange(); } }); return LayerView; });
JavaScript
0.997976
@@ -1864,16 +1864,25 @@ d.field) + %7C%7C 'N/A' %0A %7D
e6c71bd5d41b51ac60b31a25d968e230018bb67b
add category
vanilla-react/image-generator/index.js
vanilla-react/image-generator/index.js
let state = { category: '', filter: '', size: {w: 640, h: 480} }; onPageLoad(); function setState(newState) { Object.assign(state, newState); render(state); } function render(state) { document.querySelector('#root').innerHTML = App(state); } function onPageLoad() { setState({category: 'people'}); } function onGenerate() { setState({}); } function onFilterChange(event) { setState({filter: event.target.value}); } function App(state) { let url = `https://placeimg.com/${state.size.w}/${state.size.h}/${state.category}${state.filter && `/${state.filter}`}`; return ` <main style=" height: 100vh; display: flex; justify-content: center; align-items: center; flex-direction: column; gap: 1em;"> <img style="border: 1px dashed" width="${state.size.w}" height="${state.size.h}" src="${url}" /> <p>${url}</p> <div> <button onclick="onGenerate(event)">Generate</button> <input onclick="onFilterChange(event)" type="radio" ${state.filter === 'sepia' && 'checked'} value="sepia" id="sepia"><label for="sepia">Sepia</label> <input onclick="onFilterChange(event)" type="radio" ${state.filter === 'grayscale' && 'checked'} value="grayscale" id="grayscale"><label for="grayscale">Grayscale</label> </div> </main> `; }
JavaScript
0.001148
@@ -446,103 +446,136 @@ ion -App(state) %7B%0A let url = %60https://placeimg.com/$%7Bstate.size.w%7D/$%7Bstate.size.h%7D/$%7Bs +onCategoryChange(event) %7B%0A let select = event.target;%0A let option = select.options%5Bselect.selectedIndex%5D;%0A setS tate -. +(%7B category %7D$%7Bs @@ -574,48 +574,50 @@ gory -%7D$%7Bstate.filter && %60/$%7Bstate.filter%7D%60%7D%60; +: option.value%7D);%0A%7D%0A%0Afunction App(state) %7B %0A r @@ -801,15 +801,370 @@ +$%7BImage(state)%7D%0A%0A %3Cdiv%3E%0A %3Cbutton onclick=%22onGenerate(event)%22%3EGenerate%3C/button%3E%0A $%7BFilters(state.filter)%7D%0A $%7BCategories(state.category)%7D%0A %3C/div%3E%0A %3C/main%3E%0A %60;%0A%7D%0A%0Afunction Image(state) %7B%0A let url = %60https://placeimg.com/$%7Bstate.size.w%7D/$%7Bstate.size.h%7D/$%7Bstate.category%7D$%7Bstate.filter && %60/$%7Bstate.filter%7D%60%7D%60;%0A return %60%0A %3Cimg%0A - @@ -1192,18 +1192,16 @@ dashed%22%0A - wi @@ -1253,18 +1253,16 @@ %22%0A - - src=%22$%7Bu @@ -1274,18 +1274,16 @@ /%3E%0A%0A - %3Cp%3E$%7Burl @@ -1292,87 +1292,54 @@ /p%3E%0A -%0A %3Cdiv%3E%0A %3Cbutton onclick=%22onGenerate(event)%22%3EGenerate%3C/button%3E%0A + %60;%0A%7D%0A%0Afunction Filters(filter) %7B%0A return %60%0A @@ -1384,38 +1384,32 @@ type=%22radio%22 $%7B -state. filter === 'sepi @@ -1483,20 +1483,16 @@ /label%3E%0A - %3Cinp @@ -1541,22 +1541,16 @@ adio%22 $%7B -state. filter = @@ -1658,34 +1658,407 @@ %3E%0A - %3C/div%3E%0A %3C/main +%60;%0A%7D%0A%0Afunction Categories(category) %7B%0A let options = %5B%0A %7Bvalue: 'animals'%7D,%0A %7Bvalue: 'people'%7D,%0A %7Bvalue: 'nature'%7D,%0A %7Bvalue: 'tech'%7D,%0A %7Bvalue: 'architecture'%7D%0A %5D;%0A return %60%0A %3Cselect onchange=%22onCategoryChange(event)%22%3E%0A $%7Boptions.map(option =%3E %60%3Coption value=%22$%7Boption.value%7D%22 $%7Boption.value === category && 'selected'%7D%3E$%7Boption.value%7D%3C/option%3E%60).join('')%7D%0A %3C/select %3E%0A %60;%0A%7D %0A @@ -2048,17 +2048,16 @@ %3C/select%3E%0A %60;%0A%7D -%0A
60cca3e2ad78b88866a7f512a4609c34558622a4
Improve label
view/components/incomplete-form-nav.js
view/components/incomplete-form-nav.js
// Draw list of not completed sections and their missing fields. 'use strict'; var db = require('mano').db , _ = require('mano').i18n.bind('Incomplete Sections Navigation') , headersMap = require('../utils/headers-map'); var getPropertyLabel = function (formSection, propertyName) { return JSON.stringify(formSection.master.resolveSKeyPath(propertyName).ownDescriptor.label); }; var getEntityTitle = function (formSection, entity) { return entity.resolveSKeyPath(formSection.entityTitleProperty).observable; }; var generateSectionLink = function (formSection) { return a( { href: '#' + formSection.domId }, formSection.onIncompleteMessage || _("${sectionLabel} is incomplete", { sectionLabel: formSection.label }) ); }; var generateMissingPropertiesList = function (formSection) { return ul({ class: 'section-warning-missing-fields-list' }, formSection.missingRequiredPropertyNames, function (propertyName) { return getPropertyLabel(formSection, propertyName); } ); }; var generateMissingList = function (formSection, level) { level = level || 3; if (db.FormSection && (formSection instanceof db.FormSection)) { return div({ class: 'section-warning-missing-fields' }, p(_("Missing required fields:")), generateMissingPropertiesList(formSection)); } if (db.FormSectionGroup && (formSection instanceof db.FormSectionGroup)) { return div( p(_("Missing required fields:")), ul( formSection.sections, function (subSection) { if (!subSection.missingRequiredPropertyNames.size) return; return li( { class: 'section-warning-missing-fields section-warning-missing-fields-sub-1' }, p(mdi(_("In _\"${ sectionLabel }\"_ section:", { sectionLabel: subSection.label }))), generateMissingPropertiesList(subSection) ); } ) ); } if (db.FormEntitiesTable && (formSection instanceof db.FormEntitiesTable)) { return list(formSection.entitiesSet, function (entity) { var entitySections = entity.resolveSKeyPath(formSection.sectionProperty).value; return _if(not(eq(entitySections._progress, 1)), [ headersMap[level](getEntityTitle(formSection, entity)), list(entitySections.applicable, function (entitySection) { return generateMissingList(entitySection, level + 1); }) ]); }); } }; module.exports = function (sections) { return ul(sections, function (formSection) { return _if(not(eq(formSection._status, 1)), section( generateSectionLink(formSection), generateMissingList(formSection) )); }); };
JavaScript
0.093239
@@ -1700,16 +1700,20 @@ bel %7D%5C%22_ + sub section
6891d2cde7c30d4c739c5bcf08c7892511e1c121
Update shadow.class.js
src/shadow.class.js
src/shadow.class.js
(function(global) { 'use strict'; var fabric = global.fabric || (global.fabric = { }), toFixed = fabric.util.toFixed; if (fabric.Shadow) { fabric.warn('fabric.Shadow is already defined.'); return; } /** * Shadow class * @class fabric.Shadow * @see {@link http://fabricjs.com/shadows/|Shadow demo} * @see {@link fabric.Shadow#initialize} for constructor definition */ fabric.Shadow = fabric.util.createClass(/** @lends fabric.Shadow.prototype */ { /** * Shadow color * @type String * @default */ color: 'rgb(0,0,0)', /** * Shadow blur * @type Number */ blur: 0, /** * Shadow horizontal offset * @type Number * @default */ offsetX: 0, /** * Shadow vertical offset * @type Number * @default */ offsetY: 0, /** * Whether the shadow should affect stroke operations * @type Boolean * @default */ affectStroke: false, /** * Indicates whether toObject should include default values * @type Boolean * @default */ includeDefaultValues: true, /** * Constructor * @param {Object|String} [options] Options object with any of color, blur, offsetX, offsetX properties or string (e.g. "rgba(0,0,0,0.2) 2px 2px 10px, "2px 2px 10px rgba(0,0,0,0.2)") * @return {fabric.Shadow} thisArg */ initialize: function(options) { if (typeof options === 'string') { options = this._parseShadow(options); } for (var prop in options) { this[prop] = options[prop]; } this.id = fabric.Object.__uid++; }, /** * @private * @param {String} shadow Shadow value to parse * @return {Object} Shadow object with color, offsetX, offsetY and blur */ _parseShadow: function(shadow) { var shadowStr = shadow.trim(), offsetsAndBlur = fabric.Shadow.reOffsetsAndBlur.exec(shadowStr) || [ ], color = shadowStr.replace(fabric.Shadow.reOffsetsAndBlur, '') || 'rgb(0,0,0)'; return { color: color.trim(), offsetX: parseInt(offsetsAndBlur[1], 10) || 0, offsetY: parseInt(offsetsAndBlur[2], 10) || 0, blur: parseInt(offsetsAndBlur[3], 10) || 0 }; }, /** * Returns a string representation of an instance * @see http://www.w3.org/TR/css-text-decor-3/#text-shadow * @return {String} Returns CSS3 text-shadow declaration */ toString: function() { return [this.offsetX, this.offsetY, this.blur, this.color].join('px '); }, /* _TO_SVG_START_ */ /** * Returns SVG representation of a shadow * @param {fabric.Object} object * @return {String} SVG representation of a shadow */ toSVG: function(object) { var fBoxX = 40, fBoxY = 40, NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS, offset = fabric.util.rotateVector( { x: this.offsetX, y: this.offsetY }, fabric.util.degreesToRadians(-object.angle)), BLUR_BOX = 20; if (object.width && object.height) { //http://www.w3.org/TR/SVG/filters.html#FilterEffectsRegion // we add some extra space to filter box to contain the blur ( 20 ) fBoxX = toFixed((Math.abs(offset.x) + this.blur) / object.width, NUM_FRACTION_DIGITS) * 100 + BLUR_BOX; fBoxY = toFixed((Math.abs(offset.y) + this.blur) / object.height, NUM_FRACTION_DIGITS) * 100 + BLUR_BOX; } return ( '<filter id="SVGID_' + this.id + '" y="-' + fBoxY + '%" height="' + (100 + 2 * fBoxY) + '%" ' + 'x="-' + fBoxX + '%" width="' + (100 + 2 * fBoxX) + '%" ' + '>\n' + '\t<feGaussianBlur in="SourceAlpha" stdDeviation="' + toFixed(this.blur ? this.blur / 2 : 0, NUM_FRACTION_DIGITS) + '"></feGaussianBlur>\n' + '\t<feOffset dx="' + toFixed(offset.x, NUM_FRACTION_DIGITS) + '" dy="' + toFixed(offset.y, NUM_FRACTION_DIGITS) + '" result="oBlur" ></feOffset>\n' + '\t<feFlood flood-color="' + this.color + '"/>\n' + '\t<feComposite in2="oBlur" operator="in" />\n' + '\t<feMerge>\n' + '\t\t<feMergeNode></feMergeNode>\n' + '\t\t<feMergeNode in="SourceGraphic"></feMergeNode>\n' + '\t</feMerge>\n' + '</filter>\n'); }, /* _TO_SVG_END_ */ /** * Returns object representation of a shadow * @return {Object} Object representation of a shadow instance */ toObject: function() { if (this.includeDefaultValues) { return { color: this.color, blur: this.blur, offsetX: this.offsetX, offsetY: this.offsetY, affectStroke: this.affectStroke }; } var obj = { }, proto = fabric.Shadow.prototype; ['color', 'blur', 'offsetX', 'offsetY', 'affectStroke'].forEach(function(prop) { if (this[prop] !== proto[prop]) { obj[prop] = this[prop]; } }, this); return obj; } }); /** * Regex matching shadow offsetX, offsetY and blur (ex: "2px 2px 10px rgba(0,0,0,0.2)", "rgb(0,255,0) 2px 2px") * @static * @field * @memberOf fabric.Shadow */ fabric.Shadow.reOffsetsAndBlur = /(?:\s|^)(-?\d+(?:px)?(?:\s?|$))?(-?\d+(?:px)?(?:\s?|$))?(\d+(?:px)?)?(?:\s?|$)(?:$|\s)/; })(typeof exports !== 'undefined' ? exports : this);
JavaScript
0.000001
@@ -3490,24 +3490,139 @@ OX;%0A %7D%0A + if (object.flipX) %7B%0A offset.x *= -1;%0A %7D%0A if (object.flipY) %7B%0A offset.y *= -1;%0A %7D %0A retur
15f193fca7bb00f113c8eb21210f2163a656d513
Remove unused variable.
commands/branches.js
commands/branches.js
var ch = require('../src/CmdHelper'); var _ = require('lodash'); module.exports = { name: 'branches', description: 'Checks git local branch name across all services', usage: '[-r <repoPattern>]', }; function cmd(bosco) { bosco.log('Running \'git rev-parse --abbrev-ref HEAD\' across all matching repos ...'); var options = ch.createOptions(bosco, { cmd: 'git', args: ['rev-parse', '--abbrev-ref', 'HEAD'], guardFn: function(innerBosco, repoPath, opts, next) { if (innerBosco.exists([repoPath, '.git'].join('/'))) return next(); next(new Error('Doesn\'t seem to be a git repo: ' + repoPath.blue)); }, stdoutFn: function(stdout, path) { if (!stdout) return; var branchName = stdout.trim(); if (branchName !== 'master') { bosco.log(path.blue + ' is on branch \'' + branchName.cyan + '\''); } }, }); ch.iterate(bosco, options, function() { bosco.log('Complete'); }); } module.exports.cmd = cmd;
JavaScript
0.000001
@@ -34,35 +34,8 @@ r'); -%0Avar _ = require('lodash'); %0A%0Amo
a0d31ad0341180695456fa4574eccd15f8e40f1d
make the branch name cyan
commands/branches.js
commands/branches.js
var ch = require('../src/CmdHelper'); var _ = require('lodash'); module.exports = { name: 'branches', description: 'Checks git branch list across all services', usage: '[-r <repoPattern>]', }; function cmd(bosco) { bosco.log('Running \'git branch --list\' across all matching repos ...'); var options = ch.createOptions(bosco, { cmd: 'git', args: ['branch', '--list'], guardFn: function(innerBosco, repoPath, opts, next) { if (innerBosco.exists([repoPath, '.git'].join('/'))) return next(); next(new Error('Doesn\'t seem to be a git repo: ' + repoPath.blue)); }, stdoutFn: function(stdout, path) { if (!stdout) return; // find the line in the stdout with the * in front, and grab the branch name var activeBranch = stdout.match(/\* (.*)/)[1]; if (activeBranch !== 'master') { bosco.log(path.blue + ' is on branch \'' + activeBranch + '\''); } }, }); ch.iterate(bosco, options, function() { bosco.log('Complete'); }); } module.exports.cmd = cmd;
JavaScript
0.999996
@@ -903,16 +903,21 @@ veBranch +.cyan + '%5C'')
54b9597c9a01ed7904d0b9ed12cb46cbe211e7b8
Add a note about keeping unused component for later reference
packages/@sanity/desk-tool/src/components/Diff.js
packages/@sanity/desk-tool/src/components/Diff.js
import PropTypes from 'prop-types' import React from 'react' import {diffJson} from 'diff' import styles from './styles/Diff.css' function getDiffStatKey(part) { if (part.added) { return 'added' } if (part.removed) { return 'removed' } return 'neutral' } export default class Diff extends React.PureComponent { static defaultProps = { inputA: '', inputB: '' } static propTypes = { inputA: PropTypes.object, inputB: PropTypes.object } render() { const diff = diffJson(this.props.inputA, this.props.inputB) return ( <pre> {diff.map((part, index) => ( <span key={index} className={styles[getDiffStatKey(part)]}>{part.value}</span> ))} </pre> ) } }
JavaScript
0
@@ -1,12 +1,124 @@ +/**%0A *%0A *%0A *%0A *%0A *%0A *%0A *%0A * HEADSUP: This is not in use, but keep for later reference%0A *%0A *%0A *%0A *%0A *%0A *%0A *%0A */%0A import PropT
be03ae2dcf2e691abab5ef8f472f48718cadc8a2
use chai-enzyme to make tests more robust
packages/beaut-ui-range-slider/test/label-test.js
packages/beaut-ui-range-slider/test/label-test.js
import React from 'react'; import { expect } from 'chai'; import { shallow } from 'enzyme'; import Label from '../src/components/label'; describe('<Label />', () => { it('renders an SVG text node', () => { const wrapper = shallow(<Label anchor="start" position={{ x: 5 }} value={25} />); expect(wrapper.find('text')).to.have.length(1); }); it('renders a label that is a number to one fixed-point', () => { const wrapper = shallow(<Label anchor="start" position={{ x: 5, shift: 0 }} value={30.27} />); expect(wrapper.find('text').html()).to.equal( `<text text-anchor="start" fill="black" x="5">30.3</text>` ); }); it('renders a label that is a string', () => { const wrapper = shallow(<Label anchor="start" position={{ x: 5, shift: 0 }} value="Years" />); expect(wrapper.find('text').html()).to.equal( `<text text-anchor="start" fill="black" x="5">Years</text>` ); }); it('shifts the x position towards origin by shift when anchor==="start"', () => { const wrapper = shallow(<Label anchor="start" position={{ x: 20, shift: 5 }} />); expect(wrapper.find('text').html()).to.equal( `<text text-anchor="start" fill="black" x="15"></text>` ); }); it('shifts the x position away from the origin by shift when anchor==="end"', () => { const wrapper = shallow(<Label anchor="end" position={{ x: 20, shift: 5 }} />); expect(wrapper.find('text').html()).to.equal( `<text text-anchor="end" fill="black" x="25"></text>` ); }); it('does not shift the x position by shift when anchor==="middle"', () => { const wrapper = shallow(<Label anchor="middle" position={{ x: 20, shift: 5 }} />); expect(wrapper.find('text').html()).to.equal( `<text text-anchor="middle" fill="black" x="20"></text>` ); }); });
JavaScript
0
@@ -26,16 +26,22 @@ ;%0Aimport + chai, %7B expec @@ -90,16 +90,79 @@ enzyme'; +%0Aimport chaiEnzyme from 'chai-enzyme';%0A%0Achai.use(chaiEnzyme()); %0A%0Aimport @@ -338,16 +338,22 @@ =%7B%7B x: 5 +, y: 0 %7D%7D valu @@ -511,32 +511,39 @@ apper = shallow( +%0A %3CLabel anchor=%22s @@ -557,32 +557,38 @@ osition=%7B%7B x: 5, + y: 0, shift: 0 %7D%7D val @@ -596,27 +596,33 @@ e=%7B30.27%7D /%3E +%0A );%0A +%0A expect(w @@ -644,96 +644,29 @@ xt') -.html()).to.equal(%0A %60%3Ctext text-anchor=%22start%22 fill=%22black%22 x=%225%22%3E30.3%3C/text%3E%60%0A +).to.have.text('30.3' );%0A @@ -740,32 +740,39 @@ apper = shallow( +%0A %3CLabel anchor=%22s @@ -794,16 +794,22 @@ %7B%7B x: 5, + y: 0, shift: @@ -829,19 +829,25 @@ ears%22 /%3E +%0A );%0A +%0A expe @@ -873,97 +873,30 @@ xt') -.html()).to.equal(%0A %60%3Ctext text-anchor=%22start%22 fill=%22black%22 x=%225%22%3EYears%3C/text%3E%60%0A +).to.have.text('Years' );%0A @@ -1045,32 +1045,38 @@ sition=%7B%7B x: 20, + y: 0, shift: 5 %7D%7D /%3E) @@ -1112,93 +1112,34 @@ xt') -.html()).to.equal(%0A %60%3Ctext text-anchor=%22start%22 fill=%22black%22 x=%2215%22%3E%3C/text%3E%60%0A +).to.have.attr('x', '15px' );%0A @@ -1290,32 +1290,38 @@ sition=%7B%7B x: 20, + y: 0, shift: 5 %7D%7D /%3E) @@ -1357,91 +1357,34 @@ xt') -.html()).to.equal(%0A %60%3Ctext text-anchor=%22end%22 fill=%22black%22 x=%2225%22%3E%3C/text%3E%60%0A +).to.have.attr('x', '25px' );%0A @@ -1536,16 +1536,22 @@ %7B x: 20, + y: 0, shift: @@ -1595,94 +1595,34 @@ xt') -.html()).to.equal(%0A %60%3Ctext text-anchor=%22middle%22 fill=%22black%22 x=%2220%22%3E%3C/text%3E%60%0A +).to.have.attr('x', '20px' );%0A
ce5ea11e8d3f88a819d779c14a07746135d5d471
Fix matching style file of containg `modules`
build/utils.js
build/utils.js
var path = require('path') var fs = require('fs') var config = require('../config') var ExtractTextPlugin = require('extract-text-webpack-plugin') exports.assetsPath = function (_path) { var assetsSubDirectory = process.env.NODE_ENV === 'production' ? config.build.assetsSubDirectory : config.dev.assetsSubDirectory return path.posix.join(assetsSubDirectory, _path) } exports.cssLoaders = function (options) { options = options || {} var cssLoader = { loader: 'css-loader', options: { minimize: process.env.NODE_ENV === 'production', sourceMap: options.sourceMap } } var modulesCssLoader = { loader: 'css-loader', options: { modules: true, localIdentName: '[path][name]__[local]--[hash:base64:5]', minimize: process.env.NODE_ENV === 'production', sourceMap: options.sourceMap } } // generate loader string to be used with extract text plugin function generateLoaders (loader, loaderOptions) { var loaders = options.modules ? [modulesCssLoader] : [cssLoader] if (loader) { loaders.push({ loader: loader + '-loader', options: Object.assign({}, loaderOptions, { sourceMap: options.sourceMap }) }) } // Extract CSS when that option is specified // (which is the case during production build) if (options.extract) { return ExtractTextPlugin.extract({ use: loaders, fallback: 'style-loader' }) } else { return ['style-loader'].concat(loaders) } } // https://vue-loader.vuejs.org/en/configurations/extract-css.html return { css: generateLoaders(), postcss: generateLoaders(), less: generateLoaders('less'), sass: generateLoaders('sass', { indentedSyntax: true }), scss: generateLoaders('sass'), stylus: generateLoaders('stylus'), styl: generateLoaders('stylus') } } // Generate loaders for standalone style files exports.styleLoaders = function (options) { var output = [] var loaders = exports.cssLoaders(options) for (var extension in loaders) { var loader = loaders[extension] output.push({ test: new RegExp('[^\\.modules]\\.' + extension + '$'), use: loader, }) } return output } exports.modulesStyleLoaders = function(options) { var output = [] var loaders = exports.cssLoaders(options) for (var extension in loaders) { var loader = loaders[extension] output.push({ test: new RegExp('\\.modules\\.' + extension + '$'), use: loader, }) } return output }
JavaScript
0
@@ -2165,10 +2165,14 @@ xp(' -%5B %5E +(?!.* %5C%5C.m @@ -2177,17 +2177,19 @@ .modules -%5D +).* %5C%5C.' + e
fa47fd5c3fdc974656206dcad3b9dd11b4583d6d
allow passing down className to Button
packages/button/src/presenters/ButtonPresenter.js
packages/button/src/presenters/ButtonPresenter.js
import React, { Component } from "react"; import PropTypes from "prop-types"; import { css } from "emotion"; import { ThemeContext } from "@hig/theme-context"; import stylesheet from "./stylesheet"; import { availableTargets, availableTypes, availableWidths } from "../constants"; export default class ButtonPresenter extends Component { static propTypes = { disabled: PropTypes.bool, hasFocus: PropTypes.bool, hasHover: PropTypes.bool, isPressed: PropTypes.bool, icon: PropTypes.node, link: PropTypes.string, onBlur: PropTypes.func, onClick: PropTypes.func, onFocus: PropTypes.func, onHover: PropTypes.func, onMouseDown: PropTypes.func, onMouseEnter: PropTypes.func, onMouseLeave: PropTypes.func, onMouseUp: PropTypes.func, target: PropTypes.oneOf(availableTargets), title: PropTypes.string.isRequired, type: PropTypes.oneOf(availableTypes), width: PropTypes.oneOf(availableWidths) }; render() { const { disabled, hasFocus, hasHover, isPressed, icon, link, onBlur, onClick, onFocus, onHover, onMouseDown, onMouseEnter, onMouseLeave, onMouseUp, target, title, type, width, ...otherProps } = this.props; const href = link || undefined; const tabIndex = disabled ? "-1" : "0"; const Wrapper = link ? "a" : "button"; const wrapperTarget = link ? target : undefined; return ( <ThemeContext.Consumer> {({ resolvedRoles, metadata }) => { const styles = stylesheet( { disabled, hasFocus, hasHover, isPressed, type, width }, resolvedRoles, metadata ); return ( <Wrapper className={css(styles.button)} href={href} tabIndex={tabIndex} target={wrapperTarget} onBlur={onBlur} onClick={onClick} onFocus={onFocus} onMouseDown={onMouseDown} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} onMouseOver={onHover} onMouseUp={onMouseUp} disabled={disabled} {...otherProps} > {icon && <span className={css(styles.icon)}>{icon}</span>} <span className={icon ? css(styles.iconText) : ""}>{title}</span> </Wrapper> ); }} </ThemeContext.Consumer> ); } }
JavaScript
0.000012
@@ -79,16 +79,20 @@ import %7B + cx, css %7D f @@ -1311,16 +1311,55 @@ props;%0A%0A + const %7B className %7D = otherProps;%0A%0A cons @@ -1386,16 +1386,16 @@ efined;%0A - cons @@ -1822,16 +1822,46 @@ Wrapper%0A + %7B...otherProps%7D%0A @@ -1869,32 +1869,35 @@ className=%7B +cx( css(styles.butto @@ -1898,16 +1898,28 @@ .button) +, className) %7D%0A @@ -2299,16 +2299,16 @@ ouseUp%7D%0A + @@ -2337,38 +2337,8 @@ ed%7D%0A - %7B...otherProps%7D%0A
0426de4f14008656939711c7a4574f9836fbae7f
Update training.js
commands/training.js
commands/training.js
const Discord = require('discord.js'); exports.run = (client, message) => { const modlog = client.channels.find('name', 'pie-log'); const anno2 = client.channels.find('name', 'trainings'); let say = message.content.split(" ").join(" ").slice(6) if (say.length < 1) return message.reply('Please specify on what I have to say.').catch(console.error); message.delete() client.channels.get(anno2.id).send({embed: { color: 0xff0000, title: `Training Session`, description: ``, fields: [{ name: "Trainer:", value: `${message.author}` },{ name: "Message", value: `${say}` }] } }) client.channels.get(modlog.id).send({embed: { color: 0x0000FF, title: "Command input", description: `\n\n**Username:** \n${message.author.username} <${message.author}>\n**Command:** ;training ${say}`, timestamp: new Date(), footer: { icon_url: `${message.author.avatarURL}`, text: `User: ${message.author.username}` } } }) client.channels.get(anno2.id).send('@everyone') }; exports.conf = { enabled: true, guildOnly: false, aliases: [], permLevel: 1 }; exports.help = { name: 'training', description: 'Announces a training under the channel #trainings', usage: 'training message' };
JavaScript
0
@@ -1096,16 +1096,23 @@ iases: %5B +%22tanno%22 %5D,%0ApermL
7056349a0780382b7ef5b8b221466f1ffdb3ced4
Refactor render function slightly
src/styleManager.js
src/styleManager.js
import jssVendorPrefixer from 'jss-vendor-prefixer'; import { find, findIndex } from './utils'; const prefixRule = jssVendorPrefixer(); /** * styleManager module. Used to create styleManager objects. * * @module styleManager */ /** * Creates a new styleManager * * @param {Object} config - Config * @param {Object} config.jss - Jss instance * @param {Object} config.theme={} - Theme object * @return {module:styleManager~styleManager} - styleManager */ export function createStyleManager({ jss, theme = {} } = {}) { let sheetMap = []; /** * styleManager description * * @name styleManager * @type {Object} */ const styleManager = { get sheetMap() { return sheetMap; }, jss, theme, render, rerender, reset, getClasses, updateTheme, prepareInline, }; function getClasses(styleSheet) { const mapping = find(sheetMap, { styleSheet }); if (mapping) { return mapping.classes; } return undefined; } /** * Some mundane desc * * @memberOf module:styleManager~styleManager * @param {Object} styleSheet - styleSheet object created by createStyleSheet() * @return {Object} - classNames keyed by styleSheet property names */ function render(styleSheet, ...other) { let mapping = find(sheetMap, { styleSheet }); if (!mapping) { const { name, createRules, options } = styleSheet; const looseIndex = findIndex(sheetMap, { name }); if (looseIndex !== -1) { sheetMap[looseIndex].jssStyleSheet.detach(); sheetMap.splice(looseIndex, 1); } const rules = createRules(theme, ...other); const jssStyleSheet = jss.createStyleSheet(rules, { meta: name, ...options }); const { classes } = jssStyleSheet.attach(); mapping = { name, classes, styleSheet, jssStyleSheet, other }; sheetMap.push(mapping); } return mapping.classes; } /** * Replace the current theme with a new theme * * @param {Object} newTheme - New theme object * @param {boolean} shouldReset - Set to true to rerender the renderer */ function updateTheme(newTheme, shouldReset = true) { theme = newTheme; if (shouldReset) { rerender(); } } function reset() { sheetMap.forEach(({ jssStyleSheet }) => jssStyleSheet.detach()); jss.sheets.registry = []; sheetMap = []; } /** * Reset and replace all existing stylesheets * * @memberOf module:styleManager~styleManager */ function rerender() { const sheets = [...sheetMap]; reset(); sheets.forEach((n) => render(n.styleSheet, ...n.other)); } function prepareInline(declaration) { if (typeof declaration === 'function') { declaration = declaration(theme); } const rule = { type: 'regular', style: declaration, }; prefixRule(rule); return rule.style; } return styleManager; }
JavaScript
0
@@ -1342,26 +1342,31 @@ -let mapping +const index = find +Index (she @@ -1365,32 +1365,38 @@ ndex(sheetMap, %7B + name: styleSheet %7D);%0A @@ -1382,32 +1382,37 @@ name: styleSheet +.name %7D);%0A%0A if (!m @@ -1413,270 +1413,678 @@ if ( -!mapping) %7B%0A const %7B name, createRules, options %7D = styleSheet;%0A%0A const looseIndex = findIndex(sheetMap, %7B name %7D);%0A%0A if (looseIndex !== -1) %7B%0A sheetMap%5BlooseIndex%5D.jssStyleSheet.detach +index === -1) %7B%0A return renderNew(styleSheet, ...other);%0A %7D%0A%0A const mapping = sheetMap%5Bindex%5D;%0A%0A if (mapping.styleSheet !== styleSheet) %7B%0A jss.removeStyleSheet(sheetMap%5Bindex%5D.jssStyleSheet);%0A sheetMap.splice(index, 1);%0A%0A return renderNew(styleSheet, ...other);%0A %7D%0A%0A return mapping.classes;%0A %7D%0A%0A /**%0A * @private%0A * @memberOf module:styleManager~styleManager%0A * @param %7BObject%7D styleSheet - styleSheet object created by createStyleSheet () -; %0A - sheetMap.splice(looseIndex, 1);%0A %7D%0A%0A +* @return %7BObject%7D - classNames keyed by styleSheet property names%0A */%0A function renderNew(styleSheet, ...other) %7B%0A const %7B name, createRules, options %7D = styleSheet;%0A%0A @@ -2127,18 +2127,16 @@ other);%0A - cons @@ -2214,18 +2214,16 @@ %7D);%0A - const %7B @@ -2267,20 +2267,22 @@ - mapping = +sheetMap.push( %7B na @@ -2332,45 +2332,10 @@ er %7D +) ; -%0A sheetMap.push(mapping);%0A %7D %0A%0A @@ -2339,32 +2339,24 @@ %0A return -mapping. classes;%0A %7D
72c5b7255489c8b1aad0137fa44ebfb7344e9cbd
Remove stale FIXME
details.js
details.js
import {black, white} from './colors.js' import {revive} from './reviver.js' import {assert, zip} from './util.js' function setColors({style}, color, background) { if (color && style.color != color) { style.color = color } if (background && style.background != background) { style.background = background } } setColors(document.body, black, white) const port = browser.runtime.connect( null, {name: 'details'}, ) port.onMessage.addListener(message => requestAnimationFrame(async () => draw(await revive(message))), ) function update(event) { port.postMessage(event) } class Label { constructor(name) { this.name = name } create() { const node = document.createElement('label') node.htmlFor = this.name node.textContent = this.name.replace(/^./, c => c.toUpperCase()) + ':' return node } update() {} } class Checkbox { constructor(name, value) { this.name = name this.value = value } create() { const node = document.createElement('input') node.id = this.name node.type = 'checkbox' node.addEventListener('change', () => update({monitored: node.checked})) this.update(node) return node } update(node) { if (node.checked != this.value) { node.checked = this.value } } } class TextField { constructor(name) { this.name = name } create() { const node = document.createElement('input') node.id = this.name node.type = 'text' node.addEventListener('change', () => { /* FIXME Target on change \d*([.:]?)\d* null if falsy, otherwise duration hours and round to minutes or duration parse not null and strictly between zero and 1000 hours, clear error message, clear value, update name, target update({name: this.name, target}) otherwise, element set custom validity error message: h:mm */ }) return node } update() {} } class Text { constructor(value, color, background) { this.value = value this.color = color this.background = background } create() { const node = document.createElement('div') this.update(node) return node } update(node) { if (node.textContent != this.value) { node.textContent = this.value } setColors(node, this.color, this.background) } } function* getMetricCells({monitored, metrics}) { yield* [new Label('monitored'), new Checkbox('monitored', monitored)] for (const {name, value, color, target} of Object.values(metrics)) { yield* [ new Label(name), new TextField(name), new Text(value.format('seconds'), color), new Text(target.format()), ] } } function draw(message) { const metricGrid = document.getElementById('metrics') const metricNodes = metricGrid.children for (const [cell, node] of zip(getMetricCells(message), metricNodes)) { assert(cell) if (node) { cell.update(node) } else { metricGrid.appendChild(cell.create()) } } } // FIXME: Display grid, repeat 4, ID metrics, right aligned
JavaScript
0.000004
@@ -3006,65 +3006,4 @@ %7D%0A%7D%0A -%0A// FIXME: Display grid, repeat 4, ID metrics, right aligned%0A
63768665f0a37037f5c66ab9e68e06c42ebc1191
Fix linter errors
lib/assets/core/javascripts/cartodb3/data/widget-definitions-collection.js
lib/assets/core/javascripts/cartodb3/data/widget-definitions-collection.js
var Backbone = require('backbone'); var _ = require('underscore'); var WidgetDefinitionModel = require('./widget-definition-model'); var checkAndBuildOpts = require('../helpers/required-opts'); var REQUIRED_OPTS = [ 'configModel', 'mapId', 'layerDefinitionsCollection', 'analysisDefinitionNodesCollection' ]; /** * Collection of widget definitions, synhronizes the internal definitions and the widget models. */ module.exports = Backbone.Collection.extend({ comparator: 'order', model: function (d, opts) { var self = opts.collection; d.order = !_.isUndefined(d.order) ? d.order : self._getNextOrder(); var m = new WidgetDefinitionModel(d, { parse: true, // make sure data is structured as expected collection: self, configModel: self._configModel, mapId: self._mapId }); return m; }, initialize: function (models, opts) { var self = this; checkAndBuildOpts(opts, REQUIRED_OPTS, this); this._bindLayerStyleChanges(); this._attrsForThisTypeMap = { formula: function (model) { return { column: model.get('column'), operation: model.get('operation') || 'max' }; }, category: function (model) { var columnName = model.get('column'); return { aggregation: model.get('aggregation') || 'count', aggregation_column: model.get('aggregation_column') || columnName, column: columnName, widget_style_definition: model.get('widget_style_definition') || WidgetDefinitionModel.getDefaultWidgetStyle('category'), auto_style_definition: undefined }; }, histogram: function (model) { return { column: model.get('column'), bins: model.get('bins') || 10, column_type: 'number', widget_style_definition: model.get('widget_style_definition') || WidgetDefinitionModel.getDefaultWidgetStyle('histogram'), auto_style_definition: undefined }; }, 'time-series': function (model) { return { column: model.get('column'), bins: model.get('bins') || 256, aggregation: model.get('aggregation'), column_type: self.getColumnType(model.get('column'), model.get('source')), widget_style_definition: model.get('widget_style_definition') || WidgetDefinitionModel.getDefaultWidgetStyle('time-series') }; } }; }, url: function () { throw new Error('Not possible, see WidgetDefinitionModel.urlRoot'); }, _bindLayerStyleChanges: function () { this._layerDefinitionsCollection.bind('change:style_properties', this._onLayerStyleChanged, this); }, _onLayerStyleChanged: function (layerDefModel) { var styleModel = layerDefModel.styleModel; var isAllowed = styleModel && styleModel.canApplyAutoStyle(); var affectedWidgets = this.where({ layer_id: layerDefModel.id }); _.each(affectedWidgets, function (widgetDefModel) { var isNowAllowed = widgetDefModel.get('auto_style_allowed'); var willBeAllowed = isAllowed; var attrs = { auto_style_allowed: willBeAllowed }; if (isNowAllowed !== willBeAllowed) { // if autostyle is not allow, we should clean auto_style_definition if (willBeAllowed === false) { attrs = _.extend(attrs, { auto_style_definition: '' }); } widgetDefModel.save(attrs); } }); }, attrsForThisType: function (newType, m) { return this._attrsForThisTypeMap[newType](m); }, resetableAttrsForTypeMap: function (type) { switch (type) { case 'formula': return []; case 'category': return ['aggregation']; case 'histogram': return ['bins', 'column_type']; case 'time-series': return ['bins', 'aggregation', 'column_type']; } }, isThereTimeSeries: function (opts) { opts = opts || {}; var timeSeries = opts.animated ? this.findWhere({ type: 'time-series', animated: opts.animated }) : this.findWhere({ type: 'time-series' }); return !!timeSeries; }, isThereOtherWidgets: function () { return !!this.find(function (widgetModel) { return widgetModel.get('type') !== 'time-series'; }); }, _getNextOrder: function () { if (this.isEmpty()) { return 0; } else { var lastItemByOrder = this.max(function (mdl) { return mdl.get('order'); }); return lastItemByOrder.get('order') + 1; } }, widgetsOwnedByLayer: function (layerId) { var widgets = this.where({ layer_id: layerId }); return widgets.length; }, getColumnType: function (columnName, source) { var column; var node = this._analysisDefinitionNodesCollection.get(source); var schemaModel = node && node.querySchemaModel; if (schemaModel && schemaModel.get('status') === 'fetched') { column = schemaModel.columnsCollection.findWhere({ name: columnName }); } return column && column.get('type'); } });
JavaScript
0.000021
@@ -3809,24 +3809,26 @@ ies':%0A + return %5B'bin
377eb70099db321b36d7c5de67688c797e7e7867
Fix linter errors
lib/assets/core/test/spec/cartodb3/helpers/fetch-all-query-objects.spec.js
lib/assets/core/test/spec/cartodb3/helpers/fetch-all-query-objects.spec.js
var Backbone = require('Backbone'); var fetchAllQueryObjectsIfNecessary = require('../../../../javascripts/cartodb3/helpers/fetch-all-query-objects'); describe('helpers/fetch-all-query-objects', function () { describe('repeated errors', function () { beforeEach(function () { jasmine.Ajax.install(); jasmine.Ajax.stubRequest(new RegExp('^http(s)?.*')) .andReturn({status: 429, responseText: '{"error":["You are over platform\'s limits. Please contact us to know more details"]}'}); spyOn(Backbone.Model.prototype, 'fetch'); }); it('all errored should call callback', function () { var callback = jasmine.createSpy('callback'); var querySchemaModel = jasmine.createSpyObj('querySchemaModel', ['fetch', 'hasRepeatedErrors', 'isFetched', 'shouldFetch']); var queryGeometryModel = jasmine.createSpyObj('queryGeometryModel', ['fetch', 'hasRepeatedErrors', 'isFetched', 'shouldFetch']); var queryRowsCollection = jasmine.createSpyObj('queryRowsCollection', ['fetch', 'hasRepeatedErrors', 'isFetched', 'shouldFetch', 'size']); querySchemaModel.shouldFetch.and.returnValue(false); queryGeometryModel.shouldFetch.and.returnValue(false); queryRowsCollection.shouldFetch.and.returnValue(false); queryRowsCollection.size.and.returnValue(0); querySchemaModel.hasRepeatedErrors.and.returnValue(true); fetchAllQueryObjectsIfNecessary({ queryRowsCollection: queryRowsCollection, queryGeometryModel: queryGeometryModel, querySchemaModel: querySchemaModel }, callback); expect(callback).toHaveBeenCalled(); }); afterEach(function () { jasmine.Ajax.uninstall(); }); }); });
JavaScript
0.000021
@@ -370,16 +370,18 @@ )%0A + .andRetu
d23d04158aecbf7227bc3a6dfb599719f068c420
edit feature: editormodel
lib/assets/javascripts/cartodb3/editor/layers/edit-feature-content-view.js
lib/assets/javascripts/cartodb3/editor/layers/edit-feature-content-view.js
var _ = require('underscore'); var $ = require('jquery'); var CoreView = require('backbone/core-view'); var template = require('./edit-feature-content.tpl'); var EditFeatureActionView = require('./edit-feature-content-views/edit-feature-action-view'); var EditFeatureControlView = require('./edit-feature-content-views/edit-feature-control-view'); var EditFeatureHeaderView = require('./edit-feature-content-views/edit-feature-header-view'); var VisTableModel = require('../../data/visualization-table-model'); var EditFeatureInnerView = require('./edit-feature-content-views/edit-feature-inner-view'); var PanelWithOptionsView = require('../../components/view-options/panel-with-options-view'); var ScrollView = require('../../components/scroll/scroll-view'); var Notifier = require('../../components/notifier/notifier'); var errorParser = require('../../helpers/error-parser'); var NOTIFICATION_ID = 'editFeatureNotification'; var NOTIFICATION_ERROR_TEMPLATE = _.template("<span class='u-errorTextColor'><%- title %></span>"); var REQUIRED_OPTS = [ 'stackLayoutModel', 'layerDefinitionModel', 'configModel', 'mapModeModel', 'editorModel', 'modals' ]; module.exports = CoreView.extend({ className: 'Editor-content', events: { 'click .js-back': 'clean' }, initialize: function (opts) { _.each(REQUIRED_OPTS, function (item) { if (opts[item] === undefined) throw new Error(item + ' is required'); this['_' + item] = opts[item]; }, this); this._featureModel = this._mapModeModel.getFeatureDefinition(); this._tableName = ''; this._url = ''; this._getTable(); this._initBinds(); }, render: function () { this.clearSubViews(); this.$el.html(template()); this._initViews(); return this; }, _initBinds: function () { if (this._querySchemaModel.get('status') !== 'fetched') { // status can be: fetched, unavailable, fetching this._querySchemaModel.bind('change:status', this.render, this); this._querySchemaModel.fetch(); } this._featureModel.bind('updateFeature', this.render, this); this._featureModel.bind('destroyFeature', this._onDestroyFeature, this); this._featureModel.bind('destroyFeatureSuccess', this._onDestroyFeatureSuccess, this); this._featureModel.bind('destroyFeatureFailed', this._onDestroyFeatureFailed, this); this._featureModel.bind('addFeature', this._onAddFeature, this); this._featureModel.bind('saveFeature', this._onSaveFeature, this); this._featureModel.bind('saveFeatureSuccess', this._onSaveFeatureSuccess, this); this._featureModel.bind('saveFeatureFailed', this._onSaveFeatureFailed, this); this.add_related_model(this._featureModel); }, _initViews: function () { if (this._featureModel.isNew()) { this._addRow(); } else { this._renderInfo(); } }, _addRow: function () { this._renderInfo(); }, _renderInfo: function () { this._renderHeader(); this._renderContent(); }, _renderHeader: function () { if (this._headerView) { this.removeView(this._headerView); this._headerView.clean(); } this._headerView = new EditFeatureHeaderView({ url: this._url, tableName: this._tableName, model: this._featureModel, modals: this._modals, isNew: this._featureModel.isNew(), backAction: this.clean.bind(this) }); this.addView(this._headerView); this.$('.js-editFeatureHeader').html(this._headerView.render().el); }, _renderContent: function () { var self = this; if (this._contentView) { this.removeView(this._contentView); this._contentView.clean(); } this._contentView = new PanelWithOptionsView({ className: 'Editor-content', editorModel: self._editorModel, createContentView: function () { return new ScrollView({ createContentView: function () { return new EditFeatureInnerView({ model: self._featureModel, columnsCollection: self._sourceNode.querySchemaModel.columnsCollection }); } }); }, createControlView: function () { return new EditFeatureControlView(); }, createActionView: function () { return new EditFeatureActionView({ featureModel: self._featureModel, model: self.model }); } }); this.addView(this._contentView); this.$('.js-editFeatureContent').html(this._contentView.render().el); }, _onDestroyFeature: function () { if (Notifier.getNotification(NOTIFICATION_ID)) { Notifier.removeNotification(NOTIFICATION_ID); } this.notification = Notifier.addNotification({ id: NOTIFICATION_ID, status: 'loading', info: _t('notifications.edit-feature.destroy.loading'), closable: false }); }, _onDestroyFeatureSuccess: function () { this.notification.set({ status: 'success', info: _t('notifications.edit-feature.destroy.success'), closable: true }); }, _onDestroyFeatureFailed: function (mdl, error) { this.notification.set({ status: 'error', info: NOTIFICATION_ERROR_TEMPLATE({ title: _t('notifications.edit-feature.destroy.error') }), closable: true }); }, _onAddFeature: function () { if (Notifier.getNotification(NOTIFICATION_ID)) { Notifier.removeNotification(NOTIFICATION_ID); } this.notification = Notifier.addNotification({ id: NOTIFICATION_ID, status: 'loading', info: _t('notifications.edit-feature.adding'), closable: false }); }, _onSaveFeature: function () { if (Notifier.getNotification(NOTIFICATION_ID)) { Notifier.removeNotification(NOTIFICATION_ID); } this.notification = Notifier.addNotification({ id: NOTIFICATION_ID, status: 'loading', info: _t('notifications.edit-feature.save.loading'), closable: false }); }, _onSaveFeatureSuccess: function () { this.render(); this.notification.set({ status: 'success', info: _t('notifications.edit-feature.save.success'), closable: true }); }, _onSaveFeatureFailed: function (mdl, error) { this.notification.set({ status: 'error', info: NOTIFICATION_ERROR_TEMPLATE({ title: _t('notifications.edit-feature.save.error') }), closable: true }); }, _getTable: function () { this._sourceNode = this._getSourceNode(); if (this._sourceNode) { var tableName = this._sourceNode.get('table_name'); this._visTableModel = new VisTableModel({ id: tableName, table: { name: tableName } }, { configModel: this._configModel }); this._querySchemaModel = this._sourceNode.querySchemaModel; } if (this._visTableModel) { var tableModel = this._visTableModel.getTableModel(); this._tableName = tableModel.getUnquotedName(); this._url = this._visTableModel && this._visTableModel.datasetURL(); } }, _getSourceNode: function () { var node = this._layerDefinitionModel.getAnalysisDefinitionNodeModel(); var source; if (node.get('type') === 'source') { source = node; } else { var primarySource = node.getPrimarySource(); if (primarySource && primarySource.get('type') === 'source') { source = primarySource; } } return source; }, _destroyContextOverlay: function () { $('.js-editOverlay').fadeOut(200, function () { $('.js-editOverlay').remove(); }); }, clean: function () { this._destroyContextOverlay(); this._mapModeModel.enterViewingMode(); CoreView.prototype.clean.apply(this); } });
JavaScript
0.000003
@@ -1596,16 +1596,74 @@ = '';%0A%0A + this._editorModel.set(%7B%0A edition: false%0A %7D);%0A%0A this
e32e675b1e217a5771b975ff85c1e4f17daa9571
Update benchmark
lib/node_modules/@stdlib/strided/base/unary/benchmark/benchmark.ndarray.js
lib/node_modules/@stdlib/strided/base/unary/benchmark/benchmark.ndarray.js
/** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var bench = require( '@stdlib/bench' ); var randu = require( '@stdlib/random/base/randu' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var pow = require( '@stdlib/math/base/special/pow' ); var round = require( '@stdlib/math/base/special/round' ); var identity = require( '@stdlib/math/base/special/identity' ); var filledarray = require( '@stdlib/array/filled' ); var pkg = require( './../package.json' ).name; var unary = require( './../lib/ndarray.js' ); // VARIABLES // var types = [ 'float64' ]; // FUNCTIONS // /** * Creates a benchmark function. * * @private * @param {PositiveInteger} len - array length * @param {string} xtype - input array data type * @param {string} ytype - output array data type * @returns {Function} benchmark function */ function createBenchmark( len, xtype, ytype ) { var strides; var offsets; var arrays; var shape; var x; var y; var i; x = filledarray( 0.0, len, xtype ); y = filledarray( 0.0, len, ytype ); for ( i = 0; i < len; i++ ) { x[ i ] = round( ( randu()*200.0 ) - 100.0 ); } arrays = [ x, y ]; shape = [ len ]; strides = [ 1, 1 ]; offsets = [ 0, 0 ]; return benchmark; /** * Benchmark function. * * @private * @param {Benchmark} b - benchmark instance */ function benchmark( b ) { var i; b.tic(); for ( i = 0; i < b.iterations; i++ ) { unary( arrays, shape, strides, offsets, identity ); if ( isnan( y[ i%len ] ) ) { b.fail( 'should not return NaN' ); } } b.toc(); if ( isnan( arrays[ 1 ][ i%len ] ) ) { b.fail( 'should not return NaN' ); } b.pass( 'benchmark finished' ); b.end(); } } // MAIN // /** * Main execution sequence. * * @private */ function main() { var len; var min; var max; var t1; var t2; var f; var i; var j; min = 1; // 10^min max = 6; // 10^max for ( j = 0; j < types.length; j++ ) { t1 = types[ j ]; t2 = types[ j ]; for ( i = min; i <= max; i++ ) { len = pow( 10, i ); f = createBenchmark( len, t1, t2 ); bench( pkg+':ndarray:len='+len+',xtype='+t1+',ytype='+t2, f ); } } } main();
JavaScript
0.000001
@@ -685,21 +685,31 @@ );%0Avar -randu +discreteUniform = requi @@ -737,16 +737,35 @@ ase/ -randu' ) +discrete-uniform' ).factory ;%0Ava @@ -878,66 +878,8 @@ );%0A -var round = require( '@stdlib/math/base/special/round' );%0A var @@ -934,24 +934,24 @@ dentity' );%0A - var filledar @@ -987,24 +987,82 @@ /filled' );%0A +var filledarrayBy = require( '@stdlib/array/filled-by' );%0A var pkg = re @@ -1559,24 +1559,16 @@ %0A%09var y; -%0A%09var i; %0A%0A%09x = f @@ -1573,30 +1573,27 @@ filledarray -( 0.0, +By( len, xtype @@ -1587,24 +1587,54 @@ ( len, xtype +, discreteUniform( -100, 100 ) );%0A%09y = fil @@ -1666,88 +1666,8 @@ );%0A -%09for ( i = 0; i %3C len; i++ ) %7B%0A%09%09x%5B i %5D = round( ( randu()*200.0 ) - 100.0 );%0A%09%7D %0A%09ar
054242dd06e4676cdb6a3def31cb5e2c42f7bdc9
fix gulp init src path
buildsys/tasks/init.js
buildsys/tasks/init.js
/** * ./buildsys/tasks/init.js * @author Keenan Staffieri * ------------------------------------ * TASK: Init * 'gulp init' */ /* $ gulp init */ gulp.task('init', function () { // return gulp.src('./node_modules/holly-craft/templates/src/**/*') return gulp.src('./templates/src/**/*') .pipe(gulp.dest(config.root)) })
JavaScript
0.000001
@@ -182,11 +182,8 @@ %7B%0A - // ret @@ -248,50 +248,8 @@ *')%0A - return gulp.src('./templates/src/**/*')%0A
1f22875259343aebc04c9fe2bb8dc5d201d3e97d
simplify plugin components registration
components/plugin.js
components/plugin.js
export default function (components) { let map = Object.values(components).reduce( (result, component) => { return Object.assign(result, { [component.name]: component }) }, {}) return { install: (vm) => { for (let key in map) { vm.component(key, map[key]) } }, components: map } }
JavaScript
0.000013
@@ -37,253 +37,165 @@ %7B %0A -%0A -let map = Object.values(components).reduce( (result, component) =%3E %7B%0A return Object.assign(result, %7B %5Bcomponent.name%5D: component %7D)%0A %7D, %7B%7D)%0A%0A return %7B%0A install: (vm) =%3E %7B%0A for (let key in map) %7B%0A vm.component(key, map%5Bkey%5D +return %7B%0A install: (vm) =%3E %7B%0A for (let key in components) %7B%0A let component = components%5Bkey%5D%0A vm.component(component.name,component )%0A @@ -225,13 +225,8 @@ ents -: map %0A %7D
220a50f22452fc4128d98c91722e4506b60e5673
fix bug in login analytics tracking
src/ui/LoginPage.js
src/ui/LoginPage.js
/** @jsx React.DOM */ var Button = require('react-bootstrap').Button; var Link = require('react-router').Link; var React = require('react'); var LoginPage = React.createClass({ getInitialState: function() { return { message: "", messageType: "" } }, handleFBLogin: function() { this.setState({ message:"Logging you in...", messageType:"info" }); Parse.FacebookUtils.logIn(null, { success: function(user) { Parse.Analytics.track('FBLoginSuccess', {error:error}); FB.api('/me', function(response) { user.set('fbProfile', response); user.save(null, {success:function() { window.location = "/"; }}); }); }, error: function(user, error) { Parse.Analytics.track('FBLoginFail', {error:error}); } }); }, handleLogin: function() { this.setState({ message:"Logging you in...", messageType:"info" }); Parse.User.logIn( this.refs.username.getDOMNode().value, this.refs.password.getDOMNode().value, { success: function(user) { this.setState({ message:"Great success!", messageType:"success" }); window.location = "/"; }.bind(this), error: function(user, error) { this.setState({ message:"There was an error while logging you in: "+error.code+" "+error.message, messageType:"danger" }); }.bind(this) } ); }, componentDidMount: function() { this.refs.username.getDOMNode().focus(); }, render: function() { var alert = null; if (this.state.message) { alert = <div className={"alert alert-"+this.state.messageType}>{this.state.message}</div> } return ( <div className="row loginPage"> <div className="col-md-3"/> <div className="col-md-6"> <div className="jumbotron"> <h1>Log In!</h1> {alert} <form> <div className="form-group"> <Button bsStyle="primary" onClick={this.handleFBLogin}>Login with Facebook</Button> </div> <div className="form-group"> <label>Username:</label> <input ref="username" type="text" className="form-control" placeholder="Enter username" /> </div> <div className="form-group"> <label>Password:</label> <input ref="password" type="password" className="form-control" placeholder="Password" /> </div> <Button onClick={this.handleLogin}> Log In </Button> or <Link to="signup">Sign Up</Link> or <Link to="login-anonymously">Continue Anonymously</Link> </form> </div> </div> </div> ); } }); module.exports = LoginPage;
JavaScript
0
@@ -503,35 +503,24 @@ nSuccess', %7B -error:error %7D);%0A
47f7a6935639d99ad86bf30a10f47d753535eacf
Improve filtering method
App/Components/LatestRepos.js
App/Components/LatestRepos.js
'use strict'; var React = require('react-native'); var _ = require('underscore'); var Api = require('../Utils/Api'); var AuthStore = require('../Stores/Auth'); var Loading = require('./Loading'); var RepoItem = require('./RepoItem'); var { StyleSheet, View, ListView, SegmentedControlIOS } = React; var LatestRepos = React.createClass({ displayName: 'LatestRepos', getInitialState: function() { return { loading: false, isLoggedIn: { os: AuthStore.isLoggedIn(false), pro: AuthStore.isLoggedIn(true) }, repos: [], reposSource: new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, }).cloneWithRows([]), showType: 'All' }; }, componentWillMount: function() { this.fetchData(); }, fetchData: function () { var self = this; this.setState({ loading: true }); var updatedRepos = []; if (this.state.isLoggedIn.os) { Api.getLatest(false) .then(function (res) { _.each(res.repos, function(element, index) { _.extend(element, {isPro: false}); updatedRepos.push(element); }); self.setState({ loading: false, repos: updatedRepos, reposSource: self.state.reposSource.cloneWithRows(updatedRepos) }); }); } if (this.state.isLoggedIn.pro) { Api.getLatest(true) .then(function (res) { console.log(res.repos); _.each(res.repos, function(element, index) { _.extend(element, {isPro: true}); updatedRepos.push(element); }); self.setState({ loading: false, repos: updatedRepos, reposSource: self.state.reposSource.cloneWithRows(updatedRepos) }); }); } }, _onSegmentChange: function (value) { switch(value) { case 'Open Source': var filtered = _.filter(this.state.repos, function(obj) { return obj.isPro == false; }); this.setState({ loading: false, reposSource: this.state.reposSource.cloneWithRows(filtered), showType: 'Pro' }); break; case 'Travis Pro': var filtered = _.filter(this.state.repos, function(obj) { return obj.isPro == true; }); this.setState({ loading: false, reposSource: this.state.reposSource.cloneWithRows(filtered), showType: 'Pro' }); break; default: this.setState({ loading: false, reposSource: this.state.reposSource.cloneWithRows(this.state.repos), showType: 'All' }); } }, _renderHeader: function () { return ( <View style={styles.segmentWrapper}> <SegmentedControlIOS values={['All', 'Open Source', 'Travis Pro']} tintColor='#FFF' selectedIndex={0} onValueChange={this._onSegmentChange} /> </View> ); }, _renderBuildRow: function (rowData: string, sectionID: number, rowID: number) { return ( <RepoItem details={rowData} isPro={rowData.isPro} navigator={this.props.navigator} /> ); }, _renderSeparator: function ( sectionID: number | string, rowID: number | string, adjacentRowHighlighted: boolean ) { return ( <View key={'SEP_' + sectionID + '_' + rowID} style={styles.separator} /> ); }, render: function() { if (this.state.loading) { return ( <Loading text='Latest' /> ); } return ( <ListView dataSource={this.state.reposSource} renderRow={this._renderBuildRow} renderHeader={this._renderHeader} renderSeparator={this._renderSeparator} /> ); } }); var styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#F5FCFF' }, segmentWrapper: { padding: 10, backgroundColor: '#357389' }, separator: { height: 2, backgroundColor: '#e9e9e9' } }); module.exports = LatestRepos;
JavaScript
0.000064
@@ -1464,42 +1464,8 @@ ) %7B%0A - console.log(res.repos);%0A @@ -1820,32 +1820,27 @@ %7D,%0A%0A -_onSegmentChange +filterRepos : functi @@ -1843,29 +1843,29 @@ nction ( -value +isPro ) %7B%0A switch(v @@ -1860,61 +1860,85 @@ -switch(value) %7B%0A case 'Open Source':%0A +var filtered = this.state.repos;%0A%0A if (typeof isPro === 'boolean') %7B%0A -var fil @@ -1954,32 +1954,24 @@ .filter( -this.sta +fil te -. re -pos +d , functi @@ -1972,34 +1972,32 @@ function(obj) %7B%0A - return o @@ -2012,17 +2012,15 @@ == -false;%0A +isPro;%0A @@ -2017,37 +2017,39 @@ sPro;%0A %7D);%0A -%0A +%7D%0A%0A this.setStat @@ -2056,38 +2056,8 @@ e(%7B%0A - loading: false,%0A @@ -2127,190 +2127,157 @@ - showType: 'Pro'%0A %7D);%0A break;%0A case 'Travis Pro':%0A var filtered = _.filter(this.state.repos, function(obj) %7B%0A return obj.isPro == true +%7D);%0A %7D,%0A%0A _onSegmentChange: function (value) %7B%0A switch(value) %7B%0A case 'Open Source':%0A this.filterRepos(false);%0A break ;%0A %7D) @@ -2276,368 +2276,114 @@ - - %7D);%0A%0A this.setState(%7B%0A loading: false,%0A reposSource: this.state.reposSource.cloneWithRows(filtered),%0A showType: 'Pro'%0A %7D);%0A break;%0A default:%0A this.setState(%7B%0A loading: false,%0A reposSource: this.state.reposSource.cloneWithRows(this.state.repos),%0A showType: 'All'%0A %7D +case 'Travis Pro':%0A this.filterRepos(true);%0A break;%0A default:%0A this.filterRepos( );%0A
bd81f986485521a439ebaf566c06530e30b8470c
Format with prettier
src/utils/logger.js
src/utils/logger.js
const chalk = require('chalk'); const emoji = require('node-emoji') const clear = () => { process.stdout.write('\u001B[2J\u001B[0;0f'); }; const printLogo = (enchance = chalk.blue) => { console.log(enchance( ' _ _\n' + '| |__ __ _ _ _| |\n' + '| \'_ \\ / _\` | | | | |\n' + '| | | | (_| | |_| | |\n' + '|_| |_|\\__,_|\\__,_|_|\n' + '\n' )); }; // @TODO: create haul-debug.log with logged errors /** * If argument to log is a string it will be emojified, which will replace every :<emoji>: * with actul emoji. All supported emojis are listed here: * https://raw.githubusercontent.com/omnidan/node-emoji/master/lib/emoji.json */ const loggerFactory = (enchance, prefix) => (...args) => { console.log(`${enchance(prefix)}`, ...args.map( arg => typeof arg === 'string' ? emoji.emojify(arg) : arg )); }; module.exports = (devMode) => ({ clear, printLogo, info: loggerFactory(chalk.cyan, 'info', devMode), warn: loggerFactory(chalk.yellow, 'warning', devMode), error: loggerFactory(chalk.red, 'error', true), success: loggerFactory(chalk.green, 'success', devMode), });
JavaScript
0.000001
@@ -19,15 +19,15 @@ ire( -' +%22 chalk -' +%22 );%0Ac @@ -47,17 +47,17 @@ require( -' +%22 node-emo @@ -58,18 +58,19 @@ de-emoji -') +%22); %0A%0Aconst @@ -108,17 +108,17 @@ t.write( -' +%22 %5Cu001B%5B2 @@ -129,17 +129,17 @@ 01B%5B0;0f -' +%22 );%0A%7D;%0A%0Ac @@ -198,16 +198,21 @@ ole.log( +%0A enchance @@ -219,17 +219,17 @@ (%0A -' +%22 _ @@ -242,25 +242,29 @@ _%5Cn -' +%22 + %0A -+ ' + %22 %7C %7C__ @@ -282,20 +282,23 @@ %7C%5Cn -' +%22 + %0A -+ ' + %22 %7C -%5C '_ %5C @@ -316,25 +316,29 @@ %7C %7C %7C%5Cn -' +%22 + %0A -+ ' + %22 %7C %7C %7C %7C @@ -352,25 +352,29 @@ _%7C %7C %7C%5Cn -' +%22 + %0A -+ ' + %22 %7C_%7C %7C_%7C%5C @@ -394,24 +394,33 @@ _%7C%5Cn -'%0A + '%5Cn'%0A ) +%22 +%0A %22%5Cn%22%0A )%0A );%0A%7D @@ -753,16 +753,18 @@ efix) =%3E +%0A (...arg @@ -767,24 +767,26 @@ .args) =%3E %7B%0A + console.lo @@ -787,16 +787,23 @@ ole.log( +%0A %60$%7Bencha @@ -816,16 +816,22 @@ efix)%7D%60, +%0A ...args @@ -835,21 +835,16 @@ rgs.map( -%0A arg =%3E t @@ -861,16 +861,16 @@ === -' +%22 string -' +%22 ? e @@ -896,20 +896,23 @@ arg +) %0A -) + );%0A + %7D;%0A%0A -%0A modu @@ -928,17 +928,15 @@ s = -( devMode -) =%3E @@ -998,14 +998,14 @@ an, -' +%22 info -' +%22 , de @@ -1052,17 +1052,17 @@ ow, -' +%22 warning -' +%22 , de @@ -1107,15 +1107,15 @@ ed, -' +%22 error -' +%22 , tr @@ -1161,17 +1161,17 @@ en, -' +%22 success -' +%22 , de @@ -1180,9 +1180,9 @@ ode) -, %0A%7D); +%0A
d0d5d7ebc9c17c50f682b06dd1319c855e4e5944
Fix timestamps and durations.
src/utils/timing.js
src/utils/timing.js
/* @flow */ import type { TimingItemType } from '../types'; const timingMap: { [string]: number } = {}; const log: TimingItemType[] = []; const now = (): number => typeof performance !== 'undefined' ? performance.now() : Date.now() / 1000; const add = (item: TimingItemType) => { log.push(item); }; const start = (key: string) => { timingMap[key] = now(); }; const end = (key: string) => { if (timingMap[key]) { add({ text: key, start: timingMap[key], end: now(), }); delete timingMap[key]; } }; export default { add, start, end, log, };
JavaScript
0.000179
@@ -137,113 +137,8 @@ %5D;%0A%0A -const now = (): number =%3E%0A typeof performance !== 'undefined' ? performance.now() : Date.now() / 1000;%0A%0A cons @@ -173,16 +173,16 @@ e) =%3E %7B%0A + log.pu @@ -247,16 +247,21 @@ %5Bkey%5D = +Date. now();%0A%7D @@ -374,16 +374,16 @@ p%5Bkey%5D,%0A - en @@ -385,16 +385,21 @@ end: +Date. now(),%0A
30b64d736fc1b44e4d2bdaad78112551bff375ce
Remove group timers.
src/utils/timing.js
src/utils/timing.js
/* @flow */ import type { TimingItemType } from '../types'; const timingMap: { [string]: number } = {}; const countMap: { [string]: number } = {}; const log: TimingItemType[] = []; const now = (): number => typeof performance !== 'undefined' ? performance.now() : Date.now() / 1000; const add = (item: TimingItemType) => { log.push(item); }; const start = (key: string) => { timingMap[key] = now(); }; const startGroup = (key: string) => { timingMap[key] = now(); if (countMap[key]) { countMap[key]++; } else { countMap[key] = 1; } }; const end = (key: string) => { if (timingMap[key]) { add({ text: key, start: timingMap[key], end: now(), }); delete timingMap[key]; } }; const endGroup = (key: string) => { if (countMap[key] % 10 === 0) { end(key); } }; export default { add, startGroup, start, end, endGroup, log, };
JavaScript
0.000003
@@ -102,51 +102,8 @@ %7B%7D;%0A -const countMap: %7B %5Bstring%5D: number %7D = %7B%7D;%0A cons @@ -367,158 +367,8 @@ %7D;%0A%0A -const startGroup = (key: string) =%3E %7B%0A timingMap%5Bkey%5D = now();%0A if (countMap%5Bkey%5D) %7B%0A countMap%5Bkey%5D++;%0A %7D else %7B%0A countMap%5Bkey%5D = 1;%0A %7D%0A%7D;%0A%0A cons @@ -539,164 +539,46 @@ %7D;%0A%0A -const endGroup = (key: string) =%3E %7B%0A if (countMap%5Bkey%5D %25 10 === 0) %7B%0A end(key);%0A %7D%0A%7D;%0A%0Aexport default %7B%0A add,%0A startGroup,%0A start,%0A end,%0A endGroup +export default %7B%0A add,%0A start,%0A end ,%0A
20f770efee1906c7f33d1093b60f492f2120663c
implement gestureHandling
Kwc/Advanced/GoogleMapView/Component.defer.js
Kwc/Advanced/GoogleMapView/Component.defer.js
var $ = require('jQuery'); var onReady = require('kwf/on-ready'); var gmapLoader = require('kwf/google-map/loader'); var gmapMap = require('kwf/google-map/map'); var renderMap = function(el) { var cfg = el.find(".options", true); if (!cfg.length) return; cfg = $.parseJSON(cfg.val()); var text = el.find("div.text"); cfg.mapContainer = el; if (!cfg.markers) { cfg.markers = { longitude : cfg.longitude, latitude : cfg.latitude, autoOpenInfoWindow: cfg.autoOpenInfoWindow }; if (text.length) cfg.markers.infoHtml = text.html(); } var cls = eval(cfg.mapClass) || gmapMap; var myMap = new cls(cfg); gmapLoader(function() { this.show(); }, myMap); return myMap; }; onReady.onRender('.kwcClass', function(el) { el.data('gmapObject', renderMap(el)); }, { checkVisibility: true }); onReady.onRender('.kwcClass', function (el) { var mobileOverlayOpen = el.find('.mobileOverlayOpen'); var mobileOverlayClose = el.find('.mobileOverlayClose'); mobileOverlayOpen.click(function (ev) { if ($(this).is(':visible')) { var newEl = $(this).parent(); newEl.addClass('navigate'); $('html, body').animate({ scrollTop: newEl.offset().top }, 400, function() { google.maps.event.trigger(newEl.data('gmapObject').gmap, 'resize'); }); } }); mobileOverlayClose.on('touchstart click', function (ev) { if ($(this).is(':visible')) { var newEl = $(this).parent(); newEl.removeClass('navigate'); $('html, body').animate({ scrollTop: newEl.offset().top - (($(window).innerHeight() - newEl.height()) / 2) }); } }); });
JavaScript
0
@@ -187,17 +187,16 @@ n(el) %7B%0A -%0A var @@ -1817,12 +1817,414 @@ %7D);%0A%7D);%0A +%0AonReady.onResize('.kwcClass', function (el) %7B%0A if (el.hasClass('optimizedMobileUI')) %7B%0A var map = el.data('gmapObject');%0A if (map && map.gmap) %7B // gmap will be set once it's rendered%0A var gestureHandling = el.hasClass('gt700') ? 'auto' : 'greedy';%0A map.gmap.set('gestureHandling', gestureHandling);%0A %7D%0A %7D%0A%7D, %7B priority: 5 /* after responsive-el */%7D);%0A
1c74353b8c666fc9d50dced8b8ef1ee37818581f
update user profile data after linking account
examples/client/controllers/profile.js
examples/client/controllers/profile.js
angular.module('MyApp') .controller('ProfileCtrl', function($scope, $auth, $alert, Account) { /** * Get user's profile information. */ $scope.getProfile = function() { Account.getProfile() .success(function(data) { $scope.user = data; }) .error(function() { $alert({ content: 'Unable to get user information', animation: 'fadeZoomFadeDown', type: 'material', duration: 3 }); }); }; /** * Update user's profile information. */ $scope.updateProfile = function() { Account.updateProfile({ displayName: $scope.user.displayName, email: $scope.user.email }).then(function() { $alert({ content: 'Profile has been updated', animation: 'fadeZoomFadeDown', type: 'material', duration: 3 }); }); }; /** * Link third-party provider. */ $scope.link = function(provider) { $auth.link(provider) .then(function() { $alert({ content: 'You have successfully linked ' + provider + ' account', animation: 'fadeZoomFadeDown', type: 'material', duration: 3 }); }) .catch(function(response) { $alert({ content: response.data.message, animation: 'fadeZoomFadeDown', type: 'material', duration: 3 }); }); }; /** * Unlink third-party provider. */ $scope.unlink = function(provider) { $auth.unlink(provider) .then(function() { $alert({ content: 'You have successfully unlinked ' + provider + ' account', animation: 'fadeZoomFadeDown', type: 'material', duration: 3 }); }) .then(function() { $scope.getProfile(); }) .catch(function(response) { $alert({ content: response.data ? response.data.message : 'Could not unlink ' + provider + ' account', animation: 'fadeZoomFadeDown', type: 'material', duration: 3 }); }); }; $scope.getProfile(); });
JavaScript
0
@@ -1291,32 +1291,101 @@ %7D);%0A %7D)%0A + .then(function() %7B%0A $scope.getProfile();%0A %7D)%0A .catch(f
a7aca81f8e578b703c813aeaf7658a6546fb66b8
Fix broken solution for iterator_for_of.
exercises/iterator_for_of/solution/solution.js
exercises/iterator_for_of/solution/solution.js
const max = process.argv[2]; let FizzBuzz = { [Symbol.iterator]() { let num = 1; return { next() { let value = num; if (value % 15 === 0) { value = 'FizzBuzz'; } else if (value % 3 === 0) { value = 'Fizz'; } else if (value % 5 === 0) { value = 'Buzz'; } if (num <= max) return { done: false, value: value }; num++; return { done: true }; } } } } for (var n of FizzBuzz) { console.log(n); }
JavaScript
0
@@ -5,16 +5,17 @@ t max = ++ process. @@ -105,24 +105,92 @@ next() %7B%0A + if (num %3E max) %7B%0A return %7B done: true %7D;%0A %7D%0A let @@ -414,23 +414,21 @@ -if (num %3C= max) +num++;%0A re @@ -467,54 +467,8 @@ %7D;%0A - num++;%0A return %7B done: true %7D;%0A
9e625f42488260f19d7a1af768b0312bfdc17e6c
fix weight accumulation.
examples/js/postprocessing/MSAAPass.js
examples/js/postprocessing/MSAAPass.js
/** * @author bhouston / http://clara.io/ * */ THREE.MSAAPass = function ( scene, camera, params ) { this.scene = scene; this.camera = camera; this.sampleLevel = 4; // specified as n, where the number of samples is 2^n, so sampleLevel = 4, is 2^4 samples, 16. this.params = params || { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat }; this.params.minFilter = THREE.NearestFilter; this.params.maxFilter = THREE.NearestFilter; console.log( 'this.params', this.params ); this.enabled = true; this.needsSwap = true; if ( THREE.CompositeShader === undefined ) { console.error( "THREE.MSAAPass relies on THREE.CompositeShader" ); } var compositeShader = THREE.CompositeShader; this.uniforms = THREE.UniformsUtils.clone( compositeShader.uniforms ); this.materialComposite = new THREE.ShaderMaterial( { uniforms: this.uniforms, vertexShader: compositeShader.vertexShader, fragmentShader: compositeShader.fragmentShader, transparent: true, blending: THREE.CustomBlending, blendSrc: THREE.OneFactor, blendDst: THREE.OneMinusSrcAlphaFactor, blendEquation: THREE.AddEquation, depthTest: false, depthWrite: false } ); this.camera2 = new THREE.OrthographicCamera( -1, 1, 1, -1, 0, 1 ); this.scene2 = new THREE.Scene(); this.quad2 = new THREE.Mesh( new THREE.PlaneGeometry( 2, 2 ), this.materialComposite ); this.scene2.add( this.quad2 ); }; THREE.MSAAPass.prototype = { dispose: function() { if( this.sampleRenderTarget ) { this.sampleRenderTarget.dispose(); this.sampleRenderTarget = null; } }, setSize: function ( width, height ) { this.sampleRenderTarget.setSize( width, height ); }, render: function ( renderer, writeBuffer, readBuffer, delta ) { if( ! this.sampleRenderTarget ) { this.sampleRenderTarget = new THREE.WebGLRenderTarget( readBuffer.width, readBuffer.height, this.params, "msaa.renderTarget0" ); } var camera = ( this.camera || this.scene.camera ); var jitterOffsets = THREE.MSAAPass.JitterVectors[ Math.max( 0, Math.min( this.sampleLevel, 5 ) ) ]; this.uniforms[ "tForeground" ].value = this.sampleRenderTarget; var weight = 1.0; // render the scene multiple times, each slightly jitter offset from the last and accumulate the results. for( var i = 0; i < jitterOffsets.length; i ++ ) { // only jitters perspective cameras. TODO: add support for jittering orthogonal cameras if( camera.setViewOffset ) camera.setViewOffset( readBuffer.width, readBuffer.height, jitterOffsets[i].x, jitterOffsets[i].y, readBuffer.width, readBuffer.height ); renderer.render( this.scene, camera, this.sampleRenderTarget, true ); // this accumulation strategy is used to prevent decimation at low bit depths with lots of samples. this.uniforms[ "scale" ].value = weight; weight *= 0.5; // clear on the first render, accumulate the others var autoClear = renderer.autoClear; renderer.autoClear = false; renderer.render( this.scene2, this.camera2, writeBuffer, i === 0 ); renderer.autoClear = true; } // reset jitter to nothing. TODO: add support for orthogonal cameras if( camera.setViewOffset ) camera.setViewOffset( undefined, undefined, undefined, undefined, undefined, undefined ); } }; THREE.MSAAPass.normalizedJitterOffsets = function( jitterVectors ) { var scaledJitterOffsets = []; for( var i = 0; i < jitterVectors.length; i ++ ) { scaledJitterOffsets.push( new THREE.Vector2( jitterVectors[i][0], jitterVectors[i][1] ).multiplyScalar( 1.0 / 16.0 ) ); } return scaledJitterOffsets; }, // These jitter vectors are specified in integers because it is easier. // I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5) // before being used, thus these integers need to be scaled by 1/16. // // Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 THREE.MSAAPass.JitterVectors = [ THREE.MSAAPass.normalizedJitterOffsets( [ [ 0, 0 ] ] ), THREE.MSAAPass.normalizedJitterOffsets( [ [ 4, 4 ], [ -4, -4 ] ] ), THREE.MSAAPass.normalizedJitterOffsets( [ [ -2, -6 ], [ 6, -2 ], [ -6, 2 ], [ 2, 6 ] ] ), THREE.MSAAPass.normalizedJitterOffsets( [ [ 1, -3 ], [ -1, 3 ], [ 5, 1 ], [ -3, -5 ], [ -5, 5 ], [ -7, -1 ], [ 3, 7 ], [ 7, -7 ] ] ), THREE.MSAAPass.normalizedJitterOffsets( [ [ 1, 1 ], [ -1, -3 ], [ -3, 2 ], [ 4, -1 ], [ -5, -2 ], [ 2, 5 ], [ 5, 3 ], [ 3, -5 ], [ -2, 6 ], [ 0, -7 ], [ -4, -6 ], [ -6, 4 ], [ -8, 0 ], [ 7, -4 ], [ 6, 7 ], [ -7, -8 ] ] ), THREE.MSAAPass.normalizedJitterOffsets( [ [ -4, -7 ], [ -7, -5 ], [ -3, -5 ], [ -5, -4 ], [ -1, -4 ], [ -2, -2 ], [ -6, -1 ], [ -4, 0 ], [ -7, 1 ], [ -1, 2 ], [ -6, 3 ], [ -3, 3 ], [ -7, 6 ], [ -3, 6 ], [ -5, 7 ], [ -1, 7 ], [ 5, -7 ], [ 1, -6 ], [ 6, -5 ], [ 4, -4 ], [ 2, -3 ], [ 7, -2 ], [ 1, -1 ], [ 4, -1 ], [ 2, 1 ], [ 6, 2 ], [ 0, 4 ], [ 4, 4 ], [ 2, 5 ], [ 7, 5 ], [ 5, 6 ], [ 3, 7 ] ] ) ];
JavaScript
0.000001
@@ -2918,14 +2918,21 @@ ght -* = -0.5 +1.0 / (i+1) ;%0A%0A
166840f8be41671fdbcb53e1c68604d25e7c17e6
use npmRequestOptions
examples/localmarket/lib/activities.js
examples/localmarket/lib/activities.js
Activities = new Mongo.Collection('activities'); Activities.allow({ insert: function(userId, doc) { return doc.userId === userId; } }); Activities.latest = function() { return Activities.find({}, {sort: {date: -1}, limit: 1}); } Meteor.methods({ createActivity: function(activity, tweet, loc) { check(Meteor.userId(), String); check(activity, { recipeName: String, text: String, image: String }); check(tweet, Boolean); check(loc, Match.OneOf(Object, null)); activity.userId = Meteor.userId(); activity.userAvatar = Meteor.user().services.twitter.profile_image_url_https; activity.userName = Meteor.user().profile.name; activity.date = new Date; if (! this.isSimulation && loc) activity.place = getLocationPlace(loc); var id = Activities.insert(activity); if (! this.isSimulation && tweet) tweetActivity(activity); return id; } }); if (Meteor.isServer) { // Uses the Npm request module directly as provided by the http package if (! HTTPInternals.NpmModules.request.version.match(/^2\.(\d+)/)) { // maybe it doesn't have the same API any more? throw Error("http upgraded request to a new major version"); } var Request = Meteor.wrapAsync(HTTPInternals.NpmModules.request.module); var callTwitter = function(options) { var config = Meteor.settings.twitter var userConfig = Meteor.user().services.twitter; options.oauth = { consumer_key: config.consumerKey, consumer_secret: config.secret, token: userConfig.accessToken, token_secret: userConfig.accessTokenSecret }; return Request(options); } var tweetActivity = function(activity) { // creates the tweet text, optionally truncating to fit the appended text function appendTweet(text, append) { var MAX = 117; // Max size of tweet with image attached if ((text + append).length > MAX) return text.substring(0, (MAX - append.length - 3)) + '...' + append; else return text + append; } // we need to strip the "data:image/jpeg;base64," bit off the data url var image = activity.image.replace(/^data.*base64,/, ''); var response = callTwitter({ method: 'post', url: 'https://upload.twitter.com/1.1/media/upload.json', form: { media: image } }); if (response.statusCode !== 200) throw new Meteor.Error(500, 'Unable to post image to twitter'); var attachment = JSON.parse(response.body); var response = callTwitter({ method: 'post', url: 'https://api.twitter.com/1.1/statuses/update.json', form: { status: appendTweet(activity.text, ' #localmarket'), media_ids: attachment.media_id_string } }); if (response.statusCode !== 200) throw new Meteor.Error(500, 'Unable to create tweet'); } var getLocationPlace = function(loc) { var url = 'https://api.twitter.com/1.1/geo/reverse_geocode.json' + '?granularity=neighborhood' + '&max_results=1' + '&accuracy=' + loc.coords.accuracy + '&lat=' + loc.coords.latitude + '&long=' + loc.coords.longitude; var response = callTwitter({ method: 'get', url: url }); if (response.statusCode === 200) { var data = JSON.parse(response.body); var place = _.find(data.result.places, function(place) { return place.place_type === 'neighborhood'; }); return place && place.full_name; } } } // Initialize a seed activity Meteor.startup(function() { if (Meteor.isServer && Activities.find().count() === 0) { Activities.insert({ recipeName: 'summer-apricots-honey-panna-cotta', text: 'I substituted strawberries for apricots - incredible!', image: '/img/activity/activity-placeholder-strawberry-640x640.jpg', userAvatar: 'https://avatars3.githubusercontent.com/u/204768?v=2&s=400', userName: 'Matt Debergalis', place: 'SoMA, San Francisco', date: new Date }); } });
JavaScript
0.000001
@@ -979,368 +979,24 @@ %7B%0A -// Uses the Npm request module directly as provided by the http package%0A%0A if (! HTTPInternals.NpmModules.request.version.match(/%5E2%5C.(%5Cd+)/)) %7B%0A // maybe it doesn't have the same API any more?%0A throw Error(%22http upgraded request to a new major version%22);%0A %7D%0A var Request = Meteor.wrapAsync(HTTPInternals.NpmModules.request.module);%0A %0A var callTwitter +var twitterOauth = f @@ -1117,23 +1117,14 @@ -options.oauth = +return %7B%0A @@ -1296,38 +1296,8 @@ %7D; -%0A%0A return Request(options); %0A %7D @@ -1862,54 +1862,24 @@ e = -callTwitter(%7B%0A method: 'post',%0A +HTTP.post(%0A -url: 'ht @@ -1926,27 +1926,33 @@ d.json', + %7B %0A -form + params : %7B medi @@ -1961,22 +1961,83 @@ image %7D +, %0A -%7D + npmRequestOptions: %7B oauth: twitterOauth() %7D%0A %7D%0A );%0A %0A @@ -2152,36 +2152,14 @@ -var attachment = JSON.parse( +if (! resp @@ -2167,85 +2167,161 @@ nse. -body); +data) %0A -%0A - var response = callT +throw new Meteor.Error(500, 'Did not receive attachment from t witter -(%7B +');%0A %0A - method: ' +var attachment = response.data;%0A%0A response = HTTP. post -', +( %0A - url: 'ht @@ -2372,19 +2372,25 @@ on', + %7B %0A -form + params : %7B%0A @@ -2397,16 +2397,18 @@ + + status: @@ -2460,16 +2460,18 @@ + media_id @@ -2510,15 +2510,78 @@ + %7D,%0A npmRequestOptions: %7B oauth: twitterOauth() %7D%0A %7D%0A -%7D );%0A%0A @@ -3006,45 +3006,95 @@ e = -callTwitter(%7B method: 'get', url: url +HTTP.get(url,%0A %7BnpmRequestOptions: %7B oauth: twitterOauth() %7D %7D); @@ -3134,40 +3134,12 @@ 200 -) %7B%0A var data = JSON.parse( + && resp @@ -3147,14 +3147,15 @@ nse. -body); +data) %7B %0A @@ -3176,16 +3176,25 @@ _.find( +response. data.res
9221616ed65400e83269c85aff6f3cc80eb6cf78
Fix reference to tickCount
packages/vega-schema/src/legend.js
packages/vega-schema/src/legend.js
import {layoutAlign} from './layout'; import { numberValue, stringValue, colorValue, alignValue, baselineValue, fontWeightValue, numberOrSignal, stringOrSignal, arrayOrSignal, anyOf, allOf, def, enums, object, pattern, required, ref, type, numberType, stringType } from './util'; // types defined elsewhere const encodeEntryRef = def('encodeEntry'); const styleRef = ref('style'); const labelOverlapRef = ref('labelOverlap'); const tickCountRef = ref('tickCountRef'); const guideEncodeRef = def('guideEncode'); const guideEncode = pattern( object({ name: stringType, interactive: type('boolean', {default: false}), style: styleRef }), { '^(?!interactive|name|style).+$': encodeEntryRef } ); const legendTypeEnum = ['gradient', 'symbol']; const legendDirectionEnum = ['vertical', 'horizontal']; const legendOrientEnum = [ 'none', 'left', 'right', 'top', 'bottom', 'top-left', 'top-right', 'bottom-left', 'bottom-right' ]; const legendProps = object({ size: stringType, shape: stringType, fill: stringType, stroke: stringType, opacity: stringType, strokeDash: stringType, strokeWidth: stringType, type: enums(legendTypeEnum), direction: enums(legendDirectionEnum), orient: enums(legendOrientEnum, {default: 'right'}), format: stringOrSignal, title: stringOrSignal, tickCount: tickCountRef, tickMinStep: numberOrSignal, values: arrayOrSignal, zindex: numberType, // LEGEND GROUP CONFIG cornerRadius: numberValue, fillColor: colorValue, offset: numberValue, padding: numberValue, strokeColor: colorValue, // LEGEND TITLE CONFIG titleAlign: alignValue, titleBaseline: baselineValue, titleColor: colorValue, titleFont: stringValue, titleFontSize: numberValue, titleFontWeight: fontWeightValue, titleLimit: numberValue, titleOpacity: numberValue, titlePadding: numberValue, // GRADIENT CONFIG gradientLength: numberOrSignal, gradientOpacity: numberValue, gradientStrokeColor: colorValue, gradientStrokeWidth: numberValue, gradientThickness: numberOrSignal, // SYMBOL LAYOUT CONFIG clipHeight: numberOrSignal, columns: numberOrSignal, columnPadding: numberOrSignal, rowPadding: numberOrSignal, gridAlign: layoutAlign, // SYMBOL CONFIG symbolFillColor: colorValue, symbolOffset: numberValue, symbolOpacity: numberValue, symbolSize: numberValue, symbolStrokeColor: colorValue, symbolStrokeWidth: numberValue, symbolType: stringValue, // LABEL CONFIG labelAlign: alignValue, labelBaseline: baselineValue, labelColor: colorValue, labelFont: stringValue, labelFontSize: numberValue, labelFontWeight: fontWeightValue, labelLimit: numberValue, labelOffset: numberValue, labelOpacity: numberValue, labelOverlap: labelOverlapRef, labelSeparation: numberOrSignal, // CUSTOMIZED ENCODERS encode: object({ title: guideEncodeRef, labels: guideEncodeRef, legend: guideEncodeRef, entries: guideEncodeRef, symbols: guideEncodeRef, gradient: guideEncodeRef }) }); const legend = allOf( legendProps, anyOf( required('size'), required('shape'), required('fill'), required('stroke'), required('opacity'), required('strokeDash') ) ); export default { defs: { guideEncode, legend } };
JavaScript
0
@@ -466,19 +466,16 @@ ickCount -Ref ');%0A%0Acon
ff1e852ff55a995de0f546f979fe582aa5555c83
Update index.js
express-yourself/myapp/routes/index.js
express-yourself/myapp/routes/index.js
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express yourself' }); }); router.get('/', function(req, res, next) { res.render('index', {title: 'hi' }); }); module.exports = router;
JavaScript
0.000002
@@ -187,32 +187,37 @@ ;%0A%0Arouter.get('/ +nadia ', function(req,
bce2bfca6d33ad10c77e815db8265f1ed9286881
Support globalSetup and globalTeardown Jest options (#5218)
packages/react-scripts/scripts/utils/createJestConfig.js
packages/react-scripts/scripts/utils/createJestConfig.js
// @remove-file-on-eject /** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; const fs = require('fs'); const chalk = require('chalk'); const paths = require('../../config/paths'); module.exports = (resolve, rootDir, isEjecting) => { // Use this instead of `paths.testsSetup` to avoid putting // an absolute filename into configuration after ejecting. const setupTestsFile = fs.existsSync(paths.testsSetup) ? '<rootDir>/src/setupTests.js' : undefined; // TODO: I don't know if it's safe or not to just use / as path separator // in Jest configs. We need help from somebody with Windows to determine this. const config = { collectCoverageFrom: ['src/**/*.{js,jsx}'], // TODO: this breaks Yarn PnP on eject. // But we can't simply emit this because it'll be an absolute path. // The proper fix is to write jest.config.js on eject instead of a package.json key. // Then these can always stay as require.resolve()s. resolver: isEjecting ? 'jest-pnp-resolver' : require.resolve('jest-pnp-resolver'), setupFiles: [ isEjecting ? 'react-app-polyfill/jsdom' : require.resolve('react-app-polyfill/jsdom'), ], setupTestFrameworkScriptFile: setupTestsFile, testMatch: [ '<rootDir>/src/**/__tests__/**/*.{js,jsx}', '<rootDir>/src/**/?(*.)(spec|test).{js,jsx}', ], testEnvironment: 'jsdom', testURL: 'http://localhost', transform: { '^.+\\.(js|jsx)$': isEjecting ? '<rootDir>/node_modules/babel-jest' : resolve('config/jest/babelTransform.js'), '^.+\\.css$': resolve('config/jest/cssTransform.js'), '^(?!.*\\.(js|jsx|css|json)$)': resolve('config/jest/fileTransform.js'), }, transformIgnorePatterns: [ '[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$', '^.+\\.module\\.(css|sass|scss)$', ], moduleNameMapper: { '^react-native$': 'react-native-web', '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy', }, moduleFileExtensions: ['web.js', 'js', 'json', 'web.jsx', 'jsx', 'node'], }; if (rootDir) { config.rootDir = rootDir; } const overrides = Object.assign({}, require(paths.appPackageJson).jest); const supportedKeys = [ 'collectCoverageFrom', 'coverageReporters', 'coverageThreshold', 'resetMocks', 'resetModules', 'snapshotSerializers', 'watchPathIgnorePatterns', ]; if (overrides) { supportedKeys.forEach(key => { if (overrides.hasOwnProperty(key)) { config[key] = overrides[key]; delete overrides[key]; } }); const unsupportedKeys = Object.keys(overrides); if (unsupportedKeys.length) { const isOverridingSetupFile = unsupportedKeys.indexOf('setupTestFrameworkScriptFile') > -1; if (isOverridingSetupFile) { console.error( chalk.red( 'We detected ' + chalk.bold('setupTestFrameworkScriptFile') + ' in your package.json.\n\n' + 'Remove it from Jest configuration, and put the initialization code in ' + chalk.bold('src/setupTests.js') + '.\nThis file will be loaded automatically.\n' ) ); } else { console.error( chalk.red( '\nOut of the box, Create React App only supports overriding ' + 'these Jest options:\n\n' + supportedKeys .map(key => chalk.bold(' \u2022 ' + key)) .join('\n') + '.\n\n' + 'These options in your package.json Jest configuration ' + 'are not currently supported by Create React App:\n\n' + unsupportedKeys .map(key => chalk.bold(' \u2022 ' + key)) .join('\n') + '\n\nIf you wish to override other Jest options, you need to ' + 'eject from the default setup. You can do so by running ' + chalk.bold('npm run eject') + ' but remember that this is a one-way operation. ' + 'You may also file an issue with Create React App to discuss ' + 'supporting more options out of the box.\n' ) ); } process.exit(1); } } return config; };
JavaScript
0
@@ -2442,16 +2442,57 @@ shold',%0A + 'globalSetup',%0A 'globalTeardown',%0A 'res
b1400107f760f61f88780ae690ba2016a29153ca
fix object type checking fix scenario when input is null
packages/ringcentral-integration/lib/di/utils/is_type.js
packages/ringcentral-integration/lib/di/utils/is_type.js
export function isEmpty(param) { return !param || param.length === 0; } export function isArray(x) { return Array.isArray ? Array.isArray(x) : Object.prototype.toString.call(x).slice(8, -1) === 'Array'; } export function isObject(x) { return typeof x === 'object' && !isArray(x); } export function isFunction(x) { return typeof x === 'function'; } /** * Provider type guard functions */ const USE_VALUE = 'useValue'; export function isValueProvider(provider) { return USE_VALUE in provider; } export function isStaticClassProvider(provider) { return provider.useClass !== undefined; } export function isExistingProvider(provider) { return provider.useExisting !== undefined; } export function isFactoryProvider(provider) { return provider.useFactory !== undefined; }
JavaScript
0.000045
@@ -255,44 +255,77 @@ urn -typeof x === 'object' && !isArray(x) +Object.prototype.toString.call(x).toLowerCase() === '%5Bobject object%5D' ;%0A%7D%0A
90403995d86f280ea85d86f62459ac8fcb799024
fix tests
test/solidity/localsTests/helper.js
test/solidity/localsTests/helper.js
'use strict' var localDecoder = require('../../../babelify-src/solidity/localDecoder') /* Decode local variable */ function decodeLocal (st, index, traceManager, callTree, verifier) { try { traceManager.waterfall([ traceManager.getStackAt, traceManager.getMemoryAt], index, function (error, result) { if (!error) { var locals = localDecoder.solidityLocals(index, callTree, result[0].value, result[1].value) verifier(locals) } else { st.fail(error) } }) } catch (e) { st.fail(e.message) } } module.exports = { decodeLocals: decodeLocal }
JavaScript
0.000001
@@ -449,16 +449,35 @@ 1%5D.value +, %7B%7D, %7Bstart: 5000%7D )%0A
dc3f7555044dabbeba54e844f2f5bcfc98fadceb
Remove some cruft
test/spec/directives/snap-toggle.js
test/spec/directives/snap-toggle.js
/*global describe, beforeEach, module, jasmine, inject, angular, it, expect, spyOn */ /*jshint node:true, camelcase:false */ 'use strict'; describe('Directive: snapToggle', function() { beforeEach(module('snap')); var button = '<button snap-toggle>foo</button>' , rightButton = '<button snap-toggle="right" snap-id="\'mySnapId\'">foo</button>' , snapRemote , compile , scope; beforeEach(inject(function($rootScope, $compile, _snapRemote_) { scope = $rootScope.$new(); compile = $compile; snapRemote = _snapRemote_; spyOn(snapRemote, 'toggle'); })); describe('behaviour', function() { it('should call snapper toggle method on the left snap', inject(function($compile) { var element = angular.element(button); element = compile(element)(scope); element[0].click(); expect(snapRemote.toggle.mostRecentCall.args[0]).toEqual('left'); expect(snapRemote.toggle.mostRecentCall.args[1]).toBeUndefined(); })); it('should call snapper toggle method on the right snap', inject(function($rootScope, $compile) { var element = angular.element(rightButton); element = compile(element)(scope); element[0].click(); expect(snapRemote.toggle.mostRecentCall.args[0]).toEqual('right'); expect(snapRemote.toggle.mostRecentCall.args[1]).toEqual('mySnapId'); })); }); });
JavaScript
0
@@ -677,39 +677,32 @@ the left snap', -inject( function($compil @@ -694,24 +694,16 @@ unction( -$compile ) %7B%0A @@ -956,25 +956,24 @@ ed();%0A %7D) -) ;%0A%0A it('s @@ -1025,23 +1025,16 @@ snap', -inject( function @@ -1034,36 +1034,16 @@ unction( -$rootScope, $compile ) %7B%0A @@ -1310,17 +1310,16 @@ ;%0A %7D) -) ;%0A %7D);%0A
2803b3fecda0be55a7e69a4e0b814ddf66704b2a
Add format info to transfers
test/unit/aggregationFiltersSpec.js
test/unit/aggregationFiltersSpec.js
'use strict'; describe('AggregationFilters', function() { var puid_data; var find_files; var find_transfers; var tag_count; var fmt_91_records = [{ 'id': '054a0f2c-79bb-4051-b82b-4b0f14564811', 'title': 'lion.svg', 'type': 'file', 'puid': 'fmt/91', 'size': 5, 'bulk_extractor_reports': ['logs.zip'], 'tags': [], }, { 'id': '7f70d25c-be05-4950-a384-dac159926960', 'title': 'rose_quartz.svg', 'type': 'file', 'puid': 'fmt/91', 'size': 2, 'bulk_extractor_reports': ['logs.zip'], 'tags': ['test'], }]; var fmt_11_records = [{ 'id': '4e941898-3914-4add-b1f6-476580862069', 'title': 'pearl.png', 'type': 'file', 'puid': 'fmt/11', 'size': 13, 'bulk_extractor_reports': ['logs.zip'], 'tags': ['test', 'test2'], }]; var record_with_no_logs = [{ 'id': 'b2a14653-5fd8-458c-b4ae-ccaab4b46b0c', 'title': 'lapis_lazuli.tiff', 'type': 'file', 'puid': 'fmt/153', 'size': 89, }]; var transfers = [{ 'id': 'fb91bf38-3836-4312-a928-699c564865da', 'title': 'garnet', 'type': 'transfer', 'original_order': '/fixtures/transferdata/fb91bf38-3836-4312-a928-699c564865da/directory_tree.txt', }]; beforeEach(function() { module('aggregationFilters'); inject(function($injector) { puid_data = $injector.get('$filter')('puid_data'); find_files = $injector.get('$filter')('find_files'); find_transfers = $injector.get('$filter')('find_transfers'); tag_count = $injector.get('$filter')('tag_count'); }); }); it('should aggregate data about multiple files with the same format', function() { var aggregate_data = puid_data(fmt_91_records); expect(aggregate_data.length).toEqual(1); expect(aggregate_data[0].puid).toEqual('fmt/91'); expect(aggregate_data[0].data.size).toEqual(7); expect(aggregate_data[0].data.count).toEqual(2); }); it('should produce one entry for each PUID in the source records', function() { var records = fmt_91_records.concat(fmt_11_records); var aggregate_data = puid_data(records); expect(aggregate_data.length).toEqual(2); expect(aggregate_data[0].puid).toEqual('fmt/91'); expect(aggregate_data[0].data.count).toEqual(2); expect(aggregate_data[1].puid).toEqual('fmt/11'); expect(aggregate_data[1].data.count).toEqual(1); }); it('should filter lists of files to contain only files', function() { var records = fmt_91_records.concat(fmt_11_records, transfers); var filtered_records = find_files(records); expect(filtered_records.length).toEqual(3); expect(filtered_records[0].title).toEqual('lion.svg'); }); it('should omit files with no bulk_extractor logs', function() { var records = fmt_91_records.concat(record_with_no_logs); expect(records.length).toEqual(3); var filtered_records = find_files(records); expect(filtered_records.length).toEqual(2); expect(filtered_records[0].title).toEqual('lion.svg'); }); it('should filter lists of files to contain only transfers', function() { var records = fmt_91_records.concat(fmt_11_records, transfers); var filtered_records = find_transfers(records); expect(filtered_records.length).toEqual(1); expect(filtered_records[0].title).toEqual('garnet'); }); it('should be able to aggregate tag acounts', function() { var records = fmt_91_records.concat(fmt_11_records); var tags = tag_count(records); expect(tags[0][0]).toEqual('test'); expect(tags[0][1]).toEqual(2); expect(tags[1][0]).toEqual('test2'); expect(tags[1][1]).toEqual(1); }); });
JavaScript
0
@@ -224,24 +224,70 @@ 'lion.svg',%0A + 'format': 'Scalable Vector Graphics 1.0',%0A 'type': @@ -286,32 +286,32 @@ 'type': 'file',%0A - 'puid': 'fmt @@ -476,24 +476,70 @@ uartz.svg',%0A + 'format': 'Scalable Vector Graphics 1.0',%0A 'type': @@ -753,24 +753,49 @@ pearl.png',%0A + 'format': 'PNG 1.0',%0A 'type': @@ -1002,16 +1002,16 @@ 46b0c',%0A - 'tit @@ -1036,16 +1036,69 @@ .tiff',%0A + 'format': 'TIFF for Image Technology (TIFF/IT)',%0A 'typ @@ -2351,33 +2351,33 @@ d).toEqual('fmt/ -9 +1 1');%0A expect( @@ -2406,33 +2406,33 @@ .count).toEqual( -2 +1 );%0A expect(ag @@ -2458,33 +2458,33 @@ d).toEqual('fmt/ -1 +9 1');%0A expect( @@ -2513,33 +2513,33 @@ .count).toEqual( -1 +2 );%0A %7D);%0A%0A it('
6e604ee5ee1ee855d8bd3c2deaa260bf573218d2
fixes a typo in "applyAnswers" unit test
test/unit/init/applyAnswers-test.js
test/unit/init/applyAnswers-test.js
const { assert } = require('chai'); const sinon = require('sinon'); const { _applyAnswers: applyAnswers } = require('../../../lib/init'); function createConfig() { return { _: [], custom: {} }; } describe('init._applyAnswers()', () => { const ci = { appveyor: sinon.spy(), circleci: sinon.spy(), travisci: sinon.spy(), wercker: sinon.spy(), }; beforeEach(() => Object.keys(ci).forEach(name => ci[name].resetHistory())); it('applies the API description and the API host as positional CLI arguments', () => { const config = applyAnswers(createConfig(), { apiDescription: 'apiary.apib', apiHost: 'http://127.0.0.1:5000', }); assert.deepEqual(config._, ['apiary.apib', 'http://127.0.0.1:5000']); }); it('sets the server', () => { const config = applyAnswers(createConfig(), { server: 'npm start' }); assert.equal(config.server, 'npm start'); }); it('sets the server to null if not provided', () => { const config = applyAnswers(createConfig(), {}); assert.isNull(config.server); }); it('sets the language', () => { const config = applyAnswers(createConfig(), { language: 'python' }); assert.equal(config.language, 'python'); }); it('sets no reporter by default', () => { const config = applyAnswers(createConfig(), {}); assert.isUndefined(config.reporter); }); it('sets the reporter to \'apiary\' if asked', () => { const config = applyAnswers(createConfig(), { apiary: true }); assert.equal(config.reporter, 'apiary'); }); it('sets no custom data by default', () => { const config = applyAnswers(createConfig(), {}); assert.deepEqual(config.custom, {}); }); it('sets the Apiary API key if provided', () => { const config = applyAnswers(createConfig(), { apiaryApiKey: '1234' }); assert.equal(config.custom.apiaryApiKey, '1234'); }); it('sets the Apiary API name if provided', () => { const config = applyAnswers(createConfig(), { apiaryApiName: 'myproject' }); assert.equal(config.custom.apiaryApiName, 'myproject'); }); it('creates selected CI configuration if asked', () => { applyAnswers(createConfig(), { createCI: 'wercker' }, { ci }); assert.isTrue(ci.wercker.calledOnce); assert.isFalse(ci.appveyor.called || ci.circleci.called || ci.travisci.called); }); it('updates AppVeyor if asked', () => { applyAnswers(createConfig(), { appveyor: true }, { ci }); assert.isTrue(ci.appveyor.calledOnce); assert.isFalse(ci.circleci.called || ci.travisci.called || ci.wercker.called); }); it('updates CircleCI if asked', () => { applyAnswers(createConfig(), { circleci: true }, { ci }); assert.isTrue(ci.circleci.calledOnce); assert.isFalse(ci.appveyor.called || ci.travisci.called || ci.wercker.called); }); it('updates Travis CI if asked', () => { applyAnswers(createConfig(), { travisci: true }, { ci }); assert.isTrue(ci.travisci.calledOnce); assert.isFalse(ci.appveyor.called || ci.circleci.called || ci.wercker.called); }); it('updates Wercker if asked', () => { applyAnswers(createConfig(), { wercker: true }, { ci }); assert.isTrue(ci.wercker.calledOnce); assert.isFalse(ci.appveyor.called || ci.circleci.called || ci.travisci.called); }); it('updates multiple CIs if asked', () => { applyAnswers(createConfig(), { wercker: true, circleci: true }, { ci }); assert.isTrue(ci.circleci.calledOnce && ci.wercker.calledOnce); assert.isFalse(ci.appveyor.called || ci.travisci.called); }); });
JavaScript
0.998099
@@ -1205,32 +1205,210 @@ python');%0A %7D);%0A + it('sets the language when not prompted', () =%3E %7B%0A const config = applyAnswers(createConfig(%7B language: 'python' %7D), %7B%7D);%0A assert.equal(config.language, 'python');%0A %7D);%0A it('sets no re
f267bbc9e34282354997720f86f323b76ab47b1d
Update location of bridgedb index file.
test/manual-tests/get-data-sources.js
test/manual-tests/get-data-sources.js
var BridgeDb = require('../index.js'); var bridgeDb1 = BridgeDb({ apiUrlStub: 'http://pointer.ucsf.edu/d3/r/data-sources/bridgedb.php', dataSourcesUrl: 'http://pointer.ucsf.edu/d3/r/data-sources/bridgedb-datasources.php' }); //* bridgeDb1.dataSource.getAll() .each(function(dataSource) { console.log('Database metadata'); console.log(JSON.stringify(dataSource, null, '\t')); }); //*/ //* var bridgeDb2 = BridgeDb({ apiUrlStub: 'http://pointer.ucsf.edu/d3/r/data-sources/bridgedb.php', dataSourcesUrl: 'http://pointer.ucsf.edu/d3/r/data-sources/bridgedb-datasources.php' }); //*/ //* bridgeDb2.dataSource.getAll() .each(function(dataSource) { console.log('Database metadata'); console.log(JSON.stringify(dataSource, null, '\t')); }); //*/ //* bridgeDb2.dataSource.getAll() .each(function(dataSource) { console.log('Database metadata'); console.log(JSON.stringify(dataSource, null, '\t')); }); //*/
JavaScript
0
@@ -20,16 +20,19 @@ ire('../ +../ index.js
cac0454bbb793e813081520d86d239b8c0906ed9
use port exposed by docker for browser-sync proxy
app/templates/gulp/tasks/browser-sync.js
app/templates/gulp/tasks/browser-sync.js
const gulp = require('gulp'); //*------------------------------------*\ // BROWSER-SYNC //*------------------------------------*/ const browserSync = gulp.task('browser-sync', done => { global.browserSync.init({ proxy: process.env.APACHE_HOSTNAME, injectchanges: true, open: true, notify: false, // tunnel: true, }); return done(); }); //*------------------------------------*\ // BROWSER-SYNC RELOAD //*------------------------------------*/ const bsReload = gulp.task('bs-reload', done => { global.browserSync.reload(); done(); }); module.exports = { browserSync, bsReload, };
JavaScript
0
@@ -227,35 +227,24 @@ xy: -process.env.APACHE_HOSTNAME +'localhost:8080' ,%0A
0b260b87bef52e3cc6ce6295fa282ca88b40e2a2
Update worley-noise.js
src/worley-noise.js
src/worley-noise.js
function WorleyNoise(numPoints) { this._numPoints = numPoints || 0; this._init(); } WorleyNoise.prototype.addPoint = function (x, y) { this._points[this._numPoints++] = { x: x, y: y }; }; WorleyNoise.prototype.getEuclidean = function (x, y, k) { return Math.sqrt(this._calculateValue(x, y, k, euclidean)); }; WorleyNoise.prototype.getManhattan = function (x, y, k) { return this._calculateValue(x, y, k, manhattan); }; WorleyNoise.prototype.getMap = function (resolution, callback) { var step = 1 / (resolution - 1), map = [], that = this, x, y; callback = callback || function (e, m) { return e(1); }; function e(k) { return Math.sqrt(that._calculateValue(x * step, y * step, k, euclidean)); } function m(k) { return that._calculateValue(x * step, y * step, k, manhattan); } for (y = 0; y < resolution; ++y) { for (x = 0; x < resolution; ++x) { map[y * resolution + x] = callback(e, m); } } return map; }; WorleyNoise.prototype.getNormalizedMap = function (resolution, callback) { var map = this.getMap(resolution, callback), min = Number.POSITIVE_INFINITY, max = Number.NEGATIVE_INFINITY, scale, i; for (i = 0; i < map.length; ++i) { min = Math.min(min, map[i]); max = Math.max(max, map[i]); } scale = 1 / (max - min); for (i = 0; i < map.length; ++i) { map[i] = (map[i] - min) * scale; } return map; }; WorleyNoise.prototype._init = function () { var i; this._points = []; for (i = 0; i < this._numPoints; ++i) { this._points.push({ x: Math.random(), y: Math.random() }); } }; WorleyNoise.prototype._calculateValue = function (x, y, k, distFn) { var minDist, dist, minIdx, i, j; for (i = 0; i < this._numPoints; ++i) { this._points[i].selected = false; } for (j = 0; j < k; ++j) { minDist = Number.POSITIVE_INFINITY for (i = 0; i < this._numPoints; ++i) { dist = distFn(x - this._points[i].x, y - this._points[i].y); if (dist < minDist && !this._points[i].selected) { minDist = dist; minIdx = i; } } this._points[minIdx].selected = true; } return minDist; }; function euclidean(dx, dy) { return dx * dx + dy * dy; } function manhattan(dx, dy) { return Math.abs(dx) + Math.abs(dy); } module.exports = WorleyNoise;
JavaScript
0
@@ -23,16 +23,22 @@ umPoints +, seed ) %7B%0A @@ -71,16 +71,48 @@ s %7C%7C 0;%0A + this._seed = seed %7C%7C 10000;%0A this @@ -1716,32 +1716,124 @@ mPoints; ++i) %7B%0A + var x = Math.sin(i + 1) * this._seed,%0A y = Math.cos(i + 1) * this._seed;%0A this._po
56b6aa03943bf1423b8b305e56bf2215b87e26de
Fix Space spec
test/integration/space-test.js
test/integration/space-test.js
'use strict'; buster.testCase('Space', { prepare: function() { this.timeout = 30e3; var that = this; return client.createSpace({ name: 'Space Integration Test' }, 'contentful').then(function(space) { that.space = space; }); }, conclude: function() { return client.deleteSpace(this.space); }, 'can be created': function() { assert.match(this.space.name, 'Space Integration Test'); }, 'can be updated': function() { var space = { sys: this.space.sys, name: 'Space Fascination Test' }; return client.updateSpace(space).then(function(space) { assert.equals(space.sys.version, 1); }); }, 'can be read': function() { return client.getSpace(this.space.sys.id).then(function(space) { assert.match(space.name, /Space .+ Test/); }); }, 'can be listed': function() { var knownSpace = this.space; return client.getSpaces().then(function(spaces) { var space = _.find(spaces, function(space) { return space.sys.id === knownSpace.sys.id; }); assert.defined(space); }); }, 'can be deleted': function() { return client.createSpace({ name: 'Space Integration Test' }, 'contentful').then(function(space) { assert(true); return client.deleteSpace(space); }); } });
JavaScript
0.000001
@@ -658,9 +658,9 @@ on, -1 +2 );%0A
aa28c1cd5dd17cf06310001e8f4e216c4ca2317b
fix test
test/integration/test-basic.js
test/integration/test-basic.js
var http = require('http'); var assert = require('assert'); var express = require('express'); var bodyParser = require('body-parser'); var request = require('superagent'); var createSlackEventAdapter = require('../../dist').createSlackEventAdapter; var errorCodes = require('../../dist').errorCodes; var helpers = require('../helpers'); describe('when using middleware inside your own express application', function () { beforeEach(function (done) { this.port = process.env.PORT || '8080'; this.verificationToken = 'VERIFICATION_TOKEN'; this.adapter = createSlackEventAdapter(this.verificationToken); this.app = express(); this.app.use(bodyParser.json()); this.app.use('/slack', this.adapter.expressMiddleware()); this.server = http.createServer(this.app); this.server.listen(this.port, done); }); afterEach(function (done) { this.server.close(done); }); it('should emit a slack event', function (done) { var partiallyComplete = helpers.completionAggregator(done, 2); var payload = { token: this.verificationToken, event: { type: 'any_event', key: 'value', foo: 'baz' } }; this.adapter.on('any_event', function (event) { assert.deepEqual(event, payload.event); partiallyComplete(); }); request .post('http://localhost:' + this.port + '/slack') .send(payload) .end(function (err, res) { if (err) { partiallyComplete(err); } else { assert.equal(res.statusCode, 200); partiallyComplete(); } }); }); it('should emit a request verification error when handling a request with a bad verification token', function (done) { var partiallyComplete = helpers.completionAggregator(done, 2); var payload = { token: 'NOT_THE_RIGHT_VERIFICATION_TOKEN', event: { type: 'any_event', key: 'value', foo: 'baz' } }; this.adapter.on('any_event', function (event) { // If this happens, the test has failed. partiallyComplete(event); }); this.adapter.on('error', function (error) { assert(error instanceof Error); assert.equal(error.code, errorCodes.TOKEN_VERIFICATION_FAILURE); assert.deepEqual(error.body, payload); partiallyComplete(); }); request .post('http://localhost:' + this.port + '/slack') .send(payload) .end(function (err, res) { assert(err instanceof Error); assert.equal(res.statusCode, 500); partiallyComplete(); }); }); it('should handle URL verification', function (done) { var challenge = 'CHALLENGE_VALUE'; var payload = { token: this.verificationToken, challenge: challenge, type: 'url_verification' }; request .post('http://localhost:' + this.port + '/slack') .send(payload) .end(function (err, res) { if (err) { done(err); } else { assert.equal(res.statusCode, 200); assert.equal(res.text, challenge); done(); } }); }); it('should forward a challenge request error to the error handler', function (done) { var partiallyComplete = helpers.completionAggregator(done, 2); var challenge = 'CHALLENGE_VALUE'; var payload = { token: 'NOT_THE_RIGHT_VERIFICATION_TOKEN', challenge: challenge, type: 'url_verification' }; this.adapter.on('any_event', function (event) { // If this happens, the test has failed. partiallyComplete(event); }); this.adapter.on('error', function (error) { assert(error instanceof Error); assert.equal(error.code, errorCodes.TOKEN_VERIFICATION_FAILURE); assert.deepEqual(error.body, payload); partiallyComplete(); }); request .post('http://localhost:' + this.port + '/slack') .send(payload) .end(function (err, res) { assert(err instanceof Error); assert.equal(res.statusCode, 500); partiallyComplete(); }); }); }); describe('when using the built-in HTTP server', function () { beforeEach(function () { this.port = process.env.PORT || '8080'; // This is the default path this.path = '/slack/events'; this.verificationToken = 'VERIFICATION_TOKEN'; this.adapter = createSlackEventAdapter(this.verificationToken, { waitForResponse: true }); return this.adapter.start(this.port); }); afterEach(function () { return this.adapter.stop(); }); it('should be able to stop the built-in HTTP server', function () { var self = this; return self.adapter.stop() .then(function () { return self.adapter.start(self.port); }); }); it('should not stop if there is no built-in HTTP server running', function (done) { var self = this; self.adapter.stop() .then(function () { self.adapter.stop() .then(function () { done(new Error('should not be able to stop an already stopped server')); }) .catch(function (error) { assert(error instanceof Error); done(); }); }) .catch(done); }); });
JavaScript
0.000002
@@ -5145,37 +5145,162 @@ r);%0A +self.adapter.start(self.port)%0A .then(function () %7B%0A done();%0A %7D)%0A .catch( done -( );%0A %7D);
a59e872feed4816a9d38e12e0dbdc7f1c8ea8751
fix jshint
test/spec/services/individuService.js
test/spec/services/individuService.js
'use strict'; describe('IndividuService', function() { var service; beforeEach(function() { module('ddsApp'); inject(function(IndividuService) { service = IndividuService; }); }); describe('function label()', function() { it('Should return "Vous" if individu has role demandeur', function() { // given var individu = {role: 'demandeur', firstName: 'Arnaud'}; // when var result = service.label(individu); // then expect(result).toBe('Vous'); }); it('Should return "Votre conjoint" if individu has role conjoint', function() { // given var individu = { role: 'conjoint', firstName: 'Arnaud' }; // when var result = service.label(individu); // then expect(result).toBe('Votre conjoint'); }); it('Should return the individu\'s first name if individu has not role demandeur neither conjoint', function() { // given var individu = { role: 'fakeRole', firstName: 'Arnaud' }; // when var result = service.label(individu); // then expect(result).toBe('Arnaud'); }); }); describe('function formatStatutsSpecifiques()', function() { it('Should return empty string if no specific situations', function() { // when var result = service.formatStatutsSpecifiques({ situationsPro: [] }); // then expect(result).toBe(''); }); it('Should return single situation with no comma', function() { // when var result = service.formatStatutsSpecifiques({ situationsPro: [{ situation: 'retraite' }] }); // then expect(result).toBe('Retraité'); }); it('Should return comma-separated statuts when individu has several statuts specifiques', function() { // when var result = service.formatStatutsSpecifiques({ situationsPro: [{ situation: 'retraite' }, { situation: 'etudiant' }] }); // then expect(result).toBe('Étudiant, retraité'); }); it('Should display "enceinte" if the individu has the corresponding field to true', function() { // when var result = service.formatStatutsSpecifiques({ enceinte: true }); // then expect(result).toBe('Enceinte'); }); }); describe('function isParent()', function() { it('Should return true only if individu has role "demandeur" or "conjoint"', function() { // given var roles = ['demandeur', 'conjoint', 'enfant', 'personneACharge', undefined]; var individus = _.map(roles, function(role) { return { role: role }}); // when var results = _.map(individus, _.bind(service.isParent, service)); // then expect(results).toEqual([true, true, false, false, false]); }); }); });
JavaScript
0.000002
@@ -8,16 +8,32 @@ rict';%0A%0A +/* global _ */%0A%0A describe @@ -2882,16 +2882,18 @@ : role %7D +; %7D);%0A%0A
d4504732f3ddc069e841985e712b6ef8350f498b
Fix test expectations for individuService
test/spec/services/individuService.js
test/spec/services/individuService.js
'use strict'; describe('IndividuService', function() { var service; beforeEach(function() { module('ddsApp'); inject(function(IndividuService) { service = IndividuService; }); }); describe('function label()', function() { it('Should return "Vous" if individu has role demandeur', function() { // given var individu = {role: 'demandeur', firstName: 'Arnaud'}; // when var result = service.label(individu); // then expect(result).toBe('Vous'); }); it('Should return "Votre conjoint" if individu has role conjoint', function() { // given var individu = { role: 'conjoint', firstName: 'Arnaud' }; // when var result = service.label(individu); // then expect(result).toBe('Votre conjoint'); }); it('Should return the individu\'s first name if individu has not role demandeur neither conjoint', function() { // given var individu = { role: 'fakeRole', firstName: 'Arnaud' }; // when var result = service.label(individu); // then expect(result).toBe('Arnaud'); }); }); describe('function formatStatutsSpecifiques()', function() { it('Should return empty string if no specific situations', function() { // when var result = service.formatStatutsSpecifiques({ specificSituations: [] }); // then expect(result).toBe(''); }); it('Should return single situation with no comma', function() { // when var result = service.formatStatutsSpecifiques({ specificSituations: ['retraite'] }); // then expect(result).toBe('Retraité'); }); it('Should return comma-separated statuts when individu has several statuts specifiques', function() { // when var result = service.formatStatutsSpecifiques({ specificSituations: ['retraite' , 'etudiant'] }); // then expect(result).toBe('Étudiant, retraité'); }); it('Should display "enceinte", "boursier" and "en garde alternée" if the individu has the corresponding fields to true', function() { // when var result = service.formatStatutsSpecifiques({ enceinte: true, boursier: true, gardeAlternee: true }); // then expect(result).toBe('Enceinte, boursier, en garde alternée'); }); }); describe('function isParent()', function() { it('Should return true only if individu has role "demandeur" or "conjoint"', function() { // given var roles = ['demandeur', 'conjoint', 'enfant', undefined]; var individus = _.map(roles, function(role) { return { role: role }; }); // when var results = _.map(individus, _.bind(service.isParent, service)); // then expect(results).toEqual([true, true, false, false]); }); }); });
JavaScript
0.000005
@@ -1857,24 +1857,26 @@ Be('Retrait%C3%A9 +%C2%B7e ');%0A @@ -2183,16 +2183,18 @@ %C3%89tudiant +%C2%B7e , retrai @@ -2195,16 +2195,18 @@ retrait%C3%A9 +%C2%B7e ');%0A
a088c6e6e780fd1dcc9ada9c9f2c07b4dcdef53e
Migrate RadioButtonIcon to emotion (#26068)
packages/material-ui/src/Radio/RadioButtonIcon.js
packages/material-ui/src/Radio/RadioButtonIcon.js
import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import RadioButtonUncheckedIcon from '../internal/svg-icons/RadioButtonUnchecked'; import RadioButtonCheckedIcon from '../internal/svg-icons/RadioButtonChecked'; import withStyles from '../styles/withStyles'; export const styles = (theme) => ({ root: { position: 'relative', display: 'flex', '&$checked $dot': { transform: 'scale(1)', transition: theme.transitions.create('transform', { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.shortest, }), }, }, checked: {}, background: { // Scale applied to prevent dot misalignment in Safari transform: 'scale(1)', }, dot: { left: 0, position: 'absolute', transform: 'scale(0)', transition: theme.transitions.create('transform', { easing: theme.transitions.easing.easeIn, duration: theme.transitions.duration.shortest, }), }, }); /** * @ignore - internal component. */ function RadioButtonIcon(props) { const { checked, classes, fontSize } = props; return ( <span className={clsx(classes.root, { [classes.checked]: checked })}> <RadioButtonUncheckedIcon fontSize={fontSize} className={classes.background} /> <RadioButtonCheckedIcon fontSize={fontSize} className={classes.dot} /> </span> ); } RadioButtonIcon.propTypes = { /** * If `true`, the component is checked. */ checked: PropTypes.bool, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * The size of the component. * `small` is equivalent to the dense radio styling. */ fontSize: PropTypes.oneOf(['small', 'medium']), }; export default withStyles(styles, { name: 'PrivateRadioButtonIcon' })(RadioButtonIcon);
JavaScript
0
@@ -65,33 +65,8 @@ s';%0A -import clsx from 'clsx';%0A impo @@ -230,26 +230,34 @@ %0Aimport -with +experimental Style -s +d from '. @@ -269,70 +269,87 @@ les/ -with +experimental Style -s +d ';%0A%0A -export const styles = (theme) =%3E (%7B%0A root: %7B%0A +const RadioButtonIconRoot = experimentalStyled('span')(%7B%0A po @@ -368,18 +368,16 @@ ative',%0A - displa @@ -391,65 +391,341 @@ x',%0A - '&$checked $dot': %7B%0A transform: 'scale(1)',%0A +%7D);%0A%0Aconst RadioButtonIconBackground = experimentalStyled(RadioButtonUncheckedIcon)(%7B%0A // Scale applied to prevent dot misalignment in Safari%0A transform: 'scale(1)',%0A%7D);%0A%0Aconst RadioButtonIconDot = experimentalStyled(RadioButtonCheckedIcon)((%7B theme, styleProps %7D) =%3E (%7B%0A left: 0,%0A position: 'absolute',%0A transform: 'scale(0)',%0A tr @@ -774,20 +774,16 @@ orm', %7B%0A - easi @@ -819,17 +819,12 @@ ease -Out,%0A +In,%0A @@ -874,20 +874,16 @@ st,%0A - %7D),%0A %7D, @@ -882,187 +882,35 @@ ,%0A - %7D,%0A %7D,%0A checked: %7B%7D,%0A background: %7B%0A // Scale applied to prevent dot misalignment in Safari%0A transform: 'scale(1)',%0A %7D,%0A dot: %7B%0A left: 0,%0A position: 'absolute', +...(styleProps.checked && %7B %0A @@ -924,25 +924,25 @@ orm: 'scale( -0 +1 )',%0A tran @@ -1028,26 +1028,27 @@ .easing.ease -In +Out ,%0A dura @@ -1101,20 +1101,22 @@ %7D),%0A %7D +) ,%0A%7D) +) ;%0A%0A/**%0A @@ -1202,16 +1202,24 @@ checked + = false , classe @@ -1219,16 +1219,21 @@ classes + = %7B%7D , fontSi @@ -1253,26 +1253,86 @@ %0A%0A -return (%0A %3Cspan +const styleProps = %7B ...props, checked %7D;%0A%0A return (%0A %3CRadioButtonIconRoot cla @@ -1343,13 +1343,8 @@ me=%7B -clsx( clas @@ -1355,75 +1355,75 @@ root -, %7B %5Bclasses.checked%5D: checked %7D)%7D%3E%0A %3CRadioButtonUncheckedIcon +%7D styleProps=%7BstyleProps%7D%3E%0A %3CRadioButtonIconBackground%0A fon @@ -1430,32 +1430,40 @@ tSize=%7BfontSize%7D +%0A className=%7Bclas @@ -1477,16 +1477,54 @@ kground%7D +%0A styleProps=%7BstyleProps%7D%0A /%3E%0A @@ -1537,27 +1537,23 @@ ioButton -Checked Icon +Dot fontSiz @@ -1593,21 +1593,60 @@ ot%7D -/%3E%0A %3C/span +styleProps=%7BstyleProps%7D /%3E%0A %3C/RadioButtonIconRoot %3E%0A @@ -1915,19 +1915,8 @@ ject -.isRequired ,%0A @@ -2085,77 +2085,21 @@ ult -withStyles(styles, %7B name: 'PrivateRadioButtonIcon' %7D)(RadioButtonIcon) +RadioButtonIcon ;%0A
dc3063df1e4f75a1037c452b6707009854132da5
Fix dot misalignment in IE11 (#15952)
packages/material-ui/src/Radio/RadioButtonIcon.js
packages/material-ui/src/Radio/RadioButtonIcon.js
import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import RadioButtonUncheckedIcon from '../internal/svg-icons/RadioButtonUnchecked'; import RadioButtonCheckedIcon from '../internal/svg-icons/RadioButtonChecked'; import withStyles from '../styles/withStyles'; export const styles = theme => ({ root: { position: 'relative', display: 'flex', '&$checked $layer': { transform: 'scale(1)', transition: theme.transitions.create('transform', { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.shortest, }), }, }, layer: { position: 'absolute', transform: 'scale(0)', transition: theme.transitions.create('transform', { easing: theme.transitions.easing.easeIn, duration: theme.transitions.duration.shortest, }), }, checked: {}, }); /** * @ignore - internal component. */ function RadioButtonIcon(props) { const { checked, classes, className, ...other } = props; return ( <div className={clsx(classes.root, { [classes.checked]: checked }, className)} {...other}> <RadioButtonUncheckedIcon /> <RadioButtonCheckedIcon className={classes.layer} /> </div> ); } RadioButtonIcon.propTypes = { /** * If `true`, the component is checked. */ checked: PropTypes.bool, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, }; export default withStyles(styles, { name: 'PrivateRadioButtonIcon' })(RadioButtonIcon);
JavaScript
0
@@ -629,24 +629,37 @@ %0A layer: %7B%0A + left: 0,%0A position
9332d6c3ee3abc09047b7af6f1a37ef24e95dafa
Fix virtual hosts
packages/navy/src/middleware/add-virtual-hosts.js
packages/navy/src/middleware/add-virtual-hosts.js
/* @flow */ import {mapValues, find} from 'lodash' import {Navy} from '../navy' import {getHostForService} from '../util/xipio' const getServiceHTTPProxyConfig = (serviceName, navyFile) => { if (navyFile && navyFile.httpProxy && navyFile.httpProxy[serviceName]) { return navyFile.httpProxy[serviceName] } return null } const serviceHasPort80 = service => service.ports && find(service.ports, port => port.toString() === '80' ) export default (navy: Navy) => async (config: Object, state: Object) => { const navyFile = await navy.getNavyFile() return { ...config, services: mapValues(config.services, (service, serviceName) => { let proxyConfig = getServiceHTTPProxyConfig(serviceName, navyFile) // proxy port 80 even without config if (!proxyConfig && serviceHasPort80(service)) { proxyConfig = { port: 80 } } if (proxyConfig) { return { ...service, environment: { 'VIRTUAL_HOST': getHostForService(serviceName, navy.normalisedName), 'VIRTUAL_PORT': proxyConfig.port, ...service.environment, }, } } return service }), } }
JavaScript
0.000001
@@ -18,19 +18,8 @@ rt %7B -mapValues, find @@ -558,53 +558,82 @@ e()%0A -%0A -return %7B%0A ...config,%0A +const services = %7B%7D%0A%0A await Promise.all(Object.keys(config. services : ma @@ -632,47 +632,75 @@ ices -: mapValues(config.services, ( +).map(async serviceName =%3E %7B%0A const service = config. service -, +s%5B serv @@ -706,25 +706,18 @@ viceName -) =%3E %7B%0A +%5D%0A le @@ -782,18 +782,16 @@ yFile)%0A%0A - // @@ -827,26 +827,24 @@ onfig%0A - if (!proxyCo @@ -888,18 +888,16 @@ - proxyCon @@ -917,31 +917,27 @@ 80 %7D%0A - %7D%0A%0A - if (pr @@ -961,21 +961,41 @@ - return +services%5BserviceName%5D = %7B%0A - @@ -1022,18 +1022,16 @@ - environm @@ -1037,18 +1037,16 @@ ment: %7B%0A - @@ -1064,16 +1064,22 @@ L_HOST': + await getHost @@ -1128,34 +1128,32 @@ e),%0A - 'VIRTUAL_PORT': @@ -1174,34 +1174,32 @@ rt,%0A - ...service.envir @@ -1220,15 +1220,11 @@ - %7D,%0A - @@ -1231,26 +1231,24 @@ %7D%0A - %7D%0A%0A r @@ -1240,26 +1240,24 @@ %7D%0A%0A - return servi @@ -1262,17 +1262,86 @@ vice -%0A %7D) +s%5BserviceName%5D = service%0A %7D))%0A%0A return %7B%0A ...config,%0A services ,%0A
abae4e384dd7fb7e52e5f8a713a0ef74342e21e8
test msgpack with date
test/unit/serializers/msgpack.spec.js
test/unit/serializers/msgpack.spec.js
const MsgPackSerializer = require("../../../src/serializers/msgpack"); const { cloneDeep } = require("lodash"); const P = require("../../../src/packets"); describe("Test MsgPackSerializer constructor", () => { it("should create an empty options", () => { let serializer = new MsgPackSerializer(); expect(serializer).toBeDefined(); expect(serializer.serialize).toBeDefined(); expect(serializer.deserialize).toBeDefined(); }); }); describe("Test MsgPackSerializer", () => { let serializer = new MsgPackSerializer(); serializer.init(); it("should serialize the event packet", () => { const obj = { ver: "3", sender: "test-1", event: "user.created", data: { a: 5, b: "Test" }, broadcast: true }; const s = serializer.serialize(cloneDeep(obj), P.PACKET_EVENT); expect(s.length).toBe(67); const res = serializer.deserialize(s, P.PACKET_EVENT); expect(res).not.toBe(obj); expect(res).toEqual(obj); }); });
JavaScript
0
@@ -592,16 +592,42 @@ () =%3E %7B%0A +%09%09const now = new Date();%0A %09%09const @@ -634,16 +634,16 @@ obj = %7B%0A - %09%09%09ver: @@ -728,16 +728,28 @@ : %22Test%22 +,%0A%09%09%09%09c: now %0A%09%09%09%7D,%0A%09 @@ -865,10 +865,10 @@ oBe( -6 7 +9 );%0A%0A
ae8164caadff311dcf288affad3b733483cf57cc
Fix to get Travis-CI passing (hopefully)
test/responsive_images_test.js
test/responsive_images_test.js
/** * grunt-responsive-images * https://github.com/andismith/grunt-responsive-images * * Copyright (c) 2013 andismith * Licensed under the MIT license. * * Test suite for Grunt Responsive Images * * @author Andi Smith (http://twitter.com/andismith) * @version 1.0 */ /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ (function() { 'use strict'; var async = require('async'), grunt = require('grunt'), im = require('node-imagemagick'), q = require('q'); /** * Compare the created image against the expected image. * * @private * @param {string} filename The name of the file * @param {string} actual The actual file path * @param {string} expected The expected file path * @return {object} promise Either resolved rejected with an error message. */ var compareImageProperties = function(filename, actualPath, expectedPath) { var deferred = q.defer(); // load created image im.identify(actualPath + filename, function(error, actualProp) { if (error) { deferred.reject('Failed to load actual (created) image "' + actualPath + filename + '"'); } else { // load expected image im.identify(expectedPath + filename, function(error, expectedProp) { if (error) { deferred.reject('Failed to load expected image "' + expectedPath + filename + '"'); } else { // check if we have a match if ((actualProp.compression === expectedProp.compression) && (actualProp.width === expectedProp.width) && (actualProp.height === expectedProp.height) && (actualProp.quality === expectedProp.quality)) { deferred.resolve(true); } else { deferred.reject(filename + ': ' + 'actual image (' + actualProp.compression + ' ' + actualProp.width + 'x' + actualProp.height + ' - Q:' + actualProp.quality ') and ' + 'expected image (' + expectedProp.compression + ' ' + expectedProp.width + 'x' + expectedProp.height + ' - Q:' + expectedProp.quality ') should match'); } } }); } }); return deferred.promise; }; /** * Inspect and handle test results from inspecting an image * * @private * @param {object} file The file object * @param {object} test Test instance * @param {string} callback Async callback, to be run when the test is complete */ var inspectImage = function(file, test, callback) { compareImageProperties(file.filename, file.actual, file.expected) .then(function(result) { test.ok(true); }, function(error) { test.ok(false, error); }) .done(function() { return callback(); }); }; /** * Run through the array of files and add them to the queue of images to be tested * * @private * @param {array} files List of files to check (with filename, expected and actual paths) * @param {object} test Test instance */ var checkImages = function(actual, expected, files, test) { var series = [], file = {}; test.expect(files.length); files.forEach(function(filename) { var file = { actual: actual, expected: expected, filename: filename }; series.push(function(callback) { inspectImage(file, test, callback); }); }); async.series(series, function() { test.done(); }); }; // List of tests to be run exports.responsive_images = { default_options: function(test) { var actualPath = 'tmp/default_options/', expectedPath = 'test/expected/default_options/', files = [ 'minions-small.jpg', 'minions-medium.jpg', 'minions-large.jpg' ]; checkImages(actualPath, expectedPath, files, test); }, file_wildcard_options: function(test) { var actualPath = 'tmp/file_wildcard_options/', expectedPath = 'test/expected/file_wildcard_options/', files = [ 'sonic-small.png', 'sonic-medium.png', 'sonic-large.png', 'mario-yoshi-small.jpg', 'mario-yoshi-medium.jpg', 'mario-yoshi-large.jpg', 'mickey-mouse-small.gif', 'mickey-mouse-medium.gif', 'mickey-mouse-large.gif' ]; checkImages(actualPath, expectedPath, files, test); }, custom_options: function(test) { var actualPath = 'tmp/custom_options/', expectedPath = 'test/expected/custom_options/', files = [ 'panther-small.jpg', 'panther-220.jpg', 'panther-large.jpg', 'panther-large_x2.jpg' ]; checkImages(actualPath, expectedPath, files, test); }, percentage_sizes: function(test) { var actualPath = 'tmp/percentage_sizes/', expectedPath = 'test/expected/percentage_sizes/', files = [ 'captain-planet-10%.jpg', 'captain-planet-50%.jpg', 'captain-planet-200%.jpg' ]; checkImages(actualPath, expectedPath, files, test); }, custom_dest_width: function(test) { var actualPath = 'tmp/custom_dest_width/', expectedPath = 'test/expected/custom_dest_width/', files = [ '320/cedric_sneer.jpg', '640/cedric_sneer.jpg', '1024/cedric_sneer.jpg' ]; checkImages(actualPath, expectedPath, files, test); }, custom_dest_name: function(test) { var actualPath = 'tmp/custom_dest_name/', expectedPath = 'test/expected/custom_dest_name/', files = [ 'leo/tmnt.png', 'donnie/tmnt.png', 'raph/tmnt.png' ]; checkImages(actualPath, expectedPath, files, test); }, custom_dest_path: function (test) { var actualPath = 'tmp/custom_dest_path/', expectedPath = 'test/expected/custom_dest_path/', files = [ '320/battle-cat.jpg', '640/sub_directory/battle-dog.jpg' ]; checkImages(actualPath, expectedPath, files, test); } }; }());
JavaScript
0
@@ -2522,32 +2522,34 @@ tualProp.quality + + %0A @@ -2725,16 +2725,18 @@ .quality + + %0A
f37fd62eb52cfac8d462954aa91869b58cd3dbf7
Fix failing test after async.js special case added
test/unit/server/test_grunt_config.js
test/unit/server/test_grunt_config.js
'use strict'; var expect = require('chai').expect; var sinon = require('sinon'); var GruntConfig = require('../../../src/server/grunt_config'); describe('GruntConfig', function() { var grunt, fs, config; beforeEach(function() { grunt = { loadTasks: sinon.stub() }; config = new GruntConfig(grunt); config.fs = fs = {}; }); describe('#registerCopyFromBower', function() { it('honors special cases', function() { var dirs = ['lodash', 'async']; var expected = { files: { 'lib/vendor/lodash.compat.js': 'bower_components/lodash/dist/lodash.compat.js', 'lib/vendor/async.js': 'bower_components/async/async.js' } }; grunt.config = sinon.spy(function(name, data) { expect(data).to.deep.equal(expected); }); fs.readdirSync = sinon.stub().returns(dirs); fs.statSync = sinon.stub().returns({ isFile: sinon.stub().returns(true) }); config.registerCopyFromBower(); expect(grunt.config).to.have.property('callCount', 1); }); }); describe('#registerCopyFromDist', function() { it('creates just one task including all modules', function() { var modules = ['thehelp-core', 'thehelp-test']; var expected = { files: [{ expand: true, cwd: 'node_modules/thehelp-core/dist', src: ['**/*'], dest: 'lib/vendor' },{ expand: true, cwd: 'node_modules/thehelp-test/dist', src: ['**/*'], dest: 'lib/vendor' }] }; grunt.config = sinon.spy(function(name, data) { expect(data).to.deep.equal(expected); }); config.registerCopyFromDist(modules); expect(grunt.config).to.have.property('callCount', 1); }); }); });
JavaScript
0.000002
@@ -669,16 +669,20 @@ s/async/ +lib/ async.js
bb131557519b6974c5baab06df8f158cb8d46e0c
Fix return type
lib/node_modules/@stdlib/streams/utils/inspect-sink/lib/object_mode.js
lib/node_modules/@stdlib/streams/utils/inspect-sink/lib/object_mode.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isObject = require( '@stdlib/assert/is-plain-object' ); var copy = require( '@stdlib/utils/copy' ); var Stream = require( './main.js' ); // MAIN // /** * Returns an inspect stream with `objectMode` set to `true`. * * @param {Options} [options] - stream options * @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false` * @param {boolean} [options.decodeStrings=true] - specifies whether to encode strings as `Buffer` objects before writing data to a returned stream * @param {string} [options.defaultEncoding='utf8'] - default encoding when not explicitly specified when writing data * @param {Callback} clbk - callback to invoke upon receiving data * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {TypeError} must provide a callback function * @returns {InspectStream} inspect stream * * @example * function log( chunk, idx ) { * console.log( 'index: %d', idx ); * console.log( chunk ); * } * * var stream = objectMode( log ); * * stream.write( {'value': 'a'} ); * stream.write( {'value': 'b'} ); * stream.write( {'value': 'c'} ); * * stream.end(); * * // prints: 'index: 0' * // prints: {'value': 'a'} * // prints: 'index: 1' * // prints: {'value': 'b'} * // prints: 'index: 2' * // prints: {'value': 'c'} */ function objectMode( options, clbk ) { var opts; var cb; if ( arguments.length > 1 ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); } opts = copy( options ); cb = clbk; } else { opts = {}; cb = options; } opts.objectMode = true; return new Stream( opts, cb ); } // EXPORTS // module.exports = objectMode;
JavaScript
0.000007
@@ -1549,16 +1549,20 @@ InspectS +inkS tream%7D i
be30f2db872909a4f2cf9c82adbd417f8bb4e6ea
Simplify the radioRenderDelegate so that we're not duplicating a bunch of the core sproutcore code.
apps/my_system/render_delegates/radio.js
apps/my_system/render_delegates/radio.js
// ========================================================================== // Project: SproutCore - JavaScript Application Framework // Copyright: ©2006-2011 Strobe Inc. and contributors. // Portions ©2008-2011 Apple Inc. All rights reserved. // License: Licensed under MIT license (see license.js) // ========================================================================== /** Renders and updates the DOM representation of a radio button (a single button, not the group). Expected Properties ----------------------------------- - `isSelected` - `isActive` - `isMixed` - `isEnabled` - `title` Optional Properties ----------------------------------- - `width` -- an optional width of the radio button - `labelRenderDelegate` properties */ sc_require('theme'); MySystem.Theme.radioRenderDelegate = SC.RenderDelegate.create({ className: 'radio', render: function(dataSource, context) { this.addSizeClassName(dataSource, context); var theme = dataSource.get('theme'); var isSelected = dataSource.get('isSelected'), width = dataSource.get('width'), color = dataSource.get('color'), labelId = SC.guidFor(dataSource) + '-label'; context.setClass({ active: dataSource.get('isActive'), mixed: dataSource.get('isMixed'), sel: dataSource.get('isSelected'), disabled: !dataSource.get('isEnabled') }); //accessing accessibility context.attr('role', 'radio'); context.attr('aria-checked', isSelected); context.attr('aria-labelledby', labelId); context.attr('aria-disabled', dataSource.get('isEnabled') ? 'false' : 'true'); if (width) context.css('width', width); if (color) { context.css('background-color', color); context.css('color', "#FFFFFF"); } context.css('font-weight', 'bold'); context.push('<span class = "button"></span>'); context = context.begin('span').addClass('sc-button-label').id(labelId); theme.labelRenderDelegate.render(dataSource, context); context = context.end(); }, update: function(dataSource, jquery) { this.updateSizeClassName(dataSource, jquery); var theme = dataSource.get('theme'); var isSelected = dataSource.get('isSelected'), width = dataSource.get('width'), color = dataSource.get('color'), value = dataSource.get('value'); jquery.setClass({ active: dataSource.get('isActive'), mixed: dataSource.get('isMixed'), sel: dataSource.get('isSelected'), disabled: !dataSource.get('isEnabled') }); jquery.attr('aria-disabled', dataSource.get('isEnabled') ? 'false' : 'true'); jquery.attr('aria-checked', isSelected); jquery.css('width', width ? width : null); jquery.css('background-color', color ? color : null); jquery.css('color', color ? "#FFFFFF" : null); theme.labelRenderDelegate.update(dataSource, jquery.find('.sc-button-label')); } });
JavaScript
0
@@ -962,768 +962,42 @@ -this.addSizeClassName(dataSource, context);%0A%0A var theme = dataSource.get('theme');%0A %0A var isSelected = dataSource.get('isSelected'),%0A width = dataSource.get('width'),%0A color = dataSource.get('color'),%0A labelId = SC.guidFor(dataSource) + '-label';%0A%0A context.setClass(%7B%0A active: dataSource.get('isActive'),%0A mixed: dataSource.get('isMixed'),%0A sel: dataSource.get('isSelected'),%0A disabled: !dataSource.get('isEnabled')%0A %7D);%0A%0A //accessing accessibility%0A context.attr('role', 'radio');%0A context.attr('aria-checked', isSelected);%0A context.attr('aria-labelledby', labelId);%0A context.attr('aria-disabled', dataSource.get('isEnabled') ? 'false' : 'true');%0A%0A if (width) context.css('width', width +var color = dataSource.get('color' );%0A%0A @@ -1149,153 +1149,115 @@ ');%0A +%0A -context.push('%3Cspan class = %22button%22%3E%3C/span%3E');%0A%0A context = context.begin('span').addClass('sc-button-label').id(labelId);%0A theme.label +// delegate the rest of the handling to the original%0A // radioRenderDelegate%0A SC.BaseTheme.radio Rend @@ -1300,37 +1300,8 @@ t);%0A - context = context.end();%0A %7D, @@ -1351,642 +1351,42 @@ -this.updateSizeClassName(dataSource, jquery);%0A%0A var theme = dataSource.get('theme');%0A%0A var isSelected = dataSource.get('isSelected'),%0A width = dataSource.get('width'),%0A color = dataSource.get('color'),%0A value = dataSource.get('value');%0A%0A jquery.setClass(%7B%0A active: dataSource.get('isActive'),%0A mixed: dataSource.get('isMixed'),%0A sel: dataSource.get('isSelected'),%0A disabled: !dataSource.get('isEnabled')%0A %7D);%0A%0A jquery.attr('aria-disabled', dataSource.get('isEnabled') ? 'false' : 'true');%0A jquery.attr('aria-checked', isSelected);%0A jquery.css('width', width ? width : null +var color = dataSource.get('color' );%0A @@ -1502,19 +1502,26 @@ -theme.label +SC.BaseTheme.radio Rend @@ -1560,33 +1560,8 @@ uery -.find('.sc-button-label') );%0A
4b752e2e17028fb005fde0189c872d3848e73197
remove unused dependencies
spec/javascripts/projects/gke_cluster_dropdowns/components/gke_machine_type_dropdown_spec.js
spec/javascripts/projects/gke_cluster_dropdowns/components/gke_machine_type_dropdown_spec.js
import Vue from 'vue'; import GkeMachineTypeDropdown from '~/projects/gke_cluster_dropdowns/components/gke_machine_type_dropdown.vue'; import { SET_PROJECT, SET_ZONE, SET_ZONES, SET_MACHINE_TYPES, } from '~/projects/gke_cluster_dropdowns/stores/mutation_types'; import mountComponent from 'spec/helpers/vue_mount_component_helper'; import { resetStore } from '../helpers'; import { selectedZoneMock, selectedProjectMock, selectedMachineTypeMock, gapiZonesResponseMock, gapiMachineTypesResponseMock, } from '../mock_data'; const componentConfig = { fieldId: 'cluster_provider_gcp_attributes_gcp_machine_type', fieldName: 'cluster[provider_gcp_attributes][gcp_machine_type]', }; const LABELS = { LOADING: 'Fetching machine types', DISABLED_NO_PROJECT: 'Select project and zone to choose machine type', DISABLED_NO_ZONE: 'Select zone to choose machine type', DEFAULT: 'Select machine type', }; const createComponent = (config = componentConfig) => { const Component = Vue.extend(GkeMachineTypeDropdown); return mountComponent(Component, config); }; describe('GkeMachineTypeDropdown', () => { let vm; beforeEach(() => { vm = createComponent(); }); afterEach(() => { vm.$destroy(); resetStore(vm.$store); }); describe('shows various toggle text depending on state', () => { it('returns disabled state toggle text when no project and zone are selected', () => { expect(vm.toggleText).toBe(LABELS.DISABLED_NO_PROJECT); }); it('returns disabled state toggle text when no zone is selected', () => { vm.$store.commit(SET_PROJECT, selectedProjectMock); expect(vm.toggleText).toBe(LABELS.DISABLED_NO_ZONE); }); it('returns loading toggle text', () => { vm.isLoading = true; expect(vm.toggleText).toBe(LABELS.LOADING); }); it('returns default toggle text', () => { expect(vm.toggleText).toBe(LABELS.DISABLED_NO_PROJECT); vm.$store.commit(SET_PROJECT, selectedProjectMock); vm.$store.commit(SET_ZONE, selectedZoneMock); expect(vm.toggleText).toBe(LABELS.DEFAULT); }); it('returns machine type name if machine type selected', () => { vm.setMachineType(selectedMachineTypeMock); expect(vm.toggleText).toBe(selectedMachineTypeMock); }); }); describe('form input', () => { it('reflects new value when dropdown item is clicked', done => { expect(vm.$el.querySelector('input').value).toBe(''); vm.$store.commit(SET_MACHINE_TYPES, gapiMachineTypesResponseMock.items); vm.$nextTick(() => { vm.$el.querySelector('.dropdown-content button').click(); vm.$nextTick(() => { expect(vm.$el.querySelector('input').value).toBe(selectedMachineTypeMock); done(); }); }); }); }); });
JavaScript
0.000003
@@ -168,21 +168,8 @@ NE,%0A - SET_ZONES,%0A SE @@ -445,33 +445,8 @@ ck,%0A - gapiZonesResponseMock,%0A ga
90b8d45b2ac5187010b168f72c1681e25e165016
Add passing test for pull-request from jhurliman
test/transports/loggly-test.js
test/transports/loggly-test.js
/* * loggly-test.js: Tests for instances of the Loggly transport * * (C) 2010 Charlie Robbins * MIT LICENSE * */ var path = require('path'), vows = require('vows'), assert = require('assert'), winston = require('../../lib/winston'), helpers = require('../helpers'); var config = helpers.loadConfig(), tokenTransport = new (winston.transports.Loggly)({ subdomain: config.transports.loggly.subdomain, inputToken: config.transports.loggly.inputToken }), nameTransport = new (winston.transports.Loggly)({ subdomain: config.transports.loggly.subdomain, inputName: config.transports.loggly.inputName, auth: config.transports.loggly.auth }); vows.describe('winston/transports/loggly').addBatch({ "An instance of the Loggly Transport": { "when passed an input token": { "should have the proper methods defined": function () { helpers.assertLoggly(tokenTransport); }, "the log() method": helpers.testNpmLevels(tokenTransport, "should log messages to loggly", function (ign, err, logged) { assert.isNull(err); assert.isTrue(logged); }) }, "when passed an input name": { "should have the proper methods defined": function () { helpers.assertLoggly(nameTransport); }, "the log() method": helpers.testNpmLevels(nameTransport, "should log messages to loggly", function (ign, err, result) { assert.isNull(err); assert.isTrue(result === true || result.response === 'ok'); }) } } }).export(module);
JavaScript
0
@@ -1141,24 +1141,301 @@ d);%0A %7D) +,%0A %22the log() method with no metadata%22: %7B%0A topic: function () %7B%0A tokenTransport.log('info', 'test-message', null, this.callback.bind(null, null));%0A %7D,%0A %22should respond immediately%22: function () %7B%0A assert.isTrue(true);%0A %7D%0A %7D %0A %7D,%0A
4bcf47eafe51bc94f37b28b9ce91cb54688633e8
Generalize test naming
test/unit/actions/indexSpec.js
test/unit/actions/indexSpec.js
import configureStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import { expect } from 'chai'; import { storeEntityIfNew, fetchEntities } from '../../../src/actions/index'; import * as types from '../../../src/actions/types'; describe('actions', function () { function createStore(services, initialEntityItems = []) { const initialState = { entities: { status: '', items: initialEntityItems } }; const getState = () => initialState; const mockStore = configureStore([ thunk.withExtraArgument(services) ]); return mockStore(getState); } describe('storeEntityIfNew', function () { it('should dispatch ADD_ENTITY with an entity when successful', function () { const entity = { name: 'foo' }; const services = { storeEntity: () => Promise.resolve(entity) }; const store = createStore(services); return store.dispatch(storeEntityIfNew(entity.name)) .then(() => { const expectedActions = [ { type: types.ADD_ENTITY, payload: { status: 'storing' } }, { type: types.ADD_ENTITY, payload: { status: 'success', entity } } ]; expect(store.getActions()).to.deep.equal(expectedActions); }); }); it('should dispatch ADD_ENTITY with a warning if the entity already existed locally', function () { const entity = { name: 'foo' }; const services = { storeEntity: () => Promise.resolve(entity) }; const store = createStore(services, [ entity ]); return store.dispatch(storeEntityIfNew(entity.name)) .then(() => { const warning = 'Entity with that name was already present. Not adding.'; const expectedActions = [ { type: types.ADD_ENTITY, payload: { status: 'warning', warning } } ]; expect(store.getActions()).to.deep.equal(expectedActions); }); }); it('should dispatch ADD_ENTITY with an error status if there was an error', function () { const entity = { name: 'foo' }; const errorMessage = 'any error'; const services = { storeEntity: () => Promise.reject(new Error(errorMessage)) }; const store = createStore(services); return store.dispatch(storeEntityIfNew(entity.name)) .then(() => { const expectedActions = [ { type: types.ADD_ENTITY, payload: { status: 'storing' } }, { type: types.ADD_ENTITY, payload: { status: 'error', error: errorMessage } } ]; expect(store.getActions()).to.deep.equal(expectedActions); }); }); }); describe('fetchEntities', function () { it('should dispatch REQUEST_ENTITIES with the correct status when successful', function () { const entitiesInResponse = [ { name: 'entity1' }, { name: 'entity2' } ]; const services = { fetchEntities: () => Promise.resolve(entitiesInResponse) }; const store = createStore(services); return store.dispatch(fetchEntities()) .then(() => { const expectedActions = [ { type: types.REQUEST_ENTITIES, payload: { status: 'fetching' } }, { type: types.REQUEST_ENTITIES, payload: { status: 'success', items: entitiesInResponse } } ]; expect(store.getActions()).to.deep.equal(expectedActions); }); }); it('should dispatch REQUEST_ENTITIES with an error status if there was an error', function () { const errorMessage = 'any error'; const services = { fetchEntities: () => Promise.reject(new Error(errorMessage)) }; const store = createStore(services); return store.dispatch(fetchEntities()) .then(() => { const expectedActions = [ { type: types.REQUEST_ENTITIES, payload: { status: 'fetching' } }, { type: types.REQUEST_ENTITIES, payload: { status: 'error', error: errorMessage } } ]; expect(store.getActions()).to.deep.equal(expectedActions); }); }); }); });
JavaScript
0.001117
@@ -732,34 +732,46 @@ tch -ADD_ENTITY wi +an action containing th +e a -n +dded entity when @@ -766,20 +766,18 @@ entity -when +if success @@ -1419,31 +1419,36 @@ ispatch -ADD_ENTITY with +an action containing a warni @@ -2154,23 +2154,28 @@ tch -ADD_ENTITY with +an action containing an @@ -2172,38 +2172,39 @@ aining an error -status +message if there was an @@ -2978,53 +2978,52 @@ tch -REQUEST_ENTITIES with the correct status when +an action containing the fetched entities if suc @@ -3746,29 +3746,28 @@ tch -REQUEST_ENTITIES with +an action containing an @@ -3772,22 +3772,23 @@ n error -status +message if ther
9956f54a1e34d66f1d2af3a89d245b36681b4d8f
Change default port to 3333
packages/@sanity/util/src/getConfig.js
packages/@sanity/util/src/getConfig.js
import path from 'path' import get from 'lodash/get' import merge from 'lodash/merge' import {loadJsonSync} from './safeJson' const defaults = { server: { staticPath: './static', port: 3910, hostname: 'localhost' } } const configContainer = values => ({ get: (dotPath, defaultValue) => get(values, dotPath, defaultValue) }) const getConfig = rootDir => { const localConfig = rootDir && loadJsonSync(path.join(rootDir, 'sanity.json')) const config = localConfig ? merge({}, defaults, localConfig) : defaults return configContainer(config) } export default getConfig
JavaScript
0.000001
@@ -194,11 +194,11 @@ t: 3 -910 +333 ,%0A
14033520a6dc9e78ae53c9b4776a7d0d114226f5
fix equality test
purelyjs/js/purely.js
purelyjs/js/purely.js
var purely = { throwAssertionError: function(msg) { // throws TypeError as there isn't a built-in assertion error type throw TypeError('AssertionError: ' + msg); /* // Safer alternative? throw { name: 'TypeError', message: 'AssertionError: ' + msg }; */ }, contains: function(item, arr) { var found = false; for (var i = 0; i < arr.length; i++) { if (arr[i] === item) { found = true; break; } } return found; }, assertEqual: function(x, y) { // jshint -W018 if (!(x === y)) { purely.throwAssertionError((x && x.toString()) + ' === ' + (y && y.toString())); } }, assertNotEqual: function(x, y) { // jshint -W018 if (!(x !== y)) { purely.throwAssertionError((x && x.toString()) + ' !== ' + (y && y.toString())); } }, assertGreater: function(x, y) { // jshint -W018 if (!(x > y)) { purely.throwAssertionError((x && x.toString()) + ' > ' + (y && y.toString())); } }, assertGreaterEqual: function(x, y) { // jshint -W018 if (!(x >= y)) { purely.throwAssertionError((x && x.toString()) + ' >= ' + (y && y.toString())); } }, assertLess: function(x, y) { // jshint -W018 if (!(x < y)) { purely.throwAssertionError((x && x.toString()) + ' < ' + (y && y.toString())); } }, assertLessEqual: function(x, y) { // jshint -W018 if (!(x <= y)) { purely.throwAssertionError((x && x.toString()) + ' <= ' + (y && y.toString())); } }, assertIn: function(item, arr) { var found = purely.contains(item, arr); if (!found) { purely.throwAssertionError((item && item.toString()) + ' not in ' + (arr && arr.toString())); } }, assertNotIn: function(item, arr) { var found = purely.contains(item, arr); if (found) { purely.throwAssertionError((item && item.toString()) + ' in ' + (arr && arr.toString())); } }, assertRaises: function(exceptionName, func) { var thrown = false; try { func(); } catch (e) { if (e.name === exceptionName) { thrown = true; } } if (!thrown) { purely.throwAssertionError(exceptionName + ' not thrown'); } }, assertRaisesAssertion: function(func) { var thrown = false; try { func(); } catch (e) { if ((e.name == 'TypeError') && (/^AssertionError: /.test(e.message))) { thrown = true; } } if (!thrown) { purely.throwAssertionError('AssertionError not thrown'); } } };
JavaScript
0.00011
@@ -2753,16 +2753,17 @@ .name == += 'TypeEr
33757b6bd467c8a73ca7bf5389720a319681c292
" missed
static/js/client.js
static/js/client.js
(function($) { //user PopupLogin = Backbone.View.extend({ initialize: function(){ }, el: '#login', events: { 'click button': 'login' }, login: function(){ askLogin(); } }); Login = Backbone.View.extend({ initialize: function(){ }, el: '#modal1', events: { 'submit form': 'submit' }, submit: function(e){ e.preventDefault() if(pseudo != ''){ socket.emit('username', pseudo); $('#login').remove(); $('#user-name').html('<label for="right-label" class="inline"><b><div id="user-button">' + pseudo + '</div></b></label>'); $('#user-form').html('<input type="text" required="required" name="message" id="message" placeholder="Push Enter to send your message" style="height:50%; margin-top:7px;" autofocus />'); $('#user').html(pseudo); $('#modal1').remove(); $('#open-modal1').remove(); } }}); //Messages Message = Backbone.View.extend({ /* * Getting messages from the server and displaying it */ initialize: function(){ socket.on('getPosts', function (messages) { var html = ''; for (var i = 0; i < messages.length; i++) html += '<div id="line">'+messages[i].hour+' <b>'+messages[i].pseudo+'</b> : '+messages[i].message+'</div>'; $('#tchat').html(html); scrollBottom(); }); socket.on('userlist', function (users) { var html = ''; for (var i = 0; i < users.length; i++) html += '<li style="text-align:center; color:#e6e6e6;">'+users[i]+'</li>'; $('#userlist').html(html); $('#nbusers').html(users.length); scrollBottom(); }); socket.on('getNewPosts', function (message) { document.getElementById('tchat').innerHTML += '<div id="line"><b>'+message.pseudo+'</b> : '+message.message+'</div>'; //var message.hour = [hh:mm:ss]; scrollBottom(); }); socket.on('addUsername', function (pseudo) { document.getElementById('tchat').innerHTML += '<div id="line"><b>bot</b> : '+pseudo+' is now connected.</div>'; scrollBottom(); }); socket.on('removeUsername', function (pseudo) { document.getElementById('tchat').innerHTML += '<div id="line"><b>bot</b> : '+pseudo+' was disconnected.</div>'; scrollBottom(); }); socket.on('reply', function (reply){ document.getElementById('tchat').innerHTML += '<div id="line" style="font-size:12px;>'+reply+'</div>'; scrollBottom(); }) }, postmessage: function(e){ //e.preventDefault(); //Code if we have to execute something when someone posted a message console.log('okay'); } }); var popupLogin = new PopupLogin(); var Login = new Login(); var message = new Message(); }).call(this, jQuery);
JavaScript
0.999763
@@ -2725,16 +2725,17 @@ ze:12px; +%22 %3E'+reply
9533757972b16d259bc29f6d36aeefe55c83018b
increase donation timeout
static/js/donate.js
static/js/donate.js
function isMSIE() { return (navigator.userAgent.indexOf('MSIE') != -1); } function showDonateRibbon() { var ribbon = $("#donate"); ribbon.children('.amounts').show(); ribbon.children('.types').hide(); ribbon.attr('style', 'display: none;'); $("#video").hide(); if (!isMSIE()) { ribbon.css('opacity', 0.6); } ribbon.show(); if (!isMSIE()) { everythingElse = $("#header").add(".column.left").add(".column.right > *"); everythingElse.css('opacity', "0.6"); ribbon.animate({opacity: 1}, 'fast'); } } function hideDonateRibbon() { ribbon = $("#donate"); everythingElse = $("#header").add(".column.left").add(".column.right > *"); if (!isMSIE()) { everythingElse.animate({ opacity: 1}, 'fast', function() { everythingElse.css('opacity', '1');}); ribbon.animate({opacity: 0}, 'fast', function() { ribbon.hide(); $("#video").show(); }); } else { ribbon.hide(); $("#video").show(); } } $(document).ready(function () { $("#donate .amounts div").click(function () { var amount; if ($(this).hasClass('other')) { amount = $(this).children('input').val(); if (!amount) { $(this).children('input').css('border-color', 'red'); return; } } else { amount = $(this).attr('amount'); } paypal = $("#donate .types a:eq(0)"); if (!paypal.attr('oldHref')) paypal.attr('oldHref', paypal.attr('href')); paypal.attr('href', paypal.attr('oldHref') + '&amount=' + amount); cc = $("#donate .types a:eq(1)"); if (!cc.attr('oldHref')) cc.attr('oldHref', cc.attr('href')); cc.attr('href', cc.attr('oldHref') + '?' + amount); $("#donate .types").show(); $("#donate .amounts").hide(); }); $("#donate .amounts input").keypress(function(e) { if (e.which == 13) $(this).parent().click(); }).click(function() {return false;}); }); function setThanksTimeout(url) { $("#donate a:lt(2)").click(function () { setTimeout(function() { document.location = url; }, 1000); return true; }); } function vlcPlayPause(obj, button) { if (obj.isplaying() == true) { obj.pause(); button.attr('value', 'Play'); } else { obj.play(); button.attr('value', 'Pause'); } } function vlcRestart(obj) { obj.stop(); obj.play(); } function createVideo(obj, flv, mp4, image, width, height) { win = 0; var htmlCode = ''; if (navigator.mimeTypes['application/x-shockwave-flash'] && navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) { height = height + 19; var htmlCode = '<embed ' + 'src="http://s3.miroguide.com/static/images/mediaplayer.swf" '+ 'width="' + width + '" ' + 'height="' + height + '" ' + 'allowscriptaccess="always" ' + 'allowfullscreen="true" ' + 'flashvars="height=' + height + '&width=' + width + '&file=' + flv + '&image=' + image + '&showdigits=false&usefullscreen=false" '+ '/>'; } else if (navigator.mimeTypes["application/x-vlc-plugin"] && navigator.mimeTypes["application/x-vlc-plugin"].enabledPlugin) { /* use VLC */ htmlCode = '<embed type="application/x-vlc-plugin" width=' + width + ' height=' + height + ' autoplay="no" loop="no" name="video1" target="' + mp4 + '" />' + '<input id="playpause" type="button" value="Play" onclick="vlcPlayPause(document.video1, $(\'#playpause\'));" />' + '<input type="button" value="Restart" onclick="vlcRestart(document.video1);" />' + '<input type="button" value="Mute" onclick="document.video1.mute(); document.video1.get_volume();" />' win = 1; height = height + 23; } else if (navigator.mimeTypes["video/quicktime"] && navigator.mimeTypes["video/quicktime"].enabledPlugin) { height = height + 19; htmlCode = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" id="player" height="' + height +'" width="' + width + '">' + '<param name="CONTROLS" value="imagewindow">'+ '<param name="autogotourl" value="false">'+ '<param name="console" value="radio">'+ '<param name="autostart" value="false">'+ '<param name="type" value="video/quicktime">'+ '<param name="src" value="' + mp4 + '">'+ '<embed controls="imagewindow" autogotourl="false" console="radio" autostart="false" type="video/quicktime" src="' + mp4 + '" name="player" height="' + height +'" width="' + width + '">'+ '</object>'; } if (htmlCode != '') { obj.html(htmlCode).height(height); if (win) { for (var i=10; i<=100; i+= 10) { window.setTimeout(function(){ document.video1.set_volume(i); }, i); } } } }
JavaScript
0
@@ -2006,17 +2006,17 @@ rl;%0A%09%7D, -1 +5 000);%0A%09r
c519b4779adf09a693b8b27661df10e52bd9148f
Update script.js
static/js/script.js
static/js/script.js
/** * 页面ready方法 */ $(document).ready(function() { console.log("你不乖哦,彼此之间留点神秘感不好吗?"); backToTop(); search(); }); /** * 回到顶部 */ function backToTop() { $("[data-toggle='tooltip']").tooltip(); var st = $(".page-scrollTop"); var $window = $(window); var topOffset; //滚页面才显示返回顶部 $window.scroll(function() { var currnetTopOffset = $window.scrollTop(); if (currnetTopOffset > 0 && topOffset > currnetTopOffset) { st.fadeIn(500); } else { st.fadeOut(500); } topOffset = currnetTopOffset; }); //点击回到顶部 st.click(function() { $("body").animate({ scrollTop: "0" }, 500); }); } function search(){ (function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){ (w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t); e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.appendChild(s); })(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st'); _st('install','ncwR9a8S9CTx2q9SgsJm','2.0.0'); }
JavaScript
0.000002
@@ -67,25 +67,17 @@ og(%22 -%E4%BD%A0%E4%B8%8D%E4%B9%96%E5%93%A6%EF%BC%8C%E5%BD%BC%E6%AD%A4%E4%B9%8B%E9%97%B4%E7%95%99%E7%82%B9%E7%A5%9E%E7%A7%98%E6%84%9F%E4%B8%8D%E5%A5%BD%E5%90%97 +%E8%BF%99%E4%B9%88%E7%8C%B4%E6%80%A5%EF%BC%8C%E6%89%92%E6%88%91%E8%A1%A3%E6%9C%8D %EF%BC%9F%22);
85641e0db06224488dab96f69eed31f0b2a0d4ba
Use a more recent Android for integration tests
tests/integration/config-ci.js
tests/integration/config-ci.js
// this file is for use in CircleCI continuous integration environment var browserName = ['chrome', 'firefox', 'internet explorer', 'android'][process.env.CIRCLE_NODE_INDEX]; module.exports = { seleniumServerURL: { hostname: 'ondemand.saucelabs.com', port: 80 }, driverCapabilities: { 'tunnel-identifier': 'circle-' + process.env.CIRCLE_BUILD_NUM + '-' + process.env.CIRCLE_NODE_INDEX, browserName: browserName }, tags: [ 'circle-ci', '#' + process.env.CIRCLE_BUILD_NUM ], views: [ 'Verbose', 'SauceLabs' ], quit: 'always', // avoid wasting 90 seconds on SauceLabs bail: true, build: 'CircleCI#' + process.env.CIRCLE_BUILD_NUM }
JavaScript
0
@@ -69,16 +69,36 @@ nt%0A%0Avar +capabilities = %5B%0A %7B browserN @@ -104,20 +104,18 @@ Name +: -= %5B 'chrome' , 'f @@ -114,51 +114,226 @@ ome' -, 'firefox', 'internet explorer', 'android' +%7D,%0A %7BbrowserName: 'firefox'%7D,%0A %7BbrowserName: 'internet explorer'%7D,%0A %7B%0A deviceName: 'Samsung Galaxy S6 GoogleAPI Emulator',%0A browserName: 'Chrome',%0A platformName: 'Android',%0A platformVersion: '7.0'%0A %7D%0A %5D%5Bpr @@ -485,22 +485,57 @@ lities: -%7B%0A +Object.assign(%7B%7D,%0A capabilities,%0A %7B 'tunnel- @@ -629,42 +629,13 @@ NDEX -,%0A browserName: browserName%0A %7D +%7D%0A ) ,%0A
2ab41ec1f71f405f7e718db2f11acbc010862b0d
Break loop as soon as change detected.
packages/babel/src/transformation/transformers/internal/block-hoist.js
packages/babel/src/transformation/transformers/internal/block-hoist.js
import sortBy from "lodash/collection/sortBy"; export var metadata = { group: "builtin-trailing" }; /** * [Please add a description.] * * Priority: * * - 0 We want this to be at the **very** bottom * - 1 Default node position * - 2 Priority over normal nodes * - 3 We want this to be at the **very** top */ export var visitor = { /** * [Please add a description.] */ Block: { exit(node) { var hasChange = false; for (var i = 0; i < node.body.length; i++) { var bodyNode = node.body[i]; if (bodyNode && bodyNode._blockHoist != null) hasChange = true; } if (!hasChange) return; node.body = sortBy(node.body, function(bodyNode){ var priority = bodyNode && bodyNode._blockHoist; if (priority == null) priority = 1; if (priority === true) priority = 2; // Higher priorities should move toward the top. return -1 * priority; }); } } };
JavaScript
0
@@ -586,16 +586,28 @@ != null) + %7B%0A hasChan @@ -617,16 +617,43 @@ = true;%0A + break;%0A %7D%0A %7D%0A
f703a87e95a4df41fd4ff7e49b1285e88907400a
fix negative bar width
extra/nc_web_viewer/GroupedBarChart.js
extra/nc_web_viewer/GroupedBarChart.js
/*global d3 */ function GroupedBarChart(name,logaxis){ var id = "#"+name.replace(/\./g,'\\.'); var margin = {top: 20, right: 20, bottom: 30, left: 40}; //Add CSS to the div d3.select(id).style({ "overflow-y":"auto", "overflow-x":"hidden" }); var widget = this; //Make draggable and resizable d3.select(id).attr("class","resize-drag"); d3.select(id).on("divresize",function(){ widget.redraw(); }); //Collapse on dbl click d3.select(id).on('dblclick',function(d){ var currentheight = d3.select(id).style("height"); if ( currentheight != "20px"){ widget.restoreHeight =currentheight ; d3.select(id).style('height','20px'); } else{ d3.select(id).style("height",widget.restoreHeight); } }); //SVG container var svg = d3.select(id).append("svg").append("g"); //Title svg.append("text").attr('y',-5).text(name); //Axes svg.append("g").attr("class", "y axis") .attr("transform", "translate(-3,0)"); svg.append("g").attr("class", "x axis"); //Scales var y0 = d3.scale.ordinal(); var y1 = d3.scale.ordinal(); var x = d3.scale.linear(); if (logaxis){ x = d3.scale.log(); } //Axis var xAxis = d3.svg.axis(); var yAxis = d3.svg.axis(); xAxis.orient("bottom").ticks(3,",.1s"); yAxis.orient("left"); //Save vars to "this" this.margin = margin; this.svg=svg; this.y0=y0; this.y1=y1; this.x=x; this.xAxis = xAxis; this.yAxis = yAxis; this.id = id; this.data = {}; this.selection=null; } GroupedBarChart.prototype.redraw = function(){ var fdata = this.flattenData(this.data); var x =this.x; var y0 =this.y0; var y1 =this.y1; var svg =this.svg; var selection = this.selection; svg.on('click', this.click_callback); //update the axis and svgframe this.updateYAxis(fdata); this.updateXAxis(fdata); this.updateSVG(); var widget = this; //bind data var bars = this.svg.selectAll('.bar').data(fdata); //append new bars bars.enter() .append('rect') .attr('class', 'bar') .append("svg:title"); //tooltip //set shape bars.attr('x', 1) .attr('y', function(d){ return y0(d.cat) + y1(d.color); }) //selection group .attr('height',function(d){ return y1.rangeBand()-1;}) .attr('width',function(d){ return x(d.value); }) .on('click', widget.click_callback) //toggle callback .style('fill', function(d){ if (selection.length < 1 //no selection (everything) || (selection.indexOf(d.addr)!=-1)){//addr in selection return d.color; } else{ return 'gray'; } }) .transition().duration(100); //add tool tip bars.select('title').text(function(d){ return d3.format(',')(d.value); }); //remove bars with no data bars.exit().remove(); }; GroupedBarChart.prototype.updateSVG = function(){ var svg = this.svg; var margin = this.margin; var svgframe = d3.select(svg.node().parentNode); var rect=svgframe.node().parentNode.getBoundingClientRect(); //calculate width and height in side the margin var width = rect.width-margin.left-margin.right; var height = this.totalheight; //resize the frame svgframe.attr("width", width + margin.left + margin.right); svgframe.attr("height", height + margin.top + margin.bottom); svg.attr("transform", "translate("+margin.left+","+margin.top+")"); this.width = width; this.height = height; }; GroupedBarChart.prototype.updateXAxis=function(data){ var margin = this.margin; var x=this.x; var xAxis=this.xAxis; var svg=this.svg; var svgframe = d3.select(svg.node().parentNode); var rect=svgframe.node().parentNode.getBoundingClientRect(); var width = rect.width - this.margin.left-this.margin.right; x.domain([d3.min(data, function(d) {return +d.value;})*0.5 , d3.max(data, function(d) {return +d.value;})]); x.range([0,width]); xAxis.scale(x); //move and draw the axis svg.select('.x.axis') .attr("transform", "translate(0,"+this.totalheight+")") .call(xAxis); this.width=width; }; GroupedBarChart.prototype.updateYAxis=function(data){ var y0=this.y0; var y1=this.y1; var yAxis=this.yAxis; var svg = this.svg; y0.domain(data.map(function(d){return d.cat;})); y1.domain(data.map(function(d){return d.color;})); var totalheight = y0.domain().length* y1.domain().length * 18; y0.rangeRoundBands([0, totalheight]); y1.rangeRoundBands([0, y0.rangeBand()]); yAxis.scale(y0); svg.select('.y.axis').call(yAxis); //enable axis click var widget = this; svg.select('.y.axis').selectAll('.tick') .on('click',function(d){ var obj = data.filter(function(e){return e.cat==d;})[0]; widget.click_callback(obj); }); this.totalheight = totalheight; this.margin.left = svg.select('.y.axis').node().getBBox().width+10; }; GroupedBarChart.prototype.setData = function(data,id,color){ this.data[id] = {color:color, data: data}; }; GroupedBarChart.prototype.setSelection = function(sel){ this.selection = sel; }; GroupedBarChart.prototype.removeData = function(id){ if (id in this.data){ delete this.data[id]; } }; GroupedBarChart.prototype.flattenData = function(data){ return Object.keys(data).reduce(function(prev,curr){ var row = Object.keys(data[curr].data).map(function(k){ return { addr: data[curr].data[k].addr, cat: data[curr].data[k].cat, color: data[curr].color, value:data[curr].data[k].value }; }); return prev.concat(row); }, []); }; GroupedBarChart.prototype.setClickCallback = function(cb){ this.click_callback = cb; };
JavaScript
0.000007
@@ -2310,17 +2310,17 @@ tr('x', -1 +0 )%0A
c6e496c7cd5bed0ca23ae32f805cfbd70f832bc9
Improve saved Filter View Items hover effects
src/components/Filters/ViewsMenu.js
src/components/Filters/ViewsMenu.js
import * as cloneDeep from 'lodash/cloneDeep' import * as React from 'react' import styled from 'styled-components' import { Box } from '../Grid' import Text from '../Text' import * as FaTrash from 'react-icons/lib/fa/trash' import * as FaPieChart from 'react-icons/lib/fa/pie-chart' import DropDownButton from '../DropDownButton' import FilterDescription from './FilterDescription' const Wrapper = styled.div`` const UnstyledList = styled.ul` list-style: none; padding: 0 !important; margin: 0; ` const PlainPanel = styled.div` border-radius: 2px; background-color: #ffffff; box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.1); border: solid 1px #9b9b9b; ` const Preview = styled(PlainPanel)` display: none; position: absolute; right: 230px; width: 300px; right: 100%; margin-right: 3px; top: 2px; padding: 15px 15px 5px; ` const ViewListItem = styled.li` position: relative; padding: 7px 40px 7px 20px; &:hover { background-color: #f3f3f3; } & > p { padding-right: 20px; } & > button { position: absolute; top: 50%; transform: translateY(-50%); right: 2px; padding: 8px; background: none; border: none; display: none; cursor: pointer; } &:hover > button { display: block; } &:hover ${Preview} { display: block; } ` class ViewsMenu extends React.Component { constructor (props) { super(props) this.state = { showViewsMenu: false } } loadView (view) { const rules = cloneDeep(view.rules) this.props.setRules(rules) this.setState({ showViewsMenu: false }) } render () { const { views } = this.props const hasViews = views.length > 0 && views.reduce((sum, item) => sum + item.data.length, 0) > 0 return ( <Wrapper> <DropDownButton disabled={this.props.disabled} joined alignRight noListFormat label={ <span> <FaPieChart style={{ marginRight: 10 }} /> Views </span> } > <Box py={1}> {!hasViews && ( <Box py={2} px={3}> {"You haven't created any views yet"} </Box> )} {hasViews && views.map(scope => { if (!scope.data || !scope.data.length) { return } return ( <Box key={scope.key}> {!!scope.title && ( <Text fontSize={13} ml={20} mb={2} mt={2} color='#aaa'> {scope.title} </Text> )} <UnstyledList> {scope.data.map(view => ( <ViewListItem key={view.name}> <Text m={0} onClick={() => this.loadView(view)}> {view.name} <br /> <Text m={0} fontSize={12} color='#aaa'> {view.rules.length} filter{view.rules.length > 1 && 's'} </Text> </Text> <button onClick={() => this.props.deleteView(view, scope.key)} > <FaTrash name='trash' /> </button> <Preview> {view.rules.map(rule => ( <Box mb={10} key={rule.id}> <FilterDescription rule={rule} /> </Box> ))} </Preview> </ViewListItem> ))} </UnstyledList> </Box> ) })} </Box> </DropDownButton> </Wrapper> ) } } export default ViewsMenu
JavaScript
0
@@ -1263,56 +1263,175 @@ ;%0A -%7D%0A &:hover $%7BPreview%7D %7B%0A display: block;%0A %7D + opacity: 0.7;%0A %7D%0A %3E button:hover %7B%0A opacity: 1;%0A %7D%0A &:hover $%7BPreview%7D %7B%0A display: block;%0A %7D%0A%60%0A%0Aconst ViewListItemLabel = styled(Text)%60%0A cursor: pointer; %0A%60%0A%0A @@ -2955,26 +2955,95 @@ %3C -Text m=%7B0%7D +ViewListItemLabel%0A m=%7B0%7D%0A onClick @@ -3070,16 +3070,43 @@ w(view)%7D +%0A %3E%0A @@ -3385,36 +3385,49 @@ %3C/ -Text +ViewListItemLabel %3E%0A
7d75bfaa274eae503e318bacfcfbd65ab613a6b1
improve example
docs/data/interscript.js
docs/data/interscript.js
const { // Interactive content details, summary, // Scripting script, canvas } = htmlmodule const { a, body, h1, h2, article, section, p } = htmlmodule const evilscript = script(`(${(() => { alert('Error!\n' + '\nThe application is broken by user.' + ' Do not report an issue, please.' + ' Reload the page and follow the "Index" reference to continue.') parent.document.documentElement.remove() }).toString()})()`) const dangerbutton = canvas({ width : 150, height : 150, onclick : () => { if(confirm('Are you sure?')) { document.body.append(evilscript) } }, children : 'Don\'t click!' }) const ctx = dangerbutton.getContext('2d') ctx.strokeStyle = '#000' ctx.strokeRect(10, 10, 130, 130) ctx.fillStyle = '#f00' ctx.fillRect(10, 10, 130, 130) ctx.font = '30px Arial' ctx.fillStyle = '#fff' ctx.fillText('DON\'T!', 24, 85) document.body = body(article([ h1([a({ href : '#', target : '_top', children : 'Index' }), ' → Interactive and scripting']), section([ h1('Details and summary'), details([ summary('Danger! Don\'t open!'), h1('Canvas and script'), p(['Do not click the canvas below! ', 'It appends a very stupid script ' + 'to the document\'s body!']), dangerbutton ]) ]) ]))
JavaScript
0.000031
@@ -122,16 +122,21 @@ ody, + del, h1, h2, art @@ -131,16 +131,21 @@ h1, h2, + ins, article @@ -1322,25 +1322,59 @@ ery -stupid script ' + +',%0A del('evil'), ' ', ins('stupid'), %0A @@ -1387,16 +1387,24 @@ ' + script to the d
bdcad9920dfac2a021773d5a469d9610ff3347a6
Switch from DOS newlines to Unix newlines
filer/static/filer/js/addons/popup_handling.js
filer/static/filer/js/addons/popup_handling.js
'use strict'; /* global django */ (function ($) { window.dismissPopupAndReload = function (win) { document.location.reload(); win.close(); }; window.dismissRelatedImageLookupPopup = function (win, chosenId, chosenThumbnailUrl, chosenDescriptionTxt) { var name = window.windowname_to_id(win.name); var nameElement = $('#' + name); var id = nameElement.data('id'); var img = $('#' + id + '_thumbnail_img'); var txt = $('#' + id + '_description_txt'); var clear = $('#' + id + '_clear'); var lookup = $('#' + id + '_lookup'); var dropzoneMessage = $('#' + id + '_filer_dropzone_message'); var elem = $('#' + id); var oldId = elem.value; elem.val(chosenId); elem.closest('.js-filer-dropzone').addClass('js-object-attached'); img.attr('src', chosenThumbnailUrl).removeClass('hidden'); txt.text(chosenDescriptionTxt); clear.removeClass('hidden').removeAttr('style'); lookup.addClass('hidden'); dropzoneMessage.addClass('hidden'); if (oldId !== chosenId) { $(elem).trigger('change'); } win.close(); }; window.dismissRelatedFolderLookupPopup = function (win, chosenId, chosenName) { var id = window.windowname_to_id(win.name); var clearButton = $('#id_' + id + '_clear'); var input = $('#id_' + id); var folderName = $('#id_' + id + '_description_txt'); var addFolderButton = $('#' + id); input.val(chosenId); folderName.text(chosenName); clearButton.removeClass('hidden'); addFolderButton.addClass('hidden'); win.close(); }; })(django.jQuery);
JavaScript
0.000001
@@ -6,17 +6,16 @@ strict'; -%0D %0A/* glob @@ -26,19 +26,17 @@ jango */ -%0D%0A%0D +%0A %0A(functi @@ -43,17 +43,16 @@ on ($) %7B -%0D %0A win @@ -95,17 +95,16 @@ (win) %7B -%0D %0A @@ -131,17 +131,16 @@ eload(); -%0D %0A @@ -148,33 +148,31 @@ win.close(); -%0D %0A %7D; -%0D %0A window. @@ -272,17 +272,16 @@ onTxt) %7B -%0D %0A @@ -318,33 +318,32 @@ to_id(win.name); -%0D %0A var nam @@ -363,25 +363,24 @@ '#' + name); -%0D %0A var @@ -404,25 +404,24 @@ .data('id'); -%0D %0A var @@ -458,17 +458,16 @@ l_img'); -%0D %0A @@ -502,33 +502,32 @@ scription_txt'); -%0D %0A var cle @@ -546,33 +546,32 @@ id + '_clear'); -%0D %0A var loo @@ -600,17 +600,16 @@ ookup'); -%0D %0A @@ -667,25 +667,24 @@ e_message'); -%0D %0A var @@ -695,33 +695,32 @@ m = $('#' + id); -%0D %0A var old @@ -735,19 +735,17 @@ m.value; -%0D%0A%0D +%0A %0A @@ -756,33 +756,32 @@ m.val(chosenId); -%0D %0A elem.cl @@ -839,17 +839,16 @@ ached'); -%0D %0A @@ -898,33 +898,32 @@ Class('hidden'); -%0D %0A txt.tex @@ -946,17 +946,16 @@ ionTxt); -%0D %0A @@ -999,25 +999,24 @@ tr('style'); -%0D %0A loo @@ -1030,33 +1030,32 @@ Class('hidden'); -%0D %0A dropzon @@ -1082,19 +1082,17 @@ idden'); -%0D%0A%0D +%0A %0A @@ -1117,17 +1117,16 @@ senId) %7B -%0D %0A @@ -1156,17 +1156,16 @@ hange'); -%0D %0A @@ -1166,17 +1166,16 @@ %7D -%0D %0A @@ -1187,25 +1187,23 @@ close(); -%0D %0A %7D; -%0D %0A win @@ -1278,17 +1278,16 @@ nName) %7B -%0D %0A @@ -1326,25 +1326,24 @@ d(win.name); -%0D %0A var @@ -1383,17 +1383,16 @@ clear'); -%0D %0A @@ -1419,17 +1419,16 @@ ' + id); -%0D %0A @@ -1481,17 +1481,16 @@ n_txt'); -%0D %0A @@ -1528,11 +1528,9 @@ id); -%0D%0A%0D +%0A %0A @@ -1554,17 +1554,16 @@ osenId); -%0D %0A @@ -1591,17 +1591,16 @@ enName); -%0D %0A @@ -1626,33 +1626,32 @@ Class('hidden'); -%0D %0A addFold @@ -1678,17 +1678,16 @@ idden'); -%0D %0A @@ -1703,17 +1703,15 @@ e(); -%0D %0A %7D; -%0D %0A%7D)( @@ -1729,6 +1729,5 @@ ry); -%0D %0A
274a98e5cc1f044ebe925aa3c89463a69414209a
Remove unnessary definition of jquery module (now specified in webpack.config.js.
Basiljs/src/Controls/index.js
Basiljs/src/Controls/index.js
// Copyright 2018 Robert Adams // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; // holds the controls context for this threejs instance import GP from 'GP'; import Config from 'xConfig'; import * as $ from 'jquery'; import * as Graphics from 'xGraphics'; import * as Comm from 'xComm'; import * as Eventing from 'xEventing'; // Classes that implement different types of UI controls import * as UIControls from './UIControls.js'; var CO = CO || {}; GP.CO = CO; // added for debugging. Do not use for inter-package access export function Init() { // Make all 'class=clickable' page items create events $('.clickable').click(internalOnClickable); // Whether debug output window is initially displayed can be set in the configuration file ShowDebug(Config.page.showDebug); // Update the camera position for debugging CO.infoCameraCoord = new UIControls.UI_Coord('div[b-info=camPosition]'); if (CO.infoCameraCoord) { CO.eventCameraInfo = new Eventing.subscribe('display.cameraInfo', function(camInfo) { if (camInfo && camInfo.position && CO.infoCameraCoord) { CO.infoCameraCoord.Update(camInfo.position); } }); } // UPdate the renderer info CO.infoFPS = new UIControls.UI_Text('div[b-info=infoFPS]'); CO.infoDrawCalls = new UIControls.UI_Text('div[b-info=infoDrawCalls]'); CO.infoVertices = new UIControls.UI_Text('div[b-info=infoVertices]'); CO.infoTriangles = new UIControls.UI_Text('div[b-info=infoTriangles]'); // CO.infoPoints = new UIControls.UI_Text('div[b-info=infoPoints]'); CO.infoTextureMem = new UIControls.UI_Text('div[b-info=infoTextureMem]'); CO.infoGeometryMem = new UIControls.UI_Text('div[b-info=infoGeometryMem]'); if (CO.infoDrawCalls) { CO.eventDisplayInfo = new Eventing.subscribe('display.info', function(info) { if (info && info.render && CO.infoDrawCalls) { CO.infoFPS.Update(Math.round(info.render.fps)); CO.infoDrawCalls.Update(info.render.calls); CO.infoVertices.Update(info.render.vertices); CO.infoTriangles.Update(info.render.faces); // CO.infoPoints.Update(info.render.points); } if (info && info.memory && CO.infoTextureMem) { CO.infoTextureMem.Update(info.memory.textures); CO.infoGeometryMem.Update(info.memory.geometries); } }); } }; export function Start() { }; // Call to set debug window to specified state. Pass state that is should be in export function ShowDebug(onOff) { if (onOff) { // want it on var showMS = Config.page.DebugShowMS ? Config.page.DebugShowMS : 800; $('#DEBUGG').show(showMS); } else { var hideMS = Config.page.DebugHideMS ? Config.page.DebugHideMS : 400; $('#DEBUGG').hide(hideMS); } }; // Operation called on UI button click ('clickable'). function internalOnClickable(evnt) { var buttonOp = $(evnt.target).attr('op'); if (buttonOp == 'loadGltf') { var url = Config.assets.gltfURLBase + $('#SelectGltf').val(); GP.DebugLog('Controls: OnLoadButton: loading ' + url); internalDoLoadMultiple([ [ url, [0,0,0] ] ]); } if (buttonOp == 'loadAtropia') { GP.DebugLog('Controls: OnLoadAtropia'); let atropiaValue = Config.Atropia; if (atropiaValue) { GP.DebugLog('Getting value for regions from HTML') let parsedInput = JSON.parse(atropiaValue); // Add the url base for GLTF files (since it changes with the GLTF version) atropiaRegions = parsedInput.map(oneRegionInfo => { return [ Config.assets.gltfURLBase + oneRegionInfo[0], oneRegionInfo[1] ]; }); internalDoLoadMultiple(atropiaRegions); } } if (buttonOp == 'testComm') { GP.DebugLog('Controls: OnTestComm'); Comm.ConnectTransportService( { 'testmode': true, 'testWWURL': './wwtester.js' }) .then( () => { GP.DebugLog('Controls: test transport and service connected'); }) .catch( e => { GP.DebugLog('Controls: failed connecting test transport and service: ${e}'); }); } if (buttonOp == 'addTest') { GP.DebugLog('Controls: OnAddTestObject'); Graphics.AddTestObject(); } if (buttonOp == 'showDebug') { // Make the state to the opposite of what it is now ShowDebug(!$('#DEBUGG').is(':visible')); } if (buttonOp == 'showDebugLayer') { Graphics.SetDebugMode(); } }; function internalDoLoadMultiple(urlsAndLocations) { Graphics.ClearScene(); Graphics.LoadSceneMultiple(urlsAndLocations, function() { // DEBUG DEBUG -- initially point camera at one of the objects in the scene var aPlace; if (GP.GR.scene.children) { // ThreeJS // Walk down the tree until we find something not at <9,9< var anObject = GP.GR.scene.children[0]; while (anObject && anObject.position.x == 0 && anObject.position.y == 0) { let nextObj = anObject.children.find(xx => { return xx.type == 'Group'}); if (nextObj == undefined) { nextObj = anObject.children.find(xx => { return xx.type == 'Object3D'}); } anObject = nextObj; } if (anObject) { let pos = anObject.position; aPlace = [pos.x, pos.y, pos.z]; } } else { if (GP.GR.scene.meshes) { // for BabylonJS let ppos = GP.GR.scene.meshes[0].position; aPlace = [ ppos.x, ppos.y, ppos.z ]; } } // The position is passed as an array because not using some libary's Vector3 if (aPlace != undefined) { var cameraPlace = [aPlace[0] + 40, aPlace[1] + 40, aPlace[2] + 40]; Graphics.SetCameraPosition(cameraPlace); Graphics.PointCameraAt([aPlace[0], aPlace[1], aPlace[2]]); } // end DEBUG DEBUG Graphics.Start(); // ClearScene possibly shuts down rendering }); };
JavaScript
0
@@ -678,36 +678,8 @@ g';%0A -import * as $ from 'jquery'; %0Aimp @@ -784,16 +784,17 @@ nting';%0A +%0A // Class
04c0a8a64a1d60a720935e1798c596c90a0d3f75
add all Icons to register
web-app/src/components/SignUp/index.js
web-app/src/components/SignUp/index.js
/* global window */ import React, { Component } from 'react'; import GuestMode from '../GuestMode'; import Title from '../Title'; import { Input, Form, Button } from '../Form'; import api from '../../utils/api'; import './SignUp.css'; class SignUp extends Component { constructor(...props) { super(...props); this.state = { isValid: false, busy: false, }; } signUp(body) { this.setState({ busy: true, }); api.post('/auth/register', body) .then(({ data }) => { this.setState({ busy: false }); // TODO: make an easier jwt token manager window.localStorage.setItem('jwt.token', data.token); window.location = '/'; }) .catch(() => { this.setState({ busy: false }); }); } render() { const { isValid, busy, success } = this.state; return ( <GuestMode className="SignUp"> <Title name="Sign up" /> {!success && ( <Form onValidationChange={(valid) => this.setState({ isValid: valid })} onSubmit={(body) => this.signUp(body)} > <Input name="name" rules={['required']} placeholder="Name" className="SignUp__Input" /> <Input name="email" rules={['required', 'email']} placeholder="Email" className="SignUp__Input" /> <Input name="password" type="password" rules={['required', 'password']} placeholder="Password" className="SignUp__Input" /> <div className="SignUp__PasswordInformation"> Password must be at least 5 characters long. </div> <div className="SignUp__Button"> <Button disabled={!isValid || busy}>Sign up</Button> </div> </Form> )} </GuestMode> ); } } export default SignUp;
JavaScript
0
@@ -1190,32 +1190,46 @@ =%22SignUp__Input%22 + icon=%22person%22 /%3E%0A %3CI @@ -1313,32 +1313,45 @@ =%22SignUp__Input%22 + icon=%22email%22 /%3E%0A %3CI @@ -1468,20 +1468,33 @@ __Input%22 + icon=%22lock%22 /%3E%0A +%0A @@ -1598,16 +1598,16 @@ s long.%0A + @@ -1615,17 +1615,16 @@ %3C/div%3E%0A -%0A
86c5d65e12a494e2208dd13791d32453e32a27f3
Update homeController.js
partners/js/home/homeController.js
partners/js/home/homeController.js
(function(){ 'use strict'; angular .module('partner') .controller('HomeController', HomeController); function HomeController($scope, $rootScope, $firebaseAuth, userService, $state){ var vm = this; var ref = new Firebase($rootScope.fbUrl); vm.authObj = $firebaseAuth(ref); if($rootScope.currentUser) { console.log($rootScope.currentUser); $scope.currentUser = $rootScope.currentUser.profile; vm.title = $scope.currentUser.title; } //console.log(currentUser); } })();
JavaScript
0.000001
@@ -620,8 +620,329 @@ %0A%7D)(); +%0A%0A(function () %7B%0A var app = angular.module('myApp', %5B%5D);%0A%0A app.controller('TabController', function () %7B%0A this.tab = 1;%0A%0A this.setTab = function (tabId) %7B%0A this.tab = tabId;%0A %7D;%0A%0A this.isSet = function (tabId) %7B%0A return this.tab === tabId;%0A %7D;%0A %7D);%0A%7D)();%0A
3d17da3c1403d5e8cee9ac38e58e044f75df8893
Add missing displayName to Keyboard
src/components/Keyboard/Keyboard.js
src/components/Keyboard/Keyboard.js
import React, { PropTypes } from 'react'; import ReactDOM from 'react-dom'; import isFunction from 'lodash/lang/isFunction'; import { createPureComponent } from 'utils/createPureComponent'; export const keyCodes = Object.freeze({ 37: 'left', 38: 'up', 39: 'right', 40: 'down' }); const eventToProp = Object.freeze({ keydown: 'onKeyDown', keyup: 'onKeyUp', keypress: 'onKeyPress' }); export default createPureComponent({ propTypes: { children: PropTypes.element.isRequired, keyFilter: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), activeElementFilter: PropTypes.func, filter: PropTypes.func, onKeyDown: PropTypes.func, onKeyUp: PropTypes.func }, getDefaultProps() { const returnTrue = () => true; const noop = () => {}; return { keyFilter: returnTrue, activeElementFilter: returnTrue, filter: returnTrue, onKeyDown: noop, onKeyUp: noop }; }, toggleKeyboardBindings(turnOn) { // TODO: better to do this outside of component so // we don't get a ton of bindings. const method = `${turnOn ? 'add' : 'remove'}EventListener`; Object.keys(eventToProp).forEach((event) => { window[method](event, this.onKeyEvent); }); }, getEventKey(e) { const key = e.keyCode; return keyCodes[key] || String.fromCharCode(key); }, onKeyEvent(e) { const handler = this.props[eventToProp[e.type]]; if (this.matchesAllFilters(e)) { handler(this.getEventKey(e), e); } }, matchesKey(key) { const { keyFilter } = this.props; return ( isFunction(keyFilter) ? keyFilter(key) : key.toLowerCase() === keyFilter.toLowerCase() ); }, matchesActiveElement(target) { const { activeElement, body } = document; const { activeElementFilter } = this.props; return ( (activeElement === body) || activeElementFilter(activeElement, target) ); }, matchesFilter(key, modifiers, e) { return this.props.filter(key, modifiers, e); }, matchesAllFilters(e) { const key = this.getEventKey(e); return ( this.matchesKey(key) && this.matchesActiveElement(e.target) && this.matchesFilter(key, e) ); }, componentDidMount() { this.toggleKeyboardBindings(true); }, componentWillUnmount() { this.toggleKeyboardBindings(false); }, render() { return this.props.children; } });
JavaScript
0.000056
@@ -433,16 +433,44 @@ nent(%7B%0A%0A + displayName: 'Keyboard',%0A%0A propTy
fb30195308d6c0921ea57a852397faa7ccec4dbb
Handle null indicators on ndc country accordion selectors
app/javascript/app/components/ndcs/ndcs-country-accordion/ndcs-country-accordion-selectors.js
app/javascript/app/components/ndcs/ndcs-country-accordion/ndcs-country-accordion-selectors.js
import { createSelector } from 'reselect'; import { deburrUpper } from 'app/utils'; import uniq from 'lodash/uniq'; import sortBy from 'lodash/sortBy'; import snakeCase from 'lodash/snakeCase'; const getCountries = state => state.countries; const getAllIndicators = state => (state.data ? state.data.indicators : {}); const getCategories = state => (state.data ? state.data.categories : {}); const getSectors = state => (state.data ? state.data.sectors : {}); const getSearch = state => deburrUpper(state.search); export const parseIndicatorsDefs = createSelector( [getAllIndicators, getCategories, getCountries], (indicators, categories, countries) => { if (!indicators || !categories || !countries) return null; const parsedIndicators = {}; Object.keys(categories).forEach(category => { const categoryIndicators = indicators.filter( indicator => indicator.category_ids.indexOf(parseInt(category, 10)) > -1 ); const parsedDefinitions = categoryIndicators.map(def => { const descriptions = countries.map(country => ({ iso: country, value: def.locations[country] ? def.locations[country][0].value : null })); return { title: def.name, slug: def.slug, descriptions }; }); if (parsedDefinitions && parsedDefinitions.length) { parsedIndicators[category] = parsedDefinitions; } }); return parsedIndicators; } ); export const groupIndicatorsByCategory = createSelector( [getAllIndicators, getCategories], (indicators, categories) => { if (!indicators || !categories) return null; return Object.keys(categories) .map(cat => ({ ...categories[cat], indicators: indicators.filter( ind => ind.category_ids.indexOf(parseInt(cat, 10)) > -1 ) })) .filter(cat => cat.indicators.length); } ); export const getCategoriesWithSectors = createSelector( [groupIndicatorsByCategory], categories => { if (!categories) return null; return categories.map(cat => { const sectorIds = []; cat.indicators.forEach(ind => { Object.keys(ind.locations).forEach(location => { ind.locations[location].forEach( value => value.sector_id && sectorIds.push(value.sector_id) ); }); }); return { ...cat, sectors: sectorIds.length ? uniq(sectorIds) : null }; }); } ); export const parsedCategoriesWithSectors = createSelector( [getCategoriesWithSectors, getSectors, getCountries], (categories, sectors, countries) => { if (!categories) return null; return categories.map(cat => { const sectorsParsed = sortBy( cat.sectors && cat.sectors.length && cat.sectors.map(sec => { const definitions = []; cat.indicators.forEach(ind => { const descriptions = []; let hasValue = false; countries.forEach(loc => { const value = ind.locations[loc] ? ind.locations[loc].find(v => v.sector_id === sec) : null; if (value && value.value) { hasValue = true; descriptions.push({ iso: loc, value: value.value }); } }); if (hasValue) { definitions.push({ title: ind.name, slug: ind.slug, descriptions }); } }); const parent = sectors[sec].parent_id && sectors[sectors[sec].parent_id]; return { title: sectors[sec].name, slug: snakeCase(sectors[sec].name), parent, definitions }; }), ['parent.name', 'title'] ); return { title: cat.name, slug: cat.slug, sectors: sectorsParsed }; }); } ); export const getNDCs = createSelector( [getCategories, parseIndicatorsDefs], (categories, indicators) => { if (!categories) return null; const ndcs = Object.keys(categories).map(category => ({ title: categories[category].name, slug: categories[category].slug, definitions: indicators[category] ? indicators[category] : [] })); return ndcs; } ); export const filterNDCs = createSelector( [getNDCs, getSearch], (ndcs, search) => { if (!ndcs) return null; const filteredNDCs = ndcs.map(ndc => { const defs = ndc.definitions.filter( def => deburrUpper(def.title).indexOf(search) > -1 || deburrUpper(def.descriptions[0].value).indexOf(search) > -1 ); return { ...ndc, definitions: defs }; }); const reducedNDCs = filteredNDCs.filter(ndc => ndc.definitions.length > 0); return reducedNDCs; } ); export const filterSectoralNDCs = createSelector( [parsedCategoriesWithSectors, getSearch], (ndcs, search) => { if (!ndcs) return null; if (!search) return ndcs; const filteredNDCs = []; ndcs.forEach(ndc => { const sectors = []; ndc.sectors.forEach(sec => { const definitions = sec.definitions.filter( def => deburrUpper(def.title).indexOf(search) > -1 || deburrUpper(def.descriptions[0].value).indexOf(search) > -1 ); if (definitions.length) { sectors.push({ ...sec, definitions }); } }); if (sectors.length) { filteredNDCs.push({ ...ndc, sectors }); } }); return filteredNDCs; } ); export default { filterNDCs, filterSectoralNDCs };
JavaScript
0
@@ -4201,32 +4201,66 @@ s) return null;%0A + if (!indicators) return null;%0A const ndcs =
e43219015cf1f8dff6c785d91a2fa675a752de86
fix broken year tests
tests/test-for-current-year.js
tests/test-for-current-year.js
const test = require("ava") const fs = require("fs-extra") const globby = require("globby") const year = (new Date()).getFullYear() const yearRegex = new RegExp(`Copyright \\(c\\) ${year} GitHub Inc\\.`) test(`LICENSE files have the current year ${year}`, t => { return globby(["**/LICENSE", "!**/node_modules/**/LICENSE"]) .then(paths => { t.plan(paths.length) return paths.map(path => { const license = fs.readFileSync(path, "utf8") return t.regex(license, yearRegex, `The license "${path}" does not include the current year ${year}`) }) }) }) test(`Source header copyrights have the current year ${year}`, t => { return globby(["**/*.css", "**/*.scss", "!**/node_modules/**", "!**/build/**"]) .then(paths => { t.plan(paths.length) return paths.map(path => { const source = fs.readFileSync(path, "utf8") if (source.match(/Copyright \(c\)/)) { return t.regex(source, yearRegex, `The source's header "${path}" does not include the current year ${year}`) } else { return t.true(true) } }) }) })
JavaScript
0.000003
@@ -18,13 +18,13 @@ ire( -%22ava%22 +'ava' )%0Aco @@ -44,17 +44,17 @@ ire( -%22 +' fs-extra %22)%0Ac @@ -49,17 +49,17 @@ fs-extra -%22 +' )%0Aconst @@ -79,18 +79,93 @@ ire( -%22 +' globby -%22 +' )%0A +const %7Bjoin%7D = require('path')%0A%0Aconst %7Bpackages%7D = require('../lerna.json') %0Acon @@ -347,59 +347,32 @@ rn g -lobby(%5B%22**/LICENSE%22, %22!**/node_modules/**/LICENSE%22%5D +etPackageGlobs('LICENSE' )%0A @@ -488,38 +488,38 @@ dFileSync(path, -%22 +' utf8 -%22 +' )%0A return @@ -718,28 +718,36 @@ rn g -lobby(%5B%22**/ +etPackageGlobs('%7B *. +s css -%22, %22 +,lib/ **/* @@ -755,49 +755,10 @@ scss -%22, %22!**/node_modules/**%22, %22!**/build/**%22%5D +%7D' )%0A @@ -885,14 +885,14 @@ th, -%22 +' utf8 -%22 +' )%0A @@ -1111,28 +1111,118 @@ %7D%0A %7D)%0A %7D)%0A%7D)%0A +%0Afunction getPackageGlobs(glob) %7B%0A return globby(packages.map(pkg =%3E join(pkg, glob)))%0A%7D%0A
e0c6d5c9a99ddf8888dd4785eda5a6710c327b0c
secure cloudinary urls, fixing #1224
packages/nova-cloudinary/lib/server/cloudinary.js
packages/nova-cloudinary/lib/server/cloudinary.js
import Telescope from 'meteor/nova:lib'; import cloudinary from "cloudinary"; import Posts from "meteor/nova:posts"; import Users from 'meteor/nova:users'; const Cloudinary = cloudinary.v2; const uploadSync = Meteor.wrapAsync(Cloudinary.uploader.upload); Cloudinary.config({ cloud_name: Telescope.settings.get("cloudinaryCloudName"), api_key: Telescope.settings.get("cloudinaryAPIKey"), api_secret: Telescope.settings.get("cloudinaryAPISecret") }); const CloudinaryUtils = { // send an image URL to Cloudinary and get a cloudinary result object in return uploadImage(imageUrl) { try { var result = uploadSync(Telescope.utils.addHttp(imageUrl)); const data = { cloudinaryId: result.public_id, result: result, urls: CloudinaryUtils.getUrls(result.public_id) }; return data; } catch (error) { console.log("// Cloudinary upload failed for URL: "+imageUrl); console.log(error.stack); } }, // generate signed URL for each format based off public_id getUrls(cloudinaryId) { return Telescope.settings.get("cloudinaryFormats").map(format => { const url = Cloudinary.url(cloudinaryId, { width: format.width, height: format.height, crop: 'fill', sign_url: true, fetch_format: "auto", quality: "auto" }); return { name: format.name, url: url }; }); } }; // methods Meteor.methods({ testCloudinaryUpload: function (thumbnailUrl) { if (Users.isAdmin(Meteor.user())) { thumbnailUrl = typeof thumbnailUrl === "undefined" ? "http://www.telescopeapp.org/images/logo.png" : thumbnailUrl; const data = CloudinaryUtils.uploadImage(thumbnailUrl); console.log(data); } }, cachePostThumbnails: function (limit = 20) { if (Users.isAdmin(Meteor.user())) { var postsWithUncachedThumbnails = Posts.find({ thumbnailUrl: { $exists: true }, originalThumbnailUrl: { $exists: false } }, {sort: {createdAt: -1}, limit: limit}); postsWithUncachedThumbnails.forEach(Meteor.bindEnvironment((post, index) => { Meteor.setTimeout(function () { console.log(`// ${index}. Caching thumbnail for post “${post.title}” (_id: ${post._id})`); const data = CloudinaryUtils.uploadImage(post.thumbnailUrl); Posts.update(post._id, {$set:{ cloudinaryId: data.cloudinaryId, cloudinaryUrls: data.urls }}); }, index * 1000); })); } } }); // post submit callback function cachePostThumbnailOnSubmit (post) { if (Telescope.settings.get("cloudinaryAPIKey")) { if (post.thumbnailUrl) { const data = CloudinaryUtils.uploadImage(post.thumbnailUrl); Posts.update(post._id, {$set:{ cloudinaryId: data.cloudinaryId, cloudinaryUrls: data.urls }}); } } } Telescope.callbacks.add("posts.new.async", cachePostThumbnailOnSubmit); // post edit callback function cachePostThumbnailOnEdit (newPost, oldPost) { if (Telescope.settings.get("cloudinaryAPIKey")) { if (newPost.thumbnailUrl && newPost.thumbnailUrl !== oldPost.thumbnailUrl) { const data = CloudinaryUtils.uploadImage(newPost.thumbnailUrl); Posts.update(newPost._id, {$set:{ cloudinaryId: data.cloudinaryId, cloudinaryUrls: data.urls }}); } } } Telescope.callbacks.add("posts.edit.async", cachePostThumbnailOnEdit); export default CloudinaryUtils;
JavaScript
0
@@ -445,16 +445,33 @@ Secret%22) +,%0A secure: true, %0A%7D);%0A%0Aco
047e521a8779daae1fe6f68df8f9406f6988de94
Fix style error.
test/view/sequence/testTextBuilder.js
test/view/sequence/testTextBuilder.js
var chai = require('chai'); var assert = chai.assert; TextBuilder = require('../../../view/sequence/TextBuilder.js'); describe('Test sequence TextBuilder', function(){ it('it should build expected JSON object with Text data', function(){ let textBuilder = new TextBuilder(); var expected = { "attrs": { "text": "Kaikki ei kuitenkaan ollut niin kuin piti..", "fontFamily": "Chalkboard SE", "fontSize": 26, "fill": "white", "shadowColor": "#bbbbbb", "shadowBlur": 10, "width": 981, "align": "center", "y": 321 }, "className": "Text" }; var text = { "text": { "text": "Kaikki ei kuitenkaan ollut niin kuin piti.." } }; var result = textBuilder.build(text); assert.deepEqual(expected, result); }); });
JavaScript
0
@@ -308,32 +308,8 @@ ed = - %7B%0A
29bdb0a226c76279193033bf2d0e777381d2a870
Fix circleci test config file
tests/test.config.circle-ci.js
tests/test.config.circle-ci.js
module.exports = { store_url: 'http://localhost:8080', account_user: 'test', account_password: 'testing', account_name: 'tester', container_name: 'test_container', object_name: 'test_object', segment_container_name: 'segment_test_container', segment_object_name: 'segment_test_object', dlo_container_name: 'dlo_test_container', dlo_object_name: 'dlo_test_object', dlo_prefix: 'dlo_prefix', slo_container_name: 'slo_test_container', slo_object_name: 'slo_test_object' };
JavaScript
0.000001
@@ -75,16 +75,23 @@ r: 'test +:tester ',%0A a @@ -137,22 +137,25 @@ _name: ' +AUTH_ test -er ',%0A c
b4f95c85fb96ed26fb8ed3ab577427238f231f5f
Fix test
test/xd-mvc-examples/xdGalleryTest.js
test/xd-mvc-examples/xdGalleryTest.js
"use strict"; /** * @type {Chai.Assert} */ var assert = require('chai').assert var xdTesting = require('../../lib/index') var templates = xdTesting.templates /** * @type {Q} */ var q = require('q') describe('XD-MVC Gallery @large', function () { var test = this // Set test timeout test.timeout(180 * 1000) test.async_timeout = xdTesting.waitForTimeout = 30 * 1000 test.baseUrl = "http://localhost:8082/gallery.html" test.adapter = require('../../lib/adapter/xdmvc') describe('eventLogger', () => { it('should count XDconnection events', () => { let options = {A: templates.devices.chrome(), B: templates.devices.chrome()} let loadedUrlA return xdTesting.multiremote(options).init() .url(test.baseUrl) .execute(test.adapter.injectEventLogger) .execute(test.adapter.getEventCounter) .then(function (retA) { console.log(retA.value) assert.equal(retA.value.XDconnection, 0) }) // Share url from A to B .then(() => console.log('share url from A to B')) .getUrl().then(urlA => loadedUrlA = urlA) .selectById('B', B => B .url(loadedUrlA) .execute(test.adapter.injectEventLogger) ) .then(() => console.log('shared url')) // Assert connection event // TODO wait until B is initialized .execute(test.adapter.getEventCounter) .then(function (retA) { console.log(retA.value) assert.equal(retA.value.XDconnection, 1) }) .end() }) }) it('should pair two devices via url', () => { let options = {A: templates.devices.chrome(), B: templates.devices.chrome()} let deviceCount let devices = xdTesting.multiremote(options).init() devices = test.adapter.pairDevicesViaURL(devices, test.baseUrl) return devices .then(() => console.log('paired')) .getCount().then(count => deviceCount = count) .selectById('A', device => device .then(() => console.log('get event counter..')) .execute(test.adapter.getEventCounter) .then(ret => { console.log('got event counter', ret.value) assert.equal(ret.value.XDconnection, deviceCount - 1) }) ) .end() }); describe('prerequisites', () => { it('browsers should not share cookies between sessions', () => { let options = {A: templates.devices.chrome(), B: templates.devices.chrome()} let devices = xdTesting.multiremote(options).init() devices = test.adapter.pairDevicesViaURL(devices, test.baseUrl) return devices .selectById('A', deviceA => deviceA // Set cookie and verify it's there .setCookie({name: 'test_cookieA', value: 'A'}) .getCookie('test_cookieA') .then(cookie => { assert.notEqual(cookie, null) assert.equal(cookie.name, 'test_cookieA') assert.equal(cookie.value, 'A') }) ) .selectById('B', deviceB => deviceB // Set another cookie and verify it's there .setCookie({name: 'test_cookieB', value: 'B'}) .getCookie('test_cookieB').then(cookie => { assert.notEqual(cookie, null) assert.equal(cookie.name, 'test_cookieB') assert.equal(cookie.value, 'B') }) // Verify the cookie from the other browser is not here .getCookie('test_cookieA') .then(cookie => { assert.equal(cookie, null) }) ) .end() }) it('browsers should not share local storage between sessions', () => { let options = {A: templates.devices.chrome(), B: templates.devices.chrome()} let devices = xdTesting.multiremote(options).init() devices = test.adapter.pairDevicesViaURL(devices, test.baseUrl) return devices .selectById('A', deviceA => deviceA // Set local storage item and verify it's there .execute(() => localStorage.setItem('test_storageA', 'A')) .execute(() => localStorage.getItem('test_storageA')).then(ret => assert.equal(ret.value, 'A')) ) .selectById('B', deviceB => deviceB // Verify the item from the other browser is not here .execute(() => localStorage.getItem('test_storageA')).then(ret =>assert.equal(ret.value, null)) ) .end() }) }) describe('should show the selected image on the other devices', () => { xdTesting.loadSetups().forEach(setup => { // Assemble setup name let setupName = Object.keys(setup.devices).map(key => setup.devices[key].name).join(', ') it('on ' + setupName, function () { let imageUrlA let urlA let allButA let devices = xdTesting.multiremote(options).init() devices = test.adapter.pairDevicesViaURL(devices, test.baseUrl) return devices .name(setupName) .checkpoint('load app') .selectById('A', deviceA => deviceA .waitForVisible('h2.gallery-overview', test.async_timeout) .click('//*[text()="Bike Tours"]') .waitForVisible('#gallery img:nth-of-type(1)', test.async_timeout) .checkpoint('select album') .click('#gallery img:nth-of-type(1)') .waitForVisible('#image img', test.async_timeout) .scroll('#image img') .checkpoint('click thumbnail') .getAttribute('#image img', 'src').then(src => { imageUrlA = src; }) .getUrl().then(function (url) { urlA = url }) ) .getDeviceIds().then(ret => { let deviceIds = ret.value allButA = deviceIds.filter(deviceId => deviceId != 'A') }) .selectById(() => allButA, otherDevices => otherDevices .waitForVisible('#image img', test.async_timeout) .checkpoint('click thumbnail') .getAttribute('#image img', 'src') ) .then(function () { let srcs = arguments Object.keys(srcs).forEach(key => { var src = srcs[key] assert.equal(src, imageUrlA) }) }) .checkpoint('end') .end() }) }) }) })
JavaScript
0.000004
@@ -5330,16 +5330,56 @@ up name%0A + let options = setup.devices%0A @@ -5410,28 +5410,22 @@ ct.keys( -setup.device +option s).map(k @@ -5430,28 +5430,22 @@ (key =%3E -setup.device +option s%5Bkey%5D.n
05f47c950053b79341e0ede6c5a85ff6f3fbde43
check podcasts before render
src/components/person-page/index.js
src/components/person-page/index.js
import React from 'react' import st from './style.module.css' import Link, {navigateTo} from 'gatsby-link' import BackButton from '../back-button' import TelegramIcon from '-!svg-react-loader?name=Icon!../../../static/telegram.svg' import VkIcon from '-!svg-react-loader?name=Icon!../../../static/vk.svg' import SlackIcon from '-!svg-react-loader?name=Icon!../../../static/slack.svg' import TwitterIcon from '-!svg-react-loader?name=Icon!../../../static/twitter.svg' const SocialIcon = ({user, link, children}) => { const icon = user ? ( <span className={st.social_icon}> <a target='_blank' href={link}> {children} </a> </span> ) : null return icon } export default ({ history, pathContext: { data: { name, lastname, position, vk, telegram, twitter, slack, company, podcasts, photo, }, }, }) => { return ( <div> <div className={st.back_link}> <BackButton history={history} /> </div> <div className={st.person}> <div className={st.person_info}> <h2> {name} {lastname} </h2> <div className={st.company}>{company}</div> <div className={st.social}> <SocialIcon link={`https://vk.com/${vk}`} user={vk}> <VkIcon /> </SocialIcon> <SocialIcon link={`https://t.me/${telegram}`} user={telegram}> <TelegramIcon /> </SocialIcon> <SocialIcon link={twitter} user={twitter}> <TwitterIcon /> </SocialIcon> {slack ? ( <span className={st.slack_icon}> <SlackIcon /> <span className={st.slack_name}>{slack}</span> </span> ) : null} </div> </div> <div className={st.person_image}> {photo ? ( <img src={`https:${photo.file.url}?fit=thumb&h=200&w=200`} /> ) : ( <img src='/Person-placeholder.jpg' /> )} </div> </div> <div> <h4>Подкасты:</h4> {podcasts.map(({title, number}, index) => { return ( <div className={st.podcast_item} key={index}> <Link to={`/podcast/${number}`}> {title} </Link> </div> ) })} </div> </div> ) }
JavaScript
0
@@ -2222,16 +2222,28 @@ podcasts + && podcasts .map((%7Bt
94558f5dcf5ce15b7b1964dd36e1a7fa26c730fd
Add fs & path as external
packages/purgecss-webpack-plugin/rollup.config.js
packages/purgecss-webpack-plugin/rollup.config.js
import babel from 'rollup-plugin-babel' import commonjs from 'rollup-plugin-commonjs' import resolve from 'rollup-plugin-node-resolve' export default { entry: './src/index.js', targets: [ { dest: './lib/purgecss-webpack-plugin.es.js', format: 'es' }, { dest: './lib/purgecss-webpack-plugin.js', format: 'cjs' } ], plugins: [resolve(), commonjs(), babel()], external: ['purgecss', 'webpack-sources'] }
JavaScript
0
@@ -491,12 +491,26 @@ sources' +, 'fs', 'path' %5D%0A%7D%0A
f84b483b331b41bef91da01bef7ebd0e22e6b148
Remove an unnecessary call to a scroll top on load
src/containers/ViewportContainer.js
src/containers/ViewportContainer.js
import React, { Component, PropTypes } from 'react' import shallowCompare from 'react-addons-shallow-compare' import { connect } from 'react-redux' import { scrollToTop, scrollToOffsetTop } from '../vendor/scrollTop' import { setNavbarState, setViewportSizeAttributes } from '../actions/gui' import { addScrollObject, removeScrollObject } from '../components/viewport/ScrollComponent' import { addResizeObject, removeResizeObject } from '../components/viewport/ResizeComponent' import { Viewport } from '../components/viewport/Viewport' class ViewportContainer extends Component { static propTypes = { dispatch: PropTypes.func.isRequired, innerHeight: PropTypes.number, innerWidth: PropTypes.number, isNavbarFixed: PropTypes.bool, isNavbarHidden: PropTypes.bool, isNavbarSkippingTransition: PropTypes.bool, isNotificationsActive: PropTypes.bool, isOffsetLayout: PropTypes.bool, isProfileMenuActive: PropTypes.bool, offset: PropTypes.number, pathname: PropTypes.string.isRequired, } componentWillMount() { this.scrollYAtDirectionChange = null } componentDidMount() { const { isOffsetLayout } = this.props addResizeObject(this) addScrollObject(this) return isOffsetLayout ? scrollToOffsetTop() : scrollToTop() } shouldComponentUpdate(nextProps, nextState) { return shallowCompare(this, nextProps, nextState) } componentWillUnmount() { removeResizeObject(this) removeScrollObject(this) } onResize(resizeAttributes) { const { innerHeight: prevHeight, innerWidth: prevWidth } = this.props const { innerHeight: nextHeight, innerWidth: nextWidth } = resizeAttributes if (prevHeight !== nextHeight || prevWidth !== nextWidth) { this.props.dispatch(setViewportSizeAttributes(resizeAttributes)) } } onScrollTop() { const { dispatch, isNavbarFixed } = this.props if (isNavbarFixed) { dispatch(setNavbarState({ isFixed: false, isHidden: false, isSkippingTransition: false, })) } } onScrollDirectionChange(scrollProperties) { const { scrollY } = scrollProperties if (scrollY >= this.props.offset) { this.scrollYAtDirectionChange = scrollY } } onScroll(scrollProperties) { const { scrollY, scrollDirection } = scrollProperties const { dispatch, isNavbarFixed, isNavbarHidden, isNavbarSkippingTransition } = this.props let nextIsFixed = isNavbarFixed let nextIsHidden = isNavbarHidden let nextIsSkippingTransition = isNavbarSkippingTransition // Going from absolute to fixed positioning if (scrollY >= this.props.offset && !isNavbarFixed) { nextIsFixed = true nextIsHidden = true nextIsSkippingTransition = true } // Scroll just changed directions so it's about to either be shown or hidden if (scrollY >= this.props.offset && this.scrollYAtDirectionChange) { const distance = Math.abs(scrollY - this.scrollYAtDirectionChange) const delay = scrollDirection === 'down' ? 20 : 80 const isScrollingDown = scrollDirection === 'down' if (distance >= delay) { nextIsHidden = isScrollingDown nextIsSkippingTransition = false this.scrollYAtDirectionChange = null } } if (isNavbarFixed !== nextIsFixed || isNavbarHidden !== nextIsHidden || isNavbarSkippingTransition !== nextIsSkippingTransition) { dispatch(setNavbarState({ isFixed: nextIsFixed, isHidden: nextIsHidden, isSkippingTransition: nextIsSkippingTransition, })) } } render() { return <Viewport { ...this.props } /> } } const mapStateToProps = (state) => { const { gui, modal, routing } = state return { innerHeight: gui.innerHeight, innerWidth: gui.innerWidth, isNavbarFixed: gui.isNavbarFixed, isNavbarHidden: gui.isNavbarHidden, isNavbarSkippingTransition: gui.isNavbarSkippingTransition, isNotificationsActive: modal.isNotificationsActive, isOffsetLayout: gui.isOffsetLayout, isProfileMenuActive: gui.isProfileMenuActive, offset: gui.coverOffset ? gui.coverOffset - 80 : 160, pathname: routing.location.pathname, } } export default connect(mapStateToProps)(ViewportContainer)
JavaScript
0
@@ -145,77 +145,8 @@ ux'%0A -import %7B scrollToTop, scrollToOffsetTop %7D from '../vendor/scrollTop'%0A impo @@ -1055,50 +1055,8 @@ ) %7B%0A - const %7B isOffsetLayout %7D = this.props%0A @@ -1107,72 +1107,8 @@ is)%0A - return isOffsetLayout ? scrollToOffsetTop() : scrollToTop()%0A %7D%0A
2343d77cd75492c4b1bda09b4c87d406a8e3a87d
Send authorization tokens in `fetch`
frontend/app/routes/visualize/graph.js
frontend/app/routes/visualize/graph.js
import { inject as service } from '@ember/service'; import fetch from 'fetch'; import Route from '@ember/routing/route'; import ResetScrollPositionMixin from 'frontend/mixins/reset-scroll-position'; export default Route.extend(ResetScrollPositionMixin, { intl: service(), session: service(), queryParams: { specificToUser: { refreshModel: true } }, model(params) { const host = this.store.adapterFor('summarized-statistic').get('host'); let url = new URL(`${host}/chart_data/similarities.json`); if (params.specificToUser){ url.searchParams.append('specific_to_user', params.specificToUser); } return fetch(url).then(function(response) { return response.json(); }); }, actions: { toggleSpecificToUser(currentValue){ const switchedValue = currentValue != "true"; this.transitionTo({ queryParams: { specific_to_user: switchedValue }}); } } } );
JavaScript
0
@@ -553,12 +553,75 @@ -if ( +let headers = %7B%7D;%0A if (this.get('session.isAuthenticated') && para @@ -716,16 +716,111 @@ oUser);%0A + headers%5B'Authorization'%5D = %60Bearer $%7Bthis.get('session.data.authenticated.idToken')%7D%60;%0A %7D%0A @@ -842,16 +842,36 @@ etch(url +, %7Bheaders: headers%7D ).then(f
8ef3e7cde825f4fe661ddd16e40aee32653046d2
Use waitUntilVisible in editing tests.
frontend_tests/casper_tests/08-edit.js
frontend_tests/casper_tests/08-edit.js
var common = require('../casper_lib/common.js').common; common.start_and_log_in(); function then_edit_last_message() { casper.then(function () { casper.evaluate(function () { var msg = $('#zhome .message_row:last'); msg.find('.info').click(); $('.popover_edit_message').click(); }); }); casper.waitForSelector(".message_edit_content"); } // Send and edit a stream message common.then_send_message('stream', { stream: 'Verona', subject: 'edits', content: 'test editing', }); casper.waitForText("test editing"); common.wait_for_message_actually_sent(); then_edit_last_message(); casper.then(function () { casper.evaluate(function () { var msg = $('#zhome .message_row:last'); msg.find('.message_edit_topic').val("edited"); msg.find('.message_edit_content').val("test edited"); msg.find('.message_edit_save').click(); }); }); casper.waitWhileVisible("textarea.message_edit_content", function () { casper.test.assertSelectorHasText(".last_message .message_content", "test edited"); }); common.then_send_message('stream', { stream: 'Verona', subject: 'edits', content: '/me test editing one line with me', }); casper.waitForText("test editing one line with me"); common.wait_for_message_actually_sent(); then_edit_last_message(); casper.then(function () { casper.evaluate(function () { var msg = $('#zhome .message_row:last'); msg.find('.message_edit_topic').val("edited"); msg.find('.message_edit_content').val("/me test edited one line with me"); msg.find('.message_edit_save').click(); }); }); casper.waitWhileVisible("textarea.message_edit_content", function () { casper.test.assertSelectorHasText(".last_message .sender-status", "test edited one line with me"); }); common.then_send_message('private', { recipient: "cordelia@zulip.com", content: "test editing pm", }); casper.waitForText("test editing pm"); common.wait_for_message_actually_sent(); then_edit_last_message(); casper.then(function () { casper.evaluate(function () { var msg = $('#zhome .message_row:last'); msg.find('.message_edit_content').val("test edited pm"); msg.find('.message_edit_save').click(); }); }); casper.waitWhileVisible("textarea.message_edit_content", function () { casper.test.assertSelectorHasText(".last_message .message_content", "test edited pm"); }); casper.run(function () { casper.test.done(); });
JavaScript
0
@@ -357,23 +357,58 @@ per. -waitForSelector +then(function () %7B%0A casper.waitUntilVisible (%22.m @@ -430,16 +430,24 @@ tent%22);%0A + %7D);%0A %7D%0A%0A// Se
5506aa130a6880e2910f4318a85bee7e7c083a28
add meta to System.config
packages/app-decorators/jspm.config.js
packages/app-decorators/jspm.config.js
System.config({ "transpiler": false, "packageConfigPaths": [ "npm:@*/*.json", "npm:*.json", "github:*/*.json" ], "paths": { "github": "jspm_packages/github/", "npm:": "jspm_packages/npm/", "src/": "lib/", "test/": "test/", "app-decorators/": "node_modules/app-decorators/" }, "map": { "app-decorators": "app-decorators/src/index", "app-decorators/bootstrap": "app-decorators/src/bootstrap", "app-decorators-helper/register-customelement": "app-decorators/src/libs/customelement", "app-decorators-helper/random-storage": "app-decorators/src/libs/random-storage" }, "packages": { "src": { "defaultExtension": "js" }, "test": { "defaultExtension": "js" }, "node_modules": { "defaultExtension": "js" } } });
JavaScript
0.000001
@@ -677,24 +677,110 @@ age%22%0A %7D,%0A + %22meta%22: %7B%0A %22app-decorators%22: %7B%0A %22build%22: false%0A %7D%0A %7D,%0A %22package
43d9083e78c1b32bc6079565172c1af7e2de5687
change settings styles
assets/js/MainPageSliderFunctionality.js
assets/js/MainPageSliderFunctionality.js
var sliderPages = document.getElementById('circles').getElementsByTagName('div'), sliderPreviousButton = document.getElementById('previous'), sliderNextButton = document.getElementById('next'), currentIndex = 0, i, len; sliderPages[0].addEventListener('click', function (event) { changeSliderImage(event.target, 0); }); sliderPages[1].addEventListener('click', function (event) { changeSliderImage(event.target, 1); }); sliderPages[2].addEventListener('click', function (event) { changeSliderImage(event.target, 2); }); sliderPreviousButton.addEventListener('click',function(event){ if(currentIndex>=0){ currentIndex-=1; changeSliderImage(sliderPages[currentIndex],currentIndex); } if(currentIndex===-1){ currentIndex=2; changeSliderImage(sliderPages[currentIndex],currentIndex); } }); sliderNextButton.addEventListener('click',function(event){ if(currentIndex<=2){ currentIndex+=1; changeSliderImage(sliderPages[currentIndex],currentIndex); } if(currentIndex===3){ currentIndex=0; changeSliderImage(sliderPages[currentIndex],currentIndex); } }); function changeSliderImage(target, index) { var j, length; for (j = 0, length = sliderPages.length; j < length; j += 1) { if (sliderPages[j] === target) { target.style.backgroundColor = 'white'; } else { sliderPages[j].style.backgroundColor = '#908986'; } } document.getElementById('slider').style.backgroundImage = 'url(assets/img/slider-image-' + index + '.png)'; document.getElementById('url-to-go').addEventListener('click',function(event){ window.location.href+='products/cat/' + (index+1); }) } window.onload = function () { changeSliderImage(document.getElementById(currentIndex + '-image'), currentIndex); };
JavaScript
0.000001
@@ -1510,24 +1510,208 @@ %0A %7D%0A%0A +$('#slider').fadeOut(200, function () %7B%0A $('#slider').css(%22background-image%22, 'url(assets/img/slider-image-' + index + '.png)');%0A $('#slider').fadeIn(200);%0A %7D);%0A // document.get
931697e45c3e56814518d6b68d1a41a8df2f9352
fix indent
tests/dummy/app/routes/application.js
tests/dummy/app/routes/application.js
import Route from '@ember/routing/route'; export default Route.extend({ async beforeModel() { try { await this.get('state').restore(); } catch(err) { if(err.reason === 'needs_setup') { this.transitionTo('setup'); } else { throw err; } } } });
JavaScript
0.00006
@@ -106,16 +106,17 @@ %7B%0A + await th