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
36bfc9628d7a0d30f270c8a1437cfc4f9b06568c
Remove localstorage
js/apporder.js
js/apporder.js
$(function () { var app_menu = $('#apps ul'); if (!app_menu.length) return; app_menu.hide(); // restore existing order $.get(OC.filePath('apporder', 'ajax', 'order.php'), {requesttoken: oc_requesttoken}, function (data) { var json = data.order; var order = [] try { var order = JSON.parse(json).reverse(); } catch (e) { order = []; } if (order.length === 0) { $('#apps ul').show(); return; } available_apps = {}; app_menu.find('li').each(function () { var id = $(this).find('a').attr('href'); available_apps[id] = $(this); }); $.each(order, function (order, value) { app_menu.prepend(available_apps[value]); }); $('#apps ul').show(); }); // make app menu sortable $("#apps ul").sortable({ handle: 'a', stop: function (event, ui) { var items = []; $("#apps ul").children().each(function (i, el) { var item = $(el).find('a').attr('href'); items.push(item); }); var json = JSON.stringify(items); localStorage.setItem("apporder-order", json); $.get(OC.filePath('apporder', 'ajax', 'personal.php'), { order: json, requesttoken: oc_requesttoken }, function (data) { $(event.srcElement).fadeTo('fast', 0.5).fadeTo('fast', 1.0); }); } }); // Sorting inside settings $("#appsorter").sortable({ forcePlaceholderSize: true, placeholder: 'placeholder', stop: function (event, ui) { var items = []; $("#appsorter").children().each(function (i, el) { var item = $(el).find('a').attr('href'); items.push(item) }); var json = JSON.stringify(items); $.get(OC.filePath('apporder', 'ajax', 'admin.php'), { order: json, requesttoken: oc_requesttoken }, function (data) { $(event.srcElement).effect("highlight", {}, 1000); }); } }); });
JavaScript
0.000001
@@ -976,57 +976,8 @@ s);%0A -%09%09%09localStorage.setItem(%22apporder-order%22, json);%0A %09%09%09$
34f749fe47421a6c515bdf3498972bdd75121a4f
Remove unused ref.
packages/react-atlas-core/src/TextArea/TextArea.js
packages/react-atlas-core/src/TextArea/TextArea.js
import React from "react"; import PropTypes from "prop-types"; import { InputCore } from "../Input"; import cx from "classnames"; import messages from "../utils/messages"; class TextArea extends React.PureComponent { constructor(props) { super(props); let isValid, errorText; if(typeof props.isValid === 'undefined') { isValid = true; } else if(props.isValid === false) { isValid = props.isValid; errorText = messages.requiredMessage; } else { isValid = props.isValid; errorText = null; } // Initial state this.state = { "value": props.value || "", "remaining": props.maxLength, "active": false, "valid": isValid }; } _handleChange = (value, event, isValid) => { event.persist(); if (this.props.maxLength) { // Keep difference between maxlength and input value in state for count this.setState({ remaining: this.props.maxLength - value.length }); } // Set value and valid state depending on InputCore state this.setState({ "value": value, "valid": isValid }); if (this.props.onChange) { // Execute app code this.props.onChange(value, event, isValid); } }; _handleFocus = () => { this.setState({ active: true }); }; _handleBlur = () => { this.setState({ active: false }); }; render() { const { name, header, placeholder, maxLength, resizable, small, medium, large, required, disabled, hidden, className, style } = this.props; let remainingCount = maxLength && ( <div styleName={cx("remainingCount")}> {maxLength - this.state.remaining}/{maxLength} </div> ); let textAreaHeader = header && ( <div styleName={cx("header")}> <span styleName={cx("headerFont")}>{header}</span> {required && <span styleName={"error_text"}> *</span>} </div> ); let wrapperClasses = cx( { hidden, small, medium, large }, "textareaWrapper" ); let textAreaClasses = cx( { resizable, disabled, active: this.state.active, invalid: !this.state.valid }, "textarea" ); return ( <div style={style} styleName={wrapperClasses} onFocus={this._handleFocus} onBlur={this._handleBlur} className={cx(className)} > {textAreaHeader} <InputCore multiline name={name} placeholder={placeholder} maxLength={maxLength} styleName={textAreaClasses} onChange={this._handleChange} required={required} disabled={disabled} hidden={hidden} value={this.state.value} ref={node => (this.inputRef = node)} // eslint-disable-line no-return-assign /> {remainingCount} </div> ); } } TextArea.PropTypes = { "isValid": PropTypes.bool, /** An Object, array, or string of CSS classes to apply to TextArea.*/ className: PropTypes.oneOfType([ PropTypes.string, PropTypes.object, PropTypes.array ]), /** * Define a name for the textarea input. * @examples '<TextArea name="test"/>' */ name: PropTypes.string, /** * Define a value for the textarea input. * @examples '<TextArea value="test"/>' */ value: PropTypes.string, /** * Define a title or header to be displayed above the textarea. * @examples '<TextArea header="test"/>' */ header: PropTypes.string, /** * Defines a resizable textarea. Default: true. * @examples '<TextArea resizable={false}/>' */ resizable: PropTypes.bool, /** * Defines a small sized textarea. * @examples '<TextArea small/>' */ small: PropTypes.bool, /** * Defines a medium sized textarea. * @examples '<TextArea medium/>' */ medium: PropTypes.bool, /** * Defines a large sized textarea. * @examples '<TextArea large/>' */ large: PropTypes.bool, /** * Sets a maximum character length that will be validated onChange. * @examples '<TextArea maxLenght={25}/>' */ maxLength: PropTypes.number, /** * Defines placeholder text. * @examples '<TextArea placeholder="test input"/>' */ placeholder: PropTypes.string, /** * Sets a handler function to be executed when onChange event occurs (at input element). * @examples <TextArea onChange={this.customOnChangeFunc}/> */ onChange: PropTypes.func, /** * Sets the field as required. Will be validated onChange. * @examples '<TextArea required/>' */ required: PropTypes.bool, /** * Determines if the textarea is disabled. * @examples '<TextArea disabled/>' */ disabled: PropTypes.bool, /** * Determines if the textarea is hidden. * @examples '<TextArea hidden/>' */ hidden: PropTypes.bool }; TextArea.defaultProps = { className: "", resizable: true, disabled: false, hidden: false }; export default TextArea;
JavaScript
0
@@ -540,20 +540,16 @@ ;%0A %7D%0A - %0A // @@ -2843,95 +2843,8 @@ ue%7D%0A - ref=%7Bnode =%3E (this.inputRef = node)%7D // eslint-disable-line no-return-assign%0A
2d2cdd2d6fb8510ca0f53919853c13cb95c893a2
Remove ref to dead npactConstants.graphSpecDefaults
npactweb/npactweb/static/js/graphs/graph.js
npactweb/npactweb/static/js/graphs/graph.js
angular.module('npact') .controller('npactGraphContainerCtrl', function($scope, $element, $window, $log, $timeout, npactConstants, Utils, GraphConfig, Evt, GraphingCalculator) { 'use strict'; var getWidth = function() { return $element.width() - 15; //from style.css `.graph` }; //The mouse event responders var onPan = function(offset) { GraphConfig.offset += Math.round(offset); $scope.$apply(); }, onZoom = function(opts) { $log.log('Zoom event:', opts); var zoomOpts = angular.extend({}, GraphConfig, opts); //updates `offset`, and `basesPerGraph` angular.extend(GraphConfig, GraphingCalculator.zoom(zoomOpts)); $scope.$apply(); }; //The baseOpts are the graph options that are the same for every graph var baseOpts = angular.extend({ width: getWidth(), onPan: onPan, onZoom: onZoom }, npactConstants.graphSpecDefaults); this.graphOptions = function(idx) { // This function builds the specific options for a graph, the // options object is lazily generated when needed var start = $scope.graphSpecs[idx]; var opts = { startBase: start, endBase: start + GraphConfig.basesPerGraph}; opts = angular.extend(opts, baseOpts); return opts; }; var repartition = function() { if(GraphConfig.startBase === undefined || GraphConfig.endBase === undefined || GraphConfig.basesPerGraph === undefined) { return; } $scope.graphSpecs = GraphingCalculator.partition(GraphConfig); $log.log('Partitioned into', $scope.graphSpecs.length, 'rows.'); updateVisibility(); $timeout(rebuild); }, draw = function() { $scope.$broadcast(Evt.DRAW); }, redraw = function() { if (!baseOpts.axisTitle) return; //too early to do anything $scope.$broadcast(Evt.REDRAW); }, rebuild = function() { if (!baseOpts.axisTitle) return; //too early to do anything $scope.$broadcast(Evt.REBUILD); }; // watch the environment for changes we care about $scope.$watchCollection(function() { return [ GraphConfig.length, GraphConfig.basesPerGraph, GraphConfig.offset, GraphConfig.startBase, GraphConfig.endBase]; }, repartition); $scope.$watch(GraphConfig.profileTitle, function(title) { //A profileTitle change indicates different nucleotides: rebuild baseOpts.axisTitle = title; rebuild(); }); $scope.$watch(GraphConfig.activeTracks, function(val) { //Find headers and headerY angular.extend(baseOpts, GraphingCalculator.trackSizeCalc(val)); baseOpts.m = GraphingCalculator.chart(baseOpts); updateRowHeight(baseOpts.m.height); redraw(); }, true); $scope.$watch( function() { return GraphConfig.colorBlindFriendly; }, function(val) { baseOpts.colors = val ? npactConstants.colorBlindLineColors : npactConstants.lineColors; redraw(); }); /*** Scrolling and Graph Visibility management ***/ var $win = angular.element($window), winHeight = $win.height(), slack = 50, // how many pixels outside of viewport to render topOffset = $element.offset().top, topIdx = 0, bottomIdx = 0, graphBoxHeight = 0, updateRowHeight = function(height) { $scope.graphHeight = height; //add padding and border from style.css `.graph` graphBoxHeight = height + 10 + 1; updateVisibility(); }, updateVisibility = function() { if(!baseOpts.m) return; var scrollDist = $window.scrollY - topOffset - slack; topIdx = Math.floor(scrollDist / graphBoxHeight); bottomIdx = topIdx + Math.ceil((winHeight) / graphBoxHeight); }, onScroll = function() { updateVisibility(); draw(); }, onResize = function() { winHeight = $win.height(); if($element.width() !== baseOpts.width) { topOffset = $element.offset().top; baseOpts.width = getWidth(); updateVisibility(); redraw(); } else { //If the width didn't change then its the same as scrolling onScroll(); } }; this.visible = function(idx) { return idx >= topIdx && idx <= bottomIdx; }; $win.on('resize', onResize); $win.on('scroll', onScroll); $scope.$on('$destroy', function() { $win.off('resize', onResize); $win.off('scroll', onScroll); }); }) .directive('npactGraphContainer', function(STATIC_BASE_URL) { return { restrict: 'A', scope: {}, templateUrl: STATIC_BASE_URL + 'js/graphs/graph-container.html', controller: 'npactGraphContainerCtrl as ctrl' }; }) .directive('npactGraph', function (Grapher, Evt, GraphingCalculator, $log, $timeout) { 'use strict'; return { restrict: 'A', require: '^npactGraphContainer', link: function($scope, $element, $attrs, ctrl) { var g = null, visible = ctrl.visible, idx = $attrs.idx, el = $element[0], // redraw gets set for all graphs once (e.g. a new track // triggers broadcasts redraw), but only gets cleared as // the currently visible ones are drawn redraw = false, draw = function() { if(!redraw || !visible(idx)) { return; } var opts = ctrl.graphOptions(idx); //However long it actually takes to draw, we have the //latest options as of this point redraw = false; (g || (g = new Grapher(el, opts))) .redraw(opts) .catch(function() { //something went wrong, we will still need to redraw this redraw = true; }) ; }, schedule = function() { if(!redraw || !visible(idx)) { return; } $timeout(draw, 0, false); }, discard = function() { if(g) { g.destroy(); g = null; } }; $scope.$on(Evt.DRAW, schedule); $scope.$on(Evt.REDRAW, function() { redraw = true; schedule();}); $scope.$on(Evt.REBUILD, function() { discard(); redraw = true; schedule(); }); $scope.$on('$destroy', discard); } }; }) .directive('npactExtract', function(STATIC_BASE_URL) { return { restrict: 'A', scope: { extract: '=npactExtract'}, templateUrl: STATIC_BASE_URL + 'js/graphs/extract.html' }; }) ;
JavaScript
0
@@ -935,31 +935,16 @@ eOpts = -angular.extend( %7B width: @@ -959,144 +959,39 @@ h(), -%0A onPan: onPan, onZoom: onZoom %7D,%0A npactConstants.graphSpecDefaults) + onPan: onPan, onZoom: onZoom %7D ;%0A
4deb89f9921db87f425938e4739c98f41e90d17e
Remove console.dir().
website/app/application/core/projects/project/processes/link-files-to-sample.js
website/app/application/core/projects/project/processes/link-files-to-sample.js
(function (module) { module.controller("LinkFilesToSampleController", LinkFilesToSampleController); LinkFilesToSampleController.$inject = ["$modalInstance", "project", "files", "sample", "mcmodal"]; function LinkFilesToSampleController($modalInstance, project, files, sample, mcmodal) { var ctrl = this; ctrl.name = sample.name; ctrl.sample_id = sample.id; ctrl.files = files; ctrl.ok = ok; ctrl.cancel = cancel; ctrl.filesToLink = []; ctrl.linkFile = linkFile; ctrl.unlinkFile = unlinkFile; ctrl.linkAllFiles = linkAllFiles; ctrl.unlinkAllFiles = unlinkAllFiles; ctrl.openFile = openFile; console.dir(files); files.forEach(function (f) { ctrl.filesToLink.push({id: f.id, name: f.name, linked: f.linked}); }); ///////// function ok() { $modalInstance.close(ctrl.filesToLink); } function cancel() { $modalInstance.dismiss('cancel'); } function linkFile(file) { file.linked = true; var i = _.indexOf(ctrl.filesToLink, function (f) { return (f.id == file.id && f.sample_id == file.sample_id); }); if (i !== -1) { ctrl.filesToLink.splice(i, 1); ctrl.filesToLink.push({ id: file.id, command: 'add', name: file.name, linked: file.linked, sample_id: ctrl.sample_id }); } else { ctrl.filesToLink.push({ id: file.id, command: 'add', name: file.name, linked: file.linked, sample_id: ctrl.sample_id }); } } function unlinkFile(file) { file.linked = false; var i = _.indexOf(ctrl.filesToLink, function (f) { return (f.id == file.id && f.sample_id == file.sample_id); }); if (i !== -1) { ctrl.filesToLink.splice(i, 1); ctrl.filesToLink.push({ id: file.id, command: 'delete', name: file.name, linked: file.linked, sample_id: ctrl.sample_id }); } } function linkAllFiles() { ctrl.filesToLink = []; ctrl.files.forEach(function (f) { linkFile(f); }); } function unlinkAllFiles() { ctrl.files.forEach(function (f) { unlinkFile(f); }); } function openFile(file) { mcmodal.openModal(file, 'datafile', project); } } }(angular.module('materialscommons')));
JavaScript
0.000001
@@ -696,65 +696,8 @@ le;%0A - console.dir(files);%0A
7152b573c4cd7d66fc895ba900338e4eff8479fe
add persistence to theme choice
app/client.js
app/client.js
import { AppContainer } from 'react-hot-loader'; import React from 'react'; import { render } from 'react-dom'; import { Router, browserHistory } from 'react-router'; import routes from './routes'; import 'bootstrap/dist/css/bootstrap.css'; import 'dc/dc.css'; import { ThemeSwitcher } from 'react-bootstrap-theme-switcher'; const rootEl = document.getElementById('root'); render( <AppContainer> <ThemeSwitcher themePath="themes" defaultTheme="cerulean"> <Router routes={routes} history={browserHistory} key={process.env.NODE_ENV !== "production" ? Math.random() : false} /> </ThemeSwitcher> </AppContainer>, rootEl ); if (module.hot) { module.hot.accept('./routes', () => { // If you use Webpack 2 in ES modules mode, you can // use <App /> here rather than require() a <NextApp />. const routes = require('./routes').default; render( <AppContainer> <ThemeSwitcher themePath="themes" defaultTheme="yeti"> <Router routes={routes} history={browserHistory} key={process.env.NODE_ENV !== "production" ? Math.random() : false} /> </ThemeSwitcher> </AppContainer>, rootEl ); }); }
JavaScript
0
@@ -455,16 +455,38 @@ erulean%22 + storeThemeKey=%22theme%22 %3E%0A
ad6067b328c5f1349812b45f3f9b445118b536d4
make hovering div be above other things
activity.js
activity.js
function ActivityPlot(target, team_id, problem_id, update, clickable) { var self = this; self.update = typeof update !== 'undefined' ? update : true; self.clickable = typeof clickable !== 'undefined' ? clickable : true; self.target = target; self.team_id = team_id; self.problem_id = problem_id; self.source_url = 'activity_data_source.php'; self.target.data("activity_plot", self); self.update_interval = 5 * 1000; var data = get_json_synchronous("icpc/common_data.php"); self.BALLOON_COLORS = data['BALLOON_COLORS']; self.TEAMS= data['TEAMS']; self.plot = function(response) { var problems_used = response.problems_used; var num_problems = problems_used.length; var problem_height = response.max_problems_per_bin; var plot_height = num_problems * problem_height; var minY = - problem_height / 4; var maxY = plot_height + problem_height / 4; var ticks = []; var colors = []; for (var i = 0; i < num_problems; ++i) { var pid = problems_used[i].toUpperCase(); var href = set_query_field(window.location.href, 'problem_id', pid); ticks.push([i * problem_height, '<a href="' + href + '">' + pid + '</a>']); colors.push(self.BALLOON_COLORS[pid]); } var options = { colors: colors, grid: { hoverable: true, clickable: self.clickable, }, yaxis: { ticks: ticks, zoomRange: [maxY, maxY], // do not allow zooming in on the y-axis panRange: [maxY, maxY], // do not allow panning on the y-axis min: minY, max: maxY, }, xaxis: { zoomRange: [10, 321], // extra space to allow for the legend panRange: [0, 320], // extra space to allow for the legend min: 0, max: 320, // extra space to allow for the legend tickDecimals: 0, }, zoom: { interactive: true, }, pan: { interactive: true, }, } // if we are already zoomed, preserve the zoom if (self.flot) { var zoom = self.flot.getAxes(); options.xaxis.min = zoom.xaxis.min; options.xaxis.max = zoom.xaxis.max; options.yaxis.min = zoom.yaxis.min; options.yaxis.max = zoom.yaxis.max; } self.flot = $.plot(self.target, response.flot_data, options); } self.showInfo = function(x, y, contents) { $("<div class='hoverinfo'>" + contents + "</div>").css( { position: 'absolute', top: y + 10, left: x + 10, border: '1px solid green', padding: '2px', 'background-color': '#efe', opacity: 0.90 } ).appendTo(target); } self.updatePlot = function() { var query = []; if (self.team_id) { query.push("team_id=" + self.team_id); } if (self.problem_id) { query.push("problem_id=" + self.problem_id); } if (query) { query = "?" + query.join("&"); } var url = self.source_url + query; $.ajax({ url: url, data: { team_id: self.team_id }, success: self.plot, error: function(jqXHR, err) { console.log("updatePlot failed for " + url + ": " + jqXHR + ", " + err); }, dataType: "json" }); if (self.update) { setTimeout(self.updatePlot, self.update_interval); } } self.initUI = function() { self.target.bind("plothover", function(evt, pos, item) { if (item) { self.target.find("div.hoverinfo").remove(); var content = '(unknown)'; if (item.series && item.series.submissionInfo) { // for the submissions var school_name = 'UNKNOWN'; try { school_name = self.TEAMS[item.series.submissionInfo[item.dataIndex].team_id]['school_name']; } catch (e) {} content = item.series.label + ": " + school_name + " problem " + item.series.submissionInfo[item.dataIndex].problem_id + " at time " + item.datapoint[0] + " (" + item.series.submissionInfo[item.dataIndex].lang_id + ")"; } else { // for the edits var numEdits = item.datapoint[1] - item.datapoint[2]; var edit = numEdits == 1 ? "team edited" : "teams edited"; content = numEdits + " " + edit; } // move the tooltip to a position relative to the plot container var offset = self.target.offset(); self.showInfo(item.pageX - offset.left, item.pageY - offset.top, content); } } ); self.target.bind("plotclick", function(evt, pos, item) { if (item && item.series && item.series.submissionInfo) { var new_location = null; if (self.team_id && /^[0-9]+$/.test(self.team_id)) { new_location = '/domjudge/jury/submission.php?ext_id=' + item.series.submissionInfo[item.dataIndex].submission_id; } else { new_location = set_query_field(window.location.href, 'team_id', item.series.submissionInfo[item.dataIndex].team_id); } if (new_location) { window.location.assign(new_location); } } } ); } $(function() { self.initUI(); self.updatePlot(); }); }
JavaScript
0.000001
@@ -2854,24 +2854,56 @@ r': '#efe',%0A + 'z-index': 100,%0A
ebdfec8a18bf60cc8116d0f63331c0bbfa91f418
update link: register account URL
inc/gui/login-dialog/login-dialog.js
inc/gui/login-dialog/login-dialog.js
/* Copyright (C) 2013-2016 Felix Hammer, Florian Thauer, Lothar May */ myLoginDialog = new Object(); /** * class LoginDialogImpl * @constructor */ function LoginDialogImpl() { var self = this; this.showLogin = function() { var show = function() { myGui.currentVisibleMessageBoxId = "loginDialog"; var page = $('#lobbyPage'); var popup = $('<div data-role="popup" id="loginDialog" data-dismissible="false" data-overlay-theme="a" data-theme="c" style="max-width:400px;" class="ui-corner-all" data-history="false"></div>').appendTo( page ); var header = $('<div data-role="header" data-theme="a" class="ui-corner-top"><h1>Login</h1></div>').appendTo( popup ); var content = $('<div data-role="content" data-theme="d" class="ui-corner-bottom ui-content"> '+ '<form> '+ '<label for="checkbox-registeredPlayer">Registered player login</label> '+ '<input type="checkbox" name="checkbox-registeredPlayer" id="checkbox-registeredPlayer" checked="checked"></input> '+ '<input type="text" name="text-LoginDialog-username" id="text-LoginDialog-username" value="" placeholder="username"> '+ '<input type="password" name="text-LoginDialog-password" id="text-LoginDialog-password" value="" autocomplete="off" placeholder="password"> '+ '<label for="checkbox-guestPlayer">Guest player login</label> '+ '<input type="checkbox" name="checkbox-guestPlayer" id="checkbox-guestPlayer"></input> '+ '</form> '+ '<p style="font-style:italic;">Login may take some time, please be patient ...</p> '+ '<a id="loginDialogLoginButton" href="" data-role="button" data-inline="true" data-theme="c">Login</a> '+ '<a id="loginDialogCancelButton" href="" data-role="button" data-inline="true" data-theme="c">Cancel</a> '+ '<br><a target="_blank" href="http://www.poker-heroes.com/register.html">Create your PokerTH gaming account ...</a> '+ '</div> ').appendTo( popup ); popup.popup(); popup.popup("open"); popup.popup("option", "positionTo", "window" ); page.page('destroy').page(); $('#loginDialogLoginButton').removeClass('ui-disabled'); $('#text-LoginDialog-username').focus(); //enter should click the login button $(function() { $("#text-LoginDialog-password").keypress(function (e) { if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) { if(!$('#loginDialogLoginButton').hasClass('ui-disabled')) { $('#loginDialogLoginButton').click(); } return false; } else { return true; } }); }); $('#loginDialogLoginButton').click(function(){ $('#loginDialogLoginButton').addClass('ui-disabled'); if($("#checkbox-registeredPlayer").is(':checked')) { var userName = $( "#text-LoginDialog-username" ).val(); var password = $( "#text-LoginDialog-password" ).val(); myNetEventHandler.connect(userName, password); } else { myNetEventHandler.connect(); } }); $('#loginDialogCancelButton').click(function(){ self.hideLogin(); }); $('#checkbox-registeredPlayer').click(function(){ if($("#checkbox-registeredPlayer").is(':checked')) { $("#checkbox-guestPlayer").prop( "checked", false ).checkboxradio( "refresh" ); $("#text-LoginDialog-username").textinput( "enable" ); $("#text-LoginDialog-password").textinput( "enable" ); } else { $('#checkbox-guestPlayer').click(); } }); $('#checkbox-guestPlayer').click(function(){ if($("#checkbox-guestPlayer").is(':checked')) { $("#checkbox-registeredPlayer").prop( "checked", false ).checkboxradio( "refresh" ); $("#text-LoginDialog-username").textinput( "disable" ); $("#text-LoginDialog-password").textinput( "disable" ); } else { $('#checkbox-registeredPlayer').click(); } }); }; if(myGui.currentVisibleMessageBoxId != "") { $("#"+myGui.currentVisibleMessageBoxId).popup("close"); $("#"+myGui.currentVisibleMessageBoxId).remove(); setTimeout(show, 100); } else { show(); } }; this.hideLogin = function() { $("#loginDialog").popup( "close" ); $("#loginDialog").remove(); }; }; function initLoginDialogImpl() { myLoginDialog = new LoginDialogImpl(); } window.addEventListener("load", initLoginDialogImpl, false);
JavaScript
0.000001
@@ -1843,16 +1843,17 @@ ef=%22http +s ://www.p @@ -1860,33 +1860,54 @@ oker --heroes.com/register.html +th.net/component/pthranking/?view=registration %22%3ECr
96cffd89d7f87a69c745ad0d4120458ebf0926a6
remove useless log
test/tests/controllers/dialogs/answers/rgiFinalChoiceDialogCtrl.js
test/tests/controllers/dialogs/answers/rgiFinalChoiceDialogCtrl.js
'use strict'; describe('rgiFinalChoiceDialogCtrl', function () { beforeEach(module('app')); var $scope, $location, $routeParams, ngDialog, rgiNotifier, rgiAnswerSrvc, rgiAnswerMethodSrvc, rgiIdentitySrvc, rgiQuestionSetSrvc, rgiUrlGuideSrvc, $parent, currenUserBackup, currentUer = {role: 'user-role', _id: 'user-id'}, routeParamsAnswerIdBackup, answerId = 'answer2015', answerQueryStub, answerQuerySpy, ANSWERS = [1, 2]; beforeEach(inject( function ( $controller, $rootScope, _$routeParams_, _$location_, _ngDialog_, _rgiIdentitySrvc_, _rgiNotifier_, _rgiAnswerSrvc_, _rgiAnswerMethodSrvc_, _rgiQuestionSetSrvc_, _rgiUrlGuideSrvc_ ) { $scope = $rootScope.$new(); $parent = { question: {question_criteria: 'Question Criteria'}, $parent: { $parent: {'_': _}, answer: { references: [], assessment_ID: 'assessment-id', researcher_score: 'Researcher Score', researcher_justification: 'Researcher Justification', reviewer_score: 'Reviewer Score', reviewer_justification: 'Reviewer Justification' } } }; $scope.$parent = $parent; $location = _$location_; $routeParams = _$routeParams_; ngDialog = _ngDialog_; rgiIdentitySrvc = _rgiIdentitySrvc_; rgiNotifier = _rgiNotifier_; rgiAnswerSrvc = _rgiAnswerSrvc_; rgiAnswerMethodSrvc = _rgiAnswerMethodSrvc_; rgiQuestionSetSrvc = _rgiQuestionSetSrvc_; rgiUrlGuideSrvc = _rgiUrlGuideSrvc_; routeParamsAnswerIdBackup = $routeParams.answer_ID; $routeParams.answer_ID = answerId; answerQuerySpy = sinon.spy(function(assessment, callback) { callback(ANSWERS); }); answerQueryStub = sinon.stub(rgiAnswerSrvc, 'query', answerQuerySpy); currenUserBackup = _.cloneDeep(rgiIdentitySrvc.currentUser); rgiIdentitySrvc.currentUser = currentUer; $controller('rgiFinalChoiceDialogCtrl', {$scope: $scope}); } )); it('initializes the choice set', function() { $scope.answerOptions.should.deep.equal([ { text: 'Agree with researcher score', score: $parent.$parent.answer.researcher_score, justification: $parent.$parent.answer.researcher_justification, comment: '', value: 'researcher', role: 'researcher' }, { text: 'Agree with reviewer score', score: $parent.$parent.answer.reviewer_score, justification: $parent.$parent.answer.reviewer_justification, comment: '', value: 'reviewer', role: 'reviewer' }, { text: 'Other score', score: 0, justification: '', comment: '', value: 'other', role: currentUer.role } ]); }); it('initializes the question choices', function() { $scope.question_criteria.should.be.equal($parent.question.question_criteria); }); it('requires the answers data', function() { answerQuerySpy.withArgs({assessment_ID: 'answer'}).called.should.be.equal(true); }); it('sets the request processing flag', function() { $scope.requestProcessing.should.be.equal(false); }); describe('#submitFinalChoice', function() { var notifierMock; beforeEach(function() { notifierMock = sinon.mock(rgiNotifier); }); describe('INCOMPLETE DATA CASE', function() { it('shows an error message is the final score data are not set', function() { $scope.final_choice = undefined; notifierMock.expects('error').withArgs('You must select an action!'); }); it('shows an error message is the final score is not set', function() { $scope.final_choice = {score: 0}; notifierMock.expects('error').withArgs('You must select a score!'); }); it('shows an error message is the justification is not set', function() { $scope.final_choice = {score: 1, justification: ''}; notifierMock.expects('error').withArgs('You must provide a justification!'); }); afterEach(function() { $scope.submitFinalChoice(); }); }); describe('COMPLETE DATA CASE', function() { var answerMethodUpdateAnswerStub, answerMethodUpdateAnswerSpy, checkExtra = function() {}; var final_choice = { score: 'VALUE', role: 'ROLE', justification: 'JUSTIFICATION' }; beforeEach(function() { answerMethodUpdateAnswerSpy = sinon.spy(function() { return { then: function(callback) { return callback; } }; }); $scope.final_choice = final_choice; }); describe('SUCCESS CASE', function() { var $locationMock, dialogMock, urlGuideMock, stubs = {}; beforeEach(function() { $locationMock = sinon.mock($location); $locationMock.expects('path'); urlGuideMock = sinon.mock(rgiUrlGuideSrvc); notifierMock.expects('notify').withArgs('Answer finalized'); dialogMock = sinon.mock(ngDialog); dialogMock.expects('close'); checkExtra = function() { $locationMock.verify(); $locationMock.restore(); dialogMock.verify(); dialogMock.restore(); console.log('restore mocks'); }; answerMethodUpdateAnswerSpy = sinon.spy(function() { return { then: function(callback) { callback(); } }; }); }); var setCriteria = function(nextQuestionId) { stubs.isAnyQuestionRemaining = sinon.stub(rgiQuestionSetSrvc, 'isAnyQuestionRemaining', function() { return nextQuestionId !== undefined; }); if(nextQuestionId !== undefined) { stubs.getNextQuestionId = sinon.stub(rgiQuestionSetSrvc, 'getNextQuestionId', function() { return nextQuestionId; }); urlGuideMock.expects('getAnswerUrl'); } else { urlGuideMock.expects('getAssessmentUrl'); } }; it('redirects to the assessment URL if there are no more questions', function() { setCriteria(); }); it('redirects to the next question URL if there are questions available', function() { setCriteria('next-question'); }); afterEach(function() { var originalCheckExtra = checkExtra; checkExtra = function() { originalCheckExtra(); urlGuideMock.verify(); urlGuideMock.restore(); for(var stubIndex in stubs) { if(stubs.hasOwnProperty(stubIndex)) { stubs[stubIndex].restore(); } } }; }); }); describe('FAILURE CASE', function() { it('shows failure reason', function() { var REASON = 'REASON'; answerMethodUpdateAnswerSpy = sinon.spy(function() { return { then: function(uselessPositiveCallback, negativeCallback) { negativeCallback(REASON); } }; }); notifierMock.expects('error').withArgs(REASON); }); }); afterEach(function() { answerMethodUpdateAnswerStub = sinon.stub(rgiAnswerMethodSrvc, 'updateAnswer', answerMethodUpdateAnswerSpy); $scope.submitFinalChoice(); var args = angular.copy($parent.$parent.answer, { status: 'final', final_score: final_choice.score, final_role: final_choice.role, final_justification: final_choice.justification }); answerMethodUpdateAnswerSpy.withArgs(args).called.should.be.equal(true); answerMethodUpdateAnswerStub.restore(); checkExtra(); }); }); afterEach(function() { notifierMock.verify(); notifierMock.restore(); }); }); afterEach(function() { $routeParams.answer_ID = routeParamsAnswerIdBackup; answerQueryStub.restore(); rgiIdentitySrvc.currentUser = currenUserBackup; }); });
JavaScript
0.000001
@@ -6385,62 +6385,8 @@ ();%0A - console.log('restore mocks');%0A
ca2b39bdbcc142e05df63f5000829f65e2586f77
Fix "Replacable" typo in docs header
docs/App/Header.js
docs/App/Header.js
// @flow import fetch from 'unfetch'; import React, { Component } from 'react'; import { withRouter } from 'react-router-dom'; import Select from '../../src'; import type { RouterProps } from '../types'; import GitHubButton from './GitHubButton'; import TwitterButton from './TwitterButton'; const smallDevice = '@media (max-width: 769px)'; const largeDevice = '@media (min-width: 770px)'; const changes = [ { value: '/props', icon: '❤️', label: 'Simpler and more extensible', }, { value: '/styles', icon: '🎨', label: 'CSS-in-JS styling API', }, { value: '/components', icon: '📦', label: 'Replacable component architecture', }, { value: '/advanced', icon: '🔥', label: 'Lots of advanced functionality', }, { value: '/upgrade-guide', icon: '🗺', label: 'Check out the Upgrade Guide', }, ]; function getLabel({ icon, label }) { return ( <div style={{ alignItems: 'center', display: 'flex' }}> <span style={{ fontSize: 18, marginRight: '0.5em' }}>{icon}</span> <span style={{ fontSize: 14 }}>{label}</span> </div> ); } const headerSelectStyles = { control: (base, { isFocused }) => ({ ...base, backgroundClip: 'padding-box', borderColor: 'rgba(0,0,0,0.1)', boxShadow: isFocused ? '0 0 0 1px #4C9AFF' : null, ':hover': { borderColor: 'rgba(0,0,0,0.2)', }, }), option: base => ({ ...base, padding: '4px 12px', }), placeholder: base => ({ ...base, color: 'black', }), }; const Gradient = props => ( <div css={{ backgroundColor: '#2684FF', backgroundImage: 'linear-gradient(135deg, #2684FF 0%, #0747A6 100%)', color: 'white', position: 'relative', zIndex: 2, [largeDevice]: { boxShadow: '0 5px 0 rgba(0, 0, 0, 0.08)', }, }} {...props} /> ); const Container = props => ( <div css={{ boxSizing: 'border-box', maxWidth: 800, marginLeft: 'auto', marginRight: 'auto', padding: 20, [largeDevice]: { paddingBottom: 40, paddingTop: 40, }, }} {...props} /> ); type HeaderProps = RouterProps & { children: any }; type HeaderState = { contentHeight: 'auto' | number, stars: number }; const apiUrl = 'https://api.github.com/repos/jedwatson/react-select'; class Header extends Component<HeaderProps, HeaderState> { nav: HTMLElement; content: HTMLElement; state = { contentHeight: 'auto', stars: 0 }; componentDidMount() { this.getStarCount(); } componentWillReceiveProps({ location }: HeaderProps) { const valid = ['/', '/home']; const shouldCollapse = !valid.includes(this.props.location.pathname); if (location.pathname !== this.props.location.pathname && shouldCollapse) { this.toggleCollapse(); } } getStarCount = () => { fetch(apiUrl) .then(res => res.json()) .then(data => { const stars = data.stargazers_count; this.setState({ stars }); }) .catch(err => { console.error('Error retrieving data', err); }); }; isHome = (props = this.props) => { const valid = ['/', '/home']; return valid.includes(props.location.pathname); }; toggleCollapse = () => { const contentHeight = this.content.scrollHeight; this.setState({ contentHeight }); }; getContent = ref => { if (!ref) return; this.content = ref; }; render() { const { children, history } = this.props; const { contentHeight, stars } = this.state; return ( <Gradient> {children} <Collapse isCollapsed={!this.isHome()} height={contentHeight} innerRef={this.getContent} > <Container> <h1 css={{ fontSize: '2.4em', fontWeight: 'bold', lineHeight: 1, margin: 0, marginTop: '-0.2em', textShadow: '1px 1px 0 rgba(0, 82, 204, 0.33)', color: 'inherit', [largeDevice]: { fontSize: '3.6em', }, }} > React Select <small css={{ color: '#B2D4FF', fontSize: '0.5em', position: 'relative', marginLeft: '0.25em', }} > v2 </small> </h1> <Content stars={stars} onChange={opt => { history.push(opt.value); }} /> </Container> </Collapse> </Gradient> ); } } const Collapse = ({ height, isCollapsed, innerRef, ...props }) => { return ( <div ref={innerRef} css={{ height: isCollapsed ? 0 : height, overflow: isCollapsed ? 'hidden' : null, transition: 'height 260ms cubic-bezier(0.2, 0, 0, 1)', }} {...props} /> ); }; const Content = ({ onChange, stars }) => ( <div css={{ marginTop: 16, [largeDevice]: { display: 'flex' }, }} > <div css={{ flex: 1, [largeDevice]: { paddingRight: 30 } }}> <p style={{ fontSize: '1.25em', lineHeight: 1.4, marginTop: -5, }} > A flexible and beautiful Select Input control for ReactJS with multiselect, autocomplete, async and creatable support. </p> <div css={{ flex: 1, alignItems: 'center' }}> <GitHubButton count={stars} repo="https://github.com/jedwatson/react-select" /> <TwitterButton /> </div> </div> <div css={{ color: 'black', flex: '0 1 320px', [smallDevice]: { paddingTop: 30, }, }} > <div className="animate-dropin"> <Select getOptionLabel={getLabel} isSearchable={false} options={changes} onChange={onChange} value={null} placeholder="🎉 What's new in V2" styles={headerSelectStyles} /> </div> </div> </div> ); export default withRouter(Header);
JavaScript
0.000004
@@ -638,16 +638,17 @@ 'Replac +e able com
f78caa29ca7334a5cfb83469db78863fc9d48256
rename HomeCtrl to HomeController
app/js/app.js
app/js/app.js
'use strict'; var app = angular.module('app', ['ngRoute']); app.config(['$routeProvider', function($routeProvider) { $routeProvider.when('/', { templateUrl: 'partials/home.html', controller: 'HomeCtrl' }); }]); app.controller('HomeCtrl', ['$scope', function($scope) { $scope.value = "foo"; }]);
JavaScript
0.000357
@@ -202,19 +202,25 @@ : 'HomeC -trl +ontroller '%0A %7D);%0A @@ -250,11 +250,17 @@ omeC -trl +ontroller ', %5B
c38d0f425bac4c9c16b822ff84849907205bc8e3
Add playSE
app/js/app.js
app/js/app.js
/* global enchant, Event */ function main() { var DISPLAY_WIDTH = 360; var DISPLAY_HEIGHT = 360; // 表示領域をデバイスの中央に設定します (function () { var doc = document.documentElement; var width = doc.clientWidth; var height = doc.clientHeight; var canvasAspect = DISPLAY_WIDTH / DISPLAY_HEIGHT; var windowAspect = doc.clientWidth / doc.clientHeight; var bodyStyle = document.getElementsByTagName("body")[0].style; var newWidth = (canvasAspect < windowAspect) ? height * canvasAspect : width; var newHeight = (windowAspect < canvasAspect) ? width / canvasAspect : height; bodyStyle.width = newWidth + "px"; bodyStyle.height = newHeight + "px"; })(); enchant(); var core = new Core(DISPLAY_WIDTH, DISPLAY_HEIGHT); ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"].map(function (filename) { var ext = (enchant.ENV.BROWSER === "ie") ? ".mp3" : ".ogg"; var assetName = "sound/" + filename + ext; core.preload(assetName); }); core.preload("img/keys.png"); core.fps = 60; core.onload = function () { var KEY_WIDTH = 40; var KEY_HEIGHT = 200; var KEY_BLACK_HEIGHT = 120; var KEYBOARD_LEFT = (DISPLAY_WIDTH / 2) - (4 * KEY_WIDTH); var KEYBOARD_TOP = (DISPLAY_HEIGHT / 2) - (KEY_HEIGHT / 2); /** * 現在押されているキーです。 * @type Sprite */ var currentKey = null; var background = (function () { var sprite = new Sprite(DISPLAY_WIDTH, DISPLAY_HEIGHT); sprite.image = (function () { var surface = new Surface(DISPLAY_WIDTH, DISPLAY_HEIGHT); var context = surface.context; context.fillStyle = (function () { var grad = context.createLinearGradient(0, 0, 0, DISPLAY_HEIGHT); grad.addColorStop(0, "#666666"); grad.addColorStop(1, "#333333"); return grad; })(); context.fillRect(0, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT); return surface; })(); return sprite; })(); var keys = (function () { var createKey = function (index, isWhite) { var sprite = new Sprite(KEY_WIDTH, KEY_HEIGHT); sprite.image = core.assets["img/keys.png"]; sprite.frame = isWhite ? 0 : 2; sprite.x = KEYBOARD_LEFT + (index * KEY_WIDTH / 2); sprite.y = KEYBOARD_TOP; return sprite; }; return { white: [0, 2, 4, 6, 8, 10, 12, 14].map(function (index) { return createKey(index, true); }), black: [1, 3, 7, 9, 11].map(function (index) { return createKey(index, false); }) }; })(); var keyboard = (function () { var sprite = new Sprite(8 * KEY_WIDTH, KEY_HEIGHT); sprite.x = KEYBOARD_LEFT; sprite.y = KEYBOARD_TOP; var getPressedKey = function (x, y) { var localX = x - KEYBOARD_LEFT; var whiteIndex = Math.floor(localX / KEY_WIDTH); if (whiteIndex < 0 || 8 <= whiteIndex) { return null; } if (KEYBOARD_TOP + KEY_BLACK_HEIGHT < y) { return keys.white[whiteIndex]; } var blackIndex = Math.floor((localX - (KEY_WIDTH / 2)) / KEY_WIDTH); var foundIndex = [0, 1, 3, 4, 5].indexOf(blackIndex); return (foundIndex !== -1) ? keys.black[foundIndex] : keys.white[whiteIndex]; }; var pressedAction = function (e) { var pressedKey = getPressedKey(e.x, e.y); if (pressedKey === currentKey) { return; } if (currentKey) { currentKey.frame--; } if (pressedKey) { pressedKey.frame++; } currentKey = pressedKey; }; sprite.addEventListener(Event.TOUCH_START, pressedAction); sprite.addEventListener(Event.TOUCH_MOVE, pressedAction); sprite.addEventListener(Event.TOUCH_END, function () { if (currentKey) { currentKey.frame--; } currentKey = null; }); return sprite; })(); var scene = core.rootScene; scene.addChild(background); keys.white.map(function (key) { scene.addChild(key); }); keys.black.map(function (key) { scene.addChild(key); }); scene.addChild(keyboard); }; core.start(); } window.onload = main;
JavaScript
0.000001
@@ -747,24 +747,189 @@ %7D)();%0D%0A%0D%0A + var getAudioAssetName = function (name) %7B%0D%0A var ext = (enchant.ENV.BROWSER === %22ie%22) ? %22.mp3%22 : %22.ogg%22;%0D%0A return %22sound/%22 + name + ext;%0D%0A %7D;%0D%0A%0D%0A enchant( @@ -928,24 +928,24 @@ enchant();%0D%0A - var core @@ -1111,151 +1111,48 @@ -var ext = (enchant.ENV.BROWSER === %22ie%22) ? %22.mp3%22 : %22.ogg%22;%0D%0A var assetName = %22sound/%22 + filename + ext;%0D%0A core.preload(assetName +core.preload(getAudioAssetName(filename) );%0D%0A @@ -1405,32 +1405,32 @@ * KEY_WIDTH);%0D%0A - var KEYB @@ -1480,24 +1480,170 @@ HT / 2);%0D%0A%0D%0A + var playSE = function (name) %7B%0D%0A var se = core.assets%5BgetAudioAssetName(name)%5D;%0D%0A se.clone().play();%0D%0A %7D;%0D%0A%0D%0A /**%0D
f1ce5bb995bd24760df8e293f29e91628d41095f
Update default value.
src/moonstone-samples/lib/IntegerPickerSample.js
src/moonstone-samples/lib/IntegerPickerSample.js
var kind = require('enyo/kind'); var FittableRows = require('layout/FittableRows'), BodyText = require('moonstone/BodyText'), Divider = require('moonstone/Divider'), FormCheckbox = require('moonstone/FormCheckbox'), IntegerPicker = require('moonstone/IntegerPicker'), Scroller = require('moonstone/Scroller'); module.exports = kind({ name: 'moon.sample.IntegerPickerSample', kind: FittableRows, classes: 'moon enyo-unselectable enyo-fit', components: [ {kind: Scroller, fit: true, components: [ {kind: Divider, content: 'Integer Picker'}, {name: 'picker', kind: IntegerPicker, value: 2013, min: 1900, max: 2100, minWidth: 84, onChange: 'changed'}, {kind: Divider, content: 'Options'}, {kind: FormCheckbox, content: 'Animate', checked: true, prop: 'animate', onchange: 'checked'}, {kind: FormCheckbox, content: 'Wrap', prop: 'wrap', onchange: 'checked'}, {kind: FormCheckbox, content: 'Padding (5 digits)', onchange: 'paddingChecked'}, {kind: FormCheckbox, content: 'Disabled', prop: 'disabled', onchange: 'checked'} ]}, {kind: Divider, content: 'Result'}, {kind: BodyText, name: 'value', content: 'No change yet'} ], changed: function (sender, ev) { if (this.$.value) { this.$.value.setContent(ev.name + ' changed to ' + ev.value); } }, checked: function (sender, ev) { this.$.picker.set(sender.prop, sender.checked); }, paddingChecked: function (sender, ev) { this.$.picker.set('digits', sender.checked? 5 : null); this.$.picker.render(); } });
JavaScript
0
@@ -605,9 +605,9 @@ 201 -3 +6 , mi
a75ba0567bd50ea7c499be2d2dbfb5ea0e88a23b
Add test for su-dropdown
tags/dropdown/su-dropdown.search.spec.js
tags/dropdown/su-dropdown.search.spec.js
describe('su-dropdown-search', function () { let tag, select let spyOnOpen = sinon.spy() let spyOnClose = sinon.spy() let spyOnSearch = sinon.spy() let items = [ { label: 'State', value: null, default: true }, { value: 'AL', label: 'Alabama' }, { value: 'AK', label: 'Alaska' }, { value: 'AZ', label: 'Arizona' }, { value: 'AR', label: 'Arkansas' }, { value: 'CA', label: 'California' }, { value: 'CO', label: 'Colorado' }, { value: 'CT', label: 'Connecticut' }, { value: 'DE', label: 'Delaware' }, { value: 'DC', label: 'District Of Columbia' }, { value: 'FL', label: 'Florida' }, { value: 'GA', label: 'Georgia' }, { value: 'HI', label: 'Hawaii' }, { value: 'ID', label: 'Idaho' }, { value: 'IL', label: 'Illinois' }, { value: 'IN', label: 'Indiana' }, { value: 'IA', label: 'Iowa' }, { value: 'KS', label: 'Kansas' }, { value: 'KY', label: 'Kentucky' }, { value: 'LA', label: 'Louisiana' }, { value: 'ME', label: 'Maine' }, { value: 'MD', label: 'Maryland' }, { value: 'MA', label: 'Massachusetts' }, { value: 'MI', label: 'Michigan' }, { value: 'MN', label: 'Minnesota' }, { value: 'MS', label: 'Mississippi' }, { value: 'MO', label: 'Missouri' }, { value: 'MT', label: 'Montana' }, { value: 'NE', label: 'Nebraska' }, { value: 'NV', label: 'Nevada' }, { value: 'NH', label: 'New Hampshire' }, { value: 'NJ', label: 'New Jersey' }, { value: 'NM', label: 'New Mexico' }, { value: 'NY', label: 'New York' }, { value: 'NC', label: 'North Carolina' }, { value: 'ND', label: 'North Dakota' }, { value: 'OH', label: 'Ohio' }, { value: 'OK', label: 'Oklahoma' }, { value: 'OR', label: 'Oregon' }, { value: 'PA', label: 'Pennsylvania' }, { value: 'RI', label: 'Rhode Island' }, { value: 'SC', label: 'South Carolina' }, { value: 'SD', label: 'South Dakota' }, { value: 'TN', label: 'Tennessee' }, { value: 'TX', label: 'Texas' }, { value: 'UT', label: 'Utah' }, { value: 'VT', label: 'Vermont' }, { value: 'VA', label: 'Virginia' }, { value: 'WA', label: 'Washington' }, { value: 'WV', label: 'West Virginia' }, { value: 'WI', label: 'Wisconsin' }, { value: 'WY', label: 'Wyoming' } ] let keys = { enter: 13, escape: 27, upArrow: 38, downArrow: 40 } let fireEvent = function (el, name) { var e = document.createEvent('HTMLEvents') e.initEvent(name, false, true) el.dispatchEvent(e) } let fireKeyEvent = function (el, name, keyCode) { let eventObj = document.createEvent("Events") eventObj.initEvent(name, true, true); eventObj.keyCode = keyCode; el.dispatchEvent(eventObj) } beforeEach(function () { $('body').append('<su-dropdown search="true" tabindex="1"></su-dropdown>') tag = riot.mount('su-dropdown', { items })[0] tag.on('open', spyOnOpen) .on('close', spyOnClose) .on('search', spyOnSearch) this.clock = sinon.useFakeTimers() }) afterEach(function () { spyOnOpen.reset() spyOnClose.reset() spyOnSearch.reset() this.clock.restore() tag.unmount() }) it('is mounted', function () { tag.isMounted.should.be.true }) it('text input is exist', function () { should.exist($('su-dropdown .search')) }) it('opens the menu on focus', function () { $('su-dropdown .menu').is(':visible').should.equal(false) $('su-dropdown .search').click() $('su-dropdown .search').focus() this.clock.tick(310) $('su-dropdown .menu').is(':visible').should.equal(true) $('su-dropdown').blur() }) it('adding text to box filters the options list', function () { $('su-dropdown .menu').is(':visible').should.equal(false) $('su-dropdown .search').focus() spyOnSearch.should.have.been.calledOnce $('su-dropdown .menu').is(':visible').should.equal(true) $('su-dropdown .item').length.should.equal(52) spyOnOpen.should.have.been.calledOnce $('su-dropdown .search').val('m') fireEvent($('su-dropdown .search')[0], 'input') $('su-dropdown .item').length.should.equal(15) spyOnSearch.should.have.been.calledTwice }) it('pressing key down will active item', function () { $('su-dropdown').focus() this.clock.tick(310) $('su-dropdown .search').val('m') fireEvent($('su-dropdown .search')[0], 'input') $('su-dropdown .item').length.should.equal(15) let dropdown = $('su-dropdown')[0] fireKeyEvent(dropdown, 'keydown', keys.downArrow) $('su-dropdown .active .text').text().should.equal(items[1].label) fireKeyEvent(dropdown, 'keydown', keys.downArrow) $('su-dropdown .active .text').text().should.equal(items[9].label) fireKeyEvent(dropdown, 'keydown', keys.downArrow) $('su-dropdown .active .text').text().should.equal(items[20].label) $('su-dropdown').blur() }) it('pressing key down when no item', function () { $('su-dropdown').focus() $('su-dropdown .search').val('xxxxx') fireEvent($('su-dropdown .search')[0], 'input') $('su-dropdown .item').length.should.equal(0) let dropdown = $('su-dropdown')[0] fireKeyEvent(dropdown, 'keydown', keys.downArrow) $('su-dropdown .active .text').length.should.equal(0) $('su-dropdown').blur() }) })
JavaScript
0
@@ -5328,38 +5328,58 @@ 0)%0A%0A -$('su-dropdown').blur( +fireKeyEvent(dropdown, 'keyup', keys.enter )%0A %7D)%0A%7D
684f8a04a140ba00e0fd00f0d11269a58e8dc038
fix prod script to allow specifying deploy dir
talamer/packages/scripts/scripts/prod.js
talamer/packages/scripts/scripts/prod.js
const fs = require('fs'); const path = require('path'); const {execSync} = require('child_process'); const argv = process.argv.slice(2); const appDirectory = fs.realpathSync(process.cwd()); execSync( `${path.resolve(__dirname, '../node_modules/.bin/http-server')} ${path.resolve( appDirectory, argv && argv.length > 2 ? argv[1] : 'dist', )} --cors`, {stdio: [0, 1, 2]}, );
JavaScript
0.000002
@@ -319,16 +319,17 @@ length %3E += 2 ? arg
2c08d24511c49804830153cdbd11e0b1112f016b
修复当前tab页面不是配置的首页时,热刷新后tabBar消失的问题 question/101612
src/platforms/app-plus/service/framework/page.js
src/platforms/app-plus/service/framework/page.js
import { initWebview, createWebview } from './webview' import { navigateFinish } from './navigator' import tabBar from '../framework/tab-bar' import { createPage } from '../../page-factory' import { loadPage } from './load-sub-package' const pages = [] export function getCurrentPages (returnAll) { return returnAll ? pages.slice(0) : pages.filter(page => { return !page.$page.meta.isTabBar || page.$page.meta.visible }) } const preloadWebviews = {} export function removePreloadWebview (webview) { const url = Object.keys(preloadWebviews).find(url => preloadWebviews[url].id === webview.id) if (url) { if (process.env.NODE_ENV !== 'production') { console.log(`[uni-app] removePreloadWebview(${webview.id})`) } delete preloadWebviews[url] } } export function closePreloadWebview ({ url }) { const webview = preloadWebviews[url] if (webview) { if (webview.__page__) { if (!getCurrentPages(true).find(page => page === webview.__page__)) { // 未使用 webview.close('none') } else { // 被使用 webview.__preload__ = false } } else { // 未使用 webview.close('none') } delete preloadWebviews[url] } return webview } export function preloadWebview ({ url, path, query }) { if (!preloadWebviews[url]) { const routeOptions = JSON.parse(JSON.stringify(__uniRoutes.find(route => route.path === path))) preloadWebviews[url] = createWebview(path, routeOptions, query, { __preload__: true, __query__: JSON.stringify(query) }) } return preloadWebviews[url] } /** * 首页需要主动registerPage,二级页面路由跳转时registerPage */ export function registerPage ({ url, path, query, openType, webview }) { if (preloadWebviews[url]) { webview = preloadWebviews[url] if (webview.__page__) { // 该预载页面已处于显示状态,不再使用该预加载页面,直接新开 if (getCurrentPages(true).find(page => page === webview.__page__)) { if (process.env.NODE_ENV !== 'production') { console.log(`[uni-app] preloadWebview(${path},${webview.id}) already in use`) } webview = null } else { pages.push(webview.__page__) if (process.env.NODE_ENV !== 'production') { console.log(`[uni-app] reuse preloadWebview(${path},${webview.id})`) } return webview } } } const routeOptions = JSON.parse(JSON.stringify(__uniRoutes.find(route => route.path === path))) if ( openType === 'reLaunch' || ( !__uniConfig.realEntryPagePath && getCurrentPages().length === 0 // redirectTo ) ) { routeOptions.meta.isQuit = true } else if (!routeOptions.meta.isTabBar) { routeOptions.meta.isQuit = false } if (!webview) { webview = createWebview(path, routeOptions, query) } else { webview = plus.webview.getWebviewById(webview.id) webview.nvue = routeOptions.meta.isNVue } if (routeOptions.meta.isTabBar) { routeOptions.meta.visible = true } if (routeOptions.meta.isTabBar && webview.id !== '1') { tabBar.append(webview) } if (process.env.NODE_ENV !== 'production') { console.log(`[uni-app] registerPage(${path},${webview.id})`) } initWebview(webview, routeOptions, path, query) const route = path.slice(1) webview.__uniapp_route = route const pageInstance = { route, options: Object.assign({}, query || {}), $getAppWebview () { // 重要,不能直接返回 webview 对象,因为 plus 可能会被二次替换,返回的 webview 对象内部的 plus 不正确 // 导致 webview.getStyle 等逻辑出错(旧的 webview 内部 plus 被释放) return plus.webview.getWebviewById(webview.id) }, $page: { id: parseInt(webview.id), meta: routeOptions.meta, path, route, openType }, $remove () { const index = pages.findIndex(page => page === this) if (index !== -1) { if (!webview.nvue) { this.$vm.$destroy() } pages.splice(index, 1) if (process.env.NODE_ENV !== 'production') { console.log('[uni-app] removePage(' + path + ')[' + webview.id + ']') } } }, // 兼容小程序框架 selectComponent (selector) { return this.$vm.selectComponent(selector) }, selectAllComponents (selector) { return this.$vm.selectAllComponents(selector) } } pages.push(pageInstance) if (webview.__preload__) { webview.__page__ = pageInstance } // 首页是 nvue 时,在 registerPage 时,执行路由堆栈 if (webview.id === '1' && webview.nvue) { if ( __uniConfig.splashscreen && __uniConfig.splashscreen.autoclose && !__uniConfig.splashscreen.alwaysShowBeforeRender ) { plus.navigator.closeSplashscreen() } __uniConfig.onReady(function () { navigateFinish(webview) }) } if (__PLATFORM__ === 'app-plus') { if (!webview.nvue) { const pageId = webview.id try { loadPage(route, () => { createPage(route, pageId, query, pageInstance).$mount() }) } catch (e) { console.error(e) } } } return webview }
JavaScript
0.000001
@@ -3135,30 +3135,8 @@ bBar - && webview.id !== '1' ) %7B%0D @@ -5224,9 +5224,10 @@ bview%0D%0A%7D +%0D %0A
5317560d7fbc19367c453c918092c1819331d530
update bulid docs script to reference new templates package
docs/build_docs.js
docs/build_docs.js
var scrawl = require('../deps/scrawl'), Showdown = require('../deps/showdown'), async = require('../deps/async'), utils = require('../lib/utils'), templates = require('../packages/kanso.templates/build/templates'), dust = require('../deps/dustjs/lib/dust'), path = require('path'), fs = require('fs'); var output_dir = __dirname + '/../www'; var template_dir = __dirname + '/templates'; function get_named_public_apis(comments) { return comments.filter(function (c) { return c.api === 'public' && c.name; }); } function get_module_comment(comments) { return comments.filter(function (c) { return c.module; })[0]; }; function render_module(module) { var html = '<h2 id="' + module.name + '">' + module.name + '</h2>'; var c = get_module_comment(module.comments); if (c) { html += c.description_html; } var items = get_named_public_apis(module.comments); return html + items.map(function (i) { return render_item(module, i); }).join(''); } function render_item(module, item) { var html = '<h3 id="' + item_id(module, item) + '">' + item.name + '</h3>'; html += item.description_html; if (item.params) { html += '<h4>Parameters</h4>'; html += '<table class="params">'; html += item.params.map(function (p) { return '<tr>' + '<td class="name">' + (p.name || '') + '</td>' + '<td class="type">' + (p.type || '') + '</td>' + '<td class="description">' + (p.description || '') + '</td>' + '</tr>'; }).join(''); html += '</table>'; } if (item.returns) { html += '<div class="returns">' + '<strong>Returns: </strong>' + '<span class="type">' + item.returns + '</span>' + '</div>'; } return html; } function item_id(module, item) { return module.name + '.' + item.name.replace(/\(.*$/, ''); } function create_page(infile, outfile, nav, title, rootURL, callback) { if (!callback) { callback = rootURL; rootURL = '.'; } fs.readFile(infile, function (err, content) { if (err) { return callback(err); } var converter = new Showdown.converter(); var html = converter.makeHtml(content.toString()); if (!title && title !== '') { title = content.toString().replace(/^\s*# /, '').replace(/\n.*/g, ''); } var navobj = {}; navobj[nav] = true; var context = { content: html, rootURL: rootURL, nav: navobj, title: title }; dust.render('base.html', context, function (err, result) { if (err) { return callback(err); } fs.writeFile(outfile, result, callback); }); }); } function create_guides(dir, outdir, callback) { utils.find(dir, /\.md$/, function (err, files) { async.forEach(files, function (f, cb) { var name = path.basename(f, '.md'); create_page( f, outdir + '/' + name + '.html', 'guides', null, '..', callback ); }); }); } function load_templates(path, callback) { templates.find(path, function (err, paths) { if (err) { return callback(err); } async.forEach(paths, function (p, cb) { fs.readFile(p, function (err, content) { if (err) { return callback(err); } var rel = utils.relpath(p, path); dust.compileFn(content.toString(), rel); cb(); }); }, callback); }); } async.parallel({ load_templates: async.apply(load_templates, template_dir), ensureDir: async.apply(utils.ensureDir, output_dir) }, function (err, results) { if (err) { console.error(err); return console.error(err.stack); } var modules = results.parseModules; async.parallel([ async.apply( create_page, __dirname + '/index.md', output_dir + '/index.html', 'about', '' ), async.apply( create_page, __dirname + '/download.md', output_dir + '/download.html', 'download', '' ), async.apply( create_page, __dirname + '/community.md', output_dir + '/community.html', 'community', 'Community' ), async.apply( create_page, __dirname + '/docs.md', output_dir + '/docs.html', 'api', 'API' ), async.apply( create_page, __dirname + '/tutorial.md', output_dir + '/tutorial.html', 'guides', 'Guides' ), async.apply( create_guides, __dirname + '/guides', output_dir + '/guides' ) ], function (err) { if (err) { console.error(err); return console.error(err.stack); } console.log('OK'); }); });
JavaScript
0
@@ -194,17 +194,17 @@ es/kanso -. +- template
248fdbaddfa37f638017a4fddbc3ef6426f476d7
Change copy for finish cert message (#1590)
src/providers/sh/util/certs/finish-cert-order.js
src/providers/sh/util/certs/finish-cert-order.js
// @flow import chalk from 'chalk' import psl from 'psl' import { Now } from '../types' import * as Errors from '../errors' import wait from '../../../../util/output/wait' import type { Certificate } from '../types' export default async function startCertOrder(now: Now, cns: string[], context: string) { const cancelWait = wait(`Finishing certificate issuance for ${chalk.bold(cns.join(', '))}`); try { const cert: Certificate = await now.fetch('/v3/now/certs', { method: 'PATCH', body: { op: "finalizeOrder", domains: cns }, }) cancelWait() return cert } catch (error) { cancelWait() if (error.code === 'cert_order_not_found') { return new Errors.CertOrderNotFound(cns); } else if (error.code === 'configuration_error') { const {domain, subdomain} = psl.parse(error.domain) return new Errors.DomainConfigurationError(domain, subdomain, error.external) } else if (error.code === 'forbidden') { return new Errors.DomainPermissionDenied(error.domain, context) } else if (error.code === 'wildcard_not_allowed') { return new Errors.CantGenerateWildcardCert() } else if (error.code === 'rate_limited') { return new Errors.TooManyCertificates(error.domains) } else if (error.code === 'too_many_requests') { return new Errors.TooManyRequests({api: 'certificates', retryAfter: error.retryAfter}) } else if (error.code === 'validation_running') { return new Errors.DomainValidationRunning(error.domain) } else if (error.code === 'should_share_root_domain') { return new Errors.DomainsShouldShareRoot(error.domains) } else if (error.code === 'cant_solve_challenge') { return new Errors.CantSolveChallenge(error.domain, error.type) } else if (error.code === 'invalid_wildcard_domain') { return new Errors.InvalidWildcardDomain(error.domain) } else { // Throw unexpected errors throw error } } }
JavaScript
0
@@ -330,18 +330,18 @@ it(%60 -Finish +Issu ing +a cert @@ -352,17 +352,8 @@ ate -issuance for
8880c09076e4727768ace26a74766cbe6f64021c
Rename `Keyboard.remove{Event =>}Listener`
Libraries/Components/Keyboard/Keyboard.js
Libraries/Components/Keyboard/Keyboard.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow strict-local */ import NativeEventEmitter from '../../EventEmitter/NativeEventEmitter'; import LayoutAnimation from '../../LayoutAnimation/LayoutAnimation'; import dismissKeyboard from '../../Utilities/dismissKeyboard'; import Platform from '../../Utilities/Platform'; import NativeKeyboardObserver from './NativeKeyboardObserver'; import type {EventSubscription} from '../../vendor/emitter/EventEmitter'; export type KeyboardEventName = $Keys<KeyboardEventDefinitions>; export type KeyboardEventEasing = | 'easeIn' | 'easeInEaseOut' | 'easeOut' | 'linear' | 'keyboard'; export type KeyboardEventCoordinates = $ReadOnly<{| screenX: number, screenY: number, width: number, height: number, |}>; export type KeyboardEvent = AndroidKeyboardEvent | IOSKeyboardEvent; type BaseKeyboardEvent = {| duration: number, easing: KeyboardEventEasing, endCoordinates: KeyboardEventCoordinates, |}; export type AndroidKeyboardEvent = $ReadOnly<{| ...BaseKeyboardEvent, duration: 0, easing: 'keyboard', |}>; export type IOSKeyboardEvent = $ReadOnly<{| ...BaseKeyboardEvent, startCoordinates: KeyboardEventCoordinates, isEventFromThisApp: boolean, |}>; type KeyboardEventDefinitions = { keyboardWillShow: [KeyboardEvent], keyboardDidShow: [KeyboardEvent], keyboardWillHide: [KeyboardEvent], keyboardDidHide: [KeyboardEvent], keyboardWillChangeFrame: [KeyboardEvent], keyboardDidChangeFrame: [KeyboardEvent], }; /** * `Keyboard` module to control keyboard events. * * ### Usage * * The Keyboard module allows you to listen for native events and react to them, as * well as make changes to the keyboard, like dismissing it. * *``` * import React, { Component } from 'react'; * import { Keyboard, TextInput } from 'react-native'; * * class Example extends Component { * componentWillMount () { * this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow); * this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide); * } * * componentWillUnmount () { * this.keyboardDidShowListener.remove(); * this.keyboardDidHideListener.remove(); * } * * _keyboardDidShow () { * alert('Keyboard Shown'); * } * * _keyboardDidHide () { * alert('Keyboard Hidden'); * } * * render() { * return ( * <TextInput * onSubmitEditing={Keyboard.dismiss} * /> * ); * } * } *``` */ class Keyboard { _emitter: NativeEventEmitter<KeyboardEventDefinitions> = new NativeEventEmitter( // T88715063: NativeEventEmitter only used this parameter on iOS. Now it uses it on all platforms, so this code was modified automatically to preserve its behavior // If you want to use the native module on other platforms, please remove this condition and test its behavior Platform.OS !== 'ios' ? null : NativeKeyboardObserver, ); /** * The `addListener` function connects a JavaScript function to an identified native * keyboard notification event. * * This function then returns the reference to the listener. * * @param {string} eventName The `nativeEvent` is the string that identifies the event you're listening for. This *can be any of the following: * * - `keyboardWillShow` * - `keyboardDidShow` * - `keyboardWillHide` * - `keyboardDidHide` * - `keyboardWillChangeFrame` * - `keyboardDidChangeFrame` * * Note that if you set `android:windowSoftInputMode` to `adjustResize` or `adjustNothing`, * only `keyboardDidShow` and `keyboardDidHide` events will be available on Android. * `keyboardWillShow` as well as `keyboardWillHide` are generally not available on Android * since there is no native corresponding event. * * @param {function} callback function to be called when the event fires. */ addListener<K: $Keys<KeyboardEventDefinitions>>( eventType: K, listener: (...$ElementType<KeyboardEventDefinitions, K>) => mixed, context?: mixed, ): EventSubscription { return this._emitter.addListener(eventType, listener); } /** * @deprecated Use `remove` on the EventSubscription from `addEventListener`. */ removeEventListener<K: $Keys<KeyboardEventDefinitions>>( eventType: K, listener: (...$ElementType<KeyboardEventDefinitions, K>) => mixed, ): void { // NOTE: This will report a deprecation notice via `console.error`. this._emitter.removeListener(eventType, listener); } /** * Removes all listeners for a specific event type. * * @param {string} eventType The native event string listeners are watching which will be removed. */ removeAllListeners<K: $Keys<KeyboardEventDefinitions>>(eventType: ?K): void { this._emitter.removeAllListeners(eventType); } /** * Dismisses the active keyboard and removes focus. */ dismiss(): void { dismissKeyboard(); } /** * Useful for syncing TextInput (or other keyboard accessory view) size of * position changes with keyboard movements. */ scheduleLayoutAnimation(event: KeyboardEvent): void { const {duration, easing} = event; if (duration != null && duration !== 0) { LayoutAnimation.configureNext({ duration: duration, update: { duration: duration, type: (easing != null && LayoutAnimation.Types[easing]) || 'keyboard', }, }); } } } module.exports = (new Keyboard(): Keyboard);
JavaScript
0.000295
@@ -4397,21 +4397,16 @@ rom %60add -Event Listener @@ -4422,21 +4422,16 @@ remove -Event Listener
0ed14e78499f08f7744de993bee89903386f3ec1
fix missing 'afterEach' import
blueprints/initializer-test/mocha-files/tests/unit/initializers/__name__-test.js
blueprints/initializer-test/mocha-files/tests/unit/initializers/__name__-test.js
import { expect } from 'chai'; import { describe, it, beforeEach } from 'mocha'; import Ember from 'ember'; import { initialize } from '<%= dasherizedModulePrefix %>/initializers/<%= dasherizedModuleName %>'; import destroyApp from '../../helpers/destroy-app'; describe('<%= friendlyTestName %>', function() { let application; beforeEach(function() { Ember.run(function() { application = Ember.Application.create(); application.deferReadiness(); }); }); afterEach(function() { destroyApp(application); }); // Replace this with your real tests. it('works', function() { initialize(application); // you would normally confirm the results of the initializer here expect(true).to.be.ok; }); });
JavaScript
0.99927
@@ -57,16 +57,27 @@ foreEach +, afterEach %7D from
a205caefe68d4c9279aaa86470c30974da226874
Update eBay highlight script to work with new classes
Miscellaneous/ebay.highlight-bids.user.js
Miscellaneous/ebay.highlight-bids.user.js
// ==UserScript== // @name eBay - Hilight Items With Bids // @namespace http://mathemaniac.org // @include http://*.ebay.*/* // @grant none // @version 2.3.1 // @require http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js // @description Hilights items that have bids with a red border and yellow background. // ==/UserScript== // Based on http://userscripts-mirror.org/scripts/show/66089.html v.2.2.1 // Updated for newer eBay layout. $('document').ready(function() { $(".bids span").each(function() { // Skip listings with no bids. if ($(this).text().match(/\b0 bids/)) return; $(this).closest('li[listingid]').css({ "border": "3px solid red", "background-color": "yellow" }); }); });
JavaScript
0
@@ -179,17 +179,17 @@ 2.3. -1 +2 %0A// @req @@ -408,43 +408,25 @@ ipts --mirror.org/scripts/show/66089.html +.org/users/126140 v.2 @@ -510,17 +510,26 @@ $(%22. -bids span +lvprices .lvformat %22).e @@ -621,16 +621,53 @@ tch(/%5Cb0 + bids/) %7C%7C !$(this).text().match(/%5Cd+ bids/))
5de7c3e859a9aa501482e8016e8b52387406ad1e
set highlight mode to ruby in custom.js
static/custom/custom.js
static/custom/custom.js
/* Placeholder for custom JS */ $(function() { console.log("IRuby profile loaded") // load CodeMirror mode for Ruby $.getScript('/static/components/codemirror/mode/ruby/ruby.js'); });
JavaScript
0.000001
@@ -180,12 +180,78 @@ y.js');%0A + IPython.CodeCell.options_default%5B%22cm_config%22%5D%5B%22mode%22%5D = %22ruby%22;%0A %7D);%0A
45f7c21f494289e4ac79e0a29482109d8ba66d40
Update get_census.js
static/js/get_census.js
static/js/get_census.js
$.get( "https://raw.githubusercontent.com/Cutwell/Hacktoberfest-Census/master/README.md", function(file) { var census_md = file.split("### Census")[1].split("\n"); census_md.map((user) => { if(user == ""){ return; } var name = user.substring(user.lastIndexOf("[")+1, user.lastIndexOf("]")); var url = user.substring(user.lastIndexOf("(")+1, user.lastIndexOf(")")); $("#census-list").append("<li class='census-item'><a href="+url+">"+name+"</a></li>"); }); var census_count = census_md.length - 2; $("#census-count").html(census_count+" Contributors:"); } );
JavaScript
0.000001
@@ -43,15 +43,20 @@ com/ -Cutwell +AllenCompSci /Hac @@ -69,15 +69,8 @@ fest --Census /mas
1162c95ee01cef8aea8b333dcc3d6ca4dddf5ac6
Update Less to 1.7.0
frame/js/frame.js
frame/js/frame.js
(function() { 'use strict'; // nothing to see here if (parent === self) { window.location = '//' + location.hostname.replace(/^frame\./, ''); return; } requirejs.config({ paths: { jquery: '//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min', underscore: '//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min', string: '//cdnjs.cloudflare.com/ajax/libs/underscore.string/2.3.3/underscore.string.min', marked: '//cdnjs.cloudflare.com/ajax/libs/marked/0.3.1/marked.min', jade: '//cdnjs.cloudflare.com/ajax/libs/jade/1.3.0/jade.min', haml: '//cdnjs.cloudflare.com/ajax/libs/clientside-haml-js/5.4/haml.min', less: '//cdnjs.cloudflare.com/ajax/libs/less.js/1.6.3/less.min', sass: '//cdnjs.cloudflare.com/ajax/libs/sass.js/0.2.0/sass.min', traceur: '/js/lib/compilers/traceur.min', traceur_api: '/js/lib/compilers/traceur-api.min', coffeescript: '//cdnjs.cloudflare.com/ajax/libs/coffee-script/1.7.1/coffee-script.min', 'typescript-api': '//cdnjs.cloudflare.com/ajax/libs/typescript/0.9.7/typescript.min', typestring: '/js/lib/compilers/typestring.min', gorillascript: '//cdnjs.cloudflare.com/ajax/libs/gorillascript/0.9.10/gorillascript.min' }, shim: { string: { deps: ['underscore'], exports: '_.str' }, haml: { exports: 'haml' }, traceur: { exports: 'traceur' }, 'typescript-api': { exports: 'TypeScript' }, } }); require(['jquery', 'underscore', 'compiler'], function($, _, compiler) { $(function() { var $frame = $('#frame'); $(window).on('message', function(e) { var oe = e.originalEvent; if (!oe.origin) { return; } // send ack to parent frame oe.source.postMessage(oe.data.timestamp, oe.origin); compiler.compile_to_doc_str(oe.data.map).done(function(str) { _.defer(function() { // clear the current document $frame.attr('srcdoc', '').removeAttr('srcdoc'); var doc = $frame[0].contentDocument; doc.open(); doc.write(str); doc.close(); }); }); }); }); }); })();
JavaScript
0
@@ -731,11 +731,11 @@ s/1. -6.3 +7.0 /les
53a576de8bc1d5cdfc74e8bec042bf7064017405
add additional unit tests
test/dictionary.spec.js
test/dictionary.spec.js
/* globals describe it beforeEach afterEach */ require('should'); var Dictionary = require('../'); describe('Dictionary Unit Tests', function() { var dict; beforeEach(function () { dict = new Dictionary(); }); afterEach(function () { dict = null; }); it('should have a working test environment', function() { true.should.equal(true); }); it('should instantiate a dictionary instance', function () { dict.should.be.ok; dict.should.be.instanceof(Dictionary); }); it('should be empty when first instantiated', function () { dict.isEmpty().should.equal(true); dict.size().should.equal(0); }); it('should add items to the dictionary', function () { dict.set('dict', 'data structure'); dict.set('set', 'another data structure'); dict.size().should.equal(2); }); it('should determine if the dictionary has a particular key', function () { dict.set('dict', 'data structure'); dict.set('set', 'another data structure'); dict.has('dict').should.equal(true); dict.has('set').should.equal(true); }); it('should correctly remove an item', function () { dict.set('dict', 'data structure'); dict.set('set', 'another data structure'); dict.remove('dict').should.equal(true); dict.size().should.equal(1); dict.remove('nothing').should.equal(false); }); it('should correctly get an item', function () { dict.set('dict', 'data structure'); dict.set('set', 'another data structure'); dict.get('dict').should.equal('data structure'); dict.get('set').should.equal('another data structure'); dict.get('nothing').should.equal(-1); }); });
JavaScript
0
@@ -1782,13 +1782,1631 @@ %0A %7D); +%0A%0A it('should return all the keys in the dictionary', function () %7B%0A dict.set('dict', 'data structure');%0A dict.set('set', 'another data structure');%0A dict.set('linked-list', 'a very good data structure');%0A var keys = dict.keys();%0A keys.should.be.an.Array;%0A keys.should.be.length(3);%0A keys.should.containEql('dict', 'set', 'linked-list');%0A %7D);%0A%0A it('should return all the values in the dictionary', function () %7B%0A dict.set('dict', 'data structure');%0A dict.set('set', 'another data structure');%0A dict.set('linked-list', 'a very good data structure');%0A var values = dict.values();%0A values.should.be.an.Array;%0A values.should.be.length(3);%0A values.should.containEql('data structure',%0A 'another data structure', 'a very good data structure');%0A %7D);%0A%0A it('should return the complete contents of the dictionary', function () %7B%0A dict.set('dict', 'data structure');%0A dict.set('set', 'another data structure');%0A dict.set('linked-list', 'a very good data structure');%0A var items = dict.getItems();%0A items.should.be.an.Object;%0A items.should.have.properties('set', 'dict', 'linked-list');%0A %7D);%0A%0A it('should clear the dictionary of all items', function () %7B%0A dict.set('dict', 'data structure');%0A dict.set('set', 'another data structure');%0A dict.set('linked-list', 'a very good data structure');%0A dict.size().should.equal(3);%0A dict.clear();%0A dict.size().should.equal(0);%0A dict.isEmpty().should.equal(true);%0A %7D); %0A%7D);%0A
52cc8a53b0f34038ef23cf425adcfaee6872a66b
Update scripts.js
library/js/scripts.js
library/js/scripts.js
/* * Bones Scripts File * Author: Eddie Machado * * This file should contain any js scripts you want to add to the site. * Instead of calling it in the header or throwing it inside wp_head() * this file will be called automatically in the footer so as not to * slow the page load. * * There are a lot of example functions and tools in here. If you don't * need any of it, just remove it. They are meant to be helpers and are * not required. It's your world baby, you can do whatever you want. */ /* * IE8 ployfill for GetComputed Style (for Responsive Script below) * If you don't want to support IE8, you can just remove this. */ if (!window.getComputedStyle) { window.getComputedStyle = function(el, pseudo) { this.el = el; this.getPropertyValue = function(prop) { var re = /(\-([a-z]){1})/g; if (prop == 'float') prop = 'styleFloat'; if (re.test(prop)) { prop = prop.replace(re, function () { return arguments[2].toUpperCase(); }); } return el.currentStyle[prop] ? el.currentStyle[prop] : null; } return this; } } /* * Get Viewport Dimensions * returns object with viewport dimensions to match css in width and height properties * ( source: http://andylangton.co.uk/blog/development/get-viewport-size-width-and-height-javascript ) */ function updateViewportDimensions() { var w=window,d=document,e=d.documentElement,g=d.getElementsByTagName('body')[0],x=w.innerWidth||e.clientWidth||g.clientWidth,y=w.innerHeight||e.clientHeight||g.clientHeight; return {width:x,height:y} } // setting the viewport width var viewport = updateViewportDimensions(); /* * Throttle Resize-triggered Events * Wrap your actions in this function to throttle the frequency of firing them off, for better performance, esp. on mobile. * ( source: http://stackoverflow.com/questions/2854407/javascript-jquery-window-resize-how-to-fire-after-the-resize-is-completed ) */ var waitForFinalEvent = (function () { var timers = {}; return function (callback, ms, uniqueId) { if (!uniqueId) { uniqueId = "Don't call this twice without a uniqueId"; } if (timers[uniqueId]) { clearTimeout (timers[uniqueId]); } timers[uniqueId] = setTimeout(callback, ms); }; })(); // how long to wait before deciding the resize has stopped, in ms. Around 50-100 should work ok. var timeToWaitForLast = 100; /* * Here's an example so you can see how we're using the above function * * This is commented out so it won't work, but you can copy it and * remove the comments. * * * * If we want to only do it on a certain page, we can setup checks so we do it * as efficient as possible. * * if( typeof is_home === "undefined" ) var is_home = $('body').hasClass('home'); * * This once checks to see if you're on the home page based on the body class * We can then use that check to perform actions on the home page only * * When the window is resized, we perform this function * $(window).resize(function () { * * // if we're on the home page, we wait the set amount (in function above) then fire the function * if( is_home ) { waitForFinalEvent( function() { * * // if we're above or equal to 768 fire this off * if( viewport.width >= 768 ) { * console.log('On home page and window sized to 768 width or more.'); * } else { * // otherwise, let's do this instead * console.log('Not on home page, or window sized to less than 768.'); * } * * }, timeToWaitForLast, "your-function-identifier-string"); } * }); * * Pretty cool huh? You can create functions like this to conditionally load * content and other stuff dependent on the viewport. * Remember that mobile devices and javascript aren't the best of friends. * Keep it light and always make sure the larger viewports are doing the heavy lifting. * */ /* * We're going to swap out the gravatars. * In the functions.php file, you can see we're not loading the gravatar * images on mobile to save bandwidth. Once we hit an acceptable viewport * then we can swap out those images since they are located in a data attribute. */ function loadGravatars() { // set the viewport using the function above viewport = updateViewportDimensions(); // if the viewport is tablet or larger, we load in the gravatars if (viewport.width >= 768) { $('.comment img[data-gravatar]').each(function(){ $(this).attr('src',$(this).attr('data-gravatar')); }); } } // end function /* * Put all your regular jQuery in here. */ jQuery(document).ready(function($) { /* * Let's fire off the gravatar function * You can remove this if you don't need it */ loadGravatars(); }); /* end of as page load scripts */
JavaScript
0
@@ -4387,17 +4387,22 @@ %7B%0A -$ +jQuery (this).a
f08fcf785f6fb4300c841023abc047d6fe97571d
initialize icon only if model has attribute
attricon.js
attricon.js
/** * An miniscule Backbone view that binds an icon className to a model attribute. * @param {[options]} * model The model to bind to. * attribute The attribute of the model to map to an icon. * iconMap An object that maps the attribute value to an icon. */ define(function(require){ var Backbone = require('backbone') , _ = require('underscore'); var Attricon = Backbone.View.extend({ tagName: 'i', initialize: function(options){ if(! (options && options.attribute && options.iconMap && this.model)){ throw new Error('Attricon view requires a model, an attribute, and an iconMap'); } this.iconMap = options.iconMap; this.listenTo(this.model, 'change:' + options.attribute, function(model, value){ this.addIcon(value); }); this.addIcon(this.model.get(options.attribute)); }, addIcon: function(value){ var iconMap = this.iconMap, icon = iconMap[value]; Object.keys(iconMap).forEach(function(key){ this.$el[key === value ? 'addClass' : 'removeClass'](iconMap[key]); }, this); } }, { Status: { 'pending': 'icon-spinner icon-spin', 'success': 'icon-check', 'error': 'icon-warning-sign' }, OS: { 'linux': 'icon-linux', 'android': 'icon-android', 'apple': 'icon-apple', 'windows': 'icon-windows' } }); return Attricon; });
JavaScript
0.000001
@@ -348,40 +348,8 @@ ne') -%0A , _ = require('underscore') ;%0A%0A @@ -781,16 +781,63 @@ %7D);%0A%0A + if(this.model.has(options.attribute))%7B%0A th @@ -883,16 +883,24 @@ bute));%0A + %7D%0A %7D,%0A%0A
be0c6f26036575f46a120edd02a3192a1615f853
extend timeout
test/e2e.travis.conf.js
test/e2e.travis.conf.js
/* global exports */ // An example configuration file. exports.config = { specs: ['e2e/**/*Spec.js'], baseUrl: 'http://localhost:8000', sauceUser: process.env.SAUCE_USERNAME, sauceKey: process.env.SAUCE_ACCESS_KEY, multiCapabilities: [{ browserName: 'chrome', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER }, { browserName: 'firefox', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER }, { browserName: 'internet explorer', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER }, { browserName: 'safari', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER }] };
JavaScript
0.000078
@@ -606,12 +606,36 @@ BER%0A %7D%5D +,%0A getPageTimeout: 2000 %0A%7D;%0A
635fcab339eae759331775b57fceff53d3e4cf74
Add friendly unknown filesize
app/public.js
app/public.js
(function() { const OVERLAY_CLASS = 'ncc-image-checker-overlay'; const URL_CLASS = 'ncc-image-checker-url'; const BACKGROUND_IMAGE_URL_REGEX = /url\((.*)\)/i; function showImagesInfo(images) { images = images || document.getElementsByTagName('*'); images = nodeListToArray(images); let body = document.getElementsByTagName('body')[0]; getImages(images).map(image => { let div = document.createElement('div'); div.classList.add(OVERLAY_CLASS); div.style.width = image.width + 'px'; div.style.height = image.height + 'px'; div.style.top = image.position.top + 'px'; div.style.left = image.position.left + 'px'; const MIN_IMAGE_CONTENT_WIDTH = 150; const MIN_IMAGE_CONTENT_HEIGHT = 50; const MIN_IMAGE_URL_HEIGHT = 120; if (image.width > MIN_IMAGE_CONTENT_WIDTH && image.height > MIN_IMAGE_CONTENT_HEIGHT) { div.setAttribute('title', image.url); if (image.height > MIN_IMAGE_URL_HEIGHT) { let url = document.createElement('a'); url.innerHTML = getTruncatedImageUrl(image); url.setAttribute('href', image.url); url.setAttribute('target', '_blank'); url.classList.add(URL_CLASS); div.appendChild(url); appendInfoToElement(div, image); body.appendChild(div); } else { appendInfoToElement(div, image); appendAnchorToBody(div, image.url); } } else { let info = `Coverage: ${ getImageCoverage(image).toFixed(2) }%`; if (image.size) { info += `, File Size: ${ image.size } KB`; } info += `, URL: ${ image.url }`; div.setAttribute('title', info); appendAnchorToBody(div, image.url); } }); } function hideImagesInfo() { nodeListToArray(document.querySelectorAll('.ncc-image-checker-overlay')).map(o => o.remove()); } function isImagesInfoActive() { return document.querySelectorAll('.ncc-image-checker-overlay').length > 0; } function appendInfoToElement(div, image) { let renderedP = document.createElement('p'); renderedP.innerHTML = `Display: ${ image.width } x ${ image.height }`; div.appendChild(renderedP); let naturalP = document.createElement('p'); naturalP.innerHTML = `Natural: ${ image.naturalSize.width } x ${ image.naturalSize.height }`; div.appendChild(naturalP); let optimalP = document.createElement('p'); optimalP.innerHTML = `Image coverage: ${ getImageCoverage(image).toFixed(2) }%`; div.appendChild(optimalP); if (image.size) { let sizeP = document.createElement('p'); sizeP.innerHTML = `File Size: ${ image.size } KB`; div.appendChild(sizeP); } } function appendAnchorToBody(element, url) { let anchor = document.createElement('a'); anchor.setAttribute('href', url); anchor.setAttribute('target', '_blank'); anchor.appendChild(element); document.getElementsByTagName('body')[0].appendChild(anchor); } function getImageCoverage(image) { let naturalArea = image.naturalSize.width * image.naturalSize.height; let renderArea = image.width * image.height * window.devicePixelRatio; return (naturalArea / renderArea * 100); } function getTruncatedImageUrl(image) { const BOUNDING_BOX_PADDING = 10; const CHARACTER_WIDTH = 10; let limit = 2 * (image.width - BOUNDING_BOX_PADDING) / CHARACTER_WIDTH; let replace = '...'; let partialLeft = Math.ceil((limit - replace.length) / 2); let partialRight = Math.floor((limit - replace.length) / 2); if (image.url.length > limit) { return image.url.substr(0, partialLeft) + replace + image.url.substr(-partialRight); } else { return image.url; } } // this is the last point element is a DOM element function getImages(domNodes) { let images = getAvailableImages(domNodes); return images.map(element => { let size = getSize(element); if (typeof size === 'number') { size = (size / 1024).toFixed(3); } return { url: getUrl(element), size: size, position: getElementTopLeft(element), height: element.offsetHeight, width: element.offsetWidth, naturalSize: getNaturalSize(element) }; }).filter(byVisibleImage); } function getAvailableImages(elementsArray) { return elementsArray .filter(byProbableImage) .filter(byHasUrl); } function byVisibleImage(image) { return (image.height && image.width && typeof image.position.top === 'number' && typeof image.position.left === 'number') } function byProbableImage(element) { let style = window.getComputedStyle(element); if (style.visibility === 'hidden') { return false; } if (element.tagName.toLowerCase() === 'img') { return true; } if (style.backgroundImage) { let urlMatcher = BACKGROUND_IMAGE_URL_REGEX.exec(style.backgroundImage); if (urlMatcher && urlMatcher.length > 1) { return true; } } return false; } function byHasUrl(element) { return !!getUrl(element); } function getElementTopLeft(elem) { let location = { top: 0, left: 0 }; if (elem.x && elem.y) { location.top = elem.y; location.left = elem.x; } else if (elem.offsetParent) { do { location.top += elem.offsetTop; location.left += elem.offsetLeft; elem = elem.offsetParent; } while (elem); } return location; } function getNaturalSize(element) { if (element.naturalWidth) { return { width: element.naturalWidth, height: element.naturalHeight }; } else { let image = new Image(); image.src = getUrl(element); return { width: image.naturalWidth, height: image.naturalHeight }; } } function getSize(element) { let performanceEntry = performance.getEntriesByName(getUrl(element))[0]; if (performanceEntry) { return performanceEntry.encodedBodySize; } } function getUrl(element) { if (element.src) { return element.src; } else { let bkg = window.getComputedStyle(element).backgroundImage; let url = BACKGROUND_IMAGE_URL_REGEX.exec(bkg); if (url) { return url[1].replace(/["]/g, ''); } } } function nodeListToArray(nodeList) { let array = []; for (let i = 0; i < nodeList.length; i += 1) { array[i] = nodeList[i]; } return array; } window.NCC = window.NCC || {}; window.NCC.imageChecker = { showImagesInfo: showImagesInfo, hideImagesInfo: hideImagesInfo, isImagesInfoActive: isImagesInfoActive, _getImages: getImages, _nodeListToArray: nodeListToArray, _getUrl: getUrl, _getSize: getSize, _getNaturalSize: getNaturalSize, _getElementTopLeft: getElementTopLeft, _getAvailableImages: getAvailableImages, _getTruncatedImageUrl: getTruncatedImageUrl }; }());
JavaScript
0
@@ -1550,32 +1550,50 @@ if (image.size + && image.size %3E 0 ) %7B%0A in @@ -2681,16 +2681,33 @@ erHTML = + image.size %3E 0 ? %60File S @@ -2722,32 +2722,58 @@ image.size %7D KB%60 + : %60File size unavailable%60 ;%0A div.appe
ad86d9a51bca001a52969d6cae65957023e30e9c
Update dropdown.js
js/dropdown.js
js/dropdown.js
/* ======================================================================== * Bootstrap: dropdown.js v3.0.2 * http://getbootstrap.com/javascript/#dropdowns * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle=dropdown]' var Dropdown = function (element) { var $el = $(element).on('click.bs.dropdown', this.toggle) } Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we we use a backdrop because click events don't delegate $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus) } $parent.trigger(e = $.Event('show.bs.dropdown')) if (e.isDefaultPrevented()) return $parent .toggleClass('open') .trigger('shown.bs.dropdown') $this.focus() } return false } Dropdown.prototype.keydown = function (e) { if (!/(38|40|27)/.test(e.keyCode)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if (!isActive || (isActive && e.keyCode == 27)) { if (e.which == 27) $parent.find(toggle).focus() return $this.click() } var $items = $('[role=menu] li:not(.divider):visible a', $parent) if (!$items.length) return var index = $items.index($items.filter(':focus')) if (e.keyCode == 38 && index > 0) index-- // up if (e.keyCode == 40 && index < $items.length - 1) index++ // down if (!~index) index=0 $items.eq(index).focus() } function clearMenus() { $(backdrop).remove() $(toggle).each(function (e) { var $parent = getParent($(this)) if (!$parent.hasClass('open')) return $parent.trigger(e = $.Event('hide.bs.dropdown')) if (e.isDefaultPrevented()) return $parent.removeClass('open').trigger('hidden.bs.dropdown') }) } function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } // DROPDOWN PLUGIN DEFINITION // ========================== var old = $.fn.dropdown $.fn.dropdown = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('dropdown') if (!data) $this.data('dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api' , toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown) }(jQuery);
JavaScript
0.000001
@@ -1535,19 +1535,16 @@ bile we -we use a ba
d04ee811d53a29bd8cd22553e33d1ffecd8a9c7b
Format comments for generating docs using dox
selection-counter.js
selection-counter.js
/* global chrome:false, safari:false, $:false, pluralize:false, PeripheryLabel:false, SelectionListener:false */ (function (window, document, undefined) { /* * Watches the current selection and displays a count of a noun in a label. * * If multiple SelectionCounter instances exist, they will be grouped together. * * If instantiated in a browser extension context (e.g., safari, chrome), will * listen for messages: * - Chrome: message.toggle will toggle state, message.active (boolean) will set state * - Safari: event.name === 'toggle' will toggle state, (event.name === 'active' && event.message) will set state * * And may send messages to browser runtime / tab: * - Chrome: sendMessage({ active: false }) when deactivated, sendMessage({ active: true }) when activated * - Safari: dispatchMessage('active', false) when deactivated, dispatchMessage('active', true) when activated * * Parameters: * - countedNoun (string): Thing to be counted. Options: "character", "word". (default: "character") */ function SelectionCounter(countedNoun) { countedNoun = countedNoun || 'character'; this.countedNoun = countedNoun; this.active = false; // Instantiate label and and listeners this.label = new PeripheryLabel(this.countedNoun); this.selectionListener = new SelectionListener(window); var self = this; // Listen for selection changes and show/hide the label based on the number of counted nouns selected $(window).on(SelectionListener.SELECTION_CHANGE_EVENT, function (event) { if (self.active) { var count = event.selection ? event.selection[self.countedNoun + 'Count'] : 0; if (!count) { self.label.hide(); } else { var message = count + ' ' + pluralize(self.countedNoun, count); self.label.show(message); } } }); // Listen for messages from other parts of the extension to start/stop selection listening if (typeof chrome !== 'undefined') { chrome.runtime.onMessage.addListener(function (message) { if (self.active && message.toggle) { self.selectionListener.toggle(); } }); chrome.runtime.onMessage.addListener(function (message) { if (self.active && message.active !== undefined) { if (message.active) { self.selectionListener.start(); } else { self.selectionListener.stop(); } } }); } else if (typeof safari !== 'undefined') { safari.self.addEventListener('message', function (message) { if (message.name === 'toggle') { self.selectionListener.toggle(); } }, false); safari.self.addEventListener('message', function (event) { if (self.active && event.name === 'active') { if (event.message) { self.selectionListener.start(); } else { self.selectionListener.stop(); } } }, false); } // On ESC key down, deactivate the extension $(document).on('keydown', function (event) { if (self.active && event.which === 27) { // ESC key self.selectionListener.stop(); // Send message about deactivation to other parts of extension if (chrome) { chrome.runtime.sendMessage({ active: false }); } else if (safari) { safari.self.tab.dispatchMessage('active', false); } } }); } /* * Start counter */ SelectionCounter.prototype.start = function () { this.active = true; }; /* * Stop counter */ SelectionCounter.prototype.stop = function () { this.label.hide(); this.active = false; }; window.SelectionCounter = SelectionCounter; })(this, document);
JavaScript
0
@@ -152,24 +152,25 @@ ned) %7B%0A%0A /* +* %0A * Watche @@ -435,16 +435,21 @@ ssages:%0A + *%0A * - C @@ -455,16 +455,17 @@ Chrome: +%60 message. @@ -470,16 +470,17 @@ e.toggle +%60 will to @@ -491,16 +491,17 @@ state, +%60 message. @@ -506,16 +506,17 @@ e.active +%60 (boolea @@ -548,16 +548,17 @@ Safari: +%60 event.na @@ -572,16 +572,17 @@ 'toggle' +%60 will to @@ -593,17 +593,17 @@ state, -( +%60 event.na @@ -634,17 +634,17 @@ .message -) +%60 will se @@ -709,16 +709,21 @@ / tab:%0A + *%0A * - C @@ -729,16 +729,17 @@ Chrome: +%60 sendMess @@ -756,24 +756,25 @@ ve: false %7D) +%60 when deacti @@ -780,16 +780,17 @@ ivated, +%60 sendMess @@ -810,16 +810,17 @@ true %7D) +%60 when ac @@ -842,16 +842,17 @@ Safari: +%60 dispatch @@ -875,16 +875,17 @@ , false) +%60 when de @@ -895,16 +895,17 @@ ivated, +%60 dispatch @@ -927,16 +927,17 @@ ', true) +%60 when ac @@ -966,16 +966,21 @@ meters:%0A + *%0A * - c @@ -3511,24 +3511,25 @@ );%0A %7D%0A%0A /* +* %0A * Start @@ -3627,16 +3627,17 @@ %7D;%0A%0A /* +* %0A * St
15ac6d8b4d4ac25bf5c5f7245178a0f6c0fde4ee
Add missing methods to dummy pubsub publisher
app/pubsub.js
app/pubsub.js
import { dbAdapter } from './models' import { serializeUser } from './serializers/v2/user' export class DummyPublisher { userUpdated() {} postCreated() {} postDestroyed() {} postUpdated() {} commentCreated() {} commentDestroyed() {} commentUpdated() {} likeAdded() {} likeRemoved() {} postHidden() {} postUnhidden() {} commentLikeAdded() {} commentLikeRemoved() {} globalUserUpdated() {} } export default class pubSub { constructor(publisher) { this.publisher = publisher } setPublisher(publisher) { this.publisher = publisher; } async updateUnreadDirects(userId) { const unreadDirectsNumber = await dbAdapter.getUnreadDirectsNumber(userId); const user = { id: userId, unreadDirectsNumber }; const payload = JSON.stringify({ user }); await this.publisher.userUpdated(payload); } async updateUnreadNotifications(userIntId) { const [{ uid: userId }] = await dbAdapter.getUsersIdsByIntIds([userIntId]); const unreadNotificationsNumber = await dbAdapter.getUnreadEventsNumber(userId); const user = { id: userId, unreadNotificationsNumber }; const payload = JSON.stringify({ user }); await this.publisher.userUpdated(payload); } async newPost(postId) { const payload = JSON.stringify({ postId }) await this.publisher.postCreated(payload) } async destroyPost(postId, rooms) { const payload = JSON.stringify({ postId, rooms }) await this.publisher.postDestroyed(payload) } async updatePost(postId, rooms = null, usersBeforeIds = null) { const payload = JSON.stringify({ postId, rooms, usersBeforeIds }) await this.publisher.postUpdated(payload) } async newComment(comment) { const payload = JSON.stringify({ commentId: comment.id }) await this.publisher.commentCreated(payload) } async destroyComment(commentId, postId, rooms) { const payload = JSON.stringify({ postId, commentId, rooms }) await this.publisher.commentDestroyed(payload) } async updateComment(commentId) { const payload = JSON.stringify({ commentId }) await this.publisher.commentUpdated(payload) } async newLike(post, userId) { const payload = JSON.stringify({ userId, postId: post.id }) await this.publisher.likeAdded(payload) } async removeLike(postId, userId, rooms) { const payload = JSON.stringify({ userId, postId, rooms }) await this.publisher.likeRemoved(payload) } async hidePost(userId, postId) { await this.publisher.postHidden(JSON.stringify({ userId, postId })) } async unhidePost(userId, postId) { await this.publisher.postUnhidden(JSON.stringify({ userId, postId })) } async savePost(userId, postId) { await this.publisher.postSaved(JSON.stringify({ userId, postId })) } async unsavePost(userId, postId) { await this.publisher.postUnsaved(JSON.stringify({ userId, postId })) } async newCommentLike(commentId, postId, likerUUID) { const payload = JSON.stringify({ commentId, postId, likerUUID }); await this.publisher.commentLikeAdded(payload); } async removeCommentLike(commentId, postId, unlikerUUID) { const payload = JSON.stringify({ commentId, postId, unlikerUUID }); await this.publisher.commentLikeRemoved(payload); } async globalUserUpdate(userId) { const user = await dbAdapter.getUserById(userId); const payload = JSON.stringify(serializeUser(user)); await this.publisher.globalUserUpdated(payload); } }
JavaScript
0.000001
@@ -411,16 +411,52 @@ ed() %7B%7D%0A + postSaved() %7B%7D%0A postUnsaved() %7B%7D%0A %7D%0A%0Aexpor
8d6f042b0e4b422cd03eae99125bd4b2b955cb92
update to allow wrapping templates from real app partial used in build.
cuke-browser-watcher.js
cuke-browser-watcher.js
#!/usr/bin/env node var fs = require('fs'); var path = require('path'); var map = require('map-stream'); var tmpl = require('lodash.template'); var watch = require('node-watch'); var child_process = require('child_process'); var mkdirp = require('mkdirp'); var rimraf = require('rimraf'); var browserify = require('browserify'); var http = require('http'); var tinylr = require('tiny-lr'); var connect = require('connect'); var open = require('open'); var S = require('string'); var tempdir = '.tmp'; var outdir = 'test'; var browserCukes; var livereloadPort = 35729; var connectPort = 8080; var JS_EXT = /^.*\.js/i; var options = ['-f', 'ui', '-o', outdir, '--tmpl', tempdir + '/testrunner.html']; var wrap = function(wrapperTemplate) { return map(function(file, cb) { var content = file.toString(); fs.readFile(path.resolve(wrapperTemplate), 'utf8', function(err, filedata) { cb(null, tmpl(filedata, {yield:content})); }); }); }; // [TASKS] // a. re-bundle the app. var bundleApplication = function(f, callback) { return function() { browserify(__dirname + '/script/app.js') .bundle({ standalone: 'app' }) .pipe(fs.createWriteStream(path.resolve(outdir + '/script/app.js'))) .on('close', function() { console.log('changed app.js...'); if(callback) { callback(); } }); }; }; // b. template testrunner with app partial. var templateTestRunner = function(callback) { fs.createReadStream(__dirname + '/template/app-main.us') .pipe(wrap(__dirname + '/template/testrunner-wrapper.us')) .pipe(fs.createWriteStream(path.resolve(tempdir + '/testrunner.html'))) .on('close', function() { if(callback) { callback(); } }); }; // c. rerun cucumberjs-browser tool. var cuke = function(f, callback) { return function() { var filename = S(path.basename(f, '.js').split('.').join('-')).camelize().s; // templateTestRunner(function() { browserCukes = child_process.spawn('cucumberjs-browser', options) .on('exit', function() { console.log('changed ' + filename + '...'); rimraf(tempdir, function() { if(callback) { callback(); } }); }); // }); }; }; // 1. Recursive mkdir /test/script if not exist. mkdirp.sync(outdir + '/script'); mkdirp.sync(tempdir); // 2. Create tiny-livereload server. var lr = tinylr(); lr.listen(livereloadPort, function() { console.log('livereload listening on ' + livereloadPort + '...'); }); // 3. Start server on localhost. var app = connect().use(connect.static(__dirname + '/test')); var server = http.createServer(app).listen(connectPort, function() { console.log('local server started on ' + connectPort + '...'); console.log('Note: Remember to start the livereload browser extension!'); console.log('http://feedback.livereload.com/knowledgebase/articles/86242-how-do-i-install-and-use-the-browser-extensions-'); cuke('./features/support/world', function() { bundleApplication('./script/app.js', function() { open('http://localhost:' + connectPort + '/cucumber-testrunner.html'); })(); })(); }); // 4. Watch source and generate bundles. watch(['./features', './script'], {recursive:true}, function(filename) { // Used to resolve when running operation(s) are complete. var resolver; var running = false; var resolveWatch = function(limit) { var count = 0; running = true; return function() { if(++count === limit) { count = 0; running = false; } else { running = true; } }; }; if(!running && filename.match(JS_EXT)) { var bundleAppInvoke = bundleApplication(filename, function() { lr.changed({ body: { files: ['script/app'] } }); resolver(); }); if(/^script?/i.test(filename)) { resolver = resolveWatch(1); bundleAppInvoke(); } else if(/^features?/i.test(filename)) { resolver = resolveWatch(2); cuke(filename, function() { lr.changed({ body: { files: [filename] } }); resolver(); bundleAppInvoke(); })(); } } });
JavaScript
0
@@ -934,21 +934,16 @@ ll, -tmpl( filedata , %7By @@ -942,25 +942,44 @@ data -, %7Byield: +.replace(/%5B%5E%5D%3C%25= yield %25%3E/i, content -%7D ));%0A @@ -1976,19 +1976,16 @@ ).s;%0A - // templat @@ -2303,19 +2303,16 @@ %7D);%0A - // %7D);%0A %7D
64b4740e8f35e583170b0e7096ed6a0d1a9d9cde
Remove unused route (#564)
app/router.js
app/router.js
import Ember from 'ember'; import config from './config/environment'; import Location from 'travis/utils/location'; var Router = Ember.Router.extend({ location: function() { if (Ember.testing) { return 'none'; } else { // this is needed, because in the location // we need to decide if repositories or home needs // to be displayed, based on the current login status // // we should probably think about a more general way to // do this, location should not know about auth status return Location.create({ auth: Ember.getOwner(this).lookup('service:auth') }); } }.property(), generate() { var url; url = this.router.generate.apply(this.router, arguments); return this.get('location').formatURL(url); }, handleURL(url) { url = url.replace(/#.*?$/, ''); return this._super(url); }, didTransition() { this._super(...arguments); if (config.gaCode) { _gaq.push(['_trackPageview', location.pathname]); } } }); Router.map(function() { this.route('dashboard', { resetNamespace: true }, function() { this.route('repositories', { path: '/' }); }); this.route('main', { path: '/', resetNamespace: true }, function() { this.route('getting_started', { resetNamespace: true }); this.route('recent'); this.route('repositories'); this.route('my_repositories'); this.route('search', { path: '/search/:phrase' }); this.route('repo', { path: '/:owner/:name', resetNamespace: true }, function() { this.route('index', { path: '/' }); this.route('branches', { path: '/branches', resetNamespace: true }); this.route('build', { path: '/builds/:build_id', resetNamespace: true }); this.route('job', { path: '/jobs/:job_id', resetNamespace: true }); this.route('builds', { path: '/builds', resetNamespace: true }); this.route('pullRequests', { path: '/pull_requests', resetNamespace: true }); this.route('crons', { path: '/crons', resetNamespace: true }); this.route('requests', { path: '/requests', resetNamespace: true }); if (config.endpoints.caches) { this.resource('caches', { path: '/caches' }); } this.route('request', { path: '/requests/:request_id', resetNamespace: true }); this.route('settings', { resetNamespace: true }, function() { this.route('index', { path: '/' }); this.route('env_vars', { resetNamespace: true }, function() { this.route('new'); }); if (config.endpoints.sshKey) { this.resource('ssh_key'); } }); }); }); this.route('first_sync'); this.route('insufficient_oauth_permissions'); this.route('signin'); this.route('auth'); this.route('home'); this.route('home-pro', { path: '/home-pro' }); this.route('plans', { path: '/plans' }); this.route('team', { path: '/about' }); this.route('logo', { path: '/logo' }); this.route('profile', { path: '/profile', resetNamespace: true }, function() { this.route('accounts', { path: '/', resetNamespace: true }, function() { this.route('account', { path: '/:login', resetNamespace: true }); this.route('info', { path: '/info' }); }); }); this.route('owner', { path: '/:owner', resetNamespace: true }, function() { this.route('repositories', { path: '/' }); }); this.route('error404', { path: '/404' }); }); export default Router;
JavaScript
0.000001
@@ -2519,93 +2519,8 @@ %7D);%0A - if (config.endpoints.sshKey) %7B%0A this.resource('ssh_key');%0A %7D%0A
9cafc78f2af175123361480e3dda10abe4470add
Update routes to match common
app/router.js
app/router.js
import { inject as service } from '@ember/service'; import EmberRouter from '@ember/routing/router'; import config from './config/environment'; const Router = EmberRouter.extend({ iliosMetrics: service(), location: config.locationType, rootURL: config.rootURL, didTransition() { this._super(...arguments); const iliosMetrics = this.iliosMetrics; const page = this.url; const title = this.getWithDefault('currentRouteName', 'unknown'); iliosMetrics.track(page, title); }, }); Router.map(function() { this.route('dashboard', { resetNamespace: true }); this.route('courses'); this.route('course', { path: 'courses/:course_id', resetNamespace: true }, function(){ this.route('publicationCheck', { path: '/publicationcheck'}); this.route('publishall', { path: '/publishall'}); this.route('rollover', { path: '/rollover'}); this.route("session", { path: '/sessions/:session_id', resetNamespace: true }, function(){ this.route('publicationCheck', {path: '/publicationcheck'}); this.route('copy'); }); }); this.route('printCourse', { path: 'course/:course_id/print'}); this.route('course-materials', { path: 'courses/:course_id/materials'}); this.route('instructorGroups', { path: 'instructorgroups'}); this.route('instructorGroup', { path: 'instructorgroups/:instructor_group_id'}); this.route("testModels"); this.route('programs'); this.route('learnerGroup', { path: 'learnergroups/:learner_group_id'}); this.route('learnerGroups', { path: 'learnergroups'}); this.route('program', { path: 'programs/:program_id', resetNamespace: true }, function(){ this.route('publicationCheck', { path: '/publicationcheck'}); this.route("programYear", { path: '/programyears/:program-year_id', resetNamespace: true }, function(){ this.route('publicationCheck', {path: '/publicationcheck'}); }); }); this.route('admin-dashboard', { path: '/admin'}); this.route('login'); this.route('events', {path: 'events/:slug'}); this.route('users', {}); this.route('user', {path: '/users/:user_id'}); this.route('fourOhFour', { path: "*path"}); this.route('logout'); this.route('pending-user-updates', {path: '/admin/userupdates'}); this.route('schools'); this.route('school', { path: 'schools/:school_id'}); this.route('assign-students', {path: '/admin/assignstudents'}); this.route('myprofile'); this.route('mymaterials'); this.route('course-rollover'); this.route('curriculumInventoryReports', { path: 'curriculum-inventory-reports' }); this.route('curriculumInventoryReport', { path: 'curriculum-inventory-reports/:curriculum_inventory_report_id' }, function() { this.route('rollover', { path: '/rollover'}); }); this.route('curriculumInventorySequenceBlock', { path: 'curriculum-inventory-sequence-block/:curriculum_inventory_sequence_block_id' }); this.route('course-visualizations', { path: 'data/courses/:course_id' }); this.route('course-visualize-objectives', { path: 'data/courses/:course_id/objectives' }); this.route('course-visualize-session-types', { path: 'data/courses/:course_id/session-types' }); this.route('course-visualize-vocabularies', { path: 'data/courses/:course_id/vocabularies' }); this.route('course-visualize-vocabulary', { path: 'data/courses/:course_id/vocabularies/:vocabulary_id' }); this.route('course-visualize-term', { path: 'data/courses/:course_id/terms/:term_id' }); this.route('course-visualize-session-type', { path: 'data/courses/:course_id/session-types/:session-type_id' }); this.route('course-visualize-instructors', { path: 'data/courses/:course_id/instructors' }); this.route('course-visualize-instructor', { path: 'data/courses/:course_id/instructors/:user_id' }); this.route('session-type-visualize-vocabularies', { path: 'data/sessiontype/:session_type_id/vocabularies' }); this.route('session-type-visualize-terms', { path: 'data/sessiontype/:session_type_id/vocabularies/:vocabulary_id' }); this.route('weeklyevents'); this.route('program-year-visualizations', { path: 'data/programyears/:program_year_id' }); this.route('program-year-visualize-competencies', { path: 'data/programyears/:program_year_id/competencies' }); }); export default Router;
JavaScript
0
@@ -730,33 +730,34 @@ ute('publication -C +_c heck', %7B path: ' @@ -1014,33 +1014,34 @@ ute('publication -C +_c heck', %7Bpath: '/ @@ -1120,17 +1120,18 @@ e('print -C +_c ourse',
73d7187728e0bf4d91c6cb4ddde7c5c1bef546c9
debug live
app/routes.js
app/routes.js
/** * the-wall-of-quotes-api * * @license * Copyright (c) 2016 by andreasonny83. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at * https://raw.githubusercontent.com/Azurasky1/DragonArena/develop/LICENSE */ 'use strict'; const router = require('express').Router(); const pkginfo = require('pkginfo')(module); const firebase = require('firebase-admin'); const appName = module.exports.name; const appVersion = module.exports.version; let serviceAccount; let db; let ref; // serviceAccount stores the firebase serviceAccount configuration try { serviceAccount = require('../serviceAccount.json'); } catch (e) {} _init(); // Routing logic router .get('/status', status) .post('/add', add); function _init() { const databaseURL = process.env.DATABASE_URL || serviceAccount.DATABASE_URL || 'DATABASE_URL'; firebase.initializeApp({ credential: firebase.credential.cert({ projectId: process.env.PROJECT_ID || serviceAccount.PROJECT_ID || 'PROJECT_ID', clientEmail: process.env.CLIENT_EMAIL || serviceAccount.CLIENT_EMAIL || 'CLIENT_EMAIL', privateKey: process.env.PRIVATE_KEY || serviceAccount.PRIVATE_KEY || 'PRIVATE_KEY' }), databaseURL: databaseURL, databaseAuthVariableOverride: { uid: "my-service-worker" } }); db = firebase.database(); ref = db.ref('/quotes'); } // Private functions function status(req, res) { const data = { app: appName, version: appVersion, status: 200, message: 'OK - ' + Math.random().toString(36).substr(3, 8) }; res.status(200).send(data); } function add(req, res) { let captcha = req.body.captcha || null; let model = { quote: req.body.quote || null, author: req.body.author || null, creator: req.body.creator || null }; if (!model.quote || !model.author || !model.creator || !captcha) { return res.status(400).send(); } ref.push(model); res.status(200).send(); } module.exports = router;
JavaScript
0.000001
@@ -1407,16 +1407,195 @@ uotes'); +%0A%0A console.log('start debug');%0A console.log(databaseURL);%0A console.log(process.env.PROJECT_ID);%0A console.log(process.env.CLIENT_EMAIL);%0A console.log(process.env.PRIVATE_KEY); %0A%7D%0A%0A// P @@ -2017,16 +2017,63 @@ l%0A %7D;%0A%0A + console.log(captcha);%0A console.log(model);%0A%0A if (!m
1faedc397c3799a13b1fdf50973621336ccd3729
return promise to wait for finish and capture errors
test/configCases/output/charset/index.js
test/configCases/output/charset/index.js
__webpack_public_path__ = "https://example.com/public/path/"; const doImport = () => import(/* webpackChunkName: "chunk1" */ "./chunk1"); it("should not add charset attribute", () => { const promise = doImport(); expect(document.head._children).toHaveLength(1); const script = document.head._children[0]; __non_webpack_require__("./chunk1.js"); script.onload(); expect(script._type).toBe("script"); expect(script.src).toBe("https://example.com/public/path/chunk1.js"); expect(script.getAttribute("charset")).toBeUndefined(); });
JavaScript
0
@@ -529,12 +529,29 @@ ined();%0A +%09return promise;%0A %7D);%0A
eef45518f3b99c34e50f8e1b0294745b11a10bab
Document Geographic Details add-on now uses custom Extras client-side namespace
web/extras/components/document-details/document-geographic-info.js
web/extras/components/document-details/document-geographic-info.js
/** * Document geographic info component. * * @namespace Alfresco * @class Alfresco.DocumentGeographicInfo */ (function() { /** * YUI Library aliases */ var Dom = YAHOO.util.Dom; /** * Alfresco Slingshot aliases */ var $html = Alfresco.util.encodeHTML; /** * DocumentGeographicInfo constructor. * * @param {String} htmlId The HTML id of the parent element * @return {Alfresco.DocumentGeographicInfo} The new DocumentGeographicInfo instance * @constructor */ Alfresco.DocumentGeographicInfo = function(htmlId) { Alfresco.DocumentGeographicInfo.superclass.constructor.call(this, "Alfresco.DocumentGeographicInfo", htmlId); /* Decoupled event listeners */ YAHOO.Bubbling.on("documentDetailsAvailable", this.onDocumentDetailsAvailable, this); return this; }; YAHOO.extend(Alfresco.DocumentGeographicInfo, Alfresco.component.Base, { /** * GMap object */ map: null, /** * GMap marker */ marker: null, /** * Map container div */ mapContainer: null, /** * Event handler called when the "documentDetailsAvailable" event is received * * @method: onDocumentDetailsAvailable */ onDocumentDetailsAvailable: function DocumentGeographicInfo_onDocumentDetailsAvailable(layer, args) { var docData = args[1].documentDetails; this.mapContainer = Dom.get(this.id + "-map"); if (typeof(docData.geolocation) === "object" && typeof(docData.geolocation.latitude) !== "undefined") { Dom.removeClass(this.id + "-body", "hidden"); if (this.map == null) { this.initializeMap(docData); } else { this.updateMap(docData); } } else { Dom.addClass(this.id + "-body", "hidden"); } }, /** * Initialise the map itself * @method initializeMap */ initializeMap: function SiteGeotaggedContent_initializeMap(doc) { var latLng = new google.maps.LatLng(doc.geolocation.latitude, doc.geolocation.longitude); var myOptions = { zoom: 10, center: latLng, mapTypeId: google.maps.MapTypeId.ROADMAP } this.map = new google.maps.Map(this.mapContainer, myOptions); this.marker = new google.maps.Marker( { position: latLng, map: this.map, title: doc.fileName }); }, /** * Update the map view * @method updateMap */ updateMap: function SiteGeotaggedContent_updateMap(doc) { // First clear any existing marker if (this.marker != null) { this.marker.setMap(null); this.marker = null; } // Then re-center the map var latLng = new google.maps.LatLng(doc.geolocation.latitude, doc.geolocation.longitude); this.map.panTo(latLng); // Then add the new marker to the map this.marker = new google.maps.Marker( { position: latLng, map: this.map, title: doc.fileName }); } }); })();
JavaScript
0
@@ -1,12 +1,200 @@ +/**%0A * Copyright (C) 2010-2011 Share Extras contributors.%0A */%0A%0A/**%0A* Extras root namespace.%0A* %0A* @namespace Extras%0A*/%0Aif (typeof Extras == %22undefined%22 %7C%7C !Extras)%0A%7B%0A var Extras = %7B%7D;%0A%7D%0A%0A /**%0A * Docum @@ -242,24 +242,22 @@ mespace -Alfresco +Extras %0A * @cla @@ -259,24 +259,22 @@ @class -Alfresco +Extras .Documen @@ -606,24 +606,22 @@ return %7B -Alfresco +Extras .Documen @@ -706,24 +706,22 @@ */%0A -Alfresco +Extras .Documen @@ -766,24 +766,22 @@ %7B%0A -Alfresco +Extras .Documen @@ -831,24 +831,22 @@ (this, %22 -Alfresco +Extras .Documen @@ -1061,24 +1061,22 @@ .extend( -Alfresco +Extras .Documen
24a06b49c213765d5cb02226dee9328c7cf67e64
Add some line-to handling to geometry file
js/geometry.js
js/geometry.js
Class.makeClass(null, function Point(x, y) { this.x = x || 0; this.y = y || 0; }) Point.prototype.normalize = function() { var length = this.length(); return new Point(this.x/length, this.y/length); } Point.prototype.length = function() { return Math.sqrt(this.lenSqrd()); } Point.prototype.lenSqrd = function() { return (this.x * this.x) + (this.y * this.y); } Point.prototype.distTo = function(other) { return this.minus(other).length(); } // useful for inverse square law stuff, and such Point.prototype.sqrDistTo = function(other) { return this.minus(other).lenSqrd(); } Point.prototype.isZero = function() { return !(this.x || this.y); } Point.prototype.times = function(mult) { return new Point(this.x * mult, this.y * mult); } Point.prototype.toRect = function(width, height, centered) { var left = this.x; var top = this.y; if (centered) { left -= width / 2.0; top -= height / 2.0; } return new Rectangle(left, top, width, height); } Point.prototype.offsetBy = function(other) { this.x += other.x; this.y += other.y; return this; } Point.prototype.plus = function(other) { return this.clone().offsetBy(other); } Point.prototype.minus = function(other) { return this.clone().offsetBy(other.times(-1)); } Point.prototype.clone = function() { return new Point(this.x, this.y); } Class.makeClass(null, function Rectangle(left, top, width, height) { this.left = left; this.top = top; this.width = width; this.height = height; Object.defineProperty(this, 'right', { get: function() { return this.left + this.width; } }); Object.defineProperty(this, 'bottom', { get: function() { return this.top + this.height; } }); }); Rectangle.prototype.intersects = function(other) { return ( this.left < other.right && this.right > other.left && this.top < other.bottom && this.bottom > other.top ); } Rectangle.prototype.clone = function() { return new Rectangle(this.left, this.top, this.width, this.height); }
JavaScript
0.000001
@@ -741,24 +741,145 @@ * mult);%0A%7D%0A%0A +Point.prototype.projectTo = function(other, length) %7B%0A%09return other.minus(this).normalize().times(length).plus(this);%0A%7D%0A%0A Point.protot @@ -1084,16 +1084,145 @@ ht);%0A%7D%0A%0A +// for passing as an array into things like Context2D methods%0APoint.prototype.unpack = function() %7B%0A%09return %5Bthis.x, this.y%5D;%0A%7D%0A%0A %0APoint.p
70ec70ea0d16b32248f2897f770089f3107a11b4
implement changes to reflect changed server events
frontend/js/reducers.js
frontend/js/reducers.js
import _ from 'lodash' import { combineReducers } from 'redux' const initialMixerState = { channels : {}, master : {}, host : {}, sound : false } function channelState(channels, chan, state) { return { ...channels, [chan]: Object.assign({}, channels[chan], state) } } function shouldPlaySound(channels) { for (let key in channels) { if ('ring' === channels[key].mode) { return true } } return false } function mixer(state = initialMixerState, action) { switch (action.type) { case 'initialize-mixer': { const sound = shouldPlaySound(action.state.channels) return { ...action.state, sound } } case 'update-mixer': { const channels = Object.assign({}, state.channels, action.state) const sound = shouldPlaySound(channels) return { ...state, sound, channels } } case 'mute': case 'unmute': return { ...state, channels : channelState(state.channels, action.channel, { muted : 'mute' === action.type }) } case 'update-caller': return { ...state, channels : { ...state.channels, [action.channel] : { ...state.channels[action.channel], contact : Object.assign({}, state.channels[action.channel].contact, action.caller) } } } case 'update-level': return { ...state, channels : channelState(state.channels, action.channel, { level : action.level }) } case 'update-master': return { ...state, master : action.state } case 'update-master-level': return { ...state, master : { ...state.master, level : action.level } } default: return state } } function users(state = {}, action) { switch (action.type) { case 'initialize-users': return action.state case 'update-user': return { ...state, [action.userId] : action.state } case 'update-user-level': return { ...state, [action.userId] : Object.assign({}, state[action.userId], { level : action.level }) } default: return state } } function client(state = {}, action) { switch (action.type) { case 'set-diff': return { ...state, diff : action.diff } case 'update-preset': switch (action.preset) { case 'host': case 'master': case 'on_hold': case 'ivr': return { ...state, channels : { ...state.channels, [action.channel]: { preset : action.preset } } } default: return state } default: return state } } const initialInboxState = { notifications: [] } function inbox(state = initialInboxState, action) { switch (action.type) { case 'update-inbox': const message = { ...action.payload, id: action.id } return { ...state, notifications: [message, ...state.notifications] } case 'remove-message': return { ...state, notifications: state.notifications.filter(item => item.id != action.id) } default: return state } } const reducers = { mixer, users, client, inbox } export default combineReducers(reducers)
JavaScript
0
@@ -6,65 +6,228 @@ t _ -from 'lodash'%0A%0Aimport %7B combineReducers %7D %0A from 'redux' + from 'lodash'%0Aimport getQueryVariable from './url-params'%0A%0Aimport %7B combineReducers %7D %0A from 'redux'%0A%0Aconst userId = getQueryVariable('user_id') %0Aconst isHost = 'true' == getQueryVariable('host') %0A%0Aco @@ -317,24 +317,45 @@ d : false +,%0A active : false, %0A%7D%0A%0Afunction @@ -556,16 +556,33 @@ if ( +channels%5Bkey%5D && 'ring' = @@ -721,32 +721,145 @@ (action.type) %7B%0A + case 'update-mixer-active': %7B%0A return %7B%0A ...state,%0A active : action.active,%0A %7D%0A %7D%0A case 'initia @@ -977,16 +977,104 @@ e, sound +,%0A active : true,%0A channels : _.pick(action.state.channels, _.identity), %0A %7D @@ -1265,25 +1265,64 @@ sound, -channels +%0A channels : _.pick(channels, _.identity) %0A %7D @@ -2397,16 +2397,18 @@ -users': + %7B %0A r @@ -2413,28 +2413,168 @@ return -action.state +%7B%0A _userId : userId,%0A _connected : action.state.hasOwnProperty(userId) && !!action.state%5BuserId%5D,%0A ...action.state%0A %7D%0A %7D %0A cas @@ -2585,24 +2585,26 @@ pdate-user': + %7B %0A retur @@ -2655,35 +2655,359 @@ %5D : action.state +, %0A + _userId : userId,%0A _connected : state.hasOwnProperty(userId) %7C%7C action.userId == userId,%0A %7D%0A %7D%0A case 'remove-user': %7B%0A let users = _.omit(state, action.userId)%0A users._userId = userId%0A users._connected = users.hasOwnProperty(userId) && !!users%5BuserId%5D%0A return users%0A %7D%0A case ' @@ -3017,32 +3017,33 @@ ate-user-level': + %0A return %7B%0A @@ -3254,32 +3254,96 @@ (action.type) %7B%0A + case 'initialize-mixer': %0A return %7B isHost, ...state %7D%0A case 'set-di
218969787c359c827e87aed39ecd00fa9241a68e
fix test
test/externalTests/exampleBlockFinder.js
test/externalTests/exampleBlockFinder.js
const assert = require('assert') module.exports = () => (bot, done) => { bot.test.runExample('examples/blockfinder.js', (name, cb) => { assert.strictEqual(name, 'finder') const finderTest = [ cb => { bot.test.tellAndListen(name, 'find dirt', (message) => { const matches = /I found ([0-9]+) (.+?) blocks in (.+?) ms/.match(message) if (matches.length !== 4 || matches[1] === '0' || matches[2] !== 'dirt' || parseFloat(matches[3]) > 500) { assert.fail(`Unexpected message: ${message}`) // error } return true // stop listening }, cb) } ] setTimeout(() => { bot.test.callbackChain(finderTest, cb) }, 2000) }, done) }
JavaScript
0.000002
@@ -301,16 +301,30 @@ tches = +message.match( /I found @@ -362,22 +362,8 @@ ms/ -.match(message )%0A
6cd9396c2ea71a507f4fac5dc949e521926fd1fe
update baseUrl
frontend/nuxt.config.js
frontend/nuxt.config.js
module.exports = { env: { baseUrl: process.env.NODE_ENV !== 'production' ? 'http://test.com' : 'https://chulung.com' }, /* ** Headers of the page */ head: { titleTemplate: '%s - 初龙的博客', meta: [ {charset: 'utf-8'}, {name: 'viewport', content: 'width=device-width, initial-scale=1'}, {hid: 'description', name: 'description', content: '初龙的博客'} ], link: [ {rel: 'icon', type: 'image/x-icon', href: '/img/favicon.ico'} ] }, /* ** Customize the progress-bar color */ loading: {color: '#3B8070'}, /* ** Build configuration */ build: { /* ** Run ESLINT on save */ extend (config, ctx) { if (ctx.isClient) { config.module.rules.push({ enforce: 'pre', test: /\.(js|vue)$/, loader: 'eslint-loader', exclude: /(node_modules)/ }) } }, vendor: ['axios'] }, plugins: [ '~plugins/vee-validate'] }
JavaScript
0.000219
@@ -59,23 +59,24 @@ ENV -! += == ' -production +development ' ?
4e7c6d62c332bb14606c1a7d9029de13d7ad861b
Remove comments
app/routes.js
app/routes.js
// app/routes.js module.exports = function(app, passport) { app.get('/', function(req, res) { res.render('index.ejs'); // load the index.ejs file }); // show the login form app.get('/login', function(req, res) { // render the page and pass in any flash data if it exists res.render('login.ejs', { message: req.flash('loginMessage') }); }); // process the login form // app.post('/login', do all our passport stuff here); // show the signup form app.get('/signup', function(req, res) { // render the page and pass in any flash data if it exists res.render('signup.ejs', { message: req.flash('signupMessage') }); }); // process the signup form // app.post('/signup', do all our passport stuff here); // we will want this protected so you have to be logged in to visit // we will use route middleware to verify this (the isLoggedIn function) app.get('/profile', isLoggedIn, function(req, res) { res.render('profile.ejs', { user : req.user // get the user out of session and pass to template }); }); app.get('/logout', function(req, res) { req.logout(); res.redirect('/'); }); }; // route middleware to make sure a user is logged in function isLoggedIn(req, res, next) { // if user is authenticated in the session, carry on if (req.isAuthenticated()) return next(); // if they aren't redirect them to the home page res.redirect('/'); }
JavaScript
0
@@ -1,21 +1,4 @@ -// app/routes.js%0A modu
643b15f8430e95bad556ff150f64e717afd8ad92
Fix send to tab in controls from error view (#298)
components/general-controls.js
components/general-controls.js
const React = require('react'); const cn = require('classnames'); const sendToAddon = require('../client-lib/send-to-addon'); const sendMetricsEvent = require('../client-lib/send-metrics-event'); module.exports = React.createClass({ getView: function() { return this.props.loaded ? 'player_view' : 'loading_view'; }, close: function() { sendMetricsEvent(this.getView(), 'close'); sendToAddon({action: 'close'}); }, minimize: function() { sendMetricsEvent(this.getView(), 'minimize'); sendToAddon({action: 'minimize'}); window.AppData.minimized = true; }, maximize: function() { sendMetricsEvent(this.getView(), 'maximize'); sendToAddon({action: 'maximize'}); window.AppData.minimized = false; }, sendToTab: function() { sendMetricsEvent(this.getView(), 'send_to_tab'); let currentTime = 0; if (this.getView() === 'player_view') { currentTime = this.props.getTime(); } sendToAddon({ action: 'send-to-tab', id: this.props.id, domain: this.props.domain, time: currentTime }); }, render: function() { return ( <div className='right'> <a onClick={this.sendToTab} data-tip='Send to tab' className='tab' /> <a className={cn('minimize', {hidden: this.props.minimized})} onClick={this.minimize} data-tip='Minimize' /> <a onClick={this.maximize} data-tip='Maximize' className={cn('maximize', {hidden: !this.props.minimized})} /> <a className='close' onClick={this.close} data-tip='Close' /> </div> ); } });
JavaScript
0
@@ -243,32 +243,79 @@ w: function() %7B%0A + if (this.props.error) return 'error_view';%0A return this.
c7a0f20ab84b49cc517e946c0bef1b950547a4cc
Fix plane UVs
shapes/plane.js
shapes/plane.js
import { Entity } from '../core'; import { Render } from '../components'; import { Transform } from '../components'; const vertices = [ -1, 0, 1, 1, 0, 1, 1, 0, -1, -1, 0, -1 ]; const indices = [ 0, 1, 3, 3, 1, 2 ]; const normals = [ 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0 ]; const uvs = [ 0, 0, 1, 0, 0, 1, 1, 1 ]; export class Plane extends Entity { constructor(options = {}) { options.components = [ new Transform(), new Render({ vertices, indices, normals, uvs, material: options.material }) ]; super(options); } }
JavaScript
0
@@ -327,14 +327,14 @@ 0, -0 +1 ,%0A -1 +0 , 0,
b270d6f43d73613466e32a1dddbdc10d57633911
Fix issue #24
components/keybindings/init.js
components/keybindings/init.js
/* * Copyright (c) Codiad & Kent Safranski (codiad.com), distributed * as-is and without warranty under the MIT License. See * [root]/license.txt for more. This information must remain intact. */ ////////////////////////////////////////////////////////////////////// // CTRL Key Bind ////////////////////////////////////////////////////////////////////// $.ctrl = function(key, callback, args) { var isCtrl = false; $(document).keydown(function(e) { if(!args) args=[]; if(e.ctrlKey) isCtrl = true; if(e.keyCode == key && isCtrl) { callback.apply(this, args); isCtrl = false; return false; } }).keyup(function(e) { if(e.ctrlKey) isCtrl = false; }); }; $(function(){ keybindings.init(); }); ////////////////////////////////////////////////////////////////////// // Bindings ////////////////////////////////////////////////////////////////////// var keybindings = { init : function(){ // Close Modals ////////////////////////////////////////////// $(document).keyup(function(e){ if(e.keyCode == 27){ modal.unload(); } }); // Save [CTRL+S] ///////////////////////////////////////////// $.ctrl('83', function(){ active.save(); }); // Open in browser [CTRL+O] ////////////////////////////////// $.ctrl('79', function(){ active.open_in_browser(); }); // Find [CTRL+F] ///////////////////////////////////////////// $.ctrl('70', function(){ editor.open_search('find'); }); // Replace [CTRL+R] ////////////////////////////////////////// $.ctrl('82', function(){ editor.open_search('replace'); }); // Active List Up //////////////////////////////////////////// $.ctrl('38', function(){ active.move('up'); }); // Active List Down ////////////////////////////////////////// $.ctrl('40', function(){ active.move('down'); }); } };
JavaScript
0
@@ -497,34 +497,25 @@ i -f(e.ctrlKey) isCtrl = true +sCtrl = e.ctrlKey ;%0A
bf8e7f60aadb768c8cae9fcd83580258abfad035
update star variables
App_Files/Engine/SkyBox/Stars/Stars.js
App_Files/Engine/SkyBox/Stars/Stars.js
module.exports = function(){ var _azimuth = 0.5, _sunPosition = new THREE.Vector3(), _Shader = null, _geo = new THREE.SphereBufferGeometry( 450000, 32, 15), _skyMesh = {}, _logged = false, _starMesh = new THREE.Mesh( new THREE.SphereBufferGeometry( 0, 0, 0 ), new THREE.MeshBasicMaterial( { color: 0xffffff } ) ); function Stars(){ if(!_Shader){ _Shader = Engine.CreateShader(); } _Shader.fragment().clearInjects(); _Shader.fragment().injectVars([ "float Noise2d( in vec2 x )", "{", "float xhash = cos( x.x * 37.0 );", "float yhash = cos( x.y * 57.0 );", "return fract( 415.92653 * ( xhash + yhash ) );", "}", "float NoisyStarField( in vec2 vSamplePos, float fThreshhold )", "{", "float StarVal = Noise2d( vSamplePos );", "if ( StarVal >= fThreshhold )", "StarVal = pow( (StarVal - fThreshhold)/(1.0 - fThreshhold), 6.0 );", "else", "StarVal = 0.0;", "return StarVal;", "}", "float StableStarField( in vec2 vSamplePos, float fThreshhold )", "{", "float fractX = fract( vSamplePos.x );", "float fractY = fract( vSamplePos.y );", "vec2 floorSample = floor( vSamplePos );", "float v1 = NoisyStarField( floorSample, fThreshhold );", "float v2 = NoisyStarField( floorSample + vec2( 0.0, 1.0 ), fThreshhold );", "float v3 = NoisyStarField( floorSample + vec2( 1.0, 0.0 ), fThreshhold );", "float v4 = NoisyStarField( floorSample + vec2( 1.0, 1.0 ), fThreshhold );", "float StarVal = v1 * ( 1.0 - fractX ) * ( 1.0 - fractY )", "+ v2 * ( 1.0 - fractX ) * fractY", "+ v3 * fractX * ( 1.0 - fractY )", "+ v4 * fractX * fractY;", "return StarVal;", "}" ]); _Shader.fragment().injectRules([ "// Sky Background Color", "vec3 vColor = vec3( 0.0, 0.0, 0.1) * fragCoord.y / iResolution.y;", "// Note: Choose fThreshhold in the range [0.99, 0.9999].", "// Higher values (i.e., closer to one) yield a sparser starfield.", "float StarFieldThreshhold = 0.99;", "// Stars with a slow crawl.", "float xRate = 0.01;", "float yRate = 0.0;", "vec2 vSamplePos = fragCoord.xy + vec2( xRate * float( iFrame ), yRate * float( iFrame ) );", "float StarVal = StableStarField( vSamplePos, StarFieldThreshhold );", "vColor += vec3( StarVal );", "fragColor = vec4(vColor, 1.0);", ]); _Shader.Uniform('skyPosition',_starMesh.position); _starMesh.visible = false; _Shader.side(THREE.BackSide).call(); Stars.updateTime(_azimuth); _skyMesh = new THREE.Mesh(_geo,_Shader.shader()); } Sun.updateTime = function(v){ _azimuth = v; var theta = Math.PI * ( 1.0 - 0.5 ); var phi = 2 * Math.PI * ( _azimuth - 0.5 ); _starMesh.position.x = 400000 * Math.cos( phi ); _starMesh.position.y = 400000 * Math.sin( phi ) * Math.sin( theta ); _starMesh.position.z = 400000 * Math.sin( phi ) * Math.cos( theta ); //console.log("phi ",phi,Math.sin(phi),"theta ",theta,Math.sin(theta),_starMesh.position.x,_starMesh.position.y,_starMesh.position.z); _Shader.loadedUniforms().skyPosition.value.copy(_starMesh.position); _Shader.Uniform('skyPosition',_starMesh.position); } }
JavaScript
0.000001
@@ -2192,24 +2192,183 @@ jectRules(%5B%0A +%0A %22uniform float iGlobalTime;%22,%0A %22uniform vec2 iResolution;%22,%0A%0A %22varying vec2 fragCoord;%22,%0A%0A %22varying vec2 vUv;%22,%0A%0A
9aca25d1cdd4ace251519d88c9fbe7fc32681fe5
Improve the validation mechanism
app/server.js
app/server.js
"use strict"; var http = require('http'); var url = require('url'); var request = require('request'); var querystring = require('querystring'); var podXML = require('./podcast-xml.js'); var config; try { config = JSON.parse(require('fs').readFileSync(__dirname + "/config.json")) } catch (e) { throw e; } var server = http.createServer(function(req, res) { var REQURL = url.parse(req.url); if (REQURL.pathname == "/podcast" && querystring.parse(url.parse(req.url).query).url) { var SCURL = querystring.parse(url.parse(req.url).query).url; podXML.getXML(config.soundcloud_key, SCURL, function(XML) { res.write(XML); res.end(); console.log("Returned XML for " + SCURL); }); } else if (REQURL.pathname.indexOf("/track") != -1) { var trackId = url.parse(req.url).path.split("/").pop().split(".").shift(); var UA = req.headers["user-agent"]; var regex = "Mozilla|HTML|Gecko|Firefox"; var proxyOut = res; if (!(new RegExp(regex).test(UA))) { console.log(UA); request('http://api.soundcloud.com/tracks/' + trackId + '.json?client_id=' + config.soundcloud_key, function(err, res, body) { if (!err && res.statusCode == 200) { var json = JSON.parse(body); if (!json.downloadable || UA.indexOf('iTunes/') === -1) { request("http://api.soundcloud.com/tracks/" + trackId + "/stream?client_id=" + config.soundcloud_key).pipe(proxyOut); console.log("http://api.soundcloud.com/tracks/" + trackId + "/stream?client_id=" + config.soundcloud_key); } else if (json.downloadable) { request("http://api.soundcloud.com/tracks/" + trackId + "/download?client_id=" + config.soundcloud_key).pipe(proxyOut); console.log("http://api.soundcloud.com/tracks/" + trackId + "/download?client_id=" + config.soundcloud_key); } } else if (err) { throw err; res.end(); } }); } else { res.writeHead(403); res.write("iTunes and likes are the only ones authorized!"); res.end(); } } else if (REQURL.pathname == "/validate" && querystring.parse(url.parse(req.url).query).url) { var SCURL = querystring.parse(url.parse(req.url).query).url; request('http://api.soundcloud.com/resolve.json?url=' + SCURL + '&client_id=' + config.soundcloud_key, function(error, response, body) { if (!error && response.statusCode == 200) { var resJson = JSON.parse(body); res.writeHead({"Content-Type": "application/json"}); if (resJson.kind === "playlist" || resJson.kind === "user") { res.write(JSON.stringify({valid: true})); res.end(); } else { res.write(JSON.stringify({valid: false})); res.end(); } } }); } else { res.write(""); res.end(); } }).listen(config.port); console.log("Listening on port " + config.port);
JavaScript
0.000076
@@ -2606,24 +2606,98 @@ nd();%0A%09%09%09%09%7D%0A +%09%09%09%7D else %7B%0A%09%09%09%09res.write(JSON.stringify(%7Bvalid: false%7D));%0A%09%09%09%09res.end();%0A %09%09%09%7D%0A%09%09%7D);%0A%09
f76836c296b39736798f502a155493353737ea55
Save multiple occasions of player property in a CONST
app/server.js
app/server.js
const http = require('http'); const path = require('path'); const express = require('express'); const WebSocket = require('ws'); const bodyParser = require('body-parser'); const Twitter = require('twitter'); require('dotenv').config(); const port = process.env.PORT || 3000; const client = new Twitter({ consumer_key: process.env.TWITTER_CONSUMER_KEY, consumer_secret: process.env.TWITTER_CONSUMER_SECRET, access_token_key: process.env.TWITTER_CONSUMER_ACCESS_TOKEN_KEY, access_token_secret: process.env.TWITTER_CONSUMER_ACCESS_TOKEN_SECRET }); const game = { players: {}, maxScore: 10, playing: false }; // Colors are in g, r, b const colors = [ [75, 0, 50], // Blue [25, 150, 0], // Red [100, 200, 0], // Orange [150, 125, 0], // Yellow [0, 150, 175], // Purple [175, 0, 25] // Green ]; const app = express() .use(bodyParser.urlencoded({ extended: false })) .use(express.static(path.join(__dirname, 'public'))) .set('view engine', 'ejs') .set('views', path.join(__dirname, 'views')) .get('/', getApp) .get('/controller', getController) .post('/controller', postController); const server = http.createServer(app); const wss = new WebSocket.Server({ server }); wss.broadcast = broadcast; wss.on('connection', onSocketConnection); server.listen(port, onListen); function getApp(req, res) { res.render('index', { maxScore: game.maxScore, players: game.players, playing: game.playing, message: '' }); } function getController(req, res) { res.render('controller', { player: false }); } function postController(req, res) { let color; if (!game.playing) { if (game.players[req.body.name]) { color = game.players[req.body.name].color; } else { color = colors[Object.keys(game.players).length % colors.length]; game.players[req.body.name] = { id: req.body.name, type: 'phone', color, score: 0 }; } wss.broadcast( JSON.stringify({ device: 'phone', action: 'NEW_PLAYER', player: game.players[req.body.name] }) ); res.render('controller', { player: game.players[req.body.name], name: req.body.name }); } else { res.render('index', { maxScore: game.maxScore, players: game.players, playing: game.playing, message: 'Game already started, you are now spectating' }); } } function onListen() { console.log('Server started at port ' + port); } function broadcast(data) { wss.clients.forEach(sendData); function sendData(client) { if (client.readyState === WebSocket.OPEN) { client.send(data); } } } function onSocketConnection(socket) { socket.on('message', onSocketMessage); function onSocketMessage(message) { try { message = JSON.parse(message); } catch (err) { console.log('Message not in JSON:', message); } switch (message.device) { case 'nodemcu': return nodemcuMessage(socket, message); case 'phone': return phoneMessage(socket, message); case 'scoreboard': return scoreboardMessage(socket, message); default: console.log('Device not recognized: ', message.device); } } } function nodemcuMessage(socket, message) { switch (message.action) { case 'JOIN_GAME': console.log(message); if (!game.playing) { let color; if (game.players[message.id]) { color = game.players[message.id].color; } else { color = colors[Object.keys(game.players).length % colors.length]; game.players[message.id] = { id: message.id, type: 'nodemcu', color, score: 0 }; console.log(game.players) wss.broadcast( JSON.stringify({ action: 'NEW_PLAYER', player: game.players[message.id] }) ); } return socket.send( JSON.stringify({ action: 'CHANGE_COLOR', color }) ); } else { return socket.send( JSON.stringify({ action: 'SPECTATE' }) ); } case 'UPDATE_SCORE': if (game.playing) { console.log(message); game.players[message.id].score = game.players[message.id].score + 1; wss.broadcast( JSON.stringify({ action: 'UPDATE_SCORE', id: message.id }) ); if (game.players[message.id].score === game.maxScore) { wss.broadcast( JSON.stringify({ action: 'END_GAME', winner: game.players[message.id] }) ); } } break; default: return false; } } function phoneMessage(socket, message) { switch (message.action) { case 'UPDATE_SCORE': if (game.started) { const player = game.players[message.id]; console.log(message); player.score = player.score + 1; wss.broadcast( JSON.stringify({ action: 'UPDATE_SCORE', id: message.id }) ); if (player.score === game.maxScore) { wss.broadcast( JSON.stringify({ action: 'END_GAME', winner: player }) ) } } break; default: return false; } } function scoreboardMessage(socket, message) { switch (message.action) { case 'SET_MAX_SCORE': console.log(message); game.maxScore = message.maxScore; wss.broadcast(JSON.stringify({ action: 'SET_MAX_SCORE', maxScore: game.maxScore })); break; case 'MOVE_MOUSE': wss.broadcast(JSON.stringify(message)); break; case 'START_GAME': if (Object.keys(game.players).length > 1) { console.log(message); game.playing = true; wss.broadcast( JSON.stringify({ action: 'START_GAME', maxScore: game.maxScore, players: game.players }) ); } break; default: return false; } } function tweet(message) { client.post('statuses/update', {status: message}, function(error, tweet, response) { if(error) console.log(message); }); }
JavaScript
0
@@ -4252,32 +4252,81 @@ game.playing) %7B%0A + const player = game.players%5Bmessage.id%5D;%0A console. @@ -4352,32 +4352,14 @@ -game. player -s%5Bmessage.id%5D .sco @@ -4367,32 +4367,14 @@ e = -game. player -s%5Bmessage.id%5D .sco @@ -4536,32 +4536,14 @@ if ( -game. player -s%5Bmessage.id%5D .sco @@ -4680,32 +4680,14 @@ er: -game. player -s%5Bmessage.id%5D %0A
09bc819cde03814ef622fbbb9be104c51e24f6b8
fix permissions actions
jsapp/js/actions/permissions.es6
jsapp/js/actions/permissions.es6
/** * permissions related actions */ import Reflux from 'reflux'; import {dataInterface} from 'js/dataInterface'; import { t, notify } from 'js/utils'; const permissionsActions = Reflux.createActions({ getConfig: {children: ['completed', 'failed']}, getAssetPermissions: {children: ['completed', 'failed']}, getCollectionPermissions: {children: ['completed', 'failed']}, bulkSetAssetPermissions: {children: ['completed', 'failed']}, assignCollectionPermission: {children: ['completed', 'failed']}, assignAssetPermission: {children: ['completed', 'failed']}, removeAssetPermission: {children: ['completed', 'failed']}, removePerm: {children: ['completed', 'failed']}, copyPermissionsFrom: {children: ['completed', 'failed']}, assignPublicPerm: {children: ['completed', 'failed']}, setCollectionDiscoverability: {children: ['completed', 'failed']} }); /** * New actions */ permissionsActions.getConfig.listen(() => { dataInterface.getPermissionsConfig() .done(permissionsActions.getConfig.completed) .fail(permissionsActions.getConfig.failed); }); permissionsActions.getAssetPermissions.listen((assetUid) => { dataInterface.getAssetPermissions(assetUid) .done(permissionsActions.getAssetPermissions.completed) .fail(permissionsActions.getAssetPermissions.failed); }); permissionsActions.getCollectionPermissions.listen((uid) => { dataInterface.getCollectionPermissions(uid) .done(permissionsActions.getCollectionPermissions.completed) .fail(permissionsActions.getCollectionPermissions.failed); }); /** * For bulk setting permissions - wipes all current permissions, sets given ones * * @param {string} assetUid * @param {Object[]} perms - permissions to set */ permissionsActions.bulkSetAssetPermissions.listen((assetUid, perm) => { dataInterface.bulkSetAssetPermissions(assetUid, perm) .done(() => { permissionsActions.getAssetPermissions(assetUid); permissionsActions.bulkSetAssetPermissions.completed(); }) .fail(() => { permissionsActions.getAssetPermissions(assetUid); permissionsActions.bulkSetAssetPermissions.failed(); }); }); /** * For adding single collection permission * * @param {string} uid - collection uid * @param {Object} perm - permission to add */ permissionsActions.assignCollectionPermission.listen((uid, perm) => { dataInterface.assignCollectionPermission(uid, perm) .done(() => { permissionsActions.getCollectionPermissions(uid); permissionsActions.assignCollectionPermission.completed(); }) .fail(() => { permissionsActions.getCollectionPermissions(uid); permissionsActions.assignCollectionPermission.failed(); }); }); /** * For adding single asset permission * * @param {string} assetUid * @param {Object} perm - permission to add */ permissionsActions.assignAssetPermission.listen((assetUid, perm) => { dataInterface.assignAssetPermission(assetUid, perm) .done(() => { permissionsActions.getAssetPermissions(assetUid); permissionsActions.assignAssetPermission.completed(); }) .fail(() => { permissionsActions.getAssetPermissions(assetUid); permissionsActions.assignAssetPermission.failed(); }); }); /** * For removing single permission * * @param {string} assetUid * @param {string} perm - permission url */ permissionsActions.removeAssetPermission.listen((assetUid, perm) => { dataInterface.removeAssetPermission(perm) .done(() => { permissionsActions.getAssetPermissions(assetUid); permissionsActions.removeAssetPermission.completed(); }) .fail(() => { notify(t('failed to remove permission'), 'error'); permissionsActions.getAssetPermissions(assetUid); permissionsActions.removeAssetPermission.failed(); }); }); /** Old actions */ // copies permissions from one asset to other permissionsActions.copyPermissionsFrom.listen(function(sourceUid, targetUid) { dataInterface.copyPermissionsFrom(sourceUid, targetUid) .done(() => { permissionsActions.getAssetPermissions(targetUid); permissionsActions.copyPermissionsFrom.completed(sourceUid, targetUid); }) .fail(permissionsActions.copyPermissionsFrom.failed); }); permissionsActions.removePerm.listen(function(details){ if (!details.content_object_uid) { throw new Error('removePerm needs a content_object_uid parameter to be set'); } dataInterface.removePerm(details.permission_url) .done(function(resp){ permissionsActions.removePerm.completed(details.content_object_uid, resp); }) .fail(function(resp) { permissionsActions.removePerm.failed(details.content_object_uid, resp); notify(t('Failed to remove permissions'), 'error'); }); }); permissionsActions.setCollectionDiscoverability.listen(function(uid, discoverable){ dataInterface.patchCollection(uid, {discoverable_when_public: discoverable}) .done(permissionsActions.setCollectionDiscoverability.completed) .fail(permissionsActions.setCollectionDiscoverability.failed); }); export default permissionsActions;
JavaScript
0.000001
@@ -62,16 +62,111 @@ eflux';%0A +import RefluxPromise from 'js/libs/reflux-promise';%0AReflux.use(RefluxPromise(window.Promise));%0A import %7B
25c456c0c29934d6678681f8afb763e681fec349
set proper content-type and charset on /auth/calback response
app/server.js
app/server.js
import dotenv from 'dotenv'; import express from 'express'; import compression from 'compression'; import session from 'express-session'; import passport from 'passport'; import { Strategy } from 'passport-github'; import sessionFileStore from 'session-file-store'; import sapper from 'sapper'; import serve from 'serve-static'; import devalue from 'devalue'; import { Store } from 'svelte/store.js'; import { routes } from './manifest/server.js'; dotenv.config(); const FileStore = sessionFileStore(session); passport.use(new Strategy({ clientID: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET, callbackURL: `${process.env.BASEURL}/auth/callback`, userAgent: 'svelte.technology' }, (accessToken, refreshToken, profile, callback) => { return callback(null, { token: accessToken, id: profile.id, username: profile.username, displayName: profile.displayName, photo: profile.photos && profile.photos[0] && profile.photos[0].value }); })); passport.serializeUser((user, cb) => { cb(null, user); }); passport.deserializeUser((obj, cb) => { cb(null, obj); }); express() .use(compression({ threshold: 0 })) .use(session({ secret: 'svelte', resave: true, saveUninitialized: true, cookie: { maxAge: 31536000 }, store: new FileStore({ path: process.env.NOW ? `/tmp/sessions` : `.sessions` }) })) .use(passport.initialize()) .use(passport.session()) .get('/auth/login', (req, res, next) => { const { returnTo } = req.query; req.session.returnTo = returnTo ? decodeURIComponent(returnTo) : '/'; next(); }, passport.authenticate('github', { scope: ['gist', 'read:user'] })) .post('/auth/logout', (req, res) => { req.logout(); res.end('ok'); }) .get('/auth/callback', passport.authenticate('github', { failureRedirect: '/auth/error' }), (req, res) => { const { id, username, displayName, photo } = req.session.passport && req.session.passport.user; res.end(` <script> window.opener.postMessage({ user: ${devalue({ id, username, displayName, photo })} }, window.location.origin); </script> `); }) .use( compression({ threshold: 0 }), serve('assets'), sapper({ routes, store: req => { const user = req.session.passport && req.session.passport.user; return new Store({ user: user && { // strip access token id: user.id, username: user.username, displayName: user.displayName, photo: user.photo }, guide_contents: [] }); } }) ) .listen(process.env.PORT);
JavaScript
0
@@ -1930,16 +1930,75 @@ .user;%0A%0A +%09%09res.set(%7B 'Content-Type': 'text/html; charset=utf-8' %7D);%0A %09%09res.en
42b61fddb0f5a7cf6441a7aba5c214709811e1a5
fix bem impot
jsapp/js/router/accessDenied.es6
jsapp/js/router/accessDenied.es6
import React from 'react'; import {bem, makeBem} from 'js/bem'; import {redirectToLogin} from 'js/router/routerUtils'; import {stores} from 'js/stores'; import envStore from 'js/envStore'; import './accessDenied.scss'; bem.AccessDenied = makeBem(null, 'access-denied'); bem.AccessDenied__body = makeBem(bem.AccessDenied, 'body', 'section'); bem.AccessDenied__header = makeBem(bem.AccessDenied, 'header', 'header'); bem.AccessDenied__text = makeBem(bem.AccessDenied, 'text', 'section'); /** * @prop {string} [errorMessage] */ export default class AccessDenied extends React.Component { constructor(props) { super(props); } goToLogin(evt) { evt.preventDefault(); redirectToLogin(); } render() { return ( <bem.AccessDenied> <bem.AccessDenied__body> <bem.AccessDenied__header> <i className='k-icon k-icon-lock-alt'/> {t('Access denied')} </bem.AccessDenied__header> <bem.AccessDenied__text> {t("Either you don't have access to this page or this page simply doesn't exist.")} <br/> {stores.session.isLoggedIn ? t('Please ') : t('Please try logging in using the header button or ') } {envStore.data.support_url ? <a href={envStore.data.support_url} target='_blank'>{t('contact the support team')}</a> : t('contact the support team') } {t(" if you think it's an error.")} </bem.AccessDenied__text> {this.props.errorMessage && <bem.AccessDenied__text> {t('Additional details:')} <code>{this.props.errorMessage}</code> </bem.AccessDenied__text> } </bem.AccessDenied__body> </bem.AccessDenied> ); } }
JavaScript
0.000003
@@ -31,14 +31,14 @@ ort -%7B bem, +%7B make
f7a486095a84f5b8278e9f92033c721fa43f96ea
remove exclude of foundation.css from wiredep for other than sass
app/src/ui.js
app/src/ui.js
'use strict'; module.exports = function(GulpAngularGenerator) { /** * Change the ui framework module name for bootstrap * The Bower package to use is different if sass or another css preprocessor */ GulpAngularGenerator.prototype.handleBootstrapVersion = function handleBootstrapVersion() { if(this.props.ui.key.indexOf('bootstrap') !== -1 && this.props.cssPreprocessor.extension !== 'scss') { this.props.ui.name = 'bootstrap'; } }; /** * There is 2 ways of dealing with vendor styles * - If the vendor styles exist in the css preprocessor chosen, * the best is to include directly the source files * - If not, the vendor styles are simply added as standard css links * * isVendorStylesPreprocessed defines which solution has to be used * regarding the ui framework and the css preprocessor chosen */ GulpAngularGenerator.prototype.vendorStyles = function vendorStyles() { this.isVendorStylesPreprocessed = false; if(this.props.cssPreprocessor.extension === 'scss') { if(this.props.ui.key === 'bootstrap' || this.props.ui.key === 'foundation') { this.isVendorStylesPreprocessed = true; } } else if(this.props.cssPreprocessor.extension === 'less') { if(this.props.ui.key === 'bootstrap') { this.isVendorStylesPreprocessed = true; } } }; /** * Add files of the navbar and the main view depending on the ui framework * and the css preprocessor */ GulpAngularGenerator.prototype.uiFiles = function uiFiles() { this.files.push({ src: 'src/app/components/navbar/__' + this.props.ui.key + '-navbar.html', dest: 'src/app/components/navbar/navbar.html', template: false }); if(this.props.router.module !== null) { this.files.push({ src: 'src/app/main/__' + this.props.ui.key + '.html', dest: 'src/app/main/main.html', template: false }); } this.files.push({ src: 'src/app/_' + this.props.ui.key + '/__' + this.props.ui.key + '-index.' + this.props.cssPreprocessor.extension, dest: 'src/app/index.' + this.props.cssPreprocessor.extension, template: false }); if(this.props.cssPreprocessor.key !== 'none') { this.files.push({ src: 'src/app/_' + this.props.ui.key + '/__' + this.props.ui.key + '-vendor.' + this.props.cssPreprocessor.extension, dest: 'src/app/vendor.' + this.props.cssPreprocessor.extension, template: true }); } }; /** * Compute wiredep exclusions depending on the props */ GulpAngularGenerator.prototype.computeWiredepExclusions = function computeWiredepExclusions() { this.wiredepExclusions = []; if (this.props.jQuery.key === 'none') { this.wiredepExclusions.push('/jquery/'); } if (this.props.ui.key === 'bootstrap') { if(this.props.bootstrapComponents.key !== 'official') { if(this.props.cssPreprocessor.extension === 'scss') { this.wiredepExclusions.push('/bootstrap-sass-official\\/.*\\.js/'); } else { this.wiredepExclusions.push('/bootstrap\\.js/'); } } if(this.props.cssPreprocessor.key !== 'none') { this.wiredepExclusions.push('/bootstrap\\.css/'); } } else if (this.props.ui.key === 'foundation') { if(this.props.foundationComponents.key !== 'official') { this.wiredepExclusions.push('/foundation\\.js/'); } if(this.props.cssPreprocessor.key !== 'none') { this.wiredepExclusions.push('/foundation\\.css/'); } } }; };
JavaScript
0
@@ -3465,37 +3465,43 @@ reprocessor. -key !== 'none +extension === 'scss ') %7B%0A
911866e811b6c2098cb1a5df477b4e81767cb795
fix right-arrow keyboard shortcut
_js/main.js
_js/main.js
(function () { 'use strict'; var num = getNum() || -1; function getNum () { var num = window.location.pathname.replace(/[^\d]/g, ''); try { num = parseInt(num, 10); } catch (e) { return; } return num; } function setNum (increment) { var num = getNum(); num += increment || 0; return num; } var prev; var next; window.addEventListener('DOMContentLoaded', function () { prev = document.head.querySelector('link[rel~="prev"]'); next = document.head.querySelector('link[rel~="next"]'); }); function go (increment) { if (typeof increment === 'number') { if (prev && increment === -1) { window.location.href = prev.getAttribute('href'); return; } if (next && increment === 1) { window.location.href = next.getAttribute('href'); return; } } if (typeof increment === 'string') { if (increment === 'prev') { window.location.href = prev.getAttribute('href'); return; } if (increment === 'next') { window.location.href = next.getAttribute('href'); return; } } num = setNum(increment); window.location.href = './' + num + '.html'; } var sceneReady = new Promise(function (resolve, reject) { var scene = document.querySelector('a-scene'); if (scene) { resolve(scene); return; } if (!scene) { document.addEventListener('readystatechange', sceneFound); setTimeout(function () { sceneFound(true); }, 5000); } function sceneFound (didTimeout) { scene = document.querySelector('a-scene'); if (didTimeout || scene) { document.removeEventListener('readystatechange', sceneFound); if (scene.hasLoaded) { resolve(scene); } else { scene.addEventListener('loaded', function () { resolve(scene); }); } } } }); var sounds; var supports = {}; supports.iOS = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform); supports.cardboard = supports.iOS || (!('vrDisplays' in navigator) && !('vr' in navigator) && navigator.platform.indexOf('Android') > -1); // if (supports.cardboard) { // window.addEventListener('click', function (evt) { // var scene = document.querySelector('a-scene'); // if (!scene || !scene.is || !scene.is('vr-mode')) { // return; // } // evt.preventDefault(); // go(1); // }); // } sceneReady.then(function (scene) { console.log('got scene', scene); sounds = new Sounds({ scene: scene }); }); function toArray (obj) { return Array.prototype.slice.apply(obj); } function $ (selector, parent) { parent = parent || document; return parent.querySelector(selector); } function $$ (selector, parent) { parent = parent || document; return toArray(parent.querySelectorAll(selector)); } function Sounds (opts) { opts = opts || {}; opts.muted = 'muted' in opts ? opts.muted : false; opts.scene = opts.scene || $('a-scene'); var self = this; self.muted = false; self.scene = self.scene; self.toggle = function () { if (self.muted) { self.play(); } else { self.stop(); } }; self.playEl = function (el) { el.components.sound.sound.preload = el.components.sound.sound._preload; el.components.sound.sound.autoplay = el.components.sound.sound._autoplay; el.components.sound.sound.src = el.components.sound.sound._src; el.components.sound.sound.muted = el.components.sound.sound._muted; el.components.sound.play(); }; self.stopEl = function (el) { el.components.sound.pause(); el.components.sound.sound._preload = el.components.sound.sound._preload; el.components.sound.sound._autoplay = el.components.sound.sound._autoplay; el.components.sound.sound._muted = el.components.sound.sound._muted; el.components.sound.sound._src = el.components.sound.sound.src; el.components.sound.sound.preload = false; el.components.sound.sound.autoplay = false; el.components.sound.sound.muted = true; el.components.sound.sound.src = ''; }; self.play = function () { self.muted = false; self.remember(); $$('[sound]', self.scene).forEach(self.playEl); $$('audio').forEach(function (el) { el.setAttribute('data-original-muted', el.getAttribute('muted')); el.muted = false; }); }; self.stop = function () { self.muted = true; self.remember(); $$('[sound]', self.scene).forEach(self.stopEl); $$('audio').forEach(function (el) { el.muted = true; el.setAttribute('muted', el.getAttribute('data-original-muted')); }); }; self.remember = function () { try { window.localStorage.audioMuted = self.muted ? 'true' : 'false'; } catch (e) { } }; self.muteOnLoad = function () { try { return window.localStorage.audioMuted === 'true'; } catch (e) { return null; } }; if (self.muteOnLoad()) { self.stop(); } } var keys = { 'ArrowLeft': 37, 'ArrowRight': 37, 's': 83 }; window.addEventListener('keydown', function (evt) { if (evt.target !== document.body) { return; } if (evt.keyCode === keys.ArrowLeft) { evt.preventDefault(); go(-1); } else if (evt.keyCode === keys.ArrowRight) { evt.preventDefault(); go(1); } else if (evt.keyCode === keys.s) { evt.preventDefault(); sounds.toggle(); } }); if ('ontouchstart' in window) { window.addEventListener('dblclick', function () { sounds.toggle(); }); } function playVideoOnClick (selector) { var el = document.querySelector(selector); if (el) { addListener(); } else { window.addEventListener('load', addListener); } function addListener () { el = document.querySelector(selector); if (!el) { return; } if (el.paused) { window.addEventListener('click', handleFirstClick); } function handleFirstClick () { try { if (el.muted) { delete el.muted; } if (el.paused) { el.play(); } } catch (e) { } removeHandleFirstClick(); } function removeHandleFirstClick () { window.removeEventListener('click', handleFirstClick); } } } playVideoOnClick('video'); playVideoOnClick('audio'); })();
JavaScript
0.000185
@@ -5294,25 +5294,25 @@ rowRight': 3 -7 +9 ,%0A 's': 8
90c60c37c927df97be86616e72c31118098c7ab4
change require test
test/parseObjectTest.js
test/parseObjectTest.js
"use strict"; var assert = require('chai').assert; var should = require('chai').should; var querystring = require("querystring"); var parser = require("../dist/parseobject"); var object = {}; var partialObject = {}; var incorrectObject = {}; var postObject = {}; var putObject = {}; var delObject = {}; describe('ParseObject function', function () { before(function () { object = { url: "http://example.com/", type: "raw", headers: { 'User-Agent': 'testAgent' } }; partialObject = { url: "http://example.com/" }; incorrectObject = { url: "test", type: "raw" }; postObject = { url: "http://example.com/", type: "raw", data: { test: "test2" }, method: "POST" }; delObject = { url: "http://example.com/", type: "raw", data: { test: "test2" }, method: "DELETE" }; putObject = { url: "http://example.com/", type: "raw", data: { test: "test2" }, method: "PUT" }; }); it("should not pass if not an url", function () { assert.throws(function() { parser("test") }, Error, /Object/); }); it("should return a correct object", function () { var parsedObject = parser(object); assert.equal(parsedObject.type, object.type); assert.equal(parsedObject.request.headers['User-Agent'], object.headers['User-Agent']); assert.equal(object.url.includes(parsedObject.request.hostname), true); }); it("should return a correct object for POST request", function () { var parsedObject = parser(postObject); assert.equal(parsedObject.request.method, postObject.method); assert.equal(parsedObject.request.headers['Content-Type'], "application/x-www-form-urlencoded"); assert.equal(parsedObject.request.headers['Content-Length'], querystring.stringify(postObject.data).length); }); it("should return a correct object for PUT request", function () { var parsedObject = parser(putObject); assert.equal(parsedObject.request.method, putObject.method); assert.equal(parsedObject.request.headers['Content-Type'], "application/x-www-form-urlencoded"); assert.equal(parsedObject.request.headers['Content-Length'], querystring.stringify(putObject.data).length); }); it("should return a correct object for DELETE request", function () { var parsedObject = parser(delObject); assert.equal(parsedObject.request.method, delObject.method); }); it("should pass even if only url is correct", function () { var parsedObject = parser(partialObject); assert.equal(parsedObject.type, "raw"); assert.equal(parsedObject.request.headers['User-Agent'], "LittleRequester"); assert.equal(parsedObject.request.href, partialObject.url); }); it("should not pass if incorrect object", function () { assert.throws(function() { parser(incorrectObject) }, Error, /url/); }); });
JavaScript
0.000002
@@ -159,17 +159,17 @@ st/parse -o +O bject%22);
1b251d689b8862b63fd1e3aa33c0a3dac7c59363
Add test cases for `else if`
test/rules/space-in-control-statement.js
test/rules/space-in-control-statement.js
import { RuleTester } from 'eslint' import rule from '../../lib/rules/space-in-control-statement' import test from 'ava' const expectedError = ( loc, type ) => ({ message: `There must be a space ${loc} this paren.`, type: `${type}Statement`, }) new RuleTester().run('space-in-control-statement', rule, { valid: [ { code: ` if ( 1 + 1 === 2 && true ) { // Do something... } ` }, { code: ` for ( var i = 0; i < 10; i++ ) { // Do something... } ` }, { code: ` while ( true ) { // Do something... } ` }, { code: ` do { // Do something... } while ( true ) ` }, ], invalid: [ { code: ` if (true ) { // Do something... } `, errors: [ expectedError('after', 'If') ] }, { code: ` if ( true) { // Do something... } `, errors: [ expectedError('before', 'If') ] }, { code: ` if (true) { // Do something... } `, errors: [ expectedError('after', 'If'), expectedError('before', 'If') ] }, { code: ` for (var i = 0; i < 1; i++ ) { // Do something... } `, errors: [ expectedError('after', 'For') ] }, { code: ` for ( var i = 0; i < 1; i++) { // Do something... } `, errors: [ expectedError('before', 'For') ] }, { code: ` for (var i = 0; i < 1; i++) { // Do something... } `, errors: [ expectedError('after', 'For'), expectedError('before', 'For') ] }, { code: ` while (true ) { // Do something... } `, errors: [ expectedError('after', 'While') ] }, { code: ` while ( true) { // Do something... } `, errors: [ expectedError('before', 'While') ] }, { code: ` while (true) { // Do something... } `, errors: [ expectedError('after', 'While'), expectedError('before', 'While') ] }, { code: ` do { // Do something... } while (true ) `, errors: [ expectedError('after', 'DoWhile') ] }, { code: ` do { // Do something... } while ( true) `, errors: [ expectedError('before', 'DoWhile') ] }, { code: ` do { // Do something... } while (true) `, errors: [ expectedError('after', 'DoWhile'), expectedError('before', 'DoWhile') ] }, ] }) test(async t => t.pass())
JavaScript
0.000002
@@ -1359,32 +1359,1321 @@ code:%0A %60%0A + if (true) %7B%0A // Do something...%0A %7D%0A %60,%0A errors: %5B%0A expectedError('after', 'If'),%0A expectedError('before', 'If')%0A %5D%0A %7D,%0A %7B%0A code:%0A %60%0A if (true ) %7B%0A // Do something...%0A %7D else if (true ) %7B%0A // Do something else...%0A %7D%0A %60,%0A errors: %5B%0A expectedError('after', 'If'),%0A expectedError('after', 'If')%0A %5D%0A %7D,%0A %7B%0A code:%0A %60%0A if ( true) %7B%0A // Do something...%0A %7D else if ( true) %7B%0A // Do something else...%0A %7D%0A %60,%0A errors: %5B%0A expectedError('before', 'If'),%0A expectedError('before', 'If')%0A %5D%0A %7D,%0A %7B%0A code:%0A %60%0A if (true) %7B%0A // Do something...%0A %7D else if (true) %7B%0A // Do something else...%0A %7D%0A %60,%0A errors: %5B%0A expectedError('after', 'If'),%0A expectedError('before', 'If'),%0A expectedError('after', 'If'),%0A expectedError('before', 'If')%0A %5D%0A %7D,%0A %7B%0A code:%0A %60%0A if (true) %7B%0A // Do something...%0A %7D%0A %60,%0A errors: %5B%0A expectedError('after', 'If'),%0A expectedError('before', 'If')%0A %5D%0A %7D,%0A %7B%0A code:%0A %60%0A for (var
0ad93f5dec4bdfbfd15be7c6af0248ac084d9363
change dbURI on 'dronecafe'
app_api/db.js
app_api/db.js
let mongoose = require('mongoose'); let shutdownMongoose; let dbURI = 'mongodb://localhost/DroneCafe'; if (process.env.NODE_ENV === 'production') { dbURI = process.env.MONGOLAB_URI; } mongoose.connect(dbURI); // события соединения mongoose.connection.on('connected', function() { console.log('Mongoose connected to ' + dbURI); }); mongoose.connection.on('error', function(err) { console.log('Mongoose connection error: ' + err); }); mongoose.connection.on('disconnected', function() { console.log('Mongoose disconnected'); }); // закрытие соединения с MongoDB shutdownMongoose = function(msg, callback) { mongoose.connection.close(function() { console.log('Mongoose disconnected through ' + msg); callback(); }); }; // для перезапуска nodemon process.once('SIGUSR2', function() { shutdownMongoose('nodemon restart', function() { process.kill(process.pid, 'SIGUSR2'); }); }); // для завершения приложения process.on('SIGINT', function() { shutdownMongoose('app termination', function() { process.exit(0); }); }); // для завершения приложения Heroku process.on('SIGTERM', function() { shutdownMongoose('Heroku app termination', function() { process.exit(0); }); }); // схемы и модели require('./models');
JavaScript
0
@@ -88,14 +88,14 @@ ost/ -D +d rone -C +c afe'
2c0ac6830c794d9923f9558d3a1c732fecae1d51
Remove useless trace
server/lib/mailer.js
server/lib/mailer.js
// // Copyright 2009-2015 Ilkka Oksanen <iao@iki.fi> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an "AS // IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language // governing permissions and limitations under the License. // 'use strict'; const fs = require('fs'); const path = require('path'); const nodemailer = require('nodemailer'); const mailgun = require('nodemailer-mailgun-transport'); const htmlToText = require('nodemailer-html-to-text').htmlToText; const smtpTransport = require('nodemailer-smtp-transport'); const handlebars = require('handlebars'); const conf = require('../lib/conf'); const log = require('../lib/log'); const templateCache = {}; let transporter; let fromAddress; let senderAddress; setupTransporter(); exports.send = function send(templateName, data, address, subject) { const templatePath = path.join(__dirname, '..', templateName); let template = templateCache[templatePath]; if (!template) { template = handlebars.compile(fs.readFileSync(templatePath, 'utf8')); templateCache[templatePath] = template; } log.info(`Sending email to: ${address}`); transporter.sendMail({ from: `MAS admin <${fromAddress}>`, sender: senderAddress, to: address, subject, html: template(data) }, (error, info) => { if (error) { log.warn(`Failed to send email: ${error}`); } else { log.info(`Email sent: ${info.response}`); } }); }; function setupTransporter() { if (conf.get('mailgun:enabled')) { const mailgunAuth = { auth: { api_key: conf.get('mailgun:api_key'), // eslint-disable-line camelcase domain: conf.get('mailgun:domain') } }; transporter = nodemailer.createTransport(mailgun(mailgunAuth)); fromAddress = conf.get('mailgun:from'); senderAddress = conf.get('mailgun:sender'); } else if (conf.get('smtp:enabled')) { const smtpOptions = { host: conf.get('smtp:server'), port: conf.get('smtp:port') }; if (conf.get('smtp:user').length !== 0) { smtpOptions.auth = { user: conf.get('smtp:user'), pass: conf.get('smtp:password') }; } transporter = nodemailer.createTransport(smtpTransport(smtpOptions)); fromAddress = conf.get('site:admin_email'); senderAddress = fromAddress; } else { transporter = nodemailer.createTransport(); fromAddress = conf.get('site:admin_email'); senderAddress = fromAddress; } transporter.use('compile', htmlToText()); }
JavaScript
0.000017
@@ -1801,79 +1801,8 @@ %60);%0A - %7D else %7B%0A log.info(%60Email sent: $%7Binfo.response%7D%60);%0A
7c6919234f521bc019d3df4e69e92771935f5dfe
add test for #613
test/unit/authMatchPolicyResourceTest.js
test/unit/authMatchPolicyResourceTest.js
/* global describe context it */ const chai = require('chai'); const dirtyChai = require('dirty-chai'); const authMatchPolicyResource = require('../../src/authMatchPolicyResource'); const expect = chai.expect; chai.use(dirtyChai); describe('authMatchPolicyResource', () => { context('when resource has no wildcards', () => { const resource = 'arn:aws:execute-api:eu-west-1:random-account-id:random-api-id/development/GET/dinosaurs'; context('and the resource matches', () => { it('returns true', () => { expect( authMatchPolicyResource(resource, resource) ).to.eq(true); }); }); context('when the resource has one wildcard to match everything', () => { const wildcardResource = 'arn:aws:execute-api:eu-west-1:random-account-id:random-api-id/*'; it('returns true', () => { expect( authMatchPolicyResource(wildcardResource, resource) ).to.eq(true); }); }); context('when the resource has wildcards', () => { const wildcardResource = 'arn:aws:execute-api:eu-west-1:random-account-id:random-api-id/development/GET/*'; context('and it matches', () => { it('returns true', () => { expect( authMatchPolicyResource(wildcardResource, resource) ).to.eq(true); }); }); context('and it does not match', () => { it('returns false', () => { const resource = 'arn:aws:execute-api:eu-west-1:random-account-id:random-api-id/development/PUT/dinosaurs'; expect( authMatchPolicyResource(wildcardResource, resource) ).to.eq(false); }); }); context('and the resource contains colons', () => { it('returns true', () => { const resource = 'arn:aws:execute-api:eu-west-1:random-account-id:random-api-id/development/GET/dinosaurs:extinct'; expect( authMatchPolicyResource(wildcardResource, resource) ).to.eq(true); }); }); //test for #560 context('when the resource has wildcards and colons', () => { const wildcardResource = 'arn:aws:execute-api:eu-west-1:random-account-id:random-api-id/development/GET/*/stats'; context('and it matches', () => { it('returns true', () => { const resource = 'arn:aws:execute-api:eu-west-1:random-account-id:random-api-id/development/GET/dinosaurs:extinct/stats'; expect( authMatchPolicyResource(wildcardResource, resource) ).to.eq(true); }); }); context('and it does not match', () => { it('returns false', () => { const resource = 'arn:aws:execute-api:eu-west-1:random-account-id:random-api-id/development/GET/dinosaurs/all-stats'; expect( authMatchPolicyResource(wildcardResource, resource) ).to.eq(false); }); }); }); context('when the resource has multiple wildcards', () => { const wildcardResource = 'arn:aws:execute-api:eu-west-1:random-account-id:random-api-id/development/*/*/stats'; context('and it matches', () => { it('returns true', () => { const resource = 'arn:aws:execute-api:eu-west-1:random-account-id:random-api-id/development/GET/dinosaurs/stats'; expect( authMatchPolicyResource(wildcardResource, resource) ).to.eq(true); }); }); context('and it does not match', () => { it('returns false', () => { const resource = 'arn:aws:execute-api:eu-west-1:random-account-id:random-api-id/development/PUT/dinosaurs/xx'; expect( authMatchPolicyResource(wildcardResource, resource) ).to.eq(false); }); }); context('and the wildcard is between two fragments', () => { const wildcardResource = 'arn:aws:execute-api:eu-west-1:random-account-id:random-api-id/development/*/dinosaurs/*'; context('and it matches', () => { it('returns true', () => { const resource = 'arn:aws:execute-api:eu-west-1:random-account-id:random-api-id/development/GET/dinosaurs/stats'; expect( authMatchPolicyResource(wildcardResource, resource) ).to.eq(true); }); }); context('and it does not match', () => { it('returns false', () => { const resource = 'arn:aws:execute-api:eu-west-1:random-account-id:random-api-id/development/GET/cats/stats'; expect( authMatchPolicyResource(wildcardResource, resource) ).to.eq(false); }); }); }); }); }); }); });
JavaScript
0
@@ -4776,16 +4776,870 @@ %7D);%0A + context('when the resource has single character wildcards', () =%3E %7B%0A const wildcardResource = 'arn:aws:execute-api:eu-west-1:random-account-id:random-api-id/development/GET/d?nosaurs';%0A context('and it matches', () =%3E %7B%0A const resource = 'arn:aws:execute-api:eu-west-1:random-account-id:random-api-id/development/GET/dinosaurs';%0A it('returns true', () =%3E %7B%0A expect(%0A authMatchPolicyResource(wildcardResource, resource)%0A ).to.eq(true);%0A %7D);%0A %7D);%0A context('and it does not match', () =%3E %7B%0A it('returns false', () =%3E %7B%0A const resource = 'arn:aws:execute-api:eu-west-1:random-account-id:random-api-id/development/GET/diinosaurs';%0A expect(%0A authMatchPolicyResource(wildcardResource, resource)%0A ).to.eq(false);%0A %7D);%0A %7D);%0A %7D);%0A %7D);%0A%7D)
0ec9491d217d858d23980be056374e336b3bc40c
Fix test: Add stub for profiling
test/unit/cartodb/lzmaMiddleware.test.js
test/unit/cartodb/lzmaMiddleware.test.js
var assert = require('assert'); var testHelper = require('../../support/test_helper'); var lzmaMiddleware = require('../../../lib/cartodb/middleware/lzma'); describe('lzma-middleware', function() { it('it should extend params with decoded lzma', function(done) { var qo = { config: { version: '1.3.0' } }; testHelper.lzma_compress_to_base64(JSON.stringify(qo), 1, function(err, data) { const lzma = lzmaMiddleware(); var req = { headers: { host:'localhost' }, query: { api_key: 'test', lzma: data } }; lzma(req, {}, function(err) { if ( err ) { return done(err); } var query = req.query; assert.deepEqual(qo.config, query.config); assert.equal('test', query.api_key); done(); }); }); }); });
JavaScript
0.000003
@@ -693,16 +693,104 @@ a: data%0A + %7D,%0A profiler: %7B%0A done: function () %7B%7D%0A
fa8478e91cdb4cc3e78646528a519fc06e4aa35d
Exit though process exit handler
bin/jade.js
bin/jade.js
#!/usr/bin/env node /** * Module dependencies. */ var fs = require('fs') , program = require('commander') , path = require('path') , basename = path.basename , dirname = path.dirname , resolve = path.resolve , exists = fs.existsSync || path.existsSync , join = path.join , mkdirp = require('mkdirp') , jade = require('../'); // jade options var options = {}; // options program .version(require('../package.json').version) .usage('[options] [dir|file ...]') .option('-O, --obj <str>', 'javascript options object') .option('-o, --out <dir>', 'output the compiled html to <dir>') .option('-p, --path <path>', 'filename used to resolve includes') .option('-P, --pretty', 'compile pretty html output') .option('-c, --client', 'compile function for client-side runtime.js') .option('-n, --name <str>', 'The name of the compiled template (requires --client)') .option('-D, --no-debug', 'compile without debugging (smaller functions)') .option('-w, --watch', 'watch files for changes and automatically re-render') .option('-E, --extension <extension>', 'specify the output file extension') .option('--name-after-file', 'Name the template after the last section of the file path (requires --client and overriden by --name)') .option('--doctype <str>', 'Specify the doctype on the command line (useful if it is not specified by the template)') program.on('--help', function(){ console.log(' Examples:'); console.log(''); console.log(' # translate jade the templates dir'); console.log(' $ jade templates'); console.log(''); console.log(' # create {foo,bar}.html'); console.log(' $ jade {foo,bar}.jade'); console.log(''); console.log(' # jade over stdio'); console.log(' $ jade < my.jade > my.html'); console.log(''); console.log(' # jade over stdio'); console.log(' $ echo \'h1 Jade!\' | jade'); console.log(''); console.log(' # foo, bar dirs rendering to /tmp'); console.log(' $ jade foo bar --out /tmp '); console.log(''); }); program.parse(process.argv); // options given, parse them if (program.obj) { if (exists(program.obj)) { options = JSON.parse(fs.readFileSync(program.obj)); } else { options = eval('(' + program.obj + ')'); } } // --filename if (program.path) options.filename = program.path; // --no-debug options.compileDebug = program.debug; // --client options.client = program.client; // --pretty options.pretty = program.pretty; // --watch options.watch = program.watch; // --name if (typeof program.name === 'string') { options.name = program.name; } // --doctype options.doctype = program.doctype; // left-over args are file paths var files = program.args; // compile files if (files.length) { console.log(); if (options.watch) { files.forEach(function(filename) { try { renderFile(filename); } catch (ex) { // keep watching when error occured. console.error(ex.stack || ex.message || ex); } fs.watchFile(filename, {persistent: true, interval: 200}, function (curr, prev) { if (curr.mtime === prev.mtime) return; try { renderFile(filename); } catch (ex) { // keep watching when error occured. console.error(ex.stack || ex.message || ex); } }); }); } else { files.forEach(renderFile); } process.on('exit', function () { console.log(); }); // stdio } else { stdin(); } /** * Compile from stdin. */ function stdin() { var buf = ''; process.stdin.setEncoding('utf8'); process.stdin.on('data', function(chunk){ buf += chunk; }); process.stdin.on('end', function(){ var output; if (options.client) { output = jade.compileClient(buf, options); } else { var fn = jade.compile(buf, options); var output = fn(options); } process.stdout.write(output); }).resume(); process.on('SIGINT', function() { process.stdout.write('\n'); process.stdin.emit('end'); process.stdout.write('\n'); process.exit(); }) } /** * Process the given path, compiling the jade files found. * Always walk the subdirectories. */ function renderFile(path) { var re = /\.jade$/; fs.lstat(path, function(err, stat) { if (err) throw err; // Found jade file if (stat.isFile() && re.test(path)) { fs.readFile(path, 'utf8', function(err, str){ if (err) throw err; options.filename = path; if (program.nameAfterFile) { options.name = getNameFromFileName(path); } var fn = options.client ? jade.compileClient(str, options) : jade.compile(str, options); // --extension if (program.extension) var extname = '.' + program.extension; else if (options.client) var extname = '.js'; else var extname = '.html'; path = path.replace(re, extname); if (program.out) path = join(program.out, basename(path)); var dir = resolve(dirname(path)); mkdirp(dir, 0755, function(err){ if (err) throw err; try { var output = options.client ? fn : fn(options); fs.writeFile(path, output, function(err){ if (err) throw err; console.log(' \033[90mrendered \033[36m%s\033[0m', path); }); } catch (e) { if (options.watch) { console.error(e.stack || e.message || e); } else { throw e } } }); }); // Found directory } else if (stat.isDirectory()) { fs.readdir(path, function(err, files) { if (err) throw err; files.map(function(filename) { return path + '/' + filename; }).forEach(renderFile); }); } }); } /** * Get a sensible name for a template function from a file path * * @param {String} filename * @returns {String} */ function getNameFromFileName(filename) { var file = path.basename(filename, '.jade'); return file.toLowerCase().replace(/[^a-z0-9]+([a-z])/g, function (_, character) { return character.toUpperCase(); }) + 'Template'; }
JavaScript
0
@@ -3354,16 +3354,85 @@ %7D);%0A + process.on('SIGINT', function() %7B%0A process.exit(1);%0A %7D);%0A %7D else
cb222353ad48aed6d081a5b8d977f78066c8329d
add test for keyboard behaviour
test/quick-exit-spec.js
test/quick-exit-spec.js
/*global casper */ var url = 'http://localhost:9999/test/test.html'; casper.test.begin( 'quick exit', 4, function suite( test ) { casper.start() .thenOpen( url ) .then(function() { test.assertExists( 'a#quick-exit', 'Quick exit link is present' ); this.click( 'a#quick-exit' ); test.assertElementCount( '*', 0, 'Page is empty after quick exit click' ); }) .then(function() { test.assertUrlMatch( /^http:\/\/www\.google\.com/, 'Landed on google.com after clicking quick exit' ); }) .back() .then(function() { test.assertUrlMatch( /^http:\/\/localhost:9999\/$/, 'Landed on localhost:9999/ after back()' ); }) .run(function() { test.done(); }); });
JavaScript
0
@@ -94,16 +94,24 @@ ick exit + (click) ', 4, fu @@ -674,12 +674,701 @@ );%0A%09%7D);%0A%7D);%0A +%0A%0Acasper.test.begin( 'quick exit (keyboard)', 5, function suite( test ) %7B%0A%0A%09casper.start()%0A%0A%09.thenOpen( url )%0A%09.then(function() %7B%0A%09%09test.assertExists( 'a#quick-exit', 'Quick exit link is present' );%0A%09%09test.assertExists( 'a#quick-exit%5Baccesskey=q%5D', 'accesskey is Q' );%0A%0A%09%09this.sendKeys( 'body', 'q' );%0A%09%09test.assertElementCount( '*', 0, 'Page is empty after quick exit click' );%0A%09%7D)%0A%0A%09.then(function() %7B%0A%09%09test.assertUrlMatch( /%5Ehttp:%5C/%5C/www%5C.google%5C.com/, 'Landed on google.com after clicking quick exit' );%0A%09%7D)%0A%0A%09.back()%0A%09.then(function() %7B%0A%09%09test.assertUrlMatch( /%5Ehttp:%5C/%5C/localhost:9999%5C/$/, 'Landed on localhost:9999/ after back()' );%0A%09%7D)%0A%0A%09.run(function() %7B%0A%09%09test.done();%0A%09%7D);%0A%7D);%0A
7562ad88d1a73a00bb4dc4848d937dc90c743ed7
Read maps, markers, infowins and icons
server/operations.js
server/operations.js
// dependencies var Api = require ("../apis/api"); /** * This function validates the post data and * returns true if data is valid * */ function validateFormData (operation, data, link) { // operation validators var validators = { // template names _validTypes: ["map", "marker", "infowin", "icon"] , _validateObject: function (obj, name) { // validate data if (!obj || obj.constructor !== Object) { return link.send (400, name + " must be an object."); } return true; } /* * Create operation validator * */ , create: function () { // type if (!data.type || data.type.constructor !== String) { return link.send (400, "type field must be a non empty string."); } // validate type if (validators._validTypes.indexOf(data.type) === -1) { return link.send (400, "Invalid type."); } // validate data return validators._validateObject (data.data, "Data"); } /* * Read operation validator * */ , read: function () { // validate query return validators._validateObject (data.query, "Query"); } /* * Update operation validator * */ , update: function () { // type if (!data.type || data.type.constructor !== String) { return link.send (400, "type field must be a non empty string."); } // validate type if (validators._validTypes.indexOf(data.type) === -1) { return link.send (400, "Invalid type."); } // validate query and data if (validators._validateObject (data.query, "Query") === true) { return validators._validateObject (data.data, "Data"); } return true; } /* * Delete operation validator * */ , delete: function () { // type if (!data.type || data.type.constructor !== String) { return link.send (400, "type field must be a non empty string."); } // validate type if (validators._validTypes.indexOf(data.type) === -1) { return link.send (400, "Invalid type."); } // validate query if (!data.query || data.query.constructor !== Object) { return link.send (400, "Query must be an object."); } return true; } } // is the user logged in? if (!link.session || !link.session.userId || !link.session.userId.toString()) { return link.session (403, "You are not logged in."); } // call validators if (validators[operation]() === true) { // add owner types switch (operation) { case "create": data.data.owner = link.session.userId.toString(); return true; case "read": data.query.owner = link.session.userId.toString(); return true; case "update": data.data.owner = link.session.userId.toString(); data.query.owner = link.session.userId.toString(); return true; case "delete": data.query.owner = link.session.userId.toString(); return true; default: link.send (200, "Invalid operation"); return false; } } } /** * This function is called when the response * from CRUD comes * * */ function handleResponse (link, err, data) { // handle error if (err) { return link.send (400, err); } // send success link.send (200, data); } /** * mono-maps#create * Create a new map * */ exports.create = function (link) { // get data, params var data = Object(link.data); // validate data if (validateFormData ("create", data, link) !== true) { return; } // create map, marker, infowindow or icon Api[data.type].create ({ data: data.data }, function (err, data) { handleResponse (link, err, data); }); }; /** * mono-maps#read * Read maps * */ exports.read = function (link) { // get data var data = Object(link.data); // validate data if (validateFormData ("read", data, link) !== true) { return; } // read map Api.map.read ({ query: data.query , noJoins: true }, function (err, data) { handleResponse (link, err, data); }); }; /** * mono-maps#update * Update a map/marker/infowin/icon * */ exports.update = function (link) { // get data var data = Object (link.data); // validate data if (validateFormData ("update", data, link) !== true) { return; } // create map, marker, infowindow or icon Api[data.type].update ({ query: data.query , data: data.data }, function (err, data) { handleResponse (link, err, data); }); }; /** * mono-maps#delete * Delete a map * */ exports.delete = function (link) { // get data var data = Object (link.data); // validate data if (validateFormData ("delete", data, link) !== true) { return; } // create map, marker, infowindow or icon Api[data.type].delete ({ query: data.query }, function (err, data) { handleResponse (link, err, data); }); }; /** * mono-maps#embed * Embeds a map * */ exports.embed = function (link) { // get data, params var data = Object (link.data); // TODO Crud call };
JavaScript
0
@@ -3967,24 +3967,44 @@ te a new map +/marker/infowin/icon %0A *%0A */%0Aexpo @@ -4417,16 +4417,39 @@ ead maps +/markers/infowins/icons %0A *%0A */%0A @@ -4662,12 +4662,19 @@ Api -.map +%5Bdata.type%5D .rea
2f2a17f599a3d3de05b61664c6d321494c01e552
Set long time caching for js/css builds.
server/production.js
server/production.js
/* eslint strict: 0 */ 'use strict'; // Load environment variables require('dotenv-safe').load(); // Load assets const assets = require('./assets'); const express = require('express'); const compression = require('compression'); const cookieParser = require('cookie-parser'); const server = express(); // Set up the regular server server.use(cookieParser()); server.use(compression()); server.use(express.static('build')); server.use(express.static('public')); server.use((request, response) => { const app = require('../build/bundle.server.js'); return app.default(request, response, assets); }); console.log(`Listening at ${process.env.HOST} on port ${process.env.PORT}`); server.listen(process.env.PORT);
JavaScript
0
@@ -415,16 +415,38 @@ ('build' +, %7B%0A%09maxage: '365d',%0A%7D ));%0Aserv
3964a3d1132380dc0a05391e62b253a156543ebb
allow space to work.
js/keyboard.js
js/keyboard.js
// Generic Keyboard (compatible) var Keyboard = { type: 0x30cf7406, revision: 1, manufacturer: 0x904b3115, CLEAR_BUFFER: 0, GET_KEY: 1, SCAN_KEYBOARD: 2, SET_INT: 3, BS: 0x10, ENTER: 0x11, INSERT: 0x12, DELETE: 0x13, UP: 0x80, DOWN: 0x81, LEFT: 0x82, RIGHT: 0x83, SHIFT: 0x90, CONTROL: 0X91, JS: { BS: 8, ENTER: 13, SHIFT: 16, CONTROL: 17, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, INSERT: 45, DELETE: 46, }, init: function() { this.buffer = [ ]; this.shift_down = false; this.control_down = false; this.translate = { }; this.translate[this.JS.BS] = this.BS; this.translate[this.JS.ENTER] = this.ENTER; this.translate[this.JS.INSERT] = this.INSERT; this.translate[this.JS.DELETE] = this.DELETE; this.translate[this.JS.UP] = this.UP; this.translate[this.JS.DOWN] = this.DOWN; this.translate[this.JS.LEFT] = this.LEFT; this.translate[this.JS.RIGHT] = this.RIGHT; }, onkeydown: function(event) { var code = window.event ? event.keyCode : event.which; switch (code) { case this.JS.SHIFT: { this.shift_down = true; return true; } case this.JS.CONTROL: { this.control_down = true; return true; } } // have to intercept BS or chrome will do something weird. if (code == this.JS.BS || code == this.JS.UP || code == this.JS.DOWN || code == this.JS.LEFT || code == this.JS.RIGHT) { this.onkeypress(event); return false; } return true; }, onkeypress: function(event) { var code = window.event ? event.keyCode : event.which; if (this.translate[code]) { code = this.translate[code]; } else if (code < 0x20 || code > 0x7e) { // ignore return; } this.buffer.push(code); // small 8-character buffer if (this.buffer.length > 8) this.buffer.shift(); // keychar = String.fromCharCode(keynum); }, onkeyup: function(event) { var code = window.event ? event.keyCode : event.which; switch (code) { case this.JS.SHIFT: { this.shift_down = false; break; } case this.JS.CONTROL: { this.control_down = false; break; } } }, interrupt: function(memory, registers) { switch (registers.A) { case this.CLEAR_BUFFER: { this.buffer = [ ]; break; } case this.GET_KEY: { var key = this.buffer.shift(); registers.C = (key === undefined) ? 0 : key; break; } case this.SCAN_KEYBOARD: { // FIXME break; } case this.SET_INT: { // FIXME break; } } return 0; }, }; /* Interrupts do different things depending on contents of the A register: A | BEHAVIOR ---+---------------------------------------------------------------------------- 0 | Clear keyboard buffer 1 | Store next key typed in C register, or 0 if the buffer is empty 2 | Set C register to 1 if the key specified by the B register is pressed, or | 0 if it's not pressed 3 | If register B is non-zero, turn on interrupts with message B. If B is zero, | disable interrupts ---+---------------------------------------------------------------------------- When interrupts are enabled, the keyboard will trigger an interrupt when one or more keys have been pressed, released, or typed. */
JavaScript
0.000003
@@ -389,16 +389,31 @@ OL: 17,%0A + SPACE: 32,%0A LEFT @@ -459,16 +459,18 @@ WN: 40,%0A +// INSE @@ -478,16 +478,18 @@ T: 45,%0A +// DELET @@ -1499,16 +1499,41 @@ JS.RIGHT + %7C%7C code == this.JS.SPACE ) %7B%0A
6f38a2da6b75dd8c1804401948b4ff33171f71a5
修改如果有QQ信息,直接返回
js/postInfo.js
js/postInfo.js
<% $include["js/answer.js"]; $include["js/questions.js"]; var data = request.post; var validators = {}; var username = data.name || ''; $include["js/userInfo.js"]; $include["js/validator.js"]; %> (function(E){ var username = document.getElementById('username'); <% var path = require('path'); var fs = require('fs'); if(!username || !qqValidator(username) ){ print('alert("请输入你的QQ号码方便记录!")'); }else{ var filepath = path.join(request.util.conf.root, '/answers/', username + '.json'); var stats = fs.existsSync(filepath); if(stats){ data = JSON.parse(fs.readFileSync(filepath)); print('alert("您已经提交过答案,得分为: ' + data.score + '")'); choice.filter(function(que){ var ok = answers[que.id] === data[que.id].toString(); validators[que.id] = ok ? 'result-right' : 'result-wrong'; return ok; }); }else if(choice.filter(function(item){return !data[item.id]}).length){ print('alert("有未完成题目!")') }else{ var score = (choice.filter(function(que){ var ok = answers[que.id] === data[que.id].toString(); validators[que.id] = ok ? 'result-right' : 'result-wrong'; return ok; }).length / choice.length * 100).toFixed(1); if(username !== '807704186'){ fs.writeFileSync(filepath, JSON.stringify({ answer: data, score: score, postDate: new Date().toLocaleString() }, null, 2)); } print('alert("您的得分为: ' + score + '")'); } } %> var post = <%=JSON.stringify(data)%>; var validators = <%=JSON.stringify(validators)%>; username.value = '<%=username%>'; for(var name in post){ var items = document.getElementsByName(name); if(items[0]){ items[0].parentNode.parentNode.parentNode.getElementsByTagName('em')[0].className = validators[name]; } for (var i = 0; i < items.length; i++) { if(post[name].toString().indexOf(items[i].value) != -1){ items[i].click(); } } } E.cookie.set('username', '<%=username%>'); })(Exam);
JavaScript
0
@@ -656,37 +656,38 @@ )');%0A%09%09%09choice.f -ilter +orEach (function(que)%7B%0A @@ -803,39 +803,24 @@ ult-wrong';%0A -%09%09%09%09return ok;%0A %09%09%09%7D);%0A%09%09%7Del
1f8a0210228908c00445952812ff5bbb3d240005
Test that no identifier exists after (method) get()
acorn-v4.js
acorn-v4.js
var asyncExit = /^async[\t ]+(return|throw)/ ; var atomOrPropertyOrLabel = /^\s*[):;]/ ; var removeComments = /([^\n])\/\*(\*(?!\/)|[^\n*])*\*\/([^\n])/g ; function hasLineTerminatorBeforeNext(st, since) { return st.lineStart >= since; } function test(regex,st,noComment) { var src = st.input.slice(st.start) ; if (noComment) { src = src.replace(removeComments,"$1 $3") ; } return regex.test(src); } /* Create a new parser derived from the specified parser, so that in the * event of an error we can back out and try again */ function subParse(parser, pos, extensions) { var p = new parser.constructor(parser.options, parser.input, pos); if (extensions) for (var k in extensions) p[k] = extensions[k] ; var src = parser ; var dest = p ; ['inFunction','inAsync','inGenerator','inModule'].forEach(function(k){ if (k in src) dest[k] = src[k] ; }) ; p.nextToken(); return p; } function asyncAwaitPlugin (parser,options){ if (!options || typeof options !== "object") options = {} ; parser.extend("parse",function(base){ return function(){ this.inAsync = options.inAsyncFunction ; if (options.awaitAnywhere && options.inAsyncFunction) parser.raise(node.start,"The options awaitAnywhere and inAsyncFunction are mutually exclusive") ; return base.apply(this,arguments); } }) ; parser.extend("parseStatement",function(base){ return function (declaration, topLevel) { var start = this.start; var startLoc = this.startLoc; if (this.type.label==='name') { if ((options.asyncExits) && test(asyncExit,this)) { // TODO: Ensure this function is itself nested in an async function or Method this.next() ; var r = this.parseStatement(declaration, topLevel) ; r.async = true ; r.start = start; r.loc && (r.loc.start = startLoc); r.range && (r.range[0] = start); return r ; } } return base.apply(this,arguments); } }) ; parser.extend("parseIdent",function(base){ return function(liberal) { if (this.options.sourceType==='module' && this.options.ecmaVersion >= 8 && options.awaitAnywhere) return base.call(this,true) ; // Force liberal mode if awaitAnywhere is set return base.apply(this,arguments) ; } }) ; parser.extend("parseExprAtom",function(base){ var NotAsync = {}; return function(refShorthandDefaultPos){ var start = this.start ; var startLoc = this.startLoc; var rhs,r = base.apply(this,arguments); if (r.type==='Identifier') { if (r.name==='await' && !this.inAsync) { if (options.awaitAnywhere) { var n = this.startNodeAt(r.start, r.loc && r.loc.start); start = this.start ; var parseHooks = { raise:function(){ try { return pp.raise.apply(this,arguments) ; } catch(ex) { throw /*inBody?ex:*/NotAsync ; } } } ; try { rhs = subParse(this,start-4,parseHooks).parseExprSubscripts() ; if (rhs.end<=start) { rhs = subParse(this,start,parseHooks).parseExprSubscripts() ; n.argument = rhs ; n = this.finishNodeAt(n,'AwaitExpression', rhs.end, rhs.loc && rhs.loc.end) ; this.pos = rhs.end; this.end = rhs.end ; this.endLoc = rhs.endLoc ; this.next(); return n ; } } catch (ex) { if (ex===NotAsync) return r ; throw ex ; } } } } return r ; } }) ; var allowedPropValues = { undefined:true, get:true, set:true, static:true, async:true, constructor:true }; parser.extend("parsePropertyName",function(base){ return function (prop) { var prevName = prop.key && prop.key.name ; var key = base.apply(this,arguments) ; if (this.value==='get') { prop.__maybeStaticAsyncGetter = true ; } if (allowedPropValues[this.value]) return key ; if (key.type === "Identifier" && (key.name === "async" || prevName === "async") && !hasLineTerminatorBeforeNext(this, key.end) // Look-ahead to see if this is really a property or label called async or await && !this.input.slice(key.end).match(atomOrPropertyOrLabel)) { if (prop.kind === 'set' || key.name === 'set') this.raise(key.start,"'set <member>(value)' cannot be be async") ; else { this.__isAsyncProp = true ; key = base.apply(this,arguments) ; if (key.type==='Identifier') { if (key.name==='set') this.raise(key.start,"'set <member>(value)' cannot be be async") ; } } } else { delete prop.__maybeStaticAsyncGetter ; } return key; }; }) ; parser.extend("parseClassMethod",function(base){ return function (classBody, method, isGenerator) { var r = base.apply(this,arguments) ; if (method.__maybeStaticAsyncGetter) { delete method.__maybeStaticAsyncGetter ; method.kind = "get" ; } return r ; } }) ; parser.extend("parseFunctionBody",function(base){ return function (node, isArrowFunction) { var wasAsync = this.inAsync ; if (this.__isAsyncProp) { node.async = true ; this.inAsync = true ; delete this.__isAsyncProp ; } var r = base.apply(this,arguments) ; this.inAsync = wasAsync ; return r ; } }) ; } module.exports = asyncAwaitPlugin ;
JavaScript
0
@@ -5018,32 +5018,55 @@ ;%0A %7D%0A + var next ;%0A if ( @@ -5094,16 +5094,84 @@ s.value%5D + && (next = this.input.slice(this.end).match(/%5Cs*(%5Cw*)/)) && next%5B1%5D )%0A
c300204816ad57a33fea88176f13a036838b297b
reset database
back/app.js
back/app.js
const os = require('os'); const path = require('path'); const express = require('express'); const cookieParser = require('cookie-parser'); const session = require('express-session'); const SequelizeStore = require('connect-session-sequelize')(session.Store); const logger = require('morgan'); const favicon = require('serve-favicon'); const bodyParser = require('body-parser'); const passport = require('passport'); const GitHubStrategy = require('passport-github').Strategy; const routes = require('./routes/index'); const models = require('./models'); const helpers = require('./util/helpers'); const listeners = require('./util/listeners'); const app = express(); app.set('views', path.join(__dirname, '../front/views')); app.set('view engine', 'pug'); // Enable CORS app.use(function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); }); app.use(favicon(path.join(__dirname, '../front/static', 'favicon.ico'))); app.use(logger('dev')); app.use(cookieParser()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(session({ secret: 'keyboard anathema', resave: false, saveUninitialized: false, store: new SequelizeStore({ db: models.sequelize, }), })); app.use(passport.initialize()); app.use(passport.session()); passport.use(new GitHubStrategy({ clientID: 'd87530f855c18573e868', clientSecret: '16136b982bbd0d619d906ee23b8c81e516f093ad', callbackURL: 'http://muddles.nepenth.xyz/auth/github/callback', }, function(accessToken, refreshToken, profile, cb) { return models.User.findOrCreate({ where: { githubId: profile.id, accessToken, refreshToken, username: profile.username, avatar: profile._json.avatar_url, profile: profile.profileUrl, }, }) .then(function () { cb(null, profile); }); } )); passport.serializeUser(function (user, done) { done(null, user.id); }); passport.deserializeUser(function (githubId, done) { return models.User.findOne({ where: { githubId } }).then(function (user) { done(null, user); }); }); app.use(express.static(path.join(__dirname, '../front/static'))); app.use(function (req, res, next) { if (req.isAuthenticated()) { return models.User.findOne({ where: { id: req.user.id, } }) .then(function (user) { res.locals.auth = true; res.locals.username = user.username; res.locals.avatar = user.avatar; res.locals.profile = user.profile; next(); }); } else { next(); } }); app.use('/', routes); // catch 404 and forward to error handler app.use(function (req, res, next) { const err = new Error('Not Found'); err.status = 404; next(err); }); // development error handler, will print stacktrace if (app.get('env') === 'development') { app.use(function (err, req, res) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler, no stacktraces leaked to user app.use(function (err, req, res) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); const port = helpers.normalizePort(process.env.PORT || '3000'); app.set('port', port); models.sequelize.sync() // models.sequelize.sync({force: true}) .then(function () { app.listen(port); app.on('error', listeners.onError); app.on('listening', listeners.onListening); console.log('Server running on http://' + os.hostname() + ':' + port); }); module.exports = app;
JavaScript
0.000002
@@ -3423,16 +3423,19 @@ port);%0A%0A +// models.s @@ -3450,19 +3450,16 @@ .sync()%0A -// models.s
add6f1d0ff2b982e2d434db4a4a32e53c3d1e6b1
add secure check for list when creating contest
controllers/contests.js
controllers/contests.js
const Contest = require('../models/Contest') const Ids = require('../models/ID') const { extractPagination, isUndefined } = require('../utils') /** 返回比赛列表 */ async function queryList (ctx, next) { const filter = {} // 用于 mongoose 的筛选 if (ctx.query.field) { // https://docs.mongodb.com/manual/reference/operator/query/where/ // field 一般为 cid 或 title // ctx.query.query 表示搜获的内容 // 使用 string 而不是 function 是因为,这里的 function 是不能访问到外部变量的 // 用模板字符串生成筛选条件 // 正则可以匹配更多的内容 filter.$where = `${new RegExp(ctx.query.query, 'i')}.test(this["${ctx.query.field}"])` } const res = await Contest .paginate(filter, { limit: +ctx.query.limit || 30, // 加号表示使其变为数字 page: +ctx.query.page || 1, sort: {cid: 1}, // '-_id' 结果不包含 _id // http://stackoverflow.com/questions/9598505/mongoose-retrieving-data-without-id-field select: '-_id title cid start end status encrypt' }) ctx.body = { contests: res.docs, pagination: extractPagination(res) } } /** 指定cid, 返回一个比赛的具体信息 */ async function queryOneContest (ctx, next) { const cid = +ctx.params.cid if (isNaN(cid)) { // cid might be a string ctx.throw(400, 'Cid should be a number') } const contest = await Contest .findOne({cid}) .select('-_id argument cid title create encrypt start end list status') .exec() // 查无此比赛 if (!contest) { ctx.throw(400, 'No such a contest') } ctx.body = { contest } } /** 创建新的比赛 Caveat: 传 post 参数的时候,对应数字的字段显示的其实为 string 类型,比如 start,理应 int, 但从 ctx.request.body 拿出来时为字符串 即时如此,mongoose 会自动转换,但你作其它事时可能需要注意 */ async function create (ctx, next) { // 必须的字段 ;['title', 'start', 'end', 'list', 'encrypt', 'argument'].forEach((item) => { if (isUndefined(ctx.request.body[item])) { ctx.throw(400, `Field "${item}" is required to create a contest`) } }) const verified = Contest.validate(ctx.request.body) if (!verified.valid) { ctx.throw(400, verified.error) } const cid = await Ids.generateId('Contest') const { title, start, end, list, encrypt, argument } = ctx.request.body const contest = new Contest({ cid, title, start, end, list, encrypt, argument }) await contest.save() ctx.body = { contest: { cid, title, start, end, list, encrypt, argument } } } module.exports = { queryList, queryOneContest, create }
JavaScript
0
@@ -38,16 +38,61 @@ ntest')%0A +const Problem = require('../models/Problem')%0A const Id @@ -2155,16 +2155,266 @@ st.body%0A +%0A // %E6%A3%80%E6%9F%A5%E5%88%97%E8%A1%A8%E9%87%8C%E7%9A%84%E9%A2%98%E6%98%AF%E5%90%A6%E9%83%BD%E5%AD%98%E5%9C%A8%0A const ps = await Promise.all(%0A list.map((pid) =%3E Problem.findOne(%7Bpid%7D).exec())%0A )%0A%0A for (let i = 0; i %3C ps.length; i += 1) %7B%0A if (!ps%5Bi%5D) %7B // %E8%BF%99%E9%81%93%E9%A2%98%E6%B2%A1%E6%89%BE%E5%88%B0%EF%BC%8C%E8%AF%B4%E6%98%8E%E6%B2%A1%E8%BF%99%E9%A2%98%0A ctx.throw(400, %60Problem $%7Blist%5Bi%5D%7D not found%60)%0A %7D%0A %7D%0A%0A const
2682962c44e67a30d48e47181cffe653d22633bd
add logic for internal v external page links and manually add hash back to link
book/nio.js
book/nio.js
require(["gitbook"], function(gitbook) { gitbook.events.bind("page.change", function(event) { function resetToc() { $('.js-toolbar-action > .fa').removeClass('fa-chevron-down--rotate180'); $('.book-header').removeClass('toc-open'); }; function setBodyScroll() { const scrollDistance = 50; if ($(window).scrollTop() > scrollDistance) { $('body').addClass('scrolled'); } else { $('body').removeClass('scrolled'); } } function bindScrollEvent() { $(window).bind('scroll', setBodyScroll); } function bindHashEvent() { $('a[href*="#"]').click(function(e) { $('html, body').animate({ scrollTop: $(e.currentTarget.hash).offset().top}, 1000); }); } // scroll to top of header on page change, initialize TOC as closed $(document).ready(function(){ if (window.location.hash === ""){ $(window).scrollTop(0); } else { $('html, body').animate({ scrollTop: $(window.location.hash).offset().top}, 1000); }; bindHashEvent(); bindScrollEvent(); resetToc(); $('.accordion').removeClass('accordionClose'); $('table').wrap('<div class="scrolling-wrapper"></div>'); // in mobile, force page change when active chapter is clicked if ($(window).width() < 600) { $('.active').click( function(e) { window.location.href = e.target.href; }); } }); // allow dynamic active location in the header var activeLocation = gitbook.state.config.pluginsConfig['theme-nio']['active-location']; $(`#nav__list--${activeLocation}`).addClass('active'); // custom search bar placeholder text, add clickable icon, and search on return keypress $('#book-search-input').append($('<div id="search-icon"></div>')); $('#book-search-input input').attr('placeholder', 'Search'); $('#book-search-input input').keypress(function (e) { var key = e.which; if (key === 13) // the enter key code { $('.js-toolbar-action > .fa').click(); } }); $('#search-icon').click( function() { $('.js-toolbar-action > .fa').click(); }); // add class to active parent chapter // remove active chapter globally $('ul.summary li').removeClass('active--chapter'); // get the level of the selected sub-menu var level = $('ul.summary li li.active').data('level'); if (level) { // find the position of the first period after the 2nd index (only works for one or two-digit levels) var dot = level.indexOf('.', 2); // the parent is the substring before the second period var parent = level.substring(0, dot); $('ul.summary li[data-level="'+parent+'"]').addClass('active--chapter'); } // this gets the sidebar expand TOC animation working $('ul.summary > li.active').addClass('animating'); setTimeout(function() { $('ul.summary > li').removeClass('animating'); }, 50); $('ul.summary > li.chapter.active').addClass('animating'); setTimeout(function() { $('ul.summary > li.chapter.active').removeClass('animating'); }, 50); // replace header hamburger icon with chevron $('.js-toolbar-action > .fa').removeClass('fa-align-justify'); $('.js-toolbar-action > .fa').addClass('fa-chevron-down'); // remove unwanted page-header elements that are added on each page change if ($('.js-toolbar-action > .fa').length > 1) { $('.js-toolbar-action > .fa')[0].remove(); } if ($('.book-header').length > 1) { $('.book-header')[1].remove(); } // rotate chevron on click $('.js-toolbar-action > .fa').click( function() { $('.book-header').toggleClass('toc-open'); $('.js-toolbar-action > .fa').toggleClass('fa-chevron-down--rotate180'); }); // add class to blockquote according to key var blkquotes = $('blockquote'); var classMap = { '[info]': 'info', '[warning]': 'warning', '[danger]': 'danger', '[success]': 'success' }; var iconMap = { '[info]': '<i class="fa fa-info-circle fa-2x blockquote-icon"></i>', '[warning]': '<i class="fa fa-exclamation-circle fa-2x blockquote-icon"></i>', '[danger]': '<i class="fa fa-ban fa-2x blockquote-icon"></i>', '[success]': '<i class="fa fa-check-circle fa-2x blockquote-icon"></i>' }; blkquotes.each(function() { for (alertType in classMap) { htmlStr = $(this).html() if (htmlStr.indexOf(alertType) > 0) { // remove alertType from text, replace with icon htmlStr = htmlStr.replace(alertType, iconMap[alertType]); $(this).html(htmlStr); // add class $(this).addClass(classMap[alertType]); $(this).addClass('callout'); } } }) }); gitbook.events.bind("exercise.submit", function() { // do something }); gitbook.events.bind("start", function() { // do things one time only, on load of book // repurpose book-header as mobile TOC // attach book-header to header and add custom content $('.header').after($('.book-header')); $('.js-toolbar-action').after( $('.custom-book-header-content')); }); });
JavaScript
0
@@ -653,138 +653,535 @@ -$('a%5Bhref*=%22#%22%5D').click(function(e) %7B%0A $('html, body').animate(%7B scrollTop: $(e.currentTarget.hash).offset().top%7D, 1000); +// for any link that includes a '#', but not only a '#'%0A $('a%5Bhref*=%22#%22%5D').click(function(e) %7B%0A // if an internal page link%0A if (e.currentTarget.href.includes(window.location.href)) %7B%0A $('html, body').animate(%7B scrollTop: $(e.currentTarget.hash).offset().top%7D, 1000);%0A // else append hash to page and go to page while keeping the url without the hash out of the history%0A %7D else %7B%0A window.location.replace(e.currentTarget.href + e.currentTarget.hash);%0A %7D %0A
1671f2dd121799eba8e28aa6b2db0282ec678dfe
Remove unused unsubscribes in example app.
Example/app/containers/DeviceDetail.js
Example/app/containers/DeviceDetail.js
import React, { PropTypes } from 'react'; import { Text, View, StyleSheet, ActivityIndicator, TouchableOpacity } from 'react-native'; import { connect } from 'react-redux'; import TopBar from '../components/TopBar'; import ServiceList from '../components/ServiceList'; import Bluetooth from 'react-native-bluetooth'; import { applicationError } from '../actions/GlobalActions'; import { setService, setDevice } from '../actions/DeviceContextActions'; import { serviceDiscovered, storeDisconnectionHandler, setConnectionStatus, setConnectionInProgress, resetServices } from '../actions/DeviceActions'; const DeviceDetail = React.createClass({ propTypes: { navigator: PropTypes.func.isRequired, applicationError: PropTypes.func.isRequired, setConnectionStatus: PropTypes.func.isRequired, setConnectionInProgress: PropTypes.func.isRequired, storeDisconnectionHandler: PropTypes.func.isRequired, setService: PropTypes.func.isRequired, setDevice: PropTypes.func.isRequired, resetServices: PropTypes.func.isRequired, serviceDiscovered: PropTypes.func.isRequired, disconnectionHandler: PropTypes.func.isRequired, isConnected: PropTypes.bool.isRequired, connectionInProgress: PropTypes.bool.isRequired, device: PropTypes.object.isRequired, services: PropTypes.array.isRequired, }, componentWillUnmount() { this.unsubscribe && this.unsubscribe(); }, disconnect() { const { setConnectionStatus, setConnectionInProgress, resetServices, applicationError, isConnected, device, } = this.props; this.unsubscribe && this.unsubscribe(); this.unsubscribe = null; if (isConnected) { setConnectionInProgress(true); this.endListeningForDisconnection(); Bluetooth.disconnect(device) .then(() => { setConnectionStatus(false); setConnectionInProgress(false); resetServices(); }).catch(e => { applicationError(e.message); }); } else { resetServices(); } }, listenForDisconnect() { const { setConnectionStatus, resetServices, } = this.props; this.endListeningForDisconnection(); setConnectionStatus(false); resetServices(); applicationError('Device connection lost'); this.props.navigator("DeviceDiscovery"); }, connect() { const { applicationError, setConnectionStatus, isConnected, setConnectionInProgress, storeDisconnectionHandler, serviceDiscovered, device } = this.props; if (isConnected) { this.disconnect(); return; } setConnectionInProgress(true); const disconnectSubscription = Bluetooth.deviceDidDisconnect(device, this.listenForDisconnect); storeDisconnectionHandler(disconnectSubscription); if ((this.props.services || []).length > 0) { return; } Bluetooth.connect(device, null) .then(() => { setConnectionStatus(true); setConnectionInProgress(false); return Bluetooth.discoverServices(device, null); }) .then(services => { services.forEach(service => serviceDiscovered(service)); }) .catch(error => applicationError(error.message)); }, serviceSelected(service) { const { setService, navigator } = this.props; setService(service); navigator('ServiceDetail'); }, endListeningForDisconnection() { const { disconnectionHandler, storeDisconnectionHandler } = this.props; disconnectionHandler(); storeDisconnectionHandler(() => {}); }, goBack() { const { setDevice, navigator, } = this.props; this.disconnect(); setDevice(null); navigator('DeviceDiscovery'); }, renderStatus() { const { connectionInProgress, isConnected } = this.props; if (connectionInProgress) { return <ActivityIndicator animating={true} />; } return ( <View style={styles.statusContainer}> <TouchableOpacity onPress={this.connect}> <Text style={styles.statusText}>{isConnected ? 'Disconnect' : 'Connect'}</Text> </TouchableOpacity> </View> ); }, renderServiceLabel() { const { isConnected } = this.props; if (!isConnected) return null; return <Text style={styles.labelText}>Services</Text>; }, render() { const { device, services } = this.props; return ( <View style={styles.container}> <TopBar headerText={"Device - " + device.name} backAction={ this.goBack } /> {this.renderStatus()} {this.renderServiceLabel()} <View style={styles.listContainer}> <ServiceList services={services} selectService={this.serviceSelected} /> </View> </View> ); }, }); const styles = StyleSheet.create({ statusText: { fontSize: 20, color: '#00AFEE', }, container: { flex: 1, }, listContainer: { flex: 1, }, labelText: { fontSize: 20, color: 'grey', marginLeft: 15, }, statusContainer: { flexDirection: 'row', justifyContent: 'center', marginTop: 5, marginBottom: 15, }, }); const mapStateToProps = state => { const { device } = state.deviceContext; return { ...state.device, device: device, }; }; const mapDispatchToProps = dispatch => { return { applicationError: message => { dispatch(applicationError(message)); }, serviceDiscovered: service => { dispatch(serviceDiscovered(service)); }, storeDisconnectionHandler: handler => { dispatch(storeDisconnectionHandler(handler)); }, setConnectionStatus: status => { dispatch(setConnectionStatus(status)); }, setConnectionInProgress: inProgress => { dispatch(setConnectionInProgress(inProgress)); }, resetServices: () => { dispatch(resetServices()); }, setService: service => { dispatch(setService(service)); }, setDevice: device => { dispatch(setDevice(device)); }, }; }; export default connect(mapStateToProps, mapDispatchToProps, null)(DeviceDetail);
JavaScript
0
@@ -1343,85 +1343,8 @@ %7D,%0A%0A - componentWillUnmount() %7B%0A this.unsubscribe && this.unsubscribe();%0A %7D,%0A%0A di @@ -1529,82 +1529,8 @@ s;%0A%0A - this.unsubscribe && this.unsubscribe();%0A this.unsubscribe = null;%0A%0A @@ -1896,17 +1896,16 @@ ;%0A %7D%0A -%0A %7D,%0A%0A
3b0fc2e20ac7091ee0d29b90631be098e09a6beb
Remove global addDecorator
react/.storybook/config.js
react/.storybook/config.js
import React from 'react'; import { configure, addDecorator, addParameters } from '@storybook/react'; import '../../html/_spark.scss'; import { withA11y } from '@storybook/addon-a11y'; import sparkTheme from "../../storybook-theming/storybook-spark-theme"; import { withTests } from '@storybook/addon-jest'; import results from '../src/.jest-test-results.json'; import '!style-loader!css-loader!sass-loader!../../storybook-theming/font-loader.scss'; import '../../storybook-theming/icon-loader'; addDecorator(withA11y); addDecorator( withTests({ results } )); addDecorator(story => <div className="sprk-o-Box">{story()}</div>) // Option defaults. addParameters({ options: { theme: sparkTheme, }, }); configure(require.context('../src', true, /\.stories\.(js|ts|tsx|mdx)$/), module);
JavaScript
0
@@ -566,74 +566,8 @@ ));%0A -addDecorator(story =%3E %3Cdiv className=%22sprk-o-Box%22%3E%7Bstory()%7D%3C/div%3E) %0A//
7b29adfacd00d6ed3d1751044e58ab13b7374bc2
Factor out 'projector' string, see https://github.com/phetsims/scenery-phet/issues/515
js/ProjectorModeCheckbox.js
js/ProjectorModeCheckbox.js
// Copyright 2018-2021, University of Colorado Boulder /** * ProjectorModeCheckbox is a checkbox used to switch between 'default' and 'projector' color profiles. * It is most commonly used in the Options dialog, accessed from the PhET menu in some sims. It wires up to the * singleton instance of SCENERY/colorProfileProperty * * @author John Blanco * @author Chris Malley (PixelZoom, Inc.) */ import BooleanProperty from '../../axon/js/BooleanProperty.js'; import merge from '../../phet-core/js/merge.js'; import Text from '../../scenery/js/nodes/Text.js'; import SceneryConstants from '../../scenery/js/SceneryConstants.js'; import colorProfileProperty from '../../scenery/js/util/colorProfileProperty.js'; import Checkbox from '../../sun/js/Checkbox.js'; import Tandem from '../../tandem/js/Tandem.js'; import joist from './joist.js'; import joistStrings from './joistStrings.js'; import OptionsDialog from './OptionsDialog.js'; const projectorModeString = joistStrings.projectorMode; class ProjectorModeCheckbox extends Checkbox { /** * @param {Object} [options] */ constructor( options ) { options = merge( { font: OptionsDialog.DEFAULT_FONT, maxTextWidth: 350, // empirically determined, works reasonably well for long strings tandem: Tandem.REQUIRED, // phet-io phetioLinkProperty: false // we will create the `property` tandem here in the subtype }, options ); assert && assert( phet.chipper.colorProfiles[ 0 ] !== SceneryConstants.PROJECTOR_COLOR_PROFILE_NAME && phet.chipper.colorProfiles.includes( SceneryConstants.PROJECTOR_COLOR_PROFILE_NAME ), 'ProjectorModeCheckbox requires sims that support projector color profiles and a different primary one' ); const labelNode = new Text( projectorModeString, { font: options.font, maxWidth: options.maxTextWidth } ); // Internal adapter Property, to map between the string value needed by colorProfileProperty // and the boolean value needed by superclass Checkbox. const projectorModeEnabledProperty = new BooleanProperty( colorProfileProperty.value === SceneryConstants.PROJECTOR_COLOR_PROFILE_NAME, { tandem: options.tandem.createTandem( 'property' ) } ); projectorModeEnabledProperty.link( isProjectorMode => { colorProfileProperty.value = ( isProjectorMode ? SceneryConstants.PROJECTOR_COLOR_PROFILE_NAME : phet.chipper.colorProfiles[ 0 ] ); } ); const profileNameListener = profileName => { projectorModeEnabledProperty.value = ( profileName === 'projector' ); }; colorProfileProperty.link( profileNameListener ); super( labelNode, projectorModeEnabledProperty, options ); // @private - dispose function this.disposeProjectorModeCheckbox = function() { colorProfileProperty.unlink( profileNameListener ); projectorModeEnabledProperty.dispose(); }; } /** * @public * @override */ dispose() { this.disposeProjectorModeCheckbox(); super.dispose(); } } joist.register( 'ProjectorModeCheckbox', ProjectorModeCheckbox ); export default ProjectorModeCheckbox;
JavaScript
0.999987
@@ -2559,27 +2559,61 @@ ame === -'projector' +SceneryConstants.PROJECTOR_COLOR_PROFILE_NAME );%0A
a9411ef17cca6badc45ea72c73e5b87abf2ef4b7
Remove dead code
skeletons/app/bundles/frontend/public/js/global.js
skeletons/app/bundles/frontend/public/js/global.js
graoJS = angular.module('graoJS', ['ngResource', 'ui.bootstrap', 'ui.select2']); graoJS.constant("config", { baseUrl: window.location.protocol+"//"+ window.location.hostname+":"+ window.location.port+"\:"+ window.location.port }); function clearObject(obj){ for (var o in obj) { if (isNaN(parseInt(o))) { clearObject(obj[o]); if(typeof obj[o] == 'string') obj[o] = ''; else if(typeof obj[o] == 'number' || typeof obj[o] == 'boolean') obj[o] = null; else if(obj[o] instanceof Array) obj[o] = new Array(); } } } function uniqueTrue(field, newItem, itemArray){ if(newItem[field] == true) { if(itemArray.length > 0) { for(var item in itemArray) { if(itemArray[item] != newItem) itemArray[item][field] = false; } } } } function validate(alert, errorObject, responseData, pathsIgnore){ if(!pathsIgnore) pathsIgnore = new Array(); function jumpPath(errorObject, paths, value) { var newPath = paths[0]; paths.shift(); if(!errorObject[newPath]) errorObject[newPath] = {}; if(paths.length == 0) errorObject[newPath] = value; else jumpPath(errorObject[newPath], paths, value); } clearObject(errorObject); var errors = responseData.data; if(responseData.event && responseData.event.status == false) { var countErrors = 0; var isFieldErros = false; var allMessages = ''; if(errors) { for(var iField in errors){ if(errors[iField].path) { isFieldErros = true; if(!(pathsIgnore.indexOf(errors[iField].path) >= 0)) { if(errors[iField].message) allMessages += ", "+iField+": "+errors[iField].message; else allMessages += ", "+iField+": "+errors[iField]; countErrors++; if(errors[iField].path.indexOf('.') != -1) jumpPath(errorObject, errors[iField].path.split('.'), errors[iField].message); else if(typeof errorObject[errors[iField].path] != 'object') // else ? errorObject[errors[iField].path] = errors[iField].message; } } } } if(countErrors > 0 || !isFieldErros) { alert.show = true; alert.style = responseData.event.style; alert.message = responseData.event.message+allMessages; return false; } else { return true; } } else if(responseData.event && responseData.event.status == true && responseData.event.message) { // else ? alert.show = true; alert.style = responseData.event.style; alert.message = responseData.event.message; return true; } else if(responseData.event.status == true) { return true; } else { return false; } } var DataList = function() { var self = this; this.data = []; this.filter = null; this.sort = { field: '_id', type: '-'}; this.page = { skip: 0, limit: 10, current: 1 }; this.status = { totality: 0, filtered: 0, listing: 0 }; this.toParams = function(){ for(var k in this.filter) { if(this.filter[k] == null || this.filter[k] == "") delete this.filter[k]; } return { filter: JSON.stringify(this.filter), sort: JSON.stringify(this.sort), page: JSON.stringify(this.page), status: JSON.stringify(this.status) }; } this.sortClass = function(fieldName){ if(this.sort.field == fieldName && this.sort.type == '') return 'sorting_asc'; else if(this.sort.field == fieldName && this.sort.type == '-') return 'sorting_desc'; else return 'sorting'; } this.sortBy = function(fieldName){ this.sort.field = fieldName; this.sort.type = (this.sort.type == '-') ? '' : '-'; } this.reset = function(){ this.filter = null; this.sort = { field: '_id', type: '-'}; this.page = { skip: 0, limit: 10, current: 1 }; } }
JavaScript
0.001497
@@ -77,172 +77,8 @@ '%5D); -%0AgraoJS.constant(%22config%22, %7B%0A baseUrl: window.location.protocol+%22//%22+%0A window.location.hostname+%22:%22+%0A window.location.port+%22%5C:%22+%0A window.location.port%0A%7D); %0A%0Afu @@ -3726,12 +3726,13 @@ : 1 %7D;%0A %7D%0A%7D +%0A
6bc7fb4541bf5e590aaba8a8fa156f2711d3d141
Add constructor annotation as part of phetsims/joist#189 review
js/SpinningIndicatorNode.js
js/SpinningIndicatorNode.js
// Copyright 2002-2015, University of Colorado Boulder /** * A spinnable busy indicator, to indicate something behind the scenes is in progress (but with no indication of how * far along it is). * * The actual rectangles/circles/etc. (called elements in the documentation) stay in fixed positions, but their fill is * changed to give the impression of rotation. * * @author Jonathan Olson <jonathan.olson@colorado.edu> */ define( function( require ) { 'use strict'; // Imports var inherit = require( 'PHET_CORE/inherit' ); var Node = require( 'SCENERY/nodes/Node' ); var Rectangle = require( 'SCENERY/nodes/Rectangle' ); var Circle = require( 'SCENERY/nodes/Circle' ); var Color = require( 'SCENERY/util/Color' ); function SpinningIndicatorNode( options ) { // default options options = _.extend( { indicatorSize: 15, // {number} - The width/height taken up by the indicator. indicatorSpeed: 1, // {number} - A multiplier for how fast/slow the indicator will spin. elementFactory: SpinningIndicatorNode.rectangleFactory, // {function( options ) => {Node}} - To create the elements elementQuantity: 16, // {number} - How many elements should exist activeColor: 'rgba(0,0,0,1)', // {string|Color} - The active "mostly visible" color at the lead. inactiveColor: 'rgba(0,0,0,0.15)' // {string|Color} - The inactive "mostly invisible" color at the tail. }, options ); this.options = options; Node.call( this, options ); this.indicatorRotation = Math.PI * 2; // Current angle of rotation (starts at 2pi so our modulo opreation is safe below) // parse the colors (if necessary) so we can quickly interpolate between the two this.activeColor = new Color( options.activeColor ); this.inactiveColor = new Color( options.inactiveColor ); // the angle between each element this.angleDelta = 2 * Math.PI / options.elementQuantity; // create and add all of the elements this.elements = []; var angle = 0; for ( var i = 0; i < options.elementQuantity; i++ ) { var element = options.elementFactory( this.options ); // push the element to the outside of the circle element.right = options.indicatorSize / 2; // center it vertically, so it can be rotated nicely into place element.centerY = 0; // rotate each element by its specific angle element.rotate( angle, true ); angle += this.angleDelta; this.elements.push( element ); this.addChild( element ); } this.step( 0 ); // initialize colors } return inherit( Node, SpinningIndicatorNode, { step: function( dt ) { // increment rotation based on DT this.indicatorRotation += dt * 10.0 * this.options.indicatorSpeed; // update each element var angle = this.indicatorRotation; for ( var i = 0; i < this.elements.length; i++ ) { // a number from 0 (active head) to 1 (inactive tail). var ratio = Math.pow( ( angle / ( 2 * Math.PI ) ) % 1, 0.5 ); // Smoother transition, mapping our ratio from [0,0.2] => [1,0] and [0.2,1] => [0,1]. // Otherwise, elements can instantly switch from one color to the other, which is visually displeasing. if ( ratio < 0.2 ) { ratio = 1 - ratio * 5; } else { ratio = ( ratio - 0.2 ) * 10 / 8; } // Fill it with the interpolated color var red = ratio * this.inactiveColor.red + ( 1 - ratio ) * this.activeColor.red; var green = ratio * this.inactiveColor.green + ( 1 - ratio ) * this.activeColor.green; var blue = ratio * this.inactiveColor.blue + ( 1 - ratio ) * this.activeColor.blue; var alpha = ratio * this.inactiveColor.alpha + ( 1 - ratio ) * this.activeColor.alpha; this.elements[i].fill = new Color( red, green, blue, alpha ); // And rotate to the next element (in the opposite direction, so our motion is towards the head) angle -= this.angleDelta; } } }, { // Factory method for creating rectangular-shaped elements, sized to fit. rectangleFactory: function( options ) { return new Rectangle( 0, 0, options.indicatorSize * 0.175, 1.2 * options.indicatorSize / options.elementQuantity ); }, // Factory method for creating circle-shaped elements, sized to fit. circleFactory: function( options ) { return new Circle( 0.8 * options.indicatorSize / options.elementQuantity ); } } ); } );
JavaScript
0
@@ -732,16 +732,76 @@ or' );%0A%0A +%0A /**%0A * @param %7Bobject%7D options%0A * @constructor%0A */%0A functi
afbc662dcdf7f6846c9a4dd8466c56effc155455
fix gettings user roles from cache (#2034)
src/Auth.js
src/Auth.js
var deepcopy = require('deepcopy'); var Parse = require('parse/node').Parse; var RestQuery = require('./RestQuery'); // An Auth object tells you who is requesting something and whether // the master key was used. // userObject is a Parse.User and can be null if there's no user. function Auth({ config, isMaster = false, user, installationId } = {}) { this.config = config; this.installationId = installationId; this.isMaster = isMaster; this.user = user; // Assuming a users roles won't change during a single request, we'll // only load them once. this.userRoles = []; this.fetchedRoles = false; this.rolePromise = null; } // Whether this auth could possibly modify the given user id. // It still could be forbidden via ACLs even if this returns true. Auth.prototype.couldUpdateUserId = function(userId) { if (this.isMaster) { return true; } if (this.user && this.user.id === userId) { return true; } return false; }; // A helper to get a master-level Auth object function master(config) { return new Auth({ config, isMaster: true }); } // A helper to get a nobody-level Auth object function nobody(config) { return new Auth({ config, isMaster: false }); } // Returns a promise that resolves to an Auth object var getAuthForSessionToken = function({ config, sessionToken, installationId } = {}) { return config.cacheController.user.get(sessionToken).then((userJSON) => { if (userJSON) { let cachedUser = Parse.Object.fromJSON(userJSON); return Promise.resolve(new Auth({config, isMaster: false, installationId, user: cachedUser})); } var restOptions = { limit: 1, include: 'user' }; var query = new RestQuery(config, master(config), '_Session', {sessionToken}, restOptions); return query.execute().then((response) => { var results = response.results; if (results.length !== 1 || !results[0]['user']) { return nobody(config); } var now = new Date(), expiresAt = results[0].expiresAt ? new Date(results[0].expiresAt.iso) : undefined; if (expiresAt < now) { throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'Session token is expired.'); } var obj = results[0]['user']; delete obj.password; obj['className'] = '_User'; obj['sessionToken'] = sessionToken; config.cacheController.user.put(sessionToken, obj); let userObject = Parse.Object.fromJSON(obj); return new Auth({config, isMaster: false, installationId, user: userObject}); }); }); }; // Returns a promise that resolves to an array of role names Auth.prototype.getUserRoles = function() { if (this.isMaster || !this.user) { return Promise.resolve([]); } if (this.fetchedRoles) { return Promise.resolve(this.userRoles); } if (this.rolePromise) { return this.rolePromise; } this.rolePromise = this._loadRoles(); return this.rolePromise; }; // Iterates through the role tree and compiles a users roles Auth.prototype._loadRoles = function() { var cacheAdapter = this.config.cacheController; return cacheAdapter.role.get(this.user.id).then((cachedRoles) => { if (cachedRoles != null) { this.fetchedroles = true; return Promise.resolve(cachedRoles); } var restWhere = { 'users': { __type: 'Pointer', className: '_User', objectId: this.user.id } }; // First get the role ids this user is directly a member of var query = new RestQuery(this.config, master(this.config), '_Role', restWhere, {}); return query.execute().then((response) => { var results = response.results; if (!results.length) { this.userRoles = []; this.fetchedRoles = true; this.rolePromise = null; cacheAdapter.role.put(this.user.id, this.userRoles); return Promise.resolve(this.userRoles); } var rolesMap = results.reduce((m, r) => { m.names.push(r.name); m.ids.push(r.objectId); return m; }, {ids: [], names: []}); // run the recursive finding return this._getAllRolesNamesForRoleIds(rolesMap.ids, rolesMap.names) .then((roleNames) => { this.userRoles = roleNames.map((r) => { return 'role:' + r; }); this.fetchedRoles = true; this.rolePromise = null; cacheAdapter.role.put(this.user.id, this.userRoles); return Promise.resolve(this.userRoles); }); }); }); }; // Given a list of roleIds, find all the parent roles, returns a promise with all names Auth.prototype._getAllRolesNamesForRoleIds = function(roleIDs, names = [], queriedRoles = {}) { let ins = roleIDs.filter((roleID) => { return queriedRoles[roleID] !== true; }).map((roleID) => { // mark as queried queriedRoles[roleID] = true; return { __type: 'Pointer', className: '_Role', objectId: roleID } }); // all roles are accounted for, return the names if (ins.length == 0) { return Promise.resolve([...new Set(names)]); } // Build an OR query across all parentRoles let restWhere; if (ins.length == 1) { restWhere = { 'roles': ins[0] }; } else { restWhere = { 'roles': { '$in': ins }} } let query = new RestQuery(this.config, master(this.config), '_Role', restWhere, {}); return query.execute().then((response) => { var results = response.results; // Nothing found if (!results.length) { return Promise.resolve(names); } // Map the results with all Ids and names let resultMap = results.reduce((memo, role) => { memo.names.push(role.name); memo.ids.push(role.objectId); return memo; }, {ids: [], names: []}); // store the new found names names = names.concat(resultMap.names); // find the next ones, circular roles will be cut return this._getAllRolesNamesForRoleIds(resultMap.ids, names, queriedRoles) }).then((names) => { return Promise.resolve([...new Set(names)]) }) } module.exports = { Auth: Auth, master: master, nobody: nobody, getAuthForSessionToken: getAuthForSessionToken };
JavaScript
0
@@ -3221,24 +3221,60 @@ les = true;%0A + this.userRoles = cachedRoles;%0A return
86ac19830490ce57fa859752833ecddd40ba9977
fix merge
controllers/earnings.js
controllers/earnings.js
var config = require(__dirname + '/../config/config'), logger = require(__dirname + '/../lib/logger'), util = require(__dirname + '/../helpers/util'), qs = require('querystring'), http = require('http'), mysql = require(__dirname + '/../lib/mysql')(config.db_earnings); //get each earnings from the database 'earnings_report' //based from each feature from the dashboard, eto yung mga nasa overview tab exports.getChannelEarnings = function(req,res,next) { var data = util.chk_rqd(['user_id','report_id'], req.body, next); }; exports.getNetworkEarnings = function(req,res,next) { var data = util.chk_rqd(['user_id','report_id'], req.body, next); }; exports.getRecruiterEarnings = function(req,res,next) { var data = util.chk_rqd(['user_id','report_id'], req.body, next); }; exports.getPaymentSchedule = function(req,res,next) { var data = util.chk_rqd(['user_id','report_id'], req.body, next); }; exports.getRangeOfPayments = function(req,res,next) { var data = util.chk_rqd(['user_id'], req.body, next); }; exports.generateSummedPayouts = function(req,res,next) { //check if we have admin scopes var data = util.get_data([ 'report_id', 'access_token' ], [], req.query), get_earnings = function (report_id) { console.log('Processing . . . . .'); mysql('select sum(total_earnings) as total, channel, user_channel_id from revenue_vid where report_id = ? group by user_channel_id order by total asc;',[report_id], function (err, result) { if (err) return next(err); for(var i in result) { var rs = { report_id : report_id, channel_id : result[i].user_channel_id, earnings : result[i].total } mysql('INSERT into summed_earnings SET ?',rs, function(err,rs){ if(err) { logger.log('error', err.message || err); return; } console.log(rs); }); } }); }; if(typeof data === 'string') return next(data); get_earnings(data.report_id); };
JavaScript
0.000001
@@ -1686,16 +1686,29 @@ %09%09%09mysql +.open().query ('INSERT @@ -1877,16 +1877,33 @@ %09%09%09%09%7D);%0A +%09%09%09%09%09mysql.end(); %0A%09%09%09%09%7D%0A%09
b1f18cd8aeb4cbad35dd4c5fb79182dbff18a1fc
Fix test
packages/core/src/transitions/index.spec.js
packages/core/src/transitions/index.spec.js
import * as module from './'; describe('core root', () => { it('should pass', () => { expect(module).to.have.keys('expand', 'fadeout', 'move', 'reveal'); }); });
JavaScript
0.000004
@@ -119,16 +119,38 @@ ys(' -e +circleE xpand', + 'circleShrink', 'fa @@ -173,16 +173,26 @@ 'reveal' +, 'custom' );%0A %7D);
8771600d142cd774e50532d31d3cb362eab958b6
fix callData usage
Sources/Rendering/Core/PointPicker/example/PickerInteractorStyle.js
Sources/Rendering/Core/PointPicker/example/PickerInteractorStyle.js
import macro from 'vtk.js/Sources/macro'; import vtkInteractorStyleTrackballCamera from 'vtk.js/Sources/Interaction/Style/InteractorStyleTrackballCamera'; import vtkSphereSource from 'vtk.js/Sources/Filters/Sources/SphereSource'; import vtkActor from 'vtk.js/Sources/Rendering/Core/Actor'; import vtkMapper from 'vtk.js/Sources/Rendering/Core/Mapper'; // ---------------------------------------------------------------------------- // vtkInteractorStyleTrackballCamera2 methods // ---------------------------------------------------------------------------- function vtkPickerInteractorStyle(publicAPI, model) { // Set our className model.classHierarchy.push('vtkPickerInteractorStyle'); // Capture "parentClass" api for internal use const superClass = Object.assign({}, publicAPI); publicAPI.handleLeftButtonPress = () => { const pos = model.interactor.getEventPosition( model.interactor.getPointerIndex() ); publicAPI.findPokedRenderer(pos.x, pos.y); if (model.currentRenderer === null) { return; } const renderer = model.currentRenderer; const interactor = model.interactor; const point = [pos.x, pos.y, 0.0]; interactor.getPicker().pick(point, renderer); // Display picked position const pickPosition = interactor.getPicker().getPickPosition(); const sphere = vtkSphereSource.newInstance(); sphere.setCenter(pickPosition); sphere.setRadius(0.01); const mapper = vtkMapper.newInstance(); mapper.setInputData(sphere.getOutputData()); const actor = vtkActor.newInstance(); actor.setMapper(mapper); actor.getProperty().setColor(1.0, 0.0, 0.0); model.currentRenderer.addActor(actor); // Display picked point from an actor const pickedPoint = interactor.getPicker().getPickedPositions(); for (let i = 0; i < pickedPoint.length; i++) { const s = vtkSphereSource.newInstance(); s.setCenter(pickedPoint[i]); s.setRadius(0.01); const m = vtkMapper.newInstance(); m.setInputData(s.getOutputData()); const a = vtkActor.newInstance(); a.setMapper(m); a.getProperty().setColor(1.0, 1.0, 0.0); model.currentRenderer.addActor(a); } model.interactor.render(); superClass.handleLeftButtonPress(); }; } // ---------------------------------------------------------------------------- // Object factory // ---------------------------------------------------------------------------- const DEFAULT_VALUES = {}; export function extend(publicAPI, model, initialValues = {}) { Object.assign(model, DEFAULT_VALUES, initialValues); // Inheritance vtkInteractorStyleTrackballCamera.extend(publicAPI, model, initialValues); // Object specific methods vtkPickerInteractorStyle(publicAPI, model); } // ---------------------------------------------------------------------------- export const newInstance = macro.newInstance( extend, 'vtkPickerInteractorStyle' ); // ---------------------------------------------------------------------------- export default Object.assign({ newInstance, extend });
JavaScript
0
@@ -824,16 +824,24 @@ ress = ( +callData ) =%3E %7B%0A @@ -859,235 +859,63 @@ s = -model.interactor.getEventPosition(%0A model.interactor.getPointerIndex()%0A );%0A publicAPI.findPokedRenderer(pos.x, pos.y);%0A if (model.currentRenderer === null) %7B%0A return;%0A %7D%0A%0A const renderer = model.current +callData.position;%0A%0A const renderer = callData.poked Rend @@ -1476,38 +1476,25 @@ , 0.0);%0A -model.currentR +r enderer.addA @@ -2082,16 +2082,24 @@ onPress( +callData );%0A %7D;%0A
7c2620d6de71108237e62c3979d23ff96e7397be
Allow to override router's handleURL
packages/ember-routing/lib/system/router.js
packages/ember-routing/lib/system/router.js
/** @module ember @submodule ember-routing */ var Router = requireModule("router"); var get = Ember.get, set = Ember.set, classify = Ember.String.classify; var DefaultView = Ember.View.extend(Ember._Metamorph); require("ember-routing/system/dsl"); function setupLocation(router) { var location = get(router, 'location'), rootURL = get(router, 'rootURL'); if ('string' === typeof location) { location = set(router, 'location', Ember.Location.create({ implementation: location })); if (typeof rootURL === 'string') { set(location, 'rootURL', rootURL); } } } Ember.Router = Ember.Object.extend({ location: 'hash', init: function() { this.router = this.constructor.router; this._activeViews = {}; setupLocation(this); }, startRouting: function() { this.router = this.router || this.constructor.map(Ember.K); var router = this.router, location = get(this, 'location'), container = this.container, self = this; setupRouter(this, router, location); container.register('view', 'default', DefaultView); container.register('view', 'toplevel', Ember.View.extend()); router.handleURL(location.getURL()); location.onUpdateURL(function(url) { router.handleURL(url); }); }, didTransition: function(infos) { // Don't do any further action here if we redirected for (var i=0, l=infos.length; i<l; i++) { if (infos[i].handler.transitioned) { return; } } var appController = this.container.lookup('controller:application'), path = routePath(infos); set(appController, 'currentPath', path); this.notifyPropertyChange('url'); if (get(this, 'namespace').LOG_TRANSITIONS) { Ember.Logger.log("Transitioned into '" + path + "'"); } }, handleURL: function(url) { this.router.handleURL(url); this.notifyPropertyChange('url'); }, transitionTo: function(name) { var args = [].slice.call(arguments); doTransition(this, 'transitionTo', args); }, replaceWith: function() { var args = [].slice.call(arguments); doTransition(this, 'replaceWith', args); }, generate: function() { var url = this.router.generate.apply(this.router, arguments); return this.location.formatURL(url); }, isActive: function(routeName) { var router = this.router; return router.isActive.apply(router, arguments); }, send: function(name, context) { if (Ember.$ && context instanceof Ember.$.Event) { context = context.context; } this.router.trigger(name, context); }, hasRoute: function(route) { return this.router.hasRoute(route); }, _lookupActiveView: function(templateName) { var active = this._activeViews[templateName]; return active && active[0]; }, _connectActiveView: function(templateName, view) { var existing = this._activeViews[templateName]; if (existing) { existing[0].off('willDestroyElement', this, existing[1]); } var disconnect = function() { delete this._activeViews[templateName]; }; this._activeViews[templateName] = [view, disconnect]; view.one('willDestroyElement', this, disconnect); } }); Ember.Router.reopenClass({ defaultFailureHandler: { setup: function(error) { Ember.Logger.error('Error while loading route:', error); // Using setTimeout allows us to escape from the Promise's try/catch block setTimeout(function() { throw error; }); } } }); function getHandlerFunction(router) { var seen = {}, container = router.container; return function(name) { var handler = container.lookup('route:' + name); if (seen[name]) { return handler; } seen[name] = true; if (!handler) { if (name === 'loading') { return {}; } if (name === 'failure') { return router.constructor.defaultFailureHandler; } container.register('route', name, Ember.Route.extend()); handler = container.lookup('route:' + name); } handler.routeName = name; return handler; }; } function handlerIsActive(router, handlerName) { var handler = router.container.lookup('route:' + handlerName), currentHandlerInfos = router.router.currentHandlerInfos, handlerInfo; for (var i=0, l=currentHandlerInfos.length; i<l; i++) { handlerInfo = currentHandlerInfos[i]; if (handlerInfo.handler === handler) { return true; } } return false; } function routePath(handlerInfos) { var path = []; for (var i=1, l=handlerInfos.length; i<l; i++) { var name = handlerInfos[i].name, nameParts = name.split("."); path.push(nameParts[nameParts.length - 1]); } return path.join("."); } function setupRouter(emberRouter, router, location) { var lastURL; router.getHandler = getHandlerFunction(emberRouter); var doUpdateURL = function() { location.setURL(lastURL); }; router.updateURL = function(path) { lastURL = path; Ember.run.once(doUpdateURL); }; if (location.replaceURL) { var doReplaceURL = function() { location.replaceURL(lastURL); }; router.replaceURL = function(path) { lastURL = path; Ember.run.once(doReplaceURL); }; } router.didTransition = function(infos) { emberRouter.didTransition(infos); }; } function doTransition(router, method, args) { var passedName = args[0], name; if (!router.router.hasRoute(args[0])) { name = args[0] = passedName + '.index'; } else { name = passedName; } Ember.assert("The route " + passedName + " was not found", router.router.hasRoute(name)); router.router[method].apply(router.router, args); router.notifyPropertyChange('url'); } Ember.Router.reopenClass({ map: function(callback) { var router = this.router = new Router(); var dsl = Ember.RouterDSL.map(function() { this.resource('application', { path: "/" }, function() { callback.call(this); }); }); router.map(dsl.generate()); return router; } });
JavaScript
0
@@ -1165,30 +1165,28 @@ nd());%0A%0A -router +this .handleURL(l @@ -1251,22 +1251,20 @@ %7B%0A -router +self .handleU
08d4a3489c356f84df4f0aa0aacb896ea57f148e
fix handlebars require 2
app/assets/javascripts/farma_keyboard_rails_main.js
app/assets/javascripts/farma_keyboard_rails_main.js
//= require_tree .
JavaScript
0.000024
@@ -1,8 +1,31 @@ +//= require handlebars%0A //= requ
2e3520bf61b08bf4a1c386b2c90ba6a8707c42b2
use 400 messages
controllers/messages.js
controllers/messages.js
var async = require('async'), config = require('../config'), faye = require('faye'), models = require('../models'), services = require('../services'); exports.index = function(req, res) { // TODO: add paging, querying var filter = {}; var start = 0; var limit = 200; var sort = { timestamp: -1 }; services.messages.find(filter, start, limit, sort, function(err, messages) { if (err) return res.send(400, err); var clientMessages = messages.map(function(message) { return message.toClientView(); }); res.send({"messages": clientMessages}); }); }; exports.show = function(req, res) { services.messages.findById(req.params.id, function(err, message) { if (err) return res.send(400, err); if (!message) return res.send(404); res.send({"message": message.toClientView()}); }); }; exports.create = function(req, res) { console.log("message.create: received " + req.body.length + " messages."); async.concat(req.body, function(message_object, callback) { var message = new models.Message(message_object); callback(null, [message]); }, function (err, messages) { console.log("message.create: creating " + req.body.length + " messages."); services.messages.createMany(messages, function(err, saved_messages) { console.log("message.create: saved messages: " + JSON.stringify(saved_messages)); if (err) res.send(400, err); else res.send({"messages": saved_messages}); }); }); };
JavaScript
0
@@ -287,9 +287,9 @@ t = -2 +4 00;%0A
7c830fa7320fdcbe29ce425efd3748e75005902a
Rename Chart in Base to cleanup build
src/Base.js
src/Base.js
import d3 from 'd3'; import { difference, extend, inherits, isString, objectEach } from './utils'; import { property, bindAllDi, dimensions } from './helpers'; var Chart = d3.chart(); // TEMP Clear namespace from mixins /** @namespace */ /** Shared functionality between all charts and components. - Set properties automatically from `options`, - Store fully transformed data - Adds `"before:draw"` and `"draw"` events - Standard `width` and `height` calculations @class Base */ function Base(selection, options) { // d3.chart() constructor without transform and initialize cascade this.base = selection; this._layers = {}; this._attached = {}; this._events = {}; // Bind all di-functions to this chart bindAllDi(this); // Set options (and properties with set_from_options) if (options) this.options(options); // Initialize Chart (relies on explicitly calling super in initialize) this.initialize(options); } inherits(Base, Chart); extend(Base.prototype, { initialize: function() {}, transform: function(data) { return data; }, demux: function(name, data) { return data; }, // Add events to draw: "before:draw" and "draw" draw: function(data) { // Transform data (relies on explicitly calling super in transform) data = this.transform(data); // Store fully-transformed data for reference this.data(data); this.trigger('before:draw', data); objectEach(this._layers, function(layer) { layer.draw(data); }); objectEach(this._attached, function(attachment, name) { attachment.draw(this.demux(name, data)); }, this); this.trigger('draw', data); }, // Explicitly load d3.chart prototype layer: Chart.prototype.layer, unlayer: Chart.prototype.unlayer, attach: Chart.prototype.attach, on: Chart.prototype.on, once: Chart.prototype.once, off: Chart.prototype.off, trigger: Chart.prototype.trigger, /** Store fully-transformed data for direct access from the chart @property data @type Any */ data: property(), /** Overall options for chart/component, automatically setting any matching properties. @example ```js var property = d3.compose.helpers.property; d3.chart('Base').extend('HasProperties', { a: property(), b: property({ set: function(value) { return { override: value + '!' }; } }) }); var instance = d3.select('#chart') .chart('HasProperties', { a: 123, b: 'Howdy', c: true }); // Equivalent to: // d3.select(...) // .chart('HasProperties') // .options({...}); console.log(instance.a()); // -> 123 console.log(instance.b()); // -> Howdy! console.log(instance.options().c); // -> true ``` @property options @type Object */ options: property({ default_value: {}, set: function(options, previous) { // Clear all unset options, except for data and options if (previous) { var unset = difference(Object.keys(previous), Object.keys(options)); unset.forEach(function(key) { if (key != 'data' && key != 'options' && isProperty(this, key)) this[key](undefined); }, this); } objectEach(options, function setFromOptions(value, key) { if (isProperty(this, key)) this[key](value); }, this); function isProperty(chart, key) { return chart[key] && chart[key].is_property && chart[key].set_from_options; } } }), /** Get width of `this.base`. (Does not include `set` for setting width of `this.base`) @method width @return {Number} */ width: function width() { return dimensions(this.base).width; }, /** Get height of `this.base`. (Does not include `set` for setting height of `this.base`) @method height @return {Number} */ height: function height() { return dimensions(this.base).height; } }); Base.extend = function(proto_props, static_props) { // name may be first parameter for d3.chart usage var name; if (isString(proto_props)) { name = proto_props; proto_props = static_props; static_props = arguments[2]; } var Parent = this; var Child; if (proto_props && proto_props.hasOwnProperty('constructor')) { Child = proto_props.constructor; // inherits sets constructor, remove from proto_props proto_props = extend({}, proto_props); delete proto_props.constructor; } else { Child = function() { return Parent.apply(this, arguments); }; } inherits(Child, Parent); if (static_props) extend(Child, static_props); if (proto_props) extend(Child.prototype, proto_props); // If name is given, register with d3.chart if (name) Chart[name] = Child; return Child; }; export default Base;
JavaScript
0
@@ -173,16 +173,18 @@ s';%0Avar +d3 Chart = @@ -195,16 +195,16 @@ hart();%0A - %0A// TEMP @@ -983,16 +983,18 @@ s(Base, +d3 Chart);%0A @@ -1726,24 +1726,26 @@ pe%0A layer: +d3 Chart.protot @@ -1762,24 +1762,26 @@ %0A unlayer: +d3 Chart.protot @@ -1803,16 +1803,18 @@ attach: +d3 Chart.pr @@ -1835,16 +1835,18 @@ ,%0A on: +d3 Chart.pr @@ -1865,16 +1865,18 @@ once: +d3 Chart.pr @@ -1896,16 +1896,18 @@ %0A off: +d3 Chart.pr @@ -1930,16 +1930,18 @@ rigger: +d3 Chart.pr @@ -4850,16 +4850,18 @@ me)%0A +d3 Chart%5Bna
69ba5a4616081d4c0808130b972df9e550084ecb
Revert event publish
app/assets/javascripts/modules/show-hide-content.js
app/assets/javascripts/modules/show-hide-content.js
; (function(global) { 'use strict' var $ = global.jQuery var GOVUK = global.GOVUK || {} function ShowHideContent() { var self = this // Radio and Checkbox selectors var selectors = { namespace: 'ShowHideContent', radio: '[data-target] > input[type="radio"]', checkbox: '[data-target] > input[type="checkbox"]' } // Escape name attribute for use in DOM selector function escapeElementName(str) { var result = str.replace(/\[/g, '\\[').replace(/\]/g, '\\]') return result } // Adds ARIA attributes to control + associated content function initToggledContent() { var $control = $(this) var $content = getToggledContent($control) // Set aria-controls and defaults if ($content.length) { $control.attr('aria-controls', $content.attr('id')) $control.attr('aria-expanded', 'false') $content.attr('aria-hidden', 'true') } } // Return toggled content for control function getToggledContent($control) { var id = $control.attr('aria-controls') // ARIA attributes aren't set before init if (!id) { id = $control.closest('[data-target]').data('target') } // Find show/hide content by id return $('#' + id) } // Show toggled content for control function showToggledContent($control, $content) { // Show content if ($content.hasClass('js-hidden')) { $content.removeClass('js-hidden') $content.attr('aria-hidden', 'false') // If the controlling input, update aria-expanded if ($control.attr('aria-controls')) { $control.attr('aria-expanded', 'true') } $.publish('/multiple-choice/content/show/', $content) } } // Hide toggled content for control function hideToggledContent($control, $content) { $content = $content || getToggledContent($control) // Hide content if (!$content.hasClass('js-hidden')) { $content.addClass('js-hidden') $content.attr('aria-hidden', 'true') // If the controlling input, update aria-expanded if ($control.attr('aria-controls')) { $control.attr('aria-expanded', 'false') } $.publish('/multiple-choice/content/hide/', $content) } } // Handle radio show/hide function handleRadioContent($control, $content) { // All radios in this group which control content var selector = selectors.radio + '[name=' + escapeElementName($control.attr('name')) + '][aria-controls]' var $form = $control.closest('form') var $radios = $form.length ? $form.find(selector) : $(selector) // Hide content for radios in group $radios.each(function() { hideToggledContent($(this)) }) // Select content for this control if ($control.is('[aria-controls]')) { showToggledContent($control, $content) } } // Handle checkbox show/hide function handleCheckboxContent($control, $content) { // Show checkbox content if ($control.is(':checked')) { showToggledContent($control, $content) } else { // Hide checkbox content hideToggledContent($control, $content) } } // Set up event handlers etc function init($container, elementSelector, eventSelectors, handler) { $container = $container || $(document.body) // Handle control clicks function deferred() { var $control = $(this) handler($control, getToggledContent($control)) } // Prepare ARIA attributes var $controls = $(elementSelector) $controls.each(initToggledContent) // Handle events $.each(eventSelectors, function(idx, eventSelector) { $container.on('click.' + selectors.namespace, eventSelector, deferred) }) // Any already :checked on init? if ($controls.is(':checked')) { $controls.filter(':checked').each(deferred) } } // Get event selectors for all radio groups function getEventSelectorsForRadioGroups() { var radioGroups = [] // Build an array of radio group selectors return $(selectors.radio).map(function() { var groupName = $(this).attr('name') if ($.inArray(groupName, radioGroups) === -1) { radioGroups.push(groupName) return 'input[type="radio"][name="' + $(this).attr('name') + '"]' } return null }) } // Set up radio show/hide content for container self.showHideRadioToggledContent = function($container) { init($container, selectors.radio, getEventSelectorsForRadioGroups(), handleRadioContent) } // Set up checkbox show/hide content for container self.showHideCheckboxToggledContent = function($container) { init($container, selectors.checkbox, [selectors.checkbox], handleCheckboxContent) } // Remove event handlers self.destroy = function($container) { $container = $container || $(document.body) $container.off('.' + selectors.namespace) } } ShowHideContent.prototype.init = function($container) { this.showHideRadioToggledContent($container) this.showHideCheckboxToggledContent($container) } GOVUK.ShowHideContent = ShowHideContent global.GOVUK = GOVUK })(window)
JavaScript
0
@@ -1699,70 +1699,8 @@ %7D%0A - $.publish('/multiple-choice/content/show/', $content)%0A @@ -2181,70 +2181,8 @@ %7D%0A - $.publish('/multiple-choice/content/hide/', $content)%0A
aa073df76997ebd6a956f65746c08f2002b52dde
Fix cache drop
techs/y-i18n-lang-js.js
techs/y-i18n-lang-js.js
/** * y-i18n-lang-js * ============== * * Собирает `?.lang.<язык>.js`-файлы на основе `i18n`-файлов. * * Используется для локализации в JS с помощью compact-tl + y-i18n-layer. * * **Опции** * * * *String* **target** — Результирующий таргет. По умолчанию — `?.lang.{lang}.js`. * * *String* **lang** — Язык, для которого небходимо собрать файл. * * **Пример** * * ```javascript * nodeConfig.addTechs([ * [require('enb-y-i18n/techs/y-i18n-lang-js'), {lang: '{lang}'}], * ]); * ``` */ var path = require('path'); var vow = require('vow'); var vowFs = require('enb/lib/fs/async-fs'); var asyncRequire = require('enb/lib/fs/async-require'); var dropRequireCache = require('enb/lib/fs/drop-require-cache'); var CompactTL = require('compact-tl').CompactTL; var yI18NLayer = require('../lib/y-i18n-layer'); module.exports = require('enb/lib/build-flow').create() .name('y-i18n-lang-js') .target('target', '?.lang.{lang}.js') .defineOption('i18nFile', '') .defineRequiredOption('lang') .useDirList('i18n') .needRebuild(function(cache) { this._i18nFile = this._i18nFile || path.resolve(__dirname, '../client/y-i18n.js'); return cache.needRebuildFile('i18n-file', this._i18nFile); }) .saveCache(function(cache) { cache.cacheFileInfo('i18n-file', this._i18nFile); }) .builder(function(langKeysetDirs) { var lang = this._lang; var compactTl = new CompactTL(); compactTl.use(yI18NLayer.create()); this._i18nClassData = ''; return vow.all([ vowFs.read(this._i18nFile, 'utf8'), mergeKeysets(lang, langKeysetDirs) ]).spread(function (i18nClassData, keysets) { this._i18nClassData = i18nClassData; var result = []; Object.keys(keysets).sort().forEach(function(keysetName) { var keyset = keysets[keysetName]; var keysetResult = []; keysetResult.push('i18n.add(\'' + keysetName + '\', {'); Object.keys(keyset).map(function(key, i, arr) { keysetResult.push( ' ' + JSON.stringify(key) + ': ' + compactTl.process(keyset[key]) + (i === arr.length - 1 ? '' : ',') ); }); keysetResult.push('});'); result.push(keysetResult.join('\n')); }); return this.getPrependJs(lang) + '\n' + result.join('\n\n') + '\n' + this.getAppendJs(lang); }.bind(this)); }) .methods({ getPrependJs: function(lang) { if (lang !== 'all') { return '(function(){\nfunction initKeyset(i18n) {\n' + 'if (!i18n || typeof i18n !== "function") {\n' + 'i18n = ' + this._i18nClassData + '\n' + '}\n\n'; } else { return ''; } }, getAppendJs: function(lang) { if (lang !== 'all') { var res = []; res.push('i18n.setLanguage(\'' + lang + '\');'); res.push('return i18n;'); res.push('}'); res.push('if (typeof modules !== \'undefined\') {'); res.push(' modules.define(\'y-i18n\', function (provide, i18n) {'); res.push(' provide(initKeyset(i18n));'); res.push(' });'); res.push('} else if (typeof module !== \'undefined\') {'); res.push(' module.exports = function() {return initKeyset();};'); res.push('} else if (typeof window !== \'undefined\') {'); res.push(' window.i18n = initKeyset();'); res.push('} else {'); res.push(' i18n = initKeyset();'); res.push('}'); res.push('})();'); return res.join('\n'); } else { return ''; } } }) .createTech(); function mergeKeysets(lang, keysetDirs) { var langJs = lang + '.js'; var langKeysetFiles = [].concat.apply([], keysetDirs.map(function (dir) { return dir.files; })).filter(function (fileInfo) { return fileInfo.name === langJs; }); var result = {}; return vow.all(langKeysetFiles.map(function (keysetFile) { dropRequireCache(keysetFile.fullname); return asyncRequire(keysetFile.fullname).then(function (keysets) { Object.keys(keysets).forEach(function (keysetName) { var keyset = keysets[keysetName]; result[keysetName] = (result[keysetName] || {}); Object.keys(keyset).forEach(function (keyName) { result[keysetName][keyName] = keyset[keyName]; }); }); }); })).then(function () { return result; }); }
JavaScript
0.000001
@@ -4452,16 +4452,25 @@ reCache( +require, keysetFi
c203f24d9af2fa2c5e9a46ffc61e5969f9989df2
use 10meter fog
js/components/render_engine.js
js/components/render_engine.js
/** * Create new RenderEngine. * * @param debug * @param vr * @constructor */ function RenderEngine(debug, vr) { var self = this; this.controls = []; this.createScene(); this.createCamera(); this.createRenderer(); this.addFloor(); if(vr && !debug) { this.addFog(); } if(debug) { this.logicalCenter = new THREE.AxisHelper(100); this.scene.add(this.logicalCenter); this.virtualCenter = new THREE.AxisHelper(50); this.virtualCenter.position.z = - RenderEngine.SENSOR_DISTANCE; this.virtualCenter.position.y = - RenderEngine.SENSOR_HEIGHT; this.scene.add(this.virtualCenter); } if(vr) { this.addVRControls(); this.createVREffect(); } else { this.addOrbitControls(); } function onWindowResize() { self.renderer.setSize(window.innerWidth, window.innerHeight); self.camera.aspect = window.innerWidth / window.innerHeight; self.camera.updateProjectionMatrix(); if(self.effect) { self.effect.setSize(window.innerWidth, window.innerHeight); } } window.addEventListener('resize', onWindowResize, false); this.enabled = true; window.addEventListener('keydown', function(event) { if (event.keyCode == 13) { // enter event.preventDefault(); self.enabled = !self.enabled; } }, true); SimpleEmitter.call(this); } RenderEngine.prototype = Object.create(SimpleEmitter.prototype); RenderEngine.SENSOR_HEIGHT = 160; RenderEngine.SENSOR_DISTANCE = 300; /** * Create Scene. */ RenderEngine.prototype.createScene = function(){ this.scene = new THREE.Scene(); }; /** * Create Camera. */ RenderEngine.prototype.createCamera = function(){ this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.001, 10000); this.camera.position.set(0, 0, 0); }; /** * Create Renderer. */ RenderEngine.prototype.createRenderer = function(){ this.renderer = new THREE.WebGLRenderer({ antialias: true }); this.renderer.setSize(window.innerWidth, window.innerHeight); $('body').prepend(this.renderer.domElement); }; /** * Add floor to scene. */ RenderEngine.prototype.addFloor = function(){ var geometry = new THREE.CircleGeometry(1500, 100); var material = new THREE.MeshBasicMaterial({ color: 0x222222 }); this.floor = new THREE.Mesh(geometry, material); this.floor.material.side = THREE.DoubleSide; this.floor.rotation.x = deg2rad(90); this.floor.position.y = -RenderEngine.SENSOR_HEIGHT; this.scene.add(this.floor); }; /** * Add fog to scene. */ RenderEngine.prototype.addFog = function(){ this.scene.fog = new THREE.Fog(0x222222, 0, RenderEngine.SENSOR_DISTANCE); }; /** * Add Orbit Controls. */ RenderEngine.prototype.addOrbitControls = function(){ var controls = new THREE.OrbitControls(this.camera); controls.target.set(0, -RenderEngine.SENSOR_HEIGHT, 0); controls.rotateUp(deg2rad(-70)); controls.rotateLeft(deg2rad(90)); controls.dollyOut(5); controls.panUp(150); this.controls.push(controls); }; /** * Add VR Controls. */ RenderEngine.prototype.addVRControls = function(){ var controls = new THREE.VRControls(this.camera); controls.scale = 100; // from meters to centimeters this.controls.push(controls); window.addEventListener('keydown', function(event) { if (event.keyCode == 32) { // space event.preventDefault(); controls.resetSensor(); } }, true); }; /** * Create VR Effect. */ RenderEngine.prototype.createVREffect = function(){ var self = this; this.effect = new THREE.VREffect(this.renderer); this.effect.setSize(window.innerWidth, window.innerHeight); document.body.addEventListener('dblclick', function() { self.effect.setFullScreen(true); }); }; /** * Render scene. */ RenderEngine.prototype.render = function(){ if(this.enabled) { if(this.effect) { this.effect.render(this.scene, this.camera); } else { this.renderer.render(this.scene, this.camera); } this.emit('render'); } }; /** * On update cycle. */ RenderEngine.prototype.update = function(){ requestAnimationFrame(this.update.bind(this)); this.controls.forEach(function(controls){ controls.update(); }); this.render(); }; /** * Start render loop. */ RenderEngine.prototype.start = function(){ this.update(); };
JavaScript
0.000003
@@ -2610,36 +2610,12 @@ 0, -RenderEngine.SENSOR_DISTANCE +1000 );%0A%7D
b1c0949f8cfe898f9f8f8128e83b7d5afebc0497
Convert tabs to spaces to be consistent with project
packages/nexrender-provider-s3/src/index.js
packages/nexrender-provider-s3/src/index.js
const fs = require('fs') const uri = require('amazon-s3-uri') const AWS = require('aws-sdk/global') const S3 = require('aws-sdk/clients/s3') let regions = {} let endpoints = {} /* return a credentials object if possible, otherwise return false */ const getCredentials = params => { if (params.profile) { // will throw if the profile is not configured return new AWS.SharedIniFileCredentials({ profile: params.profile }) } else if (params.accessKeyId && params.secretAccessKey) { return { accessKeyId: params.accessKeyId, secretAccessKey: params.secretAccessKey } } else if (process.env.AWS_PROFILE) { // prioritize any explicitly set params before env variables // will throw if the profile is not configured return new AWS.SharedIniFileCredentials({ profile: process.env.AWS_PROFILE }) } else if (process.env.AWS_ACCESS_KEY && process.env.AWS_SECRET_KEY) { return { accessKeyId: process.env.AWS_ACCESS_KEY, secretAccessKey: process.env.AWS_SECRET_KEY } } } /* create or get api instance with region */ const s3instanceWithRegion = (region, credentials) => { const key = region || 0 if (!regions.hasOwnProperty(key)) { const options = { region: region } if (credentials) options.credentials = credentials regions[key] = new S3(options) } return regions[key] } const s3instanceWithEndpoint = (endpoint, credentials) => { const key = endpoint || 0 if (!endpoints.hasOwnProperty(key)) { const options = { endpoint: endpoint } if (credentials) options.credentials = credentials endpoints[key] = new S3(options) } return endpoints[key] } /* define public methods */ const download = (job, settings, src, dest, params, type) => { src = src.replace('s3://', 'http://') if (src.indexOf('digitaloceanspaces.com') !== -1) { throw new Error('nexrender: Digital Ocean Spaces is not yet supported by the package: amazon-s3-uri') } const parsed = uri(src) const file = fs.createWriteStream(dest) if (!parsed.bucket) { return Promise.reject(new Error('S3 bucket not provided.')) } if (!parsed.key) { return Promise.reject(new Error('S3 key not provided.')) } return new Promise((resolve, reject) => { file.on('close', resolve); const awsParams = { Bucket: parsed.bucket, Key: parsed.key, } const credentials = getCredentials(params) const s3instance = params.endpoint ? s3instanceWithEndpoint(params.endpoint, credentials) : s3instanceWithRegion(params.region, credentials) s3instance .getObject(awsParams) .createReadStream() .on('error', reject) .pipe(file) }) } const upload = (job, settings, src, params, onProgress, onComplete) => { const file = fs.createReadStream(src); if (!params.endpoint && !params.region) { return Promise.reject(new Error('S3 region or endpoint not provided.')) } if (!params.bucket) { return Promise.reject(new Error('S3 bucket not provided.')) } if (!params.key) { return Promise.reject(new Error('S3 key not provided.')) } if (!params.acl) { return Promise.reject(new Error('S3 ACL not provided.')) } const onUploadProgress = (e) => { const progress = Math.ceil(e.loaded / e.total * 100) if (typeof onProgress == 'function') { onProgress(job, progress); } settings.logger.log(`[${job.uid}] action-upload: upload progress ${progress}%...`) } const onUploadComplete = (file) => { if (typeof onComplete == 'function') { onComplete(job, file); } settings.logger.log(`[${job.uid}] action-upload: upload complete: ${file}`) } const output = params.endpoint ? `${params.endpoint}/${params.bucket}/${params.key}` : `https://s3-${params.region}.amazonaws.com/${params.bucket}/${params.key}`; settings.logger.log(`[${job.uid}] action-upload: input file ${src}`) settings.logger.log(`[${job.uid}] action-upload: output file ${output}`) return new Promise((resolve, reject) => { file.on('error', (err) => reject(err)) const awsParams = { Bucket: params.bucket, Key: params.key, ACL: params.acl, Body: file, } if (params.metadata) awsParams.Metadata = params.metadata; const credentials = getCredentials(params) const s3instance = params.endpoint ? s3instanceWithEndpoint(params.endpoint, credentials) : s3instanceWithRegion(params.region, credentials) s3instance .upload(awsParams, (err, data) => { if (err) { reject(err) } else { onUploadComplete(data.Location) resolve() } }) .on('httpUploadProgress', onUploadProgress) }) } module.exports = { download, upload, } /* tests */ // download({}, {}, 's3://BUCKET.s3.REGION.amazonaws.com/KEY', 'test.txt') // download({}, {}, 's3://BUCKET.REGION.digitaloceanspaces.com/KEY', 'test.txt')
JavaScript
0.000097
@@ -1233,25 +1233,32 @@ : region %7D%0A%0A -%09 + if (credenti @@ -1551,17 +1551,24 @@ oint %7D%0A%0A -%09 + if (cred @@ -2448,17 +2448,24 @@ %7D%0A%0A -%09 + const cr @@ -4536,9 +4536,16 @@ a;%0A%0A -%09 + cons
ac9e006577f7f3318a37e5294a46e758a6c371ef
add loading bar
js/controllers/NewEmailCtrl.js
js/controllers/NewEmailCtrl.js
newsletterjs.controller('NewEmailCtrl', function($scope, database, $location, cfpLoadingBar){ var emaillists; $scope.getEmailLists = function(){ database.getEmailLists().then(function (data) { emaillists = data; var i = 0; for (i=0; i<emaillists.length; i++){ var emails = []; emails = emaillists[i].addresses; var toAdd = { name: emaillists[i].name, id: emaillists[i].id, emails: emails, selected: true }; $scope.listsToSelect.push(toAdd); } }, function (err) { console.log(err); }); }; $scope.getEmailLists(); $scope.listsToSelect = []; $scope.getAccounts = function(){ database.getAccounts().then(function (data) { $scope.accounts = data; $scope.selectedAccount = $scope.accounts[0]; $scope.transporter = nodemailer.createTransport({ service: 'Gmail', auth: { user: $scope.selectedAccount.address, pass: $scope.selectedAccount.password } }); console.log($scope.selectedAccount); console.log($scope.accounts); }, function (err) { console.log(err); }); }; $scope.getAccounts(); var nodemailer = require('nodemailer'); $scope.setAccount = function(){ $scope.transporter = nodemailer.createTransport({ service: 'Gmail', auth: { user: $scope.selectedAccount.address, pass: $scope.selectedAccount.password, } }); console.log($scope.selectedAccount.address); console.log($scope.selectedAccount.password); console.log($scope.transporter); }; $scope.email = {sent: false, dests: "", subject: "", content: ""}; $scope.saveEmail = function(){ $scope.email.sent = false; database.saveEmail($scope.email).then(function () { console.log($scope.email); $scope.email.dests = null; $scope.email.subject = null; $scope.email.content = null; toastr.success("Email saved"); }, function (err) { console.log(err); toastr.error("Email couldn't be saved"); }); }; $scope.sendEmail = function(){ cfpLoadingBar.start(); var recipients = ""; var i = 0; for (i=0; i<$scope.listsToSelect.length; i++){ if ($scope.listsToSelect[i].selected == true) { var j = 0; recipients += $scope.listsToSelect[i].emails.join(",") + ", "; } } console.log(recipients); $scope.email.subject += " "; var mailOptions = { from: $scope.selectedAccount.address , // sender address bcc: recipients, // list of receivers subject: $scope.email.subject, // Subject line text: $scope.email.content, // plaintext body html: $scope.email.content // html body }; console.log(mailOptions.subject); $scope.transporter.sendMail(mailOptions, function(error, info){ if (error){ console.log(error); toastr.error("Email couldn't be sent"); cfpLoadingBar.complete(); }else{ console.log('Email sent: ' + info.response); $scope.email.sent = true; cfpLoadingBar.complete(); toastr.success("Email sent"); database.saveEmail($scope.email).then(function () { console.log($scope.email); $scope.email.dests = null; $scope.email.subject = null; $scope.email.content = null; }, function (err) { console.log(err); }); } }); }; });
JavaScript
0.000001
@@ -2272,15 +2272,85 @@ ,%22) -+ %22, %22; +;%0A%09%09%09%09if (i!=$scope.listsToSelect.length - 1)%7B%0A%09%09%09%09%09recipients += %22, %22;%0A%09%09%09%09%7D %0A%09%09%09
f4d79cf2e7924ef1dd294e8c37ce54bfc2a73d02
Add pagination logic, cleanup re-org code
js/controllers/catalog-ctrl.js
js/controllers/catalog-ctrl.js
catalogApp.controller('CatalogCtrl', ['$scope', 'assetService', function($scope, assetService) { $scope.assets = []; $scope.totalHits = 0; $scope.getAssets = function(data) { var promise = assetService.getAssets({ data: data }); promise.then(function(response) { var originalAssets = response.data.Data; originalAssets.forEach(function(asset, index) { asset.Item.Images.forEach(function(image, index) { if (image.Type === 1) { /* Add logic to massage data to pluck out right image size for displaying thumbs */ asset.Item.thumbImage = image.ImageId; } }); }); $scope.assets = originalAssets; $scope.totalHits = response.data.TotalHits; }, function(reason) { console.log(reason); }); }; $scope.getAssets(); }]);
JavaScript
0.000001
@@ -113,16 +113,118 @@ s = %5B%5D;%0A + $scope.currentPage = 0;%0A $scope.totalPages = 1;%0A $scope.pageNumbers = %5B%5D;%0A $scope.pageSize = 20;%0A $scope @@ -239,17 +239,16 @@ ts = 0;%0A -%0A $scope @@ -248,25 +248,53 @@ $scope. -getAssets +pageOffset = 0;%0A%0A var initPagination = funct @@ -297,20 +297,26 @@ unction( -data +totalPages ) %7B%0A @@ -324,172 +324,241 @@ ar p -romise = assetService.getAssets(%7B%0A data: data%0A %7D);%0A promise.then(function(response) %7B%0A var originalAssets = response.data. +ageNumbers = %5B%5D;%0A for (var i = 0; i %3C totalPages; i++) %7B%0A /* Add in the page number, offset it by 1 */%0A pageNumbers.push(i + 1);%0A %7D%0A return pageNumbers;%0A %7D;%0A%0A var parseAssets = function(asset Data -; +) %7B %0A - originalAssets +assetData .for @@ -589,26 +589,24 @@ ex) %7B%0A - asset.Item.I @@ -652,18 +652,16 @@ - if (imag @@ -672,26 +672,24 @@ pe === 1) %7B%0A - /* @@ -776,26 +776,24 @@ /%0A - - asset.Item.t @@ -828,201 +828,609 @@ + %7D%0A -%7D + %7D); %0A - %7D);%0A %7D);%0A $scope.assets = originalAssets;%0A $scope.totalHits = response.data.TotalHits;%0A %7D, function(reason) %7B%0A console.log(reason);%0A %7D);%0A %7D;%0A%0A $scope. +%7D);%0A return assetData;%0A %7D;%0A%0A var getAssets = function(data) %7B%0A var promise = assetService.getAssets(%7B%0A data: data%0A %7D);%0A promise.then(function(response) %7B%0A $scope.assets = parseAssets(response.data.Data);%0A $scope.totalHits = response.data.TotalHits;%0A $scope.totalPages = Math.ceil($scope.assets.length / $scope.pageSize);%0A $scope.pageNumbers = initPagination($scope.totalPages);%0A %7D, function(reason) %7B%0A console.log(reason);%0A %7D);%0A %7D;%0A%0A $scope.gotoPage = function(page) %7B%0A $scope.pageOffset = (page - 1) * $scope.pageSize;%0A %7D%0A%0A getA
c50233099ab5d5c5e8f79e3318af6e03e4ee65d7
add display:none to getStringWidth svg
packages/vx-text/src/util/getStringWidth.js
packages/vx-text/src/util/getStringWidth.js
import memoize from 'lodash/memoize'; const MEASUREMENT_ELEMENT_ID = '__react_svg_text_measurement_id'; function getStringWidth(str, style) { try { // Calculate length of each word to be used to determine number of words per line let textEl = document.getElementById(MEASUREMENT_ELEMENT_ID); if (!textEl) { const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.style.width = 0; svg.style.height = 0; textEl = document.createElementNS('http://www.w3.org/2000/svg', 'text'); textEl.setAttribute('id', MEASUREMENT_ELEMENT_ID); svg.appendChild(textEl); document.body.appendChild(svg); } Object.assign(textEl.style, style); textEl.textContent = str; return textEl.getComputedTextLength(); } catch (e) { return null; } } export default memoize(getStringWidth, (str, style) => `${str}_${JSON.stringify(style)}`);
JavaScript
0
@@ -448,24 +448,58 @@ height = 0;%0A + svg.style.display = 'none';%0A textEl
a68c16a334762b1084ed21bfbcc1d2ad48424e08
Save the time with tweets
claptrap.js
claptrap.js
const fs = require('fs'); const util = require('util'); const toml = require('toml'); const backoff = require('backoff'); const Twitter = require('twitter'); const sqlite3 = require('sqlite3'); const streamBackoff = backoff.exponential({ maxDelay: 60 * 1000 }); var dbCon = null; streamBackoff.failAfter(15); function makeError(err) { return new Error(util.format('twitter error %d: %d', err.code, err.message)); } function streamTweets(db, client) { client.stream('user', {}, (stream) => { console.log('streaming for user'); stream.on('data', function(event) { streamBackoff.reset(); var keys = Object.keys(event); if (keys.length == 1) { console.log('received object type %s', keys[0]); if (event.delete) { var sid = event.delete.status.status_id; console.log('deleting tweet %s', sid); db.run('DELETE FROM tweets WHERE tweet_id = ?', [sid], (err) => { if (err) console.error('error deleting tweet: %s', err); }) } } else if (event.event) { console.log('received event type %s', event.event); } else { console.log('received tweet ‘%s’', event.text); db.run('INSERT INTO tweets (tweet_id, user, body) VALUES (?, ?, ?)', [ event.tweet_id, event.user.screen_name, JSON.stringify(event) ], (err) => { if (err) { console.error('error saving tweet: %s', err); } }) } }); // stream.on('error', function(err) { // console.error(err); // streamBackoff.backoff(); // }); stream.on('end', function() { console.log('stream disconnected, reconnecting'); streamBackoff.backoff(); }); }) } function openDatabase(callback) { var db = new sqlite3.Database('tweets.db', function(err) { if (err) return callback(err); db.run('CREATE TABLE IF NOT EXISTS tweets (tweet_id INTEGER PRIMARY KEY, user VARCHAR, body VARCHAR)', (err) => { callback(err, db); }) }) } streamBackoff.on('backoff', function(number, delay) { console.log('will attempt to reconnect in %d ms', delay); }); streamBackoff.on('fail', function() { console.error('failed to reconnect, exiting'); if (dbCon != null) { dbCon.close(); } process.exit(3); }) fs.readFile('config.toml', (err, data) => { if (err) throw err; var str = data.toString('utf-8'); var config = toml.parse(str); var client = new Twitter({ consumer_key: config.app.key, consumer_secret: config.app.secret, access_token_key: config.user.token, access_token_secret: config.user.secret }); client.get('account/verify_credentials', {}, function(err, user) { if (err) throw makeError(err); console.log('logged in as %s', user.screen_name); openDatabase((err, db) => { if (err) throw err; dbCon = db; streamTweets(db, client); streamBackoff.on('ready', function() { streamTweets(db, client); }); }) }) })
JavaScript
0.000119
@@ -1180,24 +1180,71 @@ vent.text);%0A + var date = new Date(event.created_at);%0A db.r @@ -1282,16 +1282,27 @@ d, user, + timestamp, body) V @@ -1313,16 +1313,19 @@ S (?, ?, + ?, ?)', %5B%0A @@ -1373,16 +1373,46 @@ en_name, + date.toISOString(),%0A JSON.st @@ -2039,16 +2039,35 @@ VARCHAR, + timestamp VARCHAR, body VA
d1f625f70e81c3b94fc023fd29bdb400bb140570
Update copy files Fix the copy of the images
generators/app/index.js
generators/app/index.js
/** * @license * Copyright (c) 2016 The IBM Research Emergent Solutions authors. All rights reserved. * This code may only be used under the MIT style license found at https://ibmresearch.github.io/LICENSE.txt * The complete set of authors may be found at https://ibmresearch.github.io/AUTHORS.txt * The complete set of contributors may be found at https://ibmresearch.github.io/CONTRIBUTORS.txt */ 'use strict'; var yeoman = require('yeoman-generator'); module.exports = yeoman.Base.extend({ initializing: function() { // Yeoman replaces dashes with spaces. We want dashes. this.appname = this.appname.replace(/\s+/g, '-'); }, prompting: function() { var prompts = [ { name: 'applicationId', type: 'input', message: 'ID of the application', default: this.appname }, { name: 'applicationName', type: 'input', message: 'Name of the application', default: this.appname }, { name: 'applicationDescription', type: 'input', message: 'Brief description of the application' } ]; return this.prompt(prompts).then(function(props) { this.props = props; }.bind(this)); }, writing: function() { this.fs.copy( this.templatePath('_gitignore'), this.destinationPath('.gitignore') ); this.fs.copy( this.templatePath('.eslintrc.json'), this.destinationPath('.eslintrc.json') ); this.fs.copyTpl( this.templatePath() + '/**/!(_)*', this.destinationPath(), this.props ); }, install: function() { this.installDependencies(); } });
JavaScript
0.000101
@@ -1299,62 +1299,396 @@ th(' -_gitignore'),%0A this.destinationPath('.gitignore') +gulp-tasks/'),%0A this.destinationPath('gulp-tasks/')%0A );%0A%0A this.fs.copy(%0A this.templatePath('images/'),%0A this.destinationPath('images/')%0A );%0A%0A this.fs.copyTpl(%0A this.templatePath('src/'),%0A this.destinationPath('src/'),%0A this.props%0A );%0A%0A this.fs.copyTpl(%0A this.templatePath('test/'),%0A this.destinationPath('test/'),%0A this.props %0A @@ -1798,32 +1798,138 @@ .json')%0A );%0A%0A + this.fs.copy(%0A this.templatePath('_gitignore'),%0A this.destinationPath('.gitignore')%0A );%0A%0A this.fs.copy @@ -1967,11 +1967,8 @@ + '/ -**/ !(_)
2674f4874452d2fb50b5e0f898fd4706c3bdd9db
remove old props
packages/vx-tooltip/src/tooltips/Tooltip.js
packages/vx-tooltip/src/tooltips/Tooltip.js
import React from 'react'; import cx from 'classnames'; export default function Tooltip(props) { const { className, ...restProps } = props; return ( <div className={cx('vx-tooltip-portal', className)} style={{ position: 'absolute', top: props.top, left: props.left, backgroundColor: 'white', color: '#666666', padding: '.3rem .5rem', borderRadius: '3px', fontSize: '14px', boxShadow: '0 1px 2px rgba(33,33,33,0.2)', lineHeight: '1em', pointerEvents: 'none', ...restProps, }} > {props.children} </div> ); }
JavaScript
0.000001
@@ -258,58 +258,8 @@ e',%0A - top: props.top,%0A left: props.left,%0A
4db3cf771fe4adb39e049ca2b75fe00b6be74e6c
Clean up
js/timeline.js
js/timeline.js
function buildTimeline() { var binWidth = 12; var binNum = 1200 / binWidth; var binnedData = _.toArray(_.groupBy(data.maps, function(v, k) { var year = +v.date; var mod = year % binWidth; return year - mod; })); console.log(binnedData); // sortedData //This needs to be an array of arrays with the mapnumber somehow embedded in it var t = d3.select('.timeline') .append('svg') .style('border', '1px solid') .attr('width', '1200px') .attr('height', '100px') .attr('class', 'timeline--svg') .append('g'); var yScale = d3.scale.linear().domain([100, 0]).range([0,20]); var yAxis = d3.svg.axis().scale(yScale).orient('left'); var xScale = d3.scale.linear().range([0,1200]).domain([1600,1900]); var xAxis = d3.svg.axis() .scale(xScale) .orient('bottom') .ticks(binNum/10) .tickSize(5) .tickFormat(d3.format(".0f")); d3.select('.timeline--svg').append('g') .attr('class', 'x-axis') .call(xAxis); var bins = t.selectAll('g.bin') .data(binnedData) .enter().append('g') .attr('class', 'bin') .attr('transform', function(d, i) { return 'translate(' + xScale(+d[0].date) + ', 0)' }); bins.selectAll('.dot') .data(function(d) { console.log(d); return d }) .enter().append('circle') .attr('class', 'timeline--dot') .attr('r', 5) .attr('cx', binWidth/2) .attr('cy', function(d, i) { return i * 12; }) .style('fill', 'black'); }
JavaScript
0.000002
@@ -228,132 +228,8 @@ %7D)); -%0A console.log(binnedData);%0A // sortedData //This needs to be an array of arrays with the mapnumber somehow embedded in it%0A %0A @@ -1127,24 +1127,8 @@ d) %7B - console.log(d); ret
048e306a70cac09b3a320c5b786774a32d560b15
Add first tweet
bot/main.js
bot/main.js
const client = require('./api/twitter-api'); const logger = require('./utils/logger'); // Verify Authentication client.get('account/verify_credentials',{}) .then(() => { logger.info('Successfully Authenticated.'); }, err => { logger.error('Authentication failed: Invalid credentials.', {error: err}); process.exit(1); });
JavaScript
0.999999
@@ -351,8 +351,273 @@ %0A %7D); +%0A%0Avar tweet = 'Hello world %5CuD83C%5CuDF0F %5CnThis is posted via the twitter API.';%0Aclient.post('statuses/update', %7Bstatus: tweet%7D)%0A .then(() =%3E %7B%0A logger.info('Added a new tweet');%0A %7D, err =%3E %7B%0A logger.error('Error Tweeting', %7Berror: err%7D);%0A %7D);
87fc7d7b53c8527d78448694ec147670acc89e22
Add and improve defaults for project name variants in the prompts
generators/app/index.js
generators/app/index.js
/* eslint capitalized-comments: ["off"], comma-dangle: ["off"] */ /** * @fileOverview The main code for this generator. * * @author Andy Culbertson * * @requires NPM:yeoman-generator * @requires NPM:chalk * @requires NPM:yosay * @requires NPM:mkdirp */ 'use strict'; const Generator = require('yeoman-generator'); const chalk = require('chalk'); const yosay = require('yosay'); const mkdirp = require('mkdirp'); module.exports = class extends Generator { prompting() { // Have Yeoman greet the user. this.log(yosay( 'Welcome to the groovy ' + chalk.red('generator-python-cmd') + ' generator!' )); const prompts = [{ type: 'input', name: 'projectName', message: 'What is the project name?', }, { type: 'input', name: 'projectSlug', message: 'What is the project slug?', default: this.appname, }, { type: 'input', name: 'packageName', message: 'What is the package name?', }, { type: 'input', name: 'projectDesc', message: 'What is the project description?', }, { type: 'input', name: 'author', message: 'What is the author\'s name?', }, { type: 'input', name: 'authorEmail', message: 'What is the author\'s email address?', }, ]; return this.prompt(prompts).then(props => { // To access props later use this.props.someAnswer; this.props = props; }); } // Adapted from // https://github.com/yeoman/generator-webapp/blob/master/app/index.js writing() { this._writingGit(); this._writingScript(); this._writingConfig(); this._writingLib(); this._writingDocs(); this._writingTests(); this._writingSetup(); } _writingGit() { this.fs.copy( this.templatePath('gitignore'), this.destinationPath('.gitignore')); } _writingScript() { const templatePaths = ['app.py']; const options = {packageName: this.props.packageName}; this._copyTpls(templatePaths, options); } _writingConfig() { const dirPaths = ['config']; this._makeDirs(dirPaths); } _writingLib() { const templatePaths = [ 'cli.py', 'config.py', 'controller.py', '__init__.py', ]; const options = {}; this._copyPackageTpls(templatePaths, options); } _writingDocs() { const dirPaths = [ 'docs', ]; this._makeDirs(dirPaths); const templatePaths = [ 'LICENSE.md', 'README.md', ]; const options = {projectName: this.props.projectName, author: this.props.author, authorEmail: this.props.authorEmail}; this._copyTpls(templatePaths, options); } _writingTests() { const templatePaths = [ 'tests/context.py', 'tests/test.py', ]; const options = {packageName: this.props.packageName}; this._copyTpls(templatePaths, options); } _writingSetup() { const templatePaths = [ 'setup.py', 'requirements.txt', 'requirements-dev.txt', ]; const options = {packageName: this.props.packageName, projectName: this.props.projectName, projectDesc: this.props.projectDesc, author: this.props.author, authorEmail: this.props.authorEmail}; this._copyTpls(templatePaths, options); } _copyTpls(templatePaths, options) { var i; for (i = 0; i < templatePaths.length; i++) { var templatePath = templatePaths[i]; this.fs.copyTpl( this.templatePath(templatePath), this.destinationPath(templatePath), options ); } } _copyPackageTpls(templatePaths, options) { var i; for (i = 0; i < templatePaths.length; i++) { var templatePath = 'package/' + templatePaths[i]; var destinationPath = this.props.packageName + '/' + templatePaths[i]; this.fs.copyTpl( this.templatePath(templatePath), this.destinationPath(destinationPath), options ); } } _makeDirs(dirPaths) { var i; for (i = 0; i < dirPaths.length; i++) { var dirPath = this.destinationPath(dirPaths[i]); mkdirp.sync(dirPath, function (err) { if (err) { console.error(err); } }); } } install() { } };
JavaScript
0
@@ -740,39 +740,205 @@ project name?',%0A + // Title case the appname. Based on https://stackoverflow.com/a/196991.%0A default: this.appname.replace(/%5Cb%5Cw/g, function(txt)%7Breturn txt.toUpperCase();%7D),%0A %7D,%0A - %7B%0A type @@ -1046,16 +1046,35 @@ .appname +.replace(/ /g, '-') ,%0A %7D, @@ -1124,24 +1124,24 @@ ckageName',%0A - messag @@ -1164,32 +1164,79 @@ package name?',%0A + default: this.appname.replace(/ /g, ''),%0A %7D,%0A %7B%0A
fbc1155d7676818975362af86e8982b911bcb46f
Add evt.js
js/rolling_spider_helper.js
js/rolling_spider_helper.js
function RollingSpiderHelper() { this._manager = navigator.mozBluetooth; this.connected = false; this._characteristics = {}; this._counter = 1; } RollingSpiderHelper.prototype = { startScan: function StartScan(){ if(!this._adapter){ this._adapter = this._manager.defaultAdapter; } this._adapter.startLeScan([]).then(function onResolve(handle) { console.log('startScan resolve [' + JSON.stringify(handle) + ']'); this._leScanHandle = handle; this._leScanHandle.addEventListener('devicefound', this._onGattDeviceFound.bind(this)); return Promise.resolve(handle); }.bind(this), function onReject(reason) { console.log('startScan reject [' + JSON.stringify(reason) + ']'); return Promise.reject(reason); }.bind(this)); }, stopScan: function StopScan(){ this._adapter.stopLeScan(this._leScanHandle).then(function onResolve() { this._leScanHandle = null; console.log('stopScan resolve'); return Promise.resolve(); }.bind(this), function onReject(reason) { console.log('stopScan reject'); console.log(reason); return Promise.reject(reason); }.bind(this)); }, _onGattDeviceFound: function onGattDevceFound(evt){ if(evt.device.name.indexOf('RS_') === 0 && !this.connected){ this.connected = true; console.log('Rolling Spider FOUND!!!!!'); this._device = evt.device; this._gatt = this._device.gatt; this.connect(); this.stopScan(); } }, connect: function Connect(){ this._gatt.connect().then(function onResolve() { console.log('connect resolve'); this.discoverServices(); }.bind(this), function onReject(reason) { console.log('connect reject: ' + reason); }.bind(this)); }, takeOff: function TakeOff(){ var characteristic = this._characteristics['9a66fa0b-0800-9191-11e4-012d1540cb8e']; // 4, (byte)mSettingsCounter, 2, 0, 1, 0 var buffer = new ArrayBuffer(6); var array = new Uint8Array(buffer); array.set([4, this._counter++, 2, 0, 1, 0]); characteristic.writeValue(buffer).then(function onResolve(){ console.log('takeoff success'); }, function onReject(){ console.log('takeoff failed'); }); }, landing: function Landing(){ var characteristic = this._characteristics['9a66fa0b-0800-9191-11e4-012d1540cb8e']; // 4, (byte)mSettingsCounter, 2, 0, 3, 0 var buffer = new ArrayBuffer(6); var array = new Uint8Array(buffer); array.set([4, this._counter++, 2, 0, 3, 0]); characteristic.writeValue(buffer).then(function onResolve(){ console.log('landing success'); }, function onReject(){ console.log('landing failed'); }); }, discoverServices: function DiscoverServices(){ return this._gatt.discoverServices().then(function onResolve(value) { this._gatt.oncharacteristicchanged = function onCharacteristicChanged(evt) { var characteristic = evt.characteristic; console.log("The value of characteristic (uuid:", characteristic.uuid, ") changed to", characteristic.value); }; console.log('gatt client discoverServices:' + 'resolved with value: [' +value + ']'); console.log('gatt client found ' + this._gatt.services.length + 'services in total'); var services = this._gatt.services; for(var i = 0; i<services.length; i++){ var characteristics = services[i].characteristics; console.log('service[' + i + ']' + characteristics.length + 'characteristics in total'); for(var j=0; j<characteristics.length; j++){ var characteristic = characteristics[j]; var uuid = characteristic.uuid; this._characteristics[uuid] = characteristic; //characteristic.startNotifications(); } } return Promise.resolve(value); }.bind(this), function onReject(reason) { console.log('discoverServices reject: [' + reason + ']'); return Promise.reject(reason); }.bind(this)); } };
JavaScript
0.000019
@@ -180,16 +180,20 @@ otype = +evt( %7B%0A star @@ -4070,11 +4070,12 @@ );%0A %7D%0A%7D +) ;%0A%0A
6621e6a28e44a456da9e478fe244f14950087cd0
add a check for repo before trying to use it
generators/git/index.js
generators/git/index.js
'use strict'; var generators = require('yeoman-generator'); var originUrl = require('git-remote-origin-url'); module.exports = generators.Base.extend({ constructor: function () { generators.Base.apply(this, arguments); this.option('generateInto', { type: String, required: false, defaults: '', desc: 'Relocate the location of the generated files.' }); this.option('name', { type: String, required: true, desc: 'Module name' }); this.option('github-account', { type: String, required: true, desc: 'GitHub username or organization' }); }, initializing: function () { this.fs.copy( this.templatePath('gitattributes'), this.destinationPath(this.options.generateInto, '.gitattributes') ); this.fs.copy( this.templatePath('gitignore'), this.destinationPath(this.options.generateInto, '.gitignore') ); var done = this.async(); originUrl(this.destinationPath(this.options.generateInto), function (err, url) { if (err) { url = url || ''; } this.originUrl = url; done(); }.bind(this)); }, writing: function () { this.pkg = this.fs.readJSON(this.destinationPath(this.options.generateInto, 'package.json'), {}); var repository = ''; if (this.originUrl) { repository = this.originUrl; } else { repository = this.options.githubAccount + '/' + this.options.name; } this.pkg.repository = this.pkg.repository || repository; this.fs.writeJSON(this.destinationPath(this.options.generateInto, 'package.json'), this.pkg); }, end: function () { this.spawnCommandSync('git', ['init'], { cwd: this.destinationPath(this.options.generateInto) }); if (!this.originUrl) { var repoSSH = this.pkg.repository; if (this.pkg.repository.indexOf('.git') === -1) { repoSSH = 'git@github.com:' + this.pkg.repository + '.git'; } this.spawnCommandSync('git', ['remote', 'add', 'origin', repoSSH], { cwd: this.destinationPath(this.options.generateInto) }); } } });
JavaScript
0
@@ -1865,16 +1865,39 @@ pository + && this.pkg.repository .indexOf
08cd96f076de56d96b8d6e1174a8d16c684747f3
revise QA credits, https://github.com/phetsims/graphing-quadratics/issues/155
js/graphing-quadratics-main.js
js/graphing-quadratics-main.js
// Copyright 2014-2021, University of Colorado Boulder /** * Main entry point for the 'Graphing Quadratics' sim. * * @author Andrea Lin * @author Chris Malley (PixelZoom, Inc.) */ import Sim from '../../joist/js/Sim.js'; import simLauncher from '../../joist/js/simLauncher.js'; import Tandem from '../../tandem/js/Tandem.js'; import ExploreScreen from './explore/ExploreScreen.js'; import FocusAndDirectrixScreen from './focusanddirectrix/FocusAndDirectrixScreen.js'; import graphingQuadraticsStrings from './graphingQuadraticsStrings.js'; import StandardFormScreen from './standardform/StandardFormScreen.js'; import VertexFormScreen from './vertexform/VertexFormScreen.js'; simLauncher.launch( () => { const screens = [ new ExploreScreen( Tandem.ROOT.createTandem( 'exploreScreen' ) ), new StandardFormScreen( Tandem.ROOT.createTandem( 'standardFormScreen' ) ), new VertexFormScreen( Tandem.ROOT.createTandem( 'vertexFormScreen' ) ), new FocusAndDirectrixScreen( Tandem.ROOT.createTandem( 'focusAndDirectrixScreen' ) ) ]; const options = { credits: { leadDesign: 'Amanda McGarry', softwareDevelopment: 'Chris Malley (PixelZoom, Inc.), Andrea Lin', team: 'Mike Dubson, Karina K. R. Hensberry, Trish Loeblein, Ariel Paul, Kathy Perkins', qualityAssurance: 'Jaspe Arias, Steele Dalton, Laura Rea, Jacob Romero, Nancy Salpepi, Ethan Ward, Kathryn Woessner, Kelly Wurtz' }, // phet-io options phetioDesigned: true }; const sim = new Sim( graphingQuadraticsStrings[ 'graphing-quadratics' ].title, screens, options ); sim.start(); } );
JavaScript
0
@@ -1342,33 +1342,91 @@ on, -Laura Rea, Jacob Romero, +Brooklyn Lash, Emily Miller, Laura Rea, Jacob Romero, ' +%0A ' Nanc
7348e71f194b46cc0d89f3f067f4a635a7cc899f
Add optional context argument
smoothscroll.js
smoothscroll.js
(function (root, smoothScroll) { 'use strict'; // Support RequireJS and CommonJS/NodeJS module formats. // Attach smoothScroll to the `window` when executed as a <script>. // RequireJS if (typeof define === 'function' && define.amd) { define(smoothScroll); // CommonJS } else if (typeof exports === 'object' && typeof module === 'object') { module.exports = smoothScroll(); } else { root.smoothScroll = smoothScroll(); } })(this, function(){ 'use strict'; // Do not initialize smoothScroll when running server side, handle it in client: if (typeof window !== 'object') return; // We do not want this script to be applied in browsers that do not support those // That means no smoothscroll on IE9 and below. if(document.querySelectorAll === void 0 || window.pageYOffset === void 0 || history.pushState === void 0) { return; } // Get the top position of an element in the document var getTop = function(element) { // return value of html.getBoundingClientRect().top ... IE : 0, other browsers : -pageYOffset if(element.nodeName === 'HTML') return -window.pageYOffset return element.getBoundingClientRect().top + window.pageYOffset; } // ease in out function thanks to: // http://blog.greweb.fr/2012/02/bezier-curve-based-easing-functions-from-concept-to-implementation/ var easeInOutCubic = function (t) { return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1 } // calculate the scroll position we should be in // given the start and end point of the scroll // the time elapsed from the beginning of the scroll // and the total duration of the scroll (default 500ms) var position = function(start, end, elapsed, duration) { if (elapsed > duration) return end; return start + (end - start) * easeInOutCubic(elapsed / duration); // <-- you can change the easing funtion there // return start + (end - start) * (elapsed / duration); // <-- this would give a linear scroll } // we use requestAnimationFrame to be called by the browser before every repaint // if the first argument is an element then scroll to the top of this element // if the first argument is numeric then scroll to this location // if the callback exist, it is called when the scrolling is finished var smoothScroll = function(el, duration, callback){ duration = duration || 500; var start = window.pageYOffset; if (typeof el === 'number') { var end = parseInt(el); } else { var end = getTop(el); } var clock = Date.now(); var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || function(fn){window.setTimeout(fn, 15);}; var step = function(){ var elapsed = Date.now() - clock; window.scroll(0, position(start, end, elapsed, duration)); if (elapsed > duration) { if (typeof callback === 'function') { callback(el); } } else { requestAnimationFrame(step); } } step(); } var linkHandler = function(ev) { ev.preventDefault(); if (location.hash !== this.hash) window.history.pushState(null, null, this.hash) // using the history api to solve issue #1 - back doesn't work // most browser don't update :target when the history api is used: // THIS IS A BUG FROM THE BROWSERS. // change the scrolling duration in this call smoothScroll(document.getElementById(this.hash.substring(1)), 500, function(el) { location.replace('#' + el.id) // this will cause the :target to be activated. }); } // We look for all the internal links in the documents and attach the smoothscroll function document.addEventListener("DOMContentLoaded", function () { var internal = document.querySelectorAll('a[href^="#"]:not([href="#"])'), a; for(var i=internal.length; a=internal[--i];){ a.addEventListener("click", linkHandler, false); } }); // return smoothscroll API return smoothScroll; });
JavaScript
0.999981
@@ -2214,16 +2214,83 @@ inished%0A +// if context is set then scroll that element, else scroll window %0A var smoo @@ -2331,16 +2331,25 @@ callback +, context )%7B%0A d @@ -2375,16 +2375,49 @@ %7C%7C 500;%0A + context = context %7C%7C window;%0A var @@ -2854,24 +2854,153 @@ ck;%0A +if (context != window) %7B%0A %09context.scrollTop = position(start, end, elapsed, duration);%0A %7D%0A else %7B%0A %09 window.scrol @@ -3046,16 +3046,27 @@ tion));%0A + %7D%0A%0A
5dc4cd4da92fb9ed683cb10c70bacc2054e4dba0
Use of $.extend was creating a new copy of $.mobile and that's a no-no
js/jquery.mobile.transition.js
js/jquery.mobile.transition.js
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); //>>description: Animated page change core logic and sequence handlers //>>label: Transition Core //>>group: Transitions //>>css.structure: ../css/structure/jquery.mobile.transition.css //>>css.theme: ../css/themes/default/jquery.mobile.theme.css define( [ "jquery", "./jquery.mobile.core" ], function( $ ) { //>>excludeEnd("jqmBuildExclude"); (function( $, window, undefined ) { var createHandler = function( sequential ){ // Default to sequential if( sequential === undefined ){ sequential = true; } return function( name, reverse, $to, $from ) { var deferred = new $.Deferred(), reverseClass = reverse ? " reverse" : "", active = $.mobile.urlHistory.getActive(), toScroll = active.lastScroll || $.mobile.defaultHomeScroll, screenHeight = $.mobile.getScreenHeight(), maxTransitionOverride = $.mobile.maxTransitionWidth !== false && $( window ).width() > $.mobile.maxTransitionWidth, none = !$.support.cssTransitions || maxTransitionOverride || !name || name === "none" || Math.max( $( window ).scrollTop(), toScroll ) > $.mobile.getMaxScrollForTransition(), toPreClass = " ui-page-pre-in", toggleViewportClass = function(){ $.mobile.pageContainer.toggleClass( "ui-mobile-viewport-transitioning viewport-" + name ); }, scrollPage = function(){ // By using scrollTo instead of silentScroll, we can keep things better in order // Just to be precautios, disable scrollstart listening like silentScroll would $.event.special.scrollstart.enabled = false; window.scrollTo( 0, toScroll ); // reenable scrollstart listening like silentScroll would setTimeout(function() { $.event.special.scrollstart.enabled = true; }, 150 ); }, cleanFrom = function(){ $from .removeClass( $.mobile.activePageClass + " out in reverse " + name ) .height( "" ); }, startOut = function(){ // if it's not sequential, call the doneOut transition to start the TO page animating in simultaneously if( !sequential ){ doneOut(); } else { $from.animationComplete( doneOut ); } // Set the from page's height and start it transitioning out // Note: setting an explicit height helps eliminate tiling in the transitions $from .height( screenHeight + $(window ).scrollTop() ) .addClass( name + " out" + reverseClass ); }, doneOut = function() { if ( $from && sequential ) { cleanFrom(); } startIn(); }, startIn = function(){ // Prevent flickering in phonegap container: see comments at #4024 regarding iOS $to.css("z-index", -10); $to.addClass( $.mobile.activePageClass + toPreClass ); // Send focus to page as it is now display: block $.mobile.focusPage( $to ); // Set to page height $to.height( screenHeight + toScroll ); scrollPage(); // Restores visibility of the new page: added together with $to.css("z-index", -10); $to.css("z-index", ""); if( !none ){ $to.animationComplete( doneIn ); } $to .removeClass( toPreClass ) .addClass( name + " in" + reverseClass ); if( none ){ doneIn(); } }, doneIn = function() { if ( !sequential ) { if( $from ){ cleanFrom(); } } $to .removeClass( "out in reverse " + name ) .height( "" ); toggleViewportClass(); // In some browsers (iOS5), 3D transitions block the ability to scroll to the desired location during transition // This ensures we jump to that spot after the fact, if we aren't there already. if( $( window ).scrollTop() !== toScroll ){ scrollPage(); } deferred.resolve( name, reverse, $to, $from, true ); }; toggleViewportClass(); if ( $from && !none ) { startOut(); } else { doneOut(); } return deferred.promise(); }; }; // generate the handlers from the above var sequentialHandler = createHandler(), simultaneousHandler = createHandler( false ); // Make our transition handler the public default. $.mobile.defaultTransitionHandler = sequentialHandler; //transition handler dictionary for 3rd party transitions $.mobile.transitionHandlers = { "default": $.mobile.defaultTransitionHandler, "sequential": sequentialHandler, "simultaneous": simultaneousHandler }; $.mobile.transitionFallbacks = {}; // If transition is defined, check if css 3D transforms are supported, and if not, if a fallback is specified $.mobile._maybeDegradeTransition = function( transition ) { if( transition && !$.support.cssTransform3d && $.mobile.transitionFallbacks[ transition ] ){ transition = $.mobile.transitionFallbacks[ transition ]; } return transition; }; $.mobile = $.extend( {}, { getMaxScrollForTransition: function() { return $.mobile.getScreenHeight() * 3; } }, $.mobile ); })( jQuery, this ); //>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); }); //>>excludeEnd("jqmBuildExclude");
JavaScript
0.000023
@@ -4008,16 +4008,110 @@ false ) +,%0A%09defaultGetMaxScrollForTransition = function() %7B%0A%09%09return $.mobile.getScreenHeight() * 3;%0A%09%7D ;%0A%0A// Ma @@ -4819,136 +4819,201 @@ %7D;%0A%0A -$.mobile = $.extend( %7B%7D, %7B%0A%09getMaxScrollForTransition: function() %7B%0A%09%09return $.mobile.getScreenHeight() * 3;%0A%09%7D%0A%7D, $.mobile );%0A +// Set the getMaxScrollForTransition to default if no implementation was set by user%0A$.mobile.getMaxScrollForTransition = $.mobile.getMaxScrollForTransition %7C%7C defaultGetMaxScrollForTransition; %0A%7D)(