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
edb8df5e5897f567b57f38a9533c31ea6e347bd9
correct the url for production, will need fixed for dev
app/modules/screen-sharing/controllers/AuthenticationCtrl.js
app/modules/screen-sharing/controllers/AuthenticationCtrl.js
App.controllers.authenticationCtrl = (function ($, App) { 'use strict'; // The Authentication Controller return function (options) { var $el; var chromeUrl = 'https://chrome.google.com/webstore/detail/jlpojfookfonjolaeofpibngfpnnflne'; // A callback when the name is submitted function submitName (e) { // Prevent the form from posting back e.preventDefault(); // Get the username from the form var username = $el.find('.cbl-name__text').val(); // Disable the form $(e.target).find('input').attr('disabled', 'disabled'); // Connect the client App.models.client(username, options.onConnection); // hide the the description text var desc = $('.app-description'); desc.css('display','none'); desc = null; } function clickInstallExtension(e) { e.preventDefault(); if (respoke.needsChromeExtension && !respoke.hasChromeExtension) { console.log('attempting to install chrome extension'); chrome.webstore.install(chromeUrl, function(){ console.log('Successfully installed Chrome Extension, reloading page'); window.location.reload(); }, function(err){ console.error('Error installing extension in chrome', err); console.error('Chrome webstore URL is', chromeUrl); }); } if(respoke.needsFirefoxExtension && !respoke.hasFirefoxExtension) { console.log('attempting to install firefox extension'); InstallTrigger.install({ Foo: { URL: '/web-examples-respoke.xpi', Hash: 'sha1:b4bca99f68ab8d821caf59f1f735e622b6fec9ae', toString: function () { return this.URL; } } }); } } // Renders the authentication form function renderForm () { $el = $.helpers.insertTemplate({ template: 'user-authentication', renderTo: $el, type: 'html', bind: { '.cbl-name': { 'submit': submitName }, '#installExtension': { 'click': clickInstallExtension }, } }); function removeInstructions(){ if (respoke.hasScreenShare()) { $el.find('.screen-share-instructions').remove(); } } respoke.listen('extension-loaded', removeInstructions); removeInstructions(); } // Initializes the controller (function () { $el = $(options.renderTo); renderForm(); }()); // Exposes a public API return {}; }; }(jQuery, App));
JavaScript
0.000001
@@ -1814,16 +1814,29 @@ examples +/web-examples -respoke
d540fbf7e1bd4ac5b04801e40cd6a18d483fdae8
Use hooks, simplify PauseButton
app/js/PauseButton.js
app/js/PauseButton.js
/* @flow */ import React from 'react'; const TW = chrome.extension.getBackgroundPage().TW; // Unpack TW. const { settings } = TW; type State = { paused: boolean, }; export default class PauseButton extends React.PureComponent<{}, State> { constructor() { super(); this.state = { paused: settings.get('paused'), }; } pause = () => { chrome.browserAction.setIcon({ path: 'img/icon-paused.png' }); settings.set('paused', true); this.setState({ paused: true }); }; play = () => { chrome.browserAction.setIcon({ path: 'img/icon.png' }); settings.set('paused', false); this.setState({ paused: false }); }; render() { const content = this.state.paused ? ( <span> <i className="fas fa-play" /> {chrome.i18n.getMessage('extension_resume')} </span> ) : ( <span> <i className="fas fa-pause" /> {chrome.i18n.getMessage('extension_pause')} </span> ); return ( <button className="btn btn-outline-dark btn-sm" onClick={this.state.paused ? this.play : this.pause}> {content} </button> ); } }
JavaScript
0.000017
@@ -38,16 +38,40 @@ ';%0A%0A -const TW +// Unpack TW.%0Aconst %7B settings %7D = c @@ -115,275 +115,192 @@ W;%0A%0A -// Unpack TW.%0Aconst %7B settings %7D = TW;%0A%0Atype State = %7B%0A paused: boolean,%0A%7D;%0A%0Aexport default class PauseButton extends React.PureComponent%3C%7B%7D, State%3E %7B%0A constructor() %7B%0A super();%0A this.state = %7B%0A paused: settings.get('paused'),%0A %7D;%0A %7D%0A%0A pause = () =%3E +export default function PauseButton() %7B%0A // $FlowFixMe Upgrade Flow to get latest React types%0A const %5Bpaused, setPaused%5D = React.useState(settings.get('paused'));%0A%0A function pause() %7B%0A @@ -407,61 +407,47 @@ -this.setState(%7B p +setP aused -: +( true - %7D );%0A %7D -; %0A%0A -play = () =%3E +function play() %7B%0A @@ -548,92 +548,148 @@ -this.setState(%7B p +setP aused -: +( false - %7D );%0A %7D -; %0A%0A re -nder() %7B%0A const content = this.state. +turn (%0A %3Cbutton className=%22btn btn-outline-dark btn-sm%22 onClick=%7Bpaused ? play : pause%7D type=%22button%22%3E%0A %7B paus @@ -693,39 +693,39 @@ aused ? (%0A -%3Cspan%3E%0A + %3C%3E%0A %3Ci class @@ -793,32 +793,32 @@ me')%7D%0A -%3C/span%3E%0A + %3C/%3E%0A ) : (%0A @@ -825,15 +825,15 @@ -%3Cspan%3E%0A + %3C%3E%0A @@ -921,181 +921,23 @@ -%3C/span%3E%0A );%0A%0A return (%0A %3Cbutton%0A className=%22btn btn-outline-dark btn-sm%22%0A onClick=%7Bthis.state.paused ? this.play : this.pause%7D%3E%0A %7Bcontent%7D%0A + %3C/%3E%0A )%7D%0A @@ -952,15 +952,9 @@ %3E%0A - );%0A %7D +); %0A%7D%0A
ae360486d866539ac26f4036d1e8b2f33719fd52
change order of counter columns
frontend/src/containers/jobs.js
frontend/src/containers/jobs.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { NomadLink } from '../components/link' class Jobs extends Component { counterColumns() { return ['Queued', 'Complete', 'Failed', 'Running', 'Starting', 'Lost']; } getJobStatisticsHeader() { let output = []; this.counterColumns().forEach((key) => { output.push(<th key={'statistics-header-for-' + key} className="center">{key}</th>) }); return output } getJobStatisticsRow(job) { let counter = { Queued: 0, Complete: 0, Failed: 0, Running: 0, Starting: 0, Lost: 0 } let summary = job.JobSummary.Summary; Object.keys(summary).forEach(function(taskGroupID) { counter.Queued += summary[taskGroupID].Queued; counter.Complete += summary[taskGroupID].Complete; counter.Failed += summary[taskGroupID].Failed; counter.Running += summary[taskGroupID].Running; counter.Starting += summary[taskGroupID].Starting; counter.Lost += summary[taskGroupID].Lost; }); let output = []; this.counterColumns().forEach((key) => { output.push(<td key={job.ID + '-' + key}>{counter[key]}</td>) }); return output } render() { return ( <div className="row"> <div className="col-md-12"> <div className="card"> <div className="header"> <h4 className="title">Jobs</h4> </div> <div className="content table-responsive table-full-width"> <table className="table table-hover table-striped"> <thead> <tr> <th>ID</th> <th>Status</th> <th>Type</th> <th>Priority</th> <th>Task Groups</th> {this.getJobStatisticsHeader()} </tr> </thead> <tbody> {this.props.jobs.map((job) => { return ( <tr key={job.ID}> <td><NomadLink jobId={job.ID} short="true"/></td> <td>{job.Status}</td> <td>{job.Type}</td> <td>{job.Priority}</td> <td>{Object.keys(job.JobSummary.Summary).length}</td> {this.getJobStatisticsRow(job)} </tr> ) })} </tbody> </table> </div> </div> </div> </div> ); } } function mapStateToProps({ jobs }) { return { jobs } } export default connect(mapStateToProps)(Jobs)
JavaScript
0.000002
@@ -193,16 +193,39 @@ return %5B +'Starting', 'Running', 'Queued' @@ -251,31 +251,8 @@ ed', - 'Running', 'Starting', 'Lo
a8d31a629389091299c7348d73477b5a34d4dfa2
fix fs records
src/scrapers/familysearch-record.js
src/scrapers/familysearch-record.js
var debug = require('debug')('genscrape:scrapers:familysearch-record'), utils = require('../utils'), GedcomX = require('gedcomx-js'); var urls = [ utils.urlPatternToRegex("https://familysearch.org/pal:/MM9.1.1/*"), utils.urlPatternToRegex("https://familysearch.org/ark:/61903/1:1:*") ]; module.exports = function(register){ register(urls, run); }; function run(emitter){ debug('running'); utils.getJSON(window.location.href, function(error, json){ if(error){ debug('error'); emitter.emit('error', error); } else { debug('data'); emitter.emit('data', GedcomX(json)); } }); }
JavaScript
0.000006
@@ -438,16 +438,53 @@ on.href, + %7BAccept:'application/x-fs-v1+json'%7D, functio
deae7aa2895bce928c25c4e0d0f8155213fc5320
Update controllers.js
app/js/controllers.js
app/js/controllers.js
'use strict'; var carApp = angular.module('carApp', ['ngRoute']); carApp.config(['$routeProvider', function($routeProvider){ $routeProvider .when('/buy',{ templateUrl: 'template/buy.html', controller: 'BuyController' }) .when('/',{ templateUrl: 'template/home.html', controller: 'HomeController' }) .when('/sell',{ templateUrl: 'template/sell.html', controller: 'SellController' }) .otherwise({ redirectTo: '/' }); }]); carApp.controller('carAppController', ['$scope', '$http', '$location', function($scope, $http, $location) { }]); carApp.controller('HomeController', ['$scope', '$http', '$location', function($scope, $http, $location) { }]); carApp.controller('BuyController', ['$scope', '$http', '$location', function($scope, $http, $location) { $http.get('cars/cars.json').success(function(data, status , headers, config) { $scope.cars = data; }); }]); carApp.controller('SellController', ['$scope', '$http', '$location', function($scope, $http, $location) { }]); carApp.controller('SController', ['$scope', '$http', '$location', function($scope, $http, $location) { $scope.car = car; }]); carApp.controller('ShowAdController', ['$scope', '$http', '$location', function($scope, $http, $location) { $http.get('/car/car.json').success(function(data, status , headers, config) { $scope.cars = data; }); }]); carApp.controller('Ctrl', ['$scope', '$http', '$location', function($scope, $http, $location) { $scope.list = { car: "", id: "", imageUrl: "", model: "", snippet: "", price: "", mileage: "", fuel: "", transmission: "", engine: "", phone: "", year:"" }; $scope.submit = function() { this.list.name = this.name; this.list.car = this.car; this.list.id = this.id; this.list.imageUrl = this.imageUrl; this.list.model = this.model; this.list.snippet = this.snippet; this.list.price = this.price; this.list.mileage = this.mileage; this.list.fuel = this.fuel; this.list.transmission = this.transmission; this.list.engine = this.engine; this.list.phone = this.phone; this.list.year = this.year; $http.get('cars/cars.json').success(function(data, status , headers, config) { $scope.cars = data; $scope.cars.push($scope.list); console.log($scope.cars); $http.post('cars/cars.json').success(function(data, status , headers, config) { $scope.cars = data; console.log(1); }); }); $http.post('cars/cars.json').success(function(data, status , headers, config) { $scope.cars = data; console.log(1); }); }; }]);
JavaScript
0.000001
@@ -822,32 +822,35 @@ %7B%0D%0A%09%09$http.get(' +../ cars/cars.json')
a9ad69bfa4ea4c4e803f2386ea0c36b7d71483f1
Include path.sep in escapeRegExp argument.
frontend_tests/zjsunit/index.js
frontend_tests/zjsunit/index.js
"use strict"; const fs = require("fs"); const Module = require("module"); const path = require("path"); const Handlebars = require("handlebars/runtime"); const _ = require("lodash"); const handlebars = require("./handlebars"); const stub_i18n = require("./i18n"); const namespace = require("./namespace"); const stub = require("./stub"); const {make_zblueslip} = require("./zblueslip"); const zjquery = require("./zjquery"); require("@babel/register")({ extensions: [".es6", ".es", ".jsx", ".js", ".mjs", ".ts"], only: [ new RegExp("^" + _.escapeRegExp(path.resolve(__dirname, "../../static/js")) + path.sep), new RegExp( "^" + _.escapeRegExp(path.resolve(__dirname, "../../static/shared/js")) + path.sep, ), ], plugins: ["rewire-ts"], }); global.assert = require("assert").strict; // Create a helper function to avoid sneaky delays in tests. function immediate(f) { return () => f(); } // Find the files we need to run. const files = process.argv.slice(2); if (files.length === 0) { throw new Error("No tests found"); } // Set up our namespace helpers. global.with_field = namespace.with_field; global.set_global = namespace.set_global; global.patch_builtin = namespace.set_global; global.zrequire = namespace.zrequire; global.reset_module = namespace.reset_module; global.stub_out_jquery = namespace.stub_out_jquery; global.with_overrides = namespace.with_overrides; global.window = new Proxy(global, { set: (obj, prop, value) => { namespace.set_global(prop, value); return true; }, }); global.to_$ = () => window; // Set up stub helpers. global.make_stub = stub.make_stub; global.with_stub = stub.with_stub; // Set up fake jQuery global.make_zjquery = zjquery.make_zjquery; // Set up Handlebars global.stub_templates = handlebars.stub_templates; const noop = function () {}; // Set up fake module.hot Module.prototype.hot = { accept: noop, }; // Set up fixtures. global.read_fixture_data = (fn) => { const full_fn = path.join(__dirname, "../../zerver/tests/fixtures/", fn); const data = JSON.parse(fs.readFileSync(full_fn, "utf8", "r")); return data; }; function short_tb(tb) { const lines = tb.split("\n"); const i = lines.findIndex( (line) => line.includes("run_test") || line.includes("run_one_module"), ); if (i === -1) { return tb; } return lines.splice(0, i + 1).join("\n") + "\n(...)\n"; } // Set up Markdown comparison helper global.markdown_assert = require("./markdown_assert"); let current_file_name; function run_one_module(file) { console.info("running test " + path.basename(file, ".js")); current_file_name = file; require(file); } global.run_test = (label, f) => { if (files.length === 1) { console.info(" test: " + label); } try { global.with_overrides(f); } catch (error) { console.info("-".repeat(50)); console.info(`test failed: ${current_file_name} > ${label}`); console.info(); throw error; } // defensively reset blueslip after each test. blueslip.reset(); }; try { files.forEach((file) => { set_global("location", { hash: "#", }); global.patch_builtin("setTimeout", noop); global.patch_builtin("setInterval", noop); _.throttle = immediate; _.debounce = immediate; set_global("blueslip", make_zblueslip()); set_global("i18n", stub_i18n); namespace.clear_zulip_refs(); run_one_module(file); if (blueslip.reset) { blueslip.reset(); } namespace.restore(); Handlebars.HandlebarsEnvironment(); }); } catch (error) { if (error.stack) { console.info(short_tb(error.stack)); } else { console.info(error); } process.exit(1); }
JavaScript
0
@@ -604,25 +604,24 @@ /static/js%22) -) + path.sep) @@ -620,16 +620,17 @@ ath.sep) +) ,%0A @@ -725,17 +725,16 @@ red/js%22) -) + path. @@ -736,16 +736,17 @@ path.sep +) ,%0A
8fcb015085e02b7fc4abf702cec57ccf827c8299
add server ip addresses
functions/commands/xmservers.js
functions/commands/xmservers.js
const lib = require('lib')({token: process.env.STDLIB_TOKEN}); /** * /hello * * Basic "Hello World" command. * All Commands use this template, simply create additional files with * different names to add commands. * * See https://api.slack.com/slash-commands for more details. * * @param {string} user The user id of the user that invoked this command (name is usable as well) * @param {string} channel The channel id the command was executed in (name is usable as well) * @param {string} text The text contents of the command * @param {object} command The full Slack command object * @param {string} botToken The bot token for the Slack bot you have activated * @returns {object} */ module.exports = (user, channel, text = '', command = {}, botToken = null, callback) => { var team = { dennis: 'U0545PDQ3', rodrigo: 'U0DU10LAU', roger: 'U75RRPETH', alejandro: 'U0408Q8R0', amec: 'U707X17U3', emily: 'U6XAQ854Y' } if(Object.values(team).indexOf(user) > -1){ if(team[text]) { callback(null, { response_type: 'ephemeral', text: `Hey <@${user}> here is the info for ${text}'s sever:` }); } else { callback(null, { response_type: 'ephemeral', text: `Sorry <@${user}> I don't know about the ${text} sever` }); } } else { callback(null, { response_type: 'ephemeral', text: `Sorry, this command is exclusive to the XMPie team.` }); } };
JavaScript
0
@@ -948,206 +948,1029 @@ %0A %7D +; %0A%0A -%0A if(Object.values(team).indexOf(user) %3E -1)%7B%0A%0A if(team%5Btext%5D) %7B%0A callback(null, %7B%0A response_type: 'ephemeral',%0A text: %60Hey %3C@$%7Buser%7D%3E here is the info for $%7Btext%7D's sever:%60 + var servers = %7B%0A dennis: %7B%0A ip: '192.168.19.171',%0A %7D,%0A rodrigo: %7B%0A ip: '192.168.19.167',%0A %7D,%0A roger: %7B%0A ip: '192.168.19.165',%0A %7D,%0A alejandro: %7B%0A ip: '192.6-168.19.164',%0A %7D,%0A amec: %7B%0A ip: '192.168.19.166',%0A %7D,%0A emily: %7B%0A ip: '192.168.19.168',%0A %7D%0A %7D%0A%0A if(Object.values(team).indexOf(user) %3E -1)%7B%0A%0A if(team%5Btext%5D) %7B%0A callback(null, %7B%0A response_type: 'ephemeral',%0A text: %60Hey %3C@$%7Buser%7D%3E here is the info for $%7Btext%7D's sever:%60,%0A attachments: %5B%0A %7B%0A fallback: %60Hey %3C@$%7Buser%7D%3E, good luck%60,%0A title: servers%5Btext%5D.ip,%0A text: 'Login:'%0A color: %22#6f6a9d%22,%0A fields: %5B%0A %7B%0A title: 'User',%0A value: 'xmpieadmin',%0A short: true%0A %7D%0A %7B%0A title: 'Password',%0A value: 'RainbowTrout330',%0A short: true%0A %7D%0A %5B%0A %7D,%0A %5D %0A
37905608230e85a0c6c38a9f1b5cdb0efcdf9cbe
Update Redux DevTools to log only in production env
src/redux/configureStore.js
src/redux/configureStore.js
import { applyMiddleware, combineReducers, createStore, } from 'redux'; import thunk from 'redux-thunk'; import enhancer from './storeEnhancer'; import { composeWithDevTools } from 'redux-devtools-extension'; export default (preloadedState, preloadedReducers) => createStore( preloadedReducers ? combineReducers(preloadedReducers) : () => ({}), preloadedState, composeWithDevTools( applyMiddleware(thunk), enhancer(preloadedReducers), ), );
JavaScript
0
@@ -205,16 +205,36 @@ xtension +/logOnlyInProduction ';%0A%0Aexpo
240138cb352642ad7d8f9ddf0640e4582b5648eb
fix preventDefault
client/views/regions/regions.js
client/views/regions/regions.js
Template.region_sel_outer.created = function(){ this.subscribe("Regions"); var instance = this; instance.searchingRegions = new ReactiveVar(false); }; Template.region_sel_outer.helpers({ searchingRegions: function() { return Template.instance().searchingRegions.get(); } }); Template.regionsDisplay.helpers({ region: function(){ var region = Regions.findOne(Session.get('region')); return region; } }); Template.regionsDisplay.events({ 'click .-regionsDisplay': function(event, instance) { instance.parentInstance().searchingRegions.set(true); } }); Template.region_sel.onCreated(function() { this.regionSearch = new ReactiveVar(''); }); Template.region_sel.rendered = function(){ Template.instance().$('.-searchRegions').select(); }; var updateRegionSearch = function(event, instance) { var search = instance.$('.-searchRegions').val(); search = String(search).trim(); instance.regionSearch.set(search); }; Template.region_sel.helpers({ regions: function() { var search = Template.instance().regionSearch.get(); var query = {}; if (search !== '') query = { name: new RegExp(search, 'i') }; return Regions.find(query); }, regionNameMarked: function() { var search = Template.instance().regionSearch.get(); var name = this.name; if (search === '') return name; var match = name.match(new RegExp(search, 'i')); // To add markup we have to escape all the parts separately var marked; if (match) { var term = match[0]; var parts = name.split(term); marked = _.map(parts, Blaze._escape).join('<strong>'+Blaze._escape(term)+'</strong>'); } else { marked = Blaze._escape(name); } return Spacebars.SafeString(marked); }, region: function(){ var region = Regions.findOne(Session.get('region')); return region; }, allCourses: function() { return _.reduce(Regions.find().fetch(), function(acc, region) { return acc + region.courseCount; }, 0); }, allUpcomingEvents: function() { return _.reduce(Regions.find().fetch(), function(acc, region) { return acc + region.futureEventCount; }, 0); }, courses: function() { return coursesFind({ region: this._id }).count(); }, currentRegion: function() { var region = this._id || "all"; return region == Session.get('region'); } }); Template.region_sel.events({ 'click a.regionselect': function(event, instance){ var region_id = this._id ? this._id : 'all'; var changed = Session.get('region') !== region_id; localStorage.setItem("region", region_id); // to survive page reload Session.set('region', region_id); // When the region changes, we want the content of the page to update // Many pages do not change when the region changed, so we go to // the homepage for those if (changed) { var routeName = Router.current().route.getName(); var routesToKeep = ['home', 'find', 'locations', 'calendar']; if (routesToKeep.indexOf(routeName) < 0) Router.go('/'); } instance.parentInstance().searchingRegions.set(false); e.preventDefault(); }, 'mouseover li.region a.regionselect': function() { if (Session.get('region') == "all") $('.courselist_course').not('.'+this._id).stop().fadeTo('slow', 0.33); }, 'mouseout li.region a.regionselect': function() { if (Session.get('region') == "all") $('.courselist_course').not('.'+this._id).stop().fadeTo('slow', 1); }, 'keyup .-searchRegions': _.debounce(updateRegionSearch, 100), 'focus .-searchRegions': function(event, instance) { instance.$('.dropdown-toggle').dropdown('toggle'); updateRegionSearch(event, instance); } });
JavaScript
0.000003
@@ -2354,16 +2354,42 @@ tance)%7B%0A +%09%09event.preventDefault();%0A %09%09var re @@ -3016,30 +3016,8 @@ e);%0A -%09%09e.preventDefault();%0A %09%7D,%0A
f09b70b251769891f1a2cf8c5fea810c9b0b23c4
Set 'exact' prop to Route to PatientView
src/web/components/App.react.js
src/web/components/App.react.js
/** * Copyright 2017 Yuichiro Tsuchiya * * 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. */ import React from 'react'; import { BrowserRouter, HashRouter, Route, } from 'react-router-dom'; import connect from '../../common/connect'; import Auth from '../containers/Auth'; import Alerts from '../containers/Alerts.react'; import PatientSelect from '../containers/PatientSelect'; import PatientView from '../containers/PatientView.react'; import Admin from '../components/Admin'; import Stats from '../containers/Stats'; import AdminRoute from '../containers/AdminRoute'; // Electron or Web? const Router = (window && window.process && window.process.type) ? HashRouter : BrowserRouter; const App = ({ children }: { children: ReactClass }) => ( <div> <Alerts /> {children} </div> ); export default connect(() => ( <App> <Auth> <Router> <div> <Route exact path="/" component={PatientSelect} /> <Route path="/patient/:patientId?" component={PatientView} /> <AdminRoute path="/admin" component={Admin} /> <Route path="/stats" component={Stats} /> </div> </Router> </Auth> </App> ));
JavaScript
0.000001
@@ -1461,24 +1461,30 @@ %3CRoute +exact path=%22/patie
368be6e935365a9e680824198f471275726ec3d2
Add function delete()
app/js/controllers.js
app/js/controllers.js
'use strict'; /* Controllers */ var app = angular.module('toDoList.controllers', []); app.controller('IndexCtrl', ['$scope', '$routeParams', '$location', '$http', function ($scope, $routeParams, $location, $http) { $scope.tasks = [{"text" : "clean", "done" : false}]; $scope.count = 1; $scope.addTask = function () { $scope.tasks.push({"text" : $scope.newtask, "done" : false}); $scope.count++; }; $scope.deleteTask = function () { for (var i = 0; i <= $scope.tasks.length; i++) { console.log($scope.tasks[i].done); if ($scope.tasks[i].done == "true") delete $scope.tasks[i]; } if($scope.count > 0) $scope.count--; }; }]);
JavaScript
0.000001
@@ -481,25 +481,24 @@ n () %7B %0A -%0A for (var @@ -493,151 +493,146 @@ -for (var i = 0; i %3C= $scope.tasks.length; i++) %7B%0A console.log($scope.tasks%5Bi%5D.done);%0A if ($scope.tasks%5Bi%5D.done == %22true%22) +var oldTasks = $scope.tasks;%0A $scope.tasks = %5B%5D;%0A%0A angular.forEach(oldTasks, function(task) %7B%0A if (!task.done)%0A @@ -629,32 +629,33 @@ ne)%0A +%7B %0A de @@ -652,22 +652,18 @@ -delete + $scope. @@ -671,11 +671,19 @@ asks -%5Bi%5D +.push(task) ;%0A @@ -692,11 +692,9 @@ -%7D%0A%0A + @@ -698,16 +698,17 @@ if + ($scope. @@ -726,24 +726,32 @@ + + $scope.count @@ -754,16 +754,52 @@ ount--;%0A + %7D %0A %7D);%0A %0A %7D;
2ed93b24be877f979d4feaf441e95d33046efcb9
delete query collection in RESMI
src/resources/collection.js
src/resources/collection.js
(function() { //@exclude 'use strict'; /*globals corbel */ //@endexclude /** * Collection requests * @class * @memberOf Resources * @param {String} type The collection type * @param {CorbelDriver} corbel instance */ corbel.Resources.Collection = corbel.Resources.BaseResource.inherit({ constructor: function(type, driver, params) { this.type = type; this.driver = driver; this.params = params || {}; }, /** * Gets a collection of elements, filtered, paginated or sorted * @method * @memberOf Resources.CollectionBuilder * @param {object} options Get options for the request * @return {Promise} ES6 promise that resolves to an {Array} of Resources or rejects with a {@link CorbelError} * @see {@link corbel.util.serializeParams} to see a example of the params */ get: function(options) { options = this.getDefaultOptions(options); var args = corbel.utils.extend(options, { url: this.buildUri(this.type), method: corbel.request.method.GET, Accept: options.dataType }); return this.request(args); }, /** * Adds a new element to a collection * @method * @memberOf Resources.CollectionBuilder * @param {object} data Data array added to the collection * @param {object} options Options object with dataType request option * @return {Promise} ES6 promise that resolves to the new resource id or rejects with a {@link CorbelError} */ add: function(data, options) { options = this.getDefaultOptions(options); var args = corbel.utils.extend(options, { url: this.buildUri(this.type), method: corbel.request.method.PUT, contentType: options.dataType, Accept: options.dataType, data: data }); return this.request(args).then(function(res) { return corbel.Services.getLocationId(res); }); } }); return corbel.Resources.Collection; })();
JavaScript
0
@@ -2254,16 +2254,754 @@ %7D);%0A + %7D,%0A%0A /**%0A * Delete a collection%0A * @method%0A * @memberOf Resources.CollectionBuilder%0A * @param %7Bobject%7D options Options object with dataType request option%0A * @return %7BPromise%7D ES6 promise that resolves to the new resource id or rejects with a %7B@link CorbelError%7D%0A */%0A delete: function(options) %7B%0A options = this.getDefaultOptions(options);%0A%0A var args = corbel.utils.extend(options, %7B%0A url: this.buildUri(this.type),%0A method: corbel.request.method.DELETE,%0A contentType: options.dataType,%0A Accept: options.dataType%0A %7D);%0A%0A return this.request(args);%0A
af1519d7f0725b099075ff5634a3306b9de5260e
clear search results on empty string
client/views/sections/search.js
client/views/sections/search.js
function search (collectionName, query, sortBy) { Session.set("waiting", true); EasySearch.search(collectionName, query, function (err, data) { var results = data.results; if (collectionName === "instructors") { Session.set("profCount", results.length) } else { Session.set("courseCount", results.length) } if (results && results.length > 0) { results = _.sortBy(results, function (elem) { return elem[sortBy]; }); } Session.set(collectionName + "Search", results); Session.set("waiting", false); }); }; Template.search.events({ 'keyup #search': function (e) { var query = $(e.target).val(); Session.set('query', query); setTimeout( function() { search('courses', query, 'courseParentNum'); search('instructors', query, 'name'); }, 100); } }); Template.search.rendered = function () { Session.set("profCount", 0); Session.set("courseCount", 0); $('#search').focus(); $('#search').attr('autocomplete', 'off'); $('#search').val(Session.get('query')); };
JavaScript
0.000005
@@ -39,24 +39,208 @@ , sortBy) %7B%0A + if (query == %22%22) %7B%0A Session.set(%22profCount%22, 0);%0A Session.set(%22courseCount%22, 0);%0A Session.set(%22instructorsSearch%22, %5B%5D);%0A Session.set(%22coursesSearch%22, %5B%5D);%0A %7D%0A else %7B%0A Session.se @@ -261,16 +261,18 @@ rue);%0A + + EasySear @@ -323,24 +323,26 @@ rr, data) %7B%0A + var resu @@ -361,24 +361,26 @@ esults;%0A + if (collecti @@ -405,32 +405,34 @@ ctors%22) %7B%0A + + Session.set(%22pro @@ -460,16 +460,18 @@ th)%0A + %7D else %7B @@ -473,24 +473,26 @@ lse %7B%0A + + Session.set( @@ -518,24 +518,26 @@ lts.length)%0A + %7D%0A if @@ -530,24 +530,26 @@ %7D%0A + if (results @@ -569,24 +569,26 @@ ngth %3E 0) %7B%0A + result @@ -635,16 +635,18 @@ + return e @@ -668,16 +668,18 @@ + + %7D);%0A %7D%0A @@ -670,26 +670,30 @@ %7D);%0A -%7D%0A + %7D%0A Session. @@ -733,16 +733,18 @@ sults);%0A + Sess @@ -770,22 +770,28 @@ false);%0A + %7D);%0A + %7D%0A %7D;%0A%0ATemp @@ -1105,32 +1105,39 @@ %7B%0A Session.set +Default (%22profCount%22, 0) @@ -1143,32 +1143,39 @@ );%0A Session.set +Default (%22courseCount%22,
8692ad389f7f4a44c06531a50b9b8ffc989fe21f
Update profileCtrl.js
app/js/profileCtrl.js
app/js/profileCtrl.js
//profileCtrl app.controller("profileCtrl", // Implementation the todoCtrl function($scope, Auth, $firebaseArray, $firebaseObject,$window) { Auth.$onAuthStateChanged(function(authData){ //initialize $scope.authData = authData; ref = firebase.database().ref("users/"+$scope.authData.uid+"/readOnly/info"); profile_info = $firebaseObject(ref); profile_info.$loaded().then(function(){ console.log(profile_info); $scope.profile_name = profile_info.name; $scope.profile_age = profile_info.age ; $scope.profile_company = profile_info.company; }); $scope.profile_readOnly = true; console.log($window.location.href); var start_pos = $window.location.href.lastIndexOf("profile/"); var end_pos = $window.location.href.length; var id = $window.location.href.slice(start_pos+8,end_pos); if (id != $scope.authData.uid) $scope.button_visible = true; else $scope.button_visible = false; if (authData) console.log(authData); else { console.log("signed out"); $window.location.href = '/'; } }); $scope.button_name = "EDIT"; $scope.edit = function(){ if($scope.profile_readOnly) { $scope.profile_readOnly=false; $scope.button_name = "SAVE"; } else{ ref = firebase.database().ref("users/"+$scope.authData.uid+"/readOnly/info"); profile_info = $firebaseObject(ref); profile_info.$loaded(); profile_info.name = $scope.profile_name; profile_info.age = $scope.profile_age; profile_info.company = $scope.profile_company; profile_info.$save().then(function(){ console.log(profile_info); }); $scope.profile_readOnly=true; $scope.button_name = "EDIT"; } }; } );
JavaScript
0.000002
@@ -1,18 +1,4 @@ -//profileCtrl%0A app. @@ -27,41 +27,8 @@ l%22, -%0A%0A%09// Implementation the todoCtrl %0A%09f @@ -88,19 +88,41 @@ ,$window +, $stateParams,Helper ) %7B +%09 %0A%09%09Auth. @@ -177,16 +177,36 @@ tialize%0A +%09%09%09if (authData) %7B%0A%09 %09%09%09$scop @@ -228,16 +228,17 @@ thData;%0A +%09 %09%09%09ref = @@ -309,24 +309,32 @@ /info%22);%0A%09%09%09 +%09$scope. profile_info @@ -365,122 +365,38 @@ %0A%09%09%09 -profile_info.$loaded().then(function()%7B%0A%09%09%09%09console.log(profile_info);%0A%09%09%09%09$scope.profile_name = profile_info.nam +%09$scope.profile_readOnly = tru e;%0A%09 @@ -409,23 +409,8 @@ ope. -profile_age = prof @@ -422,259 +422,70 @@ nfo. +t ag -e ;%0A%09%09%09%09$scope.profile_company = profile_info.company;%0A%09%09%09%7D);%0A%09%09%09$scope.profile_readOnly = true;%0A%09%09%09console.log($window.location.href);%0A%09%09%09var start_pos = $window.location.href.lastIndexOf(%22profile/%22);%0A%09%09%09var end_pos = $window.location.href.length +s = Helper.tags;%0A%09%09%09%09//$scope.profile_info.tag.c++=false ;%0A +%09 %09%09%09v @@ -497,57 +497,26 @@ = $ -window.location.href.slice(start_pos+8,end_pos) +stateParams.uid ;%0A +%09 %09%09%09i @@ -570,22 +570,24 @@ sible = -tru +fals e;%0A +%09 %09%09%09else @@ -614,32 +614,18 @@ e = -fals +tru e;%0A%09%09%09 -if (authData) +%09 cons @@ -643,16 +643,21 @@ hData);%0A +%09%09%09%7D%0A %09%09%09else @@ -693,41 +693,8 @@ %22);%0A -%09%09%09%09$window.location.href = '/';%0A %09%09%09%7D @@ -885,298 +885,15 @@ %09%09%09%09 -ref = firebase.database().ref(%22users/%22+$scope.authData.uid+%22/readOnly/info%22);%0A%09%09%09%09profile_info = $firebaseObject(ref);%0A%09%09%09%09profile_info.$loaded();%0A%09%09%09%09profile_info.name = $scope.profile_name;%0A%09%09%09%09profile_info.age = $scope.profile_age;%0A%09%09%09%09profile_info.company = $scope.profile_company;%0A%09%09%09%09 +$scope. prof @@ -943,16 +943,23 @@ ole.log( +$scope. profile_
d252a22fdb3201b2e53345a744026dba3a601967
Use stdin to send messages to the #oftn channel
hub/irc/Manager.js
hub/irc/Manager.js
var Connection = require ("./Connection.js"); var IRCManager = function (config) { this.config = config; this.connections = []; }; /* This function takes the server profile from the config and extends * it with the defaults from the config so that when the defaults * change or the server profile changes, it will updated as such */ IRCManager.prototype.create_profile = function (profile, defaults) { profile.__proto__ = defaults; return profile; }; IRCManager.prototype.connect = function () { var connection, profile, servers, defaults; servers = this.config.data.IRC.servers; defaults = this.config.data.IRC.default; for (var i = 0, len = servers.length; i < len; i++) { profile = this.create_profile (servers[i], defaults); connection = new Connection (profile); ///* connection.on("raw", function (m) { console.log (m); }); connection.on("001", function (message) { this.raw ("JOIN #oftn"); }); //*/ console.log ("Connecting to IRC server \"%s\"", connection.name); connection.connect (); this.connections.push (connection); } }; IRCManager.prototype.disconnect = function(callback) { var connections, self = this; // First we clone the connections array to use as a queue connections = this.connections.slice (); console.log ("Waiting for servers to close connections..."); (function next () { var c = connections.shift (); if (!c) { callback.call (self); return; } c.quit (next); }) (); }; module.exports = IRCManager;
JavaScript
0
@@ -922,16 +922,137 @@ oftn%22);%0A +%09%09%09var stdin = process.openStdin();%0A%09%09%09stdin.on('data', function(chunk) %7B connection.send (%22PRIVMSG #oftn :%22+chunk); %7D);%0A %09%09%7D);%0A%09%09
ceabcc8bcab863000fd3047c79afac24a9b3da71
Fix syntax error in last commit
src/wrappers/node-interfaces.js
src/wrappers/node-interfaces.js
// Copyright 2013 The Polymer Authors. All rights reserved. // Use of this source code is goverened by a BSD-style // license that can be found in the LICENSE file. (function(scope) { 'use strict'; var NodeList = scope.wrappers.NodeList; function forwardElement(node) { while (node && node.nodeType !== Node.ELEMENT_NODE) { node = node.nextSibling; } return node; } function backwardsElement(node) { while (node && node.nodeType !== Node.ELEMENT_NODE) { node = node.previousSibling; } return node; } var ParentNodeInterface = { get firstElementChild() { return forwardElement(this.firstChild); }, get lastElementChild() { return backwardsElement(this.lastChild); }, get childElementCount() { var count = 0; for (var child = this.firstElementChild; child; child = child.nextElementSibling) { count++; } return count; }, get children() { var wrapperList = new NodeList(); var i = 0; for (var child = this.firstElementChild; child; child = child.nextElementSibling) { wrapperList[i++] = child; } wrapperList.length = i; return wrapperList; }, remove() { var p = this.parentNode; if (p) p.removeChild(this); } }; var ChildNodeInterface = { get nextElementSibling() { return forwardElement(this.nextSibling); }, get previousElementSibling() { return backwardsElement(this.previousSibling); } }; scope.ChildNodeInterface = ChildNodeInterface; scope.ParentNodeInterface = ParentNodeInterface; })(window.ShadowDOMPolyfill);
JavaScript
0.000012
@@ -1266,16 +1266,26 @@ remove +: function () %7B%0A
c3ad27ec2e6d61366c9230f922588164354b5179
Add functionality to cancel file read in saga
src/sagas/getArrayBuffer.js
src/sagas/getArrayBuffer.js
import { eventChannel, END } from 'redux-saga' import { take, put, call } from 'redux-saga/effects' import { saveArrayBuffer, saveProgress } from '../actions' const createFileReadChannel = (file) => { return eventChannel((emitter) => { let reader = new FileReader() const onLoad = () => { emitter({ arrayBuffer: reader.result }); emitter(END) } const onProgress = (e) => { emitter({ progress: Math.round((e.loaded / e.total) * 100) }) } const onAbort = () => { emitter({ progress: -1 }) } const onError = (error) => { emitter({ error }); emitter(END) } reader.onload = onLoad reader.onprogress = onProgress reader.onabort = onAbort reader.onerror = onError reader.readAsArrayBuffer(file) const unsubscribe = () => { reader = null } return unsubscribe }) } export const getArrayBuffer = function* (file) { yield put(saveArrayBuffer(null)) const fileReadChannel = yield call(createFileReadChannel, file) try { while (true) { const { progress, arrayBuffer, error } = yield take(fileReadChannel) if (arrayBuffer) { yield put(saveArrayBuffer(arrayBuffer)) return } if (error) { console.error('Error during file read operation: ', error) return } yield put(saveProgress(progress)) } } finally { fileReadChannel.close() } }
JavaScript
0
@@ -64,16 +64,22 @@ ut, call +, race %7D from @@ -108,16 +108,26 @@ import %7B + saveFile, saveArr @@ -168,16 +168,76 @@ actions' +%0Aimport %7B CANCEL_FILE_READ %7D from '../constants/ActionTypes' %0A%0Aconst @@ -527,64 +527,8 @@ ) %7D%0A - const onAbort = () =%3E %7B emitter(%7B progress: -1 %7D) %7D%0A @@ -658,37 +658,8 @@ ess%0A - reader.onabort = onAbort%0A @@ -748,24 +748,92 @@ e = () =%3E %7B%0A + if (reader.readyState === 1) %7B%0A reader.abort()%0A %7D%0A reader @@ -1067,16 +1067,208 @@ const %7B + channelOutput, cancelFileRead %7D = yield race(%7B%0A channelOutput: take(fileReadChannel),%0A cancelFileRead: take(CANCEL_FILE_READ)%0A %7D)%0A if (channelOutput) %7B%0A const %7B progres @@ -1297,42 +1297,30 @@ %7D = -yield take(fileReadChannel) +channelOutput %0A + if ( @@ -1330,24 +1330,26 @@ ayBuffer) %7B%0A + yiel @@ -1384,16 +1384,18 @@ uffer))%0A + @@ -1403,26 +1403,30 @@ eturn%0A -%7D%0A + %7D%0A if (er @@ -1428,24 +1428,26 @@ f (error) %7B%0A + cons @@ -1501,32 +1501,34 @@ error)%0A + return%0A %7D%0A @@ -1520,26 +1520,30 @@ eturn%0A -%7D%0A + %7D%0A yield @@ -1570,16 +1570,167 @@ gress))%0A + %7D%0A else if (cancelFileRead) %7B%0A fileReadChannel.close()%0A yield put(saveProgress(-1))%0A yield put(saveFile(null))%0A %7D%0A %7D%0A
9ef233f3e2ca3ab250b66149390c833c117c27e7
Use isBigNumber to check for a type
chai-bignumber.js
chai-bignumber.js
module.exports = function(BigNumber){ BigNumber = BigNumber || require('bignumber.js'); return function (chai, utils) { chai.Assertion.addProperty('bignumber', function() { utils.flag(this, 'bignumber', true); }); var convert = function(value, dp, rm) { var number; if (typeof value === 'string' || typeof value === 'number') { number = new BigNumber(value); } else if (value instanceof BigNumber) { number = value; } else { new chai.Assertion(value).assert(false, 'expected #{act} to be an instance of string, number or BigNumber'); } if (parseInt(dp) === dp) { if (rm === undefined) { rm = BigNumber.ROUND_HALF_UP; } number = number.round(dp, rm); } return number; }; var override = function(fn) { return function (_super) { return function(value, dp, rm) { if (utils.flag(this, 'bignumber')) { var expected = convert(value, dp, rm); var actual = convert(this._obj, dp, rm); fn.apply(this, [expected, actual]); } else { _super.apply(this, arguments); } }; }; }; // BigNumber.equals var equals = override(function(expected, actual) { this.assert( expected.equals(actual), 'expected #{act} to equal #{exp}', 'expected #{act} to be different from #{exp}', expected.toString(), actual.toString() ); }); chai.Assertion.overwriteMethod('equal', equals); chai.Assertion.overwriteMethod('equals', equals); chai.Assertion.overwriteMethod('eq', equals); // BigNumber.greaterThan var greaterThan = override(function(expected, actual) { this.assert( actual.greaterThan(expected), 'expected #{act} to be greater than #{exp}', 'expected #{act} to be less than or equal to #{exp}', expected.toString(), actual.toString() ); }); chai.Assertion.overwriteMethod('above', greaterThan); chai.Assertion.overwriteMethod('gt', greaterThan); chai.Assertion.overwriteMethod('greaterThan', greaterThan); // BigNumber.greaterThanOrEqualTo var greaterThanOrEqualTo = override(function(expected, actual) { this.assert( actual.greaterThanOrEqualTo(expected), 'expected #{act} to be greater than or equal to #{exp}', 'expected #{act} to be less than #{exp}', expected.toString(), actual.toString() ); }); chai.Assertion.overwriteMethod('least', greaterThanOrEqualTo); chai.Assertion.overwriteMethod('gte', greaterThanOrEqualTo); // BigNumber.lessThan var lessThan = override(function(expected, actual) { this.assert( actual.lessThan(expected), 'expected #{act} to be less than #{exp}', 'expected #{act} to be greater than or equal to #{exp}', expected.toString(), actual.toString() ); }); chai.Assertion.overwriteMethod('below', lessThan); chai.Assertion.overwriteMethod('lt', lessThan); chai.Assertion.overwriteMethod('lessThan', lessThan); // BigNumber.lessThanOrEqualTo var lessThanOrEqualTo = override(function(expected, actual) { this.assert( actual.lessThanOrEqualTo(expected), 'expected #{act} to be less than or equal to #{exp}', 'expected #{act} to be greater than #{exp}', expected.toString(), actual.toString() ); }); chai.Assertion.overwriteMethod('most', lessThanOrEqualTo); chai.Assertion.overwriteMethod('lte', lessThanOrEqualTo); // BigNumber.isFinite chai.Assertion.addProperty('finite', function () { var value = convert(this._obj); this.assert( value.isFinite(), 'expected #{this} to be finite', 'expected #{this} to not be finite', value.toString() ); }); // BigNumber.isInteger chai.Assertion.addProperty('integer', function () { var value = convert(this._obj); this.assert( value.isInteger(), 'expected #{this} to be an integer', 'expected #{this} to not be an integer', value.toString() ); }); // BigNumber.isNegative chai.Assertion.addProperty('negative', function () { var value = convert(this._obj); this.assert( value.isNegative(), 'expected #{this} to be negative', 'expected #{this} to not be negative', value.toString() ); }); // BigNumber.isZero chai.Assertion.addProperty('zero', function () { var value = convert(this._obj); this.assert( value.isZero(), 'expected #{this} to be zero', 'expected #{this} to not be zero', value.toString() ); }); }; };
JavaScript
0
@@ -424,20 +424,11 @@ alue - instanceof +.is BigN
f8fc1afe3ff8614955799ed1c69174925a45f184
use config variable for graphql endpoint
src/server/graphql/index.js
src/server/graphql/index.js
const graphqlExpress = require('graphql-server-express').graphqlExpress; // format Error const ensureAuthenticated = require('../middleware/ensure_authenticated'); // format Error const formatError = require('./format_error').formatError(); // get executable schema const { getExecutableSchema } = require('./schema'); const schema = getExecutableSchema(); // subscriptions const addSubscriptions = require('./subscriptions'); // pubsub const pubsub = require('./pubsub'); // get database connectors const db = require('../db'); module.exports = (app, ws_server) => { // user graphqlExpress middleware with ensure authenticated app.use('/graph', ensureAuthenticated, graphqlExpress(req => { // get query const query = req.query.query || req.body.query || {}; // root value const rootValue = {}; // viewer const viewer = req.user; // context const context = { viewer, db, pubsub }; // return config return { schema, rootValue, context, formatError }; })); // Add Subscriptions const subse = addSubscriptions({ ws_server, schema, db }); };
JavaScript
0
@@ -529,16 +529,70 @@ /db');%0A%0A +const %7B%0A graphql_endpoint%0A%7D = require('../config');%0A%0A module.e @@ -699,16 +699,30 @@ use( -'/ +%60/$%7B graph -' +ql_endpoint%7D%60 , en
cee78b01d6e25bfea716aedc3312308992c18159
Add guid to checkbox select
addon/components/form-controls/ff-checkbox-select.js
addon/components/form-controls/ff-checkbox-select.js
import FormControlsAbstractSelectComponent from './abstract-select'; import { action } from '@ember/object'; import { arg } from 'ember-arg-types'; import { string, bool } from 'prop-types'; import { get } from '@ember/object'; import { A } from '@ember/array'; export default class FormControlsFfCheckboxSelectComponent extends FormControlsAbstractSelectComponent { @arg(string) for = 'id'; @arg value = []; @arg(bool) showClearAll = false; get _showClearAll() { return this.showClearAll && this.value.length > 0; } @action idFor(item) { return `${this.for}-${this.isPrimitive ? item : get(item, this.idKey)}`; } @action labelFor(item) { return this.isPrimitive ? item : get(item, this.labelKey); } @action handleChange(value) { if (this.isSelected(value)) { this.args.onChange(this.value.filter((_) => !this._compare(_, value))); } else { this.args.onChange(A(this.value).toArray().concat(value)); } } @action isSelected(value) { return !!this.value.find((_) => this._compare(_, value)); } @action clearAll() { return this.args.onChange([]); } _compare(a, b) { return this.isPrimitive ? a === b : get(a, this.idKey) === get(b, this.idKey); } }
JavaScript
0
@@ -254,16 +254,67 @@ /array'; +%0Aimport %7B guidFor %7D from '@ember/object/internals'; %0A%0Aexport @@ -686,16 +686,33 @@ .idKey)%7D +-$%7BguidFor(this)%7D %60;%0A %7D%0A%0A
42306a7907aee5773f8cf255d7602c6c7198ea9d
use 1 and 0
src/views/home.js
src/views/home.js
"use strict" const title = document.getElementById("title") const msg = document.getElementById("msg") const msg2 = document.getElementById("msg2") const form = document.getElementById("form") const input = document.getElementById("input") const onePrep = e => { e.preventDefault() if (input.value.trim() === "") { msg2.textContent = "That can't be empty." return } one(input.value) } const one = question => { input.value = "" msg.textContent = `What are some factors that affect '${question}'?` msg2.textContent = "They should also be yes/no, and separated with commas." form.onsubmit = twoPrep(question) } const twoPrep = question => e => { e.preventDefault() if (input.value.trim() === "") { msg2.textContent = "That can't be empty." return } const factors = input.value.split(",").map(x => x.trim()) if (factors.find(x => x === "") !== undefined) { msg2.textContent = "You can't have an empty factor." return } if (factors.length > 7) { msg2.textContent = "You can't have more than 7 factors." return } two(question, factors) } const isGreen = x => x.className === "green" const addRow = n => isCalculated => () => { window.scrollTo(0, document.body.scrollHeight) const row = document.createElement("div") for (let i = 0; i < n; i++) { const el = document.createElement("span") row.appendChild(el) if (isCalculated && i === n - 1) { el.className = "gray" el.textContent = "?" continue } el.className = "green" el.textContent = "Y" el.onclick = () => { const ig = isGreen(el) el.className = ig ? "red" : "green" el.textContent = ig ? "N" : "Y" } } form.insertBefore(row, form.lastChild) return row } const two = (question, factors) => { input.remove() msg.textContent = "Enter some data." msg2.textContent = "Click to add rows and switch between yes/no." const header = document.createElement("div") let el for (const x of factors) { el = document.createElement("span") el.textContent = x el.className = "blue" header.appendChild(el) } el = document.createElement("span") el.textContent = question el.className = "cyan" header.appendChild(el) form.appendChild(header) const footer = document.createElement("div") const addRowBtn = document.createElement("span") addRowBtn.textContent = "Add datapoint" addRowBtn.className = "gray" const thisAddRow = addRow(factors.length + 1) addRowBtn.onclick = thisAddRow(false) const trainBtn = document.createElement("span") trainBtn.textContent = "Train" trainBtn.className = "yellow" trainBtn.onclick = threePrep(thisAddRow, addRowBtn, trainBtn) footer.appendChild(addRowBtn) footer.appendChild(trainBtn) form.appendChild(footer) } const toData = x => isGreen(x) ? 1 : 0 const threePrep = (thisAddRow, addRowBtn, trainBtn) => e => { e.preventDefault() // a gross hack // it would be better to use one of those fancy front-end libraries with // two-way binding and whatnot const fc = form.children const max = fc.length - 1 const data = [] const results = [] // skip the header and footer for (let i = 1; i < max; i++) { fc[i].className = "grayed" const elems = fc[i].children const max = elems.length - 1 const ary = [] for (let j = 0; j < max; j++) { elems[j].onclick = null ary.push(toData(elems[j])) } elems[max].onclick = null data.push(ary) results.push(toData(elems[max])) } three(fetch("/train", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({d: data, r: results}) }).then(x => x.json()), thisAddRow, addRowBtn, trainBtn) } const three = (train, thisAddRow, addRowBtn, calcBtn) => { msg.textContent = "Now add some data for which you don't know the answer." msg2.textContent = "Use the calculate button to make an educated guess." const pending = [] calcBtn.textContent = "Calculate" calcBtn.onclick = () => { while (pending.length !== 0) { const p = pending.pop() p.className = "grayed" const data = [] const elems = p.children const max = elems.length - 1 for (let j = 0; j < max; j++) { elems[j].onclick = null data.push(toData(elems[j])) } p.lastChild.textContent = "..." train.then(({s0, s1}) => { fetch("/get", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({d: data, s0, s1}) }) .then(x => x.json()) .then(({r}) => { p.lastChild.className = r > 0.5 ? "green" : "red" p.lastChild.textContent = r.toFixed(4) }) }) } } thisAddRow = thisAddRow(true) addRowBtn.onclick = () => { pending.push(thisAddRow()) } } title.textContent = "Stairwell" msg.textContent = "What is your question for today?" msg2.textContent = "It should be a yes/no question." input.focus() form.onsubmit = onePrep form.style.display = "block"
JavaScript
0.999975
@@ -1659,17 +1659,17 @@ tent = %22 -Y +1 %22%0A @@ -1813,15 +1813,15 @@ ? %22 -N +0 %22 : %22 -Y +1 %22%0A
6f80467f0953dd777910fb1161c21adaf2c835d6
Fix linter
src/virtualDom.js
src/virtualDom.js
/** * Wrapper on top of the Document object model javascript API, * to make our life easier when we need to interact with such API in our tests * * @constructor VirtualDom */ window.getJasmineRequireObj().VirtualDom = function () { var oldDocument, spyElement = function (el) { var original = el.addEventListener; el.events = {}; spyOn(el, 'addEventListener').and.callFake(function (name, listener) { if (this.events[name]) { this.events[name].push(listener); } else { this.events[name] = [listener]; } original.call(this, name, listener); }); return el; }, spyElements = function (elements) { var i, result = [], length = elements.length; for (i = 0; i < length; i++) { result.push(spyElement.call(this, elements[i])); } return result; }, getElementById = function (parent, id) { var children = parent.childNodes, child, result, i; for (i = 0; i < children.length; i++) { child = children[i]; if (child.id === id) { return child; } result = getElementById.call(this, child, id); if (result) { return result; } } }, getSingleElement = function (el) { if (el) { return spyElement.call(this, el); } return null; }, isAlreadyInstalled = function () { return !!oldDocument; }, mergeConfigIntoEventObject = function (eventObj, config) { var prop; for (prop in config) { if (config.hasOwnProperty(prop)) { eventObj[prop] = config[prop]; } } }, merge = function (target, source) { var result = {}, property; for (property in target) { result[property] = target[property]; } for (property in source) { if (source.hasOwnProperty(property)) { result[property] = source[property]; } } return result; }, onEventTriggered = function (e) { e.preventDefault(); e.target.removeEventListener(e.type, onEventTriggered); }, shouldEventBubble = function (element) { return element.parentElement !== null && element.parentElement !== undefined; }, callListeners = function (element, eventObject) { var i; if (element.events && element.events[eventObject.type]) { for (i = 0; i < element.events[eventObject.type].length; i++) { element.events[eventObject.type][i].call(element, eventObject); } } }, dispatchEvent = function (element, eventObject) { callListeners.call(this, element, eventObject); if (shouldEventBubble.call(this, element)) { dispatchEvent.call(this, element.parentElement, eventObject); } }; /** * This method will override the document API to use the virtual one, instead of the real one. * * @param {String} [body]. HTML template to be added into the virtual dom when installing it * @memberof VirtualDom */ this.install = function (body) { var dom ; if (isAlreadyInstalled.call(this)) { throw 'Virtual dom already installed'; } dom = document.createElement('html'); dom.innerHTML = body ? body : ''; oldDocument = { getElementsByTagName: document.getElementsByTagName, getElementById: document.getElementById, querySelector: document.querySelector, querySelectorAll: document.querySelectorAll, getElementsByClassName: document.getElementsByClassName }; document.getElementsByTagName = function (tagName) { if (tagName.toLowerCase() === 'html') { return spyElements.call(this, [dom]); } return spyElements.call(this, dom.getElementsByTagName(tagName)); }; document.getElementById = function (id) { return getSingleElement.call(this, getElementById.call(this, dom, id)); }; document.getElementsByClassName = function (className) { return spyElements.call(this, dom.getElementsByClassName(className)); }; document.querySelector = function (selector) { return getSingleElement.call(this, dom.querySelector(selector)); }; document.querySelectorAll = function (selector) { return spyElements.call(this, dom.querySelectorAll(selector)); }; // Object.defineProperty(document, 'body', { // get: function () { // return this.getElementsByTagName('body')[0]; // }, // configurable: true // }); // Object.defineProperty(document, 'head', { // get: function () { // return this.getElementsByTagName('head')[0]; // }, // configurable: true // }); }; /** * @memberof VirtualDom */ this.uninstall = function () { var method; for (method in oldDocument) { if (oldDocument.hasOwnProperty(method)) { document[method] = oldDocument[method]; } } oldDocument = null; }; /** * Trigger any kind of event from any element, native or custom events * @param {Object} element. Dom Element * @param {String} event. Event name * @param {Object} config. parameters to be added to the event object * @memberof VirtualDom */ this.trigger = function (element, event, config) { var eventObject = new Event(event, { bubbles: true, cancelable: true }), preventBackup = eventObject.preventDefault; spyOn(eventObject, 'preventDefault').and.callFake(function () { preventBackup.call(eventObject); }); element.addEventListener(event, onEventTriggered); mergeConfigIntoEventObject.call(this, eventObject, config); dispatchEvent.call(this, element, merge.call(this, eventObject, { target: element })); return eventObject.preventDefault.calls.count() === 1; }; /** * Uninstall and install the virtual dom with a new html * @param {String} [body]. HTML template to be added into the virtual dom when installing it * @memberof VirtualDom */ this.resetDom = function (body) { this.uninstall(); this.install(body); }; }; (function () { var require = window.getJasmineRequireObj(); window.jasmine.virtualDom = new require.VirtualDom(); })();
JavaScript
0.000002
@@ -1516,24 +1516,16 @@ %7D%0A - %0A @@ -1950,16 +1950,50 @@ perty;%0A%0A + /* jshint forin: false */%0A @@ -2069,32 +2069,65 @@ erty%5D;%0A %7D +%0A /* jshint forin: true */ %0A%0A for (p @@ -4308,26 +4308,16 @@ n (id) %7B - %0A
aecdbc68854f8b74aa24128ac39186e3e14a5b67
fix port in heroku
src/startup/configuration-heroku.js
src/startup/configuration-heroku.js
let fs = require("fs"); let winston = require("winston"); let logger = require("../logger"); let env = process.env; logger.configure({ level: 'verbose', transports: [ new (winston.transports.Console)() ] }); module.exports = { server: { port: env.NODE_PORT, ip: env.NODE_IP }, authentication: { passphrase: "MY-PASS-PHRASE-FOR-PROJECT-MANAGER-wd871623746173264716287346", options: {session: true} }, database : { database: env.NODE_DATABASE_NAME, username: env.NODE_DATABASE_USER, password: env.NODE_DATABASE_USER_PASSWORD, options: { host: env.NODE_DATABASE_HOST port: env.NODE_DATABASE_PORT dialect: "postgres", pool: { max: 5, min: 0, idle: 10000 }, logging: (sql) => { //logger.info(`[${new Date()}] ${sql}`); }, define: { freezeTableName: true, timestamps: false, underscored: true, } } } };
JavaScript
0
@@ -282,21 +282,16 @@ rt: env. -NODE_ PORT,%0D%0A @@ -301,19 +301,17 @@ ip: -env.NODE_IP +undefined %0D%0A
c2eea8c23cdee12d1de74b78e6a2c68ba9af2ade
remove the hardcode current date
app/assets/javascripts/map/views/layers/LossLayer.js
app/assets/javascripts/map/views/layers/LossLayer.js
/** * The UMD loss map layer view. * * @return LossLayer class (extends CanvasLayerClass) */ define([ 'd3', 'moment', 'uri', 'abstract/layer/CanvasLayerClass', 'map/presenters/layers/UMDLossLayerPresenter' ], function(d3, moment, UriTemplate, CanvasLayerClass, Presenter) { 'use strict'; var LossLayer = CanvasLayerClass.extend({ options: { threshold: 30, dataMaxZoom: 12, urlTemplate: 'https://storage.googleapis.com/wri-public/Hansen_16/tiles/hansen_world/v1/tc{threshold}{/z}{/x}{/y}.png', currentDate: ['2001-01-01','2017-01-01'] }, init: function(layer, options, map) { this.presenter = new Presenter(this); if (!! options.currentDate && (options.currentDate[0] > options.currentDate[1])) { var kllm = options.currentDate[1]; options.currentDate[1] = options.currentDate[0]; options.currentDate[0] = kllm; kllm = null; } this.currentDate = options.currentDate || [moment(layer.mindate), moment(layer.maxdate)]; this.threshold = options.threshold || this.options.threshold; this._super(layer, options, map); }, /** * Filters the canvas imgdata. * @override */ filterCanvasImgdata: function(imgdata, w, h, z) { var components = 4; var exp = z < 11 ? 0.3 + ((z - 3) / 20) : 1; if (! !!this.currentDate[0]._d) { this.currentDate[0] = moment(this.currentDate[0]); this.currentDate[1] = moment(this.currentDate[1]); } var yearStart = this.currentDate[0].year(); var yearEnd = this.currentDate[1].year(); var myscale = d3.scale.pow() .exponent(exp) .domain([0,256]) .range([0,256]); for(var i = 0; i < w; ++i) { for(var j = 0; j < h; ++j) { var pixelPos = (j * w + i) * components; var intensity = imgdata[pixelPos]; var yearLoss = 2000 + imgdata[pixelPos + 2]; if (yearLoss >= yearStart && yearLoss < yearEnd) { imgdata[pixelPos] = 220; imgdata[pixelPos + 1] = (72 - z) + 102 - (3 * myscale(intensity) / z); imgdata[pixelPos + 2] = (33 - z) + 153 - ((intensity) / z); imgdata[pixelPos + 3] = z < 13 ? myscale(intensity) : intensity; } else { imgdata[pixelPos + 3] = 0; } } } }, /** * Used by UMDLoassLayerPresenter to set the dates for the tile. * * @param {Array} date 2D array of moment dates [begin, end] */ setCurrentDate: function(date) { this.currentDate = date; this.updateTiles(); }, setThreshold: function(threshold) { this.threshold = threshold; this.presenter.updateLayer(); }, _getUrl: function(x, y, z) { return new UriTemplate(this.options.urlTemplate) .fillFromObject({x: x, y: y, z: z, threshold: this.threshold}); } }); return LossLayer; });
JavaScript
0.999999
@@ -531,56 +531,8 @@ png' -,%0A currentDate: %5B'2001-01-01','2017-01-01'%5D %0A
9c53f183795b689156aabce67726c0d8e6afad90
Update and remove leftover pre tag in prototype
app/assets/javascripts/student_profile/ElaDetails.js
app/assets/javascripts/student_profile/ElaDetails.js
import React from 'react'; import PropTypes from 'prop-types'; import _ from 'lodash'; import {toMomentFromRailsDate} from '../helpers/toMoment'; import {high, medium, low} from '../helpers/colors'; import DetailsSection from './DetailsSection'; import StarChart from './StarChart'; import {McasNextGenChart, McasOldChart, McasSgpChart} from './McasChart'; /* This renders details about ELA performance and growth in the student profile page. On charts, we could filter out older values, since they're drawn outside of the visible projection area, and Highcharts hovers look a little strange because of that. It shows a bit more historical context though, so we'll keep all data points, even those outside of the visible range since interpolation lines will still be visible. */ export default class ElaDetails extends React.Component { render() { const {hideStar} = this.props; return ( <div className="ElaDetails"> {this.renderDibels()} {this.renderFAndPs()} {!hideStar && this.renderStarReading()} {this.renderMCASELANextGenScores()} {this.renderMCASELAScores()} {this.renderMCASELAGrowth()} </div> ); } renderDibels() { const {dibels} = this.props; if (dibels.length === 0) return null; const latestDibels = _.last(_.sortBy(dibels, 'date_taken')); return ( <DetailsSection title="DIBELS, latest score"> <div>{this.renderDibelsScore(latestDibels.benchmark)} on {toMomentFromRailsDate(latestDibels.date_taken).format('M/D/YY')}</div> </DetailsSection> ); } renderDibelsScore(score) { const backgroundColor = { 'INTENSIVE': low, 'STRATEGIC': medium, 'CORE': high }[score] || '#ccc'; return <span style={{padding: 5, opacity: 0.85, fontWeight: 'bold', color: 'white', backgroundColor}}>{score}</span>; } renderFAndPs() { const {fAndPs} = this.props; if (fAndPs.length === 0) return null; const fAndP = _.last(_.sortBy(fAndPs, 'benchmark_date')); const maybeCode = (fAndP.f_and_p_code) ? ` with ${fAndP.f_and_p_code} code` : null; return ( <DetailsSection title="Fountass and Pinnell (F&P), latest score"> <pre>{JSON.stringify(fAndP)}</pre> <div>Level {fAndP.instructional_level}{maybeCode} on {toMomentFromRailsDate(fAndP.benchmark_date).format('M/D/YY')}</div> </DetailsSection> ); } renderStarReading() { const {chartData, studentGrade} = this.props; return ( <DetailsSection title="STAR Reading, last 4 years"> <StarChart starSeries={chartData.star_series_reading_percentile} studentGrade={studentGrade} /> </DetailsSection> ); } renderMCASELANextGenScores() { const {chartData, studentGrade} = this.props; const mcasSeries = chartData.next_gen_mcas_ela_scaled; if (!mcasSeries || mcasSeries.length === 0) return null; return ( <DetailsSection title="MCAS ELA Scores (Next Gen), last 4 years"> <McasNextGenChart mcasSeries={mcasSeries} studentGrade={studentGrade} /> </DetailsSection> ); } renderMCASELAScores() { const {chartData, studentGrade} = this.props; const mcasSeries = chartData.mcas_series_ela_scaled; if (!mcasSeries || mcasSeries.length === 0) return null; return ( <DetailsSection title="MCAS ELA Scores, last 4 years"> <McasOldChart mcasSeries={mcasSeries} studentGrade={studentGrade} /> </DetailsSection> ); } renderMCASELAGrowth() { const {chartData, studentGrade} = this.props; const mcasSeries = chartData.mcas_series_ela_growth; if (!mcasSeries || mcasSeries.length === 0) return null; return ( <DetailsSection title="MCAS ELA growth percentile (SGP), last 4 years"> <McasSgpChart mcasSeries={mcasSeries} studentGrade={studentGrade} /> </DetailsSection> ); } } ElaDetails.propTypes = { dibels: PropTypes.array.isRequired, fAndPs: PropTypes.array.isRequired, chartData: PropTypes.shape({ star_series_reading_percentile: PropTypes.array, mcas_series_ela_scaled: PropTypes.array, next_gen_mcas_ela_scaled: PropTypes.array, mcas_series_ela_growth: PropTypes.array }).isRequired, studentGrade: PropTypes.string.isRequired, hideStar: PropTypes.bool };
JavaScript
0
@@ -2155,17 +2155,16 @@ %22Fountas -s and Pin @@ -2203,54 +2203,94 @@ %3C -pre%3E%7BJSON.stringify(fAndP)%7D%3C/pre%3E%0A %3Cdiv +div%3E%0A %3Cspan style=%7B%7Bpadding: 5, backgroundColor: '#ccc', fontWeight: 'bold'%7D%7D %3ELev @@ -2330,16 +2330,40 @@ ybeCode%7D +%3C/span%3E%0A %3Cspan%3E on %7BtoM @@ -2412,32 +2412,48 @@ ormat('M/D/YY')%7D +%3C/span%3E%0A %3C/div%3E%0A %3C/D
114052d37d48dba50f4d43631514cb78a68986df
Fix Settings showing BusyIndicator indefinitely
src/Views/Settings.js
src/Views/Settings.js
import declare from 'dojo/_base/declare'; import lang from 'dojo/_base/lang'; import connect from 'dojo/_base/connect'; import _CardLayoutListMixin from './_CardLayoutListMixin'; import List from 'argos/List'; const resource = window.localeContext.getEntitySync('settings').attributes; /** * @class crm.Views.Settings * * * @extends argos.List * */ const __class = declare('crm.Views.Settings', [List, _CardLayoutListMixin], { // Templates itemIconTemplate: new Simplate([ '<button data-action="{%= $.action %}" {% if ($.view) { %}data-view="{%= $.view %}"{% } %} class="list-item-selector button visible">', '{% if ($$.getItemIconClass($)) { %}', '<span class="{%= $$.getItemIconClass($) %}"></span>', '{% } else { %}', '<img id="list-item-image_{%: $.$key %}" src="{%: $$.getItemIconSource($) %}" alt="{%: $$.getItemIconAlt($) %}" class="icon" />', '{% } %}', '</button>', ]), itemTemplate: new Simplate([ '<h3 data-action="{%= $.action %}">{%: $.title %}</h3>', ]), itemRowContainerTemplate: new Simplate([ '<li data-action="{%= $.action %}" {% if ($.view) { %}data-view="{%= $.view %}"{% } %}>', '{%! $$.itemRowContentTemplate %}', '</li>', ]), // Localization clearLocalStorageTitleText: resource.clearLocalStorageTitleText, clearAuthenticationTitleText: resource.clearAuthenticationTitleText, errorLogTitleText: resource.errorLogTitleText, localStorageClearedText: resource.localStorageClearedText, credentialsClearedText: resource.credentialsClearedText, titleText: resource.titleText, offlineOptionsText: resource.offlineOptionsText, // View Properties id: 'settings', expose: false, enableSearch: false, enablePullToRefresh: false, selectionOnly: true, allowSelection: false, actions: null, actionOrder: [ 'clearAuthentication', 'clearLocalStorage', 'viewErrorLogs', 'viewOfflineOptions', ], createActions: function createActions() { this.actions = { 'clearLocalStorage': { title: this.clearLocalStorageTitleText, cls: 'fa fa-database fa-2x', }, 'clearAuthentication': { title: this.clearAuthenticationTitleText, cls: 'fa fa-unlock fa-2x', }, 'viewErrorLogs': { title: this.errorLogTitleText, cls: 'fa fa-list-alt fa-2x', }, 'viewOfflineOptions': { title: this.offlineOptionsText, cls: 'fa fa-list-alt fa-2x', }, }; }, getItemIconClass: function getItemIconClass(entry) { return entry.cls; }, createIndicatorLayout: function createIndicatorLayout() { return this.itemIndicators || (this.itemIndicators = []); }, viewErrorLogs: function viewErrorLogs() { const view = App.getView('errorlog_list'); if (view) { view.show(); } }, clearLocalStorage: function clearLocalStorage() { if (window.localStorage) { window.localStorage.clear(); } connect.publish('/app/refresh', [{ resourceKind: 'localStorage', }]); alert(this.localStorageClearedText); // eslint-disable-line }, clearAuthentication: function clearAuthentication() { if (window.localStorage) { window.localStorage.removeItem('credentials'); } alert(this.credentialsClearedText); // eslint-disable-line }, viewOfflineOptions: function viewOfflineOptions() { const view = App.getView('offline_options_edit'); if (view) { view.show(); } }, hasMoreData: function hasMoreData() { return false; }, requestData: function requestData() { const list = []; for (let i = 0; i < this.actionOrder.length; i++) { const action = this.actions[this.actionOrder[i]]; if (action) { list.push({ action: this.actionOrder[i], title: action.title, icon: action.icon, cls: action.cls, }); } } this.processData(list); }, init: function init() { this.inherited(arguments); this.createActions(); }, createToolLayout: function createToolLayout() { return this.tools || (this.tools = { tbar: [], }); }, }); lang.setObject('Mobile.SalesLogix.Views.Settings', __class); export default __class;
JavaScript
0
@@ -3885,24 +3885,57 @@ %7D%0A %7D +%0A this.set('listContent', ''); %0A%0A this.p
b8e5b38562b0cce18b0aca5d47af257f2e78ef38
fix @param variable names
src/actions/movies.js
src/actions/movies.js
import 'whatwg-fetch'; import { MOVIES_LOADED, MOVIES_QUERY_CHANGED, } from '../config/constants'; import { startAjaxCall, finishAjaxCall } from './ajax'; /** * Action fired after the movies are loaded via the omdb API * * @export * @param {array} tweets */ export const moviesLoaded = (results) => { return { type: MOVIES_LOADED, results, }; }; /** * Action fired after the movie query has been set/changed * * @export * @param {string} user */ export const moviesQueryChanged = (query) => { return { type: MOVIES_QUERY_CHANGED, query, }; }; /** * Side-load the movie list via redux-thunk action * * @export * @param {string} user */ export const setMoviesQuery = (query) => { return function (dispatch) { dispatch(moviesQueryChanged(query)); dispatch(startAjaxCall()); fetch('//www.omdbapi.com/?s=' + query) .then(function(response) { return response.json(); }).then(function(json) { dispatch(moviesLoaded(json.Search)); dispatch(finishAjaxCall()); }).catch(function(ex) { dispatch(finishAjaxCall()); }); }; };
JavaScript
0.000001
@@ -254,12 +254,13 @@ ay%7D -twee +resul ts%0A @@ -451,36 +451,37 @@ @param %7Bstring%7D +q u -s er +y %0A */%0Aexport cons
7c2c9e45d1ac389c811de1e5dc66628a09501532
Fix saving a slide as a blueprint with an empty name. [IQSLDSH-273]
app/controllers/slideBlueprints.server.controller.js
app/controllers/slideBlueprints.server.controller.js
/*global require, exports, console*/ (function () { 'use strict'; var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), SlideBlueprint = mongoose.model("SlideBlueprint"), lodash = require('lodash'), Promise = require('promise'), NamesAndTagsFilter = require('../services/namesAndTagsFilter'); exports.renderSlide = function (req, res) { res.jsonp(req.slide); }; exports.renderSlides = function (req, res) { res.jsonp(req.slides); }; exports.delete = function (req, res) { var slide = req.slide; slide.remove(function (err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } res.jsonp(slide); }); }; exports.getSlideById = function (req, res, next, slideId) { SlideBlueprint.findOne({"slide._id": slideId}).sort({$natural: -1}).exec(function (err, slide) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } if (!slide) { slide = new SlideBlueprint(); } req.slide = slide; next(); }); }; exports.getSlides = function (req, res) { SlideBlueprint.find({}).exec(function (err, slides) { if (err) { console.log(err); return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } res.jsonp(slides); }); }; exports.storeByName = function (req, res) { var slide = req.slide; slide = lodash.extend(slide, req.body); SlideBlueprint.findOne({"name": req.body.name}).exec(function (err, slide) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } if (slide) { return res.status(400).send({ message: 'Blueprint with the given name already exists.' }); } slide = new SlideBlueprint(); delete req.body._id; slide = lodash.extend(slide, req.body); slide.user = req.user; slide.save(function (err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } res.jsonp(slide); }); }); }; var preparePromiseForFilter = function (select, req, actionOnFind) { var promise = new Promise(function (resolve, reject) { SlideBlueprint.find(select).sort('-created').populate('user', 'displayName').exec(function (err, slideshowsFound) { if (err) { reject(err); return; } actionOnFind(slideshowsFound); resolve(); }); }); return promise; }; exports.getFilteredNamesAndTags = function (req, res) { NamesAndTagsFilter.getFilteredNamesAndTags(req, preparePromiseForFilter, function (filterResult) { res.jsonp(filterResult); }, function (error) { return res.status(400).send({ message: errorHandler.getErrorMessage(error) }); }); }; exports.getSlideByFilter = function (req, res) { NamesAndTagsFilter.filter(req, SlideBlueprint, null, function (filterResult) { res.jsonp(filterResult); }, function (error) { console.log(error); return res.status(400).send({ message: errorHandler.getErrorMessage(error) }); }); }; }());
JavaScript
0
@@ -1845,32 +1845,193 @@ ide, req.body);%0A + if (!slide.name) %7B%0A return res.status(400).send(%7B%0A message: 'Please enter a name for the blueprint.'%0A %7D);%0A %7D%0A SlideBlu
a02427f953fcbca41df0752e456fd0335f53240c
return entities into game
client/js/game.js
client/js/game.js
/* global _ */ define(['entities/player', 'gameclient', 'entityfactory', 'map'], function (Player, GameClient, EntityFactory, Map) { var Game = Class.extend({ map: new Map(), init: function (renderer) { this.renderer = renderer; this.keybindings['w'] = this.moveUp.bind(this); this.keybindings['s'] = this.moveDown.bind(this); this.keybindings['a'] = this.moveLeft.bind(this); this.keybindings['d'] = this.moveRight.bind(this); }, run: function () { this.camera = this.renderer.camera; this.tick(); }, tick: function () { this.renderer.render(this.stage); this._handleKeyboard(); requestAnimFrame(this.tick.bind(this)); }, _handleKeyboard: function () { var self = this; _.each(this.keyboard, function (pressed, key) { if (pressed) self.keybindings[key](); }); }, connect: function () { var self = this; this.map.onMapLoaded(function () { _.each(self.map.getDisplayObjects(), function (displayObject) { self.stage.addChild(displayObject); }); }); this.client = new GameClient(this.host, this.port); this.client.onWelcome(function (data) { self.playerId = data.playerId; }); this.client.onMap(function (mapinfo) { self.map.load(mapinfo); }); this.client.onEntityList(function (entitieslist) { var entities = {}; /*_.each(entitieslist, function (entity_info) { var id = entity_info.id; var entity = id in self.entities ? self.entities[id] : entity = EntityFactory.createEntity(entity_info, id); if (entity.animated) self.stage.addChild(entity.movieclip); entity.update(entity_info); entities[id] = entity; });*/ self.entities = entities; }); this.client.connect(); }, moveCursor: function () { //var angle = 0; //return this.client.sendAngle(angle); }, moveUp: function () { return this.client.sendAction('up'); }, moveDown: function () { return this.client.sendAction('down'); }, moveLeft: function () { return this.client.sendAction('left'); }, moveRight: function () { return this.client.sendAction('right'); }, stage: new PIXI.Stage(0x000000), entities: [], keyboard: {}, keybindings: {}, mouse: { x: 0, y: 0 }, host: window.location.host, playerId: null }); return Game; });
JavaScript
0.000917
@@ -1329,18 +1329,16 @@ %7B%7D;%0A%09%09%09%09 -/* _.each(e @@ -1664,18 +1664,16 @@ %0A%09%09%09%09%7D); -*/ %0A%09%09%09%09sel
ebaef33953a98ed01d2c95a2171f7439ea5619f5
Send browser credentials with fetch instead of hard coding them
client/src/api.js
client/src/api.js
export default { fetch(url) { return fetch(url, { headers: { accept: "application/json", authorization: "Basic " + btoa("nick:Nicholson") } }).then(response => response.json()) .then(function(data) { console.log(data); return data; }) } }
JavaScript
0
@@ -46,16 +46,47 @@ (url, %7B%0A +%09%09%09credentials: %22same-origin%22,%0A %09%09%09heade @@ -125,62 +125,8 @@ son%22 -,%0A%09%09%09%09authorization: %22Basic %22 + btoa(%22nick:Nicholson%22) %0A%09%09%09
e134a7afe8647c6f5d8c057309869a6b595a740d
add scrolling animation
static/js/init.js
static/js/init.js
(function($){ $(function(){ $('.button-collapse').sideNav(); $('.parallax').parallax(); }); // end of document ready })(jQuery); // end of jQuery name space
JavaScript
0.000001
@@ -91,16 +91,456 @@ allax(); +%0A $('a%5Bhref*=#%5D').click(function() %7B%0A%09%09if (location.pathname.replace(/%5E%5C//,'') == this.pathname.replace(/%5E%5C//,'') && location.hostname == this.hostname) %7B%0A%09%09%09var $target = $(this.hash);%0A%09%09%09$target = $target.length && $target %7C%7C $('%5Bname=' + this.hash.slice(1) +'%5D');%0A%09%09%09 if ($target.length) %7B%0A%09%09%09 %09var targetOffset = $target.offset().top - 100;%0A%09%09%09%09$('html,body').animate(%7BscrollTop: targetOffset%7D, 1000);%0A%09%09%09%09return false;%0A%09%09%09%7D%0A%09%09%7D%0A%09%7D); %0A%0A %7D);
6d549713f81ebc9b80aa605d4fb0a4b9f8ebdeae
tweak scroll speed
static/js/main.js
static/js/main.js
var scroll_start = 0; var startchange, offset; var animationAdded = false; var initiallyRun = false; function updateNav() { var nav = $("nav") if (initiallyRun && !animationAdded) { console.log("ok") animationAdded = true; nav.addClass("nav-animate") } initiallyRun = true; scroll_start = $(this).scrollTop(); if(scroll_start > offset) { nav.addClass("teal"); nav.removeClass("transparent"); } else { nav.addClass("transparent"); nav.removeClass("teal"); } } $(document).ready(function(){ $(".button-collapse").sideNav(); $('.parallax').parallax(); $('#location-map') .mousedown( function(){ $(this).find('iframe').addClass('clicked') } ) .mouseleave( function(){ $(this).find('iframe').removeClass('clicked') } ); startchange = $('#cover-img'); offset = startchange.offset().top - startchange.height() / 4; $(document).scroll(updateNav); updateNav(); $('nav a').on('click', function(e) { e.preventDefault(); var target = this.hash; $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top }, 250, 'swing', function() { window.location.hash = target; }); }); })
JavaScript
0.000001
@@ -1140,9 +1140,9 @@ %7D, -2 +3 50,
165afc20ebc35aafedce81aa2d1d0c4521c3fe3a
make the analyzer more robust.
server/analyzer.js
server/analyzer.js
//#!/bin/env node /* Copyright 2014 Krzysztof Daniel 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.*/ function composeMissingComponentsMessage() { return { type : 'panel-warning', title : 'Missing components', message : 'Your map appears to be empty. I have nothing to analyze.' }; } function composeMissingNamesMessage() { return { type : 'panel-danger', title : 'Missing names', message : 'Fill all the component names first. I cannot give you feedback about anonymous components.' }; } function composePotentialDisruption(componentName) { var message = 'Your component \'' + componentName + '\' appears to be in a sweet spot. Consider delivering it as a utility product'; return { type : 'panel-success', title : 'Potential disruption', message : message }; } function composeBewareDisruption(componentName) { var message = 'Your component \'' + componentName + '\' appears to be in a sweet spot where delivering it as a utility product is possible, but you may suffer from inertia, and it is likely that YOU will be disrupted.'; return { type : 'panel-warning', title : 'Potential disruption', message : message }; } function composeLostChance(componentName) { var message = 'Your component \'' + componentName + '\' seems to be in a pretty advanced state but it was not offered to anyone although it should be. Consider abandoning it and adopting one of the market alternatives.' + 'There is a small chance your competition made a mistake and did not provide this as a utility product. If that is the case, consider going into that business right now.'; return { type : 'panel-info', title : 'Lost chance', message : message }; } function composeCreatePlayingField(componentName){ var message = 'Your rely on \'' + componentName + '\' which is pretty mature in evolution and should be delivered as a utility product soon.' + 'Consider looking for new suppliers as it may save you a lot of bucks.'; return { type : 'panel-success', title : 'Playing field creation opportunity', message : message }; } function analyse(map) { var result = []; if(map.history[0].nodes.length == 0){ result.push(composeMissingComponentsMessage()); console.error(result); return result; } var allnames = true; for(var i = 0; i < map.history[0].nodes.length; i++){ var currentNode = map.history[0].nodes[i]; currentNode.positionX = parseFloat(currentNode.positionX); currentNode.external = JSON.parse(currentNode.external); currentNode.userneed = JSON.parse(currentNode.userneed); if(currentNode.name == ""){ allnames = false; break; } // potential disruption if ((currentNode.positionX > 0.5) && (currentNode.positionX < 0.75) && !currentNode.external && !currentNode.userneed) { result.push(composePotentialDisruption(currentNode.name)); } if ((currentNode.positionX > 0.5) && (currentNode.positionX < 0.8) && !currentNode.external && currentNode.userneed) { result.push(composeBewareDisruption(currentNode.name)); } // reinvented wheel if ((currentNode.positionX > 0.75) && !currentNode.external && !currentNode.userneed) { result.push(composeLostChance(currentNode.name)); } // create playing field if ((currentNode.positionX > 0.5) && (currentNode.positionX < 0.75) && currentNode.external) { result.push(composeCreatePlayingField(currentNode.name)); } } if(!allnames){ result.push(composeMissingNamesMessage()); console.error(result); return result; } return result; } exports.analyse = analyse;
JavaScript
0.000001
@@ -2943,27 +2943,26 @@ ernal = -JSON.parse( +'true' == currentN @@ -2973,17 +2973,31 @@ external -) + ? true : false ;%0A%09%09curr @@ -3019,19 +3019,18 @@ d = -JSON.parse( +'true' == curr @@ -3045,17 +3045,31 @@ userneed -) + ? true : false ;%0A%09%09%0A%09%09i
281a899a87d6c49910978e611cbbb09e8834e600
Stop using deprecated assert.equal
test/index.js
test/index.js
var nocache = require('..') var assert = require('assert') var connect = require('connect') var request = require('supertest') describe('nocache', function () { it('sets headers properly', function () { var app = connect() app.use(function (req, res, next) { res.setHeader('ETag', 'abc123') next() }) app.use(nocache()) app.use(function (req, res) { res.end('Hello world!') }) return request(app).get('/') .expect('Surrogate-Control', 'no-store') .expect('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate') .expect('Pragma', 'no-cache') .expect('Expires', '0') .expect('ETag', 'abc123') .expect('Hello world!') }) it('names its function and middleware', function () { assert.equal(nocache.name, 'nocache') assert.equal(nocache().name, 'nocache') }) })
JavaScript
0.000004
@@ -778,33 +778,39 @@ () %7B%0A assert. -e +strictE qual(nocache.nam @@ -834,17 +834,23 @@ assert. -e +strictE qual(noc
b0eb98e1e744d8723f05634757e2f970a53924fc
Remove duplicate test
test/index.js
test/index.js
var chai = require('chai'), expect = chai.expect, hiscore = require('../index').hiscore, nock = require('nock'); describe('Mocked Hiscore API', function () { this.slow(100); var createNock = function (player, mode) { if(mode === undefined) { mode = ''; } return nock('http://services.runescape.com') .get('/m=hiscore_oldschool' + mode + '/index_lite.ws') .query({player: player}); }; it('can download standard hiscores', function (done) { var fakeApi = createNock('zezima').replyWithFile(200, __dirname + '/resources/hiscore.csv'); hiscore.standard('zezima', function (err, data) { expect(err).to.be.a('null'); expect(data).to.not.be.a('null'); fakeApi.isDone(); done(); }); }); it('can download ironman hiscores', function(done) { var fakeApi = createNock('zezima', '_ironman').replyWithFile(200, __dirname + '/resources/hiscore.csv'); hiscore.ironman('zezima', function (err, data) { expect(err).to.be.a('null'); expect(data).to.not.be.a('null'); fakeApi.isDone(); done(); }); }); it('can download ultimate ironman hiscores', function(done) { var fakeApi = createNock('zezima', '_ultimate').replyWithFile(200, __dirname + '/resources/hiscore.csv'); hiscore.ultimate('zezima', function (err, data) { expect(err).to.be.a('null'); expect(data).to.not.be.a('null'); fakeApi.isDone(); done(); }); }); it('can download deadman hiscores', function(done) { var fakeApi = createNock('zezima', '_deadman').replyWithFile(200, __dirname + '/resources/hiscore.csv'); hiscore.deadman('zezima', function (err, data) { expect(err).to.be.a('null'); expect(data).to.not.be.a('null'); fakeApi.isDone(); done(); }); }); it('can download hiscores when username has a space', function (done) { var fakeApi = createNock('zezima_fan').replyWithFile(200, __dirname + '/resources/hiscore.csv'); hiscore.standard('zezima fan', function (err, data) { expect(err).to.be.a('null'); expect(data).to.not.be.a('null'); fakeApi.isDone(); done(); }); }); it('parses hiscore data correctly', function (done) { var fakeApi = createNock('zezima').replyWithFile(200, __dirname + '/resources/hiscore.csv'); hiscore.standard('zezima', function (err, data) { expect(err).to.be.a('null'); expect(data['overall'].level, 'overall level').to.be.a('number'); expect(data['overall'].level, 'overall level').to.equal(1474); expect(data['overall'].rank, 'overall rank').to.be.a('number'); expect(data['overall'].rank, 'overall rank').to.equal(75593); expect(data['overall'].xp, 'overall xp').to.be.a('number'); expect(data['overall'].xp, 'overall xp').to.equal(32472290); expect(data['woodcutting'].level, 'woodcutting level').to.be.a('number'); expect(data['woodcutting'].level, 'woodcutting level').to.equal(96); expect(data['woodcutting'].rank, 'woodcutting rank').to.be.a('number'); expect(data['woodcutting'].rank, 'woodcutting rank').to.equal(5866); expect(data['woodcutting'].xp, 'woodcutting xp').to.be.a('number'); expect(data['woodcutting'].xp, 'woodcutting xp').to.equal(9938130); fakeApi.isDone(); done(); }); }); it('throws an error when username does not exist', function (done) { var fakeApi = createNock('zezima').reply(404); hiscore.standard('zezima', function (err, data) { expect(data).to.be.a('undefined'); expect(err.message).to.equal('Player not found: zezima'); fakeApi.isDone(); done(); }); }); it('does not blow up if server errors out', function (done) { var fakeApi = createNock('zezima').replyWithError('oh noes!'); hiscore.standard('zezima', function (err, data) { expect(data).to.be.a('undefined'); expect(err.message).to.contain('unknown error occurred'); expect(err.message).to.contain('retrieve hiscores for zezima'); expect(err.message).to.contain('Try again soon'); fakeApi.isDone(); done(); }); }); it('does not blow up if server responds with nonsense', function (done) { var fakeApi = createNock('zezima').reply(200, 'this was unexpected'); hiscore.standard('zezima', function (err, data) { expect(data).to.be.a('undefined'); expect(err.message).to.contain('unknown error occurred while parsing'); expect(err.message).to.contain('Try again soon'); fakeApi.isDone(); done(); }); }); it('can communicate with Jagex servers', function (done) { this.slow(1000); nock.cleanAll(); hiscore.standard('king_karthas', function (err, data) { expect(err).to.be.a('null'); expect(data).to.not.be.a('null'); done(); }); }); it('can communicate with Jagex servers', function (done) { this.slow(1000); nock.cleanAll(); hiscore.standard('king_karthas', function (err, data) { expect(err).to.be.a('null'); expect(data).to.not.be.a('null'); done(); }); }); });
JavaScript
0.000014
@@ -5357,312 +5357,8 @@ );%0A%0A - it('can communicate with Jagex servers', function (done) %7B%0A this.slow(1000);%0A nock.cleanAll();%0A hiscore.standard('king_karthas', function (err, data) %7B%0A expect(err).to.be.a('null');%0A expect(data).to.not.be.a('null');%0A done();%0A %7D);%0A %7D);%0A %7D);%0A
4c76fd6904501979db62db885e86358d19866eb0
add onchange for autosave capabilities
addon/components/form-for/component.js
addon/components/form-for/component.js
import Component from '@ember/component'; import { set, get, computed } from '@ember/object'; import { tryInvoke } from '@ember/utils'; import RSVP from 'rsvp'; import Changeset from 'ember-changeset'; import layout from './template'; export default Component.extend({ layout, tagName: 'form', multiple: false, novalidate: true, attributeBindings: ['novalidate'], changeset: computed('model', { get() { return new Changeset(get(this, 'model') || {}); } }), submit(evt) { if (evt) { evt.preventDefault(); evt.stopPropagation(); } let promises = []; let model = get(this, 'model'); let changeset = get(this, 'changeset'); let changes = get(this, 'changeset').snapshot().changes; let isDirty = changeset.get('isDirty') || model.get('isDeleted'); if (isDirty && (model == null || get(model, 'isNew'))) { return get(this, 'onsubmit')(model, changes).then(() => { return RSVP.all(get(this, 'nestedForms').map(function (form) { return form.submit(evt); })); }); } else { promises = get(this, 'nestedForms').map(function (form) { return form.submit(evt); }); if (isDirty) { promises.push(get(this, 'onsubmit')(model, changes)); } } return RSVP.all(promises); }, init() { this._super(...arguments); set(this, 'nestedForms', []); tryInvoke(this, 'oninit', [this]); }, register(form) { get(this, 'nestedForms').push(form); }, actions: { onchange(model, field, value) { let [fieldName, ...path] = field.split('.'); if (path.length) { let copy = Object.assign({}, get(model, fieldName)); set(copy, path.join('.'), value); model.set(fieldName, copy); } else { model.set(field, value); } }, onsubmit() { return this.submit().then(() => { get(this, 'onsaved')(get(this, 'model')); }); } } }).reopenClass({ positionalParams: ['model'] });
JavaScript
0
@@ -1826,24 +1826,150 @@ ue);%0A %7D +%0A%0A if (get(this, 'onchange')) %7B%0A get(this, 'onchange')(() =%3E %7B%0A return this.submit();%0A %7D);%0A %7D %0A %7D,%0A%0A
fb50c79eab6a9ed3c275d6492eee9c4afd5cbbe7
Update tests
test/index.js
test/index.js
var test = require('tape'); var url = require('url'); var matrixUrl = require('../'); var defaults = { href: 'http://matrix.dev/_admin' }; test('Basic functionality', function(t) { var search = [ '?SQ_BACKEND_PAGE=main', '&backend_section=am', '&am_section=edit_asset', '&assetid=', '&asset_ei_screen=', '&ignore_frames=1' ].join(''); t.equal(matrixUrl(defaults.href), defaults.href + search, 'URL as String'); t.equal(matrixUrl(url.parse(defaults.href)), defaults.href + search, 'URL Object'); t.end(); }); test('Screen value shorthand', function(t) { var search = [ '?SQ_BACKEND_PAGE=main', '&backend_section=am', '&am_section=edit_asset', '&assetid=3', '&asset_ei_screen=', '&ignore_frames=1', '&log_manager_3_direct_connection=true', '&log_manager_3_action=monitor', '&log_manager_3_log=error', '&rand=', '&log_manager_3_num_lines=25', '&log_manager_3_offset=' ].join(''); defaults.screen = 'log'; t.equal(matrixUrl(defaults), defaults.href + search, 'Default log screen'); delete defaults.screen; t.end(); });
JavaScript
0.000001
@@ -25,34 +25,8 @@ ');%0A -var url = require('url');%0A var @@ -58,24 +58,24 @@ );%0A%0Avar -defaults +DEFAULTS = %7B%0A h @@ -104,17 +104,139 @@ v/_admin -' +/'%0A%7D;%0A%0Avar testRunner = function testRunner(test) %7B%0A this.equal(test.test, DEFAULTS.href + test.search, test.description); %0A%7D;%0A%0Ates @@ -268,36 +268,41 @@ function(t) %7B%0A -var +DEFAULTS. search = %5B%0A ' @@ -454,181 +454,624 @@ %0A %5D -.join('');%0A%0A t.equal(matrixUrl(defaults.href), defaults.href + search, 'URL as String');%0A t.equal(matrixUrl(url.parse(defaults.href)), defaults.href + search, 'URL Object' +;%0A var tests = %5B%0A %7B%0A description: 'URL as String',%0A search: DEFAULTS.search.join(''),%0A test: matrixUrl(DEFAULTS.href)%0A %7D,%0A %7B%0A description: 'URL Object',%0A search: DEFAULTS.search.join(''),%0A test: matrixUrl(DEFAULTS)%0A %7D,%0A %7B%0A description: 'Setting assetId',%0A search: %5B%0A '?SQ_BACKEND_PAGE=main',%0A '&backend_section=am',%0A '&am_section=edit_asset',%0A '&assetid=3',%0A '&asset_ei_screen=',%0A '&ignore_frames=1'%0A %5D.join(''),%0A test: matrixUrl(%7B href: DEFAULTS.href, assetId: 3 %7D)%0A %7D%0A %5D;%0A%0A tests.forEach(testRunner, t );%0A @@ -1132,20 +1132,25 @@ (t) %7B%0A -var +DEFAULTS. search = @@ -1504,149 +1504,1141 @@ %0A %5D -.join('');%0A%0A defaults.screen = +;%0A var tests = %5B%0A %7B%0A description: 'Default log screen',%0A search: DEFAULTS.search.join(''),%0A test: matrixUrl(%7B%0A href: DEFAULTS.href,%0A screen: 'log'%0A %7D)%0A %7D,%0A %7B%0A description: 'Log screen with settings',%0A search: %5B%0A '?SQ_BACKEND_PAGE=main',%0A '&backend_section=am',%0A '&am_section=edit_asset',%0A '&assetid=3',%0A '&asset_ei_screen=',%0A '&ignore_frames=1',%0A ' +& log -';%0A t.equal(matrixUrl(defaults), defaults.href + search, 'Default log screen');%0A delete defaults.screen +_manager_3_direct_connection=true',%0A '&log_manager_3_action=monitor',%0A '&log_manager_3_log=system',%0A '&rand=123456',%0A '&log_manager_3_num_lines=1000',%0A '&log_manager_3_offset=654321'%0A %5D.join(''),%0A test: matrixUrl(%7B%0A href: DEFAULTS.href,%0A screen: 'log',%0A level: 'system',%0A rand: '123456',%0A lines: '1000',%0A offset: '654321'%0A %7D)%0A %7D,%0A %7B%0A description: 'Cannot override log screen assetId',%0A search: DEFAULTS.search.join(''),%0A test: matrixUrl(%7B%0A href: DEFAULTS.href,%0A screen: 'log',%0A assetId: '23'%0A %7D)%0A %7D,%0A %5D;%0A%0A tests.forEach(testRunner, t) ;%0A
d3e7e0d56cb5eb8732cfa12f07612fe2729906f2
Fix ava
test/index.js
test/index.js
import test from 'ava'; import plugin from '../postcss-rem-phi-units'; import postcss from 'postcss'; import { readFileSync } from 'fs'; test('Settingless units', async t => { postcss(plugin) .process(readFileSync('in.css')) .then(result => t.same(result.css, readFileSync('expected.css', 'utf8')); ); });
JavaScript
0.000778
@@ -299,17 +299,16 @@ 'utf8')) -; %0A%09%09);%0A%7D)
19e040de15b268ad23d5013941a84f08a699d42a
add unit tect create
test/index.js
test/index.js
function test(name, path) { describe(name, function() { require(path); }) } describe('#dl-module', function(done) { this.timeout(2 * 60000); // Auth // test('@auth/account-manager', './auth/account-manager-test'); // test('@auth/role-manager', './auth/role-manager-test'); //Master // test('@master/uom-manager', './master/uom-manager-test'); // test('@master/supplier-manager', './master/supplier-manager-test'); // test('@master/buyer-manager', './master/buyer-manager-test'); // test('@master/product-manager', './master/product-manager-test'); // test('@master/division-manager', './master/division-manager-test'); // test('@master/unit-manager', './master/unit-manager-test'); // test('@master/category-manager', './master/category-manager-test'); // test('@master/currency-manager', './master/currency-manager-test'); // test('@master/vat-manager', './master/vat-manager-test'); // test('@master/budget-manager', './master/budget-manager-test'); test('@master/machine-manager', './master/machine-manager-test'); // //Purchasing // test('@purchasing/purchase-order-manager', './purchasing/purchase-order-manager-test'); // test('@purchasing/purchase-order-external-manager', './purchasing/purchase-order-external-manager-test'); // test('@purchasing/delivery-order-manager', './purchasing/delivery-order-manager-test'); // test('@purchasing/unit-receipt-note', './purchasing/unit-receipt-note-manager-test'); // test('@purchasing/purchase-request-manager', './purchasing/purchase-request-manager-test'); // test('@purchasing/unit-payment-price-correction-note', './purchasing/unit-payment-price-correction-note-manager-test'); // test('@purchasing/unit-payment-order', './purchasing/unit-payment-order-test'); test('@purchasing/purchase-request/create', './purchasing/purchase-request/create'); test('@purchasing/purchase-request/post', './purchasing/purchase-request/post'); test('@purchasing/purchase-order/create', './purchasing/purchase-order/create'); test('@purchasing/purchase-order/update', './purchasing/purchase-order/update'); })
JavaScript
0
@@ -296,24 +296,29 @@ ger-test');%0A + %0A //Master @@ -317,27 +317,24 @@ //Master%0A - // test('@mast @@ -375,35 +375,32 @@ ager-test');%0A - // test('@master/s @@ -447,35 +447,32 @@ ager-test');%0A - // test('@master/b @@ -513,35 +513,32 @@ ager-test');%0A - // test('@master/p @@ -583,35 +583,32 @@ ager-test');%0A - // test('@master/d @@ -655,35 +655,32 @@ ager-test');%0A - // test('@master/u @@ -719,35 +719,32 @@ ager-test');%0A - // test('@master/c @@ -791,35 +791,32 @@ ager-test');%0A - // test('@master/c @@ -863,35 +863,32 @@ ager-test');%0A - // test('@master/v @@ -925,35 +925,32 @@ ager-test');%0A - // test('@master/b @@ -1076,24 +1076,125 @@ -// //Purchasing +%0A //Purchasing %0A // test('@purchasing/purchase-request-manager', './purchasing/purchase-request-manager-test'); %0A @@ -1590,107 +1590,8 @@ ');%0A - // test('@purchasing/purchase-request-manager', './purchasing/purchase-request-manager-test');%0A @@ -2145,11 +2145,639 @@ date');%0A + test('@purchasing/purchase-order-external/create', './purchasing/purchase-order-external/create');%0A test('@purchasing/delivery-order/create', './purchasing/delivery-order/create');%0A test('@purchasing/unit-receipt-note/create', './purchasing/unit-receipt-note/create');%0A test('@purchasing/unit-payment-order/create', './purchasing/unit-payment-order/create');%0A test('@purchasing/unit-payment-price-correction-note/create', './purchasing/unit-payment-price-correction-note/create');%0A test('@purchasing/unit-payment-quantity-correction-note/create', './purchasing/unit-payment-quantity-correction-note/create');%0A %7D)%0A
38755eaa8eabc75088546fab9e7285ca9fd1eda2
Test 'hotel rm' failures
test/index.js
test/index.js
process.env.HOME = `${__dirname}/home` process.env.USERPROFILE = `${__dirname}/home` let assert = require('assert') let cp = require('child_process') let fs = require('fs') let path = require('path') let supertest = require('supertest') let untildify = require('untildify') let rmrf = require('rimraf') let pkg = require('../package.json') let timeout = process.env.TRAVIS ? 10000 : 5000 // Used to give some time to the system and commands function wait (done) { setTimeout(done, timeout) } function hotel (cmd) { // Execute hotel cmd let out = cp.execSync(`node ${__dirname}/../${pkg.bin} ${cmd}`, { cwd: `${__dirname}/app` }).toString() // Log output // .replace() used to enhance tests readability console.log(out .replace(/\n /g, '\n ') .replace(/\n$/, '')) // Return output return out } let request = supertest(`http://localhost:2000`) describe('hotel', function () { this.timeout(timeout + 1000) before((done) => { hotel('stop') // Just in case rmrf.sync(untildify('~/.hotel')) wait(done) }) after(() => hotel('stop')) describe('$ hotel start', () => { before(done => { hotel('start') wait(done) }) it('should start daemon', done => { request.get('/').expect(200, done) }) }) describe('app$ hotel add "node index.js"', () => { before(done => { hotel('add "node index.js"') wait(done) }) it('should create a redirection from /app to app server', done => { request .get('/app') .expect(302, (err, res) => { if (err) throw err // Test redirection supertest(res.header.location) .get('/') .expect(200, done) }) }) }) describe('app$ hotel add -n name -o output.log -e PATH "node index.js"', () => { before(done => { hotel('add -n name -o output.log -e PATH "node index.js"') wait(done) }) it('should create a redirection from /name to app server', done => { request .get('/name') .expect(302, (err, res) => { if (err) throw err // Test redirection supertest(res.header.location) .get('/') // Server is configured to return PATH, // in order to test that PATH was passed to the server .expect(new RegExp(process.env.PATH)) .expect(200, done) }) }) it('should use the same hostname to redirect', done => { supertest(`http://127.0.0.1:2000`) .get('/name') .expect('location', /http:\/\/127.0.0.1/) .expect(302, done) }) it('should write output to output.log', () => { let log = fs.readFileSync(`${__dirname}/app/output.log`, 'utf-8') assert(log.includes('Server running')) }) }) describe('app$ hotel ls', () => { it('should return server list', () => { assert(hotel('ls').includes('app')) }) }) describe('app$ hotel rm', () => { before(done => { hotel('rm') wait(done) }) it('should remove server', done => { request .get('/app') .expect(302) .expect('location', '/', done) }) }) describe('$ hotel stop', () => { before((done) => { hotel('stop') wait(done) }) it('should stop daemon', (done) => { request.get('/').end((err) => { if (err) return done() throw new Error('Daemon should not be accessible') }) }) }) })
JavaScript
0.998208
@@ -547,32 +547,15 @@ let -out = cp.execSync(%60node +bin = %60 $%7B__ @@ -580,16 +580,64 @@ bin%7D +%60%0A let proc = cp.spawnSync('sh', %5B'-c', %60$%7Bbin%7D $%7Bcmd%7D%60 , %7B%0A @@ -632,16 +632,17 @@ $%7Bcmd%7D%60 +%5D , %7B%0A @@ -669,16 +669,43 @@ pp%60%0A %7D) +%0A %0A let out = proc.stdout .toStrin @@ -3253,32 +3253,212 @@ )%0A %7D)%0A%0A %7D)%0A%0A + describe('app$ hotel rm non-existent-app', () =%3E %7B%0A%0A it('should print an error', () =%3E %7B%0A assert(hotel('rm non-existent-app').includes('unable to delete'))%0A %7D)%0A%0A %7D)%0A%0A describe('$ ho
ea3ca815850cdf66da009b3b57bed985bb2ae2cd
simplify tests
test/index.js
test/index.js
var Hook = require('../'); var Path = require('path'); var Lab = require('lab'); var lab = exports.lab = Lab.script(); var expect = Lab.expect; var describe = lab.experiment; var it = lab.test; var internals = {}; internals.getMatcher = function () { var sep = new RegExp(Path.sep, 'g'); var path = Path.join.apply(null, arguments).replace(sep, '\\' + Path.sep); return new RegExp(path + '$'); }; describe('exports', function () { it('can find a git root', function (done) { var root = Hook.findGitRoot(__dirname); expect(root).to.be.a('string'); expect(root).to.match(internals.getMatcher(__dirname)); done(); }); it('can find a git root from higher up', function (done) { var root = Hook.findGitRoot(Path.join(__dirname, 'projects')); expect(root).to.be.a('string'); expect(root).to.match(internals.getMatcher(__dirname)); done(); }); it('can find a project root', function (done) { var root = Hook.findProjectRoot(__dirname); expect(root).to.be.a('string'); expect(root).to.match(internals.getMatcher(__dirname)); done(); }); it('can find a project root from higher up', function (done) { var root = Hook.findProjectRoot(Path.join(__dirname, 'projects', 'project6', 'node_modules', 'nope')); expect(root).to.be.a('string'); expect(root).to.match(internals.getMatcher(__dirname, 'projects', 'project6')); done(); }); it('can find projects', function (done) { var projects = Hook.findProjects(Path.join(__dirname, 'projects')); expect(projects).to.be.an('array'); expect(projects).to.have.length(4); expect(projects).to.contain(Path.join(__dirname, 'projects', 'project1')); expect(projects).to.contain(Path.join(__dirname, 'projects', 'project2')); expect(projects).to.contain(Path.join(__dirname, 'projects', 'project3', 'api')); expect(projects).to.contain(Path.join(__dirname, 'projects', 'project4', 'even', 'deeper', 'thing')); done(); }); });
JavaScript
0.999411
@@ -610,34 +610,13 @@ .to. -match(internals.getMatcher +equal (__d @@ -614,33 +614,32 @@ equal(__dirname) -) ;%0A done() @@ -852,34 +852,13 @@ .to. -match(internals.getMatcher +equal (__d @@ -856,33 +856,32 @@ equal(__dirname) -) ;%0A done() @@ -1064,34 +1064,13 @@ .to. -match(internals.getMatcher +equal (__d @@ -1076,17 +1076,16 @@ dirname) -) ;%0A @@ -1350,34 +1350,23 @@ .to. -match(internals.getMatcher +equal(Path.join (__d
dbeee6df71d4f8609ab8cd8eaa13e58eed0df056
Fix typo
test/index.js
test/index.js
import test from 'ava' import rollup from 'rollup' import fs from 'fs' import { join } from 'path' import riot from '../dist/rollup-plugin-riot.cjs.js' const fixturesDir = join(__dirname, 'fixtures'), expectDir = join(__dirname, 'expect'), expected = name => fs.readFileSync(join(expectDir, name), 'utf8').trim(), rollupRiot = (filename, options = {}) => rollup.rollup({ entry: join(fixturesDir, filename), external: ['riot'], plugins: [riot(options)] }) test('single tag', t => rollupRiot('single.js') .then(b => { t.is(b.generate().code, expected('single.js')) })) test('multiple tag', t => rollupRiot('multiple.js') .then(b => { t.is(b.generate().code, expected('multiple.js')) })) test('multiple tag in single file', t => rollupRiot('multiple2.js') .then(b => { t.is(b.generate().code, expected('multiple2.js')) })) test('tag with another extension', t => rollupRiot('another-ext.js', { ext: 'html' }) .then(b => { t.is(b.generate().code, expected('another-ext.js')) })) test('skip js', t => rollupRiot('skip.js', { skip: ['css'] }) .then(b => { t.is(b.generate().code, expected('skip.js')) }))
JavaScript
0.999999
@@ -1053,17 +1053,18 @@ t('skip -j +cs s', t =%3E
75ab9bdf4416370d2c3f453506e2430829060695
Fix broken assert
test/index.js
test/index.js
/* global describe it beforeEach */ /* eslint no-new-wrappers: 0 */ 'use strict'; var assert = require('assert'); var keys = require('keys'); var sinon = require('sinon'); var each = require('../'); // TODO: Tighten up these tests, remove duplicates describe('each', function() { var identity; beforeEach(function() { identity = sinon.spy(function(val) { return val; }); }); it('should be a function', function() { assert.equal(typeof each, 'function'); }); it('should have an arity of 2', function() { assert(each.length, 2); }); it('should pass `iterator` the value, index, and collection', function() { var elems = ['zero', 'one', 'two']; each(identity, elems); assert(identity.calledWithExactly('zero', 0, elems)); assert(identity.calledWithExactly('one', 1, elems)); assert(identity.calledWithExactly('two', 2, elems)); }); it('should iterate in left-to-right order', function() { var elems = [1, 0, 7, 14]; each(identity, elems); assert(identity.firstCall.calledWithExactly(1, 0, elems)); assert(identity.secondCall.calledWithExactly(0, 1, elems)); assert(identity.thirdCall.calledWithExactly(7, 2, elems)); assert(identity.lastCall.calledWithExactly(14, 3, elems)); }); it('should perform an action on each element', function() { each(identity, [5, 4, 3, 2, 1]); assert.equal(identity.callCount, 5); assert(identity.calledWith(5)); assert(identity.calledWith(4)); assert(identity.calledWith(3)); assert(identity.calledWith(2)); assert(identity.calledWith(1)); }); it('should permit mutation of the input collection', function() { var elems = [5, 4, 3, 2, 1]; each(function(val, i, coll) { coll[i] = 'omg'; }, elems); assert.deepEqual(elems, ['omg', 'omg', 'omg', 'omg', 'omg']); }); it('should exit early when the provided callback returns `false`', function() { each(identity, [1, 2, 3, false, 4]); assert.equal(identity.callCount, 4); assert(identity.calledWith(1)); assert(identity.calledWith(2)); assert(identity.calledWith(3)); assert(identity.calledWith(false)); }); it('should return `undefined`', function() { assert(each(identity, [1, 2, 3]) === undefined); }); it('should work on arrays', function() { var elems = ['a', 'b', 'c', 'd']; each(identity, elems); assert(identity.firstCall.calledWithExactly('a', 0, elems)); assert(identity.secondCall.calledWithExactly('b', 1, elems)); assert(identity.thirdCall.calledWithExactly('c', 2, elems)); assert(identity.lastCall.calledWithExactly('d', 3, elems)); }); it('should work on objects (with no guarantee of iteration order)', function() { var elems = { a: 1, b: 2, c: 3 }; // Compensate for object iteration being platform-specific by getting // this platform's iteration order var iter = keys(elems); each(identity, elems); assert(identity.firstCall.calledWithExactly(elems[iter[0]], iter[0], elems)); assert(identity.secondCall.calledWithExactly(elems[iter[1]], iter[1], elems)); assert(identity.thirdCall.calledWithExactly(elems[iter[2]], iter[2], elems)); }); it('should work on strings', function() { var string = 'tim'; each(identity, string); assert(identity.firstCall.calledWithExactly(string[0], 0, string)); assert(identity.secondCall.calledWithExactly(string[1], 1, string)); assert(identity.thirdCall.calledWithExactly(string[2], 2, string)); }); it('should work on string objects', function() { var string = new String('tim'); each(identity, string); assert(identity.firstCall.calledWithExactly(string[0], 0, string)); assert(identity.secondCall.calledWithExactly(string[1], 1, string)); assert(identity.thirdCall.calledWithExactly(string[2], 2, string)); }); it('should ignore inherited properties', function() { var parent = { enchanter: 'Tim' }; var child = Object.create(parent); child.a = 1; each(identity, child); assert(identity.calledOnce); assert(identity.calledWith(1, 'a', child)); assert(!identity.calledWith('Tim', 'enchanter')); }); it('should ignore non-enumerable properties', function() { var obj = Object.create(null, { a: { value: 1, enumerable: false }, b: { value: 2, enumerable: false }, c: { value: 3, enumerable: true } }); each(identity, obj); assert(identity.calledOnce); assert(identity.calledWith(3, 'c', obj)); }); });
JavaScript
0.000004
@@ -538,24 +538,30 @@ %7B%0A assert +.equal (each.length
cedb20ed96f912ac1b5ee258abcd8d6f5f1c220f
test new rules
test/index.js
test/index.js
// This file cannot be written with ECMAScript 2015 because it has to load // the Babel require hook to enable ECMAScript 2015 features! require('babel-core/register'); require('babel-core').transform('code', { plugins: ['transform-runtime'], }); // The tests, however, can and should be written with ECMAScript 2015. require('./configuration'); require('./runner'); require('./source_map'); require('./validator'); require('./rules/fields_have_descriptions'); require('./rules/fields_are_camel_cased.js'); require('./rules/types_have_descriptions'); require('./rules/deprecations_have_a_reason'); require('./rules/enum_values_sorted_alphabetically'); require('./rules/enum_values_all_caps'); require('./rules/types_are_capitalized'); require('./rules/defined_types_are_used'); require('./rules/input_object_values_have_descriptions'); require('./rules/input_object_values_are_camel_cased'); require('./rules/enum_values_have_descriptions'); require('./rules/relay_connection_types_spec'); require('./rules/relay_connection_arguments_spec'); require('./rules/relay_page_info_spec'); require('./formatters/json_formatter'); require('./formatters/text_formatter'); require('./formatters/compact_formatter.js'); require('./config/rc_file/test'); require('./config/package_json/test'); require('./config/js_file/test');
JavaScript
0.999734
@@ -429,21 +429,24 @@ ./rules/ -field +argument s_have_d @@ -481,77 +481,77 @@ les/ -fields_are_camel_cased.js');%0Arequire('./rules/types_have_descripti +defined_types_are_used');%0Arequire('./rules/deprecations_have_a_reas on -s ');%0A @@ -573,32 +573,34 @@ s/de -preca +scrip tions_ -have_a_reason +are_capitalized ');%0A @@ -632,29 +632,66 @@ ues_ -sorted_alphabetically +all_caps');%0Arequire('./rules/enum_values_have_descriptions ');%0A @@ -715,32 +715,45 @@ enum_values_ -all_caps +sorted_alphabetically ');%0Arequire( @@ -765,20 +765,21 @@ les/ -type +field s_are_ca pita @@ -770,33 +770,36 @@ ields_are_ca -pitalized +mel_cased.js ');%0Arequire( @@ -807,38 +807,40 @@ ./rules/ -defined_types_are_used +fields_have_descriptions ');%0Arequ @@ -869,32 +869,36 @@ ect_ -values_have_descriptions +fields_sorted_alphabetically ');%0A @@ -962,36 +962,44 @@ equire('./rules/ -enum +input_object _values_have_des @@ -1045,20 +1045,24 @@ nection_ -type +argument s_spec') @@ -1093,32 +1093,28 @@ _connection_ -argument +type s_spec');%0Are @@ -1144,32 +1144,172 @@ ge_info_spec');%0A +require('./rules/type_fields_sorted_alphabetically');%0Arequire('./rules/types_are_capitalized');%0Arequire('./rules/types_have_descriptions');%0A require('./forma
401413e1bb26317a3a69bccb9a3702d1f6bc175c
Improve a few tests
test/index.js
test/index.js
// Load modules var Lab = require('lab'); var Hapi = require('hapi'); // Declare internals var internals = {}; // Test shortcuts var expect = Lab.expect; var before = Lab.before; var after = Lab.after; var describe = Lab.experiment; var it = Lab.test; var S = Hapi.types.String; describe('Lout', function () { var server = null; before(function (done) { server = new Hapi.Server(); var handler = function (request) { request.reply('ok'); }; server.route([ { method: 'GET', path: '/test', config: { handler: handler, validate: { query: { param1: S().required() } } } }, { method: 'GET', path: '/another/test', config: { handler: handler, validate: { query: { param1: S().required() } } } }, { method: 'GET', path: '/zanother/test', config: { handler: handler, validate: { query: { param1: S().required() } } } }, { method: 'POST', path: '/test', config: { handler: handler, validate: { query: { param2: S().valid('first', 'last') } } } }, { method: 'GET', path: '/notincluded', config: { handler: handler, plugins: { lout: false } } } ]); server.pack.require('../', function () { done(); }); }); it('shows template when correct path is provided', function (done) { server.inject('/docs?path=/test', function (res) { expect(res.result).to.contain('GET: /test'); done(); }); }); it('returns a Not Found response when wrong path is provided', function (done) { server.inject('/docs?path=blah', function (res) { expect(res.result.error).to.equal('Not Found'); done(); }); }); it('displays the index if no path is provided', function (done) { server.inject('/docs', function (res) { expect(res.result).to.contain('?path=/test'); done(); }); }); it('index does\'t have the docs endpoint listed', function (done) { server.inject('/docs', function (res) { expect(res.result).to.not.contain('/docs'); done(); }); }); it('index does\'t include routes that are configured with docs disabled', function (done) { server.inject('/docs', function (res) { expect(res.result).to.not.contain('/notincluded'); done(); }); }); describe('Index', function () { it('doesn\'t throw an error when requesting the index when there are no POST routes', function (done) { var server = new Hapi.Server(); server.route({ method: 'GET', path: '/test', config: { handler: function (request) { request.reply('ok'); }, validate: { query: { param1: S().required() } } } }); server.pack.require('../', function () { server.inject('/docs', function (res) { expect(res).to.exist; expect(res.result).to.contain('/test'); done(); }); }); }); }); });
JavaScript
0.000232
@@ -279,16 +279,42 @@ String;%0A +var O = Hapi.types.Object; %0A%0Adescri @@ -1176,16 +1176,164 @@ alse %7D %7D + %7D,%0A %7B method: 'GET', path: '/nested', config: %7B handler: handler, validate: %7B query: %7B param1: O(%7B nestedparam1: S().required() %7D) %7D %7D %7D %7D%0A @@ -1614,32 +1614,90 @@ ('GET: /test');%0A + expect(res.result).to.contain('POST: /test');%0A done @@ -2029,33 +2029,32 @@ nction (done) %7B%0A -%0A server.i @@ -2078,32 +2078,216 @@ nction (res) %7B%0A%0A + server.routingTable().forEach(function (route) %7B%0A if ((route.settings.plugins && route.settings.plugins.lout === false) %7C%7C route.path === '/docs') %7B%0A expe @@ -2296,32 +2296,36 @@ (res.result).to. +not. contain('?path=/ @@ -2323,22 +2323,163 @@ ('?path= -/test' +' + route.path);%0A %7D else %7B%0A expect(res.result).to.contain('?path=' + route.path);%0A %7D%0A %7D );%0A @@ -2528,24 +2528,25 @@ ('index does +n %5C't have the @@ -2752,16 +2752,17 @@ dex does +n %5C't incl @@ -2981,24 +2981,288 @@ );%0A %7D);%0A%0A + it('displays nested rules', function (done) %7B%0A server.inject('/docs?path=/nested', function (res) %7B%0A expect(res.result).to.contain('param1');%0A expect(res.result).to.contain('nestedparam1');%0A done();%0A %7D);%0A %7D);%0A%0A describe @@ -3919,8 +3919,9 @@ %7D);%0A%7D); +%0A
dec2640b6a5af29903874248ab43ebf85dacbaa9
fix https://github.com/JunoLab/Juno.jl/issues/99
lib/util/pane-item.js
lib/util/pane-item.js
'use babel' import { CompositeDisposable, TextEditor } from 'atom' let subs = new CompositeDisposable let panes = new Set function ensurePaneVisible(pane) { if (!(pane && pane.getFlexScale)) return if (pane.getFlexScale() < 0.1) { pane.parent.adjustFlexScale() pane.setFlexScale(1) } ensurePaneVisible(pane.parent) } export default class PaneItem { static activate() { if (subs != null) return subs = new CompositeDisposable panes.forEach(Pane => Pane.registerView()) } static deactivate() { if (subs != null) subs.dispose() subs = null } static attachView(View) { this.View = View this.registerView() } static registerView() { panes.add(this) subs.add(atom.views.addViewProvider(this, pane => { if (pane.element != null) { return pane.element } else { return new this.View().initialize(pane) } })) subs.add(atom.deserializers.add({ name: `Ink${this.name}`, deserialize: (state) => { let pane = this.fromId(state.id) if (pane.currentPane()) return return pane } })) subs.add(atom.workspace.onDidOpen(({uri, item}) => { if (uri.match(new RegExp(`atom://ink-${this.name.toLowerCase()}/(.+)`))) { if (item.onAttached) item.onAttached() } })) subs.add(atom.workspace.addOpener(uri => { let m if (m = uri.match(new RegExp(`atom://ink-${this.name.toLowerCase()}/(.+)`))) { let [_, id] = m return this.fromId(id) } })) } getURI() { return `atom://ink-${this.constructor.name.toLowerCase()}/${this.id}` } static fromId(id, ...args) { let pane if (this.registered == null) { this.registered = {} } if (pane = this.registered[id]) { return pane } else { pane = this.registered[id] = new this(...args) pane.id = id return pane } } serialize() { if (this.id) { return { deserializer: `Ink${this.constructor.name}`, id: this.id } } } currentPane() { for (let pane of atom.workspace.getPanes()) { if (pane.getItems().includes(this)) return pane } } activate() { let pane if (pane = this.currentPane()) { pane.activate() pane.setActiveItem(this) ensurePaneVisible(pane) return true } } open(opts) { if (this.activate()) { return Promise.resolve(this) } if (this.id) { return atom.workspace.open(`atom://ink-${this.constructor.name.toLowerCase()}/${this.id}`, opts) } else { throw new Error('Pane does not have an ID') } } close() { if (this.currentPane()) this.currentPane().removeItem(this) } static focusEditorPane() { let cur = atom.workspace.getActivePaneItem() if (cur instanceof TextEditor) return for (pane of atom.workspace.getPanes()) { if (pane.getActiveItem() instanceof TextEditor) { pane.focus() break } } } }
JavaScript
0
@@ -1194,16 +1194,23 @@ if (uri + && uri .match(n
ed81dbf230cea3de2c03439b31a67850a930a094
Make registry less noisy
lib/utils/registry.js
lib/utils/registry.js
// utilities for working with the js-registry site. exports.publish = publish exports.tag = tag exports.adduser = adduser exports.get = get var npm = require("../../npm") , http = require("http") , url = require("url") , log = require("./log") , uuid = require("./uuid") , sha = require("./sha") , sys = require("sys") , ini = require("./ini") function get (project, version, cb) { if (typeof version === "function") { cb = version version = null } GET(project+"/"+(version || ""), cb) } function tag (project, version, tag, cb) { PUT(project+"/"+tag, version, cb) } function publish (data, tarball, cb) { // add the dist-url to the data, pointing at the tarball. // if the {name} isn't there, then create it. // if the {version} is already there, then fail. // then: // PUT the data to {config.registry}/{data.name}/{data.version} try { reg() } catch (ex) { return cb(ex) } var fullData = { "_id" : data.name , "name" : data.name , "description" : data.description , "dist-tags" : {} , "versions" : {} } fullData.versions[ data.version ] = data data._id = data.name+"-"+data.version data.dist = { "tarball" : tarball } // first try to just PUT the whole fullData, and this will fail if it's // already there, because it'll be lacking a _rev, so couch'll bounce it. PUT(data.name, fullData, function (er) { if (!er) return cb() // there was an error, so assume the fullData is already there. // now try to create just this version. This time, failure // is not ok. // Note: the first might've failed for a down host or something, // in which case this will likely fail, too. If the host was down for the // first req, but now it's up, then this may fail for not having the // project created yet, or because the user doesn't have access to it. PUT(data.name+"/"+data.version, data, function (er) { if (er) return cb(er) cb() }) }) } function GET (where, cb) { reg() where = ini.config.registry + where var u = url.parse(where) , headers = { "host" : u.host , "accept" : "application/json" } if (ini.config.auth) { headers.authorization = 'Basic ' + ini.config.auth } log(u, "registryGET") var https = u.protocol === "https:" , client = http.createClient(u.port || (https ? 443 : 80), u.hostname, https) , request = client.request("GET", u.pathname, headers) request.addListener("response", function (response) { // if (response.statusCode !== 200) return cb(new Error( // "Status code " + response.statusCode + " from PUT "+where)) var data = "" response.setBodyEncoding("utf8") response.addListener("data", function (chunk) { data += chunk }) response.addListener("end", function () { try { data = JSON.parse(data) } catch (ex) { ex.message += "\n" + data return cb(ex, data, response) } if (data.error) return cb(new Error( data.error + (" "+data.reason || ""))) cb(null, data, response) }) }) request.end() } function PUT (where, what, cb) { reg() what = JSON.stringify(what) log(where, "registryPUT") where = ini.config.registry + where var u = url.parse(where) , headers = { "content-type" : "application/json" , "host" : u.host , "content-length" : what.length } if (ini.config.auth) { headers.authorization = 'Basic ' + ini.config.auth } log(sys.inspect(u), "registryPUT") var https = u.protocol === "https:" , client = http.createClient(u.port || (https ? 443 : 80), u.hostname, https) , request = client.request("PUT", u.pathname, headers) log(sys.inspect(headers), "registryPUT headers") request.addListener("response", function (response) { // if (response.statusCode !== 200) return cb(new Error( // "Status code " + response.statusCode + " from PUT "+where)) var data = "" response.setBodyEncoding("utf8") response.addListener("data", function (chunk) { data += chunk }) response.addListener("end", function () { log(data, "registryPUT") try { data = JSON.parse(data) } catch (ex) { ex.message += "\n" + data return cb(ex, data, response) } if (data.error) return cb(new Error( data.error + (" "+data.reason || ""))) cb(null, data, response) }) }) request.write(what, "utf8") request.end() } function reg () { if (!ini.config.registry) throw new Error( "Must define registry before publishing.") log(ini.config.registry, "registry") if (ini.config.registry.substr(-1) !== "/") { ini.config.registry += "/" } } function adduser (username, password, email, callback) { var salt = uuid.generate() var userobj = { '_id' : 'org.couchdb.user:'+username , name : username , type : "user" , roles : [] , salt : salt , password_sha : sha.hex_sha1(password + salt) , email : email } PUT('/adduser/org.couchdb.user:'+username, userobj, function (error, data, response) { // if the error is a 409, then update the rev. if (error || response.statusCode !== 201) { callback(new Error( "Could not create user "+error+'\n'+data)) } else { callback() } }) }
JavaScript
0.000622
@@ -2268,32 +2268,8 @@ %7D%0A - log(u, %22registryGET%22)%0A va @@ -2294,32 +2294,32 @@ ol === %22https:%22%0A + , client = h @@ -3173,36 +3173,8 @@ at)%0A - log(where, %22registryPUT%22)%0A wh @@ -3477,45 +3477,8 @@ %0A %7D -%0A log(sys.inspect(u), %22registryPUT%22) %0A%0A @@ -3659,60 +3659,8 @@ s)%0A%0A - log(sys.inspect(headers), %22registryPUT headers%22)%0A%0A re @@ -3957,32 +3957,32 @@ ata += chunk %7D)%0A + response.add @@ -4015,39 +4015,8 @@ ) %7B%0A - log(data, %22registryPUT%22)%0A
dab9c3e37fa917982760dd0c4e7cf9972e272867
return sorted and sliced candidates array
api/controllers/LoadCrawlController.js
api/controllers/LoadCrawlController.js
/** * CrawlsController * * @description :: Server-side logic for managing crawls * @help :: See http://links.sailsjs.org/docs/controllers */ var FocusedCrawler = require('../../bindings/FocusedCrawler/app'); module.exports = { create: function(req, res, next) { var crawlId = req.param('crawl_id'); console.log('Load crawl: ' + crawlId); var focusedCrawler = new FocusedCrawler({ baseURL: 'http://asev.l3s.uni-hannover.de:9986/api/CrawlAPI/' }); focusedCrawler.loadCrawl(crawlId).then(function(candidates) { res.send(candidates); }); } };
JavaScript
0.000004
@@ -310,18 +310,58 @@ awl_id') +,%0A count = req.param('count') %7C%7C 50 ;%0A - %0A con @@ -395,16 +395,52 @@ rawlId); +%0A console.log('count: ' + count); %0A%0A va @@ -631,17 +631,8 @@ -res.send( cand @@ -637,16 +637,308 @@ ndidates + = JSON.parse(candidates);%0A candidates.sort(function(a, b) %7B%0A if (a.count %3E b.count) %7B%0A return 1;%0A %7D;%0A if (a.count %3C b.count) %7B%0A return -1;%0A %7D;%0A%0A return 0;%0A %7D);%0A var result = candidates.slice(0, count);%0A res.send(result );%0A %7D
5eb667d1819c99efcc4a4f784f0e07b6ff1e7641
Refactor scope test to use more describe and it blocks which makes the overall test clearer
test/scope.js
test/scope.js
require('./support/helper'); var expect = require("expect.js") , fs = require("fs") , generateTemplate = require("./support/generate_template") , Backbone = require('backbone') , variableReaction = require('../lib/reactions/variable'); describe ("With a template that has a polymorphic key but no scope changes", function(){ beforeEach(function(){ this.markup = "<div class='permissionsPolymorphic-' data-each>" + "<div class='whenUser-'>" + "Is User" + "</div>" + "<div class='whenAdmin-'>" + "Is Admin" + "</div>" + "</div>"; }); it("should not record any model/scoping reactions", function(){ var users = [ new Backbone.Model({permissions: 'user'}), new Backbone.Model({permissions: 'admin'}) ] , collection = new Backbone.Collection(users) , savedFn = variableReaction.prototype.init; variableReaction.prototype.init = function() { throw new Error('Variable reaction should not occur in this scope.js test'); }; generateTemplate(collection, this.markup); variableReaction.prototype.init = savedFn; expect($('[data-each] div:nth-child(1)').html()).to.be("Is User"); expect($('[data-each] div:nth-child(2)').html()).to.be("Is Admin"); }); });
JavaScript
0
@@ -243,18 +243,16 @@ );%0A%0A - describe (%22W @@ -251,38 +251,43 @@ ribe - (%22With a template that has a +('scope', function()%7B%0A describe (%22 poly @@ -718,40 +718,24 @@ -it(%22should not record any +describe(' model -/ + scop @@ -747,17 +747,29 @@ eactions -%22 + stubbed out' , functi @@ -770,24 +770,55 @@ function()%7B%0A + beforeEach(function()%7B%0A var us @@ -825,16 +825,17 @@ ers = %5B%0A + @@ -890,16 +890,17 @@ ser'%7D),%0A + @@ -973,17 +973,20 @@ -%5D + %5D; %0A @@ -990,108 +990,116 @@ -, collection = new Backbone.Collection(users)%0A , savedFn = variableReaction.prototype.init;%0A%0A +this.savedFn = variableReaction.prototype.init;%0A this.collection = new Backbone.Collection(users);%0A @@ -1147,16 +1147,18 @@ ion() %7B%0A + @@ -1244,61 +1244,53 @@ + %7D;%0A -%0A generateTemplate(collection, this.markup);%0A + %7D);%0A afterEach(function()%7B%0A @@ -1325,16 +1325,21 @@ .init = +this. savedFn; @@ -1343,83 +1343,358 @@ Fn;%0A -%0A%0A expect($('%5Bdata-each%5D div:nth-child(1)').html()).to.be(%22Is User%22);%0A + %7D);%0A it(%22should not record user variable interpolation%22, function()%7B%0A generateTemplate(this.collection, this.markup);%0A expect($('%5Bdata-each%5D div:nth-child(1)').html()).to.be(%22Is User%22);%0A %7D);%0A it(%22should not record admin variable interpolation%22, function()%7B%0A generateTemplate(this.collection, this.markup);%0A @@ -1759,24 +1759,34 @@ Is Admin%22);%0A + %7D);%0A %7D);%0A %7D) @@ -1787,9 +1787,12 @@ ;%0A %7D);%0A +%7D); %0A
165d49b19a9dd0c3a044a8d02e47643e01fe2679
Add proxyquire to test setup
test/setup.js
test/setup.js
import fs from 'fs'; import chai from 'chai'; import sinon from 'sinon'; import schai from 'sinon-chai'; global.sinon = sinon; global.expect = chai.expect; chai.use(schai); // Global spies import output from './../src/lib/output'; global.logSpy = sinon.spy(output, 'log'); process.env.LAM_TEST = true;
JavaScript
0
@@ -1,25 +1,4 @@ -import fs from 'fs';%0A impo @@ -247,16 +247,86 @@ log');%0A%0A +import proxyquire from 'proxyquire';%0Aglobal.proxyquire = proxyquire;%0A%0A process.
cd071d2e00356007a640d27a6bc2003d775b5b8d
Remove IE11 from saucelabs.
test/sauce.js
test/sauce.js
var user = process.env.SAUCE_USER; var key = process.env.SAUCE_KEY; var path = require('path'); var brtapsauce = require('brtapsauce'); // list of browsers & versions that you want to test var capabilities = [ { browserName: 'chrome' , platform: 'Windows 8' , version: '40' }, { browserName: 'chrome' , platform: 'Windows 8' , version: '35' }, { browserName: 'chrome' , platform: 'Windows 8' , version: '30' }, { browserName: 'firefox' , platform: 'Windows 8' , version: '35' }, { browserName: 'firefox' , platform: 'Windows 8' , version: '30' }, { browserName: 'firefox' , platform: 'Windows 8' , version: '25' }, { browserName: 'firefox' , platform: 'Windows 8' , version: '4' }, { browserName: 'firefox' , platform: 'Windows 8' , version: '3' }, { browserName: 'internet explorer' , platform: 'Windows 8' , version: '11' }, { browserName: 'internet explorer' , platform: 'Windows 8' , version: '10' }, { browserName: 'internet explorer' , platform: 'Windows 7' , version: '9' }, { browserName: 'internet explorer' , platform: 'Windows 7' , version: '8' }, { browserName: 'internet explorer' , platform: 'Windows XP', version: '7' }, { browserName: 'internet explorer' , platform: 'Windows XP', version: '6' }, { browserName: 'safari' , platform: 'Windows 7' , version: '5' }, { browserName: 'opera' , platform: 'Windows 7' , version: '' }, { browserName: 'android' , platform: 'Linux' , version: '4.0'} ]; if (!user || !key) { console.log('You need to set SAUCE_USER and SAUCE_KEY to run the tests in SauceLab.'); process.exit(); } brtapsauce({ name: 'after-all', user: user, key: key, brsrc: path.join(__dirname, 'index.js'), capabilities: capabilities });
JavaScript
0
@@ -850,88 +850,8 @@ %7D,%0A - %7B browserName: 'internet explorer' , platform: 'Windows 8' , version: '11' %7D,%0A %7B
8fafcf546e376497ff80972b30f0120577b580cb
Remove stray console.log
test/scope.js
test/scope.js
var test = require('tap').test; var browserify = require('browserify'); var path = require('path'); test('scope', function (t) { t.plan(4); var b = browserify({ node: true }); b.add(__dirname + '/files/scope'); b.transform(path.dirname(__dirname)); b.bundle(function (err, src) { if (err) t.fail(err); t.pass('build success'); src = src.toString(); console.log(src) t.ok(src.indexOf("require('fs')") !== -1, 'kept the require call'); var sentinel = new Buffer('SCOPE_SENTINEL\n', 'utf8').toString('base64') var i = src.indexOf(sentinel); t.ok(i !== -1, 'read the file'); i = src.indexOf(sentinel, i + 10); t.ok(i !== -1, 'did the require("fs").readFileSync'); }); });
JavaScript
0.000002
@@ -401,33 +401,8 @@ ();%0A - console.log(src)%0A
2094880b575fc03e7c4e944d91b4e67cde7f276c
Add test for unmock
test/smock.js
test/smock.js
/** * Tests for smock * */ var expect = require('chai').expect; var smock; // Export describe('Export', function() { before(function() { smock = require('..'); }); it('should be an object', function() { expect( smock ).to.be.an('object'); }); it('should have a mock() function', function() { expect( smock.mock ).to.be.a('function') }) it('should have a suppress() function', function() { expect( smock.suppress ).to.be.a('function'); }); it('should have a unmock() function', function() { expect( smock.unmock ).to.be.a('function'); }); it('should have a unsuppress() function', function() { expect( smock.unsuppress ).to.be.a('function'); }); it('should have a unmockAll() function', function() { expect( smock.unmockAll ).to.be.a('function'); }); it('should have a unsuppressAll() function', function() { expect( smock.unsuppressAll ).to.be.a('function'); }); }); // mock function describe('mock()', function() { beforeEach(function() { // Reset the require cache require.cache = {}; smock = require('..'); }); it('should take two arguments', function() { expect(smock.mock.length).to.equal(2); }); it('should mock correctly with a string', function() { smock.mock('blah', 42); var imp = require('blah'); expect( imp ).to.equal(42); }); it('should mock correctly with a regex', function() { smock.mock(/^blah/, 42); ['blah', 'blah1', 'blah2', 'blahblah'].forEach(function(str) { var imp = require(str); expect(imp).to.equal(42); }); }); it('should correctly mock using callbacks', function() { var filter = function(str) { return 0 === str.indexOf('blah'); }; smock.mock(filter, 42); ['blah', 'blah1', 'blah2', 'blahblah'].forEach(function(str) { var imp = require(str); expect(imp).to.equal(42); }); }); });
JavaScript
0.000001
@@ -2038,20 +2038,1207 @@ %7D);%0A %7D);%0A%0A%7D); +%0A%0Adescribe('unmock()', function() %7B%0A%0A beforeEach(function() %7B%0A // Reset the require cache%0A require.cache = %7B%7D;%0A smock = require('..');%0A %7D);%0A%0A it('should take one argument', function() %7B%0A expect(smock.unmock.length).to.equal(1);%0A %7D);%0A%0A it('should unmock correctly when using a string', function() %7B%0A smock.mock('unmockblah', 77);%0A smock.unmock('unmockblah');%0A%0A var fn = require.bind(this, 'unmockblah');%0A expect( fn ).to.throw();%0A %7D);%0A%0A it('should unmock correctly when unsing a regex', function() %7B%0A smock.mock(/%5Eregexblah/, 81);%0A smock.unmock(/%5Eregexblah/);%0A%0A %5B'regexblah', 'regexblah1', 'regexblah2', 'regexblahblah'%5D.forEach(function(str) %7B%0A var fn = require.bind(this, str);%0A%0A %7D);%0A %7D);%0A%0A it('should correctly mock using callbacks', function() %7B%0A var filter = function(str) %7B return 0 === str.indexOf('blub'); %7D;%0A smock.mock(filter, 42);%0A smock.unmock( filter );%0A%0A %5B'blub', 'blub1', 'blub2', 'blubblah'%5D.forEach(function(str) %7B%0A var fn = require.bind(this, str);%0A expect( fn ).to.throw();%0A %7D);%0A %7D);%0A%7D);
95fb92313834f45c616c0a162584b0bf9c495378
Update session-test.js
test/tests/acceptance/session-test.js
test/tests/acceptance/session-test.js
import startApp from 'test/helpers/start-app'; import DummyAdapter from 'test/helpers/dummy-adapter'; import DummySuccessProvider from 'test/helpers/dummy-success-provider'; import DummyFailureProvider from 'test/helpers/dummy-failure-provider'; var torii, app, session, container, adapter; function signIn(sessionData){ var sm = session.get('stateMachine'); sm.send('startOpen'); sm.send('finishOpen', sessionData || {}); } module('Session - Acceptance', { setup: function(){ app = startApp({loadInitializers: true}); container = app.__container__; torii = container.lookup("torii:main"); session = container.lookup("torii:session"); adapter = container.lookup("torii-adapter:application"); container.register('torii-provider:dummy-failure', DummyFailureProvider); container.register('torii-provider:dummy-success', DummySuccessProvider); }, teardown: function(){ Ember.run(app, 'destroy'); } }); test("#open dummy-success session raises must-implement on application adapter", function(){ Ember.run(function(){ session.open('dummy-success').then(function(){ ok(false, 'resolved promise'); }, function(error){ ok(true, 'fails promise'); ok(error.message.match(/must implement/), 'fails with message to implement'); }); }); }); test("#open dummy-success session fails on signed in state", function(){ signIn(); Ember.run(function(){ session.open('dummy-success').then(function(){ ok(false, 'resolved promise'); }, function(error){ ok(true, 'fails promise'); ok(error.message.match(/Unknown Event/), 'fails with message'); }); }); }); test("#open dummy-success session successfully opens", function(){ container.register("torii-adapter:dummy-success", DummyAdapter); Ember.run(function(){ session.open('dummy-success').then(function(){ ok(true, 'resolves promise'); ok(session.get('isAuthenticated'), 'authenticated'); ok(session.get('currentUser.email'), 'user has email'); }, function(err){ ok(false, 'failed to resolve promise: '+err); }); }); }); test("#open dummy-failure session fails to open", function(){ Ember.run(function(){ session.open('dummy-failure').then(function(){ ok(false, 'should not resolve promise'); }, function(error){ ok(true, 'fails to resolve promise'); }); }); }); test("#fetch dummy-success session raises must-implement on application adapter", function(){ Ember.run(function(){ session.fetch('dummy-success').then(function(){ ok(false, 'resolved promise'); }, function(error){ ok(true, 'fails promise'); ok(error.message.match(/must implement/), 'fails with message to implement'); }); }); }); test("#fetch dummy-success session fails on signed in state", function(){ container.register("torii-adapter:dummy-success", DummyAdapter); signIn(); Ember.run(function(){ session.fetch('dummy-success').then(function(){ ok(false, 'resolved promise'); }, function(error){ ok(true, 'fails promise'); ok(error.message.match(/Unknown Event/), 'fails with message'); }); }); }); test("#fetch dummy-success session successfully opens", function(){ container.register("torii-adapter:dummy-success", DummyAdapter); Ember.run(function(){ session.fetch('dummy-success').then(function(){ ok(true, 'resolves promise'); ok(session.get('isAuthenticated'), 'authenticated'); ok(session.get('currentUser.email'), 'user has email'); }, function(err){ ok(false, 'failed to resolve promise: '+err); }); }); }); test("#fetch session passes options to adapter", function(){ var adapterFetchCalledWith = null; container.register("torii-adapter:dummy-success", DummyAdapter.extend({ fetch: function(options){ adapterFetchCalledWith = options; return this._super(options); } })); Ember.run(function(){ var opts = {}; session.fetch('dummy-success', opts).then(function(){ equal(adapterFetchCalledWith, opts, 'options should be passed through to adapter'); }, function(err){ ok(false, 'failed to resolve promise: '+err); }); }); }); test("#fetch dummy-failure session fails to open", function(){ Ember.run(function(){ session.open('dummy-failure').then(function(){ ok(false, 'should not resolve promise'); }, function(error){ ok(true, 'fails to resolve promise'); }); }); }); test("#close dummy-success fails in an unauthenticated state", function(){ adapter.reopen({ close: function(){ return Ember.RSVP.Promise.resolve(); } }); Ember.run(function(){ session.close().then(function(){ ok(false, 'resolved promise'); }, function(error){ ok(true, 'fails promise'); ok(error.message.match(/Unknown Event/), 'fails with message'); }); }); }); test("#close dummy-success session closes", function(){ signIn({currentUser: {email: 'some@email.com'}}); adapter.reopen({ close: function(provider, options){ return Ember.RSVP.Promise.resolve(); } }); Ember.run(function(){ session.close('dummy-success').then(function(){ ok(true, 'resolved promise'); ok(!session.get('isAuthenticated'), 'authenticated'); ok(!session.get('currentUser.email'), 'user has email'); }, function(error){ ok(false, 'fails promise'); }); }); }); test("#close dummy-success session raises must-implement on application adapter", function(){ signIn(); Ember.run(function(){ session.close().then(function(){ ok(false, 'resolved promise'); }, function(error){ ok(true, 'fails promise'); ok(error.message.match(/must implement/), 'fails with message to implement'); }); }); }); test("#close session passes options to adapter", function(){ signIn({currentUser: {email: 'some@email.com'}}); var adapterFetchCalledWith = null; container.register("torii-adapter:dummy-success", DummyAdapter.extend({ close: function(options){ adapterFetchCalledWith = options; return this._super(options); } })); Ember.run(function(){ var opts = {}; session.close('dummy-success', opts).then(function(){ equal(adapterFetchCalledWith, opts, 'options should be passed through to adapter'); }, function(err){ ok(false, 'failed to resolve promise: '+err); }); }); });
JavaScript
0.000001
@@ -5900,37 +5900,37 @@ );%0A var adapter -Fetch +Close CalledWith = nul @@ -6041,37 +6041,37 @@ )%7B%0A adapter -Fetch +Close CalledWith = opt @@ -6236,37 +6236,37 @@ equal(adapter -Fetch +Close CalledWith, opts
4fcdb66f57d5e1e55d5cc6cb733d4c60789a5993
Add tests for unmockAll()
test/smock.js
test/smock.js
/** * Tests for smock * */ var expect = require('chai').expect; var smock; // Export describe('Export', function() { before(function() { smock = require('..'); }); it('should be an object', function() { expect( smock ).to.be.an('object'); }); it('should have a mock() function', function() { expect( smock.mock ).to.be.a('function') }) it('should have a suppress() function', function() { expect( smock.suppress ).to.be.a('function'); }); it('should have a unmock() function', function() { expect( smock.unmock ).to.be.a('function'); }); it('should have a unsuppress() function', function() { expect( smock.unsuppress ).to.be.a('function'); }); it('should have a unmockAll() function', function() { expect( smock.unmockAll ).to.be.a('function'); }); it('should have a unsuppressAll() function', function() { expect( smock.unsuppressAll ).to.be.a('function'); }); }); // mock function describe('mock()', function() { beforeEach(function() { // Reset the require cache require.cache = {}; smock = require('..'); }); it('should take two arguments', function() { expect(smock.mock.length).to.equal(2); }); it('should mock correctly with a string', function() { smock.mock('blah', 42); var imp = require('blah'); expect( imp ).to.equal(42); }); it('should mock correctly with a regex', function() { smock.mock(/^blah/, 42); ['blah', 'blah1', 'blah2', 'blahblah'].forEach(function(str) { var imp = require(str); expect(imp).to.equal(42); }); }); it('should correctly mock using callbacks', function() { var filter = function(str) { return 0 === str.indexOf('blah'); }; smock.mock(filter, 42); ['blah', 'blah1', 'blah2', 'blahblah'].forEach(function(str) { var imp = require(str); expect(imp).to.equal(42); }); }); }); describe('unmock()', function() { beforeEach(function() { // Reset the require cache require.cache = {}; smock = require('..'); }); it('should take one argument', function() { expect(smock.unmock.length).to.equal(1); }); it('should unmock correctly when using a string', function() { smock.mock('unmockblah', 77); smock.unmock('unmockblah'); var fn = require.bind(this, 'unmockblah'); expect( fn ).to.throw(); }); it('should unmock correctly when unsing a regex', function() { smock.mock(/^regexblah/, 81); smock.unmock(/^regexblah/); ['regexblah', 'regexblah1', 'regexblah2', 'regexblahblah'].forEach(function(str) { var fn = require.bind(this, str); }); }); it('should correctly mock using callbacks', function() { var filter = function(str) { return 0 === str.indexOf('blub'); }; smock.mock(filter, 42); smock.unmock( filter ); ['blub', 'blub1', 'blub2', 'blubblah'].forEach(function(str) { var fn = require.bind(this, str); expect( fn ).to.throw(); }); }); });
JavaScript
0
@@ -2052,16 +2052,36 @@ ;%0A%0A%7D);%0A%0A +%0A// unmock function%0A describe @@ -2858,16 +2858,1285 @@ , str);%0A + expect( fn ).to.throw();%0A %7D);%0A %7D);%0A%0A it('should correctly mock using callbacks', function() %7B%0A var filter = function(str) %7B return 0 === str.indexOf('blub'); %7D;%0A smock.mock(filter, 42);%0A smock.unmock( filter );%0A%0A %5B'blub', 'blub1', 'blub2', 'blubblah'%5D.forEach(function(str) %7B%0A var fn = require.bind(this, str);%0A expect( fn ).to.throw();%0A %7D);%0A %7D);%0A%7D);%0A%0A// unmockAll function%0Adescribe('unmockAll()', function() %7B%0A%0A beforeEach(function() %7B%0A // Reset the require cache%0A require.cache = %7B%7D;%0A smock = require('..');%0A %7D);%0A%0A it('should take no arguments', function() %7B%0A expect(smock.unmockAll.length).to.equal(0);%0A %7D);%0A%0A it('should unmock all correctly when using a string', function() %7B%0A smock.mock('unmockallblah', '_s3');%0A smock.unmockAll();%0A%0A var fn = require.bind(this, 'unmockallblah');%0A expect( fn ).to.throw();%0A %7D);%0A%0A it('should unmock all correctly when unsing a regex', function() %7B%0A smock.mock(/%5Efoobar/, 13);%0A smock.unmockAll();%0A%0A %5B'foobar', 'foobar1', 'foobar2', 'foobarblah'%5D.forEach(function(str) %7B%0A var fn = require.bind(this, str);%0A expect(fn).to.throw(); %0A @@ -4332,33 +4332,28 @@ smock.unmock -( filter +All( );%0A%0A
64eace3b901435e8e5687c365c967d7c929bce73
Add test for localized spoken language name
test/unit/extension_text_to_speech.js
test/unit/extension_text_to_speech.js
const test = require('tap').test; const TextToSpeech = require('../../src/extensions/scratch3_text2speech/index.js'); const fakeStage = { textToSpeechLanguage: null }; const fakeRuntime = { getTargetForStage: () => fakeStage, on: () => {} // Stub out listener methods used in constructor. }; const ext = new TextToSpeech(fakeRuntime); test('if no language is saved in the project, use default', t => { t.strictEqual(ext.getCurrentLanguage(), 'en'); t.end(); }); test('if an unsupported language is dropped onto the set language block, use default', t => { ext.setLanguage({LANGUAGE: 'nope'}); t.strictEqual(ext.getCurrentLanguage(), 'en'); t.end(); }); test('if a supported language name is dropped onto the set language block, use it', t => { ext.setLanguage({LANGUAGE: 'español'}); t.strictEqual(ext.getCurrentLanguage(), 'es'); t.end(); }); test('get the extension locale for a supported locale that differs', t => { ext.setLanguage({LANGUAGE: 'ja-hira'}); t.strictEqual(ext.getCurrentLanguage(), 'ja'); t.end(); });
JavaScript
0.000009
@@ -1056,28 +1056,443 @@ (), 'ja');%0A t.end();%0A%7D);%0A +%0Atest('use localized spoken language name in place of localized written language name', t =%3E %7B%0A ext.getEditorLanguage = () =%3E 'es';%0A const languageMenu = ext.getLanguageMenu();%0A const localizedNameForChineseInSpanish = languageMenu.find(el =%3E el.value === 'zh-cn').text;%0A t.strictEqual(localizedNameForChineseInSpanish, 'Chino (Mandar%C3%ADn)'); // i.e. should not be 'Chino (simplificado)'%0A t.end();%0A%7D);%0A
5be769837f5b089c7c6f7ac087e06c85653b6e9a
Return value onChange
components/input/Input.js
components/input/Input.js
import React, { PureComponent, createElement } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import { IconChevronUpSmallOutline, IconChevronDownSmallOutline } from '@teamleader/ui-icons'; import Counter from '../counter'; import theme from './theme.css'; export default class Input extends PureComponent { static propTypes = { bold: PropTypes.bool, className: PropTypes.string, counter: PropTypes.number, disabled: PropTypes.bool, icon: PropTypes.oneOfType([PropTypes.func, PropTypes.element]), iconPlacement: PropTypes.oneOf(['left', 'right']), id: PropTypes.string, onBlur: PropTypes.func, onChange: PropTypes.func, onFocus: PropTypes.func, placeholder: PropTypes.string, readOnly: PropTypes.bool, size: PropTypes.oneOf(['small', 'medium', 'large']), step: PropTypes.number, type: PropTypes.string, value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; static defaultProps = { iconPlacement: 'left', disabled: false, placeholder: '', readOnly: false, size: 'medium', step: 1, }; constructor(props) { super(props); this.isNumberInput = Boolean(props.type === 'number'); this.handleChange = this.onChange.bind(this); this.handleIncreaseValue = this.increaseValue.bind(this); this.handleDecreaseValue = this.decreaseValue.bind(this); if (this.isNumber) { this.state = { value: Number(props.value) || undefined, }; } else { this.state = { value: props.value || '', }; } } createEvent() { return new Event('input', { bubbles: true }); } onChange(value) { if (value.target) { if (this.isNumberInput) { this.setState({ value: Number(value.target.value) }); } else { this.setState({ value: value.target.value }); } return this.props.onChange(value); } this.setState({ value }); return this.props.onChange(new Event('input', { bubbles: true, value })); } increaseValue() { if (this.state.value) { return this.onChange(this.state.value + this.props.step); } return this.onChange(this.props.step); } decreaseValue() { if (this.state.value) { return this.onChange(this.state.value - this.props.step); } return this.onChange(-this.props.step); } renderInput() { const { bold, disabled, id, onBlur, onFocus, placeholder, readOnly, type } = this.props; const classNames = cx(theme['input'], { [theme['is-disabled']]: disabled, [theme['is-read-only']]: readOnly, [theme['is-bold']]: bold, }); const props = { className: classNames, disabled: disabled, id, onBlur: onBlur, onChange: this.handleChange, onFocus: onFocus, placeholder, readOnly, type, value: this.state.value, }; return <input {...props} />; } renderCounter() { if (this.props.counter) { return <Counter className={theme.counter} count={this.props.counter} color="ruby" size="small" />; } } renderSpinnerControls() { if (this.isNumberInput) { return ( <div className={theme['spinner']}> <button className={theme['spinner-up']} onClick={this.handleIncreaseValue}> <IconChevronUpSmallOutline /> </button> <button className={theme['spinner-down']} onClick={this.handleDecreaseValue}> <IconChevronDownSmallOutline /> </button> </div> ); } } render() { const { className, counter, icon, iconPlacement, size } = this.props; const classNames = cx(theme.wrapper, theme[size], className, { [theme[`has-icon-${iconPlacement}`]]: icon, [theme['has-counter']]: counter, }); return ( <div className={classNames}> {icon && createElement(icon, { className: theme.icon, })} {this.renderInput()} {this.renderCounter()} {this.renderSpinnerControls()} </div> ); } }
JavaScript
0.000002
@@ -1907,24 +1907,35 @@ ps.onChange( +this.state. value);%0A @@ -2003,52 +2003,13 @@ nge( -new Event('input', %7B bubbles: true, value - %7D) );%0A
d91eda8556f8148c12505a662fab0d4bf39e4b97
add options el tests (#2967)
test/unit/features/options/el.spec.js
test/unit/features/options/el.spec.js
JavaScript
0
@@ -0,0 +1,2033 @@ +import Vue from 'vue'%0A%0Adescribe('Options el', () =%3E %7B%0A it('basic usage', () =%3E %7B%0A const el = document.createElement('div')%0A el.innerHTML = '%3Cspan%3E%7B%7Bmessage%7D%7D%3C/span%3E'%0A const vm = new Vue(%7B%0A el,%0A data: %7B message: 'hello world' %7D%0A %7D)%0A expect(vm.$el.tagName).toBe('DIV')%0A expect(vm.$el.textContent).toBe(vm.message)%0A %7D)%0A%0A it('should be replaced when use togther with %60template%60 option', () =%3E %7B%0A const el = document.createElement('div')%0A el.innerHTML = '%3Cspan%3E%7B%7Bmessage%7D%7D%3C/span%3E'%0A const vm = new Vue(%7B%0A el,%0A template: '%3Cp id=%22app%22%3E%3Cspan%3E%7B%7Bmessage%7D%7D%3C/span%3E%3C/p%3E',%0A data: %7B message: 'hello world' %7D%0A %7D)%0A expect(vm.$el.tagName).toBe('P')%0A expect(vm.$el.textContent).toBe(vm.message)%0A %7D)%0A%0A it('should be replaced when use togther with %60render%60 option', () =%3E %7B%0A const el = document.createElement('div')%0A el.innerHTML = '%3Cspan%3E%7B%7Bmessage%7D%7D%3C/span%3E'%0A const vm = new Vue(%7B%0A el,%0A render () %7B%0A const h = this.$createElement%0A return h('p', %7B staticAttrs: %7B id: 'app' %7D%7D, %5B%0A h('span', %7B%7D, %5Bthis.message%5D)%0A %5D)%0A %7D,%0A data: %7B message: 'hello world' %7D%0A %7D)%0A expect(vm.$el.tagName).toBe('P')%0A expect(vm.$el.textContent).toBe(vm.message)%0A %7D)%0A%0A it('svg element', () =%3E %7B%0A const ns = 'http://www.w3.org/2000/svg'%0A const el = document.createElementNS(ns, 'svg')%0A const text = document.createElementNS(ns, 'text')%0A text.setAttribute(':x', 'x')%0A text.setAttribute(':y', 'y')%0A text.setAttribute(':fill', 'color')%0A text.textContent = '%7B%7Btext%7D%7D'%0A el.appendChild(text)%0A const vm = new Vue(%7B%0A el,%0A data: %7B%0A x: 64, y: 128, color: 'red', text: 'svg text'%0A %7D%0A %7D)%0A expect(vm.$el.tagName).toBe('svg')%0A expect(vm.$el.childNodes%5B0%5D.getAttribute('x')).toBe(vm.x.toString())%0A expect(vm.$el.childNodes%5B0%5D.getAttribute('y')).toBe(vm.y.toString())%0A expect(vm.$el.childNodes%5B0%5D.getAttribute('fill')).toBe(vm.color)%0A expect(vm.$el.childNodes%5B0%5D.textContent).toBe(vm.text)%0A %7D)%0A%7D)%0A
ede7a15ddf3860446d8207cdb7eb1701b70cd926
update test/test-runner — minor edits
test/testr.js
test/testr.js
// use this file to automate the running of tests. var runr = require('../src/task/runr') var execa = require('../src/cli/execa-commands') var spawn = require('../src/cli/spawn-commands') var concur = require('../src/async/concurrent').each var glob = require('../src/glob/globby') var map = require('../src/array/map') var segments = require('../src/path/segments') function execute (dir) { var files = map(glob.sync([`${dir}/*.js`, `!${dir}/lint*.js`]), mapr) execa(files, opts(dir)) } function mapr (v, k) { return {cmd: 'node', args: [segments.last(v)]} } function opts (dir) { return {cwd: dir, concurrent: false} } function arr () { execute('array') // spawn([{cmd: 'node', args: ['lint.js', '-a']}], opts('array')) // concur([ // // lint files // spawn([{cmd: 'node', args: ['lint.js', '-a']}], opts('array')), // // execute tests // execute('array') // ], () => { // // noop // }) } function async1 () { execute('async') } function func () { execute('function') } function gen () { execute('generator') } function lang () { execute('lang') } function num () { execute('number') } function obj () { execute('object') } function stamp () { execute('stamp') } function lint () { spawn([ {cmd: 'node', args: ['lint.js', '-a']} ], {cwd: 'array', concurrent: true}) spawn([ {cmd: 'node', args: ['lint.js', '-a']} ], {cwd: 'lang', concurrent: true}) } function defs () { arr() async1() func() gen() lang() num() obj() stamp() } function all () { defs() lint() } runr .task('default' , defs) .task('arr' , arr) .task('async' , async1) .task('func' , func) .task('gen' , gen) .task('lang' , lang) .task('num' , num) .task('obj' , obj) .task('stamp' , stamp) .task('lint' , lint) .task('all' , all)
JavaScript
0
@@ -688,269 +688,8 @@ y')%0A - // spawn(%5B%7Bcmd: 'node', args: %5B'lint.js', '-a'%5D%7D%5D, opts('array'))%0A // concur(%5B%0A // // lint files%0A // spawn(%5B%7Bcmd: 'node', args: %5B'lint.js', '-a'%5D%7D%5D, opts('array')),%0A // // execute tests%0A // execute('array')%0A // %5D, () =%3E %7B%0A // // noop%0A // %7D)%0A %7D%0A%0Af @@ -1095,16 +1095,19 @@ rue%7D)%0A%0A + // spawn(%5B @@ -1100,32 +1100,35 @@ %0A%0A // spawn(%5B%0A + // %7Bcmd: 'node', @@ -1146,32 +1146,35 @@ nt.js', '-a'%5D%7D%0A + // %5D, %7Bcwd: 'lang'
7ac014c44052cc19a5678aaab5ef47c674a3590f
check error message in track time-exception tests
test/track.js
test/track.js
var Mixpanel = require('../lib/mixpanel-node'), Sinon = require('sinon'), mock_now_time = new Date(2016, 1, 1).getTime();; exports.track = { setUp: function(next) { this.mixpanel = Mixpanel.init('token'); this.clock = Sinon.useFakeTimers(mock_now_time); Sinon.stub(this.mixpanel, 'send_request'); next(); }, tearDown: function(next) { this.mixpanel.send_request.restore(); this.clock.restore(); next(); }, "calls send_request with correct endpoint and data": function(test) { var event = "test", props = { key1: 'val1' }, expected_endpoint = "/track", expected_data = { event: 'test', properties: { key1: 'val1', token: 'token' } }; this.mixpanel.track(event, props); test.ok( this.mixpanel.send_request.calledWithMatch(expected_endpoint, expected_data), "track didn't call send_request with correct arguments" ); test.done(); }, "can be called with optional properties": function(test) { var expected_endpoint = "/track", expected_data = { event: 'test', properties: { token: 'token' } }; this.mixpanel.track("test"); test.ok( this.mixpanel.send_request.calledWithMatch(expected_endpoint, expected_data), "track didn't call send_request with correct arguments" ); test.done(); }, "can be called with optional callback": function(test) { var expected_endpoint = "/track", expected_data = { event: 'test', properties: { token: 'token' } }; this.mixpanel.send_request.callsArgWith(2, undefined); test.expect(1); this.mixpanel.track("test", function(e) { test.equal(e, undefined, "error should be undefined"); test.done(); }); }, "supports Date object for time": function(test) { var event = 'test', time = new Date(mock_now_time), props = { time: time }, expected_endpoint = "/track", expected_data = { event: 'test', properties: { token: 'token', time: time.getTime() / 1000, mp_lib: 'node' } }; this.mixpanel.track(event, props); test.ok( this.mixpanel.send_request.calledWithMatch(expected_endpoint, expected_data), "track didn't call send_request with correct arguments" ); test.done(); }, "supports unix timestamp for time": function(test) { var event = 'test', time = mock_now_time / 1000, props = { time: time }, expected_endpoint = "/track", expected_data = { event: 'test', properties: { token: 'token', time: time, mp_lib: 'node' } }; this.mixpanel.track(event, props); test.ok( this.mixpanel.send_request.calledWithMatch(expected_endpoint, expected_data), "track didn't call send_request with correct arguments" ); test.done(); }, "throws error if time property is older than 5 days": function(test) { var event = 'test', time = (mock_now_time - 1000 * 60 * 60 * 24 * 6) / 1000, props = { time: time }; test.throws(this.mixpanel.track.bind(this, event, props)); test.done(); }, "throws error if time is not a number or Date": function(test) { var event = 'test', props = { time: 'not a number or Date' }; test.throws(this.mixpanel.track.bind(this, event, props)); test.done(); }, "does not require time property": function(test) { var event = 'test', props = {}; test.doesNotThrow(this.mixpanel.track.bind(this, event, props)); test.done(); } };
JavaScript
0
@@ -131,17 +131,16 @@ tTime(); -; %0A%0Aexport @@ -3780,32 +3780,45 @@ test.throws( +%0A this.mixpanel.tr @@ -3837,32 +3837,185 @@ s, event, props) +,%0A /%60track%60 not allowed for event more than 5 days old/,%0A %22track didn't throw an error when time was more than 5 days ago%22%0A );%0A test. @@ -4202,16 +4202,29 @@ .throws( +%0A this.mix @@ -4251,32 +4251,182 @@ s, event, props) +,%0A /%60time%60 property must be a Date or Unix timestamp/,%0A %22track didn't throw an error when time wasn't a number or Date%22%0A );%0A test.
3d86fe9403acdf0278cc2ec42924a11db2818ecb
update comment
assets/scripts/sw/sync/push.js
assets/scripts/sw/sync/push.js
/*** * Copyright (c) 2015, 2016 Alex Grant (@localnerve), LocalNerve LLC * Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms. * * Synchronize push subscription. */ /* global Promise, fetch */ 'use strict'; var sync = require('./index'); var serviceable = require('./serviceable'); var debug = require('../utils/debug')('sync.push'); var idb = require('../utils/idb'); var requestLib = require('../utils/requests'); var syncable = require('../../../../utils/syncable'); var subscriptionService = '/_api'; /** * Get the existing subscriptionId and apiInfo for the subscription service. * * 1. Initializes the subscription.id store.key if never established. * 2. Sets the subscription.id to false if given subscriptionId is falsy. * 3. Determines if the existingId is an id and different than * the given suscriptionId. * 4. If the existingId is an id and different, gets the apiInfo for the * subscriptionService. * * @private * * @param {String} subscriptionId - The new or existing subscriptionId. * @returns {Promise} resolves to object containing: * {String} existingId - The existing subscriptionId, falsy if none found. * {Object} apiInfo - The apiInfo for the subscription service, falsy if an * api call should not be made. */ function getSubscriptionInfo (subscriptionId) { var result = {}; return idb.get(idb.stores.state, 'subscriptionId') .then(function (existingId) { result.existingId = existingId; if (existingId && subscriptionId !== existingId) { debug('reading init.apis'); return idb.get(idb.stores.init, 'apis'); } }) .then(function (apis) { if (apis) { result.apiInfo = apis[subscriptionService]; if (!result.apiInfo) { throw new Error('subscription service api info not found'); } } return result; }); } /** * Synchronize the given subscriptionId with IndexedDB and subscription * service. * * If no subscriptionId stored, store the subscriptionId. * If the given subscriptionId is different than stored, update storage and * subscription service. * If no change, no action performed. * * @param {String} subscriptionId - The new or existing subscriptionId. * If falsy, then deletes the existing subscriptionId from IndexedDB. * @returns {Promise} Resolves to undefined for del, Response, or false if no request was/will be made. */ function synchronizePushSubscription (subscriptionId) { var apiInfo, requestState, existingId; debug('synchronize push subscription', subscriptionId); if (!subscriptionId) { return idb.del(idb.stores.state, 'subscriptionId'); } return getSubscriptionInfo(subscriptionId) .then(function (result) { apiInfo = result.apiInfo; existingId = result.existingId; if (apiInfo) { // Would be great to create the body using fetchr itself. requestState = { url: apiInfo.xhrPath, method: 'POST', bodyType: 'json', body: { context: apiInfo.xhrContext, requests: { g0: { body: {}, operation: 'update', params: { subscriptionId: existingId, newId: subscriptionId }, resource: 'subscription' } } } }; return fetch(requestLib.rehydrateRequest(requestState, apiInfo)); } }) .then(function (resp) { var response = resp || {}; var updateSubscriptionId = !existingId || response.ok; // If subscription not found or service successfully updated, update // subscriptionId in IndexedDB. if (updateSubscriptionId) { return Promise.all([ serviceable.updatePushSubscription(response.ok && subscriptionId), idb.put(idb.stores.state, 'subscriptionId', subscriptionId) ]) .then(function () { debug('successfully updated subscriptionId'); return resp ? response : false; }); } if (response.ok === false) { debug('fetch failed (' + response.status + '), ' + response.statusText); // Add syncable property to body requestState.body = syncable.push( requestState.body, subscriptionId, syncable.ops.updateSubscription ); return sync.deferRequest( subscriptionService, requestLib.rehydrateRequest(requestState, apiInfo) ); } }); } module.exports = { synchronize: synchronizePushSubscription };
JavaScript
0
@@ -632,155 +632,8 @@ *%0A * - 1. Initializes the subscription.id store.key if never established.%0A * 2. Sets the subscription.id to false if given subscriptionId is falsy.%0A * 3. Det @@ -688,19 +688,16 @@ than%0A * - the giv @@ -720,11 +720,8 @@ .%0A * - 4. If @@ -786,19 +786,16 @@ r the%0A * - subscri
3c5725e7af9452f383f39b4f53b5908805e095b6
fix Buffer tests to work in node < 4.5 and node < 5.10
test/utils.js
test/utils.js
'use strict'; var test = require('tape'); var inspect = require('object-inspect'); var SaferBuffer = require('safer-buffer').Buffer; var forEach = require('for-each'); var utils = require('../lib/utils'); test('merge()', function (t) { t.deepEqual(utils.merge(null, true), [null, true], 'merges true into null'); t.deepEqual(utils.merge(null, [42]), [null, 42], 'merges null into an array'); t.deepEqual(utils.merge({ a: 'b' }, { a: 'c' }), { a: ['b', 'c'] }, 'merges two objects with the same key'); var oneMerged = utils.merge({ foo: 'bar' }, { foo: { first: '123' } }); t.deepEqual(oneMerged, { foo: ['bar', { first: '123' }] }, 'merges a standalone and an object into an array'); var twoMerged = utils.merge({ foo: ['bar', { first: '123' }] }, { foo: { second: '456' } }); t.deepEqual(twoMerged, { foo: { 0: 'bar', 1: { first: '123' }, second: '456' } }, 'merges a standalone and two objects into an array'); var sandwiched = utils.merge({ foo: ['bar', { first: '123', second: '456' }] }, { foo: 'baz' }); t.deepEqual(sandwiched, { foo: ['bar', { first: '123', second: '456' }, 'baz'] }, 'merges an object sandwiched by two standalones into an array'); var nestedArrays = utils.merge({ foo: ['baz'] }, { foo: ['bar', 'xyzzy'] }); t.deepEqual(nestedArrays, { foo: ['baz', 'bar', 'xyzzy'] }); var noOptionsNonObjectSource = utils.merge({ foo: 'baz' }, 'bar'); t.deepEqual(noOptionsNonObjectSource, { foo: 'baz', bar: true }); t.test( 'avoids invoking array setters unnecessarily', { skip: typeof Object.defineProperty !== 'function' }, function (st) { var setCount = 0; var getCount = 0; var observed = []; Object.defineProperty(observed, 0, { get: function () { getCount += 1; return { bar: 'baz' }; }, set: function () { setCount += 1; } }); utils.merge(observed, [null]); st.equal(setCount, 0); st.equal(getCount, 1); observed[0] = observed[0]; // eslint-disable-line no-self-assign st.equal(setCount, 1); st.equal(getCount, 2); st.end(); } ); t.end(); }); test('assign()', function (t) { var target = { a: 1, b: 2 }; var source = { b: 3, c: 4 }; var result = utils.assign(target, source); t.equal(result, target, 'returns the target'); t.deepEqual(target, { a: 1, b: 3, c: 4 }, 'target and source are merged'); t.deepEqual(source, { b: 3, c: 4 }, 'source is untouched'); t.end(); }); test('combine()', function (t) { t.test('both arrays', function (st) { var a = [1]; var b = [2]; var combined = utils.combine(a, b); st.deepEqual(a, [1], 'a is not mutated'); st.deepEqual(b, [2], 'b is not mutated'); st.notEqual(a, combined, 'a !== combined'); st.notEqual(b, combined, 'b !== combined'); st.deepEqual(combined, [1, 2], 'combined is a + b'); st.end(); }); t.test('one array, one non-array', function (st) { var aN = 1; var a = [aN]; var bN = 2; var b = [bN]; var combinedAnB = utils.combine(aN, b); st.deepEqual(b, [bN], 'b is not mutated'); st.notEqual(aN, combinedAnB, 'aN + b !== aN'); st.notEqual(a, combinedAnB, 'aN + b !== a'); st.notEqual(bN, combinedAnB, 'aN + b !== bN'); st.notEqual(b, combinedAnB, 'aN + b !== b'); st.deepEqual([1, 2], combinedAnB, 'first argument is array-wrapped when not an array'); var combinedABn = utils.combine(a, bN); st.deepEqual(a, [aN], 'a is not mutated'); st.notEqual(aN, combinedABn, 'a + bN !== aN'); st.notEqual(a, combinedABn, 'a + bN !== a'); st.notEqual(bN, combinedABn, 'a + bN !== bN'); st.notEqual(b, combinedABn, 'a + bN !== b'); st.deepEqual([1, 2], combinedABn, 'second argument is array-wrapped when not an array'); st.end(); }); t.test('neither is an array', function (st) { var combined = utils.combine(1, 2); st.notEqual(1, combined, '1 + 2 !== 1'); st.notEqual(2, combined, '1 + 2 !== 2'); st.deepEqual([1, 2], combined, 'both arguments are array-wrapped when not an array'); st.end(); }); t.end(); }); test('isBuffer()', function (t) { forEach([null, undefined, true, false, '', 'abc', 42, 0, NaN, {}, [], function () {}, /a/g], function (x) { t.equal(utils.isBuffer(x), false, inspect(x) + ' is not a buffer'); }); var fakeBuffer = { constructor: Buffer }; t.equal(utils.isBuffer(fakeBuffer), false, 'fake buffer is not a buffer'); var saferBuffer = SaferBuffer.from('abc'); t.equal(utils.isBuffer(saferBuffer), true, 'SaferBuffer instance is a buffer'); var buffer = Buffer.from('abc'); t.equal(utils.isBuffer(buffer), true, 'real Buffer instance is a buffer'); t.end(); });
JavaScript
0.000001
@@ -4942,32 +4942,66 @@ er = Buffer.from + ? Buffer.from('abc') : new Buffer ('abc');%0A t.e
786ce2b0f4b6bfe1a6b85e9a9a6f241e53fe43d9
remove console.log at start
testrunner.js
testrunner.js
/** * */ console.log(trace); var sites = [{ "url":"http://newspoverty.geolive.ca", "test":"http://newspoverty.geolive.ca/unitest.js" }]; console.log('Hello World'); phantom.exit(0); sites.forEach(function(site){ var url=site.url; var test=site.test; console.log('testing: '+url+' with: '+test); var page = require('webpage').create(); page.onError=function(msg, trace){ console.log('error: '+ msg); console.log(trace); phantom.exit(1); }; page.onConsoleMessage = function(msg, lineNum, sourceId) { console.log('CONSOLE: ' + msg ); }; page.open(url), function(status) { console.log("Status: " + status); if(status === "success") { setTimeout(function(){ try{ var status=page.evaluate(function(){ console.log("Parsing Qunit output"); var result={ failed:parseInt($$('span.failed')[0].innerHTML), passed:parseInt($$('span.passed')[0].innerHTML), total:parseInt($$('span.total')[0].innerHTML), errors:[], configs:Object.keys(UIFormManager._forms) }; $$('li li.fail').forEach(function(l){ result.errors.push(l.textContent); }); return result; }); console.log(JSON.stringify(status)); }catch(e){ console.log('Exception parsing qunit results'); } phantom.exit(status.failed); }, 10000); console.log('waiting for 10s - to ensure qunit completes'); }else{ phantom.exit(1); } }); });
JavaScript
0.000001
@@ -5,35 +5,16 @@ * %0A */%0A -console.log(trace); %0A%0Avar si
d83569df0fd4e34ee2210859ea2d0de8a61d8668
remove references to legacy relations
tests/main.js
tests/main.js
var expect = require('expect.js'); require('source-map-support').install(); describe('main module', function () { it('should be able to load using require', function () { var objection = require('../'); expect(objection.Model).to.equal(require('../lib/model/Model').default); expect(objection.ModelBase).to.equal(require('../lib/model/ModelBase').default); expect(objection.QueryBuilder).to.equal(require('../lib/queryBuilder/QueryBuilder').default); expect(objection.QueryBuilderBase).to.equal(require('../lib/queryBuilder/QueryBuilderBase').default); expect(objection.QueryBuilderOperation).to.equal(require('../lib/queryBuilder/operations/QueryBuilderOperation').default); expect(objection.RelationExpression).to.equal(require('../lib/queryBuilder/RelationExpression').default); expect(objection.ValidationError).to.equal(require('../lib/ValidationError').default); expect(objection.Relation).to.equal(require('../lib/relations/Relation').default); expect(objection.HasManyRelation).to.equal(require('../lib/relations/hasMany/HasManyRelation').default); expect(objection.HasOneRelation).to.equal(require('../lib/relations/hasOne/HasOneRelation').default); expect(objection.BelongsToOneRelation).to.equal(require('../lib/relations/belongsToOne/BelongsToOneRelation').default); expect(objection.OneToManyRelation).to.equal(require('../lib/relations/hasMany/HasManyRelation').default); expect(objection.OneToOneRelation).to.equal(require('../lib/relations/belongsToOne/BelongsToOneRelation').default); expect(objection.ManyToManyRelation).to.equal(require('../lib/relations/manyToMany/ManyToManyRelation').default); expect(objection.transaction).to.equal(require('../lib/transaction').default); expect(objection.transaction.start).to.equal(require('../lib/transaction').default.start); expect(objection.Promise).to.equal(require('bluebird')); }); });
JavaScript
0
@@ -1329,239 +1329,8 @@ t);%0A - expect(objection.OneToManyRelation).to.equal(require('../lib/relations/hasMany/HasManyRelation').default);%0A expect(objection.OneToOneRelation).to.equal(require('../lib/relations/belongsToOne/BelongsToOneRelation').default);%0A
2eeef5c7e6de27fd5061a9d169f1f644a7722d5d
Add security question tests (partially disabled)
test/client/forgotpasswordControllerSpec.js
test/client/forgotpasswordControllerSpec.js
describe('controllers', function () { var scope, controller, $httpBackend beforeEach(module('juiceShop')) beforeEach(inject(function ($injector) { $httpBackend = $injector.get('$httpBackend') $httpBackend.whenGET(/\/i18n\/.*\.json/).respond(200, {}) })) afterEach(function () { $httpBackend.verifyNoOutstandingExpectation() }) describe('ForgotPasswordController', function () { beforeEach(inject(function ($rootScope, $location, $controller) { scope = $rootScope.$new() controller = $controller('ForgotPasswordController', { '$scope': scope }) })) it('should be defined', inject(function () { expect(controller).toBeDefined() expect(scope.resetPassword).toBeDefined() expect(scope.findSecurityQuestion).toBeDefined() })) it('should clear form and show confirmation after changing password', inject(function () { $httpBackend.whenPOST('/rest/user/reset-password').respond(200, {user: {}}) scope.email = 'foobar' scope.securityQuestion = 'foobar?' scope.securityAnswer = 'foobar!' scope.newPassword = 'foobar' scope.newPasswordRepeat = 'foobar' scope.form = {$setPristine: function () {}} scope.resetPassword() $httpBackend.flush() expect(scope.email).toBeUndefined() expect(scope.securityQuestion).toBeUndefined() expect(scope.securityAnswer).toBeUndefined() expect(scope.newPassword).toBeUndefined() expect(scope.newPasswordRepeat).toBeUndefined() expect(scope.confirmation).toBeDefined() })) it('should clear form and gracefully handle error on password change', inject(function () { $httpBackend.whenPOST('/rest/user/reset-password').respond(500, 'error') scope.email = 'foobar' scope.securityQuestion = 'foobar?' scope.securityAnswer = 'foobar!' scope.newPassword = 'foobar' scope.newPasswordRepeat = 'foobar' scope.form = {$setPristine: function () {}} scope.resetPassword() $httpBackend.flush() expect(scope.email).toBeUndefined() expect(scope.securityQuestion).toBeUndefined() expect(scope.securityAnswer).toBeUndefined() expect(scope.newPassword).toBeUndefined() expect(scope.newPasswordRepeat).toBeUndefined() expect(scope.error).toBe('error') })) }) })
JavaScript
0.000001
@@ -2340,16 +2340,1088 @@ %0A %7D)) +%0A%0A xit('should find the security question of a user with a known email address', inject(function () %7B%0A $httpBackend.whenGET('rest/user/security-question?email=known@user.test').respond(200, %7B question: 'What is your favorite test tool?' %7D)%0A scope.email = 'known@user.test'%0A%0A scope.findSecurityQuestion()%0A $httpBackend.flush()%0A%0A expect(scope.securityQuestion).toBe('What is your favorite test tool?')%0A %7D))%0A%0A xit('should not find the security question for an email address not bound to a user', inject(function () %7B%0A $httpBackend.whenGET('rest/user/security-question?email=unknown@user.test').respond(200, %7B%7D)%0A scope.email = 'unknown@user.test'%0A%0A scope.findSecurityQuestion()%0A $httpBackend.flush()%0A%0A expect(scope.securityQuestion).toBeUndefined()%0A %7D))%0A%0A it('should find not attempt to find security question for empty email address', inject(function () %7B%0A scope.email = undefined%0A%0A scope.findSecurityQuestion()%0A $httpBackend.flush()%0A%0A expect(scope.securityQuestion).toBeUndefined()%0A %7D)) %0A %7D)%0A%7D)
3eebcb16f09d5a700365327250faec68c5e9fea0
add test restart all on same ports add count (number of clients to test connect)
tests/test.js
tests/test.js
/** * */ var assert=require('assert'); assert.equal(true, true); var ws=require('ws'); function EchoTest(BridgeProxy, AutoConnectProxy, ports, callback){ //a ws server that just echos back all messages... var echo=(new ws.Server({ port: ports.echo })).on('connection', function(wsclient){ wsclient.on('message',function(message){ wsclient.send(message); console.log('endpoint echos: '+message); }) }); var basicauth=''; basicauth='nickolanack:nick'; // a bridge server. pairs clients with autoconnect proxy connections. var WSBridge=require('../bridgeproxy.js'); var bridge=new WSBridge({ port:ports.bridge, basicauth:basicauth }); var WSAuto=require('../autoconnectproxy.js'); if(basicauth.length){ basicauth=basicauth+'@'; } var autoconnect=new WSAuto({source:'ws://'+basicauth+'localhost:'+ports.bridge, destination:'ws://localhost:'+ports.echo}); var clients=0; var num=50 for(var i=0;i< num; i++){ clients++; (function(i){ var client=(new ws('ws://localhost:'+ports.bridge)).on('open', function(){ setTimeout(function(){ var tm=setTimeout(function(){ assert.fail('#'+i+' expected response by now.'); callback(true, false); }, 10000); client.on('message',function(message){ assert.equal(message, 'hello world'); console.log('test client #'+i+' recieves: hello world'); clearTimeout(tm); this.close(); clients--; if(clients==0){ setTimeout(function(){ echo.close(); autoconnect.close(); bridge.close(); callback(true, false); },100); } }); console.log('test client #'+i+' sends: hello world'); client.send('hello world'); }, i*100); }); })(i); } } var series=require("async").series( [ function(callback){ EchoTest(require('../bridgeproxy.js'), require('../autoconnectproxy.js'), {echo:9001, bridge:9002},callback); }, function(callback){ EchoTest(require('../index.js').AutoConnect, require('../index.js').Bridge, {echo:9003, bridge:9004}, callback); } ], function(err, results) { console.log(err); console.log(results); });
JavaScript
0
@@ -137,21 +137,22 @@ tProxy, -ports +config , callba @@ -245,21 +245,22 @@ %09%09port: -ports +config .echo%0A%09%7D @@ -626,21 +626,22 @@ %0A%09%09port: -ports +config .bridge, @@ -832,29 +832,30 @@ localhost:'+ -ports +config .bridge, des @@ -881,21 +881,22 @@ lhost:'+ -ports +config .echo%7D); @@ -927,10 +927,21 @@ num= -50 +config.count; %0A%09fo @@ -1038,13 +1038,14 @@ t:'+ -ports +config .bri @@ -1839,32 +1839,60 @@ tion(callback)%7B%0A + %09//test direct load%0A %09EchoTes @@ -1981,16 +1981,26 @@ dge:9002 +, count:50 %7D,callba @@ -2035,32 +2035,330 @@ tion(callback)%7B%0A + %09// test same ports - cleanup must complete%0A %09EchoTest(require('../bridgeproxy.js'), require('../autoconnectproxy.js'), %7Becho:9001, bridge:9002, count:5%7D,callback);%0A %7D,%0A function(callback)%7B%0A %09//test using index, this should be the same as require('node-rproxy')%0A %09EchoTes @@ -2449,16 +2449,25 @@ dge:9004 +, count:5 %7D, callb @@ -2481,23 +2481,16 @@ %7D - %0A
d2049e7982a02e3470321f0274a26bea846f6a84
remove done, block tests
tests/test.js
tests/test.js
/*jshint esversion: 6 */ const assert = require('assert'); const axios = require('axios'); const cheerio = require('cheerio'); describe('result crawling', function() { it('should return "Libur Nasional 2013" when the index array 0', function() { const listYears = "http://www.liburnasional.com/"; return axios.get(listYears).then(res => { var $ = cheerio.load(res.data); var root = $('.dropdown-menu').eq(0).children().children(); var years = []; root.each(function(x, y) { years.push({name: y.children[0].data, link: y.attribs.href}); }); return years; }).then(function(years) { assert.equal(years[0].name, "Libur Nasional 2013"); }); }); it('should return "Minggu", "1 Januari 2013","Tahun Baru Masehi"', function(done) { var holidays = []; return axios.get("http://www.liburnasional.com/kalender-2017/").then(res => { var $ = cheerio.load(res.data); $('.libnas-calendar-holiday-title').each(function(x, y) { holidays.push({ day : y.children[1].children[0].data, date : y.children[2].children[0].data, title : y.children[0].children[0].children[0].children[0].data, }); }); return holidays; }).then(function(holidays) { assert.equal(holidays[0].day, "Minggu"); assert.equal(holidays[0].date, "1 Januari 2017"); assert.equal(holidays[0].title, "Tahun Baru Masehi"); }); }); });
JavaScript
0
@@ -888,12 +888,8 @@ ion( -done ) %7B%0D
1dfc9ee6a1c2a3e8fb014a9e693c8a5d8b5cab0b
Handle driver not loaded cleaner
thermostat.js
thermostat.js
import cli from 'cli'; import {Gpio} from 'chip-gpio'; import sensor from 'ds18x20'; var options = cli.parse(); var interval = 2000; var threshold = 25; var heater = new Gpio(0, 'out'); function setHeater(on) { console.log('Heater:', on ? 'on' : 'off'); heater.write(on ? 0 : 1); } function setHeaterOn() { setHeater(true); } function setHeaterOff() { setHeater(false); } sensor.isDriverLoaded((err, isLoaded) => { console.log(isLoaded); sensor.list((err, listOfDeviceIds) => { console.log(listOfDeviceIds); }); setInterval(() => { sensor.getAll((err, tempObj) => { var sum = 0; var len = 0; tempObj.forEach(obj => { console.log(obj); sum += obj; len++; }); var average = sum / len; console.log(average); setHeater(average < threshold); }); }, interval); });
JavaScript
0.000001
@@ -427,31 +427,79 @@ %7B%0A -console.log(isL +if (!isLoaded) %7B%0A console.log('Driver not l oaded +' );%0A + return;%0A %7D%0A se
a5627cb1f5abf902ce44133f30f01bdc88c43057
Set _zooming=false inside _zoomEnd() for non-animated zooms.
leaflet-mapbox-gl.js
leaflet-mapbox-gl.js
L.MapboxGL = L.Layer.extend({ options: { updateInterval: 32 }, initialize: function (options) { L.setOptions(this, options); if (options.accessToken) { mapboxgl.accessToken = options.accessToken; } else { throw new Error('You should provide a Mapbox GL access token as a token option.'); } /** * Create a version of `fn` that only fires once every `time` millseconds. * * @param {Function} fn the function to be throttled * @param {number} time millseconds required between function calls * @param {*} context the value of `this` with which the function is called * @returns {Function} debounced function * @private */ var throttle = function (fn, time, context) { var lock, args, wrapperFn, later; later = function () { // reset lock and call if queued lock = false; if (args) { wrapperFn.apply(context, args); args = false; } }; wrapperFn = function () { if (lock) { // called too soon, queue to call later args = arguments; } else { // call and lock until later fn.apply(context, arguments); setTimeout(later, time); lock = true; } }; return wrapperFn; }; // setup throttling the update event when panning this._throttledUpdate = throttle(L.Util.bind(this._update, this), this.options.updateInterval); }, onAdd: function (map) { if (!this._glContainer) { this._initContainer(); } map._panes.tilePane.appendChild(this._glContainer); this._initGL(); this._offset = this._map.containerPointToLayerPoint([0, 0]); // work around https://github.com/mapbox/mapbox-gl-leaflet/issues/47 if (map.options.zoomAnimation) { L.DomEvent.on(map._proxy, L.DomUtil.TRANSITION_END, this._transitionEnd, this); } }, onRemove: function (map) { if (this._map.options.zoomAnimation) { L.DomEvent.off(this._map._proxy, L.DomUtil.TRANSITION_END, this._transitionEnd, this); } map.getPanes().tilePane.removeChild(this._glContainer); this._glMap.remove(); this._glMap = null; }, getEvents: function () { return { move: this._throttledUpdate, // sensibly throttle updating while panning zoomanim: this._animateZoom, // applys the zoom animation to the <canvas> zoom: this._pinchZoom, // animate every zoom event for smoother pinch-zooming zoomstart: this._zoomStart, // flag starting a zoom to disable panning zoomend: this._zoomEnd }; }, _initContainer: function () { var container = this._glContainer = L.DomUtil.create('div', 'leaflet-gl-layer'); var size = this._map.getSize(); container.style.width = size.x + 'px'; container.style.height = size.y + 'px'; }, _initGL: function () { var center = this._map.getCenter(); var options = L.extend({}, this.options, { container: this._glContainer, interactive: false, center: [center.lng, center.lat], zoom: this._map.getZoom() - 1, attributionControl: false }); this._glMap = new mapboxgl.Map(options); // allow GL base map to pan beyond min/max latitudes this._glMap.transform.latRange = null; // treat child <canvas> element like L.ImageOverlay L.DomUtil.addClass(this._glMap._canvas, 'leaflet-image-layer'); L.DomUtil.addClass(this._glMap._canvas, 'leaflet-zoom-animated'); }, _update: function (e) { // update the offset so we can correct for it later when we zoom this._offset = this._map.containerPointToLayerPoint([0, 0]); if (this._zooming) { return; } var size = this._map.getSize(), container = this._glContainer, gl = this._glMap, topLeft = this._map.containerPointToLayerPoint([0, 0]); L.DomUtil.setPosition(container, topLeft); var center = this._map.getCenter(); // gl.setView([center.lat, center.lng], this._map.getZoom() - 1, 0); // calling setView directly causes sync issues because it uses requestAnimFrame var tr = gl.transform; tr.center = mapboxgl.LngLat.convert([center.lng, center.lat]); tr.zoom = this._map.getZoom() - 1; if (gl.transform.width !== size.x || gl.transform.height !== size.y) { container.style.width = size.x + 'px'; container.style.height = size.y + 'px'; if (gl._resize !== null && gl._resize !== undefined){ gl._resize(); } else { gl.resize(); } } else { gl._update(); } }, // update the map constantly during a pinch zoom _pinchZoom: function (e) { this._glMap.jumpTo({ zoom: this._map.getZoom() - 1, center: this._map.getCenter() }); }, // borrowed from L.ImageOverlay https://github.com/Leaflet/Leaflet/blob/master/src/layer/ImageOverlay.js#L139-L144 _animateZoom: function (e) { var scale = this._map.getZoomScale(e.zoom), offset = this._map._latLngToNewLayerPoint(this._map.getBounds().getNorthWest(), e.zoom, e.center); L.DomUtil.setTransform(this._glMap._canvas, offset.subtract(this._offset), scale); }, _zoomStart: function (e) { this._zooming = true; }, _zoomEnd: function () { var scale = this._map.getZoomScale(this._map.getZoom()), offset = this._map._latLngToNewLayerPoint(this._map.getBounds().getNorthWest(), this._map.getZoom(), this._map.getCenter()); L.DomUtil.setTransform(this._glMap._canvas, offset.subtract(this._offset), scale); }, _transitionEnd: function (e) { L.Util.requestAnimFrame(function () { var zoom = this._map.getZoom(), center = this._map.getCenter(), offset = this._map.latLngToContainerPoint(this._map.getBounds().getNorthWest()); // reset the scale and offset L.DomUtil.setTransform(this._glMap._canvas, offset, 1); // enable panning once the gl map is ready again this._glMap.once('moveend', L.Util.bind(function () { this._zooming = false; this._zoomEnd(); }, this)); // update the map position this._glMap.jumpTo({ center: center, zoom: zoom - 1 }); }, this); } }); L.mapboxGL = function (options) { return new L.MapboxGL(options); };
JavaScript
0
@@ -6196,32 +6196,62 @@ offset), scale); +%0A%0A this._zooming = false; %0A %7D,%0A%0A _tr @@ -6732,45 +6732,8 @@ ) %7B%0A - this._zooming = false;%0A
63a56ad9e5fa1ec9ebb485dfcc3422bcdc72e15c
removed timer from component. not used
src/Timer/TimerEditWidget.js
src/Timer/TimerEditWidget.js
import React, { Component } from 'react'; import TimerDashboardWidget from './TimerDashboardWidget'; import TimerNew from './TimerNew'; class TimerEditWidget extends Component { constructor() { super(); // super() must be called in our constructor. // Initial state. this.state = { widgetIsOpen: true, widgetTitle: 'New Timer', timerSavedConfirmation: false, timer: {} // We manage the current timer here, only! }; } _openWidget() { this.setState({widgetIsOpen: true}); } _afterOpenWidget() { // references are now sync'd and can be accessed. // this.refs.subtitle.style.color = 'red'; } _closeWidget() { this.setState({widgetIsOpen: false, timerSavedConfirmation: false}); } render() { return ( <TimerDashboardWidget isOpen={this.state.widgetIsOpen} onAfterOpen={this._afterOpenWidget.bind(this)} onRequestOpen={this._openWidget.bind(this)} onRequestClose={this._closeWidget.bind(this)} title={this.state.widgetTitle}> <TimerNew /> </TimerDashboardWidget> ); } } export default TimerEditWidget;
JavaScript
0.999569
@@ -206,54 +206,8 @@ r(); - // super() must be called in our constructor. %0A%0A @@ -344,67 +344,8 @@ se,%0A - timer: %7B%7D // We manage the current timer here, only!%0A
32ed71e9483bb291fd10a18a7e3ab6699772925d
throw on multiple calls to `observe` on the same cursor
lib/client/cursor.js
lib/client/cursor.js
/* eslint-disable no-param-reassign */ // eslint-disable-next-line no-unused-vars var LoggerFactory = require('slf').LoggerFactory; var uuid = require('node-uuid').v4; var Logger = require('slf').Logger; var LOG = Logger.getLogger('lx:viewdb-persistence-store-remote'); var _ = require('lodash'); var Cursor = require('viewdb').Cursor; var util = require('util'); var Observer = require('./observe'); var RemoteCursor = function (collection, query, options, getDocuments) { Cursor.call(this, collection, query, options, getDocuments); }; util.inherits(RemoteCursor, Cursor); RemoteCursor.prototype.count = function (applySkipLimit, options, callback) { if (_.isFunction(applySkipLimit)) { callback = applySkipLimit; applySkipLimit = true; } if (_.isFunction(options)) { callback = options; options = {}; } var skip = _.get(this, '_query.skip', _.get(options, 'skip', 0)); var limit = _.get(this, '_query.limit', _.get(options, 'limit', 0)); var params = { id: uuid(), count: this._query.query || this._query, collection: this._collection._name }; if (applySkipLimit) { params.skip = skip; params.limit = limit; } this._collection._client.request(params, function (err, result) { callback(err, result); }); }; RemoteCursor.prototype.sort = function (params) { this._query.sort = params; this._refresh(); return this; }; RemoteCursor.prototype.project = function (params) { this._query.project = params; return this; }; RemoteCursor.prototype._refresh = function () { this._collection.emit('change'); }; RemoteCursor.prototype.observe = function (options) { var self = this; var refreshListener = function () { LOG.info('restarting observer due to change'); self._handle.stop(); self._handle = new Observer(self._collection, options, self._query); } self._collection.on("change", refreshListener); self._handle = new Observer(self._collection, options, self._query); return { stop: function () { self._handle.stop(); self._collection.removeListener("change", refreshListener); } }; }; module.exports = RemoteCursor;
JavaScript
0
@@ -1656,16 +1656,300 @@ = this; +%0A if (self._isObserving) %7B%0A LOG.error('Already observing this cursor. Collection: %25s - Query: %25j', _.get(self, '_collection._name'), self._query)%0A throw new Error('Already observing this cursor. Collection: ' + _.get(self, '_collection._name'));%0A %7D%0A self._isObserving = true; %0A%0A var
cb9761f9a9f2024f46912a09cadb429eabdf93ee
Support Blaze._getTemplate API.
lib/client/layout.js
lib/client/layout.js
var currentLayoutName = null; var currentLayout = null; var currentRegions = new ReactiveDict(); var currentData; var _isReady = false; BlazeLayout.setRoot = function(root) { BlazeLayout._root = root; }; BlazeLayout.render = function render(layout, regions) { regions = regions || {}; Meteor.startup(function() { // To make sure dom is loaded before we do rendering layout. // Related to issue #25 if(!_isReady) { Meteor.defer(function() { _isReady = true; BlazeLayout._render(layout, regions) }); } else { BlazeLayout._render(layout, regions); } }); }; BlazeLayout.reset = function reset() { var layout = currentLayout; if(layout) { if(layout._domrange) { // if it's rendered let's remove it right away Blaze.remove(layout); } else { // if not let's remove it when it rendered layout.onViewReady(function() { Blaze.remove(layout); }); } currentLayout = null; currentLayoutName = null; currentRegions = new ReactiveDict(); } }; BlazeLayout._regionsToData = function _regionsToData(regions, data) { data = data || {}; _.each(regions, function(value, key) { currentRegions.set(key, value); data[key] = BlazeLayout._buildRegionGetter(key); }); return data; }; BlazeLayout._updateRegions = function _updateRegions(regions) { var needsRerender = false; // unset removed regions from the exiting data _.each(currentData, function(value, key) { if(regions[key] === undefined) { currentRegions.set(key, undefined); delete currentData[key]; } }); _.each(regions, function(value, key) { // if this key does not yet exist then blaze // has no idea about this key and it won't get the value of this key // so, we need to force a re-render if(currentData && currentData[key] === undefined) { needsRerender = true; // and, add the data function for this new key currentData[key] = BlazeLayout._buildRegionGetter(key); } currentRegions.set(key, value); }); // force re-render if we need to if(currentLayout && needsRerender) { currentLayout.dataVar.dep.changed(); } }; BlazeLayout._getRootDomNode = function _getRootDomNode() { var root = BlazeLayout._root if(!root) { root = $('<div id="__blaze-root"></div>'); $('body').append(root); BlazeLayout.setRoot(root); } // We need to use $(root) here because when calling BlazeLayout.setRoot(), // there won't have any available DOM elements // So, we need to defer that. var domNode = $(root).get(0); if(!domNode) { throw new Error("Root element does not exist"); } return domNode; }; BlazeLayout._buildRegionGetter = function _buildRegionGetter(key) { return function() { return currentRegions.get(key); }; }; BlazeLayout._render = function _render(layout, regions) { var rootDomNode = BlazeLayout._getRootDomNode(); if(currentLayoutName != layout) { // remove old view BlazeLayout.reset(); currentData = BlazeLayout._regionsToData(regions); currentLayout = Blaze._TemplateWith(currentData, function() { return Spacebars.include(Template[layout]); }); Blaze.render(currentLayout, rootDomNode); currentLayoutName = layout; } else { BlazeLayout._updateRegions(regions); } };
JavaScript
0
@@ -2819,24 +2819,563 @@ );%0A %7D;%0A%7D;%0A%0A +BlazeLayout._getTemplate = function (layout, rootDomNode) %7B%0A if (Blaze._getTemplate) %7B%0A // if Meteor 1.2%0A return Blaze._getTemplate(layout, function () %7B%0A var view = Blaze.getView(rootDomNode);%0A // find the closest view with a template instance%0A while (view && !view._templateInstance) %7B%0A view = view.originalParentView %7C%7C view.parentView;%0A %7D%0A // return found template instance, or null%0A return (view && view._templateInstance) %7C%7C null;%0A %7D);%0A %7D%0A else %7B%0A return Template%5Blayout%5D;%0A %7D%0A%7D;%0A%0A BlazeLayout. @@ -3416,24 +3416,24 @@ regions) %7B%0A - var rootDo @@ -3708,24 +3708,40 @@ include( +BlazeLayout._get Template %5Blayout%5D @@ -3732,24 +3732,37 @@ Template -%5B +( layout -%5D +, rootDomNode) );%0A %7D
a7d40ba8f47b822c5fa331b6c7012099055fedb3
Clarify the description of --filter option
lib/commands/test.js
lib/commands/test.js
'use strict'; var Command = require('../models/command'); var Watcher = require('../models/watcher'); var Builder = require('../models/builder'); var fs = require('fs'); var path = require('path'); module.exports = Command.extend({ name: 'test', aliases: ['test', 't'], description: 'Runs your apps test suite.', availableOptions: [ { name: 'environment', type: String, default: 'test', aliases: ['e'] }, { name: 'config-file', type: String, default: './testem.json', aliases: ['c', 'cf'] }, { name: 'server', type: Boolean, default: false, aliases: ['s'] }, { name: 'port', type: Number, default: 7357, description: 'The port to use when running with --server.', aliases: ['p'] }, { name: 'filter', type: String, description: 'A regex to filter tests ran', aliases: ['f'] }, { name: 'module', type: String, description: 'The name of a test module to run', aliases: ['m'] }, { name: 'watcher', type: String, default: 'events', aliases: ['w'] }, ], init: function() { this.assign = require('lodash-node/modern/objects/assign'); this.quickTemp = require('quick-temp'); this.Builder = this.Builder || Builder; this.Watcher = this.Watcher || Watcher; if (!this.testing) { process.env.EMBER_CLI_TEST_COMMAND = true; } }, tmp: function() { return this.quickTemp.makeOrRemake(this, '-testsDist'); }, rmTmp: function() { this.quickTemp.remove(this, '-testsDist'); this.quickTemp.remove(this, '-customConfigFile'); }, _generateCustomConfigFile: function(options) { if (!options.filter && !options.module) { return options.configFile; } var tmpPath = this.quickTemp.makeOrRemake(this, '-customConfigFile'); var customPath = path.join(tmpPath, 'testem.json'); var originalContents = JSON.parse(fs.readFileSync(options.configFile, { encoding: 'utf8' })); var containsQueryString = originalContents['test_page'].indexOf('?') > -1; var testPageJoinChar = containsQueryString ? '&' : '?'; originalContents['test_page'] = originalContents['test_page'] + testPageJoinChar + this.buildTestPageQueryString(options); fs.writeFileSync(customPath, JSON.stringify(originalContents)); return customPath; }, buildTestPageQueryString: function(options) { var params = []; if (options.module) { params.push('module=' + options.module); } if (options.filter) { params.push('filter=' + options.filter); } return params.join('&'); }, run: function(commandOptions) { var outputPath = this.tmp(); var testOptions = this.assign({}, commandOptions, { outputPath: outputPath, project: this.project, configFile: this._generateCustomConfigFile(commandOptions) }); var options = { ui: this.ui, analytics: this.analytics, project: this.project }; if (commandOptions.server) { options.builder = new this.Builder(testOptions); var TestServerTask = this.tasks.TestServer; var testServer = new TestServerTask(options); testOptions.watcher = new this.Watcher(this.assign(options, { verbose: false, options: commandOptions })); return testServer.run(testOptions) .finally(this.rmTmp.bind(this)); } else { var TestTask = this.tasks.Test; var BuildTask = this.tasks.Build; var test = new TestTask(options); var build = new BuildTask(options); return build.run({ environment: commandOptions.environment, outputPath: outputPath }) .then(function() { return test.run(testOptions); }) .finally(this.rmTmp.bind(this)); } } });
JavaScript
0.999999
@@ -785,13 +785,14 @@ 'A -regex +string to @@ -804,18 +804,21 @@ r tests -ra +to ru n', alia
b7ed0728db81e48f15e7a6f25f58e847311909d4
remove waterline logging for #147
lib/common/logger.js
lib/common/logger.js
// Copyright 2014, Renasar Technologies Inc. /* jshint node: true, newcap: false */ 'use strict'; var di = require('di'); var os = require('os'); module.exports = loggerFactory; di.annotate(loggerFactory, new di.Provide('Logger')); di.annotate(loggerFactory, new di.Inject( 'Constants', 'Assert', 'Protocol.Logging', 'LogEvent', 'Services.Waterline', 'Services.Configuration', 'Tracer', 'Q', '_', 'Util' ) ); /** * loggerFactory returns a Logger instance. * @private * @param {postal} postal Postal Instance. * * @param {configuration} configuration Configuration Instance. * * @param {Q} Q Q Instance. * * @param {di.Injector} injector Dependency Injector. * @return {Logger} a Logger instance. */ function loggerFactory( Constants, assert, loggingProtocol, LogEvent, waterline, configuration, tracer, Q, _, util ) { var levels = _.keys(Constants.Logging.Levels); /** * Logger is a logger class which provides methods for logging based * on log levels with mesages & metadata provisions. The Logger sends * all log method calls to the logger postal channel for consumption by other * services. * logger.info('Your message here...', { hello: 'world', arbitrary: 'meta data object'}); * @constructor */ function Logger (module) { var provides = util.provides(module); if (provides !== undefined) { this.module = provides; } else { if (_.isFunction(module)) { this.module = module.name; } else { this.module = module || 'No Module'; } } } /** * _log * @param {string} level Log Level * @param {string} message Log Message * @param {object} metadata Log Metadata (Optional) * @private */ Logger.prototype.log = function (level, message, context) { var self = this; assert.isIn(level, levels); assert.string(message, 'message'); return LogEvent.create( self.module, level, message, context || {} ).then(function (log) { return log.print(); }).then(function (log) { loggingProtocol.publishLog(log.level, log); return log; }).then(function(log) { return waterline.logs.create({ module: self.module, level: level, message: message, context: log.context, trace: log.trace, timestamp: log.timestamp, caller: log.caller, subject: log.subject, host: os.hostname() }).catch(function(error) { /* istanbul ignore next */ console.log("Error persisting log message: " + error); }); }).catch(function (error) { /* istanbul ignore next */ console.log(error); /* istanbul ignore next */ console.log(error.stack); }); }; // Iterate the available levels and create the appropriate prototype function. _.keys(Constants.Logging.Levels).forEach(function(level) { /** * level - Helper method to allow logging by using the specific level * as the method instead of calling log directly. * @param {string} message Log Message * @param {object} metadata Log Metadata (Optional) */ Logger.prototype[level] = function (message, context) { this.log(level, message, context); }; }); Logger.initialize = function (module) { return new Logger(module); }; return Logger; }
JavaScript
0
@@ -2362,577 +2362,8 @@ og;%0A - %7D).then(function(log) %7B%0A return waterline.logs.create(%7B%0A module: self.module,%0A level: level,%0A message: message,%0A context: log.context,%0A trace: log.trace,%0A timestamp: log.timestamp,%0A caller: log.caller,%0A subject: log.subject,%0A host: os.hostname()%0A %7D).catch(function(error) %7B%0A /* istanbul ignore next */%0A console.log(%22Error persisting log message: %22 + error);%0A %7D);%0A
f502891cde3f7f8ec17d05c6b1a0205c83f50e72
Revert OPT output changes for LDC
lib/compilers/ldc.js
lib/compilers/ldc.js
// Copyright (c) 2016, Matt Godbolt // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. const BaseCompiler = require('../base-compiler'), argumentParsers = require("./argument-parsers"), compilerOptInfo = require("compiler-opt-info"), fs = require('fs-extra'), logger = require('./../logger').logger; class LDCCompiler extends BaseCompiler { constructor(info, env) { super(info, env); this.compiler.supportsIntel = true; } optionsForFilter(filters, outputFilename) { let options = ['-g', '-of', this.filename(outputFilename)]; if (filters.intel && !filters.binary) options = options.concat('-x86-asm-syntax=intel'); if (!filters.binary) options = options.concat('-output-s'); return options; } getArgumentParser() { return argumentParsers.Clang; } filterUserOptions(userOptions) { return userOptions.filter(option => option !== '-run'); } isCfgCompiler() { return true; } couldSupportASTDump(version) { const versionRegex = /\((\d\.\d+)\.\d+/; const versionMatch = versionRegex.exec(version); if (versionMatch) { const versionNum = parseFloat(versionMatch[1]); return versionNum >= 1.4; } return false; } generateAST(inputFilename, options) { // These options make LDC produce an AST dump in a separate file `<inputFilename>.cg`. let newOptions = options.concat("-vcg-ast"); let execOptions = this.getDefaultExecOptions(); return this.runCompiler(this.compiler.exe, newOptions, this.filename(inputFilename), execOptions) .then(this.loadASTOutput); } loadASTOutput(output) { // Load the AST output from the `.cg` file. // Demangling is not needed. const astFilename = output.inputFilename.concat(".cg"); if (!fs.existsSync(astFilename)) { logger.warn(`LDC AST file ${astFilename} requested but it does not exist`); return ""; } return fs.readFileSync(astFilename, 'utf-8'); } processOptOutput(hasOptOutput, optPath) { let output = []; return new Promise(resolve => { fs.createReadStream(optPath, {encoding: "utf-8"}) .pipe(new compilerOptInfo.LLVMOptTransformer()) .on("data", opt => { if (opt.DebugLoc && opt.DebugLoc.File && opt.DebugLoc.File.indexOf(this.compileFilename) > -1) { output.push(opt); } }) .on("end", () => resolve(output)); }); } } module.exports = LDCCompiler;
JavaScript
0
@@ -1481,60 +1481,8 @@ %22),%0A - compilerOptInfo = require(%22compiler-opt-info%22),%0A @@ -3354,552 +3354,8 @@ %7D -%0A%0A processOptOutput(hasOptOutput, optPath) %7B%0A let output = %5B%5D;%0A return new Promise(resolve =%3E %7B%0A fs.createReadStream(optPath, %7Bencoding: %22utf-8%22%7D)%0A .pipe(new compilerOptInfo.LLVMOptTransformer())%0A .on(%22data%22, opt =%3E %7B%0A if (opt.DebugLoc && opt.DebugLoc.File && opt.DebugLoc.File.indexOf(this.compileFilename) %3E -1) %7B%0A output.push(opt);%0A %7D%0A %7D)%0A .on(%22end%22, () =%3E resolve(output));%0A %7D);%0A %7D %0A%7D%0A%0A
71d88d3ead78dc17fc5f4e7000c37fc798f23ebe
allow connectFridge to pass null or undefined if not pre-fetch is needed
lib/connectFridge.js
lib/connectFridge.js
import React, { Component } from 'react' import PropTypes from 'prop-types' import hoistNonReactStatics from 'hoist-non-react-statics' export default getProps => ComposedComponent => { let id class Fridge extends Component { static contextTypes = { fridge: PropTypes.object.isRequired, store: PropTypes.object.isRequired } state = {props: null} constructor (props, context) { super(props, context) const {store} = context id = store.getNextId() this.state = {props: store.get(id) || null} } getFridgeProps = async () => { const {fridge, store} = this.context const props = await getProps({fridge, props: this.props}) if (this.unmounted) return false store.register(id, props) if (this.setState) { this.setState({props}) } return true } componentWillUnmount () { this.unmounted = true } render () { const {fridge} = this.context const props = { ...this.props, ...this.state.props, fridge } return <ComposedComponent {...props} /> } } return hoistNonReactStatics(Fridge, ComposedComponent, {}) }
JavaScript
0
@@ -586,16 +586,72 @@ () =%3E %7B%0A + if (typeof getProps !== 'function') return false%0A%0A co
c68bca5b179099ea3eb864f92597b7c4f5422ae4
Clean up logging
lib/content/image.js
lib/content/image.js
var Image = require('../image') var utils = require('../utils') module.exports = exports = function(img, opts) { var image = new ImageInstance(this, img, opts) this.contents.push(image) return this } var ImageInstance = function(doc, img, opts) { this.doc = doc.doc || doc this.image = img instanceof Image ? img : doc.createImage(img) this.opts = opts || {} } ImageInstance.prototype.render = function(page, widthLeft) { var width, height if (this.opts.width && this.opts.height) { width = this.opts.width height = this.opts.height } else if(this.opts.width) { width = this.opts.width height = this.image.height * (this.opts.width / this.image.width) } else if (this.opts.height) { height = this.opts.height width = this.image.width * (this.opts.height / this.image.height) } else { width = Math.min(this.image.width, widthLeft) height = this.image.height * (width / this.image.width) if (height > this.doc.innerHeight) { height = this.doc.innerHeight width = this.image.width * (height / this.image.height) } } console.log(width, height) // page break if (utils.round(page.spaceLeft) < utils.round(height)) { var left = page.cursor.x page = this.doc.pagebreak() page.cursor.x = left } this.image.addTo(page) var x = page.cursor.x var y = page.cursor.y - height switch (this.opts.align) { case 'right': x += widthLeft - width break case 'center': x += (widthLeft - width) / 2 break case 'left': default: break } if (this.opts.wrap === false) { x = this.opts.x || x y = this.opts.y && (this.doc.height - height - this.opts.y) || y } else { page.cursor.y = y } page.contents.writeLine('q') // save graphics state page.contents.writeLine(width + ' 0 0 ' + height + ' ' + x + ' ' + y + ' cm') // translate and scale page.contents.writeLine('/' + this.image.id + ' Do') // paint image page.contents.writeLine('Q') // restore graphics state } Object.defineProperties(ImageInstance.prototype, { maxWidth: { enumerable: true, get: function() { return this.image.width } } })
JavaScript
0
@@ -1109,38 +1109,8 @@ %7D%0A%0A - console.log(width, height)%0A%0A //
64e3ac7914046c5a5257487bdb16edb3250be24f
Add sendMessages to EventManager
lib/event-manager.js
lib/event-manager.js
'use strict'; /** * Provides an interface for communication between BEST nodes in a * BEST application. One instance is created per BEST node. */ function EventManager(stateManager, publicEvents, name) { this.stateManager = stateManager; this.publicEvents = publicEvents || {}; this.name = name; } /** * Route the given message to a public event exposed by the BEST * node associated with this instance. */ EventManager.prototype.send = function(key, message) { if (this.publicEvents[key]) { this.publicEvents[key](this.stateManager, message); } else { console.warn('No public `' + key + '` event found in ' + this.name); } }; module.exports = EventManager;
JavaScript
0
@@ -671,16 +671,229 @@ %7D%0A%7D; +%0AEventManager.prototype.sendMessage = EventManager.prototype.sendMessage;%0A%0AEventManager.prototype.sendMessages = function(messages) %7B%0A for (var key in messages) %7B%0A this.send(key, messages%5Bkey%5D);%0A %7D%0A%7D; %0A%0Amodule
cc7e6b63c111925ebdeda7d37bfcc7ef98348e76
fix tolerance
lib/expander-hook.js
lib/expander-hook.js
module.exports = ExpanderHook function ExpanderHook (needsExpand) { return expander.bind(null, needsExpand) } function expander (needsExpand, element) { var handler = { handleEvent, needsExpand, element } handleEvent.call(handler) if (element.querySelector('img')) { // just in case images are still loading setTimeout(handleEvent.bind(handler), 200) element.addEventListener('mouseover', handler) return element.removeEventListener.bind(element, 'mouseover', handler) } } function handleEvent (ev) { var { needsExpand, element } = this if (!needsExpand()) { if (element.firstElementChild && element.firstElementChild.clientHeight > element.clientHeight) { needsExpand.set(true) } } }
JavaScript
0.000004
@@ -623,37 +623,8 @@ hild - && element.firstElementChild .cli @@ -633,16 +633,20 @@ tHeight ++ 5 %3E elemen
4ae1b28ff522b8ca6a88e4778c6bacad2df5e16d
Fix handling of grid node id
lib/grid-register.js
lib/grid-register.js
import request from 'request-promise'; import { fs } from 'appium-support'; import logger from './logger'; async function registerNode (configFile, addr, port) { let data; try { data = await fs.readFile(configFile, 'utf-8'); } catch (err) { logger.error(`Unable to load node configuration file to register with grid: ${err.message}`); return; } // Check presence of data before posting it to the selenium grid if (!data) { logger.error('No data found in the node configuration file to send to the grid'); return; } await postRequest(data, addr, port); } async function registerToGrid (options_post, jsonObject) { try { let response = await request(options_post); if (response === undefined || response.statusCode !== 200) { throw new Error('Request failed'); } let logMessage = `Appium successfully registered with the grid on ${jsonObject.configuration.hubHost}:${jsonObject.configuration.hubPort}`; logger.debug(logMessage); } catch (err) { logger.error(`Request to register with grid was unsuccessful: ${err.message}`); } } async function postRequest (data, addr, port) { // parse json to get hub host and port let jsonObject; try { jsonObject = JSON.parse(data); } catch (err) { logger.errorAndThrow(`Syntax error in node configuration file: ${err.message}`); } // if the node config does not have the appium/webdriver url, host, and port, // automatically add it based on how appium was initialized // otherwise, we will take whatever the user setup // because we will always set localhost/127.0.0.1. this won't work if your // node and grid aren't in the same place if (!jsonObject.configuration.url || !jsonObject.configuration.host || !jsonObject.configuration.port) { jsonObject.configuration.url = `http://${addr}:${port}/wd/hub`; jsonObject.configuration.host = addr; jsonObject.configuration.port = port; // re-serialize the configuration with the auto populated data data = JSON.stringify(jsonObject); } // prepare the header let post_headers = { 'Content-Type': 'application/json', 'Content-Length': data.length }; // the post options let post_options = { url: `http://${jsonObject.configuration.hubHost}:${jsonObject.configuration.hubPort}/grid/register`, method: 'POST', body: data, headers: post_headers, resolveWithFullResponse: true // return the full response, not just the body }; if (jsonObject.configuration.register !== true) { logger.debug(`No registration sent (${jsonObject.configuration.register} = false)`); return; } let registerCycleTime = jsonObject.configuration.registerCycle; if (registerCycleTime !== null && registerCycleTime > 0) { // initiate a new Thread let first = true; logger.debug(`Starting auto register thread for grid. Will try to register every ${registerCycleTime} ms.`); setInterval(async function () { if (first !== true) { let isRegistered = await isAlreadyRegistered(jsonObject); if (isRegistered !== null && isRegistered !== true) { // make the http POST to the grid for registration await registerToGrid(post_options, jsonObject); } } else { first = false; await registerToGrid(post_options, jsonObject); } }, registerCycleTime); } } async function isAlreadyRegistered (jsonObject) { //check if node is already registered let id = `http://${jsonObject.configuration.host}:${jsonObject.configuration.port}`; try { let response = await request({ uri: `http://${jsonObject.configuration.hubHost}:${jsonObject.configuration.hubPort}/grid/api/proxy?id=${id}`, method : 'GET', timeout : 10000, resolveWithFullResponse: true // return the full response, not just the body }); if (response === undefined || response.statusCode !== 200) { throw new Error(`Request failed`); } let responseData = JSON.parse(response.body); if (responseData.success !== true) { // if register fail, print the debug msg logger.debug(`Grid registration error: ${responseData.msg}`); } return responseData.success; } catch (err) { logger.debug(`Hub down or not responding: ${err.message}`); } } export default registerNode;
JavaScript
0.000001
@@ -1931,19 +1931,235 @@ = port;%0A -%0A +%7D%0A // if the node config does not have id automatically add it%0A if (!jsonObject.configuration.id) %7B%0A jsonObject.configuration.id = %60http://$%7BjsonObject.configuration.host%7D:$%7BjsonObject.configuration.port%7D%60;%0A %7D%0A%0A // re- @@ -2215,18 +2215,16 @@ ed data%0A - data = @@ -2251,20 +2251,16 @@ Object); -%0A %7D %0A%0A // p @@ -3682,34 +3682,24 @@ %0A let id = -%60http://$%7B jsonObject.c @@ -3715,47 +3715,10 @@ ion. -host%7D:$%7BjsonObject.configuration.port%7D%60 +id ;%0A
b38b46697057105f62eb523ba353ed26e2a4c594
Fix devwatch not ignoring certain paths
lib/init/devwatch.js
lib/init/devwatch.js
'use strict'; var allowedPattern, extensions, prevcount, watchlog, chokidar, watcher, allowed, ignored, count, cwd, fs; if (process.argv.indexOf('--disable-devwatch') > -1) { return; } if (alchemy.settings.kill_on_file_change) { chokidar = alchemy.use('chokidar'); if (!chokidar) { log.warn('Can not watch files because Chokidar is not installed'); return; } fs = alchemy.use('fs'); prevcount = 0; count = 0; ignored = /^app\/public\/views|^temp/; extensions = ['js', 'json']; cwd = process.cwd(); // Get the extensions allowed to kill the server if (Array.isArray(alchemy.settings.kill_extensions)) { extensions = alchemy.settings.kill_extensions; } allowedPattern = ''; // Go over every extensionin the array extensions.forEach(function eachExtension(extension) { if (allowedPattern) { allowedPattern += '|'; } allowedPattern += '\\.' + extension + '$'; }); // Create the regex allowed = new RegExp(allowedPattern); watchlog = Function.throttle(function watchlog() { if (prevcount == count) { return; } log.warn(count, 'files are being monitored for changes'); prevcount = count; }, 1500, false, true); // Start watching all the files, starting with the current working directory watcher = chokidar.watch(cwd, {ignored: function ignoreThisPath(_path) { var isAllowed, depth, path = _path, stat, file; // Ignore git folders if (~path.indexOf('.git')) { return true; } // Ignore non-stylesheet files in asset or public folders if (~path.indexOf('/assets/') || ~path.indexOf('/public/')) { if (path.indexOf('.') > -1 && !path.endsWith('.less') && !path.endsWith('.css') && !path.endsWith('.scss')) { return true; } else { isAllowed = true; } } // Skip some big module folders by default if (path.endsWith('/less') || path.endsWith('/caniuse-lite') || path.endsWith('/bcrypt') || path.endsWith('/node-sass') || path.endsWith('/mmmagic') || path.endsWith('/node-gyp') || path.endsWith('/lodash')) { return true; } watchlog(); path = path.replace(cwd+'/', ''); file = path.split('/'); file = file[file.length-1]; depth = path.count('/'); if (depth > 7) { return false; } if (count > 4999) { if (count == 5000) { count++ log.warn('Already watching 5000 files, not watching any more'); } return false; } if (isAllowed == null) { // Only allow the specified extensions isAllowed = allowed.exec(file); } // If it's already false, return it if (!isAllowed) { // Only disallow if it's not a directory try { if (!fs.statSync(path).isDirectory()) { return true; } } catch (err) { // Ignore files that have been removed return true; } } // See if it's still allowed based on patterns to ignore isAllowed = !ignored.exec(path); if (isAllowed && path.count('/plugins/') == 1 && path.count('node_modules')) { isAllowed = false; } // If it's still allowed, make sure it isn't 2 or more node_modules deep if (isAllowed && path.count('node_modules') > 1) { if (path.count('node_modules') == 2 && path.endsWith('node_modules')) { isAllowed = true; } else if (path.count('protoblast') || path.count('hawkejs')) { if (path.count('node_modules') > 2) { isAllowed = false; } } else { isAllowed = false; } } // If it's still allowed, increase the watch count if (isAllowed) { count++; } // Return if it should be ignored or not return !isAllowed; }, persistent: true}); // Kill the server when any of the files change watcher.on('change', function onFileChange(path, stats) { // Skip hawkejs client file if (path.indexOf('hawkejs-client-side.js') > -1) { return false; } // Skip protoblast client files if (path.indexOf('protoblast/client-file') > -1) { return false; } // Also skip files in the temp directory if (path.indexOf('temp/') === 0) { return false; } // Skip assets or public files if (path.indexOf('/assets/') > -1 || path.indexOf('/public/') > -1) { if (path.endsWith('.css') || path.endsWith('.scss') || path.endsWith('.less')) { broadcastReload(path); } return false; } // Only allow defined extensions if (!allowed.exec(path)) { return false; } // Kill the process, run together with something like "forever" to restart die('Killing server because', JSON.stringify(path.replace(cwd + '/', '')), 'has been modified'); }); let broadcastReload = Function.throttle(function broadcastReload(path) { alchemy.broadcast('css_reload', path); }, 100, false, true); }
JavaScript
0
@@ -2240,36 +2240,35 @@ 7) %7B%0A%09%09%09return -fals +tru e;%0A%09%09%7D%0A%0A%09%09if (co @@ -2393,36 +2393,35 @@ %09%09%09%7D%0A%0A%09%09%09return -fals +tru e;%0A%09%09%7D%0A%0A%09%09if (is
fe210a3e71b55e4bae418ad3505c6dfa612dfa7e
use path.sep instead of `/`
lib/lock/resolver.js
lib/lock/resolver.js
const request = require('request') const path = require('path') const fs = require('fs') const readdirSync = require('fs').readdirSync const npmrc = require('../utils/npmrc') const nm = require('../utils/nm') const resolver = (dep, base, resolve, reject) => { base = base || nm const pkgJSON = require(path.join(base, dep, 'package.json')) const options = { url: npmrc.registry + pkgJSON.name + '/' + pkgJSON.version, headers: { 'User-Agent': npmrc.userAgent } } var body = '' request.get(options) .on('data', (chunk) => { body += chunk }) .on('end', () => { try { body = JSON.parse(body) } catch (e) { reject(e) } if (base === nm) { global.dependenciesTree[pkgJSON.name] = { version: body.version, tarball: body.dist.tarball, shasum: body.dist.shasum } } else { base = base.split('/').slice(-2)[0] if (!global.dependenciesTree[base].dependencies) { global.dependenciesTree[base].dependencies = {} } global.dependenciesTree[base].dependencies[dep] = {} global.dependenciesTree[base].dependencies[dep].version = body.version global.dependenciesTree[base].dependencies[dep].tarball = body.dist.tarball global.dependenciesTree[base].dependencies[dep].shasum = body.dist.shasum } const dir = path.join(base, dep, 'node_modules') if (fs.existsSync(dir)) { const deps = readdirSync(dir).filter((n) => { return n[0] !== '.' }) const tasks = deps.map((dep) => { return new Promise((resolve, reject) => resolver(dep, dir, resolve, reject)) }) Promise.all(tasks).then(() => { resolve() }) } else { resolve() } }) .on('error', reject) } module.exports = () => { const deps = readdirSync(nm).filter((n) => { return n[0] !== '.' }) return deps.map((dep) => { return new Promise((resolve, reject) => resolver(dep, null, resolve, reject)) }) }
JavaScript
0.00324
@@ -899,19 +899,24 @@ e.split( -'/' +path.sep ).slice(
ddc22541a52af1f89e27f10ecfe4494974d1b89b
remove redundant line
lib/machines/show.js
lib/machines/show.js
'use strict'; 'use strict'; var method = require('./../method'); var assign = require('lodash.assign'); /** * @memberof machines * @method show * @description Show machine information for the machine with the given id. * @param {object} params - Machine show parameters * @param {string} params.machineId - Id of the machine to show * @param {function} cb - Node-style error-first callback function * @returns {object} machine - The machine JSON object * @example * paperspace.machines.show({ * machineId: 'ps123abc', * }, function(err, resp) { * // handle error or http response * }); * @example * $ paperspace machines show \ * --machineId "ps123abc" * @example * # HTTP request: * https://api.paperspace.io * GET /machines/getMachinePublic?machineId=ps123abc * x-api-key: 1ba4f98e7c0... * # Returns 200 on success * @example * //Example return value: * { * "id": "ps123abc", * "name": "My Machine", * "os": "Microsoft Windows Server 2016 Datacenter", * "ram": "8589938688", * "cpus": 4, * "gpu": "GRID K160Q (2GB)", * "storageTotal": "53687091200", * "storageUsed": "110080", * "usageRate": "Air monthly", * "shutdownTimeoutInHours": 168, * "shutdownTimeoutForces": false, * "performAutoSnapshot": false, * "autoSnapshotFrequency": null, * "autoSnapshotSaveCount": null, * "agentType": "WindowsDesktop", * "dtCreated": "2016-11-18T05:18:29.533Z", * "state": "ready", * "networkId": "n789ghi", * "privateIpAddress": "10.64.21.47", * "publicIpAddress": null, * "region": "East Coast (NY2)", * "userId": "u123abc", * "teamId": "te456def" * "scriptId": "sc123abc" * "dtLastRun": "2017-06-30T07:22:49.763Z" * "events": [ * { * "name": "start", * "state": "done", * "errorMsg": "", * "handle": "8ebe43dd-57c8-4bd4-b770-86b7fd0202e4", * "dtModified": "2017-08-16T14:36:24.802Z", * "dtFinished": null, * "dtCreated": "2017-08-16T14:36:18.373Z" * }, * { * "name": "start", * "state": "error", * "errorMsg": "Uh oh. This machine type can't start due to insufficient capacity or higher than normal demand. Please try again later.", * "handle": "f6adb486-f5ae-4ab3-9a1a-51c19df5b337", * "dtModified": "2017-06-09T15:32:38.115Z", * "dtFinished": "2017-06-09T15:32:38.115Z", * "dtCreated": "2017-06-09T15:32:37.019Z" * }, * { * "name": "stop", * "state": "done", * "errorMsg": "", * "handle": "e352ad96-734f-4a26-8829-007c2f1d89f2", * "dtModified": "2017-06-03T04:14:01.327Z", * "dtFinished": null, * "dtCreated": "2017-06-03T04:13:47.885Z" * } * ] * } */ function show(params, cb) { return method(show, params, cb); } assign(show, { auth: true, group: 'machines', name: 'show', method: 'get', route: '/machines/getMachinePublic', requires: { machineId: 'string', }, returns: {}, }); module.exports = show;
JavaScript
0.999999
@@ -1,23 +1,8 @@ -'use strict';%0A%0A 'use str
23daccd4383981effd82bdbb5791236c581f8fa5
fix wechat access token wrong request method
lib/routes/wechat.js
lib/routes/wechat.js
var express = require('express'); var router = express.Router(); var config = require('config'); var request = require('request'); var handlebars = require('handlebars'); var service = require('../service/service'); var urlTpl = handlebars.compile(config.app.integration.wechatAccessTokenURL); router.get('/', function(req, res) { request(urlTpl({ "appId": config.app.integration.wechatAppId, "secret": config.app.integration.wechatAppScret, "code": req.query.code })).on("response", function(response) { var credential = JSON.parse(response.body); /** access_token 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同 expires_in access_token接口调用凭证超时时间,单位(秒) refresh_token 用户刷新access_token openid 用户唯一标识,请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的OpenID scope 用户授权的作用域,使用逗号(,)分隔 */ req.session.credential = credential; req.session.openId = credential.openid; if (req.query.state && req.query.state !== "" && req.query.state !== "undefined") { service.addRefer(credential.openid, req.query.state); } res.redirect('/enter'); }); }); module.exports = router;
JavaScript
0.000001
@@ -499,22 +499,34 @@ %7D) -).on(%22 +, function(error, response %22, f @@ -525,28 +525,66 @@ onse -%22 , -function(response +body) %7B%0A if (!error && response.statusCode == 200 ) %7B%0A @@ -591,16 +591,20 @@ + var cred @@ -623,25 +623,16 @@ N.parse( -response. body);%0A @@ -642,12 +642,20 @@ -/**%0A + /**%0A @@ -738,16 +738,20 @@ + + expires_ @@ -795,16 +795,20 @@ + refresh_ @@ -844,16 +844,20 @@ + + openid @@ -921,16 +921,20 @@ + + scope @@ -961,16 +961,20 @@ + */%0A @@ -968,32 +968,36 @@ */%0A + + req.session.cred @@ -1017,32 +1017,36 @@ ential;%0A + + req.session.open @@ -1070,16 +1070,20 @@ penid;%0A%0A + @@ -1178,16 +1178,20 @@ + + service. @@ -1248,10 +1248,18 @@ + + %7D%0A + @@ -1286,16 +1286,71 @@ nter');%0A + %7D else %7B%0A res.json(body);%0A %7D%0A %7D);%0A
ade5e01c240553e228610ebee166dd5977c23c35
remove unused code
lib/server/router.js
lib/server/router.js
'use strict'; const fs = require('fs'); const path = require('path'); const EventEmitter = require('events'); const root = require('window-or-global'); const detectPort = require('detect-port'); const macacaReporterRender = require('macaca-reporter/lib/render'); root.mockData = require('macaca-reporter/test/mock'); // TODO: remove this after clean template data in macaca-reporter root.mockData.stats.passes = 0; root.mockData.stats.passPercent = 0; root.mockData.stats.duration = 0; root.mockData.stats.skipped = 0; root.mockData.stats.hasSkipped = false; const _ = require('../common/helper'); let server = require('http').createServer(); let io = require('socket.io')(server); let socketed = false; let connected = false; module.exports = function(app) { app.use(function *() { if (socketed) { /** Update content */ this.body = fs.readFileSync(path.join(__dirname, '..', '..', 'reports', 'index.html'), 'utf8'); return; } else { socketed = true; } var port = yield detectPort(56788); /** Listen to port and update change */ server.listen(port); io.on('connection', function(socket) { if (connected === false) { connected = true; console.log('socket connected'); setInterval(() => { root.mockData.stats.duration = Date.now() - root.mockData.stats.start.getTime(); root.mockData.stats.passPercent = (100 * root.mockData.stats.passes / (root.mockData.stats.tests ? root.mockData.stats.tests : 0)).toFixed(1); io.sockets.emit('update reporter', root.mockData); }, 2000); socket.on('disconnect', function() {}); } }); /** Detect port and render data */ macacaReporterRender(root.mockData, { socket: { server: `http://${_.ipv4}:${port}` } }); /** Update content */ this.body = fs.readFileSync(path.join(__dirname, '..', '..', 'reports', 'index.html'), 'utf8'); }); }; /** Add event emmiter for picking up changes */ if (!root.eventEmmiter) { root.eventEmmiter = new EventEmitter(); } root.eventEmmiter.addListener('screenRefresh', data => { let action = null; let i = 0; for (; i < data.currentNode.actions.length; i++) { if (data.currentNode.actions[i].isTriggered === false) { action = data.currentNode.actions[i]; break; } } root.mockData.current.image = `./${data.fileName}` ; root.mockData.current.list = []; root.mockData.current.list.push({'title': 'digest', 'value': data.currentNode.digest}); root.mockData.current.list.push({'title': 'actions-done', 'value': i}); root.mockData.current.list.push({'title': 'actions-total', 'value': data.currentNode.actions.length}); root.mockData.current.list.push({'title': 'action-path', 'value': action ? action.location : 'all action cleared'}); root.mockData.current.list.push({'title': 'depth', 'value': data.currentNode.depth}); root.mockData.current.list.push({'title': 'node-type', 'value': data.currentNode.type}); root.mockData.current.list.push({'title': 'action-description', 'value': action ? JSON.stringify(action.source) : ''}); }); root.eventEmmiter.addListener('terminateCrawling', data => { socketed.disconnected(); process.exist(); });
JavaScript
0.000017
@@ -3197,35 +3197,8 @@ %3E %7B%0A - socketed.disconnected();%0A pr
89bde4bd4ce27a44474d7a7f59a0add52160073d
Fix TabListView with empty panes
lib/tab_list_view.js
lib/tab_list_view.js
'use babel' import { Emitter } from 'atom' import { $$, SelectListView } from 'atom-space-pen-views' import _ from 'underscore-plus' export default class TabListView extends SelectListView { constructor(tabControllers = []) { super() this.emitter = new Emitter this.tabControllers = tabControllers this.addClass('atom-vim-like-tab') this.panel = atom.workspace.addModalPanel({ item: this }) } viewForItem(item) { return $$(function render() { this.li({ class: 'two-lines' }, () => { this.span({ class: 'primary-line' }, item.primaryTitle) _.each(item.secondaryTitles, (title, i) => { this.div({ class: 'secondary-line margin-left' }, `${i + 1}: ${title}`) }) }) }) } getFilterKey() { return 'primaryTitle' } show() { const items = this.createItems() this.setItems(items) this.panel.show() this.focusFilterEditor() } confirmed(item) { this.emitter.emit('did-tab-list-confirmed', item.index) } cancelled() { this.panel.hide() } onDidTabListConfirmed(callback) { this.emitter.on('did-tab-list-confirmed', callback) } createItems() { return this.tabControllers.map((tabController, i) => { const primaryTitle = tabController.panes[0].getActiveItem().getTitle() const paneItems = tabController.panes.map((pane) => pane.getItems()) const secondaryTitles = _.flatten(paneItems).map((item) => item.getTitle()) return { primaryTitle, secondaryTitles, index: i } }) } }
JavaScript
0
@@ -1228,28 +1228,26 @@ const -primaryTitle +activeItem = tabCo @@ -1279,27 +1279,104 @@ veItem() -.getTitle() +%0A const primaryTitle = %60$%7Bi + 1%7D $%7BactiveItem ? activeItem.getTitle() : 'No name'%7D%60 %0A c
9b6c1e26835a9cacac3cd41fe722235c03d245a9
update wdio registration
lib/wdio-commands.js
lib/wdio-commands.js
var _ = require('lodash'); function isWdioContext() { return _.isObject(browser) && _.isFunction(browser.addCommand); } function registerLogCommands(log) { if (isWdioContext()) { browser.addCommand('testableLogTrace', function async() { return log.trace.apply(log, arguments); }); browser.addCommand('testableLogDebug', function async() { return log.debug.apply(log, arguments); }); browser.addCommand('testableLogInfo', function async() { return log.info.apply(log, arguments); }); browser.addCommand('testableLogError', function async() { return log.error.apply(log, arguments); }); browser.addCommand('testableLogFatal', function async() { return log.fatal.apply(log, arguments); }); } } function registerCsvCommands(csv) { if (isWdioContext()) { browser.addCommand('testableCsvGet', function async(name, index) { return csv.open(name).get(index); }); browser.addCommand('testableCsvRandom', function async(name) { return csv.open(name).random(); }); browser.addCommand('testableCsvNext', function async(name, options) { return csv.open(name).next(options); }); } } function registerResultsCommands(results) { if (isWdioContext()) { browser.addCommand('testableResult', function(resource, url) { return results(resource, url); }) browser.addCommand('testableTiming', function async(result, name, val, units) { return result.timing(name, val, units); }); browser.addCommand('testableCounter', function async(result, name, val, units) { return result.counter(name, val, units); }); browser.addCommand('testableHistogram', function async(result, name, key, val) { return result.histogram(name, key, val); }); } } function registerInfoCommands(info) { if (isWdioContext()) { browser.addCommand('testableInfo', function () { return info; }); browser.addCommand('testableScreenshot', function(name) { const id = info.region.name + '-' + info.chunk.id + '-' + info.client + '-' + info.iteration; const dir = (process.env.OUTPUT_DIR || '.') + '/'; browser.saveScreenshot(dir + id + '-' + name + '.png'); }); } } function registerStopwatchCommands(stopwatch) { if (isWdioContext()) { browser.addCommand('testableStopwatch', function async(code, metricName, resource) { return stopwatch(code, metricName, resource); }); } } module.exports.registerLogCommands = registerLogCommands; module.exports.registerCsvCommands = registerCsvCommands; module.exports.registerResultsCommands = registerResultsCommands; module.exports.registerInfoCommands = registerInfoCommands; module.exports.registerStopwatchCommands = registerStopwatchCommands;
JavaScript
0
@@ -1359,37 +1359,77 @@ c(result -, name, val, units) %7B +) %7B%0A%09%09%09const args = Array.prototype.slice.call(arguments, 1); %0A%09%09%09retu @@ -1444,32 +1444,34 @@ t.timing -(name, val, unit +.apply(result, arg s);%0A%09%09%7D) @@ -1537,29 +1537,69 @@ sult -, name, val, units) %7B +) %7B%0A%09%09%09const args = Array.prototype.slice.call(arguments, 1); %0A%09%09%09 @@ -1623,24 +1623,26 @@ nter -(name, val, unit +.apply(result, arg s);%0A @@ -1714,27 +1714,69 @@ sult -, name, key, val) %7B +) %7B%0A%09%09%09const args = Array.prototype.slice.call(arguments, 1); %0A%09%09%09 @@ -1802,23 +1802,27 @@ gram -(name, key, val +.apply(result, args );%0A%09
48bb32716a07a2c2ab3188a1aa64305b0fe5b628
add character selection
renderer/game_queue/game-queue.js
renderer/game_queue/game-queue.js
'use strict' const {ipcRenderer} = require('electron') const $ = require('jquery') ipcRenderer.on('load', (event, data) => { console.log(data) let chars = data.options.characters for (let i = 0; i < chars.length; i++) { if (i === 0) { $('#character_0').append(`<li class="list-group-item">Character ID: ${chars[i].id}</li>`) $('#character_0').append(`<li class="list-group-item">Power Stats: ${chars[i].powerStats}</li>`) $('#character_0').append(`<li class="list-group-item">Speed Stats: ${chars[i].speedStats}</li>`) $('#character_0').append(`<li class="list-group-item">Sanity Stats: ${chars[i].sanityStats}</li>`) $('#character_0').append(`<li class="list-group-item"></li>`) } if (i === 1) { $('#character_1').append(`<li class="list-group-item">Character ID: ${chars[i].id}</li>`) $('#character_1').append(`<li class="list-group-item">Power Stats: ${chars[i].powerStats}</li>`) $('#character_1').append(`<li class="list-group-item">Speed Stats: ${chars[i].speedStats}</li>`) $('#character_1').append(`<li class="list-group-item">Sanity Stats: ${chars[i].sanityStats}</li>`) $('#character_1').append(`<li class="list-group-item"></li>`) } } })
JavaScript
0.000001
@@ -699,32 +699,109 @@ st-group-item%22%3E%3C +button class=%22btn btn-primary%22 id=%22view_$%7Bi%7D%22%3ESelect Character $%7Bi%7D%3C/button%3E%3C /li%3E%60)%0A %7D%0A @@ -1284,16 +1284,93 @@ -item%22%3E%3C +button class=%22btn btn-primary%22 id=%22view_$%7Bi%7D%22%3ESelect Character $%7Bi%7D%3C/button%3E%3C /li%3E%60)%0A
9a619cc204653f56436dff327bcfc6b5567e7879
treat input as number instead of string
src/main/webapp/js/app.js
src/main/webapp/js/app.js
$(function() { $('#inputNumber').change(function(event) { var inputValue = event.target.value, outputValue = square(inputValue); $('#outputAnswer').text(outputValue); }); });
JavaScript
0.155873
@@ -74,16 +74,23 @@ Value = +Number( event.ta @@ -99,16 +99,17 @@ et.value +) ,%0A ou
1ce2a128186d928995d0330bb34006791ec8237a
fix mirrored scrolling in markdown editor
ghost/admin/components/-markdown.js
ghost/admin/components/-markdown.js
var Markdown = Ember.Component.extend({ adjustScrollPosition: function () { var scrollWrapper = this.$('.entry-preview-content').get(0), // calculate absolute scroll position from percentage scrollPixel = scrollWrapper.scrollHeight * this.get('scrollPosition'); scrollWrapper.scrollTop = scrollPixel; // adjust scroll position }.observes('scrollPosition') }); export default Markdown;
JavaScript
0
@@ -108,16 +108,26 @@ this.$( +).closest( '.entry-
ce959463b0e59236f11e26857d7e33eb5f9d0e6e
Use child_process.execFile to prevent unescaped stuff (#2206)
app/plugins/install.js
app/plugins/install.js
const cp = require('child_process'); const queue = require('queue'); const ms = require('ms'); const {yarn, plugs} = require('../config/paths'); module.exports = { install: fn => { const spawnQueue = queue({concurrency: 1}); function yarnFn(args, cb) { const env = { NODE_ENV: 'production', ELECTRON_RUN_AS_NODE: 'true' }; spawnQueue.push(end => { const cmd = [process.execPath, yarn].concat(args).join(' '); console.log('Launching yarn:', cmd); cp.exec(cmd, { cwd: plugs.base, env, shell: true, timeout: ms('5m'), stdio: ['ignore', 'ignore', 'inherit'] }, err => { if (err) { cb(err); } else { cb(null); } end(); spawnQueue.start(); }); }); spawnQueue.start(); } yarnFn(['install', '--no-emoji', '--no-lockfile', '--cache-folder', plugs.cache], err => { if (err) { return fn(err); } fn(null); }); } };
JavaScript
0
@@ -520,12 +520,50 @@ exec -(cmd +File(process.execPath, %5Byarn%5D.concat(args) , %7B%0A @@ -608,31 +608,8 @@ nv,%0A - shell: true,%0A @@ -647,46 +647,30 @@ -stdio: %5B'ignore', 'ignore', 'inherit'%5D +maxBuffer: 1024 * 1024 %0A
214498f2e38051c8ca73dc47f81b07f890ca69b2
add debug in src/model/track_item.js
src/model/history_item.js
src/model/history_item.js
module.exports = class HistoryItem { constructor({ track, playCount = 1, updatedAt = null }) { this.track = track; this.playCount = playCount; this.updatedAt = updatedAt || Date.now(); } serialize() { return { playCount: this.playCount, updatedAt: this.updatedAt, track: this.track.serialize() }; } };
JavaScript
0.000001
@@ -1,8 +1,65 @@ +const debug = require('debug')('jukebox:history_item');%0A%0A module.e @@ -143,24 +143,108 @@ = null %7D) %7B%0A + debug('create history item, %25o', %7B track_id: track.id, playCount, updatedAt %7D);%0A this.tra
cf8fcf58a15f497c8ba9c148a30755352929c287
update js
js/jquery.media.box.js
js/jquery.media.box.js
;(function($) { 'use strict'; var pluginName = 'mediaBox'; /** * class MediaBox * @param {string} elementName * @param {object} params * @constructor */ var MediaBox = function MediaBox(elementName, params) { this._TYPE = {VIDEO: 'video', IMAGE: 'image'}; this._params = params; this._eventsListener = [ [elementName, 'click', '_onClick'], [this._params.elem.close, 'click', '_onCancel'] ]; this._initialize(); }; /** * initialize. * @private */ MediaBox.prototype._initialize = function() { this._createBaseHtml(); this._loadListeners(); }; /** * open box. * process => render and fadeIn * @param attr * @private */ MediaBox.prototype._open = function(attr) { var type = this._type(attr.src); var html = this._params.html[type]; html = this._parseHtml(attr, html); $(this._params.elem.arrange).html(html); var w = attr.width / 2, h = attr.height / 2; $(this._params.elem.contents).css({'margin-left':-w, 'margin-top':-h}); $(this._params.elem.base).fadeIn(this._params.openSpeed); }; /** * close box * @private */ MediaBox.prototype._close = function() { $(this._params.elem.base).fadeOut(this._params.closeSpeed, function() { this._resetArrange(); }.bind(this)); }; /** * reset arrange html. * @private */ MediaBox.prototype._resetArrange = function() { $(this._params.elem.arrange).html(''); }; /** * append media box base html from body tag. * @private */ MediaBox.prototype._createBaseHtml = function() { var html = this._parseHtml({src: this._params.closeImage}, this._params.html.base); $('body').append(html); }; /** * Run method to registered event listener. * @private */ MediaBox.prototype._loadListeners = function() { var _this = this; $.each(this._eventsListener, function(i, setting) { var elem = setting[0], event = setting[1], method = setting[2]; $(document).on(event, elem, function() { _this[method]($(this)); }); }); }; /** * attr from parse html. * @param attr * @param html * @returns {*} * @private */ MediaBox.prototype._parseHtml = function(attr, html) { $.each(attr, function(key, value) { key = ':' + key; html = html.replace(key, value); }); return html; }; /** * get media type. * @param src * @returns {*} * @private */ MediaBox.prototype._type = function(src) { console.log(src); if (src.search(/(.*)\.(jpg|jpeg|gif|png|bmp|tif|tiff)/gi) != -1) { return this._TYPE.IMAGE; } else if (src.search(/(.*)\.(mp4)/gi) != -1) { return this._TYPE.VIDEO; } return null; }; /** * on click event. * @param $e * @private */ MediaBox.prototype._onClick = function($e) { if ($(this._params.elem.base).length) { $(this._params.elem.base).hide(0, function() { this._resetArrange(); }.bind(this)); } var src = $e.attr('data-src'); var width = $e.attr('data-width'); var height = $e.attr('data-height'); this._open({src: src, width: width, height: height}); }; /** * on cancel event. * @private */ MediaBox.prototype._onCancel = function() { this._close(); }; /** * Default params. */ var defaults = { html: { base: '<div class="mb-base">' + '<div class="mb-contents">' + '<span class="mb-close mb-decoration-close"><img src=":src"></span>' + '<div class="mb-arrange"></div>' + '</div>' + '</div>', video: '<video class="mb-video mb-close" autoplay src=":src" width=":width" height=":height"></video>', image: '<img class="mb-image mb-close" src=":src" width=":width" height=":height" />' }, elem: { base: '.mb-base', contents: '.mb-contents', arrange: '.mb-arrange', video: '.mb-video', image: '.mb-image', close: '.mb-close' }, closeImage: 'close.png', openSpeed: 500, closeSpeed: 300 }; $.fn[pluginName] = function(params) { return new MediaBox($(this).selector, $.extend(defaults ,params)); }; })(jQuery);
JavaScript
0
@@ -2874,24 +2874,44 @@ ction($e) %7B%0A + alert('click');%0A if ($(th
a0701eb0c7830579f217f25de8d3c866830db907
Fix exports in modules/app
src/modules/app/export.js
src/modules/app/export.js
export * from './ElementModule'; export * from './CameraModule'; export * from './HelpersModule'; export * from './RenderingModule'; export * from './SceneModule'; export * from './ResizeModule'; export * from './PostProcessorModule'; export * from './VirtualMouseModule';
JavaScript
0.000009
@@ -62,41 +62,8 @@ e';%0A -export * from './HelpersModule';%0A expo
974942830f5cc23adcb370cc10ef2c472aab7ce8
Handle "EMFILE: too many open files, scandir"
src/modules/tradePairs.js
src/modules/tradePairs.js
'use strict'; const fs = require('graceful-fs'); const settings = require('./settings'); class TradePairs { constructor() { this.regExp = this.buildRegExp(); } getTradePairs() { this.initTradePairs(); return new Promise((resolve, reject) => { try { let files = fs.readdirSync(settings.pathToGunbot); for (let file of files) { let matches = this.regExp.exec(file); if (matches && matches.length >= 3) { this.tradePairs[matches[1]].push(matches[2]); } } resolve(this.tradePairs); } catch (error) { reject(error); } }); } initTradePairs() { this.tradePairs = []; for (let marketPrefix of settings.marketPrefixs) { this.tradePairs[marketPrefix] = []; } } buildRegExp() { let regExStr = '('; for (let marketPrefix of settings.marketPrefixs) { regExStr += marketPrefix + '|'; } regExStr = regExStr.slice(0, -1); regExStr += ')-(BTC_[A-Z0-9]{2,16})-log.txt'; return new RegExp(regExStr); } } module.exports = new TradePairs();
JavaScript
0
@@ -160,16 +160,42 @@ gExp();%0A + this.tradePairs = %5B%5D;%0A %7D%0A%0A g @@ -308,59 +308,464 @@ -let +fs.readdir(settings.pathToGunbot, (error, files +) = - fs.readdirSync(settings.pathToGunbot);%0A +%3E %7B%0A // If there is an error ...%0A if (error) %7B%0A // ... and the tradePairs have never been set, reject.%0A if (this.tradePairs.length === 0) %7B%0A reject(error);%0A return;%0A %7D%0A // ... but the tradePairs are already set, just return the last tradePairs.%0A resolve(this.tradePairs);%0A return;%0A %7D%0A%0A @@ -790,24 +790,26 @@ of files) %7B%0A + le @@ -844,16 +844,18 @@ (file);%0A + @@ -902,24 +902,26 @@ + this.tradePa @@ -956,34 +956,38 @@ %5B2%5D);%0A -%7D%0A + %7D%0A %7D%0A @@ -980,32 +980,34 @@ %7D%0A + resolve(this.tra @@ -1012,24 +1012,36 @@ radePairs);%0A + %7D);%0A %7D catc @@ -1056,36 +1056,328 @@ ) %7B%0A -reject(error +// If there is an error ...%0A%0A // ... and the tradePairs have never been set, reject.%0A if (this.tradePairs.length === 0) %7B%0A reject(error);%0A return;%0A %7D%0A // ... but the tradePairs are already set, just return the last tradePairs.%0A resolve(this.tradePairs );%0A %7D%0A
3e932ff89d4f869c7548f8c598cf15b7d91ea56a
Add support for setting layer.popup to a Popup instance
js/src/layers/Layer.js
js/src/layers/Layer.js
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. var widgets = require('@jupyter-widgets/base'); var _ = require('underscore'); var PMessaging = require('@phosphor/messaging'); var PWidgets = require('@phosphor/widgets'); var L = require('../leaflet.js'); var utils = require('../utils.js') var LeafletLayerModel = widgets.WidgetModel.extend({ defaults: _.extend({}, widgets.WidgetModel.prototype.defaults, { _view_name: 'LeafletLayerView', _model_name: 'LeafletLayerModel', _view_module: 'jupyter-leaflet', _model_module: 'jupyter-leaflet', opacity: 1.0, bottom: false, options: [], name: '', base: false, popup: null, popup_min_width: 50, popup_max_width: 300, popup_max_height: null, }) }, { serializers: _.extend({ popup: { deserialize: widgets.unpack_models } }, widgets.WidgetModel.serializers) }); var LeafletUILayerModel = LeafletLayerModel.extend({ defaults: _.extend({}, LeafletLayerModel.prototype.defaults, { _view_name: 'LeafletUILayerView', _model_name: 'LeafletUILayerModel' }) }); var LeafletLayerView = utils.LeafletWidgetView.extend({ initialize: function (parameters) { LeafletLayerView.__super__.initialize.apply(this, arguments); this.map_view = this.options.map_view; this.popup_content_promise = Promise.resolve(); }, render: function () { return Promise.resolve(this.create_obj()).then(() => { this.leaflet_events(); this.model_events(); this.bind_popup(this.model.get('popup')); this.listenTo(this.model, 'change:popup', function(model, value) { this.bind_popup(value); }); }) }, leaflet_events: function () { // If the layer is interactive if (this.obj.on) { this.obj.on('click dblclick mousedown mouseup mouseover mouseout', (event) => { this.send({ event: 'interaction', type: event.type, coordinates: [event.latlng.lat, event.latlng.lng] }); }); this.obj.on('popupopen', (event) => { // This is a workaround for making maps rendered correctly in popups window.dispatchEvent(new Event('resize')); }); // this layer is transformable if (this.obj.transform) { // add the handler only when the layer has been added this.obj.on('add', () => { this.update_transform(); }); this.obj.on('transformed', () => { this.model.set('locations', this.obj.getLatLngs()); this.touch(); }); } } }, model_events: function () { this.model.on_some_change(['popup_min_width', 'popup_max_width', 'popup_max_height'], this.update_popup, this); }, remove: function() { LeafletLayerView.__super__.remove.apply(this, arguments); var that = this; this.popup_content_promise.then(function() { if (that.popup_content) { that.popup_content.remove(); } }); }, bind_popup: function (value) { if (this.popup_content) { this.obj.unbindPopup(); this.popup_content.remove(); } if (value) { var that = this; this.popup_content_promise = this.popup_content_promise.then(function() { return that.create_child_view(value).then(function(view) { PMessaging.MessageLoop.sendMessage(view.pWidget, PWidgets.Widget.Msg.BeforeAttach); that.obj.bindPopup(view.el, that.popup_options()); PMessaging.MessageLoop.sendMessage(view.pWidget, PWidgets.Widget.Msg.AfterAttach); that.popup_content = view; that.trigger('popup_content:created'); }); }); } return this.popup_content_promise; }, popup_options: function () { return { minWidth: this.model.get('popup_min_width'), maxWidth: this.model.get('popup_max_width'), maxHeight: this.model.get('popup_max_height') }; }, update_popup: function () { L.setOptions(this.obj.getPopup(), this.popup_options()); // Those TWO lines will enforce the options update this.obj.togglePopup(); this.obj.togglePopup(); } }); var LeafletUILayerView = LeafletLayerView.extend({ }); module.exports = { LeafletLayerView: LeafletLayerView, LeafletUILayerView: LeafletUILayerView, LeafletLayerModel: LeafletLayerModel, LeafletUILayerModel: LeafletUILayerModel, };
JavaScript
0
@@ -3716,16 +3716,43 @@ ew(value +, %7Bmap_view: that.map_view%7D ).then(f @@ -3763,24 +3763,240 @@ ion(view) %7B%0A + // If it's a Popup widget%0A if (value.name == 'LeafletPopupModel') %7B%0A that.obj.bindPopup(view.obj, that.popup_options());%0A %7D else %7B%0A @@ -4099,32 +4099,36 @@ + that.obj.bindPop @@ -4174,32 +4174,36 @@ + + PMessaging.Messa @@ -4268,16 +4268,38 @@ Attach); +%0A %7D %0A%0A
f8350af9c094ad48ff50028c004710f8ca8b0984
Support for importing sass files from @import.css
js/views/style/menu.js
js/views/style/menu.js
define([ 'jquery', 'underscore', 'backbone', 'text!templates/style/menu.html', 'jscssp', 'config', 'libs/marked/marked' ], function($, _, Backbone, dashboardPageTemplate, jscssp, config, marked) { var DashboardPage = Backbone.View.extend({ el: '.js-kalei-menu', render: function () { var that = this; that.$el.html('Loading styles'); // If style sheet is defined in config.js if(config.css_paths) { config.css_path = config.css_paths[0]; } var page = {blocks:[]}; require(['text!' + config.css_path], function (styles) { // Default "imports.css" var masterStyle = config.css_path.substr(config.css_path.lastIndexOf('/')+1); var markedOpts = _.extend({ sanitize: false, gfm: true }, config.marked_options || {} ); marked.setOptions(markedOpts); var parser = new jscssp(); var stylesheet = parser.parse(styles, false, true); var menus = []; var menuTitle = ''; var currentMenu = { sheets: [], category: '' }; _.each(stylesheet.cssRules, function(rule) { // If /* Comment */ if(rule.type === 101) { var comment = rule.parsedCssText; comment = comment.replace('/*', ''); comment = comment.replace('*/', ''); var comments = marked.lexer(comment); var defLinks = comments.links || {}; _.each(comments, function (comment) { var tokens = [comment]; tokens.links = defLinks; // Returns <h1> if(comment.type === 'heading' && comment.depth === 1) { // menuTitle = marked.parser(tokens); menus.push(_.extend({}, currentMenu)); currentMenu.sheets = []; currentMenu.category = marked.parser(tokens); } // Returns <h2> if(comment.type === 'heading' && comment.depth === 2) { // console.log('heading 2 -----> ', comment); } // Returns <h3> if(comment.type === 'heading' && comment.depth === 3) { // menus.push(_.extend({}, currentMenu)); // currentMenu.sheets = []; // currentMenu.category = marked.parser(tokens); } }); } // If @import url(''); if(rule.type === 3) { // Removes @import url(''); leaving just the style sheet name. var sheet = rule.href.substr(rule.href.indexOf('(')+2, rule.href.indexOf(')')-rule.href.indexOf('(')-3); // console.log(config.css_path, rule, sheet); var regex = /(?:.*\/)(.*)\.(sass|scss)$/gi; var result = []; if((result = regex.exec(sheet)) !== null) { // result[0] Original Input. // result[1] Filename. // result[2] Extension. result[0] = result[0].substr(0, result[0].lastIndexOf('/scss')); console.log('RESULT', result[0]); } // Pushes style sheet to currentMenu. currentMenu.sheets.push(sheet); } }); if(config.css_paths) { for(var i = 1; i < config.css_paths.length; i++) { currentMenu.sheets.push(config.css_paths[i]) } } menus.push(currentMenu); $(that.el).html(_.template(dashboardPageTemplate, {_:_, menuTitle: menuTitle, menus: menus, entry: masterStyle})); $('[href="' + window.location.hash + '"]').addClass('active'); if(window.location.hash === '') { $('.js-kalei-home').addClass('active'); } }); }, events: { 'click .kalei-menu__list__item__link': function (ev) { this.$el.find('a.active').removeClass('active'); $(ev.currentTarget).addClass('active'); var scroll = $(window).scrollTop(); if(scroll !== 0) { $('body').animate({ // Scroll to top scrollTop: 0 }, '200'); } }, 'click .kalei-sheet-submenu li': function(ev) { $('body').removeClass('nav-open'); $('html, body').animate({ scrollTop: $(".kalei-page__item h1:contains('"+$(ev.currentTarget).text()+"')," + ".kalei-page__item h2:contains('"+$(ev.currentTarget).text()+"')").offset().top - 60 }, '200'); } } }); return DashboardPage; });
JavaScript
0
@@ -2494,24 +2494,78 @@ esult = %5B%5D;%0A +%09%09%09%09%09%09// If the style sheet is a .sass or .scss file:%0A %09%09%09%09%09%09if((re @@ -2706,25 +2706,68 @@ %0A%09%09%09%09%09%09%09 -result%5B0%5D +// Returns the path before 'scss/'.%0A%09%09%09%09%09%09%09sheetPath = resul @@ -2808,15 +2808,17 @@ Of(' -/ scss +/ ') ++5 );%0A%09 @@ -2827,39 +2827,122 @@ %09%09%09%09 -console.log('RESULT', result%5B0%5D +// Removes 'sheetPath' from 'sheet' leaving the path after 'scss/'.%0A%09%09%09%09%09%09%09sheet = result%5B0%5D.replace(sheetPath, '' );%0A%09
136736709c76c260948c4ad8d5688215fbc1f3a1
allow plugin to be bound to player after player has already been ready
jwoverlay/jwoverlay.js
jwoverlay/jwoverlay.js
(function() { var Overlay = function(player) { var overlay = document.createElement('div'); // any element with class 'jwoverlay-close' will close the overlay overlay.addEventListener('click', function(evt) { var clicked = evt.target || evt.toElement; if(clicked.className.split(/\s+/).indexOf('jwoverlay-close') > -1) { api.hide(); } else if(clicked.className.split(/\s+/).indexOf('jwoverlay-play') > -1) { api.hide(); try { player.play(); } catch(err) { } } }); // api methods are chainable var api = { show: function() { overlay.style.display = 'block'; return api; }, css: function(cssProperties) { for(p in cssProperties) { overlay.style[p] = cssProperties[p]; } return api; }, resetCss: function() { overlay.style.cssText += 'position:absolute;left:0;right:0;padding:10px;color:#FFF;'; overlay.style.cssText += 'height:100%;width:100%;background:rgba(0,0,0,.8);z-index:99'; return api; }, hide: function() { overlay.style.display = 'none'; return api; }, html: function(html) { overlay.innerHTML = html || ''; return api; }, init: function() { overlay.innerHTML = ''; overlay.className = 'jwoverlay'; overlay.style.display = 'none'; return api; }, elt: function() { return overlay; } }; // initiallize div, reset style api.init().resetCss(); return api; } window.jwoverlay = function(_player) { var overlay = Overlay(_player); // attach overlay object to player instance _player.jwoverlay = overlay; _player.on('ready', function() { _player.getContainer().appendChild(overlay.elt()); }); } })();
JavaScript
0
@@ -96,22 +96,129 @@ t('div') -; +,%0A addOverlay = function() %7B%0A player.getContainer().appendChild(overlay);%0A %7D %0A%0A @@ -1888,24 +1888,448 @@ one'; %0A + if(player.getState() && player.getContainer() && player.getContainer().className.indexOf('jwplayer') %3E -1) %7B %0A addOverlay(); // player was already %60ready%60 when jwoverlay(playerInstance); was called%0A %7D%0A else %7B %0A player.on('ready', addOverlay); // wait for player readiness%0A %7D%0A @@ -2346,32 +2346,32 @@ api; %0A - %7D,%0A @@ -2738,25 +2738,24 @@ overlay; -%0A _player. @@ -2750,115 +2750,16 @@ -_player.on('ready', function() %7B%0A _player.getContainer().appendChild(overlay.elt());%0A %7D); + %0A
16aaaea4bbc61ce4192238d2148407a573005933
Use core-js instead of es6-shim
karma/shared.config.js
karma/shared.config.js
var _ = require('lodash'); var fs = require('fs'); exports.baseConfig = function(karma) { return { // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine', 'chai', 'sinon'], // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true, // level of logging // possible values: karma.LOG_DISABLE || karma.LOG_ERROR || karma.LOG_WARN || karma.LOG_INFO || karma.LOG_DEBUG logLevel: karma.LOG_INFO, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['ChromeNoSandbox'], // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // enable / disable colors in the output (reporters and logs) colors: true, port: 2000, plugins: [ require('karma-jasmine'), require('karma-chai'), require('karma-sinon'), require('karma-chrome-launcher'), require('karma-firefox-launcher'), require('karma-ie-launcher'), ], customLaunchers: { ChromeNoSandbox: { base: 'Chrome', flags: ['--no-sandbox'], }, }, }; }; exports.polyfills = [ { pattern: 'node_modules/es6-shim/es6-shim.js', included: true, watched: false }, { pattern: 'node_modules/reflect-metadata/Reflect.js', included: true, watched: false }, { pattern: 'node_modules/systemjs/dist/system.src.js', included: true, watched: false }, 'node_modules/zone.js/dist/zone.js', 'node_modules/zone.js/dist/long-stack-trace-zone.js', 'node_modules/zone.js/dist/proxy.js', 'node_modules/zone.js/dist/sync-test.js', 'node_modules/zone.js/dist/jasmine-patch.js', 'node_modules/zone.js/dist/async-test.js', 'node_modules/zone.js/dist/fake-async-test.js', ]; exports.karmaShimFile = { pattern: 'node_modules/@renovolive/gulp-utilities/karma/karma-test-shim.js', included: true, watched: false, }; exports.defaultSettings = { timeout: 2000, appPath: '/source/', testsExtension: '.tests.js', configPath: 'system.config.js', globalSettingsPath: 'globalSettings.js', }; exports.config = function(karma, fileDependencies, settings) { settings = settings || {}; settings = _.defaults(settings, exports.defaultSettings); fs.writeFileSync(settings.globalSettingsPath, 'window.settings = ' + JSON.stringify(settings) + ';', 'utf8'); fileDependencies = arrayify(fileDependencies); fileDependencies.map(function(file) { return { pattern: file, included: true, watched: true, } }); var settingsFile = { pattern: settings.globalSettingsPath, included: true, watched: false, }; var systemConfigFile = { pattern: settings.configPath, included: false, watched: true, }; var testsReference = { pattern: 'source/**/*' + settings.testsExtension, included: false, watched: false, } var options = exports.baseConfig(karma); options.files = exports.polyfills .concat(fileDependencies) .concat([settingsFile]) .concat([exports.karmaShimFile]) .concat([systemConfigFile]) .concat([testsReference]); karma.set(options); return options; } function arrayify(maybeArray) { if (_.isArray(maybeArray)) { return maybeArray; } else if (maybeArray) { return [maybeArray]; } else { return []; } } function addPreprocessor(options, path) { options.preprocessors = options.preprocessors || {}; options.preprocessors[path] = [webpackPreprocessorLibrary]; }
JavaScript
0
@@ -1408,25 +1408,31 @@ les/ -es6-shim/es6-shim +core-js/client/shim.min .js'
e430f6952357775b82b05100b9ab16cee3d87bfe
use default export
src/no-dropping-the-ra.js
src/no-dropping-the-ra.js
// LICENSE : MIT "use strict"; import { RuleHelper } from "textlint-rule-helper"; import { tokenize } from "kuromojin"; function isTargetVerb(token) { return ( token.pos == "動詞" && token.pos_detail_1 == "自立" && token.conjugated_type == "一段" && token.conjugated_form == "未然形" ); } function isRaWord(token) { return token.pos == "動詞" && token.pos_detail_1 == "接尾" && token.basic_form == "れる"; } function isSpecialCases(token) { // Due to kuromoji.js's behavior, some dropping-ra words will be tokenized as one. // See also https://github.com/takuyaa/kuromoji.js/issues/28 return token.pos == "動詞" && (token.basic_form == "来れる" || token.basic_form == "見れる"); } module.exports = function (context) { const helper = new RuleHelper(context); const { Syntax, report, getSource, RuleError } = context; return { [Syntax.Str](node) { if (helper.isChildNode(node, [Syntax.Link, Syntax.Image, Syntax.BlockQuote, Syntax.Emphasis])) { return; } const text = getSource(node); return tokenize(text).then((tokens) => { tokens.forEach((token) => { if (isSpecialCases(token)) { report( node, new RuleError("ら抜き言葉を使用しています。", { index: token.word_position }) ); } }); // tokenのペアがない場合は無視する if (tokens.length <= 1) { return; } tokens.reduce((prev, current) => { if (isTargetVerb(prev) && isRaWord(current)) { report( node, new RuleError("ら抜き言葉を使用しています。", { index: current.word_position - 1 }) ); } return current; }); }); } }; };
JavaScript
0.000005
@@ -715,24 +715,22 @@ %0A%7D%0A%0A -module.exports = +export default fun