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
0b4dafa2b5fabd00f94c1796f25a7b2aff5a23ed
configure cssmin
gruntfile.js
gruntfile.js
module.exports = function (grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ jshint: { all: ['gruntfile.js', 'angular-defer-cloak.js'] }, uglify: { dist: { files: { 'angular-defer-cloak.min.js': ['angular-defer-cloak.js'] } } }, bump: { options: { files: ['package.json','bower.json'], updateConfigs: [], commit: true, commitMessage: 'Release v%VERSION%', commitFiles: ['package.json','bower.json'], createTag: true, tagName: 'v%VERSION%', tagMessage: 'Version %VERSION%', push: true, pushTo: 'origin', gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d', globalReplace: false, prereleaseName: false, regExp: false } }, }); grunt.registerTask('default', ['jshint','uglify']); };
JavaScript
0.000001
@@ -161,24 +161,113 @@ r-cloak.js'%5D +,%0A options: %7B%0A globals: %7B%0A angular: true%0A %7D%0A %7D %0A %7D,%0A @@ -411,24 +411,210 @@ %7D%0A %7D,%0A + cssmin: %7B%0A target: %7B%0A files: %5B%7B%0A expand: true,%0A src: %5B'angular-defer-cloak.css'%5D,%0A ext: '.min.css'%0A %7D%5D%0A %7D%0A %7D,%0A bump: @@ -1229,15 +1229,24 @@ 'uglify' +,'cssmin' %5D);%0A%7D;%0A
f91384602f20af852c67b5a0d27e1ac722ee1628
Debug alarm clock trigger time
src/modules/SebastiaanLuca/AlarmClock/src/AlarmClock.js
src/modules/SebastiaanLuca/AlarmClock/src/AlarmClock.js
var debug = require('debug')('SebastiaanLuca:AlarmClock:AlarmClock'); var _ = require('lodash'); var Moment = require('moment'); var Schedule = require('node-schedule'); var Volume = require('modules/SebastiaanLuca/Volume/src/Volume.js'); // module.exports = function AlarmClock(options, player) { var alarmTime = Moment(options.at); var playDuration = options.playTime; var targetVolume = options.volume; var increaseDuration = options.increaseDuration; // Number of times to increase volume per minute var increaseSteps = 5; var increaseVolume = targetVolume / increaseDuration / increaseSteps; var currentVolume = 0; var alarmJob; var fixedSnoozeJob; var init = function () { initAlarm(); }; /* * Initialize the alarm schedules */ var initAlarm = function () { debug('Setting an alarm for %s:%s', alarmTime.hour(), alarmTime.minute()); // Define amounts of minutes to play track before ending alarm var fixedSnoozeTime = Moment(alarmTime); fixedSnoozeTime.add(playDuration, 'minutes'); debug('Snoozing alarm at %s:%s', fixedSnoozeTime.hour(), fixedSnoozeTime.minute()); alarmJob = Schedule.scheduleJob({hour: alarmTime.hour(), minute: alarmTime.minute()}, onAlarmTriggerHandler); fixedSnoozeJob = Schedule.scheduleJob({hour: fixedSnoozeTime.hour(), minute: fixedSnoozeTime.minute()}, onFixedSnoozeTriggerHandler); }; /* * Alarm job trigger event */ var onAlarmTriggerHandler = function () { debug('Alarm triggered!'); // Start from complete silence before we start playing anything Volume.setVolume(0); // Start playing audio player.play(); // TODO: emit event (then turn on an LED or animate them like the KITT LED bar) // Increase volume every (60 seconds / increase steps) seconds Schedule.scheduleJob('*/' + (60 / increaseSteps) + ' * * * * *', onIncreaseVolumeTriggerHandler); }; /* * Alarm snooze job trigger event */ var onFixedSnoozeTriggerHandler = function () { debug('Force-snoozing alarm. Stopping playback.'); // Stop audio playback player.stop(); }; var onIncreaseVolumeTriggerHandler = function () { debug('Gradually increasing volume by %s%', increaseVolume); Volume.setVolume(Math.round(currentVolume)); // Reached target volume if (currentVolume >= targetVolume) { debug('Reached target volume %s, cancelling volume increase job', targetVolume); // Cancel volume job this.cancel(); } // Volume job runs immediately, so we need to time it right // (set to 0 on first run and end at target volume on the minute) currentVolume += increaseVolume; }; init(); };
JavaScript
0.000001
@@ -1660,17 +1660,74 @@ iggered! -' + It is now %25s', moment().format('MMMM Do YYYY, h:mm:ss a') );%0A
3f1f8489dc7d95a1a3e50a8eb40856c0116c36d7
update example
example/example.js
example/example.js
'use strict'; const Pornsearch = require('../').search('tits'); Pornsearch.driver('sex').gifs() .then((gifs) => { console.log(gifs); return Pornsearch.videos(); }) .then(videos => console.log(videos));
JavaScript
0.000001
@@ -53,14 +53,8 @@ rch( -'tits' );%0A%0A
01f4bbd020f12d25f17b5dc9cff435adbc379649
Add a resize function to noteViews and trigger it when window is resized (and the note has been rendered).
js/note_embed.js
js/note_embed.js
(function() { window.dc = window.dc || {}; dc.embed = dc.embed || {}; var notes = dc.embed.notes = dc.embed.notes || {}; var _ = dc._ = window._.noConflict(); var $ = dc.$ = dc.jQuery = window.jQuery.noConflict(true); dc.embed.loadNote = function(embedUrl, opts) { var options = opts || {} var id = parseInt(embedUrl.match(/(\d+).js$/)[1], 10); var noteModel = new dc.embed.noteModel(options); var el = options.container || '#DC-note-' + id; notes[id] = notes[id] || new dc.embed.noteView({model: noteModel, el: el}); $.getScript(embedUrl); if (dc.recordHit) dc.embed.pingRemoteUrl('note', id); }; dc.embed.noteCallback = function(response) { var id = response.id; var note = dc.embed.notes[id]; note.model.attributes = response; note.render(); if (note.model.options && note.model.options.afterLoad) note.model.options.afterLoad(note); }; dc.embed.pingRemoteUrl = function(type, id) { var loc = window.location; var url = loc.protocol + '//' + loc.host + loc.pathname; if (url.match(/^file:/)) return false; url = url.replace(/[\/]+$/, ''); var hitUrl = dc.recordHit; var key = encodeURIComponent(type + ':' + id + ':' + url); $(document).ready( function(){ $(document.body).append('<img alt="" width="1" height="1" src="' + hitUrl + '?key=' + key + '" />'); }); }; dc.embed.noteModel = function(opts) { this.options = opts || {}; }; dc.embed.noteModel.prototype = { get : function(key) { return this.attributes[key]; }, option : function(key) { return this.attributes.options[key]; }, imageUrl : function() { return (this._imageUrl = this._imageUrl || this.get('image_url').replace('{size}', 'normal').replace('{page}', this.get('page'))); }, coordinates : function() { if (this._coordinates) return this._coordinates; var loc = this.get('location'); if (!loc) return null; var css = _.map(loc.image.split(','), function(num){ return parseInt(num, 10); }); return (this._coordinates = { top: css[0], left: css[3], right: css[1], height: css[2] - css[0], width: css[1] - css[3] }); }, viewerUrl : function() { var suffix = '#document/p' + this.get('page') + '/a' + this.get('id'); return this.get('published_url') + suffix; } }; dc.embed.noteView = function(options){ // stolen out of Backbone.View.setElement var element = options.el; this.$el = element instanceof dc.$ ? element : dc.$(element); this.el = this.$el[0]; this.model = options.model; }; dc.embed.noteView.prototype = { $: function(selector){ return this.$el.find(selector); }, render : function() { this.$el.html(JST['note_embed']({note : this.model})); this.renderedWidth = this.$el.width(); if (this.renderedWidth < 700) this.center(); return this.$el; }, center : function() { var $excerpt = this.$('.DC-note-excerpt'); var coords = this.model.coordinates(); if (!coords) return; var annoCenter = coords.left + (coords.width / 2); var viewportWidth = $excerpt.closest('.DC-note-excerpt-wrap').width(); var viewportCenter = viewportWidth / 2; if (coords.left + coords.width > viewportWidth) { if (coords.width > viewportWidth) { $excerpt.css('left', -1 * coords.left); } else { $excerpt.css('left', viewportCenter - annoCenter); } } } }; })();
JavaScript
0
@@ -239,24 +239,198 @@ t(true);%0A %0A + var resizeNotes = _.debounce(function()%7B%0A _.each(notes, function(note, id)%7B if (note.renderedWidth) note.resize(); %7D);%0A %7D, 250);%0A %0A $(window).resize(resizeNotes);%0A %0A dc.embed.l @@ -462,24 +462,24 @@ rl, opts) %7B%0A - var opti @@ -1563,32 +1563,49 @@ '); %7D);%0A %7D;%0A %0A + // Note Model %0A dc.embed.noteM @@ -2633,32 +2633,47 @@ %7D%0A %0A %7D;%0A %0A + // Note View%0A dc.embed.noteV @@ -3815,21 +3815,80 @@ %7D%0A - %7D +,%0A %0A resize: function() %7B console.log(%22Resizing!%22); %7D %0A %7D;%0A%7D)
f4baef25ee52eae2615c5db2f8dcf3d8f45f4493
make secondary text colors match iOS in BusLine
views/transportation/bus/bus-line.js
views/transportation/bus/bus-line.js
// @flow import React from 'react' import {View, StyleSheet, Text} from 'react-native' import type {BusLineType} from './types' import getScheduleForNow from './get-schedule-for-now' import getSetOfStopsForNow from './get-set-of-stops-for-now' import zip from 'lodash/zip' import head from 'lodash/head' import last from 'lodash/last' import moment from 'moment-timezone' import * as c from '../../components/colors' const TIME_FORMAT = 'h:mma' const TIMEZONE = 'America/Winnipeg' let styles = StyleSheet.create({ container: { marginTop: 15, borderBottomWidth: StyleSheet.hairlineWidth, borderColor: '#c8c7cc', }, rowSectionHeader: { paddingTop: 5, paddingBottom: 5, paddingLeft: 15, borderBottomWidth: StyleSheet.hairlineWidth, borderColor: '#c8c7cc', }, rowSectionHeaderText: { color: 'rgb(113, 113, 118)', }, listContainer: { backgroundColor: '#ffffff', flex: 1, flexDirection: 'column', }, busWillSkipStopTitle: { color: c.iosText, }, busWillSkipStopDetail: {}, busWillSkipStopDot: { backgroundColor: 'transparent', borderColor: 'transparent', }, row: { flexDirection: 'row', }, rowDetail: { flex: 1, marginLeft: 0, paddingRight: 10, paddingTop: 8, paddingBottom: 8, flexDirection: 'column', }, notLastRowContainer: { borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: '#c8c7cc', }, passedStopDetail: { }, itemTitle: { color: c.black, paddingLeft: 0, paddingRight: 0, paddingBottom: 3, fontSize: 16, textAlign: 'left', }, itemDetail: { color: c.iosText, paddingLeft: 0, paddingRight: 0, fontSize: 13, textAlign: 'left', }, barContainer: { paddingRight: 5, width: 45, flexDirection: 'column', alignItems: 'center', }, bar: { flex: 1, width: 5, }, dot: { height: 15, width: 15, marginTop: -20, marginBottom: -20, borderRadius: 20, zIndex: 1, }, passedStop: { height: 12, width: 12, }, beforeStop: { borderWidth: 3, backgroundColor: 'white', height: 18, width: 18, }, atStop: { height: 20, width: 20, borderColor: 'white', borderWidth: 3, backgroundColor: 'white', }, atStopTitle: { fontWeight: 'bold', }, passedStopTitle: { color: c.iosText, }, }) export default function BusLineView({line, style, now}: {line: BusLineType, style: Object|number, now: typeof moment}) { let schedule = getScheduleForNow(line.schedules, now) schedule.times = schedule.times.map(timeset => { return timeset.map(time => time === false ? false : moment .tz(time, TIME_FORMAT, true, TIMEZONE) .dayOfYear(now.dayOfYear())) }) let times = getSetOfStopsForNow(schedule, now) let timesIndex = schedule.times.indexOf(times) let pairs: [[string], [typeof moment]] = zip(schedule.stops, times) let barColor = c.salmon if (line.line === 'Blue') { barColor = c.steelBlue } else if (line.line === 'Express') { barColor = c.moneyGreen } let currentStopColor = c.brickRed if (line.line === 'Blue') { currentStopColor = c.midnightBlue } else if (line.line === 'Express') { currentStopColor = c.hollyGreen } let isLastBus = timesIndex === schedule.times.length - 1 let lineTitle = line.line if (timesIndex === 0 && now.isBefore(head(times))) { lineTitle += ` — Starting ${head(times).format('h:mma')}` } else if (now.isAfter(last(times))) { lineTitle += ' — Over for Today' } else if (isLastBus) { lineTitle += ' — Last Bus' } else { lineTitle += ' — Running' } return ( <View style={[styles.container, style]}> <View style={styles.rowSectionHeader}> <Text style={styles.rowSectionHeaderText}> {lineTitle.toUpperCase()} </Text> </View> <View style={[styles.listContainer]}> {pairs.map(([place, time], i) => { let afterStop = time && now.isAfter(time, 'minute') let atStop = time && now.isSame(time, 'minute') let beforeStop = !afterStop && !atStop && time !== false let skippingStop = time === false let isLastRow = i === pairs.length - 1 return <View key={i} style={styles.row}> <View style={styles.barContainer}> <View style={[styles.bar, {backgroundColor: barColor}]} /> <View style={[ styles.dot, afterStop && [styles.passedStop, {borderColor: barColor, backgroundColor: barColor}], beforeStop && [styles.beforeStop, {borderColor: barColor}], atStop && [styles.atStop, {borderColor: currentStopColor}], skippingStop && styles.busWillSkipStopDot, ]} /> <View style={[styles.bar, {backgroundColor: barColor}]} /> </View> <View style={[ styles.rowDetail, !isLastRow && styles.notLastRowContainer, ]}> <Text style={[ styles.itemTitle, skippingStop && styles.busWillSkipStopTitle, afterStop && styles.passedStopTitle, atStop && styles.atStopTitle, ]}> {place} </Text> <Text style={[ styles.itemDetail, skippingStop && styles.busWillSkipStopDetail, ]} numberOfLines={1} > {schedule.times .slice(timesIndex) .map(timeSet => timeSet[i]) .map(time => time === false ? 'None' : time.format(TIME_FORMAT)) .join(' • ')} </Text> </View> </View> })} </View> </View> ) } BusLineView.propTypes = { line: React.PropTypes.object.isRequired, now: React.PropTypes.instanceOf(moment).isRequired, style: React.PropTypes.object, }
JavaScript
0.000001
@@ -988,32 +988,40 @@ color: c.ios +Disabled Text,%0A %7D,%0A bus @@ -1634,32 +1634,40 @@ color: c.ios +Disabled Text,%0A paddin @@ -2384,16 +2384,24 @@ r: c.ios +Disabled Text,%0A
a00e95a92571c18182c8d0d72f2015dd3348a355
Update mojang.username
lib/username.js
lib/username.js
'use strict'; const https = require('https'); function username(usernames, date) { date = date || Date.now() if (!Array.isArray) usernames = [ usernames ]; return new Promise(function(resolve, reject) { https.request({ method: 'POST', hostname: 'api.mojang.com', path: '/profiles/minecraft' }, function(resp) { let data = []; resp.on('data', function(chunk) { data.push(chunk); }); resp.on('end', function() { resolve(JSON.parse(Buffer.concat(data).toString())); }); }).end(JSON.stringify(usernames)); }); } module.exports = username;
JavaScript
0.000007
@@ -14,21 +14,23 @@ %0A%0Aconst -https +request = requi @@ -33,21 +33,26 @@ equire(' -https +./_request ');%0A%0Afun @@ -70,21 +70,16 @@ ame(user -names , date) @@ -84,44 +84,14 @@ ) %7B%0A - date = date %7C%7C Date.now()%0A%0A if ( -! Arra @@ -103,38 +103,96 @@ rray -) +( user -names = %5B usernames %5D;%0A%0A +)) %7B%0A let master = %5B%5D;%0A user.forEach(u =%3E master.push(username(u, date)));%0A re @@ -200,52 +200,72 @@ urn -new Promise -(function(resolve, re +.all(master);%0A %7D%0A%0A if (typeof user === 'ob ject +' ) %7B%0A http @@ -264,381 +264,331 @@ -https.request(%7B%0A +let master = %5B%5D;%0A -method: 'POST',%0A ho +let time st -n am -e: 'api.mojang.com',%0A path: '/profiles/minecraft'%0A %7D, function(resp) %7B%0A let data = %5B +p = '';%0A for (let u in user) %7B%0A timestamp = user%5Bu %5D;%0A -%0A -resp.on('data', function(chunk) %7B +master.push(username(u, timestamp)); %0A +%7D%0A -data.push(chunk);%0A %7D);%0A%0A resp.on('end', function() %7B%0A resolve(JSON.parse(Buffer.concat(data).toString()));%0A %7D);%0A%0A %7D).end(JSON.stringify(usernames)); +return Promise.all(master);%0A %7D%0A%0A date = date %7C%7C Date.now();%0A%0A return request(%7B%0A hostname: 'api.mojang.com',%0A path: '/users/profiles/minecraft/' + user + '?at=' + date, %0A %7D
4ba7557e952269314f34ee8233f12d282e8c794b
use https in favour of http for the table of contents
content/proceedings/proc_links.js
content/proceedings/proc_links.js
function proc_versions() { var versions = ['2021', '2020', '2019', '2018', '2017', '2016', '2015', '2014', '2013','2011','2010', '2009', '2008']; var proc_url = 'http://conference.scipy.org/proceedings/scipy'; document.write('<ul id="navibar">'); for (i=0; i < versions.length; i++) { document.write('<li class="wikilink">'); document.write('<a href="' + proc_url + versions[i] + '">SciPy ' + versions[i] + '</a>'); document.write('</li>'); } document.write('</ul>'); }
JavaScript
0
@@ -185,16 +185,17 @@ = 'http +s ://confe
710bce1e98b52e3a687fc32986779eb923489731
allow for validation values to just be true
lib/validate.js
lib/validate.js
module.exports = function (requestQuery, validation) { var validator = validation.validator; var callback = validation.callback || function () { }; var validated; // Allow for catchall validation if (validator === true) { validated = true; } if (!validated) { validated = Object.keys(requestQuery).every(function (prop) { var validateValue = validator[prop]; var requestQueryValue = requestQuery[prop]; // Fail if there is no validation for this field if (validateValue === undefined) { return; } if (typeof validateValue === "function") { return !!validateValue(requestQuery[prop]); } // It is either a number, string literal, or a RegExp. We can cover all by loading it in a RegExp and matching against it. return new RegExp(validateValue).exec(requestQueryValue); }); } if (validated) { process.nextTick(callback); return true; } };
JavaScript
0.00008
@@ -607,32 +607,118 @@ %0A %7D%0A%0A + if (validateValue === true) %7B%0A return true;%0A %7D%0A%0A if (
51f9718e380cfc8ea7592faa85c1f9e3dd7adf03
Remove whitespace
app/js/controllers/stats.js
app/js/controllers/stats.js
'use strict'; angular.module('OldSchool') .controller('StatsCtrl', ['$scope', '$http', 'XP', function ($scope, $http, XP) { $scope.skills = { 1: [ 'attack', 'strength', 'defence', 'ranged', 'prayer', 'magic', 'runecrafting', 'construction' ], 2: [ 'constitution', 'agility', 'herblore', 'thieving', 'crafting', 'fletching', 'slayer', 'hunter' ], 3: [ 'mining', 'smithing', 'fishing', 'cooking', 'firemaking', 'woodcutting', 'farming' ] }; $scope.player = 'Max Deviant'; $scope.lookup = function () { $http.get('http://localhost:3000/stats/' + $scope.player) .success(function (data, status, headers, config) { $scope.stats = data; }).error(function (data, status, headers, config) { console.log(data); }); }; $scope.generateTooltip = function (skill, exp) { var xp = new XP(); skill = skill.charAt(0).toUpperCase() + skill.slice(1); var currLevel = xp.getLevel(exp); var tooltip = skill + ' XP: ' + exp + '\u000ANext level at: ' + xp.atLevel(currLevel) + '\u000ARemaining XP: ' + xp.forLevel(currLevel, exp); return tooltip; }; $scope.lookup(); }]);
JavaScript
0.999999
@@ -933,24 +933,16 @@ viant';%0A - %0A
602c3b90c95c4920843cacdf7402e1da935d3fec
Add memo validation rules adapted from Stellar Laboratory
src/lib/Validate.js
src/lib/Validate.js
import _ from 'lodash'; import directory from '../directory'; // Some validation regexes and rules in this file are taken from Stellar Laboratory // Do not take code out from this file into other files // Stellar Laboratory is licensed under Apache 2.0 // https://github.com/stellar/laboratory const Validate = { publicKey(input) { if (input === '') { return null; } return StellarSdk.Keypair.isValidPublicKey(input); }, assetCode(input) { return _.isString(input) && input.match(/^[a-zA-Z0-9]+$/g) && input.length > 0 && input.length < 12; }, amount(input) { if (input === '') { return null; } let inputIsPositive = !!input.charAt(0) !== '-'; let inputValidNumber = !!input.match(/^[0-9]*(\.[0-9]+){0,1}$/g); let inputPrecisionLessThan7 = !input.match(/\.([0-9]){8,}$/g); return inputIsPositive && inputValidNumber && inputPrecisionLessThan7; }, }; export default Validate;
JavaScript
0
@@ -289,16 +289,228 @@ ratory%0A%0A +// First argument is always input%0A%0Aconst RESULT_EMPTY = %7B%0A ready: false,%0A%7D%0Aconst RESULT_VALID = %7B%0A ready: true,%0A%7D%0A%0Afunction result(errorMessage) %7B%0A return %7B%0A ready: false,%0A message: errorMessage,%0A %7D%0A%7D%0A%0A const Va @@ -1117,16 +1117,1146 @@ n7;%0A %7D, +%0A%0A // Below are the Validators using the new compound return types%0A memo(input, type) %7B%0A if (input === '') %7B%0A return RESULT_EMPTY;%0A %7D%0A // type is of type: 'MEMO_ID' %7C'MEMO_TEXT' %7C 'MEMO_HASH' %7C 'MEMO_RETURN'%0A switch (type) %7B%0A case 'MEMO_ID':%0A if (!input.match(/%5E%5B0-9%5D*$/g)) %7B%0A return result('MEMO_ID only accepts a positive integer.');%0A %7D%0A if (input !== StellarSdk.UnsignedHyper.fromString(input).toString()) %7B%0A return result(%60MEMO_ID is an unsigned 64-bit integer and the max valid%0A value is $%7BStellarSdk.UnsignedHyper.MAX_UNSIGNED_VALUE.toString()%7D%60)%0A %7D%0A break;%0A case 'MEMO_TEXT':%0A let memoTextBytes = Buffer.byteLength(input, 'utf8');%0A if (memoTextBytes %3E 28) %7B%0A return result(%60MEMO_TEXT accepts a string of up to 28 bytes. $%7BmemoTextBytes%7D bytes entered.%60);%0A %7D%0A break;%0A case 'MEMO_HASH':%0A case 'MEMO_RETURN':%0A if (!input.match(/%5E%5B0-9a-f%5D%7B64%7D$/gi)) %7B%0A return result(%60$%7Btype%7D accepts a 32-byte hash in hexadecimal format (64 characters).%60);%0A %7D%0A break;%0A %7D%0A%0A return RESULT_VALID;%0A %7D %0A%7D;%0A%0Aexp
aac2930ccf307b7baba2f49f05be63adc58d98e0
Update svg.js
html1/svg/svg.js
html1/svg/svg.js
document.getElementById("id_logic_version").innerHTML = "Logic = 2019.12.02.1"; document.getElementById("id_cerere", request_clicked); function ok_f(p) { if (p == "granted") window.addEventListener("deviceorientation", on_gyro_data_uab); else alert("Nu am primit aprobare"); } function not_ok_f(p) { alert(p); } if (typeof(DeviceOrientationEvent.requestPermission) == "function") ; else window.addEventListener("deviceorientation", on_gyro_data_uab); function request_clicked() { DeviceOrientationEvent.requestPermission().then(ok_f).catch(not_ok_f); } //window.addEventListener("devicemotion", on_acc_data_uab); function deseneaza(unghi_x, unghi_y) { // obtinem context grafic var circle = document.getElementById("id_circle"); var svg = document.getElementById("id_svg"); var r = circle.getAttribute("r"); // adaugam un cerc la cale var x = unghi_x / 90 * (svg.width / 2 - r) + svg.width / 2; var y = unghi_y / 90 * (svg.height / 2 - r) + svg.height / 2; // actualizam pozitia cercului circle.setAttribute("cx", x); circle.setAttribute("cy", y); } function on_gyro_data_uab(e) { deseneaza(e.beta, e.gamma); } function on_acc_data_uab(e) { var acc = e.accelerationIncludingGravity; var rot_x = Math.atan(acc.x / acc.z) * 180 / Math.PI; var rot_y = Math.atan(acc.y / acc.z) * 180 / Math.PI; }
JavaScript
0.000001
@@ -109,16 +109,42 @@ _cerere%22 +).addEventListener(%22click%22 , reques
eabfefb307e575c0ae53026e7d86060f7ef34532
remove manual router setup (#1548)
addon-test-support/index.js
addon-test-support/index.js
import { get } from '@ember/object'; import { getContext, settled } from '@ember/test-helpers'; import Promise from 'rsvp'; import Test from 'ember-simple-auth/authenticators/test'; const SESSION_SERVICE_KEY = 'service:session'; const TEST_CONTAINER_KEY = 'authenticator:test'; function ensureAuthenticator(owner) { const authenticator = owner.lookup(TEST_CONTAINER_KEY); if (!authenticator) { owner.register(TEST_CONTAINER_KEY, Test); } } /** * Authenticates the session. * * @param {Object} sessionData Optional argument used to mock an authenticator * response (e.g. a token or user). * @return {Promise} * @public */ export function authenticateSession(sessionData) { const { owner } = getContext(); const session = owner.lookup(SESSION_SERVICE_KEY); owner.setupRouter(); // router must initialize fully before authentication ensureAuthenticator(owner); return session.authenticate(TEST_CONTAINER_KEY, sessionData).then(() => { return settled(); }); } /** * Returns the current session. * * @return {Object} a session service. * @public */ export function currentSession() { const { owner } = getContext(); return owner.lookup(SESSION_SERVICE_KEY); } /** * Invalidates the session. * * @return {Promise} * @public */ export function invalidateSession() { const { owner } = getContext(); const session = owner.lookup(SESSION_SERVICE_KEY); const isAuthenticated = get(session, 'isAuthenticated'); return Promise.resolve().then(() => { if (isAuthenticated) { return session.invalidate(); } }) .then(() => settled()); }
JavaScript
0
@@ -776,85 +776,8 @@ Y);%0A - owner.setupRouter(); // router must initialize fully before authentication%0A en
213ffcb9118f48ce5315a9fd54731a23f448eb66
Update vectorLength
fiesta/common.js
fiesta/common.js
/* Common Fiesta functions Here is a hodgepodge of Fiesta functions. */ // Does my browser support Fiesta? Fiesta.checkSupport = function() { var canvas = !!document.createElement("canvas").getContext; var audio = !!document.createElement("audio").canPlayType; return (canvas && audio); }; // Make a GUID Fiesta._guids = []; Fiesta.guid = function() { var guid = Math.floor(Math.random() * Date.now()); for (var i in this._guids) { if (this._guids[i] === guid) return this.guid(); // Start over; we already have this GUID } this._guids.push(guid); return guid; }; // Get the file extension Fiesta.getFileExtension = function(filename) { var extension = filename.split(".").pop(); if (extension === filename) // No extension return ""; else return extension.toLowerCase(); }; // Does a string contain another string? Fiesta.contains = function(str, searching) { return (str.indexOf(searching) !== -1); }; // Convert rotation measurements Fiesta.degreesToRadians = function(d) { return (d * Math.PI) / 180; }; Fiesta.radiansToDegrees = function(r) { return (r * 180) / Math.PI; }; // Distances between points (2 and 3 dimensions) Fiesta.pointDistance2D = function(x1, y1, x2, y2) { return Fiesta.pointDistance3D(x1, y1, 0, x2, y2, 0); }; Fiesta.pointDistance3D = function(x1, y1, z1, x2, y2, z2) { return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2) + Math.pow(z1 - z2, 2)); }; // Vector length Fiesta.vectorLength = function(i, j, k) { if (!k) k = 0; return Fiesta.pointDistance3D(0, 0, 0, i, j, k); };
JavaScript
0
@@ -1481,13 +1481,49 @@ )%0A%09%09 -k = 0 +return Fiesta.pointDistance2D(0, 0, i, j) ;%0A%09r
0e70e57be0b6a8d7c648b0208e40dcf9236f7c14
change file names
gruntfile.js
gruntfile.js
module.exports = function(grunt){ grunt.initConfig({ /* concat: { options: { seperator: ";" }, target: { src: [], dest: "dest/main.js" } }, */ uglify: { options: { mangle: true, compress: true, sourceMap: 'dest/beagle.map', }, target: { src: 'src/Beagle.js', dest: 'dest/beagle.min.js' } }, watch: { script: { files: ['src/*.js'], tasks: ['uglify'], options: { livereload: 3111 } } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask("default", ['uglify']); }
JavaScript
0.000003
@@ -306,20 +306,20 @@ est/ -beagle +localDB .map' -, %0A%09%09%09 @@ -356,14 +356,15 @@ src/ -Beagle +localDB .js' @@ -385,14 +385,15 @@ est/ -beagle +localDB .min
735c7caaae4c91ee04cb48e1caf59d8d574ae632
Fix typo for sb3 test files
test/integration/scratch-tests.js
test/integration/scratch-tests.js
/* global vm, render, Promise */ const {Chromeless} = require('chromeless'); const test = require('tap').test; const path = require('path'); const fs = require('fs'); const chromeless = new Chromeless(); const indexHTML = path.resolve(__dirname, 'index.html'); const testDir = (...args) => path.resolve(__dirname, 'scratch-tests', ...args); const testFile = file => test(file, async t => { // start each test by going to the index.html, and loading the scratch file const says = await chromeless.goto(`file://${indexHTML}`) .setFileInput('#file', testDir(file)) // the index.html handler for file input will add a #loaded element when it // finishes. .wait('#loaded') .evaluate(() => { // This function is run INSIDE the integration chrome browser via some // injection and .toString() magic. We can return some "simple data" // back across as a promise, so we will just log all the says that happen // for parsing after. // this becomes the `says` in the outer scope const messages = []; const TIMEOUT = 5000; vm.runtime.on('SAY', (_, __, message) => { messages.push(message); }); vm.greenFlag(); const startTime = Date.now(); return Promise.resolve() .then(async () => { // waiting for all threads to complete, then we return while (vm.runtime.threads.some(thread => vm.runtime.isActiveThread(thread))) { if ((Date.now() - startTime) >= TIMEOUT) { // if we push the message after end, the failure from tap is not very useful: // "not ok test after end() was called" messages.unshift(`fail Threads still running after ${TIMEOUT}ms`); break; } await new Promise(resolve => setTimeout(resolve, 50)); } return messages; }); }); // Map string messages to tap reporting methods. This will be used // with events from scratch's runtime emitted on block instructions. let didPlan = false; let didEnd = false; const reporters = { comment (message) { t.comment(message); }, pass (reason) { t.pass(reason); }, fail (reason) { t.fail(reason); }, plan (count) { didPlan = true; t.plan(Number(count)); }, end () { didEnd = true; t.end(); } }; // loop over each "SAY" we caught from the VM and use the reporters says.forEach(text => { // first word of the say is going to be a "command" const command = text.split(/\s+/, 1)[0].toLowerCase(); if (reporters[command]) { return reporters[command](text.substring(command.length).trim()); } // Default to a comment with the full text if we didn't match // any command prefix return reporters.comment(text); }); if (!didPlan) { t.comment('did not say "plan NUMBER_OF_TESTS"'); } // End must be called so that tap knows the test is done. If // the test has a SAY "end" block but that block did not // execute, this explicit failure will raise that issue so // it can be resolved. if (!didEnd) { t.fail('did not say "end"'); t.end(); } }); const testBubbles = () => test('bubble snapshot', async t => { const bubbleSvg = await chromeless.goto(`file://${indexHTML}`) .evaluate(() => { const testString = '<e*&%$&^$></!abc\'>'; return render._svgTextBubble._buildTextFragment(testString); }); t.matchSnapshot(bubbleSvg, 'bubble-text-snapshot'); t.end(); }); // immediately invoked async function to let us wait for each test to finish before starting the next. (async () => { const files = fs.readdirSync(testDir()) .filter(uri => uri.endsWith('.sb2') || uri.endsWidth('.sb3')); for (const file of files) { await testFile(file); } await testBubbles(); // close the browser window we used await chromeless.end(); })();
JavaScript
0.000011
@@ -4201,17 +4201,16 @@ i.endsWi -d th('.sb3
aefc540db1a8b323d00bd7ded7b82e797b0c7200
add help for import
cli/commands.js
cli/commands.js
module.exports = { app: { default: true, desc: 'Create a new JHipster application based on the selected options' }, aws: { desc: 'Deploy the current application to Amazon Web Services' }, 'aws-containers': { desc: 'Deploy the current application to Amazon Web Services using ECS' }, 'ci-cd': { desc: 'Create pipeline scripts for popular Continuous Integration/Continuous Deployment tools' }, client: { desc: 'Create a new JHipster client-side application based on the selected options' }, cloudfoundry: { desc: 'Generate a `deploy/cloudfoundry` folder with a specific manifest.yml to deploy to Cloud Foundry' }, 'docker-compose': { desc: 'Create all required Docker deployment configuration for the selected applications' }, entity: { argument: ['name'], desc: 'Create a new JHipster entity: JPA entity, Spring server-side components and Angular client-side components' }, 'export-jdl': { argument: ['jdlFile'], desc: 'Create a JDL file from the existing entities' }, gae: { desc: 'Deploy the current application to Google App Engine' }, heroku: { desc: 'Deploy the current application to Heroku' }, 'import-jdl': { argument: ['jdlFiles...'], desc: 'Create entities from the JDL file passed in argument' }, info: { desc: 'Display information about your current project and system' }, kubernetes: { desc: 'Deploy the current application to Kubernetes' }, languages: { argument: ['languages...'], desc: 'Select languages from a list of available languages. The i18n files will be copied to the /webapp/i18n folder' }, // login: { // desc: 'Link the installed JHipster CLI to your JHipster Online account' // }, // logout: { // desc: 'Unlink the installed JHipster CLI from your JHipster Online account' // }, openshift: { desc: 'Deploy the current application to OpenShift' }, 'rancher-compose': { desc: 'Deploy the current application to Rancher' }, server: { desc: 'Create a new JHipster server-side application' }, 'spring-service': { alias: 'service', argument: ['name'], desc: 'Create a new Spring service bean' }, 'spring-controller': { argument: ['name'], desc: 'Create a new Spring controller' }, upgrade: { desc: 'Upgrade the JHipster version, and upgrade the generated application' } };
JavaScript
0
@@ -1340,32 +1340,55 @@ 'jdlFiles...'%5D,%0A + cliOnly: true,%0A desc: 'C @@ -1439,16 +1439,765 @@ rgument' +,%0A help: %60%0A --skip-install # Do not automatically install dependencies Default: false%0A --db # Provide DB option for the application when using skip-server flag%0A --json-only # Generate only the JSON files and skip entity regeneration Default: false%0A --ignore-application # Ignores application generation Default: false%0A --skip-ui-grouping # Disable the UI grouping behaviour for entity client side code Default: false%0A%0AArguments:%0A jdlFiles # The JDL file names Type: String%5B%5D Required: true%0A%0AExample:%0A jhipster import-jdl myfile.jdl%0A jhipster import-jdl myfile1.jdl myfile2.jdl%0A %60 %0A %7D,%0A
e64e4d446462477dff3c5347e7d3b5f3cb2044b5
Fix bug to make schedule url
assets/javascripts/discourse/initializers/discourse-calendar.js.es6
assets/javascripts/discourse/initializers/discourse-calendar.js.es6
import { withPluginApi } from "discourse/lib/plugin-api"; function initializeDiscourseCalendar(api) { const siteSettings = api.container.lookup("site-settings:main"); if (!siteSettings.calendar_enabled) return; api.onPageChange((url, title) => { const $button = $(".calendar-toggle-button"); if($button.length < 1) return; $button.off("click"); $(function() { const $calendarContainer = $(".calendar-container"); $button.click(function(){ if($calendarContainer.is(":visible")){ $calendarContainer.slideUp("slow"); $(this).find("span").text(I18n.t("calendar.ui.show_label")); }else{ $calendarContainer.slideDown("slow"); $(this).find("span").text(I18n.t("calendar.ui.hide_label")); $(".calendar").fullCalendar("render"); } }); }); const $div = $(".calendar"); if($div.length > 0) initializeCalendar(url, $div); }); } function initializeCalendar(url, $div){ $div.fullCalendar("destroy"); $div.fullCalendar({ header: { left: "prev,next today", center: "title", right: "month,agendaWeek,agendaDay,listMonth" }, locale: moment.locale(), navLinks: true, editable: false, eventLimit: true, timeFormat:"H:m", height: 600, contentHeidht: 500, events : function(start, end, timezone, callback){ $.ajax({ url: "/calendar/schedules".concat(url), dataType: "json", data: { start: start.unix(), end: end.unix() }, method: "GET", success: function(data){ var events = data.schedules; callback(events); } }); } }); } export default { name: "discourse-calendar", initialize() { withPluginApi("0.5", initializeDiscourseCalendar); } };
JavaScript
0.000001
@@ -293,24 +293,83 @@ le-button%22); +%0A const postfixUrl = url.replace(Discourse.BaseUri, %22%22); %0A%0A if($bu @@ -975,33 +975,40 @@ tializeCalendar( -u +postfixU rl, $div);%0A %7D); @@ -1039,17 +1039,24 @@ alendar( -u +postfixU rl, $div @@ -1477,16 +1477,33 @@ url: +Discourse.getURL( %22/calend @@ -1527,12 +1527,20 @@ cat( -u +postfixU rl) +) ,%0A
700cb238c41ea02cc90914dea929476b56aa926c
Remove subscription that did not do anything
src/GeoLocationForPhoneGap/widget/GeoLocationForPhoneGap.js
src/GeoLocationForPhoneGap/widget/GeoLocationForPhoneGap.js
define([ "mxui/widget/_WidgetBase", "mxui/dom", "dojo/dom-class", "dojo/dom-construct", "dojo/_base/declare" ], function(_WidgetBase, mxuiDom, dojoClass, dojoConstruct, declare) { "use strict"; return declare('GeoLocationForPhoneGap.widget.GeoLocationForPhoneGap', _WidgetBase, { buttonLabel: "", latAttr: 0.0, longAttr: 0.0, onchangemf: "", _result : null, _button : null, _hasStarted : false, _obj : null, _objSub : null, // Externally executed mendix function to create widget. startup: function() { if (this._hasStarted) return; this._hasStarted = true; // Setup widget this._setupWX(); // Create childnodes this._createChildnodes(); // Setup events this._setupEvents(); }, update : function (obj, callback) { if (this._objSub) { this.unsubscribe(this._objSub); this._objSub = null; } if (obj === null){ // Sorry no data no show! console.log('Whoops... the GEO Location has no data!'); } else { this._objSub = mx.data.subscribe({ guid: obj.getGuid(), callback: this.update }, this); this._obj = obj; } if (callback) callback(); }, // Setup _setupWX: function() { // Set class for domNode dojoClass.add(this.domNode, 'wx-geolocation-container'); // Empty domnode of this and appand new input dojoConstruct.empty(this.domNode); }, _createChildnodes: function() { // Placeholder container this._button = mxuiDom.create("div", { 'class': 'wx-mxwxgeolocation-button btn btn-primary' }); if (this.buttonClass) dojoClass.add(this._button, this.buttonClass); this._button.textContent = this.buttonLabel || 'GEO Location'; // Add to wxnode this.domNode.appendChild(this._button); }, // Internal event setup. _setupEvents : function() { this.connect(this._button, "click", function(evt) { console.log('GEO Location start getting location.'); navigator.geolocation.getCurrentPosition( this._geolocationSuccess.bind(this), this._geolocationFailure.bind(this), { timeout: 10000, enableHighAccuracy: true }); }); }, _geolocationSuccess : function(position){ this._obj.set(this.latAttr, position.coords.latitude); this._obj.set(this.longAttr, position.coords.longitude); this._executeMicroflow(); }, _geolocationFailure : function(error){ console.log('GEO Location failure!'); console.log(error.message); if(this._result){ this._result.textContent = 'GEO Location failure...'; } else { this._result = mxuiDom.create("div"); this._result.textContent = 'GEO Location failure...'; this.domNode.appendChild(this._result); } }, _executeMicroflow : function () { if (this.onchangemf && this._obj) { mx.data.action({ params: { actionname: this.onchangemf, applyto: 'selection', guids: [this._obj.getGuid()] }, error: function() {}, }); } } }); }); // Compatibility with older mendix versions. require([ "GeoLocationForPhoneGap/widget/GeoLocationForPhoneGap" ], function() {});
JavaScript
0
@@ -488,32 +488,8 @@ ull, -%0A _objSub : null, %0A%0A @@ -907,17 +907,16 @@ function - (obj, ca @@ -933,28 +933,24 @@ -if ( this._objSub @@ -950,488 +950,15 @@ _obj -Sub) %7B%0A this.unsubscribe(this._objSub);%0A this._objSub = null;%0A %7D%0A%0A if (obj === null)%7B%0A // Sorry no data no show!%0A console.log('Whoops... the GEO Location has no data!');%0A %7D else %7B%0A this._objSub = mx.data.subscribe(%7B%0A guid: obj.getGuid(),%0A callback: this.update%0A %7D, this);%0A%0A this._obj = obj;%0A %7D + = obj; %0A%0A
1d8c5d0d92a79a9713887a1651c54f4ce5c06d88
Fix incorrect promise chain return
angular-quasar.js
angular-quasar.js
function unpackHttpRes(fn, value) { if (angular.isObject(value) && value.data && value.status && value.headers && value.config && value.statusText && angular.isFunction(value.headers)) { fn(value.data, value.status, value.headers, value.config); } else { fn(value); } } angular.module('jutaz.quasar', []).config(['$provide', function ($provide) { $provide.decorator('$q', ['$delegate', function ($delegate) { var q = { when: $delegate.when, reject: $delegate.reject, all: $delegate.all, defer: $delegate.defer }; function decoratePromise(promise) { promise._then = promise.then; promise.then = function(thenFn, errFn, notifyFn) { var p = promise._then(thenFn, errFn, notifyFn); return decoratePromise(p); }; promise.success = function (fn) { promise.then(unpackHttpRes.bind(undefined, fn)); return promise; }; promise.error = function (fn) { promise.then(null, unpackHttpRes.bind(undefined, fn)); return promise; }; promise.delay = promise.timeout = function (fn, time) { // In case people have other preference if (angular.isNumber(fn) && angular.isFunction(time)) { var tmp = fn; fn = time; time = tmp; } var deferred = q.defer(); setTimeout(function () { promise.then(fn).then(deferred.resolve); }, time); return decoratePromise(deferred.promise); }; promise.all = function (fn) { promise.then($delegate.all).then(fn); return decoratePromise(promise); }; return promise; } $delegate.fcall = function (fn) { return $delegate.when(true).then(fn); }; $delegate.defer = function() { var deferred = q.defer(); decoratePromise(deferred.promise); return deferred; }; ['all', 'reject', 'when'].forEach(function (fn) { $delegate[fn] = function () { return decoratePromise(q[fn].apply(this, arguments)); }; }); return $delegate; }]); }]);
JavaScript
0.99867
@@ -779,32 +779,39 @@ tion (fn) %7B%0A%09%09%09%09 +return promise.then(unp @@ -843,36 +843,16 @@ , fn));%0A -%09%09%09%09return promise;%0A %09%09%09%7D;%0A%09%09 @@ -880,32 +880,39 @@ tion (fn) %7B%0A%09%09%09%09 +return promise.then(nul @@ -954,28 +954,8 @@ ));%0A -%09%09%09%09return promise;%0A %09%09%09%7D
8476f6c9de440c1c5c14acdfdacf9ea118a970fc
fix jshint error
gruntfile.js
gruntfile.js
var GittyCache = require('./tasks/utils/gitty-cache'); module.exports = function(grunt) { require('load-grunt-config')(grunt); require('load-grunt-tasks')(grunt); grunt.loadTasks('tasks'); grunt.loadTasks('backbone.marionette/tasks'); GittyCache.setReleaseTag(grunt.option('TAG')); grunt.config.merge({ 'gitty:releaseTag': { marionette: { options: { repo: 'backbone.marionette' } } }, 'gitty:checkoutTag': { marionette: { options: { repo: 'backbone.marionette' } } }, compileDocs: { marionette: { options: { repo: 'backbone.marionette', template: 'src/docs/template.hbs', indexTemplate: 'src/docs/index.hbs', svgIcons: 'src/images/svg-sprite.svg' }, src: 'backbone.marionette/docs', dest: 'dist/docs' } }, compileApi: { marionette: { options: { repo: 'backbone.marionette' }, src: 'src/api', dest: 'dist/api' } }, compileAnnotatedSrc: { marionette: { options: { repo: 'backbone.marionette', src: 'backbone.marionette/lib/backbone.marionette.js', template: 'src/docco/marionette.jst', output: 'dist/annotated-src/' } } }, compileAdditionalResources: { marionette: { options: { resUrl: 'https://raw.githubusercontent.com/sadcitizen/awesome-marionette/master/README.md', output: 'dist/data' } } } }); };
JavaScript
0.000001
@@ -1421,32 +1421,66 @@ options: %7B%0A + /*jshint ignore:start*/%0A resUrl @@ -1565,16 +1565,48 @@ ME.md',%0A + /*jshint ignore:end*/%0A
89388e97d77002c45777714ffae489664de8a00c
fix ie10 scroller issue
aura-components/src/main/components/ui/treeNode/treeNodeRenderer.js
aura-components/src/main/components/ui/treeNode/treeNodeRenderer.js
/* * Copyright (C) 2012 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ({ /** * After the initial render, add the active DOM attribute if necessary */ afterRender : function(cmp) { var active = cmp.get('v.active'); if (active) { cmp.getElement().setAttribute('active', 'true'); } return this.superAfterRender(cmp); }, /** * When the active node changes, we may need to scroll it into view. * Expansion changes and the like mean we must wait until rerender time to * react to this event. */ rerender : function(cmp) { var activeAttr = cmp.getAttributes().getValue("active"); if (activeAttr.isDirty()) { var active = activeAttr.getBooleanValue(); var elem = cmp.getElement(); if (active) { elem.setAttribute('active', 'true'); elem.scrollIntoViewIfNeeded(); } else { elem.removeAttribute('active'); } } return this.superRerender(cmp); }, }
JavaScript
0
@@ -1455,38 +1455,195 @@ -elem.scrollIntoViewIfNeeded(); +if(elem.scrollIntoViewIfNeeded)%7B%0A%09 elem.scrollIntoViewIfNeeded(); %0A %7D%0A else%7B%0A%09%09%09%09%09elem.scrollIntoView(false);%0A %7D %0A
2205e45aea4bb1bf685818a9827d7df2f9b2202e
Clean up code
examples/client.js
examples/client.js
'use strict'; const soupbintcp = require('../'); const client = soupbintcp.createClient(4000, 'localhost', () => { client.login({ username: 'foo', password: 'bar', requestedSession: '', requestedSequenceNumber: 0, }); }); client.on('accept', function(payload) { client.send(Buffer.from('Hello world!', 'ascii')); }); client.on('message', function(payload) { console.log(payload.toString('ascii')); client.logout(); });
JavaScript
0.000004
@@ -258,24 +258,16 @@ ccept', -function (payload @@ -263,24 +263,27 @@ ', (payload) + =%3E %7B%0A client. @@ -356,16 +356,8 @@ e', -function (pay @@ -361,16 +361,19 @@ payload) + =%3E %7B%0A con
4351219a048b0fabb129dafffe699a17a24e30d9
Update files
gruntfile.js
gruntfile.js
module.exports = function(grunt){ require("matchdep").filterDev("grunt-*").forEach(grunt.loadNpmTasks); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), htmlhint: { build: { options: { 'tag-pair': true, 'tagname-lowercase': true, 'attr-value-double-quotes': true, 'doctype-first': true, 'spec-char-escape': true, 'id-unique': true, 'head-script-disabled': true, 'style-disabled': true }, src: ['index.html'] } }, uglify: { build: { options: { mangle: false }, src: ['src/js/util.js', 'src/js/files.js', 'src/js/tables.js', 'src/js/components.js', 'src/js/convert.js', 'src/js/main.js', 'src/js/ui.js' ], dest: 'build/scripts.min.js' } }, cssmin: { build: { src: 'src/css/**/*.css', dest: 'build/styles.min.css' } }, watch: { html: { files: ['index.html'], tasks: ['htmlhint'] }, js: { files: ['src/js/**/*.js'], tasks: ['uglify'] }, css: { files: ['src/css/**/*.css'], tasks: ['cssmin'] } } }); grunt.registerTask('default', []); };
JavaScript
0.000001
@@ -96,24 +96,267 @@ NpmTasks);%0A%0A +%09var jsFiles = %5B%0A%09%09// maintain file order!%0A 'src/js/util.js',%0A 'src/js/files.js',%0A 'src/js/tables.js',%0A 'src/js/components.js',%0A 'src/js/convert.js',%0A 'src/js/main.js',%0A 'src/js/ui.js'%0A %5D;%0A%0A%0A grunt.in @@ -945,145 +945,15 @@ rc: -%5B'src/js/util.js', 'src/js/files.js', 'src/js/tables.js', 'src/js/components.js', 'src/js/convert.js', 'src/js/main.js', 'src/js/ui.js' %5D +jsFiles ,%0A @@ -1469,17 +1469,22 @@ efault', - +%0A %09 %5B%5D);%0A%0A%7D;
11d1513eedf26a4a955801c9e9d5d4e8656654c8
Add commas after object responses for default patterns, see https://github.com/phetsims/scenery/issues/1207
js/accessibility/speaker/VoicingResponsePatterns.js
js/accessibility/speaker/VoicingResponsePatterns.js
// Copyright 2021, University of Colorado Boulder /** * A collection of string patterns that are used with VoicingManager.collectResponses. Responses for Voicing are * categorized into one of "Name", "Object", "Context", or "Hint" responses. A node that implements voicing may * have any number of these responses and each of these responses can be enabled/disabled by user preferences * through the Properties of voicingManager. So we need string patterns that include each combination of response. * * Furthermore, you may want to control the order, punctuation, or other content in these patterns, so the default * cannot be used. VoicingResponsePatterns will have a collections of patterns that may be generally useful. But if * you need a collection that is not provided here, you can use createResponsePatterns() to create an object based * on one of the pre-made collections in this file. If you need something totally different, create your own from * scratch. The object you create must have exactly the keys of DEFAULT_RESPONSE_PATTERNS. * * @author Jesse Greenberg (PhET Interactive Simulations) */ import merge from '../../../../phet-core/js/merge.js'; import scenery from '../../scenery.js'; const VoicingResponsePatterns = { // Default order and punctuation for Voicing responses. DEFAULT_RESPONSE_PATTERNS: { nameObjectContextHint: '{{NAME}}, {{OBJECT}} {{CONTEXT}} {{HINT}}', nameObjectContext: '{{NAME}}, {{OBJECT}} {{CONTEXT}}', nameObjectHint: '{{NAME}}, {{OBJECT}} {{HINT}}', nameContextHint: '{{NAME}}, {{CONTEXT}} {{HINT}}', nameObject: '{{NAME}}, {{OBJECT}} ', nameContext: '{{NAME}}, {{CONTEXT}}', nameHint: '{{NAME}}, {{HINT}}', name: '{{NAME}}', objectContextHint: '{{OBJECT}} {{CONTEXT}} {{HINT}}', objectContext: '{{OBJECT}} {{CONTEXT}}', objectHint: '{{OBJECT}} {{HINT}}', contextHint: '{{CONTEXT}} {{HINT}}', object: '{{OBJECT}} ', context: '{{CONTEXT}}', hint: '{{HINT}}' }, // Like the default response patterns, but the name follows the object response when both are present. OBJECT_NAME_CONTEXT_HINT_PATTERNS: { nameObjectContextHint: '{{OBJECT}} {{NAME}}, {{CONTEXT}} {{HINT}}', nameObjectContext: '{{OBJECT}} {{NAME}}, {{CONTEXT}}', nameObjectHint: '{{OBJECT}} {{NAME}}, {{HINT}}', nameContextHint: '{{NAME}}, {{CONTEXT}} {{HINT}}', nameObject: '{{OBJECT}} {{NAME}}', nameContext: '{{NAME}}, {{CONTEXT}}', nameHint: '{{NAME}}, {{HINT}}', name: '{{NAME}}', objectContextHint: '{{OBJECT}} {{CONTEXT}} {{HINT}}', objectContext: '{{OBJECT}} {{CONTEXT}}', objectHint: '{{OBJECT}} {{HINT}}', contextHint: '{{CONTEXT}} {{HINT}}', object: '{{OBJECT}} ', context: '{{CONTEXT}}', hint: '{{HINT}}' }, /** * Create an Object containing patterns for responses that are generated by voicingManager.collectResponses. This * is convenient if you want to use one of the premade collections of patterns above, but have some of the patterns * slightly modified. * @public * * @param {Object} source - source for merge, probably one of the premade patterns objects in VoicingResponsPatterns * @param {Object} [options] - Object with keys that you want overridden * @returns {Object} */ createResponsePatterns( source, options ) { const newPatterns = merge( VoicingResponsePatterns.DEFAULT_RESPONSE_PATTERNS, options ); VoicingResponsePatterns.validatePatternKeys( newPatterns ); return newPatterns; }, /** * Ensures that keys of the provided pattern will work voicingManager.collectResponses. * @public * * @param {Object} object */ validatePatternKeys( object ) { assert && assert( _.difference( Object.keys( object ), Object.keys( VoicingResponsePatterns.DEFAULT_RESPONSE_PATTERNS ) ).length === 0, 'keys for the created patterns will not work, they must match DEFAULT_RESPONSE_PATTERNS exactly.' ); } }; scenery.register( 'VoicingResponsePatterns', VoicingResponsePatterns ); export default VoicingResponsePatterns;
JavaScript
0
@@ -1378,32 +1378,33 @@ ME%7D%7D, %7B%7BOBJECT%7D%7D +, %7B%7BCONTEXT%7D%7D %7B%7BH @@ -1447,32 +1447,33 @@ ME%7D%7D, %7B%7BOBJECT%7D%7D +, %7B%7BCONTEXT%7D%7D',%0A @@ -1504,32 +1504,33 @@ ME%7D%7D, %7B%7BOBJECT%7D%7D +, %7B%7BHINT%7D%7D',%0A @@ -1609,32 +1609,33 @@ ME%7D%7D, %7B%7BOBJECT%7D%7D +, ',%0A nameCont @@ -1748,32 +1748,33 @@ int: '%7B%7BOBJECT%7D%7D +, %7B%7BCONTEXT%7D%7D %7B%7BH @@ -1803,32 +1803,33 @@ ext: '%7B%7BOBJECT%7D%7D +, %7B%7BCONTEXT%7D%7D',%0A @@ -1846,32 +1846,33 @@ int: '%7B%7BOBJECT%7D%7D +, %7B%7BHINT%7D%7D',%0A @@ -2164,32 +2164,33 @@ int: '%7B%7BOBJECT%7D%7D +, %7B%7BNAME%7D%7D, %7B%7BCON @@ -2233,32 +2233,33 @@ ext: '%7B%7BOBJECT%7D%7D +, %7B%7BNAME%7D%7D, %7B%7BCON @@ -2290,32 +2290,33 @@ int: '%7B%7BOBJECT%7D%7D +, %7B%7BNAME%7D%7D, %7B%7BHIN @@ -2403,16 +2403,17 @@ OBJECT%7D%7D +, %7B%7BNAME%7D @@ -2542,32 +2542,33 @@ int: '%7B%7BOBJECT%7D%7D +, %7B%7BCONTEXT%7D%7D %7B%7BH @@ -2605,16 +2605,17 @@ OBJECT%7D%7D +, %7B%7BCONTE @@ -2648,16 +2648,17 @@ OBJECT%7D%7D +, %7B%7BHINT%7D @@ -2694,32 +2694,32 @@ XT%7D%7D %7B%7BHINT%7D%7D',%0A + object: '%7B%7BO @@ -2717,33 +2717,32 @@ ect: '%7B%7BOBJECT%7D%7D - ',%0A context:
08a84485985fc5cf93a121ad0601b9e41e41affb
fix file path
gruntfile.js
gruntfile.js
module.exports = function(grunt) { require('load-grunt-tasks')(grunt); var srcPath = './src', distPath = './dist'; grunt.initConfig({ srcPath: srcPath, distPath: distPath, express: { server: { options: { server: 'server.js', port: Number(process.env.PORT || 3000), livereload: true } } }, copy: { dev: { files: [ {src: 'bower_components/angular/angular.js', dest:'src/libs/angular/angular.js'} ] }, dist: { files: [ {src: srcPath + '/css/ng-wig.css', dest: distPath + '/css/ng-wig.css'}, ] } }, ngAnnotate: { app1: { files: { '<%= distPath %>/ng-wig.js': [ srcPath + '/javascript/app/ng-wig/!(angular.element.outerHeight).js', srcPath + '/javascript/app/plugins/formats.js', srcPath + '/javascript/app/ng-wig/angular.element.outerHeight.js', srcPath + '/javascript/app/templates.js', '!src/javascript/app/**/tests/*.js'] } } }, uglify: { build: { files: { 'dist/ng-wig.min.js': [ distPath +'/ng-wig.js'] } } }, cssmin: { build: { files: { 'dist/css/ng-wig.min.css': [ distPath +'/css/ng-wig.css'] } } }, clean:{ libs: ['src/libs/**/*'], bower: ['bower_components'], target: ['dist/**'] }, html2js: { options: { base: srcPath + '/javascript/app/', module: 'ngwig-app-templates' }, main: { src: [ srcPath + '/javascript/app/ng-wig/views/*.html'], dest: srcPath + '/javascript/app/templates.js' } }, watch: { templates: { files:['src/javascript/app/**/views/**/*.html'], tasks: ['html2js'] } }, bump: { options: { files: ['package.json', 'bower.json', 'dist/ng-wig.js', 'src/javascript/app/ng-wig/ng-wig.js'], commitFiles: ['package.json', 'bower.json', 'dist/**', 'src/javascript/app/ng-wig/ng-wig.js'], createTag: true, tagName: 'v%VERSION%', tagMessage: 'Version %VERSION%', push: false } } }); grunt.registerTask('default', ['start']); grunt.registerTask('start', ['html2js', 'express', 'watch', 'express-keepalive',]); grunt.registerTask('install', ['clean:libs', 'copy:dev', 'clean:bower', 'html2js']); grunt.registerTask('build', ['html2js', 'copy:dist', 'ngAnnotate', 'uglify', 'cssmin', 'bump:patch']); grunt.registerTask('upversion', ['bump:minor']); //grunt.registerTask('upversion', ['bump:major']); };
JavaScript
0.000003
@@ -894,16 +894,22 @@ formats. +ngWig. js',%0A
a9769d824402999b37c922593c8840ae61821db5
Remove unused imports
index.android.js
index.android.js
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, TextInput, View, ScrollView, Button, Image, TouchableHighlight } from 'react-native'; import Realm from 'realm'; import SortableListView from 'react-native-sortable-listview'; import Utils from './src/utils'; import Repository from './src/Repository'; import {DateOnly} from './src/util/time'; import DayModel from './src/DayModel'; import DayBadge from './src/components/DayBadge'; import TaskListItem from './src/components/TaskListItem'; import SixBus from './src/global/SixBus'; import SixController from './src/global/SixController'; import Icon from 'react-native-vector-icons/Ionicons'; import moment from 'moment'; export default class Six extends Component { constructor() { super(); this.repository = new Repository(); this.bus = new SixBus(); this.controller = new SixController(this.bus); this.state = { days: this.repository.get('Day'), currDay: this.repository.get('Day')[0], tasks: this.repository.get('Task') } } render() { var _scrollView: ScrollView; return ( <View style={styles.container}> <ScrollView ref={(scrollView) => { _scrollView = scrollView; }} automaticallyAdjustContentInsets={false} horizontal={true} style={styles.scrollView}> {this.state.days.map((day, i) => <DayBadge key={i} day={day} setDay={this.setCurrentDay.bind(this, i)}/>)} </ScrollView> <Text style={styles.welcome}>Day: {this.state.currDay.date.toDateString()}</Text> <SortableListView style={{flex: 3}} data={this.state.currDay.tasks} onRowMoved={e => { this.repository.move(this.state.currDay, e.from, e.to); }} renderRow={row => <TaskListItem data={row} toggle={() => this.repository.toggleTaskCompleted(row)} saveDesc={(task, desc) => this.repository.updateTaskDescription(task, desc)} />} /> </View> ); } setCurrentDay(ix) { this.setState({ currDay: this.repository.get('Day')[ix] }); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, button: { color: '#841584' }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, scrollView: { marginTop: 20, flex: 10, maxHeight: 128 }, horizontalScrollView: { height: 50, }, block: { flex: 1, margin: 8, borderRadius: 20, justifyContent: 'center', alignItems: 'center' }, }); AppRegistry.registerComponent('Six', () => Six);
JavaScript
0.000001
@@ -86,21 +86,8 @@ xt,%0A - TextInput,%0A Vi @@ -108,48 +108,8 @@ ew,%0A - Button,%0A Image,%0A TouchableHighlight%0A %7D fr @@ -297,50 +297,8 @@ y';%0A -import %7BDateOnly%7D from './src/util/time';%0A impo @@ -544,96 +544,8 @@ ';%0A%0A -import Icon from 'react-native-vector-icons/Ionicons';%0Aimport moment from 'moment';%0A%0A%0A%0A%0A expo
f65c4d005d285cac3a8ba3419bdbdc29dd0044bc
fix tests after migration to react16
lib/__tests__/Link.test.js
lib/__tests__/Link.test.js
/* eslint-env browser, jest */ import React from 'react'; import testRenderer from 'react-test-renderer'; import WithContext from 'react-with-context'; import { mount } from 'enzyme'; import Link from '../Link'; import RouterContext from '../RouterContext'; import Route from '../Route'; import history from './__mocks__/history'; describe('Link', () => { it('should render something', () => { const context = new RouterContext(); context.setRoutes({ state: new Route('state', { url: '/' }) }); context.setState('state'); const component = testRenderer.create( <WithContext context={{ router: context }}> <Link className="LinkClass" target="_blank" state="state" >Hello!</Link> </WithContext> ); expect(component.toJSON()).toMatchSnapshot(); }); it('should set classes', () => { const context = new RouterContext(); context.setRoutes({ state: new Route('state', { url: '/state' }), 'state.some': new Route('state.some', { url: '/some' }) }); context.setState('state'); const component1 = testRenderer.create( <WithContext context={{ router: context }}> <Link state="state" disabled disabledClass="disabled" activeClass="active" activePathClass="active-path" activeStateClass="active-state">Hello!</Link> </WithContext> ); expect(component1.toJSON()).toMatchSnapshot(); context.setState('state.some'); const component2 = testRenderer.create( <WithContext context={{ router: context }}> <Link state="state" disabled disabledClass="disabled" activeClass="active" activePathClass="active-path" activeStateClass="active-state">Hello!</Link> </WithContext> ); expect(component2.toJSON()).toMatchSnapshot(); }); it('should change location on click', () => { const routerContext = new RouterContext(); routerContext.setRoutes({ state: new Route('state', { url: '/' }) }); routerContext.setHistory(history({ pathname: '/' })); const onClick = jest.fn(); const link = mount(<div> <WithContext context={{ router: routerContext }}> <Link state="state" onClick={onClick}>Hello!</Link> </WithContext> </div>); link.find('a').simulate('click', { button: 0 }); expect(onClick).toBeCalled(); }); });
JavaScript
0
@@ -159,16 +159,27 @@ %7B mount +, configure %7D from @@ -184,24 +184,71 @@ m 'enzyme';%0A +import Adapter from 'enzyme-adapter-react-16';%0A import Link @@ -385,16 +385,57 @@ ry';%0A%0A%0A%0A +configure(%7B adapter: new Adapter() %7D);%0A%0A%0A describe
bedc3bb4831cdd214c850c3590ff952546006f6c
Add title to description
app/models/booking_model.js
app/models/booking_model.js
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var Objectid = mongoose.Schema.Types.ObjectId; var Room = require("./room_model"); var User = require("./user_model"); var Reserve = require("./reserve_model"); var moment = require('moment'); var BookingSchema = new Schema({ room: { type: Objectid, ref: "Room" }, start_time: Date, end_time: Date, title: String, description: String, message: String, attendees: [{ type: Objectid, ref: "User" }], external_attendees: [String], user: { type: Objectid, ref: "User" }, cost: Number, created: { type: Date, default: Date.now }, _owner_id: Objectid }); BookingSchema.set("_perms", { admin: "crud", owner: "crud", user: "cr", }); BookingSchema.pre("save", function(next) { console.log("Looking for existing reserve"); transaction = this; try { //Remove the reserve if it already exists Reserve.findOne({ source_type: "booking", source_id: transaction._id }, function(err, item) { if (item) { console.log("Found existing reserve, removing it"); item.remove(); } }); } catch(err) { console.log("Error", err); // throw(err); } //Is this free? If so, cool, don't do any more if (!transaction.cost) { return next(); } //Reserve the moneyz //We do this here, because if it fails we don't want to process the payment. try { Room.findById(transaction.room).populate('location').exec(function(err, room) { console.log(transaction); var description = "Booking: " + room.location.name + ": " + room.name + ", " + moment(transaction.start_time).format("dddd MMMM Do, H:m") + " to " + moment(transaction.end_time).format("H:m"); if (parseInt(transaction._owner_id) !== parseInt(transaction.user)) { description += " (Booked by Reception)"; } var reserve = Reserve({ user_id: transaction.user, description: description, amount: transaction.cost * -1, cred_type: "space", source_type: "booking", source_id: transaction._id }); console.log(reserve); reserve.save(function(err) { if (err) { console.error(err); return next(err); } return next(); }); }); } catch(err) { console.log("Error", err); //Roll back booking } }) BookingSchema.post("save", function(transaction) { }); BookingSchema.post("remove", function(transaction) { //Keep our running total up to date console.log("Remove called, Going to remove reserve"); console.log(transaction); try { Reserve.findOne({ source_type: "booking", source_id: transaction._id }, function(err, item) { if (err) { console.log("Error", err); return; } if (!item) { console.log("Could not find Reserve"); return; } item.remove(); }); } catch(err) { console.log("Error", err); // throw(err); } }); module.exports = mongoose.model('Booking', BookingSchema);
JavaScript
0.002184
@@ -1496,24 +1496,53 @@ Booking: %22 + + transaction.title + %22 :: %22 + room.locati @@ -1552,17 +1552,17 @@ name + %22 -: +, %22 + roo
40ebf7c76556af0dc6891a6672052b0ebf7d513f
Remove more traces
src/js/directives/chat.js
src/js/directives/chat.js
'use strict'; /** * @ngdoc function * @name Teem.controller:ChatCtrl * @description * # Chat Ctrl * Show Chat for a given project */ angular.module('Teem') .directive('chatScroll', [ '$timeout', function($timeout) { return function(scope, element) { if (scope.$last) { $timeout(function() { var bottom = angular.element(element); var newMessages = angular.element(document.getElementById('newMessages')); if (bottom) { var scrollableContentController = bottom.controller('scrollableContent'); if (scrollableContentController) { if (newMessages && newMessages.length > 0){ scrollableContentController.scrollTo(newMessages); } else { scrollableContentController.scrollTo(bottom); } } } }, 50); } }; }]) .directive('chat', function() { return { controller: [ 'SessionSvc', 'url', '$scope', '$rootScope', '$route', '$location', '$animate', 'time', function(SessionSvc, url, $scope, $rootScope, $route, $location, $animate, time){ const pageSize = 10; $scope.pageSize = pageSize; $scope.pageOffset = - pageSize; $scope.nextPage = function() { if ($scope.project.chat.length > $scope.pageSize) { $scope.pageSize += pageSize; $scope.pageOffset -= pageSize; } }; // Send button $scope.send = function(){ var msg = $scope.newMsg.trim(); if (msg === '') { return; } $scope.project.addChatMessage(msg); $scope.newMsg = ''; document.querySelector('.chat-textarea').focus(); }; $scope.standpoint = function(msg){ if (!SessionSvc.users.current()) { return msg.standpoint || 'their'; } return msg.standpoint || (SessionSvc.users.isCurrent(msg.who) ? 'mine' : 'their'); }; $scope.theirStandpoint = function(msg) { return $scope.standpoint(msg) === 'their'; }; // TODO: delete notification messages $scope.isNotificationMessage = function(msg){ return $scope.standpoint(msg) === 'notification'; }; $scope.hour = function(msg) { return time.hour(new Date(msg.time)); }; $scope.showPad = function() { $location.path('/teems/' + url.urlId($route.current.params.id) + '/pad'); }; $scope.addToPad = function(txt) { var p = $scope.project.pad; p.newLine(p.size() - 1); p.insert(p.size() - 1, txt); $scope.showPad(); }; // Returns the previous message to the one that has the index // in the current pagination function prevMessage(index) { var prevIndex = index - 1; if ($scope.project.chat.length > $scope.pageSize) { prevIndex += $scope.project.chat.length + $scope.pageOffset; } return $scope.project.chat[prevIndex]; } $scope.dayChange = function(msg, index){ var d = new Date(msg.time), prev = prevMessage(index); if (!prev || d.getDate() === new Date(prev.time).getDate()){ return undefined; } return time.date(d); }; $scope.firstNewMessage = function (msg, index){ // There is not access record if (! $scope.project.getTimestampAccess().chat) { return false; } var previousAccess = $scope.project.getTimestampAccess().chat.prev; // There is not previous access if (! previousAccess) { return false; } console.log(2); previousAccess = new Date(previousAccess); var prevMsg = prevMessage(index); // There are not more messages if (! prevMsg) { return false; } console.log(3); var date = new Date(msg.time); if (date > previousAccess && previousAccess > new Date(prevMsg.time)){ return true; } return false; }; $scope.keyDown = function(event){ if (event.which === 13) { // Input model is only updated on blur, so we have to sync manually $scope.chatForm.chatInput.$commitViewValue(); $scope.send(); event.preventDefault(); } }; } ], templateUrl: 'chat.html' }; });
JavaScript
0.000001
@@ -3970,24 +3970,8 @@ %7D%0A%0A -console.log(2);%0A @@ -4188,24 +4188,8 @@ %7D%0A%0A -console.log(3);%0A
c302dedaa00153f6417171c33481455266e72e75
Build Lesson class structure
client/desktop/app/components/teacher/classes/lessons/lessonData.js
client/desktop/app/components/teacher/classes/lessons/lessonData.js
JavaScript
0.000001
@@ -0,0 +1,257 @@ +import React from 'react'%0A%0Aclass LessonData extends React.Component %7B%0A // constructor(props)%7B%0A // super(props);%0A %0A // this.state = %7B%0A // //state here%0A // %7D;%0A // %7D%0A%0A render()%7B%0A return %3Cli%3ECS 101%3C/li%3E%0A %7D%0A%7D%0A%0Amodule.exports = LessonData;
5cef0cda5ac38034b82fde7030ec39b60acebe44
Expand example
examples/levels.js
examples/levels.js
'use strict' var Acho = require('..') var acho = Acho({ upperCase: true }) var levels = Object.keys(acho.types) var fixtureObj = { foo: 'bar', hello: 'world' } var fixtureArr = [1, 2, 3, 4, 5] acho.debug('%j', fixtureObj) acho.debug(fixtureObj) acho.debug(fixtureArr) levels.forEach(function (level) { setInterval(function () { acho[level]('This is a auto-generated ' + level + ' message') acho[level](fixtureObj) }, 1000) })
JavaScript
0.999999
@@ -67,16 +67,40 @@ se: true +,%0A // keyword: 'symbol' %0A%7D)%0A%0Avar
f1edda2564b4ee70bbd151ed79b26991d575e4e4
Set default contentStyle prop to make message more readable
src/ErrorReporting.js
src/ErrorReporting.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Snackbar from 'material-ui/Snackbar'; import { red900, grey50 } from 'material-ui/styles/colors'; class ErrorReporting extends Component { static defaultProps = { open: false, action: '', error: null, autoHideDuration: 10000, getMessage: (props) => props.error ? props.action + ': ' + props.error.toString() : '', style: { backgroundColor: red900, color: grey50 } } render() { return ( <Snackbar open={this.props.open} message={this.props.getMessage(this.props)} autoHideDuration={this.props.autoHideDuration} style={this.props.style} contentStyle={this.props.style} bodyStyle={this.props.style} /> ); } } function mapStoreToProps(state) { const { action, error } = state.errors; return { open: error !== null, action: action, error: error }; } export default connect(mapStoreToProps)(ErrorReporting);
JavaScript
0
@@ -531,16 +531,645 @@ %7D +,%0A contentStyle: %7B%0A display: 'block',%0A textOverflow: 'ellipsis',%0A whiteSpace: 'nowrap',%0A overflow: 'hidden'%0A %7D%0A %7D%0A%0A exclusiveProps = %5B%0A 'getMessage',%0A 'error',%0A 'action'%0A %5D%0A%0A getSnackbarProps() %7B%0A return Object%0A .keys(this.props)%0A .filter(%0A (name) =%3E this.exclusiveProps.indexOf(name) === -1%0A )%0A .reduce(%0A (acc, name) =%3E %7B%0A acc%5Bname%5D = this.props%5Bname%5D;%0A return acc;%0A %7D,%0A %7B%7D%0A ); %0A %7D%0A%0A @@ -1498,32 +1498,75 @@ is.props.style%7D%0A + %7B...this.getSnackbarProps()%7D%0A /%3E
1379e926be2344de12652f5ac6ecd9704c44a350
Add watch for maps folder
gruntfile.js
gruntfile.js
var properties = require('./src/js/game/properties.js'); module.exports = function (grunt) { grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-cache-bust'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-compress'); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-jade'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-stylus'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-open'); grunt.loadNpmTasks('grunt-pngmin'); var productionBuild = !!(grunt.cli.tasks.length && grunt.cli.tasks[0] === 'build'); grunt.initConfig( { pkg: grunt.file.readJSON('package.json') , properties: properties , project: { src: 'src/js' , js: '<%= project.src %>/game/{,*/}*.js' , dest: 'build/js' , bundle: 'build/js/app.min.js' , port: properties.port , banner: '/*\n' + ' * <%= properties.title %>\n' + ' * <%= pkg.description %>\n' + ' *\n' + ' * @author <%= pkg.author %>\n' + ' * @version <%= pkg.version %>\n' + ' * @copyright <%= pkg.author %>\n' + ' * @license <%= pkg.license %> licensed\n' + ' *\n' + ' * Made using Phaser JS Boilerplate <https://github.com/lukewilde/phaser-js-boilerplate>\n' + ' */\n' } , connect: { dev: { options: { port: '<%= project.port %>' , base: './build' } } } , jshint: { files: [ 'gruntfile.js' , '<%= project.js %>' ] , options: { jshintrc: '.jshintrc' } } , watch: { options: { livereload: productionBuild ? false : properties.liveReloadPort } , js: { files: '<%= project.dest %>/**/*.js' , tasks: ['jade'] } , jade: { files: 'src/templates/*.jade' , tasks: ['jade'] } , stylus: { files: 'src/style/*.styl' , tasks: ['stylus'] } , images: { files: 'src/images/**/*' , tasks: ['copy:images'] } , audio: { files: 'src/audio/**/*' , tasks: ['copy:audio'] } } , browserify: { app: { src: ['<%= project.src %>/game/app.js'] , dest: '<%= project.bundle %>' , options: { transform: ['browserify-shim'] , watch: true , bundleOptions: { debug: !productionBuild } } } } , open: { server: { path: 'http://localhost:<%= project.port %>' } } , cacheBust: { options: { encoding: 'utf8' , algorithm: 'md5' , length: 8 } , assets: { files: [ { src: [ 'build/index.html' , '<%= project.bundle %>' ] } ] } } , jade: { compile: { options: { data: { properties: properties , productionBuild: productionBuild } } , files: { 'build/index.html': ['src/templates/index.jade'] } } } , stylus: { compile: { files: { 'build/style/index.css': ['src/style/index.styl'] } , options: { sourcemaps: !productionBuild } } } , clean: ['./build/'] , pngmin: { options: { ext: '.png' , force: true } , compile: { files: [ { src: 'src/images/*.png' , dest: 'src/images/' } ] } } , copy: { images: { files: [ { expand: true, cwd: 'src/images/', src: ['**'], dest: 'build/images/' } ] } , audio: { files: [ { expand: true, cwd: 'src/audio/', src: ['**'], dest: 'build/audio/' } ] } , maps: { files: [ { expand: true, cwd: 'src/maps/', src: ['**'], dest: 'build/maps/' } ] } } , uglify: { options: { banner: '<%= project.banner %>' } , dist: { files: { '<%= project.bundle %>': '<%= project.bundle %>' } } } , compress: { options: { archive: '<%= pkg.name %>.zip' } , zip: { files: [ { expand: true, cwd: 'build/', src: ['**/*'], dest: '<%= pkg.name %>/' } ] } , cocoon: { files: [ { expand: true, cwd: 'build/', src: ['**/*'] } ] } } } ); grunt.registerTask('default', [ 'clean' , 'browserify' , 'jade' , 'stylus' , 'copy' , 'connect' , 'open' , 'watch' ] ); grunt.registerTask('build', [ /*'jshint' , */'clean' , 'browserify' , 'jade' , 'stylus' , 'uglify' , 'copy' , 'cacheBust' , 'connect' , 'open' , 'watch' ] ); grunt.registerTask('optimise', ['pngmin', 'copy:images']); grunt.registerTask('cocoon', ['compress:cocoon']); grunt.registerTask('zip', ['compress:zip']); };
JavaScript
0
@@ -2359,32 +2359,120 @@ dio'%5D%0A %7D%0A + , maps:%0A %7B files: 'src/maps/**/*'%0A , tasks: %5B'copy:maps'%5D%0A %7D%0A %7D%0A%0A , b
c86c03903c9f388c7997d576c08d92bed78df1b7
update libs
eln/libs.js
eln/libs.js
export {default as OCLE} from 'https://www.lactame.com/lib/openchemlib-extended/2.4.0/openchemlib-extended.js'; export {default as SD} from 'https://www.lactame.com/lib/spectra-data/3.1.6/spectra-data.min.js'; export {default as CCE} from 'https://www.lactame.com/lib/chemcalc-extended/1.27.5/chemcalc-extended.js'; export {default as elnPlugin} from 'https://www.lactame.com/lib/eln-plugin/0.2.0/eln-plugin.min.js';
JavaScript
0
@@ -184,9 +184,9 @@ 3.1. -6 +7 /spe @@ -389,17 +389,17 @@ gin/0.2. -0 +1 /eln-plu
fe93101f9e3b2c629cb773e8bda45c4a535b805a
Implement basic calculation of bpm, add visual elements
index.android.js
index.android.js
/** * Sample React Native App * https://github.com/facebook/react-native */ import React, { AppRegistry, Component, StyleSheet, Text, View } from 'react-native'; class TapTempo extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to Tap Tempo! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('TapTempo', () => TapTempo);
JavaScript
0.000002
@@ -4,14 +4,17 @@ %0A * -Sample +Tap Tempo Rea @@ -53,29 +53,24 @@ com/ -facebook/react-native +SumeetR/TapTempo %0A */ @@ -137,16 +137,36 @@ Text,%0A + TouchableOpacity,%0A View%0A%7D @@ -223,16 +223,983 @@ onent %7B%0A + constructor(props) %7B%0A super(props)%0A this.state = %7B%0A samples: %5B%5D%0A %7D;%0A %7D%0A%0A // Push sample into samples array%0A onPressButton = () =%3E %7B%0A const %7B samples %7D = this.state;%0A samples.push(new Date().getTime());%0A this.setState(%7Bsamples: samples%7D);%0A %7D%0A%0A%0A calculateTempo = (samples) =%3E %7B%0A // Only start processing when at least 5 samples are available%0A if (samples.length %3E= 5) %7B%0A // Take last 5 samples, subtract from first sample, and then return array of last 4 samples%0A const lastFourSamples = samples.slice(-5).map((sample, index, array) =%3E %7B%0A if (index %3E 0) %7B%0A return sample - array%5Bindex - 1%5D;%0A %7D%0A return 0;%0A %7D).slice(-4);%0A // Calculate total time%0A let total = 0;%0A for (const index in lastFourSamples) %7B%0A total = total + lastFourSamples%5Bindex%5D;%0A %7D%0A // Divide by milliseconds in a minute%0A return Math.round(60000 / (total / 4));%0A %7D%0A return 0;%0A %7D %0A%0A render @@ -1306,29 +1306,16 @@ -Welcome to Tap - Tempo -! %0A @@ -1319,32 +1319,71 @@ %3C/Text%3E%0A + %3CView style=%7Bstyles.center%7D%3E%0A %3CText st @@ -1423,54 +1423,47 @@ -To get started, edit index.android.js%0A + Tap the button to the beat!%0A %3C/Te @@ -1454,32 +1454,33 @@ t!%0A + %3C/Text%3E%0A %3CTex @@ -1459,32 +1459,34 @@ %3C/Text%3E%0A + %3CText st @@ -1501,72 +1501,194 @@ les. -instructions%7D%3E%0A Shake or press menu button for dev menu +tempo%7D%3E%0A %7Bthis.calculateTempo(this.state.samples)%7D%0A %3C/Text%3E%0A %3CTouchableOpacity style=%7Bstyles.tap%7D onPress=%7Bthis.onPressButton%7D%3E%0A %3C/TouchableOpacity%3E %0A @@ -1686,36 +1686,36 @@ city%3E%0A %3C/ -Text +View %3E%0A %3C/View%3E%0A @@ -1791,16 +1791,76 @@ lex: 1,%0A + backgroundColor: 'white',%0A %7D,%0A center: %7B%0A flex: 1,%0A just @@ -1903,24 +1903,38 @@ : 'center',%0A + %7D,%0A tap: %7B%0A backgrou @@ -1947,16 +1947,102 @@ r: ' -#F5FCFF' +red',%0A height: 100,%0A width: 100,%0A borderRadius: 100,%0A %7D,%0A tempo: %7B%0A fontSize: 24 ,%0A @@ -2072,17 +2072,41 @@ tSize: 2 -0 +4,%0A fontWeight: 'bold' ,%0A te
62c5ed8718204749a644f8a18a556275e55566e5
Use new Function() instead of eval
lib/whiskers.js
lib/whiskers.js
// whiskers.js templating library // the encapsulating function (function(whiskers) { // for compiled templates whiskers.cache = {}; // main function whiskers.render = function(template, context, partials) { template = whiskers.expand(template, partials); // use cached if it exists if (whiskers.cache[template]) return whiskers.cache[template](context); // compile and cache whiskers.cache[template] = eval(whiskers.compile(template)); return whiskers.cache[template](context); }; // expand all partials whiskers.expand = function(template, partials, indent) { // convert to string, empty if false template = (template || '')+''; // drop trailing newlines and prepend indent to each line indent = indent || ''; template = indent + template.replace(/\n+$/, '').replace(/\n/g, indent || '\n'); return template.replace(/(\n[ \t]+|)(\\*){>([\w.]+)}/g, function(str, indent, escapeChar, key) { // if tag is escaped return it untouched with first backslash removed if (escapeChar) return str.replace('\\', ''); // get partial, empty if not found try { template = eval('partials.'+key); } catch (e) { template = ''; } // recurse to expand any partials in this partial return whiskers.expand(template, partials, indent); }); }; // compile template to js string for eval whiskers.compile = function(template) { // convert to string, empty if false template = (template || '')+''; // escape backslashes and single quotes template = template.replace(/\\/g, '\\\\').replace(/\'/g, '\\\''); // replace simple key tags (like {foo}) template = template.replace(/(\\*){([\w.]+)}/g, function(str, escapeChar, key) { if (escapeChar) return str.replace('\\\\', ''); return '\'+g(\''+key+'\')+\''; }); // to check for correcting logic mistakes var levels = {'for':0, 'if': 0}; // replace logic tags (like {for foo in bar} and {if foo}) template = template.replace(/(\n[ \t]*|)(\\*){(\/?)(for|if|)( +|)(not +|)((\w+) +in +|)([\w.]+|)}(?:([ \t]*(?=\n))|)/g, function(str, newlineBefore, escapeChar, close, statement, statementSpace, ifNot, forIn, iterVar, key, newlineAfter, offset, s) { if (escapeChar) return str.replace('\\\\', ''); // remove preceding newline and whitespace for standalone logic tag if (newlineBefore && newlineAfter !== undefined) { newlineBefore = ''; } // opening tags if (statement && statementSpace && key) { levels[statement]++; // {for foo in bar} if (statement === 'for' && iterVar) { return newlineBefore+'\';var '+iterVar+'A=g(\''+key+'\');for(var '+iterVar+'I=0;'+iterVar+'I<'+iterVar+'A.length;'+iterVar+'I++){c[\''+iterVar+'\']='+iterVar+'A['+iterVar+'I];b+=\''; } // {if foo} or {if not foo} if (statement === 'if') { return newlineBefore+'\';if('+(ifNot?'!':'')+'g(\''+key+'\')){b+=\''; } } // closing tags ({/for} or {/if}) if (close && statement) { if (levels[statement] === 0) { console.warn('extra {/'+statement+'} ignored'); return ''; } else { levels[statement]--; return newlineBefore+'\';}b+=\''; } } // not a tag, don't replace return str; }); // close extra fors and ifs for (statement in levels) { for (var i=0; i<levels[statement]; i++) { console.warn('extra "'+statement+'" closed at end of template'); template = template+'\';}b+=\''; } } // escape newlines for eval template = template.replace(/\n/g, '\\n'); // wrap in function and return // c is context, b is buffer, g is get, k is key, v is value return '(function(){return function(c){var g=function(k){var v;try{v=eval(\'c.\'+k)||\'\'}catch(e){v=\'\'}if(typeof v==\'function\')v=v(c);return v;};var b=\''+template+'\';return b}})()'; }; })(typeof module == 'object' ? module.exports : this.whiskers = {});
JavaScript
0.000004
@@ -426,21 +426,16 @@ late%5D = -eval( whiskers @@ -452,17 +452,16 @@ emplate) -) ;%0A re @@ -658,25 +658,27 @@ plate %7C%7C '') -+ + + '';%0A // d @@ -1375,26 +1375,16 @@ to -js string for eval +function %0A w @@ -1494,17 +1494,19 @@ e %7C%7C '') -+ + + '';%0A%0A @@ -3641,18 +3641,9 @@ ines - for eval %0A + @@ -3690,43 +3690,8 @@ );%0A%0A - // wrap in function and return%0A @@ -3710,21 +3710,8 @@ ext, - b is buffer, g i @@ -3741,49 +3741,46 @@ alue -%0A return '(function()%7Breturn f +, b is buffer%0A return new F unction( c)%7Bv @@ -3779,11 +3779,14 @@ ion( -c)%7B +'c', ' var @@ -3927,14 +3927,10 @@ rn b -%7D%7D)() ' +) ;%0A
01d646eec28f87920ea3c148fd138faf0cae754e
Remove deprecated analytics event tests
anvil/driver/configSet/Resources/suites/analytics.js
anvil/driver/configSet/Resources/suites/analytics.js
/* * Appcelerator Titanium Mobile * Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ module.exports = new function() { var finish; var valueOf; this.init = function(testUtils) { finish = testUtils.finish; valueOf = testUtils.valueOf; } this.name = "analytics"; this.tests = [ {name: "addEvent"}, {name: "featureEvent"}, {name: "navEvent"}, {name: "settingsEvent"}, {name: "timedEvent"}, {name: "userEvent"} ] //iOS: TIMOB-5014 //Android: TIMOB-5020 this.addEvent = function(testRun) { valueOf(testRun, function() { Ti.Analytics.addEvent(); }).shouldThrowException(); valueOf(testRun, function() { Ti.Analytics.addEvent('type'); }).shouldThrowException(); valueOf(testRun, Ti.Analytics.addEvent('adding', 'featureEvent.testButton')).shouldBeUndefined(); valueOf(testRun, Ti.Analytics.addEvent('adding', 'featureEvent.testButton', {'events':'adding'})).shouldBeUndefined(); finish(testRun); } this.featureEvent = function(testRun) { valueOf(testRun, function() { Ti.Analytics.featureEvent(); }).shouldThrowException(); valueOf(testRun, Ti.Analytics.featureEvent('featureEvent.testButton')).shouldBeUndefined(); valueOf(testRun, Ti.Analytics.featureEvent('featureEvent.testButton', {'events':'feature'})).shouldBeUndefined(); finish(testRun); } this.navEvent = function(testRun) { valueOf(testRun, function() { Ti.Analytics.navEvent(); }).shouldThrowException(); valueOf(testRun, function() { Ti.Analytics.navEvent('here'); }).shouldThrowException(); valueOf(testRun, Ti.Analytics.navEvent('here', 'there')).shouldBeUndefined(); valueOf(testRun, Ti.Analytics.navEvent('here', 'there', 'navEvent.testButton')).shouldBeUndefined(); valueOf(testRun, Ti.Analytics.navEvent('here', 'there', 'navEvent.testButton', {'events':'nav'})).shouldBeUndefined(); finish(testRun); } //iOS: TIMOB-4697 this.settingsEvent = function(testRun) { valueOf(testRun, function() { Ti.Analytics.settingsEvent(); }).shouldThrowException(); valueOf(testRun, Ti.Analytics.settingsEvent('settingsEvent.testButton')).shouldBeUndefined(); valueOf(testRun, Ti.Analytics.settingsEvent('settingsEvent.testButton', {'events':'settings'})).shouldBeUndefined(); finish(testRun); } //Android: TIMOB-4642 this.timedEvent = function(testRun) { var startDate = new Date(); var stopDate = new Date(); var duration = stopDate - startDate; valueOf(testRun, function() { Ti.Analytics.timedEvent(); }).shouldThrowException(); valueOf(testRun, function() { Ti.Analytics.timedEvent('timedEvent.testButton'); }).shouldThrowException(); valueOf(testRun, function() { Ti.Analytics.timedEvent('timedEvent.testButton', startDate); }).shouldThrowException(); valueOf(testRun, function() { Ti.Analytics.timedEvent('timedEvent.testButton', startDate, stopDate); }).shouldThrowException(); valueOf(testRun, Ti.Analytics.timedEvent('timedEvent.testButton', startDate, stopDate, duration)).shouldBeUndefined(); valueOf(testRun, Ti.Analytics.timedEvent('timedEvent.testButton', startDate, stopDate, duration, {'events':'timed'})).shouldBeUndefined(); finish(testRun); } this.userEvent = function(testRun) { valueOf(testRun, function() { Ti.Analytics.userEvent(); }).shouldThrowException(); valueOf(testRun, Ti.Analytics.userEvent('userEvent.testButton')).shouldBeUndefined(); valueOf(testRun, Ti.Analytics.userEvent('userEvent.testButton', {'events':'user'})).shouldBeUndefined(); finish(testRun); } }
JavaScript
0
@@ -438,30 +438,8 @@ = %5B%0A -%09%09%7Bname: %22addEvent%22%7D,%0A %09%09%7Bn @@ -487,590 +487,9 @@ %7D,%0A%09 -%09%7Bname: %22settingsEvent%22%7D,%0A%09%09%7Bname: %22timedEvent%22%7D,%0A%09%09%7Bname: %22userEvent%22%7D%0A%09%5D%0A%0A%09//iOS: TIMOB-5014%0A%09//Android: TIMOB-5020%0A%09this.addEvent = function(testRun) %7B%0A%09%09valueOf(testRun, function() %7B%0A%09%09%09Ti.Analytics.addEvent();%0A%09%09%7D).shouldThrowException();%0A%09%09valueOf(testRun, function() %7B%0A%09%09%09Ti.Analytics.addEvent('type');%0A%09%09%7D).shouldThrowException();%0A%09%09valueOf(testRun, Ti.Analytics.addEvent('adding', 'featureEvent.testButton')).shouldBeUndefined();%0A%09%09valueOf(testRun, Ti.Analytics.addEvent('adding', 'featureEvent.testButton', %7B'events':'adding'%7D)).shouldBeUndefined();%0A%0A%09%09finish(testRun);%0A%09%7D +%5D %0A%0A%09t @@ -1407,1657 +1407,6 @@ %09%7D%0A%0A -%09//iOS: TIMOB-4697%0A%09this.settingsEvent = function(testRun) %7B%0A%09%09valueOf(testRun, function() %7B%0A%09%09%09Ti.Analytics.settingsEvent();%0A%09%09%7D).shouldThrowException();%0A%09%09valueOf(testRun, Ti.Analytics.settingsEvent('settingsEvent.testButton')).shouldBeUndefined();%0A%09%09valueOf(testRun, Ti.Analytics.settingsEvent('settingsEvent.testButton', %7B'events':'settings'%7D)).shouldBeUndefined();%0A%0A%09%09finish(testRun);%0A%09%7D%0A%0A%09//Android: TIMOB-4642%0A%09this.timedEvent = function(testRun) %7B%0A%09%09var startDate = new Date();%0A%09%09var stopDate = new Date();%0A%09%09var duration = stopDate - startDate;%0A%09%09valueOf(testRun, function() %7B%0A%09%09%09Ti.Analytics.timedEvent();%0A%09%09%7D).shouldThrowException();%0A%09%09valueOf(testRun, function() %7B%0A%09%09%09Ti.Analytics.timedEvent('timedEvent.testButton');%0A%09%09%7D).shouldThrowException();%0A%09%09valueOf(testRun, function() %7B%0A%09%09%09Ti.Analytics.timedEvent('timedEvent.testButton', startDate);%0A%09%09%7D).shouldThrowException();%0A%09%09valueOf(testRun, function() %7B%0A%09%09%09Ti.Analytics.timedEvent('timedEvent.testButton', startDate, stopDate);%0A%09%09%7D).shouldThrowException();%0A%09%09valueOf(testRun, Ti.Analytics.timedEvent('timedEvent.testButton', startDate, stopDate, duration)).shouldBeUndefined();%0A%09%09valueOf(testRun, Ti.Analytics.timedEvent('timedEvent.testButton', startDate, stopDate, duration, %7B'events':'timed'%7D)).shouldBeUndefined();%0A%0A%09%09finish(testRun);%0A%09%7D%0A%0A%09this.userEvent = function(testRun) %7B%0A%09%09valueOf(testRun, function() %7B%0A%09%09%09Ti.Analytics.userEvent();%0A%09%09%7D).shouldThrowException();%0A%09%09valueOf(testRun, Ti.Analytics.userEvent('userEvent.testButton')).shouldBeUndefined();%0A%09%09valueOf(testRun, Ti.Analytics.userEvent('userEvent.testButton', %7B'events':'user'%7D)).shouldBeUndefined();%0A%0A%09%09finish(testRun);%0A%09%7D%0A %7D%0A
6169031cc9206f00b3a3c573e762aab43b02d125
Save the student when it changes
app/models/studentModel.es6
app/models/studentModel.es6
'use strict'; import * as _ from 'lodash' import uuid from '../helpers/uuid' import randomChar from '../helpers/randomChar' import emitter from '../helpers/emitter' import db from '../helpers/db' import ScheduleSet from './scheduleSet' import StudySet from './studySet' import * as demoStudent from '../../mockups/demo_student.json' let Student = (encodedStudent) => { encodedStudent = encodedStudent || {} let student = { id: uuid(), name: 'Student ' + randomChar(), active: false, credits: { needed: 35, has: 0 }, matriculation: 1894, graduation: 1898, studies: {}, schedules: {}, overrides: [], fabrications: [], } student.id = encodedStudent.id || student.id student.name = encodedStudent.name || student.name if (encodedStudent.credits) student.credits.needed = encodedStudent.credits.needed || student.credits.needed student.matriculation = encodedStudent.matriculation || student.matriculation student.graduation = encodedStudent.graduation || student.graduation student.studies = new StudySet(encodedStudent.studies || student.studies) student.schedules = new ScheduleSet(encodedStudent.schedules || student.schedules) student.overrides = encodedStudent.overrides || student.overrides student.fabrications = encodedStudent.fabrications || student.fabrications Object.defineProperty(student, 'courses', { get() { return student.schedules.activeCourses }}) Object.defineProperty(student, 'encode', { value() { return JSON.stringify(student) }}) Object.defineProperty(student, 'save', { value() { console.log('saving student', student.name) localStorage.setItem(student.id, JSON.stringify(student)) // return db.store('students').put(student) }}) emitter.on('saveStudent', student.save) // todo: remove me when we have something more than tape. // for one thing, i'm pretty sure that all these emitters are causing some // level of a memory leak. emitter.on('change', student.save) return student } function loadStudentFromDb(forceDemo) { forceDemo = forceDemo || false let rawStudent; if (!forceDemo) { rawStudent = localStorage.getItem('3AE9E7EE-DA8F-4014-B987-8D88814BB848') // again, ick. reassignment. rawStudent = JSON.parse(rawStudent) } if (!rawStudent) rawStudent = demoStudent let student = new Student(rawStudent) window.student = student emitter.emit('loadedStudent', student) return student } emitter.on('revertStudentToDemo', () => loadStudentFromDb(true)) emitter.on('loadStudent', loadStudentFromDb) window.loadStudentFromDb = loadStudentFromDb export default Student export {loadStudentFromDb, Student}
JavaScript
0
@@ -1311,16 +1311,79 @@ ations%0A%0A +%09Object.observe(student, (changes) =%3E emitter.emit('change'))%0A%0A %09Object.
9ce78a430c87f3173e892b0d97eb68aa218bd8b4
resolve import/newline-after-import error
examples/simple.js
examples/simple.js
'use strict'; const express = require('express'); const app = module.exports = express(); const xapp = require('../'); // enabled X-App headers app.use(xapp({}, require('./package'))); // normal route app.get('/', (req, res) => { res.send('Hello World'); }); /* istanbul ignore next */ if (!module.parent) { app.listen(3000); console.log('Express started on port 3000'); // eslint-disable-line no-console }
JavaScript
0.000001
@@ -44,16 +44,46 @@ ress');%0A +const xapp = require('../');%0A%0A const ap @@ -119,38 +119,8 @@ );%0A%0A -const xapp = require('../');%0A%0A // e
b28656a8c4e5e6e60dce4e988c01e32f9834b2f2
fix for google mail again
server/core/mail/ImapConnector.js
server/core/mail/ImapConnector.js
import IPromise from 'imap-promise'; import Promise from 'bluebird'; class ImapConnector { constructor(options) { this.options = options; this.options['debug'] = function(err) { console.log(err) }; this.options['authTimeout'] = 10000; this.imap = new IPromise(options); this.imap.on('error', (err) => { console.log(err); }) } connect() { return this.imap.connectAsync(); } openBoxAsync(box) { return this.connect().then(() => this.imap.openBoxAsync(box, false)); } statusBoxAsync(box, readOnly = false) { return new Promise((resolve, reject) => { this.imap.status(box, (err, mailbox) => { if (err) { reject(err); } else { resolve(mailbox); } }); }); } getBoxes(details = false) { return this.connect().then(() => new Promise((resolve, reject) => { this.imap.getBoxes((err, boxes) => { if (err) { reject(err); } else { let boxList = []; this._generateBoxList(boxes, null, boxList, null); if (details) { let promises = []; let boxListDetails = []; boxList.forEach((box, index) => { promises.push(new Promise((resolve, reject) => { this.statusBoxAsync(box.name, false).then((res) => { boxListDetails.push({ id: index, name: res.name, shortName: res.name.substr(res.name.lastIndexOf('/') + 1, res.name.length), total: res.messages.total, new: res.messages.new, unseen: res.messages.unseen, parent: box.parent }); resolve(res); }) })); }); Promise.all(promises).then((results) => { this._populateFamilyTree(boxListDetails); resolve(boxListDetails); }); } else { resolve(boxList); } } }); })); } addBox(boxName) { return this.connect().then(() => new Promise((resolve, reject) => { this.imap.addBox(boxName, (err) => { err ? reject(err) : resolve(boxName); }) })) } delBox(boxName) { return this.connect().then(() => new Promise((resolve, reject) => { this.imap.delBox(boxName, (err) => { err ? reject(err) : resolve(boxName); }) })) } renameBox(oldBoxName, newBoxName) { return this.connect().then(() => new Promise((resolve, reject) => { this.imap.renameBox(oldBoxName, newBoxName, (err) => { err ? reject(err) : resolve(newBoxName); }) })) } append(box, args, to, from, subject, msgData) { const options = { mailbox: box, ...args }; const msg = this.createRfcMessage(from, to, subject, msgData); return this.connect().then(() => new Promise((resolve, reject) => { this.imap.append(msg, options, (err) => { err ? reject(err) : resolve(msgData); }) })); } move(msgId, srcBox, box) { return this.openBoxAsync(srcBox).then((srcBox) => new Promise((resolve, reject) => { this.imap.move(msgId, box, (err) => { err ? reject(err) : resolve(msgId); }) })); } copy(msgId, srcBox, box) { return this.openBoxAsync(srcBox).then((srcBox) => new Promise((resolve, reject) => { this.imap.copy(msgId, box, (err) => { err ? reject(err) : resolve(msgId); }) })); } addFlags(msgId, flags, box) { return this.openBoxAsync(box).then((box) => new Promise((resolve, reject) => { this.imap.addFlags(msgId, flags, (err) => { err ? reject(err) : resolve(msgId); }) })); } delFlags(msgId, flags, box) { return this.openBoxAsync(box).then((box) => new Promise((resolve, reject) => { this.imap.delFlags(msgId, flags, (err) => { err ? reject(err) : resolve(msgId); }) })); } setFlags(msgId, flags, box) { return this.openBoxAsync(box).then((box) => new Promise((resolve, reject) => { this.imap.setFlags(msgId, flags, (err) => { err ? reject(err) : resolve(msgId); }) })); } fetchAttachment(mail) { return this.imap.collectEmailAsync(mail) .then((msg) => { msg.attachments = this.imap.findAttachments(msg); msg.downloads = Promise.all(msg.attachments.map((attachment) => { const emailId = msg.attributes.uid; const saveAsFilename = attachment.params.name; return this.imap.downloadAttachmentAsync(emailId, attachment, saveAsFilename); })); return Promise.props(msg); }); } createRfcMessage(from, to, subject, msgData) { return `From: ${from} To: ${to} Subject: ${subject} ${msgData}`; } _generateBoxList(boxes, parentPath, arr, parent) { Object.keys(boxes).forEach((key, i) => { const path = parentPath ? `${parentPath}/${key}` : key; let box = null; if (key != '[Gmail]' || key != '[Google Mail]') { box = { name: path, shortName: path.substr(path.lastIndexOf('/') + 1, path.length), parent: parent }; arr.push(box); } if (boxes[key].children) { this._generateBoxList(boxes[key].children, path, arr, box); } }) } _populateFamilyTree(boxes) { boxes.forEach((box, index) => { if (box.parent != null) { let parent = boxes.filter((b) => b.name == box.parent.name)[0]; box.parent = parent; } }); } } export default ImapConnector;
JavaScript
0
@@ -5084,10 +5084,10 @@ l%5D' -%7C%7C +&& key
c498ac23dce80163740246de521bf139418d3915
Remove ‘resrc’ reference in comment.
gruntfile.js
gruntfile.js
module.exports = function(grunt) { // Initialize config grunt.initConfig({ // Load package.json pkg: require('./package.json'), // Project paths project: { assets: 'assets', design_assets: 'design/assets', styles: '<%= project.assets %>/stylesheets', styles_scss: '<%= project.styles %>/scss', styles_dev: '<%= project.styles %>/dev', styles_min: '<%= project.styles %>/min', styles_critical: '<%= project.styles %>/critical', scripts: '<%= project.assets %>/javascript', scripts_dev: '<%= project.scripts %>/dev', scripts_min: '<%= project.scripts %>/min', scripts_classes: '<%= project.scripts %>/classes', scripts_plugins: '<%= project.scripts %>/plugins', scripts_polyfills: '<%= project.scripts %>/polyfills', scripts_utils: '<%= project.scripts %>/utils', scripts_vendor: '<%= project.scripts %>/vendor', }, // Project banner tag: { banner_basic: '/**\n' + ' * <%= pkg.description %> — v<%= pkg.version %> — <%= grunt.template.today("yyyy-mm-dd") %>\n' + ' * <%= pkg.url %>\n' + ' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.copyright %>\n' + ' */\n', banner_extended: '/**\n' + ' * <%= pkg.description %>\n' + ' *\n' + ' * @authors <%= pkg.author %>\n' + ' * @link <%= pkg.url %>\n' + ' * @version <%= pkg.version %>\n' + ' * @generated <%= grunt.template.today("yyyy-mm-dd:hh:mm") %>\n' + ' * @copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.copyright %>\n' + ' * @license <%= pkg.license %>\n' + ' */\n' }, // JS files and order jsfiles: { head: [ '<%= project.scripts_vendor %>/enhance.js', '<%= project.scripts_vendor %>/modernizr.dev.js', // '<%= project.scripts_vendor %>/modernizr.min.js', // ALWAYS use custom build modernizr in production! '<%= project.scripts %>/head.scripts.js', ], main: { polyfills: [ '<%= project.scripts_polyfills %>/classlist.js', '<%= project.scripts_polyfills %>/domready.js', ], plugins: [ // '<%= project.scripts_plugins %>/domdelegate.js', '<%= project.scripts_vendor %>/fontfaceobserver.js', '<%= project.scripts_vendor %>/lazysizes.min.js', // Out-comment when using lazyload!!! // '<%= project.scripts_plugins %>/ls.respimg.js', // Out-comment when using polyfilling responsive images!!! '<%= project.scripts_plugins %>/ls.rias.js', // Out-comment when using lazyload + resrc!!! '<%= project.scripts_plugins %>/ls.bgset.js', // Out-comment when using lazyload (+ resrc) + multiple background images with a width descriptor!!! // '<%= project.scripts_plugins %>/ls.unload.js', // Out-comment when using lazyload and want to unload not in view images to improve memory consumption and orientationchange/resize performance!!! // '<%= project.scripts_plugins %>/ls.unveilhooks.js', // Out-comment when using lazyload + unveil/lazyload scripts/widgets, background images, styles and video/audio elements!!! '<%= project.scripts_plugins %>/ls.print.js', // Out-comment when there's a need to be able to print lazyloaded images!!! '<%= project.scripts_plugins %>/transitionend.js', '<%= project.scripts_plugins %>/smooth-scroll.js', '<%= project.scripts_plugins %>/gumshoe.js', // '<%= project.scripts_plugins %>/photoswipe/photoswipe.js', // Photoswipe // '<%= project.scripts_plugins %>/photoswipe/ui/photoswipe-ui-default.js', // Photoswipe ui ], utils: [ '<%= project.scripts_utils %>/extend.util.js', '<%= project.scripts_utils %>/alerts.util.js', // '<%= project.scripts_utils %>/ajax.util.js', '<%= project.scripts_utils %>/cookie.util.js', '<%= project.scripts_utils %>/domparents.util.js', ], other: [ // Classes '<%= project.scripts_classes %>/expand.class.js', '<%= project.scripts_classes %>/lazysizes.class.js', '<%= project.scripts_classes %>/fontobserver.class.js', '<%= project.scripts_classes %>/navmain.class.js', // '<%= project.scripts_classes %>/photoswipe.class.js', '<%= project.scripts_classes %>/popup.class.js', // Main '<%= project.scripts %>/main.scripts.js', ], }, mobile: { polyfills: [ '<%= project.scripts_polyfills %>/classlist.js', '<%= project.scripts_polyfills %>/domready.js', ], plugins: [ // '<%= project.scripts_plugins %>/domdelegate.js', '<%= project.scripts_vendor %>/fontfaceobserver.js', '<%= project.scripts_vendor %>/lazysizes.min.js', // Out-comment when using lazyload!!! // '<%= project.scripts_plugins %>/ls.respimg.js', // Out-comment when using polyfilling responsive images!!! '<%= project.scripts_plugins %>/ls.rias.js', // Out-comment when using lazyload + resrc!!! '<%= project.scripts_plugins %>/ls.bgset.js', // Out-comment when using lazyload (+ resrc) + multiple background images with a width descriptor!!! // '<%= project.scripts_plugins %>/ls.unload.js', // Out-comment when using lazyload and want to unload not in view images to improve memory consumption and orientationchange/resize performance!!! // '<%= project.scripts_plugins %>/ls.unveilhooks.js', // Out-comment when using lazyload + unveil/lazyload scripts/widgets, background images, styles and video/audio elements!!! '<%= project.scripts_plugins %>/ls.print.js', // Out-comment when there's a need to be able to print lazyloaded images!!! '<%= project.scripts_plugins %>/transitionend.js', '<%= project.scripts_plugins %>/smooth-scroll.js', // '<%= project.scripts_plugins %>/photoswipe/photoswipe.js', // Photoswipe // '<%= project.scripts_plugins %>/photoswipe/ui/photoswipe-ui-default.js', // Photoswipe ui ], utils: [ '<%= project.scripts_utils %>/extend.util.js', '<%= project.scripts_utils %>/alerts.util.js', // '<%= project.scripts_utils %>/ajax.util.js', '<%= project.scripts_utils %>/cookie.util.js', '<%= project.scripts_utils %>/domparents.util.js', ], other: [ // Classes '<%= project.scripts_classes %>/expand.class.js', '<%= project.scripts_classes %>/fontobserver.class.js', '<%= project.scripts_classes %>/lazysizes.class.js', '<%= project.scripts_classes %>/navmain.class.js', // '<%= project.scripts_classes %>/photoswipe.class.js', // Main '<%= project.scripts %>/mobile.scripts.js', ], }, }, }); // Load per-task config from separate files grunt.loadTasks('grunt/config'); // Register alias tasks from separate files grunt.loadTasks('grunt/tasks'); // Register default task grunt.registerTask('default', ['develop']); };
JavaScript
0
@@ -2618,34 +2618,24 @@ ing lazyload - (+ resrc) + multiple @@ -5026,18 +5026,10 @@ load - (+ resrc) +ed + m
c78ca00ab1a3f243167e242faf287e1dbc2ff504
fix billing account form missing dependency
corehq/apps/accounting/static/accounting/js/billing_account_form.js
corehq/apps/accounting/static/accounting/js/billing_account_form.js
hqDefine('accounting/js/billing_account_form', [ 'jquery', 'knockout', 'hqwebapp/js/initial_page_data', 'accounting/js/credits_tab', 'hqwebapp/js/stay_on_tab', ], function ( $, ko, initialPageData ) { var billingAccountFormModel = function (is_active) { 'use strict'; var self = {}; self.is_active = ko.observable(is_active); self.showActiveAccounts = ko.computed(function () { return !self.is_active(); }); return self; }; $(function () { var baForm = billingAccountFormModel(initialPageData.get('account_form_is_active')); $('#account-form').koApplyBindings(baForm); $("#show_emails").click(function() { $('#emails-text').show(); $(this).parent().hide(); }); }); });
JavaScript
0.000002
@@ -173,16 +173,45 @@ n_tab',%0A + 'accounting/js/widgets',%0A %5D, funct
31d5374f4093eaba98c276b94b1e078457c7c125
Introduce WAITING and DELAYED status in Service struct
src/js/structs/Service.js
src/js/structs/Service.js
import HealthStatus from '../constants/HealthStatus'; import Item from './Item'; import ServiceImages from '../constants/ServiceImages'; import ServiceStatus from '../constants/ServiceStatus'; import TaskStats from './TaskStats'; module.exports = class Service extends Item { getArguments() { return this.get('args'); } getCommand() { return this.get('cmd'); } getContainerSettings() { return this.get('container'); } getCpus() { return this.get('cpus'); } getContainer() { return this.get('container'); } getConstraints() { return this.get('constraints'); } getDeployments() { return this.get('deployments'); } getDisk() { return this.get('disk'); } getExecutor() { return this.get('executor'); } getAcceptedResourceRoles() { return this.get('acceptedResourceRoles'); } getHealth() { let {tasksHealthy, tasksUnhealthy, tasksRunning} = this.getTasksSummary(); if (tasksUnhealthy > 0) { return HealthStatus.UNHEALTHY; } if (tasksRunning > 0 && tasksHealthy === tasksRunning) { return HealthStatus.HEALTHY; } if (this.getHealthChecks() && tasksRunning === 0) { return HealthStatus.IDLE; } return HealthStatus.NA; } getHealthChecks() { return this.get('healthChecks'); } getId() { return this.get('id') || ''; } getImages() { return this.get('images') || ServiceImages.NA_IMAGES; } getInstancesCount() { return this.get('instances'); } getLabels() { return this.get('labels'); } getLastConfigChange() { return this.getVersionInfo().lastConfigChangeAt; } getLastScaled() { return this.getVersionInfo().lastScalingAt; } getLastTaskFailure() { return this.get('lastTaskFailure'); } getMem() { return this.get('mem'); } getName() { return this.getId().split('/').pop(); } getPorts() { return this.get('ports'); } getResources() { return { cpus: this.get('cpus'), mem: this.get('mem'), disk: this.get('disk') }; } getStatus() { const status = this.getServiceStatus(); if (status.displayName == null) { return null; } return status.displayName; } getServiceStatus() { let {tasksRunning} = this.getTasksSummary(); let deployments = this.getDeployments(); if (deployments.length > 0) { return ServiceStatus.DEPLOYING; } if (tasksRunning > 0) { return ServiceStatus.RUNNING; } let instances = this.getInstancesCount(); if (instances === 0) { return ServiceStatus.SUSPENDED; } return ServiceStatus.NA; } getTasksSummary() { return { tasksHealthy: this.get('tasksHealthy'), tasksRunning: this.get('tasksRunning'), tasksStaged: this.get('tasksStaged'), tasksUnhealthy: this.get('tasksUnhealthy'), tasksUnknown: this.get('tasksRunning') - this.get('tasksHealthy') - this.get('tasksUnhealthy'), }; } getTaskStats() { return new TaskStats(this.get('taskStats')); } getFetch() { return this.get('fetch'); } getUser() { return this.get('user'); } getVersions() { return this.get('versions') || new Map(); } getVersionInfo() { let currentVersionID = this.get('version'); let {lastConfigChangeAt, lastScalingAt} = this.get('versionInfo'); return {lastConfigChangeAt, lastScalingAt, currentVersionID}; } };
JavaScript
0
@@ -2355,16 +2355,262 @@ ments(); +%0A let queue = this.getQueue();%0A%0A if (queue != null && queue.delay && queue.delay.overdue) %7B%0A return ServiceStatus.WAITING;%0A %7D%0A%0A if (queue != null && queue.delay && !queue.delay.overdue) %7B%0A return ServiceStatus.DELAYED;%0A %7D %0A%0A if @@ -3367,24 +3367,74 @@ tch');%0A %7D%0A%0A + getQueue() %7B%0A return this.get('queue');%0A %7D%0A%0A getUser()
3b1eec3dfec3a881be0b63d18feb045e3cd28660
remove partial pre-compiling (buggy)
lib/assemble-handlebars.js
lib/assemble-handlebars.js
var handlebars = require('handlebars'); var helpers = require('handlebars-helpers'); var _ = require('lodash'); var plugin = function() { 'use strict'; var init = function(options) { // register built-in helpers helpers.register(handlebars, options); }; var compile = function(src, options, callback) { var tmpl; try { tmpl = handlebars.compile(src, options); } catch(ex) { callback(ex, null); } callback(null, tmpl); }; var render = function(tmpl, options, callback) { var content; try { if(typeof tmpl === 'string') { tmpl = handlebars.compile(tmpl, options); } content = tmpl(options); } catch (ex) { callback(ex, null); } callback(null, content); }; var registerFunctions = function(helperFunctions) { if(helperFunctions) { _.forOwn(helperFunctions, function(fn, key) { handlebars.registerHelper(key, fn); }); } }; var registerPartial = function(filename, content) { var tmpl; try { if(typeof content === 'string') { tmpl = handlebars.compile(content); } else { tmpl = content; } handlebars.registerPartial(filename, tmpl); } catch (ex) {} }; return { init: init, compile: compile, render: render, registerFunctions: registerFunctions, registerPartial: registerPartial, handlebars: handlebars }; }; module.exports = exports = plugin();
JavaScript
0.000002
@@ -1038,139 +1038,8 @@ y %7B%0A - if(typeof content === 'string') %7B%0A tmpl = handlebars.compile(content);%0A %7D else %7B%0A tmpl = content;%0A %7D%0A @@ -1077,20 +1077,23 @@ lename, -tmpl +content );%0A %7D
bef9f3873d4b8f1052b8f3cc690ab6c8d5c5ba1b
Add tests to ensure that attributes are set when calling incremental dom directly for fu
test/unit/vdom/incremental-dom.js
test/unit/vdom/incremental-dom.js
import * as IncrementalDOM from 'incremental-dom'; import { vdom } from '../../../src/index'; function testBasicApi (name) { describe(name, () => { it('should be a function', () => expect(vdom[name]).to.be.a('function')); it('should not be the same one as in Incremental DOM', () => expect(vdom[name]).not.to.equal(IncrementalDOM[name])); }); } describe('IncrementalDOM', function () { testBasicApi('attr'); testBasicApi('elementClose'); testBasicApi('elementOpen'); testBasicApi('elementOpenEnd'); testBasicApi('elementOpenStart'); testBasicApi('elementVoid'); testBasicApi('text'); describe('passing a function helper', () => { let fixture; beforeEach(() => fixture = document.createElement('div')); function patchAssert(elem) { expect(fixture.firstChild).to.equal(elem); expect(fixture.innerHTML).to.equal('<div id="test"></div>'); } function patchIt(desc, func) { it(desc, () => IncrementalDOM.patch(fixture, func)); } const Elem = () => { const elem = vdom.elementOpen('div', null, null, 'id', 'test'); vdom.elementClose('div'); return elem; }; patchIt('elementOpen, elementClose', () => { vdom.elementOpen(Elem); patchAssert(vdom.elementClose(Elem)); }); patchIt('elementOpenStart, elementOpenEnd, elementClose', () => { vdom.elementOpenStart(Elem); vdom.elementOpenEnd(Elem); patchAssert(vdom.elementClose(Elem)); }); patchIt('elementVoid', () => { patchAssert(vdom.elementVoid(Elem)); }); }); });
JavaScript
0
@@ -616,16 +616,21 @@ describe +.only ('passin @@ -769,16 +769,42 @@ ert(elem +, %7B checkChildren = true %7D ) %7B%0A @@ -889,17 +889,17 @@ o.equal( -' +%60 %3Cdiv id= @@ -909,15 +909,59 @@ st%22%3E +$%7B checkChildren ? '%3Cspan%3Etest%3C/span%3E' : ' %3C/div%3E' +%7D%60 );%0A @@ -1063,24 +1063,153 @@ c));%0A %7D%0A%0A + function renderChildren() %7B%0A vdom.elementOpen('span');%0A vdom.text('test');%0A vdom.elementClose('span');%0A %7D%0A%0A const El @@ -1214,16 +1214,28 @@ Elem = ( +props, chren ) =%3E %7B%0A @@ -1290,22 +1290,95 @@ null -, 'id', 'test' +);%0A Object.keys(props).forEach(prop =%3E vdom.attr(prop, props%5Bprop%5D));%0A chren( );%0A @@ -1507,24 +1507,74 @@ entOpen(Elem +, null, null, 'id', 'test');%0A renderChildren( );%0A pat @@ -1647,16 +1647,22 @@ enStart, + attr, element @@ -1721,24 +1721,67 @@ enStart(Elem +, null, null);%0A vdom.attr('id', 'test' );%0A vdo @@ -1800,24 +1800,48 @@ nEnd(Elem);%0A + renderChildren();%0A patchA @@ -1955,25 +1955,77 @@ entVoid(Elem -) +, null, null, 'id', 'test'), %7B checkChildren: false %7D );%0A %7D);%0A
aa999e4642279515e609b5da63c7be92e85a6fd6
Fix https can’t request
src/L.Routing.Conf.js
src/L.Routing.Conf.js
'use strict'; (function (factory, window) { if (typeof define === "function" && define.amd) { define(["leaflet"], factory); } else if (typeof exports === "object") { module.exports = factory(require("leaflet")); } if (typeof window !== "undefined" && window.L) { L.Routing.Conf = factory(L); } }(function (L) { L.Routing.Conf = { url: "http://restapi.amap.com/v3/", key: "1ce5f4aef24df9b3315632813c7fcaa2", style: {}, dictionary: [ ["沿", "through"], ["向前走", "go straight"], ["往前走", "go straight"], ["向东", "fece to east"], ["向西", "fece to west"], ["向南", "fece to south"], ["向北", "fece to north"], ["步行", "walk"], ["米", "meter"], ["左转", "turn left"], ["右转", "turn right"] ] }; return L.Routing.Conf; }, window));
JavaScript
0
@@ -394,16 +394,17 @@ l: %22http +s ://resta
d67d0140ccf7adbc77f27a1b2333f08f44c317a5
Add client-side validation for attachment URLs
app/assets/javascripts/student_profile/take_notes.js
app/assets/javascripts/student_profile/take_notes.js
(function() { window.shared || (window.shared = {}); var dom = window.shared.ReactHelpers.dom; var createEl = window.shared.ReactHelpers.createEl; var merge = window.shared.ReactHelpers.merge; var PropTypes = window.shared.PropTypes; var styles = { dialog: { border: '1px solid #ccc', borderRadius: 2, padding: 20, marginBottom: 20, marginTop: 10 }, date: { paddingRight: 10, fontWeight: 'bold', display: 'inline-block' }, educator: { paddingLeft: 5, display: 'inline-block' }, textarea: { fontSize: 14, border: '1px solid #eee', width: '100%' //overriding strange global CSS, should cleanup }, input: { fontSize: 14, border: '1px solid #eee', width: '100%' }, cancelTakeNotesButton: { // overidding CSS color: 'black', background: '#eee', marginLeft: 10, marginRight: 10 }, serviceButton: { background: '#eee', // override CSS color: 'black', // shrinking: width: '12em', fontSize: 12, padding: 8 } }; /* Pure UI form for taking notes about an event, tracking its own local state and submitting it to prop callbacks. */ var TakeNotes = window.shared.TakeNotes = React.createClass({ propTypes: { nowMoment: React.PropTypes.object.isRequired, eventNoteTypesIndex: React.PropTypes.object.isRequired, onSave: React.PropTypes.func.isRequired, onCancel: React.PropTypes.func.isRequired, currentEducator: React.PropTypes.object.isRequired, requestState: PropTypes.nullable(React.PropTypes.string.isRequired) }, getInitialState: function() { return { eventNoteTypeId: null, text: null, eventNoteAttachments: [], } }, // Focus on note-taking text area when it first appears. componentDidMount: function(prevProps, prevState) { this.textareaRef.focus(); }, onChangeText: function(event) { this.setState({ text: event.target.value }); }, onChangeAttachmentUrl: function (event) { this.setState({ eventNoteAttachments: [ { url: event.target.value } ] }); }, onClickNoteType: function(noteTypeId, event) { this.setState({ eventNoteTypeId: noteTypeId }); }, onClickCancel: function(event) { this.props.onCancel(); }, onClickSave: function(event) { var params = _.pick(this.state, 'eventNoteTypeId', 'text', 'eventNoteAttachments'); this.props.onSave(params); }, render: function() { return dom.div({ className: 'TakeNotes', style: styles.dialog }, this.renderNoteHeader({ noteMoment: this.props.nowMoment, educatorEmail: this.props.currentEducator.email }), dom.textarea({ rows: 10, style: styles.textarea, ref: function(ref) { this.textareaRef = ref; }.bind(this), value: this.state.text, onChange: this.onChangeText }), dom.div({ style: { marginBottom: 5, marginTop: 20 } }, 'What are these notes from?'), dom.div({ style: { display: 'flex' } }, dom.div({ style: { flex: 1 } }, this.renderNoteButton(300), this.renderNoteButton(301) ), dom.div({ style: { flex: 1 } }, this.renderNoteButton(302) ), dom.div({ style: { flex: 'auto' } }, this.renderNoteButton(304) ) ), dom.div({ style: { marginBottom: 5, marginTop: 20 } }, 'Add a link (i.e. to an attachment on Google Drive):' ), dom.input({ style: styles.input, onChange: this.onChangeAttachmentUrl, placeholder: 'Please use the format https://www.example.com.' }), dom.br({}), dom.button({ style: { marginTop: 20, background: (this.state.eventNoteTypeId === null) ? '#ccc' : undefined }, disabled: (this.state.eventNoteTypeId === null), className: 'btn save', onClick: this.onClickSave }, 'Save notes'), dom.button({ className: 'btn cancel', style: styles.cancelTakeNotesButton, onClick: this.onClickCancel }, 'Cancel'), (this.props.requestState === 'pending') ? dom.span({}, 'Saving...') : null, (this.props.requestState === 'error') ? dom.span({}, 'Try again!') : null ); }, renderNoteHeader: function(header) { return dom.div({}, dom.span({ style: styles.date }, header.noteMoment.format('MMMM D, YYYY')), '|', dom.span({ style: styles.educator }, header.educatorEmail) ); }, // TODO(kr) extract button UI renderNoteButton: function(eventNoteTypeId) { var eventNoteType = this.props.eventNoteTypesIndex[eventNoteTypeId]; return dom.button({ className: 'btn note-type', onClick: this.onClickNoteType.bind(this, eventNoteTypeId), tabIndex: -1, style: merge(styles.serviceButton, { background: '#eee', outline: 0, border: (this.state.eventNoteTypeId === eventNoteTypeId) ? '4px solid rgba(49, 119, 201, 0.75)' : '4px solid white' }) }, eventNoteType.name); } }); })();
JavaScript
0
@@ -3965,38 +3965,28 @@ his. -state.eventNoteTypeId === null +disabledSaveButton() ) ? @@ -4047,38 +4047,28 @@ his. -state.eventNoteTypeId === null +disabledSaveButton() ),%0A @@ -4499,32 +4499,177 @@ );%0A %7D,%0A%0A + disabledSaveButton: function () %7B%0A return (%0A this.state.eventNoteTypeId === null %7C%7C !this.validAttachmentUrls()%0A );%0A %7D,%0A%0A renderNoteHe @@ -4895,24 +4895,430 @@ );%0A %7D,%0A%0A + validAttachmentUrls: function () %7B%0A var eventNoteAttachments = this.state.eventNoteAttachments;%0A if (eventNoteAttachments === %5B%5D) return true;%0A%0A return eventNoteAttachments.map(function (attachment) %7B%0A return (attachment.url.slice(0, 7) === 'http://' %7C%7C%0A attachment.url.slice(0, 8) === 'https://');%0A %7D).reduce(function (a, b) %7B return a && b %7D, true);%0A %7D,%0A%0A // TODO(
da199b5e82fc92feda1ffc8f48f62358e16a1764
Use errors instead of fatal, don't delete serverMgr on stop
lib/atom-delve.js
lib/atom-delve.js
'use babel'; import SourceView from './components/source.js'; import DelveServerMgr from './delve-server-mgr'; import Config from './config'; import { DelveConnMgr } from './delve-client'; import { CompositeDisposable } from 'atom'; export default { atomDelveView: null, modalPanel: null, subscriptions: null, serverMgr: null, buildFlags: null, activate() { this.serverMgr = new DelveServerMgr(); // overridable settings this.buildFlags = Config.buildFlags; this.modalPanel = atom.workspace.addModalPanel({ item: this.atomDelveView.getElement(), visible: false }); this.subscriptions = new CompositeDisposable(); // commands this.subscriptions.add(atom.commands.add( 'atom-workspace', { 'atom-delve:toggle': () => this.startSession() } )); }, deactivate() { this.modalPanel.destroy(); this.subscriptions.dispose(); this.sourceView.destroy(); this.buildFlags = null; this.stopSession(); }, stopSession() { if (this.serverMgr) this.serverMgr.endSession(); if (this.client) DelveConnMgr.endConnection(); this.serverMgr = null; }, initViews() { this.sourceView = new SourceView(); }, startSession(sessionType, debugPath) { if (this.serverMgr.hasSessionStarted) return; switch (sessionType) { case 'debug': this.serverMgr.startDebugSession(debugPath, this.buildFlags); break; case 'test': this.serverMgr.startTestingSession(debugPath, this.buildFlags); break; default: return atom.notifications.addFatalError( `Invalid session type ${sessionType}` ); } this.serverMgr.on('startServer', (host, port) => { console.debug(`Started Delve server at ${debugPath}`); DelveConnMgr.connect() .then(() => { console.debug(`Connected to Delve server at ${host}:${port}`); this.initViews(); }) .catch(err => { atom.notifications.addFatalError('Could not connect to Delve server', { detail: err.toString(), dismissable: true }); this.stopSession(); }); }); this.serverMgr.on('error', err => { atom.notifications .addFatalError('Received an error from the Delve server process', { detail: err.toString(), dismissable: true }); this.stopSession(); }); } };
JavaScript
0
@@ -530,136 +530,8 @@ s;%0A%0A - this.modalPanel = atom.workspace.addModalPanel(%7B%0A item: this.atomDelveView.getElement(),%0A visible: false%0A %7D);%0A%0A @@ -712,18 +712,81 @@ Session( +%0A 'debug', '/Users/tylerfowler/git/atom-delve/lib'%0A ) - %7D%0A )) @@ -1090,36 +1090,8 @@ n(); -%0A%0A this.serverMgr = null; %0A %7D @@ -1196,32 +1196,51 @@ Path) %7B%0A if ( +!this.serverMgr %7C%7C this.serverMgr.h @@ -1524,29 +1524,24 @@ ications.add -Fatal Error(%0A @@ -1544,16 +1544,28 @@ %60 +atom-delve: Invalid @@ -2165,29 +2165,24 @@ s%0A .add -Fatal Error('Recei
4f7c10a2abcd38f51fdc09dbdda60c6763a6afbc
fix experiment group without ip logic
app/services/experiments.js
app/services/experiments.js
import Service, { inject as service } from '@ember/service' import ENV from 'pilasbloques/config/environment' import seedrandom from 'seedrandom'; import { computed } from '@ember/object' export default Service.extend({ group: ENV.experimentGroup, storage: service(), pilasBloquesApi: service(), challengeExpectations: service(), //This order is important, do NOT change possibleGroups: ["treatment", "control", "notAffected"], decompositionTreatmentLength: ENV.decompositionTreatmentLength, solvedChallenges: computed('storage', function () { return this.get('storage').getSolvedChallenges() }), isTreatmentGroup() { return this.experimentGroup() === this.possibleGroups[0] }, isControlGroup() { return this.experimentGroup() === this.possibleGroups[1] }, isNotAffected() { return !(this.isTreatmentGroup() || this.isControlGroup()) }, isAutoAssignGroup(){ return this.group === "autoassign" }, experimentGroup() { return this.isAutoAssignGroup() ? this.getExperimentGroupAssigned() : this.group }, getExperimentGroupAssigned(){ return this.storage.getExperimentGroup() || this.pilasBloquesApi.getUser()?.experimentGroup || this.randomizeAndSaveExperimentGroup() // jshint ignore:line }, randomizeAndSaveExperimentGroup(){ const randomExperimentGroup = this.getRandomExperimentGroup() this.storage.saveExperimentGroup(randomExperimentGroup) if(this.pilasBloquesApi.getUser()){ this.pilasBloquesApi.saveExperimentGroup(randomExperimentGroup) } return randomExperimentGroup }, getRandomExperimentGroup(){ const ip = this.storage.getUserIp() return this.possibleGroups[this.randomIndex(ip)] }, randomIndex(seed){ const randomizedSeed = seedrandom(seed) const experimentGroupNumber = randomizedSeed() * (this.possibleGroups.length - 1) return Math.floor(experimentGroupNumber) }, async saveUserIP(){ if(!this.storage.getUserIp()){ try{ const response = await fetch("https://api64.ipify.org?format=json") const jsonIp = await response.json() this.storage.saveUserIp(jsonIp.ip) }catch(e){ //If fetch fails, getRandomExperimentGroup will use 'null' as seed, resulting in "treatment" console.error(e); } } }, groupId() { return this.group.charAt(0) }, updateSolvedChallenges(challenge){ const _solvedChallenges = this.solvedChallenges if (this.shouldUpdateSolvedChallenges(challenge)){ _solvedChallenges.push(challenge.id) this.storage.saveSolvedChallenges(_solvedChallenges) } }, shouldShowCongratulationsModal(){ return this.isNotAffected() }, shouldShowBlocksExpectationFeedback(){ return this.isTreatmentGroup() && !this.feedbackIsDisabled() }, shouldShowScoredExpectations(){ return !(this.isControlGroup() || this.feedbackIsDisabled()) }, feedbackIsDisabled(){ return this.solvedChallenges.length >= this.decompositionTreatmentLength }, shouldUpdateSolvedChallenges(challenge){ return !this.solvedChallenges.includes(challenge.id) && this.hasDecompositionExpect(challenge) }, hasDecompositionExpect(challenge){ return this.challengeExpectations.hasDecomposition(challenge) } });
JavaScript
0.000001
@@ -222,16 +222,33 @@ %0A group +SelectionStrategy : ENV.ex @@ -917,21 +917,24 @@ toAssign -Group +Strategy ()%7B%0A @@ -950,16 +950,33 @@ is.group +SelectionStrategy === %22au @@ -991,16 +991,337 @@ %22%0A %7D,%0A%0A + /**%0A * If the group selection strategy is autoassign, returns a random group based on the user ip. %0A * In the case that the user does not have an internet connection, always returns notAffected group.%0A * If the group selection strategy is other than autoassign, then returns the group assigned as strategy.%0A */%0A experi @@ -1366,18 +1366,22 @@ sign -Group +Strategy () ? +( this @@ -1414,20 +1414,64 @@ d() -: this.group +%7C%7C this.possibleGroups%5B2%5D) : this.groupSelectionStrategy %0A %7D @@ -1519,45 +1519,8 @@ turn - this.storage.getExperimentGroup() %7C%7C thi @@ -1566,16 +1566,52 @@ Group %7C%7C + this.storage.getExperimentGroup()%7C%7C this.ra @@ -1990,24 +1990,229 @@ Group%0A %7D,%0A%0A + /**%0A * Randomizes with the ip as seed because we want every student in a classroom to have the same experiment group%0A * @returns an experiment group or null in case the ip has not been set yet%0A */%0A getRandomE @@ -2275,24 +2275,30 @@ )%0A return + ip && this.possib @@ -2790,110 +2790,8 @@ e)%7B%0A - //If fetch fails, getRandomExperimentGroup will use 'null' as seed, resulting in %22treatment%22 %0A
3d4047e7054971aa80ca41a2318b5e743cd56aee
Include three `*` in horizontal_rule class
src/languages/markdown.js
src/languages/markdown.js
/* Language: Markdown Requires: xml.js Author: John Crepezzi <[email protected]> Website: http://seejohncode.com/ */ function(hljs) { return { contains: [ // highlight headers { className: 'header', variants: [ { begin: '^#{1,6}', end: '$' }, { begin: '^.+?\\n[=-]{2,}$' } ] }, // inline html { begin: '<', end: '>', subLanguage: 'xml', relevance: 0 }, // lists (indicators only) { className: 'bullet', begin: '^([*+-]|(\\d+\\.))\\s+' }, // strong segments { className: 'strong', begin: '[*_]{2}.+?[*_]{2}' }, // emphasis segments { className: 'emphasis', variants: [ { begin: '\\*.+?\\*' }, { begin: '_.+?_' , relevance: 0 } ] }, // blockquotes { className: 'blockquote', begin: '^>\\s+', end: '$' }, // code snippets { className: 'code', variants: [ { begin: '`.+?`' }, { begin: '^( {4}|\t)', end: '$' , relevance: 0 } ] }, // horizontal rules { className: 'horizontal_rule', begin: '^-{3,}', end: '$' }, // using links - title and link { begin: '\\[.+?\\]\\(.+?\\)', returnBegin: true, contains: [ { className: 'link_label', begin: '\\[', end: '\\]', excludeBegin: true, excludeEnd: true, relevance: 0 }, { className: 'link_url', begin: '\\(', end: '\\)', excludeBegin: true, excludeEnd: true } ], relevance: 10 } ] }; }
JavaScript
0.000021
@@ -1291,17 +1291,22 @@ egin: '%5E -- +%5B-%5C%5C*%5D %7B3,%7D', e
0347c62101d40ab433da21a0d81a9e787aa51a67
use JSON.stringify for complex data on data export
app/src/utils/exportData.js
app/src/utils/exportData.js
import { search } from '../apis'; let jsonData = []; export const MAX_DATA = 100000; const defaultQuery = { query: { match_all: {}, }, }; /** * A function to convert multilevel object to single level object and use key value pairs as Column and row pairs using recursion */ export const flatten = data => { const result = {}; function recurse(cur, prop = '') { if (Object(cur) !== cur) { result[prop] = cur; } else if (Array.isArray(cur)) { const l = cur.length; for (let i = 0; i < l; i += 1) { recurse(cur[i], `${prop}[${i}]`); } if (l === 0) { result[prop] = []; } } else { let isEmpty = true; Object.keys(cur).forEach(p => { isEmpty = false; recurse(cur[p], prop ? `${prop}.${p}` : p); }); if (isEmpty && prop) { result[prop] = {}; } } } recurse(data); return result; }; export const searchAfter = async ( app, types, url, version, query, chunkInfo, searchAfterData, ) => { try { const others = {}; if (searchAfterData) { others.search_after = [searchAfterData]; } const sortKey = version > 5 ? '_id' : '_uid'; const data = await search(app, types, url, { ...query, size: 1000, sort: [ { [sortKey]: 'desc', }, ], ...others, }); // eslint-disable-next-line const res = await getSearchAfterData( app, types, url, version, query, chunkInfo, searchAfterData, data, ); if (typeof res === 'string') { let exportData = JSON.parse(res); const lastObject = exportData[exportData.length - 1]; exportData = exportData.map(value => { const item = Object.assign(value._source); return item; }); return { data: exportData, searchAfter: version > 5 ? lastObject._id : `${lastObject._type}#${lastObject._id}`, }; } return res; } catch (e) { console.error('SEARCH ERROR', e); return e; } }; const getSearchAfterData = async ( app, types, url, version, query, chunkInfo, searchAfterData, data, ) => { const { hits } = data; let str = null; /** * Checking if the current length is less than chunk total, recursive call searchAfter */ if (hits && jsonData.length < chunkInfo.total) { const { hits: totalhits, total } = hits; jsonData = jsonData.concat(totalhits); const lastObject = totalhits[totalhits.length - 1]; const nextSearchData = version > 5 ? lastObject._id : `${lastObject._type}#${lastObject._id}`; return searchAfter( app, types, url, version, query, chunkInfo, totalhits.length === total ? '' : nextSearchData, ); } str = JSON.stringify(jsonData, null, 4); jsonData = []; return str; }; /** * Main function for getting data to be exported; * @param {*} app * @param {*} types * @param {*} url * @param {*} query * @param {*} searchAfter */ const exportData = async ( app, types, url, version, query, chunkInfo, searchAfterData, ) => { try { const finalQuery = query || defaultQuery; const res = await searchAfter( app, types, url, version, finalQuery, chunkInfo, searchAfterData, ); return res; } catch (e) { return e; } }; export default exportData;
JavaScript
0.000003
@@ -461,154 +461,43 @@ %0A%09%09%09 -const l = cur.length;%0A%09%09%09for (let i = 0; i %3C l; i += 1) %7B%0A%09%09%09%09recurse(cur%5Bi%5D, %60$%7Bprop%7D%5B$%7Bi%7D%5D%60);%0A%09%09%09%7D%0A%09%09%09if (l === 0) %7B%0A%09%09%09%09result%5Bprop%5D = %5B%5D;%0A%09%09%09%7D +result%5Bprop%5D = JSON.stringify(cur); %0A%09%09%7D
b67caf9be48294bef290eea69e90d98223fcf3eb
Add paragraph about browser add-ons when encountering some errors (#14801)
app/javascript/mastodon/components/error_boundary.js
app/javascript/mastodon/components/error_boundary.js
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { version, source_url } from 'mastodon/initial_state'; import StackTrace from 'stacktrace-js'; export default class ErrorBoundary extends React.PureComponent { static propTypes = { children: PropTypes.node, }; state = { hasError: false, errorMessage: undefined, stackTrace: undefined, mappedStackTrace: undefined, componentStack: undefined, }; componentDidCatch (error, info) { this.setState({ hasError: true, errorMessage: error.toString(), stackTrace: error.stack, componentStack: info && info.componentStack, mappedStackTrace: undefined, }); StackTrace.fromError(error).then((stackframes) => { this.setState({ mappedStackTrace: stackframes.map((sf) => sf.toString()).join('\n'), }); }).catch(() => { this.setState({ mappedStackTrace: undefined, }); }); } handleCopyStackTrace = () => { const { errorMessage, stackTrace, mappedStackTrace } = this.state; const textarea = document.createElement('textarea'); let contents = [errorMessage, stackTrace]; if (mappedStackTrace) { contents.push(mappedStackTrace); } textarea.textContent = contents.join('\n\n\n'); textarea.style.position = 'fixed'; document.body.appendChild(textarea); try { textarea.select(); document.execCommand('copy'); } catch (e) { } finally { document.body.removeChild(textarea); } this.setState({ copied: true }); setTimeout(() => this.setState({ copied: false }), 700); } render() { const { hasError, copied } = this.state; if (!hasError) { return this.props.children; } return ( <div className='error-boundary'> <div> <p className='error-boundary__error'><FormattedMessage id='error.unexpected_crash.explanation' defaultMessage='Due to a bug in our code or a browser compatibility issue, this page could not be displayed correctly.' /></p> <p><FormattedMessage id='error.unexpected_crash.next_steps' defaultMessage='Try refreshing the page. If that does not help, you may still be able to use Mastodon through a different browser or native app.' /></p> <p className='error-boundary__footer'>Mastodon v{version} · <a href={source_url} rel='noopener noreferrer' target='_blank'><FormattedMessage id='errors.unexpected_crash.report_issue' defaultMessage='Report issue' /></a> · <button onClick={this.handleCopyStackTrace} className={copied ? 'copied' : ''}><FormattedMessage id='errors.unexpected_crash.copy_stacktrace' defaultMessage='Copy stacktrace to clipboard' /></button></p> </div> </div> ); } }
JavaScript
0.000046
@@ -1720,16 +1720,30 @@ , copied +, errorMessage %7D = thi @@ -1810,24 +1810,117 @@ ren;%0A %7D%0A%0A + const likelyBrowserAddonIssue = errorMessage && errorMessage.includes('NotFoundError');%0A%0A return ( @@ -2020,16 +2020,314 @@ _error'%3E +%0A %7B likelyBrowserAddonIssue ? (%0A %3CFormattedMessage id='error.unexpected_crash.explanation_addons' defaultMessage='This page could not be displayed correctly. This error is likely caused by a browser add-on or automatic translation tools.' /%3E%0A ) : (%0A %3CFormatt @@ -2502,26 +2502,109 @@ ' /%3E -%3C/p%3E%0A %3Cp%3E +%0A )%7D%0A %3C/p%3E%0A %3Cp%3E%0A %7B likelyBrowserAddonIssue ? (%0A %3CFor @@ -2654,16 +2654,23 @@ xt_steps +_addons ' defaul @@ -2683,16 +2683,35 @@ ge='Try +disabling them and refreshi @@ -2830,16 +2830,280 @@ app.' /%3E +%0A ) : (%0A %3CFormattedMessage id='error.unexpected_crash.next_steps' defaultMessage='Try refreshing the page. If that does not help, you may still be able to use Mastodon through a different browser or native app.' /%3E%0A )%7D%0A %3C/p%3E%0A
b3202be81dc069d5b144f99a6d1a0387f9329a76
Update handling of artificialToken ids
app/js/arethusa.artificial_token/artificial_token.js
app/js/arethusa.artificial_token/artificial_token.js
"use strict"; angular.module('arethusa.artificialToken').service('artificialToken', [ 'state', 'configurator', 'idHandler', function(state, configurator, idHandler) { var self = this; function configure() { configurator.getConfAndDelegate('artificialToken', self); self.createdTokens = {}; self.count = 0; delete self.mode; resetModel(); } configure(); function resetModel() { self.model = new ArtificialToken(); } function ArtificialToken (string, type) { var self = this; this.string = string; this.type = type || 'elliptic'; this.artificial = true; this.idMap = new idHandler.Map(); } this.supportedTypes = [ 'elliptic' ]; this.setType = function(type) { self.model.type = type; }; this.hasType = function(type) { return self.model.type === type; }; this.toggleMode = function(mode) { if (self.mode === mode) { delete self.mode; } else { self.mode = mode; } }; var count = 0; function setString() { if (! self.model.string) { self.model.string = '[' + count + ']'; count++; } } this.modelValid = function() { return self.model.type && self.model.insertionPoint; }; function idIdentifier(id) { return 'a'; } function recountATs() { self.count = Object.keys(self.createdTokens).length; } function findArtificialTokensInState() { angular.forEach(state.tokens, function(token, id) { if (token.artificial) { addArtificialToken(id, token); } }); } function addArtificialToken(id, token) { self.createdTokens[id] = token; recountATs(); } function removeArtificialToken(id) { delete self.createdTokens[id]; recountATs(); } this.removeToken = function(id) { state.removeToken(id); removeArtificialToken(id); }; this.propagateToState = function() { setString(); var id = self.model.insertionPoint.id; var idBefore = idHandler.decrement(id); var newId = idBefore + idIdentifier(idBefore); self.model.id = newId; addArtificialToken(newId, self.model); state.addToken(self.model, newId); resetModel(); }; this.init = function() { configure(); findArtificialTokensInState(); }; } ]);
JavaScript
0
@@ -1325,65 +1325,8 @@ %7D;%0A%0A - function idIdentifier(id) %7B%0A return 'a';%0A %7D%0A%0A @@ -2056,24 +2056,21 @@ var -idBefore +newId = idHan @@ -2099,54 +2099,93 @@ -var newId = idBefore + idIdentifier(idBefore); +if (!idHandler.isExtendedId(id)) %7B%0A newId = idHandler.extendId(newId);%0A %7D %0A
add244c6954d96f87d8b7d7f9459e4f940abb8dd
Improve results performance for `hain-plugin-filesearch` for recent items
app/main-es6/plugins/hain-plugin-filesearch/index.js
app/main-es6/plugins/hain-plugin-filesearch/index.js
'use strict'; const fs = require('original-fs'); const co = require('co'); const lo_reject = require('lodash.reject'); const path = require('path'); const readdir = require('./readdir'); const RECENT_ITEM_COUNT = 100; const RECENT_ITEM_WEIGHT = 1.2; const matchFunc = (filePath, stats) => { const ext = path.extname(filePath).toLowerCase(); if (stats.isDirectory()) return true; return (ext === '.exe' || ext === '.lnk'); }; function injectEnvVariable(dirPath) { let _path = dirPath; for (const envVar in process.env) { const value = process.env[envVar]; _path = _path.replace(`\${${envVar}}`, value); } return _path; } function injectEnvVariables(dirArr) { const newArr = []; for (let i = 0; i < dirArr.length; ++i) { const dirPath = dirArr[i]; newArr.push(injectEnvVariable(dirPath)); } return newArr; } module.exports = (context) => { const matchutil = context.matchutil; const logger = context.logger; const shell = context.shell; const app = context.app; const initialPref = context.preferences.get(); const localStorage = context.localStorage; const toast = context.toast; let _recentUsedItems = []; const recursiveSearchDirs = injectEnvVariables(initialPref.recursiveFolders || []); const flatSearchDirs = injectEnvVariables(initialPref.flatFolders || []); const db = {}; const lazyIndexingKeys = {}; function* refreshIndex(dirs, recursive) { for (const dir of dirs) { logger.log(`refreshIndex ${dir}`); if (fs.existsSync(dir) === false) { logger.log(`can't find a dir: ${dir}`); continue; } const files = yield co(readdir(dir, recursive, matchFunc)); logger.log(`index updated ${dir}`); db[dir] = files; } } function lazyRefreshIndex(dir, recursive) { const _lazyKey = lazyIndexingKeys[dir]; if (_lazyKey !== undefined) { clearTimeout(_lazyKey); } lazyIndexingKeys[dir] = setTimeout(() => { co(refreshIndex([dir], recursive)); }, 5000); } function* setupWatchers(dirs, recursive) { for (const dir of dirs) { const _dir = dir; fs.watch(_dir, { persistent: true, recursive: recursive }, (evt, filename) => { lazyRefreshIndex(_dir, recursive); }); } } function addRecentItem(item) { const idx = _recentUsedItems.indexOf(item); if (idx >= 0) _recentUsedItems.splice(idx, 1); if (fs.existsSync(item)) _recentUsedItems.unshift(item); _recentUsedItems = _recentUsedItems.slice(0, RECENT_ITEM_COUNT); localStorage.setItem('recentUsedItems', _recentUsedItems); } function updateRecentItems() { const aliveItems = []; for (const item of _recentUsedItems) { if (fs.existsSync(item)) aliveItems.push(item); } _recentUsedItems = aliveItems; } function startup() { _recentUsedItems = localStorage.getItemSync('recentUsedItems') || []; updateRecentItems(); co(function* () { yield* refreshIndex(recursiveSearchDirs, true); yield* refreshIndex(flatSearchDirs, false); yield* setupWatchers(recursiveSearchDirs, true); yield* setupWatchers(flatSearchDirs, false); }).catch((err) => { logger.log(err); logger.log(err.stack); }); } function computeRatio(filePath) { let ratio = 1; const ext = path.extname(filePath).toLowerCase(); const basename = path.basename(filePath).toLowerCase(); if (ext !== '.lnk' && ext !== '.exe') ratio *= 0.5; if (ext === '.lnk') ratio *= 1.5; if (basename.indexOf('uninstall') >= 0 || basename.indexOf('remove') >= 0) ratio *= 0.9; return ratio; } function _fuzzyResultToSearchResult(results, group, scoreWeight) { const _group = group || 'Files & Folders'; const _scoreWeight = scoreWeight || 1; return results.map(x => { const filePath = x.elem; const filePath_bold = matchutil.makeStringBoldHtml(filePath, x.matches); const filePath_base64 = new Buffer(filePath).toString('base64'); const score = x.score * computeRatio(filePath) * _scoreWeight; return { id: filePath, title: path.basename(filePath, path.extname(filePath)), desc: filePath_bold, icon: `icon://${filePath_base64}`, group: _group, score }; }); } function search(query, res) { const query_trim = query.replace(' ', ''); const recentFuzzyResults = matchutil.fuzzy(_recentUsedItems, query_trim, x => x); const selectedRecentItems = recentFuzzyResults.map(x => x.elem); if (recentFuzzyResults.length > 0) { const recentSearchResults = _fuzzyResultToSearchResult(recentFuzzyResults, 'Recent Items', RECENT_ITEM_WEIGHT); res.add(recentSearchResults); } const fileFuzzyResults = matchutil.fuzzy(db, query_trim, x => x); let fileSearchResults = _fuzzyResultToSearchResult(fileFuzzyResults.slice(0, 10)); // Reject if it is duplicated with recent items fileSearchResults = lo_reject(fileSearchResults, x => selectedRecentItems.indexOf(x.id) >= 0); res.add(fileSearchResults); } function execute(id, payload) { // Update recent item, and it will be deleted if file don't exists addRecentItem(id); if (fs.existsSync(id) === false) { toast.enqueue('Sorry, Could\'nt Find a File'); return; } shell.openItem(id); app.close(); } return { startup, search, execute }; };
JavaScript
0
@@ -4516,26 +4516,38 @@ rim, x =%3E x) +.slice(0, 2) ;%0A - const se @@ -4599,24 +4599,59 @@ =%3E x.elem);%0A + let recentSearchResults = %5B%5D;%0A%0A if (rece @@ -4676,31 +4676,23 @@ gth %3E 0) - %7B %0A -const recentSe @@ -4792,50 +4792,8 @@ HT); -%0A res.add(recentSearchResults);%0A %7D %0A%0A @@ -5103,25 +5103,95 @@ 0);%0A +%0A -res.add(fileS +const searchResults = recentSearchResults.concat(fileSearchResults);%0A res.add(s earc
d48d9a5442a8a0ad4ed1b8d717518becb33cda6e
Add crack time to password strength bar
app/routes/users/components/PasswordStrengthMeter.js
app/routes/users/components/PasswordStrengthMeter.js
// @flow import React, { Component, Fragment } from 'react'; import { pick } from 'lodash'; import zxcvbn from 'zxcvbn'; import Bar from 'react-meter-bar'; import styles from './PasswordStrengthMeter.css'; import { passwordLabel, barColor, passwordFeedbackMessages } from './passwordStrengthVariables'; type Props = { password: string, user: Object }; class PasswordStrengthMeter extends Component<Props> { render() { const { password, user } = this.props; const zxcvbnValue = zxcvbn( password, Object.values(pick(user, ['username', 'firstName', 'lastName'])) ); let tips = zxcvbnValue.feedback.suggestions; tips.push(zxcvbnValue.feedback.warning); tips = tips.map(tip => passwordFeedbackMessages[tip]).filter(Boolean); return ( <Fragment> <div className={styles.removeLabels}> <Bar labels={[1, 2, 3, 4, 5]} labelColor="#000" progress={zxcvbnValue.score * 25} barColor={barColor[zxcvbnValue.score]} seperatorColor="#fff" /> </div> {password && ( <div> <strong>Passordstyrke: </strong> {passwordLabel[zxcvbnValue.score]}{' '} </div> )} {password && zxcvbnValue.score < 2 && ( <ul className={styles.tipsList}> {tips.map((value, key) => { return <li key={key}>{value}</li>; })} </ul> )} </Fragment> ); } } export default PasswordStrengthMeter;
JavaScript
0.000003
@@ -86,16 +86,54 @@ odash';%0A +import moment from 'moment-timezone';%0A import z @@ -153,16 +153,16 @@ xcvbn';%0A - import B @@ -803,16 +803,289 @@ lean);%0A%0A + let crackTimeSec =%0A zxcvbnValue.crack_times_seconds.offline_slow_hashing_1e4_per_second;%0A let crackTimeDuration = moment.duration(crackTimeSec, 'seconds').humanize();%0A let crackTime =%0A crackTimeSec %3E 2 ? crackTimeDuration : crackTimeSec + ' sekunder';%0A%0A retu @@ -1427,21 +1427,47 @@ %3C -div%3E%0A +Fragment%3E%0A %3Cspan%3E%0A @@ -1502,16 +1502,35 @@ /strong%3E +%7B' '%7D%0A %7Bpasswo @@ -1560,29 +1560,183 @@ re%5D%7D -%7B' '%7D%0A %3C/div +%0A %3C/span%3E%0A %3Cp%3E%0A Dette passordet hadde tatt en maskin %7BcrackTime%7D %C3%A5 knekke @ 10%5E4%0A Hash/s.%0A %3C/p%3E%0A %3C/Fragment %3E%0A
83475a320127a1dd1919589e86e91e2ae4ba0a0a
fix signup api loading
lib/boot/index.js
lib/boot/index.js
/** * Module dependencies. */ var express = require('express') var path = require('path') var translations = require('lib/translations') var t = require('t-component') var config = require('lib/config') var visibility = require('lib/visibility') var app = module.exports = express() /** * Set `views` directory for module */ app.set('views', __dirname) /** * Set `view engine` to `jade`. */ app.set('view engine', 'jade') /** * middleware for favicon */ app.use(express.favicon(path.join(__dirname, '/assets/favicon.ico'))) /* * Register Models and Launch Mongoose */ require('lib/models')(app) /** * Set `app` configure settings */ require('lib/setup')(app) /* * PassportJS Auth Strategies and Routes */ require('lib/auth')(app) /* * Twitter card routes */ app.use('/twitter-card', require('lib/twitter-card')) /* * Facebook card routes */ app.use('/facebook-card', require('lib/facebook-card')) /* * Local signin routes */ app.use('/signin', require('lib/signin-api')) /* * Local signup routes */ if (config.signupUrl) app.use('/signup', require('lib/signup-api')) /* * Forgot password routes */ app.use('/forgot', require('lib/forgot-api')) /** * Root API Service */ app.use('/api', require('lib/api')) /** * User API Service */ app.use('/api', require('lib/user')) app.use(require('lib/signin')) app.use(require('lib/signup')) app.use(require('lib/forgot')) /* * Restrict private routes if neccesary */ app.all('*', visibility) /* * Account routes */ app.use('/settings', require('lib/settings-api')) /* * Stats routes */ app.use('/stats', require('lib/stats-api')) /* * RSS routes */ app.use('/rss', require('lib/rss')) /** * Tag API Service */ app.use('/api', require('lib/tag')) /** * Topic API Service */ app.use('/api', require('lib/topic-api')) /** * Whitelist API Service */ app.use('/api', require('lib/whitelist-api')) /** * Comment API Service */ app.use('/api', require('lib/comment')) /** * Forums API Service */ app.use('/api', require('lib/forum-api')) /** * Notifications API Service */ app.use('/api', require('lib/notification-api')) /** * Load localization dictionaries to translation application */ translations.help(t) /** * Init `t-component` component with parameter locale */ t.lang(config.locale) /** * Set native `express` router middleware */ app.use(app.router) // Here we should have our own error handler! /** * Set native `express` error handler */ app.use(express.errorHandler()) /** * Load Styleguide */ if (config.env !== 'production') { app.use(require('lib/styleguide')) } /** * GET index page. */ app.use(require('lib/browser-update')) app.use(require('lib/admin')) app.use(require('lib/settings')) app.use(require('lib/help')) app.use(require('lib/homepage')) app.use(require('lib/topic')) app.use(require('lib/notifications-page')) app.use(require('lib/forum')) app.use(require('lib/404'))
JavaScript
0
@@ -1031,28 +1031,30 @@ routes%0A */%0A +%0A if ( +! config.signu
36bce93eaf96513691fc8052ec57acb1e7f582da
Fix anvaka button position
extension/index.js
extension/index.js
// Escape HTML function esc(str) { return String(str) .replace(/&/g, '&amp;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); } // Get DOM node from HTML function html(html) { if (html.raw) { // Shortcut for html`text` instead of html(`text`) html = String.raw(...arguments); } const fragment = document.createRange().createContextualFragment(html.trim()); if (fragment.firstChild === fragment.lastChild) { return fragment.firstChild; } return fragment; } const isGitLab = document.querySelector('.navbar-gitlab'); const packageLink = document.querySelector('.files [title="package.json"], .tree-item-file-name [title="package.json"]'); if (packageLink) { const boxTemplate = document.querySelector('#readme, .readme-holder'); const dependenciesBox = createBox(boxTemplate, 'Dependencies'); fetch(packageLink.href, {credentials: 'include'}).then(res => res.text()).then(generateLists); function generateLists(domStr) { const json = html(domStr).querySelector('.blob-wrapper, .blob-content').textContent; const pkg = JSON.parse(json); const dependencies = Object.keys(pkg.dependencies || {}); const devDependencies = Object.keys(pkg.devDependencies || {}); addDependencies(dependenciesBox, dependencies); // Don't show dev dependencies if there are absolutely no dependencies if (dependencies.length || devDependencies.length) { addDependencies(createBox(boxTemplate, 'Dev Dependencies'), devDependencies); } if (dependencies.length && !pkg.private) { const link = html`<a class="npmhub-anvaka btn btn-sm">Dependency tree visualization`; link.href = `http://npm.anvaka.com/#/view/2d/${esc(pkg.name)}`; dependenciesBox.appendChild(link); } } function createBox(boxTemplate, title) { const containerEl = boxTemplate.cloneNode(); containerEl.removeAttribute('id'); containerEl.appendChild(isGitLab ? html`<div class="file-title"><strong>${title}` : html`<h3>${title}` ); containerEl.appendChild(html`<ol class="deps markdown-body">`); document.querySelector('.repository-content, .tree-content-holder').appendChild(containerEl); return containerEl; } function addDependencies(containerEl, list) { const listEl = containerEl.querySelector('.deps'); if (list.length) { list.forEach(name => { const depUrl = 'https://registry.npmjs.org/' + name; const depEl = html`<li><a href='http://ghub.io/${esc(name)}'>${esc(name)}</a>&nbsp;</li>`; listEl.appendChild(depEl); backgroundFetch(depUrl).then(dep => { depEl.appendChild(html(dep.description)); }); }); } else { listEl.appendChild(html`<li class="empty">No dependencies! 🎉</li>`); } } }
JavaScript
0.000001
@@ -1270,24 +1270,285 @@ es %7C%7C %7B%7D);%0A%0A + if (dependencies.length && !pkg.private) %7B%0A const link = html%60%3Ca class=%22npmhub-anvaka btn btn-sm%22%3EDependency tree visualization%60;%0A link.href = %60http://npm.anvaka.com/#/view/2d/$%7Besc(pkg.name)%7D%60;%0A dependenciesBox.appendChild(link);%0A %7D%0A %0A addDepen @@ -1813,265 +1813,8 @@ %7D -%0A%0A if (dependencies.length && !pkg.private) %7B%0A const link = html%60%3Ca class=%22npmhub-anvaka btn btn-sm%22%3EDependency tree visualization%60;%0A link.href = %60http://npm.anvaka.com/#/view/2d/$%7Besc(pkg.name)%7D%60;%0A dependenciesBox.appendChild(link);%0A %7D %0A %7D @@ -2837,8 +2837,9 @@ %7D%0A %7D%0A%7D +%0A
22ffe9c0158a27314ae24163592752d392ec3b7c
Update helper to set auth type.
tests/e2e/utils/setup-site-kit.js
tests/e2e/utils/setup-site-kit.js
/** * setupSiteKit utility. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * WordPress dependencies */ import { activatePlugin } from '@wordpress/e2e-test-utils'; /** * Internal depedencies */ import { setSiteVerification, setSearchConsoleProperty, } from '.'; export const setupSiteKit = async ( { verified, property } = {} ) => { await activatePlugin( 'e2e-tests-auth-plugin' ); await setSiteVerification( verified ); await setSearchConsoleProperty( property ); };
JavaScript
0
@@ -896,22 +896,148 @@ erty - %7D = %7B%7D ) =%3E %7B +, auth = 'proxy' %7D = %7B%7D ) =%3E %7B%0A%09if ( auth !== 'proxy' && auth !== 'gcp' ) %7B%0A%09%09throw new Error( 'Auth type must be either proxy or gcp' );%0A%09%7D %0A%09aw @@ -1056,17 +1056,17 @@ Plugin( -' +%60 e2e-test @@ -1067,16 +1067,26 @@ e-tests- +$%7B auth %7D- auth-plu @@ -1088,17 +1088,17 @@ h-plugin -' +%60 );%0A%09awa
a9e6dba5b9644c37137e0170cae99da4fcd570cd
remove a todo
src/scripts/components/piano-keyboard.js
src/scripts/components/piano-keyboard.js
/** @jsx REACT.DOM */ import React from 'react'; import cuid from 'cuid'; export default React.createClass({ componentDidMount: function() { let keyboardEl = this.refs.keyboard.getDOMNode(); keyboardEl.id = cuid(); this.hancock = new QwertyHancock({ id: keyboardEl.id, width: 600, height: 150, octaves: 2, startNote: 'A3', whiteNotesColour: 'white', blackNotesColour: 'black', hoverColour: '#f3e939' }); setTimeout(() => { console.log('widening'); this.hancock.width = 700; }, 5000); }, render: function () { return ( <div ref="keyboard" className="piano-keyboard">TODO keyboard goes here</div> ); } });
JavaScript
0.002849
@@ -663,31 +663,8 @@ rd%22%3E -TODO keyboard goes here %3C/di
c4c9560495ec7090751950b9a0cfa34552cf569e
Handle two forward slashes
favicon-request.js
favicon-request.js
/* eslint-disable no-console */ const http = require('http'); const https = require('https'); const MAX_REDIRECTS = 3; const KNOWN_ICONS = { 'gmail.com': 'https://ssl.gstatic.com/ui/v1/icons/mail/images/favicon5.ico' }; function faviconApp(req, res) { if (req.url === '/favicon.ico') { res.writeHead(204); res.end(); return; } if (req.url === '/') { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('This is a service for loading website favicons with CORS\n\n' + 'Usage: GET /domain.com\n' + 'Questions, source code: https://github.com/keeweb/favicon-proxy'); return; } console.log('GET', req.url, req.headers.origin || '', req.connection.remoteAddress || '', req.headers['x-forwarded-for'] || ''); const domain = req.url.substr(1).toLowerCase(); if (domain.indexOf('.') < 0 || domain.indexOf('/') >= 0) { return returnError(res, 'Usage: GET /domain.com'); } if (domain.indexOf('keeweb.info') >= 0 || domain === 'favicon-proxy.herokuapp.com') { return returnError(res, 'No, I cannot get my own favicon'); } const faviconUrl = KNOWN_ICONS[domain] || 'http://' + domain + '/favicon.ico'; loadResource(faviconUrl).then(srvRes => { pipeResponse(res, srvRes); }).catch(e => { if (e === 'Status 404') { loadResource('http://' + domain).then(srvRes => { readHtml(srvRes).then(html => { const iconUrl = getIconUrl(html, domain); if (iconUrl) { loadResource(iconUrl).then(srvRes => { pipeResponse(res, srvRes); }).catch(e => returnError(e)); } else { returnError(res, 'No favicon'); } }).catch(e => returnError(res, e)); }).catch(e => returnError(res, e)); } else { returnError(res, e); } }); } function loadResource(url, redirectNum) { return new Promise((resolve, reject) => { const proto = url.lastIndexOf('https', 0) === 0 ? https : http; const serverReq = proto.get(url, srvRes => { if (srvRes.statusCode > 300 && srvRes.statusCode < 400 && srvRes.headers.location) { if (redirectNum > MAX_REDIRECTS) { reject('Too many redirects'); } else { resolve(loadResource(srvRes.headers.location, (redirectNum || 0) + 1)); } } else if (srvRes.statusCode === 200) { resolve(srvRes); } else { reject('Status ' + srvRes.statusCode); } }); serverReq.on('error', e => { reject(e.message); }); serverReq.end(); }); } function readHtml(stream) { return new Promise((resolve, reject) => { const chunks = []; stream.on('data', chunk => { chunks.push(chunk); }); stream.on('error', () => { reject('HTML read error'); }); stream.on('end', () => { resolve(Buffer.concat(chunks).toString('utf8')); }); }); } function getIconUrl(html, domain) { const MAX_SIZE = 96; let match; const re = /<link\s+[^>]*rel=["']?icon["']?[^>]*>/g; let iconHref, iconSize = 0; do { match = re.exec(html); if (match) { let href = /href=(["'])([^'"]+)"*\1/.exec(match[0]); if (href) { href = href[2]; } const sizes = /sizes=["']?(\d+)/.exec(match[0]); if (sizes) { const size = +sizes[1]; if (size && size > iconSize && size <= MAX_SIZE) { iconHref = href; iconSize = size; } } else if (!iconHref) { iconHref = href; } } } while (match); if (/\.(png|jpg|svg|gif|ico)/.test(iconHref)) { if (iconHref.indexOf('://') > 0) { return iconHref; } else { if (!iconHref.startsWith('/')) { iconHref = '/' + iconHref; } return 'http://' + domain + iconHref; } } } function pipeResponse(res, srvRes) { res.writeHead(200, {'Content-Type': 'image/x-icon', 'Access-Control-Allow-Origin': '*'}); srvRes.pipe(res, {end: true}); } function returnError(res, err) { res.writeHead(404, {'Content-Type': 'text/plain'}); return res.end(err); } module.exports = faviconApp;
JavaScript
0.999999
@@ -4260,32 +4260,134 @@ ;%0A %7D%0A + if (iconHref.startsWith('//')) %7B%0A return 'http:' + iconHref;%0A %7D%0A retu
3619836fafb18ec388cfad94799028b3a0359251
Update wegas-app/src/main/webapp/wegas-app/js/plugin/wegas-surveylistener.js
wegas-app/src/main/webapp/wegas-app/js/plugin/wegas-surveylistener.js
wegas-app/src/main/webapp/wegas-app/js/plugin/wegas-surveylistener.js
/* * Wegas * http://wegas.albasim.ch * * Copyright (c) 2013-2020 School of Business and Engineering Vaud, Comem, MEI * Licensed under the MIT License */ /** * @fileOverview * @author Jarle Hulaas */ YUI.add('wegas-surveylistener', function(Y) { "use strict"; var SurveyListener, Plugin = Y.Plugin; SurveyListener = Y.Base.create("wegas-surveylistener", Plugin.Base, [], { initializer: function() { this.handlers = []; // Mapping of survey descr id -> survey inst update handler. this.knownSurveys = {}; this.currentSurvey = null; // Get updates about any surveys included dynamically in the game: this.handlers.push(Y.Wegas.Facade.Variable.after("updatedDescriptor", this.onUpdatedDescriptor, this)); this.handlers.push(Y.Wegas.Facade.Variable.after("added", this.onUpdatedDescriptor, this)); this.handlers.push(Y.Wegas.Facade.Variable.after("delete", this.onDeletedDescriptor, this)); // Get updates about all existing surveys: Y.Array.each(Y.Wegas.Facade.Variable.cache.findAll("@class", "SurveyDescriptor"), this.registerSurvey, this); // Once host app is rendered, check if we should display a survey: this.afterHostEvent("render", this.checkSurveys); }, onUpdatedDescriptor: function(e) { var entity = e.entity; if (entity.get("@class") === "SurveyDescriptor") { this.registerSurvey(entity); } }, onDeletedDescriptor: function(e) { var entity = e.entity; if (entity.get("@class") === "SurveyDescriptor") { this.deregisterSurvey(entity); } }, // Check if we should display one of the known surveys: checkSurveys: function() { if (!this.currentSurvey) { for (var id in this.knownSurveys) { var inst = Y.Wegas.Facade.Variable.cache.findById(id).getInstance(); if (inst.get("active") && inst.get("requested") && inst.get("validated") === false) { this.showSurvey(inst); return; } } } }, // Register a survey descriptor in order to monitor updates to its instance registerSurvey: function(sd) { var descrId = sd.get("id"), instId = sd.getInstance().get("id"); if (this.knownSurveys[descrId]) { // Updates for an already known descriptor: this.knownSurveys[descrId].detach(); } this.knownSurveys[descrId] = Y.Wegas.Facade.Instance.after(instId + ":updatedInstance", this.onUpdatedInstance, this); }, deregisterSurvey: function(sd) { var descrId = sd.get("id"), instId = sd.getInstance().get("id"); if (this.currentSurvey && this.currentSurvey.get("id") === instId) { this.retireSurvey(); } if (this.knownSurveys[descrId]) { this.knownSurveys[descrId].detach(); delete this.knownSurveys[descrId]; } }, onUpdatedInstance: function(e) { var entity = e.entity; if (entity.get("closed")) { if (this.currentSurvey && this.currentSurvey.get("id") === entity.get("id")) { this.retireSurvey(); this.checkSurveys(); } } else if (entity.get("validated")) { // do nothing } else if (entity.get("started")) { // do nothing } else if (entity.get("requested")) { this.showSurvey(entity); } }, destructor: function() { var id; for (id in this.handlers) { this.handlers[id].detach(); } for (id in this.knownSurveys){ this.knownSurveys[id].detach(); } this.retireSurvey(); }, // Removes the current survey from the screen. retireSurvey: function() { if (this.currentSurvey) { var container = Y.one(".wegas-playerview .wegas-pageloader-content").removeClass("wegas-survey-ontop"); container.one(".wegas-survey-overlay").remove(true); this.currentSurvey = null; if (this.currentWidget && !this.currentWidget.get("destroyed")) { this.currentWidget.destroy(); } this.currentWidget = null; } }, // Displays the given survey which has been "requested" showSurvey: function(inst) { var ctx = this; Y.use(["wegas-survey-widgets", "wegas-popuplistener"], function(Y) { if (ctx.currentSurvey) { // Ignore this survey, since there's already another one being displayed. Y.log("Survey request ignored, another one is already active"); return; } if (inst.get("active") && inst.get("validated") === false) { ctx.currentSurvey = inst; var cfg, container, wrapper; container = Y.one(".wegas-playerview .wegas-pageloader-content").addClass("wegas-survey-ontop"); container.insert('<div class="wegas-survey-overlay wegas-survey-page"></div>', 0); wrapper = container.one(".wegas-survey-overlay"); cfg = { survey: { "@class": "Script", "content": "Variable.find(gameModel, \"" + ctx.currentSurvey.getDescriptor().get("name") + "\");" }, displayCloseButton: true, oneQuestionPerPage: true }; ctx.currentWidget = new Y.Wegas.SurveyWidget(cfg).render(wrapper); // For displaying error messages in the survey: ctx.currentWidget.plug(Plugin.PopupListener); } }); } }, { NS: "surveylistener", ATTRS: { } }); Plugin.SurveyListener = SurveyListener; });
JavaScript
0
@@ -557,16 +557,24 @@ nSurveys +Handlers = %7B%7D;%0A
b0f926c31d0cda945a26d32b47ba6442261d49d1
simplify code
lib/collection.js
lib/collection.js
var EventEmitter = require('events').EventEmitter; var Collection = function (monk, name) { var self = this; self.monk = monk; self.name = name; self.connected = false; self._colInstance = null; self.monk._db(function (db) { self._colInstance = db.collection(self.name); self.connected = true; self.emit('connected'); }); } Collection.prototype = Object.create(EventEmitter.prototype); Collection.prototype._col = function (cb) { var self = this; if (self.connected) { cb(self._colInstance); } else { self.once('connected', function () { cb(self._colInstance); }); } }; Collection.prototype._cb = function (cb) { var self = this; return cb || function (err) { if (err) { self.emit('error', err); } }; }; Collection.prototype.id = function (hexString) { return this.monk.id(hexString); } Collection.prototype.findById = function (id, cb) { this.findOne({ _id: this.id(id) }, cb); } Collection.prototype.findOne = function (query, options, cb) { if (typeof options === 'function') { cb = options; options = {}; } cb = this._cb(cb); options.limit = 1; this.find(query, options, function (err, docs) { cb(err, ((docs || []).length > 0 ? docs[0] : null)); }); } Collection.prototype.find = function (query, options, cb) { var self = this; if (typeof options === 'function') { cb = options; options = {}; } cb = self._cb(cb); self._col(function (col) { col.find(query, options).toArray(cb); }); }; Collection.prototype.insert = function (obj, cb) { var self = this; cb = self._cb(cb); self._col(function (col) { col.insert(obj, { safe: true }, function (err, docs) { if (err) { cb(err); } else { if (Array.isArray(obj)) { cb(null, docs); } else { cb(null, docs[0] || null); } } }); }); }; module.exports = exports = Collection;
JavaScript
0.000116
@@ -770,24 +770,440 @@ %7D%0A %7D;%0A%7D;%0A%0A +Collection.prototype._opts = function (opts) %7B%0A%0A opts = opts %7C%7C %7B%7D;%0A%0A if (!('safe' in opts)) %7B%0A opts.safe = true;%0A %7D%0A%0A return opts;%0A%7D;%0A%0ACollection.prototype._args = function (opts, cb, fn) %7B%0A%0A if (typeof opts === 'function') %7B%0A cb = this._cb(opts);%0A opts = this._opts(%7B%7D);%0A %7D else %7B%0A cb = this._cb(cb);%0A opts = this._opts(opts);%0A %7D%0A%0A this._col(function (col) %7B%0A fn(col, opts, cb);%0A %7D);%0A%7D%0A%0A Collection.p @@ -1416,35 +1416,32 @@ tion (query, opt -ion s, cb) %7B%0A%0A if ( @@ -1437,208 +1437,188 @@ ) %7B%0A -%0A -if (typeof options === 'function') %7B%0A cb = options;%0A options = %7B%7D;%0A %7D%0A%0A cb = this._cb(cb);%0A options.limit = 1;%0A%0A this.find(query, options, function (err, docs) %7B%0A cb(err, ((docs %7C%7C %5B%5D) +this._args(opts, cb, function (col, opts, cb) %7B%0A col.find(query, opts).limit(1).toArray(function (err, docs) %7B%0A if (err) %7B%0A cb(err);%0A %7D else %7B%0A cb(docs .len @@ -1642,16 +1642,31 @@ : null) +;%0A %7D%0A %7D );%0A %7D); @@ -1658,33 +1658,32 @@ %7D%0A %7D);%0A %7D);%0A -%0A %7D%0A%0ACollection.pr @@ -1717,19 +1717,16 @@ ery, opt -ion s, cb) %7B @@ -1730,156 +1730,54 @@ ) %7B%0A -%0A -var self = this;%0A%0A if (typeof options === 'function') %7B%0A cb = options;%0A options = %7B%7D;%0A %7D%0A%0A cb = self._cb(cb);%0A%0A self._col(function (col +this._args(opts, cb, function (col, opts, cb ) %7B%0A @@ -1799,19 +1799,16 @@ ery, opt -ion s).toArr @@ -1817,25 +1817,24 @@ (cb);%0A %7D);%0A -%0A %7D;%0A%0ACollecti @@ -1873,70 +1873,44 @@ obj, + opts, cb) %7B%0A -%0A -var self = this;%0A%0A cb = self._cb(cb);%0A%0A self._col( +this._args(opts, cb, func @@ -1910,32 +1910,42 @@ b, function (col +, opts, cb ) %7B%0A col.inse @@ -1956,22 +1956,12 @@ bj, -%7B safe: true %7D +opts , fu @@ -2176,21 +2176,189 @@ ;%0A %7D);%0A -%0A %7D;%0A%0A +Collection.prototype.update = function (search, update, opts, cb) %7B%0A this._args(opts, cb, function (col, opts, cb) %7B%0A col.update(search, update, opts, cb);%0A %7D);%0A%7D%0A%0A module.e
23603840bb4ff60bb5637ccd90f12f971d8a398c
Update BoundsArraySet_Pointwise.js
CNN/Conv/BoundsArraySet/BoundsArraySet_Pointwise.js
CNN/Conv/BoundsArraySet/BoundsArraySet_Pointwise.js
export { Pointwise }; import * as FloatValue from "../../Unpacker/FloatValue.js"; import * as ValueDesc from "../../Unpacker/ValueDesc.js"; import * as Weights from "../../Unpacker/Weights.js"; import { ConvBiasActivation } from "./BoundsArraySet_ConvBiasActivation.js"; import { ChannelPartInfo, FiltersBiasesPartInfo } from "../Pointwise/Pointwise_ChannelPartInfo.js"; /** * The element value bounds for pointwise convolution-bias-activation. * * Only outputChannelCount0 is used. The outputChannelCount1 always undefined. * * @see ConvBiasActivation */ class Pointwise extends ConvBiasActivation { /** */ constructor( inputs, outputChannelCount0 ) { super( inputs, outputChannelCount0 ); } /** * Set this.bPassThrough[] according to inChannelPartInfoArray. * * @param {Pointwise.FiltersBiasesPartInfo[]} aFiltersBiasesPartInfoArray * The input channel range array which describe lower/higher half channels index range. */ set_bPassThrough_all_byChannelPartInfoArray( aFiltersBiasesPartInfoArray ) { let outChannelBegin = 0, outChannelEnd = 0; // [ outChannelBegin, outChannelEnd ) are output channels of the current FiltersBiasesPart. FiltersBiasesPartIndexLoop: for ( let aFiltersBiasesPartIndex = 0; aFiltersBiasesPartIndex < aFiltersBiasesPartInfoArray.length; ++aFiltersBiasesPartIndex ) { let aFiltersBiasesPartInfo = aFiltersBiasesPartInfoArray[ aFiltersBiasesPartIndex ]; let inChannelPartInfoArray = aFiltersBiasesPartInfo.aChannelPartInfoArray; outChannelBegin = outChannelEnd; // Begin from the ending of the previous FiltersBiasesPart. { let outChannel = outChannelBegin; InChannelPartIndexLoop: for ( let inChannelPartIndex = 0; inChannelPartIndex < inChannelPartInfoArray.length; ++inChannelPartIndex ) { let inChannelPartInfo = inChannelPartInfoArray[ inChannelPartIndex ]; for ( let outChannelSub = 0; outChannelSub < inChannelPartInfo.outputChannelCount; ++outChannelSub, ++outChannel ) { if ( outChannel >= this.outputChannelCount ) break InChannelPartIndexLoop; // Never exceeds the total output channel count. this.bPassThrough[ outChannel ] = inChannelPartInfo.bPassThrough; } // outChannelSub, outChannel } // inChannelPartIndex outChannelEnd = outChannel; // Record the ending output channel index of the current FiltersBiasesPart. } } // aFiltersBiasesPartIndex } }
JavaScript
0
@@ -628,33 +628,33 @@ nstructor( input -s +0 , outputChannelC @@ -679,17 +679,17 @@ r( input -s +0 , output
2767eb7caac82b306159f685ee3700e3407b7e15
Change grid amount
sketch.js
sketch.js
const WIDTH = 800; const HEIGHT = 600; const SPACING = 50; const RECT_SIZE_X = 25; const RECT_SIZE_Y = 5; var setup = function() { createCanvas(WIDTH, HEIGHT); background(0); fill(255); angleMode(DEGREES); stroke(255); strokeWeight(1); strokeCap(SQUARE); } var drawRectangle = (posX, posY, angle) => { push(); translate(posX, posY); rotate(angle); rect(-(RECT_SIZE_X/2), -(RECT_SIZE_Y/2), RECT_SIZE_X, RECT_SIZE_Y); pop(); } var draw = function() { translate(SPACING, SPACING); for (let x = 0; x < 5; x++) { for (let y = 0; y < 5; y++) { drawRectangle(x * SPACING, y * SPACING, 45); } } }
JavaScript
0
@@ -527,16 +527,17 @@ 0; x %3C +1 5; x++) @@ -562,17 +562,18 @@ 0; y %3C -5 +11 ; y++) %7B
f79129b2a6b4238c1e7f552d653c724bd509950e
Fix initial server page tag rendering bug.
lib/common/app.js
lib/common/app.js
define(['requestFilters', 'underscore', 'utils/template', 'utils/model', 'utils/document', 'backbone', 'base', 'bundler'], function (filter, _, template, model, doc, Backbone, Base, Bundler) { 'use strict'; var bundle = new Bundler(); var LazoApp = Base.extend({ isClient: false, isServer: false, defaultTitle: 'lazojs', prefetchCss: false, // if set to true then XHR will be used to prefetch css to help prevent FOUSC setData: function (key, val, ctx) { ctx._rootCtx.data[key] = val; return this; }, getData: function (key, ctx) { return ctx._rootCtx.data[key]; }, addRequestFilter: function (regex, func) { filter.add(regex, func); return this; }, addRoutes: function (routes) { LAZO.routes = LAZO.routes || {}; _.extend(LAZO.routes, routes); return this; }, navigate: function (ctx, routeName) { if (this.isClient) { if (routeName.match(/^(?:(ht|f)tp(s?)\:\/\/)?/)[0].length) { return window.location = routeName; } LAZO.router.navigate(routeName, { trigger: true }); } else { ctx._reply.redirect(routeName); } }, loadModel: function (modelName, options) { model.process(modelName, options, 'model'); return this; }, loadCollection: function (collectionName, options) { model.process(collectionName, options, 'collection'); return this; }, createModel: function (modelName, attributes, options) { model.create(modelName, attributes, options, 'model'); return this; }, createCollection: function (collectionName, attributes, options) { model.create(collectionName, attributes, options, 'collection'); return this; }, addTag: function (name, attributes, content) { doc.addTag(name, attributes, content); return this; }, addPageTag: function (ctx, name, attributes, content) { doc.addPageTag(ctx, this.isServer, name, attributes, content); return this; }, getPageTags: function (ctx) { return doc.getPageTags(ctx); }, setHtmlTag: function (val) { doc.setHtmlTag(val); return this; }, setBodyClass: function (val) { doc.setBodyClass(val); return this; }, // TODO: deprecated; remove once apps have been updated setTitle: function (title) { doc.setTitle(title); return this; }, setDefaultTitle: function (title) { this.defaultTitle = title; return this; }, registerTemplateEngine: function (engineDef, options) { template.loadTemplateEngine(engineDef, options); return this; }, getTemplateEngine: function (engineName) { return template.getTemplateEngine(engineName); }, getTemplateExt: function (engineName) { return template.getTemplateExt(engineName); }, getDefaultTemplateEngine: function () { return template.getDefaultTemplateEngine(); }, getDefaultTemplateEngineName: function () { return template.getDefaultTemplateEngineName(); }, setDefaultTemplateEngine: function (engineName) { template.setDefaultTemplateEngine(engineName); }, getImport: function (relativePath) { return bundle.resolveImport(relativePath, 'application'); } }); _.extend(LazoApp.prototype, Backbone.Events); return LazoApp; });
JavaScript
0
@@ -2428,16 +2428,31 @@ Tags(ctx +, this.isServer );%0A
84c671aaa4d23ef5bca7f6bf09d58dfe9d88a3e6
Revert "Revert "Fix for spaces in strings""
lib/connection.js
lib/connection.js
'use strict'; var Query_ = require('./binding').Query; var Options_ = require('./binding').Options; var Connection_ = require('./binding').Connection; var noop = require('./noop'); var ResultSet = require('./resultset'); var ReadStream = require('./read-stream'); module.exports = Connection; var conn = Connection.prototype; function Connection(host) { if (!(this instanceof Connection)) { return new Connection(host); } this._connected = false; this._options = Options_(); this._conn = new Connection_(this._options); this.set('implementationName', 'node-zoom2'); var parsed = this._parseHost(host || ''); parsed.database && this.set('databaseName', parsed.database); this._host = parsed.host; this._port = parsed.port | 0; } conn.set = function (key, val) { this._options.set(key, val); return this; }; conn.get = function (key) { return this._options.get(key); }; conn.query = function (type, queryString) { if (arguments.length < 2) { queryString = type; type = 'prefix'; } var clone = Object.create(this); clone._query = Query_(); if (!clone._query[type]) { throw new Error('Unknown query type'); } clone._query[type](queryString); return clone; }; conn.updateRecord = function(options, cb) { if (!options) { throw new Error('No package options given'); } var packageOpts = Options_(); Object.keys(options) .forEach(function(k) { packageOpts.set(k, options[k]) }); cb || (cb = noop); this.connect(function (err) { if (err) { cb(err); return; } this._conn.update(packageOpts, cb); }.bind(this)); } conn.sort = function () { if (!this._query) { throw new Error('Query not found'); } this._query.sortBy.apply(this._query, arguments); return this; }; conn.connect = function (cb) { cb || (cb = noop); if (this._connected) { cb(null); } else { this._conn.connect(this._host, this._port, function (err) { this._connected = !err; cb(err); }.bind(this)); } return this; }; conn.createReadStream = function (options) { if (!this._query) { throw new Error('Query not found'); } return new ReadStream(this, options); }; conn.search = function (cb) { if (!this._query) { throw new Error('Query not found'); } cb || (cb = noop); this.connect(function (err) { if (err) { cb(err); return; } this._conn.search(this._query, function (err, resultset) { if (err) { cb(err); return; } cb(null, new ResultSet(resultset)); }.bind(this)); }.bind(this)); return this; }; conn._parseHost = function (host) { var match = host.match(/^(.+?)(?::(\d+))?(?:\/(.+))?$/); return match ? { host: match[1], port: match[2], database: match[3] } : {}; };
JavaScript
0.000003
@@ -1023,16 +1023,196 @@ x';%0A %7D%0A + %0A // Fix for spaces in query string%0A var queryArray = queryString.split(' ');%0A queryString = %5BqueryArray.slice(0,2).join(' '), queryArray.slice(2).join('%5Cu00A0')%5D.join(' ');%0A%0A var cl @@ -1265,17 +1265,16 @@ ery_();%0A -%0A if (!c @@ -2995,12 +2995,176 @@ %7D : %7B%7D;%0A%7D;%0A +%0Afunction unicodeEscape(str) %7B%0A return str.replace(/%5B%5Cs%5CS%5D/g, function (escape) %7B%0A return '%5C%5Cu' + ('0000' + escape.charCodeAt().toString(16)).slice(-4);%0A %7D);%0A%7D
4bc1ab6a97ded700aeaa2424f7e6286d92e79d50
fix validation error in oauth tests when prefilled email is not cleared
tests/functional/oauth_sign_in.js
tests/functional/oauth_sign_in.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ define([ 'intern', 'intern!object', 'intern/chai!assert', 'require', 'intern/node_modules/dojo/node!xmlhttprequest', 'app/bower_components/fxa-js-client/fxa-client', 'tests/lib/restmail', 'tests/lib/helpers' ], function (intern, registerSuite, assert, require, nodeXMLHttpRequest, FxaClient, restmail, TestHelpers) { 'use strict'; var config = intern.config; var OAUTH_APP = config.fxaOauthApp; var EMAIL_SERVER_ROOT = config.fxaEmailRoot; var PAGE_URL = config.fxaContentRoot + 'signin'; var PASSWORD = 'password'; var TOO_YOUNG_YEAR = new Date().getFullYear() - 13; var user; var email; registerSuite({ name: 'oauth sign in', setup: function () { }, beforeEach: function () { email = TestHelpers.createEmail(); user = TestHelpers.emailToUser(email); var self = this; return self.get('remote') .get(require.toUrl(PAGE_URL)) .waitForElementById('fxa-signin-header') .safeEval('sessionStorage.clear(); localStorage.clear();') // sign up, do not verify steps .get(require.toUrl(OAUTH_APP)) .waitForVisibleByCssSelector('#splash') .elementByCssSelector('#splash .signup') .click() .end() .waitForVisibleByCssSelector('#fxa-signup-header') .elementByCssSelector('form input.email') .click() .type(email) .end() .elementByCssSelector('form input.password') .click() .type(PASSWORD) .end() .elementByCssSelector('#fxa-age-year') .click() .end() .elementById('fxa-' + (TOO_YOUNG_YEAR - 1)) .buttonDown() .buttonUp() .click() .end() .elementByCssSelector('button[type="submit"]') .click() .end() .waitForVisibleByCssSelector('#fxa-confirm-header') .end(); }, 'verified': function () { var self = this; // verify account return restmail(EMAIL_SERVER_ROOT + '/mail/' + user) .then(function (emails) { return self.get('remote') .get(require.toUrl(emails[0].headers['x-link'])) .waitForVisibleByCssSelector('#fxa-sign-up-complete-header') // sign in with a verified account .get(require.toUrl(OAUTH_APP)) .waitForVisibleByCssSelector('#splash') .elementByCssSelector('#splash .signin') .click() .end() .waitForVisibleByCssSelector('#fxa-signin-header') .elementByCssSelector('#fxa-signin-header') .text() .then(function (text) { assert.ok(text.indexOf('Sign in to') > -1, 'Sign Up page should have a service header'); }) .end() .url() .then(function (url) { assert.ok(url.indexOf('oauth/signin?') > -1); assert.ok(url.indexOf('client_id=') > -1); assert.ok(url.indexOf('redirect_uri=') > -1); assert.ok(url.indexOf('state=') > -1); }) .end() .elementByCssSelector('form input.email') .click() .type(email) .end() .elementByCssSelector('form input.password') .click() .type(PASSWORD) .end() .elementByCssSelector('button[type="submit"]') .click() .end() .waitForVisibleByCssSelector('#loggedin') .url() .then(function (url) { // redirected back to the App assert.ok(url.indexOf(OAUTH_APP) > -1); }) .end() .elementByCssSelector('#loggedin') .text() .then(function (text) { // confirm logged in email assert.ok(text.indexOf(email) > -1); }) .end() .elementByCssSelector('#logout') .click() .end() .waitForVisibleByCssSelector('.signup') .elementByCssSelector('#loggedin') .text() .then(function (text) { // confirm logged out assert.ok(text.length === 0); }) .end(); }); }, 'unverified': function () { var self = this; return this.get('remote') // Step 2: Try to sign in, unverified .get(require.toUrl(OAUTH_APP)) .waitForVisibleByCssSelector('#splash') .elementByCssSelector('#splash .signin') .click() .end() .waitForVisibleByCssSelector('#fxa-signin-header') .elementByCssSelector('#fxa-signin-header') .text() .then(function (text) { assert.ok(text.indexOf('Sign in to') > -1, 'Sign In page should have a service header'); }) .end() .url() .then(function (url) { assert.ok(url.indexOf('oauth/signin?') > -1); assert.ok(url.indexOf('client_id=') > -1); assert.ok(url.indexOf('redirect_uri=') > -1); assert.ok(url.indexOf('state=') > -1); }) .end() .elementByCssSelector('form input.email') .click() .type(email) .end() .elementByCssSelector('form input.password') .click() .type(PASSWORD) .end() .elementByCssSelector('button[type="submit"]') .click() .end() .waitForVisibleByCssSelector('#fxa-confirm-header') .then(function () { return restmail(EMAIL_SERVER_ROOT + '/mail/' + user) .then(function (emails) { var verifyUrl = emails[0].headers['x-link']; return self.get('remote') .get(require.toUrl(verifyUrl)); }); }) .waitForVisibleByCssSelector('#fxa-sign-up-complete-header') .elementByCssSelector('#redirectTo') .click() .end() .waitForVisibleByCssSelector('#loggedin') .url() .then(function (url) { // redirected back to the App assert.ok(url.indexOf(OAUTH_APP) > -1); }) .end() .elementByCssSelector('#loggedin') .text() .then(function (text) { // confirm logged in email assert.ok(text.indexOf(email) > -1); }) .end() .elementByCssSelector('#logout') .click() .end() .waitForVisibleByCssSelector('.signup') .elementByCssSelector('#loggedin') .text() .then(function (text) { // confirm logged out assert.ok(text.length === 0); }) .end(); } }); });
JavaScript
0.000001
@@ -1540,32 +1540,49 @@ m input.email')%0A + .clear()%0A .click() @@ -3363,32 +3363,53 @@ m input.email')%0A + .clear()%0A .cli @@ -5450,32 +5450,49 @@ m input.email')%0A + .clear()%0A .click()
21c771d14a9da82efec266b54ad2baec453dd781
remove dead code
lib/controller.js
lib/controller.js
/*global templatePath */ var fs = require('fs-extra'); module.exports = { controllerPath : 'both/controllers/', contrTemplates: templatePath + 'controller/', // Public: Creates a controller file and any type of controller needed. // By default if no options are passed in it will create all router and // CRUD controllers. Routes are appended to `/both/routes.js` // // resName - The {String} name of the resource passed in from command line // options - The options generated from a Commander command entry. // // Create all controllers passed in init: function(resName, opts) { // TODO ensure resName is always snake case this.contrFile = this.controllerPath + resName + '.js'; // ensure `both/controllers` exists fs.mkdirsSync(this.controllerPath); this.createBaseController(); // append all controllers to file this.appendController('index'); // if opts, only append those controllers // create resource controller file // append routes to routes.js }, appendController: function(action) { fs.appendFileSync(this.contrFile, action); }, // Private: copy app base controller to project if it doesn't exist createBaseController: function() { if (fs.existsSync(this.controllerPath + 'app.js')) return; fs.copySync(this.contrTemplates+'app.js', this.controllerPath+'app.js'); console.log(' Created '+ this.controllerPath +'app.js'); } };
JavaScript
0
@@ -727,89 +727,8 @@ ';%0A%0A - // ensure %60both/controllers%60 exists%0A fs.mkdirsSync(this.controllerPath);%0A%0A
cae745eee63931ce361e1f235c6c135ec973f8cb
Fix for textbox view bridge causing recursion
src/Presenters/Controls/Text/TextBox/TextBoxViewBridge.js
src/Presenters/Controls/Text/TextBox/TextBoxViewBridge.js
var bridge = function (presenterPath) { window.rhubarb.viewBridgeClasses.HtmlViewBridge.apply(this, arguments); }; bridge.prototype = new window.rhubarb.viewBridgeClasses.HtmlViewBridge(); bridge.prototype.constructor = bridge; bridge.spawn = function (spawnData, index, parentPresenterPath) { var textBox = document.createElement("INPUT"); textBox.setAttribute("type", spawnData.type); textBox.setAttribute("size", spawnData.size); if (spawnData.maxLength) { textBox.setAttribute("maxlength", spawnData.maxLength); } window.rhubarb.viewBridgeClasses.HtmlViewBridge.applyStandardAttributesToSpawnedElement(textBox, spawnData, index, parentPresenterPath); return textBox; }; bridge.prototype.onKeyPress = function(event){ if (this.onKeyPress){ this.onKeyPress(event); } }; bridge.prototype.attachDomChangeEventHandler = function (triggerChangeEvent) { window.rhubarb.viewBridgeClasses.HtmlViewBridge.prototype.attachDomChangeEventHandler.apply(this,arguments); var self = this; if (!this.viewNode.addEventListener) { this.viewNode.attachEvent("onkeypress", self.onKeyPress.bind(self)); } else { // Be interested in a changed event if there is one. this.viewNode.addEventListener('keypress', self.onKeyPress.bind(self), false); } }; window.rhubarb.viewBridgeClasses.TextBoxViewBridge = bridge;
JavaScript
0
@@ -729,26 +729,26 @@ ototype. -onK +k eyPress +ed = funct @@ -1134,34 +1134,34 @@ ress%22, self. -onK +k eyPress +ed .bind(self)) @@ -1296,26 +1296,26 @@ ', self. -onK +k eyPress +ed .bind(se
9fa7e603a2c1b67ead8ce947a3ecf85f2c2cd534
Remove unnecessary import
lib/definition.js
lib/definition.js
// Copyright (c) 2015, salesforce.com, inc. - All rights reserved // Licensed under BSD 3-Clause - https://opensource.org/licenses/BSD-3-Clause const { constant, identity } = require('core.lambda') const Either = require('data.either') const Immutable = require('immutable-ext') const { isString } = require('lodash') const { ALIAS_PATTERN } = require('./constants') const { allMatches } = require('./util') const transform = options => { /** * Transform a definition by merging globals, resolving imports, * resolving aliases, etc */ const go = def => Either .fromNullable(def) .chain(validate) .map(options.get('preprocess', identity)) .chain(validateProps(validateProp)) .map(includeRawValue) .map(mergeGlobal) .chain(validateProps(validatePropKeys)) .chain(transformImports) .map(mergeImports) .map(formatAliases) .chain(def => options.get('resolveAliases') === false ? Either.of(def) : Either.try(resolveNestedAliases)(def) ) .chain(def => options.get('resolveAliases') === false ? Either.of(def) : Either.try(resolveAliases)(def) ) .map(addPropName) .chain(transformValues) /** * Merge the "global" object into each prop */ const mergeGlobal = def => def .update('props', props => props.map((v, k) => def.get('global').merge(v) ) ) .delete('global') /** * */ const includeRawValue = def => options.get('includeRawValue') === true ? def.update('props', props => props.map(prop => prop.set('rawValue', prop.get('value')) ) ) : def /** * Validate that a prop is structured correctly */ const validateProp = (prop, propName) => Either .of(prop) .chain(prop => Immutable.Map.isMap(prop) ? Either.Right(prop) : Either.Left(`Property "${propName}" must be an object`) ) /** * Validate that a prop has all required keys */ const validatePropKeys = (prop, propName) => Immutable.List .of('value', 'type', 'category') .traverse(Either.of, propKey => prop.has(propKey) ? Either.Right() : Either.Left(`Property "${propName}" contained no "${propKey}" key`) ) .map(constant(prop)) /** * Validate that all props have required keys */ const validateProps = fn => def => def .get('props') .traverse(Either.of, fn) .map(constant(def)) /** * Validate that all props have required keys */ const formatAliases = def => def .update('aliases', aliases => aliases.map(alias => Immutable.Map.isMap(alias) ? alias : Immutable.Map({ value: alias }) ) ) /** * Validate that a definition is correctly structured */ const validate = def => Either .of(def) .chain(def => Immutable.Map.isMap(def.get('props')) ? Either.Right(def) : Either.Left('"props" key must be an object') ) .chain(def => Immutable.Map.isMap(def.get('aliases')) ? Either.Right(def) : Either.Left('"aliases" key must be an object') ) .chain(def => Immutable.Map.isMap(def.get('global')) ? Either.Right(def) : Either.Left('"global" key must be an object') ) /** * Map each import over go() */ const transformImports = def => def .get('imports') .traverse(Either.of, go) .map(imports => def.set('imports', imports) ) /** * Merge aliases/props from each import into the provided def */ const mergeImports = def => def .update('aliases', aliases => def.get('imports').reduce((aliases, i) => aliases.merge(i.get('aliases')) , aliases) ) .update('props', props => def.get('imports').reduce((props, i) => props.merge(i.get('props')) , props) ) .delete('imports') /** * Resolve aliases that refer to other aliases */ const resolveNestedAliases = def => def .update('aliases', aliases => { const resolve = value => value.update('value', v => allMatches(v, ALIAS_PATTERN).reduce((v, [alias, key]) => aliases.has(key) ? v.replace(alias, resolve(aliases.get(key)).get('value')) : v , v) ) return aliases.map(resolve) }) /** * Resolve aliases inside prop values */ const resolveAliases = def => def .update('props', props => { const aliases = def.get('aliases', Immutable.Map()) return props.map((value, key) => value.update('value', v => allMatches(v, ALIAS_PATTERN).reduce((v, [alias, key]) => { if (!aliases.has(key)) throw new Error(`Alias "${key}" not found`) return v.replace(alias, aliases.getIn([key, 'value'])) }, v) ) ) }) /** * */ const transformValue = transform => prop => transform.get('predicate')(prop) ? Either .try(transform.get('transform'))(prop) .map(value => prop.set('value', value)) : Either.Right(prop) /** * transform each prop value using the provided value transforms */ const transformValues = def => def .get('props') .traverse(Either.of, prop => options.get('transforms', Immutable.List()).reduce((p, t) => p.chain(transformValue(t)) , Either.of(prop)) ) .map(props => def.set('props', props) ) /** * Add a "name" key to each prop */ const addPropName = def => def .update('props', props => props.map((prop, name) => prop.set('name', name)) ) return go } module.exports = { transform: (def, options = Immutable.Map()) => transform(options)(def) // Cleanup after recursion .map(def => def .delete('imports') .update('props', props => options.get('includeMeta') ? props : props.map(prop => prop.delete('meta')) ) ) }
JavaScript
0.000011
@@ -278,50 +278,8 @@ ')%0A%0A -const %7B%0A isString%0A%7D = require('lodash')%0A%0A cons
2a76e3faad166e0a9329894792f26466742846e1
rename 'marker' to 'name'
src/lib/timeline.js
src/lib/timeline.js
import mitt from 'mitt'; export default function tl(initialTimeline) { const emitter = mitt(); let timeline = initialTimeline || []; return { add(time, marker, callback = false) { timeline.push({ time, marker, callback, hasBeenCalled: false }); timeline.sort((a, b) => a.time - b.time); }, set(newTimeline) { timeline = newTimeline; }, tick(timestamp) { const time = timestamp || 0; for (let i = 0; i < timeline.length; i++) { const timelineEvent = timeline[i]; if (time > timelineEvent.time && !timelineEvent.hasBeenCalled) { this.emit(timelineEvent); } } }, on(marker, callback) { return emitter.on(marker, callback); }, emit(timelineEvent) { // mark the event as called timelineEvent.hasBeenCalled = true; // emit the marker as an event emitter.emit(timelineEvent.marker); // callback if one exists if (timelineEvent.callback) { timelineEvent.callback(); } }, }; }
JavaScript
0.999753
@@ -153,30 +153,28 @@ add(time, -marker +name , callback = @@ -211,22 +211,20 @@ %7B time, -marker +name , callba @@ -663,22 +663,20 @@ %0A on( -marker +name , callba @@ -705,22 +705,20 @@ tter.on( -marker +name , callba @@ -855,21 +855,8 @@ the -marker as an even @@ -894,14 +894,12 @@ ent. -marker +name );%0A%0A
0b7859af149a65b7c0af8e187258c7a687b3d689
redefine ColorContrastCalc.prototype.contrastRatio as an alias of ColorContrastCalc.contrastRatio
lib/color-contrast-calc.js
lib/color-contrast-calc.js
"use strict"; class ColorContrastCalc { static tristimulusValue(primaryColor, base = 255) { const s = primaryColor / base; if (s <= 0.03928) { return s / 12.92; } else { return Math.pow((s + 0.055) / 1.055, 2.4); } } static relativeLuminance(rgb = [255, 255, 255]) { const [r, g, b] = rgb.map(c => this.tristimulusValue(c)); return r * 0.2126 + g * 0.7152 + b * 0.0722; } contrastRatio(foreground, background) { const [l1, l2] = [foreground, background] .map(c => this.constructor.relativeLuminance(c)) .sort((f, b) => b - f); return (l1 + 0.05) / (l2 + 0.05); } } module.exports.ColorContrastCalc = ColorContrastCalc;
JavaScript
0.000001
@@ -414,16 +414,23 @@ %0A %7D%0A%0A +static contrast @@ -536,20 +536,8 @@ his. -constructor. rela @@ -629,16 +629,130 @@ 05);%0A %7D +%0A%0A contrastRatio(foreground, background) %7B%0A return this.constructor.contrastRatio(foreground, background);%0A %7D %0A%7D%0A%0Amodu
aeaa863558f15de40e91c6207a689925fb43585f
Fix class name issue
src/SelectedOption.js
src/SelectedOption.js
import React, { Component } from 'react' export default ({ option, selectedLabel }) => { return ( <span class='powerselect__trigger-label'> { typeof selectedLabel === 'function' ? selectedLabel(option) : typeof selectedLabel === 'string' ? option[selectedLabel] : option } </span> ) }
JavaScript
0.000002
@@ -109,16 +109,20 @@ an class +Name ='powers
a74850c23873f3f6ac4033e1632262d43bf56689
Add email api url requirement
server/configuration/environment_configuration.js
server/configuration/environment_configuration.js
"use strict"; var config = require("12factor-config"); var appConfig = config({ apiUrl: { env: "AGFAPHD_WEBAPP_API_URL", type: "string", default: "http://localhost:8089" }, emailApiKey: { env: "AGFAPHD_WEBAPP_EMAIL_API_KEY", type: "string", required: true }, emailApiUrl: { env: "AGFAPHD_WEBAPP_EMAIL_API_URL", type: "string", default: "sandboxa92275a42f30470c860fda4a09140bf6.mailgun.org" }, emailFrom: { env: "AGFAPHD_WEBAPP_EMAIL_FROM", type: "string", default: "Debt Sentry <[email protected]>" }, revisionMapPath: { env: "AGFAPHD_WEBAPP_REVISION_MAP_PATH", type: "string", default: "../public/default_map.json" }, serverPort: { env: "PORT", type: "integer", default: 5000 } }); module.exports = appConfig;
JavaScript
0.000001
@@ -372,70 +372,22 @@ -default: %22sandboxa92275a42f30470c860fda4a09140bf6.mailgun.org%22 +required: true %0A %7D
0ba6ea44e606936bb9720bba8397ba6685e00307
Use let instead of var
tests/integration/settled-test.js
tests/integration/settled-test.js
import Ember from 'ember'; import { later, run } from '@ember/runloop'; import Component from '@ember/component'; import { settled, setupContext, setupRenderingContext, teardownContext, teardownRenderingContext, } from 'ember-test-helpers'; import hasEmberVersion from 'ember-test-helpers/has-ember-version'; import { module, test, skip } from 'qunit'; import hbs from 'htmlbars-inline-precompile'; import Pretender from 'pretender'; import { fireEvent } from '../helpers/events'; import hasjQuery from '../helpers/has-jquery'; import ajax from '../helpers/ajax'; module('settled real-world scenarios', function(hooks) { if (!hasEmberVersion(2, 4)) { return; } hooks.beforeEach(async function() { await setupContext(this); await setupRenderingContext(this); let { owner } = this; owner.register( 'component:x-test-1', Component.extend({ internalValue: 'initial value', init() { this._super.apply(this, arguments); later( this, function() { this.set('internalValue', 'async value'); }, 10 ); }, }) ); owner.register('template:components/x-test-1', hbs`{{internalValue}}`); owner.register( 'component:x-test-2', Component.extend({ internalValue: 'initial value', click() { later( this, function() { this.set('internalValue', 'async value'); }, 10 ); }, }) ); owner.register('template:components/x-test-2', hbs`{{internalValue}}`); owner.register( 'component:x-test-3', Component.extend({ internalValue: '', click() { ajax('/whazzits').then(data => { var value = this.get('internalValue'); run(this, 'set', 'internalValue', value + data); }); }, }) ); owner.register('template:components/x-test-3', hbs`{{internalValue}}`); owner.register( 'component:x-test-4', Component.extend({ internalValue: '', click() { later(() => run(this, 'set', 'internalValue', 'Local Data!'), 10); ajax('/whazzits').then(data => { var value = this.get('internalValue'); run(this, 'set', 'internalValue', value + data); later(() => { ajax('/whazzits').then(data => { if (this.isDestroyed) { return; } var value = this.get('internalValue'); run(this, 'set', 'internalValue', value + data); }); }, 15); }); }, }) ); owner.register('template:components/x-test-4', hbs`{{internalValue}}`); owner.register( 'component:x-test-5', Component.extend({ internalValue: 'initial value', ready: false, isReady() { return this.get('ready'); }, init() { this._super.apply(this, arguments); // In Ember < 2.8 `registerWaiter` expected to be bound to // `Ember.Test` 😭 // // Once we have dropped support for < 2.8 we should swap this to // use: // // import { registerWaiter } from '@ember/test'; Ember.Test.registerWaiter(this, this.isReady); later(() => { this.setProperties({ internalValue: 'async value', ready: true, }); }, 25); }, willDestroy() { this._super.apply(this, arguments); // must be called with `Ember.Test` as context for Ember < 2.8 Ember.Test.unregisterWaiter(this, this.isReady); }, }) ); owner.register('template:components/x-test-5', hbs`{{internalValue}}`); this.server = new Pretender(function() { this.get( '/whazzits', function() { return [200, { 'Content-Type': 'text/plain' }, 'Remote Data!']; }, 25 ); }); }); hooks.afterEach(async function() { await settled(); this.server.shutdown(); await teardownRenderingContext(this); await teardownContext(this); }); test('it works when async exists in `init`', async function(assert) { await this.render(hbs`{{x-test-1}}`); await settled(); assert.equal(this.element.textContent, 'async value'); }); test('it works when async exists in an event/action', async function(assert) { await this.render(hbs`{{x-test-2}}`); assert.equal(this.element.textContent, 'initial value'); fireEvent(this.element.querySelector('div'), 'click'); await settled(); assert.equal(this.element.textContent, 'async value'); }); test('it waits for AJAX requests to finish', async function(assert) { await this.render(hbs`{{x-test-3}}`); fireEvent(this.element.querySelector('div'), 'click'); await settled(); assert.equal(this.element.textContent, 'Remote Data!'); }); test('it waits for interleaved AJAX and run loops to finish', async function(assert) { await this.render(hbs`{{x-test-4}}`); fireEvent(this.element.querySelector('div'), 'click'); await settled(); assert.equal(this.element.textContent, 'Local Data!Remote Data!Remote Data!'); }); test('it can wait only for AJAX', async function(assert) { await this.render(hbs`{{x-test-4}}`); fireEvent(this.element.querySelector('div'), 'click'); await settled({ waitForTimers: false }); assert.equal(this.element.textContent, 'Local Data!Remote Data!'); }); // in the wait utility we specific listen for artificial jQuery events // to start/stop waiting, but when using ember-fetch those events are not // emitted and instead test waiters are used // // therefore, this test is only valid when using jQuery.ajax (hasjQuery() ? test : skip)('it can wait only for timers', async function(assert) { await this.render(hbs`{{x-test-4}}`); fireEvent(this.element.querySelector('div'), 'click'); await settled({ waitForAJAX: false }); assert.equal(this.element.textContent, 'Local Data!'); }); test('it waits for Ember test waiters', async function(assert) { await this.render(hbs`{{x-test-5}}`); await settled({ waitForTimers: false }); assert.equal(this.element.textContent, 'async value'); }); });
JavaScript
0
@@ -1813,35 +1813,35 @@ %3E %7B%0A -var +let value = this.ge @@ -2285,35 +2285,35 @@ %3E %7B%0A -var +let value = this.ge @@ -2573,11 +2573,11 @@ -var +let val
ce735fc71cc0b5b8864141b067bef8d7364bfb13
remove logs
lib/downstream.js
lib/downstream.js
'use strict' const WsServer = require('websocket').server const http = require('http') const vstamp = require('vigour-stamp') const { ClocksyServer } = require('clocksy') const clocksy = new ClocksyServer() exports.properties = { downstream: true, port: { type: 'observable', noContext: true, on: { data () { console.log('FIRE FIRE FIRE') const hub = this.cParent() const val = this.compute() if (hub.downstream) { closeServer(hub.downstream) hub.downstream = null } if (val) { server(hub, val) } } } } } exports.on = { remove: { port () { if (this.hasOwnProperty('port')) { this.port.set(null) } } } } function closeServer (server) { const connections = server.connections for (var i in connections) { connections[i].close() } console.log('KILL') server._httpServer.close() } function server (hub, port) { let httpServer = http.createServer().listen(port) let server = hub.downstream = new WsServer({ httpServer: httpServer }) server._httpServer = httpServer server.on('request', (req) => { const connection = req.accept('hubs', req.origin) connection.on('message', (data) => { if (data.type === 'utf8') { try { let payload = JSON.parse(data.utf8Data) if (payload.type && payload.type === 'clock') { connection.send(JSON.stringify({ type: 'clock', data: clocksy.processRequest(payload.data) })) } } catch (e) { console.log('errror', e) } } }) connection.on('message', (data) => { var contextHub if (data.type === 'utf8') { let connectStamp try { const payload = JSON.parse(data.utf8Data) if (payload) { if (payload.type === 'clock') { return } if (payload.offset === void 0) { console.log('need dat offset!', payload) } // make a nicer threshold const offset = payload.offset && payload.offset > 10 || payload.offset < -10 ? payload.offset : 0 delete payload.offset if (payload.client) { const client = payload.client const id = client.id if (connection.client && connection.client.key === id) { console.log('allready have client -- RECONN') } if (connection.context && connection.context !== payload.client.context) { // if (!connection.client) error! // can have multiple clients / contexts -- for multi clients (one hub to other) console.log('old context remove client there!, when no clients remove the whole thing') } const ip = connection.remoteAddress let context = client.context if (context === void 0) { context = ip } const parsed = vstamp.parse(client.stamp) connectStamp = vstamp.create(parsed.type, parsed.src || id, parsed.val) // ------------------------------ if (context === false) { contextHub = hub } else { contextHub = hub.getContext(context) if (!contextHub) { contextHub = new hub.Constructor({ context: context }, connectStamp) } } // ------------------------------ contextHub.set({ clients: { [id]: { id: id, ip: ip } } }, connectStamp) const hClient = contextHub.clients[id] hClient.ip.stamp = vstamp.create('ip', contextHub.id) // no need to close vstamp.close(connectStamp) hClient.connection = connection connection.client = hClient connection.context = contextHub if (client.subscriptions) { for (let i in client.subscriptions) { contextHub.subscribe(client.subscriptions[i], void 0, void 0, connectStamp, contextHub.clients[id]) } } delete payload.client } if (!connection.context) { // or emit error on the hub // all error handling can then be listened to on top in the hub -- def best way throw new Error('no connection context -- need to put data in a queue -- seems smoeone is doing it wrong') } else { contextHub = connection.context // console.log('incoming --', JSON.stringify(payload, false, 2)) for (let stamp in payload) { let parsed = vstamp.parse(stamp) let s = vstamp.create(parsed.type, parsed.src, Number(parsed.val) + Number(offset)) contextHub.set(payload[stamp], s) vstamp.close(s) } } } else { console.log('WTF NO PAYLOAD? --> find this', payload) } } catch (e) { // of course this try catch makes everyhting slow.. // use node arg // emit all errors on hub root -- also for context console.log('some weird error on the server', e) console.log('incoming --- ', data.utf8Data, data) } } }) connection.on('close', () => { if (connection.client) { const stamp = vstamp.create('disconnect', connection.client.get('id', false).compute()) connection.client.remove(stamp) vstamp.close(stamp) } }) }) return server }
JavaScript
0.000001
@@ -363,16 +363,54 @@ FIRE')%0A + if (!this.parent.context) %7B%0A @@ -436,16 +436,18 @@ arent()%0A + @@ -477,24 +477,26 @@ e()%0A + if (hub.down @@ -501,24 +501,26 @@ wnstream) %7B%0A + cl @@ -555,16 +555,18 @@ + hub.down @@ -579,16 +579,18 @@ = null%0A + @@ -595,24 +595,26 @@ %7D%0A + if (val) %7B%0A @@ -608,24 +608,26 @@ if (val) %7B%0A + se @@ -641,16 +641,28 @@ b, val)%0A + %7D%0A
bea5aaa09bb893b290192a0871d31f3a82338918
Add basic popup
client/entry.js
client/entry.js
var bakerHoods = require('../data/neighborhoods/bakersfield.json'); function getCoords(coords) { return coords.map((coord) => { if (Array.isArray(coord[0])) { console.log(coord); } return { lat: coord[1], lng: coord[0] }; }); } var COLORS = ['#FF0000', '#00FF00']; global.initMap = () => { var center = { lat: 35.3733, lng: -119.0187 }; var map = new google.maps.Map(document.getElementById('map'), { center, zoom: 12, mapTypeId: google.maps.MapTypeId.ROADMAP, }); console.log(bakerHoods.length); bakerHoods.forEach((hood, index) => { var color = COLORS[index % 2]; return hood.geometry.coordinates.map((coords) => { // Construct the polygon. var bermudaTriangle = new google.maps.Polygon({ paths: getCoords(coords), strokeColor: color, strokeOpacity: 0.8, strokeWeight: 2, fillColor: color, fillOpacity: 0.35 }); bermudaTriangle.setMap(map); }); }); };
JavaScript
0.000001
@@ -283,16 +283,267 @@ F00'%5D;%0A%0A +function getCenter(coords) %7B%0A var latSum = 0;%0A var lngSum = 0;%0A%0A coords.forEach((coord) =%3E %7B%0A latSum += coord.lat;%0A lngSum += coord.lng;%0A %7D);%0A%0A return %7B lat: latSum / coords.length, lng: lngSum / coords.length %7D;%0A%7D%0A%0Avar lastWindow = null;%0A%0A global.i @@ -755,42 +755,8 @@ %7D); -%0A console.log(bakerHoods.length); %0A%0A @@ -925,31 +925,23 @@ var -bermudaTriangle +polygon = new g @@ -1149,34 +1149,377 @@ -bermudaTriangle.setMap(map +polygon.setMap(map);%0A%0A var center = getCenter(getCoords(coords));%0A var infowindow = new google.maps.InfoWindow(%7B%0A content: '%3Cdiv%3EHello world%3C/div%3E',%0A position: center,%0A %7D);%0A%0A polygon.addListener('click', function() %7B%0A if (lastWindow) %7B lastWindow.close(); %7D%0A infowindow.open(map);%0A lastWindow = infowindow;%0A %7D );%0A
dc3d41ab1b8a5c5d2a142b6cbdd056e3fc5cbfcb
Use raw XHR rather than $http to access progress events on upload
client/files.js
client/files.js
/* * @license Apache-2.0 * * 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. */ //goog.provide('filedrop.Files'); var filedrop = filedrop || {}; /** * Service for handling files. * @param {!angular.$http} $http * @param {!angular.$window} $window * @constructor * @ngInject */ filedrop.Files = function($http, $window) { /** @private {!angular.$http} */ this.http_ = $http; /** @private {!Array.<string>} */ this.permissions_ = $window['permissions']; }; /** * @return {!angular.$q.Promise.<!Array.<!Object>>} */ filedrop.Files.prototype.list = function() { return this.http_.get('/file/').then(angular.bind(this, function(response) { var entries = response.data['entries']; for (var i = 0; i < entries.length; i++) { var e = entries[i]; e['url'] = this.getFileUrl_(e['name']); } return entries; })); }; /** * Upload a file. * @param {!File} file * @return {!angular.$q.Promise.<!Object>} the created file object */ filedrop.Files.prototype.upload = function(file) { var url = this.getFileUrl_(file.name); return this.http_.put(url, file, { transformRequest: filedrop.Files.transformFile_ }).then(function() { return {'name': file.name, 'url': url}; }); }; /** * Delete a file. * @param {string} name * @return {!angular.$q.Promise} */ filedrop.Files.prototype.remove = function(name) { return this.http_.delete(this.getFileUrl_(name)); }; /** * Build the URL for a file name. * @param {string} name * @return {string} the server-relative URL */ filedrop.Files.prototype.getFileUrl_ = function(name) { return '/file/' + encodeURI(name); }; /** * Report whether the user can read files. * @return {boolean} */ filedrop.Files.prototype.canRead = function() { return this.hasPerm_('read'); }; /** * Report whether the user can upload files. * @return {boolean} */ filedrop.Files.prototype.canWrite = function() { return this.hasPerm_('write'); }; /** * Report whether the user can delete files. * @return {boolean} */ filedrop.Files.prototype.canDelete = function() { return this.hasPerm_('delete'); }; /** * Report whether the user has a named permission. * @param {string} name * @return {boolean} * @private */ filedrop.Files.prototype.hasPerm_ = function(name) { for (var i = 0; i < this.permissions_.length; i++) { if (this.permissions_[i] == name) { return true; } } return false; }; /** * Transform request data for a file body. * * @param {!File} data * @param {function(): Object.<string, string>} headersGetter * @return {!File} the data as passed in * @private */ filedrop.Files.transformFile_ = function(data, headersGetter) { var h = headersGetter(); h['Content-Type'] = 'application/octet-stream'; return data; };
JavaScript
0
@@ -770,16 +770,43 @@ %7D $http%0A + * @param %7B!angular.$q%7D $q%0A * @para @@ -907,16 +907,20 @@ $window +, $q ) %7B%0A /* @@ -972,16 +972,64 @@ $http;%0A + /** @private %7B!angular.$q%7D */%0A this.q_ = $q;%0A /** @p @@ -1504,32 +1504,91 @@ * Upload a file. + Returned promise provides updates via XHR progress events. %0A * @param %7B!Fil @@ -1713,24 +1713,52 @@ ion(file) %7B%0A + var d = this.q_.defer();%0A%0A var url = @@ -1792,99 +1792,465 @@ ;%0A -return this.http_.put(url, file, %7B%0A transformRequest: filedrop.Files.transformFile_%0A %7D) +var xhr = new XMLHttpRequest();%0A%0A xhr.upload.addEventListener('progress', function(event) %7B%0A d.notify(event);%0A %7D);%0A xhr.onreadystatechange = function() %7B%0A if (xhr.readyState === 4) %7B%0A if (xhr.status === 200 %7C%7C xhr.status === 201) %7B%0A d.resolve(xhr);%0A %7D else %7B%0A d.reject(xhr);%0A %7D%0A %7D%0A %7D;%0A%0A xhr.open('PUT', url);%0A xhr.setRequestHeader('Content-Type', 'application/octet-stream');%0A xhr.send(file);%0A%0A return d.promise .the @@ -3515,357 +3515,4 @@ %0A%7D;%0A -%0A%0A/**%0A * Transform request data for a file body.%0A *%0A * @param %7B!File%7D data%0A * @param %7Bfunction(): Object.%3Cstring, string%3E%7D headersGetter%0A * @return %7B!File%7D the data as passed in%0A * @private%0A */%0Afiledrop.Files.transformFile_ = function(data, headersGetter) %7B%0A var h = headersGetter();%0A h%5B'Content-Type'%5D = 'application/octet-stream';%0A return data;%0A%7D;%0A
5067846ea92a90aff409d966606854aae842ba28
Customize gatsby config
gatsby-config.js
gatsby-config.js
module.exports = { siteMetadata: { title: "IPv6-adresse.dk", }, plugins: [ "gatsby-plugin-sass", "gatsby-plugin-image", "gatsby-plugin-react-helmet", "gatsby-plugin-sitemap", { resolve: "gatsby-plugin-manifest", options: { icon: "src/images/icon.png", }, }, "gatsby-plugin-mdx", "gatsby-plugin-sharp", "gatsby-transformer-sharp", { resolve: "gatsby-source-filesystem", options: { name: "images", path: "./src/images/", }, __key: "images", }, { resolve: "gatsby-source-filesystem", options: { name: "pages", path: "./src/pages/", }, __key: "pages", }, ], };
JavaScript
0.000001
@@ -60,21 +60,64 @@ se.dk%22,%0A + siteUrl: 'https://www.ipv6-adresse.dk'%0A %7D,%0A - plugin @@ -434,24 +434,192 @@ mer-sharp%22,%0A + %22gatsby-transformer-json%22,%0A %7B%0A resolve: %22gatsby-source-filesystem%22,%0A options: %7B%0A name: %60data%60,%0A path: %60$%7B__dirname%7D/data%60%0A %7D%0A %7D,%0A %7B%0A @@ -886,32 +886,32 @@ ges/%22,%0A %7D,%0A - __key: %22pa @@ -923,16 +923,71 @@ %0A %7D,%0A + %7B%0A resolve: 'gatsby-plugin-react-svg',%0A %7D,%0A %5D,%0A%7D;%0A
d80b81170a6e50957ed2af8daaacaa0638d6ef98
add resources folder as nodes
gatsby-config.js
gatsby-config.js
var path = require("path"); module.exports = { siteMetadata: { title: "Gatsby Default Starter", }, plugins: [ { resolve: "gatsby-source-filesystem", options: { path: path.resolve('./src/pages/'), name: "pages", } }, { resolve: "gatsby-transformer-remark" }, "gatsby-plugin-react-helmet", { resolve: "resolve-alias-plugin", options: { alias : { "~" : path.resolve('./src') } } }, "gatsby-plugin-styled-components", "gatsby-plugin-sharp" ] }
JavaScript
0
@@ -264,24 +264,181 @@ %7D,%0A %7B%0A + resolve: %22gatsby-source-filesystem%22,%0A options: %7B%0A name: %22images%22,%0A path: %60$%7B__dirname%7D/src/resources/images%60,%0A %7D,%0A %7D,%0A %7B%0A resolv @@ -725,15 +725,47 @@ n-sharp%22 +,%0A %22gatsby-transformer-sharp%22 %0A %5D%0A%7D%0A
a6c9a399b8850a3ca7c47221748078d8d5a3f023
update formatting
gatsby-config.js
gatsby-config.js
/* eslint-disable @typescript-eslint/no-var-requires */ const path = require('path'); module.exports = { siteMetadata: { title: 'AlexSwensen.io', description: 'My personal blog and site.', siteUrl: 'https://alexswensen.io', // full path to blog - no ending slash }, mapping: { 'MarkdownRemark.frontmatter.author': 'AuthorYaml', }, plugins: [ { resolve: 'gatsby-plugin-disqus', options: { shortname: 'alexswensenio', }, }, 'gatsby-plugin-sitemap', { resolve: 'gatsby-plugin-sharp', options: { quality: 100, stripMetadata: true, }, }, { resolve: 'gatsby-source-filesystem', options: { name: 'content', path: path.join(__dirname, 'src', 'content'), }, }, { resolve: 'gatsby-source-filesystem', options: { name: 'content', path: path.join(__dirname, 'src', 'content'), }, }, { resolve: 'gatsby-source-filesystem', options: { name: 'assets', path: path.join(__dirname, 'content', 'assets'), }, }, { resolve: 'gatsby-transformer-remark', options: { plugins: [ { resolve: 'gatsby-remark-responsive-iframe', options: { wrapperStyle: 'margin-bottom: 1rem', }, }, 'gatsby-remark-prismjs', 'gatsby-remark-copy-linked-files', 'gatsby-remark-smartypants', 'gatsby-remark-abbr', { resolve: 'gatsby-remark-images', options: { maxWidth: 2000, quality: 100, }, }, ], }, }, 'gatsby-transformer-json', { resolve: 'gatsby-plugin-canonical-urls', options: { siteUrl: 'https://alexswensen.io', }, }, 'gatsby-plugin-emotion', 'gatsby-plugin-typescript', 'gatsby-transformer-sharp', 'gatsby-plugin-react-helmet', 'gatsby-transformer-yaml', 'gatsby-plugin-feed', { resolve: 'gatsby-plugin-manifest', options: { name: `alexswensen.io`, short_name: `alexswensenio`, start_url: `/`, background_color: `#ffffff`, theme_color: `#000000`, display: `minimal-ui`, icon: `src/content/img/fav-icon.png` }, }, 'gatsby-plugin-remove-serviceworker', { resolve: 'gatsby-plugin-postcss', options: { postCssPlugins: [require('postcss-color-function'), require('cssnano')()], }, }, { resolve: 'gatsby-plugin-google-gtag', options: { // You can add multiple tracking ids and a pageview event will be fired for all of them. trackingIds: [ 'UA-39293631-3', ], // This object gets passed directly to the gtag config command // This config will be shared across all trackingIds gtagConfig: { // optimize_id: "OPT_CONTAINER_ID", anonymize_ip: true, cookie_expires: 0, }, // This object is used for configuration specific to this plugin pluginConfig: { // Puts tracking script in the head instead of the body head: false, // Setting this parameter is also optional respectDNT: true, // Avoids sending pageview hits from custom paths // exclude: ["/preview/**", "/do-not-track/me/too/"], }, }, }, ], };
JavaScript
0.000001
@@ -2136,25 +2136,25 @@ name: -%60 +' alexswensen. @@ -2155,17 +2155,17 @@ ensen.io -%60 +' ,%0A @@ -2178,17 +2178,17 @@ t_name: -%60 +' alexswen @@ -2192,17 +2192,17 @@ wensenio -%60 +' ,%0A @@ -2218,11 +2218,11 @@ rl: -%60/%60 +'/' ,%0A @@ -2249,17 +2249,17 @@ or: -%60 +' #ffffff -%60 +' ,%0A @@ -2281,17 +2281,17 @@ or: -%60 +' #000000 -%60 +' ,%0A @@ -2305,17 +2305,17 @@ isplay: -%60 +' minimal- @@ -2316,17 +2316,17 @@ nimal-ui -%60 +' ,%0A @@ -2333,17 +2333,17 @@ icon: -%60 +' src/cont @@ -2366,9 +2366,10 @@ .png -%60 +', %0A
173528dd8b163f43af925368c6a49693e3f49865
disable gatsby-plugin-offline for now
gatsby-config.js
gatsby-config.js
module.exports = { siteMetadata: { title: '@resir014', description: 'Web developer based in Jakarta, Indonesia.', siteUrl: `https://resir014.xyz`, author: { name: 'Resi Respati', url: 'https://twitter.com/resir014', email: '[email protected]' } }, plugins: [ { resolve: 'gatsby-source-filesystem', options: { name: 'pages', path: `${__dirname}/src/pages` } }, { resolve: 'gatsby-source-filesystem', options: { name: 'data', path: `${__dirname}/src/data` } }, { resolve: 'gatsby-plugin-canonical-urls', options: { siteUrl: `https://resir014.xyz` } }, { resolve: `gatsby-transformer-remark`, options: { plugins: [ { resolve: `gatsby-remark-responsive-iframe`, options: { wrapperStyle: `margin-bottom: 1rem` } }, 'gatsby-remark-prismjs', 'gatsby-remark-copy-linked-files', 'gatsby-remark-smartypants' ] } }, { resolve: 'gatsby-plugin-nprogress', options: { color: '#fff', showSpinner: false }, }, 'gatsby-plugin-catch-links', 'gatsby-transformer-json', 'gatsby-plugin-twitter', 'gatsby-plugin-sass', 'gatsby-plugin-typescript', 'gatsby-plugin-glamor', 'gatsby-plugin-react-helmet', { resolve: 'gatsby-plugin-manifest', options: { name: '@resir014', short_name: '@resir014', start_url: '/', background_color: '#fff', theme_color: '#000', display: 'minimal-ui', icons: [ { src: '/android-touch-icon.png', sizes: '192x192', type: 'image/png', } ] } }, 'gatsby-plugin-offline', { resolve: 'gatsby-plugin-google-analytics', options: { trackingId: 'UA-11448343-3', anonymize: true } }, { resolve: `gatsby-plugin-feed`, options: { query: ` { site { siteMetadata { title description siteUrl site_url: siteUrl } } } `, feeds: [ { serialize: ({ query: { site, allMarkdownRemark } }) => { return allMarkdownRemark.edges.map(edge => { return Object.assign({}, edge.node.frontmatter, { description: edge.node.excerpt, url: site.siteMetadata.siteUrl + edge.node.fields.slug, guid: site.siteMetadata.siteUrl + edge.node.fields.slug, custom_elements: [{ 'content:encoded': edge.node.html }], }); }); }, query: ` { allMarkdownRemark( limit: 10, filter: {id: {regex: "/posts/"}}, sort: {fields: [fields___date], order: DESC} ) { edges { node { excerpt html fields { slug date } frontmatter { title } } } } } `, output: '/posts/rss.xml', feedTitle: 'All posts by @resir014' } ] } }, { resolve: 'gatsby-plugin-netlify', options: { headers: { '/*': [ 'X-Clacks-Overhead: GNU Natalie Nguyen' ] } } } ] }
JavaScript
0
@@ -1864,37 +1864,8 @@ %7D,%0A - 'gatsby-plugin-offline',%0A
8b8d269665283723fe33ec1b41906dd608f577cd
add new progress bar tests
tests/jsPsych/progressbar.test.js
tests/jsPsych/progressbar.test.js
const root = '../../'; const utils = require('../testing-utils.js'); beforeEach(function(){ require(root + 'jspsych.js'); require(root + 'plugins/jspsych-html-keyboard-response.js'); }); describe('automatic progress bar', function(){ test('progress bar does not display by default', function(){ var trial = { type: 'html-keyboard-response', stimulus: 'foo' } jsPsych.init({ timeline: [trial] }); expect(document.querySelector('#jspsych-progressbar-container')).toBe(null); utils.pressKey(32); }); test('progress bar displays when show_progress_bar is true', function(){ var trial = { type: 'html-keyboard-response', stimulus: 'foo' } jsPsych.init({ timeline: [trial], show_progress_bar: true }); expect(document.querySelector('#jspsych-progressbar-container').innerHTML).toMatch('<span>Completion Progress</span><div id="jspsych-progressbar-outer"><div id="jspsych-progressbar-inner"></div></div>'); utils.pressKey(32); }); test('progress bar automatically updates by default', function(){ var trial = { type: 'html-keyboard-response', stimulus: 'foo' } jsPsych.init({ timeline: [trial, trial, trial, trial], show_progress_bar: true }); expect(document.querySelector('#jspsych-progressbar-inner').style.width).toBe(''); utils.pressKey(32); expect(document.querySelector('#jspsych-progressbar-inner').style.width).toBe('25%'); utils.pressKey(32); expect(document.querySelector('#jspsych-progressbar-inner').style.width).toBe('50%'); utils.pressKey(32); expect(document.querySelector('#jspsych-progressbar-inner').style.width).toBe('75%'); utils.pressKey(32); expect(document.querySelector('#jspsych-progressbar-inner').style.width).toBe('100%'); }); test('progress bar does not automatically update when auto_update_progress_bar is false', function(){ var trial = { type: 'html-keyboard-response', stimulus: 'foo' } jsPsych.init({ timeline: [trial, trial, trial, trial], show_progress_bar: true, auto_update_progress_bar: false }); expect(document.querySelector('#jspsych-progressbar-inner').style.width).toBe(''); utils.pressKey(32); expect(document.querySelector('#jspsych-progressbar-inner').style.width).toBe(''); utils.pressKey(32); expect(document.querySelector('#jspsych-progressbar-inner').style.width).toBe(''); utils.pressKey(32); expect(document.querySelector('#jspsych-progressbar-inner').style.width).toBe(''); utils.pressKey(32); expect(document.querySelector('#jspsych-progressbar-inner').style.width).toBe(''); }); test('setProgressBar() manually', function(){ var trial = { type: 'html-keyboard-response', stimulus: 'foo', on_finish: function(){ jsPsych.setProgressBar(0.2); } } var trial_2 = { type: 'html-keyboard-response', stimulus: 'foo', on_finish: function(){ jsPsych.setProgressBar(0.8); } } jsPsych.init({ timeline: [trial, trial_2], show_progress_bar: true, auto_update_progress_bar: false }); expect(document.querySelector('#jspsych-progressbar-inner').style.width).toBe(''); utils.pressKey(32); expect(document.querySelector('#jspsych-progressbar-inner').style.width).toBe('20%'); utils.pressKey(32); expect(document.querySelector('#jspsych-progressbar-inner').style.width).toBe('80%'); }); });
JavaScript
0
@@ -3554,12 +3554,1302 @@ %0A %7D);%0A%0A + test('getProgressBarCompleted() -- manual updates', function()%7B%0A var trial = %7B%0A type: 'html-keyboard-response',%0A stimulus: 'foo',%0A on_finish: function()%7B%0A jsPsych.setProgressBar(0.2);%0A %7D%0A %7D%0A%0A var trial_2 = %7B%0A type: 'html-keyboard-response',%0A stimulus: 'foo',%0A on_finish: function()%7B%0A jsPsych.setProgressBar(0.8);%0A %7D%0A %7D%0A%0A jsPsych.init(%7B%0A timeline: %5Btrial, trial_2%5D,%0A show_progress_bar: true,%0A auto_update_progress_bar: false%0A %7D);%0A%0A utils.pressKey(32);%0A%0A expect(jsPsych.getProgressBarCompleted()).toBe(0.2);%0A%0A utils.pressKey(32);%0A%0A expect(jsPsych.getProgressBarCompleted()).toBe(0.8);%0A%0A %7D);%0A%0A test('getProgressBarCompleted() -- automatic updates', function()%7B%0A var trial = %7B%0A type: 'html-keyboard-response',%0A stimulus: 'foo'%0A %7D%0A%0A jsPsych.init(%7B%0A timeline: %5Btrial, trial, trial, trial%5D,%0A show_progress_bar: true%0A %7D);%0A%0A utils.pressKey(32);%0A%0A expect(jsPsych.getProgressBarCompleted()).toBe(0.25);%0A%0A utils.pressKey(32);%0A%0A expect(jsPsych.getProgressBarCompleted()).toBe(0.50);%0A%0A utils.pressKey(32);%0A%0A expect(jsPsych.getProgressBarCompleted()).toBe(0.75);%0A%0A utils.pressKey(32);%0A%0A expect(jsPsych.getProgressBarCompleted()).toBe(1);%0A%0A %7D);%0A%0A %7D);%0A
ceaf61450c53d50119574d489e3cfe5f7e5ccdae
Fix possible bug
lib/file-icons.js
lib/file-icons.js
"use babel"; fs = require('fs-plus') /** * This class provides the file-icons service API implemented by tree-view * Please see https://github.com/atom/tree-view#api */ module.exports = class Perl6FileIconsProvider { iconClassForPath(filePath) { extension = path.extname(filePath) if (fs.isSymbolicLinkSync(filePath)) { return 'icon-file-symlink-file' } else if (fs.isReadmePath(filePath)) { return 'icon-book' } else if (fs.isCompressedExtension(extension)) { return 'icon-file-zip' } else if (fs.isImageExtension(extension)) { return 'icon-file-media' } else if (fs.isPdfExtension(extension)) { return 'icon-file-pdf' } else if (fs.isBinaryExtension(extension)) { return 'icon-file-binary' } else if (extension == ".pm6" || extension == ".pm" || extension == ".pl6" || extension == ".p6" || extension == ".pl" || extension == ".t") { return 'icon-file-perl6' } else { return 'icon-file-text' } } onWillDeactivate(fn) { return } }
JavaScript
0.000546
@@ -30,16 +30,39 @@ s-plus') +%0Apath = require('path') %0A%0A/**%0A *
29984554122f2690ba3218f7d20244cb3b6ced92
Fix for noHead option
lib/file-utils.js
lib/file-utils.js
import path from 'node:path'; import { createWriteStream } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { readFile, rm, mkdir } from 'node:fs/promises'; import copydir from 'copy-dir'; import _ from 'lodash-es'; import archiver from 'archiver'; import beautify from 'js-beautify'; import { renderFile } from 'pug'; import puppeteer from 'puppeteer'; import sanitize from 'sanitize-filename'; import untildify from 'untildify'; import { isNullOrEmpty, formatDays } from './formatters.js'; import * as templateFunctions from './template-functions.js'; /* * Attempt to parse the specified config JSON file. */ export async function getConfig(argv) { try { const data = await readFile(path.resolve(untildify(argv.configPath)), 'utf8').catch(error => { console.error(new Error(`Cannot find configuration file at \`${argv.configPath}\`. Use config-sample.json as a starting point, pass --configPath option`)); throw error; }); const config = JSON.parse(data); if (argv.skipImport === true) { config.skipImport = argv.skipImport; } if (argv.showOnlyTimepoint === true) { config.showOnlyTimepoint = argv.showOnlyTimepoint; } return config; } catch (error) { console.error(new Error(`Cannot parse configuration file at \`${argv.configPath}\`. Check to ensure that it is valid JSON.`)); throw error; } } /* * Get the full path of the template file for generating timetables based on * config. */ function getTemplatePath(templateFileName, config) { if (config.templatePath !== undefined) { return path.join(untildify(config.templatePath), `${templateFileName}.pug`); } return path.join(fileURLToPath(import.meta.url), '../../views/default', `${templateFileName}.pug`); } /* * Prepare the specified directory for saving HTML timetables by deleting * everything and creating the expected folders. */ export async function prepDirectory(exportPath) { await rm(exportPath, { recursive: true, force: true }); await mkdir(exportPath, { recursive: true }); } /* * Copy needed CSS and JS to export path. */ export function copyStaticAssets(exportPath) { const staticAssetPath = path.join(fileURLToPath(import.meta.url), '../../public'); copydir.sync(path.join(staticAssetPath, 'css'), path.join(exportPath, 'css')); copydir.sync(path.join(staticAssetPath, 'js'), path.join(exportPath, 'js')); } /* * Zips the content of the specified folder. */ export function zipFolder(exportPath) { const output = createWriteStream(path.join(exportPath, 'timetables.zip')); const archive = archiver('zip'); return new Promise((resolve, reject) => { output.on('close', resolve); archive.on('error', reject); archive.pipe(output); archive.glob('**/*.{txt,css,html}', { cwd: exportPath }); archive.finalize(); }); } /* * Generate the filename for a given timetable. */ export function generateFileName(timetable, config) { let filename = timetable.timetable_id; for (const route of timetable.routes) { filename += isNullOrEmpty(route.route_short_name) ? `_${route.route_long_name.replace(/\s/g, '-')}` : `_${route.route_short_name.replace(/\s/g, '-')}`; } if (!isNullOrEmpty(timetable.direction_id)) { filename += `_${timetable.direction_id}`; } filename += `_${formatDays(timetable, config).replace(/\s/g, '')}.html`; return sanitize(filename).toLowerCase(); } /* * Generates the folder name for a timetable page based on the date. */ export function generateFolderName(timetablePage) { // Use first timetable in timetable page for start date and end date const timetable = timetablePage.consolidatedTimetables[0]; if (!timetable.start_date || !timetable.end_date) { return 'timetables'; } return sanitize(`${timetable.start_date}-${timetable.end_date}`); } /* * Render the HTML for a timetable based on the config. */ export async function renderTemplate(templateFileName, templateVars, config) { const templatePath = getTemplatePath(templateFileName, config); // Make template functions and lodash available inside pug templates. const html = await renderFile(templatePath, { _, ...templateFunctions, ...templateVars }); // Beautify HTML if `beautify` is set in config. if (config.beautify === true) { return beautify.html_beautify(html, { indent_size: 2 }); } return html; } /* * Render the PDF for a timetable based on the config. */ export async function renderPdf(htmlPath) { const pdfPath = htmlPath.replace(/html$/, 'pdf'); const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.emulateMediaType('screen'); await page.goto(`file://${htmlPath}`, { waitUntil: 'networkidle0' }); await page.pdf({ path: pdfPath }); await browser.close(); }
JavaScript
0.000001
@@ -1534,16 +1534,137 @@ nfig) %7B%0A + let fullTemplateFileName = templateFileName;%0A if (config.noHead !== true) %7B%0A fullTemplateFileName += '_full';%0A %7D%0A%0A if (co @@ -1750,25 +1750,29 @@ tePath), %60$%7B -t +fullT emplateFileN @@ -1865,17 +1865,21 @@ lt', %60$%7B -t +fullT emplateF
172e71201569760699ffe93ec9d69f2b6105ce6b
Fix plural ending for "X podcasts found"
src/static/libs/js/views/search/index.js
src/static/libs/js/views/search/index.js
require('../../navbar.js'); require('../../auth.js'); import {searchPodcasts} from '../../podcastHelper'; $('#search .search-podcasts').on('click', () => { loadSearchResults(); if (window.searchQuery) { window.searchQuery = null; history.pushState(null, "", location.href.split("?")[0]); } }); $('#search .search-input').keypress((e) => { var key = e.which; if (key == 13) { // enter key loadSearchResults(); } if (window.searchQuery) { window.searchQuery = null; history.pushState(null, "", location.href.split("?")[0]); } }); function loadSearchResults (query) { $('.search-results').html(''); $('.search-results-empty').hide(); $('.search-loader').show(); query = query || $('#search input').val(); searchPodcasts(query) .then(results => { if (!results || results.length === 0) { $('.search-results-empty').show(); } let html = `<div class="search-result-count">${results.length} podcast${results.length > 1 ? 's' : ''} found</div>`; for (let result of results) { html += `<a class="search-result" href="/podcasts/${result.id}">`; html += `<div class="search-result-image">`; html += `<img src="${result.imageUrl}" />` html += `</div>` html += `<div class="search-result-title">`; html += `${result.title}`; html += `</div>` html += `</a>` } $('.search-loader').hide(); $('.search-results').append(html); }) .catch(err => { $('.search-loader').hide(); $('.search-results-error').show(); console.log(err); }) } if (window.searchQuery) { $('#search input').val(window.searchQuery); loadSearchResults(window.searchQuery); }
JavaScript
0.002471
@@ -990,16 +990,39 @@ gth %3E 1 +&& results.length != 0 ? 's' :
112e5123bcbeddd3591cc5914c6b4639ea027688
remove debug code
server/helpers/wowCommunityApi.js
server/helpers/wowCommunityApi.js
import { blizzardApiResponseLatencyHistogram } from 'helpers/metrics'; import RequestTimeoutError from 'helpers/request/RequestTimeoutError'; import RequestSocketTimeoutError from 'helpers/request/RequestSocketTimeoutError'; import RequestConnectionResetError from 'helpers/request/RequestConnectionResetError'; import RequestUnknownError from 'helpers/request/RequestUnknownError'; import retryingRequest from './retryingRequest'; const availableRegions = { eu: 'ru_RU', us: 'en_US', tw: 'zh_TW', kr: 'ko_KR', }; const USER_AGENT = process.env.USER_AGENT; const clientToken = {}; const get = (url, metricLabels, region, skipAccessToken = false) => { let end; return retryingRequest({ url, headers: { 'User-Agent': USER_AGENT, }, gzip: true, // we'll be making several requests, so pool connections forever: true, timeout: 4000, // ms after which to abort the request, when a character is uncached it's not uncommon to take ~2sec shouldRetry: error => { const { statusCode } = error; //generally 404 should probably just not be retried return statusCode !== 404; }, getUrlWithAccessToken: async () => { console.log(`skippingAccessToken: ${skipAccessToken}`) if(!skipAccessToken){ const accessToken = await getAccessToken(region); return `${url}&access_token=${accessToken}`; } else { return url; } }, onBeforeAttempt: () => { end = blizzardApiResponseLatencyHistogram.startTimer(metricLabels); }, onFailure: async err => { if (err.statusCode === 401) { delete clientToken[region]; end({ statusCode: 401, }); } else if (err instanceof RequestTimeoutError) { end({ statusCode: 'timeout', }); } else if (err instanceof RequestSocketTimeoutError) { end({ statusCode: 'socket timeout', }); } else if (err instanceof RequestConnectionResetError) { end({ statusCode: 'connection reset', }); } else if (err instanceof RequestUnknownError) { end({ statusCode: 'unknown', }); } else { console.log(err); // end({ // statusCode: err.statusCode, // }); } return null; }, onSuccess: () => { end({ statusCode: 200, }); }, }); }; const makeBaseUrl = region => `https://${region}.api.blizzard.com`; const getAccessToken = async (region) => { if (clientToken[region]) { return clientToken[region]; } const url = `https://${region}.battle.net/oauth/token?grant_type=client_credentials&client_id=${process.env.BATTLE_NET_API_CLIENT_ID}&client_secret=${process.env.BATTLE_NET_API_CLIENT_SECRET}`; const tokenRequest = await get( url, { category: 'token', region, }, region, true ); const tokenData = JSON.parse(tokenRequest); clientToken[region] = tokenData.access_token; return clientToken[region]; }; export async function fetchCharacter(region, realm, name, fields = '') { region = region.toLowerCase(); if (!availableRegions[region]) { throw new Error('Region not recognized.'); } const url = `${makeBaseUrl(region)}/wow/character/${encodeURIComponent(realm)}/${encodeURIComponent(name)}?locale=${availableRegions[region]}&fields=${fields}`; return get( url, { category: 'character', region, }, region, ); } export async function fetchItem(region, itemId) { region = region.toLowerCase(); if (!availableRegions[region]) { throw new Error('Region not recognized.'); } const url = `${makeBaseUrl(region)}/wow/item/${encodeURIComponent(itemId)}?locale=${availableRegions[region]}`; return get( url, { category: 'item', region, }, region, ); } export async function fetchSpell(region, spellId) { region = region.toLowerCase(); if (!availableRegions[region]) { throw new Error('Region not recognized.'); } const url = `${makeBaseUrl(region)}/wow/spell/${encodeURIComponent(spellId)}?locale=${availableRegions[region]}`; return get( url, { category: 'spell', region, }, region, ); }
JavaScript
0.02323
@@ -2202,37 +2202,8 @@ - console.log(err);%0A // end @@ -2212,19 +2212,16 @@ %0A - // statu @@ -2250,19 +2250,16 @@ %0A - // %7D);%0A @@ -2874,18 +2874,16 @@ ue%0A );%0A - %0A const
22930b0d5d2cac197d4f72c0cc814ca6b8888b0d
Add generic global error message for non 500's ajax calls
WebContent/js/global.js
WebContent/js/global.js
/* Cached Variables *******************************************************************************/ var $allModals = $('.modal'); var $globalSmallModal = $('#global-small-modal'); /* Initialization *********************************************************************************/ selectTab($('body').data('tab-id')); $('#copyright-year').text(new Date().getFullYear()); /* Listeners **************************************************************************************/ $(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) { $allModals.modal('hide'); var isServerError = jqXHR.status >= 500 && jqXHR.status < 600; if(isServerError) { $globalSmallModal.find('.modal-dialog').html(jqXHR.responseText); } $globalSmallModal.modal('show'); }); $('#submit-bug-report').on('click', function() { popupCenter('https://gitreports.com/issue/moe-bugs/moe-sounds', 'Submit Bug Report', 650, 900); }); /* Functions **************************************************************************************/ function popupCenter(url, title, w, h) { var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left; var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top; var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width; var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height; var left = ((width / 2) - (w / 2)) + dualScreenLeft; var top = ((height / 2) - (h / 2)) + dualScreenTop; var newWindow = window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left); // Puts focus on the newWindow if (window.focus) newWindow.focus(); } function selectTab(id) { $('#' + id).addClass('active'); } /* Document Ready Stuff ***************************************************************************/ $(document).ready(function() { $('.table-container').removeClass('table-loading'); });
JavaScript
0
@@ -663,18 +663,16 @@ erError) - %7B %0A $gl @@ -736,17 +736,94 @@ ext);%0A -%7D +else%0A $globalSmallModal.find('.modal-dialog').html(getGenericErrorModal()); %0A %0A $g @@ -2007,16 +2007,746 @@ e');%0A%7D%0A%0A +function getGenericErrorModal() %7B%0A %0A return '%3Cdiv class=%22modal-content%22%3E' +%0A%0A '%3Cdiv class=%22modal-header%22%3E' +%0A '%3Cbutton type=%22button%22 class=%22close%22 data-dismiss=%22modal%22 aria-label=%22Close%22%3E%3Cspan aria-hidden=%22true%22%3E&times;%3C/span%3E%3C/button%3E' +%0A '%3Ch4 class=%22modal-title%22%3EError%3C/h4%3E' +%0A '%3C/div%3E' +%0A %0A '%3Cdiv class=%22modal-body%22%3E' +%0A '%3Cp%3ESomething is goofed up. If this keeps happening please submit a bug report.%3C/p%3E' +%0A '%3C/div%3E' +%0A %0A '%3Cdiv class=%22modal-footer%22%3E' +%0A '%3Cbutton type=%22button%22 class=%22btn btn-warning%22 data-dismiss=%22modal%22%3EOK%3C/button%3E' +%0A '%3C/div%3E' +%0A %0A '%3C/div%3E';%0A%7D%0A%0A /* Docum
20066368cdd4336441d46700033e37d66650292c
add unit test to query.model.spec.js
server/models/query.model.spec.js
server/models/query.model.spec.js
'use strict'; // Set default node environment to development if (process.env.NODE_ENV === 'test') { process.env.DB_PASS='digdig'; process.env.DB_HOST='localhost'; } else { process.env.NODE_ENV = process.env.NODE_ENV || 'development'; } var config = require('../config/environment'); var should = require('should'); var models = require('./index'); describe('Query Model', function() { var testUser = 'testuserpedro'; var serialize = function (query) { query.digState = JSON.stringify(query.digState); query.elasticUIState = JSON.stringify(query.elasticUIState); return query; } var testquery = serialize({ name: 'test query', digState: { searchTerms: 'another users query', filters: {"textFilters":{"phonenumber":{"live":"","submitted":""}},"dateFilters":{"dateCreated":{"beginDate":null,"endDate":null}}}, selectedSort: {"title":"Best Match","order":"rank"}, includeMissing: {'aggregations': {}, 'allIncludeMissing': false} }, elasticUIState: { queryState: {"query_string":{"fields":["_all"],"query":"another users query"}} }, frequency: 'daily', lastRunDate: new Date() }) before(function (done) { return models.User.sync() .then(function() { return models.Query.sync() }) .then(function () { return models.User.destroy( { where: {username: testUser} }) }) .then(function () { return models.User.create({ username: testUser }) }) .then(function (user) { done(); }) .catch (function(err) { done(err); }) }); it('should create a query', function (done) { return models.Query.create(testquery) .then(function (query) { query.notificationHasRun.should.be.true; return query.setUser(testUser); }) .then(function() { done(); }) .catch(function(err) { done(err); }); }); });
JavaScript
0.000002
@@ -2172,12 +2172,414 @@ %7D);%0A%0A + it('should find no queries', function (done) %7B%0A return models.Query.findAll(%7B%0A where: %7B%0A notificationHasRun: true,%0A frequency: 'weekly'%0A %7D%0A %7D)%0A .then(function(queries) %7B%0A queries.length.should.be.within(0,4);%0A done()%0A %7D)%0A .catch(function(err) %7B%0A done(err);%0A %7D);%0A %7D);%0A%0A %7D);%0A
903a3fa5ed6383de91b650992e500ff40df6c586
rewrite fly-fake-plugin test module
test/fixtures/alt/node_modules/fly-fake-plugin/index.js
test/fixtures/alt/node_modules/fly-fake-plugin/index.js
module.exports = function () { return this.filter("fakePlugin", function (src, opts) { return src.toString().split("").reverse().join("") }) }
JavaScript
0.000001
@@ -45,17 +45,17 @@ .filter( -%22 +' fakePlug @@ -56,17 +56,17 @@ kePlugin -%22 +' , functi @@ -114,18 +114,18 @@ ).split( -%22%22 +'' ).revers @@ -137,15 +137,17 @@ oin( -%22%22 +'' )%0A %7D) +; %0A%7D +; %0A
8b63fed4d791b0b5f4498667dfcb6f3638f18643
Add top/bottom/left/right properties to Rect.
canvas-animation/js/geometry/models/rect.js
canvas-animation/js/geometry/models/rect.js
/*globals define*/ define([ 'geometry/models/object2d' ], function( Object2D ) { 'use strict'; var Rect = Object2D.extend({ defaults: function() { var defaults = Object2D.prototype.defaults(); defaults.width = 0; defaults.height = 0; return defaults; }, drawPath: function( ctx ) { var width = this.get( 'width' ), height = this.get( 'height' ); ctx.beginPath(); ctx.rect( -0.5 * width, -0.5 * height, width, height ); ctx.closePath(); } }); return Rect; });
JavaScript
0
@@ -523,16 +523,1713 @@ %0A %7D);%0A%0A + // left, right, top, and bottom properties are in world space.%0A Object.defineProperty( Rect.prototype, 'left', %7B%0A get: function() %7B%0A var halfWidth = 0.5 * this.get( 'width' );%0A return this.toWorld( -halfWidth, 0 );%0A %7D,%0A%0A set: function( position ) %7B%0A var halfWidth = 0.5 * this.get( 'width' );%0A var point = this.toLocal( position.x, position.y );%0A point = this.toWorld( point.x + halfWidth, 0 );%0A this.set( point );%0A %7D%0A %7D);%0A%0A Object.defineProperty( Rect.prototype, 'right', %7B%0A get: function() %7B%0A var halfWidth = 0.5 * this.get( 'width' );%0A return this.toWorld( halfWidth, 0 );%0A %7D,%0A%0A set: function( position ) %7B%0A var halfWidth = 0.5 * this.get( 'width' );%0A var point = this.toLocal( position.x, position.y );%0A point = this.toWorld( point.x - halfWidth, 0 );%0A this.set( point );%0A %7D%0A %7D);%0A%0A Object.defineProperty( Rect.prototype, 'top', %7B%0A get: function() %7B%0A var halfHeight = 0.5 * this.get( 'height' );%0A return this.toWorld( 0, -halfHeight );%0A %7D,%0A%0A set: function( position ) %7B%0A var halfHeight = 0.5 * this.get( 'height' );%0A var point = this.toLocal( position.x, position.y );%0A point = this.toWorld( 0, point.y + halfHeight );%0A this.set( point );%0A %7D%0A %7D);%0A%0A Object.defineProperty( Rect.prototype, 'bottom', %7B%0A get: function() %7B%0A var halfHeight = 0.5 * this.get( 'height' );%0A return this.toWorld( 0, halfHeight );%0A %7D,%0A%0A set: function( position ) %7B%0A var halfHeight = 0.5 * this.get( 'height' );%0A var point = this.toLocal( position.x, position.y );%0A point = this.toWorld( 0, point.y - halfHeight );%0A this.set( point );%0A %7D%0A %7D);%0A%0A return
14f748a4a37641eaf5e20175663c993cced1f409
remove spam
app/utils/SanitizeConfig.js
app/utils/SanitizeConfig.js
const iframeWhitelist = [ // { re: /^(https?:)?\/\/player.vimeo.com\/video\/.*/i }, // <-- medium-editor branch { re: /^(https?:)?\/\/www.youtube.com\/embed\/.*/i, fn: src => { return src.replace(/\?.+$/, ''); // strip query string (yt: autoplay=1,controls=0,showinfo=0, etc) } }, { re: /^https:\/\/w.soundcloud.com\/player\/.*/i, fn: src => { if(!src) return null // <iframe width="100%" height="450" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/257659076&amp;auto_play=false&amp;hide_related=false&amp;show_comments=true&amp;show_user=true&amp;show_reposts=false&amp;visual=true"></iframe> const m = src.match(/url=(.+?)&/) if(!m || m.length !== 2) return null return 'https://w.soundcloud.com/player/?url=' + m[1] + '&auto_play=false&hide_related=false&show_comments=true' + '&show_user=true&show_reposts=false&visual=true' } } ]; // Medium insert plugin uses: div, figure, figcaption, iframe export default ({large = true, highQualityPost = true, noImage = false, sanitizeErrors = []}) => ({ allowedTags: ` div, iframe, a, p, b, q, br, ul, li, ol, img, h1, h2, h3, h4, h5, h6, hr, blockquote, pre, code, em, strong, center, table, thead, tbody, tr, th, td, strike, sup, `.trim().split(/,\s*/), // figure, figcaption, // SEE https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet allowedAttributes: { // "src" MUST pass a whitelist (below) iframe: ['src', 'width', 'height', 'frameBorder', 'allowFullScreen'], //'class' // style is subject to attack, filtering more below td: ['style'], img: ['src'], a: ['href', 'rel'], }, transformTags: { iframe: (tagName, attribs) => { const srcAtty = attribs.src; console.log('srcAtty', srcAtty) for(const item of iframeWhitelist) if(item.re.test(srcAtty)) { const src = typeof item.fn === 'function' ? item.fn(srcAtty, item.re) : srcAtty if(!src) break return { tagName: 'iframe', attribs: { src, width: large ? '640' : '384', height: large ? '360' : '240', allowFullScreen: 'on', class: 'videoWrapper', frameBorder: '0', }, } } console.log('Blocked, did not match iframe "src" white list urls:', tagName, attribs) sanitizeErrors.push('Invalid iframe URL: ' + srcAtty) return {tagName: 'div', text: `(Unsupported ${srcAtty})`} }, img: (tagName, attribs) => { if(noImage) return {tagName: 'div', text: '(Image removed)'} //See https://github.com/punkave/sanitize-html/issues/117 let {src} = attribs if(!/^(https?:)?\/\//i.test(src)) { console.log('Blocked, image tag src does not appear to be a url', tagName, attribs) sanitizeErrors.push('Image URL does not appear to be valid: ' + src) return {tagName: 'img', attribs: {src: 'brokenimg.jpg'}} } // replace http:// with // to force https when needed src = src.replace(/^http:\/\//i, '//') return {tagName, attribs: {src}} }, td: (tagName, attribs) => { const attys = {} if(attribs.style === 'text-align:right') attys.style = 'text-align:right' return { tagName, attribs: attys } }, a: (tagName, attribs) => { let {href} = attribs if(! href) href = '#' const attys = {href} // If it's not a (relative or absolute) steemit URL... if (! href.match(/^(\/(?!\/)|https:\/\/steemit.com)/)) { // attys.target = '_blank' // pending iframe impl https://mathiasbynens.github.io/rel-noopener/ attys.rel = highQualityPost ? 'noopener' : 'nofollow noopener' } return { tagName, attribs: attys } }, } })
JavaScript
0.000001
@@ -1967,52 +1967,8 @@ rc;%0A - console.log('srcAtty', srcAtty)%0A
8598757945f4b9ee4ea7cf23b6e49b5ba62e2a76
refactor to es6 syntax
src/actions/retrieve_users_action.js
src/actions/retrieve_users_action.js
import axios from 'axios'; export const RETRIEVE_USERS = 'RETRIEVE_USERS'; const retrieveUsers = function() { const url = 'https://randomuser.me/api/?results=10' const response = axios.get(url); return { action: RETRIEVE_USERS, payload: response }; }; export default retrieveUsers;
JavaScript
0.999533
@@ -70,16 +70,23 @@ SERS';%0A%0A +export const re @@ -100,21 +100,22 @@ sers - = function() +Action = () =%3E %7B%0A%09 @@ -175,22 +175,21 @@ const re -sponse +quest = axios @@ -216,14 +216,12 @@ %7B%0A%09%09 -action +type : RE @@ -251,48 +251,15 @@ : re -sponse%0A%09%7D;%0A%7D;%0A%0Aexport default retrieveUsers; +quest%0A%09%7D;%0A%7D
126998a6e86b119cbe970c054991a2f05a387788
remove onClick focus
src/lib/RichTextEditor.js
src/lib/RichTextEditor.js
/* @flow */ import React, {Component} from 'react'; import {CompositeDecorator, Editor, EditorState, RichUtils} from 'draft-js'; import getDefaultKeyBinding from 'draft-js/lib/getDefaultKeyBinding'; import EditorToolbar from './EditorToolbar'; import EditorValue from './EditorValue'; import LinkDecorator from './LinkDecorator'; import cx from 'classnames'; import {EventEmitter} from 'events'; // Custom overrides for "code" style. const styleMap = { CODE: { backgroundColor: 'rgba(0, 0, 0, 0.05)', fontFamily: '"Inconsolata", "Menlo", "Consolas", monospace', fontSize: 16, padding: 2, }, }; type ChangeHandler = (value: EditorValue) => any; type Props = { value: EditorValue; onChange: ChangeHandler; }; export default class RichTextEditor extends Component<Props> { props: Props; constructor() { super(...arguments); this._keyEmitter = new EventEmitter(); this._focus = this._focus.bind(this); this._handleReturn = this._handleReturn.bind(this); this._customKeyHandler = this._customKeyHandler.bind(this); this._handleKeyCommand = this._handleKeyCommand.bind(this); this._onChange = this._onChange.bind(this); } render(): React.Element { let editorState = this.props.value.getEditorState(); // If the user changes block type before entering any text, we can // either style the placeholder or hide it. Let's just hide it now. let className = cx({ 'rte-editor': true, 'rte-hide-placeholder': this._shouldHidePlaceholder(), }); return ( <div className="rte-root"> <EditorToolbar keyEmitter={this._keyEmitter} editorState={editorState} onChange={this._onChange} focusEditor={this._focus} /> <div className={className} onClick={this._focus}> <Editor blockStyleFn={getBlockStyle} customStyleMap={styleMap} editorState={editorState} handleReturn={this._handleReturn} keyBindingFn={this._customKeyHandler} handleKeyCommand={this._handleKeyCommand} onChange={this._onChange} placeholder="Tell a story..." ref="editor" spellCheck={true} /> </div> </div> ); } _shouldHidePlaceholder(): boolean { let editorState = this.props.value.getEditorState(); let contentState = editorState.getCurrentContent(); if (!contentState.hasText()) { if (contentState.getBlockMap().first().getType() !== 'unstyled') { return true; } } return false; } _handleReturn(event: Object): boolean { if (event.shiftKey) { let editorState = this.props.value.getEditorState(); this._onChange(RichUtils.insertSoftNewline(editorState)); return true; } else { return false; } } _customKeyHandler(event: Object): ?string { // Allow toolbar to catch key combinations. let eventFlags = {}; this._keyEmitter.emit('keypress', event, eventFlags); if (eventFlags.wasHandled) { return null; } else { return getDefaultKeyBinding(event); } } _handleKeyCommand(command: string): boolean { let editorState = this.props.value.getEditorState(); let newEditorState = RichUtils.handleKeyCommand(editorState, command); if (newEditorState) { this._onChange(newEditorState); return true; } else { return false; } } _onChange(editorState: EditorState) { let newValue = this.props.value.setEditorState(editorState); this.props.onChange(newValue); } _focus() { this.refs.editor.focus(); } } function getBlockStyle(block) { let result = 'rte-block'; switch (block.getType()) { case 'unstyled': return result + ' rte-paragraph'; case 'blockquote': return result + ' rte-blockquote'; default: return result; } } const decorator = new CompositeDecorator([LinkDecorator]); function createEmptyValue(): EditorValue { return EditorValue.createEmpty(decorator); } function createValueFromString(markup: string, format: string): EditorValue { return EditorValue.createFromString(markup, format, decorator); } Object.assign(RichTextEditor, { EditorValue, decorator, createEmptyValue, createValueFromString, }); export {EditorValue, decorator, createEmptyValue, createValueFromString};
JavaScript
0.000001
@@ -1787,30 +1787,8 @@ ame%7D - onClick=%7Bthis._focus%7D %3E%0A
d86b65a2cdf50d9d9c8020cc420de973f40ee408
fix firebaseConfig
lib/client/firebaseConfig.js
lib/client/firebaseConfig.js
module.exports = {"apiKey":"AIzaSyAQ7YJxZruXp5RhMetYq1idFJ8-y0svN-s","authDomain":"artbot-dev.firebaseapp.com","databaseURL":"https://artbot-dev.firebaseio.com","storageBucket":"artbot-dev.appspot.com","messagingSenderId":"1001646388415"}
JavaScript
0.000005
@@ -32,40 +32,40 @@ aSyA -Q7YJxZruXp5RhMetYq1idFJ8-y0svN-s +j07kPi_C4eGAZBkV7ElSLEa_yg3sHoDc %22,%22a @@ -79,27 +79,29 @@ in%22:%22artbot- -dev +26016 .firebaseapp @@ -136,19 +136,21 @@ /artbot- -dev +26016 .firebas @@ -186,11 +186,13 @@ bot- -dev +26016 .app @@ -226,19 +226,19 @@ d%22:%22 -1001646388415 +493804710533 %22%7D +%0A
ebc230ce72f7b7de6237e73a875af6b8b5abd5ae
Add saveFile implementation into dataModifier.js
sashimi-webapp/src/database/data-modifier/dataModifier.js
sashimi-webapp/src/database/data-modifier/dataModifier.js
/* * CS3283/4 dataModifier.js * This acts as a facade class for modifying and update data for storage facade * */ import dataAdd from './dataAdd'; import dataDelete from './dataDelete'; import dataUpdate from './dataUpdate'; import exceptions from '../exceptions'; export default class dataModifier { static constructor() {} static deleteAllEntities() { dataDelete.deleteAllEntities(); } static createNewFile(organizationId, filePath, folderId) { if (typeof Promise === 'function') { return new Promise((resolve, reject) => { dataAdd.createNewFile(organizationId, filePath, folderId) .then((fileId) => { console.log('DATAMODIFIER'); console.log(fileId); resolve(fileId); }).catch(sqlErr => sqlErr); }); } else { throw new exceptions.PromiseFunctionNotDefined(); } } static createNewFolder(organizationId, folderPath, folderId) { if (typeof Promise === 'function') { return new Promise((resolve, reject) => { dataAdd.createNewFolder(organizationId, folderPath, folderId) .then(data => true) .catch(sqlErr => sqlErr); }); } else { throw new exceptions.PromiseFunctionNotDefined(); } } }
JavaScript
0.000001
@@ -1254,11 +1254,343 @@ %7D%0A %7D +%0A%0A static saveFile(fileId, file) %7B%0A if (typeof Promise === 'function') %7B%0A return new Promise((resolve, reject) =%3E %7B%0A resolve(dataUpdate.saveFile(fileId, file)%0A .then(() =%3E true))%0A .catch(sqlError =%3E sqlError);%0A %7D);%0A %7D else %7B%0A throw new exceptions.PromiseFunctionNotDefined();%0A %7D%0A %7D %0A%7D%0A
c88208ac07291631690ebd795f96e019a3a2f336
use aliasing
lib/hoodie-app.js
lib/hoodie-app.js
// Start a Hoodie app var fs = require("fs"); var http_proxy = require("http-proxy"); var hoodie_server = require("./hoodie-server"); var MultiCouch = require("multicouch"); var ltld; try { ltld = require("local-tld"); // TODO: check min version 2.0.0 } catch(e) { ltld = null; } var host = "0.0.0.0"; var http_port = parseInt(process.env.port, 10) || 80; var domain = "dev"; var package_json = JSON.parse(fs.readFileSync("./package.json")); var couchdb_url = process.env.couchdb_url; var name = package_json.name.toLowerCase(); var home = process.env.HOME; if(ltld) { var http_port = ltld.getPort(name); var couch_port = ltld.getPort("couch." + name); } // if we are on nodejitsu, we require couch_url. if(process.env.SUBDOMAIN) { // we are on nodejitsu domain = "jit.su"; // TODO: verify couchdb_url is reachable } else { console.log("Start local couch on port: %d", couch_port); // prepare hoodir dirs if they don’t exist: // mkdir -p $HOME/Application Support/Hoodie/Apps/myapp/ mkdir_p(home + "/Library/Hoodie"); mkdir_p(home + "/Library/Hoodie/Apps"); mkdir_p(home + "/Library/Hoodie/Apps/" + name); // if we are not on nodejitsu, make us a couch var couchdb = new MultiCouch({ prefix: home + "/Library/Hoodie/Apps/" + name, port: couch_port }); couchdb.on("start", function() { console.log("CouchDB Started"); }); couchdb.on("error", function(error) { console.log("CouchDB Error: %j", error); }); process.on("exit", function() { couchdb.stop(); console.log("CouchDB stop triggered by exit"); }); // on ctrl-c, stop couchdb first, then exit. process.on("SIGINT", function() { couchdb.on("stop", function() { process.exit(0); }); couchdb.stop(); }); couchdb.start(); } var hoo = new hoodie_server(couchdb, name, domain); // start frontend proxy var server = http_proxy.createServer(hoo); server.listen(http_port, function() { console.log("hoodie server started on port '%d'", http_port); console.log("Your app is ready now."); }); var worker_names = []; var deps = package_json.dependencies; for(var dep in deps) { if(dep.substr(0, 7) == "worker-") { worker_names.push(dep); } } // for each package_json/worker* var workers = worker_names.map(function(worker_name) { console.log("starting: '%s'", worker_name); // start worker var worker = require(worker_name); return new worker(process.env); }); console.log("All workers started."); function mkdir_p(dir) { try { fs.mkdirSync(dir); } catch(e) { // nope } }
JavaScript
0.000016
@@ -661,16 +661,94 @@ name);%0A + ltld.setAlias(name, %22www.%22 + name);%0A ltld.setAlias(name, %22admin.%22 + name);%0A %7D%0A%0A// if
45cf4df698f1c62b5b26b42fe8dd1fdbd5e0d137
Add meta charset in the html output.
lib/html-table.js
lib/html-table.js
module.exports = function(options) { var head = options.head; var rows = []; var tableRow = function(columns, tag, index) { var startTag = index % 2 == 0 ? tag.replace(/>$/, ' style=\'background-color:#eee\'>') : tag; var endTag = tag.replace(/^</, '</'); var body = []; body.push('<tr>'); columns.forEach(function(value) { body.push(startTag + value + endTag); }); body.push('</tr>'); return body.join('\n'); }; var buildPage = function() { var page = []; page.push('<!doctype html>'); page.push('<html>'); page.push('<head>'); page.push('<title>css-minification-benchmark results</title>'); page.push('</head>'); page.push('<body style=\'font-family:sans-serif\'>'); page.push('<table border=\'1\' cellpadding=\'3\' cellspacing=\'0\'>'); page.push('<thead>' + tableRow(head, '<th>', 0) + '</thead>'); page.push('<tbody>'); rows.forEach(function(row, index) { page.push(tableRow(row, '<td>', index + 1)); }); page.push('</tbody>'); page.push('</table>'); page.push('</body>'); page.push('</html>'); return page.join('\n'); }; return { push: function(row) { rows.push(row); }, toString: function() { return buildPage(); } }; };
JavaScript
0
@@ -537,15 +537,15 @@ ('%3C! -doctype +DOCTYPE htm @@ -592,32 +592,73 @@ push('%3Chead%3E');%0A + page.push('%3Cmeta charset=%22utf-8%22%3E');%0A page.push('%3C
4b87c9bf87359e22bdbc8aafb36e1a416c1b6bd2
Update service list tests
tests/services-list.state.spec.js
tests/services-list.state.spec.js
describe('Dashboard', function() { beforeEach(function() { module('app.states', 'app.components', 'app.config', 'gettext', bard.fakeToastr); bard.inject('$location', '$rootScope', '$state', '$templateCache', 'Session'); }); describe('route', function() { var views = { list: 'app/states/services/list/list.html' }; beforeEach(function() { bard.inject('$location', '$rootScope', '$state', '$templateCache'); }); it('should work with $state.go', function() { $state.go('services.explorer'); expect($state.is('services.explorer')); }); }); describe('controller', function() { var controller; var services = { name: 'services', count: 1, subcount: 1, resources: [] }; beforeEach(function() { bard.inject('$componentController', '$log', '$state', '$rootScope'); controller = $componentController('serviceExplorer'), {services: services}; }); it('should be created successfully', function() { expect(controller).to.be.defined; }); }); describe('service list contains power state in "timeout" and power status in "starting', function() { var controller; var services = { name: 'services', count: 1, subcount: 1, resources: [ {options: { powerState: "timeout", powerStatus: "starting" }} ] }; var serviceItem = services.resources[0].options; var Chargeback = { processReports: function(){}, adjustRelativeCost: function(){} }; beforeEach(function() { bard.inject('$componentController', '$log', '$state', '$rootScope'); controller = $componentController('serviceExplorer', {services: services, Chargeback: Chargeback}); }); it('sets the powerState value on the Service', function() { expect(serviceItem.powerState).to.eq('timeout'); }); it('sets the powerStatus value on the Service', function() { expect(serviceItem.powerStatus).to.eq('starting'); }); it('does not hide the kebab menu when "Start" operation times out', function() { expect(controller.hideMenuForItemFn(serviceItem)).to.eq(false); }); it('Shows the "Start" button when "Start" operation times out', function() { expect(controller.enableButtonForItemFn({}, serviceItem)).to.eq(true); }); it('displays "Stop" button when action is "stop"', function() { var action = {actionName: 'stop'}; controller.updateMenuActionForItemFn(action, serviceItem); expect(action.isDisabled).to.eq(false); }); it('displays "Suspend" button when action is "suspend"', function() { var action = {actionName: 'suspend'}; controller.updateMenuActionForItemFn(action, serviceItem); expect(action.isDisabled).to.eq(false); }); }); describe('service list contains power state in "on" and power status in "start_complete', function() { var controller; var services = { name: 'services', count: 1, subcount: 1, resources: [ {options: { powerState: "on", powerStatus: "start_complete" }} ] }; var serviceItem = services.resources[0].options; var Chargeback = { processReports: function(){}, adjustRelativeCost: function(){} }; var PowerOperations = { powerOperationOnState: function (item) { return item.powerState === "on" && item.powerStatus === "start_complete"; }, powerOperationUnknownState: function (item) { return item.powerState === "" && item.powerStatus === ""; }, powerOperationInProgressState: function (item) { return (item.powerState !== "timeout" && item.powerStatus === "starting") || (item.powerState !== "timeout" && item.powerStatus === "stopping") || (item.powerState !== "timeout" && item.powerStatus === "suspending"); }, powerOperationOffState: function (item) { return item.powerState === "off" && item.powerStatus === "stop_complete"; }, powerOperationSuspendState: function (item) { return item.powerState === "off" && item.powerStatus === "suspend_complete"; }, powerOperationTimeoutState: function (item) { return item.powerState === "timeout"; }, }; beforeEach(function() { bard.inject('$componentController', '$log', '$state', '$rootScope'); controller = $componentController('serviceExplorer', {services: services, Chargeback: Chargeback, PowerOperations: PowerOperations}); }); it('sets the powerState value on the Service', function() { expect(controller.powerOperationOnState(serviceItem)).to.eq(true); }); it('does not hide the kebab menu when "Start" operation leads to an "ON" power state', function() { expect(controller.hideMenuForItemFn(serviceItem)).to.eq(false); }); it('hides the "Start" button when power state is "ON"', function() { expect(controller.enableButtonForItemFn(undefined, serviceItem)).to.eq(false); }); it('displays "Stop" button when action is "stop"', function() { var action = {actionName: 'stop'}; controller.updateMenuActionForItemFn(action, serviceItem); expect(action.isDisabled).to.eq(false); }); it('displays "Suspend" button when action is "suspend"', function() { var action = {actionName: 'suspend'}; controller.updateMenuActionForItemFn(action, serviceItem); expect(action.isDisabled).to.eq(false); }); }); });
JavaScript
0
@@ -2274,32 +2274,74 @@ ', function() %7B%0A + var action = %7BactionName: 'start'%7D;%0A expect(con @@ -2344,34 +2344,38 @@ (controller. -enableButt +updateMenuActi onForItemFn( @@ -2374,18 +2374,22 @@ rItemFn( -%7B%7D +action , servic @@ -2525,32 +2525,39 @@ 'stop'%7D;%0A +expect( controller.updat @@ -2601,40 +2601,8 @@ tem) -;%0A expect(action.isDisabled ).to @@ -2738,32 +2738,39 @@ uspend'%7D;%0A +expect( controller.updat @@ -2814,40 +2814,8 @@ tem) -;%0A expect(action.isDisabled ).to @@ -5015,32 +5015,74 @@ ', function() %7B%0A + var action = %7BactionName: 'start'%7D;%0A expect(con @@ -5093,18 +5093,22 @@ ler. -enableButt +updateMenuActi onFo @@ -5119,17 +5119,14 @@ mFn( -undefined +action , se @@ -5267,32 +5267,39 @@ 'stop'%7D;%0A +expect( controller.updat @@ -5343,40 +5343,8 @@ tem) -;%0A expect(action.isDisabled ).to @@ -5484,24 +5484,31 @@ nd'%7D;%0A +expect( controller.u @@ -5556,40 +5556,8 @@ tem) -;%0A expect(action.isDisabled ).to
de9a95211ce54c6e416675bfc07edd08345f1746
Change settings for uploading chunks
Dashboard/app/js/lib/views/data/bulk-upload-view.js
Dashboard/app/js/lib/views/data/bulk-upload-view.js
/*global Resumable, FLOW, $, Ember */ FLOW.uuid = function (file) { return Math.uuidFast(); }; FLOW.uploader = Ember.Object.create({ r: new Resumable({ target: FLOW.Env.flowServices + '/upload', uploadDomain: FLOW.Env.surveyuploadurl.split('/')[2], simultaneousUploads: 4, testChunks: false, throttleProgressCallbacks: 1, // 1s chunkRetryInterval: 1000, // 1s chunkSize: 512 * 1024, // 512KB, generateUniqueIdentifier: FLOW.uuid }), assignDrop: function (el) { return this.get('r').assignDrop(el); }, assignBrowse: function (el) { return this.get('r').assignBrowse(el); }, support: function () { return this.get('r').support; }.property(), upload: function () { return this.get('r').upload(); }, pause: function () { return this.get('r').pause(); }, isUploading: function () { return this.get('r').isUploading(); }, cancel: function () { return this.get('r').cancel(); }, addFile: function (file) { return this.get('r').addFile(file); }, registerEvents: function () { var r = this.get('r'); // Handle file add event r.on('fileAdded', function (file) { var li; FLOW.uploader.set('cancelled', false); // Show progress pabr $('.resumable-progress, .resumable-list').show(); // Show pause, hide resume // $('.resumable-progress .progress-resume-link').hide(); // $('.resumable-progress .progress-pause-link').show(); // Add the file to the list li = $('.resumable-file-' + file.uniqueIdentifier); if (li.length === 0) { $('.resumable-list').append('<li class="resumable-file-' + file.uniqueIdentifier + '">Uploading <span class="resumable-file-name"></span> <span class="resumable-file-progress"></span>'); } $('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-name').html(file.fileName); $('.progress-bar').css({ width: '0%' }); // Actually start the upload r.upload(); }); r.on('pause', function () { // Show resume, hide pause $('.resumable-progress .progress-resume-link').show(); $('.resumable-progress .progress-pause-link').hide(); }); r.on('complete', function () { // Hide pause/resume when the upload has completed $('.resumable-progress .progress-resume-link, .resumable-progress .progress-pause-link').hide(); if (!FLOW.uploader.get('cancelled')) { FLOW.uploader.showCompleteMessage(); } }); r.on('fileSuccess', function (file, message) { var data = { uniqueIdentifier: file.uniqueIdentifier, filename: file.fileName, baseURL: location.protocol + '//' + location.host, uploadDomain: this.opts.uploadDomain }; if (file.fileName.toUpperCase().indexOf('.XLSX') !== -1) { data.surveyId = FLOW.selectedControl.selectedSurvey.get('id'); } // Reflect that the file upload has completed $('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-progress').html('(completed)'); $.ajax({ url: this.opts.target, cache: false, type: 'POST', data: data }); }); r.on('fileError', function (file, message) { // Reflect that the file upload has resulted in error $('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-progress').html('(file could not be uploaded: ' + message + ')'); }); r.on('fileProgress', function (file) { // Handle progress for both the file and the overall upload $('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-progress').html(Math.floor(file.progress() * 100) + '%'); $('.progress-bar').css({ width: Math.floor(r.progress() * 100) + '%' }); }); }, showCancelledMessage: function () { FLOW.dialogControl.set('activeAction', 'ignore'); FLOW.dialogControl.set('header', Ember.String.loc('_upload_cancelled')); FLOW.dialogControl.set('message', Ember.String.loc('_upload_cancelled_due_to_navigation')); FLOW.dialogControl.set('showCANCEL', false); FLOW.dialogControl.set('showDialog', true); }, showCompleteMessage: function () { FLOW.dialogControl.set('activeAction', 'ignore'); FLOW.dialogControl.set('header', Ember.String.loc('_upload_complete')); FLOW.dialogControl.set('message', Ember.String.loc('_upload_complete_message')); FLOW.dialogControl.set('showCANCEL', false); FLOW.dialogControl.set('showDialog', true); } }); FLOW.BulkUploadAppletView = FLOW.View.extend({ didInsertElement: function () { FLOW.uploader.assignDrop($('.resumable-drop')[0]); FLOW.uploader.assignBrowse($('.resumable-browse')[0]); FLOW.uploader.registerEvents(); }, willDestroyElement: function () { FLOW.uploader.set('cancelled', FLOW.uploader.isUploading()); FLOW.uploader.cancel(); this._super(); } }); /* Show warning when trying to close the tab/window with an upload process in progress */ window.onbeforeunload = function (e) { var confirmationMessage = Ember.String.loc('_upload_in_progress'); if (FLOW.uploader.isUploading()) { (e || window.event).returnValue = confirmationMessage; return confirmationMessage; } };
JavaScript
0
@@ -281,17 +281,17 @@ ploads: -4 +1 ,%0A te @@ -3087,22 +3087,34 @@ ted)');%0A +%0A +setTimeout( $.ajax(%7B @@ -3208,33 +3208,40 @@ a: data%0A %7D) -; +, 500);%0A %0A %7D);%0A%0A r.