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
93fba4dc1d0e6fd85577e8ae3936d9ccb6e2ecad
add error message in m.mount
api/mount.js
api/mount.js
"use strict" var Vnode = require("../render/vnode") var autoredraw = require("../api/autoredraw") module.exports = function(renderer, pubsub) { return function(root, component) { if (component === null) { renderer.render(root, []) pubsub.unsubscribe(root.redraw) delete root.redraw return } var run = autoredraw(root, renderer, pubsub, function() { renderer.render(root, Vnode(component, undefined, undefined, undefined, undefined, undefined)) }) run() } }
JavaScript
0.000002
@@ -302,16 +302,129 @@ turn%0A%09%09%7D +%0A%09%09%0A%09%09if (component.view == null) throw new Error(%22m.mount(element, component) expects a component, not a vnode%22) %0A%0A%09%09var
94f65cff2dd53943c9eceb23de042e517c6d3956
Create an add function for user model.
model/user.js
model/user.js
var pool = require('./db'); function User(pid, name, passport, email, password, contact) { this.pid = pid; this.name = name; this.passport = passport; this.email = email; this.password = password; this.contact = contact; } User.get = function(pid, callback) { pool.getConnection(function(err, connection) { // Use the connection connection.query('SELECT * from passenger where ?', { "pid": pid }, function(err, rows, fields) { if (err) { return callback(err.code, null); } var output = []; for (var i in rows) { output.push(rows[i]); } callback(null, output); connection.release(); }); }); }; module.exports = User;
JavaScript
0
@@ -680,16 +680,703 @@ %7D);%0A%7D;%0A%0A +User.prototype.add = function(name, passport, email, password, contact, callback) %7B%0A%09var md5 = crypto.createHash('md5'),%0A%09%09password_MD5 = md5.update(password).digest('hex');%0A%09%09console.log(password_MD5);%0A%0A%09var user = %7B%0A%09%09name = this.name;%0A%09%09passport = this.passport;%0A%09%09email = this.email;%0A%09%09password = this. password_MD5;%0A%09%09contact = this.contact;%0A%09%7D;%0A%0A%09pool.getConection(function(err, connection) %7B%0A%09%09connection.query('INSERT INTO passenger SET ?', user, function(err, rows, fields) %7B%0A%09%09%09if (err) %7B%0A%09%09%09%09return callback(err.code, null);%0A%09%09%09%7D%0A%0A%09%09%09var output = %5B%5D;%0A%09%09%09for (var i in rows) %7B%0A%09%09%09%09output.push(rows%5Bi%5D);%0A%09%09%09%7D%0A%09%09%09callback(null, output);%0A%0A%09%09%09connection.release();%0A%09%09%7D);%0A%09%7D);%0A%0A%7D;%0A%0A module.e
631d4d8b4ff03629417012338ef9cfec52f0d298
Add HyperTerm HyperLinks plugin
hyperterm.js
hyperterm.js
module.exports = { config: { // default font size in pixels for all tabs fontSize: 12, // font family with optional fallbacks fontFamily: 'Menlo, "DejaVu Sans Mono", "Lucida Console", monospace', // `BEAM` for |, `UNDERLINE` for _, `BLOCK` for █ cursorShape: 'BLOCK', // custom css to embed in the main window css: '', // custom css to embed in the terminal window termCSS: '', // custom padding (css format, i.e.: `top right bottom left`) padding: '12px 14px', // the shell to run when spawning a new session (i.e. /usr/local/bin/fish) // if left empty, your system's login shell will be used by default shell: '' // for advanced config flags please refer to https://hyperterm.org/#cfg }, // a list of plugins to fetch and install from npm // format: [@org/]project[#version] // examples: // `hyperpower` // `@company/project` // `project#1.0.1` plugins: [ 'hyperterm-tomorrow-night' ], // in development, you can create a directory under // `~/.hyperterm_plugins/local/` and include it here // to load it and avoid it being `npm install`ed localPlugins: [] };
JavaScript
0
@@ -947,16 +947,34 @@ gins: %5B%0A + 'hyperlinks',%0A 'hyp
09e1f1931303f1264c1c3135b1de8706f594e390
fix typo
config.example.js
config.example.js
// # Ghost Configuration // Setup your Ghost install for various [environments](http://support.ghost.org/config/#about-environments). // Ghost runs in `development` mode by default. Full documentation can be found at http://support.ghost.org/config/ var path = require('path'), config; config = { // ### Production // When running Ghost in the wild, use the production environment. // Configure your URL and mail settings here production: { url: 'http://my-ghost-blog.com', mail: {}, database: { client: 'sqlite3', connection: { filename: path.join(__dirname, '/content/data/ghost.db') }, debug: false }, // 配置MySQL 数据库 /*database: { client: 'mysql', connection: { host : 'host', user : 'user', password : 'password', database : 'database', charset : 'utf8' }, debug: false },*/ server: { host: '127.0.0.1', port: '2368' }, //Storage.Now,we can support `qiniu`,`upyun`, `aliyun oss`, `aliyun ace-storage` and `local-file-store` storage: { provider: 'local-file-store' } // or // 参考文档: http://www.ghostchina.com/qiniu-cdn-for-ghost/ /*storage: { provider: 'qiniu', bucketname: 'your-bucket-name', ACCESS_KEY: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', SECRET_KEY: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', root: '/image/', prefix: 'http://your-bucket-name.qiniudn.com' }*/ // or // 参考文档: http://www.ghostchina.com/upyun-cdn-for-ghost/ /*storage: { provider: 'upyun', bucketname: 'your-bucket-name', username: 'your user name', password: 'your password', root: '/image/', prefix: 'http://your-bucket-name.b0.upaiyun.com' }*/ // or // 参考文档: http://www.ghostchina.com/aliyun-oss-for-ghost/ /*storage: { provider: 'oss', bucketname: 'your-bucket-name', ACCESS_KEY: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', SECRET_KEY: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', root: '/image/', endpoint: 'http://oss-cn-hangzhou.aliyuncs.com' //阿里云的上传端点是分地域的,需要单独设置 prefix: 'http://your-bucket-name.oss-cn-hangzhou.aliyuncs.com' }*/ }, // ### Development **(default)** development: { // The url to use when providing links to the site, E.g. in RSS and email. // Change this to your Ghost blog's published URL. url: 'http://localhost:2368', // Example mail config // Visit http://support.ghost.org/mail for instructions // ``` // mail: { // transport: 'SMTP', // options: { // service: 'Mailgun', // auth: { // user: '', // mailgun username // pass: '' // mailgun password // } // } // }, // ``` // #### Database // Ghost supports sqlite3 (default), MySQL & PostgreSQL database: { client: 'sqlite3', connection: { filename: path.join(__dirname, '/content/data/ghost-dev.db') }, debug: false }, // #### Server // Can be host & port (default), or socket server: { // Host to be passed to node's `net.Server#listen()` host: '127.0.0.1', // Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT` port: '2368' }, // #### Paths // Specify where your content directory lives paths: { contentPath: path.join(__dirname, '/content/') } }, // **Developers only need to edit below here** // ### Testing // Used when developing Ghost to run tests and check the health of Ghost // Uses a different port number testing: { url: 'http://127.0.0.1:2369', database: { client: 'sqlite3', connection: { filename: path.join(__dirname, '/content/data/ghost-test.db') } }, server: { host: '127.0.0.1', port: '2369' }, logging: false }, // ### Testing MySQL // Used by Travis - Automated testing run through GitHub 'testing-mysql': { url: 'http://127.0.0.1:2369', database: { client: 'mysql', connection: { host : '127.0.0.1', user : 'root', password : '', database : 'ghost_testing', charset : 'utf8' } }, server: { host: '127.0.0.1', port: '2369' }, logging: false }, // ### Testing pg // Used by Travis - Automated testing run through GitHub 'testing-pg': { url: 'http://127.0.0.1:2369', database: { client: 'pg', connection: { host : '127.0.0.1', user : 'postgres', password : '', database : 'ghost_testing', charset : 'utf8' } }, server: { host: '127.0.0.1', port: '2369' }, logging: false } }; module.exports = config;
JavaScript
0.999991
@@ -2486,16 +2486,17 @@ ncs.com' +, //%E9%98%BF%E9%87%8C%E4%BA%91%E7%9A%84
f55ce9e169a600693f6337711e823d28787e970a
Update translations
client/lang/en.js
client/lang/en.js
// This file was generated by silverstripe/cow from client/lang/src/en.json. // See https://github.com/tractorcow/cow for details if (typeof(ss) === 'undefined' || typeof(ss.i18n) === 'undefined') { if (typeof(console) !== 'undefined') { // eslint-disable-line no-console console.error('Class ss.i18n not defined'); // eslint-disable-line no-console } } else { ss.i18n.addDictionary('en', { "Admin.BATCH_ARCHIVE_PROMPT": "You have {num} page(s) selected.\n\nAre you sure you want to archive these pages?\n\nThese pages and all of their children pages will be unpublished and sent to the archive.", "Admin.BATCH_DELETELIVE_PROMPT": "You have {num} page(s) selected.\n\nDo you really want to delete these pages from live?", "Admin.BATCH_DELETE_PROMPT": "You have {num} page(s) selected.\n\nAre you sure you want to delete these pages?\n\nThese pages and all of their children pages will be deleted and sent to the archive.", "Admin.BATCH_PUBLISH_PROMPT": "You have {num} page(s) selected.\n\nDo you really want to publish?", "Admin.BATCH_RESTORE_PROMPT": "You have {num} page(s) selected.\n\nDo you really want to restore to stage?\n\nChildren of archived pages will be restored to the root level, unless those pages are also being restored.", "Admin.BATCH_UNPUBLISH_PROMPT": "You have {num} page(s) selected.\n\nDo you really want to unpublish", "Admin.SELECTONEPAGE": "Please select at least one page", "Admin.FormatExample": "Example: {format}", "Admin.NO_SIZE": "N/A", "Admin.CLOSE": "Close", "Admin.CONFIRMUNSAVED": "Are you sure you want to navigate away from this page?\n\nWARNING: Your changes have not been saved.\n\nPress OK to continue, or Cancel to stay on the current page.", "Admin.CONFIRMUNSAVEDSHORT": "WARNING: Your changes have not been saved.", "Admin.VALIDATIONERROR": "Validation Error", "Admin.NONE": "None", "Admin.EDIT": "Edit", "Admin.ANY": "Any", "Admin.ERRORINTRANSACTION": "An error occured while fetching data from the server\n Please try again later.", "Admin.DELETECONFIRMMESSAGE": "Are you sure you want to delete this record?", "Admin.EXPANDPANEL": "Expand panel", "Admin.COLLAPSEPANEL": "Collapse panel", "Admin.NOT_FOUND_COMPONENT": "The component here ({component}) failed to load, there is a chance that you may lose data when saving due to this." }); }
JavaScript
0
@@ -2223,162 +2223,10 @@ nel%22 -,%0A %22Admin.NOT_FOUND_COMPONENT%22: %22The component here (%7Bcomponent%7D) failed to load, there is a chance that you may lose data when saving due to this.%22 %0A%7D);%0A%7D -%0A
8d09dfad15a50aedee015cb13be2324717bc908f
add '**/.git' to ignore patterns, or nothing will build, https://github.com/phetsims/chipper/issues/565
js/grunt/lint.js
js/grunt/lint.js
// Copyright 2015, University of Colorado Boulder /** * Runs the lint rules on the specified files. * * @author Sam Reid (PhET Interactive Simulations) */ /* eslint-env node */ 'use strict'; // modules var eslint = require( 'eslint' ); var assert = require( 'assert' ); // constants var CLIEngine = eslint.CLIEngine; /** * Gets the relative path for the given repo. * @param {string} repo * @returns {string} */ var GET_PATH = function( repo ) { return '../' + repo; }; /** * @param grunt - the grunt instance * @param {string} target - 'dir'|'all'|'everything' * @param {Object} buildConfig */ module.exports = function( grunt, target, buildConfig ) { assert && assert( target === 'dir' || target === 'all' || target === 'everything', 'Bad lint target: ' + target ); var repositoryName = buildConfig.name; // --disable-eslint-cache disables the cache, useful for developing rules var cache = !grunt.option( 'disable-eslint-cache' ); var cli = new CLIEngine( { // Rules are specified in the .eslintrc file configFile: '../chipper/eslint/.eslintrc', // Caching only checks changed files or when the list of rules is changed. Changing the implementation of a // custom rule does not invalidate the cache. Caches are declared in .eslintcache files in the directory where // grunt was run from. cache: cache, // Our custom rules live here rulePaths: [ '../chipper/eslint/rules' ], // Where to store the target-specific cache file cacheFile: '../chipper/eslint/cache/' + repositoryName + '-' + target + '.eslintcache', // Files to skip for linting ignorePattern: [ '**/build', '**/node_modules', '../scenery/snapshots/**', '../sherpa/**', '../kite/js/parser/svgPath.js', '../phet-io-website/root/assets/js/ua-parser-0.7.12.min.js', '../phet-io-website/root/assets/js/jquery-1.12.3.min.js', '../phet-io-website/root/assets/highlight.js-9.1.0/highlight.pack.js', '../phet-io-website/root/assets/highlight.js-9.1.0/highlight.js', '../phet-io-website/root/assets/bootstrap-3.3.6-dist/js/npm.js', '../phet-io-website/root/assets/bootstrap-3.3.6-dist/js/bootstrap.min.js', '../phet-io-website/root/assets/bootstrap-3.3.6-dist/js/bootstrap.js', '../phet-io-website/root/assets/js/phet-io-ga.js' ] } ); // Identify the repos to be linted var files = target === 'dir' ? [ repositoryName ] : target === 'all' ? buildConfig.phetLibs : grunt.file.read( '../chipper/data/active-repos' ).trim().split( /\r?\n/ ); grunt.verbose.writeln( 'linting: ' + files ); // Use the correct relative paths files = files.map( GET_PATH ); // run the eslint step var report = cli.executeOnFiles( files ); // pretty print results to console if any (report.warningCount || report.errorCount) && grunt.log.write( cli.getFormatter()( report.results ) ); report.warningCount && grunt.fail.warn( report.warningCount + ' Lint Warnings' ); report.errorCount && grunt.fail.fatal( report.errorCount + ' Lint Errors' ); };
JavaScript
0
@@ -1638,16 +1638,33 @@ tern: %5B%0A + '**/.git',%0A '*
0e942007fefcd01dd997ba61b99c5941fe698484
add key to avoid warning
src/mentionPlugin/MentionSearch/index.js
src/mentionPlugin/MentionSearch/index.js
import React, { Component } from 'react'; import Dropdown from './Dropdown'; import MentionOption from './MentionOption'; import addMention from '../modifiers/addMention'; import styles from './styles'; export default (mentions) => { class MentionSearch extends Component { onMentionSelect = (mention) => { const newEditorState = addMention(this.props.editor.props.editorState, mention, this.lastSelection); this.props.editor.onChange(newEditorState); }; // Get the first 5 mentions that match getMentionsForFilter = () => ( mentions // TODO better search algorithm than startsWith // mentions.filter((mention) => mention.handle.startsWith(this.mentionSearch)).slice(0, 10) ); renderItemForMention = (mention) => ( <div key={ mention.handle } eventKey={ mention.handle } onClick={ this.onMentionSelect } > <span>{ mention.handle }</span> </div> ); render() { // TODO ask issac to provide begin & end down to the component as prop (in decorators) this.lastSelection = this.props.editor.props.editorState.getSelection(); return ( <span {...this.props} style={ styles.root }> { this.props.children } <Dropdown> { this.getMentionsForFilter().map((mention) => ( <MentionOption onMentionSelect={ this.onMentionSelect } mention={ mention } /> )) } </Dropdown> </span> ); } } return MentionSearch; };
JavaScript
0
@@ -1367,16 +1367,57 @@ nOption%0A + key=%7B mention.handle %7D%0A
7ac1da6709fc6d5671f3bedaf80dd8d8abd8a716
Fix submit check?
public/js/submit.js
public/js/submit.js
var select = document.getElementById('existing-type'); var input = document.getElementById("bottype"); var channel = document.getElementById("channel"); var username = document.getElementById("username"); var description = document.getElementById("type"); var form = document.getElementById("submit-form"); var stNew = document.getElementById("new-bot"); var stCorrect = document.getElementById("correction"); var chanGroup = document.getElementById("channel-group"); // Conditionally show description field if the type is a new one. function update() { if(parseInt(select.value, 10) == 0) { input.removeAttribute("hidden"); description.required = true; description.disabled = false; } else { input.setAttribute("hidden", true); description.required = false; description.disabled = true; } } select.addEventListener("change", update); update(); // Validation function formChecker() { if(channel.value.toLowerCase() == username.value.toLowerCase() && stNew.checked) channel.setCustomValidity("The bot user has to be different from the channel it is for."); else channel.setCustomValidity(""); return channel.validity.valid && username.validity.valid; } formChecker(); channel.addEventListener("keyup", formChecker); username.addEventListener("keyup", function() { formChecker(); username.setCustomValidity(""); }); form.addEventListener("submit", function(e) { if(!formChecker()) e.preventDefault(); //TODO also track errors/successes var _paq = _paq || []; _paq.push(['trackEvent', 'Submission', stNew.checked ? "Submit" : "Correct", username.value]); }); // User checking function checkBot(username, cbk) { var url = "https://api.twitchbots.info/v1/bot/" + username; var xhr = new XMLHttpRequest(); xhr.open("HEAD", url, true); xhr.onreadystatechange = function(e) { if(xhr.readyState === 2) cbk(xhr.status !== 404); }; xhr.send(); } function checkTwitchUser(username, cbk) { var url = "https://api.twitch.tv/kraken/users/" + username; var xhr = new XMLHttpRequest(); xhr.setRequestHeader('Client-ID', form.dataset.clientid); xhr.setRequestHeader('Accept', 'application/vnd.twitchtv.v3+json'); xhr.open("HEAD", url, true); xhr.onreadystatechange = function(e) { if(xhr.readyState === 2) { // Only reject if the status is 404 not found. cbk(xhr.status !== 404); } }; xhr.send(); } function validateFieldContent(field, shouldExist) { field.checkValidity(); if(field.validity.valid && field.value.length) { if(shouldExist && !stNew.checked) { checkBot(field.value, function(exists) { if(exists) field.setCustomValidity(""); else field.setCustomValidity("Only known bots can be corrected."); }); } else { checkTwitchUser(field.value, function(exists) { if(exists) field.setCustomValidity(""); else field.setCustomValidity("Must be an existing Twitch user."); if(shouldExist & field.validity.valid) { checkBot(field.value, function(exists) { if(exists) field.setCustomValidity("We already know about this bot."); else field.setCustomValidity(""); }); } }); } } } function stListener() { username.setCustomValidity(""); for(var i = 0; i < fields.length; ++i) { validateFieldContent(fields[i].field, fields[i].shouldExist); } if(stNew.checked) { chanGroup.removeAttribute("hidden"); } else { chanGroup.setAttribute("hidden", true); } } var fields = [ { field: channel, shouldExist: false }, { field: username, shouldExist: true } ]; for(var i = 0; i < fields.length; ++i) { fields[i].field.addEventListener("blur", validateFieldContent.bind(null, fields[i].field, fields[i].shouldExist)); validateFieldContent(fields[i].field, fields[i].shouldExist); } stNew.addEventListener("change", stListener); stCorrect.addEventListener("change", stListener);
JavaScript
0
@@ -2147,16 +2147,50 @@ quest(); +%0A%0A xhr.open(%22HEAD%22, url, true); %0A xhr @@ -2319,42 +2319,8 @@ n'); -%0A%0A xhr.open(%22HEAD%22, url, true); %0A
7fc7fce91305df35c7283399564aba0c52482bd7
make plugin chainable
js/onebox.min.js
js/onebox.min.js
(function($){jQuery.fn.exists=function(){return this.length>0;};})(jQuery);(function($){jQuery.fn.onebox=function(){if($(this).exists()){return this.each(function(){var $this=$(this),url=$(this).children().eq(0).attr("href"),title="",description="";if($(this).data("title"))title=$(this).data("title");if($(this).data("description"))description=$(this).data("description");var requesturl=OneboxParams.renderURL +(OneboxParams.renderURL.indexOf('?')!=-1?"&onebox_url=":"?onebox_url=")+encodeURIComponent(url) +"&onebox_title="+encodeURIComponent(title) +"&onebox_description="+encodeURIComponent(description);$.getJSON(requesturl,function(data){if(data.data){if(data.data.displayurl)url=data.data.displayurl;else url=data.data.url;var template=OneboxParams.template;if(OneboxParams.flat)data.classes+=' flat';if(OneboxParams.dark)data.classes+=' dark';template=template.replace(/{url}/g,url);template=template.replace(/{class}/g,data.classes);if(data.data.favicon)template=template.replace(/{favicon}/g,'<img src="'+data.data.favicon+'" class="onebox-favicon"/>');else template=template.replace(/{favicon}/g,'');template=template.replace(/{sitename}/g,data.data.sitename);if(data.data.image)template=template.replace(/{image}/g,'<img src="'+data.data.image+'" class="onebox-thumbnail"/>');else template=template.replace(/{image}/g,'');template=template.replace(/{title}/g,data.data.title);template=template.replace(/{description}/g,data.data.description);template=template.replace(/{additional}/g,data.data.additional);template=template.replace(/{footer}/g,data.data.footer);template=template.replace(/{title-button}/g,data.data.titlebutton);template=template.replace(/{footer-button}/g,data.data.footerbutton);$this.html(template);$this.find('.onebox-stars').oneboxstars();}});});}};})(jQuery);(function($){jQuery.fn.oneboxstars=function(){if($(this).exists()){return this.each(function(){var val=parseFloat($(this).html());var size=Math.max(0,(Math.min(5,val)))*16;var $span=$('<span />').width(size);$(this).html($span);});}};})(jQuery);jQuery(document).ready(function(){if(OneboxParams.selector)jQuery(OneboxParams.selector).onebox();});
JavaScript
0
@@ -1771,24 +1771,42 @@ s();%7D%7D);%7D);%7D +%0Aelse return this; %7D;%7D)(jQuery) @@ -2038,16 +2038,34 @@ an);%7D);%7D +%0Aelse return this; %7D;%7D)(jQu
9278e9ebd52c030e7be203eba6de08058ec6719c
Revert compact() back to an array filter()
lib/findJsModulesFor.js
lib/findJsModulesFor.js
// @flow import escapeRegExp from 'lodash.escaperegexp'; import minimatch from 'minimatch'; import sortBy from 'lodash.sortby'; import uniqBy from 'lodash.uniqby'; import Configuration from './Configuration'; import JsModule from './JsModule'; import findMatchingFiles from './findMatchingFiles'; import formattedToRegex from './formattedToRegex'; function findImportsFromEnvironment( config: Configuration, variableName: string ): Array<JsModule> { return config.get('coreModules') .filter((dep: string): boolean => dep.toLowerCase() === variableName.toLowerCase()) .map((dep: string): JsModule => new JsModule({ importPath: dep, variableName, })); } function compact<T>(arr: Array<?T>): Array<T> { const result = []; for (let i = 0; i < arr.length; i++) { if (!!arr[i]) { result.push(arr[i]); } } return result; } function findImportsFromPackageJson( config: Configuration, variableName: string ): Array<JsModule> { const formattedVarName = formattedToRegex(variableName); const ignorePrefixes = config.get('ignorePackagePrefixes') .map((prefix: string): string => escapeRegExp(prefix)); const depRegex = RegExp( `^(?:${ignorePrefixes.join('|')})?${formattedVarName}$` ); const modules = config.get('packageDependencies') .filter((dep: string): boolean => depRegex.test(dep)) .map((dep: string): ?JsModule => ( JsModule.construct({ lookupPath: 'node_modules', relativeFilePath: `node_modules/${dep}/package.json`, stripFileExtensions: [], variableName, workingDirectory: config.workingDirectory, }) )); return compact(modules); } function findImportsFromLocalFiles( config: Configuration, variableName: string, pathToCurrentFile: string ): Promise<Array<JsModule>> { return new Promise((resolve: Function, reject: Function) => { const lookupPaths = config.get('lookupPaths'); const promises = lookupPaths.map((lookupPath: string): Promise<Array<string>> => findMatchingFiles(lookupPath, variableName, config.workingDirectory)); Promise.all(promises).then((results: Array<Array<string>>) => { const matchedModules = []; const excludes = config.get('excludes'); results.forEach((files: Array<string>, index: number) => { // Grab the lookup path originally associated with the promise. Because // Promise.all maintains the order of promises, we can use the index // here. const lookupPath = lookupPaths[index]; files.forEach((f: string) => { const isExcluded = excludes .some((globPattern: string): boolean => minimatch(f, globPattern)); if (isExcluded) { return; } const module = JsModule.construct({ lookupPath, relativeFilePath: f, stripFileExtensions: config.get('stripFileExtensions', { pathToImportedModule: f }), makeRelativeTo: config.get('useRelativePaths', { pathToImportedModule: f }) && pathToCurrentFile, stripFromPath: config.get('stripFromPath', { pathToImportedModule: f }), variableName, workingDirectory: config.workingDirectory, }); if (module) { matchedModules.push(module); } }); }); resolve(matchedModules); }).catch((error: Object) => { reject(error); }); }); } export default function findJsModulesFor( config: Configuration, variableName: string, pathToCurrentFile: string ): Promise<Array<JsModule>> { return new Promise((resolve: Function, reject: Function) => { const aliasModule = config.resolveAlias(variableName, pathToCurrentFile); if (aliasModule) { resolve([aliasModule]); return; } const namedImportsModule = config.resolveNamedExports(variableName); if (namedImportsModule) { resolve([namedImportsModule]); return; } let matchedModules = []; matchedModules.push(...findImportsFromEnvironment(config, variableName)); matchedModules.push(...findImportsFromPackageJson(config, variableName)); findImportsFromLocalFiles(config, variableName, pathToCurrentFile) .then((modules: Array<JsModule>) => { matchedModules.push(...modules); // If you have overlapping lookup paths, you might end up seeing the same // module to import twice. In order to dedupe these, we remove the module // with the longest path matchedModules = sortBy( matchedModules, (module: JsModule): number => module.importPath.length ); matchedModules = uniqBy( matchedModules, (module: JsModule): string => module.filePath ); resolve(sortBy( matchedModules, (module: JsModule): string => module.displayName() )); }).catch((error: Object) => { reject(error); }); }); }
JavaScript
0
@@ -683,195 +683,8 @@ %0A%7D%0A%0A -function compact%3CT%3E(arr: Array%3C?T%3E): Array%3CT%3E %7B%0A const result = %5B%5D;%0A for (let i = 0; i %3C arr.length; i++) %7B%0A if (!!arr%5Bi%5D) %7B%0A result.push(arr%5Bi%5D);%0A %7D%0A %7D%0A return result;%0A%7D%0A%0A func @@ -716,16 +716,16 @@ geJson(%0A + config @@ -1066,23 +1066,14 @@ %0A%0A -const modules = +return con @@ -1450,35 +1450,28 @@ )) -;%0A %0A -return compact(modules + .filter(Boolean );%0A%7D
7b679fa06d2d2427fb6797723e976f50c9098fd1
add missing istanbul ignore
template/content/server.js
template/content/server.js
#!/usr/bin/env node 'use strict'; var fileStart = Date.now(); var hostname = require('os').hostname; var process = require('process'); var path = require('path'); var getRepoInfo = require('git-repo-info'); var parseArgs = require('minimist'); var setTimeout = require('timers').setTimeout; var Application = require('./app.js'); module.exports = main; /*istanbul ignore else: dead branch*/ if (require.main === module) { main({ argv: parseArgs(process.argv.slice(2)) }); } function main(opts) { var mainStart = Date.now(); var processTitle = opts.argv && opts.argv.processTitle; if (typeof processTitle === 'string') { process.title = processTitle; } else { process.title = 'my-title-' + hostname(); } /*eslint no-process-exit: 0*/ var app = Application(); // attach before throwing exception process.on('uncaughtException', app.clients.uncaught); var gitRepo = path.join(__dirname, '.git'); var gitSha = getRepoInfo(gitRepo).sha; app.bootstrap(onAppReady); var bootstrapEnd = Date.now(); function onAppReady(err) { /*istanbul ignore if: should never happen in prod*/ if (err) { app.clients.logger.fatal('Could not start', { error: err }); app.clients.onError(err); var abortTimeout = app.config.get( 'clients.uncaught-exception.abortTimeout' ); setTimeout(abort, abortTimeout); return; } var now = Date.now(); app.clients.logger.info('server started', { serverAddress: app.clients.rootChannel.address(), gitSha: gitSha, startupTiming: { beforeMain: mainStart - fileStart, appTime: bootstrapEnd - mainStart, startTime: now - bootstrapEnd, totalTime: now - fileStart } }); app.clients.statsd.timing('server.startup-time', now - mainStart); } } function abort() { process.abort(); }
JavaScript
0.998638
@@ -2027,24 +2027,49 @@ );%0A %7D%0A%7D%0A%0A +/*istanbul ignore next*/%0A function abo
f360fa1bd09a47b3c9e49cd90c8dddd136a13e0c
Enable lint rule strict and autofix all occurrences, see https://github.com/phetsims/chipper/issues/814
js/assert.js
js/assert.js
// Copyright 2013-2021, University of Colorado Boulder /* * @author Jonathan Olson <[email protected]> */ ( function() { 'use strict'; window.assertions = window.assertions || {}; window.assertions.assertFunction = window.assertions.assertFunction || function( predicate, message ) { if ( !predicate ) { // Log the stack trace to IE. Just creating an Error is not enough, it has to be caught to get a stack. if ( window.navigator && window.navigator.appName === 'Microsoft Internet Explorer' ) { try { throw new Error(); } catch( e ) { message = `${message}, stack=\n${e.stack}`; } } const logMessage = message ? `Assertion failed: ${message}` : 'Assertion failed'; console && console.log && console.log( logMessage ); if ( window.phet && phet.chipper && phet.chipper.queryParameters && phet.chipper.queryParameters.debugger ) { debugger; // eslint-disable-line no-debugger } throw new Error( logMessage ); } }; window.assert = window.assert || null; window.assertSlow = window.assertSlow || null; window.assertions.enableAssert = function() { window.assert = window.assertions.assertFunction; window.console && window.console.log && window.console.log( 'enabling assert' ); }; window.assertions.disableAssert = function() { window.assert = null; window.console && window.console.log && window.console.log( 'disabling assert' ); }; window.assertions.enableAssertSlow = function() { window.assertSlow = window.assertions.assertFunction; window.console && window.console.log && window.console.log( 'enabling assertSlow' ); }; window.assertions.disableAssertSlow = function() { window.assertSlow = null; window.console && window.console.log && window.console.log( 'disabling assertSlow' ); }; } )();
JavaScript
0
@@ -134,21 +134,8 @@ %7B%0A -'use strict'; %0A%0A
db1a0853d3b4338ea5114f949a22029c4eb09c38
Use production react-onsenui to avoid errors.
js/config.js
js/config.js
/* global app */ app.config = {}; app.config.platform = 'ios'; app.config.codeType = 'javascript'; app.config.cdn = 'https://unpkg.com/'; app.config.ci = 'https://circleci.com/api/v1/project/OnsenUI/OnsenUI/latest/artifacts/0/$CIRCLE_ARTIFACTS/'; app.config.nightly = window.sessionStorage.getItem('nightly') === 'true'; // Enables local lib versions if ((window.location.hostname === 'localhost' || window.location.hostname.match(/[0-9.]+/)) && window.location.pathname.indexOf('/tutorial/') === 0) { app.config.local = true; } app.config.getCdnUrl = function(lib, path, forceRemote, skipNightly) { // Fetch from local disk if (app.config.local === true && !forceRemote) { let directory = '../../OnsenUI/'; if (lib === 'onsenui') { directory += 'build/'; } else { directory += `bindings/${lib.split('-')[0]}/`; } return directory + path; } // Fetch from remote CDN // CORS browser issue with fonts from the same server if (skipNightly) { return `${app.config.cdn}${lib}${!app.config.versions.onsenui || app.config.nightly ? '' : ('@' + app.config.versions.onsenui)}/${path}`; } var url = app.config.nightly ? app.config.ci : app.config.cdn; url += `${lib}${(app.config.versions[lib] && !app.config.nightly ? ('@' + app.config.versions[lib]) : '')}/${path}`; if (app.config.nightly) { url += '?branch=master&filter=successful'; } return url; }; app.config.ownLibs = ['onsenui', 'react-onsenui', 'ngx-onsenui', 'vue-onsenui']; app.config.extLibs = ['react', 'angular1', 'angular2', 'vue']; app.config.defaultVersions = { react: '15.4.2', angular1: '1.5.5', angular2: '4.3.6', vue: '2.4.1' }; app.config.versions = {}; (app.config.ownLibs.concat(app.config.extLibs)).forEach(function(key) { app.config.versions[key] = window.sessionStorage.getItem(key + '-version') || app.config.defaultVersions[key]; }); app.config.ownLibs.forEach(function (libName) { if (app.config.local) { console.info(`Using local version of ${libName}.js`); } else if (app.config.nightly) { console.info(`Using ${libName}.js nightly build`); } else if (app.config.versions[libName]) { console.info(`Using ${libName}.js ${app.config.versions[libName]}`); } else { console.info(`Using latest release of ${libName}.js`); } }); app.config.lib = function(forceRemote) { return { js: { // Vanilla onsenui: app.config.getCdnUrl('onsenui', 'js/onsenui.js', forceRemote), // AngularJS angular1: `https://cdnjs.cloudflare.com/ajax/libs/angular.js/${app.config.versions.angular1}/angular.min.js`, angularOnsenui: app.config.getCdnUrl('onsenui', 'js/angular-onsenui.js', forceRemote), // React react: `https://cdnjs.cloudflare.com/ajax/libs/react/${app.config.versions.react}/react.min.js`, reactDom: `https://cdnjs.cloudflare.com/ajax/libs/react/${app.config.versions.react}/react-dom.min.js`, // propTypes: `https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.js`, reactOnsenui: app.config.getCdnUrl('react-onsenui', 'dist/react-onsenui.js', forceRemote), // Vue vue: `https://cdnjs.cloudflare.com/ajax/libs/vue/${app.config.versions.vue}/vue.js`, vueOnsenui: app.config.getCdnUrl('vue-onsenui', 'dist/vue-onsenui.js', forceRemote), // Angular 2+ zone: 'https://cdnjs.cloudflare.com/ajax/libs/zone.js/0.8.18/zone.min.js', corejs: 'https://cdnjs.cloudflare.com/ajax/libs/core-js/2.5.1/core.min.js', systemjs: 'https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.47/system.js' // 0.20.18 caused `Fetch error: 404 Not Found` }, css: { onsenui: app.config.getCdnUrl('onsenui', 'css/onsenui.css', forceRemote, true), onsenuiCssComponents: app.config.getCdnUrl('onsenui', 'css/onsen-css-components.css', forceRemote) } }; }; app.config.transpilerLib = { 'babel': "https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js", 'typescript': "https://cdnjs.cloudflare.com/ajax/libs/typescript/2.5.2/typescript.min.js" };
JavaScript
0
@@ -3080,32 +3080,36 @@ t/react-onsenui. +min. js', forceRemote
a7ed648a58e73c21e4ba8fb99a19ca761f3767ff
Update header.js
js/header.js
js/header.js
document.write('\ \ <div class="logo">\ <a href="https://cont3mpo.github.io" title="Inicio"><span class="red">O</span>Contempo</a>\ </div>\ <nav>\ <ul>\ <li><a href="../../blog.html" title="Blog">Blog</a></li>\ <li><a href="../../articulos.html" title="Artículos del blog">Artículos</a></li>\ <li><a href="../../contacto.html" title="Sobre mí">Yo</a></li>\ </ul>\ </nav>\ \ ');
JavaScript
0.000001
@@ -316,78 +316,8 @@ i%3E%5C%0A - %3Cli%3E%3Ca href=%22../../contacto.html%22 title=%22Sobre m%C3%AD%22%3EYo%3C/a%3E%3C/li%3E%5C%0A
d66d497af789cbbfcc1caa6967e0724fee9f1755
clean up use of var
src/commands/restart.js
src/commands/restart.js
'use strict'; const chalk = require('chalk'); const _ = require('lodash'); const shell = require('shelljs'); var kexec = require('kexec'); const console = require('../console'); module.exports = { command: 'restart', config: { description: 'Restarts Fractal. Use if you have made changes to your fractal.js file', scope: ['project'], hidden: false }, action: function (args, done) { this.console.notice('Restarting... [any running servers will need to be restarted individually]'); kexec('fractal', ['--restart']); done(); } };
JavaScript
0.000006
@@ -117,18 +117,22 @@ ');%0A -var +const kexec + = re
59c0e6ce3242e835f50642f2432865c7f8f60b94
remove `ForeignFunction.build()`
lib/foreign_function.js
lib/foreign_function.js
var ffi = require('./ffi') , assert = require('assert') , debug = require('debug')('ffi:ForeignFunction') , ref = require('ref') , EventEmitter = require('events').EventEmitter , POINTER_SIZE = ref.sizeof.pointer , FFI_ARG_SIZE = ffi.Bindings.FFI_ARG_SIZE /** * Represents a foreign function in another library. Manages all of the aspects * of function execution, including marshalling the data parameters for the * function into native types and also unmarshalling the return from function * execution. */ function ForeignFunction (func, returnType, argTypes, abi) { debug('creating new ForeignFunction', func) // check args assert(Buffer.isBuffer(func), 'expected Buffer as first argument') assert(!!returnType, 'expected a return "type" object as the second argument') assert(Array.isArray(argTypes), 'expected Array of arg "type" objects as the third argument') // "result" must point to storage that is sizeof(long) or larger. For smaller // return value sizes, the ffi_arg or ffi_sarg integral type must be used to // hold the return value var resultSize = returnType.size >= ref.sizeof.long ? returnType.size : FFI_ARG_SIZE // the array of `ffi_type *` instances for the argument types var numArgs = argTypes.length , argsArraySize = numArgs * POINTER_SIZE // normalize the "types" (they could be strings, so turn into real type // instances) returnType = ffi.coerceType(returnType) argTypes = argTypes.map(ffi.coerceType) // create the `ffi_cif *` instance var cif = ffi.CIF(returnType, argTypes, abi) /** * This is the actual JS function that gets returned. * It handles marshalling input arguments into C values, * and unmarshalling the return value back into a JS value */ var proxy = function () { debug('invoking proxy function', returnType, argTypes) if (arguments.length !== numArgs) { throw new TypeError('Expected ' + numArgs + ' arguments, got ' + arguments.length) } // storage buffers for input arguments and the return value var result = new Buffer(resultSize) , argsList = new Buffer(argsArraySize) // write arguments to storage areas for (var i = 0; i < numArgs; i++) { var argType = argTypes[i] , val = arguments[i] var valPtr = ref.alloc(argType, val) argsList.writePointer(valPtr, i * POINTER_SIZE) } // invoke the `ffi_call()` function ffi.Bindings.ffi_call(cif, func, result, argsList) result.type = returnType return ref.deref(result) } /** * The asynchronous version of the proxy function. */ proxy.async = function () { debug('invoking async proxy function', returnType, argTypes) var argc = arguments.length if (argc !== numArgs + 1) { throw new TypeError('Expected ' + (numArgs + 1) + ' arguments, got ' + argc) } var callback = arguments[argc - 1] if (typeof callback !== 'function') { throw new TypeError('Expected a callback function as argument number: ' + (argc - 1)) } // storage buffers for input arguments and the return value var result = new Buffer(resultSize) , argsList = new Buffer(argsArraySize) result.type = returnType // write arguments to storage areas for (var i = 0; i < numArgs; i++) { var argType = argTypes[i] , val = arguments[i] var valPtr = ref.alloc(argType, val) argsList.writePointer(valPtr, i * POINTER_SIZE) } // invoke the `ffi_call()` function asynchronously ffi.Bindings.ffi_call_async(cif, func, result, argsList, function (err) { if (err) { callback(err) } else { callback(null, ref.deref(result)) } }) } return proxy } module.exports = ForeignFunction ForeignFunction.build = function () { debug('DEPRECATED') return ForeignFunction.apply(null, arguments) }
JavaScript
0
@@ -3790,115 +3790,4 @@ ion%0A -%0AForeignFunction.build = function () %7B%0A debug('DEPRECATED')%0A return ForeignFunction.apply(null, arguments)%0A%7D%0A
de8d7e0593bc9b9112b11b421f314ab26cccd5ac
Update script.js
js/script.js
js/script.js
var c = documnet.getElementById("mapCanvas"); var ctx = c.getContext("2d"); ctx.beginPath(); ctx.arc(95,50,40,0,2*Math.PI); ctx.stroke();
JavaScript
0.000002
@@ -10,10 +10,10 @@ ocum -n e +n t.ge
0c9faca0982126c8cd21767ebb81bac2fdbbcda0
remove run and stop functions, add reduce check the position of the elements
js/script.js
js/script.js
var items = document.querySelectorAll('.parallax'); for (var i = 0; i < items.length; i++ ) { var item = items[i]; parallax(item); } function parallax(item) { var current = item, currentFriction = current.getAttribute('data-friction'), wrap = current.getBoundingClientRect(), top = wrap.top + pageYOffset, bottom = top + wrap.height; document.addEventListener('scroll', function(e) { var winH = window.innerHeight, winBottom = pageYOffset + winH, offset = winBottom - top, diff = offset*currentFriction; window.requestAnimationFrame(function () { if(top < winBottom && bottom >= pageYOffset) { parallaxRun(item, diff); } if(bottom < pageYOffset || top > winBottom) { parallaxStop(item); } }); }); } function parallaxRun(item, diff) { item.style.transform = "translate3d(0, " + diff + "%, 0)"; } function parallaxStop(item) { item.style.transform = ""; }
JavaScript
0
@@ -92,31 +92,8 @@ ) %7B%0A -%09var item = items%5Bi%5D;%0A%0A %09par @@ -102,16 +102,20 @@ lax(item +s%5Bi%5D );%0A%7D%0A%0Afu @@ -544,9 +544,11 @@ fset -* + * curr @@ -609,16 +609,33 @@ () %7B -%0A%09%09%09%0A%09%09%09 + %0A if(t @@ -681,291 +681,193 @@ ) %7B%0A -%09%09%09%09parallaxRun(item, diff);%0A%09%09%09%7D%0A%0A%09%09%09if(bottom %3C pageYOffset %7C%7C top %3E winBottom) %7B%0A%09%09%09%09parallaxStop(item);%09%0A%09%09%09%7D%0A%09%09%7D);%0A%09%7D);%0A%7D%0A%0Afunction parallaxRun(item, diff) %7B%0A%09item.style.transform = %22translate3d(0, %22 + diff + %22%25, 0)%22;%0A%7D%0A%0Afunction parallaxStop(item) %7B%0A%09item.style.transform = %22%22;%09 + return item.style.transform = %22translate3d(0, %22 + diff + %22%25, 0)%22;%0A %7D %0A return item.style.transform = %22%22; %0A %7D);%0A%09%7D); %0A%7D%0A
bb633c0519f383a4f2a83aa7a63558df8f7196a7
Add more sugar to helper for iterating compound operations.
src/operation_helpers.js
src/operation_helpers.js
var Helpers = {}; Helpers.last = function(op) { if (op.type === "compound") { return op.ops[op.ops.length-1]; } return op; }; Helpers.each = function(op, iterator, context) { if (op.type === "compound") { for (var i = 0; i < op.ops.length; i++) { var child = op.ops[i]; if (child.type === "compound") Helpers.each(child, iterator, context); else iterator.call(context, child); } } else { iterator.call(context, op); } }; module.exports = Helpers;
JavaScript
0.999999
@@ -127,24 +127,291 @@ urn op;%0A%7D;%0A%0A +// Iterates all atomic operations contained in a given operation%0A// --------%0A//%0A// - op: an Operation instance%0A// - iterator: a %60function(op)%60%0A// - context: the %60this%60 context for the iterator function%0A// - reverse: if present, the operations are iterated reversely%0A%0A Helpers.each @@ -443,16 +443,25 @@ context +, reverse ) %7B%0A if @@ -484,24 +484,51 @@ ompound%22) %7B%0A + var l = op.ops.length;%0A for (var @@ -539,29 +539,17 @@ 0; i %3C -op.ops.length +l ; i++) %7B @@ -578,16 +578,76 @@ ops%5Bi%5D;%0A + if (reverse) %7B%0A child = op.ops%5Bl-i-1%5D;%0A %7D%0A if @@ -675,16 +675,30 @@ pound%22) +%7B%0A if ( Helpers. @@ -730,58 +730,206 @@ text -);%0A else iterator.call(context, child);%0A %7D +, reverse) === false) %7B%0A return false;%0A %7D%0A %7D%0A else %7B%0A if (iterator.call(context, child) === false) %7B%0A return false;%0A %7D%0A %7D%0A %7D%0A return true; %0A %7D @@ -940,16 +940,23 @@ e %7B%0A +return iterator
461c4fc0a27a1910c2e0b2e3c3c71cc4f2e3f8c8
Remove dead code
js/script.js
js/script.js
/*jslint browser: true */ (function() { "use strict"; var originalTitle = document.title, // originalURL = document.location.origin + "?name=", originalURL = document.location.href.replace(document.location.search, "") + "?name=", QshareURL = document.querySelector("section a"), decode = {}, encode = { " " : "%20", "&" : "%26", "'" : "%27", "\"": "%22", }; // Create the decoding object for (var k in encode) { if (encode.hasOwnProperty(k)) { decode[encode[k]] = k; } } /** * Encode URL escape characters in a person's name. * @param {String} name The person's name. * @returns {String} */ function encodeName(name) { for (var i = 0, len = name.length; i < len; i++) { var letter = name[i]; if (encode[letter] !== undefined) { name = name.replace(letter, encode[letter]); } } return name; } /** * Decode URL escape characters in a person's name. * @param {String} name The person's name. * @returns {String} */ function decodeName(name) { for (var k in decode) { if (decode.hasOwnProperty(k)) { name = name.replace(k, decode[k]); } } return name; } /** * Generate a sharing URL. * @param {String} name The person's name. */ function makeShareLink(name) { QshareURL.innerHTML = originalURL + decodeName(name); QshareURL.href = originalURL + encodeName(name); } /** * Update the page title with the person's name. * @param {String} name The person's name. */ function updatePageTitle(name) { document.title = decodeName(name) + " " + originalTitle; } // Initial setup of the share link QshareURL.innerHTML = originalURL; QshareURL.href = originalURL; // Update everything on keypress document.querySelector("header input").addEventListener("input", function() { updatePageTitle(this.value); makeShareLink(this.value); }); window.onload = function() { var qs = window.location.search; // No query string was given if (!/\?name=.+?$/.test(qs)) { return false; } // Get just the name and update all displays var name = qs.split("=")[1]; updatePageTitle(name); makeShareLink(name); document.querySelector("header input").value = decodeName(name); }; }());
JavaScript
0.001497
@@ -92,81 +92,8 @@ le,%0A - // originalURL = document.location.origin + %22?name=%22,%0A
c17ababf00db25a6cd6657aaa99791299a4cf7fe
Comment Juxta.Uptime
js/uptime.js
js/uptime.js
/** * @class Server uptime * @param {jQuery, String} Container */ Juxta.Uptime = function(container) { /** * @type {jQuery} */ var _container = $(container); /** * @type {String} */ var _selector = _container.selector; /** * @type {Number} */ var _time; /** * @type {String} */ var _interval; /** * @type {String} */ var _state = null; /** * Timer */ var _timer = function() { // var days, hours, minutes, seconds = _time; days = Math.floor(seconds / (3600 * 24)); seconds = Math.round(seconds / (3600 * 24) % 1 * (3600 * 24)); hours = Math.floor(seconds / 3600); seconds = Math.round(seconds / 3600 % 1 * 3600); minutes = Math.floor(seconds / 60); seconds = Math.round(seconds / 60 % 1 * 60); _time++; var state = [days, hours, minutes].join(); if (state === _state) { return; } _state = state; var uptimeString = ''; if (days === 0 && hours === 0) { // if (minutes === 0) { minutes = 1; } uptimeString = minutes; if (minutes === 1) { uptimeString += ' minute'; } else { uptimeString += ' minutes'; } } else { if (days) { uptimeString += days; if (days === 1) { uptimeString += ' day, '; } else { uptimeString += ' days, '; } } uptimeString += hours + ':'; // Minutes with leading zero uptimeString += (minutes < 10 ? '0' : '') + minutes; } _container.text(uptimeString); } var _startTime; /** * Start timer * @method start */ this.start = function(uptime) { // this.stop(); _container = $(_selector); var that = this; _time = uptime; _startTime = new Date(Date.now() - uptime * 1000); _timer(); _interval = setInterval(function() { _timer.call(that); }, 1000); } /** * Stop timer * @method stop */ this.stop = function () { clearInterval(_interval); } /** * Returns start time * @method getStartTime * @return {Date} */ this.getStartTime = function() { return _startTime; } }
JavaScript
0
@@ -1,12 +1,60 @@ /**%0A + * Counts the time since the server was started%0A * @clas
9c72c1d91f87fbeb363fb8d7ad72648be5b2bfd7
check size of README
bids-validator/validators/bids/checkReadme.js
bids-validator/validators/bids/checkReadme.js
const Issue = require('../../utils').issues.Issue const checkReadme = fileList => { const issues = [] const fileKeys = Object.keys(fileList) const hasReadme = fileKeys.some(key => { const file = fileList[key] return file.relativePath && file.relativePath == '/README' }) if (!hasReadme) { issues.push(new Issue({ code: 101 })) } return issues } export default checkReadme
JavaScript
0.000001
@@ -1,12 +1,53 @@ +import isNode from '../../utils/isNode'%0A%0A const Issue @@ -384,16 +384,447 @@ 101 %7D))%0A + %7D else %7B%0A // Get the README file object%0A for (var key in fileList) %7B%0A if (fileList%5Bkey%5D.name == 'README') %7B%0A var readmeFile = fileList%5Bkey%5D%0A break%0A %7D%0A %7D%0A%0A // Check size and raise warning if too small%0A const size = !isNode ? readmeFile.size : readmeFile.stats.size%0A var failsSizeRequirement = size %3C= 5000%0A if (failsSizeRequirement) %7B%0A issues.push(new Issue(%7B code: 101 %7D))%0A %7D%0A %7D%0A re
e896f6b18db8a4928ae81d1c726f28b1195adce9
Bump schema
src/database/schema.js
src/database/schema.js
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import { Address, Item, ItemBatch, ItemCategory, ItemDepartment, ItemStoreJoin, MasterList, MasterListItem, MasterListNameJoin, Name, NameStoreJoin, NumberSequence, NumberToReuse, Options, Requisition, RequisitionItem, Setting, Stocktake, StocktakeBatch, StocktakeItem, SyncOut, Period, PeriodSchedule, Transaction, TransactionBatch, TransactionCategory, TransactionItem, User, Unit, } from './DataTypes'; Address.schema = { name: 'Address', primaryKey: 'id', properties: { id: 'string', line1: { type: 'string', optional: true }, line2: { type: 'string', optional: true }, line3: { type: 'string', optional: true }, line4: { type: 'string', optional: true }, zipCode: { type: 'string', optional: true }, }, }; ItemCategory.schema = { name: 'ItemCategory', primaryKey: 'id', properties: { id: 'string', name: { type: 'string', default: 'placeholderName' }, parentCategory: { type: 'ItemCategory', optional: true }, }, }; ItemDepartment.schema = { name: 'ItemDepartment', primaryKey: 'id', properties: { id: 'string', name: { type: 'string', default: 'placeholderName' }, parentDepartment: { type: 'ItemDepartment', optional: true }, }, }; Setting.schema = { name: 'Setting', primaryKey: 'key', properties: { key: 'string', // Includes the user's UUID if it is per-user. value: 'string', user: { type: 'User', optional: true }, }, }; SyncOut.schema = { name: 'SyncOut', primaryKey: 'id', properties: { id: 'string', changeTime: 'int', // UNIX epoch format. changeType: 'string', // 'create', 'update', or 'delete'. recordType: 'string', // table name. recordId: 'string', }, }; TransactionCategory.schema = { name: 'TransactionCategory', primaryKey: 'id', properties: { id: 'string', name: { type: 'string', default: 'placeholderName' }, code: { type: 'string', default: 'placeholderCode' }, type: { type: 'string', default: 'placeholderType' }, parentCategory: { type: 'TransactionCategory', optional: true }, }, }; User.schema = { name: 'User', primaryKey: 'id', properties: { id: 'string', username: { type: 'string', default: 'placeholderUsername' }, lastLogin: { type: 'date', optional: true }, firstName: { type: 'string', optional: true }, lastName: { type: 'string', optional: true }, email: { type: 'string', optional: true }, passwordHash: { type: 'string', default: '4ada0b60df8fe299b8a412bbc8c97d0cb204b80e5693608ab2fb09ecde6d252d', }, salt: { type: 'string', optional: true }, }, }; export const schema = { schema: [ Address, Item, ItemBatch, ItemDepartment, ItemCategory, ItemStoreJoin, Transaction, TransactionItem, TransactionBatch, TransactionCategory, MasterList, MasterListItem, MasterListNameJoin, Name, NameStoreJoin, NumberSequence, NumberToReuse, Options, Requisition, RequisitionItem, Setting, SyncOut, Stocktake, StocktakeItem, Period, PeriodSchedule, StocktakeBatch, User, Unit, ], schemaVersion: 8, }; export default schema;
JavaScript
0.000001
@@ -3274,17 +3274,17 @@ ersion: -8 +9 ,%0A%7D;%0A%0Aex
e1857a89e37cf03cb193137405be9b1f9eb228b2
update fix token -- dateFormat
src/date/dateFormat.js
src/date/dateFormat.js
var kindOf = require('../lang/kindOf') var pad = require('../number/pad') var ordinal = require('../number/ordinal') var frmt = require('./dateMasks') var nameOfDay = require('./nameOfDay') var nameOfMonth = require('./nameOfMonth') var isLeapYear = require('./isLeapYear') var dayOfTheYear = require('./dayOfTheYear') var quarterOfTheYear = require('./quarterOfTheYear') var weekOfTheYear = require('./weekOfTheYear') var timezoneOffset = require('./timezoneOffset') var totalDaysThisMonth = require('./totalDaysThisMonth') var totalDaysThisYear = require('./totalDaysThisYear') function dateFormat (date, mask) { if (arguments.length === 1 && kindOf(date) === 'string' && !/\d/.test(date)) { mask = date date = undefined } date = date || new Date if (date instanceof Date) date = new Date(date) else date = new Date(Date.parse(date)) if (isNaN(date)) throw TypeError('Invalid date') // what we wish to match var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMSsTt])\1?|[oZWQNv]|O{1,2}|u{1,2}|x{1,3}|'[^']*'/g // what we don't wish to match -- need to optimize!! var antiToken = /[AaBbCcDEeFfGgIiJjKkLlnPpqRrUVwXYz0-9\?\.\,\!@#\$%\^\&\*\(\)\+\-]/g // what mask to use mask = String(frmt[mask] || antiPattern(mask, antiToken) || frmt.default) function makeIterator (fn) { return function (mask, token) { return fn(date, mask) } } return mask.replace(token, makeIterator(convertFlag)) } function convertFlag (date, token) { switch (token) { case 'd' : return date.getDate() case 'dd' : return pad(date.getDate(), 2) case 'ddd' : return nameOfDay(date, 3) case 'dddd' : return nameOfDay(date) case 'm' : return date.getMonth() + 1 case 'mm' : return pad(date.getMonth() + 1, 2) case 'mmm' : return nameOfMonth(date, 3) case 'mmmm' : return nameOfMonth(date) case 'yyyy' : return pad(date.getFullYear(), 4) case 'yy' : return pad(date.getFullYear() % 100, 2) case 'h' : return date.getHours() % 12 || 12 case 'hh' : return pad(date.getHours() % 12 || 12, 2) case 'H' : return date.getHours() case 'HH' : return pad(date.getHours(),2) case 'M' : return date.getMinutes() case 'MM' : return pad(date.getMinutes(), 2) case 'S' : return date.getSeconds() case 'SS' : return pad(date.getSeconds(),2) case 's' : return date.getMilliseconds() case 'ss' : return pad(date.getMilliseconds(), 3) case 't' : return date.getHours() < 12 ? ' a' : ' p' case 'tt' : return date.getHours() < 12 ? ' am' : ' pm' case 'T' : return date.getHours() < 12 ? ' A' : ' P' case 'TT' : return date.getHours() < 12 ? ' AM' : ' PM' case 'N' : return dayOfTheYear(date) case 'W' : return weekOfTheYear(date) case 'Q' : return quarterOfTheYear(date) case 'Z' : return timezoneOffset(date) case 'u' : return totalDaysThisMonth(date) case 'uu' : return totalDaysThisYear(date) case 'x' : return daysLeftThisWeek(date) case 'xx' : return daysLeftThisMonth(date) case 'xxx' : return daysLeftThisYear(date) case 'v' : return isLeapYear(date) case 'o' : return ordinal(date.getDate()) case 'O' : return nameOfDay(date, 1) case 'OO' : return nameOfDay(date, 2) default : return '' } } function antiPattern (mask, token) { if (!token.test(mask)) return mask return false } function daysLeftThisWeek (date) { return 6 - date.getDay() } function daysLeftThisMonth (date) { return totalDaysThisMonth(date) - date.getDate() } function daysLeftThisYear (date) { return totalDaysThisYear(date) - dayOfTheYear(date) } module.exports = dateFormat
JavaScript
0
@@ -3459,11 +3459,32 @@ turn + token.replace(/'/g, '' +) %0A %7D
d76b46648a349271767e166b81bf31ef1f24361f
fix makeDOMDriver import
test/browser/perf/index.js
test/browser/perf/index.js
import {run} from '@motorcycle/core' import {makeDomDriver, h} from '../../../src' import most from 'most' import {combineArray} from 'most/lib/combinator/combine' import map from 'fast.js/array/map' function InputCount(dom, initialValue) { const id = `.component-count` const value$ = dom.select(id) .events(`input`) .map(ev => ev.target.value) .startWith(initialValue) .multicast() return { dom: value$.map(value => h(`input${id}`, { key: 1000, props: { type: 'range', max: 250, min: 1, value, }, style: { width: '100%' } })), value$ } } function CycleJSLogo(id) { return { dom: most.just(h('div', { key: id, style: { alignItems: 'center', background: 'url(./cyclejs_logo.svg)', boxSizing: 'border-box', display: 'inline-flex', fontFamily: 'sans-serif', fontWeight: '700', fontSize: '8px', height: '32px', justifyContent: 'center', margin: '8px', width: '32px' } }, `${id}`)) } } function view(value, inputCountVTree, componentDOMs) { return h('div', [ h('h2', [`# of Components: ${value}`]), inputCountVTree, h('div', componentDOMs) ]) } function main(sources) { const initialValue = 100 const inputCount = InputCount(sources.dom, initialValue) const components$ = inputCount.value$ .map(value => map(Array(parseInt(value)), (v, i) => CycleJSLogo(i + 1).dom)) .map(array => combineArray((...components) => components, array)) .switch() return { dom: most.zip(view, inputCount.value$, inputCount.dom, components$) } } run(main, {dom: makeDomDriver(`#test-container`, [ require('snabbdom/modules/props'), require('snabbdom/modules/style') ])});
JavaScript
0
@@ -39,26 +39,26 @@ mport %7BmakeD -om +OM Driver, h%7D f @@ -1716,18 +1716,18 @@ m: makeD -om +OM Driver(%60
c56493649c6b412a97f05e0003fdda6a0fe9f415
document integration test library
lib/integration_test.js
lib/integration_test.js
module.exports = IntegrationTest = function() { this._client = null; this._server = null; this._port = 8000 + Math.floor(Math.random() * 1000); Test.call(this); } inherits(IntegrationTest, Test); IntegrationTest.prototype.start_server = function(base_path) { this._server = new Server(path.join(Gourdian.ROOT, "log", "test.log"), this._port, base_path); this._server.start(); if (this._server._io) { this._client = new TestClient(this._port); var self = this; this._server._io.configure(function() { self._server._io.set("heartbeat interval", .05); self._server._io.set("heartbeat timeout", .05); self._server._io.set("close timeout", 0); }); } } IntegrationTest.prototype.__defineGetter__("bound", function() { return this._server && this._server.bound_to_port }); IntegrationTest.prototype.get = function(path, callback) { this._client.get(path, callback, this); } IntegrationTest.prototype.ws_connect = function(callback) { this._client.ws_connect(callback, this); } IntegrationTest.prototype.stop_server = function() { this._server.stop(); if (this._client) this._client.end(); }
JavaScript
0.000001
@@ -1,8 +1,26 @@ +/* constructor */%0A module.e @@ -213,24 +213,710 @@ st, Test);%0A%0A +/* @returns %7BBoolean%7D is test server bound to port and accepting connections */%0AIntegrationTest.prototype.__defineGetter__(%22bound%22, function() %7B%0A return this._server && this._server.bound_to_port%0A%7D);%0A%0A/* issue a get request to the server%0A *%0A * @param %7BString%7D path%0A * @param %7BFunction%7D callback receives response%0A * @api public%0A */%0AIntegrationTest.prototype.get = function(path, callback) %7B%0A this._client.get(path, callback, this);%0A%7D%0A%0A/* connect sockit.io client to server%0A *%0A * @param %7BFunction%7D callback called after socket.io open event%0A * @api public%0A */%0AIntegrationTest.prototype.ws_connect = function(callback) %7B%0A this._client.ws_connect(callback, this);%0A%7D%0A%0A/* @api private */%0A IntegrationT @@ -1403,337 +1403,26 @@ %0A%7D%0A%0A -IntegrationTest.prototype.__defineGetter__(%22bound%22, function() %7B return this._server && this._server.bound_to_port %7D);%0A%0AIntegrationTest.prototype.get = function(path, callback) %7B%0A this._client.get(path, callback, this);%0A%7D%0A%0AIntegrationTest.prototype.ws_connect = function(callback) %7B%0A this._client.ws_connect(callback, this);%0A%7D%0A +/* @api private */ %0AInt
96835c0d6b0aefa0c3d337b3832bb1ae397a6223
active attribute test
test/ceb.attribute.spec.js
test/ceb.attribute.spec.js
import {element, attribute} from '../src/ceb.js'; /*jshint -W030 */ describe('ceb.attribute()', () => { let sandbox, builder; beforeEach(() => { if (sandbox) { sandbox.parentNode.removeChild(sandbox); } document.body.appendChild((sandbox = document.createElement('div'))); builder = element(); }); afterEach(() => { sandbox.innerHTML = ''; }); it('should define an attribute', () => { builder.builders(attribute('att1')).register('test-attribute'); let el = document.createElement('test-attribute'); el.setAttribute('att1', 'value'); expect(el.att1).to.be.eq('value'); expect(el.getAttribute('att1')).to.be.eq('value'); }); it('should define an unbound attribute', () => { builder.builders(attribute('att1').unbound()).register('test-unbound-attribute'); let el = document.createElement('test-unbound-attribute'); el.setAttribute('att1', 'fromAttr'); expect(el.att1).to.be.undefined; expect(el.getAttribute('att1')).to.be.eq('fromAttr'); el.att1 = 'fromProp'; expect(el.att1).to.be.eq('fromProp'); expect(el.getAttribute('att1')).to.be.eq('fromAttr'); }); it('should define an attribute with a default value', (done) => { builder.builders(attribute('att1').value('default')).register('test-attribute-default'); let el = document.createElement('test-attribute-default'); setTimeout(function () { expect(el.att1).to.be.eq('default'); expect(el.getAttribute('att1')).to.be.eq('default'); done(); }, 10); }); it('should define an attribute bound to the same property name', () => { builder.builders(attribute('att1')).register('test-bound-attribute'); let el = document.createElement('test-bound-attribute'); el.att1 = 'fromProp'; expect(el.att1).to.be.eq('fromProp'); expect(el.getAttribute('att1')).to.be.eq('fromProp'); el.setAttribute('att1', 'fromAtt'); expect(el.att1).to.be.eq('fromAtt'); expect(el.getAttribute('att1')).to.be.eq('fromAtt'); }); it('should define an attribute bound to another property name', () => { builder.builders(attribute('att1').property('prop1')).register('test-alt-bound-attribute'); let el = document.createElement('test-alt-bound-attribute'); el.prop1 = 'fromProp'; expect(el.prop1).to.be.eq('fromProp'); expect(el.getAttribute('att1')).to.be.eq('fromProp'); el.setAttribute('att1', 'fromAtt'); expect(el.prop1).to.be.eq('fromAtt'); expect(el.getAttribute('att1')).to.be.eq('fromAtt'); }); it('should define listener for attribute', (done) => { let listener = sinon.spy(); builder.builders(attribute('att1').listen(listener)).register('test-listener-attribute'); let el = document.createElement('test-listener-attribute'); el.att1 = 'fromProp'; setTimeout(() => { expect(listener).to.have.been.calledOnce; expect(listener).to.have.been.calledWith(el, null, 'fromProp'); el.setAttribute('att1', 'fromAttr'); setTimeout(() => { expect(listener).to.have.been.calledTwice; expect(listener).to.have.been.calledWith(el, 'fromProp', 'fromAttr'); done(); }, 10); }, 10); }); it('should define listener for boolean attribute', (done) => { let listener = sinon.spy(); builder.builders(attribute('att1').boolean().listen(listener)).register('test-listener-boolean-attribute'); let el = document.createElement('test-listener-boolean-attribute'); el.att1 = true; setTimeout(() => { //expect(listener, 'listener').to.have.been.calledOnce; //expect(listener, 'listener').to.have.been.calledWith(el, false, true); done(); /*el.removeAttribute('att1'); setTimeout(() => { expect(listener, 'listener').to.have.been.calledTwice; expect(listener, 'listener').to.have.been.calledWith(el, true, false); done(); }, 10);*/ }, 10); }); }); /*jshint +W030 */
JavaScript
0.000001
@@ -3991,30 +3991,8 @@ -done();%0A /* el.r @@ -4054,32 +4054,34 @@ +// expect(listener, @@ -4127,32 +4127,34 @@ +// expect(listener, @@ -4251,18 +4251,16 @@ %7D, 10); -*/ %0A
79cd1a3b275235a956cd125d7f681ec684b088fa
Remove verbose logging
lib/interfaceFactory.js
lib/interfaceFactory.js
'use strict'; var uuid = require('uuid'); var Interface = function (params) { // Schema defines fields and can be used for validation and form generation (optional) this.schema = params.schema; // The name of the interface, this must be unique this.name = params.name; // Additional properties that aren't exposed as form data, in the future this might be // used to check that objects fulfill the implementation this.members = params.members; this.interfaceId = uuid.v4(); console.log("[SCHEMA] Created interface [" + this.name + "] with id: " + this.interfaceId); } Interface.prototype.providedBy = function (obj) { // Does the specified object implement this interface if (obj && Array.isArray(obj._implements)) { // Object has a list of interfaces it implements for (var i=0, imax = obj._implements.length; i<imax; i++) { if (obj._implements[i].interfaceId === this.interfaceId) { return true; }; } } else if (obj && obj._implements && obj._implements.interfaceId === this.interfaceId) { // Object implements a single interface (probably a utility) return true; } // If we came this far, the object doesn't implement this interface return false; } var createInterface = function (params) { // Make sure we don't get an undefined params list params = params || {}; var extendsThese = params.extends, schema = params.schema, name = params.name; // TODO: If extends other interfaces then concatenate schemas from those, order sets precedence (first is overrides). // Then superimpose given schema on top of these. var newInterface = new Interface({ schema: schema, name: name }); return newInterface } module.exports.create = createInterface;
JavaScript
0.000019
@@ -515,16 +515,19 @@ %0A + // console
0a9df605bb02e4511b9f5bf69f0d36670636a00f
Fix typo in bin/esgenerate.js
bin/esgenerate.js
bin/esgenerate.js
#!/usr/bin/env node /* Copyright (C) 2012 Yusuke Suzuki <[email protected]> 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. 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 <COPYRIGHT HOLDER> 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. */ /*jslint sloppy:true node:true */ var fs = require('fs'), esprima = require('esprima'), escodegen = require('escodegen'), files = process.argv.splice(2); if (files.length === 0) { console.log('Usage:'); console.log(' esparse file.js'); process.exit(1); } files.forEach(function (filename) { var content = fs.readFileSync(filename, 'utf-8'); console.log(escodegen.generate(esprima.parse(content))); }); /* vim: set sw=4 ts=4 et tw=80 : */
JavaScript
0.001077
@@ -1588,20 +1588,23 @@ g(' es -pars +generat e file.j
d9113c8d7d84f67d9f3a6b695fcdafc811bec308
Fix url check for requirements
test/check-requirements.js
test/check-requirements.js
'use strict'; let loadMetadata = require('../browser/services/metadata'); let reqs = loadMetadata(require('../requirements.json'), process.platform); let request = require('request'); let data = new Object(); let fileNames = new Object(); let count = 0; function checkRequirements() { for (let attribute in reqs) { // sha256 is not set for macOS Java SE if(reqs[attribute].sha256sum !== '' && reqs[attribute].url && (reqs[attribute].useDownload == undefined || reqs[attribute].useDownload && reqs[attribute].useDownload == true)) { data[attribute] = reqs[attribute].url; count++; } else { if(reqs[attribute].sha256sum == undefined || reqs[attribute].sha256sum == '') { console.log(`skip ${attribute} no sha256sum configured` ); } if(reqs[attribute].url == undefined) { console.log(`skip ${attribute} no url configured` ); } } } //to check if the url looks like it points to what it is supposed to fileNames['cdk'] = 'cdk'; fileNames['minishift-rhel'] = 'rhel'; fileNames['oc'] = 'oc-origin-cli'; fileNames['cygwin'] = 'cygwin'; fileNames['devstudio'] = 'devstudio'; fileNames['jbosseap'] = 'jboss-eap'; fileNames['jdk'] = 'openjdk'; fileNames['virtualbox'] = 'virtualbox'; fileNames['7zip'] = '7-Zip'; fileNames['7zip-extra'] = '7-Zip'; fileNames['kompose'] = 'kompose'; fileNames['fuseplatformkaraf'] = 'karaf'; fileNames['devstuidobpm'] = 'devstudio-integration-stack'; fileNames['devstudiocentral'] = 'central'; console.log('-------------------------------'); console.log('Checking download URLs'); for (var key in data) { checkFileName(key); checkUrl(key); } } function checkFileName(key) { if (!data[key].includes(fileNames[key])) { throw new Error(key + ' - the url does not contain ' + fileNames[key] + ': ' + data[key]); } } function checkUrl(key) { let req = request.get(data[key]) .on('response', function(response) { let size = response.headers['content-length']; if (response.statusCode !== 200) { req.abort(); throw new Error('Request for ' + key + ' url returned code ' + response.statusCode); } console.log(key + ' - url: ' + reqs[key].url); console.log(key + ' - size: ' + size + 'B'); if (reqs[key].size!=size) { req.abort(); throw new Error(`${key} size ${size} does not match with size ${reqs[key].size} declared in requirements.json`); } else { console.log(key + ' - size: ' + reqs[key].size + 'B in requirements.json'); req.abort(); } console.log(); }) .on('end', function() { if (--count === 0) { console.log('Checking download URLs complete'); console.log('-------------------------------'); } }) .on('error', function(err) { console.log(`Download failed for ${key}`); req.abort(); throw err; }); } checkRequirements();
JavaScript
0.000001
@@ -1276,33 +1276,33 @@ es%5B'7zip'%5D = '7- -Z +z ip';%0A fileNames @@ -1325,9 +1325,9 @@ '7- -Z +z ip';
c666554156a3d01fb8a4ba18f1a83ef4def8f50c
implement tests for shaperFunction
lib/json-shaper.spec.js
lib/json-shaper.spec.js
import { isObject, forEach, } from './json-shaper' import sinon from 'sinon'; describe('isObject helper', () => { it('should recognize objects', () => { expect(isObject({})).to.be.true expect(isObject({ any: 'thing' })).to.be.true expect(isObject(['a', 'b'])).to.be.true }) it('should recognize non-objects', () => { expect(isObject()).to.be.false expect(isObject(null)).to.be.false expect(isObject(undefined)).to.be.false expect(isObject('hello world')).to.be.false expect(isObject(7)).to.be.false }) }) describe('forEach helper', () => { it('should iterate over object keys and call a function', () => { const iteratee = sinon.spy() const obj1 = { a: 123, b: 456, z: 789 } const obj2 = [ 'just', 'some', 'array' ] forEach(obj1, iteratee) forEach(obj2, iteratee) expect(iteratee.withArgs(123, 'a').calledOnce).to.be.true expect(iteratee.withArgs(456, 'b').calledOnce).to.be.true expect(iteratee.withArgs(789, 'z').calledOnce).to.be.true expect(iteratee.withArgs('just', '0').calledOnce).to.be.true expect(iteratee.withArgs('some', '1').calledOnce).to.be.true expect(iteratee.withArgs('array', '2').calledOnce).to.be.true }) it('should skip on non-objects', () => { const iteratee = sinon.spy() const obj1 = 'test' const obj2 = 123 const obj3 = null const obj4 = undefined forEach(obj1, iteratee) forEach(obj2, iteratee) forEach(obj3, iteratee) forEach(obj4, iteratee) expect(iteratee.callCount).to.equal(0) }) })
JavaScript
0
@@ -3,16 +3,34 @@ mport %7B%0A + shaperFunction,%0A isObje @@ -1625,20 +1625,1237 @@ equal(0)%0A%0A %7D)%0A%0A%7D)%0A%0A +%0A%0Adescribe('shaperFunction', () =%3E %7B%0A%0A const schema = %7B%0A id: 'id',%0A firstName: 'first_name',%0A lastName: 'last_name',%0A workplace: %7B%0A id: 'office_id',%0A name: 'office_company_name',%0A address: %7B%0A street: 'company_street',%0A postCode: 'company_postcode',%0A country: 'company_cty',%0A %7D%0A %7D,%0A isActive: 'user_is_active'%0A %7D%0A%0A const fnCode = shaperFunction(schema)%0A%0A it('should generate function code based on a schema', () =%3E %7B%0A%0A const schema2 = %7B%7D%0A const schema3 = %7B someKey: 'some_key_in_source_object'%7D%0A%0A const fnCode2 = shaperFunction(schema2)%0A const fnCode3 = shaperFunction(schema3)%0A%0A expect(fnCode).to.equal(%0A '%7B %22id%22: data%5B %22id%22 %5D, %22firstName%22: data%5B %22first_name%22 %5D, %22lastName%22: data%5B %22last_name%22 %5D, ' +%0A '%22workplace%22: %7B %22id%22: data%5B %22office_id%22 %5D, %22name%22: data%5B %22office_company_name%22 %5D, %22address%22: ' +%0A '%7B %22street%22: data%5B %22company_street%22 %5D, %22postCode%22: data%5B %22company_postcode%22 %5D, %22country%22: ' +%0A 'data%5B %22company_cty%22 %5D, %7D, %7D, %22isActive%22: data%5B %22user_is_active%22 %5D, %7D'%0A )%0A%0A expect(fnCode2).to.equal('%7B %7D')%0A%0A expect(fnCode3).to.equal('%7B %22someKey%22: data%5B %22some_key_in_source_object%22 %5D, %7D')%0A %7D)%0A%0A%0A%7D)%0A%0A
5710e90529613d8e1bed12e99f511d29f39aa1ed
Update page-manipulation.js
src/page-manipulation.js
src/page-manipulation.js
(function($){ //Storages var pinnedActivities = [] //Utils functions function setActivities(){ var activities = activityList.find(".notification li"); activities.removeClass("chidden"); if(!activityList.hasClass("fullList")){ for(var i = 7; i<activities.length; i++){ $(activities.get(i)).addClass("chidden"); } $("#activity-list-full-btn").addClass("chidden"); $("#activity-list-expand-btn a").text("Tout afficher"); } else { $("#activity-list-full-btn").removeClass("chidden"); $("#activity-list-expand-btn a").text("Cacher"); } } function savePinnedActivities(){ localStorage.setItem('pinned-activities', JSON.stringify(pinnedActivities)); } function loadPinnedActivities(){ pinnedActivities = JSON.parse(localStorage.getItem('pinned-activities')) } function pinActivity(pinnedObject){ var $activity = $("#activity-"+pinnedObject.hash); $activity.addClass("pinned"); $activity.prependTo($activity.parent()); } String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; function getActivityHash(activity){ var title = activity.find(".resume strong a").text(); var author = activity.find(".auteur").text(); var date = activity.find(".date").text(); return (title+author+date).hashCode().toString().replace(/-/g,"k"); } //Events and iterators functions function onEachActivity(){ var $this = $(this); var hash = getActivityHash($this); $this.attr("id","activity-"+hash); $this.attr("data-hash",hash); $this.prepend('<a href="#" class="activity-pin"><i class="fa fa-thumb-tack"></i></a>') } function initOnEachActivityBroadcast(el){ var $this = $(broadcastsActivity.get(el)); var $title = $this.find(".titre"); var title = $title.text(); $title.text("Annonce"); $this.find(".vignette_deco2").prepend("<div class=\"resume\"><strong><a hre=\"#\">"+title+"</a></strong></div>"); $this.find(".vignette_deco2 .auteur").text("Annonce d'administration") } function onClickActivity(e){ if($(e.target).is("a") || $(e.target).is("a *")) return; var link = $(this).find("strong a").attr('href'); if(link) window.location = link; } function onClickPinActivity(e){ e.preventDefault(); var activity = $(this).parent(); var pinned = pinnedActivities.find(function(el){return el.hash == activity.attr("data-hash")}) if(pinned){ activity.removeClass("pinned"); if(pinned.before){ activity.insertBefore($("#activity-"+pinned.before)); } else { activity.appendTo(activity.parent()); } pinnedActivities.splice(pinnedActivities.indexOf(pinned),1) } else { pinned = { hash: $activity.attr("data-hash"), before: $activity.next().attr("data-hash") } pinnedActivities.unshift(); pinActivity(pinned); } console.log(pinnedActivities); } function onClickExpandActivity(e){ e.preventDefault(); activityList.toggleClass("fullList"); setActivities(); } //INIT $(".layout__slot:nth-child(1)").attr("id","calendar-list"); $(".layout__slot:nth-child(2)").attr("id","app-list"); $(".layout__slot:nth-child(3)").attr("id","activity-list"); $(".layout__slot:nth-child(4)").attr("id","tweets-list"); $(".layout__slot:nth-child(5)").attr("id","campus-post-list"); $(".layout__slot:nth-child(6)").attr("id","school-post-list"); var appList = $("#app-list") appList.prependTo(appList.parent()) appList.removeClass(); var tweetsList = $("#tweets-list") tweetsList.appendTo(tweetsList.parent()) tweetsList.removeClass(); var activityList = $("#activity-list"); var broadcastsActivity = activityList.find(".notification li .vignette_deco .icon-chat").parent().parent(); broadcastsActivity.each(initOnEachActivityBroadcast); var activities = activityList.find(".notification li"); activities.on("click",onClickActivity) activities.each(onEachActivity) activities.find(".activity-pin").on("click",onClickPinActivity) var oldActivityBox = activityList.find(".card__lien"); oldActivityBox.attr("id","activity-list-full-btn"); activityList.find(".carte-activite").append("<div class=\"card__lien\" id=\"activity-list-expand-btn\"><a href=\"#\">Tout afficher</a></div>"); $("#activity-list-expand-btn").on("click",onClickExpandActivity) setActivities(); })(jQuery);
JavaScript
0.000001
@@ -646,16 +646,23 @@ ()%7B%0A +window. localSto @@ -806,16 +806,23 @@ N.parse( +window. localSto @@ -3038,17 +3038,16 @@ hash: -$ activity @@ -3082,17 +3082,16 @@ before: -$ activity @@ -3151,16 +3151,19 @@ ies. -unshift( +push(pinned );%0A @@ -3202,21 +3202,13 @@ -console.log(p +saveP inne @@ -3218,18 +3218,18 @@ tivities +( ) -; %0A %7D%0A %0A @@ -4690,17 +4690,16 @@ tivity)%0A -%0A setAct @@ -4712,16 +4712,86 @@ s();%0A %0A + pinnedActivities.forEach(function(el)%7B%0A pinActivity(el);%0A %7D)%0A %0A %7D)(jQuer
56eabb129450bfb6d7a118cc66f5f3b8eee099a3
fix kill tests on windows
test/commands/kill.spec.js
test/commands/kill.spec.js
'use strict' var path = require('path') var fs = require('fs') var childProcess = require('child_process') var should = require('should') var utils = require('../utils') var keepAliveProcess = require('../../lib/keepAliveProcess') var kill = require('../../lib/commands/kill').handler function tryCreate (dir) { try { fs.mkdirSync(dir, '0755') } catch (ex) { } } describe('kill command', function () { var pathToTempProject var pathToSocketDir var pathToWorkerSocketDir var port = 9398 before(function (done) { // disabling timeout because npm install could take a // couple of seconds this.timeout(0) utils.cleanTempDir(['kill-project']) utils.createTempDir(['kill-project'], function (dir, absoluteDir) { pathToTempProject = absoluteDir fs.writeFileSync( path.join(absoluteDir, './package.json'), JSON.stringify({ name: 'kill-project', dependencies: { jsreport: '*' }, jsreport: { entryPoint: 'server.js' } }, null, 2) ) fs.writeFileSync( path.join(absoluteDir, 'dev.config.json'), JSON.stringify({ httpPort: port }, null, 2) ) fs.writeFileSync( path.join(absoluteDir, './server.js'), [ 'var jsreport = require("jsreport")()', 'if (require.main !== module) {', 'module.exports = jsreport', '} else {', 'jsreport.init().catch(function (e) {', 'console.error("error on jsreport init")', 'console.error(e.stack)', 'process.exit(1)', '})', '}' ].join('\n') ) pathToSocketDir = path.join(absoluteDir, 'sock-dir') pathToWorkerSocketDir = path.join(absoluteDir, 'workerSock-dir') tryCreate(pathToSocketDir) tryCreate(pathToWorkerSocketDir) console.log('installing dependencies for test suite...') childProcess.exec('npm install', { cwd: pathToTempProject }, function (error, stdout, stderr) { if (error) { console.log('error while installing dependencies for test suite...') return done(error) } console.log('installation of dependencies for test suite completed...') done() }) }) }) describe('when there is no daemon instance running', function () { it('should fail searching daemon by current working directory', function () { return ( kill({ context: { cwd: pathToTempProject, workerSockPath: pathToWorkerSocketDir } }) .then(function () { throw new Error('kill should have failed') }, function (err) { should(err).be.Error() }) ) }) it('should fail searching daemon by identifier', function () { return ( kill({ context: { cwd: pathToTempProject, workerSockPath: pathToWorkerSocketDir }, _: [null, 'xXsfrt'] }) .then(function () { throw new Error('kill should have failed') }, function (err) { should(err).be.Error() }) ) }) }) describe('when there is daemon instance running', function () { var childInfo var child beforeEach(function () { this.timeout(0) console.log('spawning a daemon jsreport instance for the test suite..') return keepAliveProcess({ mainSockPath: pathToSocketDir, workerSockPath: pathToWorkerSocketDir, cwd: pathToTempProject }).then(function (info) { console.log('daemonized jsreport instance is ready..') childInfo = info child = info.proc }) }) it('should kill by current working directory', function () { return ( kill({ context: { cwd: pathToTempProject, workerSockPath: pathToWorkerSocketDir } }) .then(function (result) { should(result).not.be.undefined() should(result.pid).be.eql(child.pid) }) ) }) it('should kill by process id', function () { return ( kill({ context: { cwd: pathToTempProject, workerSockPath: pathToWorkerSocketDir }, _: [null, child.pid] }) .then(function (result) { should(result).not.be.undefined() should(result.pid).be.eql(child.pid) }) ) }) it('should kill by uid', function () { return ( kill({ context: { cwd: pathToTempProject, workerSockPath: pathToWorkerSocketDir }, _: [null, childInfo.uid] }) .then(function (result) { should(result).not.be.undefined() should(result.uid).be.eql(childInfo.uid) }) ) }) afterEach(function () { if (child) { child.kill() } }) }) after(function () { // disabling timeout because removing files could take a // couple of seconds this.timeout(0) utils.cleanTempDir(['kill-project']) }) })
JavaScript
0.000001
@@ -3059,14 +3059,18 @@ l, ' -xXsfrt +zzzzzzzzzz '%5D%0A @@ -4132,32 +4132,36 @@ id).be.eql(child +Info .pid)%0A %7D) @@ -4398,24 +4398,28 @@ %5Bnull, child +Info .pid%5D%0A @@ -4542,16 +4542,20 @@ ql(child +Info .pid)%0A
2e75af9429c9e81cd10ddd659fb695c341903d10
update transition detection
src/dialog-renderer.js
src/dialog-renderer.js
import {DOM} from 'aurelia-pal'; import {transient} from 'aurelia-dependency-injection'; let containerTagName = 'ai-dialog-container'; let overlayTagName = 'ai-dialog-overlay'; let transitionEvent = (function() { let transition = null; return function() { if (transition) return transition; let t; let el = DOM.createElement('fakeelement'); let transitions = { 'transition': 'transitionend', 'OTransition': 'oTransitionEnd', 'MozTransition': 'transitionend', 'WebkitTransition': 'webkitTransitionEnd' }; for (t in transitions) { if (el.style[t] !== undefined) { transition = transitions[t]; return transition; } } }; }()); let hasTransition = (function () { const defaultDuration = '0s'; let transitionDuration; let t; let el = DOM.createElement('fakeelement'); let transitions = { 'transition': 'transitionDuration', 'OTransition': 'oTransitionDuration', 'MozTransition': 'transitionDuration', 'WebkitTransition': 'webkitTransitionDuration' }; for (t in transitions) { if (el.style[t] !== undefined) { transitionDuration = transitions[t]; break; } } return function (element) { return !!transitionDuration && DOM.getComputedStyle(element)[transitionDuration] !== defaultDuration; } }()); @transient() export class DialogRenderer { _escapeKeyEventHandler = (e) => { if (e.keyCode === 27) { let top = this._dialogControllers[this._dialogControllers.length - 1]; if (top && top.settings.lock !== true) { top.cancel(); } } } getDialogContainer() { return DOM.createElement('div'); } showDialog(dialogController: DialogController) { let settings = dialogController.settings; let body = DOM.querySelectorAll('body')[0]; let wrapper = document.createElement('div'); this.modalOverlay = DOM.createElement(overlayTagName); this.modalContainer = DOM.createElement(containerTagName); this.anchor = dialogController.slot.anchor; wrapper.appendChild(this.anchor); this.modalContainer.appendChild(wrapper); this.stopPropagation = (e) => { e._aureliaDialogHostClicked = true; }; this.closeModalClick = (e) => { if (!settings.lock && !e._aureliaDialogHostClicked) { dialogController.cancel(); } else { return false; } }; dialogController.centerDialog = () => { if (settings.centerHorizontalOnly) return; centerDialog(this.modalContainer); }; this.modalOverlay.style.zIndex = settings.startingZIndex; this.modalContainer.style.zIndex = settings.startingZIndex; let lastContainer = Array.from(body.querySelectorAll(containerTagName)).pop(); if (lastContainer) { lastContainer.parentNode.insertBefore(this.modalContainer, lastContainer.nextSibling); lastContainer.parentNode.insertBefore(this.modalOverlay, lastContainer.nextSibling); } else { body.insertBefore(this.modalContainer, body.firstChild); body.insertBefore(this.modalOverlay, body.firstChild); } if (!this._dialogControllers.length) { DOM.addEventListener('keyup', this._escapeKeyEventHandler); } this._dialogControllers.push(dialogController); dialogController.slot.attached(); if (typeof settings.position === 'function') { settings.position(this.modalContainer, this.modalOverlay); } else { dialogController.centerDialog(); } this.modalContainer.addEventListener('click', this.closeModalClick); this.anchor.addEventListener('click', this.stopPropagation); return new Promise((resolve) => { let renderer = this; if (settings.ignoreTransitions || !hasTransition(this.modalContainer)) { resolve(); } else { this.modalContainer.addEventListener(transitionEvent(), onTransitionEnd); } this.modalOverlay.classList.add('active'); this.modalContainer.classList.add('active'); body.classList.add('ai-dialog-open'); function onTransitionEnd(e) { if (e.target !== renderer.modalContainer) { return; } renderer.modalContainer.removeEventListener(transitionEvent(), onTransitionEnd); resolve(); } }); } hideDialog(dialogController: DialogController) { let settings = dialogController.settings; let body = DOM.querySelectorAll('body')[0]; this.modalContainer.removeEventListener('click', this.closeModalClick); this.anchor.removeEventListener('click', this.stopPropagation); let i = this._dialogControllers.indexOf(dialogController); if (i !== -1) { this._dialogControllers.splice(i, 1); } if (!this._dialogControllers.length) { DOM.removeEventListener('keyup', this._escapeKeyEventHandler); } return new Promise((resolve) => { let renderer = this; if (settings.ignoreTransitions || !hasTransition(this.modalContainer)) { resolve(); } else { this.modalContainer.addEventListener(transitionEvent(), onTransitionEnd); } this.modalOverlay.classList.remove('active'); this.modalContainer.classList.remove('active'); function onTransitionEnd() { renderer.modalContainer.removeEventListener(transitionEvent(), onTransitionEnd); resolve(); } }) .then(() => { body.removeChild(this.modalOverlay); body.removeChild(this.modalContainer); dialogController.slot.detached(); if (!this._dialogControllers.length) { body.classList.remove('ai-dialog-open'); } return Promise.resolve(); }); } } DialogRenderer.prototype._dialogControllers = []; // will be shared by all instances function centerDialog(modalContainer) { const child = modalContainer.children[0]; const vh = Math.max(DOM.querySelectorAll('html')[0].clientHeight, window.innerHeight || 0); child.style.marginTop = Math.max((vh - child.offsetHeight) / 2, 30) + 'px'; child.style.marginBottom = Math.max((vh - child.offsetHeight) / 2, 30) + 'px'; }
JavaScript
0
@@ -734,17 +734,16 @@ function - () %7B%0A c @@ -751,38 +751,26 @@ nst -defaultDuration = '0s';%0A let +unprefixedName = ' tran @@ -787,23 +787,17 @@ tion +' ;%0A -let t;%0A le +cons t el @@ -843,82 +843,52 @@ let -transitions = %7B%0A 'transition': 'transitionDuration',%0A 'OTransition': +prefixedNames = %5B'webkitTransitionDuration', 'oT @@ -909,175 +909,133 @@ ion' -,%0A 'MozTransition': 'transitionDuration',%0A 'WebkitTransition': 'webkitTransitionDuration'%0A %7D;%0A for (t in transitions) %7B%0A if (el.style%5Bt%5D !== undefined) +%5D;%0A let transitionDurationName;%0A if (unprefixedName in el.style) %7B%0A transitionDurationName = unprefixedName;%0A %7D else %7B%0A - @@ -1056,51 +1056,75 @@ tion - = transitions%5Bt%5D;%0A break;%0A %7D +Name = prefixedNames.find(prefixed =%3E (prefixed in el.style)); %0A %7D%0A -%0A re @@ -1180,20 +1180,26 @@ Duration +Name && +!! DOM.getC @@ -1242,29 +1242,79 @@ tion -%5D !== defaultD +Name%5D%0A .split(',')%0A .find(duration =%3E !!parseFloat(d uration +)) ;%0A
0801d838561b2bd29cef2d421a424596cbf4cb1d
add github icon in GlobalFooter
src/pages/login/index.js
src/pages/login/index.js
import React, { PureComponent, Fragment } from 'react' import PropTypes from 'prop-types' import { connect } from 'dva' import { Button, Row, Form, Input } from 'antd' import router from 'umi/router' import { GlobalFooter } from 'ant-design-pro' import { Trans, withI18n } from '@lingui/react' import config from 'utils/config' import styles from './index.less' const FormItem = Form.Item @withI18n() @connect(({ loading }) => ({ loading })) @Form.create() class Login extends PureComponent { handleOk = () => { const { dispatch, form } = this.props const { validateFieldsAndScroll } = form validateFieldsAndScroll((errors, values) => { if (errors) { return } dispatch({ type: 'login/login', payload: values }) }) } render() { const { loading, form, i18n } = this.props const { getFieldDecorator } = form const footerLinks = [ { key: 'English', title: <span onClick={() => router.push('/en/login')}>English</span>, }, { key: 'Chinese', title: <span onClick={() => router.push('/zh/login')}>中文</span>, }, ] return ( <Fragment> <div className={styles.form}> <div className={styles.logo}> <img alt="logo" src={config.logoPath} /> <span>{config.siteName}</span> </div> <form> <FormItem hasFeedback> {getFieldDecorator('username', { rules: [ { required: true, }, ], })( <Input onPressEnter={this.handleOk} placeholder={i18n.t`Username`} /> )} </FormItem> <FormItem hasFeedback> {getFieldDecorator('password', { rules: [ { required: true, }, ], })( <Input type="password" onPressEnter={this.handleOk} placeholder={i18n.t`Password`} /> )} </FormItem> <Row> <Button type="primary" onClick={this.handleOk} loading={loading.effects.login} > <Trans>Sign in</Trans> </Button> <p> <span> <Trans>Username</Trans> :guest </span> <span> <Trans>Password</Trans> :guest </span> </p> </Row> </form> </div> <div className={styles.footer}> <GlobalFooter links={footerLinks} copyright={config.copyright} /> </div> </Fragment> ) } } Login.propTypes = { form: PropTypes.object, dispatch: PropTypes.func, loading: PropTypes.object, } export default Login
JavaScript
0
@@ -140,16 +140,22 @@ w, Form, + Icon, Input %7D @@ -890,32 +890,193 @@ nks = %5B%0A %7B%0A + key: 'github',%0A title: %3CIcon type=%22github%22 /%3E,%0A href: 'https://github.com/zuiidea/antd-admin',%0A blankTarget: true,%0A %7D,%0A %7B%0A key: 'En
22ddd7a37ef86b2c91c52516a56c160ca416f31c
Implement CompoundPath#curves.
src/path/CompoundPath.js
src/path/CompoundPath.js
/* * Paper.js * * This file is part of Paper.js, a JavaScript Vector Graphics Library, * based on Scriptographer.org and designed to be largely API compatible. * http://paperjs.org/ * http://scriptographer.org/ * * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey * http://lehni.org/ & http://jonathanpuckey.com/ * * Distributed under the MIT license. See LICENSE file for details. * * All rights reserved. */ /** * @name CompoundPath * * @class A compound path contains two or more paths, holes are drawn * where the paths overlap. All the paths in a compound path take on the * style of the backmost path and can be accessed through its * {@link Item#children} list. * * @extends PathItem */ var CompoundPath = this.CompoundPath = PathItem.extend(/** @lends CompoundPath# */{ _type: 'compoundpath', /** * Creates a new compound path item and places it in the active layer. * * @param {Path[]} [paths] the paths to place within the compound path. * * @example {@paperscript} * // Create a circle shaped path with a hole in it: * var circle = new Path.Circle(new Point(50, 50), 30); * var innerCircle = new Path.Circle(new Point(50, 50), 10); * var compoundPath = new CompoundPath([circle, innerCircle]); * compoundPath.fillColor = 'red'; * * // Move the inner circle 5pt to the right: * compoundPath.children[1].position.x += 5; */ initialize: function(paths) { this.base(); // Allow CompoundPath to have children and named children. this._children = []; this._namedChildren = {}; // Do not reassign to paths, since arguments would get modified, which // we potentially use as array, depending on what is passed. this.addChildren(Array.isArray(paths) ? paths : arguments); }, insertChild: function(index, item, _cloning) { // Only allow the insertion of paths if (item._type !== 'path') return null; var res = this.base(index, item); // All children except for the bottom one (first one in list) are set // to anti-clockwise orientation, so that they appear as holes, but // only if their orientation was not already specified before // (= _clockwise is defined). if (!_cloning && res && item._clockwise === undefined) item.setClockwise(item._index == 0); return res; }, /** * If this is a compound path with only one path inside, * the path is moved outside and the compound path is erased. * Otherwise, the compound path is returned unmodified. * * @return {CompoundPath|Path} the flattened compound path */ reduce: function() { if (this._children.length == 1) { var child = this._children[0]; child.insertAbove(this); this.remove(); return child; } return this; }, smooth: function() { for (var i = 0, l = this._children.length; i < l; i++) this._children[i].smooth(); }, isEmpty: function() { return this._children.length == 0; }, contains: function(point) { point = Point.read(arguments); var count = 0; for (var i = 0, l = this._children.length; i < l; i++) { if (this._children[i].contains(point)) count++; } return (count & 1) == 1; }, _hitTest: function(point, options) { return this.base(point, Base.merge(options, { fill: false })) || options.fill && this._style._fillColor && this.contains(point) ? new HitResult('fill', this) : null; }, draw: function(ctx, param) { var children = this._children, style = this._style; // Return early if the compound path doesn't have any children: if (children.length == 0) return; ctx.beginPath(); param.compound = true; for (var i = 0, l = children.length; i < l; i++) Item.draw(children[i], ctx, param); param.compound = false; if (this._clipMask) { ctx.clip(); } else { this._setStyles(ctx); if (style._fillColor) ctx.fill(); if (style._strokeColor) ctx.stroke(); } } }, new function() { // Injection scope for PostScript-like drawing functions /** * Helper method that returns the current path and checks if a moveTo() * command is required first. */ function getCurrentPath(that) { if (!that._children.length) throw new Error('Use a moveTo() command first'); return that._children[that._children.length - 1]; } var fields = { // Note: Documentation for these methods is found in PathItem, as they // are considered abstract methods of PathItem and need to be defined in // all implementing classes. moveTo: function(point) { var path = new Path(); this.addChild(path); path.moveTo.apply(path, arguments); }, moveBy: function(point) { this.moveTo(getCurrentPath(this).getLastSegment()._point.add( Point.read(arguments))); }, closePath: function() { getCurrentPath(this).setClosed(true); } }; // Redirect all other drawing commands to the current path Base.each(['lineTo', 'cubicCurveTo', 'quadraticCurveTo', 'curveTo', 'arcTo', 'lineBy', 'curveBy', 'arcBy'], function(key) { fields[key] = function() { var path = getCurrentPath(this); path[key].apply(path, arguments); }; }); return fields; });
JavaScript
0
@@ -2810,16 +2810,337 @@ );%0A%09%7D,%0A%0A +%09/**%0A%09 * All the curves contained within the compound-path, from all its child%0A%09 * %7B@link Path%7D items.%0A%09 *%0A%09 * @type Curve%5B%5D%0A%09 * @bean%0A%09 */%0A%09getCurves: function() %7B%0A%09%09var curves = %5B%5D;%0A%09%09for (var i = 0, l = this._children.length; i %3C l; i++)%0A%09%09%09curves = curves.concat(this._children%5Bi%5D.getCurves());%0A%09%09return curves;%0A%09%7D,%0A%0A %09isEmpty
b833b9ac918f780df8512406d6c2d49d522b33f7
Remove erroneous console.log
src/patterns/mediator.js
src/patterns/mediator.js
function mediator() { mediator.base.call(this); this._observers = $.hash(); } mediator.prototype = { subscribe: function(name, method, scope, id) { var observers = this._observers; if(observers.containsKey(name)) observers.find(name).add(method, scope, id); else observers.add(name, $.observer().add(method, scope, id)); return this; }, unsubscribe: function(name, id) { var observers = this._observers; if(observers.containsKey(name)) observers.find(name).remove(id); return this; }, notify: function() { var args = $.list.parseArguments(arguments), firstArg = args.find(0), isFirstArgData = !this._observers.containsKey(firstArg), isFilteredCall = !isFirstArgData || (args.count() > 1), data = isFirstArgData ? firstArg : null, nameList = isFirstArgData ? args.remove(firstArg) : args; console.log() return (isFilteredCall) ? this._notify(data, nameList) : this._notifyAll(data); }, clear: function(){ this._observers .each(function(o){ o.value.clear(); }) .clear(); return this; }, isEmpty: function(){ return this._observers.isEmpty(); }, _notifyAll: function(data){ $.list(this._observers.values()).each(function(observer){ observer.notify(data); }); return this; }, _notify: function(data, list) { var o = this._observers; list.each(function(name){ try { o.find(name).notify(data); } catch(e){ throw new Error($.str.format("{0}: {1}", e.message, name)); } }); return this; } } $.Class.extend(mediator, $.Class); $.mediator = function() { return new mediator(); } $.mediator.Class = mediator;
JavaScript
0.000009
@@ -937,30 +937,8 @@ gs;%0A - console.log()%0A
fc3e38b9de6b23553b7a17d8852faaababb49888
Add page scrolling to sortable pattern.
src/patterns/sortable.js
src/patterns/sortable.js
define([ 'jquery', "../registry" ], function($, patterns) { var _ = { name: "sortable", trigger: "ul.pat-sortable", init: function($el) { if ($el.length > 1) return $el.each(function() { _.init($(this)); }); // use only direct descendants to support nested lists var $lis = $el.children().filter('li'); // add handles and make them draggable for HTML5 and IE8/9 // it has to be an "a" tag (or img) to make it draggable in IE8/9 var $handles = $('<a href="#" class="handle"></a>').appendTo($lis); if('draggable' in document.createElement('span')) $handles.attr('draggable', true); else $handles.bind('selectstart', function(event) { event.preventDefault(); }); $handles.bind('dragstart', function(event) { // Firefox seems to need this set to any value event.originalEvent.dataTransfer.setData('Text', ''); event.originalEvent.dataTransfer.effectAllowed = ['move']; if ('setDragImage' in event.originalEvent.dataTransfer) event.originalEvent.dataTransfer.setDragImage( $(this).parent()[0], 0, 0); $(this).parent().addClass('dragged'); // list elements are only drop targets when one element of the // list is being dragged. avoids dragging between lists. $lis.bind('dragover.pat-sortable', function(event) { var $this = $(this), midlineY = $this.offset().top - $(document).scrollTop() + $this.height()/2; // bail if dropping on self if ($(this).hasClass('dragged')) return; $this.removeClass('drop-target-above drop-target-below'); if (event.originalEvent.clientY > midlineY) $this.addClass('drop-target-below'); else $this.addClass('drop-target-above'); event.preventDefault(); }); $lis.bind('dragleave.pat-sortable', function(event) { $lis.removeClass('drop-target-above drop-target-below'); }); $lis.bind('drop.pat-sortable', function(event) { if ($(this).hasClass('drop-target-below')) $(this).after($('.dragged')); else $(this).before($('.dragged')); $(this).removeClass('drop-target-above drop-target-below'); event.preventDefault(); }); }); $handles.bind('dragend', function(event) { $('.dragged').removeClass('dragged'); $lis.unbind('.pat-sortable'); }); return $el; } }; patterns.register(_); return _; }); // jshint indent: 4, browser: true, jquery: true, quotmark: double // vim: sw=4 expandtab
JavaScript
0
@@ -865,32 +865,868 @@ %7D);%0A%0A + // invisible scroll activation areas%0A var scrollup = $('%3Cdiv id=%22pat-scroll-up%22%3E&nbsp;%3C/div%3E'),%0A scrolldn = $('%3Cdiv id=%22pat-scroll-dn%22%3E&nbsp;%3C/div%3E'),%0A scroll = $().add(scrollup).add(scrolldn);%0A%0A scrollup.css(%7B top:0 %7D);%0A scrolldn.css(%7B bottom: 0 %7D);%0A scroll.css(%7B%0A position: 'fixed', zIndex: 999999,%0A height: 32, left: 0, right: 0%0A %7D);%0A%0A scroll.bind('dragover', function(event) %7B%0A event.preventDefault();%0A if ($('html,body').is(':animated')) return;%0A%0A var newpos = $(window).scrollTop() +%0A ($(this).attr('id')=='pat-scroll-up' ? -32 : 32);%0A%0A $('html,body').animate(%7BscrollTop: newpos%7D, 50, 'linear');%0A %7D);%0A%0A $han @@ -1758,32 +1758,32 @@ nction(event) %7B%0A - @@ -2561,16 +2561,18 @@ ollTop() + + %0A @@ -2591,18 +2591,16 @@ - + $this.h @@ -3668,24 +3668,103 @@ %7D); +%0A%0A scroll.appendTo('body');//.append(scrollup).append(scrolldn); %0A @@ -3874,24 +3874,24 @@ 'dragged');%0A - @@ -3920,24 +3920,86 @@ sortable');%0A + $('#pat-scroll-up, #pat-scroll-dn').detach();%0A
685695d53d5123c5512091c4558c119da9ee581a
add warn log for duplicate out res
relay_handler.js
relay_handler.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 errors = require('./errors'); function RelayRequest(channel, inreq, buildRes) { var self = this; self.channel = channel; self.inreq = inreq; self.inres = null; self.outres = null; self.outreq = null; self.buildRes = buildRes; } RelayRequest.prototype.createOutRequest = function createOutRequest() { var self = this; self.outreq = self.channel.request({ streamed: self.inreq.streamed, ttl: self.inreq.ttl, service: self.inreq.service, headers: self.inreq.headers, retryFlags: self.inreq.retryFlags }); self.outreq.on('response', onResponse); self.outreq.on('error', onError); if (self.outreq.streamed) { // TODO: frame-at-a-time rather than re-streaming? self.inreq.arg1.pipe(self.outreq.arg1); self.inreq.arg2.pipe(self.outreq.arg2); self.inreq.arg3.pipe(self.outreq.arg3); } else { self.outreq.send(self.inreq.arg1, self.inreq.arg2, self.inreq.arg3); } return self.outreq; function onResponse(res) { self.onResponse(res); } function onError(err) { self.onError(err); } }; RelayRequest.prototype.createOutResponse = function createOutResponse(options) { var self = this; if (self.outres) { return; } self.outres = self.buildRes(options); return self.outres; }; RelayRequest.prototype.onResponse = function onResponse(res) { var self = this; self.inres = res; if (!self.createOutResponse({ streamed: self.inres.streamed, code: self.inres.code })) return; if (self.outres.streamed) { self.outres.arg1.end(); self.inres.arg2.pipe(self.outres.arg2); self.inres.arg3.pipe(self.outres.arg3); } else { self.outres.send(self.inres.arg2, self.inres.arg3); } }; RelayRequest.prototype.onError = function onError(err) { var self = this; if (!self.createOutResponse()) return; var codeName = errors.classify(err); if (codeName) { self.outres.sendError(codeName, err.message); } else { self.outres.sendError('UnexpectedError', err.message); self.channel.logger.error('unexpected error while forwarding', { error: err // TODO context }); } // TODO: stat in some cases, e.g. declined / peer not available }; function RelayHandler(channel) { var self = this; self.channel = channel; } RelayHandler.prototype.type = 'tchannel.relay-handler'; RelayHandler.prototype.handleRequest = function handleRequest(req, buildRes) { var self = this; var rereq = new RelayRequest(self.channel, req, buildRes); rereq.createOutRequest(); }; module.exports = RelayHandler;
JavaScript
0
@@ -2413,24 +2413,219 @@ f.outres) %7B%0A + self.channel.logger.warn('relay request already responded', %7B%0A // TODO: better context%0A remoteAddr: self.inreq.remoteAddr,%0A id: self.inreq.id%0A %7D);%0A retu
5b91be77409948be12828afeec75f9f17edd7ce4
fix superfluous requests to conversation
lib/middleware/index.js
lib/middleware/index.js
/** * Copyright 2016 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var debug = require('debug')('watson-middleware:index'); var Promise = require('bluebird'); var ConversationV1 = require('watson-developer-cloud/conversation/v1'); var watsonUtils = require('./utils'); var readContext = Promise.promisify(watsonUtils.readContext); var updateContext = Promise.promisify(watsonUtils.updateContext); var postMessage = Promise.promisify(watsonUtils.postMessage); // These are initiated by Slack itself and not from the end-user. Won't send these to WCS. var ignoreType = ['presence_change', 'reconnect_url']; module.exports = function(config) { if (!config) { throw new Error('Watson Conversation config parameters absent.'); } var middleware = { minimum_confidence: 0.75, hear: function(patterns, message) { if (message.watsonData && message.watsonData.intents) { for (var p = 0; p < patterns.length; p++) { for (var i = 0; i < message.watsonData.intents.length; i++) { if (message.watsonData.intents[i].intent === patterns[p] && message.watsonData.intents[i].confidence >= middleware.minimum_confidence) { return true; } } } } return false; }, before: function(message, payload, callback) { callback(null, payload); }, after: function(message, response, callback) { callback(null, response); }, receive: function(bot, message, next) { var before = Promise.promisify(middleware.before); var after = Promise.promisify(middleware.after); if (!middleware.conversation) { debug('Creating Conversation object with parameters: ' + JSON.stringify(config, 2, null)); middleware.conversation = new ConversationV1(config); } if (!message.text || ignoreType.indexOf(message.type) !== -1 || message.reply_to) { // Ignore messages initiated by Slack. Reply with dummy output object message.watsonData = { output: { text: [] } }; return message; } middleware.storage = bot.botkit.storage; readContext(message.user, middleware.storage).then(function(userContext) { var payload = { workspace_id: config.workspace_id, input: { text: message.text } }; if (userContext) { payload.context = userContext; } return payload; }).then(function(payload) { return before(message, payload); }).then(function(watsonRequest) { return postMessage(middleware.conversation, watsonRequest); }).then(function(watsonResponse) { message.watsonData = watsonResponse; return updateContext(message.user, middleware.storage, watsonResponse); }).then(function(watsonResponse) { return after(message, watsonResponse); }).catch(function(error) { debug('Error: %s', JSON.stringify(error, null, 2)); }).done(function(response) { next(); }); } }; debug('Middleware: ' + JSON.stringify(middleware, 2, null)); return middleware; };
JavaScript
0.000006
@@ -2043,25 +2043,24 @@ ge, next) %7B%0A -%0A var be @@ -2454,16 +2454,34 @@ reply_to + %7C%7C message.bot_id ) %7B%0A
576f2da7c323363c97f1472e79db6065b46af2b1
Update boilerplate, fix http server body request, fix validators on empty scenarios
lib/mysql/Connection.js
lib/mysql/Connection.js
'use strict'; /** * @namespace Jii * @ignore */ var Jii = require('jii'); var mysql = require('mysql'); require('../BaseConnection'); /** * * @class Jii.sql.mysql.Connection * @extends Jii.sql.BaseConnection */ Jii.defineClass('Jii.sql.mysql.Connection', { __extends: Jii.sql.BaseConnection, /** * @type {string} */ host: '127.0.0.1', /** * @type {string} */ port: 3306, /** * @type {string} */ database: '', /** * @type {string|object} */ schemaClass: 'Jii.sql.mysql.Schema', /** * @type {string} */ driverName: 'mysql', _connection: null, /** * Initializes the DB connection. * This method is invoked right after the DB connection is established. * @protected */ _initConnection: function () { this._connection = mysql.createConnection({ host: this.host, port: this.port, user: this.username, password: this.password, database: this.database, timezone: 'local', typeCast: this._typeCast }); this._connection.on('error', this._onError); this._connection.connect(); if (this.charset !== null) { this.exec('SET NAMES ' + this.quoteValue(this.charset)); } this.__super(); }, /** * @protected */ _closeConnection: function () { if (this._connection) { this._connection.end(); } }, /** * Disable auto typing * @returns {string} * @private */ _typeCast: function (field, next) { return field.string(); }, /** * * @param {string} message * @private */ _onError: function(message) { }, /** * * @param {string} sql * @param {string} [method] * @returns {Jii.when} */ exec: function(sql, method) { method = method || null; console.log(sql); return new Jii.when.promise(function(resolve, reject) { this._connection.query(sql, function(err, rows) { if (err) { Jii.error('Database query error, sql: `' + sql + '`, error: ' + String(err)); if (method === 'execute' || method === null) { reject(new Jii.sql.SqlQueryException(err)); } else { resolve(false); } return; } var result = null; switch (method) { case 'execute': result = { affectedRows : rows.affectedRows, insertId: rows.insertId || null }; break; case 'one': result = rows.length > 0 ? rows[0] : null; break; case 'all': result = rows; break; case 'scalar': result = rows.length > 0 ? Jii._.values(rows[0])[0] : null; break; case 'column': result = Jii._.map(rows, function(row) { return Jii._.values(row)[0]; }); break; default: result = rows; } resolve(result); }); }.bind(this)); } });
JavaScript
0
@@ -1670,16 +1670,18 @@ ull;%0A%0A%09%09 +// console.
fd0be9da73742ac2ad913bfa227387a5cde26e1e
Make Epsilon an optional arg that falls back to the global
lib/numeric/calculus.js
lib/numeric/calculus.js
var calculus = exports; /** * Calculate point differential for a specified function at a * specified point. For functions of one variable. * * @param {Function} math function to be evaluated * @param {Number} point to be evaluated * @return {Number} result */ calculus.pointDiff = function (func, point) { var a = func(point - 0.00001); var b = func(point + 0.00001); return (b - a) / (0.00002); }; /** * Calculate riemann sum for a specified, one variable, function * from a starting point, to a finishing point, with n divisions. * * @param {Function} math function to be evaluated * @param {Number} point to initiate evaluation * @param {Number} point to complete evaluation * @param {Number} quantity of divisions * @param {Function} (Optional) Function that returns which value * to sample on each interval; if none is provided, left endpoints * will be used. * @return {Number} result */ calculus.riemann = function (func, start, finish, n, sampler) { var inc = (finish - start) / n, totalHeight = 0, i; if (typeof sampler === 'function') { for (var i = start; i < finish; i += inc) { totalHeight += func(sampler(i, i + inc)); } } else { for (var i = start; i < finish; i += inc) { totalHeight += func(i); } } return totalHeight * inc; }; /** * Helper function in calculating integral of a function * from a to b using simpson quadrature. * * @param {Function} math function to be evaluated * @param {Number} point to initiate evaluation * @param {Number} point to complete evaluation * @return {Number} evaluation */ function simpsonDef (func, a, b) { var c = (a + b) / 2; var d = Math.abs(b - a) / 6; return d * (func(a) + 4 * func(c) + func(b)); } /** * Helper function in calculating integral of a function * from a to b using simpson quadrature. Manages recursive * investigation, handling evaluations within an error bound. * * @param {Function} math function to be evaluated * @param {Number} point to initiate evaluation * @param {Number} point to complete evaluation * @param {Number} error bound (epsilon) * @param {Number} total value * @return {Number} recursive evaluation of left and right side */ function simpsonRecursive (func, a, b, eps, whole) { var c = a + b; var left = simpsonDef(func, a, c); var right = simpsonDef(func, c, b); if (Math.abs(left + right - whole) <= 15 * eps) { return left + right + (left + right - whole) / 15; } else { return simpsonRecursive(func, a, c, eps/2, left) + simpsonRecursive(func, c, b, eps / 2, right); } } /** * Evaluate area under a curve using adaptive simpson quadrature. * * @param {Function} math function to be evaluated * @param {Number} point to initiate evaluation * @param {Number} point to complete evaluation * @param {Number} error bound (epsilon) * @return {Number} area underneath curve */ calculus.adaptiveSimpson = function (func, a, b, eps) { return simpsonRecursive(func, a, b, eps, simpsonDef(func, a, b)); }; /** * Calculate limit of a function at a given point. Can approach from * left, middle, or right. * * @param {Function} math function to be evaluated * @param {Number} point to evaluate * @param {String} approach to limit * @return {Number} limit */ calculus.limit = function (func, point, approach) { if (approach === 'left') { return func(point - 0.001); } else if (approach === 'right') { return func(point + 0.001); } else if (approach === 'middle') { return (calculus.limit(func, point, 'left') + calculus.limit(func, point, 'right')) / 2; } else { throw new Error('Approach not provided'); } };
JavaScript
0
@@ -1080,36 +1080,32 @@ on') %7B%0A for ( -var i = start; i %3C f @@ -1197,20 +1197,16 @@ for ( -var i = star @@ -2092,60 +2092,60 @@ er%7D -error bound (epsilon)%0A * @param %7BNumber%7D total value +total value%0A * @param %7BNumber%7D Error bound (epsilon) %0A * @@ -2252,18 +2252,18 @@ b, -eps, whole +, eps ) %7B%0A @@ -2277,23 +2277,23 @@ = a + b -;%0A var +,%0A left = @@ -2314,23 +2314,23 @@ c, a, c) -;%0A var +,%0A right = @@ -2354,16 +2354,19 @@ c, b);%0A + %0A if (Ma @@ -2822,16 +2822,25 @@ %7BNumber%7D + Optional error b @@ -2845,32 +2845,84 @@ bound (epsilon) +; %0A * global error bound will be used as a fallback. %0A * @return %7BNum @@ -3008,16 +3008,79 @@ eps) %7B%0A + eps = (typeof eps === %22undefined%22) ? numeric.EPSILON : eps;%0A%0A return @@ -3112,13 +3112,8 @@ , b, - eps, sim @@ -3131,16 +3131,21 @@ c, a, b) +, eps );%0A%7D;%0A%0A%0A
ff768d1d5d5a50566582a5132a8451dad8f6fe38
add checks for left/rightButton existance
test/e2e/viewState/test.js
test/e2e/viewState/test.js
describe('tabs test page', function() { var P; beforeEach(function() { browser.get('http://localhost:8080/test/e2e/viewState/test.html'); P = protractor.getInstance(); }); function navTitle() { return element(by.css('h1.title')); } function navButtons(dir) { return dir == 'back' ? element(by.css('header .back-button')) : element(by.css('header .'+dir+'-buttons .button')); } it('navbar with multiple histories', function() { browser.sleep(1000); expect(navTitle().getText()).toBe('Sign-In'); expect(navButtons('back').getAttribute('class')).toContain('hide'); expect(navButtons('left').getText()).toEqual('Home'); expect(navButtons('left').getAttribute('class')).toContain('ion-home'); expect(navButtons('right').getText()).toEqual(''); expect(navButtons('right').getAttribute('class')).toContain('ion-navicon'); element(by.id('sign-in-button')).click(); expect(navTitle().getText()).toBe('Auto List'); expect(navButtons('back').getAttribute('class')).toContain('hide'); expect(navButtons('left').isPresent()).toBe(false); expect(navButtons('right').isPresent()).toBe(false); element(by.css('[href="#/tabs/autos/3"]')).click(); expect(navTitle().getText()).toBe('Auto Details'); expect(navButtons('back').getAttribute('class')).not.toContain('hide'); expect(navButtons('back').getText()).toEqual('Back'); expect(element(by.css('.back-button i')).getAttribute('class')).toContain('ion-arrow-left-c'); // expect(P.isElementPresent(navButtons('left'))).toBe(false); // expect(P.isElementPresent(navButtons('right'))).toBe(false); element(by.css('.tabs a.tab-item:nth-child(2)')).click(); expect(navTitle().getText()).toBe('Add Auto'); expect(navButtons('back').getAttribute('class')).toContain('hide'); // expect(P.isElementPresent(navButtons('left'))).toBe(false); // expect(P.isElementPresent(navButtons('right'))).toBe(false); element(by.css('.tabs a:nth-child(1)')).click(); expect(navTitle().getText()).toBe('Auto Details'); expect(navButtons('back').getAttribute('class')).not.toContain('hide'); navButtons('back').click(); expect(navTitle().getText()).toBe('Auto List'); expect(navButtons('back').getAttribute('class')).toContain('hide'); element(by.css('[href="#/tabs/autos/3"]')).click(); expect(navTitle().getText()).toBe('Auto Details'); expect(navButtons('back').getAttribute('class')).not.toContain('hide'); element(by.css('.tabs a:nth-child(1)')).click(); expect(navTitle().getText()).toBe('Auto List'); expect(navButtons('back').getAttribute('class')).toContain('hide'); element(by.css('[href="#/tabs/autos/3"]')).click(); expect(navTitle().getText()).toBe('Auto Details'); expect(navButtons('back').getAttribute('class')).not.toContain('hide'); element(by.css('.tabs a:nth-child(4)')).click(); expect(navTitle().getText()).toBe('Sign-In'); expect(navButtons('back').getAttribute('class')).toContain('hide'); element(by.id('sign-in-button')).click(); expect(navTitle().getText()).toBe('Auto List'); expect(navButtons('back').getAttribute('class')).toContain('hide'); }); });
JavaScript
0.000001
@@ -1513,35 +1513,32 @@ eft-c');%0A - // expect( P.isElementP @@ -1525,35 +1525,16 @@ expect( -P.isElementPresent( navButto @@ -1535,32 +1535,43 @@ vButtons('left') +.isPresent( )).toBe(false);%0A @@ -1569,35 +1569,32 @@ (false);%0A - // expect( P.isElementP @@ -1581,35 +1581,16 @@ expect( -P.isElementPresent( navButto @@ -1592,32 +1592,43 @@ Buttons('right') +.isPresent( )).toBe(false);%0A @@ -1813,35 +1813,32 @@ 'hide');%0A - // expect( P.isElementP @@ -1825,35 +1825,16 @@ expect( -P.isElementPresent( navButto @@ -1843,16 +1843,27 @@ ('left') +.isPresent( )).toBe( @@ -1877,19 +1877,16 @@ %0A - // expect( P.is @@ -1885,27 +1885,8 @@ ect( -P.isElementPresent( navB @@ -1900,16 +1900,27 @@ 'right') +.isPresent( )).toBe( @@ -2108,24 +2108,137 @@ ain('hide'); +%0A expect(navButtons('left').isPresent()).toBe(false);%0A expect(navButtons('right').isPresent()).toBe(false); %0A%0A navBut @@ -2375,32 +2375,145 @@ Contain('hide'); +%0A expect(navButtons('left').isPresent()).toBe(false);%0A expect(navButtons('right').isPresent()).toBe(false); %0A%0A element(by @@ -2677,32 +2677,145 @@ Contain('hide'); +%0A expect(navButtons('left').isPresent()).toBe(false);%0A expect(navButtons('right').isPresent()).toBe(false); %0A%0A element(by @@ -2969,32 +2969,145 @@ Contain('hide'); +%0A expect(navButtons('left').isPresent()).toBe(false);%0A expect(navButtons('right').isPresent()).toBe(false); %0A%0A element(by @@ -3271,32 +3271,145 @@ Contain('hide'); +%0A expect(navButtons('left').isPresent()).toBe(false);%0A expect(navButtons('right').isPresent()).toBe(false); %0A%0A element(by @@ -3569,16 +3569,285 @@ 'hide'); +%0A expect(navButtons('left').getText()).toEqual('Home');%0A expect(navButtons('left').getAttribute('class')).toContain('ion-home');%0A expect(navButtons('right').getText()).toEqual('');%0A expect(navButtons('right').getAttribute('class')).toContain('ion-navicon'); %0A%0A el
eea540b0fbea9897d146f1e2322c9af804d3f73e
Use moment.utc() over moment() since we're currently always dealing with UTC times
src/plugins/webserver.js
src/plugins/webserver.js
const http = require('http'); const mime = require('mime'); const url = require('url'); const fs = require('fs'); const moment = require('moment'); const config = require('../config'); const threads = require('../data/threads'); const attachments = require('../data/attachments'); const {THREAD_MESSAGE_TYPE} = require('../data/constants'); function notfound(res) { res.statusCode = 404; res.end('Page Not Found'); } async function serveLogs(res, pathParts) { const threadId = pathParts[pathParts.length - 1]; if (threadId.match(/^[0-9a-f\-]+$/) === null) return notfound(res); const thread = await threads.findById(threadId); if (! thread) return notfound(res); const threadMessages = await thread.getThreadMessages(); const lines = threadMessages.map(message => { // Legacy messages are the entire log in one message, so just serve them as they are if (message.message_type === THREAD_MESSAGE_TYPE.LEGACY) { return message.body; } let line = `[${moment(message.created_at).format('YYYY-MM-DD HH:mm:ss')}] `; if (message.message_type === THREAD_MESSAGE_TYPE.SYSTEM) { // System messages don't need the username line += message.body; } else if (message.message_type === THREAD_MESSAGE_TYPE.FROM_USER) { line += `[FROM USER] ${message.user_name}: ${message.body}`; } else if (message.message_type === THREAD_MESSAGE_TYPE.TO_USER) { line += `[TO USER] ${message.user_name}: ${message.body}`; } else { line += `${message.user_name}: ${message.body}`; } return line; }); res.setHeader('Content-Type', 'text/plain; charset=UTF-8'); res.end(lines.join('\n')); } function serveAttachments(res, pathParts) { const desiredFilename = pathParts[pathParts.length - 1]; const id = pathParts[pathParts.length - 2]; if (id.match(/^[0-9]+$/) === null) return notfound(res); if (desiredFilename.match(/^[0-9a-z\._-]+$/i) === null) return notfound(res); const attachmentPath = attachments.getPath(id); fs.access(attachmentPath, (err) => { if (err) return notfound(res); const filenameParts = desiredFilename.split('.'); const ext = (filenameParts.length > 1 ? filenameParts[filenameParts.length - 1] : 'bin'); const fileMime = mime.lookup(ext); res.setHeader('Content-Type', fileMime); const read = fs.createReadStream(attachmentPath); read.pipe(res); }) } module.exports = () => { const server = http.createServer((req, res) => { const parsedUrl = url.parse(`http://${req.url}`); const pathParts = parsedUrl.path.split('/').filter(v => v !== ''); if (parsedUrl.path.startsWith('/logs/')) { serveLogs(res, pathParts); } else if (parsedUrl.path.startsWith('/attachments/')) { serveAttachments(res, pathParts); } else { notfound(res); } }); server.listen(config.port); };
JavaScript
0
@@ -991,16 +991,20 @@ $%7Bmoment +.utc (message
f9f5af8d5fe9ddae0bed612a756c51ce75f589b1
Fix Collapsed Output
lib/output-collapsed.js
lib/output-collapsed.js
/* * lib/output-collapsed.js: emits StackSets in collapsed format, compatible with * Brendan Gregg's FlameGraph tool. */ var mod_assert = require('assert'); /* * Arguments: * * stacks StackSet Stacks to visualize * * output WritableStream Output file */ exports.emit = function emitCollapsed(args, callback) { mod_assert.ok(args.stacks && args.stacks.constructor && args.stacks.constructor.name == 'StackSet', 'required "stacks" argument must be a StackSet'); mod_assert.ok(args.output && args.output.write && typeof (args.output.write) == 'function', 'required "output" argument must be a function'); args.stacks.eachStackByCount(function (frames, count) { process.stdout.write(frames.join(',') + ' ' + count + '\n'); }); };
JavaScript
0
@@ -700,20 +700,17 @@ %7B%0A%09%09 -process.stdo +args.outp ut.w @@ -759,11 +759,24 @@ );%0A%09%7D);%0A +%09callback();%0A %7D;%0A
f3cf96cc38baa24a41bf60b59f4adec556397645
Fix primitive and update issues. (fixes #243, #248)
src/primitives/a-tube.js
src/primitives/a-tube.js
/** * Tube following a custom path. * * Usage: * * ```html * <a-tube path="5 0 5, 5 0 -5, -5 0 -5" radius="0.5"></a-tube> * ``` */ module.exports.Primitive = AFRAME.registerPrimitive('a-tube', { defaultComponents: { tube: {}, }, mappings: { path: 'tube.path', segments: 'tube.segments', radius: 'tube.radius', radialSegments: 'tube.radialSegments', closed: 'tube.closed' } }); module.exports.Component = AFRAME.registerComponent('tube', { schema: { path: {default: []}, segments: {default: 64}, radius: {default: 1}, radialSegments: {default: 8}, closed: {default: false} }, init: function () { const el = this.el, data = this.data; let material = el.components.material; if (!data.path.length) { console.error('[a-tube] `path` property expected but not found.'); return; } const curve = new THREE.CatmullRomCurve3(data.path.map(function (point) { point = point.split(' '); return new THREE.Vector3(Number(point[0]), Number(point[1]), Number(point[2])); })); const geometry = new THREE.TubeGeometry( curve, data.segments, data.radius, data.radialSegments, data.closed ); if (!material) { material = {}; material.material = new THREE.MeshPhongMaterial(); } this.mesh = new THREE.Mesh(geometry, material.material); this.el.setObject3D('mesh', this.mesh); }, remove: function () { if (this.mesh) this.el.removeObject3D('mesh'); } });
JavaScript
0
@@ -371,30 +371,33 @@ s',%0A +' radial -S +-s egments +' : 'tube. @@ -1499,16 +1499,138 @@ ;%0A %7D,%0A%0A + update: function (prevData) %7B%0A if (!Object.keys(prevData).length) return;%0A%0A this.remove();%0A this.init();%0A %7D,%0A%0A remove
dfffc00922865aed35871fbf488e19facb3a8df1
Exclude URLs in uppercase, too (eg HTTP://...).
lib/rules/heuristic/date-format.js
lib/rules/heuristic/date-format.js
'use strict'; exports.name = 'heuristic.date-format'; exports.check = function (sr, done) { // Pseudo-constants: var MONTHS = 'jan|january|feb|february|mar|march|apr|april|may|jun|june|jul|july|aug|august|sep|september|oct|october|nov|november|dec|december' , POSSIBLE_DATE = new RegExp('([0123]?\\d|' + MONTHS + ')[\\ \\-\\/–—]([0123]?\\d|' + MONTHS + ')[\\ \\-\\/–—]([\\\'‘’]?\\d{2})(\\d\\d)?', 'gi') , EXPECTED_DATE_FORMAT = new RegExp('[0123]?\\d\\ (' + MONTHS + ')\\ \\d{4}', 'i'); var boilerplateSections = [ sr.$('div.head'), , sr.$("h2[name='abstract'], h2#abstract, h2[name='status'], h2#status-of-this-document").parent() ] , candidateDates = [] , i , j , elem; for (i in boilerplateSections) { elem = sr.$(boilerplateSections[i]).text().replace(/(?:https?|ftp):\/\/\S+/g, '').match(POSSIBLE_DATE); for (j in elem) { candidateDates.push(elem[j]); } } for (i in candidateDates) { if (!candidateDates[i].match(EXPECTED_DATE_FORMAT)) { sr.error(exports.name, 'wrong', {text: candidateDates[i]}); } } return done(); };
JavaScript
0.000028
@@ -870,16 +870,17 @@ /%5C/%5CS+/g +i , '').ma
361239704a0f9cd9be7260e619f8523fe8b9d5b1
Add events for Split View
app/alloy.js
app/alloy.js
/* global Alloy, ENV_PROD */ // The contents of this file will be executed before any of // your view controllers are ever executed, including the index. // You have access to all functionality on the `Alloy` namespace. // // This is a great place to do any initialization for your app // or create any global variables/functions that you'd like to // make available throughout your app. You can easily make things // accessible globally by attaching them to the `Alloy.Globals` // object. For example: // // Alloy.Globals.someGlobalFunction = function(){}; /** * It's a best practice to your code in alloy.js in a self-executing function * since any variable declared here will be in global scope and never garbage * collected. Use this or global to explicitly define a global, but rather * use Alloy.Globals or a CommonJS module you require where needed. */ (function(global) { // This variable would have been global without the above SEF var versions = Ti.version.split('.'); // Used in the index view and controller to check if the appw as build with Ti 5.2 or later Alloy.Globals.isSupported = (parseInt(versions[0], 10) >= 5 && parseInt(versions[1], 10) >= 2); // Used in index.tss to set flags for supported examples Alloy.Globals.isForceTouchSupported = (OS_IOS && Ti.UI.iOS.forceTouchSupported); Alloy.Globals.isWatchSupported = (OS_IOS && Ti.WatchSession.isSupported); })(this);
JavaScript
0
@@ -23,16 +23,43 @@ ROD */%0A%0A +var log = require('log');%0A%0A // The c @@ -1425,16 +1425,1058 @@ rted);%0A%0A + if (OS_IOS && Alloy.isTablet) %7B%0A%0A // This event fires when the app was still active in the background when it Slides Over another app%0A Ti.App.addEventListener('resume', function(e) %7B%0A log.args('Ti.App:resume', e);%0A %7D);%0A%0A // Will (also) fires when:%0A // 1) This app Slides Over another app%0A // 2) This app goes from Slide Over to Split View%0A // 3) This app goes from quarter to half Split View or visa versa%0A // 4) The Split View devider is dragged but bounces back to existing mode%0A // 5) This app goes from Split View to full view by dragging the devider to the left edge%0A // 6) This app goes from Split View to Slide Over (via singletap on devider)%0A // 7) Another app that was Slide Over this app goes to Split View%0A //%0A // It does not fire when:%0A // 1) This app goes from Split View back full view because the other app goes back from Split View to Slide Over (via singletap on devider)%0A Ti.App.addEventListener('resumed', function(e) %7B%0A log.args('Ti.App:resumed', e);%0A %7D);%0A%0A %7D%0A%0A %7D)(this)
c4c349276ed3f66584bfeb4d8663cdfc9d8840ff
add comment
component.config.js
component.config.js
var bower = require('./bower.json'); var pkg = require('./package.json'); module.exports = { bower: bower, buildFonts: true, // or false. Set to false if you are doing your own thing in the fonts directory buildTool: 'gulp', // grunt not yet available buildStyles: 'sass', // less not yet available buildHTML: 'html-concat', // moustache or assemble or jekyll not yet available buildScripts: 'browserify', // or requirejs not yet available release: 'aws', /// or 'aws', releaseConfig: { //add you release config here... this is for AWS bucket: process.env.AWS_SKYGLOBAL_BUCKET, accessKey: process.env.AWS_ACCESS_KEY_ID, secret: process.env.AWS_SECRET_ACCESS_KEY, region: process.env.AWS_REGION, directoryPrefix: 'components/' }, test: 'karma', //or mocha testConfig: { // where your tests config, specs and reports are saved root: './test', specs: './test/specs', config: './test/karma.conf.js', summary: './test/coverage/summary.json' }, serve: '_site', // can be a node app like below //{ script : 'src/app/server.js', // host: 'http://localhost:3000', // port: 3001, // env: { NODE_ENV: 'local'} //}, // or serve static folders '_site' or ['_site','bower_component'] paths: { /* All paths also have `script`, `styles`, `fonts`, `icons` and `images` properties Feel free to specify a custom path i.e. `scripts: './src/js'` */ "bower": { root: './bower_components', fonts: './bower_components/*/dist/fonts' }, source: { //source files to build your component / site root: "./src" }, "demo": { // files used to demo the source code or an accompanying site. // not files you would want to distribute. root: "./demo" }, dist : { // Compiled source code to be redistributed i.e. via bower root: "./dist" }, "site": { // Compiled demo code + Compiled source code. // Final build code pushed to your chosen release cloud i.e. AWS root: './_site' } }, pkg: pkg };
JavaScript
0
@@ -791,16 +791,57 @@ onents/' + //prefix your target release destination %0A %7D,%0A
b5d22957205f6e8cd4cdc936fe17e88b28f991f4
use this.props.children demo
app/index.js
app/index.js
var USER_DATA = { name: 'Kevin', username: 'wedgedeadly', image: 'https://avatars0.githubusercontent.com/u/3848154?v=3&s=460' } var React = require('react'); var ReactDOM = require('react-dom'); var ProfilePic = React.createClass({ render: function() { return ( <img src={this.props.imageUrl} style={{height: 100, width: 100}} /> ) } }); var ProfileLink = React.createClass({ render: function () { return ( <div> <a href={'https://github.com/' + this.props.username}>{this.props.username}</a> </div> ) } }); var ProfileName = React.createClass({ render: function() { return ( <div>{this.props.name}</div> ) } }); var Avatar = React.createClass({ render: function() { return ( <div> <ProfilePic imageUrl={this.props.user.image} /> <ProfileName name={this.props.user.name} /> <ProfileLink username={this.props.user.username} /> </div> ) } }); ReactDOM.render( <Avatar user={USER_DATA} />, document.getElementById('app') );
JavaScript
0
@@ -45,19 +45,26 @@ e: ' -wedgedeadly +kevinhamiltonsmith ',%0A @@ -133,16 +133,17 @@ s=460'%0A%7D +; %0A%0Avar Re @@ -200,24 +200,325 @@ act-dom');%0A%0A +var Link = React.createClass(%7B%0A changeUrl: function() %7B%0A window.location.replace(this.props.href);%0A %7D,%0A render: function() %7B%0A return (%0A %3Cspan %0A style=%7B%7Bcolor: 'blue', cursor: 'pointer'%7D%7D%0A onClick=%7Bthis.changeUrl%7D%3E%0A %7Bthis.props.children%7D%0A %3C/span%3E%0A )%0A %7D%0A%7D);%0A%0A var ProfileP @@ -763,17 +763,20 @@ %3C -a +Link href=%7B' @@ -819,16 +819,27 @@ ername%7D%3E +%0A %7Bthis.pr @@ -855,11 +855,23 @@ ame%7D -%3C/a +%0A %3C/Link %3E%0A
0910e867863501d9015e87c72966bde65d702ed3
Increase post size limit
app/index.js
app/index.js
#!/usr/bin/env node const express = require('express') const bodyParser = require('body-parser') const browserify = require('browserify-middleware') const sanitizeHtml = require('sanitize-html') const session = require('express-session') const studentHtml = require('./student.html') const mathImg = require('./mathImg') const startedAt = new Date() const FI = require('./FI') const SV = require('./SV') const studentHtmlFI = studentHtml((Object.assign({startedAt: formatDate(startedAt)}, FI.editor))) const studentHtmlSV = studentHtml((Object.assign({startedAt: formatDate(startedAt)}, SV.editor))) const teacherHtml = require('./teacher.html') const teacherHtmlFI = teacherHtml(Object.assign({startedAt: formatDate(startedAt)}, FI.annotating)) const teacherHtmlSV = teacherHtml(Object.assign({startedAt: formatDate(startedAt)}, SV.annotating)) const interfaceIP = process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0' const port = process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || 5000 const app = express() let savedData = {} let savedMarkers = {} const sanitizeOpts = require('./sanitizeOpts') app.use(session({ secret: 'alsdjfwernfeklbjweiugerpfiorq3jlkhewfbads', saveUninitialized: true, resave: true })) app.use('/student.js', browserify(__dirname + '/student.front.js')) app.use('/teacher.js', browserify(__dirname + '/teacher.front.js')) app.use(express.static(__dirname + '/../public')) exposeModules([ 'bootstrap', 'jquery', 'baconjs', 'bacon.jquery', 'mathquill', 'mathjax']) app.get('/tarkistus', (req, res) => res.send(teacherHtmlFI)) app.get('/', (req, res) => res.send(studentHtmlFI)) app.get('/sv/bedomning', (req, res) => res.send(teacherHtmlSV)) app.get('/sv', (req, res) => res.send(studentHtmlSV)) app.use(bodyParser.urlencoded({extended: false})) app.use(bodyParser.json({limit: 20 * 1024 * 1024, strict: false})) app.post('/save', (req, res) => { savedData[req.session.id] = { timestamp: new Date().toISOString(), html: sanitizeHtml(req.body.text, sanitizeOpts) } res.sendStatus(200) }) app.post('/saveMarkers', (req, res) => { savedMarkers[req.session.id] = req.body res.sendStatus(200) }) app.get('/load', (req, res) => res.send(savedData[req.session.id]) || null) app.get('/loadMarkers', (req, res) => res.send(savedMarkers[req.session.id])) app.get('/math.svg', mathImg.handler) app.get('/version', (req, res) => { res.send({ serverStarted: startedAt.toString(), currentServerTime: new Date().toString() }) }) app.listen(port, interfaceIP, () => console.log('Server started at localhost:' + port)) function exposeModules(names) { names.forEach(name => app.use('/' + name, express.static(__dirname + '/../node_modules/' + name))) } function formatDate(date) { return `${date.getDate()}.${date.getMonth() + 1}.${date.getFullYear()} ${pad(date.getHours())}:${pad(date.getMinutes())}` } function pad(num) { return (num > 9 ? '' : '0') + num }
JavaScript
0
@@ -1790,24 +1790,38 @@ ended: false +, limit: '5mb' %7D))%0Aapp.use( @@ -1848,24 +1848,13 @@ it: -20 * 1024 * 1024 +'5mb' , st
b7555bd1ee6043f414cd10502195fe54bcea2bcb
Install npm and bower
app/index.js
app/index.js
'use strict'; var yeoman = require('yeoman-generator'); var path = require('path'); var cgUtils = require('../utils.js'); var _ = require('underscore'); var glob = require('glob'); module.exports = yeoman.Base.extend({ constructor: function(args, options, config) { yeoman.Base.apply(this, arguments); this.config.set('partialDirectory','partial/'); this.config.set('modalDirectory','partial/'); this.config.set('directiveDirectory','directive/'); this.config.set('filterDirectory','filter/'); this.config.set('serviceDirectory','service/'); var inject = { js: { file: 'index.html', marker: cgUtils.JS_MARKER, template: '<script src="<%= filename %>"></script>' }, less: { relativeToModule: true, file: '<%= module %>.less', marker: cgUtils.LESS_MARKER, template: '@import "<%= filename %>";' } }; this.config.set('inject',inject); this.config.save(); }, askForData: function() { this.log('askForData'); return this.prompt([ { name: 'appname', message: 'What would you like the angular app/module name to be?', default: path.basename(process.cwd()) }, { name: 'router', type:'list', message: 'Which router would you like to use?', default: 0, choices: ['Standard Angular Router','Angular UI Router'] }, { type: 'confirm', name: 'jsstrict', message: 'Would you like your AngularJS code to \'use strict\'?', default: true }, { name: 'buildPath', message: 'Which path would you like to build your app? Can be changed later in Gruntfile.js', default: 'dist' } ]).then(function (answers) { this.appname = answers.appname; if (answers.router === 'Angular UI Router') { this.uirouter = true; this.routerJs = 'bower_components/angular-ui-router/release/angular-ui-router.js'; this.routerModuleName = 'ui.router'; this.routerViewDirective = 'ui-view'; } else { this.uirouter = false; this.routerJs = 'bower_components/angular-route/angular-route.js'; this.routerModuleName = 'ngRoute'; this.routerViewDirective = 'ng-view'; } this.config.set('uirouter',this.uirouter); this.config.set('jsstrict', !!answers.jsstrict); this.buildPath = answers.buildPath; this._generateFiles(); }.bind(this)); }, _generateFiles: function() { var root = this.templatePath('skeleton/'); var files = glob.sync('**', { dot: true, nodir: true, cwd: root }); for(var i in files) { var appname = files[i] === 'bower.json' ? _.slugify(this.appname) : _.camelize(this.appname); this.fs.copyTpl( this.templatePath('skeleton/' + files[i]), this.destinationPath(files[i]), { appname: appname, routerModuleName: this.routerModuleName, uirouter: this.uirouter, jsstrict: this.jsstrict, buildPath: this.buildPath, routerJs: this.routerJs, routerViewDirective: this.routerViewDirective } ); } // this._install(); }, _install: function() { this.installDependencies({ skipInstall: this.options['skip-install'] }); } });
JavaScript
0
@@ -3798,11 +3798,8 @@ - // thi
38d01bfec637df5dd9bee48b75a97cccef2f9558
Remove conditional in index for inuit
app/index.js
app/index.js
'use strict'; var fs = require('fs'), util = require('util'), path = require('path'), spawn = require('child_process').spawn, yeoman = require('yeoman-generator'), yosay = require('yosay'), chalk = require('chalk'), wiredep = require('wiredep'); var FrancisCraftGenerator = yeoman.generators.Base.extend({ init: function() { this.pkg = require('../package.json'); }, askFor: function() { var done = this.async(); this.log(yosay('You\'re using Francis Bond\'s fantastic Craft generator.')); var prompts = [{ name: 'slug', message: 'Please enter a unique slug for this project', }, { type: 'checkbox', name: 'features', message: 'What more would you like?', choices: [{ name: 'inuit.css', value: 'includeInuit', checked: true }, { name: 'jQuery', value: 'includejQuery', checked: true }] }]; this.prompt(prompts, function(props) { this.slug = props.slug; var features = props.features, hasFeature = function(feat) { return features.indexOf(feat) !== -1; } this.includeInuit = hasFeature('includeInuit'); this.includejQuery = hasFeature('includejQuery'); done(); }.bind(this)); }, app: function() { this.mkdir('app'); this.mkdir('app/images'); this.mkdir('app/webfonts'); }, styles: function() { this.mkdir('app/styles'); this.copy('main.scss', 'app/styles/main.scss'); if (this.includeInuit) { this.copy('vars.scss', 'app/styles/_vars.scss'); } }, scripts: function() { this.mkdir('app/scripts'); this.write('app/scripts/main.js', 'console.log(\'\\\'Allo \\\'Allo!\');'); }, projectfiles: function() { this.copy('gulpfile.js', 'gulpfile.js'); this.copy('_package.json', 'package.json'); this.copy('_composer.json', 'composer.json'); this.write('composer.lock', ''); this.copy('bowerrc', '.bowerrc'); this.copy('_bower.json', 'bower.json'); this.copy('editorconfig', '.editorconfig'); this.copy('jshintrc', '.jshintrc'); this.copy('gitignore', '.gitignore'); this.copy('gitattributes', '.gitattributes'); this.copy('favicon.ico', 'app/favicon.ico'); this.copy('robots.txt', 'app/robots.txt'); this.copy('humans.txt', 'app/humans.txt'); }, vagrant: function() { this.copy('Vagrantfile', 'Vagrantfile'); }, puppet: function() { this.mkdir('puppet'); this.mkdir('puppet/manifests'); this.mkdir('puppet/modules'); this.mkdir('puppet/modules/app'); this.mkdir('puppet/modules/app/manifests'); this.write('puppet/manifests/init.pp', 'include \'app\''); this.copy('init.pp', 'puppet/modules/app/manifests/init.pp'); this.directory('bootstrap', 'puppet/bootstrap'); this.directory('apache', 'puppet/modules/apache'); this.directory('mysql', 'puppet/modules/mysql'); this.directory('php', 'puppet/modules/php'); this.directory('git', 'puppet/modules/git'); this.directory('curl', 'puppet/modules/curl'); this.directory('composer', 'puppet/modules/composer'); }, craft: function() { this.mkdir('craft'); this.mkdir('craft/storage'); this.mkdir('public'); this.mkdir('public/assets'); this.copy('index.php', 'public/index.php') this.copy('htaccess', 'public/.htaccess'); this.copy('app', 'craft/app'); this.copy('config', 'craft/config'); this.copy('plugins', 'craft/plgins'); this.copy('general.php', 'craft/config/general.php'); this.copy('db.php', 'craft/config/db.php'); }, templates: function() { this.mkdir('app/templates'); this.mkdir('app/templates/news'); this.copy('layout.html', 'app/templates/_layout.html') this.copy('index.html', 'app/templates/index.html') this.copy('404.html', 'app/templates/404.html') this.copy('news__index.html', 'app/templates/news/index.html') this.copy('news__entry.html', 'app/templates/news/_entry.html') }, install: function() { var done = this.async(); this.installDependencies({ callback: function() { var bowerJson = JSON.parse(fs.readFileSync('./bower.json')); wiredep({ bowerJson: bowerJson, directory: 'app/bower_components', src: 'app/templates/_layout.html'<% if (includeInuit) { %>, exclude: ['inuitcss']<% } %> }); done(); }.bind(this) }); } }); module.exports = FrancisCraftGenerator;
JavaScript
0.000015
@@ -4879,33 +4879,8 @@ tml' -%3C%25 if (includeInuit) %7B %25%3E ,%0A @@ -4922,15 +4922,8 @@ ss'%5D -%3C%25 %7D %25%3E %0A
2f1aacc7a2fa234382b7e993fe5d9ebc0d635294
fix index.js
app/index.js
app/index.js
'use strict'; var util = require('util'); var path = require('path'); var yeoman = require('yeoman-generator'); var yosay = require('yosay'); var chalk = require('chalk'); var AppGenerator = yeoman.generators.Base.extend({ init: function () { this.pkg = require('../package.json'); this.on('end', function () { if (!this.options['skip-install']) { this.installDependencies(); } }); }, askFor: function () { var done = this.async(); // Have Yeoman greet the user. this.log(yosay('Welcome to the marvelous Styleguide generator by Antistatique!')); var prompts = [{ type: 'input', name: 'name', message: "What's the name of your project?", default: this.appname }]; this.prompt(prompts, function (props) { this.name = props.name; done(); }.bind(this)); }, app: function () { this.copy('_package.json', 'package.json'); this.copy('_bower.json', 'bower.json'); this.directory('assets/sass/components', 'assets/sass/components'); this.directory('assets/sass/javascript', 'assets/sass/javascript'); this.directory('assets/sass/layout', 'assets/sass/layout'); this.directory('assets/doc_assets', 'assets/doc_assets'); this.mkdir('assets/fonts'); this.mkdir('img'); this.copy('assets/sass/bootstrap-variables.scss', 'assets/sass/bootstrap-variables.scss'); this.copy('assets/sass/bootstrap.scss', 'assets/sass/bootstrap.scss'); this.template('assets/sass/project-variables.scss', 'assets/sass/'+this.name+'-variables.scss'); this.template('assets/sass/project-mixins.scss', 'assets/sass/'+this.name+'-mixins.scss'); this.template('assets/sass/project.scss', 'assets/sass/'+this.name+'.scss'); this.template('assets/README.md', 'assets/README.md'); this.template('hologram_config.yml', 'hologram_config.yml'); this.copy('gulpfile.js', 'gulpfile.js'); }, projectfiles: function () { this.copy('editorconfig', '.editorconfig'); this.copy('jshintrc', '.jshintrc'); } }); module.exports = AppGenerator;
JavaScript
0.000046
@@ -1882,20 +1882,24 @@ this. -copy +template ('gulpfi
5c5df520ac6c345c224715f251d6279a51e625ff
Replace deprecated Buffer constructor with Buffer.from
lib/raygun.transport.js
lib/raygun.transport.js
/* * raygun * https://github.com/MindscapeHQ/raygun4node * * Copyright (c) 2015 MindscapeHQ * Licensed under the MIT license. */ 'use strict'; var http = require('http'); var https = require('https'); var API_HOST = 'api.raygun.io'; var getFullPath = function(options) { var useSSL = options.useSSL, port = useSSL ? 443 : 80, protocol = useSSL ? 'https' : 'http'; return protocol + '://' + API_HOST + ':' + port + '/entries'; }; var send = function (options) { try { var data = new Buffer(JSON.stringify(options.message), 'utf8'); var fullPath = getFullPath(options); var httpOptions = { host: options.host || API_HOST, port: options.port || 443, path: fullPath, method: 'POST', headers: { 'Host': API_HOST, 'Content-Type': 'application/json', 'Content-Length': data.length, 'X-ApiKey': options.apiKey } }; var cb = function (response) { if (options.callback) { if (options.callback.length > 1) { options.callback(null, response); } else { options.callback(response); } } }; var httpLib = options.useSSL ? https : http; var request = httpLib.request(httpOptions, cb); request.on("error", function (e) { console.log("Raygun: error " + e.message + " occurred while attempting to send error with message: " + options.message); // If the callback has two parameters, it should expect an `error` value. if (options.callback && options.callback.length > 1) { options.callback(e); } }); request.write(data); request.end(); } catch (e) { console.log("Raygun: error " + e + " occurred while attempting to send error with message: " + options.message); } }; exports.send = send;
JavaScript
0
@@ -514,19 +514,20 @@ ta = - new Buffer +.from (JSO @@ -558,16 +558,8 @@ age) -, 'utf8' );%0A
f7b90b76335fd4fc0fda51ac4592cf5423773991
fix menu options
app/index.js
app/index.js
'use strict' const fs = require('fs') const os = require('os') const path = require('path') const { app, BrowserWindow, Menu, ipcMain } = require('electron') const windowStateKeeper = require('electron-window-state') const event = require('./eme/event') const buildMenu = require('./eme/menu') const emeWindow = require('./eme/window') const config = require('./eme/config') const {parseShellCommand} = require('./eme/shell') const { isDev } = require('./eme/utils') const contextMenu = require('./eme/context-menu') require('electron-context-menu')(contextMenu) const platform = os.platform() const createMainWindow = () => { const windowState = windowStateKeeper({ defaultWidth: 800, defaultHeight: 600 }) if (platform === 'linux') { windowState.icon = path.join(__dirname, 'resources/icon.png') } const win = emeWindow.createWindow({windowState}) windowState.manage(win) return win } const showAboutWindow = () => { emeWindow.createWindow({ homepage: 'file://' + path.join(__dirname, 'pages/about.html'), windowState: { title: 'About EME', width: 360, height: 408, resizable: false, center: true, fullscreenable: false, maximizable: false, titleBarStyle: 'hidden-inset', frame: false, backgroundColor: '#ECECEC' } }) } const appMenu = buildMenu({ createWindow: emeWindow.createWindow, showAboutWindow }) const reloadMenu = () => { Menu.setApplicationMenu(buildMenu({ createWindow: emeWindow.createWindow })) } let mainWindow // eslint-disable-line let pdfWindow // eslint-disable-line app.on('ready', () => { const argv = parseShellCommand() Menu.setApplicationMenu(appMenu) mainWindow = createMainWindow() if (!isDev) { const {pathsToOpen, resourcePath} = argv const pathToOpen = pathsToOpen[0] if (pathToOpen && resourcePath) { const locationToOpen = `${resourcePath}/${pathToOpen}` mainWindow.webContents.on('did-finish-load', () => { mainWindow.webContents.send('open-file', locationToOpen) }) } } if (platform === 'darwin') { mainWindow.setSheetOffset(36) } }) app.on('window-all-closed', () => { if (platform !== 'darwin') { app.quit() } }) app.on('activate', () => { if (emeWindow.wins === 0) { mainWindow = createMainWindow() if (platform === 'darwin') { mainWindow.setSheetOffset(36) } } }) app.on('open-file', (e, filePath) => { e.preventDefault() console.log(filePath) }) ipcMain.on('close-focus-window', () => { BrowserWindow.getFocusedWindow().close() }) // TODO: refactor ipcMain.on('print-to-pdf', (e, html) => { pdfWindow = new BrowserWindow({show: false}) const tempPath = path.join(os.tmpdir(), `eme-export-pdf.${Date.now()}.html`) fs.writeFileSync(tempPath, html, 'utf8') console.log(tempPath) pdfWindow.loadURL(`file://${tempPath}`) }) ipcMain.on('pdf-window-ready', (e, options) => { const page = pdfWindow.webContents page.on('did-finish-load', () => { page.printToPDF({ pageSize: options.isPresentation ? 'Tabloid' : 'A4', landscape: options.isPresentation }, (err, pdfData) => { if (err) { return console.log(err) } fs.writeFile(options.saveTo, pdfData, err => { pdfWindow.destroy() pdfWindow = undefined mainWindow.webContents.send('finish-exporting-pdf', err, options.saveTo) }) }) }) }) ipcMain.on('add-recent-file', (e, filePath) => { const files = config.get('recentFiles') const existing = files.indexOf(filePath) if (existing === -1) { // add to the head files.unshift(filePath) if (files.length > 10) { files.pop() } } else { // remove the existing one // add to the head files.splice(existing, 1) files.unshift(filePath) } config.set('recentFiles', files) reloadMenu() }) ipcMain.on('remove-recent-file', (e, fileToRemove) => { config.set('recentFiles', config.get('recentFiles').filter(filePath => { return filePath !== fileToRemove })) reloadMenu() }) ipcMain.on('log', (e, msg) => { console.log(JSON.stringify(msg, null, 2)) }) ipcMain.on('reload-menu', () => { reloadMenu() }) event.on('reload-menu', () => { reloadMenu() })
JavaScript
0.000011
@@ -1342,28 +1342,22 @@ nst -appMenu = buildMenu( +menuOptions = %7B%0A @@ -1413,16 +1413,55 @@ Window%0A%7D +%0A%0Aconst appMenu = buildMenu(menuOptions )%0A%0Aconst @@ -1522,54 +1522,19 @@ enu( -%7B%0A createWindow: emeWindow.createWindow%0A %7D +menuOptions ))%0A%7D
da3bbdf2e316288bfde2ab906f7fe294b9e62540
bump version number on example and docs
lib/release-override.js
lib/release-override.js
// While galaxy apps are on their own special meteor releases, override // Meteor.release here. if (Meteor.isClient) { Meteor.release = Meteor.release ? "0.6.6.1" : undefined; }
JavaScript
0
@@ -159,9 +159,9 @@ 6.6. -1 +2 %22 :
6b1cc4ae9776e4b755ad353652466616a74c1ba2
Add support for direct requests
lib/request-analyzer.js
lib/request-analyzer.js
/** * Request Analyzer * Belongs to Decentraleyes. * * @author Thomas Rientjes * @since 2014-05-30 * @license MPL 2.0 * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict'; /** * Imports */ /** * Resource version mappings. * @var {object} mappings */ var mappings = require('./mappings'); /** * Public Methods */ function isValidCandidate(httpChannel) { if (mappings[httpChannel.URI.host] === undefined) { return false; } //noinspection JSUnresolvedVariable var whitelistedDomains = require('sdk/simple-prefs').prefs.domainWhitelist.split(";"); for (var domain in whitelistedDomains) { if (whitelistedDomains[domain] === httpChannel.referrer.host) { // Remove referer header from request. httpChannel.setRequestHeader('Referer', null, false); return false; } } return httpChannel.requestMethod === 'GET'; } function getLocalTarget(channelHost, channelPath) { var basePath, hostMappings, resourceMappings, localTarget; hostMappings = mappings[channelHost]; // Ignore mapping files. if (channelPath.indexOf('.min.js.map') > -1) { return false; } if (channelPath.indexOf('.min.map') > -1) { return false; } basePath = matchBasePath(hostMappings, channelPath); if (!basePath) { return false; } resourceMappings = hostMappings[basePath]; localTarget = matchResourcePath(resourceMappings, basePath, channelPath); if (!localTarget) { return false; } return localTarget; } /** * Exports */ exports.isValidCandidate = isValidCandidate; exports.getLocalTarget = getLocalTarget; /** * Private Methods */ function matchBasePath(hostMappings, channelPath) { for (var basePath in hostMappings) { if (hostMappings.hasOwnProperty(basePath)) { if (channelPath.indexOf(basePath) === 0) { return basePath; } } } return false; } function matchResourcePath(resourceMappings, basePath, channelPath) { var resourcePath, versionNumber, resourcePattern; resourcePath = channelPath.replace(basePath, ''); versionNumber = resourcePath.match(/(?:\d{1,2}\.){1,3}\d{1,2}/); resourcePattern = resourcePath.replace(versionNumber, '{version}'); for (var resourceMold in resourceMappings) { if (resourceMappings.hasOwnProperty(resourceMold)) { if (resourcePattern.indexOf(resourceMold) === 0) { var localTarget = { path: resourceMappings[resourceMold].path, type: resourceMappings[resourceMold].type }; // Fill in the appropriate version number. localTarget.path = localTarget.path.replace('{version}', versionNumber); return localTarget; } } } return false; }
JavaScript
0
@@ -762,24 +762,61 @@ plit(%22;%22);%0A%0A + if (httpChannel.referrer) %7B%0A%0A for (var @@ -845,24 +845,28 @@ Domains) %7B%0A%0A + if ( @@ -938,16 +938,20 @@ + + // Remov @@ -981,16 +981,20 @@ equest.%0A + @@ -1056,32 +1056,36 @@ );%0A%0A + + return false;%0A @@ -1078,24 +1078,38 @@ turn false;%0A + %7D%0A %7D%0A
c0c2a060f6829cb11ccec6d727bd571b9d6cbbb9
make object susan
codeacad_this2.js
codeacad_this2.js
// here we define our method using "this", before we even introduce bob var setAge = function (newAge) { this.age = newAge; }; // now we make bob var bob = new Object(); bob.age = 30; bob.setAge = setAge;
JavaScript
0.999828
@@ -204,8 +204,126 @@ Age;%0A %0A +// make susan here, and first give her an age of 25%0Avar susan = new Object();%0Asusan.age = 25;%0Asusan.setAge = setAge;%0A%0A
97821d120b0664b244624620fedf4a4719c73336
Return listening to $locationChangeSuccess back because it is not the source of broken query error
lib/web/angular-base-workaround.js
lib/web/angular-base-workaround.js
if ('angular' in window) { angular.module('ng').run(['$rootScope', '$window', function ($rootScope, $window) { $rootScope.$watch(function() { return $window.location.pathname + $window.location.search; }, function (newUrl, oldUrl) { if (newUrl === oldUrl) { return; } var evt = document.createEvent('CustomEvent'); evt.initCustomEvent('spriteLoaderLocationUpdated', false, false, { newUrl: newUrl }); window.dispatchEvent(evt); }); }]); }
JavaScript
0.000003
@@ -65,19 +65,8 @@ pe', - '$window', fun @@ -86,209 +86,63 @@ cope -, $window) %7B%0A%0A %09$rootScope.$watch(function() %7B%0A%09%09 return $window.location.pathname + $window.location.search;%0A %09%7D, function (newUrl, oldUrl) %7B%0A if (newUrl === oldUrl) %7B%0A return;%0A %7D%0A +) %7B%0A%0A function dispatchLocationUpdateEvent(newUrl) %7B %0A @@ -330,16 +330,134 @@ t(evt);%0A + %7D%0A%0A $rootScope.$on('$locationChangeSuccess', function (e, newUrl) %7B%0A dispatchLocationUpdateEvent(newUrl);%0A %7D);%0A
b8befe3fbb95efda2df36471f8a0d22237afab44
Add watch option to wee build command
commands/build.js
commands/build.js
const exec = require('child_process').exec; const spawn = require('child_process').spawn; const name = 'build'; const assets = { images: '--images', styles: '--styles', scripts: '--scripts' }; module.exports = { name: name, description: 'Compile project assets', usage: '- wee build [options]', options: [ ['-i, ' + assets.images, 'copy and minify image assets'], ['-c, ' + assets.styles, 'compile and minify stylesheets'], ['-s, ' + assets.scripts, 'compile and minify scripts'] ], action(config, options) { // Set Arguments array const commands = []; const ansi = '--ansi'; const baseCommand = 'run'; let feedbackItems = []; let option = name; let spawnCount = 0; let error = null; if (options.images) { commands.push([baseCommand, 'build:images', ansi]); option = option + ' ' + assets.images; feedbackItems.push(assets.images); } if (options.styles) { commands.push([baseCommand, 'build:css', ansi]); option += ' ' + assets.styles; feedbackItems.push(assets.styles); } if (options.scripts) { commands.push([baseCommand, 'build:js', ansi]); option += ' ' + assets.scripts; feedbackItems.push(assets.scripts); } if (! commands.length) { commands.push([baseCommand, 'build', ansi]); feedbackItems.push('build'); } const lastSpawn = commands.length; commands.forEach(command => { // Execute npm build [options] let child = spawn('npm', command, { cwd: config.rootPath, stdio: 'inherit' }); child.on('error', data => { error = true; console.log(data); }); child.on('close', (code) => { spawnCount += 1; if (spawnCount === lastSpawn && ! error) { console.log(`Finished: ${buildFeedback(feedbackItems)}`); } }); }); } }; /** * Build out feedback string * * @param {Array} items * @return {string} */ function buildFeedback(items) { return items.map(item => { return item.replace('--', ''); }) .join(', '); }
JavaScript
0
@@ -486,16 +486,50 @@ cripts'%5D +,%0A%09%09%5B'-w, --watch', 'watch files'%5D %0A%09%5D,%0A%09ac @@ -1776,16 +1776,274 @@ );%0A%09%09%09%09%7D +%0A%0A%09%09%09%09if (options.watch) %7B%0A%09%09%09%09%09// Execute npm build %5Boptions%5D%0A%09%09%09%09%09let child = spawn('npm', %5BbaseCommand, 'watch', ansi%5D, %7B%0A%09%09%09%09%09%09cwd: config.rootPath,%0A%09%09%09%09%09%09stdio: 'inherit'%0A%09%09%09%09%09%7D);%0A%0A%09%09%09%09%09child.on('error', data =%3E %7B%0A%09%09%09%09%09%09console.log(data);%0A%09%09%09%09%09%7D);%0A%09%09%09%09%7D %0A%09%09%09%7D);%0A
48e250c715b3a424b41d5cd198b23e2e83b8b4f6
Update greet.js
commands/greet.js
commands/greet.js
exports.run = function(client, message){ console.log("Margarine greeted someone."); message.channel.send("Hello!"); }; exports.conf = { enabled: true, guildOnly: false, aliases: ["greet"], permLevel: 0 }; exports.help = { name: "Greet", description: "Have Margarine greet you with a hello!", usage: "greet" };
JavaScript
0
@@ -1,16 +1,53 @@ +const moment = require(%22moment%22);%0D%0A%0D%0A exports.run = fu @@ -92,36 +92,108 @@ log( -%22Margarine greeted someone.%22 +%60%5B$%7Bmoment().format('YYYY-MM-DD HH:mm')%7D%5D Margarine greeted someone.%60);%0D%0A message.delete().catch( );%0D%0A @@ -221,16 +221,43 @@ end( -%22 +%60 Hello -!%22 + $%7Bmessage.author.username%7D!%60 );%0D%0A
956e73b73b7db1ca75ec12ada9b42f55b95cb0c2
debug code
app/js/ui.js
app/js/ui.js
//------------Input Button Stuff----------------------// document.getElementById('upload_link').onclick = function() { document.getElementById('input_csv').click(); }; document.getElementById('upload_link_topo').onclick = function() { document.getElementById('input_topo').click(); }; function clearContents(element) { switch(element) { console.log("clearContents()"); case "Enter projection": element.value = ''; break; case "Enter scale": element.value = ''; break; case "Enter set of colors": element.value = ''; break; case "Enter session ID": element.value = ''; break; } } /* * Code to run when document is ready */ $(document).ready(function() { // the "href" attribute of the modal trigger must specify the modal ID that wants to be triggered $('.modal').modal(); $('.modal').modal({ dismissible: true, // Modal can be dismissed by clicking outside of the modal opacity: .5, // Opacity of modal background inDuration: 300, // Transition in duration outDuration: 200, // Transition out duration startingTop: '4%', // Starting top style attribute endingTop: '10%', // Ending top style attribute ready: function(modal, trigger) { // Callback for Modal open. Modal and trigger parameters available. //alert("Ready test 1 2"); console.log(modal, trigger); }, complete: function() { //alert('Closed test test'); } // Callback for Modal close }); $(".dropdown-button").dropdown(); }); function download_png(){ console.log("download png"); var svg = d3.select('svg'); saveSvgAsPng(d3.select('svg').node(), 'cartogram.png'); } $('#download_svg').click(function(){ var a = document.createElement('a'); a.href = 'data:image/svg+xml;utf8,' + unescape($('#map')[0].outerHTML); a.download = 'svg_info.svg'; a.target = '_blank'; document.body.appendChild(a); a.click(); document.body.removeChild(a); }); function share_email(){ console.log("email"); svgAsDataUri(d3.select('svg').node(), {}, function(uri) { // console.log('uri', uri); // var pic = d3.select('svg'); var pic = d3.select('svg'); window.open('mailto:[email protected]?subject=Check out my cartogram!&body='+pic); // window.location.href = "mailto:[email protected]?subject=Mail request&body="+body; }); } function share_twitter(){ console.log("tweet"); window.open(href="https://twitter.com/intent/tweet?text=Hello%20world", '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600'); }
JavaScript
0.000007
@@ -323,30 +323,8 @@ ) %7B%0A - switch(element) %7B%0A co @@ -349,24 +349,44 @@ ntents()%22);%0A + switch(element) %7B%0A case %22En
e670d6d2319a8274cd162958e8cde61b5ca5841d
Add simply API request proxy.
app/proxy.js
app/proxy.js
var http = require('http'); var sys = require('sys'); http.createServer(function(request, response) { sys.log(request.connection.remoteAddress + ": " + request.method + " " + request.url); var proxy = http.createClient(6800, request.headers['host']) var proxy_request = proxy.request(request.method, request.url, request.headers); proxy_request.addListener('response', function (proxy_response) { proxy_response.addListener('data', function(chunk) { response.write(chunk, 'binary'); }); proxy_response.addListener('end', function() { response.end(); }); response.writeHead(proxy_response.statusCode, proxy_response.headers); }); request.addListener('data', function(chunk) { proxy_request.write(chunk, 'binary'); }); request.addListener('end', function() { proxy_request.end(); }); }).listen(8080);
JavaScript
0
@@ -29,12 +29,56 @@ var -sys +child_process = require('child_process');%0Avar fs = r @@ -85,18 +85,17 @@ equire(' -sy +f s');%0A%0Aht @@ -114,348 +114,811 @@ ver( -function(request, response) %7B%0A sys.log(request.connection.remoteAddress + %22: %22 + request.method + %22 %22 + request.url);%0A var proxy = http.createClient(6800, request.headers%5B'host'%5D)%0A var proxy_request = proxy.request(request.method, request.url, request.headers) +onRequest).listen(3000);%0A%0Avar json_cmds = %5B'addversion.json','schedule.json','cancel.json','listprojects.json','listversions,json','listspiders.json','listjobs.json','delversion.json','delproject.json'%5D;%0A%0Afunction isApiRequest(url)%7B%0A var result = false;%0A url = url.toLowerCase();%0A for(var i = 0; i %3C json_cmds.length; i++)%7B%0A if(url.indexOf(json_cmds%5Bi%5D) != -1)%7B%0A console.log('Found: ' + json_cmds%5Bi%5D);%0A result = true;%0A break;%0A %7D%0A %7D%0A return result;%0A%7D%0A%0A%0Afunction onRequest(client_req, client_res) %7B%0A%0A var options = %7B%0A hostname: 'ec2-50-16-60-252.compute-1.amazonaws.com',%0A port: 6800,%0A path: client_req.url,%0A method: 'GET'%0A %7D ;%0A +%0A -proxy_request.addListener('response', function (proxy_response) %7B +if(isApiRequest(client_req.url) === true)%7B%0A // Proxy all API requests%0A %0A @@ -926,41 +926,40 @@ +var proxy -_response.addListener('data' + = http.request(options , fu @@ -956,38 +956,37 @@ ptions, function -(chunk + (res ) %7B%0A @@ -992,364 +992,438 @@ res -ponse.write(chunk, 'binary');%0A %7D);%0A proxy_response.addListener('end', function() %7B%0A response.end();%0A %7D);%0A response.writeHead(proxy_response.statusCode, proxy_response.headers);%0A %7D);%0A request.addListener('data', function(chunk) %7B%0A proxy_request.write(chunk, 'binary'); +.pipe(client_res, %7B%0A end: true%0A %7D);%0A %7D);%0A client_req.pipe(proxy, %7B%0A end: true%0A %7D);%0A %7D else %7B%0A%0A var f = client_req.url.substring(1);%0A%0A // Serve up ordinary files from the local filesystem%0A var readStream = fs.createReadStream(f);%0A // This will wait until we know the readable stream is actually valid before piping %0A -%7D);%0A re -quest.addListener(' +adStream.on('op en -d ', f @@ -1429,16 +1429,17 @@ function + () %7B%0A @@ -1447,49 +1447,224 @@ + -proxy_request.end( + // This just pipes the read stream to the response object (which goes to the client)%0A readStream.pipe(client_res );%0A + + %7D);%0A -%7D).listen(8080 +%0A %7D%0A%7D%0A%0A%0Achild_process.spawn('open', %5B'http://localhost:3000/index.html'%5D ); +%0A
d144e40af05b4053d7ebaa818f9edc24f1a04c5b
Test 2
lib/components/announcements.js
lib/components/announcements.js
'use strict'; var Zermelo = require('../index.js'); Zermelo.prototype.getAnnouncements = function(bool, callback) { var a = true; if(a) { console.log('b'); } else { console.log('c'); } };
JavaScript
0
@@ -111,18 +111,16 @@ back) %7B%0A -%0A%0A var @@ -120,16 +120,28 @@ var a +nUnknownBool = true; @@ -150,16 +150,28 @@ if(a +nUnknownBool ) %7B%0A @@ -186,16 +186,24 @@ e.log('b +bbbbbbbb ');%0A @@ -235,16 +235,24 @@ e.log('c +cccccccc ');%0A
76a6f972d1cc7e6d65e9e8b5d8c97ec273f7ef7e
Include query string when retrieving window path
lib/stores/url-store.js
lib/stores/url-store.js
var invariant = require('react/lib/invariant'); var warning = require('react/lib/warning'); var ExecutionEnvironment = require('react/lib/ExecutionEnvironment'); var normalizePath = require('../path').normalize; var CHANGE_EVENTS = { hash: 'hashchange', history: 'popstate' }; var _location; function getWindowPathname() { return _location === 'history' ? window.location.pathname : window.location.hash.substr(1); } function pushHistory(path) { window.history.pushState({ path: path }, '', path); notifyChange(); } function pushHash(path) { window.location.hash = path; } function replaceHistory(path) { window.history.replaceState({ path: path }, '', path); notifyChange(); } function replaceHash(path) { window.location.replace(path); } var _currentPath = '/'; function updateCurrentPath(path) { _currentPath = normalizePath(path); notifyChange(); } var EventEmitter = require('event-emitter'); var _events = EventEmitter(); function notifyChange() { _events.emit('change'); } var URLStore = { /** * Returns the type of navigation that is currently being used. */ getLocation: function () { return _location || 'hash'; }, /** * Pushes the given path onto the browser navigation stack. */ push: function (path) { if (_location != null) { _location === 'history' ? pushHistory(path) : pushHash(path); } else { updateCurrentPath(path); } }, /** * Replaces the current URL path with the given path without adding an entry * to the browser's history. */ replace: function (path) { if (_location != null) { _location === 'history' ? replaceHistory(path) : replaceHash(path); } else { updateCurrentPath(path); } }, /** * Returns the value of the current URL path. */ getCurrentPath: function () { return _location == null ? _currentPath : getWindowPathname(); }, /** * Returns true if the URL store has already been setup. */ isSetup: function () { return _location != null; }, /** * Sets up the URL store to get the value of the current path from window.location * as it changes. The location argument may be either "hash" or "history". */ setup: function (location) { invariant( ExecutionEnvironment.canUseDOM, 'You cannot setup the URL store in an environment with no DOM' ); if (_location != null) { warning( _location === location, 'The URL store was already setup using ' + _location + ' location. ' + 'You cannot use ' + location + ' location on the same page' ); return; // Don't setup twice. } var changeEvent = CHANGE_EVENTS[location]; invariant( changeEvent, 'The URL store location "' + location + '" is not valid. ' + 'It must be either "hash" or "history"' ); _location = location; if (location === 'hash' && getWindowPathname() === '') pushHash('/'); window.addEventListener(changeEvent, notifyChange, false); }, /** * Stops listening for changes to window.location. */ teardown: function () { if (_location == null) return; var changeEvent = CHANGE_EVENTS[_location]; window.removeEventListener(changeEvent, notifyChange, false); _location = null; }, /** * Adds a listener that will be called when the URL changes. */ addChangeListener: function (listener) { _events.on('change', listener); }, /** * Removes the given change listener. */ removeChangeListener: function (listener) { _events.off('change', listener); } }; module.exports = URLStore;
JavaScript
0
@@ -383,16 +383,41 @@ athname ++ window.location.search : window
d0b3be1c9064bfab402ec825bf08b2acac8cfb9e
add startsWith string polyfill
lib/test/cases/build.js
lib/test/cases/build.js
var fs = require("fs"); //------------------------------------------------------------------------------ // Result Data //------------------------------------------------------------------------------ function getInitialResult() { var result = { cases: [], currLabel: null, // "in" or "out" currCase: getInitialCase() }; Object.preventExtensions(result); return result; } function getInitialCase() { var testCase = { "in": null, "out": null }; Object.preventExtensions(testCase); return testCase; } //------------------------------------------------------------------------------ // Error Handling //------------------------------------------------------------------------------ function error(fileLineNo, msg) { console.error("error at test-case line #" + (fileLineNo+1) + ": " + msg); process.exit(1); } //------------------------------------------------------------------------------ // Test case parsing //------------------------------------------------------------------------------ function parseLine_endBlock(result, fileLineNo, line) { if (result.currLabel === null) { error(fileLineNo, "opening block must have a name: 'in' or 'out'."); } var isTestCaseDone = (result.currCase.out !== null); if (isTestCaseDone) { result.cases.push(result.currCase); result.currLabel = null; result.currCase = getInitialCase(); } else { result.currLabel = null; } } function parseLine_startBlock(result, fileLineNo, line) { if (result.currLabel !== null) { error(fileLineNo, "must close previous block '" + result.currLabel + "' before starting new one."); } var label = line.substring("```".length); if (label !== "in" && label !== "out") { error(fileLineNo, "block name '" + label + "' must be either 'in' or 'out'."); } if (label === "in" && result.currCase.in !== null) { error(fileLineNo, "there is already an 'in' block for this test case."); } if (label === "out" && result.currCase.in === null) { error(fileLineNo, "must include an 'in' block before an 'out' block."); } result.currLabel = label; result.currCase[label] = { "fileLineNo": fileLineNo, "lines": [], "cursor": null }; } function parseLine_insideBlock(result, fileLineNo, line) { var block = result.currCase[result.currLabel]; var cursorX = line.indexOf("|"); if (cursorX !== -1) { if (result.currLabel === "out") { error(fileLineNo, "no cursor allowed in 'out' block yet"); } if (block.cursor !== null) { error(fileLineNo, "only one cursor allowed. cursor already found at line", block.cursor.cursorLine); } var lineClean = line.split("|").join(""); if (lineClean.length < line.length-1) { error(fileLineNo, "only one cursor allowed"); } line = lineClean; block.cursor = { "cursorX": cursorX, "cursorLine": block.lines.length }; } block.lines.push(line); } function parseLine_default(result, fileLineNo, line) { return result; } function parseLine(result, fileLineNo, line) { var f; if (line === "```") { f = parseLine_endBlock; } else if (line.startsWith("```")) { f = parseLine_startBlock; } else if (result.currLabel !== null) { f = parseLine_insideBlock; } else { f = parseLine_default; } return f(result, fileLineNo, line); } function parseText(text) { var lines = text.split("\n"); var result = getInitialResult(); var i; for (i=0; i<lines.length; i++) { parseLine(result, i, lines[i]); } if (result.currLabel !== null) { error("EOF", "code block not closed"); } if (result.currCase.in !== null || result.currCase.out !== null) { error("EOF", "test case 'out' block not completed"); } return result.cases; } //------------------------------------------------------------------------------ // JSON builder //------------------------------------------------------------------------------ var casesPath = __dirname; function buildJson(name) { // JSON.stringify(data, null, " "); var inFile = casesPath + "/" + name + ".md"; var outFile = casesPath + "/" + name + ".json"; var inText = fs.readFileSync(inFile, "utf8"); console.log( " compiling " + name + ".md" + " --> " + name + ".json" ); var cases = parseText(inText); var outText = JSON.stringify(cases, null, " "); fs.writeFileSync(outFile, outText); } function buildAll() { console.log("\nReading test cases described in Markdown and compiling to JSON..."); buildJson("indent-mode"); buildJson("paren-mode"); console.log(); } //------------------------------------------------------------------------------ // Exports and Entry //------------------------------------------------------------------------------ // export api exports.buildAll = buildAll; // allow running this file directly with Node if (require.main === module) { buildAll(); }
JavaScript
0.000006
@@ -18,16 +18,503 @@ %22fs%22);%0A%0A +//------------------------------------------------------------------------------%0A// String Polyfill%0A//------------------------------------------------------------------------------%0A%0A// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith%0Aif (!String.prototype.startsWith) %7B%0A String.prototype.startsWith = function(searchString, position) %7B%0A position = position %7C%7C 0;%0A return this.indexOf(searchString, position) === position;%0A %7D;%0A%7D%0A%0A //------ @@ -5433,13 +5433,12 @@ ildAll();%0A%7D%0A -%0A
d4bdcb60a01ca3988e9c5aebb1036d7fc304386c
Make template token objects adhere to token object structure (#343)
lib/token-translator.js
lib/token-translator.js
/** * @fileoverview Translates tokens between Acorn format and Esprima format. * @author Nicholas C. Zakas */ /* eslint no-underscore-dangle: 0 */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ // none! //------------------------------------------------------------------------------ // Private //------------------------------------------------------------------------------ // Esprima Token Types var Token = { Boolean: "Boolean", EOF: "<end>", Identifier: "Identifier", Keyword: "Keyword", Null: "Null", Numeric: "Numeric", Punctuator: "Punctuator", String: "String", RegularExpression: "RegularExpression", Template: "Template", JSXIdentifier: "JSXIdentifier", JSXText: "JSXText" }; /** * Converts part of a template into an Esprima token. * @param {AcornToken[]} tokens The Acorn tokens representing the template. * @param {string} code The source code. * @returns {EsprimaToken} The Esprima equivalent of the template token. * @private */ function convertTemplatePart(tokens, code) { var firstToken = tokens[0], lastTemplateToken = tokens[tokens.length - 1]; var token = { type: Token.Template, value: code.slice(firstToken.start, lastTemplateToken.end) }; if (firstToken.loc) { token.loc = { start: firstToken.loc.start, end: lastTemplateToken.loc.end }; } if (firstToken.range) { token.range = [firstToken.range[0], lastTemplateToken.range[1]]; } return token; } /** * Contains logic to translate Acorn tokens into Esprima tokens. * @param {Object} acornTokTypes The Acorn token types. * @param {string} code The source code Acorn is parsing. This is necessary * to correct the "value" property of some tokens. * @constructor */ function TokenTranslator(acornTokTypes, code) { // token types this._acornTokTypes = acornTokTypes; // token buffer for templates this._tokens = []; // track the last curly brace this._curlyBrace = null; // the source code this._code = code; } TokenTranslator.prototype = { constructor: TokenTranslator, /** * Translates a single Esprima token to a single Acorn token. This may be * inaccurate due to how templates are handled differently in Esprima and * Acorn, but should be accurate for all other tokens. * @param {AcornToken} token The Acorn token to translate. * @param {Object} extra Espree extra object. * @returns {EsprimaToken} The Esprima version of the token. */ translate: function(token, extra) { var type = token.type, tt = this._acornTokTypes; if (type === tt.name) { token.type = Token.Identifier; // TODO: See if this is an Acorn bug if (token.value === "static") { token.type = Token.Keyword; } if (extra.ecmaVersion > 5 && (token.value === "yield" || token.value === "let")) { token.type = Token.Keyword; } } else if (type === tt.semi || type === tt.comma || type === tt.parenL || type === tt.parenR || type === tt.braceL || type === tt.braceR || type === tt.dot || type === tt.bracketL || type === tt.colon || type === tt.question || type === tt.bracketR || type === tt.ellipsis || type === tt.arrow || type === tt.jsxTagStart || type === tt.incDec || type === tt.starstar || type === tt.jsxTagEnd || type === tt.prefix || (type.binop && !type.keyword) || type.isAssign) { token.type = Token.Punctuator; token.value = this._code.slice(token.start, token.end); } else if (type === tt.jsxName) { token.type = Token.JSXIdentifier; } else if (type.label === "jsxText" || type === tt.jsxAttrValueToken) { token.type = Token.JSXText; } else if (type.keyword) { if (type.keyword === "true" || type.keyword === "false") { token.type = Token.Boolean; } else if (type.keyword === "null") { token.type = Token.Null; } else { token.type = Token.Keyword; } } else if (type === tt.num) { token.type = Token.Numeric; token.value = this._code.slice(token.start, token.end); } else if (type === tt.string) { if (extra.jsxAttrValueToken) { extra.jsxAttrValueToken = false; token.type = Token.JSXText; } else { token.type = Token.String; } token.value = this._code.slice(token.start, token.end); } else if (type === tt.regexp) { token.type = Token.RegularExpression; var value = token.value; token.regex = { flags: value.flags, pattern: value.pattern }; token.value = "/" + value.pattern + "/" + value.flags; } return token; }, /** * Function to call during Acorn's onToken handler. * @param {AcornToken} token The Acorn token. * @param {Object} extra The Espree extra object. * @returns {void} */ onToken: function(token, extra) { var that = this, tt = this._acornTokTypes, tokens = extra.tokens, templateTokens = this._tokens; /** * Flushes the buffered template tokens and resets the template * tracking. * @returns {void} * @private */ function translateTemplateTokens() { tokens.push(convertTemplatePart(that._tokens, that._code)); that._tokens = []; } if (token.type === tt.eof) { // might be one last curlyBrace if (this._curlyBrace) { tokens.push(this.translate(this._curlyBrace, extra)); } return; } if (token.type === tt.backQuote) { // if there's already a curly, it's not part of the template if (this._curlyBrace) { tokens.push(this.translate(this._curlyBrace, extra)); this._curlyBrace = null; } templateTokens.push(token); // it's the end if (templateTokens.length > 1) { translateTemplateTokens(); } return; } else if (token.type === tt.dollarBraceL) { templateTokens.push(token); translateTemplateTokens(); return; } else if (token.type === tt.braceR) { // if there's already a curly, it's not part of the template if (this._curlyBrace) { tokens.push(this.translate(this._curlyBrace, extra)); } // store new curly for later this._curlyBrace = token; return; } else if (token.type === tt.template) { if (this._curlyBrace) { templateTokens.push(this._curlyBrace); this._curlyBrace = null; } templateTokens.push(token); return; } if (this._curlyBrace) { tokens.push(this.translate(this._curlyBrace, extra)); this._curlyBrace = null; } tokens.push(this.translate(token, extra)); } }; //------------------------------------------------------------------------------ // Public //------------------------------------------------------------------------------ module.exports = TokenTranslator;
JavaScript
0.999999
@@ -1599,17 +1599,16 @@ ken. -range +start = -%5B firs @@ -1622,17 +1622,37 @@ range%5B0%5D -, +;%0A token.end = lastTem @@ -1670,16 +1670,63 @@ range%5B1%5D +;%0A token.range = %5Btoken.start, token.end %5D;%0A %7D
afacc582841cd5e57e8bdced690e9e3f2703a515
Return null if a transaction hasn't been verified yet.
lib/transactionstore.js
lib/transactionstore.js
var assert = require('assert'); var sys = require('sys'); var TransactionStore = exports.TransactionStore = function (node) { events.EventEmitter.call(this); this.node = node; this.txIndex = {}; }; sys.inherits(TransactionStore, events.EventEmitter); /** * Add transaction to memory pool. * * Note that transaction verification is asynchronous, so for proper error * handling you need to provide a callback. * * @return Boolean Whether the transaction was new. */ TransactionStore.prototype.add = function (tx, callback) { var txHash = tx.getHash().toString('base64'); // Transaction is currently being verified, add callback to queue if (Array.isArray(this.txIndex[txHash])) { this.txIndex[txHash].push(callback); return false; } try { if (tx.isCoinBase()) throw new Error("Coinbase transactions are only allowed as part of a block"); if (!tx.isStandard()) throw new Error("Non-standard transactions are currently not accepted"); tx.verify((function (err) { var callbackQueue = this.txIndex[txHash]; if (err) { delete this.txIndex[txHash]; callbackQueue.forEach(function (cb) { cb(err); }); return; } // TODO: Check conflicts with other in-memory transactions this.txIndex[txHash] = tx; callbackQueue.forEach(function (cb) { cb(); }); this.emit("txNotify", { store: this, tx: tx }); }).bind(this)); this.txIndex[txHash] = [callback]; } catch (e) { callback(e); return true; } return true; }; TransactionStore.prototype.get = function (hash) { if (hash instanceof Buffer) { hash = hash.toString('base64'); } assert.equal(typeof hash, 'string'); return this.txIndex[hash]; }; /** * Handles a spend entering the block chain. * * If a transaction spend enters the block chain, we have to remove any * conflicting transactions from the memory pool. */ TransactionStore.prototype.handleSpend = function (e) { // TODO: Implement // 1. Find transaction depending on this output // If there is none, we're done, otherwise: // 2. Remove it from the pool // 3. Issue txCancel messages };
JavaScript
0
@@ -1645,16 +1645,77 @@ ing');%0A%0A +%09if (Array.isArray(this.txIndex%5Bhash%5D)) %7B%0A%09%09return null;%0A%09%7D%0A%0A %09return
5f16dd85542745fc6f4b3f6ae24493871ad971be
clean up SortableSet
lib/util/SortableSet.js
lib/util/SortableSet.js
"use strict"; module.exports = class SortableSet extends Set { constructor(initialIterable, defaultSort) { super(initialIterable); this._sortFn = defaultSort; this._lastActiveSortFn = null; this._isSorted = false; } /** * @param {any} value - value to add to set * @returns {SortableSet} - returns itself */ add(value) { this._lastActiveSortFn = null; this._isSorted = false; super.add(value); return this; } /** * @returns {void} */ clear() { this._lastActiveSortFn = null; this._isSorted = false; super.clear(); } /** * @param {Function} sortFn - function to sort the set * @returns {void} */ sortWith(sortFn) { if(this._isSorted && sortFn === this._lastActiveSortFn) { // already sorted - nothing to do return; } const sortedArray = Array.from(this).sort(sortFn); super.clear(); for(let i = 0; i < sortedArray.length; i += 1) { this.add(sortedArray[i]); } this._lastActiveSortFn = sortFn; this._isSorted = true; } /** * @returns {void} */ sort() { this.sortWith(this._sortFn); } };
JavaScript
0.000002
@@ -196,37 +196,11 @@ ll;%0A -%09%09this._isSorted = false;%0A %09%7D%0A + %0A%09/* @@ -346,34 +346,8 @@ ll;%0A -%09%09this._isSorted = false;%0A %09%09su @@ -385,129 +385,8 @@ %09%7D%0A%0A -%09/**%0A%09 * @returns %7Bvoid%7D%0A%09 */%0A%09clear() %7B%0A%09%09this._lastActiveSortFn = null;%0A%09%09this._isSorted = false;%0A%09%09super.clear();%0A%09%7D%0A%0A %09/** @@ -501,20 +501,21 @@ his. -_isSorted && +size === 0 %7C%7C sor @@ -755,16 +755,16 @@ %5D);%0A%09%09%7D%0A + %09%09this._ @@ -794,33 +794,8 @@ Fn;%0A -%09%09this._isSorted = true;%0A %09%7D%0A%0A
c298afe08aa38fbee990ef09e24bbb912b8d3c0c
rename to PonosErrorCat
lib/error.js
lib/error.js
'use strict'; var util = require('util'); var ErrorCat = require('error-cat'); var log = require('./logger'); /** * Custom ErrorCat error handler. * @class */ function PonosError () { ErrorCat.apply(this, arguments); } util.inherits(PonosError, ErrorCat); /** * Logs errors via default ponos logger. * @param {error} err PonosError to log. * @see error-cat */ PonosError.prototype.log = function (err) { log.error({ err: err }, err.message); }; /** * PonosError handling via error-cat. * @module ponos:error * @author Ryan Sandor Richards */ module.exports = new PonosError();
JavaScript
0.999998
@@ -176,16 +176,19 @@ nosError +Cat () %7B%0A @@ -246,16 +246,19 @@ nosError +Cat , ErrorC @@ -340,16 +340,19 @@ nosError +Cat to log. @@ -384,16 +384,19 @@ nosError +Cat .prototy @@ -478,24 +478,27 @@ * PonosError +Cat handling vi @@ -600,12 +600,15 @@ nosError +Cat ();%0A
19adac4676483a5b42aed2540099c93426598d60
Remove forgotten console.error (sorry)
lib/htmly.js
lib/htmly.js
var extend = require('extend') var concatStream = require('concat-stream') var createReadStream = require('fs').createReadStream var lrio = require('lrio') var transform = require('./transform.js') var processor = require('./processor.js') var chokidar = require('chokidar') var resolve = require('resolve').sync var remedy = require('./remedy') // htmly is a browserify transform and a browserify plugin var htmly = module.exports = module.exports = function (fileOrBrowserify, opts) { if (typeof (fileOrBrowserify) === 'string') { return require('./transform')(fileOrBrowserify, opts) } else { return require('./plugin')(fileOrBrowserify, opts) } } // Export api htmly.transform = transform htmly.processor = processor htmly.remedy = remedy /** * Add a global htmly pre-processor * * @param {Array/Function} procs * A processor function or an array of functions * @return {htmly} */ htmly.pre = function (procs) { if (!Array.isArray(procs)) procs = [procs] procs.forEach(function (proc) { if (typeof (proc) === 'string') { proc = require(resolve(proc, {basedir: process.cwd()})) } process.htmly.preProcessors.push(proc) }) return htmly } /** * Add a global htmly post-processor * * @param {Array/Function} procs * A processor function or an array of functions * @return {htmly} */ htmly.post = function (procs) { if (!Array.isArray(procs)) procs = [procs] procs.forEach(function (proc) { if (typeof (proc) === 'string') { proc = require(resolve(proc, {basedir: process.cwd()})) } process.htmly.postProcessors.push(proc) }) return htmly } /** * Add an automatic htmly live source reload on a http(s) server * * This must be used on the same process than the browserify bundler * * @param {http(s).Server} server * A node http / https server * * @param {[FSWatcher]} watcher * Optional: a EventEmitter watcher instance (same as chokidar.FSWatcher) * * @return {Function} * A change listener (take one argument: the filename that changed) * * With two static properties: * - watcher: the chokidar instance * - lrioServer: the lrio instance */ htmly.live = function (server, watcher) { if (typeof (server) === 'string') { server = require(resolve(server)) } watcher = watcher || (new chokidar.FSWatcher({persistent: true})) var watched = [] var listener = htmly.attachServer(server) watcher.on('change', listener) htmly.post(function (ctx, done) { // Chokidar mays watch a file many times (>=0.10) if (watched.indexOf(ctx.filename) === -1) { watched.push(ctx.filename) watcher.add(ctx.filename) } done(null, ctx) }) listener.watcher = watcher return listener } /** * Attach a htmly live-reload server to a given http-server * * This must be used on for development purpose only: Attaching a htmly * live-reload server add a live-reload client to generated sources. * * Exemple with chokidar: * * var chokidar = require('chokidar') * var htmly = require('htmly') * var server = require('http').createServer() * * if(process.env.NODE_ENV === 'development') { * var htmlyListener = htmly.attachServer(server) * chokidar.watch('./src').on('change', htmlyListener) * } * * @param {http(s).Server} server * A node http / https server * * @return {Function} * A change listener (take one argument: the filename that changed) * * With one static property: * - lrioServer: the lrio instance */ htmly.attachServer = function (server) { function change (filename) { var proc = processor(filename) if (!proc) return createReadStream(filename) .pipe(concatStream(function (source) { proc(source.toString(), function (err, result) { console.error(err) lrioServer.broadcast({type: 'change', uid: result.filename, src: result.src}) }) })) } // Attach server only once if (!server._htmlyChangeListener) { var lrioServer = lrio(server, 'htmly') process.htmly.livereload = true change.lrioServer = lrioServer server._htmlyChangeListener = change } return server._htmlyChangeListener } /** * Global config getter/setter * * - `minify`: Minify source * - `sourcemap`: Enable source-map * * @param {[Object]} * object to merge with global config * * @return {Object} current config */ htmly.config = function (config) { process.htmly.config = extend(process.htmly.config, config || {}) return process.htmly.config } /** * Reset htmly global configuration */ htmly.reset = function () { process.htmly = {} process.htmly.postProcessors = [] process.htmly.preProcessors = [] process.htmly.livereload = false process.htmly.config = { minify: false, sourcemap: true } } // Reset once if needed if (!process.htmly) { htmly.reset() }
JavaScript
0.000001
@@ -3858,37 +3858,8 @@ ) %7B%0A - console.error(err)%0A
7c7588219c020a7482f5498745b8eec159ddfe32
Add TODO about refactoring for greater reuse of RPC module
lib/index.js
lib/index.js
var _ = require('lodash'); var derbyServices = require('derby-services'); var DefaultCollection = require('./DefaultCollection'); var DefaultItem = require('./DefaultItem'); var rpc = require('./rpc'); // TODO: Split up into one separate file for the server and one for the client for faster loading and less useless code transmitted to the client? // See: https://github.com/derbyparty/derby-faq/tree/master/en#how-to-require-a-module-that-will-run-only-on-the-server-of-a-derby-application module.exports = function(derby) { var racer = derby; var Model = racer.Model; var options = { schemas: {}, formats: {}, validators: {}, skipNonExisting: true }; racer._models = {}; Model.INITS.push(function (model) { // Initiate racer-schema ASAP model is initiated as we then know no more models can be added racer.use(require('racer-schema'), options); }); derby.use(rpc.plugin); derby.use(derbyServices); /** * Adds model classes to Racer * * @param {Object} args * @param {String} args.name - the name/path to the collection on which to bind to * @param {Class} [args.Collection] - the model class to be used for the collection * @param {Class} [args.Item] - the model class to be used for each item in the collection * @param {Object} [args.schema] - a (model) schema for each item in the collection * @param {Object} [args.formats] - formats to be used for schema * @param {Object} [args.validators] - validators to be used for schema * @param {Array} [args.hooks] - a list of hooks to bind to Share. Note! Not yet implemented! */ racer.model = function (args) { if(!args || !args.name) throw new Error('Name/path of collection must be passed'); racer._models[args.name] = args; // Use racer-schema for underlying schema stuff // TODO: Possibly, do a transformation from a (imo) nicer format for schema stuff // TODO: Implement schema refs, basically not using racer-schema if(args.schema) options.schemas[args.name] = args.schema; if(args.formats) racer.util.mergeInto(options.formats, args.formats); if(args.validators) racer.util.mergeInto(options.validators, args.validators); // Look into how to do this best. if(args.hooks) throw new Error('Hooks are not yet implemented!'); }; // Overwrite scope, which is used by all other fns related to path // Preserve old scope fn for re-use internally Model.prototype._scope = Model.prototype.scope; Model.prototype.scope = function(path) { var segments = this.__splitPath(path); // No segments - no point in parsing further if(!segments.length) return this._scope(path); // Dereference to simplify checks (if refs are present) var dereferencedSegments = this._dereference(segments, true); var dereferenced = dereferencedSegments.join('.'); // Get Models var Model = racer._models[segments[0]]; var dereferencedModel = racer._models[dereferencedSegments[0]]; // Only allow collection level models straight up from non-dereferenced Models, // since otherwise we're either moving through a ref to a collection, which is just pointless (or is it?) // or we're moving through a refList on the refList level which doesn't point to the whole collection but only a subset of it - and in those scenarios we don't want a Collection Model to be returned // TODO: Revise assumption above, it seems that in some scenarios you'd want to create regular references to a whole collection like if you'd want to reference a certain global collection to a component's view model so that the component could render all of it (though, then it might be a special case of above where it is a "subset" that just happens to be all of the items of the original collection) if(Model && segments.length === 1 && Model.Collection) { // We are at a collection level, return Collection instance // TODO: Add support for refList collections? See above return this._createCollection(path, Model.Collection); } else if(dereferencedModel && dereferencedSegments.length === 2 && dereferencedModel.Item) { // We are at an item level, return Item instance return this._createItem(dereferenced, dereferencedModel.Item); } // Always fallback on original scope/regular Child Model return this._scope(path); }; /** * Helper fn for splitting a full path */ Model.prototype.__splitPath = function(path) { return (path && path.split('.')) || []; }; /** * Helper fn for creating a collection for a specific path */ Model.prototype._createCollection = function(path, constructor) { function Collection() {} constructor.prototype = rpc.add(this, path, constructor.prototype); Collection.prototype = _.assign(this._scope(path), DefaultCollection.prototype, constructor.prototype); return new Collection(); } Model.prototype._createItem = function(path, constructor) { function Item() {} constructor.prototype = rpc.add(this, path, constructor.prototype); Item.prototype = _.assign(this._scope(path), DefaultItem.prototype, constructor.prototype); return new Item(); } };
JavaScript
0
@@ -163,24 +163,89 @@ aultItem');%0A +// TODO: Move RPC into separate module for greater re-usability?%0A var rpc = re
8352f9765fa8c1a8dc759796212221701b82c1c2
remove extra semi colon
lib/index.js
lib/index.js
'use strict' import readCache from './read-cache' import serialize from './serialize' import memoryStore from './memory' import exclude from './exclude' function cache (config = {}) { config.store = config.store || memoryStore const key = config.key || cache.key config.maxAge = config.maxAge || 0 config.readCache = config.readCache || readCache config.serialize = config.serialize || serialize config.clearOnStale = config.clearOnStale !== undefined ? config.clearOnStale : true config.exclude = config.exclude || {} config.exclude.query = config.exclude.query || true config.exclude.paths = config.exclude.paths || [] config.exclude.filter = null if (config.log !== false) { config.log = typeof config.log === 'function' ? config.log : console.log.bind(console) } return (req, next, service) => { if (exclude(req, service, config.exclude)) { return null } const uuid = key(req) // clear cache if method different from GET. // We should exclude HEAD const method = req.method.toLowerCase() if (method === 'head') { return null } if (method !== 'get') { config.store.removeItem(uuid) return null } const f = () => { return next() .then(res => { const type = res.status / 100 | 0 // only cache 2xx response if (type !== 2) { return res } // exclude binary response from cache if (['arraybuffer', 'blob'].indexOf(res.responseType) >= -1) { return res; } return config.store.setItem(uuid, { expires: config.maxAge === 0 ? 0 : Date.now() + config.maxAge, data: config.serialize(req, res) }) }) } return config.store.getItem(uuid).then(value => { return config.readCache(req, config.log)(value) .catch(err => { // clean up cache if stale config.clearOnStale && err.reason === 'cache-stale' ? config.store.removeItem(uuid).then(f) : f() }) }) } } cache.readCache = readCache cache.serialize = serialize cache.key = function (req) { return req.url } export default cache
JavaScript
0.000085
@@ -1559,9 +1559,8 @@ res -; %0A
233fc26152ad8044a71d0524cac8c60cd2387d86
remove https keepalive for local testing
lib/index.js
lib/index.js
'use strict'; var Schema = require('./Schema'); var Model = require('./Model'); var https = require('https'); var debug = require('debug')('dynamoose'); function Dynamoose () { this.models = {}; this.defaults = { create: true, waitForActive: true, // Wait for table to be created waitForActiveTimeout: 180000, // 3 minutes prefix: '' }; // defaults } Dynamoose.prototype.model = function(name, schema, options) { options = options || {}; for(var key in this.defaults) { options[key] = (typeof options[key] === 'undefined') ? this.defaults[key] : options[key]; } name = options.prefix + name; debug('Looking up model %s', name); if(this.models[name]) { return this.models[name]; } if (!(schema instanceof Schema)) { schema = new Schema(schema, options); } var model = Model.compile(name, schema, options, this); this.models[name] = model; return model; }; /** * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor * * @method VirtualType * @api public */ Dynamoose.prototype.VirtualType = require('./VirtualType'); Dynamoose.prototype.AWS = require('aws-sdk'); Dynamoose.prototype.local = function (url) { this.endpointURL = url || 'http://localhost:8000'; debug('Setting DynamoDB to local (%s)', this.endpointURL); }; /** * Document client for executing nested scans */ Dynamoose.prototype.documentClient = function() { if (this.dynamoDocumentClient) { return this.dynamoDocumentClient; } if (this.endpointURL) { debug('Setting dynamodb document client to %s', this.endpointURL); this.AWS.config.update({ endpoint: this.endpointURL }); } else { debug('Getting default dynamodb document client'); } this.dynamoDocumentClient = new this.AWS.DynamoDB.DocumentClient(); return this.dynamoDocumentClient; }; Dynamoose.prototype.ddb = function () { if(this.dynamoDB) { return this.dynamoDB; } if(this.endpointURL) { debug('Setting DynamoDB to %s', this.endpointURL); this.dynamoDB = new this.AWS.DynamoDB({ endpoint: new this.AWS.Endpoint(this.endpointURL), httpOptions: { agent: new https.Agent({ rejectUnauthorized: true, keepAlive: true }) } }); } else { debug('Getting default DynamoDB'); this.dynamoDB = new this.AWS.DynamoDB({ httpOptions: { agent: new https.Agent({ rejectUnauthorized: true, keepAlive: true }) } }); } return this.dynamoDB; }; Dynamoose.prototype.setDefaults = function (options) { for(var key in this.defaults) { options[key] = (typeof options[key] === 'undefined') ? this.defaults[key] : options[key]; } this.defaults = options; }; Dynamoose.prototype.Schema = Schema; Dynamoose.prototype.Table = require('./Table'); Dynamoose.prototype.Dynamoose = Dynamoose; module.exports = new Dynamoose();
JavaScript
0
@@ -2099,144 +2099,8 @@ URL) -,%0A httpOptions: %7B%0A agent: new https.Agent(%7B%0A rejectUnauthorized: true,%0A keepAlive: true%0A %7D)%0A %7D %0A
bbc3e042ee0032b36b327ee9c337077e12e6b9f1
fix missing attr error
lib/utils/xml-stream.js
lib/utils/xml-stream.js
const _ = require('./under-dash'); const utils = require('./utils'); // constants const OPEN_ANGLE = '<'; const CLOSE_ANGLE = '>'; const OPEN_ANGLE_SLASH = '</'; const CLOSE_SLASH_ANGLE = '/>'; const EQUALS_QUOTE = '="'; const QUOTE = '"'; const SPACE = ' '; function pushAttribute(xml, name, value) { xml.push(SPACE); xml.push(name); xml.push(EQUALS_QUOTE); xml.push(utils.xmlEncode(value.toString())); xml.push(QUOTE); } function pushAttributes(xml, attributes) { if (attributes) { _.each(attributes, (value, name) => { if (value !== undefined) { pushAttribute(xml, name, value); } }); } } class XmlStream { constructor() { this._xml = []; this._stack = []; this._rollbacks = []; } get tos() { return this._stack.length ? this._stack[this._stack.length - 1] : undefined; } get cursor() { // handy way to track whether anything has been added return this._xml.length; } openXml(docAttributes) { const xml = this._xml; // <?xml version="1.0" encoding="UTF-8" standalone="yes"?> xml.push('<?xml'); pushAttributes(xml, docAttributes); xml.push('?>\n'); } openNode(name, attributes) { const parent = this.tos; const xml = this._xml; if (parent && this.open) { xml.push(CLOSE_ANGLE); } this._stack.push(name); // start streaming node xml.push(OPEN_ANGLE); xml.push(name); pushAttributes(xml, attributes); this.leaf = true; this.open = true; } addAttribute(name, value) { if (!this.open) { throw new Error('Cannot write attributes to node if it is not open'); } pushAttribute(this._xml, name, value); } addAttributes(attrs) { if (!this.open) { throw new Error('Cannot write attributes to node if it is not open'); } pushAttributes(this._xml, attrs); } writeText(text) { const xml = this._xml; if (this.open) { xml.push(CLOSE_ANGLE); this.open = false; } this.leaf = false; xml.push(utils.xmlEncode(text.toString())); } writeXml(xml) { if (this.open) { this._xml.push(CLOSE_ANGLE); this.open = false; } this.leaf = false; this._xml.push(xml); } closeNode() { const node = this._stack.pop(); const xml = this._xml; if (this.leaf) { xml.push(CLOSE_SLASH_ANGLE); } else { xml.push(OPEN_ANGLE_SLASH); xml.push(node); xml.push(CLOSE_ANGLE); } this.open = false; this.leaf = false; } leafNode(name, attributes, text) { this.openNode(name, attributes); if (text !== undefined) { // zeros need to be written this.writeText(text); } this.closeNode(); } closeAll() { while (this._stack.length) { this.closeNode(); } } addRollback() { this._rollbacks.push({ xml: this._xml.length, stack: this._stack.length, leaf: this.leaf, open: this.open, }); return this.cursor; } commit() { this._rollbacks.pop(); } rollback() { const r = this._rollbacks.pop(); if (this._xml.length > r.xml) { this._xml.splice(r.xml, this._xml.length - r.xml); } if (this._stack.length > r.stack) { this._stack.splice(r.stack, this._stack.length - r.stack); } this.leaf = r.leaf; this.open = r.open; } get xml() { this.closeAll(); return this._xml.join(''); } } XmlStream.StdDocAttributes = { version: '1.0', encoding: 'UTF-8', standalone: 'yes', }; module.exports = XmlStream;
JavaScript
0.000002
@@ -1625,32 +1625,65 @@ t open');%0A %7D%0A + if (value !== undefined) %7B%0A pushAttribut @@ -1709,16 +1709,22 @@ value);%0A + %7D%0A %7D%0A%0A a
bd34ed766cbf2e42325b8c181bd4e8ddd63847f3
Update style of textarea in Modal preview
lib/mcide.js
lib/mcide.js
'use babel'; import { CompositeDisposable } from 'atom'; const child_process = require('child_process'); const fs = require('fs'); const net = require('net'); const tls = require('tls'); const ooc = require('./onlyonecommand'); export default { subscriptions: null, config: { onlyOneCommand: { type: 'object', description: 'Settings for the "only one command" generator', properties: { coordinates: { type: 'object', description: 'Coordinates of the command structure', properties: { relative: { type: 'boolean', description: 'Should the command structure be generated relative to the command execution spot', default: true }, x: { type: 'integer', description: 'X coordinate', default: 5 }, y: { type: 'integer', description: 'Y coordinate', default: 5 }, z: { type: 'integer', description: 'Z coordinate', default: 5 } } }, dimensions: { type: 'object', description: 'Dimensions of the command structure', properties: { x: { type: 'integer', description: 'X coordinate', default: 5 }, z: { type: 'integer', description: 'Z coordinate', default: 5 } } } } }, previewMode: { type: 'string', description: 'Mode used to preview commands', default: 'modal', enum: [ "alert", "modal" ] }, indexFile: { type: 'string', description: 'Path to index php file (current for file which is open)', default: 'current' }, packageFolder: { type: 'string', description: 'Path to index package folder (no slash at the end!)', default: '~/.atom/packages' }, serverAddress: { type: 'string', description: 'Address of the McIDE server', default: '127.0.0.1' }, serverPort: { type: 'integer', description: 'Port of the McIDE server', default: 25563, minimum: 0, maximum: 65535 }, rejectUnauthorized: { type: 'boolean', description: '(Only when using ssl) Should unautherizes certificates be rejected', default: false }, data: { type: 'object', description: 'Data to the McIDE server', properties: { world: { type: 'string', description: 'Name (or UUID) of the minecraft world', default: 'world' }, password: { type: 'string', description: 'Password to connect to the minecraft McIDE server', default: '' } } } }, activate(state) { // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable this.subscriptions = new CompositeDisposable(); // Register command that toggles this view this.subscriptions.add(atom.commands.add('atom-workspace', { 'mcide:upload_secure': () => this.uploadSecure(), 'mcide:upload_insecure': () => this.uploadInsecure(), 'mcide:set_index_file': () => this.setIndexFile(), 'mcide:show_preview': () => this.showPreview(), 'mcide:generate_ooc': () => ooc.toOnlyOneCommand(this.getCommands()) })); }, deactivate() { this.subscriptions.dispose(); }, serialize() { return {}; }, showPreview() { switch (atom.config.get('mcide.previewMode')) { case "modal": const div = document.createElement("div"); const textarea = document.createElement("textarea"); textarea.textContent = this.getCommands(); textarea.style.width = "100%"; textarea.rows = 20; textarea.readOnly = true; const hr = document.createElement("hr"); const button = document.createElement("button"); button.textContent = "Close Modal"; button.className = "btn btn-info"; button.onclick = () => { atom.workspace.getModalPanels().forEach((modal) => { modal.destroy(); }); }; div.appendChild(textarea); div.appendChild(hr); div.appendChild(button); atom.workspace.addModalPanel({ item: div }); break; case "alert": atom.notifications.addInfo("Preview", { detail: this.getCommands(), dismissable: true }); break; } }, /** * Uploads the outputs of index file to the McIDE server */ uploadSecure() { let data = atom.config.get('mcide.data'); let commands = this.getCommands(); data.commands = commands; const client = tls.connect({ host: atom.config.get('mcide.serverAddress'), port: atom.config.get('mcide.serverPort'), rejectUnauthorized: atom.config.get('mcide.rejectUnauthorized') }, () => { client.end(JSON.stringify(data) + "\n\n------***endofsequence***-------"); atom.notifications.addInfo("Sent commands", { detail: commands, dismissable: true }); }); }, uploadInsecure() { let data = atom.config.get('mcide.data'); let commands = this.getCommands(); data.commands = commands; const client = net.connect({ host: atom.config.get('mcide.serverAddress'), port: atom.config.get('mcide.serverPort') }, () => { client.end(JSON.stringify(data) + "\n\n------***endofsequence***-------"); atom.notifications.addInfo("Sent commands", { detail: commands, dismissable: true }); }); }, /** * Sets the index file (in config) to the currently open file */ setIndexFile() { currentFile = this.getCurrentFile(); if (currentFile === "") { atom.notifications.addWarning("Path of current File not available", { detail: "Could not set the index file", dismissable: true }); } else { atom.config.set('mcide.indexFile', currentFile); } }, /** * Gets the index file path * * @return {string} path */ getIndexFile() { let indexFile = atom.config.get('mcide.indexFile'); if (indexFile == "current") { indexFile = this.getCurrentFile(); } return indexFile; }, /** * Checks if a path points to a file * * @param {string} path file path * @return {boolean} path points to file */ isFile(path) { const stat = fs.statSync(path); return stat.isFile(); }, /** * Returns the currently open file * * @return {string|null} Path to current file or null */ getCurrentFile() { return atom.workspace.getActiveTextEditor().getPath(); }, /** * Returs the commands generated using php * * @return {string} output of php */ getCommands() { const indexFile = this.getIndexFile(); if (!this.isFile(indexFile)) { throw indexFile + " is not a File!"; } const php = child_process.spawnSync('php', [indexFile]); const commands = php.stdout.toString('utf8'); const error = php.stderr.toString('utf8'); if (error) { throw error; } return commands; } };
JavaScript
0
@@ -3909,15 +3909,98 @@ rea. -style.w +className = %22form-control%22;%0A textarea.style.width = %22100%25%22;%0A textarea.style.maxW idth
22344041caccd5a1843015619cb7e4add6494658
set monday as the first day of the week
src/domain/calendar.js
src/domain/calendar.js
export default class Calendar { constructor(firstWeekDay = 0){ this.firstWeekDay = firstWeekDay; } _weekStartDate(date) { var startDate = new Date(date.getTime()); while (startDate.getDay() !== this.firstWeekDay) { startDate.setDate(startDate.getDate() - 1); } return startDate; } _monthDates(year, month, dayFormatter, weekFormatter) { if ((typeof year !== "number") || (year < 1970)) { throw new Error('year must be a number >= 1970'); }; if ((typeof month !== "number") || (month < 0) || (month > 11)) { throw new Error('month must be a number (Jan is 0)'); }; var weeks = [], week = [], i = 0, date = this._weekStartDate(new Date(year, month, 1)); do { for (i=0; i<7; i++) { week.push(dayFormatter ? dayFormatter(date) : date); date = new Date(date.getTime()); date.setDate(date.getDate() + 1); } weeks.push(weekFormatter ? weekFormatter(week) : week); week = []; } while ((date.getMonth()<=month) && (date.getFullYear()===year)); return weeks; } monthDays(year, month) { var getDayOrZero = function getDayOrZero(date) { return date.getMonth() === month ? date.getDate() : 0; }; return this._monthDates(year, month, getDayOrZero); } }; Calendar.monthNames = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; Calendar.dayNames = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ];
JavaScript
0.000907
@@ -54,17 +54,17 @@ ekDay = -0 +1 )%7B%0A t
6d1d4f9fb0036281353b1e27e04df497507fb65c
fix comment
lib/pi-io.js
lib/pi-io.js
'use strict'; var LinuxIO = require('linux-io'), pigpio = require('pigpio'), Gpio = pigpio.Gpio, util = require('util'), pins = require('./pins'), controller = require('./controller'), RangeFinder = require('./range-finder'); function PiIO() { LinuxIO.call(this, { name: 'Pi-IO', pins: pins, defaultI2cBus: 1, defaultLed: 'LED0' }); pigpio.initialize(); // After explicitly calling pigpio.initialize wait 50ms for pigpio to become // ready for usage. This delay is necessary for alerts to function correctly. // See https://github.com/joan2937/pigpio/issues/127 // Update: This issue was fixed with pigpio V63 in May 2017. When Raspbian is // updated to include pigpio V63 the timeout here can be removed. setTimeout(function () { this.emit('connect'); this.emit('ready'); }.bind(this), 100); } util.inherits(PiIO, LinuxIO); PiIO.prototype._pinPigpioMode = function(pinData, pigpioMode) { if (!pinData.gpio) { pinData.gpio = new Gpio(pinData.gpioNo, { mode: pigpioMode, pullUpDown : Gpio.PUD_OFF }); } else { pinData.gpio.mode(pigpioMode); } }; PiIO.prototype._pinModeInput = function(pinData) { this._pinPigpioMode(pinData, Gpio.INPUT); }; PiIO.prototype._pinModeOutput = function(pinData) { this._pinPigpioMode(pinData, Gpio.OUTPUT); }; PiIO.prototype._pinModePwm = function(pinData) { this._pinPigpioMode(pinData, Gpio.OUTPUT); }; PiIO.prototype._pinModeServo = function(pinData) { this._pinPigpioMode(pinData, Gpio.OUTPUT); pinData.servoConfig = { min: 500, max: 2500 }; }; PiIO.prototype._enablePullUpResistor = function(pinData) { pinData.gpio.pullUpDown(Gpio.PUD_UP); }; PiIO.prototype._enablePullDownResistor = function(pinData) { pinData.gpio.pullUpDown(Gpio.PUD_DOWN); }; PiIO.prototype._digitalReadSync = function(pinData) { return pinData.gpio.digitalRead(); }; PiIO.prototype._digitalWriteSync = function(pinData, value) { pinData.gpio.digitalWrite(value); }; PiIO.prototype._pwmWriteSync = function(pinData, value) { pinData.gpio.pwmWrite(value >> 0); }; PiIO.prototype._servoWriteSync = function(pinData, value) { var min = pinData.servoConfig.min, max = pinData.servoConfig.max; pinData.gpio.servoWrite((min + (value / 180) * (max - min)) >> 0); }; PiIO.prototype._pingRead = function(pinData, callback) { if (!pinData.custom.rangeFinder) { pinData.custom.rangeFinder = new RangeFinder(pinData.gpioNo); } pinData.custom.rangeFinder.pingRead(callback); }; PiIO.HCSR04 = controller.HCSR04; module.exports = PiIO;
JavaScript
0
@@ -438,17 +438,18 @@ ze wait -5 +10 0ms for
a7732df5577a69a49aa04f055df232784faa5cde
fix typo breaking `getClients` method
lib/websocket-server.js
lib/websocket-server.js
module.exports = (function() { var each = require('foreach'); var extend = require('extend'); function WebSocketServer() { this._clients = { }; } extend(WebSocketServer.prototype, { _randomAsync: function(client, fn) { var self = this; window.setTimeout(function() { var clientInstance = self._getClientEntry(client); if(clientInstance) { fn.call(self, clientInstance); } else { throw 'client not connected to the server'; } }, Math.floor(Math.random() * 50)); }, // search for the client entry for passed WebSocket mock instance _getClientEntry: function(client) { var res; each(this._clients, function(c) { if(c.mock === client) { res = c; } }, this); return res; }, // sends message to the client send: function(client, data) { this._randomAsync(client, function (clientInstance) { clientInstance.mock.dispatchEvent(new CustomEvent('message', { 'data': data })); }); }, // sends error to the client error: function(client) { this._randomAsync(client, function (clientInstance) { clientInstance.mock._connection = null; clientInstance.mock.readyState = clientInstance.mock.CLOSED; clientInstance.mock.dispatchEvent(new CustomEvent('error')); delete this._clients[clientInstance.id]; }); }, // sends disconnect signal to the client disconnect: function(client, reason) { this._randomAsync(client, function (clientInstance) { clientInstance.mock._connection = null; clientInstance.mock.readyState = clientInstance.mock.CLOSED; clientInstance.mock.dispatchEvent(new CustomEvent('close', { reason: reason })); delete this._clients[clientInstance.id]; }); }, getMessages: function(client) { var clientInstance = this._getClientEntry(client); if(clientInstance) { return clientInstance.messages; } else { throw 'client not connected to the server'; } }, getClients: function() { return Object.keys(this._clients).map(function(clientId) { return this._clientId[clientId]; }, this); }, // register the new client and returns deregistration and send functions connect: function(webSocketMock) { var clientId = Math.floor(Math.random() * 10e8).toString(36) + Date.now().toString(36) + Math.floor(Math.random() * 10e8).toString(36); this._clients[clientId] = { id: clientId, mock: webSocketMock, messages: [ ] }; var server = this; return { disconnect: function() { if(server._clients[clientId]) { delete server._clients[clientId]; } else { throw 'client not connected to the server'; } }, send: function(message) { if(server._clients[clientId]) { server._clients[clientId].messages.push(message); } else { throw 'client not connected to the server'; } } }; } }); return new WebSocketServer(); })();
JavaScript
0.000006
@@ -2591,18 +2591,17 @@ ._client -Id +s %5BclientI
8873b7e28e83f9adbf6c3a28ec639c9151a838ae
Fix jshint error
test/lib/test-selection.js
test/lib/test-selection.js
var Selection = require('../../lib/selection'); var Range = Selection.Range; var TextOperation = require('../../lib/text-operation'); exports.testCreateCursor = function (test) { test.ok(Selection.createCursor(5).equals(new Selection([new Range(5, 5)]))); test.done(); }; exports.testFromJSON = function (test) { var selection = Selection.fromJSON({ ranges: [{ anchor: 3, head: 5 }, { anchor: 11, head: 23 }] }); test.ok(selection instanceof Selection); test.strictEqual(selection.ranges.length, 2); test.ok(selection.ranges[0].equals(new Range(3, 5))); test.ok(selection.ranges[1].equals(new Range(11, 23))); test.done(); }; exports.testSomethingSelected = function (test) { var selection = new Selection([new Range(7, 7), new Range(10,10)]); test.ok(!selection.somethingSelected()); selection = new Selection([new Range(7, 10)]); test.ok(selection.somethingSelected()); test.done(); }; exports.testTransform = function (test) { var selection = new Selection([new Range(3, 7), new Range(19, 21)]); test.ok(selection .transform(new TextOperation().retain(3).insert('lorem')['delete'](2).retain(42)) .equals(new Selection([new Range(8, 10), new Range(22,24)]))); test.ok(selection .transform(new TextOperation()['delete'](45)) .equals(new Selection([new Range(0,0), new Range(0,0)]))); test.done(); }; exports.testCompose = function (test) { var a = new Selection([new Range(3, 7)]); var b = Selection.createCursor(4); test.strictEqual(a.compose(b), b); test.done(); };
JavaScript
0.000006
@@ -1,12 +1,28 @@ +(function () %7B%0A%0A var Selectio @@ -1520,28 +1520,36 @@ se(b), b);%0A test.done();%0A%7D; +%0A%0A%7D)();%0A
323bd333884f330b0a22ba0a73d60b52375aaeef
add specs for custom projection
test/map/ProjectionSpec.js
test/map/ProjectionSpec.js
describe('#Projection', function () { var container; var map; var center = new maptalks.Coordinate(118.846825, 32.046534); beforeEach(function () { container = document.createElement('div'); container.style.width = '800px'; container.style.height = '600px'; document.body.appendChild(container); var option = { zoomAnimation:false, zoom: 17, center: center }; map = new maptalks.Map(container, option); }); afterEach(function () { map.remove(); REMOVE_CONTAINER(container); }); describe('is default projection', function () { it('default projection is EPSG:3857', function () { var projection = map.getProjection(); expect(projection.code).to.be.eql('EPSG:3857'); }); }); describe('change to EPSG:4326', function () { it('change to EPSG:4326', function () { map.setView({ projection:'EPSG:4326' }); expect(map.getProjection().code).to.be.eql('EPSG:4326'); expect(map.getCenter()).to.closeTo(center); }); it('change center before changing view', function () { var newCenter = new maptalks.Coordinate(100, 0); map.setCenter(newCenter); map.setView({ projection:'EPSG:4326' }); expect(map.getProjection().code).to.be.eql('EPSG:4326'); expect(map.getCenter()).to.closeTo(newCenter); }); }); describe('change to IDENTITY', function () { it('change to IDENTITY', function () { map.setView({ projection:'IDENTITY', resolutions : [0, 10, 20], fullExtent:{ 'top':0, 'left':0, 'bottom':1000000, 'right':1000000 } }); expect(map.getProjection().code).to.be.eql('IDENTITY'); expect(map.getCenter()).to.closeTo(center); expect(map.computeLength([0, 10], [0, 20])).to.be.eql(10); var circle = new maptalks.Circle([10, 10], 1); expect(map.computeGeometryArea(circle)).to.be.eql(Math.PI); var polygon = new maptalks.Polygon([ [0, 0], [0, 10], [10, 10], [10, 0] ]); expect(map.computeGeometryArea(polygon)).to.be.eql(100); expect(map.locate([0, 0], 10, 10)).to.be.eql(new maptalks.Coordinate(10, 10)); }); }); describe('change to Baidu', function () { it('change to baidu', function () { map.setView({ projection:'baidu' }); expect(map.getProjection().code).to.be.eql('BAIDU'); expect(map.getCenter()).to.closeTo(center); }); }); });
JavaScript
0
@@ -603,32 +603,1133 @@ iner);%0A %7D);%0A%0A + it('customize projection', function () %7B%0A var custom = %7B%0A project : function (c) %7B%0A return c.add(1, 1);%0A %7D,%0A%0A unproject : function (c) %7B%0A return c.sub(1, 1);%0A %7D%0A %7D;%0A%0A map.setView(%7B%0A 'projection': custom,%0A 'resolutions': (function () %7B%0A var resolutions = %5B%5D;%0A for (var i = 0; i %3C 10; i++) %7B%0A resolutions%5Bi%5D = 4 / Math.pow(2, i);%0A %7D%0A return resolutions;%0A %7D)(),%0A 'fullExtent': %7B%0A 'top' : 100000,%0A 'left' : 0,%0A 'right' : 100000,%0A 'bottom' : 0%0A %7D%0A %7D);%0A%0A var projection = map.getProjection();%0A var coords = %5B%0A new maptalks.Coordinate(0, 0),%0A new maptalks.Coordinate(1, 1)%0A %5D;%0A var expected = %5B%5B1, 1%5D, %5B2, 2%5D%5D;%0A var actual = maptalks.Coordinate.toNumberArrays(projection.projectCoords(coords));%0A expect(actual).to.be.eql(expected);%0A %7D);%0A%0A describe('is @@ -1756,32 +1756,32 @@ , function () %7B%0A - it('defa @@ -1930,24 +1930,24 @@ PSG:3857');%0A + %7D);%0A @@ -1942,25 +1942,24 @@ %7D);%0A -%0A %7D);%0A%0A
85fb324791c671729c9852e9befc2c466857cb5b
Refactor and move some functions to utils
lib/utils.js
lib/utils.js
var spark = require('textspark'); var generateMetricParams = function(namespace, metric, unit, instance_id, dimension, period) { var endDate = new Date(); var startDate = new Date(endDate); var durationMinutes = 120; return { EndTime: endDate, MetricName: metric, Namespace: 'AWS/' + namespace, Period: period, StartTime: new Date(startDate.setMinutes(endDate.getMinutes() - durationMinutes)), Statistics: [ 'Average' ], Dimensions: [{Name: dimension, Value: instance_id}], Unit: unit }; }; module.exports = { displayMetric: function(aws, bot, channel, namespace, metric, unit, instance_id, dimension, period){ var params = generateMetricParams(namespace, metric, unit, instance_id, dimension, period); aws.getMetricStatistics(params, function(err, data) { if (err){ console.log(err); } else{ var datapoints = data['Datapoints'] if(datapoints && datapoints.length > 0){ datapoints.sort(function(x, y){ return x.Timestamp - y.Timestamp; }) var processed_data = []; var total = 0; var max = 0; datapoints.forEach(function (val, index, array) { processed_data.push(Number(val['Average']).toFixed(2)); total = total + val['Average']; if(val['Average'] > max){ max = val['Average']; } }); message = "*" + metric + "*: " + spark(processed_data) + " [*AVG*: " + (total/processed_data.length).toFixed(2) + " " + unit + ", *MAX*: " + max.toFixed(2) + " " + unit + "]"; bot.postMessage(channel, message, {as_user: true}); } else{ bot.postMessage(channel, "Id '" + instance_id + "' not found", {as_user: true, mrkdwn: true}); } } }); } };
JavaScript
0
@@ -604,16 +604,171 @@ rts = %7B%0A + bold: function(message)%7B%0A return '*' + message + '*';%0A %7D,%0A makeMention: function(userId) %7B%0A return '%3C@' + userId + '%3E';%0A %7D,%0A disp
c2116573c2d6839bdeb29e77f973f70b979b3425
Extend the max path length
lifeforce.js
lifeforce.js
/** * Set up imports that are required at this level for the application */ const restify = require("restify"); const corsMiddleware = require("restify-cors-middleware"); const fs = require("fs"); const os = require("os"); const path = require("path"); /** * Set up imports from local files */ const log = require("./utils/logger.js"); const logName = "Lifeforce"; // Set the app name and some other helpful variables const tempdir = os.tmpdir(); const pluginpath = "./plugins/"; // This variable will contain settings and api keys that are not public log.info("Loading settings from config.json...", logName); const settings = require("./config.json"); log.info("loading enabled list from enabled.json", logName); const enabledPlugins = require("./enabled.json"); log.info("Creating Restify Server...", logName); const server = restify.createServer({ name: "api.repkam09.com", version: "1.1.0", maxParamLength: 1000 }); const cors = corsMiddleware({ origins: [ "https://repkam09.com", "http://localhost:8080", "http://localhost:8000", "http://localhost", "https://demo.kaspe.net", "http://localhost:3000" ], allowHeaders: ["cache-control", "repka-repcast-token", "repka-verify"] }); server.pre(cors.preflight); server.use(cors.actual); server.use(restify.plugins.authorizationParser()); server.use( restify.plugins.bodyParser({ mapParams: true, mapFiles: true, overrideParams: true, keepExtensions: true, uploadDir: tempdir, multiples: true, hash: "md5" }) ); /** * Quick function to log incoming requests */ server.pre(function logging(req, res, next) { let clientip = "unknown"; if (req.headers["x-forwarded-for"]) { clientip = req.headers["x-forwarded-for"]; } else if (req.connection.remoteAddress) { clientip = req.connection.remoteAddress; } const user = { method: req.method, endpoint: req.url, ip: clientip }; log.info(">>> " + JSON.stringify(user) + " <<<", logName); return next(); }); const endpoints = []; server.updateAbout = (entry) => { endpoints.push(entry); } server.getAbout = () => { return endpoints; } // Go out and check the plugins list for endpoints to listen on const pluginList = []; fs.readdir(pluginpath, (err, files) => { files.forEach(file => { fs.stat(pluginpath + "/" + file, (err, stats) => { if (!stats.isDirectory()) { let type = path.extname(file); if (type === ".js") { // Load the plugin and check if it is enabled const plugin = require(pluginpath + "/" + file); let status = enabledPlugins[plugin.name]; if (!status) { log.debug( "Skipping " + plugin.name + " plugin because it does not have an entry in config", logName ); } else { if (status && status.enabled) { // Call the plugins start method to attach the various get/post/etc let temp = new plugin(server, log, plugin.name); // Attach the handlers to restify temp.addHandlers(); // Add this plugin to the list of plugins pluginList.push(temp); } else { log.debug( "Skipping " + plugin.name + " plugin because it is disabled", logName ); } } } } }); }); }); // Startup the server log.info("Starting Restify Server...", logName); server.listen(16001, () => { log.info(server.name + " listening at " + server.url, logName); });
JavaScript
0.925573
@@ -924,12 +924,12 @@ th: -1000 +2048 %0A%7D);
c16841c1a591bdd7376b75d7cf4d25ef48c09464
Use PresetManager.populateFromPairs.
src/gemooy-launcher.js
src/gemooy-launcher.js
function launch(prefix, container, config) { if (typeof container === 'string') { container = document.getElementById(container); } config = config || {}; function loadThese(deps, callback) { var loaded = 0; for (var i = 0; i < deps.length; i++) { var elem = document.createElement('script'); elem.src = prefix + deps[i]; elem.onload = function() { if (++loaded < deps.length) return; callback(); } document.body.appendChild(elem); } } loadThese([ "yoob/element-factory.js", "yoob/controller.js", "yoob/playfield.js", "yoob/playfield-canvas-view.js", "yoob/cursor.js", "yoob/preset-manager.js", "yoob/source-manager.js" ], function() { loadThese(["gemooy.js"], function() { var controlPanel = yoob.makeDiv(container); var subPanel = yoob.makeDiv(container); var selectSource = yoob.makeSelect(subPanel, 'example source:', []); var display = yoob.makeDiv(container); display.id = 'canvas_viewport'; var canvas = yoob.makeCanvas(display, 400, 400); var editor = yoob.makeTextArea(container, 40, 25); var v = (new yoob.PlayfieldCanvasView()).init({ canvas: canvas }); v.setCellDimensions(undefined, 20); var c = (new GemooyController()).init({ panelContainer: controlPanel, view: v }); var sourceManager = (new yoob.SourceManager()).init({ panelContainer: controlPanel, editor: editor, hideDuringEdit: [display], disableDuringEdit: [c.panel], storageKey: 'gemooy.js', onDone: function() { c.performReset(this.getEditorText()); } }); var presetManager = (new yoob.PresetManager()).init({ selectElem: selectSource }); function makeCallback(sourceText) { return function(id) { sourceManager.loadSource(sourceText); } } for (var i = 0; i < examplePrograms.length; i++) { presetManager.add(examplePrograms[i][0], makeCallback(examplePrograms[i][1])); } presetManager.select('toggle-column.gemooy'); }); }); }
JavaScript
0
@@ -1830,299 +1830,59 @@ %7D) -;%0A function makeCallback(sourceText) %7B%0A return function(id) %7B%0A sourceManager.loadSource(sourceText);%0A %7D%0A %7D%0A for (var i = 0; i %3C examplePrograms.length; i++) %7B%0A presetManager.add(examplePrograms%5Bi%5D%5B0%5D, makeCallback(examplePrograms%5Bi%5D%5B1%5D));%0A %7D +.populateFromPairs(sourceManager, examplePrograms); %0A
5ceac54b1adec1149c10aef27853bb1db82dbeef
Remove .only().
test/unit/api/component.js
test/unit/api/component.js
import { Component, define } from '../../../src'; import { classStaticsInheritance } from '../../lib/support'; import createSymbol from '../../../src/util/create-symbol'; describe('api/Component', () => { if (!classStaticsInheritance()) { return; } describe('property getters', () => { it('observedAttributes', () => { class Test extends Component { static get observedAttributes() { return ['test']; } }; expect(Test.observedAttributes).to.deep.equal(['test']); }); it('props', () => { class Test extends Component { static get props() { return { test: { attribute: true } }; } }; expect(Test.props).to.deep.equal({ test: { attribute: true } }); }); }); describe('property initialisers', () => { it('observedAttributes', () => { class Test extends Component { static observedAttributes = ['test']; }; expect(Test.observedAttributes).to.deep.equal(['test']); }); it('props', () => { class Test extends Component { static props = { test: { attribute: true } }; }; expect(Test.props).to.deep.equal({ test: { attribute: true } }); }); }); describe('updated function', () => { it.only('should return true if a prop changes', () => { const initialValue = 'hello world!' class Test extends Component { static props = { test: { attribute: true, initial: initialValue } }; }; define('test-updated-function', Test); const instance = document.createElement('test-updated-function'); expect(instance.test).to.equal(initialValue); instance.test = 'Hello world!'; const hasChange = Component.updated(instance, { test: initialValue}); expect(hasChange).to.be.true; }); it('should return true if a Symbol() prop has changed', () => { const initialValue = 'hello world!' const testSymbol = createSymbol('test'); class Test extends Component { static props = { [testSymbol]: { initial: initialValue } }; }; define('test-updated-function-2', Test); const instance = document.createElement('test-updated-function-2'); expect(instance[testSymbol]).to.equal(initialValue); instance[testSymbol] = 'Hello world!'; const hasChange = Component.updated(instance, { [testSymbol]: initialValue}); expect(hasChange).to.be.true; }); }); });
JavaScript
0.000392
@@ -1340,13 +1340,8 @@ it -.only ('sh
552bc677d9020e02c0a4f8a1aa8eeb21448d6e99
fix prop type again
src/components/Entry.js
src/components/Entry.js
import React from 'react'; import { Paper } from 'material-ui'; import _ from 'underscore'; const Entry = React.createClass({ propTypes: { entry: React.PropTypes.shape({ title: React.PropTypes.string.isRequired, url: React.PropTypes.string.isRequired, authors: React.PropTypes.string.isRequired, type: React.PropTypes.oneOf(['story', 'bug', 'chore', 'pr']), estimate: React.PropTypes.number.isRequired }).isRequired }, render() { const styles = { content: { padding: 5 }, link: { fontSize: 12 }, authors: { fontSize: 10 } }; const { title, url, authors, type, estimate } = this.props.entry; return ( <Paper style={styles.content}> {_.isEmpty(type) ? null : <img src={require(`../img/${type}.png`)} alt={type} />} <div>{Array(estimate + 1).join('•')}</div> <a href={url} target='_new' style={styles.link}>{title}</a> <br /> <div style={styles.authors}>{authors}</div> </Paper> ); } }); export default Entry;
JavaScript
0
@@ -354,13 +354,15 @@ f(%5B' -story +feature ', '
369b534ead78de35b55182374893eb69441e0d22
Make `<Katex />` a pure component
src/components/Katex.js
src/components/Katex.js
/** * Simple KaTeX bindings, compatible with server-side rendering due to * doing everything synchronously. */ import PropTypes from 'prop-types'; import React, {Component} from 'react'; import {renderToString as katexSync} from 'katex'; import {dedentRaw} from '../dedent'; // Rendering context that detects whether `Katex` appears in the tree. const Context = React.createContext(() => {}); export default function katex(options) { options = { display: false, ...(options || {}), }; return function katexTag(template, ...args) { const tex = dedentRaw(template, ...args); return <Katex tex={tex} display={options.display} />; }; } const inlineCache = new Map(); const displayCache = new Map(); function cacheMap(display) { return display ? displayCache : inlineCache; } class Katex extends Component { static propTypes = { tex: PropTypes.string.isRequired, display: PropTypes.bool.isRequired, } render() { return <Context.Consumer> {(katexCallback) => { katexCallback(); if (typeof document !== 'undefined') { // Side-effect in render!? Hey, it works great ;-) ensureStylesLoaded(); } return this._render(); }} </Context.Consumer>; } _html() { const cache = cacheMap(this.props.display); const cachedResult = cache.get(this.props.tex); if (cachedResult != null) { return cachedResult; } const options = { displayMode: this.props.display, fleqn: true, }; const html = katexSync(this.props.tex, options); cache.set(this.props.tex, html); return html; } _render() { // We use `dangerouslySetInnerHTML`, which should be safe // because KaTeX is meant to be injection-safe [1] and also // because all the inputs are static text written by me. // // [1]: https://katex.org/docs/security.html return <span dangerouslySetInnerHTML={{__html: this._html()}} />; } } /** * Decorate a component to detect whether `<Katex />` is used in its render tree. * * Usage: assign the result of this call to `{component, usesKatex}`, * then render `component`, *then* call `usesKatex` to get a boolean. * Rendering `component` has a side-effect of (idempotently) mutating * the state read by the `usesKatex` callback. */ export function listenForKatex(component) { const box = {called: false}; const callback = () => void (box.called = true); const wrapped = <Context.Provider value={callback}>{component}</Context.Provider>; return {component: wrapped, usesKatex: () => box.called}; } let stylesLoaded = false; function ensureStylesLoaded() { if (stylesLoaded) { return; } for (const child of document.head.children) { if (child.tagName === 'STYLE' && child.dataset.katex != null) { stylesLoaded = true; return; } } const style = document.createElement('style'); style.dataset.katex = ''; style.textContent = require('katex/dist/katex.min.css'); document.head.appendChild(style); stylesLoaded = true; }
JavaScript
0.000016
@@ -159,16 +159,20 @@ React, %7B +Pure Componen @@ -850,16 +850,20 @@ extends +Pure Componen
e4d740c0f7ff99601272be36197cfd657e51290a
Implement optional for num range
src/components/Range.js
src/components/Range.js
import React from 'react'; import Select from 'react-select'; import masterdata from '../store/masterdata.js'; import _ from 'lodash'; import Nouislider from 'react-nouislider'; export default React.createClass({ getInitialState() { let sortedProp = _.sortBy(masterdata, this.props.propname).map(o => { return o[this.props.propname]; }); sortedProp = sortedProp.filter(function(o){ return typeof o !== "undefined"; }); this.min = sortedProp[0]; this.max = sortedProp[sortedProp.length - 1]; return { start: [this.min, this.max] }; }, componentWillMount() { }, componentDidMount() { }, rangeChangeHandler(start) { start = start.map(s => parseInt(s)); this.setState({start}); let component = this; let event = new CustomEvent('filterChange', { detail: { propName: component.props.propname, filterFunction: function(data) { return data.filter(function(d) { return d[component.props.propname] >= start[0] && d[component.props.propname] <= start[1]; }); } } }); document.dispatchEvent(event); }, render() { return ( <Nouislider range = { { min: this.min, max: this.max } } step = {1} start = {this.state.start} onChange = {this.rangeChangeHandler} tooltips /> ); } });
JavaScript
0.000001
@@ -490,32 +490,33 @@ %7D);%0A +%0A this @@ -591,24 +591,258 @@ ength - 1%5D;%0A +%0A let filterEventDetailsObj = this.filterEventDetails(%5Bthis.min, this.max%5D, !this.props.optional);%0A let event = new CustomEvent('filterChange', filterEventDetailsObj);%0A document.dispatchEvent(event);%0A%0A @@ -893,16 +893,63 @@ his.max%5D +,%0A disabled: this.props.optional %0A @@ -1229,47 +1229,300 @@ let -event = new CustomEvent('filterChange', +filterEventDetailsObj = this.filterEventDetails(start, true);%0A let event = new CustomEvent('filterChange', filterEventDetailsObj);%0A document.dispatchEvent(event);%0A %7D,%0A%0A filterEventDetails(val, enabled) %7B%0A let component = this;%0A return %7B%0A @@ -1602,16 +1602,54 @@ opname,%0A + enabled: enabled,%0A @@ -1816,21 +1816,19 @@ ame%5D %3E= -start +val %5B0%5D && d @@ -1857,21 +1857,19 @@ ame%5D %3C= -start +val %5B1%5D;%0A @@ -1950,117 +1950,936 @@ %7D -);%0A document.dispatchEvent(event);%0A %7D,%0A%0A render() %7B%0A return ( %3CNouislider +;%0A %7D,%0A%0A toggleFilter(e) %7B%0A this.setState(prevState =%3E %7B%0A prevState.disabled = !e.target.checked;%0A return prevState;%0A %7D);%0A let filterEventDetailsObj = this.filterEventDetails(this.state.start, e.target.checked);%0A let event = new CustomEvent('filterChange', filterEventDetailsObj);%0A document.dispatchEvent(event);%0A %7D,%0A%0A render() %7B%0A let filterSwitch = '';%0A if (this.props.optional) %7B%0A filterSwitch = %3Cinput type='checkbox' name='filterState' checked=%7B!this.state.disabled%7D onChange=%7Bthis.toggleFilter%7D /%3E%0A %7D%0A let style = %7Bdisplay: (this.state.disabled) ? 'none' : 'block'%7D;%0A return ( %0A %3Cdiv%3E%0A %7BfilterSwitch%7D%0A %3Cdiv style = %7Bstyle%7D%3E%0A %3CNouislider %0A ran @@ -2884,16 +2884,17 @@ ange = %7B +%7B %0A @@ -2906,14 +2906,8 @@ - %7B%0A @@ -2965,16 +2965,32 @@ + + max: thi @@ -3007,34 +3007,32 @@ -%7D%0A @@ -3024,33 +3024,46 @@ %7D -%0A +%7D%0A @@ -3081,32 +3081,44 @@ + + start = %7Bthis.st @@ -3144,16 +3144,28 @@ + + onChange @@ -3213,18 +3213,138 @@ -tooltips / + disabled=%7Bthis.state.disabled%7D%0A tooltips/%3E%0A %3C/div%3E%0A %3C/div %3E%0A
4e593d113f54abc387bc9bba3ef7a775904faec9
add constructor
src/compressor/index.js
src/compressor/index.js
'use strict'; var fs = require('fs'); var path = require('path'); var Fontmin = require('fontmin'); var utils = require('./utils'); var Adapter = require('../adapter'); // http://font-spider.org/css/style.css // var RE_SERVER = /^(\/|http\:|https\:)/i; var RE_SERVER = /^https?\:/i; var TEMP = '.FONT_SPIDER_TEMP'; var number = 0; function Compress(webFont, options) { options = new Adapter(options); return new Promise(function(resolve, reject) { if (webFont.length === 0) { resolve(webFont); return; } number++; var source; webFont.files.forEach(function(file) { if (RE_SERVER.test(file.source)) { throw new Error('does not support remote path "' + file + '"'); } if (file.format === 'truetype') { source = file.source; } }); // 必须有 TTF 字体 if (!source) { throw new Error('"' + webFont.family + '"' + ' did not find turetype fonts'); } this.source = source; this.webFont = webFont; this.options = options; this.dirname = path.dirname(source); this.extname = path.extname(source); this.basename = path.basename(source, this.extname); this.temp = path.join(this.dirname, TEMP + number); // 备份字体与恢复备份 if (options.backup) { this.backup(); } if (!fs.existsSync(this.source)) { throw new Error('"' + source + '" file not found'); } this.min(resolve, reject); }.bind(this)); } Compress.defaults = { backup: true }; Compress.prototype = { // 字体恢复与备份 backup: function() { var backupFile; var source = this.source; var dirname = this.dirname; var basename = this.basename; // version < 0.2.1 if (fs.existsSync(source + '.backup')) { backupFile = source + '.backup'; } else { backupFile = path.join(dirname, '.font-spider', basename); } if (fs.existsSync(backupFile)) { utils.cp(backupFile, source); } else { utils.cp(source, backupFile); } }, min: function(succeed, error) { var webFont = this.webFont; var source = this.source; var temp = this.temp; var that = this; var originalSize = fs.statSync(source).size; var fontmin = new Fontmin().src(source); if (webFont.chars) { fontmin.use(Fontmin.glyph({ text: webFont.chars })); } var types = { 'embedded-opentype': 'ttf2eot', 'woff': 'ttf2woff', 'woff2': 'ttf2woff2', 'svg': 'ttf2svg' }; Object.keys(types).forEach(function(index) { var key = types[index]; if (typeof Fontmin[key] === 'function') { fontmin.use(Fontmin[key]({ clone: true })); } }); fontmin.dest(temp); fontmin.run(function(errors /*, buffer*/ ) { if (errors) { that.clear(); error(errors); } else { // 从临时目录把压缩后的字体剪切出来 webFont.files.forEach(function(file) { var basename = path.basename(file.source); var tempFile = path.join(temp, basename); var out = file.source; utils.rename(tempFile, out); if (fs.existsSync(file.source)) { file.size = fs.statSync(file.source).size; } else { file.size = null; } }); that.clear(); // 添加新字段:记录原始文件大小 webFont.originalSize = originalSize; succeed(webFont); } }); }, clear: function() { utils.rmdir(this.temp); } }; /** * 压缩字体 * @param {Array<WebFont>} `WebFonts` 描述信息 @see ../spider/web-font.js * @param {Adapter} 选项 * @param {Function} 回调函数 * @return {Promise} */ module.exports = function(webFonts, adapter, callback) { adapter = new Adapter(adapter); if (!Array.isArray(webFonts)) { webFonts = [webFonts]; } webFonts = Promise.all(webFonts.map(function(webFont) { return new Compress(webFont, adapter); })); if (typeof callback === 'function') { webFonts.then(function(webFonts) { process.nextTick(function() { callback(null, webFonts); }); return webFonts; }).catch(function(errors) { process.nextTick(function() { callback(errors); }); return Promise.reject(errors); }); } return webFonts; };
JavaScript
0.000001
@@ -568,38 +568,36 @@ -number++;%0A%0A%0A var source +var source;%0A number++ ;%0A%0A%0A @@ -1684,16 +1684,42 @@ ype = %7B%0A + constructor: Compress, %0A%0A%0A /
9e23eb42720daba4c48d0b7381d3d8fcf3917a01
Add Filename Override
Generator.js
Generator.js
/** * Module dependencies */ var util = require('util'); var _ = require('lodash'); _.defaults = require('merge-defaults'); /** * sails-generate-humpback-view * * Usage: * `sails generate humpback-view` * * @description Generates a humpback-view * @help See http://links.sailsjs.org/docs/generators */ module.exports = { /** * `before()` is run before executing any of the `targets` * defined below. * * This is where we can validate user input, configure default * scope variables, get extra dependencies, and so on. * * @param {Object} scope * @param {Function} cb [callback] */ before: function (scope, cb) { // scope.args are the raw command line arguments. // // e.g. if someone runs: // $ sails generate humpback-view user find create update // then `scope.args` would be `['user', 'find', 'create', 'update']` if (!scope.args[0]) { return cb( new Error('Please provide a name for this humpback-view.') ); } // scope.rootPath is the base path for this generator // // e.g. if this generator specified the target: // './Foobar.md': { copy: 'Foobar.md' } // // And someone ran this generator from `/Users/dbowie/sailsStuff`, // then `/Users/dbowie/sailsStuff/Foobar.md` would be created. if (!scope.rootPath) { return cb( INVALID_SCOPE_VARIABLE('rootPath') ); } // Attach defaults _.defaults(scope, { createdAt: new Date() }); var args = scope.args[0].toLowerCase().split("/"); // Decide the output filename for use in targets below: scope.filename = args.length > 1 ? args[args.length - 1] : 'index'; scope.statename = args[args.length - 1]; scope.controllername = args[args.length - 1].charAt(0).toUpperCase() + args[args.length - 1].slice(1); scope.foldername = args.length > 1 ? args.slice(0, args.length - 1).join('/') + '/' : args + '/'; // Add other stuff to the scope for use in our templates: scope.whatIsThis = 'A humpback-view created at '+scope.createdAt; // When finished, we trigger a callback with no error // to begin generating files/folders as specified by // the `targets` below. cb(); }, /** * The files/folders to generate. * @type {Object} */ targets: { // Usage: // './path/to/destination.foo': { someHelper: opts } // Creates a dynamically-named file relative to `scope.rootPath` // (defined by the `filename` scope variable). // // The `template` helper reads the specified template, making the // entire scope available to it (uses underscore/JST/ejs syntax). // Then the file is copied into the specified destination (on the left). // Creates a folder at a static path //'./assets/views/:foldername': { folder: {} }, './assets/app/views/:foldername:filename.controllers.js': { template: 'controllers.template.js' }, './assets/app/views/:foldername:filename.states.js': { template: 'states.template.js' }, //'./views/:foldername': { folder: {} }, './views/:foldername:filename.ejs': { template: 'ejs.template.js' } }, /** * The absolute path to the `templates` for this generator * (for use with the `template` helper) * * @type {String} */ templatesDirectory: require('path').resolve(__dirname, './templates') }; /** * INVALID_SCOPE_VARIABLE() * * Helper method to put together a nice error about a missing or invalid * scope variable. We should always validate any required scope variables * to avoid inadvertently smashing someone's filesystem. * * @param {String} varname [the name of the missing/invalid scope variable] * @param {String} details [optional - additional details to display on the console] * @param {String} message [optional - override for the default message] * @return {Error} * @api private */ function INVALID_SCOPE_VARIABLE (varname, details, message) { var DEFAULT_MESSAGE = 'Issue encountered in generator "humpback-view":\n'+ 'Missing required scope variable: `%s`"\n' + 'If you are the author of `sails-generate-humpback-view`, please resolve this '+ 'issue and publish a new patch release.'; message = (message || DEFAULT_MESSAGE) + (details ? '\n'+details : ''); message = util.inspect(message, varname); return new Error(message); }
JavaScript
0.000002
@@ -1529,16 +1529,118 @@ it(%22/%22); +%0A var filenameOverride = typeof scope.args%5B1%5D !== 'undefined' ? scope.args%5B1%5D.toLowerCase() : null; %0A%0A // @@ -1710,24 +1710,63 @@ .filename = +filenameOverride ? filenameOverride : ( args.length @@ -1802,16 +1802,17 @@ 'index' +) ;%0A sc
d7db0583105cb6623cdfd96eb83800f6739eda2d
Add useYarn: true to ember-try config
config/ember-try.js
config/ember-try.js
'use strict'; const getChannelURL = require('ember-source-channel-url'); module.exports = function() { return Promise.all([ getChannelURL('release'), getChannelURL('beta'), getChannelURL('canary') ]).then((urls) => { return { scenarios: [ { env: { EMBER_OPTIONAL_FEATURES: JSON.stringify({ 'jquery-integration': true }) }, name: 'ember-lts-2.18', npm: { devDependencies: { '@ember/jquery': '^0.5.1', 'ember-source': '~2.18.0' } } }, { name: 'ember-lts-3.4', npm: { devDependencies: { 'ember-source': '~3.4.0' } } }, { name: 'ember-release', npm: { devDependencies: { 'ember-source': urls[0] } } }, { name: 'ember-beta', npm: { devDependencies: { 'ember-source': urls[1] } } }, { name: 'ember-canary', npm: { devDependencies: { 'ember-source': urls[2] } } }, // The default `.travis.yml` runs this scenario via `npm test`, // not via `ember try`. It's still included here so that running // `ember try:each` manually or from a customized CI config will run it // along with all the other scenarios. { name: 'ember-default', npm: { devDependencies: {} } }, { env: { EMBER_OPTIONAL_FEATURES: JSON.stringify({ 'jquery-integration': true }) }, name: 'ember-default-with-jquery', npm: { devDependencies: { '@ember/jquery': '^0.5.1' } } } ] }; }); };
JavaScript
0.000011
@@ -1958,16 +1958,37 @@ %0A %5D +,%0A useYarn: true %0A %7D;%0A
6cb0e4e238443e3d65d4439acce9bb545b013972
add useYarn to see if fixes build
config/ember-try.js
config/ember-try.js
/* eslint-env node */ module.exports = { scenarios: [ { name: 'ember-lts-2.8', bower: { dependencies: { 'ember': 'components/ember#lts-2-8' }, resolutions: { 'ember': 'lts-2-8' } }, npm: { devDependencies: { 'ember-source': null } } }, { name: 'ember-lts-2.12', npm: { devDependencies: { 'ember-source': '~2.12.0' } } }, { name: 'ember-release', bower: { dependencies: { 'ember': 'components/ember#release' }, resolutions: { 'ember': 'release' } }, npm: { devDependencies: { 'ember-source': null } } }, { name: 'ember-beta', bower: { dependencies: { 'ember': 'components/ember#beta' }, resolutions: { 'ember': 'beta' } }, npm: { devDependencies: { 'ember-source': null } } }, { name: 'ember-canary', bower: { dependencies: { 'ember': 'components/ember#canary' }, resolutions: { 'ember': 'canary' } }, npm: { devDependencies: { 'ember-source': null } } }, { name: 'ember-default', npm: { devDependencies: {} } } ] };
JavaScript
0
@@ -34,16 +34,33 @@ rts = %7B%0A + useYarn: true,%0A scenar
1dd6cf66136b6a5c94f546ccd8b68da239427478
add browserify watch to Gruntfile
Gruntfile.js
Gruntfile.js
/* * holonomy-website * https://github.com/holonomy/website * licensed under the AGPLv3 license. */ 'use strict'; var _ = require('lodash'); var banner = '/* <%= pkg.name %> <%= pkg.version %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'; var lessPaths = [ 'node_modules/semantic/src', 'node_modules/font-awesome/less', 'styles', ]; var fontFiles = [ 'node_modules/font-awesome/fonts/*', 'node_modules/semantic/src/fonts/*', ]; module.exports = function(grunt) { // project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // lint JavaScript jshint: { all: ['Gruntfile.js', 'helpers/*.js'], options: { jshintrc: '.jshintrc', }, }, // build HTML from templates and data assemble: { options: { pkg: '<%= pkg %>', flatten: true, assets: 'static/assets', partials: ['templates/includes/*.hbs'], helpers: ['templates/helpers/*.js'], layout: 'templates/layouts/layout.hbs', data: ['data/*.{json,yml}'], }, build: { files: {'build/': ['templates/*.hbs']}, }, }, // compile LESS to CSS less: { options: { banner: banner, paths: lessPaths, }, develop: { files: { 'build/index.css': 'styles/index.less', }, }, deploy: { options: { cleancss: true, report: 'min', sourceMap: true, }, files: { 'build/index.css': 'styles/index.less', }, }, }, // compile JS browserify: { develop: { files: { 'build/index.js': 'scripts/index.js', }, }, deploy: { files: { 'build/index.js': 'scripts/index.js', }, options: { transform: ['uglifyify'], } }, }, // before generating any new files, // remove any previously-created files. clean: { build: ['build/**/*'] }, copy: { assets: { expand: true, cwd: 'assets', src: ['**'], dest: 'build/', }, fonts: { src: fontFiles, dest: 'build/fonts/', expand: true, flatten: true, filter: 'isFile', }, cname: { src: 'CNAME', dest: 'build/', }, }, connect: { options: { port: 5000, base: 'build', }, develop: { options: { livereload: true, }, }, default: { options: { keepalive: true, }, }, }, watch: { livereload: { options: { livereload: true, }, files: ['build/**/*'], }, all: { files: ['<%= jshint.all %>'], tasks: ['jshint'], }, grunt: { files: ['Gruntfile.js'], tasks: ['clean', 'assemble', 'less:develop'], }, less: { files: _.map(lessPaths, function (p) { return p + '/*.less'; } ), tasks: ['less'], }, assemble: { files: ['README.md', 'templates/**/*.hbs', 'templates/helpers/*.js', 'content/**'], tasks: ['assemble'], }, }, compress: { options: { mode: 'gzip', }, deploy: { files: [ { expand: true, cwd: 'build', src: '**/*', dest: 'build', filter: 'isFile', }, ], }, }, hashres: { deploy: { src: [ 'build/*.css*', 'build/*.js*', ], dest: 'build/**/*.html', }, }, 'gh-pages': { deploy: { options: { base: 'build', repo: '[email protected]:holonomy/holonomy.github.io', branch: 'master', message: banner, }, src: ['**/*'], }, }, }); // load npm plugins to provide necessary tasks. require('load-grunt-tasks')(grunt, { pattern: ['grunt-*', 'assemble*'], }); // register grunt tasks grunt.registerTask('develop', ['clean', 'jshint', 'assemble', 'less:develop', 'browserify:develop', 'copy', 'connect:develop', 'watch']); grunt.registerTask('deploy', ['clean', 'jshint', 'assemble', 'less:deploy', 'browserify:deploy', 'copy', /*'compress', */'hashres', 'gh-pages']); // default task to be run. grunt.registerTask('default', ['clean', 'assemble', 'less:deploy', 'connect:default']); };
JavaScript
0
@@ -3098,24 +3098,117 @@ : %5B'less'%5D,%0A + browserify: %7B%0A files: 'scripts/**/*.js',%0A tasks: %5B'browserify:develop'%5D,%0A %7D,%0A
8cf46dc434a2e7a6d4cd760918446b48d4e43b49
Add python junk files in ignore list when packing
Gruntfile.js
Gruntfile.js
/*jshint globalstrict: true*/ 'use strict'; var configuration = require('splunkdev-grunt/lib/configuration'), splunkEnvironment = require('splunkdev-grunt/lib/environment'), splunkWatchConfig = require('splunkdev-grunt/lib/watchConfig'), path = require('path'); var pkg = require('./package.json'); module.exports = function(grunt) { // Verify environment if (!splunkEnvironment.splunkHome()) { grunt.fail.fatal('Could not locate splunk home directory'); } // Verify configuration var splunkConfig = configuration.get(); if (!splunkConfig) { grunt.fail.fatal( 'Could not load configuration for current Splunk instance. Use `splunkdev configure`.' + 'If `splunkdev` is not available install it with `npm install -g splunkdev`.'); } // Set splunk application splunkConfig.splunkApp = 'routemap'; // ------------------------------------- // splunk-pack task configuration // ------------------------------------- // Specify config for splunk-pack task splunkConfig.pack = { sourceDir: path.join(__dirname, 'routemap'), output: path.join(__dirname, 'routemap', (splunkConfig.splunkApp + '.tar.gz')), source: [ './**/*', '!./local/**', '!./*.tar.gz', '!./django/routemap/static/routemap/bower_components/**/*', './django/routemap/static/routemap/bower_components/Leaflet.label/dist/leaflet.label.js', './django/routemap/static/routemap/bower_components/Leaflet.label/dist/leaflet.label.css' ] }; // ------------------------------------- // splunk-watch task configuration // ------------------------------------- // Watch config. Launch jshint for all changed JS files var watchConfig = { js: { files: ['<%= jshint.files %>'], tasks: ['jshint'] } }; // Add watch configuration for splunk app (reload splunk) watchConfig = splunkWatchConfig.watchForApp(watchConfig, splunkConfig.splunkApp); // ------------------------------------- // splunk-services task configuration // ------------------------------------- // Initialize Splunk config grunt.config.init({ splunk: splunkConfig, jshint: { files: ['Gruntfile.js', 'routemap/django/routemap/static/routemap/**/*.js'], options: { ignores: ['routemap/django/routemap/static/routemap/bower_components/**/*'], globals: { console: true, module: true, require: true, process: true, Buffer: true, __dirname: true } } }, watch: watchConfig }); // Load grunt-splunk grunt.loadNpmTasks('splunkdev-grunt'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.registerTask('default', ['watch']); grunt.registerTask('build', ['splunk-pack']); };
JavaScript
0
@@ -1236,16 +1236,58 @@ ar.gz',%0A + '!./**/*.pyo',%0A '!./**/*.pyc',%0A '!
12c9f855e55a124396bd2bf6f49e4e1804dbd7d3
add clean and rebuild tasks
Gruntfile.js
Gruntfile.js
/** Copyright © 2015 Luis Sieira Garcia This file is part of Planète. Planète is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Planète 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Foobar. If not, see <http://www.gnu.org/licenses/> **/ 'use strict'; var glob = require("glob"), util = require("./util"); process.env.NODE_ENV = 'test'; var exclude = ['.git', 'node_modules','bower_components','sample_module']; var files = glob.sync("**/test/**/*.js", {}); // var cleanFiles = glob.sync("{**/node_modules/!(grunt*)/,**/bower_components}", {}); files = files.filter(function(path) { return exclude.every(function(regexp) { return path.match(regexp) === null; }); }); files = util.pathsort(files); module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // clean: cleanFiles, symlink: { options: { overwrite: true }, expanded: { files: [ { src: 'core/backend', dest: 'node_modules/_' }, { src: 'core/frontend', dest: 'node_modules/#' } ] } }, auto_install: { local: {}, options: { recursive: true, exclude: exclude } }, mochaTest: { test: { options: { quiet: false, // Optionally suppress output to standard out (defaults to false) clearRequireCache: true // Optionally clear the require cache before running tests (defaults to false) }, src: files } } }); grunt.loadNpmTasks('grunt-auto-install'); grunt.loadNpmTasks('grunt-contrib-symlink'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-mocha-test'); grunt.registerTask('build', ['symlink', 'auto_install']); grunt.registerTask('test', ['mochaTest']); // grunt.registerTask('clean', ['clean']); // grunt.registerTask('rebuild', ['clean', 'build']); };
JavaScript
0.000002
@@ -953,19 +953,16 @@ , %7B%7D);%0A%0A -// var clea @@ -982,19 +982,16 @@ .sync(%22%7B -**/ node_mod @@ -1003,17 +1003,55 @@ !(grunt* -) +%7Cglob*),!(node_modules)/**/node_modules /,**/bow @@ -1065,20 +1065,16 @@ onents%7D%22 -, %7B%7D );%0A%0Afile @@ -1336,18 +1336,16 @@ son'),%0A%0A -// clea @@ -2385,54 +2385,8 @@ %5D);%0A -// grunt.registerTask('clean', %5B'clean'%5D);%0A// gr
d05ffb55d73e3966d84924299e96246104b2905e
Add tests around title setting for tgr command
tests/commands/tgrTests.js
tests/commands/tgrTests.js
var tgr = require("__buttercup/classes/commands/command.tgr.js"); module.exports = { errors: { groupNotFoundThrowsError: function (test) { var command = new tgr(); var fakeSearching = { findGroupByID: function (a, b) { return false; } }; command.injectSearching(fakeSearching); test.throws(function() { command.execute({ }, 1, 'a'); }, 'Group not found for ID', 'An error was thrown when no group found'); test.done(); } } };
JavaScript
0
@@ -504,15 +504,1065 @@ ;%0A %7D%0A + %7D,%0A%0A titleSet: %7B%0A titleSetCorrectlyForBla: function (test) %7B%0A var expectedTitle = 'Bla';%0A var command = new tgr();%0A%0A var fakeGroup = %7B%0A title: ''%0A %7D;%0A%0A var fakeSearching = %7B%0A findGroupByID: function (a, b) %7B%0A return fakeGroup;%0A %7D%0A %7D;%0A%0A command.injectSearching(fakeSearching);%0A%0A command.execute(%7B %7D, 1, expectedTitle);%0A%0A test.strictEqual(fakeGroup.title, expectedTitle, 'The title was set to ' + expectedTitle + ' correctly');%0A test.done();%0A %7D,%0A%0A titleSetCorrectlyForJames: function (test) %7B%0A var expectedTitle = 'James';%0A var command = new tgr();%0A%0A var fakeGroup = %7B%0A title: ''%0A %7D;%0A%0A var fakeSearching = %7B%0A findGroupByID: function (a, b) %7B%0A return fakeGroup;%0A %7D%0A %7D;%0A%0A command.injectSearching(fakeSearching);%0A%0A command.execute(%7B %7D, 1, expectedTitle);%0A%0A test.strictEqual(fakeGroup.title, expectedTitle, 'The title was set to ' + expectedTitle + ' correctly');%0A test.done();%0A %7D%0A %7D%0A%7D;%0A
6848c44547ce8e415ce45f4e5b02b012fb5cba9b
Remove unused hack from start-app helper
tests/helpers/start-app.js
tests/helpers/start-app.js
import Ember from 'ember'; import Application from '../../app'; import config from '../../config/environment'; import './sign-in-user'; export default function startApp(attrs) { let application; let attributes = Ember.merge({}, config.APP); attributes = Ember.merge(attributes, attrs); // use defaults, but you can override; Ember.run(function() { application = Application.create(attributes); application.setupForTesting(); application.injectTestHelpers(); }); // TODO: I'm not sure if this is the best thing to do, but it seems // easiest for now. That way in tests I can just write: // // application.auth.signInForTests() application.auth = application.__container__.lookup('auth:main'); return application; }
JavaScript
0
@@ -486,253 +486,8 @@ );%0A%0A - // TODO: I'm not sure if this is the best thing to do, but it seems%0A // easiest for now. That way in tests I can just write:%0A //%0A // application.auth.signInForTests()%0A application.auth = application.__container__.lookup('auth:main');%0A%0A re
133b4828be0af0dca481be41d1ce0b64158fcf0d
set default properties to event
src/jquery.editable.js
src/jquery.editable.js
(function($){ $.fn.editable = function(event, callback){ if(typeof callback != 'function') callback = function(arg){}; if(typeof event == "string"){ var trigger = this; var action = event; } else{ var trigger = event.trigger; var action = event.action; } var target = this; var edit = {}; edit.start = function(e){ trigger.unbind(action == 'clickhold' ? 'mousedown' : action); if(trigger != target) trigger.hide(); var old_value = target.text().replace(/^\s+/,'').replace(/\s+$/,''); var input = $('<input>').val(old_value). width(target.width()+target.height()).css('font-size','100%'). css('margin',0).attr('id','editable_'+(new Date()*1)). addClass('editable'); var finish = function(){ var res = input.val().replace(/^\s+/,'').replace(/\s+$/,''); target.text(res); callback({value : res, target : target, old_value : old_value}); edit.register(); if(trigger != target) trigger.show(); }; input.blur(finish); input.keydown(function(e){ if(e.keyCode == 13) finish(); }); target.html(input); input.focus(); }; edit.register = function(){ if(action == 'clickhold'){ var tid = null; trigger.bind('mousedown', function(e){ tid = setTimeout(function(){ edit.start(e); }, 500); }); trigger.bind('mouseup mouseout', function(e){ clearTimeout(tid); }); } else{ trigger.bind(action, edit.start); } }; edit.register(); return this; }; })(jQuery);
JavaScript
0.000002
@@ -78,16 +78,17 @@ lback != += 'functi @@ -146,17 +146,18 @@ t == - %22 += ' string -%22 +' )%7B%0A @@ -256,16 +256,24 @@ .trigger + %7C%7C this ;%0A @@ -297,16 +297,27 @@ t.action + %7C%7C 'click' ;%0A %7D%0A @@ -412,32 +412,33 @@ unbind(action == += 'clickhold' ? ' @@ -470,32 +470,33 @@ if(trigger != += target) trigger @@ -1035,16 +1035,17 @@ igger != += target) @@ -1153,16 +1153,17 @@ yCode == += 13) fin @@ -1285,16 +1285,17 @@ ction == += 'clickh
15aaa6dc12af90931a63be35ea383a3fa4520080
Fix comment URL 404 (#577)
auth/auth.js
auth/auth.js
/** * Copyright 2017, 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. */ /** * Demonstrates how to authenticate to Google Cloud Platform APIs using the * Google Cloud Client Libraries. */ 'use strict'; function authCloudImplicit () { // [START auth_cloud_implicit] // Imports the Google Cloud client library. const Storage = require('@google-cloud/storage'); // Instantiates a client. If you don't specify credentials when constructing // the client, the client library will look for credentials in the // environment. const storage = new Storage(); // Makes an authenticated API request. storage .getBuckets() .then((results) => { const buckets = results[0]; console.log('Buckets:'); buckets.forEach((bucket) => { console.log(bucket.name); }); }) .catch((err) => { console.error('ERROR:', err); }); // [END auth_cloud_implicit] } function authCloudExplicit () { // [START auth_cloud_explicit] // Imports the Google Cloud client library. const Storage = require('@google-cloud/storage'); // Instantiates a client. Explicitly use service account credentials by // specifying the private key file. All clients in google-cloud-node have this // helper, see https://googlecloudplatform.github.io/google-cloud-node/#/docs/google-cloud/latest/guides/authentication const storage = new Storage({ keyFilename: '/path/to/keyfile.json' }); // Makes an authenticated API request. storage .getBuckets() .then((results) => { const buckets = results[0]; console.log('Buckets:'); buckets.forEach((bucket) => { console.log(bucket.name); }); }) .catch((err) => { console.error('ERROR:', err); }); // [END auth_cloud_explicit] } const cli = require(`yargs`) .demand(1) .command( `auth-cloud-implicit`, `Loads credentials implicitly.`, {}, authCloudImplicit ) .command( `auth-cloud-explicit`, `Loads credentials implicitly.`, {}, authCloudExplicit ) .example(`node $0 implicit`, `Loads credentials implicitly.`) .example(`node $0 explicit`, `Loads credentials explicitly.`) .wrap(120) .recommendCommands() .epilogue(`For more information, see https://cloud.google.com/docs/authentication`) .help() .strict(); if (module === require.main) { cli.parse(process.argv.slice(2)); }
JavaScript
0
@@ -1782,36 +1782,37 @@ ://g +ithub.com/G oogle -c +C loud -p +P latform -.github.io /goo @@ -1830,40 +1830,23 @@ ode/ -#/docs/google-cloud/latest/guide +blob/master/doc s/au @@ -1857,16 +1857,19 @@ tication +.md %0A const