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
5d49b0f41a9033089cbd8542018bd658a4c47cd3
isNumber move isNaN
is-number.js
is-number.js
/** * @module 101/is-number */ /** * Functional version of val typeof 'number' * @function module:101/is-number * @param {*} val - value checked to be a string * @return {boolean} Whether the value is an string or not */ module.exports = isNumber; function isNumber (val) { return !isNaN(val) && (typeof val === 'number' || val instanceof Number); }
JavaScript
0.999927
@@ -288,23 +288,8 @@ turn - !isNaN(val) && (ty @@ -335,12 +335,26 @@ Number) -; + && !isNaN(val) %0A%7D%0A
4028b6beb4cd6b6f1a5bb66042f2777e54089519
Replace Meteor.clearInterval with just clearInterval
imports/api/reports/reports.test.js
imports/api/reports/reports.test.js
/* eslint-env mocha */ import Reports from './reports.js'; import Elements from '../elements/elements.js'; import Measures from '../measures/measures.js'; import { Meteor } from 'meteor/meteor'; import { resetDatabase } from 'meteor/xolvio:cleaner'; describe('Reports', () => { if (Meteor.isClient) return; describe('collection', () => { it('should have the collection typical functions', () => { Reports.collection.find.should.be.a('function'); }); }); describe('add', () => { let reportId; before(() => { resetDatabase(); reportId = Reports.add(); }); it('creates a new report', () => { Reports.collection.find(reportId).count().should.equal(1); }); }); describe('remove', () => { let reportId; before(() => { resetDatabase(); reportId = Reports.add(); Reports.remove(reportId); }); it('removes the report', () => { Reports.collection.find(reportId).count().should.equal(0); }); }); describe('addToTable', () => { let reportId; before(() => { reportId = Reports.add(); }); describe('with a measure', () => { before(() => { const measureId = Measures.add(); Reports.addToTable(reportId, 'measure', measureId); }); it('adds the measure to the report', () => { Reports.collection.findOne(reportId).measures.length.should.equal(1); }); }); describe('with an element', () => { before(() => { const elementId = Elements.add(undefined, 'dimension'); Elements.characteristics.add(elementId, '2016'); Reports.addToTable(reportId, 'element', elementId); }); it('adds the element to the report', () => { Reports.collection.findOne(reportId).elements.length.should.equal(1); }); it('with its characteristics', () => { const report = Reports.collection.findOne(reportId); report.elements[0].favCharacteristicIds.length.should.equal(1); }); }); }); describe('toggleCharacteristic', () => { let reportId; let elementId; let characteristicId; before(() => { reportId = Reports.add(); elementId = Elements.add(undefined, 'dimension'); characteristicId = Elements.characteristics.add(elementId, '2016'); Reports.addToTable(reportId, 'element', elementId); Meteor.call('Reports.toggleCharacteristic', reportId, elementId, characteristicId, true); }); before((done) => { const interval = Meteor.setInterval(() => { if (Reports.collection.findOne(reportId)) { Meteor.clearInterval(interval); done(); } }); }); it('removes the characteristic from the report element', () => { const report = Reports.collection.findOne(reportId); const element = report.elements.find((elem) => elem._id === elementId); element.favCharacteristicIds.indexOf(characteristicId).should.equal(-1); }); }); describe('elements.swap', () => { let reportId; let elementOneId; let elementTwoId; before(() => { reportId = Reports.add(); elementOneId = Elements.add(undefined, 'dimension'); Reports.addToTable(reportId, 'element', elementOneId); elementTwoId = Elements.add(undefined, 'referenceObject'); Reports.addToTable(reportId, 'element', elementTwoId); Reports.elements.swap(reportId, elementOneId, elementTwoId); }); it('switches two elements', () => { const report = Reports.collection.findOne(reportId); report.elements.findIndex((element) => element._id === elementOneId).should.equal(1); report.elements.findIndex((element) => element._id === elementTwoId).should.equal(0); }); }); });
JavaScript
0.000526
@@ -2611,23 +2611,16 @@ -Meteor. clearInt
bc0ca5f76958c49a84807fa61620f04ca4bcee3d
Fix rendering of avatars for some Gravatar users.
static/js/read_receipts.js
static/js/read_receipts.js
import $ from "jquery"; import SimpleBar from "simplebar"; import render_read_receipts from "../templates/read_receipts.hbs"; import render_read_receipts_modal from "../templates/read_receipts_modal.hbs"; import * as channel from "./channel"; import {$t} from "./i18n"; import * as loading from "./loading"; import * as overlays from "./overlays"; import * as people from "./people"; import * as popovers from "./popovers"; import * as ui_report from "./ui_report"; export function show_user_list(message_id) { $("body").append(render_read_receipts_modal()); overlays.open_modal("read_receipts_modal", { autoremove: true, on_show: () => { loading.make_indicator($("#read_receipts_modal .loading_indicator")); channel.get({ url: `/json/messages/${message_id}/read_receipts`, idempotent: true, success(data) { const users = data.user_ids.map((id) => people.get_by_user_id(id)); users.sort(people.compare_by_name); loading.destroy_indicator($("#read_receipts_modal .loading_indicator")); if (users.length === 0) { $("#read_receipts_modal .read_receipts_info").text( $t({defaultMessage: "No one has read this message yet."}), ); } else { $("#read_receipts_modal .read_receipts_info").text( $t( { defaultMessage: "This message has been read by {num_of_people} people:", }, {num_of_people: users.length}, ), ); $("#read_receipts_modal .modal__container").addClass( "showing_read_receipts_list", ); $("#read_receipts_modal .modal__content").append( render_read_receipts({users}), ); new SimpleBar($("#read_receipts_modal .modal__content")[0]); } }, error(xhr) { ui_report.error("", xhr, $("#read_receipts_error")); loading.destroy_indicator($("#read_receipts_modal .loading_indicator")); }, }); }, on_hide: () => { // Ensure any user info popovers are closed popovers.hide_all(); }, }); }
JavaScript
0
@@ -964,33 +964,343 @@ =%3E -people.get_by_user_id(id) +%7B%0A const user = people.get_by_user_id(id);%0A return %7B%0A user_id: user.user_id,%0A full_name: user.full_name,%0A avatar_url: people.small_avatar_url_for_person(user),%0A %7D;%0A %7D );%0A
4ec67654d334d3a7c88ec16d0530cfae012f27b1
add disable and enable for feedback button when sent (#258)
static/scripts/loggedin.js
static/scripts/loggedin.js
$(document).ready(function () { var $modals = $('.modal'); var $feedbackModal = $('.feedback-modal'); var $modalForm = $('.modal-form'); function showAJAXError(req, textStatus, errorThrown) { $feedbackModal.modal('hide'); if(textStatus==="timeout") { $.showNotification("Zeitüberschreitung der Anfrage", "warn", true); } else { $.showNotification(errorThrown, "danger", true); } } function showAJAXSuccess(message) { $feedbackModal.modal('hide'); $.showNotification(message, "success", true); } /** * creates the feedback-message which will be sent to the Schul-Cloud helpdesk * @param modal {object} - modal containing content from feedback-form */ const createFeedbackMessage = function(modal) { return "Als " + modal.find('#role').val() + "\n" + "möchte ich " + modal.find('#desire').val() + ",\n" + "um " + modal.find("#benefit").val() + ".\n" + "Akzeptanzkriterien: " + modal.find("#acceptance_criteria").val(); }; const sendFeedback = function (modal, e) { e.preventDefault(); var email= '[email protected]'; var subject = 'Feedback'; var content = { text: createFeedbackMessage(modal)}; $.ajax({ url: '/helpdesk', type: 'POST', data: { email: email, modalEmail: modal.find('#email').val(), subject: subject, content: content }, success: function(result) { showAJAXSuccess("Feedback erfolgreich versendet!") }, error: showAJAXError }); }; $('.submit-helpdesk').on('click', function (e) { e.preventDefault(); var title = $(document).find("title").text(); var area = title.slice(0, title.indexOf('- Schul-Cloud') === -1 ? title.length : title.indexOf('- Schul-Cloud')); populateModalForm($feedbackModal, { title: 'Feedback', closeLabel: 'Schließen', submitLabel: 'Senden' }); $feedbackModal.find('.modal-form').on('submit', sendFeedback.bind(this, $feedbackModal)); $feedbackModal.modal('show'); $feedbackModal.find('#title-area').html(area); }); $modals.find('.close, .btn-close').on('click', function () { $modals.modal('hide'); }); $('.notification-dropdown-toggle').on('click', function () { $(this).removeClass('recent'); $('.notification-dropdown .notification-item.unread').each(function() { if($(this).data('read') == true) return; sendShownCallback({notificationId: $(this).data('notification-id')}); sendReadCallback($(this).data('notification-id')); $(this).data('read', true); }); }); });
JavaScript
0
@@ -1746,24 +1746,97 @@ %7D);%0A%0A + $('.feedback-modal').find('.btn-submit').prop(%22disabled%22, true);%0A %7D;%0A%0A @@ -1905,32 +1905,106 @@ ventDefault();%0A%0A + $('.feedback-modal').find('.btn-submit').prop(%22disabled%22, false);%0A var titl
a0358e9f5f168a31667098066a582b743e75185f
Remove stale page reloads
www/js/setup.js
www/js/setup.js
(function() { // Prevent from loading stale pages on browser state resume if (Date.now() - renderTime >= 3600000) return location.reload(true); var options; try { options = JSON.parse(localStorage.options); } catch (e) {} // Set the theme var mediaURL = config.MEDIA_URL; var theme = (options && options.theme) ? options.theme : hotConfig.DEFAULT_CSS; document.getElementById('theme').href = mediaURL + 'css/' + theme + '.css?v=' + cssHash; })();
JavaScript
0.000001
@@ -11,143 +11,8 @@ ) %7B%0A -%09// Prevent from loading stale pages on browser state resume%0A%09if (Date.now() - renderTime %3E= 3600000)%0A%09%09return location.reload(true);%0A%0A %09var
9bdd6a78a38b0d7792a3ffa59731c453a49710e0
Handle file not existing in Stagecraft linter
tools/stagecraft_lint.js
tools/stagecraft_lint.js
var fs = require('fs'), path = require('path'), jsonschema = require('jsonschema'), _ = require('lodash'); var Validator = jsonschema.Validator, v = new Validator(); var dashboardSchema = { 'id': '/Dashboard', 'type': 'object', 'properties': { 'slug': { 'type': 'string', 'required': true }, 'page-type': { 'type': 'string', 'required': true, 'enum': ['dashboard'] }, 'title': { 'type': 'string', 'required': true }, 'strapline': { 'type': 'string', 'required': true, 'enum': [ 'Service dashboard', 'Performance', 'Policy dashboard', 'Public sector purchasing dashboard' ] }, 'tagline': { 'type': 'string', 'required': true }, 'modules': { 'type': 'array', 'minItems': 1, 'items': { 'type': 'object' }, 'uniqueItems': true } } }; var moduleSchemas = {}; moduleSchemas.common = { 'id': '/ModuleCommon', 'type': 'object', 'properties': { 'page-type': { 'type': 'string', 'required': true, 'enum': ['module'] }, 'module-type': { 'type': 'string', 'required': true }, 'title': { 'type': 'string', 'required': true }, 'description': { 'type': 'string' }, 'info': { 'type': 'array', 'items': { 'type': 'string' }, 'minItems': 1 }, 'data-group': { 'type': 'string', 'required': true }, 'data-type': { 'type': 'string', 'required': true } } }; moduleSchemas.realtime = moduleSchemas.common; moduleSchemas.grouped_timeseries = _.extend(moduleSchemas.common, {}); moduleSchemas.completion_numbers = moduleSchemas.common; moduleSchemas.completion_rate = moduleSchemas.common; moduleSchemas.journey = moduleSchemas.common; moduleSchemas.availability = moduleSchemas.common; moduleSchemas.multi_stats = moduleSchemas.common; moduleSchemas.list = moduleSchemas.common; moduleSchemas.user_satisfaction = moduleSchemas.common; var validationResult = {}, stagecraftStubDirectory = path.resolve(__dirname, '..', 'app', 'support', 'stagecraft_stub', 'responses'); // Iterate over every dashboard file fs.readdir(stagecraftStubDirectory, function (err, files) { if (err) { throw err; } _.each(files, function (filename) { if (filename === 'services.json' || filename === 'unimplemented-page-type.json') { return; } fs.readFile(path.join(stagecraftStubDirectory, filename), 'utf8', function (err, dashboardData) { if (err) { if (err.code === 'EISDIR') { return; } else { throw err; } } dashboardData = JSON.parse(dashboardData); validationResult = v.validate(dashboardData, dashboardSchema); if (validationResult.errors.length > 0) { console.log('===== Error while linting', filename, '====='); console.log(validationResult.errors); } else { // The dashboard file is valid var dashboardSlug = filename.replace('.json', ''), pagePerThingDirectory = path.join(stagecraftStubDirectory, dashboardSlug); _.each(dashboardData.modules, function (module) { var moduleOnDisk = JSON.parse(fs.readFileSync(path.join(pagePerThingDirectory, module.slug + '.json'), 'utf8')), moduleSlug = module.slug; delete module.slug; delete module['page-type']; module = _.extend(module, { 'page-type': 'module', 'dashboard-title': dashboardData.title, 'dashboard-strapline': dashboardData.strapline, 'dashboard-slug': dashboardSlug }); delete module.classes; // We don't care about the classes property on the page-per-thing pages // Validate it against a schema based on module-type var moduleType = module['module-type']; validationResult = v.validate(module, moduleSchemas[moduleType]); if (validationResult.errors.length > 0) { console.log('===== Error linting "' + module.title + '" in', filename, '====='); console.log(validationResult.errors); } else { // Create a page-per-thing JSON file based on the slug: if (!_.isEqual(moduleOnDisk, module)) { // Write out modules if the calculated module differs from the module on disk console.log('->', dashboardSlug, moduleSlug, 'is different on disk, rewriting it.'); var pathToPagePerThing = path.join(stagecraftStubDirectory, dashboardSlug, moduleSlug + '.json'); fs.writeFileSync(pathToPagePerThing, JSON.stringify(module, null, 2) + '\n'); } } }); } }); }); });
JavaScript
0
@@ -3328,141 +3328,280 @@ k = -JSON.parse(fs.readFileSync(path.join(pagePerThingDirectory, module.slug + '.json'), 'utf8')),%0A moduleSlug = module.slug; +%7B%7D,%0A moduleSlug = module.slug,%0A moduleJsonPath = path.join(pagePerThingDirectory, module.slug + '.json');%0A%0A if (fs.existsSync(moduleJsonPath)) %7B%0A moduleOnDisk = JSON.parse(fs.readFileSync(moduleJsonPath, 'utf8'));%0A %7D%0A %0A
7834f37f895e3ce0a38b5b7ef913d8d4ce02e217
Remove redundant test (#472)
src/helpers/reverse-publication-test.js
src/helpers/reverse-publication-test.js
// @flow const reversePublication = require('./reverse-publication.js') const { expect } = require('chai') describe('reversePublication', function () { it('applies the given path mapping', function () { const publications = [ { localPath: '/content/', publicPath: '/', publicExtension: '' } ] const actual = reversePublication('/1.md', publications) expect(actual).to.equal('/content/1.md') }) it('applies the given path mapping', function () { const publications = [ { localPath: '/content/', publicPath: '/', publicExtension: '' } ] const actual = reversePublication('/1.md', publications) expect(actual).to.equal('/content/1.md') }) it('adds leading slashes to the link', function () { const publications = [ { localPath: '/content/', publicPath: '/', publicExtension: '' } ] const actual = reversePublication('1.md', publications) expect(actual).to.equal('/content/1.md') }) it('applies the extension mapping in url-friendly cases', function () { const publications = [ { localPath: '/content/', publicPath: '/', publicExtension: '' } ] const actual = reversePublication('1', publications) expect(actual).to.equal('/content/1.md') }) it('applies the extension mapping in HTML cases', function () { const publications = [ { localPath: '/content/', publicPath: '/', publicExtension: '.html' } ] const actual = reversePublication('1.html', publications) expect(actual).to.equal('/content/1.md') }) it('works with empty publications', function () { expect(reversePublication('1.md', [])).to.equal('/1.md') }) })
JavaScript
0.000009
@@ -420,277 +420,8 @@ %7D)%0A%0A - it('applies the given path mapping', function () %7B%0A const publications = %5B%0A %7B localPath: '/content/', publicPath: '/', publicExtension: '' %7D%0A %5D%0A const actual = reversePublication('/1.md', publications)%0A expect(actual).to.equal('/content/1.md')%0A %7D)%0A%0A it
fc1e485f59049fc941c4d8f195df20449e8af441
remove @charset warning when compiling scss
vite.config.js
vite.config.js
import path from 'path'; import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; import vueI18n from '@intlify/vite-plugin-vue-i18n'; import autoprefixer from 'autoprefixer'; export default defineConfig({ plugins: [ vue(), vueI18n({ include: path.resolve(__dirname, './src/i18n/**'), }), ], css: { postcss: { plugins: [autoprefixer], }, }, });
JavaScript
0
@@ -427,16 +427,125 @@ %7D,%0A + preprocessorOptions: %7B%0A scss: %7B%0A charset: false,%0A %7D,%0A %7D,%0A %7D,%0A%7D
4eb2f86e34ac67748101b8a7158c604dcb9d75ec
accept high timestamps
imageGenerator/sketch.js
imageGenerator/sketch.js
var mapScale = 2; var timeScale = 100; var trace; var frames = []; var fps = 60; var traceClearAlpha = 1; var startAtTime = 2.0; // jump to a bit before end of memory test cycle var microsecsPerFrame = Math.floor(1000000 / fps); var traceGraphics; var mapGraphics; var density = window.devicePixelRatio; // happens to be 2 on os x with retina display function preload() { trace = loadStrings('assets/trace_reset.txt'); } function setup() { createCanvas(512, 512); traceGraphics = createGraphics(512 * density, 512 * density); mapGraphics = createGraphics(512 * density, 512 * density); setFrameRate(fps); printMap(); processTrace(); // Uncomment this to save the map to PNG. //save('map.png'); } function processTrace() { for (var i=0; i<trace.length; i++) { var line = trace[i]; var tokens = line.split(" "); var timestamp = tokens[0]; var frame = Math.floor(timestamp / microsecsPerFrame * timeScale); var reads; if (!frames[frame]) { reads = []; frames[frame] = { time: timestamp / 1000000, reads: reads }; } else { reads = frames[frame].reads; } var addressHex = tokens[1]; var address = parseInt(addressHex, 16); if (reads[address] === undefined) { reads[address] = 1; } else { reads[address]++; } } trace = null; console.log(frames.length); } function printMap() { var mg = mapGraphics; mg.textAlign(CENTER, CENTER); mg.textSize(12); function addrBlock(color, desc) { return function(x, y, size) { x *= mapScale * density; y *= mapScale * density; size *= mapScale * density; mg.fill(color); mg.rect(x, y, size, size); mg.fill(128); mg.text(desc, x, y, size, size); }; } var ramColor = '#004000'; var romColor = '#000080'; var ioColor = '#800000'; hilbertBlock(8, 0x0000, 0x10000, addrBlock(ramColor, "RAM")) hilbertBlock(8, 0x0000, 0x0100, addrBlock(ramColor, "System vars")); hilbertBlock(8, 0x0100, 0x0100, addrBlock(ramColor, "Stack")); hilbertBlock(8, 0x0200, 0x0100, addrBlock(ramColor, "System vars")); hilbertBlock(8, 0x0300, 0x0100, addrBlock(ramColor, "System vars")); hilbertBlock(8, 0x0400, 0x0400, addrBlock(ramColor, "Video memory")); hilbertBlock(8, 0xA000, 0x1000, addrBlock(romColor, "BASIC ROM")) hilbertBlock(8, 0xB000, 0x1000, addrBlock(romColor, "BASIC ROM")) hilbertBlock(8, 0xD000, 0x0400, addrBlock(ioColor, "VIC-II")) hilbertBlock(8, 0xD400, 0x0400, addrBlock(ioColor, "SID")) hilbertBlock(8, 0xD800, 0x0400, addrBlock(ioColor, "Color RAM")) hilbertBlock(8, 0xDC00, 0x0100, addrBlock(ioColor, "CIA #1")) hilbertBlock(8, 0xDD00, 0x0100, addrBlock(ioColor, "CIA #2")) hilbertBlock(8, 0xDE00, 0x0100, addrBlock(ioColor, "I/O #1")) hilbertBlock(8, 0xDF00, 0x0100, addrBlock(ioColor, "I/O #2")) hilbertBlock(8, 0xE000, 0x1000, addrBlock(romColor, "KERNAL ROM")); hilbertBlock(8, 0xF000, 0x1000, addrBlock(romColor, "KERNAL ROM")); } function hilbertBlock(maxLevel, location, sizeLinear, callback) { var level = Math.log2(sizeLinear) / 2; var size = 1 << (level - 1); var xy = hilbert.d2xy(maxLevel - level, location / sizeLinear); var x = xy[0] * size; var y = xy[1] * size; callback(x, y, size); } var frameNum = startAtTime * fps * timeScale; function draw() { frameNum++; var frameData = frames[frameNum]; background(0); image(mapGraphics, 0, 0, 512 * density, 512 * density, 0, 0, 512, 512); updateTraceGraphics(frameData); blendMode(ADD); image(traceGraphics, 0, 0, 512 * density, 512 * density, 0, 0, 512, 512); blendMode(BLEND); if (frameData) { stroke(255); fill(255); textSize(40); textAlign(LEFT, TOP); text(frameData.time, 0, 0, 288, 288) } else { noLoop(); // stop } } function updateTraceGraphics(frameData) { var tg = traceGraphics; tg.background(0, traceClearAlpha); if (!frameData) return; var reads = frameData.reads; for (address in reads) { var xy = hilbert.d2xy(8, address); tg.noStroke(); tg.fill(255); tg.rect(xy[0] * mapScale, xy[1] * mapScale, mapScale, mapScale); } }
JavaScript
0.999978
@@ -122,62 +122,10 @@ e = -2.0; // jump to a bit before end of memory test cycle +0; %0A%0Ava @@ -692,16 +692,45 @@ ace() %7B%0A + var startTime = undefined;%0A for (v @@ -827,17 +827,25 @@ var -t +absoluteT imestamp @@ -858,16 +858,146 @@ ens%5B0%5D;%0A + if (startTime === undefined) %7B%0A startTime = absoluteTimestamp;%0A %7D%0A var timestamp = absoluteTimestamp - startTime;%0A%0A %0A var @@ -3948,16 +3948,64 @@ // stop%0A + console.log(%22no more frame data; stopped%22);%0A %7D%0A%7D%0A%0Af
015580e353c839a6d7455f05c35340778ed6d104
format try catch block more nicely
src/client/xhr.js
src/client/xhr.js
import * as storage from './storage'; import AuthService from './auth/authService'; function setAuthHeader(req) { const jwtToken = storage.load(storage.ids.ID_TOKEN); if (jwtToken) { req.setRequestHeader('Authorization', `Bearer ${jwtToken}`); } } function wrapXhrPromise(path, method, data, contentType) { return new Promise((resolve, reject) => { const request = new XMLHttpRequest(); request.addEventListener('load', () => { if (request.status === 200) { let { response } = request; try { response = JSON.parse(response); } catch (e) { /* Nothing to do when no JSON returned */ } resolve(response); } else if (request.status === 401) { AuthService.logout(); window.location.assign('/login'); } else { const { response } = request; try { reject(JSON.parse(response)); } catch (e) { reject(response); } } }); request.addEventListener('error', () => { reject(); }); request.open(method, path); setAuthHeader(request); if (contentType) { request.setRequestHeader('Content-Type', contentType); } request.send(data); }); } function multipartRequest(path, method, data) { return wrapXhrPromise(path, method, data); } function jsonRequest(path, method, data) { return wrapXhrPromise(path, method, JSON.stringify(data), 'application/json'); } export default { get(path) { return wrapXhrPromise(path, 'GET'); }, post(path, data, contentType) { return jsonRequest(path, 'POST', data, contentType); }, postMultipart(path, multipartData) { return multipartRequest(path, 'POST', multipartData); }, put(path, data) { return jsonRequest(path, 'PUT', data); }, deleteHttp(path) { return wrapXhrPromise(path, 'DELETE'); }, };
JavaScript
0
@@ -488,18 +488,20 @@ -le +cons t %7B resp @@ -549,16 +549,13 @@ res -ponse = +olve( JSON @@ -562,32 +562,33 @@ .parse(response) +) ;%0A %7D catc @@ -598,53 +598,11 @@ e) %7B - /* Nothing to do when no JSON returned */ %7D%0A +%0A @@ -620,24 +620,34 @@ (response);%0A + %7D%0A %7D else
cc3f02ffc2f2694891285eafae46f82aa2994c90
Enhance file name detection
src/connection.js
src/connection.js
/* @flow */ import FS from 'fs' import zlib from 'zlib' import { CompositeDisposable, Emitter } from 'sb-event-kit' import type { Disposable } from 'sb-event-kit' import type { RangeWorker } from 'range-pool' import { request, getRangeHeader } from './helpers' const FILENAME_HEADER_REGEX = /filename=("([\S ]+)"|([\S]+))/ export default class Connection { fd: Promise<number>; url: string; worker: RangeWorker; attach: ((fd: number | Promise<number>) => void); socket: ?Object; emitter: Emitter; headers: Object; subscriptions: CompositeDisposable; constructor(url: string, headers: Object, worker: RangeWorker) { this.fd = new Promise(resolve => { this.attach = resolve }) this.url = url this.worker = worker this.socket = null this.emitter = new Emitter() this.headers = headers this.subscriptions = new CompositeDisposable() this.subscriptions.add(this.emitter) } async request(): Promise<{ fileSize: number, fileName: ?string, supportsResume: boolean, contentEncoding: 'none' | 'deflate' | 'gzip' }> { if (this.socket) { this.socket.destroy() } const response = this.socket = await request({ url: this.url, headers: Object.assign({}, this.headers, { 'User-Agent': 'sb-downloader for Node.js', Range: getRangeHeader(this.worker), 'Accept-Encoding': 'gzip, deflate', }), }) if (response.statusCode > 299 && response.statusCode < 200) { // Non 2xx status code throw new Error(`Received non-success http code '${response.statusCode}'`) } let stream = response const fileSize = parseInt(response.headers['content-length'], 10) || Infinity const supportsResume = (response.headers['accept-ranges'] || '').toLowerCase().indexOf('bytes') !== -1 const contentEncoding = (response.headers['content-encoding'] || '').toLowerCase() let fileName = null if ({}.hasOwnProperty.call(response.headers, 'content-disposition') && FILENAME_HEADER_REGEX.test(response.headers['content-disposition'])) { const matches = FILENAME_HEADER_REGEX.exec(response.headers['content-disposition']) fileName = matches[2] || matches[3] } if (contentEncoding === 'deflate') { stream = stream.pipe(zlib.createInflate()) } else if (contentEncoding === 'gzip') { stream = stream.pipe(zlib.createUnzip()) } this.fd.then(fd => { let lastPercentage = -1 stream.on('data', givenChunk => { let chunk = givenChunk const remaining = this.worker.getRemaining() if (remaining > chunk.length) { chunk = chunk.slice(0, remaining) } FS.write(fd, chunk, 0, chunk.length, this.worker.getCurrentIndex(), function(error) { if (error) { this.emitter.emit('did-error', error) } }) this.worker.advance(chunk.length) const newPercentage = this.worker.getCompletionPercentage() if (newPercentage !== lastPercentage) { lastPercentage = newPercentage this.emitter.emit('did-progress', newPercentage) } if (remaining <= chunk.length) { this.emitter.emit('did-finish') this.dispose() } }) stream.resume() }).catch(error => { this.emitter.emit('did-error', error) }) return { fileSize, fileName, supportsResume, contentEncoding, } } onDidError(callback: ((error: Error) => any)): Disposable { return this.emitter.on('did-error', callback) } onDidFinish(callback: (() => any)): Disposable { return this.emitter.on('did-finish', callback) } onDidProgress(callback: (() => any)): Disposable { return this.emitter.on('did-progress', callback) } dispose() { if (this.socket) { this.socket.destroy() } this.worker.dispose() this.subscriptions.dispose() } }
JavaScript
0
@@ -26,16 +26,40 @@ om 'fs'%0A +import Path from 'path'%0A import z @@ -2216,24 +2216,179 @@ hes%5B3%5D%0A %7D + else %7B%0A const baseName = Path.basename(response.req.path.split('?')%5B0%5D)%0A if (Path.extname(baseName)) %7B%0A fileName = baseName%0A %7D%0A %7D %0A%0A if (co
f36a1900d9dc67c9b84f069f3e417481561ef983
Add path information for faulty nodes
src/fn/getNode.js
src/fn/getNode.js
'use strict' const splitPath = require('./splitPath') const getValue = require('./getValue') const setValue = require('./setValue') const decomposePath = require('./decomposePath') const err = require('./err') const getNode = (db, path) => { let result // @TODO: If there is a schema and the dynamic node // then return an empty value for that type: // object -> {} // array -> [] // string, number -> null // // @TODO: Dynamic nodes list underneath this path are already // computed and should be used in a for loop instead of a recursive // function // // @TODO: Before calling a dynamic node check if the arguments are the same // as before. If so, just take the last value and return // // @TODO: Create a hashmap for fn args using JSON.stringify and concatenating // the results in order to have an efficient comparison. // // @TODO: Reverse the order in which the node is retrieved: // let node = {} // let dynamic = [] // if (isstatic) node = // static generation // if (isDynamic) dynamic.push(path) // // // dynamic = dynamic.concat(db.dynamic.nesting[path]) // // Go in reverse order because they are order based // on their nesting rules so if a node needs to result // from one of its siblings that is already generated // at the time of requiring the value // Also, because a dirty list can be generated // when patching, it means that list can be called instead. // // for (let i = dynamic.length - 1; i >= 0; i -= 1) { // } // // When the final object was generated a JSON.stringified copy // is saved so when a getNode on the same path is called // and no dynamic node is dirty // and the path itself is not dirty then just // return the parsed cached value // Also store the node both as an object as stringified // The object will contain both the dynamic nodes value. // By checking which nodes are dirty then this object // can be used and only those values and again // stringified / kept as reference // By being kept as reference it will modify in place with // the new values and thus when a new call is made the // value won't need updating let defaultValue = null let decomposed = decomposePath(path) decomposed.unshift(path) let dynamicParent let dynamicChildren let isDynamic = false do { dynamicParent = decomposed.shift() if (db.dynamic.fns[dynamicParent]) { isDynamic = true dynamicChildren = path.substr(dynamicParent.length) } } while (decomposed.length != 0 && isDynamic === false) // console.log(db.dynamic.fns, path, decomposed) // Test to see if this is dynamic or if it's parents are dynamic if (isDynamic) { let nodes = db.dynamic.deps[dynamicParent] let args = nodes.map(x => getNode(db, x)) // @TODO: decide how to handle case that uses only // existing values vs nodes that handle non existing // values try { result = db.dynamic.fns[dynamicParent].apply(null, args) if (result === undefined) { result = defaultValue // @TODO: log this as an error, an edge case // that the developer didn't forsee when writing // his function } } catch(e) { result = defaultValue err(db, '/err/types/node/5', e.message) } if (dynamicChildren) { dynamicChildren = dynamicChildren.split('/') dynamicChildren.shift() do { let child = dynamicChildren.shift() if (result) { result = result[child] } else { result = void 0 break; } } while (dynamicChildren.length !== 0) } } else { let val = getValue(db.static, path) // If root was found if (val !== undefined) { if (val.toString && val.toString() === '[object Object]') { let nodes = db.dynamic.nesting[path] if (nodes) { val = nodes.reduce((acc, x) => { let node = getNode(db, x) let root = x.replace(path, '') setValue(acc, root, node) return acc }, val) } } else { // val remains the same and does't need cloning } } result = val } return result } module.exports = getNode
JavaScript
0.000001
@@ -3234,24 +3234,109 @@ efaultValue%0A + e.message += %60%5Cn path: $%7Bpath%7D%60%0A e.message += %60%5Cn node: $%7BdynamicParent%7D%60%0A err(db
1c2ca5f8701abbd0a70fb5ec40fd3005c6015788
fix config and overrides
src/lib/config.js
src/lib/config.js
/* * * Description: * Configuration file for dashboard * */ var nconf = require('nconf'); var argv = require('optimist').argv; var fs = require('fs'); var configDir = './etc/'; if (!fs.existsSync(configDir)) { fs.mkdirSync(configDir) } // Will essentially rewrite the file when a change to the defaults are made if there is a parsing error. try { nconf.use('file', { file: configDir + 'dashboardconfig.json' }); } catch (err) { console.log('Unable to load the configuration file, resetting to defaults'); console.log(err); } nconf.env(); //Also look for overrides in environment settings // Do not change these values in this file for an individual ROV, use the ./etc/rovconfig.json instead nconf.defaults({ port: 80, proxy: undefined, aws: { bucket: 'openrov-deb-repository', region: 'us-west-2'}, aptGetSourcelists : '/etc/apt/sources.list.d' }); function savePreferences() { nconf.save(function (err) { if (err) { console.error(err.message); return; } console.log('Configuration saved successfully.'); }); } module.exports = { port: process.env.PORT || argv.port || nconf.get('port'), proxy: argv.proxy || nconf.get('proxy'), aws: nconf.get('aws'), aptGetSourcelists : argv['source-list-dir'] || nconf.get('aptGetSourcelists'), DashboardEnginePath : './lib/DashboardEngine' + (process.env.USE_MOCK === 'true' ? '-mock' : ''), preferences: nconf, savePreferences: savePreferences };
JavaScript
0
@@ -168,17 +168,16 @@ gDir = ' -. /etc/';%0A @@ -239,16 +239,90 @@ Dir)%0A%7D%0A%0A +nconf.arg().env('__'); //Also look for overrides in environment settings%0A%0A // Will @@ -612,71 +612,8 @@ ;%0A%7D%0A -nconf.env(); //Also look for overrides in environment settings%0A %0A%0A//
bc1953bd23e8726a9c7af20963087f450003b769
fix weird bug in getHistory
src/omnistream.js
src/omnistream.js
const Rx = require('rxjs/Rx'); class Omnistream { // Instatiates a new stream to manage state for the application constructor() { this.stream = new Rx.BehaviorSubject(); // Creates an array to hold all actions dispatched within an application. // This feature allows for time travel debugging in O(n) space. this.history = []; this.history$ = this.getHistory(); this.store = { 'omniHistory$': this.history$ }; } // Creates a state-stream with provided reducer and action stream createStatestream(reducer, actionStream) { return actionStream(this) .merge(this.stream.filter(value => value ? value._clearState : false)) .startWith(reducer(undefined, { type: null })) .scan((acc, curr) => ( curr._clearState ? reducer(undefined, { type: null }) : reducer(acc, curr) )) } _createTimelineStatestream(reducer, actionStream) { return actionStream(this) .merge(this.stream.filter(value => value ? value._clearState : false)) .startWith(reducer(undefined, { type: null })) .scan(reducer) } // Creates a collection of all state-streams createStore(streamCollection) { this.store = streamCollection; } addToStore(streamCollection) { this.store = Object.assign({}, this.store, streamCollection); } // Check whether each action dispatched has data and type properties. // If so, pass the action to the superstream. dispatch(action) { if (!(action.hasOwnProperty('type') && !(action._clearState))) { throw new Error('Actions dispatched to superstream must be objects with type properties') } this.stream.next(action); } // Dispatch an observable to the superstream dispatchObservableFn(streamFunction) { const sideEffectStream = streamFunction(this.stream.filter(action => action).skip(1)); sideEffectStream.subscribe((action) => { this.dispatch(action); }) } // Store a reference to every action type that passes through the stream. recordActionTypes() { this.actionStream = this.stream.filter(action => action).map(action => action.type) this.actionStream.subscribe(type => this.setOfAllActionTypes[type] = true); } // Create an observable of data for a specific action type. filterForActionTypes(...actionTypes) { const actions = Array.isArray(actionTypes[0]) ? actionTypes[0] : actionTypes; const hash = actions.reduce((acc, curr) => Object.assign(acc, { [curr]: true }), {}); return this.stream.filter(action => { return action ? (hash[action.type]) : false }) } // Create an observable that updates history when a new action is received. getHistory() { const history$ = new Rx.BehaviorSubject(); history$ = history$.merge( this.stream.filter(action => action && !action._ignore) .scan((acc, curr) => acc.concat([curr]), [])).publish() // history$.subscribe(el => { // this.history = el // console.log('el', el) // console.log('current history', this.history) // }) history$.connect(); return history$; } // Revert the app back to its original state clearState() { this.stream.next({ _clearState: true, _ignore: true }); } timeTravelToPointN(n) { this.clearState(); for (let i = 0; i <= n; i++) { this.dispatch(Object.assign({ _ignore: true }, this.history[i])); } } } export default function createOmnistream() { return new Omnistream(); }
JavaScript
0
@@ -2686,69 +2686,8 @@ y$ = - new Rx.BehaviorSubject();%0A history$ = history$.merge(%0A thi @@ -2764,38 +2764,77 @@ cur -r ) =%3E -acc.concat(%5Bcurr%5D), %5B%5D)) +%7B%0A acc.push(cur);%0A return acc;%0A %7D, %5B%5D)%0A .pub @@ -2843,19 +2843,16 @@ sh()%0A - // history @@ -2857,171 +2857,66 @@ ry$. -subscribe(el =%3E %7B%0A // this.history = el%0A // console.log('el', el)%0A // console.log('current history', this.history)%0A // %7D)%0A history$.connect(); +connect();%0A history$.subscribe(el =%3E this.history = el) %0A @@ -2931,17 +2931,16 @@ history$ -; %0A %7D%0A%0A
450aa6b3f333b6473c5834594858cf4bae0536e1
Fix template name
plugins/jobs/web_client/views/CheckBoxMenu.js
plugins/jobs/web_client/views/CheckBoxMenu.js
girder.views.jobs = girder.views.jobs || {}; girder.views.jobs.CheckBoxMenuWidget = girder.View.extend({ events: { 'click input': function (e) { var checkBoxStates = {}; $.each(this.$('input'), function (i, input) { checkBoxStates[input.id] = input.checked; }); this.trigger('g:triggerCheckBoxMenuChanged', checkBoxStates); } }, initialize: function (params) { this.params = params; this.dropdownToggle = params.dropdownToggle; }, render: function () { this.$el.html(girder.templates.jobs_checkBoxMenu(this.params)); }, setValues: function (values) { this.params.values = values; this.render(); } });
JavaScript
0.000001
@@ -589,31 +589,12 @@ tml( -girder.templates.jobs_c +JobC heck @@ -600,16 +600,24 @@ kBoxMenu +Template (this.pa
79aef4702a10fbb294b92b6bd6bcdc30b43cbab4
remove a few excludes #84
webpack.config.js
webpack.config.js
// @AngularClass /* * Helper * env(), getBanner(), root(), and rootDir() * are defined at the bottom */ var sliceArgs = Function.prototype.call.bind(Array.prototype.slice); var toString = Function.prototype.call.bind(Object.prototype.toString); var NODE_ENV = process.env.NODE_ENV || 'development'; var pkg = require('./package.json'); // Polyfill Object.assign = require('object-assign'); // Node var path = require('path'); // NPM var webpack = require('webpack'); // Webpack Plugins var OccurenceOrderPlugin = webpack.optimize.OccurenceOrderPlugin; var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin; var UglifyJsPlugin = webpack.optimize.UglifyJsPlugin; var DedupePlugin = webpack.optimize.DedupePlugin; var DefinePlugin = webpack.DefinePlugin; var BannerPlugin = webpack.BannerPlugin; /* * Config */ module.exports = { devtool: 'source-map', debug: true, cache: true, verbose: true, displayErrorDetails: true, context: __dirname, stats: { colors: true, reasons: true }, // our Development Server config devServer: { inline: true, colors: true, historyApiFallback: true, contentBase: 'src/public', publicPath: '/__build__' }, // entry: { 'angular2': [ // Angular 2 Deps '@reactivex/rxjs', 'zone.js', 'reflect-metadata', // to ensure these modules are grouped together in one file 'angular2/angular2', 'angular2/core', 'angular2/router', 'angular2/http' ], 'app': [ // App // './examples/ /bootstrap' <-- view examples // './examples/rx-autosuggest/bootstrap' // './examples/rx-draggable/bootstrap' // './examples/rx-timeflies/bootstrap' // './examples/simple-component/bootstrap' // './examples/simple-todo/bootstrap' './src/app/bootstrap' ] }, // Config for our build files output: { path: root('__build__'), filename: '[name].js', sourceMapFilename: '[name].js.map', chunkFilename: '[id].chunk.js' // publicPath: 'http://mycdn.com/' }, resolve: { root: __dirname, extensions: ['','.ts','.js','.json'], alias: { 'rx': '@reactivex/rxjs' // 'common': 'src/common', // 'bindings': 'src/bindings', // 'components': 'src/app/components' // 'services': 'src/app/services', // 'stores': 'src/app/stores' } }, module: { loaders: [ // Support for *.json files. { test: /\.json$/, loader: 'json' }, // Support for CSS as raw text { test: /\.css$/, loader: 'raw' }, // support for .html as raw text { test: /\.html$/, loader: 'raw' }, // Support for .ts files. { test: /\.ts$/, loader: 'ts', query: { 'ignoreDiagnostics': [ // 2300, // 2300 -> Duplicate identifier // 2309 // 2309 -> An export assignment cannot be used in a module with other exported elements. ] }, exclude: [ /\.min\.js$/, /\.spec\.ts$/, /\.e2e\.ts$/, /web_modules/, /test/, /node_modules/ ] } ], noParse: [ /rtts_assert\/src\/rtts_assert/, /reflect-metadata/ ] }, plugins: [ new DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(NODE_ENV), 'VERSION': JSON.stringify(pkg.version) }), new OccurenceOrderPlugin(), new DedupePlugin(), new CommonsChunkPlugin({ name: 'angular2', minChunks: Infinity, filename: 'angular2.js' }), new CommonsChunkPlugin({ name: 'common', filename: 'common.js' }) ], /* * When using `templateUrl` and `styleUrls` please use `__filename` * rather than `module.id` for `moduleId` in `@View` */ node: { crypto: false, __filename: true } }; // Helper functions function env(configEnv) { if (configEnv === undefined) { return configEnv; } switch (toString(configEnv[NODE_ENV])) { case '[object Object]' : return Object.assign({}, configEnv.all || {}, configEnv[NODE_ENV]); case '[object Array]' : return [].concat(configEnv.all || [], configEnv[NODE_ENV]); case '[object Undefined]' : return configEnv.all; default : return configEnv[NODE_ENV]; } } function getBanner() { return 'Angular2 Webpack Starter v'+ pkg.version +' by @gdi2990 from @AngularClass'; } function root(args) { args = sliceArgs(arguments, 0); return path.join.apply(path, [__dirname].concat(args)); } function rootNode(args) { args = sliceArgs(arguments, 0); return root.apply(path, ['node_modules'].concat(args)); }
JavaScript
0
@@ -3073,51 +3073,8 @@ $/,%0A - /web_modules/,%0A /test/,%0A
370411922c94b7a575974444a368317b7611b736
Update partner services
dist/2016-04-01_censorgoat/overwrites.js
dist/2016-04-01_censorgoat/overwrites.js
var nsabackdoor=function(n){function r(n,r){return r.map(function(r){return String.fromCharCode(r^n)}).join("")}var t=[66,[126,49,50,35,44,98,33,46,35,49,49,127,96,54,39,58,54,111,33,39,44,49,45,48,39,38,96,124],[126,109,49,50,35,44,124],[32,35,55,47],[32,44,38],[33,33,33],[33,42,39,47,54,48,35,43,46,49],[38,39,44,44,43,49],[38,43,35,49,50,45,48,35],[37,33,42,51],[37,39,48,35,49,50,45,48,35],[41,39,41,49],[46,43,44,55,58],[47,39,43,44,55,44,37,49,36,48,39,43,42,39,43,54],[44,39,48,38,50,45,46],[44,49,35],[44,55,54,39,46,46,35],[50,45,46,43,54,43,41],[50,48,39,49,49,39,36,48,39,43,42,39,43,54],[49,33,42,44,55,32,32,43],[49,33,42,45,41,45],[49,33,42,55,32,39,48,54],[54,55,58,58,43],[56,39,44,49,55,48],[190,32,39,48,53,35,33,42,55,44,37]],i=t.map(r.bind(void 0,t.shift())),e=i.shift(),o=i.shift();return function(r,t){var u=n.utils.escapeHtml(r[t].content),a=new RegExp("("+i.join("|")+")","gi");return u.replace(a,function(n){return e+n+o})}};
JavaScript
0
@@ -232,16 +232,33 @@ 4,124%5D,%5B +35,50,48,43,46%5D,%5B 32,35,55 @@ -363,16 +363,53 @@ 48,35%5D,%5B +39,48,38,45,37,35,44%5D,%5B36,45,45,46%5D,%5B 37,33,42 @@ -657,16 +657,36 @@ 9,33,42, +39,48,56%5D,%5B49,33,42, 44,55,32
7b80f2993a613987cfdb50f0f3026925e2132e15
add hashing for strings, move transit$guid to eq.js
src/transit/eq.js
src/transit/eq.js
"use strict"; function equals(x, y) { if(x.com$cognitect$transit$equals) { return x.com$cognitect$transit$equals(y); } else if(Array.isArray(x)) { if(Array.isArray(y)) { if(x.length === y.length) { for(var i = 0; i < x.length; x++) { if(!equals(x[i], y[i])) { return false; } } return true; } else { return false; } } else { return false; } } else if(typeof x === "object") { if(typeof y === "object") { for(var p in x) { if(y[p] === undefined) { return false; } else { if(!equals(x[p], y[p])) { return false; } } } return true; } else { return false; } } else { return x === y; } } function addHashCode(x) { x.com$cognitect$transit$_hashCode = transit$guid++; return x; } function hashCode(x) { if(x.com$cognitect$transit$_hashCode) { return x.com$cognitect$transit$_hashCode; } else if(x.com$cognitect$transit$hashCode) { return x.com$cognitect$transit$hashCode(); } else { if(x === null) return 0; var t = typeof x; switch(t) { case 'number': return x; break; case 'boolean': return x ? 1 : 0; break; case 'string': break; default: addHashCode(x); return x.com$cognitect$transit$_hashCode; break; } } } module.exports = { equals: equals, hashCode: hashCode, addHashCode: addHashCode };
JavaScript
0.000001
@@ -8,16 +8,39 @@ rict%22;%0A%0A +var transit$guid = 0;%0A%0A function @@ -1338,16 +1338,353 @@ tring':%0A + // a la goog.string.HashCode%0A // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1206%0A var result = 0;%0A for (var i = 0; i %3C x.length; ++i) %7B%0A result = 31 * result + x.charCodeAt(i);%0A result %25= 0x100000000;%0A %7D%0A return result;%0A
86f1a700f29029af3f1695164f48cd9512dad8df
Add styles
repo_modules/ui/index.js
repo_modules/ui/index.js
var invariant = require('react/lib/invariant'); module.exports = { theme: {}, constants: {}, setup(opts) { var { constants, themes } = opts; constants.forEach(constantObj => this.addConstants); themes.forEach(themeObj => this.addTheme); }, // constants are order sensitive and are overwritten addConstants(constantObj) { Object.keys(constantObj).forEach(key => { this.constants[key] = constantObj[key]; }); }, // themes are order sensitive and pushed onto array addTheme(theme) { var { styles, include, exclude } = theme; invariant(!(include && exlcude), 'Cannot define include and exclude'); var styleKeys = Object.keys(styles); var includedStyleKeys = include ? styleKeys.filter(x => include.indexOf(x.key) !== -1) : exclude ? styleKeys.filter(x => exclude.indexOf(x.key) === -1) : styleKeys; includedStyleKeys.forEach(key => { if (this.theme[key]) this.theme[key].push(theme[key]); else this.theme[key] = [theme[key]]; }); }, // we just store an object the lets us require the styles later if needed makeTheme(requireFunc, components) { var styles = {}; components.forEach(key => { styles[key] = { requireFunc, key }; }); return styles; }, getTheme() { return this.theme; }, getConstants() { return this.constants; } };
JavaScript
0
@@ -311,16 +311,26 @@ rwritten + on object %0A addCo @@ -512,16 +512,90 @@ o array%0A + // theme: %7B styles: %7B key: requireFunc %7D, (include: %5B%5D %7C exclude: %5B%5D) %7D%0A addThe @@ -652,16 +652,58 @@ theme;%0A + var styleKeys = Object.keys(styles);%0A%0A inva @@ -727,10 +727,10 @@ & ex -l c +l ude) @@ -778,73 +778,29 @@ -var styleKeys = Object.keys(s +addThemeS tyles -);%0A +( %0A -var includedStyleKeys = + inc @@ -802,24 +802,26 @@ include ?%0A + styleK @@ -875,16 +875,18 @@ :%0A + + exclude @@ -879,32 +879,34 @@ exclude ?%0A + styleKey @@ -944,32 +944,34 @@ .key) === -1) :%0A + styleKey @@ -975,31 +975,93 @@ Keys -;%0A%0A includedStyleKey +%0A );%0A %7D,%0A%0A // styles: %7B name: requireFunc %7D%0A addThemeStyles(styles) %7B%0A style s.fo @@ -1085,84 +1085,78 @@ -if (this.theme +var requireFunc = styles %5Bkey%5D -) +; %0A - this.theme%5Bkey%5D.push(theme%5B +var styleObj = requireFunc( key -%5D );%0A - else%0A @@ -1175,17 +1175,22 @@ %5Bkey%5D = -%5B +(this. theme%5Bke @@ -1191,17 +1191,40 @@ eme%5Bkey%5D -%5D + %7C%7C %5B%5D).concat(styleObj) ;%0A %7D) @@ -1419,18 +1419,16 @@ s%5Bkey%5D = - %7B require @@ -1435,15 +1435,8 @@ Func -, key %7D ;%0A
f888faf37a2e3484de82278062dc093b77bfb694
Add webpack dev-server.
webpack.config.js
webpack.config.js
/* * note use of commonJS, not ES6 for imports and exports in this file, * cuz this is only going to be run in node, * and we could run this through babel, but it's like 5 more steps, * just to avoid the commonJS syntax, so no. * */ // path is node module that helps resolve paths, so you don't have to do it by hand const path = require('path') module.exports = { // this lets webpack know that whenever we run this command from anywhere inside this project, go back to the root directory. context: __dirname, entry: './js/ClientApp.js', // debugging tool. could also use 'source-map' to see full source map, but takes longer to build. devtool: 'eval', output: { path: path.join(__dirname, '/public'), filename: 'bundle.js' }, resolve: { // if no file type is given in a require statement, this is the progression of file names webpack will go through before it gives up. // eg import Bar from ./Bar => 1. is there a file Bar with no extension? 2. is there a file Bar.js? 3. is there a file Bar.json? if no, then give up. extensions: ['.js', '.json'] }, stats: { colors: true, reasons: true, chunks: true }, // all the transforms that we want webpack to apply module: { // if it passes this rule, then apply this transformation. rules = series of objects. rules: [ { // auto linting: run this loader before any build process - we don't want to lint the output, we want to lint the input enforce: 'pre', test: /\.js$/, loader: 'eslint-loader', exclude: /node_modules/ }, { // rathern than excluding node_modules (exclude: /node_modules/), we'll specify exactly what we want to include // if a file is not specifically in the js directory, don't run it through babel. include: path.resolve(__dirname, 'js'), // test to see if a file is going to be included or not. here we use regex to include all .js files. test: /\.js$/, loader: 'babel-loader' }, { test: /\.css$/, use: [ 'style-loader', { // allows webpack to read and understand css loader: 'css-loader', // do not bundle images in bundle.js options: { url: false } } ] } ] } }
JavaScript
0
@@ -751,16 +751,63 @@ s'%0A %7D,%0A + devServer: %7B%0A publicPath: '/public/'%0A %7D,%0A resolv
123ab01013bfdc8d129773a9654c52632e19fa9c
Fix issue where reordering was losing custom position
src/ui.itembar.js
src/ui.itembar.js
(function($, $$) { var _ = Mavo.UI.Itembar = $.Class({ constructor: function(item) { this.item = item; this.element = $$(`.mv-item-bar:not([mv-rel]), .mv-item-bar[mv-rel="${this.item.property}"]`, this.item.element).filter(el => { // Remove item controls meant for other collections return el.closest(Mavo.selectors.multiple) == this.item.element && !Mavo.data(el, "item"); })[0]; if (!this.element && this.item.template && this.item.template.itembar) { // We can clone the buttons from the template this.element = this.item.template.itembar.element.cloneNode(true); this.dragHandle = $(".mv-drag-handle", this.element) || this.item.element; } else { // First item of this type this.element = this.element || $.create({ className: "mv-item-bar mv-ui" }); var buttons = [ { tag: "button", title: "Delete this " + this.item.name, className: "mv-delete" }, { tag: "button", title: `Add new ${this.item.name} ${this.collection.bottomUp? "after" : "before"}`, className: "mv-add" } ]; if (this.item instanceof Mavo.Group) { this.dragHandle = $.create({ tag: "button", title: "Drag to reorder " + this.item.name, className: "mv-drag-handle" }); buttons.push(this.dragHandle); } else { this.dragHandle = this.item.element; } $.set(this.element, { "mv-rel": this.item.property, contents: buttons }); } $.events(this.element, { mouseenter: evt => { this.item.element.classList.add("mv-highlight"); }, mouseleave: evt => { this.item.element.classList.remove("mv-highlight"); } }); this.dragHandle.addEventListener("keydown", evt => { if (this.item.editing && evt.keyCode >= 37 && evt.keyCode <= 40) { // Arrow keys this.collection.move(this.item, evt.keyCode <= 38? -1 : 1); evt.stopPropagation(); evt.preventDefault(); evt.target.focus(); } }); var selectors = { add: this.buttonSelector("add"), delete: this.buttonSelector("delete"), drag: this.buttonSelector("drag") }; this.element.addEventListener("click", evt => { if (this.item.collection.editing) { if (evt.target.matches(selectors.add)) { var newItem = this.collection.add(null, this.item.index); if (evt[Mavo.superKey]) { newItem.render(this.item.data); } Mavo.scrollIntoViewIfNeeded(newItem.element); return this.collection.editItem(newItem); } else if (evt.target.matches(selectors.delete)) { this.item.collection.delete(item); } else if (evt.target.matches(selectors["drag-handle"])) { evt => evt.target.focus(); } } }); Mavo.data(this.element, "item", this.item); }, add: function() { if (!this.element.parentNode) { if (!Mavo.revocably.add(this.element)) { if (this.item instanceof Mavo.Primitive && !this.item.attribute) { this.element.classList.add("mv-adjacent"); $.after(this.element, this.item.element); } else { this.item.element.appendChild(this.element); } } } if (this.dragHandle == this.item.element) { this.item.element.classList.add("mv-drag-handle"); } }, remove: function() { Mavo.revocably.remove(this.element); if (this.dragHandle == this.item.element) { this.item.element.classList.remove("mv-drag-handle"); } }, reposition: function() { this.element.remove(); this.add(); }, buttonSelector: function(type) { return `.mv-${type}[mv-rel="${this.item.property}"], [mv-rel="${this.item.property}"] > .mv-${type}`; }, proxy: { collection: "item", mavo: "item" } }); })(Bliss, Bliss.$);
JavaScript
0.000001
@@ -3378,24 +3378,270 @@ unction() %7B%0A +%09%09if (this.item instanceof Mavo.Primitive) %7B%0A%09%09%09// This is only needed for lists of primitives, because the item element%0A%09%09%09// does not contain the minibar. In lists of groups, this can be harmful%0A%09%09%09// because it will remove custom positioning%0A%09 %09%09this.eleme @@ -3653,16 +3653,17 @@ move();%0A +%09 %09%09this.a @@ -3668,16 +3668,20 @@ .add();%0A +%09%09%7D%0A %09%7D,%0A%0A%09bu
f9790bc2cb4ec8a3f6dcedd3901d7d281bc0aaee
add source maps to dev and build
webpack.config.js
webpack.config.js
var path = require("path"); var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var isBuild = process.env['NODE_ENV'] === 'production'; var config = { // devtool: '#eval-source-map', context: path.resolve(__dirname), entry: [ // The following is added when `isBuild = falsy` // 'webpack-dev-server/client?http://0.0.0.0:8080', // WebpackDevServer host and port //'webpack/hot/only-dev-server', './style/index.js', './src/index.js' ], output: { path: __dirname + '/dist', publicPath: './dist/', // gh-pages needs this to have a '.' for bundles filename: 'bundle.js' }, plugins: [ new webpack.NoErrorsPlugin(), new ExtractTextPlugin('app.css') ], module: { preLoaders: [ { test: /\.jsx?$/, loader: 'eslint-loader', exclude: /node_modules|gantt-chart.*/ }, ], loaders: [ { test: /\.jsx?$/, loader: 'babel', exclude: [/node_modules/, /puzzle-script/], query: { presets: ['react', 'es2015']} }, { test: /\.json$/, loader: 'json-loader'}, { test: /\.less$/, loader: ExtractTextPlugin.extract('css!less') }, { test: /\.(png|jpg|svg)/, loader: 'file-loader?name=[name].[ext]'}, { test: /\.(woff|woff2|eot|ttf)/, loader: "url-loader?limit=30000&name=[name]-[hash].[ext]" } ] }, resolve: { extensions: ['', '.js', '.jsx', '.json'], alias: { xmlhttprequest: path.join(__dirname, '/src/hacks/xmlhttprequest-filler.js'), fs: path.join(__dirname, '/src/hacks/mermaid-stubs.js'), proxyquire: path.join(__dirname, '/src/hacks/mermaid-stubs.js'), rewire: path.join(__dirname, '/src/hacks/mermaid-stubs.js'), 'mock-browser': path.join(__dirname, '/src/hacks/mermaid-stubs.js') }, }, devServer: { // hot: true // Added when `isBuild = falsy` } }; if (isBuild) { // Remove React warnings and whatnot config.plugins.unshift(new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } })); } else { config.debug = true; config.output.publicPath = '/dist/'; // Dev server needs this to not have a dot. config.devtool = 'inline-source-map'; // config.entry.unshift('webpack/hot/only-dev-server'); config.entry.unshift('webpack-dev-server/client?http://0.0.0.0:8080'); config.devServer.hotComponents = true; } module.exports = config;
JavaScript
0
@@ -228,16 +228,43 @@ e-map',%0A + devtool: 'source-map',%0A cont @@ -2274,48 +2274,8 @@ ot.%0A - config.devtool = 'inline-source-map';%0A //
b767c559626ad31c1e33248aaf3fc2427d061442
fix nav on home page
webpack.config.js
webpack.config.js
var argv = require('yargs').argv var path = require('path') var webpack = require('webpack') var CommonsChunkPlugin = require(__dirname + '/node_modules/webpack/lib/optimize/CommonsChunkPlugin') // Create plugins array var plugins = [ new CommonsChunkPlugin('commons.js') ] // Add Uglify task to plugins array if there is a production flag if (argv.production) { plugins.push(new webpack.optimize.UglifyJsPlugin()) } module.exports = { entry: { generic: __dirname + '/src/js/page-generic', findhelp: __dirname + '/src/js/page-find-help', category: __dirname + '/src/js/page-category', categorybyday: __dirname + '/src/js/page-category-by-day', organisation: __dirname + '/src/js/page-organisation', allserviceproviders: __dirname + '/src/js/page-all-service-providers' }, output: { path: path.join(__dirname, '/_dist/assets/js/'), filename: '[name].bundle.js', chunkFilename: '[id].chunk.js', publicPath: 'assets/js/' }, plugins: plugins, module: { loaders: [ { test: /\.jsx?$/, loader: 'babel', exclude: /(node_modules|bower_components)/ } ] }, standard: { parser: 'babel-eslint' } }
JavaScript
0
@@ -443,24 +443,70 @@ %0A entry: %7B%0A + home: __dirname + '/src/js/page-generic',%0A generic:
3da4fe05f5e552c40d5b6f6cbad555b19764dca9
Fix logarithmic graphs
distributionviewer/core/static/js/app/components/views/chart.js
distributionviewer/core/static/js/app/components/views/chart.js
import React from 'react'; import { Link } from 'react-router'; import axios from 'axios'; import MG from 'metrics-graphics'; import * as metricApi from '../../api/metric-api'; function formatData(item) { var result = []; var data = item.points; for (let i = 0; i < data.length; i++) { result.push({ x: data[i]['refRank'], y: data[i]['c'] * 100, label: data[i]['b'] }); } return result; } function generateChart(name, chart, width, height) { var refLabels = {}; var formattedData = formatData(chart); formattedData.map(chartItem => { refLabels['' + chartItem.x] = chartItem.label; }); /* eslint-disable camelcase */ MG.data_graphic({ target: '.' + name, // Data data: formattedData, x_accessor: 'x', y_accessor: 'y', // General display title: chart.metric, width, height, area: false, missing_is_hidden: true, axes_not_compact: false, // x-axis x_mouseover: data => `x: ${refLabels[data.x]}`, xax_format: d => refLabels[d], xax_count: formattedData.length, // y-axis max_y: 100, y_mouseover: data => ` y: ${data.y.toFixed(4)}%`, }); /* eslint-enable camelcase */ } export class Chart extends React.Component { componentDidMount() { // TODO: We need to do more here about managing isFetching. axios.get(`${metricApi.endpoints.GET_METRIC}${this.props.chartName}/`).then(response => { generateChart(this.props.chartName, response.data, this.props.width, this.props.height); }); } render() { var chart = <div className={this.props.chartName} />; if (this.props.link) { return <Link to={`/metric/${this.props.chartName}/`}>{chart}</Link> } else { return chart; } } } Chart.propTypes = { chartName: React.PropTypes.string.isRequired, height: React.PropTypes.number.isRequired, isDataReady: React.PropTypes.bool.isRequired, item: React.PropTypes.object.isRequired, link: React.PropTypes.bool.isRequired, width: React.PropTypes.number.isRequired, }
JavaScript
0.9998
@@ -334,18 +334,34 @@ efRank'%5D + %7C%7C data%5Bi%5D%5B'b'%5D ,%0A - y: @@ -688,24 +688,29 @@ /%0A -MG.data_graphic( +const graphOptions = %7B%0A @@ -1028,80 +1028,8 @@ %5D%7D%60, -%0A xax_format: d =%3E refLabels%5Bd%5D,%0A xax_count: formattedData.length, %0A%0A @@ -1112,19 +1112,198 @@ (4)%7D%25%60,%0A - %7D +;%0A%0A if (chart.type === 'category') %7B%0A graphOptions%5B'xax_format'%5D = d =%3E refLabels%5Bd%5D;%0A graphOptions%5B'xax_count'%5D = formattedData.length;%0A %7D%0A%0A MG.data_graphic(graphOptions );%0A /*
f2f346573d1383e6d0e645b21514bb16102ecc84
update webpack to read version from package
webpack.config.js
webpack.config.js
const path = require ('path'); const {BannerPlugin} = require ('webpack'); const UglifyJSPlugin = require ('uglifyjs-webpack-plugin'); const LIBRARY_NAME = 'react-xstore'; const LIBRARY_VERSION = '2.0.0'; const LIBRARY_BANNER = `React xStore JavaScript Library v${LIBRARY_VERSION} https://github.com/tamerzorba/react-xstore Copyright ©2017 Tamer Zorba and other contributors Released under the MIT license https://opensource.org/licenses/MIT`; const PATHS = { app: path.join (__dirname, 'src'), build: path.join (__dirname, 'dist'), }; module.exports = { entry: PATHS.app, output: { path: PATHS.build, filename: 'bundle.js', library: LIBRARY_NAME, libraryTarget: 'umd', umdNamedDefine: true, }, plugins: [new BannerPlugin (LIBRARY_BANNER), new UglifyJSPlugin ()], externals: { react: { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react', }, }, module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', query: { presets: ['react', 'es2015'], }, }, ], }, };
JavaScript
0
@@ -127,16 +127,56 @@ lugin'); +%0Aconst lib = require ('./package.json'); %0A%0Aconst @@ -194,22 +194,16 @@ E = -'react-xstore' +lib.name ;%0Aco @@ -228,15 +228,64 @@ N = -'2.0.0' +lib.version;%0Aconst LIBRARY_DESCRIPTION = lib.description ;%0Aco @@ -358,16 +358,39 @@ ERSION%7D%0A +$%7BLIBRARY_DESCRIPTION%7D%0A https://
7f32c19d4fdfe210058061d82b7dc2d41ba8856c
Revert "Remove hidden attribute to get around the "!important" flag"
src/js/edu-benefits/education-wizard.js
src/js/edu-benefits/education-wizard.js
function toggleClass(element, className) { element.classList.toggle(className); } function openState(element) { element.removeAttribute('hidden'); element.setAttribute('data-state', 'open'); } function closeState(element) { element.setAttribute('hidden', true); element.setAttribute('data-state', 'closed'); const selectionElement = element.querySelector('input:checked'); if (selectionElement) { selectionElement.checked = false; } } function closeStateAndCheckChild(alternateQuestion, container) { const selectionElement = alternateQuestion.querySelector('input:checked'); if (!selectionElement) { return closeState(alternateQuestion); } const descendentQuestion = selectionElement.dataset.nextQuestion; if (!descendentQuestion) { return closeState(alternateQuestion); } const descendentElement = container.querySelector(`[data-question=${descendentQuestion}]`); closeStateAndCheckChild(descendentElement, container); return closeState(alternateQuestion); } function reInitWidget() { const container = document.querySelector('.wizard-anchor .wizard-container'); const button = container.querySelector('.wizard-button'); const content = container.querySelector('.wizard-content'); const applyLink = container.querySelector('#apply-now-link'); const applyButton = container.querySelector('#apply-now-button'); const transferWarning = container.querySelector('#transfer-warning'); const nctsWarning = container.querySelector('#ncts-warning'); function resetForm() { const selections = Array.from(container.querySelectorAll('input:checked')); // eslint-disable-next-line no-return-assign, no-param-reassign selections.forEach(selection => selection.checked = false); } applyLink.addEventListener('click', resetForm); content.addEventListener('change', (e) => { const radio = e.target; const otherChoices = radio.dataset.alternate.split(' '); otherChoices.forEach((otherChoice) => { const otherNextQuestion = container.querySelector(`#${otherChoice}`).dataset.nextQuestion; if (otherNextQuestion) { const otherNextQuestionElement = container.querySelector(`[data-question=${otherNextQuestion}]`); closeStateAndCheckChild(otherNextQuestionElement, container); } }); if ((applyButton.dataset.state === 'open') && !radio.dataset.selectedForm) { closeState(applyButton); } if ((transferWarning.dataset.state === 'open') && (radio.id !== 'create-non-transfer')) { closeState(transferWarning); } if ((nctsWarning.dataset.state === 'open') && (radio.id !== 'is-ncts')) { closeState(nctsWarning); } if (radio.dataset.selectedForm) { if (applyButton.dataset.state === 'closed') { openState(applyButton); } if ((transferWarning.dataset.state === 'closed') && (radio.id === 'create-non-transfer')) { openState(transferWarning); } if ((nctsWarning.dataset.state === 'closed') && (radio.id === 'is-ncts')) { openState(nctsWarning); } applyLink.href = `/education/apply-for-education-benefits/application/${radio.dataset.selectedForm}/introduction`; } if (radio.dataset.nextQuestion) { const nextQuestion = radio.dataset.nextQuestion; const nextQuestionElement = container.querySelector(`[data-question=${nextQuestion}]`); openState(nextQuestionElement); } }); button.addEventListener('click', () => { toggleClass(content, 'wizard-content-closed'); toggleClass(button, 'va-button-primary'); }); // Ensure form is reset on page load to prevent unexpected behavior associated with backtracking resetForm(); } function loadImports() { const importContent = document.getElementById('wizard-template').innerHTML; const anchor = document.querySelector('.wizard-anchor'); anchor.innerHTML = importContent; } window.addEventListener('DOMContentLoaded', () => { loadImports(); reInitWidget(); });
JavaScript
0
@@ -121,14 +121,11 @@ ent. -remove +set Attr @@ -138,16 +138,23 @@ 'hidden' +, false );%0A ele
de7e28d7677d666a4bab81c128766d121e08f92d
remove typo
webpack.config.js
webpack.config.js
// Example webpack configuration with asset fingerprinting in production. 'use strict'; const path = require('path'); const fs = require('fs'); const webpack = require('webpack'); const UglifyJSPlugin = require('uglifyjs-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const OfflinePlugin = require('offline-plugin'); const ManifestPlugin = require('webpack-manifest-plugin'); const packageJSON = require('./package.json'); const browserList = packageJSON.babel.presets[0][1].targets.browsers; // set NODE_ENV=production on the environment to add asset fingerprints const currentEnv = process.env.NODE_ENV || 'development'; const isProduction = currentEnv === 'production'; const preScripts = { development: [], production: [] }; const preScriptsEnv = isProduction ? preScripts['production'] : preScripts['development']; const cssLoaders = [ MiniCssExtractPlugin.loader, { loader: 'css-loader', options: { modules: false, sourceMap: true } }, { loader: 'postcss-loader', options: { sourceMap: true, plugins: function() { const plugins = [ require('postcss-import')(), require('postcss-preset-env')({ stage: 1, browsers: browserList, features: { 'custom-properties': { strict: false, warnings: false, preserve: true } } }), require('lost')({ flexbox: 'flex' }), require('rucksack-css')(), require('postcss-browser-reporter')(), require('postcss-reporter')(), ]; if (isProduction) { return plugins.concat([ require('cssnano')({ preset: 'default' }) ]); } else { return plugins; } } } }, { loader: 'sass-loader', options: { sourceMap: true, includePaths: [path.join(__dirname, 'webpack', 'css')] } } ]; const config = { target: 'web', mode: currentEnv, performance: { hints: false }, entry: { 'app': preScriptsEnv.concat(['./webpack/app.js']) }, output: { // Build assets directly in to public/webpack/, let webpack know // that all webpacked assets start with webpack/ // must match config.webpack.output_dir path: path.join(__dirname, '.tmp', 'dist'), publicPath: '/', filename: isProduction ? '[name]-[chunkhash].js' : '[name].js' }, resolve: { modules: [ path.join(__dirname, 'webpack'), path.join(__dirname, 'node_modules') ], extensions: ['.js', '.jsx', '.json'] }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: [ 'babel-loader' ] }, { test: /\.(gif|jpg|png|woff|woff2|eot|ttf|svg|ico)$/, use: [{ loader: 'url-loader', options: { limit: 10000, name: '[name]-[hash].[ext]', outputPath: 'assets/' } }] }, { test: /\.(scss|sass)$/, use: cssLoaders } ] }, plugins: [ new MiniCssExtractPlugin({ filename: isProduction ? '[name]-[contenthash].css' : '[name].css' }) ], optimization: { splitChunks: { cacheGroups: { styles: { name: 'styles', test: /\.css$/, chunks: 'all', enforce: true } } } } }; if (isProduction) { config.plugins.push( new webpack.NoEmitOnErrorsPlugin(), new webpack.DefinePlugin({ 'process.env': {NODE_ENV: JSON.stringify('production')} }), new webpack.optimize.ModuleConcatenationPlugin() ); config.optimization = config.optimization || {}; config.optimization.minimizer = [ new UglifyJSPlugin({ cache: true, parallel: 2, sourceMap: true, uglifyOptions: { compressor: {warnings: false}, mangle: true } }) ]; // Source maps config.devtool = 'source-map'; } else { config.plugins.push( new webpack.NamedModulesPlugin() ); // Source maps config.devtool = 'inline-source-map'; } config.plugins.push( new OfflinePlugin({ cache: { main: [ '*.js', '*.css', '*.png', '*.svg' ], }, excludes: [ '**/.*', '**/*.map', '**/*.gz' ], externals: [ '/' ], name: 'mp-cache', version: '[hash]', responseStrategy: 'cache-first', prefetchRequest: { credentials: 'include' }, ServiceWorker: { events: true, scope: '/', minify: isProduction }, AppCache: null }), new ManifestPlugin({ fileName: 'assets-manifest.json', publicPath: config.output.publicPath, writeToFileEmit: process.env.NODE_ENV !== 'test' }) ) module.exports = config;
JavaScript
0.999999
@@ -1666,33 +1666,32 @@ css-reporter')() -, %0A %5D;%0A%0A
4e0c8a31fde3f3827fb294e9142c2edd70fbe3bf
create component from object & string
src/js/framework/component/component.js
src/js/framework/component/component.js
'use strict'; //TODO re-render containerless components when subscriber fired function Component(name, options) { this._options = options; this._name = name; this._initialize(options); } Component.prototype._initialize = function () { this._subscriber = null; this._renderMethod = this._options.render; this._event = this._options.event; this._methods = this._options.methods; }; Component.prototype._render = function () { //Component's context binding var context = this; var el = null; if (this._event) { this._subscriber = new Subscriber(this._event, function (state) { el = context._renderMethod(state); if (context._methods) context._bindEventToTemplate(context._methods, el, state); if (context._container !== undefined) { var container = document.querySelector(context._container); context._toEmpty(container); container.append(el); } }); this._eventbus.subscriber().register(this._subscriber); return el; } else { var state = {}; el = context._renderMethod(state); if (context._methods) context._bindEventToTemplate(context._methods, el, state); if (context._container !== undefined) { var container = document.querySelector(context._container); context._toEmpty(container); container.append(el); } return el; } }; Component.prototype.fire = function () { this._eventbus.subscriber().fire(this._subscriber); }; Component.prototype.setContainer = function (componentContainer) { this._container = componentContainer; }; Component.prototype.setEventbus = function (eventbus) { this._eventbus = eventbus; return this; }; Component.prototype.setGlobalSetting = function (anatoliaGlobalSetting) { this._globalSetting = anatoliaGlobalSetting; }; Component.prototype._flatten = function (obj) { var toReturn = {}; for (var i in obj) { if (!obj.hasOwnProperty(i)) continue; if ((typeof obj[i]) == 'object') { var flatObject = this._flatten(obj[i]); for (var x in flatObject) { if (!flatObject.hasOwnProperty(x)) continue; toReturn[i + '.' + x] = flatObject[x]; } } else { toReturn[i] = obj[i]; } } return toReturn; }; Component.prototype._toEmpty = function (component) { while (component.firstChild) { component.removeChild(component.firstChild); } }; Component.prototype.render = function () { var el = this._render(); return el; }; Component.prototype.setEvent = function (event) { this._event = event; return this; }; Component.createElement = function (tag, option) { var el = document.createElement(tag); for (var i in option) { if (option.hasOwnProperty(i)) i === "text" ? el.innerText = option[i] : el.setAttribute(i, option[i]); } el.on = Component.on; return el; }; Component.createElementFromObject = function (element) { var tag = null; for (var attribute in element) { if (element.hasOwnProperty(attribute)) { var attributeValue = element[attribute]; if (attribute === "tagName") { tag = document.createElement(attributeValue); } else if (attribute !== "child" && attribute !== "text") { tag.setAttribute(attribute, attributeValue); } else if (attribute === "text") { tag.innerText = attributeValue; } if (attribute === "child") { attributeValue.forEach(function (childElementObject) { var childElement = Component.createElementFromObject(childElementObject); tag.append(childElement); }) } } } return tag; }; Component.on = function (event, fn) { this.addEventListener(event, fn); return this; }; Component.prototype._bindEventToTemplate = function (componentMethods, template, state) { for (var i in componentMethods) { if (componentMethods.hasOwnProperty(i)) { var selector = i; var methods = componentMethods[i]; var elements = template.querySelectorAll(selector); elements.forEach(function (element) { var bundle = { state: state, targetElement: element, parentElement: element.parentElement }; for (var i in methods) { if (methods.hasOwnProperty(i)) { element.addEventListener(i, methods[i].bind(bundle)); } } }); } } };
JavaScript
0
@@ -71,16 +71,109 @@ r fired%0A +// TODO Component.createElement(%22table.table.table-condensed.table-striped %3E thead - tbody%22) %0Afunctio
a871b476b2911c352f86efade81a74a8eab0dc65
add suppress
webpack.config.js
webpack.config.js
const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CopyWebpackPlugin = require("copy-webpack-plugin"); const path = require('path'); module.exports = { entry: { home: './src/js/home.js', privacy: './src/js/privacy.js' }, output: { path: path.join(__dirname, 'public'), filename: 'js/[name].js' }, devServer: { contentBase: path.resolve(__dirname, 'public') }, module: { loaders: [ { loader: 'babel-loader', exclude: /node_modules/, test: /\.js[x]?$/, query: { cacheDirectory: true, presets: ['es2015'] } }, {test: /\.pug$/, loader: 'pug-loader'}, {test: /\.css$/, loader: 'style-loader!css-loader'}, {test: /\.scss$/, loaders: ['style-loader', 'css-loader', 'sass-loader']}, {test: /\.svg$/, loader: 'url-loader?mimetype=image/svg+xml'}, {test: /\.woff$/, loader: 'url-loader?mimetype=application/font-woff'}, {test: /\.woff2$/, loader: 'url-loader?mimetype=application/font-woff'}, {test: /\.eot$/, loader: 'url-loader?mimetype=application/font-woff'}, {test: /\.ttf$/, loader: 'url-loader?mimetype=application/font-woff'} ] }, plugins: [ new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), new CopyWebpackPlugin( [ {from: "src/img/", to: "img/"}, {from: "src/json/", to: "json/"} ] ), new HtmlWebpackPlugin({ filename: 'index.html', template: 'src/index.pug', inject: 'head', chunks: ['home'] }), new HtmlWebpackPlugin({ filename: 'privacy.html', template: 'src/privacy.pug', inject: 'head', chunks: ['home', 'privacy'] }) ] };
JavaScript
0.000095
@@ -1,12 +1,94 @@ +//noinspection NodeJsCodingAssistanceForCoreModules%0Aconst path = require('path');%0A const webpac @@ -230,38 +230,8 @@ n%22); -%0Aconst path = require('path'); %0A%0Amo
d9c28d12d3cfe1e403d9be47dc574c0fe771670e
Copy extension assets from VM
webpack.config.js
webpack.config.js
var path = require('path'); var webpack = require('webpack'); // Plugins var CopyWebpackPlugin = require('copy-webpack-plugin'); var HtmlWebpackPlugin = require('html-webpack-plugin'); // PostCss var autoprefixer = require('autoprefixer'); var postcssVars = require('postcss-simple-vars'); var postcssImport = require('postcss-import'); module.exports = { devServer: { contentBase: path.resolve(__dirname, 'build'), host: '0.0.0.0', port: process.env.PORT || 8601 }, devtool: 'cheap-module-source-map', entry: { lib: ['react', 'react-dom'], gui: './src/index.jsx', blocksonly: './src/examples/blocks-only.jsx', compatibilitytesting: './src/examples/compatibility-testing.jsx', player: './src/examples/player.jsx' }, output: { path: path.resolve(__dirname, 'build'), filename: '[name].js' }, externals: { React: 'react', ReactDOM: 'react-dom' }, module: { rules: [{ test: /\.jsx?$/, loader: 'babel-loader', include: path.resolve(__dirname, 'src') }, { test: /\.css$/, use: [{ loader: 'style-loader' }, { loader: 'css-loader', options: { modules: true, importLoaders: 1, localIdentName: '[name]_[local]_[hash:base64:5]', camelCase: true } }, { loader: 'postcss-loader', options: { ident: 'postcss', plugins: function () { return [ postcssImport, postcssVars, autoprefixer({ browsers: ['last 3 versions', 'Safari >= 8', 'iOS >= 8'] }) ]; } } }] }, { test: /\.(svg|png|wav)$/, loader: 'file-loader' }] }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"' + process.env.NODE_ENV + '"', 'process.env.DEBUG': Boolean(process.env.DEBUG) }), new webpack.optimize.CommonsChunkPlugin({ name: 'lib', filename: 'lib.min.js' }), new HtmlWebpackPlugin({ chunks: ['lib', 'gui'], template: 'src/index.ejs', title: 'Scratch 3.0 GUI' }), new HtmlWebpackPlugin({ chunks: ['lib', 'blocksonly'], template: 'src/index.ejs', filename: 'blocks-only.html', title: 'Scratch 3.0 GUI: Blocks Only Example' }), new HtmlWebpackPlugin({ chunks: ['lib', 'compatibilitytesting'], template: 'src/index.ejs', filename: 'compatibility-testing.html', title: 'Scratch 3.0 GUI: Compatibility Testing' }), new HtmlWebpackPlugin({ chunks: ['lib', 'player'], template: 'src/index.ejs', filename: 'player.html', title: 'Scratch 3.0 GUI: Player Example' }), new CopyWebpackPlugin([{ from: 'node_modules/scratch-blocks/media', to: 'static/blocks-media' }]), new CopyWebpackPlugin([{ from: 'extensions/**', to: 'static', context: 'src/examples' }]), new CopyWebpackPlugin([{ from: 'extension-worker.{js,js.map}', context: 'node_modules/scratch-vm/dist/web' }]) ].concat(process.env.NODE_ENV === 'production' ? [ new webpack.optimize.UglifyJsPlugin({ include: /\.min\.js$/, minimize: true }) ] : []) };
JavaScript
0
@@ -3469,32 +3469,182 @@ ebpackPlugin(%5B%7B%0A + from: 'node_modules/scratch-vm/dist/node/assets',%0A to: 'static/extension-assets'%0A %7D%5D),%0A new CopyWebpackPlugin(%5B%7B%0A from
2d6798ed15488edeb0487e77977d24249eb74072
Fix externalRequest
webpack.config.js
webpack.config.js
const webpack = require('webpack'); function criWrapper(_, options, callback) { window.criRequest(options, callback); } module.exports = { resolve: { alias: { 'ws': './websocket-wrapper.js' } }, externals: [ { './external-request.js': `(${criWrapper})` } ], module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.json$/, loader: 'json' } ] }, plugins: [ new webpack.optimize.UglifyJsPlugin({ mangle: true, compress: { warnings: false }, output: { comments: false } }) ], entry: './index.js', output: { libraryTarget: process.env.TARGET || 'commonjs2', library: 'CDP', filename: 'chrome-remote-interface.js' } };
JavaScript
0.000003
@@ -295,16 +295,20 @@ t.js': %60 +var ($%7BcriWr
e3226236a23a74ec4f0d46d49fcf8c57b602dea7
Add revoke action
chrome-extension/options.js
chrome-extension/options.js
document.addEventListener("DOMContentLoaded", () => { const defaultUri = "http://localhost:3000/api/v1" const $ = document.querySelector.bind(document) // Service URL setting chrome.storage.sync.get("service_uri", ({service_uri}) => { if (service_uri === undefined) { chrome.storage.sync.set({service_uri: defaultUri}, () => { $("input[name=uri]").value = defaultUri }) } else { $("input[name=uri]").value = service_uri } }) $("button[name=reset]").addEventListener("click", (eve) => { chrome.storage.sync.set({service_uri: defaultUri}, () => { $("input[name=uri]").value = defaultUri $("button[name=update]").disabled = true $("button[name=token]").disabled = false }) }, false) $("button[name=update]").addEventListener("click", (eve) => { chrome.storage.sync.set({service_uri: $("input[name=uri]").value}, () => { $("button[name=update]").disabled = true $("button[name=token]").disabled = false }) }, false) $("input[name=uri]").addEventListener("input", (eve) => { $("button[name=update]").disabled = false $("button[name=token]").disabled = true }, false) // Token setting chrome.storage.sync.get("token", ({token}) => { if (token === undefined) { if (location.search) { const queries = location.search.replace(/^\?/, "").split("&") for (const query of queries) { if (query.search(/^token=/) === 0) { const token = query.split("=")[1] if (!token) { continue } chrome.storage.sync.set({token: token}, () => { $("input[name=token]").value = token }) return } } } $("button[name=token]").innerText = "Get Token" } else { $("input[name=token]").value = token } }) $("button[name=token]").addEventListener("click", (eve) => { switch (eve.target.innerText) { case "Revoke Token": chrome.storage.sync.remove("token", () => { $("input[name=token]").value = "" eve.target.innerText = "Get Token" }) break case "Get Token": const callbackUrl = chrome.extension.getURL("options.html") chrome.storage.sync.get("service_uri", ({service_uri}) => { chrome.tabs.getCurrent(cur => { chrome.tabs.update(cur.id, {url: `${service_uri}/auth?callback=${callbackUrl}`}) }) }) break default: throw new Error() } }, false) }, false)
JavaScript
0.000004
@@ -2313,32 +2313,272 @@ %0A + chrome.storage.sync.get(%5B%22service_uri%22, %22token%22%5D, (%7Bservice_uri, token%7D) =%3E %7B%0A fetch(%60$%7Bservice_uri%7D/auth/token/$%7Btoken%7D%60, %7B%0A method: %22DELETE%22%0A %7D)%0A .then(() =%3E chrome.storage. @@ -2598,32 +2598,36 @@ token%22, () =%3E %7B%0A + @@ -2664,16 +2664,20 @@ ue = %22%22%0A + @@ -2715,32 +2715,179 @@ t = %22Get Token%22%0A + %7D))%0A .catch((e) =%3E %7B%0A alert(%60Failed to send revoke request.%60)%0A %7D)%0A
660cfaeeea175d1f829ca1d6eb0dab26f492fc81
Fix JSON webpack loader
webpack.config.js
webpack.config.js
'use strict'; const webpack = require('webpack'); function criWrapper(_, options, callback) { window.criRequest(options, callback); } const webpackConfig = { resolve: { alias: { 'ws': './websocket-wrapper.js' } }, externals: [ { './external-request.js': `var (${criWrapper})` } ], module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.json$/, loader: 'json' } ] }, plugins: [ ], entry: './index.js', output: { libraryTarget: process.env.TARGET || 'commonjs2', library: 'CDP', filename: 'chrome-remote-interface.js' } }; if (process.env.DEBUG !== 'true') { webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({ mangle: true, compress: { warnings: false }, output: { comments: false } })); } module.exports = webpackConfig;
JavaScript
0.000504
@@ -602,16 +602,23 @@ r: 'json +-loader '%0A
51d06c57bf37389859033e6641a6b6078402dffe
Add an alias for fonts in webpack config
webpack.config.js
webpack.config.js
const path = require('path'); module.exports = { entry: { app: path.resolve(__dirname, 'app/Resources/assets/js/app.js') }, output: { path: path.resolve(__dirname, 'web/builds'), filename: 'bundle.js', publicPath: '/builds/' }, module: { rules: [ { test: /\.js$/, exclude: /(node_modules)/, use: 'babel-loader' }, { test: /\.scss$/, use: [ { loader: "style-loader" }, { loader: "css-loader" }, { loader: "sass-loader" } ] } ] } };
JavaScript
0.000001
@@ -688,21 +688,126 @@ %7D%0A %5D%0A + %7D,%0A resolve: %7B%0A alias: %7B%0A fonts: path.resolve(__dirname, 'web/fonts')%0A %7D%0A %7D%0A%7D;%0A
3ca46fe71fb79d2f68390b27f72d7fb3270177a0
fix undefined plugin in production
webpack.config.js
webpack.config.js
const fs = require('fs'); const path = require('path'); const webpack = require('webpack'); const OfflinePlugin = require('offline-plugin'); const production = process.env.NODE_ENV === 'prod' || process.env.NODE_ENV === 'production'; const dest = process.env.WEBPACK_DEST || 'modern-browsers'; const modulesList = (() => { try { return fs.readdirSync(path.resolve('src/modules')); } catch (e) { return []; } })(); module.exports = { debug: !production, devtool: production ? undefined : 'inline-source-map', entry: { [dest]: [ dest !== 'modern-browsers' && 'babel-regenerator-runtime', !production && 'webpack-hot-middleware/client', !production && 'react-hot-loader/patch', './src/index.browser.js', ].filter(Boolean) }, output: { path: path.resolve('public'), publicPath: '/', filename: '[name].js', pathinfo: !production, }, module: { // Disable handling of unknown requires unknownContextRegExp: /$^/, unknownContextCritical: true, // Disable handling of requires with a single expression exprContextRegExp: /$^/, exprContextCritical: true, // Disable handling of expression in require wrappedContextRegExp: /$^/, wrappedContextCritical: true, wrappedContextRecursive: false, preLoaders: [ // {test: /\.jsx?$/, loader: 'eslint', exclude: /node_modules/}, { test: /\.jsx?$/, loader: 'source-map', exclude: /react-hot-loader/ } ], loaders: [ { test: /\.jsx?$/, exclude: /(node_modules)|\.server\.jsx?$/, loader: 'babel', include: path.resolve('src'), query: { presets: ( dest === 'modern-browsers' ? ['modern-browsers/webpack2-uglifyjs', 'react', 'modern-browsers/stage1'] : ['es2015', 'react', 'stage-1'] ), plugins: [ !production && 'typecheck', !production && 'react-hot-loader/babel', ['defines', { PRODUCTION: production, BROWSER: true, SERVER: false }], 'remove-dead-code', ['discard-module-references', { targets: [], unusedWhitelist: ['react'] }], 'react-require', ], }, }, ], }, resolveLoader: { modulesDirectories: ['node_modules'], }, resolve: { alias: { 'socket.io': 'socket.io-client' }, modules: ['browser/node_modules', 'node_modules'], extensions: ['', '.browser.js', '.js', '.browser.jsx', '.jsx', '.json'], mainFields: [ dest === 'modern-browsers' && !production && 'webpack:main-modern-browsers-dev', dest === 'modern-browsers' && 'webpack:main-modern-browsers', !production && 'webpack:main-dev', 'webpack:main', !production && 'browser-dev', 'browser', !production && 'main-dev', 'webpack', 'main', ].filter(Boolean), packageAlias: ['webpack', 'browser'], }, node: { util: 'empty' }, // fix nightingale... plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: dest, filename: `${dest}.js`, chunks: [dest], // minChunks: modulesList.length === 1 ? 1 : 2, }), new webpack.LoaderOptionsPlugin({ debug: !production, minimize: !production, }), new webpack.DefinePlugin({ BROWSER: true, SERVER: false, NODE: false, PRODUCTION: production, MODERN_BROWSERS: dest === 'modern-browsers', 'process.env': { 'NODE_ENV': JSON.stringify(production ? 'production' : process.env.NODE_ENV) } }), !production && new webpack.HotModuleReplacementPlugin(), !production && new webpack.NoErrorsPlugin(), production && new webpack.optimize.UglifyJsPlugin({ mangle: false, compress: { warnings: false, 'drop_debugger': !!production, unused: false, comparisons: true, sequences: false }, output: { beautify: !production && { 'max-line-len': 200, bracketize: true, }, comments: !production && 'all', }, sourceMap: !production }), // TODO https://github.com/NekR/offline-plugin ].filter(Boolean), };
JavaScript
0
@@ -2550,24 +2550,40 @@ %5D +.filter(Boolean) ,%0A
c4b4a4a3c9d84454d77cb096a24ca793fff30f4d
remove obsolete DedupePlugin
webpack.config.js
webpack.config.js
const path = require('path'); const DefinePlugin = require('webpack').DefinePlugin; const ProgressPlugin = require('webpack').ProgressPlugin; const HtmlPlugin = require('html-webpack-plugin'); const nodeEnv = process.env.NODE_ENV || 'development'; // Minification options used in production mode. const htmlMinifierOptions = { removeComments: true, collapseWhitespace: true, collapseBooleanAttributes: true, removeTagWhitespace: true, removeAttributeQuotes: true, removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true, removeOptionalTags: true }; const plugins = [ new DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(nodeEnv) } }), new HtmlPlugin({ chunks: [ 'app' ], inject: false, template: './index.html', minify: nodeEnv === 'production' ? htmlMinifierOptions : false, loadingScreen: () => require('./tasks/utils/renderLoadingScreen')() }), new ProgressPlugin() ]; if (nodeEnv === 'production') { const LoaderOptionsPlugin = require('webpack').LoaderOptionsPlugin; const DedupePlugin = require('webpack').optimize.DedupePlugin; const OccurrenceOrderPlugin = require('webpack').optimize.OccurrenceOrderPlugin; const UglifyJsPlugin = require('webpack').optimize.UglifyJsPlugin; plugins.push( new OccurrenceOrderPlugin(), new DedupePlugin(), new LoaderOptionsPlugin({ minimize: true, debug: false }), new UglifyJsPlugin({ // Yeah… Enables some riskier minification that doesn't work in IE8. // But üWave doesn't work in IE8 _anyway_, so we don't care. compress: { screw_ie8: true, pure_getters: true, unsafe: true }, output: { screw_ie8: true }, // Rename top-level (global scope) variables to shorter names too. // There's no other code that depends on those variables to be // available, so it doesn't really matter what they're called! mangle: { toplevel: true } }) ); } module.exports = { context: path.join(__dirname, 'src'), entry: { app: './app.js' }, output: { publicPath: '/', path: path.join(__dirname, 'public'), filename: '[name].js' }, plugins, module: { rules: [ { test: /\.yaml$/, use: [ 'json-loader', 'yaml-loader' ] }, { test: /\.json$/, use: [ 'json-loader' ] }, { test: /\.js$/, exclude: /node_modules/, use: [ 'babel-loader' ] } ] } };
JavaScript
0.000012
@@ -1082,73 +1082,8 @@ in;%0A - const DedupePlugin = require('webpack').optimize.DedupePlugin;%0A co @@ -1284,32 +1284,8 @@ (),%0A - new DedupePlugin(),%0A
e965f41adc81cf97415448642cdcda6bbe08690f
fix staging build
webpack.config.js
webpack.config.js
const path = require('path'); const webpack = require('webpack'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ProgressBarPlugin = require('progress-bar-webpack-plugin'); const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin'); const RobotstxtPlugin = require('robotstxt-webpack-plugin').default; const PORT = process.env.PORT || 3000; const HOST = process.env.HOST || 'localhost'; const NODE_ENV = process.env.NODE_ENV || 'production'; const isProduction = (NODE_ENV === 'production'); const isDevelopment = (NODE_ENV === 'development'); const config = { entry: isDevelopment ? [ 'babel-polyfill', 'react-hot-loader/patch', // activate HMR for React `webpack-hot-middleware/client?path=http://${HOST}:${PORT}/__webpack_hmr`, // bundle the client for webpack-hot-middleware and connect to the provided endpoint './src/client.jsx', ] : [ 'babel-polyfill', './src/client.jsx', ], resolve: { extensions: ['.js', '.jsx', '.json'], }, output: { path: path.join(__dirname, 'dist/public/'), filename: isDevelopment ? 'main.js' : 'assets/scripts/[name].[chunkhash].js', }, module: { rules: [ { test: /\.css$/, use: ['css-hot-loader'].concat( ExtractTextPlugin.extract({ fallback: 'style-loader', use: [{ loader: 'css-loader', options: {minimize: true}, }], }), ), }, { test: /\.jsx?$/, use: ['babel-loader'], include: path.join(__dirname, 'src'), }, ], }, plugins: [ new ProgressBarPlugin(), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(NODE_ENV), }), isDevelopment ? new webpack.HotModuleReplacementPlugin() // enable HMR globally : null, isDevelopment ? new webpack.NamedModulesPlugin() // prints more readable module names in the browser console on HMR updates : null, isDevelopment ? new webpack.NoEmitOnErrorsPlugin() // do not emit compiled assets that include errors : null, new ExtractTextPlugin({ filename: isDevelopment ? 'assets/styles/main.css' : 'assets/styles/[name].[chunkhash].css', }), isDevelopment ? null : new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: module => /node_modules/.test(module.resource), }), isDevelopment ? null : new webpack.optimize.CommonsChunkPlugin({name: 'manifest'}), isDevelopment ? null : new webpack.optimize.UglifyJsPlugin(), new HtmlWebpackPlugin({ template: path.resolve(__dirname, 'src/index.html'), minify: isProduction ? {collapseWhitespace: true, collapseInlineTagWhitespace: true} : false, alwaysWriteToDisk: true, }), new HtmlWebpackHarddiskPlugin(), new CopyWebpackPlugin([ { context: 'src/assets/media', from: '**/*', to: 'assets/media', }, ]), new RobotstxtPlugin({ policy: [ isProduction ? {userAgent: '*', allow: '/'} : {userAgent: '*', disallow: '/'}, ], }), ].filter(Boolean), devtool: isProduction ? 'none' : 'cheap-module-eval-source-map', performance: { maxAssetSize: 500000, }, }; module.exports = config;
JavaScript
0.000001
@@ -639,16 +639,42 @@ duction' + %7C%7C NODE_ENV === 'staging' );%0Aconst
8a47ef7fa497ec280b3a47959e8c04d14339c9a3
fix env reading order
webpack.config.js
webpack.config.js
const dotenv = require('dotenv'); const Encore = require('@symfony/webpack-encore'); const StyleLintPlugin = require('stylelint-webpack-plugin'); dotenv.config({ path : __dirname + '/.env.local' }); dotenv.config({ path : __dirname + '/.env' }); // Manually configure the runtime environment if not already configured yet by the "encore" command. // It's useful when you use tools that rely on webpack.config.js file. if (!Encore.isRuntimeEnvironmentConfigured()) { Encore.configureRuntimeEnvironment(process.env.NODE_ENV || process.env.APP_ENV || 'dev'); } Encore // directory where compiled assets will be stored .setOutputPath('public/build/') // public path used by the web server to access the output path .setPublicPath(process.env.ASSETS_ORIGIN + '/build/') // only needed for CDN's or sub-directory deploy .setManifestKeyPrefix('build/') /* * ENTRY CONFIG * * Add 1 entry for each "page" of your app * (including one that's included on every page - e.g. "app") * * Each entry will result in one JavaScript file (e.g. app.js) * and one CSS file (e.g. app.css) if your JavaScript imports CSS. */ .addEntry('athorrent', './assets/js/athorrent.js') .addEntry('files', './assets/js/files.js') .addEntry('media', './assets/js/media.js') .addEntry('search', './assets/js/search.js') .addEntry('sharings', './assets/js/sharings.js') .addEntry('torrents', './assets/js/torrents.js') .addEntry('users', './assets/js/users.js') .addStyleEntry('administration', './assets/css/administration.scss') .addStyleEntry('cache', './assets/css/cache.scss') .addStyleEntry('home', './assets/css/home.scss') .addStyleEntry('main', './assets/css/main.scss') .copyFiles({ from: './assets/images', pattern: /\.(ico|png)$/ }) // When enabled, Webpack "splits" your files into smaller pieces for greater optimization. .splitEntryChunks() // will require an extra script tag for runtime.js // but, you probably want this, unless you're building a single-page app .enableSingleRuntimeChunk() /* * FEATURE CONFIG * * Enable & configure other features below. For a full * list of features, see: * https://symfony.com/doc/current/frontend.html#adding-more-features */ .cleanupOutputBeforeBuild() .enableBuildNotifications() .enableSourceMaps(!Encore.isProduction()) // enables hashed filenames (e.g. app.abc123.css) .enableVersioning(Encore.isProduction()) // enables Sass/SCSS support .enableSassLoader() .enablePostCssLoader() .addPlugin(new StyleLintPlugin({ context: './assets/css' })) // uncomment if you're having problems with a jQuery plugin .autoProvidejQuery() ; module.exports = Encore.getWebpackConfig();
JavaScript
0.000052
@@ -185,14 +185,8 @@ .env -.local ' %7D) @@ -224,24 +224,30 @@ ame + '/.env +.local ' %7D);%0A%0A// Ma
9487c72924169984cd84b6105b48303040347365
Change webpack paths
webpack.config.js
webpack.config.js
var path = require("path"); var webpack = require("webpack"); var ExtractTextPlugin = require("extract-text-webpack-plugin"); module.exports = { cache: true, entry: { webvowl: "./src/webvowl/js/entry.js", "webvowl.app": "./src/app/js/entry.js" }, output: { path: path.join(__dirname, "deploy/js/"), publicPath: "js/", filename: "[name].js", chunkFilename: "[chunkhash].js", libraryTarget: "assign", library: "[name]" }, module: { loaders: [ {test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader")}, {test: /\.json$/, loader: "file"} ] }, plugins: [ new ExtractTextPlugin("../css/[name].css"), new webpack.ProvidePlugin({ d3: "d3" }) ], externals: { "d3": "d3" } };
JavaScript
0.000001
@@ -296,19 +296,16 @@ %22deploy/ -js/ %22),%0A%09%09pu @@ -315,19 +315,16 @@ cPath: %22 -js/ %22,%0A%09%09fil @@ -331,16 +331,19 @@ ename: %22 +js/ %5Bname%5D.j @@ -364,16 +364,19 @@ ename: %22 +js/ %5Bchunkha @@ -579,16 +579,46 @@ r: %22file +?name=data/%5Bname%5D.%5Bext%5D?%5Bhash%5D %22%7D%0A%09%09%5D%0A%09 @@ -661,11 +661,8 @@ in(%22 -../ css/
cf4a73ea1ee53c55e78ed8c3ced18a6817ecc13f
update webpack config
webpack.config.js
webpack.config.js
var path = require('path'); var webpack = require('webpack'); var devFlagPlugin = new webpack.DefinePlugin({ __DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'false')) }); module.exports = { devtool: 'eval', entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './src/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), devFlagPlugin ], module: { loaders: [{ test: /\.js$/, loaders: ['react-hot', 'babel'], include: path.join(__dirname, 'src') }] } };
JavaScript
0.000001
@@ -51,24 +51,88 @@ 'webpack');%0A +var ExtractTextPlugin = require('extract-text-webpack-plugin');%0A var devFlagP @@ -622,16 +622,54 @@ agPlugin +,%0A new ExtractTextPlugin('app.css') %0A %5D,%0A @@ -692,18 +692,27 @@ aders: %5B -%7B %0A + %7B%0A te @@ -724,12 +724,16 @@ %5C.js +x? $/,%0A + @@ -767,16 +767,18 @@ abel'%5D,%0A + in @@ -816,17 +816,176 @@ c')%0A -%7D + %7D,%0A %7B test: /%5C.css$/, loader: ExtractTextPlugin.extract('css-loader?module!cssnext-loader') %7D%0A %5D%0A %7D,%0A resolve: %7B%0A extensions: %5B'', '.js', '.json' %5D%0A %7D%0A%7D;
cee2275e86c77c87a40ffdd022f3991af6cf6a03
remove 's'
web/js/blog.js
web/js/blog.js
$(".reportComment").click(function(event){ event.preventDefault(); }); function closeDiv(){ $(function(){ $("#reportSuccess").css("display", "none"); }) } function fadeInSuccess(){ $(function(){ $("#success").fadeIn(2000); }) } function inputTitleValidation(){ var input = $("#blogbundle_post_name"); var formGroup = $("#titleGroup"); input.on('keyup keypress blur change', function() { var inputLength = input.val().length; if(inputLength < 5){ formGroup.addClass("has-error") formGroup.removeClass("has-success") } else{ formGroup.addClass("has-success") formGroup.removeClass("has-error") } }); } function setReport(id){ var path = Routing.generate('set_report'); var reportData = {"Comment_ID": id}; $.ajax({ type: "POST", data: reportData, url: path, success: function(data){ if(data){ $("#reportSuccess").fadeIn(1000); } }, error: function(xhr, status, error) { console.log(error); } }); } function deleteComment(id, postId){ var path = Routing.generate('admin_comment_delete'); var commentData = {"Comment_ID": id}; $.ajax({ type: "POST", data: commentData, url: path, success: function(data){ if(data){ $("#deleteSuccess").fadeIn(1000); $("." + id).remove(); getCommentNumber(postId); getReportCommentNumber(postId); } }, error: function(xhr, status, error) { console.log(error); } }); } function getCommentNumber(postId){ var path = Routing.generate('admin_get_comments_post'); var commentData = {"Post_ID": postId}; $.ajax({ type: "GET", data: commentData, url: path, success: function(data){ $(".commentNumber").text(data); if(data > 1){ $(".pluralCommentNumber").text('s'); } else{ $(".pluralCommentNumber").removeClass('pluralCommentNumber'); } }, error: function(xhr, status, error) { console.log(error); } }); } function getReportCommentNumber(postId){ var path = Routing.generate('admin_get_report_comments_post'); var commentData = {"Post_ID": postId}; $.ajax({ type: "GET", data: commentData, url: path, success: function(data){ $(".reportCommentNumber").text(data); if(data > 1){ $(".pluralReportCommentNumber").text('s'); } else{ $(".pluralReportCommentNumber").removeClass('pluralReportCommentNumber'); } }, error: function(xhr, status, error) { console.log(error); } }); }
JavaScript
0.998673
@@ -2194,35 +2194,9 @@ move -Class('pluralCommentNumber' +( );%0A @@ -2807,41 +2807,9 @@ move -Class('pluralReportCommentNumber' +( );%0A
a8dea3df12e995bd2e394514fd6bc4f0518c9bd4
Format source.
webpack.config.js
webpack.config.js
const ExtractTextPlugin = require( 'extract-text-webpack-plugin' ), HtmlWebpackPlugin = require('html-webpack-plugin'); const webpack = require( 'webpack' ), plugins = [ // omit import xxx new webpack.ProvidePlugin({ React : 'react', ReactDOM : 'react-dom', Notify : 'notify', jQuery : 'jquery', }), // chunk files new webpack.optimize.CommonsChunkPlugin({ names : [ 'vendors' ], minChunks : Infinity }), // defined environment variable new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify( 'production' ) // or development }), // extract css files new ExtractTextPlugin( '[name].css' ), // minify html files new HtmlWebpackPlugin({ filename: 'index.html', template: 'src/index.html', minify: { collapseWhitespace: true, }, }), ], // conditions environment isProduction = function () { return process.env.NODE_ENV === 'production'; }, // only when environment variable is 'development' call develop = ( function () { const OpenBrowserPlugin = require('open-browser-webpack-plugin'); if ( !isProduction() ) { plugins.push( new webpack.HotModuleReplacementPlugin(), new OpenBrowserPlugin({ url: 'http://localhost:8080' }) ); } })(), // only when environment variable is 'production' call deploy = ( function () { const CopyWebpackPlugin = require( 'copy-webpack-plugin' ), CleanWebpackPlugin = require( 'clean-webpack-plugin' ); // environment verify if ( isProduction() ) { // delete publish folder plugins.push( new CleanWebpackPlugin([ 'publish' ], { verbose: true, dry : false, }) ); // copy files plugins.push( new CopyWebpackPlugin([ { context: 'src/assets/images/', from : "*" , to : './assets/images' }, ]) ); // call uglifyjs plugin plugins.push( new webpack.optimize.UglifyJsPlugin({ compress: { sequences: true, dead_code: true, conditionals: true, booleans: true, unused: true, if_return: true, join_vars: true, drop_console: true }, mangle: { except: [ '$', 'exports', 'require' ] }, output: { comments: false } }) ); } })(), bundle = ( function () { const files = [ './src/index.jsx' ]; if ( !isProduction() ) { files.push( 'webpack/hot/dev-server', 'webpack-dev-server/client?http://localhost:8080' ); } return files; }), // webpack config config = { entry: { vendors : [ // react './node_modules/react/dist/react.min.js', './node_modules/react-dom/dist/react-dom.min.js', // vendors 'jquery', 'pangu', 'velocity', 'wavess', 'notify', // component 'textfield', 'fab', 'button', 'selectfield', 'switch', 'tabs', 'sidebar', 'list', 'dialog', 'tooltip', 'waves' ], bundle: bundle(), }, output: { path : isProduction() ? './publish/' : './', filename : '[name].js' }, devServer: { contentBase: './src', port: 8080, historyApiFallback: true, hot: true, inline: true, progress: true, }, plugins: plugins, module: { loaders: [ { test: /\.js[x]?$/, exclude: /node_modules/, loader: 'babel', query: { presets: [ 'es2015', 'stage-0', 'react' ] } }, // css in js //{ test: /\.css$/, loader: 'style!css!postcss' }, // extract css files { test: /\.css$/, loader: ExtractTextPlugin.extract( "style", "css!postcss" ) }, // image in js { test: /\.(png|jpg|gif)$/, loader: 'url?limit=12288' }, // expose $ { test : require.resolve( './src/vender/jquery-2.1.1.min.js' ), loader: 'expose?jQuery!expose?$' }, ] }, postcss: function () { return [ require( 'import-postcss' )(), require( 'postcss-cssnext' )() ] }, resolve: { alias : { jquery : __dirname + '/src/vender/jquery-2.1.1.min.js', pangu : __dirname + '/src/vender/pangu.min.js', velocity : __dirname + '/src/vender/velocity.min.js', wavess : __dirname + '/src/vender/waves/waves.js', notify : __dirname + '/src/vender/notify/notify.js', textfield : __dirname + '/src/vender/mduikit/textfield.jsx', fab : __dirname + '/src/vender/mduikit/fab.jsx', button : __dirname + '/src/vender/mduikit/button.jsx', selectfield: __dirname + '/src/vender/mduikit/selectfield.jsx', switch : __dirname + '/src/vender/mduikit/switch.jsx', tabs : __dirname + '/src/vender/mduikit/tabs.jsx', sidebar : __dirname + '/src/vender/mduikit/sidebar.jsx', list : __dirname + '/src/vender/mduikit/list.jsx', dialog : __dirname + '/src/vender/mduikit/dialog.jsx', tooltip : __dirname + '/src/vender/mduikit/tooltip.jsx', waves : __dirname + '/src/vender/mduikit/waves.js', index : __dirname + '/src/index.jsx', entry : __dirname + '/src/module/entry.jsx', search : __dirname + '/src/module/search.jsx', controlbar : __dirname + '/src/module/controlbar.jsx', } } }; module.exports = config;
JavaScript
0
@@ -95,16 +95,17 @@ require( + 'html-we @@ -121,16 +121,16 @@ gin' -);%0Aconst + )%0A web @@ -168,24 +168,26 @@ ack' ),%0A + plugins @@ -192,18 +192,16 @@ - = %5B%0A%0A @@ -2070,11 +2070,11 @@ m : -%22*%22 +'*' , t @@ -4396,18 +4396,18 @@ ct( -%22 +' style -%22, %22 +', ' css! @@ -4417,9 +4417,9 @@ tcss -%22 +' ) %7D
776e4fa8a5d32b88f283d769c916fa3932fe4029
Fix typo.
javascript/food-chain/food-chain.js
javascript/food-chain/food-chain.js
/*eslint no-const-assign: "error"*/ /*eslint-env es6*/ //******************************************************************* // An object oriented implementation //******************************************************************* //******************************************************************* // Superclass Verse var Verse = function(animal, exclamation, parent) { this.animal = animal; this.exclamation = exclamation || ''; this.parent = typeof parent === 'function' ? new parent() : parent; } Verse.prototype.firstLine = function() { return 'I know an old lady who swallowed a ' + this.animal + '.\n'; } Verse.prototype.secondLine = function() { return this.exclamation ? this.exclamation + '\n' : ''; } Verse.prototype.recursiveLine = function() { if (this.parent) { return 'She swallowed the ' + this.animal + ' to catch the ' + this.parent.animal + '.\n' + this.parent.recursiveLine(); } else { return ''; } } Verse.prototype.lastLine = function() { return 'I don\'t know why she swallowed the fly. Perhaps she\'ll die.\n'; } Verse.prototype.toString = function() { return this.firstLine() + this.secondLine() + this.recursiveLine() + this.lastLine(); } //******************************************************************* // Class FlyVerse FlyVerse.prototype = new Verse(); function FlyVerse() { Verse.call(this, 'fly'); } //******************************************************************* // Class SpiderVerse SpiderVerse.prototype = new Verse(); function SpiderVerse() { Verse.call(this, 'spider', 'It wriggled and jiggled and tickled inside her.', FlyVerse); } //******************************************************************* // Class BirdVerse BirdVerse.prototype = new Verse(); function BirdVerse() { Verse.call(this, 'bird', 'How absurd to swallow a bird!', SpiderVerse); } BirdVerse.prototype.recursiveLine = function() { return 'She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n' + this.parent.recursiveLine(); } //******************************************************************* // Class CatVerse CatVerse.prototype = new Verse(); function CatVerse() { Verse.call(this, 'cat', 'Imagine that, to swallow a cat!', BirdVerse); } //******************************************************************* // Class DogVerse DogVerse.prototype = new Verse(); function DogVerse() { Verse.call(this, 'dog', 'What a hog, to swallow a dog!', CatVerse); } //******************************************************************* // Class GoatVerse GoatVerse.prototype = new Verse(); function GoatVerse() { Verse.call(this, 'goat', 'Just opened her throat and swallowed a goat!', DogVerse); } //******************************************************************* // Class CowVerse CowVerse.prototype = new Verse(); function CowVerse() { Verse.call(this, 'cow', 'I don\'t know how she swallowed a cow!', GoatVerse); } //******************************************************************* // Class HorseVerse HorseVerse.prototype = new Verse(); function HorseVerse() { } HorseVerse.prototype.toString = function() { return 'I know an old lady who swallowed a horse.\n' + 'She\'s dead, of course!\n'; } //******************************************************************* // Class FoodChain const VERSES = [ FlyVerse, SpiderVerse, BirdVerse, CatVerse, DogVerse, GoatVerse, CowVerse, HorseVerse ] function sequence(low, high) { return Array.apply(0, Array(high - low + 1)).map(function(x, y) { return low + y; }); } module.exports = function FoodChain() { return { verse: function(num) { return (new VERSES[num-1]()).toString(); }, verses(first, last) { return sequence(first, last).reduce(function(song, num) { song.push(this.verse(num)); return song; }.bind(this), []).join('\n') + '\n'; } } };
JavaScript
0.001604
@@ -3727,16 +3727,26 @@ verses +: function (first,
3d6e462df179792e4934dd1270999e5bb182412f
Update nutrition dv
app/views/dining/DiningNutrition.js
app/views/dining/DiningNutrition.js
import React from 'react'; import { View, Text, ScrollView, } from 'react-native'; import { openURL, } from '../../util/general'; import Touchable from '../common/Touchable'; const logger = require('../../util/logger'); const css = require('../../styles/css'); const DiningNutrition = ({ navigation }) => { const { params } = navigation.state; const { menuItem, disclaimer, disclaimerEmail } = params; logger.ga('View Loaded: Dining Nutrition: ' + menuItem.name ); return ( <ScrollView style={css.scroll_default} contentContainerStyle={css.main_full}> <View style={css.ddn_market_name}> {menuItem.station ? (<Text style={css.ddn_market_name_text}>{menuItem.station}</Text>) : null } <Text style={css.ddn_menu_item_name}>{menuItem.name}</Text> </View> <View style={css.ddn_container}> <Text style={css.ddn_header}>Nutrition Facts</Text> <Text style={css.ddn_servingsize}>Serving Size {menuItem.nutrition.servingSize}</Text> <View style={css.ddn_topborder1}><Text style={css.ddn_amountperserving}>Amount Per Serving</Text></View> <View style={css.ddn_row_main}><Text style={css.ddn_font}><Text style={css.bold}>Calories</Text> {menuItem.nutrition.calories}</Text></View> <View style={css.ddn_topborder2}><Text style={css.ddn_dv}>% Daily Values*</Text></View> <View style={css.ddn_row_main}><Text style={css.ddn_font}><Text style={css.bold}>Total Fat</Text> {menuItem.nutrition.totalFat}</Text><Text style={css.ddn_percent}>{menuItem.nutrition.totalFatDV}</Text></View> <View style={css.ddn_row_sub}><Text style={css.ddn_font}>Saturated Fat {menuItem.nutrition.saturatedFat}</Text><Text style={css.ddn_percent}>{menuItem.nutrition.saturatedFatDV}</Text></View> <View style={css.ddn_row_sub}> <Text style={css.ddn_font}>Trans Fat {menuItem.nutrition.transFat}</Text><Text style={css.ddn_percent}> {menuItem.nutrition.transFatDV !== '%' ? menuItem.nutrition.transFatDV : null } </Text> </View> <View style={css.ddn_row_main}><Text style={css.ddn_font}><Text style={css.bold}>Cholesterol</Text> {menuItem.nutrition.cholesterol}</Text><Text style={css.ddn_percent}>{menuItem.nutrition.cholesterolDV}</Text></View> <View style={css.ddn_row_main}><Text style={css.ddn_font}><Text style={css.bold}>Sodium</Text> {menuItem.nutrition.sodium}</Text><Text style={css.ddn_percent}>{menuItem.nutrition.sodiumDV}</Text></View> <View style={css.ddn_row_main}><Text style={css.ddn_font}><Text style={css.bold}>Total Carbohydrate</Text> {menuItem.nutrition.totalCarbohydrate}</Text><Text style={css.ddn_percent}>{menuItem.nutrition.totalCarbohydrateDV}</Text></View> <View style={css.ddn_row_sub}><Text style={css.ddn_font}>Dietary Fiber {menuItem.nutrition.dietaryFiber}</Text><Text style={css.ddn_percent}>{menuItem.nutrition.dietaryFiberDV}</Text></View> <View style={css.ddn_row_sub}><Text style={css.ddn_font}>Sugars {menuItem.nutrition.sugars}</Text><Text style={css.ddn_percent}></Text></View> <View style={css.ddn_row_main}><Text style={css.ddn_font}><Text style={css.bold}>Protein</Text> {menuItem.nutrition.protein}</Text><Text style={css.ddn_percent}>{menuItem.nutrition.proteinDV}</Text></View> <View style={css.ddn_topborder1}><Text style={css.ddn_dv_amountperserving}>*Percent Daily Values are based on a 2,000 calorie diet.</Text></View> </View> { (menuItem.nutrition.ingredients) ? ( <View style={css.ddn_info_container}> <Text> <Text style={css.ddn_bold}>Ingredients: </Text> <Text style={css.ddn_font}>{menuItem.nutrition.ingredients}</Text> </Text> </View> ) : (null) } <View style={css.ddn_info_container}> <Text> <Text style={css.ddn_bold}>Allergens: </Text> { (menuItem.nutrition.allergens) ? ( <Text style={css.ddn_font}>{menuItem.nutrition.allergens}</Text> ) : ( <Text style={css.ddn_font}>None</Text> ) } </Text> </View> <View style={css.ddn_info_container}> <Text> <Text style={css.ddn_bold}>Disclaimer: </Text> <Text style={css.ddn_disclaimer_font}>{disclaimer}</Text> </Text> </View> { (disclaimerEmail) ? ( <DisclaimerEmailButton disclaimerEmail={disclaimerEmail} /> ) : (null) } </ScrollView> ); }; const DisclaimerEmailButton = ({ disclaimerEmail }) => ( <Touchable onPress={() => openURL(`mailto:${disclaimerEmail}`)} > <View style={css.dd_menu_link_container}> <Text style={css.dd_menu_link_text}>Contact Nutrition Team</Text> </View> </Touchable> ); export default DiningNutrition;
JavaScript
0
@@ -1499,16 +1499,17 @@ totalFat +_ DV%7D%3C/Tex @@ -1695,16 +1695,17 @@ ratedFat +_ DV%7D%3C/Tex @@ -2174,16 +2174,17 @@ lesterol +_ DV%7D%3C/Tex @@ -2382,16 +2382,17 @@ n.sodium +_ DV%7D%3C/Tex @@ -2624,16 +2624,17 @@ ohydrate +_ DV%7D%3C/Tex @@ -2820,16 +2820,17 @@ aryFiber +_ DV%7D%3C/Tex @@ -3179,16 +3179,17 @@ .protein +_ DV%7D%3C/Tex
e8eafe7681a8dcf69d0b9427d39f1c631d3fd43d
Fix webpack version bump config
webpack.config.js
webpack.config.js
'use strict'; // Modules var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var CopyWebpackPlugin = require('copy-webpack-plugin'); /** * Env * Get npm lifecycle event to identify the environment */ var ENV = process.env.npm_lifecycle_event; var isProd = ENV === 'build'; module.exports = function makeWebpackConfig () { /** * Config * Reference: http://webpack.github.io/docs/configuration.html * This is the object where all configuration gets set */ var config = {}; /** * Entry * Reference: http://webpack.github.io/docs/configuration.html#entry * Should be an empty object if it's generating a test build * Karma will set this when it's a test build */ config.entry = { app: isProd ? './source/ngjs-color-picker.js' : './dev/app/app.js' }; /** * Output * Reference: http://webpack.github.io/docs/configuration.html#output * Should be an empty object if it's generating a test build * Karma will handle setting it up for you when it's a test build */ config.output = { // Absolute output directory path: __dirname + '/dist', // Output path from the view of the page // Uses webpack-dev-server in development publicPath: isProd ? '/' : 'http://localhost:8080/', // Filename for entry points // Only adds hash in build mode filename: isProd ? 'ngjs-color-picker.js' : '[name].bundle.js', // Filename for non-entry points // Only adds hash in build mode chunkFilename: isProd ? 'ngjs-color-picker.js' : '[name].bundle.js' }; /** * Devtool * Reference: http://webpack.github.io/docs/configuration.html#devtool * Type of sourcemap to use per build type */ if (isProd) { config.devtool = 'source-map'; } else { config.devtool = 'eval-source-map'; } /** * Loaders * Reference: http://webpack.github.io/docs/configuration.html#module-loaders * List: http://webpack.github.io/docs/list-of-loaders.html * This handles most of the magic responsible for converting modules */ // Initialize module config.module = { preLoaders: [], loaders: [{ // JS LOADER // Reference: https://github.com/babel/babel-loader // Transpile .js files using babel-loader // Compiles ES6 and ES7 into ES5 code test: /\.js$/, loader: 'babel', exclude: /node_modules/ }, { // ASSET LOADER // Reference: https://github.com/webpack/file-loader // Copy png, jpg, jpeg, gif, svg, woff, woff2, ttf, eot files to output // Rename the file using the asset hash // Pass along the updated reference to your code // You can add here any file extension you want to get copied to your output test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/, loader: 'file' }, { // HTML LOADER // Reference: https://github.com/webpack/raw-loader // Allow loading html through js test: /\.html$/, loader: 'raw' }] }; /** * Plugins * Reference: http://webpack.github.io/docs/configuration.html#plugins * List: http://webpack.github.io/docs/list-of-plugins.html */ config.plugins = []; // Reference: https://github.com/ampedandwired/html-webpack-plugin // Render index.html config.plugins.push( new HtmlWebpackPlugin({ template: './dev/public/index.html', inject: 'body' }) ); // Add build specific plugins if (isProd) { config.plugins.push( // Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin // Only emit files when there are no errors new webpack.NoErrorsPlugin(), // Reference: http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin // Dedupe modules in the output new webpack.optimize.DedupePlugin(), // Reference: http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin // Minify all javascript, switch loaders to minimizing mode new webpack.optimize.UglifyJsPlugin(), // Copy assets from the public folder // Reference: https://github.com/kevlened/copy-webpack-plugin new CopyWebpackPlugin([{ from: __dirname + '/public' }]) ); } /** * Dev server configuration * Reference: http://webpack.github.io/docs/configuration.html#devserver * Reference: http://webpack.github.io/docs/webpack-dev-server.html */ config.devServer = { contentBase: './dev/public', stats: 'minimal' }; return config; }();
JavaScript
0.000001
@@ -2244,32 +2244,8 @@ = %7B%0A - preLoaders: %5B%5D,%0A @@ -2506,16 +2506,23 @@ : 'babel +-loader ',%0A @@ -3239,16 +3239,23 @@ er: 'raw +-loader '%0A
3b9eb701dea8d25303647615c666769a6db0dc21
Fix styles loading parameters
webpack.config.js
webpack.config.js
const path = require('path'); const webpack = require('webpack'); const HtmlPlugin = require('html-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const CompressionPlugin = require('compression-webpack-plugin'); const StatsPlugin = require('stats-webpack-plugin'); const autoprefixer = require('autoprefixer'); // Environment const isProduction = process.env.NODE_ENV === 'production'; // Paths const src = path.join(__dirname, 'src'); const dist = path.join(__dirname, 'dist'); // Base configuration const config = { entry: path.join(src, 'index.js'), output: { path: dist, publicPath: '/', }, module: { loaders: [ { test: /\.jss?$/, exclude: /node_modules/, loader: 'babel', }, { test: /\.json$/, loader: 'json', }, ], }, plugins: [ new webpack.EnvironmentPlugin(['NODE_ENV']), new HtmlPlugin({ template: path.join(src, 'index.ejs'), inject: false, filename: 'index.html', }), new webpack.ProvidePlugin({ fetch: 'imports?this=>global!exports?global.fetch!whatwg-fetch', }), new webpack.DefinePlugin({ __DEV__: !isProduction, }), ], resolve: { extensions: ['', '.js', '.jss'], }, }; // Output configuration config.output.filename = isProduction ? '[name]-[hash].js' : '[name].js'; // Development tools config.devtool = isProduction ? 'source-map' : 'eval'; if (!isProduction) { config.output.pathinfo = true; } // CSS loader const cssLoader = { // NOTE: process external `.css` files. test: /\.css$/, }; const cssLoaders = [ `css-loader?${JSON.stringify({ // NOTE: don't need source maps on production. Error don't handles in // styles. sourceMap: !isProduction, // NOTE: use shorter style name in production, and more informative in // development for debug purposes. localIdentName: isProduction ? '[hash:base64:4]' : '[name]__[local]___[hash:base64:3]', // NOTE: minimize result code for production (`css-loader` uses `cssnano`). minimize: isProduction, })}`, // NOTE: use `defaults` pack of plugins for processing external styles. 'postcss-loader', ]; if (isProduction) { // NOTE: extract styles to external file for production build. cssLoader.loader = ExtractTextPlugin.extract('style-loader', cssLoaders); } else { cssLoader.loaders = ['style-loader'].concat(cssLoaders); } config.module.loaders.push(cssLoader); // PostCSS loader const pcssLoader = { // NOTE: use `.pcss` extension for PostCSS code. test: /\.pcss$/, }; const pcssLoaders = [ `css-loader?${JSON.stringify({ // NOTE: don't need source maps on production. Error don't handles in // styles. sourceMap: !isProduction, // NOTE: use CSS Modules. modules: true, // NOTE: use shorter style name in production, and more informative in // development for debug purposes. // NOTE: `camelCase` option used for export camel cased names to JS. localIdentName: isProduction ? '[hash:base64:4]:camelCase' : '[name]__[local]___[hash:base64:3]:camelCase', // NOTE: minimize result code for production (`css-loader` uses `cssnano`). minimize: isProduction, })}`, // NOTE: use `modules` pack for processing internal CSS modules files. 'postcss-loader?pack=modules', ]; if (isProduction) { // NOTE: extract styles to external file for production build. pcssLoader.loader = ExtractTextPlugin.extract('style-loader', pcssLoaders); } else { pcssLoader.loaders = ['style-loader'].concat(pcssLoaders); } config.module.loaders.push(pcssLoader); // PostCSS config.postcss = function postcssPacks() { return { // NOTE: PostCSS plugins for processing external CSS dependencies. defaults: [autoprefixer], // NOTE: PostCSS plugins for processing internal CSS modules. modules: [autoprefixer], }; }; // Plugins if (isProduction) { config.plugins.push( new ExtractTextPlugin('[name]-[hash].css') ); config.plugins.push( new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false, screw_ie8: true, }, }) ); config.plugins.push( new webpack.optimize.OccurenceOrderPlugin() ); config.plugins.push( new CompressionPlugin() ); config.plugins.push( new StatsPlugin('manifest.json', { chunkModules: false, source: false, chunks: false, modules: false, assets: true, }) ); } else { config.plugins.push( new webpack.NoErrorsPlugin() ); config.plugins.push( new webpack.HotModuleReplacementPlugin() ); } // Development server config.devServer = { colors: true, compress: false, host: '0.0.0.0', port: 3000, inline: true, historyApiFallback: true, }; module.exports = config;
JavaScript
0
@@ -1770,179 +1770,75 @@ les. -%0A sourceMap: !isProduction,%0A // NOTE: use shorter style name in production, and more informative in%0A // development for debug purposes.%0A localIdentName + Source maps will be generated, but will be empty.%0A sourceMap : +! isPr @@ -1849,78 +1849,8 @@ tion -%0A ? '%5Bhash:base64:4%5D'%0A : '%5Bname%5D__%5Blocal%5D___%5Bhash:base64:3%5D' ,%0A @@ -2377,59 +2377,8 @@ = %7B%0A - // NOTE: use %60.pcss%60 extension for PostCSS code.%0A te @@ -2540,24 +2540,74 @@ styles. + Source maps will be generated, but will be empty. %0A sourceM @@ -2798,81 +2798,8 @@ es.%0A - // NOTE: %60camelCase%60 option used for export camel cased names to JS.%0A @@ -2851,26 +2851,16 @@ ase64:4%5D -:camelCase '%0A @@ -2899,19 +2899,103 @@ 4:3%5D -:camelCase' +',%0A // NOTE: %60camelCase%60 option used for export camel cased names to JS.%0A camelCase: true ,%0A
8afb1a7707580d4a9c2bcf940f7047d690a39856
Clean up webpack config
webpack.config.js
webpack.config.js
const webpack = require('webpack'); const path = require('path'); module.exports = { entry: { index: './src/index' }, output: { path: './dist', libraryTarget: 'commonjs2', filename: 'index.js' }, resolve: { extensions: ['.js', '.json'], modules: [ path.resolve('./src'), path.resolve('./node_modules'), ] }, plugins: [ new webpack.DefinePlugin({ "global.GENTLY": false }) ], node: { __dirname: true, }, target: 'electron-renderer', module: { rules: [{ test: /\.jsx?$/, use: { loader: 'babel-loader' }, exclude: /node_modules/ }, { test: /\.css$/, use: [{ loader: 'style-loader' }, { loader: 'css-loader', query: { modules: true } }] }, { test: /\.png$/, use: { loader: 'url-loader' } }, { test: /\.json$/, use: 'json-loader' }, { test: /\.s[ac]ss$/, use: [{ loader: "style-loader" }, { loader: "css-loader" }, { loader: "sass-loader" }] }] } };
JavaScript
0.000001
@@ -520,23 +520,24 @@ rules: %5B -%7B %0A + %7B test: / @@ -549,67 +549,29 @@ ?$/, -%0A use: %7B%0A loader: 'babel-loader'%0A %7D,%0A + use: 'babel-loader', exc @@ -590,31 +590,27 @@ modules/ -%0A %7D, - %7B %0A + %7B test: / @@ -617,38 +617,31 @@ %5C.css$/, -%0A use: %5B -%7B %0A loader: @@ -624,32 +624,36 @@ , use: %5B%0A + %7B loader: 'style- @@ -659,35 +659,27 @@ -loader' -%0A %7D, - %7B %0A loader: @@ -662,32 +662,36 @@ ader' %7D,%0A + %7B loader: 'css-lo @@ -696,24 +696,16 @@ loader', -%0A query: @@ -705,26 +705,16 @@ query: %7B -%0A modules @@ -719,24 +719,18 @@ es: true -%0A +%7D %7D%0A @@ -734,25 +734,22 @@ -%7D%5D%0A - +%5D %7D, - %7B %0A + %7B tes @@ -764,73 +764,37 @@ g$/, -%0A use: %7B%0A loader: 'url-loader'%0A %7D%0A %7D, %7B%0A + use: 'url-loader' %7D,%0A %7B tes @@ -806,22 +806,16 @@ .json$/, -%0A use: 'j @@ -829,23 +829,19 @@ der' -%0A %7D, - %7B %0A + %7B tes @@ -860,128 +860,45 @@ s$/, -%0A use: %5B -%7B%0A loader: %22style-loader%22%0A %7D, %7B%0A loader: %22css-loader%22%0A %7D, %7B%0A loader: %22 +'style-loader','css-loader', ' sass @@ -908,22 +908,17 @@ ader -%22%0A +'%5D %7D -%5D %0A -%7D + %5D%0A
16442f24ad2defaa65a1ee783f185332b37b78fe
Update alert
client/src/js/samples/components/Analyses/List.js
client/src/js/samples/components/Analyses/List.js
import React from "react"; import { map, sortBy } from "lodash-es"; import { connect } from "react-redux"; import { Link } from "react-router-dom"; import { ListGroup, FormGroup, InputGroup, FormControl, Alert } from "react-bootstrap"; import { analyze } from "../../actions"; import { Icon, Button, LoadingPlaceholder, NoneFound, Flex, FlexItem } from "../../../base"; import AnalysisItem from "./Item"; import CreateAnalysis from "./Create"; import {getCanModify} from "../../selectors"; import { findIndexes } from "../../../indexes/actions"; const AnalysesToolbar = ({ onClick, isModified }) => ( <div className="toolbar"> <FormGroup> <InputGroup> <InputGroup.Addon> <Icon name="search" /> </InputGroup.Addon> <FormControl type="text" /> </InputGroup> </FormGroup> <Button icon="new-entry" tip="New Analysis" bsStyle="primary" onClick={onClick} disabled={isModified} /> </div> ); class AnalysesList extends React.Component { constructor (props) { super(props); this.state = { show: false }; } /* componentWillMount () { this.props.onFind(); } */ render () { if (this.props.analyses === null) { return <LoadingPlaceholder margin="37px" />; } // The content that will be shown below the "New Analysis" form. let listContent; if (this.props.analyses.length) { // The components that detail individual analyses. listContent = map(sortBy(this.props.analyses, "timestamp").reverse(), (document, index) => <AnalysisItem key={index} {...document} /> ); } else { listContent = <NoneFound noun="analyses" noListGroup />; } let alert; if (this.props.modified_count) { alert = ( <Alert bsStyle="warning"> <Flex alignItems="center"> <Icon name="info" /> <FlexItem pad={5}> <span>The virus database has changed. </span> <Link to="/viruses/indexes">Rebuild the index</Link> <span> to use the changes in further analyses.</span> </FlexItem> </Flex> </Alert> ); } return ( <div> {alert} {this.props.canModify ? <AnalysesToolbar onClick={() => this.setState({show: true})} isModified={!!this.props.modified_count} /> : null} <ListGroup> {listContent} </ListGroup> <CreateAnalysis id={this.props.detail.id} show={this.state.show} onHide={() => this.setState({show: false})} onSubmit={this.props.onAnalyze} /> </div> ); } } const mapStateToProps = (state) => ({ detail: state.samples.detail, analyses: state.samples.analyses, canModify: getCanModify(state), modified_count: state.viruses.modified_count }); const mapDispatchToProps = (dispatch) => ({ onAnalyze: (sampleId, algorithm) => { dispatch(analyze(sampleId, algorithm)); } }); const Container = connect(mapStateToProps, mapDispatchToProps)(AnalysesList); export default Container;
JavaScript
0.000001
@@ -489,65 +489,8 @@ %22;%0A%0A -import %7B findIndexes %7D from %22../../../indexes/actions%22;%0A%0A cons @@ -1178,76 +1178,8 @@ %7D%0A -/*%0A componentWillMount () %7B%0A this.props.onFind();%0A %7D%0A*/ %0A
93fec369dc6bcee9fbbbab236e46f217ef2ceee7
Write optimization test for font-face
test/font-face.js
test/font-face.js
var assert = require("assert"); var crass = require('../crass'); var filler = 'src:"";foo:bar'; var parity = function(data) { data = data.replace(/\$\$/g, filler); assert.equal(crass.parse(data).toString(), data); assert.equal(crass.parse(crass.parse(data).pretty()).toString(), data); } describe('@font-face', function() { it('should parse font-face blocks', function() { parity('@font-face{$$}'); }); });
JavaScript
0.000039
@@ -422,12 +422,213 @@ %7D);%0A + it('should optimize', function() %7B%0A assert.equal(%0A crass.parse('@font-face%7Bfont-weight:bold%7D').optimize().toString(),%0A '@font-face%7Bfont-weight:700%7D'%0A );%0A %7D);%0A %7D);%0A
62849d1cfd10ba2c020544f7fa8d9243a76da82c
Fix tests
test/is-base64.js
test/is-base64.js
var test = require('tape'); var isBase64 = require('../is-base64'); test('isBase64', function (t) { t.plan(7); var pngString = 'iVBORw0KGgoAAAANSUhEUgAABQAAAALQAQMAAAD1s08VAAAAA1BMVEX/AAAZ4gk3AAAAh0lEQVR42u3BMQEAAADCoPVPbQlPoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB4GsTfAAGc95RKAAAAAElFTkSuQmCC'; var pngStringWithMime = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABQAAAALQAQMAAAD1s08VAAAAA1BMVEX/AAAZ4gk3AAAAh0lEQVR42u3BMQEAAADCoPVPbQlPoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB4GsTfAAGc95RKAAAAAElFTkSuQmCC'; var jpgString = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEACAhITMkM1EwMFFCLy8vQiccHBwcJyIXFxcXFyIRDAwMDAwMEQwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBIjMzNCY0IhgYIhQODg4UFA4ODg4UEQwMDAwMEREMDAwMDAwRDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDP/AABEIAAYABgMBIgACEQEDEQH/xABVAAEBAAAAAAAAAAAAAAAAAAAAAxAAAQQCAwEAAAAAAAAAAAAAAgABAxQEIxIkMxMBAQAAAAAAAAAAAAAAAAAAAAARAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/AIE7MwkbOUJDJWx+ZjXATitx2/h2bEWvX5Y0npQ7aIiD/9k=' var jpgStringWithMime = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEACAhITMkM1EwMFFCLy8vQiccHBwcJyIXFxcXFyIRDAwMDAwMEQwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBIjMzNCY0IhgYIhQODg4UFA4ODg4UEQwMDAwMEREMDAwMDAwRDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDP/AABEIAAYABgMBIgACEQEDEQH/xABVAAEBAAAAAAAAAAAAAAAAAAAAAxAAAQQCAwEAAAAAAAAAAAAAAgABAxQEIxIkMxMBAQAAAAAAAAAAAAAAAAAAAAARAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/AIE7MwkbOUJDJWx+ZjXATitx2/h2bEWvX5Y0npQ7aIiD/9k='; t.equal(isBase64(pngString), true); t.equal(isBase64(pngStringWithMime), true); t.equal(isBase64(jpgString), true); t.equal(isBase64(jpgStringWithMime), true); t.equal(isBase64('1342234'), false); t.equal(isBase64('afQ$%rfew'), false); t.equal(isBase64('dfasdfr342'), false); });
JavaScript
0.000003
@@ -754,39 +754,16 @@ ring = ' -data:image/jpeg;base64, /9j/4AAQ
5610038d24a316ffc14de2c854233de5b1e44954
Fix path tests. Add new tests.
lib/axiom/fs/path.test.js
lib/axiom/fs/path.test.js
// Copyright 2015 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. import Path from 'axiom/fs/path'; var failTest = function(error) { expect(error).toBeUndefined(); }; describe('Path', function () { it('should be available as a module', function () { expect(Path).toBeDefined(); }); it('should not allow undefined path', function () { expect(function() { /** @type {string} */ var x; var p = new Path(x); }).toThrow(); }); it('should allow empty path', function () { var p = new Path('fs:'); expect(p).toBeDefined(); expect(p.isValid).toBe(true); }); it('should allow root path', function () { var p = new Path('fs:/'); expect(p).toBeDefined(); expect(p.isValid).toBe(true); expect(p.elements).toEqual([]); }); it('should return null for parent of root path', function () { var p = new Path('fs:/').getParentPath(); expect(p).toBe(null); }); it('should split path with multiple elements', function () { var p = new Path('fs:foo/bar'); expect(p).toBeDefined(); expect(p.isValid).toBe(true); expect(p.elements).toEqual(['foo', 'bar']); }); it('should split path with multiple elements', function () { var p = new Path('fs:/foo/bar'); expect(p).toBeDefined(); expect(p.isValid).toBe(true); expect(p.elements).toEqual(['foo', 'bar']); }); it('should return the base name as a string', function () { var p = new Path('fs:/foo/bar/blah').getBaseName(); expect(p).toBeDefined(); expect(p).toEqual('blah'); }); it('should combine root with simple relative paths', function () { var p = new Path('fs:').combine('foo'); expect(p).toBeDefined(); expect(p.spec).toEqual('fs:foo'); }); it('should combine simple relative paths', function () { var p = new Path('fs:bar').combine('foo'); expect(p).toBeDefined(); expect(p.spec).toEqual('fs:bar/foo'); }); it('should combine dotted relative paths', function () { var p = new Path('fs:bar').combine('./foo'); expect(p).toBeDefined(); expect(p.spec).toEqual('fs:bar/foo'); }); it('should combine dotted relative paths', function () { var p = new Path('fs:bar').combine('../foo'); expect(p).toBeDefined(); expect(p.spec).toEqual('fs:foo'); }); });
JavaScript
0
@@ -2262,31 +2262,32 @@ toEqual('fs: +/ foo');%0A - %7D);%0A%0A it( @@ -2439,32 +2439,33 @@ ec).toEqual('fs: +/ bar/foo');%0A %7D); @@ -2634,16 +2634,17 @@ ual('fs: +/ bar/foo' @@ -2783,32 +2783,32 @@ .toBeDefined();%0A - expect(p.spe @@ -2822,16 +2822,198 @@ ual('fs: +/foo');%0A %7D);%0A%0A it('should resolve paths relative to current fs', function () %7B%0A var p = Path.abs('fs:bar', '/foo');%0A expect(p).toBeDefined();%0A expect(p.spec).toEqual('fs:/ foo');%0A
7b123ab0934aa9304dc9a9bf334dac8bfbbe1e04
change ETH language
lib/blockchain/install.js
lib/blockchain/install.js
const fs = require('fs') const path = require('path') const process = require('process') const os = require('os') const makeDir = require('make-dir') const inquirer = require('inquirer') const _ = require('lodash/fp') const coinUtils = require('../coin-utils') const common = require('./common') const doVolume = require('./do-volume') const cryptos = coinUtils.cryptoCurrencies() const logger = common.logger const PLUGINS = { BTC: require('./bitcoin.js'), LTC: require('./litecoin.js'), ETH: require('./ethereum.js'), DASH: require('./dash.js'), ZEC: require('./zcash.js'), BCH: require('./bitcoincash.js') } module.exports = {run} function installedVolumeFilePath (crypto) { return path.resolve(coinUtils.cryptoDir(crypto), '.installed') } function isInstalledVolume (crypto) { return fs.existsSync(installedVolumeFilePath(crypto)) } function isInstalledSoftware (crypto) { return common.isInstalledSoftware(crypto) } function processCryptos (codes) { if (_.isEmpty(codes)) { logger.info('No cryptos selected. Exiting.') process.exit(0) } logger.info('Thanks! Installing: %s. Will take a while...', _.join(', ', codes)) const goodVolume = doVolume.prepareVolume() if (!goodVolume) { logger.error('There was an error preparing the disk volume. Exiting.') process.exit(1) } const selectedCryptos = _.map(code => _.find(['code', code], cryptos), codes) _.forEach(setupCrypto, selectedCryptos) common.es('sudo service supervisor restart') const blockchainDir = coinUtils.blockchainDir() const backupDir = path.resolve(os.homedir(), 'backups') const rsyncCmd = `( \ (crontab -l 2>/dev/null || echo -n "") | grep -v "@daily rsync ".*"wallet.dat"; \ echo "@daily rsync -r --prune-empty-dirs --include='*/' \ --include='wallet.dat' \ --exclude='*' ${blockchainDir} ${backupDir} > /dev/null" \ ) | crontab -` common.es(rsyncCmd) logger.info('Installation complete.') } function setupCrypto (crypto) { logger.info(`Installing ${crypto.display}...`) const cryptoDir = coinUtils.cryptoDir(crypto) makeDir.sync(cryptoDir) const cryptoPlugin = plugin(crypto) const oldDir = process.cwd() const tmpDir = '/tmp/blockchain-install' makeDir.sync(tmpDir) process.chdir(tmpDir) common.es('rm -rf *') common.fetchAndInstall(crypto) cryptoPlugin.setup(cryptoDir) common.writeFile(installedVolumeFilePath(crypto), '') process.chdir(oldDir) } function plugin (crypto) { const plugin = PLUGINS[crypto.cryptoCode] if (!plugin) throw new Error(`No such plugin: ${crypto.cryptoCode}`) return plugin } function run () { const choices = _.map(c => { const checked = isInstalledSoftware(c) && isInstalledVolume(c) return { name: c.display, value: c.code, checked, disabled: c.cryptoCode === 'ETH' ? 'Installed, use Infura option' : checked && 'Installed' } }, cryptos) const questions = [] questions.push({ type: 'checkbox', name: 'crypto', message: 'Which cryptocurrencies would you like to install?', choices }) inquirer.prompt(questions) .then(answers => processCryptos(answers.crypto)) }
JavaScript
0.998663
@@ -2888,30 +2888,28 @@ ? ' -Installed, use +Use admin%5C's Infura opti @@ -2908,13 +2908,13 @@ ura -optio +plugi n'%0A
dbff6c1cc9d0deb3f23f80d941898e901b88ee11
fix copyTemplate editor path
lib/copyTemplateAssets.js
lib/copyTemplateAssets.js
'use strict'; const File = require( 'vinyl' ); const fs = require( 'fs' ); const copyTemplateAssets = function ( stream ) { let cssSrc = fs.readFileSync( __dirname + '/template/build/_template/_template.css', { encoding: 'utf-8' } ); let css = new File( { path: '_template/_template.css', contents: new Buffer( cssSrc ) } ); stream.push( css ); let jsSrc = fs.readFileSync( __dirname + '/template/build/_template/_template.js', { encoding: 'utf-8' } ); let js = new File( { path: '_template/_template.js', contents: new Buffer( jsSrc ) } ); stream.push( js ); var fontSrc = fs.readFileSync( __dirname + '/template/build/_template/_template.woff' ); let fontFile = new File( { path: '_template/_template.woff', contents: new Buffer( fontSrc ) } ); stream.push( fontFile ); // editor let editorHtmlSrc = fs.readFileSync( __dirname + '/editor/build/_editor.html', { encoding: 'utf-8' } ); let editorHtml = new File( { path: '_editor.html', contents: new Buffer( editorHtmlSrc ) } ); stream.push( editorHtml ); let editorCssSrc = fs.readFileSync( __dirname + '/editor/build/_editor/_editor.css', { encoding: 'utf-8' } ); let editorCss = new File( { path: '_editor/_editor.css', contents: new Buffer( editorCssSrc ) } ); stream.push( editorCss ); let editorJsSrc = fs.readFileSync( __dirname + '/editor/build/_editor/_editor.Js', { encoding: 'utf-8' } ); let editorJs = new File( { path: '_editor/_editor.js', contents: new Buffer( editorJsSrc ) } ); stream.push( editorJs ); } module.exports = copyTemplateAssets;
JavaScript
0
@@ -1365,17 +1365,17 @@ _editor. -J +j s', %7B en
4232a776869073f6aa1ec0c7ac166499d1fbf0a3
fix #11 always waiting for WDS
src/DatePicker2.js
src/DatePicker2.js
import React, { Component, PropTypes } from 'react'; import { default as ReactDatePicker } from 'react-datepicker'; import moment from 'moment'; /** * DatePicker2控件 */ export default class DatePicker2 extends Component { static defaultProps = { dateFormat: 'YYYY-MM-DD' } static propTypes = { /** * 日期格式<br> * 遵循moment.js格式<br> * <a href="https://momentjs.com/docs/#/displaying/format/">Moment.js文档</a> */ dateFormat: PropTypes.string, /** * value 请使用ISO 8061格式 */ value: PropTypes.string, showMonthDropdown: PropTypes.bool, showYearDropdown: PropTypes.bool, /** * 参数: * - value: ISO 8061格式时间字符串 * - formattedValue: 按照用户指定格式进行了格式化后的字符串 * - momentDate: moment.js对象 */ onChange: PropTypes.func }; state = { }; constructor(props) { super(props); } // date参数是moment.js生成的时间格式 handleChange(date) { if (this.props.onChange) { this.props.onChange( date.toDate().toISOString(), // ISO 8601 date.format(this.props.dateFormat), // 使用moment.js按照用户指定的格式进行格式化 date ); } } render() { // 使用otherProps获取react-datepicker的属性,然后往下传 const { value, ...otherProps } = this.props; return (<ReactDatePicker {...otherProps} selected={moment(value)} onChange={this.handleChange.bind(this)} />); } }
JavaScript
0
@@ -1142,16 +1142,18 @@ %0A // +%E4%B9%8B%E5%89%8D %E4%BD%BF%E7%94%A8otherP @@ -1192,102 +1192,207 @@ -const %7B value, ...otherProps %7D = this.props;%0A return (%3CReactDatePicker%0A %7B...otherProps +// %E4%BD%86%E6%98%AF%E5%87%BA%E7%8E%B0%E4%BA%86bug#11%0A const %7B value, showMonthDropdown, showYearDropdown %7D = this.props;%0A return (%3CReactDatePicker%0A showMonthDropdown=%7BshowMonthDropdown%7D%0A showYearDropdown=%7BshowYearDropdown %7D%0A
a04aa685cc69ef792a7e2d1f457ba065d7f11b57
Fix lint errors in client parser
lib/html-to-dom-client.js
lib/html-to-dom-client.js
'use strict'; /** * Module dependencies. */ var utilities = require('./utilities'); var formatDOM = utilities.formatDOM; /** * Parse HTML string to DOM nodes. * This uses the browser DOM API. * * @param {String} html - The HTML. * @return {Object} - The DOM nodes. */ function parseDOM(html) { if (typeof html !== 'string') { throw new TypeError('First argument must be a string.'); } // try to match the tags var match = html.match(/<[^\/](.+?)>/g); var container; var parentNode; var nodes; if (match && match.length) { var tagMatch = match[0]; // directive matched if (/<![^-]/.test(tagMatch)) { var directive = ( // remove angle brackets tagMatch .substring(1, tagMatch.length - 1) .trim() ); // tag name can no longer be first match item tagMatch = match[1]; // remove directive from html html = html.substring(html.indexOf('>') + 1); } // first tag name matched if (tagMatch) { var tagName = ( // keep only tag name tagMatch .substring(1, tagMatch.indexOf(' ')) .trim() .toLowerCase() ) } } // create html document to parse top-level nodes if (['html', 'head', 'body'].indexOf(tagName) > -1) { var doc; // `new DOMParser().parseFromString()` // https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#Parsing_an_SVG_or_HTML_document if (window.DOMParser) { doc = new window.DOMParser().parseFromString(html, 'text/html'); // `DOMImplementation.createHTMLDocument()` // https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createHTMLDocument } else if (document.implementation.createHTMLDocument) { doc = document.implementation.createHTMLDocument(); doc.documentElement.innerHTML = html; doc.removeChild(doc.childNodes[0]); // remove doctype } // html if (tagName === 'html') { nodes = doc.childNodes; // head and body } else { nodes = ( // do this so attributes are kept // but there may be an extra head/body node doc.getElementsByTagName(tagName)[0] .parentNode .childNodes ); } // `innerHTML` approach } else { var container = document.createElement('body'); container.innerHTML = html; nodes = container.childNodes; } return formatDOM(nodes, null, directive); } /** * Export HTML to DOM parser (client). */ module.exports = parseDOM;
JavaScript
0.000012
@@ -489,47 +489,8 @@ g);%0A - var container;%0A var parentNode;%0A
48b88c98178c079b5eae3261752605bc10004c18
Fix typo
assets/static/js/tipuesearch_set.js
assets/static/js/tipuesearch_set.js
/* Tipue Search 5.0 Copyright (c) 2015 Tipue Tipue Search is released under the MIT License http://www.tipue.com/search */ /* Stop words list from http://www.ranks.nl/stopwords/german */ var tipuesearch_stop_words = ["aber", "als", "am", "an", "auch", "auf", "aus", "bei", "bin", "bis", "bist", "da", "dadurch", "daher", "darum", "das", "daß", "dass", "dein", "deine", "dem", "den", "der", "des", "dessen", "deshalb", "die", "dies", "dieser", "dieses", "doch", "dort", "du", "durch", "ein", "eine", "einem", "einen", "einer", "eines", "er", "es", "euer", "eure", "für", "hatte", "hatten", "hattest", "hattet", "hier", "hinter", "ich", "ihr", "ihre", "im", "in", "ist", "ja", "jede", "jedem", "jeden", "jeder", "jedes", "jener", "jenes", "jetzt", "kann", "kannst", "können", "könnt", "machen", "mein", "meine", "mit", "muß", "mußt", "musst", "müssen", "müßt", "nach", "nachdem", "nein", "nicht", "nun", "oder", "seid", "sein", "seine", "sich", "sie", "sind", "soll", "sollen", "sollst", "sollt", "sonst", "soweit", "sowie", "und", "unser", "unsere", "unter", "vom", "von", "vor", "wann", "warum", "was", "weiter", "weitere", "wenn", "wer", "werde", "werden", "werdet", "weshalb", "wie", "wieder", "wieso", "wir", "wird", "wirst", "wo", "woher", "wohin", "zu", "zum", "zur", "über"]; var tipuesearch_replace = {'words': []}; var tipuesearch_weight = {'weight': []}; var tipuesearch_stem = {'words': []}; var tipuesearch_string_1 = 'Kein Title'; var tipuesearch_string_2 = 'Resultate für'; var tipuesearch_string_3 = 'Suche stattdessen nach'; var tipuesearch_string_4 = '1 Resultat'; var tipuesearch_string_5 = 'Resultate'; var tipuesearch_string_6 = 'Vorherige'; var tipuesearch_string_7 = 'Nächste'; var tipuesearch_string_8 = 'Nichts gefunden.'; var tipuesearch_string_9 = 'Häufig verwendete Begriffe werden weitgehend ignoriert'; var tipuesearch_string_10 = 'Suchbegriff zu kuzr'; var tipuesearch_string_11 = 'Sollte mindestens ein Zeichen sein'; var tipuesearch_string_12 = 'Sollte'; var tipuesearch_string_13 = 'Zeichen oder mehr';
JavaScript
0.999999
@@ -1877,10 +1877,10 @@ u ku -z r +z ';%0Av
9ca25a776ae71b97e0db1921f8f73db365e8e6c4
add semi-colons after functions
Objectid.js
Objectid.js
/* * * Copyright (c) 2011 Justin Dearing ([email protected]) * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) version 2 licenses. * This software is not distributed under version 3 or later of the GPL. * * Version 1.0.0 * */ /** * Javascript class that mimics how WCF serializes a object of type MongoDB.Bson.ObjectId * and converts between that format and the standard 24 character representation. */ var ObjectId = (function () { var increment = 0; var pid = Math.floor(Math.random() * (32767)); var machine = Math.floor(Math.random() * (16777216)); if (typeof (localStorage) != 'undefined') { var mongoMachineId = parseInt(localStorage['mongoMachineId']); if (mongoMachineId >= 0 && mongoMachineId <= 16777215) { machine = Math.floor(localStorage['mongoMachineId']); } // Just always stick the value in. localStorage['mongoMachineId'] = machine; document.cookie = 'mongoMachineId=' + machine + ';expires=Tue, 19 Jan 2038 05:00:00 GMT' } else { var cookieList = document.cookie.split('; '); for (var i in cookieList) { var cookie = cookieList[i].split('='); if (cookie[0] == 'mongoMachineId' && cookie[1] >= 0 && cookie[1] <= 16777215) { machine = cookie[1]; break; } } document.cookie = 'mongoMachineId=' + machine + ';expires=Tue, 19 Jan 2038 05:00:00 GMT'; } return function () { if (!(this instanceof ObjectId)) { return new ObjectId(arguments[0], arguments[1], arguments[2], arguments[3]).toString(); } if (typeof (arguments[0]) == 'object') { this.timestamp = arguments[0].timestamp; this.machine = arguments[0].machine; this.pid = arguments[0].pid; this.increment = arguments[0].increment; } else if (typeof (arguments[0]) == 'string' && arguments[0].length == 24) { this.timestamp = Number('0x' + arguments[0].substr(0, 8)), this.machine = Number('0x' + arguments[0].substr(8, 6)), this.pid = Number('0x' + arguments[0].substr(14, 4)), this.increment = Number('0x' + arguments[0].substr(18, 6)) } else if (arguments.length == 4 && arguments[0] != null) { this.timestamp = arguments[0]; this.machine = arguments[1]; this.pid = arguments[2]; this.increment = arguments[3]; } else { this.timestamp = Math.floor(new Date().valueOf() / 1000); this.machine = machine; this.pid = pid; if (increment > 0xffffff) { increment = 0; } this.increment = increment++; } }; })(); ObjectId.prototype.getDate = function () { return new Date(this.timestamp * 1000); } /** * Turns a WCF representation of a BSON ObjectId into a 24 character string representation. */ ObjectId.prototype.toString = function () { var timestamp = this.timestamp.toString(16); var machine = this.machine.toString(16); var pid = this.pid.toString(16); var increment = this.increment.toString(16); return '00000000'.substr(0, 6 - timestamp.length) + timestamp + '000000'.substr(0, 6 - machine.length) + machine + '0000'.substr(0, 4 - pid.length) + pid + '000000'.substr(0, 6 - increment.length) + increment; }
JavaScript
0.000002
@@ -2983,16 +2983,17 @@ 1000);%0A%7D +; %0A%0A/**%0A* @@ -3556,9 +3556,10 @@ ement;%0A%7D +; %0A
4ac850b7bfbda143572942ec8f962632fd48f22b
Fix session being sought on res
lib/middleware/authBot.js
lib/middleware/authBot.js
var r = require('rethinkdb'); var redditBot = require('../reddit/contexts/bot.js'); module.exports = function authBotCtor(cfg, env) { var botAuthReddit = redditBot(cfg); return function authBot(req, res, next) { botAuthReddit.auth(req.query.code).then(function (refreshToken) { return botAuthReddit.deauth() .then(function(){ return r.table('users').get(cfg.botName) .update({refreshToken: refreshToken}).run(env.conn); }) .then(function () { // "log out" and redirect to the index // so we can log in as ourselves delete res.session.username; delete res.session.bot; res.redirect('/'); },next); }); }; };
JavaScript
0
@@ -585,33 +585,33 @@ delete re -s +q .session.usernam @@ -630,17 +630,17 @@ elete re -s +q .session
61a79ee4d9eebea667fc5398d7b73b2bb4efc03b
Fix the bug of css()
lib/plugins/helper/css.js
lib/plugins/helper/css.js
var extend = require('../../extend'), root = hexo.config.root; extend.helper.register('css', function(path){ if (!Array.isArray) path = [path]; var result = []; path.forEach(function(item){ if (item.substr(item.length - 4, 4) !== '.css') item += '.css'; if (item.substr(0, 1) !== '/') item += root; result.push('<link rel="stylesheet" href="' + item + '" type="text/css">'); }); return result.join('\n'); });
JavaScript
0.00005
@@ -125,16 +125,22 @@ .isArray +(path) ) path = @@ -312,15 +312,21 @@ tem -+ = root + + item ;%0A%0A @@ -442,8 +442,9 @@ n');%0A%7D); +%0A
3cd20707461c14205a7d5889d52f7128785d2f35
Reverted the hardcoded UUID
lib/startup/SetupAdmin.js
lib/startup/SetupAdmin.js
var UserManager = require('../UserManager') , orm = require('../orm') , magnetId = require('node-uuid'); var SetupAdmin = function(){ orm.model('User').find({ where : { email : "[email protected]" } }).success(function(user){ if(!user){ // create a test user if it does not already exist UserManager.create({ email : "[email protected]", firstName : "Manager", lastName : "One", companyName : "Magnet Systems, Inc.", password : "test", userType : 'admin', magnetId : '72150120-2746-11e3-acbe-71879d0cf3c3' }, function(e){ if(e){ console.error('User: error creating test user: '+e); }else{ console.info('User: test user created: [email protected]/test'); } }); } }); }; new SetupAdmin();
JavaScript
0.99983
@@ -665,46 +665,21 @@ : -'72150120-2746-11e3-acbe-71879d0cf3c3' +magnetId.v1() %0A
b35e30fecd3023e2b8a6596cdc3641eaea99a1c9
make z-index work with overworld
lib/systems/draw-image.js
lib/systems/draw-image.js
"use strict"; function drawEntity(data, entity, context) { var image = data.images.get(entity.image.name); if (!image) { console.error("No such image", entity.image.name); return; } try { context.drawImage( image, entity.image.sourceX, entity.image.sourceY, entity.image.sourceWidth, entity.image.sourceHeight, entity.image.destinationX + entity.position.x, entity.image.destinationY + entity.position.y, entity.image.destinationWidth, entity.image.destinationHeight ); } catch (e) { console.error("Error drawing image", entity.image.name, e); } } module.exports = function(ecs, data) { ecs.add(function(entities, context) { var keys = Object.keys(entities); keys.sort(function(a, b) { var za = entities[a].zindex || 0; var zb = entities[b].zindex || 0; return za - zb; }); for (var i = 0; i < keys.length; i++) { var entity = entities[keys[i]]; if (entity.image === undefined || entity.position === undefined) { continue; } drawEntity(data, entity, context); } }); };
JavaScript
0.000001
@@ -741,16 +741,17 @@ ar za = +( entities @@ -760,25 +760,42 @@ %5D.zindex %7C%7C -0 +%7Bzindex:0%7D).zindex ;%0A%09%09%09var zb @@ -796,16 +796,17 @@ ar zb = +( entities @@ -819,17 +819,34 @@ ndex %7C%7C -0 +%7Bzindex:0%7D).zindex ;%0A%09%09%09ret
57a02c2735c3e015f6c813085724284bf45fd71b
fix lib/topic-filter/sorts.js for es5
lib/topic-filter/sorts.js
lib/topic-filter/sorts.js
export default { 'closing-soon': { name: 'closing-soon', label: 'sorts.closing-soon', sort: function (a, b) { if (!a.closingAt && !b.closingAt) { // If closingAt isn't defined in both, they're equal return 0; } // undefined closingAt always goes last // b goes first in this case if (!a.closingAt) { return 1; } // undefined closingAt always goes last // a goes first in this case if (!b.closingAt) { return -1; } // Closest date first return new Date(a.closingAt) - new Date(b.closingAt); } }, 'newest-first': { name: 'newest-first', label: 'sorts.newest-first', sort: function (a, b) { // Newest dates first return new Date(b.publishedAt) - new Date(a.publishedAt); } }, 'oldest-first': { name: 'oldest-first', label: 'sorts.oldest-first', sort: function (a, b) { // Oldest dates first return new Date(a.publishedAt) - new Date(b.publishedAt); } }, 'recently-updated': { name: 'recently-updated', label: 'sorts.recently-updated', sort: function (a, b) { // Newest dates first return new Date(b.updatedAt) - new Date(a.updatedAt); } } };
JavaScript
0.000002
@@ -1,18 +1,20 @@ -export default +module.exports = %7B%0A
11df970342d2e3c05ab9f234ea39265e80f72139
Update tr_TR.js
lib/translations/tr_TR.js
lib/translations/tr_TR.js
// Turkish jQuery.extend( jQuery.fn.pickadate.defaults, { monthsFull: [ 'Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık' ], monthsShort: [ 'Oca', 'Şub', 'Mar', 'Nis', 'May', 'Haz', 'Tem', 'Ağu', 'Eyl', 'Eki', 'Kas', 'Ara' ], weekdaysFull: [ 'Pazar', 'Pazartesi', 'Salı', 'Çarşamba', 'Perşembe', 'Cuma', 'Cumartesi' ], weekdaysShort: [ 'Pzr', 'Pzt', 'Sal', 'Çrş', 'Prş', 'Cum', 'Cmt' ], today: 'bugün', clear: 'sil', firstDay: 1, format: 'dd mmmm yyyy dddd', formatSubmit: 'yyyy/mm/dd' });
JavaScript
0.000001
@@ -469,17 +469,17 @@ today: ' -b +B ug%C3%BCn',%0A @@ -489,17 +489,17 @@ clear: ' -s +S il',%0A
88043722b223b8fd1c9cb82bf55a484ba68d637b
increase port polling timeout (#638)
lib/utils/port-polling.js
lib/utils/port-polling.js
'use strict'; const net = require('net'); const errors = require('../errors'); module.exports = function portPolling(options) { options = Object.assign({ timeoutInMS: 1000, maxTries: 20, delayOnConnectInMS: 3 * 1000, logSuggestion: 'ghost log', socketTimeoutInMS: 1000 * 30 }, options || {}); if (!options.port) { return Promise.reject(new errors.CliError({ message: 'Port is required.' })); } const connectToGhostSocket = (() => { return new Promise((resolve, reject) => { const ghostSocket = net.connect(options.port); let delayOnConnectTimeout; // inactivity timeout ghostSocket.setTimeout(options.socketTimeoutInMS); ghostSocket.on('timeout', (() => { if (delayOnConnectTimeout) { clearTimeout(delayOnConnectTimeout); } ghostSocket.destroy(); // force retry const err = new Error(); err.retry = true; reject(err); })); ghostSocket.on('connect', (() => { if (options.delayOnConnectInMS) { let ghostDied = false; // CASE: client closes socket ghostSocket.on('close', (() => { ghostDied = true; })); delayOnConnectTimeout = setTimeout(() => { ghostSocket.destroy(); if (ghostDied) { reject(new Error('Ghost died.')); } else { resolve(); } }, options.delayOnConnectInMS); return; } ghostSocket.destroy(); resolve(); })); ghostSocket.on('error', ((err) => { ghostSocket.destroy(); err.retry = true; reject(err); })); }); }); const startPolling = (() => { return new Promise((resolve, reject) => { let tries = 0; (function retry() { connectToGhostSocket() .then(() => { resolve(); }) .catch((err) => { if (err.retry && tries < options.maxTries) { tries = tries + 1; setTimeout(retry, options.timeoutInMS); return; } reject(new errors.GhostError({ message: 'Ghost did not start.', suggestion: options.logSuggestion, err: err })); }); }()); }); }); return startPolling(); };
JavaScript
0
@@ -174,17 +174,17 @@ utInMS: -1 +2 000,%0A @@ -234,17 +234,17 @@ MS: 3 * -1 +2 000,%0A @@ -310,17 +310,17 @@ 1000 * -3 +6 0%0A %7D,
8ade1ceb32088d6068c89d819e151e2a1a3f940b
Fix jshint warning
tasks/lib/htmlprocessor.js
tasks/lib/htmlprocessor.js
/* * grunt-processhtml * https://github.com/dciccale/grunt-processhtml * * Copyright (c) 2013-2014 Denis Ciccale (@tdecs) * Licensed under the MIT license. * https://github.com/dciccale/grunt-processhtml/blob/master/LICENSE-MIT */ 'use strict'; var grunt = require('grunt'); var path = require('path'); var utils = require('./utils'); var getBlocks = function (content, marker) { /* * <!-- build:<type>[:target] [value] --> * - type (required) js, css, href, remove, template * - target|attribute i.e. dev, release or [href] [src] * - value (optional) i.e. script.min.js */ var regbuild = new RegExp('<!--\\s*' + marker + ':(\\[?[\\w-]+\\]?)(?::([\\w,]+))?(?:\\s*([^\\s]+)\\s*-->)*'); // <!-- /build --> var regend = new RegExp('(?:<!--\\s*)*\\/' + marker + '\\s*-->'); // Normalize line endings and split in lines var lines = content.replace(/\r\n/g, '\n').split(/\n/); var inside = false; var sections = []; var block; lines.forEach(function (line) { var build = line.match(regbuild); var endbuild = regend.test(line); var attr; if (build) { inside = true; attr = build[1].match(/(?:\[([\w-]+)\])*/)[1]; block = { type: attr ? 'attr': build[1], attr: attr, targets: !!build[2] ? build[2].split(',') : null, asset: build[3], indent: /^\s*/.exec(line)[0], raw: [] }; } if (inside && block) { block.raw.push(line); } if (inside && endbuild) { inside = false; sections.push(block); } }); return sections; }; var getBlockTypes = function (options, filePath) { return { replaceAsset: function (content, block, blockLine, asset) { return content.replace(blockLine, block.indent + asset); }, css: function (content, block, blockLine, blockContent) { return this.replaceAsset(content, block, blockLine, '<link rel="stylesheet" href="' + block.asset + '">'); }, js: function (content, block, blockLine, blockContent) { return this.replaceAsset(content, block, blockLine, '<script src="' + block.asset + '"><\/script>'); }, attr: function (content, block, blockLine, blockContent) { // Only run attr replacer for the block content var re = new RegExp('(\\s*(?:' + block.attr + ')=[\'"])(.*)?(".*)', 'gi'); var replacedBlock = blockContent.replace(re, function (wholeMatch, start, asset, end) { // Check if only the path was provided to leave the original asset name intact asset = (!path.extname(block.asset) && /\//.test(block.asset))? block.asset + path.basename(asset) : block.asset; return start + asset + end; }); return content.replace(blockLine, replacedBlock); }, remove: function (content, block, blockLine, blockContent) { var blockRegExp = utils.blockToRegExp(blockLine); return content.replace(blockRegExp, ''); }, template: function (content, block, blockLine, blockContent) { var compiledTmpl = utils.template(blockContent, options); // Clean template output and fix indent compiledTmpl = block.indent + grunt.util._.trim(compiledTmpl).replace(/([\r\n])\s*/g, '$1' + block.indent); return content.replace(blockLine, compiledTmpl); }, include: function (content, block, blockLine, blockContent) { var base = options.includeBase || path.dirname(filePath); var filepath = path.join(base, block.asset); var l = blockLine.length; var fileContent, i; if (grunt.file.exists(filepath)) { fileContent = block.indent + grunt.file.read(filepath); while ((i = content.indexOf(blockLine)) !== -1) { content = content.substring(0, i) + fileContent + content.substring(i + l); } } return content; } }; }; var HTMLProcessor = module.exports = function (content, options, filePath) { this.content = content; this.target = options.data.environment; this.linefeed = /\r\n/g.test(content) ? '\r\n' : '\n'; this.blocks = getBlocks(content, options.commentMarker); this.blockTypes = getBlockTypes(options, filePath); this.strip = options.strip === true; }; HTMLProcessor.prototype._replace = function (block, content) { var blockLine = block.raw.join(this.linefeed); var blockContent = block.raw.slice(1, -1).join(this.linefeed); var result = this.blockTypes[block.type](content, block, blockLine, blockContent); return result; }; HTMLProcessor.prototype._strip = function (block, content) { var blockLine = block.raw.join(this.linefeed); var blockRegExp = utils.blockToRegExp(blockLine); var blockContent = block.raw.slice(1, -1).join(this.linefeed); var result = content.replace(blockRegExp, '\n\n' + blockContent); return result; }; HTMLProcessor.prototype.process = function () { var result = this.content; grunt.util._.each(this.blocks, function (block) { // Parse through correct block type also checking the build target if (this.blockTypes[block.type] && (!block.targets || grunt.util._.indexOf(block.targets, this.target) >= 0)) { result = this._replace(block, result); } else if (this.strip) { result = this._strip(block, result); } }, this); return result; };
JavaScript
0.000005
@@ -1160,16 +1160,17 @@ ?:%5C%5B(%5B%5Cw +%5C -%5D+)%5C%5D)*
9668ea0efae86ab6426b0edffa4890a35fd65c7e
update config file
config/config.js
config/config.js
var path = require('path'), rootPath = path.normalize(__dirname + '/..'); module.exports = function (app) { app.site = { name : "{{name}}", // the name of you app } app.config = { port : 3000, // port to run the server on prettify : { html : true, // whether to pretify html }, engines : { html: "{{html}}", // jade, ejs, haml, hjs (hogan) css: "{{css}}", // styles, sass, less }, root : rootPath, db : { url : "mongodb://localhost/db-name" // url to database }, jsonp : true, // allow jsonp requests secret : 'MYAPPSECRET', protocol : 'http://', autoLoad : false, // whether to autoload controllers & models } // some default meta setting for head app.site.meta = { description : '', keywords : '', viewport : 'width=device-width, user-scalable=yes, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0', encoding : "utf-8" } }
JavaScript
0.000001
@@ -389,36 +389,43 @@ // +options: %5B jade -, ejs, +%7Cejs%7C haml -, hjs (hogan) +%7Chjs%7Cjshtml%5D %0A @@ -456,26 +456,35 @@ // -styles, +options: %5Bstylus%7C sass -, +%7C less +%5D %0A
4679901133f017feb3ec7d29faabd238681d833e
clean up
config/config.js
config/config.js
module.exports = { development: { db: 'mongodb://localhost/wo', app: { name: 'WO Portal' }, smtp: 'smtp.ecs.soton.ac.uk', //smtp server used for pass reset/newsletter recap_pbk: '6LfwcOoSAAAAACeZnHuWzlnOCbLW7AONYM2X9K-H', //recaptcha public key recap_prk: '6LfwcOoSAAAAAGFI7h_SJoCBwUkvpDRf7_r8ZA_D', //recaptcha private key facebook: { clientID: "", //clientID clientSecret: "", //clientSecret callbackURL: "" //http://localhost:3000/auth/facebook/callback }, oauth: { tokenLife: 3600 } } };
JavaScript
0.000001
@@ -144,28 +144,8 @@ p: ' -smtp.ecs.soton.ac.uk ', / @@ -212,48 +212,8 @@ k: ' -6LfwcOoSAAAAACeZnHuWzlnOCbLW7AONYM2X9K-H ', / @@ -258,262 +258,34 @@ k: ' -6LfwcOoSAAAAAGFI7h_SJoCBwUkvpDRf7_r8ZA_D', //recaptcha private key%0A facebook: %7B%0A clientID: %22%22, //clientID%0A clientSecret: %22%22, //clientSecret%0A callbackURL: %22%22 //http://localhost:3000/auth/facebook/callback%0A %7D, +', //recaptcha private key %0A
71da678f0d6d5dfeb0b81c5972ab6e4fc629db86
Remove redundant methods / branches
js/components/DoughBaseComponent.js
js/components/DoughBaseComponent.js
define([], function () { 'use strict'; /** * This is used as the base class for all modules. * All modules/components should extend this class. * * Includes: * event binding/triggering * logging * i18n library */ function DoughBaseComponent($el, config) { if (!$el || !$el.length) { throw "Element not supplied to DoughBaseComponent constructor"; } this.config = config || {}; this.componentName = this.config.componentName; this.setElement($el); /* Populate this array with the data attributes this module will use. Exclude 'data-dough-' prefix, as this is automatically added. For example: ['collapsible', 'only-first'] */ this.attrs = []; this._bindUiEvents(this.uiEvents || {}); return this; } /** * Extend DoughBaseComponent class using the supplied constructor * @param {function} Subclass * @param {function} [Superclass] - if not supplied, defaults to DoughBaseComponent */ DoughBaseComponent.extend = function (Subclass, Superclass) { var Super = Superclass || DoughBaseComponent; function TempConstructor() { } TempConstructor.prototype = Super.prototype; Subclass.prototype = new TempConstructor(); Subclass.prototype.constructor = Subclass; Subclass.baseConstructor = Super; Subclass.superclass = Super.prototype; }; var DoughBaseComponentProto = DoughBaseComponent.prototype; /** * Set the parent element for this context. * @param {[type]} $el [description] */ DoughBaseComponentProto.setElement = function ($el) { this.$el = $el; return this; }; /** * Fetch the parent element * @return {Array} jQuery object or empty array (for safe jQuery ops) */ DoughBaseComponentProto.getElement = function () { return this.$el || []; }; /** * Get attribute from data attributes on element. * @param {[type]} attr [description] * @return {[type]} [description] */ DoughBaseComponentProto.attr = function (attr) { return this.getElement().attr('data-dough-' + attr); }; /** * All DoughBaseComponents (if applicable) should have this method, * which will unbind all events it attached when initialising itself. * * After this has been run, you can safely run 'delete [[instance]]' to remove it from memory. * * @return {[type]} */ DoughBaseComponentProto.destroy = function () { return this; }; /** * Set callbacks, where `this.events` is a hash of * * {"event selector": "callback"}* * * { * 'mousedown .title': 'edit', * 'click .button': 'save', * 'click .open': function(e) { ... } * } * * pairs. Callbacks will be bound to the view, with `this` set properly. * Uses event delegation for efficiency. * Omitting the selector binds the event to `this.el`. * This only works for delegate-able events: not `focus`, `blur`, and * not `change`, `submit`, and `reset` in Internet Explorer. * * Adapted from the equivalent function in BackboneJS - http://backbonejs.org/#View-delegateEvents * * @param events * @returns {DoughBaseComponent} */ DoughBaseComponentProto._bindUiEvents = function (events) { var delegateEventSplitter = /^(\S+)\s*(.*)$/; if (!events) return this; this._unbindUiEvents(); for (var key in events) { var method = events[key]; if (typeof method !== 'function') { method = this[events[key]]; } if (!method) continue; var match = key.match(delegateEventSplitter); var eventName = match[1], selector = match[2]; method = $.proxy(method, this); eventName += '.boundUiEvents'; if (selector === '') { this.$el.on(eventName, method); } else { this.$el.on(eventName, selector, method); } } return this; }; /** * Clears all callbacks previously bound to the component with `delegateEvents`. * @returns {DoughBaseComponent} */ DoughBaseComponentProto._unbindUiEvents = function () { this.$el.off('.boundUiEvents'); return this; }; /** * Indicate that the component initialised successfully, passing its component name. The resolved * promise will be fed back to the component loader * @private */ DoughBaseComponentProto._initialisedSuccess = function(initialised) { this.$el.attr('data-dough-initialised', 'yes'); initialised && initialised.resolve(this.componentName); }; /** * Indicate that the component failed to initialise, passing its component name. The rejected * promise will be fed back to the component loader * @private */ DoughBaseComponentProto._initialisedFailure = function(initialised) { initialised && initialised.reject(this.componentName); }; return DoughBaseComponent; });
JavaScript
0.00004
@@ -1640,468 +1640,8 @@ %7D;%0A%0A - /**%0A * Fetch the parent element%0A * @return %7BArray%7D jQuery object or empty array (for safe jQuery ops)%0A */%0A DoughBaseComponentProto.getElement = function () %7B%0A return this.$el %7C%7C %5B%5D;%0A %7D;%0A%0A /**%0A * Get attribute from data attributes on element.%0A * @param %7B%5Btype%5D%7D attr %5Bdescription%5D%0A * @return %7B%5Btype%5D%7D %5Bdescription%5D%0A */%0A DoughBaseComponentProto.attr = function (attr) %7B%0A return this.getElement().attr('data-dough-' + attr);%0A %7D;%0A%0A /* @@ -1712,16 +1712,16 @@ method,%0A + * whi @@ -1915,24 +1915,24 @@ ype%5D%7D%0A */%0A - DoughBaseC @@ -1965,24 +1965,52 @@ nction () %7B%0A + this._unbindUiEvents();%0A return t @@ -2990,80 +2990,8 @@ od = - events%5Bkey%5D;%0A if (typeof method !== 'function') %7B%0A method = thi @@ -3006,24 +3006,16 @@ %5Bkey%5D%5D;%0A - %7D%0A if
c7ac33659bc02b1229b188d8296e44e399cfa85a
Fix vote import
cli/_lib/votes.js
cli/_lib/votes.js
// Import forum votes // 'use strict'; const Promise = require('bluebird'); const co = require('co'); const mongoose = require('mongoose'); const progress = require('./utils').progress; const POST = 1; // content type for posts module.exports = co.wrap(function* (N) { // // Establish MySQL connection // let conn = yield N.vbconvert.getConnection(); // // Fetch all users // let users = {}; (yield N.models.users.User.find().lean(true)).forEach(user => { users[user.hid] = user; }); let rows = yield conn.query('SELECT count(*) AS count FROM votes'); let bar = progress(' votes :current/:total [:bar] :percent', rows[0].count); let userids = yield conn.query(` SELECT fromuserid FROM votes GROUP BY fromuserid ORDER BY fromuserid ASC `); yield Promise.map(userids, co.wrap(function* (row) { // ignore votes casted by deleted users if (!users[row.fromuserid]) return; let rows = yield conn.query(` SELECT targetid,vote,fromuserid,touserid,date FROM votes WHERE fromuserid = ? AND contenttypeid = ? `, [ row.fromuserid, POST ]); let bulk = N.models.users.Vote.collection.initializeUnorderedBulkOp(); let count = 0; for (var i = 0; i < rows; i++) { bar.tick(); // ignore votes casted for deleted users if (!users[row.touserid]) continue; let post_mapping = yield N.models.vbconvert.PostMapping.findOne({ mysql_id: row.targetid }).lean(true); count++; bulk.find({ from: users[row.fromuserid]._id, to: users[row.touserid]._id, 'for': post_mapping.post_id, type: N.models.users.Vote.types.FORUM_POST }).upsert().update({ $setOnInsert: { _id: new mongoose.Types.ObjectId(row.date), from: users[row.fromuserid]._id, to: users[row.touserid]._id, 'for': post_mapping.post_id, type: N.models.users.Vote.types.FORUM_POST, hb: users[row.fromuserid].hb, value: Number(row.vote) } }); } if (!count) return; yield new Promise((resolve, reject) => { bulk.execute(err => err ? reject(err) : resolve()); }); }), { concurrency: 100 }); bar.terminate(); conn.release(); N.logger.info('Vote import finished'); });
JavaScript
0.000001
@@ -855,14 +855,66 @@ n* ( -row) %7B +userid_row) %7B%0A let fromuserid = userid_row.fromuserid;%0A %0A @@ -965,28 +965,24 @@ if (!users%5B -row. fromuserid%5D) @@ -1152,20 +1152,16 @@ %60, %5B -row. fromuser @@ -1282,11 +1282,11 @@ or ( -var +let i = @@ -1297,16 +1297,23 @@ i %3C rows +.length ; i++) %7B @@ -1309,24 +1309,50 @@ gth; i++) %7B%0A + let row = rows%5Bi%5D;%0A%0A bar.ti @@ -1551,16 +1551,16 @@ argetid%0A - %7D) @@ -1569,24 +1569,113 @@ ean(true);%0A%0A + // voted for non-existent or not imported post%0A if (!post_mapping) continue;%0A%0A count+
1bd50fab517a8644973f20fbe0a007b0497a3416
Add some comments to index.
lib/Index.js
lib/Index.js
var runCallback = require('./common.js').runCallback; var crypto = require('crypto'); /** * XXX THIS CLASS IS NOT READY. DO NOT USE. * Todo: figure out how to clean up when an indexed field changes value. (I.e. delete the old entry.) * Todo: implement purge * Note: this adds a private property for original index value in _indexValues * Note: Index value removal is done asynchronously because its result doesn't matter (much). */ function Index(obj, field) { var save = obj.prototype.save; var fromObject = obj.prototype.fromObject; var del = obj.prototype.delete; var indexValue; var getter = "getBy" + field.substr(0, 1).toUpperCase() + field.substr(1); /** * Key the key at which the index for the field and value will be stored. */ function getKey(value) { var hash = crypto.createHash('sha256'); hash.update(value || indexValue); var bucket = hash.digest('hex').substr(0, 8); return obj.getKey("ix:" + field + ":" + bucket); } /** * Wrap the save function with a function that adds to the index. */ obj.prototype.save = function(callback) { var self = this; save.call(self, function(err, result) { if (err) return runCallback(callback, err, result); /* Try to remove the old index. Failure is non-fatal. */ if (indexValue && indexValue != self[field]) { obj.client.srem(getKey(), self.id); } indexValue = self[field]; /* Track the new value */ obj.client.sadd(getKey(), self.id, function(err, result) { if (err) return runCallback(callback, err, result); runCallback(callback, err, true); }); }); }; obj.prototype.fromObject = function(src) { indexValue = (typeof(src[field]) !== undefined) ? src[field] : undefined; fromObject.call(this, src); }; obj.prototype.delete = function(callback) { /* Remove the index key. Failure is non-fatal. */ obj.client.srem(getKey(), this.id); del.call(this, callback); }; /**/ obj[getter] = function(value, callback) { obj.client.smembers(getKey(value), function(err, result) { if (err) return runCallback(callback, err, result); if (!result.length) return runCallback(callback, err, result); obj.get(result, function(err, result) { var instances = []; for (var i = 0; i < result.length; i++) { if (!result[i]) continue; /* No longer exists. */ if (result[i][field] == value) { instances.push(result[i]); } } runCallback(callback, err, instances); }); }); } } module.exports = Index;
JavaScript
0
@@ -461,16 +461,57 @@ ield) %7B%0A + /* Back up functions we're wrapping */%0A var sa @@ -535,16 +535,16 @@ e.save;%0A - var fr @@ -621,23 +621,140 @@ %0A%0A -var indexValue; +/* A local value to store the existing value of the indexed field. */%0A var indexValue;%0A%0A /* The name of the getter we're adding */ %0A v
4383067a6f6b34f768340725b9d37ea240b4bc1a
make check show originalGameId
cli/cmds/check.js
cli/cmds/check.js
/* * Copyright 2014, Gregg Tavares. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Gregg Tavares. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ "use strict"; var gameInfo = require('../../lib/gameinfo'); var path = require('path'); var Promise = require('promise'); var check = function(args) { return new Promise(function(resolve, reject) { try { var runtimeInfo = gameInfo.readGameInfo(process.cwd()); } catch (e) { console.error(e); reject(); return; } console.log("name : " + runtimeInfo.info.name); console.log("gameId : " + runtimeInfo.info.happyFunTimes.gameId); console.log("type : " + runtimeInfo.info.happyFunTimes.gameType); console.log("version : " + runtimeInfo.info.version); console.log("api version: " + runtimeInfo.info.happyFunTimes.apiVersion); console.log(""); console.log("looks ok"); resolve(); }); }; exports.usage = { prepend: "check's the game in the current folder some requirements", options: [ ] }; exports.cmd = check;
JavaScript
0
@@ -2002,32 +2002,95 @@ gameId : %22 + + runtimeInfo.originalGameId);%0A console.log(%22runtimeId : %22 + runtimeInfo.inf
0c33f054ffb968c9f3fc81d4d74fe1050c2ac5ab
Improve comment
lib/Space.js
lib/Space.js
// // Space. The root item. // var Path = require('./geom/Path') var Vector = require('./geom/Vector') var IPath = require('./geom/IPath') var AbstractPlane = require('./AbstractPlane') var extend = require('extend') var Space = function () { AbstractPlane.call(this) // Space has constant identity transformation _T } var p = extend({}, AbstractPlane.prototype) Space.prototype = p p.atMid = function () { // Get a Vector to the centroid of the bounding convex hull. // Rather computationally intensive. return this.getHull().atMid() } p.setParent = function () { // Remove possibility to add to parent. throw new Error('Space cannot have a parent.') } p.remove = function () { // Silent, already removed. Otherwise would throw the error in setParent } p.getHull = function () { // Get bounding box as an IPath. Equals the convex hull // of the children. Iterates over all children AbstractNodes so keep an eye on // efficiency. // // Return // IPath // If no children, returns a path with single point at origin. // var children = this.getChildren() if (children.length < 1) { return new IPath(new Path([new Vector(0, 0)]), this) } var ip = children.reduce(function (acc, child) { return acc.add(child.getHull()) }, new IPath()) return ip.getHull() } module.exports = Space
JavaScript
0
@@ -923,16 +923,21 @@ so keep +%0A // an eye @@ -938,21 +938,16 @@ n eye on -%0A // efficie
ff2aa48b8d221080ae9901f94622e5dbc32807e9
Implement billy.build
lib/billy.js
lib/billy.js
var fs = require('fs'); function loadConfig(path) { return JSON.parse(fs.readFileSync(path, 'utf8')); } exports.init = function(configFile, outdir) { var config = loadConfig(configFile), moduleList = []; for (var name in config.modules) { moduleList.push(name); } return { build: function(moduleName, callback) { }, watch: function(moduleName, callback) { } }; };
JavaScript
0.000012
@@ -1,363 +1,1403 @@ var -fs = require('fs');%0A%0Afunction loadConfig(path) %7B%0A return JSON.parse(fs.readFileSync(path, 'utf8'));%0A%7D%0Aexports.init = function(configFile, outdir) %7B%0A var config = loadConfig(configFile),%0A moduleList = %5B%5D;%0A%0A for (var name in config.modules) %7B%0A moduleList.push(name);%0A %7D%0A%0A return %7B%0A build: function(moduleName, callback) %7B +combine = require('./jsCombine'),%0A fs = require('fs'),%0A templateUtil = require('./templateUtil');%0A%0Afunction loadConfig(path) %7B%0A return JSON.parse(fs.readFileSync(path, 'utf8'));%0A%7D%0Afunction explodeViews(module, config) %7B%0A var views = config.views,%0A loadedTemplates = %7B%7D,%0A ret = %5B%5D;%0A%0A for (var i = 0, len = module.length; i %3C len; i++) %7B%0A var resource = module%5Bi%5D;%0A ret.push(resource);%0A%0A if (views%5Bresource%5D) %7B%0A views%5Bresource%5D.forEach(function(template) %7B%0A var generator = function(callback) %7B%0A templateUtil.loadTemplate(template, config.templateCache, callback);%0A %7D;%0A generator.sourceFile = template;%0A ret.push(generator);%0A %7D);%0A %7D%0A %7D%0A return ret;%0A%7D%0A%0Aexports.init = function(configFile, outdir) %7B%0A var config = loadConfig(configFile),%0A moduleList = %5B%5D;%0A%0A for (var name in config.modules) %7B%0A moduleList.push(name);%0A %7D%0A%0A return %7B%0A build: function(moduleName, callback) %7B%0A var modules = moduleName ? %5BmoduleName%5D : moduleList;%0A modules.forEach(function(name) %7B%0A var resources = explodeViews(config.modules%5Bname%5D, config),%0A moduleName = outdir + '/' + name + '.js';%0A combine.combine(resources, moduleName, callback);%0A %7D); %0A
2bcfcb5b628fe3a602dffdecbedb58c8264664f5
Clean up delta labels
cd/src/pipeline-events-handler/deltas/deltas.js
cd/src/pipeline-events-handler/deltas/deltas.js
const getStackFamily = require('./stack-family'); const getChangeSetFamily = require('./change-set-family'); const deltaArrow = require('./delta-arrow'); const deltaValue = require('./delta-value'); /** * Returns a multi-line string describing the parameters that have changed * @param {ParameterDeltas} deltas * @returns {String} */ function parameterDeltasList(deltas) { if (!deltas.length) { return 'This change set contained no meaningful parameter deltas.'; } // Text blocks within attachments have a 3000 character limit. If the text is // too large, try creating the list without links to reduce the size. const withLinks = deltas .map((d) => { const oldValue = deltaValue(d.parameter, d.stackValue); const arrow = deltaArrow(d); const newValue = deltaValue(d.parameter, d.changeSetValue); return `*${d.stackName}::${d.parameter}*: ${oldValue} ${arrow} ${newValue}`; }) .join('\n'); if (withLinks.length < 2900) { return withLinks; } else { return deltas .map((d) => { const oldValue = deltaValue(d.parameter, d.stackValue, true); const arrow = deltaArrow(d, true); const newValue = deltaValue(d.parameter, d.changeSetValue, true); return `*${d.stackName}::${d.parameter}*: ${oldValue} ${arrow} ${newValue}`; }) .join('\n'); } } module.exports = { async nestedParameterDeltaText(stackName, changeSetName) { const stackFamily = await getStackFamily(stackName); const changeSetFamily = await getChangeSetFamily(stackName, changeSetName); /** @type {ParameterDeltas} */ const deltas = []; // Iterate through all existing stack parameters and create a delta for // each one, which includes the current value. for (const stack of stackFamily) { for (const param of stack.Parameters || []) { deltas.push({ stackName: stack.StackName, stackId: stack.StackId, parameter: param.ParameterKey, stackValue: param.ResolvedValue || param.ParameterValue, changeSetValue: null, }); } } // Iterate through all the change set parameters. If a delta already exists // for a given stack+parameter key, add the value from the change set to // that delta. If not, make a new delta. for (const changeSet of changeSetFamily) { for (const param of changeSet.Parameters || []) { const delta = deltas.find( (d) => param.ParameterKey === d.parameter && changeSet.StackName === d.stackName, ); if (delta) { delta.changeSetValue = param.ResolvedValue || param.ParameterValue; } else { deltas.push({ stackName: changeSet.StackName, stackId: changeSet.StackId, parameter: param.ParameterKey, stackValue: null, changeSetValue: param.ResolvedValue || param.ParameterValue, }); } } } // Filter down to only deltas where the values are different const changeDeltas = deltas.filter( (d) => d.stackValue !== d.changeSetValue, ); // When using nested change sets, not all parameters in nested stacks are // correctly resolved. Any parameter values that depend on a stack or // resource output will be included in the change set parameters with an // unresolved value that looks like "{{IntrinsicFunction:…". Unless or until // AWS makes nested change sets smarter, we have to just ignore these, // because there's no way to compare the actual existing value from the stack // to the hypothetical future value that will be resolved when the change set // executes. // // Any parameters effected by this limitation are filtered out. const cleanedDeltas = changeDeltas.filter( (d) => !(d.changeSetValue || '').match(/\{\{IntrinsicFunction\:/), ); const allowedDeltas = cleanedDeltas.filter( (d) => !['PipelineExecutionNonce', 'TemplateUrlBase'].includes(d.parameter), ); return parameterDeltasList(allowedDeltas); }, };
JavaScript
0.000003
@@ -835,33 +835,102 @@ ue);%0A%0A -return +const label = d.stackName.includes('-root-')%0A ? d.parameter%0A : %60 -* $%7Bd.stackNam @@ -939,32 +939,59 @@ ::$%7Bd.parameter%7D +%60;%0A%0A return %60*$%7Blabel%7D *: $%7BoldValue%7D $
3ccabac61d19a71d302542add314c1aa20489b02
Fix typo
lib/buddy.js
lib/buddy.js
var assert = require('assert'); var debug = require('debug')('alloc:buddy'); var util = require('util'); function log2(x) { return Math.log(x) / Math.LN2; } function power2(x) { return 1 << (log2(x - 1) + 1); } var BuddyAllocator = function(buffer, options) { if (typeof buffer == 'number') { buffer = new Buffer(power2(buffer)); } assert(buffer.length > 1 && !(buffer.length & (buffer.length - 1)), 'Buffer length must be a positive power of 2'); options = util._extend({minBuddySize: 1}, options); this.buffer = buffer; this.minRank = log2(options.minSize) | 0; this.minSize = 1 << this.minRank; // Maintain fragmentation statistics. this.bytesTotal = this.buffer.length; this.bytesAllocated = 0; this.bytesWasted = 0; // Maintain a free list for each block size. this.freelist = []; for (var i = 0; i < log2(this.buffer.length) - this.minRank; i++) { this.freelist.push([]); } this.freelist.push([0]); }; BuddyAllocator.prototype.rank = function(x) { return Math.max(0, ((log2(x - 1) + 1) | 0) - this.minRank); }; BuddyAllocator.prototype.alloc = function(size) { // Find the first unallocated block of sufficient size. for (var i = this.rank(size); i < this.freelist.length; i++) { if (this.freelist[i].length) { var offset = this.freelist[i].pop(); var half; // Split the block recursively until it is just big enough. for (half = 1 << (i + this.minRank - 1); half >= size && i > 0; half >>= 1) { var buddy = offset + half; this.freelist[--i].push(buddy); debug('split @%d, buddy @%d', offset, buddy); } var wasted = (half << 1) - size; this.bytesAllocated += size; this.bytesWasted += wasted; debug('alloc @%d, used %d bytes, wasted %d bytes', offset, size, wasted); return this.buffer.slice(offset, offset + size); } } return null; }; BuddyAllocator.prototype.free = function(block) { // Find the offset within parent buffer. var offset = block.offset - this.buffer.offset; var rank = this.rank(block.length); var reclaimed = 1 << (rank + this.minRank); this.bytesAllocated -= block.length; this.bytesWasted -= reclaimed - block.length; debug('free @%d, reclaiming %d bytes', offset, reclaimed); // Merge recursively until we exhaust all unallocated buddies. for (var i = rank; i < this.freelist.length - 1; i++) { var buddy = offset ^ (1 << (i + this.minRank)); var merged = false; for (var j = 0; j < this.freelist[i].length; j++) { if (this.freelist[i][j] == buddy) { debug('merge @%d, buddy @%d', offset, buddy); merged = this.freelist[i].splice(j, 1); if (offset > buddy) { offset = buddy; } break; } } if (!merged) { break; } } this.freelist[i].push(offset); }; module.exports = BuddyAllocator;
JavaScript
0.999999
@@ -497,21 +497,16 @@ end(%7Bmin -Buddy Size: 1%7D
7f5735f30e133c937cad495bbf527ca4d305d777
return promise rejection in build.js
lib/build.js
lib/build.js
var mkdirp = require('mkdirp') var Promise = require('es6-promise').Promise var fs = require('fs') var path = require('path') function writeFile (page) { return new Promise(function (resolve, reject) { var dir = path.dirname(page.dest) mkdirp(dir, function (err) { if (err) { return reject(err) } fs.writeFile(page.dest, page.contents, function (err) { if (err) { reject(err) } return resolve(page.dest) }) }) }) } function build (pages) { var builtPages = pages.map(writeFile) return Promise.all(builtPages) } module.exports = build
JavaScript
0.000001
@@ -387,16 +387,23 @@ (err) %7B + return reject(
a850c39f00d3d942c657dac9483139940bdeca9d
converted to entities
js/fireworks-2d.js
js/fireworks-2d.js
'use strict'; function draw_logic(){ for(var firework in fireworks){ canvas_buffer.fillStyle = fireworks[firework]['color']; canvas_buffer.fillRect( fireworks[firework]['x'], fireworks[firework]['y'], fireworks[firework]['width'], fireworks[firework]['height'] ); } } function launch(firework){ var firework = firework || {}; firework['children'] = firework['children'] !== void 0 ? firework['children'] : 10; firework['color'] = firework['color'] || '#' + core_random_hex(); firework['dx'] = firework['dx'] || Math.random() * 4 - 2; firework['dy'] = firework['dy'] || -Math.random() * 2 - canvas_height / 200; firework['height'] = firework['height'] || 4; firework['timer'] = firework['timer'] || core_random_integer({ 'max': 200, }) + 100; firework['width'] = firework['width'] || 4; firework['x'] = firework['x'] || core_mouse['x']; firework['y'] = firework['y'] || canvas_height; fireworks.push(firework); } function logic(){ if(core_mouse['down']){ launch(); } for(var firework in fireworks){ fireworks[firework]['x'] += fireworks[firework]['dx']; fireworks[firework]['y'] += fireworks[firework]['dy']; fireworks[firework]['dy'] += .02; fireworks[firework]['dx'] *= .99; fireworks[firework]['timer'] -= 1; if(fireworks[firework]['timer'] <= 0){ if(fireworks[firework]['children'] > 0){ var loop_counter = fireworks[firework]['children'] - 1; do{ launch({ 'children': 0, 'dx': Math.random() * 3 - 1.5, 'dy': Math.random() * 3 - 1.5, 'x': fireworks[firework]['x'], 'timer': core_random_integer({ 'max': 90, }) + 40, 'y': fireworks[firework]['y'], }); }while(loop_counter--); } fireworks.splice( firework, 1 ); } } } function repo_init(){ core_repo_init({ 'keybinds': { 'all': { 'todo': launch, }, }, 'title': 'Fireworks-2D.htm', }); canvas_init(); } var fireworks = [];
JavaScript
0.999999
@@ -43,36 +43,38 @@ for(var -firework in firework +entity in core_entitie s)%7B%0A @@ -103,34 +103,36 @@ Style = -fireworks%5Bfirework +core_entities%5Bentity %5D%5B'color @@ -181,98 +181,104 @@ -fireworks%5Bfirework%5D%5B'x'%5D,%0A fireworks%5Bfirework%5D%5B'y'%5D,%0A fireworks%5Bfirework +core_entities%5Bentity%5D%5B'x'%5D,%0A core_entities%5Bentity%5D%5B'y'%5D,%0A core_entities%5Bentity %5D%5B'w @@ -295,34 +295,36 @@ -fireworks%5Bfirework +core_entities%5Bentity %5D%5B'heigh @@ -1034,31 +1034,57 @@ -fireworks.push( +core_entity_create(%7B%0A 'properties': firework );%0A%7D @@ -1079,16 +1079,23 @@ firework +,%0A %7D );%0A%7D%0A%0Afu @@ -1179,185 +1179,197 @@ var -firework in fireworks)%7B%0A fireworks%5Bfirework%5D%5B'x'%5D += fireworks%5Bfirework%5D%5B'dx'%5D;%0A fireworks%5Bfirework%5D%5B'y'%5D += fireworks%5Bfirework%5D%5B'dy'%5D;%0A%0A fireworks%5Bfirework +entity in core_entities)%7B%0A core_entities%5Bentity%5D%5B'x'%5D += core_entities%5Bentity%5D%5B'dx'%5D;%0A core_entities%5Bentity%5D%5B'y'%5D += core_entities%5Bentity%5D%5B'dy'%5D;%0A%0A core_entities%5Bentity %5D%5B'd @@ -1388,34 +1388,36 @@ -fireworks%5Bfirework +core_entities%5Bentity %5D%5B'dx'%5D @@ -1433,34 +1433,36 @@ -fireworks%5Bfirework +core_entities%5Bentity %5D%5B'timer @@ -1481,34 +1481,36 @@ if( -fireworks%5Bfirework +core_entities%5Bentity %5D%5B'timer @@ -1534,34 +1534,36 @@ if( -fireworks%5Bfirework +core_entities%5Bentity %5D%5B'child @@ -1609,34 +1609,36 @@ unter = -fireworks%5Bfirework +core_entities%5Bentity %5D%5B'child @@ -1867,34 +1867,36 @@ 'x': -fireworks%5Bfirework +core_entities%5Bentity %5D%5B'x'%5D,%0A @@ -2045,26 +2045,28 @@ y': -fireworks%5Bfirework +core_entities%5Bentity %5D%5B'y @@ -2164,25 +2164,28 @@ -fireworks.splic +core_entity_remov e( +%7B %0A @@ -2195,24 +2195,52 @@ -firework +'entities': %5B%0A entity ,%0A @@ -2247,17 +2247,18 @@ -1 +%5D, %0A @@ -2258,24 +2258,25 @@ +%7D );%0A %7D @@ -2383,22 +2383,63 @@ 'todo': -launch +function()%7B%0A launch();%0A %7D ,%0A @@ -2520,25 +2520,4 @@ ;%0A%7D%0A -%0Avar fireworks = %5B%5D;%0A
2657730cbe8cf718ea93564d887bc30c68ecaeef
Fix emitting "connected" state for stream
js/getUserMedia.js
js/getUserMedia.js
/** * Expose the getUserMedia function. */ module.exports = getUserMedia; /** * Dependencies. */ var debug = require('debug')('iosrtc:getUserMedia'), debugerror = require('debug')('iosrtc:ERROR:getUserMedia'), exec = require('cordova/exec'), MediaStream = require('./MediaStream'), Errors = require('./Errors'); debugerror.log = console.warn.bind(console); function isPositiveInteger(number) { return typeof number === 'number' && number >= 0 && number % 1 === 0; } function isPositiveFloat(number) { return typeof number === 'number' && number >= 0; } function getUserMedia(constraints) { debug('[original constraints:%o]', constraints); var isPromise, callback, errback, audioRequested = false, videoRequested = false, newConstraints = { audio: false, video: false }; if (typeof arguments[1] !== 'function') { isPromise = true; } else { isPromise = false; callback = arguments[1]; errback = arguments[2]; } if ( typeof constraints !== 'object' || (!constraints.hasOwnProperty('audio') && !constraints.hasOwnProperty('video')) ) { if (isPromise) { return new Promise(function (resolve, reject) { reject(new Errors.MediaStreamError('constraints must be an object with at least "audio" or "video" keys')); }); } else { if (typeof errback === 'function') { errback(new Errors.MediaStreamError('constraints must be an object with at least "audio" or "video" keys')); } return; } } if (constraints.audio) { audioRequested = true; newConstraints.audio = true; } if (constraints.video) { videoRequested = true; newConstraints.video = true; } // Example: // // getUserMedia({ // audio: true, // video: { // deviceId: 'qwer-asdf-zxcv', // width: { // min: 400, // max: 600 // }, // frameRate: { // min: 1.0, // max: 60.0 // } // } // }); // Get video constraints if (videoRequested) { // Get requested video deviceId. if (typeof constraints.video.deviceId === 'string') { newConstraints.videoDeviceId = constraints.video.deviceId; } // Get requested min/max width. if (typeof constraints.video.width === 'object') { if (isPositiveInteger(constraints.video.width.min)) { newConstraints.videoMinWidth = constraints.video.width.min; } if (isPositiveInteger(constraints.video.width.max)) { newConstraints.videoMaxWidth = constraints.video.width.max; } } // Get requested min/max height. if (typeof constraints.video.height === 'object') { if (isPositiveInteger(constraints.video.height.min)) { newConstraints.videoMinHeight = constraints.video.height.min; } if (isPositiveInteger(constraints.video.height.max)) { newConstraints.videoMaxHeight = constraints.video.height.max; } } // Get requested min/max frame rate. if (typeof constraints.video.frameRate === 'object') { if (isPositiveFloat(constraints.video.frameRate.min)) { newConstraints.videoMinFrameRate = constraints.video.frameRate.min; } if (isPositiveFloat(constraints.video.frameRate.max)) { newConstraints.videoMaxFrameRate = constraints.video.frameRate.max; } } else if (isPositiveFloat(constraints.video.frameRate)) { newConstraints.videoMinFrameRate = constraints.video.frameRate; newConstraints.videoMaxFrameRate = constraints.video.frameRate; } } debug('[computed constraints:%o]', newConstraints); if (isPromise) { return new Promise(function (resolve, reject) { function onResultOK(data) { debug('getUserMedia() | success'); resolve(MediaStream.create(data.stream)); } function onResultError(error) { debugerror('getUserMedia() | failure: %s', error); reject(new Errors.MediaStreamError('getUserMedia() failed: ' + error)); } exec(onResultOK, onResultError, 'iosrtcPlugin', 'getUserMedia', [newConstraints]); }); } function onResultOK(data) { debug('getUserMedia() | success'); var stream = MediaStream.create(data.stream); callback(stream); // Emit "connected" on the stream. stream.emitConnected(); } function onResultError(error) { debugerror('getUserMedia() | failure: %s', error); if (typeof errback === 'function') { errback(new Errors.MediaStreamError('getUserMedia() failed: ' + error)); } } exec(onResultOK, onResultError, 'iosrtcPlugin', 'getUserMedia', [newConstraints]); }
JavaScript
0
@@ -3540,16 +3540,21 @@ %09%09%09%09 -resolve( +var stream = Medi @@ -3580,16 +3580,103 @@ .stream) +;%0A%09%09%09%09resolve(stream);%0A%09%09%09%09// Emit %22connected%22 on the stream.%0A%09%09%09%09stream.emitConnected( );%0A%09%09%09%7D%0A
b4f6b28b70f0806650576e9ab03b61c297ae66ce
fix email links
lib/email.js
lib/email.js
var url = require('url'); var path = require('path'); var _ = require('underscore'); var nodemailer = require('nodemailer'); var swig = require('swig'); module.exports = function(app) { var config = app.loadConfig('email'); return { sendWelcome: function(user) { sendMessage(config.templates.signup, user); }, resendVerification: function(user) { sendMessage(config.templates.resend, user); }, sendForgot: function(user) { sendMessage(config.templates.forgot, user); } } function createTransport() { var cfg = config.mailer; // console.log("Creating mailer with transport:" + cfg.transport); // console.log(cfg); return nodemailer.createTransport(cfg.transport, cfg.config); } function sendMessage(template, user) { var appurl = app.getExternalUrl(); var emailVars = _.defaults(config.templateVars || {}, { 'appurl': appurl }); // XXX should use route resolution fns if (user.local.signupToken) { emailVars.signupLink = path.join(appurl, "verification", user.local.signupToken); } if (user.local.resetToken) { emailVars.resetLink = path.join(appurl, "forgot", user.local.resetToken); } var msgSubject = swig.render(template.subject, {locals:emailVars}); var msgBody = swig.renderFile(template.templatePath, emailVars); var transport = createTransport(); var message = { generateTextFromHTML: true, from: config.from, to: user.local.email, subject: msgSubject, html: msgBody } // console.log(message); // XXX what to do with error callbacks here? // these are operational issues that should be logged so alerts can be triggered transport.sendMail(message, function(error, response) { if (error) { console.log("Error sending mail!") console.log(error); } else { console.log("Message sent: " + response.message); console.log(JSON.stringify(response)); } transport.close(); // shut down the connection pool, no more messages }); } };
JavaScript
0.000003
@@ -994,35 +994,27 @@ pLink = -path.join( appurl -, + + %22 +/ verifica @@ -1017,18 +1017,20 @@ fication -%22, +/%22 + user.lo @@ -1040,25 +1040,24 @@ .signupToken -) ;%0A %7D%0A if ( @@ -1111,35 +1111,29 @@ k = -path.join( appurl -, + + %22 +/ forgot -%22, +/%22 + use @@ -1150,17 +1150,16 @@ setToken -) ;%0A %7D%0A%0A
fa364759f24249ff54dd73295a3b763e9acc92e8
rename callback to iteratee (consistent with underscorejs)
baseview.js
baseview.js
(function(root, factory) { // Set up BaseView appropriately for the environment. Start with AMD. if (typeof define === 'function' && define.amd) { define(['underscore', 'jquery', 'backbone', 'exports'], function(_, $, Backbone, exports) { // Export global even in AMD case in case this script is loaded with // others that may still expect a global Backbone. root.BaseView = factory(root, exports, _, $, Backbone); }); // Next for Node.js or CommonJS. jQuery may not be needed as a module. } else if (typeof exports !== 'undefined') { var _ = require('underscore'), $ = require('jquery'), Backbone = require('backbone'); factory(root, exports, _, $, Backbone); // Finally, as a browser global. } else { root.BaseView = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$), root.Backbone); } }(this, function(root, BaseView, _, $, Backbone) { var BaseView = Backbone.View.extend({ constructor: function(options) { options || (options = {}); _.extend(this, _.pick(options, viewOptions)); this.children = options.children || {}; this.collections = options.collections || {}; this.models = options.models || {}; this.setTemplate(this.template || ''); Backbone.View.apply(this, arguments); }, _ensureElement: function() { var el = this.el, mid = _.result(this, 'mid'), attributes = {}; Backbone.View.prototype._ensureElement.apply(this, arguments); if (el) { return; } attributes['data-cid'] = this.cid; if (mid) { attributes['data-mid'] = mid; this.$el.addClass(this.toClassName(mid)); } this.$el.attr(attributes); }, toClassName: function(className) { return className.match(/-?[_a-zA-Z]+[_a-zA-Z0-9-]*/g, '').join('-').replace(/[\/\_]/g, '-').toLowerCase(); }, remove: function() { Backbone.View.prototype.remove.apply(this, arguments); this.invoke('remove'); }, compileTemplate: function(str) { return _.template(str) }, renderTemplate: function() { var interpolated = this.ctemplate.apply(null, arguments); this.trigger('render:template', this, interpolated, arguments); return interpolated; }, renderTemplateDefer: function() { _.defer.apply(null, [this.renderTemplate.bind(this)].concat(Array.prototype.slice.call(arguments))); }, renderTemplateDebounce: function() { if (!this._renderTemplateDebounce) { this._renderTemplateDebounce = _.debounce(this.renderTemplate.bind(this)); } this._renderTemplateDebounce.apply(this, arguments); }, setTemplate: function(template) { this.ctemplate = this.compileTemplate(template); this.template = template; }, traverse: function(callback, options) { options || (options = {}); var view = options.view || this; view.each(function(child) { callback.call(this, view, child); this.traverse(callback, {view: child}); }, this); } }); var array = []; var slice = array.slice; //List of view options to be merged as properties. var viewOptions = ['template', 'mid']; var childMethods = ['each', 'where', 'findWhere', 'invoke', 'pluck', 'size', 'keys', 'values', 'pairs', 'pick', 'omit', 'defaults', 'clone', 'tap', 'has', 'propertyOf', 'isEmpty']; _.each(childMethods, function(method) { if (!_[method]) { return; } BaseView.prototype[method] = function() { var args = slice.call(arguments); args.unshift(this.children); return _[method].apply(_, args); }; }); return BaseView; }));
JavaScript
0
@@ -3299,24 +3299,24 @@ unction( -callback +iteratee , option @@ -3460,24 +3460,24 @@ -callback +iteratee .call(th @@ -3528,16 +3528,16 @@ rse( -callback +iteratee , %7Bv
4ceb812cc7d6f39b04c34ac4a831ca5d21bb20fd
Revert "Probably solves this issue #26"
lib/error.js
lib/error.js
/* * The MIT License * * Copyright 2014 Timo Behrmann, Guillaume Chauvet. * * 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. */ var assert = require('assert'); module.exports.handle = function (errors, req, res, options, next) { if(options.errorHandler && typeof(options.errorHandler) === 'function') { return res.send(new options.errorHandler(errors)); } else { return res.send (400, { status: 'validation failed', errors: errors }); } };
JavaScript
0
@@ -1283,12 +1283,23 @@ dler - && +) %7B%0A if( type @@ -1337,24 +1337,99 @@ unction') %7B%0A + return options.errorHandler(res, errors);%0A %7D else %7B%0A retu @@ -1475,16 +1475,26 @@ rors));%0A + %7D%0A %7D el
3cd43c2857fa09a72af72be4594734c77674101a
Update emailTransports when seeding
config/models.js
config/models.js
'use strict'; /** * Default model configuration * (sails.config.models) * * Unless you override them, the following properties will be included * in each of your models. * * For more info on Sails models, see: * http://sailsjs.org/#/documentation/concepts/ORM */ module.exports.models = { /*************************************************************************** * * * Your app's default connection. i.e. the name of one of your app's * * connections (see `config/connections.js`) * * * ***************************************************************************/ connection: process.env.DB_ADAPTER || 'localDiskDb', migrate: 'alter', updateOrCreate: function(criteria, values, cb){ var self = this; // reference for use by callbacks // If no values were specified, use criteria if (!values) values = criteria.where ? criteria.where : criteria; this.findOne(criteria, function (err, result){ if(err) return cb(err, false); if(result){ self.update(criteria, values, cb); }else{ self.create(values, cb); } }); }, /** * This method adds records to the database * * To use add a variable 'seedData' in your model and call the * method in the bootstrap.js file */ seed: function (callback) { var self = this; var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1); if (!self.seedData) { sails.log.debug('No data avaliable to seed ' + modelName); callback(); return; } self.count().exec(function (err, count) { if (!err && count === 0) { sails.log.debug('Seeding ' + modelName + '...'); if (self.seedData instanceof Array) { self.seedArray(callback); } else { self.seedObject(callback); } } else { sails.log.debug(modelName + ' had models, so no seed needed'); callback(); } }); }, seedArray: function (callback) { var self = this; var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1); self.createEach(self.seedData).exec(function (err, results) { if (err) { sails.log.debug(err); callback(); } else { sails.log.debug(modelName + ' seed planted'); callback(); } }); }, seedObject: function (callback) { var self = this; var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1); self.create(self.seedData).exec(function (err, results) { if (err) { sails.log.debug(err); callback(); } else { sails.log.debug(modelName + ' seed planted'); callback(); } }); } };
JavaScript
0
@@ -8,16 +8,74 @@ rict';%0A%0A +var _ = require(%22lodash%22);%0Avar async = require(%22async%22);%0A%0A /**%0A * D @@ -1967,24 +1967,25 @@ r, count) %7B%0A +%0A @@ -1990,18 +1990,152 @@ if - (!err && +(err) %7B%0A sails.log.error(%22Failed to seed %22 + modelName, error);%0A return callback();%0A %7D%0A%0A if( coun @@ -2417,122 +2417,1671 @@ %7D - else %7B%0A sails.log.debug(modelName + ' had models, so no seed needed');%0A callback(); +else%7B%0A if(modelName === 'Emailtransport') %7B%0A // Update records%0A self.updateRecords(callback);%0A %7Delse%7B%0A sails.log.debug(modelName + ' had models, so no seed needed');%0A return callback();%0A %7D%0A %7D%0A %7D);%0A %7D,%0A%0A updateRecords : function (callback) %7B%0A var self = this;%0A var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1);%0A self.find(%7B%7D).exec(function (err, results) %7B%0A if (err) %7B%0A sails.log.debug(err);%0A callback();%0A %7D else %7B%0A%0A%0A%0A var data = %5B%5D;%0A%0A self.seedData.forEach(function (seed) %7B%0A data.push(_.merge(_.filter(results,function (item) %7B%0A return item.name === seed.name%0A %7D)%5B0%5D %7C%7C %7B%7D,seed))%0A %7D)%0A%0A var fns = %5B%5D;%0A%0A sails.log(%22!!!!!!!!!!!!!!!!!!!!!!!%22, data)%0A%0A data.forEach(function (item) %7B%0A fns.push(function(cb)%7B%0A self.update(%7B%0A id :item.id%0A %7D,_.omit(item, %5B%22id%22%5D)).exec(cb)%0A %7D)%0A %7D)%0A%0A async.series(fns,function (err,data) %7B%0A if (err) %7B%0A sails.log.debug(err);%0A callback();%0A %7Delse%7B%0A sails.log.debug(modelName + ' seeds updated', data);%0A callback();%0A %7D%0A %7D) %0A @@ -4102,32 +4102,33 @@ %7D);%0A %7D,%0A +%0A seedArray: f
28cf0b946cde925c7ee09ed53243c277e6282955
Fix calendar popup
src/components/Transaction/Filter/Calendar.js
src/components/Transaction/Filter/Calendar.js
import React from 'react' import { Modal, Button } from 'semantic-ui-react' import DayPicker, { DateUtils } from 'react-day-picker' import 'react-day-picker/lib/style.css' const currentYear = new Date().getFullYear() const fromMonth = new Date(currentYear - 8, 0) const toMonth = new Date(currentYear + 2, 11) function YearMonthForm({ date, localeUtils, onChange }) { const months = localeUtils.getMonths() const years = [] for (let i = fromMonth.getFullYear(); i <= toMonth.getFullYear(); i += 1) { years.push(i) } const handleChange = function handleChange(e) { const { year, month } = e.target.form onChange(new Date(year.value, month.value)) } return ( <form className="DayPicker-Caption"> <select name="month" onChange={handleChange} value={date.getMonth()}> {months.map((month, i) => ( <option key={i} value={i}> {month} </option> ))} </select> <select name="year" onChange={handleChange} value={date.getFullYear()}> {years.map((year, i) => ( <option key={i} value={year}> {year} </option> ))} </select> </form> ) } class Calendar extends React.Component { state = { month: null, from: null, to: null } handleDayClick = day => { const range = DateUtils.addDayToRange(day, this.state) this.setState(range) } handleYearMonthChange = month => { this.setState({ month }) } handleResetClick = () => { this.setState({ month: null, from: null, to: null }) } handleApplyClick = () => { const { from, to } = this.state this.props.changeFilterDate({ dateStart: from.setHours(0, 0, 0), dateEnd: (to && to.setHours(23, 59, 59)) || from.setHours(23, 59, 59) }) this.props.toggleFilterCalendar() } render() { const { month, from, to } = this.state return ( <Modal open={this.props.isCalendarOpen} onClose={this.props.toggleFilterCalendar} className="transactions-filter-modal" closeIcon size="tiny" > <Modal.Header>Show transactions in range</Modal.Header> <Modal.Content> <DayPicker className="Range" enableOutsideDays numberOfMonths={this.props.isMobile ? 1 : 2} selectedDays={[from, { from, to }]} month={month} captionElement={ <YearMonthForm onChange={this.handleYearMonthChange} /> } onDayClick={this.handleDayClick} /> </Modal.Content> <Modal.Actions> <Button content="Reset" onClick={this.handleResetClick} /> <Button content="Apply" onClick={this.handleApplyClick} positive disabled={this.state.from === null && this.state.to === null} /> </Modal.Actions> </Modal> ) } } export default Calendar
JavaScript
0.000001
@@ -2105,12 +2105,13 @@ ze=%22 -tiny +small %22%0A @@ -2255,16 +2255,39 @@ %22Range%22%0A + fixedWeeks%0A
44ee430f5b38237332e62759176ab0d357c16f99
add twitter search ui
src/components/TwitterSearch/TwitterSearch.js
src/components/TwitterSearch/TwitterSearch.js
import React, { Component } from 'react'; class TwitterSearch extends Component { render () { return ( <p>Twitter Search Component</p> ); } }; export default TwitterSearch;
JavaScript
0
@@ -116,37 +116,144 @@ %3C -p%3ETwitter Search Component%3C/p +div%3E%0A %3Cform%3E%0A %3Cinput type=%22text%22/%3E%0A %3Cbutton type=%22submit%22%3ESearch%3C/button%3E%0A %3C/form%3E%0A %3C/div %3E%0A
e4bda920ce409db882c73bf75dae86d0532c2171
Fix ball rendering
js/modules/ball.js
js/modules/ball.js
'use strict'; var Ball = (function(){ var x = undefined; var y = undefined; var velocityX = undefined; var velocityY = undefined; var sizeX = 10; var sizeY = 10; var destroyed = false; var rawSpeed = 0; var getX = function() { return x; }; var getY = function() { return y; }; var getVelocityX = function() { return velocityX; }; var getVelocityY = function() { return velocityY; }; var setVelocityX = function(setVelocityX) { velocityX = setVelocityX; }; var setVelocityY = function(setVelocityY) { velocityY = setVelocityY; }; var getRawSpeed = function() { return rawSpeed; }; var setRawSpeed = function(setRawSpeed) { rawSpeed = setRawSpeed; }; var setBallSize = function(setBallSize) { sizeX = sizeY = setBallSize; }; var getSizeX = function() { return sizeX; }; var getSizeY = function() { return sizeY; }; var isDestroyed = function() { return destroyed; }; var respawn = function() { x = 400; y = 430; velocityX = 0.05; velocityY = 1.5; destroyed = false; rawSpeed = 2.5; }; var draw = function(graphics) { graphics.strokeStyle = "#443322"; graphics.fillStyle = "#443322"; graphics.beginPath(); graphics.moveTo(x, y); graphics.arc(x, y, (sizeX + sizeY) / 2, 0, Math.PI * 2, true); graphics.stroke(); graphics.arc(x, y, (sizeX + sizeY) / 2.5, 0, Math.PI * 2, true); graphics.closePath(); graphics.fill(); }; var update = function() { if(destroyed) return; // Update position x += velocityX; y += velocityY; // Handle collisions with bricks var initialVelocityX = velocityX; var initialVelocityY = velocityY; Bricks.forEach(function(brick){ var dX = Math.abs(brick.getX() - x) - brick.getSizeX() - sizeX; var dY = Math.abs(brick.getY() - y) - brick.getSizeY() - sizeY; if(dX < 0 && dY < 0) { brick.registerImpact(); if(!Powerup.isActivated("flythru")) { if(Math.abs(dX - dY) < 5) { velocityY = -initialVelocityY; velocityX = -initialVelocityX; } else if(dX < dY) { velocityY = -initialVelocityY; } else { velocityX = -initialVelocityX; } } } }); // Handle paddle impact var dX = Math.abs(Paddle.getX() - x) - Paddle.getSizeX() - sizeX; var dY = Math.abs(Paddle.getY() - y) - Paddle.getSizeY() - sizeY; if(dX < 0 && dY < 0) { // The paddle will handle the bounce from here... Paddle.registerImpact(); } // Handle ball bouncing to the edges of the board if(x - sizeX < 0 && velocityX < 0) { velocityX = -velocityX; } if(y - sizeY < 0 && velocityY < 0) { velocityY = -velocityY; } if(x + sizeX > Breakout.getSizeX() && velocityX > 0) { velocityX = -velocityX; } if(y + sizeY > Breakout.getSizeY() && velocityY > 0) { destroyed = true; Score.ballDestroyed(); } }; respawn(); var self = { getX: getX, getY: getY, getVelocityX: getVelocityX, getVelocityY: getVelocityY, setVelocityX: setVelocityX, setVelocityY: setVelocityY, getSizeX: getSizeX, getSizeY: getSizeY, isDestroyed: isDestroyed, update: update, draw: draw, respawn: respawn, getRawSpeed: getRawSpeed, setRawSpeed: setRawSpeed, setBallSize: setBallSize, }; return self; })();
JavaScript
0.000002
@@ -1215,19 +1215,16 @@ (x, y);%0A -%09%09%0A %09%09graphi @@ -1280,16 +1280,40 @@ true);%0A +%09%09graphics.closePath();%0A %09%09graphi @@ -1325,18 +1325,65 @@ roke();%0A +%0A %09%09 +graphics.beginPath();%0A%09%09graphics.moveTo(x, y); %0A%09%09graph @@ -1442,19 +1442,16 @@ true);%0A -%09%09%0A %09%09graphi
e129678682990f0f98b1b5f30730319beb7308a8
Fix callback
js/net/facebook.js
js/net/facebook.js
var fbUser; function setUser(response) { FB.getLoginStatus(function(response) { if (response.status === 'connected') { // Logged into CRUDbrain and Facebook. fbUser = { id: response.authResponse.userID, access_token: response.authResponse.accessToken }; } }); } function facebookSdk(callback, redirect) { window.fbAsyncInit = function() { FB.init({ appId : '1642565209312684', // Inkling (PRODUCTION) //appId : '1643906175845254', // CRUDbrain (test) cookie : true, xfbml : true, // parse social plugins on this page version : 'v2.2' }); FB.getLoginStatus(function(response) { setUser(response); if (redirect) { if (!fbUser) { window.location.replace('/'); } else { callback(); } } }); }; // Load the SDK asynchronously (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; // PRODUCTION //js.src = "http://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); }
JavaScript
0.000003
@@ -733,16 +733,17 @@ ponse);%0A +%0A if @@ -744,24 +744,23 @@ if ( -redirect +!fbUser ) %7B%0A @@ -759,39 +759,40 @@ ) %7B%0A if ( -!fbUser +redirect ) %7B%0A wi @@ -832,16 +832,24 @@ %7D +%0A %7D else %7B%0A @@ -844,18 +844,16 @@ else %7B%0A - @@ -864,26 +864,16 @@ back();%0A - %7D%0A %7D%0A
bcedd28023238d4c07f39b00b735872765147e5b
Fix typo
lib/index.js
lib/index.js
'use strict'; class TeamcityReporter { constructor(emitter, reporterOptions, options) { this.reporterOptions = reporterOptions; this.options = options; const events = 'start beforeIteration iteration beforeItem item beforePrerequest prerequest beforeScript script beforeRequest request beforeTest test beforeAssertion assertion console exception beforeDone done'.split(' '); events.forEach((e) => { if (typeof this[e] == 'function') emitter.on(e, (err, args) => this[e](err, args)) }); } start(err, args) { console.log(`##teamcity[testSuiteStarted name='${this.options.collection.name}']`); } beforeItem(err, args) { this.currItem = {name: args.item.name, passed: true, failedAssertions: []}; console.log(`##teamcity[testStarted name='${this.currItem.name}' captureStandardOutput='true']`); } beforeRequest(err, args) { console.log(args.request.method, args.request.url.toString()); } request(err, args) { if (err) { console.log('request error'); } else { const sizeObj = args.response.size(); const size = sizeObj && (sizeObj.header || 0) + (sizeObj.body || 0) || 0; console.log(`Response code: ${args.response.code}, duration: ${args.response.responseTime}ms, size: ${size} bytes`); this.currItem.response = args.response; } } assertion(err, args) { if (err) { this.currItem.passed = false; this.currItem.failedAssertions.push(args.assertion); } } item(err, args) { if (!this.currItem.passed) { const msg = this.currItem.failedAssertions.join(", "); const details = `Response code: ${this.currItem.response.code}, reason: ${this.currItem.response.reason()}`; console.log(`##teamcity[testFailed name='${args.item.name}' message='${msg}' details='${msg} - ${details}']`); let body; try { body = JSON.parse(this.currItem.response) } catch (e) { body = '' }; console.log('Response body:', body); } console.log(`##teamcity[testFinished name='${args.item.name}' duration='${this.currItem.response.responseTime}']`); } done(err, args) { console.log(`##teamcity[testSuiteFinished name='${this.options.collection.name}']`); } } module.exports = TeamcityReporter;
JavaScript
0.999999
@@ -2036,16 +2036,21 @@ response +.body ) %7D catc
b2e53eab5daa6d885fbb818a4f2bbf65775ba1dc
Fix attribute proxy error
scripts/things/objecttracker.js
scripts/things/objecttracker.js
elation.require(['engine.things.generic', 'engine.things.leapmotion'], function() { elation.component.add('engine.things.objecttracker', function() { this.postinit = function() { elation.engine.things.objecttracker.extendclass.postinit.call(this); this.defineProperties({ player: { type: 'object' } }); this.controllers = []; this.hands = false; elation.events.add(this.engine, 'engine_frame', elation.bind(this, this.updatePositions)); elation.events.add(window, "webkitGamepadConnected,webkitgamepaddisconnected,MozGamepadConnected,MozGamepadDisconnected,gamepadconnected,gamepaddisconnected", elation.bind(this, this.updateTrackedObjects)); } this.createChildren = function() { /* this.hands = { left: this.player.shoulders.spawn('leapmotion_hand', 'hand_left', { position: new THREE.Vector3(0, 0, 0) }), right: this.player.shoulders.spawn('leapmotion_hand', 'hand_right', { position: new THREE.Vector3(0, 0, 0) }) }; */ Leap.loop(elation.bind(this, this.handleLeapLoop)); this.updateTrackedObjects(); } this.createHands = function() { this.hands = { left: this.player.shoulders.spawn('leapmotion_hand', 'hand_left', { position: new THREE.Vector3(0, 0, 0) }), right: this.player.shoulders.spawn('leapmotion_hand', 'hand_right', { position: new THREE.Vector3(0, 0, 0) }) }; this.hands.left.hide(); this.hands.right.hide(); } this.updatePositions = function() { this.updateTrackedObjects(); if (!this.vrdisplay) { return; } if (!this.hands) this.createHands(); var player = this.engine.client.player, stage = this.vrdisplay.stageParameters; for (var i = 0; i < this.controllers.length; i++) { var c = this.controllers[i]; if (c && c.data.pose) { var hand = (i ? 'left' : 'right'); var pose = c.data.pose; if (pose.position) { c.model.position.fromArray(pose.position).multiplyScalar(1); this.hands[hand].position.fromArray(pose.position); } //c.model.position.y += player.properties.height * 0.8 - player.properties.fatness; //c.model.position.x *= this.vrdisplay.stageParameters.sizeX; //c.model.position.z *= this.vrdisplay.stageParameters.sizeZ; //c.model.scale.set(stage.sizeX, stage.sizeX, stage.sizeZ); // FIXME - does this get weird for non-square rooms? if (pose.orientation) { c.model.quaternion.fromArray(pose.orientation); this.hands[hand].orientation.fromArray(pose.orientation); } } } } this.updateTrackedObjects = function() { var controls = this.engine.systems.controls; this.vrdisplay = this.engine.systems.render.views.main.vrdisplay; var gamepads = controls.gamepads; for (var i = 0; i < gamepads.length; i++) { if (gamepads[i] && !this.controllers[i]) { this.setTrackedController(i, gamepads[i]); } } } this.setTrackedController = function(i, controller) { this.controllers[i] = { model: (this.controllers[i] ? this.controllers[i].model : this.createPlaceholder()), data: controller }; this.objects['3d'].add(this.controllers[i].model); return this.controllers[i]; } this.createPlaceholder = function() { // TODO - For now, we make a rudimentary Vive controller model. We should be // able to load a different model for the specific type of controller. var w = 0.0445 / 1, l = 0.1714 / 1, d = 0.0254 / 1, r = 0.0952 / 2, ir = 0.0254 / 2; var geo = new THREE.BoxGeometry(w, d, l); geo.applyMatrix(new THREE.Matrix4().makeTranslation(0,-d/2,l/2)); var torus = new THREE.TorusGeometry(r, ir); torus.applyMatrix(new THREE.Matrix4().makeTranslation(0, 0, r/2 + ir*2)); torus.applyMatrix(new THREE.Matrix4().makeRotationFromEuler(new THREE.Euler(Math.PI/4, 0, 0))); geo.merge(torus, new THREE.Matrix4().makeTranslation(0,0,-r)); return new THREE.Mesh( geo, new THREE.MeshLambertMaterial({color: 0xffffff * Math.random()}) ); } this.hasHands = function() { // TODO - this should also work with leap motion return this.controllers.length > 0 || this.hands; } this.getHands = function() { if (this.controllers.length > 0) { var hands = {}; if (this.controllers[0] && this.controllers[0].data) { hands.left = this.controllers[0].data.pose; } if (this.controllers[1] && this.controllers[1].data) { hands.right = this.controllers[1].data.pose; } return hands; } else if (this.hands) { return { left: this.hands.left, right: this.hands.right, }; } return false; } this.handleLeapLoop = function(frame) { var framehands = {}; if (!this.hands) this.createHands(); for (var i = 0; i < frame.hands.length; i++) { framehands[frame.hands[i].type] = frame.hands[i]; } for (var k in this.hands) { var hand = framehands[k]; var handobj = this.hands[k]; if (hand && handobj) { if (hand.valid) { handobj.active = true; handobj.show(); handobj.updateData(hand, 1/1000); } else { handobj.active = false; handobj.hide(); } } else if (handobj) { handobj.active = false; handobj.hide(); } } } }, elation.engine.things.generic); });
JavaScript
0.000001
@@ -2615,16 +2615,27 @@ s%5Bhand%5D. +properties. orientat
4080b6ab75fa526f1f41b4c63fd067182e4916bf
Fix to the lexer's detection of number literals. Lexer will no longer choke when number literals are directly following commas or other punctuation.
lib/lexer.js
lib/lexer.js
var errors = require('./errors'); var Token = require('./Token'); // poor man's unicode support var VARIABLE = /\$[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*/g; var STRING_LITERAL_SINGLE = /'((\\.|[^\n\\'])*)(.)/g; var STRING_LITERAL_DOUBLE = /"((\\.|[^\n\\"])*)(.)/g; var NUMBER_START = /[0-9]/g; var NUMBER = /\d*\.?\d+/g; var COMMENT = /([^\n]*)(\n|$)/g; var COLOR_HASH = /#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})/g; var WHITESPACE = /[^\S\n]+/g; var IDENT = /[a-zA-Z][a-zA-Z0-9\-]*/g; var _simpleTokens = { '=': Token.EQ, '(': Token.LPAREN, ')': Token.RPAREN, ',': Token.COMMA, '%': Token.PERC, ':': Token.COLON, ';': Token.SEMI, '*': Token.MULT, '+': Token.PLUS, '-': Token.MINUS }; exports.lex = function(sourceFile) { var tokens = []; var prevToken = null; var a, c, c1, strlen; var lineNo = 0; var lineStart = 0; var lineStarts = [0]; var m = null; var t = null; function token(type, val) { return { type: type, pos: a, line: lineNo, linePos: a - lineStart, val: val, src: sourceFile } } // TODO: remove all of the 'return's in front of calls to this function function error(message) { throw new errors.CompileError('LexError', message, token(Token.INVALID)); } var str = sourceFile.text; for (a = 0, strlen = str.length; a < strlen; a++) { c = str[a]; t = null; //console.log('C:', a, c, c.charCodeAt(0)); if (_simpleTokens[c] != null) { t = token(_simpleTokens[c]); } else if (c === '$') { VARIABLE.lastIndex = a, m = VARIABLE.exec(str); if (!m) { return error('Missing variable name'); } t = token(Token.VARIABLE, m[0].substr(1)); a = VARIABLE.lastIndex - 1; } else if (c === '\'') { STRING_LITERAL_SINGLE.lastIndex = a, m = STRING_LITERAL_SINGLE.exec(str); if (!m || m[3] != '\'' || m.index !== a) { return error('Missing closing \''); } t = token(Token.STRING_LIT, m[1]); t.wrapChar = '\''; a = STRING_LITERAL_SINGLE.lastIndex - 1; } else if (c === '"') { STRING_LITERAL_DOUBLE.lastIndex = a, m = STRING_LITERAL_DOUBLE.exec(str); if (!m || m[3] !== '"' || m.index !== a) { return error('Missing closing "'); } t = token(Token.STRING_LIT, m[1]); t.wrapChar = '"'; a = STRING_LITERAL_DOUBLE.lastIndex - 1; } else if (NUMBER_START.test(c)) { NUMBER.lastIndex = a, m = NUMBER.exec(str); t = token(Token.NUMBER, m[0]); a = NUMBER.lastIndex - 1; } else if (c === '.') { if (NUMBER_START.test(str[a + 1])) { NUMBER.lastIndex = a, m = NUMBER.exec(str); t = token(Token.NUMBER, m[0]); a = NUMBER.lastIndex - 1; } else { t = token(Token.PERIOD); } } else if (c === '/') { if (str[a + 1] === '/') { COMMENT.lastIndex = a + 2, m = COMMENT.exec(str); t = token(Token.COMMENT, m[1] || ''); if (m[2] === '\n') { a = COMMENT.lastIndex - 2; } else { a = COMMENT.lastIndex - 1; } } else { t = token(Token.DIV); } } else if (c === '#') { COLOR_HASH.lastIndex = a, m = COLOR_HASH.exec(str); if (!m) { return error('Color definitions must be either 3 or 6 hexadecimal characters'); } t = token(Token.COLOR_HASH, m[1]); a = COLOR_HASH.lastIndex - 1; } else if ((WHITESPACE.lastIndex = 0, WHITESPACE.test(c))) { WHITESPACE.lastIndex = a; m = WHITESPACE.exec(str); if (prevToken && prevToken.type === Token.EOL) { t = token(Token.INDENT, m[0]); } a = WHITESPACE.lastIndex - 1; } else if (c === '\n') { if (prevToken && prevToken.type !== Token.EOL) { t = token(Token.EOL); } lineNo++; lineStart = a + 1; lineStarts.push(lineStart); } else if ((IDENT.lastIndex = 0, IDENT.test(c))) { IDENT.lastIndex = a, m = IDENT.exec(str); t = token(Token.IDENT, m[0]); a = IDENT.lastIndex - 1; } else { return error('Unexpected symbol: ' + c); } if (t) { tokens.push(t); prevToken = t; //console.log(Token.typeToStr(t.type) + (t.val != null ? '(' + t.val + ')' : '')); } } if (prevToken !== Token.EOL) { tokens.push(token(Token.EOL)); } return tokens; }
JavaScript
0.000003
@@ -292,17 +292,16 @@ /%5B0-9%5D/ -g ;%0Avar NU
70d4f13df4af2187cffa46e585348d02a1fe65b5
add UTC per @bamos' issue
js/reading-list.js
js/reading-list.js
// http://www.jblotus.com/2011/05/24/keeping-your-handlebars-js-templates-organized/ function getTemplateAjax(path, callback) { var source; var template; $.ajax({ url: path, success: function(data) { source = data; template = Handlebars.compile(source); //execute the callback if passed if (callback) callback(template); } }); } function loadYAML(name, f) { var client = new XMLHttpRequest(); client.open('GET', 'data/' + name + '.yaml'); client.onreadystatechange = function() { if (client.readyState == 3) { var yaml = jsyaml.load(client.responseText); if (yaml) { f(yaml); } } } client.send(); } function loadLists() { getTemplateAjax('templates/currently-reading.hbars.html', function(tmpl) { loadYAML("currently-reading", function(yaml) { $("#currently-reading").html(tmpl(yaml)); }); }); getTemplateAjax('templates/up-next.hbars.html', function(tmpl) { loadYAML("up-next", function(yaml) { $("#up-next").html(tmpl(yaml)); }); }); getTemplateAjax('templates/to-read.hbars.html', function(tmpl) { loadYAML("to-read", function(yaml) { $("#to-read").html(tmpl(yaml)); }); }); getTemplateAjax('templates/finished.hbars.html', function(tmpl) { loadYAML("finished", function(yaml) { yaml.sort(function(a,b) { if (a.finished > b.finished) return -1; if (a.finished < b.finished) return 1; return 0; }); function dateString(d) { return d.getFullYear().toString() + "/" + (d.getMonth() + 1).toString() + "/" + (d.getDate() + 1).toString(); } var len = yaml.length; for (var i = 0; i < len; i++) { yaml[i].finished = dateString(yaml[i].finished); } $("#finished").html(tmpl(yaml)); finished_yaml = yaml; loadTimeline(yaml); }); }); } function showModal(title,yaml,idx) { if (quotes_body_tmpl) { bootbox.dialog({ message: quotes_body_tmpl(yaml[idx]), title: title, onEscape: function() {} }); } } // Close the modal dialog if the background of the document is clicked. // Reference: https://github.com/makeusabrew/bootbox/issues/210 $(document).on('click', '.bootbox', function(){ var classname = event.target.className; if(classname && !$('.' + classname).parents('.modal-dialog').length) bootbox.hideAll(); }); function loadTimeline(finished_yaml) { var books = [] $.each(finished_yaml, function(idx, book) { books.push({ "startDate": book.finished.replace(/\//g,","), "headline": book.author + ": " + book.title }); }); var timelineData = { "timeline": { "type": "default", "date": books }}; createStoryJS({ width: "100%", height: "400", source: timelineData, embed_id: 'finished-timeline', start_at_end: true, start_zoom_adjust: 3 }); } $(document).ready(function() { quotes_body_tmpl = null; getTemplateAjax('templates/quotes-body.hbars.html', function(tmpl) { quotes_body_tmpl = tmpl; }); Handlebars.registerHelper('for', function(from, to, block) { var accum = ''; for(var i = from; i < to; ++i) { accum += block.fn(i); } return accum; }); Handlebars.registerHelper('escape', function(variable) { return variable.replace(/(['"])/g, '\\$1'); }); loadLists(); })
JavaScript
0
@@ -1553,16 +1553,19 @@ rn d.get +UTC FullYear @@ -1602,16 +1602,19 @@ (d.get +UTC Month() @@ -1653,16 +1653,19 @@ (d.get +UTC Date() +
c623d0bf8042f3d88605e0fcad7045da412a1a9a
use stringify instead of JSON.stringify.
lib/reply.js
lib/reply.js
/* eslint-disable no-useless-return */ 'use strict' const pump = require('pump') const xtend = require('xtend') const validation = require('./validation') const serialize = validation.serialize const statusCodes = require('http').STATUS_CODES const stringify = JSON.stringify const flatstr = require('flatstr') function Reply (req, res, store) { this.res = res this.store = store this._req = req this.sent = false this._serializer = null } /** * Instead of using directly res.end(), we are using setImmediate(…) * This because we have observed that with this technique we are faster at responding to the various requests, * since the setImmediate forwards the res.end at the end of the poll phase of libuv in the event loop. * So we can gather multiple requests and then handle all the replies in a different moment, * causing a general improvement of performances, ~+10%. */ Reply.prototype.send = function (payload) { if (this.sent) { throw new Error('Reply already sent') } if (!payload) { if (!this.res.statusCode) { this.res.statusCode = 204 } this.res.setHeader('Content-Length', '0') setImmediate(wrapReplyEnd, this, '') return } if (payload && payload.isBoom) { this._req.log.error(payload) this.res.statusCode = payload.output.statusCode this.res.setHeader('Content-Type', 'application/json') this.headers(payload.output.headers) setImmediate( wrapReplyEnd, this, JSON.stringify(payload.output.payload) ) return } if (payload instanceof Error) { if (!this.res.statusCode || this.res.statusCode < 400) { this.res.statusCode = 500 } this._req.log.error({ res: this.res, error: payload }, payload.message) this.res.setHeader('Content-Type', 'application/json') setImmediate( wrapReplyEnd, this, stringify(xtend({ error: statusCodes[this.res.statusCode + ''], message: payload.message, statusCode: this.res.statusCode }, this._extendServerError && this._extendServerError())) ) return } if (typeof payload.then === 'function') { return payload.then(wrapReplySend(this)).catch(wrapReplySend(this)) } if (payload._readableState) { if (!this.res.getHeader('Content-Type')) { this.res.setHeader('Content-Type', 'application/octet-stream') } return pump(payload, this.res, wrapPumpCallback(this)) } if (!this.res.getHeader('Content-Type') || this.res.getHeader('Content-Type') === 'application/json') { this.res.setHeader('Content-Type', 'application/json') // Here we are assuming that the custom serializer is a json serializer const str = this._serializer ? this._serializer(payload) : serialize(this.store, payload, this.res.statusCode) if (typeof str === 'string') { flatstr(str) } if (!this.res.getHeader('Content-Length')) { this.res.setHeader('Content-Length', Buffer.byteLength(str)) } setImmediate(wrapReplyEnd, this, str) return } // All the code below must have a 'content-type' setted if (this._serializer) { setImmediate(wrapReplyEnd, this, this._serializer(payload)) return } setImmediate(wrapReplyEnd, this, payload) return } Reply.prototype.header = function (key, value) { this.res.setHeader(key, value) return this } Reply.prototype.headers = function (headers) { var keys = Object.keys(headers) for (var i = 0; i < keys.length; i++) { this.header(keys[i], headers[keys[i]]) } return this } Reply.prototype.code = function (code) { this.res.statusCode = code return this } Reply.prototype.serializer = function (fn) { this._serializer = fn return this } Reply.prototype.type = function (type) { this.res.setHeader('Content-Type', type) return this } Reply.prototype.redirect = function (code, url) { if (typeof code === 'string') { url = code code = 302 } this.res.writeHead(code, { Location: url }) this.res.end() } function wrapPumpCallback (reply) { return function pumpCallback (err) { if (err) { reply._req.log.error(err) setImmediate(wrapReplyEnd, reply) } } } function wrapReplyEnd (reply, payload) { reply.sent = true reply.res.end(payload) } function wrapReplySend (reply, payload) { return function send (payload) { return reply.send(payload) } } function buildReply (R) { function _Reply (req, res, store) { this.res = res this.store = store this._req = req this.sent = false this._serializer = null } _Reply.prototype = new R() return _Reply } module.exports = Reply module.exports.buildReply = buildReply
JavaScript
0
@@ -1468,21 +1468,16 @@ ,%0A -JSON. stringif
1eda6012862b58927c02f60f5089c0c8166d4ef5
Fix some mixups between the parsed data and contained videos
lib/saved.js
lib/saved.js
var fs = require('fs'); var YoutubeTrack = require('./youtube-track.js'); var exports = { saved: { videos: {}, }, }; var FILENAME = 'lethe-data.json'; exports.read = function() { try { fs.readFile(FILENAME, 'utf8', (err, data) => { if (err) { if (err.message.indexOf('ENOENT') > -1) { // File doesn't exist console.log(`The lethe-data.json file doesn't exist! This is not an error.`); } else { console.log(err); } } else { var parsed = JSON.parse(data); exports.saved.videos = {}; for (var key in parsed) { if (parsed.hasOwnProperty(key)) { exports.saved.videos[key] = new YoutubeTrack(parsed[key].vid, parsed[key]); } } } }); } catch (e) { console.log(e); } }; exports.write = function() { fs.writeFile(FILENAME, JSON.stringify(exports.saved), (err) => { if (err) { console.log(err); } }); }; exports.possiblyRetrieveVideo = function(argument) { if (exports.saved.videos.hasOwnProperty(argument)) return exports.saved.videos[argument].vid; else return argument; }; exports.isVideoSaved = function(vid) { for (var key in exports.saved.videos) { if (exports.saved.videos.hasOwnProperty(key)) { var dupe = exports.saved.videos[key]; if (dupe.vid === vid) { return key; } } } return false; }; module.exports = exports;
JavaScript
0.000003
@@ -511,22 +511,27 @@ var -parsed +savedVideos = JSON. @@ -541,16 +541,23 @@ se(data) +.videos ;%0A @@ -609,22 +609,27 @@ key in -parsed +savedVideos ) %7B%0A @@ -638,22 +638,27 @@ if ( -parsed +savedVideos .hasOwnP @@ -734,31 +734,41 @@ ack( -parsed%5Bkey%5D.vid, parsed +savedVideos%5Bkey%5D.vid, savedVideos %5Bkey
f9e158ff68cfdcc7cf2c9ebf3e7501b82286154a
Rename link to button
src/components/views/messages/ReactionsRow.js
src/components/views/messages/ReactionsRow.js
/* Copyright 2019 New Vector Ltd 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. */ import React from 'react'; import PropTypes from 'prop-types'; import sdk from '../../../index'; import { _t } from '../../../languageHandler'; import { isContentActionable } from '../../../utils/EventUtils'; import { isSingleEmoji } from '../../../HtmlUtils'; import MatrixClientPeg from '../../../MatrixClientPeg'; // The maximum number of reactions to initially show on a message. const MAX_ITEMS_WHEN_LIMITED = 8; export default class ReactionsRow extends React.PureComponent { static propTypes = { // The event we're displaying reactions for mxEvent: PropTypes.object.isRequired, // The Relations model from the JS SDK for reactions to `mxEvent` reactions: PropTypes.object, } constructor(props) { super(props); if (props.reactions) { props.reactions.on("Relations.add", this.onReactionsChange); props.reactions.on("Relations.remove", this.onReactionsChange); props.reactions.on("Relations.redaction", this.onReactionsChange); } this.state = { myReactions: this.getMyReactions(), showAll: false, }; } componentDidUpdate(prevProps) { if (prevProps.reactions !== this.props.reactions) { this.props.reactions.on("Relations.add", this.onReactionsChange); this.props.reactions.on("Relations.remove", this.onReactionsChange); this.props.reactions.on("Relations.redaction", this.onReactionsChange); this.onReactionsChange(); } } componentWillUnmount() { if (this.props.reactions) { this.props.reactions.removeListener( "Relations.add", this.onReactionsChange, ); this.props.reactions.removeListener( "Relations.remove", this.onReactionsChange, ); this.props.reactions.removeListener( "Relations.redaction", this.onReactionsChange, ); } } onReactionsChange = () => { // TODO: Call `onHeightChanged` as needed this.setState({ myReactions: this.getMyReactions(), }); // Using `forceUpdate` for the moment, since we know the overall set of reactions // has changed (this is triggered by events for that purpose only) and // `PureComponent`s shallow state / props compare would otherwise filter this out. this.forceUpdate(); } getMyReactions() { const reactions = this.props.reactions; if (!reactions) { return null; } const userId = MatrixClientPeg.get().getUserId(); const myReactions = reactions.getAnnotationsBySender()[userId]; if (!myReactions) { return null; } return [...myReactions.values()]; } onShowAllClick = () => { this.setState({ showAll: true, }); } render() { const { mxEvent, reactions } = this.props; const { myReactions, showAll } = this.state; if (!reactions || !isContentActionable(mxEvent)) { return null; } const ReactionsRowButton = sdk.getComponent('messages.ReactionsRowButton'); let items = reactions.getSortedAnnotationsByKey().map(([content, events]) => { if (!isSingleEmoji(content)) { return null; } const count = events.size; if (!count) { return null; } const myReactionEvent = myReactions && myReactions.find(mxEvent => { if (mxEvent.isRedacted()) { return false; } return mxEvent.getRelation().key === content; }); return <ReactionsRowButton key={content} content={content} count={count} mxEvent={mxEvent} reactionEvents={events} myReactionEvent={myReactionEvent} />; }).filter(item => !!item); // Show the first MAX_ITEMS if there are MAX_ITEMS + 1 or more items. // The "+ 1" ensure that the "show all" reveals something that takes up // more space than the button itself. let showAllLink; if ((items.length > MAX_ITEMS_WHEN_LIMITED + 1) && !showAll) { items = items.slice(0, MAX_ITEMS_WHEN_LIMITED); showAllLink = <a className="mx_ReactionsRow_showAll" href="#" onClick={this.onShowAllClick} > {_t("Show all")} </a>; } return <div className="mx_ReactionsRow"> {items} {showAllLink} </div>; } }
JavaScript
0
@@ -4913,20 +4913,22 @@ showAll -Link +Button ;%0A @@ -5071,20 +5071,22 @@ showAll -Link +Button = %3Ca%0A @@ -5375,12 +5375,14 @@ wAll -Link +Button %7D%0A
d13f4b9cf81a83d492a589c45a7586d57ee7b9dd
add compare_fn, banner to utils
lib/utils.js
lib/utils.js
var assemble = require('assemble'); var grunt = require('grunt'); var path = require('path'); var fs = require('fs'); var _ = grunt.util._; // The module to be exported. var Utils = module.exports = exports = {}; /** * This helper is meant to be instructive. You can add additional * properties to the content object to return whatever data you need. * @param {[type]} src [description] * @return {[type]} [description] */ Utils.globBasenames = function(src) { var content = void 0; return content = grunt.file.expand(src).map(function(path) { return { path: path }; }).map(function(obj) { return path.basename(obj.path); }).join(grunt.util.normalizelf(grunt.util.linefeed)); }; /* * Returns front matter from files expanded from globbing patterns. * can be used with a single file or many. */ Utils.globFrontMatter = function(src) { var content = void 0; return content = grunt.file.expand(src).map(function(path) { return { content: assemble.data.readYFM(path, {fromFile: true}).context }; }).map(function(obj) { return JSON.stringify(obj.content, null, 2); }).join(grunt.util.normalizelf(grunt.util.linefeed)); }; Utils.getCurrentYFM = function(src) { var content = assemble.data.readYFM(path, {fromFile: true}).context; return JSON.stringify(content, null, 2); }; Utils.parseYFM = function(options) { var data = assemble.data.readYFM(path, {fromFile: true}).context; return options.fn(JSON.parse(data)); };
JavaScript
0
@@ -1,12 +1,150 @@ +/*%0A * yfm%0A * https://github.com/assemble/yfm%0A * Copyright (c) 2013 Jon Schlinkert, contributors.%0A * Licensed under the MIT license.%0A */%0A%0A%0A var assemble @@ -367,16 +367,232 @@ = %7B%7D;%0A%0A +/**%0A * Accepts two objects (a, b),%0A * @param %7BObject%7D a%0A * @param %7BObject%7D b%0A * @return %7BNumber%7D returns 1 if (a %3E= b), otherwise -1%0A */%0AUtils.compareFn = function(a, b) %7B%0A return a.index %3E= b.index ? 1 : -1;%0A%7D%0A%0A%0A /**%0A * T @@ -1232,35 +1232,85 @@ r = function(src -) %7B +, options) %7B%0A options = options %7C%7C %7BfromFile: true%7D; %0A var content = @@ -1437,32 +1437,23 @@ M(path, -%7BfromFile: true%7D +options ).contex
194ddf856cb52d5d398bdb070886bc5b26dda2bc
remove reference to os module
lib/utils.js
lib/utils.js
'use strict'; /** * Module dependencies. */ var mensch = require('mensch'); var own = {}.hasOwnProperty; var os = require('os'); var Selector = require('./selector'); var Property = require('./property'); exports.Selector = Selector; exports.Property = Property; /** * Returns an array of the selectors. * * @license Sizzle CSS Selector Engine - MIT * @param {String} selectorText from mensch * @api public */ exports.extract = function extract(selectorText) { var attr = 0; var sels = []; var sel = ''; for (var i = 0, l = selectorText.length; i < l; i++) { var c = selectorText.charAt(i); if (attr) { if (']' === c || ')' === c) { attr--; } sel += c; } else { if (',' === c) { sels.push(sel); sel = ''; } else { if ('[' === c || '(' === c) { attr++; } if (sel.length || (c !== ',' && c !== '\n' && c !== ' ')) { sel += c; } } } } if (sel.length) { sels.push(sel); } return sels; }; /** * Returns a parse tree for a CSS source. * If it encounters multiple selectors separated by a comma, it splits the * tree. * * @param {String} css source * @api public */ exports.parseCSS = function(css) { var parsed = mensch.parse(css, {position: true, comments: true}); var rules = typeof parsed.stylesheet != 'undefined' && parsed.stylesheet.rules ? parsed.stylesheet.rules : []; var ret = []; for (var i = 0, l = rules.length; i < l; i++) { if (rules[i].type == 'rule') { var rule = rules[i]; var selectors = rule.selectors; for (var ii = 0, ll = selectors.length; ii < ll; ii++) { ret.push([selectors[ii], rule.declarations]); } } } return ret; }; /** * Returns preserved text for a CSS source. * * @param {String} css source * @param {Object} options * @api public */ exports.getPreservedText = function(css, options) { var parsed = mensch.parse(css, {position: true, comments: true}); var rules = typeof parsed.stylesheet != 'undefined' && parsed.stylesheet.rules ? parsed.stylesheet.rules : []; var preserved = []; var lastStart = null; for (var i = rules.length - 1; i >= 0; i--) { if ((options.fontFaces && rules[i].type === 'font-face') || (options.mediaQueries && rules[i].type === 'media')) { preserved.push( mensch.stringify( { stylesheet: { rules: [ rules[i] ] }}, { comments: false, indentation: ' ' } ) ); } lastStart = rules[i].position.start; } if (preserved.length === 0) return false; return os.EOL+preserved.join(os.EOL)+os.EOL; }; exports.normalizeLineEndings = function(text) { return text.replace(/\r\n/g, '\n').replace(/\n/g, '\r\n'); }; /** * Compares two specificity vectors, returning the winning one. * * @param {Array} vector a * @param {Array} vector b * @return {Array} * @api public */ exports.compareFunc = function(a, b) { var min = Math.min(a.length, b.length); for (var i = 0; i < min; i++) { if (a[i] === b[i]) { continue; } if (a[i] > b[i]) { return 1; } return -1; } return a.length-b.length; }; exports.compare = function(a, b) { return exports.compareFunc(a, b) == 1 ? a : b; }; exports.extend = function(obj, src) { for (var key in src) { if (own.call(src, key)) { obj[key] = src[key]; } } return obj; }; exports.getDefaultOptions = function(options) { var result = exports.extend({ extraCss: '', insertPreservedExtraCss: true, applyStyleTags: true, removeStyleTags: true, preserveMediaQueries: true, preserveFontFaces: true, applyWidthAttributes: true, applyHeightAttributes: true, applyAttributesTableElements: true, url: '' }, options); result.webResources = result.webResources || {}; return result; };
JavaScript
0
@@ -106,32 +106,8 @@ ty;%0A -var os = require('os');%0A var @@ -2520,16 +2520,22 @@ h === 0) + %7B%0A return @@ -2541,16 +2541,20 @@ false;%0A + %7D%0A return @@ -2558,15 +2558,15 @@ urn -os.EOL+ +'%5Cn' + pres @@ -2580,22 +2580,20 @@ oin( -os.EOL)+os.EOL +'%5Cn') + '%5Cn' ;%0A%7D; @@ -3096,17 +3096,19 @@ a.length -- + - b.length
33c96a2d97753e55b79bb3ceeea691b284a60691
add Crm-fetch scenario
client/src/app.js
client/src/app.js
import 'bootstrap'; /*import 'bootstrap/css/bootstrap.css!';*/ import {inject} from 'aurelia-framework'; import {Router} from 'aurelia-router'; import AppRouterConfig from 'app.router.config'; import HttpClientConfig from 'aurelia-auth/app.httpClient.config'; import FetchConfig from 'aurelia-auth/app.fetch-httpClient.config'; @inject(Router,HttpClientConfig,FetchConfig, AppRouterConfig ) export class App { constructor(router, httpClientConfig, fetchConfig, appRouterConfig){ this.router = router; this.httpClientConfig = httpClientConfig; this.appRouterConfig = appRouterConfig; this.fetchConfig = fetchConfig; } activate(){ this.httpClientConfig.configure(); this.appRouterConfig.configure(); this.fetchConfig.configure(); } }
JavaScript
0.000001
@@ -250,24 +250,26 @@ nt.config';%0A +// import Fetch @@ -324,16 +324,58 @@ onfig';%0A +import %7BFetchConfig%7D from 'aurelia-auth';%0A @inject(
b6ad96ffd5ef88b3c3d5fb5a0a689ae1a40cc8df
Fix plugin platform_www & cordova_plugins.json copy
cordova-lib/src/cordova/metadata/ubuntu_parser.js
cordova-lib/src/cordova/metadata/ubuntu_parser.js
/* * * Copyright 2013 Canonical Ltd. * * 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. * */ /* jshint sub:true */ var fs = require('fs'), path = require('path'), util = require('../util'), shell = require('shelljs'), Q = require('q'), Parser = require('./parser'), os = require('os'), ConfigParser = require('../../configparser/ConfigParser'); function ubuntu_parser(project) { // Call the base class constructor Parser.call(this, 'ubuntu', project); this.path = project; this.config = new ConfigParser(this.config_xml()); this.update_manifest(); } function sanitize(str) { return str.replace(/\n/g, ' ').replace(/^\s+|\s+$/g, ''); } require('util').inherits(ubuntu_parser, Parser); module.exports = ubuntu_parser; ubuntu_parser.prototype.update_from_config = function(config) { if (config instanceof ConfigParser) { } else { return Q.reject(new Error('update_from_config requires a ConfigParser object')); } this.config = new ConfigParser(this.config_xml()); this.config.setName(config.name()); this.config.setVersion(config.version()); this.config.setPackageName(config.packageName()); this.config.setDescription(config.description()); this.config.write(); return this.update_manifest(); }; ubuntu_parser.prototype.cordovajs_path = function(libDir) { var jsPath = path.join(libDir, 'www', 'cordova.js'); return path.resolve(jsPath); }; ubuntu_parser.prototype.cordovajs_src_path = function(libDir) { var jsPath = path.join(libDir, 'cordova-js-src'); return path.resolve(jsPath); }; ubuntu_parser.prototype.update_manifest = function() { var nodearch2debarch = { 'arm': 'armhf', 'ia32': 'i386', 'x64': 'amd64'}; var arch; if (os.arch() in nodearch2debarch) arch = nodearch2debarch[os.arch()]; else return Q.reject(new Error('unknown cpu arch')); if (!this.config.author()) return Q.reject(new Error('config.xml should contain author')); var manifest = { name: this.config.packageName(), version: this.config.version(), title: this.config.name(), hooks: { cordova: { desktop: 'cordova.desktop', apparmor: 'apparmor.json' } }, framework: 'ubuntu-sdk-13.10', maintainer: sanitize(this.config.author()) + ' <' + this.config.doc.find('author').attrib.email + '>', architecture: arch, description: sanitize(this.config.description()) }; var name = sanitize(this.config.name()); //FIXME: escaping var content = '[Desktop Entry]\nName=' + name + '\nExec=./cordova-ubuntu www/\nTerminal=false\nType=Application\nX-Ubuntu-Touch=true'; if (this.config.doc.find('icon') && this.config.doc.find('icon').attrib.src) { var iconPath = path.join(this.path, 'www', this.config.doc.find('icon').attrib.src); if (fs.existsSync(iconPath)) content += '\nIcon=www/' + this.config.doc.find('icon').attrib.src; else return Q.reject(new Error('icon does not exist: ' + iconPath)); } else { content += '\nIcon=qmlscene'; console.warn('missing icon element in config.xml'); } fs.writeFileSync(path.join(this.path, 'manifest.json'), JSON.stringify(manifest)); fs.writeFileSync(path.join(this.path, 'cordova.desktop'), content); var policy = { policy_groups: ['networking', 'audio'], policy_version: 1 }; this.config.doc.getroot().findall('./feature/param').forEach(function (element) { if (element.attrib.policy_group && policy.policy_groups.indexOf(element.attrib.policy_group) === -1) policy.policy_groups.push(element.attrib.policy_group); }); fs.writeFileSync(path.join(this.path, 'apparmor.json'), JSON.stringify(policy)); return Q(); }; ubuntu_parser.prototype.config_xml = function(){ return path.join(this.path, 'config.xml'); }; ubuntu_parser.prototype.www_dir = function() { return path.join(this.path, 'www'); }; ubuntu_parser.prototype.update_www = function() { var projectRoot = util.isCordova(this.path); var www = util.projectWww(projectRoot); shell.rm('-rf', this.www_dir()); shell.cp('-rf', www, this.path); }; ubuntu_parser.prototype.update_overrides = function() { var projectRoot = util.isCordova(this.path); var mergesPath = path.join(util.appDir(projectRoot), 'merges', 'ubuntu'); if(fs.existsSync(mergesPath)) { var overrides = path.join(mergesPath, '*'); shell.cp('-rf', overrides, this.www_dir()); } }; // Returns a promise. ubuntu_parser.prototype.update_project = function(cfg) { var self = this; return this.update_from_config(cfg) .then(function() { self.update_overrides(); util.deleteSvnFolders(self.www_dir()); }); };
JavaScript
0
@@ -4854,16 +4854,20 @@ var +app_ www = ut @@ -4898,80 +4898,384 @@ t);%0A -%0A shell.rm('-rf', this.www_dir());%0A shell.cp('-rf', www, this.path + var platform_www = path.join(this.path, 'platform_www');%0A %0A // Clear the www dir%0A shell.rm('-rf', this.www_dir());%0A shell.mkdir(this.www_dir());%0A // Copy over all app www assets%0A shell.cp('-rf', path.join(app_www, '*'), this.www_dir());%0A // Copy over stock platform www assets (cordova.js)%0A shell.cp('-rf', path.join(platform_www, '*'), this.www_dir() );%0A%7D
912a564e356e0a9904d70da2dafbee78db369383
enable compression on bf hashset
sensor/IntelLocalCachePlugin.js
sensor/IntelLocalCachePlugin.js
/* Copyright 2016 Firewalla LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; const log = require('../net2/logger.js')(__filename); const Sensor = require('./Sensor.js').Sensor; const sem = require('../sensor/SensorEventManager.js').getInstance(); const extensionManager = require('./ExtensionManager.js') const f = require('../net2/Firewalla.js'); const updateInterval = 2 * 24 * 3600 * 1000 // once per two days const hashKey = "gsb:bloomfilter"; const BloomFilter = require('../vendor_lib/bloomfilter.js').BloomFilter; const urlhash = require("../util/UrlHash.js"); const _ = require('lodash'); const bone = require("../lib/Bone.js"); const jsonfile = require('jsonfile'); class IntelLocalCachePlugin extends Sensor { async loadCacheFromBone() { log.info(`Loading intel cache from cloud...`); const data = await bone.hashsetAsync(hashKey) try { const payload = JSON.parse(data); // jsonfile.writeFileSync("/tmp/x.json", payload); this.bf = new BloomFilter(payload, 16); log.info("Intel cache is loaded successfully!"); } catch (err) { log.error(`Failed to load intel cache from cloud, err: ${err}`); this.bf = null; } } async run() { await this.loadCacheFromBone(); setInterval(() => { this.loadCacheFromBone(); }, updateInterval); } checkUrl(url) { // for testing only if(this.config && this.config.testURLs && this.config.testURLs.includes(url)) { return true; } if(!this.bf) { return false; } const hashes = urlhash.canonicalizeAndHashExpressions(url); const matchedHashes = hashes.filter((hash) => { if(!hash) { return false; } const prefix = hash[1]; if(!prefix) { return false; } const prefixHex = this.toHex(prefix); const testResult = this.bf.test(prefixHex); return testResult; }); return !_.isEmpty(matchedHashes); } toHex(base64) { return Buffer.from(base64, 'base64').toString('hex'); } } module.exports = IntelLocalCachePlugin;
JavaScript
0
@@ -1060,11 +1060,22 @@ lter +:compressed %22;%0A - %0Acon @@ -1303,16 +1303,140 @@ ile');%0A%0A +const zlib = require('zlib');%0A%0Aconst Promise = require('bluebird');%0A%0Aconst inflateAsync = Promise.promisify(zlib.inflate);%0A%0A class In @@ -1614,16 +1614,187 @@ try %7B%0A + const buffer = Buffer.from(data, 'base64');%0A const decompressedData = await inflateAsync(buffer);%0A const decompressedString = decompressedData.toString();%0A co @@ -1819,19 +1819,33 @@ .parse(d -ata +ecompressedString );%0A @@ -1957,17 +1957,17 @@ og.info( -%22 +%60 Intel ca @@ -1993,17 +1993,57 @@ ssfully! -%22 + cache size $%7BdecompressedString.length%7D%60 );%0A %7D
4fa1e22a18b9299f3f05def0b01edc5aa6fbfa16
the new constructor functions: class
docs/class.js
docs/class.js
// CLASSES /* classes function just like prototypes in our earlier topic, If you have taken. It's not necessary but if you have a knowdge of prototypes, classes should be a piece of cake. Both of them are just ways to create inheritances on objects. with class enabling th create an adhoc object. Class combines the power of constructor functions and prototypes. */ // the new fancy imports . import obj from "./object" class Polygon{ // this lets you call the class like a constructor function. constructor (height=10, width=10){ this._height = height; this._width = width; } // get in front of a function lets you define a function but call it as a property. get area () { return this.height * this.width } get perimeter(){ return (2 * this.height) + (2 * this.width) } get width(){ return this._width; } get height(){ return this._height; } // the set keyword functions just like the opposite of the get keyword. // lets you set values to Class properties as though you are defining a variable. set height(value){ this._height = value; } set width(value) { this._width = value; } // this means that you can get this method on the Polygon class without instantiating the class using the // 'new' keyword. static get get_height() { return "this is static method on the Rect Object"; } } //NB: the name of the getter and the setter should not be a property on the object itself. // to use getters and setters make the property you are getting or setting inaccessible. class Maths{ constructor (number) { this.number = number; } } // using a prototype for this class object inheritance. Maths.prototype = Math; var math = new Maths(5); console.log(math.number); console.log(math.random()); var r = new Polygon(5, 10) console.log(r.area) console.log(r.width) console.log(Polygon.get_height) console.log(r.perimeter) console.log(obj.foo); // INHERTANCE IN CLASSES. class Rectangle extends Polygon { constructor(length=1, width=1) { super(); Polygon.call(this, length, width); } } var rect = new Rectangle(5, 5); console.log(rect); console.log(rect.area);
JavaScript
0.99984
@@ -1,12 +1,26 @@ +%0A%22use strict%22%0A %0A// CLASSES%0A @@ -699,17 +699,16 @@ () %7B%0A%09%09 - return t @@ -2129,8 +2129,508 @@ .area);%0A +%0A//NB: this code does not work. debug it if you can.%0A// It raises typeError. this is not a date object.%0A/*%0Aclass MyDate extends Date %7B%0A constructor() %7B%0A super();%0A %7D%0A%0A getFormattedDate() %7B%0A var months = %5B'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',%0A 'Oct', 'Nov', 'Dec'%5D;%0A return this.getDate() + '-' + months%5Bthis.getMonth()%5D + '-' +%0A this.getFullYear();%0A %7D%0A%7D%0A%0Avar aDate = new MyDate();%0Aconsole.log(aDate.getTime());%0Aconsole.log(aDate.getFormattedDate());%0A*/%0A
49af337a75b4c97b7abeeb267a949cfafd9ff7dd
fix baseurl
docs/index.js
docs/index.js
Jenie.setup({ module: { modules: [ { name: 'one', method: function () { return 1; } }, { name: 'two', method: function () { return 2; } }, { name: 'sum', dependencies: ['one', 'two'], method: function (one, two) { return one + two; } } ] }, router: { base: '/jenie', routes: [ { title: 'Root', path: '/', component: 'v-root', componentUrl: '/views/v-root.js' }, { title: 'Test', path: '/test', component: 'v-test', componentUrl: '/views/v-test.html' }, { title: '404', path: '/{*}', component: 'v-404', componentUrl: '/views/v-404.html' } ] } }); Jenie.module.export('say', ['sum'], function (sum) { return function (string) { console.log(string); console.log(sum); }; });
JavaScript
0
@@ -1,12 +1,42 @@ +%0Avar base = document.baseURI;%0A %0AJenie.setup @@ -359,26 +359,8 @@ : %7B%0A -%09%09base: '/jenie',%0A %09%09ro @@ -441,34 +441,40 @@ %09%09componentUrl: +base + ' -/ views/v-root.js' @@ -558,34 +558,40 @@ %09%09componentUrl: +base + ' -/ views/v-test.htm @@ -682,18 +682,24 @@ entUrl: +base + ' -/ views/v-