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
703d698df4f241e9ed8b53473f15189a998a4319
remove reverse from morph example shape
examples/morph/client.js
examples/morph/client.js
import { shape, render, play } from './tmp'; const from = { type: 'circle', cx: 25, cy: 25, r: 25, fill: '#E54', }; const to = { type: 'path', d: 'M75,75l10-5l15,20v10h-10l-5-5l-10,5z', fill: '#0FA', moveIndex: 1, reverse: true, }; const animation = shape( from, to ); render({ selector: '.svg' }, animation ); play( animation, { alternate: true, duration: 2000, iterations: Infinity, });
JavaScript
0.000003
@@ -231,25 +231,8 @@ 1,%0A - reverse: true,%0A %7D;%0A%0A
05ea041839e1b10b77754f89c2c3225f19a8a542
add bracket in section
lib/iniReader.js
lib/iniReader.js
(function() { "use strict"; function parseLines(lines, options) { options = { caseInsensitive: true, section: { allowDuplicate: false }, key: { allowDuplicate: false, replcaeDuplicate: false }, value: { hasDelimiter: true, needToSort: true, delimiter: ' ' } } function parseValue(value) { if (options.value.hasDelimiter) { let val = value.split(options.value.delimiter); if (options.value.needToSort) { val.sort(); // inplace sort } return val.join(options.value.delimiter); } else { return value; } } let state = null; let section = null; let data = {}; // section, key, value, case_sensitive, comment for (let line of lines.split('\n')) { line = line.trim(); if (options.caseInsensitive) { line = line.toLowerCase(); } // ignore blank line if (line.length === 0) { continue; } if (line.match(/^\[([^\]])*\]$/)) { // ex: [sectionName] let sectionName = line.trim().substring(1, line.length - 1); let exist = data[sectionName]; if (!options.section.allowDuplicate && exist) { throw new Error('Section duplicate not allowed'); } data[sectionName] = data[sectionName] ? data[sectionName] : {}; section = data[sectionName]; continue; } if (!section) { throw new Error('There is no section'); } // parse key value if (line.indexOf('=') < 0) { throw new Error('Invalid key value format. there is no character \'=\'') } let ary = line.split('='); let key = ary[0].trim(); let value = ary[1].trim(); if (!options.key.allowDuplicate && section[key]) { throw new Error('Key duplicate not allowed'); } // section 안의 key 가 이미 존재하는 경우에는 reaplce 할지 무시할지를 결정한다. if (section[key]) { if (options.key.replcaeDuplicate) { section[key] = parseValue(value, options); } } else { section[key] = parseValue(value); } } return data; }; module.exports = function(lines, options) { return parseLines(lines, options); } })();
JavaScript
0.000008
@@ -1134,38 +1134,8 @@ im() -.substring(1, line.length - 1) ;%0A
b67fec45a55b5b2e78d1c58a9ba9be123fba647a
Add pageInfoStrings
src/localization/pageInfoStrings.js
src/localization/pageInfoStrings.js
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import LocalizedStrings from 'react-native-localization'; export const pageInfoStrings = new LocalizedStrings({ gb: { address: 'Address', code: 'Code', comment: 'Comment', confirm_date: 'Confirm Date', customer: 'Customer', entered_by: 'Entered By', entry_date: 'Entry Date', months_stock_required: 'Months Stock', stocktake_name: 'Stocktake Name', supplier: 'Supplier', their_ref: 'Their Ref', }, fr: { address: 'Addresse', code: 'Code', comment: 'Commentaire', confirm_date: 'Date de confirmation', customer: 'Client', entered_by: 'Entrée par', entry_date: "Date d'entrée", months_stock_required: 'Mois de stock', stocktake_name: "Nom du relevé d'inventaire", supplier: 'Fournisseur', their_ref: 'Leur référence', }, gil: { // TODO: add - stocktake_name address: 'Am tabo', code: 'Code', comment: 'Comment', confirm_date: 'Confirm Date', customer: 'Kiriniki ke aoraki', entered_by: 'Entered By', entry_date: 'Entry Date', months_stock_required: 'Iraua te Namakaina?', supplier: 'Kambana n oota, Pharmacy ke HC', their_ref: 'Ana Ref', }, tl: { // TODO: add - stocktake_name address: 'Enderesu', code: 'Kódigu', comment: 'komentáriu', confirm_date: 'Data Konfirmadu', customer: 'Kliente', entered_by: 'Naran Hatama\nDadus', entry_date: 'Data Hatama', months_stock_required: 'Pedido ba fulan', supplier: 'Distribuidor', their_ref: 'Referensia', }, la: { address: 'ທີ່ຢູ່', code: 'ລະຫັດ', comment: 'ຄໍາເຫັນ', confirm_date: 'ຢືນຢັນ ວັນທີ', customer: 'ລາຍຊື່ຜູ້ຮັບສິນຄ້າ', entered_by: 'ປ້ອນ​ຂໍ​້​ມູນໂດຍ', entry_date: 'ວັນທີປ້ອນ', months_stock_required: 'ສິນ​ຄ້າພາຍໃນເດືອນ', stocktake_name: 'ຊື່​ຂອງ​ໃບກວດ​ກາ​ສິນ​ຄ້າ​ໃນ​ສາງ', supplier: 'ຜູ້ສະໜອງ', their_ref: 'ຂໍ້ມູນອ້າງອີງ', }, }); export default pageInfoStrings;
JavaScript
0
@@ -60,16 +60,43 @@ 19%0A */%0A%0A +/**%0A * TODO: by_batch%0A */%0A%0A import L @@ -525,24 +525,50 @@ Their Ref',%0A + by_batch: 'By batch',%0A %7D,%0A fr: %7B @@ -924,16 +924,42 @@ rence',%0A + by_batch: 'By batch',%0A %7D,%0A g @@ -1318,16 +1318,42 @@ a Ref',%0A + by_batch: 'By batch',%0A %7D,%0A t @@ -1700,16 +1700,42 @@ ensia',%0A + by_batch: 'By batch',%0A %7D,%0A l @@ -2065,24 +2065,24 @@ '%E0%BA%9C%E0%BA%B9%E0%BB%89%E0%BA%AA%E0%BA%B0%E0%BB%9C%E0%BA%AD%E0%BA%87',%0A - their_re @@ -2101,16 +2101,42 @@ %E0%BA%B2%E0%BA%87%E0%BA%AD%E0%BA%B5%E0%BA%87',%0A + by_batch: 'By batch',%0A %7D,%0A%7D);
b82d32506d6fbbea6d6901586ca260408f851c86
update resume reporter location
src/location/LocationReporter.hy.js
src/location/LocationReporter.hy.js
import { Syncher } from 'service-framework/dist/Syncher'; import URI from 'urijs'; import position from './position'; import Search from '../utils/Search'; import IdentityManager from 'service-framework/dist/IdentityManager'; import { Discovery } from 'service-framework/dist/Discovery'; import { callbackify } from 'util'; class LocationHypertyFactory { constructor(hypertyURL, bus, config) { let uri = new URI(hypertyURL); this.objectDescURL = `hyperty-catalogue://catalogue.${uri.hostname()}/.well-known/dataschema/Context`; this.syncher = new Syncher(hypertyURL, bus, config); this.identityManager = new IdentityManager(hypertyURL, config.runtimeURL, bus); this.discovery = new Discovery(hypertyURL, config.runtimeURL, bus); this.search = new Search(this.discovery, this.identityManager); this.currentPosition = null; this.identity = null; this.bus = bus; this.hypertyURL = hypertyURL; this.reporter = null; this.watchID = null; } _getRegisteredUser() { let _this = this; return new Promise((resolve, reject) => { _this.identityManager.discoverUserRegistered().then((identity) => { console.log('[LocationReporter] GET MY IDENTITY:', identity); resolve(identity); }).catch((error) => { console.error('[LocationReporter] ERROR:', error); reject(error); }); }); } _resumeReporters() { let _this = this; //debugger; return new Promise((resolve, reject) => { _this.syncher.resumeReporters({store: true}).then((reporters) => { console.log('[LocationReporter] Reporters resumed', reporters); let reportersList = Object.keys(reporters); if (reportersList.length > 0) { _this._getRegisteredUser().then((identity) => { reportersList.forEach((dataObjectReporterURL) => { //debugger; console.log(identity); _this.identity = identity; console.log('[LocationReporter] ', dataObjectReporterURL); console.log('[LocationReporter]', reporters[dataObjectReporterURL]); if (identity.userURL == reporters[dataObjectReporterURL].metadata.subscriberUsers[0] && reporters[dataObjectReporterURL].metadata.name == 'location') { //debugger; _this.reporter = reporters[dataObjectReporterURL]; _this.reporter.onSubscription((event) => event.accept()); return resolve(true); } else { return resolve(false); } }); }); } else { return resolve(false); } }).catch((reason) => { console.info('[LocationReporter] Reporters:', reason); }); }); } //FOR invite checkin -> hyperty://sharing-cities-dsm/checkin-rating invite(observer) { let _this = this; _this.reporter.inviteObservers([observer]); } watchMyLocation(callback) { function success(pos) { var crd = pos.coords; callback(crd); } function error(err) { console.warn('ERROR(' + err.code + '): ' + err.message); } const options = { enableHighAccuracy: true // timeout: 5000, // maximumAge: 0 }; this.watchID = navigator.geolocation.watchPosition(success, error, options); } removeWatchMyLocation() { navigator.geolocation.clearWatch(this.watchID); } getLocation() { return this.currentPosition; } startPositionBroadcast() { let _this = this; if (_this.reporter == null) { _this.syncher.create(_this.objectDescURL, [], position(), true, false, 'location', {}, { resources: ['location-context'] }) .then((reporter) => { _this.reporter = reporter; console.log('[LocationReporter] DataObjectReporter', _this.reporter); reporter.onSubscription((event) => event.accept()); _this.search.myIdentity().then(identity => { _this.identity = identity; _this.broadcastMyPosition(); }); }); } else { _this.broadcastMyPosition(); } } initPosition() { //debugger; let _this = this; if (_this.reporter == null) { _this.syncher.create(_this.objectDescURL, [], position(), true, false, 'location', {}, { resources: ['location-context'] }) .then((reporter) => { _this.reporter = reporter; console.log('[LocationReporter] DataObjectReporter', _this.reporter); reporter.onSubscription((event) => event.accept()); _this.search.myIdentity().then(identity => { _this.identity = identity; _this.setCurrentPosition(); }); }); } else { _this.setCurrentPosition(); } } setCurrentPosition() { let _this = this; navigator.geolocation.watchPosition((position) => { console.log('[LocationReporter] my position: ', position); _this.currentPosition = position; //debugger; }); } broadcastMyPosition() { let _this = this; navigator.geolocation.watchPosition((position) => { console.log('[LocationReporter] my position: ', position); _this.currentPosition = position; _this.reporter.data.values = [ { name: 'latitude', unit: 'lat', value: position.coords.latitude}, { name: 'longitude', unit: 'lon', value: position.coords.longitude } ]; _this.reporter.data.time = position.timestamp; _this.reporter.data.tag = _this.identity.preferred_username; //debugger; }); } updateLocation() { let _this = this; let latitude = _this.currentPosition.coords.latitude; let longitude = _this.currentPosition.coords.longitude; _this.reporter.data.values = [ { name: 'latitude', unit: 'lat', value: latitude }, { name: 'longitude', unit: 'lon', value: longitude } ]; _this.reporter.data.time = _this.currentPosition.timestamp; _this.reporter.data.tag = _this.identity.preferred_username; } checkin(spotId) { let _this = this; let latitude = _this.currentPosition.coords.latitude; let longitude = _this.currentPosition.coords.longitude; _this.reporter.data.values = [ { name: 'latitude', unit: 'lat', value: latitude }, { name: 'longitude', unit: 'lon', value: longitude }, { name: 'checkin', unit: 'checkin', value: spotId } ]; } // can call with 'data://sharing-cities-dsm/shops' retrieveSpots(spotsURL) { return new Promise((resolve) => { let _this = this; let createMessage = { type: 'forward', to: spotsURL, from: _this.hypertyURL, body: { from: _this.hypertyURL, type: 'read' } }; console.log('location-reporter-retrieveSpots()', createMessage); _this.bus.postMessage(createMessage, (reply) => { resolve(reply); console.log('location-reporter-retrieveSpots() reply: ', reply); }); }); } } export default function activate(hypertyURL, bus, config) { return { name: 'LocationReporter', instance: new LocationHypertyFactory(hypertyURL, bus, config) }; }
JavaScript
0
@@ -2502,36 +2502,41 @@ %7D - else %7B%0A +%0A %7D);%0A @@ -2562,40 +2562,8 @@ e);%0A - %7D%0A %7D);%0A
dc34a68af21dd77d8aa6eafed5ec886821921c5d
test fixes
lib/browser/lighthouse.js
lib/browser/lighthouse.js
/* * Copyright (c) 2015, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ 'use strict'; const assert = require('assertive'); const { isEmpty } = require('lodash'); function getTotalScore(success, failure) { const successCount = Object.keys(success).length; const errorCount = Object.keys(failure).length; return (successCount * 100) / (successCount + errorCount); } const lhConfig = { passes: [ { passName: 'accessibilityPass', gatherers: ['accessibility'], }, ], audits: [ 'accessibility/accesskeys', 'accessibility/aria-allowed-attr', 'accessibility/aria-required-attr', 'accessibility/aria-required-children', 'accessibility/aria-required-parent', 'accessibility/aria-roles', 'accessibility/aria-valid-attr-value', 'accessibility/aria-valid-attr', 'accessibility/audio-caption', 'accessibility/button-name', 'accessibility/bypass', 'accessibility/color-contrast', 'accessibility/definition-list', 'accessibility/dlitem', 'accessibility/document-title', 'accessibility/duplicate-id', 'accessibility/frame-title', 'accessibility/html-has-lang', 'accessibility/html-lang-valid', 'accessibility/image-alt', 'accessibility/input-image-alt', 'accessibility/label', 'accessibility/layout-table', 'accessibility/link-name', 'accessibility/list', 'accessibility/listitem', 'accessibility/meta-refresh', 'accessibility/meta-viewport', 'accessibility/object-alt', 'accessibility/tabindex', 'accessibility/td-headers-attr', 'accessibility/th-has-data-cells', 'accessibility/valid-lang', 'accessibility/video-caption', 'accessibility/video-description', ], }; const parseLhResult = function(results) { if (!results || !results.lhr || !results.lhr.audits) { return null; } const audits = results.lhr.audits; const errorsObj = {}; const notApplicableObj = {}; const successObj = {}; for (const key in audits) { const audit = audits[key]; const description = audit.description; const details = audit.details; const id = audit.id; const score = audit.score; const scoreDisplayMode = audit.scoreDisplayMode; const auditInfo = { description, details }; if (score) { successObj[id] = auditInfo; } else if (scoreDisplayMode === 'not-applicable') { notApplicableObj[id] = auditInfo; } else if (scoreDisplayMode !== 'manual') { const snippets = []; if (!isEmpty(details.items)) { details.items.forEach(item => snippets.push(item.node.snippet || '')); } errorsObj[id] = { description, snippets }; } } const score = getTotalScore(successObj, errorsObj); return { audits, score, isSuccess(cutoff) { return score >= cutoff; }, success(type) { return type ? successObj[type] : successObj; }, errors(type) { return type ? errorsObj[type] : errorsObj; }, errorString() { const errorList = []; for (const id in errorsObj) { const description = errorsObj[id].description; const snippets = errorsObj[id].snippets; errorList.push(`${description}:\n\t${snippets.join('\n\t')}`); } return errorList.join('\n\n'); }, }; }; exports.assertLighthouseScore = function assertLighthouseScore( score, flags, config ) { const assertScore = function aScore(res) { assert.expect(parseLhResult(res).isSuccess(score)); }; return this.getLighthouseData(flags, config || lhConfig).then(assertScore); }; exports.runLighthouseAudit = function runLighthouseAudit(flags, config) { const assertScore = function aScore(res) { assert.expect(parseLhResult(res).isSuccess(score)); }; return this.getLighthouseData(flags, config || lhConfig).then(parseLhResult); };
JavaScript
0.001366
@@ -1606,18 +1606,16 @@ onst - %7B isEmpty %7D = @@ -1610,18 +1610,16 @@ isEmpty - %7D = requi @@ -1628,16 +1628,24 @@ ('lodash +/isEmpty ');%0A%0Afun @@ -5136,115 +5136,8 @@ ) %7B%0A - const assertScore = function aScore(res) %7B%0A assert.expect(parseLhResult(res).isSuccess(score));%0A %7D;%0A%0A re
d7ea301132d402cc0b288a0def226d370dffb2e7
Update intercept.js
lib/intercept.js
lib/intercept.js
/** * @module nock/intercepts */ var RequestOverrider = require('./request_overrider'), mixin = require('./mixin'), path = require('path'), url = require('url'), inherits = require('util').inherits, EventEmitter = require('events').EventEmitter, http = require('http'), parse = require('url').parse, ClientRequest = http.ClientRequest /** * @name NetConnectNotAllowedError * @private * @desc Error trying to make a connection when disabled external access. * @class * @example * nock.disableNetConnect(); * http.get('http://zombo.com'); * // throw NetConnectNotAllowedError */ function NetConnectNotAllowedError(host) { this.message = 'Nock: Not allow net connect for "' + host + '"'; this.name = 'NetConnectNotAllowedError'; } var allInterceptors = {}, allowNetConnect = /.*/; /** * Enabled real request. * @public * @param {String|RegExp} matcher=RegExp.new('.*') Expression to match * @example * // Enables all real requests * nock.enableNetConnect(); * @example * // Enables real requests for url that matches google * nock.enableNetConnect('google'); * @example * // Enables real requests for url that matches google and amazon * nock.enableNetConnect(/(google|amazon)/); */ function enableNetConnect(matcher) { if (typeof matcher === 'string') { allowNetConnect = new RegExp(matcher); } else if (typeof matcher === 'object' && typeof matcher.test === 'function') { allowNetConnect = matcher; } else { allowNetConnect = /.*/; } } function isEnabledForNetConnect(options) { normalizeForRequest(options); return allowNetConnect && allowNetConnect.test(options.host); } /** * Disable all real requests. * @public * @param {String|RegExp} matcher=RegExp.new('.*') Expression to match * @example * nock.disableNetConnect(); */ function disableNetConnect() { allowNetConnect = false; } function isOn() { return !isOff(); } function isOff() { return process.env.NOCK_OFF === 'true'; } function add(key, interceptor, scope) { if (! allInterceptors.hasOwnProperty(key)) { allInterceptors[key] = []; } interceptor.__nock_scope = scope; allInterceptors[key].push(interceptor); } function remove(interceptor) { if (interceptor.__nock_scope.shouldPersist()) return; if (interceptor.counter > 1) { interceptor.counter -= 1; return; } var key = interceptor._key.split(' '), u = url.parse(key[1]), hostKey = u.protocol + '//' + u.host, interceptors = allInterceptors[hostKey], interceptor, thisInterceptor; if (interceptors) { for(var i = 0; i < interceptors.length; i++) { thisInterceptor = interceptors[i]; if (thisInterceptor === interceptor) { interceptors.splice(i, 1); break; } } } } function removeAll() { allInterceptors = {}; } function normalizeForRequest(options) { options.proto = options.proto || 'http'; options.port = options.port || ((options.proto === 'http') ? 80 : 443); if (options.host) { options.hostname = options.hostname || options.host.split(':')[0]; } options.host = (options.hostname || 'localhost') + ':' + options.port; return options; } function interceptorsFor(options) { var basePath; normalizeForRequest(options); basePath = options.proto + '://' + options.host; return allInterceptors[basePath] || []; } function activate() n{ // ----- Extending http.ClientRequest function OverridenClientRequest(options, cb) { var interceptors = interceptorsFor(options); if (interceptors.length) { var overrider = RequestOverrider(this, options, interceptors, remove, cb); for(var propName in overrider) { if (overrider.hasOwnProperty(propName)) { this[propName] = overrider[propName]; } } } else { ClientRequest.apply(this, arguments); } } inherits(OverridenClientRequest, ClientRequest); http.ClientRequest = OverridenClientRequest; // ----- Overriding http.request and https.request: [ 'http', 'https'].forEach( function(proto) { var moduleName = proto, // 1 to 1 match of protocol and module is fortunate :) module = require(moduleName), oldRequest = module.request; module.request = function(options, callback) { var interceptors, req, res; if (typeof options === 'string') { options = parse(options); } options.proto = proto; interceptors = interceptorsFor(options); if (isOn() && interceptors.length) { var matches = false, allowUnmocked = false; interceptors.forEach(function(interceptor) { if (! allowUnmocked && interceptor.options.allowUnmocked) { allowUnmocked = true; } if (interceptor.matchIndependentOfBody(options)) { matches = true; } }); if (! matches && allowUnmocked) { return oldRequest.apply(module, arguments); } req = new OverridenClientRequest(options); res = RequestOverrider(req, options, interceptors, remove); if (callback) { res.on('response', callback); } return req; } else { if (isOff() || isEnabledForNetConnect(options)) { return oldRequest.apply(module, arguments); } else { throw new NetConnectNotAllowedError(options.host); } } }; } ); } activate(); module.exports = add; module.exports.removeAll = removeAll; module.exports.isOn = isOn; module.exports.activate = activate; module.exports.enableNetConnect = enableNetConnect; module.exports.disableNetConnect = disableNetConnect;
JavaScript
0.000002
@@ -3505,17 +3505,16 @@ ivate() -n %7B%0A // -
756b2b45b20df3e63f52c91600df3dec15102f8e
update file /api/v1/index.js
api/v1/index.js
api/v1/index.js
var router = new require('express').Router() , bodyParser = require('body-parser') , $fh = require('fh-mbaas-api') , Cloud = require('./cloud') , Hash = require('./hash') , Sec = require('./sec') , Service = require('./service') , Db = require('./db') , Cache = require('./cache') ; var parser = bodyParser(); router.use(function(req, res, next){ var start = Date.now(); $fh.stats.inc('increment'); $fh.stats.dec('decrement'); res.on('header', function(){ $fh.stats.timing('timing', Date.now() - start); }); if(['POST', 'PUT'].indexOf(req.method) !== -1){ return parser(req, res, next); } next(); }); exports.route = function(app){ app.use('/api/v1', router); app.use('/api/v1', Cloud.router); app.use('/api/v1', Hash.router); app.use('/api/v1', Sec.router); app.use('/api/v1', Service.router); app.use('/api/v1', Db.router); app.use('/api/v1', Cache.router); app.use(function(err, req, res, next){ console.error(err.stack || err); res.status(500).send('ಠ_ಠ This is why we can\'t have nice things.'); }); };
JavaScript
0.000002
@@ -458,22 +458,16 @@ inc('inc -rement ');%0A $f @@ -486,14 +486,8 @@ 'dec -rement ');%0A @@ -542,19 +542,17 @@ ing('tim -ing +e ', Date.
da3c16633f1c4d6e5ed53ac753704aad8a51e00e
make note of to do
BlazarUI/app/scripts/components/Helpers.js
BlazarUI/app/scripts/components/Helpers.js
import React from 'react'; import {some, uniq, flatten, filter, contains} from 'underscore'; import humanizeDuration from 'humanize-duration'; import moment from 'moment'; import BuildStates from '../constants/BuildStates.js'; import {LABELS, iconStatus} from './constants'; import Icon from './shared/Icon.jsx'; // 1234567890 => 1 Aug 1991 15:00 export const timestampFormatted = function(timestamp, format='lll') { timestamp = parseInt(timestamp); if (!timestamp) { return ''; } const timeObject = moment(timestamp); return timeObject.format(format); }; export const timestampDuration = function(startTimestamp, endTimestamp, round='true') { return humanizeDuration(endTimestamp - startTimestamp, {round: round}); }; // 'BUILD_SUCCEEEDED' => 'Build Succeeded' export const humanizeText = function(string) { if (!string) { return ''; } string = string.replace(/_/g, ' '); string = string.toLowerCase(); string = string[0].toUpperCase() + string.substr(1); return string; }; export const truncate = function(str, len = 10, ellip=false) { if (str && str.length > len && str.length > 0) { let new_str = str + ' '; new_str = str.substr(0, len); new_str = str.substr(0, new_str.lastIndexOf(' ')); new_str = (new_str.length > 0) ? new_str : str.substr(0, len); if (ellip && str.length > len) { new_str += '…'; } return new_str; } return str; }; export const githubShaLink = function(info) { return `https://${info.gitInfo.host}/${info.gitInfo.organization}/${info.gitInfo.repository}/commit/${info.build.sha}/`; }; export const cmp = function(x, y) { return x > y ? 1 : x < y ? -1 : 0; }; export const getIsStarredState = function(stars, id) { return some(stars, (star) => { return star.moduleId === id; }); }; // Data Helpers export const uniqueBranches = function(branches) { const uniqueBranches = uniq(branches, false, (b) => { return b.gitInfo.branch; }); return uniqueBranches.map((b) => { return { value: b.gitInfo.branch, label: b.gitInfo.branch }; }); }; export const tableRowBuildState = function(state) { if (state === BuildStates.FAILED) { return 'bgc-danger'; } else if (state === BuildStates.CANCELLED) { return 'bgc-warning'; } }; export const getFilteredBranches = function(filters, branches) { const branchFilters = filters.branch; const filteredBranches = branches.filter((b) => { let passGo = false; // not filtering if (branchFilters.length === 0) { return true; } if (branchFilters.length > 0) { let branchMatch = false; branchFilters.some((branch) => { if (branch.value === b.gitInfo.branch) { branchMatch = true; } }); return branchMatch; } return passGo; }); //finally sort by branch and bodule name return filteredBranches.sort((a, b) => { return cmp(a.gitInfo.branch, b.gitInfo.branch); }); }; export const buildIsOnDeck = function(buildState) { return contains([BuildStates.LAUNCHING, BuildStates.QUEUED], buildState); }; export const buildIsInactive = function(buildState) { return contains([BuildStates.SUCCESS, BuildStates.FAILED, BuildStates.CANCELLED], buildState); }; // DOM Helpers export const events = { listenTo: function(event, cb) { window.addEventListener(event, cb); }, removeListener: function(event, cb) { window.removeEventListener(event, cb); } }; export const dataTagValue = function(e, tagName) { const currentTarget = e.currentTarget; return currentTarget.getAttribute(`data-${tagName}`); }; export const scrollTo = function(direction) { if (direction === 'bottom') { window.scrollTo(0, document.body.scrollHeight); } else if (direction === 'top') { window.scrollTo(0, 0); } }; export const getPathname = function() { return window.location.pathname; }; // Components export const buildResultIcon = function(result) { const classNames = LABELS[result]; return ( <Icon name={iconStatus[result]} classNames={classNames} title={humanizeText(result)} /> ); }; export const renderBuildStatusIcon = function(state) { return ( <Icon name={iconStatus[state]} classNames={`icon-roomy ${LABELS[state]}`} title={humanizeText(state)} /> ); };
JavaScript
0
@@ -3917,18 +3917,64 @@ %0A// -Components +To do: move these out as components in components/shared %0Aexp
1c02d08b059f857cb66af81aba2f8a425fcaae86
Remove commented-out test code
test/model/FeatureTest.js
test/model/FeatureTest.js
var promises = require('q'); var Watai = require('../helpers/subject'), my = require('../helpers/driver').getDriverHolder(), expectedOutputs = require('../helpers/testWidget').expectedOutputs, WidgetTest; /** Timeout value of the test's config. */ var GLOBAL_TIMEOUT = 500; /** This test suite is redacted with [Mocha](http://visionmedia.github.com/mocha/) and [Should](https://github.com/visionmedia/should.js). */ describe('Feature', function() { var featureWithScenario; before(function() { WidgetTest = require('../helpers/testWidget').getWidget(my.driver); featureWithScenario = function featureWithScenario(scenario) { return new Watai.Feature('Test feature', scenario, { TestWidget: WidgetTest }, require('../config')); } }); describe('functional scenarios with', function() { var failureReason = 'It’s a trap!'; var failingFeatureTest = function() { return featureWithScenario([ function() { throw failureReason } ]).test(); } function makeFailingPromiseWithSuffix(suffix) { return function() { var deferred = promises.defer(); deferred.reject(failureReason + suffix); return deferred.promise; } } var failingPromise = makeFailingPromiseWithSuffix(''); it('an empty feature should be accepted', function(done) { featureWithScenario([]).test().then(function() { done(); }, function(err) { done(new Error(err)); }).done(); }); it('a failing function should be rejected', function(done) { failingFeatureTest().then(function() { done(new Error('Resolved instead of rejected!')); }, function() { done(); // can't pass it directly, Mocha complains about param not being an error }).done(); }); it('a failing promise should be rejected', function(done) { featureWithScenario([ failingPromise ]).test().then(function() { done(new Error('Resolved instead of rejected!')); }, function() { done(); }).done(); }); it('multiple failing promises should be rejected', function(done) { featureWithScenario([ makeFailingPromiseWithSuffix(0), makeFailingPromiseWithSuffix(1), makeFailingPromiseWithSuffix(2) ]).test().then(function() { done(new Error('Resolved instead of rejected!')); }, function() { done(); }).done(); }); it('a function should be called', function(done) { var called = false; featureWithScenario([ function() { called = true; } ]).test().then(function() { if (called) done(); else done(new Error('Promise resolved without actually calling the scenario function')); }, function() { done(new Error('Feature evaluation failed, with' + (called ? '' : 'out') + ' actually calling the scenario function (but that’s still an error)')); }).done(); }); }); describe('badly-formatted scenarios', function() { function scenarioShouldThrowWith(responsibleStep) { (function() { featureWithScenario([ responsibleStep ]); }).should.throw(/at step 1/); } it('with null should throw', function() { scenarioShouldThrowWith(null); }); it('with explicit undefined should throw', function() { scenarioShouldThrowWith(undefined); }); it('with undefined reference should throw', function() { var a; scenarioShouldThrowWith(a); }); it('with a free string should throw', function() { scenarioShouldThrowWith('string'); }); it('with a free number should throw', function() { scenarioShouldThrowWith(12); }); it('with a free 0 should throw', function() { scenarioShouldThrowWith(0); }); }); describe('unclickable elements', function() { it('should respect the global timeout', function(done) { var start = new Date(); featureWithScenario([ WidgetTest.overlayedAction(), { 'TestWidget.output': expectedOutputs.overlayedActionLink } ]).test().then(function() { done(new Error('Passed while the overlayed element should not have been clickable!')); }, function() { var waitedMs = new Date() - start; if (waitedMs >= GLOBAL_TIMEOUT) done(); else done(new Error('Waited only ' + waitedMs + ' ms instead of at least ' + GLOBAL_TIMEOUT + ' ms.')); }).done(); }); it('should be fine if made clickable', function(done) { featureWithScenario([ WidgetTest.hideOverlay(), WidgetTest.overlayedAction(), { 'TestWidget.output': expectedOutputs.overlayedActionLink } ]).test().then(function() { done() }, function(report) { done(new Error(report)); }).done(); }); }); describe('events', function() { var subject; function expectFired(eventName, expectedParam) { var hasExpectedParam = arguments.length > 1; // allow for falsy values to be expected params return function(done) { subject.on(eventName, function(param) { if (hasExpectedParam) param.should.equal(expectedParam); done(); }); subject.test(); } } function expectNotFired(eventName) { return function(done) { subject.on(eventName, function() { done(new Error('Fired while it should not have')); }); subject.test(); setTimeout(done, 40); } } describe('of a feature with a failing step', function() { beforeEach(function() { subject = featureWithScenario([ function() { throw 'Boom!' } ]); }); [ 'start', 'step' ].forEach(function(type) { it('should fire a "' + type + '" event', expectFired(type)); }); // [ 'step:start', 'step:end', 'step:failure' ].forEach(function(type) { // it('should fire a "' + type + '" event and pass the 0-based step index', expectFired(type, 0)); // }); // [ 'match:start', 'match:end', 'match:failure' ].forEach(function(type) { // it('should NOT fire any "' + type + '" event', expectNotFired(type)); // }); }); describe('of a feature with an empty scenario', function() { beforeEach(function() { subject = featureWithScenario([ ]); }); it('should fire a "start" event', expectFired('start')); it('should NOT fire any "step" event', expectNotFired('step')); }); }); });
JavaScript
0
@@ -3771,38 +3771,33 @@ dAction(),%0A%09%09%09%09%7B -%0A%09%09%09%09%09 + 'TestWidget.outp @@ -3828,37 +3828,33 @@ rlayedActionLink -%0A%09%09%09%09 + %7D%0A%09%09%09%5D).test().t @@ -5450,365 +5450,8 @@ %09%7D); -%0A%0A%09%09%09// %5B 'step:start', 'step:end', 'step:failure' %5D.forEach(function(type) %7B%0A%09%09%09// %09it('should fire a %22' + type + '%22 event and pass the 0-based step index', expectFired(type, 0));%0A%09%09%09// %7D);%0A%0A%09%09%09// %5B 'match:start', 'match:end', 'match:failure' %5D.forEach(function(type) %7B%0A%09%09%09// %09it('should NOT fire any %22' + type + '%22 event', expectNotFired(type));%0A%09%09%09// %7D); %0A%09%09%7D
41abf95230732c81afc594ca9a962336e3145d9b
make it swing
examples/sequences.js
examples/sequences.js
var bap = require('../index'); function sequences () { var lowPianoKit = bap.sample({ src: 'sounds/new/own_barricade_end.wav', attack: 0.1, release: 0.1, pitch: -40, pan: 25 }).slice(8); var piano1 = bap.pattern({ tempo: 84, bars: 2 }); piano1.kit('A', lowPianoKit).channel(1).add( ['1.odd.01', 'A3', 96], ['1.even.01', 'A4', 96], ['2.1.01', 'A3', 96], ['2.2.01', 'A4', 96], ['2.3.01', 'A1', 96], ['2.4.01', 'A2', 96] ); var otherPianoKit = bap.sample({ src: 'sounds/new/own_barricade_middle.wav', attack: 0.3, release: 0.1, pitch: -40, pan: -25, volume: 150 }).slice(5); var otherPianoPattern = bap.pattern({ bars: 2 }).kit('B', otherPianoKit); otherPianoPattern.channel(1).add( ['1.*.52', 'B2', 48], ['1.1.01', 'B1', 52], ['2.*.48', 'B4', 48] ); var bassKit = bap.kit(); bassKit.slot(1).layer(bap.sample({ src: 'sounds/new/Sample25.WAV', channel: 'left' })); var bassPattern = bap.pattern().kit('A', bassKit); bassPattern.channel(1).add( // ['2.3.01', 'A1'] ); var drumKit = bap.kit(); drumKit.slot(1).layer('sounds/kick.wav'); drumKit.slot(2).layer('sounds/new/SNARE1.WAV').layer(bap.sample({ src: 'sounds/new/SNARE_38.WAV', volume: 40 })); drumKit.slot(3).layer(bap.sample({ src: 'sounds/hihat.wav', volume: 20 })); var drumPattern = bap.pattern({ bars: 2 }).kit('X', drumKit); drumPattern.channel(1).add( ['*.1.01', 'X1'], ['*.3.52', 'X1'], ['2.*.25', 'X3'], ['*.odd.92', 'X2'], ['*.*.%52', 'X3'] ); var breakSample = bap.sample({ src: 'sounds/esther.wav', pitch: -48, volume: 30, channel: 'right' }); var breakKit = breakSample.slice(16); var smallBreakKit = breakSample.slice(32); var breakPattern = bap.pattern({ tempo: 84, bars: 2 }) .kit('A', breakKit) .kit('B', smallBreakKit); breakPattern.channel(1).add( ['*.1.01', 'A1', 96], ['*.1.93', 'A2', 100], ['1.3.01', 'B8', 48], ['1.3.52', 'A1', 48], ['1.3.94', 'A2', 100], ['2.3.01', 'A3', 96], ['2.4.01', 'A4', 96] ); var y = bap.sequence( // [drumPattern], // // [drumPattern], // [piano1, drumPattern], [piano1, otherPianoPattern, drumPattern, breakPattern], [piano1, otherPianoPattern, drumPattern, breakPattern], [piano1, otherPianoPattern, drumPattern, breakPattern], [piano1, otherPianoPattern, breakPattern], { loop: true } ); var z = bap.sequence( // [y,y,y,y], y, // y, // // piano1, // [piano1, otherPianoPattern], // y, // [y,y], // [y,y], { loop: true } ); // // var x = bap.sequence( // y,z,y,z,y,z,y,z,y,z,y, // { loop: true } // ) z.start(); // window.z = z; // setTimeout(function () { // bap.clock.position = '1.1.01'; // }, 3000); } module.exports = sequences;
JavaScript
0.000004
@@ -50,16 +50,41 @@ s () %7B%0A%0A + bap.clock.tempo = 84;%0A%0A var lo @@ -1551,17 +1551,17 @@ 2.*. -2 +3 5', 'X3' %5D,%0A @@ -1556,16 +1556,26 @@ 5', 'X3' +, null, 30 %5D,%0A %5B
4235ed6135500cf5e478a02f72bc28f66d6c5653
Consolidate CORS domain RegExp
routes/api/index.js
routes/api/index.js
const fs = require('fs'); const path = require('path'); const express = require('express'); const request = require('superagent'); const async = require('async'); const cors = require('cors'); const router = express.Router(); const corsOptions = { origin: [ /\.?dev\.com:3000$/, /\.?literasee\.io$/, /\.?literasee\.org$/ ], methods: ['POST'], allowedHeaders: ['Authorization', 'Content-Type'], credentials: true }; router.use(cors(corsOptions)); router.options('*', cors(corsOptions)); router.use(require('cookie-parser')()); router.use(require('body-parser').json({limit: '10mb'})); // // actual routes // router.get('/featured_projects', require('./get-featured-projects')); router.get('/projects/:owner', require('./get-projects-by-owner')); router.get('/projects/:owner/:project', [ require('./get-project-from-db'), require('./get-gist-from-github'), require('./get-repo-from-github') ]); router.post('/update_project_description', require('./update-project-description')); router.post('/project/:owner/:project', require('./save-project-file')); module.exports = router;
JavaScript
0.000001
@@ -303,36 +303,16 @@ ee%5C. +( io -$/,%0A /%5C.?literasee%5C. +%7C org +) $/%0A
fbe14a64857b810d2e6776f00d35fd48ca9f985b
set maximum timeout to 60 secs
src/main/js/my-app/src/constants.js
src/main/js/my-app/src/constants.js
export const BASE_URL = document.location.origin.match(/3000/) ? 'http://localhost:8181' : document.location.origin; export const studentsAPI = `${BASE_URL}/api/students`; export const studentClassesAPI = `${BASE_URL}/api/studentClasses/`; export const registersAPI = `${BASE_URL}/api/registers/`; export const paymentsAPI = `${BASE_URL}/api/payeds/`; export const searchPaymentByRegistration = `${BASE_URL}/api/payeds/search/findByRegister?register=`; export const searchStudentFindByName = `${BASE_URL}/api/students/search/findByFname`; export const searchStudentFindByFnameAndLname = `${BASE_URL}/api/students/search/findByFnameAndLname?fname=`; export const searchRegistrationsByStudent = `${BASE_URL}/api/registers/search/findByStudent?student=`; export const searchRegistrationsByStudentAndStudentClass = `${BASE_URL}/api/registers/search/findByStudentAndStudentClass?student=`; export const searchRegistrationsByStudentClass = `${BASE_URL}/api/registers/search/findByStudentClass?studentClass=`; export const searchStudentClassesByDescription = `${BASE_URL}/api/studentClasses/search/findBydescription?description=`; export const searchStudentClassesByFnameAndLname = `${BASE_URL}/api/studentClasses/search/findByFnameAndLname?fname=`; export const searchByManager = `${BASE_URL}/api/managers/17`; export const txtMsg = ` Please select class, write your message and press enter. The message will be send only to \n those students that has registered to classes and has payed.`; export const giveMessage = 'Press a key to delete this message and give yours'; export const maximumTimeToWaitForData = 10; export const templateStudentBody = { fname: {}, lname: {}, phone: {}, date: {}, email: {}, facebook: {}, manager : {}, };
JavaScript
0.000655
@@ -1598,17 +1598,17 @@ rData = -1 +6 0;%0A%0Aexpo
d7da3ad674900f900555cba49ae01fdca49600b7
Use attachMediaStream() from adapter.js
src/content/getusermedia/resolution/js/main.js
src/content/getusermedia/resolution/js/main.js
/* * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ 'use strict'; var dimensions = document.querySelector('#dimensions'); var video = document.querySelector('video'); var stream; var vgaButton = document.querySelector('#vga'); var qvgaButton = document.querySelector('#qvga'); var hdButton = document.querySelector('#hd'); var fullHdButton = document.querySelector('#full-hd'); vgaButton.onclick = function() { getMedia(vgaConstraints); }; qvgaButton.onclick = function() { getMedia(qvgaConstraints); }; hdButton.onclick = function() { getMedia(hdConstraints); }; fullHdButton.onclick = function() { getMedia(fullHdConstraints); }; var qvgaConstraints = { video: {width: {exact: 320}, height: {exact: 240}} }; var vgaConstraints = { video: {width: {exact: 640}, height: {exact: 480}} }; var hdConstraints = { video: {width: 1280, height: 720} }; var fullHdConstraints = { video: {width: {exact: 1920}, height: {exact: 1080}} }; function successCallback(stream) { window.stream = stream; // stream available to console video.src = window.URL.createObjectURL(stream); } function errorCallback(error) { console.log('navigator.getUserMedia error: ', error); } function displayVideoDimensions() { if (!video.videoWidth) { setTimeout(displayVideoDimensions, 500); } dimensions.innerHTML = 'Actual video dimensions: ' + video.videoWidth + 'x' + video.videoHeight + 'px.'; } video.onloadedmetadata = displayVideoDimensions; function getMedia(constraints) { if (stream) { video.src = null; stream.stop(); } setTimeout(function() { navigator.getUserMedia(constraints, successCallback, errorCallback); }, (stream ? 200 : 0)); }
JavaScript
0
@@ -1218,47 +1218,33 @@ e%0A -video.src = window.URL.createObjectURL( +attachMediaStream(video, stre
10eb8fc52fbf6ffe0282acbdb3dddfed27a6b0ae
handle keyup enter on autocomplete and prevent default
src/control/content/components/LocationForm.js
src/control/content/components/LocationForm.js
import Buildfire, { components } from 'buildfire'; import React from 'react'; class LocationForm extends React.Component { constructor(props) { super(props); let model = { title: '', description: '', address: null, image: '', categories: [], carousel: [] }; this.state = Object.assign(model, props.location); } /** * Handles mounting of dom dependant components * - Google Maps * - Carousel */ componentDidMount() { // Mount google map const { maps } = window.google; this.autocomplete = new maps.places.Autocomplete(this.addressInput); this.autocomplete.addListener('place_changed', () => this.onPlaceChanged()); setTimeout(() => { let container = document.querySelector('.pac-container'); this.addressInput.parentNode.appendChild(container); container.style.top = '10px'; container.style.left = '10px'; }, 400); // Mount carousel this.editor = new components.carousel.editor('#carousel', { items: this.props.location ? this.props.location.carousel : [] }); this.editor.onAddItems = (items) => this.updateCarouselState(); this.editor.onDeleteItems = (items, index) => this.updateCarouselState(); this.editor.onItemChange = (item) => this.updateCarouselState(); this.editor.onOrderChange = (item, prevIndex, newIndex) => this.updateCarouselState(); } onInputChange(e) { const changes = {}; changes[e.target.name] = e.target.value; this.setState(changes); } onCategoryChange(e) { let { name, checked } = e.target; console.log({ name, checked }); // Category was selected if (checked) { let { categories } = this.state; categories.push(name); this.setState({ categories }); // Category was unselected } else { let index = this.state.categories.indexOf(name); let { categories } = this.state; categories.splice(index, 1); this.setState({ categories }); } } /** * Handles updating the carousel state data */ updateCarouselState() { const {items } = this.editor; this.setState({ carousel: items }); } /** * Handle showing the image dialog */ showImageDialog() { const dialogOptions = { showIcons: false, multiSelection: false }; // Request user to select image Buildfire.imageLib.showDialog(dialogOptions, (err, result) => { if (err) return console.error(err); // Stop if we don't have any images if (!result || !result.selectedFiles || !result.selectedFiles.length) { return; } this.setState({ image: result.selectedFiles[0] }); }); } /** * Handle the google maps autocomplete place change */ onPlaceChanged() { const place = this.autocomplete.getPlace(); if (!place.geometry) { return this.setState({ address: null }); } const address = { name: place.formatted_address, lat: place.geometry.location.lat(), lng: place.geometry.location.lng() }; this.setState({ address }); } /** * Pass submissions to parent component * * @param {Event} e Form submission event */ onSubmit(e) { e.preventDefault(); this.props.onSubmit(this.state); } render() { const { title, address, description, image, categories } = this.state; return ( <form onSubmit={ e => this.onSubmit(e) }> <div className='form-group'> <label htmlFor='name'>Title</label> <input onChange={ e => this.onInputChange(e) } value={ title } name='title' type='text' className='form-control' /> </div> <div className='form-group'> <label htmlFor='category'>Categories</label> <div className='row'> { this.props.categories ? this.props.categories.map((category, index) => ( <div key={ index } className='col-xs-3'> <input onChange={ e => this.onCategoryChange(e) } type='checkbox' name={ category.id } checked={ categories.indexOf(category.id) > -1 } /> &nbsp; <label>{ category.name }</label> </div> )) : null } </div> </div> <div className='form-group autocomplete-container'> <label htmlFor='address'>Address</label> <input key='address-input' ref={ n => this.addressInput = n } value={ address ? address.name : '' } type='text' className='form-control' /> </div> <div className='form-group'> <label htmlFor='description'>Description</label> <textarea value={ description } onChange={ e => this.onInputChange(e) } className='form-control' name='description' rows='3' /> </div> <div className='form-group'> <div id='carousel' /> </div> <div className='form-group'> <label>List Image</label> <div style={{ backgroundImage: image ? `url(${image})` : '' }} className='image-dialog' onClick={ () => this.showImageDialog() }> { this.state.image ? null : <a>Add Image +</a> } </div> </div> <div className='form-group'> <button disabled={ !title.length || !description.length || !address } type='submit' className='btn btn-primary'> { this.props.location ? 'Save Location' : 'Save Location' } </button> </div> </form> ); } } export default LocationForm;
JavaScript
0
@@ -3275,16 +3275,138 @@ );%0A %7D%0A%0A + onAutoKeyUp(e) %7B%0A let keyCode = e.keyCode %7C%7C e.which;%0A if (keyCode === 13) %7B%0A e.preventDefault();%0A %7D%0A %7D%0A%0A render @@ -4596,32 +4596,81 @@ %3Cinput%0A + onKeyUp=%7B e =%3E this.onAutoKeyUp(e) %7D%0A key=
e21ac48c3f1612421c9d722ee10ab9076d07682c
Use strict to prevent failing tests on node 4
test/query-parser.test.js
test/query-parser.test.js
let test = require('tap').test let parse = require('../lib/query-parser') test('should extract CSS selector from query and keep it intact', t => { let query = '.home li > a' let result = parse(query) t.strictSame(result.selector, query) t.end() }) test('should return null for `getter` if not present in the query', t => { let query = '.home li > a' let result = parse(query) t.strictSame(result.getter, null) t.end() }) test('should return empty array for `filters` if not present in the query', t => { let query = '.home li > a' let result = parse(query) t.deepEqual(result.filters, []) t.end() }) test('should extract `getter` from query if present', t => { let query = '.home li > a => href' let result = parse(query) t.strictSame(result.getter, 'href') t.end() }) test('should ignore whitespace around and in between `getter`', t => { let query = `.home li > a => hr e f ` let result = parse(query) t.strictSame(result.getter, 'href') t.end() }) test('should extract filter name', t => { let query = '.home li > a | trim' let result = parse(query) t.strictSame(result.filters[0].name, 'trim') t.end() }) test('should extract all filter names in order', t => { let query = '.home li > a | trim | normalizeWhitespace' let result = parse(query) t.strictSame(result.filters[0].name, 'trim') t.strictSame(result.filters[1].name, 'normalizeWhitespace') t.end() })
JavaScript
0
@@ -1,12 +1,26 @@ +'use strict'%0A%0A let test = r
65200f5ef93356c3444614d61e2d5acf25e05579
update api
routes/employees.js
routes/employees.js
var express = require('express'); var employees = express.Router(); var log = require('../lib/log'); var EmployeeObject = require('../models/employee-object').EmployeeObject; var getEmployeeList = require('../lib/active-employee-list').getEmployeeList; employees.get('/', function (req, res) { res.send('need a resource view'); }); employees.get('/today', function (req, res) { var today = new Date(); var y = today.getUTCFullYear(); var m = today.getUTCMonth() + 1; var d = today.getUTCDate(); res.redirect('year' + y + '/month' + m + '/day' + d); }); employees.get('/year/:y/month/:m/day/:d', function (req, res) { res.send('need a view here'); }); employees.get('/year/:y/month/:m/day/:d/json', function (req, res) { EmployeeObject.findOne({ year: Number(req.params.y), month: Number(req.params.m), day: Number(req.params.d) }, function (err, list) { if (err) { log.error(err); return res.status(500).send(err.message); } if (list) { return res.json(list); } // check if today return res.status(404).send('cannot find the list for ' + req.params.y + '-' + req.params.m + '-' + req.params.d + '.'); }); }); employees.post('/now', function (req, res) { getEmployeeList(true, function (err, response, list) { if (err) { log.error(err); } if (list) { return res.json(list); } res.status(500).send(err.message); }); }); module.exports = employees;
JavaScript
0
@@ -1269,18 +1269,8 @@ err, - response, lis
db9917a834ed460030dd3c7952b9571ad9d11a25
Fix and clean card
src/card.js
src/card.js
'use strict' // import modules import init from './component/init' import create from './element/create' import insert from './component/insert' import classify from './component/classify' // import components import Layout from './layout' let defaults = { prefix: 'material', class: 'card' } class Card { /** * Constructor * @param {Object} options - Component options * @return {Object} Class instance */ constructor (options) { this.options = Object.assign({}, defaults, options || {}) this.init() this.build() } init () { Object.assign(this, insert) } /** * build the component using the super method * @return {Object} The class instance */ build () { var tag = this.options.tag || 'div' this.wrapper = create(tag) classify(this.wrapper, this.options) this.layout = new Layout(this.options.layout, this.wrapper) } } export default Card
JavaScript
0
@@ -289,16 +289,30 @@ : 'card' +,%0A tag: 'div' %0A%7D%0A%0Aclas @@ -458,24 +458,93 @@ (options) %7B%0A + %0A%0A this.init(options)%0A this.build()%0A %7D%0A%0A init (options) %7B%0A this.opt @@ -596,59 +596,8 @@ %7B%7D) -%0A%0A this.init()%0A this.build()%0A %7D%0A%0A init () %7B %0A @@ -747,48 +747,8 @@ () %7B -%0A var tag = this.options.tag %7C%7C 'div' %0A%0A @@ -771,16 +771,29 @@ create( +this.options. tag)%0A
34f15baaeb26659dfd2c883598b255c6de4381a2
Fix test that fails on Windows due to path separator differences. Use ES2015 template literals.
test/resolve-path.spec.js
test/resolve-path.spec.js
import test from 'tape'; import path from 'path'; import url from 'url'; import resolvePath from '../src/resolve-path'; test('sanity check', assert => { assert.equal(typeof resolvePath, 'function', 'can import resolvePath and it is a function'); assert.end(); }); test('jspm import', assert => { System.config({ baseURL: __dirname, defaultJSExtensions: true, paths: { 'github:*': 'jspm_packages/github/*', 'npm:*': 'jspm_packages/npm/*', }, map: { 'mock-package': 'npm:[email protected]', }, }); const request = { current: 'jspm:mock-package/mock-asset', previous: 'stdin', }; resolvePath(request, '/') .then(p => { // System.normalize in resolvePath will give us the absolute path const relative = '/' + path.relative(__dirname, url.parse(p).path); assert.equal(relative, '/jspm_packages/npm/[email protected]/mock-asset.scss', 'resolves "jspm:" import'); }) .catch(e => assert.fail(e)) .then(() => assert.end()); }); test('nested imports', assert => { let request = { current: 'mixins/mixin', previous: '/jspm_packages/npm/[email protected]/mock-asset', }; resolvePath(request, '/') .then(p => { assert.equal(p, '/jspm_packages/npm/[email protected]/mixins/mixin.scss', 'resolves a nested import'); }) .catch(e => assert.fail(e)) .then(() => { request = { current: 'deeper/mixin', previous: 'mixins/mixin', }; resolvePath(request, '/') .then(p => { assert.equal(p, '/jspm_packages/npm/[email protected]/mixins/deeper/mixin.scss', 'resolves a double nested import'); }) .catch(e => assert.fail(e)) .then(() => assert.end()); }); });
JavaScript
0
@@ -781,14 +781,12 @@ e = -'/' + +%60/$%7B path @@ -824,16 +824,18 @@ p).path) +%7D%60 ;%0A @@ -857,18 +857,31 @@ lative, +%60/$%7Bpath.join( ' -/ jspm_pac @@ -877,37 +877,43 @@ n('jspm_packages -/npm/ +', 'npm', ' [email protected] @@ -906,33 +906,36 @@ [email protected] -/ +', ' mock-asset.scss' @@ -938,35 +938,11 @@ css' -, 'resolves %22jspm:%22 import' +)%7D%60 );%0A
261f8c73e1b7ca47ab26d89137af04d2042ca4f1
Clean up myaccount route.
routes/myaccount.js
routes/myaccount.js
var express = require('express'); var ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn; var db = require('../db'); var router = express.Router(); /* GET users listing. */ router.get('/', ensureLoggedIn(), function(req, res, next) { db.get('SELECT rowid AS id, username, name FROM users WHERE rowid = ?', [ req.user.id ], function(err, row) { if (err) { return next(err); } // TODO: Handle undefined row. var user = { id: row.id.toString(), username: row.username, displayName: row.name }; res.render('profile', { user: user }); }); }); module.exports = router;
JavaScript
0
@@ -196,16 +196,18 @@ get('/', +%0A ensureL @@ -216,16 +216,18 @@ gedIn(), +%0A functio @@ -246,16 +246,18 @@ next) %7B%0A + db.get @@ -364,16 +364,18 @@ ) %7B%0A + + if (err) @@ -398,24 +398,26 @@ rr); %7D%0A %0A + // TODO: @@ -448,16 +448,18 @@ %0A + var user @@ -469,16 +469,18 @@ %7B%0A + + id: row. @@ -494,16 +494,18 @@ ring(),%0A + us @@ -532,16 +532,18 @@ ,%0A + + displayN @@ -556,16 +556,18 @@ ow.name%0A + %7D;%0A @@ -569,16 +569,18 @@ %7D;%0A + res.rend @@ -614,14 +614,18 @@ %7D);%0A + %7D);%0A + %7D);%0A
007f8f69e29cb1d56427d217d6abf0ef0b1da6ae
Fix result data handling
view/statistics-time-per-person.js
view/statistics-time-per-person.js
'use strict'; var copy = require('es5-ext/object/copy') , forEach = require('es5-ext/object/for-each') , capitalize = require('es5-ext/string/#/capitalize') , uncapitalize = require('es5-ext/string/#/uncapitalize') , memoize = require('memoizee') , ObservableValue = require('observable-value') , location = require('mano/lib/client/location') , _ = require('mano').i18n.bind('View: Statistics') , db = require('mano').db , getData = require('mano/lib/client/xhr-driver').get , setupQueryHandler = require('../utils/setup-client-query-handler') , resolveFullStepPath = require('../utils/resolve-processing-step-full-path') , getQueryHandlerConf = require('../routes/utils/get-statistics-time-query-handler-conf') , getDurationDaysHours = require('./utils/get-duration-days-hours') , getDynamicUrl = require('./utils/get-dynamic-url'); exports._parent = require('./statistics-time'); exports._customFilters = Function.prototype; exports._queryConf = null; exports['time-nav'] = { class: { 'submitted-menu-item-active': true } }; exports['per-person-nav'] = { class: { 'pills-nav-active': true } }; var queryServer = memoize(function (query) { return getData('/get-time-per-person/', query); }, { normalizer: function (args) { return JSON.stringify(args[0]); } }); var getRowResult = function (rowData, label) { var result = copy(rowData); result.label = label; result.avgTime = rowData.avgTime ? getDurationDaysHours(rowData.avgTime) : '-'; result.minTime = rowData.minTime ? getDurationDaysHours(rowData.minTime) : '-'; result.maxTime = rowData.maxTime ? getDurationDaysHours(rowData.maxTime) : '-'; return result; }; exports['statistics-main'] = function () { var processingStepsMeta = this.processingStepsMeta, stepsMap = {}, queryHandler , params; Object.keys(processingStepsMeta).forEach(function (stepShortPath) { stepsMap[stepShortPath] = new ObservableValue(); }); queryHandler = setupQueryHandler(getQueryHandlerConf({ db: db, processingStepsMeta: processingStepsMeta, queryConf: exports._queryConf }), location, '/time/per-person/'); params = queryHandler._handlers.map(function (handler) { return handler.name; }); queryHandler.on('query', function (query) { if (query.dateFrom) { query.dateFrom = query.dateFrom.toJSON(); } if (query.dateTo) { query.dateTo = query.dateTo.toJSON(); } queryServer(query).done(function (result) { Object.keys(stepsMap).forEach(function (key) { var preparedResult = []; if (!result.byStep[key]) { stepsMap[key].value = null; return; } forEach(result.byStepAndProcessor[key], function (rowData, userId) { preparedResult.push(getRowResult(rowData.processing, db.User.getById(userId).fullName)); }); preparedResult.push(getRowResult(result.byStep[key], _("Total & times"))); stepsMap[key].value = preparedResult; }); }); }); section({ class: 'section-primary users-table-filter-bar' }, form({ action: '/time/per-person', autoSubmit: true }, div( { class: 'users-table-filter-bar-status' }, label({ for: 'service-select' }, _("Service"), ":"), select({ id: 'service-select', name: 'service' }, option( { value: '', selected: location.query.get('service').map(function (value) { return (value == null); }) }, _("All") ), list(db.BusinessProcess.extensions, function (service) { var serviceName = uncapitalize.call(service.__id__.slice('BusinessProcess'.length)); return option({ value: serviceName, selected: location.query.get('service').map(function (value) { var selected = (serviceName ? (value === serviceName) : (value == null)); return selected ? 'selected' : null; }) }, service.prototype.label); }, null)) ), div( { class: 'users-table-filter-bar-status' }, exports._customFilters.call(this) ), div( { class: 'users-table-filter-bar-status' }, label({ for: 'date-from-input' }, _("Date from"), ":"), input({ id: 'date-from-input', type: 'date', name: 'dateFrom', value: location.query.get('dateFrom') }) ), div( { class: 'users-table-filter-bar-status' }, label({ for: 'date-to-input' }, _("Date to"), ":"), input({ id: 'date-to-input', type: 'date', name: 'dateTo', value: location.query.get('dateTo') }) ), div( a({ class: 'users-table-filter-bar-print', href: getDynamicUrl('/time-per-person.pdf', { only: params }), target: '_blank' }, span({ class: 'fa fa-print' }), " ", _("Print pdf")) ))); insert(list(Object.keys(stepsMap), function (shortStepPath) { return stepsMap[shortStepPath].map(function (data) { if (!data) return; var step = db['BusinessProcess' + capitalize.call(processingStepsMeta[shortStepPath]._services[0])].prototype .processingSteps.map.getBySKeyPath(resolveFullStepPath(shortStepPath)); return section({ class: "section-primary" }, h3(step.label), table({ class: 'statistics-table' }, thead( th(), th({ class: 'statistics-table-number' }, _("Files processed")), th({ class: 'statistics-table-number' }, _("Average time")), th({ class: 'statistics-table-number' }, _("Min time")), th({ class: 'statistics-table-number' }, _("Max time")) ), tbody({ onEmpty: tr(td({ class: 'empty statistics-table-number', colspan: 5 }, _("There are no files processed at this step"))) }, data, function (rowData) { return tr( td(rowData.label), td({ class: 'statistics-table-number' }, rowData.processed), td({ class: 'statistics-table-number' }, rowData.avgTime), td({ class: 'statistics-table-number' }, rowData.minTime), td({ class: 'statistics-table-number' }, rowData.maxTime) ); }) )); }); })); };
JavaScript
0.000212
@@ -2974,16 +2974,27 @@ tep%5Bkey%5D +.processing , _(%22Tot @@ -5756,25 +5756,21 @@ rowData. -processed +count ),%0A%09%09%09%09%09
405db4f8fee5c15582985b4ac63738c216aa0308
fix spacces
lib/mergeSort.js
lib/mergeSort.js
/*! * sort-algorithms-js * mergeSort * Copyright(c) 2015 Eyas Ranjous <[email protected]> * MIT Licensed */ 'use strict'; var getMiddle = require('./helpers/getMiddle'); module.exports = function(numbersArray) { var merge = function(leftPartition, rightPartition) { var mergePartitions = function(merged, leftPartition, rightPartition) { if (leftPartition.length === 0) { return merged.concat(rightPartition); } if (rightPartition.length === 0) { return merged.concat(leftPartition); } if (leftPartition[0] < rightPartition[0]) { merged.push(leftPartition.shift()); } else { merged.push(rightPartition.shift()); } return mergePartitions(merged, leftPartition, rightPartition); }; return mergePartitions([], leftPartition, rightPartition); }, partitionAndMerge = function(arr, startIndex, endIndex) { var middleIndex = getMiddle(startIndex, endIndex), leftPartition, rightPartition; if (endIndex - startIndex > 0) { leftPartition = partitionAndMerge(arr, startIndex, middleIndex); rightPartition = partitionAndMerge(arr, middleIndex + 1, endIndex); } if (startIndex == endIndex) { return [arr[startIndex]]; } return merge(leftPartition, rightPartition); }; return partitionAndMerge(numbersArray, 0, numbersArray.length - 1); };
JavaScript
0.000001
@@ -272,25 +272,33 @@ artition) %7B%0A + %0A - @@ -377,32 +377,36 @@ + if (leftPartitio @@ -415,32 +415,36 @@ length === 0) %7B%0A + @@ -493,34 +493,40 @@ -%7D%0A + %7D%0A @@ -521,24 +521,26 @@ + if (rightPar @@ -554,32 +554,36 @@ length === 0) %7B%0A + @@ -631,34 +631,42 @@ -%7D%0A + %7D%0A @@ -721,32 +721,36 @@ + merged.push(left @@ -777,34 +777,42 @@ -%7D%0A + %7D%0A @@ -830,32 +830,36 @@ + + merged.push(righ @@ -887,34 +887,42 @@ -%7D%0A + %7D%0A @@ -976,32 +976,36 @@ ightPartition);%0A + %7D;%0A%0A
2cb7798cfe7debc76c704b33e6dacb04901edc94
fix typo
eln/Toc.js
eln/Toc.js
// this class is not really related to a sampleToc but can be used for any TOC import API from 'src/util/api'; import Versioning from 'src/util/versioning'; let defaultOptions = { group: 'all', varName: 'sampleToc', viewName: 'sample_toc', filter: (entry) => !entry.value.hidden, sort: (a, b) => { if (a.value.modified && a.value.modified > b.value.modified) { return -1; } else if ( a.value.modificationDate && a.value.modificationDate > b.value.modificationDate ) { return -1; } else if (a.value.modified && a.value.modified < b.value.modified) { return 1; } else if ( a.value.modificationDate && a.value.modificationDate < b.value.modificationDate ) { return 1; } else { return 0; } } }; class Toc { /** * Create an object managing the Toc * @param {object} [options={}] * @param {object} [roc=undefined] * @param {string} [options.group='mine'] Group to retrieve products. mine, all of a specific group name * @param {string} [options.varName='sampleToc'] * @param {string} [options.viewName='sample_toc'] * @param {function} [options.sort] Callback, by default sort by reverse date * @param {function} [options.filter] Callback to filter the result */ constructor(roc, options = {}) { this.roc = roc; this.options = Object.assign({}, defaultOptions, options); } setFilter(filter) { this.options.filter = filter; return this.refresh(); } /** * Retrieve the toc and put the result in the specified variable * */ refresh(options = {}) { let { group, sort, filter, viewName } = Object.assign( {}, this.options, options ); let mine = 0; let groups = ''; group = String(group); if (group === 'mine') { mine = 1; } else if (group !== 'all') { groups = group; } console.log('refresh', { groups, mine, filter }); return this.roc .query(viewName, { groups, mine, sort, filter, varName: this.options.varName }) .then((entries) => { if (this.options.callback) { entries.forEach(this.options.callback); } return entries; }); } /** * Retrieve the allowed groups for the logged in user and create 'groupForm' * variable and 'groupFormSchema' (for onde module). It will keep in a cookie * the last selected group. Calling this method should reload automatically * @param {object} [options={}] * @param {string} [varName='groupForm'] contains the name of the variable containing the form value * @param {string} [schemaVarName='groupFormSchema'] contains the name of the variable containing the form schema * @param {string} [cookieName='eln-default-sample-group''] cookie name containing the last selected group * @param {string} [filter] filter applied on first refresh * @param {string} [autoRefresh=true] refresh least after initialization * @param {boolean} [listAllGroups=true] select from any group, even if not the a member * @return {string} the form to select group} */ async initializeGroupForm(options = {}) { const { schemaVarName = 'groupFormSchema', varName = 'groupForm', cookieName = 'eln-default-sample-group', filter, autoRefresh = true, listAllGroups = false } = options; let groups = []; if (listAllGroups) { groups = (await this.roc.getGroupsInfo()).map((g) => g.name); } else { groups = (await this.roc.getGroupsMembership()).map((g) => g.name); } var possibleGroups = ['all', 'mine'].concat(groups); var defaultGroup = localStorage.getItem(cookieName); if (possibleGroups.indexOf(defaultGroup) === -1) { defaultGroup = 'all'; } var schema = { type: 'object', properties: { group: { type: 'string', enum: possibleGroups, default: defaultGroup, required: true } } }; API.createData(schemaVarName, schema); let groupForm = await API.createData(varName, { group: defaultGroup }); this.options.group = groupForm.group; if (autoRefresh) { await this.refresh(filter); } let mainData = Versioning.getData(); mainData.onChange((evt) => { if (evt.jpath[0] === varName) { localStorage.setItem(cookieName, groupForm.group); this.options.group = String(groupForm.group); this.refresh(); } }); return groupForm; } } module.exports = Toc;
JavaScript
0.999991
@@ -3564,17 +3564,16 @@ getGroup -s Membersh
c50e494d519363587e7cb51e5139a9de2eec8b56
remove extra space
_server.js
_server.js
const express = require('express'); const app = express(); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); app.use(bodyParser.json()); const trailRouter = require(__dirname + '/routes/trail_routes'); const authRouter = require(__dirname + '/routes/auth_routes'); const hikeMatchRouter = require(__dirname + '/routes/hikematch_routes'); app.use('/api', trailRouter); app.use('/api', authRouter); app.use('/api', hikeMatchRouter); module.exports = exports = { server: { close: function() { throw new Error('Server not started yet!'); } }, listen: function(port, mongoString, cb) { mongoose.connect(mongoString); return this.server = app.listen(port, cb); }, close: function(cb) { this.server.close(); if (cb) cb(); } };
JavaScript
0.002319
@@ -459,17 +459,16 @@ uter);%0A%0A -%0A module.e
15ac7503b2451369ac39b1693a8d2aedb5a89698
enable QUnit.config.noglobals in tests
test/setup/environment.js
test/setup/environment.js
(function() { var sync = Backbone.sync; var ajax = Backbone.ajax; var emulateHTTP = Backbone.emulateHTTP; var emulateJSON = Backbone.emulateJSON; var history = window.history; var pushState = history.pushState; var replaceState = history.replaceState; QUnit.testStart(function() { var env = QUnit.config.current.testEnvironment; // We never want to actually call these during tests. history.pushState = history.replaceState = function(){}; // Capture ajax settings for comparison. Backbone.ajax = function(settings) { env.ajaxSettings = settings; }; // Capture the arguments to Backbone.sync for comparison. Backbone.sync = function(method, model, options) { env.syncArgs = { method: method, model: model, options: options }; sync.apply(this, arguments); }; }); QUnit.testDone(function() { Backbone.sync = sync; Backbone.ajax = ajax; Backbone.emulateHTTP = emulateHTTP; Backbone.emulateJSON = emulateJSON; history.pushState = pushState; history.replaceState = replaceState; }); })();
JavaScript
0
@@ -261,16 +261,50 @@ State;%0A%0A + QUnit.config.noglobals = true;%0A%0A QUnit.
e1ecd95dd5f429ef171719df43103c0629a78aa2
Fix Feedback modal on Enter
lib/assets/javascripts/builder/editor/feedback/feedback-button-view.js
lib/assets/javascripts/builder/editor/feedback/feedback-button-view.js
var CoreView = require('backbone/core-view'); var ViewFactory = require('builder/components/view-factory'); var template = require('./feedback-button.tpl'); var TipsyTooltipView = require('builder/components/tipsy-tooltip-view'); var feedbackModalTemplate = require('./feedback-modal.tpl'); module.exports = CoreView.extend({ tagName: 'button', className: 'EditorMenu-feedback typeform-share button js-feedback', events: { 'click': '_onClick' }, initialize: function (opts) { if (!opts.modals) throw new Error('modals is required'); this._modals = opts.modals; }, render: function () { this.clearSubViews(); this.el.setAttribute('data-mode', '1'); this.el.setAttribute('target', '_blank'); this.$el.append(template()); var tooltip = new TipsyTooltipView({ el: this.el, gravity: 'w', title: function () { return _t('feedback'); } }); this.addView(tooltip); return this; }, _onClick: function () { this._modals.once('destroyedModal', this.clean, this); this._modals.create(function (modalModel) { return ViewFactory.createByTemplate(feedbackModalTemplate, null, { className: 'Editor-feedbackModal' }); }); } });
JavaScript
0
@@ -984,32 +984,112 @@ : function () %7B%0A + this.$el.blur();%0A this._createView();%0A %7D,%0A%0A _createView: function () %7B%0A this._modals @@ -1185,22 +1185,26 @@ %7B%0A -return +var view = ViewFac @@ -1304,24 +1304,233 @@ '%0A %7D);%0A + // Set focus to the iframe after 3 seconds.%0A // This is required to enable Enter key event%0A setTimeout(function () %7B%0A view.$el.find('iframe').focus();%0A %7D, 3000);%0A return view;%0A %7D);%0A %7D%0A
8b35a8e1d9d85d4001e7d7d1e758eb4ced04723c
remove only modifier
test/simul/player.test.js
test/simul/player.test.js
import test from "ava" import { match, mock, stub, spy } from "sinon" import { xor } from "ramda" import { Chess } from "chess.js" import { WHITE, BLACK, PAWN } from "~/share/constants/chess" import Player from "~/simul/player" test("noop functions", t => { const player = new Player() t.is(typeof player.game, "function") t.is(typeof player.universe, "function") }) test.skip("login: starts playing after receiving user information", t => { const sender = spy() const user = mock() const player = new Player(sender) player.login({ user }) t.is(user, player.user) t.true(sender.called) }) test("start: receives information about a game", t => { const user = { uuid: 0 } const game = { uuid: 0, players: [ { color: WHITE, uuid: 0 }, { color: BLACK, uuid: 1 } ] } const player = new Player(() => {}) player.login(user) player.start({ game }) t.is(game, player.serializedGame) }) test("position: receives information about positions", t => { const user = { uuid: 0 } const game = { uuid: 0, players: [ { color: WHITE, uuid: 0 }, { color: BLACK, uuid: 1 } ] } const position = { fen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" } const player = new Player(() => {}) player.login(user) player.start({ game }) player.position({ game, position }) t.pass() }) test("move: always sends a move when reserve is empty", t => { const player = new Player() const sendMove = stub() player.sendMove = sendMove player.color = WHITE player.currentPosition = { reserves: { [WHITE]: { [PAWN]: 0 } } } player.move() t.true(sendMove.calledOnce) }) test("move: either sends a move or a drop", t => { const player = new Player() const sendDrop = stub() player.sendDrop = sendDrop const sendMove = stub() player.sendMove = sendMove player.color = WHITE player.currentPosition = { reserves: { [WHITE]: { [PAWN]: 1 } } } player.move() const called = xor( sendMove.calledOnce && !sendDrop.calledOnce, sendDrop.calledOnce && !sendMove.calledOnce ) t.true(called) }) test.only("sendDrop: selects a drop at random to send", t => { const send = stub() const player = new Player(send) player.color = WHITE player.chess = new Chess() player.currentPosition = { reserves: { [WHITE]: { [PAWN]: 1 } } } player.sendDrop(t) t.true(send.calledOnce) t.true(send.calledWithMatch({ action: "drop", piece: "p", square: match(/[a-h][1-8]/) })) }) test.todo("sendMove")
JavaScript
0.000018
@@ -2139,13 +2139,8 @@ test -.only (%22se
ce3670b36ec3a14c9f0e73bc53c58c4c9ddf7f0f
fix hit slop for bottom tab bar (#110)
packages/bottom-tabs/src/views/BottomTabBar.js
packages/bottom-tabs/src/views/BottomTabBar.js
/* @flow */ import React from 'react'; import { TouchableWithoutFeedback, StyleSheet, View, Platform, } from 'react-native'; import { SafeAreaView } from '@react-navigation/native'; import Animated from 'react-native-reanimated'; import CrossFadeIcon from './CrossFadeIcon'; import withDimensions from '../utils/withDimensions'; export type TabBarOptions = { activeTintColor?: string, inactiveTintColor?: string, activeBackgroundColor?: string, inactiveBackgroundColor?: string, allowFontScaling: boolean, showLabel: boolean, showIcon: boolean, labelStyle: any, tabStyle: any, adaptive?: boolean, style: any, }; type Props = TabBarOptions & { navigation: any, descriptors: any, jumpTo: any, onTabPress: any, onTabLongPress: any, getAccessibilityLabel: (props: { route: any }) => string, getButtonComponent: ({ route: any }) => any, getLabelText: ({ route: any }) => any, getTestID: (props: { route: any }) => string, renderIcon: any, dimensions: { width: number, height: number }, isLandscape: boolean, safeAreaInset: { top: string, right: string, bottom: string, left: string }, }; const majorVersion = parseInt(Platform.Version, 10); const isIos = Platform.OS === 'ios'; const isIOS11 = majorVersion >= 11 && isIos; const DEFAULT_MAX_TAB_ITEM_WIDTH = 125; class TouchableWithoutFeedbackWrapper extends React.Component<*> { render() { const { onPress, onLongPress, testID, accessibilityLabel, ...props } = this.props; return ( <TouchableWithoutFeedback onPress={onPress} onLongPress={onLongPress} testID={testID} hitSlop={{ left: 15, right: 15, top: 5, bottom: 5 }} accessibilityLabel={accessibilityLabel} > <View {...props} /> </TouchableWithoutFeedback> ); } } class TabBarBottom extends React.Component<Props> { static defaultProps = { activeTintColor: '#007AFF', activeBackgroundColor: 'transparent', inactiveTintColor: '#8E8E93', inactiveBackgroundColor: 'transparent', showLabel: true, showIcon: true, allowFontScaling: true, adaptive: isIOS11, safeAreaInset: { bottom: 'always', top: 'never' }, }; _renderLabel = ({ route, focused }) => { const { activeTintColor, inactiveTintColor, labelStyle, showLabel, showIcon, allowFontScaling, } = this.props; if (showLabel === false) { return null; } const label = this.props.getLabelText({ route }); const tintColor = focused ? activeTintColor : inactiveTintColor; if (typeof label === 'string') { return ( <Animated.Text numberOfLines={1} style={[ styles.label, { color: tintColor }, showIcon && this._shouldUseHorizontalLabels() ? styles.labelBeside : styles.labelBeneath, labelStyle, ]} allowFontScaling={allowFontScaling} > {label} </Animated.Text> ); } if (typeof label === 'function') { return label({ route, focused, tintColor }); } return label; }; _renderIcon = ({ route, focused }) => { const { navigation, activeTintColor, inactiveTintColor, renderIcon, showIcon, showLabel, } = this.props; if (showIcon === false) { return null; } const horizontal = this._shouldUseHorizontalLabels(); const activeOpacity = focused ? 1 : 0; const inactiveOpacity = focused ? 0 : 1; return ( <CrossFadeIcon route={route} horizontal={horizontal} navigation={navigation} activeOpacity={activeOpacity} inactiveOpacity={inactiveOpacity} activeTintColor={activeTintColor} inactiveTintColor={inactiveTintColor} renderIcon={renderIcon} style={[ styles.iconWithExplicitHeight, showLabel === false && !horizontal && styles.iconWithoutLabel, showLabel !== false && !horizontal && styles.iconWithLabel, ]} /> ); }; _shouldUseHorizontalLabels = () => { const { routes } = this.props.navigation.state; const { isLandscape, dimensions, adaptive, tabStyle } = this.props; if (!adaptive) { return false; } if (Platform.isPad) { let maxTabItemWidth = DEFAULT_MAX_TAB_ITEM_WIDTH; const flattenedStyle = StyleSheet.flatten(tabStyle); if (flattenedStyle) { if (typeof flattenedStyle.width === 'number') { maxTabItemWidth = flattenedStyle.width; } else if (typeof flattenedStyle.maxWidth === 'number') { maxTabItemWidth = flattenedStyle.maxWidth; } } return routes.length * maxTabItemWidth <= dimensions.width; } else { return isLandscape; } }; render() { const { navigation, activeBackgroundColor, inactiveBackgroundColor, onTabPress, onTabLongPress, safeAreaInset, style, tabStyle, } = this.props; const { routes } = navigation.state; const tabBarStyle = [ styles.tabBar, this._shouldUseHorizontalLabels() && !Platform.isPad ? styles.tabBarCompact : styles.tabBarRegular, style, ]; return ( <SafeAreaView style={tabBarStyle} forceInset={safeAreaInset}> {routes.map((route, index) => { const focused = index === navigation.state.index; const scene = { route, focused }; const accessibilityLabel = this.props.getAccessibilityLabel({ route, }); const testID = this.props.getTestID({ route }); const backgroundColor = focused ? activeBackgroundColor : inactiveBackgroundColor; const ButtonComponent = this.props.getButtonComponent({ route }) || TouchableWithoutFeedbackWrapper; return ( <ButtonComponent key={route.key} onPress={() => onTabPress({ route })} onLongPress={() => onTabLongPress({ route })} testID={testID} accessibilityLabel={accessibilityLabel} style={[ styles.tab, { backgroundColor }, this._shouldUseHorizontalLabels() ? styles.tabLandscape : styles.tabPortrait, tabStyle, ]} > {this._renderIcon(scene)} {this._renderLabel(scene)} </ButtonComponent> ); })} </SafeAreaView> ); } } const DEFAULT_HEIGHT = 49; const COMPACT_HEIGHT = 29; const styles = StyleSheet.create({ tabBar: { backgroundColor: '#fff', borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: 'rgba(0, 0, 0, .3)', flexDirection: 'row', }, tabBarCompact: { height: COMPACT_HEIGHT, }, tabBarRegular: { height: DEFAULT_HEIGHT, }, tab: { flex: 1, alignItems: isIos ? 'center' : 'stretch', }, tabPortrait: { justifyContent: 'flex-end', flexDirection: 'column', }, tabLandscape: { justifyContent: 'center', flexDirection: 'row', }, iconWithoutLabel: { flex: 1, }, iconWithLabel: { flex: 1, }, iconWithExplicitHeight: { height: Platform.isPad ? DEFAULT_HEIGHT : COMPACT_HEIGHT, }, label: { textAlign: 'center', backgroundColor: 'transparent', }, labelBeneath: { fontSize: 11, marginBottom: 1.5, }, labelBeside: { fontSize: 12, marginLeft: 15, }, }); export default withDimensions(TabBarBottom);
JavaScript
0
@@ -1690,17 +1690,17 @@ 5, top: -5 +0 , bottom
c8297bfb867668ffe2e46a356c1cd3e91db0cf60
change boolean change
callctrl.js
callctrl.js
/** * Call controller */ var callctrl = { /** * Once (call a function once) * @example once.trigger(); once.reset(); * @param {function} callback The callback * @config {boolean} bool Boolean to control actions * @return {object} Returns a object to trigger callback */ once: function once(callback){ var bool = false; return{ trigger:function(){ if(bool) return; callback(); bool = true; }, reset:function(){ bool = false; } } }, /** * Shift (callbackA can only be called once, until callbackB has been called) * @example shift.alpha(); shift.beta(); * @param {function} callbackA The callback * @param {function} callbackB The callback * @config {boolean} bool Boolean to control actions * @return {object} Returns a object to trigger callbacks */ shift: function shift(callbackA, callbackB){ var bool = false; var callbackA = callbackA || function(){}; var callbackB = callbackB || function(){}; return { alpha:function() { if(bool) return; callbackA(); bool = true; }, beta:function() { if(!bool) return; callbackB(); bool = false; } } }, /** * Toggle (toggle between callbackA and callbackB) * @example toggle.trigger(); toggle.reset(); * @param {function} callbackA The callback * @param {function} callbackB The callback * @config {boolean} bool Boolean to control actions * @return {object} Returns a object to trigger callbacks */ toggle: function toggle(callbackA, callbackB){ var bool = true; return { trigger: function() { if(bool){ callbackA(); }else{ callbackB(); } bool = !bool; }, reset:function(){ bool = true; } } } } /** @export */ module.exports = callctrl;
JavaScript
0.000045
@@ -392,35 +392,35 @@ %09%09%09%09 -callback();%0A%09%09%09%09bool = true +bool = true;%0A%09%09%09%09callback() ;%0A%09%09 @@ -1029,36 +1029,36 @@ %09%09%09%09 -callbackA();%0A%09%09%09%09bool = true +bool = true;%0A%09%09%09%09callbackA() ;%0A%09%09 @@ -1112,37 +1112,37 @@ %09%09%09%09 -callbackB();%0A%09%09%09%09bool = false +bool = false;%0A%09%09%09%09callbackB() ;%0A%09%09
4d97f0686081aeb9e7ed55ce6ab36f708d11f206
fix a setState in Searchbar/android
source/views/components/searchbar/index.android.js
source/views/components/searchbar/index.android.js
// @flow import * as React from 'react' import {StyleSheet} from 'react-native' import * as c from '../colors' import NativeSearchBar from 'react-native-searchbar' import Icon from 'react-native-vector-icons/Ionicons' const iconStyles = StyleSheet.create({ icon: { color: c.gray, }, }) const searchIcon = <Icon name="md-search" size={28} style={iconStyles.icon} /> const backIcon = <Icon name="md-arrow-back" size={28} style={iconStyles.icon} /> const closeIcon = <Icon name="md-close" size={28} style={iconStyles.icon} /> const styles = StyleSheet.create({ searchbar: { backgroundColor: c.white, height: 44, }, }) type Props = { getRef?: any, style?: any, placeholder?: string, onChangeText: string => any, onCancel: () => any, onFocus: () => any, onSearchButtonPress: string => any, searchActive: boolean, } type State = { input: string, } export class SearchBar extends React.PureComponent<Props, State> { state = { input: '', } updateText = input => { this.setState({input: input}) } onSearch = () => { this.props.onSearchButtonPress(this.state.input) } render() { const backButton = this.props.searchActive ? backIcon : searchIcon return ( <NativeSearchBar ref={this.props.getRef} backButton={backButton} closeButton={this.props.searchActive ? closeIcon : null} focusOnLayout={false} handleChangeText={this.updateText} hideX={!this.props.searchActive} onBack={this.props.onCancel} onFocus={this.props.onFocus} onSubmitEditing={this.onSearch} placeholder={this.props.placeholder || 'Search'} showOnLoad={true} style={[styles.searchbar, this.props.style]} /> ) } }
JavaScript
0.000443
@@ -996,16 +996,23 @@ setState +(() =%3E (%7Binput: @@ -1019,16 +1019,17 @@ input%7D) +) %0A%09%7D%0A%0A%09on
eddd1db3e9fcf68933cb2747ebf3e33c7c13a950
fix config, ref: a73d0504
site/bisheng.config.js
site/bisheng.config.js
const path = require('path'); const CSSSplitWebpackPlugin = require('css-split-webpack-plugin').default; const isDev = process.env.NODE_ENV === 'development'; module.exports = { port: 8001, source: { components: './components', docs: './docs', changelog: [ 'CHANGELOG.zh-CN.md', 'CHANGELOG.en-US.md', ], }, theme: './site/theme', htmlTemplate: './site/theme/static/template.html', themeConfig: { categoryOrder: { 设计原则: 2, Principles: 2, }, typeOrder: { General: 0, Layout: 1, Navigation: 2, 'Data Entry': 3, 'Data Display': 4, Feedback: 5, Localization: 6, Other: 7, }, docVersions: { '0.9.x': 'http://09x.ant.design', '0.10.x': 'http://010x.ant.design', '0.11.x': 'http://011x.ant.design', '0.12.x': 'http://012x.ant.design', '1.x': 'http://1x.ant.design', }, }, filePathMapper(filePath) { if (filePath === '/index.html') { return ['/index.html', '/index-cn.html']; } if (filePath.endsWith('/index.html')) { return [filePath, filePath.replace(/\/index\.html$/, '-cn/index.html')]; } if (filePath !== '/404.html' && filePath !== '/index-cn.html') { return [filePath, filePath.replace(/\.html$/, '-cn.html')]; } return filePath; }, doraConfig: { verbose: true, plugins: ['dora-plugin-upload'], }, webpackConfig(config) { config.resolve.alias = { 'antd/lib': path.join(process.cwd(), 'components'), antd: path.join(process.cwd(), 'index'), site: path.join(process.cwd(), 'site'), 'react-router': 'react-router/umd/ReactRouter', }; config.externals = { react: 'React', 'react-dom': 'ReactDOM', 'react-router-dom': 'ReactRouterDOM', }; config.babel.plugins.push([ require.resolve('babel-plugin-transform-runtime'), { polyfill: false, regenerator: true, }, ]); config.plugins.push(new CSSSplitWebpackPlugin({ size: 4000 })); return config; }, htmlTemplateExtraData: { isDev, }, };
JavaScript
0
@@ -1712,49 +1712,131 @@ +' react -: 'React',%0A 'react-dom' +-router-dom': 'ReactRouterDOM',%0A %7D;%0A if (isDev) %7B%0A Object.assign(config.externals, %7B%0A react : 'React DOM' @@ -1831,22 +1831,21 @@ : 'React -DOM ',%0A + 'r @@ -1841,39 +1841,32 @@ %0A 'react- -router- dom': 'ReactRout @@ -1861,34 +1861,37 @@ : 'React -Router DOM',%0A + %7D -; +);%0A %7D %0A%0A co
2527f4f6899b1ce2743f5d0efe58c65c895ab9f0
Fix TextareaEditor extends jsdoc
src/extensions/text-cell/backgrid-text-cell.js
src/extensions/text-cell/backgrid-text-cell.js
/* backgrid-text-cell http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong Licensed under the MIT @license. */ (function (window, $, _, Backbone, Backgrid) { /** Renders a form with a text area and a save button in a modal dialog. @class Backgrid.Extension.TextareaEditor @extends Backgrid.InputCellEditor */ var TextareaEditor = Backgrid.Extension.TextareaEditor = Backgrid.CellEditor.extend({ /** @property */ tagName: "div", /** @property */ className: "modal hide fade", /** @property {function(Object, ?Object=): string} template */ template: _.template('<form><div class="modal-header"><button type="button" class="close" data-dismiss="modal">&times;</button><h3><%- column.get("label") %></h3></div><div class="modal-body"><textarea cols="<%= cols %>" rows="<%= rows %>"><%- content %></textarea></div><div class="modal-footer"><input class="btn" type="submit" value="Save"/></div></form>'), /** @property */ cols: 80, /** @property */ rows: 10, /** @property */ events: { "submit": "save", "hide": "cancel", "hidden": "close" }, /** @property {Object} modalOptions The options passed to Bootstrap's modal plugin. */ modalOptions: { backdrop: false }, /** Renders a modal form dialog with a textarea, submit button and a close button. */ render: function () { this.$el.html($(this.template({ column: this.column, cols: this.cols, rows: this.rows, content: this.formatter.fromRaw(this.model.get(this.column.get("name"))) }))); this.$el.modal(this.modalOptions); return this; }, /** Event handler. Saves the text in the text area to the model. Triggers a Backbone `error` event if the value cannot be converted. Classes listening to the `error` event, usually the Cell classes, should respond appropriately, usually by rendering some kind of error feedback. @param {Event} e */ save: function (e) { if (e) e.preventDefault(); var content = this.formatter.toRaw(this.$el.find("textarea").val()); if (_.isUndefined(content) || !this.model.set(this.column.get("name"), content, {validate: true})) { this.trigger("error"); } else { this.$el.modal("hide"); } }, /** Event handler. Revert the text in the model after asking for confirmation if dirty, otherwise just close the editor. @param {Event} e */ cancel: function (e) { var content = this.formatter.toRaw(this.$el.find("textarea").val()); // Dirty if (content !== this.model.get(this.column.get("name")).replace(/\r/g, '') && window.confirm("Would you like to save your changes?")) { e.preventDefault(); e.stopPropagation(); return this.save(); } }, /** Triggers a `done` event after the modal is hidden. */ close: function () { this.trigger("done"); } }); /** TextCell is a string cell type that renders a form with a text area in a modal dialog instead of an input box editor. It is best suited for entering a large body of text. @class Backgrid.Extension.TextCell @extends Backgrid.StringCell */ var TextCell = Backgrid.Extension.TextCell = Backgrid.StringCell.extend({ /** @property */ className: "text-cell", /** @property */ editor: TextareaEditor }); }(window, jQuery, _, Backbone, Backgrid));
JavaScript
0.000001
@@ -337,13 +337,8 @@ rid. -Input Cell
4fbfd840e337df90041906964d0f7c8b8e93b0b6
Allow overriding API url from ENV (#16689)
packages/gatsby-telemetry/src/event-storage.js
packages/gatsby-telemetry/src/event-storage.js
const os = require(`os`) const path = require(`path`) const Store = require(`./store`) const fetch = require(`node-fetch`) const Configstore = require(`configstore`) const { ensureDirSync } = require(`fs-extra`) const isTruthy = require(`./is-truthy`) /* The events data collection is a spooled process that * buffers events to a local fs based buffer * which then is asynchronously flushed to the server. * This both increases the fault tolerancy and allows collection * to continue even when working offline. */ module.exports = class EventStorage { constructor() { try { this.config = new Configstore(`gatsby`, {}, { globalConfigPath: true }) } catch (e) { // This should never happen this.config = { get: key => this.config[key], set: (key, value) => (this.config[key] = value), all: this.config, path: path.join(os.tmpdir(), `gatsby`), "telemetry.enabled": true, "telemetry.machineId": `not-a-machine-id`, } } const baseDir = path.dirname(this.config.path) try { ensureDirSync(baseDir) } catch (e) { // TODO: Log this event } this.store = new Store(baseDir) this.verbose = isTruthy(process.env.GATSBY_TELEMETRY_VERBOSE) this.debugEvents = isTruthy(process.env.GATSBY_TELEMETRY_DEBUG) this.disabled = isTruthy(process.env.GATSBY_TELEMETRY_DISABLED) } isTrackingDisabled() { return this.disabled } addEvent(event) { if (this.disabled) { return } const eventString = JSON.stringify(event) if (this.debugEvents || this.verbose) { console.error(`Captured event:`, JSON.parse(eventString)) if (this.debugEvents) { // Bail because we don't want to send debug events return } } this.store.appendToBuffer(eventString + `\n`) } async sendEvents() { return this.store.startFlushEvents(async eventsData => { const events = eventsData .split(`\n`) .filter(e => e && e.length > 2) // drop empty lines .map(e => JSON.parse(e)) return this.submitEvents(events) }) } async submitEvents(events) { try { const res = await fetch(`https://analytics.gatsbyjs.com/events`, { method: `POST`, headers: { "content-type": `application/json` }, body: JSON.stringify(events), }) return res.ok } catch (e) { return false } } getConfig(key) { if (key) { return this.config.get(key) } return this.config.all } updateConfig(key, value) { return this.config.set(key, value) } }
JavaScript
0
@@ -552,16 +552,113 @@ orage %7B%0A + analyticsApi =%0A process.env.GATSBY_TELEMETRY_API %7C%7C %60https://analytics.gatsbyjs.com/events%60%0A constr @@ -2295,47 +2295,25 @@ tch( -%60https://analytics.gatsbyjs.com/events%60 +this.analyticsApi , %7B%0A
b2e3ce9cd502206c64ef617270ff37b529ada88a
add inlineStyle util test for unpopulated styles
packages/mwp-core/src/util/inlineStyle.test.js
packages/mwp-core/src/util/inlineStyle.test.js
import { getInlineStyleTags } from './inlineStyle.js'; // `simple-universal-style-loader` reades from `global`, // so we must mock the data directly in `global.__styles__` global.__styles__ = [ { id: 666, parts: [ { css: '.foo { overflow: inherit; }', media: '' } ] } ]; describe('getInlineStyleTags', () => { it('matches snapshot', () => { const result = getInlineStyleTags()[0]; expect(result).toMatchSnapshot(); }); });
JavaScript
0
@@ -166,33 +166,40 @@ yles__%60%0A -global.__styles__ +const MOCK_GLOBAL_STYLES = %5B%0A%09%7B%0A @@ -366,16 +366,58 @@ () =%3E %7B%0A +%09%09global.__styles__ = MOCK_GLOBAL_STYLES;%0A %09%09const @@ -486,16 +486,168 @@ shot();%0A +%09%09global.__styles__ = null;%0A%09%7D);%0A%09it('does not throw when global styles are not populated', () =%3E %7B%0A%09%09expect(() =%3E getInlineStyleTags()).not.toThrow();%0A %09%7D);%0A%7D);
e36d9413ea174eded30d32510d664664d8736ab4
save Project rules
js/projectRulesViewModel.js
js/projectRulesViewModel.js
function pageViewModel(gvm) { // projecttitle gvm.projecttitle = ko.observable(""); gvm.projectId = $("#projectHeader").data('value'); gvm.lastIdFromDb = 2; gvm.lastId = -1; // Page specific i18n bindings gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitleRules");}, gvm); gvm.projectRules = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRulesTitle");}, gvm); gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm); gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm); gvm.addRuleName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddRule");}, gvm); gvm.deleteRuleName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DeleteRule");}, gvm); gvm.ruleName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("RuleName");}, gvm); gvm.ruleAction = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("RuleAction");}, gvm); gvm.ruleActionDropdown = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("RuleActionDropdown");}, gvm); gvm.ruleNotOK = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("RuleNotOK");}, gvm); gvm.getProjectInfo = function() { $.getJSON('/api/project/' + gvm.projectId, function(data) { gvm.pageHeader(data[0].code + ' - ' + data[0].name); }); }; gvm.projectRules = ko.observableArray([]); gvm.projectActions = ko.observableArray([]); gvm.availableOperators = ko.observableArray([]); gvm.addRule = function() { gvm.projectRules.push(new Rule(this)); } gvm.removeRule = function(rule) { gvm.projectRules.remove(rule); } gvm.updateRule = function(rule) { gvm.projectRules.push(rule); } gvm.clearActionsStructure = function() { gvm.projectActions.destroyAll(); } gvm.clearRuleStructure = function() { gvm.projectRules.destroyAll(); } gvm.addProjectAction = function(data) { gvm.projectActions.push(data); } } function initPage() { fetchActions(); fetchProjectRules(); $(".addRuleBtn").click(function() { viewModel.addRule(); }); $(".savePageBtn").click(function() { saveProjectRules(); }); setOperators(); } function setOperators() { viewModel.availableOperators.push("="); viewModel.availableOperators.push("!="); viewModel.availableOperators.push("<"); viewModel.availableOperators.push("<="); viewModel.availableOperators.push(">"); viewModel.availableOperators.push(">="); } function removeRuleFromDb(rule) { console.log(rule.id()); var data = viewModel.projectRules.indexOf(rule); $.ajax({ type: "POST", url: "/api/projectrules/" + projectid + "/remove", data: viewModel.projectRules()[data].id(), success: function(data) { fetchProjectRules(); } }) } function fetchActions() { viewModel.clearActionsStructure(); $.getJSON("/api/projectstructure/" + projectid, function(data){ viewModel.addProjectAction(new Action(0,"Total project score")) $.each(data, function(i, item){ viewModel.addProjectAction(new Action(item.id,item.description)); $.each(item.subcompetences, function(i, subcomp){ viewModel.addProjectAction(new Action(subcomp.id,subcomp.description)); $.each(subcomp.indicators, function(i, indic){ viewModel.addProjectAction(new Action(indic.id, indic.description)); }); }); }) }); $.getJSON('/api/project/'+ projectid + '/documents', function(data) { viewModel.addProjectAction(new Action(0,"Total documents")); $.each(data, function(i, item) { viewModel.addProjectAction(new Action(item.id, "Documents: " + item.description)); }); }); } function fetchProjectRules() { viewModel.clearRuleStructure(); $.getJSON('/api/projectrules/' + projectid, function(data) { $.each(data, function(i, item) { viewModel.updateRule(new Rule(viewModel,item.id,item.name,item.action,item.operator,item.value,item.result)); }); console.log(data); }); } function saveProjectRules() { $.ajax({ type: "POST", url: "/api/projectrules/" + projectid, data: ko.toJSON(viewModel.projectRules), success: function(data){ // TODO make multilangual and with modals console.log("Saved"); console.log(data); fetchProjectRules(); }, error: function(){ console.log("Error"); } }); } /** * Rule class */ function Rule(viewmodel,id, name, action, operator, value, result) { return{ id: ko.observable(id), name: ko.observable(name), action: ko.observable(action), operator: ko.observable(operator), value: ko.observable(value), result: ko.observable(result), removeThisRule: function() { viewModel.removeRule(this); removeRuleFromDb(this); } } } /** * Action class **/ function Action(id, name) { return { id: ko.observable(id), name: ko.observable(name) } }
JavaScript
0
@@ -2823,89 +2823,8 @@ )%0A%7B%0A - console.log(rule.id());%0A var data = viewModel.projectRules.indexOf(rule);%0A @@ -2824,32 +2824,32 @@ %0A%7B%0A $.ajax(%7B%0A + type: %22P @@ -2931,38 +2931,12 @@ ta: -viewModel.projectRules()%5Bdata%5D +rule .id(
106598d4c762de59c1ad0c77ab6b9cbf508037f7
Add usage output to css-smash.
bin/css-smash.js
bin/css-smash.js
#!/usr/bin/env node var css = require("../lib/css"), nopt = require("nopt"), knownOpts = { }, shortHands = { }, usage = "Usage: css-smash [options] <cssfile1> <cssfile2> <cssfile3> ...\n\nThis compresses each of the specified css files and outputs the compressed results. By default css-smash outputs to stdout.\n\nWhere the options are:\n\n\t-o, --output\n\t\tPath to output compressed CSS to.\n\nExamples:\n\n\tcss-smash my.css\n\tcss-smash -o smashed.css file1.css file2.css", parsed = nopt(knownOpts, shortHands, process.argv); function die(why) { console.warn(why); console.warn(usage); process.exit(1); } if (!parsed.argv.remain.length) { die("No files specified!"); } console.log(parsed);
JavaScript
0
@@ -101,29 +101,77 @@ -%7D,%0A shortHands = %7B + %22usage%22 : Boolean%0A %7D,%0A shortHands = %7B%0A %22u%22 : %5B%22--usage%22%5D %0A @@ -463,16 +463,67 @@ S to.%5Cn%5C +n%5Ct-u, --usage%5Cn%5Ct%5CtDisplays this usage message.%5Cn%5C nExample @@ -692,16 +692,22 @@ warn(why +, %22%5Cn%22 );%0A con @@ -746,16 +746,80 @@ (1);%0A%7D%0A%0A +if (parsed.usage) %7B%0A console.log(usage);%0A process.exit(0);%0A%7D%0A%0A if (!par
b05d61a93b8aa7fd4cb0374009071deeed59d49d
Revert "alias ID based on pr# rather than branch name"
src/core.js
src/core.js
/* eslint-disable camelcase */ const {exec} = require('child_process'); const path = require('path'); const url = require('url'); const crypto = require('crypto'); const {fs} = require('mz'); const git = require('simple-git/promise')(); const axios = require('axios'); const log = require('./logger'); const envs = require('./envs'); if (!process.env.GITHUB_TOKEN) throw new Error('GITHUB_TOKEN must be defined in environment. Create one at https://github.com/settings/tokens'); if (!process.env.GITHUB_WEBHOOK_SECRET) throw new Error('GITHUB_WEBHOOK_SECRET must be defined in environment. Create one at https://github.com/{OWNERNAME}/{REPONAME}/settings/hooks (swap in the path to your repo)'); if (!process.env.ZEIT_API_TOKEN) throw new Error('ZEIT_API_TOKEN must be defined in environment. Create one at https://zeit.co/account/tokens'); const now = (cmd='') => { const nowBin = path.resolve('./node_modules/now/build/bin/now'); return `${nowBin} ${cmd} --token ${process.env.ZEIT_API_TOKEN}`; }; const githubApi = axios.create({ headers: { Authorization: `token ${process.env.GITHUB_TOKEN}`, Accept: 'application/vnd.github.ant-man-preview+json, application/json' } }); function stage(cwd, {alias}) { return new Promise((resolve, reject) => { let url, aliasError; const nowProc = exec(now(envs()), {cwd}); nowProc.stderr.on('data', (error) => reject(new Error(error))); nowProc.stdout.on('data', (data) => {if (!url) url = data;}); nowProc.stdout.on('close', () => { if (!url) return reject(new Error('Deployment failed')); log.info(`> Setting ${url} to alias ${alias}`); const aliasProc = exec(now(`alias set ${url} ${alias}`), {cwd}); aliasProc.stderr.on('data', (error) => {aliasError = error;}); aliasProc.on('close', () => { if (aliasError) return reject(new Error(aliasError)); log.info(`> Alias ready ${alias}`); resolve(alias); }); }); }); } async function sync(cloneUrl, localDirectory, {ref, checkout}) { try { await fs.stat(localDirectory); } catch (error) { log.info('> Cloning repository...'); await git.clone(cloneUrl, localDirectory, ['--depth=1', `--branch=${ref}`]); } await git.cwd(localDirectory); log.info(`> Fetching ${ref}...`); await git.fetch('origin', ref); log.info(`> Checking out ${ref}@${checkout}...`); await git.checkout(checkout); } function UnsafeWebhookPayloadError(language) { const asJson = { error: { type: 'fatal', name: 'UNSAFE_WEBHOOK_PAYLOAD', message: `We could not cryptograhpically verify the payload sent to the stage-ci webhook from ${language.provider.name}. Make sure your ${language.provider.name} environment variable matches the Secret field in your ${language.provider.name} webhook config ${language.provider.webhookLocationInstructions}.` } }; this.message = asJson.error.message; this.name = asJson.error.name; this.asJson = asJson; } function github({headers, body}) { // Don't log but give a very specific error. We don't want to fill the logs. if (!isGithubRequestCrypographicallySafe({headers, body, secret: process.env.GITHUB_WEBHOOK_SECRET})) throw new UnsafeWebhookPayloadError({ provider: { name: 'Github', environmentVariable: 'GITHUB_WEBHOOK_SECRET', webhookLocationInstructions: 'at https://github.com/{OWNERNAME}/{REPONAME}/settings/hooks (swap in the path to your repo)' } }); if (!['opened', 'synchronize'].includes(body.action)) return {success: false}; const {repository, pull_request} = body; const {ref, sha} = pull_request.head; const {deployments_url} = repository; const aliasID = `${repository.name.replace(/[^A-Z0-9]/gi, '-')}-pr${pull_request.number}`; let deploymentId; return { ref, sha, success: true, name: repository.full_name, alias: `https://${aliasID}.now.sh`, cloneUrl: url.format(Object.assign( url.parse(pull_request.head.repo.clone_url), {auth: process.env.GITHUB_TOKEN} )), deploy: async () => { // https://developer.github.com/v3/repos/deployments/#create-a-deployment-status // https://developer.github.com/changes/2016-04-06-deployment-and-deployment-status-enhancements/ const result = await githubApi.post(deployments_url, { ref: sha, auto_merge: false, required_contexts: [], transient_environment: true, environment: 'PR staging' }); deploymentId = result.data.id; }, setStatus: (state, description, targetUrl) => { log.info(`> Setting GitHub status to "${state}"...`); return githubApi.post(`${deployments_url}/${deploymentId}/statuses`, { state, description, environment_url: targetUrl, target_url: targetUrl, auto_inactive: false }); } }; } function isGithubRequestCrypographicallySafe({headers, body, secret}) { const blob = JSON.stringify(body); const hmac = crypto.createHmac('sha1', secret); const ourSignature = `sha1=${hmac.update(blob).digest('hex')}`; const theirSignature = headers['x-hub-signature']; const bufferA = Buffer.from(ourSignature, 'utf8'); const bufferB = Buffer.from(theirSignature, 'utf8'); return crypto.timingSafeEqual(bufferA, bufferB); } module.exports = { stage, sync, github };
JavaScript
0
@@ -3672,16 +3672,56 @@ sitory;%0A + const INVALID_URI_CHARACTERS = /%5C//g;%0A const @@ -3782,31 +3782,50 @@ ')%7D- -pr$%7Bpull_request.number +$%7Bref.replace(INVALID_URI_CHARACTERS, '-') %7D%60;%0A
bea39b3731cfc90530056cb6eb14961d1e48e4e9
fix MultipleOptionsSearchBarCmp click option is missing the context
invenio_search_ui/assets/semantic-ui/js/invenio_search_ui/components/MultipleOptionsSearchBar.js
invenio_search_ui/assets/semantic-ui/js/invenio_search_ui/components/MultipleOptionsSearchBar.js
/* * This file is part of Invenio. * Copyright (C) 2022 CERN. * * Invenio is free software; you can redistribute it and/or modify it * under the terms of the MIT License; see LICENSE file for more details. */ import React, { Component } from "react"; import { withState } from "react-searchkit"; import { Search, Label, Button, Icon } from "semantic-ui-react"; import { i18next } from "@translations/invenio_search_ui/i18next"; import _isEmpty from "lodash/isEmpty"; import PropTypes from "prop-types"; const resultRenderer = ({ text }, queryString) => { let searchOption = "..."; if (!_isEmpty(queryString)) { searchOption = queryString; } return ( <div className="flex"> <div className="truncated pt-5">{searchOption}</div> <Label className="right-floated">{text}</Label> </div> ); }; export class MultipleOptionsSearchBar extends Component { /** Multiple options searchbar to be used as a standalone component */ constructor(props) { super(props); this.state = { queryString: "", }; } handleOnSearchClick = () => { const { options, defaultOption } = this.props; const { queryString } = this.state; let destinationURL = options[0]?.value || defaultOption.value; window.location = `${destinationURL}?q=${queryString}`; }; handleOnResultSelect = (e, { result }) => { const { queryString } = this.state; const { value: url } = result; window.location = `${url}?q=${queryString}`; }; handleOnSearchChange = (e, { value }) => { this.setState({ queryString: value }); }; render() { const { placeholder, options } = this.props; const { queryString } = this.state; const button = ( <Button icon className="right-floated search" onClick={this.handleOnSearchClick} > <Icon name="search" /> </Button> ); return ( <Search fluid onResultSelect={this.handleOnResultSelect} onSearchChange={this.handleOnSearchChange} resultRenderer={(props) => resultRenderer(props, queryString)} results={options} value={queryString} placeholder={placeholder} minCharacters={0} icon={button} className="right-angle-search-content" selectFirstResult /> ); } } MultipleOptionsSearchBar.propTypes = { options: PropTypes.array.isRequired, placeholder: PropTypes.string, defaultOption: PropTypes.shape({ key: PropTypes.string, text: PropTypes.string, value: PropTypes.string, }), }; MultipleOptionsSearchBar.defaultProps = { placeholder: i18next.t("Search records..."), defaultOption: { key: "records", text: i18next.t("All records"), value: "/search", }, }; export class MultipleOptionsSearchBarCmp extends Component { /** Multiple options searchbar to be wrapped with RSK context */ onBtnSearchClick = () => { const { queryString, updateQueryState, currentQueryState } = this.props; const { options, defaultOption } = this.props; let destinationURL = options[0]?.value || defaultOption.value; if (window.location.pathname === destinationURL) { updateQueryState({ ...currentQueryState, queryString }); } else { window.location = `${destinationURL}?q=${queryString}`; } }; handleOnSearchChange = (e, { value }) => { const { onInputChange } = this.props; onInputChange(value); }; render() { const { placeholder, queryString, options } = this.props; const button = ( <Button icon className="right-floated search" onClick={this.onBtnSearchClick} > <Icon name="search" /> </Button> ); return ( <Search fluid onResultSelect={this.onBtnSearchClick} onSearchChange={this.handleOnSearchChange} resultRenderer={(props) => resultRenderer(props, queryString)} results={options} value={queryString} placeholder={placeholder} className="right-angle-search-content" selectFirstResult icon={button} minCharacters={0} /> ); } } MultipleOptionsSearchBarCmp.propTypes = { options: PropTypes.array.isRequired, queryString: PropTypes.string.isRequired, updateQueryState: PropTypes.func.isRequired, onInputChange: PropTypes.func.isRequired, placeholder: PropTypes.string, defaultOption: PropTypes.shape({ key: PropTypes.string, text: PropTypes.string, value: PropTypes.string, }), }; MultipleOptionsSearchBarCmp.defaultProps = { placeholder: i18next.t("Search records..."), // defaultOption: { // key: "records", // text: i18next.t("All records"), // value: "/search", // }, }; export const MultipleOptionsSearchBarRSK = withState( MultipleOptionsSearchBarCmp );
JavaScript
0
@@ -2902,39 +2902,52 @@ nSearchClick = ( +e, %7B result %7D ) =%3E %7B%0A - const %7B quer @@ -3014,33 +3014,24 @@ %0A const %7B - options, defaultOpti @@ -3049,26 +3049,63 @@ .props;%0A -le +const %7B value: url %7D = result;%0A cons t destinatio @@ -3111,33 +3111,19 @@ onURL = -options%5B0%5D?.value +url %7C%7C defa @@ -4644,19 +4644,16 @@ ...%22),%0A - // default @@ -4663,19 +4663,16 @@ ion: %7B%0A - // key: @@ -4684,21 +4684,18 @@ rds%22,%0A -// - text: i1 @@ -4719,19 +4719,16 @@ rds%22),%0A - // value @@ -4745,11 +4745,8 @@ %22,%0A - // %7D,%0A
95af8473a3d013806f9b7ec69cdf5285269c99af
Enable "no-useless-concat" rule, see https://github.com/phetsims/chipper/issues/814
js/stringSubmissionQueue.js
js/stringSubmissionQueue.js
// Copyright 2015-2020, University of Colorado Boulder /** * An asynchronous (async.queue) queue with a concurrency of one (meaning that only one task is executed at a time) * that is used to serialize submissions of strings for a translation. * * @author Aaron Davis * @author John Blanco */ 'use strict'; // modules const _ = require( 'lodash' ); // eslint-disable-line const longTermStringStorage = require( './longTermStringStorage' ); const { Pool } = require( 'pg' ); // eslint-disable-line const requestBuild = require( './requestBuild' ); const RosettaConstants = require( './RosettaConstants' ); const winston = require( 'winston' ); // for debug purposes, it is possible to configure Rosetta to skip sending build requests to the build server const SEND_BUILD_REQUESTS = global.config.sendBuildRequests === undefined ? true : global.config.sendBuildRequests; /** * task queue into which translation requests are pushed * @public */ module.exports.stringSubmissionQueue = async ( req, res ) => { const { targetLocale } = req.params; const { simName } = req.params; const userId = ( req.session.userId ) ? req.session.userId : 0; // Define an object that will contain the sets of strings that need to be stored. The keys for this object will be // the sim or library name, aka the 'repo', and the strings will be in the form needed for long term string storage. // Multiple sims and/or libraries may need to be committed as part of a single translation due to shared code. const stringSets = {}; // flags for checking if strings have changed for a given sim or lib const stringsChangedFlags = {}; // Extract the string sets from the submitted translation. The body of the request (req.body) contains an object with // all of the strings submitted through the POST request from the translation utility. The keys are in the form // "[repository] [key]" and the values are the strings, for example: "chains chains.title": "Chains". _.keys( await req.body ).forEach( submittedStringKey => { // data submitted is in the form "[repository] [key]", for example "area-builder area-builder.title" const repoAndStringKey = submittedStringKey.split( ' ' ); const repo = repoAndStringKey[ 0 ]; const stringKey = repoAndStringKey[ 1 ]; // if this sim or lib isn't represent yet, add it if ( !stringSets[ repo ] ) { stringSets[ repo ] = {}; } // get the value of the string let stringValue = req.body[ submittedStringKey ]; // Handle any embedded line feeds. There is some history here, please see // https://github.com/phetsims/rosetta/issues/144 and https://github.com/phetsims/rosetta/issues/207. The best // thing to do going forward is to always use <br> in multi-line strings instead of '\n', this code is here to // handle older sims in which '\n' was used in multi-line strings. if ( stringValue.indexOf( '\\n' ) !== -1 ) { winston.info( 'replacing line feed sequence in string from repo ' + repo + ' with key ' + stringKey ); stringValue = stringValue.replace( /\\n/g, '\n' ); } // check if the string is already in translatedStrings to get the history if it exists const translatedString = req.session.translatedStrings[ targetLocale ] && req.session.translatedStrings[ targetLocale ][ repo ] && req.session.translatedStrings[ targetLocale ][ repo ][ stringKey ]; let history = translatedString && translatedString.history; const oldValue = ( history && history.length ) ? history[ history.length - 1 ].newValue : ''; // only add the update if the value has changed if ( oldValue !== stringValue ) { const newHistoryEntry = { userId: ( req.session.userId ) ? req.session.userId : 'phet-test', timestamp: Date.now(), oldValue: oldValue, newValue: stringValue }; if ( history ) { history.push( newHistoryEntry ); } else { history = [ newHistoryEntry ]; } stringSets[ repo ][ stringKey ] = { value: stringValue, history: history }; // set flag indicating that a string has changed if ( !stringsChangedFlags[ repo ] ) { stringsChangedFlags[ repo ] = true; } } else if ( translatedString ) { stringSets[ repo ][ stringKey ] = translatedString; } } ); // make a list of only the string sets that have changed const changedStringSets = _.pick( stringSets, _.keys( stringsChangedFlags ) ); // save the modified strings to long-term storage const stringSavePromises = []; _.keys( changedStringSets ).forEach( simOrLibName => { stringSavePromises.push( longTermStringStorage.saveTranslatedStrings( simOrLibName, targetLocale, changedStringSets[ simOrLibName ] ) ); } ); // wait for all the save operations to complete try { // wait for all the save operations to complete await Promise.all( stringSavePromises ); } catch( err ) { winston.error( 'error while submitting strings, err = ' + err ); winston.info( 'rendering error page' ); // render an error page res.render( 'error.html', { title: 'Translation Utility Error', message: 'An error occurred when trying to save the translated strings.', errorDetails: err, timestamp: new Date().getTime() } ); // bail out return; } try { // request a build of the new translation (if enabled) if ( SEND_BUILD_REQUESTS ) { await requestBuild( simName, targetLocale, userId ); } else { winston.info( 'build requests for translations are disabled, skipping' ); } // clear out short-term storage, since these strings have now been successfully stored in the long-term area await deleteStringsFromDB( userId, targetLocale, _.keys( stringSets ) ).catch(); // render the page that indicates that the translation was successfully submitted res.render( 'translation-submit.html', { title: 'Translation submitted', simName: simName, targetLocale: targetLocale } ); } catch( err ) { winston.error( 'error while requesting build and clearing out DB, err = ' + err ); winston.info( 'rendering error page' ); // render an error page res.render( 'error.html', { title: 'Translation Utility Error', message: 'An error occurred when trying to build the new simulation.', errorDetails: err, timestamp: new Date().getTime() } ); } }; /** * delete the strings that are stored in short-term storage * {string} userID * {string} locale * {string[]} simOrLibNames * @private */ async function deleteStringsFromDB( userID, locale, simOrLibNames ) { winston.info( 'removing strings from short term storage for userID = ' + userID + ', sim/libs = ' + simOrLibNames + ', locale = ' + locale ); // create a string with all the repo names that can be used in the SQL query let simOrLibNamesString = ''; simOrLibNames.forEach( ( simOrLibName, index ) => { simOrLibNamesString += 'repository = ' + '\'' + simOrLibName + '\''; if ( index < simOrLibNames.length - 1 ) { simOrLibNamesString += ' OR '; } } ); const deleteQuery = 'DELETE FROM saved_translations WHERE user_id = $1 AND locale = $2 AND (' + simOrLibNamesString + ')'; const pool = new Pool( { connectionTimeoutMillis: RosettaConstants.DATABASE_QUERY_TIMEOUT } ); try { winston.info( 'attempting query: ' + deleteQuery ); await pool.query( deleteQuery, [ userID, locale ] ); winston.info( 'deletion of strings succeeded' ); } catch( err ) { winston.error( 'deletion of strings failed, err = ' + err ); } }
JavaScript
0.000001
@@ -7128,13 +7128,8 @@ y = -' + ' %5C''
3848d28f3141a78fab22bf80883bd9396269a7af
clean ticker element doc
packages/elements/animation-ticker/index.js
packages/elements/animation-ticker/index.js
import Ticker from '/node_modules/@damienmortini/core/util/Ticker.js'; const PAUSED_BY_USER = 1; const PAUSED_BY_INTERSECTION = 2; const PAUSED_BY_VISIBILITY = 4; const PAUSED_BY_BLUR = 8; const PAUSED_BY_CONNECTION = 16; /** * @customElement * Element triggering requestAnimationFrame on it's update method. */ export default class AnimationTickerElement extends HTMLElement { constructor() { super(); this.noautoplay = false; this._updateBinded = this.update.bind(this); this._pauseFlag = 0; document.addEventListener('visibilitychange', () => { if (document.hidden) { this._pauseFlag |= PAUSED_BY_VISIBILITY; } else { this._pauseFlag &= ~PAUSED_BY_VISIBILITY; } }); const observer = new IntersectionObserver((entries) => { let isIntersecting = false; for (const entry of entries) { if (entry.isIntersecting) { isIntersecting = true; } } if (isIntersecting) { this._pauseFlag &= ~PAUSED_BY_INTERSECTION; } else { this._pauseFlag |= PAUSED_BY_INTERSECTION; } }); observer.observe(this); window.addEventListener('blur', () => { this._pauseFlag |= PAUSED_BY_BLUR; }); window.addEventListener('focus', () => { this._pauseFlag &= ~PAUSED_BY_BLUR; }); } connectedCallback() { this._pauseFlag &= ~PAUSED_BY_CONNECTION; if (!document.hasFocus()) { this._pauseFlag |= PAUSED_BY_BLUR; } if (this.noautoplay) { this._pauseFlag |= PAUSED_BY_USER; } this.update(); } disconnectedCallback() { this._pauseFlag |= PAUSED_BY_CONNECTION; } get _pauseFlag() { return this.__pauseFlag; } set _pauseFlag(value) { if (this.__pauseFlag === value) { return; } this.__pauseFlag = value; if (this.__pauseFlag) { Ticker.delete(this._updateBinded); } else { Ticker.add(this._updateBinded); } } /** * Indicating whether element should automatically play * @type {Boolean} */ get noautoplay() { return this.hasAttribute('noautoplay'); } set noautoplay(value) { if (value) { this.setAttribute('noautoplay', ''); } else { this.removeAttribute('noautoplay'); } } /** * Play element animation */ play() { this._pauseFlag &= ~PAUSED_BY_USER; } /** * Pause element animation */ pause() { this._pauseFlag |= PAUSED_BY_USER; } /** * Tells whether the media element is paused. * @type {Boolean} * @readonly */ get paused() { return !!this._pauseFlag; } update() { } }
JavaScript
0.000004
@@ -225,26 +225,8 @@ /**%0A - * @customElement%0A * E @@ -294,25 +294,30 @@ .%0A * -/%0Aexport default + @hideconstructor%0A */%0A clas @@ -1960,60 +1960,54 @@ * -Indicating whether element should automa +Automatically pause element at ini ti -c al -ly play +ization. %0A @@ -2271,34 +2271,25 @@ Play element - animation +. %0A */%0A pla @@ -2367,18 +2367,9 @@ ment - animation +. %0A @@ -2460,14 +2460,8 @@ the -media elem @@ -2584,10 +2584,50 @@ e() %7B %7D%0A - %7D%0A +%0Aexport default AnimationTickerElement;%0A
d58f61c5b9316e082d711362b5e1c804fb603b3f
correct a mistake on moneypush.js
lib/moneypush.js
lib/moneypush.js
http = require('http'); URLSTREAM = 'stream.moneypush.com'; PORTSTREAM = 3002; exports.GetStream = function(key, money, CallBack) { var i, m, moneyURL, options, _i, _len; moneyURL = ''; if (money === 'AllSymbol') { moneyURL = 'AllSymbol'; } else { i = 0; for (_i = 0, _len = money.length; _i < _len; _i++) { m = money[_i]; if (i === 0) { moneyURL = m.replace("/", "_"); i = 1; } else { moneyURL = moneyURL + '%2C' + m.replace("/", "_"); } } } options = { hostname: URLSTREAM, port: PORTSTREAM, path: '/SubSymbol/' + key + '/' + moneyURL, method: 'GET' }; return http.get(options, function(res) { res.setEncoding('utf8'); return res.on('data', function(data) { return CallBack(JSON.parse(data)); }); }); };
JavaScript
0.000312
@@ -1,11 +1,16 @@ +var http = - +%09%09 requ @@ -34,17 +34,18 @@ STREAM = - +%09%09 'stream. @@ -60,17 +60,16 @@ h.com';%0A -%0A PORTSTRE @@ -72,17 +72,17 @@ STREAM = - +%09 3002;%0A%0Ae @@ -174,16 +174,37 @@ , _len;%0A + var dataTmp, data;%0A moneyU @@ -743,16 +743,31 @@ utf8');%0A +%09dataTmp = '';%0A retu @@ -801,52 +801,239 @@ data +_ ) %7B%0A +%09 - return CallBack(JSON.parse(data)); +if (data_ === undefined) return ;%0A%09 dataTmp = dataTmp + data_.trim();%0A%09 if (dataTmp%5B0%5D === %22%7B%22 && dataTmp%5BdataTmp.length - 1%5D === %22%7D%22)%0A%09 %7B%0A%09%09 data = JSON.parse(dataTmp);%0A%09%09 dataTmp = '';%0A%09%09 return CallBack(data);%0A%09 %7D %0A @@ -1045,8 +1045,9 @@ %7D);%0A%7D; +%0A
d0ef213eba6da39cf0786aef92eedfa675aa1e9e
Sort the maps country selector items
Dashboard/app/js/lib/controllers/maps-controllers.js
Dashboard/app/js/lib/controllers/maps-controllers.js
/*jshint browser:true, jquery:true */ /*global Ember, FLOW */ FLOW.placemarkControl = Ember.ArrayController.create({ content: null, populate: function () { this.set('content', FLOW.store.findAll(FLOW.Placemark)); } }); FLOW.placemarkDetailControl = Ember.ArrayController.create({ content: null, selectedDetailImage: null, selectedPointCode: null, populate: function (placemarkId) { if(typeof placemarkId === 'undefined') { this.set('content', null); } else { this.set('content', FLOW.store.find(FLOW.PlacemarkDetail, { "placemarkId": placemarkId })); } } }); FLOW.countryControl = Ember.Object.create({ content: null, init: function() { this._super(); this.set('content', this.getContent(Ember.ENV.countries)); }, getContent: function (countries) { var countryList = []; for (var i = 0; i < countries.length; i++) { countryList.push( Ember.Object.create({ label: countries[i].label, lat: countries[i].lat, lon: countries[i].lon, zoom: countries[i].zoom }) ); } return countryList; } });
JavaScript
0.999973
@@ -857,16 +857,157 @@ = %5B%5D;%0A%0A + countries.sort(function (a, b) %7B%0A if (a.label %3C b.label) return -1;%0A if (a.label %3E b.label) return 1;%0A return 0;%0A %7D);%0A%0A for
5a0122b03269b5cf6ffa11eee3a232e169c06734
modify annyang
MMM-Hello-Mirror.js
MMM-Hello-Mirror.js
/* Magic Mirror * Module: MMM-Hello-Mirror * * By Mathias Kaniut * MIT Licensed */ Module.register("MMM-Hello-Mirror", { // Default module config. defaults: { language: "de", voice: "Deutsch Female", wakeUp: "Hallo (magischer) Spiegel", animationSpeed: 2000, debug: true, broadcastEvents: true }, // Load required additional scripts getScripts: function() { return [ //'//cdnjs.cloudflare.com/ajax/libs/annyang/2.6.0/annyang.min.js', // annyang! SpeechRecognition 'script/annyang.min.js', // annyang! SpeechRecognition (modified) 'http://code.responsivevoice.org/responsivevoice.js', // ResponsiveVoice 'moment.js' // Parse, validate, manipulate, and display dates in JavaScript ]; }, // Define additional styles getStyles: function() { return [ "font-awesome.css", this.file('css/MMM-Hello-Mirror.css') ]; }, // Request translation files getTranslations: function() { return { en: "translations/en.json", de: "translations/de.json" }; }, textMessage: "", // Called when all modules are loaded an the system is ready to boot up start: function() { if (responsiveVoice) { responsiveVoice.setDefaultVoice(this.config.voice); } if (annyang) { Log.info("Starting module: " + this.name); var self = this; // Set language for date object moment.locale(this.config.language); // Set the debug mode annyang.debug(this.config.debug); // Set the language of annyang annyang.setLanguage(this.config.language); // Define the commands var sentence = self.config.wakeUp + ' *command'; var commands = { sentence: function(command) { Log.info('Voice command recognized in module ' + self.name + ': ' + command); if (self.config.broadcastEvents) { self.sendNotification("VOICE_COMMAND", command); } if (responsiveVoice) { responsiveVoice.speak( self.translate("VOICE_ACCEPTED") ); } } }; // Add the commands to annyang annyang.addCommands(commands); // Add callback functions for errors annyang.addCallback('error', function() { Log.error('ERROR in module ' + self.name + ': ' + 'Speech Recognition fails because an undefined error occured'); }); annyang.addCallback('errorNetwork', function() { Log.error('ERROR in module ' + self.name + ': ' + 'Speech Recognition fails because of a network error'); }); annyang.addCallback('errorPermissionBlocked', function() { Log.error('ERROR in module ' + self.name + ': ' + 'Browser blocks the permission request to use Speech Recognition'); }); annyang.addCallback('errorPermissionDenied', function() { Log.error('ERROR in module ' + self.name + ': ' + 'The user blocks the permission request to use Speech Recognition'); }); annyang.addCallback('resultNoMatch', function(phrases) { Log.error('ERROR in module ' + self.name + ': ' + 'No match for voice command ' + phrases); }); annyang.addCallback('soundstart', function() { self.textMessage = self.translate("HEAR_YOU"); self.updateDom(self.config.animationSpeed); }); annyang.addCallback('result', function() { self.textMessage = ""; self.updateDom(self.config.animationSpeed); }); // Start listening annyang.start(); } else { Log.error('ERROR in module ' + self.name + ': ' + 'Google Speech Recognizer is down :('); } }, // Override dom generator. getDom: function() { var wrapper = document.createElement("div"); wrapper.className = "small light"; wrapper.innerHTML = this.textMessage; return wrapper; }, });
JavaScript
0.000882
@@ -546,16 +546,26 @@ +this.file( 'script/ @@ -575,36 +575,26 @@ yang.min.js' +) , -
951d5661367f6719d200a6c7ef10b655b690bdca
Update test-main-leaflet.js
test/test-main-leaflet.js
test/test-main-leaflet.js
/*leaflet -- control*/ // import './leaflet/control/ChangeTileVersionSpec.js'; /*leaflet -- core*/ import './leaflet/core/NonEarthCRSSpec.js'; import './leaflet/core/TransformUtilSpec.js'; import './leaflet/core/Proj4LeafletSpec.js'; /*leaflet -- mapping*/ // import './leaflet/mapping/ImageMapLayerSpec.js'; import './leaflet/mapping/TiledMapLayerSpec.js'; import './leaflet/mapping/TileLayer.WMTSSpec.js'; // import './leaflet/mapping/WebMapSpec.js'; /*leaflet -- overlay*/ import './leaflet/overlay/EchartsLayerSpec.js'; /*deck相关测试未通过,待解决后打开注释*/ import './leaflet/overlay/graphic/GraphicSpec.js'; import './leaflet/overlay/GraphicLayerSpec.js'; import './leaflet/overlay/graphic/CloverStyleSpec'; import './leaflet/overlay/GraphThemeLayerSpec.js'; import './leaflet/overlay/HeatMapLayerSpec.js'; import './leaflet/overlay/LabelThemeLayerSpec.js'; import './leaflet/overlay/MapVLayerSpec.js'; import './leaflet/overlay/RangeThemeLayerSpec.js'; import './leaflet/overlay/RankSymbolThemeLayerSpec.js'; import './leaflet/overlay/TileVectorLayerSpec.js'; import './leaflet/overlay/UniqueThemeLayerSpec.js'; import './leaflet/overlay/vectortile/PointSymbolizerSpec.js'; import './leaflet/overlay/vectortile/TextSymbolizerSpec.js'; import './leaflet/overlay/TurfLayerSpec.js'; import './leaflet/overlay/mapv/MapVRendererSpec.js'; /**leaflet -- services**/ import './leaflet/services/AddressMatchServiceSpec.js'; import './leaflet/services/BufferAnalysisSpec.js'; import './leaflet/services/DensityAnalysisSpec.js'; import './leaflet/services/EditFeaturesLineSpec.js'; import './leaflet/services/EditFeaturesPointSpec.js'; import './leaflet/services/EditFeaturesRegionSpec.js'; import './leaflet/services/FieldServiceSpec.js'; import './leaflet/services/GenerateSpatialDataSpec.js'; import './leaflet/services/GeoRelationAnalysisSpec.js'; import './leaflet/services/GeometryBatchAnalysisSpec.js'; import './leaflet/services/GetFeaturesByBoundsSpec.js'; import './leaflet/services/GetFeaturesByBufferSpec.js'; import './leaflet/services/GetFeaturesByGeometrySpec.js'; import './leaflet/services/GetFeaturesByIDsSpec.js'; import './leaflet/services/GetFeaturesBySQLSpec.js'; import './leaflet/services/GridCellInfosServiceSpec.js'; import './leaflet/services/InterpolationAnalysisSpec.js'; import './leaflet/services/LayerInfoServiceSpec.js'; import './leaflet/services/MapServiceSpec.js'; import './leaflet/services/MathExpressionAnalysisSpec.js'; import './leaflet/services/MeasureServiceSpec.js'; import './leaflet/services/NetworkAnalystServiceSpec.js'; import './leaflet/services/OverlayAnalysisSpec.js'; import './leaflet/services/ProcessingServiceSpec.js'; import './leaflet/services/QueryByBoundsSpec.js'; import './leaflet/services/QueryByDistanceSpec.js'; import './leaflet/services/QueryByGeometrySpec.js'; import './leaflet/services/QueryBySQLSpec.js'; import './leaflet/services/RouteCalculateMeasureSpec.js'; import './leaflet/services/RouteLocateSpec.js'; import './leaflet/services/SurfaceAnalysisSpec.js'; import './leaflet/services/TerrainCurvatureCalculateSpec.js'; import './leaflet/services/ThemeServiceSpec.js'; import './leaflet/services/ThiessenAnalysisSpec.js'; import './leaflet/services/TrafficTransferAnalystServiceSpec.js'; /* component */ import './leaflet/components/openfile/OpenFileViewSpec.js'; import './leaflet/components/dataservicequery/DataServiceQueryViewSpec.js'; import './leaflet/components/distributedanalysis/DistributedAnalysisViewSpec.js'; import './leaflet/components/clientcomputation/ClientComputationViewSpec.js'; import './leaflet/components/search/SearchViewSpec.js'; import './leaflet/components/dataflow/DataFlowViewSpec.js'; import './leaflet/overlay/DataFlowLayerSpec.js';
JavaScript
0
@@ -473,16 +473,19 @@ rlay*/%0A%0A +// import '
dc37c5be47190d6a1597d484e41d75dc750ac707
Fix search query parsing
packages/telescope-search/lib/client/routes.js
packages/telescope-search/lib/client/routes.js
adminNav.push({ route: 'searchLogs', label: 'Search Logs' }); Meteor.startup(function () { PostsSearchController = PostsListController.extend({ view: 'search', onBeforeAction: function() { if ("q" in this.params) { Session.set("searchQuery", this.params.q); } this.next(); } }); Router.onBeforeAction(Router._filters.isAdmin, {only: ['logs']}); // Search Router.route('/search/:limit?', { name: 'search', controller: PostsSearchController }); // Search Logs Router.route('/logs/:limit?', { name: 'searchLogs', waitOn: function () { var limit = this.params.limit || 100; if(Meteor.isClient) { Session.set('logsLimit', limit); } return Meteor.subscribe('searches', limit); }, data: function () { return Searches.find({}, {sort: {timestamp: -1}}); }, fastRender: true }); });
JavaScript
0.898907
@@ -227,16 +227,22 @@ s.params +.query ) %7B%0A @@ -284,16 +284,22 @@ .params. +query. q);%0A
5298ea88afe35ba9f7b51dbe0a307c5d22949b8f
Remove unnecessary formatting from 'stylish'
lib/formatters/stylish.js
lib/formatters/stylish.js
/** * @fileoverview Stylish reporter * @author Matthew Harrison-Jones & ESLint (https://github.com/eslint/eslint/blob/113c81f49712e3d86db1b112c37ce3b900f6c25e/lib/formatters/stylish.js) */ 'use strict' var chalk = require('chalk'), table = require('text-table') //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ /** * Given a word and a count, append an s if count is not one. * @param {string} word A word in its singular form. * @param {int} count A number controlling whether word should be pluralized. * @returns {string} The original word with an s on the end if count is not one. */ function pluralize(word, count) { return (count === 1 ? word : word + 's') } //------------------------------------------------------------------------------ // Public Interface //------------------------------------------------------------------------------ module.exports = function(results) { var output = '\n', total = 0, errors = 0, warnings = 0, summaryColor = 'yellow' results.forEach(function(result) { var messages = result.messages if (messages.length === 0) { return } total += messages.length output += chalk.underline(result.url + ' — ' + result.summary) + '\n' output += table( messages.map(function(message) { var messageType if (message.severity === 2) { messageType = chalk.red('error') summaryColor = 'red' errors++ } else { messageType = chalk.yellow('warning') warnings++ } return [ '', messageType, message.message.replace(/\.$/, ''), chalk.dim(message.ruleId || '') ] }), { align: ['', 'r', 'l'], stringLength: function(str) { return chalk.stripColor(str).length } } ).split('\n').map(function(el) { return el.replace(/(\d+)\s+(\d+)/, function(m, p1, p2) { return chalk.dim(p1 + ':' + p2) }) }).join('\n') + '\n\n' }) if (total > 0) { output += chalk[summaryColor].bold([ '\u2716 ', total, pluralize(' problem', total), ' (', errors, pluralize(' error', errors), ', ', warnings, pluralize(' warning', warnings), ')\n' ].join('')) } return total > 0 ? output : '' }
JavaScript
0.000026
@@ -2229,193 +2229,8 @@ ) -.split('%5Cn').map(function(el) %7B%0A return el.replace(/(%5Cd+)%5Cs+(%5Cd+)/, function(m, p1, p2) %7B%0A return chalk.dim(p1 + ':' + p2)%0A %7D)%0A %7D).join('%5Cn') + '
593d68c3664c01b730c97e1e979eb320f79daa9f
Update test-main-leaflet.js
test/test-main-leaflet.js
test/test-main-leaflet.js
/*leaflet -- control*/ // import './leaflet/control/ChangeTileVersionSpec.js'; /*leaflet -- core*/ import './leaflet/core/NonEarthCRSSpec.js'; import './leaflet/core/TransformUtilSpec.js'; import './leaflet/core/Proj4LeafletSpec.js'; /*leaflet -- mapping*/ import './leaflet/mapping/ImageMapLayerSpec.js'; import './leaflet/mapping/TiledMapLayerSpec.js'; import './leaflet/mapping/TileLayer.WMTSSpec.js'; // import './leaflet/mapping/WebMapSpec.js'; /*leaflet -- overlay*/ import './leaflet/overlay/EchartsLayerSpec.js'; /*deck相关测试未通过,待解决后打开注释*/ import './leaflet/overlay/graphic/GraphicSpec.js'; import './leaflet/overlay/GraphicLayerSpec.js'; import './leaflet/overlay/graphic/CloverStyleSpec'; import './leaflet/overlay/GraphThemeLayerSpec.js'; import './leaflet/overlay/HeatMapLayerSpec.js'; import './leaflet/overlay/LabelThemeLayerSpec.js'; import './leaflet/overlay/MapVLayerSpec.js'; import './leaflet/overlay/RangeThemeLayerSpec.js'; import './leaflet/overlay/RankSymbolThemeLayerSpec.js'; import './leaflet/overlay/TileVectorLayerSpec.js'; import './leaflet/overlay/UniqueThemeLayerSpec.js'; import './leaflet/overlay/vectortile/PointSymbolizerSpec.js'; import './leaflet/overlay/vectortile/TextSymbolizerSpec.js'; import './leaflet/overlay/TurfLayerSpec.js'; import './leaflet/overlay/mapv/MapVRendererSpec.js'; /**leaflet -- services**/ import './leaflet/services/AddressMatchServiceSpec.js'; import './leaflet/services/BufferAnalysisSpec.js'; import './leaflet/services/DensityAnalysisSpec.js'; import './leaflet/services/EditFeaturesLineSpec.js'; import './leaflet/services/EditFeaturesPointSpec.js'; import './leaflet/services/EditFeaturesRegionSpec.js'; import './leaflet/services/FieldServiceSpec.js'; import './leaflet/services/GenerateSpatialDataSpec.js'; import './leaflet/services/GeoRelationAnalysisSpec.js'; import './leaflet/services/GeometryBatchAnalysisSpec.js'; import './leaflet/services/GetFeaturesByBoundsSpec.js'; import './leaflet/services/GetFeaturesByBufferSpec.js'; import './leaflet/services/GetFeaturesByGeometrySpec.js'; import './leaflet/services/GetFeaturesByIDsSpec.js'; import './leaflet/services/GetFeaturesBySQLSpec.js'; import './leaflet/services/GridCellInfosServiceSpec.js'; import './leaflet/services/InterpolationAnalysisSpec.js'; import './leaflet/services/LayerInfoServiceSpec.js'; import './leaflet/services/MapServiceSpec.js'; import './leaflet/services/MathExpressionAnalysisSpec.js'; import './leaflet/services/MeasureServiceSpec.js'; import './leaflet/services/NetworkAnalystServiceSpec.js'; import './leaflet/services/OverlayAnalysisSpec.js'; import './leaflet/services/ProcessingServiceSpec.js'; import './leaflet/services/QueryByBoundsSpec.js'; import './leaflet/services/QueryByDistanceSpec.js'; import './leaflet/services/QueryByGeometrySpec.js'; import './leaflet/services/QueryBySQLSpec.js'; import './leaflet/services/RouteCalculateMeasureSpec.js'; import './leaflet/services/RouteLocateSpec.js'; import './leaflet/services/SurfaceAnalysisSpec.js'; import './leaflet/services/TerrainCurvatureCalculateSpec.js'; import './leaflet/services/ThemeServiceSpec.js'; import './leaflet/services/ThiessenAnalysisSpec.js'; import './leaflet/services/TrafficTransferAnalystServiceSpec.js'; /* component */ import './leaflet/components/openfile/OpenFileViewSpec.js'; // import './leaflet/components/dataservicequery/DataServiceQueryViewSpec.js'; import './leaflet/components/distributedanalysis/DistributedAnalysisViewSpec.js'; import './leaflet/components/clientcomputation/ClientComputationViewSpec.js'; import './leaflet/components/search/SearchViewSpec.js'; import './leaflet/components/dataflow/DataFlowViewSpec.js'; import './leaflet/overlay/DataFlowLayerSpec.js';
JavaScript
0
@@ -16,19 +16,16 @@ ntrol*/%0A -// import ' @@ -3306,35 +3306,32 @@ leViewSpec.js';%0A -// import './leafle
efcbb67a8fde010e00d587912ec6ddbac4b6a891
remove unnecessary ui prop def
packages/veui-theme-one/components/AlertBox.js
packages/veui-theme-one/components/AlertBox.js
import '../icons/check-circle-o-large' import '../icons/info-circle-o-large' import '../icons/cross-circle-o-large' import config from 'veui/managers/config' config.defaults({ icons: { success: 'check-circle-o-large', info: 'info-circle-o-large', error: 'cross-circle-o-large' }, ui: { type: { values: ['success', 'error', 'info'] } } }, 'alertbox')
JavaScript
0.000007
@@ -289,82 +289,8 @@ ge'%0A - %7D,%0A ui: %7B%0A type: %7B%0A values: %5B'success', 'error', 'info'%5D%0A %7D%0A %7D%0A
f556b0171063ea735844b8c32debbc1e3cbf8776
Add logging when sending email
lib/npmalerts.js
lib/npmalerts.js
'use strict'; var github = require('./github'); var npm = require('./npm'); var db = require('./db'); var email = require('./email'); var _ = require('underscore'); var cache = {}; var yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); npm.getLatestPackages(yesterday, function(error, packages) { if (error) { return console.error(error); } cache = packages; console.info('There are ' + cache.length + ' package updates.'); db.readSubscriptions(function(error, subscriptions) { if (error) { return console.error(error); } _.each(subscriptions, function(subscription) { var user = github.getUserFromUrl(subscription.repourl); var repo = github.getRepoFromUrl(subscription.repourl); github.getPackageJson(user, repo, processPackageJson(subscription)); }); }); }); function processPackageJson(subscription) { return function(error, json) { if (error) { return console.error(error); } var packages = _.filter(_.extend(json.dependencies || {}, json.devDependencies || {}), isPackageInCache); _.each(packages, function(packageName) { var cached = cache[packageName]; var versionRange = packages[packageName]; email.send(subscription.email, subscription.repourl, packageName, versionRange, cached.version); }); }; } function isPackageInCache(dependency) { return !!cache[dependency]; }
JavaScript
0.000001
@@ -1,16 +1,23 @@ -'use strict' +require('newrelic') ;%0A%0Av @@ -1251,16 +1251,80 @@ Name%5D;%0A%0A + console.info('Sending email about ' + packageName);%0A
89885e17a5ad2421fa112289528f3215dc13790d
Set translation to use in templates
lib/generators/website.js
lib/generators/website.js
var util = require("util"); var path = require("path"); var Q = require("q"); var _ = require("lodash"); var nunjucks = require("nunjucks"); var AutoEscapeExtension = require("nunjucks-autoescape"); var FilterExtension = require("nunjucks-filter"); var I18nExtension = require("nunjucks-i18n"); var fs = require("../utils/fs"); var BaseGenerator = require("../generator"); var links = require("../utils/links"); var pageUtil = require("../utils/page"); var pkg = require("../../package.json"); var Generator = function() { BaseGenerator.apply(this, arguments); // revision this.revision = new Date(); // Style to integrates in the output this.styles = ["website"]; // Templates this.templates = {}; }; util.inherits(Generator, BaseGenerator); // Prepare the genertor Generator.prototype.prepare = function() { return BaseGenerator.prototype.prepare.apply(this) .then(this.prepareStyles) .then(this.prepareTemplates) .then(this.prepareTemplateEngine); }; // Prepare all styles Generator.prototype.prepareStyles = function() { var that = this; this.styles = _.chain(this.styles) .map(function(style) { var stylePath = that.options.styles[style]; if (fs.existsSync(path.resolve(that.book.root, stylePath))) { return stylePath; } return null; }) .compact() .value(); return Q(); }; // Prepare templates Generator.prototype.prepareTemplates = function() { this.templates["page"] = this.plugins.template("site:page") || path.resolve(this.options.theme, 'templates/website/page.html'); this.templates["langs"] = this.plugins.template("site:langs") || path.resolve(this.options.theme, 'templates/website/langs.html'); this.templates["glossary"] = this.plugins.template("site:glossary") || path.resolve(this.options.theme, 'templates/website/glossary.html'); return Q(); }; // Prepare template engine Generator.prototype.prepareTemplateEngine = function() { var that = this; return fs.readdir(path.resolve(__dirname, "../../theme/i18n")) .then(function(locales) { locales = _.chain(locales) .map(function(local) { local = path.basename(local, ".json"); return [local, require("../../theme/i18n/"+local)]; }) .object() .value(); if (!_.contains(_.keys(locales), that.options.language)) { that.book.logWarn("Language '"+that.options.language+"' is not available as a layout locales ("+_.keys(locales).join(", ")+")"); } var folders = _.chain(that.templates) .values() .map(path.dirname) .uniq() .value(); that.env = new nunjucks.Environment( new nunjucks.FileSystemLoader(folders), { autoescape: true } ); // Add filter that.env.addFilter("contentLink", that.book.contentLink.bind(that.book)); that.env.addFilter('lvl', function(lvl) { return lvl.split(".").length; }); // Add extension that.env.addExtension('AutoEscapeExtension', new AutoEscapeExtension(that.env)); that.env.addExtension('FilterExtension', new FilterExtension(that.env)); that.env.addExtension('I18nExtension', new I18nExtension({ env: that.env, translations: locales })); }); }; // Finis generation Generator.prototype.finish = function() { return this.copyAssets() .then(this.copyCover) .then(this.writeGlossary) .then(this.writeSearchIndex); }; // Convert an input file Generator.prototype.writeParsedFile = function(page) { var that = this; var relativeOutput = this.book.contentLink(page.path); var output = path.join(that.options.output, relativeOutput); var basePath = path.relative(path.dirname(output), this.options.output) || "."; if (process.platform === 'win32') basePath = basePath.replace(/\\/g, '/'); that.book.logInfo("write parsed file", page.path, "to", relativeOutput); return that.normalizePage(page) .then(function() { return that._writeTemplate(that.templates["page"], { progress: page.progress, _input: page.path, content: page.sections, basePath: basePath, staticBase: links.join(basePath, "gitbook") }, output); }); }; // Write the index for langs Generator.prototype.langsIndex = function(langs) { var that = this; return this._writeTemplate(this.templates["langs"], { langs: langs }, path.join(this.options.output, "index.html")); }; // Write glossary Generator.prototype.writeGlossary = function() { var that = this; // No glossary if (this.book.glossary.length == 0) return Q(); return this._writeTemplate(this.templates["glossary"], {}, path.join(this.options.output, "GLOSSARY.html")); }; // Write the search index Generator.prototype.writeSearchIndex = function() { var that = this; return fs.writeFile( path.join(this.options.output, "search_index.json"), JSON.stringify(this.book.searchIndex) ); }; // Convert a page into a normalized data set Generator.prototype.normalizePage = function(page) { var that = this; var _callHook = function(name) { return that.callHook(name, page) .then(function(_page) { page = _page; return page; }); }; return Q() .then(function() { return _callHook("page"); }) .then(function() { return page; }); }; // Generate a template Generator.prototype._writeTemplate = function(tpl, options, output, interpolate) { var that = this; interpolate = interpolate || _.identity; return Q() .then(function(sections) { return that.env.render( tpl, _.extend({ gitbook: { version: pkg.version }, styles: that.styles, revision: that.revision, title: that.options.title, description: that.options.description, glossary: that.book.glossary, summary: that.book.summary, allNavigation: that.book.navigation, plugins: that.plugins, pluginsConfig: JSON.stringify(that.options.pluginsConfig), htmlSnippet: _.partialRight(that.plugins.html, that, options), options: that.options, basePath: ".", staticBase: path.join(".", "gitbook"), }, options) ); }) .then(interpolate) .then(function(html) { return fs.writeFile( output, html ); }); }; // Copy assets Generator.prototype.copyAssets = function() { var that = this; // Copy gitbook assets return fs.copy( path.join(that.options.theme, "assets"), path.join(that.options.output, "gitbook") ) // Copy plugins assets .then(function() { return Q.all( _.map(that.plugins.list, function(plugin) { var pluginAssets = path.join(that.options.output, "gitbook/plugins/", plugin.name); return plugin.copyAssets(pluginAssets, { base: that.pluginAssetsBase }); }) ); }); }; module.exports = Generator;
JavaScript
0
@@ -3452,16 +3452,48 @@ locales +,%0A locale: %22language%22 %0A @@ -6231,24 +6231,73 @@ description, +%0A language: that.options.language, %0A%0A%09
2ee58044b4d1fbab62b544bc57a352061656e7d1
Add deprecation warning about moved import
packages/lingui-formats/src/createFormat.js
packages/lingui-formats/src/createFormat.js
// @flow import React from 'react' type FormatProps<V, FormatOptions> = { value: V, format?: FormatOptions, i18n: { language: string } } function createFormat<V, FormatOptions, P: FormatProps<V, FormatOptions>> (formatFunction: (language: string, format?: FormatOptions) => (value: V) => string): Class<React$Component<void, P, void>> { return class extends React.Component { props: P render () { const { value, format, i18n } = this.props const formatter = formatFunction(i18n.language, format) return <span>{formatter(value)}</span> } } } export default createFormat
JavaScript
0
@@ -344,16 +344,111 @@ oid%3E%3E %7B%0A + console.warn('DEPRECATED (removal in 1.x): createFormat was moved to lingui-react package')%0A%0A return
2a6f8732547904ea09fa63df939239a31d34348c
Fix test to depend on drive
test/test.transporters.js
test/test.transporters.js
/** * Copyright 2013 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var assert = require('assert'); var googleapis = require('../lib/googleapis.js'); var DefaultTransporter = require('../lib/transporters'); describe('Transporters', function() { var defaultUserAgentRE = 'google-api-nodejs-client/\\d+\.\\d+\.\\d+'; var transporter = new DefaultTransporter(); it('should set default client user agent if none is set', function() { var opts = transporter.configure({}); var re = new RegExp(defaultUserAgentRE); assert(re.test(opts.headers['User-Agent'])); }); it('should append default client user agent to the existing user agent', function() { var applicationName = 'MyTestApplication-1.0'; var opts = transporter.configure({ headers: { 'User-Agent': applicationName } }); var re = new RegExp(applicationName + ' ' + defaultUserAgentRE); assert(re.test(opts.headers['User-Agent'])); }); it('should automatically add content-type', function() { var google = require('../lib/googleapis'); var datastore = google.datastore({ version: 'v1beta2' }); var req = datastore.datasets.beginTransaction({ datasetId: 'test' }); assert.equal(req.headers['content-type'], 'application/json'); }); });
JavaScript
0
@@ -1616,23 +1616,19 @@ var d -atastor +riv e = goog @@ -1635,113 +1635,51 @@ le.d -atastore(%7B version: 'v1beta2' %7D);%0A var req = datastore.datasets.beginTransaction(%7B datasetId: 'test' %7D +rive('v2');%0A var req = drive.files.list( );%0A
ec90e012a0f201d12a54045fc5a9860faad11701
update file /lib/overrider.js
lib/overrider.js
lib/overrider.js
var express = require('express'); var bodyParser = require('body-parser'); var cors = require('cors'); function formRoute() { var form = new express.Router(); form.use(cors()); form.use(bodyParser()); // GET REST endpoint - query params may or may not be populated form.get('/mbaas/forms/:appId/:formId', function(req, res) { $fh.forms.getForm({ "_id": req.params.formId }, function (err, form) { if (err) return res.status(500).json(err); return res.json(form); }); }); // POST method route form.post('/', function (req, res) { res.send('POST request to the homepage'); }); return form; } module.exports = formRoute;
JavaScript
0.000001
@@ -202,16 +202,159 @@ er());%0A%0A + // middleware specific to this router%0A form.use(function timeLog(req, res, next) %7B%0A console.log('Time: ', Date.now());%0A next();%0A %7D);%0A %0A // GE
cd0551541d8db13b1653a2f78cf490f52199a96c
Add an alternative check to detect opus codec support
feature-detects/audio.js
feature-detects/audio.js
/*! { "name" : "HTML5 Audio Element", "property": "audio", "tags" : ["html5", "audio", "media"] } !*/ /* DOC Detects the audio element */ define(['Modernizr', 'createElement'], function(Modernizr, createElement) { // This tests evaluates support of the audio element, as well as // testing what types of content it supports. // // We're using the Boolean constructor here, so that we can extend the value // e.g. Modernizr.audio // true // Modernizr.audio.ogg // 'probably' // // Codec values from : github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845 // thx to NielsLeenheer and zcorpan // Note: in some older browsers, "no" was a return value instead of empty string. // It was live in FF3.5.0 and 3.5.1, but fixed in 3.5.2 // It was also live in Safari 4.0.0 - 4.0.4, but fixed in 4.0.5 Modernizr.addTest('audio', function() { /* jshint -W053 */ var elem = createElement('audio'); var bool = false; try { if (bool = !!elem.canPlayType) { bool = new Boolean(bool); bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''); bool.mp3 = elem.canPlayType('audio/mpeg; codecs="mp3"') .replace(/^no$/, ''); bool.opus = elem.canPlayType('audio/ogg; codecs="opus"') .replace(/^no$/, ''); // Mimetypes accepted: // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements // bit.ly/iphoneoscodecs bool.wav = elem.canPlayType('audio/wav; codecs="1"') .replace(/^no$/, ''); bool.m4a = (elem.canPlayType('audio/x-m4a;') || elem.canPlayType('audio/aac;')) .replace(/^no$/, ''); } } catch (e) { } return bool; }); });
JavaScript
0
@@ -1141,16 +1141,17 @@ orbis%22') + .replace @@ -1230,16 +1230,17 @@ mp3%22') + .replace @@ -1314,24 +1314,95 @@ ecs=%22opus%22') + %7C%7C%0A elem.canPlayType('audio/webm; codecs=%22opus%22') .replace(/%5E
a0921dd12f2ed5f2f974ca056af9c47cb3238768
rename window to global to work on server
packages/node_modules/cerebral/src/index.js
packages/node_modules/cerebral/src/index.js
import * as tags from './tags' import ControllerClass from './Controller' import { DEPRECATE } from './utils' import ModuleClass from './Module' import UniversalControllerClass from './UniversalController' let tagsVar = tags if ( process.env.NODE_ENV !== 'production' && typeof window.Proxy !== 'undefined' ) { tagsVar = Object.keys(tags).reduce((proxyHost, key) => { proxyHost[key] = new Proxy(tags[key], { get(obj, prop) { throw new Error('YOU HAVE NOT ENABLED THE BABEL-PLUGIN-CEREBRAL') }, }) return proxyHost }, {}) } export const props = tagsVar.props export const path = tagsVar.path export const state = tagsVar.state export const string = tagsVar.string export const sequences = tagsVar.sequences export const computed = tagsVar.computed export const moduleState = tagsVar.moduleState export const moduleSequences = tagsVar.moduleSequences export const moduleComputed = tagsVar.moduleComputed // Needed to test for instanceof. export { default as ModuleClass } from './Module' export { default as ControllerClass } from './Controller' export { default as ProviderClass } from './Provider' export { default as BaseControllerClass } from './BaseController' export { SequenceFactory as ChainSequenceFactory, SequenceWithPropsFactory as ChainSequenceWithPropsFactory, } from 'function-tree/fluent' export { sequence, parallel, createTemplateTag, extractValueWithPath, resolveObject, ResolveValue, Tag, } from 'function-tree' export function Controller(rootModule, options) { DEPRECATE('Controller', 'Use App default import instead') return new ControllerClass(rootModule, options) } export function UniversalController(rootModule, options) { DEPRECATE('UniversalController', 'Use UniversalApp import instead') return new UniversalControllerClass(rootModule, options) } export function UniversalApp(rootModule, options) { return new UniversalControllerClass(rootModule, options) } export function Module(definition) { DEPRECATE( 'Module', 'Use plain object/function. Type with ModuleDefinition export' ) return new ModuleClass(definition) } export { default as CerebralError } from './CerebralError' export { default as Provider } from './Provider' export { default as Compute } from './Compute' export { default as Reaction } from './Reaction' export { default as View } from './View' export { createDummyController, throwError } from './utils' export default function App(rootModule, options) { return new ControllerClass(rootModule, options) }
JavaScript
0
@@ -282,14 +282,14 @@ eof -window +global .Pro
c7656a48c63126c98c857cbc2b76339271952e10
Use proper fs-extra dep.
lib/helpers/file/index.js
lib/helpers/file/index.js
/** * Module dependencies */ var fs = require('fs-extra'), path = require('path'), async = require('async'), _ = require('lodash'), switchback = require('node-switchback'); /** * Generate a file using the specified string. * * @option {String} rootPath * @option {String} contents - the string contents to write to disk * [@option {Boolean} force=false] * [@option {Boolean} dry=false] * * @sb success * @sb error * @sb invalid * @sb alreadyExists */ module.exports = function ( options, sb ) { // Provide default values for switchback sb = switchback(sb, { alreadyExists: sb.error, invalid: sb.error }); // Provide defaults and validate required options _.defaults(options, { force: false }); var missingOpts = _.difference([ 'contents', 'rootPath' ], Object.keys(options)); if ( missingOpts.length ) return sb.invalid(missingOpts); // In case we ended up here w/ a relative path, // resolve it using the process's CWD var rootPath = path.resolve( process.cwd() , options.rootPath ); // console.log('FileHelper trying to generate:',rootPath); // Only override an existing file if `options.force` is true fs.exists(rootPath, function (exists) { if (exists && !options.force) { console.log(rootPath); return sb.alreadyExists(rootPath); } // Don't actually write the file if this is a dry run. if (options.dry) return sb.success(); async.series([ function deleteExistingFileIfNecessary (cb) { if ( !exists ) return cb(); return fs.remove(rootPath, cb); }, function writeToDisk (cb) { fs.outputFile(rootPath, options.contents, cb); } ], function (err) { if (err) return sb.error(err); else sb.success(); }); }); };
JavaScript
0
@@ -1227,16 +1227,19 @@ e) %7B%0A%09%09%09 +// console.
531e4fb26ded54c17d84f7055c40f4ad7493a4b6
implement helpers for enable/disable of buttons and input (#1452)
src/instanceMethods/enable-disable-elements.js
src/instanceMethods/enable-disable-elements.js
import privateProps from '../privateProps.js' export function enableButtons () { const domCache = privateProps.domCache.get(this) domCache.confirmButton.disabled = false domCache.cancelButton.disabled = false } export function disableButtons () { const domCache = privateProps.domCache.get(this) domCache.confirmButton.disabled = true domCache.cancelButton.disabled = true } export function enableConfirmButton () { const domCache = privateProps.domCache.get(this) domCache.confirmButton.disabled = false } export function disableConfirmButton () { const domCache = privateProps.domCache.get(this) domCache.confirmButton.disabled = true } export function enableInput () { const input = this.getInput() if (!input) { return false } if (input.type === 'radio') { const radiosContainer = input.parentNode.parentNode const radios = radiosContainer.querySelectorAll('input') for (let i = 0; i < radios.length; i++) { radios[i].disabled = false } } else { input.disabled = false } } export function disableInput () { const input = this.getInput() if (!input) { return false } if (input && input.type === 'radio') { const radiosContainer = input.parentNode.parentNode const radios = radiosContainer.querySelectorAll('input') for (let i = 0; i < radios.length; i++) { radios[i].disabled = true } } else { input.disabled = true } }
JavaScript
0.99909
@@ -40,16 +40,503 @@ ps.js'%0A%0A +function setButtonsDisabled (buttons, disabled) %7B%0A buttons.forEach(button =%3E %7B%0A button.disabled = disabled%0A %7D)%0A%7D%0A%0Afunction setInputDisabled (input, disabled) %7B%0A if (!input) %7B%0A return false%0A %7D%0A if (input.type === 'radio') %7B%0A const radiosContainer = input.parentNode.parentNode%0A const radios = radiosContainer.querySelectorAll('input')%0A for (let i = 0; i %3C radios.length; i++) %7B%0A radios%5Bi%5D.disabled = disabled%0A %7D%0A %7D else %7B%0A input.disabled = disabled%0A %7D%0A%7D%0A%0A export f @@ -607,32 +607,52 @@ che.get(this)%0A +setButtonsDisabled(%5B domCache.confirm @@ -657,35 +657,17 @@ rmButton -.disabled = false%0A +, domCach @@ -680,33 +680,25 @@ elButton -.disabled = +%5D, false +) %0A%7D%0A%0Aexpo @@ -774,32 +774,52 @@ che.get(this)%0A +setButtonsDisabled(%5B domCache.confirm @@ -824,34 +824,17 @@ rmButton -.disabled = true%0A +, domCach @@ -847,32 +847,24 @@ elButton -.disabled = +%5D, true +) %0A%7D%0A%0Aexpo @@ -945,32 +945,52 @@ che.get(this)%0A +setButtonsDisabled(%5B domCache.confirm @@ -995,33 +995,25 @@ rmButton -.disabled = +%5D, false +) %0A%7D%0A%0Aexpo @@ -1103,16 +1103,36 @@ this)%0A +setButtonsDisabled(%5B domCache @@ -1145,32 +1145,24 @@ rmButton -.disabled = +%5D, true +) %0A%7D%0A%0Aexpo @@ -1196,350 +1196,55 @@ %7B%0A -const input = this.getInput()%0A if (!input) %7B%0A return false%0A %7D%0A if (input.type === 'radio') %7B%0A const radiosContainer = input.parentNode.parentNode%0A const radios = radiosContainer.querySelectorAll('input')%0A for (let i = 0; i %3C radios.length; i++) %7B%0A radios%5Bi%5D.disabled = false%0A %7D%0A %7D else %7B%0A input.disabled = +return setInputDisabled(this.getInput(), false -%0A %7D +) %0A%7D%0A%0A @@ -1283,356 +1283,53 @@ %7B%0A -const input = this.getInput()%0A if (!input) %7B%0A return false%0A %7D%0A if (input && input.type === 'radio') %7B%0A const radiosContainer = input.parentNode.parentNode%0A const radios = radiosContainer.querySelectorAll('input')%0A for (let i = 0; i %3C radios.length; i++) %7B%0A radios%5Bi%5D.disabled = true%0A %7D%0A %7D else %7B%0A input.disabled = +return setInputDisabled(this.getInput(), true -%0A %7D +) %0A%7D%0A
1e86cc181fe65d918222920df1363d9dab5773b4
remove unnecessary import
app/src/root.js
app/src/root.js
import React, { Component } from 'react-native'; import { Provider } from 'react-redux'; import configureStore from './store/configure-store'; import App from './containers/app'; const store = configureStore(); const Root = () => ( <Provider store={store}> <App /> </Provider> ); export default Root;
JavaScript
0.000037
@@ -9,23 +9,8 @@ eact -, %7B Component %7D fro
8ae017c5fb97db1d5eb16182f98768db42d4b618
update files
lib/htmlparser/context.js
lib/htmlparser/context.js
/*! * context * Version: 0.0.1 * Date: 2016/7/29 * https://github.com/Nuintun/fengine * * Original Author: https://github.com/tmont/html-parser * * This is licensed under the MIT License (MIT). * For details, see: https://github.com/Nuintun/fengine/blob/master/LICENSE */ 'use strict'; // lib var util = require('./util'); // event types var EVENTTYPES = [ 'openElement', 'closeElement', 'attribute', 'comment', 'cdata', 'text', 'docType', 'xmlType', 'closeOpenedElement' ]; /** * format rule * @param rule * @param porp */ function formatRule(rule, porp){ switch (util.type(rule[porp])) { case 'string': rule[porp] = util.str2regex(rule[porp]); break; case 'regexp': if (rule[porp].global) { var attr = ''; if (rule[porp].ignoreCase) { attr += 'i'; } if (rule[porp].multiline) { attr += 'm'; } rule[porp] = util.str2regex(rule[porp].source, attr); } break; default: throw new TypeError('rules.dataElements.' + porp + ' must be a sting or regexp.'); break; } } /** * create read * @param raw * @param callbacks * @param rules * @returns {{ * text: string, * peek: context.peek, * read: context.read, * readUntilNonWhitespace: context.readUntilNonWhitespace, * readRule: context.readRule, * peekIgnoreWhitespace: context.peekIgnoreWhitespace * }} */ module.exports.create = function (raw, callbacks, rules){ var index = 0; var current = null; var substring = null; var context = { text: '', peek: function (count){ count = count || 1; return this.raw.substr(this.index + 1, count); }, read: function (count, peek){ var next; count = count || 1; if (peek) { next = this.peek(count); } this.index += count; if (this.index > this.length) { this.index = this.length; } return next; }, readUntilNonWhitespace: function (){ var next; var value = ''; while (!this.EOF) { next = this.read(1, true); value += next; if (!/\s$/.test(value)) { break; } } return value; }, readRule: function (rule){ var match = rule.exec(this.raw.substring(this.index)); var value = match ? match[0] : ''; this.index += (match ? match.index : 0) + value.length; return value; }, peekIgnoreWhitespace: function (count){ count = count || 1; var value = ''; var next = ''; var offset = 0; do { next = this.raw.charAt(this.index + ++offset); if (!next) { break; } if (!/\s/.test(next)) { value += next; } } while (value.length < count); return value; } }; // end of file context.__defineGetter__('EOF', function (){ return this.index >= this.length; }); // current char context.__defineGetter__('current', function (){ return this.EOF ? '' : current === null ? (current = this.raw.charAt(this.index)) : current; }); // raw code context.__defineGetter__('raw', function (){ return raw; }); // raw length context.__defineGetter__('length', function (){ return this.raw.length; }); // index context.__defineGetter__('index', function (){ return index; }); // set index context.__defineSetter__('index', function (value){ index = value; current = null; substring = null; }); // non parsed code context.__defineGetter__('substring', function (){ return substring === null ? (substring = this.raw.substring(this.index)) : substring; }); // callbacks context.callbacks = {}; // format event callbacks EVENTTYPES.forEach(function (value){ context.callbacks[value] = util.noop; }); // merge callbacks util.merge(context.callbacks, callbacks || {}); // rules context.rules = { name: /[a-zA-Z_][\w:.-]*/, attribute: /[a-zA-Z_][\w:.-]*/, dataElements: { cdata: { start: '<![CDATA[', end: ']]>' }, comment: { start: '<!--', end: '-->' }, docType: { start: /^<!DOCTYPE /i, end: '>' } } }; // merge rules util.merge(context.rules, rules || {}); var rule; var dataElements = context.rules.dataElements; for (var data in dataElements) { if (dataElements.hasOwnProperty(data)) { rule = dataElements[data]; formatRule(rule, 'start'); formatRule(rule, 'end'); } } // return read return context; };
JavaScript
0.000001
@@ -2298,28 +2298,24 @@ e.exec(this. -raw. substring(th @@ -2311,28 +2311,16 @@ ubstring -(this.index) );%0A
850342f0979be4367e79967d0a4be117c036844f
Update src/data.js to allow the storing of functions as data. This is consistent with the JQuery documentation.
src/data.js
src/data.js
// Zepto.js // (c) 2010-2012 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. // The following code is heavily inspired by jQuery's $.fn.data() ;(function($) { var data = {}, dataAttr = $.fn.data, uuid = $.uuid = +new Date(), exp = $.expando = 'Zepto' + uuid function getData(node, name) { var id = node[exp], store = id && data[id] return name === undefined ? store || setData(node) : (store && store[name]) || dataAttr.call($(node), name) } function setData(node, name, value) { var id = node[exp] || (node[exp] = ++uuid), store = data[id] || (data[id] = {}) if (name !== undefined) store[name] = value return store } $.fn.data = function(name, value) { return value === undefined ? this.length == 0 ? undefined : getData(this[0], name) : this.each(function(idx){ setData(this, name, $.isFunction(value) ? value.call(this, idx, getData(this, name)) : value) }) } })(Zepto)
JavaScript
0
@@ -902,97 +902,15 @@ me, -$.isFunction(value) ?%0A value.call(this, idx, getData(this, name)) : value) +; %0A @@ -914,20 +914,22 @@ %7D) +; %0A %7D +; %0A%7D)(Zept
72c4e7a1b952664419dcde39056e7c8f494c3cd6
Fix typo
public/scripts/example.js
public/scripts/example.js
/** * This file provided by Facebook is for non-commercial testing and evaluation purposes only. * Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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. */ var Comment = React.createClass({ render: function() { var rawMarkup = marked(this.props.children.toString(), {sanitize: true}); return ( <div className="comment"> <h2 className="commentAuthor"> {this.props.author} </h2> <span dangerouslySetInnerHTML={{__html: rawMarkup}} /> </div> ); } }); var CommentBox = React.createClass({ loadCommentsFromServer: function() { $.ajax({ url: this.props.url, dataType: 'json', cache: false, success: function(data) { this.setState({data: data}); }.bind(this), error: function(xhr, status, err) { console.error(this.props.url, status, err.toString()); }.bind(this) }); }, handleCommentSubmit: function(comment) { var comments = this.state.data; comments.push(comment); this.setState({data: comments}, function() { // `setState` accepts a callback. To avoid (improbable) race condition, // `we'll send the ajax request right after we optimistically set the new // `state. $.ajax({ url: this.props.url, dataType: 'json', type: 'POST', data: comment, success: function(data) { this.setState({data: data}); }.bind(this), error: function(xhr, status, err) { console.error(this.props.url, status, err.toString()); }.bind(this) }); }); }, getInitialState: function() { return {data: []}; }, componentDidMount: function() { this.loadCommentsFromServer(); setInterval(this.loadCommentsFromServer, this.props.pollInterval); }, render: function() { return ( <div className="commentBox"> <h1>Comments</h1> <CommentList data={this.state.data} /> <CommentForm onCommentSubmit={this.handleCommentSubmit} /> </div> ); } }); var CommentList = React.createClass({ render: function() { var commentNodes = this.props.data.map(function(comment, index) { return ( // `key` is a React-specific concept and is not mandatory for the // purpose of this tutorial. if you're curious, see more here: // http://facebook.github.io/react/docs/multiple-components.html#dynamic-children <Comment author={comment.author} key={index}> {comment.text} </Comment> ); }); return ( <div className="commentList"> {commentNodes} </div> ); } }); var CommentForm = React.createClass({ handleSubmit: function(e) { e.preventDefault(); var author = React.findDOMNode(this.refs.author).value.trim(); var text = React.findDOMNode(this.refs.text).value.trim(); if (!text || !author) { return; } this.props.onCommentSubmit({author: author, text: text}); React.findDOMNode(this.refs.author).value = ''; React.findDOMNode(this.refs.text).value = ''; }, render: function() { return ( <form className="commentForm" onSubmit={this.handleSubmit}> <input type="text" placeholder="Your name" ref="author" /> <input type="text" placeholder="Say something..." ref="text" /> <input type="submit" value="Post" /> </form> ); } }); React.render( <CommentBox url="comments.json" pollInterval={2000} />, document.getElementById('content') );
JavaScript
0.999999
@@ -1593,17 +1593,16 @@ // -%60 we'll se @@ -1672,17 +1672,16 @@ // -%60 state.%0A
a37dae9de80affd984f31372b0849e191544fddf
Reorder the flag checks so version can be shown
bin/oust.js
bin/oust.js
#!/usr/bin/env node var oust = require('../index'); var pkg = require('../package.json'); var fs = require('fs'); var argv = require('minimist')(process.argv.slice(2)); var printHelp = function() { console.log([ 'oust', pkg.description, '', 'Usage:', ' $ oust <filename> <type>' ].join('\n')); }; if(argv.h || argv.help || argv._.length === 0) { printHelp(); return; } if(argv.v || argv.version) { console.log(pkg.version); return; } var file = argv._[0]; var type = argv._[1]; fs.readFile(file, function(err, data) { if(err) { console.error('Error opening file:', err.message); process.exit(1); } var res = oust(data, type); console.log(res.join('\n')); });
JavaScript
0.000001
@@ -357,63 +357,56 @@ rgv. -h %7C%7C argv.help %7C%7C argv._.length === 0) %7B%0A printHelp( +v %7C%7C argv.version) %7B%0A console.log(pkg.version );%0A @@ -419,33 +419,33 @@ urn;%0A%7D%0A%0Aif(argv. -v +h %7C%7C argv.version @@ -441,46 +441,53 @@ rgv. -version) %7B%0A console.log(pkg.version +help %7C%7C argv._.length === 0) %7B%0A printHelp( );%0A
b523acaa9e07212de9e8e3d9a12a4cd3c020c26f
update API Key and project name in #283
site/assets/js/search.js
site/assets/js/search.js
// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT // IT'S ALL JUST JUNK FOR OUR DOCS! // ++++++++++++++++++++++++++++++++++++++++++ (function () { 'use strict' if (!window.docsearch) { return } var inputElement = document.getElementById('search-input') var siteDocsVersion = inputElement.getAttribute('data-docs-version') function getOrigin() { var location = window.location var origin = location.origin if (!origin) { var port = location.port ? ':' + location.port : '' origin = location.protocol + '//' + location.hostname + port } return origin } window.docsearch({ apiKey: '5990ad008512000bba2cf951ccf0332f', indexName: 'bootstrap', inputSelector: '#search-input', algoliaOptions: { facetFilters: ['version:' + siteDocsVersion] }, transformData: function (hits) { return hits.map(function (hit) { var currentUrl = getOrigin() var liveUrl = 'https://getbootstrap.com' // When in production, return the result as is, // otherwise remove our url from it. // eslint-disable-next-line no-negated-condition hit.url = currentUrl.indexOf(liveUrl) !== -1 ? // lgtm [js/incomplete-url-substring-sanitization] hit.url : hit.url.replace(liveUrl, '') // Prevent jumping to first header if (hit.anchor === 'content') { hit.url = hit.url.replace(/#content$/, '') hit.anchor = null } return hit }) }, // Set debug to `true` if you want to inspect the dropdown debug: false }) })()
JavaScript
0
@@ -636,40 +636,40 @@ y: ' -5990ad008512000bba2cf951ccf0332f +a2fb9f18ccc85658e152aeb2dd350860 ',%0A @@ -686,22 +686,27 @@ me: 'boo -t st -rap +ed-orange ',%0A i @@ -964,20 +964,22 @@ s:// -get boo -t st -rap +ed.orange .com
f513a37ce6ade7782bf4354f6c5295348803ee70
READ Entity: First initially failing test (TDD phase 1)
spec/api/api_session_spec.js
spec/api/api_session_spec.js
/** * API Session Tests */ var frisby = require('frisby'); var panaxui = require('../../panaxui'); var hostname = panaxui.config.hostname, port = panaxui.config.port, url = 'http://' + hostname + ':' + port + '/api'; /** * Test login */ frisby.create('Login') .post(url + panaxui.api.login, { username: panaxui.config.username, password: panaxui.config.password }) .expectStatus(200) .expectHeaderContains('content-type', 'application/json') .expectJSON({ success: true, // data: { // userId: //ToDo: Special userId verification? // } }) .expectJSONTypes({ success: Boolean, data: { userId: String } }) .after(get_sitemap) // Chain tests (sync http requests) .toss(); /** * Test get sitemap when logged in */ function get_sitemap(err, res, body) { // ToDo: Should be stateless: https://github.com/vlucas/frisby/issues/36 // Grab returned session cookie var cookie = res.headers['set-cookie'][0].split(';')[0]; console.dir(cookie); frisby.create('Get sitemap') .addHeader('Cookie', cookie) // Pass session cookie with each request .get(url + panaxui.api.sitemap) .expectStatus(200) .expectHeaderContains('content-type', 'application/json') .expectJSON({ success: true }) .expectJSONLength('data', function (val) { expect(val).toBeGreaterThan(0); // Custom matcher callback }) .expectJSONTypes({ success: Boolean, data: Array }) .after(logout) // Chain tests (sync http requests) .toss() } /** * Test logout */ function logout(err, res, body) { frisby.create('Logout') .get(url + panaxui.api.logout) .expectStatus(200) .expectHeaderContains('content-type', 'application/json') .expectJSON({ success: true }) .expectJSONTypes({ success: Boolean }) .after(fail_sitemap) // Chain tests (sync http requests) .toss(); } /** * Test logout */ function fail_sitemap(err, res, body) { frisby.create('Fail sitemap') .get(url + panaxui.api.sitemap) .expectStatus(500) .expectHeaderContains('content-type', 'application/json') .expectJSON({ success: false }) .expectJSONTypes({ success: Boolean }) .toss(); }
JavaScript
0.000003
@@ -217,16 +217,37 @@ /api';%0A%0A +var session_cookie;%0A%0A /**%0A * T @@ -250,17 +250,17 @@ * Test -l +L ogin%0A */ @@ -740,20 +740,21 @@ est -get s +Get S itemap +( when @@ -763,16 +763,17 @@ ogged in +) %0A */%0Afun @@ -883,21 +883,19 @@ sues/36%0A -%0A %09// - Grab re @@ -920,20 +920,24 @@ kie%0A -var +session_ cookie = @@ -984,30 +984,8 @@ %5B0%5D; -%0A%09console.dir(cookie); %0A%0A%09f @@ -1002,17 +1002,17 @@ te('Get -s +S itemap') @@ -1038,16 +1038,24 @@ ookie', +session_ cookie) @@ -1418,24 +1418,488 @@ Array%0A%09%09%7D)%0A +%09%09.after(read_entity) // Chain tests (sync http requests)%0A%09.toss()%0A%7D%0A%0A/**%0A * Test Read Entity (when logged in)%0A */%0Afunction read_entity(err, res, body) %7B%0A%0A%09frisby.create('Read Entity')%0A%09 .addHeader('Cookie', session_cookie) // Pass session cookie with each request%0A%09%09.get(url + panaxui.api.read)%0A%09%09.expectStatus(200)%0A%09%09.expectHeaderContains('content-type', 'application/json')%0A%09%09.expectJSON(%7B%0A%09%09%09success: true%0A%09%09%7D)%0A%09%09.expectJSONTypes(%7B%0A%09%09%09success: Boolean%0A%09%09%7D)%0A %09%09.after(log @@ -1956,33 +1956,33 @@ %7D%0A%0A%0A/**%0A * Test -l +L ogout%0A */%0Afuncti @@ -2320,18 +2320,103 @@ est -logout%0A */ +Fail Read Entity (when logged out)%0A * ToDo%0A */%0A%0A/**%0A * Test Fail Sitemap (when logged out)%0A */%0A %0Afun @@ -2473,17 +2473,17 @@ e('Fail -s +S itemap')
0ea5770a19952abfbd3f744f4f838c105286f3b6
Add fragment() test for accepting document fragments (already works).
test/unit/api/fragment.js
test/unit/api/fragment.js
import element from '../../lib/element'; import resolved from '../../lib/resolved'; import skate from '../../../src/index'; import typeAttribute from 'skatejs-type-attribute'; describe('api/fragment', function () { var tagName; beforeEach(function () { tagName = element().safe; }); it('should return an empty fragment if no argument specified', function () { var frag = skate.fragment(); expect(frag instanceof DocumentFragment).to.equal(true); expect(frag.childNodes.length).to.equal(0); }); describe('html', function () { it('should not init an element without a definition', function () { var html = `<${tagName}></${tagName}>`; var frag = skate.fragment(html); expect(resolved(frag.childNodes[0])).to.equal(false); }); it('should init a single element', function () { skate(tagName, {}); var html = `<${tagName}></${tagName}>`; var frag = skate.fragment(html); expect(resolved(frag.childNodes[0])).to.equal(true); }); it('should init multiple elements', function () { skate(tagName, {}); var html = `<${tagName}></${tagName}>`; var frag = skate.fragment(html + html); expect(frag.childNodes.length).to.equal(2); expect(resolved(frag.childNodes[0])).to.equal(true); expect(resolved(frag.childNodes[1])).to.equal(true); }); it('should init an element and its descendents', function () { var descendantTagName = element().safe; skate(tagName, {}); skate(descendantTagName, { type: typeAttribute }); var html = `<${tagName}><div ${descendantTagName}></div></${tagName}>`; var frag = skate.fragment(html); expect(resolved(frag.childNodes[0])).to.equal(true, 'host'); expect(resolved(frag.childNodes[0].firstElementChild)).to.equal(true, 'descendent'); }); it('should work with special tags', function () { var html = '<td></td><td></td>'; var frag = skate.fragment(html); expect(frag.childNodes.length).to.equal(2); expect(frag.childNodes[0].tagName).to.equal('TD'); expect(frag.childNodes[1].tagName).to.equal('TD'); }); it('should work with normal tags', function () { const html = '<form><input></form>'; const frag = skate.fragment(html); expect(frag.childNodes[0].tagName).to.equal('FORM'); expect(frag.childNodes[0].childNodes[0].tagName).to.equal('INPUT'); }); it('should treat as html even if it starts with text', function () { const html = 'test<form><input></form>'; const frag = skate.fragment(html); expect(frag.childNodes[0].textContent).to.equal('test'); expect(frag.childNodes[1].tagName).to.equal('FORM'); expect(frag.childNodes[1].childNodes[0].tagName).to.equal('INPUT'); }); }); describe('text', function () { it('works with text that has no parent element', function () { const text = 'some text'; const frag = skate.fragment(text); expect(frag.childNodes[0].textContent).to.equal('some text'); }); }); describe('node', function () { it('should work with element nodes', function () { const node = document.createElement('div'); const frag = skate.fragment(node); expect(frag.childNodes[0]).to.equal(node); }); it('should work with text nodes', function () { const node = document.createTextNode(''); const frag = skate.fragment(node); expect(frag.childNodes[0]).to.equal(node); }); it('should work with comment nodes', function () { const node = document.createComment(''); const frag = skate.fragment(node); expect(frag.childNodes[0]).to.equal(node); }); it('should initialise element nodes that are custom elements', function () { const elem = skate(element().safe, {}); const node = document.createElement(elem.id); const frag = skate.fragment(node); expect(frag.childNodes[0]).to.equal(node); expect(resolved(frag.childNodes[0])).to.equal(true); }); }); });
JavaScript
0
@@ -3679,32 +3679,300 @@ node);%0A %7D);%0A%0A + it('should work with document fragments', function () %7B%0A const frag = document.createDocumentFragment();%0A const elem = document.createElement('div');%0A frag.appendChild(elem);%0A expect(skate.fragment(frag).childNodes%5B0%5D).to.equal(elem);%0A %7D);%0A%0A it('should i
180411baa966474f8e05b61e37dbd5d36526a184
Change Visgoth's list of profilers to a dictionary of profilers
webapp/webapp/static/js/visgoth.js
webapp/webapp/static/js/visgoth.js
"use strict"; // http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript function guid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + "-" + s4() + "-" + s4() + "-" + s4() + "-" + s4() + s4() + s4(); } var VisgothLabels = { "bandwidth": "bandwidth", "networkLatency": "networkLatency", "fps": "fps", "bufferLoadTime": "bufferLoadTime", "networkBufferSize": "networkBufferSize", "extent": "extent", }; // ************** // // Visgoth Stat // // ************** // function VisgothStat(label, id) { this.label = label; this.id = id; this.start = 0; this.end = 0; this.state = []; } VisgothStat.prototype.addValue = function(value) { this.state.push(value); }; VisgothStat.prototype.markStart = function() { this.start = performance.now(); }; VisgothStat.prototype.markEnd = function() { this.end = performance.now(); }; VisgothStat.prototype.measurePerformance = function(shouldEnd) { if (shouldEnd !== false) { this.markEnd(); } this.addValue(this.end - this.start); }; // ***************** // // Visgoth Profiler // // ***************** // function VisgothProfiler(label, getProfileDataFn) { this.label = label; this.getProfileData = getProfileDataFn; } VisgothProfiler.prototype.sumArray = function(array) { return array.reduce(function(x, y) { return x + y; }, 0); }; VisgothProfiler.prototype.avgArray = function(array) { var length = array.length; if (length === 0) { return 0; } else { return this.sumArray(array) / length; } }; VisgothProfiler.prototype.sumStatArray = function(statArray) { return this.sumArray(statArray.reduce(function(x, y) { return x.concat(y.state); }, [])); }; VisgothProfiler.prototype.avgStatArray = function(statArray) { return this.avgArray(statArray.reduce(function(x, y) { return x.concat(y.state); }, [])); }; var NetworkLatencyProfiler = new VisgothProfiler(VisgothLabels.networkLatency, function(stats) { stats = stats[this.label]; return this.avgStatArray(stats); }); var BandwidthProfiler = new VisgothProfiler(VisgothLabels.bandwidth, function(stats) { var networkLatencyStats = stats[VisgothLabels.networkLatency]; var networkBufferSizeStats = stats[VisgothLabels.networkBufferSize]; // should this instead be the average per request? return this.avgStatArray(networkBufferSizeStats) / this.avgStatArray(networkLatencyStats); }); var FpsProfiler = new VisgothProfiler(VisgothLabels.fps, function(stats) { stats = stats[this.label]; // events per second return 1000 / this.avgStatArray(stats); }); var MockExtentProfiler = new VisgothProfiler(VisgothLabels.extent, function(stats) { var extent_state = stats[this.label][0].state; return extent_state[extent_state.length - 1]; }); // ********* // // Visgoth // // ********* // function Visgoth() { this.profilers = [ BandwidthProfiler, NetworkLatencyProfiler, FpsProfiler, MockExtentProfiler, ]; this.stats = {}; var profiler; for (var i in this.profilers) { profiler = this.profilers[i]; this.stats[profiler.label] = []; } this.clientId = guid(); } Visgoth.prototype.registerStat = function(visgothStat) { if (this.stats[visgothStat.label] === undefined) { this.stats[visgothStat.label] = []; } this.stats[visgothStat.label].push(visgothStat); }; Visgoth.prototype.getProfileData = function() { var profile = {}; var profiler, label; for (var i in this.profilers) { profiler = this.profilers[i]; label = profiler.label; profile[label] = profiler.getProfileData(this.stats); } return profile; }; Visgoth.prototype.getMetadata = function() { return { "client_id": this.clientId, "timestamp": Date.now(), }; }; Visgoth.prototype.sendProfiledMessage = function(type, content) { var visgoth_content = { "metadata": this.getMetadata(), "profile": this.getProfileData(), }; sendMessage(type, content, visgoth_content); };
JavaScript
0
@@ -2747,24 +2747,88 @@ on(stats) %7B%0A + // Index 0 is hard-coded, corresponds to the 'LL' spectrogram%0A var extent @@ -3010,13 +3010,55 @@ s = -%5B%0A +%7B%7D;%0A this.profilers%5BVisgothLabels.bandwidth%5D = Ban @@ -3071,21 +3071,66 @@ Profiler -,%0A +;%0A this.profilers%5BVisgothLabels.networkLatency%5D = Network @@ -3144,21 +3144,55 @@ Profiler -,%0A +;%0A this.profilers%5BVisgothLabels.fps%5D = FpsProf @@ -3195,21 +3195,58 @@ Profiler -,%0A +;%0A this.profilers%5BVisgothLabels.extent%5D = MockExt @@ -3260,13 +3260,8 @@ iler -,%0A %5D ;%0A%0A @@ -3297,33 +3297,37 @@ ler;%0A for (var -i +label in this.profile @@ -3358,25 +3358,29 @@ s.profilers%5B -i +label %5D;%0A this. @@ -3385,25 +3385,16 @@ s.stats%5B -profiler. label%5D = @@ -3727,15 +3727,8 @@ iler -, label ;%0A @@ -3736,17 +3736,21 @@ or (var -i +label in this @@ -3797,38 +3797,14 @@ ers%5B -i%5D;%0A label = profiler. label +%5D ;%0A
dff51718e9483dab6b140d1adbd3c3ab0ea49b0d
Update lib/partition: Fix error when no buffer given
lib/partition.js
lib/partition.js
/** * Partition Constructor * @return {Partition} */ function Partition( device, options ) { if( !(this instanceof Partition) ) return new Partition( device, options ) this.device = device this.firstLBA = options.firstLBA || 0 this.lastLBA = options.lastLBA || -1 } /** * Partition Prototype * @type {Object} */ Partition.prototype = { constructor: Partition, __OOB: function( lba ) { return lba < this.firstLBA || lba > this.lastLBA }, get blockSize() { return this.device.blockSize }, get sectors() { return this.lastLBA - this.firstLBA }, get size() { return this.sectors * this.blockSize }, readBlocks: function( from, to, buffer, callback ) { callback = callback.bind( this ) from = from + this.firstLBA to = to + this.firstLBA if( this.__OOB( from ) || this.__OOB( to ) ) { var msg = 'Block address out of bounds: ' + '['+from+','+to+'] not in range ' + '['+this.firstLBA+','+this.lastLBA+']' return callback( new Error( msg ) ) } this.device.readBlocks( from, to, buffer, callback ) return this }, writeBlocks: function( from, data, callback ) { callback = callback.bind( this ) from = from + this.firstLBA if( this.__OOB( from ) ) { var msg = 'Block address out of bounds: ' + '['+from+','+to+'] not in range ' + '['+this.firstLBA+','+this.lastLBA+']' return callback( new Error( msg ) ) } this.device.writeBlocks( from, data, callback ) return this }, } // Exports module.exports = Partition
JavaScript
0.000001
@@ -729,32 +729,128 @@ llback ) %7B%0A %0A + if( typeof buffer === 'function' ) %7B%0A callback = buffer%0A buffer = null%0A %7D%0A %0A callback = c @@ -1299,36 +1299,38 @@ function( from, -data +buffer , callback ) %7B%0A @@ -1676,12 +1676,14 @@ om, -data +buffer , ca
8afe15a168b34e2665ae71212ab4815523694a73
fix order
database/scripts/setupPanel.js
database/scripts/setupPanel.js
var accounts = require('../db.js'); // included to connect to database var accounts = require('../dbAccounts.js'); var passwords = require('../../passwords.json'); console.log("Setting up Secret DJ Panel..."); var callback = function(err, privilegeSaved) { if (err) { console.log("error occurred saving privilege");}}; // links to make available to managers var links = []; var managerPanel = {title: "Manager Panel", link: "/panel/manager"}; links.push(managerPanel); // addPrivilege = function(privilege, links, callback) accounts.addPrivilege(accounts.managerPrivilegeName, links, callback); /***** Create General Manager Account *****/ // requestNewAccount = function(username, pass, email, fullName, callback) accounts.requestNewAccount("gm", passwords.gmpass, "[email protected]", "General Manager", function(err, saved) { if (err) { console.log("error creating gm account:", err); } }); // db.verifyAccount = function(username, callback) accounts.verifyAccount("gm", function(err, o) { if (err) { console.log("error validating gm user", err); } }); // updatePrivilege = function(username, privilege, shouldHave, callback) accounts.updatePrivilege("gm", accounts.managerPrivilegeName, true, callback); console.log("Finished setting up Secret DJ Panel");
JavaScript
0.000046
@@ -924,67 +924,29 @@ %7D%0D%0A -%7D);%0D%0A%0D%0A// db.verifyAccount = function(username, callback)%0D%0A + else if (o) %7B%0D%0A acco @@ -986,24 +986,28 @@ (err, o) %7B%0D%0A + if (err) %7B @@ -1060,11 +1060,81 @@ %7D%0D%0A -%7D); + %7D);%0D%0A %7D%0D%0A%7D);%0D%0A%0D%0A// db.verifyAccount = function(username, callback)%0D%0A %0D%0A%0D%0A
15fbfbfd03cc834a8c785dfb08f3ae27ff7fdbaa
optimize code
lib/positions.js
lib/positions.js
var config = require(__dirname + '/../config.js'); var utils = require(__dirname + '/../utils.js'); var assets = require(__dirname + '/assets.js'); var rates = require(__dirname + '/rates'); var async = require('async'); var position = function() { return { 'pid' : 0, 'aid' : 0, 'cid' : 0, 'tid' : 0, 'amount' : 0, 'open' : 0, 'opentime' : 0, 'close' : 0, 'closetime' : 0 } }; /* SELECT * FROM positions LEFT JOIN (SELECT rates.* FROM (SELECT MAX(rid) as rid FROM rates GROUP BY CONCAT(aid, "-", cid)) as last LEFT JOIN rates ON (last.rid = rates.rid)) as lastrates ON (positions.aid = lastrates.aid) */ /* * get one or all posoitions */ var get = function(id, connection, callback) { var q = 'SELECT *, assets.name as assetname FROM positions LEFT JOIN assets ON (positions.aid = assets.aid) LEFT JOIN connectors ON (positions.cid = connectors.cid)'; if(id !== 'all') { q += ' WHERE positions.pid = ' + parseInt(id, 10); } q += ' ORDER BY positions.aid ASC, connectors.name ASC'; if (config.dev) utils.log(q); connection.query(q, function(err, rows) { if(err) { if (config.dev) utils.log(err); callback(err); } else { if(config.dev) utils.log(rows); var positions = rows; // Get last rates for each asset var async = require('async'); async.eachOfLimit(rows, 1, function(item, key, cb){ assets.last(item.aid, connection, function(e, rows){ if (e) { // TODO: Error handling } else { positions[key].rates = rows; } cb(); }); }, function(err){ async.series({ BTC: function(cb){rates.last(110, 12, connection, cb);}, LTC: function(cb){rates.last(25, 1, connection, cb);} }, function(err, results){ callback(null, {'BTC': {bitstamp:results.BTC},'LTC': {poloniex:results.LTC}, positions: positions}); }); }); } }); }; exports.get = get; var update = function(id, values, connection, callback) { var cols = []; var vals = []; var pos = new position(); for (let i in values) { if (typeof pos[i] !== 'undefined') { vals.push(values[i]); cols.push(i + ' = ?'); } else { utils.log('Table Col ' + i + 'does not exist. Dropping.'); } } var q = 'UPDATE positions SET ' + cols.join(', ') + ' WHERE pid = ?'; if (config.dev) utils.log(q); vals.push(id); connection.query(q, function(err, results, fields) { if(err) { if (config.dev) utils.log(err); callback(err); } else { if(config.dev) utils.log(results); if(config.dev) utils.log(fields); callback(null); } }); }; exports.update = update;
JavaScript
0.999117
@@ -1405,47 +1405,8 @@ set%0A - var async = require('async');%0A @@ -1434,17 +1434,17 @@ t(rows, -1 +2 , functi
095308b911b496a7f9762638e954bcd1d70b739a
Make logging work on more environments (#499)
packages/autobahn/lib/log.js
packages/autobahn/lib/log.js
/////////////////////////////////////////////////////////////////////////////// // // AutobahnJS - http://autobahn.ws, http://wamp.ws // // A JavaScript library for WAMP ("The Web Application Messaging Protocol"). // // Copyright (c) Crossbar.io Technologies GmbH and contributors // // Licensed under the MIT License. // http://www.opensource.org/licenses/mit-license.php // /////////////////////////////////////////////////////////////////////////////// var debug = function () {}; if ('AUTOBAHN_DEBUG' in global && AUTOBAHN_DEBUG && 'console' in global) { debug = function () { console.log.apply(console, arguments); } } var warn = console.warn; exports.debug = debug; exports.warn = warn;
JavaScript
0
@@ -456,19 +456,19 @@ /////%0A%0A%0A -var +let debug = @@ -642,11 +642,11 @@ %0A%7D%0A%0A -var +let war @@ -661,16 +661,30 @@ ole.warn +.bind(console) ;%0A%0Aexpor
ff99989ffd32dd311fb792a62d43a4d4916c3a75
Accumulated commit of the following from branch 'origin/ready/jph-us126':
selenium/selenium_test.js
selenium/selenium_test.js
'use strict'; var config = require('./saucelabs.config'); var assert = require('assert'); var test = require('selenium-webdriver/testing'); var webdriver = require('selenium-webdriver'); var isSauceLabsTest = false; var sauceLabsCaps = config.saucelabs.browserCaps; var SAUCE_URL = 'http://ondemand.saucelabs.com:80/wd/hub'; var DBC_URLS = ['http://uxwin7-01:4444/wd/hub', 'http://uxwin81-01:4444/wd/hub', 'http://uxwin10-01:5432/wd/hub']; var BASE_URL = isSauceLabsTest ? 'https://pg.demo.dbc.dk' : process.env.SELENIUM_URL || 'http://localhost:8080'; // eslint-disable-line function runAllTests(driverCaps) { test.describe('Express endpoint', function () { test.it('/profile/login can be reached', function () { var endpoint = '/profile/login'; var driver = driverCaps.build(); driver.get(BASE_URL + endpoint); driver.wait(webdriver.until.elementIsVisible(driver.findElement({tagName: 'body'})), 12000); var body = driver.findElement({tagName: 'body'}); var header = body.findElement({id: 'header'}); header.getId() .then(function (id) { assert.notEqual(typeof id, 'undefined'); }); driver.quit(); }); test.it('/profile/signup can be reached', function () { var endpoint = '/profile/signup'; var driver = driverCaps.build(); driver.get(BASE_URL + endpoint); driver.wait(webdriver.until.elementIsVisible(driver.findElement({tagName: 'body'})), 12000); var body = driver.findElement({tagName: 'body'}); var header = body.findElement({id: 'header'}); header.getId() .then(function (id) { assert.notEqual(typeof id, 'undefined'); }); driver.quit(); }); }); test.describe('Login page', function () { test.it('is rendered', function () { var endpoint = '/profile/login'; var driver = driverCaps.build(); driver.get(BASE_URL + endpoint); driver.wait(webdriver.until.elementIsVisible(driver.findElement({tagName: 'input', name: 'username'})), 5000); var emailInput = driver.findElement({tagName: 'input', name: 'username'}); emailInput.sendKeys('[email protected]'); driver.quit(); }); }); test.describe('Signup page', function () { test.it('is rendered', function () { var endpoint = '/profile/signup'; var driver = driverCaps.build(); driver.get(BASE_URL + endpoint); driver.wait(webdriver.until.elementIsVisible(driver.findElement({tagName: 'input', name: 'username'})), 5000); driver.quit(); }); }); test.describe('Library Suggest - Autocomplete', function () { test.it('returns suggestions', function () { var driver = driverCaps.build(); driver.get(BASE_URL + '/library/suggest'); driver.wait(webdriver.until.elementIsVisible(driver.findElement({tagName: 'input'})), 5000); var searchField = driver.findElement({tagName: 'input'}); searchField.sendKeys('køb'); driver.wait(webdriver.until.elementLocated(webdriver.By.className('autocomplete--row-text')), 5000); var acRow = driver.findElement(webdriver.By.className('autocomplete--row-text')); acRow.getInnerHtml().then(function(html) { assert.notEqual(typeof html, 'undefined'); }); acRow.click(); driver.quit(); }); }); test.describe('Library', function () { test.it('SSR rendering of library', function () { var driver = driverCaps.build(); var libraryId = '710100'; var branchName = 'Hovedbiblioteket, Krystalgade'; // ssrTimeout url param sets how many milliseconds to wait for data // Test times out before the ssrTimeout to ensure whats sent is rendered server side // If this test functions it SSR must work driver.get(BASE_URL + '/library?id=' + libraryId + '&ssrTimeout=900000'); driver.wait(webdriver.until.elementLocated(webdriver.By.className('library--branch-name')), 5000); var libraryTitle = driver.findElement(webdriver.By.className('library--branch-name')); libraryTitle.getInnerHtml().then(function (html) { assert.equal(html, branchName); }); driver.quit(); }); }); } if (isSauceLabsTest) { for (var k in sauceLabsCaps) { if (sauceLabsCaps.hasOwnProperty(k)) { var caps = sauceLabsCaps[k]; caps.username = config.saucelabs.username; caps.accessKey = config.saucelabs.accessKey; var sauceDriverCaps = new webdriver.Builder(). usingServer(SAUCE_URL). withCapabilities(caps); runAllTests(sauceDriverCaps); } } } else if (process.env.JENKINS_TESTING || false) { // eslint-disable-line var driver = new webdriver.Builder() .forBrowser(process.env.SELENIUM_BROWSER_NAME || 'internet explorer') // eslint-disable-line .usingServer(process.env.SELENIUM_TEST_SERVER || DBC_URLS[1]); // eslint-disable-line runAllTests(driver); } else { var chromeCaps = new webdriver.Builder() .withCapabilities(webdriver.Capabilities.chrome()); runAllTests(chromeCaps); }
JavaScript
0.999999
@@ -571,16 +571,110 @@ le-line%0A +var driverTimeout = process.env.DRIVER_TIMEOUT %7C%7C 10000; // eslint-disable-line no-process-env %0A%0Afuncti @@ -1011,37 +1011,45 @@ ame: 'body'%7D)), -12000 +driverTimeout );%0A var bod @@ -1563,13 +1563,21 @@ )), -12000 +driverTimeout );%0A @@ -2140,36 +2140,45 @@ 'username'%7D)), -5000 +driverTimeout );%0A var ema @@ -2653,20 +2653,29 @@ me'%7D)), -5000 +driverTimeout );%0A @@ -2996,28 +2996,37 @@ 'input'%7D)), -5000 +driverTimeout );%0A%0A va @@ -3214,28 +3214,37 @@ ow-text')), -5000 +driverTimeout );%0A%0A va @@ -4112,12 +4112,21 @@ )), -5000 +driverTimeout );%0A%0A
1f2c98633f5cea82a7bc02792a636dc0817ef8ce
fix an easy one
tests/transform-tests.js
tests/transform-tests.js
import should from 'should'; import { transformString } from '../src/transform'; function test(input, output) { it(input, () => should(transformString(input)).equal(output)); } describe('transform', () => { it('should turn a string into a string', () => transformString("()").should.be.a.String()); describe('variables', () => { test('(let a 2)', 'var a = 2;'); test('(let a 2 b 4 c 5)', 'var a = 2, b = 4, c = 5;'); test('(let a (+ 1 2))', 'var a = (1 + 2);'); }); describe('math', () => { test('(+ 1 2)', '(1 + 2)'); test('(- 9 6)', '(9 - 6)'); test('(* 2 3)', '(2 * 3)'); test('(/ 4 2)', '(4 / 2)'); test('(* (+ 2 4) (- 5 3))', '((2 + 4) * (5 - 3))'); test('(+ 2 3 4 5)', '(2 + 3 + 4 + 5)'); test('(Math.pow 2 4)', 'Math.pow( 2, 4 )'); test('(Math.abs -4)', 'Math.abs( -4 )'); test('(Math.pow (* 2 3) (- 2 4))', 'Math.pow( (2 * 3), (2 - 4) )'); }); describe('control flow', () => { describe('if else', () => {}); describe('for loops', () => {}); describe('while loops', () => {}); }); describe('function literals', () => { test('(function ())', '(function () { return undefined;})'); test('(function () 4)', '(function () { return 4;})'); test('(function (x y) (+ x y))', '(function (x, y) { return (x + y);})'); test('(function adder (x y) (+ x y))', '(function adder(x, y) { return (x + y);})'); test('(function (x) (function (y) (+ x y)))', '(function (x) { return (function (y) { return (x + y);});})'); }); describe('function calls', () => { test('(some_func 1 2 3)', 'some_func( 1, 2, 3 )'); test('(func 1 (nested 2 3))', 'func( 1, nested( 2, 3 ) )'); test('(empty_func)', 'empty_func( )'); }); describe('data structures', () => { describe('arrays', () => {}); describe('objects', () => {}); }); describe('modules', () => { test(` (module testEm (+ 1 2)) `, `module('testEm', function (require, export) {(1 + 2);})`); test(` (module testEm (export varA (+ 1 2))) `, `module('testEm', function (require, export) {export('varA', (1 + 2));})`); test(` (module testEmA (require testEmB (var-a))) `, `module('testEmA', function (require, export) { var testEmB = require('testEmB'); var varA = testEmB['varA']; })`); test(` (module testEmA (require testEmB (varA varB varC))) `, `module('testEmA', function (require, export) { var testEmB = require('testEmB'); var varA = testEmB['varA']; var varB = testEmB['varB']; var varC = testEmB['varC']; })`); }); describe('calling methods on dynamic entities', () => {}); });
JavaScript
0.001609
@@ -1713,18 +1713,16 @@ ty_func( - )');%0A %7D
831d4bc6781525a1298228f4780a534d164b3fc4
update author default avatar uri
source/common/index.js
source/common/index.js
import React, { NetInfo } from 'react-native'; import _ from 'lodash'; import Config from '../config'; import entities from 'entities'; export function getBloggerName(authorUri) { authorUri = _.trimEnd(authorUri, '\/'); return authorUri.slice(authorUri.lastIndexOf("\/") + 1); } const seedColors = ['#ec898a', '#69bb97', '#55b9ce', '#cc936e', '#65be8d', '#6bb6cb', '#ae9cc3']; export function getRandomColor(){ return seedColors[_.random(0, seedColors.length -1)]; } export function getBloggerAvatar(avatarUri){ if (avatarUri && !_.endsWith(avatarUri, ".gif")) { avatarUri = avatarUri.replace(/face/, 'avatar'); avatarUri = avatarUri.replace(/avatar\/u/, 'avatar\/a'); return avatarUri; } return "http://www.sucaijishi.com/uploadfile/2016/0203/20160203022631602.png"; } export function filterCodeSnippet(codeText) { if (codeText && codeText.length) { codeText = _.trim(codeText); codeText = _.trim(codeText, '&#xD;'); if (codeText.startsWith(' ') || codeText.endsWith(' ') || codeText.startsWith('&#xD;') || codeText.endsWith('&#xD;')) { codeText = filterCodeSnippet(codeText); } } return codeText; } export function filterCommentData(commentText) { if (commentText && commentText.length) { commentText = commentText.replace(/<(script)[\S\s]*?\1>|<\/?(a|img)[^>]*>/gi, ""); commentText = "<comment>" + commentText + "</comment>"; } return commentText; } export function decodeHTML(htmlStr) { if (htmlStr && htmlStr.length) { htmlStr = entities.decodeHTML(htmlStr); } return htmlStr; } const imageSourcePath = Config.domain + "/public/img/metarial/"; export function getImageSource(key){ let imageLen = 20; if (!key) { key = _.random(1, imageLen - 1); } return imageSourcePath + key + ".jpg?v=1.1"; }
JavaScript
0
@@ -750,78 +750,29 @@ urn -%22http://www.sucaijishi.com/uploadfile/2016/0203/20160203022631602.png%22 +Config.appInfo.avatar ;%0A%7D%0A
91c6c1d76a5ae5bfff889be39dc8eb843224d026
add missing semicolon
packages/all/src/index.js
packages/all/src/index.js
import * as core from '@candela/core'; import * as events from '@candela/events'; import * as geojs from '@candela/geojs'; import * as glo from '@candela/glo'; import * as lineup from '@candela/lineup'; import * as onset from '@candela/onset'; import * as sententree from '@candela/sententree'; import * as similaritygraph from '@candela/similaritygraph'; import * as size from '@candela/size'; import * as stats from '@candela/stats'; import * as treeheatmap from '@candela/treeheatmap'; import * as upset from '@candela/upset'; import * as vega from '@candela/vega'; function load (obj, target) { for (let prop in obj) { target[prop] = obj[prop]; } } // Collect all candela components into a single object. let components = {}; for (let bundle of [geojs, glo, lineup, onset, sententree, similaritygraph, stats, treeheatmap, upset]) { load(bundle, components); } for (let component in vega) { if (vega[component] !== vega.VegaView) { components[component] = vega[component] } } // Collect all candela mixings into a single object. let mixins = {}; for (let bundle of [events, size]) { load(bundle, mixins); } mixins.VegaView = vega.VegaView; let VisComponent = core.VisComponent; // Export everything, both as default... export default { VisComponent, components, mixins }; // ...and non-default. export { VisComponent, components, mixins };
JavaScript
0.000507
@@ -985,16 +985,17 @@ mponent%5D +; %0A %7D%0A%7D%0A%0A
3ab26d38e886fd43ae4f91123c80c16a7949f093
add classnames, rest props
packages/vx-tooltip/src/tooltips/Tooltip.js
packages/vx-tooltip/src/tooltips/Tooltip.js
import React from 'react'; export default function Tooltip(props) { return ( <div className="vx-tooltip-portal" style={{ position: 'absolute', top: props.top, left: props.left, backgroundColor: 'white', color: '#666666', padding: '.3rem .5rem', borderRadius: '3px', fontSize: '14px', boxShadow: '0 1px 2px rgba(33,33,33,0.2)', lineHeight: '1em', pointerEvents: 'none', ...props.style }} > {props.children} </div> ); }
JavaScript
0
@@ -19,16 +19,45 @@ 'react'; +%0Aimport cx from 'classnames'; %0A%0Aexport @@ -91,16 +91,61 @@ rops) %7B%0A + const %7B className, ...restProps %7D = props;%0A return @@ -172,17 +172,21 @@ assName= -%22 +%7Bcx(' vx-toolt @@ -198,9 +198,22 @@ rtal -%22 +', className)%7D %0A @@ -575,19 +575,18 @@ ... -props.style +restProps, %0A
3654ada5570327e30965e252b4f2851f81cd6bb2
Replace var with const
example.js
example.js
var fibonacci = require ('fibonacci'); // Return last result object fibonacci.on ('done', console.log); // Run 1000 iterations fibonacci.iterate (1000);
JavaScript
0.000027
@@ -1,7 +1,9 @@ -var +const fib
e92979b360a832df6dae6c00e4ce850284a1d2c5
check --quality is not given either for auto container
bin/ytdl.js
bin/ytdl.js
#!/usr/bin/env node var path = require('path'); var fs = require('fs'); var ytdl = require('..'); var cliff = require('cliff'); require('colors'); var info = require('../package'); var opts = require('nomnom') .option('version', { abbr: 'v', flag: true, callback: function() { console.log(info.version); process.exit(); }, help: 'Print program version.' }) .option('url', { position: 0, required: true, help: 'URL to the video.' }) .option('quality', { abbr: 'q', metavar: 'ITAG', help: 'Video quality to download. Default: highest' }) .option('range', { abbr: 'r', metavar: 'INT-INT', help: 'Byte range to download. ie 10355705-12452856' }) .option('output', { abbr: 'o', metavar: 'FILE', help: 'Where to save the file. Default: stdout' }) .option('filterContainer', { full: 'filter-container', metavar: 'REGEXP', help: 'Filter in format container. Default: -o ext' }) .option('unfilterContainer', { full: 'unfilter-container', metavar: 'REGEXP', help: 'Filter out format container.' }) .option('filterResolution', { full: 'filter-resolution', metavar: 'REGEXP', help: 'Filter in format resolution.' }) .option('unfilterResolution', { full: 'unfilter-resolution', metavar: 'REGEXP', help: 'Filter out format resolution.' }) .option('filterEncoding', { full: 'filter-encoding', metavar: 'REGEXP', help: 'Filter in format encoding.' }) .option('unfilterEncoding', { full: 'unfilter-encoding', metavar: 'REGEXP', help: 'Filter out format encoding.' }) .option('info', { abbr: 'i', flag: true, help: 'Print video info without downloading' }) .script('ytdl') .colors() .parse() ; /** * Converts seconds into human readable time hh:mm:ss * * @param {Number} seconds * @return {String} */ function toHumanTime(seconds) { var h = Math.floor(seconds / 3600); var m = Math.floor(seconds / 60) % 60; var time; if (h > 0) { time = h + ':'; if (m < 10) { m = '0' + m; } } else { time = ''; } var s = seconds % 60; if (s < 10) { s = '0' + s; } return time + m + ':' + s; } /** * Prints basic video information. * * @param {Object} info */ function printVideoInfo(info) { console.log(); console.log('title: '.grey.bold + info.title); console.log('author: '.grey.bold + info.author); var rating = typeof info.avg_rating === 'number' ? info.avg_rating.toFixed(1) : info.avg_rating; console.log('average rating: '.grey.bold + rating); console.log('view count: '.grey.bold + info.view_count); console.log('length: '.grey.bold + toHumanTime(info.length_seconds)); } if (opts.info) { ytdl.getInfo(opts.url, function(err, info) { if (err) { console.error(err.message); process.exit(1); return; } printVideoInfo(info); var cols = [ 'itag', 'container', 'resolution', 'video enc', 'audio bitrate', 'audio enc' ]; info.formats.forEach(function(format) { format['video enc'] = format.encoding; format['audio bitrate'] = format.audioBitrate; format['audio enc'] = format.audioEncoding; cols.forEach(function(col) { format[col] = format[col] || ''; }); }); console.log('formats:'.grey.bold); var colors = ['green', 'blue', 'green', 'blue', 'green', 'blue']; console.log(cliff.stringifyObjectRows(info.formats, cols, colors)); ytdl.cache.die(); }); return; } var output = opts.output; var writeStream; if (output) { writeStream = fs.createWriteStream(output); var ext = path.extname(output); if (ext && !opts.filterContainer) { opts.filterContainer = '^' + ext.slice(1) + '$'; } } else { writeStream = process.stdout; } var ytdlOptions = {}; ytdlOptions.quality = opts.quality; ytdlOptions.range = opts.range; // Create filters. var filters = []; /** * @param {String} field * @param {String} regexpStr * @param {Boolean|null} negated */ function createFilter(field, regexpStr, negated) { try { var regexp = new RegExp(regexpStr, 'i'); } catch (err) { console.error(err.message); process.exit(1); } filters.push(function(format) { return negated !== regexp.test(format[field]); }); } ['container', 'resolution', 'encoding'].forEach(function(field) { var key = 'filter' + field[0].toUpperCase() + field.slice(1); if (opts[key]) { createFilter(field, opts[key], false); } key = 'un' + key; if (opts[key]) { createFilter(field, opts[key], true); } }); ytdlOptions.filter = function(format) { return filters.every(function(filter) { return filter(format); }); }; var readStream = ytdl(opts.url, ytdlOptions); readStream.pipe(writeStream); readStream.on('error', function(err) { console.error(err.message); process.exit(1); }); // Converst bytes to human readable unit. // Thank you Amir from StackOverflow. var units = ' KMGTPEZYXWVU'; function toHumanSize(bytes) { if (bytes <= 0) { return 0; } var t2 = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), 12); return (Math.round(bytes * 100 / Math.pow(1024, t2)) / 100) + units.charAt(t2).replace(' ', '') + 'B'; } // Print progress bar and some video info if not streaming to stdout. if (output) { readStream.on('info', function(info, format) { printVideoInfo(info); console.log('container: '.grey.bold + format.container); console.log('resolution: '.grey.bold + format.resolution); console.log('encoding: '.grey.bold + format.encoding); console.log('size: '.grey.bold + toHumanSize(format.size)); console.log('output: '.grey.bold + output); console.log(); // Create progress bar. var bar = require('progress-bar').create(process.stdout, 50); bar.format = '$bar; $percentage;%'; // Keep track of progress. var dataRead = 0; readStream.on('data', function(data) { dataRead += data.length; var percent = dataRead / format.size; bar.update(percent); }); ytdl.cache.die(); }); } readStream.on('end', function onend() { console.log(); }); process.on('SIGINT', function onsigint() { console.log(); process.exit(); });
JavaScript
0
@@ -3721,16 +3721,33 @@ (ext && + !opts.quality && !opts.f
e7667b9b3fd5f83aee9f96cf9714b392eabf36ed
remove trailing comma
tests/unit/ErrorUtils.js
tests/unit/ErrorUtils.js
define([ 'intern!object', 'intern/chai!assert', 'oe_dojo/ErrorUtils' ], function ( registerSuite, assert, ErrorUtils ) { registerSuite({ name: 'ErrorUtils', 'parseError msg and title error': function() { var errorMsgTitle = {title: 'Incorrecte Token', message: 'Het aangeboden SSO token is niet geldig'}; // msg and title error assert.deepEqual(ErrorUtils.parseError(errorMsgTitle), errorMsgTitle, 'parseError should return the given error with message and title'); }, 'parseError unformatted error': function() { var errorNoFormat = 'Het aangeboden SSO token is ongeldig'; // unformatted error (string) assert.deepEqual(ErrorUtils.parseError(errorNoFormat), {message: 'Het aangeboden SSO token is ongeldig', title: 'Er is een fout opgetreden'}, 'parseError should return the given unformatted error as message of the returned error object'); }, 'parseError formatted error': function() { var errorFormatted = { response: { text: '{"message": "Het aangeboden SSO token is incorrect", "errors": ["error 1", "error 2"]}' } }; assert.deepEqual(ErrorUtils.parseError(errorFormatted), {title: 'Het aangeboden SSO token is incorrect', message: '-error 1</br>-error 2</br>'}, 'parseError should return the parsed and formatted error'); }, 'parseError formatted error without message': function() { var errorFormatted = { response: { text: '{"errors": ["error 1", "error 2"]}' } }; assert.deepEqual(ErrorUtils.parseError(errorFormatted), {title: 'Er is een fout opgetreden', message: '-error 1</br>-error 2</br>'}, 'parseError should return the parsed and formatted error with the default title'); }, 'parseError formatted error with empty errors array': function() { var errorFormatted = { response: { text: '{"message": "Het aangeboden SSO token is incorrect", "errors": []}' } }; assert.deepEqual(ErrorUtils.parseError(errorFormatted), {title: 'Er is een fout opgetreden', message: 'Het aangeboden SSO token is incorrect'}, 'parseError should return an error with the default title and the error message'); }, 'error during json parsing': function() { var errorHtml = { response: { text: '<html></html>' } }; assert.deepEqual(ErrorUtils.parseError(errorHtml), {title: 'Er is een fout opgetreden', message: 'Het formaat van de foutmelding is onleesbaar'}, 'parseError should return a default error telling the error format is incorrect'); }, }); });
JavaScript
0.999551
@@ -2700,18 +2700,16 @@ );%0A %7D -,%0A %0A%0A %7D);%0A
dc4edd91c512c179b4b9970cead26229aabf5688
use random english words for example
example.js
example.js
const chalk = require('chalk') const chromahash = require('./') const words = 'hello there how are you doing today and what other ' + 'wonderful things can we accomplish today ' + 'we seem to not be able to generate different enough colors' words.split(' ').forEach(w => { const hex = '#' + chromahash(w) console.log(hex, chalk.bgHex(hex)(w)) })
JavaScript
0.000118
@@ -1,16 +1,67 @@ +const words = require('an-array-of-english-words')%0A const chalk = re @@ -113,224 +113,130 @@ ')%0A%0A -const words =%0A 'hello there how are you doing today and what other ' +%0A 'wonderful things can we accomplish today ' +%0A 'we seem to not be able to generate different enough colors'%0A%0Awords.split(' ').forEach(w =%3E %7B%0A +Array(20)%0A .fill()%0A .forEach(() =%3E %7B%0A const rand = Math.floor(Math.random() * 250000)%0A const word = words%5Brand%5D%0A co @@ -263,18 +263,23 @@ mahash(w -)%0A +ord)%0A consol @@ -311,10 +311,15 @@ x)(w +ord ))%0A + %7D)%0A
715a8e9af675c2b924efce4db3c993f00780d3c2
fix path to dist/assets/*
packages/xod-client-browser/webpack/base.js
packages/xod-client-browser/webpack/base.js
const path = require('path'); const webpack = require('webpack'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const pkgpath = subpath => path.join(__dirname, '..', subpath); module.exports = { devtool: 'source-map', entry: [ 'babel-polyfill', pkgpath('src/shim.js'), pkgpath('src/index.jsx'), pkgpath('node_modules/xod-client/src/core/styles/main.scss'), ], output: { filename: 'bundle.js', path: pkgpath('dist'), publicPath: '', }, resolve: { modulesDirectories: [ pkgpath('node_modules'), pkgpath('node_modules/xod-client/node_modules'), pkgpath('node_modules/xod-client/node_modules/xod-core/node_modules'), ], extensions: ['', '.js', '.jsx', '.scss'], }, module: { loaders: [ { test: /src\/.*\.jsx?$/, loaders: [ 'babel?presets[]=react,presets[]=es2015', ], }, { test: /\.scss$/, loaders: [ 'style', 'css', 'sass?outputStyle=expanded', ], }, { test: /assets\/.*\.(jpe?g|png|gif|svg|ttf|eot|svg|woff|woff2)?$/, loaders: [ 'file?name=[path][name].[ext]?[hash:6]&context=./src', ], }, { test: /node_modules\/font-awesome\/.*\.(jpe?g|png|gif|svg|ttf|eot|svg|woff|woff2)(\?\S*)?$/, loaders: [ 'file?name=assets/font-awesome/[name].[ext]?[hash:6]', ], }, { test: /\.json5$/, loader: 'json5-loader', }, { test: /json5\/lib\/require/, loader: 'null', } ], }, plugins: [ new webpack.NoErrorsPlugin(), new CopyWebpackPlugin([ { from: pkgpath('src/index.html') }, ]), ], };
JavaScript
0
@@ -1167,16 +1167,23 @@ le?name= +assets/ %5Bpath%5D%5Bn @@ -1211,20 +1211,44 @@ ontext=. -/src +./xod-client/src/core/assets ',%0A
f035ed59e28db05bd79b2a44e0c863ed122934b4
remove logging
example.js
example.js
var Merkle = require('./') var createStream = require('./stream') var hash = require('./util').hash function isDefined (v) { return 'undefined' !== typeof v } /* Example of how to use Merkle for replication. */ module.exports = function (_hash) { var set = {} var tree = new Merkle() hash = _hash || hash return { set: set, tree: tree, add: function (obj) { var h = hash(obj) set[h] = obj tree.update(h) return this }, createStream: function () { var s = createStream(tree).start() s.on('send_branch', function (pre, h) { var t = tree.subtree(pre) var l = t.leaves() l.forEach(function (key) { console.error('>>>', pre, key) if(isDefined(set[key])) s.send(key, set[key]) else console.error('do not have branch:'+ key) console.log('.') }) }) s.on('receive', function (key, obj) { console.error('<<<', key, obj) var _key = hash(obj) if(_key !== key) s.emit('error', new Error('invalid object, expected:' + key + ' but got: ' + _key)) else set[key] = obj }) return s } } }
JavaScript
0.000001
@@ -684,32 +684,34 @@ ey) %7B%0A +// console.error('%3E @@ -875,32 +875,34 @@ key)%0A +// console.log('.') @@ -966,32 +966,34 @@ obj) %7B%0A +// console.error('%3C
e0b24e3bb82cb59fc8150a7cb3edfca3646f7add
make _createIndexes in module unit-manager
src/managers/master/unit-manager.js
src/managers/master/unit-manager.js
'use strict' var ObjectId = require("mongodb").ObjectId; require("mongodb-toolkit"); var DLModels = require('dl-models'); var map = DLModels.map; var Unit = DLModels.master.Unit; var BaseManager = require('../base-manager'); var i18n = require('dl-i18n'); module.exports = class UnitManager extends BaseManager { constructor(db, user) { super(db, user); this.collection = this.db.use(map.master.collection.Unit); } _getQuery(paging) { var deleted = { _deleted: false }; var query = paging.keyword ? { '$and': [deleted] } : deleted; if (paging.keyword) { var regex = new RegExp(paging.keyword, "i"); var filterDivision = { 'division': { '$regex': regex } }; var filterSubDivision = { 'subDivision': { '$regex': regex } }; var $or = { '$or': [filterDivision, filterSubDivision] }; query['$and'].push($or); } return query; } _validate(unit) { var errors = {}; return new Promise((resolve, reject) => { var valid = unit; // 1. begin: Declare promises. var getunitPromise = this.collection.singleOrDefault({ "$and": [{ _id: { '$ne': new ObjectId(valid._id) } }, { division: valid.division, subDivision: valid.subDivision }] }); // 2. begin: Validation. Promise.all([getunitPromise]) .then(results => { var _unit = results[0]; if (!valid.division || valid.division == '') errors["division"] = i18n.__("Unit.division.isRequired:%s is required", i18n.__("Unit.division._:Division")); //"Divisi Tidak Boleh Kosong"; else if (_unit) { errors["division"] = i18n.__("Unit.division.isExists:%s is already exists", i18n.__("Unit.division._:Division"));//"Perpaduan Divisi dan Sub Divisi sudah terdaftar"; } if (!valid.subDivision || valid.subDivision == '') errors["subDivision"] = i18n.__("Unit.subDivision.isRequired:%s is required", i18n.__("Unit.subDivision._:SubDivision")); //"Sub Divisi Tidak Boleh Kosong"; else if (_unit) { errors["subDivision"] = i18n.__("Unit.subDivision.isExists:%s is already exists", i18n.__("Unit.subDivision._:SubDivision"));//"Perpaduan Divisi dan Sub Divisi sudah terdaftar"; } if (Object.getOwnPropertyNames(errors).length > 0) { var ValidationError = require('../../validation-error'); reject(new ValidationError('data does not pass validation', errors)); } valid = new Unit(unit); valid.stamp(this.user.username, 'manager'); resolve(valid); }) .catch(e => { reject(e); }) }); } }
JavaScript
0.000001
@@ -3400,13 +3400,461 @@ ;%0A %7D%0A + _createIndexes() %7B%0A var dateIndex = %7B%0A name: %60ix_$%7Bmap.master.collection.Unit%7D__updatedDate%60,%0A key: %7B%0A _updatedDate: -1%0A %7D%0A %7D%0A%0A var codeIndex = %7B%0A name: %60ix_$%7Bmap.master.collection.Unit%7D_code%60,%0A key: %7B%0A code: 1%0A %7D,%0A unique: true%0A %7D%0A%0A return this.collection.createIndexes(%5BdateIndex, codeIndex%5D);%0A %7D%0A %0A%7D
5fd52baf306fb7c6100e1e4e455f1d48b6318eae
Implement HGET
Source/Methods_Hash.js
Source/Methods_Hash.js
"use strict"; var Main = module.parent.exports; Main.ActionHSET = function(Request){ if(Request.length < 3){ throw new Error(Main.MSG_ARGS_LESS); } Main.ValidateArguments(Main.ARGS_ODD, Request.length); let Key = Request.shift(); let Value = this.Database.get(Key); try { Main.Validate(Main.VAL_HASH, 'HSET', Value); } catch(err){ Value = new Map(); this.Database.set(Key, Value); } for(let Number = 0; Number < Request.length; Number += 2){ let HValue = Main.NormalizeType(Request[Number + 1]); Value.set(Request[Number], HValue); } return {Type: 'OK'}; };
JavaScript
0.000001
@@ -599,8 +599,384 @@ OK'%7D;%0A%7D; +%0A%0AMain.ActionHGET = function(Request)%7B%0A let Key = Request.shift();%0A let Value = this.Database.get(Key);%0A%0A if(typeof Value !== 'undefined')%0A Main.Validate(Main.VAL_HASH, 'HGET', Value);%0A%0A if(Request.length === 1)%7B%0A return Value && Value.get(Request%5B0%5D) %7C%7C '';%0A %7D else %7B%0A return Request.map(function(Key)%7B%0A return Value && Value.get(Key) %7C%7C '';%0A %7D);%0A %7D%0A%7D;
821fa68654ad04619f7337103823f8dba283a86d
Update server.es6
src/Plugins/server/server.es6
src/Plugins/server/server.es6
import http from 'http'; import fs from 'fs'; import http2 from 'http2'; import Koa from 'koa'; import path from 'path'; import serve from 'koa-serve'; import {RenderUtil} from '../../helper'; import render from 'koa-ejs'; import dispatcher from './middleware/dispatcher'; import routeMap from './middleware/routemap'; import {util} from '../../helper'; import {Server as WebSocketServer} from 'ws'; import bodyParser from 'koa-bodyparser'; class Server { constructor(config) { this.middleware = []; this.ifAppendHtmls = []; this.app = Koa(); Object.assign(this, config); if (!this.syncDataMatch) { this.syncDataMatch = (url) => path.join(this.syncData, url); } if (!this.asyncDataMatch) { this.asyncDataMatch = (url) => path.join(this.asyncData, url); } if (undefined == this.divideMethod) { this.divideMethod = false; } this.setRender(); this.setStaticHandler(); } delayInit() { const app = this.app; if (!this.ifProxy) { app.use(bodyParser()); } app.use(routeMap(this)); this.middleware.forEach((g) => { app.use(g); }); app.use(dispatcher(this)); this.htmlAppender(); } use(middleware) { this.middleware.push(middleware(this)); } setRender() { if (this.tpl) { Object.assign(this, this.tpl); } let Render = this.RenderUtil || RenderUtil; this.extension = this.extension || 'ftl'; this.tplRender = new Render({viewRoot: this.viewRoot}); render(this.app, { root: path.resolve(__dirname, '../../../views'), layout: 'template', viewExt: 'html', cache: process.env.NODE_ENV !== 'development', debug: true }); } setStaticHandler() { let rootdir; let dir; if (this.static && !Array.isArray(this.static)) this.static = [this.static]; this.static.forEach((item) => { dir = /[^(\\\/)]*$/.exec(item); if (!dir || !dir[0]) return; rootdir = item.replace(/[^(\\\/)]*$/, ''); this.app.use(serve(dir[0], rootdir)); }); this.app.use(serve('foxman_client', path.resolve(__dirname, '../../../'))); } appendHtml(condition) { this.ifAppendHtmls.push(condition); } htmlAppender() { const ifAppendHtmls = this.ifAppendHtmls; let html; this.app.use(function*(next) { if (/text\/html/ig.test(this.type)) { html = ifAppendHtmls.map((item) => { return item.condition(this.request) ? item.html : ''; }).join(''); this.body = this.body + html; } yield next; }); } createServer() { const port = this.port || 3000; this.delayInit(); const root = path.resolve(__dirname, '..', '..', '..'); const httpOptions = { key: fs.readFileSync(path.resolve(root, 'config', 'crt', 'localhost.key')), cert: fs.readFileSync(path.resolve(root, 'config', 'crt', 'localhost.crt')), }; const callback = this.app.callback(); this.serverApp = (this.https ? http2.createServer(httpOptions, callback) : http.createServer(callback)).listen(port); this.wss = this.buildWebSocket(this.serverApp); util.log(`Server running on ${this.https ? 'https' : 'http'}://127.0.0.1:${port}/`); } buildWebSocket(serverApp) { var wss = new WebSocketServer({ server: serverApp }); wss.on('connection', (ws) => { ws.on('message', (message) => { console.log('received: %s', message); }); }); wss.broadcast = (data) => { wss.clients.forEach(function each(client) { client.send(data, function (error) { if (error) { console.log(error); } }); }); }; return wss; } } export default Server;
JavaScript
0
@@ -3746,12 +3746,10 @@ n', -( ws -) =%3E @@ -3783,17 +3783,15 @@ e', -( message -) =%3E @@ -3903,14 +3903,12 @@ t = -( data -) =%3E @@ -3945,29 +3945,18 @@ ach( -function each( + client -) + =%3E %7B%0A @@ -3992,24 +3992,16 @@ ta, -function ( error -) + =%3E %7B%0A @@ -4056,25 +4056,27 @@ -console.l +util.debugL og(error
481e969fa773e7dfa24b7f965c9e085850f0b2ae
Remove clutter
src/file.js
src/file.js
var util = require('./util') , isFunc = util.isFunc , path = require("path") , fs = require("fs") , all = {} , AbstractResource = require("./abstract_resource") function File(p) { AbstractResource.call(this) this._path = p } File.new = function(p, fs) { p = File.normalizePath(p) return p in all ? all[p] : all[p] = new File(p) } File.normalizePath = function(p) { p = File.absolutePath.test(p) ? p : path.join(process.cwd(), p) p = path.normalize(p) return p } File.absolutePath = /^\// util.inherits(File, AbstractResource) util.def(File.prototype, { watchStart: function() { if (this._watching) return this._watching = true this._watchModule.watchFile(this._path, function(current, prev) { this.emit("change", this) }.bind(this)) } , watchStop: function() { this._watchModule.unwatchFile(this._path) this._watching = false } , toString: function() { return this._path } , get path() { return this._path } , _watchModule: fs }) module.exports = File
JavaScript
0.000105
@@ -26,33 +26,8 @@ l')%0A - , isFunc = util.isFunc%0A ,
6319c1b78c976c392a619aa9167dec99e80d31a3
Attach image details to report
public/scripts/app/views/Report/Description.js
public/scripts/app/views/Report/Description.js
define(function(require) { 'use strict'; var _ = require('underscore') , Base = require('app/views/Base') , autosize = require('autosize') , Thankyou = require('app/views/Report/Thankyou') , File = require('app/models/File') , user = require('app/store/User') , log = require('bows.min')('Views:Report:Description') return Base.extend({ template: _.template(require('text!tpl/Report/Description.html')), requiresLogin: true, title: 'Add Description', className: 'report screen', events: { 'submit form': 'send', 'click .js-back': 'back' }, initialize: function(options) { this.options = options this.router = options.router if (localStorage.uploads && window.File && window.FileReader && window.FileList && window.Blob) { this.model.set('canUploadFiles', true) this.file = new File({ jid: user.get('channelJid') }) } else { log('The File APIs are not fully supported in this browser.') this.model.set('canUploadFiles', false) } }, afterRender: function() { this.input = this.$('.js-description') autosize(this.input) }, send: function(event) { event.preventDefault() this.showSpinner('Sending Report') if (!this.file) { return this.sendReport() } this.file.on('error:file', function(message) { this.error(message) }, this) this.file.on('change:id', function(url) { log('success', arguments) this.sendReport() }, this) this.file.upload(event) }, sendReport: function(error) { this.model.set('description', this.$('.js-description').val()) if ('home' === this.model.get('category')) { this.model.set( 'idNumber', this.$('.js-municipal-account-number').val() ) } // also upload photo(s) from this.$('.js-photos').val() log('Attempting to create a ticket', this.model) this.model.once('ticket:success', _.bind(this.success, this)) this.model.once('ticket:error', _.bind(this.error, this)) this.model.save() }, error: function(error) { this.closeSpinner() this.showError( 'Unfortunately we couldn\'t post your report. ' + 'Please try again later.' ) }, success: function() { console.log(arguments) this.closeSpinner() log('Ticket created successfully') var thankyouView = new Thankyou(this.options) this.router.showView(thankyouView) }, back: function(event) { /* overwrite the back buttons default behaviour * in order to hand over the report state */ event.stopPropagation() this.router.showReportLocation(this.model) }, onDestroy: function() { this.triggerAutosizeEvent('autosize.destroy') }, triggerAutosizeEvent: function(event) { var evt = document.createEvent('Event'); evt.initEvent(event, true, false); this.input.get(0).dispatchEvent(evt); }, }) })
JavaScript
0
@@ -1648,77 +1648,75 @@ ion( -url) %7B%0A log('success', arguments)%0A this.sendReport( +details) %7B%0A this.sendReport(details.url + '/' + details.id )%0A @@ -1792,37 +1792,40 @@ eport: function( -error +imageUrl ) %7B%0A this @@ -2065,16 +2065,241 @@ %7D +%0A if (imageUrl) %7B%0A this.model.set(%0A 'description',%0A this.model.get('description')%0A + '%5Cn%5CnThe following image was attached: '%0A + imageUrl%0A )%0A %7D %0A%0A @@ -2790,24 +2790,24 @@ )%0A %7D,%0A%0A + succes @@ -2826,39 +2826,8 @@ ) %7B%0A - console.log(arguments)%0A
5adfb09d9a1d3304d322cce464dd687090d115e3
Add link to logo
src/modules/Layout/Header/Header.js
src/modules/Layout/Header/Header.js
import React from 'react'; import PropTypes from 'prop-types'; import block from '../../../helpers/bem-cn'; import Nav from '../Nav/Nav'; import './Header.css'; const b = block('j-header'); const propTypes = { logout: PropTypes.func.isRequired, user: PropTypes.string.isRequired, }; const Header = ({ logout, user }) => { if (user) { return ( <header className={b}> <div className={b('col', { left: true })}> <span className={b('logo')} /> </div> <div className={b('col', { middle: true })}> <Nav /> </div> <div className={b('col', { right: true })}> { user && <div className={b('user')}> <div className={b('user-name')}> {user} <div className={b('user-menu')} onClick={logout}>Logout</div> </div> </div> } </div> </header> ); } return ( <header className={b}></header> ); }; Header.propTypes = propTypes; export default Header;
JavaScript
0
@@ -55,16 +55,57 @@ -types'; +%0Aimport %7B Link %7D from 'react-router-dom'; %0A%0Aimport @@ -143,16 +143,76 @@ em-cn';%0A +import ROUTES from '../../../configurations/routes.config';%0A import N @@ -581,36 +581,117 @@ %3C -span className=%7Bb('logo')%7D / +Link to=%7BROUTES.MAIN.path%7D%3E%0A %3Cspan className=%7Bb('logo')%7D /%3E%0A %3C/Link %3E%0A
2e660a69855d6d73d93ebcc4e65143b49194ad3c
Allow custom cell height
components/CustomCell.js
components/CustomCell.js
import React, { Component, PropTypes, StyleSheet, View, Text, TouchableHighlight } from 'react-native'; export default class CustomCell extends Component { render() { const {children} = this.props; const cellTintColor = this.props.cellTintColor; const isDisabled = this.props.isDisabled; const isPressable = this.props.onPress ? true : false; const highlightUnderlayColor = this.props.highlightUnderlayColor; const highlightActiveOpacity = this.props.highlightActiveOpacity; /* Set styles */ const styleCell = [...{}, styles.cell, { backgroundColor: cellTintColor}]; if(isPressable && !isDisabled) { return( <TouchableHighlight onPress={this.props.onPress} underlayColor={highlightUnderlayColor} activeOpacity={highlightActiveOpacity}> <View style={styleCell}>{children}</View> </TouchableHighlight> ) } return (<View style={styleCell}>{children}</View>) } } var styles = StyleSheet.create({ 'cell': { justifyContent: 'center', paddingLeft: 15, paddingRight: 20, paddingTop: 10, paddingBottom: 10, flexDirection: 'row', alignItems: 'center', height: 44, } }); CustomCell.propTypes = { cellTintColor: PropTypes.string, isDisabled: PropTypes.bool, onPress: PropTypes.oneOfType([ React.PropTypes.bool, React.PropTypes.func ]), highlightActiveOpacity: PropTypes.number, highlightUnderlayColor: PropTypes.string, } CustomCell.defaultProps = { cellTintColor: '#fff', isDisabled: false, highlightActiveOpacity: 0.8, highlightUnderlayColor: 'black' }
JavaScript
0.000002
@@ -414,20 +414,17 @@ yColor;%0A - +%09 %09const h @@ -486,13 +486,52 @@ ty;%0A - %09 +%09%09const cellHeight = this.props.cellHeight;%0A %0A%09%09/ @@ -623,14 +623,32 @@ olor +, height: cellHeight %7D%5D;%0A -%09%09 %0A%09%09i @@ -903,18 +903,16 @@ %09%09%09)%0A%09%09%7D - %0A r @@ -1185,24 +1185,8 @@ r',%0A - height: 44,%0A %7D%0A @@ -1278,16 +1278,47 @@ s.bool,%0A +%09cellHeight: PropTypes.number,%0A %09onPress @@ -1554,16 +1554,33 @@ false,%0A +%09cellHeight: 44,%0A %09highlig @@ -1637,8 +1637,9 @@ black'%0A%7D +%0A
6f05de4392c9a43665ed8ef75ef81deff37c40f6
add error checking
lib/requester.js
lib/requester.js
var request = require('request') var request = request.defaults({jar: true}) var _ = require('underscore') var jsesc = require('jsesc') var utils = require('./utilities') var util = require('util') var Requester = function(){ this.auth_token = ''; this.base_uri = 'https://api.gotinder.com/'; } Requester.prototype.auth_request = function(facebook_id, facebook_token, callback){ var data = { facebook_id: facebook_id, facebook_token: facebook_token } var that = this this.post_request( 'auth', data, function(err, res, body){ that.auth_token = body.token if(callback) callback(err, res, body) } ) } Requester.prototype.get_request = function(endpoint, callback){ url = utils.resolve_url(this.base_uri, endpoint) request({method: 'GET', url: url, headers: this.all_headers(), json:true}, function(err, res, body){ if(callback) callback(err, res, body) }) } Requester.prototype.post_request = function(endpoint, data, callback){ url = utils.resolve_url(this.base_uri, endpoint) request({method: 'POST', url: url, body: data, headers: this.all_headers(), json: true}, function(err, res, body){ if(callback) callback(err, res, body) }) } Requester.prototype.all_headers = function(){ return _.extend(this.default_headers(), this.auth_headers()) } Requester.prototype.auth_headers = function(){ if(this.auth_token){ return { "X-Auth-Token": this.auth_token, "Authorization": jsesc( 'Token token="' + this.auth_token + '"', {quotes: 'double'} ) } } else{ return {} } } Requester.prototype.default_headers = function(){ return { 'User-Agent': 'Tinder/4.0.4 (iPhone; iOS 7.1.1; Scale/2.00)' } } module.exports = Requester
JavaScript
0.000001
@@ -548,24 +548,119 @@ res, body)%7B%0A + if (err) return callback(err)%0A if (!body) return callback(%22No body, no token.%22,res)%0A that.a
a64f5f7488e447c17327eef256dc40979eb0d3c4
🐛 Handle names as array in report module
lib/modules/report.mdl.js
lib/modules/report.mdl.js
'use strict'; const fs = require('fs'); const { basename, join, resolve } = require('path'); const project = require('./project'); const html = require('./html'); const consoleModule = require('./console.mdl'); const messages = require('./messages'); const dual = require('./dual'); const ldir = join(process.cwd(), 'licenses'); const reportFileName = (name, type) => { let rfn = `${name}_${type}.txt`; rfn = rfn.replace(/@/gi, ''); rfn = rfn.replace(/\//gi, '-'); return rfn; }; const reportFileData = (projectMetaData) => { projectMetaData.dependencies.dependency.forEach(d => { if (d.file && d.file.includes(d.licenses.license[0].name.split(' ')[0].toUpperCase())) { const link = join('./', d.file); d.localLicense = require('querystring').escape(link).replace(/%2F/gi, '/'); d.linkLabel = link; } else { d.localLicense = '#'; d.linkLabel = 'No local license could be found for the dependency'; } }); return projectMetaData; }; const htmlReport = (reportData) => { html.parse(reportData).then(output => { fs.writeFileSync(join(ldir, 'license.html'), output); }); }; const copyCSS = (css) => { if (fs.existsSync(css)) { fs.createReadStream(resolve(css)) .pipe(fs.createWriteStream(join(ldir, 'licenses.css'))); } else { console.error(`CSS file not found: ${css}`); } }; const copyLicenseFile = (name, type, file) => { let fileName; if (basename(file).toUpperCase() !== 'README.MD') { fileName = reportFileName(name, type).toUpperCase(); fs.createReadStream(file) .pipe(fs.createWriteStream(join(ldir, fileName))); } return fileName; }; const licenseMetaData = (licenses, canonicalNameMapper, ilc, file) => { const licenseData = { license: [] }; if (dual.isDual(licenses)) { let nameUrl = consoleModule.licenseNameUrl(canonicalNameMapper, dual.first(licenses)); licenseData.license.push({name: dual.first(licenses), url: nameUrl.url}); nameUrl = consoleModule.licenseNameUrl(canonicalNameMapper, dual.last(licenses)); licenseData.license.push({name: dual.last(licenses), url: nameUrl.url}); } else { const nameUrl = consoleModule.licenseNameUrl(canonicalNameMapper, licenses); licenseData.license.push({name: licenses, url: nameUrl.url}); } return licenseData; }; const transform = (data, canonicalNameMapper, cwd, ilc) => { const projectMetaData = project.projectMetaData(cwd); data = consoleModule.declaredDependencies(data, project.dependencies(cwd)); data = consoleModule.packageMetaData(data); data.forEach((d) => { if (d.file) { d.file = copyLicenseFile(d.packageName, d.licenses, d.file); } else { console.log(`No license file found for ${d.packageName}`); } d.licenses = licenseMetaData(d.licenses, canonicalNameMapper, ilc, d.file); }); data.forEach((d) => { if (d.licenses.license.length === 2) { const clone = JSON.parse(JSON.stringify(d)); d.licenses.license.pop(); clone.licenses.license.shift(); data.push(clone); } }); data.sort((a, b) => a.packageName.localeCompare(b.packageName)); projectMetaData.dependencies.dependency = data; messages.show(project.dependencies(cwd), projectMetaData); return projectMetaData; }; const report = (projectMetaData, css) => { copyCSS(css); htmlReport(reportFileData(projectMetaData)); }; module.exports = { report, transform };
JavaScript
0.999901
@@ -596,38 +596,89 @@ -i +const nameUpperCase = typeo f -( d. -file && d.file.includes( +licenses.license%5B0%5D.name === 'string'%0A ? d.li @@ -727,16 +727,108 @@ erCase() +%0A : d.licenses.license%5B0%5D.name%5B0%5D;%0A%0A if (d.file && d.file.includes(nameUpperCase )) %7B%0A
72f4e3ee9a4bbaa9d334290e9f7750ea09b061a6
Update MediumPost.js
components/MediumPost.js
components/MediumPost.js
import PropTypes from 'prop-types' import styled from 'styled-components' const Wrapper = styled.div` border-radius: 8px; background: white; &:before { content: '.'; display: block; color: transparent; position: absolute; position: absolute; top: 5%; left: 5%; width: 90%; height: 90%; transition: all 0.25s ease-out; box-shadow: 0 16px 32px rgba(14,21,47,0.25), 0 8px 8px rgba(14,21,47,0.25); } ` const Link = styled.a` display: block; border-radius: 8px; height: 21vh; background-image: url(${props => props.image}); background-repeat: no-repeat; background-size: cover; background-position: center; position: relative; overflow: hidden; text-decoration: none; ` const Header = styled.h3` margin: 0; color: white; font-size: 18px; position: absolute; padding: 10px 10px 0 10px; top: 0; right: 0; bottom: 0; left: 0; background: linear-gradient(to bottom, black, transparent); text-shadow: black 0 2px 4px; ` const MediumPost = ({ url, title, image }) => <Wrapper> <Link image={image} href={url} target="_blank"> <Header>{title}</Header> </Link> </Wrapper> MediumPost.propTypes = { url: PropTypes.object.isRequired, title: PropTypes.string.isRequired, image: PropTypes.string.isRequired, } export default MediumPost
JavaScript
0
@@ -138,16 +138,38 @@ : white; +%0A position: relative; %0A%0A &:be
7bb9a3cf3b79fcf03098bf07c709aac53c9e7187
Add missing values test for quotes.
test/yahoo-quotes-test.js
test/yahoo-quotes-test.js
"use strict"; const test = require("tape"); const csv = require("../lib/parse-csv"); const quotes = require("../lib/yahoo-quotes"); test("Yahoo Quotes tests", t => { t.plan(5); quotes.getHistoricalQuotesFromYahoo({ symbol: "GOOGL", beginDate: new Date(2013, 0, 2), // Jan 2nd, 2013 endDate: new Date(2013, 3, 6) // Apr 6th, 2013 }, (err, symbol, res) => { t.notOk(err, "check error for getting prices"); if (!err) { const prices = csv.parse(res, { skipHeader: true, column: 4, // close prices reverse: true // from oldest to newest }); t.equal("391.916931", prices[0], "get oldest price"); t.equal("367.742737", prices[prices.length - 1], "get newest price"); } }); quotes.getHistoricalQuotesFromYahoo({ symbol: "IBM190118C00100000", beginDate: new Date(2013, 0, 2), // Jan 2nd, 2013 endDate: new Date(2013, 3, 6) // Apr 6th, 2013 }, (err, symbol, res) => { t.equal(err, "Not Found", "not found for unknown symbol"); t.notOk(res, "no data for unknown symbol"); }); });
JavaScript
0
@@ -177,9 +177,9 @@ lan( -5 +7 );%0A%0A @@ -1176,12 +1176,357 @@ %7D);%0A +%0A quotes.getHistoricalQuotesFromYahoo(%7B%0A symbol: %22CEC.VI%22,%0A beginDate: new Date(2017, 7, 13), // Aug 13th, 2017%0A endDate: new Date(2018, 5, 23) // Jun 23th, 2018%0A %7D, (err, symbol, res) =%3E %7B%0A t.equal(err, %22contains missing values%22, %22missing values%22);%0A t.notOk(res, %22no data for missing values%22);%0A %7D);%0A%0A %7D);%0A
84fb444101f498f05a7e7e6bf86f3d0cebda6c6a
add if statement for RS.remove();
lib/rockstage.js
lib/rockstage.js
// Copyright (c) 2012 HIRAKI Satoru, https://github.com/Layzie // // 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. (function(window, undefined) { 'use strict'; var _selectStorage = function _selectStorage(flag) { var storage; if (typeof flag !== 'boolean' && flag !== undefined) { throw new Error('2nd argument should be boolean'); } else { if (flag === true || flag === undefined) { storage = localStorage; } else { storage = sessionStorage; } } return storage; }; if (typeof window.RS === 'undefined') { window.RS = {}; } window.RS = { put: function put(obj, flag) { var storage = _selectStorage(flag); if (typeof obj === 'object' && !(obj instanceof Array)) { for (var i in obj) { if (obj.hasOwnProperty(i)) { storage.setItem(i, JSON.stringify(obj[i])); } } } else { throw new Error('1st argument should be object'); } }, get: function get(key, flag) { var storage = _selectStorage(flag), selectKey = storage.getItem(key); if (typeof key === 'string') { if (selectKey) { return JSON.parse(selectKey); } else { return console.log('This key is not in storage'); } } else { throw new Error('1st argument should be string'); } }, remove: function remove(key, flag) { var storage = _selectStorage(flag); storage.removeItem(key); }, clear: function clear(flag) { var storage = _selectStorage(flag); storage.clear(); }, is: function(key, flag) { var storage = _selectStorage(flag), selectKey = storage.getItem(key); if (typeof key === 'string') { if (selectKey) { return true; } else { return false; } } else { throw new Error('1st argument should be strings'); } } }; })(this);
JavaScript
0.000007
@@ -2502,41 +2502,239 @@ lag) -;%0A%0A storage.removeItem(key); +,%0A selectKey = storage.getItem(key);%0A%0A if (typeof key === 'string') %7B%0A if (selectKey) %7B%0A storage.removeItem(key);%0A %7D else %7B%0A console.log('This key is not in storage');%0A %7D%0A %7D %0A
e75bf64e573334f33d2faad55a239e4798d8fee5
make writers capable of dependency injection
packages/ephemeral/writer.js
packages/ephemeral/writer.js
const EphermalStorage = require('./storage'); const crypto = require('crypto'); const Error = require('@cardstack/plugin-utils/error'); const PendingChange = require('@cardstack/plugin-utils/pending-change'); const pendingChanges = new WeakMap(); module.exports = class Writer { constructor({ storageKey }) { this.storage = EphermalStorage.create(storageKey); } async prepareCreate(branch, user, type, document, isSchema) { if (branch !== 'master') { throw new Error("ephemeral storage only supports branch master"); } let id = document.id; if (id == null) { id = this._generateId(); } if (this.storage.lookup(type, id)) { throw new Error(`id ${id} is already in use`, { status: 409, source: { pointer: '/data/id'}}); } let pending = new PendingChange(null, document, finalizer); pendingChanges.set(pending, { type, id, storage: this.storage, isSchema: isSchema }); return pending; } async prepareUpdate(branch, user, type, id, document, isSchema) { if (!document.meta || !document.meta.version) { throw new Error('missing required field "meta.version"', { status: 400, source: { pointer: '/data/meta/version' } }); } let before = this.storage.lookup(type, id); if (!before) { throw new Error(`${type} with id ${id} does not exist`, { status: 404, source: { pointer: '/data/id' } }); } let after = patch(before, document); let pending = new PendingChange(before, after, finalizer); pendingChanges.set(pending, { type, id, storage: this.storage, isSchema, ifMatch: document.meta.version }); return pending; } async prepareDelete(branch, user, version, type, id, isSchema) { if (!version) { throw new Error('version is required', { status: 400, source: { pointer: '/data/meta/version' } }); } let before = this.storage.lookup(type, id); if (!before) { throw new Error(`${type} with id ${id} does not exist`, { status: 404, source: { pointer: '/data/id' } }); } let pending = new PendingChange(before, null, finalizer); pendingChanges.set(pending, { type, id, storage: this.storage, isSchema, ifMatch: version }); return pending; } _generateId() { return crypto.randomBytes(20).toString('hex'); } }; function patch(before, diffDocument) { let after = Object.assign({}, before); for (let section of ['attributes', 'relationships']) { if (diffDocument[section]) { after[section] = Object.assign( {}, before[section], diffDocument[section] ); } } return after; } async function finalizer(pendingChange) { let { storage, isSchema, ifMatch, type, id } = pendingChanges.get(pendingChange); return { version: storage.store(type, id, pendingChange.finalDocument, isSchema, ifMatch) }; }
JavaScript
0.000006
@@ -274,16 +274,76 @@ riter %7B%0A + static create(params) %7B%0A return new this(params);%0A %7D%0A%0A constr
192ac053db8d3c714fdf8e2036304a4766b0cd11
Fix tests
generators/app/templates/test/service.tests.js
generators/app/templates/test/service.tests.js
const expect = require('expect.js'); const system = require('../system'); const supertest = require('supertest'); describe('Service Tests', () => { let request; let sys; before(done => { sys = system().start((err, { app }) => { if (err) return done(err); request = supertest(app); done(); }); }); after(done => sys.stop(done)); it('should return manifest', () => request .get('/__/manifest') .expect(200) .then((response) => { expect(response.headers['content-type']).to.equal('application/json; charset=utf-8'); })); });
JavaScript
0.000003
@@ -166,16 +166,27 @@ let sys + = system() ;%0A%0A bef @@ -206,27 +206,16 @@ %0A sys - = system() .start(( @@ -342,16 +342,18 @@ (done =%3E + %7B sys.sto @@ -359,18 +359,21 @@ op(done) + %7D ); +s %0A%0A it('
1e9a235a4fffff0741a0d6dfdcc5d1283e04059e
Secure by proper design! Ha! And IPs!
server/api/petitioners.js
server/api/petitioners.js
var mongo = require('mongodb'), nconf = require('nconf'), assert = require('assert'); var Server = mongo.Server, Db = mongo.Db, Client = mongo.MongoClient, ObjectId = mongo.ObjectID; nconf.env(['mongodb:connection']) .file('api/config.json'); var uri = nconf.get('mongodb:connection'); var os = require('os'); var networkInterfaces = os.networkInterfaces(); console.log(os.hostname()); console.log(networkInterfaces); var Allowed = function (req, res) { //var ip = req.ip || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress; //console.log(ip); //return (ip === ''); res.send(req); } module.exports.GetAll = function (req, res) { if (!Allowed(req, res)) { res.end(403, 'Forbidden'); }; Client.connect(uri, function (err, db) { assert.equal(err, null); db.collection('WeWantTrubel-Petitioners') .find() .toArray(function (err, docs) { assert.equal(err, null); res.send(docs); }); }); }; module.exports.Post = function (req, res) { };
JavaScript
0
@@ -626,21 +626,71 @@ %0A%09%0A%09 -res.send(req) +console.log(req.hostname);%0A%09console.dir(req.ips);%0A%0A%09return true ;%0A%7D%0A @@ -920,16 +920,94 @@ %09%09.find( +%7B%7D, %7B %22Name%22: 1, %22Location%22: 1, %22TimeStamp%22: 1 %7D)%0A%09%09%09.sort(%7B %22TimeStamp%22: -1 %7D )%0A%09%09%09.to
6d2a077de80ad117158a6c92e73728b4e5e8644c
add `--force` flag to dataset alias delete command
packages/@sanity/core/src/commands/dataset/alias/deleteAliasHandler.js
packages/@sanity/core/src/commands/dataset/alias/deleteAliasHandler.js
import validateDatasetAliasName from '../../../actions/dataset/alias/validateDatasetAliasName' import * as aliasClient from './datasetAliasesClient' import {ALIAS_PREFIX} from './datasetAliasesClient' export default async (args, context) => { const {apiClient, prompt, output} = context const [, ds] = args.argsWithoutOptions const client = apiClient() if (!ds) { throw new Error('Dataset alias name must be provided') } let aliasName = `${ds}` const dsError = validateDatasetAliasName(aliasName) if (dsError) { throw dsError } aliasName = aliasName.startsWith(ALIAS_PREFIX) ? aliasName.substring(1) : aliasName const [fetchedAliases] = await Promise.all([aliasClient.listAliases(client)]) const linkedAlias = fetchedAliases.find((elem) => elem.name === aliasName) const message = linkedAlias && linkedAlias.datasetName ? `This dataset alias is linked to ${linkedAlias.datasetName}. ` : '' await prompt.single({ type: 'input', message: `${message}Are you ABSOLUTELY sure you want to delete this dataset alias?\n Type the name of the dataset alias to confirm delete: `, filter: (input) => `${input}`.trim(), validate: (input) => { return input === aliasName || 'Incorrect dataset alias name. Ctrl + C to cancel delete.' }, }) // Strip out alias prefix if it exist in the string aliasName = aliasName.startsWith(ALIAS_PREFIX) ? aliasName.substring(1) : aliasName return aliasClient.removeAlias(client, aliasName).then(() => { output.print('Dataset alias deleted successfully') }) }
JavaScript
0.000003
@@ -1,12 +1,82 @@ +import %7BhideBin%7D from 'yargs/helpers'%0Aimport yargs from 'yargs/yargs'%0A import valid @@ -265,16 +265,150 @@ lient'%0A%0A +function parseCliFlags(args) %7B%0A return yargs(hideBin(args.argv %7C%7C process.argv).slice(2)).option('force', %7Btype: 'boolean'%7D).argv%0A%7D%0A%0A export d @@ -528,16 +528,60 @@ Options%0A + const %7Bforce%7D = await parseCliFlags(args)%0A const @@ -1185,16 +1185,132 @@ : ''%0A%0A + if (force) %7B%0A output.warn(%60'--force' used: skipping confirmation, deleting alias %22$%7BaliasName%7D%22%60)%0A %7D else %7B%0A await @@ -1325,16 +1325,18 @@ ingle(%7B%0A + type @@ -1350,16 +1350,18 @@ t',%0A + message: @@ -1499,16 +1499,18 @@ %60,%0A + filter: @@ -1543,16 +1543,18 @@ (),%0A + validate @@ -1564,24 +1564,26 @@ input) =%3E %7B%0A + return @@ -1673,15 +1673,23 @@ + %7D,%0A + %7D) +%0A %7D %0A%0A
e0dc07d93b9a88be5079bedc3b417965fe329515
Add setInstanceOptions
packages/core/src/Dicy.js
packages/core/src/Dicy.js
/* @flow */ import path from 'path' import readdir from 'readdir-enhanced' import State from './State' import StateConsumer from './StateConsumer' import File from './File' import Rule from './Rule' import type { Action, Command, Option, Phase, RuleInfo } from './types' export default class Dicy extends StateConsumer { static async create (filePath: string, options: Object = {}) { const schema = await Dicy.getOptionDefinitions() const state = await State.create(filePath, schema) const builder = new Dicy(state) const instance = await state.getFile('dicy-instance.yaml-ParsedYAML') if (instance) instance.value = options await builder.initialize() return builder } async initialize () { const ruleClassPath: string = path.join(__dirname, 'Rules') const entries: Array<string> = await readdir.async(ruleClassPath) this.state.ruleClasses = entries .map(entry => require(path.join(ruleClassPath, entry)).default) } async analyzePhase (command: Command, phase: Phase) { for (const ruleClass: Class<Rule> of this.ruleClasses) { const jobNames = ruleClass.ignoreJobName ? [undefined] : this.options.jobNames for (const jobName of jobNames) { const rule = await ruleClass.analyzePhase(this.state, command, phase, jobName) if (rule) { await this.addRule(rule) } } } } async analyzeFiles (command: Command, phase: Phase) { let rulesAdded = false while (true) { const file: ?File = Array.from(this.files).find(file => !file.analyzed) if (!file) break for (const ruleClass: Class<Rule> of this.ruleClasses) { const jobNames = file.jobNames.size === 0 ? [undefined] : Array.from(file.jobNames.values()) for (const jobName of jobNames) { const rule = await ruleClass.analyzeFile(this.state, command, phase, jobName, file) if (rule) { rulesAdded = true await this.addRule(rule) } } } file.analyzed = true } if (rulesAdded) this.calculateDistances() } getAvailableRules (command: ?Command): Array<RuleInfo> { return this.ruleClasses .filter(rule => !command || rule.commands.has(command)) .map(rule => ({ name: rule.name, description: rule.description })) } async evaluateRule (rule: Rule, action: Action) { if (rule.success) { await rule.evaluate(action) } else { this.info(`Skipping rule ${rule.id} because of previous failure.`) } } async evaluate (command: Command, phase: Phase, action: Action) { const rules: Array<Rule> = Array.from(this.rules).filter(rule => rule.needsEvaluation && rule.command === command && rule.phase === phase) const ruleGroups: Array<Array<Rule>> = [] for (const rule of rules) { let notUsed = true for (const ruleGroup of ruleGroups) { if (this.isConnected(ruleGroup[0], rule)) { ruleGroup.push(rule) notUsed = false break } } if (notUsed) ruleGroups.push([rule]) } const primaryCount = ruleGroup => ruleGroup.reduce( (total, rule) => total + rule.parameters.reduce((count, parameter) => parameter.filePath === this.filePath ? count + 1 : count, 0), 0) ruleGroups.sort((x, y) => primaryCount(x) - primaryCount(y)) for (const ruleGroup of ruleGroups) { let candidateRules = [] let dependents = [] let minimumCount = Number.MAX_SAFE_INTEGER for (const x of ruleGroup) { const inputCount = ruleGroup.reduce((count, y) => this.isChild(y, x) ? count + 1 : count, 0) if (inputCount === 0) { candidateRules.push(x) } else if (inputCount === minimumCount) { dependents.push(x) } else if (inputCount < minimumCount) { dependents = [x] minimumCount = inputCount } } if (candidateRules.length === 0) { candidateRules = dependents } candidateRules.sort((x, y) => x.inputs.size - y.inputs.size) for (const rule of candidateRules) { await this.checkUpdates(command, phase) await this.evaluateRule(rule, action) } } await this.checkUpdates(command, phase) } async checkUpdates (command: Command, phase: Phase) { for (const file of this.files) { for (const rule of file.rules.values()) { await rule.addFileActions(file, command, phase) } file.hasBeenUpdated = false } } async run (...commands: Array<Command>): Promise<boolean> { await Promise.all(Array.from(this.files).map(file => file.update())) for (const command of commands) { for (const phase: Phase of ['initialize', 'execute', 'finalize']) { await this.runPhase(command, phase) } } return Array.from(this.rules).every(rule => rule.success) } async runPhase (command: Command, phase: Phase): Promise<void> { for (const file of this.files) { file.hasBeenUpdated = file.hasBeenUpdatedCache file.analyzed = false } for (const rule of this.rules) { await rule.phaseInitialize(command, phase) } await this.analyzePhase(command, phase) for (let cycle = 0; cycle < this.options.phaseCycles; cycle++) { for (const action of ['updateDependencies', 'run']) { await this.analyzeFiles(command, phase) await this.evaluate(command, phase, action) } if (Array.from(this.files).every(file => file.analyzed) && Array.from(this.rules).every(rule => rule.command !== command || rule.phase !== phase || !rule.needsEvaluation)) break } } static async getOptionDefinitions (): Promise<Array<Option>> { const filePath = path.resolve(__dirname, '..', 'resources', 'option-schema.yaml') const schema = await File.load(filePath) const options = [] for (const name in schema) { const option = schema[name] option.name = name options.push(option) } return options } async updateOptions (options: Object = {}, user: boolean = false): Promise<Object> { const normalizedOptions = {} const filePath = this.resolvePath(user ? '$HOME/.dicy.yaml' : '$DIR/$NAME.yaml') if (await File.canRead(filePath)) { const currentOptions = await File.safeLoad(filePath) this.state.assignSubOptions(normalizedOptions, currentOptions) } this.state.assignSubOptions(normalizedOptions, options) await File.safeDump(filePath, normalizedOptions) return normalizedOptions } }
JavaScript
0.000001
@@ -536,151 +536,79 @@ -const instance = await state.getFile('dicy-instance.yaml-ParsedYAML')%0A if (instance) instance.value = options%0A%0A await builder.initialize( +await builder.initialize()%0A await builder.setInstanceOptions(options )%0A%0A @@ -896,24 +896,197 @@ fault)%0A %7D%0A%0A + async setInstanceOptions (options: Object = %7B%7D) %7B%0A const instance = await this.getFile('dicy-instance.yaml-ParsedYAML')%0A if (instance) instance.value = options%0A %7D%0A%0A async anal
e236f7ca0a7322574f0c9855c1208e8b6fec584a
change event name
packages/node_modules/@webex/internal-plugin-presence/src/constants.js
packages/node_modules/@webex/internal-plugin-presence/src/constants.js
export const GROUNDSKEEPER_INTERVAL = 20 * 1000; // 20 seconds in ms export const FETCH_DELAY = 300; // ms export const UPDATE_PRESENCE_DELAY = 60 * 1000; // 1 minute in ms export const EXPIRED_PRESENCE_TIME = 10 * 60 * 1000; // 10 minutes in ms export const SUBSCRIPTION_DELAY = 60 * 1000; // 1 minute in ms export const PREMATURE_EXPIRATION_SUBSCRIPTION_TIME = 60 * 1000; // 1 minute in ms export const DEFAULT_SUBSCRIPTION_TTL = 10 * 60 * 1000; // 10 minutes in ms export const APHELEIA_SUBSCRIPTION_UPDATE = 'event:apheleia.subscription_update'; export const PRESENCE_UPDATE = 'update'; export const ENVELOPE_TYPE = { SUBSCRIPTION: 'subscription', PRESENCE: 'presence', DELETE: 'delete' };
JavaScript
0.000133
@@ -588,16 +588,17 @@ 'update +d ';%0A%0Aexpo
49a07c627e053447eda0848fb1713c6c04339f7e
Tweak test page
TestPage.js
TestPage.js
/** * Copyright (c) 2015, Peter W Moresi */ import React from 'react'; import {Table, Column} from './Table'; import Colors from './CrayolaColors'; /* Write some great components about what data * this application presents and how it needs to be * organized. */ export default class TestPage extends React.Component { constructor() { super(); this.state = { rows: Colors, startRow: 1, numberOfRows: 5 }; } handleStartRowChanged(event) { this.setState({ startRow: +event.currentTarget.value }); } render() { return ( <div> Start Row: <br/> <input type="number" className="form-control" min="1" onChange={ this.handleStartRowChanged.bind(this) } value={ this.state.startRow } /> <h1>Default</h1> <Table startRow={this.state.startRow} numberOfRows={this.state.numberOfRows} getRowAt={ (rowIndex) => this.state.rows[rowIndex] } headerRenderers={['#', 'Color', 'Hex Value']} columnRenderers={[ (row) => row.id, (row) => `${row.name} (${row.hex})`, (row) => <span style={{ paddingTop: 10, display: 'block', backgroundColor: row.hex, width: row.width + '%', height: '3em' }}></span>] } /> <h1>Fixed Header Off</h1> <Table fixedHeader={false} startRow={this.state.startRow} numberOfRows={this.state.numberOfRows*2} interval={2} getRowAt={ (rowIndex) => this.state.rows[rowIndex] } headerRenderers={['#', 'Color', <span style={{color: 'red'}}>Hex Value</span>]}> <Column column="id" /> <Column cellRenderer={(row) => `${row.name} (${row.hex})`}/> <Column cellRenderer={(row) => <span style={{ paddingTop: 10, display: 'block', backgroundColor: row.hex, width: row.width + '%', height: '3em' }}></span>}/> </Table> <h1>Header Off</h1> <Table showHeader={false} startRow={this.state.startRow-1} numberOfRows={this.state.numberOfRows*2} interval={2} getRowAt={ (rowIndex) => this.state.rows[rowIndex] } headerRenderers={['#', 'Color', <span style={{color: 'green'}}>Hex Value</span>]}> <Column column="id" /> <Column cellRenderer={(row) => `${row.name} (${row.hex})`}/> <Column cellRenderer={(row) => <span style={{ paddingTop: 10, display: 'block', backgroundColor: row.hex, width: row.width + '%', height: '3em' }}></span>}/> </Table> </div> ); } }
JavaScript
0
@@ -894,16 +894,73 @@ OfRows%7D%0A + fixedHeader=%7Btrue%7D%0A showHeader=%7Btrue%7D%0A @@ -1611,32 +1611,62 @@ interval=%7B2%7D%0A + showHeader=%7Btrue%7D%0A getR
248297af63b30be4561a9096ad6043229fe802d5
fix "BiwaScheme.Port.current_error.puts is not a function"
src/platforms/browser/release_initializer.js
src/platforms/browser/release_initializer.js
// // release_initializer.js - read user's program and eval it (if it exists) // // This file is put on the end the lib/biwascheme.js. // (function(){ //local namespace var dumper = null; if ($("#biwascheme-debugger")[0]) { dumper = new BiwaScheme.Dumper($("#biwascheme-debugger")[0]); } // Error handler (show message to console div) var onError = function(e, state){ BiwaScheme.Port.current_error.puts(e.message); if (dumper) { dumper.dump(state); dumper.dump_move(1); } else if (typeof(console) !== "undefined" && console.error) { console.error(e.message); } else { throw(e); } }; // Start user's program var script = $("script[src$='biwascheme.js']").html() || $("script[src$='biwascheme-min.js']").html(); if (script) { var intp = new BiwaScheme.Interpreter(onError); try{ intp.evaluate(script, function(){}); } catch(e){ onError(e); } } })();
JavaScript
0.000005
@@ -414,17 +414,23 @@ rror.put -s +_string (e.messa @@ -427,24 +427,31 @@ ng(e.message + + %22%5Cn%22 );%0A if (d