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
b71174fa92deba71aa769b08d3afae62b000a7d7
add url-loader for png/jpg files
build/webpack/_base.js
build/webpack/_base.js
import webpack from 'webpack'; import cssnano from 'cssnano'; import HtmlWebpackPlugin from 'html-webpack-plugin'; import config from '../../config'; const paths = config.utils_paths; const debug = require('debug')('kit:webpack:_base'); debug('Create configuration.'); const CSS_MODULES_LOADER = [ 'css-loader?modules', 'sourceMap', 'importLoaders=1', 'localIdentName=[name]__[local]___[hash:base64:5]' ].join('&'); const webpackConfig = { name : 'client', target : 'web', entry : { app : [ paths.base(config.dir_client) + '/app.js' ], vendor : config.compiler_vendor }, output : { filename : `[name].[${config.compiler_hash_type}].js`, path : paths.base(config.dir_dist), publicPath : '/' }, plugins : [ new webpack.DefinePlugin(config.globals), new webpack.optimize.OccurrenceOrderPlugin(), new webpack.optimize.DedupePlugin(), new HtmlWebpackPlugin({ template : paths.client('index.html'), hash : false, filename : 'index.html', inject : 'body', minify : { collapseWhitespace : true } }) ], resolve : { extensions : ['', '.js', '.jsx'], alias : config.utils_aliases }, module : { loaders : [ { test : /\.(js|jsx)$/, exclude : /node_modules/, loader : 'babel', query : { stage : 0, optional : ['runtime'], env : { development : { plugins : ['react-transform'], extra : { 'react-transform' : { transforms : [{ transform : 'react-transform-catch-errors', imports : ['react', 'redbox-react'] }] } } } } } }, { test : /\.scss$/, loaders : [ 'style-loader', CSS_MODULES_LOADER, 'postcss-loader', 'sass-loader' ] }, { test : /\.css$/, loaders : [ 'style-loader', CSS_MODULES_LOADER ] }, /* eslint-disable */ { test: /\.woff(\?.*)?$/, loader: "url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff" }, { test: /\.woff2(\?.*)?$/, loader: "url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2" }, { test: /\.ttf(\?.*)?$/, loader: "url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream" }, { test: /\.eot(\?.*)?$/, loader: "file-loader?prefix=fonts/&name=[path][name].[ext]" }, { test: /\.svg(\?.*)?$/, loader: "url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml" } /* eslint-enable */ ] }, sassLoader : { includePaths : paths.client('styles') }, postcss : [ cssnano({ sourcemap : true, autoprefixer : { add : true, remove : true, browsers : ['last 2 versions'] }, discardComments : { removeAll : true } }) ] }; // NOTE: this is a temporary workaround. I don't know how to get Karma // to include the vendor bundle that webpack creates, so to get around that // we remove the bundle splitting when webpack is used with Karma. const commonChunkPlugin = new webpack.optimize.CommonsChunkPlugin({ names : ['vendor', 'manifest'] }); commonChunkPlugin.__KARMA_IGNORE__ = true; webpackConfig.plugins.push(commonChunkPlugin); export default webpackConfig;
JavaScript
0.000001
@@ -2860,16 +2860,84 @@ svg+xml%22 + %7D,%0A %7B test: /%5C.(png%7Cjpg)$/, loader: 'url-loader?limit=8192' %7D%0A
89ed4deb234ec9892ebcc674af04be0f2f64bc75
Create index.js
www/js/index.js
www/js/index.js
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var app = { // Application Constructor initialize: function() { this.bindEvents(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicitly call 'app.receivedEvent(...);' onDeviceReady: function() { window.open("http://kraftstoffbilliger.de/m3/", '_self', 'toolbar=no,location=no'); admob.setOptions({publisherId: "ca-app-pub-3940256099942544/6300978111", adSize: admob.AD_SIZE.SMART_BANNER, bannerAtTop: false, isTesting: true, autoShowBanner: true }); admob.createBannerView(); app.receivedEvent('deviceready'); }, // Update DOM on a Received Event receivedEvent: function(id) { var parentElement = document.getElementById(id); var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received'); listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;'); } };
JavaScript
0.000002
@@ -1401,16 +1401,18 @@ ) %7B%0A +// window.o @@ -1489,24 +1489,85 @@ no'); %0A + window.location.href=%22http://kraftstoffbilliger.de/m3/%22;%0A admob.se
ac1dc5303c563fb82870f8a93e2690b02fab2ca6
Add logic for adding datebox to time formated records
www/js/index.js
www/js/index.js
var post = function(action, data){ return new Promise(function(resolve, reject){ console.log("About to make a post call - "); console.log(action); console.log(data); var request = $.post(action, data); request.done(function(serverData){ resolve(serverData) }); request.fail(function(serverData){ reject(serverData) }); }); } var get = function(action, data){ return new Promise(function(resolve, reject){ console.log("About to make a get call - "); console.log(action); console.log(data); var request = $.get(action, data); request.done(function(serverData){ resolve(serverData) }); request.fail(function(serverData){ reject(serverData) }); }); } var view = { goTo: function(contentId){ $(":mobile-pagecontainer").pagecontainer("change", contentId); }, errorMessage: function(errorTarget, message){ $(errorTarget).text("There was an error signing in. " + message); }, loginUser: function(){ this.updatePersonalInfo(); this.goTo('#cardsPage'); }, logoutUser: function(){ this.goTo('#loginPage'); }, updatePersonalInfo: function(){ var name = localStorage.getItem("u_first_name"); name += " " + localStorage.getItem("u_last_name"); $(".uName").text(name); $(".uSchoolName").text(localStorage.getItem('u_school_name')); }, showObservation: function(observations){ observation = observations[0]; $('#emptyNotice').hide(); this.updateNickname(observation); this.updateObservationForm(observation); $('#date').datebox({ mode: "calbox" }); }, updateNickname: function(observation){ var student = observation[2]; var nickname = student['nickname']; $("#sAlias").text(nickname); }, updateObservationForm: function(observation){ var record_inputs = this.makeRecordInputs(observation[1]); $('#observationRecordsForm').prepend($(record_inputs)); $('#observationRecordsForm').trigger('create'); }, makeRecordInputs: function(records){ var inputs = '<input type="text" id="date" />' $.each(records, function(index, record){ input = '<label for="record_' + record["id"] + '">' + record["prompt"] + '</label>' input += '<input name="' + record["id"] + '" type="text" placeholder="10" />'; inputs += input; }); return inputs; } } var app = { initialize: function() { this.bindEvents(); }, bindEvents: function() { $("#loginForm").submit(this.submitLoginForm); $("#logoutLink").click(this.handleLogOut); }, handleLogOut: function(){ localStorage.removeItem("uid"); localStorage.removeItem("utoken"); view.logoutUser(); }, getObservations: function(user_id, authenticity_token){ var data = "user_id=" + user_id + "&authenticity_token=" + authenticity_token; get('http://localhost:3000/api/v1/observations?' + data) .then(function(serverData){ localStorage.setItem("observations", serverData); view.showObservation(serverData); }) .catch(function(serverData){ console.log('error'); console.log(serverData.responseText) }); }, submitLoginForm: function(){ var data = $("#loginForm").serialize(); post('http://localhost:3000/api/v1/login', data) .then(function(serverData){ localStorage.setItem("uid", serverData.id); localStorage.setItem("utoken", serverData.token); localStorage.setItem("u_first_name", serverData.first_name); localStorage.setItem("u_last_name", serverData.last_name); localStorage.setItem("u_school_name", serverData.school_name); app.getObservations(serverData.id, serverData.token); view.loginUser(); }) .catch(function(serverData){ view.errorMessage('#loginError', serverData.responseText); }); return false; } };
JavaScript
0
@@ -1577,12 +1577,12 @@ $(' -#dat +.tim e'). @@ -1610,14 +1610,111 @@ e: %22 -calbox +durationflipbox%22,%0A overrideDurationOrder:%5B%22h%22,%22i%22,%22s%22%5D,%0A overrideDurationFormat: %22%25DM:%25DS %22%0A @@ -2144,17 +2144,16 @@ cords)%7B%0A -%0A var @@ -2166,40 +2166,10 @@ = ' -%3Cinput type=%22text%22 id=%22date%22 /%3E ' +; %0A @@ -2286,16 +2286,17 @@ prompt%22%5D + + '%3C/la @@ -2301,16 +2301,54 @@ label%3E'%0A + if(record%5B%22meme%22%5D == %22Time%22)%7B%0A in @@ -2423,12 +2423,135 @@ 10%22 -/%3E'; +class=%22time%22 /%3E';%0A %7D else %7B%0A input += '%3Cinput name=%22' + record%5B%22id%22%5D + '%22 type=%22text%22 placeholder=%2210%22 /%3E';%0A %7D %0A
fd6b4a4af9af234e9ec47ce230b5d888df1afc1e
remove json filetype
www/js/login.js
www/js/login.js
function checkCookie(){ if(localStorage.getItem('user_id') != "" && localStorage.getItem('user_id') != null){ window.location = ('pages/main.html'); } } $("button#submit").click( function() { if( $("#username").val() == "" || $("#password").val() == "" ) $("div#loginmsg").html('<font color="red">Vennligst skriv brukernavn og passord'); else $.post( $("#loginform").attr("action"), $("#loginform :input").serializeArray(), function(data) { $("div#loginmsg").html(data); /*var returnStr = data; if(isUser_id(returnStr)){ localStorage.setItem('user_id', returnStr); checkCookie(); } else{ $("div#loginmsg").html(data); }*/ },'json'); $("#loginform").submit( function() { return false; }); }); function isUser_id(string){ return (string != "false"); }
JavaScript
0.00002
@@ -706,15 +706,8 @@ %09%09%09%7D -,'json' );%0A
86dbf911764ec44141fd3d9c5924b2221ee634ad
Update myapp.js
www/js/myapp.js
www/js/myapp.js
var app = angular.module('myApp', []); app.controller('formHide', function($scope){ $scope.buy = true; var storedData = myApp.formGetData('buyform'); if (storedData){ $scope.metreName = storedData.metreName; $scope.metre = storedData.metre;} $scope.switcher = true; $scope.regswitcher = true; $scope.changebtn = function(){ if (($$("#select-metre").val() !== "") &&($$("#amt").val() !== "")){ $scope.switcher = false; } else { $scope.switcher = true; } } $scope.regchangebtn = function(){ if (($$("#metre").val() !== "") && ($$("#metreName").val() !== "")){ $scope.regswitcher = false; } else { $scope.regswitcher = true; } } $scope.cancelbtn = function(){ $$("#metre").val(parseInt('')).trigger('change'); $$("#metreName").val('').trigger('change'); $scope.reg = false; $scope.buy = true; loadOptions(); $$('#regFab').html('&nbsp New<i class="icon icon-plus"></i>'); } $scope.savebtn = function(){ metreNumber = $$("#metre").val(); metreName = $$("#metreName").val(); db.transaction(function(tx) {tx.executeSql('INSERT INTO metreNumbers values(' + metreNumber +',"'+ metreName + '")');}, function(err) {alert ('failed'+err.code+ 'because'+ err.message);}, function(){}); $scope.reg = false; $scope.buy = true; myApp.formDeleteData('buyform'); loadOptions(); $scope.metreName = ''; $scope.metre = ''; $$('#regFab').html('&nbsp New<i class="icon icon-plus"></i>'); } $scope.openForm = function(){ if ($scope.buy == true){ $$('#regFab').html('buy'); $scope.buy = false; $scope.reg = true; $$(".reg").removeClass("regdisappear"); $scope.regchangebtn(); loadSavedTables(); } else{ $$('#regFab').html('&nbsp New<i class="icon icon-plus"></i>'); $$("#amt").val(parseInt('')).trigger('change'); $scope.reg = false; $scope.buy = true; loadOptions(); } } $scope.editbtn = function(){ metreNumber = $$("#metre").val(); metreName = $$("#metreName").val(); db.transaction(function(tx) {tx.executeSql('UPDATE metreNumbers SET metreNumber =' + metreNumber +', metreName = "'+ metreName + '" where metreNumber ='+id);}, function(err) {alert ('failed'+err.code+ 'because'+ err.message);}, function(){}); myApp.formDeleteData('buyform'); $$("#metre").val('').trigger('change'); $$("#metreName").val('').trigger('change'); loadSavedTables(); $$('#editbutton').hide(); $$('#savebutton').show(); } $scope.buyZESA = function(){ amt = $$("#amt").val(); metreNumber = $$("#select-metre").val(); ussdnum = "*151*2*6*1*1*"+amt+"*"+metreNumber+"#"; $scope.dialNum(ussdnum); } $scope.dialNum = function(ussdnum){ window.plugins.CallNumber.callNumber(onSuccess, onError, ussdnum, false); function onSuccess(result){ $$("#amt").val('').trigger('change'); } function onError(result) { $$("#amt").val('').trigger('change'); console.log("Error:"+result); alert ('sorry failed to purchase token this is because '+result); } } }); $$('.totop').on('click', function(){ $$(".page-content").scrollTop(0); });
JavaScript
0.000002
@@ -2441,16 +2441,113 @@ tion()%7B%0A +%09%09if (currentCarrier == %22ECONET%22)%0A%09%09%09alert('ecocash');%0A%09%09else%0A%09%09%09alert('telecash or onewallet');%0A %09%09amt = @@ -3122,12 +3122,13 @@ lTop(0);%0A%7D); +%0A
d5ccf40bc135e478dab9442f0c589cfc1b57a9ef
Update myapp.js
www/js/myapp.js
www/js/myapp.js
var app = angular.module('myApp', []); app.controller('formHide', function($scope){ $scope.buy = true; var storedData = myApp.formGetData('buyform'); if (storedData){ $scope.metreName = storedData.metreName; $scope.metre = storedData.metre;} $scope.switcher = true; $scope.regswitcher = true; $scope.changebtn = function(){ if (($$("#select-metre").val() !== "") &&($$("#amt").val() !== "")){ $scope.switcher = false; } else { $scope.switcher = true; } } $scope.regchangebtn = function(){ if (($$("#metre").val() !== "") && ($$("#metreName").val() !== "")){ $scope.regswitcher = false; } else { $scope.regswitcher = true; } } $scope.cancelbtn = function(){ $$("#metre").val(parseInt('')).trigger('change'); $$("#metreName").val('').trigger('change'); $scope.reg = false; $scope.buy = true; loadOptions(); $$('#regFab').html('&nbsp New<i class="icon icon-plus"></i>'); } $scope.savebtn = function(){ metreNumber = $$("#metre").val(); metreName = $$("#metreName").val(); db.transaction(function(tx) {tx.executeSql('INSERT INTO metreNumbers values(' + metreNumber +',"'+ metreName + '")');}, function(err) {alert ('failed'+err.code+ 'because'+ err.message);}, function(){}); $scope.reg = false; $scope.buy = true; myApp.formDeleteData('buyform'); loadOptions(); $scope.metreName = ''; $scope.metre = ''; $$('#regFab').html('&nbsp New<i class="icon icon-plus"></i>'); } $scope.openForm = function(){ if ($scope.buy == true){ $$('#regFab').html('buy'); $scope.buy = false; $scope.reg = true; $$(".reg").removeClass("regdisappear"); $scope.regchangebtn(); loadSavedTables(); } else{ $$('#regFab').html('&nbsp New<i class="icon icon-plus"></i>'); $scope.reg = false; $scope.buy = true; loadOptions(); } } $scope.editbtn = function(){ metreNumber = $$("#metre").val(); metreName = $$("#metreName").val(); db.transaction(function(tx) {tx.executeSql('UPDATE metreNumbers SET metreNumber =' + metreNumber +', metreName = "'+ metreName + '" where metreNumber ='+id);}, function(err) {alert ('failed'+err.code+ 'because'+ err.message);}, function(){}); myApp.formDeleteData('buyform'); $$("#metre").val(parseInt('')).trigger('change'); $$("#metreName").val('').trigger('change'); loadSavedTables(); $$('#editbutton').hide(); $$('#savebutton').show(); } $scope.dialNum = function(){ window.cordova.plugins.CallNumber.callNumber(onSuccess, onError, 0777155777, false); function onSuccess(result){ alert ('calling'); console.log("Success:"+result); } function onError(result) { console.log("Error:"+result); alert ('failed '+result); } } });
JavaScript
0.000002
@@ -2413,16 +2413,8 @@ dow. -cordova. plug
70c60cf5882a677acdb54d6dff639d5e07930e45
remove duplicate js
assets/js/custom.js
assets/js/custom.js
$(function(){ $('.entry-content a').attr('target','_blank'); var headers = $('#post .entry-content :header').map(function (idx, h){ var a = $('<a href="#">'); a.attr('data-id',h.id); a.attr('href', '#' + h.id); a.attr('class', h.nodeName.toLowerCase()); a.html( '<span>' + h.textContent) return $('<li>').append(a)[0].outerHTML; }).toArray().join(""); var menu = $('<div id="dl-headers" class=""><button class="dl-btn btn btn-success">Contents</button></div>'); $('#post').parents('body').append(menu.append($('<ul class="dl-headers" id="headers">').append(headers))); if($('#dl-headers .dl-btn').is(':visible')) { $('#dl-headers .dl-btn').on('click',function(){ $('ul#headers').slideToggle(); }) } $('#headers a').click(function (e){ e.preventDefault(); console.info("scrollTo #" + $(this).attr('data-id')); var selector = '#'+$(this).attr('data-id'); var top = $(selector).offset().top; $('body, html').animate({ scrollTop: top - 25 }, 500, 'swing'); }); /*Thanks to http://beiyuu.com/js/post.js*/ var waitForFinalEvent = (function () { var timers = {}; return function (callback, ms, uniqueId) { if (!uniqueId) { uniqueId = "Don't call this twice without a uniqueId"; } if (timers[uniqueId]) { clearTimeout (timers[uniqueId]); } timers[uniqueId] = setTimeout(callback, ms); }; })(); var scrollTop = []; $.each($('#headers li a'),function(index,item){ var selector = $(item).attr('data-id') ? '#'+$(item).attr('data-id') : 'h1' var top = $(selector).offset().top; scrollTop.push(top); }); var footerTop = $('.entry-meta').offset().top; var headersTop = $('#headers').offset().top; var headersLeft = $('#headers').offset().left; $(window).scroll(function(){ waitForFinalEvent(function(){ var nowTop = $(window).scrollTop(); var length = scrollTop.length; var index; if(nowTop+60 > scrollTop[length-1]){ index = length; }else{ for(var i=0;i<length;i++){ if(nowTop+60 <= scrollTop[i]){ index = i; break; } } } $('#headers li').removeClass('on'); if( 0 == index ) index = 1; $('#headers li').eq(index-1).addClass('on'); if(nowTop >= footerTop) { $('#dl-headers').hide(); } else { $('#dl-headers').show(); } }); }); });
JavaScript
0.99851
@@ -498,16 +498,20 @@ $(' +body #post'). pare @@ -510,24 +510,8 @@ t'). -parents('body'). appe @@ -1793,105 +1793,10 @@ op;%0A -%0A -var headersTop = $('#headers').offset().top;%0A var headersLeft = $('#headers').offset().left;%0A %0A $
097104012aba3d7eed59c9472d4a8ca587c23ee2
Update jest dependency
react-native-scripts/src/scripts/init.js
react-native-scripts/src/scripts/init.js
// @flow import chalk from 'chalk'; import fse from 'fs-extra'; import path from 'path'; import pathExists from 'path-exists'; import spawn from 'cross-spawn'; import log from '../util/log'; // UPDATE DEPENDENCY VERSIONS HERE const DEFAULT_DEPENDENCIES = { expo: '^18.0.1', react: '16.0.0-alpha.12', 'react-native': '^0.45.1', }; // TODO figure out how this interacts with ejection const DEFAULT_DEV_DEPENDENCIES = { 'jest-expo': '~1.0.2', 'react-test-renderer': '16.0.0-alpha.12', }; module.exports = async (appPath: string, appName: string, verbose: boolean, cwd: string = '') => { const ownPackageName: string = require('../../package.json').name; const ownPath: string = path.join(appPath, 'node_modules', ownPackageName); const useYarn: boolean = await pathExists(path.join(appPath, 'yarn.lock')); // FIXME(perry) remove when npm 5 is supported if (!useYarn) { let npmVersion = spawn.sync('npm', ['--version']).stdout.toString().trim(); if (npmVersion.startsWith('5')) { console.log( chalk.yellow( ` ******************************************************************************* ERROR: npm 5 is not supported yet ******************************************************************************* It looks like you're using npm 5 which was recently released. Create React Native App doesn't work with npm 5 yet, unfortunately. We recommend using npm 4 or yarn until some bugs are resolved. You can follow the known issues with npm 5 at: https://github.com/npm/npm/issues/16991 ******************************************************************************* ` ) ); process.exit(1); } } const readmeExists: boolean = await pathExists(path.join(appPath, 'README.md')); if (readmeExists) { await fse.rename(path.join(appPath, 'README.md'), path.join(appPath, 'README.old.md')); } const appPackagePath: string = path.join(appPath, 'package.json'); const appPackage = JSON.parse(await fse.readFile(appPackagePath)); // mutate the default package.json in any ways we need to appPackage.main = './node_modules/react-native-scripts/build/bin/crna-entry.js'; appPackage.scripts = { start: 'react-native-scripts start', eject: 'react-native-scripts eject', android: 'react-native-scripts android', ios: 'react-native-scripts ios', test: 'node node_modules/jest/bin/jest.js --watch', }; appPackage.jest = { preset: 'jest-expo', }; if (!appPackage.dependencies) { appPackage.dependencies = {}; } if (!appPackage.devDependencies) { appPackage.devDependencies = {}; } // react-native-scripts is already in the package.json devDependencies // so we need to merge instead of assigning Object.assign(appPackage.dependencies, DEFAULT_DEPENDENCIES); Object.assign(appPackage.devDependencies, DEFAULT_DEV_DEPENDENCIES); // Write the new appPackage after copying so that we can include any existing await fse.writeFile(appPackagePath, JSON.stringify(appPackage, null, 2)); // Copy the files for the user await fse.copy(path.join(ownPath, 'template'), appPath); // Rename gitignore after the fact to prevent npm from renaming it to .npmignore try { await fse.rename(path.join(appPath, 'gitignore'), path.join(appPath, '.gitignore')); } catch (err) { // Append if there's already a `.gitignore` file there if (err.code === 'EEXIST') { const data = await fse.readFile(path.join(appPath, 'gitignore')); await fse.appendFile(path.join(appPath, '.gitignore'), data); await fse.unlink(path.join(appPath, 'gitignore')); } else { throw err; } } // Run yarn or npm let command = ''; let args = []; if (useYarn) { command = 'yarnpkg'; } else { command = 'npm'; args = ['install', '--save']; if (verbose) { args.push('--verbose'); } } log(`Installing dependencies using ${command}...`); log(); // why is this here if (command === 'yarnpkg') { // it's weird to print a yarn alias that no one uses command = 'yarn'; } const proc = spawn(command, args, { stdio: 'inherit' }); proc.on('close', code => { if (code !== 0) { console.error(`\`${command} ${args.join(' ')}\` failed`); return; } // display the cleanest way to get to the app dir // if the cwd + appName is equal to the full path, then just cd into appName let cdpath; if (path.resolve(cwd, appName) === appPath) { cdpath = appName; } else { cdpath = appPath; } log( ` Success! Created ${appName} at ${appPath} Inside that directory, you can run several commands: ${chalk.cyan(command + ' start')} Starts the development server so you can open your app in the Expo app on your phone. ${chalk.cyan(command + ' run ios')} (Mac only, requires Xcode) Starts the development server and loads your app in an iOS simulator. ${chalk.cyan(command + ' run android')} (Requires Android build tools) Starts the development server and loads your app on a connected Android device or emulator. ${chalk.cyan(command + ' test')} Starts the test runner. ${chalk.cyan(command + ' run eject')} Removes this tool and copies build dependencies, configuration files and scripts into the app directory. If you do this, you can’t go back! We suggest that you begin by typing: ${chalk.cyan('cd ' + cdpath)} ${chalk.cyan(command + ' start')}` ); if (readmeExists) { log( ` ${chalk.yellow('You had a `README.md` file, we renamed it to `README.old.md`')}` ); } log(); log('Happy hacking!'); }); };
JavaScript
0.000001
@@ -441,12 +441,13 @@ '~1 +8 .0. -2 +0 ',%0A
2137ba2e5138bfc3f2da256e76bfbc32e08c8bb9
fix for priorities in Z3
z3/CommandLineZ3.js
z3/CommandLineZ3.js
module('users.timfelgentreff.z3.CommandLineZ3').requires('users.timfelgentreff.z3.NaClZ3', "lively.ide.CommandLineInterface").toRun(function() { NaCLZ3.subclass("CommandLineZ3", { loadModule: function () { // No module used }, get strength() { return { required: undefined, // default strength strong: 10, medium: 5, weak: 1 } }, postMessage: function (string) { string = "(set-option :pp.decimal true)\n" + string + ("\n(check-sat)\n(get-value (" + this.variables.inject("", function (acc, v) { return acc + v.name + " " }) + "))"); // console.log(string); var commandString = this.constructor.z3Path + ' -T:4 -smt2 -in', self = this; if (!this.sync) { lively.ide.CommandLineInterface.run( commandString, {sync: this.sync, stdin: string}, function (r) { this.applyResult(r.getStdout() + r.getStderr()); }.bind(this) ); } else { var r = lively.ide.CommandLineInterface.run( commandString, {sync: this.sync, stdin: string} ); this.applyResult(r.getStdout() + r.getStderr()); } }, initialize: function($super, sync) { this.sync = !!(sync || true); $super(); }, applyResult: function(result) { result = result.replace(/ ?\|->.*\n/m, ""); // Z3-opt has this in the beginning result = result.replace(/\(error.*\n/m, ""); if (result.startsWith("sat")/* || result.indexOf("\nsat\n") != -1 */) { var idx = result.indexOf("sat\n"); result = result.slice(idx + "sat".length, result.length - 1); // remove outer parens result = result.trim().slice(1, result.length - 1); var assignments = result.split("\n").map(function (str) { var both = str.trim().slice(1, str.length - 1).split(" "); if (both.length < 2) return; both = [both[0].trim(), both.slice(1, both.length).join(" ").trim()]; var name = both[0]; var value = this.parseAndEvalSexpr(both[1]); return {name: name, value: value}; }.bind(this)); assignments.each(function (a) { this.varsByName[a.name].value = a.value; this.varsByName[a.name].updateStay(); if (!this.sync) { this.cvarsByName[a.name].suggestValue(a.value); } }.bind(this)); } else if (result.startsWith("unsat")) { throw new Error("Unsatisfiable constraint system"); } else { throw new Error("Z3 failed to solve this system"); } }, solve: function () { var decls = [""].concat(this.variables).reduce(function (acc, v) { return acc + "\n" + v.printDeclaration(); }); var constraints = ["\n"].concat(this.constraints).reduce(function (acc, c) { if (c.strength) { return acc + "\n" + "(assert-soft " + c.print() + " :weight " + c.strength + ")" } else { return acc + "\n" + "(assert " + c.print() + ")"; } }); this.postMessage(decls + constraints); return decls + constraints; }, constraintVariableFor: function($super, value, ivarname, cvar) { var cvar = $super(value, ivarname, cvar); if (cvar && this.constructor === CommandLineZ3) { // XXX: only add stays for this specific solver for now cvar.stay(); } return cvar; }, always: function($super, opts, func) { var prio = opts.priority; delete opts.priority; // not supported by NaClZ3 var result = cop.withLayers([CommandLineZ3Layer], function () { return $super(opts, func); }); if (prio && prio !== this.strength.required) { result.priority = prio; } return result; }, }); if (window.Config && window.Config.codeBase) { // Only in Lively Object.extend(CommandLineZ3, { modulePath: module('users.timfelgentreff.z3.CommandLineZ3').relativePath().replace("CommandLineZ3.js", "") }); Object.extend(CommandLineZ3, { z3Path: lively.ide.CommandLineInterface.cwd() + "/" + Config.codeBase.replace(Config.rootPath, "") + CommandLineZ3.modulePath + "z3" }); } else { Object.extend(CommandLineZ3, { get z3Path() { console.error("Standalone deployment must define CommandLineZ3.z3Path"); } }); } cop.create('CommandLineZ3Layer'). refineObject(Global, { get NaCLZ3Variable() { return CommandLineZ3Variable } }). refineClass(NaCLZ3Constraint, { enable: function (strength) { this.strength = strength; this.solver.addConstraint(this); } }) NaCLZ3Variable.subclass('CommandLineZ3Variable', { stay: function (strength) { strength = strength || this.solver.strength.weak; if (!this._stayCn) { this._stayCn = new NaCLZ3BinaryExpression("=", this, this.value, this.solver); this._stayCn.strength = strength; this.solver.addConstraint(this._stayCn); } }, removeStay: function() { if (this._stayCn) { this._stayCn.disable(); delete this._stayCn; } }, updateStay: function () { if (this._stayCn) { var s = this._stayCn.strength; this.solver.removeConstraint(this._stayCn); this._stayCn = new NaCLZ3BinaryExpression("=", this, this.value, this.solver); this._stayCn.strength = s; this.solver.addConstraint(this._stayCn); } } }); }) // end of module
JavaScript
0
@@ -4162,16 +4162,132 @@ iority;%0A + if (prio instanceof String %7C%7C typeof(prio) == %22string%22) %7B%0A prio = this.strength%5Bprio%5D;%0A %7D%0A
f606357e4814693e34502caaf1c705c006ac9659
Fix regressions related to SwitchTextTypeCommand.
packages/text/SwitchTextTypeCommand.js
packages/text/SwitchTextTypeCommand.js
'use strict'; var Command = require('../../ui/Command'); var _isMatch = require('lodash/isMatch'); var _find = require('lodash/find'); var _clone = require('lodash/clone'); function SwitchTextType() { Command.apply(this, arguments); } SwitchTextType.Prototype = function() { // Available text types on the surface this.getTextTypes = function(context) { var surface = context.surface; if (surface.isContainerEditor()) { return surface.getTextTypes(); } else { return []; } }; this.getTextType = function(context, textTypeName) { var textTypes = this.getTextTypes(context); return _find(textTypes, function(t) { return t.name === textTypeName; }); }; // Search which textType matches the current node // E.g. {type: 'heading', level: 1} => heading1 this.getCurrentTextType = function(context, node) { var textTypes = this.getTextTypes(context); var currentTextType; textTypes.forEach(function(textType) { var nodeProps = _clone(textType.data); delete nodeProps.type; if (_isMatch(node, nodeProps) && node.type === textType.data.type) { currentTextType = textType; } }); return currentTextType; }; this.getCommandState = function(context) { var sel = context.documentSession.getSelection(); var surface = context.surface; var doc = context.document; if (!surface) { return { disabled: true, active: false }; } var newState = { disabled: false, sel: sel, textTypes: this.getTextTypes(context) }; // Set disabled when not a property selection if (!surface.isEnabled() || sel.isNull()) { newState.disabled = true; } else if (sel.isContainerSelection()) { newState.disabled = true; newState.currentTextType = {name: 'container-selection'}; } else { var path = sel.getPath(); var node = doc.get(path[0]); // There are cases where path points to an already deleted node, // so we need to guard node if (node) { if (node.isText() && node.isBlock()) { newState.currentTextType = this.getCurrentTextType(context, node); } if (!newState.currentTextType) { // We 'abuse' the currentTextType field by providing a property // identifier that is translated into a name using an i18n resolve. // E.g. this.i18n('figure.caption') -> Figre Caption newState.currentTextType = {name: [node.type, path[1]].join('.')}; newState.disabled = true; } } } return newState; }; /** Trigger a switchTextType transaction @param {String} textTypeName identifier (e.g. heading1) */ this.execute = function(context, textTypeName) { var textType = this.getTextType(context, textTypeName); var nodeData = textType.data; var surface = context.surface; surface.transaction(function(tx, args) { args.data = nodeData; return surface.switchType(tx, args); }); return nodeData; }; }; Command.extend(SwitchTextType); SwitchTextType.static.name = 'switch-text-type'; module.exports = SwitchTextType;
JavaScript
0
@@ -166,16 +166,55 @@ clone'); +%0Avar warn = require('../../util/warn'); %0A%0Afuncti @@ -433,18 +433,56 @@ face -;%0A if ( +Manager.getFocusedSurface();%0A if (surface && surf @@ -1328,32 +1328,83 @@ tion(context) %7B%0A + var documentSession = context.documentSession;%0A var sel = co @@ -1478,40 +1478,80 @@ face -;%0A var doc = context.d +Manager.getFocusedSurface();%0A var doc = documentSession.getD ocument +() ;%0A%0A @@ -3077,17 +3077,147 @@ .surface -; +Manager.getFocusedSurface();%0A if (!surface) %7B%0A warn('No focused surface. Stopping command execution.');%0A return;%0A %7D %0A sur
429324f8df9027506fe76bb33ff0b507b7237ec9
add FlagsProvider to storybook
.storybook/stories/playground/index.js
.storybook/stories/playground/index.js
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import App from '../../../assets/src/edit-story/app'; export default { title: 'Playground|Stories Editor', }; // @todo: Find better way to mock these. const config = { allowedMimeTypes: { image: ['image/png', 'image/jpeg', 'image/jpg', 'image/gif'], audio: [], video: ['video/mp4'], }, allowedFileTypes: ['png', 'jpeg', 'jpg', 'gif', 'mp4'], storyId: 1234, api: { stories: '', media: '', fonts: '', }, metadata: { publisher: { name: '', logo: '', }, poster: '', }, capabilities: { hasUploadMediaAction: false, hasAssignAuthorAction: false, hasPublishAction: false, }, }; export const _default = () => { return <App config={config} />; };
JavaScript
0
@@ -589,16 +589,91 @@ e.%0A */%0A%0A +/**%0A * External dependencies%0A */%0Aimport %7B FlagsProvider %7D from 'flagged';%0A%0A /**%0A * I @@ -1387,18 +1387,45 @@ =%3E -%7B%0A return +(%0A %3CFlagsProvider features=%7B%7B%7D%7D%3E%0A %3CAp @@ -1448,9 +1448,27 @@ %7D /%3E -;%0A%7D +%0A %3C/FlagsProvider%3E%0A) ;%0A
b22d63bc8beb7aa1ddf191c7e685392c6a5b1e4d
Use dedicated heroku instance
scripts/containers/HomePage.js
scripts/containers/HomePage.js
import { bindActionCreators } from "redux"; import { connect } from "react-redux"; import HomePage from "../components/HomePage"; import * as PollActions from "../actions/poll"; function mapStateToProps(state) { return { server: "https://kinto-leplatrem.herokuapp.com/v1", bucket: "happiness" }; } function mapDispatchToProps(dispatch) { return bindActionCreators(PollActions, dispatch); } export default connect( mapStateToProps, mapDispatchToProps )(HomePage);
JavaScript
0
@@ -244,14 +244,8 @@ s:// -kinto- lepl @@ -249,16 +249,26 @@ eplatrem +-happiness .herokua
41bcbd60a688ffb90d0b6a33a8a94c6fd6773a78
fix bug with deleting tags leaving them in as filters
packages/tags/tags.js
packages/tags/tags.js
Session.setDefault('with_tags', []); Session.setDefault('without_tags', []); tagsHandle = Meteor.subscribe('tags', function () {}); Template.tags.events({ 'keydown #new-tag, keyup #new-tag, focusout #new-tag': function (evt) { if(evt.type === 'keyup' && evt.which === 27) { //esc -> cancel //cancel evt.target.value=''; } if(evt.type === 'keyup' && evt.which === 13 || evt.type === 'focusout') { var value = String(evt.target.value || ""); if (value) { //ok var tag = Tags.insert({ name: value, userId: Meteor.userId(), tagged: { 'Todos': [], 'Dailies': [], 'Habits': []} }); evt.target.value=''; } else { //cancel evt.target.value=''; } } stopProp(evt); }, }); Template.tags.helpers({ tags: function () { if(Meteor.userId()) { return Tags.find({}); } } }); Template.tag.events({ "click li" : function (evt) { var with_tags = Session.get("with_tags"); var without_tags = Session.get("without_tags"); /*console.log("with_tags:"); console.log(with_tags); console.log("without_tags:"); console.log(without_tags); */ if(_.contains(with_tags, this._id)) { Session.set("with_tags", _.without(with_tags, this._id)); Session.set("without_tags", without_tags.concat(this._id)); } else if (_.contains(without_tags, this._id)) { Session.set("without_tags", _.without(without_tags, this._id)); } else { Session.set("with_tags", with_tags.concat(this._id)); } }, "click span.remove" : function (evt) { if(this.tagged.Todos.length != 0 || this.tagged.Dailies != 0 || this.tagged.Habits != 0) { if(!confirm("The tag " + this.name + " is in use! Are you sure you want to delete it? (Tagged items we be de-tagged)")) { return; } } Mediator.publish('delete_tag', { tagged: this.tagged, deleted: this._id}); Tags.remove(this._id); } }); Template.tag.helpers({ filters: function () { if (_.contains(Session.get("with_tags"), this._id)) { return "label-success" } if (_.contains(Session.get("without_tags"), this._id)) { return "label-danger" } return "label-info" } });
JavaScript
0
@@ -2053,16 +2053,195 @@ s._id);%0A + Session.set(%22with_tags%22, _.without(Session.get(%22with_tags%22), this._id));%0A Session.set(%22without_tags%22, %0A _.without(Session.get(%22without_tags%22), this._id));%0A %7D%0A%7D);%0A
c7b91e9db8f199fda49cabe08a049f21d8ced9ca
fix test description and route
test/integration/index.js
test/integration/index.js
'use strict'; const request = require('supertest'); const bootstrap = require('../../'); const http = require('http'); const path = require('path'); describe('bootstrap()', () => { let promise; it('must be given a list of routes', () => (() => bootstrap()).should.Throw('Must be called with a list of routes') ); it('routes must each have a list of one or more steps', () => (() => bootstrap({ routes: [{}] })).should.Throw('Each route must define a set of one or more steps') ); it('requires the path to fields argument to be valid', () => (() => bootstrap({ fields: 'not_a_valid_path', routes: [{ steps: {}, }] })).should.Throw('Cannot find fields at ' + path.resolve(__dirname, '../../test/not_a_valid_path')) ); it('requires the path to the route fields argument to be valid', () => (() => bootstrap({ fields: '', routes: [{ steps: {}, fields: 'not_a_valid_path' }] })).should.Throw('Cannot find route fields at ' + path.resolve(__dirname, '../../test/not_a_valid_path')) ); it('requires the path to the views argument to be valid', () => (() => bootstrap({ views: 'not_a_valid_path', routes: [{ steps: {} }] })).should.Throw('Cannot find views at ' + path.resolve(__dirname, '../../test/not_a_valid_path')) ); it('requires the path to the route views argument to be valid', () => (() => bootstrap({ routes: [{ steps: {}, views: 'not_a_valid_path', }] })).should.Throw('Cannot find route views at ' + path.resolve(__dirname, '../../test/not_a_valid_path')) ); it('uses the route fields as the path', () => bootstrap({ routes: [{ steps: {}, fields: 'fields' }] }).then(api => { api.server.should.be.an.instanceof(http.Server) api.stop(); }) ); it('uses the name to find a path to the fields', () => bootstrap({ routes: [{ name: 'app_1', steps: {} }] }).then(api => { api.server.should.be.an.instanceof(http.Server) api.stop(); }) ); describe('with valid routes and steps', () => { it('returns a promise that resolves with the bootstrap interface', () => bootstrap({ routes: [{ steps: { '/one': {} } }] }).then(api => { api.server.should.be.an.instanceof(http.Server); api.stop.should.be.a.function; api.use.should.be.a.function; return api; }).then(api => api.stop()) ); it('starts the service and responds successfully', () => bootstrap({ routes: [{ steps: { '/one': {} } }] }).then(api => { request(api.server).get('/one').expect(200); return api; }).then(api => api.stop()) ); it('serves the correct view when requested from each step', () => bootstrap({ routes: [{ // baseUrl: '/path', steps: { '/one': {}, '/two': {} } }] }).then(api => { request(api.server) .get('/one') .expect(200) .expect(res => res.text.should.eql('<div>one</div>\n')) return api; }).then(api => { request(api.server) .get('/two') .expect(200) .expect(res => res.text.should.eql('<div>one</div>\n')) return api; }).then(api => api.stop()) ); it('uses a route baseUrl to serve the views and fields at the correct step', () => bootstrap({ routes: [{ baseUrl: '/app_1', steps: { '/one': {} } }] }).then(api => { request(api.server) .get('/baseUrl/one') .expect(200) .expect(res => res.text.should.eql('<div>one</div>\n')) return api; }).then(api => api.stop()) ); it('can be given a route param', () => bootstrap({ routes: [{ params: '/:action?', steps: { '/one': {} } }] }).then(api => { request(api.server) .get('/one/param') .expect(200) .expect(res => res.text.should.eql('<div>one</div>\n')) return api; }).then(api => api.stop()) ); it('uses a route param', () => bootstrap({ baseController: require('hof').controllers.base, routes: [{ steps: { '/one': {} } }] }).then(api => { request(api.server) .get('/one/param') .expect(200) .expect(res => res.text.should.eql('<div>one</div>\n')) return api; }).then(api => api.stop()) ); it('does not start the service if start is false', () => bootstrap({ start: false, routes: [{ steps: { '/one': {} } }] }).then(api => should.equal(api.server, undefined)) ); it('starts the server when start is called', () => bootstrap({ start: false, routes: [{ steps: { '/one': {} } }] }) .then(api => api.start({start: true})) .then(api => { request(api.server) .get('/one') .expect(200) .expect(res => res.text.should.eql('<div>one</div>\n')) return api; }).then(api => api.stop()) ); }); });
JavaScript
0.000003
@@ -4393,26 +4393,39 @@ it(' -uses a route param +accepts a baseController option ', ( @@ -4651,38 +4651,32 @@ .get('/one -/param ')%0A .ex
ea6b6754f7379b21eaebb18834d5169f5d18c0d2
Make process wait for prosody startup to complete
test/integration/index.js
test/integration/index.js
'use strict'; var Component = require('../../index') , ltx = require('node-xmpp-core').ltx , Client = require('node-xmpp-client') , exec = require('child_process').exec require('should') var component = null , client = null , user = null var options = {} /* jshint -W030 */ describe('Integration tests', function() { beforeEach(function(done) { options = { jid: 'component.localhost', password: 'mysecretcomponentpassword', host: 'localhost', port: 5347 } user = (+new Date()).toString(36) exec('sudo service prosody start', function() { component = new Component(options) component.on('close', function() { done('Could not connect component') }) component.on('online', function() { var options = { jid: user + '@localhost', password: 'password', host: '127.0.0.1', register: true } client = new Client(options) client.on('online', function() { client.send(new ltx.Element('presence')) done() }) client.on('error', function(error) { done(error) }) }) }) }) afterEach(function() { if (client) client.end() if (component) component.end() component = null client = null }) it('Can connect and send a message', function(done) { client.on('stanza', function(stanza) { if (false === stanza.is('message')) return stanza.is('message').should.be.true stanza.attrs.from.should.equal('component.localhost') stanza.attrs.to.should.equal(user + '@localhost') stanza.attrs.type.should.equal('chat') stanza.getChildText('body').should.equal('Hello little miss client!') done() }) var outgoing = new ltx.Element( 'message', { to: user + '@localhost', type: 'chat', from: 'component.localhost' } ) outgoing.c('body').t('Hello little miss client!') component.send(outgoing) }) it('Can receive a message', function(done) { component.on('stanza', function(stanza) { if (false === stanza.is('message')) return stanza.is('message').should.be.true stanza.attrs.to.should.equal('component.localhost') stanza.attrs.from.should.include(user + '@localhost') stanza.attrs.type.should.equal('chat') stanza.getChildText('body') .should.equal('Hello mr component!') done() }) var outgoing = new ltx.Element( 'message', { from: user + '@localhost', type: 'chat', to: 'component.localhost' } ) outgoing.c('body').t('Hello mr component!') client.send(outgoing) }) it('Errors if connecting with bad authentication information', function(done) { component.end() component = null options.password = 'incorrect' component = new Component(options) component.on('close', function() { done() }) component.on('online', function() { done('Should not connect') }) }) it('Sends error when server stops', function(done) { client.end() component.on('error', function() { done() }) component.on('close', function() { done() }) exec('sudo service prosody stop', function() {}) }) })
JavaScript
0
@@ -6,16 +6,35 @@ strict'; +%0A/* jshint -W030 */ %0A%0Avar Co @@ -286,56 +286,28 @@ %7B%7D%0A%0A -/* jshint -W030 */%0Adescribe('Integration tests', +var connectClients = fun @@ -316,28 +316,82 @@ ion( +done ) %7B%0A -%0A -beforeEach( +component = new Component(options)%0A component.on('online', func @@ -387,36 +387,32 @@ line', function( -done ) %7B%0A opti @@ -403,24 +403,28 @@ ) %7B%0A +var options = %7B%0A @@ -440,27 +440,25 @@ jid: -'component. +user + '@ localhos @@ -488,25 +488,8 @@ d: ' -mysecretcomponent pass @@ -514,25 +514,25 @@ host: ' -localhost +127.0.0.1 ',%0A @@ -542,18 +542,22 @@ -port: 5347 +register: true %0A @@ -575,171 +575,180 @@ -user +client = -(+ new -Date()).toString(36)%0A exec('sudo service prosody start', function() %7B%0A component = new Component(options)%0A compon +Client(options)%0A client.on('online', function() %7B%0A client.send(new ltx.Element('presence'))%0A done()%0A %7D)%0A cli ent.on(' clos @@ -735,37 +735,37 @@ client.on(' -close +error ', function() %7B%0A @@ -752,32 +752,37 @@ rror', function( +error ) %7B%0A @@ -785,46 +785,18 @@ - - done( -'Could not connect component' +error )%0A @@ -805,82 +805,104 @@ - - %7D)%0A component.on('online', function() %7B%0A +%7D)%0A %7D)%0A%7D%0A%0Adescribe('Integration tests', function() %7B%0A%0A beforeEach(function(done) %7B%0A -var opt @@ -922,38 +922,32 @@ - - jid: user + '@ +jid: 'component. localhos @@ -958,32 +958,24 @@ - - password: 'p @@ -965,32 +965,49 @@ password: ' +mysecretcomponent password',%0A @@ -1017,32 +1017,24 @@ - - host: ' -127.0.0.1 +localhost ',%0A @@ -1048,43 +1048,27 @@ - - register: true%0A +port: 5347%0A @@ -1055,36 +1055,32 @@ t: 5347%0A - %7D%0A @@ -1077,318 +1077,190 @@ - client +user = +(+ new -Client(options)%0A client.on('online', function() %7B%0A client.send(new ltx.Element('presence'))%0A d +Date()).toString(36)%0A exec('sudo service prosody start', function() %7B%0A setTimeout(functi on -e () -%0A %7D)%0A client.on('error', function(error) %7B%0A done(error)%0A %7D)%0A %7D + %7B%0A connectClients(done)%0A %7D, 1000 )%0A
35fd39f0fbc51d4e1bf0e7ba45592413937ec0e8
Fix test after rebase.
test/less_options/main.js
test/less_options/main.js
if (typeof window !== "undefined" && window.QUnit) { var systemInstantiate = System.instantiate; System.instantiate = function(load) { if (load.name.indexOf("main.less") !== -1) { var hasLineNumber = load.source.indexOf("line 1, input") !== -1, hasStrictMath = load.source.indexOf("100%") !== -1; QUnit.ok(hasLineNumber, "less set to dump line numbers"); QUnit.ok(hasStrictMath, "less set to process only maths inside un-necessary parenthesis"); QUnit.start(); removeMyself(); } return systemInstantiate.apply(this, arguments); }; steal("less_options/main.less!"); }
JavaScript
0
@@ -233,15 +233,8 @@ ne 1 -, input %22) !
0aef18125a917565adc7b9db90a6d07a01d17681
support skipping default empty state assert/check
test/lib/alloc-cluster.js
test/lib/alloc-cluster.js
// Copyright (c) 2015 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. 'use strict'; var extend = require('xtend'); var CountedReadySignal = require('ready-signal/counted'); var test = require('tape'); var util = require('util'); var TChannel = require('../../channel.js'); var parallel = require('run-parallel'); var debugLogtron = require('debug-logtron'); module.exports = allocCluster; function allocCluster(opts) { opts = opts || {}; var host = 'localhost'; var logger = debugLogtron('tchannel', { enabled: true, verbose: !!opts.logVerbose }); var cluster = { logger: logger, hosts: new Array(opts.numPeers), channels: new Array(opts.numPeers), destroy: destroy, ready: CountedReadySignal(opts.numPeers), assertCleanState: assertCleanState, assertEmptyState: assertEmptyState, connectChannels: connectChannels, connectChannelToChannels: connectChannelToChannels, timers: opts.timers }; var channelOptions = extend({ logger: logger, timeoutFuzz: 0, traceSample: 1 }, opts.channelOptions || opts); for (var i = 0; i < opts.numPeers; i++) { createChannel(i); } return cluster; function assertCleanState(assert, expected) { cluster.channels.forEach(function eachChannel(chan, i) { var chanExpect = expected.channels[i]; if (!chanExpect) { assert.fail(util.format('unexpected channel[%s]', i)); return; } var peers = chan.peers.values(); assert.equal(peers.length, chanExpect.peers.length, util.format( 'channel[%s] should have %s peer(s)', i, chanExpect.peers.length)); peers.forEach(function eachPeer(peer, j) { var peerExpect = chanExpect.peers[j]; if (!peerExpect) { assert.fail(util.format( 'unexpected channel[%s] peer[%s]', i, j)); return; } peer.connections.forEach(function eachConn(conn, k) { var connExpect = peerExpect.connections[k]; if (!connExpect) { assert.fail(util.format( 'unexpected channel[%s] peer[%s] conn[%s]', i, j, k)); return; } Object.keys(connExpect).forEach(function eachProp(prop) { var desc = util.format( 'channel[%s] peer[%s] conn[%s] should .%s', i, j, k, prop); var pending = conn.ops.getPending(); var handler = conn.handler; switch (prop) { case 'inReqs': assert.equal(pending.in, connExpect.inReqs, desc); break; case 'outReqs': assert.equal(pending.out, connExpect.outReqs, desc); break; case 'streamingReq': var streamingReq = Object.keys(handler.streamingReq).length; assert.equal(streamingReq, connExpect.streamingReq, desc); break; case 'streamingRes': var streamingRes = Object.keys(handler.streamingRes).length; assert.equal(streamingRes, connExpect.streamingRes, desc); break; default: assert.equal(conn[prop], connExpect[prop], desc); } }); }); }); }); } function assertEmptyState(assert) { assertCleanState(assert, { channels: cluster.channels.map(function build(channel) { var peers = channel.peers.values(); return { peers: peers.map(function b(p) { var conn = p.connections; return { connections: conn.map(function k(c) { return { direction: c.direction, inReqs: 0, outReqs: 0, streamingReq: 0, streamingRes: 0 }; }) }; }) }; }) }); } function createChannel(i) { var chan = TChannel(extend(channelOptions)); var port = opts.listen && opts.listen[i] || 0; chan.on('listening', chanReady); chan.listen(port, host); cluster.channels[i] = chan; function chanReady() { var port = chan.address().port; cluster.hosts[i] = util.format('%s:%s', host, port); cluster.ready.signal(cluster); } } function destroy(cb) { parallel(cluster.channels.map(function(chan) { return function(done) { if (!chan.destroyed) chan.quit(done); }; }), cb); } } function clusterTester(opts, t) { if (typeof opts === 'number') { opts = { numPeers: opts }; } if (typeof opts === 'function') { t = opts; opts = {}; } if (opts.timers && opts.channelOptions) { opts.channelOptions.timers = opts.timers; } return t2; function t2(assert) { opts.assert = assert; allocCluster(opts).ready(function clusterReady(cluster) { assert.once('end', function testEnded() { cluster.assertEmptyState(assert); cluster.destroy(); }); t(cluster, assert); }); } } allocCluster.test = function testCluster(desc, opts, t) { if (opts === undefined) { return test(desc); } test(desc, clusterTester(opts, t)); }; allocCluster.test.only = function testClusterOnly(desc, opts, t) { test.only(desc, clusterTester(opts, t)); }; function connectChannels(channels, callback) { return parallel(channels.map(function (channel) { return function connectChannelToHosts(callback) { return connectChannelToChannels(channel, channels, callback); }; }), callback); } function connectChannelToChannels(channel, channels, callback) { return parallel(channels.map(function (peerChannel) { return function connectChannelToHost(callback) { if (channel.hostPort === peerChannel.hostPort) { return callback(); } var peer = channel.peers.add(peerChannel.hostPort); var connection = peer.connect(); connection.identifiedEvent.on(onIdentified); // TODO impl connect on self connect function onIdentified() { callback(); } }; }), callback); } allocCluster.Pool = require('./resource_pool');
JavaScript
0
@@ -6973,24 +6973,72 @@ stEnded() %7B%0A + if (!opts.skipEmptyCheck) %7B%0A @@ -7067,32 +7067,50 @@ yState(assert);%0A + %7D%0A
700f65aa50e23eb06bcfe1bf0c675fb2996bbf75
Add implementation of revertSQLInjection in query.js
sashimi-webapp/src/database/retrieve/query.js
sashimi-webapp/src/database/retrieve/query.js
/* * * CS3283/4 - query.js * This class deals with query statements for the facade storage * This class will communicate with sqlCommands to get a certain command for * */ import SqlCommands from 'src/database/sql-related/sqlCommands'; import constants from 'src/database/constants'; import StringManipulator from 'src/database/stringManipulation'; const stringManipulator = new StringManipulator(); const sqlCommands = new SqlCommands(); // dummy function to init sequence running for code aesthetic below function initPromiseSequence() { return new Promise((resolve, reject) => resolve() ); } export default class query { static constructor() {} static getAllFilesAndFolders() { return new Promise((resolve, reject) => { const fileAndFolderArray = []; initPromiseSequence() .then(() => sqlCommands.getFullTableData(constants.ENTITIES_FILE_MANAGER) .then(fileArr => fileAndFolderArray.push(fileArr)) .catch(sqlError => reject(sqlError))) .then(() => sqlCommands.getFullTableData(constants.ENTITIES_FOLDER) .then(folderArr => fileAndFolderArray.push(folderArr)) .catch(sqlError => reject(sqlError))) .then(() => resolve(fileAndFolderArray)) .catch(sqlErr => reject(sqlErr)); }); } static isTableExistsInDatabase(tableName, databaseName) { return new Promise((resolve, reject) => { const thisDatabaseName = databaseName || constants.INDEXEDDB_NAME; const requestOpenDatabase = indexedDB.open(thisDatabaseName); requestOpenDatabase.onsuccess = function onSuccess(event) { const tableNames = event.target.result.objectStoreNames; if (tableNames.contains(tableName) === false) { requestOpenDatabase.result.close(); resolve(false); } else { requestOpenDatabase.result.close(); resolve(true); } }; // if database version not supported, implies table does not exists requestOpenDatabase.onupgradeneeded = function onUpgradeNeeded(event) { resolve(false); }; }); } static getFullTableData(tableName) { return sqlCommands.getFullTableData(tableName); } static searchString(searchString) { return new Promise((resolve, reject) => { const fileAndFolderArray = []; initPromiseSequence() .then(() => sqlCommands.partialSearchFileName(searchString) .then(fileArr => fileAndFolderArray.push(fileArr)) .catch(sqlError => reject(sqlError))) .then(() => sqlCommands.partialSearchFolderName(searchString) .then(folderArr => fileAndFolderArray.push(folderArr)) .catch(sqlError => reject(sqlError))) .then(() => resolve(fileAndFolderArray)) .catch(sqlErr => reject(sqlErr)); }); } static loadFolder(folderId) { return new Promise((resolve, reject) => { const fileAndFolderArray = []; initPromiseSequence() .then(() => sqlCommands.loadFilesFromFolder(folderId) .then(fileArr => fileAndFolderArray.push(fileArr)) .catch(sqlError => reject(sqlError))) .then(() => sqlCommands.loadFoldersFromFolder(folderId) .then(folderArr => fileAndFolderArray.push(folderArr)) .catch(sqlError => reject(sqlError))) .then(() => resolve(fileAndFolderArray)) .catch(sqlError => reject(sqlError)); }); } static loadFile(fileId) { return new Promise((resolve, reject) => sqlCommands.loadFile(fileId) .then((fileContent) => { fileContent = stringManipulator.replaceAll(fileContent, '\\"', '"'); resolve(fileContent); }) .catch(sqlError => reject(sqlError)) ); } }
JavaScript
0.000001
@@ -3566,40 +3566,37 @@ r.re -placeAll(fileContent, '%5C%5C%22', '%22' +vertSQLInjections(fileContent );%0A
2faffd7df04e2b399ee2cd2236a5755465670cb3
Reword descriptions for unit tests
test/spec/widgets.spec.js
test/spec/widgets.spec.js
describe('VK widgets', function () { beforeEach(module('vk-api-angular')); beforeEach(inject(function (_$compile_, _$rootScope_) { $compile = _$compile_; $rootScope = _$rootScope_; })); it('call VK.Widgets.Comments()', inject(function () { var spy = spyOn(VK.Widgets, 'Comments'); $compile('<vk-comments></vk-comments>')($rootScope); $rootScope.$digest(); expect(spy).toHaveBeenCalled(); })); it('call VK.Widgets.Community()', inject(function () { spyOn(VK.Widgets, 'Community'); $compile('<vk-community></vk-community>')($rootScope); $rootScope.$digest(); expect(VK.Widgets.Community).toHaveBeenCalled(); })); it('call VK.Widgets.ContactUs()', inject(function () { spyOn(VK.Widgets, 'ContactUs'); $compile('<vk-contact></vk-contact>')($rootScope); $rootScope.$digest(); expect(VK.Widgets.ContactUs).toHaveBeenCalled(); })); it('call VK.Widgets.Like()', inject(function () { spyOn(VK.Widgets, 'Like'); $compile('<vk-like></vk-like>')($rootScope); $rootScope.$digest(); expect(VK.Widgets.Like).toHaveBeenCalled(); })); it('call VK.Widgets.Post()', inject(function () { spyOn(VK.Widgets, 'Post'); $compile('<vk-post></vk-post>')($rootScope); $rootScope.$digest(); expect(VK.Widgets.Post).toHaveBeenCalled(); })); it('call VK.Share.button()', inject(function () { spyOn(VK.Share, 'button'); $compile('<vk-share></vk-share>')($rootScope); $rootScope.$digest(); expect(VK.Share.button).toHaveBeenCalled(); })); it('warns when using unsupported argument', inject(function () { spyOn(console, 'warn'); $compile('<vk-share data-type="nonexistent-type"></vk-share>')($rootScope); $rootScope.$digest(); expect(console.warn).toHaveBeenCalled(); })); });
JavaScript
0
@@ -198,32 +198,33 @@ %7D));%0A%0A it('call +s VK.Widgets.Comm @@ -229,16 +229,32 @@ mments() + Open API method ', injec @@ -443,32 +443,33 @@ %7D));%0A%0A it('call +s VK.Widgets.Comm @@ -475,16 +475,32 @@ munity() + Open API method ', injec @@ -699,32 +699,33 @@ %7D));%0A%0A it('call +s VK.Widgets.Cont @@ -731,16 +731,32 @@ tactUs() + Open API method ', injec @@ -951,32 +951,33 @@ %7D));%0A%0A it('call +s VK.Widgets.Like @@ -978,16 +978,32 @@ s.Like() + Open API method ', injec @@ -1186,24 +1186,25 @@ %0A%0A it('call +s VK.Widgets. @@ -1209,16 +1209,32 @@ s.Post() + Open API method ', injec @@ -1421,16 +1421,17 @@ it('call +s VK.Shar @@ -1440,16 +1440,32 @@ button() + Open API method ', injec
25d8e4ceafa63baff07a0facc0691c94cd967df0
Attach scroll listener after scrollNode is existed
packages/core/src/InfiniteScroll.js
packages/core/src/InfiniteScroll.js
// ************************************* // // Inspired by react-infinite-scroller // // @ref https://github.com/CassetteRocks/react-infinite-scroller // // ************************************* import React, { PureComponent, isValidElement } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import documentOffset from 'document-offset'; import Button from './Button'; import TextLabel from './TextLabel'; import Icon from './Icon'; import icBEM from './utils/icBEM'; import prefixClass from './utils/prefixClass'; import './styles/InfiniteScroll.scss'; const COMPONENT_NAME = prefixClass('infinite-scroll'); const ROOT_BEM = icBEM(COMPONENT_NAME); export const BEM = { root: ROOT_BEM, footer: ROOT_BEM.element('footer') }; const FILL_SPACE_TYPE = { AUTO: 'auto', MANUAL: 'manual' }; class InfiniteScroll extends PureComponent { static propTypes = { onLoadMore: PropTypes.func.isRequired, threshold: PropTypes.number, // Distance in px before the end of items isLoading: PropTypes.bool, hasMore: PropTypes.bool, usePageAsContainer: PropTypes.bool, fillSpace: PropTypes.oneOf(Object.values(FILL_SPACE_TYPE)), // Footer children loadingLabel: PropTypes.node, showMoreButton: PropTypes.node, noNewestButton: PropTypes.node }; static defaultProps = { onLoadMore: () => {}, threshold: 100, isLoading: false, hasMore: true, usePageAsContainer: false, fillSpace: FILL_SPACE_TYPE.MANUAL, loadingLabel: null, showMoreButton: null, noNewestButton: null } componentDidMount() { this.attachScrollListener(); this.loadMoreToFillSpace(); } componentDidUpdate() { // Auto trigger onLoadMore this.loadMoreToFillSpace(); } componentWillUnmount() { this.detachScrollListener(); } // ------------------------------------- // Calculate remaining bottom offset // while scrolling // ------------------------------------- /** * Get scrollNode's height * * @return {Number} */ getScrollNodeHeight = () => { const scrollNode = this.scrollNode; const { usePageAsContainer } = this.props; if (usePageAsContainer) { const scrollNodeOffset = documentOffset(scrollNode) || {}; const scrollNodeTopOffset = scrollNodeOffset.top || 0; return scrollNodeTopOffset + scrollNode.offsetHeight; } return scrollNode.scrollHeight; } /** * Get container's height * * @return {Number} */ getContainerHeight = () => { const { usePageAsContainer } = this.props; if (usePageAsContainer) { return window.innerHeight; } return this.scrollNode.parentNode.clientHeight; } /** * Get container's scrollTop * * @return {Number} */ getContainerScrollTop = () => { const { usePageAsContainer } = this.props; if (usePageAsContainer) { const windowBodyElement = document.documentElement || document.body.parentNode || document.body; return window.pageYOffset || windowBodyElement.scrollTop; } return this.scrollNode.parentNode.scrollTop; } /** * Get remaining bottom offset * * scrollNodeHeight * |-------------| * | | <= scrollTop * __|_____________|__ * | | | | * | | | | <= containerHeight * | | | | * |_|_____________|_| * | | <= remainingBottomOffset * |_____________| * * @return {Number} */ getRemainingBottomOffset = () => { const scrollNodeHeight = this.getScrollNodeHeight(); const containerHeight = this.getContainerHeight(); const containerScrollTop = this.getContainerScrollTop(); return scrollNodeHeight - (containerScrollTop + containerHeight); } // ------------------------------------- // Attach and detach scroll listener // ------------------------------------- /** * Auto trigger onLoadMore if scrollNode's height * smaller than 2 times of its container's height */ loadMoreToFillSpace = (event) => { const { onLoadMore, hasMore, isLoading, fillSpace } = this.props; if (!isLoading && hasMore && fillSpace === FILL_SPACE_TYPE.AUTO) { const scrollNodeHeight = this.getScrollNodeHeight(); const containerHeight = this.getContainerHeight(); const idealContainerHeight = 2 * containerHeight; if (scrollNodeHeight <= idealContainerHeight) { onLoadMore(event); } } } /** * Scroll listener */ handleScrollListener = (event) => { const { onLoadMore, threshold, hasMore, isLoading } = this.props; const remainingBottomOffset = this.getRemainingBottomOffset(); if (!isLoading && hasMore && threshold > remainingBottomOffset) { onLoadMore(event); } } attachScrollListener = () => { const { usePageAsContainer } = this.props; this.scrollContainer = usePageAsContainer ? window : this.scrollNode.parentNode; this.scrollContainer .addEventListener('scroll', this.handleScrollListener); } detachScrollListener = () => { if (this.scrollContainer) { this.scrollContainer .removeEventListener('scroll', this.handleScrollListener); } } // ------------------------------------- // Render footer // ------------------------------------- renderLoadingLabel() { const { loadingLabel } = this.props; if (isValidElement(loadingLabel)) { return loadingLabel; } return ( <TextLabel disabled align="center" icon={<Icon type="loading" spinning />} basic={loadingLabel} /> ); } renderFooterButton(buttonItem) { const { onLoadMore } = this.props; if (!buttonItem) { return null; } if (isValidElement(buttonItem)) { return buttonItem; } return ( <Button color="black" align="center" basic={buttonItem} minified={false} onClick={onLoadMore} /> ); } /** * Render footer child */ renderFooter() { const { isLoading, hasMore, showMoreButton, noNewestButton } = this.props; let footerChild = null; if (isLoading) { footerChild = this.renderLoadingLabel(); } else if (hasMore) { footerChild = this.renderFooterButton(showMoreButton); } else { footerChild = this.renderFooterButton(noNewestButton); } return ( <div className={BEM.footer}> {footerChild} </div> ); } // ------------------------------------- // Renderer // ------------------------------------- render() { const { onLoadMore, threshold, isLoading, hasMore, usePageAsContainer, fillSpace, // Footer children loadingLabel, showMoreButton, noNewestButton, children, className, style, ...rootProps } = this.props; // Get classnames and styles` const rootClassName = classNames(`${BEM.root}`, className); return ( <div {...rootProps} ref={(ref) => { this.scrollNode = ref; }} className={rootClassName}> {children} {this.renderFooter()} </div> ); } } export default InfiniteScroll;
JavaScript
0
@@ -5499,16 +5499,35 @@ : + this.scrollNode && this.sc @@ -5548,32 +5548,36 @@ tNode;%0A%0A +if ( this.scrollConta @@ -5572,33 +5572,73 @@ .scrollContainer +) %7B %0A + this.scrollContainer%0A .add @@ -5685,24 +5685,34 @@ lListener);%0A + %7D%0A %7D%0A%0A d
c3b8de708615878863e74bae39c8374f194aad46
Fix order of arguments
packages/core/src/Rules/EpsToPdf.js
packages/core/src/Rules/EpsToPdf.js
/* @flow */ import path from 'path' import File from '../File' import Log from '../Log' import Rule from '../Rule' import State from '../State' import type { Action, ShellCall, Command, Phase, CommandOptions, ParsedLog } from '../types' export default class EpsToPdf extends Rule { static parameterTypes: Array<Set<string>> = [ new Set(['EncapsulatedPostScript']), new Set(['ParsedLaTeXLog', 'Nil']) ] static description: string = 'Converts EPS to PDF using epstopdf.' static async appliesToParameters (state: State, command: Command, phase: Phase, jobName: ?string, ...parameters: Array<File>): Promise<boolean> { switch (parameters[1].type) { case 'Nil': // If there is not a LaTeX log present then only apply epstopdf when the // main source file is an EPS. const filePath = state.getOption('filePath', jobName) return !!filePath && parameters[0].filePath === path.normalize(filePath) case 'ParsedLaTeXLog': // When there is a LaTeX log present only apply epstopdf if there are // specific calls present, usually from the epstopdf package. return !!EpsToPdf.findCall(parameters[1].value, parameters[0].filePath) default: return false } } /** * Find an epstopdf call either in the call list or in an epstopdf package * message. * @param {ParsedLog} parsedLog The parsed LaTeX log. * @param {string} filePath The file path to look for. * @return {ShellCall} The shell call found or null if no * matching call was found. */ static findCall (parsedLog: ?ParsedLog, filePath: string): ?ShellCall { let call if (parsedLog) { // First look for shell escape call. call = Log.findCall(parsedLog, /^r?epstopdf$/, filePath) if (!call) { // If there is no shell escape call then look for a message from the // epstopdf package. call = Log.findMessageMatches(parsedLog, /Command: <([^>]*)>/, 'Package epstopdf') .map(match => Log.parseCall(match[1])) .find(call => call.args.includes(filePath)) } } return call } async initialize () { const call = EpsToPdf.findCall(this.parameters[1].value, this.parameters[0].filePath) if (call) { // There is a matching call so scrape the options from it. if (call.options.outfile) { this.options.epstopdfOutputPath = call.options.outfile } else if (call.args.length > 2) { this.options.epstopdfOutputPath = call.args[2] } this.options.epstopdfBoundingBox = call.options.exact ? 'exact' : (call.options.hires ? 'hires' : 'default') this.options.epstopdfRestricted = !!call.options.restricted } } async getFileActions (file: File): Promise<Array<Action>> { // Only return a run action for the actual eps file. return file.type === 'EncapsulatedPostScript' ? ['run'] : [] } async preEvaluate () { const call = EpsToPdf.findCall(this.parameters[1].value, this.parameters[0].filePath) if (call && call.status.startsWith('executed')) { // There is a matching and successful call so just get the resolved output // and skip the evaluation. this.info(`Skipping epstopdf call since epstopdf was already executed via shell escape.`, this.id) await this.getResolvedOutput(this.options.epstopdfOutputPath) this.actions.delete('run') } } constructCommand (): CommandOptions { const outputPath = this.resolvePath(this.options.epstopdfOutputPath) // Newer versions of epstopdf support the dvipdf style "epstopdf in out" // style but for backward compatability we use `--outfile` instead. const args = [ 'epstopdf', `--outfile=${outputPath}`, '$DIR_0/$BASE_0' ] // Look for a bounding box setting. switch (this.options.epstopdfBoundingBox) { case 'exact': args.push('--exact') break case 'hires': args.push('--hires') break } // Use restricted if required even though we are executing outside the // context of shell escape. if (this.options.epstopdfRestricted) { args.push('--restricted') } return { args, cd: '$ROOTDIR', severity: 'error', outputs: [outputPath] } } }
JavaScript
0.999871
@@ -3648,16 +3648,17 @@ e dvipdf +m style %22 @@ -3680,22 +3680,16 @@ %22%0A // - style but for @@ -3812,32 +3812,8 @@ th%7D%60 -,%0A '$DIR_0/$BASE_0' %0A @@ -4218,32 +4218,65 @@ ricted')%0A %7D%0A%0A + args.push('$DIR_0/$BASE_0')%0A%0A return %7B%0A
4c28abc8f33ecc2c1773a0bbd3ffa66fa8f375f5
Convert static/js/portico/confirm-preregistrationuser.js to ES6 module.
static/js/portico/confirm-preregistrationuser.js
static/js/portico/confirm-preregistrationuser.js
"use strict"; $(() => { $("#register").trigger("submit"); });
JavaScript
0.000001
@@ -1,19 +1,4 @@ -%22use strict%22;%0A%0A $(() @@ -45,8 +45,19 @@ %22);%0A%7D);%0A +export %7B%7D;%0A
bae719a4eceb3dc5c671c7e68cb677d17468f0b2
Correct error asserts
test/unit/transactions.js
test/unit/transactions.js
'use strict' process.env.NODE_ENV = 'test' const should = require('should') const transactions = require('../../src/api/transactions') describe("calculateTransactionBodiesByteLength()", () => { it("should calculate the bodies length of a transaction", async () => { const lengthObj = { length: 0 } let transaction = { body: '123456789' } transactions.calculateTransactionBodiesByteLength(lengthObj, transaction, new WeakSet()) lengthObj.length.should.be.exactly(9) }) it("should calculate the bodies length of a transaction with hidden bodies", async () => { const lengthObj = { length: 0 } let transaction = { body: '123456789', arbitrary: { property: { body: '123456789' } } } transactions.calculateTransactionBodiesByteLength(lengthObj, transaction, new WeakSet()) lengthObj.length.should.be.exactly(18) }) it("should calculate the bodies length of a transaction", async () => { const lengthObj = { length: 0 } let transaction = {} try { transactions.calculateTransactionBodiesByteLength(lengthObj, transaction, new WeakSet()) lengthObj.length.should.be.exactly(0) } catch (e) { e.should.not.exist() } }) }) describe("updateTransactionMetrics()", () => { it("should update transaction metrics", async () => { try { const updates = { $push: { routes: {} } } transactions.updateTransactionMetrics(updates, {}) } catch (e) { e.should.not.exist() } }) })
JavaScript
0.000003
@@ -1201,32 +1201,34 @@ )%0A %7D catch (e +rr ) %7B%0A e.shou @@ -1213,34 +1213,32 @@ h (err) %7B%0A -e. should.not.exist @@ -1230,32 +1230,35 @@ hould.not.exist( +err )%0A %7D%0A %7D)%0A%7D)%0A @@ -1522,16 +1522,18 @@ catch (e +rr ) %7B%0A @@ -1534,18 +1534,16 @@ %7B%0A -e. should.n @@ -1551,16 +1551,19 @@ t.exist( +err )%0A %7D%0A
47901b647abff3a9a6800cefc1e1220d7dc0c11a
Streamline Downscope sample (#2560)
auth/downscoping.js
auth/downscoping.js
// Copyright 2021, Google, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; const downscopingWithCredentialAccessBoundary = async ({ bucketName, objectName, }) => { // [START auth_downscoping_token_broker] // Imports the Google Auth libraries. const {GoogleAuth, DownscopedClient} = require('google-auth-library'); /** * Simulates token broker generating downscoped tokens for specified bucket. * * @param bucketName The name of the Cloud Storage bucket. * @param objectPrefix The prefix string of the object name. This is used * to ensure access is restricted to only objects starting with this * prefix string. */ async function getTokenFromBroker(bucketName, objectPrefix) { const googleAuth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/cloud-platform', }); // [START auth_downscoping_rules] // Define the Credential Access Boundary object. const cab = { // Define the access boundary. accessBoundary: { // Define the single access boundary rule. accessBoundaryRules: [ { availableResource: `//storage.googleapis.com/projects/_/buckets/${bucketName}`, // Downscoped credentials will have readonly access to the resource. availablePermissions: ['inRole:roles/storage.objectViewer'], // Only objects starting with the specified prefix string in the object name // will be allowed read access. availabilityCondition: { expression: "resource.name.startsWith('projects/_/buckets/" + `${bucketName}/objects/${objectPrefix}')`, }, }, ], }, }; // [END auth_downscoping_rules] // [START auth_downscoping_initialize_downscoped_cred] // Obtain an authenticated client via ADC. const client = await googleAuth.getClient(); // Use the client to create a DownscopedClient. const cabClient = new DownscopedClient(client, cab); // Refresh the tokens. const refreshedAccessToken = await cabClient.getAccessToken(); // [END auth_downscoping_initialize_downscoped_cred] // This will need to be passed to the token consumer. return refreshedAccessToken; } // [END auth_downscoping_token_broker] // [START auth_downscoping_token_consumer] // Imports the Google Auth and Google Cloud libraries. const {OAuth2Client} = require('google-auth-library'); const {Storage} = require('@google-cloud/storage'); /** * Simulates token consumer generating calling GCS APIs using generated * downscoped tokens for specified bucket. * * @param bucketName The name of the Cloud Storage bucket. * @param objectName The name of the object in the Cloud Storage bucket * to read. */ async function tokenConsumer(bucketName, objectName) { // Create the OAuth credentials (the consumer). const oauth2Client = new OAuth2Client(); // We are defining a refresh handler instead of a one-time access // token/expiry pair. // This will allow the consumer to obtain new downscoped tokens on // demand every time a token is expired, without any additional code // changes. oauth2Client.refreshHandler = async () => { // The common pattern of usage is to have a token broker pass the // downscoped short-lived access tokens to a token consumer via some // secure authenticated channel. For illustration purposes, we are // generating the downscoped token locally. We want to test the ability // to limit access to objects with a certain prefix string in the // resource bucket. objectName.substring(0, 3) is the prefix here. This // field is not required if access to all bucket resources are allowed. // If access to limited resources in the bucket is needed, this mechanism // can be used. const refreshedAccessToken = await getTokenFromBroker( bucketName, objectName.substring(0, 3) ); return { access_token: refreshedAccessToken.token, expiry_date: refreshedAccessToken.expirationTime, }; }; const storageOptions = { projectId: process.env.GOOGLE_CLOUD_PROJECT, authClient: { sign: () => { Promise.reject('unsupported'); }, getCredentials: async () => { Promise.reject(); }, request: opts => { return oauth2Client.request(opts); }, authorizeRequest: async opts => { opts = opts || {}; const url = opts.url || opts.uri; const headers = await oauth2Client.getRequestHeaders(url); opts.headers = Object.assign(opts.headers || {}, headers); return opts; }, }, }; const storage = new Storage(storageOptions); const downloadFile = await storage .bucket(bucketName) .file(objectName) .download(); console.log(downloadFile.toString('utf8')); } // [END auth_downscoping_token_consumer] try { tokenConsumer(bucketName, objectName); } catch (error) { console.log(error); } }; // TODO(developer): Replace these variables before running the sample. // The Cloud Storage bucket name. const bucketName = 'your-gcs-bucket-name'; // The Cloud Storage object name that resides in the specified bucket. const objectName = 'your-gcs-object-name'; const cli = require('yargs') .demand(2) .command( 'auth-downscoping-with-credential-access-boundary', 'Loads Downscoped Credentials.', { bucketName: { alias: 'b', default: bucketName, }, objectName: { alias: 'o', default: objectName, }, }, downscopingWithCredentialAccessBoundary ) .example( 'node $0 auth-downscoping-with-credential-access-boundary -b your-gcs-bucket-name -o your-gcs-object-name', 'Loads Downscoped Credentials.' ) .wrap(120) .recommendCommands() .epilogue( 'For more information, see https://cloud.google.com/iam/docs/downscoping-short-lived-credentials' ) .help() .strict(); if (module === require.main) { cli.parse(process.argv.slice(2)); }
JavaScript
0
@@ -4795,538 +4795,20 @@ nt: -%7B%0A sign: () =%3E %7B%0A Promise.reject('unsupported');%0A %7D,%0A getCredentials: async () =%3E %7B%0A Promise.reject();%0A %7D,%0A request: opts =%3E %7B%0A return oauth2Client.request(opts);%0A %7D,%0A authorizeRequest: async opts =%3E %7B%0A opts = opts %7C%7C %7B%7D;%0A const url = opts.url %7C%7C opts.uri;%0A const headers = await oauth2Client.getRequestHeaders(url);%0A opts.headers = Object.assign(opts.headers %7C%7C %7B%7D, headers);%0A return opts;%0A %7D,%0A %7D +oauth2Client ,%0A
80fa0df141371e5b929726e9eabef959adcfed28
Add developer flag to user schema
schemas/userSchema.js
schemas/userSchema.js
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var userSchema = new Schema({ githubId: Number, name: String, avatar_url: String, projects: Array }); module.exports = mongoose.model('User', userSchema);
JavaScript
0.000001
@@ -148,16 +148,40 @@ String,%0A + isDeveloper: Boolean,%0A projec
842c2db6f2cadbd49ec5e0248e71c7667e127a7c
Fix es6 in build scripts
resources/babel/transform-error-codes.js
resources/babel/transform-error-codes.js
/* eslint-disable */ var fs = require('fs') var path = require('path') var _errorCodes = null var _lastReadErrorCodes = null function getErrorCodes() { if (!_errorCodes || !_lastReadErrorCodes || (Date.now() - _lastReadErrorCodes) > 5000) { _errorCodes = JSON.parse(fs.readFileSync(path.join(__dirname, '../', 'error-codes.json'))) _lastReadErrorCodes = Date.now() } return _errorCodes } module.exports = function (babel) { var t = babel.types var SEEN_SYMBOL = Symbol('transform-error-codes.seen') return { visitor: { CallExpression: { exit: function (path) { var errorCodes = getErrorCodes() var node = path.node if (node[SEEN_SYMBOL]) return if (path.get('callee').isIdentifier({ name: 'invariant' })) { node[SEEN_SYMBOL] = true var errCode = node.arguments[1].value if (!errorCodes[errCode]) { throw path.buildCodeFrameError( 'Error code ' + errCode + ' not found in error-codes.json' ) } var extraArgs = node.arguments.length - 2 var expectedArgs = errorCodes[errCode].split('%s').length - 1 if (extraArgs !== expectedArgs) { throw path.buildCodeFrameError( 'Not enough arguments provided for error code ' + errCode + ', expected ' + expectedArgs ) } var newExpression = t.callExpression( node.callee, [ node.arguments[0], t.stringLiteral(errorCodes[errCode]), ...node.arguments.slice(2), ] ) newExpression[SEEN_SYMBOL] = true path.replaceWith(newExpression) } }, }, }, } }
JavaScript
0
@@ -1604,17 +1604,16 @@ rrCode%5D) -, %0A @@ -1623,13 +1623,17 @@ - ... +%5D.concat( node @@ -1655,25 +1655,9 @@ e(2) -,%0A %5D +) %0A
281588e18ff81ed73b13bad8572897c87becf9f4
clean up update-associations
scripts/update-associations.js
scripts/update-associations.js
/*eslint-disable */ /** * * This script queries dfp for all line items that match the arguments * specified, modifies their javascript representation and the submits an update * to DFP. * * Usage: * * $ node scripts/update-associations.js --channel A --platform M --position MIDDLE --region USA --partner SONOBI * */ 'use strict'; var Bluebird = require('bluebird'); var argv = require('minimist')(process.argv.slice(2)); var _ = require('lodash'); var DFP_CREDS = require('../local/application-creds'); var config = require('../local/config'); var formatter = require('../lib/formatter'); var Dfp = require('node-google-dfp-wrapper'); var credentials = { clientId: DFP_CREDS.installed.client_id, clientSecret: DFP_CREDS.installed.client_secret, redirectUrl: DFP_CREDS.installed.redirect_uris[0] }; var dfp = new Dfp(credentials, config, config.refreshToken); // read command line arguments var creativeId = argv.creativeId; var ProgressBar = require('progress'); var progressBar; var CONCURRENCY = { concurrency: 1 }; // use a default object to force certain properties to be in the correct order // startDateTime throws an error if you use full values var defaultAssociation = { lineItemId: null, creativeId: null, startDateTime: { date: { year: 2016, month: 2, day: 9 }, hour: 11, minute: 19, second: 35, timeZoneID: 'America/New_York' }, startDateTimeType: 'USE_START_DATE_TIME', sizes: null, status: null, stats: {stats:{}}, lastModifiedDateTime: null }; console.log(process.argv.slice(2).join(' ')); function getQuery() { return { creativeId: creativeId }; }; function getAssociations(query) { return dfp.getAssociations(query); } function includeAssociation(association){ var isIncluded = true; if(association.sizes){ isIncluded = association.sizes.length !== 4; } return isIncluded; } function editAssociation(association){ var clone = _.cloneDeep(defaultAssociation); association = _.assign(clone, association); association.sizes = [ { width: 300, height: 250, isAspectRatio: false }, { width: 160, height: 600, isAspectRatio: false }, { width: 728, height: 90, isAspectRatio: false }, { width: 320, height: 50, isAspectRatio: false } ]; return association; } function updateAssociations(associations) { return dfp.updateAssociations(associations) .tap(advanceProgress); } function logSuccess(results) { if (results) { console.log('sucessfully updated associations'); } } function handleError(err) { console.log('updating associations failed'); console.log('because', err.stack); } // this function is to help debugging function log(x){ console.log(x); } function splitBatches(associations){ var batches = _.chunk(associations, 400); console.log(batches.length, 'batches'); progressBar = new ProgressBar('Progress [:bar] :percent :elapseds', { total: batches.length + 1 }); advanceProgress(); return batches; } function advanceProgress(){ progressBar.tick(); }; Bluebird.resolve(getQuery()) .then(getAssociations) .filter(includeAssociation) .map(editAssociation) .then(splitBatches) .map(updateAssociations, CONCURRENCY) .then(logSuccess) .catch(handleError);
JavaScript
0
@@ -555,53 +555,8 @@ g'); -%0Avar formatter = require('../lib/formatter'); %0A%0Ava @@ -1079,64 +1079,8 @@ der%0A -// startDateTime throws an error if you use full values%0A var @@ -1138,24 +1138,82 @@ veId: null,%0A + // startDateTime throws an error if you use full values%0A startDateT @@ -1712,132 +1712,69 @@ ion) + %7B%0A -var isIncluded = true;%0A if(association.sizes)%7B%0A isIncluded = association.sizes.length !== 4;%0A %7D%0A return isIncluded +// filter associations however you need to%0A return true ;%0A%7D%0A @@ -1791,32 +1791,33 @@ editAssociation( +_ association)%7B%0A @@ -1812,18 +1812,99 @@ ciation) + %7B%0A + // extend the default association so that all fields are in the correct order%0A var cl @@ -1936,32 +1936,36 @@ Association);%0A +var association = _. @@ -1978,16 +1978,17 @@ (clone, +_ associat @@ -1995,16 +1995,25 @@ ion);%0A +//mutate associat @@ -2019,294 +2019,28 @@ tion -.sizes = %5B %7B width: 300, height: 250, isAspectRatio: false %7D,%0A %7B width: 160, height: 600, isAspectRatio: false %7D,%0A %7B width: 728, height: 90, isAspectRatio: false %7D,%0A %7B width: 320, height: 50, isAspectRatio: false %7D %5D; + however you need to %0A r @@ -2056,25 +2056,24 @@ ociation;%0A%7D%0A -%0A function upd
d3f9a17f7c1fff7b133e7ea58b9478847763b384
Rename takeScreenshot to checkForVisualChanges
tests/acceptance/setup.js
tests/acceptance/setup.js
import { remote } from 'webdriverio'; import Mugshot from 'mugshot'; import WebdriverIOAdapte from 'mugshot-webdriverio'; import path from 'path'; let mugshot; before(function() { this.timeout(10 * 1000); const options = { host: 'selenium', desiredCapabilities: { browserName: 'chrome' } }; global.browser = remote(options).init(); const adapter = new WebdriverIOAdapte(global.browser); mugshot = new Mugshot(adapter, { rootDirectory: path.join(__dirname, 'screenshots'), acceptFirstBaseline: false }); return global.browser; }); function takeScreenshot(test, name, selector = '.todoapp') { return new Promise((resolve, reject) => { try { mugshot.test({ name, selector }, (err, result) => { if (err) { test.error(err); resolve(); return; } if (result.isEqual) { resolve(); } else { // If we reject the promise Mocha will halt the suite. Workaround from // https://github.com/mochajs/mocha/issues/1635#issuecomment-191019928 test.error(new Error('Visual changes detected. Check screenshots')); resolve(); } }); } catch (e) { // These are Mugshot internal errors. Rejecting them here will halt the // suite. reject(e); } }); } beforeEach(function() { return global.browser.url('http://app:3000/') // Wait for webpack to build the app. .then(() => global.browser.waitForVisible('.todoapp', 5 * 1000)); }); afterEach(function() { return takeScreenshot(this.test, this.currentTest.fullTitle()); }); after(function() { return global.browser.end(); });
JavaScript
0
@@ -572,30 +572,37 @@ unction -takeScreenshot +checkForVisualChanges (test, n @@ -1558,22 +1558,29 @@ urn -takeScreenshot +checkForVisualChanges (thi
be305de857aeebccf2479f50966c346a9ad201a4
add more tests
packages/vx-axis/test/AxisLeft.test.js
packages/vx-axis/test/AxisLeft.test.js
import { AxisLeft } from '../src'; describe('<AxisLeft />', () => { test('it should be defined', () => { expect(AxisLeft).toBeDefined() }) })
JavaScript
0
@@ -1,8 +1,35 @@ +import React from 'react';%0A import %7B @@ -54,16 +54,50 @@ ../src'; +%0Aimport %7B shallow %7D from 'enzyme'; %0A%0Adescri @@ -201,12 +201,1085 @@ d()%0A %7D) +%0A%0A test('it should render with class .vx-axis-left', () =%3E %7B%0A const wrapper = shallow(%3CAxisLeft /%3E)%0A expect(wrapper.prop('className')).toEqual('vx-axis-left')%0A %7D)%0A%0A test('it should set className', () =%3E %7B%0A const wrapper = shallow(%3CAxisLeft className='test' /%3E)%0A expect(wrapper.prop('className')).toEqual('vx-axis-left test')%0A %7D)%0A%0A test('it should default labelOffset prop to 36', () =%3E %7B%0A const wrapper = shallow(%3CAxisLeft /%3E)%0A expect(wrapper.prop('labelOffset')).toEqual(36)%0A %7D)%0A%0A test('it should set labelOffset prop', () =%3E %7B%0A const labelOffset = 3%0A const wrapper = shallow(%3CAxisLeft labelOffset=%7BlabelOffset%7D /%3E)%0A expect(wrapper.prop('labelOffset')).toEqual(labelOffset)%0A %7D)%0A%0A test('it should default tickLength prop to 8', () =%3E %7B%0A const wrapper = shallow(%3CAxisLeft /%3E)%0A expect(wrapper.prop('tickLength')).toEqual(8)%0A %7D)%0A%0A test('it should set tickLength prop', () =%3E %7B%0A const tickLength = 15%0A const wrapper = shallow(%3CAxisLeft tickLength=%7BtickLength%7D /%3E)%0A expect(wrapper.prop('tickLength')).toEqual(tickLength)%0A %7D) %0A%7D)%0A
e29d7a79fa89fab18ce1bf8f30ffba57081fdf66
add removing tmpDir after tests and change its name to .tmp (cause its already ignored in .gitignore)
packages/xod-doc/test/generate.spec.js
packages/xod-doc/test/generate.spec.js
import chai, { expect } from 'chai'; import path from 'path'; import chaiFiles from 'chai-files'; import chaiFs from 'chai-fs'; import dirtyChai from 'dirty-chai'; import doc from '../src/index'; const packed = require('./mocks/pack.json'); chai.use(chaiFiles); chai.use(chaiFs); chai.use(dirtyChai); function pathResolve(ending, rootPath = __dirname) { return path.resolve(rootPath, ending); } describe('Generate docs', () => { const file = chaiFiles.file; const dir = chaiFiles.dir; const tmpPath = path.join(__dirname, 'tmp'); before((done) => { doc( tmpPath, pathResolve('layouts'), pathResolve('xod/core'), true) .then(done); }); it('shoult create folder tmp', () => expect( dir(tmpPath) ).to.exist() ); it('shoult create folder nodes', () => expect( dir( pathResolve('nodes', tmpPath) ) ) .to.exist() ); it('shoult create index file', () => expect( file( pathResolve('index.html', tmpPath) ) ) .to.exist() ); it('should create doc files', () => { const files = packed.map(el => (el.link.replace('nodes/', ''))); expect(pathResolve('nodes', tmpPath)).to.be.a.directory().and.include.files(files); }); it('files should contain not less than 1 match of patch label', () => { packed.forEach(el => { const re = new RegExp(`<h1>${el.label}</h1>`); expect(file(pathResolve(el.link, tmpPath))).to.match(re); }); }); it('index should contain all labels', () => { packed.forEach(el => { const re = new RegExp(el.label); expect(file(pathResolve('index.html', tmpPath))).to.match(re); }); }); });
JavaScript
0
@@ -153,24 +153,53 @@ irty-chai';%0A +import rimraf from 'rimraf';%0A import doc f @@ -558,16 +558,17 @@ rname, ' +. tmp');%0A%0A @@ -699,32 +699,80 @@ hen(done);%0A %7D); +%0A after(() =%3E %7B%0A rimraf.sync(tmpPath);%0A %7D); %0A%0A it('shoult c
295d172ba443ef28ccf5360927fde71cb5d586a5
Make trigger element available on getExtraData
indico/htdocs/js/indico/jquery/ajaxdialog.js
indico/htdocs/js/indico/jquery/ajaxdialog.js
/* This file is part of Indico. * Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). * * Indico is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of the * License, or (at your option) any later version. * * Indico 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 * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Indico; if not, see <http://www.gnu.org/licenses/>. */ (function(global, $) { 'use strict'; // Ajaxifies a link to open the target page (which needs to be using WPJinjaMixin.render_template) in a // modal dialog. Any forms on the page are ajaxified and should be using redirect_or_jsonify() in case // of success (or just return a JSON response containing success=true and possibly flashedmessages). // The link target MUST point to a page which is also valid when loaded directly in the browser since the // link could still be opened in a new tab manually. If you don't have a non-AJAX version, place the url in // data-href. $.fn.ajaxDialog = function jqAjaxDialog(options) { return this.on('click', function(e) { e.preventDefault(); var href = $(this).attr('href'); if (href == '#') { var data_href = $(this).data('href'); href = data_href? data_href : href; } ajaxDialog($.extend({}, options, { url: href })); }); }; // See the documentation of $.fn.ajaxDialog - use this function if you want to open an ajax-based dialog // manually instead of triggering it from a link using its href. global.ajaxDialog = function ajaxDialog(options) { options = $.extend({ title: null, // title of the dialog url: null, // url to GET the form from backSelector: '[data-button-back]', // elements in the form which will close the form clearFlashes: true, // clear existing flashed messages before showing new ones onClose: null // callback to invoke after closing the dialog. first argument is null if closed manually, // otherwise the JSON returned by the server }, options); var popup = null; $.ajax({ type: 'GET', url: options.url, cache: false, // IE caches GET AJAX requests. WTF. complete: IndicoUI.Dialogs.Util.progress(), error: handleAjaxError, success: function(data) { if (handleAjaxError(data)) { return; } showDialog(data); } }); function showDialog(dialogData) { popup = new ExclusivePopup(options.title, function() { if (options.onClose) { options.onClose(null); } return true; }, false, false); popup.draw = function() { this.ExclusivePopup.prototype.draw.call(this, dialogData.html); }; popup.postDraw = ajaxifyForms; popup.open(); } function closeDialog(callbackData) { if (options.onClose) { options.onClose(callbackData); } popup.close(); } function ajaxifyForms() { var killProgress = null; var forms = popup.contentContainer.find('form'); showFormErrors(popup.resultContainer); forms.on('click', options.backSelector, function(e) { e.preventDefault(); closeDialog(); }).each(function() { // We often use forms with an empty action; those need to go to // their page and not the page that loaded the dialog! var action = $(this).attr('action') || options.url; $(this).ajaxForm({ url: action, dataType: 'json', beforeSubmit: function() { killProgress = IndicoUI.Dialogs.Util.progress(); }, error: function(xhr) { killProgress(); closeDialog(); handleAjaxError(xhr); }, success: function(data) { killProgress(); if (handleAjaxError(data)) { closeDialog(); return; } if (options.clearFlashes) { $('#flashed-messages').empty(); } if (data.flashed_messages) { var flashed = $(data.flashed_messages.trim()).children(); $('#flashed-messages').append(flashed); } if (data.close_dialog || data.success) { closeDialog(data); } else if (data.html) { popup.contentContainer.html(data.html); ajaxifyForms(); } } }); }); } }; })(window, jQuery);
JavaScript
0
@@ -1637,16 +1637,17 @@ ata_href + ? data_h @@ -1658,16 +1658,16 @@ : href;%0A - @@ -1744,16 +1744,47 @@ rl: href +,%0A trigger: this %0A @@ -2075,16 +2075,77 @@ xtend(%7B%0A + trigger: null, // element that opened the dialog%0A @@ -2449,16 +2449,17 @@ se: null +, // call @@ -2564,24 +2564,25 @@ + // otherwise @@ -2614,16 +2614,132 @@ server%0A + getExtraData: function() %7B%7D // callback to add data to the form. receives the %3Cform%3E element as %60this%60%0A @@ -4530,16 +4530,131 @@ 'json',%0A + data: options.getExtraData.call(this, options.trigger),%0A traditional: true,%0A
15811398e36dd78afd782e89fa1280e05d627ca2
Remove logging
initializers/points.js
initializers/points.js
module.exports = { loadPriority: 1000, startPriority: 1000, stopPriority: 1000, initialize: function(api, next){ var nano = require('nano')(api.config.database.host); var points = nano.use('points'); function sluggify (text) { var slug = text.replace(/[^a-zA-Z0-9\s]/g,""); slug = slug.toLowerCase(); slug = slug.trim(); slug = slug.replace(/\s/g,'-'); return slug; } api.points = { pointAdd: function(userName, title, content, next){ var data = { addedBy: userName, created: new Date().getTime(), type: 'point', title: title, description: content }; points.insert(data, sluggify(userName + ' ' + title), function(error, body) { if (!error) { console.log(body); next(error, body); } else next(error); }); }, pointView: function(userName, title, next){ points.get(sluggify(userName + ' ' + title), function (error, body) { if (!error) { console.log(body); next(error, body); } else next(error); }) }, userPointsList: function(userName, next){ points.view('point_list', 'forUser', {'key': userName}, function (error, body) { if (!error) { console.log(body); next(error, body); } else next(error); }) }, pointsList: function(userName, next){ points.view('point_list', 'forUser', function (error, body) { if (!error) { console.log(body); next(error, body); } else next(error); }) }, pointEdit: function(userName, title, content, next){}, pointDelete: function(userName, title, next){}, }; next(); }, start: function(api, next){ next(); }, stop: function(api, next){ next(); } };
JavaScript
0.000001
@@ -803,39 +803,8 @@ ) %7B%0A - console.log(body);%0A @@ -822,32 +822,32 @@ t(error, body);%0A + %7D else @@ -1049,39 +1049,8 @@ ) %7B%0A - console.log(body);%0A @@ -1303,39 +1303,8 @@ ) %7B%0A - console.log(body);%0A @@ -1498,32 +1498,32 @@ (error, body) %7B%0A + if (!e @@ -1534,39 +1534,8 @@ ) %7B%0A - console.log(body);%0A
62e1d8515fd2434166ea9dc58203bc90f54f61c9
Correcting the service address
bakbak_validator.js
bakbak_validator.js
$.fn.bakbak_validator = function(options) { return this.each(function() { $(this).focusout(function() { run_validator($(this).val(), options); }); }); }; function run_validator(address_text, options) { // don't run validator without input if (!address_text) { return; } // length check if (address_text.length > 512) { error_message = 'Stream exceeds maxiumum allowable length of 512.'; if (options && options.error) { options.error(error_message); } else { console.log(error_message); } return; } // validator is in progress if (options && options.in_progress) { options.in_progress(); } var success = false; // make ajax call to get validation results $.ajax({ type: "GET", url: 'https://verifyemail.bakbak.io/validate', data: { email: address_text}, dataType: "json", crossDomain: true, success: function(data, status_text) { success = true; if (options && options.success) { options.success(data); } }, error: function(request, status_text, error) { success = true; error_message = 'Error occurred, unable to validate address.'; if (options && options.error) { options.error(error_message); } else { console.log(error_message); } } }); // timeout incase of some kind of internal server error setTimeout(function() { error_message = 'Error occurred, unable to validate address.'; if (!success) { if (options && options.error) { options.error(error_message); } else { console.log(error_message); } } }, 30000); }
JavaScript
0.999996
@@ -910,17 +910,16 @@ l: 'http -s ://verif @@ -935,16 +935,20 @@ kbak.io/ +api/ validate
dd80da7a019a07003aa8a588f2f3e57f03dd4218
Remove dead code
formatters/custom.js
formatters/custom.js
define(function(require, exports, module) { main.consumes = [ "Plugin", "settings", "save", "collab", "tabManager", "dialog.error", "format" ]; main.provides = ["format.custom"]; return main; function main(options, imports, register) { var settings = imports.settings; var tabs = imports.tabManager; var save = imports.save; var format = imports.format; var collab = imports.collab; var showError = imports["dialog.error"].show; var Plugin = imports.Plugin; var plugin = new Plugin("Ajax.org", main.consumes); var ERROR_NOT_FOUND = 127; function load() { if (!options.collab) { save.on("beforeSave", function() {}, plugin); } collab.on("beforeSave", beforeSave, plugin); collab.on("postProcessorError", function(e) { var mode = getMode(e.docId) || "language"; if (e.code !== ERROR_NOT_FOUND) return console.error("Error running formatter for " + mode + ": " + (e.stderr || e.code)); var formatter = (settings.get("project/" + mode + "/@formatter") || "formatter").replace(/(.*?) .*/, "$1"); showError("Error running code formatter for " + mode + ": " + formatter + " not found, please check your project settings"); }); format.on("format", function(e) { if (!settings.get("project/" + e.mode + "/@formatOnSave")) return; if (e.mode === "javascript" && settings.getBool("project/javascript/@use_jsbeautify")) return; // use built-in JS Beautify instead save.save(tabs.currentTab); return true; }, plugin); } function beforeSave(e) { var mode = getMode(e.docId); var enabled = settings.getBool("project/" + mode + "/@formatOnSave"); if (!enabled) return; if (mode === "javascript" && settings.getBool("project/javascript/@use_jsbeautify")) return; // use built-in JS Beautify instead var formatter = settings.get("project/" + mode + "/@formatter"); if (!formatter) return showError("No code formatter set for " + mode + ": please check your project settings"); e.postProcessor = { command: "bash", args: ["-c", formatter] }; } function getMode(docId) { var tab = tabs.findTab(docId); if (!tab || !tab.editor || !tab.editor.ace) return; return tab.editor.ace.session.syntax; } plugin.on("load", function() { load(); }); plugin.on("unload", function() { }); /** * Custom code formatter extension * * Reformats code in the current document on save */ plugin.freezePublicAPI({}); register(null, { "format.custom": plugin }); } });
JavaScript
0.001497
@@ -679,119 +679,8 @@ ) %7B%0A - if (!options.collab) %7B%0A save.on(%22beforeSave%22, function() %7B%7D, plugin);%0A %7D%0A @@ -3095,8 +3095,9 @@ %7D%0A%7D); +%0A
841b0e79b763b3f3afc672a02a4a2f0a1b7a8e1e
Fix reset endpoint
packages/shared/lib/api/settings.js
packages/shared/lib/api/settings.js
export const getSettings = () => ({ url: 'settings', method: 'get' }); export const updatePassword = (data) => ({ url: 'settings/password', method: 'put', data }); export const upgradePassword = (data) => ({ url: 'settings/password/upgrade', method: 'put', data }); export const updateLocale = (Locale) => ({ url: 'settings/locale', method: 'put', data: { Locale } }); export const updateNews = (News) => ({ url: 'settings/news', method: 'put', data: { News } }); export const updateInvoiceText = (InvoiceText) => ({ url: 'settings/invoicetext', method: 'put', data: { InvoiceText } }); export const updateLogAuth = (LogAuth) => ({ url: 'settings/logauth', method: 'put', data: { LogAuth } }); export const updateEmail = (data) => ({ url: 'settings/email', method: 'put', data }); export const updateNotifyEmail = (Notify) => ({ url: 'settings/email/notify', method: 'put', data: { Notify } }); export const updateResetEmail = (data) => ({ url: 'settings/email/reset', method: 'put', data }); export const verifyEmail = (Token) => ({ url: 'settings/email/verify', method: 'post', data: { Token } }); export const updatePhone = (data) => ({ url: 'settings/phone', method: 'put', data }); export const updateNotifyPhone = (Notify) => ({ url: 'settings/phone/notify', method: 'put', data: { Notify } }); export const updateResetPhone = (data) => ({ url: 'settings/phone/reset', method: 'put', data }); export const verifyPhone = (Token) => ({ url: 'settings/phone/verify', method: 'post', data: { Token } });
JavaScript
0.000002
@@ -1026,36 +1026,37 @@ teResetEmail = ( -data +Reset ) =%3E (%7B%0A url: @@ -1099,32 +1099,43 @@ 'put',%0A data +: %7B Reset %7D %0A%7D);%0A%0Aexport con
02b87d59683c2431c1319f2a55d6226d800daa57
Add redo hotkey for Windows (Ctrl+Shift+Z) (#3110)
packages/slate-hotkeys/src/index.js
packages/slate-hotkeys/src/index.js
import { isKeyHotkey } from 'is-hotkey' import { IS_IOS, IS_MAC } from 'slate-dev-environment' /** * Hotkey mappings for each platform. * * @type {Object} */ const HOTKEYS = { bold: 'mod+b', compose: ['down', 'left', 'right', 'up', 'backspace', 'enter'], moveBackward: 'left', moveForward: 'right', moveWordBackward: 'ctrl+left', moveWordForward: 'ctrl+right', deleteBackward: 'shift?+backspace', deleteForward: 'shift?+delete', extendBackward: 'shift+left', extendForward: 'shift+right', italic: 'mod+i', splitBlock: 'shift?+enter', undo: 'mod+z', } const APPLE_HOTKEYS = { moveLineBackward: 'opt+up', moveLineForward: 'opt+down', moveWordBackward: 'opt+left', moveWordForward: 'opt+right', deleteBackward: ['ctrl+backspace', 'ctrl+h'], deleteForward: ['ctrl+delete', 'ctrl+d'], deleteLineBackward: 'cmd+shift?+backspace', deleteLineForward: ['cmd+shift?+delete', 'ctrl+k'], deleteWordBackward: 'opt+shift?+backspace', deleteWordForward: 'opt+shift?+delete', extendLineBackward: 'opt+shift+up', extendLineForward: 'opt+shift+down', redo: 'cmd+shift+z', transposeCharacter: 'ctrl+t', } const WINDOWS_HOTKEYS = { deleteWordBackward: 'ctrl+shift?+backspace', deleteWordForward: 'ctrl+shift?+delete', redo: 'ctrl+y', } /** * Hotkeys. * * @type {Object} */ const Hotkeys = {} const IS_APPLE = IS_IOS || IS_MAC const IS_WINDOWS = !IS_APPLE const KEYS = [] .concat(Object.keys(HOTKEYS)) .concat(Object.keys(APPLE_HOTKEYS)) .concat(Object.keys(WINDOWS_HOTKEYS)) KEYS.forEach(key => { const method = `is${key[0].toUpperCase()}${key.slice(1)}` if (Hotkeys[method]) return const generic = HOTKEYS[key] const apple = APPLE_HOTKEYS[key] const windows = WINDOWS_HOTKEYS[key] const isGeneric = generic && isKeyHotkey(generic) const isApple = apple && isKeyHotkey(apple) const isWindows = windows && isKeyHotkey(windows) Hotkeys[method] = event => { if (isGeneric && isGeneric(event)) return true if (IS_APPLE && isApple && isApple(event)) return true if (IS_WINDOWS && isWindows && isWindows(event)) return true return false } }) /** * Export. * * @type {Object} */ export default Hotkeys
JavaScript
0
@@ -1265,16 +1265,17 @@ redo: +%5B 'ctrl+y' @@ -1275,16 +1275,33 @@ ctrl+y', + 'ctrl+shift+z'%5D, %0A%7D%0A%0A/**%0A
62be43779e7fcc361fae365ebdd742dea1e932e1
reduce ambiguity
server/game/deck.js
server/game/deck.js
const _ = require('underscore'); const cards = require('./cards'); const DrawCard = require('./drawcard.js'); const ProvinceCard = require('./provincecard.js'); const StrongholdCard = require('./strongholdcard.js'); class Deck { constructor(data) { this.data = data; } prepare(player) { var result = { allCards: [], allPlayableCards: [], faction: {}, conflictDrawCards: [], dynastyDrawCards: [], provinceCards: [], stronghold: [] }; //faction result.faction = this.data.faction; //conflict this.eachRepeatedCard(this.data.conflictDrawCards, cardData => { if(['conflict'].includes(cardData.deck)) { var drawCard = this.createCard(DrawCard, player, cardData); drawCard.location = 'conflict deck'; result.conflictDrawCards.push(drawCard); } }); //dynasty this.eachRepeatedCard(this.data.dynastyDrawCards, cardData => { if(['dynasty'].includes(cardData.deck)) { var drawCard = this.createCard(DrawCard, player, cardData); drawCard.location = 'dynasty deck'; result.dynastyDrawCards.push(drawCard); } }); this.eachRepeatedCard(this.data.provinceCards, cardData => { if(cardData.type_code === 'province') { var provinceCard = this.createCard(ProvinceCard, player, cardData); provinceCard.location = 'province deck'; result.provinceCards.push(provinceCard); } }); this.eachRepeatedCard(this.data.stronghold, cardData => { if(cardData.type_code === 'stronghold') { var strongholdCard = this.createCard(StrongholdCard, player, cardData); strongholdCard.location = 'stronghold province'; result.stronghold.push(strongholdCard); } }); result.allCards = [result.stronghold].concat(result.provinceCards).concat(result.conflictDrawCards).concat(result.dynastyDrawCards); result.allPlayableCards = [result.conflictDrawCards].concat(result.dynastyDrawCards); return result; } eachRepeatedCard(cards, func) { _.each(cards, cardEntry => { for(var i = 0; i < cardEntry.count; i++) { func(cardEntry.card); } }); } createCard(baseClass, player, cardData) { var cardClass = cards[cardData.code] || baseClass; return new cardClass(player, cardData); } } module.exports = Deck;
JavaScript
0.999999
@@ -772,36 +772,40 @@ var -draw +conflict Card = this.crea @@ -848,36 +848,40 @@ -draw +conflict Card.location = @@ -935,36 +935,40 @@ tDrawCards.push( -draw +conflict Card);%0A @@ -1150,19 +1150,22 @@ var d -raw +ynasty Card = t @@ -1225,19 +1225,22 @@ d -raw +ynasty Card.loc @@ -1309,19 +1309,22 @@ s.push(d -raw +ynasty Card);%0A
c7fcd6b4b31da03e5e14194acc5f0aa73c4f4b10
Update to Electron v1
electron-start.js
electron-start.js
var app = require('app'); // Module to control application life. var BrowserWindow = require('browser-window'); // Module to create native browser window. // Report crashes to our server. require('crash-reporter').start(); // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is GCed. var mainWindow = null; // Quit when all windows are closed. app.on('window-all-closed', function() { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform != 'darwin') { app.quit(); } }); // This method will be called when Electron has finished // initialization and is ready to create browser windows. app.on('ready', function() { // Create the browser window. mainWindow = new BrowserWindow({width: 800, height: 600}); // and load the index.html of the app. mainWindow.loadUrl('file://' + __dirname + '/index.html'); // Open the devtools. mainWindow.openDevTools(); // Emitted when the window is closed. mainWindow.on('closed', function() { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null; }); });
JavaScript
0
@@ -1,15 +1,20 @@ var -app +electron = requi @@ -21,13 +21,42 @@ re(' +electron');%0Avar app = electron. app -') ; / @@ -117,33 +117,30 @@ w = -require('b +electron.B rowser --w +W indow -') ; / @@ -186,77 +186,8 @@ w.%0A%0A -// Report crashes to our server.%0Arequire('crash-reporter').start();%0A%0A // K @@ -917,10 +917,10 @@ oadU -rl +RL ('fi
2a918ce67875ec970f27477099dd4779588fb3de
add Node import to appease TypeScript
js/buttons/BooleanRectangularToggleButton.js
js/buttons/BooleanRectangularToggleButton.js
// Copyright 2013-2020, University of Colorado Boulder /** * This toggle button uses a boolean Property and a trueNode and falseNode to display its content. */ import merge from '../../../phet-core/js/merge.js'; import Tandem from '../../../tandem/js/Tandem.js'; import BooleanToggleNode from '../BooleanToggleNode.js'; import sun from '../sun.js'; import RectangularToggleButton from './RectangularToggleButton.js'; class BooleanRectangularToggleButton extends RectangularToggleButton { /** * @param {Node} trueNode * @param {Node} falseNode * @param {Property.<boolean>} booleanProperty * @param {Object} [options] */ constructor( trueNode, falseNode, booleanProperty, options ) { options = merge( { tandem: Tandem.REQUIRED }, options ); assert && assert( !options.content, 'options.content cannot be set' ); options.content = new BooleanToggleNode( trueNode, falseNode, booleanProperty ); super( false, true, booleanProperty, options ); // @private this.disposeBooleanRectangularToggleButton = () => { options.content && options.content.dispose(); }; } /** * @public * @override */ dispose() { this.disposeBooleanRectangularToggleButton(); super.dispose(); } } sun.register( 'BooleanRectangularToggleButton', BooleanRectangularToggleButton ); export default BooleanRectangularToggleButton;
JavaScript
0
@@ -413,16 +413,94 @@ ton.js'; +%0Aimport %7B Node %7D from '../../../scenery/js/imports.js'; // eslint-disable-line %0A%0Aclass
005f9f6c6f6dcf01859e1b7e993521658e7bf186
add safety
js/common/tests/shell-collection-volatile.js
js/common/tests/shell-collection-volatile.js
//////////////////////////////////////////////////////////////////////////////// /// @brief test the collection interface w/ volatile collections /// /// @file /// /// DISCLAIMER /// /// Copyright 2010-2012 triagens GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Jan Steemann /// @author Copyright 2012, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// var jsunity = require("jsunity"); var internal = require("internal"); // ----------------------------------------------------------------------------- // --SECTION-- collection methods // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // --SECTION-- volatile collections // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief test suite: volatile collections //////////////////////////////////////////////////////////////////////////////// function CollectionVolatileSuite () { var ERRORS = require("internal").errors; var cn = "UnittestsVolatileCollection"; return { //////////////////////////////////////////////////////////////////////////////// /// @brief set up //////////////////////////////////////////////////////////////////////////////// setUp : function () { internal.db._drop(cn); }, //////////////////////////////////////////////////////////////////////////////// /// @brief tear down //////////////////////////////////////////////////////////////////////////////// tearDown : function () { internal.db._drop(cn); }, //////////////////////////////////////////////////////////////////////////////// /// @brief create a volatile collection //////////////////////////////////////////////////////////////////////////////// testCreation1 : function () { var c = internal.db._create(cn, { isVolatile : true, waitForSync : false }); assertEqual(cn, c.name()); assertEqual(true, c.properties().isVolatile); }, //////////////////////////////////////////////////////////////////////////////// /// @brief create a volatile collection //////////////////////////////////////////////////////////////////////////////// testCreation2 : function () { var c = internal.db._create(cn, { isVolatile : true }); assertEqual(cn, c.name()); assertEqual(true, c.properties().isVolatile); }, //////////////////////////////////////////////////////////////////////////////// /// @brief create w/ error //////////////////////////////////////////////////////////////////////////////// testCreationError : function () { try { // cannot set isVolatile and waitForSync at the same time var c = internal.db._create(cn, { isVolatile : true, waitForSync : true }); fail(); } catch (err) { assertEqual(ERRORS.ERROR_BAD_PARAMETER.code, err.errorNum); } }, //////////////////////////////////////////////////////////////////////////////// /// @brief test property change //////////////////////////////////////////////////////////////////////////////// testPropertyChange : function () { var c = internal.db._create(cn, { isVolatile : true, waitForSync : false }); try { // cannot set isVolatile and waitForSync at the same time c.properties({ waitForSync : true }); fail(); } catch (err) { assertEqual(ERRORS.ERROR_BAD_PARAMETER.code, err.errorNum); } }, //////////////////////////////////////////////////////////////////////////////// /// @brief load/unload //////////////////////////////////////////////////////////////////////////////// testLoadUnload : function () { var c = internal.db._create(cn, { isVolatile : true }); assertEqual(cn, c.name()); assertEqual(true, c.properties().isVolatile); c.unload(); internal.wait(4); assertEqual(true, c.properties().isVolatile); }, //////////////////////////////////////////////////////////////////////////////// /// @brief data storage //////////////////////////////////////////////////////////////////////////////// testStorage : function () { var c = internal.db._create(cn, { isVolatile : true }); assertEqual(true, c.properties().isVolatile); c.save({"test": true}); assertEqual(1, c.count()); c.unload(); internal.wait(4); assertEqual(true, c.properties().isVolatile); assertEqual(0, c.count()); }, //////////////////////////////////////////////////////////////////////////////// /// @brief data storage //////////////////////////////////////////////////////////////////////////////// testStorageMany : function () { var c = internal.db._create(cn, { isVolatile : true, journalSize: 1024 * 1024 }); assertEqual(true, c.properties().isVolatile); for (var i = 0; i < 10000; ++i) { c.save({"test": true, "foo" : "bar"}); } assertEqual(10000, c.count()); c.unload(); internal.wait(4); assertEqual(true, c.properties().isVolatile); assertEqual(0, c.count()); assertEqual([ ], c.toArray()); }, //////////////////////////////////////////////////////////////////////////////// /// @brief compaction //////////////////////////////////////////////////////////////////////////////// testCompaction : function () { var c = internal.db._create(cn, { isVolatile : true, journalSize: 1024 * 1024 }); assertEqual(true, c.properties().isVolatile); for (var i = 0; i < 10000; ++i) { c.save({"test": "the quick brown fox jumped over the lazy dog", "foo" : "bar"}); } assertEqual(10000, c.count()); c.truncate(); c.save({"test": 1}); assertEqual(1, c.count()); c.truncate(); c.unload(); internal.wait(5); assertEqual(0, c.count()); assertEqual([ ], c.toArray()); } }; } // ----------------------------------------------------------------------------- // --SECTION-- main // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief executes the test suites //////////////////////////////////////////////////////////////////////////////// jsunity.run(CollectionVolatileSuite); return jsunity.done(); // Local Variables: // mode: outline-minor // outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)" // End:
JavaScript
0.000576
@@ -5852,32 +5852,48 @@ c.unload();%0A + c = null;%0A %0A int @@ -5895,34 +5895,61 @@ internal.wait( -4) +5);%0A c = internal.db%5Bcn%5D ;%0A assertEq
caf73e4296e2c16469a5113b1d16e99f25111ac0
Tidy up custom email form
src/admin/dumb_components/custom_email_form.js
src/admin/dumb_components/custom_email_form.js
const React = require('react') const { map, objOf, zipWith, merge, compose, indexBy, prop, converge, dissoc } = require('ramda') export default ({ members, submit }) => { const onSubmit = (e) => { e.preventDefault() submit(members, e.target) } return ( <div className='custom-email-container'> <p><i>Write out your custom email.</i></p> <form onSubmit={onSubmit}> <input type='text' className='custom-email-subject' placeholder='Subject'></input> <textarea className='custom-email' placeholder='Email body' /> <button type='submit'>Submit</button> </form> </div> ) }
JavaScript
0.000083
@@ -27,106 +27,8 @@ ct') -%0Aconst %7B map, objOf, zipWith, merge, compose, indexBy, prop, converge, dissoc %7D = require('ramda') %0A%0Aex
cf919af73a26bacb03ac4eb3b1914d7472d82d4d
fix db index on media
models/users/Media.js
models/users/Media.js
// Model for file page (comments, file usage...) 'use strict'; var fs = require('fs'); var extname = require('path').extname; var exec = require('child_process').exec; var Mongoose = require('mongoose'); var Schema = Mongoose.Schema; var resize = require('./_lib/resize'); var configReader = require('../../server/_lib/uploads_config_reader'); module.exports = function (N, collectionName) { var mediaConfig; // Need different options, depending on ImageMagick or GraphicsMagick used. var gmConfigOptions; var Media = new Schema({ file_id : Schema.Types.ObjectId, // image_sizes contains list of previews size: // // { // orig: { width: 1280, height: 800 }, // md: { width: 640, height: 400 }, // ... // } image_sizes : Schema.Types.Mixed, user_id : Schema.Types.ObjectId, album_id : Schema.Types.ObjectId, ts : { 'type': Date, 'default': Date.now }, type : { 'type': String, 'enum': [ 'image', 'medialink', 'binary' ], 'default': 'binary' }, medialink_html : String, // medialink_data contains: // // { // provider : String, // src : String, // thumb : String, // video_width : Number, // video_height : Number, // video_url : String // } medialink_data : Schema.Types.Mixed, file_size : Number, file_name : String, description : String, exists : { 'type': Boolean, 'default': true } }, { versionKey: false }); // Indexes ////////////////////////////////////////////////////////////////////////////// // Media page, routing Media.index({ file_id: 1 }); // Album page, fetch medias // !!! sorting done in memory, because medias count per album is small Media.index({ album_id: 1 }); // "All medias" page, medias list, sorted by date Media.index({ user_id: 1, exists: 1, ts: -1 }); ////////////////////////////////////////////////////////////////////////////// // Remove files with previews // Media.pre('remove', function (callback) { if (this.type === 'medialink') { callback(); return; } N.models.core.File.remove(this.file_id, true, callback); }); var saveFile = function (path, name, maxSize, callback) { fs.stat(path, function (err, stats) { if (err) { callback(err); return; } if (stats.size > maxSize) { callback(new Error('Can\'t save file: max size exceeded')); return; } var storeOptions = { metadata: { origName: name } }; N.models.core.File.put(path, storeOptions, function (err, info) { if (err) { callback(err); return; } callback(null, { id: info._id, size: stats.size }); }); }); }; // Create media with original image with previews or binary file // // - options // - album_id // - user_id // - path - file path // - name - (optional) original file name (required for binary files). // - ext - (optional) file extension (needed only if path without extension) // // - callback(err, media_id) // Media.statics.createFile = function (options, callback) { var media = new N.models.users.Media(); media._id = new Mongoose.Types.ObjectId(); media.user_id = options.user_id; media.album_id = options.album_id; var format; // Format (extension) taken from options.name, options.ext or options.path in same order if (options.ext) { format = options.ext; } else { format = extname(options.path).replace('.', '').toLowerCase(); } // Is config for this type exists if (!mediaConfig.types[format]) { callback(new Error('Can\'t save file: \'' + format + '\' not supported')); return; } var typeConfig = mediaConfig.types[format]; var supportedImageFormats = [ 'bmp', 'gif', 'jpg', 'jpeg', 'png' ]; // Just save if file is not an image if (supportedImageFormats.indexOf(format) === -1) { if (!options.name) { callback(new Error('Can\'t save file: you must specify options.name for binary files')); return; } saveFile(options.path, options.name, typeConfig.max_size || mediaConfig.max_size, function (err, data) { if (err) { callback(err); return; } media.type = 'binary'; media.file_id = data.id; media.file_size = data.size; media.file_name = options.name; media.save(function (err) { if (err) { callback(err); return; } callback(null, media._id); }); }); return; } resize( options.path, { store: N.models.core.File, imageMagick: gmConfigOptions.imageMagick, ext: format, maxSize: typeConfig.max_size || mediaConfig.max_size, resize: typeConfig.resize }, function (err, data) { if (err) { callback(err); return; } media.type = 'image'; media.image_sizes = data.images; media.file_id = data.id; media.file_size = data.size; media.save(function (err) { if (err) { callback(err); return; } callback(null, media._id); }); } ); }; N.wire.on('init:models', function emit_init_Media(__, callback) { // Read config try { mediaConfig = configReader(((N.config.options || {}).users || {}).media || {}); } catch (e) { callback(e); return; } // Check is ImageMagick or GraphicsMagick installed // GraphicsMagick prefered exec('gm version', function (__, stdout) { // Don't check error because condition below is most strict if (stdout.indexOf('GraphicsMagick') !== -1) { // GraphicsMagick installed continue loading gmConfigOptions = {}; N.wire.emit('init:models.' + collectionName, Media, callback); return; } // Check ImageMagick if GraphicsMagick not found exec('convert -version', function (__, stdout) { // Don't check error because condition below is most strict if (stdout.indexOf('ImageMagick') !== -1) { // ImageMagick installed continue loading gmConfigOptions = { 'imageMagick': true }; N.wire.emit('init:models.' + collectionName, Media, callback); return; } callback(new Error('You need GraphicsMagick or ImageMagick to run this application. Can\'t find any.')); }); }); }); N.wire.on('init:models.' + collectionName, function init_model_Media(schema) { N.models[collectionName] = Mongoose.model(collectionName, schema); }); };
JavaScript
0
@@ -1734,16 +1734,18 @@ );%0A%0A // + - Album p @@ -1771,75 +1771,47 @@ // -!!! sorting done in memory, because medias count per album is small +- Media page, fetch next and prev _id's %0A M @@ -1828,24 +1828,43 @@ (%7B album_id: + 1, exists: 1, _id: 1 %7D);%0A%0A //
227ec4c8bd245fc42e321a61e5b0c454675691e3
Create exports as function taking IO
server/controllers/students.js
server/controllers/students.js
//var Teachers = require('../models/teachers'); //var TeacherClasses = require('../models/Teacher_classes'); //var Classes = require('../models/classes'); //var ClassLessons = require('../models/class_lessons'); // var Lessons = require('../models/lessons'); //var RequestedResponses = require('../models/requested_responses'); module.exports = { readyStage: function(io, req, res, next) { io.on('connection', function(client){ console.log('Hey, server! A student is ready to learn!'); client.emit('greeting', 'Hello, student!'); client.on('responseRecorded', function(data){ io.sockets.emit('responseRecordedFromStudent', data); }); }); var responseHTML = `<!doctype html> <html lang='en'> <head> </head> <body> <h1>Thumbroll</h1> <p></p><button id='submit'>Record Response</button><script></script> <script src='https://code.jquery.com/jquery-1.10.2.js'></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.5/socket.io.js'></script> <script>var socket=io.connect('http://localhost:3000'); socket.on('connect', function(data){socket.emit('studentJoin', 'Hiya, Teach! It's a student!');}); socket.on('thumbsCheck', function(data){console.log('new poll received'); $('p').html(data);}); socket.on('greeting', function(data){console.log(data);}); $('submit').on('click', function(){io.socket.emit('responseRecordedFromStudent');}); </script> </body></html>`; res.send(responseHTML); }, };
JavaScript
0.000002
@@ -339,20 +339,74 @@ ports = +function(io) %7B%0A +%0A +var functionTable = %7B%7D;%0A%0A functionTable. readySta @@ -407,17 +407,18 @@ adyStage -: + = functio @@ -423,12 +423,8 @@ ion( -io, req, @@ -735,801 +735,70 @@ - %0A%0A%0A %7D);%0A var responseHTML = %60%3C!doctype html%3E %3Chtml lang='en'%3E %3Chead%3E %3C/head%3E %3Cbody%3E %3Ch1%3EThumbroll%3C/h1%3E %3Cp%3E%3C/p%3E%3Cbutton id='submit'%3ERecord Response%3C/button%3E%3Cscript%3E%3C/script%3E %3Cscript src='https://code.jquery.com/jquery-1.10.2.js'%3E%3C/script%3E %3Cscript src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.5/socket.io.js'%3E%3C/script%3E %3Cscript%3Evar socket=io.connect('http://localhost:3000'); socket.on('connect', function(data)%7Bsocket.emit('studentJoin', 'Hiya, Teach! It's a student!');%7D); socket.on('thumbsCheck', function(data)%7Bconsole.log('new poll received'); $('p').html(data);%7D); socket.on('greeting', function(data)%7Bconsole.log(data);%7D); $('submit').on('click', function()%7Bio.socket.emit('responseRecordedFromStudent');%7D); %3C/script%3E %3C/body%3E%3C/html%3E%60;%0A%0A res.send(responseHTML);%0A%0A %7D,%0A +%7D);%0A res.send(responseHTML);%0A %7D;%0A %0A return functionTable; %0A%7D;
c5dffe31e6de8a9db5392f222918598f5aa3bc87
Add status field to the users model
models/users_model.js
models/users_model.js
import mongoose, { Schema } from 'mongoose'; const userSchema = new Schema({ first_name: { type: String, required: true }, last_name: { type: String, required: true }, email: { type: String, unique: true, required: true }, username: { type: String, unique: true, required: true }, password: { type: String, required: true }, created_at: { type: Number, default: Date.now, required: true } }); export default mongoose.model('User', userSchema);
JavaScript
0.000001
@@ -335,24 +335,95 @@ ed: true %7D,%0A + status: %7B type: String, enum: %5B'user', 'admin'%5D, required: true %7D,%0A created_
a0c57ac8a360bd53f40ebe8e38fe5c2880175942
Fix missing page action icon
scripts/background.js
scripts/background.js
/*jslint indent: 2 */ /*global window: false, XMLHttpRequest: false, chrome: false, btoa: false */ "use strict"; var TogglButton = { $user: null, $apiUrl: "https://www.toggl.com/api/v7", $newApiUrl: "https://new.toggl.com/api/v8", checkUrl: function (tabId, changeInfo, tab) { if (changeInfo.status === 'complete') { if (/toggl\.com\/track/.test(tab.url)) { TogglButton.fetchUser(TogglButton.$apiUrl); } else if (/toggl\.com\/app/.test(tab.url)) { TogglButton.fetchUser(TogglButton.$newApiUrl); } } }, fetchUser: function (apiUrl) { var xhr = new XMLHttpRequest(); xhr.open("GET", apiUrl + "/me?with_related_data=true", true); xhr.onload = function () { if (xhr.status === 200) { var resp = JSON.parse(xhr.responseText); TogglButton.$user = resp.data; } else if (apiUrl === TogglButton.$apiUrl) { TogglButton.fetchUser(TogglButton.$newApiUrl); } }; xhr.send(); }, createTimeEntry: function (timeEntry) { var start = new Date(), xhr = new XMLHttpRequest(), entry = { time_entry: { start: start.toISOString(), created_with: "Toggl Button", description: timeEntry.description, wid: TogglButton.$user.default_wid, pid: timeEntry.projectId || null, billable: timeEntry.billable || false, duration: -(start.getTime() / 1000) } }; xhr.open("POST", TogglButton.$newApiUrl + "/time_entries", true); xhr.setRequestHeader('Authorization', 'Basic ' + btoa(TogglButton.$user.api_token + ':api_token')); xhr.send(JSON.stringify(entry)); }, setPageAction: function(tabId) { var imagePath = 'images/inactive-19.png'; if (TogglButton.$user !== null) { imagePath = 'images/active-19.png'; } chrome.pageAction.setIcon({ tabId: tabId, path: imagePath }); chrome.pageAction.show(tabId); }, newMessage: function (request, sender, sendResponse) { if (request.type === 'activate') { TogglButton.setPageAction(sender.tab.id); sendResponse({success: TogglButton.$user !== null, user: TogglButton.$user}); } else if (request.type === 'timeEntry') { TogglButton.createTimeEntry(request); } } }; chrome.pageAction.onClicked.addListener(function (tab) { if (TogglButton.$user === null) { chrome.tabs.create({url: 'https://new.toggl.com/#login'}); } }); TogglButton.fetchUser(TogglButton.$apiUrl); chrome.tabs.onUpdated.addListener(TogglButton.checkUrl); chrome.extension.onMessage.addListener(TogglButton.newMessage);
JavaScript
0.000335
@@ -230,16 +230,289 @@ api/v8%22, +%0A $sites: new RegExp(%5B%0A 'asana%5C%5C.com',%0A 'podio%5C%5C.com',%0A 'trello%5C%5C.com',%0A 'github%5C%5C.com',%0A 'gitlab%5C%5C.com',%0A 'teambox%5C%5C.com',%0A 'teamweek%5C%5C.com',%0A 'basecamp%5C%5C.com',%0A 'unfuddle%5C%5C.com',%0A 'worksection%5C%5C.com',%0A 'pivotaltracker%5C%5C.com'%5D.join('%7C')), %0A%0A chec @@ -602,24 +602,119 @@ %7B%0A if +(TogglButton.$sites.test(tab.url)) %7B%0A TogglButton.setPageAction(tabId);%0A %7D else if (/toggl%5C.com @@ -2055,24 +2055,25 @@ on: function + (tabId) %7B%0A
3d58b58f5333f1c394b0223ef13acc8e044b9623
remove pact
scripts/botCleaner.js
scripts/botCleaner.js
const pact = require('../pact.js'); pact.db.createReadStream({start: 'poll!', end: 'poll!~' }) .on('data', (data) => { console.log(data.value); const title = JSON.parse(data.value).question; console.log(title); if (title.match('href') || title.match('http')) { pact.db.del(data.key, (err) => { if (err) { console.log(err); } }); } else { console.log(title); } }) .on('end', () => { console.log('done'); });
JavaScript
0.000102
@@ -1,18 +1,21 @@ const -pact +levelup = requi @@ -22,28 +22,47 @@ re(' -../pact.js');%0A%0Apact. +level');%0Aconst db = levelup('../db');%0A%0A db.c @@ -117,21 +117,16 @@ - end: 'po @@ -131,21 +131,16 @@ poll!~'%0A - @@ -349,13 +349,8 @@ -pact. db.d
7eeb2e526de312c11b08b9ac7e0d639b9f3c301a
Update colorWheel.js
scripts/colorWheel.js
scripts/colorWheel.js
var ColorWheel = React.createClass({ render: function() { var n = this.props.n == undefined ? 24 : this.props.n; var radius = this.props.radius == undefined ? 200 : this.props.radius; var thickness = this.props.thickness == undefined ? 40 : this.props.thickness; // radus is the outer radius var radius2 = radius - thickness; var colorDots = []; for(var i = 0; i < n; i++) { var a1 = Math.PI * 2 * i / n; var a2 = Math.PI * 2 * (i+1)/n; colorDots.push(<path d={ "M" + (radius + Math.round(Math.cos(a1) * radius)) + "," + (radius - Math.round(Math.sin(a1) * radius)) + " " + "A" + radius + "," + radius + " 0 0,0 " + (radius + Math.round(Math.cos(a2) * radius)) + "," + (radius - Math.round(Math.sin(a2) * radius)) + " " + "L" + (radius + Math.round(Math.cos(a2) * radius2)) + "," + (radius - Math.round(Math.sin(a2) * radius2)) + " " + "A" + radius2 + "," + radius2 + " 0 0,1 " + (radius + Math.round(Math.cos(a1) * radius2)) + "," + (radius - Math.round(Math.sin(a1) * radius2)) + " " + "Z" } fill={i%2 == 0 ? "red" : "blue" } stroke = "black" />); } return ( <svg height={radius*2+2} width={radius*2+2}> {colorDots} </svg> ); } })
JavaScript
0
@@ -1,14 +1,10 @@ %0A%0A -var ColorWhe
eb1b5cf172acc0ac09367b0779cdaa1965786f7b
Remove more from controller
scripts/controller.js
scripts/controller.js
/* * Copyright 2014, Gregg Tavares. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Gregg Tavares. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ "use strict"; // Start the main app logic. requirejs( [ 'hft/commonui', 'hft/gameclient', 'hft/misc/input', 'hft/misc/misc', 'hft/misc/mobilehacks', 'hft/misc/touch', '../bower_components/hft-utils/dist/audio', '../bower_components/hft-utils/dist/imageloader', '../bower_components/hft-utils/dist/imageutils', ], function( CommonUI, GameClient, Input, Misc, MobileHacks, Touch, AudioManager, ImageLoader, ImageUtils) { var g_client; var g_audioManager; var g_clock; var g_grid; var g_instrument; var g_leftRight = 0; var g_oldLeftRight = 0; var g_jump = false; var globals = { debug: false, orientation: "portrait-primary", }; Misc.applyUrlSettings(globals); MobileHacks.fixHeightHack(); MobileHacks.disableContextMenu(); MobileHacks.adjustCSSBasedOnPhone([ { test: MobileHacks.isIOS8OrNewerAndiPhone4OrIPhone5, styles: { ".button": { bottom: "100px", }, }, }, ]); function $(id) { return document.getElementById(id); } var startClient = function() { g_client = new GameClient(); // var handleScore = function() { }; var handleDeath = function() { }; var handleSetColor = function(msg) { var canvas = $("avatar"); var width = canvas.clientWidth; var height = canvas.clientHeight; canvas.width = width; canvas.height = height; var ctx = canvas.getContext("2d"); var coloredImage = ImageUtils.adjustHSV(images.idle.img, msg.h, msg.s, msg.v, msg.range) var frame = ImageUtils.cropImage(coloredImage, 0, 0, 16, 16); var frame = ImageUtils.scaleImage(frame, 128, 128); ctx.drawImage(frame, 0, 0, ctx.canvas.width, ctx.canvas.height); }; g_client.addEventListener('score', handleScore); g_client.addEventListener('die', handleDeath); g_client.addEventListener('setColor', handleSetColor); var sounds = {}; g_audioManager = new AudioManager(sounds); CommonUI.setupStandardControllerUI(g_client, globals); var handleLeftRight = function(pressed, bit) { g_leftRight = (g_leftRight & ~bit) | (pressed ? bit : 0); if (g_leftRight != g_oldLeftRight) { g_oldLeftRight = g_leftRight; g_client.sendCmd('move', { dir: (g_leftRight & 1) ? -1 : ((g_leftRight & 2) ? 1 : 0), }); } }; var handleJump = function(pressed) { if (g_jump != pressed) { g_jump = pressed; g_client.sendCmd('jump', { jump: pressed, }); } }; var keys = { }; keys[Input.cursorKeys.kLeft] = function(e) { handleLeftRight(e.pressed, 0x1); } keys[Input.cursorKeys.kRight] = function(e) { handleLeftRight(e.pressed, 0x2); } keys["Z".charCodeAt(0)] = function(e) { handleJump(e.pressed); } Input.setupKeys(keys); Touch.setupButtons({ inputElement: $("buttons"), buttons: [ { element: $("left"), callback: function(e) { handleLeftRight(e.pressed, 0x1); }, }, { element: $("right"), callback: function(e) { handleLeftRight(e.pressed, 0x2); }, }, { element: $("up"), callback: function(e) { handleJump(e.pressed); }, }, ], }); }; var images = { idle: { url: "assets/spr_idle.png", }, }; var wordInput = $("word-choice") var wordChoiceButton = $("word-choice-button") wordChoiceButton.addEventListener('click', inputSubmit, false); if (wordInput.form) { wordInput.form.addEventListener('submit', formSubmit, false); } function formSubmit() { //alert("form submit") } function inputSubmit() { //alert(wordInput.value) g_client.sendCmd('word choice', { word: wordInput.value, }); wordInput.value = ""; } function inputChange() { //alert("input change") } ImageLoader.loadImages(images, startClient); });
JavaScript
0
@@ -3663,1204 +3663,8 @@ );%0A%0A - var handleLeftRight = function(pressed, bit) %7B%0A g_leftRight = (g_leftRight & ~bit) %7C (pressed ? bit : 0);%0A if (g_leftRight != g_oldLeftRight) %7B%0A g_oldLeftRight = g_leftRight;%0A g_client.sendCmd('move', %7B%0A dir: (g_leftRight & 1) ? -1 : ((g_leftRight & 2) ? 1 : 0),%0A %7D);%0A %7D%0A %7D;%0A%0A var handleJump = function(pressed) %7B%0A if (g_jump != pressed) %7B%0A g_jump = pressed;%0A g_client.sendCmd('jump', %7B%0A jump: pressed,%0A %7D);%0A %7D%0A %7D;%0A%0A var keys = %7B %7D;%0A keys%5BInput.cursorKeys.kLeft%5D = function(e) %7B handleLeftRight(e.pressed, 0x1); %7D%0A keys%5BInput.cursorKeys.kRight%5D = function(e) %7B handleLeftRight(e.pressed, 0x2); %7D%0A keys%5B%22Z%22.charCodeAt(0)%5D = function(e) %7B handleJump(e.pressed); %7D%0A Input.setupKeys(keys);%0A%0A Touch.setupButtons(%7B%0A inputElement: $(%22buttons%22),%0A buttons: %5B%0A %7B element: $(%22left%22), callback: function(e) %7B handleLeftRight(e.pressed, 0x1); %7D, %7D,%0A %7B element: $(%22right%22), callback: function(e) %7B handleLeftRight(e.pressed, 0x2); %7D, %7D,%0A %7B element: $(%22up%22), callback: function(e) %7B handleJump(e.pressed); %7D, %7D,%0A %5D,%0A %7D);%0A %7D;
63fbbbe9aaa87d7effa710dca58dd65aaa2b94af
Test script
scripts/directLink.js
scripts/directLink.js
const directDownload = document.getElementById('directDownload'); const lastReleaseUrl = 'https://api.github.com/repos/nvaccess/nvda/releases/latest'; const lastRelease = async () => { const response =await fetch(lastReleaseUrl); const json = await response.json(); const version = await json.name.substr(9); await directDownload.setAttribute('href', version()); } lastRelease();
JavaScript
0.000001
@@ -350,12 +350,13 @@ te(' -href +title ', v
77e19adab7093bfe8ae841c35a4d5f793a3e5ce8
fix failing test
scripts/dispatcher.js
scripts/dispatcher.js
module.exports = { fire: function (eventName, eventData) { var customEvent = new CustomEvent(eventName, { detail: eventData }); window.dispatchEvent(customEvent); }, on: function (eventName, callback) { window.addEventListener(eventName, function(e) { callback.call(this, e.detail); }); } };
JavaScript
0.000006
@@ -20,33 +20,32 @@ fire: function - (eventName, even @@ -195,17 +195,16 @@ function - (eventNa
d97b6b337febc40ee806db032400d85d9f7f36d1
Use editor instance.
demo/src/example/index.js
demo/src/example/index.js
import React, { Component } from 'react'; import styled from 'styled-components'; import EmailEditor from '../../../src'; import sample from './sample.json'; const Container = styled.div` display: flex; flex-direction: column; position: relative; height: 100%; `; const Bar = styled.div` flex: 1; background-color: #61dafb; color: #000; padding: 10px; display: flex; max-height: 40px; h1 { flex: 1; font-size: 16px; text-align: left; } button { flex: 1; padding: 10px; margin-left: 10px; font-size: 14px; font-weight: bold; background-color: #000; color: #fff; border: 0px; max-width: 150px; cursor: pointer; } `; export default class Example extends Component { render() { return ( <Container> <Bar> <h1>React Email Editor (Demo)</h1> <button onClick={this.saveDesign}>Save Design</button> <button onClick={this.exportHtml}>Export HTML</button> </Bar> <EmailEditor ref={(editor) => (this.editor = editor)} onLoad={this.onLoad} onDesignLoad={this.onDesignLoad} /> </Container> ); } onLoad = () => { // this.editor.addEventListener('onDesignLoad', this.onDesignLoad) this.editor.loadDesign(sample); }; saveDesign = () => { this.editor.saveDesign((design) => { console.log('saveDesign', design); alert('Design JSON has been logged in your developer console.'); }); }; exportHtml = () => { this.editor.exportHtml((data) => { const { design, html } = data; console.log('exportHtml', html); alert('Output HTML has been logged in your developer console.'); }); }; onDesignLoad = (data) => { console.log('onDesignLoad', data); }; }
JavaScript
0
@@ -9,25 +9,22 @@ eact, %7B -Component +useRef %7D from @@ -694,658 +694,132 @@ %60;%0A%0A -export default class Example extends Component %7B%0A render() %7B%0A return (%0A %3CContainer%3E%0A %3CBar%3E%0A %3Ch1%3EReact E +const Example = (props) =%3E %7B%0A const e mail - Editor - (Demo)%3C/h1%3E%0A%0A %3Cbutton onClick=%7Bthis.saveDesign%7D%3ESave Design%3C/button%3E%0A %3Cbutton onClick=%7Bthis.exportHtml%7D%3EExport HTML%3C/button%3E%0A %3C/Bar%3E%0A%0A %3CEmailEditor%0A ref=%7B(editor) =%3E (this.editor = editor)%7D%0A onLoad=%7Bthis.onLoad%7D%0A onDesignLoad=%7Bthis.onDesignLoad%7D%0A /%3E%0A %3C/Container%3E%0A );%0A %7D%0A%0A onLoad = () =%3E %7B%0A // this.editor.addEventListener('onDesignLoad', this.onDesignLoad)%0A this.editor.loadDesign(sample);%0A %7D;%0A%0A saveDesign = () =%3E %7B%0A this +Ref = useRef(null);%0A%0A const saveDesign = () =%3E %7B%0A emailEditorRef.current .edi @@ -975,16 +975,22 @@ %7D;%0A%0A +const exportHt @@ -1010,12 +1010,30 @@ -this +emailEditorRef.current .edi @@ -1222,16 +1222,22 @@ %7D;%0A%0A +const onDesign @@ -1299,10 +1299,520 @@ );%0A %7D;%0A -%7D +%0A const onLoad = () =%3E %7B%0A emailEditorRef.current.editor.addEventListener('onDesignLoad', onDesignLoad);%0A emailEditorRef.current.editor.loadDesign(sample);%0A %7D;%0A%0A return (%0A %3CContainer%3E%0A %3CBar%3E%0A %3Ch1%3EReact Email Editor (Demo)%3C/h1%3E%0A%0A %3Cbutton onClick=%7BsaveDesign%7D%3ESave Design%3C/button%3E%0A %3Cbutton onClick=%7BexportHtml%7D%3EExport HTML%3C/button%3E%0A %3C/Bar%3E%0A%0A %3CEmailEditor%0A ref=%7BemailEditorRef%7D%0A onLoad=%7BonLoad%7D%0A /%3E%0A %3C/Container%3E%0A );%0A%7D;%0A%0Aexport default Example; %0A
4518c7a53eec48def29af1d78566929a72bac011
Fix magnitude
2020/js/day22.js
2020/js/day22.js
module.exports = ( input ) => { input = input .replace( /Player [12]:\n/g, '' ) .split( '\n\n' ) .map( l => l.split( '\n' ).map( x => parseInt( x, 10 ) ) ); function score( deck ) { return deck.reduce( ( a, b, i ) => a + b * ( deck.length - i ), 0 ); } function solvePart1() { const d1 = [ ...input[ 0 ] ]; const d2 = [ ...input[ 1 ] ]; do { const c1 = d1.shift(); const c2 = d2.shift(); if( c1 > c2 ) { d1.push( c1 ); d1.push( c2 ); } else { d2.push( c2 ); d2.push( c1 ); } } while( d1.length > 0 && d2.length > 0 ); return score( d1.length > d2.length ? d1 : d2 ); } function solvePart2() { const p1Winner = recursiveCombat( input[ 0 ], input[ 1 ] ); return score( input[ p1Winner ? 0 : 1 ] ); } function recursiveCombat( d1, d2 ) { const previousRounds = new Set(); do { const hash = score( d1 ) + ( 10000 * score( d2 ) ); if( previousRounds.has( hash ) ) { return true; } previousRounds.add( hash ); const c1 = d1.shift(); const c2 = d2.shift(); let p1Winner = c1 > c2; if( c1 <= d1.length && c2 <= d2.length ) { p1Winner = recursiveCombat( d1.slice( 0, c1 ), d2.slice( 0, c2 ) ); } if( p1Winner ) { d1.push( c1 ); d1.push( c2 ); } else { d2.push( c2 ); d2.push( c1 ); } } while( d1.length > 0 && d2.length > 0 ); return d1.length > d2.length; } const part1 = solvePart1(); //const part1 = 0; const part2 = solvePart2(); return [ part1, part2 ]; };
JavaScript
0.000068
@@ -874,16 +874,25 @@ t hash = + 100000 * score( @@ -901,18 +901,8 @@ ) + - ( 10000 * sco @@ -907,18 +907,16 @@ core( d2 - ) );%0A%0A%09%09%09
34c0e2f4cc885e38716841fbf854c7e92e4e7bba
Add missing key parameter to EXPIREAT call
models/OneTimeToken.js
models/OneTimeToken.js
var crypto = require('crypto') , client = require('../boot/redis') ; /** * OneTimeToken * * OneTimeToken is an expiring (TTL) token class * used for any process that requires an expiring * token such as email verification and password * reset. * * The constructor generates a random string suitable * for use as a public token, and stores metadata * such as when the token expires, what the token * should be used for, and the identifier of the * subject in question (user, client, etc). */ function OneTimeToken (options) { this._id = options._id || crypto.randomBytes(32).toString('hex'); this.exp = options.exp; this.use = options.use; this.sub = options.sub; if (options.ttl) { this.exp = Math.round(Date.now() / 1000) + options.ttl; } } /** * Peek * * Peek gets a persisted token from the data store * and attempts to parse the result. If there is no * token found, or the token is expired, the callback * in invoked with null error and value. If the token * value can't be parsed as JSON, the callback is invoked * with an error. Otherwise, the callback is invoked * with a null error and an instance of OneTimeToken. */ OneTimeToken.peek = function (id, callback) { client.get('onetimetoken:' + id, function (err, result) { if (err) { return callback(err); } if (!result) { return callback(null, null) } try { var token = new OneTimeToken(JSON.parse(result)); } catch (err) { return callback(err); } if (Math.round(Date.now() / 1000) > token.exp) { return callback(null, null); } callback(null, token); }); }; /** * Revoke */ OneTimeToken.revoke = function (id, callback) { client.del('onetimetoken:' + id, function (err) { callback(err); }); }; /** * Consume * * Consume retrieves a OneTimeToken instance from * the data store and immediately deletes it before * invoking the callback with the token. */ OneTimeToken.consume = function (id, callback) { OneTimeToken.peek(id, function (err, token) { if (err) { return callback(err); } OneTimeToken.revoke(id, function (err) { if (err) { return callback(err); } callback(null, token); }); }); }; /** * Issue * * Issue creates a new OneTimeToken from options and * stores the token in the datastore with a TTL. */ OneTimeToken.issue = function (options, callback) { if (options instanceof OneTimeToken) { var token = options; } else { var token = new OneTimeToken(options); } // transaction var multi = client.multi(); multi.set('onetimetoken:' + token._id, JSON.stringify(token)); // only expire if "exp" is set on the token if (token.exp) { multi.expireat(token.exp); } multi.exec(function (err, results) { if (err) { return callback(err); } callback(null, token); }); }; module.exports = OneTimeToken;
JavaScript
0
@@ -2702,16 +2702,45 @@ xpireat( +'onetimetoken:' + token._id, token.ex
90015b90457bda15c887fe67211b4625209c8856
Fix issue where cog-wheel would not spin.
site/content/js/navigation-animation.js
site/content/js/navigation-animation.js
--- yuiCompress: !!bool false --- (function($, window, document) { /** * jQuery event handler that should be triggered when navigating has * completed ('denvelop-navigated' event). This will animate some icons. */ var animate = function(event, prevPage, newPage) { // TODO gearRotating = false; }, /** * jQuery event handler that should be triggered when navigating starts * ('denvelop-navigating' event). This will show a spinning cog-wheel. */ animateLoading = function(event) { gearRotating = true; rotateSomewhat(); gearObj.stop().animate({'top': 0}, 150); }, gear = null, gearObj = null, gearRotating = false, rotateSomewhat = function() { gear.stop().animate({'transform': 'r45,80,96'}, 1000, function() { if (gearRotating) { // reset transformation and repeat it (so it looks infinite) gear.attr({'transform': 'rotate(0 80 96)'}); rotateSomewhat(); } else { // stop, but keep it spinning while it goes down gear.stop().animate({'transform': 'r45,80,96'}, 1000); gearObj.stop().animate({'top': 5}, 150); } }); }, /** * Function that splits the envelope SVG in a foreground and background, * so that icons can be put 'in' the envelope. */ splitEnvelope = function() { var bgWrapper = $('#envelope'), bg = Snap(bgWrapper.get(0)), fgWrapper = bgWrapper.clone(); fgWrapper.addClass('logo-layer-fg') .on('load', function() { var fg = Snap(fgWrapper.get(0)); fg.selectAll('path:not(:last-child)').remove(); bg.selectAll('path:last-child').remove(); }) .appendTo($('#logo')); // append a margin element to cover icons sticking out of the bottom // of the envelope var marginEl = $('<div />'); marginEl.css({ 'position': 'absolute', 'top': parseInt(bgWrapper.css('marginTop')) + bgWrapper.height(), 'right': 0, 'bottom': 0, 'left': 0, 'z-index': 3, 'background': $('#header').css('background-color') }); $('#logo').append(marginEl); }; $(function() { // make gear icon globally available for easy access gearObj = $('#loading-gear'); gear = Snap(gearObj.get(0)).select('g'); gearObj.css({'display': 'block', 'top': 5}); // split the envelope icon in parts, so that we can move icons in and // out of the envelope easily and also add a margin element that covers // the gear when it moves out of the envelope (and other icons too) splitEnvelope(); // bind to the custom event that is fired as soon as a navigation link // is clicked and intercepted, but the page must still be loaded $(window).on('denvelop-navigating', animateLoading); // bind to the custom event that is fired when navigation is changed // and the event could be intercepted and handled using JS $(window).on('denvelop-navigated', animate); }); }(jQuery, window, document));
JavaScript
0
@@ -844,32 +844,105 @@ gear.stop() +%0A .attr(%7B'transform': 'rotate(0 80 96)'%7D)%0A .animate(%7B'trans @@ -997,16 +997,20 @@ + if (gear @@ -1017,24 +1017,28 @@ Rotating) %7B%0A + @@ -1122,24 +1122,28 @@ + gear.attr(%7B' @@ -1187,32 +1187,36 @@ + rotateSomewhat() @@ -1233,16 +1233,20 @@ + %7D else %7B @@ -1262,24 +1262,28 @@ + + // stop, but @@ -1331,32 +1331,36 @@ + gear.stop().anim @@ -1350,24 +1350,121 @@ gear.stop() +%0A .attr(%7B'transform': 'rotate(0 80 96)'%7D)%0A .animate(%7B't @@ -1507,32 +1507,36 @@ + gearObj.stop().a @@ -1550,17 +1550,21 @@ %7B'top': -5 +'20%25' %7D, 150); @@ -1584,10 +1584,18 @@ -%7D%0A + %7D%0A @@ -3071,17 +3071,21 @@ 'top': -5 +'20%25' %7D);%0A
752352815867a7a503550c93c81ea0aed1c1d8f9
remove "map" file patterns from clean tasks
template-project/gulpfile.js
template-project/gulpfile.js
/** * Configuration */ var config = { host: 'devbox.dev', directory: 'avalanche/template-project', styles: { destination: 'dist', destinationFileName: 'avalanche.css', extractDestination: 'dist-extract', watchDirectories: ['scss/**/*'] }, scripts: { destination: 'dist', destinationFileName: 'avalanche.js', browserifyEntries: ['js/avalanche.js'], watchDirectories: ['js/**/*'] }, styleGuide: { destination: 'style-guide' }, sassOptions: { precision: 7 } }; /** * Plugins */ var browserSync = require('browser-sync').create(); var browserify = require('browserify'); var del = require('del'); var eyeglass = require('eyeglass'); var fs = require('fs'); var gulp = require('gulp'); var autoprefixer = require('gulp-autoprefixer'); var cssGlobbing = require('gulp-css-globbing'); var cssnano = require('gulp-cssnano'); var minifyCss = require('gulp-minify-css'); var postcss = require('gulp-postcss'); var rename = require('gulp-rename'); var replace = require('gulp-replace'); var sass = require('gulp-sass'); var sourcemaps = require('gulp-sourcemaps'); var uglify = require('gulp-uglify'); var buffer = require('vinyl-buffer'); var source = require('vinyl-source-stream'); /** * Styles */ gulp.task('styles:build', ['clean:styles'], function () { return gulp.src('scss/**/*.scss') .pipe(cssGlobbing({ extensions: ['.scss'], scssImportPath: { leading_underscore: false, filename_extension: false } })) .pipe(sourcemaps.init()) .pipe(sass(eyeglass(config.sassOptions)).on('error', sass.logError)) .pipe(autoprefixer()) .pipe(sourcemaps.write()) .pipe(rename(config.styles.destinationFileName)) .pipe(gulp.dest(config.styles.destination)) .pipe(browserSync.stream()); }); gulp.task('styles:extract', ['clean:styles:extract', 'styles:minify'], function () { fs.readFile(config.styles.destination + '/' + config.styles.destinationFileName, 'utf8', function (error, data) { if (error) throw error; var files = stylesExtractFiles(data); for (var fileName in files) { var fileData = files[fileName]; var fileDir = config.styles.extractDestination; var filePath = fileDir + '/' + fileName; // Create directory if it doesn't exist. if (!fs.existsSync(fileDir)){ fs.mkdirSync(fileDir); } // Create the file. fs.openSync(filePath, 'w'); fs.writeFileSync(filePath, fileData); // Create a minified version of the file. stylesMinify(filePath, fileDir); } }); }); gulp.task('styles:minify', ['styles:build'], function () { stylesMinify(config.styles.destination + '/' + config.styles.destinationFileName, config.styles.destination); }); function stylesExtractFiles(data) { var files = {}; var extractRegExp = /\/\* extract (.*?) \*\/((.|\n)*?)\/\* end extract \1 \*\//g; // Find extract placeholders in the CSS file. while (match = extractRegExp.exec(data)) { var extractFileName = match[1]; var extractFileData = match[0].replace('/* extract ' + extractFileName + ' */', '').replace('/* end extract ' + extractFileName + ' */', ''); if (!files[extractFileName]) { files[extractFileName] = ''; } // Append the file data if it already exists. files[extractFileName] += extractFileData; // Find nested extraction placeholders. var nestedFiles = stylesExtractFiles(extractFileData); for (var nestedFileName in nestedFiles) { var nestedFileData = nestedFiles[nestedFileName]; if (!files[nestedFileName]) { files[nestedFileName] = ''; } files[nestedFileName] += nestedFileData; } } return files; } function stylesMinify(files, dest) { return gulp.src(files) .pipe(minifyCss()) .pipe(replace(/[^;\{]+:[^;\}]+;?\/\*\!remove\*\//g, '')) .pipe(cssnano()) .pipe(rename(function (path) { path.basename += '.min'; })) .pipe(gulp.dest(dest)) .pipe(browserSync.stream()); } /** * Scripts */ gulp.task('scripts:build', ['clean:scripts'], function () { // Set up the browserify instance. var b = browserify({ entries: config.scripts.browserifyEntries, debug: true }); return b.bundle() .pipe(source(config.scripts.destinationFileName)) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest(config.scripts.destination)) .pipe(browserSync.stream()); }); /** * Style guide * * Create a mdcss style guide. */ gulp.task('style_guide', ['styles:minify'], function () { return gulp.src(config.styles.destination + '/' + config.styles.destinationFileName) .pipe(postcss([ require('mdcss')({ theme: require('avalanchesass_mdcss_theme')({ logo: '../logo.svg', examples: { css: ['../' + config.styles.destination + '/' + config.styles.destinationFileName], bodyjs: ['../' + config.scripts.destination + '/' + config.scripts.destinationFileName], htmlcss: '', bodycss: '' } }), destination: config.styleGuide.destination }) ])); }); /** * Clean * * Remove compiled files before regenerating them. */ gulp.task('clean:styles', function () { return del([ // Remove everything inside the destination direcotry. config.styles.destination + '/**/*.css', config.styles.destination + '/**/*.css.map' ]); }); gulp.task('clean:scripts', function () { return del([ // Remove everything inside the destination direcotry. config.styles.destination + '/**/*.js', config.styles.destination + '/**/*.js.map' ]); }); gulp.task('clean:styles:extract', function () { return del([ config.styles.extractDestination + '/**/*.css', config.styles.extractDestination + '/**/*.css.map' ]); }); /** * Watch */ gulp.task('watch', function () { browserSync.init({ proxy: config.host + '/' + config.directory }); gulp.watch(config.styles.watchDirectories, ['styles:minify']); gulp.watch(config.scripts.watchDirectories, ['scripts:build']); }); gulp.task('watch:extract', function () { browserSync.init({ proxy: config.host + '/' + config.directory }); gulp.watch(config.styles.watchDirectories, ['styles:extract']); }); gulp.task('watch:style_guide', function () { browserSync.init({ proxy: config.host + '/' + config.directory + '/' + config.styleGuide.destination }); gulp.watch(config.styles.watchDirectories, ['style_guide']); gulp.watch(config.scripts.watchDirectories, ['scripts:build']); gulp.watch(config.styleGuide.destination + '/*.html').on('change', browserSync.reload); }); /** * Default task * * Run this task with `gulp`. */ gulp.task('default', function () { gulp.start('watch'); });
JavaScript
0.000002
@@ -5437,57 +5437,8 @@ css' -,%0A config.styles.destination + '/**/*.css.map' %0A %5D @@ -5606,56 +5606,8 @@ .js' -,%0A config.styles.destination + '/**/*.js.map' %0A %5D @@ -5731,64 +5731,8 @@ css' -,%0A config.styles.extractDestination + '/**/*.css.map' %0A %5D
3c1e5417d7cf6e426577a4bf7053b78fd74db88c
change function to arrow function
mp3tracksorganizer.js
mp3tracksorganizer.js
var nodeID3 = require('node-id3'); var fs = require('fs-extra'); var mv = require('mv'); var path = require('path'); var args = process.argv.slice(2); //get arguments var mPath; //where music is if (typeof args[0] == 'undefined'){ //check if at least an argument is specified console.log("Usage: node mp3tracksorganizer path/of/files"); process.exit(1); } else{ mPath = args[0]; //set first argument as path. Other pathes will be ignored } if(!fs.existsSync(mPath)){ //check if path exist. console.log("Specified path doesn't exist"); process.exit(3); } fs.access(mPath, fs.constants.R_OK | fs.constants.W_OK, (err) => { if(err){ console.log("No read/write permission on selected folder."); process.exit(4); } }); function getFiles (dir){ //get file pathes and filenames not recursevely var filelist = {name : [],path : []}; var tmp; tmp = fs.readdirSync(dir); for (var i = 0;i<tmp.length;i++){ var fullpath = path.join(dir,tmp[i]); try{ if (fs.statSync(fullpath).isFile()){ filelist.path.push(fullpath); filelist.name.push(tmp[i]); } } catch(e){ console.log("Catched error on reading " + tmp[i] + ", probably a permission issue. Skipping."); continue; } } return filelist; } function encodePath(dir){ //remove illegal win32 chars var output = dir.replace(/[|&;$:%@"<>()+,"\\|*?]/g, "") return output; } var list = getFiles(mPath); //get filenames and pathes list var files = list.path.length; if(files == 0) { console.log("No tracks found. Closing."); process.exit(2); } for (var i = 0;i<files;i++){ //do the job var read = nodeID3.read(list.path[i]); var year = read.year; if (typeof read.album == 'undefined'){ console.log("Can't find album tag on " + list.name[i] + " file. Skipping."); continue; } if(typeof read.year == 'undefined'){ console.log("Year tag not found, so it won't be specified on folder name"); year = ''; } else{ year = read.year + ' - '; } var album = encodePath(read.album); if (!fs.existsSync(path.join(mPath , year + album))){ //check if folder exist, if not create then fs.mkdirsSync(path.join(mPath, year + album)); } console.log( path.join(mPath,year + album + list.name[i])); mv(list.path[i], path.join(mPath,year + album + '\\' + list.name[i]), //move files to created folder function(err) { if(err){ console.log(err); } }); } console.log("END");
JavaScript
0.000037
@@ -2534,22 +2534,16 @@ %0A - function (err) + =%3E %7B
928ac66cffe487ca0efd32de13da7962625d0b35
Fix comment typo.
bibleQueryParser.js
bibleQueryParser.js
"use strict" const bcvParser = require("bible-passage-reference-parser/js/en_bcv_parser").bcv_parser let bcv = resetParser() // The only exported function. It normalizes the string and returns an object with a recommended course of action. function parse(q) { // The BCV parser expects normalized UTF-8. If the query contains anything besides ASCII or punctuation, make sure it's normalized. If your environment doesn't support `String.normalize`, try https://github.com/walling/unorm . Alternately, if you're only interested in ASCII text, you could probably delete this line. q = q.normalize("NFC") const response = { q, counts: { words: 0, osis: 0, book: 0, // Not camel-cased because it's an output propery, so we want it consistent with output from `bcv_parser`. invalid_osis: 0 }, components: [], } let entities try { entities = bcv.parse(q).parsed_entities() } catch (e) { response.error = e entities = [] bcv = resetParser() } if (entities.length === 0) { noEntities(q, response) } else { handleEntities(q, entities, response) // Do a simple heuristic to recommend to the consumer how to treat the query. if (response.counts.osis > 0) { response.recommend = "osis" } else if (response.counts.words > 0) { // Queries like `John the Baptist` should be `words` rather than `osis`. response.recommend = "words" } else if (response.counts.book > 0) { response.recommend = "osis" } else if (response.counts.invalid_osis > 0) { response.recommend = "error" } else { response.recommend = "words" } } return response } // Even if there are no entities in the string, return an object in the same format that `handleEntities` produces. function noEntities(q, response) { handleQueryText(q, response, 0, q.length) response.recommend = "words" } // Loop through the query string and identify all the components, whether osis, text, or book. function handleEntities(q, entities, response) { // The current offset in string `q`. let currentIndex = 0 for (const entity of entities) { const [start, end] = entity.indices // If there's text between the current position in the string and where the entity starts, then count it as text. if (start > currentIndex) { handleQueryText(q, response, currentIndex, start) } const obj = { type: "osis", osis: entity.osis, content: q.substr(start, end - start), indices: [start, end], } // Because we're using `sequence_combination_strategy: separate`, there's only one object in `entity.entities`. if (Object.getOwnPropertyNames(entity.entities[0].valid.messages).length > 0) { obj.messages = entity.entities[0].valid.messages } // The consumer may want to treat books without references differently from regular references. if (entity.type === "b") { obj.type = "book" response.counts.book++ } else if (entity.osis === "") { obj.type = "invalid_osis" // TODO: We could do something more useful here, like make a suggestion for a correct reference. response.counts.invalid_osis++ } else { response.counts.osis++ } // Include any valid alternates. if (entity.entities[0].alternates != null) { for (const alt of entity.entities[0].alternates) { if (alt.valid.valid === false) { continue } if (!obj.alternates) { obj.alternates = [] } obj.alternates.push(makeAlternate(alt.start, alt.end)) } } response.components.push(obj) currentIndex = end } // Grab any spare text at the end of the string. if (currentIndex < q.length) { handleQueryText(q, response, currentIndex, q.length) } } // Turn the `alternate` objects into valid osises. function makeAlternate(startObj, endObj) { const start = objToOsis(startObj) const end = objToOsis(endObj) if (start === end) { return start } else { return `${start}-${end}` } } // Given an object with `b` and optional `c` and `v` keys, produce an osis. function objToOsis(obj) { let osis = obj.b if (obj.c != null) { osis += "." + obj.c if (obj.v != null) { osis += "." + obj.v } } return osis } // Extract text from the query string and increment the count if relevant. function handleQueryText(q, response, currentIndex, endIndex) { const text = extractText(q, currentIndex, endIndex) response.components.push(text) if (text.subtype === "words" || text.subtype === "other") { response.counts.words++ } } // Turn text into an object for future manipulation. function extractText(q, start, end) { const content = q.substr(start, end - start) return { type: "text", subtype: extractTextSubtype(content), content, indices: [start, end], } } // Based on the content of the string, guess whether it contains words that the consumer might want to handle. function extractTextSubtype(text) { if (/[A-Za-z0-9]/.test(text)) { return "words" } else if (/^\s+$/.test(text)) { return "space" // Latin punctuation characters and spaces. } else if (/^[\s,.?\/<>`~!@#$%^&*()\-_=+;:'"\[\]{}\\|\u2000-\u206F]+$/.test(text)) { return "punctuation" } // We could do a complicated test here to handle non-English queries and determine whether the other characters are letters or punctuation, but we don't. return "other" } function resetParser() { const parser = new bcvParser return parser.set_options({ book_sequence_strategy: "include", book_alone_strategy: "first_chapter", captive_end_digits_strategy: "include", include_apocrypha: true, invalid_passage_strategy: "include", invalid_sequence_strategy: "include", non_latin_digits_strategy: "replace", osis_compaction_strategy: "bc", sequence_combination_strategy: "separate", zero_chapter_strategy: "upgrade", zero_verse_strategy: "upgrade" }) } module.exports = parse
JavaScript
0
@@ -722,16 +722,17 @@ t proper +t y, so we
6a67cec2a8d2e607811555a612265cb8585e703b
increase min width of advanced search button
templates/advanced_search.js
templates/advanced_search.js
$( document ).ready(function() { var search_input = $('.header__search__input') var search_button = $('.header__search-button') var advanced_search = $('.advanced-search') var advanced_search_input = $('#id_adv_search') var advanced_search_button = $('.adv-filter-submit') var header_bar = $('.header') var adv_arrow = $('.adv-filter-arrow') var adv_form = $('.adv-filter-form') if ($(window).width() > 768) { header_bar.on('mouseenter', function() { advanced_search.slideDown('slow') }) $('#BelowTheBanner').on('mouseenter', function() { advanced_search.slideUp('slow') }) } if (search_input.val() !== undefined && search_input.val().trim() === "") { search_button.prop('disabled', true) } search_input.on('keyup paste change input', function() { var input = $(this) if (input.val().trim() === "") { search_button.prop('disabled', true) } else { search_button.prop('disabled', false) } }) adv_arrow.on('click', function() { var icon = $(this) if (icon.hasClass('fa-angle-up')) { adv_form.slideUp('slow') adv_arrow.toggleClass('fa-angle-up fa-angle-down') } else { $('.adv-filter-form').slideDown('slow') adv_arrow.toggleClass('fa-angle-down fa-angle-up') } }) $('[data-toggle="datepicker"]').datepicker({ format: 'dd/mm/yyyy', }); });
JavaScript
0
@@ -437,11 +437,12 @@ ) %3E -768 +1024 ) %7B%0A
85fd4305e47a7b25ffe7ae8cf8797bcca676b0ec
add withInfo decorator as global config
.storybook/config.js
.storybook/config.js
import React from "react"; import { createGlobalStyle } from "styled-components"; import { configure, addDecorator } from "@storybook/react"; const req = require.context( "../", true, /^((?![\\/]node_modules).)*\.story\.js$/ ); function loadStories() { req.keys().forEach(filename => req(filename)); } const GlobalStyle = createGlobalStyle` @font-face { font-family: 'lato'; src: url('./lato-regular-webfont.woff2') format('woff2'), url('./lato-regular-webfont.woff') format('woff'); font-weight: 400; font-style: normal; } @font-face { font-family: 'lato'; src: url('./lato-semibold-webfont.woff2') format('woff2'), url('./lato-semibold-webfont.woff') format('woff'); font-weight: 600; font-style: normal; } @font-face { font-family: 'lato'; src: url('./lato-light-webfont.woff2') format('woff2'), url('./lato-light-webfont.woff') format('woff'); font-weight: 300; font-style: normal; } @font-face { font-family: 'whatsgood-fonticon'; src: url('./whatsgood-iconfont.eot?vexkpz'); src: url('./whatsgood-iconfont.eot?vexkpz#iefix') format('embedded-opentype'), url('./whatsgood-iconfont.ttf?vexkpz') format('truetype'), url('./whatsgood-iconfont.woff?vexkpz') format('woff'), url('./whatsgood-iconfont.svg?vexkpz#whatsgood-iconfont') format('svg'); font-weight: normal; font-style: normal; } .wg-order:before { content: "\\e906"; } .wg-meat:before { content: "\\e933"; } .wg-loading:before { content: "\\e90b"; } .wg-edit:before { content: "\\e924"; } .wg-close:before { content: "\\e965"; } .wg-alert:before { content: "\\e92c"; } .wg-small-arrow-right:before { content: "\\e944"; } .wg-check:before { content: "\\e91b"; } .wg-checker:before { content: "\\e949"; } .wg-place:before { content: "\\e972"; } .wg-external-link:before { content: "\\e973"; } .wg-small-arrow-bottom:before { content: "\\e942"; } .wg-small-arrow-top:before { content: "\\e945"; } .wg-search:before { content: "\\e941"; } .wg-close-int:before { content: "\\e91d"; } .wg-purveyor:before { content: "\\e908"; } .wg-question:before { content: "\\e93d"; } .wg-add:before { content: "\\e90f"; } .wg-minus:before { content: "\\e974"; } .wg-location:before { content: "\\e931"; } .wg-check-box:before { content: "\\e978"; } .wg-order, .wg-meat, .wg-loading, .wg-close, .wg-alert, .wg-small-arrow-right, .wg-check, .wg-checker, .wg-edit, .wg-place, .wg-external-link, .wg-small-arrow-bottom, .wg-small-arrow-top, .wg-search, .wg-close-int, .wg-purveyor, .wg-question, .wg-minus, .wg-add, .wg-location, .wg-check-box { /* use !important to prevent issues with browser extensions that change fonts */ font-family: 'whatsgood-fonticon' !important; speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; /* Better Font Rendering =========== */ -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } `; function withGlobalStyle(storyFn) { return ( <React.Fragment> <GlobalStyle /> {storyFn()} </React.Fragment> ); } addDecorator(withGlobalStyle); configure(loadStories, module);
JavaScript
0.000001
@@ -134,16 +134,66 @@ /react%22; +%0Aimport %7B withInfo %7D from %22@storybook/addon-info%22; %0A%0Aconst @@ -3365,16 +3365,40 @@ );%0A%7D%0A%0A +addDecorator(withInfo);%0A addDecor
f7c0e61e1addeb91a1901f2180ccaf4eedf9f006
remove unused imports
src/components/services/content/ServiceView.js
src/components/services/content/ServiceView.js
import React, { Component, Fragment } from 'react'; import PropTypes from 'prop-types'; import { autorun } from 'mobx'; import { observer } from 'mobx-react'; import classnames from 'classnames'; import ServiceModel from '../../../models/Service'; import StatusBarTargetUrl from '../../ui/StatusBarTargetUrl'; import WebviewLoader from '../../ui/WebviewLoader'; import WebviewCrashHandler from './WebviewCrashHandler'; import WebviewErrorHandler from './ErrorHandlers/WebviewErrorHandler'; import ServiceDisabled from './ServiceDisabled'; import ServiceRestricted from './ServiceRestricted'; import WebControlsScreen from '../../../features/webControls/containers/WebControlsScreen'; import { CUSTOM_WEBSITE_ID } from '../../../features/webControls/constants'; export default @observer class ServiceView extends Component { static propTypes = { service: PropTypes.instanceOf(ServiceModel).isRequired, reload: PropTypes.func.isRequired, edit: PropTypes.func.isRequired, enable: PropTypes.func.isRequired, isActive: PropTypes.bool, upgrade: PropTypes.func.isRequired, }; static defaultProps = { isActive: false, }; state = { forceRepaint: false, targetUrl: '', statusBarVisible: false, }; autorunDisposer = null; forceRepaintTimeout = null; componentDidMount() { this.autorunDisposer = autorun(() => { if (this.props.service.isActive) { this.setState({ forceRepaint: true }); this.forceRepaintTimeout = setTimeout(() => { this.setState({ forceRepaint: false }); }, 100); } }); } componentWillUnmount() { this.autorunDisposer(); clearTimeout(this.forceRepaintTimeout); } updateTargetUrl = (event) => { let visible = true; if (event.url === '' || event.url === '#') { visible = false; } this.setState({ targetUrl: event.url, statusBarVisible: visible, }); }; render() { const { service, reload, edit, enable, upgrade, } = this.props; const webviewClasses = classnames({ services__webview: true, 'services__webview-wrapper': true, 'is-active': service.isActive, 'services__webview--force-repaint': this.state.forceRepaint, 'is-loaded': service.isEnabled && !service.isFirstLoad, }); let statusBar = null; if (this.state.statusBarVisible) { statusBar = ( <StatusBarTargetUrl text={this.state.targetUrl} /> ); } return ( <div className={webviewClasses}> {service.isActive && service.isEnabled && ( <Fragment> {service.hasCrashed && ( <WebviewCrashHandler name={service.recipe.name} webview={service.webview} reload={reload} /> )} {service.isEnabled && service.isLoading && service.isFirstLoad && !service.isServiceAccessRestricted && ( <WebviewLoader loaded={false} name={service.name} /> )} {service.isError && ( <WebviewErrorHandler name={service.recipe.name} errorMessage={service.errorMessage} reload={reload} edit={edit} /> )} </Fragment> )} {!service.isEnabled ? ( <Fragment> {service.isActive && ( <ServiceDisabled name={service.recipe.name} webview={service.webview} enable={enable} /> )} </Fragment> ) : ( <> {service.isServiceAccessRestricted && ( <ServiceRestricted name={service.recipe.name} upgrade={upgrade} type={service.restrictionType} /> )} </> )} {statusBar} </div> ); } }
JavaScript
0.000001
@@ -589,177 +589,8 @@ ed'; -%0Aimport WebControlsScreen from '../../../features/webControls/containers/WebControlsScreen';%0Aimport %7B CUSTOM_WEBSITE_ID %7D from '../../../features/webControls/constants'; %0A%0Aex
c63ac7e7df9759e754c5b907bf2847b339ceb59e
Update run.js
AI/script/run.js
AI/script/run.js
var ai ={}; var fallback ="/"; function Run(){ ai.input = document.createElement('input'); ai[input].setAttribute("style", "width: 600px; height: 300px;"); document.body.appendChild(ai[input]); }
JavaScript
0.000001
@@ -1,12 +1,39 @@ +alert(%22loaded: No errors%22)%0A var ai =%7B%7D;%0A
73e1ecdcc28c6779d14343ae95278163c4dcb893
Update benchmarks
lib/node_modules/@stdlib/random/base/laplace/benchmark/benchmark.js
lib/node_modules/@stdlib/random/base/laplace/benchmark/benchmark.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var bench = require( '@stdlib/bench' ); var randu = require( '@stdlib/random/base/randu' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var EPS = require( '@stdlib/constants/math/float64-eps' ); var pkg = require( './../package.json' ).name; var laplace = require( './../lib' ); // MAIN // bench( pkg, function benchmark( b ) { var scale; var mu; var z; var i; b.tic(); for ( i = 0; i < b.iterations; i++ ) { mu = ( randu()*100.0 ) - 50.0; scale = ( randu()*20.0 ) + EPS; z = laplace( mu, scale ); if ( isnan( z ) ) { b.fail( 'should not return NaN' ); } } b.toc(); if ( isnan( z ) ) { b.fail( 'should not return NaN' ); } b.pass( 'benchmark finished' ); b.end(); }); bench( pkg+':factory', function benchmark( b ) { var scale; var rand; var mu; var z; var i; mu = 0.0; scale = 1.5; rand = laplace.factory( mu, scale ); b.tic(); for ( i = 0; i < b.iterations; i++ ) { z = rand(); if ( isnan( z ) ) { b.fail( 'should not return NaN' ); } } b.toc(); if ( isnan( z ) ) { b.fail( 'should not return NaN' ); } b.pass( 'benchmark finished' ); b.end(); });
JavaScript
0.000001
@@ -1368,16 +1368,17 @@ ( pkg+': +: factory' @@ -1747,28 +1747,451 @@ finished' );%0A%09b.end();%0A%7D);%0A +%0Abench( pkg+'::factory,arguments', function benchmark( b ) %7B%0A%09var scale;%0A%09var rand;%0A%09var mu;%0A%09var z;%0A%09var i;%0A%0A%09mu = 0.0;%0A%09scale = 1.5;%0A%09rand = laplace.factory();%0A%0A%09b.tic();%0A%09for ( i = 0; i %3C b.iterations; i++ ) %7B%0A%09%09z = rand( mu, scale );%0A%09%09if ( isnan( z ) ) %7B%0A%09%09%09b.fail( 'should not return NaN' );%0A%09%09%7D%0A%09%7D%0A%09b.toc();%0A%09if ( isnan( z ) ) %7B%0A%09%09b.fail( 'should not return NaN' );%0A%09%7D%0A%09b.pass( 'benchmark finished' );%0A%09b.end();%0A%7D);%0A
a3d7e4ce54be40f91793b0ab61fe0e2422fe0688
Use touchend as click when drawing lines
client/DrawTogheter.js
client/DrawTogheter.js
function DrawTogheter (container, server) { this.container = container; this.container.style.position = "relative"; this.background = container.appendChild(document.createElement("canvas")); this.canvas = container.appendChild(document.createElement("canvas")); this.effects = container.appendChild(document.createElement("canvas")); this.setCanvasPosition(this.canvas); this.setCanvasPosition(this.effects); this.ctx = this.canvas.getContext("2d"); this.bCtx = this.background.getContext("2d"); this.eCtx = this.effects.getContext("2d"); this.drawings = []; this.localDrawings = []; window.addEventListener("resize", this.resizeHandler.bind(this)); this.effects.addEventListener("click", this.callTool.bind(this)); this.effects.addEventListener("mousedown", this.callTool.bind(this)); this.effects.addEventListener("mouseup", this.callTool.bind(this)); this.effects.addEventListener("mousemove", this.callTool.bind(this)); this.effects.addEventListener("touchstqrt", this.callTool.bind(this)); this.effects.addEventListener("touchend", this.callTool.bind(this)); this.effects.addEventListener("touchmove", this.callTool.bind(this)); this.setTool("brush"); this.setToolSize("5"); this.setToolColor("#F0BC11"); this.resizeHandler(); //this.connect(server); } DrawTogheter.prototype.setCanvasPosition = function setCanvasPosition (canvas) { canvas.style.position = "absolute"; canvas.style.left = "0"; canvas.style.top = "0"; }; DrawTogheter.prototype.connect = function connect (server) { this.socket = io(server); this.socket.on("drawing", this.drawing); }; DrawTogheter.prototype.setTool = function setTool (tool) { if (typeof this.tools[this.tool] === "function") { this.tools[this.tool].call(this, "remove"); } this.tool = tool; }; DrawTogheter.prototype.setToolSize = function setToolSize (size) { this.toolSize = size; }; DrawTogheter.prototype.setToolColor = function setToolColor (color) { this.toolColor = color; }; DrawTogheter.prototype.drawLine = function (ctx, sx, sy, ex, ey, size, color) { ctx.beginPath(); ctx.moveTo(sx, sy); ctx.lineTo(ex, ey); ctx.lineWidth = size; ctx.strokeStyle = color; ctx.stroke(); }; DrawTogheter.prototype.drawDot = function (ctx, x, y, size, color) { ctx.beginPath(); ctx.arc(x, y, size, 0, 2*Math.PI); ctx.fillStyle = color; ctx.fill(); }; DrawTogheter.prototype.drawing = function (data) { }; DrawTogheter.prototype.tools = {}; DrawTogheter.prototype.tools.grab = function (event) { }; DrawTogheter.prototype.tools.line = function (event) { if (typeof event !== 'object') { if (event === 'remove') { this.eCtx.clearRect(0, 0, this.effects.width, this.effects.height); delete this.linePoint; } return; } var clientX = (event.clientX || event.changedTouches[0].clientX), clientY = (event.clientY || event.changedTouches[0].clientY), target = event.target || document.elementFromPoint(clientX, clientY), boundingBox = target.getBoundingClientRect(), relativeX = clientX - boundingBox.left, relativeY = clientY - boundingBox.top; if (event.type === 'click') { if (this.linePoint) { this.addNewLine(this.linePoint, [relativeX, relativeY]); delete this.linePoint; } else { this.linePoint = [relativeX, relativeY]; } } if ((event.type === 'mousemove' || event.type === 'touchmove') && this.linePoint) { this.eCtx.clearRect(0, 0, this.effects.width, this.effects.height); this.drawLine(this.eCtx, this.linePoint[0], this.linePoint[1], relativeX, relativeY, this.toolSize, this.toolColor); event.preventDefault(); } }; DrawTogheter.prototype.tools.brush = function (event) { }; DrawTogheter.prototype.callTool = function () { if (typeof this.tools[this.tool] === "function") { this.tools[this.tool].apply(this, arguments); } }; DrawTogheter.prototype.resizeHandler = function () { this.background.width = this.container.offsetWidth; this.background.height = this.container.offsetHeight; this.canvas.width = this.container.offsetWidth; this.canvas.height = this.container.offsetHeight; this.effects.width = this.container.offsetWidth; this.effects.height = this.container.offsetHeight; };
JavaScript
0
@@ -3095,16 +3095,45 @@ 'click' + %7C%7C event.type === 'touchend' ) %7B%0A%09%09if
70655120cb2a51756c240c46ac0206aa28c81631
Add ctcp to constants, adds to auto-complete
client/js/constants.js
client/js/constants.js
"use strict"; const commands = [ "/away", "/back", "/ban", "/banlist", "/close", "/connect", "/deop", "/devoice", "/disconnect", "/invite", "/join", "/kick", "/leave", "/me", "/mode", "/msg", "/nick", "/notice", "/op", "/part", "/query", "/quit", "/raw", "/say", "/send", "/server", "/slap", "/topic", "/unban", "/voice", "/whois" ]; module.exports = { commands: commands };
JavaScript
0
@@ -93,16 +93,26 @@ nnect%22,%0A +%09%22/ctcp%22,%0A %09%22/deop%22
588255e3f1e2457d6c5a368c9059bf7a05b1c358
Add doc for new property.
Source/Core/throttleRequestByServer.js
Source/Core/throttleRequestByServer.js
/*global define*/ define([ '../ThirdParty/Uri', '../ThirdParty/when', './defaultValue' ], function( Uri, when, defaultValue) { "use strict"; var activeRequests = {}; var pageUri = new Uri(document.location.href); function getServer(url) { var uri = new Uri(url).resolve(pageUri); uri.normalize(); var server = uri.authority; if (!/:/.test(server)) { server = server + ':' + (uri.scheme === 'https' ? '443' : '80'); } return server; } /** * Because browsers throttle the number of parallel requests allowed to each server, * this function tracks the number of active requests in progress to each server, and * returns undefined immediately if the request would exceed the maximum, allowing * the caller to retry later, instead of queueing indefinitely under the browser's control. * * @exports throttleRequestByServer * * @param {String} url The URL to request. * @param {throttleRequestByServer~RequestFunction} requestFunction The actual function that * makes the request. * @returns {Promise} Either undefined, meaning the request would exceed the maximum number of * parallel requests, or a Promise for the requested data. * * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A} * * @example * // throttle requests for an image * var url = 'http://madeupserver.example.com/myImage.png'; * var requestFunction = function(url) { * // in this simple example, loadImage could be used directly as requestFunction. * return Cesium.loadImage(url); * }; * var promise = Cesium.throttleRequestByServer(url, requestFunction); * if (!Cesium.defined(promise)) { * // too many active requests in progress, try again later. * } else { * promise.then(function(image) { * // handle loaded image * }); * } */ var throttleRequestByServer = function(url, requestFunction) { var server = getServer(url); var activeRequestsForServer = defaultValue(activeRequests[server], 0); if (activeRequestsForServer >= throttleRequestByServer.maximumRequestsPerServer) { return undefined; } activeRequests[server] = activeRequestsForServer + 1; return when(requestFunction(url), function(result) { activeRequests[server]--; return result; }).otherwise(function(error) { activeRequests[server]--; return when.reject(error); }); }; throttleRequestByServer.maximumRequestsPerServer = 6; /** * A function that will make a request if there are available slots to the server. * @callback throttleRequestByServer~RequestFunction * * @param {String} url The url to request. * @returns {Promise} A promise for the requested data. */ return throttleRequestByServer; });
JavaScript
0
@@ -2671,24 +2671,363 @@ %7D);%0A %7D;%0A%0A + /**%0A * Specifies the maximum number of requests that can be simultaneously open to a single server. If this value is higher than%0A * the number of requests per server actually allowed by the web browser, Cesium's ability to prioritize requests will be adversely%0A * affected.%0A * @type %7BNumber%7D%0A * @default 6%0A */%0A throttle
6d9522626f708e507791531a11f62582d03d05b0
fix pay password not reset success
src/app/components/forget/forget.controller.js
src/app/components/forget/forget.controller.js
'use strict'; angular.module('csyywx') .controller('ForgetPasswordCtrl', function($scope, $state, $stateParams, $ionicLoading, UserApi, userConfig, utils, settingService) { var resendCountdown = utils.resendCountdown($scope); $scope.pay = +$stateParams.type === 3; // 3支付 $scope.user = { phone: $stateParams.phone || userConfig.getUser().phone, invalidVcode: false, approach: $stateParams.type, certificateNumber: '' }; $scope.sendVcode = function() { $ionicLoading.show(); UserApi.sendCheckCode($scope.user) .success(function(data) { $ionicLoading.hide(); if(+data.flag === 1) { resendCountdown(); $scope.user.sessionId = data.data.sessionId; } }); }; $scope.submit = function() { $ionicLoading.show(); UserApi.securityCheck({ sessionId: $scope.user.sessionId, phone: $scope.user.phone, certificateNumber: $scope.pay ? $scope.user.certificateNumber : '', // id, for retrieve pay password checkCode: $scope.user.vcode, // 2015, for dev test, type: +$stateParams.type-1 // 1:login, 2: pay }).success(function(data) { $ionicLoading.hide(); console.log(data); if (+data.flag === 1) { if ($scope.pay) { $state.go('tabs.retrievePayPassword'); } else { console.log($scope.user.phone) userConfig.setSessionId(data.data.sessionId); $state.go('tabs.retrievePassword', { phone: $scope.user.phone }); } } else { alert(data.msg) } }); }; }) ;
JavaScript
0.000004
@@ -1292,32 +1292,88 @@ a.flag === 1) %7B%0A + userConfig.setSessionId(data.data.sessionId);%0A if ($s @@ -1458,109 +1458,8 @@ e %7B%0A - console.log($scope.user.phone)%0A userConfig.setSessionId(data.data.sessionId);%0A @@ -1601,22 +1601,63 @@ -alert(data.msg +utils.alert(%7B%0A content: data.msg%0A %7D )%0A
27cce1446cea7d7691621da3165e176ad30e2f86
Add descriptions to transformation/file/options/index
src/babel/transformation/file/options/index.js
src/babel/transformation/file/options/index.js
import * as parsers from "./parsers"; import config from "./config"; export { config }; /** * [Please add a description.] */ export function validateOption(key, val, pipeline) { var opt = config[key]; var parser = opt && parsers[opt.type]; if (parser && parser.validate) { return parser.validate(key, val, pipeline); } else { return val; } } /** * [Please add a description.] */ export function normaliseOptions(options = {}) { for (var key in options) { var val = options[key]; if (val == null) continue; var opt = config[key]; if (!opt) continue; var parser = parsers[opt.type]; if (parser) val = parser(val); options[key] = val; } return options; }
JavaScript
0
@@ -94,35 +94,27 @@ %0A * -%5BPlease add a descri +Validate an o ption. -%5D %0A */ @@ -362,35 +362,30 @@ %0A * -%5BPlease add a descri +Normalize all o ption +s . -%5D %0A */
5c00463296d8564298ccf9f3f346247a4929a0a9
fix get message error
server/src/utils/chatHelper.js
server/src/utils/chatHelper.js
'use strict' const Promise = require("bluebird"); let ServerHelper = require('./serverHelper'); module.exports = class ChatHelper { constructor(db) { this.database = db; this.serverHelper = new ServerHelper(db); } getSessions(userId) { return new Promise((resolve,reject)=>{ this.database.collection('users').findOneAsync({ _id: userId }) .then(userData => { if(userData===null){ resolve(null) } else { this.resolveSessionObject(userData.sessions) .then(sessionMap => { var sessions = userData.sessions.map((id) => sessionMap[id]); resolve(sessions); }) } }) .catch(err => {reject(err)}) }) } resolveSessionObject(sessionList) { return new Promise((resolve, reject) => { if (sessionList.length === 0) { resolve({}); } else { var query = { $or: sessionList.map((id) => { return {_id: id} }) }; // Resolve 'like' counter this.database.collection('messageSession').findAsync(query) .then(cursor => { return cursor.toArrayAsync(); }) .then(sessions => { var sessionMap = {}; sessions.forEach((session) => { sessionMap[session._id] = session; }); resolve(sessionMap); }) .catch(err => {reject(err)}); } }); } getMessage(time, sessionId) { return new Promise((resolve, reject)=>{ this.database.collection('message').aggregateAsync([ {$match: { _id: sessionId}}, {$unwind: "$messages"}, {$match:{"messages.date":{$lt:parseInt(time)}}}, {$sort:{"messages.date":-1}}, {$limit:10} ]) .then(cursor=>{return cursor.toArray();}) .then(messages=>{ if(messages.length===0){ resolve(messages); } else{ var resultMsgs = messages.map((message)=>{ return message.messages; }); resultMsgs = resultMsgs.reverse(); var userList = [resultMsgs[0].sender, resultMsgs[0].target]; this.serverHelper.resolveUserObjects(userList, (err, userMap)=>{ if (err) reject(err); resultMsgs.forEach((message) => { message.target = userMap[message.target]; message.sender = userMap[message.sender]; }); resolve(resultMsgs); }) } }) .catch(err=>reject(err)); }) } getSession(userid, targetid) { return new Promise((resolve,reject)=>{ this.database.collection("messageSession").findOneAsync({ users: { $all: [userid, targetid] } }) .then(session=>{ resolve(session); }) .catch(err=>reject(err)); }) } getSessionContentsID(sessionid, cb) { this.database.collection("messageSession").findOneAsync({ _id: sessionid }) .then(session=>{ cb(null, session.contents); }) .catch(err=>cb(err)); } createSession(userid, targetid, cb){ this.database.collection("message").insertOneAsync({ messages:[] }) .then(message=>{ var newSession = { users : [userid, targetid], contents: message.insertedId, lastmessage : {} }; return newSession; }) .then(newSession=>{ this.database.collection("messageSession").insertOneAsync(newSession) .then(messageSession=>{ this.database.collection("users").updateMany({ $or:[ {_id:userid}, {_id:targetid} ] },{$addToSet:{ sessions: messageSession.insertedId }},function(err){ if(err) cb(err) else{ cb(null,newSession); } }) }) .catch(err=>cb(err)); }) .catch(err=>cb(err)); } }
JavaScript
0.000002
@@ -2117,16 +2117,18 @@ Int(time ++1 )%7D%7D%7D,%0A
b36cf33fd0d5de9e7d155a200f984cc957464a07
Update ismobile.js
javascript/ismobile.js
javascript/ismobile.js
//look for Mobile Device browsers var isMobile = { Android: function() { return navigator.userAgent.match(/Android/i); }, BlackBerry: function() { return navigator.userAgent.match(/BlackBerry/i); }, iOS: function() { return navigator.userAgent.match(/Potato|iPad|iPod/i); }, Opera: function() { return navigator.userAgent.match(/Opera Mini/i); }, Windows: function() { return navigator.userAgent.match(/IEMobile/i); }, any: function() { return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows()); } }; //if any mobile device is detected change to mobile.css if(isMobile.any()) { document.getElementById('style').setAttribute('href', '/css/mobile.css'); } if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) { if (document.cookie.indexOf("iphone_redirect=false") == -1) document.getElementById('style').setAttribute('href', '/css/mobile.css'); }
JavaScript
0.000193
@@ -837,16 +837,17 @@ if( +! isMobile
ebe2503dd548c0f26521ee6e96245d41a6bf9e0b
remove sensitive field from export as it is not needed (#704)
server/tasks/AtlasBspbStats.js
server/tasks/AtlasBspbStats.js
const { api } = require('actionhero') const PublicStatTask = require('../classes/PublicStatTask') const { QueryTypes } = require('sequelize') module.exports = class AtlasBspbStats extends PublicStatTask { constructor () { super() this.name = 'AtlasBspbStats' this.description = 'Export atlas statistics for use on bspb.org' // use cronjob to schedule the task // npm run enqueue AtlasBspbStats this.frequency = 0 } async generateStats (data, worker) { return { atlas_bspb_summer_species: api.sequelize.sequelize.query(` SELECT DISTINCT b.bgatlas2008_utm_code AS "utmCode", b.species AS "specLat", s."labelBg" AS "specBG", s."labelEn" AS "specEN", s.sensitive FROM "birds_observations" b JOIN "Species" s ON (b.species = s."labelLa" AND s.type = 'birds' AND NOT s.sensitive) WHERE ( date_part('month', b.start_datetime) = 4 OR date_part('month', b.start_datetime) = 5 OR date_part('month', b.start_datetime) = 6 OR (date_part('month', b.start_datetime) = 7 AND date_part('day', b.start_datetime) <= 15) ) AND b.start_datetime >= '2016-04-01 00:00:00.000+00' AND b.bgatlas2008_utm_code IS NOT NULL AND b.bgatlas2008_utm_code != '' `, { type: QueryTypes.SELECT }), atlas_bspb_winter_species: api.sequelize.sequelize.query(` SELECT DISTINCT b.bgatlas2008_utm_code AS "utmCode", b.species AS "specLat", s."labelBg" AS "specBG", s."labelEn" AS "specEN", s.sensitive FROM "birds_observations" b JOIN "Species" s ON (b.species = s."labelLa" AND s.type = 'birds' AND NOT s.sensitive) WHERE ( date_part('month', b.observation_date_time) = 12 OR date_part('month', b.observation_date_time) = 1 OR date_part('month', b.observation_date_time) = 2 ) AND b.start_datetime >= '2016-01-01 00:00:00.000+00' AND b.bgatlas2008_utm_code IS NOT NULL AND b.bgatlas2008_utm_code != '' `, { type: QueryTypes.SELECT }) } } }
JavaScript
0
@@ -741,34 +741,8 @@ cEN%22 -,%0A s.sensitive %0A @@ -1661,34 +1661,8 @@ cEN%22 -,%0A s.sensitive %0A
756796de8d54d3482daa86f701129eb443f2ed76
fix typo
mods/eventNewMember.js
mods/eventNewMember.js
module.exports = { name: "New Member", event: "guildMemberAdd", task: (member) => { if (member.guild.id == "261878898290196491") { member .send(`Welcome ${member.toString()} to **Live Mapping Project**!` + `\n` + `\nYou are currently in probation to look over the server rules.` + `\nYou can read them at <#421546926803124224>. Please wait patiently as it will expire in 5 minutes.` + `\nPlease follow them as they will be your guide and lifeline to this server.` + `\n` + `\nThis has been Kokoro, Happy! Lucky! Smile! Hooray!`); member.addRole(member.guild.roles.find("name", "Limited"), "A new member joined."); setTimeout(() => { if (member) { member.send("Your probation has ended and you can now talk. Don't forget to say hi to us!"); member.removeRole(member.guild.roles.find("name", "Limited"), "Probation expired."); member.addRole(member.guild.roles.find("name", "Member"), "Probation expired."); } }, 300000); } } }
JavaScript
0.999991
@@ -1152,16 +1152,17 @@ %22Member +s %22), %22Pro
8d74b9e2ec7a0c1cbcc101e26a876fb6a7eac36a
call app chat not chat-sharelatex
services/chat/app/js/server.js
services/chat/app/js/server.js
/* eslint-disable no-unused-vars, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const metrics = require('metrics-sharelatex') metrics.initialize('chat') const logger = require('logger-sharelatex') logger.initialize('chat-sharelatex') const Path = require('path') const express = require('express') const app = express() const server = require('http').createServer(app) const Router = require('./router') app.use(express.bodyParser()) app.use(metrics.http.monitor(logger)) metrics.injectMetricsRoute(app) if (app.get('env') === 'development') { console.log('Development Enviroment') app.use(express.errorHandler({ dumpExceptions: true, showStack: true })) } if (app.get('env') === 'production') { console.log('Production Enviroment') app.use(express.logger()) app.use(express.errorHandler()) } const profiler = require('v8-profiler') app.get('/profile', function(req, res) { const time = parseInt(req.query.time || '1000') profiler.startProfiling('test') return setTimeout(function() { const profile = profiler.stopProfiling('test') return res.json(profile) }, time) }) Router.route(app) module.exports = { server, app }
JavaScript
0.000001
@@ -468,27 +468,16 @@ ze('chat --sharelatex ')%0Aconst
d6f2f871e475e3a2da21279f013fbf4a6f5cdaca
remove extra requirement code
benchmark/performance.js
benchmark/performance.js
var args = require('optimist').argv; var util = require('util'); var path = require('path'); global.LIKELIHOOD_OF_REJECTION = args.e || 0.1; global.triggerIntentionalError = function(){ if(LIKELIHOOD_OF_REJECTION && Math.random() <= LIKELIHOOD_OF_REJECTION) throw new Error("intentional failure"); } function printPlatform() { console.log("\nPlatform info:"); var os = require("os"); var v8 = process.versions.v8; var node = process.versions.node; var plat = os.type() + " " + os.release() + " " + os.arch() + "\nNode.JS " + node + "\nV8 " + v8; var cpus = os.cpus().map(function(cpu){ return cpu.model; }).reduce(function(o, model){ if( !o[model] ) o[model] = 0; o[model]++; return o; }, {}); cpus = Object.keys(cpus).map(function( key ){ return key + " \u00d7 " + cpus[key]; }).join("\n"); console.log(plat + "\n" + cpus + "\n"); } var perf = module.exports = function(args, done) { var errs = 0; var lastErr; var times = args.n; global.asyncTime = args.t; global.parallelQueries = args.p || 10; if (args.longStackSupport) { global.longStackSupport = require('q').longStackSupport = args.longStackSupport; require('bluebird').longStackTraces(); } var fn = require(args.file); var start = Date.now(); var warmedUp = 0; var tot = Math.min( 350, times ); for (var k = 0, kn = tot; k < kn; ++k) fn(k,'b','c', warmup); var memMax; var memStart; var start; function warmup() { warmedUp++ if( warmedUp === tot ) { start = Date.now(); memStart = process.memoryUsage().rss; for (var k = 0, kn = args.n; k < kn; ++k) fn(k, 'b', 'c', cb); memMax = process.memoryUsage().rss; } } function cb (err) { if (err && err.message !== "intentional failure") { ++errs; lastErr = err; } memMax = Math.max(memMax, process.memoryUsage().rss); if (!--times) { fn.end && fn.end(); done(null, { time: Date.now() - start, mem: (memMax - memStart)/1024/1024, errors: errs, lastErr: lastErr ? lastErr.stack : null }); } } } function report(err, res) { console.log(JSON.stringify(res)); } if (args.file) { perf(args, function(err, res) { report(err, res); if (res.lastErr) console.error(res.lastErr); }); } else { var cp = require('child_process') var async = require('async'); var fs = require('fs'); var dir = __dirname + '/examples'; var table = require('text-table'); var files = args._.filter(function(f) { return !/^src-/.test(path.basename(f)); }); measure(files, args.n, args.t, args.p, function(err, res) { console.log(""); console.log("results for", args.n, "parallel executions,", args.t, "ms per I/O op"); if(args.e) console.log("Likelihood of rejection:", args.e); res.sort(function(r1, r2) { return parseFloat(r1.data.time) - parseFloat(r2.data.time) }); console.log(""); res = res.map(function(r) { var failText = 'OOM'; if (r.data.timeout) failText = 'T/O'; return [path.basename(r.file), r.data.mem != null ? r.data.time: failText, r.data.mem != null ? r.data.mem.toFixed(2) : failText] }); res = [['file', 'time(ms)', 'memory(MB)']].concat(res) console.log(table(res, {align: ['l', 'r', 'r']})); printPlatform(); }); } function measure(files, requests, time, parg, callback) { async.mapSeries(files, function(f, done) { console.log("benchmarking", f); var logFile = path.basename(f) + ".log"; var profileFlags = ["--prof", "--logfile=C:/etc/v8/" + logFile]; var argsFork = [__filename, '--n', requests, '--t', time, '--p', parg, '--file', f]; if (args.profile) argsFork = profileFlags.concat(argsFork); if (args.harmony) argsFork.unshift('--harmony'); if (args.longStackSupport) argsFork.push('--longStackSupport'); var p = cp.spawn(process.execPath, argsFork); var complete = false, timedout = false; if (args.timeout) setTimeout(function() { if (complete) return; timedout = true; p.kill(); }, args.timeout); var r = { file: f, data: [] }; p.stdout.on('data', function(d) { r.data.push(d.toString()); }); p.stdout.pipe(process.stdout); p.stderr.pipe(process.stderr); p.stdout.on('end', function(code) { complete = true; try { r.data = JSON.parse(r.data.join('')); } catch(e) { r.data = {time: Number.POSITIVE_INFINITY, mem: null, missing: true, timeout: timedout}; } done(null, r); }); }, callback); }
JavaScript
0.000002
@@ -36,37 +36,8 @@ v;%0A%0A -var util = require('util');%0A%0A var
9628a3ff4d6722dd73abc4afae0427ae32b29331
Modify fetchHotArticles
sources/javascripts/fetchHotArticles.js
sources/javascripts/fetchHotArticles.js
document.addEventListener('DOMContentLoaded', () => { const hotArticlesEl = document.getElementById('hotArticles'); const partialLiTemplate = ` <li class="hotArticles__body__articles__item"> <a href=":url" class="hotArticles__body__articles__item__link" > <div class="hotArticles__body__articles__item__link__image" style="background-image: url(:image)" ></div> <div class="hotArticles__body__articles__item__link__meta"> <span class="hotArticles__body__articles__item__link__meta__title"> <span> :title </span> <img src="http://b.hatena.ne.jp/entry/image/:url" alt="はてなブックマーク - :title" title="はてなブックマーク - :title" > </span> </div> </a> </li> `; const appendHotArticle = ({ title, url, images }) => { const partialHtml = partialLiTemplate .replace(/\:title/g, title) .replace(/\:url/g, url) .replace(/\:image/g, images[0]); hotArticlesEl.innerHTML = hotArticlesEl.innerHTML + partialHtml; }; google.load('feeds', '1', { callback() { const feed = new google.feeds.Feed( `http://b.hatena.ne.jp/entrylist?mode=rss&sort=count&url=http://axross.me/` ); feed.setNumEntries(5); feed.load(result => { if (result.err) return console.error(err); result.feed.entries .map(entry => { return { title: entry.title, url: entry.link, images: entry.content.match(/https?:\/\/[^"]+\.(gif|jpg|png)/g), publishedAt: new Date(entry.publishedDate), }; }) .forEach(entry => appendHotArticle(entry)); }); }, }); });
JavaScript
0.000001
@@ -1360,24 +1360,64 @@ url= -http://axross. +$%7Bwindow.location.protocol%7D//$%7Bwindow.location.hostna me +%7D /%60%0A
b32a0ed3e0cfbc9354f0d4b7f3c75221185cd444
Make all button ripples more prominent
shared/common-adapters/button.desktop.js
shared/common-adapters/button.desktop.js
/* @flow */ import React, {Component} from 'react' import {FlatButton} from 'material-ui' import ProgressIndicator from './progress-indicator' import {globalStyles, globalColors} from '../styles/style-guide' import type {Props} from './button' class Button extends Component { props: Props; _styles (type: Props.type): Object { let backgroundStyle = {} let labelStyle = {} let progressColor = globalColors.white const disabled = this.props.disabled || this.props.waiting switch (this.props.type) { case 'Primary': backgroundStyle = { ...stylesButtonPrimary, opacity: disabled ? stylesButtonPrimary.disabledOpacity : 1 } break case 'Follow': backgroundStyle = { ...stylesButtonFollow, opacity: disabled ? stylesButtonFollow.disabledOpacity : 1 } break case 'Following': backgroundStyle = { ...stylesButtonFollowing, opacity: disabled ? stylesButtonFollowing.disabledOpacity : 1 } labelStyle = { color: globalColors.green } progressColor = globalColors.black_75 break case 'Unfollow': backgroundStyle = { ...stylesButtonUnfollow, opacity: disabled ? stylesButtonUnfollow.disabledOpacity : 1 } break case 'Danger': backgroundStyle = { ...stylesButtonDanger, opacity: disabled ? stylesButtonDanger.disabledOpacity : 1 } break case 'Secondary': default: backgroundStyle = { ...stylesButtonSecondary, backgroundColor: this.props.backgroundMode === 'Terminal' ? globalColors.blue_30 : stylesButtonSecondary.backgroundColor, opacity: disabled ? stylesButtonSecondary.disabledOpacity : 1 } labelStyle = { color: this.props.backgroundMode === 'Terminal' ? globalColors.white : globalColors.black_75 } progressColor = globalColors.black_75 } return {backgroundStyle, labelStyle, progressColor} } render () { // First apply styles for the main button types. let {backgroundStyle, labelStyle, progressColor} = this._styles(this.props.type) let smallStyle = {} // Then some overrides that apply to all button types. if (this.props.small) { smallStyle = stylesButtonSmall labelStyle = { ...labelStyle, ...stylesButtonSmallLabel } } if (this.props.waiting) { labelStyle = { ...labelStyle, opacity: 0 } } let outerStyle = {position: 'relative'} if (this.props.style) { outerStyle = {...outerStyle, alignSelf: this.props.style.alignSelf} } if (this.props.fullWidth) { // Using minWidth here means we can't have a full-width button on the // same line/row as another button, the right thing is very unlikely to // happen. The alternative is 'flex: 1' here, which would work but is // dangerous, because we'd be modifying our container. // // So let's just say that a fullWidth button can't have siblings. outerStyle = {...outerStyle, minWidth: '100%'} backgroundStyle = {...backgroundStyle, minWidth: '100%', height: 38} } if (this.props.waiting) { outerStyle = {...outerStyle, cursor: 'wait'} } let label = this.props.label if (this.props.more) { label = '•••' } return ( <div style={outerStyle}> <FlatButton onClick={this.props.onClick} style={{...backgroundStyle, ...smallStyle, ...this.props.style}} labelStyle={{...stylesButtonLabel, ...labelStyle, ...this.props.labelStyle}} label={label} primary={this.props.type === 'Primary'} secondary={this.props.type === 'Secondary'} disabled={this.props.disabled || this.props.waiting}> {this.props.waiting && ( <ProgressIndicator white={progressColor === globalColors.white} style={{...stylesProgress}} />)} </FlatButton> </div> ) } } const buttonCommon = { ...globalStyles.fontSemibold, color: globalColors.white, whiteSpace: 'nowrap', borderRadius: 55, fontSize: 16, height: 32, lineHeight: '24px', textTransform: 'none', minWidth: 10 } const stylesButtonPrimary = { ...buttonCommon, backgroundColor: globalColors.blue, disabledOpacity: 0.2 } const stylesButtonSecondary = { ...buttonCommon, backgroundColor: globalColors.lightGrey2, disabledOpacity: 0.3, marginRight: 10 } const stylesButtonDanger = { ...buttonCommon, backgroundColor: globalColors.red, disabledOpacity: 0.2, marginRight: 10 } const stylesButtonFollow = { ...buttonCommon, backgroundColor: globalColors.green, disabledOpacity: 0.3, marginRight: 10, minWidth: 125 } const stylesButtonFollowing = { ...buttonCommon, backgroundColor: globalColors.white, border: `solid 2px ${globalColors.green}`, marginRight: 10, minWidth: 125 } const stylesButtonUnfollow = { ...buttonCommon, backgroundColor: globalColors.blue, disabledOpacity: 0.2, marginRight: 10, minWidth: 125 } const stylesButtonSmall = { height: 28, lineHeight: '24px' } const stylesButtonLabel = { paddingLeft: 25, paddingRight: 25 } const stylesButtonSmallLabel = { ...globalStyles.fontRegular, paddingLeft: 20, paddingRight: 20 } const stylesProgress = { position: 'absolute', height: 'calc(100% - 4px)', left: 0, right: 0, top: 0, bottom: 0, margin: 'auto' } export default Button
JavaScript
0.000396
@@ -423,16 +423,169 @@ rs.white +%0A let rippleStyle: %7BrippleColor: string%7D = %7B%7D%0A // Set all button ripples to be more prominent%0A rippleStyle = %7BrippleColor: 'rgba(0, 0, 0, 0.3)'%7D %0A%0A co @@ -2240,16 +2240,29 @@ essColor +, rippleStyle %7D%0A %7D%0A%0A @@ -2378,16 +2378,29 @@ essColor +, rippleStyle %7D = this @@ -3830,24 +3830,24 @@ ops.style%7D%7D%0A - la @@ -3917,24 +3917,51 @@ abelStyle%7D%7D%0A + %7B...rippleStyle%7D%0A la
5f9423c71b8a56557002b523f0e04bc8d4c5fca8
add shebang
bin/browser-sync.js
bin/browser-sync.js
var startOpts = require("../lib/cli/opts.start.json"); var reloadOpts = require("../lib/cli/opts.reload.json"); var recipeOpts = require("../lib/cli/opts.recipe.json"); var pkg = require("../package.json"); var utils = require("../lib/utils"); /** * Handle cli input */ if (!module.parent) { var yargs = require("yargs") .command("start", "Start the server") .command("init", "Create a configuration file") .command("reload", "Send a reload event over HTTP protocol") .command("recipe", "Generate the files for a recipe") .version(function () { return pkg.version; }) .epilogue("For help running a certain command, type <command> --help\neg: $0 start --help"); var argv = yargs.argv; var command = argv._[0]; var valid = ["start", "init", "reload", "recipe"]; if (valid.indexOf(command) > -1) { handleIncoming(command, yargs.reset()); } else { yargs.showHelp(); } } /** * @param {{cli: object, [whitelist]: array, [cb]: function}} opts * @returns {*} */ function handleCli(opts) { opts.cb = opts.cb || utils.defaultCallback; return require("../lib/cli/command." + opts.cli.input[0])(opts); } module.exports = handleCli; /** * @param {string} command * @param {object} yargs */ function handleIncoming(command, yargs) { var out; if (command === "start") { out = yargs .usage("Usage: $0 start [options]") .options(startOpts) .example("$0 start -s app", "- Use the App directory to serve files") .example("$0 start -p www.bbc.co.uk", "- Proxy an existing website") .help() .argv; } if (command === "init") { out = yargs .usage("Usage: $0 init") .example("$0 init") .help() .argv; } if (command === "reload") { out = yargs .usage("Usage: $0 reload") .options(reloadOpts) .example("$0 reload") .example("$0 reload --port 4000") .help() .argv; } if (command === "recipe") { out = yargs .usage("Usage: $0 recipe <recipe-name>") .option(recipeOpts) .example("$0 recipe ls", "list the recipes") .example("$0 recipe gulp.sass", "use the gulp.sass recipe") .help() .argv; } if (out.help) { return yargs.showHelp(); } handleCli({cli: {flags: out, input: out._}}); }
JavaScript
0.000001
@@ -1,12 +1,32 @@ +#!/usr/bin/env node%0A var startOpt
3b6579b6e934cbe5558d168d95208b0b6a329bcb
Use both keyup and keypress if input unsupported
jquery.formrestrict.js
jquery.formrestrict.js
/* * Every time the form field is changed, sanitize its contents with the given * function to only allow input of a certain form. */ (function ($) { var inputEvents = "input"; if (!("oninput" in document || "oninput" in $("<input>")[0])) { inputEvents += " keyup"; } jQuery.fn.restrict = function(sanitizationFunc) { $(this).bind(inputEvents, function(e) { $(this).val(sanitizationFunc($(this).val())); }); }; /* * Every time the form field is changed, modify its contents by eliminating * matches for the given regular expression within the field. */ jQuery.fn.regexRestrict = function(regex){ var sanitize = function(text) { return text.replace(regex, ''); }; $(this).restrict(sanitize); } })(jQuery);
JavaScript
0.000001
@@ -268,16 +268,25 @@ nts += %22 + keypress keyup%22;
cc97569d730015aeefe9be7fbed2ed5854a229f8
Add _addFilter and _addFilters private functions
scripts/wee-routes.js
scripts/wee-routes.js
import pathToRegExp from 'path-to-regexp'; import { _castString, $isArray, $unserialize } from 'core/types'; import { _doc } from 'core/variables'; import { $exec } from 'core/core'; const REMOVE_SLASHES_REGEXP = /^\/|\/$/g; let _routes = []; let _filters = {}; /** * Add a route to routes array * * @param routes * @private */ function _addRoutes(routes) { const count = routes.length; for (let i = 0; i < count; i++) { let route = _getRoute(routes[i].path); if (route) { _routes[route.index] = routes[i]; break; } _routes.push(routes[i]); } } /** * Retrieve existing route with associated index * * @param {string} value * @param {string} key * @returns {Object} * @private */ function _getRoute(value) { const count = _routes.length; for (let i = 0; i < count; i++) { let route = _routes[i]; if (route.path === value || route.name === value) { return { route: route, index: i }; } } return null; } /** * Parse url and return results * * @param {string} value * @returns {Object} * @private */ function _parseUrl(value) { const a = _doc.createElement('a'); a.href = value || window.location; const search = a.search, path = a.pathname.replace(REMOVE_SLASHES_REGEXP, ''); return { full: '/' + path + search + a.hash, hash: a.hash.slice(1), path: '/' + path, query: search ? $unserialize(search) : {}, segments: path.split('/'), url: a.href, port: a.port }; } /** * Extract parameters from current URL based on matching route * * @param {string} path * @param {string} location * @returns {Object} * @private */ function _getParams(path, location) { let keys = [], params = {}, results = pathToRegExp(path, keys).exec(location); if ($isArray(results)) { results.slice(1) .forEach((segment, j) => params[keys[j].name] = _castString(segment)); } return Object.keys(params).length ? params : null; } export default { /** * Register routes * * @param {Array} routes * @returns {Object} */ map(routes) { _addRoutes(routes); return this; }, /** * Reset all routes and filters - mainly for testing purposes */ reset() { _routes = []; _filters = {}; }, /** * Retrieve all routes or specific route by name/path * * @param {string} [value] * @returns {Object|Array} */ routes(value) { if (value) { let result = _getRoute(value); if (result) { return result.route; } } return _routes; }, run() { const uri = this.uri(); const length = _routes.length; for (let i = 0; i < length; i++) { let path = _routes[i].path; let params = _getParams(path, uri.full); if (params) { let toPath = pathToRegExp.compile(path); path = toPath(params); } if (uri.full === path) { $exec(_routes[i].handler, { args: [params] }); break; } } }, /** * Retrieve information about current location * * @param {string} [value] * @returns {Object} */ uri(value) { return _parseUrl(value); }, /** * Add a filter or array of filters to internal filter registry * * @param {string|Array} name * @param {Function} [callback] */ addFilter(name, callback) { if ($isArray(name)) { _addFilters(name); } else { _addFilter(name, callback) } return this; }, /** * Return all registered filters * * @returns {{}} */ filters() { return _filters; } };
JavaScript
0.000001
@@ -562,24 +562,371 @@ %5Bi%5D);%0A%09%7D%0A%7D%0A%0A +/**%0A * Add a filter to the filter registry%0A *%0A * @param name%0A * @param handler%0A * @private%0A */%0Afunction _addFilter(name, handler) %7B%0A%09_filters%5Bname%5D = handler;%0A%7D%0A%0A/**%0A * Add multiple filters to filter registry%0A * @param filters%0A * @private%0A */%0Afunction _addFilters(filters) %7B%0A%09filters.forEach(filter =%3E _addFilter(filter.name, filter.handler));%0A%7D%0A%0A /**%0A * Retri @@ -3672,17 +3672,16 @@ ters%0A%09 * - %0A%09 * @re
02d59ef777ae2fe88bd207a95c2f5cb21288210d
Add missing this.resource.fetch() call
openbudgets/apps/tools/static/tools/comparisons/ui/entities-list.js
openbudgets/apps/tools/static/tools/comparisons/ui/entities-list.js
define([ 'uijet_dir/uijet', 'api', 'comparisons', 'tool_widgets/FilteredList' ], function (uijet, ui, comparisons) { return { type : 'FilteredList', config : { element : '#entities_list', mixins : ['Templated', 'Scrolled', 'Deferred'], adapters : ['jqWheelScroll', 'Spin'], resource : 'Munis', promise : comparisons.routes_set_promise, position : 'top|120px bottom fluid', fetch_options : { data: { has_sheets : true, page_by : 300, ordering : 'name' } }, search : { fields : { code : 20, name : 10, name_en : 10, name_ru : 10, name_ar : 10 } }, filters : { search : 'search' }, data_events : { 'change:selected' : function () { uijet.Resource('Contexts').fetch({ data: { entities: this.resource.where({ selected : true }).map(function (model) { return model.id; }).toString() }, remove : false }); }, request : 'spin', sync : function () { this.spinOff() .index().search_index.add( this.resource.toJSON() ); }, error : 'spinOff' }, signals : { pre_wake : function () { return ! this.has_content; }, post_render : function () { this.$children = this.$element.children(); if ( this.queued_filters ) { this.publish('rendered'); setImmediate(this.filterChildren.bind(this)); } }, pre_select : function ($selected) { var id = $selected.attr('data-id'); this.resource.get(id).set('selected', true); return id; }, post_filtered : function (ids) { var search_term = this.last_search_term; uijet.utils.requestAnimFrame( function () { var resource = this.resource, highlight = this.highlight.bind(this); if ( this.$last_filter_result ) { this.$last_filter_result.each(function (i, item) { var text = resource.get(item.getAttribute('data-id')).get('name'); if ( search_term ) { item.innerHTML = highlight(text, search_term); } else { item.innerHTML = ''; item.appendChild(document.createTextNode(text)); } }); } }.bind(this) ); } }, app_events : { 'entity_field.changed' : function (value) { this.last_search_term = value || null; this.filterBySearch(this.last_search_term); if ( ! this.queued_filters ) { this.filterChildren(); uijet.utils.requestAnimFrame(this.scroll.bind(this)); } } } } }; });
JavaScript
0.000053
@@ -107,17 +107,18 @@ (uijet, -u +ap i, compa @@ -442,38 +442,214 @@ : -comparisons.routes_set_promise +function () %7B%0A return uijet.whenAll(%5B%0A comparisons.routes_set_promise,%0A this.resource.fetch(this.options.fetch_options)%0A %5D);%0A %7D ,%0A
8e4ca2f2eae07b3043edac42c269c80a32801f1e
save cross section
M-N-Kappa/js/save.js
M-N-Kappa/js/save.js
$("#save").click(function () { localStorage.setItem("mkap", $("#polygon_input").html()) }); $("#load").click(function () { var b = localStorage.getItem("mkap"); $("#polygon_input").html(b) console.log(b); watch() });
JavaScript
0
@@ -33,146 +33,946 @@ -localStorage.setItem(%22mkap%22, $(%22#polygon_input%22).html())%0A%7D);%0A%0A$(%22#load%22).click(function () %7B%0A var b = localStorage.getItem(%22mkap%22 +var save_loc = prompt(%22The cross section will be saved in your browser memory%5Cn%22 +%0A %22Under which name should it be saved? : %22, %22name%22);%0A%0A var input = %5B%5D;%0A var all = $(%22#polygon_input%22).find(%22input%22).toArray();%0A all = all.concat($(%22#polygon_input%22).find(%22select%22).toArray());%0A for (var i = 0; i %3C all.length; i++) %7B%0A if (!$(all%5Bi%5D).hasClass(%22hidden%22))%7B%0A if (all%5Bi%5D.value == undefined) %7B%0A input.push(%22na%22)%0A %7D%0A else %7B%0A input.push($(all%5Bi%5D).val())%0A %7D%0A %7D%0A%0A %7D%0A%0A var a = %7Bpg: $(%22#polygon_input%22).html(),%0A pg_val: input%7D;%0A localStorage.setItem(save_loc, JSON.stringify(a))%0A%7D);%0A%0A$(%22#load%22).click(function () %7B%0A var save_loc = prompt(%22Enter the name of your saved cross section : %22, %22name%22);%0A var a = JSON.parse(localStorage.getItem(save_loc));%0A console.log(a)%0A%0A $(%22#polygon_input%22).html(a.pg );%0A +%0A + var all = $(%22 @@ -992,48 +992,364 @@ t%22). -html(b)%0A console.log(b);%0A watch()%0A +find(%22input%22).toArray();%0A all = all.concat($(%22#polygon_input%22).find(%22select%22).toArray());%0A%0A for (var i = 0; i %3C all.length; i++) %7B%0A if (!$(all%5Bi%5D).hasClass(%22hidden%22))%7B%0A if (a.pg_val%5Bi%5D !== %22na%22) %7B%0A $(all%5Bi%5D).val(a.pg_val%5Bi%5D);%0A%0A %7D%0A %7D%0A %7D%0A watch();%0A trigger_polygon()%0A trigger_rebar_input() %0A%7D);
62048b323862016705e8b89466024dff0d60c8d6
Include the eslint react defaults so it behaves as expected for React JSX files
.eslintrc.js
.eslintrc.js
module.exports = { 'parser': 'babel-eslint', 'env': { 'browser': true, 'es6': true, 'node': true, }, 'extends': 'eslint:recommended', 'installedESLint': true, 'parserOptions': { 'ecmaFeatures': { 'experimentalObjectRestSpread': true, 'jsx': true, }, 'sourceType': 'module', }, 'plugins': [ 'react', 'jsx', ], 'rules': { 'indent': [ 'error', 2, ], 'linebreak-style': [ 'error', 'unix', ], 'quotes': [ 'error', 'single', ], 'semi': [ 'error', 'never', ], } }
JavaScript
0
@@ -124,16 +124,22 @@ xtends': + %5B%0A 'eslint @@ -153,16 +153,53 @@ ended',%0A + 'plugin:react/recommended',%0A %5D,%0A 'insta
eedaf53de0d6dbc99e64a461bb98168aa8fa8ecd
disable no-continue rule
.eslintrc.js
.eslintrc.js
// To make use of this eslint config file run: // // npm ci // // Then install eslint support in your IDE of choice. module.exports = { env: { browser: true, es6: true, }, extends: [ 'airbnb-base', ], globals: { Atomics: 'readonly', SharedArrayBuffer: 'readonly', }, parserOptions: { ecmaVersion: 2018, sourceType: 'module', }, rules: { 'camelcase': ['off'], 'class-methods-use-this': ['off'], 'func-names': ['off'], 'import/prefer-default-export': ['off'], 'max-classes-per-file': ['off'], 'max-len': ['off'], 'no-bitwise': ['warn'], 'no-lone-blocks':['off'], 'no-param-reassign': ['off'], 'no-plusplus': ['off'], 'no-restricted-syntax': ['warn'], 'no-return-assign': ['off'], 'no-shadow': ['warn'], 'no-underscore-dangle': ['off'], 'no-use-before-define': ['error', { 'functions': false, 'variables': false }], 'object-shorthand': ['off'], 'prefer-destructuring': ['off'], 'prefer-object-spread': ['off'], 'space-before-function-paren': ['error', { 'anonymous': 'never', 'named': 'never', 'asyncArrow': 'always' }], }, };
JavaScript
0.000021
@@ -596,32 +596,60 @@ ise': %5B'warn'%5D,%0A + 'no-continue': %5B'off'%5D,%0A 'no-lone-blo
b8e5fe5eef70050af96d37fa58158b08f2efdef5
update eslint config
.eslintrc.js
.eslintrc.js
module.exports = { parser: 'babel-eslint', root: true, env: { node: true, browser: true, es6: true, 'jest/globals': true }, extends: [ 'eslint:recommended', ], plugins: [ 'jest' ], parserOptions: { ecmaVersion: 2017, sourceType: 'module', ecmaFeatures: { experimentalObjectRestSpread: true, jsx: true } }, globals: { BRANCH: true, COMMIT: true }, rules: { indent: ['error', 2], 'comma-dangle': ['error', { arrays: 'always-multiline', objects: 'always-multiline', imports: 'always-multiline', exports: 'always-multiline', functions: 'never' }], 'no-console': 'warn', 'no-use-before-define': 'off', 'no-confusing-arrow': ['error', { allowParens: true }], 'react/jsx-closing-bracket-location': [ 'error', 'after-props' ], 'react/jsx-filename-extension': ['error', { extensions: ['.js'] }], 'react/prop-types': 'warn', 'import/no-extraneous-dependencies': [ 'error', { dependencies: true, peerDependencies: true } ], 'no-restricted-syntax': [ 'error', { selector: 'ForInStatement', message: 'for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array.', }, /* { selector: 'ForOfStatement', message: 'iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations.', }, */ { selector: 'LabeledStatement', message: 'Labels are a form of GOTO; using them makes code confusing and hard to maintain and understand.', }, { selector: 'WithStatement', message: '`with` is disallowed in strict mode because it makes code impossible to predict and optimize.', }, ], }, };
JavaScript
0.000001
@@ -131,24 +131,25 @@ obals': true +, %0A %7D,%0A exte @@ -187,34 +187,94 @@ ,%0A -%5D,%0A plugins: %5B%0A 'jest' + 'plugin:react/recommended',%0A %5D,%0A plugins: %5B%0A 'jest',%0A 'import',%0A 'react', %0A %5D @@ -420,22 +420,24 @@ sx: true +, %0A %7D +, %0A %7D,%0A @@ -481,16 +481,17 @@ IT: true +, %0A %7D,%0A @@ -720,16 +720,17 @@ 'never' +, %0A %7D%5D, @@ -1087,16 +1087,19 @@ r', %7B de +vDe pendenci @@ -1106,38 +1106,43 @@ es: -true, peerDependencies: true +%5B'**/*.test.js', '**/*.spec.js'%5D %7D +, %0A
b9d12f0e6abe1014e9d9be6083c6e87ee73d4f2d
Fix ESLint config
.eslintrc.js
.eslintrc.js
'use strict'; module.exports = { root: true, parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 2018, sourceType: 'module', ecmaFeatures: { legacyDecorators: true, }, }, plugins: ['ember', '@typescript-eslint'], extends: [ 'eslint:recommended', 'plugin:ember/recommended', 'plugin:prettier/recommended', ], env: { browser: true, }, rules: { 'ember/no-mixins': 'warn', 'ember/no-new-mixins': 'warn', 'ember/no-classic-classes': 'warn', 'ember/no-classic-components': 'warn', 'ember/require-tagless-components': 'warn', }, overrides: [ // ts files { files: ['**/*.ts'], extends: [ 'plugin:@typescript-eslint/eslint-recommended', 'plugin:@typescript-eslint/recommended', 'prettier/@typescript-eslint', ], rules: { '@typescript-eslint/explicit-module-boundary-types': 'error', // We want to be strict with types '@typescript-eslint/explicit-function-return-type': 'error', // We want to be strict with types '@typescript-eslint/no-unused-vars': [ 'error', { argsIgnorePattern: '^_' }, ], }, }, // node files { files: [ '.eslintrc.js', '.prettierrc.js', '.template-lintrc.js', 'ember-cli-build.js', 'index.js', 'testem.js', 'blueprints/*/index.js', 'config/**/*.js', 'tests/dummy/config/**/*.js', 'lib/**/*.js', ], excludedFiles: [ 'addon/**', 'addon-test-support/**', 'app/**', 'tests/dummy/app/**', ], parserOptions: { sourceType: 'script', }, env: { browser: false, node: true, }, plugins: ['node'], extends: ['plugin:node/recommended'], }, // node test files { files: ['node-tests/**/*.js'], parserOptions: { sourceType: 'script', }, env: { browser: false, node: true, jest: true, }, plugins: ['node'], rules: Object.assign( {}, require('eslint-plugin-node').configs.recommended.rules, { 'ember/no-jquery': 'off', 'ember/no-global-jquery': 'off', } ), }, ], };
JavaScript
0.000012
@@ -800,47 +800,8 @@ d',%0A - 'prettier/@typescript-eslint',%0A
4eda1050e81c613f3e1a733d0f22e33baec8c8f3
Set jsx curly spacing eslint rule
.eslintrc.js
.eslintrc.js
module.exports = { "parser": "babel-eslint", "env": { "browser": true }, "plugins": [ "react" ], "extends": [ "eslint:recommended", "plugin:react/recommended" ], "rules": { } };
JavaScript
0.000001
@@ -174,19 +174,191 @@ %09%5D,%0A -%09%22rules%22: %7B + %22parserOptions%22: %7B%0A %22ecmaFeatures%22: %7B%0A %22jsx%22: true%0A %7D%0A %7D,%0A%09%22rules%22: %7B%0A %22react/jsx-curly-spacing%22: %5B2, %22always%22, %7B %22spacing%22: %7B%0A %22objectLiterals%22: %22never%22%0A %7D%7D%5D %0A%09%7D%0A
4d4c877b5068e49c964de3ecf94b167b74fb8a2f
Enable the no-const-assign rule
.eslintrc.js
.eslintrc.js
module.exports = { extends: [ 'onelint' ], env: { es6: true }, parserOptions: { ecmaVersion: 2017 } };
JavaScript
0.000049
@@ -52,16 +52,65 @@ %0A %5D,%0A + rules: %7B%0A 'no-const-assign': 2%0A %7D,%0A env:
cf5d73073aad4ea37098a58c5b1fa01482b037c4
Disable `ember/no-test-support-import` rule for `node-tests` folder
.eslintrc.js
.eslintrc.js
'use strict'; module.exports = { root: true, parser: 'babel-eslint', parserOptions: { ecmaVersion: 2018, sourceType: 'module', ecmaFeatures: { legacyDecorators: true, }, }, plugins: ['ember'], extends: [ 'eslint:recommended', 'plugin:ember/recommended', 'plugin:prettier/recommended', ], env: { browser: true, }, rules: {}, overrides: [ // node files { files: [ '.eslintrc.js', '.prettierrc.js', '.template-lintrc.js', 'ember-cli-build.js', 'index.js', 'testem.js', 'testem.multiple-test-page.js', 'testem.no-test-page.js', 'testem.simple-test-page.js', 'blueprints/*/index.js', 'config/**/*.js', 'tests/dummy/config/**/*.js', 'lib/**/*', ], excludedFiles: [ 'addon/**', 'addon-test-support/**', 'app/**', 'tests/dummy/app/**', ], parserOptions: { sourceType: 'script', }, env: { browser: false, node: true, }, plugins: ['node'], extends: ['plugin:node/recommended'], }, { files: ['node-tests/**/*'], excludedFiles: ['testem.multiple-test-page.js'], parserOptions: { ecmaVersion: 2018, }, env: { node: true, mocha: true, }, rules: {}, }, { // Test files: files: ['tests/**/*-test.{js,ts}'], extends: ['plugin:qunit/recommended'], }, ], };
JavaScript
0
@@ -1384,24 +1384,78 @@ rules: %7B +%0A 'ember/no-test-support-import': 'off',%0A %7D,%0A %7D,%0A
80e9b32acc12524f96804fc8738dc6d05a4da951
Update eslintrc
.eslintrc.js
.eslintrc.js
module.exports = { 'extends': 'airbnb-base', 'plugins': [ 'import' ], 'env': { 'browser': true, }, 'settings': { 'import/resolver': 'webpack', }, 'rules': { 'no-param-reassign': ['error', { 'props': false }], 'import/prefer-default-export': 'off', 'no-use-before-define': ['error', { 'functions': false, 'classes': true }], }, };
JavaScript
0.000001
@@ -357,16 +357,49 @@ rue %7D%5D,%0A + 'brace-style': 'stroustrup',%0A %7D,%0A%7D;%0A
bcc9099100ee009e513cc321e1a56f7f7160e103
configure airbnb rules
.eslintrc.js
.eslintrc.js
module.exports = { root: true, parser: "babel-eslint", extends: [ "standard", "eslint:recommended", "plugin:react/recommended", "prettier" // Turns off all rules that are unnecessary or might conflict with Prettier. ], plugins: [ "react", "prettier" // Runs Prettier as an ESLint rule and reports differences as individual ESLint issues. ], rules: { "prettier/prettier": "error" // Prettier rules must throw errors } };
JavaScript
0
@@ -135,24 +135,38 @@ commended%22,%0A + %22airbnb%22,%0A %22prettie @@ -245,16 +245,16 @@ ettier.%0A - %5D,%0A p @@ -276,16 +276,29 @@ react%22,%0A + %22babel%22,%0A %22pre @@ -440,16 +440,17 @@ %22error%22 +, // Pret @@ -478,15 +478,896 @@ errors%0A + %22no-unused-expressions%22: %22off%22,%0A %22babel/no-unused-expressions%22: %22error%22,%0A %22react/jsx-filename-extension%22: %22off%22,%0A %22import/no-named-as-default-member%22: %22off%22,%0A %22react/destructuring-assignment%22: %22off%22,%0A %22react/require-default-props%22: %22off%22,%0A %22react/jsx-one-expression-per-line%22: %22off%22,%0A %22jsx-a11y/anchor-is-valid%22: %22off%22,%0A %22react/jsx-wrap-multilines%22: %22off%22,%0A %22react/button-has-type%22: %22off%22,%0A %22react/no-array-index-key%22: %22warn%22,%0A %22react/forbid-prop-types%22: %22warn%22,%0A %22react/no-did-update-set-state%22: %22warn%22,%0A %22consistent-return%22: %5B%22error%22, %7B treatUndefinedAsUnspecified: true %7D%5D,%0A %22react/sort-comp%22: %5B%0A %22error%22,%0A %7B order: %5B%22lifecycle%22, %22everything-else%22, %22render%22, %22static-methods%22%5D %7D%0A %5D%0A %7D,%0A overrides: %7B%0A files: %22**/*.%7Btest,story,testFramework%7D.js%22,%0A rules: %7B%0A %22import/no-extraneous-dependencies%22: %22off%22%0A %7D%0A %7D%0A%7D;%0A
f0592c4906ee4ff0df34e6285bdf62bafcdbed3b
Add `root: true` to .eslintrc.js
.eslintrc.js
.eslintrc.js
const baseRules = require("eslint-config-lydell"); module.exports = { parser: "babel-eslint", plugins: [ "flowtype", "flowtype-errors", "import", "prettier", "simple-import-sort", ], env: { es6: true, node: true, }, rules: Object.assign({}, baseRules({ flow: true, import: true }), { "flowtype-errors/show-errors": "error", "import/no-restricted-paths": [ "error", { basePath: "src", // Disallow these dirs from importing from each other. zones: makeRestrictedPathsZones([ "background", "popup", "renderer", "worker", ]), }, ], "no-console": "error", "no-script-url": "off", "prettier/prettier": "error", "require-await": "error", }), overrides: [ { files: [".*.js", "*.config.js", "web-ext-*.js"], rules: { "flowtype/require-parameter-type": "off", "flowtype/require-return-type": "off", "flowtype/require-valid-file-annotation": "off", "import/order": ["error", { "newlines-between": "always" }], }, }, { files: ["src/*/**/*.js", "html/**/*.js"], env: { es6: true, node: false, }, globals: Object.assign({}, baseRules.browserEnv(), { BROWSER: true, BUILD_TIME: true, PROD: false, browser: false, }), rules: { "simple-import-sort/sort": "error", }, }, ], }; function makeRestrictedPathsZones(dirs) { return [].concat( ...dirs.map(dir => { const otherDirs = dirs.filter(dir2 => dir2 !== dir); return otherDirs.map(dir2 => ({ target: dir, from: dir2 })); }) ); }
JavaScript
0.000372
@@ -64,16 +64,30 @@ rts = %7B%0A + root: true,%0A parser
135eff847339056712a184f96d8fe267581ac640
Add browser to eslint globals
.eslintrc.js
.eslintrc.js
module.exports = { "env": { "browser": true, "es6": true }, "extends": "eslint:recommended", "parserOptions": { "sourceType": "module" }, "rules": { "indent": [ "error", 2 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ] } };
JavaScript
0
@@ -12,20 +12,17 @@ rts = %7B%0A - +%09 %22env%22: %7B @@ -22,24 +22,18 @@ env%22: %7B%0A - +%09%09 %22browser @@ -41,24 +41,18 @@ : true,%0A - +%09%09 %22es6%22: t @@ -54,28 +54,47 @@ 6%22: true -%0A %7D,%0A +,%0A%09%09%22webextensions%22: true%0A%09%7D,%0A%09 %22extends @@ -118,20 +118,17 @@ ended%22,%0A - +%09 %22parserO @@ -138,24 +138,18 @@ ons%22: %7B%0A - +%09%09 %22sourceT @@ -167,19 +167,13 @@ le%22%0A - %7D,%0A +%09%7D,%0A%09 %22rul @@ -179,24 +179,18 @@ les%22: %7B%0A - +%09%09 %22indent%22 @@ -197,281 +197,200 @@ : %5B%0A - %22error%22,%0A 2%0A %5D,%0A %22linebreak-style%22: %5B%0A %22error%22,%0A %22unix%22%0A %5D,%0A %22quotes%22: %5B%0A %22error%22,%0A %22single%22%0A %5D,%0A %22semi%22: %5B%0A %22error%22,%0A %22always%22%0A %5D%0A +%09%09%09%22error%22,%0A%09%09%092%0A%09%09%5D,%0A%09%09%22linebreak-style%22: %5B%0A%09%09%09%22error%22,%0A%09%09%09%22unix%22%0A%09%09%5D,%0A%09%09%22quotes%22: %5B%0A%09%09%09%22error%22,%0A%09%09%09%22single%22%0A%09%09%5D,%0A%09%09%22semi%22: %5B%0A%09%09%09%22error%22,%0A%09%09%09%22always%22%0A%09%09%5D%0A%09%7D,%0A%09%22globals%22: %7B%0A%09%09%22browser%22: true%0A%09 %7D%0A%7D;
6229ba9e1192df7b25d8dc7f4f41266bb36832f3
Remove line break style check
.eslintrc.js
.eslintrc.js
module.exports = { 'env': { 'browser' : true, 'commonjs': true, 'es6' : true, 'node' : true }, 'extends': [ 'eslint:recommended' ], 'ignorePatterns': [ 'dist' ], 'parserOptions': { 'sourceType': 'module' }, 'plugins': [], 'rules': { 'array-bracket-spacing' : ['error', 'never'], 'array-callback-return' : ['error'], 'block-scoped-var' : ['error'], 'block-spacing' : ['error', 'always'], 'curly' : ['error'], 'dot-notation' : ['error'], 'eqeqeq' : ['error'], 'indent' : ['error', 4, {'SwitchCase': 1}], 'linebreak-style' : ['error', 'unix'], 'no-console' : ['warn'], 'no-floating-decimal' : ['error'], 'no-implicit-coercion' : ['error'], 'no-implicit-globals' : ['error'], 'no-loop-func' : ['error'], 'no-return-assign' : ['error'], 'no-template-curly-in-string': ['error'], 'no-unneeded-ternary' : ['error'], 'no-unused-vars' : ['error', { 'args': 'none' }], 'no-useless-computed-key' : ['error'], 'no-useless-return' : ['error'], 'no-var' : ['error'], 'prefer-const' : ['error'], 'quotes' : ['error', 'single'], 'semi' : ['error', 'always'] } };
JavaScript
0
@@ -774,66 +774,8 @@ %7D%5D,%0A - 'linebreak-style' : %5B'error', 'unix'%5D,%0A
15a787f336679f684b768df6d25a75e17e7b7b6d
add eslint:recommended rules
.eslintrc.js
.eslintrc.js
module.exports = { 'extends': 'google', 'parserOptions': { 'ecmaVersion': 6, }, 'rules': { 'no-multiple-empty-lines': ['error',{'max': 1}], 'arrow-spacing': ['error'] } };
JavaScript
0
@@ -29,16 +29,38 @@ s': +%5B'eslint:recommended', 'google' ,%0A @@ -55,16 +55,17 @@ 'google' +%5D ,%0A 'par @@ -106,16 +106,84 @@ 6,%0A %7D,%0A + 'env':%7B%0A 'es6': true,%0A 'mocha': true,%0A 'node': true%0A %7D,%0A 'rules @@ -240,16 +240,16 @@ ': 1%7D%5D,%0A - 'arr @@ -270,16 +270,43 @@ 'error'%5D +,%0A 'no-console': %5B'off'%5D %0A %7D%0A%7D;%0A
e4997bda872e4cc49d58c70988df5c82827a090e
add rule for blank lines
.eslintrc.js
.eslintrc.js
module.exports = { "env": { "browser": true, "es6": true }, "parser": "babel-eslint", "extends": "eslint:recommended", "parserOptions": { "ecmaFeatures": { "experimentalObjectRestSpread": true, "jsx": true }, "sourceType": "module" }, "plugins": [ "react" ], "rules": { "comma-dangle": ["error", "always-multiline"], "no-console": "error", "no-debugger": "error", "indent": [ "error", 2 ], "no-multi-spaces": [2, { "exceptions": { "Identifier": true, "ClassProperty": true, "ImportDeclaration": true, "VariableDeclarator": true, "AssignmentExpression": true } }], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ], "react/prefer-stateless-function": [2, { "ignorePureComponents": true }], "react/prop-types": 2, "react/jsx-uses-vars": [2], "react/jsx-indent": [2, 2], "react/jsx-indent-props": [2, 2], "key-spacing": [2, { "singleLine": { "beforeColon": false, "afterColon": true }, "multiLine": { "beforeColon": false, "afterColon": true, "mode": "minimum" } }], } };
JavaScript
0.000051
@@ -466,24 +466,100 @@ 2%0A %5D,%0A + %22no-multiple-empty-lines%22: %5B2, %7B %22max%22: 2, %22maxEOF%22: 0, %22maxEOF%22: 0 %7D%5D,%0A %22no-mult
5b87f63f3e9c5817bcddf008c0b4005494059368
Use relative URL to access Gerrit base URL
src/main/resources/static/js/plugin-manager.js
src/main/resources/static/js/plugin-manager.js
// Copyright (C) 2015 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var app = angular.module('PluginManager', []).controller( 'LoadInstalledPlugins', function($scope, $http, $location, $window) { var plugins = this; plugins.list = []; plugins.available = {}; $scope.searchPlugin = ''; $scope.pluginIndexOf = function(pluginId) { var pluginIndex = -1 angular.forEach(plugins.list, function(row, rowIndex) { if (row.id == pluginId) { pluginIndex = rowIndex } }); return pluginIndex; } $scope.refreshInstalled = function(refreshPluginId) { $http.get('/plugins/?all', plugins.httpConfig).then( function successCallback(response) { angular.forEach(response.data, function(plugin) { if (refreshPluginId == undefined || refreshPluginId == plugin.id) { var currPluginIdx = $scope.pluginIndexOf(plugin.id); if (currPluginIdx < 0) { plugins.list.push({ id : plugin.id, description : plugin.description, index_url : plugin.index_url, version : plugin.version, sha1 : '', url : plugin.url, update_version : '' }); } else { plugins.list[currPluginIdx] = { id : plugin.id, description : plugin.description, index_url : plugin.index_url, version : plugin.version, sha1 : '', url : plugin.url, update_version : '' } } } }); $scope.refreshAvailable(refreshPluginId); }, function errorCallback(response) { }); } $scope.refreshAvailable = function(refreshPluginId) { $http.get('/plugins/plugin-manager/available', plugins.httpConfig) .then( function successCallback(response) { angular.forEach(response.data, function(plugin) { if (refreshPluginId == undefined || refreshPluginId == plugin.id) { var currRow = $scope.pluginIndexOf(plugin.id); var currPlugin = currRow < 0 ? undefined : plugins.list[currRow]; if (currPlugin === undefined) { currPlugin = { id : plugin.id, index_url : '', version : '' } } if (plugin.version != currPlugin.version) { currPlugin.update_version = plugin.version; } currPlugin.sha1 = plugin.sha1; currPlugin.url = plugin.url; currPlugin.description = plugin.description; if (currRow < 0) { plugins.list.push(currPlugin); } else { plugins.list[currRow] = currPlugin; } } }); plugins.available = response.data; }, function errorCallback(response) { }); } $scope.install = function(id, url) { var pluginInstallData = { "url" : url }; $("button#" + id).addClass("hidden"); $("span#installing-" + id).removeClass("hidden"); $http.put('/a/plugins/' + id + ".jar", pluginInstallData).then( function successCallback(response) { $("span#installing-" + id).addClass("hidden"); $("span#installed-" + id).removeClass("hidden"); $scope.refreshInstalled(id); }, function errorCallback(response) { $("span#installing-" + id).addClass("hidden"); $("span#failed-" + id).removeClass("hidden"); }); } plugins.goToGerrit = function () { var currUrl = $location.absUrl(); var indexOfHash = currUrl.indexOf("#") if(indexOfHash > 0) { currUrl = currUrl.substring(0,indexOfHash) } var newUrl = currUrl + "/../../../.." $window.location.href = newUrl }; $scope.refreshInstalled(); }); app.config(function($httpProvider) { $httpProvider.defaults.headers.common = { 'X-Gerrit-Auth' : '@X-Gerrit-Auth' }; });
JavaScript
0.000214
@@ -1124,32 +1124,550 @@ Index;%0A %7D%0A%0A + $scope.getBaseUrl = function () %7B%0A // Using a relative URL for allowing to reach Gerrit base URL%0A // which could be a non-root path when behind a reverse proxy%0A // on a path location.%0A // The use of a relative URL is for allowing a flexible way%0A // to reach the root even when accessed outside the canonical web%0A // URL (e.g. accessing on node directly with the hostname instead%0A // of the FQDN)%0A return window.location.pathname + '/../../../..';%0A %7D%0A%0A $scope.ref @@ -1720,32 +1720,54 @@ $http.get( +$scope.getBaseUrl() + '/plugins/?all', @@ -3175,16 +3175,38 @@ ttp.get( +$scope.getBaseUrl() + '/plugin @@ -4885,32 +4885,32 @@ lass(%22hidden%22);%0A - $http.pu @@ -4911,16 +4911,38 @@ ttp.put( +$scope.getBaseUrl() + '/a/plug
9daadcf94b7d3e3f3556b90d75a22b7a3d2d310b
Fix detection for ski tracks etc. in geometry field. Fixes #26.
src/modules/unit/components/SingleUnitOnMap.js
src/modules/unit/components/SingleUnitOnMap.js
import React, {Component} from 'react'; import L from 'leaflet'; import {getUnitQuality} from '../helpers'; import UnitMarker from './UnitMarker'; import UnitGeometry from './UnitGeometry'; export class SingleUnitOnMap extends Component{ constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(e) { const {unit, openUnit} = this.props; L.DomEvent.stopPropagation(e); openUnit(unit.id); } shouldComponentUpdate(nextProps) { const {unit, isSelected} = this.props; const isQuality = getUnitQuality(unit) !== getUnitQuality(nextProps.unit); const isSelectedUpdated = isSelected !== nextProps.isSelected; return isQuality || isSelectedUpdated; } render () { const {unit, zoomLevel, isSelected, ...rest} = this.props; const geometry = unit.geometry; return( <div> <UnitMarker unit={unit} zoomLevel={zoomLevel} isSelected={isSelected} handleClick={this.handleClick} {...rest}/> {geometry && <UnitGeometry unit={unit} onClick={this.handleClick} isSelected={isSelected}/> } </div> ); } } export default SingleUnitOnMap;
JavaScript
0
@@ -841,16 +841,83 @@ geometry + && unit.geometry.type === 'MultiLineString' ? unit.geometry : null ;%0A%0A r
9031b75bbc859d0cef401719fa995c931c1d032d
rename assertHasOwnProperties.js -> assertHasProperties.js, https://github.com/phetsims/sun/issues/257
js/EnabledComponent.js
js/EnabledComponent.js
// Copyright 2020, University of Colorado Boulder /** * Mixin that adds a settable Property that determines whether the Object is enabled or not. This includes support for * phet-io instrumentation and a variety of options to customize the enabled Property as well as how it is created. * * @author Michael Kauzmann (PhET Interactive Simulations) */ import BooleanProperty from '../../axon/js/BooleanProperty.js'; import assertHasOwnProperties from '../../phet-core/js/assertHasOwnProperties.js'; import assertMutuallyExclusiveOptions from '../../phet-core/js/assertMutuallyExclusiveOptions.js'; import extend from '../../phet-core/js/extend.js'; import merge from '../../phet-core/js/merge.js'; import Node from '../../scenery/js/nodes/Node.js'; import PhetioObject from '../../tandem/js/PhetioObject.js'; import Tandem from '../../tandem/js/Tandem.js'; import sun from './sun.js'; import SunConstants from './SunConstants.js'; // constants // TODO: maybe provide a default value for a custom made enabledProperty like in AquaRadioButton `enabled`? const DEFAULT_OPTIONS = { enabledProperty: null, // {BooleanProperty} initialized in mixin if not provided enabledPropertyOptions: null, disabledOpacity: SunConstants.DISABLED_OPACITY, tandem: Tandem.OPTIONAL }; const ENABLED_PROPERTY_TANDEM_NAME = 'enabledProperty'; const EnabledComponent = { /** * @public * @param {function} type - The type (constructor) whose prototype we'll modify. */ mixInto: function( type ) { const proto = type.prototype; assert && assert( !proto.hasOwnProperty( 'setEnabled' ), 'do not want to overwrite' ); assert && assert( !proto.hasOwnProperty( 'getEnabled' ), 'do not want to overwrite' ); assert && assert( !proto.hasOwnProperty( 'enabled' ), 'do not want to overwrite' ); extend( proto, { /** * IMPORTANT: This must be called after the supertype constructor has been called. In es6 classes this is forced behavior, but * for older `inherit` style hierarchy, the developer must manually ensure this behavior. * * @param {Object} [options] */ initializeEnabledComponent: function( options ) { // can't provide both assert && assertMutuallyExclusiveOptions( options, [ 'enabledProperty' ], [ 'enabledPropertyOptions' ] ); options = merge( {}, DEFAULT_OPTIONS, options ); // validate options assert && assert( options.disabledOpacity >= 0 && options.disabledOpacity <= 1, 'invalid disabledOpacity: ' + options.disabledOpacity ); const mixedIntoNode = this instanceof Node; if ( mixedIntoNode ) { assertHasOwnProperties( this, [ 'interruptSubtreeInput', 'opacity', 'pickable', 'cursor' ] ); // used from the Node API } const mixedIntoPhetioObject = this instanceof PhetioObject; if ( mixedIntoPhetioObject ) { assertHasOwnProperties( this, [ 'isPhetioInstrumented', 'addLinkedElement', 'phetioFeatured' ] ); // used from the PhetioObject API } // does this mixin own the enabledProperty? const ownsEnabledProperty = !options.enabledProperty; // This phet-io support only applies to instances of PhetioObject if ( !ownsEnabledProperty && mixedIntoPhetioObject ) { assert && Tandem.PHET_IO_ENABLED && Tandem.errorOnFailedValidation() && this.isPhetioInstrumented() && assert( !!options.enabledProperty.phetioFeatured === !!this.phetioFeatured, 'provided enabledProperty must be phetioFeatured if this checkbox is' ); // If enabledProperty was passed in, PhET-iO wrappers like Studio needs to know about that linkage this.addLinkedElement( options.enabledProperty, { tandem: options.tandem.createTandem( ENABLED_PROPERTY_TANDEM_NAME ) } ); } // @public this.enabledProperty = options.enabledProperty || new BooleanProperty( true, merge( { tandem: options.tandem.createTandem( ENABLED_PROPERTY_TANDEM_NAME ), phetioDocumentation: 'When disabled, the component is grayed out and cannot be interacted with.', phetioFeatured: true }, options.enabledPropertyOptions ) ); let enabledListener = null; if ( mixedIntoNode ) { const cursor = this.cursor; enabledListener = enabled => { this.interruptSubtreeInput(); this.pickable = enabled; this.opacity = enabled ? 1.0 : options.disabledOpacity; // handle cursor by supporting setting back to what the cursor was when component was made disabled. this.cursor = enabled ? cursor : 'default'; }; this.enabledProperty.link( enabledListener ); } // @private called by dispose this._disposeEnabledComponent = () => { enabledListener && this.enabledProperty.unlink( enabledListener ); ownsEnabledProperty && this.enabledProperty.dispose(); }; }, /** * @public */ disposeEnabledComponent: function() { this._disposeEnabledComponent(); }, /** * @public * @param {boolean} enabled */ setEnabled: function( enabled ) { this.enabledProperty.value = enabled; }, set enabled( value ) { this.setEnabled( value ); }, /** * @public * @returns {boolean} */ getEnabled: function() { return this.enabledProperty.value; }, get enabled() { return this.getEnabled(); } } ); } }; sun.register( 'EnabledComponent', EnabledComponent ); export default EnabledComponent;
JavaScript
0.000001
@@ -422,35 +422,32 @@ import assertHas -Own Properties from @@ -467,35 +467,32 @@ ore/js/assertHas -Own Properties.js';%0A @@ -2647,35 +2647,32 @@ assertHas -Own Properties( this @@ -2899,19 +2899,16 @@ ssertHas -Own Properti
0fe79328e19b17eb5858797dae94363692fca20b
Bump the load timeout for subsuites
browser/subsuite.js
browser/subsuite.js
/** * @license * Copyright (c) 2014 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 */ (function() { /** * A Mocha suite (or suites) run within a child iframe, but reported as if they * are part of the current context. */ function SubSuite(url, parentScope) { var params = WCT.util.getParams(parentScope.location.search); delete params.cli_browser_id; params.bust = [Math.random()]; this.url = url + WCT.util.paramsToQuery(params); this.parentScope = parentScope; this.state = 'initializing'; } WCT.SubSuite = SubSuite; // SubSuites get a pretty generous load timeout by default. SubSuite.loadTimeout = 5000; // We can't maintain properties on iframe elements in Firefox/Safari/???, so we // track subSuites by URL. SubSuite._byUrl = {}; /** * @return {SubSuite} The `SubSuite` that was registered for this window. */ SubSuite.current = function() { return SubSuite.get(window); }; /** * @param {!Window} target A window to find the SubSuite of. * @return {SubSuite} The `SubSuite` that was registered for `target`. */ SubSuite.get = function(target) { var subSuite = SubSuite._byUrl[target.location.href]; if (subSuite || window.parent === window) return subSuite; // Otherwise, traverse. return window.parent.WCT.SubSuite.get(target); }; /** * Loads and runs the subsuite. * * @param {function} done Node-style callback. */ SubSuite.prototype.run = function(done) { WCT.util.debug('SubSuite#run', this.url); this.state = 'loading'; this.onRunComplete = done; this.iframe = document.createElement('iframe'); this.iframe.src = this.url; this.iframe.classList.add('subsuite'); var container = document.getElementById('subsuites'); if (!container) { container = document.createElement('div'); container.id = 'subsuites'; document.body.appendChild(container); } container.appendChild(this.iframe); // let the iframe expand the URL for us. this.url = this.iframe.src; SubSuite._byUrl[this.url] = this; this.timeoutId = setTimeout( this.loaded.bind(this, new Error('Timed out loading ' + this.url)), SubSuite.loadTimeout); this.iframe.addEventListener('error', this.loaded.bind(this, new Error('Failed to load document ' + this.url))); this.iframe.contentWindow.addEventListener('DOMContentLoaded', this.loaded.bind(this, null)); }; /** * Called when the sub suite's iframe has loaded (or errored during load). * * @param {*} error The error that occured, if any. */ SubSuite.prototype.loaded = function(error) { if (this.timeoutId) { clearTimeout(this.timeoutId); } if (error) { this.signalRunComplete(error); this.done(); } }; /** Called when the sub suite's tests are complete, so that it can clean up. */ SubSuite.prototype.done = function done() { WCT.util.debug('SubSuite#done', this.url, arguments); this.signalRunComplete(); if (!this.iframe) return; this.iframe.parentNode.removeChild(this.iframe); }; SubSuite.prototype.signalRunComplete = function signalRunComplete(error) { if (!this.onRunComplete) return; this.state = 'complete'; this.onRunComplete(error); this.onRunComplete = null; }; })();
JavaScript
0.000001
@@ -1073,9 +1073,10 @@ t = -5 +10 000; @@ -2961,24 +2961,78 @@ on(error) %7B%0A + WCT.util.debug('SubSuite#loaded', this.url, error);%0A if (this.t
cb1bacfac8fc9fd39bd5577371c42055decb591c
rename cacheBuster -> cacheBust, https://github.com/phetsims/chipper/issues/759
js/axon-test-config.js
js/axon-test-config.js
// Copyright 2019, University of Colorado Boulder /* * IMPORTANT: This file was auto-generated by "grunt generate-config". Please do not modify this directly. Instead * please modify axon/package.json to control dependencies. * * RequireJS configuration file for the axon sim. * Paths are relative to the location of this file. */ require.config( { deps: [ 'axon-tests' ], paths: { // Third-party libs text: '../../sherpa/lib/text-2.0.12', // PhET plugins sound: '../../chipper/js/requirejs-plugins/sound', image: '../../chipper/js/requirejs-plugins/image', mipmap: '../../chipper/js/requirejs-plugins/mipmap', string: '../../chipper/js/requirejs-plugins/string', ifphetio: '../../chipper/js/requirejs-plugins/ifphetio', // PhET libs, uppercase names to identify them in require.js imports. // IMPORTANT: DO NOT modify. This file is auto-generated. See documentation at the top. AXON: '.', BRAND: '../../brand/' + phet.chipper.brand + '/js', DOT: '../../dot/js', JOIST: '../../joist/js', KITE: '../../kite/js', PHETCOMMON: '../../phetcommon/js', PHET_CORE: '../../phet-core/js', PHET_IO: '../../phet-io/js', REPOSITORY: '..', SCENERY: '../../scenery/js', SCENERY_PHET: '../../scenery-phet/js', SUN: '../../sun/js', TAMBO: '../../tambo/js', TANDEM: '../../tandem/js' }, // optional cache buster to make browser refresh load all included scripts, can be disabled with ?cacheBuster=false urlArgs: phet.chipper.getCacheBusterArgs() } );
JavaScript
0
@@ -1402,18 +1402,16 @@ che bust -er to make @@ -1485,18 +1485,16 @@ acheBust -er =false%0A @@ -1528,18 +1528,16 @@ acheBust -er Args()%0A%7D
1ee3fef99ae982bf1221f827c437c014530c35b7
make verification field hidden
js/components/about.js
js/components/about.js
/** * @jsx React.DOM */ var React = require('react'); var Router = require('react-router'); var Link = Router.Link; var Tag = require('./tag'); var About = React.createClass({ componentWillMount: function(){ document.title = 'About'; }, render: function(){ return ( <div className="release-full article"> <h1>About</h1> <p>Enough Records is a netlabel (<a href="http://en.wikipedia.org/wiki/Netlabel">wikipedia link</a>). We have been active since 2001 and have no focus on any specific genre.</p> <h1>Release Terms</h1> <p>Our entire catalogue is free for download.</p> <p>Our releases are available in several free distribution platforms such as <a href="http://scene.org/dir.php?dir=%2Fmusic%2Fgroups%2Fenough_records/">Scene.Org</a>, <a href="http://archive.org/details/enough_records">Internet Archive</a>, <a href="http://sonicsquirrel.net/detail/label/enoughrecords/118">Sonic Squirrel</a>, <a href="http://freemusicarchive.org/label/Enough_Records/">Free Music Archive</a>, etc.</p> <p>Our releases are also available on a few commercial distribution and online radio platforms such as Last FM, Bandcamp, Spotify, iTunes, Amazon, Google Play, etc. Some of these platforms force us to put a price tag on our releases, we try to always set the possible minimum required. Any income from such platforms is used on promotional material for the label as described on our activity reports of <a href="http://enoughrecords.org/?p=450">2012</a> and <a href="http://enoughrecords.org/?p=726">2013</a>. We operate non-profit.</p> <p>Our releases are free of any DRM and have associated <a href="http://creativecommons.org/licenses/by-nc-sa/3.0/">Creative Commons BY-NC-SA 4.0</a> licenses (unless otherwise specified). Feel free to share, use and remix accordingly.</p> <h1>Demo Policy</h1> <p>We are closed to demos from new artists. We are trying to focus more on promoting our current (and very long) roster of artists. That doesn't mean it's impossible to debut a new artist on Enough, just highly unlikely.</p> <h1>Sub Labels</h1> <ul> <li><b>Catita!</b>, tagged as <Tag tag="c!">c!</Tag> in our database. It groups the 4 releases salvaged from digital oblivion as the Catita! netlabel stopped its activities. They focused on 8bit music.</li> <li><a href="http://enoughrecords.scene.org/anonymous_archives/">Anonymous Archives</a>, tagged as <Tag tag="Anon">Anon</Tag>. Our socio-political activist sub-label.</li> <li><b>[Esc.] Laboratory</b>, tagged as <Tag tag="[Esc.]">[Esc.]</Tag>. This sub-label groups the releases that are related to the <a href="http://www.esc-laboratory.com/">[Esc.] Laboratory</a> collective from Germany.</li> <li><b>Thisko</b>, tagged as <Tag tag="thisk">thisk</Tag>. This sub-label groups the releases related or co-released with our friends from <a href="http://thisco.net/">Thisco Records</a>.</li> </ul> <h1>Mailing List</h1> <p> <div id="mc_embed_signup"> <form action="//scene.us3.list-manage.com/subscribe/post?u=f8c1f1dae22f9657c634ea871&amp;id=163fce62d4" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" className="validate" target="_blank" noValidate> <div id="mc_embed_signup_scroll"> <input type="email" name="EMAIL" className="email" id="mce-EMAIL" placeholder="email address" required /> <div id="outside"><input type="text" name="b_f8c1f1dae22f9657c634ea871_163fce62d4" tabIndex="-1" /></div> <input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" className="button" /> </div> </form> </div> </p> <h1>Contact</h1> <p>We are present on all major social networks (<a href="https://www.facebook.com/enoughrec">facebook</a>, <a href="https://twitter.com/enoughrec">twitter</a> and <a href="https://plus.google.com/b/116362931350553021949/116362931350553021949/posts">google plus</a>).</p> <p>Any further inquiries about Enough Records please contact Filipe 'ps' Cruz by <a href="mailto:ps@enoughrecords.org">email</a>.</p> <h1>Acknowledgements</h1> <p>Enough Records was founded in 2001 by Fred, H4rv3st and ps.</p> <p>Thanks to everyone who helped us improve, run and promote Enough Records throughout the years, Enough Records would not be what it is without you.</p> <p>Website developed by <a href="http://twitter.com/danpeddle" target="_blank">Dan Peddle</a> and ps as an <a href="https://github.com/enoughrec/arecordlabel/">open source project</a>, feel free to fork, re-use and contribute.</p> </div> ); } }); module.exports = About;
JavaScript
0
@@ -3363,12 +3363,14 @@ pe=%22 -text +hidden %22 na