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
efafa2f2b465a3da2edb6936ced1ebfdb7bd922d
Add missing function name
lib/node_modules/@stdlib/utils/is-anagram/test/test.js
lib/node_modules/@stdlib/utils/is-anagram/test/test.js
'use strict'; // MODULES // var tape = require( 'tape' ); var isAnagram = require( './../lib' ); // TESTS // tape( 'main export is a function', function test( t ) { t.ok( true, __filename ); t.strictEqual( typeof isAnagram, 'function', 'main export is a function' ); t.end(); }); tape( 'the function throws an error if not provided a primitive comparison string', function test( t ) { var values; var i; values = [ 5, null, undefined, NaN, true, [], {}, function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] ); } t.end(); function badValue( value ) { return function () { isAnagram( value ); }; } }); tape( 'the function returns `true` if provided an anagram', function test( t ) { t.strictEqual( isAnagram( 'bat', 'tab' ), true, 'returns true when provided `bat` and `tab`' ); t.strictEqual( isAnagram( 'bat', 'TaB' ), true, 'returns true when provided `bat` and `TaB`' ); t.strictEqual( isAnagram( 'bat', 't a b' ), true, 'returns true when provided `bat` and `t a b`' ); t.strictEqual( isAnagram( 'bat', 'TAB' ), true, 'returns true when provided `bat` and `TAB`' ); t.strictEqual( isAnagram( 'William Shakespeare', 'I am a weakish speller' ), true, 'returns true when provided `William Shakespeare` and `I am a weakish speller`' ); t.strictEqual( isAnagram( 'bat 321', 'tab 123' ), true, 'returns true when provided `bat 321` and `tab 123`' ); t.end(); }); tape( 'the function returns `false` if not provided an anagram', function test( t ) { var values; var i; values = [ 'abbt', 'bbt', 5, null, undefined, true, NaN, [], {}, function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.strictEqual( isAnagram( 'bat', values[i] ), false, 'returns false when provided ' + values[i] + ' and `bat`' ); } t.end(); });
JavaScript
0.999928
@@ -699,16 +699,24 @@ unction +badValue () %7B%0A%09%09%09
6ee5ae9d4df79f32853aea90dbf843d214da1979
add new retailer
app-webdriver/components/crawler/CrawlerInstance.js
app-webdriver/components/crawler/CrawlerInstance.js
/** * Created by Shawn Liu on 2015/5/20. */ var ScrapeQueue = require("./ScrapeQueue"); var Promise = require("bluebird"); var webdriver = require('selenium-webdriver'), By = require('selenium-webdriver').By, until = require('selenium-webdriver').until; var async = require("async"); var logger = require("node-config-logger").getLogger("app-webdriver/components/crawler/CrawlerInstance.js"); var fs = require("fs"); var rp = require("request-promise"); var _ = require("lodash"); function CrawlerInstance(serverURL, type) { this.server = serverURL; this.port = serverURL.replace("http://127.0.0.1:", ""); this.id = serverURL; this.queue = new ScrapeQueue(this, { id: this.server, maxRetries: 3 }); this.type = type; this.timeout = 60000; } CrawlerInstance.prototype.request = function (job, selectorConfig) { if (job.method === "details") { return _scrapeDetails(job.productURL, selectorConfig.selectors, job.browser, this); } else if (job.method === "links") { return _scrapeDetails(job.productURL, selectorConfig.selectors, job.browser, this); } //return _scrape(job.productURL, selectorConfig.selectors, job.browser, this) } var listenerConfig = require("config").listener.driverInstanceApp; CrawlerInstance.prototype.restart = function () { return rp("http://127.0.0.1:" + listenerConfig.port + "/driver/restart/" + this.type + "/" + this.port); } function _scrapeLinks() { } /** * assume each element has multiply css or xpath selector * @param driver * @param selectorConfig * @param jsonResult * @returns {*} * @private */ function _extractDataBySelector(driver, selectorConfig, jsonResult, productURL) { return new Promise(function (resolve, reject) { var selectors = _.cloneDeep(selectorConfig.content); jsonResult[selectorConfig.field] = null; async.until(function isDone() { return selectors.length === 0 || jsonResult[selectorConfig.field]; }, function next(callback) { var selector = selectors.shift(); var byC = ""; if (selectorConfig.selectorType === "css") { byC = By.css(selector); } else { byC = By.xpath(selector); } var element = driver.findElement(byC); element.getText() .then(function (content) { jsonResult[selectorConfig.field] = content; callback() }, function onError(err) { var error = { "productURL": productURL, "message": err.state, "code": err.code, "selector": selector }; logger.error(error); delete error.productURL; if (selectors.length === 0) { jsonResult.status = false; error.selector = selectorConfig; jsonResult.errors.push(error); } callback(); }) }, function done() { resolve(jsonResult); }) }); } function _scrapeDetails(productURL, selectors, browser, ph) { var jsonResult = { "status": true, "productURL": productURL, "errors": [], "selectors": _.cloneDeep(selectors) }; return new Promise(function (resolve, reject) { if (!browser) { browser = "phantomjs"; } var instanceTimeout = setTimeout(function () { ph.restart() .catch(function (err) { logger.error("Restart phantom instance:", err); }) .finally(function () { resolve({ "status": false, "message": "server '" + ph.id + "' timeout" }) }) }, ph.timeout); try { if (_isValidBrowser(browser)) { var driver = new webdriver.Builder() .forBrowser(browser) .usingServer(ph.server) .build(); driver.get(productURL); async.until(function isDone() { return selectors.length === 0; }, function next(callback) { var selector = selectors.shift(); _extractDataBySelector(driver, selector, jsonResult, productURL) .then(function (result) { jsonResult = result; }) .catch(function (err) { logger.error(err) }) .finally(function () { callback(); }) }, function done() { driver.quit() .then(function () { clearTimeout(instanceTimeout); resolve(jsonResult); }) }) } else { logger.error("Invalid browser '%s'", browser); jsonResult.errors.push({ "message": "Invalid browser '" + browser + "'" }) clearTimeout(instanceTimeout); resolve(jsonResult); } } catch (err) { logger.error("catch error"); logger.error(err); jsonResult.errors.push({ "message": err.message || err }) clearTimeout(instanceTimeout); resolve(jsonResult); } }) } function _isValidBrowser(browser) { return true; } function writeScreenshot(data, name) { name = name || 'ss.png'; var screenshotPath = path.join(__dirname, ""); fs.writeFileSync(screenshotPath + name, data, 'base64'); }; module.exports = CrawlerInstance;
JavaScript
0
@@ -779,17 +779,17 @@ meout = -6 +3 0000;%0A%0A%7D
a7f9ea1340392fae44976db5503e3fcd64443c30
fix tests
e2e-tests/scenarios.js
e2e-tests/scenarios.js
'use strict'; /* https://github.com/angular/protractor/blob/master/docs/toc.md */ describe('my app', function() { browser.get('home.html'); it('should automatically redirect to /view1 when location hash/fragment is empty', function() { expect(browser.getLocationAbsUrl()).toMatch("/view1"); }); describe('view1', function() { beforeEach(function() { browser.get('home.html#/view1'); }); it('should render view1 when user navigates to /view1', function() { expect(element.all(by.css('[ng-view] p')).first().getText()). toMatch(/partial for view 1/); }); }); describe('view2', function() { beforeEach(function() { browser.get('home.html#/view2'); }); it('should render view2 when user navigates to /view2', function() { expect(element.all(by.css('[ng-view] p')).first().getText()). toMatch(/partial for view 2/); }); }); });
JavaScript
0.000001
@@ -121,28 +121,29 @@ rowser.get(' -home +index .html');%0A%0A @@ -378,36 +378,37 @@ browser.get(' -home +index .html#/view1');%0A @@ -699,12 +699,13 @@ et(' -home +index .htm
03a556e43f543f7d26fa331c31f610e1be2fc3ab
adding correct sw js url
gulpfile.babel.js
gulpfile.babel.js
'use strict'; import gulp from 'gulp'; import gulpLoadPlugins from 'gulp-load-plugins'; import runSequence from 'run-sequence'; import browserSync from 'browser-sync'; import access from 'gulp-accessibility'; import swPrecache from 'sw-precache'; import rename from 'gulp-rename'; const $ = gulpLoadPlugins(); // Test our website accessibility gulp.task('accessibility', function() { return gulp.src('./_site/**/*.html') .pipe(access({ force: true, verbose: false, // true: to output error to console; false: output report files only options: { accessibilityLevel: 'WCAG2AA', reportLocation: 'accessibility-reports', reportLevels: { notice: true, warning: true, error: true } } })) .on('error', console.log) .pipe(access.report({reportType: 'txt'})) .pipe(rename({extname: '.txt'})) .pipe(gulp.dest('reports/json')); }); // Minify the HTML. gulp.task('minify-html', () => { return gulp.src('_site/**/*.html') .pipe($.htmlmin({ removeComments: true, collapseWhitespace: true, collapseBooleanAttributes: true, removeAttributeQuotes: true, removeRedundantAttributes: true, removeEmptyAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true, removeOptionalTags: true })) .pipe(gulp.dest('_site')); }); // Optimize images. gulp.task('minify-images', () => { gulp.src('images/**/*') .pipe($.imagemin({ progressive: true, interlaced: true })) .pipe(gulp.dest('_site/images')); }); // Concatenate, transpiles ES2015 code to ES5 and minify JavaScript. gulp.task('scripts', () => { gulp.src([ // Note: You need to explicitly list your scripts here in the right order // to be correctly concatenated './_scripts/vendor/medium-lightbox.js', './_scripts/vendor/anime.js', './_scripts/vendor/headroom.js', './_scripts/main.js' ]) // .pipe($.babel()) .pipe($.concat('main.min.js')) .pipe($.uglify({preserveComments: 'some'})) .pipe(gulp.dest('scripts')); }); // Minify and add prefix to css. gulp.task('css', () => { const AUTOPREFIXER_BROWSERS = [ 'ie >= 10', 'ie_mob >= 10', 'ff >= 30', 'chrome >= 34', 'safari >= 7', 'opera >= 23', 'ios >= 7', 'android >= 4.4', 'bb >= 10' ]; return gulp.src('css/main.css') .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS)) .pipe($.cssnano()) .pipe(gulp.dest('_site/css')); }); // Compile scss to css. gulp.task('scss', () => { return gulp.src('scss/main.scss') .pipe($.sass({ includePaths: ['css'], onError: browserSync.notify })) .pipe(gulp.dest('css')); }); // Watch change in files. gulp.task('serve', ['jekyll-build-dev'], () => { browserSync.init({ notify: false, // Run as an https by uncommenting 'https: true' // Note: this uses an unsigned certificate which on first access // will present a certificate warning in the browser. // https: true, server: '_site', port: 3000 }); // Watch html changes. gulp.watch([ 'css/**/*.css', 'scripts/**/*.js', '_includes/**/*.html', '_layouts/**/*.html', '_posts/**/*.md', '*.md', '*.html', '_config.yml' ], ['jekyll-build-dev', browserSync.reload]); // Watch scss changes. gulp.watch('scss/**/*.scss', ['scss']); // Watch JavaScript changes. gulp.watch('_scripts/**/*.js', ['scripts']); }); gulp.task('generate-service-worker-production', function(callback) { var path = require('path'); var rootDir = '_site'; swPrecache.write(path.join(rootDir, 'sw.js'), { staticFileGlobs: [rootDir + '/**/*.{js,html,css,png,jpg,gif,json}'], stripPrefix: rootDir, replacePrefix: '/' }, callback); }); gulp.task('generate-service-worker-gh-pages', function(callback) { var path = require('path'); var rootDir = '_site'; swPrecache.write(path.join(rootDir, 'sw.js'), { staticFileGlobs: [rootDir + '/**/*.{js,html,css,png,jpg,gif,json}'], stripPrefix: rootDir, replacePrefix: '/faulkner' }, callback); }); gulp.task('jekyll-build-prod', ['scripts', 'scss'], $.shell.task([ 'jekyll build --config _config.yml' ])); gulp.task('jekyll-build-test', ['scripts', 'scss'], $.shell.task([ 'jekyll build --config _config-test.yml' ])); gulp.task('jekyll-build-dev', ['scripts', 'scss'], $.shell.task([ 'jekyll build --config _config.yml,_config-dev.yml' ])); // Default local task. gulp.task('default', () => runSequence( 'scss', 'jekyll-build-dev', 'minify-html', 'css', 'generate-service-worker-production', 'minify-images' ) ); // Deploy website to static01. gulp.task('deploy-to-prod', () => { runSequence( 'scss', 'jekyll-build-prod', 'minify-html', 'css', 'generate-service-worker-production', 'minify-images' ) }); // Deploy website to gh-pages. gulp.task('gh-pages', () => { return gulp.src('./_site/**/*') .pipe($.ghPages()); }); gulp.task('deploy-to-test', () => { runSequence( 'scss', 'jekyll-build-test', 'minify-html', 'css', 'generate-service-worker-gh-pages', 'minify-images', 'gh-pages' ) });
JavaScript
0.99986
@@ -3851,17 +3851,16 @@ refix: ' -/ '%0A %7D, c
899c655fe3fade0def42b4cbce95a7af285ebe3c
Fix map generation on the end of block
lib/map-generator.js
lib/map-generator.js
import { Base64 } from 'js-base64'; import mozilla from 'source-map'; import path from 'path'; export default class { constructor(root, opts) { this.root = root; this.opts = opts; this.mapOpts = opts.map || { }; } isMap() { if ( typeof this.opts.map !== 'undefined' ) { return !!this.opts.map; } else { return this.previous().length > 0; } } previous() { if ( !this.previousMaps ) { this.previousMaps = []; this.root.eachInside( (node) => { if ( node.source && node.source.input.map ) { let map = node.source.input.map; if ( this.previousMaps.indexOf(map) === -1 ) { this.previousMaps.push(map); } } }); } return this.previousMaps; } isInline() { if ( typeof this.mapOpts.inline !== 'undefined' ) { return this.mapOpts.inline; } let annotation = this.mapOpts.annotation; if ( typeof annotation !== 'undefined' && annotation !== true ) { return false; } if ( this.previous().length ) { return this.previous().some( i => i.inline ); } else { return true; } } isSourcesContent() { if ( typeof this.mapOpts.sourcesContent !== 'undefined' ) { return this.mapOpts.sourcesContent; } if ( this.previous().length ) { return this.previous().some( i => i.withContent() ); } else { return true; } } clearAnnotation() { if ( this.mapOpts.annotation === false ) return; let node; for ( let i = this.root.nodes.length - 1; i >= 0; i-- ) { node = this.root.nodes[i]; if ( node.type !== 'comment' ) continue; if ( node.text.indexOf('# sourceMappingURL=') === 0 ) { this.root.remove(i); } } } setSourcesContent() { let already = { }; this.root.eachInside( (node) => { if ( node.source ) { let from = node.source.input.from; if ( from && !already[from] ) { already[from] = true; let relative = this.relative(from); this.map.setSourceContent(relative, node.source.input.css); } } }); } applyPrevMaps() { for ( let prev of this.previous() ) { let from = this.relative(prev.file); let root = prev.root || path.dirname(prev.file); let map; if ( this.mapOpts.sourcesContent === false ) { map = new mozilla.SourceMapConsumer(prev.text); if ( map.sourcesContent ) { map.sourcesContent = map.sourcesContent.map( () => null ); } } else { map = prev.consumer(); } this.map.applySourceMap(map, from, this.relative(root)); } } isAnnotation() { if ( this.isInline() ) { return true; } else if ( typeof this.mapOpts.annotation !== 'undefined' ) { return this.mapOpts.annotation; } else if ( this.previous().length ) { return this.previous().some( i => i.annotation ); } else { return true; } } addAnnotation() { let content; if ( this.isInline() ) { content = 'data:application/json;base64,' + Base64.encode( this.map.toString() ); } else if ( typeof this.mapOpts.annotation === 'string' ) { content = this.mapOpts.annotation; } else { content = this.outputFile() + '.map'; } this.css += '\n/*# sourceMappingURL=' + content + ' */'; } outputFile() { if ( this.opts.to ) { return this.relative(this.opts.to); } else if ( this.opts.from ) { return this.relative(this.opts.from); } else { return 'to.css'; } } generateMap() { this.stringify(); if ( this.isSourcesContent() ) this.setSourcesContent(); if ( this.previous().length > 0 ) this.applyPrevMaps(); if ( this.isAnnotation() ) this.addAnnotation(); if ( this.isInline() ) { return [this.css]; } else { return [this.css, this.map]; } } relative(file) { let from = this.opts.to ? path.dirname(this.opts.to) : '.'; if ( typeof this.mapOpts.annotation === 'string' ) { from = path.dirname( path.resolve(from, this.mapOpts.annotation) ); } file = path.relative(from, file); if ( path.sep === '\\' ) { return file.replace(/\\/g, '/'); } else { return file; } } sourcePath(node) { return this.relative(node.source.input.from); } stringify() { this.css = ''; this.map = new mozilla.SourceMapGenerator({ file: this.outputFile() }); let line = 1; let column = 1; let lines, last; let builder = (str, node, type) => { this.css += str; if ( node && node.source && node.source.start && type !== 'end' ) { this.map.addMapping({ source: this.sourcePath(node), original: { line: node.source.start.line, column: node.source.start.column - 1 }, generated: { line: line, column: column - 1 } }); } lines = str.match(/\n/g); if ( lines ) { line += lines.length; last = str.lastIndexOf('\n'); column = str.length - last; } else { column = column + str.length; } if ( node && node.source && node.source.end && type !== 'start' ) { this.map.addMapping({ source: this.sourcePath(node), original: { line: node.source.end.line, column: node.source.end.column }, generated: { line: line, column: column } }); } }; this.root.stringify(builder); } generate() { this.clearAnnotation(); if ( this.isMap() ) { return this.generateMap(); } else { return [this.root.toString()]; } } }
JavaScript
0
@@ -6619,24 +6619,28 @@ lumn: column + - 1 %0A
afae87ab3f681ee08ba4cb5244fe3993bd1ac1c8
Use both short- and long-form getText
lib/i18n.js
lib/i18n.js
/* * Utilities: A classic collection of JavaScript utilities * Copyright 2112 Matthew Eernisse ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ var core = require('./core') , i18n; i18n = new (function () { var _defaultLocale = 'en-us' , _strings = {}; this.getText = function (key, opts, locale) { var currentLocale = locale || _defaultLocale , currentLocaleStrings = _strings[currentLocale] || {} , defaultLocaleStrings = _strings[_defaultLocale] || {} , str = currentLocaleStrings[key] || defaultLocaleStrings[key] || "[[" + key + "]]"; for (p in opts) { str = str.replace(new RegExp('\\{' + p + '\\}', 'g'), opts[p]); } return str; }; this.getDefaultLocale = function (locale) { return _defaultLocale; }; this.setDefaultLocale = function (locale) { _defaultLocale = locale; }; this.loadLocale = function (locale, strings) { _strings[locale] = _strings[locale] || {}; core.mixin(_strings[locale], strings); }; })(); i18n.I18n = function (locale) { this.t = function (key, opts) { return i18n.getText(key, opts || {}, locale); }; }; module.exports = i18n;
JavaScript
0.000002
@@ -1589,16 +1589,22 @@ %0A this. +getTex t = func @@ -1677,16 +1677,41 @@ );%0A %7D;%0A + this.t = this.getText;%0A %7D;%0A%0Amodu
960aea2ebebdcb878069e30493e4a950ea5daf03
Use <noscript> instead of <span> to avoid inline style for CSP
lib/marko-widgets.js
lib/marko-widgets.js
/* * Copyright 2011 eBay Software Foundation * * 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. */ /** * Module to manage the lifecycle of widgets * */ var stringify = require('raptor-json/stringify'); var raptorRenderer = require('raptor-renderer'); var WidgetsContext = require('./WidgetsContext'); var TAG_START = '<span id="markoWidgets" data-ids="'; var TAG_END = '" style="display:none;"></span>'; var STRINGIFY_OPTIONS = { special: /([^ -~]|(["'\\<&%]))/g, replace: { '"': '\\u0022', '\n': '\\n' }, useSingleQuote: true }; function WrappedString(val) { this.html = val; } WrappedString.prototype = { toString: function() { return this.html; } }; exports.WidgetsContext = WidgetsContext; exports.getWidgetsContext = WidgetsContext.getWidgetsContext; exports.uniqueId = require('./uniqueId'); exports.attrs = function(widgetDef) { if (!widgetDef.type) { return null; } var attrs = { 'data-widget': widgetDef.type }; var widgetConfig = widgetDef.config; if (widgetConfig) { attrs['data-w-config'] = new WrappedString(stringify(widgetConfig, STRINGIFY_OPTIONS)); } var widgetState = widgetDef.state; if (widgetState) { attrs['data-w-state'] = new WrappedString(stringify(widgetState, STRINGIFY_OPTIONS)); } var hasDomEvents = widgetDef.hasDomEvents; if (hasDomEvents) { attrs['data-w-on'] = '1'; } var customEvents = widgetDef.customEvents; if (customEvents) { attrs['data-w-events'] = widgetDef.scope + ',' + customEvents.join(','); } var extend = widgetDef.extend; if (extend && extend.length) { attrs['data-w-extend'] = new WrappedString(extend.join(',')); } var bodyElId = widgetDef.bodyElId; if (bodyElId != null) { attrs['data-w-body'] = bodyElId === '' ? true : bodyElId; } return attrs; }; exports.writeDomEventsEl = function(widgetDef, out) { var domEvents = widgetDef.domEvents; if (domEvents) { out.write('<span id="' + widgetDef.elId('$on') + '" data-on="' + domEvents.join(',') + '"></span>'); } }; exports.writeInitWidgetsCode = function(widgetsContext, out, options) { var clearWidgets = true; var scanDOM = false; var immediate = false; if (options) { clearWidgets = options.clearWidgets !== false; scanDOM = options.scanDOM === true; immediate = options.immediate === true; } if (scanDOM) { out.write(TAG_START + '*' + TAG_END); } else { var widgets = widgetsContext.getWidgets(); if (!widgets || !widgets.length) { return; } var ids = ''; var commaRequired = false; var writeWidget = function(widget) { if (widget.children.length) { // Depth-first search (children should be initialized before parent) writeWidgets(widget.children); } if (commaRequired) { ids += ','; } else { commaRequired = true; } ids += widget.id; }; var writeWidgets = function(widgets) { for (var i = 0, len = widgets.length; i < len; i++) { writeWidget(widgets[i]); } }; writeWidgets(widgets); if (immediate) { out.write('<script type="text/javascript">$markoWidgets("' + ids + '")</script>'); } else { out.write(TAG_START + ids + TAG_END); } } if (clearWidgets !== false) { widgetsContext.clearWidgets(); } }; function getWidgetIdsString(widgetsContext) { if (!widgetsContext) { throw new Error('"widgetsContext" is required'); } if (!(widgetsContext instanceof WidgetsContext)) { // Assume that the provided "widgetsContext" argument is // actually an AsyncWriter var asyncWriter = widgetsContext; if (!asyncWriter.global) { throw new Error('Invalid argument: ' + widgetsContext); } widgetsContext = WidgetsContext.getWidgetsContext(asyncWriter); } var widgets = widgetsContext.getWidgets(); if (!widgets || !widgets.length) { return; } var ids = ''; var commaRequired = false; function writeWidget(widget) { if (widget.children.length) { // Depth-first search (children should be initialized before parent) writeWidgets(widget.children); } if (commaRequired) { ids += ','; } else { commaRequired = true; } ids += widget.id; } function writeWidgets(widgets) { for (var i = 0, len = widgets.length; i < len; i++) { writeWidget(widgets[i]); } } writeWidgets(widgets); return ids; } exports.getInitWidgetsCode = function(widgetsContext) { var idsString = getWidgetIdsString(widgetsContext); return '$markoWidgets("' + idsString + '");'; }; exports.getRenderedWidgetIds = function(widgetsContext) { var idsString = getWidgetIdsString(widgetsContext); return idsString; }; exports.makeRenderable = exports.renderable = raptorRenderer.renderable; exports.render = raptorRenderer.render; exports.defineComponent = require('./defineComponent'); exports.defineWidget = require('./defineWidget'); exports.defineRenderer = require('./defineRenderer'); // registerWidget is a no-op on the server. // Fixes https://github.com/marko-js/marko-widgets/issues/111 exports.registerWidget = function() {};
JavaScript
0
@@ -821,20 +821,24 @@ ART = '%3C -span +noscript id=%22mar @@ -881,37 +881,19 @@ = '%22 - style=%22display:none;%22%3E%3C/span +%3E%3C/noscript %3E';%0A
53e8f329741460f3fe1fca0e905c2b696220fadf
Use toggleModal for headerbar navigation
library/Denkmal/library/Denkmal/Component/HeaderBar.js
library/Denkmal/library/Denkmal/Component/HeaderBar.js
/** * @class Denkmal_Component_HeaderBar * @extends Denkmal_Component_Abstract */ var Denkmal_Component_HeaderBar = Denkmal_Component_Abstract.extend({ /** @type String */ _class: 'Denkmal_Component_HeaderBar', /** @type Boolean */ narrow: null, events: { 'click .menu.dates .active .navButton': function() { if (!this.narrow) { return; } this.toggleMenu(true); }, 'click .menu-expand .menu.dates .navButton': function() { if (!this.narrow) { return; } this.toggleMenu(false); } }, ready: function() { var self = this; var handlers = { match: function() { self.narrow = true; }, unmatch: function() { self.narrow = false; self.toggleMenu(false); } }; enquire.register('(max-width: 580px)', handlers); this.on('destruct', function() { enquire.unregister('(max-width: 580px)', handlers); }); }, /** * * @param {Boolean} state */ toggleMenu: function(state) { this.$('.bar').toggleClass('menu-expand', state); } });
JavaScript
0
@@ -324,33 +324,32 @@ n() %7B%0A if ( -! this.narrow) %7B%0A @@ -349,38 +349,16 @@ ow) %7B%0A - return;%0A %7D%0A th @@ -374,24 +374,32 @@ Menu(true);%0A + %7D%0A %7D,%0A%0A @@ -470,9 +470,8 @@ if ( -! this @@ -487,30 +487,8 @@ %7B%0A - return;%0A %7D%0A @@ -509,24 +509,32 @@ enu(false);%0A + %7D%0A %7D%0A %7D,%0A%0A @@ -1003,24 +1003,43 @@ on(state) %7B%0A + if (state) %7B%0A this.$(' @@ -1055,36 +1055,152 @@ ggle -Class('menu-expand', state); +Modal(function(state) %7B%0A $(this).toggleClass('menu-expand', state);%0A %7D);%0A %7D else %7B%0A this.$('.bar').toggleModalClose();%0A %7D %0A %7D
acde460e830de9485dbc4e8cc01db1b1ecc78329
Remove pre-fetching pagination
app/assets/javascripts/components/pagination.es6.js
app/assets/javascripts/components/pagination.es6.js
// Require React React = require('react/addons'); // import material UI import mui from 'material-ui'; // Dependent component let RaisedButton = mui.RaisedButton; let ThemeManager = mui.Styles.ThemeManager; let LightRawTheme = mui.Styles.LightRawTheme; let Colors = mui.Styles.Colors // Define component const Pagination = React.createClass({ childContextTypes: { muiTheme: React.PropTypes.object }, getInitialState () { return { muiTheme: ThemeManager.getMuiTheme(LightRawTheme) }; }, getChildContext() { return { muiTheme: this.state.muiTheme, }; }, componentWillMount() { let newMuiTheme = ThemeManager.modifyRawThemePalette(this.state.muiTheme, { accent1Color: Colors.deepOrange500 }); this.setState({muiTheme: newMuiTheme}); }, render() { return ( <div className="container"> <div className="pull-right"> {this.props.links.map(link => ( <RaisedButton key={link.id} label={link.label} style={{marginTop: '20px', marginRight: '10px'}} primary={true} onClick={this._loadPage.bind(this, link.url)} /> ))} </div> </div> ); }, _loadPage(link) { this.props.fetchNextPage('/members/search?' + decodeURIComponent(link), {}) } }); module.exports = Pagination;
JavaScript
0.000024
@@ -1183,24 +1183,112 @@ age(link) %7B%0A + $.get('/members' + '?' + decodeURIComponent(link), function(data) %7B%0A %7D, %22html%22);%0A this.pro
45104aa604b5b1d6970933d0d7b2f9621c6194b3
fix images path after zip task
gulpfile.babel.js
gulpfile.babel.js
import gulp from 'gulp'; import plugins from 'gulp-load-plugins'; import browser from 'browser-sync'; import rimraf from 'rimraf'; import panini from 'panini'; import yargs from 'yargs'; import lazypipe from 'lazypipe'; import inky from 'inky'; import fs from 'fs'; import siphon from 'siphon-media-query'; import path from 'path'; import merge from 'merge-stream'; import beep from 'beepbeep'; import colors from 'colors'; const $ = plugins(); // Look for the --production flag const PRODUCTION = !!(yargs.argv.production); const EMAIL = yargs.argv.to; // Declar var so that both AWS and Litmus task can use it. var CONFIG; // Build the "dist" folder by running all of the above tasks gulp.task('build', gulp.series(clean, pages, sass, images, inline)); // Build emails, run the server, and watch for file changes gulp.task('default', gulp.series('build', server, watch)); // Build emails, then send to litmus gulp.task('litmus', gulp.series('build', creds, aws, litmus)); // Build emails, then send to EMAIL gulp.task('mail', gulp.series('build', creds, aws, mail)); // Build emails, then zip gulp.task('zip', gulp.series('build', zip)); // Delete the "dist" folder // This happens every time a build starts function clean(done) { rimraf('dist', done); } // Compile layouts, pages, and partials into flat HTML files // Then parse using Inky templates function pages() { return gulp.src('src/pages/**/*.html') .pipe(panini({ root: 'src/pages', layouts: 'src/layouts', partials: 'src/partials', helpers: 'src/helpers' })) .pipe(inky()) .pipe(gulp.dest('dist')); } // Reset Panini's cache of layouts and partials function resetPages(done) { panini.refresh(); done(); } // Compile Sass into CSS function sass() { return gulp.src('src/assets/scss/app.scss') .pipe($.if(!PRODUCTION, $.sourcemaps.init())) .pipe($.sass({ includePaths: ['node_modules/foundation-emails/scss'] }).on('error', $.sass.logError)) .pipe($.if(PRODUCTION, $.uncss( { html: ['dist/**/*.html'] }))) .pipe($.if(!PRODUCTION, $.sourcemaps.write())) .pipe(gulp.dest('dist/css')); } // Copy and compress images function images() { return gulp.src('src/assets/img/**/*') .pipe($.imagemin()) .pipe(gulp.dest('./dist/assets/img')); } // Inline CSS and minify HTML function inline() { return gulp.src('dist/**/*.html') .pipe($.if(PRODUCTION, inliner('dist/css/app.css'))) .pipe(gulp.dest('dist')); } // Start a server with LiveReload to preview the site in function server(done) { browser.init({ server: 'dist' }); done(); } // Watch for file changes function watch() { gulp.watch('src/pages/**/*.html').on('all', gulp.series(pages, inline, browser.reload)); gulp.watch(['src/layouts/**/*', 'src/partials/**/*']).on('all', gulp.series(resetPages, pages, inline, browser.reload)); gulp.watch(['../scss/**/*.scss', 'src/assets/scss/**/*.scss']).on('all', gulp.series(resetPages, sass, pages, inline, browser.reload)); gulp.watch('src/assets/img/**/*').on('all', gulp.series(images, browser.reload)); } // Inlines CSS into HTML, adds media query CSS into the <style> tag of the email, and compresses the HTML function inliner(css) { var css = fs.readFileSync(css).toString(); var mqCss = siphon(css); var pipe = lazypipe() .pipe($.inlineCss, { applyStyleTags: false, removeStyleTags: true, preserveMediaQueries: true, removeLinkTags: false }) .pipe($.replace, '<!-- <style> -->', `<style>${mqCss}</style>`) .pipe($.replace, '<link rel="stylesheet" type="text/css" href="css/app.css">', '') .pipe($.htmlmin, { collapseWhitespace: true, minifyCSS: true }); return pipe(); } // Ensure creds for Litmus are at least there. function creds(done) { var configPath = './config.json'; try { CONFIG = JSON.parse(fs.readFileSync(configPath)); } catch(e) { beep(); console.log('[AWS]'.bold.red + ' Sorry, there was an issue locating your config.json. Please see README.md'); process.exit(); } done(); } // Post images to AWS S3 so they are accessible to Litmus and manual test function aws() { var publisher = !!CONFIG.aws ? $.awspublish.create(CONFIG.aws) : $.awspublish.create(); var headers = { 'Cache-Control': 'max-age=315360000, no-transform, public' }; return gulp.src('./dist/assets/img/*') // publisher will add Content-Length, Content-Type and headers specified above // If not specified it will set x-amz-acl to public-read by default .pipe(publisher.publish(headers)) // create a cache file to speed up consecutive uploads //.pipe(publisher.cache()) // print upload updates to console .pipe($.awspublish.reporter()); } // Send email to Litmus for testing. If no AWS creds then do not replace img urls. function litmus() { var awsURL = !!CONFIG && !!CONFIG.aws && !!CONFIG.aws.url ? CONFIG.aws.url : false; return gulp.src('dist/**/*.html') .pipe($.if(!!awsURL, $.replace(/=('|")(\/?assets\/img)/g, "=$1"+ awsURL))) .pipe($.litmus(CONFIG.litmus)) .pipe(gulp.dest('dist')); } // Send email to specified email for testing. If no AWS creds then do not replace img urls. function mail() { var awsURL = !!CONFIG && !!CONFIG.aws && !!CONFIG.aws.url ? CONFIG.aws.url : false; if (EMAIL) { CONFIG.mail.to = [EMAIL]; } return gulp.src('dist/**/*.html') .pipe($.if(!!awsURL, $.replace(/=('|")(\/?assets\/img)/g, "=$1"+ awsURL))) .pipe($.mail(CONFIG.mail)) .pipe(gulp.dest('dist')); } // Copy and compress into Zip function zip() { var dist = 'dist'; var ext = '.html'; function getHtmlFiles(dir) { return fs.readdirSync(dir) .filter(function(file) { var fileExt = path.join(dir, file); var isHtml = path.extname(fileExt) == ext; return fs.statSync(fileExt).isFile() && isHtml; }); } var htmlFiles = getHtmlFiles(dist); var moveTasks = htmlFiles.map(function(file){ var sourcePath = path.join(dist, file); var fileName = path.basename(sourcePath, ext); var moveHTML = gulp.src(sourcePath) .pipe($.rename(function (path) { path.dirname = fileName; return path; })); var moveImages = gulp.src(sourcePath) .pipe($.htmlSrc({ selector: 'img'})) .pipe($.rename(function (path) { path.dirname = fileName + '/' + path.dirname; return path; })); return merge(moveHTML, moveImages) .pipe($.zip(fileName+ '.zip')) .pipe(gulp.dest('dist')); }); return merge(moveTasks); }
JavaScript
0.000005
@@ -6446,14 +6446,8 @@ me + - '/' + pat @@ -6455,16 +6455,36 @@ .dirname +.replace('dist', '') ;%0A
3a76f4361e4137606bcb3732fd3ad8ac17432eb9
remove console log
lib/media-source.js
lib/media-source.js
var EventEmitter = require('events').EventEmitter var createAudio = require('simple-media-element').audio var assign = require('object-assign') var resume = require('./resume-context') var createAudioContext = require('./audio-context') var canPlaySrc = require('./can-play-src') var addOnce = require('./event-add-once') module.exports = createMediaSource function createMediaSource (src, opt) { opt = assign({}, opt) var emitter = new EventEmitter() // Default to Audio instead of HTMLAudioElement // There is not much difference except in the following: // x instanceof Audio // x instanceof HTMLAudioElement // And in my experience Audio has better support on various // platforms like CocoonJS. // Please open an issue if there is a concern with this. if (!opt.element) opt.element = new window.Audio() var desiredVolume = opt.volume delete opt.volume // make sure <audio> tag receives full volume var audio = createAudio(src, opt) var audioContext = opt.context || createAudioContext() var node = audioContext.createGain() var mediaNode = audioContext.createMediaElementSource(audio) mediaNode.connect(node) audio.addEventListener('ended', function () { emitter.emit('end') }) audio.addEventListener('play', function () { console.log("PLAY") }) var loopStart = opt.loopStart var loopEnd = opt.loopEnd var hasLoopStart = typeof loopStart === 'number' && isFinite(loopStart) var hasLoopEnd = typeof loopEnd === 'number' && isFinite(loopEnd) var isLoopReady = false if (hasLoopStart || hasLoopEnd) { window.requestAnimationFrame(function update () { // audio hasn't been loaded yet... if (typeof audio.duration !== 'number') return var currentTime = audio.currentTime // where to end the buffer var endTime = hasLoopEnd ? Math.min(audio.duration, loopEnd) : audio.duration if (currentTime > (loopStart || 0)) { isLoopReady = true } // jump ahead to loop start point if (hasLoopStart && isLoopReady && currentTime < loopStart) { audio.currentTime = loopStart } // if we've hit the end of the buffer if (currentTime >= endTime) { // if there is no loop end point, let native looping take over // if we have a loop end point, jump back to start point or zero if (hasLoopEnd) { audio.currentTime = hasLoopStart ? loopStart : 0 } } window.requestAnimationFrame(update) }); } emitter.element = audio emitter.context = audioContext emitter.node = node emitter.pause = audio.pause.bind(audio) emitter.play = function () { if (opt.autoResume !== false) resume(emitter.context) return audio.play() } // This exists currently for parity with Buffer source // Open to suggestions for what this should dispose... emitter.dispose = function () {} emitter.stop = function () { var wasPlaying = emitter.playing audio.pause() audio.currentTime = 0 isLoopReady = false if (wasPlaying) { emitter.emit('end') } } Object.defineProperties(emitter, { duration: { enumerable: true, configurable: true, get: function () { return audio.duration } }, currentTime: { enumerable: true, configurable: true, get: function () { return audio.currentTime } }, playing: { enumerable: true, configurable: true, get: function () { return !audio.paused } }, volume: { enumerable: true, configurable: true, get: function () { return node.gain.value }, set: function (n) { node.gain.value = n } } }) // Set initial volume if (typeof desiredVolume === 'number') { emitter.volume = desiredVolume } // Check if all sources are unplayable, // if so we emit an error since the browser // might not. var sources = Array.isArray(src) ? src : [ src ] sources = sources.filter(Boolean) var playable = sources.some(canPlaySrc) if (playable) { // At least one source is probably/maybe playable startLoad() } else { // emit error on next tick so user can catch it process.nextTick(function () { emitter.emit('error', canPlaySrc.createError(sources)) }) } return emitter function startLoad () { // The file errors (like decoding / 404s) appear on <source> var srcElements = Array.prototype.slice.call(audio.children) var remainingSrcErrors = srcElements.length var hasErrored = false var sourceError = function (err, el) { if (hasErrored) return remainingSrcErrors-- console.warn('Error loading source: ' + el.getAttribute('src')) if (remainingSrcErrors <= 0) { hasErrored = true srcElements.forEach(function (el) { el.removeEventListener('error', sourceError, false) }) emitter.emit('error', new Error('Could not play any of the supplied sources')) } } var done = function () { emitter.emit('load') } if (audio.readyState >= audio.HAVE_ENOUGH_DATA) { process.nextTick(done) } else { addOnce(audio, 'canplay', done) addOnce(audio, 'error', function (ev) { emitter.emit(new Error('Unknown error while loading <audio>')) }) srcElements.forEach(function (el) { addOnce(el, 'error', sourceError) }) } // On most browsers the loading begins // immediately. However, on iOS 9.2 Safari, // you need to call load() for events // to be triggered. audio.load() } }
JavaScript
0.000003
@@ -1232,84 +1232,8 @@ %7D) -%0A audio.addEventListener('play', function () %7B%0A console.log(%22PLAY%22)%0A %7D) %0A%0A
8d80b36ebb18596be35ddc345817d089260c205c
fix missing file copy task on watch
gulpfile.babel.js
gulpfile.babel.js
'use strict' // Load global config and gulp import config from './foley.json' import gulp from 'gulp' // Load modules to run tasks from files import requireDir from 'require-dir' import runSequence from 'run-sequence' const tasks = requireDir(__dirname + '/tasks') // eslint-disable-line // Watch task gulp.task('watch', () => { gulp.watch(config.paths.scss + '**/*.scss', ['scss']) gulp.watch(config.paths.js + '**/*.js', ['webpack']) gulp.watch(config.paths.img + '{,**/}*.{png,jpg,gif,svg}', ['img']) gulp.watch(config.paths.icons + '**/*.svg', ['svgsprite']) gulp.watch(config.paths.fonts + '**/*', ['copy']) gulp.watch([ config.paths.layouts + '**/*.hbs', config.paths.pages + '**/*.hbs', config.paths.partials + '**/*.hbs' ], ['metalsmith']) }) // Build website, either with development or minified assets and run server with live reloading gulp.task('default', callback => { runSequence( 'clean', 'metalsmith', ['htmlmin', 'svgsprite', 'scss', 'webpack', 'img', 'copy'], ['browsersync', 'watch'], callback ) }) // Build website, either with development or minified assets depending on flag gulp.task('deploy', callback => { runSequence( 'clean', 'metalsmith', ['htmlmin', 'svgsprite', 'scss', 'webpack', 'img', 'copy'], 'crticalcss', callback ) }) // Run the audit task to check the code gulp.task('auditcode', callback => { runSequence( 'scsslint', 'jslint', callback ) }) // Run the audit task to check the built website for accessibility // NOTE: Not used yet /* gulp.task('auditsite', callback => { runSequence( 'deploy', callback ) }) */ // Run the audit task to check performance using ... // NOTE: Not used yet /* gulp.task('auditperf', callback => { runSequence( 'deploy', callback ) }) */
JavaScript
0.000019
@@ -572,32 +572,33 @@ %5D)%0A gulp.watch( +%5B config.paths.fon @@ -609,16 +609,46 @@ '**/*', + config.paths.files + '**/*'%5D, %5B'copy' @@ -664,21 +664,16 @@ .watch(%5B -%0A config.p @@ -690,36 +690,32 @@ ts + '**/*.hbs', -%0A config.paths.pa @@ -731,20 +731,16 @@ /*.hbs', -%0A config. @@ -766,19 +766,16 @@ */*.hbs' -%0A %5D, %5B'met
09c0fef7426900ba8ad1b474268e5036d5ae4ed8
Update controller1.js
controllers/controller1.js
controllers/controller1.js
/* load forcast of current location on load. Then upon submit/enter return forecast for searched city. Use Autocomplete API for search results. This will return a Json. list the city names from the Json, and attach the link associated with each city so it will load the forecast from that city. Populate new forecast into cards. */ "use strict"; angular.module('myapp') .controller("WeatherController", function($scope, $http){ $scope.objects = {}; $scope.forecast = []; if (navigator.geolocation) navigator.geolocation.getCurrentPosition(onPositionUpdate); function onPositionUpdate(position) { var lati = position.coords.latitude; var longi = position.coords.longitude; var url = 'https://api.wunderground.com/api/4a82154c39d11213/forecast/q/' + lati + ',' + longi + '.json'; $http.get(url) .then(function(info) { // console.log(info); for(var i ; i < 9; i++){ objects[i] = { title: info.data.forecast.txt_forecast.forecastday.i.title, icon: info.data.forecast.txt_forecast.forecastday.i.icon_url, conditionsI: info.data.forecast.txt_forecast.forecastday.i.fcttext, conditionsM: info.data.forecast.txt_forecast.forecastday.i.fcttext_metric, }; $scope.forecast.push(objects[i]); } console.log($scope.forecast); }); }; });
JavaScript
0.000001
@@ -969,16 +969,23 @@ +$scope. objects%5B @@ -1360,16 +1360,23 @@ st.push( +$scope. objects%5B
51b57e062da5ac28e30148413da076911cbbf10c
Add onended callback for streams
lib/mediaSession.js
lib/mediaSession.js
var _ = require('underscore'); var util = require('util'); var bows = require('bows'); var JingleSession = require('./genericSession'); var RTCPeerConnection = require('rtcpeerconnection'); var log = bows('JingleMedia'); function MediaSession(opts) { JingleSession.call(this, opts); var self = this; var config = this.parent.config.peerConnectionConfig; var constraints = this.parent.config.peerConnectionConstraints; config.useJingle = true; this.pc = new RTCPeerConnection(config, constraints); this.pc.on('ice', this.onIceCandidate.bind(this)); this.pc.on('addStream', this.onStreamAdded.bind(this)); this.pc.on('removeStream', this.onStreamRemoved.bind(this)); if (this.parent.localStream) { this.pc.addStream(this.parent.localStream); this.localStream = this.parent.localStream; } else { this.parent.once('localStream', function (stream) { self.pc.addStream(stream); this.localStream = stream; }); } } util.inherits(MediaSession, JingleSession); Object.defineProperty(MediaSession.prototype, 'streams', { get: function () { return this.pc.remoteStreams; } }); MediaSession.prototype = _.extend(MediaSession.prototype, { start: function () { var self = this; this.state = 'pending'; this.pc.isInitiator = true; this.pc.offer(function (err, sessDesc) { self.send('session-initiate', sessDesc.jingle); }); }, end: function (reason) { var self = this; this.pc.close(); _.each(this.streams, function (stream) { self.onStreamRemoved({stream: stream}); }); JingleSession.prototype.end.call(this, reason); }, accept: function () { var self = this; log(this.sid + ': Accepted incoming session'); this.state = 'active'; this.pc.answer(function (err, answer) { if (err) { return log(self.sid + ': Could not create WebRTC answer', err); } self.send('session-accept', answer.jingle); }); }, ring: function () { log(this.sid + ': Ringing on incoming session'); this.send('session-info', {ringing: true}); }, mute: function (creator, name) { log(this.sid + ': Muting'); this.send('session-info', {mute: {creator: creator, name: name}}); }, unmute: function (creator, name) { log(this.sid + ': Unmuting'); this.send('session-info', {unmute: {creator: creator, name: name}}); }, hold: function () { log(this.sid + ': Placing on hold'); this.send('session-info', {hold: true}); }, resume: function () { log(this.sid + ': Resuing from hold'); this.send('session-info', {active: true}); }, onSessionInitiate: function (changes, cb) { var self = this; log(self.sid + ': Initiating incoming session'); this.state = 'pending'; this.pc.isInitiator = false; this.pc.handleOffer({type: 'offer', jingle: changes}, function (err) { if (err) { log(self.sid + ': Could not create WebRTC answer', err); return cb({condition: 'general-error'}); } cb(); }); }, onSessionAccept: function (changes, cb) { var self = this; log(this.sid + ': Activating accepted outbound session'); this.state = 'active'; this.pc.handleAnswer({type: 'answer', jingle: changes}, function (err) { if (err) { log(self.sid + ': Could not process WebRTC answer', err); return cb({condition: 'general-error'}); } self.parent.emit('accepted', self); cb(); }); }, onSessionTerminate: function (changes, cb) { var self = this; log(this.sid + ': Terminating session'); this.pc.close(); _.each(this.streams, function (stream) { self.onStreamRemoved({stream: stream}); }); JingleSession.prototype.end.call(this, changes.reason, true); cb(); }, onTransportInfo: function (changes, cb) { var self = this; log(this.sid + ': Adding ICE candidate'); this.pc.processIce(changes, function (err) { if (err) { log(self.sid + ': Could not process ICE candidate', err); } cb(); }); }, onSessionInfo: function (info, cb) { log(info); if (info.ringing) { log(this.sid + ': Ringing on remote stream'); this.parent.emit('ringing', this); } if (info.hold) { log(this.sid + ': On hold'); this.parent.emit('hold', this); } if (info.active) { log(this.sid + ': Resumed from hold'); this.parent.emit('resumed', this); } if (info.mute) { log(this.sid + ': Muted', info.mute); this.parent.emit('mute', this, info.mute); } if (info.unmute) { log(this.sid + ': Unmuted', info.unmute); this.parent.emit('unmute', this, info.unmute); } cb(); }, onIceCandidate: function (candidateInfo) { log(this.sid + ': Discovered new ICE candidate', candidateInfo.jingle); this.send('transport-info', candidateInfo.jingle); }, onStreamAdded: function (event) { log(this.sid + ': Remote media stream added'); this.parent.emit('peerStreamAdded', this, event.stream); }, onStreamRemoved: function (event) { log(this.sid + ': Remote media stream removed'); this.parent.emit('peerStreamRemoved', this, event.stream); } }); module.exports = MediaSession;
JavaScript
0
@@ -5505,32 +5505,57 @@ ction (event) %7B%0A + var self = this;%0A log(this @@ -5589,24 +5589,140 @@ am added');%0A +%0A event.stream.onended = function () %7B%0A self.onStreamRemoved(%7Bstream: event.stream%7D);%0A %7D;%0A%0A this
c6596d85946ec0b858a65f08eab4d3715663b3f6
Disable test-headless task
gulpfile.babel.js
gulpfile.babel.js
var gulp = require('gulp'), _ = require('lodash'), path = require('path'), lintSpecific = require('./util/gulp/lint-specific'), config = require('config'); var settings = { clientSource: path.resolve(config.get('clientSource')), ddocSource: path.resolve(config.get('ddocSource')), ddocOutput: config.get('outputDDoc'), destination: config.get('destination'), codeOutputPath: path.join(config.get('outputDDoc'), '_attachments', 'code'), styleOutputPath: path.join(config.get('outputDDoc'), '_attachments', 'style'), isDebug: config.has('debug') ? config.get('debug') : false, libraryModules: config.get("libraryModules"), extraPaths: config.get("extraPaths"), externalUIJSDev: config.get("externalUIJSDev"), externalUICSSDev: config.get("externalUICSSDev"), externalUICSSTest: config.get("externalUICSSTest"), testSource: path.resolve(config.get('testSource')), testOutputPath: config.get("outputTest"), dynamic: {} // To contain any cross-task variables. }; if (config.has("_docs")) { settings._docs = config.get("_docs"); } // Setup globs for watching file changes. // Encase any values in arrays that should be joined with other values. settings.globs = { 'allCode': ['app/code/**/*.js'], 'code': ['app/code/**/*.js', '!app/code/test/**/*.js'], 'ddocCode': path.join(settings.ddocSource, '**/*.js'), 'testCode': ['app/code/test/**/*.js', 'app/code/test/*.html'], 'templates': ['app/code/**/*.html', '!app/code/test/*.html'], 'ui': path.join(settings.clientSource, '/**/*.html'), 'directUI': path.join(settings.clientSource, '*.html'), 'images': path.join(settings.clientSource, 'img', '**/*'), 'ddoc': path.join(settings.ddocSource, '**/*'), 'sass': 'app/style/*.scss' }; // All code that should be seen in dev or prod. // (Get all values in globs **except** allCode, testCode, ddocCode, which are better handled by 'code'.) settings.globsAll = _.flattenDeep(_.values(_.omit(settings.globs, ['allCode', 'ddocCode', 'testCode']))); // Only code under test. settings.globsTest = _.flattenDeep([settings.globs.allCode, settings.globs.testCode]); // Import external tasks, giving them the settings object. require("./tasks/bulk-update")(gulp, settings); require("./tasks/build-docs")(gulp, settings); require("./tasks/clean-ui-framework")(gulp, settings); require("./tasks/ui-framework")(gulp, settings); require("./tasks/ui-local")(gulp, settings); require("./tasks/bundle-lib")(gulp, settings); require("./tasks/push")(gulp, settings); require("./tasks/code-dev")(gulp, settings); require("./tasks/code")(gulp, settings); require("./tasks/build-app")(gulp, settings); require("./tasks/build-ddoc")(gulp, settings); require("./tasks/lint")(gulp, settings); require("./tasks/test-in-browser.js")(gulp, settings); require("./tasks/test-headless.js")(gulp, settings); require("./tasks/bundle-test-lib.js")(gulp, settings); require("./tasks/ui-test.js")(gulp, settings); require("./tasks/build-tests.js")(gulp, settings); require("./tasks/copy-test-lib.js")(gulp, settings); require("./tasks/browser-sync-init.js")(gulp, settings); require("./tasks/browser-sync-reload.js")(gulp, settings); /** * Show settings for this task runner. **/ gulp.task('default', function() { // place code for your default task here if (_.isEmpty(process.env.NODE_ENV)) { // process.env.NODE_ENV = "personal"; console.warn("*** No environment set (NODE_ENV is empty); using default. ***"); console.info("\tUsage (BEFORE launching gulp): export NODE_ENV=somevalue"); console.info("\tUsage (PER-USE): NODE_ENV=somevalue gulp"); } else { console.info("Current environment (NODE_ENV)", process.env.NODE_ENV); } console.info("config.clientSource", settings.clientSource); console.info("config.ddocSource", settings.ddocSource); console.info("Build output (config.outputDDoc)", settings.ddocOutput); console.info("Server design doc (config.destination)", settings.destination); console.info(); console.info("Typical dev command: `gulp push dev-watch docs-watch test-watch`"); console.info(" (This pushes the current code to CouchDB, then watches for changes.)"); }); /** * Watch for changes, trigger ``push`` task. **/ gulp.task('push:watch', function() { gulp.watch(settings.globsAll, function(event) { console.log(path.relative(process.cwd(), event.path)+' ==> '+event.type+', running tasks.'); gulp.start('push'); }); }); // Watch files, run dev tasks. gulp.task('dev-watch', function() { settings.isDebug = true; // When any source code changes, combine/run browserify/push to server. var watcher = gulp.watch(settings.globsAll, {debounceDelay: 100}, ['push']); watcher.on('change', function(event) { console.log(path.relative(process.cwd(), event.path)+' ==> '+event.type+', running tasks.'); }); }); // Watch files, run analyze tasks. gulp.task('analyze-watch', function() { // When any source code changes, analyze with jshint. var watcher = gulp.watch([settings.globs.code, settings.globs.ddocCode]); watcher.on('change', function(event) { lintSpecific(event.path); }); }); // Watch files, run docs tasks. gulp.task('docs-watch', function() { if (_.has(settings, "_docs")) { // When any doc changes, push to server. var watcher = gulp.watch(_.values(settings._docs), {debounceDelay: 100}, ['bulk-update']); watcher.on('change', function(event) { console.log(path.relative(process.cwd(), event.path)+' ==> '+event.type+', pushing docs.'); }); } }); // Watch files, run production tasks. gulp.task('prod-watch', function() { settings.isDebug = false; // When any source code changes, combine/run browserify/push to server. var watcher = gulp.watch(settings.globsAll, ['push']); watcher.on('change', function(event) { console.log(path.relative(process.cwd(), event.path)+' ==> '+event.type+', running tasks.'); }); }); // Watch files, run test tasks. gulp.task('test-watch', ['browser-sync-init'], function() { // When any test or source code changes, combine/run browserify/run tests. var watcher = gulp.watch(settings.globsTest, {debounceDelay: 100}, ['browser-sync-reload', 'test-headless']); watcher.on('change', function(event) { console.log(path.relative(process.cwd(), event.path)+' ==> '+event.type+', running tasks.'); }); });
JavaScript
0
@@ -2821,32 +2821,34 @@ ulp, settings);%0A +// require(%22./tasks @@ -2875,32 +2875,90 @@ gulp, settings); + // Disabled until node LTS supports async/await AND gulp. %0Arequire(%22./task @@ -6399,16 +6399,18 @@ -reload' +/* , 'test- @@ -6418,16 +6418,18 @@ eadless' +*/ %5D);%0A%0A
7ded6bd0aed4852b4a80583cc2fd425403f8f1ed
Remove comma dangle
gulpfile.babel.js
gulpfile.babel.js
import gulp from 'gulp'; import thrift from 'gulp-thrift'; import babel from 'gulp-babel'; const basePaths = { src: 'src/', dest: 'lib/', }; const paths = { js: { src: `${basePaths.src}*.js`, dest: basePaths.dest, }, thrift: { src: `${basePaths.src}thrift/*.thrift`, dest: `${basePaths.dest}thrift/`, }, }; /** * Runs watch task as default. */ gulp.task('default', ['watch']); gulp.task('watch', ['compile:js'], () => { gulp.watch(paths.js.src, ['compile:js']); }); /** * Generates thrift files. This task requires to have thrift * installed in the system. */ gulp.task('thrift', () => { gulp.src(paths.thrift.src) .pipe(thrift({ gen: 'js:node', })) .pipe(gulp.dest(paths.thrift.dest)); }); /** * Compiles ES6 code to ES5. */ gulp.task('compile:js', () => { gulp.src(paths.js.src) .pipe(babel({ presets: ['es2015'], })) .on('error', console.error.bind(console)) .pipe(gulp.dest(paths.js.dest)); });
JavaScript
0.998703
@@ -134,18 +134,17 @@ : 'lib/' -, %0A + %7D;%0A%0Acons @@ -220,17 +220,16 @@ ths.dest -, %0A %7D,%0A @@ -322,14 +322,12 @@ ft/%60 -, %0A %7D -, %0A%7D;%0A @@ -685,17 +685,16 @@ js:node' -, %0A %7D)) @@ -852,16 +852,16 @@ babel(%7B%0A + pr @@ -877,17 +877,16 @@ es2015'%5D -, %0A %7D))
10c223378729014a25cc48559aed507b968709d8
Remove the render throttle logic
lib/node-progress.js
lib/node-progress.js
/*! * node-progress * Copyright(c) 2011 TJ Holowaychuk <[email protected]> * MIT Licensed */ /** * Expose `ProgressBar`. */ exports = module.exports = ProgressBar; /** * Initialize a `ProgressBar` with the given `fmt` string and `options` or * `total`. * * Options: * * - `curr` current completed index * - `total` total number of ticks to complete * - `width` the displayed width of the progress bar defaulting to total * - `stream` the output stream defaulting to stderr * - `head` head character defaulting to complete character * - `complete` completion character defaulting to "=" * - `incomplete` incomplete character defaulting to "-" * - `renderThrottle` minimum time between updates in milliseconds defaulting to 16 * - `callback` optional function to call when the progress bar completes * - `clear` will clear the progress bar upon termination * * Tokens: * * - `:bar` the progress bar itself * - `:current` current tick number * - `:total` total ticks * - `:elapsed` time elapsed in seconds * - `:percent` completion percentage * - `:eta` eta in seconds * - `:rate` rate of ticks per second * * @param {string} fmt * @param {object|number} options or total * @api public */ function ProgressBar(fmt, options) { this.stream = options.stream || process.stderr; if (typeof(options) == 'number') { var total = options; options = {}; options.total = total; } else { options = options || {}; if ('string' != typeof fmt) throw new Error('format required'); if ('number' != typeof options.total) throw new Error('total required'); } this.fmt = fmt; this.curr = options.curr || 0; this.total = options.total; this.width = options.width || this.total; this.clear = options.clear this.chars = { complete : options.complete || '=', incomplete : options.incomplete || '-', head : options.head || (options.complete || '=') }; this.renderThrottle = options.renderThrottle !== 0 ? (options.renderThrottle || 16) : 0; this.callback = options.callback || function () {}; this.tokens = {}; this.lastDraw = ''; } /** * "tick" the progress bar with optional `len` and optional `tokens`. * * @param {number|object} len or tokens * @param {object} tokens * @api public */ ProgressBar.prototype.tick = function(len, tokens){ if (len !== 0) len = len || 1; // swap tokens if ('object' == typeof len) tokens = len, len = 1; if (tokens) this.tokens = tokens; // start time for eta if (0 == this.curr) this.start = new Date; this.curr += len // schedule render this.render(); // progress complete if (this.curr >= this.total) { this.render(); this.complete = true; this.terminate(); this.callback(this); return; } }; /** * Method to render the progress bar with optional `tokens` to place in the * progress bar's `fmt` field. * * @param {object} tokens * @api public */ ProgressBar.prototype.render = function (tokens) { clearTimeout(this.renderThrottleTimeout); this.renderThrottleTimeout = null; if (tokens) this.tokens = tokens; if (!this.stream.isTTY) return; var ratio = this.curr / this.total; ratio = Math.min(Math.max(ratio, 0), 1); var percent = Math.floor(ratio * 100); var incomplete, complete, completeLength; var elapsed = new Date - this.start; var eta = (percent == 100) ? 0 : elapsed * (this.total / this.curr - 1); var rate = this.curr / (elapsed / 1000); /* populate the bar template with percentages and timestamps */ var str = this.fmt .replace(':current', this.curr) .replace(':total', this.total) .replace(':elapsed', isNaN(elapsed) ? '0.0' : (elapsed / 1000).toFixed(1)) .replace(':eta', (isNaN(eta) || !isFinite(eta)) ? '0.0' : (eta / 1000) .toFixed(1)) .replace(':percent', percent.toFixed(0) + '%') .replace(':rate', Math.round(rate)); /* compute the available space (non-zero) for the bar */ var availableSpace = Math.max(0, this.stream.columns - str.replace(':bar', '').length); if(availableSpace && process.platform === 'win32'){ availableSpace = availableSpace - 1; } var width = Math.min(this.width, availableSpace); /* TODO: the following assumes the user has one ':bar' token */ completeLength = Math.round(width * ratio); complete = Array(Math.max(0, completeLength + 1)).join(this.chars.complete); incomplete = Array(Math.max(0, width - completeLength + 1)).join(this.chars.incomplete); /* add head to the complete string */ if(completeLength > 0) complete = complete.slice(0, -1) + this.chars.head; /* fill in the actual progress bar */ str = str.replace(':bar', complete + incomplete); /* replace the extra tokens */ if (this.tokens) for (var key in this.tokens) str = str.replace(':' + key, this.tokens[key]); if (this.lastDraw !== str) { this.stream.cursorTo(0); this.stream.write(str); this.stream.clearLine(1); this.lastDraw = str; } }; /** * "update" the progress bar to represent an exact percentage. * The ratio (between 0 and 1) specified will be multiplied by `total` and * floored, representing the closest available "tick." For example, if a * progress bar has a length of 3 and `update(0.5)` is called, the progress * will be set to 1. * * A ratio of 0.5 will attempt to set the progress to halfway. * * @param {number} ratio The ratio (between 0 and 1 inclusive) to set the * overall completion to. * @api public */ ProgressBar.prototype.update = function (ratio, tokens) { var goal = Math.floor(ratio * this.total); var delta = goal - this.curr; this.tick(delta, tokens); }; /** * "interrupt" the progress bar and write a message above it. * @param {string} message The message to write. * @api public */ ProgressBar.prototype.interrupt = function (message) { // clear the current line this.stream.clearLine(); // move the cursor to the start of the line this.stream.cursorTo(0); // write the message text this.stream.write(message); // terminate the line after writing the message this.stream.write('\n'); // re-display the progress bar with its lastDraw this.stream.write(this.lastDraw); }; /** * Terminates a progress bar. * * @api public */ ProgressBar.prototype.terminate = function () { if (this.clear) { if (this.stream.clearLine) { this.stream.clearLine(); this.stream.cursorTo(0); } } else { this.stream.write('\n'); } };
JavaScript
0
@@ -3022,90 +3022,8 @@ ) %7B%0A - clearTimeout(this.renderThrottleTimeout);%0A this.renderThrottleTimeout = null;%0A%0A if
85a1849d10980bd5738b231a2bcefb4e4a63f47d
Update token.js
lib/models/token.js
lib/models/token.js
'use strict'; /** * @file Model for Token * * Every connected user from AnyFetch has one, mapping its AnyFetch token to a set of Dropbox tokens. */ var mongoose = require('mongoose'); var TokenSchema = new mongoose.Schema({ // Access token to communicate with AnyFetch anyfetchToken: {type: String, default: '', unique: true}, // Account identifier accountName: '', // Data needed by the provider data: {}, // Last cursor (may be a date, a string or anything) cursor: {}, // Are we currently updating isUpdating: {type: Boolean, default: false}, // Date we started last update lastUpdate: {type: Date, default: null}, // Is this token is stale and requiring a refresh? requireRefresh: {type: Boolean, default: false} }); // Register & export the model module.exports = mongoose.model('Token', TokenSchema);
JavaScript
0.000001
@@ -665,19 +665,16 @@ s token -is stale an
86c5dac9f251613fc02c87843010223e24cb65ba
Add eslint validation for data modules
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/webpack.config.js
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/webpack.config.js
/** * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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. * */ /* eslint-disable */ var path = require('path'); const config = { entry: { index: './source/index.jsx', }, output: { path: path.resolve(__dirname, 'public/dist'), filename: '[name].bundle.js', chunkFilename: '[name].bundle.js', publicPath: 'public/app/dist/', }, watch: false, devtool: 'source-map', resolve: { extensions: ['.js', '.jsx'], }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: [ { loader: 'babel-loader', }, ], }, { test: /\.css$/, use: ['style-loader', 'css-loader'], }, { test: /\.less$/, use: [ { loader: 'style-loader', // creates style nodes from JS strings }, { loader: 'css-loader', // translates CSS into CommonJS }, { loader: 'less-loader', // compiles Less to CSS }, ], }, { test: /\.(woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000', }, ], }, externals: { Config: 'Configurations', }, plugins: [], }; if (process.env.NODE_ENV === 'development') { config.watch = true; } else if (process.env.NODE_ENV === 'production') { /* ESLint will only un in production build to increase the continues build(watch) time in the development mode */ const esLintLoader = { enforce: 'pre', test: /\.(js|jsx)$/, /* exclude: /node_modules/, */ include: [ /.*\/Apis\/Details\/NavBar.jsx/, /.*\/components\/Endpoints\/*/, /.*\/Apis\/Details\/index.jsx/, /.*\/Apis\/Create\/*/, /.*\/Base\/*/, ], loader: 'eslint-loader', options: { failOnError: true, quiet: true, }, }; config.module.rules.push(esLintLoader); } module.exports = function(env) { if (env && env.analysis) { var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; config.plugins.push(new BundleAnalyzerPlugin()); } return config; }; /* eslint-enable */
JavaScript
0
@@ -2846,32 +2846,375 @@ /.*%5C/Base%5C/*/,%0D%0A + /.*%5C/data%5C/APIClient.js/,%0D%0A /.*%5C/data%5C/AuthManager.js/,%0D%0A /.*%5C/data%5C/APIClientFactory.js/,%0D%0A /.*%5C/data%5C/ApiPermissionValidation.js/,%0D%0A /.*%5C/data%5C/AuthManager.js/,%0D%0A /.*%5C/data%5C/ConfigManager.js/,%0D%0A /.*%5C/data%5C/ScopeValidation.jsx/,%0D%0A /.*%5C/data%5C/User.js/,%0D%0A %5D,%0D%0A
1df0a84615d5c1d72fdebee41f89e98ce3158668
Add source mapping to production build
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/webpack.config.js
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/webpack.config.js
var path = require('path'); const config = { entry: { index: './source/index.js' }, output: { path: path.resolve(__dirname, 'public/dist'), filename: "[name].bundle.js", chunkFilename: "[name].bundle.js", publicPath: 'public/app/dist/' }, watch: false, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: [ { loader: 'babel-loader', } ] }, { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.less$/, use: [{ loader: "style-loader" // creates style nodes from JS strings }, { loader: "css-loader" // translates CSS into CommonJS }, { loader: "less-loader" // compiles Less to CSS }] }, { test: /\.(woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' } ] }, externals: { Config: "Configurations" }, plugins: [] }; if (process.env.NODE_ENV === "development") { config.watch = true; config.devtool = "source-map"; } if (process.env.NODE_ENV === 'production') { } module.exports = function (env) { if (env && env.analysis) { var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; config.plugins.push(new BundleAnalyzerPlugin()) } return config; }
JavaScript
0
@@ -320,16 +320,44 @@ false,%0D%0A + devtool: %22source-map%22,%0D%0A modu @@ -1441,95 +1441,8 @@ e;%0D%0A - config.devtool = %22source-map%22;%0D%0A%7D%0D%0Aif (process.env.NODE_ENV === 'production') %7B%0D%0A%0D%0A %7D%0D%0A%0D
3d5810dd38d4818b8cea227683d84541e9614618
context gaurd in is
lib/observable/is.js
lib/observable/is.js
'use strict' var Promise = require('bluebird') Promise.config({ cancellation: true }) exports.define = { is (val, callback, event) { var type = typeof val var compare var promise var parsed = this.val var _this = this if (type === 'function') { compare = val } else { compare = function (compare) { return compare == val //eslint-disable-line } } if (!callback) { let cancel = function () { promise.cancel() } promise = new Promise(function (resolve, reject, onCancel) { onCancel(function () { _this.off('data', is) _this.off('remove', cancel) }) // reject callback = function (data, event) { _this.off('remove', cancel) resolve(this, data, event) } }) // _this.on('remove', cancel) } if (compare.call(this, parsed, void 0, event)) { if (callback) { callback.call(this, parsed, event) } } else { this.on('data', is) } // use attach not a closure function is (data, event) { // context problems in clear if (compare.call(this, this.val, data, event)) { // console.log(_this.path.join('.')) _this.clearContext() _this.off('data', is) // console.log('does it godamn get removed????', _this._on.data.fn) callback.call(this, data, event) } } return promise || this } }
JavaScript
0.998004
@@ -830,44 +830,8 @@ %7D)%0A - // _this.on('remove', cancel)%0A @@ -1009,40 +1009,8 @@ %7D%0A%0A - // use attach not a closure%0A @@ -1139,220 +1139,275 @@ -// console.log(_this.path.join('.'))%0A _this.clearContext()%0A _this.off('data', is)%0A // console.log('does it godamn get removed????', _this._on.data.fn)%0A callback.call(this, data, event) +let stored%0A if (_this._context) %7B%0A stored = _this.storeContextChain()%0A %7D%0A _this.clearContext()%0A _this.off('data', is)%0A callback.call(this, data, event)%0A if (stored) %7B%0A _this.setContextChain(stored)%0A %7D %0A
d91d1c97dee5d3c75b8cb5ad91fbcd2506ef6f84
Use ast-types directly in lib/leap.js instead of recast.
lib/leap.js
lib/leap.js
/** * Copyright (c) 2013, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ var assert = require("assert"); var recast = require("recast"); var n = recast.namedTypes; var b = recast.builders; var inherits = require("util").inherits; function Entry() { assert.ok(this instanceof Entry); } function FunctionEntry(returnLoc) { Entry.call(this); n.Literal.assert(returnLoc); Object.defineProperties(this, { returnLoc: { value: returnLoc } }); } inherits(FunctionEntry, Entry); exports.FunctionEntry = FunctionEntry; function LoopEntry(breakLoc, continueLoc, label) { Entry.call(this); n.Literal.assert(breakLoc); n.Literal.assert(continueLoc); if (label) { n.Identifier.assert(label); } else { label = null; } Object.defineProperties(this, { breakLoc: { value: breakLoc }, continueLoc: { value: continueLoc }, label: { value: label } }); } inherits(LoopEntry, Entry); exports.LoopEntry = LoopEntry; function SwitchEntry(breakLoc) { Entry.call(this); n.Literal.assert(breakLoc); Object.defineProperties(this, { breakLoc: { value: breakLoc } }); } inherits(SwitchEntry, Entry); exports.SwitchEntry = SwitchEntry; function TryEntry(catchEntry, finallyEntry) { Entry.call(this); if (catchEntry) { assert.ok(catchEntry instanceof CatchEntry); } else { catchEntry = null; } if (finallyEntry) { assert.ok(finallyEntry instanceof FinallyEntry); } else { finallyEntry = null; } Object.defineProperties(this, { catchEntry: { value: catchEntry }, finallyEntry: { value: finallyEntry } }); } inherits(TryEntry, Entry); exports.TryEntry = TryEntry; function CatchEntry(firstLoc, paramId) { Entry.call(this); n.Literal.assert(firstLoc); n.Identifier.assert(paramId); Object.defineProperties(this, { firstLoc: { value: firstLoc }, paramId: { value: paramId } }); } inherits(CatchEntry, Entry); exports.CatchEntry = CatchEntry; function FinallyEntry(firstLoc, nextLocTempVar) { Entry.call(this); n.Literal.assert(firstLoc); n.MemberExpression.assert(nextLocTempVar); Object.defineProperties(this, { firstLoc: { value: firstLoc }, nextLocTempVar: { value: nextLocTempVar } }); } inherits(FinallyEntry, Entry); exports.FinallyEntry = FinallyEntry; function LeapManager(emitter) { assert.ok(this instanceof LeapManager); var Emitter = require("./emit").Emitter; assert.ok(emitter instanceof Emitter); Object.defineProperties(this, { emitter: { value: emitter }, entryStack: { value: [new FunctionEntry(emitter.finalLoc)] } }); } var LMp = LeapManager.prototype; exports.LeapManager = LeapManager; LMp.withEntry = function(entry, callback) { assert.ok(entry instanceof Entry); this.entryStack.push(entry); try { callback.call(this.emitter); } finally { var popped = this.entryStack.pop(); assert.strictEqual(popped, entry); } }; LMp._leapToEntry = function(predicate, defaultLoc) { var entry, loc; var finallyEntries = []; var skipNextTryEntry = null; for (var i = this.entryStack.length - 1; i >= 0; --i) { entry = this.entryStack[i]; if (entry instanceof CatchEntry || entry instanceof FinallyEntry) { // If we are inside of a catch or finally block, then we must // have exited the try block already, so we shouldn't consider // the next TryStatement as a handler for this throw. skipNextTryEntry = entry; } else if (entry instanceof TryEntry) { if (skipNextTryEntry) { // If an exception was thrown from inside a catch block and this // try statement has a finally block, make sure we execute that // finally block. if (skipNextTryEntry instanceof CatchEntry && entry.finallyEntry) { finallyEntries.push(entry.finallyEntry); } skipNextTryEntry = null; } else if ((loc = predicate.call(this, entry))) { break; } else if (entry.finallyEntry) { finallyEntries.push(entry.finallyEntry); } } else if ((loc = predicate.call(this, entry))) { break; } } if (loc) { // fall through } else if (defaultLoc) { loc = defaultLoc; } else { return null; } n.Literal.assert(loc); while ((finallyEntry = finallyEntries.pop())) { this.emitter.emitAssign(finallyEntry.nextLocTempVar, loc); loc = finallyEntry.firstLoc; } return loc; }; function getLeapLocation(entry, property, label) { var loc = entry[property]; if (loc) { if (label) { if (entry.label && entry.label.name === label.name) { return loc; } } else { return loc; } } return null; } LMp.emitBreak = function(label) { var loc = this._leapToEntry(function(entry) { return getLeapLocation(entry, "breakLoc", label); }); if (loc === null) { throw new Error("illegal break statement"); } this.emitter.clearPendingException(); this.emitter.jump(loc); }; LMp.emitContinue = function(label) { var loc = this._leapToEntry(function(entry) { return getLeapLocation(entry, "continueLoc", label); }); if (loc === null) { throw new Error("illegal continue statement"); } this.emitter.clearPendingException(); this.emitter.jump(loc); }; LMp.emitReturn = function(argument) { var loc = this._leapToEntry(function(entry) { return getLeapLocation(entry, "returnLoc"); }); if (loc === null) { throw new Error("illegal return statement"); } if (argument) { this.emitter.setReturnValue(argument); } this.emitter.clearPendingException(); this.emitter.jump(loc); };
JavaScript
0
@@ -331,22 +331,21 @@ %22);%0Avar -recast +types = requi @@ -348,22 +348,25 @@ equire(%22 -rec ast +-types %22);%0Avar @@ -369,22 +369,21 @@ var n = -recast +types .namedTy @@ -399,14 +399,13 @@ b = -recast +types .bui
59c601cc6cb68adcb3b48bd04292f643798a4759
Fix spaced-comment style issues
plugins/google_analytics/web_client/main.js
plugins/google_analytics/web_client/main.js
import _ from 'underscore'; import events from 'girder/events'; import { restRequest } from 'girder/rest'; import './lib/backbone.analytics'; import './routes'; events.on('g:appload.after', function () { /*eslint-disable */ (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); /*eslint-enable */ restRequest({ type: 'GET', path: 'google_analytics/id' }).done(_.bind(function (resp) { if (resp.google_analytics_id) { ga('create', resp.google_analytics_id, 'none'); } }, this)); }); /** * Add analytics for the hierarchy widget specifically since it routes without * triggering (calling navigate without {trigger: true}). */ events.on('g:hierarchy.route', function (args) { var curRoute = args.route; if (!/^\//.test(curRoute)) { curRoute = '/' + curRoute; } /*global ga*/ ga('send', 'pageview', curRoute); });
JavaScript
0.000004
@@ -1124,16 +1124,17 @@ %7D%0A /* + global g @@ -1134,16 +1134,23 @@ lobal ga +:false */%0A g
94ccbd815ac94506eb6d8a8461166614872bb0ac
Update access
lib/magi.js
lib/magi.js
var http = require('http') , https = require('https') var api = require('./commands') , errors = require('./errors') function Client(options) { this.opts = { host: 'localhost' , port: 8232 , method: 'POST' , user: 'magirpc' , pass: 'magipass' , headers: { 'Host': 'localhost' , 'Authorization': '' } , passphrasecallback: null , https: false , ca: null } if (options) { this.set(options) } } Client.prototype = { invalid:function(command) { var args = Array.prototype.slice.call(arguments, 1) , fn = args.pop() if (typeof fn !== 'function') { fn = console.log } return fn(new Error('No such command "' + command + '"')) }, send:function(command) { var args = Array.prototype.slice.call(arguments, 1) , self = this , fn if (typeof args[args.length-1] === 'function') { fn = args.pop().bind(this) }else { fn = console.log } var rpcData = JSON.stringify({ id: new Date().getTime() , method: command.toLowerCase() , params: args }) var options = this.opts options.headers['Content-Length'] = rpcData.length var request; if (options.https === true){ request = https.request; } else{ request = http.request; } var req = request(options, function(res) { var data = '' res.setEncoding('utf8') res.on('data', function(chunk) { data += chunk }) res.on('end', function() { try { data = JSON.parse(data) }catch(exception) { var errMsg = res.statusCode !== 200 ? 'Invalid params ' + res.statusCode : 'Failed to parse JSON' errMsg += ' : '+JSON.stringify(data) return fn(new Error(errMsg)) } if (data.error) { if (data.error.code === errors.RPC_WALLET_UNLOCK_NEEDED && options.passphrasecallback) { return self.unlock(command, args, fn) } else { var err = new Error(JSON.stringify(data)) err.code = data.error.code return fn(err) } } fn(null, data.result !== null ? data.result : data) }) }) req.on('error', fn) req.end(rpcData) return this }, exec:function(command) { var func = api.isCommand(command) ? 'send' : 'invalid' return this[func].apply(this, arguments) }, auth:function(user, pass) { if (user && pass) { var authString = ('Basic ') + new Buffer(user+':'+pass).toString('base64') this.opts.headers['Authorization'] = authString } return this }, unlock:function(command, args, fn) { var self = this var retry = function(err) { if (err) { fn(err) } else { var sendargs = args.slice(); sendargs.unshift(command); sendargs.push(fn) self.send.apply(self, sendargs) } } this.opts.passphrasecallback(command, args, function(err, passphrase, timeout) { if (err) { fn(err) } else { self.send('walletpassphrase', passphrase, timeout, retry) } }) }, set:function(k, v) { var type = typeof(k); if (typeof(k) === 'object') { for (var key in k) { this.set(key, k[key]); }; return; }; var opts = this.opts; var k = k.toLowerCase(); if (opts.hasOwnProperty(k)) { opts[k] = v if (/^(user|pass)$/.test(k)) { this.auth(opts.user, opts.pass) }else if (k === 'host') { opts.headers['Host'] = v }else if (k === 'passphrasecallback' || k === 'https' || k === 'ca') { opts[k] = v } } return this; }, get:function(k) { //Special case for booleans if(this.opts[k] === false){ return false; }else { if(this.opts[k] !== false){ var opt = this.opts[k.toLowerCase()] } return opt; //new Error('No such option "'+k+'" exists'); } }, errors: errors } api.commands.forEach(function(command) { var cp = Client.prototype; var tlc = [command.toLowerCase()]; cp[command] = cp[tlc] = function() { cp.send.apply(this, tlc.concat(([]).slice.call(arguments))); }; }) module.exports = function(options) { return new Client(options) }
JavaScript
0
@@ -260,15 +260,8 @@ ' -magirpc '%0A @@ -280,16 +280,8 @@ ' -magipass '%0A
b6806b04528dd11d7fc036e10805ebd94cc4f3c5
Save tags to result_tags variable
clarifai.js
clarifai.js
// Cloned from https://github.com/cassidoo/clarifai-javascript-starter module.exports = function (imgurl) { var $ = require('jQuery'); //tags to be returned var result_tags; var LocalStorage = require('node-localstorage').LocalStorage, localStorage = new LocalStorage('./scratch'); function getCredentials(cb) { console.log("getCredentials() is running!"); var data = { grant_type: 'client_credentials', client_id: "LPOXuuwXLHA2yZ7fBrN_DAHTsu26s2mR9h4DVmMa", client_secret: "VMEOyjHqQqIRRdpNL-o8wmfEpnsObF9ksIaPJ2Yt" }; return $.ajax({ type: 'POST', url: 'https://api.clarifai.com/v1/token', data: data }) .then(function(r) { localStorage.setItem('accessToken', r.access_token); localStorage.setItem('tokenTimestamp', Math.floor(Date.now() / 1000)); console.log(("ajax in getCredentials ran!")); cb(); }); } function postImage(imgurl) { var data = { url: imgurl }; var accessToken = localStorage.getItem('accessToken'); console.log(accessToken); $.ajax({ // TODO This ajax is not running. Once it runs, everything should work type: 'POST', url: 'https://api.clarifai.com/v1/tag', headers: { Authorization: 'Bearer ' + accessToken }, data: data }).then(function(r){ console.log("ajax in postImage ran!"); result_tags = parseResponse(r); }); } function parseResponse(resp) { var tags = []; if (resp.status_code === 'OK') { var results = resp.results; tags = results[0].result.tag.classes; console.log("clarifai.js is parsing tags!"); } else { console.log('Sorry, something is wrong.'); } $('#tags').text(tags.toString().replace(/,/g, ', ')); console.log("clarifai.js tags is about to be returned!"); console.log(tags); return tags; } if (localStorage.getItem('tokenTimeStamp') - Math.floor(Date.now() / 1000) > 86400 || localStorage.getItem('accessToken') === null) { getCredentials(function() { console.log("getCredentials callback is being called!"); postImage(imgurl); // IMPLTMENT HIS ! }); } else { postImage(imgurl); } console.log("everything ran!"); return result_tags; }
JavaScript
0
@@ -101,16 +101,77 @@ gurl) %7B%0A + console.log(%22INSIDE clarifai.js!%22);%0A console.log(imgurl);%0A var $ @@ -1923,16 +1923,40 @@ (tags);%0A + result_tags = tags;%0A retu
7bda9c55f975fa010f1a21f478025c02d611f988
Update namespace
lib/node_modules/@stdlib/math/base/blas/lib/index.js
lib/node_modules/@stdlib/math/base/blas/lib/index.js
'use strict'; /* * When adding modules to the namespace, ensure that they are added in alphabetical order according to module name. */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-read-only-property' ); // MAIN // /** * Top-level namespace. * * @namespace blas */ var blas = {}; /** * @name asum * @memberof blas * @readonly * @type {Function} * @see {@link module:@stdlib/math/base/blas/asum} */ setReadOnly( blas, 'asum', require( '@stdlib/math/base/blas/asum' ) ); /** * @name dasum * @memberof blas * @readonly * @type {Function} * @see {@link module:@stdlib/math/base/blas/dasum} */ setReadOnly( blas, 'dasum', require( '@stdlib/math/base/blas/dasum' ) ); /** * @name daxpy * @memberof blas * @readonly * @type {Function} * @see {@link module:@stdlib/math/base/blas/daxpy} */ setReadOnly( blas, 'daxpy', require( '@stdlib/math/base/blas/daxpy' ) ); /** * @name dcopy * @memberof blas * @readonly * @type {Function} * @see {@link module:@stdlib/math/base/blas/dcopy} */ setReadOnly( blas, 'dcopy', require( '@stdlib/math/base/blas/dcopy' ) ); /** * @name sasum * @memberof blas * @readonly * @type {Function} * @see {@link module:@stdlib/math/base/blas/sasum} */ setReadOnly( blas, 'sasum', require( '@stdlib/math/base/blas/sasum' ) ); // EXPORTS // module.exports = blas;
JavaScript
0.000001
@@ -479,32 +479,222 @@ las/asum' ) );%0A%0A +/**%0A* @name copy%0A* @memberof blas%0A* @readonly%0A* @type %7BFunction%7D%0A* @see %7B@link module:@stdlib/math/base/blas/copy%7D%0A*/%0AsetReadOnly( blas, 'copy', require( '@stdlib/math/base/blas/copy' ) );%0A%0A /**%0A* @name dasu
b7d166905d9b80f22eca61bb4fdde4357c1b722d
Update the interval of test danmus
lib/main.js
lib/main.js
// Require SDK var tmr = require('sdk/timers'); var tabs = require("sdk/tabs"); var self = require("sdk/self"); var prefs = require('sdk/simple-prefs').prefs; var buttons = require('sdk/ui/button/action'); var pageMod = require("sdk/page-mod"); // Global Variables var attached = false; var shooting = true; var wx_worker = undefined; var dm_worker = undefined; var dm_workers = {}; // Toolbar Button var button = buttons.ActionButton({ id: "weixin-danmu", label: "微信弹幕", icon: { "16": "./icons/icon-o-16.png", "32": "./icons/icon-o-32.png", "64": "./icons/icon-o-64.png" }, onClick: function() { if (prefs["danmuDebug"]) { if (dm_worker) { var counter = 0; var timer = tmr.setInterval(function() { if (counter++ < 10) { dm_worker.port.emit("bullet", {content:{text: randomString() }}); } else { tmr.clearTimeout(timer); } }, 100); } } else { if (attached) { if (shooting) { shooting = false; button.black(); console.log("Deactivated"); } else { shooting = true; button.light(); console.log("Activated"); } } else { tabs.open("https://wx.qq.com/"); } } } }); button.light = function() { button.icon = { "16": "./icons/icon-16.png", "32": "./icons/icon-32.png", "64": "./icons/icon-64.png" }; }; button.black = function() { button.icon = { "16": "./icons/icon-o-16.png", "32": "./icons/icon-o-32.png", "64": "./icons/icon-o-64.png" }; }; // Attach weixin.js pageMod.PageMod({ include: "*.qq.com", attachTo: "top", contentScriptFile: [ self.data.url("jquery-2.1.3.min.js"), self.data.url("weixin.js") ], onAttach: function(worker){ attached = true; button.light(); console.log("weixin.js attached"); wx_worker = worker; wx_worker.port.on("bullet", function(msg) { if (prefs["weixinDebug"]) { tabs.activeTab.attach({ contentScript: 'alert("' + msg.content.text + '");' }); } else { if (shooting && dm_worker) { dm_worker.port.emit("bullet", msg); } } }); } }); // Attach danmu.js for (let tab of tabs) { autoloadDanmu(tab); } tabs.on('open', autoloadDanmu); tabs.on('activate', function(tab) { dm_worker = dm_workers[tab.id]; if (dm_worker) { pushDanmuSettings(dm_worker); } }); // Utility functions function autoloadDanmu(tab) { attachDanmu(tab); tab.on('pageshow', attachDanmu); } function attachDanmu(tab) { console.log("danmu.js attached to:" + tab.url); var worker = tab.attach({ contentScriptFile: [ self.data.url("jquery-2.1.3.min.js"), self.data.url("danmu.js") ] }); pushDanmuSettings(worker); dm_workers[tab.id] = worker; if (tabs.activeTab.id == tab.id) { dm_worker = worker; } } function pushDanmuSettings(worker) { worker.port.emit("fontSize", prefs["fontSize"]); } function randomString(len) { len = len || 32; var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxy0z123456789'; var maxPos = chars.length; var str = ''; for (_i = 0; _i < len; _i++) { str += chars.charAt(Math.floor(Math.random() * maxPos)); } return str; }
JavaScript
0.000077
@@ -953,17 +953,17 @@ %7D, -1 +5 00);%0A
6ab9f7831fc2c12ae383847d22cb4fa50f9c334d
Add resource types to allowed types
test/solution-template-validation-tests/test/mainTemplateTests.js
test/solution-template-validation-tests/test/mainTemplateTests.js
var assert = require('assert'); var util = require('./util'); const filesFolder = './'; var path = require('path'); var chai = require('chai'); var assert = chai.assert; // Using Assert style var expect = chai.expect; // Using Expect style var should = chai.should(); // Using Should style var folder = process.env.npm_config_folder || filesFolder; var mainTemplateFileJSONObject = util.getMainTemplateFile(folder).jsonObject; var mainTemplateFile = util.getMainTemplateFile(folder).file; var createUiDefFileJSONObject = util.getCreateUiDefFile(folder).jsonObject; var createUiDefFile = util.getCreateUiDefFile(folder).file; var templateFiles = util.getTemplateFiles(folder).files; var templateFileJSONObjects = util.getTemplateFiles(folder).fileJSONObjects; chai.use(function(_chai, _) { _chai.Assertion.addMethod('withMessage', function(msg) { _.flag(this, 'message', msg); }); }); function getErrorMessage(obj, file, message) { return 'json object with \'name\' at line number ' + util.getPosition(obj, file) + ' ' + message; } describe('mainTemplate.json file - ', () => { describe('parameters tests - ', () => { it('each parameter that does not have a defaultValue, must have a corresponding output in createUIDef', () => { var currentDir = path.dirname(mainTemplateFile); // assert create ui def exists in the above directory util.assertCreateUiDefExists(currentDir); // get the corresponding create ui def var createUiDefJSONObject = util.getCreateUiDefFile(currentDir).jsonObject; // get output keys in main template var outputsInCreateUiDef = Object.keys(createUiDefJSONObject.parameters.outputs); // convert to lowercase for (var i in outputsInCreateUiDef) { outputsInCreateUiDef[i] = outputsInCreateUiDef[i].toLowerCase(); } // validate each parameter in main template has a value in outputs mainTemplateFileJSONObject.should.have.property('parameters'); var parametersInMainTemplate = Object.keys(mainTemplateFileJSONObject.parameters); parametersInMainTemplate.forEach(parameter => { if (typeof(mainTemplateFileJSONObject.parameters[parameter].defaultValue) === 'undefined') { outputsInCreateUiDef.should.withMessage('in file:mainTemplate.json. outputs in createUiDefinition is missing the parameter ' + parameter).contain(parameter.toLowerCase()); } }); }); // TODO: should it be non null, or should all secure strings not contain default value? it('non-null default values must not be provided for secureStrings', () => { templateFileJSONObjects.forEach(templateJSONObject => { var templateObject = templateJSONObject.value; Object.keys(templateObject.parameters).forEach(parameter => { if (templateObject.parameters[parameter].type.toLowerCase() == 'securestring') { // get default value if one exists var defaultVal = templateObject.parameters[parameter].defaultValue; if (defaultVal && defaultVal.length > 0) { expect(templateObject.parameters[parameter], 'in file:' + templateJSONObject.filename + parameter + ' should not have defaultValue').to.not.have.property('defaultValue'); } } }); }); }); // TODO: should location prop in resources all be set to param('location') ? it('a parameter named "location" must exist and must be used on all resource "location" properties', () => { mainTemplateFileJSONObject.should.withMessage('file:mainTemplate.json is missing parameters property').have.property('parameters'); mainTemplateFileJSONObject.parameters.should.withMessage('file:mainTemplate.json is missing location property in parameters').have.property('location'); // TODO: if location default value exists, it should be set to resourceGroup.location(). Correct? // each resource location should be "location": "[parameters('location')]" var expectedLocation = '[parameters(\'location\')]'; var message = 'in file:mainTemplate.json should have location set to [parameters(\'location\')]'; Object.keys(mainTemplateFileJSONObject.resources).forEach(resource => { var val = mainTemplateFileJSONObject.resources[resource]; if (val.location && val.type.toLowerCase() != 'microsoft.resources/deployments') { val.location.split(' ').join('').should.withMessage(getErrorMessage(val, mainTemplateFile, message)).be.eql(expectedLocation); } }); }); it('the template must not contain any unused parameters', () => { mainTemplateFileJSONObject.should.have.property('parameters'); var parametersInMainTemplate = Object.keys(mainTemplateFileJSONObject.parameters); parametersInMainTemplate.forEach(parameter => { var paramString = 'parameters(\'' + parameter.toLowerCase() + '\')'; JSON.stringify(mainTemplateFileJSONObject).toLowerCase().should.withMessage('file:mainTemplate.json. unused parameter ' + parameter + ' in mainTemplate').contain(paramString); }); }); }); describe('resources tests - ', () => { it('resourceGroup().location must not be used in the solution template except as a defaultValue for the location parameter', () => { templateFileJSONObjects.forEach(templateJSONObject => { var templateObject = templateJSONObject.value; templateObject.should.have.property('resources'); var locationString = '[resourceGroup().location]'; var message = 'in file:' + templateJSONObject.filename + ' should NOT have location set to [resourceGroup().location]'; Object.keys(templateObject.resources).forEach(resource => { var val = templateObject.resources[resource]; if (val.location) { val.location.should.withMessage(getErrorMessage(val, templateJSONObject.filepath, message)).not.be.eql(locationString); } }); }); }); it('apiVersions must NOT be retrieved using providers().apiVersions[n]. This function is non-deterministic', () => { templateFileJSONObjects.forEach(templateJSONObject => { var templateObject = templateJSONObject.value; templateObject.should.have.property('resources'); var message = 'in file:' + templateJSONObject.filename + ' should NOT have api version determined by providers().'; Object.keys(templateObject.resources).forEach(resource => { var val = templateObject.resources[resource]; if (val.apiVersion) { val.apiVersion.should.withMessage(getErrorMessage(val, templateJSONObject.filepath, message)).not.contain('providers('); } }); }); }); it('template must contain only approved resources (Compute/Network/Storage)', () => { templateFileJSONObjects.forEach(templateJSONObject => { var templateObject = templateJSONObject.value; templateObject.should.have.property('resources'); var message = 'in file:' + templateJSONObject.filename + ' is NOT a compute, network or a storage resource type'; Object.keys(templateObject.resources).forEach(resource => { var val = templateObject.resources[resource]; if (val.type) { var rType = val.type.split('/'); var cond = rType[0].toLowerCase() == 'microsoft.compute' || rType[0].toLowerCase() == 'microsoft.storage' || rType[0].toLowerCase() == 'microsoft.network' || rType[0].toLowerCase() == 'microsoft.resources'; expect(cond, getErrorMessage(val, templateJSONObject.filepath, message + '. The resource object: ' + JSON.stringify(val))).to.be.true; } }); }); }); }); });
JavaScript
0
@@ -8011,24 +8011,88 @@ split('/');%0A + var lowerType = val.type.toLowerCase();%0A @@ -8392,16 +8392,186 @@ sources' + %7C%7C%0A lowerType == 'microsoft.insights/autoscalesettings' %7C%7C %0A lowerType == 'microsoft.authorization/roleassignments' ;%0A
381dbb6569b07554a2543082cbb2e736fb425e2a
Fix image uploads being perfectly white when canvas read access is blocked
app/javascript/flavours/glitch/util/resize_image.js
app/javascript/flavours/glitch/util/resize_image.js
import EXIF from 'exif-js'; const MAX_IMAGE_PIXELS = 1638400; // 1280x1280px const getImageUrl = inputFile => new Promise((resolve, reject) => { if (window.URL && URL.createObjectURL) { try { resolve(URL.createObjectURL(inputFile)); } catch (error) { reject(error); } return; } const reader = new FileReader(); reader.onerror = (...args) => reject(...args); reader.onload = ({ target }) => resolve(target.result); reader.readAsDataURL(inputFile); }); const loadImage = inputFile => new Promise((resolve, reject) => { getImageUrl(inputFile).then(url => { const img = new Image(); img.onerror = (...args) => reject(...args); img.onload = () => resolve(img); img.src = url; }).catch(reject); }); const getOrientation = (img, type = 'image/png') => new Promise(resolve => { if (!['image/jpeg', 'image/webp'].includes(type)) { resolve(1); return; } EXIF.getData(img, () => { const orientation = EXIF.getTag(img, 'Orientation'); resolve(orientation); }); }); const processImage = (img, { width, height, orientation, type = 'image/png' }) => new Promise(resolve => { const canvas = document.createElement('canvas'); if (4 < orientation && orientation < 9) { canvas.width = height; canvas.height = width; } else { canvas.width = width; canvas.height = height; } const context = canvas.getContext('2d'); switch (orientation) { case 2: context.transform(-1, 0, 0, 1, width, 0); break; case 3: context.transform(-1, 0, 0, -1, width, height); break; case 4: context.transform(1, 0, 0, -1, 0, height); break; case 5: context.transform(0, 1, 1, 0, 0, 0); break; case 6: context.transform(0, 1, -1, 0, height, 0); break; case 7: context.transform(0, -1, -1, 0, height, width); break; case 8: context.transform(0, -1, 1, 0, 0, width); break; } context.drawImage(img, 0, 0, width, height); canvas.toBlob(resolve, type); }); const resizeImage = (img, type = 'image/png') => new Promise((resolve, reject) => { const { width, height } = img; const newWidth = Math.round(Math.sqrt(MAX_IMAGE_PIXELS * (width / height))); const newHeight = Math.round(Math.sqrt(MAX_IMAGE_PIXELS * (height / width))); getOrientation(img, type) .then(orientation => processImage(img, { width: newWidth, height: newHeight, orientation, type, })) .then(resolve) .catch(reject); }); export default inputFile => new Promise((resolve, reject) => { if (!inputFile.type.match(/image.*/) || inputFile.type === 'image/gif') { resolve(inputFile); return; } loadImage(inputFile).then(img => { if (img.width * img.height < MAX_IMAGE_PIXELS) { resolve(inputFile); return; } resizeImage(img, inputFile.type) .then(resolve) .catch(() => resolve(inputFile)); }).catch(reject); });
JavaScript
0
@@ -1916,16 +1916,363 @@ ight);%0A%0A + // The Tor Browser and maybe other browsers may prevent reading from canvas%0A // and return an all-white image instead. Assume reading failed if the resized%0A // image is perfectly white.%0A const imageData = context.getImageData(0, 0, width, height);%0A if (imageData.every(value =%3E value === 255)) %7B%0A throw 'Failed to read from canvas';%0A %7D%0A%0A canvas
0e453572719f95e9a13053bc87d97740b73a77dc
add description
Algorithms/JS/trees/binaryLvlOrderTraverse.js
Algorithms/JS/trees/binaryLvlOrderTraverse.js
JavaScript
0.000004
@@ -0,0 +1,460 @@ +// Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).%0A%0A// For example:%0A// Given binary tree %7B3,9,20,#,#,15,7%7D,%0A// 3%0A// / %5C%0A// 9 20%0A// / %5C%0A// 15 7%0A// return its level order traversal as:%0A// %5B%0A// %5B3%5D,%0A// %5B9,20%5D,%0A// %5B15,7%5D%0A// %5D%0A%0A%0A/**%0A * Definition for a binary tree node.%0A * function TreeNode(val) %7B%0A * this.val = val;%0A * this.left = this.right = null;%0A * %7D%0A */%0A
4b0a2181fac143c4bd6d30ccebb3305d29c4bb8c
correct notification message.
preload.js
preload.js
(function(){ var onMessageCreated = function(user, store, router) { return function(data){ var notify = false; var mode = 'all'; if (mode == 'all') { notify = true; } else if (mode == 'mention') { if (data.message.mentions.indexOf(parseInt(user.get('id'))) >= 0) { notify = true; } } if (notify) { store.find('message', data.message.id).then(function(message) { var roomUrl = '/' + router.generate('room.index', message.get('room')); var roomName = message.get('room.organization.name').toString() + ' / ' + message.get('room.name').toString(); var payload = { sender: data.message.senderName, roomName: roomName, text: data.message.bodyPlain, iconUrl: data.message.senderIconUrl, url: roomUrl }; new Notification(JSON.stringify(payload)); }); } } }; window.addEventListener('ready.idobata', function(e) { var container = e.detail.container; var pusher = container.lookup('pusher:main'); var user = container.lookup('service:session').get('user'); var store = container.lookup('store:main'); var router = container.lookup('router:main'); pusher.bind('message:created', onMessageCreated(user, store, router)); }); })();
JavaScript
0.000001
@@ -460,242 +460,15 @@ var -roomUrl = '/' + router.generate('room.index', message.get('room'));%0A var roomName = message.get('room.organization.name').toString() + ' / ' + message.get('room.name').toString();%0A var payload = %7B%0A sender: +title = dat @@ -483,25 +483,25 @@ e.senderName -, +; %0A @@ -503,29 +503,33 @@ - roomName: roomName, +new Notification(title, %7B %0A @@ -541,12 +541,12 @@ -text +body : da @@ -583,19 +583,16 @@ icon -Url : data.m @@ -615,100 +615,21 @@ nUrl -,%0A url: roomUrl%0A %7D;%0A new Notification(JSON.stringify(payload)); +%0A %7D) %0A
5fa757f7c4d3b0455798515d42819972e88e02f4
Use different token/serial files for dev & hack modes
app/argv.js
app/argv.js
/** * argv.js * client arguments & defaults */ var fs = require('fs') , path = require('path') , banner = fs.readFileSync( path.resolve( __dirname , 'banner' ) ) , defaults , argv ; if (process.env.NODE_ENV === "development") { defaults = { cloudHost : "127.0.0.1" , streamHost : "127.0.0.1" , logFile : path.resolve(process.env.PWD, 'ninjablock.log') , serialFile : path.resolve(process.env.PWD, 'serial.conf') , tokenFile : path.resolve(process.env.PWD, 'token.conf') , env : 'development' , streamPort : 3003 , cloudPort : 3001 , secure : false } } else if (process.env.NODE_ENV === "hacking") { defaults = { cloudHost : "zendo.ninja.is" , streamHost : "stream.ninja.is" , logFile : path.resolve(process.env.PWD, 'ninjablock.log') , serialFile : path.resolve(process.env.PWD, 'serial.conf') , tokenFile : path.resolve(process.env.PWD, 'token.conf') , env : 'hacking' , streamPort : 443 , cloudPort : 443 , secure : true } } else { defaults = { cloudHost : "zendo.ninja.is" , streamHost : "stream.ninja.is" , logFile : '/var/log/ninjablock.log' , serialFile : '/etc/opt/ninja/serial.conf' , tokenFile : '/etc/opt/ninja/token.conf' , env : 'production' , streamPort : 443 , cloudPort : 443 , secure : true } } argv = require('optimist') .usage( [ banner , "This process requires certain parameters to run." , "Please see usage information below." , "" , "Example: $0 --device /dev/tty.usb*B" ].join("\n") ) .default(defaults) .argv ; module.exports = argv;
JavaScript
0
@@ -421,32 +421,44 @@ env.PWD, 'serial +-development .conf')%0A%09%09, toke @@ -493,32 +493,44 @@ .env.PWD, 'token +-development .conf')%0A%09%09, env @@ -852,24 +852,32 @@ PWD, 'serial +-hacking .conf')%0A%09%09, @@ -920,24 +920,32 @@ .PWD, 'token +-hacking .conf')%0A%09%09,
0ab63c6f3704b288300c0ec7abf5a0075cdf4be3
Comment out unused
lib/main.js
lib/main.js
/*globals exports, require, console */ /*jslint vars:true, todo:true */ (function () {'use strict'; function l (msg) { console.log(msg); } var _ = require('sdk/l10n').get, data = require('sdk/self').data, cm = require('sdk/context-menu'); exports.main = function () { // Content-type handlers: on all links that do not have http/s (unless option?) // Protocol handlers: on all non-http/s links (though would be nice to open in other browsers too) cm.Menu({label: _("Open protocol handler"), context: cm.PredicateContext(function (ctx) { return ctx.linkURL && !(/https?:/).test(ctx.linkURL); }), contentScriptFile: data.url('add-protocol-handlers.js'), onMessage: function (protocol) { console.log('protocol:' + protocol); }}); }; exports.onUnload = function () { // reason }; }());
JavaScript
0
@@ -94,17 +94,19 @@ rict';%0A%0A +/* %0A - function @@ -136,16 +136,19 @@ (msg);%0A%7D +%0A*/ %0A%0Avar%0A%09_ @@ -254,10 +254,9 @@ ');%0A -%09 %0A + expo @@ -365,20 +365,16 @@ ption?)%0A - %0A // @@ -781,17 +781,9 @@ %7D);%0A - %0A +%0A %0A%7D;%0A
10f0ab0c5fc029ce3497441fc7eb45431e67a3f2
missing comma
app/boot.js
app/boot.js
(function(document) { 'use strict'; if(/Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)) { console.log = function(){}; } var gitVersion = document.documentElement.attributes['git-version'].value; require.config({ waitSeconds: 30, baseUrl : '/app/', paths: { 'authentication' : 'services/authentication', 'angular' : 'libs/angular/angular.min', 'angular-flex' : 'libs/angular-flex/angular-flex', 'ngRoute' : 'libs/angular-route/angular-route.min', 'ngCookies' : 'libs/angular-cookies/angular-cookies.min', 'ngAnimate' : 'libs/angular-animate/angular-animate.min', 'ngSanitize' : 'libs/angular-sanitize/angular-sanitize.min', 'ngDialog' : 'libs/ng-dialog/js/ngDialog.min', 'text' : 'libs/requirejs-text/text', 'css' : 'libs/require-css/css.min', 'json' : 'libs/requirejs-plugins/src/json', 'bootstrap' : 'libs/bootstrap/dist/js/bootstrap.min', 'lodash' : 'libs/lodash/lodash.min', 'dragula' : 'libs/dragula.js/dist/dragula', 'bootstrap-notify': 'libs/remarkable-bootstrap-notify/bootstrap-notify.min', 'moment' : 'libs/moment/min/moment.min', 'moment-timezone' : 'libs/moment-timezone/builds/moment-timezone-with-data-2010-2020.min', 'rangy' : 'libs/rangy-release/rangy-core.min', 'shim' : 'libs/require-shim/src/shim', 'interface' : 'js/interface', 'magnific-popup' : 'libs/magnific-popup/dist/jquery.magnific-popup.min', 'jquery' : 'libs/jquery/dist/jquery.min', 'jquery-migrate' : 'libs/jquery-migrate/jquery-migrate.min', 'ammap3WorldHigh' : 'directives/reporting-display/worldEUHigh', 'alasql' : 'libs/alasql/dist/alasql.min', 'js-xlsx' : 'libs/js-xlsx/dist/xlsx.min', 'js-zip' : 'libs/js-xlsx/dist/jszip', 'ods' : 'libs/js-xlsx/dist/ods', 'linqjs' : 'libs/linqjs/linq', 'ngInfiniteScroll': 'libs/ngInfiniteScroll/build/ng-infinite-scroll', 'ngSmoothScroll' : 'libs/ngSmoothScroll/lib/angular-smooth-scroll', 'bootstrap-datepicker': 'libs/bootstrap-datepicker/js/bootstrap-datepicker', 'toastr' : 'libs/angular-toastr/dist/angular-toastr.tpls.min', 'ammap3' : 'libs/ammap3/ammap/ammap', 'ammap-theme' : 'libs/ammap3/ammap/themes/light', 'ngMeta' : 'libs/ngMeta/dist/ngMeta.min', 'facebook' : '//connect.facebook.net/en_US/sdk', 'gmapsapi' : 'https://maps.googleapis.com/maps/api/js?key=AIzaSyCyD6f0w00dLyl1iU39Pd9MpVVMOtfEuNI&libraries=places', 'vue' : 'libs/vue/vue.min', 'ngVue' : 'libs/ngVue/index.min', 'conferenceCal' : 'libs/@scbd/conference-cal/dist/lib/ConferenceCal.umd.min', 'conferenceCalCSS' : 'libs/@scbd/conference-cal/dist/lib/ConferenceCal' }, shim: { 'angular' : { deps : ['jquery'], exports: 'angular' }, 'angular-flex' : { deps : ['angular', 'jquery'] }, 'ngRoute' : { deps : ['angular-flex'] }, 'ngCookies' : { deps : ['angular-flex'] }, 'ngAnimate' : { deps : ['angular-flex'] }, 'ngSanitize' : { deps : ['angular-flex'] }, 'ngDialog' : { deps : ['angular-flex' ]},// 'css!libs/ng-dialog/css/ngDialog.min', 'css!libs/ng-dialog/css/ngDialog-theme-default.css'] }, 'bootstrap' : { deps : ['jquery' ] }, 'bootstrap-notify' : { deps : ['jquery', 'bootstrap'] }, 'moment-timezone' : { deps : ['moment'] }, 'jquery-migrate' : { deps : ['jquery']}, 'interface' : { deps : ['jquery-migrate']}, 'magnific-popup' : { deps : ['jquery']}, 'dragula' : { deps : ['css!libs/dragula.js/dist/dragula.css']}, 'alasql' : { deps : ['js-xlsx']}, 'js-xlsx' : { deps : ['js-zip', 'ods']}, 'toastr' : { deps : ['angular-flex'] }, 'ngSmoothScroll' : { deps : ['angular-flex'] }, 'ngInfiniteScroll' : { deps : ['angular-flex'] }, 'gmapsapi' : { exports: 'google'}, 'facebook' : { exports: 'FB'} 'ngVue' : { deps : ['vue'] }, 'conferenceCal' : { deps : ['ngVue'] } }, packages: [ { name: 'amchart', main: 'amcharts', location : 'libs/amcharts3/amcharts/' }, { name: 'ammap' , main: 'ammap' , location : 'libs/ammap3/ammap' } ], urlArgs: 'v=' + gitVersion }); define('xlsx', ['js-zip', 'ods'], function (jszip, ods) { window.JSZip = jszip; window.ODS = ods; }); define('underscore', ['lodash'], function(_) { console.log('Deprecated: use lodash'); return _; }); define('dropbox-dropins', ['https://www.dropbox.com/static/api/2/dropins.js'], function(){ if(window.Dropbox) window.Dropbox.appKey = "uvo7kuhmckw68pl"; //[email protected] return window.Dropbox; }); // BOOT require(['angular', 'app', 'bootstrap', 'routes', 'template', 'ngSanitize', 'ngRoute', 'providers/extended-route'], function(ng, app) { ng.element(document).ready(function(){ ng.bootstrap(document, [app.name]); }); }); })(document); // MISC //================================================== // Protect window.console method calls, e.g. console is not defined on IE // unless dev tools are open, and IE doesn't define console.debug //================================================== (function fixIEConsole() { 'use strict'; if (!window.console) { window.console = {}; } var methods = ["log", "info", "warn", "error", "debug", "trace", "dir", "group","groupCollapsed", "groupEnd", "time", "timeEnd", "profile", "profileEnd", "dirxml", "assert", "count", "markTimeline", "timeStamp", "clear"]; var noop = function() {}; for(var i = 0; i < methods.length; i++) { if (!window.console[methods[i]]) window.console[methods[i]] = noop; } })();
JavaScript
0.999885
@@ -4513,16 +4513,17 @@ s: 'FB'%7D +, %0A
162a2dd58fc0d3270dbb564f1b6751a5a1049d24
remove commented out log line [TASK-1025]
src/plugin/modules/widgets/knowledgeEngine.js
src/plugin/modules/widgets/knowledgeEngine.js
define([ 'knockout-plus', 'kb_common/html' ], function ( ko, html ) { 'use strict'; var t = html.tag, div = t('div'); function factory(config) { var runtime = config.runtime, hostNode, container; function attach(node) { hostNode = node; container = hostNode.appendChild(document.createElement('div')); } function start(params) { // console.log('params?', params); // crude for now... if (params.objectInfo.typeName !== 'Genome') { container.innerHTML = 'Sorry, Knowledge Engine Connections not yet available for ' + params.objectInfo.typeName; return; } container.innerHTML = div({ class: 'row' }, [ div({ class: 'col-sm-6' }, [ 'This is the Knowledge Engine Connections Panel' ]), div({ class: 'col-sm-6' }, [ div({ dataBind: { component: { name: '"dataview/knowledge-engine"', params: { ref: 'ref', runtime: 'runtime' } } } }), ]) ]); ko.applyBindings({ runtime: runtime, ref: params.objectInfo.ref }, container); } function stop () { } function detach() { if (hostNode && container) { hostNode.removeChild(container); } } return { attach: attach, start: start, stop: stop, detach: detach }; } return { make: function(config) { return factory(config); } }; });
JavaScript
0
@@ -434,56 +434,8 @@ ) %7B%0A - // console.log('params?', params);%0A%0A
c38a6e6af6ae578d51d3b3d35d007d0e3912b30a
Update ctrl.js
app/ctrl.js
app/ctrl.js
latinSquaresGame.controller('ctrl', ['$scope', '$rootScope', function($scope, $rootScope) { $scope.ngGridsterItems = [ { size: { x: 2, y: 3 }, position: [0, 0], id: 0 }, { size: { x: 2, y: 3 }, position: [0, 2], id: 1 }, { size: { x: 2, y: 3 }, position: [0, 4], id: 2 }, { size: { x: 2, y: 3 }, position: [0, 6], id: 3 }, { size: { x: 2, y: 3 }, position: [2, 0], id: 4 }, { size: { x: 2, y: 3 }, position: [2, 2], id: 5 }, { size: { x: 2, y: 3 }, position: [2, 4], id: 6 }, { size: { x: 2, y: 3 }, position: [2, 6], id: 7 }, { size: { x: 2, y: 3 }, position: [4, 0], id: 8 }, { size: { x: 2, y: 3 }, position: [4, 2], id: 8 }, { size: { x: 2, y: 3 }, position: [4, 4], id: 8 }, { size: { x: 2, y: 3 }, position: [4, 6], id: 8 }, { size: { x: 2, y: 3 }, position: [6, 0], id: 8 }, { size: { x: 2, y: 3 }, position: [6, 2], id: 8 }, { size: { x: 2, y: 3 }, position: [6, 4], id: 8 }, { size: { x: 2, y: 3 }, position: [6, 6], id: 8 } ]; $scope.ngGridsterItemsMap = { sizeX: 'item.size.x', sizeY: 'item.size.y', row: 'item.position[0]', col: 'item.position[1]', id: 'item.id' }; $scope.ngGridsterOpts = { columns: 8, pushing: false, floating: true, swapping: true, width: 'auto', colWidth: 'auto', rowHeight: 'match', margins: [15, 15], outerMargin: true, isMobile: false, mobileBreakPoint: 300, mobileModeEnabled: false, minColumns: 1, minRows: 1, maxRows: 22, defaultSizeX: 2, defaultSizeY: 3, minSizeX: 1, maxSizeX: null, minSizeY: 1, maxSizeY: null, resizable: { enabled: false, handles: ['s', 'e', 'n', 'w', 'se', 'ne', 'sw', 'nw'], start: function(event, $element, widget) {}, resize: function(event, $element, widget) {}, stop: function(event, $element, widget) {} }, draggable: { enabled: true, handle: '', start: function(event, $element, widget) {}, drag: function(event, $element, widget) {}, stop: function(event, $element, widget) {} } }; $scope.ngGridsterImageGal = [ { src: "img/bg.jpg", id: 1 }, { src: "img/bg.jpg", id: 2 }, { src: "img/bg.jpg", id: 3 }, { src: "img/bg.jpg", id: 4 }, { src: "img/bg.jpg", id: 5 }, { src: "img/bg.jpg", id: 6 }, { src: "img/bg.jpg", id: 7 }, { src: "img/bg.jpg", id: 8 }, { src: "img/bg.jpg", id: 9 }, { src: "img/bg.jpg", id: 10 }, { src: "img/bg.jpg", id: 11 }, { src: "img/bg.jpg", id: 12 }, { src: "img/bg.jpg", id: 13 }, { src: "img/bg.jpg", id: 14 }, { src: "img/bg.jpg", id: 15 }, { src: "img/bg.jpg", id: 16 }, ]; $scope.testMouseOver = function(item){ console.log(item.id); } }]); // КОНЕЦ КОНТРОЛЛЕРА
JavaScript
0.000003
@@ -1,8 +1,23 @@ +'use strict';%0A%0A latinSqu @@ -704,33 +704,33 @@ on: %5B4, 2%5D, id: -8 +9 %0A%09%09%7D,%0A%09%09%7B %0A%09%09%09si @@ -763,33 +763,34 @@ on: %5B4, 4%5D, id: -8 +10 %0A%09%09%7D,%0A%09%09%7B %0A%09%09%09si @@ -827,25 +827,26 @@ %5B4, 6%5D, id: -8 +11 %0A%09%09%7D,%0A%09%09%7B %0A%09 @@ -883,33 +883,34 @@ on: %5B6, 0%5D, id: -8 +12 %0A%09%09%7D,%0A%09%09%7B %0A%09%09%09si @@ -947,25 +947,26 @@ %5B6, 2%5D, id: -8 +13 %0A%09%09%7D,%0A%09%09%7B %0A%09 @@ -1007,25 +1007,26 @@ %5B6, 4%5D, id: -8 +14 %0A%09%09%7D,%0A%09%09%7B %0A%09 @@ -1067,25 +1067,26 @@ %5B6, 6%5D, id: -8 +15 %0A%09%09%7D%0A%09%5D;%0A%0A%09$ @@ -2871,74 +2871,8 @@ %5D;%0A%0A -%09$scope.testMouseOver = function(item)%7B%0A%09%09console.log(item.id);%0A%09%7D %0A%0A%0A%0A
434742a91a656c3b73e4e6231a1dca800d7dd1cd
Add more error detail in console when test fail
scripts/test/test-wrapper.js
scripts/test/test-wrapper.js
define(['jquery', 'lodash'], function($, _) { var testWrapper = function() { this.currentTest = ''; this.startTime = 0; this.testQuantity = 0; this.testFailed = 0; this.testSucceed = 0; this.$resultContainer = $('.TestResultsArea'); this.$testReportContainer = $('.TestReport'); this.$testQuantity = this.$testReportContainer.find('.tests-quantity'); this.$testSuceedQuantity = this.$testReportContainer.find('.tests-succeed-quantity'); this.$testFailedQuantity = this.$testReportContainer.find('.tests-failed-quantity'); this.execTest = function(mainName, testName, testFn) { var myself = this; setTimeout(function() { var startTime = new Date(); var succeed = null; var errorMsg = null; try { testFn(); succeed = true; } catch (error) { succeed = false; errorMsg = error; } var timeSpent = new Date() - startTime; console[succeed ? 'log' : 'error']('Test #' + this.testQuantity + ' "' + mainName + ' | ' + testName + '" took ' + timeSpent + 'ms to ' + (succeed ? 'SUCCEED' : 'FAILED') + '.'); myself.updateCounters(succeed); myself.renderTest(succeed, mainName, testName, timeSpent, errorMsg); }, 0); } this.updateCounters = function(succeed) { this.testQuantity++; if (succeed) { this.testSucceed++; } else { this.testFailed++; } this.$testQuantity.text(this.testQuantity); this.$testSuceedQuantity.text(this.testSucceed); this.$testFailedQuantity.text(this.testFailed); } this.createTestClass = function(mainName) { return 'testBlock-' + _.replace(mainName, ' ', '_'); } this.getTestContainer = function(mainName) { var className = this.createTestClass(mainName); var $container = this.$resultContainer.find('.' + className); if (!$container.length) { $container = $('<div>',{ class: className, }); $ul = $('<ul>'); $title = $('<h3>', { text: mainName, }); $container.append($title); $container.append($ul); this.$resultContainer.append($container); } return $container.find('ul'); } this.renderTest = function(succeed, mainName, name, time, errorMsg) { var $container = this.getTestContainer(mainName); var $result = $('<li/>', { class: 'mdl-list__item', }); var iconName = succeed ? 'done' : 'close'; var checked = succeed ? 'checked' : ''; var secondaryBlock = succeed ? `${time} ms` : errorMsg; var iconClass = succeed ? 'icon-succeed' : 'icon-failed'; var $testStatus = $(` <span class="mdl-list__item-primary-content"> <i class="material-icons mdl-list__item-avatar ${iconClass}"> ${iconName} </i> ${name} </span> <span class="mdl-list__item-secondary-action"> ${secondaryBlock} </span>` ); $result.append($testStatus); $container.append($result); } }; return new testWrapper(); });
JavaScript
0
@@ -1395,24 +1395,120 @@ + '.');%0A%0A + if (!succeed) %7B%0A console.error(errorMsg);%0A %7D%0A%0A
f78c227893d8c85b4757773892ef9e9a03d29373
Support Request url in fetch interceptor
src/interceptors/fetchInterceptor.js
src/interceptors/fetchInterceptor.js
import queryString from 'query-string'; import parseUrl from 'parse-url'; import { baseInterceptor } from './baseInterceptor'; import { Response as KakapoResponse } from '../Response'; import { nativeFetch } from '../helpers/nativeServices'; export const name = 'fetch'; export const reference = nativeFetch; const fakeResponse = (response = {}, headers = {}) => { const responseStr = JSON.stringify(response); return new window.Response(responseStr, { headers }); }; export const fakeService = config => baseInterceptor(config, (helpers, url, options = {}) => { const body = options.body || ''; const method = options.method || 'GET'; const headers = options.headers || {}; const handler = helpers.getHandler(url, method); const params = helpers.getParams(url, method); if (!handler) { return reference(url, options); } const query = queryString.parse(parseUrl(url).search); const response = handler({ params, query, body, headers }); if (!(response instanceof KakapoResponse)) { return new Promise((resolve) => setTimeout( () => resolve(fakeResponse(response)), config.requestDelay )); } const result = fakeResponse(response.body, response.headers); return new Promise((resolve, reject) => setTimeout( () => { if (response.error) { return reject(result); } return resolve(result); }, config.requestDelay )); });
JavaScript
0
@@ -562,24 +562,75 @@ = %7B%7D) =%3E %7B%0A + url = url instanceof Request ? url.url : url;%0A%0A const bo
691d833b07f405040008348dfe3a0557d4fe9ac6
Remove auto-timeline refresh
javascript/controllers/twitter-controller.js
javascript/controllers/twitter-controller.js
angular.module('Gistter') .controller('TwitterController', function($scope, $q, twitterService, $http) { $scope.tweets = []; $scope.repos = []; twitterService.initialize(); // using the OAuth authorization result get the latest 20+ tweets from twitter for the user $scope.refreshTimeline = function(maxId) { var has_gist = []; twitterService.getLatestTweets(maxId).then(function(data) { $scope.tweets = $scope.tweets.concat(data); // go through each tweet and find gists angular.forEach($scope.tweets, function(tweet, i) { if (tweet.entities.urls[0]) { if (tweet.entities.urls[0].expanded_url.indexOf("github") > -1) { $scope.findRepos(tweet.entities.urls[0].expanded_url); has_gist.push(tweet); } } }); $scope.tweets = has_gist; }); }; // Query tweet that contains gist for git user's repos $scope.findRepos = function(gist) { var username = gist.split('/')[3]; if ($scope.repos.length === 0) { getUserRepos(username); } else { // make sure username doesn't exist var getOut = 0; for(var i; i < $scope.repos.length ;i++){ if (username === $scope.repos[i]) { getOut++; break; } } if (getOut === 0) { getUserRepos(username); } } }; var getUserRepos = function(username){ $http.get("https://api.github.com/users/" + username + "/repos") .then(onRepos, onError); }; var onRepos = function(response) { for(var i = 0; i < response.data.length; i++){ $scope.repos.push(response.data[i]); } }; var onError = function(reason) { $scope.error = "Could not fetch the data"; }; //when the user clicks the connect twitter button, the popup authorization window opens $scope.connectButton = function() { twitterService.connectTwitter().then(function() { if (twitterService.isReady()) { //if the authorization is successful, hide the connect button and display the tweets $('#connectButton').fadeOut(function() { $('#getTimelineButton, #signOut').fadeIn(); $scope.refreshTimeline(); $scope.connectedTwitter = true; }); } else { alert("We could not connect you successfully."); } }); }; //sign out clears the OAuth cache, the user will have to reauthenticate when returning $scope.signOut = function() { twitterService.clearCache(); $scope.tweets.length = 0; $('#getTimelineButton, #signOut').fadeOut(function() { $('#connectButton').fadeIn(); $scope.$apply(function() { $scope.connectedTwitter = false; }); }); }; //if the user is a returning user, hide the sign in button and display the tweets if (twitterService.isReady()) { $('#connectButton').hide(); $('#getTimelineButton, #signOut').show(); $scope.connectedTwitter = true; $scope.refreshTimeline(); } });
JavaScript
0.000001
@@ -2149,44 +2149,8 @@ ();%0A - $scope.refreshTimeline();%0A @@ -2906,38 +2906,8 @@ ue;%0A - $scope.refreshTimeline();%0A %7D%0A
68f0ab5355c4d56a273a83dc30b066f3fb0be074
Disable Node integration
app/main.js
app/main.js
var path = require("path"); var fs = require("fs"); var underscore = require("underscore"); require('electron-debug')({ showDevTools: false }); if (process.env.METEOR_SETTINGS){ var meteorSettings = JSON.parse(process.env.METEOR_SETTINGS); var electronSettings = meteorSettings.electron || {}; } else { var electronSettings = JSON.parse(fs.readFileSync( path.join(__dirname, "electronSettings.json"), "utf-8")); } var rootUrl = electronSettings.rootUrl || process.env.ROOT_URL; var app = require('app'); // Module to control application life. var BrowserWindow = require('browser-window'); // Module to create native browser window. var windowOptions = { width: electronSettings.width || 800, height: electronSettings.height || 600, resizable: true, frame: true }; if (electronSettings.resizable === false){ windowOptions.resizable = false; } if (electronSettings.frame === false){ windowOptions.frame = false; } app.on("ready", function(){ mainWindow = new BrowserWindow(windowOptions); mainWindow.focus(); mainWindow.loadURL(rootUrl); });
JavaScript
0
@@ -782,16 +782,452 @@ me: true +,%0A /**%0A * Disable Electron's Node integration so that browser dependencies like %60moment%60 will load themselves%0A * like normal i.e. into the window rather than into modules, and also to prevent untrusted client%0A * code from having access to the process and file system:%0A * - https://github.com/atom/electron/issues/254%0A * - https://github.com/atom/electron/issues/1753%0A */%0A webPreferences: %7B%0A nodeIntegration: false%0A %7D %0A%7D;%0A%0Aif
173b1d22895a42d7cedad5219d543607814b0ab6
Fix pokemon relase message
src/javascript/components/pokemon.js
src/javascript/components/pokemon.js
import emitter from 'js/emitter'; class Pokemon { constructor(element, options = {}) { this.$element = element; this.options = options; this.isPokemonCaught = false; this.caughtClass = 'pokemon--caught'; } init() { this.bindListeners(); } bindListeners() { this.$element.on('click', this.onElementClick.bind(this)); } onElementClick() { if (this.isPokemonCaught) { this.releasePokemon(); } else { this.catchPokemon(); } } releasePokemon() { const options = this.options; const message = `${options.releaseText} ${options.pokemonName}?`; // eslint-disable-next-line no-alert if (window.confirm(message)) { this.isPokemonCaught = false; this.toggleCaughtClass(); this.sendNotification('released'); } } catchPokemon() { this.isPokemonCaught = true; this.toggleCaughtClass(); this.sendNotification('caught'); } toggleCaughtClass() { this.$element.toggleClass(this.caughtClass); } sendNotification(event) { const notificationOptions = { body: `${this.options.pokemonName} was ${event}!`, icon: `images/pokemons/${this.options.pokemonId}.svg`, }; emitter.emit('notification:show', notificationOptions); } } /* istanbul ignore next */ export default ($element) => { new Pokemon($element, $element.data()).init(); }; export { Pokemon };
JavaScript
0.000032
@@ -571,17 +571,24 @@ options. -r +pokemonR eleaseTe
2b50da4a4acb5ef18af4c77eea1c41e37d8872cf
Load GA on deviceready
app/main.js
app/main.js
require(['jquery','backbone', 'router', 'fastclick', 'moxie.conf', 'backbone.queryparams', 'backbone.layoutmanager'], function($, Backbone, MoxieRouter, FastClick, conf) { // Include FastClick, this removes a 300ms touch event delay $(function() { new FastClick(document.body); // Listen for events on each click on Android // This seems to be the only way to open links in the android browser // $(document).on("deviceready", function() { if ((window.device) && (window.device.platform==='Android')) { $('#content').on('click', "a[href][target='_blank']", function(ev) { ev.preventDefault(); navigator.app.loadUrl(this.href, { openExternal:true }); return false; }); } }); }); // Initialse our router var moxieRouter = new MoxieRouter(); // Default to requesting hal+json but fallback to json $.ajaxSetup({ headers: { 'Accept': 'application/hal+json;q=1.0, application/json;q=0.9, */*; q=0.01' } }); // Add an event listener for sending document title changes Backbone.on('domchange:title', function(title) {$(document).attr('title', conf.titlePrefix+title);}, this); // This kicks off the app -- discovering the hashchanges and calling routers Backbone.history.start(); // Some simple events called on the default index page -- mostly for the sidebar menu $('#home a').click(function(ev) { ev.preventDefault(); $('body').toggleClass('is-sidebar-active'); return false; }); $('#back a').click(function(ev) { ev.preventDefault(); window.history.back(); return false; }); $('.overlay, #sidebar a').click(function(ev) { $('body').toggleClass('is-sidebar-active'); }); });
JavaScript
0
@@ -59,16 +59,22 @@ e.conf', + 'ga', 'backbo @@ -167,24 +167,28 @@ ck, conf +, GA ) %7B%0A // Inclu @@ -183,127 +183,689 @@ -// Include FastClick, this removes a 300ms touch event delay%0A $(function() %7B%0A new FastClick(document.body);%0A%0A +function startGA() %7B%0A // Init GA & start listening on hashchange%0A var ga = new GA(%7Bdebug: conf.ga.debug%7D);%0A ga.init(conf.ga.trackingID, conf.ga.period);%0A ga.startListening();%0A %7D%0A $(function() %7B%0A // Include FastClick, this removes a 300ms touch event delay%0A new FastClick(document.body);%0A%0A var app = (document.URL.indexOf( 'http://' ) === -1 && document.URL.indexOf( 'https://' ) === -1);%0A if (app) %7B%0A // Native application - Cordova%0A $(document).on(%22deviceready%22, function() %7B%0A // Now the GAPlugin will have loaded we can start sending analytics%0A startGA();%0A%0A @@ -910,16 +910,37 @@ on +both Android -%0A + and iOS%0A @@ -971,53 +971,100 @@ the -only way to open links in the android +most reliable way to open target=_blank%0A // url's in the native phone browser %0A @@ -1059,16 +1059,18 @@ browser +s. %0A @@ -1074,19 +1074,16 @@ -//%0A $(do @@ -1082,51 +1082,15 @@ -$(document).on(%22deviceready%22, function() %7B%0A +//%0A @@ -1180,19 +1180,19 @@ + + $(' -#content +body ').o @@ -1257,32 +1257,36 @@ + ev.preventDefaul @@ -1310,16 +1310,20 @@ + + navigato @@ -1383,32 +1383,36 @@ + return false;%0A @@ -1417,32 +1417,36 @@ + %7D);%0A @@ -1441,24 +1441,28 @@ + + %7D%0A %7D) @@ -1455,27 +1455,492 @@ %7D%0A -%7D); + else if ((window.device) && (window.device.platform==='iOS')) %7B%0A $('body').on('click', %22a%5Bhref%5D%5Btarget='_blank'%5D%22, function(ev) %7B%0A ev.preventDefault();%0A window.open(this.href, '_system');%0A return false;%0A %7D);%0A %7D%0A %7D);%0A %7D else %7B%0A // Load the GA plugin and start sending analytics%0A startGA();%0A %7D %0A %7D);%0A%0A @@ -1932,24 +1932,30 @@ %7D%0A %7D);%0A + // %0A // Init
cd13553757d73c8a9d7c4c626c242fb8b9ce2394
fix ytsr.getFilters handling previous querys wrong
lib/main.js
lib/main.js
const UTIL = require('./util.js'); const PARSE_ITEM = require('./parseItem.js'); const MINIGET = require('miniget'); // eslint-disable-next-line no-useless-escape, max-len const nextpagRegex = /<div class="(([^"]*branded\-page\-box[^"]*search\-pager)|([^"]*search\-pager[^"]*branded\-page\-box))/; const main = module.exports = async(searchString, options) => { const resp = {}; options = UTIL.checkArgs(searchString, options); resp.query = options.query; // Save provided nextpageRef and do the request resp.currentRef = options.nextpageRef; // Do request const body = await MINIGET(UTIL.buildRef(resp.currentRef, searchString, options), options).text(); const parsed = JSON.parse(body); const content = parsed[parsed.length - 1].body.content; // Get the table of items and parse it (remove null items where the parsing failed) resp.items = UTIL .between(content, '<ol id="item-section-', '\n</ol>') .split('</li>\n\n<li>') .filter(t => { let condition1 = !t.includes('<div class="pyv-afc-ads-container" style="visibility:visible">'); let condition2 = !t.includes('<span class="spell-correction-corrected">'); let condition3 = !t.includes('<div class="search-message">'); let condition4 = !t.includes('<li class="search-exploratory-line">'); return condition1 && condition2 && condition3 && condition4; }) .map(t => PARSE_ITEM(t, body, searchString)) .filter(a => a) .filter((_, index) => index < options.limit); // Adjust tracker options.limit -= resp.items.length; // Get amount of results resp.results = UTIL.between(UTIL.between(content, '<p class="num-results', '</p>'), '>') || '0'; // Get information about set filters const filters = UTIL.parseFilters(content); resp.filters = Array.from(filters).map(a => a[1].active).filter(a => a); // Parse the nextpageRef const pagesMatch = content.match(nextpagRegex); if (pagesMatch) { const pagesContainer = UTIL.between(content, pagesMatch[0], '</div>').split('<a'); const lastPageRef = pagesContainer[pagesContainer.length - 1]; resp.nextpageRef = UTIL.removeHtml(UTIL.between(lastPageRef, 'href="', '"')) || null; } // We're already on last page or hit the limit if (!resp.nextpageRef || options.limit < 1) return resp; // Recursively fetch more items options.nextpageRef = resp.nextpageRef; const nestedResp = await main(searchString, options); // Merge the responses resp.items.push(...nestedResp.items); resp.currentRef = nestedResp.currentRef; resp.nextpageRef = nestedResp.nextpageRef; return resp; }; main.getFilters = async(searchString, options) => { if (!searchString) throw new Error('searchString is mandatory'); const ref = UTIL.buildRef(null, searchString, options); const body = await MINIGET(ref, options).text(); const parsed = JSON.parse(body); const content = parsed[parsed.length - 1].body.content; return UTIL.parseFilters(content); };
JavaScript
0.000003
@@ -1,12 +1,40 @@ +const URL = require('url');%0A const UTIL = @@ -2696,16 +2696,53 @@ chString + %7C%7C typeof(searchString) !== 'string' ) throw @@ -2782,16 +2782,286 @@ ory');%0A%0A + // watch out for previous filter requests%0A // in such a case searchString would be an url including %60sp%60 & %60search_query%60 querys%0A let prevQuery = URL.parse(searchString, true).query;%0A const urlOptions = prevQuery ? Object.assign(%7B%7D, options, prevQuery) : options;%0A%0A const @@ -3085,16 +3085,42 @@ ef(null, + prevQuery.search_query %7C%7C searchS @@ -3118,33 +3118,36 @@ %7C searchString, -o +urlO ptions);%0A const
4dce405276b4b486ea63335f1e531770172bed89
Add support for matching errors from gfortran
lib/make.js
lib/make.js
'use babel'; import fs from 'fs'; import path from 'path'; import os from 'os'; import { exec } from 'child_process'; import voucher from 'voucher'; import { EventEmitter } from 'events'; export const config = { jobs: { title: 'Simultaneous jobs', description: 'Limits how many jobs make will run simultaneously. Defaults to number of processors. Set to 1 for default behavior of make.', type: 'number', default: os.cpus().length, minimum: 1, maximum: os.cpus().length, order: 1 }, useMake: { title: 'Target extraction with make', description: 'Use `make` to extract targets. This may yield unwanted targets, or take a long time and a lot of resource.', type: 'boolean', default: false, order: 2 } }; export function provideBuilder() { const gccErrorMatch = '(?<file>([A-Za-z]:[\\/])?[^:\\n]+):(?<line>\\d+):(?<col>\\d+):\\s*(fatal error|error):\\s*(?<message>.+)'; const ocamlErrorMatch = '(?<file>[\\/0-9a-zA-Z\\._\\-]+)", line (?<line>\\d+), characters (?<col>\\d+)-(?<col_end>\\d+):\\n(?<message>.+)'; const golangErrorMatch = '(?<file>([A-Za-z]:[\\/])?[^:\\n]+):(?<line>\\d+):\\s*(?<message>.*error.+)'; const errorMatch = [ gccErrorMatch, ocamlErrorMatch, golangErrorMatch ]; const gccWarningMatch = '(?<file>([A-Za-z]:[\\/])?[^:\\n]+):(?<line>\\d+):(?<col>\\d+):\\s*(warning):\\s*(?<message>.+)'; const warningMatch = [ gccWarningMatch ]; return class MakeBuildProvider extends EventEmitter { constructor(cwd) { super(); this.cwd = cwd; atom.config.observe('build-make.jobs', () => this.emit('refresh')); } getNiceName() { return 'GNU Make'; } isEligible() { this.files = [ 'Makefile', 'GNUmakefile', 'makefile' ] .map(f => path.join(this.cwd, f)) .filter(fs.existsSync); return this.files.length > 0; } settings() { const args = [ `-j${atom.config.get('build-make.jobs')}` ]; const defaultTarget = { exec: 'make', name: 'GNU Make: default (no target)', args: args, sh: false, errorMatch: errorMatch, warningMatch: warningMatch }; const promise = atom.config.get('build-make.useMake') ? voucher(exec, 'make -prRn', { cwd: this.cwd }) : voucher(fs.readFile, this.files[0]); // Only take the first file return promise.then(output => { return [ defaultTarget ].concat(output.toString('utf8') .split(/[\r\n]{1,2}/) .filter(line => /^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/.test(line)) .map(targetLine => targetLine.split(':').shift()) .filter( (elem, pos, array) => (array.indexOf(elem) === pos) ) .map(target => ({ exec: 'make', args: args.concat([ target ]), name: `GNU Make: ${target}`, sh: false, errorMatch: errorMatch, warningMatch: warningMatch }))); }).catch(e => [ defaultTarget ]); } }; }
JavaScript
0
@@ -912,32 +912,141 @@ ?%3Cmessage%3E.+)';%0A + const gfortranErrorMatch = '(?%3Cfile%3E%5B%5E:%5C%5Cn%5D+):(?%3Cline%3E%5C%5Cd+):(?%3Ccol%3E%5C%5Cd+):%5B%5C%5Cs%5C%5CS%5D+?Error: (?%3Cmessage%3E.+)';%0A const ocamlErr @@ -1317,16 +1317,36 @@ orMatch, + gfortranErrorMatch, ocamlEr
7f2fe45cfef9df2ced1146915b811e4225bee3be
Add summary with first two rows implemented
src/sections/Summary.js
src/sections/Summary.js
import React from 'react'; export default ({ modules, serverID }) => ( <p>Summary not implemented yet</p> );
JavaScript
0
@@ -25,88 +25,1297 @@ ';%0A%0A -export default (%7B modules, serverID %7D) =%3E (%0A %3Cp%3ESummary not implemented yet%3C/p%3E%0A +import %7B NAME, PAGES, FEATURES %7D from '../data/columnNames';%0A%0Aexport default (%7B modules, serverID %7D) =%3E (%0A (!modules %7C%7C !serverID) ? (%0A %3Cspan%3E%3C/span%3E%0A ) : (%0A %3Cdiv%3E%0A %3Ch2%3ECaptiva Capture License ID: %7BserverID%7D%3C/h2%3E%0A %3Ctable style=%7B%7B border: 'none' %7D%7D%3E%0A %3Ctbody%3E%0A %7Brow(%0A 'Server Type',%0A isEnterprise(modules) ? 'Enterprise' : 'Standard'%0A )%7D%0A %7Brow(%0A 'Page Volume',%0A pageVolume(modules)%0A )%7D%0A %3C/tbody%3E%0A %3C/table%3E%0A %3C/div%3E%0A )%0A);%0A%0Afunction row(title, value) %7B%0A return (%0A %3Ctr%3E%0A %3Ctd style=%7B%7B fontWeight: 'bold' %7D%7D%3E%7Btitle%7D:%3C/td%3E%0A %3Ctd style=%7B%7B paddingLeft: '1em' %7D%7D%3E%7Bvalue%7D%3C/td%3E%0A %3C/tr%3E%0A )%0A%7D%0A%0Afunction isEnterprise(modules) %7B%0A const serverModule = modules.find(module =%3E module%5BNAME%5D.includes('SERVER'));%0A%0A const hasFeatures = /%5BCDEFSW%5D/.test(serverModule%5BFEATURES%5D);%0A const hasModules = modules.some(module =%3E (%0A %5B'DPMANAGER', 'WSINPUT', 'WSOUTPUT', 'ECOPY'%5D.some(name =%3E (%0A module%5BNAME%5D.includes(name)%0A ))%0A ));%0A%0A return hasFeatures %7C%7C hasModules;%0A%7D%0A%0Afunction pageVolume(modules) %7B%0A return modules.filter(%0A module =%3E module%5BNAME%5D.includes('ANNUAL')%0A ).map(%0A module =%3E module%5BPAGES%5D%0A ).reduce((a, b) =%3E (%0A parseInt(a) + parseInt(b)%0A ), 0 );%0A +%7D%0A
7c8720dfa852b844f6c1db80182c072d8dc044d5
Update home link
src/js/containers/app/main-header.js
src/js/containers/app/main-header.js
'use strict' import React from 'react' const MainHeader = () => ( <header className='header' role='banner'> <a className='logo' href='/' role='logo'> <img src='svg/logo.svg' /> </a> <a className='btn-link' href='https://github.com/frontendbr/eventos' title='Anuncie seu evento'> Anunciar Evento </a> </header> ) export default MainHeader
JavaScript
0
@@ -135,16 +135,17 @@ ' href=' +. /' role=
c0fd2c8497d6c4f0a64fc43d49a0272b6e3b7f8b
Fix jshint errors in lib/make.js
lib/make.js
lib/make.js
var VM = require('vm'), Q = require('q'), QFS = require('q-fs'), INHERIT = require('inherit'), APW = require('apw'), PATH = require('./path'), UTIL = require('util'), BEMUTIL = require('./util'), REGISTRY = require('./nodesregistry'), LOGGER = require('./logger'); exports.DEFAULT_WORKERS = 10; exports.APW = INHERIT(APW, { findAndProcess: function(targets) { if (!Array.isArray(targets)) targets = [targets]; // Strip trailing slashes from target names // See https://github.com/bem/bem-tools/issues/252 var re = new RegExp(PATH.dirSep + '$'); targets = targets.map(function(t) { return t.replace(re, ''); }); var _this = this, foundNodes = targets.map(function(t) { return _this.findNode(t); }); return Q.all(foundNodes) .fail(function(err) { if (typeof err === 'string') return; return Q.reject(err); }) .then(function() { return _this.process(targets); }); }, // TODO: move node introspection logic to the node in arch findNode: function(id, head, tail) { head = head || ''; tail = tail || id; if (this.arch.hasNode(id)) return Q.resolve(id); if (head == id) return Q.reject(UTIL.format('Node "%s" not found', id)); var parts = tail.split(PATH.dirSep), p = parts.shift(); head = (head? [head, p] : [p]).join(PATH.dirSep); tail = parts.join(PATH.dirSep); var _this = this, magicHead = head + '*'; if (!this.arch.hasNode(magicHead)) { return this.findNode(id, head, tail); } return this.process(magicHead).then(function() { return _this.findNode(id, head, tail); }); } }, { Workers: INHERIT(APW.Workers, { start: function(plan) { LOGGER.finfo("[i] Going to build '%s' [%s]", plan.getTargets().join("', '"), plan.getId()); return this.__base(plan); } }) }); exports.createArch = function(opts) { var arch = new APW.Arch(), DefaultArch = require('./default-arch'), rootMakefile = PATH.join(opts.root, '.bem', 'make.js'); return QFS.exists(rootMakefile) .then(function(exists) { LOGGER.fsilly("File '%s' %s", rootMakefile, exists? 'exists' : "doesn't exist"); if (exists) return include(rootMakefile); }) .then(function() { return new (DefaultArch.Arch)(arch, opts).alterArch(); }); }; function getPathResolver(base) { return function(path) { return path.match(/^\./)? PATH.resolve(PATH.dirname(base), path) : path; } } function getRequireFunc(resolvePath) { return function(path) { return require(resolvePath(path)); } } function getIncludeFunc(resolvePath) { return function(path) { return include(resolvePath(path)); } } function include(path) { return evalConfig(require('fs').readFileSync(path, 'utf8'), path); } function evalConfig(content, path) { LOGGER.fsilly("File '%s' read, evaling", path); var resolvePath = getPathResolver(path), requireFunc = getRequireFunc(resolvePath); // let require.resolve() to work in make.js modules requireFunc.resolve = resolvePath; VM.runInNewContext( content, BEMUTIL.extend({}, global, { MAKE: REGISTRY, module: null, __filename: path, __dirname: PATH.dirname(path), require: requireFunc, include: getIncludeFunc(resolvePath) }), path); LOGGER.fsilly("File '%s' evaled", path); }
JavaScript
0.00003
@@ -1,12 +1,27 @@ +'use strict';%0A%0A var VM = req @@ -1369,16 +1369,17 @@ (head == += id) ret @@ -1974,24 +1974,55 @@ ion(plan) %7B%0A + /* jshint -W109 */%0A @@ -2109,24 +2109,55 @@ n.getId());%0A + /* jshint +W109 */%0A @@ -2456,24 +2456,55 @@ (exists) %7B%0A%0A + /* jshint -W109 */%0A @@ -2584,16 +2584,47 @@ xist%22);%0A + /* jshint +W109 */%0A @@ -2936,24 +2936,25 @@ path;%0A %7D +; %0A%0A%7D%0A%0Afunctio @@ -3054,32 +3054,33 @@ th(path));%0A %7D +; %0A%0A%7D%0A%0Afunction ge @@ -3184,16 +3184,17 @@ );%0A %7D +; %0A%0A%7D%0A%0Afun @@ -3323,24 +3323,47 @@ t, path) %7B%0A%0A + /* jshint -W109 */%0A LOGGER.f @@ -3908,24 +3908,24 @@ path);%0A%0A - LOGGER.f @@ -3956,12 +3956,35 @@ , path); +%0A /* jshint +W109 */ %0A%0A%7D%0A
027328087d4db667aeced2bfabd1c41c4b101769
remove unused services reference
app/views/search/search-filters/left-side-filter.js
app/views/search/search-filters/left-side-filter.js
define(['app', 'text!views/search/search-filters/left-side-filter.html', 'lodash', 'ngDialog', 'components/scbd-angularjs-services/services/utilities'], function (app, template, _) { app.directive('leftSideFilter', ['ngDialog', 'Thesaurus', 'locale', '$timeout', function (ngDialog, thesaurus, locale, $timeout) { return { restrict: 'EA', replace: true, require: '^searchDirective', template: template, scope: false, link: function ($scope, $element, $attrs, searchDirectiveCtrl) { var freeTextKeys = 0; // $scope.leftMenuFilters = {} $scope.locale = locale; $scope.onSchemaFilterChanged = function (schema, selected) { if (!selected) { if ($scope.leftMenuFilters) $scope.leftMenuFilters[schema] = undefined; $scope.leftMenuFilters = _.omit($scope.leftMenuFilters, _.isUndefined); if (_.isEmpty($scope.leftMenuFilters)) $scope.leftMenuFilters = undefined; } else { var fieldMappings = angular.copy(searchDirectiveCtrl.getSchemaFieldMapping(schema)); if (!_.isEmpty(fieldMappings)) { if (!$scope.leftMenuFilters) $scope.leftMenuFilters = {}; $scope.leftMenuFilters[schema] = fieldMappings } } return $scope.leftMenuFilters; } $scope.showFilterDialog = function (schema, filter, facets) { ngDialog.open({ template: 'filtersDialog', className: 'search-filters ngdialog-theme-default wide', controller: ['$scope', '$timeout', 'thesaurusService', 'searchService', function ($scope, $timeout, thesaurusService, searchService) { $scope.treeViewSelected = []; $scope.schema = schema; $scope.filter = filter; $scope.facets = facets; $scope.searchRelated = filter.searchRelated; var options; _.each(filter.selectedItems, function (option) { if (filter.type == 'thesaurus' || filter.type == 'solr' || filter.type == 'customListFn') $scope.treeViewSelected.push({ identifier: option.identifier }); }); $scope.treeOptions = function () { var dataSource; if (filter.type == "thesaurus") { var otherTerm = filter.otherTerm; if(otherTerm == undefined) otherTerm = true; dataSource = thesaurusService.getDomainTerms(filter.term, {other:otherTerm, narrowerOf: filter.narrowerOf}) } else if (filter.type == 'solr') { dataSource = runSolrQuery(filter.query); } else if (filter.type == 'customListFn') dataSource = searchDirectiveCtrl[filter.fn](); return dataSource.then(function (data) { return options = data; }) }; $scope.closeDialog = function () { ngDialog.close(); } $scope.applyFilter = function () { var selectedItems = {}; _.each($scope.treeViewSelected, function (item) { selectedItems[item.identifier] = _.find(options, { identifier: item.identifier }); }) updateBaseFilter(selectedItems, schema, filter, $scope.searchRelated); ngDialog.close(); } $scope.onBeforeSearch = function(keyword){ keyword = keyword.replace(/[0]/g, "Ø"); return keyword; } function runSolrQuery(query) { var lQuery = { query: query.q, fields: query.fl, sort: query.s, rowsPerPage: 3000, currentPage: 0 } return searchService.list(lQuery) .then(function (result) { return _(result.data.response.docs).map(function (item) { if(_.isArray(item.title)){ item.title = item.title.join(' | ') } return { identifier: item.identifier, title: { en: item.title } } }).sortBy('title.en').value() }); } }] }) function updateBaseFilter(selectedItems, schema, field, searchRelated) { var filter = _.find($scope.leftMenuFilters[schema], { title: field.title }) filter.selectedItems = selectedItems; filter.searchRelated = searchRelated; searchDirectiveCtrl.onLeftFilterUpdate($scope.leftMenuFilters) } } $scope.ngRepeatFinished = function () { $element.find('[data-toggle="tooltip"]').tooltip(); } $scope.removeSchemaFilters = function (option, filter) { // $scope.ngRepeatFinished(); $element.find('#' + (option.identifier||option.identifier_s)).tooltip('destroy') // $timeout(function(){ if(filter.type=='solrRecords'){ var index = _.findIndex(filter.selectedItems, function(item){ return item.identifier == option.identifier_s });//+ '@' + option._revision_i filter.selectedItems.splice(index, 1); } else{ delete filter.selectedItems[option.identifier]; } searchDirectiveCtrl.onLeftFilterUpdate($scope.leftMenuFilters); // }, 300) } $scope.RemoveLeftMenuFilters = function(){ $scope.leftMenuFilters = undefined; searchDirectiveCtrl.onLeftFilterUpdate($scope.leftMenuFilters) } $scope.clearFilterOptions = function (schema, filter) { if(filter){ clearFilterOptions(filter) } else{ var filters = $scope.leftMenuFilters[schema] _.each(filters, clearFilterOptions); } searchDirectiveCtrl.onLeftFilterUpdate($scope.leftMenuFilters); } $scope.onFilterDateChange = function (val) { searchDirectiveCtrl.onLeftFilterUpdate($scope.leftMenuFilters); } $scope.clearFilterDate = function (filter) { filter.filterValue = undefined; searchDirectiveCtrl.onLeftFilterUpdate($scope.leftMenuFilters); } $scope.saveSchemaFreeText = function (filter, text) { if (!filter.selectedItems) filter.selectedItems = {}; freeTextKeys++; filter.selectedItems[freeTextKeys] = { title: text, identifier: freeTextKeys }; searchDirectiveCtrl.onLeftFilterUpdate($scope.leftMenuFilters) filter.searchKeyword = ''; } $scope.recordSelected = function(item, filter){ searchDirectiveCtrl.onLeftFilterUpdate($scope.leftMenuFilters) } $scope.hasItems = function(items){ return items && _.keys(items).length; } function clearFilterOptions(filter){ if(filter.type!='solrRecords'){ _.each(filter.selectedItems, function(item){ $element.find('#' + item.identifier).tooltip('hide') }) } filter.selectedItems = {}; } //load dependant directive require(['views/forms/edit/document-selector']) } }; }]); });
JavaScript
0
@@ -240,89 +240,43 @@ ', ' -Thesaurus', 'locale', '$timeout', function (ngDialog, thesaurus, locale, $timeout +locale', function (ngDialog, locale ) %7B%0A @@ -2066,20 +2066,8 @@ pe', - '$timeout', 'th @@ -2121,18 +2121,8 @@ ope, - $timeout, the
92b756559b8c178b4ef338513d8c8b54f03f83f3
change cronjob to daily
src/sendStuffToUsers.js
src/sendStuffToUsers.js
'use strict'; var sender = { registerCronJob: function(bot) { var CronJob = require('cron').CronJob; // for testing: all minute new CronJob('*/1 * * * *', function() { //new CronJob('0 1 0 * * *', function() { console.log("++++++++++++++++++\nTime to send the newest stuff to the users!\n++++++++++++++++++"); sender.sendMessagesToUsers(bot); }, null, true, 'America/Los_Angeles'); }, sendMessagesToUsers: function(bot) { var users = require("./users"); users.getUsers().find({abo:1},{},function(err, docs) { docs.forEach(function(user) { sender.sendToUser(user, bot); }) }); }, sendToUser: function(user, bot) { console.log("sending to user " + user._id); var webscraper = require("./web_scraper.js"); webscraper.scrapeThisShit(user.lang, function(data) { console.log("send image"); bot.sendPhoto(user._id, data.image, {caption: data.title}); }); } }; module.exports = sender;
JavaScript
0.000003
@@ -136,16 +136,18 @@ ute%0A +// new Cron @@ -178,26 +178,24 @@ ion() %7B%0A -// new CronJob(
6b1985b20c982b0d2a16f704c8fd1d9c93e60321
Break merged single-line into multi-line
lib/pulsar/index.js
lib/pulsar/index.js
var PulsarStatus = require('./status'); var PulsarExec = require('./exec'); var PulsarTask = require('./task'); var events = require('events'); var util = require('util'); var _ = require('underscore'); var shellwords = require('shellwords'); var log = require('../logger'); module.exports = (function() { /** * @param {Object} db * @param {Object} config * @constructor */ var Pulsar = function(db, config) { this.db = db; this.config = config || {}; this.taskQueue = []; events.EventEmitter.call(this); }; util.inherits(Pulsar, events.EventEmitter); /** * @param {Object} args {@see PulsarExec} * @param {Object} [data] {@see PulsarExec} * @return {PulsarTask} task */ Pulsar.prototype._createTask = function(args, data) { var task = new PulsarTask(args, data); if (this.config.repo) { task._args.pulsarOptions.push('--conf-repo ' + this.config.repo); } if (this.config.branch) { args._args.pulsarOptions.push('--conf-branch ' + this.config.branch); } return task; }; /** * @param {String} app * @param {String} env * @param {String} action * @param {Object} [taskVariables] * @param {Function} callback */ Pulsar.prototype.createTask = function(app, env, action, taskVariables, callback) { if (!action || !_.isString(action) || !action.trim()) { throw new ValidationError('create task requires an action'); } var args = { app: app, env: env, action: action }; if (taskVariables) { if (_.isFunction(taskVariables)) { callback = taskVariables; } else { this._validateTaskVariables(taskVariables); args.capistranoOptions = this._taskVariablesToCapistrano(taskVariables); } } var task = this._createTask(args); var self = this; this.db.saveTask(task, function(err) { if (err) { return callback(err); } self.taskQueue[task.id] = task; task.on('change', function() { self.db.updateTask(task, function(err) { if (err) { log.error('Task update failed', {id: task.id}, err); } }); }); task.on('close', function() { delete self.taskQueue[task.id]; }); self.emit('create', task); return callback(null, task); }); }; /** * @param {Object} variables * @return {Object} validated variables formatted as required for capistranoOptions in constructor of PulsarExec * @throws {ValidationError} if taskVariables contain incorrect options */ Pulsar.prototype._validateTaskVariables = function(variables) { if (!_.isObject(variables) || _.isArray(variables)) { throw new ValidationError('taskVariables must be the hash object'); } //taskVariables are going to be '-s' capistrano options var errors = []; _.each(variables, function(value, key) { key = key.trim(); if (key.indexOf(' ') !== -1 || key.indexOf('"') !== -1 || key.indexOf('\'') !== -1) { errors.push('taskVariables.key:[' + key + '] contains illegal whitespace or quotes'); } if (!_.isString(value) && !_.isFinite(value)) { errors.push('taskVariables.key:[' + key + '] contains illegal value. Value must be a string or a number'); } }); if (errors.length) { throw new ValidationError(errors.join('; ')); } }; Pulsar.prototype._taskVariablesToCapistrano = function(variables) { var result = []; _.each(variables, function(value, key) { result.push('-s ' + shellwords.escape(key) + '="' + shellwords.escape(value) + '"'); }); return result; }; Pulsar.prototype.getTask = function(taskId, callback) { if (this.taskQueue[taskId]) { return callback(null, this.taskQueue[taskId]); } this.db.getTask(taskId, function(err, task) { return callback(err, task); }.bind(this)); }; Pulsar.prototype.getAvailableCapTasks = function(app, env, callback) { var args = { app: app, env: env, capistranoOptions: ['--tasks'] }; var task = this._createTask(args); task.on('close', function() { if (!task.status.is(PulsarStatus.FINISHED)) { return callback(new Error('Collecting of available cap tasks finished abnormally.\n' + task.output)); } var regex = /cap\s([^\s]+)\s+#\s+([^\s].+)\n/g; var match; var tasks = {}; while (null !== (match = regex.exec(task.output))) { tasks[match[1]] = match[2]; } return callback(null, tasks); }); task.execute(); }; Pulsar.prototype.getTaskList = function(callback) { return this.db.getTaskList(callback); }; return Pulsar; })();
JavaScript
0.0004
@@ -4022,24 +4022,30 @@ app: app, +%0A env: env, c @@ -4042,16 +4042,22 @@ nv: env, +%0A capistr
71cc4d7d99b58dc079a056530366735952a86601
Change requestStart on mqlight probe to not mark all events as root
probes/mqlight-probe.js
probes/mqlight-probe.js
/******************************************************************************* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ var Probe = require('../lib/probe.js'); var aspect = require('../lib/aspect.js'); var request = require('../lib/request.js'); var util = require('util'); var url = require('url'); var am = require('appmetrics'); /** * Probe to instrument the MQLight npm client */ function MQLightProbe() { Probe.call(this, 'mqlight'); } util.inherits(MQLightProbe, Probe); MQLightProbe.prototype.attach = function(name, target) { var that = this; if( name != 'mqlight' ) return target; if(target.__probeAttached__) return; target.__probeAttached__ = true; // After 'createClient' aspect.after(target, 'createClient', {}, function(target, methodName, createClientArgs, context, rc) { var thisClient = rc; // the MQLight client that was created // Just monitor 'send' for now as not sure what else will be useful var methods = 'send'; // Before one of the above methods is called on the client aspect.around(thisClient, methods, function(target, methodName, args, probeData) { // Start the monitoring for the method that.metricsProbeStart(probeData, methodName, args); that.requestProbeStart(probeData, methodName, args); // Advise the callback for the method. Will do nothing if no callback is registered aspect.aroundCallback(args, probeData, function(target, callbackArgs, probeData){ // method has completed and the callback has been called, so end the monitoring that.metricsProbeEnd(probeData, methodName, args, thisClient); that.requestProbeEnd(probeData, methodName, args, thisClient); }); }, function(target, methodName, args, probeData, rc) { // If no callback used then end the monitoring after returning from the method instead if (aspect.findCallbackArg(args) == undefined) { that.metricsProbeEnd(probeData, methodName, args, thisClient); that.requestProbeEnd(probeData, methodName, args, thisClient); } return rc; }); // Advise the callback code that is called when a message is received aspect.before(thisClient, 'on', function(target, methodName, args, probeData) { // only care about 'message' events if(args[0] == 'message') { // Must be a callback so no need to check for it aspect.aroundCallback(args, new Object(), function(obj, callbackArgs, probeData) { that.metricsProbeStart(probeData, 'message', callbackArgs); that.requestProbeStart(probeData, 'message', callbackArgs); }, function (target, callbackArgs, probeData, ret) { // method has completed and the callback has been called, so end the monitoring that.metricsProbeEnd(probeData, 'message', callbackArgs, thisClient); that.requestProbeEnd(probeData, 'message', callbackArgs, thisClient); return ret; }); } }); return rc; }); return target; }; /* * Lightweight metrics probe end for MQLight messages */ MQLightProbe.prototype.metricsEnd = function(probeData, method, methodArgs, client) { probeData.timer.stop(); if(method == 'message') { var data = methodArgs[0]; if(data.length > 25) { data = data.substring(0, 22) + "..."; } var topic = methodArgs[1].message.topic; am.emit('mqlight', { time : probeData.timer.startTimeMillis, clientid : client.id, data : data, method : method, topic : topic, duration : probeData.timer.timeDelta }); } else if(method == 'send') { var data = methodArgs[1]; if(data.length > 25) { data = data.substring(0, 22) + "..."; } var qos; var options; // options are optional - check number of arguments. if(methodArgs.length > 3) { options = methodArgs[2]; qos = options[0]; } am.emit('mqlight', { time : probeData.timer.startTimeMillis, clientid : client.id, data : data, method : method, topic : methodArgs[0], qos : qos, duration : probeData.timer.timeDelta }); } }; /* * Heavyweight request probes for MQLight messages */ MQLightProbe.prototype.requestStart = function (probeData, method, methodArgs) { probeData.req = request.startRequest('MQLight', method, true, probeData.timer); }; MQLightProbe.prototype.requestEnd = function (probeData, method, methodArgs, client) { if(method == 'message') { var data = methodArgs[0]; if(data.length > 25) { data = data.substring(0, 22) + "..."; } var topic = methodArgs[1].message.topic; probeData.req.stop({clientid: client.id, data: data, method: method, topic: methodArgs[0]}); } else if(method == 'send') { var data = methodArgs[1]; if(data.length > 25) { data = data.substring(0, 22) + "..."; } var qos; var options; // options are optional - check number of arguments. if(methodArgs.length > 3) { options = methodArgs[2]; qos = options[0]; } probeData.req.stop({clientid: client.id, data: data, method: method, topic: methodArgs[0], qos: qos}); } }; module.exports = MQLightProbe;
JavaScript
0
@@ -4668,24 +4668,52 @@ thodArgs) %7B%0A +%09if(method == 'message') %7B%0A%09 %09probeData.r @@ -4781,16 +4781,112 @@ timer);%0A +%09%7D else %7B%0A%09%09probeData.req = request.startRequest('MQLight', method, false, probeData.timer);%0A%09%7D%0A %7D;%0A%0AMQLi
7b06894eaf6bcd626a6120016225dda625097e62
fix back button bug when asked to exit
src/js/services/backButtonService.js
src/js/services/backButtonService.js
'use strict'; angular.module('copayApp.services').factory('backButton', function($log, $rootScope, gettextCatalog, $deepStateRedirect, $document, $timeout, go, $state, lodash) { var root = {}; root.menuOpened = false; root.dontDeletePath = false; var arrHistory = []; var body = $document.find('body').eq(0); var shownExitMessage = false; $rootScope.$on('$stateChangeSuccess', function(event, to, toParams, from, fromParams){ // if we navigated to point already been somewhere in history -> cut all the history past this point /*for (var i = 0; i < arrHistory.length; i++) { var state = arrHistory[i]; if (to.name == state.to && lodash.isEqual(toParams, state.toParams)) { arrHistory.splice(i+1); break; } }*/ lastState = arrHistory.length ? arrHistory[arrHistory.length - 1] : null; if (from.name == "" // first state || (lastState && !(to.name == lastState.to && lodash.isEqual(toParams, lastState.toParams)))) // jumped back in history arrHistory.push({to: to.name, toParams: toParams, from: from.name, fromParams: fromParams}); if (to.name == "walletHome") { $rootScope.$emit('Local/SetTab', 'walletHome', true); } root.menuOpened = false; }); function back() { if (body.hasClass('modal-open')) { $rootScope.$emit('closeModal'); } else if (root.menuOpened) { go.swipe(); root.menuOpened = false; } else { var currentState = arrHistory.pop(); if (!currentState || currentState.from == "") { arrHistory.push(currentState); askAndExit(); } else { var parent_state = $state.get('^'); if (parent_state.name) { // go up on state tree $deepStateRedirect.reset(parent_state.name); $state.go(parent_state); } else { // go back across history var targetState = $state.get(currentState.from); if (targetState.modal || (currentState.to == "walletHome" && $rootScope.tab == "walletHome")) { // don't go to modal and don't go to anywhere wfom home screen askAndExit(); } else if (currentState.from.indexOf(currentState.to) != -1) { // prev state is a child of current one go.walletHome(); } else { $state.go(currentState.from, currentState.fromParams); } } } } } function askAndExit(){ if (shownExitMessage) { navigator.app.exitApp(); } else { shownExitMessage = true; window.plugins.toast.showShortBottom(gettextCatalog.getString('Press again to exit')); $timeout(function() { shownExitMessage = false; }, 2000); } } function clearHistory() { arrHistory.splice(1); } document.addEventListener('backbutton', function() { back(); }, false); /*document.addEventListener('keydown', function(e) { if (e.which == 37) back(); }, false);*/ root.back = back; root.arrHistory = arrHistory; root.clearHistory = clearHistory; return root; });
JavaScript
0.000001
@@ -1969,16 +1969,54 @@ e screen + %0A%09%09%09%09%09%09arrHistory.push(currentState); %0A%09%09%09%09%09%09a
a5c68989d8bde44410b9dd94ce852f6b2632cfeb
fix test
src/server/_modelFor.js
src/server/_modelFor.js
(function() { "use strict"; var modelFor = require("./modelFor"); exports.test_standard_model_includes_page_title = function(test) { var expectedTitle = "abc ABC 123"; var result = modelFor(expectedTitle, {}); test.equal(result.title, expectedTitle); test.done(); }; exports.test_standard_model_includes_isAuthenticated = function(test) { var authenticatedRequest = { user: {} }; var unathenticatedRequest = {}; var authenticated = modelFor("", authenticatedRequest); var unauthenticated = modelFor("", unathenticatedRequest); test.equal(authenticated.isAuthenticated, true); test.equal(unauthenticated.isAuthenticated, false); test.done(); }; })();
JavaScript
0.000002
@@ -66,24 +66,134 @@ odelFor%22);%0A%0A + function fakeRequest() %7B%0A return %7B%0A flash : function() %7B return %7B%7D; %7D%0A %7D;%0A %7D%0A%0A exports. @@ -339,18 +339,29 @@ dTitle, -%7B%7D +fakeRequest() );%0A @@ -549,39 +549,60 @@ t = -%7B%0A user: %7B%7D%0A +fakeRequest();%0A authenticatedRequest.user = %7B %7D;%0A%0A @@ -637,18 +637,29 @@ quest = -%7B%7D +fakeRequest() ;%0A%0A
b6f7f94344522229cb683db63b25bc879fcbce09
fix in text
lib/property/text.js
lib/property/text.js
'use strict' var Property = require('./') /** * Use text to specify a text to an element * @type {string} * @memberOf Property * * @example * var a = new Element({ * text: { * val: "some text" * } * }) * */ exports.properties = { text: new Property({ define: { generateConstructor () { return function DerivedProperty (val, ev, parent, key) { if (parent) { parent.node.appendChild(document.createTextNode('')) } } } }, on: { data: { text (data, event) { if (data !== null && this._input !== null) { let element = this.parent if (element) { let val = this.val let type = typeof val let node = element.node if (type !== 'string' && type !== 'number') { val = '' } if (/text/.test(node.type)) { if (node.value !== val) { node.value = val } return } let childNodes = node.childNodes if (childNodes) { for (let i = 0, l = childNodes.length; i < l; i++) { let childNode = childNodes[i] if (childNode.nodeType === 3) { childNode.nodeValue = val return } } } } } } } } }).Constructor }
JavaScript
1
@@ -469,32 +469,81 @@ '))%0A %7D%0A + return Property.apply(this, arguments)%0A %7D%0A
dbdc93c7e88c9cb6d2307b954090eb65b2e8763e
Fix disappearing cards, yeah!
packages/game-factory/lib/preset-helper.js
packages/game-factory/lib/preset-helper.js
"use strict"; const Symbols = require("dc-constants").Symbols; function PresetHelper(preset, gameData, choiceProvider) { function createStateFromPreset() { return new preset.state.class(...evaluateStateArgs()); } this.createStateFromPreset = createStateFromPreset; function evaluateStateArgs() { let args = [ gameData, choiceProvider ]; preset.state.args.forEach(function(arg) { switch(arg) { case Symbols.player1: args.push(gameData.players[0]); break; case Symbols.player2: args.push(gameData.players[1]); break; case Symbols.player3: args.push(gameData.players[2]); break; case Symbols.player4: args.push(gameData.players[3]); break; default: args.push(arg); break; } }); return args; } function adjustPlayer(player, playerPreset, gameData) { player.money = playerPreset.money; playerPreset.dcCards.forEach( adjustCards.bind(null, player.gainDcCard, gameData.dcDeck) ); playerPreset.cars.forEach( adjustCards.bind(null, player.gainCar, gameData.carDeck) ); playerPreset.insurances.forEach( adjustCards.bind(null, player.gainInsurance, gameData.insuranceDeck) ); console.log("final cards ", player.dcCards); } this.adjustPlayer = adjustPlayer; function adjustCards(gainCard, cards, cardPreset) { let card; if(cardPreset === Symbols.random) { card = cards.pop(); console.log("popped card ", card); } else { card = cards.pickCard(cardPreset); console.log("picked " + cardPreset + " ", card); } gainCard(card); } } module.exports = PresetHelper;
JavaScript
0
@@ -1529,62 +1529,8 @@ ); -%0A%0A console.log(%22final cards %22, player.dcCards); %0A @@ -1686,18 +1686,16 @@ .random) - %7B %0A @@ -1723,65 +1723,8 @@ ();%0A - console.log(%22popped card %22, card);%0A %7D%0A @@ -1731,18 +1731,16 @@ else - %7B %0A @@ -1782,79 +1782,8 @@ et); -%0A console.log(%22picked %22 + cardPreset + %22 %22, card);%0A %7D %0A%0A
514f451a6af39eb7aaac6bb008fe746ea0460d58
fix proper bot api
lib/misc.js
lib/misc.js
var auth = require('./auth'); var logger = require('./logger'); var sessions = require('./sessions'); const timeDelay = 30 * 1000; function start_feedback(chatId, callback) { var feedbackMsg = "Thanks for using Cinnabot 😁\n"; feedbackMsg += "Feel free to tell us how cinnabot can be improved.\n"; feedbackMsg += "Type /done to end the feedback session.\n"; feedbackMsg += "Type /cancel to cancel feedback"; var remindDone = function() { callback("Please remember to type /done when you are done."); setTimeout(remindDone, timeDelay); }; setTimeout(remindDone, timeDelay); var feedbackSession = sessions.createFeedbackSession(chatId); return callback(feedbackMsg); } function continue_feedback(body, chatId, msg, callback) { var feedbackSession = sessions.getFeedbackSession(chatId); feedbackSession.feedbackMsg += body + "\n"; if (body.endsWith("/done")) { return done_feedback(chatId, msg, callback); } return; } function done_feedback(chatId, msg, callback) { var feedbackSession = sessions.getFeedbackSession(chatId); var feedbackMsg = feedbackSession.feedbackMsg; feedbackMsg = feedbackMsg.substring(0, feedbackMsg.length - 6); logger.feedback(feedbackMsg, msg, callback); sessions.deleteFeedbackSession(chatId); var doneMsg = "Thanks for the feedback 😁"; return callback(doneMsg); } function help(callback) { var helpMessage = "Here's what you can ask Cinnabot!\n\n" + "/bus - check bus timings for UTown and Dover road\n" + "/bus <busstop> - check bus timings for <busstop>\n" + "/dining - tell us how the food was\n" + "/events - view upcoming USP events\n" + "/fault - report building faults in Cinnamon\n" + "/feedback - send suggestions and complaints\n" + "/links - view useful links\n" + "/nusbus - check bus timings for NUS buses\n" + "/psi - get the psi and weather conditions\n" + "/register - register your NUS account!\n" + "/spaces - view upcoming activities in USP spaces\n" + "/stats - view key statistics"; callback(helpMessage); } function getLinks(chatId, bot) { var linkText = "USEFUL LINKS:\n" + "==============\n\n"; function authCallback(row) { if (!row) { return bot.sendMessage("Sorry you're not registered. Type /register to register."); } else { // if (!row.isCinnamonResident) { linkText += "Check your NUS library account:\n" + "https://linc.nus.edu.sg/patroninfo/\n\n"; // } // if (row.isCinnamonResident) { linkText += "Check the USP reading room catalogue:\n" + "https://myaces.nus.edu.sg/libms_isis/login.jsp\n\n" + "Check your meal credits:\n" + "https://bit.ly/hungrycinnamon\n\n" + "Report faults in Cinnamon:\n" + "https://bit.ly/faultycinnamon\n\n" + "Check your air-con credits:\n" + "https://bit.ly/chillycinnamon"; // } } bot.sendMessage(chatId, linkText, { disable_web_page_preview: true }); } auth.isCinnamonResident(chatId, authCallback); } module.exports = { start_feedback, continue_feedback, done_feedback, help, getLinks };
JavaScript
0.0126
@@ -2564,16 +2564,24 @@ Message( +chatId, %22Sorry y
0494a8e406453f01a4ba67aab4c3cabe8fad87d1
exit on core:cancel
lib/mleh.js
lib/mleh.js
'use babel'; import {CompositeDisposable} from 'atom'; import MlehView from './mleh-view'; export default { activate(state) { this.mleh = new MlehView(); this.mleh.createPanel(); console.log(this.mleh.contentContainer); this.mleh.contentContainer.style.position = "relative"; this.mleh.contentContainer.style.bottom = "0px"; // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable this.subscriptions = new CompositeDisposable(); // Register command that toggles this view this.subscriptions.add(atom.commands.add('atom-workspace', { 'mleh:toggle': () => this.toggle() })); this.subscriptions.add(atom.commands.add('.mleh', { 'mleh:move-cursor-down': () => this.mleh.moveCursorDown(), 'mleh:move-cursor-up': () => this.mleh.moveCursorUp() })); this.mleh.onDidClickOutside(::this.detach); }, deactivate() { if (this.mleh) { this.mleh.destroy(); } }, detach() { this.mleh.destroy(); }, toggle() { this.mleh.toggle(); } }
JavaScript
0.000002
@@ -834,16 +834,58 @@ rsorUp() +,%0A 'core:cancel': () =%3E this.detach() %0A %7D))
ac8324ffb09ac13cb060085c78fa0a0c796b053c
use prototype methods
promise.js
promise.js
function Promise(worker) { this.onResolve = undefined; this.onReject = undefined; this.result = undefined; this.state = 'pending'; this.resolve = function(result) { this.result = result; this.state = 'resolved'; if (this.onResolve) this.onResolve(result); } this.reject = function(result) { this.result = result; this.state = 'rejected'; if (this.onReject) this.onReject(result); } this.then = function(onResolve, onReject) { if (this.state === 'resolved') onResolve(this.result); else if (this.state === 'rejected') onReject(this.result); else if (this.state === 'pending') { this.onResolve = onResolve; this.onReject = onReject; } } worker(this.resolve.bind(this), this.reject.bind(this)); } module.exports = function(worker) { return new Promise(worker); }
JavaScript
0.000001
@@ -137,24 +137,31 @@ ding';%0D%0A%0D%0A +worker( this.resolve @@ -160,16 +160,85 @@ .resolve +.bind(this), this.reject.bind(this));%0D%0A%7D%0D%0A%0D%0APromise.prototype.resolve = funct @@ -246,34 +246,32 @@ on(result) %7B%0D%0A - - this.result = re @@ -269,34 +269,32 @@ sult = result;%0D%0A - this.state = ' @@ -299,34 +299,32 @@ 'resolved';%0D%0A - - if (this.onResol @@ -328,18 +328,16 @@ solve)%0D%0A - this @@ -357,29 +357,38 @@ sult);%0D%0A - %7D%0D%0A%0D%0A - this +Promise.prototype .reject @@ -409,18 +409,16 @@ ult) %7B%0D%0A - this.r @@ -432,26 +432,24 @@ result;%0D%0A - - this.state = @@ -462,18 +462,16 @@ cted';%0D%0A - if (th @@ -484,26 +484,24 @@ eject)%0D%0A - this.onRejec @@ -516,21 +516,30 @@ );%0D%0A - %7D%0D%0A%0D%0A - this +Promise.prototype .the @@ -575,18 +575,16 @@ ect) %7B%0D%0A - if (th @@ -609,26 +609,24 @@ lved')%0D%0A - onResolve(th @@ -632,34 +632,32 @@ his.result);%0D%0A - - else if (this.st @@ -681,18 +681,16 @@ ')%0D%0A - onReject @@ -707,18 +707,16 @@ lt);%0D%0A - - else if @@ -743,18 +743,16 @@ ding')%0D%0A - %7B%0D%0A @@ -748,26 +748,24 @@ )%0D%0A %7B%0D%0A - this.onResol @@ -781,18 +781,16 @@ solve;%0D%0A - this @@ -816,85 +816,14 @@ t;%0D%0A - %7D%0D%0A - %7D%0D%0A%0D%0A worker(this.resolve.bind(this), this.reject.bind(this));%0D%0A%7D%0D%0A +%7D %0D%0A%0D%0A
27bae7e1ae0392502fa338ac73d1824fa6469ffb
add nomralize css to core.css
src/layouts/CoreLayout/CoreLayout.js
src/layouts/CoreLayout/CoreLayout.js
import React from 'react' import Header from '../../components/Header' import Navbar from '../../components/Navbar' import './CoreLayout.css' import '../../styles/core.css' import '~normalize.css/normalize'; export const CoreLayout = ({ children }) => ( <div className='container'> <Header /> <Navbar /> <div className='core-layout__viewport'> {children} </div> </div> ) CoreLayout.propTypes = { children : React.PropTypes.element.isRequired } export default CoreLayout
JavaScript
0.000003
@@ -169,43 +169,8 @@ css' -%0Aimport '~normalize.css/normalize'; %0A%0Aex
5470972f6a61111da661b0092d71645751bf1259
Update devtools injection
src/renderers/native/ReactNative/ReactNative.js
src/renderers/native/ReactNative/ReactNative.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNative * @flow */ 'use strict'; // Require ReactNativeDefaultInjection first for its side effects of setting up // the JS environment var ReactNativeDefaultInjection = require('ReactNativeDefaultInjection'); var ReactCurrentOwner = require('ReactCurrentOwner'); var ReactElement = require('ReactElement'); var ReactInstanceHandles = require('ReactInstanceHandles'); var ReactNativeMount = require('ReactNativeMount'); var ReactUpdates = require('ReactUpdates'); var findNodeHandle = require('findNodeHandle'); ReactNativeDefaultInjection.inject(); var render = function( element: ReactElement, mountInto: number, callback?: ?(() => void) ): ?ReactComponent { return ReactNativeMount.renderComponent(element, mountInto, callback); }; var ReactNative = { hasReactNativeInitialized: false, findNodeHandle: findNodeHandle, render: render, unmountComponentAtNode: ReactNativeMount.unmountComponentAtNode, /* eslint-disable camelcase */ unstable_batchedUpdates: ReactUpdates.batchedUpdates, /* eslint-enable camelcase */ unmountComponentAtNodeAndRemoveContainer: ReactNativeMount.unmountComponentAtNodeAndRemoveContainer, // Deprecations (remove for 0.13) renderComponent: function( element: ReactElement, mountInto: number, callback?: ?(() => void) ): ?ReactComponent { warning('Use React.render instead of React.renderComponent'); return ReactNative.render(element, mountInto, callback); }, }; // Inject the runtime into a devtools global hook regardless of browser. // Allows for debugging when the hook is injected on the page. /* globals __REACT_DEVTOOLS_GLOBAL_HOOK__ */ if ( typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ CurrentOwner: ReactCurrentOwner, InstanceHandles: ReactInstanceHandles, Mount: ReactNativeMount, Reconciler: require('ReactReconciler'), TextComponent: require('ReactNativeTextComponent'), }); } module.exports = ReactNative;
JavaScript
0
@@ -462,16 +462,84 @@ ronment%0A +var ReactNativeComponentTree = require('ReactNativeComponentTree');%0A var Reac @@ -2208,81 +2208,516 @@ C -urrentOwner: ReactCurrentOwner,%0A InstanceHandles: ReactInstanceHandles +omponentTree: %7B%0A getClosestInstanceFromNode: function(node) %7B%0A return ReactNativeComponentTree.getClosestInstanceFromNode(node);%0A %7D,%0A getNodeFromInstance: function(inst) %7B%0A // inst is an internal instance (but could be a composite)%0A while (inst._renderedComponent) %7B%0A inst = inst._renderedComponent;%0A %7D%0A if (inst) %7B%0A return ReactNativeComponentTree.getNodeFromInstance(inst);%0A %7D else %7B%0A return null;%0A %7D%0A %7D,%0A %7D ,%0A @@ -2791,64 +2791,8 @@ '),%0A - TextComponent: require('ReactNativeTextComponent'),%0A %7D)
a62a09e67e324964467f7c447a722e3a8ba7aa17
Change mongo connection error message
packages/strapi-hook-mongoose/lib/index.js
packages/strapi-hook-mongoose/lib/index.js
'use strict'; /** * Module dependencies */ // Public node modules. const path = require('path'); const fs = require('fs'); const url = require('url'); const _ = require('lodash'); const mongoose = require('mongoose'); require('mongoose-long')(mongoose); const Mongoose = mongoose.Mongoose; const relations = require('./relations'); const buildQuery = require('./buildQuery'); const getQueryParams = require('./get-query-params'); const mountModels = require('./mount-models'); const queries = require('./queries'); /** * Mongoose hook */ const defaults = { defaultConnection: 'default', host: 'localhost', port: 27017, database: 'strapi', authenticationDatabase: '', ssl: false, debug: false, }; const isMongooseConnection = ({ connector }) => connector === 'strapi-hook-mongoose'; module.exports = function(strapi) { function initialize() { const { connections } = strapi.config; const connectionsPromises = Object.keys(connections) .filter(key => isMongooseConnection(connections[key])) .map(async connectionName => { const connection = connections[connectionName]; const instance = new Mongoose(); _.defaults(connection.settings, strapi.config.hook.settings.mongoose); const { uri, host, port, username, password, database, srv, } = connection.settings; const uriOptions = uri ? url.parse(uri, true).query : {}; const { authenticationDatabase, ssl, debug } = _.defaults( connection.options, uriOptions, strapi.config.hook.settings.mongoose ); const isSrv = srv === true || srv === 'true'; // Connect to mongo database const connectOptions = {}; if (!_.isEmpty(username)) { connectOptions.user = username; if (!_.isEmpty(password)) { connectOptions.pass = password; } } if (!_.isEmpty(authenticationDatabase)) { connectOptions.authSource = authenticationDatabase; } connectOptions.ssl = ssl === true || ssl === 'true'; connectOptions.useNewUrlParser = true; connectOptions.dbName = database; connectOptions.useCreateIndex = true; try { /* FIXME: for now, mongoose doesn't support srv auth except the way including user/pass in URI. * https://github.com/Automattic/mongoose/issues/6881 */ await instance.connect( uri || `mongodb${isSrv ? '+srv' : ''}://${username}:${password}@${host}${ !isSrv ? ':' + port : '' }/`, connectOptions ); } catch ({ message }) { const errMsg = message.includes(`:${port}`) ? 'Make sure your MongoDB database is running...' : message; throw new Error(errMsg); } const initFunctionPath = path.resolve( strapi.config.appPath, 'config', 'functions', 'mongoose.js' ); if (fs.existsSync(initFunctionPath)) { require(initFunctionPath)(instance, connection); } instance.set('debug', debug === true || debug === 'true'); instance.set('useFindAndModify', false); const ctx = { instance, connection, }; return Promise.all([ mountGroups(connectionName, ctx), mountApis(connectionName, ctx), mountAdmin(connectionName, ctx), mountPlugins(connectionName, ctx), ]); }); return Promise.all(connectionsPromises); } function mountGroups(connectionName, ctx) { const options = { models: _.pickBy( strapi.groups, ({ connection }) => connection === connectionName ), target: strapi.groups, plugin: false, }; return mountModels(options, ctx); } function mountApis(connectionName, ctx) { const options = { models: _.pickBy( strapi.models, ({ connection }) => connection === connectionName ), target: strapi.models, plugin: false, }; return mountModels(options, ctx); } function mountAdmin(connectionName, ctx) { const options = { models: _.pickBy( strapi.admin.models, ({ connection }) => connection === connectionName ), target: strapi.admin.models, plugin: false, }; return mountModels(options, ctx); } function mountPlugins(connectionName, ctx) { return Promise.all( Object.keys(strapi.plugins).map(name => { const plugin = strapi.plugins[name]; return mountModels( { models: _.pickBy( plugin.models, ({ connection }) => connection === connectionName ), target: plugin.models, plugin: name, }, ctx ); }) ); } return { defaults, initialize, getQueryParams, buildQuery, queries, ...relations, }; };
JavaScript
0
@@ -2730,19 +2730,13 @@ ch ( -%7B message %7D +error ) %7B%0A @@ -2758,80 +2758,64 @@ err -Msg = message.includes(%60:$%7Bport%7D%60)%0A ? 'Make sure your + = new Error(%0A %60Error connecting to the Mongo -DB dat @@ -2823,81 +2823,88 @@ base - is running...'%0A : message;%0A%0A throw new Error(errMsg) +. $%7Berror.message%7D%60%0A );%0A delete err.stack;%0A throw err ;%0A
6d52b3eda020367a16c6315835d3cf23d19fc9b8
add .vy to find_contracts pattern
packages/truffle-contract-sources/index.js
packages/truffle-contract-sources/index.js
const debug = require("debug")("contract-sources"); const path = require("path"); const glob = require("glob"); const DEFAULT_PATTERN = "**/*.sol"; module.exports = function(pattern, callback) { // pattern is either a directory (contracts directory), or an absolute path // with a glob expression if (!glob.hasMagic(pattern)) { pattern = path.join(pattern, DEFAULT_PATTERN); } const globOptions = { follow: true // follow symlinks }; glob(pattern, globOptions, callback); };
JavaScript
0
@@ -137,19 +137,24 @@ = %22**/*. +%7B sol +,vy%7D %22;%0A%0Amodu @@ -432,17 +432,16 @@ w: true - // follo
06b63e3920018c7940f99cc99f82263958ecbecc
Add JSONParser.js to ViewlessModels - working in node again
core/FOAMViewlessModels.js
core/FOAMViewlessModels.js
/** * @license * Copyright 2012 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. */ var files = [ 'stdlib', 'io', 'writer', 'socket', 'hash', 'base64', 'encodings', 'utf8', 'parse', 'event', 'JSONUtil', 'XMLUtil', 'context', 'FOAM', 'TemplateUtil', 'AbstractPrototype', 'ModelProto', 'mm1Model', 'mm2Property', 'mm3Types', 'mm4Method', 'mm5Misc', 'mm6Protobuf', 'mlang', 'QueryParser', 'search', 'async', 'visitor', 'dao', 'ClientDAO', 'diff', 'SplitDAO', 'index', 'experimental/protobufparser', 'experimental/protobuf', 'models', 'oauth' ];
JavaScript
0
@@ -799,16 +799,32 @@ 'FOAM',%0A + 'JSONParser',%0A 'Templ
893f42ab0017d4ffc030a8928b9836f329784ca1
Update init.js
packages/truffle-core/lib/commands/init.js
packages/truffle-core/lib/commands/init.js
var command = { command: 'init', description: 'Initialize new Ethereum project with example contracts and tests', builder: {}, run: function (options, done) { var Config = require("truffle-config"); var OS = require("os"); var UnboxCommand = require("./unbox"); var config = Config.default().with({ logger: console }); if (options._ && options._.length > 0) { config.logger.log( "Error: `truffle init` no longer accepts a project template name as an argument." ); config.logger.log(); config.logger.log( " - For an empty project, use `truffle init` with no arguments" + OS.EOL + " - Or, browse the Truffle Boxes at <http://truffleframework.com/boxes>!" ); process.exit(1); } // defer to `truffle unbox` command with "bare" box as arg var url = "https://github.com/truffle-box/bare-box.git"; options._ = [url]; UnboxCommand.run(options, done); } } module.exports = command;
JavaScript
0
@@ -59,16 +59,26 @@ ize new +and empty Ethereum @@ -89,41 +89,8 @@ ject - with example contracts and tests ',%0A
da87fd77470f8182c3603cfea7eb6e035d6b9e6c
Make warnings go out on stderr
lib/renderers/cli.js
lib/renderers/cli.js
var mout = require('mout'); var sizes = { tag: 10, // Tag max chars label: 23, // Label max chars sumup: 5 // Amount to sum when the label exceeds }; var tagColors = { 'warn': 'yellow', 'error': 'red', 'default': 'cyan' }; function isCompact() { return process.stdout.columns < 120; } function uncolor(str) { return str.replace(/\x1B\[\d+m/g, ''); } function renderTagPlusLabel(data) { var label; var length; var nrSpaces; var tag = data.tag; var tagColor = tagColors[data.level] || tagColors['default']; // If there's not enough space, print only the tag if (isCompact()) { return mout.string.rpad(tag, sizes.tag)[tagColor]; } label = data.origin + '#' + data.endpoint.target; length = tag.length + label.length + 1; nrSpaces = sizes.tag + sizes.label - length; // Ensure at least one space between the label and the tag if (nrSpaces < 1) { sizes.label = label.length + sizes.sumup; nrSpaces = sizes.tag + sizes.label - length; } return label.green + mout.string.repeat(' ', nrSpaces) + tag[tagColor]; } // ------------------------- var colorful = { begin: function () {}, end: function () {}, error: function (err) { var str; str = 'bower ' + renderTagPlusLabel(err) + ' ' + (err.code ? err.code + ' ,' : '') + err.message + '\n'; // Check if additional details were provided if (err.details) { str += err.details + '\n'; } // Print stack str += '\n' + err.stack + '\n'; this._write(process.stderr, str); }, data: function (data) { data.data = data.data || ''; this._write(process.stdout, 'bower ' + renderTagPlusLabel(data) + ' ' + data.data + '\n'); }, checkout: function (data) { if (isCompact()) { data.data = data.origin + '#' + data.data; } this.data(data); }, _write: function (channel, str) { channel.write(str); } }; // The colorless variant simply removes the colors from the write method var colorless = mout.object.mixIn({}, colorful, { _write: function (channel, str) { channel.write(uncolor(str)); } }); module.exports.colorful = colorful; module.exports.colorless = colorless;
JavaScript
0.000043
@@ -1708,34 +1708,167 @@ -this._write(process.stdout +var outputStream = process.stdout;%0A%0A if (data.level === 'warn') %7B%0A outputStream = process.stderr;%0A %7D%0A%0A this._write(outputStream , 'b
9d6e8bc8b30a3c4acb0b471967ddd2b59c2c2380
Fix style
src/lib/substituteVariantsAtRules.js
src/lib/substituteVariantsAtRules.js
import _ from 'lodash' import postcss from 'postcss' import selectorParser from 'postcss-selector-parser' import generateVariantFunction from '../util/generateVariantFunction' import prefixSelector from '../util/prefixSelector' function generatePseudoClassVariant(pseudoClass, selectorPrefix = pseudoClass) { return generateVariantFunction(({ modifySelectors, separator }) => { return modifySelectors(({ selector }) => { return selectorParser(selectors => { selectors.walkClasses(sel => { sel.value = `${selectorPrefix}${separator}${sel.value}` sel.parent.insertAfter(sel, selectorParser.pseudo({ value: `:${pseudoClass}` })) }) }).processSync(selector) }) }) } function ensureIncludesDefault(variants) { return variants.includes('default') ? variants : ['default', ...variants] } const defaultVariantGenerators = config => ({ default: generateVariantFunction(() => {}), 'group-hover': generateVariantFunction(({ modifySelectors, separator }) => { return modifySelectors(({ selector }) => { return selectorParser(selectors => { selectors.walkClasses(sel => { sel.value = `group-hover${separator}${sel.value}` sel.parent.insertBefore( sel, selectorParser().astSync(prefixSelector(config.prefix, '.group:hover ')) ) }) }).processSync(selector) }) }), 'group-focus': generateVariantFunction(({ modifySelectors, separator }) => { return modifySelectors(({ selector }) => { return selectorParser(selectors => { selectors.walkClasses(sel => { sel.value = `group-focus${separator}${sel.value}` sel.parent.insertBefore( sel, selectorParser().astSync(prefixSelector(config.prefix, '.group:focus ')) ) }) }).processSync(selector) }) }), hover: generatePseudoClassVariant('hover'), 'focus-within': generatePseudoClassVariant('focus-within'), focus: generatePseudoClassVariant('focus'), active: generatePseudoClassVariant('active'), visited: generatePseudoClassVariant('visited'), disabled: generatePseudoClassVariant('disabled'), first: generatePseudoClassVariant('first-child', 'first'), last: generatePseudoClassVariant('last-child', 'last'), odd: generatePseudoClassVariant('nth-child(odd)', 'odd'), even: generatePseudoClassVariant('nth-child(even)', 'even'), }) export default function(config, { variantGenerators: pluginVariantGenerators }) { return function(css) { const variantGenerators = { ...defaultVariantGenerators(config), ...pluginVariantGenerators, } css.walkAtRules('variants', atRule => { const variants = postcss.list.comma(atRule.params).filter(variant => variant !== '') if (variants.includes('responsive')) { const responsiveParent = postcss.atRule({ name: 'responsive' }) atRule.before(responsiveParent) responsiveParent.append(atRule) } _.forEach(_.without(ensureIncludesDefault(variants), 'responsive'), variant => { if (!variantGenerators[variant]) { throw new Error(`Your config mentions the "${variant}" variant, but "${variant}" doesn't appear to be a variant. Did you forget or misconfigure a plugin that supplies that variant?`); } variantGenerators[variant](atRule, config) }) atRule.remove() }) } }
JavaScript
0.000001
@@ -3146,16 +3146,29 @@ w Error( +%0A %60Your co @@ -3328,10 +3328,20 @@ nt?%60 +%0A ) -; %0A
631a9fdfd0f9fe3129c33c05b73acd941aba5d76
Update ip_blur.js
ip/ip_blur.js
ip/ip_blur.js
/* blur.js */ var ip_blur = function(src, r){ var dst = ip_create_img( src.width, src.height ); _ip_gauss_blur( src.data,dst.data, src.width,src.height, r ); return dst; } var _ip_guass_boxes = function(sigma, n){ var wIdeal = Math.sqrt((12*sigma*sigma/n)+1); // Ideal averaging filter width var wl = Math.floor(wIdeal); if(wl%2==0) wl--; var wu = wl+2; var mIdeal = (12*sigma*sigma - n*wl*wl - 4*n*wl - 3*n)/(-4*wl - 4); var m = Math.round(mIdeal); // var sigmaActual = Math.sqrt( (m*wl*wl + (n-m)*wu*wu - n)/12 ); var sizes = []; for(var i=0; i<n; i++) sizes.push(i<m?wl:wu); return sizes; } var _ip_gauss_blur = funcion(scl, tcl, w, h, r) { var bxs = _ip_gauss_boxes(r, 3); _ip_box_blur(scl, tcl, w, h, (bxs[0]-1)/2); _ip_box_blur(tcl, scl, w, h, (bxs[1]-1)/2); _ip_box_blur(scl, tcl, w, h, (bxs[2]-1)/2); } var _ip_box_blur = function(scl, tcl, w, h, r) { for(var i=0; i<scl.length; i++) tcl[i] = scl[i]; _ip_box_blur_h(tcl, scl, w, h, r); _ip_box_blur_t(scl, tcl, w, h, r); } var _ip_box_blur_h = function(scl, tcl, w, h, r) { var iarr = 1 / (r+r+1); for(var i=0; i<h; i++) { var ti = i*w, li = ti, ri = ti+r; var fv = scl[ti], lv = scl[ti+w-1], val = (r+1)*fv; for(var j=0; j<r; j++) val += scl[ti+j]; for(var j=0 ; j<=r ; j++) { val += scl[ri++] - fv ; tcl[ti++] = Math.round(val*iarr); } for(var j=r+1; j<w-r; j++) { val += scl[ri++] - scl[li++]; tcl[ti++] = Math.round(val*iarr); } for(var j=w-r; j<w ; j++) { val += lv - scl[li++]; tcl[ti++] = Math.round(val*iarr); } } } var _ip_box_blur_t = function(scl, tcl, w, h, r) { var iarr = 1 / (r+r+1); for(var i=0; i<w; i++) { var ti = i, li = ti, ri = ti+r*w; var fv = scl[ti], lv = scl[ti+w*(h-1)], val = (r+1)*fv; for(var j=0; j<r; j++) val += scl[ti+j*w]; for(var j=0 ; j<=r ; j++) { val += scl[ri] - fv ; tcl[ti] = Math.round(val*iarr); ri+=w; ti+=w; } for(var j=r+1; j<h-r; j++) { val += scl[ri] - scl[li]; tcl[ti] = Math.round(val*iarr); li+=w; ri+=w; ti+=w; } for(var j=h-r; j<h ; j++) { val += lv - scl[li]; tcl[ti] = Math.round(val*iarr); li+=w; ti+=w; } } }
JavaScript
0.000001
@@ -676,16 +676,17 @@ r = func +t ion(scl,
50f03e053a2b00833faa2e0e2dce1b45a9847d9d
Update test-script.js
src/test/test-script.js
src/test/test-script.js
/* global EpubMaker */ 'use strict'; window.runTest = function() { function f(title) { return function(value) { return { title: title, content: value }; }; } $.when( $.get('src/test/content-for-epub/header.html', null, null, 'text').then(f()), $.get('src/test/content-for-epub/preface.html', null, null, 'text').then(f('Preface')), $.get('src/test/content-for-epub/chapter1.html', null, null, 'text').then(f('It came from the desert')), $.get('src/test/content-for-epub/chapter2.html', null, null, 'text').then(f('No, it came from the Blue Lagoon')), $.get('src/test/content-for-epub/chapter3.html', null, null, 'text').then(f('Actually, it came from above')), $.get('src/test/content-for-epub/chapter4.html', null, null, 'text').then(f('It went back')), $.get('src/test/content-for-epub/rearnote-1.html', null, null, 'text').then(f('Note 1')), $.get('src/test/content-for-epub/rearnote-2.html', null, null, 'text').then(f('Note 2')) ).then(createTestEpub); }; function createTestEpub(coverImg, header, preface, ch1, ch2, ch3, ch4, rn1, rn2) { // FIXME add way to include custom jpg for cover new EpubMaker() .withUuid('github.com/bbottema/js-epub-maker::it-came-from::example-using-idpf-wasteland') .withTemplate('idpf-wasteland') .withAuthor('T. Est') .withLanguage('en-GB') .withModificationDate(new Date(2015, 8, 7)) .withRights({ description: 'This work is shared with the public using the Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0) license.', license: 'http://creativecommons.org/licenses/by-sa/3.0/' }) .withAttributionUrl('https://github.com/bbottema/js-epub-maker') .withCover('src/test/content-for-epub/js-epub-maker-cover.jpg', { license: 'http://creativecommons.org/licenses/by-sa/3.0/', attributionUrl: 'http://www.webestools.com/web20-title-generator-logo-title-maker-online-web20-effect-reflect-free-photoshop.html' }) .withTitle('It Came From... [Example Using Waste Land Template]') .withSection(new EpubMaker.Section('frontmatter', 'frontmatter', { title: 'Title page' }, false, true) .withSubSection(new EpubMaker.Section('titlepage', 'manuscript-header', header, false, false)) ) .withSection(new EpubMaker.Section('bodymatter', 'bodymatter', { title: 'Start of the story' }, false, true) .withSubSection(new EpubMaker.Section(null, 'preface', preface, true, false)) .withSubSection(new EpubMaker.Section(null, 'part-1', { title: 'Part 1' }, true, false) .withSubSection(new EpubMaker.Section(null, 'chapter-1', ch1, true, false)) .withSubSection(new EpubMaker.Section(null, 'chapter-2', ch2, true, false)) ) .withSubSection(new EpubMaker.Section(null, 'part-2', { title: 'Part 2' }, true, false) .withSubSection(new EpubMaker.Section(null, 'chapter-3', ch3, true, false)) .withSubSection(new EpubMaker.Section(null, 'chapter-4', ch4, true, false)) ) ) .withSection(new EpubMaker.Section('backmatter', 'backmatter', { title: 'Notes and rest' }, false, true) .withSubSection(new EpubMaker.Section('rearnotes', 'rear-notes', { title: 'Notes on "It Came From"' }, true, false) .withSubSection(new EpubMaker.Section('rearnote', 'rearnote-1', rn1, false, false)) .withSubSection(new EpubMaker.Section('rearnote', 'rearnote-2', rn2, false, false)) ) ) .downloadEpub(); }
JavaScript
0.000001
@@ -1136,61 +1136,8 @@ ) %7B%0A - // FIXME add way to include custom jpg for cover%0A @@ -3603,12 +3603,13 @@ oadEpub();%0A%7D +%0A
737c2872ef21f973dd265031764631515d6ed716
Fix typo in evented mixin.
packages/ember-runtime/lib/mixins/evented.js
packages/ember-runtime/lib/mixins/evented.js
/** @module ember @submodule ember-runtime */ /** This mixin allows for Ember objects to subscribe to and emit events. ```javascript App.Person = Ember.Object.extend(Ember.Evented, { greet: function() { // ... this.trigger('greet'); } }); var person = App.Person.create(); person.on('greet', function() { console.log('Our person has greeted'); }); person.greet(); // outputs: 'Our person has greeted' ``` @class Evented @namespace Ember @extends Ember.Mixin */ Ember.Evented = Ember.Mixin.create({ /** Subscribes to a named event with given function. ```javascript person.on('didLoad', function() { // fired once the person has loaded }); ``` An optional target can be passed in as the 2nd argument that will be set as the "this" for the callback. This is a good way to give your function access to the object triggering the event. When the target parameter is used the callback becomes the third argument. @method on @param {String} name The name of the event @param {Object} [target] The "this" binding for the callback @param {Function} method The callback to execute */ on: function(name, target, method) { Ember.addListener(this, name, target, method); }, /** Subscribes a function to a named event and then cancels the subscription after the first time the event is triggered. It is good to use ``one`` when you only care about the first time an event has taken place. This function takes an optional 2nd argument that will become the "this" value for the callback. If this argument is passed then the 3rd argument becomes the function. @method one @param {String} name The name of the event @param {Object} [target] The "this" binding for the callback @param {Function} method The callback to execute */ one: function(name, target, method) { if (!method) { method = target; target = null; } Ember.addListener(this, name, target, method, true); }, /** Triggers a named event for the object. Any additional arguments will be passed as parameters to the functions that are subscribed to the event. ```javascript person.on('didEat', food) { console.log('person ate some ' + food); }); person.trigger('didEat', 'broccoli'); // outputs: person ate some broccoli ``` @method trigger @param {String} name The name of the event @param {Object...} args Optional arguments to pass on */ trigger: function(name) { var args = [], i, l; for (i = 1, l = arguments.length; i < l; i++) { args.push(arguments[i]); } Ember.sendEvent(this, name, args); }, fire: function(name) { Ember.deprecate("Ember.Evented#fire() has been deprecated in favor of trigger() for compatibility with jQuery. It will be removed in 1.0. Please update your code to call trigger() instead."); this.trigger.apply(this, arguments); }, /** Cancels subscription for give name, target, and method. @method off @param {String} name The name of the event @param {Object} target The target of the subscription @param {Function} method The function of the subscription */ off: function(name, target, method) { Ember.removeListener(this, name, target, method); }, /** Checks to see if object has any subscriptions for named event. @method has @param {String} name The name of the event @return {Boolean} does the object have a subscription for event */ has: function(name) { return Ember.hasListeners(this, name); } });
JavaScript
0.000002
@@ -2247,16 +2247,25 @@ idEat', +function( food) %7B%0A
601fba9ef7de4726fdbc010913d86f520dcacbc9
fix Scrollable test typos, and make sure to limit actions to container div
tests/unit/Scrollable.js
tests/unit/Scrollable.js
define([ "dcl/dcl", "intern!object", "intern/chai!assert", "requirejs-dplugins/jquery!attributes/classes", // hasClass() "delite/register", "delite/Widget", "delite/Scrollable", "./resources/ScrollableTestContainer", "./resources/Scrollable-shared" ], function (dcl, registerSuite, assert, $, register, Widget, Scrollable, ScrollableTestContainer, ScrollableSharedTests) { var container, MyScrollableWidget, MyScrollableTestContainer; /*jshint multistr: true */ var html = "<test-scrollable-container id='sc1' \ style='position: absolute; width: 200px; height: 200px;'> \ <div id='sc1content' style='width: 2000px; height: 2000px;'></div> \ </test-scrollable-container>\ <my-scrolable-test-container id='mysc1'> \ </my-scrolable-test-container> \ <test-scrollable-container scrollDirection='none' id='sc2'> \ </test-scrollable-container>"; registerSuite({ name: "delite/Scrollable", setup: function () { container = document.createElement("div"); document.body.appendChild(container); MyScrollableWidget = register("my-scrollable-widget", [HTMLElement, Widget, Scrollable], { // to be able to check that scrollableNode is already set to the // correct value when refreshRendering() gets called. scrollableNodeInRefreshRendering: null, refreshRendering: function () { // Store the value at the moment refreshRendering() was called, // such that the test can later check it. this.scrollableNodeInRefreshRendering = this.scrollableNode; } }); }, "Default CSS": function () { var w = (new MyScrollableWidget({id: "mysw"})).placeAt(container); w.startup(); w.deliver(); assert.strictEqual(w.scrollableNode, w, "The scrollableNode should be the widget itself!"); assert.strictEqual(w.scrollableNodeInRefreshRendering, w.scrollableNode, "The scrollableNode should been already set to 'this' when refreshRendering() was called!"); // The CSS class d-scrollable is expected to be added by the mixin delite/Scrollable assert.isTrue($(w.scrollableNode).hasClass("d-scrollable"), "Expecting d-scrollable CSS class!"); }, "scrollableNode property": function () { // Test case for a custom widget which sets the scrollableNode in its render(). var ScrollableWithCustomScrollableNode = register("my-scrollable-widget-sn", [HTMLElement, Widget, Scrollable], { // to be able to check that scrollableNode isn't changed afterwards, // store here the instance of custom node set in render(). createdScrollableNode: null, render: dcl.superCall(function (sup) { return function () { this.scrollableNode = document.createElement("div"); this.createdScrollableNode = this.scrollableNode; this.appendChild(this.scrollableNode); sup.apply(this, arguments); }; }) }); var w = (new ScrollableWithCustomScrollableNode()).placeAt(container); w.startup(); w.deliver(); assert.strictEqual(w.scrollableNode, w.createdScrollableNode, "The scrollableNode property has changed since it was set in render!"); // Test that the CSS class d-scrollable has been added by the mixin delite/Scrollable // on the custom scrollableNode. assert.isTrue($(w.scrollableNode).hasClass("d-scrollable"), "Expecting d-scrollable CSS class on my-scrollable-widget-sn!"); }, // The remaining of the API of the mixin delite/Scrollable is tested // in tests/ScrollableTestContainer-markup and tests/ScrollableTestContainer-prog // via an ad-hoc widget (tests/ScrollableTestContainer) which uses the mixin. teardown: function () { container.parentNode.removeChild(container); } }); // Markup use-case var suite = { name: "delite/Scrollable: ScrollableTestContainer in markup", setup: function () { container = document.createElement("div"); document.body.appendChild(container); container.innerHTML = html; register("my-scrolable-test-container", [ScrollableTestContainer], {}); register.parse(); }, teardown: function () { container.parentNode.removeChild(container); } }; dcl.mix(suite, ScrollableSharedTests.testCases); registerSuite(suite); // Programatic creation suite = { name: "delite/Scrollable: ScrollableTestContainer programatically", setup: function () { container = document.createElement("div"); document.body.appendChild(container); MyScrollableTestContainer = register("my-sc-prog", [ScrollableTestContainer], {}); var w = new ScrollableTestContainer({ id: "sc1" }); w.style.position = "absolute"; w.style.width = "200px"; w.style.height = "200px"; container.appendChild(w); w.startup(); var innerContent = document.createElement("div"); innerContent.id = "sc1content"; innerContent.style.width = "2000px"; innerContent.style.height = "2000px"; w.appendChild(innerContent); w.startup(); w = new MyScrollableTestContainer({ id: "mysc1" }); container.appendChild(w); w.startup(); w = new ScrollableTestContainer({ id: "sc2" }); w.scrollDirection = "none"; container.appendChild(w); w.startup(); }, teardown: function () { container.parentNode.removeChild(container); } }; dcl.mix(suite, ScrollableSharedTests.testCases); registerSuite(suite); });
JavaScript
0
@@ -691,32 +691,33 @@ r%3E%5C%0A%09%09%09%3Cmy-scrol +l able-test-contai @@ -739,32 +739,33 @@ %5C%0A%09%09%09%3C/my-scrol +l able-test-contai @@ -3942,16 +3942,17 @@ my-scrol +l able-tes @@ -4015,16 +4015,25 @@ r.parse( +container );%0A%09%09%7D,%0A @@ -4197,24 +4197,25 @@ %0A%09// Program +m atic creatio @@ -4215,17 +4215,16 @@ creation - %0A%0A%09suite
62a180bafccf31ee24da282d53c37cd1c733644b
Add req and res as arguments to .put's callback
lib/restifyclient.js
lib/restifyclient.js
/* * Copyright (c) 2012, Joyent, Inc. All rights reserved. * * Generic restify client with basic auth */ var restify = require('restify'); /** * Constructor * * Note that in options you can pass in any parameters that the restify * RestClient constructor takes (for example retry/backoff settings). * * @param {Object} options * - username {String} username for basic auth. * - password {String} password for basic auth. * - url {String} NAPI url. * - ... any other options allowed to `restify.createJsonClient` * */ function RestifyClient(options) { if (!options) throw new TypeError('options required'); if (!options.url) throw new TypeError('options.url (String) is required'); this.client = restify.createJsonClient(options); if (options.username && options.password) this.client.basicAuth(options.username, options.password); } /** * Generic GET method * * Note that you can call this with or without params, * eg: f(path, cb) or f(path, params, cb) * * @param {String} path : the path to get * @param {Object} params : the parameters to filter on (optional) * @param {Function} callback : of the form f(err, obj) or * f(err, obj, req, res) if you need the extra data */ RestifyClient.prototype.get = function (path, params, callback) { if (!path) throw new TypeError('path is required'); if (!params) throw new TypeError('callback (Function) is required'); if (typeof (params) !== 'function' && typeof (params) !== 'object') throw new TypeError('params must be an object'); // Allow calling .get(path, callback): if (typeof (params) === 'function') callback = params; if (!callback || typeof (callback) !== 'function') throw new TypeError('callback (Function) is required'); var getParams = { path: path }; if (typeof (params) === 'object' && Object.keys(params).length !== 0) getParams.query = params; return this.client.get(getParams, function (err, req, res, obj) { if (err) { return callback(err, null, req, res); } return callback(null, obj, req, res); }); }; /** * Generic PUT method * * @param {String} path : the path to put * @param {Object} params : the parameters to put * @param {Function} callback : of the form f(err, obj) or * f(err, obj, req, res) if you need the extra data */ RestifyClient.prototype.put = function (path, params, callback) { if (!path) throw new TypeError('path is required'); if (!params || typeof (params) !== 'object') throw new TypeError('params is required (object)'); if (!callback || typeof (callback) !== 'function') throw new TypeError('callback (Function) is required'); return this.client.put(path, params, function (err, req, res, obj) { if (err) { return callback(err); } return callback(null, obj); }); }; /** * Generic POST method * * @param {String} path : the path to post * @param {Object} params : the parameters to post * @param {Function} callback : of the form f(err, obj) or * f(err, obj, req, res) if you need the extra data */ RestifyClient.prototype.post = function (path, params, callback) { if (!path) throw new TypeError('path is required'); if (!params || typeof (params) !== 'object') throw new TypeError('params is required (object)'); if (!callback || typeof (callback) !== 'function') throw new TypeError('callback (Function) is required'); return this.client.post(path, params, function (err, req, res, obj) { if (err) { return callback(err, null, req, res); } return callback(null, obj, req, res); }); }; /** * Generic DELETE method * * @param {String} path : the path to post * @param {Function} callback : of the form f(err, obj) or * f(err, obj, req, res) if you need the extra data */ RestifyClient.prototype.del = function (path, params, callback) { if (!path) throw new TypeError('path is required'); if (!params) throw new TypeError('callback (Function) is required'); if (typeof (params) !== 'function' && typeof (params) !== 'object') throw new TypeError('params must be an object'); // Allow calling .del(path, callback): if (typeof (params) === 'function') callback = params; if (!callback || typeof (callback) !== 'function') throw new TypeError('callback (Function) is required'); var getParams = { path: path }; if (typeof (params) === 'object' && Object.keys(params).length !== 0) getParams.query = params; return this.client.del(getParams, function (err, req, res, obj) { if (err) { return callback(err, null, req, res); } return callback(null, obj, req, res); }); }; module.exports = RestifyClient;
JavaScript
0
@@ -2956,16 +2956,26 @@ ull, obj +, req, res );%0A %7D
70fbaf1ae0cc3765ab4b876f48e068064dfe6123
Update scionWrapper.js
lib/scionWrapper.js
lib/scionWrapper.js
(function(global, factory) { if (typeof module === 'object') { module.exports = factory(); } else if (typeof define === 'function' && define.amd) { define(factory); } else { window.scionWrapper = factory(); } })(this, function() { // console.log("load: util.js"); return function init(_scion) { var _instance = { _scion: _scion, _states: {}, _events: {}, _transitions: {}, _startState: undefined, _id: undefined, /** * Start scxml interpreter */ start: function() { _scion.start(); }, /** * Check if state equals initial state * @param {String} stateId * @return {Boolean} */ isInitialDefaultState: function(stateId) { return stateId === _instance._startState; }, /** * Flag to ignore the execution of the content inside the script tag */ ignoreScript: function() { _scion.opts.retrace = true; }, /** * Flag to evaluate the content inside the script tag */ evaluateScript: function() { _scion.opts.retrace = false; }, /** * Set a global variable to the scxml model * @param {String} name Name of variable * @param {Object} object Value of the variable */ setDataModel: function(name, object) { _scion._datamodel[name].set(object); }, /** * Set a global variable to the scxml model * @param {String} name Name of variable * @param {Object} object Value of the variable */ getDataModel: function(name, object) { _scion._datamodel[name].get(); }, /** * Injects code inside the script tag * @param {String} stateId * @param {Integer} getData * @param {Integer} setData * @param {Object} events * @param {Integer} raise */ execScript: function(stateId, data, when) { var actionId; if (when !== 'onexit') { actionId = _scion.model.states.filter(function(state) { return state.id === stateId; })[0].onentry; } else { actionId = _scion.model.states.filter(function(state) { return state.id === stateId; })[0].onexit; } _scion._actions[actionId](0, 0, {0: data}, 0); }, /** * Executes a transition * @param {String} event * @param {Object} data Injects data to the scxml */ gen: function(event, data) { _scion.gen(event, data); }, /** * Name of the state * @param {String} id * @return {String} name */ getStateNameById: function(id){ return _instance._states[id].name; }, /** * Type of the state * @param {String} id * @return {String} type */ getStateTypeById: function(id){ return _instance._states[id].type; }, /** * Atomic states of the current configuration * @return {Array} of state names */ getStateName: function() { var names = _scion.getConfiguration().map(function(id){ return _instance._states[id] ? _instance._states[id].name : id; }); return names[0]; }, /** * Compound states of the current configuration * @return {Array} of state names */ getActiveStatesName: function() { return _scion.getFullConfiguration().map(function(id){ return _instance._states[id] ? _instance._states[id].name : id; }); }, /** * Atomic states of the current configuration * @return {Array} of state ids */ getStateId: function() { return _scion.getConfiguration()[0]; }, /** * Compound states of the current configuration * @return {Array} of state ids */ getActiveStatesId: function() { return _scion.getFullConfiguration(); }, /** * Accessible events contained by the atomic states * @return {Array} */ getEvents: function() { var i, events = [], states = _scion.getConfiguration(); for (i = 0; i < states.length; i++) { events = events.concat(_instance._events[states[i]]); } return events; }, /** * Accessible events contained by the compound states * @return {Array} */ getActiveEvents: function() { var i, events = [], states = _scion.getFullConfiguration(); for (i = 0; i < states.length; i++) { events = events.concat(_instance._events[states[i]]); } return events; }, /** * Accessible states from atomic states given the current configuration * @return {Object} */ getTransitions: function() { var i, t, e, transitions = {}, states = _scion.getConfiguration(); for (i = 0; i < states.length; i++) { t = _instance._transitions[states[i]]; for (e in t) { transitions[e] = t[e]; } } return transitions; }, /** * Accessible states from compound states given the current configuration * @return {Object} */ getActiveTransitions: function() { var i, t, e, transitions = {}, states = _scion.getFullConfiguration(); for (i = 0; i < states.length; i++) { t = _instance._transitions[states[i]]; for (e in t) { transitions[e] = t[e]; } } return transitions; } }; (function(){ var events = [], transitions = {}, states = _scion.model.states, n, stateObj, transitionObjects, m, ev, targets, targetObject, t; // startState; _scion.start(); _instance._startState = _scion.getConfiguration()[0]; _instance._id = uuid(); // crawl all states, events and transitions for (n = 0; n < states.length; n++) { stateObj = states[n]; var id = stateObj.id; if (id.substr(0, 1) !== '$') _instance._states[id] = stateObj; transitionObjects = stateObj.transitions; for (m = 0; m < transitionObjects.length; m++) { targets = transitionObjects[m].targets; ev = transitionObjects[m].events; events = events.concat(ev); if (targets) { for (t = 0; t < targets.length; t++) { targetObject = targets[t]; if (typeof transitions[ev] === 'undefined') { transitions[ev] = targetObject.id; } else { var tmp = transitions[ev]; if (typeof tmp === 'string') { var a = []; a.push(targetObject.id); } else if (tmp instanceof Array) { transitions[ev].push(targetObject[ev]); } } } } else { transitions[ev] = stateObj.id; } } _instance._transitions[stateObj.id] = transitions; transitions = {}; _instance._events[stateObj.id] = events; events = []; } function uuid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } }()); return _instance; }; });
JavaScript
0
@@ -1956,32 +1956,24 @@ unction(name -, object ) %7B%0A
0ee2b1633caaf19542e9fde17e17d489545999a9
Use new crossorigin getter to determine which anchors to work on
lib/transforms/addRelNoopenerToBlankTargetAnchors.js
lib/transforms/addRelNoopenerToBlankTargetAnchors.js
module.exports = function (queryObj) { return function addRelNoopenerToBlankTargetAnchors(assetGraph) { var externalAnchors = assetGraph.findRelations({ type: 'HtmlAnchor', hrefType: 'absolute' // FIXME: also check that the relation is cross origin }, true).filter(function (relation) { return relation.node.getAttribute('target') === '_blank'; }); externalAnchors.forEach(function (relation) { var node = relation.node; var currentRel = node.getAttribute('rel'); if (typeof currentRel === 'string') { var rels = currentRel.split(' ').map(function (str) { return str.toLowerCase(); }); if (rels.indexOf('noopener') === -1) { node.setAttribute('rel', rels.concat('noopener').join(' ')); } } else { relation.node.setAttribute('rel', 'noopener'); } relation.from.markDirty(); }); }; };
JavaScript
0
@@ -24,16 +24,8 @@ on ( -queryObj ) %7B%0A @@ -198,95 +198,25 @@ -hrefType: 'absolute'%0A // FIXME: also check that the relation is cross origin +crossorigin: true %0A
bdec7e363be5b66eb7116a57e3370b99be370fec
Add keydown event to fix invalid() bug
javascript.js
javascript.js
'use strict'; //highlights the border red for invalid() //Set to global for resetBorder() var inputBorder = document.getElementById("chirps"); //Triggers event when user submits button from enter on keyboard $("#enterKeyboard").submit(function(event) { event.preventDefault(); submitButton(); }); function submitButton() { // Get number string from input field in html document var cricketStr = document.getElementById("chirps").value; // for invalid() and calculation() var submit = true; //answer message displays in calculation() or invalid() var answer = document.getElementById("answer"); function invalid() { if (cricketStr < 1 || cricketStr % 1 !== 0) { //highlights the input field red inputBorder.className = "redBorder"; answer.innerHTML = ""; submit = false; //will not perform calculation() return submit; } } //Converts cricket chirps to Fahrenheit or Celcius based off radio butten function calculation() { //Radio button for Fahrenheit var radioF = document.getElementById("F"); // Turns string into an integer for calculations var cricketNum = parseInt(cricketStr); // Calculation to turn chirps into degrees Fahrenheit var fTemp = cricketNum + 40; //Coversion of F to C, and rounded to the nearest 10th var cTempRounded = Math.round(((fTemp - 32) * .5556) * 10) / 10; //output variable text for calculation var message = "The crickets predict the temperature is about "; //checks if submit is true based on invalid() and if Fahrenheit is checked - the radio button's default if (submit === true && radioF.checked === true) { //Output of Fahrenheit calculation message += fTemp + "&deg;F"; answer.innerHTML = message; //checks if submit is true based on invalid() and if Fahrenheit is NOT checked (thus, it is Celsius) } else if (submit === true && radioF.checked !== true) { //output of Celsius calculation message += cTempRounded + "&deg;C";; answer.innerHTML = message; } } // Assigns an empty value to clear the input field after user clicks button function clearValueField() { document.getElementById("chirps").value = ""; } clearValueField(); invalid(); calculation(); } function resetBorder() { inputBorder.className = ""; }
JavaScript
0.000001
@@ -301,16 +301,82 @@ );%0A%7D);%0A%0A +$(%22#enterKeyboard%22).keydown(function() %7B%0A resetBorder();%0A%7D);%0A%0A%0A function
fd6c8da6139c4fde57d1a18c87b0a67cc8709e8e
Migrate expectAssertion to assert.throws
tests/unit/array-test.js
tests/unit/array-test.js
import Ember from 'ember'; import { module, test } from 'qunit'; import ArrayController from 'ember-legacy-controllers/array'; import expectAssertion from 'ember-dev/test-helper/assertion'; const { get, set } = Ember; module('ArrayController'); test('defaults its `model` to an empty array', function (assert) { var Controller = ArrayController.extend(); assert.deepEqual(Controller.create().get('model'), [], '`ArrayController` defaults its model to an empty array'); assert.equal(Controller.create().get('firstObject'), undefined, 'can fetch firstObject'); assert.equal(Controller.create().get('lastObject'), undefined, 'can fetch lastObject'); }); test('Ember.ArrayController length property works even if model was not set initially', function(assert) { var controller = ArrayController.create(); controller.pushObject('item'); assert.equal(controller.get('length'), 1); }); test('works properly when model is set to an Ember.A()', function(assert) { var controller = ArrayController.create(); set(controller, 'model', Ember.A(['red', 'green'])); assert.deepEqual(get(controller, 'model'), ['red', 'green'], 'can set model as an Ember.Array'); }); test('works properly when model is set to a plain array', function(assert) { var controller = ArrayController.create(); if (Ember.EXTEND_PROTOTYPES) { set(controller, 'model', ['red', 'green']); assert.deepEqual(get(controller, 'model'), ['red', 'green'], 'can set model as a plain array'); } else { assert.expect(0); expectAssertion(function() { set(controller, 'model', ['red', 'green']); }, /ArrayController expects `model` to implement the Ember.Array mixin. This can often be fixed by wrapping your model with `Ember\.A\(\)`./); } }); test('works properly when model is set to `null`', function(assert) { var controller = ArrayController.create(); set(controller, 'model', null); assert.equal(get(controller, 'model'), null, 'can set model to `null`'); set(controller, 'model', undefined); assert.equal(get(controller, 'model'), undefined, 'can set model to `undefined`'); set(controller, 'model', false); assert.equal(get(controller, 'model'), false, 'can set model to `undefined`'); });
JavaScript
0.000001
@@ -123,71 +123,8 @@ ay'; -%0Aimport expectAssertion from 'ember-dev/test-helper/assertion'; %0A%0Aco @@ -1441,38 +1441,14 @@ ert. -expect(0);%0A expectAssertion +throws (fun
9ff68fee1f667d2d1aec8ea5530257fe3f7f84c9
optimize storage
src/storage/database.js
src/storage/database.js
import {merge, pick} from 'lodash' const key = 'wukong' export function open(state = {}) { try { return merge({ user: { auth: { status: true }, preferences: { listenOnly: false, connection: 0, audioQuality: 2 } } }, JSON.parse(localStorage.getItem(key)), state) } catch (error) { return state } } export function save(state = {}) { try { localStorage.setItem(key, JSON.stringify(pick(state, [ 'user.preferences', 'song.playlist', 'player.volume' ]))) } catch (error) { localStorage.removeItem(key) } }
JavaScript
0.000001
@@ -12,16 +12,25 @@ ge, pick +, isEqual %7D from ' @@ -63,85 +63,45 @@ ng'%0A -%0Aexport function open(state +const data = %7B -%7D) %7B%0A try %7B%0A return merge( +%0A open: %7B%0A - user: %7B%0A @@ -92,26 +92,24 @@ user: %7B%0A - auth: @@ -118,18 +118,16 @@ - status: @@ -141,15 +141,11 @@ - %7D,%0A - @@ -169,18 +169,16 @@ - listenOn @@ -196,18 +196,16 @@ - connecti @@ -219,18 +219,16 @@ - audioQua @@ -244,26 +244,105 @@ + %7D%0A + %7D%0A - %7D%0A %7D +%7D,%0A save: %7B%7D%0A%7D%0A%0Aexport function open(state = %7B%7D) %7B%0A try %7B%0A return merge(data.open , JS @@ -480,49 +480,21 @@ -localStorage.setItem(key, JSON.stringify( +const data = pick @@ -580,18 +580,130 @@ '%0A %5D) -)) +%0A if (isEqual(data, data.save)) return%0A localStorage.setItem(key, JSON.stringify(data))%0A data.save = data %0A %7D cat
11a3bace81ea9af2d9f914fffe613ecf2d54c4dc
Add a GROUP server type into the database specification
src/tracker/savefile.js
src/tracker/savefile.js
/* * SAVEFILE STRUCTURE * ================== * * { * meta: { * users: { * <discord user id>: { * name: <user name> * }, ... * }, * * // the user index is an array of discord user ids, * // these indexes are used in the message objects to save space * userindex: [ * <discord user id>, ... * ], * * servers: [ * { * name: <server name>, * type: <"SERVER"|"DM"> * }, ... * ], * * channels: { * <discord channel id>: { * server: <server index in the meta.servers array>, * name: <channel name> * }, ... * } * }, * * data: { * <discord channel id>: { * <discord message id>: { * u: <user index of the sender>, * t: <message timestamp>, * m: <message content>, * f: <message flags>, // bit 1 = edited, bit 2 = has user mentions (omit for no flags), * e: [ // omit for no embeds * { * url: <embed url>, * type: <embed type> * }, ... * ], * a: [ // omit for no attachments * { * url: <attachment url> * }, ... * ] * }, ... * }, ... * } * } * * * TEMPORARY OBJECT STRUCTURE * ========================== * * { * userlookup: { * <discord user id>: <user index in the meta.userindex array> * } * } */ var SAVEFILE = function(parsedObj){ if (parsedObj){ this.meta = parsedObj.meta; this.meta.users = this.meta.users || {}; this.meta.userindex = this.meta.userindex || []; this.meta.servers = this.meta.servers || []; this.meta.channels = this.meta.channels || {}; this.data = parsedObj.data; } else{ this.meta = {}; this.meta.users = {}; this.meta.userindex = []; this.meta.servers = []; this.meta.channels = {}; this.data = {}; } this.tmp = {}; this.tmp.userlookup = {}; }; SAVEFILE.prototype.findOrRegisterUser = function(userId, userName){ if (!(userId in this.meta.users)){ this.meta.users[userId] = { name: userName }; this.meta.userindex.push(userId); return this.tmp.userlookup[userId] = this.meta.userindex.length-1; } else if (!(userId in this.tmp.userlookup)){ return this.tmp.userlookup[userId] = this.meta.userindex.findIndex(id => id == userId); } else{ return this.tmp.userlookup[userId]; } }; SAVEFILE.prototype.findOrRegisterServer = function(serverName, serverType){ var index = this.meta.servers.findIndex(server => server.name === serverName && server.type === serverType); if (index === -1){ this.meta.servers.push({ name: serverName, type: serverType }); return this.meta.servers.length-1; } else{ return index; } }; SAVEFILE.prototype.tryRegisterChannel = function(serverIndex, channelId, channelName){ if (!this.meta.servers[serverIndex]){ return undefined; } else if (channelId in this.meta.channels){ return false; } else{ this.meta.channels[channelId] = { server: serverIndex, name: channelName }; return true; } }; SAVEFILE.prototype.addMessage = function(channelId, messageId, messageObject){ var container = this.data[channelId] || (this.data[channelId] = {}); var wasUpdated = messageId in container; container[messageId] = messageObject; return wasUpdated; }; SAVEFILE.prototype.convertToMessageObject = function(discordMessage){ var obj = { u: this.findOrRegisterUser(discordMessage.author.id, discordMessage.author.username), t: +Date.parse(discordMessage.timestamp), m: discordMessage.content }; var flags = 0; if (discordMessage.edited_timestamp !== null){ flags |= 1; } if (discordMessage.mentions.length > 0){ flags |= 2; } if (flags !== 0){ obj.f = flags; } if (discordMessage.embeds.length > 0){ obj.e = discordMessage.embeds.map(embed => ({ url: embed.url, type: embed.type })); } if (discordMessage.attachments.length > 0){ obj.a = discordMessage.attachments.map(attachment => ({ url: attachment.url })); } return obj; }; SAVEFILE.prototype.addMessagesFromDiscord = function(channelId, discordMessageArray){ var wasUpdated = false; for(var discordMessage of discordMessageArray){ wasUpdated |= this.addMessage(channelId, discordMessage.id, this.convertToMessageObject(discordMessage)); } return wasUpdated; }; SAVEFILE.prototype.combineWith = function(obj){ for(var userId in obj.meta.users){ this.findOrRegisterUser(userId, obj.meta.users[userId].name); } for(var channelId in obj.meta.channels){ var oldServer = obj.meta.servers[obj.meta.channels[channelId].server]; var serverIndex = this.findOrRegisterServer(oldServer.name, oldServer.type); this.tryRegisterChannel(serverIndex, channelId, obj.meta.channels[channelId].name); } for(var channelId in obj.data){ for(var messageId in obj.data[channelId]){ this.addMessage(channelId, messageId, obj.data[channelId][messageId]); } } }; SAVEFILE.prototype.toJson = function(){ return JSON.stringify({ meta: this.meta, data: this.data }); };
JavaScript
0
@@ -447,16 +447,23 @@ ERVER%22%7C%22 +GROUP%22%7C DM%22%3E%0A *
66b1196c3c4f7439c4a0b2a58ba516d56943e426
revert jest-setup file back to original state
jest-setup.js
jest-setup.js
import Enzyme from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; Enzyme.configure({ adapter: new Adapter() });
JavaScript
0
@@ -115,8 +115,9 @@ er() %7D); +%0A
772a9f7785701cf6d560f67205f4526fb5f66972
Fix put function in client library
src/store/api/client.js
src/store/api/client.js
import superagent from 'superagent' const client = { get (path, callback) { superagent .get(path) .end((err, res) => { callback(err, res.body) }) }, post (path, data, callback) { superagent .post(path) .send(data) .end((err, res) => { callback(err, res.body) }) }, put (path, data, callback) { superagent .post(path) .send(data) .end((err, res) => { callback(err, res.body) }) }, del (path, callback) { superagent .del(path) .end((err, res) => { callback(err, res.body) }) } } export default client
JavaScript
0.000003
@@ -381,34 +381,33 @@ eragent%0A .p -os +u t(path)%0A .s
5d5908c3e497066ab7fac20dbfbdb43d410b4b1b
fix navigation to the next question on answer submission
public/app/services/utils/rgiQuestionSetSrvc.js
public/app/services/utils/rgiQuestionSetSrvc.js
'use strict'; angular.module('app').factory('rgiQuestionSetSrvc', function (rgiUtilsSrvc) { var answers = []; return { isAnyQuestionRemaining: function(answer) { return answer.question_order !== answers.length; }, getNextQuestionId: function(answer) { return String(rgiUtilsSrvc.zeroFill((answer.question_order + 1), 3)); }, setAnswers: function(answersData) { answers = answersData; } }; });
JavaScript
0.988665
@@ -70,16 +70,33 @@ nction ( +rgiQuestionSrvc, rgiUtils @@ -127,134 +127,1856 @@ = %5B%5D -;%0A%0A return %7B%0A isAnyQuestionRemaining: function(answer) %7B%0A return answer.question_order !== answers.length +, questions;%0A%0A rgiQuestionSrvc.query(%7Bassessment_ID: 'base'%7D, function (questionList) %7B%0A questions = questionList;%0A %7D);%0A%0A var getNextQuestion = function(answer) %7B%0A var linkedQuestion = getLinkedQuestion(getQuestionOption(answer));%0A return linkedQuestion === undefined ? getRootQuestions()%5B0%5D : linkedQuestion;%0A %7D;%0A%0A var getLinkedQuestion = function(option) %7B%0A var foundQuestion;%0A%0A questions.forEach(function(question) %7B%0A if(question.linkedOption === option._id) %7B%0A foundQuestion = question;%0A %7D%0A %7D);%0A%0A return foundQuestion;%0A %7D;%0A%0A var getQuestionOption = function(answer) %7B%0A var foundOption;%0A%0A questions.forEach(function(question) %7B%0A if(answer.root_question_ID === question._id) %7B%0A question.question_criteria.forEach(function(option) %7B%0A if(answer.researcher_score.text === option.text) %7B%0A foundOption = option;%0A %7D%0A %7D);%0A %7D%0A %7D);%0A%0A return foundOption;%0A %7D;%0A%0A var getRootQuestions = function() %7B%0A var rootQuestions = %5B%5D;%0A%0A questions.forEach(function(question) %7B%0A if((question.linkedOption === undefined) && !isQuestionAnswered(question)) %7B%0A rootQuestions.push(question);%0A %7D%0A %7D);%0A%0A return rootQuestions;%0A %7D;%0A%0A var isQuestionAnswered = function(question) %7B%0A var answered = false;%0A%0A answers.forEach(function(answer) %7B%0A if((answer.root_question_ID === question._id) && answer.researcher_score) %7B%0A answered = true;%0A %7D%0A %7D);%0A%0A return answered;%0A %7D;%0A%0A return %7B%0A isAnyQuestionRemaining: function(answer) %7B%0A return getNextQuestion(answer) !== undefined ;%0A @@ -2079,22 +2079,39 @@ roFill(( +getNextQuestion( answer +) .questio @@ -2121,12 +2121,8 @@ rder - + 1 ), 3
9a063bd4c490f8bda620fbb7ece90d7c869f6eda
fix flow error
packages/preact-fela/src/renderToNodeList.js
packages/preact-fela/src/renderToNodeList.js
/* @flow */ import { h as createElement } from 'preact' import { renderToNodeListFactory } from 'fela-bindings' export default renderToNodeListFactory(createElement)
JavaScript
0.000001
@@ -5,16 +5,30 @@ flow */%0A +// $FlowFixMe%0A import %7B
194d57c7ca20abbbd675f201b5a12f4e451aa7e9
Remove log
main/server/cluster/index.js
main/server/cluster/index.js
const os = require('os'); const path = require('path'); const SocketCluster = require('socketcluster') .SocketCluster; //var workerCount = process.env.WEB_CONCURRENCY || 1; // TODO: Make more stable the multiple workers module.exports = function(options) { var workerCount = 1; workerCount = workerCount || os.cpus() .length; console.log(`Starting ${workerCount} workers`); //------------------------------------------------- var socketPath = '/socket'; process.env.PATH_SOCKET = process.env.PATH_SOCKET || socketPath; //------------------------------------------------- var environment = process.env.NODE_ENV; switch (environment) { case 'production': environment = 'prod'; break; default: environment = 'dev'; break; } //--------------------------------------------------- var clusterOptions = { workers: workerCount, port: process.env.PORT, protocol: process.env.PROTOCOL, path: socketPath, workerController: path.join(__dirname, 'worker.js'), environment: environment, logLevel: 3, protocolOptions: options.protocolOptions }; console.log(clusterOptions); var socketCluster = new SocketCluster(clusterOptions); return require('./master') .run(socketCluster) .then(function(result) { return { port: process.env.PORT, result: result }; }); };
JavaScript
0.000001
@@ -1135,41 +1135,8 @@ %7D;%0A%0A - console.log(clusterOptions);%0A%0A%0A va
b76bd0d4ca26b2a85f17b02f1989d89775ce50f8
Add ssl.enabled to filtered config. This branch fixes #35
lib/config/index.js
lib/config/index.js
'use strict'; var fs = require('fs'), extend = require('extend'), path = require('path'); var defaultConfig = { host: 'localhost', port: 9090, login: { enabled: false, sessionSecret: 'secretsecret', // Steam powered log in, get API key from http://steamcommunity.com/dev/apikey steam: { enabled: false, apiKey: 'XXXXX', //Only allow certain people to log in. Currently uses 64 bit Steam IDs. allowedIds: [ '11111111111111111', '22222222222222222' ] }, // Twitch login, get clientID/clientSecret from http://www.twitch.tv/kraken/oauth2/clients/new twitch: { enabled: false, clientID: 'twitch_client_id', clientSecret: 'twitch_client_secret', scope: 'user_read', //Only allow certain people to log in. allowedUsernames: [ 'some_name', 'another_name' ] } }, logging: { console: { enabled: true, level: 'debug' }, file: { enabled: true, path: 'logs/server.log', level: 'info' } }, ssl: { enabled: false, // Path to private key & certificate keyPath: '', certificatePath: '' } }; var config = null; var filteredConfig = null; // Create the cfg dir if it does not exist var cfgDirPath = path.resolve(__dirname, '../..', 'cfg'); if (!fs.existsSync(cfgDirPath)) { fs.mkdirSync(cfgDirPath); } var defaultConfigCopy = extend(true, {}, defaultConfig); // Load user config if it exists, and merge it var jsonPath = path.join(cfgDirPath, 'nodecg.json'); var cfgPath = path.join(cfgDirPath, 'nodecg.cfg'); if (fs.existsSync(jsonPath)) { // Check if .cfg exists, warn if so if (fs.existsSync(cfgPath)) { console.warn('warning: cfg/nodecg.json and cfg/nodecg.cfg detected!' + 'NodeCG will use nodecg.json, it is recommended you delete one of these!'); } parseConfig(jsonPath, defaultConfigCopy); } else if (fs.existsSync(cfgPath)) { // Warn that the file should be called .json console.warn('warning: NodeCG prefers cfg/nodecg.json,' + ' it is recommended you rename your config file to nodecg.json!'); parseConfig(cfgPath, defaultConfigCopy); } else { config = defaultConfigCopy; } function parseConfig(path, defaults) { var userConfig = JSON.parse(fs.readFileSync(path, 'utf8')); config = extend(true, defaults, userConfig); } // Create the filtered config filteredConfig = { host: config.host, port: config.port, login: { enabled: config.login.enabled, steam: { enabled: config.login.steam.enabled }, twitch: { enabled: config.login.twitch.enabled } } }; exports.getConfig = function() { return extend(true, {}, config); }; exports.getFilteredConfig = function() { return extend(true, {}, filteredConfig); }; module.exports = exports;
JavaScript
0
@@ -2923,24 +2923,78 @@ d%0A %7D%0A + %7D,%0A ssl: %7B%0A enabled: config.ssl.enabled%0A %7D%0A%7D;%0A%0Aex
ef42e11376044787db1c1967892ff83cb93a6158
make serializable
lib/dependencies/AMDRequireItemDependency.js
lib/dependencies/AMDRequireItemDependency.js
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); const ModuleDependencyTemplateAsRequireId = require("./ModuleDependencyTemplateAsRequireId"); class AMDRequireItemDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; } get type() { return "amd require"; } } AMDRequireItemDependency.Template = ModuleDependencyTemplateAsRequireId; module.exports = AMDRequireItemDependency;
JavaScript
0.000001
@@ -109,16 +109,78 @@ rict%22;%0A%0A +const makeSerializable = require(%22../util/makeSerializable%22);%0A const Mo @@ -223,24 +223,24 @@ pendency%22);%0A - const Module @@ -429,16 +429,17 @@ quest);%0A +%0A %09%09this.r @@ -497,17 +497,336 @@ re%22;%0A%09%7D%0A -%7D +%0A%09serialize(context) %7B%0A%09%09const %7B write %7D = context;%0A%0A%09%09write(this.range);%0A%0A%09%09super.serialize(context);%0A%09%7D%0A%0A%09deserialize(context) %7B%0A%09%09const %7B read %7D = context;%0A%0A%09%09this.range = read();%0A%0A%09%09super.deserialize(context);%0A%09%7D%0A%7D%0A%0AmakeSerializable(%0A%09AMDRequireItemDependency,%0A%09%22webpack/lib/dependencies/AMDRequireItemDependency%22%0A); %0A%0AAMDReq
68e6612a39a2eab8b0b0e972683bcaf987f72acf
Update metric validation to support single metric or array.
assets/js/modules/adsense/util/report-validation.js
assets/js/modules/adsense/util/report-validation.js
/** * Reporting API validation utilities. * * Site Kit by Google, Copyright 2021 Google LLC * * 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 * * https://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. */ /** * Internal dependencies */ import invariant from 'invariant'; /* eslint-disable-next-line */ /** @see (@link https://developers.google.com/adsense/management/reference/rest/v2/Metric) */ const VALID_METRICS = [ 'ACTIVE_VIEW_MEASURABILITY', 'ACTIVE_VIEW_TIME', 'ACTIVE_VIEW_VIEWABILITY', 'AD_REQUESTS_COVERAGE', 'AD_REQUESTS_CTR', 'AD_REQUESTS_RPM', 'AD_REQUESTS_SPAM_RATIO', 'AD_REQUESTS', 'ADS_PER_IMPRESSION', 'CLICKS_SPAM_RATIO', 'CLICKS', 'COST_PER_CLICK', 'ESTIMATED_EARNINGS', 'IMPRESSIONS_CTR', 'IMPRESSIONS_RPM', 'IMPRESSIONS_SPAM_RATIO', 'IMPRESSIONS', 'INDIVIDUAL_AD_IMPRESSIONS_CTR', 'INDIVIDUAL_AD_IMPRESSIONS_RPM', 'INDIVIDUAL_AD_IMPRESSIONS_SPAM_RATIO', 'INDIVIDUAL_AD_IMPRESSIONS', 'MATCHED_AD_REQUESTS_CTR', 'MATCHED_AD_REQUESTS_RPM', 'MATCHED_AD_REQUESTS_SPAM_RATIO', 'MATCHED_AD_REQUESTS', 'METRIC_UNSPECIFIED', 'PAGE_VIEWS_CTR', 'PAGE_VIEWS_RPM', 'PAGE_VIEWS_SPAM_RATIO', 'PAGE_VIEWS', 'TOTAL_EARNINGS', 'TOTAL_IMPRESSIONS', 'WEBSEARCH_RESULT_PAGES', ]; /* eslint-disable-next-line */ /** @see (@link https://developers.google.com/adsense/management/reference/rest/v2/Dimension) */ const VALID_DIMENSIONS = [ 'ACCOUNT_NAME', 'AD_CLIENT_ID', 'AD_FORMAT_CODE', 'AD_FORMAT_NAME', 'AD_PLACEMENT_CODE', 'AD_PLACEMENT_NAME', 'AD_UNIT_ID', 'AD_UNIT_NAME', 'AD_UNIT_SIZE_CODE', 'AD_UNIT_SIZE_NAME', 'BID_TYPE_CODE', 'BID_TYPE_NAME', 'BUYER_NETWORK_ID', 'BUYER_NETWORK_NAME', 'CONTENT_PLATFORM_CODE', 'CONTENT_PLATFORM_NAME', 'COUNTRY_CODE', 'COUNTRY_NAME', 'CREATIVE_SIZE_CODE', 'CREATIVE_SIZE_NAME', 'CUSTOM_CHANNEL_ID', 'CUSTOM_CHANNEL_NAME', 'CUSTOM_SEARCH_STYLE_ID', 'CUSTOM_SEARCH_STYLE_NAME', 'DATE', 'DIMENSION_UNSPECIFIED', 'DOMAIN_CODE', 'DOMAIN_NAME', 'DOMAIN_REGISTRANT', 'MONTH', 'OWNED_SITE_DOMAIN_NAME', 'OWNED_SITE_ID', 'PLATFORM_TYPE_CODE', 'PLATFORM_TYPE_NAME', 'PRODUCT_CODE', 'PRODUCT_NAME', 'REQUESTED_AD_TYPE_CODE', 'REQUESTED_AD_TYPE_NAME', 'SERVED_AD_TYPE_CODE', 'SERVED_AD_TYPE_NAME', 'TARGETING_TYPE_CODE', 'TARGETING_TYPE_NAME', 'URL_CHANNEL_ID', 'URL_CHANNEL_NAME', 'WEBSEARCH_QUERY_STRING', 'WEEK', ]; /** * Validates the given metrics are valid to be used in a request. * * @since n.e.x.t * * @param {Array} metrics Metrics to validate. */ export function validateMetrics( metrics ) { invariant( Array.isArray( metrics ), 'metrics must be an array.' ); invariant( metrics.length, 'at least one metric is required.' ); const invalidMetrics = metrics.filter( ( metric ) => ! VALID_METRICS.includes( metric ) ); invariant( invalidMetrics.length === 0, `invalid AdSense metrics requested: ${ invalidMetrics.toString() }` ); } /** * Validates the given dimensions are valid to be used in a request. * * @since n.e.x.t * * @param {Array} dimensions Dimensions to validate. */ export function validateDimensions( dimensions ) { invariant( Array.isArray( dimensions ), 'dimensions must be an array.' ); invariant( dimensions.length, 'at least one dimension is required.' ); const invalidDimensions = dimensions.filter( ( metric ) => ! VALID_DIMENSIONS.includes( metric ) ); invariant( invalidDimensions.length === 0, `invalid AdSense dimensions requested: ${ invalidDimensions.toString() }` ); }
JavaScript
0
@@ -652,16 +652,92 @@ e.%0A */%0A%0A +/**%0A * External dependencies%0A */%0Aimport castArray from 'lodash/castArray';%0A%0A /**%0A * I @@ -2962,21 +2962,30 @@ @param %7B +( Array +%7Cstring) %7D metric @@ -2992,17 +2992,19 @@ s Metric -s +(s) to vali @@ -3063,72 +3063,47 @@ %7B%0A%09 -invariant( Array.isArray( metrics ), 'metrics must be an array.' +const metricsArray = castArray( metrics );%0A @@ -3117,24 +3117,29 @@ ant( metrics +Array .length, 'at @@ -3205,16 +3205,21 @@ metrics +Array .filter(
72d9daacf61311bcc5f7aad090f0d70e6fa533a7
Update userscript info
hide_info.user.js
hide_info.user.js
// ==UserScript== // @name Hide/Show Unnecessary Info in Chat // @version 1.0 // @author michaelpri // @description Userscript to hide/show unecessary information that takes up room on the chat sidebar // @include *://chat.stackexchange.com/* // @include *://chat.stackoverflow.com/* // @include *://chat.meta.stackexchange.com/* // ==/UserScript== function hide_show($) { function hide_show_users() { var present_users = $("#present-users"); $("<table id='users-button-table'></table>").insertAfter(present_users); var users_button_table = $("#users-button-table"); users_button_table.append("<tr id='users-button-row'></tr>"); var users_button_row = $('#users-button-row'); users_button_row.append("<td class='users-show-hide-button' id='hide-users'>Hide Users</td>"); users_button_row.append("<td class='users-show-hide-button' id='show-users'>Show Users</td>"); var hide_users = $("#hide-users"); var show_users = $('#show-users'); var users_show_hide_buttons = $(".users-show-hide-button"); users_button_table.css({"border-bottom":"1px dotted #cecece", "width":"100%"}); users_show_hide_buttons.css({"color":"darkblue", "font-weight":"bold", "padding-bottom":"5px"}); present_users.css({"margin-bottom":"5px"}); users_show_hide_buttons.on("mouseover", function() { users_show_hide_buttons.css({"text-decoration":"underline", "cursor":"pointer"}); }); users_show_hide_buttons.on("mouseout", function() { users_show_hide_buttons.css({"text-decoration":"none", "cursor":"default"}); }); present_users.hide(); hide_users.hide(); show_users.on("click", function() { present_users.show(); hide_users.show(); show_users.hide(); }); hide_users.on("click", function() { present_users.hide(); show_users.show(); hide_users.hide(); }); } function hide_show_info() { var room_desc = $("#roomdesc"); var room_tags = $('#room-tags'); var sidebar_menu = $('#sidebar-menu'); $("<table id='info-button-table'></table>").insertAfter(room_tags); var info_button_table = $("#info-button-table"); info_button_table.append("<tr id='info-button-row'></tr>"); var info_button_row = $('#info-button-row'); info_button_row.append("<td class='info-show-hide-button' id='hide-info'>Hide Info</td>"); info_button_row.append("<td class='info-show-hide-button' id='show-info'>Show Info</td>"); var hide_info = $("#hide-info"); var show_info = $('#show-info'); var info_show_hide_buttons = $(".info-show-hide-button"); info_button_table.css({"border-top":"1px dotted #cecece", "width":"100%", "border-bottom":"1px dotted #cecece"}); info_show_hide_buttons.css({"color":"darkblue", "font-weight":"bold", "padding-top":"5px", "padding-bottom":"5px"}); sidebar_menu.css({"padding-top":"5px"}) info_show_hide_buttons.on("mouseover", function() { info_show_hide_buttons.css({"text-decoration":"underline", "cursor":"pointer"}); }); info_show_hide_buttons.on("mouseout", function() { info_show_hide_buttons.css({"text-decoration":"none", "cursor":"default"}); }); room_desc.hide(); room_tags.hide(); hide_info.hide(); show_info.on("click", function() { room_desc.show(); room_tags.show(); hide_info.show(); show_info.hide(); }); hide_info.on("click", function() { room_desc.hide(); room_tags.hide(); hide_info.hide(); show_info.show(); }); } hide_show_users(); hide_show_info(); } window.addEventListener('load', function() { var scriptEl = document.createElement('script'); scriptEl.type = 'text/javascript'; scriptEl.text = '(' + hide_show + ')(jQuery);'; document.head.appendChild(scriptEl); });
JavaScript
0
@@ -28,13 +28,8 @@ Hide -/Show Unn @@ -45,16 +45,19 @@ Info in +SE Chat%0A// @@ -129,13 +129,8 @@ hide -/show une @@ -137,16 +137,30 @@ cessary +or cluttering informat
009acc2b3ec4d18ac08bb05ff840a3721619863c
add EngagementLevel to meta
BackOffice/modules/services/EditorMetaService.js
BackOffice/modules/services/EditorMetaService.js
import R from 'ramda'; import { types, enumType, initializeTypes } from './TypesService'; import { boolAllowedValue, fromEnum } from './EditorMetaAllowedValuesService'; export default class EditorMetaService { static _instance; static get instance() { if (!EditorMetaService._instance) { EditorMetaService._instance = new EditorMetaService(); } return EditorMetaService._instance; } static async initialize() { const initPromise = initializeTypes(); initPromise.then(() => EditorMetaService.instance._initializeMeta()); return initPromise; } getFieldMeta(field) { if (field === '') return { type: 'empty' }; try { const [identity, property] = field.split('.'); const fieldMeta = this.meta.fields[identity][property]; if (!fieldMeta) { throw 'unsupported field meta: ' + field; } return fieldMeta; } catch (exp) { console.log('error occurd getting field meta', exp.message); return { type: 'string' }; } } getKeyMeta(key) { } getIdentities() { return Object.keys(this.meta.identities); } getSuggestions({ type, query }) { if (type === 'MatcherProperty') { return R.reduce(R.concat, [])(R.keys(this.meta.identities).map(identity => R.toPairs(this.meta.fields[identity]).map(([field, meta]) => ({ label: `${field}`, value: `${identity}.${field}`, meta }))) ); } else { return []; } } _initializeMeta() { this.meta = { identities: { device: {}, technician: {}, }, fields: { device: { '@@id': { multipleValues: true, description: "device id", ...types.string, }, PartnerBrandId: { multipleValues: true, description: "The name of the partner", ...types.string, }, DeviceOsType: { multipleValues: true, description: "Device operation system name", ...enumType('string'), allowedValues: fromEnum('Android', 'Ios'), }, SubscriptionType: { multipleValues: true, description: "The home tier subscription of the device", ...enumType('string'), allowedValues: fromEnum('Evaluation', 'Free', 'Insurance', 'InsuranceAndSupport', 'HomeSupport', 'DefaultFree'), }, AgentVersion: { multipleValues: true, defaultValue: '1.0.0.0', ...types.version }, DeviceOsVersion: { multipleValues: true, ...types.version }, DeviceVendor: { multipleValues: true, description: "Device vendor", ...types.string, }, CountryCode: { multipleValues: true, description: "Country code", type: "string", }, DeviceModel: { multipleValues: true, description: "device model", ...types.string, }, InstallationSource: { multipleValues: true, description: "Installation source", ...types.string, }, IsInGroup: { multipleValues: true, description: "Is in group", defaultValue: false, ...types.bool, allowedValues: boolAllowedValue, }, CreatedAt: { multipleValues: true, description: "Created at", ...types.string, }, DeviceType: { multipleValues: true, description: "Device type", ...enumType('string'), allowedValues: fromEnum('Unknown', 'Desktop', 'Laptop', 'Tablet', 'Mobile', 'WinServer', 'Car', 'Television', 'PrinterFax', 'Bike', 'ChildItem', 'KitchenAppliance', 'CleaningAppliance', 'VideoGamingDevice', 'HomeTheaterDevice', 'Computer', 'Other' ), }, }, }, }; EditorMetaService.isLoaded = true; } }
JavaScript
0
@@ -3589,32 +3589,182 @@ g,%0A %7D,%0A + EngagementLevel: %7B%0A multipleValues: true,%0A description: %22Engagement Level%22,%0A ...types.string,%0A %7D,%0A Device
b05c618f93130418d481dcf872c1258f57dbfee8
Add Meteor.settings support for configurations
lib/server/config.js
lib/server/config.js
Config = {}; Config.captcha = { siteKey: getEnv("FIREWALL_CAPTCHA_SITE_KEY", "6LdkcgMTAAAAAJosMQhYSfKeFldhn644i9w9c4Oi"), secret: getEnv("FIREWALL_CAPTCHA_SECRET", "6LdkcgMTAAAAADftIWaISsvQ7SqIeLqHM3PWu79Q") }; Config.rateLimits = { perIp: getEnv("FIREWALL_PER_IP_MAX_RPS", 50), perHuman: getEnv("FIREWALL_PER_HUMAN_MAX_RPS", 20), perSession: getEnv("FIREWALL_PER_HUMAN_MAX_RPS", 20), }; Config.times = { blockIpFor: getEnv("FIREWALL_BLOCK_IP_FOR_MILLIS", 1000 * 60 * 2), humanLivesUpto: getEnv("FIREWALL_HUMAN_LIVES_UPTO_MILLIS", 1000 * 60 * 60) }; function getEnv(key, defaultValue) { return process.env[key] || defaultValue; }
JavaScript
0
@@ -35,27 +35,30 @@ siteKey: get -Env +Config (%22FIREWALL_C @@ -74,16 +74,44 @@ TE_KEY%22, + %22firewall.captcha.siteKey%22, %226Ldkcg @@ -157,27 +157,30 @@ secret: get -Env +Config (%22FIREWALL_C @@ -194,16 +194,43 @@ SECRET%22, + %22firewall.captcha.secret%22, %226Ldkcg @@ -300,27 +300,30 @@ perIp: get -Env +Config (%22FIREWALL_P @@ -337,16 +337,45 @@ AX_RPS%22, + %22firewall.rateLimits.perIp%22, 50),%0A @@ -383,27 +383,30 @@ erHuman: get -Env +Config (%22FIREWALL_P @@ -419,24 +419,56 @@ AN_MAX_RPS%22, + %22firewall.rateLimits.perHuman%22, 20),%0A perS @@ -474,27 +474,30 @@ Session: get -Env +Config (%22FIREWALL_P @@ -514,16 +514,50 @@ AX_RPS%22, + %22firewall.rateLimits.perSession%22, 20),%0A%7D; @@ -588,27 +588,30 @@ ckIpFor: get -Env +Config (%22FIREWALL_B @@ -622,32 +622,61 @@ _IP_FOR_MILLIS%22, + %22firewall.times.blockIpFor%22, 1000 * 60 * 2), @@ -697,19 +697,22 @@ pto: get -Env +Config (%22FIREWA @@ -744,93 +744,534 @@ S%22, -1000 * 60 * 60)%0A%7D;%0A%0Afunction getEnv(key, defaultValue) %7B%0A return process.env%5Bkey%5D %7C%7C +%22firewall.times.humanLivesUpto%22, 1000 * 60 * 60)%0A%7D;%0A%0Aconsole.log(%22Firewall: starting with these configurations:%22, JSON.stringify(Config));%0A%0Afunction getConfig(key, meteorSettingsKey, defaultValue) %7B%0A var envVar = process.env%5Bkey%5D;%0A if(envVar) %7B%0A return envVar;%0A %7D%0A%0A if(Meteor.settings) %7B%0A var parts = meteorSettingsKey.split('.');%0A var value = Meteor.settings;%0A parts.forEach(function(key) %7B%0A if(value) %7B%0A value = value%5Bkey%5D;%0A %7D%0A %7D);%0A%0A if(value) %7B%0A return value;%0A %7D%0A %7D%0A%0A return def
a2013645d8f63ea1607c57399a57f0bf994cb4b9
Add tests for importing link with formatting elements.
test/Annotations.test.js
test/Annotations.test.js
import { test } from 'substance-test' import { setCursor, setSelection, openManuscriptEditor, loadBodyFixture, isToolEnabled, openMenu, ensureValidJATS } from './shared/integrationTestHelpers' import setupTestApp from './shared/setupTestApp' import { doesNotThrowInNodejs } from './shared/testHelpers' const ANNOS = [ { name: 'Strong', menu: 'format', tool: 'toggle-bold', selector: '.sc-annotation.sm-bold' }, { name: 'Emphasize', menu: 'format', tool: 'toggle-italic', selector: '.sc-annotation.sm-italic' }, { name: 'Link', menu: 'insert', tool: 'create-external-link', selector: '.sc-external-link' }, { name: 'Small Caps', menu: 'format', tool: 'toggle-small-caps', selector: '.sc-annotation.sm-small-caps' }, { name: 'Subscript', menu: 'format', tool: 'toggle-subscript', selector: '.sc-annotation.sm-subscript' }, { name: 'Superscript', menu: 'format', tool: 'toggle-superscript', selector: '.sc-annotation.sm-superscript' }, { name: 'Monospace', menu: 'format', tool: 'toggle-monospace', selector: '.sc-annotation.sm-monospace' }, { name: 'Overline', menu: 'format', tool: 'toggle-overline', selector: '.sc-annotation.sm-overline' }, { name: 'Strike Through', menu: 'format', tool: 'toggle-strike-through', selector: '.sc-annotation.sm-strike-through' }, { name: 'Underline', menu: 'format', tool: 'toggle-underline', selector: '.sc-annotation.sm-underline' } ] // const ANNO_SELECTOR = { // 'external-link': '.sc-external-link' // } const FIXTURE = `<p id="p1">Lorem ipsum dolor sit amet.</p>` ANNOS.forEach(spec => { test(`Annotations: toggle ${spec.name} annotation`, t => { testAnnotationToggle(t, spec) }) }) function testAnnotationToggle (t, spec) { let { app, editor } = _setup(t) const _hasAnno = () => { return Boolean(editor.find(`[data-path="p1.content"] ${spec.selector}`)) } // Set the cursor and check if tool is active setCursor(editor, 'p1.content', 3) t.notOk(_isToolEnabled(editor, spec), 'tool should be disabled') // Set the selection and check if tool is active setSelection(editor, 'p1.content', 2, 4) t.ok(_isToolEnabled(editor, spec), 'tool should be enabled') // Toggle the annotation _toggleAnnotation(t, editor, spec) t.ok(_hasAnno(), 'there should be an annotation') ensureValidJATS(t, app) // then toggle the annotation again to remove it t.ok(_isToolEnabled(editor, spec), 'tool should be enabled') _toggleAnnotation(t, editor, spec) t.notOk(_hasAnno(), 'There should be no annotation') t.end() } function _setup (t) { let { app } = setupTestApp(t, { archiveId: 'blank', readOnly: true }) let editor = openManuscriptEditor(app) loadBodyFixture(editor, FIXTURE) return { app, editor } } function _isToolEnabled (editor, spec) { return isToolEnabled(editor, spec.menu, `.sc-tool.sm-${spec.tool}`) } function _toggleAnnotation (t, editor, spec) { doesNotThrowInNodejs(t, () => { let menu = openMenu(editor, spec.menu) menu.find(`.sc-tool.sm-${spec.tool}`).el.click() }) }
JavaScript
0
@@ -1830,16 +1830,1011 @@ %7D)%0A%7D)%0A%0A +const FORMATTED_LINK_FIXTURE = %60%3Cp%3E%3Citalic%3E%3Cext-link%3Elink content%3C/ext-link%3E%3C/italic%3E%3C/p%3E%60%0A%0Atest(%60Annotations: link inside of formatting%60, t =%3E %7B%0A let %7B editor %7D = _setup(t, FORMATTED_LINK_FIXTURE)%0A const anno = editor.find(%60.sm-italic%60)%0A const link = editor.find(%60.sc-external-link%60)%0A t.ok(Boolean(anno), 'annotation should exist')%0A t.ok(Boolean(anno), 'link should exist')%0A t.equal(anno.text(), link.text(), 'content of the annotation and the link should be the same')%0A t.end()%0A%7D)%0A%0Aconst LINK_WITH_FORMATTING_FIXTURE = %60%3Cp%3E%3Cext-link%3E%3Cbold%3Ebold content%3C/bold%3E%3C/ext-link%3E%3C/p%3E%60%0A%0Atest(%60Annotations: formatting content inside a link%60, t =%3E %7B%0A let %7B editor %7D = _setup(t, LINK_WITH_FORMATTING_FIXTURE)%0A const anno = editor.find(%60.sm-bold%60)%0A const link = editor.find(%60.sc-external-link%60)%0A t.ok(Boolean(anno), 'annotation should exist')%0A t.ok(Boolean(anno), 'link should exist')%0A t.equal(anno.text(), link.text(), 'content of the annotation and the link should be the same')%0A t.end()%0A%7D)%0A%0A function @@ -2899,16 +2899,25 @@ _setup(t +, FIXTURE )%0A cons @@ -3707,16 +3707,25 @@ setup (t +, fixture ) %7B%0A le @@ -3859,23 +3859,23 @@ editor, -FIXTURE +fixture )%0A retu
9c1f56dd707574fc6f32743ffc63ed85c163a1db
Fix navigation buttons in detached window.
extension/content/firebug/navigationHistory.js
extension/content/firebug/navigationHistory.js
/* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // Constants const Cc = Components.classes; const Ci = Components.interfaces; const MAX_HISTORY_MENU_ITEMS = 15; // ************************************************************************************************ /** * @class Support for back and forward pattern for navigating within Firebug UI (panels). */ Firebug.NavigationHistory = extend(Firebug.Module, { currIndex: 0, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Extending Module initContext: function(context, persistedState) { Firebug.Module.initContext.apply(this, arguments); if (persistedState && persistedState.navigationHistory) context.navigationHistory = persistedState.navigationHistory; }, destroyContext: function(context, persistedState) { Firebug.ActivableModule.destroyContext.apply(this, arguments); if (persistedState) persistedState.navigationHistory = context.navigationHistory; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // History popup menu onPopupShowing: function(popup, context) { FBL.eraseNode(popup); var list = this.getHistory(context); // Don't display the popup for a single item. var count = list.length; if (count <= 1) return false; var maxItems = MAX_HISTORY_MENU_ITEMS; var half = Math.floor(maxItems / 2); var start = Math.max(this.currIndex - half, 0); var end = Math.min(start == 0 ? maxItems : this.currIndex + half + 1, count); if (end == count) start = Math.max(count - maxItems, 0); var tooltipBack = $STR("firebug.history.Go back to this panel"); var tooltipCurrent = $STR("firebug.history.Stay on this panel"); var tooltipForward = $STR("firebug.history.Go forward to this panel"); for (var i=end-1; i>=start; i--) { var historyItem = list[i]; var panelType = Firebug.getPanelType(historyItem.panelName); var label = Firebug.getPanelTitle(panelType); if (historyItem.location && historyItem.location.href) label += " - " + historyItem.location.href; var menuInfo = { label: label, nol10n: true, className: "menuitem-iconic fbURLMenuItem", }; if (i < this.currIndex) { menuInfo.className += " navigationHistoryMenuItemBack"; menuInfo.tooltiptext = tooltipBack; } else if (i == this.currIndex) { menuInfo.type = "radio"; menuInfo.checked = "true"; menuInfo.className = "navigationHistoryMenuItemCurrent"; menuInfo.tooltiptext = tooltipCurrent; } else { menuInfo.className += " navigationHistoryMenuItemForward"; menuInfo.tooltiptext = tooltipForward; } var menuItem = FBL.createMenuItem(popup, menuInfo); menuItem.repObject = location; menuItem.setAttribute("index", i); } return true; }, onHistoryCommand: function(event, context) { var menuItem = event.target; var index = menuItem.getAttribute("index"); if (!index) return false; this.gotoHistoryIndex(context, index); return true; }, goBack: function(context) { this.gotoHistoryIndex(context, --this.currIndex); }, goForward: function(context) { this.gotoHistoryIndex(context, ++this.currIndex); }, gotoHistoryIndex: function(context, index) { var list = this.getHistory(context); if (index < 0 || index >= list.length) return; var historyItem = list[index]; try { this.navInProgress = true; Firebug.chrome.navigate(historyItem.location, historyItem.panelName); this.currIndex = index; } catch (e) { } finally { this.navInProgress = false; } this.updateButtons(context); }, updateButtons: function(context) { var list = this.getHistory(context); var backButton = $("fbNavigateBackButton"); var forwardButton = $("fbNavigateForwardButton"); backButton.setAttribute("disabled", "true"); forwardButton.setAttribute("disabled", "true"); if (list.length <= 1) return; if (this.currIndex > 0) backButton.removeAttribute("disabled"); if (this.currIndex < list.length-1) forwardButton.removeAttribute("disabled"); }, getHistory: function(context) { if (!context.navigationHistory) context.navigationHistory = []; return context.navigationHistory; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // UI Listener onPanelNavigate: function(location, panel) { if (FBTrace.DBG_HISTORY) FBTrace.sysout("history.onPanelNavigate; " + "Panel: " + (panel ? panel.name : "Unknown Panel") + "Location: " + (location ? location.href : "No Location")); // The panel must be always there if (!panel) return; // The user is navigating using the history UI, this action doesn't affect // the history list. if (this.navInProgress) return; var list = this.getHistory(panel.context); // Remove forward history. list.splice(this.currIndex+1, list.length-(this.currIndex+1)); // If the last item in the history is the same bail out. var lastHistoryItem = list.length ? list[list.length-1] : null; if (lastHistoryItem && lastHistoryItem.panelName == panel.name && lastHistoryItem.location == location) return; if (lastHistoryItem && lastHistoryItem.location && location && lastHistoryItem.location.href == location.href) return; list.push({panelName: panel.name, location: location}); this.currIndex = list.length-1; // Update back and forward buttons in the UI. this.updateButtons(panel.context); } }); // ************************************************************************************************ // Registration Firebug.registerModule(Firebug.NavigationHistory); Firebug.registerUIListener(Firebug.NavigationHistory); // ************************************************************************************************ }});
JavaScript
0.000064
@@ -939,24 +939,187 @@ ry;%0A %7D,%0A%0A + reattachContext: function(browser, context)%0A %7B%0A Firebug.Module.reattachContext.apply(this, arguments);%0A%0A this.updateButtons(context);%0A %7D,%0A%0A destroyC @@ -1186,17 +1186,8 @@ bug. -Activable Modu @@ -4758,32 +4758,47 @@ ar backButton = +Firebug.chrome. $(%22fbNavigateBac @@ -4836,16 +4836,31 @@ utton = +Firebug.chrome. $(%22fbNav
07eee47257486896f237c64c6f0aa7ecc97b66ed
Fix Pebble API detecting mmol units from settings
lib/server/pebble.js
lib/server/pebble.js
'use strict'; var _ = require('lodash'); var sandbox = require('../sandbox')(); var units = require('../units')(); var DIRECTIONS = { NONE: 0 , DoubleUp: 1 , SingleUp: 2 , FortyFiveUp: 3 , Flat: 4 , FortyFiveDown: 5 , SingleDown: 6 , DoubleDown: 7 , 'NOT COMPUTABLE': 8 , 'RATE OUT OF RANGE': 9 }; function directionToTrend (direction) { var trend = 8; if (direction in DIRECTIONS) { trend = DIRECTIONS[direction]; } return trend; } function reverseAndSlice (entries, req) { var reversed = entries.slice(0); reversed.reverse(); return reversed.slice(0, req.count); } function mapSGVs(req, sbx) { function scaleMgdlAPebbleLegacyHackThatWillNotGoAway (bg) { if (req.mmol) { return units.mgdlToMMOL(bg); } else { return bg.toString(); } } var cal = sbx.lastEntry(sbx.data.cals); return _.map(reverseAndSlice(sbx.data.sgvs, req), function transformSGV(sgv) { var transformed = { sgv: scaleMgdlAPebbleLegacyHackThatWillNotGoAway(sgv.mgdl), trend: directionToTrend(sgv.direction), direction: sgv.direction, datetime: sgv.mills }; if (req.rawbg && cal) { transformed.filtered = sgv.filtered; transformed.unfiltered = sgv.unfiltered; transformed.noise = sgv.noise; } return transformed; }); } function addExtraData (first, req, sbx) { //for compatibility we're keeping battery and iob on the first bg, but they would be better somewhere else var data = sbx.data; function addDelta() { var delta = sbx.properties.delta; //for legacy reasons we need to return a 0 for delta if it can't be calculated first.bgdelta = delta && delta.scaled || 0; if (req.mmol) { first.bgdelta = first.bgdelta.toFixed(1); } } function addBattery() { var uploaderStatus = _.findLast(data.devicestatus, function (status) { return ('uploader' in status); }); var battery = uploaderStatus && uploaderStatus.uploader && uploaderStatus.uploader.battery; if (battery && battery >= 0) { first.battery = battery.toString(); } } function addIOB() { if (req.iob) { var iobResult = req.ctx.plugins('iob').calcTotal(data.treatments, data.devicestatus, data.profile, Date.now()); if (iobResult) { first.iob = iobResult.display || 0; } sbx.properties.iob = iobResult; var bwpResult = req.ctx.plugins('bwp').calc(sbx); if (bwpResult) { first.bwp = bwpResult.bolusEstimateDisplay; first.bwpo = bwpResult.outcomeDisplay; } } } function addCOB() { if (req.cob) { var cobResult = req.ctx.plugins('cob').cobTotal(data.treatments, data.devicestatus, data.profile, Date.now()); if (cobResult) { first.cob = cobResult.display || 0; } } } addDelta(); addBattery(); addIOB(); addCOB(); } function prepareBGs (req, sbx) { if (sbx.data.sgvs.length === 0) { return []; } var bgs = mapSGVs(req, sbx); addExtraData(bgs[0], req, sbx); return bgs; } function prepareCals (req, sbx) { var data = sbx.data; if (req.rawbg && data.cals && data.cals.length > 0) { return _.map(reverseAndSlice(data.cals, req), function transformCal (cal) { return _.pick(cal, ['slope', 'intercept', 'scale']); }); } else { return []; } } function prepareSandbox (req) { var clonedEnv = _.cloneDeep(req.env); if (req.mmol) { clonedEnv.settings.units = 'mmol'; } var sbx = sandbox.serverInit(clonedEnv, req.ctx); req.ctx.plugins('bgnow').setProperties(sbx); return sbx; } function pebble (req, res) { var sbx = prepareSandbox(req); res.setHeader('content-type', 'application/json'); res.write(JSON.stringify({ status: [ {now: Date.now()} ] , bgs: prepareBGs(req, sbx) , cals: prepareCals(req, sbx) })); res.end( ); } function configure (env, ctx) { var wares = require('../middleware/')(env); function middle (req, res, next) { req.env = env; req.ctx = ctx; req.rawbg = env.settings.isEnabled('rawbg'); req.iob = env.settings.isEnabled('iob'); req.cob = env.settings.isEnabled('cob'); req.mmol = (req.query.units || env.DISPLAY_UNITS) === 'mmol'; req.count = parseInt(req.query.count) || 1; next( ); } return [middle, wares.sendJSONStatus, ctx.authorization.isPermitted('api:pebble,entries:read'), pebble]; } configure.pebble = pebble; module.exports = configure;
JavaScript
0.000001
@@ -4195,21 +4195,22 @@ env. -DISPLAY_UNITS +settings.units ) ==
db8712c7ad7934f1fbbe9e45a052b1949bd0804b
remove !!
Resources/public/js/components/products/components/pricing/main.js
Resources/public/js/components/products/components/pricing/main.js
/* * This file is part of the Sulu CMS. * * (c) MASSIVE ART WebServices GmbH * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ define(['config'], function (Config) { 'use strict'; var formSelector = '#product-pricing-form', pricesSelector = '#prices', maxLengthTitle = 60, render = function () { this.sandbox.dom.html(this.$el, this.renderTemplate('/admin/product/template/product/pricing')); setHeaderInformation.call(this); initForm.call(this, this.options.data); var priceListData = {}; if (!!this.options.data.prices) { priceListData.prices = this.options.data.prices; } if (!!this.options.data.specialPrices) { priceListData.specialPrices = this.options.data.specialPrices; } initPriceList.call(this, priceListData); }, initPriceList = function(data) { var options = { currencies: this.currencies, defaultCurrency: this.defaultCurrency, data: data, el: pricesSelector }; this.sandbox.start([{ name: 'price-list@suluproduct', options: options }]); }, bindCustomEvents = function () { this.sandbox.on('sulu.header.toolbar.delete', function () { this.sandbox.emit('sulu.product.delete', this.sandbox.dom.val('#id')); }.bind(this)); this.sandbox.on('product.state.change', function(id) { if (!this.options.data.status || this.options.data.status.id !== id) { this.status = {id: id}; this.options.data.status = this.status; setHeaderBar.call(this, false); } }, this); this.sandbox.on('sulu.header.toolbar.save', function () { save.call(this); }, this); this.sandbox.on('sulu.products.saved', function(data) { setHeaderBar.call(this, true); this.options.data = data; this.options.data.status = this.status; }, this); this.sandbox.on('sulu.header.back', function () { this.sandbox.emit('sulu.products.list'); }, this); this.sandbox.on('sulu.product.set-currencies', function(currencies){ this.currencies = currencies; }, this); this.sandbox.on('sulu.product.set-default-currency', function(cur){ this.defaultCurrency = cur; }, this); }, save = function () { if (this.sandbox.form.validate(formSelector)) { var data = this.sandbox.form.getData(formSelector); data.status = this.status; this.sandbox.emit('sulu.products.save', data); } }, // TODO remove the following functions, as soon as they are extracted somewhere else initForm = function (data) { // set form data var formObject = this.sandbox.form.create(formSelector); formObject.initialized.then(function () { setFormData.call(this, data); }.bind(this)); }, setFormData = function (data) { this.sandbox.form.setData(formSelector, data).then(function () { this.sandbox.start(formSelector); }.bind(this)).fail(function (error) { this.sandbox.logger.error("An error occured when setting data!", error); }.bind(this)); }, setHeaderBar = function(saved) { if (saved !== this.saved) { var type = (!!this.options.data && !!this.options.data.id) ? 'edit' : 'add'; this.sandbox.emit('sulu.header.toolbar.state.change', type, saved, true); } this.saved = saved; }, setHeaderInformation = function () { var title = 'pim.product.title', breadcrumb = [ {title: 'navigation.pim'}, {title: 'pim.products.title'} ]; if (!!this.options.data && !!this.options.data.name) { title = this.options.data.name; } title = this.sandbox.util.cropTail(title, maxLengthTitle); this.sandbox.emit('sulu.header.set-title', title); if (!!this.options.data && !!this.options.data.number) { breadcrumb.push({ title: '#' + this.options.data.number }); } else { breadcrumb.push({ title: 'pim.product.title' }); } this.sandbox.emit('sulu.header.set-breadcrumb', breadcrumb); }, listenForChange = function () { this.sandbox.dom.on(formSelector, 'change', function () { setHeaderBar.call(this, false); }.bind(this), 'select'); this.sandbox.dom.on(formSelector, 'keyup', function () { setHeaderBar.call(this, false); }.bind(this), 'input, textarea'); this.sandbox.on('sulu.content.changed', function () { setHeaderBar.call(this, false); }.bind(this)); this.sandbox.on('husky.select.tax-class.selected.item', function () { setHeaderBar.call(this, false); }.bind(this)); }; return { name: 'Sulu Product Pricing View', view: true, templates: ['/admin/product/template/product/pricing'], initialize: function () { this.status = !!this.options.data ? this.options.data.status : Config.get('product.status.active'); bindCustomEvents.call(this); render.call(this); listenForChange.call(this); } }; });
JavaScript
0
@@ -650,34 +650,32 @@ if ( -!! this.options.dat @@ -774,34 +774,32 @@ if ( -!! this.options.dat
762b7dcb7a9ed684cf3e8c1086d85a8eca9e640b
add send button to send prompt
plugins/Wallet/js/components/sendprompt.js
plugins/Wallet/js/components/sendprompt.js
import React, { PropTypes } from 'react'; const SendPrompt = ({visible, sendAddress, sendAmount, actions}) => { const onSendAddressChange = (e) => actions.setSendAddress(e.target.value); const onSendAmountChange = (e) => actions.setSendAmount(e.target.value); if (!visible) { return ( <div></div> ); } return ( <div className="sendprompt"> <div className="sendamount"> Send <input onChange={onSendAmountChange}></input> SC </div> <div className="sendaddress"> To <input onChange={onSendAddressChange}></input> </div> </div> ); } export default SendPrompt;
JavaScript
0
@@ -385,20 +385,47 @@ t%22%3E%0A%09%09%09%09 -Send +%3Cspan%3ESend Amount (SC): %3C/span%3E %0A%09%09%09%09%3Cin @@ -471,15 +471,8 @@ ut%3E%0A -%09%09%09%09SC%0A %09%09%09%3C @@ -518,11 +518,37 @@ %09%09%09%09 -To +%3Cspan%3ETo Address:%3C/span%3E%0A%09%09%09%09 %3Cinp @@ -600,16 +600,96 @@ %09%3C/div%3E%0A +%09%09%09%3Cbutton className=%22send-button%22 onClick=%7Bactions.sendSiacoins%7D%3ESend%3C/button%3E%0A %09%09%3C/div%3E
6863c69adee81c8ba33e9b4df3e7c3e429dde507
debug added as status was not updated
media/person/js/Dashboard.js
media/person/js/Dashboard.js
FlightDeck = Class.refactor(FlightDeck, { options: {upload_package_modal: ''}, initialize: function(options) { this.previous(options); var self = this; if (document.id('upload-package')) { document.id('upload-package').addEvent('click', function(ev) { if (ev) ev.stop(); self.displayModal(self.options.upload_package_modal); document.id('upload-package-submit').addEvent('click', function(eve){ // here add in JS functionality // it will be needed for interactive upload which will support // adding Libraries }) }) } $$('.UI_AMO_Upload_New_Version a').addEvent('click', this.uploadToAMO.bind(this)); $$('.UI_AMO_Upload_New_Addon a').addEvent('click', this.uploadToAMO.bind(this)); $$('.UI_AMO_Info').each(this.getStatusFromAMO, this); }, /* * Method: uploadToAMO * create XPI and upload it to AMO */ uploadToAMO: function(e) { if (e) e.stop(); else { fd.error.alert('System error', 'FlightDeck.uploadToAMO needs to be called with event'); return } var el = e.target.getParent('li'); new Request.JSON({ url: el.get('data-upload_url'), useSpinner: true, spinnerTarget: el.getElement('a'), spinnerOptions: { img: { 'class': 'spinner-img spinner-16' }, maskBorder: false }, onSuccess: function(response) { fd.message.alert('Uploading to AMO (' + settings.amooauth_domain +')', 'We\'ve scheduled the Add-on to upload<br/>' + 'Check the upload status and complete the process on your ' + '<a href="' + settings.amooauth_protocol + '://' + settings.amooauth_domain + '/en-US/developers/addons" target="amo_dashboard">AMO dashboard</a>'); this.getStatus.delay(5000, this, el.getParent('.UI_AMO_Info')); this.updateStatus(el, {'status': 'Upload Scheduled'}) }.bind(this), addOnFailure: function() { this.getStatus.delay(500, this, el.getParent('.UI_AMO_Info')); }.bind(this) }).send(); }, /* * Method: getStatusFromAMO * pull Add-o status from AMO and update data on the page */ getStatusFromAMO: function(status_el) { if (!status_el.get('data-uploaded')) { return; } new Request.JSON({ url: status_el.get('data-pull_info_url'), useSpinner: true, spinnerTarget: status_el.getElements('h2')[0], spinnerOptions: { img: { 'class': 'spinner-img spinner-16' }, maskBorder: false }, onSuccess: function(response) { this.updateStatus(status_el, response); }.bind(this) }).send(); }, /* * Method: getStatus * pull Add-o status and update data on the page */ getStatus: function(status_el) { new Request.JSON({ url: status_el.get('data-get_addon_info_url'), useSpinner: true, spinnerTarget: status_el.getElements('h2')[0], spinnerOptions: { img: { 'class': 'spinner-img spinner-16' }, maskBorder: false }, onSuccess: function(response) { this.updateStatus(status_el, response); if (!status_el.get('data-uploaded')) { status_el.set('data-uploaded', 1) } // repeat every 10s if still no answer from AMO was // saved if (response.status_code && response.status_code == -1) { this.getStatus.delay(10000, this, status_el); } }.bind(this) }).send(); }, /* * Method: updateStatus * update data on the page */ updateStatus: function(status_el, data, created) { var update = function(className, content) { status_el.getElements(className)[0].set('text', content).highlight(); }; if (data.status) update('.amo-review_status', data.status); if (data.version) update('.amo-latest_version', data.version); if (data.get_addon_info_url) status_el.set('data-get_addon_info_url', data.get_addon_info_url) //if (data.pk) status_el.set('data-revision_id', data.pk) ; var edit_on_amo = status_el.getElements('.UI_AMO_Edit_On_AMO'); edit_on_amo = edit_on_amo ? edit_on_amo[0] : false; var view_on_amo = status_el.getElements('.UI_AMO_View_On_AMO'); view_on_amo = view_on_amo ? view_on_amo[0] : false; if (view_on_amo && data.view_on_amo_url && data.status_code > 0) { view_on_amo.getElements('a')[0].set('href', data.view_on_amo_url); view_on_amo.removeClass('hidden'); view_on_amo.highlight(); if (edit_on_amo) edit_on_amo.addClass('hidden'); } if (edit_on_amo && data.edit_on_amo_url && data.status_code == 0) { edit_on_amo.getElements('a')[0].set('href', data.edit_on_amo_url); edit_on_amo.removeClass('hidden'); edit_on_amo.highlight(); if (view_on_amo) view_on_amo.addClass('hidden'); } if (data.hasOwnProperty('uploaded')) { status_el.set('data-uploaded', data.uploaded); if (data.uploaded) { // remove ability to upload var li_anchor = $$('.upload_link')[0], anchor = li_anchor.getElement('a'); li_anchor.set('text', anchor.get('text')); anchor.destroy(); li_anchor.removeClass('UI_AMO_Version_Uploaded').removeClass('UI_AMO_Version_Uploaded'); li_anchor.addClass('UI_AMO_Version_Uploaded'); li_anchor.highlight(); } } } });
JavaScript
0
@@ -4391,24 +4391,86 @@ content) %7B%0A + $log('FD: setting ' + className + ' ' + content);%0A
eb917751b84709aadf3bbb2f8b7e8eed70d6561a
debug start of chain with new protocol.parse
lib/stores/store.js
lib/stores/store.js
/** * @author Gilles Coomans <[email protected]> * * * TODO : * - files extensions matching optimisation * - add optimised mode that do not return deep chain handle for any HTTP verb (to be used when stores are used from within a chain) * - check range object usage in chain * * * * - CLONE STORES : reset and initialised = false */ if (typeof define !== 'function') { var define = require('amdefine')(module); } define(["require"], function (require) { return function(deep){ //deep.extensions = []; deep.clients = deep.client || {}; /** * start chain setted with a certain store * @example * * deep.store("json").get("/campaign/").log(); * ... * deep.store("campaign").get("?").log() * * * @class deep.store * @constructor */ deep.store = function (name) { //console.log("deep.store(name) : ",name) return deep(deep.protocol.parse(name).done(function(handler){ return handler.provider; }))//, { ignoreInit:true, ignoreOCM:true})) .store(name); }; /** * Empty class : Just there to get instanceof working (be warning with iframe issue in that cases). * @class deep.Store * @constructor */ deep.Store = function (protocol) { //console.log("deep.Store : protocol : ", protocol); if(protocol && typeof protocol === 'object') deep.utils.up(protocol, this); else this.protocol = protocol || this.protocol; if (this.protocol) deep.protocol(this.protocol, this); this._deep_store_ = true; }; deep.Store.forbidden = function(message){ return function(any, options) { return deep.when(deep.errors.Forbidden(message)); }; }; deep.store.Restrictions = function() { var restrictions = {}; for(var i in arguments) restrictions[arguments[i]] = deep.Store.forbidden(); return restrictions; }; deep.store.AllowOnly = function() { var restrictions = { get:deep.Store.forbidden(), range:deep.Store.forbidden(), post:deep.Store.forbidden(), put:deep.Store.forbidden(), patch:deep.Store.forbidden(), del:deep.Store.forbidden(), rpc:deep.Store.forbidden(), bulk:deep.Store.forbidden() }; for(var i in arguments) delete restrictions[arguments[i]]; return restrictions; }; deep.store.filterPrivate = function(method) { return function(result){ //console.log("private check : ", this, result); if(!this.schema) return result; var schema = this.schema; if(schema._deep_ocm_) schema = schema(method); var res = deep.utils.remove(result, ".//!?_schema.private=true", this.schema); return result; }; }; return deep; }; });
JavaScript
0
@@ -895,24 +895,34 @@ n deep(deep. +when(deep. protocol.par @@ -929,16 +929,17 @@ se(name) +) .done(fu
657118bc4527985740040ce14f29c9858fa290f4
Remove options from slate new command
packages/slate-cli/commands/new.js
packages/slate-cli/commands/new.js
var path = require('path'); var findRoot = require('find-root'); var utils = require('../includes/utils.js'); var msg = require('../includes/messages.js'); var slateRoot = path.resolve(__dirname, '..'); var destRoot = process.cwd(); module.exports = { command: function(args/*, options*/) { if (args.length === 0) { process.stdout.write(msg.noGenerator()); } else { var scriptArgs; switch (args[0]) { case 'theme': scriptArgs = ['generate-theme', destRoot]; if (args[1]) { scriptArgs.push(args[1]); } utils.runScript(slateRoot, scriptArgs); break; case 'section': var themeRoot = findRoot(destRoot); scriptArgs = ['generate-section', themeRoot]; if (args[1]) { scriptArgs.push(args[1]); } utils.runScript(slateRoot, scriptArgs); break; default: process.stdout.write(msg.unknownGenerator()); } } }, help: function() { utils.logHelpMsg([ 'Usage: slate new [args] [--options]', '', 'Scaffold a theme or section.', '', 'Arguments:', '', ' theme generate a theme with build tools', ' section generate a section folder' ]); } };
JavaScript
0.000001
@@ -1049,20 +1049,8 @@ rgs%5D - %5B--options%5D ',%0A
b594cd21b327ad92341bbd87ae7c5464e79459d9
Fix typo (#5223)
www/src/examples/Alert/DismissibleControlled.js
www/src/examples/Alert/DismissibleControlled.js
function AlertDismissible() { const [show, setShow] = useState(true); return ( <> <Alert show={show} variant="success"> <Alert.Heading>How's it going?!</Alert.Heading> <p> Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Cras mattis consectetur purus sit amet fermentum. </p> <hr /> <div className="d-flex justify-content-end"> <Button onClick={() => setShow(false)} variant="outline-success"> Close me ya'll! </Button> </div> </Alert> {!show && <Button onClick={() => setShow(true)}>Show Alert</Button>} </> ); } render(<AlertDismissible />);
JavaScript
0.998413
@@ -556,10 +556,10 @@ me y -a ' +a ll!%0A
c66af9262cbd224dbc3cfe70f234d2e86f6784a7
Fix batch usage memory leaks
manifest.js
manifest.js
/** * Events: * dependenciesChange(differences, manifest, user, repo, private) - When one or more dependencies for a manifest change * devDependenciesChange(differences, manifest, user, repo, private) - When one or more devDependencies for a manifest change * peerDependenciesChange(differences, manifest, user, repo, private) - When one or more peerDependencies for a manifest change * optionalDependenciesChange(differences, manifest, user, repo, private) - When one or more optionalDependencies for a manifest change * retrieve(manifest, user, repo, private) - The first time a manifest is retrieved */ var events = require("events") , moment = require("moment") , config = require("config") , registry = require("./registry") , github = require("./github") , githubUrl = require("github-url") , depDiff = require("dep-diff") , batch = require("./batch")() module.exports = exports = new events.EventEmitter() function Manifest (data, priv) { this.data = data this.private = priv // Is manifest in a private repo? this.expires = moment().add(Manifest.TTL) } Manifest.TTL = moment.duration({hours: 1}) var manifests = {} /** * Prevent JSON.parse errors from going postal and killing us all. * Currently we smother SyntaxError and the like into a more manageable null. * We may do something more clever soon. * * @param body * @return {*} */ function parseManifest (body) { try { // JSON.parse will barf with a SyntaxError if the body is ill. return JSON.parse(body) } catch (error) { return null } } exports.getManifest = function (user, repo, authToken, cb) { var manifest = manifests[user] ? manifests[user][repo] : null if (manifest && !manifest.private && manifest.expires > new Date()) { console.log("Using cached manifest", manifest.data.name, manifest.data.version) return cb(null, JSON.parse(JSON.stringify(manifest.data))) } var gh = github.getInstance(authToken) , batchKey = [user, repo, authToken].join("-") if (batch.exists(batchKey)) { return batch.push(batchKey, cb) } batch.push(batchKey, cb) gh.repos.getContent({user: user, repo: repo, path: "package.json"}, function (er, resp) { if (er) return cb(er) if (manifest && manifest.expires > new Date()) { console.log("Using cached private manifest", manifest.data.name, manifest.data.version) return batch.call(batchKey, function (cb) { cb(null, JSON.parse(JSON.stringify(manifest.data))) }) } var packageJson = new Buffer(resp.content, resp.encoding).toString() var data = parseManifest(packageJson) if (!data) { return batch.call(batchKey, function (cb) { cb(new Error("Failed to parse package.json: " + packageJson)) }) } console.log("Got manifest", data.name, data.version) if (!authToken) { // There was no authToken so MUST be public onGetRepo(null, {"private": false}) } else { // Get repo info so we can determine private/public status gh.repos.get({user: user, repo: repo}, onGetRepo) } function onGetRepo (er, repoData) { if (er) return console.error("Failed to get repo data", user, repo, er) var oldManifest = manifest manifest = new Manifest(data, repoData.private) manifests[user] = manifests[user] || {} manifests[user][repo] = manifest batch.call(batchKey, function (cb) { cb(null, manifest.data) }) if (!oldManifest) { exports.emit("retrieve", manifest.data, user, repo, repoData.private) } else { var oldDependencies = oldManifest ? oldManifest.data.dependencies : {} , oldDevDependencies = oldManifest ? oldManifest.data.devDependencies : {} , oldPeerDependencies = oldManifest ? oldManifest.data.peerDependencies : {} , oldOptionalDependencies = oldManifest ? oldManifest.data.optionalDependencies : {} var diffs = depDiff(oldDependencies, data.dependencies) if (diffs.length) { exports.emit("dependenciesChange", diffs, manifest.data, user, repo, repoData.private) } diffs = depDiff(oldDevDependencies, data.devDependencies) if (diffs.length) { exports.emit("devDependenciesChange", diffs, manifest.data, user, repo, repoData.private) } diffs = depDiff(oldPeerDependencies, data.peerDependencies) if (diffs.length) { exports.emit("peerDependenciesChange", diffs, manifest.data, user, repo, repoData.private) } diffs = depDiff(oldOptionalDependencies, data.optionalDependencies) if (diffs.length) { exports.emit("optionalDependenciesChange", diffs, manifest.data, user, repo, repoData.private) } } } }) } /** * Set the TTL for cached manifests. * * @param {moment.duration} duration Time period the manifests will be cahced for, expressed as a moment.duration. */ exports.setCacheDuration = function (duration) { Manifest.TTL = duration } // When a user publishes a project, they likely updated their project dependencies registry.on("change", function (change) { var info = githubUrl(change.doc.repository, config.github.host) // Expire the cached manifest for this user/repo if (info && manifests[info.user] && manifests[info.user][info.project]) { console.log("Expiring cached manifest", info.user, info.project) manifests[info.user][info.project].expires = moment() } })
JavaScript
0.000007
@@ -2208,21 +2208,129 @@ er) -return cb(er) +%7B%0A console.error(%22Failed to get package.json%22, er)%0A return batch.call(batchKey, function (cb) %7B cb(er) %7D)%0A %7D %0A%0A @@ -2729,24 +2729,91 @@ f (!data) %7B%0A + console.error(%22Failed to parse package.json: %22, packageJson)%0A return @@ -3307,22 +3307,25 @@ if (er) -return +%7B%0A console @@ -3373,16 +3373,86 @@ epo, er) +%0A return batch.call(batchKey, function (cb) %7B cb(er) %7D)%0A %7D %0A%0A
ba333dc4b0df6bedce3f9048fa20138e19b9c6d6
rework export order
docs/color-variables.js
docs/color-variables.js
import titleCase from 'title-case' import primerColors from 'primer-colors' import colorSystemSCSS from '!!raw-loader?module!../src/support/variables/color-system.scss' import colorVariablesSCSS from '!!raw-loader?module!../src/support/variables/colors.scss' export const variables = {} parseSCSSVariables(colorSystemSCSS, variables) parseSCSSVariables(colorVariablesSCSS, variables) // XXX we don't necessarily define them in this order in primer-colors, // so we define an array here just to be safe export const gradientHues = ['gray', 'blue', 'green', 'purple', 'yellow', 'orange', 'red', 'pink'] export const colors = { ...primerColors, pink: Object.keys(variables) .filter(key => key.startsWith('pink-')) .sort() .map(key => variables[key]) } export const gradientPalettes = gradientHues.map(name => { const bgClass = `bg-${name}` const textClass = `text-${name}` return { name, title: titleCase(name), value: colors[name][5], bg: variables[bgClass] ? {className: bgClass, value: variables[bgClass]} : null, fg: variables[textClass] ? {className: textClass, value: variables[textClass]} : null, values: colors[name].map((value, index) => ({ value, index, variable: `${name}-${index}00`, slug: `${name}-${index}` })) } }) export const backgroundPalettes = gradientPalettes .filter(palette => palette.bg) .map(({name, values, bg, ...paletteRest}) => ({ name, ...paletteRest, className: bg.className, value: bg.value, values: values.map(value => ({...value, className: `bg-${value.slug}`})) })) export const foregroundPalettes = gradientPalettes .filter(palette => palette.fg) .map(({name, values, fg, ...paletteRest}) => ({ name, ...paletteRest, className: fg.className, value: fg.value, values: values.map(value => ({...value, className: `color-${value.slug}`})) })) export function getBackgroundPalette(name) { return backgroundPalettes.find(palette => palette.name === name) } export function getForegroundPalette(name) { return foregroundPalettes.find(palette => palette.name === name) } function parseSCSSVariables(scssString, variables = {}) { const variablePattern = /\$([-\w]+):\s*(.+)( !default);/g let match do { match = variablePattern.exec(scssString) if (match) { // eslint-disable-next-line no-unused-vars const [_, name, value] = match variables[name] = value.startsWith('$') ? variables[value.substr(1)] : value } } while (match) return variables }
JavaScript
0
@@ -254,23 +254,16 @@ .scss'%0A%0A -export const va @@ -492,23 +492,16 @@ be safe%0A -export const gr @@ -585,23 +585,16 @@ pink'%5D%0A%0A -export const co @@ -743,23 +743,36 @@ ey%5D)%0A%7D%0A%0A -export +const aliases = %7B%7D%0A%0A const gr @@ -1278,16 +1278,55 @@ %7Bindex%7D%60 +,%0A aliases: (aliases%5Bvalue%5D = %7B%7D), %0A %7D)) @@ -1334,23 +1334,16 @@ %7D%0A%7D)%0A%0A -export const ba @@ -1625,23 +1625,16 @@ %0A %7D))%0A%0A -export const fo @@ -1919,23 +1919,395 @@ %0A %7D))%0A%0A -export +for (const key of Object.keys(variables)) %7B%0A const match = key.match(/%5E(bg%7Ctext%7Cborder)-(%5Cw+)(?!-(light%7Cdark))?$/)%0A if (match) %7B%0A const %5B_, type, name, suffix%5D = match%0A aliases%5Bvalue%5D%5Btype%5D = %60.$%7Bkey%7D%60%0A %7D%0A%7D%0A%0Aexport %7B%0A colors,%0A gradientHues,%0A gradientPalettes,%0A backgroundPalettes,%0A foregroundPalettes,%0A variables,%0A getForegroundPalette,%0A getBackgroundPalette%0A%7D%0A%0A function @@ -2406,23 +2406,16 @@ ame)%0A%7D%0A%0A -export function
93e92a6f10c453f6d601d87f54660f647bbc8d03
add userAgent to client id.
public/js/app-middle.js
public/js/app-middle.js
(function (window, io, $, _, Backbone, location, app) { // "use strict"; var ID = "id", watchedEvents = {}; app.middle = app.middle || {}; function getServerURL() { //For now, we are assuming that socket.io is hosted locally. return ""; } function convert(arg) { try { return JSON.stringify(arg); } catch (e) { var simpified = {}; _.each(arg, function (entry, key) { if (entry !== window) { simpified[key] = entry; } }); return convert(simpified); } } function log(socket, level, loggingLevel, _args) { var logToServer = false; if('error' === loggingLevel === level) { logToServer = true; console.error.apply(console, _args); } else if ('debug' === loggingLevel) { logToServer = true; console.log.apply(console, _args); } if(logToServer) { var args = Array.prototype.slice.call(_args), params = [ "log", level, new Date() ]; _.each(args, function (arg) { var param = convert(arg); params.push(param); }); return socket.emit.apply(socket, params); } } function emitter(socket) { return function () { return socket.emit.apply(socket, arguments); }; } function connect(url, cb) { try { return cb(io.connect(url, { "reconnection limit":4001, // four second max delay "max reconnection attempts":Infinity, "match origin protocol": true, "force new connection":true })); } catch (e) { setTimeout(function () { connect(url, cb); }, 500); return app.error("io.connect exception", e); } } function openSocket(cb) { var tryAgain = function () { if (cb) { app.log("middle trying to connect again"); setTimeout(function () { openSocket(cb); }, 500); } }, app_log = app.log, app_debug = app.debug, app_error = app.error, url = getServerURL(); return connect(url, function (socket) { socket.on('error', function (err) { app.error("middle socket error", err); tryAgain(); }); socket.on('connecting', function () { return app.log("middle connecting"); }); socket.on('connect_failed', function (err) { app.error("connect_failed", err); tryAgain(); }); socket.on('reconnect', function () { return app.log("middle reconnect"); }); socket.on('reconnecting', function () { return app.log("middle reconnecting"); }); socket.on('connect', function () { app.middle.connected = true; var _cb = cb, device = window.device || {}; cb = undefined; socket.emit("middle-initialize", { id:app.middle.id, uuid:device.uuid, name:device.name, platform:device.platform, version:device.version, cordova:device.cordova }, function(err, result) { app.log = function () { return log(socket, "info", result.loggingLevel, arguments); }; app.debug = function () { return log(socket, "debug", result.loggingLevel, arguments); }; app.error = function () { return log(socket, "error", result.loggingLevel, arguments); }; app.log("middle connected"); return _cb && _cb(socket); }); }); socket.on('disconnect', function () { app.middle.connected = false; app.log = app_log; app.debug = app_debug; app.error = app_error; app.middle.trigger("disconnect", app.middle.id); return app.log("disconnected", app.middle.id); }); }); } app.starter.$(function (next) { if (app.middle.disable) { return next(); } app.store("middle", function (store) { store.get(ID, function (id) { app.middle.id = (id && id.id) || app.utils.uuid(); if (!id) { store.save(ID, app.middle.id); } var bindSocketListeners = function(socket) { app.middle.bind = app.middle.on = app.middle.on || function (event, callback, context) { var events = event.split(/\s+/); _.each(events, function (event) { if (!watchedEvents[event]) { watchedEvents[event] = true; socket.on(event, function () { var args = Array.prototype.slice.call(arguments); args.unshift(event); return app.middle.trigger.apply(app.middle, args); }); } }); Backbone.Events.on.call(app.middle, event, callback, context); }; app.middle.unbind = app.middle.off = app.middle.off || function () { Backbone.Events.off.apply(app.middle, arguments); }; app.middle.trigger = app.middle.trigger = app.middle.trigger || function () { Backbone.Events.trigger.apply(app.middle, arguments); }; app.middle.stop = function() { console.log("disconnect"); socket.disconnect(); }; app.middle.restart = function() { console.log("restart"); if(socket) { socket.connect(); } else { openSocket(function (socket) { bindSocketListeners(socket); }); } }; app.middle.emit = emitter(socket); }; return openSocket(function (socket) { bindSocketListeners(socket); return next(); }); }); }); }); })(window, window.io, $, _, Backbone, window.location, window["jolira-app"]);
JavaScript
0
@@ -3383,24 +3383,83 @@ ow.device %7C%7C + %7B%7D,%0A userAgent = navigator.userAgent %7C%7C %7B%7D;%0A%0A @@ -3782,16 +3782,58 @@ .cordova +,%0A userAgent: userAgent %0A