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
2e4c5c76638de5abf18458bfb7ae57ed104c1683
remove failing test
frontend/src/components/RoomCard/RoomCard.test.js
frontend/src/components/RoomCard/RoomCard.test.js
test('It is hello world!', () => { expect('hello world!').toBe('hello world!'); }); test('It is failing', () => { expect('hello world!').toBe('not hello world!'); });
JavaScript
0.000091
@@ -83,89 +83,4 @@ %7D);%0A -%0Atest('It is failing', () =%3E %7B%0A expect('hello world!').toBe('not hello world!');%0A%7D);
2b549dbe5dacd391981854c2f18b2e18108c6af7
make CountDays provide correct array
src/helpers/day-counter.js
src/helpers/day-counter.js
const countDays = (startDate, endDate) => { console.log({startDate, endDate}); const yearInDays = [] let currentDate = startDate console.log({currentDate, 'typeof': typeof currentDate}); // let currentDate = new Date() while (currentDate <= endDate) { yearInDays.push(currentDate) currentDate = currentDate.setDate(currentDate.getDate() + 1) } return yearInDays.reduce((counter, day) => { counter[day] ? counter[day]++ : counter[day] = 1 return counter }, {}) } const now = new Date() const thisYear = now.getFullYear() const [startDate, endDate] = [new Date(`01/01/${thisYear}`), new Date(`12/31/${thisYear}`)] export default countDays(startDate, endDate) // returns an object with keys corresponding to each day of the week, and respective values which count how many of those occur during the specified date range, in our case thisYear.
JavaScript
0.005482
@@ -42,46 +42,8 @@ %7B%0D%0A - console.log(%7BstartDate, endDate%7D);%0D%0A co @@ -100,76 +100,50 @@ %0D%0A -console.log(%7BcurrentDate, 'typeof': typeof current +// let currentDate = new Date -%7D); +() %0D%0A -// let +while ( curr @@ -150,39 +150,35 @@ entDate +%3C = -new +end Date -( ) + %7B %0D%0A -while ( + currentD @@ -177,37 +177,47 @@ currentDate -%3C = +new Date(curr en -d +t Date) - %7B %0D%0A yearIn @@ -233,24 +233,33 @@ (currentDate +.getDay() )%0D%0A curre
1f033d217c9875f5882dc877f1fd834fe96a5a51
Update parameter labels
cd/src/pipeline-events-handler/deltas/deltas.js
cd/src/pipeline-events-handler/deltas/deltas.js
const getStackFamily = require('./stack-family'); const getChangeSetFamily = require('./change-set-family'); const deltaArrow = require('./delta-arrow'); const deltaValue = require('./delta-value'); /** * Returns a multi-line string describing the parameters that have changed * @param {ParameterDeltas} deltas * @returns {String} */ function parameterDeltasList(deltas) { if (!deltas.length) { return 'This change set contained no meaningful parameter deltas.'; } // Text blocks within attachments have a 3000 character limit. If the text is // too large, try creating the list without links to reduce the size. const withLinks = deltas .map((d) => { const oldValue = deltaValue(d.parameter, d.stackValue); const arrow = deltaArrow(d); const newValue = deltaValue(d.parameter, d.changeSetValue); let label; if ( [ 'infrastructure-cd-root-staging', 'infrastructure-cd-root-production', ].includes(d.stackName) ) { // For root stack parameters, label with just the parameter name label = d.parameter; } else { // For nested stacks, try to extract some meaningful part of the stack // name that is useful to include const nickname = d.stackName.split('-').at(-2); label = `${nickname}::${d.parameter}`; } return `*${label}*: ${oldValue} ${arrow} ${newValue}`; }) .join('\n'); if (withLinks.length < 2900) { return withLinks; } else { return deltas .map((d) => { const oldValue = deltaValue(d.parameter, d.stackValue, true); const arrow = deltaArrow(d, true); const newValue = deltaValue(d.parameter, d.changeSetValue, true); return `*${d.stackName}::${d.parameter}*: ${oldValue} ${arrow} ${newValue}`; }) .join('\n'); } } module.exports = { async nestedParameterDeltaText(stackName, changeSetName) { let stackFamily = await getStackFamily(stackName); const changeSetFamily = await getChangeSetFamily(stackName, changeSetName); const changeSetFamilyStackIds = changeSetFamily.map((c) => c.StackId); // When there's only a single change set, it likely means that nested // change sets was disabled for the given change set. In these cases, only // the root stack's parameters should be included in the deltas, because // there won't be anything to compare the child stacks to, and all // parameters will look like they've changed. if (changeSetFamily.length === 1) { stackFamily = [stackFamily[0]]; } /** @type {ParameterDeltas} */ const deltas = []; // Iterate through all existing stack parameters and create a delta for // each one, which includes the current value. for (const stack of stackFamily) { // Not all nested stacks are guaranteed to be have a change set. If a // stack in the stack family does not have a corresponding change set, // and the deltas are determined strictly by finding matching values in // the stack and change set families, all parameters for that stack would // appear to be unmatched. So, if there is no corresponding change set // for a given stack, that stack's parameters should not be included in // the deltas. (If there is a change set with no corresponding stack, // those deltas *will* still be included below.) if (changeSetFamilyStackIds.includes(stack.StackId)) { for (const param of stack.Parameters || []) { deltas.push({ stackName: stack.StackName, stackId: stack.StackId, parameter: param.ParameterKey, stackValue: param.ResolvedValue || param.ParameterValue, changeSetValue: null, }); } } } // Iterate through all the change set parameters. If a delta already exists // for a given stack+parameter key, add the value from the change set to // that delta. If not, make a new delta. for (const changeSet of changeSetFamily) { for (const param of changeSet.Parameters || []) { const delta = deltas.find( (d) => param.ParameterKey === d.parameter && changeSet.StackName === d.stackName, ); if (delta) { delta.changeSetValue = param.ResolvedValue || param.ParameterValue; } else { deltas.push({ stackName: changeSet.StackName, stackId: changeSet.StackId, parameter: param.ParameterKey, stackValue: null, changeSetValue: param.ResolvedValue || param.ParameterValue, }); } } } // Filter down to only deltas where the values are different const changeDeltas = deltas.filter( (d) => d.stackValue !== d.changeSetValue, ); // When using nested change sets, not all parameters in nested stacks are // correctly resolved. Any parameter values that depend on a stack or // resource output will be included in the change set parameters with an // unresolved value that looks like "{{IntrinsicFunction:…". Unless or until // AWS makes nested change sets smarter, we have to just ignore these, // because there's no way to compare the actual existing value from the stack // to the hypothetical future value that will be resolved when the change set // executes. // // Any parameters effected by this limitation are filtered out. const cleanedDeltas = changeDeltas.filter( (d) => !(d.changeSetValue || '').match(/\{\{IntrinsicFunction\:/), ); // Some additional parameters that don't make sense to display in Slack are // also filtered out. const allowedDeltas = cleanedDeltas.filter( (d) => ![ 'PipelineExecutionNonce', 'TemplateUrlBase', 'TemplateUrlPrefix', ].includes(d.parameter), ); console.log(JSON.stringify(allowedDeltas)); return parameterDeltasList(allowedDeltas); }, };
JavaScript
0.000001
@@ -1745,46 +1745,576 @@ -return %60*$%7Bd.stackName%7D::$%7Bd.parameter +let label;%0A%0A if (%0A %5B%0A 'infrastructure-cd-root-staging',%0A 'infrastructure-cd-root-production',%0A %5D.includes(d.stackName)%0A ) %7B%0A // For root stack parameters, label with just the parameter name%0A label = d.parameter;%0A %7D else %7B%0A // For nested stacks, try to extract some meaningful part of the stack%0A // name that is useful to include%0A const nickname = d.stackName.split('-').at(-2);%0A label = %60$%7Bnickname%7D::$%7Bd.parameter%7D%60;%0A %7D%0A%0A return %60*$%7Blabel %7D*:
037144d8a3e856a83b0a5d26e35c234d75856c83
Remove onOffSwitch check from rule summarizing
static/js/rules/Rule.js
static/js/rules/Rule.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/.* */ /* global API */ /** * Model of a Rule loaded from the Rules Engine * @constructor * @param {Gateway} gateway - The remote gateway to which to talk * @param {RuleDescription?} desc - Description of the rule to load * @param {Function?} onUpdate - Listener for when update is called */ function Rule(gateway, desc, onUpdate) { this.gateway = gateway; this.onUpdate = onUpdate; if (desc) { this.id = desc.id; this.enabled = desc.enabled; if (desc.name) { this.name = desc.name; } else { this.name = 'Rule Name'; } this.trigger = desc.trigger; this.effect = desc.effect; } else { this.enabled = true; } } /** * Validate and save the rule * @return {Promise} */ Rule.prototype.update = function() { if (this.onUpdate) { this.onUpdate(); } let desc = this.toDescription(); if (!desc) { return Promise.reject('invalid description'); } let fetchOptions = { headers: API.headers(), method: 'PUT', body: JSON.stringify(desc) }; fetchOptions.headers['Content-Type'] = 'application/json'; let request = null; if (typeof(this.id) !== 'undefined') { request = fetch('/rules/' + this.id, fetchOptions); } else { fetchOptions.method = 'POST'; request = fetch('/rules/', fetchOptions).then(res => { return res.json(); }).then(rule => { this.id = rule.id; }); } return request; }; /** * Delete the rule * @return {Promise} */ Rule.prototype.delete = function() { let fetchOptions = { headers: API.headers(), method: 'DELETE' }; if (typeof(this.id) === 'undefined') { return; } return fetch('/rules/' + this.id, fetchOptions); }; /** * Convert this rule into a serialized description * @return {RuleDescription?} description or null if not a valid rule */ Rule.prototype.toDescription = function() { if (!this.trigger || !this.effect) { return null; } return { enabled: this.enabled, name: this.name, trigger: this.trigger, effect: this.effect }; }; // Helper function for selecting the thing corresponding to a property const RuleUtils = { byProperty: function byProperty(property) { return function(option) { let optProp = option.properties[property.name]; return optProp && (optProp.href === property.href); }; } }; /** * Convert the rule's trigger's description to a human-readable string * @return {String} */ Rule.prototype.toTriggerHumanDescription = function() { let triggerThing = this.gateway.things.filter( RuleUtils.byProperty(this.trigger.property) )[0]; let triggerStr = `${triggerThing.name} `; if (this.trigger.type === 'BooleanTrigger') { triggerStr += 'is '; if (!this.trigger.onValue) { triggerStr += 'not '; } triggerStr += this.trigger.property.name; } else { triggerStr += `${this.trigger.property.name} is `; if (this.trigger.levelType === 'LESS') { triggerStr += 'less than '; } else { triggerStr += 'greater than '; } triggerStr += this.trigger.level; } return triggerStr; }; /** * Convert the rule's effect's description to a human-readable string * @return {String} */ Rule.prototype.toEffectHumanDescription = function() { let effectThing = this.gateway.things.filter( RuleUtils.byProperty(this.effect.property) )[0]; let effectStr = ''; if (this.effect.property.name === 'on' && effectThing.type === 'onOffSwitch') { effectStr = `turn ${effectThing.name} `; if (this.effect.value) { effectStr += 'on'; } else { effectStr += 'off'; } if (this.effect.type === 'SET') { effectStr += ' permanently'; } return effectStr; } if (this.effect.type === 'SET') { effectStr += 'set '; } else { effectStr += 'pulse '; } effectStr += `${effectThing.name} ${this.effect.property.name} to `; effectStr += this.effect.value; return effectStr; }; /** * Convert the rule's description to a human-readable string * @return {String} */ Rule.prototype.toHumanDescription = function() { let triggerStr = '???'; let effectStr = '???'; if (this.trigger) { triggerStr = this.toTriggerHumanDescription(); } if (this.effect) { effectStr = this.toEffectHumanDescription(); } return 'If ' + triggerStr + ' then ' + effectStr; }; /** * Set the trigger of the Rule, updating the server model if valid * @return {Promise} */ Rule.prototype.setTrigger = function(trigger) { this.trigger = trigger; return this.update(); }; /** * Set the effect of the Rule, updating the server model if valid * @return {Promise} */ Rule.prototype.setEffect = function(effect) { this.effect = effect; return this.update(); };
JavaScript
0
@@ -3621,50 +3621,8 @@ 'on' - &&%0A effectThing.type === 'onOffSwitch' ) %7B%0A
297dadc8b74ec5649704c2f42f390412862b05a2
Update TeamEditPageModelView.js
app/scripts/TeamEditPage/TeamEditPageModelView.js
app/scripts/TeamEditPage/TeamEditPageModelView.js
/* TeamEditPage */ (function(module, sstt) { module.ModelView = Backbone.View.extend({ template: JST['app/scripts/TeamEditPage/TeamEditPageTpl.ejs'], events: { "click #watchers": "showWatchers", "click #developers": "showDevelopers", "click #techleads": "showTeachLeads", "click #ok_btn": "hideConfirm" }, subscriptions: { "TeamPage:TeamSelected": "render", "ContextMenu:Back": "removeTeamPage", "ContextMenu:BackFromTeamEditPage": "removeTeamPage" }, render: function(team_id) { this.$el.append(this.template()); mediator.pub("TeamEditPage:Open", { element: this.$el, team_id: team_id }); this.showWatchers(); return this; }, showWatchers: function() { mediator.pub("TeamEditPage:RoleSetUp", "watcher"); }, showDevelopers: function() { mediator.pub("TeamEditPage:RoleSetUp", "developer"); }, showTeachLeads: function() { mediator.pub("TeamEditPage:RoleSetUp", "techlead"); }, hideConfirm: function() { this.$el.find("#save_confirm").addClass("hidden"); }, removeTeamPage: function() { this.$el.removeClass("hiddenTeams"); this.$el.find(".team-edit-page").remove(); } }); })(app.TeamEditPage, sstt);
JavaScript
0.000001
@@ -939,21 +939,23 @@ his.show -Watch +Develop ers();%0A%0A @@ -1120,223 +1120,775 @@ -%7D,%0A%0A showDevelopers: function() %7B%0A mediator.pub(%22TeamEditPage:RoleSetUp%22, %22developer%22);%0A %7D,%0A%0A showTeachLeads: function() %7B%0A mediator.pub(%22TeamEditPage:RoleSetUp%22, %22techlead + $(%22#watchers%22).css(%22background-color%22, %22white%22);%0A $(%22#developers%22).css(%22background-color%22, %22none%22);%0A $(%22#techleads%22).css(%22background-color%22, %22none%22);%0A %7D,%0A%0A showDevelopers: function() %7B%0A mediator.pub(%22TeamEditPage:RoleSetUp%22, %22developer%22);%0A $(%22#watchers%22).css(%22background-color%22, %22none%22);%0A $(%22#developers%22).css(%22background-color%22, %22white%22);%0A $(%22#techleads%22).css(%22background-color%22, %22none%22);%0A %7D,%0A%0A showTeachLeads: function() %7B%0A mediator.pub(%22TeamEditPage:RoleSetUp%22, %22techlead%22);%0A $(%22#watchers%22).css(%22background-color%22, %22none%22);%0A $(%22#developers%22).css(%22background-color%22, %22none%22);%0A $(%22#techleads%22).css(%22background-color%22, %22white %22);%0A
b85bd0b1a6dff515713b611b2745de283d56aa8a
fix battle pets total
app/scripts/controllers/application.controller.js
app/scripts/controllers/application.controller.js
'use strict'; (function() { angular .module('simpleArmoryApp') .controller('ApplicationCtrl' , ApplicationCtrl); function ApplicationCtrl($scope, LoginService, $location, $filter) { // default to not logged in $scope.isLoggedIn = false; // Listen for path changed and then parse and fetch the character $scope.$on('$locationChangeSuccess', function(){ // If there was an error we need to reset everything if ($location.$$path === '/error') { $scope.character = null; $scope.isLoggedIn = false; } else if ($location.$$path !== '' && $location.$$path !== '/') { // "us/proudmoore/marko" // [0]: us/proudmoore/marko // [1]: spirestone // [2]: marko // [3]: location part var rgr = new RegExp('([^\/]+)/([^\/]+)/([^\/]+)/?([^\/]+)?').exec($location.$$path); rgr = rgr ? rgr : {}; LoginService.getCharacter({'region': rgr[1], 'realm':rgr[2], 'character':rgr[3]}) .then(function(character) { $scope.character = character[0]; $scope.isLoggedIn = true; }); } }); // Helper function for percentage numbers. Used in a lot of screens $scope.percent = function(n, d) { return $filter('number')(((n / d) * 100), 0); }; $scope.achFormater = function(n, d) { if (!n || !d) { return ""; } return '' + n + ' / ' + d + ' (' + $scope.percent(n, d) + '%)'; }; // Helper to get the image id off an item $scope.getImageSrc = function(item) { if (item.collected) { // wowhead img return 'http://wow.zamimg.com/images/wow/icons/medium/' + item.icon.toLowerCase() + '.jpg'; } else { // 1x1 gif return 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; } }; } })();
JavaScript
0
@@ -1604,10 +1604,10 @@ urn -%22%22 +'' ;%0A @@ -1610,32 +1610,33 @@ ;%0A %7D%0A +%0A %0A @@ -1631,16 +1631,225 @@ +var perc = $scope.percent(n, d);%0A%0A // if the percentage is low enough, don't print the numbers, just use the percentage%0A if (perc %3C 18) %7B%0A return perc + '%25';%0A %7D%0A %0A @@ -1888,36 +1888,20 @@ ' (' + -$scope.percent(n, d) +perc + '%25)';
d2457d8a3fd797332332bd50a6fb2044c66a203a
Fix MediaKeys with new mpris API MediaKeys code only works for Mate and older version of gnome All OSs using gnome3 use MPRIS to send mediakey shortcuts
linux/lib/registerMediaKeys.js
linux/lib/registerMediaKeys.js
const DBus = require('dbus-next'); const debug = require('debug'); const { ipcMain } = require('electron'); const logger = debug('headset:mediaKeys'); let track = null; ipcMain.on('win2Player', (e, args) => { if (args[0] === 'trackInfo') { track = args[1]; } }); function executeMediaKey(win, key) { logger('Executing %o media key command', key); win.webContents.executeJavaScript(` window.electronConnector.emit('${key}') `); } async function registerBindings(win, desktopEnv, bus) { let serviceName = `org.${desktopEnv}.SettingsDaemon`; let objectPath = `/org/${desktopEnv}/SettingsDaemon/MediaKeys`; let interfaceName = `org.${desktopEnv}.SettingsDaemon.MediaKeys`; if (desktopEnv === 'gnome3') { serviceName = 'org.gnome.SettingsDaemon.MediaKeys'; objectPath = '/org/gnome/SettingsDaemon/MediaKeys'; interfaceName = 'org.gnome.SettingsDaemon.MediaKeys'; } try { const settings = await bus.getProxyObject(serviceName, objectPath); const mediaKeys = settings.getInterface(interfaceName); mediaKeys.on('MediaPlayerKeyPressed', (iface, n, keyName) => { logger('Media key pressed: %o', keyName); switch (keyName) { case 'Next': executeMediaKey(win, 'play-next'); break; case 'Previous': executeMediaKey(win, 'play-previous'); break; case 'Play': if (track !== null) executeMediaKey(win, 'play-pause'); break; default: } }); mediaKeys.GrabMediaPlayerKeys('headset', 0); logger('Grabbed media keys for %o', desktopEnv); } catch (err) { // Error if trying to grab keys in another desktop environment } } module.exports = (win) => { logger('Registering media Keys'); const bus = DBus.sessionBus(); registerBindings(win, 'gnome', bus); registerBindings(win, 'gnome3', bus); registerBindings(win, 'mate', bus); };
JavaScript
0
@@ -1094,11 +1094,8 @@ ace, - n, key
1294e4c335e1b006a0b718a1795b0bd92f66be84
rename tests folder to test
local/config/src/playwright.js
local/config/src/playwright.js
const { devices } = require('@playwright/test'); module.exports = { testMatch: /.*\/tests\/playwright\/.*\.test\.[jt]sx?/, timeout: 10 * 60 * 1500, navigationTimeout: 1000, retries: 0, maxFailures: 0, workers: 4, fullyParallel: true, reporter: 'list', projects: [ { name: 'Chromium', use: { ...devices['Desktop Chromium'], headless: false, }, }, /* { name: 'Firefox', use: { ...devices['Desktop Firefox'], headless: false, }, }, { name: 'Safari', use: { ...devices['Desktop Safari'], headless: false, }, }, */ ], };
JavaScript
0.000001
@@ -84,17 +84,16 @@ .*%5C/test -s %5C/playwr
9894125e223eb2f13948cf1ef4fa970187dc69e1
update typo
problems/003_longest-substring-without-repeating-characters/index.js
problems/003_longest-substring-without-repeating-characters/index.js
/** * @param {string} s * @return {number} */ var lengthOfLongestSubstring = function(s) { var maxLen = 0, numArr = [], index; for (var i = 0; i < s.length; i++) { index = numArr.indexOf(s[i]); if (index !== -1) { numArr = numArr.slice(index + 1, numArr.length); } numArr.push(s[i]); maxLen = numArr.length > maxLen ? numArr.length : maxLen; } return maxLen; }; module.exports = lengthOfLongestSubstring;
JavaScript
0.000004
@@ -105,19 +105,19 @@ en = 0, -num +sub Arr = %5B%5D @@ -176,19 +176,19 @@ index = -num +sub Arr.inde @@ -232,20 +232,20 @@ -num +sub Arr = -num +sub Arr. @@ -261,19 +261,19 @@ ex + 1, -num +sub Arr.leng @@ -287,19 +287,19 @@ %7D%0A -num +sub Arr.push @@ -319,19 +319,19 @@ axLen = -num +sub Arr.leng @@ -344,19 +344,19 @@ axLen ? -num +sub Arr.leng
02c62c48f437a4c873e4dc1cebfe41ac418be7cd
Fix the "reloaded" link on about:net-internals.
chrome/browser/resources/net_internals/index.js
chrome/browser/resources/net_internals/index.js
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. <include src="util.js"/> <include src="view.js"/> <include src="tab_switcher_view.js"/> <include src="data_view.js"/> <include src="http_cache_view.js"/> <include src="test_view.js"/> <include src="hsts_view.js"/> <include src="browser_bridge.js"/> <include src="source_tracker.js"/> <include src="main.js"/> <include src="dns_view.js"/> <include src="source_row.js"/> <include src="events_view.js"/> <include src="details_view.js"/> <include src="source_entry.js"/> <include src="resizable_vertical_split_view.js"/> <include src="top_mid_bottom_view.js"/> <include src="timeline_view_painter.js"/> <include src="log_view_painter.js"/> <include src="log_grouper.js"/> <include src="proxy_view.js"/> <include src="socket_pool_wrapper.js"/> <include src="sockets_view.js"/> <include src="spdy_view.js"/> <include src="service_providers_view.js"/> <include src="http_throttling_view.js"/> <include src="logs_view.js"/> <include src="prerender_view.js"/> document.addEventListener('DOMContentLoaded', function () { $('reloaded-link').addEventListener('click', function () { history.go(0); }); onLoaded(); // from main.js });
JavaScript
0.002524
@@ -1228,24 +1228,29 @@ , function ( +event ) %7B%0A hist @@ -1260,16 +1260,44 @@ .go(0);%0A + event.preventDefault();%0A %7D);%0A
2c01ff1c4d344d50254edbdb8ea87f46a2fbb1f6
fix missing slugify (bug 1049858)
src/media/js/app_selector.js
src/media/js/app_selector.js
define('app_selector', ['jquery', 'format', 'l10n', 'log', 'requests', 'settings', 'templates', 'underscore', 'urls', 'utils', 'utils_local', 'z'], function($, format, l10n, log, requests, settings, nunjucks, _, urls, utils, utils_local, z) { 'use strict'; var gettext = l10n.gettext; var results_map = {}; z.page.on('keypress input', '.app-selector input', _.debounce(function() { var $app_selector = $('.app-selector'); $app_selector.find('.paginator').attr('data-offset', 0); if (this.value.length > 2) { $('.loading').show(); $app_selector.addClass('focused'); search_handler(this.value, 0); } else { $app_selector.removeClass('focused'); $('.results').hide(); } }, 250)) .on('click', '.app-selector .paginator a:not(.disabled)', function() { var $this = $(this); var $paginator = $this.closest('.paginator'); $('.results').hide(); $('.loading').show(); var offset = parseInt($paginator.data('offset') || 0, 10); offset = $this.hasClass('prev') ? (offset - 5) : (offset + 5); search_handler($('.app-selector input').val(), offset); $paginator.data('offset', offset); }) .on('click', '.app-selector .result', function(evt) { evt.preventDefault(); // To prevent click-off to app detail page. var $app_selector = $('.app-selector'); var $this = $(this); $app_selector.find('input[name="app"]').val($this.data('id')); // Trigger with ID. $('.results').hide(); $app_selector.removeClass('focused'); $('#app-selector').val(''); if (z.body.is('[data-page-type~="apps"]')) { $('#slug').val(utils_local.slugify($this.find('.name a').text())); } z.page.trigger('app-selected', [results_map[$this.attr('data-id')]]); }); function get_disabled_regions(app) { // Given app, do set difference between all regions and app's regions // to get the disabled regions. return Object.keys(settings.REGION_CHOICES_SLUG).filter(function(slug) { return app.regions .map(function(region) { return region.slug; }) .indexOf(slug) < 0; }); } var render_result = function(app, with_actions) { return nunjucks.env.render('app_selector/app_selector_result.html', { author: app.author, detail_url: settings.api_url + '/app/' + app.slug, device_types: app.device_types, disabled_regions: get_disabled_regions(app), icon: app.icons['32'], id: app.id, name: utils.translate(app.name), price: app.payment_required ? app.price_locale : gettext('Free'), rating: app.ratings.average, with_actions: with_actions }); }; function search_handler(q, offset) { var $paginator = $('.app-selector .paginator'); var $results = $('.results'); // Search. var search_url = urls.api.unsigned.params( 'search', {'q': q, 'limit': 5, 'offset': offset}); requests.get(search_url).done(function(data) { $results.find('.result').remove(); $results.show(); // Append results. if (data.objects.length === 0) { var no_results = nunjucks.env.render( 'app_selector/app_selector_no_results.html', {}); $paginator.hide(); $results.append(no_results); } else { $paginator.show(); for (var i = 0; i < data.objects.length; i++) { $results.append(render_result(data.objects[i])); results_map[data.objects[i].id] = data.objects[i]; } } var $desc = $paginator.find('.desc'); var $next = $paginator.find('.next'); var $prev = $paginator.find('.prev'); var meta = data.meta; if (!meta.previous && !meta.next) { $paginator.hide(); } else { $paginator.show(); if (meta.previous) { $prev.removeClass('disabled'); } else { $prev.addClass('disabled'); } if (meta.next) { $next.removeClass('disabled'); } else { $next.addClass('disabled'); } // L10n: {0} refers to the position of the first app on the page, // {1} refers to the position of the last app on the page, // and {2} refers to the total number of apps across all pages. var desc = format.format(gettext('Apps {0}-{1} of {2}.'), (meta.offset + 1), (meta.offset + meta.limit), meta.total_count); $desc.text(desc); } $('.loading').hide(); }); } return { render_result: render_result }; });
JavaScript
0.000015
@@ -127,23 +127,8 @@ ls', - 'utils_local', 'z' @@ -214,21 +214,8 @@ ils, - utils_local, z) @@ -1749,22 +1749,16 @@ al(utils -_local .slugify
03fa8cdfd45a30ed1282b1e161690a13b405088f
Update wrapper example with Cycle Streams
rx-run/examples/synthetic-examples/wrapper-custom-element/wrapper.js
rx-run/examples/synthetic-examples/wrapper-custom-element/wrapper.js
var h = Cycle.h; var Rx = Cycle.Rx; Cycle.registerCustomElement('wrapper-element', function (user, props) { var view = Cycle.createView(function (props) { return { vtree$: props.get('children$').map(function (children) { return h('div.wrapper', {style: {backgroundColor: 'lightgray'}}, children); }) }; }); user.inject(view).inject(props); }); var view = Cycle.createView(function () { return { vtree$: Rx.Observable.just( h('div.everything', [ h('wrapper-element', {key: 1}, [ h('h3', 'I am supposed to be inside a gray box.') ]) ]) ) }; }); var user = Cycle.createDOMUser('.js-container'); user.inject(view);
JavaScript
0
@@ -87,20 +87,25 @@ nction ( -user +rootElem$ , props) @@ -110,27 +110,29 @@ s) %7B%0A var v -iew +tree$ = Cycle.cre @@ -126,36 +126,38 @@ $ = Cycle.create -View +Stream (function (props @@ -151,21 +151,25 @@ nction ( -props +children$ ) %7B%0A @@ -179,35 +179,8 @@ urn -%7B%0A vtree$: props.get(' chil @@ -184,18 +184,16 @@ hildren$ -') .map(fun @@ -211,18 +211,16 @@ dren) %7B%0A - re @@ -301,18 +301,10 @@ - %7D)%0A %7D +) ;%0A @@ -310,20 +310,25 @@ %7D);%0A%0A -user +rootElem$ .inject( @@ -328,19 +328,21 @@ inject(v -iew +tree$ ).inject @@ -351,80 +351,45 @@ rops -);%0A%7D);%0A%0Avar view = Cycle.createView(function () %7B%0A return %7B%0A +.get('children$'));%0A%7D);%0A%0Avar vtree$ -: + = Rx. @@ -405,20 +405,16 @@ e.just(%0A - h('div @@ -433,20 +433,16 @@ , %5B%0A - - h('wrapp @@ -466,20 +466,16 @@ : 1%7D, %5B%0A - h( @@ -530,71 +530,41 @@ - %5D)%0A %5D)%0A )%0A %7D;%0A%7D);%0A%0Avar user = +%5D)%0A %5D)%0A);%0A%0A Cycle. -c re -ateDOMUser( +nder(vtree$, '.js @@ -581,24 +581,4 @@ ');%0A -%0Auser.inject(view);%0A
8b431fa6169dfb1eb2d34fcc930590fb35a16b39
fix rees error
src/integrations/REES46.js
src/integrations/REES46.js
import { getProp } from 'driveback-utils/dotProp'; import { getEnrichableVariableMappingProps, extractVariableMappingValues, } from '../IntegrationUtils'; import Integration from '../Integration'; import { VIEWED_PAGE, VIEWED_PRODUCT_DETAIL, VIEWED_PRODUCT_LISTING, ADDED_PRODUCT, REMOVED_PRODUCT, COMPLETED_TRANSACTION, SEARCHED_PRODUCTS, } from '../events/semanticEvents'; const SEMANTIC_EVENTS = [ VIEWED_PAGE, VIEWED_PRODUCT_DETAIL, VIEWED_PRODUCT_LISTING, ADDED_PRODUCT, REMOVED_PRODUCT, COMPLETED_TRANSACTION, SEARCHED_PRODUCTS, ]; class REES46 extends Integration { constructor(digitalData, options) { const optionsWithDefaults = Object.assign({ storeKey: '', feedWithGroupedProducts: false, productVariables: {}, }, options); super(digitalData, optionsWithDefaults); this.addTag({ type: 'script', attr: { src: 'https://cdn.rees46.com/v3.js', }, }); } initialize() { window.r46 = window.r46 || function r46Init() { (window.r46.q = window.r46.q || []).push(arguments); }; window.r46('init', this.getOption('storeKey')); } getSemanticEvents() { return SEMANTIC_EVENTS; } getEnrichableEventProps(event) { switch (event.name) { case VIEWED_PAGE: return ['user', 'website']; case VIEWED_PRODUCT_LISTING: return ['listing.categoryId']; case SEARCHED_PRODUCTS: return ['listing.query']; case COMPLETED_TRANSACTION: return ['transaction']; case VIEWED_PRODUCT_DETAIL: return [ ...getEnrichableVariableMappingProps(this.getOption('productVariables')), 'product', ]; default: return []; } } getProductVariables(event) { const { product } = event; const mapping = this.getOption('productVariables'); return extractVariableMappingValues( { event, product }, mapping, { multipleScopes: true }, ); } trackEvent(event) { const eventMap = { [VIEWED_PAGE]: this.onViewedPage.bind(this), [VIEWED_PRODUCT_DETAIL]: this.onViewedProductDetail.bind(this), [VIEWED_PRODUCT_LISTING]: this.onViewedProductListing.bind(this), [SEARCHED_PRODUCTS]: this.onSearchedProducts.bind(this), [ADDED_PRODUCT]: this.onAddedProduct.bind(this), [REMOVED_PRODUCT]: this.onRemovedProduct.bind(this), [COMPLETED_TRANSACTION]: this.onCompletedTransaction.bind(this), }; if (eventMap[event.name]) { eventMap[event.name](event); } } onViewedPage(event) { const { user } = event; if (!user || !user.userId || !user.email) return; const gender = String(user.gender).toLowerCase(); const rees46Data = cleanObject({ id: user.userId, email: user.email, gender: ['m', 'f'].indexOf(gender) >= 0 ? gender : undefined, birthday: user.birthDate, location: getProp(event, 'website.regionId'), }); window.r46('profile', 'set', rees46Data); } onViewedProductDetail(event) { const product = event.product || {}; const feedWithGroupedProducts = this.getOption('feedWithGroupedProducts'); const productId = (feedWithGroupedProducts) ? product.skuCode : product.id; if (!productId) return; const productVariables = this.getProductVariables(event); const { stock } = product; if (stock !== undefined) { productVariables.stock = (stock > 0); } if (Object.keys(productVariables).length > 0) { window.r46('track', 'view', { id: productId, ...productVariables, }); } else { window.r46('track', 'view', productId); } } onAddedProduct(event) { const product = event.product || {}; const feedWithGroupedProducts = this.getOption('feedWithGroupedProducts'); const productId = (feedWithGroupedProducts) ? product.skuCode : product.id; if (productId) { window.r46('track', 'cart', { id: productId, amount: event.quantity || 1, }); } } onRemovedProduct(event) { const product = event.product || {}; const feedWithGroupedProducts = this.getOption('feedWithGroupedProducts'); const productId = (feedWithGroupedProducts) ? product.skuCode : product.id; if (productId) { window.r46('track', 'remove_from_cart', productId); } } onViewedProductListing(event) { const listing = event.listing || {}; const { categoryId } = listing; if (categoryId) { window.r46('track', 'category', categoryId); } } onSearchedProducts(event) { const listing = event.listing || {}; const { query } = listing; if (query) { window.r46('track', 'search', query); } } onCompletedTransaction(event) { const transaction = event.transaction || {}; const lineItems = transaction.lineItems || []; const feedWithGroupedProducts = this.getOption('feedWithGroupedProducts'); if (lineItems.length) { window.r46('track', 'purchase', { products: lineItems.map(lineItem => ({ id: (feedWithGroupedProducts) ? getProp(lineItem, 'product.skuCode') : getProp(lineItem, 'product.id'), price: getProp(lineItem, 'product.unitSalePrice'), amount: lineItem.quantity || 1, })), order: transaction.orderId, order_price: transaction.total, }); } } } export default REES46;
JavaScript
0.000001
@@ -1,16 +1,71 @@ +import cleanObject from 'driveback-utils/cleanObject';%0A import %7B getProp
abeef0c40074cffa1735736bb29eb6870bd2d712
Fix fab initialization
mithril/components/fab.js
mithril/components/fab.js
v.component.fab = { oninit: (vnode) => { vnode.state.onclick = (e) => { vnode.attrs.fab.onclick(e) } }, oncreate: (vnode) => { var fab = mdc.ripple.MDCRipple.attachTo(vnode.dom) }, view: (vnode) => [ (v.state.admin || null) && m('button.mdc-fab material-icons v-fab', { onclick: vnode.state.onclick }, m('span.mdc-fab__icon', 'add') ) ] }
JavaScript
0.000104
@@ -137,24 +137,47 @@ vnode) =%3E %7B%0A + if (vnode.dom) %7B%0A var fab @@ -219,16 +219,22 @@ de.dom)%0A + %7D%0A %7D,%0A v
606339ed3e3a8e511f0cfb9ff94aac8a28c17cee
fix opening the settings (opens overview for now)
[email protected]/randomWallpaperMenu.js
[email protected]/randomWallpaperMenu.js
const GLib = imports.gi.GLib; const Shell = imports.gi.Shell; //self const Self = imports.misc.extensionUtils.getCurrentExtension(); const LoggerModule = Self.imports.logger; const Timer = Self.imports.timer; // UI Imports const PanelMenu = imports.ui.panelMenu; const PopupMenu = imports.ui.popupMenu; const CustomElements = Self.imports.elements; const Main = imports.ui.main; // Filesystem const Gio = imports.gi.Gio; // Settings const Prefs = Self.imports.settings; var RandomWallpaperMenu = class { constructor(wallpaperController) { this.panelMenu = new PanelMenu.Button(0, "Random wallpaper"); this.settings = new Prefs.Settings(); this.wallpaperController = wallpaperController; this.logger = new LoggerModule.Logger('RWG3', 'RandomWallpaperEntry'); this.hidePanelIconHandler = this.settings.observe('hide-panel-icon', this.updatePanelMenuVisibility.bind(this)); // Panelmenu Icon this.statusIcon = new CustomElements.StatusElement(); this.panelMenu.actor.add_child(this.statusIcon.icon); // new wallpaper button this.newWallpaperItem = new CustomElements.NewWallpaperElement(); this.panelMenu.menu.addMenuItem(this.newWallpaperItem); this.panelMenu.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); // current background section this.currentBackgroundSection = new PopupMenu.PopupMenuSection(); this.panelMenu.menu.addMenuItem(this.currentBackgroundSection); this.panelMenu.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); // history section this.historySection = new CustomElements.HistorySection(); this.panelMenu.menu.addMenuItem(this.historySection); this.panelMenu.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); // clear history button this.clearHistoryItem = new PopupMenu.PopupMenuItem('Clear History'); this.panelMenu.menu.addMenuItem(this.clearHistoryItem); // open wallpaper folder button this.openFolder = new PopupMenu.PopupMenuItem('Open Wallpaper Folder'); this.panelMenu.menu.addMenuItem(this.openFolder); // settings button this.openSettings = new PopupMenu.PopupMenuItem('Settings'); this.panelMenu.menu.addMenuItem(this.openSettings); /* add eventlistener */ this.wallpaperController.registerStartLoadingHook(this.statusIcon.startLoading.bind(this.statusIcon)); this.wallpaperController.registerStopLoadingHook(this.statusIcon.stopLoading.bind(this.statusIcon)); this.wallpaperController.registerStopLoadingHook(this.setHistoryList.bind(this)); // new wallpaper event this.newWallpaperItem.connect('activate', () => { this.wallpaperController.fetchNewWallpaper(); }); // clear history event this.clearHistoryItem.connect('activate', () => { this.wallpaperController.deleteHistory(); }); // Open Wallpaper Folder this.openFolder.connect('activate', (event) => { let uri = GLib.filename_to_uri(this.wallpaperController.wallpaperlocation, ""); Gio.AppInfo.launch_default_for_uri(uri, global.create_app_launch_context(0, -1)) }); this.openSettings.connect("activate", () => { // call gnome settings tool for this extension let app = Shell.AppSystem.get_default().lookup_app("gnome-shell-extension-prefs.desktop"); if (app != null) { // only works in Gnome >= 3.12 let info = app.get_app_info(); let timestamp = global.display.get_current_time_roundtrip(); info.launch_uris([Self.uuid], global.create_app_launch_context(timestamp, -1)); } }); this.panelMenu.menu.actor.connect('show', () => { this.newWallpaperItem.show(); }); // when the popupmenu disapears, check if the wallpaper is the original and // reset it if needed this.panelMenu.menu.actor.connect('hide', () => { this.wallpaperController.resetWallpaper(); }); this.panelMenu.menu.actor.connect('leave-event', () => { this.wallpaperController.resetWallpaper(); }); this.settings.observe('history', this.setHistoryList.bind(this)); } init() { this.updatePanelMenuVisibility(); this.setHistoryList(); // add to panel Main.panel.addToStatusArea("random-wallpaper-menu", this.panelMenu); } cleanup() { this.clearHistoryList(); this.panelMenu.destroy(); // remove all signal handlers if (this.hidePanelIconHandler !== null) { this.settings.disconnect(this.hidePanelIconHandler); } } updatePanelMenuVisibility() { if (this.settings.get('hide-panel-icon', 'boolean')) { this.panelMenu.actor.hide(); } else { this.panelMenu.actor.show(); } } setCurrentBackgroundElement() { this.currentBackgroundSection.removeAll(); let historyController = this.wallpaperController.getHistoryController(); let history = historyController.history; if (history.length > 0) { let currentImage = new CustomElements.CurrentImageElement(history[0]); this.currentBackgroundSection.addMenuItem(currentImage); } } setHistoryList() { this.wallpaperController.update(); this.setCurrentBackgroundElement(); let historyController = this.wallpaperController.getHistoryController(); let history = historyController.history; if (history.length <= 1) { this.clearHistoryList(); return; } function onLeave(actor) { this.wallpaperController.resetWallpaper(); } function onEnter(actor) { this.wallpaperController.previewWallpaper(actor.historyId); } function onSelect(actor) { this.wallpaperController.setWallpaper(actor.historyEntry.id); } this.historySection.updateList(history, onEnter.bind(this), onLeave.bind(this), onSelect.bind(this)); } clearHistoryList() { this.historySection.clear(); } };
JavaScript
0
@@ -3045,16 +3045,122 @@ () =%3E %7B%0A +%09%09%09// Fixme: opens the settings overview in 3.36 where you have to select the correct extension yourself.%0A %09%09%09// ca @@ -3260,29 +3260,27 @@ pp(%22 +org. gnome --shell-e +.E xtension -pre @@ -3279,13 +3279,8 @@ sion --pref s.de @@ -3288,16 +3288,17 @@ ktop%22);%0A +%0A %09%09%09if (a
9bf26ec5776b64b645ed7ee7a5d46837d0a3a8ca
fix lang.js
src/interface/lang/lang.js
src/interface/lang/lang.js
var translations = require('./translations') var mustache = require('mustache') var EventEmitter = require('events').EventEmitter var inherits = require('inherits') inherits(Lang, EventEmitter) function Lang () { var self = this if (!(self instanceof Lang)) return new Lang() var langLocale = navigator.languages ? navigator.languages[0] : (navigator.language || navigator.userLanguage) self.lang = langLocale.split('-')[0] self.locale = langLocale.split('-')[1] // TODO: locale support // translate the DOM document.querySelector('#save > span').innerHTML = self.get('save') document.querySelector('#deploy > span').innerHTML = self.get('deploy') document.querySelector('#voice > span').innerHTML = self.get('talk') document.querySelector('#save > span').innerHTML = self.get('save') } Lang.prototype.get = function (key, data) { var self = this data = data || {} console.log(key) return (typeof translations[self.lang] != 'undefined') ? mustache.render(translations[self.lang][key], data) : mustache.render(translations['en'][key], data) } module.exports = new Lang()
JavaScript
0.998545
@@ -938,22 +938,20 @@ %0A -return (typeof +var lookup = tra @@ -975,79 +975,38 @@ ng%5D -!= 'undefined') ? mustache.render(translations%5Bself.lang%5D%5Bkey%5D, data) : +%7C%7C translations%5B'en'%5D%0A return mus @@ -1018,16 +1018,31 @@ .render( +lookup%5Bkey%5D %7C%7C translat
26f5653882e714bb04935e6ad745cdfafb8e371d
update comments to match change to ensureAsync
mocha_test/ensureAsync.js
mocha_test/ensureAsync.js
var async = require('../lib'); var expect = require('chai').expect; describe('ensureAsync', function() { var passContext = function(cb) { cb(this); }; it('should propely bind context to the wrapped function', function(done) { // call bind after wrapping with initialParams var context = {context: "post"}; var postBind = async.ensureAsync(passContext); postBind = postBind.bind(context); postBind(function(ref) { expect(ref).to.equal(context); done(); }); }); it('should not override the bound context of a function when wrapping', function(done) { // call bind before wrapping with initialParams var context = {context: "pre"}; var preBind = passContext.bind(context); preBind = async.ensureAsync(preBind); preBind(function(ref) { expect(ref).to.equal(context); done(); }); }); });
JavaScript
0
@@ -275,37 +275,35 @@ apping with -initialParams +ensureAsync %0D%0A var co @@ -659,21 +659,19 @@ ith -initialParams +ensureAsync %0D%0A
f811b7b82a80dff1e0ea024991f002c355cd7380
add contraint/overlap members to eventdef
src/models/EventDefinition.js
src/models/EventDefinition.js
var EventDefinition = Class.extend({ source: null, id: null, title: null, rendering: null, miscProps: null, constructor: function() { this.miscProps = {}; }, buildInstances: function(start, end) { // subclasses must implement }, clone: function() { var copy = new this.constructor(); copy.source = this.source; copy.id = this.id; copy.title = this.title; copy.rendering = this.rendering; copy.miscProps = $.extend({}, this.miscProps); return copy; } }); EventDefinition.uuid = 0; EventDefinition.reservedPropMap = {}; EventDefinition.addReservedProps = function(propArray) { var map = {}; var i; for (i = 0; i < propArray.length; i++) { map[propArray[i]] = true; } // won't modify original object. don't want sideeffects on superclasses this.reservedPropMap = $.extend({}, this.reservedPropMap, map); }; EventDefinition.isReservedProp = function(propName) { return this.reservedPropMap[propName] || false; }; EventDefinition.parse = function(rawProps) { var def = new this(); var propName; var miscProps = {}; def.id = rawProps.id || ('_fc' + (++EventDefinition.uuid)); def.title = rawProps.title || ''; def.rendering = rawProps.rendering || null; for (propName in rawProps) { if (!this.isReservedProp(propName)) { miscProps[propName] = rawProps[propName]; } } def.miscProps = miscProps; return def; }; EventDefinition.addReservedProps([ 'id', 'title', 'rendering' ]);
JavaScript
0
@@ -90,16 +90,51 @@ : null,%0A +%09constraint: null,%0A%09overlap: null,%0A %09miscPro @@ -449,16 +449,84 @@ dering;%0A +%09%09copy.constraint = this.constraint;%0A%09%09copy.overlap = this.overlap;%0A %09%09copy.m @@ -1309,16 +1309,88 @@ %7C%7C null; +%0A%09def.constraint = rawProps.constraint;%0A%09def.overlap = rawProps.overlap; %0A%0A%09for ( @@ -1614,13 +1614,38 @@ ndering' +, 'constraint', 'overlap' %5D);%0A
261965ccbf33393ebbe46cafeff3d999b135999a
Fix proptype warning when setting label={false} on an input
src/js/components/label.js
src/js/components/label.js
import React from 'react' import { sizeClassNames } from '../util.js' import cx from 'classnames' export default class Label extends React.Component { static displayName = 'FriggingBootstrap.Label' static propTypes = { labelWidth: React.PropTypes.object.isRequired, layout: React.PropTypes.string.isRequired, block: React.PropTypes.bool, label: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.element, ]), } static defaultProps = { block: false, label: '', } isEmpty() { return !this.props.label } render() { const horizontalClasses = sizeClassNames( this.props.labelWidth, { offsets: false } ) if (this.props.block) return null if (this.props.layout === 'horizontal' && this.isEmpty()) { return <div className={horizontalClasses} /> } const labelHtml = Object.assign({}, this.props) labelHtml.className = cx(labelHtml.className, { [horizontalClasses]: this.props.layout === 'horizontal', }) return ( <div> <label {...labelHtml}> {this.props.label} </label> </div> ) } }
JavaScript
0.000329
@@ -449,16 +449,92 @@ lement,%0A + React.PropTypes.bool, // can set label=%7Bfalse%7D to not show a label%0A %5D),%0A
8b26888fedfbf5a851e70b227a35df5e7f679471
Mejora instapago & processPayment
instapago.js
instapago.js
'use strict'; import { axios as http } from 'axios'; function instapago({keyId, publicKeyId, strict = true}) { if (!keyId || !publicKeyId) { throw new Error('Los parámetos keyId y publicKeyId son requerido'); } else if (typeof keyId !== 'string' || typeof publicKeyId !== 'string') { throw new Error('Los parámetos keyId y publicKeyId deben ser String.'); } const config = { keyId, publicKeyId, strict }; return { pay: data => processPayment('pay', config, data), resume: data => processPayment('resume', config, data), cancel: data => processPayment('cancel', config, data), view: data => processPayment('view', config, data) } } function processPayment(type, config, data) { const validation = validatePaymentData(type, data); const params = Object.assign({}, config, data); let endpoint; let method; switch (type) { case 'pay': endpoint = 'payment'; method = 'POST'; break; case 'resume': endpoint = 'complete'; method = 'POST'; break; case 'cancel': endpoint = 'payment'; method = 'DELETE'; break; case 'view': endpoint = 'payment'; method = 'GET'; break; } if (config.strict && validation.error) { return new Promise((resolve, reject) => reject(validation.error)); } else { return http({ method, url: `https://api.instapago.com/${endpoint}`, params: params }); } } function validatePaymentData(type, data) { const result = {}; const _data = {}; Object.keys(data).forEach(key => { Object.assign(_data, {[key.toLowerCase()]: data[key]}); }); const rules = [ { param: 'amount', rule: 'Sólo caracteres numéricos y punto (.) como separador decimal.', valid: /[0-9]/.test(_data.amount) }, { param: 'description', rule: 'Cadena de caracteres con los detalles de la operación.', valid: typeof _data.description === 'string' }, { param: 'cardholder', rule: 'Sólo caracteres alfabéticos, incluyendo la letra ñ y espacio.', valid: /^[ñA-Za-z\s]*$/.test(_data.cardholder) }, { param: 'cardholderid', rule: 'Sólo caracteres numéricos; mínimo 6 dígitos y máximo 8.', valid: /^[0-9]{6,8}$/.test(_data.cardholderid) }, { param: 'cardnumber', rule: 'Sólo caracteres numéricos; mínimo 15 dígitos y máximo 16.', valid: /^[0-9]{15,16}$/.test(_data.cardnumber) }, { param: 'cvc', rule: 'Sólo caracteres numéricos; deben ser 3 dígitos.', valid: /^[0-9]{3}$/.test(_data.cvc) }, { param: 'expirationdate', rule: 'Sólo fechas mayores a la fecha en curso, en formato MM/YYYY.', valid: isCardExpired(_data.expirationdate) }, { param: 'statusid', rule: 'Sólo caracteres numéricos; debe ser 1 dígito.', valid: /^[1-2]{1}$/.test(_data.statusid) }, { param: 'ip', rule: 'Dirección IP del cliente que genera la solicitud del pago.', valid: typeof _data.description === 'string' } ]; let requiredParams = ['id']; if (type === 'pay') { requiredParams = [ 'amount', 'description', 'cardholder', 'cardholderid', 'cardnumber', 'cvc', 'expirationdate', 'statusid', 'ip' ]; } else if (type === 'resume') { requiredParams = ['id', 'amount']; } requiredParams.every(param => { const _param = rules.find(rule => rule.param === param); if (_data[param] && _param.valid) { return true; } result.error = new Error(`Parámetro inválido (${param}): ${_param.rule}`); return false; }); return result; } function isCardExpired(date) { const _date = date ? date.split('/') : null; if (_date) { const yearOnCard = parseInt(_date[1]); const monthOnCard = parseInt(_date[0]); const year = new Date().getFullYear(); const month = new Date().getUTCMonth() + 1; return ((yearOnCard === year && monthOnCard >= month) || yearOnCard > year); } return false; } export default instapago;
JavaScript
0
@@ -67,17 +67,16 @@ stapago( -%7B keyId, p @@ -100,17 +100,16 @@ t = true -%7D ) %7B%0A if @@ -160,32 +160,33 @@ ror('Los par%C3%A1met +r os keyId y publi @@ -205,16 +205,18 @@ equerido +s. ');%0A %7D @@ -320,16 +320,17 @@ par%C3%A1met +r os keyId @@ -389,16 +389,42 @@ fig = %7B%0A + strict,%0A keys: %7B%0A keyI @@ -422,24 +422,26 @@ keyId,%0A + publicKe @@ -447,20 +447,14 @@ eyId -, %0A -strict +%7D %0A %7D @@ -840,24 +840,29 @@ n(%7B%7D, config +.keys , data);%0A l @@ -868,73 +868,8 @@ let -endpoint;%0A let method;%0A%0A switch (type) %7B%0A case 'pay':%0A endp @@ -880,35 +880,35 @@ = 'payment';%0A - +let method = 'POST' @@ -909,38 +909,57 @@ 'POST';%0A - break;%0A%0A case +%0A if (type !== 'pay') %7B%0A if (type === 'resume @@ -959,23 +959,17 @@ 'resume' -:%0A +) endpoin @@ -992,177 +992,74 @@ - method = 'POST';%0A break;%0A%0A case 'cancel':%0A endpoint = 'payment';%0A method = 'DELETE';%0A break;%0A%0A case 'view':%0A endpoint = 'payment';%0A +if (type === 'cancel') method = 'DELETE';%0A if (type === 'view') met @@ -1075,21 +1075,8 @@ T';%0A - break;%0A %7D%0A
7674e1a4be3ed16a7318e6c22e9cd3cf674fdef0
add method to get width of scrollbar
src/js/global-scrollbar.js
src/js/global-scrollbar.js
/* to define width of scrollbar */ ;(function ($, _, undefined) { 'use strict'; _.globalScrollbar = { prop: 'margin', side: 'right', selector: '.js-scrollbar-offset', _hidden: false, _width: 0, _prevOverflow: '', _prevMargin: '', _num: 0, _first: true, hide: function (_callback) { if (this._first) { this.prop = this.prop ? (this.prop + '-') : ''; this._first = false; } this._num++; if (this._hidden) { return false; } this._hidden = true; var nHTML = document.documentElement, iWidth = Math.round(window.innerWidth - nHTML.clientWidth), sProp = this.prop, sSide = this.side; this._width = iWidth; this._prevOverflow = nHTML.style.overflow; this._prevMargin = nHTML.style[sProp + sSide]; nHTML.style.overflow = 'hidden'; nHTML.style[sProp + sSide] = iWidth + 'px'; var anNeedOffset = document.querySelectorAll(this.selector), nElem, sDataProp, i, L; for (i = 0, L = anNeedOffset.length; i < L; i++) { nElem = anNeedOffset[i]; sDataProp = nElem.getAttribute('data-offset-prop'); if (sDataProp === 'true') { nElem.style[sSide] = iWidth + 'px'; } else if (sDataProp) { nElem.style[sDataProp + '-' + sSide] = iWidth + 'px'; } else { nElem.style[sProp + sSide] = iWidth + 'px'; } } if (_callback) { _callback(iWidth, sSide, sProp); } }, restore: function (_callback, _bRightNow) { this._num--; if (!this._hidden || (this._num > 0 && !_bRightNow)) { return false; } this._hidden = false; var sProp = this.prop, sSide = this.side, nHTML = document.documentElement; nHTML.style.overflow = this._prevOverflow; nHTML.style[sProp + sSide] = this._prevMargin; this._prevOverflow = ''; this._prevMargin = ''; var anNeedOffset = document.querySelectorAll(this.selector), nElem, sDataProp, i, L; for (i = 0, L = anNeedOffset.length; i < L; i++) { nElem = anNeedOffset[i]; sDataProp = nElem.getAttribute('data-offset-prop'); if (sDataProp === 'true') { nElem.style[sSide] = ''; } else if (sDataProp) { nElem.style[sDataProp + '-' + sSide] = ''; } else { nElem.style[sProp + sSide] = ''; } } if (_callback) { _callback(this._width, sSide, sProp); } } }; })(window.jQuery, window._);
JavaScript
0
@@ -601,56 +601,19 @@ h = -Math.round(window.innerWidth - nHTML.clientWidth +this.width( ),%0D%0A @@ -2472,16 +2472,130 @@ %0D%0A%09%09%09%7D%0D%0A +%09%09%7D,%0D%0A%09%09width: function ()%0D%0A%09%09%7B%0D%0A%09%09%09return Math.round(window.innerWidth - document.documentElement.clientWidth);%0D%0A %09%09%7D%0D%0A%09%7D;
424687e47bd17b8966e8bd0cf978ccf96be3d5f4
Fix mts filters
src/modules/postgres/query.js
src/modules/postgres/query.js
import * as pg from '../../lib/pg'; import { TABLES, TYPES } from '../../lib/schema'; const MAX_LIMIT = 1024; const operators = { gt: '>', lt: '<', in: 'IN', neq: '<>', gte: '>=', lte: '<=', cts: '@>', ctd: '<@', mts: '@@' }; function getPropOp(prop) { const i = prop.lastIndexOf('_'); if (i > 0) { return [ prop.substr(i + 1, prop.length), prop.substr(0, i) ]; } else { return ''; } } function fromPart (slice) { const fields = [], joins = []; fields.push('row_to_json("' + TABLES[TYPES[slice.type]] + '".*)::jsonb as "' + slice.type + '"'); joins.push('"' + TABLES[TYPES[slice.type]] + '"'); if (slice.join) { for (const type in slice.join) { joins.push( 'LEFT OUTER JOIN "' + TABLES[TYPES[type]] + '" ON "' + TABLES[TYPES[type]] + '"."' + slice.join[type] + '" = "' + TABLES[TYPES[slice.type]] + '"."id"' ); fields.push('row_to_json("' + TABLES[TYPES[type]] + '".*)::jsonb as "' + type + '"'); } } if (slice.link) { for (const type in slice.link) { joins.push( 'LEFT OUTER JOIN "' + TABLES[TYPES[type]] + '" ON "' + TABLES[TYPES[slice.type]] + '"."' + slice.link[type] + '" = "' + TABLES[TYPES[type]] + '"."id"' ); fields.push('row_to_json("' + TABLES[TYPES[type]] + '".*)::jsonb as "' + type + '"'); } } return pg.cat([ 'SELECT ', pg.cat(fields, ','), 'FROM', pg.cat(joins, ' ') ], ' '); } function wherePart (f) { const sql = []; let filter = f; for (const prop in filter) { const [ op, name ] = getPropOp(prop); if (Number.POSITIVE_INFINITY === filter[prop] || Number.NEGATIVE_INFINITY === filter[prop]) { continue; } switch (op) { case 'gt': case 'lt': case 'neq': case 'gte': case 'lte': case 'in': case 'cts': case 'ctd': case 'mts': sql.push(`"${name.toLowerCase()}" ${operators[op]} &{${prop}}`); break; default: sql.push(`"${prop.toLowerCase()}" = &{${prop}}`); } } if (sql.length) { filter = Object.create(filter); filter.$ = 'WHERE ' + sql.join(' AND '); return filter; } else { return ''; } } function orderPart(order, limit) { if (limit < 0) { return `ORDER BY "${order.toLowerCase()}" DESC LIMIT ${-limit}`; } else { return `ORDER BY "${order.toLowerCase()}" ASC LIMIT ${limit}`; } } function simpleQuery(slice, limit) { return pg.cat([ fromPart(slice), wherePart(slice.filter), orderPart(slice.order, limit) ], ' '); } function boundQuery (slice, start, end) { slice.filter[slice.order + '_gte'] = start; slice.filter[slice.order + '_lte'] = end; const query = simpleQuery(slice, MAX_LIMIT); delete slice.filter[slice.order + '_gte']; delete slice.filter[slice.order + '_lte']; return query; } function beforeQuery (slice, start, before, exclude) { slice.filter[slice.order + (exclude ? '_lt' : '_lte')] = start; const query = simpleQuery(slice, Math.max(-MAX_LIMIT, -before)); delete slice.filter[slice.order + (exclude ? '_lt' : '_lte')]; return pg.cat([ 'SELECT * FROM (', query, { $: `) r ORDER BY ${slice.type.toLowerCase()}->&{order} ASC`, order: slice.order.toLowerCase() } ], ' '); } function afterQuery (slice, start, after, exclude) { if (!slice.filter) slice.filter = {}; slice.filter[slice.order + (exclude ? '_gt' : '_gte')] = start; const query = simpleQuery(slice, Math.min(MAX_LIMIT, after)); delete slice.filter[slice.order + (exclude ? '_gt' : '_gte')]; return query; } export default function (slice, range) { let query; if (slice.order) { if (range.length === 2) { query = boundQuery(slice, range[0], range[1]); } else { if (range[1] > 0 && range[2] > 0) { query = pg.cat([ '(', beforeQuery(slice, range[0], range[1], true), ')', 'UNION ALL', '(', afterQuery(slice, range[0], range[2]), ')' ], ' '); } else if (range[1] > 0) { query = beforeQuery(slice, range[0], range[1]); } else if (range[2] > 0) { query = afterQuery(slice, range[0], range[2]); } } } else { query = simpleQuery(slice, MAX_LIMIT); } return query; }
JavaScript
0.000001
@@ -228,10 +228,12 @@ s: ' -@@ +like '%0A%7D;
23f89401afc33fe4fc275c166b52f1763755838d
fix #9 new article page is not working due to null state
resources/assets/js/common/wysiwyg-editor/index.js
resources/assets/js/common/wysiwyg-editor/index.js
import React, { Component } from 'react' import PropTypes from 'prop-types' import { EditorState, convertToRaw, ContentState, convertFromHTML } from 'draft-js' import { Editor } from 'react-draft-wysiwyg' import draftToHtml from 'draftjs-to-html' import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css' class WYSIWYG extends Component { static propTypes = { value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, } constructor(props) { super(props) this.state = { editorState: this.convertHtmlToEditorState(this.props.value), } this.onEditorStateChange = this.onEditorStateChange.bind(this) } convertHtmlToEditorState() { const { value } = this.props const blocksFromHTML = convertFromHTML(value) const state = ContentState.createFromBlockArray( blocksFromHTML.contentBlocks, blocksFromHTML.entityMap ) return EditorState.createWithContent(state) } onEditorStateChange(editorState) { this.setState({ editorState, }) this.props.onChange(draftToHtml(convertToRaw(editorState.getCurrentContent()))) } render() { const { editorState } = this.state return ( <div> <Editor editorState={editorState} wrapperClassName="demo-wrapper" editorClassName="form-control" onEditorStateChange={this.onEditorStateChange} /> </div> ) } } export default WYSIWYG
JavaScript
0
@@ -438,27 +438,25 @@ quired,%0A %7D%0A - %0A + constructo @@ -483,21 +483,17 @@ (props)%0A - %0A + this @@ -577,21 +577,17 @@ ,%0A %7D%0A - %0A + this @@ -649,18 +649,16 @@ is)%0A %7D%0A - %0A conve @@ -677,24 +677,29 @@ orState( +value ) %7B%0A const %7B @@ -694,41 +694,26 @@ -const %7B value %7D = this.props%0A +if (value)%7B%0A - cons @@ -754,16 +754,18 @@ (value)%0A + cons @@ -811,24 +811,26 @@ rray(%0A + blocksFromHT @@ -849,24 +849,26 @@ ocks,%0A + + blocksFromHT @@ -884,23 +884,23 @@ Map%0A -)%0A +)%0A%0A -%0A retu @@ -939,23 +939,27 @@ (state)%0A + %7D%0A %7D%0A - %0A + onEdit @@ -1037,13 +1037,9 @@ %7D)%0A - %0A + @@ -1122,18 +1122,16 @@ )))%0A %7D%0A - %0A rende
9f9f654c60f7790683e227e3c66a0b7b0e678700
Set player actions status
integrate.js
integrate.js
/* * Copyright 2014 Your name <your e-mail> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function(Nuvola) { "use strict"; // Create media player component var player = Nuvola.$object(Nuvola.MediaPlayer); // Handy aliases var PlaybackState = Nuvola.PlaybackState; var PlayerAction = Nuvola.PlayerAction; // Create new WebApp prototype var WebApp = Nuvola.$WebApp(); // Initialization routines WebApp._onInitWebWorker = function(emitter) { Nuvola.WebApp._onInitWebWorker.call(this, emitter); var state = document.readyState; if (state === "interactive" || state === "complete") this._onPageReady(); else document.addEventListener("DOMContentLoaded", this._onPageReady.bind(this)); }; // Page is ready for magic WebApp._onPageReady = function() { // Connect handler for signal ActionActivated Nuvola.actions.connect("ActionActivated", this); // Start update routine this.update(); }; // Extract data from the web page WebApp.update = function() { var hasClass = function (el, cls) { return el && el.className && new RegExp("(\\s|^)" + cls + "(\\s|$)").test(el.className); }; var playerElement = document.querySelector(".player.music"); // Playback state var state = PlaybackState.UNKNOWN; if (playerElement) { var playElement = playerElement.querySelector(".play-btn"); var pauseElement = playerElement.querySelector(".pause-btn"); if (hasClass(playElement, "hidden")) { state = PlaybackState.PLAYING; } else if (hasClass(pauseElement, "hidden")) { state = PlaybackState.PAUSED; } } player.setPlaybackState(state); // Track informations var track = { title: null, artist: null, album: null, artLocation: null }; if (playerElement) { var posterElement = playerElement.querySelector(".media-poster"); track.title = posterElement.attributes['data-title'].value; track.album = posterElement.attributes['data-parent-title'].value; track.artist = posterElement.attributes['data-grandparent-title'].value; track.artLocation = posterElement.attributes['data-image-url'].value; } player.setTrack(track); // Schedule the next update setTimeout(this.update.bind(this), 500); }; // Handler of playback actions WebApp._onActionActivated = function(emitter, name, param) { }; WebApp.start(); })(this); // function(Nuvola)
JavaScript
0.000001
@@ -2199,57 +2199,34 @@ %0A%0A -// Extract data from the web page%0A WebApp.update +WebApp._isHiddenOrDisabled = f @@ -2228,28 +2228,29 @@ d = function -()%0A + (el) %7B%0A var h @@ -2252,142 +2252,196 @@ var -hasClass = function (el, cls) %7B%0A return el && el.className && new RegExp(%22(%5C%5Cs%7C%5E)%22 + cls + %22(%5C%5Cs%7C$)%22).test(el.className);%0A %7D;%0A +regex = new RegExp(%22(%5C%5Cs%7C%5E)(disabled%7Chidden)(%5C%5Cs%7C$)%22);%0A return el && el.className && regex.test(el.className);%0A %7D;%0A%0A // Extract data from the web page%0A WebApp.update = function()%0A %7B %0A @@ -2506,68 +2506,71 @@ %22);%0A -%0A -// Playback state%0A var state = PlaybackState.UNKNOWN +var playElement, pauseElement, previousElement, nextElement ;%0A @@ -2594,28 +2594,24 @@ nt) %7B%0A -var playElement @@ -2660,20 +2660,16 @@ ;%0A -var pauseEle @@ -2728,42 +2728,272 @@ -if (hasClass +previousElement = playerElement.querySelector(%22.previous-btn%22);%0A nextElement = playerElement.querySelector(%22.next-btn%22);%0A %7D%0A // Playback state%0A var state = PlaybackState.UNKNOWN;%0A if (play +er Element -, %22hidden%22 +) %7B%0A if (this._isHiddenOrDisabled(playElement )) %7B @@ -3053,16 +3053,32 @@ if ( -hasClass +this._isHiddenOrDisabled (pau @@ -3090,18 +3090,8 @@ ment -, %22hidden%22 )) %7B @@ -3179,16 +3179,17 @@ state);%0A +%0A // T @@ -3735,24 +3735,377 @@ ck(track);%0A%0A + // Player actions%0A player.setCanPlay(playerElement && !this._isHiddenOrDisabled(playElement));%0A player.setCanPause(playerElement && !this._isHiddenOrDisabled(pauseElement));%0A player.setCanGoPrev(playerElement && !this._isHiddenOrDisabled(previousElement));%0A player.setCanGoNext(playerElement && !this._isHiddenOrDisabled(nextElement));%0A%0A // Sched
bec3a3b6987a71ab1d07331b7367be9156cbf538
define router property in NavigationInstruction
src/navigation-instruction.js
src/navigation-instruction.js
interface NavigationInstructionInit { fragment: string, queryString: string, params : Object, queryParams: Object, config: RouteConfig, parentInstruction: NavigationInstruction, previousInstruction: NavigationInstruction, router: Router, options: Object } export class CommitChangesStep { run(navigationInstruction: NavigationInstruction, next: Function) { return navigationInstruction._commitChanges(true).then(() => { navigationInstruction._updateTitle(); return next(); }); } } /** * Class used to represent an instruction during a navigation. */ export class NavigationInstruction { /** * The URL fragment. */ fragment: string; /** * The query string. */ queryString: string; /** * Parameters extracted from the route pattern. */ params: any; /** * Parameters extracted from the query string. */ queryParams: any; /** * The route config for the route matching this instruction. */ config: RouteConfig; /** * The parent instruction, if this instruction was created by a child router. */ parentInstruction: NavigationInstruction; /** * The instruction being replaced by this instruction in the current router. */ previousInstruction: NavigationInstruction; /** * viewPort instructions to used activation. */ viewPortInstructions: any; plan: Object = null; options: Object = {}; constructor(init: NavigationInstructionInit) { Object.assign(this, init); this.params = this.params || {}; this.viewPortInstructions = {}; let ancestorParams = []; let current = this; do { let currentParams = Object.assign({}, current.params); if (current.config && current.config.hasChildRouter) { // remove the param for the injected child route segment delete currentParams[current.getWildCardName()]; } ancestorParams.unshift(currentParams); current = current.parentInstruction; } while (current); let allParams = Object.assign({}, this.queryParams, ...ancestorParams); this.lifecycleArgs = [allParams, this.config, this]; } /** * Gets an array containing this instruction and all child instructions for the current navigation. */ getAllInstructions(): Array<NavigationInstruction> { let instructions = [this]; for (let key in this.viewPortInstructions) { let childInstruction = this.viewPortInstructions[key].childNavigationInstruction; if (childInstruction) { instructions.push(...childInstruction.getAllInstructions()); } } return instructions; } /** * Gets an array containing the instruction and all child instructions for the previous navigation. * Previous instructions are no longer available after navigation completes. */ getAllPreviousInstructions(): Array<NavigationInstruction> { return this.getAllInstructions().map(c => c.previousInstruction).filter(c => c); } /** * Adds a viewPort instruction. */ addViewPortInstruction(viewPortName: string, strategy: string, moduleId: string, component: any): any { let viewportInstruction = this.viewPortInstructions[viewPortName] = { name: viewPortName, strategy: strategy, moduleId: moduleId, component: component, childRouter: component.childRouter, lifecycleArgs: this.lifecycleArgs.slice() }; return viewportInstruction; } /** * Gets the name of the route pattern's wildcard parameter, if applicable. */ getWildCardName(): string { let wildcardIndex = this.config.route.lastIndexOf('*'); return this.config.route.substr(wildcardIndex + 1); } /** * Gets the path and query string created by filling the route * pattern's wildcard parameter with the matching param. */ getWildcardPath(): string { let wildcardName = this.getWildCardName(); let path = this.params[wildcardName] || ''; if (this.queryString) { path += '?' + this.queryString; } return path; } /** * Gets the instruction's base URL, accounting for wildcard route parameters. */ getBaseUrl(): string { if (!this.params) { return this.fragment; } let wildcardName = this.getWildCardName(); let path = this.params[wildcardName] || ''; if (!path) { return this.fragment; } path = encodeURI(path); return this.fragment.substr(0, this.fragment.lastIndexOf(path)); } _commitChanges(waitToSwap: boolean) { let router = this.router; router.currentInstruction = this; if (this.previousInstruction) { this.previousInstruction.config.navModel.isActive = false; } this.config.navModel.isActive = true; router._refreshBaseUrl(); router.refreshNavigation(); let loads = []; let delaySwaps = []; for (let viewPortName in this.viewPortInstructions) { let viewPortInstruction = this.viewPortInstructions[viewPortName]; let viewPort = router.viewPorts[viewPortName]; if (!viewPort) { throw new Error(`There was no router-view found in the view for ${viewPortInstruction.moduleId}.`); } if (viewPortInstruction.strategy === activationStrategy.replace) { if (waitToSwap) { delaySwaps.push({viewPort, viewPortInstruction}); } loads.push(viewPort.process(viewPortInstruction, waitToSwap).then((x) => { if (viewPortInstruction.childNavigationInstruction) { return viewPortInstruction.childNavigationInstruction._commitChanges(); } return undefined; })); } else { if (viewPortInstruction.childNavigationInstruction) { loads.push(viewPortInstruction.childNavigationInstruction._commitChanges(waitToSwap)); } } } return Promise.all(loads).then(() => { delaySwaps.forEach(x => x.viewPort.swap(x.viewPortInstruction)); return null; }).then(() => prune(this)); } _updateTitle(): void { let title = this._buildTitle(); if (title) { this.router.history.setTitle(title); } } _buildTitle(separator: string = ' | '): string { let title = this.config.navModel.title || ''; let childTitles = []; for (let viewPortName in this.viewPortInstructions) { let viewPortInstruction = this.viewPortInstructions[viewPortName]; if (viewPortInstruction.childNavigationInstruction) { let childTitle = viewPortInstruction.childNavigationInstruction._buildTitle(separator); if (childTitle) { childTitles.push(childTitle); } } } if (childTitles.length) { title = childTitles.join(separator) + (title ? separator : '') + title; } if (this.router.title) { title += (title ? separator : '') + this.router.title; } return title; } } function prune(instruction) { instruction.previousInstruction = null; instruction.plan = null; }
JavaScript
0.000001
@@ -1346,16 +1346,73 @@ : any;%0A%0A + /**%0A * The router instance.%0A */%0A router: Router;%0A%0A plan:
b16b4771812102abfb1ef09a9611175bf0187999
use `MouseEvent.button` instead of `event.which` (#270)
src/js/page/ui/pan-zoom.js
src/js/page/ui/pan-zoom.js
function getXY(obj) { return { x: obj.pageX, y: obj.pageY }; } function touchDistance(touch1, touch2) { const dx = Math.abs(touch2.x - touch1.x); const dy = Math.abs(touch2.y - touch1.y); return Math.sqrt(dx*dx + dy*dy); } function getMidpoint(point1, point2) { return { x: (point1.x + point2.x) / 2, y: (point1.y + point2.y) / 2 }; } function getPoints(event) { if (event.touches) { return Array.from(event.touches).map(t => getXY(t)); } else { return [getXY(event)]; } } export default class PanZoom { constructor(target, { eventArea = target, shouldCaptureFunc = () => true }={}) { this._target = target; this._shouldCaptureFunc = shouldCaptureFunc; this._dx = 0; this._dy = 0; this._scale = 1; this._active = 0; this._lastPoints = []; // bind [ '_onPointerDown', '_onPointerMove', '_onPointerUp' ].forEach(funcName => { this[funcName] = this[funcName].bind(this); }); // bound events eventArea.addEventListener('mousedown', this._onPointerDown); eventArea.addEventListener('touchstart', this._onPointerDown); // unbonud eventArea.addEventListener('wheel', e => this._onWheel(e)); } reset() { this._dx = 0; this._dy = 0; this._scale = 1; this._update(); } _onWheel(event) { if (!this._shouldCaptureFunc(event.target)) return; event.preventDefault(); const boundingRect = this._target.getBoundingClientRect(); let delta = event.deltaY; if (event.deltaMode === 1) { // 1 is "lines", 0 is "pixels" // Firefox uses "lines" when mouse is connected delta *= 15; } // stop mouse wheel producing huge values delta = Math.max(Math.min(delta, 60), -60); const scaleDiff = (delta / 300) + 1; // avoid to-small values if (this._scale * scaleDiff < 0.05) return; this._scale *= scaleDiff; this._dx -= (event.pageX - boundingRect.left) * (scaleDiff - 1); this._dy -= (event.pageY - boundingRect.top) * (scaleDiff - 1); this._update(); } _onFirstPointerDown() { document.addEventListener('mousemove', this._onPointerMove); document.addEventListener('mouseup', this._onPointerUp); document.addEventListener('touchmove', this._onPointerMove); document.addEventListener('touchend', this._onPointerUp); } _onPointerDown(event) { if (event.type == 'mousedown' && event.which != 1) return; if (!this._shouldCaptureFunc(event.target)) return; event.preventDefault(); this._lastPoints = getPoints(event); this._active++; if (this._active === 1) { this._onFirstPointerDown(); } } _onPointerMove(event) { event.preventDefault(); const points = getPoints(event); const averagePoint = points.reduce(getMidpoint); const averageLastPoint = this._lastPoints.reduce(getMidpoint); const boundingRect = this._target.getBoundingClientRect(); this._dx += averagePoint.x - averageLastPoint.x; this._dy += averagePoint.y - averageLastPoint.y; if (points[1]) { const scaleDiff = touchDistance(points[0], points[1]) / touchDistance(this._lastPoints[0], this._lastPoints[1]); this._scale *= scaleDiff; this._dx -= (averagePoint.x - boundingRect.left) * (scaleDiff - 1); this._dy -= (averagePoint.y - boundingRect.top) * (scaleDiff - 1); } this._update(); this._lastPoints = points; } _update() { this._target.style.transform = `translate3d(${this._dx}px, ${this._dy}px, 0) scale(${this._scale})`; } _onPointerUp(event) { event.preventDefault(); this._active--; this._lastPoints.pop(); if (this._active) { this._lastPoints = getPoints(event); return; } document.removeEventListener('mousemove', this._onPointerMove); document.removeEventListener('mouseup', this._onPointerUp); document.removeEventListener('touchmove', this._onPointerMove); document.removeEventListener('touchend', this._onPointerUp); } }
JavaScript
0
@@ -2436,18 +2436,20 @@ ent. -which != 1 +button !== 0 ) re
97a7a55a7cb3c374a314cc0561fbae768ad8caae
Add statistics button
src/injectscripts/nitc.js
src/injectscripts/nitc.js
$("#lighthouseExportButton").on('click mouseenter', function() { var exports = JSON.parse(filterDataForExport()); var href = lighthouseUrl + "pages/nitcexport.html?host=" + location.hostname + "&start=" + encodeURIComponent(exports.StartDate) + "&end=" + encodeURIComponent(exports.EndDate); if (exports.hasOwnProperty("EntityIds")) href += "&EntityIds=" + exports.EntityIds; if (exports.hasOwnProperty("NonIncidentTypeIds")) href += "&NonIncidentTypeIds=" + exports.NonIncidentTypeIds; if (exports.hasOwnProperty("TagIds")) href += "&TagIds=" + exports.TagIds; if (exports.hasOwnProperty("IncludeCompleted")) href += "&IncludeCompleted=" + exports.IncludeCompleted; $(this).attr("href", href); }); function filterDataForExport() { var n=contentViewModel.lastReceivedFilterData; return n.PageIndex=1,n.PageSize=contentViewModel.totalNonIncidents(), n.SortField=contentViewModel.sortColumn(), n.SortOrder=contentViewModel.sortDirection(), JSON.stringify(n) }
JavaScript
0.000001
@@ -745,16 +745,764 @@ );%0A%7D);%0A%0A +$(%22#lighthouseStatsButton%22).on('click mouseenter', function() %7B%0A var exports = JSON.parse(filterDataForExport());%0A var href = lighthouseUrl + %22pages/nitcstats.html?host=%22 + location.hostname +%0A %22&start=%22 + encodeURIComponent(exports.StartDate) + %22&end=%22 +%0A encodeURIComponent(exports.EndDate);%0A if (exports.hasOwnProperty(%22EntityIds%22))%0A href += %22&EntityIds=%22 + exports.EntityIds;%0A if (exports.hasOwnProperty(%22NonIncidentTypeIds%22))%0A href += %22&NonIncidentTypeIds=%22 + exports.NonIncidentTypeIds;%0A if (exports.hasOwnProperty(%22TagIds%22))%0A href += %22&TagIds=%22 + exports.TagIds;%0A if (exports.hasOwnProperty(%22IncludeCompleted%22))%0A href += %22&IncludeCompleted=%22 + exports.IncludeCompleted;%0A $(this).attr(%22href%22, href);%0A%7D);%0A%0A function
7e842b0850cc8223d34af98e6af4a043f747845f
Fix option name zoomInTipLabel
src/ol/control/zoomcontrol.js
src/ol/control/zoomcontrol.js
// FIXME works for View2D only goog.provide('ol.control.Zoom'); goog.require('goog.asserts'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.events'); goog.require('goog.events.EventType'); goog.require('ol.View2D'); goog.require('ol.animation'); goog.require('ol.control.Control'); goog.require('ol.css'); goog.require('ol.easing'); /** * Create a new control with 2 buttons, one for zoom in and one for zoom out. * This control is part of the default controls of a map. To style this control * use css selectors `.ol-zoom-in` and `.ol-zoom-out`. * @constructor * @extends {ol.control.Control} * @param {olx.control.ZoomOptions=} opt_options Zoom options. * @todo stability experimental */ ol.control.Zoom = function(opt_options) { var options = goog.isDef(opt_options) ? opt_options : {}; var className = goog.isDef(options.className) ? options.className : 'ol-zoom'; var delta = goog.isDef(options.delta) ? options.delta : 1; var zoomInLabel = goog.isDef(options.zoomInLabel) ? options.zoomInLabel : '+'; var zoomOutLabel = goog.isDef(options.zoomOutLabel) ? options.zoomOutLabel : '\u2212'; var zoomInTipLabel = goog.isDef(options.zoomTipLabel) ? options.zoomInTipLabel : 'Zoom in'; var zoomOutTipLabel = goog.isDef(options.zoomOutTipLabel) ? options.zoomOutTipLabel : 'Zoom out'; var tTipZoomIn = goog.dom.createDom(goog.dom.TagName.SPAN, { 'role' : 'tooltip' }, zoomInTipLabel); var inElement = goog.dom.createDom(goog.dom.TagName.BUTTON, { 'class': className + '-in ol-has-tooltip', 'name' : 'ZoomIn', 'type' : 'button' }, tTipZoomIn, zoomInLabel); goog.events.listen(inElement, [ goog.events.EventType.TOUCHEND, goog.events.EventType.CLICK ], goog.partial(ol.control.Zoom.prototype.zoomByDelta_, delta), false, this); var tTipsZoomOut = goog.dom.createDom(goog.dom.TagName.SPAN, { 'role' : 'tooltip', 'type' : 'button' }, zoomOutTipLabel); var outElement = goog.dom.createDom(goog.dom.TagName.BUTTON, { 'class': className + '-out ol-has-tooltip', 'name' : 'ZoomOut' }, tTipsZoomOut, zoomOutLabel); goog.events.listen(outElement, [ goog.events.EventType.TOUCHEND, goog.events.EventType.CLICK ], goog.partial(ol.control.Zoom.prototype.zoomByDelta_, -delta), false, this); var cssClasses = className + ' ' + ol.css.CLASS_UNSELECTABLE; var element = goog.dom.createDom(goog.dom.TagName.DIV, cssClasses, inElement, outElement); goog.base(this, { element: element, target: options.target }); /** * @type {number} * @private */ this.duration_ = goog.isDef(options.duration) ? options.duration : 250; }; goog.inherits(ol.control.Zoom, ol.control.Control); /** * @param {number} delta Zoom delta. * @param {goog.events.BrowserEvent} browserEvent The browser event to handle. * @private */ ol.control.Zoom.prototype.zoomByDelta_ = function(delta, browserEvent) { browserEvent.preventDefault(); // prevent the anchor from getting appended to the url var map = this.getMap(); // FIXME works for View2D only var view = map.getView(); goog.asserts.assert(goog.isDef(view)); var view2D = view.getView2D(); goog.asserts.assertInstanceof(view2D, ol.View2D); var currentResolution = view2D.getResolution(); if (goog.isDef(currentResolution)) { if (this.duration_ > 0) { map.beforeRender(ol.animation.zoom({ resolution: currentResolution, duration: this.duration_, easing: ol.easing.easeOut })); } var newResolution = view2D.constrainResolution(currentResolution, delta); view2D.setResolution(newResolution); } };
JavaScript
0.999287
@@ -1206,16 +1206,18 @@ ons.zoom +In TipLabel
b53d74285bdf3759a6eb7be8ccd31b60a94effd5
Fix checks for undefined in zoom control
src/ol/control/zoomcontrol.js
src/ol/control/zoomcontrol.js
goog.provide('ol.control.Zoom'); goog.require('goog.dom'); goog.require('ol.events'); goog.require('ol.events.EventType'); goog.require('ol.animation'); goog.require('ol.control.Control'); goog.require('ol.css'); goog.require('ol.easing'); /** * @classdesc * A control with 2 buttons, one for zoom in and one for zoom out. * This control is one of the default controls of a map. To style this control * use css selectors `.ol-zoom-in` and `.ol-zoom-out`. * * @constructor * @extends {ol.control.Control} * @param {olx.control.ZoomOptions=} opt_options Zoom options. * @api stable */ ol.control.Zoom = function(opt_options) { var options = opt_options ? opt_options : {}; var className = options.className ? options.className : 'ol-zoom'; var delta = options.delta ? options.delta : 1; var zoomInLabel = options.zoomInLabel ? options.zoomInLabel : '+'; var zoomOutLabel = options.zoomOutLabel ? options.zoomOutLabel : '\u2212'; var zoomInTipLabel = options.zoomInTipLabel ? options.zoomInTipLabel : 'Zoom in'; var zoomOutTipLabel = options.zoomOutTipLabel ? options.zoomOutTipLabel : 'Zoom out'; var inElement = goog.dom.createDom('BUTTON', { 'class': className + '-in', 'type' : 'button', 'title': zoomInTipLabel }, zoomInLabel); ol.events.listen(inElement, ol.events.EventType.CLICK, goog.partial( ol.control.Zoom.prototype.handleClick_, delta), this); var outElement = goog.dom.createDom('BUTTON', { 'class': className + '-out', 'type' : 'button', 'title': zoomOutTipLabel }, zoomOutLabel); ol.events.listen(outElement, ol.events.EventType.CLICK, goog.partial( ol.control.Zoom.prototype.handleClick_, -delta), this); var cssClasses = className + ' ' + ol.css.CLASS_UNSELECTABLE + ' ' + ol.css.CLASS_CONTROL; var element = goog.dom.createDom('DIV', cssClasses, inElement, outElement); goog.base(this, { element: element, target: options.target }); /** * @type {number} * @private */ this.duration_ = options.duration !== undefined ? options.duration : 250; }; goog.inherits(ol.control.Zoom, ol.control.Control); /** * @param {number} delta Zoom delta. * @param {Event} event The event to handle * @private */ ol.control.Zoom.prototype.handleClick_ = function(delta, event) { event.preventDefault(); this.zoomByDelta_(delta); }; /** * @param {number} delta Zoom delta. * @private */ ol.control.Zoom.prototype.zoomByDelta_ = function(delta) { var map = this.getMap(); var view = map.getView(); if (!view) { // the map does not have a view, so we can't act // upon it return; } var currentResolution = view.getResolution(); if (currentResolution) { if (this.duration_ > 0) { map.beforeRender(ol.animation.zoom({ resolution: currentResolution, duration: this.duration_, easing: ol.easing.easeOut })); } var newResolution = view.constrainResolution(currentResolution, delta); view.setResolution(newResolution); } };
JavaScript
0
@@ -717,16 +717,30 @@ assName +!== undefined ? option @@ -793,16 +793,30 @@ s.delta +!== undefined ? option @@ -865,24 +865,38 @@ zoomInLabel +!== undefined ? options.zo @@ -954,16 +954,30 @@ utLabel +!== undefined ? option @@ -1042,32 +1042,46 @@ .zoomInTipLabel +!== undefined ?%0A options. @@ -1156,16 +1156,30 @@ ipLabel +!== undefined ?%0A
ec811bfa1f2a42a406f44d154d0d6b74a5b2feb9
Add primaryAction condition to DragPan interaction
src/ol/interaction/DragPan.js
src/ol/interaction/DragPan.js
/** * @module ol/interaction/DragPan */ import {scale as scaleCoordinate, rotate as rotateCoordinate} from '../coordinate.js'; import {easeOut} from '../easing.js'; import {noModifierKeys} from '../events/condition.js'; import {FALSE} from '../functions.js'; import PointerInteraction, {centroid as centroidFromPointers} from './Pointer.js'; /** * @typedef {Object} Options * @property {import("../events/condition.js").Condition} [condition] A function that takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a boolean * to indicate whether that event should be handled. * Default is {@link module:ol/events/condition~noModifierKeys}. * @property {import("../Kinetic.js").default} [kinetic] Kinetic inertia to apply to the pan. */ /** * @classdesc * Allows the user to pan the map by dragging the map. * @api */ class DragPan extends PointerInteraction { /** * @param {Options=} opt_options Options. */ constructor(opt_options) { super({ stopDown: FALSE }); const options = opt_options ? opt_options : {}; /** * @private * @type {import("../Kinetic.js").default|undefined} */ this.kinetic_ = options.kinetic; /** * @type {import("../pixel.js").Pixel} */ this.lastCentroid = null; /** * @type {number} */ this.lastPointersCount_; /** * @type {boolean} */ this.panning_ = false; /** * @private * @type {import("../events/condition.js").Condition} */ this.condition_ = options.condition ? options.condition : noModifierKeys; /** * @private * @type {boolean} */ this.noKinetic_ = false; } /** * @inheritDoc */ handleDragEvent(mapBrowserEvent) { if (!this.panning_) { this.panning_ = true; this.getMap().getView().beginInteraction(); } const targetPointers = this.targetPointers; const centroid = centroidFromPointers(targetPointers); if (targetPointers.length == this.lastPointersCount_) { if (this.kinetic_) { this.kinetic_.update(centroid[0], centroid[1]); } if (this.lastCentroid) { const delta = [ this.lastCentroid[0] - centroid[0], centroid[1] - this.lastCentroid[1] ]; const map = mapBrowserEvent.map; const view = map.getView(); scaleCoordinate(delta, view.getResolution()); rotateCoordinate(delta, view.getRotation()); view.adjustCenter(delta); } } else if (this.kinetic_) { // reset so we don't overestimate the kinetic energy after // after one finger down, tiny drag, second finger down this.kinetic_.begin(); } this.lastCentroid = centroid; this.lastPointersCount_ = targetPointers.length; } /** * @inheritDoc */ handleUpEvent(mapBrowserEvent) { const map = mapBrowserEvent.map; const view = map.getView(); if (this.targetPointers.length === 0) { if (!this.noKinetic_ && this.kinetic_ && this.kinetic_.end()) { const distance = this.kinetic_.getDistance(); const angle = this.kinetic_.getAngle(); const center = /** @type {!import("../coordinate.js").Coordinate} */ (view.getCenter()); const centerpx = map.getPixelFromCoordinate(center); const dest = map.getCoordinateFromPixel([ centerpx[0] - distance * Math.cos(angle), centerpx[1] - distance * Math.sin(angle) ]); view.animate({ center: view.getConstrainedCenter(dest), duration: 500, easing: easeOut }); } if (this.panning_) { this.panning_ = false; view.endInteraction(); } return false; } else { if (this.kinetic_) { // reset so we don't overestimate the kinetic energy after // after one finger up, tiny drag, second finger up this.kinetic_.begin(); } this.lastCentroid = null; return true; } } /** * @inheritDoc */ handleDownEvent(mapBrowserEvent) { if (this.targetPointers.length > 0 && this.condition_(mapBrowserEvent)) { const map = mapBrowserEvent.map; const view = map.getView(); this.lastCentroid = null; // stop any current animation if (view.getAnimating()) { view.cancelAnimations(); } if (this.kinetic_) { this.kinetic_.begin(); } // No kinetic as soon as more than one pointer on the screen is // detected. This is to prevent nasty pans after pinch. this.noKinetic_ = this.targetPointers.length > 1; return true; } else { return false; } } } export default DragPan;
JavaScript
0
@@ -182,16 +182,31 @@ fierKeys +, primaryAction %7D from ' @@ -670,16 +670,69 @@ ierKeys%7D + and %7B@link module:ol/events/condition~primaryAction%7D .%0A * @pr @@ -1639,30 +1639,32 @@ ition : -noModifierKeys +defaultCondition ;%0A%0A / @@ -4731,16 +4731,258 @@ %0A %7D%0A%7D%0A%0A +/**%0A * @param %7Bol.MapBrowserEvent%7D mapBrowserEvent Browser event.%0A * @return %7Bboolean%7D Combined condition result.%0A */%0Afunction defaultCondition(mapBrowserEvent) %7B%0A return noModifierKeys(mapBrowserEvent) && primaryAction(mapBrowserEvent);%0A%7D%0A%0A export d
9ed5bf87a126fb69f215684998ea5849eea5c473
Fix user cover images
ghost/admin/controllers/settings/users/user.js
ghost/admin/controllers/settings/users/user.js
import SlugGenerator from 'ghost/models/slug-generator'; var SettingsUserController = Ember.ObjectController.extend({ user: Ember.computed.alias('model'), email: Ember.computed.readOnly('user.email'), slugValue: Ember.computed.oneWay('user.slug'), lastPromise: null, coverDefault: Ember.computed('ghostPaths', function () { return this.get('ghostPaths.url').asset('/shared/img/user-cover.png'); }), userDefault: Ember.computed('ghostPaths', function () { return this.get('ghostPaths.url').asset('/shared/img/user-image.png'); }), cover: Ember.computed('user.cover', 'coverDefault', function () { var cover = this.get('user.cover'); if (Ember.isBlank(cover)) { cover = this.get('coverDefault'); } return cover; }), coverTitle: Ember.computed('user.name', function () { return this.get('user.name') + '\'s Cover Image'; }), image: Ember.computed('imageUrl', function () { return 'background-image: url(' + this.get('imageUrl') + ')'; }), imageUrl: Ember.computed('user.image', function () { return this.get('user.image') || this.get('userDefault'); }), last_login: Ember.computed('user.last_login', function () { var lastLogin = this.get('user.last_login'); return lastLogin ? lastLogin.fromNow() : ''; }), created_at: Ember.computed('user.created_at', function () { var createdAt = this.get('user.created_at'); return createdAt ? createdAt.fromNow() : ''; }), //Lazy load the slug generator for slugPlaceholder slugGenerator: Ember.computed(function () { return SlugGenerator.create({ ghostPaths: this.get('ghostPaths'), slugType: 'user' }); }), actions: { changeRole: function (newRole) { this.set('model.role', newRole); }, revoke: function () { var self = this, model = this.get('model'), email = this.get('email'); //reload the model to get the most up-to-date user information model.reload().then(function () { if (self.get('invited')) { model.destroyRecord().then(function () { var notificationText = 'Invitation revoked. (' + email + ')'; self.notifications.showSuccess(notificationText, false); }).catch(function (error) { self.notifications.showAPIError(error); }); } else { //if the user is no longer marked as "invited", then show a warning and reload the route self.get('target').send('reload'); self.notifications.showError('This user has already accepted the invitation.', {delayed: 500}); } }); }, resend: function () { var self = this; this.get('model').resendInvite().then(function (result) { var notificationText = 'Invitation resent! (' + self.get('email') + ')'; // If sending the invitation email fails, the API will still return a status of 201 // but the user's status in the response object will be 'invited-pending'. if (result.users[0].status === 'invited-pending') { self.notifications.showWarn('Invitation email was not sent. Please try resending.'); } else { self.get('model').set('status', result.users[0].status); self.notifications.showSuccess(notificationText); } }).catch(function (error) { self.notifications.showAPIError(error); }); }, save: function () { var user = this.get('user'), slugValue = this.get('slugValue'), afterUpdateSlug = this.get('lastPromise'), promise, slugChanged, self = this; if (user.get('slug') !== slugValue) { slugChanged = true; user.set('slug', slugValue); } promise = Ember.RSVP.resolve(afterUpdateSlug).then(function () { return user.save({ format: false }); }).then(function (model) { var currentPath, newPath; self.notifications.showSuccess('Settings successfully saved.'); // If the user's slug has changed, change the URL and replace // the history so refresh and back button still work if (slugChanged) { currentPath = window.history.state.path; newPath = currentPath.split('/'); newPath[newPath.length - 2] = model.get('slug'); newPath = newPath.join('/'); window.history.replaceState({ path: newPath }, '', newPath); } return model; }).catch(function (errors) { self.notifications.showErrors(errors); }); this.set('lastPromise', promise); }, password: function () { var user = this.get('user'), self = this; if (user.get('isPasswordValid')) { user.saveNewPassword().then(function (model) { // Clear properties from view user.setProperties({ 'password': '', 'newPassword': '', 'ne2Password': '' }); self.notifications.showSuccess('Password updated.'); return model; }).catch(function (errors) { self.notifications.showAPIError(errors); }); } else { self.notifications.showErrors(user.get('passwordValidationErrors')); } }, updateSlug: function (newSlug) { var self = this, afterSave = this.get('lastPromise'), promise; promise = Ember.RSVP.resolve(afterSave).then(function () { var slug = self.get('slug'); newSlug = newSlug || slug; newSlug = newSlug.trim(); // Ignore unchanged slugs or candidate slugs that are empty if (!newSlug || slug === newSlug) { self.set('slugValue', slug); return; } return self.get('slugGenerator').generateSlug(newSlug).then(function (serverSlug) { // If after getting the sanitized and unique slug back from the API // we end up with a slug that matches the existing slug, abort the change if (serverSlug === slug) { return; } // Because the server transforms the candidate slug by stripping // certain characters and appending a number onto the end of slugs // to enforce uniqueness, there are cases where we can get back a // candidate slug that is a duplicate of the original except for // the trailing incrementor (e.g., this-is-a-slug and this-is-a-slug-2) // get the last token out of the slug candidate and see if it's a number var slugTokens = serverSlug.split('-'), check = Number(slugTokens.pop()); // if the candidate slug is the same as the existing slug except // for the incrementor then the existing slug should be used if (_.isNumber(check) && check > 0) { if (slug === slugTokens.join('-') && serverSlug !== newSlug) { self.set('slugValue', slug); return; } } self.set('slugValue', serverSlug); }); }); this.set('lastPromise', promise); } } }); export default SettingsUserController;
JavaScript
0
@@ -800,21 +800,54 @@ return -cover +'background-image: url(' + cover + ')' ;%0A %7D)
a81fb8c5c274611081a3303f343e444b526de4e0
Update OU Theorymon
mods/theorymon/scripts.js
mods/theorymon/scripts.js
exports.BattleScripts = { init: function () { this.modData('Pokedex', 'archeops').abilities['1'] = 'Vital Spirit'; this.modData('Pokedex', 'porygonz').types = ['Normal', 'Ghost']; this.modData('Pokedex', 'weezing').types = ['Poison', 'Steel']; this.modData('Pokedex', 'moltres').abilities['1'] = 'Magic Guard'; this.modData('Pokedex', 'abomasnowmega').abilities['0'] = 'Technician'; this.modData('Pokedex', 'cradily').abilities['1'] = 'Sand Stream'; this.modData('Pokedex', 'froslass').abilities['1'] = 'Prankster'; this.modData('Learnsets', 'absol').learnset.partingshot = ['6T']; this.modData('Pokedex', 'goodra').abilities['1'] = 'Protean'; this.modData('Pokedex', 'entei').abilities['1'] = 'Defiant'; this.modData('Pokedex', 'milotic').abilities['H'] = 'Multiscale'; this.modData('Pokedex', 'empoleon').abilities['1'] = 'Lightning Rod'; this.modData('Learnsets', 'reuniclus').learnset.voltswitch = ['6T']; this.modData('Pokedex', 'steelixmega').abilities['0'] = 'Arena Trap'; this.modData('Pokedex', 'audinomega').abilities['0'] = 'Simple'; this.modData('Learnsets', 'ampharos').learnset.wish = ['6T']; this.modData('Pokedex', 'absolmega').types = ['Dark', 'Fairy']; this.modData('Pokedex', 'weavile').abilities['1'] = 'Moxie'; this.modData('Learnsets', 'pangoro').learnset.suckerpunch = ['6T']; this.modData('Pokedex', 'rotomfan').types = ['Electric', 'Steel']; this.modData('Learnsets', 'rotomfan').learnset.flashcannon = this.data.Learnsets.rotomfan.learnset.airslash; this.modData('Learnsets', 'rotomfan').learnset.airslash = null; this.modData('Learnsets', 'mantine').learnset.roost = ['6T']; this.modData('Learnsets', 'pidgeot').learnset.focusblast = ['6T']; this.modData('Pokedex', 'granbull').abilities['1'] = 'Fur Coat'; } };
JavaScript
0
@@ -1778,14 +1778,83 @@ Coat';%0A +%09%09this.modData('Pokedex', 'aggronmega').types = %5B'Steel', 'Dragon'%5D;%0A %09%7D%0A%7D;%0A
7285a7e7794af8965223e9439a2306a58f263fa2
update tests to reflect new model api
front_end/js/tests/specs/reg-data-spec.js
front_end/js/tests/specs/reg-data-spec.js
define(['regs-data', 'samplejson'], function(RegsData, testjson) { describe("RegsData module", function() { RegsData.parse(testjson); it("should have a regStructure array", function() { expect(RegsData.regStructure).toBeTruthy(); }); it("should have a regStructure array with 7 values", function() { expect(RegsData.regStructure.length).toEqual( 7 ); }); it("should have content", function() { expect(RegsData.content).toBeTruthy(); }); it("should have content for 2345-9-a", function() { var content = "<p><dfn>placerat in egestas.</dfn> Sed erat enim, hendrerit mollis tempus et, consequat et ante. Donec imperdiet orci eget nisi lobortis molestie. Nullam pellentesque scelerisque hendrerit</p>"; expect(RegsData.content['2345-9-a'].valueOf()).toEqual(content); }); it("should retrieve 2345-9", function() { expect(RegsData.retrieve('2345-9')).toEqual("asdfksjflksjdf"); }); it("should get children", function() { var arr = ["2345-9-a-2", "2345-9-a-1"]; expect(RegsData.getChildren('2345-9-a')).toEqual(arr); }); it("should not get children", function() { expect(RegsData.getChildren('233')).toEqual([]); }); it("should get parent", function() { expect(RegsData.getParent('2345-9-b')).toEqual("asdfksjflksjdf"); }); it("should differentiate between regStructure presence and being loaded", function() { expect(RegsData.isLoaded("2345-9-b-1")).toEqual(false); }); }); });
JavaScript
0
@@ -295,17 +295,17 @@ ay with -7 +8 values%22 @@ -375,9 +375,9 @@ al( -7 +8 );%0A @@ -850,24 +850,19 @@ %22should -r +g et -rieve 2345-9%22 @@ -902,16 +902,11 @@ ata. -r +g et -rieve ('23 @@ -1460,16 +1460,11 @@ ata. -isLoaded +has (%2223
377659959242db6389d110ff9b60f8d421b6d5ee
Add test for the "each" method
src/lib/collection.spec.js
src/lib/collection.spec.js
let Collection = require('./collection'); describe('Collection', function () { let collection; beforeEach(function () { collection = new Collection(); }); describe('when instantiating without items', function () { it('should instantiate', function () { expect(collection).toBeDefined(); }); it('should have an empty data object', function () { expect(collection.data).toEqual({}); }); }); describe('when instantiating with items', function () { let foo, bar, baz; beforeEach(function () { foo = {name: 'foo'}; bar = {name: 'bar'}; baz = {name: 'baz'}; collection = new Collection(foo, bar, baz); }); it('should instantiate', function () { expect(collection).toBeDefined(); }); it('should have those items in its data object', function () { expect(collection.data[foo.id]).toEqual(foo); expect(collection.data[bar.id]).toEqual(bar); expect(collection.data[baz.id]).toEqual(baz); }); }); describe('when adding an item', function () { let item; beforeEach(function () { item = {name: 'foo'}; collection.add(item); }); it('should place the item in its data object', function () { expect(collection.data[item.id]).toEqual(item); }); }); describe('when removing an item', function () { let item; beforeEach(function () { item = {name: 'foo'}; collection.add(item); collection.remove(item); }); it('should place the item in its data object', function () { expect(collection.data[item.id]).toBeUndefined(); }); }); });
JavaScript
0.998437
@@ -1838,13 +1838,493 @@ %0A %7D); +%0A%0A describe('when iterating through data with the each method', function () %7B%0A let item;%0A let count;%0A%0A beforeEach(function () %7B%0A item = %7Bname: 'foo'%7D;%0A collection.add(%7Bname: 'foo'%7D, %7Bname: 'bar'%7D, %7Bname: 'baz'%7D);%0A count = 0;%0A collection.each(function (item) %7B count++; %7D);%0A %7D);%0A%0A it('should invoke the callback once per item', function () %7B%0A expect(count).toEqual(3);%0A %7D);%0A %7D); %0A%7D);%0A
1bc596b822ef3a8eacf4fcbe1c211cde4233d011
fix formatting of custom usage field
src/ng/directive/ngSwitch.js
src/ng/directive/ngSwitch.js
'use strict'; /** * @ngdoc directive * @name ngSwitch * @restrict EA * * @description * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location * as specified in the template. * * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element * matches the value obtained from the evaluated expression. In other words, you define a container element * (where you place the directive), place an expression on the **`on="..."` attribute** * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default * attribute is displayed. * * <div class="alert alert-info"> * Be aware that the attribute values to match against cannot be expressions. They are interpreted * as literal string values to match against. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the * value of the expression `$scope.someVal`. * </div> * @animations * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM * * @usage * <ANY ng-switch="expression"> * <ANY ng-switch-when="matchValue1">...</ANY> * <ANY ng-switch-when="matchValue2">...</ANY> * <ANY ng-switch-default>...</ANY> * </ANY> * * * @scope * @priority 800 * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>. * On child elements add: * * * `ngSwitchWhen`: the case statement to match against. If match then this * case will be displayed. If the same match appears multiple times, all the * elements will be displayed. * * `ngSwitchDefault`: the default case when no other case match. If there * are multiple default cases, all of them will be displayed when no other * case match. * * * @example <example module="ngAnimate" deps="angular-animate.js" animations="true"> <file name="index.html"> <div ng-controller="Ctrl"> <select ng-model="selection" ng-options="item for item in items"> </select> <tt>selection={{selection}}</tt> <hr/> <div class="animate-switch-container" ng-switch on="selection"> <div class="animate-switch" ng-switch-when="settings">Settings Div</div> <div class="animate-switch" ng-switch-when="home">Home Span</div> <div class="animate-switch" ng-switch-default>default</div> </div> </div> </file> <file name="script.js"> function Ctrl($scope) { $scope.items = ['settings', 'home', 'other']; $scope.selection = $scope.items[0]; } </file> <file name="animations.css"> .animate-switch-container { position:relative; background:white; border:1px solid black; height:40px; overflow:hidden; } .animate-switch { padding:10px; } .animate-switch.ng-animate { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; position:absolute; top:0; left:0; right:0; bottom:0; } .animate-switch.ng-leave.ng-leave-active, .animate-switch.ng-enter { top:-50px; } .animate-switch.ng-leave, .animate-switch.ng-enter.ng-enter-active { top:0; } </file> <file name="protractor.js" type="protractor"> var switchElem = element(by.css('[ng-switch]')); var select = element(by.model('selection')); it('should start in settings', function() { expect(switchElem.getText()).toMatch(/Settings Div/); }); it('should change to home', function() { select.element.all(by.css('option')).get(1).click(); expect(switchElem.getText()).toMatch(/Home Span/); }); it('should select default', function() { select.element.all(by.css('option')).get(2).click(); expect(switchElem.getText()).toMatch(/default/); }); </file> </example> */ var ngSwitchDirective = ['$animate', function($animate) { return { restrict: 'EA', require: 'ngSwitch', // asks for $scope to fool the BC controller module controller: ['$scope', function ngSwitchController() { this.cases = {}; }], link: function(scope, element, attr, ngSwitchController) { var watchExpr = attr.ngSwitch || attr.on, selectedTranscludes, selectedElements, previousElements, selectedScopes = []; scope.$watch(watchExpr, function ngSwitchWatchAction(value) { var i, ii = selectedScopes.length; if(ii > 0) { if(previousElements) { for (i = 0; i < ii; i++) { previousElements[i].remove(); } previousElements = null; } previousElements = []; for (i= 0; i<ii; i++) { var selected = selectedElements[i]; selectedScopes[i].$destroy(); previousElements[i] = selected; $animate.leave(selected, function() { previousElements.splice(i, 1); if(previousElements.length === 0) { previousElements = null; } }); } } selectedElements = []; selectedScopes = []; if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) { scope.$eval(attr.change); forEach(selectedTranscludes, function(selectedTransclude) { var selectedScope = scope.$new(); selectedScopes.push(selectedScope); selectedTransclude.transclude(selectedScope, function(caseElement) { var anchor = selectedTransclude.element; selectedElements.push(caseElement); $animate.enter(caseElement, anchor.parent(), anchor); }); }); } }); } }; }]; var ngSwitchWhenDirective = ngDirective({ transclude: 'element', priority: 800, require: '^ngSwitch', link: function(scope, element, attrs, ctrl, $transclude) { ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []); ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element }); } }); var ngSwitchDefaultDirective = ngDirective({ transclude: 'element', priority: 800, require: '^ngSwitch', link: function(scope, element, attr, ctrl, $transclude) { ctrl.cases['?'] = (ctrl.cases['?'] || []); ctrl.cases['?'].push({ transclude: $transclude, element: element }); } });
JavaScript
0.000001
@@ -1771,16 +1771,26 @@ @usage%0A + *%0A * %60%60%60%0A * %3CANY @@ -1959,16 +1959,23 @@ %3C/ANY%3E%0A + * %60%60%60%0A *%0A *%0A *
d20b418422781e7e7202d872ef943a8648fd5435
rename test name for commands
test/arbitrary/commands.js
test/arbitrary/commands.js
"use strict"; const assert = require('assert'); const jsc = require('jsverify'); const lazyseq = require("lazy-seq"); const {commands} = require('../../src/arbitrary/commands'); const GENSIZE = 10; var fakeJscCommand = function(ClassType) { return jsc.bless({ generator: size => new Object({ command: new ClassType(), parameters: [] }), shrink: lazyseq.nil, show: t => "fake" }); }; var fakeClass = function() { return function() {}; }; describe('commands', function() { describe('generator', function() { it('should instantiate an array', function() { jsc.assert(jsc.forall(jsc.integer(1, 1024), function(num) { const classes = [...Array(num).keys()].map(fakeClass); const arbs = classes.map(fakeJscCommand); const arb = commands.apply(this, arbs); var v = arb.generator(GENSIZE); return Array.isArray(v); })); }); it('should instantiate multiple command', function() { jsc.assert(jsc.forall(jsc.integer(1, 1024), function(num) { const classes = [...Array(num).keys()].map(fakeClass); const arbs = classes.map(fakeJscCommand); const arb = commands.apply(this, arbs); var v = arb.generator(GENSIZE); return v.every(cmd => classes.find(c => cmd.command instanceof c) !== undefined); })); }); }); });
JavaScript
0.000063
@@ -1039,24 +1039,24 @@ ate -multiple command +command elements ', f
29799d326e4b69b586df101344824720cdaeecf8
Add energy converter carousel
js/energy-systems/model/EnergySystemsModel.js
js/energy-systems/model/EnergySystemsModel.js
// Copyright 2014-2015, University of Colorado Boulder /** * Model for the 'Energy Systems' screen of the Energy Forms And Changes simulation. * * @author John Blanco * @author Jesse Greenberg * @author Andrew Adare */ define( function( require ) { 'use strict'; // Modules var EnergySystemElementCarousel = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/model/EnergySystemElementCarousel' ); var FaucetAndWater = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/model/FaucetAndWater' ); var inherit = require( 'PHET_CORE/inherit' ); var PropertySet = require( 'AXON/PropertySet' ); var SolarPanel = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/model/SolarPanel' ); var SunEnergySource = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/model/SunEnergySource' ); var TeaPot = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/model/TeaPot' ); var Vector2 = require( 'DOT/Vector2' ); // Constants // For the images (sun, teapot, biker, ...) scrolling like a one-armed bandit, // this is the offset between them (purely vertical). var OFFSET_BETWEEN_ELEMENTS_ON_CAROUSEL = new Vector2( 0, -0.4 ); /** * Main constructor for EnergySystemsModel, which contains all of the model * logic for the entire sim screen. * @constructor */ function EnergySystemsModel() { PropertySet.call( this, { // Boolean property that controls whether the energy chunks are visible to the user. energyChunksVisible: false, steamPowerableElementInPlace: false, waterPowerableElementInPlace: false, // Play/pause state isPlaying: true } ); // Carousels that control the positions of the energy sources, converters, // and users. this.energySourcesCarousel = new EnergySystemElementCarousel( new Vector2( -0.15, 0 ), OFFSET_BETWEEN_ELEMENTS_ON_CAROUSEL ); this.energyConvertersCarousel = new EnergySystemElementCarousel( new Vector2( -0.025, 0 ), OFFSET_BETWEEN_ELEMENTS_ON_CAROUSEL ); this.energyUsersCarousel = new EnergySystemElementCarousel( new Vector2( 0.09, 0 ), OFFSET_BETWEEN_ELEMENTS_ON_CAROUSEL ); // TODO change from the single-element version to all, once the others are non-empty this.carousels = [ this.energySourcesCarousel ]; // this.carousels = [ // this.energySourcesCarousel, // this.energyConvertersCarousel, // this.energyUsersCarousel // ]; this.solarPanel = new SolarPanel( this.energyChunksVisible ); this.sun = new SunEnergySource( this.solarPanel, this.energyChunksVisible ); this.teaPot = new TeaPot( this.energyChunksVisible, this.steamPowerableElementInPlace ); this.faucet = new FaucetAndWater( this.energyChunksVisible, this.waterPowerableElementInPlace ); this.energySourcesCarousel.add( this.sun ); this.energySourcesCarousel.add( this.teaPot ); this.energySourcesCarousel.add( this.faucet ); } return inherit( PropertySet, EnergySystemsModel, { step: function( dt ) { // Elements managed by carousels need to be scrollable/selectable regardless // of play/pause state. this.carousels.forEach( function( carousel ) { carousel.stepInTime( dt ); } ); if ( this.isPlaying ) { // var energyFromSource = this.energySourcesCarousel.getSelectedElement().stepInTime( dt ); } } } ); } );
JavaScript
0
@@ -2121,643 +2121,540 @@ // -TODO change from the single-element version to all, once the others are non-empty%0A this.carousels = %5B%0A this.energySourcesCarousel%0A %5D;%0A // this.carousels = %5B%0A // this.energySourcesCarousel,%0A // this.energyConvertersCarousel,%0A // this.energyUsersCarousel%0A // %5D;%0A%0A this.solarPanel = new SolarPanel( this.energyChunksVisible );%0A this.sun = new SunEnergySource( this.solarPanel, this.energyChunksVisible );%0A this.teaPot = new TeaPot( this.energyChunksVisible, this.steamPowerableElementInPlace );%0A this.faucet = new FaucetAndWater( this.energyChunksVisible, this.waterPowerableElementInPlac +Energy sources%0A this.faucet = new FaucetAndWater( this.energyChunksVisible, this.waterPowerableElementInPlace );%0A this.sun = new SunEnergySource( this.solarPanel, this.energyChunksVisible );%0A this.teaPot = new TeaPot( this.energyChunksVisible, this.steamPowerableElementInPlace );%0A this.energySourcesCarousel.add( this.faucet );%0A this.energySourcesCarousel.add( this.sun );%0A this.energySourcesCarousel.add( this.teaPot );%0A%0A // Energy converters%0A this.solarPanel = new SolarPanel( this.energyChunksVisibl e );%0A -%0A @@ -2656,38 +2656,41 @@ %0A this.energy -Source +Converter sCarousel.add( t @@ -2686,38 +2686,46 @@ usel.add( this.s -un +olarPanel );%0A +%0A this.energyS @@ -2721,99 +2721,131 @@ his. -energySourcesCarousel.add( this.teaPot );%0A this.energySourcesCarousel.add( this.faucet ) +carousels = %5B%0A this.energySourcesCarousel,%0A this.energyConvertersCarousel%0A // this.energyUsersCarousel%0A %5D ;%0A
217b6e8395eda0ff2d95bd16fea9a36672df0a39
Update SecretHug.js
skills/SecretHug.js
skills/SecretHug.js
module.exports = function(skill, info, bot, message, db) { bot.api.users.info({user: message.user}, (error, response) => { let {name, real_name} = response.user; bot.reply(message, 'under development'); }) //bot.reply(message, 'http://foaas.com/everyone/' + bot.identity.name); //bot.reply(message, 'I understood this as ' + skill + ', but you haven\'t configured how to make me work yet! Tell your local code monkey to fill in the code module for ' + skill); };
JavaScript
0
@@ -120,20 +120,16 @@ e) =%3E %7B%0A - let @@ -163,20 +163,16 @@ e.user;%0A - bot. @@ -216,91 +216,187 @@ -%7D) %0A //bot.reply(message, 'http://foaas.com/everyone/' + bot.identity.name);%0A // +var userData = message.text.match(/%3C@(%5BA-Z0%E2%80%939%5D%7B9%7D)%3E/); // parse the text for user's 9 character id%0A%0A if (userData) %7B%0A // if there is a user named send ze hugs!%0A %7D else %7B%0A bot. @@ -415,167 +415,106 @@ e, ' -I understood this as ' + skill + ', but you haven%5C't configured how to make me work yet! Tell your local code monkey to fill in the code module for ' + skill); +You didn%5C't name anyone%E2%80%A6were you the one that needed a hug ' + name + '?');%0A %7D%0A %0A %7D) %0A %0A%7D;%0A
527d185fb68a7c039b4e60b109a625e3b2ca8afe
Use strict mode in config/targets.js to avoid build crash
packages/@glimmer/blueprint/files/config/targets.js
packages/@glimmer/blueprint/files/config/targets.js
let browsers = [ '> 5%', 'last 2 Edge versions', 'last 2 Chrome versions', 'last 2 Firefox versions', 'last 2 Safari versions', ]; if (process.env.EMBER_ENV === 'test') { browsers = [ 'last 1 Chrome versions', 'last 1 Firefox versions' ]; } module.exports = { browsers };
JavaScript
0.000001
@@ -1,8 +1,23 @@ +'use strict';%0A%0A let brow
e167b3ee1d81c3cb32c19122008304d3f5f1ff71
Fix issue with accumulated queries + default pagination limit (#610)
packages/@sanity/preview/src/utils/optimizeQuery.js
packages/@sanity/preview/src/utils/optimizeQuery.js
// @flow import {identity, sortBy, values} from 'lodash' type Path = string[] type Selection = [string[], Path[]] type CombinedSelection = { ids: string[], paths: string[], map: number[], } type Doc = { _id: string } type Result = Doc[] export function combineSelections(selections: Array<Selection>): number { return values(selections.reduce((output, [id, paths], index) => { const key = sortBy(paths.join(','), identity) if (!output[key]) { output[key] = {paths, ids: [], map: []} } const idx = output[key].ids.length output[key].ids[idx] = id output[key].map[idx] = index return output }, {})) } function stringifyId(id: string) { return JSON.stringify(id) } function toSubQuery({ids, paths}) { return `*[_id in [${ids.map(stringifyId).join(',')}]]{_id,_type,${paths.join(',')}}` } export function toGradientQuery(combinedSelections: CombinedSelection[]) { return `[${combinedSelections.map(toSubQuery).join(',')}]` } export function reassemble(queryResult: Result[], combinedSelections: CombinedSelection[]) { return queryResult.reduce((reprojected, subResult, index) => { const map = combinedSelections[index].map map.forEach((resultIdx, i) => { const id = combinedSelections[index].ids[i] reprojected[resultIdx] = subResult.find(doc => doc._id === id) }) return reprojected }, []) }
JavaScript
0
@@ -800,16 +800,35 @@ (',')%7D%5D%5D +%5B0...$%7Bids.length%7D%5D %7B_id,_ty @@ -988,16 +988,50 @@ n(',')%7D%5D +%5B0...$%7BcombinedSelections.length%7D%5D %60%0A%7D%0A%0Aexp
47d492bfffd78b4027ea3ab4f452d574053165df
Fix bug in cache clearing.
angular-osd-resource.js
angular-osd-resource.js
(function () { var osdResource = angular.module('osdResource', [ 'ngLodash' ]); /* Creates a default resource. Generally, we would decorate this with a service that handles data returned from an API (for example, we could decorate this with a cache decorator). Each resource is built using a resourceConfig constant. */ function createResource(config) { return function ($resource) { var self = this; self.config = config; var customResources = { query: {method: 'GET', isArray: false}, update: {method: 'PUT'} }; self.resource = $resource(config.route, {id: '@id'}, customResources); self.save = function (data) { return self.resource.save(data).$promise; }; self.update = function (data) { return self.resource.update(data).$promise; }; self.get = function (params) { return self.resource.get(params).$promise; }; self.query = function (params) { return self.resource.query(params).$promise; }; self.delete = function (id) { return self.resource.delete({id: id}).$promise; }; return self; }; } /* A single cache decorator is used to cache data for all resources. Each resource caches its data in self.caches[<resource name>]. @ngInject */ function cacheDecorator($delegate, lodash) { var self = this; self.caches = {}; function initResourceCache($delegate) { self.caches[$delegate.config.name] = { get: { cached: false, params: null, data: null }, query: { cached: false, params: null, data: null } }; return self.caches[$delegate.config.name]; } /* If not forced, cached is true and the query params are the same return the cached data, otherwise make the API call. */ function getCachedCall(call, params, forced) { var currentCache = self.caches[$delegate.config.name]; if (!currentCache) { currentCache = initResourceCache($delegate); } if (!forced && currentCache[call].cached && lodash.isEqual(params, currentCache[call].params)) { return currentCache[call].data; } /* Here we cache the results and set flags for the next time the resource method is called. */ currentCache[call].cached = true; currentCache[call].params = params; /* This is the decorated call. */ var promisedResponse = $delegate[call](params) .then(function (response) { return response; }); currentCache[call].data = promisedResponse; return promisedResponse; } /* On save or update, we invalidate the cache. This prevents us from returning outdated data on a later call. */ function clearCachedCall(call, data) { var currentCache = self.caches[$delegate.config.name]; if (!currentCache) { initResourceCache($delegate); } currentCache.get.cached = false; currentCache.query.cached = false; return $delegate[call](data); } return { // Call the parent save function and invalidate cache save: function (data) { return clearCachedCall('save', data); }, // Call the parent update function and invalidate cache update: function (data) { return clearCachedCall('update', data); }, // Get possibly cached data get: function (params, forced) { return getCachedCall('get', params, forced); }, // Query possibly cached data query: function (params, forced) { return getCachedCall('query', params, forced); }, // Call the parent delete function and invalidate cache delete: function (data) { return clearCachedCall('delete', data); } }; } /* This provider allows separate modules to configure the resource generator. */ osdResource.provider('ResourceConfig', function () { var config = []; return { config: function (value) { config = value; }, $get: function () { return config; } }; }); /* Bind $provide to the module so that it can be used during the angular.run phase. Resource creation needs to happen in the angular.run phase because configuration isn't available before then. @ngInject */ osdResource.config(function ($provide) { osdResource.register = { factory: $provide.factory, decorator: $provide.decorator }; }); /* Loop through each resource defined in resourceConfig, create resources and adding decorators if specified. @ngInject */ osdResource.run(function (ResourceConfig) { ResourceConfig.forEach(function (config) { osdResource.register.factory(config.name, ['$resource', createResource(config)]); config.decorators.forEach(function (decorator) { if (decorator == 'cache') { osdResource.register.decorator(config.name, cacheDecorator); } }); }); }); }) ();
JavaScript
0
@@ -3565,16 +3565,31 @@ + currentCache = initRes
607bf7de090d7cde9cededf6883f72ba2291f4c7
remove un-needed console.log
src/node/registry-builder.js
src/node/registry-builder.js
/*eslint strict:0, no-console:0*/ 'use strict'; const _ = require('lodash'); const cheerio = require('cheerio'); const npm = require('npm'); const Promise = require('bluebird'); const { all, fromNode, promisify, promisifyAll } = require('bluebird'); const fs = promisifyAll(require('fs')); const request = require('request'); const logOutput = function (...args) { console.log(...args); }; const logProgress = function (...args) { console.error(...args); }; function calculateDownloadMetrics(extensionInfo) { let downloadsArray = extensionInfo.downloads; // downloadsLastWeek let today = new Date(); today.setDate(today.getDate() - 7); let weekAgo = today.toISOString().substring(0, 10); extensionInfo.downloadsLastWeek = downloadsArray .filter(obj => obj.day >= weekAgo) .reduce((sum, obj) => sum + obj.downloads, 0); // downloadsTotal extensionInfo.downloadsTotal = downloadsArray .reduce((sum, obj) => sum + obj.downloads, 0); } function buildRegistry(targetFile) { logProgress('loading npm'); return fromNode(npm.load.bind(npm)) .then(() => { // npm is loaded, we can start the search // get all entries tagged 'brackets-extension' logProgress(`executing npm search brackets-extension`); return fromNode(npm.commands.search.bind(npm.commands, ['brackets-extension'], true)); }) .then(searchResults => { // call view for all potential extensions logProgress(`executing npm view to get detailed info about the extensions`); let npmView = promisify(npm.commands.view, npm.commands); return all(Object.keys(searchResults).map( extensionId => npmView([extensionId + '@latest'], true).then(result => result[Object.keys(result)[0]] ) )); }) .then(viewResults => { logProgress(`got all view results`); // filter out those, which doesn't have brackets engine specified return viewResults.filter(result => result.engines && result.engines.brackets); }) .then(extensionInfos => { logProgress(`getting download info counts for the extensions`); // get download counts for the extensions let extensionIds = extensionInfos.map(i => i.name); let from = '2015-01-01'; let to = new Date().toISOString().substring(0, 10); return new Promise((resolve, reject) => { request(`https://api.npmjs.org/downloads/range/${from}:${to}/${extensionIds.join(',')}`, (error, response, body) => { if (error) { return reject(error); } if (response.statusCode !== 200) { return reject(body); } if (typeof body === 'string') { try { body = JSON.parse(body); } catch (err) { return reject(err); } } if (extensionIds.length === 1) { extensionInfos[0].downloads = body.downloads; calculateDownloadMetrics(extensionInfos[0]); } else { extensionInfos.forEach(extensionInfo => { let info = body[extensionInfo.name]; if (info && info.downloads) { extensionInfo.downloads = info.downloads; calculateDownloadMetrics(extensionInfo); } }); } resolve(extensionInfos); }); }); }) .then(extensionInfos => { logProgress(`getting issue/pr counts for the extensions`); return Promise.all(extensionInfos.map(extensionInfo => { const githubRepo = /^https?:\/\/[^\/]*github.com\/([^\/]+)\/([^\/]+)$/; let githubIssueCount = -1; let githubPullCount = -1; let candidates = _.compact([ extensionInfo.repository ? extensionInfo.repository.url : null, extensionInfo.repository, extensionInfo.homepage ]).filter(x => typeof x === 'string').filter(x => x.match(githubRepo)); if (candidates.length === 0) { return Promise.resolve(); } let m = candidates[0].match(githubRepo); let username = m[1]; let repo = m[2]; extensionInfo.githubUsername = username; extensionInfo.githubRepository = repo; if (repo.match(/\.git$/)) { repo = repo.slice(0, -4); } return new Promise((resolve) => { let url = `https://github.com/${username}/${repo}/issues/counts`; console.log(url); request({ url, method: `GET`, json: true, headers: { 'User-Agent': `brackets-npm-registry` } }, (error, response, body) => { if (error || response.statusCode !== 200) { return resolve(); } githubIssueCount = parseInt(cheerio.load(body.issues_count)('.counter').text(), 10); githubPullCount = parseInt(cheerio.load(body.pulls_count)('.counter').text(), 10); resolve(); }); }).then(() => { extensionInfo.githubIssueCount = isNaN(githubIssueCount) ? -1 : githubIssueCount; extensionInfo.githubPullCount = isNaN(githubPullCount) ? -1 : githubPullCount; }); })).then(() => extensionInfos); }) .then(extensionInfos => { let strResults = JSON.stringify(extensionInfos, null, 2); logProgress(`all done`); if (targetFile) { logProgress(`writing the results to file:\n`, targetFile); return fs.writeFileAsync(targetFile, strResults) .then(() => extensionInfos); } logOutput(strResults); return extensionInfos; }); } if (process.argv[1] === __filename) { buildRegistry(...process.argv.slice(2)); } else { module.exports = buildRegistry; }
JavaScript
0.000009
@@ -4435,36 +4435,8 @@ s%60;%0A - console.log(url);%0A
e96ce04227d203ee8220e837da9729c0418c1f66
Revert "Adding delay to tests"
test/css-validator_test.js
test/css-validator_test.js
var fs = require('fs'); var expect = require('chai').expect; var nock = require('nock'); var validateCss = require('../'); function runValidateCss() { before(function (done) { var that = this; validateCss(this.css, function (err, data) { that.err = err; that.data = data; done(); }); }); } function wait(ms) { before(function (done) { setTimeout(done, ms); }); } if (process.env.FIXTURE_HTTP) { before(function () { this._invalidXml = nock('http://jigsaw.w3.org') .post('/css-validator/validator') .reply(200, fs.readFileSync(__dirname + '/test-files/invalid.xml', 'utf8')); }); after(function () { this._invalidXml.done(); }); } describe('A valid CSS file', function () { before(function () { this.css = fs.readFileSync(__dirname + '/test-files/valid.css', 'utf8'); }); describe('when validated', function () { runValidateCss(); it('has no errors', function () { expect(this.data.validity).to.equal(true); expect(this.data.errors).to.deep.equal([]); expect(this.data.warnings).to.deep.equal([]); }); }); }); describe('A invalid CSS file', function () { before(function () { this.css = fs.readFileSync(__dirname + '/test-files/invalid.css', 'utf8'); }); describe('when validated', function () { // Wait a seconds for the w3c rate limiting wait(1000); runValidateCss(); it('was not valid errors', function () { expect(this.data.validity).to.equal(false); }); it('has an expected error', function () { var errors = this.data.errors; expect(errors.length).to.equal(1); expect(errors[0].message).to.contain('background-color'); }); it('has an expected warning', function () { var warnings = this.data.warnings; expect(warnings.length).to.equal(1); expect(warnings[0].message).to.contain('-moz-box-sizing'); }); }); });
JavaScript
0
@@ -321,89 +321,8 @@ );%0A%7D -%0Afunction wait(ms) %7B%0A before(function (done) %7B%0A setTimeout(done, ms);%0A %7D);%0A%7D %0A%0Aif @@ -1276,72 +1276,8 @@ ) %7B%0A - // Wait a seconds for the w3c rate limiting%0A wait(1000);%0A
610fbf0a54e63e4117d139415aa2cf2c5667cd3b
increase the precision of the button component's test config when running vrt
packages/components/bolt-button/__tests__/button.js
packages/components/bolt-button/__tests__/button.js
import { render, renderString, stop as stopTwigRenderer, } from '@bolt/twig-renderer'; import { fixture as html } from '@open-wc/testing-helpers'; const { readYamlFileSync } = require('@bolt/build-tools/utils/yaml'); const { join } = require('path'); const schema = readYamlFileSync(join(__dirname, '../button.schema.yml')); const { tag } = schema.properties; async function renderTwig(template, data) { return await render(template, data, true); } async function renderTwigString(template, data) { return await renderString(template, data, true); } const timeout = 60000; describe('button', async () => { let page; afterAll(async () => { await stopTwigRenderer(); }, timeout); beforeEach(async () => { page = await global.__BROWSER__.newPage(); await page.goto('http://127.0.0.1:4444/', { timeout: 0, waitLoad: true, waitNetworkIdle: true, // defaults to false }); }, timeout); test('basic button', async () => { const results = await renderTwig('@bolt-components-button/button.twig', { text: 'Hello World', }); expect(results.ok).toBe(true); expect(results.html).toMatchSnapshot(); }); tag.enum.forEach(async tagChoice => { test(`button tag: ${tagChoice}`, async () => { const results = await renderTwig('@bolt-components-button/button.twig', { text: 'Hello World', tag: tagChoice, }); expect(results.ok).toBe(true); expect(results.html).toMatchSnapshot(); }); }); test('Button with outer classes via Drupal Attributes', async () => { const results = await renderTwig('@bolt-components-button/button.twig', { text: 'Button with outer classes', attributes: { class: ['u-bolt-padding-medium'], }, }); expect(results.ok).toBe(true); expect(results.html).toMatchSnapshot(); }); test('Button with inner classes via Drupal Attributes', async () => { const results = await renderTwig('@bolt-components-button/button.twig', { text: 'Button with inner classes', attributes: { class: ['is-active'], }, }); expect(results.ok).toBe(true); expect(results.html).toMatchSnapshot(); }); test('Button with outer JS-class via Drupal Attributes', async () => { const results = await renderTwig('@bolt-components-button/button.twig', { text: 'Button with outer JS-prefixed class', attributes: { class: ['js-click-me'], }, }); expect(results.ok).toBe(true); expect(results.html).toMatchSnapshot(); }); test('Button with c-bolt- class is thrown out', async () => { const results = await renderTwig('@bolt-components-button/button.twig', { text: 'Button with outer JS-prefixed class', attributes: { class: ['c-bolt-button--secondary'], }, }); expect(results.ok).toBe(true); expect(results.html).toMatchSnapshot(); }); test('Button with an onClick param renders properly', async () => { const results = await renderTwig('@bolt-components-button/button.twig', { text: 'Button with onClick via param', onClick: 'on-click-test', }); expect(results.ok).toBe(true); expect(results.html).toMatchSnapshot(); }); test('Button with an onClick attributes renders properly', async () => { const results = await renderTwig('@bolt-components-button/button.twig', { text: 'Button w/ onClick via attributes', attributes: { 'on-click': 'on-click-test', }, }); expect(results.ok).toBe(true); expect(results.html).toMatchSnapshot(); }); test('Default <bolt-button> w/o Shadow DOM renders', async function() { const renderedButtonHTML = await page.evaluate(() => { const btn = document.createElement('bolt-button'); btn.textContent = 'Hello World!'; document.body.appendChild(btn); btn.useShadow = false; btn.updated(); return btn.outerHTML; }); const renderedHTML = await html(renderedButtonHTML); expect( renderedHTML .querySelector('.c-bolt-button') .classList.contains('c-bolt-button--primary'), ).toBe(true); const image = await page.screenshot(); expect(image).toMatchImageSnapshot({ failureThreshold: '0.01', failureThresholdType: 'percent', }); expect(renderedHTML).toMatchSnapshot(); }); test('Default <bolt-button> with Shadow DOM renders', async function() { const defaultButtonShadowRoot = await page.evaluate(() => { const btn = document.createElement('bolt-button'); btn.textContent = 'Button Test -- Shadow Root HTML'; document.body.appendChild(btn); btn.updated(); return btn.renderRoot.innerHTML; }); const defaultButtonOuter = await page.evaluate(() => { const btn = document.createElement('bolt-button'); btn.textContent = 'Button Test -- Outer HTML'; document.body.appendChild(btn); btn.updated(); return btn.outerHTML; }); const renderedShadowDomHTML = await html(defaultButtonShadowRoot); const renderedHTML = await html(defaultButtonOuter); expect(renderedHTML.textContent).toEqual('Button Test -- Outer HTML'); // expect( // renderedShadowDomHTML // .querySelector('.c-bolt-button') // .classList.contains('c-bolt-button--primary'), // ).toBe(true); // expect(renderedShadowDomHTML.querySelector('style')).toBe(true); // expect(renderedShadowDomHTML.querySelector('button')).toBe(true); const image = await page.screenshot(); expect(image).toMatchImageSnapshot({ failureThreshold: '0.01', failureThresholdType: 'percent', }); expect(renderedShadowDomHTML).toMatchSnapshot(); expect(renderedHTML).toMatchSnapshot(); }); });
JavaScript
0.000001
@@ -4261,35 +4261,32 @@ ureThreshold: '0 -.01 ',%0A failure @@ -5633,11 +5633,8 @@ : '0 -.01 ',%0A
844a99bfeab6709ef8f83b4201391c489aa60e82
Introduce delays in directed requester tests to increase test stability
test/directed-requester.js
test/directed-requester.js
import test from 'ava'; import r from 'randomstring'; import LogSuppress from '../lib/log-suppress'; LogSuppress.init(console); const environment = r.generate(); const { Requester, Responder } = require('../')({ environment }); test.cb('Supports directed requests targeted at single responder using callbacks', (t) => { const key = r.generate(); const namespace = r.generate(); const subset = r.generate(); const targetResponder = new Responder({ name: `PBR ${t.title}: directed responder`, key, namespace, subset }, { log: false }); const wrongResponder = new Responder({ name: `PBR ${t.title}: directed responder`, key, namespace }, { log: false }); const requester = new Requester( { name: `PBR ${t.title}: directed requester`, key, namespace }, { log: false }); const args = [1, 2, 6]; // Send the request twice. It should end up in the same Responder both times // Also make sure the wrongResponder is connected wrongResponder.sock.on('bind', () => { requester.send({ __subset: subset, type: 'test', args }, (res) => { t.deepEqual(res, args); requester.send({ __subset: subset, type: 'test', args }, (res) => { t.deepEqual(res, args); t.end(); }); }); }); targetResponder.on('test', (req, cb) => { t.deepEqual(req.args, args); cb(req.args); }); wrongResponder.on('test', (req, cb) => { t.fail('Not targeted responder should have never gotten a message'); t.end(); }); }); test('Supports directed requests targeted at multiple targeted requesters using promises', async (t) => { // Times to send requests, times/nrOfRequesters has to result in a just number const times = 10; const nrOfRequesters = 2; const key = r.generate(); const namespace = r.generate(); const subset = r.generate(); const subset2 = r.generate(); const responders = []; Array.from({ length: nrOfRequesters }).forEach(() => { const responder = new Responder({ name: `PBR ${t.title}: directed responder`, key, namespace, subset }, { log: false }); responder.count = 0; responder.on('test', async (req) => { responder.count++; return req.args; }); responders.push(responder); }); // Normal responder without subset const wrongResponder = new Responder({ name: `PBR ${t.title}: directed responder`, key, namespace }, { log: false }); wrongResponder.on('test', () => { t.fail('Not targeted responder should have never gotten a message'); }); // Responder in different subset const wrongResponder2 = new Responder({ name: `PBR ${t.title}: directed responder`, key, namespace, subset: subset2, }, { log: false }); wrongResponder2.on('test', () => { t.fail('Not targeted responder should have never gotten a message'); }); const requester = new Requester( { name: `PBR ${t.title}: directed requester`, key, namespace }, { log: false }); const args = [1, 2, 6]; // Send the request multiple times // It should end up in the both requesters somewhat // evenly distributed, but never in the wrong one for (let index = 0; index < times; index++) { await requester.send({ __subset: subset, type: 'test', args }); } const totalRecieved = responders.reduce((accumulator, responder) => { // Both should have at least gotten one request t.true(responder.count > 0); return accumulator += responder.count; }, 0); t.is(totalRecieved, times); }); test('Timeout works with directed requester', async (t) => { const key = r.generate(); const namespace = r.generate(); const subset = r.generate(); const requester = new Requester({ name: `PBR ${t.title}: directed requester`, key, namespace, subset }, { log: false }); try { await requester.send({ __subset: subset, __timeout: 1000, type: 'test', args: [1, 2, 6] }); t.fail(); } catch (error) { if (error.message.includes('Request timed out')) return t.pass(); t.fail(error); } }); test('Queuing works with directed requester', async (t) => { const key = r.generate(); const namespace = r.generate(); const subset = r.generate(); const subset2 = r.generate(); const args = [1, 2, 6]; const requester = new Requester({ name: `PBR ${t.title}: directed requester`, key, namespace, subset }, { log: false, checkInterval: 500 }); const responder = new Responder({ name: `PBR ${t.title}: directed responder`, key, namespace, subset }, { log: false, checkInterval: 500 }); responder.on('test', async (req) => { return req.args; }); // Make sure it does not sent to the wrong responder in a different subset // when there are no other responders available const responder2 = new Responder({ name: `PBR ${t.title}: directed responder`, key, namespace, subset: subset2 }, { log: false, checkInterval: 500 }); responder2.on('test', async (req) => { t.fail(); }); try { // Send an receive const res = await requester.send({ __subset: subset, type: 'test', args }); t.deepEqual(res, args); // Destroy responder and wait for heartbeat responder.close(); await wait(501); // Next request let pending = true; const promise = requester.send({ __subset: subset, type: 'test', args }) .then((res) => { pending = false; return res; }); await wait(500); t.true(pending); // Recreate responder const responder2 = new Responder({ name: `PBR ${t.title}: directed responder`, key, namespace, subset }, { log: false }); responder2.on('test', async (req) => { return req.args; }); // make sure it received the message const res2 = await promise; t.false(pending); t.deepEqual(res2, args); } catch (error) { t.fail(error); } }); function wait(ms) { return new Promise((res) => { setTimeout(() => { res(); }, ms); }); }
JavaScript
0
@@ -3382,24 +3382,89 @@ index++) %7B%0A + await new Promise((resolve) =%3E setTimeout(resolve, 50));%0A awai
c2fadb0945434710d0117bac793c95a81aa16636
fix seconds lost in datetime
src/js/datetime-picker.js
src/js/datetime-picker.js
/* global $:true */ /* jshint unused:false*/ + function($) { "use strict"; var defaults; var formatNumber = function (n) { return n < 10 ? "0" + n : n; } var Datetime = function(input, params) { this.input = $(input); this.params = params; this.initMonthes = ('01 02 03 04 05 06 07 08 09 10 11 12').split(' '); this.initYears = (function () { var arr = []; for (var i = 1950; i <= 2030; i++) { arr.push(i); } return arr; })(); var p = $.extend({}, params, this.getConfig()); $(this.input).picker(p); } Datetime.prototype = { getDays : function(max) { var days = []; for(var i=1; i<= (max||31);i++) { days.push(i < 10 ? "0"+i : i); } return days; }, getDaysByMonthAndYear : function(month, year) { var int_d = new Date(year, parseInt(month)+1-1, 1); var d = new Date(int_d - 1); return this.getDays(d.getDate()); }, getConfig: function() { var today = new Date(), params = this.params, self = this, lastValidValues; var config = { rotateEffect: false, //为了性能 cssClass: 'datetime-picker', value: [today.getFullYear(), formatNumber(today.getMonth()+1), formatNumber(today.getDate()), formatNumber(today.getHours()), (formatNumber(today.getMinutes()))], onChange: function (picker, values, displayValues) { var cols = picker.cols; var days = self.getDaysByMonthAndYear(values[1], values[0]); var currentValue = values[2]; if(currentValue > days.length) currentValue = days.length; picker.cols[4].setValue(currentValue); //check min and max var current = new Date(values[0]+'-'+values[1]+'-'+values[2]); var valid = true; if(params.min) { var min = new Date(typeof params.min === "function" ? params.min() : params.min); if(current < +min) { picker.setValue(lastValidValues); valid = false; } } if(params.max) { var max = new Date(typeof params.max === "function" ? params.max() : params.max); if(current > +max) { picker.setValue(lastValidValues); valid = false; } } valid && (lastValidValues = values); if (self.params.onChange) { self.params.onChange.apply(this, arguments); } }, formatValue: function (p, values, displayValues) { return self.params.format(p, values, displayValues); }, cols: [ { values: (function () { var years = []; for (var i=1950; i<=2050; i++) years.push(i); return years; })() }, { divider: true, // 这是一个分隔符 content: params.yearSplit }, { values: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'] }, { divider: true, // 这是一个分隔符 content: params.monthSplit }, { values: (function () { var dates = []; for (var i=1; i<=31; i++) dates.push(formatNumber(i)); return dates; })() }, ] } if (params.dateSplit) { config.cols.push({ divider: true, content: params.dateSplit }) } config.cols.push({ divider: true, content: params.datetimeSplit }) var times = self.params.times(); if (times && times.length) { config.cols = config.cols.concat(times); } var inputValue = this.input.val(); if(inputValue) config.value = params.parse(inputValue); if(this.params.value) { this.input.val(this.params.value); config.value = params.parse(this.params.value); } return config; } } $.fn.datetimePicker = function(params) { params = $.extend({}, defaults, params); return this.each(function() { if(!this) return; var $this = $(this); var datetime = $this.data("datetime"); if(!datetime) $this.data("datetime", new Datetime(this, params)); return datetime; }); }; defaults = $.fn.datetimePicker.prototype.defaults = { input: undefined, // 默认值 min: undefined, // YYYY-MM-DD 最大最小值只比较年月日,不比较时分秒 max: undefined, // YYYY-MM-DD yearSplit: '-', monthSplit: '-', dateSplit: '', // 默认为空 datetimeSplit: ' ', // 日期和时间之间的分隔符,不可为空 times: function () { return [ // 自定义的时间 { values: (function () { var hours = []; for (var i=0; i<24; i++) hours.push(formatNumber(i)); return hours; })() }, { divider: true, // 这是一个分隔符 content: ':' }, { values: (function () { var minutes = []; for (var i=0; i<59; i++) minutes.push(formatNumber(i)); return minutes; })() } ]; }, format: function (p, values) { // 数组转换成字符串 return p.cols.map(function (col) { return col.value || col.content; }).join(''); }, parse: function (str) { // 把字符串转换成数组,用来解析初始值 // 如果你的定制的初始值格式无法被这个默认函数解析,请自定义这个函数。比如你的时间是 '子时' 那么默认情况这个'时'会被当做分隔符而导致错误,所以你需要自己定义parse函数 // 默认兼容的分隔符 var t = str.split(this.datetimeSplit); return t[0].split(/\D/).concat(t[1].split(/:|时|分|秒/)).filter(function (d) { return !!d; }) } } }($);
JavaScript
0.00008
@@ -5078,10 +5078,10 @@ ; i%3C -59 +60 ; i+
10a955148e1193729883acf225ca93e9e04ebff0
Change `_gc` method name
packages/relay-runtime/store/RelayMarkSweepStore.js
packages/relay-runtime/store/RelayMarkSweepStore.js
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @format */ 'use strict'; const RelayDataLoader = require('./RelayDataLoader'); const RelayModernRecord = require('./RelayModernRecord'); const RelayProfiler = require('../util/RelayProfiler'); const RelayReader = require('./RelayReader'); const RelayReferenceMarker = require('./RelayReferenceMarker'); const deepFreeze = require('../util/deepFreeze'); const hasOverlappingIDs = require('./hasOverlappingIDs'); const recycleNodesInto = require('../util/recycleNodesInto'); const resolveImmediate = require('resolveImmediate'); const {UNPUBLISH_RECORD_SENTINEL} = require('./RelayStoreUtils'); import type {Disposable} from '../util/RelayRuntimeTypes'; import type { MutableRecordSource, RecordSource, Selector, Snapshot, Store, UpdatedRecords, } from './RelayStoreTypes'; type Subscription = { callback: (snapshot: Snapshot) => void, snapshot: Snapshot, }; /** * @public * * An implementation of the `Store` interface defined in `RelayStoreTypes`. * * Note that a Store takes ownership of all records provided to it: other * objects may continue to hold a reference to such records but may not mutate * them. The static Relay core is architected to avoid mutating records that may have been * passed to a store: operations that mutate records will either create fresh * records or clone existing records and modify the clones. Record immutability * is also enforced in development mode by freezing all records passed to a store. */ class RelayMarkSweepStore implements Store { _gcEnabled: boolean; _hasScheduledGC: boolean; _index: number; _recordSource: MutableRecordSource; _roots: Map<number, Selector>; _subscriptions: Set<Subscription>; _updatedRecordIDs: UpdatedRecords; constructor(source: MutableRecordSource) { // Prevent mutation of a record from outside the store. if (__DEV__) { const storeIDs = source.getRecordIDs(); for (let ii = 0; ii < storeIDs.length; ii++) { const record = source.get(storeIDs[ii]); if (record) { RelayModernRecord.freeze(record); } } } this._gcEnabled = true; this._hasScheduledGC = false; this._index = 0; this._recordSource = source; this._roots = new Map(); this._subscriptions = new Set(); this._updatedRecordIDs = {}; } getSource(): RecordSource { return this._recordSource; } check(selector: Selector): boolean { return RelayDataLoader.check( this._recordSource, this._recordSource, selector, [], ); } retain(selector: Selector): Disposable { const index = this._index++; const dispose = () => { this._roots.delete(index); this._scheduleGC(); }; this._roots.set(index, selector); return {dispose}; } lookup(selector: Selector): Snapshot { const snapshot = RelayReader.read(this._recordSource, selector); if (__DEV__) { deepFreeze(snapshot); } return snapshot; } notify(): void { this._subscriptions.forEach(subscription => { this._updateSubscription(subscription); }); this._updatedRecordIDs = {}; } publish(source: RecordSource): void { updateTargetFromSource(this._recordSource, source, this._updatedRecordIDs); } subscribe( snapshot: Snapshot, callback: (snapshot: Snapshot) => void, ): Disposable { const subscription = {callback, snapshot}; const dispose = () => { this._subscriptions.delete(subscription); }; this._subscriptions.add(subscription); return {dispose}; } // Internal API __getUpdatedRecordIDs(): UpdatedRecords { return this._updatedRecordIDs; } _updateSubscription(subscription: Subscription): void { const {callback, snapshot} = subscription; if (!hasOverlappingIDs(snapshot, this._updatedRecordIDs)) { return; } const {data, seenRecords} = RelayReader.read(this._recordSource, snapshot); const nextData = recycleNodesInto(snapshot.data, data); const nextSnapshot = { ...snapshot, data: nextData, seenRecords, }; if (__DEV__) { deepFreeze(nextSnapshot); } subscription.snapshot = nextSnapshot; if (nextSnapshot.data !== snapshot.data) { callback(nextSnapshot); } } _scheduleGC() { if (!this._gcEnabled || this._hasScheduledGC) { return; } this._hasScheduledGC = true; resolveImmediate(() => { this._gc(); this._hasScheduledGC = false; }); } _gc(): void { const references = new Set(); // Mark all records that are traversable from a root this._roots.forEach(selector => { RelayReferenceMarker.mark(this._recordSource, selector, references); }); // Short-circuit if *nothing* is referenced if (!references.size) { this._recordSource.clear(); return; } // Evict any unreferenced nodes const storeIDs = this._recordSource.getRecordIDs(); for (let ii = 0; ii < storeIDs.length; ii++) { const dataID = storeIDs[ii]; if (!references.has(dataID)) { this._recordSource.remove(dataID); } } } // Internal hooks to enable/disable garbage collection for experimentation __enableGC(): void { this._gcEnabled = true; } __disableGC(): void { this._gcEnabled = false; } } /** * Updates the target with information from source, also updating a mapping of * which records in the target were changed as a result. */ function updateTargetFromSource( target: MutableRecordSource, source: RecordSource, updatedRecordIDs: UpdatedRecords, ): void { const dataIDs = source.getRecordIDs(); for (let ii = 0; ii < dataIDs.length; ii++) { const dataID = dataIDs[ii]; const sourceRecord = source.get(dataID); const targetRecord = target.get(dataID); // Prevent mutation of a record from outside the store. if (__DEV__) { if (sourceRecord) { RelayModernRecord.freeze(sourceRecord); } } if (sourceRecord === UNPUBLISH_RECORD_SENTINEL) { // Unpublish a record target.remove(dataID); updatedRecordIDs[dataID] = true; } else if (sourceRecord && targetRecord) { const nextRecord = RelayModernRecord.update(targetRecord, sourceRecord); if (nextRecord !== targetRecord) { // Prevent mutation of a record from outside the store. if (__DEV__) { RelayModernRecord.freeze(nextRecord); } updatedRecordIDs[dataID] = true; target.set(dataID, nextRecord); } } else if (sourceRecord === null) { target.delete(dataID); if (targetRecord !== null) { updatedRecordIDs[dataID] = true; } } else if (sourceRecord) { target.set(dataID, sourceRecord); updatedRecordIDs[dataID] = true; } // don't add explicit undefined } } RelayProfiler.instrumentMethods(RelayMarkSweepStore.prototype, { lookup: 'RelayMarkSweepStore.prototype.lookup', notify: 'RelayMarkSweepStore.prototype.notify', publish: 'RelayMarkSweepStore.prototype.publish', retain: 'RelayMarkSweepStore.prototype.retain', subscribe: 'RelayMarkSweepStore.prototype.subscribe', }); module.exports = RelayMarkSweepStore;
JavaScript
0.000001
@@ -4610,16 +4610,17 @@ this._ +_ gc();%0A @@ -4668,16 +4668,17 @@ %0A %7D%0A%0A +_ _gc(): v
2d424eb1f55c54242b9907d9193880638e4a5834
check if government is defined
app/views/directives/party-status.js
app/views/directives/party-status.js
define(['app', '/app/js/common.js'], function(app) { app.directive('ngPartyStatus', [ '$rootScope', '$filter', '$timeout', 'commonjs', '$q', function($rootScope, $filter, $timeout, commonjs, $q) { return { restrict: 'EAC', templateUrl : '/app/views/directives/party-status.html', scope : { government : '=' }, link: function($scope, elem, attrs) { console.log($scope.government); $q.when(commonjs.getCountry($scope.government.identifier.toUpperCase())) .then(function(country){ console.log(country); $scope.partyStatus = country; }); } }; } ]); });
JavaScript
0
@@ -493,27 +493,18 @@ -console.log +if ($scope. @@ -514,18 +514,22 @@ ernment) -;%0A +%7B%0A @@ -633,16 +633,20 @@ + .then(fu @@ -686,16 +686,20 @@ + console. @@ -736,16 +736,20 @@ + + $scope.p @@ -790,19 +790,45 @@ -%7D); + %7D);%0A %7D %0A
8ceae775b4f509a303632e5efb42962dff937c32
Update off-canvas-menu.js
src/js/off-canvas-menu.js
src/js/off-canvas-menu.js
(function($) { $.fn.offCanvasMenu = function(options) { var settings = $.extend({ // These are the defaults. container : $(this), containerActiveAffix: "active", globalName: "js-offCanvasMenu", activeState: "is-active", effect: "push", buttonName: "button", overlayName: "overlay", iconOpen : "fa-navicon", textOpen : "Menu", iconClose : "fa-times", textClose : "Sluit" }, options), htmlClasses = { containerActive: settings.globalName + "--" + settings.containerActiveAffix, button: settings.globalName + "-" + settings.buttonName, buttonActive: settings.activeState, overlay: settings.globalName + "-" + settings.overlayName, effect: settings.globalName + "--effect--" + settings.effect }, cssClasses = { containerActive: "." + htmlClasses.containerActiveAffix, button: "." + htmlClasses.button, buttonText: "." + htmlClasses.button + "-text", buttonIcon: "." + htmlClasses.button + "-icon", overlay: "." + htmlClasses.overlay, effect: "." + htmlClasses.effect }, elements = { button: $(cssClasses.button), buttonText: $(cssClasses.buttonText), buttonIcon: $(cssClasses.buttonIcon), container: settings.container, overlay: $(cssClasses.overlay) }, toggle = function(elem, effect) { var time, checkIdenticalEffects = function(){ var elementEffect = elem.data("effect"), containerEffect = elements.container.data("effect"); if (containerEffect === elementEffect) { return true; } else { return false; } }, toggleClasses = function(){ if (settings.container.hasClass(htmlClasses.containerActive)) { //elem.removeClass(htmlClasses.activeCssClass); elements.container.removeClass(htmlClasses.containerActive); buttonSettings.icon.removeClass(settings.iconClose).addClass(settings.iconOpen); elements.buttonText.textfi(settings.textOpen); } else { //elem.addClass(htmlClasses.activeCssClass); elements.container.addClass(htmlClasses.containerActive); buttonSettings.icon.removeClass(settings.iconOpen).addClass(settings.iconClose); elements.buttonText.text(settings.textClose); } }; if (checkIdenticalEffects()) { time = 0; } else { time = 400; } setTimeout( function(time){ toggleClasses(); }, time); //Update effect data and class elements.container.removeClass(function () { return (settings.globalName + "--effect--" + $(this).data("effect")); }); elements.container.addClass(settings.globalName + "--effect--" + checkEffect(elem)); elements.container.data("effect", checkEffect(elem)); }, checkEffect = function(elem) { if (elem.data("effect").length > 0){ return elem.data("effect"); } else { return settings.effect; } }; // Click event // ======================================================= elements.button.click(function(e) { e.preventDefault(); toggle( $(this) , checkEffect($(this)) ); }); //Refactor for use of overlay elements.overlay.click(function(e) { e.preventDefault(); $(this).data("effect", checkEffect(settings.container)); toggle( $(this), checkEffect(settings.container) ); }); // On load // Provide the correct effect class to the container. // ======================================================= elements.container.addClass(htmlClasses.effect); elements.container.data("effect", settings.effect); }; }(jQuery));
JavaScript
0.000003
@@ -2359,32 +2359,32 @@ -buttonSettings.i +elements.buttonI con.remo @@ -2488,18 +2488,16 @@ ext.text -fi (setting @@ -2717,24 +2717,24 @@ -buttonSettings.i +elements.buttonI con.
cf55408d6e2d2c3bc0f2c29121be519d95272ad0
Add documentation in delete-trip-button.
frontend/src/components/ViewTrips/delete-trip-button.js
frontend/src/components/ViewTrips/delete-trip-button.js
import React from 'react'; import app from '../Firebase/'; import Button from 'react-bootstrap/Button'; import * as DB from '../../constants/database.js'; const db = app.firestore(); /** * Component used to delete a Trip. * * * @param {Object} props These are the props for this component: * - tripId: Document ID for the current Trip document. * - refreshTripsContainer: Handler that refreshes the TripsContainer * component upon trip creation (Remove when fix Issue #62). */ const DeleteTripsButton = (props) => { /** * Deletes documents in query with a batch delete. */ async function deleteQueryBatch(db, query, resolve) { const snapshot = await query.get(); const batchSize = snapshot.size; if (batchSize === 0) { // When there are no documents left, we are done resolve(); return; } // Delete documents in a batch const batch = db.batch(); snapshot.docs.forEach((doc) => { batch.delete(doc.ref); }); await batch.commit(); // Recurse on the next process tick, to avoid // exploding the stack. process.nextTick(() => { deleteQueryBatch(db, query, resolve); }); } /** * Deletes a trips subcollection of activities corrsponding to the * `tripId` prop. * * TODO(Issue #81): Consider deleting data with callabable cloud function * https://firebase.google.com/docs/firestore/solutions/delete-collections */ async function deleteTripActivities() { const query = db.collection(DB.COLLECTION_TRIPS) .doc(props.tripId) .collection(DB.COLLECTION_ACTIVITIES) .orderBy(DB.ACTIVITIES_TITLE) .limit(3); return new Promise((resolve, reject) => { deleteQueryBatch(db, query, resolve).catch(reject); }); } /** * Deletes a trip and its subcollection of activities corrsponding to the * `tripId` prop and then refreshes the TripsContainer component. * TODO(Issue #62): Remove refreshTripsContainer. */ async function deleteTrip() { await deleteTripActivities(); db.collection(DB.COLLECTION_TRIPS) .doc(props.tripId) .delete() .then(() => { console.log("Document successfully deleted with id: ", props.tripId); }).catch(error => { console.error("Error removing document: ", error); }); props.refreshTripsContainer(); } return ( <Button type='button' variant='primary' onClick={deleteTrip} > Delete Trip </Button> ); } export default DeleteTripsButton;
JavaScript
0
@@ -530,16 +530,17 @@ =%3E %7B%0A + /**%0A * @@ -588,16 +588,475 @@ delete.%0A + *%0A * This was derived from the delete collection snippets in the documentation%0A * at https://firebase.google.com/docs/firestore/manage-data/delete-data.%0A *%0A * @param %7Bfirebase.firestore.Firestore%7D db Firestore database instance.%0A * @param %7Bfirebase.firestore.Query%7D query Query containing documents from%0A * the activities subcollection of a trip documents.%0A * @param %7BFunction%7D resolve Resolve function that returns a void Promise.%0A */%0A @@ -1733,24 +1733,184 @@ prop.%0A *%0A + * This was derived from the delete collection snippets in the documentation%0A * at https://firebase.google.com/docs/firestore/manage-data/delete-data.%0A *%0A * TODO(Is
41c3bf899ac0889037bae316c1d5359294024742
Update iconFont sass generator for use with nunjucks-render 2.0.0
gulpfile.js/tasks/iconFont/generateIconSass.js
gulpfile.js/tasks/iconFont/generateIconSass.js
var gulp = require('gulp') var render = require('gulp-nunjucks-render') var rename = require('gulp-rename') var handleErrors = require('../../lib/handleErrors') var gutil = require('gulp-util') module.exports = function(config) { return function(glyphs, options) { gutil.log(gutil.colors.blue('Generating ' + config.sassDest + '/' + config.sassOutputName)) render.nunjucks.configure(config.nunjucks, {watch: false }) return gulp.src(config.template) .pipe(render({ icons: glyphs.map(function(glyph) { gutil.log(gutil.colors.green('+ adding ' + glyph.name + ' glyph')) return { name: glyph.name, code: glyph.unicode[0].charCodeAt(0).toString(16).toUpperCase() } }), fontName: config.options.fontName, fontPath: config.fontPath, className: config.className, comment: '// DO NOT EDIT DIRECTLY!\n //Generated by gulpfile.js/tasks/iconFont.js\n //from ' + config.template })) .on('error', handleErrors) .pipe(rename(config.sassOutputName)) .pipe(gulp.dest(config.sassDest)) } }
JavaScript
0
@@ -213,16 +213,56 @@ p-util') +%0Avar data = require('gulp-data') %0A%0Amodule @@ -537,22 +537,20 @@ .pipe( -render +data (%7B%0A @@ -1061,16 +1061,77 @@ %7D))%0A + .pipe(render(%7B%0A path: config.template%0A %7D))%0A .on(
9a97ae0b12d5aa002a63b0218c2110c4a5cc84d8
converts "event" to string in headlights
src/js/util/headlights.js
src/js/util/headlights.js
/* * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ define(function (require, exports) { "use strict"; var Promise = require("bluebird"), adapterPS = require("adapter/ps"), global = require("./global"); /** * Logs an event entry in Headlights for Photoshop * Will not log anything in debug builds * * NOTE: This is an Adobe-private API that must not be used by third-party * developers! * * @private * @param {string} category * @param {string} subcategory * @param {string} event * * @return {Promise} */ var logEvent = function (category, subcategory, event) { if (global.debug) { return Promise.resolve(); } else { return adapterPS.logHeadlightsEvent(category, subcategory, event); } }; exports.logEvent = logEvent; });
JavaScript
1
@@ -1929,22 +1929,30 @@ tegory, +String( event) +) ;%0A
09febf15696b315cb779103b37886c5656f272c4
Support any storage resolution
server/data-fragments/get-direct-object-fragments.js
server/data-fragments/get-direct-object-fragments.js
// Returns fragment that emits direct data for specified object // Optional filtering of some records is possible via `options.filter` 'use strict'; var ensureCallable = require('es5-ext/object/valid-callable') , ensureString = require('es5-ext/object/validate-stringifiable-value') , escape = require('es5-ext/reg-exp/escape') , memoize = require('memoizee') , Fragment = require('data-fragment') , driver = require('mano').dbDriver; var getKeyPathFilter = function (keyPath) { var matches = RegExp.prototype.test.bind(new RegExp('^[a-z0-9][a-z0-9A-Z]*/' + escape(keyPath) + '(?:/.+|$)')); return function (data) { return matches(data.id); }; }; module.exports = memoize(function (storageName) { var storage = driver.getStorage(ensureString(storageName)); return memoize(function (ownerId/*, options*/) { var fragment, options = Object(arguments[1]), filter, index, customFilter, keyPathFilter; ownerId = ensureString(ownerId); if (options.filter != null) customFilter = ensureCallable(options.filter); index = ownerId.indexOf('/'); if (index !== -1) { keyPathFilter = getKeyPathFilter(ownerId.slice(index + 1)); ownerId = ownerId.slice(0, index); } if (keyPathFilter) { if (customFilter) { filter = function (data) { return keyPathFilter(data) && customFilter(data); }; } else { filter = keyPathFilter; } } else if (customFilter) { filter = customFilter; } fragment = new Fragment(); fragment.promise = storage.getObject(ownerId)(function (data) { data.forEach(function (data) { if (!filter || filter(data)) fragment.update(data.id, data.data); }); }); storage.on('owner:' + ownerId, function (event) { if (event.type !== 'direct') return; if (!filter || filter(event)) fragment.update(event.id, event.data); }); return fragment; }, { primitive: true }); }, { primitive: true });
JavaScript
0
@@ -423,16 +423,75 @@ agment') +%0A , anyIdToStorage = require('../utils/any-id-to-storage') %0A%0A , dr @@ -795,16 +795,51 @@ ) %7B%0A%09var + storage;%0A%09if (storageName != null) storage @@ -859,29 +859,16 @@ Storage( -ensureString( storageN @@ -871,17 +871,16 @@ ageName) -) ;%0A%09retur @@ -1013,16 +1013,45 @@ thFilter +%0A%09%09 , promise, setupListener ;%0A%0A%09%09own @@ -1585,54 +1585,79 @@ ;%0A%09%09 -fragment.promise = storage.getObject( +setupListener = function (storage) %7B%0A%09%09%09storage.on('owner:' + ownerId -)( +, func @@ -1666,49 +1666,57 @@ on ( -data +event ) %7B%0A%09%09%09 -data.forEach(function (data) %7B +%09if (event.type !== 'direct') return; %0A%09%09%09 @@ -1738,20 +1738,21 @@ filter( -data +event )) fragm @@ -1766,21 +1766,23 @@ ate( -data.id, data +event.id, event .dat @@ -1799,44 +1799,143 @@ %0A%09%09%7D -);%0A%09%09storage.on('owner:' + +;%0A%09%09if (storage) %7B%0A%09%09%09promise = storage.getObject(ownerId);%0A%09%09%09setupListener(storage);%0A%09%09%7D else %7B%0A%09%09%09promise = anyIdToStorage( ownerId -, +)( func @@ -1944,57 +1944,179 @@ on ( -event) %7B%0A%09%09%09if (event.type !== 'direct') return;%0A +storage) %7B%0A%09%09%09%09setupListener(storage);%0A%09%09%09%09return storage.getObject(ownerId);%0A%09%09%09%7D);%0A%09%09%7D%0A%09%09fragment.promise = promise(function (data) %7B%0A%09%09%09data.forEach(function (data) %7B%0A%09 %09%09%09i @@ -2128,37 +2128,36 @@ ilter %7C%7C filter( -event +data )) fragment.upda @@ -2159,36 +2159,41 @@ .update( -event.id, event.data +data.id, data.data);%0A%09%09%09%7D );%0A%09%09%7D); @@ -2242,29 +2242,142 @@ %7D);%0A%7D, %7B primitive: true +, resolvers: %5Bfunction (storageName) %7B%0A%09if (storageName == null) return '';%0A%09return ensureString(storageName);%0A%7D%5D %7D);%0A
52461ae83ede02b3c111a75797b253a60d3beaa9
Update combine.js
devtools-plugin/combine.js
devtools-plugin/combine.js
var fs = require('fs'); module.exports = function(gameServer,split) { var fileone = fs.readFileSync('./console.txt',"utf8"); var filetwo = fs.readFileSync('./translate.txt',"utf8"); var one = fileone.split("\n"); var two = filetwo.split("\n"); var result = ""; for (var i in one) { var on = one[i]; var tw = two[i]; var s = "this.lang[" + i + "] = { original:" + on + ",replace:" + tw + "};\n" result = result + s; } fs.writeFileSync("result.js",result); };
JavaScript
0.000001
@@ -251,16 +251,33 @@ sult = %22 +this.lang = %5B%5D;%5Cn %22;%0Afor ( @@ -435,16 +435,60 @@ + s;%0A%7D%0A +result = result + %22module.exports = this;%22;%0A fs.write
f97eb4345aa08b876beecda2d9e46aeebfac5a3f
Update firefox-user.js
apps/firefox-user.js
apps/firefox-user.js
// Mozilla User Preferences //dennyhalim.com //http://kb.mozillazine.org/User.js_file //http://kb.mozillazine.org/Locking_preferences //https://developer.mozilla.org/en-US/docs/Mozilla/Preferences/A_brief_guide_to_Mozilla_preferences pref("app.update.channel", "esr"); user_pref("browser.cache.compression_level", 1); user_pref("browser.sessionhistory.max_entries", 10); //user_pref("devtools.memory.enabled", false); user_pref("browser.cache.memory.enable", false); //very usefull if you have < 4GB RAM user_pref("network.cookie.cookieBehavior", 3); user_pref("network.cookie.lifetimePolicy", 2); user_pref("privacy.clearOnShutdown.cache", true); user_pref("privacy.clearOnShutdown.offlineApps", true); user_pref("privacy.sanitize.pending", "[{\"id\":\"shutdown\",\"itemsToClear\":[\"cache\",\"offlineApps\"],\"options\":{}}]"); //user_pref("privacy.sanitize.pending", "[{\"id\":\"shutdown\",\"itemsToClear\":[\"cache\",\"cookies\",\"offlineApps\",\"formdata\",\"sessions\",\"siteSettings\"],\"options\":{}}]"); user_pref("privacy.sanitize.sanitizeOnShutdown", true); user_pref("privacy.donottrackheader.enabled", true); user_pref("privacy.trackingprotection.enabled", true); user_pref("privacy.trackingprotection.pbmode.enabled", true); user_pref("dom.webnotifications.enabled", false); user_pref("dom.webnotifications.serviceworker.enabled", false); user_pref("dom.serviceWorkers.enabled", false); user_pref("browser.urlbar.placeholderName", "DuckDuckGo"); user_pref("geo.enabled", false); user_pref("geo.provider.ms-windows-location", false); user_pref("geo.provider.use_corelocation", false); user_pref("geo.provider.use_gpsd", false); user_pref("toolkit.telemetry.unified", false); user_pref("toolkit.telemetry.enabled", false); user_pref("toolkit.telemetry.archive.enabled", false); user_pref("network.trr.mode", 2); user_pref("network.trr.uri", "https://doh.cleanbrowsing.org/doh/adult-filter/"); //https://cleanbrowsing.org/dnsoverhttps user_pref("dom.netinfo.enabled", false); user_pref("media.video_stats.enabled", false); //user_pref("dom.maxHardwareConcurrency", 1); //faster on slow devices user_pref("dom.battery.enabled", false); user_pref("dom.telephony.enabled", false); user_pref("beacon.enabled", false); user_pref("device.sensors.enabled", false); user_pref("dom.vibrator.enabled", false); user_pref("dom.enable_resource_timing", false);
JavaScript
0.000003
@@ -334,268 +334,437 @@ ser. -sessionhistory.max_entries%22, 10);%0A//user_pref(%22devtools.memory.enabled%22, false);%0Auser_pref(%22browser.cache.memory.enable%22, false); //very usefull if you have %3C 4GB RAM%0Auser_pref(%22network.cookie.cookieBehavior%22, 3);%0Auser_pref(%22network.cookie.lifetimePolicy%22, 2); +cache.memory.enable%22, false); //very usefull if you have %3C 4GB RAM%0Auser_pref(%22browser.sessionhistory.max_entries%22, 10);%0Auser_pref(%22browser.urlbar.placeholderName%22, %22DuckDuckGo%22);%0Auser_pref(%22network.cookie.cookieBehavior%22, 3);%0Auser_pref(%22network.cookie.lifetimePolicy%22, 2);%0Auser_pref(%22network.trr.mode%22, 2);%0Auser_pref(%22network.trr.uri%22, %22https://doh.cleanbrowsing.org/doh/adult-filter/%22); //https://cleanbrowsing.org/dnsoverhttps %0Ause @@ -1393,32 +1393,204 @@ nabled%22, true);%0A +//user_pref(%22devtools.memory.enabled%22, false);%0Auser_pref(%22dom.battery.enabled%22, false);%0Auser_pref(%22dom.telephony.enabled%22, false);%0Auser_pref(%22dom.netinfo.enabled%22, false);%0A user_pref(%22dom.w @@ -1750,53 +1750,84 @@ ef(%22 -browser.urlbar.placeholderName%22, %22DuckDuckGo%22 +dom.vibrator.enabled%22, false);%0Auser_pref(%22dom.enable_resource_timing%22, false );%0Au @@ -2170,556 +2170,184 @@ ef(%22 -network.trr.mode%22, 2);%0Auser_pref(%22network.trr.uri%22, %22https://doh.cleanbrowsing.org/doh/adult-filter/%22); //https://cleanbrowsing.org/dnsoverhttps%0Auser_pref(%22dom.netinfo.enabled%22, false);%0Auser_pref(%22media.video_stats.enabled%22, false);%0A//user_pref(%22dom.maxHardwareConcurrency%22, 1); //faster on slow devices%0Auser_pref(%22dom.battery.enabled%22, false);%0Auser_pref(%22dom.telephony.enabled%22, false);%0Auser_pref(%22beacon.enabled%22, false);%0Auser_pref(%22device.sensors.enabled%22, false);%0Auser_pref(%22dom.vibrator.enabled%22, false);%0Auser_pref(%22dom.enable_resource_timing +media.video_stats.enabled%22, false);%0A//user_pref(%22dom.maxHardwareConcurrency%22, 1); //faster on slow devices%0Auser_pref(%22beacon.enabled%22, false);%0Auser_pref(%22device.sensors.enabled %22, f
881405af40942aec69ed4d05a501c5b8661e2ea2
read nonexistent tx-db folder
lib/db.js
lib/db.js
const _ = require('lodash/fp') const pify = require('pify') const fs = pify(require('fs')) const cp = require('child_process') const uuid = require('uuid') const path = require('path') const BN = require('./bn') let dbName module.exports = { save, prune, clean } function list (dbRoot) { return fs.mkdir(dbRoot) .catch(() => {}) .then(() => fs.readdir(dbRoot)) } function rotate (dbRoot) { dbName = 'tx-db-' + uuid.v4() + '.dat' return fs.mkdir(dbRoot) .catch(() => {}) .then(() => fs.writeFile(path.resolve(dbRoot, dbName), '')) } function save (dbRoot, tx) { return fs.appendFile(path.resolve(dbRoot, dbName), JSON.stringify(tx) + '\n') } function nuke (dbPath) { return fs.unlink(dbPath) } function safeJsonParse (txt) { try { return JSON.parse(txt) } catch (_) { } } function pruneFile (dbRoot, cleanP, _dbName) { const dbPath = path.resolve(dbRoot, _dbName) return load(dbPath) .then(txs => cleanP(txs)) .then(r => { return nuke(dbPath) .catch(err => console.log(`Couldn't nuke ${dbPath}: ${err}`)) .then(() => r) }) } function prune (dbRoot, cleanP) { return list(dbRoot) .then(files => { console.log(`Processing ${files.length} db files`) return rotate(dbRoot) .then(() => { const promises = _.map(file => pruneFile(dbRoot, cleanP, file), files) return Promise.all(promises) .then(results => { const sum = _.sum(results) if (sum === 0) return console.log('No pending txs to process.') console.log(`Successfully processed ${_.sum(results)} pending txs.`) }) .catch(err => console.log(`Error processing pending txs: ${err.stack}`)) }) }) } function massage (tx) { if (!tx) return const massagedFields = { fiat: _.isNil(tx.fiat) ? undefined : BN(tx.fiat), cryptoAtoms: _.isNil(tx.cryptoAtoms) ? undefined : BN(tx.cryptoAtoms) } return _.assign(tx, massagedFields) } function load (dbPath) { const txTable = {} return fs.readFile(dbPath, {encoding: 'utf8'}) .then(f => { const recs = f.split('\n') const parse = _.flow([safeJsonParse, massage]) const txs = _.remove(_.isEmpty, _.map(parse, recs)) _.forEach(tx => { txTable[tx.id] = tx }, txs) return _.sortBy(tx => tx.deviceTime, _.values(txTable)) }) } function clean (dbRoot) { if (_.isNil(dbRoot)) return const files = fs.readdirSync(dbRoot) if (files.length) { cp.exec('rm ' + dbRoot + '/*', {}, err => { if (err) console.log(err) }) } }
JavaScript
0.000001
@@ -2443,16 +2443,53 @@ return%0A + if (!fs.existsSync(dbRoot)) return%0A const
ac3caa9a23b495af94a1febdbd43b5e6b7beb778
Fix so on update is run
lib/db.js
lib/db.js
'use babel'; import {Emitter} from 'atom'; import CSON from 'season'; import fs from 'fs'; import path from 'path'; import os from 'os'; import _ from 'underscore-plus'; export default class DB { constructor() { this.emitter = new Emitter(); this.updaters = {}; fs.exists(this.file(), (exists) => { if (exists) { this.observeProjects(); } else { this.writeFile({}); } }); } get environmentSpecificProjects() { return atom.config.get('project-manager.environmentSpecificProjects'); } find(callback=null) { this.readFile(results => { let projects = []; let result = null; let template = null; let key; for (key in results) { result = results[key]; template = result.template || null; result._id = key; if (template && results[template] !== null) { result = _.deepExtend(result, results[template]); } for (let i in result.paths) { if (typeof result.paths[i] !== 'string') { continue; } if (result.paths[i].charAt(0) === '~') { result.paths[i] = result.paths[i].replace('~', os.homedir()); } } this.sendUpdate(result); projects.push(result); } if (callback) { callback(projects); } }); } add(props, callback) { this.readFile(projects => { const id = this.generateID(props.title); projects[id] = props; this.writeFile(projects, () => { atom.notifications.addSuccess(`${props.title} has been added`); callback(id); }); }); } update(props) { if (!props._id) { return false; } let project = null; let key; this.readFile(projects => { for (key in projects) { project = projects[key]; if (key === props._id) { delete(props._id); projects[key] = props; } this.writeFile(projects); } }); } delete(id, callback) { this.readFile(projects => { for (let key in projects) { if (key === id) { delete(projects[key]); } } this.writeFile(projects, () => { if (callback) { callback(); } }); }); } onUpdate(callback=null) { this.emitter.on('db-updated', () => { console.log('Updated'); this.find(callback); }); } sendUpdate(project) { for (let key in this.updaters) { const {id, query, callback} = this.updaters[key]; if (id === project._id || _.isEqual(project[query.key], query.value)) { callback(project); } } } addUpdater(id, query, callback) { this.updaters[id] = { id, query, callback }; } observeProjects() { if (this.fileWatcher) { this.fileWatcher.close(); } try { this.fileWatcher = fs.watch(this.file(), () => { this.emitter.emit('db-updated'); }); } catch (error) { let url = 'https://github.com/atom/atom/blob/master/docs/'; url += 'build-instructions/linux.md#typeerror-unable-to-watch-path'; const filename = path.basename(this.file()); const errorMessage = `<b>Project Manager</b><br>Could not watch changes to ${filename}. Make sure you have permissions to ${this.file()}. On linux there can be problems with watch sizes. See <a href='${url}'> this document</a> for more info.>`; this.notifyFailure(errorMessage); } } updateFile() { fs.exists(this.file(true), (exists) => { if (!exists) { this.writeFile({}); } }); } generateID(string) { return string.replace(/\s+/g, '').toLowerCase(); } file() { let filename = 'projects.cson'; const filedir = atom.getConfigDirPath(); if (this.environmentSpecificProjects) { let hostname = os.hostname().split('.').shift().toLowerCase(); filename = `projects.${hostname}.cson`; } return `${filedir}/${filename}`; } readFile(callback) { fs.exists(this.file(), (exists) => { if (exists) { try { let projects = CSON.readFileSync(this.file()) || {}; callback(projects); } catch (error) { const message = `Failed to load ${path.basename(this.file())}`; const detail = error.location != null ? error.stack : error.message; this.notifyFailure(message, detail); } } else { fs.writeFile(this.file(), '{}', () => callback({})); } }); } writeFile(projects, callback) { CSON.writeFileSync(this.file(), projects); if (callback) { callback(); } } notifyFailure(message, detail=null) { atom.notifications.addError(message, { detail: detail, dismissable: true }); } }
JavaScript
0
@@ -268,16 +268,139 @@ = %7B%7D;%0A%0A + this.onUpdate((projects) =%3E %7B%0A for (let project of projects) %7B%0A this.sendUpdate(project);%0A %7D%0A %7D);%0A%0A fs.e @@ -1348,42 +1348,8 @@ %7D%0A%0A - this.sendUpdate(result);%0A%0A @@ -2465,38 +2465,8 @@ %3E %7B%0A - console.log('Updated');%0A
896cf70e97356f1c1c38a90e6985c71239fb10da
add dirty fix to display rankings at 8:08 in France ;-)
huitparfait-api/src/services/rankingService.js
huitparfait-api/src/services/rankingService.js
import { cypher } from '../infra/neo4j' import { betterUser } from './userService' import moment from 'moment' export function calculateRanking({ groupId, userId, from = 0, pageSize = 50 }) { const transformAnonymous = (groupId == null) const eightLimit = getEightLimit() return cypher(` MATCH (me:User { id: {userId} })-[:IS_MEMBER_OF_GROUP { isActive: true }]->(g:Group {id: {groupId}} ) MATCH (u:User)-[:IS_MEMBER_OF_GROUP { isActive: true }]->(g) OPTIONAL MATCH (u)<-[:CREATED_BY_USER]-(p:Pronostic)-[IS_ABOUT_GAME]->(game:Game) WHERE game.startsAt < {eightLimit} OPTIONAL MATCH (u)<-[:CREATED_BY_USER]-(pp:Pronostic)-[IS_ABOUT_GAME]->(game) WHERE p.classicPoints IS NOT NULL AND pp.classicPoints = 5 AND pp.riskPoints = 3 WITH u, p.classicPoints + p.riskPoints AS score, pp AS perfect RETURN u.id AS userId, u.name AS userName, u.anonymousName AS anonymousName, u.avatarUrl AS avatarUrl, u.isAnonymous AS isAnonymous, SUM(score) as totalScore, COUNT(score) as nbPredictions, COUNT(perfect) AS nbPerfects ORDER BY totalScore DESC, nbPredictions DESC, nbPerfects DESC`, { userId, groupId, eightLimit, }) .map(formatRanking({ transformAnonymous })) .then(calculateRank) .then(paginate) function paginate(results = []) { if (pageSize == null) { return results } return results.slice(from, pageSize + from) } function getEightLimit() { const now = moment() const eightLimit = moment().startOf('day').add({ hours: 8, minutes: 8 }) if (now.isBefore(eightLimit)) { return eightLimit.subtract(1, 'days').valueOf() } return eightLimit.valueOf() } } function formatRanking({ transformAnonymous }) { return function formatRanking(rank) { return { user: betterUser(rank, transformAnonymous), stats: { totalScore: rank.totalScore, nbPredictions: rank.nbPredictions, nbPerfects: rank.nbPerfects, }, } } } export function calculateRank(ranking = []) { ranking.forEach((row, idx, rows) => { if (idx > 0 && rows[idx - 1].stats.totalScore === row.stats.totalScore) { row.rank = rows[idx - 1].rank return } row.rank = idx + 1 }) return ranking }
JavaScript
0
@@ -1798,16 +1798,82 @@ oment()%0A + // TODO handle 8:08 on Europe/Paris timezone properly ;-)%0A @@ -1928,17 +1928,17 @@ hours: -8 +6 , minute
c9ca96e2702be54f8a0964c39667c0f34b87a990
add int & uint methods
lib/is.js
lib/is.js
var typeOf = require('./of'); var typify = require('./typify'); var isBuffer = require('./is.buffer'); var isArrayLike = require('./is.array-like'); function is(expected, value) { return new RegExp('(' + typify(expected, true) + ')').test(typeOf(value)); } is.not = function isnt(expected, value) { return !is(expected, value); }; is.not.buffer = function isntBuffer(value) { return !isBuffer(value); }; is.not.arrayLike = function isntArrayLike(value) { return !isArrayLike(value); }; is.buffer = isBuffer; is.arrayLike = isArrayLike; is.a = is.an = is; is.not.a = is.not.an = is.not; module.exports = is;
JavaScript
0.000041
@@ -488,16 +488,321 @@ e);%0A%7D;%0A%0A +is.int = function isInt(value) %7B%0A%09return parseFloat(value, 10) === parseInt(value, 10);%0A%7D;%0A%0Ais.not.int = function isntInt(value) %7B%0A%09return !is.int(value);%0A%7D;%0A%0Ais.uint = function isUint(value) %7B%0A%09return is.int(value) && value %3E= 0;%0A%7D;%0A%0Ais.not.uint = function isntUint(value) %7B%0A%09return !is.uint(value);%0A%7D;%0A%0A is.buffe
3560b6eb3beabc9d3332a057f954f07154eca4db
Fix browser compatibility issues of the zoom
remote/remotezoom.js
remote/remotezoom.js
const RevealRemoteZoom = () => { let reveal = null let currentZoom = null let currentSlideElement = null function allowControl() { const config = reveal.getConfig() return config.controls && config.touch } function dispatchEnableZoom(focus) { if (!isValidFocus(focus)) { console.warn('invalid focus parameter for dispatchEnableZoom()'); return } reveal.dispatchEvent({ type: 'enable-zoom', data: { focus } }) } function dispatchDisableZoom() { reveal.dispatchEvent({ type: 'disable-zoom' }) } const doubleClickListener = (e) => { if (!allowControl()) return if (currentZoom !== null) { dispatchDisableZoom() } else { const location = getRelativeLocation({ element: currentSlideElement, event: e }) dispatchEnableZoom(location) } } function setupForSlideElement(element) { if (currentSlideElement !== null) { applyZoom(null) currentSlideElement.removeEventListener('dblclick', doubleClickListener) } element.addEventListener('dblclick', doubleClickListener) currentSlideElement = element } function getRelativeLocation({event, element}) { const elementLocation = element.getBoundingClientRect() const x = Math.round((event.clientX - elementLocation.left) * 100 / (elementLocation.right - elementLocation.left)) const y = Math.round((event.clientY - elementLocation.top) * 100 / (elementLocation.bottom - elementLocation.top)) return { x, y } } function applyZoom(focus) { if (focus === null) { currentSlideElement.style.transform = '' currentZoom = null } else { if (!isValidFocus(focus)) { console.warn('invalid focus parameter for applyZoom()'); return } const transform = 'scale(200%) translate(' + (50 - focus.x) + '%, ' + (50 - focus.y) + '%)' currentSlideElement.style.transform = transform currentZoom = focus } } function isValidFocus(focus) { return typeof focus === 'object' && Number.isInteger(focus.x) && Number.isInteger(focus.y) && focus.x >= 0 && focus.x <= 100 && focus.y >= 0 && focus.y <= 100 && Object.keys(focus).length === 2 } return { id: 'remote-zoom', init: (initReveal) => { reveal = initReveal reveal.addEventListener('slidechanged', (e) => setupForSlideElement(e.currentSlide)) reveal.addEventListener('ready', (e) => setupForSlideElement(e.currentSlide)) reveal.on('enable-zoom', (e) => applyZoom(e.focus)) reveal.on('disable-zoom', (e) => applyZoom(null)) reveal.on('overviewshown', () => dispatchDisableZoom()); }, getCurrentZoom: () => currentZoom, setCurrentZoom: (focus) => { if (focus === null) { dispatchDisableZoom() } else { if (!isValidFocus(focus)) { console.warn('invalid focus parameter for setCurrentZoom()'); return } dispatchEnableZoom(focus) } } } };
JavaScript
0
@@ -1797,11 +1797,8 @@ le(2 -00%25 ) tr
b74b4ed7bd7026fa9583ee334e1914fa91a4f6e2
update HuePicker
src/HuePicker/HuePicker.js
src/HuePicker/HuePicker.js
/** * @file HuePicker component * @author liangxiaojun([email protected]) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import Event from '../_vendors/Event'; import Dom from '../_vendors/Dom'; import Valid from '../_vendors/Valid'; import Color from '../_vendors/Color'; export default class HuePicker extends Component { constructor(props, ...restArgs) { super(props, ...restArgs); this.state = { offset: 0, value: props.value }; this.activated = false; this.mouseDownHandler = ::this.mouseDownHandler; this.mouseMoveHandler = ::this.mouseMoveHandler; this.mouseUpHandler = ::this.mouseUpHandler; } getOffset(value) { if (!Valid.isRGB(value)) { return 0; } return this.huePickerEl.offsetWidth * Color.hue2PerCent(value); } mouseDownHandler(e) { this.activated = true; this.changeHandler(e.clientX - Dom.getOffset(this.huePickerEl).left); } mouseMoveHandler(e) { if (this.activated) { this.changeHandler(e.clientX - Dom.getOffset(this.huePickerEl).left); } } mouseUpHandler(e) { this.activated = false; } changeHandler(offsetX) { const width = this.huePickerEl.offsetWidth, offset = Valid.range(offsetX, 0, width), perCent = offset / width, value = Color.perCent2Hue(perCent); this.setState({ offset, value }, () => { const {onChange} = this.props; onChange && onChange(value); }); } componentDidMount() { this.huePickerEl = this.refs.huePicker; this.setState({ offset: this.getOffset(this.props.value) }); Event.addEvent(document, 'mousemove', this.mouseMoveHandler); Event.addEvent(document, 'mouseup', this.mouseUpHandler); } componentWillUnmount() { Event.removeEvent(document, 'mousemove', this.mouseMoveHandler); Event.removeEvent(document, 'mouseup', this.mouseUpHandler); } render() { const {className, style} = this.props, {offset} = this.state, wrapperClassName = (className ? ' ' + className : ''), pointerStyle = { transform: `translateX(${offset}px)` }; return ( <div ref="huePicker" className={'hue-picker' + wrapperClassName} style={style} onMouseDown={this.mouseDownHandler}> <div className="color-picker-hue-pointer-wrapper" style={pointerStyle}> <i className="fa fa-caret-down color-picker-hue-pointer-top"></i> <i className="fa fa-caret-up color-picker-hue-pointer-bottom"></i> </div> </div> ); } }; HuePicker.propTypes = { /** * The CSS class name of the root element. */ className: PropTypes.string, /** * Override the styles of the root element. */ style: PropTypes.object, value: PropTypes.any, onChange: PropTypes.func }; HuePicker.defaultProps = { className: null, style: null, value: [255, 0, 0] };
JavaScript
0
@@ -558,24 +558,67 @@ d = false;%0A%0A + this.getOffset = ::this.getOffset;%0A this @@ -799,16 +799,35 @@ et(value + = this.props.value ) %7B%0A%0A @@ -1880,26 +1880,10 @@ set( -this.props.value )%0A + @@ -2027,32 +2027,284 @@ ndler);%0A%0A %7D%0A%0A + componentWillReceiveProps(nextProps) %7B%0A if (nextProps.value !== this.state.value) %7B%0A this.setState(%7B%0A value: nextProps.value,%0A offset: this.getOffset(nextProps.value)%0A %7D);%0A %7D%0A %7D%0A%0A componentWil
65065ccf92c147333e32694dcfb9e4f1dcb3fb39
fix to support SerialPort 7.x
src/NodeSerialTransport.js
src/NodeSerialTransport.js
'use strict'; var SerialPort = require('serialport').SerialPort, webduino = require('webduino-js'); var push = Array.prototype.push; var Transport = webduino.Transport, TransportEvent = webduino.TransportEvent, proto; function NodeSerialTransport(options) { Transport.call(this, options); this._options = options; this._port = null; this._sendTimer = null; this._buf = []; this._connHandler = onConnect.bind(this); this._messageHandler = onMessage.bind(this); this._sendOutHandler = sendOut.bind(this); this._disconnHandler = onDisconnect.bind(this); this._errorHandler = onError.bind(this); init(this); } function init(self) { var options = self._options; self._port = new SerialPort(options.path, { baudRate: options.baudRate }); self._port.on('open', self._connHandler); self._port.on('data', self._messageHandler); self._port.on('close', self._disconnHandler); self._port.on('error', self._errorHandler); } function onConnect() { this.emit(TransportEvent.OPEN); } function onMessage(data) { this.emit(TransportEvent.MESSAGE, data); } function onDisconnect(error) { if (error) { this.emit(TransportEvent.ERROR, error); } this._port.removeAllListeners(); delete this._port; this.emit(TransportEvent.CLOSE); } function onError(error) { this.emit(TransportEvent.ERROR, error); } function sendOut() { var payload = new Buffer(this._buf); this.isOpen && this._port.write(payload); clearBuf(this); } function clearBuf(self) { self._buf = []; clearImmediate(self._sendTimer); self._sendTimer = null; } NodeSerialTransport.prototype = proto = Object.create(Transport.prototype, { constructor: { value: NodeSerialTransport }, isOpen: { get: function () { return this._port && this._port.isOpen(); } } }); proto.send = function (payload) { push.apply(this._buf, payload); if (!this._sendTimer) { this._sendTimer = setImmediate(this._sendOutHandler); } }; proto.close = function () { if (this._port) { if (this._port.isOpen()) { this._port.close(); } else { this._port.removeAllListeners(); delete this._port; } } }; module.exports = NodeSerialTransport;
JavaScript
0
@@ -50,19 +50,8 @@ rt') -.SerialPort ,%0A @@ -1784,20 +1784,18 @@ t.isOpen -() ;%0A + %7D%0A @@ -1962,16 +1962,48 @@ %7D%0A%7D;%0A%0A +proto.flush = function () %7B%0A%0A%7D%0A%0A proto.cl @@ -2067,18 +2067,16 @@ t.isOpen -() ) %7B%0A @@ -2188,16 +2188,16 @@ %7D%0A%7D;%0A%0A + module.e @@ -2221,13 +2221,12 @@ alTransport; -%0A
8f85e73f324899829289a21e69ec3b6ac39a59ae
Add reject if map function failed
source/class/core/event/Flow.js
source/class/core/event/Flow.js
/* ================================================================================================== Core - JavaScript Foundation Copyright 2013 Sebastian Werner Copyright 2013 Sebastian Fastner ================================================================================================== */ (function() { var identity = function(x) { return x }; var map = function(promiseOrValues, mapFunction, context) { var promise; context = context || this; if (promiseOrValues && promiseOrValues.then && typeof promiseOrValues.then == "function") { return promiseOrValues.then(function(value) { return map(value, mapFunction, context); }, null, context); } else if (core.Main.isTypeOf(promiseOrValues, "Array")) { promise = core.event.Promise.obtain(); var resolved = 0; var len = promiseOrValues.length; var result = []; for (var i=0; i<len; i++) { map(promiseOrValues[i], mapFunction, context).then(function(value) { result.push(value); if (result.length == len) { promise.fulfill(result); } }); } } else { return mapFunction.call(context, promiseOrValues); // map([promiseOrValues], mapFunction, context); } return promise; }; core.Module("core.event.Flow", { /** * Initiates a competitive race that allows one winner, returning a promise that will * resolve when any one of the items in array resolves. The returned promise will * only reject if all items in array are rejected. The resolution value of the returned * promise will be the fulfillment value of the winning promise. The rejection value will be * an array of all rejection reasons. */ any : function(promiseOrValues) { }, /** * {core.event.Promise} Return a promise that will resolve only once all the inputs have resolved. * The resolution value of the returned promise will be an array containing the * resolution values of each of the inputs. * * If any of the input promises is rejected, the returned promise will be * rejected with the reason from the first one that is rejected. * * Inspired by when.js */ all : function(promiseOrValues) { return map(promiseOrValues, identity); }, map : map }); })();
JavaScript
0.000006
@@ -1076,16 +1076,75 @@ %7D%0A + %7D, function(reason) %7B%0A %09promise.reject(reason);%0A %7D) @@ -1220,57 +1220,8 @@ es); - // map(%5BpromiseOrValues%5D, mapFunction, context); %0A %7D
89808411d57ced163ab101e8cc63b9f68480bc33
use response end as indicator
test/integration/server.js
test/integration/server.js
module.exports = ServerTest = function() { IntegrationTest.call(this); var async = this.start(); this.server_responds_to_nonexistent_static_file_request_with_a_404 = function() { this.get("/dne.html", function(response) { assert.equal(response.statusCode, 404); async.finish(); }); } this.server_responds_to_static_file_request = function() { this.get("/index.html", function(response) { assert.equal(response.statusCode, 200); async.finish(); }); } this.server_responds_to_top_level_request = function() { this.get("/", function(response) { assert.equal(response.statusCode, 200); async.finish(); }); } this.can_fetch_transporter_include = function() { this.get("/lib/transporter/receiver.js", function(response) { assert.equal(response.statusCode, 200); async.finish(); }); } this.can_fetch_a_shared_resource_from_the_server = function() { this.get("/lib/shared.js", function(response) { assert.equal(response.statusCode, 200); async.finish(); }); } this.server_responds_to_unchunked_dynamic_requests = function() { this.get("/welcome", function(response) { assert.equal(response.statusCode, 200); async.finish(); }); } this.server_responds_to_chunked_dynamic_requests_via_template_loader = function() { this.get("/streaming", function(response) { assert.equal(response.complete, false); assert.equal(response.headers["transfer-encoding"], "chunked"); assert.equal(response.statusCode, 200); response.on("end", function() { assert.equal(response.complete, true); async.finish(); }); }); } this.server_can_access_params_from_query_string = function() { this.get("/params?id=secret", function(response) { assert.equal(response.statusCode, 200); var data = ""; response.on("data", function(d) { data += d }); ext.Sync.wait_for(function() { return data.length === 6 }, function() { assert.equal(data, "secret"); async.finish(); }); }); } this.server_can_access_params_from_request_body = function() { this.post("/form", { secret: "message" }, function(response) { assert.equal(response.statusCode, 200); var data = ""; response.on("data", function(d) { data += d }); response.on("end", function() { assert.equal(data, "message"); async.finish(); }); }); }; this.server_catches_and_reports_exceptions_in_controller_action = function() { this.get("/error", function(response) { assert.equal(response.statusCode, 500); var data = ""; response.on("data", function(d) { data += d }); response.on("end", function() { assert.equal(data.substring(0, 10), "test error"); async.finish(); }); }); } } inherits(ServerTest, IntegrationTest);
JavaScript
0.000001
@@ -1946,72 +1946,31 @@ %7D);%0A -%0A -ext.Sync.wait_for(function() %7B return data.length === 6 %7D +response.on(%22end%22 , fu
dfbc0debbe4fe77ba1c4e7bafcf42d53dcd8c606
Add reasons to focus properties, test for same, and test for audit rules to ignore
test/js/properties-test.js
test/js/properties-test.js
module("Text Descendant", { }); test("Find text descendants in an iframe.", function() { // Setup fixture var fixture = document.getElementById('qunit-fixture'); var iframe = document.createElement('iframe'); var html = '<body><div id="foo">bar</div></body>'; fixture.appendChild(iframe); iframe.contentWindow.document.open(); iframe.contentWindow.document.write(html); iframe.contentWindow.document.close(); var foo = iframe.contentDocument.getElementById("foo"); equal(axs.properties.hasDirectTextDescendant(foo), true); }); module('findTextAlternatives', { setup: function () { this.fixture_ = document.getElementById('qunit-fixture'); } }); test('returns the calculated text alternative for the given element', function() { var targetNode = document.createElement('select'); this.fixture_.appendChild(targetNode); try { equal(axs.properties.findTextAlternatives(targetNode, {}, true), ''); } catch(e) { ok(false, 'Threw exception'); } }); module('getTextFromHostLanguageAttributes', { setup: function () { this.fixture_ = document.getElementById('qunit-fixture'); } }); test('does not crash when targetNode has a numeric id attribute', function() { var targetNode = document.createElement('input'); targetNode.setAttribute('id', '123_user'); this.fixture_.appendChild(targetNode); try { equal(axs.properties.getTextFromHostLanguageAttributes(targetNode, {}, null), null); } catch(e) { ok(false, 'Threw exception: ' + e); } }); test('Get focus properties', function() { // Setup fixture var fixture = document.getElementById('qunit-fixture'); fixture.style.top = 0; fixture.style.left = 0; var html = '<div id="overlapped" tabindex="0">Overlapped element</div>' + '<div id="overlapping" style="font-size: 48px; ' + 'position: relative; top: -40px; height: 40px; ' + 'background: rgba(255, 255, 255, 0.5);">Overlapping div</div>'; fixture.innerHTML = html; var overlapped = document.getElementById('overlapped'); var overlapping = document.getElementById('overlapping'); var rect = overlapped.getBoundingClientRect(); var center_x = (rect.left + rect.right) / 2; var center_y = (rect.top + rect.bottom) / 2; var elementAtPoint = document.elementFromPoint(center_x, center_y); var focusProperties = axs.properties.getFocusProperties(overlapped); if (elementAtPoint != null) { deepEqual(focusProperties, { tabindex: { value: "0", valid: true }, visible: { value: false, valid: false, overlappingElement: overlapping } }); } else { // This will occur if running in phantomjs. deepEqual(focusProperties, { tabindex: { value: "0", valid: true }, visible: { value: true, valid: true } }); } });
JavaScript
0
@@ -565,17 +565,16 @@ );%0A%7D);%0A%0A -%0A module('
5282a920fef9bf7850117b2723b4fdd9710093be
fix datepicker
source/assets/javascripts/locastyle/_datepicker.js
source/assets/javascripts/locastyle/_datepicker.js
var locastyle = locastyle || {}; locastyle.datepicker = (function() { 'use strict'; function init() { var $datepicker = $('#datepicker').pikaday({ firstDay: 1, minDate: new Date('2000-01-01'), maxDate: new Date('2020-12-31'), yearRange: [2000,2020], i18n: { previousMonth : 'Anterior', nextMonth : 'Próximo', months : ['Janeiro','Fevereiro','Março','Abril','Maio','Junnho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'], weekdays : ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado'], weekdaysShort : ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'] } }); $datepicker.pikaday('show').pikaday('nextMonth'); } return { init: init }; }());
JavaScript
0.000001
@@ -87,52 +87,188 @@ %0A%0A -function init() %7B%0A var $datepicker = $('# +var config = %7B%0A selector: '.datepicker'%0A %7D;%0A%0A function init() %7B%0A $(config.selector).each(function()%7B%0A create($(this));%0A %7D);%0A %7D%0A%0A function create($elem)%7B%0A var $ date @@ -273,18 +273,24 @@ tepicker -') + = $elem .pikaday @@ -292,18 +292,16 @@ kaday(%7B%0A - fi @@ -317,18 +317,16 @@ ,%0A - - minDate: @@ -346,26 +346,24 @@ 00-01-01'),%0A - maxDat @@ -395,18 +395,16 @@ ,%0A - - yearRang @@ -429,18 +429,16 @@ - i18n: %7B%0A @@ -433,18 +433,16 @@ i18n: %7B%0A - @@ -477,18 +477,16 @@ - nextMont @@ -504,18 +504,16 @@ %C3%B3ximo',%0A - @@ -645,34 +645,32 @@ mbro'%5D,%0A - weekdays : @@ -739,26 +739,24 @@ '%5D,%0A - weekdaysShor @@ -809,18 +809,16 @@ %5D%0A - %7D%0A %7D) @@ -825,59 +825,71 @@ ;%0A - $datepicker.pikaday('show').pikaday('nextMonth' +%7D%0A%0A function newDatepicker(selector)%7B%0A create($(selector) ); + %0A %7D @@ -915,16 +915,50 @@ it: init +,%0A newDatepicker: newDatepicker %0A %7D;%0A%0A%7D
8a9eb6c5f1112ef9f0db6d0102ce475d158c9a01
disable snackbar message in error handler
addon/-lib/authenticated.js
addon/-lib/authenticated.js
import { get, getWithDefault } from '@ember/object'; import { isEmpty } from '@ember/utils'; import { getOwner } from '@ember/application'; import { Mixin as M } from 'base-object'; import { isFunction, isPlainObject } from 'lodash-es'; const bearerErrorCodes = [ 'invalid_token', 'unknown_token', 'token_disabled', 'unknown_client', 'client_disabled', 'unknown_account', 'account_disabled' ]; const AuthenticatedMixin = M.create ({ beforeModel (transition) { this._super (...arguments); this._checkSignedIn (transition); }, actions: { error (reason) { let errors = get (reason, 'errors'); if (isEmpty (errors)) { return true; } for (let i = 0, len = errors.length; i < len; ++ i) { let error = errors[i]; if (error.status === '403' && bearerErrorCodes.indexOf (error.code) !== -1) { // Redirect to sign in page, allowing the user to redirect back to the // original page. But, do not support the back button. let ENV = getOwner (this).resolveRegistration ('config:environment'); let signInRoute = getWithDefault (ENV, 'gatekeeper.signInRoute', 'sign-in'); // Display the error message. this.send ('app:snackbar', { message: error.detail }); // Force the user to sign out. this.session.forceSignOut (); this.replaceWith (signInRoute); return; } } return true; } }, _checkSignedIn (transition) { let isSignedIn = get (this, 'session.isSignedIn'); if (!isSignedIn) { let ENV = getOwner (this).resolveRegistration ('config:environment'); let signInRoute = getWithDefault (ENV, 'gatekeeper.signInRoute', 'sign-in'); let { intent: { url }} = transition; // Set the redirect to route so we can come back to this route when the // user has signed in. const queryParams = { redirect: url }; this.replaceWith (signInRoute, { queryParams }); } }, }); function applyMixin (Clazz) { return AuthenticatedMixin.apply (Clazz.prototype); } export default function authenticated (param) { if (isFunction (param)) { return applyMixin (param); } else if (isPlainObject (param)) { return applyMixin; } }
JavaScript
0.000002
@@ -1224,24 +1224,26 @@ .%0A +// this.send ('
091a2184d68cc8420db324f1c0b6e821ee57afbf
fix carousel CSS
src/components/carousels/CarouselRenderables.js
src/components/carousels/CarouselRenderables.js
import React, { PureComponent } from 'react' import PropTypes from 'prop-types' import Slider from 'react-slick' import { NextPaddle, PrevPaddle } from './CarouselParts' import PostStreamContainer from '../../containers/PostStreamContainer' import { css, media, select } from '../../styles/jss' import * as s from '../../styles/jso' const editorialWrapperStyle = css( s.relative, s.fullHeight, select('& .slick-slider, & .slick-list, & .slick-track', s.fullHeight), ) const editorialNavStyle = css( s.absolute, s.zIndex3, { top: 0, right: 0 }, media(s.minBreak2, { top: 5, right: 5 }), ) const itemBaseStyle = css( s.relative, s.flex, s.flexWrap, s.fullWidth, s.fullHeight, s.px20, s.py20, s.bgcTransparent, media(s.minBreak2, s.px40, s.py40), ) export class SlickCarousel extends PureComponent { static propTypes = { postIds: PropTypes.object.isRequired, renderProps: PropTypes.object.isRequired, } next = () => { this.slider.slickNext() } prev = () => { this.slider.slickPrev() } render() { const { postIds, renderProps } = this.props return ( <div className={editorialWrapperStyle}> <Slider autoplay arrows={false} infinite ref={(comp) => { this.slider = comp return this.slider }} > {postIds.map(id => ( <div className={itemBaseStyle} key={`curatedEditorial_post_${id}`}> <PostStreamContainer postId={id} {...renderProps} /> </div> ))} </Slider> {postIds.size > 1 && <nav className={editorialNavStyle}> <PrevPaddle onClick={this.prev} /> <NextPaddle onClick={this.next} /> </nav> } </div> ) } } export default SlickCarousel
JavaScript
0.000003
@@ -392,16 +392,64 @@ Height,%0A + select('& .slick-slide %3E div', s.fullHeight),%0A select @@ -808,18 +808,8 @@ s.p -x40, s.py4 0),%0A
393f975f9252a656d2f7e365a4523791ac951031
fix to use step objects from json
lib/imports/api/authority/server/authority.js
lib/imports/api/authority/server/authority.js
// import { ProseMirror } from './../../../prosemirror/dist/edit' import { Step } from './../../../prosemirror/dist/transform' import { defaultSchema } from './../../../prosemirror/dist/model/defaultschema' export class ProseMeteorAuthority { /** * Central authority to track a ProseMirror document, apply steps from clients, and notify clients when changes occur. * @param {String} docId a unique id for the doc * @constructor */ constructor( docId, snapshotCollection, serverStreamer ) { console.log('created authority for doc: ' + docId); // create a new PM instance to track the doc's' state // = new ProseMirror(); this.doc = null; this.docId = docId; this.snapshotCollection = snapshotCollection; this.steps = []; this.stepClientIds = []; this.streamer = serverStreamer; // when a client submits new steps, we receieve them this.streamer.on('clientSubmitSteps', this.receieveSteps.bind(this)); } /** * Receive new steps from a client, applying them to the local doc and * storing them. * @param {Number} version version of the document these steps apply to * @param {[Step]} steps steps to be applied to the doc * @param {String} clientId id of the client submitting the steps * @return {[type]} [description] */ receieveSteps({ clientId, steps, version }) { // parse the steps from json and convert them into Step instances const stepObjects = steps.map((step) => { return Step.fromJSON(defaultSchema, step); }); //console.log('Server got step: ' + resp); console.log('Authority received steps from client ' + clientId + ' for version ' + version); // // if the client submitted steps but that client didn't have the latest version // of the doc, stop since they must be applied to newest doc version if (version !== this.steps.length) { return; } // apply and accumulate new steps steps.forEach((step) => { this.doc = step.apply(this.doc).doc; this.steps.push(step); this.stepClientIds.push(clientId); }); console.log('Authority updated doc:', this.doc); console.log('Authority steps:', this.steps); console.log('Authority step client Ids:', this.stepClientIds); // notify listening clients that new steps have arrived // this.streamer.emit('authorityNewSteps'); } /** * Return all steps since the provided version. * @param {Number} version version of the document * @return {Object} stepsSince object with "steps" array and "clientIds" array */ stepsSince(version) { return { steps: this.steps.slice(version), clientIds: this.stepClientIds.slice(version) }; } // /** // * Store a snapshot of the current document in the snapshotCollection // */ // storeSnapshot() { // const doc = this.pm.doc; // const newSnapshotJSON = doc.toJSON(); // const newSnapshotNumber = ProseMeteorManager.numberOfSnapshots() + 1; // this.snapshotCollection.insert({ // docId: this.docId, // docJSON: newSnapshotJSON, // timestamp: Date.now(), // number: newSnapshotNumber // }); // } // /** // * Loads the latest snapshot from db and sets it to this authority's PM instance's doc state. // */ // loadLatestSnapshot() { // const snapshotJSON = ProseMeteorManager.getLatestSnapshotJSON(this.docId); // this.pm.setDoc(this.pm.schema.nodeFromJSON(lastSnapshot)); // } }
JavaScript
0
@@ -1971,16 +1971,22 @@ step +Object s.forEac
9170a32fe7b6bf047eb342aadf5fbc7e23144ff5
add functional logic for total value
src/components/rows/presentation/DaysWorking.js
src/components/rows/presentation/DaysWorking.js
import React from 'react' import { TableRow, TableRowColumn } from 'material-ui/Table' const DaysWorking = ({ annualLeave, sickLeave, publicHolidays, weekends, days, style }) => { delete days.thisYear // get total number of days in the year. // subtract weekends, sickLeave, annualLeave, publicHolidays from it. const total = Object.values(days) return ( <TableRow> <TableRowColumn> <h3>Total number of days you are working this year</h3> </TableRowColumn> <TableRowColumn> <p style={style.outputNumbers}>{ !isNaN(total) && total }</p> </TableRowColumn> </TableRow> ) } export default DaysWorking
JavaScript
0.000053
@@ -181,181 +181,232 @@ %7B%0A -delete days.thisYear%0A // get total number of days in the year.%0A // subtract weekends, sickLeave, annualLeave, publicHolidays from it.%0A const total = Object.values(day +const total = Object.values(days)%0A .filter(value =%3E value %3C 54) // get rid of the thisYear value%0A .reduce((a, b) =%3E a + b) // add up all the remaining values%0A - (annualLeave + sickLeave + publicHolidays + weekend s)%0A -%0A re @@ -553,32 +553,32 @@ TableRowColumn%3E%0A - %3Cp style @@ -618,16 +618,44 @@ otal) && + annualLeave && sickLeave && total %7D
76a3754dcc698442b2ec4396f6f6f986ce14dbf8
rework regex
plugins/link-text/index.js
plugins/link-text/index.js
/** * A plugin to identify unclear link text such as "more" and "click here," * which can make for a bad experience when using a screen reader */ let $ = require("jquery"); let Plugin = require("../base"); let annotate = require("../shared/annotate")("link-text"); class LinkTextPlugin extends Plugin { getTitle() { return "Link text"; } getDescription() { return ` Identifies links that may be confusing when read by a screen reader `; } /** * Slightly modified unclear text checking that has been refactored into * a single method to be called with arbitrary strings. * * Original: https://github.com/GoogleChrome/accessibility-developer-tools/blob/9183b21cb0a02f5f04928f5cb7cb339b6bbc9ff8/src/audits/LinkWithUnclearPurpose.js#L55-67 */ isDescriptiveText(textContent) { textContent = textContent.replace(/[^a-zA-Z ]/g, ""); let stopWords = [ "click", "tap", "go", "here", "learn", "more", "this", "page", "link", "about" ]; for (let i = 0; i < stopWords.length; i++) { let stopwordRE = new RegExp("\\b" + stopWords[i] + "\\b", "ig"); textContent = textContent.replace(stopwordRE, ""); if (textContent.trim() === "") { return false; } } return true; } /** * Checks whether or not the text content of an element (including things * like `aria-label`) is unclear. */ validateTextContent(el) { let textContent = $.axs.properties.getTextFromDescendantContent(el); return { textContent: textContent, result: this.isDescriptiveText(textContent), }; } /** * Checks if an image has descriptive alt text. This is used to determine * whether or not image links (<a> tags with a single <img> descendant) * are unclear. */ validateAltText(el) { let altTextContent = el.getAttribute("alt"); return { textContent: altTextContent, result: this.isDescriptiveText(altTextContent), }; } reportError($el, description, textContent) { let entry = this.error("Link text is unclear", description, $el); annotate.errorLabel($el, "", `Link text "${textContent}" is unclear`, entry); } run() { $("a").each((i, el) => { let $el = $(el); // Ignore the tota11y UI if ($el.parents(".tota11y").length) { return; } // If this anchor contains a single image, we will test the // clarity of that image's alt text. if ($el.find("> img").length === 1) { let report = this.validateAltText($el.find("> img")[0]); if (!report.result) { let description = ` The alt text for this link's image, <i>"${report.textContent}"</i>, is unclear without context and may be confusing to screen readers. Consider providing more detailed alt text. `; this.reportError($el, description, report.textContent); } } else { let report = this.validateTextContent(el); if (!report.result) { let description = ` The text <i>"${report.textContent}"</i> is unclear without context and may be confusing to screen readers. Consider rearranging the <code>&lt;a&gt;&lt;/a&gt; </code> tags or including special screen reader text. `; this.reportError($el, description, report.textContent); } } }); } cleanup() { annotate.removeAll(); } } module.exports = LinkTextPlugin;
JavaScript
0.00003
@@ -873,70 +873,8 @@ ) %7B%0A - textContent = textContent.replace(/%5B%5Ea-zA-Z %5D/g, %22%22);%0A @@ -1009,25 +1009,24 @@ %5D;%0A -%0A for (let @@ -1021,57 +1021,59 @@ -for (let i = 0; i %3C stopWords.length; i++) %7B%0A +// Generate a regex to match each of the stopWords%0A @@ -1084,20 +1084,21 @@ let stop -w +W ord +s RE = new @@ -1109,16 +1109,15 @@ Exp( -%22%5C%5Cb%22 + +%60%5C%5Cb($%7B stop @@ -1125,19 +1125,24 @@ ords -%5Bi%5D + %22%5C%5Cb%22 +.join(%22%7C%22)%7D)%5C%5Cb%60 , %22i @@ -1142,28 +1142,25 @@ %5Cb%60, %22ig%22);%0A - +%0A text @@ -1184,33 +1184,105 @@ tent -.replace(stopwordRE +%0A // Strip leading non-alphabetical characters%0A .replace(/%5B%5Ea-zA-Z %5D/g , %22%22) -; %0A @@ -1294,115 +1294,168 @@ -if (textContent.trim() === %22%22) %7B%0A return false;%0A %7D%0A %7D%0A%0A return true +// Remove the stopWords%0A .replace(stopWordsRE, %22%22);%0A%0A // Return whether or not there is any text left%0A return textContent.trim() !== %22%22 ;%0A
1b8591fca0fd2773d1969faaf60ba6eee86c4997
Fix Issue232, avoid TD002 for EMG
lib/package/plugins/TD002-useTargetServers.js
lib/package/plugins/TD002-useTargetServers.js
/* Copyright 2019 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. */ //useTargetServers //| &nbsp; |:white_medium_square:| TD002 | Use Target Server | Discourage use of direct URLs in Target Server. | const xpath = require("xpath"), ruleId = require("../myUtil.js").getRuleId(), debug = require("debug")("apigeelint:" + ruleId); var plugin = { ruleId, name: "Discourage use of direct URLs in Target Server.", message: "Using a Target Server simplifies CI/CD.", fatal: false, severity: 1, //warn nodeType: "TargetEndpoint", enabled: true }; var onTargetEndpoint = function(target, cb) { //get /TargetEndpoint/HTTPTargetConnection/URL var hadWarnErr = false; var url = xpath.select( "/TargetEndpoint/HTTPTargetConnection/URL/text()", target.getElement() ); if (url && url[0] !== undefined ) { let name = target.getName(); target.addMessage({ plugin, message: `TargetEndpoint (${name}) is using URL (${url}), using a Target Server simplifies CI/CD.` }); hadWarnErr=true; } if (typeof cb == "function") { cb(null,hadWarnErr); } return hadWarnErr; }; module.exports = { plugin, onTargetEndpoint };
JavaScript
0
@@ -1091,19 +1091,242 @@ %7D;%0A%0A -var +let emg = false;%0A%0Aconst onBundle = function (b, cb) %7B%0A debug( %22onBundle: %22 + b.getName());%0A if( b.getName().startsWith(%22edgemicro_%22) ) %7B%0A emg = true;%0A %7D%0A if (typeof cb == %22function%22) %7B%0A cb(null, false);%0A %7D%0A%7D;%0A%0Aconst onTarge @@ -1366,15 +1366,18 @@ %7B%0A -//get / +debug( %22on Targ @@ -1390,33 +1390,24 @@ oint -/HTTPTargetConnection/URL + emg: %22 + emg ); %0A v @@ -1429,16 +1429,34 @@ false;%0A +%0A if( !emg ) %7B%0A var ur @@ -1473,16 +1473,18 @@ select(%0A + %22/ @@ -1534,24 +1534,26 @@ t()%22,%0A + target.getEl @@ -1568,14 +1568,18 @@ + );%0A%0A + + if ( @@ -1614,16 +1614,18 @@ ) %7B%0A + let name @@ -1645,16 +1645,18 @@ Name();%0A + targ @@ -1677,24 +1677,26 @@ %7B%0A + plugin,%0A me @@ -1687,16 +1687,18 @@ plugin,%0A + me @@ -1802,12 +1802,16 @@ + + %7D);%0A + @@ -1823,24 +1823,30 @@ rnErr=true;%0A + %7D%0A %7D%0A%0A if (t @@ -1954,16 +1954,28 @@ plugin,%0A + onBundle,%0A onTarg
c0141e9ccd02fe0226a7695d56b69f9b8a0e2060
fix bugs, plus log progress better
generate.js
generate.js
var sbot = require('scuttlebot') var fs = require('fs') var path = require('path') var pull = require('pull-stream') var paramap = require('pull-paramap') var Blather = require('blather') function markov (name) { var m = new Blather() var text = fs.readFileSync(path.join(__dirname, 'text', name+'.txt'), 'utf8') console.log(text.length) m.addText(text) return m } //some text sources from the front pages of project gutenburg var markovs = { melville: markov('moby-dick'), twain : markov('a-tale-of-two-cities'), wilde : markov('picture-of-dorian-grey'), kafka : markov('metamorphosis'), grim : markov('grims-fairy-tales') } var keys = Object.keys(markovs) var crypto = require('crypto') var ssbKeys = require('ssb-keys') function hash (s) { return crypto.createHash('sha256').update(s).digest() } var names = require('random-name') function randomName(feed) { return names.first() + '_' + names.last() } function randA(feeds) { return feeds[~~(Math.random()*feeds.length)] } function addNames () { return paramap(function (feed, cb) { feed.name = randomName() feed.voice = keys.shift() keys.push(feed.voice) feed.add({ type: 'contact', contact: {feed: feed.id}, follow: true, name: feed.name, voice: feed.voice }, function () { cb(null, feed) }) }) } function addMessage (feeds) { return paramap(function (feed, cb) { var random = Math.random() var f = randA(feeds) if(random < 0.5) //say something feed.add({ type: 'post', text: markovs[feed.voice].paragraph() }, function (_, msg) { //track the latest message feed.msg = msg cb(null, msg) }) if(random < 0.7) { //follow someone feed.add({ type: 'contact', contact: {feed: f.id}, name: f.name }, cb) } else { //reply to some one feed.add({ type: 'post', repliesTo: f.msg ? {msg: f.msg.key} : undefined, text: markovs[feed.voice].sentence() + ' @' + f.id, mentions: [{feed: f.id}], }, function (_, msg) { //track the latest message feed.msg = msg cb(null, msg) }) } }) } var config = { feeds: 1000, messages: 100000, seed: 'generate test networks key, [add your own entropy here]' } module.exports = function (ssb, main, cb) { var seed = config, count = 0, key = 0 var root = hash(seed) var last = '' var feeds = [] pull( pull.count(1000), //config.feeds), pull.map(function () { var feed = ssb.createFeed(ssbKeys.generate('ed25519', hash(seed + ++key)) feeds.push(feed) last = feed.id return feed }), addNames(), pull.collect(function (err, feeds) { if(err) throw err pull( pull.count(config.messages), pull.map(function (n) { return randA(feeds) }), addMessage(feeds), pull.drain(function () { console.log(++count) }, cb) ) }) ) } sbot.init(require('./config'), function (err, sbot) { module.exports(sbot.ssb, sbot.feed, function () { console.log('generated!') }) })
JavaScript
0
@@ -2242,17 +2242,17 @@ feeds: 1 -0 +5 00,%0A me @@ -2259,17 +2259,17 @@ ssages: -1 +2 00000,%0A @@ -2336,16 +2336,320 @@ re%5D'%0A%7D%0A%0A +function flowMeter (log, slice) %7B%0A var count = 0, slice_count = 0, ts%0A return pull.through(function (data) %7B%0A count ++; slice_count++%0A if(!ts) ts = Date.now()%0A if(Date.now() %3E ts + slice) %7B%0A log(count, slice_count, slice_count/slice)%0A ts = Date.now(); slice_count = 0%0A %7D%0A %7D)%0A%0A%7D%0A%0A module.e @@ -2694,23 +2694,8 @@ var - seed = config, cou @@ -2725,24 +2725,31 @@ root = hash( +config. seed)%0A%0A var @@ -2805,17 +2805,8 @@ unt( -1000), // conf @@ -2908,16 +2908,23 @@ ', hash( +config. seed + + @@ -2929,16 +2929,17 @@ ++key)) +) %0A f @@ -3082,16 +3082,81 @@ row err%0A + if(!feeds.length) throw new Error('feed generation failed') %0A p @@ -3310,73 +3310,61 @@ -pull.drain(function () %7B%0A console.log(++count)%0A %7D +flowMeter(console.log, 1000),%0A pull.drain(null , cb @@ -3525,16 +3525,33 @@ ated!')%0A + sbot.close()%0A %7D)%0A%7D)%0A
0c7edbae0916f4ad82dfbdb55042dc58933c2f94
fix part of bug 1272 testcases test_compareToLjava_lang_Enum and test_valueOfLjava_lang_String in EnumTest will failed
sources/net.sf.j2s.java.core/src/java/lang/Enum.js
sources/net.sf.j2s.java.core/src/java/lang/Enum.js
Clazz.load (["java.io.Serializable", "java.lang.Comparable"], "java.lang.Enum", ["java.lang.ClassCastException", "$.CloneNotSupportedException", "$.IllegalArgumentException", "$.NullPointerException"], function () { c$ = java.lang.Enum = Enum = function () { this.$name = null; this.$ordinal = 0; Clazz.instantialize (this, arguments); }; Clazz.decorateAsType (c$, "Enum", null, [Comparable, java.io.Serializable]); Clazz.defineMethod (c$, "name", function () { return this.$name; }); Clazz.defineMethod (c$, "ordinal", function () { return this.$ordinal; }); Clazz.makeConstructor (c$, function (name, ordinal) { this.$name = name; this.$ordinal = ordinal; }, "String, Number"); Clazz.defineMethod (c$, "toString", function () { return this.$name; }); Clazz.defineMethod (c$, "equals", function (other) { return this == other; }, "Object"); Clazz.defineMethod (c$, "hashCode", function () { return System.identityHashCode (this); }); Clazz.defineMethod (c$, "clone", function () { throw new CloneNotSupportedException (); }); Clazz.defineMethod (c$, "compareTo", function (o) { var other = o; var self = this; if (self.getClass () != other.getClass () && self.getDeclaringClass () != other.getDeclaringClass ()) throw new ClassCastException (); return self.ordinal - other.ordinal; }, "E"); Clazz.defineMethod (c$, "getDeclaringClass", function () { var clazz = this.getClass (); var zuper = clazz.getSuperclass (); return (zuper == Enum) ? clazz : zuper; }); Clazz.defineMethod (Enum, "$valueOf", function (enumType, name) { return enumType.$valueOf (name); }, "Object, String"); /* "Class, String" */ Clazz.defineMethod (Enum, "$valueOf", function (name) { if (name == null) throw new NullPointerException ("Name is null"); var vals = this.values (); for (var i = 0; i < vals.length; i++) { if (name == vals[i].name ()) { return vals[i]; } } throw new IllegalArgumentException ("No enum const " + enumType + "." + name); }, "String"); Enum.$valueOf = Enum.prototype.$valueOf; Clazz.defineMethod (Enum, "values", function () { if (this.$ALL$ENUMS != null) { return this.$ALL$ENUMS; } this.$ALL$ENUMS = new Array (); var clazzThis = this.getClass (); for (var e in clazzThis) { if (clazzThis[e] != null && clazzThis[e].__CLASS_NAME__ != null && e != "prototype" && Clazz.instanceOf (clazzThis[e], clazzThis)) { this.$ALL$ENUMS[this.$ALL$ENUMS.length] = clazzThis[e]; } } return this.$ALL$ENUMS; }); Enum.values = Enum.prototype.values; });
JavaScript
0
@@ -1115,24 +1115,85 @@ tion (o) %7B%0D%0A +if (o == null) %7B%0D%0A throw new NullPointerException ();%0D%0A%7D%0D%0A var other = @@ -1363,16 +1363,17 @@ rn self. +$ ordinal @@ -1380,16 +1380,17 @@ - other. +$ ordinal; @@ -2038,24 +2038,35 @@ nst %22 + -enumType +this.__CLASS_NAME__ + %22.%22 +
793c250803439636096110bb082a950e55b67b29
Update GoogleApiComponent.js
dist/GoogleApiComponent.js
dist/GoogleApiComponent.js
(function (global, factory) { if (typeof define === "function" && define.amd) { define(['exports', 'react', 'react-dom', './lib/ScriptCache', './lib/GoogleApi'], factory); } else if (typeof exports !== "undefined") { factory(exports, require('react'), require('react-dom'), require('./lib/ScriptCache'), require('./lib/GoogleApi')); } else { var mod = { exports: {} }; factory(mod.exports, global.react, global.reactDom, global.ScriptCache, global.GoogleApi); global.GoogleApiComponent = mod.exports; } })(this, function (exports, _react, _reactDom, _ScriptCache, _GoogleApi) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.wrapper = undefined; var _react2 = _interopRequireDefault(_react); var _reactDom2 = _interopRequireDefault(_reactDom); var _GoogleApi2 = _interopRequireDefault(_GoogleApi); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var defaultMapConfig = {}; var defaultCreateCache = function defaultCreateCache(options) { options = options || {}; var apiKey = options.apiKey; var libraries = options.libraries || ['places']; var version = options.version || '3.24'; var language = options.language || 'en'; return (0, _ScriptCache.ScriptCache)({ google: (0, _GoogleApi2.default)({ apiKey: apiKey, language: language, libraries: libraries, version: version }) }); }; var wrapper = exports.wrapper = function wrapper(options) { return function (WrappedComponent) { var apiKey = options.apiKey; var libraries = options.libraries || ['places']; var version = options.version || '3'; var createCache = options.createCache || defaultCreateCache; var Wrapper = function (_React$Component) { _inherits(Wrapper, _React$Component); function Wrapper(props, context) { _classCallCheck(this, Wrapper); var _this = _possibleConstructorReturn(this, (Wrapper.__proto__ || Object.getPrototypeOf(Wrapper)).call(this, props, context)); _this.scriptCache = createCache(options); _this.scriptCache.google.onLoad(_this.onLoad.bind(_this)); _this.state = { loaded: false, map: null, google: null }; return _this; } _createClass(Wrapper, [{ key: 'onLoad', value: function onLoad(err, tag) { this._gapi = window.google; this.setState({ loaded: true, google: this._gapi }); } }, { key: 'render', value: function render() { var props = Object.assign({}, this.props, { loaded: this.state.loaded, google: window.google }); return _react2.default.createElement( 'div', null, _react2.default.createElement(WrappedComponent, props), _react2.default.createElement('div', { ref: 'map' }) ); } }]); return Wrapper; }(_react2.default.Component); return Wrapper; }; }; exports.default = wrapper; });
JavaScript
0.000001
@@ -3224,9 +3224,9 @@ '3.2 -4 +8 ';%0A @@ -5717,8 +5717,9 @@ per;%0A%7D); +%0A
f291eff799dd74c06f5934aacbcfbdb4d8f7d009
Fix dynamic commit hash abbreviation length (#272)
lib/ui.js
lib/ui.js
'use strict'; const execa = require('execa'); const inquirer = require('inquirer'); const chalk = require('chalk'); const githubUrlFromGit = require('github-url-from-git'); const util = require('./util'); const version = require('./version'); function prettyVersionDiff(oldVersion, inc) { const newVersion = version.getNewVersion(oldVersion, inc).split('.'); oldVersion = oldVersion.split('.'); let firstVersionChange = false; const output = []; for (let i = 0; i < newVersion.length; i++) { if ((newVersion[i] !== oldVersion[i] && !firstVersionChange)) { output.push(`${chalk.dim.cyan(newVersion[i])}`); firstVersionChange = true; } else if (newVersion[i].indexOf('-') >= 1) { let preVersion = []; preVersion = newVersion[i].split('-'); output.push(`${chalk.dim.cyan(`${preVersion[0]}-${preVersion[1]}`)}`); } else { output.push(chalk.reset.dim(newVersion[i])); } } return output.join(chalk.reset.dim('.')); } function printCommitLog(repositoryUrl) { return execa.stdout('git', ['rev-list', `--tags`, '--max-count=1']) .then(latestHash => execa.stdout('git', ['log', '--format=%s %h', `${latestHash}..HEAD`])) .then(result => { if (!result) { return false; } const history = result.split('\n') .map(commit => { const commitParts = commit.match(/^(.+)\s([a-f\d]{7})$/); const commitMessage = util.linkifyIssues(repositoryUrl, commitParts[1]); const commitId = util.linkifyCommit(repositoryUrl, commitParts[2]); return `- ${commitMessage} ${commitId}`; }) .join('\n'); console.log(`${chalk.bold('Commits:')}\n${history}\n`); return true; }); } module.exports = options => { const pkg = util.readPkg(); const oldVersion = pkg.version; const repositoryUrl = pkg.repository && githubUrlFromGit(pkg.repository.url); console.log(`\nPublish a new version of ${chalk.bold.magenta(pkg.name)} ${chalk.dim(`(current: ${oldVersion})`)}\n`); const prompts = [ { type: 'list', name: 'version', message: 'Select semver increment or specify new version', pageSize: version.SEMVER_INCREMENTS.length + 2, choices: version.SEMVER_INCREMENTS .map(inc => ({ name: `${inc} ${prettyVersionDiff(oldVersion, inc)}`, value: inc })) .concat([ new inquirer.Separator(), { name: 'Other (specify)', value: null } ]), filter: input => version.isValidVersionInput(input) ? version.getNewVersion(oldVersion, input) : input }, { type: 'input', name: 'version', message: 'Version', when: answers => !answers.version, filter: input => version.isValidVersionInput(input) ? version.getNewVersion(pkg.version, input) : input, validate: input => { if (!version.isValidVersionInput(input)) { return 'Please specify a valid semver, for example, `1.2.3`. See http://semver.org'; } if (!version.isVersionGreater(oldVersion, input)) { return `Version must be greater than ${oldVersion}`; } return true; } }, { type: 'list', name: 'tag', message: 'How should this pre-release version be tagged in npm?', when: answers => !pkg.private && version.isPrereleaseVersion(answers.version) && !options.tag, choices: () => execa.stdout('npm', ['view', '--json', pkg.name, 'dist-tags']) .then(stdout => { const existingPrereleaseTags = Object.keys(JSON.parse(stdout)) .filter(tag => tag !== 'latest'); if (existingPrereleaseTags.length === 0) { existingPrereleaseTags.push('next'); } return existingPrereleaseTags .concat([ new inquirer.Separator(), { name: 'Other (specify)', value: null } ]); }) }, { type: 'input', name: 'tag', message: 'Tag', when: answers => !pkg.private && version.isPrereleaseVersion(answers.version) && !options.tag && !answers.tag, validate: input => { if (input.length === 0) { return 'Please specify a tag, for example, `next`.'; } if (input.toLowerCase() === 'latest') { return 'It\'s not possible to publish pre-releases under the `latest` tag. Please specify something else, for example, `next`.'; } return true; } }, { type: 'confirm', name: 'confirm', message: answers => { const tag = answers.tag || options.tag; const tagPart = tag ? ` and tag this release in npm as ${tag}` : ''; return `Will bump from ${chalk.cyan(oldVersion)} to ${chalk.cyan(answers.version + tagPart)}. Continue?`; } } ]; return printCommitLog(repositoryUrl) .then(hasCommits => { if (!hasCommits) { return inquirer.prompt([{ type: 'confirm', name: 'confirm', message: 'No commits found since previous release, continue?', default: false }]); } }) .then(answers => { if (answers && !answers.confirm) { return answers; } return inquirer.prompt(prompts); }) .then(answers => Object.assign({}, options, answers)); };
JavaScript
0.000322
@@ -1280,57 +1280,43 @@ nst -commitParts = commit.match(/%5E(.+)%5Cs(%5Ba-f%5Cd%5D%7B7%7D)$/ +splitIndex = commit.lastIndexOf(' ' );%0A%09 @@ -1385,16 +1385,33 @@ mmit -Parts%5B1%5D +.substring(0, splitIndex) );%0A%09 @@ -1475,16 +1475,34 @@ mmit -Parts%5B2%5D +.substring(splitIndex + 1) );%0A%0A
107859379e200094b9f4a4d5978b0b305f479a87
Add missing method documentation for ImageOverlay (#5158)
src/layer/ImageOverlay.js
src/layer/ImageOverlay.js
/* * @class ImageOverlay * @aka L.ImageOverlay * @inherits Interactive layer * * Used to load and display a single image over specific bounds of the map. Extends `Layer`. * * @example * * ```js * var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg', * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]]; * L.imageOverlay(imageUrl, imageBounds).addTo(map); * ``` */ L.ImageOverlay = L.Layer.extend({ // @section // @aka ImageOverlay options options: { // @option opacity: Number = 1.0 // The opacity of the image overlay. opacity: 1, // @option alt: String = '' // Text for the `alt` attribute of the image (useful for accessibility). alt: '', // @option interactive: Boolean = false // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered. interactive: false, // @option crossOrigin: Boolean = false // If true, the image will have its crossOrigin attribute set to ''. This is needed if you want to access image pixel data. crossOrigin: false }, initialize: function (url, bounds, options) { // (String, LatLngBounds, Object) this._url = url; this._bounds = L.latLngBounds(bounds); L.setOptions(this, options); }, onAdd: function () { if (!this._image) { this._initImage(); if (this.options.opacity < 1) { this._updateOpacity(); } } if (this.options.interactive) { L.DomUtil.addClass(this._image, 'leaflet-interactive'); this.addInteractiveTarget(this._image); } this.getPane().appendChild(this._image); this._reset(); }, onRemove: function () { L.DomUtil.remove(this._image); if (this.options.interactive) { this.removeInteractiveTarget(this._image); } }, // @method setOpacity(opacity: Number): this // Sets the opacity of the overlay. setOpacity: function (opacity) { this.options.opacity = opacity; if (this._image) { this._updateOpacity(); } return this; }, setStyle: function (styleOpts) { if (styleOpts.opacity) { this.setOpacity(styleOpts.opacity); } return this; }, // @method bringToFront(): this // Brings the layer to the top of all overlays. bringToFront: function () { if (this._map) { L.DomUtil.toFront(this._image); } return this; }, // @method bringToBack(): this // Brings the layer to the bottom of all overlays. bringToBack: function () { if (this._map) { L.DomUtil.toBack(this._image); } return this; }, // @method setUrl(url: String): this // Changes the URL of the image. setUrl: function (url) { this._url = url; if (this._image) { this._image.src = url; } return this; }, setBounds: function (bounds) { this._bounds = bounds; if (this._map) { this._reset(); } return this; }, getEvents: function () { var events = { zoom: this._reset, viewreset: this._reset }; if (this._zoomAnimated) { events.zoomanim = this._animateZoom; } return events; }, getBounds: function () { return this._bounds; }, getElement: function () { return this._image; }, _initImage: function () { var img = this._image = L.DomUtil.create('img', 'leaflet-image-layer ' + (this._zoomAnimated ? 'leaflet-zoom-animated' : '')); img.onselectstart = L.Util.falseFn; img.onmousemove = L.Util.falseFn; img.onload = L.bind(this.fire, this, 'load'); if (this.options.crossOrigin) { img.crossOrigin = ''; } img.src = this._url; img.alt = this.options.alt; }, _animateZoom: function (e) { var scale = this._map.getZoomScale(e.zoom), offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min; L.DomUtil.setTransform(this._image, offset, scale); }, _reset: function () { var image = this._image, bounds = new L.Bounds( this._map.latLngToLayerPoint(this._bounds.getNorthWest()), this._map.latLngToLayerPoint(this._bounds.getSouthEast())), size = bounds.getSize(); L.DomUtil.setPosition(image, bounds.min); image.style.width = size.x + 'px'; image.style.height = size.y + 'px'; }, _updateOpacity: function () { L.DomUtil.setOpacity(this._image, this.options.opacity); } }); // @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options) // Instantiates an image overlay object given the URL of the image and the // geographical bounds it is tied to. L.imageOverlay = function (url, bounds, options) { return new L.ImageOverlay(url, bounds, options); };
JavaScript
0
@@ -2767,24 +2767,128 @@ is;%0D%0A%09%7D,%0D%0A%0D%0A +%09// @method setBounds(bounds: LatLngBounds): this%0D%0A%09// Update the bounds that this ImageOverlay covers%0D%0A %09setBounds: @@ -3213,63 +3213,260 @@ %0A%0D%0A%09 -getBounds: function () %7B%0D%0A%09%09return this._bounds;%0D%0A%09%7D,%0D%0A +// @method getBounds(): LatLngBounds%0D%0A%09// Get the bounds that this ImageOverlay covers%0D%0A%09getBounds: function () %7B%0D%0A%09%09return this._bounds;%0D%0A%09%7D,%0D%0A%0D%0A%09// @method getElement(): HTMLElement%0D%0A%09// Get the img element that represents the ImageOverlay on the map %0D%0A%09g
89e5ca132672819710973338b6fee2fa12af0787
fix multiple mapped test
array/test/mapped.js
array/test/mapped.js
var test = require('tape') var GraphArray = require('../') var Observ = require('observ') var ObservStruct = require('observ-struct') var computed = require('observ/computed') var getTypes = require('../../lib/get-types') test('map nested observ', function (t) { var obs = GraphArray({ getType: getTypes({ Test: function (context) { var obs = ObservStruct({ id: Observ(), value: Observ() }) obs.specialValue = computed([obs], function (data) { return data.id + '-' + data.value }) return obs } }) }) var values = obs.map('specialValue') obs.set([ { type: 'Test', id: '1', value: 'foo' }, { type: 'Test', id: '2', value: 'bar' }, { type: 'Test', id: '3', value: 'baz' } ]) var changes = [] values(function (change) { changes.push(change) }) values.flush() // bypass nextTick t.equal(values.get(0), obs.get(0).specialValue) obs.remove(obs.get(1)) values.flush() t.equal(changes.length, 2) t.deepEqual(changes[0], ['1-foo', '2-bar', '3-baz']) t.deepEqual(changes[1], ['1-foo', '3-baz']) t.end() }) test('map nested observ with function', function (t) { var obs = GraphArray({ getType: getTypes({ Test: function (context) { var obs = ObservStruct({ id: Observ(), value: Observ() }) obs.specialValue = computed([obs], function (data) { return data.id + '-' + data.value }) return obs } }) }) var values = obs.map(function (x) { return x.specialValue }) obs.set([ { type: 'Test', id: '1', value: 'foo' }, { type: 'Test', id: '2', value: 'bar' }, { type: 'Test', id: '3', value: 'baz' } ]) var changes = [] values(function (change) { changes.push(change) }) values.flush() // bypass nextTick t.equal(values.get(0), obs.get(0).specialValue) obs.remove(obs.get(1)) values.flush() t.equal(changes.length, 2) t.deepEqual(changes[0], ['1-foo', '2-bar', '3-baz']) t.deepEqual(changes[1], ['1-foo', '3-baz']) t.end() }) test('multiple maps', function (t) { var values = GraphArray({ getType: function () { return function (context) { return ( ObservStruct({ first: ObservStruct({ second: ObservStruct({ third: Observ() }) }) }) ) } } }) var firstMapped = values.map(function (val) { return val.first }) var secondMapped = firstMapped.map(function (val) { return val.second }) var thirdMapped = secondMapped.map(function (val) { return val.third }) values.set([ { first: { second: { third: 'foo' } } }, { first: { second: { third: 'bar' } } }, { first: { second: { third: 'baz' } } } ]) // bypass nextTick function flush () { ;[ firstMapped, secondMapped, thirdMapped ].forEach(function (x) { x.flush() }) } flush() t.deepEqual(values(), [ { first: { second: { third: 'foo' } } }, { first: { second: { third: 'bar' } } }, { first: { second: { third: 'baz' } } } ]) t.deepEqual(firstMapped(), [ { second: { third: 'foo' } }, { second: { third: 'bar' } }, { second: { third: 'baz' } } ]) t.deepEqual(secondMapped(), [ { third: 'foo' }, { third: 'bar' }, { third: 'baz' } ]) t.deepEqual(thirdMapped(), [ 'foo', 'bar', 'baz' ]) var thirdChanges = [] thirdMapped(function (val) { thirdChanges.push(val) }) values.remove(1) flush() t.deepEqual(values(), [ { first: { second: { third: 'foo' } } }, { first: { second: { third: 'baz' } } } ]) t.deepEqual(firstMapped(), [ { second: { third: 'foo' } }, { second: { third: 'baz' } } ]) t.deepEqual(secondMapped(), [ { third: 'foo' }, { third: 'baz' } ]) t.deepEqual(thirdMapped(), [ 'foo', 'baz' ]) t.deepEqual(thirdChanges, [ ['foo', 'bar', 'baz'], ['foo', 'baz'] ]) t.end() })
JavaScript
0.000422
@@ -2686,24 +2686,112 @@ third%0A %7D)%0A%0A + var thirdChanges = %5B%5D%0A thirdMapped(function (val) %7B%0A thirdChanges.push(val)%0A %7D)%0A%0A values.set @@ -3575,96 +3575,8 @@ %5D)%0A%0A - var thirdChanges = %5B%5D%0A thirdMapped(function (val) %7B%0A thirdChanges.push(val)%0A %7D)%0A%0A va
34669aa9458e06eef13e67c53815ad340646f0cb
fix bug of not being able to find the collection in database
database.js
database.js
var MongoClient = require('mongodb').MongoClient; module.exports = { getConnection: function(address, callback){ return getConnection(address, callback); } }; function getConnection(address, callback){ var connection = MongoClient.connect( address, function(err){ if(err){ callback(err); }else{ callback(null); } } ); }
JavaScript
0
@@ -261,24 +261,28 @@ function(err +, db )%7B%0A%09%09%09if(err @@ -330,16 +330,20 @@ ack(null +, db );%0A%09%09%09%7D%0A
f7f09faac829d881a13add5b74c43bf4bd6673cb
fix moz://a
api/src/models/posts.js
api/src/models/posts.js
module.exports = function(mongoose) { var schema = new mongoose.Schema({ text:String, app:{type:mongoose.Schema.Types.ObjectId,ref:"apps"}, user:{type:mongoose.Schema.Types.ObjectId,ref:"users"}, files:[{type:mongoose.Schema.Types.ObjectId,ref:"files"}], favoriteCount:{type:Number,default:0}, replyTo:{type:mongoose.Schema.Types.ObjectId,ref:"posts"} },{ timestamps:true }) schema.methods.toResponseObject = async function (token) { var obj = this.toObject() obj.id = this._id obj._id = undefined obj.__v = undefined if (this.user.toResponseObject) obj.user=await this.user.toResponseObject(token) else { this.user = await mongoose.model("users").findById(this.user) if (this.user) obj.user = await this.user.toResponseObject(token) } if (this.app && this.app.toResponseObject) { obj.app=await this.app.toResponseObject(token) delete obj.app.appKey delete obj.app.appSecret } if (this.files && this.files.length) { for (let i=0;i<this.files.length;i++) { if (!this.files[i].toResponseObject) { obj.files = [] break } obj.files[i] = await this.files[i].toResponseObject(token) } } if (token) { obj.isFavorited = !!(await mongoose.model("favorites").findOne({user:token.user.id,post:this.id})) } if (this.replyTo && this.replyTo.toResponseObject) obj.replyTo = await this.replyTo.toResponseObject() obj.html = obj.text obj.html = obj.html.split('&').join("&amp;") obj.html = obj.html.split("<").join("&lt;") obj.html = obj.html.split(">").join("&gt;") // obj.html = obj.html.split('"').join("&quot;") obj.html = obj.html.split("\n").join("<br>") obj.html = obj.html.replace(/(^| |\u3000)@([A-Za-z0-9_]+)/g,'$1<a href="/u/$2">@$2</a>') obj.html = obj.html.replace(/(https?:\/\/[a-zA-Z0-9-\.]+(:[0-9]+)?(\/?[a-zA-Z0-9-\._~\!#$&'\(\)\*\+,\/:;=\?@\[\]]*))/g,'<a href="$1" rel="nofollow" target="_blank">$1</a>') obj.html = obj.html.replace(/moz:\/\/a/,'<a href="https://www.mozilla.jp/">moz://a</a>') return obj } return mongoose.model("posts",schema) }
JavaScript
0.000001
@@ -2314,10 +2314,11 @@ lla. -jp +org /%22%3Em
4af7a5da1f7d0701b0bbe6637abaa5b1c3d340bf
Allow onMove callbacks to terminate gestures
gestures.js
gestures.js
(function(){ "use strict"; var html = document.documentElement; var touchEnabled = "ontouchstart" in html; /** Event types */ var START = touchEnabled ? "touchstart" : "mousedown"; var MOVE = touchEnabled ? "touchmove" : "mousemove"; var END = touchEnabled ? "touchend" : "mouseup"; var CANCEL = touchEnabled ? "touchcancel" : null; function Gesture(el, options){ options = options || {}; var THIS = this; var _tracking = false; var startCallback = options.onStart; var moveCallback = options.onMove; var endCallback = options.onEnd; Object.defineProperties(THIS, { /** Whether the gesture's currently being made */ tracking: { get: function(){ return _tracking }, set: function(i){ if((i = !!i) !== _tracking){ _tracking = i; if(i){ html.addEventListener(MOVE, onMove); html.addEventListener(END, onEnd); CANCEL && html.addEventListener(CANCEL, onEnd); window.addEventListener("blur", onEnd); window.addEventListener("contextmenu", onEnd); } else{ html.removeEventListener(MOVE, onMove); html.removeEventListener(END, onEnd); CANCEL && html.removeEventListener(CANCEL, onEnd); window.removeEventListener("blur", onEnd); window.removeEventListener("contextmenu", onEnd); } } } } }); /** * Return the coordinates of an event instance. * * @param {Event} event * @return {Array} */ function getCoords(event){ /** Touch-enabled device */ if(touches = event.touches){ var touches; var length = touches.length; /** Use .changedTouches if .touches is empty (e.g., "touchend" events) */ if(!length){ touches = event.changedTouches; length = touches.length; } var result = []; for(var t, i = 0; i < length; ++i){ t = touches[i]; result.push(t.pageX, t.pageY); } return result; } /** MouseEvent or something similar */ else return [event.pageX, event.pageY]; } function onMove(event){ event.preventDefault(); moveCallback && moveCallback.call(null, getCoords(event), event, THIS); }; function onEnd(event){ THIS.tracking = false; endCallback && endCallback.call(null, getCoords(event), event, THIS); }; el.addEventListener(START, function(event){ /** Don't do anything if the user right-clicked */ if(event.button > 0) return; /** Allow an onStart callback to abort the gesture by returning false */ if(startCallback && false === startCallback.call(null, getCoords(event), event, THIS)) return; THIS.tracking = true; event.preventDefault(); }); } /** Export */ window.Gesture = Gesture; }());
JavaScript
0
@@ -616,24 +616,135 @@ s.onEnd;%0A%09%09%0A +%09%09THIS.onStart = startCallback;%0A%09%09THIS.onMove = moveCallback;%0A%09%09THIS.onEnd = endCallback;%0A%09%09%0A %09%09%0A%09%09Object. @@ -2275,35 +2275,97 @@ %0A%09%09%09 -event.preventDefault(); +%0A%09%09%09/** Allow an onMove callback to abort the entire gesture by returning false */ %0A%09%09%09 +if( move @@ -2375,16 +2375,26 @@ lback && + false === moveCal @@ -2432,32 +2432,104 @@ t), event, THIS) +)%7B%0A%09%09%09%09THIS.tracking = false;%0A%09%09%09%09return;%0A%09%09%09%7D%0A%09%09%09event.preventDefault() ;%0A%09%09%7D;%0A%09%09%0A%09%09func
c450743d9a69892e3534221ce981cd96630fd9ce
check if view exists for attribute changed call back
src/pitana.registerElement.js
src/pitana.registerElement.js
/** * Created by narendra on 15/3/15. */ (function() { "use strict"; pitana.nodeToViewMapping = new pitana.ObjectMap(); pitana.register = function(elementProto) { if (elementProto.initialize === undefined) { elementProto.initialize = function() { pitana.HTMLElement.apply(this, arguments); }; } pitana.registerElement(pitana.HTMLElement.extend(elementProto)); }; pitana.registerElement = function(ViewConstructor) { var ElementPrototype = Object.create(HTMLElement.prototype); ElementPrototype.createdCallback = function() { var view = new ViewConstructor({ ele: this }); pitana.nodeToViewMapping.add(this, view); if (view !==undefined && typeof view.createdCallback === "function") { try{ view.createdCallback.apply(view, arguments); } catch (e){ console.error("pitana:createdCallback:exception",e); } } }; ElementPrototype.attachedCallback = function() { var view = pitana.nodeToViewMapping.get(this); if (view !==undefined && typeof view.attachedCallback === "function") { try{ view.attachedCallback.apply(view, arguments); } catch (e){ console.error("pitana:attachedCallback:exception",e); } } }; ElementPrototype.detachedCallback = function() { var view = pitana.nodeToViewMapping.get(this); if (view !== undefined) { if (typeof view.detachedCallback === "function") { try{ view.detachedCallback.apply(view, arguments); } catch (e){ console.error("pitana:detachedCallback:exception",e); } } view._endModule(); pitana.nodeToViewMapping.remove(this); } }; if (ViewConstructor.prototype.methods !== undefined) { ElementPrototype._commonMethod = function(methodName, args) { var view = pitana.nodeToViewMapping.get(this); var f = view[methodName]; if (typeof f === "function") { return f.apply(view, args); } }; //Append method on EP ViewConstructor.prototype.methods.map(function(methodName, i) { ElementPrototype[methodName] = function() { return ElementPrototype._commonMethod.call(this, methodName, arguments); }; }); } ElementPrototype.attributeChangedCallback = function(attrName) { var view = pitana.nodeToViewMapping.get(this); var mainArgs = arguments; pitana.util.for(view.accessors, function(config, name) { if (name.toLowerCase() === attrName && typeof config.onChange === "string") { view[config.onChange].apply(view, mainArgs); } }); if (typeof view.attributeChangedCallback === "function") { view.attributeChangedCallback.apply(view, arguments); } }; if (ViewConstructor.prototype.accessors !== undefined) { pitana.util.for(ViewConstructor.prototype.accessors, function(attrObj, attrName) { if (attrObj.type === undefined) { attrObj.type = "string"; } var Prop = {}; Prop[attrName] = { get: function() { if (pitana.accessorType[attrObj.type] !== undefined && typeof pitana.accessorType[attrObj.type].get === "function") { return pitana.accessorType[attrObj.type].get.call(this, attrName, attrObj); } }, set: function(newVal) { if (pitana.accessorType[attrObj.type] !== undefined && typeof pitana.accessorType[attrObj.type].set === "function") { pitana.accessorType[attrObj.type].set.call(this, attrName, newVal, attrObj); } } }; Object.defineProperties(ElementPrototype, Prop); }); } if (typeof document.registerElement === "function") { var elementName = ViewConstructor.prototype.tagName.split("-").map(function(v) { return v.charAt(0).toUpperCase() + v.slice(1); }).join("") + "Element"; window[elementName] = document.registerElement(ViewConstructor.prototype.tagName, { extends : ViewConstructor.prototype.extends, prototype: ElementPrototype }); } else { throw "document.registerElement not found, make sure you can included WebComponents Polyfill"; } }; })();
JavaScript
0
@@ -2503,16 +2503,46 @@ uments;%0A + if(view!==undefined)%7B%0A pi @@ -2592,24 +2592,26 @@ ig, name) %7B%0A + if ( @@ -2690,24 +2690,26 @@ %7B%0A + + view%5Bconfig. @@ -2745,26 +2745,30 @@ s);%0A -%7D%0A + %7D%0A %7D);%0A @@ -2767,24 +2767,26 @@ %7D);%0A + + if (typeof v @@ -2824,32 +2824,34 @@ = %22function%22) %7B%0A + view.att @@ -2898,26 +2898,35 @@ nts);%0A + %7D%0A %7D -%0A %0A %7D;%0A%0A
9cf85f2a43d29824f4b1ec572ccfb98718d73a0a
fix tour test
test/spec/lib/test.Tour.js
test/spec/lib/test.Tour.js
import { expect } from 'chai'; import { dialogModes, actionTypes } from '../../../src/assets/constants'; import createDialogs from '../../../src/assets/dialogs'; import defaults from '../../fixtures/default'; import MockUI from '../../mocks/UI'; describe('Tour', function() { var stats = {}, dialogs, Tour, ui; before(() => { Tour = require('../../../src/lib/Tour').default; dialogs = createDialogs(defaults); }); beforeEach(() => { ui = new MockUI(); // stats is defined as an object above so it is passed to the mock UI by reference // its values are then reset before each test stats._showDialog = []; stats._hideDialog = 0; stats.dispatches = []; ui.__set_test_stats(stats); }); afterEach(() => { ui = null; }); it('Should instantiate', function() { var tour = new Tour(ui); expect(tour).to.be.an.instanceof(Tour); }); describe('#intro', function() { it('Should show an intro', function() { ui.__set_showDialog_resolver(function(resolve) { resolve(); }); var tour = new Tour(ui); return tour.intro() .then(() => { expect(ui.__test_stats._showDialog[0].mode).to.equal(dialogModes.GENERAL); expect(ui.__test_stats._showDialog[0].data).to.eql(dialogs.intro); expect(ui.__test_stats._hideDialog).to.equal(1); }); }); }); describe('start', function() { it('Should start the tour', function() { ui.__set_showDialog_resolver(function(resolve) { // pause the tour so only the first dialog is shown resolve({ action: 'pause' }); }); var tour = new Tour(ui); return tour.start() .then(() => { expect(stats._showDialog[0].mode).to.equal(dialogModes.TOUR); expect(stats._showDialog[0].data).to.eql(dialogs.tour[0]); expect(stats._showDialog).to.have.lengthOf(1); }); }); }); describe('_setTourStage', function() { it('Should set the tour stage to 1', function() { var tour = new Tour(ui); tour._setTourStage(1); expect(stats.dispatches[0]).to.eql({ type: actionTypes.SET_TOUR_STAGE, stage: 1 }); }); it('Should only set the tour stage once', function() { var tour = new Tour(ui); tour._setTourStage(1); expect(stats.dispatches).to.have.lengthOf(1); }); }); });
JavaScript
0.000001
@@ -200,16 +200,17 @@ /default +s ';%0Aimpor
89155cb3580b3462107fe93a0d1245b0ed72e201
add oauth2-postmessage-profile project
test/storage/index_test.js
test/storage/index_test.js
goog.require('goog.debug.Console'); goog.require('goog.testing.jsunit'); goog.require('ydn.db.Storage'); var reachedFinalContinuation, basic_schema; var table_name = 't1'; var setUp = function() { var c = new goog.debug.Console(); c.setCapturing(true); //goog.debug.LogManager.getRoot().setLevel(goog.debug.Logger.Level.FINE); //goog.debug.Logger.getLogger('ydn.gdata.MockServer').setLevel(goog.debug.Logger.Level.FINEST); //goog.debug.Logger.getLogger('ydn.db').setLevel(goog.debug.Logger.Level.FINEST); goog.debug.Logger.getLogger('ydn.db.con.IndexedDb').setLevel(goog.debug.Logger.Level.FINEST); goog.debug.Logger.getLogger('ydn.db.IndexedDb').setLevel(goog.debug.Logger.Level.FINEST); //ydn.db.con.IndexedDb.DEBUG = true; //ydn.db.req.IndexedDb.DEBUG = true; basic_schema = new ydn.db.DatabaseSchema(1); basic_schema.addStore(new ydn.db.StoreSchema(table_name, 'id')); }; var tearDown = function() { assertTrue('The final continuation was not reached', reachedFinalContinuation); }; var do_test_multiEntry = function (db_type) { var options = {preference: [db_type]}; var store_name = 'st'; var db_name = 'test_51_multiEntry_2'; var indexSchema = new ydn.db.IndexSchema('tag', ydn.db.DataType.TEXT, false, true); var store_schema = new ydn.db.StoreSchema(store_name, 'id', false, ydn.db.DataType.TEXT, [indexSchema]); var schema = new ydn.db.DatabaseSchema(1, [store_schema]); var db = new ydn.db.Storage(db_name, schema, options); console.log('db ' + db); var objs = [ {id:'qs0', value: 0, tag: ['a', 'b']}, {id:'qs1', value: 1, tag: 'a'}, {id:'at2', value: 2, tag: ['a', 'b']}, {id:'bs1', value: 3, tag: 'b'}, {id:'bs2', value: 4, tag: ['a', 'c', 'd']}, {id:'bs3', value: 5, tag: 'c'}, {id:'st3', value: 6} ]; var tags = ['d', 'b', 'c', 'a', 'e']; var exp_counts = [1, 3, 2, 4, 0]; var counts = []; var total = tags.length; var done = 0; waitForCondition( // Condition function () { return done == total; }, // Continuation function () { for (var i = 0; i < total; i++) { assertEquals(db_type + ' ' + tags[i] + ' count', exp_counts[i], counts[i]); } reachedFinalContinuation = true; }, 100, // interval 1000); // maxTimeout db.put(store_name, objs).addCallback(function (value) { console.log([db + ' receiving put callback.', value]); var count_for = function (tag_name, idx) { var keyRange = ydn.db.KeyRange.only(tag_name); var q = db.query(store_name, 'tag', 'next', keyRange); q.fetch().addBoth(function (value) { console.log(db + ' fetch value: ' + JSON.stringify(value)); counts[idx] = value.length; done++; }); }; for (var i = 0; i < total; i++) { count_for(tags[i], i); } }); }; var test_11_multiEntry_idb = function () { do_test_multiEntry('indexeddb'); }; //var test_51_multiEntry_websql = function () { // do_test_multiEntry('websql'); //}; var testCase = new goog.testing.ContinuationTestCase(); testCase.autoDiscoverTests(); G_testRunner.initialize(testCase);
JavaScript
0
@@ -1794,16 +1794,32 @@ %7D%0A %5D;%0A%0A + goog.scope()%0A%0A var ta @@ -2940,26 +2940,26 @@ %0A//var test_ -5 1 +2 _multiEntry_
7e86ffaaccd9ebef3d42e232ab6719157d13d013
add blurb
test/streaming-resp-err.js
test/streaming-resp-err.js
'use strict'; var setTimeout = require('timers').setTimeout; var allocCluster = require('./lib/alloc-cluster.js'); allocCluster.test('end response with error frame', { numPeers: 2 }, function t(cluster, assert) { var client = cluster.channels[0]; var server = cluster.channels[1]; server.makeSubChannel({ serviceName: 'stream' }).register('stream', { streamed: true }, streamHandler); var req = client.request({ serviceName: 'stream', host: server.hostPort, streamed: true }); req.arg1.end('stream'); req.arg2.end(); req.arg3.end(); req.on('response', onResponse); req.on('error', onError); function onResponse(resp) { assert.ok(resp); resp.on('finish', onResponseFinished); resp.on('error', onResponseError); function onResponseFinished() { assert.ok(false, 'expected no finished event'); } function onResponseError(err) { assert.equal(err.message, 'oops'); assert.end(); } } function onError(err) { assert.ifError(err); assert.ok(false, 'expected no req error event'); } function streamHandler(inreq, buildRes) { var res = buildRes({ streamed: true }); res.arg1.end(); res.arg2.end(); res.arg3.write('a message'); setTimeout(function datTime() { res.sendError('UnexpectedError', 'oops'); }, 500); } });
JavaScript
0
@@ -1,8 +1,1130 @@ +// Copyright (c) 2015 Uber Technologies, Inc.%0A//%0A// Permission is hereby granted, free of charge, to any person obtaining a copy%0A// of this software and associated documentation files (the %22Software%22), to deal%0A// in the Software without restriction, including without limitation the rights%0A// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell%0A// copies of the Software, and to permit persons to whom the Software is%0A// furnished to do so, subject to the following conditions:%0A//%0A// The above copyright notice and this permission notice shall be included in%0A// all copies or substantial portions of the Software.%0A//%0A// THE SOFTWARE IS PROVIDED %22AS IS%22, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR%0A// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,%0A// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE%0A// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER%0A// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,%0A// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN%0A// THE SOFTWARE.%0A%0A 'use str
fb76e1b1cd37fb246469822e7f514278a2782fba
Make sur init.js file is loaded before unit tests
tasks/core/mochaTest.js
tasks/core/mochaTest.js
module.exports = { // Core unit tests core: { options: { reporter: "spec" }, src: ["tests/server/*.js"] } };
JavaScript
0
@@ -101,16 +101,40 @@ src: %5B +%22tests/server/init.js%22, %22tests/s
b2d35de40733a7590eca87451c638fb652d8f46c
Update index.ios.js
index.ios.js
index.ios.js
var frameModule = require("ui/frame"); var Contact = require("./contact-model"); var KnownLabel = require("./known-label"); var CustomCNContactPickerViewControllerDelegate = NSObject.extend({ initWithResolveReject: function(resolve, reject) { var self = this.super.init(); if(self) { this.resolve = resolve; this.reject = reject; } return self; }, contactPickerDidCancel: function(controller){ this.resolve({ data: null, response: "cancelled", ios: null, android: null }); }, contactPickerDidSelectContact: function(controller, contact) { controller.dismissModalViewControllerAnimated(true); //Convert the native contact object var contactModel = new Contact(); contactModel.initializeFromNative(contact); this.resolve({ data: contactModel, response: "selected", ios: contact, android: null }); CFRelease(controller.delegate); } }, { protocols: [CNContactPickerDelegate] }); exports.getContact = function (){ return new Promise(function (resolve, reject) { var controller = CNContactPickerViewController.alloc().init(); var delegate = CustomCNContactPickerViewControllerDelegate.alloc().initWithResolveReject(resolve, reject); CFRetain(delegate); controller.delegate = delegate; var page = frameModule.topmost().ios.controller; page.presentModalViewControllerAnimated(controller, true); }); }; exports.fetchContactsByName = function(searchPredicate){ return new Promise(function (resolve, reject){ var store = new CNContactStore(), error, keysToFetch = [ "givenName", "familyName", "middleName", "namePrefix", "nameSuffix", "phoneticGivenName", "phoneticMiddleName", "phoneticFamilyName", "nickname", "jobTitle", "departmentName", "organizationName", "notes", "phoneNumbers", "emailAddresses", "postalAddresses", "urlAddresses", "imageData", "imageDataAvailable" ], // All Properties that we are using in the Model foundContacts = store.unifiedContactsMatchingPredicateKeysToFetchError(CNContact.predicateForContactsMatchingName(searchPredicate), keysToFetch, error); if(error){ reject(error.localizedDescription); } if (foundContacts.count > 0) { var cts = []; for(var i=0; i<foundContacts.count; i++){ var contactModel = new Contact(); contactModel.initializeFromNative(foundContacts[i]); cts.push(contactModel); } resolve({ data: cts, response: "fetch" }); } else{ resolve({ data: null, response: "fetch" }); } }); }; exports.fetchAllContacts = function(){ return new Promise(function (resolve, reject){ var store = new CNContactStore(), error, keysToFetch = [ "givenName", "familyName", "middleName", "namePrefix", "nameSuffix", "phoneticGivenName", "phoneticMiddleName", "phoneticFamilyName", "nickname", "jobTitle", "departmentName", "organizationName", "notes", "phoneNumbers", "emailAddresses", "postalAddresses", "urlAddresses", "imageData", "imageDataAvailable" ], // All Properties that we are using in the Model fetch = CNContactFetchRequest.alloc().initWithKeysToFetch(keysToFetch), cts = []; fetch.unifyResults = true; fetch.predicate = null; store.enumerateContactsWithFetchRequestErrorUsingBlock(fetch, error, function(c,s){ var contactModel = new Contact(); contactModel.initializeFromNative(c); cts.push(contactModel); }); if(error){ reject(error.localizedDescription); } if(cts.length > 0){ resolve({ data: cts, response: "fetch" }); } else{ resolve({ data: null, response: "fetch" }); } }); }; exports.Contact = Contact; exports.KnownLabel = KnownLabel;
JavaScript
0
@@ -1660,21 +1660,19 @@ exports. -f +g et -ch Contacts
9d27d8f58fa733d123a8fa51cedd31f018d47eee
Add support for {value:json} to json encode values
tasks/generateConfig.js
tasks/generateConfig.js
/* * grunt-generate-config * https://github.com/gmodev/grunt-generate-config * * Copyright (c) 2013 Jason Gill * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { grunt.registerMultiTask('generateConfig', 'A Grunt plugin to generate configs from templates', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ }); var target = this.target; var input = grunt.file.readJSON(options.input); var pattern = /\$(.*)\$/g; options.templates.forEach(function(template) { var templateInput = grunt.file.read(template); var output = templateInput; var match; while (match = pattern.exec(templateInput)) { var replaceMe = match[0]; var parts = match[1].split("|"); var sectionConfigEntry = parts[0].split(":"); var iterator = parts[1]; var section = sectionConfigEntry[0]; var configEntry = sectionConfigEntry[1]; if(input[section] == null) { grunt.fail.fatal("Missing section: '" + section + "' from input: '" + options.input + "'"); } var configEntryValue; if (typeof input[section][configEntry] === "object" && !(input[section][configEntry] instanceof Array) ) { if(input[section][configEntry][target] == null) { grunt.fail.fatal("Missing section: '" + section + "' config entry: '" + configEntry + "' target: '" + target + "' from input: '" + options.input + "'"); } configEntryValue = input[section][configEntry][target]; } else { if(input[section][configEntry] == null) { grunt.fail.fatal("Missing section: '" + section + "' config entry: '" + configEntry + "' from input: '" + options.input + "'"); } configEntryValue = input[section][configEntry]; } var replaceWith = ""; if (iterator !== undefined) { for( var i = 0; i < configEntryValue.length; i++) { var value = configEntryValue[i]; var temp = replaceWith + iterator.replace("{value}", value); var j = i + 1; if( j === configEntryValue.length ) { temp = temp.replace("{newline}", ""); temp = temp.replace("{comma}", ""); } else { temp = temp.replace("{newline}", "\n"); temp = temp.replace("{comma}", ","); } replaceWith = temp; } } else { replaceWith = configEntryValue; } output = output.replace(replaceMe, replaceWith); } var configFile = template.replace(".template", ""); grunt.log.writeln("Generating config: " + configFile); grunt.file.write(configFile, output); }); }); };
JavaScript
0.00018
@@ -2004,16 +2004,82 @@ value); +%0A%09%09%09%09%09%09temp = temp.replace(%22%7Bvalue:json%7D%22, JSON.stringify(value)); %0A%0A%09%09%09%09%09%09
fc2fb7302bf1f827545352c1fc8261098208bdd2
use our fork to generate packager URLs
index.ios.js
index.ios.js
/** * React Native Playground * https://github.com/jsierles/rnplay */ 'use strict'; var React = require('react-native'); var qs = require('qs'); var LinkingIOS = require('LinkingIOS'); var AppReloader = require('NativeModules').AppReloader; var Login = require('./App/Screens/Login'); var Signup = require('./App/Screens/Signup'); var Home = require('./App/Screens/Home'); var Guest = require('./App/Screens/Guest'); var ProfileStore = require('./App/Stores/ProfileStore'); var LocalStorage = require('./App/Stores/LocalStorage'); var _ = require('lodash'); var { AppRegistry, Navigator, StyleSheet, Text, View, StatusBarIOS } = React; // globals are bad, we make an exception here for now var RN_VERSION = require('./package.json').dependencies['react-native']; var githubPrefix = 'facebook/react-native#'; if (RN_VERSION.indexOf(githubPrefix) === 0) { RN_VERSION = RN_VERSION.replace(githubPrefix, ''); } else { RN_VERSION = RN_VERSION.replace(/\./g,'').replace(/-/g, '') } global.RN_VERSION = RN_VERSION; var RNPlayNative = React.createClass({ getInitialState() { return { bootstrapped: false }; }, componentDidMount() { StatusBarIOS.setStyle(StatusBarIOS.Style.lightContent); LocalStorage.bootstrap(() => this.setState({bootstrapped: true})); LinkingIOS.addEventListener('url', this._processURL); var url = LinkingIOS.popInitialURL(); if (url) { this._processURL({url}); } }, componentWillUnmount() { LinkingIOS.removeEventListener('url', this._processURL); }, _processURL(e) { var url = e.url.replace('rnplay://', ''); var {bundle_url, module_name} = qs.parse(url); if (bundle_url && module_name) { AppReloader.reloadAppWithURLString(bundle_url, module_name); } }, render() { if (this.state.bootstrapped === false) { return <View />; } return <Home />; } }); AppRegistry.registerComponent('RNPlayNative', () => RNPlayNative);
JavaScript
0
@@ -799,16 +799,14 @@ = ' -facebook +rnplay /rea
cfee1c3600c55812319821343214d83777d534fb
use request animtion frame
index.ios.js
index.ios.js
/** * Sample React Native App * https://github.com/facebook/react-native */ 'use strict'; var React = require('react-native'); //var Sample=require("./src/index.js"); const { Surface } = require("gl-react-native"); const GL = require("gl-react"); const forth2gl=require("./forth2gl"); var { AppRegistry, Image, ListView, StyleSheet, Text, TextInput, View, ScrollView, PixelRatio, TouchableHighlight, Dimensions, } = React; var shader; var frag=`precision highp float; varying vec2 uv; uniform float time_val; void main () { gl_FragColor = vec4(uv.x, uv.y,time_val,1.0); } ` var width=Dimensions.get('window').width; var height=Dimensions.get('window').height; var GetTime=function() { var dt = new Date(); var tm = dt.getHours(); tm = tm * 60 + dt.getMinutes(); tm = tm * 60 + dt.getSeconds(); tm = tm + dt.getMilliseconds() / 1000.0; return tm; } var forthhaiku = React.createClass({ getInitialState:function(){ return {frag:frag,forthcode:'x t sin .5 * .5 +',time_val:0} } ,onChangeForth:function(forthcode) { this.setState({forthcode:forthcode}) } ,onChangeFrag:function(text){ this.setState({frag:text}); } ,updatefrag:function(){ var frag=forth2gl.transpile(this.state.forthcode); shader=GL.Shaders.create({Haiku:{frag:frag}}); this.forceUpdate(); } ,componentWillUnmount:function(){ clearInterval(this.timer); } ,componentDidMount:function() { this.timer=setInterval(function(){ this.setState({time_val:GetTime()}); }.bind(this),5); } ,componentWillMount:function(){ shader=GL.Shaders.create({Haiku:{frag:frag}}) } ,render: function() { return <View style={{flex:1}}> <View style={{height:20}}/> <View style={{paddingLeft:width*0.075}}> <Surface width={width*0.85} height={width*0.85} ref="helloGL"> <GL.Node shader={shader.Haiku} uniforms={{time_val:this.state.time_val}} /> </Surface> </View> <View style={{flexDirection:'row'}}> <TouchableHighlight underlayColor='white' activeOpacity={0.5} style={styles.runhighlight} onPress={this.updatefrag}> <Text style={styles.runbutton}>Run</Text></TouchableHighlight> <Text>Name:</Text> <TextInput ref="name" style={{width:160,height:25,borderColor:'black', borderWidth:(1/PixelRatio.get())}}/> </View> <ScrollView styles={{flex:1}}> <TextInput ref="forthcode" multiline={true} style={{fontSize:16,height:240,borderColor:'gray',borderWidth:(1/PixelRatio.get())}} onChangeText={this.onChangeForth} value={this.state.forthcode}/> <TextInput ref="frag" multiline={true} style={{fontSize:16,height:120,borderColor:'gray',borderWidth:1}} onChangeText={this.onChangeFrag} value={this.state.frag}/> </ScrollView> </View> } }); var styles = StyleSheet.create({ runhighlight:{shadowRadius:5}, runbutton:{textAlign:'center',textShadowRadius:10,fontSize:18, textShadowColor:'black',borderWidth:1,height:25*PixelRatio.get(),borderRadius:5,width:150} }); AppRegistry.registerComponent('forthhaiku', () => forthhaiku);
JavaScript
0
@@ -1358,15 +1358,12 @@ nent -WillUnm +DidM ount @@ -1382,33 +1382,39 @@ %0A - clearInterval +requestAnimationFrame (this. -timer +step );%0A @@ -1419,33 +1419,20 @@ %0A %7D%0A , -componentDidMount +step :functio @@ -1430,25 +1430,24 @@ p:function() - %7B%0A this.t @@ -1449,81 +1449,91 @@ his. -timer=setInterval(function()%7B%0A this.setState(%7Btime_val:GetTime()%7D +setState(%7Btime_val:GetTime()%7D,function()%7B%0A requestAnimationFrame(this.step ); - %0A @@ -1549,12 +1549,15 @@ his) -,5 ); +%0A %0A %7D
974c9f4eace142a6ae6c85cc75f248e4631c4547
fix timestamps.
possel/data/static/main.js
possel/data/static/main.js
"use strict"; var possel = { get_users: function(id){ return $.get("/user/" + id); }, events: { submit_event: function(node) { $(node).submit(function(event) { event.preventDefault(); var message = $('#message-input').val(); var buffer_id = $('.buffer.active')[0].id; possel.send_line(buffer_id, message).then(function(){ $('#message-input').val(''); }); }); } }, get_buffer: function(id){ return $.get("/buffer/" + id); }, get_line_by_id: function(id){ return $.get("/line?id=" + id); }, get_last_line: function(){ return $.get("/line?last=true"); }, send_line: function(buffer, content){ return $.ajax({ type: 'POST', url: '/line', data: JSON.stringify({ buffer: buffer, content: content }), contentType: 'application/json' }); } }; var util = { node: function(elem, val, attrs) { var element = $("<" + elem + ">"); if (val instanceof Array) { for(var i in val) { element.append(val[i]); } } else { element.html(val); } if (attrs !== undefined) { var keys = Object.keys(attrs); for(var a in keys) { element.attr(keys[a], attrs[keys[a]]); } } return element; } } $(function(){ var users = [], buffers = []; function new_line(line){ var buffer = buffers[line.buffer], user = users[line.user]; $("#" + buffer.id).append( util.node("div", [util.node("span", user.nick, { class: "nick column mid-column" }) , util.node("span", line.content, { class: "message column mid-column" })], { class: "buffer-line" })); } function buffer_maker(){ var first = true; var inner_func = function(buffer){ buffers[buffer.id] = buffer; var active_class = first?' active':''; first = false; $("#bufferlist").append( util.node("li", util.node("a", buffer.name, { href: "#" + buffer.id, role: "tab", "data-toggle": "tab", "aria-controls": buffer.id }), { role: "presentation", class: active_class } ) ); $("#message-pane").append( util.node("div", null, { id: buffer.id, class: "buffer tab-pane " + active_class, role: "tabpanel" })); } return inner_func; } var new_buffer = buffer_maker(); function prepopulate_lines(last_line_data, nlines){ if (last_line_data.length == 0) { console.warn("no lines found."); return 0; } var last_line = last_line_data[0]; $.get("/line?after=" + (last_line.id - nlines)).then(function(lines){ lines.forEach(function(line){ new_line(line); }); }); } function handle_push(event){ var msg = JSON.parse(event.data); console.log(msg); switch(msg.type){ case "line": possel.get_line_by_id(msg.line).then(function(data) { var line = data[0]; new_line(line); }); break; case "buffer": possel.get_buffer(msg.buffer).then(function(buffer_data){ new_buffer(buffer_data[0]); }); break; case "user": get_user(msg.user).then(function(user_data){ var user = user_data[0]; users[user.id] = user; }); } } possel.events.submit_event('#message-input-form'); $.when(possel.get_users("all"), possel.get_buffer("all"), possel.get_last_line() ) .done(function(user_data, buffer_data, last_line_data){ user_data[0].forEach(function(user){ users[user.id] = user; }); buffer_data[0].forEach(function(buffer) { new_buffer(buffer); }); var ws = new ReconnectingWebSocket(ws_url); ws.onopen = function() { console.log("connected"); }; ws.onclose = function() { console.log("disconnected"); }; ws.onmessage = handle_push; prepopulate_lines(last_line_data[0], 30); }); });
JavaScript
0.000039
@@ -1538,32 +1538,80 @@ v%22,%0A + %5Bmoment(line.timestamp).format(%22hh:mm:ss%22),%0A %5Butil @@ -1605,17 +1605,22 @@ -%5B + util.nod @@ -1638,30 +1638,24 @@ ser.nick, %7B%0A - @@ -1714,23 +1714,11 @@ - - %7D)%0A +%7D)%0A @@ -1777,38 +1777,32 @@ - class: %22message @@ -1812,38 +1812,32 @@ umn mid-column%22%0A -
8e16fc365057a2b5cca0b0f46041f4f1d26109a7
fix init i18n
assets/i18n/index.js
assets/i18n/index.js
import i18next from "i18next"; import resBundle from "i18next-resource-store-loader!./locales"; import LanguageDetector from "i18next-browser-languagedetector"; i18next .use(LanguageDetector) .init({ resources: resBundle }); export default i18next;
JavaScript
0.002273
@@ -231,16 +231,84 @@ esBundle +,%0A whitelist: %5B%22zh%22, %22en%22, %22ja%22%5D,%0A fallbackLng: %22zh%22 %0A %7D);
02e79bbabfd5c9875e3a426cc827d43bcf653854
Fix a ESDoc
src/lib/cross-conf-env.js
src/lib/cross-conf-env.js
import Spawn from 'cross-spawn'; /** * Select the key of the value to be replaced from "process.env". * * @return {Array.<String>} Keys. */ export function FilterKeys() { return Object .keys( process.env ) .filter( ( key ) => { return ( key && typeof key === 'string' && ( key.indexOf( 'npm_package_' ) !== -1 || key.indexOf( 'npm_config_' ) !== -1 ) ); } ) .sort( ( a, b ) => { // Processing the variables with the same prefix in the correct order. // "npm_package_config_NAME_NAME2" contained in "npm_package_config_NAME" // is in descending order by the length to prevent from being replace earlier. // return ( b.length - a.length ); } ); } /** * Replace the arguments in the value of "process.env". * * @param {Array.<Object>} argv Arguments of the command line. * @param {Array.<Object>} argv The filtered key ( "npm_package_" or "npm_config_" ) of "process.env". * * @return {Array.<String>} Augments. */ export function ReplaceArgv( argv, keys ) { if( keys.length === 0 ) { return argv; } return argv.map( ( arg ) => { let newArg = arg; keys.forEach( ( key ) => { const pettern = '%' + key + '%|\\$' + key + '|' + key; const regexp = new RegExp( pettern ); if( regexp.test( newArg ) ) { newArg = newArg.replace( regexp, String( process.env[ key ] ) ); } } ); return newArg; } ); } /** * Replace the value of the command line arguments in process.env, * and run the process with a replaced arguments. * * @param {Array.<Object>} argv Arguments of the command line. * * @return {Object} Process. */ export default function CrossConfEnv( argv ) { const newArgv = ReplaceArgv( argv, FilterKeys() ); if( !( newArgv && 0 < newArgv.length ) ) { return process.exit(); } const command = newArgv.shift(); const proc = Spawn( command, newArgv, { stdio: 'inherit' } ); proc.on( 'exit', process.exit ); return proc; }
JavaScript
0.999957
@@ -849,20 +849,20 @@ bject%3E%7D -argv +keys The fil
20f1c51904048d788b3a62e7f8de9f4662c3cc25
Use lodash's debounce instead of tying it to Ember's runloop
addon/components/license-picker/component.js
addon/components/license-picker/component.js
import Ember from 'ember'; import layout from './template'; export default Ember.Component.extend({ layout, store: Ember.inject.service(), licensesAvailable: Ember.A(), showBorder: true, showYear: true, showText: false, toggleText: true, showCopyrightHolders: true, showCategories: true, allowDismiss: false, showOtherFields: Ember.observer('nodeLicense', 'nodeLicense.text', function() { let text = this.get('nodeLicense.text'); if (!text) { return; } this.set('showYear', text.indexOf('{{year}}') !== -1); this.set('showCopyrightHolders', text.indexOf('{{copyrightHolders}}') !== -1); }), yearRequired: Ember.computed('nodeLicense', function() { return this.get('nodeLicense.requiredFields') && this.get('nodeLicense.requiredFields').indexOf('year') !== -1; }), copyrightHoldersRequired: Ember.computed('nodeLicense', function() { return this.get('nodeLicense.requiredFields') && this.get('nodeLicense.requiredFields').indexOf('copyrightHolders') !== -1; }), didReceiveAttrs() { if (!this.get('licenses')) { this.get('store').query('license', { 'page[size]': 20 }).then(ret => { this.set('licensesAvailable', ret); }); } else { this.set('licensesAvailable', this.get('licenses')); } if (!this.get('currentValues.year')) { let date = new Date(); this.set('year', String(date.getUTCFullYear())); } else { this.set('year', this.get('currentValues.year')); } if (this.get('currentValues.copyrightHolders')) { this.set('copyrightHolders', this.get('currentValues.copyrightHolders')); } }, _setNodeLicense: Ember.observer('licensesAvailable', 'currentValues.licenseType', function() { if (!this.get('currentValues.licenseType.id')) { //if not resolved properly this.set('nodeLicense', this.get('licensesAvailable.firstObject')); } else { this.set('nodeLicense', this.get('currentValues.licenseType')); } }), nodeLicenseText: Ember.computed('nodeLicense', 'nodeLicense.text', 'year', 'copyrightHolders', function() { let text = this.get('nodeLicense.text'); if (text) { text = text.replace(/({{year}})/g, this.get('year') || ''); text = text.replace(/({{copyrightHolders}})/g, this.get('copyrightHolders') || ''); } return text; }), licenseEdited: Ember.observer('copyrightHolders', 'nodeLicense', 'year', function() { Ember.run.debounce(this, function() { if (this.get('autosave')) { this.get('actions.save').bind(this)(); } }, 250); }), year: null, copyrightHolders: null, actions: { selectLicense(license) { this.set('nodeLicense', license); }, toggleFullText() { this.set('showText', !this.get('showText')); }, save() { let values = { licenseType: this.get('nodeLicense'), year: this.get('year'), copyrightHolders: this.get('copyrightHolders') ? this.get('copyrightHolders') : '' }; this.attrs.editLicense( values, !((this.get('yearRequired') && !values.year) || (this.get('copyrightHoldersRequired') && values.copyrightHolders.length === 0)) ); }, sendSubmit() { this.sendAction('pressSubmit'); }, dismiss() { this.attrs.dismiss(); } } });
JavaScript
0
@@ -20,16 +20,47 @@ ember';%0A +import _ from 'lodash/lodash';%0A import l @@ -370,24 +370,450 @@ iss: false,%0A + init() %7B%0A this._super(...arguments);%0A // Debouncing autosave prevents a request per keystroke, only sending it%0A // when the user is done typing (trailing=true), debounce timer can be tweaked.%0A this.set('debouncedAutosave', _.debounce(() =%3E %7B%0A if (this.get('autosave')) %7B%0A this.get('actions.save').bind(this)();%0A %7D%0A %7D, 500, %7Btrailing: true%7D));%0A %7D,%0A showOthe @@ -3105,169 +3105,38 @@ -Ember.run.debounce(this, function() %7B%0A if (this.get('autosave')) %7B%0A this.get('actions.save').bind(this)();%0A %7D%0A %7D, 250 +this.get('debouncedAutosave')( );%0A
a68b1413939c765d98a215067be895e7b98d9c86
Debug artist insert 3
assets/js/analyze.js
assets/js/analyze.js
/** * Main module for analyze view * @param {type} $ jQuery module * @param {type} facebook Facebook Graph API module * @param {type} LastFMProxy LastFM API Wrapper module * @param {type} Aggregate Custom aggregation methods module * @returns {void} */ define (['jquery', 'facebook', 'LastFMProxy', 'StatsAnalyzer'], function ($, facebook, LastFMProxy, StatsAnalyzer) { // Stats object for every artist (associative array) var artistStats = []; // Number of artists liked by the user var artistCount = 0; // Number of artist already analyzed var analyzedArtistCount = 0; /** * Try to login and get an array of musicians * @param {type} callback * @returns {undefined} */ function getArtists(callback) { FB.init({ appId : '1468034890110746', xfbml : true, status : true, cookie : true, version : 'v2.1' }); // Try to login after init is complete FB.getLoginStatus(function(response){ FB.login(function () { FB.api( "/me/music?fields=likes,id,name, category", function (response) { var likes = response.data || []; var artists = []; // Filter by category likes.forEach(function (like) { if(like.category === "Musician/band") { artists.push(like); } }); callback(artists); }); }, {scope: 'user_likes'}); }); } /** * Show the modal window with a given text * @param {type} title Window title to show * @param {type} text Text to show * @param {function} callback * @returns {undefined} */ function showModal (title, text, callback) { $('#modalTitle').text(title); $('#modalText').text(text); $('#myModal').modal('show'); if (callback) { $('#modalOk').click(callback); $('#modalClose').click(callback); } } /** * Update progress bar as analyzedArtistCound increases * @returns {undefined} */ function updateProgress () { analyzedArtistCount++; var percent = analyzedArtistCount / artistCount; var progress = percent*100; $('#appProgress').css('width', progress + '%'); } /** * * @param {type} artist * @returns {undefined} */ function artistCallback (artist) { var initialStatus = $('#initial-status').val(); $('#status').text(initialStatus + ' ' + artist + '...'); } function albumCallback (artist) { var initialStatus = $('#initial-status-album').val(); $('#status').text(initialStatus + ' ' + artist + '...'); } function fanCallback (artist) { var initialStatus = $('#initial-status-fan').val(); $('#status').text(initialStatus + ' ' + artist + '...'); } function tagCallback (artist) { var initialStatus = $('#initial-status-tag').val(); $('#status').text(initialStatus + ' ' + artist + '...'); } function similarCallback (artist) { var initialStatus = $('#initial-status-similar').val(); $('#status').text(initialStatus + ' ' + artist + '...'); } // Get stats one by one recursively and call a callback when finished function getStats (artists, callback) { // Race end: empty array if (artists.length === 0) { callback(); return; } // Pop an artist from array var artist = artists.pop(); // Get stats for the popped artist and then continue console.log("id del artista:" + artist.id); LastFMProxy.getStats(artist.id, artist.name, artistCallback, albumCallback, fanCallback, tagCallback, similarCallback, function (stats) { updateProgress(); artistStats[artist.name] = JSON.parse(stats); getStats(artists, callback); }); } function showResults() { // Analyze the stats StatsAnalyzer.build(artistStats); // Get the results text var ageText = StatsAnalyzer.getAgeText(); var epochText = StatsAnalyzer.getEpochText(); var styleText = StatsAnalyzer.getStyleText(); var similarText = StatsAnalyzer.getSimilarText(); // Print the resutls $('#age_result').text(ageText); $('#epoch_result').text(epochText); $('#style_result').text(styleText); $('#similar_result').text(similarText); // Add sharing event handlers shareResult('prueba'); $('#share_age').click(function () { shareResult(ageText); }); $('#share_epoch').click(function () { shareResult(epochText); }); $('#share_style').click(function () { shareResult(styleText); }); $('#share_similar').click(function () { shareResult(similarText); }); $('#process').hide(); $('#results').removeClass('hidden'); $('#results').animate({ maxHeight: '1000px', opacity:1 },{ duration: 1000 }); } function selectTopRated (artists, n) { // Sort from more to less likes artists.sort(function (a, b) { return b.likes - a.likes; }); return artists.splice(0,n); } function shareResult (message) { var wallPost = { method: 'feed', picture: $('#share-image').val(), link: 'https://apps.facebook.com/music-analyzer', name: message, caption: "music-analyzer.herokuapp.com", description: $('#description').val() }; FB.ui(wallPost); /* FB.login(function(loginResponse) { if (!loginResponse || loginResponse.error) { // No permission console.log('Login error'); } else { FB.api('/me/feed', 'post', wallPost , function(response) { if (!response || response.error) { console.log('Hubo un error'); console.log(response); } else { console.log('Posteado correctamente'); } }); } }, {scope: 'publish_actions'}); */ } // DOM callbacks $(document).ready(function () { // Get user artists getArtists(function (artists) { var MAX_ARTISTS = 10; // If no artist likes show message if (artists.length === 0) { showModal($('#error-title').val(), $('#error-status').val(), function () { document.location = '/'; }); } // If too much musicians if (artists.length > MAX_ARTISTS) { artists = selectTopRated(artists, MAX_ARTISTS); } artistCount = artists.length || 0; // Else get stats one by one getStats(artists, function () { showResults(); }); }); // Get user artists }); // End document ready }); // End module
JavaScript
0
@@ -6156,25 +6156,16 @@ %7D;%0A - %0A @@ -6185,647 +6185,8 @@ t);%0A - /*%0A FB.login(function(loginResponse) %7B%0A if (!loginResponse %7C%7C loginResponse.error) %7B%0A // No permission%0A console.log('Login error');%0A %7D else %7B%0A FB.api('/me/feed', 'post', wallPost , function(response) %7B%0A if (!response %7C%7C response.error) %7B%0A console.log('Hubo un error');%0A console.log(response);%0A %7D else %7B%0A console.log('Posteado correctamente');%0A %7D%0A %7D);%0A %7D%0A %7D, %7Bscope: 'publish_actions'%7D);%0A */%0A @@ -6638,32 +6638,32 @@ %0A %7D%0A - // I @@ -6678,24 +6678,66 @@ ch musicians + select the top 10 sorting by likes count %0A
f36ec2b0f33ff5864166459ca14940d88c5b9cba
Remove unnecessary call to angular.extend.
intersect.js
intersect.js
(function (root, factory) { if (typeof define === 'function' && define.amd) { define(['exports', 'angular'], factory); } else if (typeof exports === 'object') { factory(exports, require('angular')); } else { factory((root.commonJsStrict = {}), root.angular); } }(this, function (intersect, angular) { var root = this, extendInjection = function (module, attribute) { var original = module[attribute]; return (function (name, dependencies, fn) { if (typeof fn === 'function' && angular.isArray(dependencies)) { dependencies = angular.copy(dependencies); dependencies.push(fn); } return original.call(module, name, dependencies); }); }, getWrappedComponent = function (module) { return angular.extend({}, module, { provider: extendInjection(module, 'provider'), factory: extendInjection(module, 'factory'), service: extendInjection(module, 'service'), value: extendInjection(module, 'value'), constant: extendInjection(module, 'constant'), directive: extendInjection(module, 'directive'), }); }; angular.extend(intersect, angular); angular.extend(intersect, { module: function () { var module = angular.extend({}, angular.module.apply(angular, arguments)); return getWrappedComponent(module); }, conflict: function (providedRoot) { if (typeof providedRoot === 'undefined') { providedRoot = root; } root.angular = intersect; } }); return intersect; }));
JavaScript
0
@@ -1211,37 +1211,8 @@ ular -);%0A angular.extend(intersect , %7B%0A
51aed4ae977a18afdb48331a01511ff13966d6d6
Update countdown for bag day
assets/js/checkin.js
assets/js/checkin.js
$(document).ready(function(){ $('#studentid').focus(); var timeout; var l; var working = false; handleresponse = function (msg) { console.log(msg); l.stop(); working = false; $('#studentid').val('').focus(); var level='danger'; var title='Uh-Oh...'; var description='There may be a problem with your account. Please contact an administrator if this keeps happening.'; if(msg.code=="checkin"){ level='success'; title=msg.name+','; description='you are now checked in. Don\'t forget to check out when the meeting is over!'; } if(msg.code=="checkout"){ level='success'; title=msg.name+','; description='you have checked out. You now have '+msg.hours+' hours.'; } if(msg.code=="exceed"){ level='warning'; description='You\'ve been checked in too long! Hours from the last session will not be counted. Input again if you need to be checked in.'; } if(msg.code=="false"){ description='The entered ID is either too short or too nonexistant.'; } $('#alertbox').html('<div class="alert alert-'+level+'" style="margin-top: -7px;"><strong>'+title+'</strong> '+description+'</div>'); $('#alertbox').fadeIn(200); timeout=setTimeout(function(){$('#alertbox').fadeOut(100);},3000); } $('#checkin').click(function () { if(!working){ l = Ladda.create(this); l.start(); working = true; clearTimeout(timeout); $('#alertbox').fadeOut(100); var studentid=$('#studentid').val(); $.ajax({ type: "GET", url: '?p=json&r=checkin&d='+studentid }).done(handleresponse).fail(function(){console.log('Something has gone very wrong')}); } }); $("#studentid").keyup(function(event){ if(event.keyCode == 13){ $("#checkin").click(); } }); var timer = countdown(new Date(2019, 0, 5, 9, 0, 0, 0), function(ts) { document.getElementById('clock').innerHTML = ts.toString(); }, countdown.DAYS | countdown.HOURS | countdown.MINUTES | countdown.SECONDS); });
JavaScript
0
@@ -2106,18 +2106,21 @@ 19, -0, 5, 9, 0 +1, 19, 22, 59 , 0,
7e3982a9631220c4cb0f656aa974f1a376795350
Disable gallery effect on small screens
assets/js/gallery.js
assets/js/gallery.js
(function() { var RESET_INTERVAL = 3000; var IMG_DIR = '/assets/img/team/'; var IMG_FORMAT = '.jpg'; var portrait = 'portrait'; var background = 'background'; var thumbnail = 'thumbnail'; var thumbBg = 'thumbnail-background'; var allToggleButtons = document.querySelectorAll('[data-fx="toggle-button"] input'); var teamProfiles = document.querySelectorAll('[data-fx="profile"]'); var allNestedLinks = document.querySelectorAll('[data-info="nested-link"]'); // TODO List // 1. Do something about mobile. Reduce functionality so as not // to overload it. var inactivityTime = function () { var time; window.onload = resetTimer; document.onmousemove = resetTimer; document.onlick = resetTimer; document.onchange = resetTimer; document.onkeypress = resetTimer; function resetTimer() { clearTimeout(time); time = setTimeout(removeExpand, RESET_INTERVAL); } }; var toggleClass = function(e, c) { (e).classList.toggle(c) }; var setBackground = function(targetProfile, imgType) { var slug = targetProfile.getAttribute('data-slug'); var imgPath = `${IMG_DIR}${imgType}/${slug}${IMG_FORMAT}`; targetProfile.style.backgroundImage = `url(${imgPath})`; }; var setThumbnailSrc = function(targetProfile, thumbnailType) { var slug = targetProfile.getAttribute('data-slug'); var thumbnail = targetProfile.querySelector('[data-fx="thumbnail-photo"]'); var srcPath = `${IMG_DIR}${thumbnailType}/${slug}${IMG_FORMAT}`; thumbnail.src = srcPath; }; var removeExpand = function() { teamProfiles.forEach(function(profile) { profile.classList.remove('fx-expand'); setThumbnailSrc(profile, thumbnail); }); }; var preventLinkBubble = function() { allNestedLinks.forEach(function(nestedLink) { nestedLink.addEventListener('click', function(event) { event.stopPropagation(); }); }); }; var toggleMemberBackground = function() { allToggleButtons.forEach(function(tgBtn) { tgBtn.addEventListener('change', function() { var parentProfile = this.closest('[data-fx="profile"]') if (this.checked) { setBackground(parentProfile, background); setThumbnailSrc(parentProfile, thumbnail); } else { setBackground(parentProfile, portrait); setThumbnailSrc(parentProfile, thumbBg); } }); }); }; var expandProfile = function() { teamProfiles.forEach(function(profile) { profile.addEventListener('click', function() { removeExpand(); setBackground(profile, portrait); setThumbnailSrc(profile, thumbBg); toggleClass(this, 'fx-expand'); }) }); }; var init = function() { preventLinkBubble(); expandProfile(); toggleMemberBackground(); }; window.onload = function() { inactivityTime(); init(); } })();
JavaScript
0
@@ -231,24 +231,68 @@ ckground';%0A%0A + var screenResolution = window.innerWidth;%0A var allTog @@ -2918,24 +2918,62 @@ unction() %7B%0A + if (screenResolution %3E= 1024) %7B%0A inactivi @@ -2990,16 +2990,18 @@ + init();%0A %7D%0A @@ -2996,16 +2996,22 @@ init();%0A + %7D%0A %7D%0A%7D)()
33573af3b0dfdd5713e99fa6605880d2d414ed22
fix camelcase property names
src/lib/ui/main-window.js
src/lib/ui/main-window.js
'use strict' // var uiHelpers = require('./helpers') var uiComponents = require('./components') var eventHandlers = require('../event-handlers') module.exports = { openMainWinFunction: openMainWinFunction } /** * Make the openMainWin function as a closure * @method * @param {Editor} editor The tinymce active editor instance * @returns {function} openMainWin The openMainWin closure function */ function openMainWinFunction (editor) { return openMainWin /** * Open the main paragraph properties window * @function * @inner * @returns {undefined} */ function openMainWin () { var generalTab = uiComponents.createGeneralTab() var spacingsTab = uiComponents.createSpacingTab() var bordersTab = uiComponents.createBordersTab(editor) var paragraph = editor.dom.getParent(editor.selection.getStart(), 'p') // console.log('paragraph',paragraph) editor.windowManager.open({ bodyType: 'tabpanel', title: 'Paragraph properties', body: [ generalTab, spacingsTab, bordersTab ], data: { indent: editor.dom.getStyle(paragraph, 'text-indent'), linespacing: editor.dom.getStyle(paragraph, 'line-height'), padding: editor.dom.getStyle(paragraph, 'padding'), margin: editor.dom.getStyle(paragraph, 'margin'), borderwidth: editor.dom.getStyle(paragraph, 'border-width'), bordercolor: editor.dom.getStyle(paragraph, 'border-color') }, onsubmit: eventHandlers.processAllChangesOnMainWinSubmit(editor, paragraph) }) } }
JavaScript
0.000032
@@ -1124,17 +1124,17 @@ line -s +S pacing: @@ -1312,17 +1312,86 @@ border -w +Style: editor.dom.getStyle(paragraph, 'border-style'),%0A borderW idth: ed @@ -1450,17 +1450,17 @@ border -c +C olor: ed
dbb2f802d1ef7d401d39e5df30cdfab922a34702
Change game duration
source/src/Index.js
source/src/Index.js
import $ from 'jquery'; let TIMER_COUNT = 3; let GAME_TIME = 10; let score = 0; let chillLifetime = 1200; $(document).ready(function () { // change to deviceready after cordova integration $('#playNow').click(startGame); $('#home').click(showHome); }); function startGame() { showCounter(TIMER_COUNT).done(initGameScreen); } function showCounter(total) { $('.screen.active').removeClass('active'); $('#counter').addClass('active'); let defer = $.Deferred(), i = total; $('#counter #count').html(`[${i}]`); let interval = setInterval(() => { i--; if (i > 0) { $('#counter #count').html(`[${i}]`); } else if (i === 0) { $('#counter #count').html('[CHILL]'); } else if (i < 0) { defer.resolve(); clearInterval(interval) } },1000); return defer; } function initGameTimer() { let timeRemaining = GAME_TIME $('#timer').html(`[${timeRemaining}]`); let defer = $.Deferred(); let interval = setInterval(() => { timeRemaining--; $('#timer').html(`[${timeRemaining}]`); if (timeRemaining === 0) { defer.resolve(); clearInterval(interval); } }, 1000) return defer; } function showFinalScore() { $('.screen.active').removeClass('active'); $('#finalScore').html(`[${score}]`); $('#finalChillmeter .inner').css('marginTop', -score); $('#gameOver').addClass('active'); } function initGameScreen() { renderScore(); $('.screen.active').removeClass('active'); $('#game').addClass('active'); let chillCount = 7; let chillArr = []; let renderChill = function() { let c = new Chill(); c.render(); chillArr.push(c); }; for (let i = 0; i < chillCount; i++) { setTimeout(renderChill, i * 450); } initGameTimer().then(() => { showFinalScore(); for (let i = 0; i < chillCount; i++) { chillArr[i].destroy(); } }); } function showHome() { score = 0; $('.screen.active').removeClass('active'); $('#welcome').addClass('active'); } function renderScore() { $('#score').html(`[${score}]`); $('#inner').css('marginTop', -score); } function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } class Chill { getRandomProps() { this.width = getRandomInt(10,50); this.height = this.width; this.top = getRandomInt(0, $('#playground').height() - this.height); this.left = getRandomInt(0, $('#playground').width() - this.width); } rerender() { this.destroy(); this.render(); } render() { this.id = guid(); this.getRandomProps(); let node = $('<img>', { id: this.id, src: 'dist/images/chill.png', css: { position: 'absolute', top: this.top, left: this.left, width: this.width }, click: (event) => { $(event.target).remove(); score += Math.round(this.width/10); clearInterval(this.interval); this.render(); renderScore(); } }); this.interval = setInterval(this.rerender.bind(this), chillLifetime); $(playground).append(node); } destroy() { $('#' + this.id).remove(); clearInterval(this.interval); } } function guid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); }
JavaScript
0.000001
@@ -54,17 +54,17 @@ _TIME = -1 +6 0;%0Alet s @@ -2145,17 +2145,17 @@ mInt(10, -5 +7 0);%0A%09%09th