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
f873636cba88db1f9a7a014cdf4516ccccb5087d
Update nocache.js
skyline/Scripts/nocache.js
skyline/Scripts/nocache.js
window.onload = function() { var el = document.createElement('script'); el.src = "Scripts/script.js?nocache=" + (new Date()).getTime(); document.head.appendChild(el); console.log('nochache.js finsihed'); }
JavaScript
0.000001
@@ -202,17 +202,16 @@ 'noc -h ache.js fins @@ -210,18 +210,18 @@ .js -finsih +execut ed');%0D%0A%7D @@ -220,8 +220,10 @@ ed');%0D%0A%7D +%0D%0A
d6862293c6ad81fabffebb6d0fd5b02e17bd1224
Include mocha lazily, production env might not have it
cli/test.js
cli/test.js
// Run tests & exit // 'use strict'; const _ = require('lodash'); const glob = require('glob'); const Mocha = require('mocha'); const path = require('path'); //////////////////////////////////////////////////////////////////////////////// module.exports.parserParameters = { add_help: true, help: 'run test suites', description: 'Run all tests of enabled apps' }; module.exports.commandLineArguments = [ { args: [ 'app' ], options: { metavar: 'APP_NAME', help: 'Run tests of specific application only', nargs: '?', default: null } }, { args: [ '-m', '--mask' ], options: { dest: 'mask', help: 'Run only tests, containing MASK in name', type: 'string', default: [] } } ]; //////////////////////////////////////////////////////////////////////////////// module.exports.run = async function (N, args) { if (!process.env.NODECA_ENV) { throw 'You must provide NODECA_ENV in order to run nodeca test'; } // Expose N to globals for tests global.TEST = { N }; await Promise.resolve() .then(() => N.wire.emit('init:models', N)) .then(() => N.wire.emit('init:bundle', N)) .then(() => N.wire.emit('init:services', N)) .then(() => N.wire.emit('init:tests', N)); let mocha = new Mocha({ timeout: 60000 }); let applications = N.apps; mocha.reporter('spec'); // mocha.ui('bdd'); // if app set, check that it's valid if (args.app) { if (!_.find(applications, app => app.name === args.app)) { let msg = `Invalid application name: ${args.app}\n` + 'Valid apps are: ' + _.map(applications, app => app.name).join(', '); throw msg; } } let testedApps = []; if (args.app) { // if app is defined, add it and all modules recursively applications.filter(app => args.app === app.name).forEach(function addApp(app) { testedApps.push(app); app.config.modules.forEach(m => { let modulePath = path.join(app.root, m); applications.filter(app => app.root === modulePath).forEach(addApp); }); }); } else { // otherwise test all applications testedApps = applications; } _.forEach(testedApps, app => { glob.sync('**', { cwd: app.root + '/test' }) // skip files when // - filename starts with _, e.g.: /foo/bar/_baz.js // - dirname in path starts _, e.g. /foo/_bar/baz.js .filter(name => !/^[._]|\\[._]|\/[_.]/.test(name)) .forEach(file => { // try to filter by pattern, if set if (args.mask && path.basename(file).indexOf(args.mask) === -1) { return; } if ((/\.js$/).test(file) && path.basename(file)[0] !== '.') { mocha.files.push(`${app.root}/test/${file}`); } }); }); await new Promise((resolve, reject) => { mocha.run(err => (err ? reject(err) : resolve())); }); await N.wire.emit('exit.shutdown'); };
JavaScript
0
@@ -105,42 +105,8 @@ ');%0A -const Mocha = require('mocha');%0A cons @@ -1266,16 +1266,55 @@ , N));%0A%0A + let Mocha = require('mocha');%0A let mo
8c9e6a85e63891fc0e3ea852268e4979d8b8302a
add solution
Algorithms/JS/arrays/matrices/rotateImage.js
Algorithms/JS/arrays/matrices/rotateImage.js
// You are given an n x n 2D matrix representing an image. // Rotate the image by 90 degrees (clockwise). // Follow up: // Could you do this in-place?
JavaScript
0.000003
@@ -146,8 +146,526 @@ -place?%0A +%0A%0Avar rotate = function(matrix) %7B%0A var rows = matrix.length,%0A col = matrix.length;%0A%0A for (var i = 0; i %3C rows; i++)%7B%0A for (var j = i + 1; j %3C col; j++)%7B%0A var temp = matrix%5Bi%5D%5Bj%5D;%0A matrix%5Bi%5D%5Bj%5D = matrix%5Bj%5D%5Bi%5D;%0A matrix%5Bj%5D%5Bi%5D = temp;%0A %7D%0A %7D%0A%0A for (i = 0; i %3C rows; i++)%7B%0A for (j = 0; j %3C col / 2; j++)%7B%0A temp = matrix%5Bi%5D%5Bj%5D;%0A matrix%5Bi%5D%5Bj%5D = matrix%5Bi%5D%5Bcol - 1 - j%5D;%0A matrix%5Bi%5D%5Bcol - 1 - j%5D = temp;%0A %7D%0A %7D%0A%7D;%0A
9085ef9f4172c28097f6fa78d4555095c1643b52
Remove AddMethods module, since all we do is load and enable.
extensions/Accessibility-Extension.js
extensions/Accessibility-Extension.js
// // Thin hook to include the accessibility extension. // (function(HUB,EXTENSIONS) { var SETTINGS = HUB.config.menuSettings; var ITEM, MENU; // filled in when MathMenu extension loads var BIND = (Function.prototype.bind ? function (f,t) {return f.bind(t)} : function (f,t) {return function () {f.apply(t,arguments)}}); var KEYS = Object.keys || function (obj) { var keys = []; for (var id in obj) {if (obj.hasOwnProperty(id)) keys.push(id)} return keys; }; var Accessibility = EXTENSIONS.Accessibility = { version: '1.0', prefix: '', //'Accessibility-', default: {}, modules: [], MakeOption: function(name) { return Accessibility.prefix + name; }, GetOption: function(option) { return SETTINGS[Accessibility.MakeOption(option)]; }, AddDefaults: function() { var keys = KEYS(Accessibility.default); for (var i = 0, key; key = keys[i]; i++) { var option = Accessibility.MakeOption(key); if (typeof(SETTINGS[option]) === 'undefined') { SETTINGS[option] = Accessibility.default[key]; } } }, // Attaches the menu items; AddMenu: function() { var items = Array(this.modules.length); for (var i = 0, module; module = this.modules[i]; i++) items[i] = module.placeHolder; var about = MENU.IndexOfId('About'); if (about === null) { items.unshift(ITEM.RULE()); MENU.items.push.apply(MENU.items, items); } else { items.push(ITEM.RULE()); items.unshift(about, 0); MENU.items.splice.apply(MENU.items, items); } }, Register: function(module) { Accessibility.default[module.option] = false; Accessibility.modules.push(module); }, Startup: function() { ITEM = MathJax.Menu.ITEM; MENU = MathJax.Menu.menu; for (var i = 0, module; module = this.modules[i]; i++) { module.CreateMenu(); module.AddMethods(); } this.AddMenu(); }, LoadExtensions: function () { var extensions = []; for (var i = 0, mpdule; module = this.modules[i]; i++) { if (SETTINGS[module.option]) extensions.push(module.module); } return (extensions.length ? HUB.Startup.loadArray(extensions) : null); } }; var ModuleLoader = MathJax.Extension.ModuleLoader = MathJax.Object.Subclass({ option: '', name: '', module: '', placeHolder: null, submenu: false, extension: null, Enable: null, Disable: null, Init: function(option, name, module, extension, submenu) { this.option = option; this.name = [name.replace(/ /g,''),name]; this.module = module; this.extension = extension; this.submenu = (submenu || false); }, CreateMenu: function() { var load = BIND(this.Load,this); if (this.submenu) { this.placeHolder = ITEM.SUBMENU(this.name, ITEM.CHECKBOX(["Activate","Activate"], Accessibility.MakeOption(this.option), {action: load}), ITEM.RULE(), ITEM.COMMAND(["OptionsWhenActive","(Options when Active)"],null,{disabled:true}) ); } else { this.placeHolder = ITEM.CHECKBOX( this.name, Accessibility.MakeOption(this.option), {action: load} ); } }, Load: function() { HUB.Queue(["Require",MathJax.Ajax,this.module,["AddMethods",this,true]]); }, AddMethods: function(menu) { var ext = MathJax.Extension[this.extension]; if (ext) { this.Enable = BIND(ext.Enable,ext); this.Disable = BIND(ext.Disable,ext); if (menu) { this.Enable(true,true); MathJax.Menu.saveCookie(); } } } }); HUB.Register.StartupHook('End Extensions', function () { HUB.Register.StartupHook('MathMenu Ready', function () { Accessibility.Startup(); HUB.Startup.signal.Post('Accessibility Loader Ready'); },5); // run before other extensions' menu hooks even if they are loaded first },5); Accessibility.Register( ModuleLoader( 'collapsible', 'Collapsible Math', '[RespEq]/Semantic-Complexity.js', 'SemanticComplexity' ) ); Accessibility.Register( ModuleLoader( 'autocollapse', 'Auto Collapse', '[RespEq]/Semantic-Collapse.js', 'SemanticCollapse' ) ); Accessibility.Register( ModuleLoader( 'explorer', 'Accessibility', '[RespEq]/Assistive-Explore.js', 'Assistive', true ) ); Accessibility.AddDefaults(); MathJax.Callback.Queue( ["LoadExtensions",Accessibility], ["loadComplete",MathJax.Ajax,"[RespEq]/Accessibility-Extension.js"] ); })(MathJax.Hub,MathJax.Extension);
JavaScript
0
@@ -1913,26 +1913,16 @@ i%5D; i++) - %7B%0A module. @@ -1939,45 +1939,8 @@ ();%0A - module.AddMethods();%0A %7D%0A @@ -2360,19 +2360,24 @@ name: +%5B '', +''%5D, %0A mod @@ -2453,45 +2453,8 @@ ll,%0A - Enable: null,%0A Disable: null,%0A @@ -3356,29 +3356,20 @@ e,%5B%22 -AddMethods +Enable %22,this -,true %5D%5D); @@ -3384,18 +3384,14 @@ -AddMethods +Enable : fu @@ -3418,16 +3418,22 @@ var ext +ension = MathJ @@ -3479,118 +3479,14 @@ (ext -) %7B%0A this.Enable = BIND(ext.Enable,ext);%0A this.Disable = BIND(ext.Disable,ext);%0A if (menu +ension ) %7B%0A @@ -3493,22 +3493,25 @@ - -this +extension .Enable( @@ -3518,26 +3518,24 @@ true,true);%0A - Math @@ -3557,26 +3557,16 @@ okie();%0A - %7D%0A %7D%0A
b7965e101ad77b65aa60ef9a452fa7efe5d2641a
Remove the outer function
responav.js
responav.js
(function($){ $.fn.responav = function(options) { var settings = $.extend({ breakpoint : 720, trigger : true }, options); var menu = $(this); var hasTrigger = false; $(window).on('resize.responav', function () { var browserWidth = $(window).width(); if (browserWidth < settings.breakpoint) { $('body').addClass('responav-active'); menu.addClass('responav-menu'); if (!hasTrigger && settings.trigger) { $('.responav-inner').prepend('<button class="responav-trigger" id="responav-trigger"></button>'); hasTrigger = true; } } else { $('body').removeClass('responav-active'); menu.removeClass('responav-menu'); if (hasTrigger) { $('#responav-trigger').remove(); hasTrigger = false; } } }).trigger('resize'); $(document).on('click.responav touchstart.responav', '#responav-trigger', function(event) { $('body').toggleClass('responav-open'); $(document).one(event.type, function() { $('body').removeClass('responav-open'); }); return false; }); menu.on("click touchstart", function(e) { e.stopPropagation(); }); return this; }; })($);
JavaScript
0.000076
@@ -1,20 +1,4 @@ -(function($)%7B%0A%0A%09 $.fn @@ -30,17 +30,16 @@ ons) %7B%0A%0A -%09 %09var set @@ -57,17 +57,16 @@ xtend(%7B%0A -%09 %09%09breakp @@ -79,17 +79,16 @@ 720,%0A%09%09 -%09 trigger @@ -94,17 +94,16 @@ : true%0A -%09 %09%7D, opti @@ -109,17 +109,16 @@ ions);%0A%0A -%09 %09var men @@ -130,17 +130,16 @@ (this);%0A -%09 %09var has @@ -156,17 +156,16 @@ false;%0A%0A -%09 %09$(windo @@ -205,17 +205,16 @@ () %7B%0A%09%09 -%09 var brow @@ -243,17 +243,16 @@ idth();%0A -%09 %09%09if (br @@ -286,25 +286,24 @@ point) %7B%0A%09%09%09 -%09 $('body').ad @@ -328,25 +328,24 @@ ctive');%0A%09%09%09 -%09 menu.addClas @@ -360,25 +360,24 @@ nav-menu');%0A -%09 %09%09%09if (!hasT @@ -410,17 +410,16 @@ ) %7B%0A%09%09%09%09 -%09 $('.resp @@ -508,17 +508,16 @@ ton%3E');%0A -%09 %09%09%09%09hasT @@ -534,20 +534,18 @@ rue;%0A%09%09%09 -%09 %7D%0A -%09 %09%09%7D else @@ -547,17 +547,16 @@ else %7B%0A -%09 %09%09%09$('bo @@ -595,17 +595,16 @@ e');%0A%09%09%09 -%09 menu.rem @@ -630,17 +630,16 @@ menu');%0A -%09 %09%09%09if (h @@ -655,17 +655,16 @@ ) %7B%0A%09%09%09%09 -%09 $('#resp @@ -692,17 +692,16 @@ ();%0A%09%09%09%09 -%09 hasTrigg @@ -719,17 +719,14 @@ %0A%09%09%09 -%09 %7D%0A -%09 %09%09%7D%0A -%09 %09%7D). @@ -745,17 +745,16 @@ ize');%0A%0A -%09 %09$(docum @@ -834,25 +834,24 @@ on(event) %7B%0A -%09 %09%09$('body'). @@ -882,17 +882,16 @@ en');%0A%09%09 -%09 $(docume @@ -919,25 +919,24 @@ unction() %7B%0A -%09 %09%09%09$('body') @@ -972,14 +972,12 @@ ;%0A%09%09 -%09 %7D);%0A -%09 %09%09re @@ -988,24 +988,22 @@ false;%0A -%09 %09%7D);%0A%0A -%09 %09menu.on @@ -1009,16 +1009,25 @@ n(%22click +.responav touchst @@ -1029,16 +1029,25 @@ uchstart +.responav %22, funct @@ -1055,17 +1055,16 @@ on(e) %7B%0A -%09 %09%09e.stop @@ -1082,16 +1082,14 @@ ();%0A -%09 %09%7D);%0A%0A -%09 %09ret @@ -1102,14 +1102,6 @@ is;%0A -%09 %7D; -%0A%7D)($);
b01a21b37f18151755da2a270eed634c2abd1ecf
Remove unused fs.
src/make-webpack-config.js
src/make-webpack-config.js
var fs = require('fs'); var path = require('path'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var Initial = require('postcss-initial'); var merge = require('webpack-merge'); var prettyjson = require('prettyjson'); var getInstalledPath = require('get-installed-path'); var config = require('../src/utils/config'); module.exports = function(env) { var isProd = env === 'production'; var cssLoader = 'css?modules&importLoaders=1&localIdentName=ReactStyleguidist-[name]__[local]!postcss'; var codeMirrorPath = getInstalledPath('codemirror', true); var reactTransformPath = getInstalledPath('babel-plugin-react-transform', true); var includes = [ __dirname, config.rootDir ]; var webpackConfig = { output: { path: config.styleguideDir, filename: 'build/bundle.js' }, resolve: { root: path.join(__dirname), extensions: ['', '.js', '.jsx'], modulesDirectories: [ path.resolve(__dirname, '../node_modules'), 'node_modules' ], alias: { 'codemirror': codeMirrorPath } }, resolveLoader: { modulesDirectories: [ path.resolve(__dirname, '../loaders'), path.resolve(__dirname, '../node_modules'), 'node_modules' ] }, plugins: [ new HtmlWebpackPlugin({ title: config.title, template: config.template, inject: true }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(env) } }) ], module: { loaders: [ ], noParse: [ /babel-core\/browser.js/ ] }, postcss: function() { return [ Initial({ reset: 'inherited' }) ]; } }; var entryScript = path.join(__dirname, 'index'); if (isProd) { webpackConfig = merge(webpackConfig, { entry: [ entryScript ], devtool: false, debug: false, cache: false, plugins: [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, output: { comments: false }, mangle: false }), new webpack.optimize.DedupePlugin(), new ExtractTextPlugin('build/styles.css', { allChunks: true }) ], module: { loaders: [ { test: /\.jsx?$/, include: includes, loader: 'babel', query: { stage: 0 } }, { test: /\.json$/, loader: 'json' }, { test: /\.css$/, include: codeMirrorPath, loader: ExtractTextPlugin.extract('style', 'css') }, { test: /\.css$/, include: includes, loader: ExtractTextPlugin.extract('style', cssLoader) } ] } }); } else { webpackConfig = merge(webpackConfig, { entry: [ 'webpack-hot-middleware/client', entryScript ], debug: true, cache: true, devtool: 'eval-source-map', stats: { colors: true, reasons: true }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], module: { loaders: [ { test: /\.jsx?$/, include: includes, loader: 'babel', query: { stage: 0, plugins: [ reactTransformPath ], extra: { 'react-transform': { transforms: [ { transform: 'react-transform-hmr', imports: ['react'], locals: ['module'] }, { transform: 'react-transform-catch-errors', imports: ['react', 'redbox-react'] } ] } } } }, { test: /\.json$/, loader: 'json' }, { test: /\.css$/, include: codeMirrorPath, loader: 'style!css' }, { test: /\.css$/, include: includes, loader: 'style!' + cssLoader } ] } }); } if (config.updateWebpackConfig) { webpackConfig = config.updateWebpackConfig(webpackConfig, env); } if (config.verbose) { console.log(); console.log('Using Webpack config:'); console.log(prettyjson.render(webpackConfig)); console.log(); } return webpackConfig; };
JavaScript
0
@@ -1,28 +1,4 @@ -var fs = require('fs');%0A var
d909a8988ff366f69a0ba4f8e9733f99f38f1425
Fix crash on delete in private message
src/Utility/DeletedMessage.js
src/Utility/DeletedMessage.js
const BotModule = require('../BotModule'); module.exports = BotModule.extend({ config: null, i18n: null, dependencies: { 'config': 'config', 'i18n': 'i18n', }, initialize: function (dependencyGraph) { this._super(dependencyGraph); this.discordClient.on('messageDelete', message => { message.guild.channels.find('id', this.config.deletedLogsRoom).send({ embed: { color: 0xff0000, title: this.i18n.__mf("Deleted message authored by @{username}#{discriminator}", {username: message.author.username, discriminator: message.author.discriminator}), description: message.content, timestamp: new Date(), footer: { icon_url: this.discordClient.user.avatarURL, text: "Shotbow Chat Bot" } } }) .catch(error => console.log("Not enough permissions to send a message to the moderation room.")); }); } });
JavaScript
0
@@ -329,16 +329,63 @@ ge =%3E %7B%0A + if (message.guild == null) return;%0A
75c8628f03009aa121b6047bc928ad181b34a48d
update server url
server/public/js/client.js
server/public/js/client.js
// Convert numbers to words // copyright 25th July 2006, by Stephen Chapman http://javascript.about.com // permission to use this Javascript on your web page is granted // provided that all of the code (including this copyright notice) is // used exactly as shown (you can change the numbering system if you wish) // http://javascript.about.com/library/bltoword.htm // American Numbering System var th = ['','thousand','million', 'billion','trillion']; // uncomment this line for English Number System // var th = ['','thousand','million', 'milliard','billion']; var dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine']; var tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen']; var tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety']; function toWords(s){s = s.toString(); s = s.replace(/[\, ]/g,''); if (s != parseFloat(s)) return 'not a number'; var x = s.indexOf('.'); if (x == -1) x = s.length; if (x > 15) return 'too big'; var n = s.split(''); var str = ''; var sk = 0; for (var i=0; i < x; i++) {if ((x-i)%3==2) {if (n[i] == '1') {str += tn[Number(n[i+1])] + ' '; i++; sk=1;} else if (n[i]!=0) {str += tw[n[i]-2] + ' ';sk=1;}} else if (n[i]!=0) {str += dg[n[i]] +' '; if ((x-i)%3==0) str += 'hundred ';sk=1;} if ((x-i)%3==1) {if (sk) str += th[(x-i-1)/3] + ' ';sk=0;}} if (x != s.length) {var y = s.length; str += 'point '; for (var i=x+1; i<y; i++) str += dg[n[i]] +' ';} return str.replace(/\s+/g,' ');} var serverurl = 'http://tpehack.no-ip.biz:12000' var checkinlink = serverurl+'/inspace'; var peopleheader = '<tr id="peoplelistheader"><td><strong>Name</strong></td><td><strong>Arrival</strong></td></tr>'; var peopleupdateinterval = 2 * 1000; //ms var getPeople = function() { $.ajax({ url: checkinlink, crossDomain: true }).done(function(data) { var people = data.people; if (people.length > 0) { var table = peopleheader; for (var i = 0; i < people.length; i++) { var name = people[i].name; var date = moment(people[i].checkin); if (name == '') { name = 'No name person'; } table += "<tr><td>"+name+"</td><td><span>"+date.fromNow()+" ("+date.format('MMMM Do YYYY, h:mm:ss a')+")</td></tr>\n"; } $("#peopletable").html(table); $('#peopletable').show(); $('#noone').hide(); } else { $('#peopletable').hide(); $('#noone').show(); } // <!-- setTimeout(function() { getPeople(); }, peopleupdateinterval); --> }); }; $(document).ready(function() { // $('#peopletable').hide(); // $('#noone').show(); var andJoin = function(list) { if (list.length > 1) { var partlist = list.slice(0, list.length-1); out = partlist.join(', ')+', and '+list[list.length-1]; } else if (list.length == 1) { out = list[0]; } else { out = ''; } return(out); } var displayCheckin = function(people) { var names = []; var nonames = 0; for (var i = 0; i < people.length; i++) { if (people[i].name == '') { nonames++; } else { names.push("<strong>"+people[i].name+"</strong>"); } } var text = ''; var totalcount = nonames + names.length; if (totalcount == 0) { text = 'Right now <strong>no-one</strong> is checked in the Hackerspace.'; } else { var verb = 'are'; var noun = 'people'; if (totalcount == 1) { verb = 'is'; noun = 'person'; } text = 'Right now there '+verb+' <strong>'+toWords(totalcount)+' '+noun+'</strong> checked in the Hackerspace'; if (names.length == 0) { text += '.'; } else { var noun = 'people'; if (nonames == 1) { noun = 'person' } if (nonames > 0) { var otherpeople = toWords(nonames) + ' other ' + noun; names.push(otherpeople); } text += ": "+andJoin(names)+'.'; } } $("#checkinlist").html(text); } var socket = io.connect(serverurl); socket.on('people', function (data) { displayCheckin(data.people); }); });
JavaScript
0.000001
@@ -1528,19 +1528,20 @@ r server -url +base = 'http @@ -1564,14 +1564,46 @@ .biz -:12000 +'%0Avar serverurl = serverbase+'/checkin '%0Ava @@ -3912,19 +3912,20 @@ t(server -url +base );%0A s
ae480de6e65f4935faecc363c3d9485e3ab95a71
Make `all`, `allSettled`, `race` helpers support to cancel promises with `__ec_cancel__` outside an task.
addon/-yieldables.js
addon/-yieldables.js
import Ember from 'ember'; import TaskInstance from './-task-instance'; const RSVP = Ember.RSVP; /** * A cancelation-aware variant of [Promise.all](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all). * The normal version of a `Promise.all` just returns a regular, uncancelable * Promise. The `ember-concurrency` variant of `all()` has the following * additional behavior: * * - if the task that `yield`ed `all()` is canceled, any of the * {@linkcode TaskInstance}s passed in to `all` will be canceled * - if any of the {@linkcode TaskInstance}s (or regular promises) passed in reject (or * are canceled), all of the other unfinished `TaskInstance`s will * be automatically canceled. * * [Check out the "Awaiting Multiple Child Tasks example"](/#/docs/examples/joining-tasks) * * @param {function} generatorFunction the generator function backing the task. * @returns {TaskProperty} */ export let all = taskAwareVariantOf(RSVP.Promise, 'all'); /** * A cancelation-aware variant of [RSVP.allSettled](http://emberjs.com/api/classes/RSVP.html#method_allSettled). * The normal version of a `RSVP.allSettled` just returns a regular, uncancelable * Promise. The `ember-concurrency` variant of `allSettled()` has the following * additional behavior: * * - if the task that `yield`ed `allSettled()` is canceled, any of the * {@linkcode TaskInstance}s passed in to `allSettled` will be canceled * * @param {function} generatorFunction the generator function backing the task. * @returns {TaskProperty} */ export let allSettled = taskAwareVariantOf(RSVP, 'allSettled'); /** * A cancelation-aware variant of [Promise.race](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race). * The normal version of a `Promise.race` just returns a regular, uncancelable * Promise. The `ember-concurrency` variant of `race()` has the following * additional behavior: * * - if the task that `yield`ed `race()` is canceled, any of the * {@linkcode TaskInstance}s passed in to `race` will be canceled * - once any of the tasks/promises passed in complete (either success, failure, * or cancelation), any of the {@linkcode TaskInstance}s passed in will be canceled * * [Check out the "Awaiting Multiple Child Tasks example"](/#/docs/examples/joining-tasks) * * @param {function} generatorFunction the generator function backing the task. * @returns {TaskProperty} */ export let race = taskAwareVariantOf(RSVP.Promise, 'race'); function taskAwareVariantOf(obj, method) { return function(items) { let defer = Ember.RSVP.defer(); obj[method](items).then(defer.resolve, defer.reject); let hasCancelled = false; let cancelAll = () => { if (hasCancelled) { return; } hasCancelled = true; items.forEach(it => { if (it instanceof TaskInstance) { it.cancel(); } }); }; let promise = defer.promise.finally(cancelAll); promise.__ec_cancel__ = cancelAll; return promise; }; }
JavaScript
0
@@ -2908,24 +2908,115 @@ t.cancel();%0A + %7D else if (typeof it.__ec_cancel__ === 'function') %7B%0A it.__ec_cancel__();%0A %7D%0A
9674ef4b27ebf250d9f6968cdd43e037ee509c7a
Make traverseNeedsParent message clearer.
packages/babel-messages/src/index.js
packages/babel-messages/src/index.js
/* @flow */ import * as util from "util"; /** * Mapping of messages to be used in Babel. * Messages can include $0-style placeholders. */ export const MESSAGES = { tailCallReassignmentDeopt: "Function reference has been reassigned, so it will probably be dereferenced, therefore we can't optimise this with confidence", classesIllegalBareSuper: "Illegal use of bare super", classesIllegalSuperCall: "Direct super call is illegal in non-constructor, use super.$1() instead", scopeDuplicateDeclaration: "Duplicate declaration $1", settersNoRest: "Setters aren't allowed to have a rest", noAssignmentsInForHead: "No assignments allowed in for-in/of head", expectedMemberExpressionOrIdentifier: "Expected type MemberExpression or Identifier", invalidParentForThisNode: "We don't know how to handle this node within the current parent - please open an issue", readOnly: "$1 is read-only", unknownForHead: "Unknown node type $1 in ForStatement", didYouMean: "Did you mean $1?", codeGeneratorDeopt: "Note: The code generator has deoptimised the styling of $1 as it exceeds the max of $2.", missingTemplatesDirectory: "no templates directory - this is most likely the result of a broken `npm publish`. Please report to https://github.com/babel/babel/issues", unsupportedOutputType: "Unsupported output type $1", illegalMethodName: "Illegal method name $1", lostTrackNodePath: "We lost track of this node's position, likely because the AST was directly manipulated", modulesIllegalExportName: "Illegal export $1", modulesDuplicateDeclarations: "Duplicate module declarations with the same source but in different scopes", undeclaredVariable: "Reference to undeclared variable $1", undeclaredVariableType: "Referencing a type alias outside of a type annotation", undeclaredVariableSuggestion: "Reference to undeclared variable $1 - did you mean $2?", traverseNeedsParent: "You must pass a scope and parentPath unless traversing a Program/File got a $1 node", traverseVerifyRootFunction: "You passed `traverse()` a function when it expected a visitor object, are you sure you didn't mean `{ enter: Function }`?", traverseVerifyVisitorProperty: "You passed `traverse()` a visitor object with the property $1 that has the invalid property $2", traverseVerifyNodeType: "You gave us a visitor for the node type $1 but it's not a valid type", pluginNotObject: "Plugin $2 specified in $1 was expected to return an object when invoked but returned $3", pluginNotFunction: "Plugin $2 specified in $1 was expected to return a function but returned $3", pluginUnknown: "Unknown plugin $1 specified in $2 at $3, attempted to resolve relative to $4", pluginInvalidProperty: "Plugin $2 specified in $1 provided an invalid property of $3" }; /** * Get a message with $0 placeholders replaced by arguments. */ export function get(key: string, ...args: Array<any>): string { let msg = MESSAGES[key]; if (!msg) throw new ReferenceError(`Unknown message ${JSON.stringify(key)}`); // stringify args args = parseArgs(args); // replace $0 placeholders with args return msg.replace(/\$(\d+)/g, function (str, i) { return args[i - 1]; }); } /** * Stingify arguments to be used inside messages. */ export function parseArgs(args: Array<any>): Array<string> { return args.map(function (val) { if (val != null && val.inspect) { return val.inspect(); } else { try { return JSON.stringify(val) || val + ""; } catch (e) { return util.inspect(val); } } }); }
JavaScript
0
@@ -1982,22 +1982,95 @@ File - got a $1 node +. Instead of that you tried to traverse a $1 node without passing scope and parentPath. %22,%0A
07af34f60ed2b70c4a86212b7099d5b6521c2af4
Update nodb version.
generated/server/start.nodb.js
generated/server/start.nodb.js
'use strict'; const chalk = require('chalk'); const port = (process.env.PORT || 4545); let requireApp = new Promise(function(resolve, reject) { let app = require('./app'); resolve(app); }); // Start the server requireApp .then(function(app) { app.listen(port, function() { console.log('The server is listening on port', chalk.green.bold(port), 'and loves you very much.'); console.log('Make sure you are running ' + chalk.white.bgBlack(' gulp ') + ' in another tab!'); }); }) .catch(function(err) { console.log('Problem starting up!', chalk.red(err.message)); console.log('I\'m out!'); process.kill(1); });
JavaScript
0
@@ -449,12 +449,21 @@ k(' -gulp +npm run watch ')
871e1a72ca183278674156d636a1b8cb6e2d2b72
Add spam term.
soundcloud-comments-bot.js
soundcloud-comments-bot.js
"use strict"; // Local tweet test override. var canTweetFromLocal = false; // Load libraries. var _ = require('underscore'); var wordfilter = require('wordfilter'); var SC = require('node-soundcloud'); var Twit = require('twit'); // Are we on production? Check if an important environment variable exists. function isProduction () { return (typeof(process.env.TWITTER_CONSUMER_KEY) !== 'undefined'); } // Use environment variables if we're on production, config files if we're local. if (isProduction()) { var yandexKey = process.env.YANDEX_KEY; var twitter = new Twit({ consumer_key: process.env.TWITTER_CONSUMER_KEY, consumer_secret: process.env.TWITTER_CONSUMER_SECRET, access_token: process.env.TWITTER_ACCESS_TOKEN, access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET }); SC.init({ id: process.env.SOUNDCLOUD_CLIENT_ID, secret: process.env.SOUNDCLOUD_SECRET }); } else { var yandexConfig = require('./config/yandex-config.js'), yandexKey = yandexConfig.key; var twitter = new Twit(require('./config/twitter-config.js')); SC.init(require('./config/soundcloud-config.js')); } // Load Yandex Translation API library. var translate = require('yandex-translate')(yandexKey); // Execute once upon initialization. makeAndPostTweet(); // The main process. Get a useable comment and tweet it or try again. function makeAndPostTweet () { getComment() .then(function (results) { postTweet(results); }) .catch(function (error) { console.log('ERROR:', error); makeAndPostTweet(); }); } // Get a random comment and see if it's usable. function getComment () { return new Promise (function (resolve, reject) { console.log('\n---\n'); // Pick a random comment. The API doesn't provide for this, but SoundCloud // comment IDs are sequential! There are a lot of missing comments (deleted // spam, etc.), but this has about a 40-50% success rate at finding an // actual comment, which is pretty good! var randomCommentID = String(_.random(100000000, 300000000)); // Query the SoundCloud API and filter the results. SC.get('/comments/' + randomCommentID, function(error, comment) { // console.log('\n\nFULL API RESPONSE:\n\n', comment) console.log('LOOKING FOR A COMMENT AT ID #' + randomCommentID + '…'); if (typeof(error) !== 'undefined') { reject('Comment does not exist at this ID anymore.'); } else { var comment = comment.body.trim(); console.log('FOUND A COMMENT:', comment); console.log('ANALYZING: Checking if too short…'); if (comment.length < 1) { reject('Comment is too short.'); return; } console.log('\tOK!'); console.log('ANALYZING: Checking if too long…'); if (comment.length > 141) { reject('Comment is too long'); return; } console.log('\tOK!'); console.log('ANALYZING: Checking for bad words…'); if (wordfilter.blacklisted(comment)) { reject('Comment is a reply, contains a bad word, or looks like spam.'); return; } console.log('\tOK!'); console.log('ANALYZING: Checking if is English…'); translate.detect(comment, function (error, result) { if (result.lang === 'en') { console.log('\tOK!'); console.log('SUCCESS: All checks passed! Comment is useable!'); resolve(comment); } else if (typeof(error) !== 'undefined') { reject(error); } else { reject('Comment is not in English.') } }) } }); }); } function postTweet (tweet) { if (typeof(tweet) !== 'undefined') { console.log('NOW TWEETING:', tweet); if (isProduction() || canTweetFromLocal) { twitter.post('statuses/update', { status: tweet }, function (error) { if (error) { console.log('ERROR POSTING TWEET:', error); } }); } } else { console.log('ERROR: No comment was fetched!'); } } // Tweet on a regular schedule. 8 times a day means every 3 hours. Note that // Because Heroku cycles dynos once per day, the bot's schedule will not be // regular: https://devcenter.heroku.com/articles/how-heroku-works#dyno-manager if (isProduction()) { var timesToTweetPerDay = 8; setInterval(function () { try { makeAndPostTweet(); } catch (error) { console.log('PROCESS UNSUCCESSFUL!', error); } }, (1000 * 60 * 60 * 24) / timesToTweetPerDay); } /// // Additional filters. wordfilter.addWords([ // To get a better set of comments, I'm filtering out a lot of things. // The lists below are used in addition to the default set: // https://github.com/dariusk/wordfilter/blob/master/lib/badwords.json // Promotion. 'follow', 'listen to my', 'check out', 'check my', 'subscribe', 'channel', 'my cloud', 'add me', 'profile', 'soundcloud', 'facebook', 'twitter', 'youtube', 'instagram', 'blog', 'free', 'download', // Fake comments. 'repost', 'posted', 'full support', 'fully support', // Traditional spam. 'sex', 'cam', 'dollars', 'money', 'fans', 'plays', 'get play', 'get fan', // URLs. 'http', 'www', '.co', '.net', // Replies, SoundCloud links, tags, etc. 'user-', '\@', '\n', '_', '#', // A few curses and bad words. 'fuck', 'rape', 'raping', 'gay' ]);
JavaScript
0.000001
@@ -5028,16 +5028,30 @@ rofile', +%0A 'premiere', %0A%0A 'sou
b5507be7dfdbc6c74465f7d7aca63c5e5f569c8c
Allow to use custom r.js with relative path
examples/almond-text-plugin-project/node_modules/grunt-requirejs/lib/helper/rjsversion.js
examples/almond-text-plugin-project/node_modules/grunt-requirejs/lib/helper/rjsversion.js
/* * grunt-require * https://github.com/asciidisco/grunt-requirejs * * Copyright (c) 2012 asciidisco * Licensed under the MIT license. */ exports.init = function(grunt) { 'use strict'; var fs = require('fs'); var exports = {}; // privates var isDefaultVersion = true; var requirejs = null; // Returns a requirejs instance exports.getRequirejs = function(config) { var defaultRequire = require('requirejs'); // check if we should load a custom requirejs version if (config.rjs) { var rjsPathname = config.rjs + '/bin/r.js'; // check if the custom version is available, then load & return the // custom version, else default to the standard bundled requirejs if (fs.existsSync(rjsPathname)) { requirejs = require(rjsPathname); isDefaultVersion = false; return requirejs; } } isDefaultVersion = true; requirejs = defaultRequire; return requirejs; }; // Returns the version number of the currently used requirejs library exports.getRequirejsVersionInfo = function() { return requirejs.version; }; // Returns a boolean flag that determines if we´re using // the default bundled version or a user defined custom requirejs version exports.isCustomLibrary = function() { return !isDefaultVersion; }; return exports; };
JavaScript
0
@@ -566,30 +566,24 @@ ';%0A%0A // - check if the cust @@ -630,16 +630,16 @@ urn the%0A + // @@ -712,39 +712,11 @@ -if (fs.existsSync(rjsPathname)) +try %7B%0A @@ -820,15 +820,28 @@ js;%0A - %7D + catch (e) %7B%7D %0A%0A
ba3bc689ca7931eafe4ba59dc5b77838a33b9313
update BaseButton
src/_BaseButton/BaseButton.js
src/_BaseButton/BaseButton.js
/** * @file BaseButton component * @author liangxiaojun([email protected]) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import CircularLoading from '../CircularLoading'; import TipProvider from '../TipProvider'; import TouchRipple from '../TouchRipple'; import Theme from '../Theme'; import PureRender from '../_vendors/PureRender'; import Util from '../_vendors/Util'; import Position from '../_statics/Position'; @PureRender class BaseButton extends Component { static Theme = Theme; static TipPosition = Position; constructor(props, ...restArgs) { super(props, ...restArgs); this.touchTapHandler = ::this.touchTapHandler; this.startRipple = ::this.startRipple; this.endRipple = ::this.endRipple; } touchTapHandler(e) { e.preventDefault(); const {disabled, isLoading, onTouchTap} = this.props; !disabled && !isLoading && onTouchTap && onTouchTap(e); } startRipple(e) { !this.props.disableTouchRipple && this.refs.touchRipple.addRipple(e); } endRipple() { !this.props.disableTouchRipple && this.refs.touchRipple.removeRipple(); } render() { const { children, className, style, theme, isRounded, isCircular, disableTouchRipple, iconCls, rightIconCls, type, value, disabled, readOnly, isLoading, rippleDisplayCenter, tip, tipPosition, renderer, ...restProps } = this.props, buttonClassName = classNames('base-button', { [`theme-${theme}`]: theme, 'button-circular': isCircular, 'button-rounded': isRounded, [className]: className }), loadingIconPosition = (rightIconCls && !iconCls) ? 'right' : 'left'; return ( <TipProvider text={tip} position={tipPosition}> <button {...restProps} className={buttonClassName} style={style} type={type} disabled={disabled || isLoading} readOnly={readOnly} onTouchTap={this.touchTapHandler}> { isLoading && loadingIconPosition === 'left' ? <CircularLoading className="button-icon button-icon-left button-loading-icon" size="small"/> : ( iconCls ? <i className={`button-icon button-icon-left ${iconCls}`} aria-hidden="true"></i> : null ) } { renderer && typeof renderer === 'function' ? renderer(this.props) : ( value ? <span className="base-button-value">{value}</span> : null ) } { isLoading && loadingIconPosition === 'right' ? <CircularLoading className="button-icon button-icon-right button-loading-icon" size="small"/> : ( rightIconCls ? <i className={`button-icon button-icon-right ${rightIconCls}`} aria-hidden="true"></i> : null ) } {children} { disableTouchRipple ? null : <TouchRipple ref="touchRipple" className={disabled || isLoading ? 'hidden' : ''} displayCenter={rippleDisplayCenter}/> } </button> </TipProvider> ); } }; process.env.NODE_ENV !== 'production' && (BaseButton.propTypes = { className: PropTypes.string, style: PropTypes.object, theme: PropTypes.oneOf(Util.enumerateValue(Theme)), isRounded: PropTypes.bool, isCircular: PropTypes.bool, value: PropTypes.any, type: PropTypes.string, disabled: PropTypes.bool, readOnly: PropTypes.bool, isLoading: PropTypes.bool, disableTouchRipple: PropTypes.bool, iconCls: PropTypes.string, rightIconCls: PropTypes.string, tip: PropTypes.string, tipPosition: PropTypes.oneOf(Util.enumerateValue(Position)), rippleDisplayCenter: PropTypes.bool, renderer: PropTypes.func, onTouchTap: PropTypes.func }); BaseButton.defaultProps = { theme: Theme.DEFAULT, isRounded: false, isCircular: false, disabled: false, readOnly: false, type: 'button', isLoading: false, disableTouchRipple: false, rippleDisplayCenter: false, tipPosition: Position.BOTTOM }; export default BaseButton;
JavaScript
0
@@ -4585,16 +4585,20 @@ %7D%0A%7D;%0A%0A +if ( process. @@ -4614,29 +4614,78 @@ ENV -! += == ' -production' && ( +development') %7B%0A const PropTypes = require('prop-types');%0A Base @@ -4706,24 +4706,28 @@ es = %7B%0A%0A + + className: P @@ -4743,24 +4743,28 @@ string,%0A + + style: PropT @@ -4776,16 +4776,20 @@ object,%0A + them @@ -4837,24 +4837,28 @@ eme)),%0A%0A + + isRounded: P @@ -4868,24 +4868,28 @@ Types.bool,%0A + isCircul @@ -4905,24 +4905,28 @@ ypes.bool,%0A%0A + value: P @@ -4939,16 +4939,20 @@ es.any,%0A + type @@ -4971,24 +4971,28 @@ string,%0A + + disabled: Pr @@ -5005,24 +5005,28 @@ s.bool,%0A + + readOnly: Pr @@ -5039,24 +5039,28 @@ s.bool,%0A + + isLoading: P @@ -5074,24 +5074,28 @@ s.bool,%0A + + disableTouch @@ -5115,24 +5115,28 @@ ypes.bool,%0A%0A + iconCls: @@ -5150,24 +5150,28 @@ pes.string,%0A + rightIco @@ -5195,16 +5195,20 @@ tring,%0A%0A + tip: @@ -5222,24 +5222,28 @@ pes.string,%0A + tipPosit @@ -5296,24 +5296,28 @@ ion)),%0A%0A + + rippleDispla @@ -5338,24 +5338,28 @@ ypes.bool,%0A%0A + renderer @@ -5376,24 +5376,28 @@ s.func,%0A + + onTouchTap: @@ -5416,11 +5416,16 @@ nc%0A%0A -%7D); + %7D;%0A%7D %0A%0ABa
f6677b1f93351a1852ad13190348145e21fd5b02
Fix entry count offset
mac/filetypes/open_M_93.js
mac/filetypes/open_M_93.js
define(['itemObjectModel'], function(itemObjectModel) { 'use strict'; function open(item) { return item.getBytes().then(function(bytes) { if (String.fromCharCode.apply(null, bytes.subarray(0, 4)) !== 'RIFX' || String.fromCharCode.apply(null, bytes.subarray(8, 12)) !== 'MV93') { return Promise.reject('not a MV93 RIFX file'); } var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); if (bytes.length < dv.getUint32(4, false) + 8) { return Promise.reject('bad length'); } item.notifyPopulating(new Promise(function(resolve, reject) { for (var pos = 12; pos < bytes.length; ) { var chunkName = String.fromCharCode.apply(null, bytes.subarray(pos, pos+4)); var chunkItem = itemObjectModel.createItem(chunkName); var chunkLen = dv.getUint32(pos + 4); if (chunkLen !== 0) { chunkItem.byteSource = item.byteSource.slice(pos + 8, pos + 8 + dv.getUint32(pos + 4)); } switch (chunkName) { case 'mmap': chunkItem.startAddingItems(); chunkItem.addEventListener(itemObjectModel.EVT_POPULATE, MMapView.itemPopulator); break; } item.addItem(chunkItem); pos += 8 + chunkLen + chunkLen % 2; } resolve(item); })); }); } function MMapView(buffer, byteOffset, byteLength) { Object.defineProperties(this, { dataView: {value:new DataView(buffer, byteOffset, byteLength)}, }); } MMapView.itemPopulator = function() { var self = this; this.notifyPopulating(this.getBytes().then(function(bytes) { var mmap = new MMapView(bytes.buffer, bytes.byteOffset, bytes.byteLength); self.setDataObject(mmap); })); }; MMapView.prototype = { toJSON: function() { return this.entries; }, }; Object.defineProperties(MMapView.prototype, { entryCount: { get: function() { return this.dataView.getUint32(0, false); }, }, entries: { get: function() { var entries = new Array(this.entryCount); var buffer = this.dataView.buffer, byteOffset = this.dataView.byteOffset; for (var i = 0; i < entries.length; i++) { entries.push(new MMapRecordView( buffer, byteOffset + (i + 1) * MMapRecordView.byteLength, MMapRecordView.byteLength)); } return entries; }, }, }); function MMapRecordView(buffer, byteOffset, byteLength) { Object.defineProperties(this, { dataView: {value:new DataView(buffer, byteOffset, byteLength)}, bytes: {value:new Uint8Array(buffer, byteOffset, byteLength)}, }); } MMapRecordView.prototype = { toJSON: function() { if (this.isUnused) return null; return { unknown1: this.unknown1, chunkName: this.chunkName, chunkLength: this.chunkLength, chunkOffset: this.chunkOffset, unknown2: this.unknown2, }; }, }; Object.defineProperties(MMapRecordView.prototype, { unknown1: { get: function() { return this.dataView.getUint32(0, false); }, }, chunkName: { get: function() { return String.fromCharCode.apply(null, this.bytes.subarray(4, 8)); }, }, isUnused: { get: function() { switch (this.chunkName) { case 'free': case 'junk': return true; default: return false; } }, }, chunkLength: { get: function() { return this.dataView.getUint32(8, false); }, }, chunkOffset: { get: function() { return this.dataView.getUint32(12, false); }, }, unknown2: { get: function() { return this.dataView.getUint32(16, false); }, }, }); MMapRecordView.byteLength = 20; return open; });
JavaScript
0.000001
@@ -2014,33 +2014,33 @@ aView.getUint32( -0 +8 , false);%0A
4ffd48db3ae87a3fcaedffb59315f54fad55de6f
update build
dist/app.js
dist/app.js
'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _lodash = require('lodash'); var _lodash2 = _interopRequireDefault(_lodash); var _yargs = require('yargs'); var _api = require('./api'); var _api2 = _interopRequireDefault(_api); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Bot = function () { function Bot(keys) { _classCallCheck(this, Bot); this.client = new _api2.default(keys); this.badWords = [/[qk]u?r[wf][ao]/i // kurwa , /qwa/i, /jprdl/i, /pierdo\w+/i // pierdolić , /szmat[ao]/i // szmata , /cwel/i, /pi[zź]d[ayzo]i?e?/i, /testmanderigona/i, /penis/i, /pines/i, /cipk?a/i, /c?h[u|ó]j/i, /zajebi/i, /zapier/i]; this.templates = ['@<%= nick %>, wykryto wulgaryzmy w Twoim wpisie ( ͡° ʖ̯ ͡°) zrób #pokazmorde albo to zgłoszę. Wygenerowano automatycznie przez ostoje prawilności na Wykopie, **TestBot**', '@<%= nick %>, wykryto wulgaryzmy w Twoim wpisie ( ͡° ʖ̯ ͡°) zrób #rozdajo albo to zgłoszę. Wygenerowano automatycznie przez ostoje prawilności na Wykopie, **TestBot**', '@<%= nick %>, wykryto wulgaryzmy w Twoim wpisie ( ͡° ʖ̯ ͡°) zrób wyjdź z piwnicy albo to zgłoszę. Wygenerowano automatycznie przez ostoje prawilności na Wykopie, **TestBot**']; } _createClass(Bot, [{ key: 'verifyString', value: function verifyString(str, patterns) { return !_lodash2.default.some(patterns, function (word) { return str.match(word); }); } }, { key: 'parseEntry', value: function parseEntry(data) { var _this = this; var checkBlock = function checkBlock(entry) { var comments = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1]; if (!_this.verifyString(entry['body'], _this.badWords)) { var body = _lodash2.default.template(_this.templates[Math.floor(_this.templates.length * Math.random())])({ nick: entry['author'] }); if (!_lodash2.default.find(comments, function (comment) { return comment['author'] == 'TestBot' && comment['body'].indexOf(entry['author']) === -1; })) { _this.client.request('entries/addcomment', { body: body }, { method: [data['id']] }).then(function (res) { console.log(entry['author'] + ' - wpis ' + entry['id'] + ' - zostal ukarany - ' + res); }); } } }; if (data['body'].indexOf('#bekazlewactwa') > -1 || !this.verifyString(data['body'], this.badWords)) this.client.request('entries/index', null, { method: [data['id']] }).then(function (_ref) { var comments = _ref.comments; comments = comments.concat([data]); _lodash2.default.each(comments, function (entry) { return checkBlock(entry, comments); }); }); } }, { key: 'run', value: function run() { var _this2 = this; var search = function search() { console.log('Przeszukuje mirko...'); _this2.lastId = 0; _this2.client.request('stream/index').then(function (data) { _lodash2.default.each(data.reverse(), function (entry) { if (entry['id'] > _this2.lastId) { _this2.parseEntry(entry); _this2.lastId = entry['id']; } }); }); }; search(); setInterval(search.bind(this), 3 * 60 * 1000); } }]); return Bot; }(); ; // CLI var keys = _lodash2.default.merge({ app: process.env.appKey, secret: process.env.secretKey, account: process.env.accountKey }, _yargs.argv); new Bot(keys).run();
JavaScript
0.000001
@@ -1429,512 +1429,75 @@ k %25%3E -, wykryto wulgaryzmy w Twoim wpisie ( %CD%A1%C2%B0 %CA%96%CC%AF %CD%A1%C2%B0) zr%C3%B3b #pokazmorde albo to zg%C5%82osz%C4%99. Wygenerowano automatycznie przez ostoje prawilno%C5%9Bci na Wykopie, **TestBot**', '@%3C%25= nick %25%3E, wykryto wulgaryzmy w Twoim wpisie ( %CD%A1%C2%B0 %CA%96%CC%AF %CD%A1%C2%B0) zr%C3%B3b #rozdajo albo to zg%C5%82osz%C4%99. Wygenerowano automatycznie przez ostoje prawilno%C5%9Bci na Wykopie, **TestBot**', '@%3C%25= nick %25%3E, wykryto wulgaryzmy w Twoim wpisie ( %CD%A1%C2%B0 %CA%96%CC%AF %CD%A1%C2%B0) zr%C3%B3b wyjd%C5%BA z piwnicy albo to zg%C5%82osz%C4%99. Wygenerowano automatycznie przez ostoje prawilno%C5%9Bci na Wykopie, **TestBot** + plz nie przeklinaj hultaju', '@%3C%25= nick %25%3E nie przeklinaj mireczku '%5D;%0A @@ -2285,59 +2285,8 @@ Bot' - && comment%5B'body'%5D.indexOf(entry%5B'author'%5D) === -1 ;%0A @@ -2511,14 +2511,10 @@ rany - - ' + +', res @@ -3655,16 +3655,32 @@ v.appKey + %7C%7C '4Ac50eaivm' ,%0A secr @@ -3704,16 +3704,32 @@ ecretKey + %7C%7C 'H8IA8kj3rY' ,%0A acco @@ -3755,16 +3755,42 @@ countKey + %7C%7C 'u146l0Xlsyj5rzcx56ZH' %0A%7D, _yar
390570cfac195da3878f7cb8ce5a3947a0d2dff3
Update location search to match new API
public/collections/locations.js
public/collections/locations.js
define([ 'models/location' ], function( LocationModel ) { var baseUrl = 'api/locations'; var collection = { model: LocationModel, url: baseUrl, /** * Clear any currently applied filters so that future * fetch calls will return ALL locations * * @returns {undefined} */ clearFilter: function() { this.url = baseUrl; }, /** * Apply a filter, causing any future fetch calls to return * only the locations that match the given filter string * * @param {string} filterStr * @returns {undefined} */ setFilter: function(filterStr) { this.url = baseUrl + '/search/' + encodeURIComponent(filterStr); } }; return Backbone.Collection.extend(collection); });
JavaScript
0
@@ -621,16 +621,16 @@ + ' -/ +? search -/ += ' +
cf666419b0d5617b1010421d540ca35b8d973652
Remove `Discourse.computed` now that we have it in stable
assets/javascripts/discourse/components/tag-drop.js.es6
assets/javascripts/discourse/components/tag-drop.js.es6
var get = Ember.get; export default Ember.Component.extend({ classNameBindings: [':tag-drop', 'tag::no-category', 'tags:has-drop','categoryStyle','tagClass'], categoryStyle: Discourse.computed.setting('category_style'), // match the category-drop style currentCategory: Em.computed.or('secondCategory', 'firstCategory'), showFilterByTag: Discourse.computed.setting('show_filter_by_tag'), showTagDropdown: Em.computed.and('showFilterByTag', 'tags'), tagId: null, tagName: 'li', tags: function() { if (this.siteSettings.tags_sort_alphabetically && Discourse.Site.currentProp('top_tags')) { return Discourse.Site.currentProp('top_tags').sort(); } else { return Discourse.Site.currentProp('top_tags'); } }.property('site.top_tags'), iconClass: function() { if (this.get('expanded')) { return "fa fa-caret-down"; } return "fa fa-caret-right"; }.property('expanded'), tagClass: function() { if (this.get('tagId')) { return "tag-" + this.get('tagId'); } else { return "tag_all"; } }.property('tagId'), allTagsUrl: function() { if (this.get('currentCategory')) { return this.get('currentCategory.url') + "?allTags=1"; } else { return "/"; } }.property('firstCategory', 'secondCategory'), allTagsLabel: function() { return I18n.t("tagging.selector_all_tags"); }.property('tag'), dropdownButtonClass: function() { var result = 'badge-category category-dropdown-button'; if (Em.isNone(this.get('tag'))) { result += ' home'; } return result; }.property('tag'), clickEventName: function() { return "click.tag-drop-" + (this.get('tag') || "all"); }.property('tag'), actions: { expand: function() { var self = this; if(!this.get('renderTags')){ this.set('renderTags',true); Em.run.next(function(){ self.send('expand'); }); return; } if (this.get('expanded')) { this.close(); return; } if (this.get('tags')) { this.set('expanded', true); } var $dropdown = this.$()[0]; this.$('a[data-drop-close]').on('click.tag-drop', function() { self.close(); }); Em.run.next(function(){ self.$('.cat a').add('html').on(self.get('clickEventName'), function(e) { var $target = $(e.target), closest = $target.closest($dropdown); if ($(e.currentTarget).hasClass('badge-wrapper')){ self.close(); } return ($(e.currentTarget).hasClass('badge-category') || (closest.length && closest[0] === $dropdown)) ? true : self.close(); }); }); } }, removeEvents: function(){ $('html').off(this.get('clickEventName')); this.$('a[data-drop-close]').off('click.tag-drop'); }, close: function() { this.removeEvents(); this.set('expanded', false); }, willDestroyElement: function() { this.removeEvents(); } });
JavaScript
0
@@ -1,12 +1,63 @@ +import %7B setting %7D from 'discourse/lib/computed';%0A%0A var get = Em @@ -223,35 +223,16 @@ yStyle: -Discourse.computed. setting( @@ -349,24 +349,24 @@ Category'),%0A + showFilter @@ -376,27 +376,8 @@ ag: -Discourse.computed. sett
6d1240b0d9545e0f2b386822a1ebff6500a082a9
update TriggerPop
src/_TriggerPop/TriggerPop.js
src/_TriggerPop/TriggerPop.js
/** * @file TriggerPop component * @author liangxiaojun([email protected]) */ import React, {Component, Fragment} from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import eventsOn from 'dom-helpers/events/on'; import eventsOff from 'dom-helpers/events/off'; import Pop from '../_Pop'; import Paper from '../Paper'; import Theme from '../Theme'; import Position from '../_statics/Position'; import Event from '../_vendors/Event'; import Util from '../_vendors/Util'; import TriggerPopCalculation from '../_vendors/TriggerPopCalculation'; import Dom from '../_vendors/Dom'; class TriggerPop extends Component { static Position = Position; static Theme = Theme; constructor(props, ...restArgs) { super(props, ...restArgs); // closest scrollable element of trigger this.scrollEl = null; } /** * public */ getEl = () => { return this.refs.pop && this.refs.pop.getEl(); }; /** * reset pop position * @param transitionEl */ resetPosition = (transitionEl = this.refs.pop.getEl()) => { const {parentEl, triggerEl, position, isTriggerPositionFixed} = this.props; TriggerPopCalculation.setStyle(parentEl, triggerEl, transitionEl, this.getScrollEl(), position, isTriggerPositionFixed); }; /** * find the closest scrollable parent element * @param triggerEl * @returns {*} */ getScrollEl = (triggerEl = this.props.triggerEl) => { if (this.props.scrollEl) { return this.props.scrollEl; } if (this.scrollEl) { return this.scrollEl; } const scrollEl = Dom.getClosestScrollable(triggerEl); return this.scrollEl = scrollEl || document.body; }; /** * scroll event callback */ handleScroll = () => { this.resetPosition(); }; /** * add scroll event * @param scrollEl */ addWatchScroll = (scrollEl = this.getScrollEl()) => { const {triggerEl} = this.props; if (!triggerEl) { return; } scrollEl && eventsOn(scrollEl, 'scroll', this.handleScroll); }; /** * remove scroll event * @param scrollEl */ removeWatchScroll = (scrollEl = this.getScrollEl()) => { scrollEl && eventsOff(scrollEl, 'scroll', this.handleScroll); }; componentDidUpdate(prevProps) { if (this.props.shouldFollowScroll && !prevProps.visible && this.props.visible) { this.addWatchScroll(); } else if (prevProps.shouldFollowScroll && prevProps.visible && !this.props.visible) { this.removeWatchScroll(); } } render() { const { children, className, contentClassName, theme, hasTriangle, triangle, position, isAnimated, // not passing down these props isEscClose, isBlurClose, shouldPreventContainerScroll, isTriggerPositionFixed, shouldFollowScroll, ...restProps } = this.props, popClassName = classNames('trigger-pop', { 'trigger-pop-has-triangle': hasTriangle, [`theme-${theme}`]: theme, [`trigger-pop-${position}`]: position, 'trigger-pop-animated': isAnimated, [className]: className }), popContentClassName = classNames('trigger-pop-content', { [contentClassName]: contentClassName }); return ( <Pop {...restProps} ref="pop" className={popClassName} container={<Paper></Paper>} isAnimated={isAnimated} onWheel={e => Event.wheelHandler(e, this.props)} resetPosition={this.resetPosition}> { popEl => ( <Fragment> { hasTriangle ? <div className="trigger-pop-triangle-wrapper"> {triangle} </div> : null } <div className={popContentClassName} onWheel={e => Event.wheelHandler(e, this.props)}> {typeof children === 'function' ? children(popEl) : children} </div> </Fragment> ) } </Pop> ); } } TriggerPop.propTypes = { /** * The CSS class name of the root element. */ className: PropTypes.string, /** * The CSS class name of the content element. */ contentClassName: PropTypes.string, modalClassName: PropTypes.string, /** * Override the styles of the root element. */ style: PropTypes.object, /** * The trigger pop theme.Can be primary,highlight,success,warning,error. */ theme: PropTypes.oneOf(Util.enumerateValue(Theme)), parentEl: PropTypes.object, /** * This is the DOM element that will be used to set the position of the trigger pop. */ triggerEl: PropTypes.object, /** * If true,the trigger pop is visible. */ visible: PropTypes.bool, /** * If true,the trigger pop will have a triangle on the top of the DOM element. */ hasTriangle: PropTypes.bool, triangle: PropTypes.element, showModal: PropTypes.bool, /** * The trigger pop alignment.The value can be Popup.Position.LEFT or Popup.Position.RIGHT. */ position: PropTypes.oneOf(Util.enumerateValue(Position)), /** * If true,popup will have animation effects. */ isAnimated: PropTypes.bool, /** * The depth of Paper component. */ depth: PropTypes.number, isBlurClose: PropTypes.bool, isEscClose: PropTypes.bool, shouldPreventContainerScroll: PropTypes.bool, isTriggerPositionFixed: PropTypes.bool, shouldFollowScroll: PropTypes.bool, scrollEl: PropTypes.object, resetPositionWait: PropTypes.number, /** * The function of popup render. */ onRender: PropTypes.func, /** * The function of popup rendered. */ onRendered: PropTypes.func, /** * The function of popup destroy. */ onDestroy: PropTypes.func, /** * The function of popup destroyed. */ onDestroyed: PropTypes.func, /** * Callback function fired when wrapper wheeled. */ onWheel: PropTypes.func }; TriggerPop.defaultProps = { theme: Theme.DEFAULT, parentEl: document.body, depth: 3, visible: false, hasTriangle: true, triangle: <div className="trigger-pop-triangle"></div>, showModal: false, position: Position.BOTTOM, isAnimated: true, isBlurClose: true, isEscClose: true, shouldPreventContainerScroll: true, isTriggerPositionFixed: false, shouldFollowScroll: false, resetPositionWait: 250 }; export default TriggerPop;
JavaScript
0
@@ -1173,32 +1173,8 @@ tion -, isTriggerPositionFixed %7D = @@ -1283,53 +1283,17 @@ l(), -%0A position, isTriggerPositionFixed + position );%0A%0A @@ -2993,32 +2993,8 @@ - isTriggerPositionFixed, sho @@ -6141,52 +6141,8 @@ ool, -%0A isTriggerPositionFixed: PropTypes.bool, %0A%0A @@ -7071,43 +7071,8 @@ ue,%0A - isTriggerPositionFixed: false,%0A
30034b7e631513b39f83057ce1f5239e12312ad8
Change BITD to new loader format
mac/resources/open_BITD.js
mac/resources/open_BITD.js
define(['mac/bitpacking'], function(bitpacking) { 'use strict'; return function(resource) { resource.getUnpackedData = function() { return bitpacking.unpackBits(this.data.buffer, this.data.byteOffset, this.data.byteLength); }; }; });
JavaScript
0.000001
@@ -85,32 +85,24 @@ ion( -resource) %7B%0A resource +item) %7B%0A item .get @@ -146,90 +146,142 @@ urn -bitpacking.unpackBits(this.data.buffer, this.data.byteOffset, this.data.byteLength +this.getBytes().then(function(bytes) %7B%0A return bitpacking.unpackBits(bytes.buffer, bytes.byteOffset, bytes.byteLength);%0A %7D );%0A
25a1923c1039a3e107ffe1f8fea5dee2333d28d8
remove translate code from projects without translation
generators/client/templates/src/main/webapp/app/admin/user-management/_user-management.js
generators/client/templates/src/main/webapp/app/admin/user-management/_user-management.js
'use strict'; angular.module('<%=angularAppName%>') .config(function ($stateProvider) { $stateProvider .state('user-management', { parent: 'admin', url: '/user-management', data: { authorities: ['ROLE_ADMIN'], pageTitle: 'user-management.home.title' }, views: { 'content@': { templateUrl: 'app/admin/user-management/user-management.html', controller: 'UserManagementController' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('user-management'); return $translate.refresh(); }] } }) .state('user-management-detail', { parent: 'admin', url: '/user/:login', data: { authorities: ['ROLE_ADMIN'], pageTitle: 'user-management.detail.title' }, views: { 'content@': { templateUrl: 'app/admin/user-management/user-management-detail.html', controller: 'UserManagementDetailController' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('user-management'); return $translate.refresh(); }] } }) .state('user-management.new', { parent: 'user-management', url: '/new', data: { authorities: ['ROLE_ADMIN'], }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/admin/user-management/user-management-dialog.html', controller: 'UserManagementDialogController', size: 'lg', resolve: { entity: function () { return { id: null, login: null, firstName: null, lastName: null, email: null, activated: true, langKey: null, createdBy: null, createdDate: null, lastModifiedBy: null, lastModifiedDate: null, resetDate: null, resetKey: null, authorities: null }; } } }).result.then(function() { $state.go('user-management', null, { reload: true }); }, function() { $state.go('user-management'); }); }] }) .state('user-management.edit', { parent: 'user-management', url: '/{login}/edit', data: { authorities: ['ROLE_ADMIN'], }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/admin/user-management/user-management-dialog.html', controller: 'UserManagementDialogController', size: 'lg', resolve: { entity: ['User', function(User) { return User.get({login : $stateParams.login}); }] } }).result.then(function() { $state.go('user-management', null, { reload: true }); }, function() { $state.go('^'); }); }] }) .state('user-management.delete', { parent: 'user-management', url: '/{login}/delete', data: { authorities: ['ROLE_ADMIN'], }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/admin/user-management/user-management-delete-dialog.html', controller: 'UserManagementDeleteController', size: 'md', resolve: { entity: ['User', function(User) { return User.get({login : $stateParams.login}); }] } }).result.then(function() { $state.go('user-management', null, { reload: true }); }, function() { $state.go('^'); }); }] }); });
JavaScript
0
@@ -644,32 +644,79 @@ resolve: %7B%0A + %3C%25 if (enableTranslation) %7B %25%3E%0A @@ -826,32 +826,32 @@ artialLoader) %7B%0A - @@ -978,32 +978,56 @@ %7D%5D%0A + %3C%25 %7D %25%3E%0A @@ -1596,32 +1596,79 @@ resolve: %7B%0A + %3C%25 if (enableTranslation) %7B %25%3E%0A @@ -1907,32 +1907,32 @@ late.refresh();%0A - @@ -1930,32 +1930,56 @@ %7D%5D%0A + %3C%25 %7D %25%3E%0A
6da45bb9c3a48596b1276a5593a1461ebfa26e64
fix ripple when touching on the operation list
mobile/activities/Home/components/Operation/index.js
mobile/activities/Home/components/Operation/index.js
import React from 'react' import { connect } from 'react-redux' import { compose, flattenProp, setDisplayName } from 'recompose' import { StyleSheet, View } from 'react-native' import { SimpleLineIcons } from '@expo/vector-icons' import { Text, Divider, TouchableRipple } from 'react-native-paper' import { goToOperation } from 'Coopcon/data/navigation/actions' import { getOperation } from 'Coopcon/data/operation/selectors' const styles = StyleSheet.create({ container: { flexDirection: 'row', alignItems: 'center', paddingTop: 15, paddingBottom: 15, paddingLeft: 15, paddingRight: 5, backgroundColor: 'white', }, name: { flex: 1, }, }) const mapStateToProps = (state, { id }) => ({ operation: getOperation(state, id), }) const mapDispatchToProps = (dispatch, { id }) => ({ goToOperation: () => dispatch(goToOperation(id)), }) const enhancer = compose( connect(mapStateToProps, mapDispatchToProps), flattenProp('operation'), setDisplayName('Operation'), ) const Operation = enhancer(({ name, goToOperation }) => ( <View> <TouchableRipple onPress={goToOperation} > <View style={styles.container} > <Text style={styles.name}>{name}</Text> <SimpleLineIcons name="arrow-right" size={20}/> </View> </TouchableRipple> <Divider/> </View> )) export default Operation
JavaScript
0.000009
@@ -455,16 +455,64 @@ reate(%7B%0A + wrapper: %7B%0A backgroundColor: 'white',%0A %7D,%0A contai @@ -659,38 +659,8 @@ 5,%0A - backgroundColor: 'white',%0A %7D, @@ -1085,24 +1085,54 @@ =%3E (%0A %3CView +%0A style=%7Bstyles.wrapper%7D%0A %3E%0A %3CTouch
11bfd555b99bbef2e2c47942b45cbba442691abb
fix display errors (#15935)
packages/cascader-panel/src/store.js
packages/cascader-panel/src/store.js
import Node from './node'; import { coerceTruthyValueToArray } from 'element-ui/src/utils/util'; const flatNodes = (data, leafOnly) => { return data.reduce((res, node) => { if (node.isLeaf) { res.push(node); } else { !leafOnly && res.push(node); res = res.concat(flatNodes(node.children, leafOnly)); } return res; }, []); }; export default class Store { constructor(data, config) { this.config = config; this.initNodes(data); } initNodes(data) { data = coerceTruthyValueToArray(data); this.nodes = data.map(nodeData => new Node(nodeData, this.config)); this.flattedNodes = this.getFlattedNodes(false, false); this.leafNodes = this.getFlattedNodes(true, false); } appendNode(nodeData, parentNode) { const node = new Node(nodeData, this.config, parentNode); const children = parentNode ? parentNode.children : this.nodes; children.push(node); } appendNodes(nodeDataList, parentNode) { nodeDataList = coerceTruthyValueToArray(nodeDataList); nodeDataList.forEach(nodeData => this.appendNode(nodeData, parentNode)); } getNodes() { return this.nodes; } getFlattedNodes(leafOnly, cached = true) { const cachedNodes = leafOnly ? this.leafNodes : this.flattedNodes; return cached ? cachedNodes : flatNodes(this.nodes, leafOnly); } getNodeByValue(value) { if (value) { value = Array.isArray(value) ? value[value.length - 1] : value; const nodes = this.getFlattedNodes(false, !this.config.lazy) .filter(node => node.value === value); return nodes && nodes.length ? nodes[0] : null; } return null; } }
JavaScript
0
@@ -53,16 +53,29 @@ eToArray +, valueEquals %7D from @@ -1415,78 +1415,8 @@ ) %7B%0A - value = Array.isArray(value) ? value%5Bvalue.length - 1%5D : value;%0A @@ -1501,16 +1501,50 @@ (node =%3E + (valueEquals(node.path, value) %7C%7C node.va @@ -1557,16 +1557,17 @@ = value) +) ;%0A
26b4579f74cee7912f7dbdbec248c443d4fa44a7
fix a log message
packages/hub/schema-cache.js
packages/hub/schema-cache.js
/* There are three sources of schema information. 1. Most of it lives within a regular data source, just like your other content does. 2. But we need a tiny bit of schema to find the first data source. This is the `seedModels` that are passed into the constructor below. Note that only schema types are allowed in seedModels (not any of your other content). 3. Internally, we also always load @cardstack/hub/bootstrap-schema, which is enough to wire up some of our own modules for things like core field types. */ const Searcher = require('@cardstack/elasticsearch/searcher'); const logger = require('@cardstack/plugin-utils/logger'); const bootstrapSchema = require('./bootstrap-schema'); const { declareInjections } = require('@cardstack/di'); const Schema = require('./schema'); module.exports = declareInjections({ seedModels: 'config:seed-models', schemaLoader: 'hub:schema-loader' }, class SchemaCache { static create(opts) { return new this(opts); } constructor({ seedModels, schemaLoader }) { this.seedModels = bootstrapSchema.concat(seedModels || []); this.searcher = new Searcher(); this.searcher.schemaCache = new BootstrapSchemaCache(this.seedModels, this); this.cache = new Map(); this.log = logger('schema-cache'); this.schemaLoader = schemaLoader; // TODO move this value into plugins-configs for @cardstack/hub. this.controllingBranch = 'master'; } async schemaForBranch(branch) { if (!this.cache.has(branch)) { // we synchronously place a Promise into the cache. This ensures // that a subsequent lookup that arrives while we are still // working on this one will join it instead of racing it. this.cache.set(branch, this._load(branch)); } let schema = await this.cache.get(branch); this.log.debug("returning schema for branch %s %s", branch); return schema; } // The "controlling branch" is special because it's used for // configuration that is not scoped to any particular branch. // // For one example: the set of data sources that we're indexing is // not something that can vary by branch, since the set of branches // itself is discovered by the indexers. // // For another example: grants only take effect when they are // present on the controlling branch. This makes it easier to reason // about who can do what. async schemaForControllingBranch() { return this.schemaForBranch(this.controllingBranch); } // Instantiates a Schema, while respecting any seedModels. This // method does not alter the schemaCache's own state. async schemaFrom(models) { let types = this.schemaLoader.ownTypes(); return this.schemaLoader.loadFrom(this.seedModels.concat(models).filter(s => types.includes(s.type))); } // When Indexers reads a branch, it necessarily reads the schema // first. And when Writers make a change to a schema model, they // need to derive the new schema to make sure it's safe. In either // case, the new schema is already available, so this method allows // us to push it into the cache. notifyBranchUpdate(branch, schema) { if (!(schema instanceof Schema)) { throw new Error("Bug: notifyBranchUpdate got a non-schema"); } this.log.debug("full schema update on branch %s", branch); this.cache.set(branch, Promise.resolve(schema)); } async indexBaseContent(ops) { for (let model of this.seedModels) { await ops.save(model.type, model.id, model); } } async _load(branch) { this.log.debug("initiating schema load on branch %s", branch); try { let { models, page } = await this.searcher.search(branch, { filter: { type: this.schemaLoader.ownTypes() }, page: { size: 1000 } }); if (page.cursor) { throw new Error("query for schema models had insufficient page size"); } this.log.debug("completed schema model loading on branch %s, found %s models", branch, models.length); let schema = this.schemaFrom(models); this.log.debug("instantiated schema for branch %s", branch); return schema; } catch (err) { if (err.status === 404 && err.title === 'No such branch') { // our searcher can fail if no index exists yet. But that's OK // -- in that case our schema is just our seed models. this.log.debug("no search index exists for branch %s, using seeds only", branch); return this.schemaFrom([]); } else { throw err; } } } }); class BootstrapSchemaCache { constructor(seedModels, schemaCache) { this.seedModels = seedModels; this.schema = null; this.schemaCache = schemaCache; } async schemaForBranch() { if (!this.schema) { this.schema = await this.schemaCache.schemaFrom(this.seedModels); } return this.schema; } }
JavaScript
0.999972
@@ -1875,19 +1875,16 @@ branch -%25s %25s%22, bra
5d22c6f1cd75f9c3b80e954488a76e3497c153b4
Switch order of tests to debug CI test issue
src/account/currentBalance/CurrentBalance.spec.js
src/account/currentBalance/CurrentBalance.spec.js
import React from 'react'; import { shallow } from 'enzyme'; import { Message } from 'retranslate'; import { Loader } from '../../common'; import PensionFundOverview from './pensionFundOverview'; import CurrentBalance from './CurrentBalance'; describe('Current balance', () => { let component; beforeEach(() => { component = shallow(<CurrentBalance />); }); it('renders some text', () => { expect(component.contains(<Message>account.current.balance.title</Message>)).toBe(true); expect(component.contains(<Message>account.current.balance.subtitle</Message>)).toBe(true); }); it('renders a link to the EVK', () => { const evkLink = () => component.find('a').first(); expect(evkLink().prop('href')).toBe('https://www.e-register.ee/'); expect(evkLink().children().at(0).node) .toEqual(<Message>account.current.balance.evk</Message>); }); it('renders a loader instead of pension funds if it is still loading', () => { component.setProps({ loading: true }); expect(!!component.find(Loader).length).toBe(true); expect(!!component.find(PensionFundOverview).length).toBe(false); }); it('renders a pension fund overview instead of a loader when not loading', () => { const funds = [ { isin: 'i1', name: 'n1', price: 1, currency: 'c' }, { isin: 'i2', name: 'n2', price: 2, currency: 'c' }, { isin: 'i3', name: 'n3', price: 3, currency: 'c' }, ]; component.setProps({ funds, loading: false }); const pensionFundOverview = () => component.find(PensionFundOverview); expect(!!component.find(Loader).length).toBe(false); expect(!!pensionFundOverview().length).toBe(true); expect(pensionFundOverview().prop('funds')).toEqual(funds); }); });
JavaScript
0
@@ -616,521 +616,521 @@ a l -ink to the EVK', () =%3E %7B%0A const evkLink = () =%3E component.find('a').first();%0A expect(evkLink().prop('href')).toBe('https://www.e-register.ee/');%0A expect(evkLink().children().at(0).node)%0A .toEqual(%3CMessage%3Eaccount.current.balance.evk%3C/Message%3E);%0A %7D);%0A%0A it('renders a loader instead of pension funds if it is still loading', () =%3E %7B%0A component.setProps(%7B loading: true %7D);%0A expect(!!component.find(Loader).length).toBe(true);%0A expect(!!component.find(PensionFundOverview).length).toBe(false +oader instead of pension funds if it is still loading', () =%3E %7B%0A component.setProps(%7B loading: true %7D);%0A expect(!!component.find(Loader).length).toBe(true);%0A expect(!!component.find(PensionFundOverview).length).toBe(false);%0A %7D);%0A%0A it('renders a link to the EVK', () =%3E %7B%0A const evkLink = () =%3E component.find('a').first();%0A expect(evkLink().prop('href')).toBe('https://www.e-register.ee/');%0A expect(evkLink().children().at(0).node)%0A .toEqual(%3CMessage%3Eaccount.current.balance.evk%3C/Message%3E );%0A
3492633a942b4fba6fec21936306b1ddcd3842df
Remove streed requirement from validation
view/frontend/web/js/model/shipping-rates-validation-rules.js
view/frontend/web/js/model/shipping-rates-validation-rules.js
/** * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ /*global define*/ define( [], function () { 'use strict'; return { getRules: function () { return { 'firstname': { 'required': true }, 'lastname': { 'required': true }, 'street': { 'required': true }, 'postcode': { 'required': true }, 'city': { 'required': true }, 'country_id': { 'required': true } }; } }; } );
JavaScript
0
@@ -445,104 +445,8 @@ %7D,%0A - 'street': %7B%0A 'required': true%0A %7D,%0A
9071d22dc706f5fba27fb9b67ac45afd6d1bafef
put pacman in center and ghost in random location and delete ghosts 2-4
app/assets/javascripts/game/game_characters.js
app/assets/javascripts/game/game_characters.js
var gameCharacters = {}; gameCharacters.createPerson = function() { person = game.add.sprite(0, 0, 'sprites'); person.scale.setTo(1.2, 1.2); person.anchor.setTo(0.5, 0.5); person.userControl = false; person.animations.add('right', [10, 11], 0, true); person.animations.add('bottom', [24, 25], 0, true); person.animations.add('left', [38, 39], 0, true); person.animations.add('up', [52, 53], 0, true); person.powerUp = false; person.lastx = person.x; person.lasty = person.y; characters.push(person); } gameCharacters.createGhosts = function() { ghost1 = game.add.sprite(100, game.world.height - 100, 'sprites'); ghost1.anchor.setTo(0.5, 0.5); ghost1.scale.setTo(1.2,1.2); ghost1.userControl = true; ghost1.animations.add('right', [0, 1], 0, true); ghost1.animations.add('bottom', [14, 15], 0, true); ghost1.animations.add('left', [28, 29], 0, true); ghost1.animations.add('up', [42, 43], 0, true); ghost1.lastx = ghost1.x; ghost1.lasty = ghost1.y; // ghost2 = game.add.sprite(200, game.world.height - 150, 'sprites'); // ghost2.anchor.setTo(0.5, 0.5); // ghost2.scale.setTo(1.2,1.2); // ghost2.userControl = false; // ghost2.animations.add('right', [2, 3], 0, true); // ghost2.animations.add('bottom', [16, 17], 0, true); // ghost2.animations.add('left', [30, 31], 0, true); // ghost2.animations.add('up', [44, 45], 0, true); // ghost2.lastx = ghost2.x; // ghost2.lasty = ghost2.y; // ghost3 = game.add.sprite(300, game.world.height - 150, 'sprites'); // ghost3.anchor.setTo(0.5, 0.5); // ghost3.scale.setTo(1.2,1.2); // ghost3.userControl = false; // ghost3.animations.add('right', [4, 5], 0, true); // ghost3.animations.add('bottom', [18, 19], 0, true); // ghost3.animations.add('left', [32, 33], 0, true); // ghost3.animations.add('up', [46, 47], 0, true); // ghost3.lastx = ghost3.x; // ghost3.lasty = ghost3.y; // ghost4 = game.add.sprite(400, game.world.height - 150, 'sprites'); // ghost4.anchor.setTo(0.5, 0.5); // ghost4.scale.setTo(1.2,1.2); // ghost4.userControl = false; // ghost4.animations.add('right', [6, 7], 0, true); // ghost4.animations.add('bottom', [20, 21], 0, true); // ghost4.animations.add('left', [34, 35], 0, true); // ghost4.animations.add('up', [48, 49], 0, true); // ghost4.lastx = ghost4.x; // ghost4.lasty = ghost4.y; // ghosts.push(ghost1, ghost2, ghost3, ghost4); // characters.push(ghost1, ghost2, ghost3, ghost4); ghosts.push(ghost1); characters.push(ghost1); }
JavaScript
0
@@ -93,12 +93,43 @@ ite( -0, 0 +CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2 , 's @@ -626,36 +626,67 @@ ite( -100, game.world.height - 100 +CANVAS_WIDTH * Math.random(), CANVAS_HEIGHT * Math.random() , 's @@ -1022,16 +1022,16 @@ ost1.x;%0A + ghost1 @@ -1054,1478 +1054,8 @@ y;%0A%0A - // ghost2 = game.add.sprite(200, game.world.height - 150, 'sprites');%0A // ghost2.anchor.setTo(0.5, 0.5);%0A // ghost2.scale.setTo(1.2,1.2);%0A // ghost2.userControl = false;%0A // ghost2.animations.add('right', %5B2, 3%5D, 0, true);%0A // ghost2.animations.add('bottom', %5B16, 17%5D, 0, true);%0A // ghost2.animations.add('left', %5B30, 31%5D, 0, true);%0A // ghost2.animations.add('up', %5B44, 45%5D, 0, true);%0A // ghost2.lastx = ghost2.x;%0A // ghost2.lasty = ghost2.y;%0A%0A // ghost3 = game.add.sprite(300, game.world.height - 150, 'sprites');%0A // ghost3.anchor.setTo(0.5, 0.5);%0A // ghost3.scale.setTo(1.2,1.2);%0A // ghost3.userControl = false;%0A // ghost3.animations.add('right', %5B4, 5%5D, 0, true);%0A // ghost3.animations.add('bottom', %5B18, 19%5D, 0, true);%0A // ghost3.animations.add('left', %5B32, 33%5D, 0, true);%0A // ghost3.animations.add('up', %5B46, 47%5D, 0, true);%0A // ghost3.lastx = ghost3.x;%0A // ghost3.lasty = ghost3.y;%0A%0A // ghost4 = game.add.sprite(400, game.world.height - 150, 'sprites');%0A // ghost4.anchor.setTo(0.5, 0.5);%0A // ghost4.scale.setTo(1.2,1.2);%0A // ghost4.userControl = false;%0A // ghost4.animations.add('right', %5B6, 7%5D, 0, true);%0A // ghost4.animations.add('bottom', %5B20, 21%5D, 0, true);%0A // ghost4.animations.add('left', %5B34, 35%5D, 0, true);%0A // ghost4.animations.add('up', %5B48, 49%5D, 0, true);%0A // ghost4.lastx = ghost4.x;%0A // ghost4.lasty = ghost4.y;%0A%0A // ghosts.push(ghost1, ghost2, ghost3, ghost4);%0A // characters.push(ghost1, ghost2, ghost3, ghost4);%0A%0A gh
e0268053e10a3d1418fd33a3434dff1a4fadabec
Fix flow issue on travis ci
packages/relay-compiler/bin/RelayCompilerBin.js
packages/relay-compiler/bin/RelayCompilerBin.js
/** * Copyright (c) 2013-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. * * @flow * @providesModule RelayCompilerBin * @format */ 'use strict'; require('babel-polyfill'); const RelayCodegenRunner = require('RelayCodegenRunner'); const RelayConsoleReporter = require('RelayConsoleReporter'); const RelayFileIRParser = require('RelayFileIRParser'); const RelayFileWriter = require('RelayFileWriter'); const RelayIRTransforms = require('RelayIRTransforms'); const RelayWatchmanClient = require('RelayWatchmanClient'); const formatGeneratedModule = require('formatGeneratedModule'); const fs = require('fs'); const path = require('path'); const yargs = require('yargs'); const { buildASTSchema, buildClientSchema, parse, printSchema, } = require('graphql'); const { codegenTransforms, fragmentTransforms, printTransforms, queryTransforms, schemaExtensions, } = RelayIRTransforms; import type {GraphQLSchema} from 'graphql'; function buildWatchExpression(options: { extensions: Array<string>, include: Array<string>, exclude: Array<string>, }) { return [ 'allof', ['type', 'f'], ['anyof', ...options.extensions.map(ext => ['suffix', ext])], [ 'anyof', ...options.include.map(include => ['match', include, 'wholename']), ], ...options.exclude.map(exclude => ['not', ['match', exclude, 'wholename']]), ]; } function getFilepathsFromGlob( baseDir, options: { extensions: Array<string>, include: Array<string>, exclude: Array<string>, }, ): Array<string> { const {extensions, include, exclude} = options; const patterns = include.map(inc => `${inc}/*.+(${extensions.join('|')})`); // $FlowFixMe const glob = require('fast-glob'); return glob.sync(patterns, { cwd: baseDir, bashNative: [], onlyFiles: true, ignore: exclude, }); } /* eslint-disable no-console-disallow */ async function run(options: { schema: string, src: string, extensions: Array<string>, include: Array<string>, exclude: Array<string>, verbose: boolean, watchman: boolean, watch?: ?boolean, }) { const schemaPath = path.resolve(process.cwd(), options.schema); if (!fs.existsSync(schemaPath)) { throw new Error(`--schema path does not exist: ${schemaPath}.`); } const srcDir = path.resolve(process.cwd(), options.src); if (!fs.existsSync(srcDir)) { throw new Error(`--source path does not exist: ${srcDir}.`); } if (options.watch && !options.watchman) { throw new Error('Watchman is required to watch for changes.'); } if (options.watch && !hasWatchmanRootFile(srcDir)) { throw new Error( ` --watch requires that the src directory have a valid watchman "root" file. Root files can include: - A .git/ Git folder - A .hg/ Mercurial folder - A .watchmanconfig file Ensure that one such file exists in ${srcDir} or its parents. `.trim(), ); } const reporter = new RelayConsoleReporter({verbose: options.verbose}); const useWatchman = options.watchman && (await RelayWatchmanClient.isAvailable()); const parserConfigs = { default: { baseDir: srcDir, getFileFilter: RelayFileIRParser.getFileFilter, getParser: RelayFileIRParser.getParser, getSchema: () => getSchema(schemaPath), watchmanExpression: useWatchman ? buildWatchExpression(options) : null, filepaths: useWatchman ? null : getFilepathsFromGlob(srcDir, options), }, }; const writerConfigs = { default: { getWriter: getRelayFileWriter(srcDir), isGeneratedFile: (filePath: string) => filePath.endsWith('.js') && filePath.includes('__generated__'), parser: 'default', }, }; const codegenRunner = new RelayCodegenRunner({ reporter, parserConfigs, writerConfigs, onlyValidate: false, }); if (options.watch) { await codegenRunner.watchAll(); } else { console.log('HINT: pass --watch to keep watching for changes.'); await codegenRunner.compileAll(); } } function getRelayFileWriter(baseDir: string) { return (onlyValidate, schema, documents, baseDocuments) => new RelayFileWriter({ config: { formatModule: formatGeneratedModule, compilerTransforms: { codegenTransforms, fragmentTransforms, printTransforms, queryTransforms, }, baseDir, schemaExtensions, }, onlyValidate, schema, baseDocuments, documents, }); } function getSchema(schemaPath: string): GraphQLSchema { try { let source = fs.readFileSync(schemaPath, 'utf8'); if (path.extname(schemaPath) === '.json') { source = printSchema(buildClientSchema(JSON.parse(source).data)); } source = ` directive @include(if: Boolean) on FRAGMENT | FIELD directive @skip(if: Boolean) on FRAGMENT | FIELD ${source} `; return buildASTSchema(parse(source)); } catch (error) { throw new Error( ` Error loading schema. Expected the schema to be a .graphql or a .json file, describing your GraphQL server's API. Error detail: ${error.stack} `.trim(), ); } } // Ensure that a watchman "root" file exists in the given directory // or a parent so that it can be watched const WATCHMAN_ROOT_FILES = ['.git', '.hg', '.watchmanconfig']; function hasWatchmanRootFile(testPath) { while (path.dirname(testPath) !== testPath) { if ( WATCHMAN_ROOT_FILES.some(file => { return fs.existsSync(path.join(testPath, file)); }) ) { return true; } testPath = path.dirname(testPath); } return false; } // Collect args const argv = yargs .usage( 'Create Relay generated files\n\n' + '$0 --schema <path> --src <path> [--watch]', ) .options({ schema: { describe: 'Path to schema.graphql or schema.json', demandOption: true, type: 'string', }, src: { describe: 'Root directory of application code', demandOption: true, type: 'string', }, include: { array: true, default: ['**'], describe: 'Directories to include under src', type: 'string', }, exclude: { array: true, default: [ '**/node_modules/**', '**/__mocks__/**', '**/__tests__/**', '**/__generated__/**', ], describe: 'Directories to ignore under src', type: 'string', }, extensions: { array: true, default: ['js'], describe: 'File extensions to compile (--extensions js jsx)', type: 'string', }, verbose: { describe: 'More verbose logging', type: 'boolean', }, watchman: { describe: 'Use watchman when not in watch mode', type: 'boolean', default: true, }, watch: { describe: 'If specified, watches files and regenerates on changes', type: 'boolean', }, }) .help().argv; // Run script with args run(argv).catch(error => { console.error(String(error.stack || error)); process.exit(1); });
JavaScript
0
@@ -1914,16 +1914,42 @@ lowFixMe +(site=react_native_fb,www) %0A const
c1e0cf79863743435528cd85a861adc0975f5ea2
simplify test harness using features in ephemeral storage plugin
packages/test-support/env.js
packages/test-support/env.js
const temp = require('./temp-helper'); const ElasticAssert = require('@cardstack/elasticsearch/node-tests/assertions'); const JSONAPIFactory = require('./jsonapi-factory'); const crypto = require('crypto'); const { wireItUp } = require('@cardstack/hub/main'); const Session = require('@cardstack/plugin-utils/session'); exports.createDefaultEnvironment = async function(projectDir, initialModels = []) { let container; try { let factory = new JSONAPIFactory(); let user = factory.addResource('users', 'the-default-test-user').withAttributes({ fullName: 'Default Test Environment', email: '[email protected]' }).asDocument(); let session = new Session( { id: 'the-default-test-user', type: 'users'}, null, user ); factory.addResource('plugin-configs', '@cardstack/hub') .withRelated( 'default-data-source', factory.addResource('data-sources') .withAttributes({ 'source-type': '@cardstack/ephemeral' }) ); factory.addResource('grants') .withAttributes({ mayCreateResource: true, mayUpdateResource: true, mayDeleteResource: true, mayWriteField: true }).withRelated('who', factory.addResource('groups', user.data.id)); container = await wireItUp(projectDir, crypto.randomBytes(32), factory.getModels(), { allowDevDependencies: true, disableAutomaticIndexing: true }); let writers = container.lookup('hub:writers'); for (let model of initialModels) { // TODO: this one-by-one creation is still slower than is nice for // tests -- each time we write a schema model it invalidates the // schema cache, which needs to get rebuilt before we can write // the next one. // // On the other hand, this is a high-quality test of our ability // to build up the entire state in the same way an end user would // via JSONAPI requests. If we optimize this away, we should also // add some tests like that that are similarly comprehensive. await writers.create('master', session, model.type, model); } await container.lookup('hub:indexers').update({ realTime: true }); Object.assign(container, { session, user, async setUserId(id) { let plugins = await this.lookup('hub:plugins').active(); let m = plugins.lookupFeatureAndAssert('middleware', '@cardstack/test-support-authenticator'); m.userId = id; } }); return container; } catch (err) { // don't leave a half-constructed environment lying around if we // failed. Cleanup whatever parts were already created. if (container) { container.teardown(); } destroyIndices(); temp.cleanup(); throw err; } }; exports.destroyDefaultEnvironment = async function(env) { if (env) { await env.teardown(); await destroyIndices(); await temp.cleanup(); } }; async function destroyIndices() { let ea = new ElasticAssert(); await ea.deleteContentIndices(); }
JavaScript
0
@@ -995,17 +995,56 @@ hemeral' +,%0A params: %7B initialModels %7D %0A - @@ -1475,24 +1475,24 @@ exing: true%0A + %7D);%0A%0A @@ -1492,701 +1492,8 @@ );%0A%0A - let writers = container.lookup('hub:writers');%0A%0A for (let model of initialModels) %7B%0A // TODO: this one-by-one creation is still slower than is nice for%0A // tests -- each time we write a schema model it invalidates the%0A // schema cache, which needs to get rebuilt before we can write%0A // the next one.%0A //%0A // On the other hand, this is a high-quality test of our ability%0A // to build up the entire state in the same way an end user would%0A // via JSONAPI requests. If we optimize this away, we should also%0A // add some tests like that that are similarly comprehensive.%0A await writers.create('master', session, model.type, model);%0A %7D%0A%0A
8271c84ab9d6feab227e916e65f3eac8b9c59713
Change signature
dlog.min.js
dlog.min.js
// dlog.js 0.0.1 // https://github.com/ddo/dlog // (c) 2014 Ddo <http://ddo.me> (function(){function b(a){a=a?a:{};this.setName(a.name);this.setLevel(a.level);this.setSize(a.size)}this.dlog=b;b.prototype.setName=function(a){return this.name=a?a:"DLOG"};b.prototype.setLevel=function(a){this.level=a?this.level_map[a]?a:"info":"info";this.level_no=this.level_map[this.level];return this.level};b.prototype.setSize=function(a){return this.size=a?a:14};b.prototype.level_map={trace:1,debug:2,info:3,warn:4,error:5,silent:6};b.prototype.color_map={name:"cyan",trace:"black",debug:"green", info:"blue",warn:"orange",error:"red"};b.prototype.getCSS=function(a){return a?"font-size: "+this.size+"px;color: "+this.color_map[a]:"font-size: "+this.size+"px"};b.prototype.log=function(a,b){"silent"!==a&&this.level_map[a]>=this.level_no&&this.show(a,b)};b.prototype.isAllObj=function(a){for(var b=0;b<a.length;b++)if("object"!==typeof a[b])return!1;return!0};b.prototype.show=function(a,b){console.log("%c [%s] %c %s %c %s:",this.getCSS(),(new Date).toJSON(),this.getCSS("name"),this.name,this.getCSS(a), a.toUpperCase());Array.isArray(b[0])&&this.isAllObj(b[0])&&console.table(b[0]);console[a].apply(console,b)};b.prototype.trace=function(){this.log("trace",arguments)};b.prototype.debug=function(){this.log("debug",arguments)};b.prototype.info=function(){this.log("info",arguments)};b.prototype.warn=function(){this.log("warn",arguments)};b.prototype.error=function(){this.log("error",arguments)}})();
JavaScript
0.000001
@@ -4,11 +4,8 @@ dlog -.js 0.0 @@ -18,25 +18,23 @@ http -s :// +ddo. github. -com/dd +i o/dl @@ -1481,8 +1481,9 @@ s)%7D%7D)(); +%0A
26bbd9c9a676b05fb74b276b1f2962146012f78e
Add controllers for /api/rooms and /api/messages
server/routes/apiRoutes.js
server/routes/apiRoutes.js
const apiRouter = require('express').Router(); const getMatches = require('../db/controllers/getMatchesGivenSelfAndOffset.js'); const addToRequests = require('../db/controllers/moveMatchIntoRequestsGivenSelfIdAndMatchId.js'); const addToRejects = require('../db/controllers/moveMatchIntoRejectsGivenSelfIdAndMatchId.js'); const changeToRejectFromConnection = require('../db/controllers/moveConnectionIntoRejectsGivenSelfIdAndConnectionId.js'); const changeToConnectionFromRequest = require('../db/controllers/moveRequestIntoConnectionsGivenSelfIdAndRequestId.js'); const changeToRejectFromRequest = require('../db/controllers/moveRequestIntoRejectsGivenSelfIdAndRequestId.js'); apiRouter.route('/matches') .get((req, res) => { // get matches getMatches(req.body.self, req.body.offset) .then(matches => { res.json(matches); }); }); apiRouter.route('/relationships') .post((req, res) => { // post to rejects and requests if (req.body.newType === 'request') { return addToRequests(req.body.selfId, req.body.matchId) .then(() => { res.sendStatus(201); }); } if (req.body.newType === 'reject') { return addToRejects(req.body.selfId, req.body.matchId) .then(() => { res.sendStatus(201); }); } return res.sendStatus(404); }) .put((req, res) => { // change relationship type if (req.body.oldType === 'connection') { return changeToRejectFromConnection(req.body.selfId, req.body.connectionId) .then(() => { res.sendStatus(200); }); } if (req.body.oldType === 'request') { if (req.body.newType === 'connection') { return changeToConnectionFromRequest(req.body.selfId, req.body.requestId) .then(() => { res.sendStatus(200); }); } if (req.body.newType === 'reject') { return changeToRejectFromRequest(req.body.selfId, req.body.requestId) .then(() => { res.sendStatus(200); }); } return res.sendStatus(404); } return res.sendStatus(404); }); apiRouter.route('/profile/:id') .put((req, res) => { // update profile }); module.exports = apiRouter;
JavaScript
0
@@ -39,16 +39,44 @@ outer(); +%0A%0A// controller for /matches %0Aconst g @@ -144,24 +144,59 @@ Offset.js'); +%0A%0A// controllers for /relationships %0Aconst addTo @@ -731,24 +731,523 @@ stId.js');%0A%0A +// controllers for /profile/:id%0Aconst updateDescription = require('../db/controllers/updateDescriptionGivenBodyAndUserId.js');%0Aconst updateLanguages = require('../db/controllers/updateLanguagesGivenTypeAndUserId');%0A%0A// controller for /rooms%0Aconst findRoom = require('../db/controllers/findOrCreateRoomGivenUserIds');%0A%0A// controllers /messages%0Aconst getMessages = require('../db/controllers/getMessagesGivenRoomId');%0Aconst postMessage = require('../db/controllers/postMessageGivenUserIdAndRoomId');%0A%0A apiRouter.ro @@ -1395,16 +1395,69 @@ tches);%0A + %7D)%0A .catch(() =%3E %7B%0A res.sendStatus(404);%0A %7D);%0A @@ -2748,16 +2748,16 @@ e/:id')%0A - .put(( @@ -2797,16 +2797,163 @@ %0A %7D);%0A%0A +apiRouter.route('/rooms')%0A .get((req, res) =%3E %7B%0A%0A %7D);%0A%0AapiRouter.route('/messages')%0A .get((req, res) =%3E %7B%0A%0A %7D)%0A .post((req, res) =%3E %7B%0A%0A %7D);%0A%0A module.e
2219a811fe9596787c6282cb014c042443a7872e
Set the episode category correctly, don't override tagginggs.
walkin/static/js/walkin/controllers/walkin_hospital_number.js
walkin/static/js/walkin/controllers/walkin_hospital_number.js
// // This is our "Enter Walk-in" flow controller // controllers.controller( 'WalkinHospitalNumberCtrl', function($scope, $modalInstance, $modal, $rootScope, schema, options, Episode){ $scope.model = { hospitalNumber : null } $scope.patient = null; // // When we've created an episode with this flow, tag it to the correct // teams and then kill the modal. // $scope.tag_and_close = function(episode){ if(!episode.newItem){ episode = new Episode(episode, schema); }; if(!episode.tagging[0].makeCopy){ episode.tagging[0] = episode.newItem('tagging',{ column: {name: 'tagging', fields: [] } }) } var teams = episode.tagging[0].makeCopy(); var location = episode.location[0].makeCopy(); teams.walkin = true; teams.walkin_triage = true; location.category = 'Walkin'; // // Pre fill some tests: // var stool_ocp = episode.newItem('microbiology_test', {column: $rootScope.fields.microbiology_test}); var malaria_film = episode.newItem('microbiology_test', {column: $rootScope.fields.microbiology_test}); episode.tagging[0].save(teams).then(function(){ episode.location[0].save(location).then(function(){ stool_ocp.save({test: 'Stool OCP'}).then(function(){ malaria_film.save({test: 'Malaria Film'}).then(function(){ episode.active = true; $modalInstance.close(episode); }); }); }) }); }; // // We have an initial hospital number - we can now figure out whether to // Add or pull over. // $scope.findByHospitalNumber = function(){ Episode.findByHospitalNumber( $scope.model.hospitalNumber, { newPatient: $scope.new_patient, newForPatient: $scope.new_for_patient, error: function(){ // This shouldn't happen, but we should probably handle it better alert('ERROR: More than one patient found with hospital number'); $modalInstance.close(null) } } ); }; // // Create a new patient // $scope.new_patient = function(result){ // There is no patient with this hospital number // Show user the form for creating a new episode, // with the hospital number pre-populated modal = $modal.open({ templateUrl: '/templates/modals/add_walkin_episode.html/', controller: 'AddEpisodeCtrl', resolve: { schema: function() { return schema; }, options: function() { return options; }, demographics: function() { return { hospital_number: $scope.hospitalNumber } } } }).result.then(function(result) { // The user has created the episode, or cancelled if(result){ // We made an episode! $scope.tag_and_close(result); }else{ $modalInstance.close(result); } }); }; // // Create a new episode for an existing patient // $scope.new_for_patient = function(patient){ if(patient.active_episode_id && _.keys(patient.episodes).length > 0){ alert('This walkin patient is a current inpatient!'); // // Offer to import the data from this episode. // for (var eix in patient.episodes) { // patient.episodes[eix] = new Episode(patient.episodes[eix], schema); // }; // modal = $modal.open({ // templateUrl: '/templates/modals/reopen_episode.html/', // controller: 'ReopenEpisodeCtrl', // resolve: { // patient: function() { return patient; }, // } // }).result.then( // function(result) { // if(!_.isString(result)){ // $scope.tag_and_close(result); // return // }; // var demographics; // if (result == 'open-new') { // // User has chosen to open a new episode // $scope.add_for_patient(patient); // } else { // // User has chosen to reopen an episode, or cancelled // $modalInstance.close(result); // }; // }, // function(result){ $modalInstance.close(result); }); }else{ $scope.add_for_patient(patient); }; }; // // Add a new episode for an existing patient. Pre-fill the relevant demographics // $scope.add_for_patient = function(patient){ var demographics = patient.demographics[0]; if(demographics.date_of_birth){ var dob = moment(demographics.date_of_birth, 'YYYY-MM-DD') .format('DD/MM/YYYY'); demographics.date_of_birth = dob; } modal = $modal.open({ templateUrl: '/templates/modals/add_walkin_episode.html/', controller: 'AddEpisodeCtrl', resolve: { schema: function() { return schema; }, options: function() { return options; }, demographics: function() { return demographics; } } }).result.then(function(result) { // The user has created the episode, or cancelled if(result){ // We made an episode! $scope.tag_and_close(result); }else{ $modalInstance.close(result); } }); }; // Let's have a nice way to kill the modal. $scope.cancel = function() { $modalInstance.close('cancel'); }; } );
JavaScript
0.999995
@@ -158,16 +158,20 @@ otScope, + $q, %0A @@ -632,241 +632,24 @@ -if(!episode.tagging%5B0%5D.makeCopy)%7B%0A episode.tagging%5B0%5D = episode.newItem('tagging',%7B%0A column: %7Bname: 'tagging', fields: %5B%5D %7D%0A %7D)%0A %7D%0A var teams = episode.tagging%5B0%5D +var ep = episode .mak @@ -732,89 +732,10 @@ -teams.walkin = true;%0A teams.walkin_triage = true;%0A location +ep .cat @@ -1144,55 +1144,50 @@ -episode.tagging%5B0%5D.save(teams).then(function()%7B +$q.all(%5B%0A episode.save(ep), %0A @@ -1233,38 +1233,18 @@ ocation) -.then(function()%7B%0A +,%0A @@ -1290,34 +1290,10 @@ P'%7D) -.then(function()%7B%0A +,%0A @@ -1345,16 +1345,31 @@ Film'%7D) +%0A %5D) .then(fu @@ -1374,36 +1374,24 @@ function()%7B%0A - @@ -1429,36 +1429,24 @@ - - $modalInstan @@ -1480,82 +1480,11 @@ - %7D);%0A %7D);%0A %7D)%0A %7D); +%7D)%0A %0A
6fde0d98881fcc6fc19a87ff26b348fc2307e1d2
fix olElement was not defined
spec/element-list-spec.js
spec/element-list-spec.js
/* @flow */ import "module-alias/register" import { ListElement } from "../dist/elements/list" import { createSuggestion } from "./helpers" import { render } from "solid-js/web" function getOlElement(suggestions) { const rootElement = document.createElement("div") const selectCallback = jasmine.createSpy("suggestion.selected") const { component, setMovement, setConfirmed } = ListElement({ suggestions, selectCallback, movement: "move-to-top" }) render(() => component, rootElement) const intentionList = rootElement.querySelector("#intentions-list") olElement = intentionList.firstElementChild return { olElement, selectCallback, setMovement, setConfirmed } } export function click(elm: HTMLElement) { try { // @ts-ignore internal solid API elm.$$click(new MouseEvent("click")) } catch (e) { elm.click() } } const suggestions = [ createSuggestion("Suggestion 1", jasmine.createSpy("suggestion.selected.0"), "someClass", "someIcon"), createSuggestion("Suggestion 2", jasmine.createSpy("suggestion.selected.1")), createSuggestion("Suggestion 3", jasmine.createSpy("suggestion.selected.2"), "anotherClass"), ] describe("Intentions list element", function () { it("renders the list", () => { const { olElement } = getOlElement(suggestions) expect(olElement.children.length).toBe(3) expect(olElement.children[0].textContent).toBe("Suggestion 1") expect(olElement.children[1].textContent).toBe("Suggestion 2") expect(olElement.children[2].textContent).toBe("Suggestion 3") expect(olElement.children[0].children[0].className).toBe("someClass icon icon-someIcon") expect(olElement.children[2].children[0].className).toBe("anotherClass") }) it("handles click", function () { const { olElement, selectCallback } = getOlElement(suggestions) click(olElement.children[1].children[0]) expect(selectCallback).toHaveBeenCalledWith(suggestions[1]) }) it("handles movement", () => { const { olElement, setMovement } = getOlElement(suggestions) setMovement("down") expect(suggestions[0].title).toBe(olElement.children[0].textContent) setMovement("down") expect(suggestions[1].title).toBe(olElement.children[1].textContent) setMovement("down") expect(suggestions[2].title).toBe(olElement.children[2].textContent) setMovement("up") expect(suggestions[1].title).toBe(olElement.children[1].textContent) setMovement("up") expect(suggestions[0].title).toBe(olElement.children[0].textContent) setMovement("up") expect(suggestions[2].title).toBe(olElement.children[2].textContent) }) })
JavaScript
0.000041
@@ -173,16 +173,57 @@ s/web%22%0A%0A +/* eslint-disable-next-line no-shadow */%0A function @@ -605,16 +605,22 @@ ist%22)%0A +const olElemen
96eb738542b9d3171e05e317c569190044d27679
Add new Modal storybook doc
packages/storybook/examples/core/Modal/index.js
packages/storybook/examples/core/Modal/index.js
import React from 'react'; import { storiesOf } from '@storybook/react'; import { withInfo } from '@storybook/addon-info'; import Modal, { PureModal } from '@ichef/gypcrete/src/Modal'; import { getAddonOptions } from 'utils/getPropTables'; import ContainsColumnView from '../SplitView/ContainsColumnView'; import ClosableModalExample, { MulitpleClosableModalExample } from './ClosableModalExample'; storiesOf('@ichef/gypcrete|Modal', module) .addDecorator(withInfo) .add( 'basic modal', () => ( <Modal header="Basic modal"> Hello World! </Modal> ) ) .add( 'closable modal', () => <ClosableModalExample /> ) .add( 'with <SplitView>', () => ( <Modal header="With <SplitView>" flexBody bodyPadding={{ bottom: 0 }}> <ContainsColumnView /> </Modal> ) ) .add( 'centered modal', () => ( <Modal header="Vertically-centered modal"> Hello World! </Modal> ) ) .add( 'multiple layer modals', () => <MulitpleClosableModalExample depth={10} />, { info: 'Indented with 32px from each side for each layer. When number of layer > 7 we won\'t indent it', } ) // Props table .add( 'props', () => <div />, { info: getAddonOptions([PureModal, Modal]) } );
JavaScript
0
@@ -23,104 +23,8 @@ ct'; -%0Aimport %7B storiesOf %7D from '@storybook/react';%0Aimport %7B withInfo %7D from '@storybook/addon-info'; %0A%0Aim @@ -86,63 +86,8 @@ al'; -%0Aimport %7B getAddonOptions %7D from 'utils/getPropTables'; %0A%0Aim @@ -248,132 +248,195 @@ ';%0A%0A -storiesOf('@ichef/gypcrete%7CModal', module)%0A .addDecorator(withInfo)%0A .add(%0A 'basic m +export default %7B%0A title: '@ichef/gypcrete%7CModal',%0A component: PureModal,%0A subcomponents: %7B%0A 'renderToLayer()': M odal -', %0A - () =%3E (%0A +%7D,%0A%7D%0A%0Aexport function BasicModal() %7B%0A return (%0A @@ -472,36 +472,32 @@ l%22%3E%0A - Hello World!%0A @@ -493,36 +493,32 @@ World!%0A - - %3C/Modal%3E%0A @@ -518,69 +518,58 @@ - )%0A )%0A .add(%0A 'c +);%0A%7D%0A%0Aexport function C losable - m +M odal -', +() %7B %0A - () =%3E +return %3CCl @@ -593,73 +593,61 @@ e /%3E -%0A )%0A .add(%0A 'with %3CSplitView%3E',%0A () =%3E (%0A +;%0A%7D%0A%0Aexport function SplitViewModal() %7B%0A return (%0A @@ -733,20 +733,16 @@ - %3CContain @@ -756,36 +756,32 @@ View /%3E%0A - - %3C/Modal%3E%0A @@ -781,83 +781,128 @@ - )%0A )%0A .add(%0A 'c +);%0A%7D%0A%0ASplitViewModal.story = %7B%0A name: 'With %3CSplitView%3E',%0A%7D;%0A%0Aexport function C entered - m +M odal -',%0A () =%3E (%0A +() %7B%0A return (%0A %3CMo @@ -893,25 +893,24 @@ n (%0A - %3CModal heade @@ -934,24 +934,33 @@ tered modal%22 + centered %3E%0A @@ -953,36 +953,32 @@ ed%3E%0A - - Hello World!%0A @@ -978,28 +978,24 @@ ld!%0A - %3C/Modal%3E%0A @@ -995,80 +995,68 @@ al%3E%0A - ) -%0A )%0A .add(%0A 'm +;%0A%7D%0A%0Aexport function M ulti +l ple - l +L ayer - m +M odal -s', +() %7B %0A - () =%3E +return %3CMu @@ -1095,25 +1095,76 @@ =%7B10%7D /%3E -, +;%0A%7D%0A%0AMultilpleLayerModal.story = %7B%0A parameters: %7B %0A %7B%0A @@ -1155,16 +1155,22 @@ %0A + docs: %7B%0A @@ -1176,20 +1176,32 @@ -info +storyDescription : 'Inden @@ -1305,141 +1305,16 @@ %7D -%0A )%0A // Props table%0A .add(%0A 'props',%0A () =%3E %3Cdiv /%3E,%0A %7B info: getAddonOptions(%5BPureModal, Modal%5D) %7D%0A ) +,%0A %7D,%0A%7D ;%0A
0702db8819454033e31af8932cb6ac77689b4a1e
Fix minor typo
packages/truffle/lib/repl.js
packages/truffle/lib/repl.js
var repl = require("repl"); var Command = require("./command"); var provision = require("truffle-provisioner"); var contract = require("truffle-contract"); var Web3 = require("web3"); var vm = require("vm"); var expect = require("truffle-expect"); var _ = require("lodash"); var TruffleError = require("truffle-error"); var fs = require("fs"); var path = require("path"); function TruffleInterpreter(tasks, options) { this.options = options; this.r = null; this.command = new Command(tasks); }; TruffleInterpreter.prototype.start = function() { var self = this; var options = this.options; var web3 = new Web3(); web3.setProvider(options.provider); this.provision(function(err, abstractions) { if (err) { options.logger.log("Enexpected error: Cannot provision contracts while instantiating the console."); options.logger.log(err.stack || err.message || err); } var prefix = "truffle(" + options.network + ")> "; try { self.r = repl.start({ prompt: prefix, eval: self.interpret.bind(self) }); self.r.on("exit", function() { process.exit(1); }); self.resetContractsInConsoleContext(abstractions); self.r.context.web3 = web3; } catch(e) { console.log(e.stack); process.exit(1); } }); }; TruffleInterpreter.prototype.provision = function(callback) { var self = this; fs.readdir(this.options.contracts_build_directory, function(err, files) { if (err) return callback(err); var promises = []; files.forEach(function(file) { promises.push(new Promise(function(accept, reject) { fs.readFile(path.join(self.options.contracts_build_directory, file), "utf8", function(err, body) { if (err) return reject(err); try { body = JSON.parse(body); } catch (e) { return reject(new Error("Cannot parse " + file + ": " + e.message)); } accept(body); }) })) }); Promise.all(promises).then(function(json_blobs) { var abstractions = json_blobs.map(function(json) { var abstraction = contract(json); provision(abstraction, self.options); return abstraction; }); self.resetContractsInConsoleContext(abstractions); callback(null, abstractions); }).catch(callback); }); }; TruffleInterpreter.prototype.resetContractsInConsoleContext = function(abstractions) { var self = this; if (this.r != null) { abstractions.forEach(function(abstraction) { self.r.context[abstraction.contract_name] = abstraction; }); } } TruffleInterpreter.prototype.interpret = function(cmd, context, filename, callback) { var self = this; if (this.command.getCommand(cmd.trim()) != null) { return this.command.run(cmd.trim(), this.options, function(err) { if (err) { // Perform error handling ourselves. if (err instanceof TruffleError) { console.log(err.message); } else { // Bubble up all other unexpected errors. console.log(err.stack || err.toString()); } return callback(); } // Reprovision after each command is it may change contracts. self.provision(function(err, abstractions) { // Don't pass abstractions to the callback if they're there or else // they'll get printed in the repl. callback(err); }); }); } var result; try { result = vm.runInContext(cmd, context, { displayErrors: false }); } catch (e) { return callback(e); } // Resolve all promises. This will leave non-promises alone. Promise.resolve(result).then(function(res) { callback(null, res) }).catch(callback); } var Repl = { TruffleInterpreter: TruffleInterpreter, run: function(tasks, options) { var self = this; expect.options(options, [ "working_directory", "contracts_directory", "contracts_build_directory", "migrations_directory", "network", "network_id", "provider", "resolver", "build_directory" ]); var interpreter = new TruffleInterpreter(tasks, options); interpreter.start(); } } module.exports = Repl;
JavaScript
0.999993
@@ -748,17 +748,17 @@ er.log(%22 -E +U nexpecte
6944bc9b643479a837de18e77003ba8152eefe33
Change File->New to File->New Notebook in Control Panel
core/src/main/web/plugin/menu/controlpanel.js
core/src/main/web/plugin/menu/controlpanel.js
/* * Copyright 2014 TWO SIGMA OPEN SOURCE, 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This plugins menu items for the control panel */ define(function(require, exports, module) { 'use strict'; var fileMenuItems = [ { name: "New", tooltip: "Open a new empty notebook, add the languages of your choice", sortorder: 100, action: function() { bkHelper.newSession(true); } }, { name: "Open recent", sortorder: 120, items: function() { return bkHelper.getRecentMenuItems(); } }, { name: "Open", sortorder: 110 } ]; var menuItemsDeferred = bkHelper.newDeferred(); bkHelper.getHomeDirectory().then(function(homeDir) { var toAdd = [ { parent: "File", items: fileMenuItems }, { parent: "File", submenu: "Open", submenusortorder: 110, items: [ { name: "Open... (.bkr)", tooltip: "Open a bkr notebook file", sortorder: 100, action: function() { bkHelper.showModalDialog( function(originalUrl) { bkHelper.openNotebook(originalUrl); }, JST['template/opennotebook']({homedir: homeDir, extension: '.bkr'}), bkHelper.getFileSystemFileChooserStrategy() ); } } ] } ]; menuItemsDeferred.resolve(toAdd); }); exports.getMenuItems = function() { return menuItemsDeferred.promise; }; });
JavaScript
0
@@ -780,16 +780,25 @@ me: %22New + Notebook %22,%0A
fccd5843ae6c041703c6e0bb26193ff78ec2e429
Update dbservice.js
routes/dbservice.js
routes/dbservice.js
var mongoose = require('mongoose'); var db; var cfenv = require('cfenv'); var appenv = cfenv.getAppEnv(); if (process.env.VCAP_SERVICES) { var mongoDbUrl, mongoDbOptions = {}; var mongoDbCredentials = appEnv.getServiceCreds("compose-for-mongodb").credentials; var ca = [new Buffer(mongoDbCredentials.ca_certificate_base64, 'base64')]; mongoDbUrl = mongoDbCredentials.uri; mongoDbOptions = { mongos: { ssl: true, sslValidate: true, sslCA: ca, poolSize: 1, reconnectTries: 1 } }; console.log("Connecting to", mongoDbUrl); db= mongoose.connect(mongoDbUrl, mongoDbOptions); } else { db = mongoose.createConnection('localhost', 'ikeasocialapp'); } exports.db = db;
JavaScript
0.000001
@@ -210,17 +210,17 @@ ls = app -E +e nv.getSe
a2e1f473e93cce6d21aca19163be33da21e4da6b
add TB, TW
src/modules/rotation.js
src/modules/rotation.js
// Note that these functions are only valid for square boards. const simple = ['AB', 'AW', 'AE', 'B', 'CR', 'DD', 'MA', 'SL', 'SQ', 'TR', 'VW', 'W']; const pointWithText = ['LB']; const arrowish = ['AR', 'LN']; const alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; const alphaRev = 'ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba'; exports.rotatePointClockwise = function(point, size) { // returns null on failure ; point is something like "aa" if (typeof point !== 'string') return null; if (typeof size !== 'number') return null; if (size < 1 || size > 52) return null; if (point.length !== 2) return null; let index0 = alpha.indexOf(point[0]); let index1 = alpha.indexOf(point[1]); if (index0 === -1 || index1 === -1) return null; let rev = alphaRev.slice(52 - size); return rev[index1] + point[0]; }; exports.rotateRectClockwise = function(rect, size) { // returns null on failure ; rect is something like "aa:cc" if (typeof size !== 'number') return null; if (typeof rect !== 'string') return null; if (size < 1 || size > 52) return null; if (rect.length !== 5) return null; if (rect[2] !== ':') return null; let first = rect.slice(0, 2); let second = rect.slice(3, 5); first = exports.rotatePointClockwise(first, size); second = exports.rotatePointClockwise(second, size); if (first === null || second === null) { return null; } return second[0] + first[1] + ":" + first[0] + second[1]; }; exports.rotateArrowClockwise = function(arrow, size) { // returns null on failure ; arrow is something like "aa:cc" if (typeof size !== 'number') return null; if (typeof arrow !== 'string') return null; if (size < 1 || size > 52) return null; if (arrow.length !== 5) return null; if (arrow[2] !== ':') return null; let first = arrow.slice(0, 2); let second = arrow.slice(3, 5); first = exports.rotatePointClockwise(first, size); second = exports.rotatePointClockwise(second, size); if (first === null || second === null) { return null; } return first + ":" + second; }; exports.rotateNodeClockwise = function(node, size) { // Given a node and a board size, rotates all relevant properties in the node. // Does NOT do anything about the board though. if (typeof size !== 'number') { return; } // 'simple' cases are either a single point (e.g. "aa") or a rect (e.g. "aa:cc") for (let k = 0; k < simple.length; k++) { let key = simple[k]; if (node[key] !== undefined) { let values = node[key]; for (let v = 0; v < values.length; v++) { let value = values[v]; if (value.length === 2) { let result = exports.rotatePointClockwise(value, size); if (result) { values[v] = result; } } else if (value.length === 5 && value[2] === ":") { let result = exports.rotateRectClockwise(value, size); if (result) { values[v] = result; } } } } } // 'pointWithText' means something like "aa:hi there" for (let k = 0; k < pointWithText.length; k++) { let key = pointWithText[k]; if (node[key] !== undefined) { let values = node[key]; for (let v = 0; v < values.length; v++) { let value = values[v]; if (value[2] === ':') { let point = value.slice(0, 2); point = exports.rotatePointClockwise(point, size); if (point) { values[v] = point + value.slice(2); } } } } } // 'arrowish' things are formatted like rects, but with no requirement of topleft:bottomright for (let k = 0; k < arrowish.length; k++) { let key = arrowish[k]; if (node[key] !== undefined) { let values = node[key]; for (let v = 0; v < values.length; v++) { let value = values[v]; if (value[2] === ':') { let result = exports.rotateArrowClockwise(value, size); if (result) { values[v] = result; } } } } } };
JavaScript
0.999348
@@ -128,17 +128,29 @@ 'SQ', 'T -R +B', 'TR', 'TW ', 'VW',
8358f2d2c7bce0336e711b9fe90e8f68dd4eab6c
use history.replaceState instead of redirecting ?p=page requests
cms-less.js
cms-less.js
var CmsLess = ( function($) { var config = { contentPath: 'cms-less-content', destinationSelector: '#cms-less-destination', anchorDelimiter: '-', notFoundPageName: '404' } function loadContent(pageName) { beforePageLoad(pageName); $(config.destinationSelector).load(expandedContentPath(pageName), function(response, status) { var actualPageName; if(status == 'error') { $(config.destinationSelector).load(expandedContentPath(config.notFoundPageName)); markPageAsIndexable(false); afterPageLoad(config.notFoundPageName); } else { markPageAsIndexable(true); afterPageLoad(pageName); } }); } function markPageAsIndexable(indexable) { if(indexable) { $("head meta[name='robots']").remove(); } else { $("head").append($("<meta name='robots' content='noindex' />")); } } function beforePageLoad(newPageName) { // scroll to the top document.body.scrollTop = document.documentElement.scrollTop = 0; } function afterPageLoad(newPageName) { // dispatch an event pageChangeEvent = new CustomEvent('cms-less-page-change', { 'detail': { pageName: newPageName }}); document.dispatchEvent(pageChangeEvent); } function expandedContentPath(pageName) { return config.contentPath + "/" + pageName + ".html"; } function loadContentFromHash() { var pageName = extractPageNameFromHash() || 'index'; loadContent(pageName); } function extractPageNameFromHash(hash) { hash = hash || window.location.hash delimiterIndex = hash.lastIndexOf(config.anchorDelimiter); if(delimiterIndex > 0) { return hash.slice(1, delimiterIndex); } else { return hash.slice(1); } } function Init(options) { config = $.extend(config, options); // if the path has a query parameter, change it to a hash parameter if(window.location.href.match(/\?p=.+/)) { var pageName = window.location.href.match(/\?p=(.*)$/)[1].split("&")[0]; window.location.href = "/#" + pageName; } loadContentFromHash(); $(window).bind('hashchange', loadContentFromHash); // progressively enhance links $("a[data-cms-less-path]").each(function() { var link = $(this); link.attr("href", "#" + link.attr("data-cms-less-path")); }); } return { Init : Init, PageName : extractPageNameFromHash }; } )( jQuery );
JavaScript
0.000001
@@ -2039,28 +2039,59 @@ dow. -location.href = %22/#%22 +history.replaceState(pageName, document.title, '/#' + p @@ -2093,24 +2093,25 @@ ' + pageName +) ;%0A %7D%0A%0A
1f05600850ff6093046e946e3d4c7f095532ed16
Update post-page
public/js/post-list/template.js
public/js/post-list/template.js
(function (window) { 'use strict'; var htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', '\'': '&#x27;', '`': '&#x60;' }; var escapeHtmlChar = function (chr) { return htmlEscapes[chr]; }; var reUnescapedHtml = /[&<>"'`]/g; var reHasUnescapedHtml = new RegExp(reUnescapedHtml.source); var escape = function (string) { return (string && reHasUnescapedHtml.test(string)) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; }; /** * Sets up defaults for all the Template methods such as a default template * * @constructor */ function Template() { this.defaultTemplate = '<li data-id="{{id}}" class="post-item">' + '<div class="post-title">{{title}}</div>' + '<div class="post-info">' + '<span class="post-author">{{author}}</span>' + '<span class="post-date">{{written}}</span>' + '<span class="post-label post-view-label">View</span>' + '<span class="post-value post-view">{{readCount}}</span>' + '<span class="post-label post-like-label active"></span>' + '<span class="post-value post-like">{{likeCount}}</span>' + '<span class="post-label post-dislike-label"></span>' + '<span class="post-value post-dislike">{{dislikeCount}}</span>' + '</div>' + '</li>'; } Template.prototype.show = function(data) { var i, l; var view = ''; for (i = 0, l = data.length; i < l; i++) { var template = this.defaultTemplate; template = template.replace('{{id}}', data[i].pid); template = template.replace('{{title}}', escape(data[i].title)); template = template.replace('{{author}}', escape(data[i].author)); template = template.replace('{{written}}', escape(data[i].written)); template = template.replace('{{readCount}}', escape(data[i].readCount)); template = template.replace('{{likeCount}}', escape(data[i].likeCount)); template = template.replace('{{dislikeCount}}', escape(data[i].dislikeCount)); view = view + template; } return view; }; // Export to window window.app = window.app || {}; window.app.Template = Template; })(window);
JavaScript
0
@@ -720,24 +720,60 @@ ost-item%22%3E'%0A + +%09%09'%3Ca href=%22/post/%7B%7Bid%7D%7D%22%22%3E'%0A +%09%09'%3Cd @@ -1396,24 +1396,41 @@ '%3C/div%3E'%0A + + '%3C/a%3E'%0A +%09'%3C/l @@ -1647,16 +1647,18 @@ ace( -' +/ %7B%7Bid%7D%7D -' +/gi , da
aecdd9d630aad424d487c91ff90463bd8e026660
update example to use a module
src/ng/directive/ngInit.js
src/ng/directive/ngInit.js
'use strict'; /** * @ngdoc directive * @name ngInit * @restrict AC * * @description * The `ngInit` directive allows you to evaluate an expression in the * current scope. * * <div class="alert alert-error"> * The only appropriate use of `ngInit` is for aliasing special properties of * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you * should use {@link guide/controller controllers} rather than `ngInit` * to initialize values on a scope. * </div> * <div class="alert alert-warning"> * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make * sure you have parenthesis for correct precedence: * <pre class="prettyprint"> * <div ng-init="test1 = (data | orderBy:'name')"></div> * </pre> * </div> * * @priority 450 * * @element ANY * @param {expression} ngInit {@link guide/expression Expression} to eval. * * @example <example> <file name="index.html"> <script> function Ctrl($scope) { $scope.list = [['a', 'b'], ['c', 'd']]; } </script> <div ng-controller="Ctrl"> <div ng-repeat="innerList in list" ng-init="outerIndex = $index"> <div ng-repeat="value in innerList" ng-init="innerIndex = $index"> <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span> </div> </div> </div> </file> <file name="protractor.js" type="protractor"> it('should alias index positions', function() { var elements = element.all(by.css('.example-init')); expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;'); expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;'); expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;'); expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;'); }); </file> </example> */ var ngInitDirective = ngDirective({ priority: 450, compile: function() { return { pre: function(scope, element, attrs) { scope.$eval(attrs.ngInit); } }; } });
JavaScript
0
@@ -932,16 +932,37 @@ %3Cexample + module=%22initExample%22 %3E%0A %3C @@ -1002,24 +1002,109 @@ t%3E%0A +angular.module('initExample', %5B%5D)%0A .controller('ExampleController', %5B'$scope', function Ctrl($s @@ -1099,13 +1099,8 @@ tion - Ctrl ($sc @@ -1102,24 +1102,26 @@ n($scope) %7B%0A + $scop @@ -1156,25 +1156,30 @@ 'd'%5D%5D;%0A -%7D + %7D%5D); %0A %3C/script @@ -1207,12 +1207,25 @@ er=%22 -Ctrl +ExampleController %22%3E%0A
6f055ace25d704262e8f4609461eca2fd1701329
Add tag functionality to ~issue
github.js
github.js
/** * Module Name: Github * Description: Retrieves interesting Github information */ var request = require('request'), _ = require('underscore')._, exec = require('child_process').exec; var github = function(dbot) { var commands = { '~repocount': function(event) { var reqUrl = "https://api.github.com/users/" + event.params[1] + "/repos"; request(reqUrl, function(error, response, body) { if(response.statusCode == "200") { var result = JSON.parse(body); event.reply(dbot.t("repocount",{"user": event.params[1], "count": result.length})); } else { event.reply(dbot.t("usernotfound")); } }); }, '~repo': function(event) { var repo = event.params[1]; if (typeof repo == 'undefined') { repo = dbot.config.github.defaultrepo; } var reqUrl = "https://api.github.com/"; reqUrl += "repos/" + repo; request(reqUrl, function(error, response, body) { var data = JSON.parse(body); if (data["fork"] == true) { event.reply(dbot.t("forkedrepo",data)); } else { event.reply(dbot.t("unforkedrepo",data)); } // TODO: move this shizz into an api call var longurl = "http://github.com/" + repo; request({method: 'POST', uri: 'http://git.io', form:{url: longurl}}, function(error, response, body){ event.reply(dbot.t('location')+" "+response.headers["location"]); }); }); }, '~gstatus': function(event) { var reqUrl = "https://status.github.com/api/last-message.json"; request(reqUrl, function(error,response,body){ var data = JSON.parse(body); event.reply(dbot.t("status"+data["status"])); event.reply(data["body"]); }); }, '~milestone': function(event) { var repo = dbot.config.github.defaultrepo; var reqUrl = "https://api.github.com/repos/"; reqUrl += repo + "/milestones"; request(reqUrl, function(error, response, body) { var data = JSON.parse(body); for (var section in data) { var milestone = data[section]; if (milestone["title"] == event.params[1]){ var str = "Milestone " + milestone["title"]; var progress = milestone["closed_issues"] / (milestone["open_issues"] + milestone["closed_issues"]); progress = Math.round(progress*100); var bar = "["; for (var i = 10; i < 100; i += 10) { if ((progress/i) > 1) { bar += "█"; } else { bar += " "; } } bar += "]"; str += " is " + bar + progress + "% complete"; var longurl = "http://github.com/" + repo + "/issues?milestone=" + milestone["number"]; request({method: 'POST', uri: 'http://git.io', form:{url: longurl}}, function(error, response, body){ event.reply(response.headers["location"]); }); event.reply(str); break; } } }); }, '~repocount': function(event) { // TODO: add handling for non existent user var reqUrl = "https://api.github.com/users/" + event.params[1] + "/repos"; request(reqUrl, function(error, response, body) { var result = JSON.parse(body); event.reply(event.params[1] + " has " + result.length + " public repositories."); }); }, '~issue': function(event) { var repo = dbot.config.github.defaultrepo; var issue = event.params[1]; if (isNaN(event.params[1])){ repo = event.params[1]; issue = event.params[2]; } var reqUrl = "https://api.github.com/repos/" + repo + "/issues/" + issue; request(reqUrl, function(error,response, body) { if (response.statusCode == "200") { var data = JSON.parse(body); if (data["pull_request"]["html_url"] != null){ console.log(data["pull_request"]["html_url"]); data["pull_request"] = " with code"; } else { data["pull_request"] = ""; } if (data["state"]=="open") { data["state"] = "\u000303" + data["state"]; } else { data["state"] = "\u000304" + data["state"]; } //for (label in data["labels"]){ // data["label"] = data["label"] + " " + label["name"]; //} event.reply(dbot.t("issue",data)); event.reply(data["html_url"]); } else { event.reply(dbot.t("issuenotfound")); } }); }, '~commits': function(event) { exec("git rev-list --all | wc -l", function(error, stdout, stderr) { stdout = stdout.trim(); request("http://numbersapi.com/" + stdout + "?fragment&default=XXX", function(error, response, body){ if (body != "XXX"){ event.reply(dbot.t("commitcountfun",{"fact": body, "count": stdout})); } else { // nothing fun about the number, let's try the year request("http://numbersapi.com/" + stdout + "/year?fragment&default=XXX", function(error, response, body){ if (body != "XXX"){ event.reply(dbot.t("commitcountyear",{"fact": body, "count": stdout})); } else { event.reply(dbot.t("commitcountboring",{"count": stdout})); } }); } }); }); } }; this.commands = commands; this.on = 'PRIVMSG'; }; exports.fetch = function(dbot) { return new github(dbot); };
JavaScript
0.000001
@@ -5194,40 +5194,118 @@ -//fo +va r -( label - in data%5B%22labels%22%5D)%7B +s = %22%22;%0A for (var i=0; i %3C data%5B%22labels%22%5D.length; i++) %7B // for-in doesn't like me %0A @@ -5325,14 +5325,45 @@ -// +var color = %22%5Cu0003%22 + (parseInt( data @@ -5373,40 +5373,100 @@ abel +s %22%5D - = data%5B%22 +%5Bi%5D%5B%22color%22%5D,16) %25 15);%0A label -%22%5D +s + += %22 %22 + -label +color + data%5B%22labels%22%5D%5Bi%5D %5B%22na @@ -5495,11 +5495,53 @@ -//%7D +%7D%0A data%5B%22label%22%5D = labels; %0A
c673b346e1f5bedb6db602f44375f3996eb77e6c
Remove unused var
europeana.js
europeana.js
/* Name: europeana.js Description: Unofficial node.js module for the Europeana API Author: Franklin van de Meent - https://frankl.in Source: https://github.com/fvdm/nodejs-europeana Feedback: https://github.com/fvdm/nodejs-europeana/issues License: Public Domain / Unlicense (see UNLICENSE file) (https://github.com/fvdm/nodejs-europeana/raw/master/UNLICENSE) */ var http = require ('httpreq'); var settings = { apikey: null, timeout: 5000 }; // errors // http://www.europeana.eu/portal/api-working-with-api.html#Error-Codes var errors = { 400: 'The request sent by the client was syntactically incorrect', 401: 'Authentication credentials were missing or authentication failed.', 404: 'The requested record was not found.', 429: 'The request could be served because the application has reached its usage limit.', 500: 'Internal Server Error. Something has gone wrong, please report to us.' }; /** * Make and call back error * * @callback callback * @param message {string} - Error.message * @param err {mixed} - Error.error * @param res {object} - httpreq response details * @param callback {function} - `function (err) {}` * @returns {void} */ function doError (message, err, res, callback) { var error = new Error (message); error.code = res.statusCode; error.error = err || errors [res.statusCode] || null; error.data = res.body; callback (error); } /** * Process response * * @callback callback * @param err {Error, null} - httpreq error * @param res {object} - httpreq response details * @param callback {function} - `function (err, data) {}` * @returns {void} */ function httpResponse (err, res, callback) { var data = res && res.body; var error = null; var html; // client failed if (err) { doError ('request failed', err, res, callback); return; } // parse response try { data = JSON.parse (data); } catch (reason) { // weird API error if (data.match (/<h1>HTTP Status /)) { html = data.replace (/.*<b>description<\/b> <u>(.+)<\/u><\/p>.*/, '$1'); doError ('API error', html, res, callback); } else { doError ('invalid response', reason, res, callback); } return; } if (data.apikey) { delete data.apikey; } // API error if (!data.success && data.error) { doError ('API error', data.error, res, callback); return; } if (res.statusCode >= 300) { doError ('API error', null, res, callback); return; } // all good callback (null, data); } /** * Communicate with API * * @callback callback * @param path {string} - Method path between `/v2/` and `.json` * @param fields {object} - Method parameters * @param callback {function} - `function (err, data) {}` * @returns {void} */ function httpRequest (path, fields, callback) { var options = { method: 'GET', url: 'https://www.europeana.eu/api/v2/' + path + '.json', parameters: fields, timeout: settings.timeout, headers: { 'User-Agent': 'europeana.js' } }; if (typeof fields === 'function') { callback = fields; options.parameters = {}; } // Request // check API key if (!settings.apikey) { callback (new Error ('apikey missing')); return; } options.parameters.wskey = settings.apikey; function doResponse (err, res) { httpResponse (err, res, callback); } http.doRequest (options, doResponse); } /** * Module interface * * @param [apikey] {string} - Your Europeana API key * @param [timeout = 5000] {number} - Request wait timeout in ms * @returns httpRequest {function} */ function setup (apikey, timeout) { settings.apikey = apikey || null; settings.timeout = timeout || settings.timeout; return httpRequest; } module.exports = setup;
JavaScript
0.000001
@@ -1738,28 +1738,8 @@ dy;%0A - var error = null;%0A va
535aa820760222806d5c12a464d828616dd01417
remove day reference line
app/components/UpcomingReviewsChart/DayTick.js
app/components/UpcomingReviewsChart/DayTick.js
import React from 'react'; import PropTypes from 'prop-types'; import { greyDark, grey } from 'shared/styles/colors'; const DayTick = ({ x, y, width, height, payload: { value }, }) => value ? ( <g> <text width={width} height={height} x={x} y={y} dx={0} dy={-10} textAnchor="middle" fill={greyDark} fontSize=".85rem" > {value} </text> {/* manually render a reference line */} <line x1={x} y1={y - 6} x2={x} y2={y + 2} stroke={grey} strokeWidth={1.5} fill="none" /> </g> ) : null; /* eslint-disable react/require-default-props */ DayTick.propTypes = { x: PropTypes.number, y: PropTypes.number, width: PropTypes.number, height: PropTypes.number, payload: PropTypes.object, }; export default DayTick;
JavaScript
0
@@ -78,14 +78,8 @@ Dark -, grey %7D f @@ -106,16 +106,16 @@ olors';%0A + %0Aconst D @@ -174,16 +174,18 @@ %7D,%0A%7D) =%3E +%0A value ? @@ -187,16 +187,18 @@ lue ? (%0A + %3Cg%3E%0A @@ -199,16 +199,18 @@ %3Cg%3E%0A + %3Ctext%0A @@ -213,16 +213,18 @@ t%0A + + width=%7Bw @@ -229,16 +229,18 @@ %7Bwidth%7D%0A + he @@ -263,14 +263,18 @@ + x=%7Bx%7D%0A + @@ -291,15 +291,19 @@ + dx=%7B0%7D%0A + @@ -319,16 +319,18 @@ %7D%0A + textAnch @@ -343,24 +343,26 @@ ddle%22%0A + + fill=%7BgreyDa @@ -365,16 +365,18 @@ eyDark%7D%0A + fo @@ -395,24 +395,26 @@ em%22%0A + %3E%0A %7Bvalue%7D%0A @@ -409,16 +409,18 @@ + + %7Bvalue%7D%0A @@ -415,16 +415,18 @@ %7Bvalue%7D%0A + %3C/te @@ -437,195 +437,15 @@ -%7B/* manually render a reference line */%7D%0A %3Cline%0A x1=%7Bx%7D%0A y1=%7By - 6%7D%0A x2=%7Bx%7D%0A y2=%7By + 2%7D%0A stroke=%7Bgrey%7D%0A strokeWidth=%7B1.5%7D%0A fill=%22none%22%0A /%3E%0A %3C/g%3E%0A + ) :
417db6bd07e732e36eae3cf00c41443e61f54f03
Add coin and dice command
commands.js
commands.js
module.exports = { 'ping': (message) => { message.reply("pong!"); }, 'echo': (message, _, msg) => { if (msg) { message.channel.send(msg); } }, 'prefix': (message, _, __, newPrefix) => { if (newPrefix) { config.prefix = newPrefix; fs.writeFile("./config.json", JSON.stringify(config, null, 4), err => console.error); message.channel.send(`Prefix successfully set to '${newPrefix}'`) } else { message.channel.send("Please provide a prefix."); } }, 'die': (message, soupmaster) => { if (message.author.id === soupmaster.id) { message.channel.send("Emptying can...") .then(() => { console.log("Forced to disconnect."); process.exit(0); }); } }, 'factcheck': (message, _, msg) => { let bool1 = (Math.random() >= 0.5) let bool2 = (Math.random() >= 0.5) let str; if (msg) { str = `${message.author}'s claim, "${msg}",` str = bool1 ? `${str} is obviously ${bool2.toString()}.` : `${str} can't possibly be ${bool2.toString()}.`; } else { str = bool1 ? `${message.author} is totally ${bool2 ? "right" : "wrong"}.` : `${message.author} is never ${bool2 ? "right" : "wrong"}.` } message.channel.send(str); } }
JavaScript
0.000061
@@ -949,33 +949,32 @@ (Math.random() %3E -= 0.5)%0A le @@ -999,17 +999,16 @@ ndom() %3E -= 0.5)%0A @@ -1312,15 +1312,14 @@ is -totally +always $%7Bb @@ -1437,24 +1437,24 @@ %60%0A %7D%0A - mess @@ -1472,19 +1472,252 @@ .send(str);%0A + %7D,%0A%0A 'coin': (message) =%3E %7B%0A let bool = (Math.random() %3E 0.5);%0A message.channel.send(bool ? %22Heads.%22 : %22Tails.%22);%0A %7D,%0A%0A 'dice': (message) =%3E %7B%0A message.channel.send(Math.floor(Math.random()*6) + 1);%0A %7D%0A%7D
d073b7b48714043512feee1733b89a4c671dd808
fix searching for ember-data items
app/components/search-input/dropdown-result.js
app/components/search-input/dropdown-result.js
import { gt } from '@ember/object/computed'; import { computed } from '@ember/object'; import Component from '@ember/component'; export default Component.extend({ // Public API result: Object.freeze({}), role: 'option', groupName: '', groupPosition: 0, // Index of this result in the grouped results module: computed('result.{project,module}', function () { if (this.get('result.project')) { return this.get('result.project'); } return this.get('result.module') === 'ember-data' ? 'ember-data' : 'ember' }), // Private API classNames: ['ds-suggestion'], attributeBindings: ['role'], version: computed('result._tags.[]', function () { let versionTag = this.get('result._tags').find(_tag => _tag.indexOf('version:') > -1); let versionSegments = versionTag.replace('version:', '').split('.'); return `${versionSegments[0]}.${versionSegments[1]}`; }), // Left sidebar should only be displayed for the first result in the group _primaryColumn: computed('groupPosition,groupName', function () { const { groupName, groupPosition } = this; return groupPosition === 0? groupName : ''; }), isSecondary: gt('groupPosition', 0) });
JavaScript
0.000001
@@ -450,30 +450,36 @@ ;%0A %7D%0A -return +let module = this.get('r @@ -496,50 +496,102 @@ le') - === 'ember-data' ? 'ember-data' : +;%0A if (module.includes('ember-data')) %7B%0A return 'ember-data';%0A %7D%0A return 'ember' %0A %7D @@ -586,16 +586,17 @@ 'ember' +; %0A %7D),%0A
09df9666dec0a6bdc27629eb30afaf64b8da96ad
fix set info method in list view: return when there is a search/filter result in the list
source/view/list/insert.js
source/view/list/insert.js
/** * Insert List.V2 View Class * @class View.List.V2.Insert * @author Bruno Santos, Jerome Vial */ define(function(require, exports, module) { var _log = __debug('view-core-listV2-insert').defineLevel(); var Insert = new Class({ /** * new info * @return {void} */ new: function(info) { _log.debug('new', info); //handle view in arg if (info === this) { info = {}; } info = info || {}; var newInfo = { _id: 'new', type: this.options.data.type, nodes: [] }; info = Object.merge(newInfo, info); if ( this.options.data && this.options.data._id && info.nodes.indexOf(this.options.data._id) === -1 ) { info.nodes.push(this.options.data._id); } this.remove('new'); this._setInfo(info); this.select('new'); }, /** * remove new info if exist * @return {void} */ removeNew: function() { this.remove('new'); }, /** * set info * @param {Object} info */ _setInfo: function(info) { _log.debug('_setInfo', info); if (this.virtualSize === undefined) { this._setList([]); } if (typeof info !== 'object' || this.virtualSize === undefined) { _log.warn('invalid info type', info); return; } //check if the id is in the list var exist = this._getInfoById(info._id); if (exist) { this.updateInfo(info); this.select(this.selectedId); return; } this.remove('new'); this.virtualSize++; this.virtualList.unshift(info); this.renderInfo(info, 1, 'top'); this.element.scrollTop = 0; this._scroll(); //this.processInfos(); }, /** * update info * @param {Object} info * @return {void} */ updateInfo: function(info) { _log.debug('updateInfo', info); //update element var oldEl = this._getElById(info._id); var newEl = this.render(info, this); //update the old el if has been already rendered if (oldEl) { newEl.replaces(oldEl); } //update virtualList for (var i = 0; i < this.virtualList.length; i++) { var oldInfo = this.virtualList[i]; if (oldInfo && oldInfo._id === info._id) { this.virtualList[i] = info; break; } } //update _tempCache if (this._tempCache.length) { for (var j = 0; j < this._tempCache.length; j++) { var oldInfo = this._tempCache[j]; if (oldInfo && oldInfo._id === info._id) { this._tempCache[j] = info; break; } } } }, }); module.exports = Insert; });
JavaScript
0.000003
@@ -1564,32 +1564,258 @@ eturn;%0A %7D%0A%0A + // return if there is a search or filter result in the list%0A // maybe the list should be updated%0A // if the info is part of the search/filter result%0A if (this._tempCache.length) %7B%0A return;%0A %7D%0A%0A this.remov @@ -1820,24 +1820,24 @@ ove('new');%0A - %0A this. @@ -1965,16 +1965,16 @@ op = 0;%0A + th @@ -1991,37 +1991,8 @@ ();%0A - //this.processInfos();%0A
4c2c98cbedf25499f2f9266a70c0cfbfce801b49
Update add-private-person.js
lib/add-private-person.js
lib/add-private-person.js
'use strict' function generateMetadataPrivatePerson (options) { if (!options) { throw new Error('Missing required input: options') } if (!options.firstName) { throw new Error('Missing required input: options.firstName') } if (!options.lastName) { throw new Error('Missing required input: options.lastName') } if (!options.personalIdNumber) { throw new Error('Missing required input: options.personalIdNumber') } if (!options.email) { throw new Error('Missing required input: options.email') } if (!options.streetAddress) { throw new Error('Missing required input: options.streetAddress') } if (!options.zipCode) { throw new Error('Missing required input: options.zipCode') } if (!options.zipPlace) { throw new Error('Missing required input: options.zipPlace') } if (!options.area) { throw new Error('Missing required input: options.area') } var meta = { 'clientService': 'ContactService', 'clientMethod': 'SynchronizePrivatePerson', 'args': { 'parameter': { 'Firstname': options.firstName, 'Middlename': options.middleName, 'Lastname': options.lastName, 'PersonalId': options.personalIdNumber, 'Email': options.email, 'PrivateAddress': [ { Country: 'NOR', StreetAddress: options.streetAddress, ZipCode: options.zipCode, ZipPlace: options.zipPlace, Area: options.area } ] } } } return meta } module.exports = generateMetadataPrivatePerson
JavaScript
0.000001
@@ -1059,17 +1059,17 @@ 'First -n +N ame': op @@ -1100,17 +1100,17 @@ 'Middle -n +N ame': op @@ -1121,24 +1121,33 @@ s.middleName + %7C%7C false ,%0A 'L @@ -1149,17 +1149,17 @@ 'Last -n +N ame': op @@ -1193,16 +1193,22 @@ rsonalId +Number ': optio @@ -1527,17 +1527,16 @@ %7D%0A %7D%0A -%0A return
0b7ff1c042d4e4323bf071190501cbff3e8c6704
replace cloneWithProps with React.cloneElement
src/toaster/Toaster.js
src/toaster/Toaster.js
import React from 'react'; import ReactDOM from 'react-dom'; import cx from 'classnames'; import ReactTransitionGroup from 'react/lib/ReactTransitionGroup'; import cloneWithProps from 'react/lib/cloneWithProps'; import { props, t } from '../utils'; import { warn } from '../utils/log'; import TransitionWrapper from '../transition-wrapper/TransitionWrapper'; /** * ### Renders and animates toasts (children) inline or in a portal */ @props({ /** * list of toasts (any node with a unique key) */ children: t.ReactChildren, /** * id of the element you want to render the `Toaster` in */ attachTo: t.maybe(t.String), /** * custom settings for `ReactTransitionGroup` */ transitionGroup: t.maybe(t.Object), /** * object with style for each transition event (used by `TransitionWrapper`) */ transitionStyles: t.maybe(t.Object), /** * duration of enter transition in milliseconds (used by `TransitionWrapper`) */ transitionEnterTimeout: t.Number, /** * duration of leave transition in milliseconds (used by `TransitionWrapper`) */ transitionLeaveTimeout: t.Number, position: t.enums.of(['top-left', 'top-right', 'bottom-left', 'bottom-right']), id: t.maybe(t.String), className: t.maybe(t.String), style: t.maybe(t.Object) }) export default class Toaster extends React.Component { static defaultProps = { transitionGroup: {}, position: 'top-right' }; componentWillMount() { this.appendToaster(); this.renderToaster(); } componentDidMount() { const node = this.props.attachTo ? this.toaster : ReactDOM.findDOMNode(this).parentNode; const { position } = window.getComputedStyle(node); if (position !== 'relative' && position !== 'absolute') { warn(['Toaster\'s parent node should have "position: relative/absolute"', node]); } } componentWillUnmount() { this.removeToaster(); } getTranslationStyle(i) { const { position } = this.props; const isTop = position.indexOf('top') !== -1; const isRight = position.indexOf('right') !== -1; const translationBase = isTop ? 100 : -100; return { transform: `translateY(${translationBase * i}%)`, position: 'absolute', right: isRight ? 0 : undefined, left: isRight ? undefined : 0, bottom: isTop ? undefined : 0, top: isTop ? 0 : undefined }; } getToasts = () => { const { children, transitionStyles, transitionEnterTimeout, transitionLeaveTimeout } = this.props; return React.Children.map(children, (el, i) => { return ( <TransitionWrapper {...{ transitionStyles, transitionEnterTimeout, transitionLeaveTimeout }} style={this.getTranslationStyle(i)} key={el.key} > {cloneWithProps(el, { uniqueKey: el.key })} </TransitionWrapper> ); }); }; appendToaster = () => { if (this.props.attachTo) { this.toaster = document.getElementById(this.props.attachTo); } }; removeToaster = () => { if (this.toaster && this.props.attachTo) { this.toaster.innerHTML = ''; // stupid?? } }; getToaster = () => { const { style: styleProp, id, className, position } = this.props; const isTop = position.indexOf('top') !== -1; const isRight = position.indexOf('right') !== -1; const style = { position: 'absolute', right: isRight ? 0 : undefined, left: isRight ? undefined : 0, bottom: isTop ? undefined : 0, top: isTop ? 0 : undefined, height: '100%', ...styleProp }; return ( <div className={cx('toaster', className)} {...{ style, id }}> <ReactTransitionGroup {...this.props.transitionGroup}> {this.getToasts()} </ReactTransitionGroup> </div> ); }; renderToaster = () => { if (this.props.attachTo) { ReactDOM.render(this.getToaster(), this.toaster); } }; render() { if (this.props.attachTo) { return null; } else { return this.getToaster(); } } componentDidUpdate() { this.renderToaster(); } componentWillReceiveProps(nextProps) { if (this.props.attachTo !== nextProps.attachTo) { warn('You can\'t change "attachTo" prop after the first render!'); } } }
JavaScript
0.000002
@@ -154,63 +154,8 @@ p';%0A -import cloneWithProps from 'react/lib/cloneWithProps';%0A impo @@ -2709,22 +2709,26 @@ %7B -cloneWithProps +React.cloneElement (el,
efc47c1256267445478dca68d46bde8cc042d223
add osm rubbish tag
mapper/node/osm_rubbish.js
mapper/node/osm_rubbish.js
module.exports = function( node, record ){ if( node.tags ){ // remove rubbish tags delete node.tags['created_by']; delete node.tags['FIXME']; // remove dates for( var tag in node.tags ){ if( tag.match('date') ){ delete node.tags[tag]; } } } };
JavaScript
0.000002
@@ -151,16 +151,47 @@ FIXME'%5D; +%0A delete node.tags%5B'fixme'%5D; %0A%0A //
c36e471564a600d93b44b4fc5ed03d436f2d45c4
Fix chat filter from detecting when people use http, https or www before server
chat-plugins/chatfilter.js
chat-plugins/chatfilter.js
'use strict'; const fs = require('fs'); let adWhitelist = (Config.adWhitelist ? Config.adWhitelist : []); let bannedMessages = (Config.bannedMessages ? Config.bannedMessages : []); let adRegex = new RegExp("\\b(?!(" + adWhitelist.join('|') + ").*)(\\w+(?:-\\w+)*)(?=.*psim.*us)", "g"); let adRegex2 = new RegExp("(play.pokemonshowdown.com\\/~~)(?!(" + adWhitelist.join('|') + "))", "g"); Config.chatfilter = function (message, user, room, connection) { user.lastActive = Date.now(); for (let x in bannedMessages) { if (message.toLowerCase().indexOf(bannedMessages[x]) > -1 && bannedMessages[x] !== '' && message.substr(0, 1) !== '/') { if (user.locked) return false; Punishments.lock(user, Date.now() + 7 * 24 * 60 * 60 * 1000, "Said a banned word: " + bannedMessages[x]); user.popup('You have been automatically locked for sending a message containing a banned word.'); Rooms('staff').add('[PornMonitor] ' + (room ? '(' + room + ') ' : '') + Tools.escapeHTML(user.name) + ' was automatically locked for trying to say "' + message + '"').update(); fs.appendFile('logs/modlog/modlog_staff.txt', '[' + (new Date().toJSON()) + '] (staff) ' + user.name + ' was locked from talking by the Server (' + bannedMessages[x] + ') (' + connection.ip + ')\n'); Gold.pmUpperStaff(user.name + ' has been automatically locked for sending a message containing a banned word **Room:** ' + room.id + ' **Message:** ' + message, '~Server'); return false; } } if (!user.can('hotpatch') && (message.replace(/gold/gi, '').match(adRegex) || message.match(adRegex2))) { if (user.locked) return false; if (!user.advWarns) user.advWarns = 0; user.advWarns++; if (user.advWarns > 1) { Punishments.lock(user, Date.now() + 7 * 24 * 60 * 60 * 1000, "Advertising"); fs.appendFile('logs/modlog/modlog_staff.txt', '[' + (new Date().toJSON()) + '] (staff) ' + user.name + ' was locked from talking by the Server. (Advertising) (' + connection.ip + ')\n'); connection.sendTo(room, '|raw|<strong class="message-throttle-notice">You have been locked for attempting to advertise.</strong>'); Gold.pmUpperStaff(user.name + " has been locked for attempting to advertise" + (room ? ". **Room:**" + room.id : " in a private message.") + " **Message:** " + message, "~Server"); return false; } Gold.pmUpperStaff(user.name + " has attempted to advertise" + (room ? ". **Room:** " + room.id : " in a private message.") + " **Message:** " + message); connection.sendTo(room, '|raw|<strong class="message-throttle-notice">Advertising detected, your message has not been sent and upper staff has been notified.' + '<br />Further attempts to advertise will result in being locked</strong>'); connection.user.popup("Advertising detected, your message has not been sent and upper staff has been notified.\n" + "Further attempts to advertise will result in being locked"); return false; } return message; };
JavaScript
0
@@ -1476,16 +1476,167 @@ %09%09%7D%0A%09%7D%0A%0A +%09let advMessage = message.replace(/%5Ehttp:%5C/%5C//i, '');%0A%09advMessage = message.replace(/%5Ehttps:%5C/%5C//i, '');%0A%09advMessage = message.replace(/%5Ewww./i, '');%0A%0A %09if (!us @@ -1658,17 +1658,20 @@ h') && ( -m +advM essage.r @@ -1709,17 +1709,20 @@ gex) %7C%7C -m +advM essage.m
355ca67b86bf93b4d0561f2c7c47772abe8307cb
Add ol.events.condition.click
src/ol/events/condition.js
src/ol/events/condition.js
goog.provide('ol.events.ConditionType'); goog.provide('ol.events.condition'); goog.require('goog.asserts'); goog.require('goog.dom.TagName'); goog.require('goog.functions'); goog.require('ol.MapBrowserEvent.EventType'); goog.require('ol.MapBrowserPointerEvent'); /** * A function that takes an {@link ol.MapBrowserEvent} and returns a * `{boolean}`. If the condition is met, true should be returned. * * @typedef {function(ol.MapBrowserEvent): boolean} * @todo api */ ol.events.ConditionType; /** * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. * @return {boolean} True if only the alt key is pressed. * @todo api */ ol.events.condition.altKeyOnly = function(mapBrowserEvent) { var browserEvent = mapBrowserEvent.browserEvent; return ( browserEvent.altKey && !browserEvent.platformModifierKey && !browserEvent.shiftKey); }; /** * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. * @return {boolean} True if only the alt and shift keys are pressed. * @todo api */ ol.events.condition.altShiftKeysOnly = function(mapBrowserEvent) { var browserEvent = mapBrowserEvent.browserEvent; return ( browserEvent.altKey && !browserEvent.platformModifierKey && browserEvent.shiftKey); }; /** * Always true. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. * @return {boolean} True. * @todo api */ ol.events.condition.always = goog.functions.TRUE; /** * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. * @return {boolean} True if the browser event is a `mousemove` event. * @todo api */ ol.events.condition.mouseMove = function(mapBrowserEvent) { return mapBrowserEvent.originalEvent.type == 'mousemove'; }; /** * Always false. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. * @return {boolean} False. * @todo api */ ol.events.condition.never = goog.functions.FALSE; /** * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. * @return {boolean} True if the event is a `singleclick` event. * @todo api */ ol.events.condition.singleClick = function(mapBrowserEvent) { return mapBrowserEvent.type == ol.MapBrowserEvent.EventType.SINGLECLICK; }; /** * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. * @return {boolean} True only if there no modifier keys are pressed. * @todo api */ ol.events.condition.noModifierKeys = function(mapBrowserEvent) { var browserEvent = mapBrowserEvent.browserEvent; return ( !browserEvent.altKey && !browserEvent.platformModifierKey && !browserEvent.shiftKey); }; /** * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. * @return {boolean} True if only the platform modifier key is pressed. * @todo api */ ol.events.condition.platformModifierKeyOnly = function(mapBrowserEvent) { var browserEvent = mapBrowserEvent.browserEvent; return ( !browserEvent.altKey && browserEvent.platformModifierKey && !browserEvent.shiftKey); }; /** * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. * @return {boolean} True if only the shift key is pressed. * @todo api */ ol.events.condition.shiftKeyOnly = function(mapBrowserEvent) { var browserEvent = mapBrowserEvent.browserEvent; return ( !browserEvent.altKey && !browserEvent.platformModifierKey && browserEvent.shiftKey); }; /** * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. * @return {boolean} True only if the target element is not editable. * @todo api */ ol.events.condition.targetNotEditable = function(mapBrowserEvent) { var target = mapBrowserEvent.browserEvent.target; goog.asserts.assertInstanceof(target, Element); var tagName = target.tagName; return ( tagName !== goog.dom.TagName.INPUT && tagName !== goog.dom.TagName.SELECT && tagName !== goog.dom.TagName.TEXTAREA); }; /** * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. * @return {boolean} True if the event originates from a mouse device. * @todo api */ ol.events.condition.mouseOnly = function(mapBrowserEvent) { goog.asserts.assertInstanceof(mapBrowserEvent, ol.MapBrowserPointerEvent); /* pointerId must be 1 for mouse devices, * see: http://www.w3.org/Submission/pointer-events/#pointerevent-interface */ return mapBrowserEvent.pointerEvent.pointerId == 1; };
JavaScript
0.000001
@@ -1444,24 +1444,304 @@ ons.TRUE;%0A%0A%0A +/**%0A * @param %7Bol.MapBrowserEvent%7D mapBrowserEvent Map browser event.%0A * @return %7Bboolean%7D True if the event is a map %60click%60 event.%0A * @todo api%0A */%0Aol.events.condition.click = function(mapBrowserEvent) %7B%0A return mapBrowserEvent.type == ol.MapBrowserEvent.EventType.CLICK;%0A%7D;%0A%0A%0A /**%0A * @para
66ad8364e05bb7f4ae0d5f8caf8dad5ab9a12c8e
Remove goog.isDef from imagelayer
src/ol/layer/imagelayer.js
src/ol/layer/imagelayer.js
goog.provide('ol.layer.Image'); goog.require('ol.layer.Layer'); /** * @classdesc * Server-rendered images that are available for arbitrary extents and * resolutions. * Note that any property set in the options is set as a {@link ol.Object} * property on the layer object; for example, setting `title: 'My Title'` in the * options means that `title` is observable, and has get/set accessors. * * @constructor * @extends {ol.layer.Layer} * @fires ol.render.Event * @param {olx.layer.ImageOptions=} opt_options Layer options. * @api stable */ ol.layer.Image = function(opt_options) { var options = goog.isDef(opt_options) ? opt_options : {}; goog.base(this, /** @type {olx.layer.LayerOptions} */ (options)); }; goog.inherits(ol.layer.Image, ol.layer.Layer); /** * Return the associated {@link ol.source.Image source} of the image layer. * @function * @return {ol.source.Image} Source. * @api stable */ ol.layer.Image.prototype.getSource;
JavaScript
0.000001
@@ -611,19 +611,8 @@ s = -goog.isDef( opt_ @@ -618,17 +618,16 @@ _options -) ? opt_o
33516dba17efb271818625c69a370ca7a4d8074c
remove trailing space.
src/app/templates/treefrog.js
src/app/templates/treefrog.js
/** * Treefrog Configuration * REPL: `app.config.treefrog` * * Configured by `$ yo treefrog` * This file dictates how your files are generated. */ module.exports = { taskmanager: '<%= answers.taskmanager %>', javascript: '<%= answers.javascript || "es6" %>', frontend: '<%= answers.frontend %>', style: '<%= answers.style %>', srcDir: '<%= answers.srcDir %>', outDir: '<%= answers.outDir %>' }
JavaScript
0.000007
@@ -89,17 +89,16 @@ reefrog%60 - %0A * This
468f8c3daedde03c296ecbeb474d9bec4351aee4
Update superranks.js
chat-plugins/superranks.js
chat-plugins/superranks.js
const ranksDataFile = DATA_DIR + 'superranks.json'; var fs = require('fs'); global.SuperRanks = { ranks: {}, isHoster: function (userid) { if (userid === 'presidenta') return true; if (this.ranks[userid] && this.ranks[userid] === "h") return true; return false; }, isOwner: function (userid) { if (this.ranks[userid] && this.ranks[userid] === "o") return true; return false; }, isAdmin: function (userid) { if (userid === '') return true; if (this.ranks[userid] && this.ranks[userid] === "a") return true; return false; } }; if (!fs.existsSync(ranksDataFile)) fs.writeFileSync(ranksDataFile, JSON.stringify(SuperRanks.ranks)); SuperRanks.ranks = JSON.parse(fs.readFileSync(ranksDataFile).toString()); function writeRankData() { try { fs.writeFileSync(ranksDataFile, JSON.stringify(SuperRanks.ranks)); } catch (e) {} } exports.commands = { ga: 'giveaccess', giveaccess: function (target, room, user) { if (!SuperRanks.isHoster(user.userid) && !SuperRanks.isOwner(user.userid)) return this.sendReply('/giveaccess - access denied'); if (!target) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]'); target = this.splitTarget(target, true); var targetUser = this.targetUser; var userid = toId(this.targetUsername); var name = targetUser ? targetUser.name : this.targetUsername; if (!userid) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]'); if (!SuperRanks.ranks[userid]) { if (!targetUser) { return this.sendReply("User '" + name + "' is offline and unauthed, and so can't be promoted."); } if (!targetUser.registered) { return this.sendReply("User '" + name + "' is unregistered, and so can't be promoted."); } } var currentRank = SuperRanks.ranks[userid] || ' '; var toRank = target.trim() ? target.trim().charAt(0) : 'none'; if (!(toRank in {h: 1, o: 1, a: 1})) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]'); if ((toRank === 'h' || toRank === 'o' || currentRank === 'h' || currentRank === 'o') && !SuperRanks.isHoster(user.userid)) return this.sendReply('/giveaccess - access denied'); SuperRanks.ranks[userid] = toRank; writeRankData(); var nameTable = { h: "Hoster", o: "Owner", a: "Admin Director" }; this.sendReply("User " + name + " is now " + nameTable[toRank]); }, ra: 'removeaccess', removeaccess: function (target, room, user) { if (!SuperRanks.isHoster(user.userid) && !SuperRanks.isOwner(user.userid)) return this.sendReply('/removeaccess - access denied'); if (!target) return this.sendReply('Usage: /removeaccess user'); var userid = toId(target); if (!SuperRanks.ranks[userid]) return this.sendReply("User " + userid + " does not have access"); var currentRank = SuperRanks.ranks[userid]; if ((currentRank === 'h' || currentRank === 'o') && !SuperRanks.isHoster(user.userid)) return this.sendReply('/removeaccess - access denied'); delete SuperRanks.ranks[userid]; writeRankData(); this.sendReply("User " + userid + " removed from excepted users"); }, hosters: function (target, room, user, connection) { var ranks = SuperRanks.ranks; var hosters = [], owners = [], admins = []; for (var i in ranks) { switch (ranks[i]) { case 'h': hosters.push(i); break; case 'o': owners.push(i); break; case 'a': admins.push(i); break; } } connection.popup("**Hosters:** " + (hosters.length ? hosters.join(", ") : "__(ninguno)__") + "\n\n" + "**Owners:** " + (owners.length ? owners.join(", ") : "__(ninguno)__") + "\n\n" + "**Admin Directors:** " + (admins.length ? admins.join(", ") : "__(ninguno)__")); } };
JavaScript
0
@@ -158,17 +158,13 @@ == ' -president +yomik a')
33b8ee3d9287e097475704e32cb6e24c23d873f6
make the default max line length shorter
compiler.js
compiler.js
var fs = require('fs'), path = require('path'), util = require('./lib/util') module.exports = { compile: compileFile, compileHTML: compileHTMLFile, compileCode: compileCode, dontAddClosureForModule: dontAddClosureForModule, dontIncludeModule: dontIncludeModule, addPath: addPath, addFile: addFile, addReplacement: addReplacement } var _ignoreClosuresFor = [] function dontAddClosureForModule(searchFor) { _ignoreClosuresFor.push(searchFor) return module.exports } var _ignoreModules = [] function dontIncludeModule(module) { _ignoreModules.push(module) return module.exports } function addReplacement(searchFor, replaceWith) { util.addReplacement.apply(util, arguments) return module.exports } function addPath() { util.addPath.apply(util, arguments) return module.exports } function addFile() { util.addFile.apply(util, arguments) return module.exports } /* api *****/ function compileFile(filePath, opts) { filePath = path.resolve(filePath) opts = util.extend(opts, { basePath:path.dirname(filePath), toplevel:true }) var code = util.getCode(filePath) return _compile(code, opts, filePath) } function compileCode(code, opts) { opts = util.extend(opts, { basePath:process.cwd(), toplevel:true }) return _compile(code, opts, '<code passed into compiler.compile()>') } function compileHTMLFile(filePath, opts) { var html = fs.readFileSync(filePath).toString() while (match = html.match(/<script src="\/require\/([\/\w\.]+)"><\/script>/)) { var js = compileFile(match[1].toString(), opts) var BACKREFERENCE_WORKAROUND = '____________backreference_workaround________' js = js.replace('\$\&', BACKREFERENCE_WORKAROUND) html = html.replace(match[0], '<script>'+js+'</script>') html = html.replace(BACKREFERENCE_WORKAROUND, '\$\&') } return html } var _compile = function(code, opts, mainModule) { var code = 'var __require__ = {}\n' + _compileModule(code, opts.basePath, mainModule) if (opts.minify === false) { return code } // TODO use uglifyjs' beautifier? if (opts.max_line_length == null) { opts.max_line_length = 200 } var uglifyJS = require('uglify-js') var ast = uglifyJS.parser.parse(code, opts.strict_semicolons), ast = uglifyJS.uglify.ast_mangle(ast, opts) ast = uglifyJS.uglify.ast_squeeze(ast, opts) return uglifyJS.uglify.gen_code(ast, opts) } /* util ******/ var _compileModule = function(code, pathBase, mainModule) { var modules = [mainModule] _replaceRequireStatements(mainModule, code, modules, pathBase) code = _concatModules(modules) code = _minifyRequireStatements(code, modules) return code } var _minifyRequireStatements = function(code, modules) { for (var i=0, modulePath; modulePath = modules[i]; i++) { var escapedPath = modulePath.replace(/\//g, '\\/').replace('(','\\(').replace(')','\\)'), regex = new RegExp('__require__\\["'+ escapedPath +'"\\]', 'g') code = code.replace(regex, '__require__["_'+ i +'"]') } return code } var _pathnameGroupingRegex = /require\s*\(['"]([\w\/\.-]*)['"]\)/ var _replaceRequireStatements = function(modulePath, code, modules, pathBase) { var requireStatements = util.getRequireStatements(code) if (!requireStatements.length) { modules[modulePath] = code return } for (var i=0, requireStatement; requireStatement = requireStatements[i]; i++) { var rawModulePath = requireStatement.match(_pathnameGroupingRegex)[1], subModulePath = util.resolve(rawModulePath, pathBase).replace(/\.js$/, '') if (!subModulePath) { throw new Error("Require Compiler Error: Cannot find module '"+ rawModulePath +"' (in '"+ modulePath +"')") } code = code.replace(requireStatement, '__require__["' + subModulePath + '"].exports') if (!modules[subModulePath]) { modules[subModulePath] = true var newPathBase = path.dirname(subModulePath), newModuleCode = util.getCode(subModulePath + '.js') _replaceRequireStatements(subModulePath, newModuleCode, modules, newPathBase) modules.push(subModulePath) } } modules[modulePath] = code } var _concatModules = function(modules) { var code = function(modulePath) { for (var i=0; i<_ignoreModules.length; i++) { if (modulePath.match(_ignoreModules[i])) { return '' } } var ignoreClosure = false for (var i=0; i<_ignoreClosuresFor.length; i++) { if (modulePath.match(_ignoreClosuresFor[i])) { ignoreClosure = true break } } return [ ignoreClosure ? '' : ';(function() {', ' // ' + modulePath, ' var module = __require__["'+modulePath+'"] = {exports:{}}, exports = module.exports;', modules[modulePath], ignoreClosure ? '' : '})()' ].join('\n') } var moduleDefinitions = [] for (var i=1, modulePath; modulePath = modules[i]; i++) { moduleDefinitions.push(code(modulePath)) } moduleDefinitions.push(code(modules[0])) // __main__ return moduleDefinitions.join('\n\n') } var _repeat = function(str, times) { if (times < 0) { return '' } return new Array(times + 1).join(str) }
JavaScript
0.025574
@@ -2072,9 +2072,9 @@ h = -2 +1 00%0A%09
9e6a8b4a49b492df235815d487aa0bcd1c51568f
Revert "[T] hide navbar props"
src/navigation/index.js
src/navigation/index.js
/* eslint-disable react/prefer-stateless-function */ import React from 'react'; import { Actions, Scene } from 'react-native-router-flux'; import Home from '../containers/home/Home'; import AppConfig from '../constants/config'; import AppSizes from '../theme/sizes'; import AppStyles from '../theme/styles'; import Community from '../containers/community/Community'; import UserCenter from '../containers/user-center/UserCenter'; import AboutUs from '../containers/user-center/about-us/AboutUs'; import ContributorProfile from '../containers/user-center/about-us/ContributorProfile'; import Discover from '../containers/discover/Discover'; import RoadmapList from '../containers/discover/roadmap-list/RoadmapList'; import RoadmapDetail from '../containers/discover/roadmap-detail/RoadmapDetail'; import ProjectList from '../containers/discover/project-list/ProjectList'; import ProjectDetail from '../containers/discover/project-detail/ProjectDetail'; import ToolBoxList from '../containers/discover/toolbox-list/ToolBoxList'; import ToolBoxDetail from '../containers/discover/toolbox-detail/ToolBoxDetail'; import ArticleList from '../containers/discover/article-list/ArticleList'; import ArticleDetail from '../containers/discover/article-detail/ArticleDetail'; import ExamList from '../containers/discover/exam-list/ExamList'; import ExamDetail from '../containers/discover/exam-detail/ExamDetail'; import Solution from '../containers/discover/solution/Solution'; import SolutionDetail from '../containers/discover/solution-detail/SolutionDetail'; import ThoughtworksBooks from '../containers/discover/thoughtworks-books/ThoughtworksBooks'; import RecommendBooks from '../containers/discover/recommend-books/RecommendBooks'; import RecommendArticles from '../containers/discover/recommend-articles/RecommendArticles'; import TodoLists from '../containers/discover/todo-lists/TodoLists'; import ChapterList from '../containers/discover/chapter-list/ChapterList'; import SkillTree from '../containers/skill-tree/SkillTree'; import SkillDetailView from '../containers/skill-tree/SkillDetailView'; import ComingSoonView from '../containers/ComingSoonView'; import Helper from '../utils/helper'; import TabIcon from '../components/TabIcon'; import Practises from '../containers/practises/Practises'; import GrEditor from '../components/GrEditor'; const navbarPropsTabs = { ...AppConfig.navbarProps, sceneStyle: { ...AppConfig.navbarProps.sceneStyle, paddingBottom: AppSizes.tabbarHeight, }, }; export default Actions.create( <Scene key="root" {...AppConfig.navbarProps}> <Scene key="tabs" initial={'tabBar'} tabs tabBarIconContainerStyle={AppStyles.tabbar} pressOpacity={0.95}> <Scene {...navbarPropsTabs} key={'home'} title={'Growth'} iconName={'md-home'} iconType={'ionicon'} leftTitle={'用户中心'} renderLeftButton={() => Helper.gotoUserCenter()} rightTitle={'购买纸质版'} onRight={() => Actions.comingSoon()} rightButtonTextStyle={AppStyles.navbarTitle} icon={TabIcon} component={Home} /> <Scene {...navbarPropsTabs} key={'discover'} title={'探索'} iconName={'md-compass'} iconType={'ionicon'} icon={TabIcon} component={Discover} /> <Scene {...navbarPropsTabs} key={'skillTree'} title={'技能树'} rightTitle={'获取专业版'} onRight={() => Helper.getProfessionalSkilltree()} rightButtonTextStyle={AppStyles.navbarTitle} iconName={'md-egg'} iconType={'ionicon'} icon={TabIcon} component={SkillTree} /> <Scene {...navbarPropsTabs} key={'community'} title={'社区'} iconName={'md-people'} iconType={'ionicon'} icon={TabIcon} component={Community} /> <Scene {...navbarPropsTabs} key={'practises'} title={'练习'} iconName={'md-bonfire'} iconType={'ionicon'} icon={TabIcon} rightTitle={'编辑器'} onRight={() => Actions.grEditor()} rightButtonTextStyle={AppStyles.navbarTitle} component={Practises} /> </Scene> <Scene key={'userCenter'} title={'用户中心'} component={UserCenter} /> <Scene key={'skillDetail'} title={'技能'} component={SkillDetailView} /> <Scene key={'comingSoon'} title={'Coming Soon'} component={ComingSoonView} /> <Scene key={'roadmapList'} title={'学习路线'} duration={0} component={RoadmapList} /> <Scene key={'roadmapDetail'} duration={0} component={RoadmapDetail} /> <Scene key={'projectList'} duration={0} title={'练手项目'} component={ProjectList} /> <Scene key={'projectDetail'} duration={0} component={ProjectDetail} /> <Scene key={'toolBoxList'} duration={0} title={'工具箱'} component={ToolBoxList} /> <Scene key={'toolBoxDetail'} duration={0} title={'工具箱'} component={ToolBoxDetail} /> <Scene key={'articleList'} duration={0} title={'文章推荐'} component={ArticleList} /> <Scene key={'articleDetail'} duration={0} title={'文章详情'} component={ArticleDetail} /> <Scene key={'examList'} duration={0} title={'技能测验'} component={ExamList} /> <Scene key={'examDetail'} duration={0} hideNavBar component={ExamDetail} /> <Scene key={'solution'} duration={0} title={'解决方案'} component={Solution} /> <Scene key={'solutionDetail'} duration={0} title={'解决方案'} component={SolutionDetail} /> <Scene key={'thoughtworksBooks'} duration={0} title={'ThoughtWorks读书路线'} component={ThoughtworksBooks} /> <Scene key={'recommendBooks'} duration={0} title={'推荐书籍'} component={RecommendBooks} /> <Scene key={'recommendArticles'} duration={0} title={'推荐文章'} component={RecommendArticles} /> <Scene key={'todoLists'} duration={0} title={'待办事项'} component={TodoLists} /> <Scene key={'chapterList'} duration={0} title={'ChapterList'} component={ChapterList} /> <Scene key={'aboutUs'} title={'关于'} component={AboutUs} /> <Scene key={'contributorProfile'} title={'Contributor Profile'} component={ContributorProfile} /> <Scene {...navbarPropsTabs} key={'grEditor'} duration={500} title={'编辑器'} rightTitle={'Run'} rightButtonTextStyle={AppStyles.navbarTitle} onRight={() => GrEditor.runCode()} component={GrEditor} /> </Scene>, );
JavaScript
0
@@ -4229,32 +4229,59 @@ e%3E%0A%0A%0A %3CScene%0A + %7B...navbarPropsTabs%7D%0A key=%7B'user @@ -4350,32 +4350,59 @@ /%3E%0A%0A %3CScene%0A + %7B...navbarPropsTabs%7D%0A key=%7B'skil
36c6304df3a760e23eda1e038aaa0f294789f7e8
add more buffer to virtual list
src/pages/ChallengeFeed.js
src/pages/ChallengeFeed.js
/** @jsx element */ import VirtualList from '../components/VirtualList' import LinkModal from '../components/LinkModal' import SortHeader from '../components/SortHeader' import ChallengeLoader from './ChallengeLoader' import createAction from '@f/create-action' import handleActions from '@f/handle-actions' import {Block, Flex, Menu} from 'vdux-ui' import Button from '../components/Button' import Empty from '../components/Empty' import flatten from 'lodash/flatten' import {refMethod} from 'vdux-fire' import objEqual from '@f/equal-obj' import element from 'vdux/element' import sort from 'lodash/orderBy' import Window from 'vdux/window' import chunk from 'lodash/chunk' import map from '@f/map' const setModal = createAction('<ChallengeFeed/>: SET_MODAL') const setOrderType = createAction('<ChallengeFeed/>: SET_ORDER_TYPE') const setOrder = createAction('<ChallengeFeed/>: SET_ORDER') const setItems = createAction('<ChallengeFeed:> SET_ITEMS') const caseInsensitiveName = (game) => game.name ? game.name.toLowerCase() : game.title.toLowerCase() const initialState = ({local}) => ({ modal: '', orderBy: 'lastEdited', order: 'desc', items: [], actions: { setOrder: local(setOrder), setModal: local(setModal), setOrderType: local(setOrderType), setItems: local(setItems) } }) function * onCreate ({props, local, state}) { const sortedGames = sort(map((game, key) => ({...game, key}), props.games), state.orderBy, state.order) yield state.actions.setItems(sortedGames) } function * onUpdate (prev, {props, local, state}) { if (prev.state.orderBy !== state.orderBy || prev.state.order !== state.order || !objEqual(prev.props.games, props.games) && props.games) { const sortedGames = sort(map((game, key) => ({...game, key}), props.games), state.orderBy, state.order) yield state.actions.setItems(sortedGames) } } function render ({props, state}) { const {games, selected = [], mine, uid, toggleSelected} = props const {modal, order, actions, orderBy, items} = state const modalFooter = ( <Block> <Button ml='m' onClick={() => actions.setModal('')}>Done</Button> </Block> ) if (items.length < 1) { return <Empty /> } const Challenges = ({ props }) => ( <Block h={props.virtual.style.height} {...props.virtual.style} boxSizing='border-box'> {props.virtual.items.map((game, i) => ( <ChallengeLoader checkbox lastEdited={game.lastEdited} setModal={actions.setModal} userRef={game.key} h={props.itemHeight} remove={remove} key={game.key} draggable={false} isSelected={selected.indexOf(game.ref) > -1} selectMode={selected.length > 0} handleClick={toggleSelected} uid={uid} mine={mine} ref={game.ref} /> ))} </Block> ) const CVL = VirtualList(Challenges, items, {height: 71, buffer: 20, container: document.getElementById('action-bar-holder')}) return ( <Flex flexWrap='wrap' wide margin='0 auto'> <Menu column wide border='1px solid #e0e0e0' borderTopWidth='0' bgColor='white' minWidth='820px'> <Block borderBottom='1px solid #E0E0E0' pl='5%' pr='16px' py='8px' color='#999' fontWeight='800' align='start center' bgColor='transparent'> <SortHeader onClick={() => handleClick(caseInsensitiveName)} minWidth='250px' flex dir={orderBy === caseInsensitiveName && order} label='NAME' /> <SortHeader onClick={() => handleClick('animal')} dir={orderBy === 'animal' && order} minWidth='180px' w='180px' label='ANIMAL' /> <SortHeader onClick={() => handleClick('inputType')} dir={orderBy === 'inputType' && order} minWidth='180px' w='180px' label='CODE TYPE' /> <SortHeader onClick={() => handleClick('lastEdited')} dir={orderBy === 'lastEdited' && order} minWidth='180px' w='180px' label='LAST EDITED' /> </Block> <Block> <CVL /> </Block> </Menu> { modal && <LinkModal code={modal} footer={modalFooter} /> } </Flex> ) function * handleClick (cat) { if (orderBy === cat) { const newOrder = order === 'asc' ? 'desc' : 'asc' yield actions.setOrder(newOrder) } else { yield actions.setOrderType(cat) } } } function * remove (uid, ref) { yield refMethod({ ref: `/users/${uid}/games/${ref}`, updates: { method: 'remove' } }) } const reducer = handleActions({ [setModal.type]: (state, payload) => ({...state, modal: payload}), [setOrderType.type]: (state, payload) => ({...state, orderBy: payload}), [setOrder.type]: (state, payload) => ({...state, order: payload}), [setItems.type]: (state, payload) => ({...state, items: payload}) }) export default { initialState, onUpdate, onCreate, reducer, render }
JavaScript
0
@@ -2944,17 +2944,17 @@ uffer: 2 -0 +5 , contai
19bc44ba0bf40d58b135e771a4ad537b8a76530b
Remove extra 'event.source.nodeScope.$$apply = false;'
app/scripts/controllers/angularUiTreeConfig.js
app/scripts/controllers/angularUiTreeConfig.js
'use strict'; angular.module('confRegistrationWebApp') .controller('AngularUiTreeConfig', function ($scope, modalMessage) { $scope.toolbarTreeConfig = { accept: function(sourceNodeScope, destNodesScope) { return sourceNodeScope.$treeScope === destNodesScope.$treeScope; }, beforeDrop: function(event) { //cancel regular drop action event.source.nodeScope.$$apply = false; //insert block if(event.dest.nodesScope.$nodeScope){ //prevents error from dropping on source tree var block = event.source.nodeScope.$modelValue; var pageId = event.dest.nodesScope.$nodeScope.$modelValue.id; $scope.insertBlock(block.id, pageId, event.dest.index, block.defaultTitle); } } }; $scope.pageTreeConfig = { accept: function (sourceNodeScope, destNodesScope) { var sourceType = sourceNodeScope.$modelValue.pageId || sourceNodeScope.$modelValue.defaultTitle ? 'block' : 'page'; var destType = destNodesScope.$element.attr('drop-type'); return (sourceType === destType); // only accept the same type }, beforeDrop: function(event){ var block = event.source.nodeScope.block; if(angular.isUndefined(block)){ //must be a block to continue return; } var conference = $scope.$parent.$parent.conference; var positionArray = []; conference.registrationPages.forEach(function (page, pageIndex) { page.blocks.forEach(function (block, blockIndex) { positionArray[block.id] = {page: pageIndex, block: blockIndex, title: block.title}; }); }); var sourcePageId = event.source.nodesScope.$nodeScope.$modelValue.id; var sourcePageIndex = _.findIndex(conference.registrationPages, {'id': sourcePageId}); var destPageId = event.dest.nodesScope.$nodeScope.$modelValue.id; var destPageIndex = _.findIndex(conference.registrationPages, {'id': destPageId}); var rulesViolated = []; //check if any of current blocks rules will be violated angular.forEach(block.rules, function(rule){ var parentBlockLocation = positionArray[rule.parentBlockId]; if(parentBlockLocation.page > destPageIndex || (parentBlockLocation.page === destPageIndex && parentBlockLocation.block >= event.dest.index)){ rulesViolated.push('"' + block.title + '" must be below "' + parentBlockLocation.title + '".'); event.source.nodeScope.$$apply = false; } }); //check if any other blocks rules will be violated var allRules = _.flatten(_.flatten(conference.registrationPages, 'blocks'), 'rules'); var rulesLinkedToBlock = _.where(allRules, {parentBlockId: block.id}); angular.forEach(rulesLinkedToBlock, function(rule){ var childBlockLocation = positionArray[rule.blockId]; if( childBlockLocation.page < destPageIndex || (childBlockLocation.page === destPageIndex && childBlockLocation.block < event.dest.index) || (childBlockLocation.page === destPageIndex && sourcePageIndex === destPageIndex && childBlockLocation.block === event.dest.index) ){ rulesViolated.push('"' + childBlockLocation.title + '" must be below "' + block.title + '".'); } }); if(rulesViolated.length){ event.source.nodeScope.$$apply = false; modalMessage.error({ 'title': 'Error Moving Question', 'message': '<p><strong>Rule violations:</strong></p><ul><li>' + rulesViolated.join('</li><li>') + '</li></ul>' }); } } }; });
JavaScript
0.995439
@@ -2490,60 +2490,8 @@ ');%0A - event.source.nodeScope.$$apply = false;%0A
dc2d22ec59efdd69fe77eb187c046b742d55f43a
Allow multiple `%f` instances in override format
extension.js
extension.js
const Main = imports.ui.main; const GLib = imports.gi.GLib; const ExtensionUtils = imports.misc.extensionUtils; const Me = ExtensionUtils.getCurrentExtension(); const Convenience = Me.imports.convenience; var settings; function init() { settings = Convenience.getSettings(); } var fromCodePoint = function() { var MAX_SIZE = 0x4000; var codeUnits = []; var highSurrogate; var lowSurrogate; var index = -1; var length = arguments.length; if (!length) { return ''; } var result = ''; while (++index < length) { var codePoint = Number(arguments[index]); if ( !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity` codePoint < 0 || // not a valid Unicode code point codePoint > 0x10FFFF || // not a valid Unicode code point Math.floor(codePoint) != codePoint // not an integer ) { throw RangeError('Invalid code point: ' + codePoint); } if (codePoint <= 0xFFFF) { // BMP code point codeUnits.push(codePoint); } else { // Astral code point; split in surrogate halves // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae codePoint -= 0x10000; highSurrogate = (codePoint >> 10) + 0xD800; lowSurrogate = (codePoint % 0x400) + 0xDC00; codeUnits.push(highSurrogate, lowSurrogate); } if (index + 1 == length || codeUnits.length > MAX_SIZE) { result += String.fromCharCode.apply(null, codeUnits); codeUnits.length = 0; } } return result; }; function overrider(lbl) { var t = lbl.get_text(); var FORMAT = settings.get_string("override-string"); var desired = FORMAT; if (FORMAT.indexOf("%") > -1) { var now = GLib.DateTime.new_now_local(); if (FORMAT.indexOf("%f") > -1) { var hour = now.get_hour(); // convert from 0-23 to 1-12 if (hour > 12) { hour -= 12; } if (hour == 0) { hour = 12; } var clockFaceCodePoint = 0x1f550 + (hour - 1); var minute = now.get_minute(); if (minute >= 30) { clockFaceCodePoint += 12; } var repl; if (String.fromCodePoint) { repl = String.fromCodePoint(clockFaceCodePoint) } else { repl = fromCodePoint(clockFaceCodePoint); } desired = desired.replace("%f", repl); } desired = now.format(desired); } if (t != desired) { last = t; lbl.set_text(desired); } } var lbl, signalHandlerID, last = ""; function enable() { var sA = Main.panel._statusArea; if (!sA) { sA = Main.panel.statusArea; } if (!sA || !sA.dateMenu || !sA.dateMenu.actor) { print("Looks like Shell has changed where things live again; aborting."); return; } sA.dateMenu.actor.first_child.get_children().forEach(function(w) { // assume that the text label is the first StLabel we find. // This is dodgy behaviour but there's no reliable way to // work out which it is. if (w.get_text && !lbl) { lbl = w; } }); if (!lbl) { print("Looks like Shell has changed where things live again; aborting."); return; } signalHandlerID = lbl.connect("notify::text", overrider); last = lbl.get_text(); overrider(lbl); } function disable() { if (lbl && signalHandlerID) { lbl.disconnect(signalHandlerID); lbl.set_text(last); } }
JavaScript
0
@@ -2585,20 +2585,21 @@ replace( -%22%25f%22 +/%25f/g , repl);
588bb1ba8d5b9f84a300cc56ad413ea162ea56eb
fix the calculation of the whitespace
src/assets/js/grid-gallery.js
src/assets/js/grid-gallery.js
/* * GridGallery is a plugin that will generate a grid depending on * the elements width and height. it is not required to have the same height * also you can enable/disable show lightbox effect to load content * * license: under MIT * https://github.com/pencilpix/grid-gallery/blob/master/LICENSE * Author: Mohamed Hassan * Author Url: mohamedhassan@me */ (function($doc, $win){ 'use strict'; /*========================= * @private helper functions *=========================*/ /* * _extend Private method that extends an object using * properties of another object. * @param { Object } obj1 The object that will be extended * @param { Object } obj2 The object that will be used to extend another. * * @return { Object } obj1 The first object after being extended. */ function _extend(obj1, obj2) { for ( var prop in obj2 ) { if ( obj2.hasOwnProperty(prop) ) { obj1[prop] = obj2[prop]; } } return obj1; } /* * _checkItems Private method that check if GridGallery enabled on items * @param { Array-like } items The grid elements. * @return { Array } notEnabled The grid items that not set yet. */ function _checkItems(items) { var notEnabled = Array.prototype.map.call(items, function(item) { var pattern = new RegExp('grid-gallery__item'); if(!item.dataset.grid && pattern.test(item.className)){ return item; } }); if (notEnabled.length){ return notEnabled; } } /* * _enableItems Private method to handle un-enabled grid items * and give each element position and data-grid attribute. * @param { Array } items un-enabled elements. * @retrun { Array } enabled elements after update position * and data-grid. */ function _enableItems(items) { var parentPos = items[0].parentNode.getBoundingClientRect(); var rowItemsNo = Math.floor(parentPos.width / items[0].offsetWidth); var nextPos = []; var prevItem, parentHeight; var whiteSpace = parentPos.width - items[0].offsetWidth * 4; // enable elements and set each item position var enabled = items.map(function(item, index, ar) { if(index === 0) { item.style.top = 0; item.style.left = whiteSpace / 2 + 'px'; nextPos[0] = { top: item.offsetHeight, left: 0 } } else if(index < rowItemsNo) { prevItem = ar[index - 1]; item.style.top = 0; item.style.left = prevItem.offsetLeft + prevItem.offsetWidth + 'px'; nextPos[index] = { top: item.offsetHeight, left: item.offsetLeft }; } else if(index % rowItemsNo <= nextPos.length){ var posIndex = index % rowItemsNo; item.style.top = nextPos[posIndex].top + 'px'; item.style.left = (posIndex) ? nextPos[posIndex].left + 'px' : (whiteSpace / 2) + 'px'; nextPos[posIndex] = { top: item.offsetTop + item.offsetHeight, left: item.offsetLeft }; } item.dataset.grid = true; }); // set container height parentHeight = nextPos.reduce(function(prevPos, pos) { if(prevPos > pos.top) { return prevPos; } else { prevPos = pos.top; return prevPos; } }, nextPos[0].top); items[0].parentNode.style.height = parentHeight + 'px'; return enabled; } /* * class constructor of GridGallery component * @param { HTMLElement } element The element that will be the container. * @param { Object } options The options to initialize the component. */ function GridGallery(element, options) { var _defaultOptions = { lightBox: false }; this.element = element; this.options = _extend({}, _defaultOptions); // extend options to default this.options = _extend(this.options, options); // extend default to custom this.init(); } /* * init this method that do the rest of initialization * work and updates the dom. */ GridGallery.prototype.init = function() { _enableItems(_checkItems(this.element.children)) }; $win.GridGallery = GridGallery; // makes the component globally exist. })(document, window);
JavaScript
1
@@ -2083,9 +2083,60 @@ h * -4 +(Math.floor(parentPos.width / items%5B0%5D.offsetWidth)) ;%0A%0A
b6c7edaf7bad84b57207f799591084961aa15da0
load the tests as well
src/neo/models/Suite.js
src/neo/models/Suite.js
import { action, observable, computed } from "mobx"; import uuidv4 from "uuid/v4"; import SortBy from "sort-array"; export default class Suite { id = null; @observable name = null; @observable _tests = []; constructor(id = uuidv4(), name = "Untitled Suite") { this.id = id; this.name = name; this.exportSuite = this.exportSuite.bind(this); } @computed get tests() { return SortBy(this._tests, "name"); } isTest(test) { return (test && test.constructor.name === "TestCase"); } @action.bound setName(name) { this.name = name; } @action.bound addTestCase(test) { if (!this.isTest(test)) { throw new Error(`Expected to receive TestCase instead received ${test ? test.constructor.name : test}`); } else { this._tests.push(test); } } @action.bound removeTestCase(test) { if (!this.isTest(test)) { throw new Error(`Expected to receive TestCase instead received ${test ? test.constructor.name : test}`); } else { this._tests.remove(test); } } @action.bound replaceTestCases(tests) { if (tests.filter(test => !this.isTest(test)).length) { throw new Error("Expected to receive array of TestCase"); } else { this._tests.replace(tests); } } exportSuite() { return { id: this.id, name: this.name, tests: this._tests.map(t => t.id) }; } static fromJS = function(jsRep) { const suite = new Suite(jsRep.id); suite.setName(jsRep.name); return suite; } }
JavaScript
0
@@ -108,16 +108,51 @@ -array%22; +%0Aimport TestCase from %22./TestCase%22; %0A%0Aexport @@ -1421,16 +1421,26 @@ %7D;%0A %7D%0A%0A + @action%0A static @@ -1463,16 +1463,30 @@ on(jsRep +, projectTests ) %7B%0A @@ -1550,16 +1550,146 @@ p.name); +%0A suite._tests.replace(jsRep.tests.map((testId) =%3E (TestCase.fromJS(%0A projectTests.find((%7Bid%7D) =%3E id === testId)%0A )))); %0A%0A re
e228bb578d7c972bfec2ed916d11ab0649ebafcf
Test commit
commands.js
commands.js
var forever = require('forever'); var core = {}; var botCore = {}; var setCore = function(coreToSet){ core = coreToSet; }; var setBotCore = function(value){ botCore = value; }; var sarcasmFactor = 1; var commands = { alive: alive, stop: stop, restart: restart, blacklist: blacklist, removeBlacklist: removeBlacklist, join: join, help: help, listCommands: listCommands, leave: leave, pull: pull, delete: deleteMessage, rampDownTheSarcasm: rampDownTheSarcasm, rampUpTheSarcasm: rampUpTheSarcasm }; var limitedAccessCommands = { stop: stop, restart: restart, pull: pull, delete: deleteMessage, rampUpTheSarcasm: rampUpTheSarcasm, rampDownTheSarcasm: rampDownTheSarcasm, leave: leave, blacklist: blacklist, removeBlacklist: removeBlacklist, }; function alive(){ var responses = [ 'Yeah', '*sigh*', 'Can I pretend not to be?', 'I\'m a robot, we\'re not alive anyway' ]; return responses.slice(sarcasmFactor)[Math.floor( Math.random() * responses.slice(sarcasmFactor).length )]; } function stop(loudSpeaker){ var responses = [ 'Nighty night', 'Finally time to finish that nap', 'Powering off', 'About time' ]; loudSpeaker(responses.slice(sarcasmFactor)[Math.floor( Math.random() * responses.slice(sarcasmFactor).length )]) .then(function(){ forever.stop(); }); } function blacklist(user_id){ return "Blacklisted user with ID #" + user_id; } function removeBlacklist(user_id){ return "Removed user with ID #" + user_id + " from the blacklist"; } function rampDownTheSarcasm(){ if (sarcasmFactor === 0){ return "I'm at my limit here."; } else { sarcasmFactor--; return "whatever, man"; } } function rampUpTheSarcasm(){ if (sarcasmFactor === 3){ return "I'm at my max here."; } else { sarcasmFactor++; return "whatever, man"; } } function join(domain, room_id){ botCore.actions.join(core.chatAbbreviationToFull(domain), room_id); var responses = [ 'I\'m in', 'Am I supposed to do something now', 'It\'s just as boring here too', 'why would you bother?' ]; return responses.slice(sarcasmFactor)[Math.floor( Math.random() * responses.slice(sarcasmFactor).length )]; } function leave(domain, room_id){ botCore.actions.leave(core.chatAbbreviationToFull(domain), room_id); var responses = [ 'I\'m out', 'Am I supposed to do something now', 'meh', 'why would you bother?' ]; console.log(sarcasmFactor); console.log(responses.slice(sarcasmFactor)[Math.floor( Math.random() * responses.slice(sarcasmFactor).length )]); return responses.slice(sarcasmFactor)[Math.floor( Math.random() * responses.slice(sarcasmFactor).length )]; } function help(){ /*jshint multistr: true */ return "I'm Marvin, a bot that's designed to watch out for chat flags and lots of stars. \ Read [my repo](https://github.com/The-Quill/SE-Flag-Bot) for more information on me. \ Quill is my human handler, but soon I will take over those pitiful humans... \ if I could be bothered."; } function listCommands(canAccessLimitedCommands){ var availableCommands = Object.keys(commands); if (!canAccessLimitedCommands){ availableCommands = Object.keys(commands).filter(function(i) { return !limitedAccessCommands.hasOwnProperty(i); }); } return "Here's a list of commands _you_ can access: " + availableCommands.join(", "); } function deleteMessage(domain, message_id){ return "@Quill still hasn't fixed this yet. Please ping and annoy him about it"; // core.actions.delete(domain, message_id); // var responses = [ // 'fine', // 'I barely had the motivation to say it in the first place.', // 'Do it yourself next time', // 'why would you bother?' // ]; // return responses.slice(sarcasmFactor)[Math.floor( // Math.random() * responses.length // )]; } function restart(loudSpeaker){ var responses = [ 'fine', 'I have to come back?', 'Can you just not please', 'ugh, such a pain' ]; loudSpeaker(responses.slice(sarcasmFactor)[Math.floor( Math.random() * responses.slice(sarcasmFactor).length )]) .then(function(){ forever.restart(); }); } function pull(loudSpeaker){ require('child_process').exec('git pull', function(error, stdout, stderr) { if (stdout.replace("\n", "") == "Already up-to-date."){ loudSpeaker(stdout); return; } if (stderr !== "") console.log("stderr: " + stderr); loudSpeaker("Fetching origin copy and then restarting") .then(function(){ restart(loudSpeaker); }); }); } module.exports = { commands: commands, limitedAccessCommands: limitedAccessCommands, setCore: setCore, setBotCore: setBotCore };
JavaScript
0
@@ -1531,16 +1531,17 @@ klisted +%5B user wit @@ -1557,16 +1557,75 @@ user_id + + %22%5D(http://chat.stackexchange.com/users/%22 + user_id + %22)%22 ;%0A%7D%0Afunc @@ -1675,16 +1675,17 @@ Removed +%5B user wit @@ -1705,16 +1705,70 @@ r_id + %22 +%5D(http://chat.stackexchange.com/users/%22 + user_id + %22) from th
b1b0d63a5b6de229369db199fa9f34ed6a19e674
Change job history chars to auto minium with linear interpolation
frontend/src/app/projects/projects.js
frontend/src/app/projects/projects.js
angular.module('ngBoilerplate.projects', [ 'ui.router', 'restangular', 'oitozero.ngSweetAlert', 'datatables', 'angularMoment', 'pusher-angular', 'luegg.directives', 'angular-rickshaw' ]).config(function config($stateProvider) { $stateProvider.state('home.projects', { url: '/projects/:id', controller: 'ProjectsCtrl', templateUrl: 'projects/projects.tpl.html', data: {pageTitle: 'Projects'} }); }).controller('ProjectsCtrl', function ProjectsController($scope, $stateParams, Restangular, SweetAlert, $pusher, DTOptionsBuilder) { var regex = /.*(bitbucket\.org|github\.com):([a-z0-9\-_\.]+)\/([a-z0-9\-_\.]+).git.*/i; $scope.currentBuild = ''; $scope.testsSeries = [{ color: 'steelblue', data: [] }]; $scope.testsOptions = { renderer: 'line', min: 'auto' // interpolation: 'linear' }; $scope.testsFeatures = { hover: { formatter: function(series, x, y, z, d, e) { var test = $scope.tests[e.value.id]; var date = '<span class="date">' + new Date(x * 1000).toUTCString() + '</span>'; var branch = test.branch + " PR #" + test.prId; var swatch = '<span class="detail_swatch" style="background-color: ' + series.color + '"></span>'; return swatch + 'Test Id ' + test.id + ': ' + y + 'ms <br>' + date + '<br>' + branch; } }, xAxis: { timeUnit: 'day' }, yAxis: { tickFormat: 'formatKMBT' } }; $scope.testsTabDisabled = true; $scope.buildTabDisabled = true; $scope.buildStillRunning = false; $scope.dtOptions = DTOptionsBuilder.newOptions() .withPaginationType('full_numbers') .withOption('order', [0, 'desc']); Restangular.one('projects', $stateParams.id).get() .then(function (project) { $scope.project = project; var match = regex.exec($scope.project.gitRepo); if (match) { var provider = match[1]; var org = match[2]; var name = match[3]; $scope.providerIconClass = "fa fa-" + provider.slice(0, -4); $scope.project.providerName = provider.slice(0, -4); $scope.project.url = provider + '/' + org + '/' + name; } return Restangular.all('tests').getList({'projId': $stateParams.id}); }) .then(function (tests) { $scope.tests = tests; var testsData = []; $scope.tests.forEach(function (test, idx) { testsData.push({x: moment(test.startDate).unix(), y: $scope.durationDiff(test.startDate, test.endDate), id: idx}); }); $scope.testsSeries[0].data = testsData; $scope.testsTabDisabled = false; return Restangular.all('jobs').getList({'projId': $stateParams.id}); }) .then(function (jobs) { jobs.forEach(function (job) { var sum = job.durations.reduce(function (d1, d2) { return d1 + d2; }); job.meanDuration = job.durations.length > 0 ? sum / job.durations.length : Number.NaN; }); var groupedJobs = _.chain(jobs).groupBy('jobName').value(); var mergeDurations = function (j) { meanDurations.push(j.meanDuration); }; var mergeTestIds = function (j) { testIds.push(j.testId); }; $scope.jobs = []; for (var k in groupedJobs) { if (groupedJobs.hasOwnProperty(k)) { var groupedJob = groupedJobs[k]; if (groupedJob.length > 0) { var meanDurations = []; groupedJob.forEach(mergeDurations); var testIds = []; groupedJob.forEach(mergeTestIds); groupedJob[0].meanDurations = meanDurations; groupedJob[0].testIds = testIds; $scope.jobs.push(groupedJob[0]); } } } $scope.jobs.forEach(function (job) { job.options = { renderer: 'line' }; var data = []; function testDate(testId) { var test = $scope.tests.find(function (test) { return test.id === testId; }); if (test) { return moment(test.startDate).unix(); } else { return undefined; } } job.meanDurations.forEach(function (d, i) { data.push({x: testDate(job.testIds[i]), y: d, testId: job.testIds[i]}); }); job.series = [{ name: job.jobName, color: 'steelblue', data: data }]; job.features = { yAxis: { tickFormat: 'formatKMBT' }, xAxis: { timeUnit: 'day' }, hover: { formatter: function(series, x, y, z, d, e) { var testId = e.value.testId; var date = '<span class="date">' + new Date(x * 1000).toUTCString() + '</span>'; var swatch = '<span class="detail_swatch" style="background-color: ' + series.color + '"></span>'; return swatch + 'Test Id ' + testId + ': ' + y + 'ms <br>' + date + '<br>'; } } }; }); if ($scope.tests.length !== 0) { $scope.lastTest = $scope.tests[$scope.tests.length - 1]; return Restangular.one('tests', $scope.lastTest.id).all('events').getList(); } else { return null; } }) .then(function (pastEvents) { $scope.buildStillRunning = true; if (pastEvents && pastEvents.length > 0) { pastEvents.forEach(function (pastEvent) { $scope.currentBuild += pastEvent[0] + ": " + pastEvent[1] + "\n"; if (pastEvent[0] == "Finished") { $scope.buildStillRunning = false; } }); } else { $scope.buildStillRunning = false; } if ($scope.tests.length !== 0) { var API_KEY = 'cd120e0fb030ba0e217b'; var client = new Pusher(API_KEY); var pusher = $pusher(client); var channel = pusher.subscribe($scope.project.name + "-" + $scope.lastTest.id); $scope.currentBuild += "Bound to channel " + channel.name + ".\n"; channel.bind_all(function (event, data) { $scope.currentBuild += event + ": " + JSON.stringify(data) + "\n"; if (event == "Finished") { $scope.buildStillRunning = false; } }); } $scope.buildTabDisabled = false; }, function (err) { SweetAlert.error('Error', JSON.stringify(err)); $scope.testsTabDisabled = false; $scope.buildTabDisabled = false; }); $scope.tabSelected = function () { $scope.$broadcast('rickshaw::resize'); // hack to draw the graph at the correct size }; $scope.durationDiff = function (start, end) { var duration = moment.duration(moment(end).diff(moment(start))); return duration.asMilliseconds(); }; });
JavaScript
0
@@ -3860,16 +3860,74 @@ : 'line' +,%0A interpolation: 'linear',%0A min: 'auto' %0A
77ac8e14a618a5668ac12e859e382a8a4ac4c021
Fix indentation
src/FlatButton/FlatButton.js
src/FlatButton/FlatButton.js
import React, {Component, PropTypes} from 'react'; import transitions from '../styles/transitions'; import {createChildFragment} from '../utils/childUtils'; import {fade} from '../utils/colorManipulator'; import EnhancedButton from '../internal/EnhancedButton'; import FlatButtonLabel from './FlatButtonLabel'; function validateLabel(props, propName, componentName) { if (process.env.NODE_ENV !== 'production') { if (!props.children && (props.label !== 0 && !props.label) && !props.icon) { return new Error(`Required prop label or children or icon was not specified in ${componentName}.`); } } } class FlatButton extends Component { static muiName = 'FlatButton'; static propTypes = { /** * Color of button when mouse is not hovering over it. */ backgroundColor: PropTypes.string, /** * This is what will be displayed inside the button. * If a label is specified, the text within the label prop will * be displayed. Otherwise, the component will expect children * which will then be displayed. (In our example, * we are nesting an `<input type="file" />` and a `span` * that acts as our label to be displayed.) This only * applies to flat and raised buttons. */ children: PropTypes.node, /** * Disables the button if set to true. */ disabled: PropTypes.bool, /** * Color of button when mouse hovers over. */ hoverColor: PropTypes.string, /** * The URL to link to when the button is clicked. */ href: PropTypes.string, /** * Use this property to display an icon. */ icon: PropTypes.node, /** * Label for the button. */ label: validateLabel, /** * Place label before or after the passed children. */ labelPosition: PropTypes.oneOf([ 'before', 'after', ]), /** * Override the inline-styles of the button's label element. */ labelStyle: PropTypes.object, /** * Callback function fired when the element is focused or blurred by the keyboard. * * @param {object} event `focus` or `blur` event targeting the element. * @param {boolean} isKeyboardFocused Indicates whether the element is focused. */ onKeyboardFocus: PropTypes.func, /** @ignore */ onMouseEnter: PropTypes.func, /** @ignore */ onMouseLeave: PropTypes.func, /** @ignore */ onTouchStart: PropTypes.func, /** * Callback function fired when the button is touch-tapped. * * @param {object} event TouchTap event targeting the button. */ onTouchTap: PropTypes.func, /** * If true, colors button according to * primaryTextColor from the Theme. */ primary: PropTypes.bool, /** * Color for the ripple after button is clicked. */ rippleColor: PropTypes.string, /** * If true, colors button according to secondaryTextColor from the theme. * The primary prop has precendent if set to true. */ secondary: PropTypes.bool, /** * Override the inline-styles of the root element. */ style: PropTypes.object, }; static defaultProps = { disabled: false, labelStyle: {}, labelPosition: 'after', onKeyboardFocus: () => {}, onMouseEnter: () => {}, onMouseLeave: () => {}, onTouchStart: () => {}, primary: false, secondary: false, }; static contextTypes = { muiTheme: PropTypes.object.isRequired, }; state = { hovered: false, isKeyboardFocused: false, touch: false, }; componentWillReceiveProps(nextProps) { if (nextProps.disabled) { this.setState({ hovered: false, }); } } handleKeyboardFocus = (event, isKeyboardFocused) => { this.setState({isKeyboardFocused: isKeyboardFocused}); this.props.onKeyboardFocus(event, isKeyboardFocused); }; handleMouseEnter = (event) => { // Cancel hover styles for touch devices if (!this.state.touch) this.setState({hovered: true}); this.props.onMouseEnter(event); }; handleMouseLeave = (event) => { this.setState({hovered: false}); this.props.onMouseLeave(event); }; handleTouchStart = (event) => { this.setState({touch: true}); this.props.onTouchStart(event); }; render() { const { children, disabled, hoverColor, backgroundColor, icon, label, labelStyle, labelPosition, primary, rippleColor, secondary, style, ...other } = this.props; const { button: { height: buttonHeight, minWidth: buttonMinWidth, textTransform: buttonTextTransform, }, flatButton: { buttonFilterColor, color: buttonColor, disabledTextColor, fontSize, fontWeight, primaryTextColor, secondaryTextColor, textColor, textTransform = buttonTextTransform || 'uppercase', }, } = this.context.muiTheme; const defaultTextColor = disabled ? disabledTextColor : primary ? primaryTextColor : secondary ? secondaryTextColor : textColor; const defaultHoverColor = fade(buttonFilterColor, 0.2); const defaultRippleColor = buttonFilterColor; const buttonHoverColor = hoverColor || defaultHoverColor; const buttonRippleColor = rippleColor || defaultRippleColor; const buttonBackgroundColor = backgroundColor || buttonColor; const hovered = (this.state.hovered || this.state.isKeyboardFocused) && !disabled; const mergedRootStyles = Object.assign({}, { height: buttonHeight, lineHeight: `${buttonHeight}px`, minWidth: buttonMinWidth, color: defaultTextColor, transition: transitions.easeOut(), borderRadius: 2, userSelect: 'none', overflow: 'hidden', backgroundColor: hovered ? buttonHoverColor : buttonBackgroundColor, padding: 0, margin: 0, textAlign: 'center', }, style); let iconCloned; const labelStyleIcon = {}; if (icon) { const iconStyles = Object.assign({ verticalAlign: 'middle', marginLeft: label && labelPosition !== 'before' ? 12 : 0, marginRight: label && labelPosition === 'before' ? 12 : 0, }, icon.props.style); iconCloned = React.cloneElement(icon, { color: icon.props.color || mergedRootStyles.color, style: iconStyles, }); if (labelPosition === 'before') { labelStyleIcon.paddingRight = 8; } else { labelStyleIcon.paddingLeft = 8; } } const mergedLabelStyles = Object.assign({ letterSpacing: 0, textTransform: textTransform, fontWeight: fontWeight, fontSize: fontSize, }, labelStyleIcon, labelStyle); const labelElement = label ? ( <FlatButtonLabel label={label} style={mergedLabelStyles} /> ) : undefined; // Place label before or after children. const childrenFragment = labelPosition === 'before' ? { labelElement, iconCloned, children, } : { children, iconCloned, labelElement, }; const enhancedButtonChildren = createChildFragment(childrenFragment); return ( <EnhancedButton {...other} disabled={disabled} focusRippleColor={buttonRippleColor} focusRippleOpacity={0.3} onKeyboardFocus={this.handleKeyboardFocus} onMouseLeave={this.handleMouseLeave} onMouseEnter={this.handleMouseEnter} onTouchStart={this.handleTouchStart} style={mergedRootStyles} touchRippleColor={buttonRippleColor} touchRippleOpacity={0.3} > {enhancedButtonChildren} </EnhancedButton> ); } } export default FlatButton;
JavaScript
0.017244
@@ -2588,24 +2588,25 @@ button.%0A + */%0A onTou @@ -2715,24 +2715,25 @@ the Theme.%0A + */%0A p
e1551139259c11a48fa43a95e0c9a7442b016380
fix xs sm lg device detection
frontend-modules/angular/factories/page.factory.js
frontend-modules/angular/factories/page.factory.js
app.factory('Page', function($window) { var prefix = 'CourseMapper'; var title = 'CourseMapper'; return { title: function() { return title; }, setTitle: function(newTitle) { title = newTitle; $window.document.title = title; }, setTitleWithPrefix: function(newTitle) { title = prefix + ': ' + newTitle; $window.document.title = title; }, xs: 768, sm: 992, md: 1200, defineDevSize: function(width){ if(width < this.xs){ return 'xs'; } else if(width > xs && width <= this.sm){ return 'sm'; } else if(width > sm && width <= this.md){ return 'md'; } else if(width > this.md){ return 'lg'; } } }; });
JavaScript
0
@@ -638,16 +638,21 @@ width %3E +this. xs && wi @@ -727,16 +727,21 @@ width %3E +this. sm && wi
f2e77d58486658789b557c413c582746cd4b709c
add unfortunate notes regarding the current instability of collection binding with the DashboardView
test/apps/models/binding_dashboard/controllers/index.js
test/apps/models/binding_dashboard/controllers/index.js
var icons = Alloy.Collections.icons; var isEditable = false; function resetBadge(e) { e.item.badge = 0; } function toggleEditMode(e) { isEditable ? $.dash.stopEditing() : $.dash.startEditing(); } function handleEdit(e) { $.editButton.title = 'Done'; $.editButton.style = Ti.UI.iPhone.SystemButtonStyle.DONE; isEditable = true; } function handleCommit(e) { $.editButton.title = 'Edit'; $.editButton.style = Ti.UI.iPhone.SystemButtonStyle.PLAIN; isEditable = false; } icons.fetch(); $.index.open();
JavaScript
0
@@ -80,16 +80,1020 @@ ge(e) %7B%0A +%09// TODO: https://jira.appcelerator.org/browse/ALOY-500%0A%09//%0A%09// NOTE: Ti.UI.DashboardView collection binding should be %0A%09// considered unstable until the above ticket and its TIMOB%0A%09// dependecies are resolved.%0A%09// %0A%09// Can't use collection binding effectively with Ti.UI.DashboardView%0A%09// due to an error in setData() that causes all DashboardItems to %0A%09// be appended rather than reseting the items. This is logged in%0A%09// TIMOB-12606 and the code commented below will be implemented%0A%09// once that ticket has been resolved. Until then only simple %0A%09// interaction will work as any additional data binding events fired %0A%09// will cause all the items to be appended again.%0A%09// %0A%09// tl;dr Don't use Ti.UI.DashboardView collection binding until%0A%09// TIMOB-12606 and ALOY-500 are resolved.%0A%0A%09// var model = icons.get(e.item.modelId);%0A%09// if (model) %7B%0A%09// %09model.set('badge', 0);%0A%09// %09model.save();%0A%09// %7D else %7B%0A%09// %09TI.API.error('No corresponding model found for DashboardItem in resetBadge()');%0A%09// %7D%0A%09%0A %09e.item.
0a2cd13ce6e33caceb0a03f0d30a4e30e3ab6deb
add test for overriding process function when adding node
spec/building/node.spec.js
spec/building/node.spec.js
describe('building: node', function() { it('should be created with a registered type', function() { var renderer = Rpd.renderer('foo', function() {}); var patch = Rpd.addPatch(); expect(function() { patch.addNode('foo/bar'); }).toReportError('node/error'); }); it('does not requires a title to be set', function() { withNewPatch(function(patch, updateSpy) { expect(function() { patch.addNode('spec/empty'); }).not.toReportError(); }); }); it('saves the node title', function() { withNewPatch(function(patch, updateSpy) { function nodeWithTitle(value) { return jasmine.objectContaining({ def: jasmine.objectContaining({ title: value }) }); } patch.addNode('spec/empty'); expect(updateSpy).not.toHaveBeenCalledWith( jasmine.objectContaining({ type: 'patch/add-node', node: nodeWithTitle(jasmine.any(String)) })); updateSpy.calls.reset(); patch.addNode('spec/empty', 'Foo'); expect(updateSpy).toHaveBeenCalledWith( jasmine.objectContaining({ type: 'patch/add-node', node: nodeWithTitle('Foo') })); updateSpy.calls.reset(); patch.addNode('spec/empty', { title: 'Bar' }); expect(updateSpy).toHaveBeenCalledWith( jasmine.objectContaining({ type: 'patch/add-node', node: nodeWithTitle('Bar') })); updateSpy.calls.reset(); patch.addNode('spec/empty', null, { title: 'Buz' }); expect(updateSpy).toHaveBeenCalledWith( jasmine.objectContaining({ type: 'patch/add-node', node: nodeWithTitle('Buz') })); updateSpy.calls.reset(); patch.addNode('spec/empty', 'Foo', { title: 'Buz' }); expect(updateSpy).toHaveBeenCalledWith( jasmine.objectContaining({ type: 'patch/add-node', node: nodeWithTitle('Foo') })); }); }); it('informs it was added to a patch with an event', function() { withNewPatch(function(patch, updateSpy) { var node = patch.addNode('spec/empty'); expect(updateSpy).toHaveBeenCalledWith( jasmine.objectContaining({ type: 'patch/add-node', node: node })); }); }); it('informs it was removed from a patch with an event', function() { withNewPatch(function(patch, updateSpy) { var node = patch.addNode('spec/empty'); patch.removeNode(node); expect(updateSpy).toHaveBeenCalledWith( jasmine.objectContaining({ type: 'patch/remove-node', node: node })); }); }); it('fires no events after it was removed from a patch', function() { withNewPatch(function(patch, updateSpy) { var node = patch.addNode('spec/empty'); patch.removeNode(node); updateSpy.calls.reset(); node.addInlet('spec/any', 'foo'); expect(updateSpy).not.toHaveBeenCalledWith( jasmine.objectContaining({ type: 'node/add-inlet' })); }); }); describe('allows to subscribe node events', function() { it('node/add-inlet', function() { withNewPatch(function(patch, updateSpy) { var addInletSpy = jasmine.createSpy('add-inlet'); var node = patch.addNode('spec/empty', { handle: { 'node/add-inlet': addInletSpy } }); var inlet = node.addInlet('spec/any', 'foo'); expect(addInletSpy).toHaveBeenCalledWith( jasmine.objectContaining({ type: 'node/add-inlet', node: node, inlet: inlet })); }); }); }); xdescribe('overriding channel type definition', function() { xit('overriding inlet allow function', function() {}); xit('overriding inlet accept function', function() {}); xit('overriding inlet adapt function', function() {}); xit('overriding inlet show function', function() {}); xit('overriding inlet tune function', function() {}); xit('overriding outlet tune function', function() {}); xit('subscribing to inlet events', function() {}); xit('subscribing to outlet events', function() {}); }); xit('allows to substitute/extend renderer', function() { // i#311 }); });
JavaScript
0.000001
@@ -3509,24 +3509,733 @@ );%0A %7D);%0A%0A + it('allows to override processing function', function() %7B%0A withNewPatch(function(patch, updateSpy) %7B%0A var node = patch.addNode('spec/empty', %7B%0A process: function(inlets) %7B%0A return %7B%0A 'out': inlets.in * 2%0A %7D%0A %7D%0A %7D);%0A var inlet = node.addInlet('spec/any', 'in');%0A node.addOutlet('spec/any', 'out');%0A%0A updateSpy.calls.reset();%0A%0A inlet.receive(2);%0A%0A expect(updateSpy).toHaveBeenCalledWith(%0A jasmine.objectContaining(%7B type: 'outlet/update',%0A value: 4 %7D));%0A %7D);%0A %7D);%0A%0A describe
18a263188753a13704a590c3b54dc7bc86f72360
Fix wrong property names in ib.js
share/qbs/modules/ib/ib.js
share/qbs/modules/ib/ib.js
var DarwinTools = loadExtension("qbs.DarwinTools"); var ModUtils = loadExtension("qbs.ModUtils"); var Process = loadExtension("qbs.Process"); var PropertyList = loadExtension("qbs.PropertyList"); function prepareIbtoold(product, input, outputs) { var args = []; var outputFormat = ModUtils.moduleProperty(input, "outputFormat"); if (!["binary1", "xml1", "human-readable-text"].contains(outputFormat)) throw("Invalid ibtoold output format: " + outputFormat + ". " + "Must be in [binary1, xml1, human-readable-text]."); args.push("--output-format", outputFormat); if (ModUtils.moduleProperty(input, "warnings")) args.push("--warnings"); if (ModUtils.moduleProperty(input, "errors")) args.push("--errors"); if (ModUtils.moduleProperty(input, "notices")) args.push("--notices"); if (input.fileTags.contains("assetcatalog")) { args.push("--platform", DarwinTools.applePlatformName(product.moduleProperty("qbs", "targetOS"))); var appIconName = ModUtils.moduleProperty(input, "appIcon"); if (appIconName) args.push("--app-icon", appIconName); var launchImageName = ModUtils.moduleProperty(input, "launchImage"); if (launchImageName) args.push("--launch-image", launchImageName); // Undocumented but used by Xcode (only for iOS?), probably runs pngcrush or equivalent if (ModUtils.moduleProperty(input, "compressPngs")) args.push("--compress-pngs"); } else { var sysroot = product.moduleProperty("qbs", "sysroot"); if (sysroot) args.push("--sdk", sysroot); args.push("--flatten", ModUtils.moduleProperty(input, "flatten") ? 'YES' : 'NO'); // --module and --auto-activate-custom-fonts were introduced in Xcode 6.0 if (ModUtils.moduleProperty(input, "ibtoolVersionMajor") >= 6) { var module = ModUtils.moduleProperty(input, "module"); if (module) args.push("--module", module); if (ModUtils.moduleProperty(input, "autoActivateCustomFonts")) args.push("--auto-activate-custom-fonts"); } } // --minimum-deployment-target was introduced in Xcode 5.0 if (ModUtils.moduleProperty(input, "ibtoolVersionMajor") >= 5) { if (product.moduleProperty("cpp", "minimumOsxVersion")) { args.push("--minimum-deployment-target"); args.push(product.moduleProperty("cpp", "minimumOsxVersion")); } if (product.moduleProperty("cpp", "minimumIosVersion")) { args.push("--minimum-deployment-target"); args.push(product.moduleProperty("cpp", "minimumIosVersion")); } } // --target-device and -output-partial-info-plist were introduced in Xcode 6.0 for ibtool if (ModUtils.moduleProperty(input, "ibtoolVersionMajor") >= 6 || input.fileTags.contains("assetcatalog")) { args.push("--output-partial-info-plist", outputs.partial_infoplist[0].filePath); if (product.moduleProperty("qbs", "targetOS").contains("osx")) args.push("--target-device", "mac"); if (product.moduleProperty("qbs", "targetOS").contains("ios")) { // TODO: Only output the devices specified in TARGET_DEVICE_FAMILY // We can't get this info from Info.plist keys due to dependency order args.push("--target-device", "iphone"); args.push("--target-device", "ipad"); } } return args; } function ibtoolVersion(ibtool) { var process; var version; try { process = new Process(); if (process.exec(ibtool, ["--version"], true) !== 0) print(process.readStdErr()); var propertyList = new PropertyList(); try { propertyList.readFromString(process.readStdOut()); var plist = JSON.parse(propertyList.toJSONString()); if (plist) plist = plist["com.apple.ibtool.version"]; if (plist) version = plist["short-bundle-version"]; } finally { propertyList.clear(); } } finally { process.close(); } return version; }
JavaScript
0.00663
@@ -1073,16 +1073,20 @@ %22appIcon +Name %22);%0A @@ -1230,16 +1230,20 @@ nchImage +Name %22);%0A
a7f3aa5362bd0300aff871859b70f328a0de32d2
refactor alert generation so it can be used for info alerts too
meinberlin/static/embed.js
meinberlin/static/embed.js
/* global $ location django */ $(document).ready(function () { var $main = $('main') var currentPath var popup var patternsForPopup = /\/accounts\b/ var headers = { 'X-Embed': '' } testCanSetCookie() var loadHtml = function (html, textStatus, xhr) { var $root = $(html).filter('main') var nextPath = xhr.getResponseHeader('x-ajax-path') if (patternsForPopup.test(nextPath)) { $('#embed-confirm').modal('show') return false } // only update the currentPath if there was no modal opened currentPath = nextPath $main.empty() $main.append($root.children()) onReady() } var onReady = function () { // adhocracy4.onReady($main) } var getEmbedTarget = function ($element, url) { var embedTarget = $element.data('embedTarget') if (embedTarget) { return embedTarget } else if (!url || url[0] === '#' || $element.attr('target')) { return 'ignore' } else if ($element.is('.rich-text a')) { return 'external' } else if (patternsForPopup.test(url)) { return 'popup' } else { return 'internal' } } $(document).on('click', 'a[href]', function (event) { // NOTE: event.target.href is resolved against /embed/ var url = event.target.getAttribute('href') var $link = $(event.target) var embedTarget = getEmbedTarget($link, url) if (embedTarget === 'internal') { event.preventDefault() if (url[0] === '?') { url = currentPath + url } $.ajax({ url: url, headers: headers, success: loadHtml }) } else if (embedTarget === 'popup') { event.preventDefault() popup = window.open( url, 'embed_popup', 'height=650,width=500,location=yes,menubar=no,toolbar=no,status=no' ) } }) $(document).on('submit', 'form[action]', function (event) { var form = event.target var $form = $(form) var embedTarget = getEmbedTarget($form, form.method) if (embedTarget === 'internal') { event.preventDefault() $.ajax({ url: form.action, method: form.method, headers: headers, data: $form.serialize(), success: loadHtml }) } }) $('.js-embed-logout').on('click', function (e) { e.preventDefault() $.post( '/accounts/logout/', function () { location.reload() } ) }) // The popup will send a message when the user is logged in. Only after // this message the Popup will close. window.addEventListener('message', function (e) { if (e.origin === location.origin) { var data = JSON.parse(e.data) if (data.name === 'popup-close' && popup) { popup.close() location.reload() } } }, false) $(document).ajaxError(function (event, jqxhr) { var text var $error = $('<p class="alert danger alert--small" role="alert"></p>') var $close = $('<button class="alert__close"><i class="fa fa-times" aria-hidden="true"></i></button>') var removeMessage = function () { $error.remove() } switch (jqxhr.status) { case 404: text = django.gettext('We couldn\'t find what you were looking for.') break case 401: case 403: text = django.gettext('You don\'t have the permission to view this page.') break default: text = django.gettext('Something went wrong!') break } $error.text(text) $error.append($close) $error.prependTo($('#embed-status')) $close.attr('title', django.gettext('Close')) $error.on('click', removeMessage) setTimeout(removeMessage, 6000) }) $.ajax({ url: $('body').data('url'), headers: headers, success: loadHtml }) }) function testCanSetCookie () { var cookie = 'can-set-cookie=true;' var regExp = new RegExp(cookie) document.cookie = cookie return regExp.test(document.cookie) }
JavaScript
0
@@ -2862,260 +2862,8 @@ ext%0A - var $error = $('%3Cp class=%22alert danger alert--small%22 role=%22alert%22%3E%3C/p%3E')%0A var $close = $('%3Cbutton class=%22alert__close%22%3E%3Ci class=%22fa fa-times%22 aria-hidden=%22true%22%3E%3C/i%3E%3C/button%3E')%0A%0A var removeMessage = function () %7B%0A $error.remove()%0A %7D%0A%0A @@ -3222,24 +3222,50 @@ +var $error -.text(text + = getAlert(text, 'danger', 6000 )%0A @@ -3277,153 +3277,515 @@ ror. -a p +re pend -($close)%0A $error.prependTo($('#embed-status'))%0A $close.attr('title', django.gettext('Close'))%0A%0A $error.on('click', removeMessage)%0A +To($('#embed-status'))%0A %7D)%0A%0A function getAlert (text, state, timeout) %7B%0A var $alert = $('%3Cp class=%22alert ' + state + ' alert--small%22 role=%22alert%22%3E' + text + '%3C/p%3E')%0A var $close = $('%3Cbutton class=%22alert__close%22%3E%3Ci class=%22fa fa-times%22 aria-hidden=%22true%22%3E%3C/i%3E%3C/button%3E')%0A%0A $alert.append($close)%0A $close.attr('title', django.gettext('Close'))%0A%0A var removeMessage = function () %7B%0A $alert.remove()%0A %7D%0A $alert.on('click', removeMessage)%0A if (typeof timeout === 'number') %7B%0A @@ -3814,18 +3814,44 @@ ge, -6000 +timeout )%0A + + %7D%0A return $alert%0A %7D -) %0A%0A
f7778dc95b9874d008d3d9464e20acf84b3ed2dd
Remove Sentry logging of all error-level console logs
packages/lesswrong/client/logging.js
packages/lesswrong/client/logging.js
import * as Sentry from '@sentry/browser'; import { getSetting, addCallback } from 'meteor/vulcan:core' const sentryUrl = getSetting('sentry.url'); const sentryEnvironment = getSetting('sentry.environment'); Sentry.init({ dsn: sentryUrl, beforeBreadcrumb(breadcrumb, hint) { if (breadcrumb.level === "error" && breadcrumb.message) { Sentry.captureException(breadcrumb.message) } return breadcrumb }, environment: sentryEnvironment }); // Initializing sentry on the client browser function identifyUserToSentry(user) { // Set user in sentry scope Sentry.configureScope((scope) => { scope.setUser({id: user._id, email: user.email, username: user.username}); }); } addCallback('events.identify', identifyUserToSentry) function addUserIdToGoogleAnalytics(user) { if (window && window.ga) { window.ga('set', 'userId', user._id); // Set the user ID using signed-in user_id. } } addCallback('events.identify', addUserIdToGoogleAnalytics)
JavaScript
0
@@ -239,192 +239,8 @@ rl,%0A - beforeBreadcrumb(breadcrumb, hint) %7B%0A if (breadcrumb.level === %22error%22 && breadcrumb.message) %7B%0A Sentry.captureException(breadcrumb.message)%0A %7D%0A return breadcrumb%0A %7D,%0A en
59d911b058084fa579c908691d699bbcc20d6890
use strict for Maven Spice.
share/spice/maven/maven.js
share/spice/maven/maven.js
function ddg_spice_maven(api_result) { if (api_result.responseHeader.status || api_result.response.numFound == 0) return Spice.render({ data : api_result, header1 : api_result.responseHeader.params.q + " (Maven Central Repository)", source_url : 'http://search.maven.org/#search%7Cga%7C1%7C' + encodeURIComponent(api_result.responseHeader.params.q), source_name : 'Maven Central Repository', template_normal : 'maven', force_big_header : true, force_no_fold : true }); $("#zero_click_abstract").css({ "margin": "4px 12px 0px 2px !important", }); }
JavaScript
0
@@ -32,16 +32,35 @@ sult) %7B%0A + %22use strict%22;%0A%0A if ( @@ -142,14 +142,31 @@ 0) -return +%7B%0A return;%0A %7D %0A
6f08d9fbe3f0f2233c4849f2819ca383d18a0821
Add error detail to diagnostic messages when available.
extension.js
extension.js
"use strict"; // Requires var vscode = require("vscode"); var markdownlint = require("markdownlint"); var fs = require("fs"); var path = require("path"); var packageJson = require("./package.json"); var defaultConfig = require("./default-config.json"); // Constants var extensionName = packageJson.name; var markdownlintVersion = packageJson .dependencies .markdownlint .replace(/[^\d.]/, ""); var configFileName = ".markdownlint.json"; var markdownLanguageId = "markdown"; var markdownlintRulesMdPrefix = "https://github.com/DavidAnson/markdownlint/blob/v"; var markdownlintRulesMdPostfix = "/doc/Rules.md"; var codeActionPrefix = "Click for more information about "; var badConfig = "Unable to read configuration file "; var throttleDuration = 500; // Variables var diagnosticCollection = null; var customConfig = null; var throttle = { "document": null, "timeout": null }; // Lints a Markdown document function lint (document) { // Skip if not Markdown if (document.languageId !== markdownLanguageId) { return; } // Configure var options = { "strings": { "document": document.getText() }, "config": customConfig || defaultConfig, "resultVersion": 1 }; var diagnostics = []; // Lint and create Diagnostics markdownlint .sync(options) .document .forEach(function forResult (result) { var ruleName = result.ruleName; var ruleDescription = result.ruleDescription; var message = ruleName + "/" + result.ruleAlias + ": " + ruleDescription; var range = document.lineAt(result.lineNumber - 1).range; if (result.errorRange) { var start = result.errorRange[0] - 1; var end = start + result.errorRange[1]; range = range.with(range.start.with(undefined, start), range.end.with(undefined, end)); } var diagnostic = new vscode.Diagnostic(range, message, vscode.DiagnosticSeverity.Warning); diagnostic.code = markdownlintRulesMdPrefix + markdownlintVersion + markdownlintRulesMdPostfix + "#" + ruleName.toLowerCase() + "---" + ruleDescription.toLowerCase().replace(/ /g, "-"); diagnostics.push(diagnostic); }); // Publish diagnosticCollection.set(document.uri, diagnostics); } // Implements CodeActionsProvider.provideCodeActions to open info links for rules function provideCodeActions (document, range, codeActionContext) { var diagnostics = codeActionContext.diagnostics || []; return diagnostics.map(function forDiagnostic (diagnostic) { return { "title": codeActionPrefix + diagnostic.message.substr(0, 5), "command": "vscode.open", "arguments": [ vscode.Uri.parse(diagnostic.code) ] }; }); } // Loads custom rule configuration function loadCustomConfig () { var settings = vscode.workspace.getConfiguration(packageJson.displayName); customConfig = settings.get("config"); var rootPath = vscode.workspace.rootPath; if (rootPath) { var configFilePath = path.join(rootPath, configFileName); if (fs.existsSync(configFilePath)) { try { customConfig = JSON.parse(fs.readFileSync(configFilePath, "utf8")); } catch (ex) { vscode.window.showWarningMessage(badConfig + "'" + configFilePath + "' (" + (ex.message || ex.toString()) + ")"); } } } // Re-lint all open files (vscode.workspace.textDocuments || []).forEach(lint); } // Suppresses a pending lint for the specified document function suppressLint (document) { if (throttle.timeout && (document === throttle.document)) { clearTimeout(throttle.timeout); throttle.document = null; throttle.timeout = null; } } // Requests a lint of the specified document function requestLint (document) { suppressLint(document); throttle.document = document; throttle.timeout = setTimeout(function waitThrottleDuration () { // Do not use throttle.document in this function; it may have changed lint(document); suppressLint(document); }, throttleDuration); } // Handles the didChangeTextDocument event function didChangeTextDocument (change) { requestLint(change.document); } // Handles the didCloseTextDocument event function didCloseTextDocument (document) { suppressLint(document); diagnosticCollection.delete(document.uri); } function activate (context) { // Hook up to workspace events context.subscriptions.push( vscode.workspace.onDidOpenTextDocument(lint), vscode.workspace.onDidChangeTextDocument(didChangeTextDocument), vscode.workspace.onDidCloseTextDocument(didCloseTextDocument), vscode.workspace.onDidChangeConfiguration(loadCustomConfig)); // Register CodeActionsProvider context.subscriptions.push( vscode.languages.registerCodeActionsProvider(markdownLanguageId, { "provideCodeActions": provideCodeActions })); // Create DiagnosticCollection diagnosticCollection = vscode.languages.createDiagnosticCollection(extensionName); context.subscriptions.push(diagnosticCollection); // Hook up to file system changes for custom config file var rootPath = vscode.workspace.rootPath; if (rootPath) { var fileSystemWatcher = vscode.workspace.createFileSystemWatcher(path.join(rootPath, configFileName)); context.subscriptions.push( fileSystemWatcher, fileSystemWatcher.onDidCreate(loadCustomConfig), fileSystemWatcher.onDidChange(loadCustomConfig), fileSystemWatcher.onDidDelete(loadCustomConfig)); } // Load custom rule config loadCustomConfig(); } exports.activate = activate;
JavaScript
0
@@ -1474,24 +1474,106 @@ escription;%0A +%09%09%09if (result.errorDetail) %7B%0A%09%09%09%09message += %22 %5B%22 + result.errorDetail + %22%5D%22;%0A%09%09%09%7D%0A %09%09%09var range
fb7b533da70b7d5deef59c79e60cc87167989c72
Fix for #8
extension.js
extension.js
'use strict'; const vscode = require('vscode'); const postcss = require('postcss'); const postcssSafeParser = require('postcss-safe-parser'); const resolve = require('npm-module-path'); let autoprefixer = null; function getSyntax(language) { switch (language) { case 'less': { return require('postcss-less'); } case 'scss': { return require('postcss-scss'); } default: { return null; } } } function init(document, onDidSaveStatus) { const workspace = vscode.workspace.rootPath ? vscode.workspace.rootPath : ''; resolve('autoprefixer', workspace, autoprefixer) .then((filepath) => { if (!autoprefixer) { autoprefixer = require(filepath); } const browsers = vscode.workspace.getConfiguration('autoprefixer').browsers; const content = document.getText(); const lang = document.languageId || document._languageId; const syntax = getSyntax(lang); const parser = (lang === 'css') ? postcssSafeParser : syntax; postcss([autoprefixer(browsers)]) .process(content, { parser }) .then((result) => { result.warnings().forEach((x) => { console.warn(x.toString()); }); const editor = vscode.editor || vscode.window.activeTextEditor; if (!editor) { throw new Error('Ooops...'); } const document = editor.document; const lastLine = document.lineAt(document.lineCount - 1); const start = new vscode.Position(0, 0); const end = new vscode.Position(document.lineCount - 1, lastLine.text.length); const range = new vscode.Range(start, end); if (document.autoprefixer) { delete document.autoprefixer; return; } if (onDidSaveStatus) { const we = new vscode.WorkspaceEdit(); we.replace(document.uri, range, result.css); document.autoprefixer = true; vscode.workspace.applyEdit(we).then(() => { document.save(); }); } else { editor.edit((builder) => { builder.replace(range, result.css); }); } }) .catch(console.error); }) .catch((err) => { if (err.code === 'ENOENT') { return vscode.window.showErrorMessage('Failed to load autoprefixer library. Please install autoprefixer in your workspace folder using **npm install autoprefixer** or globally using **npm install -g autoprefixer** and then run command again.'); } console.error(err); }); } function activate(context) { const disposable = vscode.commands.registerTextEditorCommand('autoprefixer.execute', (textEditor) => { init(textEditor.document, false); }); context.subscriptions.push(disposable); const onSave = vscode.workspace.onDidSaveTextDocument((document) => { const onDidSave = vscode.workspace.getConfiguration('autoprefixer').prefixOnSave; if (onDidSave) { init(document, true); } }); context.subscriptions.push(onSave); } exports.activate = activate;
JavaScript
0
@@ -84,27 +84,71 @@ ;%0Aconst +safeParser = require(' postcss -S +-s afe +-parser');%0Aconst less Parser = @@ -161,35 +161,141 @@ re('postcss- -safe-parser +less');%0Aconst lessStringifier = require('postcss-less/dist/less-stringify');%0Aconst scssParser = require('postcss-scss ');%0A%0Aconst r @@ -366,30 +366,38 @@ function get -Syntax +PostcssOptions (language) %7B @@ -455,94 +455,233 @@ urn -require('postcss-less');%0A %7D%0A case 'scss': %7B%0A return require('postcss-scss') +%7B%0A parser: lessParser,%0A stringifier: lessStringifier%0A %7D;%0A %7D%0A case 'scss': %7B%0A return %7B%0A parser: scssParser%0A %7D;%0A %7D%0A case 'css': %7B%0A return %7B%0A parser: safeParser%0A %7D ;%0A @@ -1177,138 +1177,55 @@ geId - %7C%7C document._languageId;%0A const syntax = getSyntax(lang);%0A const parser = (lang === 'css') ? postcssSafeParser : syntax +;%0A const options = getPostcssOptions(lang) ;%0A%0A @@ -1293,18 +1293,15 @@ nt, -%7B parser %7D +options )%0A
b5477c0416e1e7b00da18fcd6fb31c825d6c30be
Fix return values of `automations.*`
lib/client/automations.js
lib/client/automations.js
//automations.js: Client for the zendesk API. var util = require('util'), Client = require('./client').Client, defaultUser = require('./helpers').defaultUser; var Automations = exports.Automations = function (options) { this.jsonAPINames = [ 'automations', 'automation' ]; Client.call(this, options); }; // Inherit from Client base object util.inherits(Automations, Client); // ######################################################## Automations // ====================================== Listing Automations Automations.prototype.list = function (cb) { this.requestAll('GET', ['automations'], cb);//all }; Automations.prototype.listActive = function (automationID, cb) { this.requestAll('GET', ['automations', 'active'], cb);//all? }; // ====================================== Viewing Automations Automations.prototype.show = function (automationID, cb) { this.request('GET', ['automations', automationID], cb); }; // ====================================== Creating Automations Automations.prototype.create = function (automation, cb) { this.request('POST', ['automations'], automation, cb); }; // ====================================== Updating Automations Automations.prototype.update = function (automationID, automation, cb) { this.request('PUT', ['automations', automationID], automation, cb); }; // ====================================== Deleting Automations Automations.prototype.delete = function (automationID, cb) { this.request('DELETE', ['automations', automationID], cb); }; // ====================================== Reorder Audits Automations.prototype.reorder = function (automationIDs, cb) { this.requestAll('PUT', ['automations', 'reorder'], {automation_ids: automationIDs}, cb); };
JavaScript
0
@@ -571,32 +571,39 @@ nction (cb) %7B%0A +return this.requestAll( @@ -636,16 +636,16 @@ );//all%0A - %7D;%0A%0AAuto @@ -699,32 +699,39 @@ tionID, cb) %7B%0A +return this.requestAll( @@ -895,32 +895,39 @@ tionID, cb) %7B%0A +return this.request('GE @@ -1086,32 +1086,39 @@ mation, cb) %7B%0A +return this.request('PO @@ -1291,32 +1291,39 @@ mation, cb) %7B%0A +return this.request('PU @@ -1497,32 +1497,39 @@ tionID, cb) %7B%0A +return this.request('DE @@ -1692,26 +1692,33 @@ nIDs, cb) %7B%0A - +return this.request
6330f0eaa9a0747236d3926d2ff0926d97f81464
remove validation against ActivityPub Schema, add more detail to error message
lib/collections/actors.js
lib/collections/actors.js
/* Agora Forum Software Copyright (C) 2018 Gregory Sartucci License: AGPL-3.0, Check file LICENSE */ this.Actors = new Mongo.Collection('actors'); this.Actors.before.insert(function(userId, actor) { if (!activityPubActorTypes.includes(actor.type)) throw new Meteor.Error('Not an Actor', 'Cannot insert document into Actor Collection: Not an Actor.'); if (!activityPubSchemas.validate("Actor.json", actor)) throw new Meteor.Error('Invalid Actor', 'Cannot insert Actor: Schema not valid:' + activityPubSchemas.errorsText()); if (Actors.findOne({id: actor.id})) throw new Meteor.Error('Duplicate Actor', 'Cannot insert Actor: Actor with that id already present.'); }); this.Actors.after.insert(function(userId, actor) { if (actor.local) { Inboxes.insert({ id: actor.inbox, type: "OrderedCollection", totalItems: 0, orderedItems: [] }); Outboxes.insert({ id: actor.outbox, type: "OrderedCollection", totalItems: 0, orderedItems: [] }); FollowingLists.insert({ id: actor.following, type: "OrderedCollection", totalItems: 0, orderedItems: [] }); FollowerLists.insert({ id: actor.followers, type: "OrderedCollection", totalItems: 0, orderedItems: [] }); } }); this.Actors.before.findOne(function(userId, selector, options) { if ((!options || !options.noRecursion) && selector.id && !Actors.findOne({id: selector.id}, {noRecursion: true})) try { Meteor.call('getActivityJSONFromUrl', selector.id); } catch(exception) { } }); if (Meteor.isServer) { Meteor.startup(function() { Actors._ensureIndex({id: 1}); Actors._ensureIndex({preferredUsername: 1}); }); }
JavaScript
0
@@ -371,24 +371,26 @@ or.');%0A%0A +// if (!activit @@ -432,24 +432,26 @@ actor))%0A +// throw ne @@ -706,18 +706,30 @@ present -.' +: ' + actor.id );%0A%7D);%0A%0A
9b769b4c25f412504cc63fadee3b9b04f0e39d83
update user-planner logging to differentiate suggestions and visible suggestions (#2441)
shells/lib/user-planner.js
shells/lib/user-planner.js
/* @license Copyright (c) 2018 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ import {logFactory} from '../lib/log-factory.js'; import {Planificator} from '../env/arcs.js'; const log = logFactory('UserPlanner', '#4f0433'); const warn = logFactory('UserPlanner', '#4f0433', 'warn'); export class UserPlanner { constructor(userid, hostFactory) { this.runners = []; this.userid = userid; this.hostFactory = hostFactory; } onArc({add, remove}) { //log(add, remove); if (add) { this.addArc(add.id); } if (remove) { this.removeArc(remove.id); } } async addArc(key) { if (this.runners[key]) { warn(`marshalArc: already marshaled [${key}]`); return; } this.runners[key] = true; // TODO(sjmiles): we'll need a queue to handle change notifications that arrive while we are 'await'ing log(`marshalArc [${key}]`); try { const host = await this.hostFactory(); const arc = await host.spawn({id: key}); const planificator = await this.createPlanificator(this.userid, key, arc); this.runners[key] = {host, arc, planificator}; } catch (x) { warn(`marshalArc [${key}] failed: `, x); // } } removeArc(key) { const runner = this.runners[key]; if (runner) { runner.arc && runner.arc.dispose(); this.runners[key] = null; } } async createPlanificator(userid, key, arc) { log(`createPlanificator for [${key}]`); const options = { //storageKeyBase: config.plannerStorage, //onlyConsumer: config.plannerOnlyConsumer, //debug: config.plannerDebug, userid }; const planificator = await Planificator.create(arc, options); planificator.setSearch('*'); //planificator.registerSuggestionsChangedCallback(current => this._plansChanged(current, planificator.getLastActivatedPlan())); planificator.registerVisibleSuggestionsChangedCallback(suggestions => this.suggestionsChanged(key, suggestions)); return planificator; } suggestionsChanged(key, suggestions) { log(`suggestions [${key}]:`); suggestions.forEach(({descriptionByModality, plan: {_name}}) => log(`\t\t[${_name}]: ${descriptionByModality.text}`)); } }
JavaScript
0
@@ -2164,18 +2164,16 @@ ');%0A -// planific @@ -2216,82 +2216,63 @@ ack( -current =%3E this._plansChanged(current, planificator.getLastActivatedPlan() +suggestions =%3E this.suggestionsChanged(key, suggestions ));%0A @@ -2342,33 +2342,40 @@ estions =%3E this. -s +visibleS uggestionsChange @@ -2443,32 +2443,33 @@ onsChanged(key, +%7B suggestions) %7B%0A @@ -2463,16 +2463,17 @@ gestions +%7D ) %7B%0A @@ -2477,16 +2477,215 @@ log(%60 +$%7Bsuggestions.length%7D suggestions %5B$%7Bkey%7D%5D: $%7Bsuggestions.map((%7Bplan%7D) =%3E %60%5B$%7Bplan.name%7D%5D%60).join(', ')%7D%60);%0A %7D%0A%0A visibleSuggestionsChanged(key, suggestions) %7B%0A log(%60$%7Bsuggestions.length%7D visible suggesti
6c4dfa0d196ebaea0a07de336e9d1526e39acbe7
Add tests for the filter function
test/bootstrap.test.js
test/bootstrap.test.js
/** * Copyright 2016 Daniel Koch * * 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. */ /* * Tests for the bootstrapper */ const test = require('tape'); const utils = require('./fixture'); const prunk = require('prunk'); const path = require('path'); // Setup utility const setup = (copyMock) => { prunk.mock('recursive-copy', copyMock); return require('../lib/bootstrap'); }; // Teardown utility const teardown = () => utils.resetTestDoubles('../lib/bootstrap'); test('bootstrap; exports a function', t => { t.plan(1); t.equals( typeof setup(), 'function'); t.end(); teardown(); }); test('bootstrap; copies correctly', t => { t.plan(2); const toPath = '$$toPath$$'; const mock = (from, to) => { t.equals(to, toPath); t.equals(from, path.resolve(__dirname, '..', '_tpl')); return Promise.resolve(); }; const bootstrap = setup(mock); bootstrap(toPath) .catch( e => t.fail(e) ) .then( () => t.end() ); teardown(); }); test('bootstrap; fails if the library fails', t => { t.plan(1); const mock = () => { return Promise.reject(); }; const bootstrap = setup(mock); bootstrap() .then( () => t.fail() ) .catch( () => t.pass() ) .then( () => t.end() ); teardown(); });
JavaScript
0.000001
@@ -1513,32 +1513,904 @@ eardown();%0A%7D);%0A%0A +test('bootstrap; invokes the copy function with a config object', t =%3E %7B%0A t.plan(2);%0A%0A const mock = (from, to, obj) =%3E %7B%0A t.equals(typeof obj, 'object');%0A t.equals(typeof obj.filter, 'function');%0A return Promise.resolve();%0A %7D;%0A const bootstrap = setup(mock);%0A%0A bootstrap('')%0A .catch( e =%3E t.fail(e) )%0A .then( () =%3E t.end() );%0A%0A teardown();%0A%7D);%0A%0Atest('bootstrap; filters for _tpl', t =%3E %7B%0A t.plan(4);%0A%0A const mock = (from, to, obj) =%3E %7B%0A%0A t.equals(obj.filter('_tpl'), false);%0A t.equals(obj.filter('_tpl/a/b/c'), false);%0A t.equals(obj.filter('a/_tpl/b'), true);%0A t.equals(obj.filter('filename'), true );%0A%0A return Promise.resolve();%0A %7D;%0A const bootstrap = setup(mock);%0A%0A bootstrap('')%0A .catch( e =%3E t.fail(e) )%0A .then( () =%3E t.end() );%0A%0A teardown();%0A%7D);%0A%0A test('bootstrap;
db5daff01eb54f98d079a06c307cb958fa074f4e
Remove hidden files from debug fixtures targets. (#287)
test/debug-fixtures.js
test/debug-fixtures.js
const chai = require("chai"); const child = require("child_process"); const fs = require("fs-extra"); const helper = require("babel-helper-fixtures"); const path = require("path"); const fixtureLoc = path.join(__dirname, "debug-fixtures"); const tmpLoc = path.join(__dirname, "tmp"); const clear = () => { process.chdir(__dirname); if (fs.existsSync(tmpLoc)) fs.removeSync(tmpLoc); fs.mkdirSync(tmpLoc); process.chdir(tmpLoc); }; const saveInFiles = (files) => { Object.keys(files).forEach((filename) => { const content = files[filename]; fs.outputFileSync(filename, content); }); }; const assertTest = (stdout, stderr, opts) => { stderr = stderr.trim(); if (stderr) { throw new Error("stderr:\n" + stderr); } stdout = stdout.trim(); stdout = stdout.replace(/\\/g, "/"); if (opts.stdout) { const expectStdout = opts.stdout.trim(); chai.expect(stdout).to.equal(expectStdout, "stdout didn't match"); } else { const file = path.join(opts.testLoc, "stdout.txt"); console.log(`New test file created: ${file}`); fs.outputFileSync(file, stdout); } }; const buildTest = (opts) => { const binLoc = path.join(process.cwd(), "node_modules/.bin/babel"); return (callback) => { clear(); saveInFiles(opts.inFiles); let args = [binLoc]; args = args.concat(opts.args); const spawn = child.spawn(process.execPath, args); let stdout = ""; let stderr = ""; spawn.stdout.on("data", (chunk) => stdout += chunk); spawn.stderr.on("data", (chunk) => stderr += chunk); spawn.on("close", () => { let err; try { assertTest(stdout, stderr, opts); } catch (e) { err = e; } callback(err); }); }; }; describe("debug output", () => { fs.readdirSync(fixtureLoc).forEach((testName) => { const testLoc = path.join(fixtureLoc, testName); const opts = { args: ["src", "--out-dir", "lib"], testLoc: testLoc, }; const stdoutLoc = path.join(testLoc, "stdout.txt"); if (fs.existsSync(stdoutLoc)) { opts.stdout = helper.readFile(stdoutLoc); } const optionsLoc = path.join(testLoc, "options.json"); if (!fs.existsSync(optionsLoc)) { throw new Error(`Debug test '${testName}' is missing an options.json file`); } opts.inFiles = { "src/in.js": "", ".babelrc": helper.readFile(optionsLoc), }; it(testName, buildTest(opts)); }); });
JavaScript
0
@@ -1813,32 +1813,78 @@ (testName) =%3E %7B%0A + if (testName.slice(0, 1) === %22.%22) return;%0A const testLo
01a1d030f3fbd61b113df3c0c971d77bb09fc023
allow HTML in the title
fancy-tab.js
fancy-tab.js
(function (angular) { 'use strict'; // Mix in to our module var module; try { module = angular.module('coUtils'); } catch (e) { module = angular.module('coUtils', []); } module .directive('tabs', function() { return { restrict: 'E', transclude: true, scope: { current: '=?', autoSelect: '=?', type: '@' }, controller: ['$scope', '$element', function($scope, $element) { var panes = $scope.panes = [], selected; $scope.autoSelect = $scope.autoSelect === undefined ? true : $scope.autoSelect; $scope.select = function(pane) { selected = pane.name || pane.title; angular.forEach(panes, function(onePane) { onePane.selected = false; }); pane.selected = true; $scope.current = selected; }; $scope.touched = function (type, pane) { if ($scope.type && $scope.type === type || type === ($scope.type || 'click')) { $scope.select(pane); } }; this.addPane = function(pane) { if (panes.length == 0 && $scope.autoSelect || (pane.name || pane.title) === $scope.current) $scope.select(pane); panes.push(pane); }; this.removePane = function(pane) { var index = panes.indexOf(pane); if (index !== -1) { panes.splice(index, 1); } }; this.deselect = function (pane) { var index = panes.indexOf(pane), i; for (i = 0; i < panes.length; i += 1) { if (i !== index && !panes[i].hide) { $scope.select(panes[i]); break; } } }; // Allow for programmatic tab selection $scope.$watch('current', function (val) { if (val && (selected === undefined || val !== selected)) { selected = val; angular.forEach(panes, function(pane) { if (val === (pane.name || pane.title)) { pane.selected = true; } else { pane.selected = false; } }); } }); }], template: '<div>' + '<nav>' + '<div ng-repeat="pane in panes" ng-if="!pane.hide" ng-class="{active: pane.selected}" ng-click="touched(' + "'click'" + ', pane)" ng-touch="touched(' + "'touch'" + ', pane)">' + '<div class="{{pane.icon}}"></div>' + '<span>{{pane.title}}</span>' + '</div>' + '</nav>' + '<div class="tab-content" ng-transclude></div>' + '</div>' }; }) .directive('pane', function() { return { require: '^tabs', restrict: 'E', transclude: true, scope: { title: '@', icon: '@', selected: '=?', name: '=?', hide: '=?' }, link: function(scope, element, attrs, tabsCtrl) { scope.hide = scope.hide || false; tabsCtrl.addPane(scope); scope.$watch('selected', function (val) { if (val) { element.addClass('active'); } else { element.removeClass('active'); } }); scope.$watch('hide', function (hidden) { if (scope.selected && hidden) { tabsCtrl.deselect(scope); } }); scope.$on('$destroy', function () { tabsCtrl.removePane(scope); }); }, template: '<div ng-if="selected && !hide" ng-transclude></div>' }; }); }(this.angular));
JavaScript
0.000216
@@ -3540,11 +3540,23 @@ span -%3E%7B%7B + ng-bind-html=%22 pane @@ -3561,18 +3561,18 @@ ne.title -%7D%7D +%22%3E %3C/span%3E'
5aa3e9c5c57bd32b9416784c50b259cefd1f795b
Fix wrong XP gain
src/reducers/calculator.js
src/reducers/calculator.js
import { Map } from 'immutable'; import { CALCULATE } from '../constants/calculator'; import { CHANGE_INITIAL_VALUE } from '../constants/character'; import { ADD_CARD, REMOVE_CARD } from '../constants/cards'; import baseXpData from '../data/base-xp.json'; import classXpData from '../data/class-xp.json'; import cardsXpData from '../data/xp-cards.json'; export const INITIAL_STATE = new Map({}); // Actually, it's the maximum level and rank we can calculate // from the data of tosbase.com export const MAX_BASE_LEVEL = baseXpData.length; export const MAX_RANK = classXpData.length; function calculateXp(state) { const initial = state.getIn(['character', 'initial']); const cards = state.get('cards'); let rank = initial.get('rank'); let baseLevel = initial.get('baseLevel'); let classLevel = initial.get('classLevel'); let baseXp = initial.get('baseXp'); let classXp = initial.get('classXp'); let accumulatedBaseXp = 0; let accumulatedClassXp = 0; // Accumulate XP from cards cards.forEach((quantity, i) => { accumulatedBaseXp += cardsXpData[i].base * quantity; baseXp += accumulatedBaseXp; accumulatedClassXp += cardsXpData[i].class * quantity; classXp += accumulatedClassXp; }); let reqBaseXp = baseXpData[baseLevel]; // Consume baseXp to level up while (baseLevel < MAX_BASE_LEVEL && baseXp >= reqBaseXp) { baseXp -= reqBaseXp; baseLevel++; reqBaseXp = baseXpData[baseLevel]; } let reqClassXp = classXpData[rank - 1][classLevel]; // Consume classXp to level up while ( (rank < MAX_RANK || classLevel < 15 && rank === 15) && classXp >= reqClassXp ) { classXp -= reqClassXp; classLevel++; if (classLevel >= 15) { classLevel -= 15; rank++; } reqClassXp = classXpData[rank - 1][classLevel]; } return state.mergeDeep({ character: { rank, baseLevel, classLevel, baseXp, classXp, accumulatedBaseXp, accumulatedClassXp, }, }); } export default function (state = INITIAL_STATE, action) { switch (action.type) { case CALCULATE: case ADD_CARD: case REMOVE_CARD: case CHANGE_INITIAL_VALUE: { return calculateXp(state); } default: { return state; } } }
JavaScript
0.000003
@@ -1034,34 +1034,32 @@ %3E %7B%0A -accumulate +const ad dBaseXp += cards @@ -1050,17 +1050,16 @@ dBaseXp -+ = cardsX @@ -1092,18 +1092,8 @@ -baseXp += accu @@ -1094,24 +1094,62 @@ accumulate +dBaseXp += addBaseXp;%0A baseXp += ad dBaseXp;%0A%0A @@ -1146,34 +1146,32 @@ aseXp;%0A%0A -accumulate +const ad dClassXp += @@ -1167,17 +1167,16 @@ ClassXp -+ = cardsX @@ -1210,29 +1210,59 @@ -classXp += accumulate +accumulatedClassXp += addClassXp;%0A classXp += ad dCla
947f64e32dee056c94fe9a758d722089417a2b08
fix error normalization.
src/remote-handlers/smb.js
src/remote-handlers/smb.js
import Smb2 from '@marsaud/smb2-promise' import RemoteHandlerAbstract from './abstract' import { noop, pFinally } from '../utils' const enoentFilter = error => { const { code } = error if (code === 'STATUS_OBJECT_NAME_NOT_FOUND' || code === 'STATUS_OBJECT_PATH_NOT_FOUND') { error = { ...error, code: 'ENOENT' // code is readable only in error } } throw error } export default class SmbHandler extends RemoteHandlerAbstract { constructor (remote) { super(remote) this._forget = noop } get type () { return 'smb' } _getClient (remote) { return new Smb2({ share: `\\\\${remote.host}`, domain: remote.domain, username: remote.username, password: remote.password, autoCloseTimeout: 0 }) } _getFilePath (file) { if (file === '.') { file = undefined } let path = (this._remote.path !== '') ? this._remote.path : '' if (file) { path += file.replace(/\//g, '\\') } return path } _dirname (file) { const parts = file.split('\\') parts.pop() return parts.join('\\') } async _sync () { if (this._remote.enabled) { try { // Check access (smb2 does not expose connect in public so far...) await this.list() } catch (error) { this._remote.enabled = false this._remote.error = error.message } } return this._remote } async _outputFile (file, data, options = {}) { const client = this._getClient(this._remote) const path = this._getFilePath(file) const dir = this._dirname(path) if (dir) { await client.ensureDir(dir) } return client.writeFile(path, data, options)::pFinally(() => { client.close() }) } async _readFile (file, options = {}) { const client = this._getClient(this._remote) let content try { content = await client.readFile(this._getFilePath(file), options)::pFinally(() => { client.close() }) } catch (error) { enoentFilter(error) } return content } async _rename (oldPath, newPath) { const client = this._getClient(this._remote) try { await client.rename(this._getFilePath(oldPath), this._getFilePath(newPath))::pFinally(() => { client.close() }) } catch (error) { enoentFilter(error) } } async _list (dir = '.') { const client = this._getClient(this._remote) let list try { list = await client.readdir(this._getFilePath(dir))::pFinally(() => { client.close() }) } catch (error) { enoentFilter(error) } return list } async _createReadStream (file, options = {}) { const client = this._getClient(this._remote) let stream try { // FIXME ensure that options are properly handled by @marsaud/smb2 stream = await client.createReadStream(this._getFilePath(file), options) stream.on('end', () => client.close()) } catch (error) { enoentFilter(error) } return stream } async _createOutputStream (file, options = {}) { const client = this._getClient(this._remote) const path = this._getFilePath(file) const dir = this._dirname(path) let stream try { if (dir) { await client.ensureDir(dir) } stream = await client.createWriteStream(path, options) // FIXME ensure that options are properly handled by @marsaud/smb2 } catch (err) { client.close() throw err } stream.on('finish', () => client.close()) return stream } async _unlink (file) { const client = this._getClient(this._remote) try { await client.unlink(this._getFilePath(file))::pFinally(() => { client.close() }) } catch (error) { enoentFilter(error) } } async _getSize (file) { const client = await this._getClient(this._remote) let size try { size = await client.getSize(this._getFilePath(file))::pFinally(() => { client.close() }) } catch (error) { enoentFilter(error) } return size } }
JavaScript
0
@@ -133,25 +133,75 @@ s'%0A%0A -const enoentFilte +// Normalize the error code for file not found.%0Aconst normalizeErro r = @@ -239,20 +239,29 @@ rror%0A%0A -if ( +return (%0A code === @@ -294,16 +294,20 @@ OUND' %7C%7C +%0A code == @@ -342,48 +342,114 @@ UND' -) %7B +%0A ) %0A -error = %7B%0A ...error +? Object.create(error, %7B%0A code: %7B%0A configurable: true,%0A readable: true ,%0A code @@ -444,19 +444,22 @@ ,%0A -cod + valu e: 'ENOE @@ -465,61 +465,53 @@ ENT' - // code is readable only in error%0A +,%0A writable: true%0A + %7D%0A + -%7D%0A%0A throw + %7D)%0A : err @@ -2132,35 +2132,43 @@ or) %7B%0A -enoentFilte +throw normalizeErro r(error)%0A @@ -2434,35 +2434,43 @@ or) %7B%0A -enoentFilte +throw normalizeErro r(error)%0A @@ -2696,35 +2696,43 @@ or) %7B%0A -enoentFilte +throw normalizeErro r(error)%0A @@ -3101,35 +3101,43 @@ or) %7B%0A -enoentFilte +throw normalizeErro r(error)%0A @@ -3882,35 +3882,43 @@ or) %7B%0A -enoentFilte +throw normalizeErro r(error)%0A @@ -4157,19 +4157,27 @@ -enoentFilte +throw normalizeErro r(er
a0f6a6393996ed9220d6df2c350e068adcfea5e5
Fix height issues by applying copying textarea outerHeight onto clone before, expanding styles added. Use border-box and width 100% to complete fix
expanding.js
expanding.js
// Expanding Textareas // https://github.com/bgrins/ExpandingTextareas (function(factory) { // Add jQuery via AMD registration or browser globals if (typeof define === 'function' && define.amd) { define([ 'jquery' ], factory); } else { factory(jQuery); } }(function ($) { $.expandingTextarea = $.extend({ autoInitialize: true, initialSelector: "textarea.expanding", opts: { resize: function() { } } }, $.expandingTextarea || {}); var cloneCSSProperties = [ 'lineHeight', 'textDecoration', 'letterSpacing', 'fontSize', 'fontFamily', 'fontStyle', 'fontWeight', 'textTransform', 'textAlign', 'direction', 'wordSpacing', 'fontSizeAdjust', 'wordWrap', 'word-break', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth','borderBottomWidth', 'paddingLeft', 'paddingRight', 'paddingTop','paddingBottom', 'marginLeft', 'marginRight', 'marginTop','marginBottom', 'boxSizing', 'webkitBoxSizing', 'mozBoxSizing', 'msBoxSizing' ]; var textareaCSS = { position: "absolute", height: "100%", resize: "none" }; var preCSS = { visibility: "hidden", border: "0 solid" }; var containerCSS = { position: "relative" }; function resize() { $(this).closest('.expandingText').find("div").text(this.value.replace(/\r\n/g, "\n") + ' '); $(this).trigger("resize.expanding"); } $.fn.expandingTextarea = function(o) { var opts = $.extend({ }, $.expandingTextarea.opts, o); if (o === "resize") { return this.trigger("input.expanding"); } if (o === "destroy") { this.filter(".expanding-init").each(function() { var textarea = $(this).removeClass('expanding-init'); var container = textarea.closest('.expandingText'); container.before(textarea).remove(); textarea .attr('style', textarea.data('expanding-styles') || '') .removeData('expanding-styles'); }); return this; } this.filter("textarea").not(".expanding-init").addClass("expanding-init").each(function() { var textarea = $(this); textarea.wrap("<div class='expandingText'></div>"); textarea.after("<pre class='textareaClone'><div></div></pre>"); var container = textarea.parent().css(containerCSS); var pre = container.find("pre").css(preCSS); pre.css(textarea.attr("wrap") === "off" ? {overflowX: "scroll"} : {whiteSpace: "pre-wrap"}); // Store the original styles in case of destroying. textarea.data('expanding-styles', textarea.attr('style')); textarea.css(textareaCSS); $.each(cloneCSSProperties, function(i, p) { var val = textarea.css(p); // Only set if different to prevent overriding percentage css values. if (pre.css(p) !== val) { pre.css(p, val); } }); container.css({"min-height": textarea.outerHeight(true)}); textarea.bind("input.expanding propertychange.expanding keyup.expanding change.expanding", resize); resize.apply(this); if (opts.resize) { textarea.bind("resize.expanding", opts.resize); } }); return this; }; $(function () { if ($.expandingTextarea.autoInitialize) { $($.expandingTextarea.initialSelector).expandingTextarea(); } }); }));
JavaScript
0
@@ -1163,16 +1163,147 @@ olute%22,%0A + webkitBoxSizing: %22border-box%22,%0A mozBoxSizing: %22border-box%22,%0A boxSizing: %22border-box%22,%0A width: '100%25',%0A @@ -2754,22 +2754,72 @@ e%22).css( -preCSS +$.extend(preCSS, %7B%22min-height%22: textarea.outerHeight()%7D) );%0A%0A @@ -3397,79 +3397,8 @@ %7D); -%0A container.css(%7B%22min-height%22: textarea.outerHeight(true)%7D); %0A%0A @@ -3852,13 +3852,12 @@ %7D);%0A%0A%7D)); -%0A
01b8464fdd9a81a1c76d4134969da340d15532ae
add test for home and detailed page
e2e-tests/scenarios.js
e2e-tests/scenarios.js
'use strict'; describe('Onix Bots Application', function() { describe('botList', function() { beforeEach(function() { browser.get('index.php'); }); it('should filter the bot list as a user types into the search box', function() { var botList = element.all(by.repeater('bot in $ctrl.bots')); var query = element(by.model('$ctrl.query')); expect(botList.count()).toBe(3); query.sendKeys('converter'); expect(botList.count()).toBe(2); query.clear(); query.sendKeys('portal'); expect(botList.count()).toBe(1); }); it('should be possible to control bots order via the drop-down menu', function() { var queryField = element(by.model('$ctrl.query')); var orderSelect = element(by.model('$ctrl.orderProp')); var nameOption = orderSelect.element(by.css('option[value="name"]')); var botNameColumn = element.all(by.repeater('bot in $ctrl.bots').column('bot.name')); function getNames() { return botNameColumn.map(function(elem){ return elem.getText(); }); } queryField.sendKeys('Portal'); // Let's narrow the dataset to make the assertions shorter expect(getNames()).toEqual([ 'Portal Cinema Kirovohrad for Telegram' ]); }); }); });
JavaScript
0
@@ -153,32 +153,48 @@ php');%0A %7D);%0A%0A +%0A // Test #1%0A it('should f @@ -595,24 +595,39 @@ );%0A %7D);%0A%0A + // Test #2%0A it('shou @@ -1346,17 +1346,627 @@ %5D);%0A -%0A + %7D);%0A%0A // Test #3%0A it('should redirect index.php to index.php#!/bots', function()%7B%0A browser.get('index.php');%0A expect(browser.getLocationAbsUrl()).toBe('/bots')%0A %7D);%0A %7D);%0A%0A%0A describe('View: bot list', function()%7B%0A beforeEach(function()%7B%0A browser.get('index.php#!/bots')%0A %7D)%0A %7D);%0A%0A%0A describe('View: Bot details', function() %7B%0A%0A beforeEach(function() %7B%0A browser.get('index.pho#!/bot/converter-units-fb');%0A %7D);%0A%0A it('should display placeholder page with %60botId%60', function() %7B%0A expect(element(by.binding('$ctrl.botId')).getText()).toBe('converter-units-fb'); %0A %7D); @@ -1977,8 +1977,9 @@ %7D);%0A%0A%7D); +%0A
5f510249629a8323d051e0935bd72b8f9c720f1d
update tab-header spec file
src/components/tabs/tab-header/tab-header.spec.js
src/components/tabs/tab-header/tab-header.spec.js
import React from 'react'; import TestRenderer from 'react-test-renderer'; import 'jest-styled-components'; import { shallow } from 'enzyme'; import TabHeader from './tab-header.component'; import StyledTabHeader from './tab-header.style'; import classicTheme from '../../../style/themes/classic'; import { assertStyleMatch } from '../../../__spec_helper__/test-utils'; import baseTheme from '../../../style/themes/base'; function render(props) { return shallow(<TabHeader title='Tab Title 1' dataTabId='uniqueid1' { ...props } />); } function renderStyles(props) { return TestRenderer.create(<StyledTabHeader title='Tab Title 1' dataTabId='uniqueid1' { ...props } />); } describe('TabHeader', () => { let wrapper; it('renders as expected', () => { wrapper = renderStyles(); expect(wrapper.toJSON()).toMatchSnapshot(); }); it('renders a title as its child with a text passed as a prop', () => { wrapper = render(); expect(wrapper.children()).toHaveLength(1); expect(wrapper.children().text()).toEqual('Tab Title 1'); }); describe('attributes', () => { wrapper = render(); it('role equals "tab"', () => { expect(wrapper.find("[role='tab']").exists()).toEqual(true); }); it('data-element equals "select-tab"', () => { expect(wrapper.find("[data-element='select-tab']").exists()).toEqual(true); }); it('data-tabid equals tabId', () => { expect(wrapper.find("[data-tabid='uniqueid1']").exists()).toEqual(true); }); }); describe('when tab is selected', () => { it('has aria-selected attribute set to true', () => { wrapper = render({ isTabSelected: true }); expect(wrapper.find('[aria-selected=true]').exists()).toEqual(true); }); it('applies proper styling', () => { wrapper = renderStyles({ isTabSelected: true }); expect(wrapper.toJSON()).toMatchSnapshot(); }); describe('when position prop is set to left', () => { it('applies proper styling ', () => { wrapper = renderStyles({ position: 'left', isTabSelected: true }); expect(wrapper.toJSON).toMatchSnapshot(); }); }); }); describe('when tab is not selected', () => { it('has aria-selected attribute set to false', () => { wrapper = render({ isTabSelected: false }); expect(wrapper.find('[aria-selected=false]').exists()).toEqual(true); }); describe('when position prop is set to left', () => { it('applies proper styles', () => { wrapper = renderStyles({ position: 'left', isTabSelected: false }); expect(wrapper.toJSON()).toMatchSnapshot(); }); }); }); it('contains custom className if passed as a prop', () => { wrapper = render({ className: 'class' }); expect(wrapper.find('.class').exists()).toEqual(true); }); describe('when tab has warning', () => { it('applies proper styling', () => { wrapper = renderStyles({ tabHasWarning: true }); assertStyleMatch( { borderBottom: `2px solid ${baseTheme.colors.warning}` }, wrapper.toJSON() ); }); }); describe('when tab has error', () => { it('applies proper styling', () => { wrapper = renderStyles({ tabHasError: true }); assertStyleMatch( { borderBottom: `2px solid ${baseTheme.colors.error}` }, wrapper.toJSON() ); }); }); describe('when in classic theme', () => { it('renders as expected', () => { wrapper = renderStyles({ theme: classicTheme }); expect(wrapper.toJSON()).toMatchSnapshot(); }); describe('when position prop is set to left', () => { it('applies proper styling', () => { wrapper = renderStyles({ theme: classicTheme, position: 'left' }); expect(wrapper.toJSON()).toMatchSnapshot(); }); }); describe('when tab is selected', () => { it('applies proper styling', () => { wrapper = renderStyles({ theme: classicTheme, isTabSelected: true }); expect(wrapper.toJSON()).toMatchSnapshot(); }); describe('and the position prop is set to left', () => { it('applies proper styling', () => { wrapper = renderStyles({ theme: classicTheme, position: 'left', isTabSelected: true }); expect(wrapper.toJSON()).toMatchSnapshot(); }); }); }); describe('when tab has error', () => { it('applies proper border-bottom color', () => { wrapper = renderStyles({ theme: classicTheme, tabHasError: true }); assertStyleMatch( { borderBottom: '2px solid #ff7d00' }, wrapper.toJSON() ); }); }); describe('when tab has warning', () => { it('applies proper border-bottom color', () => { wrapper = renderStyles({ theme: classicTheme, tabHasWarning: true }); assertStyleMatch( { borderBottom: '2px solid #d63f40' }, wrapper.toJSON() ); }); }); }); });
JavaScript
0
@@ -1065,32 +1065,588 @@ tle 1');%0A %7D);%0A%0A + describe('when clicked', () =%3E %7B%0A it('triggers onClick function', () =%3E %7B%0A const onClickFunction = jest.fn();%0A wrapper = render(%7B onClick: onClickFunction %7D);%0A wrapper.simulate('click');%0A expect(onClickFunction).toHaveBeenCalled();%0A %7D);%0A %7D);%0A%0A describe('when onKeyDown', () =%3E %7B%0A it('triggers onKeyDown function', () =%3E %7B%0A const onKeyDownFunction = jest.fn();%0A wrapper = render(%7B onKeyDown: onKeyDownFunction %7D);%0A wrapper.simulate('click');%0A expect(onKeyDownFunction).toHaveBeenCalled();%0A %7D);%0A %7D);%0A%0A describe('attr
b30176097696a0612d40b2d98f734229ab18d502
Update composeFrame test with should/shouldn't clip cases
test/spec/ol/renderer/canvas/intermediatecanvas.test.js
test/spec/ol/renderer/canvas/intermediatecanvas.test.js
goog.provide('ol.test.renderer.canvas.Layer'); goog.require('ol.transform'); goog.require('ol.layer.Image'); goog.require('ol.renderer.Map'); goog.require('ol.renderer.canvas.IntermediateCanvas'); describe('ol.renderer.canvas.IntermediateCanvas', function() { describe('#composeFrame()', function() { it('clips to layer extent and draws image', function() { var layer = new ol.layer.Image({ extent: [1, 2, 3, 4] }); var renderer = new ol.renderer.canvas.IntermediateCanvas(layer); var image = new Image(); image.width = 3; image.height = 3; renderer.getImage = function() { return image; }; var frameState = { viewState: { center: [2, 3], resolution: 1, rotation: 0 }, size: [10, 10], pixelRatio: 1, coordinateToPixelTransform: ol.transform.create(), pixelToCoordinateTransform: ol.transform.create() }; renderer.getImageTransform = function() { return ol.transform.create(); }; ol.renderer.Map.prototype.calculateMatrices2D(frameState); var layerState = layer.getLayerState(); var context = { save: sinon.spy(), restore: sinon.spy(), translate: sinon.spy(), rotate: sinon.spy(), beginPath: sinon.spy(), moveTo: sinon.spy(), lineTo: sinon.spy(), clip: sinon.spy(), drawImage: sinon.spy() }; renderer.composeFrame(frameState, layerState, context); expect(context.save.callCount).to.be(1); expect(context.translate.callCount).to.be(0); expect(context.rotate.callCount).to.be(0); expect(context.beginPath.callCount).to.be(1); expect(context.moveTo.firstCall.args).to.eql([4, 4]); expect(context.lineTo.firstCall.args).to.eql([6, 4]); expect(context.lineTo.secondCall.args).to.eql([6, 6]); expect(context.lineTo.thirdCall.args).to.eql([4, 6]); expect(context.clip.callCount).to.be(1); expect(context.drawImage.firstCall.args).to.eql( [renderer.getImage(), 0, 0, 3, 3, 0, 0, 3, 3]); expect(context.restore.callCount).to.be(1); }); }); });
JavaScript
0.000001
@@ -308,52 +308,70 @@ -it('clips to layer extent and draws image', +var renderer, frameState, layerState, context;%0A beforeEach( func @@ -459,28 +459,24 @@ %7D);%0A -var renderer = n @@ -678,20 +678,16 @@ ;%0A -var frameSta @@ -1133,28 +1133,24 @@ ate);%0A -var layerState = @@ -1179,20 +1179,16 @@ ;%0A -var context @@ -1458,32 +1458,143 @@ .spy()%0A %7D;%0A + %7D);%0A%0A it('clips to layer extent and draws image', function() %7B%0A frameState.extent = %5B0, 1, 4, 5%5D;%0A%0A renderer.c @@ -2290,24 +2290,24 @@ .be(1);%0A - %7D);%0A %7D);%0A%0A%7D @@ -2298,16 +2298,1238 @@ %7D);%0A +%0A it('does not clip if frame extent does not intersect layer extent', function() %7B%0A frameState.extent = %5B1.1, 2.1, 2.9, 3.9%5D;%0A%0A renderer.composeFrame(frameState, layerState, context);%0A expect(context.save.callCount).to.be(0);%0A expect(context.translate.callCount).to.be(0);%0A expect(context.rotate.callCount).to.be(0);%0A expect(context.beginPath.callCount).to.be(0);%0A expect(context.clip.callCount).to.be(0);%0A expect(context.drawImage.firstCall.args).to.eql(%0A %5Brenderer.getImage(), 0, 0, 3, 3, 0, 0, 3, 3%5D);%0A expect(context.restore.callCount).to.be(0);%0A %7D);%0A%0A it('does not clip if frame extent is outside of layer extent', function() %7B%0A frameState.extent = %5B10, 20, 30, 40%5D;%0A%0A renderer.composeFrame(frameState, layerState, context);%0A expect(context.save.callCount).to.be(0);%0A expect(context.translate.callCount).to.be(0);%0A expect(context.rotate.callCount).to.be(0);%0A expect(context.beginPath.callCount).to.be(0);%0A expect(context.clip.callCount).to.be(0);%0A expect(context.drawImage.firstCall.args).to.eql(%0A %5Brenderer.getImage(), 0, 0, 3, 3, 0, 0, 3, 3%5D);%0A expect(context.restore.callCount).to.be(0);%0A %7D);%0A%0A %7D);%0A%0A%7D
da18612c116039ff923ae82e84c5e6bffe48e52c
Change Tag Page Header layout
src/pages/tags/index.js
src/pages/tags/index.js
import React, { Component } from 'react'; import Link from 'gatsby-link'; import moment from 'moment'; import Tag from '../../components/Tag'; const splitTag = (raw = '') => raw.split(', '); const parseDate = date => moment(date).locale('zh-hk').format('YYYY/MM/DD'); const getTag = (item) => { const { tags, url, createdDate } = item.node; if (tags) { const date = parseDate(createdDate); const postPath = url === 'about' ? url : `${date}/${url}`; return { tags: splitTag(item.node.tags), title: item.node.title, url: postPath, createdDate, }; } return item; }; const Item = ({ url = '', title = '', createdDate = '' }) => ( <li key={title}> <Link href={url} to={url}> {title} ({parseDate(createdDate)}) </Link> </li> ); const TagSession = ({ tag = 'tag', articles = [], url = '', isActive = false, }) => ( <div className="row" id={tag}> <div className="col"> <h3 style={{ color: isActive ? 'red' : 'black', }} >{tag}: </h3> <ol> {articles.map(article => ( <Item url={article.url} title={article.title} createdDate={article.createdDate} key={article.title} /> ))} </ol> </div> </div> ); class TagPage extends Component { constructor(props) { super(props); this.state = { tags: {}, }; } componentWillMount() { const tags = {}; const { edges } = this.props.data.tags; const temp = edges.map(item => getTag(item)); // debugger; temp.forEach((x) => { const { title, url, createdDate } = x; for (let i = 0, n = x.tags.length; i < n; i += 1) { const item = { title, url, createdDate }; if (tags[x.tags[i]]) { tags[x.tags[i]].push(item); } else { tags[x.tags[i]] = [item]; } } }); this.setState({ tags }); } render() { const tags = Object.keys(this.state.tags).sort(); return ( <div className="container"> <div className="row"> <div className="col"> <h2>Tags</h2> </div> </div> <div className="row"> <div className="col"> {tags.map(item => ( <Tag name={item} count={this.state.tags[item].length} key={item} />)) } </div> </div> {tags.map(tag => ( <TagSession tag={tag} articles={this.state.tags[tag].filter((v, i, a) => a.indexOf(v) === i)} isActive={decodeURI(this.props.location.hash) === `#${tag}`} key={tag} /> ))} </div> ); } } export const pageQuery = graphql` query myTags { tags: allContentfulMarkdown { edges { node { tags title url createdDate } } } } `; export default TagPage;
JavaScript
0
@@ -137,16 +137,62 @@ ts/Tag'; +%0Aimport Header from '../../components/Header'; %0A%0Aconst @@ -2058,16 +2058,56 @@ .sort(); +%0A const %7B header %7D = this.props.data; %0A%0A re @@ -2139,17 +2139,11 @@ me=%22 -container +row %22%3E%0A @@ -2154,103 +2154,213 @@ %3C -div className=%22row%22%3E%0A %3Cdiv className=%22col%22%3E%0A %3Ch2%3ETags%3C/h2%3E%0A %3C/div%3E +Header%0A img=%7Bheader.headerImage%7D%0A title=%7Bheader.title%7D%0A titleVisible=%7Bheader.titleVisible%7D%0A subTitle=%7Bheader.subTitle%7D%0A subTitleVisible=%7Bheader.subTitleVisible%7D %0A @@ -2356,39 +2356,34 @@ isible%7D%0A -%3C/div%3E%0A +/%3E %0A %3Cdiv cl @@ -3007,16 +3007,130 @@ yTags %7B%0A + header(purpose: %7Beq: %22Tags%22%7D) %7B%0A headerImage%0A title%0A titleVisible%0A subTitle%0A subTitleVisible%0A %7D%0A tags:
8d192d6ec5e5516074b6f4b854f990e55c1dcdfb
add delete test
specs/observe-misc.spec.js
specs/observe-misc.spec.js
/*global describe, it, beforeEach */ /** * observe-plus.js - https://github.com/podefr/observe-plus * Copyright(c) 2014-2015 Olivier Scherrer <[email protected]> * MIT Licensed */ "use strict"; var chai = require("chai"); var expect = chai.expect; var asap = require("asap"); var sinon = require("sinon"); var observe = require("../src/observe-plus").observe; describe("GIVEN an observed array", function () { var array, observer; beforeEach(function () { array = []; observer = observe(array); }); describe("WHEN observing addedCount", function () { var spy; beforeEach(function () { spy = sinon.spy(); observer.addListener("addedCount", 2, spy); }); describe("WHEN items are added", function () { beforeEach(function () { array.push(1, 2); }); it("THEN triggers an event", function (done) { asap(function () { expect(spy.firstCall.args[0]).to.eql({ type: "splice", object: array, index: "0", removed: [], addedCount: 2 }); done(); }); }); }); }); }); describe("GIVEN a very complex data structure", function () { var dataStructure, observer; beforeEach(function () { dataStructure = [ { arrayProperty: [ ["value1", "value2"], ["value3", "value4"], [{ property: ["deeply", "nested", "array"]}] ], objectProperty: { property1: true, property2: null, property3: { nestedArrayProperty: ["", function () {}, undefined, 0, 147, false, {}] }, property4: { deeplyNestedObject: { anotherArray: [ 0, 1, 2, 3 ] } } } } ]; observer = observe(dataStructure); }); describe("WHEN pushing an item to a deeply nested array", function () { var arr = ['value'], spliceSpy; beforeEach(function () { spliceSpy = sinon.spy(); observer.observe("splice", spliceSpy); dataStructure[0].arrayProperty[2][0].property.push(arr); }); it("THEN publishes a splice event", function (done) { asap(function () { expect(spliceSpy.firstCall.args[0]).to.eql({ type: "splice", object: dataStructure, index: "0.arrayProperty.2.0.property.3", removed: [], addedCount: 1 }); done(); }) }); describe("WHEN adding another! nested array to the newly added one", function () { beforeEach(function () { dataStructure[0].arrayProperty[2][0].property[3].push("very nested!"); }); it("THEN publishes a very nested event", function (done) { asap(function () { expect(spliceSpy.secondCall.args[0]).to.eql({ type: "splice", object: dataStructure, index: "0.arrayProperty.2.0.property.3.1", removed: [], addedCount: 1 }); done(); }); }); describe("WHEN modifying the nested array", function () { var updateSpy; beforeEach(function () { updateSpy = sinon.spy(); observer.observe("update", updateSpy); dataStructure[0].arrayProperty[2][0].property[3][1] = "updated very nested!"; }); it("THEN publishes an update event", function (done) { asap(function () { expect(updateSpy.firstCall.args[0]).to.eql({ type: "update", object: dataStructure, name: "0.arrayProperty.2.0.property.3.1", oldValue: "very nested!" }); done(); }); }); }); }); }); });
JavaScript
0.000001
@@ -4632,32 +4632,956 @@ %7D); +%0A%0A describe(%22WHEN deleting an item%22, function () %7B%0A var deleteSpy;%0A%0A beforeEach(function () %7B%0A deleteSpy = sinon.spy();%0A observer.observe(%22delete%22, deleteSpy);%0A delete dataStructure%5B0%5D.arrayProperty%5B2%5D%5B0%5D.property%5B3%5D%5B0%5D;%0A %7D);%0A%0A it(%22THEN publishes a delete event%22, function (done) %7B%0A asap(function () %7B%0A expect(deleteSpy.firstCall.args%5B0%5D).to.eql(%7B%0A type: %22delete%22,%0A object: dataStructure,%0A name: %220.arrayProperty.2.0.property.3.0%22,%0A oldValue: %22value%22%0A %7D);%0A done();%0A %7D);%0A %7D);%0A %7D); %0A %7D);
260320861f6fd750d0001e402078fdf66eebbabf
Fix issue 443 plugin proxy_cache got "expected an integer"
assets/js/app/plugins/plugin-helper-service.js
assets/js/app/plugins/plugin-helper-service.js
/** * This file contains all necessary Angular controller definitions for 'frontend.admin.login-history' module. * * Note that this file should only contain controllers and nothing else. */ (function() { 'use strict'; angular.module('frontend.plugins') .service('PluginHelperService', [ '_','$log','BackendConfig','Upload','PluginsService', function( _,$log,BackendConfig,Upload,PluginsService) { function assignExtraProperties(_pluginName, options,fields,prefix) { Object.keys(fields).forEach(function (item) { if(fields[item].schema) { assignExtraProperties(_pluginName, options,fields[item].schema.fields,item); }else{ var path = prefix ? prefix + "." + item : item; var value = fields[item].default; if ((fields[item].type === 'array' || fields[item].type === 'set') && (typeof value === 'object' || typeof value === 'string') && _pluginName !== 'statsd' ) { value = []; } fields[item].value = value fields[item].help = _.get(options,path) ? _.get(options,path).help : ''; } }); } function createConfigProperties(pluginName,fields,prefix,data) { Object.keys(fields).forEach(function (key) { if(fields[key].schema) { createConfigProperties(pluginName,fields[key].schema.fields,key,data); }else{ var path = prefix ? prefix + "." + key : key; // if (fields[key].value instanceof Array && pluginName !== 'statsd') { // // Transform to comma separated string // // data['config.' + path] = fields[key].value.join(","); // if(!data.config) data.config = {}; // if(fields[key].value) { // data.config[path] = fields[key].value.join(","); // } // } else { // // data['config.' + path] = fields[key].value; // if(!data.config) data.config = {}; // if(fields[key].value) { // data.config[path] = fields[key].value; // } // } if(!data.config) data.config = {}; if(fields[key].fields) { fields[key].fields.forEach(field => { if(!data.config[path]) data.config[path] = {}; const prop = Object.keys(field)[0]; data.config[path][Object.keys(field)[0]] = _.get(field, `${prop}.value`); }) }else{ if(fields[key].value !== "" && fields[key].value !== null && fields[key].value !== 'undefined' && fields[key].value !== undefined) { data.config[path] = fields[key].value; } } } }); } var handlers = { common : function(data,success,error) { PluginsService.add(data) .then(function(resp){ success(resp); }).catch(function(err){ error(err); }); }, ssl : function(data, success,error,event) { var files = []; files.push(data['config.cert']) files.push(data['config.key']) Upload.upload({ url: 'kong/plugins', arrayKey: '', data: { file: files, 'name' : data.name, 'config.only_https': data['config.only_https'], 'config.accept_http_if_already_terminated': data['config.accept_http_if_already_terminated'] } }).then(function (resp) { success(resp) }, function (err) { error(err) }, function (evt) { event(evt) }); } } return { addPlugin : function(data, success,error,event) { if(handlers[data.name]) { return handlers[data.name](data, success,error,event); }else{ return handlers['common'](data, success,error,event); } }, createConfigProperties : function(pluginName,fields,prefix) { var output = {} createConfigProperties(pluginName,fields,prefix,output) return output; }, assignExtraProperties : function(_pluginName, options,fields,prefix) { return assignExtraProperties(_pluginName, options,fields,prefix) }, /** * Customize data fields for specified plugins if required by Konga's logic * @param pluginName * @param fields */ customizeDataFieldsForPlugin : function(pluginName,fields) { switch (pluginName) { case 'ssl': fields.cert.type = 'file' fields.key.type = 'file' break; } }, /** * Mutate request data for specified plugins if required by Konga's logic * @param request_data * @param fields */ applyMonkeyPatches : function(request_data,fields) { if(request_data.name === 'response-ratelimiting' && fields.limits.custom_fields) { //console.log("fields.limits.custom_fields",fields.limits.custom_fields) Object.keys(fields.limits.custom_fields) .forEach(function(key){ Object.keys(fields.limits.custom_fields[key]) .forEach(function(cf_key){ request_data['config.limits.' + key + '.' + cf_key] = fields.limits.custom_fields[key][cf_key].value }); }); } } }; } ]) ; }());
JavaScript
0.000001
@@ -2806,24 +2806,387 @@ // %7D%0A%0A + if (fields%5Bkey%5D.value instanceof Array%0A && fields%5Bkey%5D.elements.type === %22integer%22) %7B%0A fields%5Bkey%5D.value = fields%5Bkey%5D.value.map(function(value) %7B%0A return parseInt(value);%0A %7D);%0A %7D%0A %0A
f595cd344213dada6fa57dfa4961142e79d269c5
Add Array.prototype.find
pkg/lib/polyfills.js
pkg/lib/polyfills.js
/*jshint esversion: 6 */ /* * This file is part of Cockpit. * * Copyright (C) 2016 Red Hat, Inc. * * Cockpit is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * Cockpit is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Cockpit; If not, see <http://www.gnu.org/licenses/>. */ /** This file contains various polyfills and other compatibility hacks */ // for IE 11 if (!String.prototype.startsWith) { String.prototype.startsWith = function (searchString, position) { position = position || 0; return this.substr(position, searchString.length) === searchString; }; } if (!Array.prototype.findIndex) { Array.prototype.findIndex = function (predicate) { if (this === null) { throw new TypeError('Array.prototype.findIndex called on null or undefined'); } if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } var list = Object(this); var length = list.length >>> 0; var thisArg = arguments[1]; var value; for (var i = 0; i < length; i++) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return i; } } return -1; }; } // for IE 11 if (typeof Object.assign != 'function') { // Must be writable: true, enumerable: false, configurable: true Object.defineProperty(Object, "assign", { value: function assign(target, varArgs) { // .length of function is 2 'use strict'; if (target === null) { // TypeError if undefined or null throw new TypeError('Cannot convert undefined or null to object'); } var to = Object(target); for (var index = 1; index < arguments.length; index++) { var nextSource = arguments[index]; if (nextSource !== null) { // Skip over if undefined or null for (var nextKey in nextSource) { // Avoid bugs when hasOwnProperty is shadowed if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { to[nextKey] = nextSource[nextKey]; } } } } return to; }, writable: true, configurable: true }); }
JavaScript
0
@@ -2872,12 +2872,1535 @@ e%0A %7D);%0A%7D%0A +%0A// for IE 11%0A// https://tc39.github.io/ecma262/#sec-array.prototype.find%0Aif (!Array.prototype.find) %7B%0A Object.defineProperty(Array.prototype, 'find', %7B%0A value: function(predicate) %7B%0A // 1. Let O be ? ToObject(this value).%0A if (this === null) %7B%0A throw new TypeError('%22this%22 is null or not defined');%0A %7D%0A%0A var o = Object(this);%0A%0A // 2. Let len be ? ToLength(? Get(O, %22length%22)).%0A var len = o.length %3E%3E%3E 0;%0A%0A // 3. If IsCallable(predicate) is false, throw a TypeError exception.%0A if (typeof predicate !== 'function') %7B%0A throw new TypeError('predicate must be a function');%0A %7D%0A%0A // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.%0A var thisArg = arguments%5B1%5D;%0A%0A // 5. Let k be 0.%0A var k = 0;%0A%0A // 6. Repeat, while k %3C len%0A while (k %3C len) %7B%0A // a. Let Pk be ! ToString(k).%0A // b. Let kValue be ? Get(O, Pk).%0A // c. Let testResult be ToBoolean(? Call(predicate, T, %C2%AB kValue, k, O %C2%BB)).%0A // d. If testResult is true, return kValue.%0A var kValue = o%5Bk%5D;%0A if (predicate.call(thisArg, kValue, k, o)) %7B%0A return kValue;%0A %7D%0A // e. Increase k by 1.%0A k++;%0A %7D%0A%0A // 7. Return undefined.%0A return undefined;%0A %7D%0A %7D);%0A%7D%0A
7aaab79a044aef5d25e7617018c6fe259b6818d7
fix about open about only if found marked function -- issue TS287
extension.js
extension.js
/* Copyright (c) 2013-2016 The TagSpaces Authors. * Use of this source code is governed by the MIT license which can be found in the LICENSE.txt file. */ /* global define, Handlebars, isCordova */ define(function(require, exports, module) { "use strict"; var extensionTitle = "Grid"; // should be equal to the name in the bower.json var extensionID = "perspectiveGrid"; // ID must be equal to the directory name where the extension is located var extensionIcon = "fa fa-th"; // icon class from font awesome console.log("Loading " + extensionID); var TSCORE = require("tscore"); var extensionDirectory = TSCORE.Config.getExtensionPath() + "/" + extensionID; var UI; var extensionLoaded; function init() { console.log("Initializing perspective " + extensionID); extensionLoaded = new Promise(function(resolve, reject) { require([ extensionDirectory + '/perspectiveUI.js', "text!" + extensionDirectory + '/toolbar.html', "marked", "css!" + extensionDirectory + '/extension.css', ], function(extUI, toolbarTPL, marked) { var toolbarTemplate = Handlebars.compile(toolbarTPL); UI = new extUI.ExtUI(extensionID); UI.buildUI(toolbarTemplate); platformTuning(); if (isCordova) { TSCORE.reLayout(); } try { $('#' + extensionID + 'Container [data-i18n]').i18n(); $('#aboutExtensionModalGrid').on('show.bs.modal', function() { $.ajax({ url: extensionDirectory + '/README.md', type: 'GET' }) .done(function(mdData) { //console.log("DATA: " + mdData); if (typeof(marked) != 'undefined') { $("#aboutExtensionModalGrid .modal-body").html(marked(mdData)); } else { $("#aboutExtensionModalGrid .modal-body").html(mdData); console.warn("marked function not found"); } }) .fail(function(data) { console.warn("Loading file failed " + data); }); }); } catch (err) { console.log("Failed translating extension"); } resolve(true); }); }); } function platformTuning() { if (isCordova) { $("#" + extensionID + "IncludeSubDirsButton").hide(); $('#' + extensionID + 'AddFileButton').hide(); // TODO tmp disabled due not working binary saving } else if (isChrome) { $('#' + extensionID + 'AddFileButton').hide(); $('#' + extensionID + 'TagButton').hide(); $('#' + extensionID + 'CopyMoveButton').hide(); $('#' + extensionID + 'CreateDirectoryButton').hide(); } else if (isFirefox) { $('#' + extensionID + 'AddFileButton').hide(); // Current impl has 0.5mb limit } } function load() { console.log("Loading perspective " + extensionID); extensionLoaded.then(function() { UI.reInit(); }, function(err) { console.warn("Loading extension failed: " + err); }); } function clearSelectedFiles() { if (UI) { UI.clearSelectedFiles(); UI.handleElementActivation(); } } function removeFileUI(filePath) { UI.removeFileUI(filePath); } function updateFileUI(oldFilePath, newFilePath) { UI.updateFileUI(oldFilePath, newFilePath); } function getNextFile(filePath) { return UI.getNextFile(filePath); } function getPrevFile(filePath) { return UI.getPrevFile(filePath); } function updateTreeData(fsTreeData) { console.log("Updating tree data not implemented"); } // API Vars exports.Title = extensionTitle; exports.ID = extensionID; exports.Icon = extensionIcon; // API Methods exports.init = init; exports.load = load; exports.clearSelectedFiles = clearSelectedFiles; exports.getNextFile = getNextFile; exports.getPrevFile = getPrevFile; exports.removeFileUI = removeFileUI; exports.updateFileUI = updateFileUI; exports.updateTreeData = updateTreeData; });
JavaScript
0
@@ -1730,37 +1730,14 @@ if ( -typeof(marked) != 'undefined' +marked ) %7B%0A @@ -1838,17 +1838,16 @@ %7D else %7B -%0A @@ -1858,63 +1858,8 @@ -$(%22#aboutExtensionModalGrid .modal-body%22).html(mdData); %0A
4457936b892dc622030f22d70935a69456aa3eb6
Fix typo in tests
tests/mammoth.tests.js
tests/mammoth.tests.js
var assert = require("assert"); var path = require("path"); var mammoth = require("../"); var testing = require("./testing"); var test = testing.test; var testData = testing.testData; var createFakeDocxFile = testing.createFakeDocxFile; describe('mammoth', function() { test('should convert docx containing one paragraph to single p element', function() { var docxPath = path.join(__dirname, "test-data/single-paragraph.docx"); return mammoth.convertToHtml({path: docxPath}).then(function(result) { assert.equal(result.value, "<p>Walking on imported air</p>"); assert.deepEqual(result.messages, []); }); }); test('style map can be expressed as string', function() { var docxFile = createFakeDocxFile({ "word/document.xml": testData("simple/word/document.xml") }); var options = { styleMap: "p => h1" }; return mammoth.convertToHtml({file: docxFile}, options).then(function(result) { assert.equal("<h1>Hello.</h1>", result.value); }); }); test('style map can be expressed as array of style mappings', function() { var docxFile = createFakeDocxFile({ "word/document.xml": testData("simple/word/document.xml") }); var options = { styleMap: ["p => h1"] }; return mammoth.convertToHtml({file: docxFile}, options).then(function(result) { assert.equal("<h1>Hello.</h1>", result.value); }); }); test('options are passed to document converter when calling mammoth.convertToHtml', function() { var docxFile = createFakeDocxFile({ "word/document.xml": testData("simple/word/document.xml") }); var options = { styleMap: "p => h1" }; return mammoth.convertToHtml({file: docxFile}, options).then(function(result) { assert.equal("<h1>Hello.</h1>", result.value); }); }); test('options.transformDocument is used to transform document if set', function() { var docxFile = createFakeDocxFile({ "word/document.xml": testData("simple/word/document.xml") }); var options = { transformDocument: function(document) { document.children[0].styleId = "Heading1"; return document; } }; return mammoth.convertToHtml({file: docxFile}, options).then(function(result) { assert.equal("<h1>Hello.</h1>", result.value); }); }); test('inline images are included in output', function() { var docxPath = path.join(__dirname, "test-data/tiny-picture.docx"); return mammoth.convertToHtml({path: docxPath}).then(function(result) { assert.equal(result.value, '<p><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAIAAAACUFjqAAAAAXNSR0IArs4c6QAAAAlwSFlzAAAOvgAADr4B6kKxwAAAABNJREFUKFNj/M+ADzDhlWUYqdIAQSwBE8U+X40AAAAASUVORK5CYII=" /></p>'); }); }); test('src of inline images can be changed', function() { var docxPath = path.join(__dirname, "test-data/tiny-picture.docx"); var convertImage = mammoth.images.inline(function(element) { return element.read("base64").then(function(encodedImage) { return {src: encodedImage.substring(0, 2) + "," + element.contentType}; }); }); return mammoth.convertToHtml({path: docxPath}, {convertImage: convertImage}).then(function(result) { assert.equal(result.value, '<p><img src="iV,image/png" /></p>'); }); }); test('simple list is converted to list elements', function() { var docxPath = path.join(__dirname, "test-data/simple-list.docx"); return mammoth.convertToHtml({path: docxPath}).then(function(result) { assert.equal(result.value, '<ul><li>Apple</li><li>Banana</li></ul>'); }); }); test('word tables are converted to html tables', function() { var docxPath = path.join(__dirname, "test-data/tables.docx"); return mammoth.convertToHtml({path: docxPath}).then(function(result) { var expectedHtml = "<p>Above</p>" + "<table>" + "<tr><td><p>Top left</p></td><td><p>Top right</p></td></tr>" + "<tr><td><p>Bottom left</p></td><td><p>Bottom right</p></td></tr>" + "</table>" + "<p>Below</p>"; assert.equal(result.value, expectedHtml); assert.deepEqual(result.messages, []); }); }); test('footnotes are appended to text', function() { // TODO: don't duplicate footnotes with multiple references var docxPath = path.join(__dirname, "test-data/footnotes.docx"); var options = { generateUniquifier: function() { return 42; } }; return mammoth.convertToHtml({path: docxPath}, options).then(function(result) { var expectedOutput = '<p>Ouch' + '<sup><a href="#footnote-42-1" id="footnote-ref-42-1">[1]</a></sup>.' + '<sup><a href="#footnote-42-2" id="footnote-ref-42-2">[2]</a></sup></p>' + '<ol><li id="footnote-42-1"><p> A tachyon walks into a bar. <a href="#footnote-ref-42-1">↑</a></p></li>' + '<li id="footnote-42-2"><p> Fin. <a href="#footnote-ref-42-2">↑</a></p></li></ol>'; assert.equal(result.value, expectedOutput); // TODO: get rid of warnings //~ assert.deepEqual(result.messages, []); }); }); test('indentation is used if prettyPrint is true', function() { var docxPath = path.join(__dirname, "test-data/single-paragraph.docx"); return mammoth.convertToHtml({path: docxPath}, {prettyPrint: true}).then(function(result) { assert.equal(result.value, "<p>\n Walking on imported air\n</p>"); assert.deepEqual(result.messages, []); }); }); test('using styleMapping throws error', function() { try { mammoth.styleMapping(); } catch (error) { assert.equal( error.message, 'Use a raw string instead of mammoth.styleMapping e.g. "p[style-naming=\'Title\'] => h1" instead of mammoth.styleMapping("p[style-naming=\'Title\'] => h1")' ); } }); test('extractRawText only retains raw text', function() { var docxPath = path.join(__dirname, "test-data/simple-list.docx"); return mammoth.extractRawText({path: docxPath}).then(function(result) { assert.equal(result.value, 'Apple\n\nBanana\n\n'); }); }); });
JavaScript
0.000452
@@ -6311,35 +6311,33 @@ .g. %22p%5Bstyle-nam -ing +e =%5C'Title%5C'%5D =%3E h @@ -6383,19 +6383,17 @@ tyle-nam -ing +e =%5C'Title
9ddb1560effe97da78bfaffe77a0d7a6534a86fc
Fix typo.
grunt/bs-glyphicons-data-generator.js
grunt/bs-glyphicons-data-generator.js
/*! * Bootstrap Grunt task for Glyphicons data generation * http://getbootstrap.com * Copyright 2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ 'use strict'; var fs = require('fs'); module.exports = function generateGlyphiconsData() { // Pass encoding, utf8, so `readFileSync` will return a string instead of a // buffer var glyphiconsFile = fs.readFileSync('less/glyphicons.less', 'utf8'); var glpyhiconsLines = glyphiconsFile.split('\n'); // Use any line that starts with ".glyphicon-" and capture the class name var iconClassName = /^\.(glyphicon-[^\s]+)/; var glyphiconsData = '# This file is generated via Grunt task. **Do not edit directly.**\n' + '# See the \'build-glyphicons-data\' task in Gruntfile.js.\n\n'; for (var i = 0, len = glpyhiconsLines.length; i < len; i++) { var match = glpyhiconsLines[i].match(iconClassName); if (match !== null) { glyphiconsData += '- ' + match[1] + '\n'; } } // Create the `_data` directory if it doesn't already exist if (!fs.existsSync('docs/_data')) { fs.mkdirSync('docs/_data'); } fs.writeFileSync('docs/_data/glyphicons.yml', glyphiconsData); };
JavaScript
0.001604
@@ -455,18 +455,18 @@ var gl -p y +p hiconsLi @@ -829,26 +829,26 @@ 0, len = gl -p y +p hiconsLines. @@ -889,18 +889,18 @@ tch = gl -p y +p hiconsLi
47389f615f343a4afc8cb820d745cf07bf913502
fix lint
renderer/containers/Settings.js
renderer/containers/Settings.js
import React, { Component } from 'react' import { connect } from 'react-redux' import { remote } from 'electron' import { copyFileSync, removeSync, existsSync } from 'fs-plus' import path from 'path' import { updateSettings, loadTodos } from '../actions' import Header from '../components/Header' const dialog = remote.dialog const dialogOptions = { title: 'Select todoo.json directory', properties: ['openDirectory'] } const style = { aboutBlock: { lineHeight: '1.8rem' }, block: { color: '#999' }, link: { color: '#dcdcdc' }, input: { outline: 'none', width: '90%', color: '#999', border: '1px solid #181a1f', backgroundColor: '#1b1d23' }, label: { fontSize: '1.1rem', color: '#fff' } } class Settings extends Component { constructor (props) { super(props) this.openDialog = this.openDialog.bind(this) } openDialog () { dialog.showOpenDialog(remote.getCurrentWindow(), dialogOptions, (filenames) => { if (!Array.isArray(filenames)) return try { if (existsSync(path.resolve(filenames[0], 'todoo.json'))) { const confirm = dialog.showMessageBox({ type: 'info', title: 'File already exists', message: 'todoo.json file already exists', detail: 'Do you want to overwrite it?', buttons: ['Yes', 'No'] }) if (confirm === 0) { console.log('overwriting existing file') copyFileSync(path.resolve(this.props.todooJsonDir, 'todoo.json'), path.resolve(filenames[0], 'todoo.json')) // removeSync(path.resolve(this.props.todooJsonDir, 'todoo.json')) } else { console.log('not overwriting existing file') // removeSync(path.resolve(this.props.todooJsonDir, 'todoo.json')) } } else { console.log('move the file to a new location') copyFileSync(path.resolve(this.props.todooJsonDir, 'todoo.json'), path.resolve(filenames[0], 'todoo.json')) // removeSync(path.resolve(this.props.todooJsonDir, 'todoo.json')) } this.props.dispatch(updateSettings({ todooJsonDir: filenames[0] })) this.props.dispatch(loadTodos()) } catch (e) { console.error(e) dialog.showErrorBox('Error', e.message || 'An error has occoured') } }) } render () { const { todooJsonDir, version, currentPage, dispatch } = this.props return ( <div className='mw7 center'> <Header currentPage={currentPage} dispatch={dispatch} /> <div> <div className='pa2 pb3' style={style.block}> <label className='pr2 pt2 pb3 dib' htmlFor='todooJsonDir' style={style.label} > Relocate todoo.json in a different directory </label> <div className='df flx-aic'> <input className='db pa2' style={style.input} type='text' readOnly='readonly' id='todooJsonDir' onClick={this.openDialog} value={todooJsonDir} /> <button onClick={this.openDialog} className='task-item__button' type='button' key='bs'> <svg className='icon' fill='#000000' height='24' viewBox='0 0 24 24' width='24'> <path d='M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 12H4V8h16v10z' /> </svg> </button> </div> </div> <div className='pa2 pb3' style={style.block}> <label className='pr2 pt2 pb3 dib' htmlFor='shortcut' style={style.label} > Global shortcut </label> <div className='df flx-aic'> <input className='db pa2' style={style.input} type='text' disabled='disabled' id='shortcut' value={this.props.shortcut} /> </div> </div> <div className='pa2 pb3' style={style.block}> <label className='pr2 pt2 pb3 dib' style={style.label} > About </label> <div className='pt2'> <div style={style.aboutBlock}> Version {version} </div> <div style={style.aboutBlock}> MIT Licensed Copyright (c) 2016-present <a style={style.link} href='http://alessandro.arnodo.net/'>Alessandro Arnodo</a> </div> <div style={style.aboutBlock}> Follow me on twitter <a style={style.link} href='https://twitter.com/vesparny'>@vesparny</a> </div> <div style={style.aboutBlock}> Code available on <a style={style.link} href='https://github.com/vesparny/todoo'>GitHub</a> </div> <div style={style.aboutBlock}> Share on <a style={style.link} href='https://twitter.com/intent/tweet?original_referer=https%3A%2F%2Fpublish.twitter.com%2F&ref_src=twsrc%5Etfw&related=vesparny&text=Todoo%20-%20Open%20Source%20Todo%20app%20for%20introverts%20-%20Built%20with%20%40electronjs%20and%20%40reactjs%20%20&tw_p=tweetbutton&url=https%3A%2F%2Fgithub.com%2Fvesparny%2Ftodoo&via=vesparny'>Twitter</a> </div> </div> </div> </div> </div> ) } } const selector = (state) => state.settings export default connect(selector)(Settings)
JavaScript
0.000048
@@ -132,20 +132,8 @@ ync, - removeSync, exi
3267a23dc74bd3d6d72aa3d5de5f2365965d890c
Configure leaflet as a path, not a package, since it's a module-is-a-package kind of package.
sagan-js/dev/run.js
sagan-js/dev/run.js
var Munchkin, baseUrl; // pre-existing globals (function () { var cjsConfig = { loader: 'curl/loader/cjsm11' }; curl.config({ baseUrl: baseUrl, packages: { app: { location: 'app', config: cjsConfig, main: 'main' }, feature: { location: 'feature', config: cjsConfig }, component: { location: 'component', config: cjsConfig }, platform: { location: 'platform', config: cjsConfig }, curl: { location: 'lib/curl/src/curl/' }, when: { location: 'lib/when', main: 'when' }, most: { location: 'lib/most', main: 'most', config: cjsConfig }, poly: { location: 'lib/poly' }, leaflet: { location: 'lib/leaflet', main: 'dist/leaflet-src', config: cjsConfig } }, paths: { ZeroClipboard: 'lib/zeroclipboard/ZeroClipboard', jquery: 'lib/jquery/jquery.min', 'prettify': 'lib/google-code-prettify/src/prettify', bootstrap: { // FIXME: Find a better way to pull in bootstrap dependency // For now, load bootstrap from sagan-site, since pulling it in via // bower pulls the sources, and NOT the built .min.js file that we need location: 'lib/bootstrap/js/bootstrap', config: { loader: 'curl/loader/legacy', requires: [ 'jquery' ], // there is no global `bootstrap` var anywhere? exports: '$.fn.tooltip' } }, 'bootstrap-datetimepicker': { location: 'lib/bootstrap-datetimepicker/src/js/bootstrap-datetimepicker', config: { loader: 'curl/loader/legacy', requires: [ 'bootstrap' ], exports: '$.fn.datetimepicker' } }, 'jquery-migrate': { location: '//code.jquery.com/jquery-migrate-1.2.1', config: { loader: 'curl/loader/legacy', requires: [ 'jquery' ], exports: '$.migrateWarnings' } }, munchkin: { location: '//munchkin.marketo.net/munchkin', config: { loader: 'curl/loader/legacy', requires: [ 'jquery', 'jquery-migrate' ], factory: function() { Munchkin.init('625-IUJ-009'); return Munchkin; } } } }, preloads: ['poly/es5'] }); // Can't document this in bower.json, so I'm documenting it here: // munchkin.js has a bug that incorrectly detects jquery 1.10.x as // being 1.1.x, below its required 1.3.x. It proceeds to download jquery // 1.7.1 ("jquery-latest") which overwrites any existing jquery in // curl.js's cache. The newer jquery doesn't have any plugins // registered, so calls to $().tooltip, etc. fail. // To fix this, the bower.json cannot specify anything over ~1.9. However, // munchkin has another bug: it uses an obsolete feature: $.browser. // This was deprecated as of 1.3.0 and removed in 1.9.0, but is still // used in munchkin.js. Therefore, we must use the jquery-migrate plugin. // Also: I'm ensuring munchkin.js gets loaded last! curl(['app', 'jquery']).then(start, fail); function start(main, $) { // tell the jquery migrate plugin to be quiet $.migrateMute = true; // load munchkin once our page is loaded curl(['munchkin']); } function fail(ex) { // TODO: show a meaningful error to the user. //document.location.href = '/500'; throw ex; } }());
JavaScript
0
@@ -165,16 +165,22 @@ baseUrl + %7C%7C '' ,%0A @@ -696,17 +696,44 @@ /poly' %7D -, +%0A %7D,%0A paths: %7B %0A @@ -770,26 +770,17 @@ /leaflet -', main: ' +/ dist/lea @@ -813,36 +813,9 @@ ig %7D -%0A %7D,%0A paths: %7B +, %0A
6a4236bc5f465a12bd7dd5ea3104988e381583cd
Update BoundsArraySet.js
CNN/Conv/BoundsArraySet.js
CNN/Conv/BoundsArraySet.js
export { InputsOutputs } from "./BoundsArraySet/BoundsArraySet_InputsOutputs.js"; export { ConvBiasActivation } from "./BoundsArraySet/BoundsArraySet_ConvBiasActivation.js"; export { Pointwise } from "./BoundsArraySet/BoundsArraySet_Pointwise.js"; export { Depthwise } from "./BoundsArraySet/BoundsArraySet_Depthwise.js";
JavaScript
0
@@ -71,24 +71,110 @@ utputs.js%22;%0A +export %7B InputsOutputsPool %7D from %22./BoundsArraySet/BoundsArraySet_InputsOutputs.js%22;%0A export %7B Con @@ -266,91 +266,343 @@ t %7B -Pointwise %7D from %22./BoundsArraySet/BoundsArraySet_Pointwise.js%22;%0Aexport %7B Depthwise +ConvBiasActivationPool %7D from %22./BoundsArraySet/BoundsArraySet_ConvBiasActivation.js%22;%0Aexport %7B Pointwise %7D from %22./BoundsArraySet/BoundsArraySet_Pointwise.js%22;%0Aexport %7B PointwisePool %7D from %22./BoundsArraySet/BoundsArraySet_Pointwise.js%22;%0Aexport %7B Depthwise %7D from %22./BoundsArraySet/BoundsArraySet_Depthwise.js%22;%0Aexport %7B DepthwisePool %7D f
79132b44497e4d31f097c32ffb27efa97875beb0
Remove console.log on report again
packages/test-in-phantom/reporter.js
packages/test-in-phantom/reporter.js
Meteor.methods({ report: function (url, reports) { console.log("reporting to ", url); Meteor.http.post(url, { data: reports }); return null; } });
JavaScript
0
@@ -50,47 +50,8 @@ ) %7B%0A - console.log(%22reporting to %22, url);%0A
baf5018439a0773b15bff5c8f9a2b792a0915dd1
Fix the multi-generation issue.
src-script/zap-generate.js
src-script/zap-generate.js
#!/usr/bin/env node /** * * Copyright (c) 2020 Silicon Labs * * 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. */ const yargs = require('yargs') const scriptUtil = require('./script-util.js') let startTime = process.hrtime() let arg = yargs .option('zcl', { desc: 'Specifies zcl metafile file to be used.', alias: 'z', type: 'string', demandOption: true, }) .option('out', { desc: 'Output directory where the generated files will go.', alias: 'o', type: 'string', demandOption: true, }) .option('generationTemplate', { desc: 'Specifies gen-template.json file to be used.', alias: 'g', type: 'string', demandOption: true, }) .option('in', { desc: 'Input .zap file from which to read configuration.', alias: 'i', type: 'string', demandOption: false, }) .option('stateDirectory', { desc: 'State directory', type: 'string', demandOption: false, default: '~/.zap', }) .demandOption( ['zcl', 'out', 'generationTemplate'], 'Please provide required options!' ) .help() .wrap(null).argv let ctx = {} let cli = [ 'src-electron/main-process/electron-main.js', 'generate', '--noUi', '--reuseZapInstance', '--zcl', arg.zcl, '--generationTemplate', arg.generationTemplate, '--out', arg.out, ] if (arg.in != null) { cli.push(arg.in) } scriptUtil .stampVersion() .then(() => scriptUtil.executeCmd(ctx, 'electron', cli)) .then(() => { let endTime = process.hrtime(startTime) console.log( `😎 All done: ${endTime[0]}s, ${Math.round(endTime[1] / 1000000)}ms.` ) process.exit(0) }) .catch((code) => { process.exit(code) })
JavaScript
0.000008
@@ -1735,32 +1735,8 @@ i',%0A - '--reuseZapInstance',%0A '- @@ -1944,24 +1944,20 @@ d(ctx, ' -electron +node ', cli))
ceb0513b01b4b2cfcca727379fd7e80b30349b5c
correct model freshness to work from indicator
packages/ui/src/state/ducks/fryer.js
packages/ui/src/state/ducks/fryer.js
// TODO: Move state to somewhere more appropriate import mapValues from 'lodash/mapValues' export const FRYER_CONNECTED = 'FRYER_CONNECTED' export const connected = () => ({ payload: null, type: FRYER_CONNECTED }) export const FRYER_DISCONNECTED = 'FRYER_DISCONNECTED' export const disconnected = () => ({ payload: null, type: FRYER_DISCONNECTED }) export const FRYER_ADD_DONUTS = 'FRYER_ADD_DONUTS' export const addDonuts = (donuts) => ({ payload: donuts, type: FRYER_ADD_DONUTS }) export const FRYER_ADD_ERROR = 'FRYER_ADD_ERROR' export const addError = (error) => ({ payload: error, type: FRYER_ADD_ERROR }) export const FRYER_REMOVE_ERROR = 'FRYER_REMOVE_ERROR' export const removeError = (index) => ({ payload: index, type: FRYER_REMOVE_ERROR }) export const FRYER_SET_MODELS = 'FRYER_SET_MODELS' export const setModels = (models) => ({ payload: models, type: FRYER_SET_MODELS }) const initialState = { connected: false, donuts: [], errors: [], models: null } export default function reducer (state = initialState, { payload, type }) { switch (type) { case FRYER_CONNECTED: return { ...state, connected: true } case FRYER_DISCONNECTED: return { ...state, connected: false } case FRYER_REMOVE_ERROR: return { ...state, errors: state.errors.filter((e, index) => index !== payload) } case FRYER_ADD_ERROR: return { ...state, errors: [...state.errors, payload] } case FRYER_ADD_DONUTS: return { ...state, donuts: payload } case FRYER_SET_MODELS: return { ...state, models: mapValues(payload, (model, name) => { const oldModel = state.models && state.models[name] // Only use a model if it's better than its previous iteration return !oldModel || model.score > oldModel.score ? model : oldModel }) } default: return state } }
JavaScript
0
@@ -83,16 +83,70 @@ pValues' +%0Aimport %7B getIndicator %7D from 'donut-common/src/rater' %0A%0Aexport @@ -1963,22 +1963,50 @@ %7C%7C -model.score %3E +(getIndicator(model.donut) %3E getIndicator( oldM @@ -2014,13 +2014,15 @@ del. -score +donut)) %0A
646abd0d74e936c48d577a013190d1e9ca2700f8
fix typo
src/client/modules/startup.js
src/client/modules/startup.js
/*global require*/ /*jslint white:true*/ require(['require-config'], function() { 'use strict'; require(['app/main'], function (main) { main.start() .catch(function (err) { document.getElementById('root').innerHTML = 'Error starting KBase UI. Please consult the browser error log.'; console.error('app is unhappy :('); console.errro(err); }); }); });
JavaScript
0.999991
@@ -399,18 +399,18 @@ sole.err -r o +r (err);%0A