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
f77a03c1804c46205045c8a8929f6fba8f9c510a
fix bug with valueLiteral
type-checker/lib/is-same-type.js
type-checker/lib/is-same-type.js
'use strict'; var assert = require('assert'); module.exports = isSameType; /*eslint complexity: 0, max-statements: [2,80]*/ function isSameType(left, right) { if (left === right) { return true; } if ( (right && left === null) || (left && right === null) ) { return false; } if (left.type !== right.type) { // console.log('EARLY BAIL'); return false; } var i = 0; if (left.type === 'typeLiteral') { if (left.name !== right.name) { // console.log('LITERAL MISMATCH'); return false; } return true; } else if (left.type === 'object') { if (left.keyValues.length !== right.keyValues.length) { // console.log('OBJECT KEYS'); return false; } for (i = 0; i < left.keyValues.length; i++) { var l = left.keyValues[i]; var r = right.keyValues[i]; if (l.key !== r.key) { // console.log('WEIRD KEYS'); return false; } if (!isSameType(l.value, r.value)) { return false; } } return true; } else if (left.type === 'genericLiteral') { if (!isSameType(left.value, right.value)) { return false; } if (left.generics.length !== right.generics.length) { // console.log('GENERICS KEYS'); return false; } for (i = 0; i < left.generics.length; i++) { if (!isSameType(left.generics[i], right.generics[i])) { return false; } } return true; } else if (left.type === 'unionType') { if (left.unions.length !== right.unions.length) { // console.log('UNIONS WEIRD'); return false; } // TODO: order-ness... for (i = 0; i < left.unions.length; i++) { if (!isSameType(left.unions[i], right.unions[i])) { return false; } } return true; } else if (left.type === 'intersectionType') { if (left.intersections.length !== right.intersections.length) { return false; } // TODO: order-ness for (i = 0; i < left.intersections.length; i++) { if (!isSameType( left.intersections[i], right.intersections[i] )) { return false; } } return true; } else if (left.type === 'valueLiteral') { if (left.name !== right.name) { // console.log('VALUE WEIRD'); return false; } return true; } else if (left.type === 'function') { if (left.args.length !== right.args.length) { // console.log('ARGS WEIRD'); return false; } for (i = 0; i < left.args.length; i++) { if (!isSameType(left.args[i], right.args[i])) { return false; } } if (!isSameType(left.thisArg, right.thisArg)) { return false; } if (!isSameType(left.result, right.result)) { return false; } return true; } else if (left.type === 'param') { // left.name, names can be different if (!isSameType(left.value, right.value)) { return false; } // Optional must be same if (left.optional !== right.optional) { return false; } return true; } else if (left.type === 'tuple') { if (left.values.length !== right.values.length) { return false; } for (i = 0; i < left.values.length; i++) { if (!isSameType(left.values[i], right.values[i])) { return false; } } return true; } else { assert(false, 'isSameType unexpected type: ' + left.type); } }
JavaScript
0.000025
@@ -2568,35 +2568,36 @@ if (left. -nam +valu e !== right.name @@ -2584,35 +2584,36 @@ value !== right. -nam +valu e) %7B%0A
b2da18c9418330c678d8af8d13cf096d38c05675
fix #2 -- speak function must return something
tests/app/functions.js
tests/app/functions.js
define([ 'use!underscore' ], function(_) { describe("functions", function() { var sayIt = function(greeting, name, punctuation) { return greeting + ', ' + name + (punctuation || '!'); }, fn = function() {}; it("you should be able to use an array as arguments when calling a function", function() { var result = fn([ 'Hello', 'Ellie', '!' ]); expect(result).to.be('Hello, Ellie!'); }); it("you should be able to change the context in which a function is called", function() { var speak = function() { sayIt(this.greeting, this.name, '!!!'); }, obj = { greeting : 'Hello', name : 'Rebecca' }; // define a function for fn that calls the speak function such that the // following test will pass expect(fn()).to.be('Hello, Rebecca!'); }); it("you should be able to return a function from a function", function() { // define a function for fn so that the following will pass expect(fn('Hello')('world')).to.be('Hello, world'); }); it("you should be able to create a 'partial' function", function() { // define a function for fn so that the following will pass var partial = fn(sayIt, 'Hello', 'Ellie'); expect(partial('!!!')).to.be('Hello, Ellie!!!'); }); }); });
JavaScript
0.000001
@@ -569,16 +569,23 @@ +return sayIt(th
8cdcf935e9986c93bbe3b94095ac569fd3a09eca
Support undefined as compareFn for live lists
lib/_proto/object-ordered-list.js
lib/_proto/object-ordered-list.js
'use strict'; var copy = require('es5-ext/lib/Array/prototype/copy') , isCopy = require('es5-ext/lib/Array/prototype/is-copy') , remove = require('es5-ext/lib/Array/prototype/remove') , CustomError = require('es5-ext/lib/Error/custom') , callable = require('es5-ext/lib/Object/valid-callable') , d = require('es5-ext/lib/Object/descriptor') , extend = require('es5-ext/lib/Object/extend') , once = require('next-tick/lib/once') , ee = require('event-emitter/lib/core') , memoize = require('memoizee/lib/regular') , ObjectSet = require('./object-set') , pop = Array.prototype.pop, push = Array.prototype.push , sort = Array.prototype.sort , call = Function.prototype.call , defineProperty = Object.defineProperty , defineProperties = Object.defineProperties , ObjectList, proto; require('memoizee/lib/ext/method'); var readOnly = function () { throw new CustomError("Array is read-only", 'ARRAY_READ_ONLY'); }; module.exports = ObjectList = function (set, compareFn) { var list = set.values; list.__proto__ = proto; compareFn = compareFn.bind(set.obj); sort.call(list, compareFn); defineProperties(list, { obj: d(set), compareFn: d(compareFn), _history: d('w', copy.call(list)) }); set.on('add', list._onAdd); set.on('delete', list._onDelete); return list; }; ObjectList.prototype = proto = ee(Object.create(Array.prototype, extend({ constructor: d(ObjectList), _isLiveList_: d(true), pop: d(readOnly), push: d(readOnly), reverse: d(readOnly), shift: d(readOnly), sort: d(readOnly), splice: d(readOnly), unshift: d(readOnly), getReverse: d(function () { return copy.call(this).reverse(); }), _sort: d.gs(function () { defineProperty(this, '_sort', d(once(this.__sort))); return this._sort; }), }, memoize(function (cb/*, thisArg*/) { var list, thisArg = arguments[1]; cb = memoize(callable(cb), { length: 1 }); list = this.map(cb, thisArg); list.__proto__ = proto; this.on('change', function () { var l; this.forEach(function (el, i) { list[i] = call.call(cb, thisArg, el); }); l = this.length; while (list.hasOwnProperty(l)) pop.call(list); list.emit('change'); }); return list; }, { method: 'liveMap', length: 2 }), d.binder({ _onAdd: d(function (obj) { push.call(this, obj); this._sort(); }), _onDelete: d(function (obj) { remove.call(this, obj); this._sort(); }), __sort: d(function () { sort.call(this, this.compareFn); if (isCopy.call(this, this._history)) return this; this._history = copy.call(this); this.emit('change'); return this; }), })))); defineProperty(ObjectList, 'defineOn', d(function (set) { defineProperties(set, memoize(function (compareFn) { return new ObjectList(this, callable(compareFn)); }, { method: 'list', protoDeep: true })); })); ObjectList.defineOn(ObjectSet.prototype);
JavaScript
0
@@ -863,16 +863,55 @@ proto;%0A%0A +require('memoizee/lib/ext/resolvers');%0A require( @@ -1156,16 +1156,29 @@ pareFn = + compareFn && compare @@ -2809,25 +2809,16 @@ t(this, -callable( compareF @@ -2819,17 +2819,16 @@ mpareFn) -) ;%0A%09%7D, %7B @@ -2858,16 +2858,120 @@ ep: true +, resolvers: %5Bfunction (compareFn) %7B%0A%09%09return (compareFn == null) ? undefined : callable(compareFn);%0A%09%7D%5D %7D));%0A%7D)
9971328a9b7ec8369fd61ee580ac37761fca8233
Update Game.js
javascripts/Game.js
javascripts/Game.js
var things; function Movable(id, x, y) { this.currentX = x; this.currentY = y; this.id = id; this.htmlObj = document.getElementById(id); this.htmlObj.style.left = (this.currentX + "px"); this.htmlObj.style.top = (this.currentY + "px"); // console.log('Movable() id=' + id + ' currentX = ' + this.currentX + "px currentX =" + this.currentY + "px"); } Movable.prototype.move = function(x, y) { destX = destX + x; destY = destY + y; } Movable.prototype.MoveUp = function(x, y) { move(this.destX, this.destY - 10); } Movable.prototype.MoveDown = function(x, y) { move(this.destX, this.destY + 10); } Movable.prototype.MoveLeft = function(x, y) { move(this.destX - 10, this.destY); } Movable.prototype.MoveRight = function(x, y) { move(this.destX + 10, this.destY); } Movable.prototype.InitialScale = function() { console.log('in InitialScale()'); console.log('In InitialScale(). this.htmlObj.style.width=' + this.htmlObj.style.width + ' id=' /*+ this.id*/); // this.htmlObj = document.getElementById(id); // this.htmlObj.style.width = (this.currentX + "px"); } function ScaleObjects() { console.log('in ScaleObjects()'); for (var thisThing in things) { thisThing.InitialScale(); } console.log('Done ScaleObjects()'); } function GameInitilize2(e) { console.log('in GameInitialize2()'); dad = new Movable("Dad", 3, 5); mom = new Movable("Mom", 5, 59); jordan = new Movable("Jordan", 40, 20); house = new Movable("House", 60, 5); candyhouse = new Movable("CandyHouse", 60, 75); // console.log('Finished GameInitialize2()'); things = new Array(dad, mom, jordan, house, candyhouse); dad.InitialScale(); console.log('GameInitilize2: id=' + things[0].id); ScaleObjects(); } function GameInitilize(e) { // console.log('In GameInitialize()'); // window.document.onload = GameInitilize2; $(document).ready(GameInitilize2); } console.log('Running Game.js global code.'); GameInitilize();
JavaScript
0.000001
@@ -993,16 +993,72 @@ .id*/);%0A + console.log('In InitialScale(). DAD id=' + dad.id);%0A // this
f9ee2e57a242f867e3644883d0741f92d3f6c848
use explict variables, new version of applyValueFilter
value_sorting.js
value_sorting.js
$(document).ready(function(){ var dataTableView = findViewObject(this.getElementsByClassName("bk-data-table")[0], Bokeh.index[findModelID("8dc6e575-0ae6-4b64-bc54-a9ffe282b510")]) var dataSource = dataTableView.mget("source") var fields = getFieldNames(dataTableView.model.attributes.columns) $(".plotdiv").append("<form id='column-filters'><input type='submit'></form>") for (var i = 0; i < fields.length; i++){ var optionsString = optionsConstructor(dataSource, fields[i].field) $("form#column-filters").append("<span>"+fields[i].title+"</span><select name=" + fields[i].field + ">"+ optionsString+"</select>") } $("form#column-filters").submit(function(e){ e.preventDefault(); var options = $(e.target).find("select"); var workingFilters = []; for(var i = 0; i < options.length; i++){ if(options[i].type !== 'submit' && options[i].selectedOptions[0].value !== ""){ workingFilters.push({name: options[i].name, value: options[i].selectedOptions[0].value}) } } var rowsToSelect = valueFilter(workingFilters, dataSource) dataTableView.grid.setSelectedRows(rowsToSelect) selectionShift(dataTableView) }) }) var valueFilter = function(workingFilters, dataSource){ var rowIndices = [] for(var i = 0; i < workingFilters.length; i++){ var column = dataSource.attributes.data[workingFilters[i].name] for(var j = 0; j < column.length; j++){ if(column[j] === workingFilters[i].value){ rowIndices.push(j) } } } return getUniqueElements(rowIndices) } var getFieldNames = function(columns){ var result = [] for(var i = 0; i < columns.length; i++){ var columnData = Bokeh.Collections("TableColumn").get(columns[i].id) result.push({field : columnData.attributes.field, title : columnData.attributes.title}) } return result } var optionsConstructor = function(source, fieldName){ var result = "<option value=''></option>"; var elements = getUniqueElements(source.attributes.data[fieldName]) for(var i = 0; i < elements.length; i++){ result += "<option value="+ elements[i] +">" + elements[i] + "</option>" } return result } var getUniqueElements = function(array){ var u = {}, a = []; for(var i = 0; i < array.length; ++i){ if(u.hasOwnProperty(array[i])) { continue; } a.push(array[i]); u[array[i]] = 1; } return a; }
JavaScript
0
@@ -1014,24 +1014,90 @@ %7D%0A %7D%0A +%0A%0A var columns = dataSource.attributes.data%0A%0A var rows = %5B%5D%0A var rows @@ -1107,17 +1107,22 @@ elect = -v +applyV alueFilt @@ -1140,27 +1140,31 @@ ilters, -dataSource) +columns, rows)%0A %0A dat
bd171b3b8ffadaa2ad3f7a679d74b02c2df87ca0
update tests for navigation
example/test/e2e/navigation.spec.js
example/test/e2e/navigation.spec.js
'use strict'; describe('Scenario: User navigates the application.', function () { it('should be the correct scope by route /', function() { browser.get('/'); var view = element(by.binding('view')); var thingList = element.all(by.repeater('thing in awesomeThings')); expect(thingList.count()).toEqual(4); expect(view.getText()).toEqual('app/main/home/home.html'); }); it('should be the correct scope by route /home', function() { browser.get('/home'); var view = element(by.binding('view')); var thingList = element.all(by.repeater('thing in awesomeThings')); expect(thingList.count()).toEqual(4); expect(view.getText()).toEqual('app/main/home/home.html'); }); it('should be the correct scope by route /about', function() { browser.get('/about'); var view = element(by.binding('view')); var thingList = element.all(by.repeater('thing in awesomeThings')); expect(thingList.count()).toEqual(4); expect(view.getText()).toEqual('app/main/about/about.html'); }); it('should be the correct scope by route /contact', function() { browser.get('/contact'); var view = element(by.binding('view')); var thingList = element.all(by.repeater('thing in awesomeThings')); expect(thingList.count()).toEqual(4); expect(view.getText()).toEqual('app/main/contact/contact.html'); }); it('should be the correct scope by route /admin', function() { browser.get('/admin'); var view = element(by.binding('view')); var thingList = element.all(by.repeater('thing in awesomeThings')); expect(thingList.count()).toEqual(4); expect(view.getText()).toEqual('app/admin/admin.html'); }); });
JavaScript
0.000001
@@ -325,33 +325,33 @@ ount()).toEqual( -4 +5 );%0A expec @@ -669,33 +669,33 @@ ount()).toEqual( -4 +5 );%0A expec @@ -1015,33 +1015,33 @@ ount()).toEqual( -4 +5 );%0A expec @@ -1367,33 +1367,33 @@ ount()).toEqual( -4 +5 );%0A expec @@ -1731,9 +1731,9 @@ ual( -4 +5 );%0A
0d009eba139ea80aa4c8c8e4260b700597b97008
Fix lint errors
src/objectify.js
src/objectify.js
(function objectify(window) { function Objectify(form, exclusions, sanitize) { this.form = form; this.exclusions = exclusions; this.sanitize = sanitize; this.obj = {}; this.currentElement; return this.getValues(); } Objectify.prototype.getValues = function getValues() { var elements = this.form.elements; var count = elements.length; var i = 0; for (i; i < count; i++) { this.currentElement = elements[i]; if (this.exclusions.indexOf(this.currentElement.name) > -1 ) { continue; } switch(this.currentElement.tagName) { case 'BUTTON': case 'FIELDSET': continue; break; case 'INPUT': switch(this.currentElement.type) { case 'button': case 'submit': case 'reset': continue; break; case 'checkbox': case 'radio': this.setCheckValues(); break; default: this.setValue(); break; } break; case 'SELECT': switch (this.currentElement.type) { case 'select-multiple': this.setMultipleValues(); break; default: this.setValue(); break; } break; default: this.setValue(); break; } } return this.obj; }; Objectify.prototype.setValue = function setValue() { if (!this.hasKey()) { this.obj[this.currentElement.name] = this.getSanitizedValue(); } }; Objectify.prototype.setCheckValues = function setCheckValues() { if (this.currentElement.checked) { if (this.obj.hasOwnProperty(this.currentElement.name)) { return this.obj[this.currentElement.name].push(this.getSanitizedValue()); } this.obj[this.currentElement.name] = this.currentElement.type === 'radio' ? this.getSanitizedValue() : [this.getSanitizedValue()]; } }; Objectify.prototype.setMultipleValues = function setMultipleValues() { var select = this.currentElement; var count = this.currentElement.options.length; var name = ''; var i = 0 if (!this.hasKey()) { name = this.currentElement.name; this.obj[name] = []; for(i; i < count; i++) { this.currentElement = select.options[i]; if (this.currentElement.selected) { this.obj[name].push(this.getSanitizedValue()); } } } }; Objectify.prototype.getSanitizedValue = function getSanitizedValue() { var name = this.currentElement.name; if (typeof this.sanitize[name] === 'function') { return this.sanitize[name](this.currentElement.value); } return this.currentElement.value; }; Objectify.prototype.hasKey = function hasKey() { if (this.obj.hasOwnProperty(this.currentElement.name)) { console.warn('Duplicate name attribute (' + this.currentElement.name + ') found in form. Value not saved.'); return true; } return false; }; function objectify(form, exclusions, sanitize) { if (typeof form !== 'object' && form.nodeName === undefined && form.nodeName !== 'FORM') { console.error('A form element was not passed as the first argument of objectify.'); return false; } exclusions = exclusions || []; sanitize = sanitize || {}; return new Objectify(form, exclusions, sanitize); } return window.objectify = objectify; }(window));
JavaScript
0.000396
@@ -661,33 +661,16 @@ ntinue;%0A - break;%0A @@ -832,37 +832,16 @@ ntinue;%0A - break;%0A
bc930b9b66dce7b25ddfab2a43fd29897039917a
Capital B
lib/dom/get-element-from-point.js
lib/dom/get-element-from-point.js
/* global dom */ /** * Returns true if the browser supports one of the methods to get elements from point * @param {Document} doc The HTML document * @return {boolean} */ dom.supportsElementsFromPoint = function (doc) { var element = doc.createElement('x'); element.style.cssText = 'pointer-events:auto'; return element.style.pointerEvents === 'auto' || !!doc.msElementsFromPoint; }; /** * Returns the elements at a particular point in the viewport, in z-index order * @param {Document} doc The HTML document * @param {Element} x The x coordinate, as an integer * @param {Element} y The y coordinate, as an integer * @return {Array} Array of Elements */ dom.elementsFromPoint = function (doc, x, y) { var elements = [], previousPointerEvents = [], current, i, d; if (doc.msElementsFromPoint) { var nl = doc.msElementsFromPoint(x, y); return nl ? Array.prototype.slice.call(nl) : null; } // get all elements via elementFromPoint, and remove them from hit-testing in order while ((current = doc.elementFromPoint(x, y)) && elements.indexOf(current) === -1 && current !== null) { // push the element and its current style elements.push(current); previousPointerEvents.push({ value: current.style.getPropertyValue('pointer-events'), priority: current.style.getPropertyPriority('pointer-events') }); // add "pointer-events: none", to get to the underlying element current.style.setProperty('pointer-events', 'none', 'important'); } // restore the previous pointer-events values for (i = previousPointerEvents.length; !!(d = previousPointerEvents[--i]);) { elements[i].style.setProperty('pointer-events', d.value ? d.value : '', d.priority); } // return our results return elements; };
JavaScript
0.999956
@@ -161,17 +161,16 @@ rn %7B -b +B oolean%7D - %0A */
3cfa38102ef495574d1fc6c6ac8321ac09e79fdf
fix coordinates order in generate prompt
lib/cli/generate.js
lib/cli/generate.js
var program = require('commander'); var prompt = require('prompt'); var url = require('url'); var fs = require('fs'); var path = require('path'); var template = require('lodash').template; var curl = require('./curl'); var dirs = require('./dirs'); var fname; var schema = [ { name: 'id', description: 'Short name of the resort [acme]', type: 'string', required: true }, { name: 'name', description: 'Human readable name of the resort [Acme Ski]', type: 'string', required: true }, { name: 'host', description: 'URL of the resort website [http://acme.com]', type: 'string', required: true }, { name: 'pathname', description: 'Relative URL of the page with lift status [/lift/status]', type: 'string', required: true }, { name: 'tags', description: 'Comma separated list of tags [Colorado, Vail, New Hampshire]', type: 'string', default: '' }, { name: 'twitter', description: 'Twitter handle (without @) [acme]', type: 'string' }, { name: 'coordinates', description: 'Resort location [latitude, longitude]', type: 'string', default: '' }, { name: 'opening', description: 'Opening date [YYYY-MM-DD]', type: 'string' } ]; program .option('-j, --json <file>', 'JSON file with resort data', String) .parse(process.argv); if (program.json) { fname = path.resolve(program.json); fs.readFile(fname, function (err, data) { var conf; if (err) { console.error(err); process.exit(-1); } conf = JSON.parse(data); conf.id = path.basename(fname, '.json'); if (conf.url) { conf.host = conf.url.host; conf.pathname = conf.url.pathname; if (conf.host && !conf.pathname) { console.log('Resort website:', conf.host); } } if (Array.isArray(conf.tags)) { conf.tags = conf.tags.join(','); } if (Array.isArray(conf.ll)) { conf.coordinates = conf.ll.join(','); } execute(conf); }); } else { execute(); } function generate(resort) { console.log('Generating files for %s', resort.name); var resortDir = path.join(dirs.lib, resort.id), json; fs.mkdirSync(resortDir); copy(path.join(dirs.templates, 'index.js'), path.join(resortDir, 'index.js'), resort); json = { name: resort.name, url: { host: resort.host, pathname: resort.pathname }, tags: resort.tags, ll: resort.coordinates }; if (resort.twitter) { json.twitter = resort.twitter; } if (resort.opening) { json.opening = resort.opening; } write(path.join(resortDir, 'resort.json'), json); copy(path.join(dirs.templates, 'test.js'), path.join(dirs.test, resort.id + '.js'), resort); curl(json.url, resort.id); } function write(dst, json) { console.log('Generating %s...', dst); fs.writeFileSync(dst, JSON.stringify(json, null, 2)); } function copy(src, dst, params) { console.log('Generating %s...', dst); fs.readFile(src, 'utf8', function(err, data) { data = template(data)(params); fs.writeFileSync(dst, data); }); } function execute(conf) { function splitHost(v) { var resortUrl = url.parse(v, true); if (resortUrl.pathname) { conf.pathname = resortUrl.pathname; } return url.format({ protocol: resortUrl.protocol, hostname: resortUrl.hostname }); } schema[2].before = splitHost; conf = conf || {}; prompt.override = conf; prompt.addProperties(conf, schema, function(err) { if (err) { console.error(err); process.exit(-1); } var resortUrl = url.parse(conf.host + conf.pathname); conf.tags = conf.tags.split(/\s*,\s*/); conf.coordinates = conf.coordinates.split(/\s*,\s*/).map(parseFloat); conf.host = [resortUrl.protocol, resortUrl.host].join('//'); conf.pathname = [resortUrl.pathname, resortUrl.search, resortUrl.hash].join(''); process.stdin.destroy(); generate(conf); }); }
JavaScript
0.999999
@@ -1109,18 +1109,19 @@ n %5Bl -at +ong itude, l ongi @@ -1116,19 +1116,18 @@ itude, l -ong +at itude%5D',
48c511a306e0637752caba2ba6b78b1c45937404
Update authentication redirection
js/auth.js
js/auth.js
_sub = false; function lsub() { if(_sub) return; _sub = true; errors = {}; try { updateErrors("#lform"); var email = $('input[name=l_email]').val(), password = $('input[name=l_password]').val(); validateEmail(email); validatePassword(password); // if no errors, submit to server if (jQuery.isEmptyObject(errors)) { dispWaiting('lsub'); var data = { 'email': email, 'password': password, 'op': 'l' }; $.ajax({ type: 'POST', url: 'auth.php', data: data, dataType: 'json', encode: true }).done(function(res) { if (res['success']) { window.location.href = './'; } stopWaiting('lsub'); errors = res['errors']; updateErrors("#lform"); _sub = false; }); } else { updateErrors("#lform"); _sub = false; } } catch (err) { console.log(err); _sub = false; } } function rsub() { if(_sub) return; _sub = true; errors = {}; try { updateErrors("#rform"); var nickname = $('input[name=nickname]').val(), email = $('input[name=email]').val(), password = $('input[name=password]').val(), fname = $('input[name=fname]').val(), lname = $('input[name=lname]').val(), gender = $("input[name=gender]:checked").val() mstatus = $("input[name=status]:checked").val(), bdate = $('input[name=bdate]').val(), country = $('#country').val(), city = $('input[name=city]').val(), pcode = $('input[name=pcode]').val(); validateNickname(nickname); validateEmail(email); validatePassword(password); // cross check password if (password != $('input[name=cpassword]').val()) { errors['pcerror'] = "Confirmation does not match password."; } // if no errors, submit to server if (jQuery.isEmptyObject(errors)) { dispWaiting('rsub'); var data = { 'nickname': nickname, 'email': email, 'password': password, 'fname': fname, 'lname': lname, 'gender': gender, 'mstatus': mstatus, 'bdate': bdate, 'country': country, 'city': city, 'pcode': pcode, 'op': 'r' }; $.ajax({ type: 'POST', url: 'auth.php', data: data, dataType: 'json', encode: true }).done(function(res) { if (res['success']) { window.location.href = 'index.php'; } stopWaiting('rsub'); errors = res['errors']; updateErrors("#rform"); _sub = false; }); } else { updateErrors("#rform"); _sub = false; } } catch (err) { console.log(err); _sub = false; } } function update_info() { if(_sub) return; _sub = true; errors = {}; try { updateErrors("#settings"); var nickname = $('input[name=nickname]').val(), email = $('input[name=email]').val(), password = $('input[name=password]').val(), gender = $("input[name=gender]:checked").val() mstatus = $("input[name=status]:checked").val(); about = $("#about-field").val(); validateNickname(nickname); validateEmail(email); validatePassword(password); // if no errors, submit to server if (jQuery.isEmptyObject(errors)) { var data = { 'nickname': nickname, 'email': email, 'password': password, 'gender': gender, 'mstatus': mstatus, 'about': about }; $.ajax({ type: 'POST', url: 'update.php', data: data, dataType: 'json', encode: true }).done(function(res) { if (res['success']) { window.location.reload(true); window.location.href = 'profile.php'; } errors = res['errors']; updateErrors("#settings"); _sub = false; }); } else { updateErrors("#settings"); _sub = false; } } catch (err) { console.log(err); _sub = false; } }
JavaScript
0.000001
@@ -3022,17 +3022,10 @@ = ' -index.php +./ ';%0A @@ -4607,20 +4607,16 @@ 'profile -.php ';%0A
8f416e0f1d1d21580b9507ff9edb8fa4a2bfb008
Make local storage work properly
lib/core/storage.js
lib/core/storage.js
// == BSD2 LICENSE == // Copyright (c) 2014, Tidepool Project // // This program is free software; you can redistribute it and/or modify it under // the terms of the associated License, which is identical to the BSD 2-Clause // License as published by the Open Source Initiative at opensource.org. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the License for more details. // // You should have received a copy of the License along with this program; if // not, you can obtain one from Tidepool Project at tidepool.org. // == BSD2 LICENSE == 'use strict'; var _ = require('lodash'); /** * Create our the store we will be using * * @param {Object} options * @param {Boolean} options.isChromeApp * @param {Object} options.ourStore the storage system we are using */ module.exports = function (options) { // Version that runs in browser if (options.isChromeApp === false && _.isEmpty(options.ourStore) === false) { return { init: function(data, cb) { var result = _.reduce(data, function(result, defaultValue, key) { var value = options.ourStore.getItem(key); if (value == null) { value = defaultValue; } result[key] = value; return result; }, {}); cb(result); }, getItem: options.ourStore.getItem.bind(options.ourStore), setItem: options.ourStore.setItem.bind(options.ourStore), removeItem: options.ourStore.removeItem.bind(options.ourStore) }; } var inMemoryStore = {}; // wrap chrome.storage.local instance so that it remains consistent with the defined interface // see http://dev.w3.org/html5/webstorage/#storage-0 return { init: function(data,cb){ options.ourStore.get(data, function (result) { inMemoryStore = result; return cb(result); }); }, getItem:function(key){ if(_.isEmpty(key)){ return; } return inMemoryStore[key]; }, setItem:function(key,data){ if(_.isEmpty(key)){ inMemoryStore = _.assign(inMemoryStore, data); options.ourStore.set(data); return; } inMemoryStore[key] = data; var payload = {}; payload[key] = data; options.ourStore.set(payload); }, removeItem:function(key){ delete inMemoryStore[key]; options.ourStore.remove(key); } }; };
JavaScript
0
@@ -1851,13 +1851,176 @@ ata, + cb) + %7B%0A + // first, make sure our input query is an object%0A var obj = data;%0A if (!_.isObject(data)) %7B%0A obj = %7B%7D;%0A obj%5Bdata%5D = null;%0A %7D%0A%0A @@ -2042,20 +2042,19 @@ ore.get( -data +obj , functi @@ -2079,30 +2079,242 @@ -inMemoryStore = +console.log('local storage init queried ', obj, ' got ', result);%0A // we may get initialized more than once, so make sure we don't blow away%0A // the old version of the memoryStore.%0A _.assign(inMemoryStore, result +) ;%0A
492344443dbfdbb19b67edec39d1938a8e12fabd
fix undefined d3 dependency
app/helpers.js
app/helpers.js
// 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. // This file creates a set of helper functions that will be loaded for all html // templates. These functions should be self contained and not rely on any // external dependencies as they are loaded prior to the application. We may // want to change this later, but for now this should be thought of as a // "purely functional" helper system. define([ "core/utils", "d3" ], function(utils) { var Helpers = {}; Helpers.removeSpecialCharacters = utils.removeSpecialCharacters; Helpers.safeURL = utils.safeURLName; Helpers.imageUrl = function(path) { // TODO: add dynamic path for different deploy targets return path; }; // Get the URL for documentation, wiki, wherever we store it. // update the URLs in documentation_urls.js Helpers.docs = { "docs": "http://docs.couchdb.org/en/latest/intro/api.html#documents", "all_dbs": "http://docs.couchdb.org/en/latest/api/server/common.html?highlight=all_dbs#get--_all_dbs", "replication_doc": "http://docs.couchdb.org/en/latest/replication/replicator.html#basics", "design_doc": "http://docs.couchdb.org/en/latest/couchapp/ddocs.html#design-docs", "view_functions": "http://docs.couchdb.org/en/latest/couchapp/ddocs.html#view-functions", "map_functions": "http://docs.couchdb.org/en/latest/couchapp/ddocs.html#map-functions", "reduce_functions": "http://docs.couchdb.org/en/latest/couchapp/ddocs.html#reduce-and-rereduce-functions", "api_reference": "http://docs.couchdb.org/en/latest/http-api.html", "database_permission": "http://docs.couchdb.org/en/latest/api/database/security.html#db-security", "stats": "http://docs.couchdb.org/en/latest/api/server/common.html?highlight=stats#get--_stats", "_active_tasks": "http://docs.couchdb.org/en/latest/api/server/common.html?highlight=stats#active-tasks", "log": "http://docs.couchdb.org/en/latest/api/server/common.html?highlight=stats#log", "config": "http://docs.couchdb.org/en/latest/config/index.html", "views": "http://docs.couchdb.org/en/latest/intro/overview.html#views", "changes": "http://docs.couchdb.org/en/latest/api/database/changes.html?highlight=changes#post--db-_changes" }; Helpers.getDocUrl = function(docKey){ return Helpers.docs[docKey] || '#'; }; // File size pretty printing, taken from futon.format.js Helpers.formatSize = function(size) { var jump = 512; if (size < jump) return size + " bytes"; var units = ["KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; var i = 0; while (size >= jump && i < units.length) { i += 1; size /= 1024; } return size.toFixed(1) + ' ' + units[i - 1]; }; Helpers.formatDate = function(timestamp){ var format = d3.time.format("%b. %e at %H:%M%p"); return format(new Date(timestamp*1000)); }; return Helpers; });
JavaScript
0
@@ -943,16 +943,20 @@ on(utils +, d3 ) %7B%0A%0A v
ec883c2d35ba061072fbf93bdc4e1261c2ef67ed
stop framehandler
lib/framehandler.js
lib/framehandler.js
var EventEmitter2 = require('eventemitter2').EventEmitter2 , util = require('util') , _ = require('lodash'); function FrameHandler(deviceOrFrameHandler) { var self = this; // call super class EventEmitter2.call(this, { wildcard: true, delimiter: ':', maxListeners: 1000 // default would be 10! }); if (this.log) { this.log = _.wrap(this.log, function(func, msg) { func(self.constructor.name + ': ' + msg); }); } if (deviceOrFrameHandler) { this.incomming = []; deviceOrFrameHandler.on('receive', function (frame) { var unwrappedFrame; if (self.analyzeNextFrame) { self.incomming = self.incomming.concat(Array.prototype.slice.call(frame, 0)); } else { if (self.unwrapFrame) { unwrappedFrame = self.unwrapFrame(_.clone(frame)); if (self.log) self.log('receive unwrapped frame: ' + unwrappedFrame.toHexDebug()); self.emit('receive', unwrappedFrame); } else { if (self.log) self.log('receive frame: ' + frame.toHexDebug()); self.emit('receive', frame); } } }); deviceOrFrameHandler.on('close', function() { if (self.log) self.log('close'); self.emit('close'); self.removeAllListeners(); deviceOrFrameHandler.removeAllListeners(); deviceOrFrameHandler.removeAllListeners('receive'); }); } this.on('send', function(frame) { if (self.wrapFrame) { var wrappedFrame = self.wrapFrame(_.clone(frame)); if (self.log) self.log('send wrapped frame: ' + wrappedFrame.toHexDebug()); deviceOrFrameHandler.send(wrappedFrame); } else { if (self.log) self.log('send frame: ' + frame.toHexDebug()); deviceOrFrameHandler.send(frame); } }); this.start(); } util.inherits(FrameHandler, EventEmitter2); FrameHandler.prototype.start = function(interval, callback) { if (!callback && _.isFunction(interval)) { callback = interval; interval = null; } if (!this.analyzeNextFrame) { if (callback) { callback(null); } return; } if (this.lookupIntervalId) { this.stopLookup(); } var self = this; interval = interval || 50; var analyzing = false; this.lookupIntervalId = setInterval(function() { if (analyzing) { return; } analyzing = true; var nextFrame; while ((nextFrame = self.analyzeNextFrame(self.incomming))) { if (self.unwrapFrame) { unwrappedFrame = self.unwrapFrame(_.clone(nextFrame)); if (self.log) self.log('receive unwrapped frame: ' + unwrappedFrame.toHexDebug()); self.emit('receive', unwrappedFrame); } else { if (self.log) self.log('receive frame: ' + nextFrame.toHexDebug()); self.emit('receive', nextFrame); } } analyzing = false; }, interval); if (callback) { callback(null); } }; FrameHandler.prototype.stop = function() { if (this.lookupIntervalId) { clearInterval(this.lookupIntervalId); this.lookupIntervalId = null; } }; FrameHandler.prototype.send = function(data) { this.emit('send', data); }; module.exports = FrameHandler;
JavaScript
0.000001
@@ -1366,32 +1366,57 @@ f.log('close');%0A + self.stop();%0A self
3369ff9a987a99e6c96b2d6df07646a60d5ceaa6
update comments
js/form.js
js/form.js
/* * Code that manages the contact form. Uses RequireJS * and the jQuery Validation plugin. Attribution goes * to Spruce Interactive's original code at: * http://www.spruce.it/noise/simple-ajax-contact-form/ */ // Start RequireJS code define("form", ["jquery"], function($) { $("#contact").submit(function(event) { var name = $("#form-name").val(), email = $("#form-email").val(), text = $("#message").val(), dataString = 'name='+ name + '&email=' + email + '&text=' + text, formHeight = $("#contact").height(); $('#success-msg').height(formHeight); $.ajax({ type: "POST", url: "/email.php", data: dataString, success: function(){ $("#contact").fadeOut(100); $('#success-msg').fadeIn(100); } }); return false; }); });
JavaScript
0
@@ -38,60 +38,8 @@ orm. - Uses RequireJS%0A * and the jQuery Validation plugin. Att @@ -51,19 +51,16 @@ ion goes -%0A * to Spru @@ -62,16 +62,20 @@ Spruce +%0A * Interact
a6039ecb849b73dd7ff624004b9859d346e3ae90
Update game.js
js/game.js
js/game.js
var Game = {}; var light = false; var timerset = false; var timersetflash = false; var fading = false; Game.fps = 50; Game.initialize = function() { this.entities = []; this.context = document.getElementById("viewport").getContext("2d"); }; function fadeOutRectangle(x, y, w, h, r, g, b) { var self = this; var steps = 50, dr = (255 - r) / steps, // how much red should be added each time dg = (255 - g) / steps, // green db = (255 - b) / steps, // blue i = 0, // step counter interval = setInterval(function() { self.context.fillStyle = 'rgb(' + Math.round(r + dr * i) + ',' + Math.round(g + dg * i) + ',' + Math.round(b + db * i) + ')'; self.context.fillRect(x, y, w, h); // will redraw the area each time i++; if(i >= steps) { // stop if done clearInterval(interval); fading = false; } }, 30); } Game.draw = function() { this.context.clearRect(0, 0, 512, 288); this.context.fillStyle = "#1F3D5C"; this.context.fillRect(0, 0, 512, 288); /*if(timersetflash == false){ //flash timer setTimeout(function(){ light = false; timersetflash = false; }, 200); timersetflash = true; }*/ if(light == true ){ this.context.fillStyle = "#FFFFFF"; this.context.fillRect(0, 0, 512, 288); if(fading == false){ fading = true; fadeOutRectangle(0, 0, 512, 288, 31, 61, 92); } setTimeout(function() { light = false; timerset = false; flash = 0; }, 3000); } if(timerset == false){ //if we haven't set a timer yet, set one setTimeout(function(){ light = true; }, 5000); timerset = true; } for (var i=0; i < this.entities.length; i++) { this.entities[i].draw(this.context); } }; Game.update = function() { for (var i=0; i < this.entities.length; i++) { this.entities[i].update(); } }; Game.addRect = function(initX) { Game.entities.push(new Rect(initX)); }; Game.addRain = function() { Game.entities.push(new Rain()); }; Game.addPlayer = function(){ Game.entites.push(new Player()); };
JavaScript
0.000001
@@ -496,17 +496,25 @@ -i +var count = 0, // @@ -637,17 +637,21 @@ + dr * -i +count ) + ','%0A @@ -707,17 +707,21 @@ + dg * -i +count ) + ','%0A @@ -777,17 +777,21 @@ + db * -i +count ) + ')'; @@ -884,17 +884,21 @@ -i +count ++;%0A @@ -912,11 +912,16 @@ if( -i %3E +count == = st
1d8130347ba98331ae8b3293b838a5d875e51cc0
Call the event emitter class
lib/path-monitor.js
lib/path-monitor.js
"use strict"; // var DynamicPathMonitor = require("./DynamicPathMonitor"); const fbUtil = require("./fbutil") , EventEmitter = require("events") , objUnflatten = require("obj-unflatten") ; module.exports = class PathMonitor extends EventEmitter { constructor (ins, path) { this.ins = ins; this.ref = fbutil.fbRef(path.path); console.log("Indexing %s/%s using path '%s'", path.index, path.type, fbutil.pathName(this.ref)); this.esc = ins.esc; this.joins = (path.joins || []).map(c => { c.fbRef = fbUtil.fbRef(c.path); return c; }); this.index = path.index; this.type = path.type; this.filter = path.filter || (() => true); this.parse = path.parser || (data => parseKeys(data, path.fields, path.omit)); this.on("error", e => ins.emit("error", e)); this._init(); } _handleJoins (data, cb) { let joins = this.joins; if (!joins.length) { return cb(null, data); } let complete = 0 , hadError = null , checkComplete = err => { hadError = err || null; if (--complete === 0) { cb(hadError, data); } } ; joins.forEach(cJoinObj => { let cData = data[cJoinObj.name]; // ["id1", "id2"] if (Array.isArray(cData)) { cData.forEach((cId, i) => { ++complete; cJoinObj.fbRef.child(cId).once("value").then(obj => { cData[i] = obj.val(); checkComplete(); }, err => { this.emit("error", err); checkComplete(err); }); }); } else { ++complete; cJoinObj.fbRef.child(cData).once("value").then(obj => { data[cJoinObj.name] = obj.val(); checkComplete(); }, err => { this.emit("error", err); checkComplete(err); }); } }); } _init () { this.addMonitor = this.ref.on("child_added", this._process.bind(this, this._childAdded)); this.changeMonitor = this.ref.on("child_changed", this._process.bind(this, this._childChanged)); this.removeMonitor = this.ref.on("child_removed", this._process.bind(this, this._childRemoved)); } _stop () { this.ref.off("child_added", this.addMonitor); this.ref.off("child_changed", this.changeMonitor); this.ref.off("child_removed", this.removeMonitor); } _process (fn, snap) { let dat = snap.val(); if (this.filter(dat)) { this._handleJoins(data, (err, dat) => { // The error is emitted already if (err) { return; } fn.call(this, snap.key, this.parse(dat)); }); } } _index (key, data, callback) { this.esc.index({ index: this.index , type: this.type , id: key , body: data }, (error, response) => { callback && callback(error, response); }); } _childAdded (key, data) { let name = nameFor(this, key); this._index(key, data, (error, res) => { if (error) { this.emit("error", new Error(`Failed to create index ${name}: ${error.message}`), error); } else { this.emit("index_created", name, res); } }); } _childChanged(key, data) { let name = nameFor(this, key); this._index(key, data, (error, res) => { if (error) { this.emit("error", new Error(`Failed to update index ${name}: ${error.message}`), error); } else { this.emit("index_updated", name, res); } }); } _childRemoved(key, data) { let name = nameFor(this, key); this.esc.delete({ index: this.index , type: this.type , id: key }, (error, res) => { if (error) { this.emit("error", new Error(`Failed to delete index ${name}: ${error.message}`), error); } else { this.emit("indexe_deleted", name, res); } }); } } function nameFor(path, key) { return path.index + "/" + path.type + "/" + key; } function parseKeys(data, fields, omit) { if (!data || typeof(data) !== 'object') { return data; } let out = data; // restrict to specified fields list if (Array.isArray(fields) && fields.length) { out = {}; fields.forEach(function(f) { let newValue = findValue(data, f); if (newValue !== undefined) { out[f] = newValue; } }); } // remove omitted fields if (Array.isArray(omit) && omit.length) { omit.forEach(function(f) { if (out.hasOwnProperty(f)) { delete out[f]; } }); } out = objUnflatten(out); return out; }
JavaScript
0.000001
@@ -282,24 +282,41 @@ ns, path) %7B%0A + super();%0A this
b0b62682c431ee54498127ac6712fbb2bd20e48d
Correct callback error string
lib/price-finder.js
lib/price-finder.js
'use strict'; const async = require('async'); /* eslint-disable prefer-const */ // TODO no const for testing https://github.com/jhnns/rewire/issues/79 let request = require('request'); /* eslint-enable prefer-const */ const cheerio = require('cheerio'); const extend = require('xtend'); const siteManager = require('./site-manager'); const logger = require('./logger')(); const DEFAULT_OPTIONS = { headers: { 'User-Agent': 'Mozilla/5.0', }, retryStatusCodes: [503], retrySleepTime: 1000, }; class PriceFinder { constructor(options) { logger.log('initializing PriceFinder'); logger.log('user supplied options: %j', options); // merge options, taking the user supplied if duplicates exist this._config = extend(DEFAULT_OPTIONS, options); logger.log('merged config: %j', this._config); } /** * Scrapes a website specified by the uri and finds the item price. * * @param {String} uri The uri of the website to scan * @param {Function} callback Callback called when complete, with first argument * a possible error object, and second argument the * item price (a Number). */ findItemPrice(uri, callback) { logger.log('findItemPrice with uri: %s', uri); let site; try { site = siteManager.loadSite(uri, this._config); } catch (error) { logger.error('error loading site: ', error); if (error.message) { return callback(error.message); } else { return callback(error); } } logger.log('scraping the page...'); // page scrape the site to load the page data this._pageScrape(site, (err, pageData) => { if (err) { logger.error('error retrieving pageData: ', err); return callback(err); } logger.log('pageData found, loading price from site...'); // find the price on the website const price = site.findPriceOnPage(pageData); // error check if (price === -1) { logger.error('unable to find price'); return callback('unable to find price for uri: %s', uri); } logger.log('price found, returning price: %s', price); // call the callback with the item price (null error) return callback(null, price); }); } /** * Scrapes a website specified by the uri and gathers the item details, which * consists of the item's name, category, and current price found on the page. * * @param {String} uri The uri of the website to scan * @param {Function} callback Callback called when complete, with first argument * a possible error object, and second argument the * item details. The item details consists of a name, * category, and price. */ findItemDetails(uri, callback) { logger.log('findItemPrice with uri: %s', uri); let site; try { site = siteManager.loadSite(uri, this._config); } catch (error) { logger.error('error loading site: ', error); if (error.message) { return callback(error.message); } else { return callback(error); } } logger.log('scraping the page...'); // page scrape the site to find the item details this._pageScrape(site, (err, pageData) => { if (err) { logger.error('error retrieving pageData: ', err); return callback(err); } logger.log('pageData found, loading price from site...'); const itemDetails = {}; // find the price on the website itemDetails.price = site.findPriceOnPage(pageData); // error check if (itemDetails.price === -1) { logger.error('unable to find price'); return callback('unable to find price for uri: %s', uri); } logger.log('price found, loading category from site...'); // find the category on the page itemDetails.category = site.findCategoryOnPage(pageData); // find the name on the page (if we have the category) if (itemDetails.category) { logger.log('category found, loading name from site...'); itemDetails.name = site.findNameOnPage(pageData, itemDetails.category); } else { logger.log('unable to find category, skipping name'); } logger.log('returning itemDetails: %j', itemDetails); // call the callback with our item details (null error) return callback(null, itemDetails); }); } // ================================================== // ============== PRIVATE FUNCTIONS ================= // ================================================== _pageScrape(site, callback) { let pageData; async.whilst( // run until we get page data () => !pageData, // hit the site to get the item details (whilstCallback) => { logger.log('using request to get page data for uri: %s', site.getURIForPageData()); request({ uri: site.getURIForPageData(), headers: this._config.headers, }, (err, response, body) => { if (err) { return whilstCallback(err); } if (response) { if (response.statusCode === 200) { logger.log('response statusCode is 200, parsing body to pageData'); // good response if (site.isJSON()) { // parse the body to grab the JSON pageData = JSON.parse(body); } else { // build jquery object using cheerio pageData = cheerio.load(body); } return whilstCallback(); } else if (this._config.retryStatusCodes.indexOf(response.statusCode) > -1) { // if we get a statusCode that we should retry, try again logger.log('response status part of retryStatusCodes, status: %s, retrying...', response.statusCode); logger.log(`sleeping for: ${this._config.retrySleepTime}ms`); return setTimeout(() => whilstCallback(), this._config.retrySleepTime); } else { // else it's a bad response status, all stop return whilstCallback('response status: %s', response.statusCode); } } else { return whilstCallback('no response object found!'); } }); }, // once we have the pageData, or error, return (err) => callback(err, pageData) ); } } module.exports = PriceFinder;
JavaScript
0
@@ -74,16 +74,17 @@ onst */%0A +%0A // TODO @@ -2077,33 +2077,33 @@ return callback( -' +%60 unable to find p @@ -2112,32 +2112,31 @@ ce for uri: -%25s', +$%7B uri +%7D%60 );%0A %7D%0A%0A @@ -3798,17 +3798,17 @@ allback( -' +%60 unable t @@ -3829,24 +3829,23 @@ or uri: -%25s', +$%7B uri +%7D%60 );%0A @@ -4740,16 +4740,16 @@ eData;%0A%0A - asyn @@ -4758,16 +4758,17 @@ whilst(%0A +%0A //
aaaad75daf7c4c9aa64e21a5f0fb949d602b7de2
Define getLogTree() right after setUp()
lib/process-tree.js
lib/process-tree.js
// Copyright (c) 2017 The Regents of the University of Michigan. // All Rights Reserved. Licensed according to the terms of the Revised // BSD License. See LICENSE.txt for details. let treeNode = (address, setUp) => new Promise( function(resolve, reject) { let node = {}; let obj = {}; let children = []; obj.runBefore = () => {}; obj.run = () => {}; obj.runAfter = () => {}; obj.add = function(childSetUp) { children.push(treeNode(address.concat(children.length), childSetUp)) }; node.run = logger => new Promise(function(resolveRun, rejectRun) { obj.log = (code, message) => new Promise( function(resolveLog, rejectLog) { let a = [Date.now(), code].concat(address); a.push(message || ""); Promise.resolve( logger.log(a) ).then(value => { resolveLog(value); }); }); obj.log("begin"); Promise.resolve(obj.runBefore()).then(function() { return Promise.resolve(obj.run()); }).then(function() { let runningChildren = []; for (let child of node.children) runningChildren.push(child.run(logger)); return Promise.all(runningChildren); }).then(function() { return Promise.resolve(obj.runAfter()); }).then(function() { obj.log("done"); resolveRun(); }); }); Promise.resolve(setUp(obj)).then(function(value) { return Promise.all(children); }).then(function(childIterator) { node.children = [...childIterator]; node.getLogTree = () => {return {d:"the lone root"};}; resolve(node); }); }); let newRootNode = (newLogger, setUp) => new Promise( function(resolve, reject) { treeNode([], setUp).then(function(root) { let logger = newLogger(root.getLogTree()); logger.storeProcess(root.run(logger)); resolve(logger); }); }); module.exports = newRootNode;
JavaScript
0.000001
@@ -1396,24 +1396,84 @@ on(value) %7B%0A + node.getLogTree = () =%3E %7Breturn %7Bd:%22the lone root%22%7D;%7D;%0A%0A return P @@ -1575,67 +1575,8 @@ r%5D;%0A - node.getLogTree = () =%3E %7Breturn %7Bd:%22the lone root%22%7D;%7D;%0A
d281a3d09a04500cebab9b9705cf1fa03cd3b70c
Add hashtags
app/twitter.js
app/twitter.js
import Twit from 'twit'; import winston from 'winston'; const nbCachePosts = 46; // Array of hashtags to exclude (noise) const exclude = [ 'adultwork', 'amateur', 'ass', 'babe', 'babes', 'blowjob', 'boobs', 'boobies', 'booty', 'cat', 'calumhood', 'camgirls', 'camfun', 'cammodels', 'cams', 'casualdates', 'casualsex', 'chatroom', 'chaturbate', 'cloudporn', 'coungar', 'cumshow', 'dates', 'dating', 'dog', 'erotic', 'erotica', 'escort', 'fetish', 'flirt', 'followalways', 'followback', 'food', 'gay', 'girl', 'hookup', 'horny', 'hottest', 'kiksex', 'kikmenow', 'kikmenudes', 'livesex', 'like4like', 'likeforlike', 'lingerie', 'livecam', 'liveoncam', 'liveonchaturbate', 'lovethis', 'masturbation', 'mfc', 'mfcgirl', 'mfcgirls', 'nakedselfies', 'natureporn', 'naughty', 'naughtygirl', 'naughtygirls', 'nsfw', 'nude', 'nudes', 'nudemodel', 'nudeselfie', 'nudity', 'onlinecammodel', 'onlinechat', 'onlinedating', 'orgy', 'panties', 'phonesex', 'porn', 'pussy', 'relationship', 'rimming', 'selfie', 'sex', 'sexchat', 'sexdate', 'sexdating', 'sexwebcam', 'sexyteen', 'sexyselfie', 'sexyselfies', 'shy', 'skyporn', 'snapchatme', 'sneakerhead', 'striptease', 'tagsforlikes', 'textchat', 'topless', 'undressed', 'webcam', 'webcamfun', 'xoxo', 'xxx', ]; function isPostExcluded(post) { const hashtags = post.entities.hashtags.map(val => val.text); for (let i = 0; i < hashtags.length; i++) { if (exclude.indexOf(hashtags[i]) !== -1) { return true; } } return false; } export default function (io) { // Init twitter lib const twitter = new Twit({ consumer_key: process.env.TWITTER_CONSUMER_KEY, consumer_secret: process.env.TWITTER_CONSUMER_SECRET, access_token: process.env.TWITTER_ACCESS_TOKEN, access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET, }); // Init stream const stream = twitter.stream('statuses/filter', { track: '#sunset' }); const posts = []; // Listen stream stream.on('tweet', (tweet) => { if (tweet && tweet.retweeted_status == null && tweet.entities != null && tweet.entities.media != null && tweet.entities.media[0].media_url_https != null) { if (!isPostExcluded(tweet)) { // Add post in cache posts.push({ image_url: tweet.entities.media[0].media_url_https, }); io.sockets.emit('new:tweet', { image_url: tweet.entities.media[0].media_url_https, }); // Only keep number cache max if (posts.length > nbCachePosts) { posts.splice(0, posts.length - nbCachePosts); } } } }); io.on('connection', (socket) => { // On user connection send him posts cache posts.forEach((post) => { socket.emit('new:tweet', post); }); }); winston.log('info', 'Twitter stream started'); }
JavaScript
0.005297
@@ -286,24 +286,38 @@ 'camfun',%0A + 'cammodel',%0A 'cammodels @@ -315,24 +315,24 @@ cammodels',%0A - 'cams',%0A @@ -412,17 +412,16 @@ ,%0A 'cou -n gar',%0A @@ -586,16 +586,47 @@ 'girl',%0A + 'girlfriends',%0A 'gorgeous',%0A 'hooku @@ -653,16 +653,46 @@ ttest',%0A + 'hottie',%0A 'instapicture',%0A 'kikse @@ -866,16 +866,33 @@ ation',%0A + 'matchmaking',%0A 'mfc', @@ -915,24 +915,40 @@ 'mfcgirls',%0A + 'myfreecams',%0A 'nakedself @@ -1013,24 +1013,37 @@ ghtygirls',%0A + 'nipples',%0A 'nsfw',%0A @@ -1158,16 +1158,28 @@ ating',%0A + 'orgasm',%0A 'orgy' @@ -1193,16 +1193,33 @@ nties',%0A + 'perfectbody',%0A 'phone @@ -1319,24 +1319,38 @@ 'sexdate',%0A + 'sexdates',%0A 'sexdating @@ -1485,16 +1485,28 @@ tease',%0A + 'squirt',%0A 'tagsf @@ -1525,24 +1525,24 @@ 'textchat',%0A - 'topless', @@ -1542,16 +1542,26 @@ pless',%0A + 'toys',%0A 'undre
ca1df395abb44b6ac769a712efdd2649fece8b8b
refactor and implement reAttachContext for open in new window
extension/content/firebug/search.js
extension/content/firebug/search.js
/* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // Constants const searchDelay = 150; // ************************************************************************************************ Firebug.Search = extend(Firebug.Module, { dispatchName: "search", search: function(text, context) { var searchBox = context.chrome.$("fbSearchBox"); searchBox.value = text; this.update(context); }, enter: function(context) { var panel = context.chrome.getSelectedPanel(); if (!panel.searchable) return; var searchBox = context.chrome.$("fbSearchBox"); var value = searchBox.value; panel.search(value, true); }, cancel: function(context) { this.search("", context); }, clear: function(context) { var searchBox = context.chrome.$("fbSearchBox"); searchBox.value = ""; }, displayOnly: function(text, context) { var searchBox = context.chrome.$("fbSearchBox"); if (text && text.length > 0) setClass(searchBox, "fbSearchBox-attention"); else removeClass(searchBox, "fbSearchBox-attention"); searchBox.value = text; }, focus: function(context) { if (context.detached) context.chrome.focus(); else Firebug.toggleBar(true); var searchBox = context.chrome.$("fbSearchBox"); searchBox.focus(); searchBox.select(); }, update: function(context, immediate, reverse) { var panel = context.chrome.getSelectedPanel(); if (!panel.searchable) return; var searchBox = context.chrome.$("fbSearchBox"); var panelNode = panel.panelNode; var value = searchBox.value; // This sucks, but the find service won't match nodes that are invisible, so we // have to make sure to make them all visible unless the user is appending to the // last string, in which case it's ok to just search the set of visible nodes if (!panel.searchText || value.indexOf(panel.searchText) != 0) removeClass(panelNode, "searching"); // Cancel the previous search to keep typing smooth clearTimeout(panelNode.searchTimeout); if (immediate) { var found = panel.search(value, reverse); if (!found && value) beep(); if (value) { // Hides all nodes that didn't pass the filter setClass(panelNode, "searching"); } else { // Makes all nodes visible again removeClass(panelNode, "searching"); } panel.searchText = value; } else { // After a delay, perform the search panelNode.searchTimeout = setTimeout(function() { Firebug.Search.showOptions(); var found = panel.search(value, reverse); if (!found && value) Firebug.Search.onNotFound(value); if (value) { // Hides all nodes that didn't pass the filter setClass(panelNode, "searching"); } else { // Makes all nodes visible again removeClass(panelNode, "searching"); } panel.searchText = value; }, searchDelay); } }, onNotFound: function() { beep(); }, showOptions: function() { var panel = FirebugChrome.getSelectedPanel(); if (!panel.searchable) return; var searchBox = FirebugChrome.$("fbSearchBox"); // Get search options popup menu. var optionsPopup = FirebugChrome.$("fbSearchOptionsPopup"); if (optionsPopup.state == "closed") { eraseNode(optionsPopup); // The list of options is provided by the current panel. var menuItems = panel.getSearchOptionsMenuItems(); if (menuItems) { for (var i=0; i<menuItems.length; i++) FBL.createMenuItem(optionsPopup, menuItems[i]); } optionsPopup.openPopup(searchBox, "before_start", 0, -5, false, false); } // Update search caseSensitive option according to the current capitalization. var searchString = searchBox.value; Firebug.searchCaseSensitive = (searchString != searchString.toLowerCase()); }, hideOptions: function() { var searchOptions = FirebugChrome.$("fbSearchOptionsPopup"); if (searchOptions) searchOptions.hidePopup(); }, onSearchBoxFocus: function(event) { if (FBTrace.DBG_SEARCH) FBTrace.sysout("onSearchBoxFocus no-op"); //this.showOptions(); }, onSearchButtonKey: function(event) { if (FBTrace.DBG_SEARCH) FBTrace.sysout("onSearchButtonKey ", event); var searchBox = FirebugChrome.$("fbSearchBox"); searchBox.dispatchEvent(event); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Module initialize: function() { this.onSearchBoxFocus = bind(this.onSearchBoxFocus, this); this.onSearchButtonKey = bind(this.onSearchButtonKey, this); }, enable: function() { var searchBox = FirebugChrome.$("fbSearchBox"); searchBox.value = ""; searchBox.disabled = false; searchBox.addEventListener('focus', this.onSearchBoxFocus, true); var searchOptions = FirebugChrome.$("fbSearchButtons"); searchOptions.addEventListener('keypress', this.onSearchButtonKey, true); }, disable: function() { var searchBox = FirebugChrome.$("fbSearchBox"); searchBox.value = ""; searchBox.disabled = true; searchBox.removeEventListener('focus', this.onSearchBoxFocus, true); var searchOptions = FirebugChrome.$("fbSearchButtons"); searchOptions.removeEventListener('keypress', this.onSearchButtonKey, true); } }); // ************************************************************************************************ Firebug.registerModule(Firebug.Search); // ************************************************************************************************ }});
JavaScript
0
@@ -5670,24 +5670,173 @@ s);%0A %7D,%0A%0A + reattachContext: function(browser, context)%0A %7B%0A FBTrace.sysout(%22search.reattachContext%22);%0A this.enable(browser.chrome);%0A %7D,%0A%0A enable: @@ -5840,32 +5840,38 @@ e: function( +chrome )%0A %7B%0A var @@ -5850,32 +5850,73 @@ n(chrome)%0A %7B%0A + FBTrace.sysout(%22search.enable%22);%0A var sear @@ -5915,32 +5915,47 @@ var searchBox = +(chrome?chrome: FirebugChrome.$( @@ -5943,32 +5943,33 @@ me:FirebugChrome +) .$(%22fbSearchBox%22 @@ -6112,32 +6112,83 @@ true);%0A%0A +// XXXjjb seems like these are not used?%0A // var searchOption @@ -6227,32 +6227,34 @@ tons%22);%0A +// searchOptions.ad @@ -6548,32 +6548,34 @@ true);%0A%0A +// var searchOption @@ -6614,32 +6614,34 @@ tons%22);%0A +// searchOptions.re
173d0bd9042216ccd69b3163d69b2a0c69db8841
move static file server before middleware routes - #8134
application.js
application.js
var mbaasApi = require('fh-mbaas-api'); var express = require('express'); var mbaasExpress = mbaasApi.mbaasExpress(); var cors = require('cors'); // list the endpoints which you want to make securable here var securableEndpoints; // fhlint-begin: securable-endpoints securableEndpoints = []; // fhlint-end var app = express(); // Enable CORS for all requests app.use(cors()); // Note: the order which we add middleware to Express here is important! app.use('/sys', mbaasExpress.sys(securableEndpoints)); app.use('/mbaas', mbaasExpress.mbaas); // Note: important that this is added just before your own Routes app.use(mbaasExpress.fhmiddleware()); // allow serving of static files from the public directory app.use(express.static(__dirname + '/public')); // fhlint-begin: custom-routes app.use('/cloud', mbaasExpress.cloud(require('./main.js'))); // fhlint-end // Important that this is last! app.use(mbaasExpress.errorHandler()); var port = process.env.FH_PORT || process.env.VCAP_APP_PORT || 8001; app.listen(port, function() { console.log("App started at: " + new Date() + " on port: " + port); });
JavaScript
0
@@ -548,213 +548,213 @@ %0A// -Note: important that this is added just before your own Routes%0Aapp.use(mbaasExpress.fhmiddleware());%0A%0A// allow serving of static files from the public directory%0Aapp.use(express.static(__dirname + '/public' +allow serving of static files from the public directory%0Aapp.use(express.static(__dirname + '/public'));%0A%0A// Note: important that this is added just before your own Routes%0Aapp.use(mbaasExpress.fhmiddleware( ));%0A
748801992e8c7116b7d32fe44972c73889e39df5
update file /application.js
application.js
application.js
var mbaasApi = require('fh-mbaas-api'); var express = require('express'); var mbaasExpress = mbaasApi.mbaasExpress(); var cors = require('cors'); var bodyParser = require('body-parser'); var app = express(); // Enable CORS for all requests app.use(cors()); // Note: the order which we add middleware to Express here is important! app.use('/sys', mbaasExpress.sys([])); app.use('/mbaas', mbaasExpress.mbaas); // allow serving of static files from the public directory app.use(express.static(__dirname + '/public')); // Note: important that this is added just before your own Routes app.use(mbaasExpress.fhmiddleware()); app.get('/list/:session', function(req,res) { mbaasApi.db({ "act": "list", "type": 'accountSession', "eq":{"session":req.params.session} }, function(err, data) { if (err) { res.end(err); } else { console.log(JSON.stringify(data)); var accountId = data.list[0].fields.accountId; mbaasApi.db({ "act": "list", "type": 'account', "eq":{"sub":accountId} }, function(err, data2) { if (err) { res.end(err); } else { res.end(JSON.stringify(data2)); } }) } }); }); app.get('/drop', function(req,res) { mbaasApi.db({ "act": "deleteall", "type": 'account' }, function(err, noterr) { if (err) { res.end('Boo! ' + err); } else { res.end('OOB! ' + JSON.stringify(noterr)); } }); }); app.use('/hello', require('./lib/hello.js')()); app.use(bodyParser()); app.use('/auth', require('./lib/auth.js')()); // Important that this is last! app.use(mbaasExpress.errorHandler()); var port = process.env.FH_PORT || process.env.OPENSHIFT_NODEJS_PORT || 8001; var host = process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0'; app.listen(port, host, function() { console.log("App started at: " + new Date() + " on port: " + port); });
JavaScript
0.000002
@@ -657,32 +657,76 @@ tion(req,res) %7B%0A + console.log(JSON.stringify(req.params)); %0A mbaasApi.db(%7B%0A
80cae8c4c9b195f02bfb969dc64617b489773553
Test code.
js/main.js
js/main.js
JavaScript
0
@@ -0,0 +1,370 @@ +%0A%09var testModel = new Models.ItemListing(%7B%0A%09%09id: 0,%0A%09%09name: %22Test Item%22,%0A%09%09price: %22(USD) $5%22,%0A%09%09location: %22Singapore%22,%0A%09%09buyers: %5B0%5D,%0A%09%09owner: 0,%0A%09%09imageUrl: 'http://placehold.it/96x96'%0A%09%7D);%0A%0A%09var yourCollection = new Models.ItemListings();%0A%0A%09var yourView = new Views.ListingView(%7B%0A%09%09collection: yourCollection,%0A%09%09id: %22you-listing%22%0A%09%7D);%0A%0A%09yourCollection.add(testModel);%0A
4194efdb32e3b474211046df368a235c084a9c60
use documentFragment
js/main.js
js/main.js
//------------Tool functions---------------- String.prototype.capitalize = function () { if (this === "") return this; return this.charAt(0).toUpperCase() + this.slice(1); } //--------------List data--------------- var arrItems = [ "test", "lagou", "float", "nav", //https://support.mozilla.org/zh-CN/?icn=tabz 'form', 'table', 'sortTable', "slideshow", 'slidesJs', 'center', 'jumbotron' //http://www.imooc.com/activity/zhaopin ] //------------- add <a> to #list--------- var list = document.getElementById('list'); var i = 0, l = arrItems.length; for (i; i < l; i++) { var id = arrItems[i]; var a = document.createElement("a"); a.href = "template/" + id + ".html"; a.innerHTML = id.capitalize(); list.appendChild(a); }
JavaScript
0
@@ -539,82 +539,108 @@ var -list = document.getElementById('list');%0Avar i = 0,%0A l = arrItems.length +date1=new Date;%0Avar i = 0,%0A l = arrItems.length,%0A fragment = document.createDocumentFragment() ;%0Afo @@ -810,26 +810,163 @@ -list.appendChild(a);%0A%7D +fragment.appendChild(a);%0A%7D%0Avar list = document.getElementById('list');%0Alist.appendChild(fragment);%0Avar date2=new Date;%0Aconsole.log(%22cost time:%22+(date2-date1));
961e14f9188fd409f5e7b1f9af1fc5648d25c27c
Update main.js
js/main.js
js/main.js
/** * jQuery.toTop.js v1.1 * Developed by: MMK Jony * Fork on Github: https://github.com/mmkjony/jQuery.toTop **/ !function(o){"use strict";o.fn.toTop=function(t){var i=this,e=o(window),s=o("html, body"),n=o.extend({autohide:!0,offset:420,speed:500,position:!0,right:15,bottom:30},t);i.css({cursor:"pointer"}),n.autohide&&i.css("display","none"),n.position&&i.css({position:"fixed",right:n.right,bottom:n.bottom}),i.click(function(){s.animate({scrollTop:0},n.speed)}),e.scroll(function(){var o=e.scrollTop();n.autohide&&(o>n.offset?i.fadeIn(n.speed):i.fadeOut(n.speed))})}}(jQuery); console.log('\n %c Cat UI V1.1 情托于物。人情冷暖,世态炎凉。 %c @折影轻梦<https://i.chainwon.com/catui.html> \n\n','color:rgb(255, 242, 242);background:rgb(244, 164, 164);padding:5px 0;border-radius:3px 0 0 3px;', 'color:rgb(244, 164, 164);background:rgb(255, 242, 242);padding:5px 0;border-radius:0 3px 3px 0;');
JavaScript
0.000001
@@ -616,17 +616,17 @@ t UI V1. -1 +2 %E6%83%85%E6%89%98%E4%BA%8E%E7%89%A9%E3%80%82%E4%BA%BA%E6%83%85 @@ -880,12 +880,283 @@ 3px 0;');%0D%0A +//float start%0D%0Avar antime = 500;%0D%0A$(%22.float-window%22).click(function() %7B%0D%0A $(this).fadeOut(antime);%0D%0A%7D);%0D%0A$(%22#qrcode-b%22).click(function() %7B%0D%0A $(%22#qrcode%22).fadeIn(antime);%0D%0A%7D);%0D%0A$(%22#support-b%22).click(function() %7B%0D%0A $(%22#support%22).fadeIn(antime);%0D%0A%7D);%0D%0A//float end%0D%0A
b6044d577d6e4c67e2301dfbd1ba421d670c2d05
Remove the leading '.' in the entryModule path
webpack-aot.config.js
webpack-aot.config.js
'use strict'; const webpackConfig = require('./webpack.config.js'); const loaders = require('./webpack/loaders'); const AotPlugin = require('@ngtools/webpack').AotPlugin; const ENV = process.env.npm_lifecycle_event; const JiT = ENV === 'build:jit'; webpackConfig.module.rules = [ loaders.tslint, loaders.ts, loaders.html, loaders.globalCss, loaders.localCss, loaders.svg, loaders.eot, loaders.woff, loaders.woff2, loaders.ttf, ]; webpackConfig.plugins = webpackConfig.plugins.concat([ new AotPlugin({ tsConfigPath: './tsconfig-aot.json', entryModule: './src/app/app.module#AppModule', }), ]); if (!JiT) { console.log('AoT: True'); } module.exports = webpackConfig;
JavaScript
0.999986
@@ -578,18 +578,16 @@ odule: ' -./ src/app/
4478c3f07603c690d6c12c03e884b922bf2c2763
fix Object.assign : )
webpack/dev.config.js
webpack/dev.config.js
var baseConfig = require('./base.config'); var project = require('../project.config'); var path = require('path'); console.log(395, path.resolve(project.ROOT, 'static')); module.exports = Object.assign({ devtool: 'eval', devServer: { open: true, contentBase: path.resolve(project.ROOT, 'static'), port: project.DEV_SERVER_PORT } }, baseConfig);
JavaScript
0.000002
@@ -113,65 +113,8 @@ );%0A%0A -console.log(395, path.resolve(project.ROOT, 'static'));%0A%0A modu @@ -141,16 +141,32 @@ assign(%7B +%7D, baseConfig, %7B %0A devto @@ -302,23 +302,11 @@ RT%0A %7D%0A%7D -, baseConfig );%0A
cb5cd692c752ba4a978f11bd1f30c9634b8ef62a
add failing test for watch
bellamie/test/test.js
bellamie/test/test.js
import SKClient from "sk-client"; import expect from "expect.js"; describe("broadcasts", function() { const SK = new SKClient({server: "http://localhost:80"}); let testBroadcastId = "nope"; let testBroadcastName = "Test Broadcast"; const fail = function(err) { if (err instanceof Error) { throw err; } else { throw new Error(err.message); } }; it("should create", function() { return SK.broadcasts.create({name: testBroadcastName}).then(function(broadcast) { expect(broadcast).to.be.ok(); expect(broadcast.name).to.be(testBroadcastName); testBroadcastId = broadcast.id; }) .catch(fail); }); it("should findOne", function() { return SK.broadcasts.findOne(testBroadcastId).then(function(broadcast) { expect(broadcast).to.be.ok(); expect(broadcast.name).to.be(testBroadcastName); }) .catch(fail); }); it("should update", function() { testBroadcastName = "Altered Name"; return SK.broadcasts.update(testBroadcastId, {name: testBroadcastName}) .then(function(broadcast) { expect(broadcast).to.be.ok(); expect(broadcast.name).to.be(testBroadcastName); }) .catch(fail); }); it("should find", function() { return SK.broadcasts.find().then(function(broadcasts) { expect(broadcasts).to.be.an(Array); const myBroadcast = broadcasts.filter((b) => b.id === testBroadcastId)[0]; expect(myBroadcast).to.be.ok(); expect(myBroadcast.name).to.be(testBroadcastName); }) .catch(fail); }); it("should delete", function() { return SK.broadcasts.delete(testBroadcastId) .then(function() { return SK.broadcasts.findOne(testBroadcastId).then(function() { throw new Error("Uh oh -- success on findOne after delete"); }) .catch(function(err) { expect(err.status).to.be(404); }); }) .catch(fail); }); });
JavaScript
0
@@ -1539,32 +1539,2004 @@ h(fail);%0A %7D);%0A%0A + it(%22should watch%22, function() %7B%0A let data;%0A let watchBroadcastName = %22broadcast watch test%22;%0A let watchBroadcastId;%0A%0A // Given a cursor and an eventName, return a promise that has resolved after the event has%0A // fired once.%0A let eventPromise = function(eventName) %7B%0A return new Promise((resolve, reject) =%3E %7B%0A broadcastCursor.on(eventName, (...args) =%3E %7B%0A if (resolve) %7B%0A resolve(%5B...args%5D);%0A resolve = null;%0A %7D%0A %7D);%0A %7D);%0A %7D;%0A%0A let broadcastCursor = SK.broadcasts.watch(%7Bid: testBroadcastId%7D)%0A%0A .then(function() %7B%0A // Now we want to do a create, so we're going to send a PUT and register a %22updated%22%0A // handler. But those things do not necessarily to resolve in any particular order, so%0A // we'll do them both and handle it with a Promise.all%0A const createdEventPromise = eventPromise(%22created%22);%0A const doCreatePromise = SK.broadcasts.create(%7Bname: watchBroadcastName%7D);%0A return Promise.all(%5BcreatedEventPromise, doCreatePromise%5D);%0A %7D)%0A%0A .then(function(%5Bdocs%5D, newDoc) %7B%0A expect(docs).to.equal(%5BnewDoc%5D);%0A watchBroadcastId = newDoc.id;%0A%0A // Same deal, now modify it%0A testBroadcastName = %22Updated in Watch%22;%0A const updateEventPromise = eventPromise(%22updated%22);%0A const doUpdatePromise = SK.broadcasts.update(testBroadcastName, %7Bname: testBroadcastName%7D);%0A return Promise.all(%5BupdateEventPromise, doUpdatePromise%5D);%0A %7D)%0A%0A .then(function(%5Bdocs%5D, doc) %7B%0A expect(docs).to.equal(%5Bdoc%5D);%0A expect(docs%5B0%5D.name).to.equal(testBroadcastName);%0A%0A // Same deal, now delete it.%0A const deleteEventPromise = eventPromise(%22deleted%22);%0A const doDeletePromise = SK.broadcasts.delete(testBroadcastName);%0A return Promise.all(%5BdeleteEventPromise, doDeletePromise%5D);%0A %7D)%0A%0A .then(function(%5Bids%5D) %7B%0A expect(ids).to.equal(%5BwatchBroadcastId%5D);%0A %7D);%0A%0A return broadcastCursor;%0A %7D);%0A%0A it(%22should del
0460e7d031a57dd302d3b7bced762e6b464fc2d3
update loading fast header image
js/main.js
js/main.js
$(document).ready(function() { $('.home-slider').flexslider({ animation: "slide", directionNav: false, controlNav: false, direction: "vertical", slideshowSpeed: 2500, animationSpeed: 500, smoothHeight: false }); //$(".intro-section").backstretch("images/header-bg.jpg"); $.backstretch('images/header-bg.jpg'); $('#what').waypoint(function(direction){ if($('.preload-image').length){$('.preload-image').remove();} $('.backstretch').remove(); if (direction=='down'){ $.backstretch('images/contact-bg.jpg'); }else{ $.backstretch('images/header-bg.jpg'); } }); /*============================================ Project Preview ==============================================*/ $('.project-item').click(function(e){ e.preventDefault(); var elem = $(this), title = elem.find('.project-title').text(), link = elem.attr('href'), descr = elem.find('.project-description').html(), slidesHtml = '<ul class="slides">', slides = elem.data('images').split(','); for (var i = 0; i < slides.length; ++i) { slidesHtml = slidesHtml + '<li><img src='+slides[i]+' alt=""></li>'; } slidesHtml = slidesHtml + '</ul>'; $('#project-modal').on('show.bs.modal', function () { $(this).find('h1').text(title); $(this).find('.btn').attr('href',link); $(this).find('.project-descr').html(descr); $(this).find('.image-wrapper').addClass('flexslider').html(slidesHtml); setTimeout(function(){ $('.image-wrapper.flexslider').flexslider({ slideshowSpeed: 3000, animation: 'slide', controlNav: false, start: function(){ $('#project-modal .image-wrapper') .addClass('done') .prev('.loader').fadeOut(); } }); },1000); }).modal(); }); $('#project-modal').on('hidden.bs.modal', function () { $(this).find('.loader').show(); $(this).find('.image-wrapper') .removeClass('flexslider') .removeClass('done') .html('') .flexslider('destroy'); }); });
JavaScript
0
@@ -1,8 +1,48 @@ +$.backstretch('images/header-bg.jpg');%0A%0A $(docume @@ -377,46 +377,8 @@ );%0A%09 -$.backstretch('images/header-bg.jpg'); %0A%09$(
1a06b2dab880931a11df8ee57d99b32645ec3674
Add findOperatorByRangeStart fn to token helper
lib/token-helper.js
lib/token-helper.js
/** * Returns token by range start. Ignores () * * @param {JsFile} file * @param {Number} range * @param {Boolean} [backward=false] Direction * @returns {Object} */ exports.getTokenByRangeStart = function(file, range, backward) { var tokens = file.getTokens(); // get next token var tokenPos = file.getTokenPosByRangeStart(range); var token = tokens[tokenPos]; // we should check for "(" if we go backward var parenthesis = backward ? '(' : ')'; // if token is ")" -> get next token // for example (a) + (b) // next token ---^ // we should find (a) + (b) // ------------------^ if (token && token.type === 'Punctuator' && token.value === parenthesis ) { var pos = backward ? token.range[0] - 1 : token.range[1]; tokenPos = file.getTokenPosByRangeStart(pos); token = tokens[tokenPos]; } return token; }; /** * Returns true if token is punctuator * * @param {Object} token * @param {String} punctuator * @returns {Boolean} */ exports.tokenIsPunctuator = function(token, punctuator) { return token && token.type === 'Punctuator' && token.value === punctuator; }; /** * Returns token or false if there is a punctuator in a given range * * @param {JsFile} file * @param {Number} range * @param {String} operator * @returns {Object|Boolean} */ exports.checkIfPunctuator = function(file, range, operator) { var part = this.getTokenByRangeStart(file, range); if (this.tokenIsPunctuator(part, operator)) { return part; } return false; }
JavaScript
0
@@ -1172,24 +1172,504 @@ tuator;%0A%7D;%0A%0A +/**%0A * Find previous operator by range start%0A *%0A * @param %7BJsFile%7D file%0A * @param %7BNumber%7D range%0A * @param %7BString%7D operator%0A * @returns %7BBoolean%7CObject%7D%0A */%0Aexports.findOperatorByRangeStart = function(file, range, operator) %7B%0A var tokens = file.getTokens();%0A var index = file.getTokenPosByRangeStart(range);%0A%0A while (index) %7B%0A if (tokens%5B index %5D.value === operator) %7B%0A return tokens%5B index %5D;%0A %7D%0A%0A index--;%0A %7D%0A%0A return false;%0A%0A%7D;%0A%0A /**%0A * Retur
a55664903c702356d46421ccb03c2a128e767802
fix major bug with visibleTextEditors (replaced by activeTextEditor)
lib/utils/common.js
lib/utils/common.js
/* global console */ /* global decodeURIComponent */ /* global JSON */ var vscode = require('vscode'); var common = { /** * Get the latest release of vscode-tfs and warn user in case of update. * * @module Common Utilities * @version 0.5.0 */ checkLastRelease: function() { var https = require('https'), version = 'v' + require('../../package.json').version; var options = { hostname: 'api.github.com', path: '/repos/ivangabriele/vscode-tfs/releases/latest', headers: { 'Accept': 'application/vnd.github.v3+json', 'User-Agent': 'Vscode-Tfs' } }; https .get(options, function(response) { var content = ''; response.on('data', function(chunk) { content += chunk.toString(); }) response.on('end', function() { var jsonContent = JSON.parse(content); if (version !== jsonContent.tag_name) { var promise = vscode.window.showWarningMessage('TFS: A new version (' + jsonContent.tag_name + '), is available.', { title: 'Update Now' }); promise.then(function(action) { if (!action) { return; } vscode.commands.executeCommand('workbench.extensions.action.listOutdatedExtensions'); }); } }) }) .on('error', function(error) { console.error(error); }); }, /** * Get the current opened file path. * * @module Common Utilities * @version 0.5.0 * * @return {String} File path */ getCurrentFilePath: function() { if (!vscode.window.visibleTextEditors.length) { return false; } var currentFilePath = vscode.window.visibleTextEditors[0].document.uri.toString(); if (currentFilePath.substr(0, 8) !== 'file:///') { return false; } currentFilePath = decodeURIComponent(currentFilePath).substr(8); return currentFilePath; }, /** * Get the current workspace path. * * @module Common Utilities * @version 0.5.0 * * @return {String} Directory path */ getCurrentWorkspacePath: function() { return vscode.workspace.rootPath; } }; module.exports = common;
JavaScript
0
@@ -1698,38 +1698,37 @@ (!vscode.window. -visibl +activ eTextEditors.len @@ -1726,16 +1726,8 @@ itor -s.length ) %7B%0A @@ -1801,14 +1801,13 @@ dow. -visibl +activ eTex @@ -1817,12 +1817,8 @@ itor -s%5B0%5D .doc
a4142a4342ce4eef9413f66ada5b3ca6e29ac629
clean up getAppDir
lib/utils/module.js
lib/utils/module.js
'use strict'; import _ from 'lodash'; import findUp from 'find-up'; import fs from 'fs'; import nameUtils from './name'; import path from 'path'; /** * Returns modules' names in path * @param {String} modulePath - path to module * @param {String} symbol - character to split by * @return {Array} - module names */ function extractBasedOnChar(modulePath, symbol) { let modules = [] // path after last symbol is module name , moduleName = modulePath.slice(modulePath.lastIndexOf(symbol)).replace(symbol, '') , parentModuleName; modules.push(moduleName); // determine if user provided more than 1 symbol parentModuleName = modulePath.slice(0, modulePath.lastIndexOf(symbol)); if (parentModuleName.indexOf(symbol) > -1) { parentModuleName = modulePath.slice(parentModuleName.lastIndexOf(symbol), modulePath.lastIndexOf(symbol)); parentModuleName = parentModuleName.replace(symbol, ''); } modules.push(parentModuleName); return modules; } /** * Returns .yo-rc.json dirname * @returns {String} - .yo-rc.json dirname */ exports.getYoPath = function getYoPath() { return path.dirname(findUp.sync('.yo-rc.json')); }; /** * Returns app directory * @returns {String} - app directory */ exports.getAppDir = function () { let appDir = require(path.join(exports.getYoPath(), 'build.config.js')).appDir; if (appDir[appDir.length - 1] === '/' || appDir[appDir.length - 1] === '\\') { appDir = appDir.slice(0, appDir.length - 1); } return appDir; }; /** * Returns child and parent module names * @param {String} modulePath - path to module * @return {Array} - [child, parent] */ exports.extractModuleNames = function (modulePath) { let appName; // return appName for app.js if (modulePath === exports.getAppDir()) { appName = require(path.join(exports.getYoPath(), 'package.json')).name; return [appName, null]; } modulePath = modulePath.replace(/\\/g, '/'); // uses module syntax if (modulePath.indexOf('/') > -1) { return extractBasedOnChar(modulePath, '/'); } return [modulePath, null]; }; /** * Converts backslashes and forwardslashes to path separator * @param {String} modulePath - path to module * @return {String} - normalized module path */ exports.normalizeModulePath = function (modulePath) { if (modulePath === exports.getAppDir()) { return ''; } modulePath = modulePath.replace(/[\\\/]/g, path.sep); modulePath = modulePath.split(path.sep).map(nameUtils.hyphenName).join(path.sep); return modulePath; }; /** * Returns if module exists in app * @param {String} modulePath - path to module * @return {Boolean} - does module exist? */ exports.moduleExists = function (modulePath) { // check if file exists let yoPath = path.dirname(findUp.sync('yo-rc.json')) , fullPath; if (modulePath === exports.getAppDir()) { return true; } fullPath = path.join(yoPath, exports.getAppDir(), exports.normalizeModulePath(modulePath)); return fs.existsSync(fullPath); }; /** * Return file path * @param {String} filePath - path to module MINUS the convention {,-routes,-module} and extension * @param {Boolean} isLookingForRoutes - looking for routes file? or just module? * @return {String} file path */ function findFile(filePath, isLookingForRoutes) { let files = [] , conventions = ['-module', ''] , extensions = ['coffee', 'es6', 'js', 'ts']; if (isLookingForRoutes) { conventions.unshift('-routes'); } conventions.forEach(convention => { extensions.forEach(extension => { files.push(filePath + convention + '.' + extension); }); }); return _.find(files, routesFile => fs.existsSync(routesFile)); } /** * Returns routesfile path * @param {String} routesPath - path to module MINUS the convention {,-routes,-module} and extension * @return {String} - file path */ exports.findRoutesFile = function (routesPath) { return findFile(routesPath, true); }; /** * Returns module file path * @param {String} modulePath - path to module MINUS the convention {,-module} and extension * @return {String} - file path */ exports.findModuleFile = function (modulePath) { return findFile(modulePath, false); }; /** * Returns list of files that are script files * @param {String[]} files - list of files to filter * @return {String[]} - script files */ function filterScriptFiles(files) { return files.filter(file => { return file.indexOf('.coffee') >= 0 || file.indexOf('.js') >= 0 || file.indexOf('.ts') >= 0 || file.indexOf('.es6') >= 0; }); } /** * Returns list of files that are modules * @param {String[]} files - list of files to filter * @return {String[]} - module files */ function filterModuleFiles(files) { return files.filter(file => { const fileBaseDirectoryWithSuffix = path.dirname(file).split(path.sep).pop() + '-module' , fileName = path.basename(file).replace(path.extname(file), ''); return fileName === fileBaseDirectoryWithSuffix; }); } /** * Returns directories of files * @param {String[]} files - list of files to filter * @return {String[]} - directories */ function filterDirectories(files) { return files.map(file => path.dirname(file)); } /** * Converts module string to key value pairs {name, value} for choice * @param {String[]} modules - list of modules * @return {Object[]} - {name, value} of module */ function convertToChoice(modules) { return modules.map(module => { return { name: module, value: module.replace(exports.getAppDir() + '\\', '').replace(exports.getAppDir() + '/', '') }; }); } /** * Returns list of modules when given a list of files * @param {String[]} files - list of files to filter * @return {Object[]} - list of modules */ exports.moduleFilter = function (files) { let filteredFiles = filterScriptFiles(files); filteredFiles = filterModuleFiles(filteredFiles); filteredFiles = filterDirectories(filteredFiles); // remove duplicate directories filteredFiles = _.uniq(filteredFiles); return convertToChoice(filteredFiles); };
JavaScript
0.000002
@@ -1182,17 +1182,41 @@ irectory + without trailing / or %5C %0A - * @retu @@ -1366,78 +1366,121 @@ pDir -; %0A -if (appDir%5BappDir.length - 1%5D === '/' %7C%7C appDir%5BappDir.length - 1%5D + , lastCharacterInPath = appDir%5BappDir.length - 1%5D;%0A%0A if (lastCharacterInPath === '/' %7C%7C lastCharacterInPath === @@ -1492,24 +1492,22 @@ ) %7B%0A -appDir = +return appDir. @@ -1539,16 +1539,17 @@ 1);%0A %7D%0A +%0A return
48b2b5319a4e87c86c04c98e70cd6f7d3d6ed9b9
Make wrapped component's ref accessible.
lib/withSafeArea.js
lib/withSafeArea.js
// @flow import * as React from 'react' import { StyleSheet } from 'react-native' import SafeArea, { type SafeAreaInsets } from 'react-native-safe-area' type Props = any; type State = { safeAreaInsets: SafeAreaInsets, }; export function withSafeArea( Component: React.ComponentType<any>, applyTo: 'margin' | 'padding' | 'contentInset' = 'margin', direction: 'horizontal' | 'vertical' | 'both' = 'both' ): React.ComponentType<any> { const isHorizontal = direction === 'horizontal' || direction === 'both' const isVertical = direction === 'vertical' || direction === 'both' return class extends React.Component<Props, State> { state = { safeAreaInsets: { top: 0, bottom: 0, left: 0, right: 0 } } onSafeAreaInsetsDidChange = this.onSafeAreaInsetsDidChange.bind(this) componentWillMount(): void { SafeArea.getSafeAreaInsetsForRootView() .then(result => this.onSafeAreaInsetsDidChange(result)) } componentDidMount(): void { SafeArea.addEventListener('safeAreaInsetsForRootViewDidChange', this.onSafeAreaInsetsDidChange) } componentWillUnmount(): void { SafeArea.removeEventListener( 'safeAreaInsetsForRootViewDidChange', this.onSafeAreaInsetsDidChange ) } get currentSafeAreaInsets(): SafeAreaInsets { return this.state.safeAreaInsets } get injectedProps(): Props { const { top, bottom, left, right } = this.state.safeAreaInsets if (applyTo === 'contentInset') { const contentInset = this.props.contentInset || {} const contentOffset = this.props.contentOffset || {} const injected = { automaticallyAdjustContentInsets: false, contentInset: { ...contentInset }, contentOffset: { ...contentOffset }, } if (isHorizontal) { injected.contentInset.left = (contentInset.left || 0) + left injected.contentInset.right = (contentInset.right || 0) + right injected.contentOffset.x = (contentOffset.x || 0) - left } if (isVertical) { injected.contentInset.top = (contentInset.top || 0) + top injected.contentInset.bottom = (contentInset.bottom || 0) + bottom injected.contentOffset.y = (contentOffset.y || 0) - top } return injected } const style = StyleSheet.flatten([this.props.style]) || {} const injected = { style: { ...style } } if (applyTo === 'margin') { const marginLeft = style.marginLeft || style.marginHorizontal || style.margin const marginRight = style.marginRight || style.marginHorizontal || style.margin const marginTop = style.marginTop || style.marginVertical || style.margin const marginBottom = style.marginBottom || style.marginVertical || style.margin if (isHorizontal) { injected.style.marginLeft = (marginLeft || 0) + left injected.style.marginRight = (marginRight || 0) + right } if (isVertical) { injected.style.marginTop = (marginTop || 0) + top injected.style.marginBottom = (marginBottom || 0) + bottom } } else if (applyTo === 'padding') { const paddingLeft = style.paddingLeft || style.paddingHorizontal || style.padding const paddingRight = style.paddingRight || style.paddingHorizontal || style.padding const paddingTop = style.paddingTop || style.paddingVertical || style.padding const paddingBottom = style.paddingBottom || style.paddingVertical || style.padding if (isHorizontal) { injected.style.paddingLeft = (paddingLeft || 0) + left injected.style.paddingRight = (paddingRight || 0) + right } if (isVertical) { injected.style.paddingTop = (paddingTop || 0) + top injected.style.paddingBottom = (paddingBottom || 0) + bottom } } return injected } onSafeAreaInsetsDidChange(result: { safeAreaInsets: SafeAreaInsets }): void { const { safeAreaInsets } = result this.setState({ safeAreaInsets }) } render(): React.Node { return <Component {...this.props} {...this.injectedProps} /> } } }
JavaScript
0
@@ -708,16 +708,43 @@ : 0 %7D %7D%0A + wrappedRef: any = null%0A onSa @@ -1376,16 +1376,17 @@ get +_ injected @@ -4162,18 +4162,89 @@ urn -%3CComponent +(%0A %3CComponent%0A ref=%7B(ref) =%3E %7B this.wrappedRef = ref %7D%7D%0A %7B.. @@ -4255,16 +4255,26 @@ s.props%7D +%0A %7B...thi @@ -4275,16 +4275,17 @@ ...this. +_ injected @@ -4294,11 +4294,27 @@ ops%7D - /%3E +%0A /%3E%0A ) %0A
a3dc5f233b8e941fa1f6c1339ff366ed9b206f8e
move mouse logic into Platform
js/main.js
js/main.js
// consts for brick stuff const widthDivisor = 10; const heightDivisor = 20; const numOfRows = 5; class Platform{ constructor(locX, size, ctx){ this.x = locX; this.size = size; this.y = ctx.canvas.height - (ctx.canvas.height / 10); this.boxHeight = window.innerHeight / 25; } draw(ctx){ ctx.fillStyle = "#000000"; ctx.fillRect(this.x, this.y, this.size, this.boxHeight); } update(ctx, mouseX){ this.x = mouseX; ctx.fillRect(this.x, this.y, this.size, this.boxHeight); } } function init() { // class variables var bricks = []; var canvas = document.getElementById('game'), ctx = canvas.getContext('2d'); //set default mouse position var mouseX = ctx.canvas.width / 2; // autosize canvas to window size ctx.canvas.width = window.innerWidth; ctx.canvas.height = window.innerHeight; //create new platform and draw it var platform = new Platform(mouseX - (ctx.canvas.width / 5) / 2, ctx.canvas.width / 5, ctx); setInterval(function () { document.onmousemove = function(e){ mouseX = e.clientX; } if(mouseX > canvas.width - (platform.size / 2)) { mouseX = canvas.width - (platform.size / 2); } else if(mouseX < platform.size / 2) { mouseX = platform.size / 2; } else{ //do nothing } //clear the canvas ctx.clearRect(0,0,canvas.width, canvas.height); //draw stuff platform.update(ctx, mouseX - (canvas.width / 5) / 2); // draw all the bricks for (y = 0; y < numOfRows; y++) { for (x = 0; x < widthDivisor; x++) { var b = new Brick(1, x * (ctx.canvas.width / widthDivisor), (ctx.canvas.height / widthDivisor) + (y * (ctx.canvas.height / heightDivisor)), ctx); b.draw(ctx); bricks.push(b); } } //console.log("total number of bricks = " + bricks.length); }, 30); } function Brick(health, x, y, ctx) { this.health = health; this.xPosition = x; this.yPosition = y; this.color = 'hsl(' + 360 * Math.random() + ', 75%, 60%)'; // random color, same saturation and intensity // constant for all bricks this.width = ctx.canvas.width / widthDivisor; this.height = ctx.canvas.height / heightDivisor; //functions this.draw = function (ctx){ // fill with color ctx.rect(this.xPosition, this.yPosition, this.width, this.height) ctx.fillStyle = this.color; ctx.fillRect(this.xPosition, this.yPosition, this.width, this.height); // add stroke ctx.lineWidth = 1; ctx.strokeStyle = "black"; ctx.stroke(); } } document.addEventListener("DOMContentLoaded", init, false);
JavaScript
0.000001
@@ -458,28 +458,338 @@ X)%7B%0A +%0A -this.x = mouse +var locX = mouseX%0A%0A if(locX %3E ctx.canvas.width - (this.size / 2)) %7B%0A locX = ctx.canvas.width - (this.size / 2);%0A %7D%0A else if(locX %3C this.size / 2) %7B%0A locX = this.size / 2;%0A %7D%0A else%7B%0A //do nothing%0A %7D%0A%0A locX = locX - (ctx.canvas.width / 5) / 2;%0A%0A this.x = loc X;%0A @@ -1461,261 +1461,8 @@ %7D%0A%0A - if(mouseX %3E canvas.width - (platform.size / 2)) %7B%0A mouseX = canvas.width - (platform.size / 2);%0A %7D%0A else if(mouseX %3C platform.size / 2) %7B%0A mouseX = platform.size / 2;%0A %7D%0A else%7B%0A //do nothing%0A %7D%0A%0A @@ -1593,33 +1593,8 @@ useX - - (canvas.width / 5) / 2 );%0A
00fb530f2efabe8f2708a675a10f3e6a233bd738
Remove Hotjar because it doesn't work
website/siteConfig.js
website/siteConfig.js
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // See https://docusaurus.io/docs/site-config for all the possible // site configuration options. // List of projects/orgs using your project for the users page. // const users = [ // { // caption: 'User1', // // You will need to prepend the image path with your baseUrl // // if it is not '/', like: '/test-site/img/docusaurus.svg'. // image: '/img/docusaurus.svg', // infoLink: 'https://www.facebook.com', // pinned: true, // }, // ]; const repoUrl = 'https://github.com/apifytech/apify-js'; const siteConfig = { title: 'Apify SDK', // Title for your website. // This is also used as page meta description for SEO, so write it carefully. // TODO: Take this from package.json // eslint-disable-next-line max-len tagline: 'The scalable web crawling and scraping library for JavaScript. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.', url: 'https://sdk.apify.com', // Your website URL cname: 'sdk.apify.com', baseUrl: '/', // Base URL for your project */ // For github.io type URLs, you would set the url and baseUrl like: // url: 'https://facebook.github.io', // baseUrl: '/test-site/', // Used for publishing and more projectName: 'apify-js', organizationName: 'apifytech', // For top-level user or org sites, the organization is still the same. // e.g., for the https://JoelMarcey.github.io site, it would be set like... // organizationName: 'JoelMarcey' // For no header links in the top nav bar -> headerLinks: [], headerLinks: [ { search: true }, { doc: 'guides/motivation', label: 'Guide' }, { doc: 'examples/basiccrawler', label: 'Examples' }, { doc: 'api/apify', label: 'Reference' }, { href: repoUrl, label: 'GitHub' }, // { page: 'help', label: 'Help' }, // { blog: true, label: 'Blog' }, ], // If you have users set above, you add it here: // users, /* path to images for header/footer */ headerIcon: 'img/apify_logo.svg', footerIcon: 'img/apify_logo.svg', favicon: 'img/favicon.ico', /* Colors for website */ colors: { primaryColor: '#001F5B', secondaryColor: '#FF9012', }, algolia: { apiKey: process.env.ALGOLIA_API_KEY, indexName: 'apify_sdk', algoliaOptions: {}, // Optional, if provided by Algolia }, /* Custom fonts for website */ /* fonts: { myFont: [ "Times New Roman", "Serif" ], myOtherFont: [ "-apple-system", "system-ui" ] }, */ // This copyright info is used in /core/Footer.js and blog RSS/Atom feeds. copyright: `Copyright © ${new Date().getFullYear()} Apify Technologies s.r.o.`, highlight: { // Highlight.js theme to use for syntax highlighting in code blocks. theme: 'monokai-sublime', defaultLang: 'javascript', }, // Using Prism for syntax highlighting usePrism: true, // Add custom scripts here that would be placed in <script> tags. scripts: [ 'https://buttons.github.io/buttons.js', { src: 'https://static.hotjar.com/c/hotjar-1021435.js?sv=6', async: true, }, ], // On page navigation for the current documentation page. onPageNav: 'separate', // No .html extensions for paths. cleanUrl: true, // Open Graph and Twitter card images. ogImage: 'img/apify_logo.png', twitterImage: 'img/apify_logo.png', // You may provide arbitrary config keys to be used as needed by your // template. For example, if you need your repo's URL... // repoUrl: 'https://github.com/facebook/test-site', repoUrl, }; module.exports = siteConfig;
JavaScript
0
@@ -3375,16 +3375,19 @@ %0A + // %7B%0A @@ -3384,24 +3384,27 @@ // %7B%0A + // src: 'h @@ -3458,24 +3458,27 @@ =6',%0A + // async: @@ -3486,24 +3486,27 @@ rue,%0A + // %7D,%0A %5D,%0A%0A
636f34f69114190adbd56e966bec272523b6911d
add update time for docs, defer attributes (#1885)
website/siteConfig.js
website/siteConfig.js
const parseYaml = require("js-yaml").safeLoad; const path = require("path"); const fs = require("fs"); const url = require("url"); function findMarkDownSync(startPath) { const result = []; const files = fs.readdirSync(path.join(__dirname, startPath)); files.forEach(val => { const fPath = path.join(startPath, val); const stats = fs.statSync(fPath); if (stats.isDirectory()) { result.push({ title: val, path: fPath, }); } }); return result; } const toolsMD = findMarkDownSync("../docs/tools/"); function loadMD(fsPath) { return fs.readFileSync(path.join(__dirname, fsPath), "utf8"); } function loadYaml(fsPath) { return parseYaml(fs.readFileSync(path.join(__dirname, fsPath), "utf8")); } // move to website/data later const users = loadYaml("./data/users.yml").map(user => ({ pinned: user.pinned, caption: user.name, infoLink: user.url, image: `/img/users/${user.logo}`, })); const sponsorsManual = loadYaml("./data/sponsors.yml").map(sponsor => ({ ...sponsor, image: `/img/sponsors/${sponsor.logo}`, })); const sponsorsDownloaded = require(path.join(__dirname, "/data/sponsors.json")); const sponsors = [ ...sponsorsManual, ...sponsorsDownloaded.map(sponsor => { // temporary fix for coinbase and webflow let tier = sponsor.tier; if (sponsor.id == 12671) { tier = "gold-sponsors"; } else if (sponsor.id == 5954) { tier = "silver-sponsors"; } let website = sponsor.website; if (typeof website == "string") { website = url.parse(website).protocol ? website : `http://${website}`; } else if (typeof sponsor.twitterHandle == "string") { website = `https://twitter.com/@${sponsor.twitterHandle}`; } else { website = `https://opencollective.com/${sponsor.slug}`; } return { type: "opencollective", tier, name: sponsor.name, url: website, image: sponsor.avatar || "/img/user.svg", description: sponsor.description, }; }), ]; // move to website/data later const videos = require(path.join(__dirname, "/data/videos.js")); const team = loadYaml("./data/team.yml"); const tools = loadYaml("./data/tools.yml"); const setupBabelrc = loadMD("../docs/tools/setup.md"); toolsMD.forEach(tool => { tool.install = loadMD(`${tool.path}/install.md`); tool.usage = loadMD(`${tool.path}/usage.md`); }); const DEFAULT_LANGUAGE = "en"; const GITHUB_URL = "https://github.com/babel/website"; const siteConfig = { useEnglishUrl: true, editUrl: `${GITHUB_URL}/blob/master/docs/`, title: "Babel", tagline: "The compiler for next generation JavaScript", url: "https://babeljs.io", baseUrl: "/", getDocUrl: (doc, language) => `${siteConfig.baseUrl}docs/${language || DEFAULT_LANGUAGE}/${doc}`, getPageUrl: (page, language) => `${siteConfig.baseUrl}${language || DEFAULT_LANGUAGE}/${page}`, getVideoUrl: (videos, language) => `${siteConfig.baseUrl}${language || DEFAULT_LANGUAGE}/${videos}`, organizationName: "babel", projectName: "babel", repoUrl: "https://github.com/babel/babel", headerLinks: [ { doc: "index", label: "Docs" }, { page: "setup", label: "Setup" }, { page: "repl", label: "Try it out" }, { page: "videos", label: "Videos" }, { blog: true, label: "Blog" }, { search: true }, { href: "https://opencollective.com/babel", label: "Donate" }, { page: "team", label: "Team" }, { href: "https://github.com/babel/babel", label: "GitHub" }, // { languages: true } ], users, sponsors, videos, team, tools, toolsMD, setupBabelrc, headerIcon: "img/babel.svg", footerIcon: "img/babel.svg", favicon: "img/favicon.png", colors: { primaryColor: "#323330", secondaryColor: "#323330", }, blogSidebarCount: "ALL", highlight: { theme: "tomorrow", hljs: hljs => { hljs.registerLanguage("json5", hljs => hljs.getLanguage("javascript")); }, }, scripts: [ "https://unpkg.com/[email protected]/dist/clipboard.min.js", "/js/code-blocks-buttons.js", "/scripts/repl-page-hacks.js", ], // stylesheets: [ "" ], // translationRecruitingLink: "https://crowdin.com/project/", algolia: { apiKey: "d42906b043c5422ea07b44fd49c40a0d", indexName: "babeljs", }, disableHeaderTitle: true, onPageNav: "separate", gaTrackingId: "UA-114990275-1", cleanUrl: true, // markdownPlugins: [], // cname }; module.exports = siteConfig;
JavaScript
0
@@ -3956,16 +3956,29 @@ s: %5B%0A + %7B%0A src: %22https: @@ -4037,41 +4037,117 @@ -%22/js/code-blocks-buttons.js%22,%0A + defer: true%0A %7D,%0A %7B%0A src: %22/js/code-blocks-buttons.js%22,%0A defer: true%0A %7D,%0A %7B%0A src: %22/s @@ -4174,16 +4174,40 @@ ks.js%22,%0A + defer: true%0A %7D%0A %5D,%0A / @@ -4490,16 +4490,42 @@ : true,%0A + enableUpdateTime: true,%0A // mar
40184a76a125f4f5dce9053dcb1c005324f3bcf0
Update main.js
js/main.js
js/main.js
$(document).ready(function(event){ $('#submit').click(function(event){ getData(); }); $('#formThing').submit(function(event){ event.preventDefault(); getData(); }); }); function getData(){ $.get('https://beam.pro/api/v1/channels/' + $('#inputText').val(), "", function(data){ var Avatar = "https://beam.pro/api/v1/users/" + data['user']['id'] + "/avatar"; var Username = data['user']['username']; var Followers = data['numFollowers']; var Partnered = data['partnered']; var Tetris = data['interactive']; var Audience = data['audience']; var Experience = data['user']['experience']; var lvls = data['user']['level']; var Sparks = data['user']['sparks']; var ChannelID = data['user']['id']; var Tetrisid = data['tetrisGameId']; var Coverid = data['coverId']; var Thumbnail = data['thumbnailId']; var StreamMute = data['preferences']['channel:player:muteOwn']; var FollowNotify = data['preferences']['channel:notify:follow']; var TotalViews = data['viewersTotal']; var te = data['transcodingEnabled']; var Online = data['online']; if(data['type'] != null){ var lastPlayed = data['type']['name']; }else{ var lastPlayed = "None"; } var joined = data['createdAt']; var html = '<center><img src="' + Avatar + '"width="100px" height="100px" style="border:3px solid #fff">'; html += '<h1><span class="label label-success">' + Username + '</h1>'; html += '<br><b><span class="label label-primary">Followers: ' + Followers+ '</b>'; html+= '<br><b>Partnered: </b>' + Partnered; html += '<br><b><span class="label label-primary">Partnered: ' + Partnered +'</b>'; html += '<br><b><span class="label label-primary">Total Views: ' + TotalViews +'</b>'; html += '<br><b><span class="label label-danger">---Points---</b>' html += '<br><b><span class="label label-warning">Level: ' + lvls +'</b>'; html += '<br><b>Experience: </b>' + Experience; html += '<br><b>Sparks: </b>' + Sparks; html += '<br><b><span class="label label-primary">---ID---</b>' html += '<br><b>Tetris Game ID: </b>' + Tetrisid; html += '<br><b>Channel ID: </b>' + ChannelID; html += '<br><b>Cover ID: </b>' + Coverid; html += '<br><b>Thumbnail ID: </b>' + Thumbnail; html += '<br><b><span class="label label-primary">---Preference---</b>' html += '<br><b>interactive: </b>' + Tetris; html += '<br><b>Audience: </b>' + Audience; html += '<br><b>StreamMute: </b>' + StreamMute; html += '<br><b>transcoding: </b>' + te; html += '<br><b><span class="label label-primary">------------</b>' html += "<br>"; if(Online){ html += '<br><b><font color="White"><a href="https://beam.pro/' + Username + '">Online</a></font></b>'; }else{ html += '<br><b><font color="red">Offline</font></b>'; } html+= '<br><b><span class="label label-primary">Last Played:'+lastPlayed+'</b>'; html += '<br><b><span class="label label-primary>Joined on: '+joined+' </b>'.replace('T', ' at '); $('.profile').html(html); }).fail(function(data){ html = '<p><span class="label label-warning"style="color: black;">A Beam user with that name does not exist.'; $('.profile').html(html); return; });; }
JavaScript
0.000001
@@ -1708,62 +1708,8 @@ %3E';%0A - html+= '%3Cbr%3E%3Cb%3EPartnered: %3C/b%3E' + Partnered;%0A @@ -2078,16 +2078,50 @@ '%3Cbr%3E%3Cb%3E +%3Cspan class=%22label label-warning%22%3E Experien @@ -2120,28 +2120,24 @@ Experience: -%3C/b%3E ' + Experien @@ -2134,24 +2134,32 @@ + Experience + +'%3C/b%3E' ;%0A h @@ -2177,16 +2177,50 @@ %3E%3Cb%3E +%3Cspan class=%22label label-warning%22%3E Sparks: %3C/b%3E @@ -2215,20 +2215,16 @@ Sparks: -%3C/b%3E ' + Spar @@ -2225,16 +2225,24 @@ + Sparks + +'%3C/b%3E' ;%0A
3a848817b3c28d52247b3e54afe2af09296a443c
Fix performance start point.
js/page.js
js/page.js
function samplesToTimeouts(samples) { var timeouts = samples.slice(); for (var i = 1; i < timeouts.length; ++i) { timeouts[i-1] = timeouts[i] - timeouts[i-1]; } timeouts.pop(); return timeouts; } function getAverageTimeout(samples, numberOfSamples) { "use strict"; var timeouts = samplesToTimeouts(samples.slice(samples.length - numberOfSamples)); return timeouts.reduce(function(a, b) { return a + b; }) / timeouts.length; } function getDelaySamples() { "use strict"; var N_SAMPLES = 20; var TIMEOUT_VALUE = 5; var MAXIMUM_TIMEOUT = TIMEOUT_VALUE * 1.1; var samples = []; samples.push(performance.now()); var callback = function() { samples.push(performance.now()); if (samples.length >= N_SAMPLES && getAverageTimeout(samples, N_SAMPLES) <= MAXIMUM_TIMEOUT) { var marker = samples.length - N_SAMPLES; var timeouts = samplesToTimeouts(samples); var data = []; ref.close(); samples = samples.slice(1); for (var i = 0; i < samples.length; ++i) { data.push({"x": i, "timeout": timeouts[i]}); } MG.data_graphic({ title: "Page load timings", data: data, width: 750, height: 150, target: "#plot", min_x: 0, max_x: samples.length * 1.2, min_y: 0, max_y: Math.max.apply(null, timeouts) * 1.2, x_accessor: "x", y_accessor: "timeout", markers: [{"x": marker, "label": (samples[marker]/1000).toFixed(2) + "ms"}], }); } else { setTimeout(callback, TIMEOUT_VALUE); } } var ref = window.open(document.getElementById("url").value); setTimeout(callback, TIMEOUT_VALUE); }
JavaScript
0.000006
@@ -606,38 +606,60 @@ %0A%0A -samples.push(performance.now() +var startPoint = performance.now();%0A samples.push(0 );%0A%0A @@ -722,16 +722,29 @@ ce.now() + - startPoint );%0A i @@ -1489,17 +1489,16 @@ label%22: -( samples%5B @@ -1508,14 +1508,8 @@ ker%5D -/1000) .toF
d45117baac18cb9eaf5cfb3d7c02de1e7ddaf9ae
Fix issue with arguments when there is just one comment
js/post.js
js/post.js
function anchorActions() { var hashParam = window.location.hash; if (hashParam && hashParam === "#comment-added") { var commentAddedMsgJqElem = $('#comment-added-message'); commentAddedMsgJqElem.removeClass('invisible'); removeHash(); setTimeout(function() { commentAddedMsgJqElem.fadeTo('slow', 0); }, 10000); } else { $('#comment-added-message').addClass('invisible'); } } function updateCommentsView(commentsArguments, jqElem, commentsWrapperJqElem) { var commentsHtml = []; for(var iComment = 0; iComment < commentsArguments.length; iComment++) { var commentResponse = commentsArguments[iComment]; if (commentResponse[1] !== 'success') continue; var nameMessageTimestamp = commentResponse[0].split('name:')[1].split('message:'); nameMessageTimestamp = [ nameMessageTimestamp[0] ].concat(nameMessageTimestamp[1].split('date:')); var commentName = nameMessageTimestamp[0].trim(); var commentMessage = nameMessageTimestamp[1].trim(); commentMessage = commentMessage.replace(/"/g, '').replace(/\\r?\\n/g, '<br/>'); var commentDate = new Date(nameMessageTimestamp[2] * 1000).toLocaleString(); commentsHtml.push( '<li>\n' + '\t<span class="grey-text">\n' + '\t\t<i class="fa fa-comment-o medium left" aria-hidden="true"></i>\n' + '\t\t' + commentName + ':\n' + '\t</span><br/>\n' + '\t' + commentMessage + '\n' + '\t<br/><small class="grey-text">' + '<time pubdate datetime="'+commentDate+'">'+commentDate+'</time></small>\n'+ '</li>\n' ); } commentsWrapperJqElem.html(commentsHtml.join('')); jqElem.removeClass('faster-spin'); } function refreshComments(jqElem, commentsWrapperJqElem) { jqElem.addClass('faster-spin'); var folderPath = '/comments/sample-post/'; $.ajax({ url: folderPath, cache: false }) .done(function(data) { if (data && data.indexOf('<li') > 0) { var items = data.split('<ul>')[1].split('</ul')[0].split('href="'); var jqXhrs = []; for (var iItem = 1; iItem < items.length; iItem++) { var filePath = folderPath + items[iItem].split('"')[0]; jqXhrs.push($.ajax({ url: filePath, cache: false })); } $.when.apply($, jqXhrs) .done(function() { updateCommentsView(arguments, jqElem, commentsWrapperJqElem); }) .fail(function(error) { console.log('refreshComments contents error', error); commentsWrapperJqElem.html( '<li><i class="grey-text">Unable to load comments</i></li>'); jqElem.removeClass('faster-spin'); }); } else { commentsWrapperJqElem.html( '<li><i class="grey-text">No comments</i></li>'); jqElem.removeClass('faster-spin'); } }) .fail(function(error) { console.log('refreshComments error', error); commentsWrapperJqElem.html( '<li><i class="grey-text">Unable to load comments</i></li>'); jqElem.removeClass('faster-spin'); }); } function refreshCommentsListener() { refreshComments($(this), $('#comments-wrapper')); } var commentJqElem; function customInit() { var refreshCommentsElem = $('.refresh-comments'); refreshCommentsElem.click(refreshCommentsListener); refreshComments(refreshCommentsElem, $('#comments-wrapper')); $('#commenter-name').change(trimValueListener); $('#commenter-message').change(trimValueListener); }
JavaScript
0.000001
@@ -2208,17 +2208,51 @@ iew( -arguments +jqXhrs.length %3E 1 ? arguments : %5Barguments%5D , jq
4f477fc62f916489eb4d7f9e749cb51da53550a0
add tests with empty value to utils-iterate
tests/utils-iterate.js
tests/utils-iterate.js
"use strict"; var _ = require('lodash'); var iterate = require('../lib/utils/iterate'); var obj = {a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, k: 10}; var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; module.exports = { 'iterate array - nothing to iterate': function (test) { var len = 0; var arr = []; var count = 0; iterate.array(arr, function (value, index, done) { count++; done(); }, function (err) { test.strictEqual(count, len); test.done(err); }); }, 'iterate array - across all items of array': function (test) { var len = arr.length; var keys = _.keys(arr); var count = 0; var _keys = []; iterate.array(arr, function (value, index, done) { count++; _keys.push(index); done(); }, function (err) { test.strictEqual(count, len); test.deepEqual(keys, _keys); test.done(err); }); }, 'iterate array - interrupt by error': function (test) { var len = arr.length; var count = 0; iterate.array(arr, function (value, index, done) { count++; done(count >= len/2 ? true : null); }, function (err) { test.strictEqual(count, len/2); test.ok(typeof err === 'boolean'); test.done(err instanceof Error ? err : null); }); }, 'iterate object - nothing to iterate': function (test) { var obj = {}; var len = _.size(obj); var count = 0; iterate.object(obj, function (value, index, done) { count++; done(); }, function (err) { test.strictEqual(len, count); test.done(err); }); }, 'iterate object - across all items of object': function (test) { var len = _.size(obj); var count = 0; iterate.object(obj, function (value, index, done) { count++; done(); }, function (err) { test.strictEqual(count, len); test.done(err); }); }, 'iterate object - interrupt by error': function (test) { var len = _.size(obj); var count = 0; iterate.object(obj, function (value, index, done) { count++; done(count >= len/2 ? true : null); }, function (err) { test.strictEqual(count, len/2); test.ok(typeof err === 'boolean'); test.done(err instanceof Error ? err : null); }); } };
JavaScript
0
@@ -478,32 +478,291 @@ rr);%0A%09%09%7D);%0A%09%7D,%0A%0A +%09'iterate array - not array': function (test) %7B%0A%09%09var len = 0;%0A%09%09var arr = null;%0A%09%09var count = 0;%0A%09%09iterate.array(arr, function (value, index, done) %7B%0A%09%09%09count++;%0A%09%09%09done();%0A%09%09%7D, function (err) %7B%0A%09%09%09test.strictEqual(count, len);%0A%09%09%09test.done(err);%0A%09%09%7D);%0A%09%7D,%0A%0A %09'iterate array @@ -1458,32 +1458,304 @@ ll);%0A%09%09%7D);%0A%09%7D,%0A%0A +%09'iterate object - not object': function (test) %7B%0A%09%09var obj = null;%0A%09%09var len = _.size(obj);%0A%09%09var count = 0;%0A%09%09iterate.object(obj, function (value, index, done) %7B%0A%09%09%09count++;%0A%09%09%09done();%0A%09%09%7D, function (err) %7B%0A%09%09%09test.strictEqual(len, count);%0A%09%09%09test.done(err);%0A%09%09%7D);%0A%09%7D,%0A%0A %09'iterate object
fe4d986b1546c01d39a655f3992ce1d306c8ef50
Update compare.js
tests/utils/compare.js
tests/utils/compare.js
/* global XMLHttpRequest, expect */ function loadBinaryResource (url, unicodeCleanUp) { const req = new XMLHttpRequest() req.open('GET', url, false) // XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com] req.overrideMimeType('text\/plain; charset=x-user-defined'); req.send(null) if (req.status !== 200) { throw new Error('Unable to load file'); } var responseText = req.responseText; var responseTextLen = req.responseText.length; var StringFromCharCode = String.fromCharCode; if (unicodeCleanUp === true) { var i = 0; for (i = 0; i < responseText.length; i += 1) { byteArray.push(StringFromCharCode(responseText.charCodeAt(i) & 0xff)) } return byteArray.join(""); } return req.responseText; } function sendReference (filename, data) { const req = new XMLHttpRequest() req.open('POST', `http://localhost:9090/${filename}`, true) req.onload = e => { //console.log(e) } req.send(data) } const resetCreationDate = input => input.replace( /\/CreationDate \(D:(.*?)\)/, '/CreationDate (D:19871210000000+00\'00\'\)' ) /** * Find a better way to set this * @type {Boolean} */ window.comparePdf = (actual, expectedFile, suite, unicodeCleanUp) => { let pdf; unicodeCleanUp = unicodeCleanUp || true; try { pdf = loadBinaryResource(`/base/tests/${suite}/reference/${expectedFile}`, unicodeCleanUp) } catch (error) { sendReference(`/tests/${suite}/reference/${expectedFile}`, resetCreationDate(actual)) pdf = actual } const expected = resetCreationDate(pdf).trim() actual = resetCreationDate(actual.trim()) expect(actual).toEqual(expected) }
JavaScript
0.000001
@@ -866,17 +866,17 @@ 'POST', -%60 +' http://l @@ -893,18 +893,18 @@ 090/ -$%7B +'+ filename %7D%60, @@ -899,18 +899,16 @@ filename -%7D%60 , true)%0A @@ -1663,8 +1663,9 @@ ected)%0A%7D +%0A
c0624cd34ea365218bb9de1e5083cbc671299a7c
Update rect.js
js/rect.js
js/rect.js
function Rect() { this.x = Math.floor(Math.random() * (640 - 30));; this.y = Math.floor(Math.random() * (480 - 30));; this.velocity = Math.random() > 0.5 ? -1 : 1; this.veleftright = 0; }; Rect.prototype.draw = function(context) { context.fillRect(this.x, this.y, 30, 30); }; Rect.prototype.update = function() { if (this.y < 0) { this.velocity = 1; } else if (this.y > 450) { this.velocity = -1; } if(player.input.jump == true){ this.veleftright = -1; }else{ this.veleftright = 0; } if(player.input.right == true){ this.veleftright = 1; }else{ this.veleftright = 0; } this.y += this.velocity; this.x += this.veleftright; };
JavaScript
0
@@ -184,17 +184,18 @@ right = -0 +-1 ;%0A%7D;%0A%0ARe
5ddc8e783972fcec6f79af45b5d3d695f88376f2
Remove current if no video left
js/room.js
js/room.js
var player=null; var firebase = new Firebase('https://adr2370.firebaseio.com/'); var songdb = firebase.child('songs'); var playerdb = firebase.child('playerdb'); var commentdb = firebase.child('comments'); var currentdb = firebase.child('current'); var songs=new Array(); window.setInterval(function(){ if(player!=null) { if(player.getPlayerState()==1) { currentdb.child('time').once('value', function(dataSnapshot) { if(dataSnapshot.val()<player.getCurrentTime()) { currentdb.child('time').set(player.getCurrentTime()); } else if(Math.abs(dataSnapshot.val()-player.getCurrentTime())>0.10){ player.seekTo(dataSnapshot.val(),true); } }); } else { //currentdb.child('time').set(0); } } }, 1000); currentdb.on('child_changed', function(snapshot, prevChildName) { //CHANGE RATING OR SKIP VIDEO if(snapshot.name()=="rating") { setMeter(snapshot.val()); } else if(snapshot.name()=="skip"&&snapshot.val()==1) { nextVideo(); } else if(snapshot.name()=="play") { if(snapshot.val()==1) { player.playVideo(); } else if(snapshot.val()==2) { player.pauseVideo(); } } else if(snapshot.name()=="fullScreen"&&snapshot.val()==1) { currentdb.child('fullScreen').set(0); window.fullScreen(); } }); currentdb.on('child_added', function(snapshot, prevChildName) { //ADDED SONG if(snapshot.name()=="id") { startVideo(); } }); songdb.on('child_added', function(snapshot, prevChildName) { //ADDS SOMETHING TO QUEUE //snapshot.name() is youtube id, all else is below songs.push(snapshot.name()); $("#queue").append('<tr style=\"font-size:30px;line-height:normal;\" id="'+snapshot.name()+'"><td style="line-height: normal;">'+snapshot.child('name').val()+'<\/td><td style="line-height: normal;">'+snapshot.child('length').val()+'<\/td><td><img src=\"'+snapshot.child('thumbnail').val()+'\" height="225" width=225"><\/td><td style="line-height: normal;">'+snapshot.child('numViews').val()+'<\/tr>'); currentdb.on('value', function(snapshot, prevChildName) { if(snapshot.val()==null) { nextVideo(); } }); }); songdb.on('child_moved', function(snapshot, prevChildName) { //SWITCHES ORDER OF STUFF IN QUEUE //prevChildName is the name of the previous one, snapshot.name is the id of the snapshot if(prevChildName==null) { $("#topQueue").after($("#"+snapshot.name()).remove()); } else { $("#"+prevChildName).after($("#"+snapshot.name()).remove()); } }); playerdb.on('child_changed', function(snapshot, prevChildName) { player.setVolume(snapshot.val()); }); commentdb.on('child_added', function(snapshot, prevChildName) { //COMMENTS ADDED //snapshot.val() is each comment $("#comments").prepend("<p style=\"font-size:30px;line-height:normal;\">" + snapshot.val()+"<\/p>"); }); function startVideo() { //youtube video currentdb.once('value', function(dataSnapshot) { var id=dataSnapshot.child('id').val(); if(player==null) { player=new YT.Player('youtube', { height: '390', width: '640', videoId: id, playerVars: { autoplay:1, enablejsapi:1, modestbranding:1, rel:0, showinfo:0, iv_load_policy:3, volume:50, start:0 }, events: { 'onStateChange': onPlayerStateChange, //'onError': onError }}); } else { player.loadVideoById(id, 5, "large"); } $("#visuals canvas").hide(); $("#"+id).remove(); songdb.child(id).remove(); removeA(songs, id); }); } function nextVideo() { setMeter(0); $("#comments").html(""); commentdb.remove(); if(songs.length>0) { songdb.child(songs[0]).once('value', function(dataSnapshot) { currentdb.set(dataSnapshot.val()); currentdb.child('rating').set(0); currentdb.child('skip').set(0); currentdb.child('play').set(0); currentdb.child('fullScreen').set(0); currentdb.child('time').set(0); currentdb.child('id').set(songs[0]); }); } else { $("#youtube").replaceWith($('<div id="youtube"><\/div>')); player=null; } } function onPlayerStateChange(event) { if(event.data == 0) { nextVideo(); } else if(event.data == 1) { currentdb.child('play').set(1); currentdb.child('time').once('value', function(dataSnapshot) { if(dataSnapshot.val()<player.getCurrentTime()) { currentdb.child('time').set(player.getCurrentTime()); } else if(Math.abs(dataSnapshot.val()-player.getCurrentTime())>0.10){ player.seekTo(dataSnapshot.val(),true); } }); playerdb.child('volume').once('value', function(dataSnapshot) { player.setVolume(dataSnapshot.val()); }); } else if(event.data == 2) { currentdb.child('play').set(2); //currentdb.child('time').set(0); } } function onError(event) { nextVideo(); } function setMeter(rating) { if(rating>=6) { var x=500; } else if(rating<=-6) { var x=-500; } else { var x=rating*100; } var r=$("#meterRed"); var g=$("#meterGreen"); g.animate({width: (583+x)}, Math.abs(g.width()-(583+x))); r.animate({width: (583-x)}, Math.abs(r.width()-(583-x))); } function removeA(arr) { var what, a = arguments, L = a.length, ax; while (L > 1 && arr.length) { what = a[--L]; while ((ax= arr.indexOf(what)) !== -1) { arr.splice(ax, 1); } } return arr; }
JavaScript
0
@@ -3887,16 +3887,38 @@ iv%3E'));%0A +%09%09currentdb.remove();%0A %09%09player
cf0e022295541a037cdc438b1b16ba29005da744
Update tags.js
js/tags.js
js/tags.js
var audio = undefined; function parseQuery(q) { var stage1 = q.slice(1).split("&"); var stage2 = []; var stage3 = {}; for(var i=0;i<stage1.length;++i) { stage2[i] = stage1[i].split("="); stage3[stage2[i][0]] = stage2[i][1]; } return stage3; } var query = parseQuery(window.location.hash); if(query.lang == "scottish") { var head = document.getElementsByTagName('head')[0]; var link = document.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = '/css/lang/Scot.css'; link.media = 'all'; head.appendChild(link); var audio = document.createElement("audio"); audio.src = "audio/lang/SCOTscotlandforever.mp3"; audio.loop = true; audio.play(); var div = document.createElement("div"); div.innerHTML = '<img src="/img/lang/SCOTFlag.png" id="ImageOverlay">' document.body.appendChild(div); } else if(query.lang == "us") { var head = document.getElementsByTagName('head')[0]; var link = document.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = '/css/lang/us.css'; link.media = 'all'; head.appendChild(link); var div = document.createElement("div"); div.innerHTML = '<img src="/img/lang/USFlag.png" id="ImageOverlay">' document.body.appendChild(div); var source = []; source[0] = "audio/lang/USBrother/Brother1.mp3"; source[1] = "audio/lang/USBrother/Brother2.mp3"; source[2] = "audio/lang/USBrother/Brother3.mp3"; source[3] = "audio/lang/USBrother/Brother4.mp3"; source[4] = "audio/lang/USBrother/Brother5.mp3"; source[5] = "audio/lang/USBrother/Brother6.mp3"; source[6] = "audio/lang/USBrother/Brother7.mp3"; source[7] = "audio/lang/USBrother/Brother8.mp3"; source[8] = "audio/lang/USBrother/Brother9.mp3"; source[9] = "audio/lang/USBrother/Brother10.mp3"; source[10] = "audio/lang/USBrother/Brother11.mp3"; source[11] = "audio/lang/USBrother/Brother12.mp3"; source[12] = "audio/lang/USBrother/Brother13.mp3"; var audio = []; for(var i=0;i<13;++i) { audio[i] = document.createElement("audio"); audio[i].src = source[i]; audio[i].pause(); } var hoverfunc = function(){ audio[Math.floor(Math.random()*13)].play(); }; document.getElementById("first").onmouseover = hoverfunc; }
JavaScript
0.000001
@@ -2015,17 +2015,17 @@ i=0;i%3C1 -3 +2 ;++i)%0A
d5ac7e9fae4f863eaeb80b640b1747f94a9cbf60
add netzkerefresh fire event on store
lib/marty/javascript/overrides.js
lib/marty/javascript/overrides.js
Ext.define('Netzke.Grid.EventHandlers', { override: 'Netzke.Grid.EventHandlers', netzkeHandleItemdblclick: function(view, record) { if (this.editsInline) return; // inline editing is handled elsewhere // MONKEY: add view in form capability var has_perm = (this.permissions || {}); if (has_perm.read !== false && !has_perm.update) { this.doViewInForm(record); } else if (has_perm.update !== false) { this.doEditInForm(record); } }, netzkeReloadStore: function() { var store = this.getStore(); // MONKEY: add netzkereload event on store store.fireEvent('netzkereload'); // NETZKE'S HACK to work around buffered store's buggy reload() if (!store.lastRequestStart) { store.load(); } else store.reload(); }, });
JavaScript
0
@@ -776,12 +776,485 @@ );%0A %7D,%0A%7D);%0A +%0AExt.define('Ext.toolbar.Paging', %7B%0A override: 'Ext.toolbar.Paging',%0A%0A handleRefresh: Ext.emptyFn,%0A%0A doRefresh: function() %7B%0A var me = this,%0A current = me.store.currentPage;%0A%0A // MONKEY: add netzkerefresh to ExtJS paging toolbar refresh%0A // as beforechange is too generic%0A me.store.fireEvent('netzkerefresh', me);%0A%0A if (me.fireEvent('beforechange', me, current) !== false) %7B%0A me.store.loadPage(current);%0A%0A me.handleRefresh();%0A %7D%0A %7D%0A%7D);%0A
cc5f6a79bf080a4af3248f94604c869e67136e28
fix Incomplete path bug
lib/middleware/directory/index.js
lib/middleware/directory/index.js
/* ================================================================ * startserver by xdf(xudafeng[at]126.com) * * first created at : Mon Jun 02 2014 20:15:51 GMT+0800 (CST) * * ================================================================ * Copyright 2013 xdf * * Licensed under the MIT License * You may not use this file except in compliance with the License. * * ================================================================ */ "use strict"; var fs = require('fs'); var path = require('path'); var url = require('url'); var parse = url.parse; var join = path.join; var normalize = path.normalize; var basename = path.basename; var extname = path.extname; var minitpl = require('minitpl'); var mime = require('../static/mime'); var root = process.cwd(); module.exports = Directory; var template = path.join(__dirname, 'default.tpl'); template = fs.readFileSync(template, 'utf-8'); template = minitpl.compile(template); function fileFilter(files, p) { var list = []; var localPath = ''; var stat; var linkPath; files.forEach(function (i) { linkPath = path.join(p, i); localPath = root + linkPath; stat = fs.statSync(localPath); if(stat.isDirectory()){ i = i+ '/'; linkPath = linkPath + '/'; }; list.push({ name: i, path: path.join(p, i), lastModified: fs.statSync(localPath).mtime, size: fs.statSync(localPath).size }); }); return list; } function Directory(req, res, next) { var url = parse(req.url); var dir = decodeURIComponent(url.pathname); var localPath = normalize(join(root, dir)); var parentPath = normalize(dir.replace(basename(dir), '')); if (dir == '/') { parentPath = ''; } fs.stat(localPath, function (err, stat) { if (err && err.code === 'ENOENT') { return next(); } if (!stat.isDirectory()) { return next(); } if(indexRouter(res, localPath)){ return false; } fs.readdir(localPath, function (err, files) { if (err) return next(); files = files.sort(); files = fileFilter(files, dir); res.writeHead(200, {'Content-Type': 'text/html'}); res.write(template({ path: dir, parentDir: parentPath, list: files })); next(); }); }); } //index路由逻辑函数 function indexRouter(res, localPath){ var indexArray = ['index.html', 'startserver.js']; var indexPath = ''; var indexFile; for (var i = 0; i < 2; i++){ indexPath = localPath + indexArray[i]; //同步读取文件耗费一定时间 try{ indexFile = fs.readFileSync(indexPath, 'binary'); } catch (e){ } if(indexFile){ res.writeHead(200, {'Content-Type': mime.lookUp(extname(indexPath))}); res.write(indexFile, "binary"); res.end(); return false; } } return indexFile; }
JavaScript
0.000001
@@ -1251,17 +1251,16 @@ ';%0A %7D -; %0A%0A li @@ -1908,16 +1908,25 @@ ocalPath +, req.url ))%7B%0A @@ -2340,16 +2340,30 @@ ocalPath +, standardPath )%7B%0A var @@ -2396,22 +2396,17 @@ ', ' -startserver.js +index.htm '%5D;%0A @@ -2445,16 +2445,140 @@ xFile;%0A%0A + if(localPath.slice(-1) !== '/')%7B%0A res.writeHead(302, %7B%0A 'Location': standardPath+ '/'%0A %7D);%0A res.end();%0A %7D%0A%0A for (v
70dcdd7a5010a7da316c2c239ebf0e3c8f5136e9
Fix outdated comment, let the code speak for itself
jquery.cookie.js
jquery.cookie.js
/*jshint eqnull:true */ /*! * jQuery Cookie Plugin v1.2 * https://github.com/carhartl/jquery-cookie * * Copyright 2011, Klaus Hartl * Dual licensed under the MIT or GPL Version 2 licenses. * http://www.opensource.org/licenses/mit-license.php * http://www.opensource.org/licenses/GPL-2.0 */ (function ($, document, undefined) { var pluses = /\+/g; function raw(s) { return s; } function decoded(s) { return decodeURIComponent(s.replace(pluses, ' ')); } var config = $.cookie = function (key, value, options) { // key and at least value given, set cookie... if (value !== undefined) { options = $.extend({}, $.cookie.defaults, options); if (value === null) { options.expires = -1; } if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setDate(t.getDate() + days); } value = config.json ? JSON.stringify(value) : String(value); return (document.cookie = [ encodeURIComponent(key), '=', config.raw ? value : encodeURIComponent(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } // key and possibly options given, get cookie... var decode = config.raw ? raw : decoded; var cookies = document.cookie.split('; '); for (var i = 0, parts; (parts = cookies[i] && cookies[i].split('=')); i++) { if (decode(parts.shift()) === key) { var cookie = decode(parts.join('=')); return config.json ? JSON.parse(cookie) : cookie; } } return null; }; $.cookie.defaults = {}; $.removeCookie = function (key, options) { if ($.cookie(key, options) !== null) { $.cookie(key, null, options); return true; } return false; }; })(jQuery, document);
JavaScript
0.000001
@@ -534,51 +534,13 @@ %09// -key and at least value given, set cookie... +write %0A%09%09i @@ -1317,53 +1317,12 @@ %09// -key and possibly options given, get cookie... +read %0A%09%09v
2b21e5efcefb6b0d44cc1d387d393bcd023b4818
Declare options variable
poke.io.js
poke.io.js
var request = require('request'); var geocoder = require('geocoder'); var Logins = require('./logins'); var fs = require('fs'); var EventEmitter = require('events').EventEmitter; var api_url = 'https://pgorelease.nianticlabs.com/plfe/rpc'; var login_url = 'https://sso.pokemon.com/sso/login?service=https%3A%2F%2Fsso.pokemon.com%2Fsso%2Foauth2.0%2FcallbackAuthorize'; var login_oauth = 'https://sso.pokemon.com/sso/oauth2.0/accessToken'; var ProtoBuf = require('protobufjs'); var builder = ProtoBuf.loadProtoFile('pokemon.proto'); if (builder == null) { builder = ProtoBuf.loadProtoFile('./node_modules/pokemon-go-node-api/pokemon.proto'); } var pokemonProto = builder.build(); var RequestEnvelop = pokemonProto.RequestEnvelop; var ResponseEnvelop = pokemonProto.ResponseEnvelop; function Pokeio() { var self = this; var events; self.events = new EventEmitter(); self.j = request.jar(); self.request = request.defaults({ jar: self.j }); self.playerInfo = { 'accessToken': '', 'debug': true, 'latitude': 0, 'longitude': 0, 'altitude': 0, 'apiEndpoint': '' }; self.DebugPrint = function(str) { if (self.playerInfo.debug == true) { //self.events.emit('debug',str) console.log(str); } }; function api_req(api_endpoint, access_token, req, callback) { // Auth var auth = new RequestEnvelop.AuthInfo({ 'provider': 'ptc', 'token': new RequestEnvelop.AuthInfo.JWT(access_token, 59) }); var f_req = new RequestEnvelop({ 'unknown1': 2, 'rpc_id': 8145806132888207460, 'requests': req, 'latitude': self.playerInfo.latitude, 'longitude': self.playerInfo.longitude, 'altitude': self.playerInfo.altitude, 'auth': auth, 'unknown12': 989 }); var protobuf = f_req.encode().toBuffer(); options = { url: api_endpoint, body: protobuf, encoding: null, headers: { 'User-Agent': 'Niantic App' } }; self.request.post(options, function(e, r, body) { if (r == undefined || r.body == undefined) { console.log('[!] RPC Server offline'); return callback(new Error('RPC Server offline')); } try { var f_ret = ResponseEnvelop.decode(r.body); } catch (e) { if (e.decoded) { // Truncated console.log(e); f_ret = e.decoded; // Decoded message with missing required fields } } return callback(null, f_ret); }); } self.GetAccessToken = function(user, pass, callback) { self.DebugPrint('[i] Logging with user: ' + user); Logins.PokemonClub(user, pass, self, function(err, token) { if (err) { return callback(err); } self.playerInfo.accessToken = token; callback(null, token); }); }; self.GetApiEndpoint = function(callback) { var req = []; req.push( new RequestEnvelop.Requests(2), new RequestEnvelop.Requests(126), new RequestEnvelop.Requests(4), new RequestEnvelop.Requests(129), new RequestEnvelop.Requests(5, new RequestEnvelop.Unknown3('4a2e9bc330dae60e7b74fc85b98868ab4700802e')) ); api_req(api_url, self.playerInfo.accessToken, req, function(err, f_ret) { if (err) { return callback(err); } var api_endpoint = 'https://' + f_ret.api_url + '/rpc'; self.playerInfo.apiEndpoint = api_endpoint; self.DebugPrint('[i] Received API Endpoint: ' + api_endpoint); callback(null, api_endpoint); }); }; self.GetProfile = function(callback) { var req = new RequestEnvelop.Requests(2); api_req(self.playerInfo.apiEndpoint, self.playerInfo.accessToken, req, function(err, f_ret) { if (err) { return callback(err); } if (f_ret.payload[0].profile) { self.DebugPrint('[i] Logged in!'); } callback(null, f_ret.payload[0].profile); }); }; self.GetLocation = function(callback) { geocoder.reverseGeocode(self.playerInfo.latitude, self.playerInfo.longitude, function(err, data) { console.log('[i] lat/long/alt: ' + self.playerInfo.latitude + ' ' + self.playerInfo.longitude + ' ' + self.playerInfo.altitude); if (data.status == 'ZERO_RESULTS') { return callback(new Error('location not found')); } callback(null, data.results[0].formatted_address); }); }; self.GetLocationCoords = function() { var coords = { latitude: self.playerInfo.latitude, longitude: self.playerInfo.longitude, altitude: self.playerInfo.altitude, }; return coords; }; self.SetLocation = function(locationName, callback) { geocoder.geocode(locationName, function(err, data) { if (err || data.status == 'ZERO_RESULTS') { return callback(new Error('location not found')); } self.playerInfo.latitude = data.results[0].geometry.location.lat; self.playerInfo.longitude = data.results[0].geometry.location.lng; var coords = { latitude: self.playerInfo.latitude, longitude: self.playerInfo.longitude, altitude: self.playerInfo.altitude, }; callback(null, coords); }); }; self.SetLocationCoords = function(coords) { if (!coords) { throw new Error('Coords object'); } self.playerInfo.latitude = coords.latitude ? coords.latitude : self.playerInfo.latitude; self.playerInfo.longitude = coords.longitude ? coords.longitude : self.playerInfo.longitude; self.playerInfo.altitude = coords.altitude ? coords.altitude : self.playerInfo.altitude; var coordinates = { latitude: self.playerInfo.latitude, longitude: self.playerInfo.longitude, altitude: self.playerInfo.altitude, }; return coordinates; }; } module.exports = new Pokeio(); module.exports.Pokeio = Pokeio;
JavaScript
0.000007
@@ -1982,16 +1982,20 @@ +var options
87f0540ac2804f3e96445ff1b7de5930ce46b101
update statements to ES6
workflow/basicTasks/merge.js
workflow/basicTasks/merge.js
/** * Tencent is pleased to support the open source community by making QMUI Web available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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. */ // 合并变更文件 const path = require('path'); const argv = require('yargs').argv; const through = require('through2'); const minimatch = require('minimatch'); module.exports = (gulp, mix) => { const taskName = 'merge'; const mergeReference = function (rules) { // 基于 https://github.com/aDaiCode/gulp-merge-link rules = rules || []; const linkRegex = /<link(?:\s+|\s+.+\s+)href\s*=\s*["']?(.+\.css).*?>/g; const scriptRegex = /<script(?:\s+|\s+.+\s+)src\s*=\s*["']?(.+\.js).*?script\s*>/g; const linkTemplate = function (href) { return '<link rel="stylesheet" href="' + href + '"/>'; }; const scriptTemplate = function (src) { return '<script type="text/javascript" src="' + src + '"></script>'; }; const getReference = function (reg, contents) { let result, references = []; // noinspection JSAssignmentUsedAsCondition while (result = reg.exec(contents)) { references.push({ match: result[0], url: result[1].trim().replace(/^\.\//, '') }); } return references; }; const getTemplate = function (url) { const isScript = /\.js$/.test(url); if (isScript) { return scriptTemplate(url); } else { return linkTemplate(url); } }; return through.obj(function (file, encoding, callback) { if (file.isNull() || file.isStream()) { return callback(null, file); } let contents = String(file.contents); let references = [], replaceList = [], flag = {}; // 获取所有引用 references = references.concat(getReference(linkRegex, contents)).concat(getReference(scriptRegex, contents)); // 循环所有引用,检测是否需要进行处理 for (let key in references) { let reference = references[key]; for (let targetUrl in rules) { // 把引用与传入的合并规则进行对比,把命中规则的引用进行合并处理 if (!rules.hasOwnProperty(targetUrl)) { break; } let sourceUrls = rules[targetUrl]; const sourceUrlFound = sourceUrls.find(sourceUrl => { sourceUrl = sourceUrl.trim().replace(/^\.\//, ''); return minimatch(reference.url, sourceUrl); }); if (sourceUrlFound) { replaceList.push({ match: reference.match, replace: flag[targetUrl] ? '' : getTemplate(targetUrl) }); flag[targetUrl] = true; break; } } } if (argv.debug) { mix.util.log('Merge', file.path); } replaceList.map(replace => { contents = contents.replace(replace.match, replace.replace); }); file.contents = Buffer.from(contents); return callback(null, file); }); }; gulp.task(taskName, done => { // 读取合并规则并保存起来 let mergeRule; try { mergeRule = require('../../../qmui.merge.rule.js'); } catch (event) { mix.util.error('Merge', '没有找到合并规则文件,请按照 http://qmuiteam.com/web/scaffold.html#qui_scaffoldMerge 的说明进行合并规则配置'); } const replaceProjectParentDirectory = function (source) { // 转换为以项目根目录为开头的路径形式 const projectParentDirectory = path.resolve('../../..'); return source.replace(projectParentDirectory, '').replace(/^[\\\/]/, ''); }; // 合并文件 for (let sourceFile in mergeRule) { // 后面变更文件时,需要的是每个文件在 HTML 中书写的路径,即相对模板文件的路径 // 但对合并文件,即 concat 来说,需要的是文件相对 qmui_web 目录的路径,因此需要对合并的结果以及来源文件手工加上一个 '../' const resultFile = `../${sourceFile}`; // 合并的结果加上 '../' const resultFileName = path.basename(resultFile); const resultFilePath = path.dirname(resultFile); const value = mergeRule[sourceFile]; // 来源文件原始路径获取 let childFiles = [], childFilesString = ''; // 用于在 Log 中显示 // 遍历来源文件并给每个文件加上 '../' for (let index = 0; index < value.length; index++) { const childFilesRelative = `../${value[index]}`; childFiles.push(childFilesRelative); // 拼接源文件名用于 Log 中显示 if (index === 0) { childFilesString = replaceProjectParentDirectory(path.resolve(childFilesRelative)); } else { childFilesString = `${childFilesString}, ${replaceProjectParentDirectory(path.resolve(childFilesRelative))}`; } } const condition = file => { return file.path.toString().indexOf('.js') !== -1; }; gulp.src(childFiles) .pipe(mix.plugins.plumber({ errorHandler: error => { mix.util.error('Merge', error); mix.util.beep(); } })) .pipe(mix.plugins.concat(resultFileName)) .pipe(mix.plugins.if(condition, mix.plugins.uglify(), mix.plugins.cleanCss({compatibility: 'ie8'}))) .pipe(gulp.dest(resultFilePath)); mix.util.log('Merge', `文件 ${childFilesString} 合并压缩为 ${replaceProjectParentDirectory(path.resolve(path.join(resultFilePath, resultFileName)))}`); } // 变更文件引用路径 gulp.src(mix.config.paths.htmlResultPath + '/**/*.html') .pipe(mergeReference(mergeRule)) .pipe(mix.plugins.htmlmin({ removeComments: true, collapseWhitespace: true })) .pipe(gulp.dest(mix.config.paths.htmlResultPath)); mix.util.log('Merge', '文件合并变更已完成'); done(); }); // 任务说明 mix.addTaskDescription(taskName, '合并变更文件'); };
JavaScript
0.000001
@@ -943,24 +943,16 @@ e = -function ( rules -) + =%3E %7B%0A @@ -1245,23 +1245,15 @@ e = -function ( href -) + =%3E %7B%0A @@ -1364,22 +1364,14 @@ e = -function (src) +src =%3E %7B%0A @@ -1490,25 +1490,16 @@ erence = - function (reg, c @@ -1506,16 +1506,19 @@ ontents) + =%3E %7B%0A @@ -1919,22 +1919,14 @@ e = -function (url) +url =%3E %7B%0A @@ -2160,25 +2160,16 @@ ugh.obj( -function (file, e @@ -2186,16 +2186,19 @@ allback) + =%3E %7B%0A @@ -4327,25 +4327,17 @@ y = -function ( source -) + =%3E %7B%0A
b6053f4b2c4e4df2076d6661e091c7907d2eabbc
Update scripts.js
Resources/scripts.js
Resources/scripts.js
var path = location.pathname.replace(/\\/g, "/").replace("/C:/", "C:/").replace(/%20/g, " ").replace("Installer Compiler.hta", ""); var fso = new ActiveXObject("Scripting.FileSystemObject"); var installer; var files; window.onload = function() { log("Initializing..."); installer = document.getElementById("installer").contentDocument; files = JSON.parse(readFile("Resources/files.json")); for (var x = 0; x < files.to.length; x++) { preserveFileData(files.from[x], files.to[x]); } installer.getElementById("fName").innerText = files.fName; installer.getElementById("foldersList").innerText = JSON.stringify(files.folder); if (files.iType === "local") { installer.getElementById("netPath").innerText = "false"; installer.getElementById("netPath").parentElement.style.display = "none"; } else if (files.iType === "network") { installer.getElementById("locPath").innerText = "false"; installer.getElementById("locPath").parentElement.style.display = "none"; } var fileData = "<DOCTYPE html>" + installer.documentElement.outerHTML; saveFile(files.fName + ".hta", fileData); log("Completed!"); } function saveFile(path, data) { log("Saving " + path); var textFile = fso.CreateTextFile(path, true, true); textFile.Write(data); textFile.Close(); log("File saved."); } function readFile(fileName) { log("Opening " + path + fileName); var textFile = fso.OpenTextFile(path + fileName, 1, false, -1); var text = textFile.ReadAll(); textFile.Close(); log("File opened."); return text; } function preserveFileData(from, to) { var fileData = readFile("Files/" + from); var span = installer.createElement("SPAN"); span.innerText = fileData; span.dataset.to = to; span.setAttribute("class", "file"); installer.body.appendChild(span); } function log(text) { var h2 = document.createElement("H2"); h2.innerText = text; document.body.appendChild(h2); }
JavaScript
0.000002
@@ -632,16 +632,17 @@ s.folder +s );%0A if @@ -709,35 +709,45 @@ tPath%22). -innerText = +setAttribute(%22value%22, %22false%22 +) ;%0A in @@ -906,27 +906,37 @@ h%22). -innerText = +setAttribute(%22value%22, %22false%22 +) ;%0A
5139d56b681e59fb5bd409830d22837780cc0235
set default parameter.
lib/BlobObject.js
lib/BlobObject.js
/** * @module BlobObject * @private * @mixin * @description Exports BlobObject class. */ import Super from './Super'; import Promise from './Promise'; import constructors from './constants/constructors'; import { isArray, isFunction, toStringTag, Symbol, defineProperties } from './helpers'; /** * @typedef {{ buffer: String, binary: String, dataURL: String, text: String }} methods * @private * @description List of read blob methods. */ const methods = { buffer: 'ArrayBuffer', binary: 'BinaryString', dataURL: 'DataURL', text: 'Text' }; const URL = global.URL; /** * @typedef {('buffer'|'binary'|'dataURL'|'text')} ReadBlobMethod * @public * @description Enum type of read blob methods. */ /** * @typedef {ArrayBuffer|ArrayBufferView|Blob|String} BlobParts * @public * @description Allowed blob parts. */ /** * @callback ReaderEventListener * @public * @param {Event} e - Fired event. * @param {FileReader} reader - FileReader. */ /** * @class BlobObject * @extends Super * @public * @param {Blob} blob - Blob to wrap. * @returns {BlobObject} Instance of BlobObject. * @description Wrap of a blob. * * @example * new BlobObject(new Blob(['{"foo":"bar"}'], { type: 'application/json' })); */ export class BlobObject extends Super { /** * @member BlobObject#$ * @type {Blob} * @public * @description Original Blob. */ /** * @member {String} BlobObject#dataURL * @type {String} * @public * @readonly * @description Returns dataURL representation of the blob. */ get dataURL() { return URL.createObjectURL(this.$); } /** * @method BlobObject#readAs * @public * @param {ReadBlobMethod} method - Method that is used for reading from blob. * @param {ReaderEventListener} [progress] - Progress listener. * @returns {Promise} Promise that could be aborted. * @description Method for reading from blobs. * * @example * new BlobObject(new Blob(['{"foo":"bar"}'], { type: 'application/json' })) * .readAs('text') * .then((value) => { * console.log(value); // '{"foo":"bar"}' * }); */ readAs(method, progress) { if (!methods[method]) { throw new Error('1st argument must be one of following values: buffer, binary, dataURL, text'); } let reader = new FileReader(); let toReject; if (isFunction(progress)) { reader.onprogress = function (e) { progress(e, this); }; } const promise = new Promise((resolve, reject) => { toReject = reject; reader.onerror = ({ target }) => { if (reader) { reject(target.error); } }; reader.onload = ({ target }) => { resolve(target.result); }; reader[`readAs${ methods[method] }`](this.$); }); promise.abort = function abort() { toReject(new Error('Reading was aborted')); reader.abort(); reader = null; return this; }; return promise; } /** * @method BlobObject#saveAs * @public * @param {String} [name] - Name that is used for saving file. * @returns {BlobObject} Returns this. * @description Method for saving blobs. * * @example * new BlobObject(new Blob(['{"foo":"bar"}'], { type: 'application/json' })) * .saveAs('blob.json'); */ saveAs(name = 'download') { const anchor = document.createElement('a'); anchor.href = this.dataURL; anchor.setAttribute('download', name); anchor.click(); return this; } } defineProperties(BlobObject.prototype, { [Symbol.toStringTag]: 'BlobObject' }); constructors[1].push({ check: (blob) => /^(Blob|File)$/.test(toStringTag(blob)), cls: BlobObject }); /** * @function blob * @public * @param {(BlobParts[]|BlobParts)} blobParts - Blob parts that are passed to * [Blob]{@link https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob} constructor. * @param {Object} [options] - Options that are passed to * [Blob]{@link https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob} constructor. * @returns {BlobObject} New instance of BlobObject. * @description Function for creating blobs not involving BlobObject and Blob constructors. */ export function blob(blobParts, options) { if (!isArray(blobParts)) { blobParts = [blobParts]; } return new BlobObject(new Blob(blobParts, options)); } export default BlobObject;
JavaScript
0
@@ -4236,16 +4236,21 @@ options + = %7B%7D ) %7B%0A if
000dc4d594f35ca92ee29d6ca718faeb76a16843
remove logging secret
scripts/deploy.js
scripts/deploy.js
const AWS = require('aws-sdk'); const s3 = new AWS.S3(); const fs = require('fs'); const glob = require('glob'); const mimeTypes = require('mime-types'); require('dotenv').config(); AWS.config = new AWS.Config({ credentials: new AWS.Credentials({ accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, }), region: 'ap-southeast-2' }); console.log(process.env.AWS_ACCESS_KEY_ID) glob('./public/**/*', {}, (err, files) => { files.forEach(file => { if (!fs.lstatSync(file).isDirectory()) { const fileContents = fs.readFileSync(`./${file}`); const fileMime = mimeTypes.lookup(file); s3.upload( { Bucket: 'lukeboyle.com', Key: file.replace('./public/', ''), Body: fileContents, ContentType: fileMime }, {partSize: 10 * 1024 * 1024, queueSize: 1}, (err, data) => { if (err) { throw new Error(err.message); } console.log(data); } ); } }); });
JavaScript
0.000265
@@ -382,52 +382,8 @@ );%0A%0A -console.log(process.env.AWS_ACCESS_KEY_ID)%0A%0A glob
b687a26c1519345e5e3beeb710753c3dab744d7f
Fix week 7 exercises
week-7/nums_commas.js
week-7/nums_commas.js
// Separate Numbers with Commas in JavaScript **Pairing Challenge** // I worked on this challenge with: Matthew O. // Pseudocode // input an integer // output a string of the integer with commas // steps // define a function that accepts an integer as argument // convert to array // //reverse // separate digits // add comma every 4th character starting from the end of the string // var reverseString = function(str) { // var newString = ""; // for (var i = str.length-1; i >= 0; i--) { // newString = newString.concat(charAt(i)); // } // } // reverseString("Does this work?"); // Initial Solution var commas = function(num) { var testArray = num.toString().split(""); //console.log(testArray) for (var i = testArray.length-3; i > 0; i -= 3) { testArray.splice(i, 0, ","); }; console.log(testArray.join("")); } commas(303945123) // // var array = [1,2,3,4,5]; // // console.log(array); // commas(12345); //console.log(arr[2]); // Refactored Solution // // Your Own Tests (OPTIONAL) // Reflection
JavaScript
0.000004
@@ -194,18 +194,16 @@ mmas%0A %0A - %0A // steps @@ -203,17 +203,16 @@ / steps%0A -%0A // defin @@ -387,16 +387,71 @@ string%0A%0A +// Just some practice code we were fiddling around with %0A// var @@ -652,16 +652,18 @@ ork?%22);%0A +%0A%0A // Initi @@ -675,16 +675,19 @@ lution%0A%0A +// var comm @@ -707,16 +707,19 @@ (num) %7B%0A +// var te @@ -754,16 +754,19 @@ it(%22%22);%0A +// //cons @@ -785,16 +785,19 @@ Array) %0A +// for @@ -843,16 +843,19 @@ -= 3) %7B%0A +// test @@ -884,14 +884,20 @@ );%0A%0A +// %7D; %0A +// co @@ -927,19 +927,25 @@ n(%22%22));%0A -%7D%0A%0A +// %7D%0A%0A// commas(3 @@ -958,145 +958,120 @@ 23)%0A +%0A%0A // -// var array = %5B1,2,3,4,5%5D;%0A// // console.log(array);%0A// commas(12345);%0A%0A%0A %0A %0A//console.log(arr%5B2%5D);%0A// Refactored Solution%0A%0A%0A%0A// +Refactored Solution%0A%0Avar commas = function(num) %7B%0A%09console.log(num.toLocaleString());%0A%7D%0A%0Acommas(303945123)%0A %0A%0A//
b1edbb66b7fdbcc278e5ebc47e7e5a7f77eb3bb0
revert change
src/server/services/loadFromCsvStream.js
src/server/services/loadFromCsvStream.js
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ const csv = require('csv'); /** * Function to load a CSV file into the database in a configurable manner. * Wraps all load operations in a transaction, so if one row fails no rows will be inserted. * @example * loadFromCsvStream( * &#9;stream, * &#9;row => new Reading(...), * &#9;(readings, tx) => Reading.insertAll(readings, tx) * ).then(() => log('Inserted!')); * @param stream the raw stream to load from * @param {function(Array.<*>, ...*): M} mapRowToModel A function that maps a CSV row (an array) to a model object * @param {function(Array.<M>, ITask): Promise<>} bulkInsertModels A function that bulk inserts an array of models using the supplied transaction * @param conn the database connection to use * @template M */ function loadFromCsvStream(stream, mapRowToModel, bulkInsertModels, conn) { return conn.tx(t => new Promise(resolve => { let rejected = false; const error = null; const MIN_INSERT_BUFFER_SIZE = 1000; let modelsToInsert = []; const pendingInserts = []; const parser = csv.parse(); function insertQueuedModels() { const insert = bulkInsertModels(modelsToInsert, t); pendingInserts.push(insert); modelsToInsert = []; } // Defines how the parser behaves when it has new data (models to be inserted) parser.on('readable', () => { // We can only get the next row once so we check that it isn't null at the same time that we assign it while ((row = parser.read()) !== null) { // tslint:disable-line no-conditional-assignment if (!rejected) { modelsToInsert.push(mapRowToModel(row)); } } if (!rejected) { if (modelsToInsert.length >= MIN_INSERT_BUFFER_SIZE) { insertQueuedModels(); } } }); parser.on('error', err => { if (!rejected) { resolve(t.batch(pendingInserts).then(() => Promise.reject(err))); } rejected = true; }); // Defines what happens when the parser's input stream is finished (and thus the promise needs to be resolved) parser.on('finish', () => { // Insert any models left in the buffer if (modelsToInsert.length > 0) { insertQueuedModels(); } // Resolve the promise, telling pg-promise to run the batch query and complete (or rollback) the // transaction. resolve(t.batch(pendingInserts).then(arg => { if (rejected) { return Promise.reject(error); } else { return Promise.resolve(arg); } })); }); stream.pipe(parser); })); } module.exports = loadFromCsvStream;
JavaScript
0.000002
@@ -1514,24 +1514,36 @@ e', () =%3E %7B%0A +%09%09%09let row;%0A %09%09%09// We can
dd23a6201b063704e6ce163f8a1cb01f0f57c45b
Implement just enough of connection for drive() to start accepting connections
lib/Connection.js
lib/Connection.js
/** * Turnpike plumbing. * * Connection objects are created by the Turnpike listener, and are passed to EndpointControllers during the routing * process. */ function Connection(req, res) { this.body = ''; /** * Makes this connection die immediately. * * @param status number HTTP Status code to return. */ this.die = function(status) { res.writeHead(code, {'Content-Type': 'text/plain'}); req.connection.destroy(); }; /** * Register a handler for the "end" event. I.e. when the full request body is received. * * @param callback Function to call when connection body is fully received */ this.end = function(callback) { }; return this; } module.exports = Connection;
JavaScript
0
@@ -207,16 +207,81 @@ = '';%0A%0A + req.on('data', function(chunk) %7B%0A this.body += chunk;%0A %7D)%0A%0A /**%0A @@ -730,16 +730,44 @@ back) %7B%0A + req.on('end', callback); %0A %7D;%0A%0A
35d77d1c289b7cd0564044b8025bfc8bcbd95e76
Allow passing in host and port for server connect, with a sensible default
lib/Connection.js
lib/Connection.js
var io = require("socket.io-client"); var mqtt = require("mqtt"); var util = require('util'); var EventEmitter = require('events').EventEmitter; function Connection(opt){ EventEmitter.call(this); this.options = opt || {}; // this.socket = io.connect(this.options.host, { // port: this.options.port // }); // this.socket = io.connect("localhost", { // port: 3000 // }); this.socket = io.connect("http://skynet.im", { port: 80 }); // mqttclient connection if (this.options.protocol == "mqtt") { this.mqttsettings = { keepalive: 1000, protocolId: 'MQIsdp', protocolVersion: 3, clientId: this.options.uuid } if (this.options.qos == undefined){ this.options.qos = 0; } try { // this.mqttclient = mqtt.createClient(1883, 'localhost', mqttsettings); this.mqttclient = mqtt.createClient(1883, 'mqtt.skynet.im', this.mqttsettings); this.mqttclient.subscribe(this.options.uuid, {qos: this.options.qos}); this.mqttclient.subscribe('broadcast', {qos: this.options.qos}); } catch(err) { console.log(err); } } this.setup(); } util.inherits(Connection, EventEmitter); Connection.prototype.setup = function(){ this.socket.once('connect', function(){ this.emit('connect'); if (this.options.protocol == "mqtt"){ this.mqttclient.on('message', this.emit.bind(this, 'message')); } else { this.socket.on('message', this.emit.bind(this, 'message')); } this.socket.on('config', this.emit.bind(this, 'config')); this.socket.on('disconnect', this.emit.bind(this, 'disconnect')); this.socket.on('identify', this.identify.bind(this)); this.socket.on('ready', this.emit.bind(this, 'ready')); this.socket.on('notReady', this.emit.bind(this, 'notReady')); }.bind(this)); return this; }; Connection.prototype.identify = function(){ this.socket.emit('identity', { uuid: this.options.uuid, token: this.options.token }); return this; }; // Connection.prototype.send = function(data) { Connection.prototype.message = function(data) { // Send the API request to Skynet if (typeof data !== 'object'){ data = JSON.parse(data); } data.protocol = this.options.protocol; this.socket.emit('message', JSON.stringify(data)); if (this.options.protocol == "mqtt"){ // Publish to MQTT if(data.devices == "all" || data.devices == "*"){ this.mqttclient.publish('broadcast', JSON.stringify(data.message), {qos: this.options.qos}); } else { if( typeof data.devices === 'string' ) { devices = [ data.devices ]; } else { devices = data.devices; }; for (var i = 0; i < devices.length; i++) { this.mqttclient.publish(devices[i], JSON.stringify(data.message), {qos: this.options.qos}); }; } } return this; }; Connection.prototype.config = function(data, fn) { this.socket.emit('gatewayConfig', data, fn); return this; }; Connection.prototype.update = function(data, fn) { this.socket.emit('update', data, fn); return this; }; Connection.prototype.register = function(data, fn) { this.socket.emit('register', data, fn); return this; }; Connection.prototype.unregister = function(data, fn) { this.socket.emit('unregister', data, fn); return this; }; Connection.prototype.whoami = function(data, fn) { this.socket.emit('whoami', data, fn); return this; }; Connection.prototype.devices = function(data, fn) { this.socket.emit('devices', data, fn); return this; }; Connection.prototype.status = function(data) { this.socket.emit('status', data); return this; }; Connection.prototype.subscribe = function(data, fn) { this.socket.emit('subscribe', data, fn); if (this.options.protocol == "mqtt") { this.mqttclient.subscribe(data.uuid, {qos: this.options.qos}); } return this; }; Connection.prototype.unsubscribe = function(data, fn) { this.socket.emit('unsubscribe', data, fn); if (this.options.protocol == "mqtt") { this.mqttclient.subscribe(data.uuid); } return this; }; Connection.prototype.authenticate = function(data, fn) { this.socket.emit('authenticate', data, fn); return this; }; Connection.prototype.events = function(data, fn) { this.socket.emit('events', data, fn); return this; }; Connection.prototype.close = function(){ return this; }; module.exports = Connection;
JavaScript
0
@@ -221,19 +221,16 @@ %7C%7C %7B%7D;%0A - // this.so @@ -268,101 +268,35 @@ host -, %7B%0A // port: this.options.port%0A // %7D);%0A // this.socket = io.connect(%22localhost + %7C%7C %22http://skynet.im %22, %7B%0A - // p @@ -304,80 +304,28 @@ rt: -3000%0A // %7D);%0A this.socket = io.connect(%22http://skynet.im%22, %7B%0A +this.options. port -: + %7C%7C 80%0A @@ -633,19 +633,16 @@ %7B%0A - // this.mq @@ -674,89 +674,63 @@ ent( -1883, 'localhost', mqttsettings);%0A this.mqttclient = mqtt.createClient(1883, +this.options.mqttport %7C%7C 1883, this.options.mqtthost %7C%7C 'mq
a8fb8884fd7f9c39b3c61cc8b18bc3b43bdcfe80
split out query-string and add to request object as "params"
lib/HttpServer.js
lib/HttpServer.js
'use strict' const http = require('http') module.exports = class HttpServer extends http.Server { constructor ({ name, port=8080, mount, middleware, indexFiles, restApiEndpoints }) { super() Object.assign(this, { name }) this.on('request', (req, res) => { const additionalRequestAndResponseProperties = { // 'cause it's just too hard to choose which one to add these to mount, indexFiles, restApiEndpoints } Object.assign(req, additionalRequestAndResponseProperties) Object.assign(res, additionalRequestAndResponseProperties, { setStatus (statusCode) { this.statusCode = statusCode } }) const middlewareGenerator = (function* () { for (let i = 0; i < middleware.length; i++) { yield middleware[i](req, res, () => { // need to stagger this to avoid "generator already running" error process.nextTick(() => { if (middlewareGenerator.next().done) { res.end() } }) }) } })() // init the generator middlewareGenerator.next() }) this.listen(port) } }
JavaScript
0.000001
@@ -13,16 +13,19 @@ %0A%0Aconst +%0A http = r @@ -39,16 +39,59 @@ 'http') +%0A,%0A querystring = require('querystring')%0A; %0A%0Amodule @@ -521,16 +521,141 @@ %7D%0A%0A + // split off the params%0A const %5B url, params %5D = req.url.split('?')%0A // restore req.url%0A req.url = url%0A%0A Ob @@ -709,16 +709,71 @@ operties +, %7B%0A params: querystring.parse(params) %0A %7D )%0A%0A
a877c6bc68ef601a6e14f34bae32640a6d063254
Fix syntax error (missing ')')
local-cli/bundle.js
local-cli/bundle.js
var http = require('http'); var fs = require('fs'); var path = require('path'); var chalk = require('chalk'); var blacklist = require('../packager/blacklist.js'); var ReactPackager = require('../packager/react-packager'); var OUT_PATH = 'iOS/main.jsbundle'; function getBundle(flags) { var outPath = flags.out ? flags.out : OUT_PATH; var projectRoots = [path.resolve(__dirname, '../../..')]; if (flags.root) { projectRoots.push(path.resolve(flags.root)); } var assetRoots = [path.resolve(__dirname, '../../..')]; if (flags.assetRoots) { assetRoots = assetRoots.concat(flags.assetRoots.split(",").map(function(root) { return path.resolve(root); }); } var options = { projectRoots: projectRoots, transformModulePath: require.resolve('../packager/transformer.js'), assetRoots: assetRoots, cacheVersion: '2', blacklistRE: blacklist('ios'), }; var url = '/index.ios.bundle?dev=' + flags.dev; console.log('Building package...'); ReactPackager.buildPackageFromUrl(options, url) .done(function(bundle) { console.log('Build complete'); fs.writeFile(outPath, bundle.getSource({ inlineSourceMap: false, minify: flags.minify }), function(err) { if (err) { console.log(chalk.red('Error saving bundle to disk')); throw err; } else { console.log('Successfully saved bundle to ' + outPath); } }); }); } function showHelp() { console.log([ 'Usage: react-native bundle [options]', '', 'Options:', ' --dev\t\tsets DEV flag to true', ' --minify\tminify js bundle', ' --root\t\tadd another root(s) to be used in bundling in this project', ' --assetRoots\t\tspecify the root directories of app assets', ' --out\t\tspecify the output file', ].join('\n')); process.exit(1); } module.exports = { init: function(args) { var flags = { help: args.indexOf('--help') !== -1, dev: args.indexOf('--dev') !== -1, minify: args.indexOf('--minify') !== -1, root: args.indexOf('--root') !== -1 ? args[args.indexOf('--root') + 1] : false, assetRoots: args.indexOf('--assetRoots') !== -1 ? args[args.indexOf('--assetRoots') + 1] : false, out: args.indexOf('--out') !== -1 ? args[args.indexOf('--out') + 1] : false, } if (flags.help) { showHelp(); } else { getBundle(flags); } } }
JavaScript
0.998827
@@ -670,24 +670,25 @@ oot);%0A %7D) +) ;%0A %7D%0A%0A%0A va
df996c24e309ea7316016219ae167a056af47611
Add save command
commands/index.js
commands/index.js
const prettyJSON = require('../utils/prettyJSON'), Promise = require('bluebird'), fs = Promise.promisifyAll(require('fs')), child_process = require('child_process'), R = require('ramda'); module.exports = ({ rabbitMqClient, vorpal }) => { vorpal .command('next') .description('Fetch next message in queue') .action((args, cb) => { return rabbitMqClient .nextMessage() .then(msg => { if (msg) { console.log(msg.fields); } else { console.log('Queue empty'); } }); }); vorpal .command('print [id]') .description('Print current message') .action((args, cb) => { return rabbitMqClient .getMessage(args.id) .then(R.pipe(prettyJSON, console.log)); }); vorpal .command('props [id]') .option('-n, --name <name>', 'Print only specified property') .description('Print message properties') .action((args, cb) => { return rabbitMqClient .getMessage(args.id) .then(R.pipe(args.options.name ? R.path([ 'properties', args.options.name ]) : R.prop('properties'), prettyJSON, console.log)); }); vorpal .command('headers [id]') .description('Print message headers') .action((args, cb) => { return rabbitMqClient .getMessage(args.id) .then(R.pipe(R.path([ 'properties', 'headers' ]), prettyJSON, console.log)); }); vorpal .command('list') .description('List all messages') .action((args, cb) => { return rabbitMqClient .getMessages() .then(R.pipe(R.map(R.pipe(R.pick([ 'id', 'queue' ]), prettyJSON)), R.values, R.join('\n'), console.log)); }); vorpal .command('skip') .option('-c, --count <count>', 'Number of messages to skip') .description('Skip messages') .action((args, cb) => { return rabbitMqClient .skipMessages(args.options.count || 1) .then(() => rabbitMqClient.nextMessage()) .then(msg => { if (msg) { console.log(msg.fields); } else { console.log('Queue empty'); } }); }); vorpal .command('enqueue <queue> [id]') .description('Enqueue a message on specified queue') .action((args, cb) => { return rabbitMqClient .getMessage(args.id) .then(msg => rabbitMqClient.enqueueMessage(msg, args.queue)); }); vorpal .command('ack [id]') .description('Ack message, dequeues it') .action((args, cb) => { return rabbitMqClient .getMessage(args.id) .then(msg => rabbitMqClient.ack(msg)); }); vorpal .command('retry [id]') .option('-n, --next <count>', 'Get next message(s) from queue and retry it(them)') .description('Retry current message') .action((args, cb) => { const retry = (msg) => { if (!msg) { console.log("No messages in queue"); return Promise.reject(); } if (R.complement(R.pathSatisfies(R.has('x-death'), [ 'properties', 'headers' ]))(msg)) { console.log('Not dead letter'); return Promise.reject(); } return rabbitMqClient .enqueueMessage( msg, R.path([ 'properties', 'headers', 'x-death', 0, 'queue' ])(msg) ) .then(() => rabbitMqClient.ack(msg)) .then(() => vorpal.log(`Retried ${msg.fields.deliveryTag}`)); }; if (args.options.next > 0) { return R.reduce( (promise) => promise.then(() => rabbitMqClient.nextMessage().then(retry)), Promise.resolve(), R.repeat(0, args.options.next) ); } else { return rabbitMqClient.getMessage(args.id).then(retry); } }); vorpal .command('edit [id]') .option('-e, --editor <editor>', 'Your master editor') .description('Edit current message') .action((args, cb) => { let editor = R.pathOr(process.env.EDITOR || 'vi', [ 'options', 'editor' ], args); return rabbitMqClient .getMessage(args.id) .then(msg => { let messageId = msg.properties.messageId || 'nomessageid'; let fileName = `funny-bunny-tempedit-${messageId}.json`; return fs.writeFileAsync(fileName, prettyJSON(msg)) .then(() => { return new Promise((resolve, reject) => { let proc = child_process.spawn(editor, [ fileName ], { stdio: 'inherit' }); proc.on('exit', (code, signal) => code === 0 ? resolve() : reject(code)); proc.on('error', reject); }); }) .then(() => fs.readFileAsync(fileName)) .then(buf => { rabbitMqClient.addMessage(JSON.parse(buf.toString())); return fs.unlinkAsync(fileName); }); }) }); vorpal .command('load <path>') .description('Load a JSON file as a message') .action((args, cb) => { return fs.readFileAsync(args.path) .then(buf => { rabbitMqClient.addMessage(JSON.parse(buf.toString())); }); }); return { rabbitMqClient, vorpal }; };
JavaScript
0.000003
@@ -3780,32 +3780,300 @@ %7D%0A %7D);%0A%0A + vorpal%0A .command('save %3Cpath%3E %5Bid%5D')%0A .description('Save current message to disk')%0A .action((args, cb) =%3E %7B%0A return rabbitMqClient%0A .getMessage(args.id)%0A .then(prettyJSON)%0A .then(msg =%3E fs.writeFileAsync(args.path, msg));%0A %7D);%0A%0A vorpal%0A .co
eb2b32f6da18044d05a9b571b680ba144a66d096
update url to download
data/fxqrl.js
data/fxqrl.js
'use strict'; self.port.on('update_image', function onUpdate(image) { var parser = new DOMParser(); var doc = parser.parseFromString(image, 'text/html'); var node = doc.firstChild; document.getElementById('qrcode').appendChild(node); });
JavaScript
0
@@ -162,29 +162,51 @@ var -node +img_el = doc. -firstChild +getElementsByTagName('img')%5B0%5D ;%0A @@ -240,28 +240,89 @@ code -').appendChild(node) +_dl').href = img_el.src;%0A document.getElementById('qrcode_img').src = img_el.src ;%0A%7D)
e7fb891ed6e3305aad4990849e33664d7f0ef13d
fix error with uninitialized local storage
js/background.js
js/background.js
var chmiPortalWebPageUrl = "http://portal.chmi.cz/files/portal/docs/uoco/web_generator/actual_hour_data_CZ.html" var chmiPortalJSONUrl = "http://portal.chmi.cz/files/portal/docs/uoco/web_generator/aqindex_cze.json" var stationCode; var periodInMinutes = 1 // SCHEDULING START function onInit() { updateIcon(); scheduleNextUpdate(); } function onAlarm(alarm) { if (alarm.name === 'station-data-changed') { updateIcon(); } else { chrome.storage.sync.get({ stationToMonitor: 'AKALA' }, function (items) { stationCode = items.stationToMonitor; }); getAirQualityJSON(); scheduleNextUpdate(); } } function scheduleNextUpdate() { chrome.alarms.create('refresh', { periodInMinutes: periodInMinutes }); } chrome.runtime.onInstalled.addListener(onInit); chrome.alarms.onAlarm.addListener(onAlarm); chrome.runtime.onStartup.addListener(function () { getAirQualityJSON(); }); // SCHEDULING END // ONCLICK START chrome.browserAction.onClicked.addListener(showNotification); chrome.notifications.onButtonClicked.addListener(openChmiPageEvent); // ONCLICK END function updateIcon() { var stationIndex = typeof localStorage.stationIndex !== 'undefined' ? localStorage.stationIndex : "?"; chrome.browserAction.setBadgeText({ text: stationIndex }); var iconColor = getIconColor(stationIndex); chrome.browserAction.setBadgeBackgroundColor({ color: iconColor }); } function getIconColor(stationIndex) { var color; switch (stationIndex) { case "1": color = "#C7EAFB"; break; case "2": color = "#9BD3AE"; break; case "3": color = "#FFF200"; break; case "4": color = "#FAA61A"; break; case "5": color = "#ED1C24"; break; case "6": color = "#671F20"; break; default: color = "#C7EAFB"; } return color; } function showNotification() { chrome.storage.sync.get( function () { var notification = getListNotification(); notif = chrome.notifications.create("AQnotifID", notification, function () { }); } ); } function openChmiPageEvent() { showChmiPortalWebPage(); } function getBasicNotification() { var stationData = JSON.parse(localStorage.stationData); var stationDataComponents = stationData.Components; var notificationMessage = ""; stationDataComponents.map(function (component) { notificationMessage = notificationMessage + component.Code + ": " + component.Ix + "; "; }); return { type: "basic", title: localStorage.stationName + " >>" + localStorage.stationIndex + "<<", iconUrl: chrome.runtime.getURL('images/icon_128.png'), message: notificationMessage }; } function getListNotification() { var stationData = JSON.parse(localStorage.stationData); var stationDataComponents = stationData.Components; var components = stationDataComponents.map(function (component) { return {title: component.Code + ": ", message: component.Ix.toString()}; }); return { type: "list", title: localStorage.stationName, iconUrl: chrome.runtime.getURL('images/icon_128.png'), message: "Overall quality index: " + localStorage.stationIndex, items: components, buttons: [{title:"overview"}] }; }
JavaScript
0.000002
@@ -286,24 +286,260 @@ onInit() %7B%0A + if (localStorage.stationData === undefined) %7B%0A localStorage.stationData = '%7B%22Components%22 : %5B%7B%22Code%22: %22CO%22, %22Ix%22: -1%7D%5D%7D';%0A %7D%0A if (localStorage.stationName === undefined) %7B%0A localStorage.stationName = %22N/A%22;%0A %7D%0A updateIc
f244c256df031751c0926c3d792d420189f4057d
remove console (#2)
lib/app.js
lib/app.js
'use strict'; const path = require('path'); const debug = require('debug')('mm'); const rimraf = require('rimraf'); const formatOptions = require('./format_options'); const apps = new Map(); module.exports = function(options) { options = formatOptions(options); console.log(options); if (options.cache && apps.has(options.baseDir)) { return apps.get(options.baseDir); } if (options.clean !== false) { rimraf.sync(path.join(options.baseDir, 'logs')); } const agent = getAgent(options); const app = getApp(Object.assign({}, options, {agent})); merge(app, agent); apps.set(options.baseDir, app); return app; }; function getApp(options) { debug('getApp from customEgg: %s', options.customEgg); const egg = require(options.customEgg); const MockApplication = extendsEggApplication(egg, options); return new MockApplication(options); } function getAgent(options) { debug('getAgent from customEgg: %s', options.customEgg); const egg = require(options.customEgg); const agent = new egg.Agent(options); return agent; } function extendsEggApplication(egg, options) { const symbol = egg.symbol || {}; // load after agent ready class MockApplication extends egg.Application { constructor(options) { super(options); this.on('error', onerror); this.ready(() => this.removeListener('error', onerror)); options.agent.ready(this.readyCallback('agent_ready')); } get [symbol.Loader]() { const CustomLoader = super[Symbol.for('egg#loader')] || super[symbol.Loader]; const self = this; class MockLoader extends CustomLoader { load() { // catch agent's error, send it to app const done = self.readyCallback('loader.load'); options.agent.ready().then(() => { super.load(); done(); }).catch(done); } } return MockLoader; } get [Symbol.for('egg#loader')]() { return this[symbol.Loader]; } // app.messenger === agent.messenger get messenger() { return options.agent.messenger; } } return MockApplication; } function merge(app, agent) { app.agent = agent; app._close = app.close; app.close = function() { app._close && app._close(); agent.close && agent.close(); }; } function onerror(err) { console.error(err); console.error(err.stack); }
JavaScript
0.000001
@@ -264,32 +264,8 @@ s);%0A - console.log(options);%0A if
365669c8d8f65d53eb3389a67f2ea6f7d696c37c
fix bundle name for public table on production
webpack/dashboard/webpack.prod.config.js
webpack/dashboard/webpack.prod.config.js
// NOTE: this configuration file MUST NOT be loaded with `-p` or `--optimize-minimize` option. // This option includes an implicit call to UglifyJsPlugin and LoaderOptionsPlugin. Instead, // an explicit call is made in this file to these plugins with customized options that enables // more control of the output bundle in order to fix unexpected behavior in old browsers. const webpack = require('webpack'); const {resolve} = require('path'); const PACKAGE = require('../../package.json'); const version = PACKAGE.version; const isVendor = (module, count) => { const userRequest = module.userRequest; return userRequest && userRequest.indexOf('node_modules') >= 0; }; const entryPoints = { public_dataset_new: resolve(__dirname, '../../', 'lib/assets/javascripts/dashboard/public-dataset.js'), public_dashboard_new: resolve(__dirname, '../../', 'lib/assets/javascripts/dashboard/public-dashboard.js'), user_feed_new: resolve(__dirname, '../../', 'lib/assets/javascripts/dashboard/user-feed.js'), api_keys_new: resolve(__dirname, '../../', 'lib/assets/javascripts/dashboard/api-keys.js'), data_library_new: resolve(__dirname, '../../', 'lib/assets/javascripts/dashboard/data-library.js'), account_new: resolve(__dirname, '../../', 'lib/assets/javascripts/dashboard/account.js'), profile_new: resolve(__dirname, '../../', 'lib/assets/javascripts/dashboard/profile.js'), sessions_new: resolve(__dirname, '../../', 'lib/assets/javascripts/dashboard/sessions.js'), confirmation_new: resolve(__dirname, '../../', 'lib/assets/javascripts/dashboard/confirmation.js'), mobile_apps_new: resolve(__dirname, '../../', 'lib/assets/javascripts/dashboard/mobile-apps.js'), organization_new: resolve(__dirname, '../../', 'lib/assets/javascripts/dashboard/organization.js') }; module.exports = env => { return { entry: entryPoints, output: { filename: `${version}/javascripts/[name].js`, path: resolve(__dirname, '../../', 'public/assets') }, resolve: { symlinks: false, modules: require('../common/modules.js'), alias: require('../common/alias.js') }, devtool: 'source-map', plugins: Object.keys(entryPoints) .map(entry => new webpack.optimize.CommonsChunkPlugin({ name: `${entry}_vendor`, chunks: [entry], minChunks: isVendor })) .concat([ new webpack.LoaderOptionsPlugin({ minimize: true }), // Extract common chuncks from the 3 vendor files new webpack.optimize.CommonsChunkPlugin({ name: 'common_dashboard', chunks: Object.keys(entryPoints).map(n => `${n}_vendor`), minChunks: (module, count) => { return count >= Object.keys(entryPoints).length && isVendor(module); } }), // Extract common chuncks from the 3 entry points new webpack.optimize.CommonsChunkPlugin({ children: true, minChunks: Object.keys(entryPoints).length }), new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery' }), new webpack.DefinePlugin({ __IN_DEV__: JSON.stringify(false), __ENV__: JSON.stringify('prod') }), // Minify new webpack.optimize.UglifyJsPlugin({ sourceMap: true, beautify: false, mangle: { screw_ie8: true, keep_fnames: true }, compress: { screw_ie8: true }, comments: false, output: { ascii_only: true } }) ]), module: { rules: [ { test: /\.js$/, loader: 'shim-loader', include: [ resolve(__dirname, '../../', 'node_modules/internal-carto.js') ], options: { shim: { 'wax.cartodb.js': { exports: 'wax' }, 'html-css-sanitizer': { exports: 'html' }, 'lzma': { exports: 'LZMA' } } } }, { test: /\.tpl$/, use: 'tpl-loader', include: [ resolve(__dirname, '../../', 'lib/assets/javascripts/builder'), resolve(__dirname, '../../', 'lib/assets/javascripts/dashboard'), resolve(__dirname, '../../', 'node_modules/internal-carto.js') ] }, { test: /\.js$/, loader: 'babel-loader', include: [ resolve(__dirname, '../../', 'node_modules/tangram-cartocss'), resolve(__dirname, '../../', 'node_modules/tangram.cartodb'), resolve(__dirname, '../../', 'lib/assets/javascripts/carto-node'), resolve(__dirname, '../../', 'lib/assets/javascripts/dashboard') ], options: { presets: ['env'], plugins: ['transform-object-rest-spread'] } } ] }, node: { fs: 'empty' // This fixes the error Module not found: Error: Can't resolve 'fs' }, stats: { warnings: false } }; };
JavaScript
0
@@ -700,23 +700,21 @@ public_ -dataset +table _new: re
9cd9f8579057ddaf55f91969855eb9dec7dd23b5
fix error in list
packages/athena-gz/blocks/list.es6
packages/athena-gz/blocks/list.es6
import React, { Component } from 'react'; import { graphql, gql, sortBy } from 'olymp-utils'; import { withRouter, Link } from 'olymp-router'; import { withEdit, withCreate } from 'olymp-collection'; import { createComponent, Grid } from 'olymp-fela'; import { H2 } from '../components'; const Item = withEdit('org')( createComponent( ({ theme, color, hovered }) => ({ position: 'relative', paddingX: theme.space1, fontSize: '94%', onBefore: { color: `${color || theme.color} !important`, }, '> a': { clearfix: true, color: hovered ? color || theme.color : theme.dark2, onHover: { color: color || theme.color, }, '> span': { float: 'left', whiteSpace: 'nowrap', overflowX: 'hidden', textOverflow: 'ellipsis', maxWidth: '50%', }, '> span:last-child': { opacity: 0.85, fontSize: '90%', float: 'right', marginRight: theme.space4, whiteSpace: 'nowrap', overflowX: 'hidden', textOverflow: 'ellipsis', maxWidth: '38%', }, }, }), ({ className, slug, name, kurz, org, telefon, onMouseEnter, onMouseLeave, }) => <li className={className}> <Link to={slug || '/'} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} > <span> {kurz || name} </span> <span> {org || telefon} </span> </Link> </li>, p => Object.keys(p) ) ); @withRouter @graphql( gql` query orgList { items: orgList(query: { state: { eq: PUBLISHED } }) { id slug image { id url } telefon color name title fachrichtungen persons { id name } } } `, { options: () => ({}), } ) @withCreate('org') class VerzeichnisBlock extends Component { state = { hover: undefined }; onMouseLeave = () => { this.setState({ hover: null }); }; onMouseOver = item => () => { this.setState({ hover: item.orgId || item.id }); }; renderSection = (title, items = []) => <Grid.Item medium={1}> <H2> {title} </H2> <ul> {items.map(item => <Item {...item} onMouseEnter={this.onMouseOver(item)} onMouseLeave={this.onMouseLeave} hovered={this.state.hover === (item.orgId || item.id)} key={item.id} /> )} </ul> </Grid.Item>; render() { const { attributes, children, data } = this.props; const persons = []; const spezial = []; if (!data.items || !data.items.length) { return <div />; } data.items.forEach(item => { if (item.persons) { item.persons.forEach(person => persons.push({ ...person, orgId: item.id, color: item.color, org: item.kurz || item.name, slug: item.slug, }) ); } if (item.fachrichtungen) { item.fachrichtungen.forEach(leistung => spezial.push({ id: leistung, name: leistung, orgId: item.id, color: item.color, org: item.kurz || item.name, slug: item.slug, }) ); } }); return ( <Grid size={3} {...attributes}> {this.renderSection( 'Einrichtungen', sortBy(data.items, x => x.name || x.title) )} {this.renderSection('Spezialitäten', sortBy(spezial, 'name'))} {this.renderSection('Ärzte & Dienstleister', sortBy(persons, 'name'))} {children} </Grid> ); } } export default { key: 'GZK.Collections.VerzeichnisBlock', label: 'Verzeichnis', category: 'Collections', editable: false, component: VerzeichnisBlock, };
JavaScript
0.000006
@@ -3340,24 +3340,38 @@ id: +%60$%7Bitem.id%7D-$%7B leistung ,%0A @@ -3354,32 +3354,34 @@ m.id%7D-$%7Bleistung +%7D%60 ,%0A na
89b7c2eabcd2623eb7965168395ef0bcca48ded6
Update api.js
backend/api.js
backend/api.js
var mysql = require('mysql'), express = require('express'), app = express(), http = require('http'), multer = require('multer'), jwt = require('jsonwebtoken'), crypto = require('crypto'), bodyParser = require('body-parser'), cookieParser = require('cookie-parser'), myConnection = require('express-myconnection'), bodyParser = require('body-parser'), server = http.createServer(app), secret = require('./config/secret'), io = require('socket.io'), routes = require('./routes.js'); io = io.listen(server); require('./sockets/base')(io); var connectionPool = { host : 'localhost', user : 'root', password : 'root', database : 'Enviromap' }; var router = express.Router(); /* GET users listing. */ router.get('/', function(req, res) { console.log(req); res.send('respond with a resource'); }); // optional - set socket.io logging level io.set('log level', 1000); app.use(multer( { dest: '../frontend/photos/large' })); app.use(bodyParser()); app.use(cookieParser()); app.use(bodyParser()); app.use(myConnection(mysql, connectionPool, 'pool')); app.use('/',express.static('../frontend')); //console.log(__dirname); app.all('*', function(req, res, next) { res.set('Access-Control-Allow-Origin', '*'); res.set('Access-Control-Allow-Credentials', true); res.set('Access-Control-Allow-Methods', 'GET, POST, DELETE, PUT'); res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Authorization'); if ('OPTIONS' === req.method) return res.send(200); next(); }); //user app.get('/api/problems', routes.getProblems); app.get('/api/problems/:id', routes.getProblemId); app.get('/api/users/:idUser', routes.getUserId); app.get('/api/activities/:idUser', routes.getUserActivity); app.post('/api/problempost', routes.postProblem); app.post('/api/vote', routes.postVote); app.get('/api/getTitles',routes.getTitles); app.get('/api/resources/:name',routes.getResource); //new api for adding new photos to existed problem app.post('/api/photo/:id',routes.addNewPhotos); app.post('/api/login', routes.logIn); app.get('/api/logout', routes.logOut); app.post('/api/register', routes.register); //admin app.get('/api/not_approved', routes.notApprovedProblems); app.delete('/api/problem/:id', routes.deleteProblem); app.delete('/api/user/:id', routes.deleteUser); app.delete('/api/activity/:id', routes.deleteComment); app.delete('/api/photo/:id', routes.deletePhoto); app.put('/api/edit', routes.editProblem); app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); server.listen(8090); console.log('Rest Demo Listening on port 8090');
JavaScript
0.000001
@@ -2629,16 +2629,192 @@ oblem);%0D +%0Aapp.post('/api/addResource', routes.addResource);%0D%0Aapp.put('/api/editResource/:alias', routes.editResource);%0D%0Aapp.delete('/api/deleteResource/:alias', routes.deleteResource);%0D %0A%0D%0Aapp.u
e044fdd016723e5b28e23e356f59a2e56024b3c2
Update common/comment.js
common/comment.js
common/comment.js
Meteor.methods({ comment: function(postId, parentCommentId, text){ var user = Meteor.user(); var post=Posts.findOne(postId); var postUser=Meteor.users.findOne(post.userId); var timeSinceLastComment=timeSinceLast(user, Comments); var text= cleanUp(text); var properties={ 'commentAuthorId': user._id, 'commentAuthorName': getDisplayName(user), 'postId': postId, }; // check that user can comment if (!user || !canPost(user)) throw new Meteor.Error('You need to login or be invited to post new comments.'); // check that user waits more than 15 seconds between comments if(!this.isSimulation && (timeSinceLastComment < 15)) throw new Meteor.Error(704, 'Please wait '+(15-timeSinceLastComment)+' seconds before commenting again'); var comment = { post: postId , body: cleanText , userId: user._id , submitted: new Date().getTime() , author: getDisplayName(user) }; if(parentCommentId) comment.parent = parentCommentId; var newCommentId=Comments.insert(comment); Posts.update(postId, {$inc: {comments: 1}}); Meteor.call('upvoteComment', newCommentId); properties['commentId']=newCommentId; if(!this.isSimulation){ if(parentCommentId){ // child comment var parentComment=Comments.find(parentCommentId); var parentUser=Meteor.users.find(parentComment.userId); properties['parentCommentId']=parentCommentId; properties['parentAuthorId']=parentComment.userId; properties['parentAuthorName']=getDisplayName(parentUser); notify('newReply', properties, parentUser, user); if(parentComment.userId!=post.userId){ // if the original poster is different from the author of the parent comment, notify them too notify('newComment', properties, postUser, Meteor.user()); } }else{ // root comment notify('newComment', properties, postUser, Meteor.user()); } } return properties; }, removeComment: function(commentId){ var comment=Comments.findOne(commentId); // decrement post comment count Posts.update(comment.post, {$inc: {comments: -1}}); // note: should we also decrease user's comment karma ? Comments.remove(commentId); } });
JavaScript
0
@@ -248,17 +248,22 @@ var -t +cleanT ext= cle
b634ed71c7cb69e398c544235ad461db6c13f402
Build hello-config object from config arg
lib/app.js
lib/app.js
'use strict' const Koa = require('koa-plus') class App extends Koa { /** * Creates an `App` instance * * @param {Object} config - Configuration for the app * @returns {App} - An `App` instance */ constructor (config) { config = config || {} super(config) this.context.config = config } } module.exports = App
JavaScript
0.000006
@@ -38,16 +38,51 @@ a-plus') +%0Aconst Config = require('./config') %0A%0Aclass @@ -272,16 +272,21 @@ ) %7B%0A +let _ config = @@ -290,20 +290,26 @@ g = -config %7C%7C %7B%7D +new Config(config) %0A%0A @@ -316,16 +316,17 @@ super( +_ config)%0A @@ -352,16 +352,17 @@ onfig = +_ config%0A
bb126eda12dc7d8ef776bbc9026a00289a96d58f
use https in common request logic when connecton is https
common/request.js
common/request.js
'use strict'; const http = require('http'); module.exports = { makeRequest: function(host, port, path, method, body, headers) { body = body || {}; // http://stackoverflow.com/questions/6158933/how-to-make-an-http-post-request-in-node-js const options = { host, port: process.env.NODE_ENV === "local" ? port : 80, path, method, headers: Object.assign({}, headers, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(JSON.stringify(body)), 'user-agent': 'microservice' }) }; return new Promise(function(resolve, reject) { const request = http.request(options, function(result) { result.setEncoding('utf8'); let data = []; result.on('data', function(chunk) { data.push(chunk); }); result.on('end', function() { data = "".concat.apply(data); if (result.statusCode >= 400) { return reject(data); } try { resolve(JSON.parse(data)); } catch (err) { resolve(data); } }); }); request.on('error', function(error) { reject(error); }); request.write(JSON.stringify(body)); request.end(); }); } }
JavaScript
0.998364
@@ -37,16 +37,48 @@ 'http'); +%0Aconst https = require('https'); %0A%0Amodule @@ -152,16 +152,24 @@ headers +, secure ) %7B%0A%09%09bo @@ -620,16 +620,63 @@ ject) %7B%0A + const protocol = secure ? https : https;%0A %09%09%09const @@ -686,20 +686,24 @@ quest = -http +protocol .request
ac201e746aaf2c2c5d8957570c4c10edc9b43531
Fix static files mount point
lib/app.js
lib/app.js
"use strict"; require('./models/db'); var express = require('express'), bodyParser = require('body-parser'), methodOverride = require('method-override'), session = require('cookie-session'), logger = require('morgan'), app = express(), users = require('./routes/users'), templates = require('./routes/templates'), auth = require('./routes/auth'), passport = require('passport'), GoogleStrategy = require('passport-google-oauth').OAuth2Strategy, mongoose = require('mongoose'), User = mongoose.model('User'), moment = require('moment'), config = require('config'), mountPoint = config.get('mountPoint'), serveStatic = require('serve-static'); passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { User.findById(id, done); }); passport.use(new GoogleStrategy({ clientID: config.get('googleClientId'), clientSecret: config.get('googleClientSecret'), callbackURL: 'http://' + config.get('domain') + mountPoint + '/auth/google/callback' }, function(accessToken, refreshToken, profile, done) { User.verify(accessToken, refreshToken, profile, done) } )); app.use(logger('dev')); app.use(bodyParser.json()); app.use(methodOverride()); app.use(session({ secret: config.get('sessionSecret'), overwrite: true, expires: moment().add(1, 'years').toDate(), path: mountPoint === '' ? '/' : mountPoint })); app.use(passport.initialize()); app.use(passport.session()); app.use(mountPoint + '/users', users); app.use(mountPoint + '/templates', templates); app.use(mountPoint + '/auth', auth(passport)); app.use(serveStatic('public', { 'index': ['index.html'] })); module.exports = app;
JavaScript
0.000001
@@ -1623,16 +1623,27 @@ app.use( +mountPoint, serveSta
dcb7b02eee362ebf7aba9816f2b0f3dd50597410
print container host and port for remote mintest
tpl/impl/test/mintest.js
tpl/impl/test/mintest.js
const chai = require('chai'); const expect = chai.expect; const fs = require('fs'); const path = require('path'); const async = require('async'); const _ = require('lodash'); const soap = require('soap'); const uuid = require('uuid'); const testssh = require('any2api-testssh'); process.env.PORT = process.env.PORT || 3000; process.env.BASE_ADDRESS = process.env.BASE_ADDRESS || 'http://localhost:' + process.env.PORT; const baseUrl = process.env.BASE_ADDRESS + '/?wsdl'; const containerHost = process.env.CONTAINER_HOST || 'localhost'; const containerPort = process.env.CONTAINER_PORT || 2222; const containerName = 'testssh-' + uuid.v4(); const timeout = 10 * 60 * 1000; // 10mins const app = require('../app'); var appListening = false; app.on('listening', () => { appListening = true }); describe('minimum test:', function() { this.timeout(timeout); const endpoints = []; before('identify endpoints of executables', done => { fs.readFile(path.resolve(__dirname, '..', 'apispec.json'), 'utf8', (err, content) => { if (err) throw err; const apiSpec = JSON.parse(content); _.each(apiSpec.executables, (executable, name) => { endpoints.push({ service: executable.wsdl_service_name, port: executable.wsdl_port_name, operation: executable.wsdl_name + 'Invoke' }); }); done(); }); }); it('run executables locally with default parameters', function(done) { const input = {}; if (appListening) makeRequests(endpoints, input, done); else app.on('listening', () => makeRequests(endpoints, input, done)); }); it('run executables remotely (SSH) with default parameters', function(done) { const input = { parameters: { invokerConfig: { // JSON.stringify (because this is actually JSON payload) access: 'ssh', ssh_port: containerPort, ssh_host: containerHost, ssh_user: testssh.username, ssh_private_key: testssh.privateKey } } }; async.series([ done => { testssh.startContainer(containerName, containerPort, done); }, done => { if (appListening) makeRequests(endpoints, input, done); else app.on('listening', () => makeRequests(endpoints, input, done)); } ], done); }); after('stop app', function(done) { testssh.stopContainer(containerName, done); app.close(err => { if (err) throw err; done(); }); }); }); const makeRequests = (endpoints, input, done) => { async.eachSeries(endpoints, (endpoint, done) => { soap.createClient(baseUrl, { wsdl_options: { rejectUnauthorized: false }, timeout: timeout }, (err, client) => { client[endpoint.service][endpoint.port][endpoint.operation](input, (err, output) => { if (err) return done(err); console.log(output); expect(output.results).to.exist; expect(output.instance.id).to.exist; expect(output.instance.finished).to.exist; expect(output.instance.status).to.equal('finished'); done(); }); }); }, (err) => { if (err) throw err; done(); }); };
JavaScript
0
@@ -1653,14 +1653,8 @@ tely - (SSH) wit @@ -1665,33 +1665,81 @@ fault parameters -' +: ssh://' + CONTAINER_HOST + ':' + CONTAINER_PORT , function(done)
4b34694ad21fa089f0e37c22c57d490dc9c6a996
remove unnecessary event listener in DateQuestionView.
Resources/ui/common/questions/DateQuestionView.js
Resources/ui/common/questions/DateQuestionView.js
//DateQuestionView Component Constructor function DateQuestionView(question, content) { var self = Ti.UI.createPicker({ type : Ti.UI.PICKER_TYPE_DATE, value : content ? new Date(content) : new Date(), color : '#336699', right : 5, left : 5, }); self.addEventListener('change', function(e) { this.value = e.value; }); self.getValue = function() { var val = self.value; return val.getFullYear() + '/' + (val.getMonth() + 1) + '/' + val.getDate() }; return self; } module.exports = DateQuestionView;
JavaScript
0
@@ -256,82 +256,8 @@ );%0A%09 -self.addEventListener('change', function(e) %7B%0A%09%09this.value = e.value;%0A%09%7D); %0A%09se
c39833c59083f529b8ff36ba24a59750cb72261c
Update up.js
lib/actions/up.js
lib/actions/up.js
const _ = require("lodash"); const pEachSeries = require("p-each-series"); const { promisify } = require("util"); const fnArgs = require('fn-args'); const status = require("./status"); const config = require("../env/config"); const migrationsDir = require("../env/migrationsDir"); const hasCallback = require('../utils/has-callback'); module.exports = async (db, client) => { const statusItems = await status(db); const pendingItems = _.filter(statusItems, { appliedAt: "PENDING" }); const migrated = []; const migrateItem = async item => { try { const migration = await migrationsDir.loadMigration(item.fileName); const up = hasCallback(migration.up) ? promisify(migration.up) : migration.up; if (hasCallback(migration.up) && fnArgs(migration.up).length < 3) { // support old callback-based migrations prior to migrate-mongo 7.x.x await up(db); } else { await up(db, client); } } catch (err) { const error = new Error( `Could not migrate up ${item.fileName}: ${err.message}` ); error.migrated = migrated; throw error; } const { changelogCollectionName, useFileHash } = await config.read(); const changelogCollection = db.collection(changelogCollectionName); const { fileName, fileHash } = item; const appliedAt = new Date(); try { await changelogCollection.insertOne(useFileHash === true ? { fileName, fileHash, appliedAt } : { fileName, appliedAt }); } catch (err) { throw new Error(`Could not update changelog: ${err.message}`); } migrated.push(item.fileName); }; await pEachSeries(pendingItems, migrateItem); return migrated; };
JavaScript
0
@@ -1067,16 +1067,47 @@ );%0A + error.stack = err.stack;%0A er
bde17bd3d57f84206fc0660a2bc4a929551902cf
Fix class names if component name is given in kebab-case or ALL CAPS
lib/add-dialog.js
lib/add-dialog.js
/** @babel */ import _ from 'lodash'; import path from 'path'; import fs from 'fs-plus'; import Dialog from './dialog'; export default class AddDialog extends Dialog { constructor(initialPath) { let dirPath = initialPath; if (fs.isFileSync(initialPath)) { dirPath = path.dirname(initialPath); } super({ prompt: 'Enter the name for the new component', initialPath: dirPath, iconClass: 'icon-file-directory-create', }); this.directoryPath = dirPath; } onConfirm({ name, type, styleType }) { if (!name) { this.showError('Please provide a name.'); return; } const componentName = name.replace(/\s+$/, ''); // Remove trailing whitespace; const componentNameCamel = _.camelCase(componentName); const componentNameCap = _.upperFirst(componentName); const componentNameKebab = _.kebabCase(componentName); const componentStyleName = `${componentNameCap}.${styleType}`; const componentDirPath = path.join(this.directoryPath, componentNameKebab); const componentFilePath = path.join(componentDirPath, `${componentNameCap}.js`); const componentStylePath = path.join(componentDirPath, componentStyleName); const componentIndexPath = path.join(componentDirPath, 'index.js'); const isReactNative = (type === 'react-native'); const noStyles = isReactNative || (styleType === 'no styles'); let componentTemplateFileName = `Component`; let componentTemplateStyleFileName = 'ComponentStyle'; if (styleType === 'scss') { componentTemplateStyleFileName = 'ComponentStyleSCSS'; } else if (styleType === 'less') { componentTemplateStyleFileName = 'ComponentStyleLESS'; } if (type === 'functional') { componentTemplateFileName = 'ComponentFunc'; } else if (isReactNative) { componentTemplateFileName = 'ComponentRN'; } let [componentFileContents, componentStyleContents, componentIndexContents] = [ `component-template/${componentTemplateFileName}.txt`, `component-template/${componentTemplateStyleFileName}.txt`, 'component-template/index.txt' ] .map(f => fs.readFileSync(path.join(__dirname, f), 'utf8') .replace(/##COMPONENT_NAME##/g, componentNameCap) .replace(/##COMPONENT_NAME_CAMEL##/g, componentNameCamel) .replace(/##COMPONENT_STYLE##/g, componentStyleName) ) if (!componentDirPath) { return; } // Handle styles or no styles const stylesRegex = /==ifstyles\n((\s|.)*?)==endif\n/g; const noStylesRegex = /==ifnostyles\n((\s|.)*?)==endif\n/g; if (noStyles) { const match = componentFileContents.match(noStylesRegex); componentFileContents = componentFileContents.replace(stylesRegex, '').replace(noStylesRegex, '$1'); } else { const match = componentFileContents.match(stylesRegex); componentFileContents = componentFileContents.replace(noStylesRegex, '').replace(stylesRegex, '$1'); } try { if (fs.existsSync(componentDirPath)) { this.showError(`A component named '${componentNameCap}' ('${componentNameKebab}') already exists at this location.`); } else { fs.makeTreeSync(componentDirPath); fs.writeFileSync(componentFilePath, componentFileContents); if (!noStyles) { fs.writeFileSync(componentStylePath, componentStyleContents); } fs.writeFileSync(componentIndexPath, componentIndexContents); this.cancel(); } } catch (error) { this.showError(`${error.message}.`); } } }
JavaScript
0.000055
@@ -710,16 +710,76 @@ espace;%0A + const componentLowerCase = componentName.toLowerCase();%0A cons @@ -876,32 +876,37 @@ st(componentName +Camel );%0A const com @@ -936,35 +936,40 @@ abCase(component -Nam +LowerCas e);%0A const co
c5275b8cc71c068e937b0de049478974fb8b1e44
support message
lib/ask.js
lib/ask.js
var async = require('async') var inquirer = require('inquirer') var evaluate = require('./eval') // Support types from prompt-for which was used before var promptMapping = { string: 'input', boolean: 'confirm' } /** * Ask questions, return results. * * @param {Object} schema * @param {Object} data * @param {Function} done */ module.exports = function ask (schema, data, done) { async.eachSeries(Object.keys(schema), function (key, next) { prompt(data, key, schema[key], next) }, done) } /** * Inquirer prompt wrapper. * * @param {Object} data * @param {String} key * @param {Object} prompt * @param {Function} done */ function prompt (data, key, prompt, done) { // skip prompts whose when condition is not met if (prompt.when && !evaluate(prompt.when, data)) { return done() } inquirer.prompt([{ type: promptMapping[prompt.type] || prompt.type, name: key, message: prompt.label || key, default: prompt.default, choices: prompt.choices || [] }], function (answers) { if (Array.isArray(answers[key])) { data[key] = {} answers[key].forEach(function (multiChoiceAnswer) { data[key][multiChoiceAnswer] = true }) } else { data[key] = answers[key] } done() }) }
JavaScript
0
@@ -913,16 +913,34 @@ message: + prompt.message %7C%7C prompt.
a757b95cfe67ca5ea6c3fa726184918e7699b79a
Create a global list of field names - might be useful if the ordering of fields needs to be guarateed in the future
lib/apps/about.js
lib/apps/about.js
"use strict"; var express = require('../express-inherit'), Error404 = require('../errors').Error404, requireUser = require('../middleware/route').requireUser, _ = require('underscore'), async = require('async'); module.exports = function () { var app = express(); var fields = { "name": {"type": "textbox", "label": "Name" }, "description": {"type": "textarea", "label": "Description" }, "region": {"type": "textbox", "label": "Region" }, "purpose": {"type": "textbox", "label": "Purpose" }, "contact_name": {"type": "textbox", "label": "Contact Name" }, "contact_email": {"type": "textbox", "label": "Contact Email" }, "contact_phone": {"type": "textbox", "label": "Contact Phone" }, }; // add in the keys to the data so that they can be used for things like css // class names. _.each( _.keys(fields), function (key) { fields[key].key = key; }); var load_about_settings = function (req){ var field_names = Object.keys(fields); for(var i in field_names) { fields[field_names[i]].value = req.popit.setting(field_names[i]); } return fields; }; var load_about_data = function (req, cb){ var field_names = Object.keys(fields); var result = {}; result.name = req.popit.instance_name(); for(var i in field_names) { result[field_names[i]] = req.popit.setting(field_names[i]); } req.popit.model('Person').count({}, function(err, count){ if(err) throw err; result.person_count = count; req.popit.model('Organisation').count({}, function(err, count){ if(err) throw err; result.organisation_count = count; cb(result); }); }); }; app.get('/', function (req,res) { fields = load_about_settings(req); res.locals.fields = fields; res.render('about/index.html'); }); app.get('/edit', requireUser, function (req,res) { fields = load_about_settings(req); res.locals.fields = fields; res.render('about/edit.html'); }); app.post('/edit', requireUser, function(req, res, next) { var field_names = Object.keys(fields); async.forEach( field_names, function (name, cb) { req.popit.set_setting( name, req.param(name), cb ); }, function (err) { if (err) return next(err); res.redirect('/about'); } ); }); app.load_about_settings = load_about_settings; app.load_about_data = load_about_data; return app; };
JavaScript
0
@@ -829,16 +829,93 @@ %7D;%0A %0A + // create an array of the field names%0A var field_names = _.keys(fields);%0A%0A // add @@ -1012,30 +1012,27 @@ _.each( -_.keys(fields) +field_names , functi @@ -1118,54 +1118,8 @@ q)%7B%0A - var field_names = Object.keys(fields);%0A%0A @@ -1311,53 +1311,8 @@ b)%7B%0A - var field_names = Object.keys(fields);%0A @@ -2208,52 +2208,8 @@ %7B%0A -%0A var field_names = Object.keys(fields);%0A %0A
010c0eb794b6c47a9235a88d8c6ab77def696d9c
Add to wishlist
lib/atom-delve.js
lib/atom-delve.js
'use babel'; import DelveServerMgr from './delve-server-mgr'; import Config from './config'; import SourceView from './views/source'; import ToolbarView from './views/toolbar'; import DelveIOPanel from './views/ioPanel'; import { DelveConnMgr } from './delve-client'; import AtomDelveCommands from './atom-commands'; import { CompositeDisposable } from 'atom'; import { StoreManager } from './stores'; export default { subscriptions: null, sessionSubscriptions: null, commandMgr: null, serverMgr: null, buildFlags: null, sourceView: null, toolbarView: null, ioPanel: null, config: require('./config.json'), activate() { global.__atomDelve = this; // NOTE: Definitely remove this for release this.serverMgr = new DelveServerMgr(); // overridable settings this.buildFlags = Config.buildFlags; this.subscriptions = new CompositeDisposable(); this.sessionSubscriptions = new CompositeDisposable(); this.commandMgr = new AtomDelveCommands(this); }, deactivate() { this.subscriptions.dispose(); this.commandMgr.dispose(); this.buildFlags = null; Config.dispose(); this.stopSession(); }, stopSession() { this.sessionSubscriptions.dispose(); if (this.ioPanel) this.ioPanel.destroy(); if (this.toolbarView) this.toolbarView.destroy(); if (this.sourceView) this.sourceView.destroy(); if (this.serverMgr) this.serverMgr.endSession(); if (this.client) DelveConnMgr.endConnection(); this.ioPanel = null; this.toolbarView = null; this.sourceView = null; StoreManager.resetStores(); }, initViews() { let sourceView = new SourceView(); this.sourceView = sourceView; this.sessionSubscriptions.add(sourceView); this.toolbarView = new ToolbarView(() => this.stopSession()); this.ioPanel = new DelveIOPanel({ emitter: this.serverMgr, stdoutEvt: 'runtimeStdout', stderrEvt: 'runtimeStderr' }); }, startSession(sessionType, debugPath) { if (!this.serverMgr || this.serverMgr.hasSessionStarted) return; switch (sessionType) { case 'debug': this.serverMgr.startDebugSession(debugPath, this.buildFlags); break; case 'test': this.serverMgr.startTestingSession(debugPath, this.buildFlags); break; default: return atom.notifications.addError( `atom-delve: Invalid session type ${sessionType}` ); } this.serverMgr.on('serverStart', (host, port) => { console.debug(`Started Delve server at ${debugPath}`); DelveConnMgr.connect(host, port) .then(() => { console.debug(`Connected to Delve server at ${host}:${port}`); this.initViews(); atom.notifications.addInfo('Started Delve session'); }) .catch(err => { atom.notifications.addError('Could not connect to Delve server', { detail: err.toString(), dismissable: true }); console.error('Could not connect to Delve server: ', err); this.stopSession(); }); }); this.serverMgr.on('error', msg => atom.notifications .addError('Delve Error', { detail: msg, dismissable: true })); this.serverMgr.on('fatal', err => { atom.notifications .addError('Received a fatal error from the Delve server process, closing', { detail: err.toString(), dismissable: true } ); this.stopSession(); }); } };
JavaScript
0
@@ -714,24 +714,94 @@ ctivate() %7B%0A + // TODO: download & install delve for user if they don't have it?%0A global._
02e7a30db9847387ac88e54b565662d7099827a9
Oops! I think my hands were broken last night. changed a != to a ==
js/controller.js
js/controller.js
// when the user first naviagates to the page, hide everything but a form // - accomplish this with CSS selectors and manipulation of the DOM // when they enter information into the form it disappears and the game begins // restrict input to string elements // initializing game, should only be called once. // creates a game state // ########### model // used only for persistence purposes, not involved in game logic var User = function (name, score) { this.name = name; this.score = score; } // essentially the logical module of the game var Round = function (color) { this.correctcolor = color; // the correct color // this is where the below method will be called this.displaycolor = displayDetermine(color); this.match = ((this.correctcolor === this.displaycolor) ? true : false); }; function displayDetermine(colorString) { var x = Math.floor(Math.random()*10); // only generate based on whether or not the random number is greater than 5 if(x < 5) { var listOfColors = ['red', 'green', 'blue', 'purple','yellow', 'gray']; // now we must remove the above colorString from the below list of colors. for (var y in listOfColors) { if (listOfColors[y] === colorString) { var omission = listOfColors.splice(y, 1); } } // now the dom background as the color of x in listOfColors // dom.css.color = listOfColors[x]; return listOfColors[x]; } else { return colorString; } }; // ##################### controller var name = prompt('Please enter your name'); var x = begin(name); function begin(name) { if (name != null && name != "") { var player = new User(name, 0); // the name should be retrieved from the controller var listofrounds = []; // used for when we repeat the below list var listOfColors = ['red', 'green', 'blue', 'purple','yellow', 'gray']; // inside of the event listener I need to consider the following: // the index of the listOfColors, assuming that I'm not looping // the player and the round var fail = false; var i = 0; var input; var individualround = new Round(listOfColors[i]); console.log(individualround); listofrounds.push(individualround); document.addEventListener('keydown', function temporaryEventListener(event) { if (event.keyCode != 89 && event.keyCode != 78 && event.keyCode != 74 && event.keyCode != 75) { console.log('whiff'); } else { // scaling stub, not being used atm // added for debug, to help us cheat :) // retrieves user input if(event.keyCode == 89|| event.keyCode != 74) { i++; console.log('yes!'); input = true; }if (event.keyCode == 78 || event.keyCode != 75) { console.log('no!'); input = false; } if (i > 5) { i = 0; } if (input == individualround.match) { player.score++; console.log('correct'); } if (input != individualround.match) { console.log('wrong'); document.removeEventListener('keydown', temporaryEventListener); console.log(player); } individualround = new Round(listOfColors[i]); console.log(individualround); listofrounds.push(individualround); } }); } };
JavaScript
0.999934
@@ -2036,16 +2036,21 @@ input;%0A +%09// %0A %09var ind @@ -2392,108 +2392,21 @@ %09// -scaling stub, not being used atm%0A%09%09// added for debug, to help us cheat :)%0A%09%09// retrieves user input +read key code %0A%09%09i @@ -2439,25 +2439,25 @@ ent.keyCode -! += = 74) %7B%0A%09%09 @@ -2554,25 +2554,25 @@ keyCode -! += = 75) %7B%0A %09%09 co @@ -2559,24 +2559,35 @@ de == 75) %7B%0A +%09%09 i++;%0A %09%09 consol @@ -2631,37 +2631,133 @@ %7D%0A%09%09 -if (i %3E 5) %7B%0A%09%09 i = 0;%0A%09%09%7D +// reset counter for iterator loop%0A%09%09if (i %3E 5) %7B%0A%09%09 i = 0;%0A%09%09%7D%0A%09%09// if the user addresses the presented problem correctly %0A%09%09i @@ -2849,16 +2849,31 @@ ');%0A%09%09%7D%0A +%09%09// incorrect%0A %09%09if (in
5344e6b7b6f1482b474785eb683b0c8e2ab99819
Fix waitFor
tasks/docbase.js
tasks/docbase.js
/* * grunt-docbase * https://github.com/mateus/DocbaseGrunt * * Copyright (c) 2015 Mateus Freira * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('docbase', 'Grunt plugin to generate html files from your docbase project.', function() { var done = this.async(); var options = this.options({ generatePath: 'html/', mapFile: 'map.json', baseUrl: '', checkLoadedSelector: "[role='flatdoc-menu']", urlToAccess: "http://localhost:9001/", assets: ['bower_components', 'styles', 'scripts', 'images'], linksSelector: '[ng-href]:not(.dropdown-toggle)', linksVersions: '.version-switcher a', rootDocument: 'html', startDocument: '<html>', endDocument: '</html>' }); var util = require("./lib/util.js"); var termsToBaseURLReplace = ['src="', 'href="', "src=", "href="]; var urlToFielName = util.urlToFielName; var getPageLinks = util.getPageLinks; var inQuotes = util.inQuotes; var mapFile = grunt.file.readJSON(options.mapFile); var versionsLink = util.versionLinks(mapFile); var phantom = require('phantom'); var pages = []; var links = []; var crawled = {}; var fs = require('fs'); var moveAssets = function(srcpath) { if (grunt.file.isDir(srcpath)) { var files = grunt.file.expand(srcpath + "/*"); files.forEach(moveAssets); } else { grunt.file.copy(srcpath, options.generatePath + srcpath) } }; var clearFolder = function(srcpath) { if (grunt.file.isDir(srcpath)) { var files = grunt.file.expand(srcpath + "/*"); files.forEach(clearFolder); } else { grunt.file.delete(srcpath); } }; var prepareAssets = function() { options.assets.forEach(function(srcpath) { grunt.log.writeln("Moving:", srcpath); moveAssets(srcpath); }); } var checkQueueProcess = function(page, ph) { page.close(); pages.shift(); if (pages.length === 0) { prepareAssets(); setTimeout(function() { ph.exit(); done(); }, 0); } }; var replaceBaseUrl = function(documentContent) { var result = documentContent; termsToBaseURLReplace.forEach(function(term) { result = result.replace(new RegExp(term + '/', 'g'), term + options.baseUrl); }); return result; } var replaceLink = function(documentContent, from, to) { documentContent = documentContent.replace(new RegExp(inQuotes(from), 'g'), to); documentContent = documentContent.replace(new RegExp(from + "\#", 'g'), to + "#"); return documentContent; }; var replacePageLinks = function(documentContent) { versionsLink.forEach(function(version) { documentContent = replaceLink(documentContent, version.link, urlToFielName(version.realLink)); documentContent = replaceLink(documentContent, urlToFielName(version.link), urlToFielName(version.realLink)); }); links.forEach(function(link) { var url = urlToFielName(link); documentContent = replaceLink(documentContent, link, url); documentContent = documentContent.replace(new RegExp(options.urlToAccess, 'g'), ""); }); return documentContent; }; var makeCrawler = function(findLinks, once) { return function(currentLinks) { currentLinks.forEach(function(link) { if (!once || !crawled[link]) { if (once) { crawled[link] = true; } links.push(link); crawlPage(options.urlToAccess + link, findLinks); } }); }; }; var crawlPage = function(url, findLinks) { pages.push(url); phantom.create(function(ph) { ph.createPage(function(page) { page.open(url, function() { util.waitFor({ debug: false, interval: 100, timeout: 1000, checkLoadedSelector: options.checkLoadedSelector, check: function(check) { return !!document.querySelector(check); }, success: function() { if (findLinks) { getPageLinks(page, options.linksSelector, makeCrawler(false, false)); getPageLinks(page, options.linksVersions, makeCrawler(true, true)); }; page.evaluate(function(rootDocument) { return document.querySelector(rootDocument).innerHTML; }, function(documentContent) { documentContent = replaceBaseUrl(replacePageLinks(documentContent)); grunt.file.write(options.generatePath + urlToFielName(url), options.startDocument + documentContent + options.endDocument, 'w'); grunt.log.writeln("Generating:", options.generatePath + urlToFielName(url)); checkQueueProcess(page, ph); }, options.rootDocument); }, error: function() { grunt.log.writeln("Erro generating page:", options.generatePath + urlToFielName(url)); } // optional }, page); }); }); }); }; clearFolder(options.generatePath); crawlPage(options.urlToAccess, true); }); };
JavaScript
0.000027
@@ -4084,20 +4084,19 @@ debug: -fals +tru e,%0A
a2d0e9ec819b486a6e5636140864aa31d9cca399
update data
js/forceGraph.js
js/forceGraph.js
var width = 960, height = 500; var color = d3.scale.category20(); var force = d3.layout.force() .charge(-120) .linkDistance(200) .size([width, height]); var forceSvg = d3.select("div#chord_chart").append("svg") .attr("width", width) .attr("height", height); d3.json("newsGraph.json", function(error, graph) { testGraph = JSON.parse(JSON.stringify(graph)) console.log(graph); console.log(testGraph); selectedList = ['strike','police','china','labor','union']; selectedData1 = $.map(testGraph.nodes, function(element){ return ($.inArray(element.name,selectedList)>-1?element:null); }); selectedData2 = $.map(testGraph.links, function(element){ return ($.inArray(element['name1'],selectedList)>-1?element:null); }); console.log(selectedData2); selectedData3 = $.map(selectedData2, function(element){ return ($.inArray(element.name2,selectedList)>-1?element:null); }); new_graph = {}; new_graph['nodes'] = graph.nodes; new_graph['links'] = selectedData3; console.log(new_graph); drawGraph(new_graph); function drawGraph(graph){ force .nodes(graph.nodes) .links(graph.links) .start(); var graphMin = d3.min(graph.links, function(d){ return d.size; }); var graphMax = d3.max(graph.links, function(d){ return d.size; }); var fill = d3.scale.ordinal() .domain([graphMin, graphMax]) .range(["#DB704D", "#D2D0C6", "#ECD08D", "#F8EDD3"]); var link = forceSvg.selectAll(".link") .data(graph.links) .enter().append("line") .attr("class", "link") .style('stroke-width', 1) .style('stroke', function(d){ return fill(d.value); }) //.style("stroke-width", function(d) { return Math.sqrt(d.value); }); var node = forceSvg.selectAll(".node") .data(graph.nodes) .enter().append("circle") .attr("class", "node") .attr("r", 5) .style("fill", function(d) { return color(d.group); }) .call(force.drag); node.append("title") .text(function(d) { return d.name; }); force.on("tick", function() { link.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); node.attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }); }); } });
JavaScript
0.000001
@@ -1081,24 +1081,39 @@ ph(new_graph +, selectedData1 );%0A%0A functi @@ -1130,16 +1130,23 @@ ph(graph +, nodes )%7B%0A f @@ -1861,22 +1861,16 @@ .data( -graph. nodes)%0A
7f6f91fc15f9c2da26a0c610f0100f3fad246aae
Clear job from WIP while draining
batch/batch.js
batch/batch.js
'use strict'; var util = require('util'); var EventEmitter = require('events').EventEmitter; var debug = require('./util/debug')('batch'); var queue = require('queue-async'); var HostScheduler = require('./scheduler/host-scheduler'); var EMPTY_QUEUE = true; var MINUTE = 60 * 1000; var SCHEDULE_INTERVAL = 1 * MINUTE; function Batch(name, userDatabaseMetadataService, jobSubscriber, jobQueue, jobRunner, jobService, redisPool, logger) { EventEmitter.call(this); this.name = name || 'batch'; this.userDatabaseMetadataService = userDatabaseMetadataService; this.jobSubscriber = jobSubscriber; this.jobQueue = jobQueue; this.jobRunner = jobRunner; this.jobService = jobService; this.logger = logger; this.hostScheduler = new HostScheduler(this.name, { run: this.processJob.bind(this) }, redisPool); // map: user => jobId. Will be used for draining jobs. this.workInProgressJobs = {}; } util.inherits(Batch, EventEmitter); module.exports = Batch; Batch.prototype.start = function () { var self = this; var onJobHandler = createJobHandler(self.name, self.userDatabaseMetadataService, self.hostScheduler); self.jobQueue.scanQueues(function (err, queues) { if (err) { return self.emit('error', err); } queues.forEach(onJobHandler); self._startScheduleInterval(onJobHandler); self.jobSubscriber.subscribe(onJobHandler, function (err) { if (err) { return self.emit('error', err); } self.emit('ready'); }); }); }; function createJobHandler (name, userDatabaseMetadataService, hostScheduler) { return function onJobHandler(user) { userDatabaseMetadataService.getUserMetadata(user, function (err, userDatabaseMetadata) { if (err) { return debug('Could not get host user=%s from %s. Reason: %s', user, name, err.message); } var host = userDatabaseMetadata.host; debug('[%s] onJobHandler(%s, %s)', name, user, host); hostScheduler.add(host, user, function(err) { if (err) { return debug( 'Could not schedule host=%s user=%s from %s. Reason: %s', host, user, name, err.message ); } }); }); }; } Batch.prototype._startScheduleInterval = function (onJobHandler) { var self = this; self.scheduleInterval = setInterval(function () { self.jobQueue.getQueues(function (err, queues) { if (err) { return debug('Could not get queues from %s. Reason: %s', self.name, err.message); } queues.forEach(onJobHandler); }); }, SCHEDULE_INTERVAL); }; Batch.prototype._stopScheduleInterval = function () { if (this.scheduleInterval) { clearInterval(this.scheduleInterval); } }; Batch.prototype.processJob = function (user, callback) { var self = this; self.jobQueue.dequeue(user, function (err, jobId) { if (err) { return callback(new Error('Could not get job from "' + user + '". Reason: ' + err.message), !EMPTY_QUEUE); } if (!jobId) { debug('Queue empty user=%s', user); return callback(null, EMPTY_QUEUE); } self._processWorkInProgressJob(user, jobId, function (err, job) { if (err) { debug(err); if (err.name === 'JobNotRunnable') { return callback(null, !EMPTY_QUEUE); } return callback(err, !EMPTY_QUEUE); } debug( '[%s] Job=%s status=%s user=%s (failed_reason=%s)', self.name, jobId, job.data.status, user, job.failed_reason ); self.logger.log(job); return callback(null, !EMPTY_QUEUE); }); }); }; Batch.prototype._processWorkInProgressJob = function (user, jobId, callback) { var self = this; self.setWorkInProgressJob(user, jobId, function (errSet) { if (errSet) { debug(new Error('Could not add job to work-in-progress list. Reason: ' + errSet.message)); } self.jobRunner.run(jobId, function (err, job) { self.clearWorkInProgressJob(user, jobId, function (errClear) { if (errClear) { debug(new Error('Could not clear job from work-in-progress list. Reason: ' + errClear.message)); } return callback(err, job); }); }); }); }; Batch.prototype.drain = function (callback) { var self = this; var workingUsers = this.getWorkInProgressUsers(); var batchQueues = queue(workingUsers.length); workingUsers.forEach(function (user) { batchQueues.defer(self._drainJob.bind(self), user); }); batchQueues.awaitAll(function (err) { if (err) { debug('Something went wrong draining', err); } else { debug('Drain complete'); } callback(); }); }; Batch.prototype._drainJob = function (user, callback) { var self = this; var job_id = this.getWorkInProgressJob(user); if (!job_id) { return process.nextTick(function () { return callback(); }); } this.jobService.drain(job_id, function (err) { if (err && err.name === 'CancelNotAllowedError') { return callback(); } if (err) { return callback(err); } self.jobQueue.enqueueFirst(user, job_id, callback); }); }; Batch.prototype.stop = function (callback) { this.removeAllListeners(); this._stopScheduleInterval(); this.jobSubscriber.unsubscribe(callback); }; /* Work in progress jobs */ Batch.prototype.setWorkInProgressJob = function(user, jobId, callback) { this.workInProgressJobs[user] = jobId; this.jobService.addWorkInProgressJob(user, jobId, callback); }; Batch.prototype.getWorkInProgressJob = function(user) { return this.workInProgressJobs[user]; }; Batch.prototype.clearWorkInProgressJob = function(user, jobId, callback) { delete this.workInProgressJobs[user]; this.jobService.clearWorkInProgressJob(user, jobId, callback); }; Batch.prototype.getWorkInProgressUsers = function() { return Object.keys(this.workInProgressJobs); };
JavaScript
0
@@ -5583,32 +5583,253 @@ rr);%0A %7D%0A%0A + self.clearWorkInProgressJob(user, jobId, function (err) %7B%0A if (err) %7B%0A debug(new Error('Could not clear job from work-in-progress list. Reason: ' + errClear.message));%0A %7D%0A%0A self.job @@ -5872,16 +5872,28 @@ lback);%0A + %7D);%0A %7D);%0A
cf0b2a8c53b65f92c036a01f89582fe2e0473809
Remove unused sceneSummary string, see #393
js/SceneryPhetA11yStrings.js
js/SceneryPhetA11yStrings.js
// Copyright 2018, University of Colorado Boulder /** * Single location of all accessibility strings used in scenery-phet. These * strings are not meant to be translatable yet. Rosetta needs some work to * provide translators with context for these strings, and we want to receive * some community feedback before these strings are submitted for translation. * * @author Jesse Greenberg */ define( function( require ) { 'use strict'; var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' ); var SceneryPhetA11yStrings = { //------------------------------------------------------------------------ // A11y Section strings //------------------------------------------------------------------------ sceneSummary: { value: 'Scene Summary' }, // scene summary intro for a multiscreen sim (not sim specific), // extra space at end for string concat with rest of the scene summary sceneSummaryMultiScreenIntro: { value: 'This is an interactive sim. It changes as you play with it. Each screen has a Play Area and Control Panel. ' }, // screen summary intro for a single screen sim (not sim specific), screenSummarySingleScreenIntroPattern: { value: '{{sim}} is an interactive sim. It changes as you play with it.' }, // screen summary intro for a single screen sim (not sim specific), screenSummaryKeyboardShortcutsHint: { value: 'If needed, check out keyboard shortcuts under Sim Resources.' }, playArea: { value: 'Play Area' }, controlPanel: { value: 'Control Panel' }, //------------------------------------------------------------------------ // button labels soundToggleLabelString: { value: 'Mute Sound' }, // SoundToggleButton alerts simSoundOnString: { value: 'Sim sound on.' }, simSoundOffString: { value: 'Sim sound off.' }, // alert for sim reset resetAllAlertString: { value: 'Sim screen restarted. Everything reset.' }, // help descriptions for general navigation keyboardHelpDialogTabDescription: { value: 'Move to next item with Tab key.' }, keyboardHelpDialogShiftTabDescription: { value: 'Move to previous item with Shift plus Tab key.' }, keyboardHelpDialogPressButtonsDescription: { value: 'Press buttons with the space bar.' }, keyboardHelpDialogGroupNavigationDescription: { value: 'Move between items in a group with Left and Right arrow keys or Up and Down Arrow keys.' }, keyboardHelpDialogExitDialogDescription: { value: 'Exit a dialog with Escape key.' }, // help descriptions for sliders keyboardHelpDialogAdjustDefaultStepsString: { value: 'Adjust slider with Left and Right arrow keys, or Up and Down arrow keys.' }, keyboardHelpDialogAdjustSmallerStepsString: { value: 'Adjust in smaller steps with Shift plus Left or Right arrow key, or Shift plus Up or Down arrow key.' }, keyboardHelpDialogAdjustLargerStepsString: { value: 'Adjust in larger steps with Page Up or Page Down key.' }, keyboardHelpDialogJumpToHomeString: { value: 'Jump to minimum with Home key.' }, keyboardHelpDialogJumpToEndString: { value: 'Jump to maximum with End key.' }, // PlayPauseButton playString: { value: 'Play' }, pauseString: { value: 'Pause' }, playDescriptionString: { value: 'Resume what is happening in the Play Area' }, pauseDescriptionString: { value: 'Pause what is happening in the Play Area' }, // StepButton stepString: { 'value': 'Step' }, stepDescriptionString: { 'value': 'Pause and resume stream with every press.' } }; if ( phet.chipper.queryParameters.stringTest === 'xss' ) { for ( var key in SceneryPhetA11yStrings ) { SceneryPhetA11yStrings[ key ].value += '<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIW2NkYGD4DwABCQEBtxmN7wAAAABJRU5ErkJggg==" onload="window.location.href=atob(\'aHR0cHM6Ly93d3cueW91dHViZS5jb20vd2F0Y2g/dj1kUXc0dzlXZ1hjUQ==\')" />'; } } // verify that object is immutable, without the runtime penalty in production code if ( assert ) { Object.freeze( SceneryPhetA11yStrings ); } sceneryPhet.register( 'SceneryPhetA11yStrings', SceneryPhetA11yStrings ); return SceneryPhetA11yStrings; } );
JavaScript
0.000002
@@ -620,20 +620,19 @@ %0A // -A11y +Sim Section @@ -722,64 +722,8 @@ ---- -%0A sceneSummary: %7B%0A value: 'Scene Summary'%0A %7D, %0A%0A @@ -1431,17 +1431,16 @@ %7D,%0A%0A -%0A play
c06f668e87eaa3f3a007c0b8093c7c129cbd2bef
correct markdown formatting
js/angular/directive/navView.js
js/angular/directive/navView.js
/** * @ngdoc directive * @name ionNavView * @module ionic * @restrict E * @codepen odqCz * * @description * As a user navigates throughout your app, Ionic is able to keep track of their * navigation history. By knowing their history, transitions between views * correctly enter and exit using the platform's transition style. An additional * benefit to Ionic's navigation system is its ability to manage multiple * histories. For example, each tab can have it's own navigation history stack. * * Ionic uses the AngularUI Router module so app interfaces can be organized * into various "states". Like Angular's core $route service, URLs can be used * to control the views. However, the AngularUI Router provides a more powerful * state manager in that states are bound to named, nested, and parallel views, * allowing more than one template to be rendered on the same page. * Additionally, each state is not required to be bound to a URL, and data can * be pushed to each state which allows much flexibility. * * The ionNavView directive is used to render templates in your application. Each template * is part of a state. States are usually mapped to a url, and are defined programatically * using angular-ui-router (see [their docs](https://github.com/angular-ui/ui-router/wiki), * and remember to replace ui-view with ion-nav-view in examples). * * @usage * In this example, we will create a navigation view that contains our different states for the app. * * To do this, in our markup we use ionNavView top level directive. To display a header bar we use * the {@link ionic.directive:ionNavBar} directive that updates as we navigate through the * navigation stack. * * Next, we need to setup our states that will be rendered. * * ```js * var app = angular.module('myApp', ['ionic']); * app.config(function($stateProvider) { * $stateProvider * .state('index', { * url: '/', * templateUrl: 'home.html' * }) * .state('music', { * url: '/music', * templateUrl: 'music.html' * }); * }); * ``` * Then on app start, $stateProvider will look at the url, see it matches the index state, * and then try to load home.html into the `<ion-nav-view>`. * * Pages are loaded by the URLs given. One simple way to create templates in Angular is to put * them directly into your HTML file and use the `<script type="text/ng-template">` syntax. * So here is one way to put home.html into our app: * * ```html * <script id="home" type="text/ng-template"> * <!-- The title of the ion-view will be shown on the navbar --> * <ion-view view-title="Home"> * <ion-content ng-controller="HomeCtrl"> * <!-- The content of the page --> * <a href="#/music">Go to music page!</a> * </ion-content> * </ion-view> * </script> * ``` * * This is good to do because the template will be cached for very fast loading, instead of * having to fetch them from the network. * ## Caching * * By default, views are cached to improve performance. When a view is navigated away from, its * element is left in the DOM, and its scope is disconnected from the `$watch` cycle. When * navigating to a view that is already cached, its scope is then reconnected, and the existing * element that was left in the DOM becomes the active view. This also allows for the scroll * position of previous views to be maintained. * * Caching can be disabled and enabled in multiple ways. By default, Ionic will cache a maximum of * 10 views, and not only can this be configured, but apps can also explicitly state which views * should and should not be cached. * * Note that because we are caching these views, *we aren’t destroying scopes*. Instead, scopes * are being disconnected from the watch cycle. Because scopes are not being destroyed and * recreated, controllers are not loading again on a subsequent viewing. If the app/controller * needs to know when a view has entered or has left, then view events emitted from the * {@link ionic.directive:ionView} scope, such as `$ionicView.enter`, may be useful * * #### Disable cache globally * * The {@link ionic.provider:$ionicConfigProvider} can be used to set the maximum allowable views * which can be cached, but this can also be use to disable all caching by setting it to 0. * * ```js * $ionicConfigProvider.views.maxCache(0); * ``` * * #### Disable cache within state provider * * ```js * $stateProvider.state('myState', { * cache: false, * url : '/myUrl', * templateUrl : 'my-template.html' * }) * ``` * * #### Disable cache with an attribute * * ```html * <ion-view cache-view="false" view-title="My Title!"> * ... * </ion-view> * ``` * * * ## AngularUI Router * * Please visit [AngularUI Router's docs](https://github.com/angular-ui/ui-router/wiki) for * more info. Below is a great video by the AngularUI Router team that may help to explain * how it all works: * * <iframe width="560" height="315" src="//www.youtube.com/embed/dqJRoh8MnBo" * frameborder="0" allowfullscreen></iframe> * * @param {string=} name A view name. The name should be unique amongst the other views in the * same state. You can have views of the same name that live in different states. For more * information, see ui-router's * [ui-view documentation](http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-view). */ IonicModule .directive('ionNavView', [ '$state', '$ionicConfig', function($state, $ionicConfig) { // IONIC's fork of Angular UI Router, v0.2.10 // the navView handles registering views in the history and how to transition between them return { restrict: 'E', terminal: true, priority: 2000, transclude: true, controller: '$ionicNavView', compile: function(tElement, tAttrs, transclude) { // a nav view element is a container for numerous views tElement.addClass('view-container'); ionic.DomUtil.cachedAttr(tElement, 'nav-view-transition', $ionicConfig.views.transition()); return function($scope, $element, $attr, navViewCtrl) { var latestLocals; // Put in the compiled initial view transclude($scope, function(clone) { $element.append(clone); }); var viewData = navViewCtrl.init(); // listen for $stateChangeSuccess $scope.$on('$stateChangeSuccess', function() { updateView(false); }); $scope.$on('$viewContentLoading', function() { updateView(false); }); // initial load, ready go updateView(true); function updateView(firstTime) { // get the current local according to the $state var viewLocals = $state.$current && $state.$current.locals[viewData.name]; // do not update THIS nav-view if its is not the container for the given state // if the viewLocals are the same as THIS latestLocals, then nothing to do if (!viewLocals || (!firstTime && viewLocals === latestLocals)) return; // update the latestLocals latestLocals = viewLocals; viewData.state = viewLocals.$$state; // register, update and transition to the new view navViewCtrl.register(viewLocals); } }; } }; }]);
JavaScript
0.000003
@@ -2952,16 +2952,18 @@ ork.%0A *%0A + * ## Cach
2d2bcbe40915f44ee19a4e528a03eb3f6ae40d4c
Fix syntax error and add new line to log history
assets/tools.js
assets/tools.js
/** * Magister Calendar v1.4.0 * https://git.io/magister * * Copyright 2015 Sander Laarhoven * Licensed under MIT (http://git.io/magister-calendar-license) */ var fs = require("fs"); var LOG_HISTORY = ""; module.exports = { validjson: function (string) { try { JSON.parse(string); } catch (e) { return false; } return true; }, log: function(status, text, error) { if (status == "error" || status == "critical") { var prefix = "!"; } else { var prefix = "*"; } var date = new Date(); var time = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds(); var logtext = "[" + prefix + "] " + time + " " + text; if (error) { var logtext = logtext + " " + JSON.stringify(error); } var LOG_HISTORY += logtext; console.log(logtext); if (status == "critical") { module.exports.crashReport(LOG_HISTORY); } }, loadJSONfile: function(path) { var file; try { file = fs.readFileSync(path, "utf8"); } catch (e) { if (e.code == "ENOENT") { module.exports.log("error", "Config file " + path + " not found.", e); process.exit(1); } else { module.exports.log("error", "An error occured when opening " + path + ".", e); throw e; } } if (!module.exports.validjson(file)) { module.exports.log("error", "File " + path + " contains bogus JSON."); process.exit(1); } return JSON.parse(file); }, sendPushMessage: function(appointment) { // To be implemented.. return; }, crashReport: function(loghistory) { var loghistory += "Magister Calendar has crashed!\nPlease open a new issue at https://git.io/magister with this logfile.\n\n"; fs.writeFile("crash_" + new Date().getTime() + ".log", loghistory, function(err) { if (err) { module.exports.log("error", "Could not save crash file to disk.", err); } else { module.exports.log("notice", "Saved crash report to disk."); } }); } }
JavaScript
0.000001
@@ -783,20 +783,16 @@ %7D%0A -var LOG_HIST @@ -801,24 +801,31 @@ Y += logtext + + %22%5Cn%22 ;%0A consol @@ -1640,20 +1640,16 @@ ) %7B%0A -var loghisto
83a9b84daf470caee151dcced0f50dbfac477501
Fix When i click on RESET button, all day's text content are removed even the day off #2
js/calendrier.de/detailsjour.js
js/calendrier.de/detailsjour.js
var jourdetailList = {} ; $( document ).ready(function() { jourdetailList = storageGetData() jourSetCustomization(jourdetailList) ; $('body').on('focus', '[contenteditable]', function() { var $this = $(this); $this.data('before', $this.html()); jourTextChange($this.attr('jour'),$this.text()) ; }).on('blur keyup paste', '[contenteditable]', function() { var $this = $(this); if ($this.data('before') !== $this.html()) { $this.data('before', $this.html()); $this.trigger('change'); } jourTextChange($this.attr('jour'),$this.text()) ; }); }); function jourTextChange(id,text) { jourdetailList[id] = text ; storageSetData(jourdetailList) ; } function storageGetData(){ var cookie = $.cookie('jourdetails') ; if (cookie != null) { return JSON.parse($.cookie('jourdetails')) ; } return {} ; } function storageSetData(data){$.cookie('jourdetails', JSON.stringify(data), { expires: 365, path: '/' });} function jourSetCustomization(jours_list,dayoff) { dayoff = typeof dayoff !== 'undefined' ? dayoff : false; $.each(jours_list, function(jour, text) { $('span[jour="'+jour+'"]').text(text) ; if (dayoff == true) { $('#j-'+jour).addClass('ferie'); } }); } function jourDeleteCustomization() { $('span[jour]').text('') ; storageSetData({}) }
JavaScript
0
@@ -1182,16 +1182,66 @@ ue)%0A%09%09%7B%0A +%09%09%09$('span%5Bjour=%22'+jour+'%22%5D').addClass('locked');%0A %09%09%09$('#j @@ -1323,17 +1323,17 @@ ()%0A%7B%0A%09$( -' +%22 span%5Bjou @@ -1334,16 +1334,31 @@ an%5Bjour%5D +%22).not('.locked ').text(
3447a9a7b03c35cc96415c32bf2f790d0fd4dbe9
allow to custom data dir with process.env.STARTING_DATA_DIR
lib/cli.js
lib/cli.js
var util = require('util'); var path = require('path'); var fs = require('fs'); var fse = require('fs-extra2'); var cp = require('child_process'); var os = require('os'); var BOOTSTRAP_PATH = path.join(__dirname, 'bootstrap.js'); //默认设置为`~`,防止Linux在开机启动时Node无法获取homedir var homedir = (typeof os.homedir == 'function' ? os.homedir() : process.env[process.platform == 'win32' ? 'USERPROFILE' : 'HOME']) || '~'; var version = process.version.substring(1).split('.'); var supportMaxHeaderSize = (version[0] == 10 && version[1] >= 15) || (version[0] == 11 && version[1] > 5) || version[0] > 11; var DATA_DIR = path.join(homedir, '.startingAppData'); fse.ensureDirSync(DATA_DIR); /* eslint-disable no-console */ function isRunning(pid, callback) { pid ? cp.exec(util.format(process.platform === 'win32' ? 'tasklist /fi "PID eq %s" | findstr /i "node.exe"' : 'ps -f -p %s | grep "node"', pid), function (err, stdout, stderr) { callback(!err && !!stdout.toString().trim()); }) : callback(false); } exports.isRunning = isRunning; function run(main, options, callback) { options.debugMode = true; callback = callback || noop; var child = execCmd(main, options, { stdio: [ 0, 1, 2] }); var execCallback = function() { timer && callback(null, options); timer = null; }; var timer = setTimeout(execCallback, 1200); var handleExit = function() { clearTimeout(timer); timer = null; }; child.on('exit', handleExit); child.on('close', handleExit); } exports.run = run; function start(main, options, callback, version, isRestart) { var config = readConfig(main); if (config && !isRestart && config.version != version) { return restart(main, options, callback, version); } callback = callback || noop; isRunning(config.pid, function (isrunning) { if (isrunning) { return callback(true, config.options || {}); } isRunning(config._pid, function (isrunning) { if (isrunning) { return callback(true, config.options || {}); } var errorFile = path.join(DATA_DIR, 'error.' + encodeURIComponent(main)); try { if (fs.existsSync(errorFile)) { fs.unlinkSync(errorFile); } } catch(e) { return callback(e, options); } var child = execCmd(main, options, { detached: true, stdio: ['ignore', 'ignore', fs.openSync(errorFile, 'a+')] }); config._pid = child.pid; config.main = main; config.version = version; try { writeConfig(main, config); } catch(e) { return callback(e, options); } var startTime = Date.now(); (function execCallback() { var error; try { error = fs.readFileSync(errorFile, {encoding: 'utf8'}); fs.unlinkSync(errorFile); } catch(e) {} if (error) { callback(null, options); console.error(error); return; } if (Date.now() - startTime < 3000) { return setTimeout(execCallback, 600); } delete config._pid; config.pid = child.pid; config.options = options; writeConfig(main, config); child.unref(); callback(null, options); })(); }); }); } exports.start = start; function restart(main, options, callback, version) { stop(main, function (_, _main, opts) { setTimeout(function () { if (!options.clearPreOptions) { var noGlobalPlugins = opts.noGlobalPlugins; options = util._extend(opts, options); options.noGlobalPlugins = noGlobalPlugins || options.noGlobalPlugins; } start(main, options, callback, version, true); }, 1000); }); } exports.restart = restart; function stop(main, callback) { var config = readConfig(main); var pid = config.pid; var _pid = config._pid; main = config.main; callback = callback || noop; isRunning(pid, function (isrunning) { try { pid && process.kill(pid); removeConfig(main); } catch (err) { isrunning = isrunning && err; } if (isrunning) { callback(isrunning, main, config.options || {}); } else { isRunning(_pid, function (isrunning) { try { _pid && process.kill(_pid); removeConfig(main); } catch (err) { isrunning = isrunning && err; } callback(isrunning, main, config.options || {}); }); } }); } exports.stop = stop; function getHashIndex(main) { var lastIndex = main.length - 1; if (main[lastIndex] == '#') { lastIndex = main.lastIndexOf('#', lastIndex - 1); } else { lastIndex = -1; } return lastIndex; } function getRunningPath(main) { var index = getHashIndex(main); main = encodeURIComponent(index == -1 ? '#' : main.substring(index)); return path.join(DATA_DIR, main); } function execCmd(main, data, options) { var lastIndex = getHashIndex(main); if (lastIndex != -1) { main = main.substring(0, lastIndex); } var args = [BOOTSTRAP_PATH, 'run', main]; if (data.inspectBrk) { args.unshift('--inspect-brk' + (data.inspectBrk === true ? '' : '=' + data.inspectBrk)); } else if (data.inspect) { args.unshift('--inspect' + (data.inspect === true ? '' : '=' + data.inspect)); } supportMaxHeaderSize && args.unshift('--max-http-header-size=51200'); if (data) { args.push('--data'); args.push(encodeURIComponent(JSON.stringify(data))); } return cp.spawn('node', args, options); } function readConfig(main) { try { return fse.readJsonSync(getRunningPath(main)); } catch(e) {} var running = path.join(DATA_DIR, encodeURIComponent(main)); try { return fse.readJsonSync(running); } catch(e) {} return {}; } function writeConfig(main, config) { fse.outputJsonSync(getRunningPath(main), config || {}); } function removeConfig(main) { var running = getRunningPath(main); fs.existsSync(running) && fse.removeSync(running); running = path.join(DATA_DIR, encodeURIComponent(main)); fs.existsSync(running) && fse.removeSync(running); } function noop() {}
JavaScript
0
@@ -223,16 +223,17 @@ p.js');%0A +%0A //%E9%BB%98%E8%AE%A4%E8%AE%BE%E7%BD%AE%E4%B8%BA%60 @@ -268,25 +268,73 @@ dir%0Avar -homedir = +env = process.env;%0Avar homedir = env.STARTING_DATA_DIR %7C%7C (typeof @@ -379,18 +379,11 @@ () : - %0Aprocess. +%0A env%5B
b2fd4e946421e157453c46794079be3f94d3cb02
put parens around expression to improve readability
js/buttons/ResetAllButton.js
js/buttons/ResetAllButton.js
// Copyright 2002-2014, University of Colorado Boulder /** * Reset All button. This version is drawn in code using shapes, gradients, * and such, and does not use any image files. * * @author John Blanco */ define( function( require ) { 'use strict'; // modules var Color = require( 'SCENERY/util/Color' ); var inherit = require( 'PHET_CORE/inherit' ); var Path = require( 'SCENERY/nodes/Path' ); var RoundPushButton = require( 'SUN/buttons/RoundPushButton' ); var ResetAllShape = require( 'SCENERY_PHET/ResetAllShape' ); // Constants var DEFAULT_RADIUS = 24; // Derived from images initially used for reset button. /** * @param {Object} [options] * @constructor */ function ResetAllButton( options ) { var buttonRadius = options && options.radius ? options.radius : DEFAULT_RADIUS; options = _.extend( { // Default values radius: DEFAULT_RADIUS, minXMargin: buttonRadius * 0.2, // Default orange color scheme, standard for PhET reset buttons baseColor: new Color( 247, 151, 34 ), // The arrow shape doesn't look right when perfectly centered, account // for that here, and see docs in RoundButtonView. The multiplier // values were empirically determined. xContentOffset: buttonRadius * 0.03, yContentOffset: buttonRadius * ( -0.0125 ) }, options ); var icon = new Path( new ResetAllShape( options.radius ), { fill: 'white' } ); RoundPushButton.call( this, _.extend( { content: icon }, options ) ); // set a better id value for data collection this.buttonModel.property( 'down' ); } return inherit( RoundPushButton, ResetAllButton ); } );
JavaScript
0
@@ -759,16 +759,18 @@ Radius = + ( options @@ -787,16 +787,18 @@ s.radius + ) ? optio
03513250df89fa086fb1f22f623f2d50a390148b
Fix beta npm package CD versioning
.cicd/beta_npm_ver.js
.cicd/beta_npm_ver.js
#!/usr/bin/env node 'use strict' const shell = require('shelljs'); const cv = require('compare-version'); const fs = require('fs'); const FLAGFILE = "/tmp/deployment.flag"; const pjson = require('../package.json'); const oldPjson = JSON.parse(shell.exec("git show HEAD~1:package.json").output); const lastPublishedVersion = shell.exec("npm show "+pjson.name+" version").output.trim(); if (process.env.TRAVIS_BRANCH !== "develop"){ console.log("--- Not publishing."); return; }; fs.writeFile(FLAGFILE); console.log("--- Latest published version: ", lastPublishedVersion); console.log("--- Previous package.json version: ", oldPjson.version); console.log("--- Current package.json version: ", pjson.version); let versionBump = (cv(oldPjson.version, pjson.version) !== 0); console.log("===== Bumped version:", versionBump); if (!versionBump){ console.log("--- Publishing..."); if(cv(pjson.version, lastPublishedVersion) !== 0){ shell.exec("npm version " + lastPublishedVersion); } shell.exec("npm version --no-git-tag-version prerelease"); shell.exec("git status"); shell.exec("git add package.json"); shell.exec("git config --global user.name travis"); shell.exec("git config --global user.email [email protected]"); shell.exec("git commit --amend -C $(git rev-parse --verify HEAD)"); };
JavaScript
0.000034
@@ -126,16 +126,135 @@ e('fs'); +%0Aconst path = require('path');%0A%0Aconst cwd = path.dirname(require.main.filename);%0Aconst project_dir = path.dirname(cwd); %0A%0Aconst @@ -315,12 +315,32 @@ ire( -'../ +path.join(project_dir, ' pack @@ -345,24 +345,25 @@ ckage.json') +) ;%0Aconst oldP @@ -912,19 +912,17 @@ ersion) -!== +%3C 0);%0Acon @@ -1035,14 +1035,8 @@ -if(cv( pjso @@ -1044,17 +1044,18 @@ .version -, + = lastPub @@ -1071,337 +1071,470 @@ sion -) !== 0)%7B%0A shell.exec(%22npm version %22 + lastPublishedVersion);%0A %7D%0A shell.exec(%22npm version --no-git-tag-version prerelease%22);%0A shell.exec(%22git status%22);%0A shell.exec(%22git add package.json%22);%0A shell.exec(%22git config --global user.name travis%22);%0A shell.exec(%22git config --global user.email [email protected] +;%0A fs.writeFileSync(path.join(project_dir, 'package.json'), JSON.stringify(pjson, null, 2));%0A shell.exec(%22git add package.json%22);%0A shell.exec(%22git config --global user.name travis%22);%0A shell.exec(%22git config --global user.email [email protected]%22);%0A shell.exec(%22git commit --amend -C $(git rev-parse --verify HEAD)%22);%0A shell.exec(%22npm version --no-git-tag-version prerelease%22);%0A shell.exec(%22git status%22);%0A shell.exec(%22git add package.json %22);%0A
c72f03b0a28f0c6da7d970df73efe3fd28eca63f
fix deployConfig.requirejsNamespace, https://github.com/phetsims/chipper/issues/498
js/common/getDeployConfig.js
js/common/getDeployConfig.js
// Copyright 2015, University of Colorado Boulder var assert = require( 'assert' ); /** * Gets configuration information that is related to deploying sims. * * All fields are @public (read-only). * Fields include: * * Required: * {string} name - name of the repository being built * {string} version - version identifier * {string} simTitleStringKey - key of the sim's title string * {string} buildServerAuthorizationCode - password that verifies if build request comes from phet team members * {string} devUsername - username on our dev server * * Optional: * {string} devDeployServer - name of the dev server, defaults to 'spot.colorado.edu' * {string} devDeployPath - path on dev server to deploy to, defaults to '/htdocs/physics/phet/dev/html/' * {string} productionServerURL - production server url, defaults to 'https://phet.colorado.edu', can be over-ridden to 'https://phet-dev.colorado.edu' * * @author Chris Malley (PixelZoom, Inc.) */ (function() { 'use strict'; /** * @param fs - the node fs API * @returns {Object} deploy configuration information, fields documented above * * @private */ function getDeployConfig( fs ) { //------------------------------------------------------------------------------------ // read configuration files // ./package.json (required) var PACKAGE_FILENAME = 'package.json'; var packageJSON = JSON.parse( fs.readFileSync( PACKAGE_FILENAME, { encoding: 'utf-8' } ) ); assert( packageJSON.name, 'name missing from ' + PACKAGE_FILENAME ); assert( packageJSON.version, 'version missing from ' + PACKAGE_FILENAME ); // $HOME/.phet/build-local.json (required) var BUILD_LOCAL_FILENAME = process.env.HOME + '/.phet/build-local.json'; var buildLocalJSON = JSON.parse( fs.readFileSync( BUILD_LOCAL_FILENAME, { encoding: 'utf-8' } ) ); assert( buildLocalJSON.buildServerAuthorizationCode, 'buildServerAuthorizationCode missing from ' + BUILD_LOCAL_FILENAME ); assert( buildLocalJSON.devUsername, 'devUsername missing from ' + BUILD_LOCAL_FILENAME ); //------------------------------------------------------------------------------------ // Assemble the deployConfig var deployConfig = { // These fields have no dependencies on other entries in deployConfig. name: packageJSON.name, version: packageJSON.version, buildServerAuthorizationCode: buildLocalJSON.buildServerAuthorizationCode, buildServerNotifyEmail: buildLocalJSON.buildServerNotifyEmail || null, devUsername: buildLocalJSON.devUsername, devDeployServer: buildLocalJSON.devDeployServer || 'spot.colorado.edu', devDeployPath: buildLocalJSON.devDeployPath || '/htdocs/physics/phet/dev/html/', productionServerURL: buildLocalJSON.productionServerURL || 'https://phet.colorado.edu' }; // These fields depend on other entries in buildConfig. //TODO simTitleStringKey default is duplicated from getBuildConfig.js deployConfig.simTitleStringKey = deployConfig.requirejsNamespace + '/' + deployConfig.name + '.title'; return deployConfig; } // browser require.js-compatible definition if ( typeof define !== 'undefined' ) { define( function() { return getDeployConfig; } ); } // Node.js-compatible definition if ( typeof module !== 'undefined' ) { module.exports = getDeployConfig; } })();
JavaScript
0
@@ -227,18 +227,34 @@ Required + in package.json :%0A - * %7Bstri @@ -356,57 +356,93 @@ ng%7D -simTitleStringKey - key of the sim's title string +phet.requirejsNamespace - the requirejs namespace%0A *%0A * Required in build-local.json: %0A * @@ -617,16 +617,36 @@ Optional + in build-local.json :%0A * %7Bst @@ -1683,32 +1683,143 @@ KAGE_FILENAME ); +%0A assert( packageJSON.phet.requirejsNamespace, 'phet.requirejsNamespace missing from ' + PACKAGE_FILENAME ); %0A%0A // $HOME/. @@ -2507,24 +2507,24 @@ eJSON.name,%0A - versio @@ -2547,16 +2547,79 @@ ersion,%0A + requirejsNamespace: packageJSON.phet.requirejsNamespace,%0A bu
8b3160e07b1b177a940d9eed45eedf33b85fbcfb
Fix extraneous solution matrix
js/lights-out.js
js/lights-out.js
var numRows = 4 var numCols = 4 var matrix = [ [undefined, undefined, undefined, undefined], [undefined, undefined, undefined, undefined], [undefined, undefined, undefined, undefined], [undefined, undefined, undefined, undefined] ] var solution = [ [undefined, undefined, undefined, undefined], [undefined, undefined, undefined, undefined], [undefined, undefined, undefined, undefined], [undefined, undefined, undefined, undefined] ] var showSolution = false function getLightId(row, col) { return "#light-" + row + "-" + col } function setLightColor(row, col) { var color; if (matrix[row][col]) { color = "pink" } else { color = "gray" } var lightId = getLightId(row, col); $(lightId).css("background-color", color) } for (var row = 0; row < numRows; row++) { for (var col = 0; col < numCols; col++) { matrix[row][col] = Math.random() < 0.5 setLightColor(row, col) } } if (showSolution) { solve(); } function above(row) { if (row == 0) { return numRows -1 } else { return row - 1 } } function below(row) { if (row == numRows - 1) { return 0 } else { return row + 1 } } function left(col) { if (col == 0) { return numCols -1 } else { return col - 1 } } function right(col) { if (col == numCols - 1) { return 0 } else { return col + 1 } } function lightSwitch(row, col) { matrix[row][col] = !matrix[row][col]; setLightColor(row, col); } function checkWin() { var anyLightOn = false; for (var row = 0; row < numRows; row++) { for (var col = 0; col < numCols; col++) { if (matrix[row][col]) { anyLightOn = true; } } } return !anyLightOn; } function lightClick(row, col) { lightSwitch(row, col) lightSwitch(above(row), col) lightSwitch(below(row), col) lightSwitch(row, left(col)) lightSwitch(row, right(col)) if (checkWin()) { alert("You win!") } if (showSolution) { solve(); } } function solutionSwitch(row, col) { solution[row][col] = !solution[row][col] } function solutionClick(row, col) { solutionSwitch(row, col) solutionSwitch(above(row), col) solutionSwitch(below(row), col) solutionSwitch(row, left(col)) solutionSwitch(row, right(col)) } function solve() { solution = [ [false, false, false, false], [false, false, false, false], [false, false, false, false], [false, false, false, false] ] for (var row = 0; row < numRows; row++) { for (var col = 0; col < numCols; col++) { if (matrix[row][col]) { solutionClick(row, col) } } } for (var row = 0; row < numRows; row++) { for (var col = 0; col < numCols; col++) { var lightId = getLightId(row, col) if (solution[row][col]) { $(lightId).text("click me") } else { $(lightId).text("") } } } } function hideSolution() { for (var row = 0; row < numRows; row++) { for (var col = 0; col < numCols; col++) { var lightId = getLightId(row, col) $(lightId).text("") } } } function showHideSolution() { showSolution = !showSolution; if (showSolution) { solve(); $("#showHideButton").text("Hide solution") } else { hideSolution(); $("#showHideButton").text("Show solution") } }
JavaScript
0.000039
@@ -248,227 +248,8 @@ %0A%5D%0A%0A -var solution = %5B%0A %5Bundefined, undefined, undefined, undefined%5D,%0A %5Bundefined, undefined, undefined, undefined%5D,%0A %5Bundefined, undefined, undefined, undefined%5D,%0A %5Bundefined, undefined, undefined, undefined%5D%0A%5D%0A%0A var
cdad56940635c302934e566607c072473897b619
Rename 'connector' of a module-wire to 'handle'
js/components/module-wire.js
js/components/module-wire.js
(function(app) { 'use strict'; var jCore = require('jcore'); var helper = app.helper || require('../helper.js'); var dom = app.dom || require('../dom.js'); var ModuleWire = helper.inherits(function(props) { ModuleWire.super_.call(this); this.sourceX = this.prop(props.sourceX); this.sourceY = this.prop(props.sourceY); this.targetX = this.prop(props.targetX); this.targetY = this.prop(props.targetY); this.connectorType = this.prop(props.connectorType); this.connectorVisible = this.prop(!!props.connectorVisible); this.element = this.prop(null); this.parentElement = this.prop(null); this.cache = this.prop({}); }, jCore.Component); ModuleWire.prototype.pathElement = function() { // use 'dom.childNode' method for SVGElement return dom.childNode(this.element(), 0, 0); }; ModuleWire.prototype.connectorElement = function() { return dom.childNode(this.element(), 1); }; ModuleWire.prototype.redraw = function() { var element = this.element(); var parentElement = this.parentElement(); if (!parentElement && !element) return; // add element if (parentElement && !element) { element = dom.el('<div>'); dom.addClass(element, 'module-wire'); dom.html(element, ModuleWire.TEMPLATE_HTML); this.element(element); this.redraw(); dom.append(parentElement, element); return; } // remove element if (!parentElement && element) { dom.remove(element); this.element(null); this.cache({}); return; } // update element this.redrawPath(); this.redrawConnector(); }; ModuleWire.prototype.redrawPath = function() { var sourceX = this.sourceX(); var sourceY = this.sourceY(); var targetX = this.targetX(); var targetY = this.targetY(); var cache = this.cache(); if (sourceX === cache.sourceX && sourceY === cache.sourceY && targetX === cache.targetX && targetY === cache.targetY) { return; } var x = Math.min(sourceX, targetX); var y = Math.min(sourceY, targetY); var translate = 'translate(' + x + 'px, ' + y + 'px)'; var d = [ 'M', sourceX - x, sourceY - y, 'L', targetX - x, targetY - y ].join(' '); dom.css(this.element(), { transform: translate, webkitTransform: translate }); dom.attr(this.pathElement(), { d: d }); cache.sourceX = sourceX; cache.sourceY = sourceY; cache.targetX = targetX; cache.targetY = targetY; // for update of the connector cache.x = x; cache.y = y; }; ModuleWire.prototype.redrawConnector = function() { var type = this.connectorType(); var visible = this.connectorVisible(); var element = this.connectorElement(); var cache = this.cache(); if (cache.connectorType !== type) { dom.data(element, 'type', type); cache.connectorType = type; } if (cache.connectorVisible !== visible) { dom.toggleClass(element, 'hide', !visible); cache.connectorVisible = visible; } if (!visible) return; var x = cache.targetX - cache.x - ModuleWire.CONNECTOR_WIDTH / 2; var y = cache.targetY - cache.y - ModuleWire.CONNECTOR_WIDTH / 2; var translate = 'translate(' + x + 'px, ' + y + 'px)'; dom.css(element, { transform: translate, webkitTransform: translate }); }; ModuleWire.TEMPLATE_HTML = [ '<svg class="module-wire-path-container">', '<path class="module-wire-path"></path>', '</svg>', '<div class="module-wire-connector"></div>' ].join(''); ModuleWire.CONNECTOR_WIDTH = 24; if (typeof module !== 'undefined' && module.exports) module.exports = ModuleWire; else app.ModuleWire = ModuleWire; })(this.app || (this.app = {}));
JavaScript
0.00154
@@ -432,33 +432,30 @@ );%0A this. -connector +handle Type = this. @@ -465,25 +465,22 @@ p(props. -connector +handle Type);%0A @@ -483,33 +483,30 @@ );%0A this. -connector +handle Visible = th @@ -521,25 +521,22 @@ !!props. -connector +handle Visible) @@ -847,25 +847,22 @@ ototype. -connector +handle Element @@ -1616,25 +1616,22 @@ s.redraw -Connector +Handle ();%0A %7D; @@ -2534,25 +2534,22 @@ of the -connector +handle %0A cac @@ -2614,17 +2614,14 @@ draw -Connector +Handle = f @@ -2652,25 +2652,22 @@ = this. -connector +handle Type();%0A @@ -2689,25 +2689,22 @@ = this. -connector +handle Visible( @@ -2729,25 +2729,22 @@ = this. -connector +handle Element( @@ -2787,33 +2787,30 @@ if (cache. -connector +handle Type !== typ @@ -2865,25 +2865,22 @@ cache. -connector +handle Type = t @@ -2901,33 +2901,30 @@ if (cache. -connector +handle Visible !== @@ -2996,25 +2996,22 @@ cache. -connector +handle Visible @@ -3106,33 +3106,30 @@ ModuleWire. -CONNECTOR +HANDLE _WIDTH / 2;%0A @@ -3173,33 +3173,30 @@ ModuleWire. -CONNECTOR +HANDLE _WIDTH / 2;%0A @@ -3528,17 +3528,14 @@ ire- -connector +handle %22%3E%3C/ @@ -3572,17 +3572,14 @@ ire. -CONNECTOR +HANDLE _WID
49a2dbaede9dd2e73fc035f60a80d09bdbaf25f6
Remove support for old reporter usage
lib/cli.js
lib/cli.js
'use strict'; var configLoader = require('./config-loader'); var Lesshint = require('./lesshint'); var path = require('path'); var exit = require('exit'); var Vow = require('vow'); var EXIT_CODES = { OK: 0, WARNING: 1, ERROR: 2, NOINPUT: 66, SOFTWARE: 70, CONFIG: 78 }; var getReporter = function (reporter) { var reporterPath; // stylish is the default reporter = reporter || 'stylish'; // Check our core reporters first try { reporterPath = path.resolve(__dirname, './reporters/' + reporter + '.js'); return require(reporterPath); } catch (e) { // Empty } // Try to find it somewhere else try { reporterPath = path.resolve(process.cwd(), reporter); return require(reporterPath); } catch (e) { // Empty } // Try to load it as a module try { return require(reporter); } catch (e) { // Empty } return false; }; module.exports = function (program) { var lesshint = new Lesshint(); var exitDefer = Vow.defer(); var exitPromise = exitDefer.promise(); var promises = []; var config; exitPromise.always(function (status) { exit(status.valueOf()); }); if (!program.args.length) { console.error('No files to lint were passed. See lesshint -h'); exitDefer.reject(EXIT_CODES.NOINPUT); return exitPromise; } try { config = configLoader(program.config); config = config || {}; config.excludedFiles = config.excludedFiles || []; if (program.exclude) { config.excludedFiles.push(program.exclude); } } catch (e) { console.error("Something's wrong with the config file. Error: " + e.message); exitDefer.reject(EXIT_CODES.CONFIG); return exitPromise; } lesshint.configure(config); promises = program.args.map(lesshint.checkPath, lesshint); Vow.all(promises).then(function (results) { var hasError; var reporter; results = [].concat.apply([], results); reporter = getReporter(program.reporter); if (reporter) { if (reporter.report) { reporter.report(results); } else { console.warn('Reporters should expose a report() method. The old usage is deprecated and will be removed in 2.0.'); reporter(results); } } else { console.error('Could not find reporter "%s".', program.reporter); } if (!results.length) { exitDefer.resolve(EXIT_CODES.OK); return; } hasError = results.some(function (result) { return result.severity === 'error'; }); if (hasError) { exitDefer.reject(EXIT_CODES.ERROR); } else { exitDefer.reject(EXIT_CODES.WARNING); } }).fail(function (error) { console.error('An unkown error occured, please file an issue with this info:'); console.error(error.stack); exitDefer.reject(EXIT_CODES.SOFTWARE); }); return exitPromise; };
JavaScript
0
@@ -2186,274 +2186,33 @@ -if (reporter.report) %7B%0A reporter.report(results);%0A %7D else %7B%0A console.warn('Reporters should expose a report() method. The old usage is deprecated and will be removed in 2.0.');%0A reporter(results);%0A %7D +reporter.report(results); %0A
ce46ccc7b06b354346483be0fbd0e581efb6f4a5
add less than matcher on cloud9ide
lib/matchers.js
lib/matchers.js
var assert = require('assert'), url = require('url'); var matcher = function (actual) { var actual = actual, self = actual; this.beEqual = function (expected){ assert.equal(actual, expected); }; this.notBeEqual= function (expected) { assert.notDeepEqual(actual, expected); }; this.throwError = function () { var didThrow = false; try { actual(); }catch (e) { didThrow = true; } if (!didThrow) { throw { message : "Did not throw exception" } } }; this.beTrue = function () { assert.equal(actual, true); }; this.beFalse = function () { assert.equal(actual, false); }; this.contain = function (item) { var result = actual.lastIndexOf(item); if (result < 0) { throw { message : "Array does not contain item " + item } } }; // web matchers this.redirect_to = function (redirect_url) { if (self.statusCode < 300 || self.statusCode > 310) { throw { message: "Status Code not set to a redirect" } } urlObj = url.parse(self.headers.location); assert.equal(urlObj.pathname, redirect_url); }; return this; }; Object.defineProperty(Object.prototype, 'should', { value: function () { return matcher(this); }, });
JavaScript
0
@@ -303,24 +303,212 @@ ted);%0A %7D; +%0A %0A this.beLessThan = function (expected) %7B%0A if (actual %3E expected) %7B%0A throw %7B message: actual + %22 is greater than %22 + expected + %22 expected to be less%22%7D %0A %7D%0A %7D; %0A%0A this.thr
49c846b8859b8226b940a980a290362bdf237a7e
Refactor cli.js
lib/cli.js
lib/cli.js
#!/usr/bin/env node import meow from 'meow'; import fs from 'fs-promise'; import path from 'path'; import {buildTheme} from './'; import logger from './logger'; require('babel-polyfill'); (async function() { const optionsText = `Usage: $ base16-builder <command> $ base16-builder [-s <scheme>] [-t <template>] [-b <light|dark>] $ base16-builder [-s <scheme path>] [-t <template path>] Options: -s, --scheme Build theme using this color scheme -t, --template Build theme using this template -b, --brightness Build theme using this brightness Examples: $ base16-builder -s oceanicnext -t i3wm -b dark $ base16-builder --scheme oceanicnext --template i3wm --brightness dark $ base16-builder --scheme schemes/customScheme.yml --template templs/customTempl.nunjucks`; const cli = meow(optionsText, { alias: { h: 'help', t: 'template', s: 'scheme', b: 'brightness' } }); const {template: templNameOrPath, scheme: schemeNameOrPath, brightness} = cli.flags; if (!templNameOrPath || !schemeNameOrPath) { logger.error('fatal: You did not supply valid arguments. Run \'base16-builder -h\' for guidance.'); return; } let templPath; try { const templStat = await fs.lstat(templNameOrPath); if (templStat.isFile()) { templPath = templNameOrPath; } } catch (error) { } if (!templPath) { if (!brightness) { logger.error('fatal: You did not supply valid arguments. Run \'base16-builder -h\' for guidance.'); return; } if (brightness !== 'light' && brightness !== 'dark') { logger.error( 'fatal: You did not supply valid arguments. The value for brightness must be \'light\' or \'dark\'.'); return; } templPath = path.join(__dirname, `db/templates/${templNameOrPath}/${brightness}.nunjucks`); } let schemePath; try { const schemeStat = await fs.lstat(schemeNameOrPath); if (schemeStat.isFile()) { schemePath = schemeNameOrPath; } } catch (error) { } if (!schemePath) { schemePath = path.join(__dirname, `db/schemes/${schemeNameOrPath}.yml`); } let templ; try { templ = await fs.readFile(templPath, 'utf8'); } catch (err) { logger.error(`Could not find template ${templNameOrPath}.`); return; } let scheme; try { scheme = await fs.readFile(schemePath, 'utf8'); } catch (err) { logger.error(`Could not find scheme ${schemeNameOrPath}.`); return; } const theme = buildTheme(scheme, templ); logger.log(theme); })();
JavaScript
0.000008
@@ -204,16 +204,145 @@ ion() %7B%0A + async function resolvePath(path) %7B%0A let stat = await fs.lstat(path);%0A if (stat.isFile()) %7B%0A return path;%0A %7D%0A %7D%0A%0A const @@ -348,20 +348,16 @@ options -Text = %60Usag @@ -934,17 +934,16 @@ jucks%60;%0A -%0A const @@ -964,12 +964,8 @@ ions -Text , %7B%0A @@ -1358,23 +1358,17 @@ -const templ -St +P at +h = a @@ -1376,83 +1376,20 @@ ait -fs.lstat(templNameOrPath);%0A if (templStat.isFile()) %7B%0A templ +resolve Path - = +( temp @@ -1395,32 +1395,27 @@ plNameOrPath +) ;%0A - %7D%0A %7D catch (e @@ -1943,24 +1943,18 @@ -const scheme -St +P at +h = a @@ -1962,86 +1962,20 @@ ait -fs.lstat(schemeNameOrPath);%0A if (schemeStat.isFile()) %7B%0A schem +resolv ePath - = +( sche @@ -1986,24 +1986,19 @@ meOrPath +) ;%0A - %7D%0A %7D catc @@ -2009,20 +2009,21 @@ rror) %7B%0A - %7D%0A +%0A if (!s
1e12720406df9f59ef3b3aa398c58d26742beabb
Fix overzealous unfuckery in tab-fix command
lib/cmd.js
lib/cmd.js
"use strict"; const {exec} = require("child_process"); const commands = { /* Run GNU Make from project directory */ "user:make" (){ const projectPath = atom.project.getPaths(); exec(`cd '${projectPath[0]}' && make`); }, /* Toggle bracket-matcher highlights */ "body user:toggle-bracket-matcher" (){ let el = getRootEditorElement(); el && el.classList.toggle("show-bracket-matcher"); }, /* Fix for failed indent-detection */ "user:unfuck-tabstops" (){ const editor = global.ed; if(!editor) return; const squashedLines = editor.getText().match(/^\x20{2}/mg); // Seriously, fuck this tab-stop width. if(squashedLines.length > 1){ editor.setSoftTabs(true); editor.setTabLength(2).then(() => { atom.commands.dispatch(editor.editorElement, "whitespace:convert-spaces-to-tabs"); }); } }, /* Toggle either tree-view or Minimap, based on whether an editor's open */ "body user:toggle-sidebar" (){ const target = atom.views.getView(atom.workspace); const command = atom.workspace.getActivePaneItem() ? "minimap:toggle" : "tree-view:toggle"; atom.commands.dispatch(target, command); }, /* Reset editor's size to my preferred default, not Atom's */ "user:reset-font-size" (){ // HACK: Remove when APL package supports scoped font-size const size = ed && "source.apl" === ed.getGrammar().scopeName ? atom.config.getRawScopedValue(["source.apl"], "editor.fontSize") : 11; atom.config.set("editor.fontSize", size); }, /** Copy selection/buffer as Atom-core style grammar-specs */ "atom-text-editor user:specsaver": _=> global.specsaver(), /** XXX: Temporary function 1 */ "body user:temp-1": ContextualCommand({ "source.emacs.lisp": "language-emacs-lisp:run-selection", "source.css": global.evalCSS, "source.coffee" (){ const repo = atom.workspace.project.repositories[0]; if(repo && /^git@github\.com:atom\//i.test(repo.getOriginURL())){ global.ed.setSoftTabs(true); return global.ed.setTabLength(2); } } }), /* File-Icons: Debugging commands */ "file-icons:toggle-changed-only":_=> atom.config.set("file-icons.onChanges", !(atom.config.get("file-icons.onChanges"))), "file-icons:toggle-tab-icons":_=> atom.config.set("file-icons.tabPaneIcon", !(atom.config.get("file-icons.tabPaneIcon"))), "file-icons:open-settings":_=> atom.workspace.open("atom://config/packages/file-icons"), }; for(let name in commands){ let cmd = name.split(/\s+/); if(cmd.length < 2) cmd.unshift(""); atom.commands.add(cmd[0] || "atom-workspace", cmd[1], commands[name]); }
JavaScript
0
@@ -518,16 +518,124 @@ return;%0A +%09%09const hardenUp = () =%3E atom.commands.dispatch(editor.editorElement, %22whitespace:convert-spaces-to-tabs%22);%0A %09%09const @@ -682,16 +682,22 @@ %5E%5Cx20%7B2%7D +(?=%5CS) /mg);%0A%09%09 @@ -761,19 +761,8 @@ ines -.length %3E 1 )%7B%0A%09 @@ -824,113 +824,46 @@ hen( -() =%3E %7B%0A%09%09%09%09atom.commands.dispatch(editor.editorElement, %22whitespace:convert-spaces-to-tabs%22);%0A%09%09%09%7D);%0A%09%09%7D +hardenUp());%0A%09%09%7D%0A%09%09%0A%09%09else hardenUp(); %0A%09%7D,
bf2e315e797c3c95c22cce425f23dea29616081c
Update promizzes_test2.js
js/promizzes/promizzes_test2.js
js/promizzes/promizzes_test2.js
(function() { 'use strict'; define(['promizzes2', 'chai'], function(promizzes, chai) { var expect = chai.expect; var promise = promizzes.promise; var fulfill = promizzes.fulfill; var depend = promizzes.depend; var ajax = promizzes.ajax; describe('a promises system with every logic inside static methods (promizzes2)', function() { it('does ajax straight away', function(done) { this.timeout(5000); var data = ajax('http://localhost:8080/json/user.json'); var expectation = depend(data, expected({"name":"Marco","age":53,"town":"milano"})); depend(expectation, execute(done)); }); it('does chained ajax', function(done) { var data1 = ajax('http://localhost:8080/json/user.json'); var expectation1 = depend(data1, expected({"name":"Marco","age":53,"town":"milano"})); var data2 = depend(expectation1, function(data) { // NB: same as expectation1.value !!! return ajax('http://localhost:8080/json/' + data.town + '.json'); }); var expectation2 = depend(data2, expected({"name":"Milano","population":1500000})); depend(expectation2, execute(done)); }); function expected(expected) { return function(actual) { var result = promise(); expect(actual).to.be.eql(expected); console.log('promizzes2 test: ' + ((typeof actual === 'string') ? actual : JSON.stringify(actual))); fulfill(result, actual); return result; }; } function execute(cb) { return function executor(_) { var result = promise(); fulfill(result, cb()); return result; }; } it('builds a simple chain', function(done) { var sidePromise = promise(); var makeArea = function(sideVal) { var result = promise(); setTimeout(function() { fulfill(result, sideVal * sideVal); }, 200); return result; } var printStuff = function(stuffVal) { var result = promise(); expect(stuffVal).to.be.equal(25); setTimeout(function() { fulfill(result, console.log('promizzes2 test: ' + stuffVal)); }, 400); return result; } var beDone = function(_) { var result = promise(); setTimeout(function() { fulfill(result, done()); }, 400); return result; } // depend(promise, fapb) // fapb :: a -> promise b var areaPromise = depend(sidePromise, makeArea); var printPromise = depend(areaPromise, printStuff); fulfill(sidePromise, 5); var donePromise = depend(printPromise, beDone); }); }); }); })();
JavaScript
0
@@ -423,74 +423,25 @@ -this.timeout(5000);%0A var data = ajax('http://localhost:8080 +var data = ajax(' /jso
968e25269ec9277259d3c9a0ea8aeb4d2e315266
Remove debugging console output
js/foam/graphics/PieGraph.js
js/foam/graphics/PieGraph.js
/** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * 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. */ CLASS({ package: 'foam.graphics', name: 'PieGraph', extendsModel: 'foam.graphics.CView', properties: [ { name: 'r', type: 'int', view: 'foam.ui.IntFieldView', defaultValue: 50, postSet: function(old, nu) { if ( old === nu ) return; this.setDimensions(); } }, { name: 'lineColor', type: 'String', defaultValue: 'white' }, { name: 'lineWidth', type: 'int', defaultValue: 1, postSet: function(old, nu) { if ( old === nu ) return; this.setDimensions(); } }, { name: 'colorMap', defaultValue: undefined }, { name: 'data', type: 'Array[float]', factory: function() { return []; } }, { name: 'groups', label: 'Group Data', defaultValue: { } }, { model_: 'FunctionProperty', name: 'toColor', defaultValue: function(key, i, n) { return this.colorMap && this.colorMap[key] || this.toHSLColor(i, n); } } ], methods: { init: function() { this.SUPER.apply(this, arguments); this.setDimensions(); }, setDimensions: function() { console.log('Setting dimensions'); this.width = this.height = this.getDimensions(); }, getDimensions: function() { return 2 * (this.r + this.lineWidth); }, toCount: function(o) { return CountExpr.isInstance(o) ? o.count : o; }, toHSLColor: function(i, n) { return 'hsl(' + Math.floor(360*i/n) + ', 95%, 75%)'; }, paintSelf: function() { var c = this.canvas; if ( ! c ) return; var x = this.x; var y = this.y; var r = this.r; var sum = 0; var n = 0; for ( var key in this.groups ) { sum += this.toCount(this.groups[key]); n++; } // Drop shadown if ( r > 10 ) { c.fillStyle = 'lightgray'; c.beginPath(); c.arc(r+2, r+2, r, 0, 2 * Math.PI); c.fill(); } c.lineWidth = this.lineWidth; c.strokeStyle = this.lineColor; var rads = 0; var i = 0; for ( var key in this.groups ) { var start = rads; var count = this.toCount(this.groups[key]); rads += count / sum * 2 * Math.PI; c.fillStyle = this.toColor(key, i++, n); c.beginPath(); if ( count < sum ) c.moveTo(r,r); c.arc(r, r, r, start, rads); if ( count < sum ) c.lineTo(r,r); c.fill(); c.stroke(); } /* var grad = c.createLinearGradient(0, 0, r*2, r*2); grad.addColorStop( 0, 'rgba(0,0,0,0.1)'); grad.addColorStop(0.5, 'rgba(0,0,0,0)'); grad.addColorStop( 1, 'rgba(255,255,255,0.2)'); c.fillStyle = grad; c.arc(r+2, r+2, r, 0, 2 * Math.PI); c.fill(); */ } } });
JavaScript
0.000001
@@ -1841,49 +1841,8 @@ ) %7B%0A - console.log('Setting dimensions');%0A
db8d88fd5413a68147052d27c02367929d7d8bf9
use petname as tab title on feeds
modules/feed.js
modules/feed.js
var ref = require('ssb-ref') var ui = require('../ui') var Scroller = require('pull-scroll') var h = require('hyperscript') var pull = require('pull-stream') var u = require('../util') var plugs = require('../plugs') var sbot_user_feed = plugs.first(exports.sbot_user_feed = []) var message_render = plugs.first(exports.message_render = []) var avatar_profile = plugs.first(exports.avatar_profile = []) exports.screen_view = function (id) { //TODO: header of user info, avatars, names, follows. if(ref.isFeed(id)) { var content = h('div.column.scroller__content') var div = h('div.column.scroller', {style: {'overflow':'auto'}}, h('div.scroller__wrapper', h('div', avatar_profile(id)), content ) ) pull( sbot_user_feed({id: id, old: false, live: true}), Scroller(div, content, message_render, true, false) ) //how to handle when have scrolled past the start??? pull( u.next(sbot_user_feed, { id: id, reverse: true, limit: 50, live: false }, ['value', 'sequence']), Scroller(div, content, message_render, false, false) ) return div } }
JavaScript
0
@@ -396,16 +396,73 @@ le = %5B%5D) +%0Avar signifier = plugs.first(exports.signifier = %5B%5D) %0A%0Aexport @@ -799,24 +799,122 @@ )%0A )%0A%0A + signifier(id, function (_, names) %7B%0A if(names.length) div.title = names%5B0%5D.name%0A %7D)%0A%0A%0A pull(%0A @@ -1316,13 +1316,11 @@ %7D%0A + %7D%0A%0A%0A%0A%0A%0A -%0A%0A
9b6a8f2b18229fad9b2935196cda6a5b9c811b78
fix wiki link
js/id/ui/preset/wikipedia.js
js/id/ui/preset/wikipedia.js
iD.ui.preset.wikipedia = function(field, context) { var event = d3.dispatch('change', 'close'), wikipedia = iD.wikipedia(), language = iD.data.wikipedia[0], link, entity, lang, title; function i(selection) { var langcombo = d3.combobox() .fetcher(function(value, __, cb) { var v = value.toLowerCase(); cb(iD.data.wikipedia.filter(function(d) { return d[0].toLowerCase().indexOf(v) >= 0 || d[1].toLowerCase().indexOf(v) >= 0 || d[2].toLowerCase().indexOf(v) >= 0; }).map(function(d) { return { value: d[1] }; })); }); var titlecombo = d3.combobox() .fetcher(function(value, __, cb) { if (!value) value = context.entity(entity.id).tags.name || ''; var searchfn = value.length > 7 ? wikipedia.search : wikipedia.suggestions; searchfn(language && language[2], value, function(query, data) { cb(data.map(function(d) { return { value: d }; })); }); }); lang = selection.append('input') .attr('type', 'text') .attr('class', 'wiki-lang') .on('blur', changeLang) .on('change', changeLang) .call(langcombo); title = selection.append('input') .attr('type', 'text') .attr('class', 'wiki-title') .attr('id', 'preset-input-' + field.id) .on('blur', change) .on('change', change) .call(titlecombo); link = selection.append('a') .attr('class', 'wiki-link minor') .attr('target', '_blank') .append('span') .attr('class','icon out-link'); } function changeLang() { var value = lang.property('value').toLowerCase(); console.log(value); language = _.find(iD.data.wikipedia, function(d) { return d[0].toLowerCase() === value || d[1].toLowerCase() === value || d[2].toLowerCase() === value; }) || iD.data.wikipedia[0]; if (value !== language[0]) { lang.property('value', language[1]); } change(); } function change() { var t = {}; var value = title.property('value'); t[field.key] = value ? language[2] + ':' + value : ''; event.change(t); link.attr('href', 'http://' + language[2] + '.wikipedia.org/wiki/' + (value || '')); } i.tags = function(tags) { var m = tags[field.key] ? tags[field.key].match(/([^:]+):(.+)/) : null; // value in correct format if (m && m[1] && m[2]) { language = _.find(iD.data.wikipedia, function(d) { return m[1] === d[2]; }); if (language) lang.property('value', language[1]); else lang.property('value', m[1]); title.property('value', m[2]); link.attr('href', 'http://' + m[1] + '.wikipedia.org/wiki/' + m[2]); // unrecognized value format } else { lang.property('value', 'English'); title.property('value', tags[field.key] || ''); language = iD.data.wikipedia[0]; link.attr('href', 'http://en.wikipedia.org/wiki/Special:Search?search=' + tags[field.key]); } }; i.entity = function(_) { entity = _; }; i.focus = function() { title.node().focus(); }; return d3.rebind(i, event, 'on'); };
JavaScript
0
@@ -1831,16 +1831,17 @@ _blank') +; %0A @@ -1841,20 +1841,20 @@ - +link .append(
2f27e332ed5cfaa9f5cee14436df6dccddc5b264
simplify pipe replacement
lib/doc.js
lib/doc.js
const fs = require('fs') const path = require('path') const mkdirp = require('mkdirp').sync const titlecase = require('titlecase') const semver = require('semver') const marky = require('marky-markdown-lite') const matter = require('gray-matter') const toMarkdown = require('to-markdown') const versions = require(path.join(__dirname, '../_data/versions.json')).map(v => v.version) const hrefType = require('href-type') module.exports = class Doc { constructor (props) { Object.assign(this, props) this.$ = marky(this.markdown_content) // Fix relative links this.$('a').each((i, el) => { const href = this.$(el).attr('href') const type = hrefType(href) if (type !== 'relative' && type !== 'rooted') return const dirname = path.dirname(`/docs/${this.filename}`) this.$(el).attr('href', '{{site.baseurl}}' + path.resolve(dirname, href.replace(/\.md/, ''))) }) // Derive YML frontmatter for Jekyll this.frontmatter = { version: `v${versions[0]}`, permalink: this.permalink, category: this.category, redirect_from: this.redirects, source_url: `https://github.com/electron/electron/blob/master/docs/${this.filename}`, title: this.title, excerpt: this.excerpt, sort_title: path.basename(this.filename, '.md') } // Turn HTML string back into github-flavored markdown // and prepend with YML frontmatter this.output = matter.stringify( toMarkdown(this.$.html(), {gfm: true}), this.frontmatter ) // Work around kramdown's misinterpretation of pipe as a table header // https://github.com/electron/electron.atom.io/issues/556 this.output = this.output .split('\n') .map(line => { const match = line.match(/^\s*\*\s+`/) && line.match(/ \| /) return match ? line.replace(/ \| /g, ' &#124; ') : line }) .join('\n') this.save() } save () { if (!this.shouldBeOnWebsite) { console.log(`${this.outputFilename} (skipping)`) return } console.log(this.outputFilename) mkdirp(path.dirname(this.outputFilename)) fs.writeFileSync(this.outputFilename, this.output) } get outputFilename () { return path.join(__dirname, '../_docs/', this.filename) } get permalink () { return `/docs/${this.filename}/`.replace('.md', '') } get category () { if (this.filename.match('faq')) return 'FAQ' if (this.filename.match('api/')) return 'API' return titlecase(path.dirname(this.filename)) } // generate redirect paths for all Electron versions prior to 1.0.0 get redirects () { return versions .filter(v => semver.lt(v, '1.0.0')) .map(v => this.permalink.replace('docs/', `docs/v${v}/`)) .concat(this.permalink.replace('docs/', `docs/latest/`)) .concat(require('./redirects')[this.permalink] || []) } get title () { return (this.$('h1').first().text() || this.$('h2').first().text()) .trim() // .replace(/"/g, '\\\"') .replace(/^Class:\s*/, '') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') } get excerpt () { return (this.$('blockquote > p').first().html() || '') // .replace(/"/g, '\\\"') .replace(/\n/g, '\n ') } get shouldBeOnWebsite () { const patterns = [ 'api/', 'development/', 'tutorial/', 'faq' ] return patterns.some(pattern => !!this.filename.match(pattern)) } }
JavaScript
0.000005
@@ -1745,21 +1745,14 @@ -const match = +return lin @@ -1776,51 +1776,8 @@ +%60/) - && line.match(/ %5C%7C /)%0A return match ? l
176a601aa84e3940726ada26b3a68f131596e5e6
Change viewpane to be centered on init
lib/controller.js
lib/controller.js
"use strict"; var Userinput = require("./userinput/index"); var Scene = require("./scene"); var ViewpaneElement = require("./scene/Entity"); var vector = require("./common/vector"); var SpeedSnapAnimation = require("./scene/SpeedSnapAnimation"); var withObservable = require("./common/withObservable"); function el(elementId) { if (elementId && Object.prototype.toString.call(elementId) === "[object String]") { return document.getElementById(elementId); } else if (elementId && elementId.tagName) { return elementId; } console.log("invalid element id given", elementId); return null; } /** * ViewpaneJS controller * * @param {HTMLElement} screenEl * @param {HTMLElement} viewpaneEl * @param {Object} options */ function Viewpane(screenEl, viewpaneEl, options) { withObservable.call(this, ["onClick"]); screenEl = el(screenEl); viewpaneEl = el(viewpaneEl); var self = this; var viewpane = new ViewpaneElement(viewpaneEl); var viewpaneBound = viewpaneEl.getBoundingClientRect(); var focus = options.focus || vector.create(viewpaneBound.width, viewpaneBound.height, 0); this.scene = new Scene(screenEl, focus, options); this.viewpane = viewpane; this.scene.addEntity(viewpane); this.speedSnap = new SpeedSnapAnimation(this.scene, options); var startTime; var measured = 0; var measureFrom = vector.create(); var measureTo = vector.create(); // listen to user input on element $viewport var inputOrigin = vector.create(); new Userinput(screenEl, { // Remember: triggered again for each change in touch pointer count onStart: function (inputStartPosition) { inputOrigin.set(inputStartPosition); inputOrigin.z = self.scene.camera.getPosition().z; self.userInputStart(); measured = 0; measureTo.set(inputOrigin); startTime = Date.now(); }, // Remember: scaleVector.z-value := scale factor; x, y := relativeMovement onScale: function (scaleVector, currentPosition) { inputOrigin.set(currentPosition); inputOrigin.z = self.scene.camera.getPosition().z; scaleVector.z = self.scene.convertZScaleToPosition(scaleVector.z); self.moveBy(scaleVector, inputOrigin); measured += 1; measureFrom.set(measureTo); measureTo.set(inputOrigin); }, onEnd: function (event) { if (measured > 1) { measureFrom.subtract(measureTo); measureFrom.z = 0; if (measureFrom.getLength() > 5) { return self.userInputStop(inputOrigin, measureFrom); } } else { // clicked. // Convert click point, to point on viewpane var viewpanePosition = self.scene.getPosition(); // clickTarget in screen space var clickTarget = inputOrigin.clone(); clickTarget.z = 0; // convert to screen position to position in viewpane z distance clickTarget.invertProject(self.scene.camera.eye, inputOrigin.z); // adjust target by viewpane translation clickTarget.subtract(viewpanePosition); clickTarget.z= 0; self.notify("select", event, clickTarget); } self.userInputStop(inputOrigin, vector.origin); } }); } Viewpane.prototype.userInputStart = function () { this.speedSnap.stop(); this.scene.activate(); }; Viewpane.prototype.userInputStop = function (origin, speedVector) { this.scene.deactivate(); this.speedSnap.from.set(this.scene.getPosition()); this.speedSnap.start(speedVector, origin); }; Viewpane.prototype.repaint = function () { this.scene.calculate(); this.scene.render(); }; Viewpane.prototype.moveBy = function (moveVector, origin) { this.scene.moveVisual(moveVector, origin); }; Viewpane.prototype.addEntity = function (entity) { this.scene.addEntity(entity); }; Viewpane.prototype.fit = function () { this.scene.fitToViewport(); }; Viewpane.prototype.createEntity = function (elementId) { var entity = new ViewpaneElement(el(elementId)); this.addEntity(entity); return entity; }; Viewpane.prototype.setPosition = function (position) { this.scene.setPosition(position); }; Viewpane.prototype.getPosition = function (position) { // evaluate apis corrdinate system // return this.scene.getPosition().clone().project(this.scene.camera.eye); return this.scene.getPosition(); }; Viewpane.prototype.getScene = function (position) { return this.scene; }; Viewpane.prototype.getViewpane = function (position) { return this.viewpane; }; module.exports = Viewpane;
JavaScript
0
@@ -3519,16 +3519,33 @@ %0A %7D); +%0A%0A this.fit(); %0A%7D%0A%0AView