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
ed9701f078c02b341761655a13155942c94dd478
Update gennumplan.js
tools/phone/gennumplan.js
tools/phone/gennumplan.js
/* * gennumplan.js - ilib tool to generate the json numplan information from the libphonefmt-js * library * * Copyright © 2019 JEDLSoft * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. */ /* * This code is intended to be run under node.js */ var fs = require('fs'); var util = require('util'); var path = require('path'); var common = require('../cldr/common.js'); var mkdirs = common.makeDirs; var toDir = "tmp"; if (process.argv.length > 2) { toDir = process.argv[2]; } function usage() { console.log("Usage: gengeoinfo.js [-h] [ output_dir ]\n" + "-h or --help\n" + " this help\n"); process.exit(1); } process.argv.forEach(function (val, index, array) { if (val === "-h" || val === "--help") { usage(); } }); console.log("gennumplan.js - generate the numplan.json file.\n"); var metadata = require("./libphonenumber-js/metadata.json"); var countryData = metadata.countries; var country, filename, exampleNums = {}; function getFormatChars(phonedata) { var formats = phonedata.formats; if (!formats) return ""; var numformats = formats.length; var combineString = "", uniqChars = ""; var i; for (i=0; i< numformats; i++) { combineString += formats[i].format; } trimString = combineString.replace(/[\$[0-9]|[0-9]*/g, "").replace(/\s+/g," "); if (trimString.length >1) { for (i=0; i < trimString.length; i++) { if (uniqChars.indexOf(trimString[i]) == -1) { uniqChars += trimString[i]; } } } return uniqChars ? uniqChars : trimString; } for (country in countryData) { if (country === "001") break; var numPlanData = {}; var regx = RegExp(/[\!|\?|\:]/); var phoneMetadata = countryData[country]; filename = path.join(toDir, 'und', country) if (!fs.existsSync(filename)) { mkdirs(filename); } numPlanData["region"] = country; numPlanData["countryCode"] = phoneMetadata["phone_code"]; if (regx.test(countryData[country]["idd_prefix"])){ numPlanData["iddCode"] = phoneMetadata["idd_prefix"] + " - It's a regular expression. It needs to be checked"; } else { numPlanData["iddCode"] = phoneMetadata["idd_prefix"]; } numPlanData["trunkCode"] = phoneMetadata["national_prefix"]; numPlanData["skipTrunk"] = (phoneMetadata["national_prefix"] ? true : false); /* * No info in metadata. Just set default value * "dialingPlan": "closed" */ numPlanData["dialingPlan"] = "closed"; numPlanData["commonFormatChars"] = getFormatChars(phoneMetadata); var fieldLength = { "areaCode": 0, "cic": 0, "vsc": 0, "mobilePrefix": 0, "serviceCode": 0, "personal": 0, "minLocalLength": 0, "maxLocalLength": 8, "emergency": 0, "special": 0 }; if (phoneMetadata["types"]["fixed_line"] && phoneMetadata["types"]["fixed_line"]["possible_lengths"]) { countLength = phoneMetadata["types"]["fixed_line"]["possible_lengths"]; if (countLength.length == 1) { fieldLength["maxLocalLength"] = countLength[0]; } else { fieldLength["minLocalLength"] = countLength[0]; fieldLength["maxLocalLength"] = countLength[countLength.length-1]; } } numPlanData["fieldLengths"] = fieldLength; exampleNums[country]= phoneMetadata["examples"]; if (typeof phoneMetadata["national_prefix"] !== "undefined") { exampleNums[country]["trunkCode"] = phoneMetadata["national_prefix"]; } var file1 = path.join(filename, "numplan.json"); console.log("Creating " + filename + "/numplan.json") fs.writeFileSync(file1, JSON.stringify(numPlanData, true, 4), "utf-8"); } var file2 = path.join(toDir, "exampleNums.json"); fs.writeFileSync(file2, JSON.stringify(exampleNums, true, 4), "utf-8");
JavaScript
0
@@ -930,16 +930,139 @@ %22tmp%22;%0A%0A +var skipCountry = %5B%22KR%22, %22US%22, %22GB%22, %22ES%22, %22MX%22, %22AR%22, %22CO%22, %22BR%22, %22CA%22, %22FR%22, %22IT%22, %22DE%22, %22RU%22, %22JP%22, %22CN%22, %22TW%22, %22NL%22%5D;%0A%0A if (proc @@ -2294,16 +2294,138 @@ 001%22 -) break; + %7C%7C%0A (skipCountry.indexOf(country) !== -1 ) ) %7B%0A console.log(%22skip country.... : %22, country)%0A continue;%0A %7D%0A %0A
fb425d0f24d41ca6c58db9fd986c6c0ada94bf49
test guest rules
app/modules/core/test/unit/auth-service-test.js
app/modules/core/test/unit/auth-service-test.js
'use strict'; describe('auth-service', function () { var AuthService, StorageService, StorageServiceMock, authClientMock = { $login: function(){}, $logout: function(){}, $getCurrentUser: function(){} }; beforeEach(module('kosh')); beforeEach(module(function($provide) { StorageServiceMock = { getAuthClient: function() { return authClientMock; } }; $provide.value('StorageService', StorageServiceMock); })); beforeEach(inject(function(_AuthService_, _StorageService_) { AuthService = _AuthService_; StorageService = _StorageService_; })); describe('test login and logout', function() { it('should call $login on the authClient object', function() { spyOn(authClientMock, '$login'); AuthService.login(); expect(authClientMock.$login).toHaveBeenCalledWith('github', {rememberMe: true}); }); it('should call $logout on the authClient object', function() { spyOn(authClientMock, '$logout'); AuthService.logout(); expect(authClientMock.$logout).toHaveBeenCalled(); }); it('should tell that user is logged in when uid is present', function() { AuthService.user = { uid: 123 }; expect(AuthService.loggedIn()).toBe(true); }); it('should tell that user is logged out when uid is not present', function() { AuthService.user = {}; expect(AuthService.loggedIn()).toBe(false); }); }); describe('test authorization', function () { var USER_ROLES, $q, $rootScope; beforeEach(inject(function(_USER_ROLES_, _$q_, _$rootScope_) { USER_ROLES = _USER_ROLES_; $q = _$q_; $rootScope = _$rootScope_; })); describe('test rules that require user to be logged in', function() { it('should deny access if user is not logged in', function() { var deferred = $q.defer(), catchHandler = jasmine.createSpy('catchHandler'); spyOn(authClientMock, '$getCurrentUser').andReturn(deferred.promise); AuthService.isAuthorized(USER_ROLES.LOGGED_IN).catch(catchHandler); deferred.resolve(null); $rootScope.$digest(); expect(catchHandler).toHaveBeenCalled(); }); it('should grant access if user is logged in', function() { var deferred = $q.defer(), thenHandler = jasmine.createSpy('thenHandler'); spyOn(authClientMock, '$getCurrentUser').andReturn(deferred.promise); AuthService.isAuthorized(USER_ROLES.LOGGED_IN).then(thenHandler); deferred.resolve('some user'); $rootScope.$digest(); expect(thenHandler).toHaveBeenCalled(); }); }); describe('test rules that allow guest users', function () { it('should grant access if user is logged in', function() { var deferred = $q.defer(), thenHandler = jasmine.createSpy('thenHandler'); AuthService.isAuthorized(USER_ROLES.GUEST).then(thenHandler); deferred.resolve('some user'); $rootScope.$digest(); expect(thenHandler).toHaveBeenCalled(); }); }); }); });
JavaScript
0.000001
@@ -3131,32 +3131,388 @@ d();%0A %7D);%0A%0A + it('should grant access if user is not logged in', function() %7B%0A var deferred = $q.defer(),%0A thenHandler = jasmine.createSpy('thenHandler');%0A AuthService.isAuthorized(USER_ROLES.GUEST).then(thenHandler);%0A deferred.resolve(null);%0A $rootScope.$digest();%0A expect(thenHandler).toHaveBeenCalled();%0A %7D);%0A%0A %7D);%0A%0A %7D);%0A%0A
1c5491ec980c983c2df5c53e529360dc1788dd23
add padding to user dash table
app/src/components/UserDashboardTable/styles.js
app/src/components/UserDashboardTable/styles.js
import styled from 'styled-components'; import Box from 'grommet-udacity/components/Box'; import Heading from 'grommet-udacity/components/Heading'; import TableRow from 'grommet-udacity/components/TableRow'; import GrommetLabel from 'grommet-udacity/components/Label'; import GrommetSelect from 'grommet-udacity/components/Select'; export const BoxWrapper = styled(Box)` display: flex; align-items: center; justify-content: space-between; flex-direction: row !important; width: 100%; margin-top: 40px; `; export const InnerWrapper = styled(Box)` width: 80vw; justify-content: center; `; export const ListWrapper = styled(Box)` min-height: 600px; max-width: 100vw !important; box-sizing: border-box; `; export const GrowBox = styled(Box)` flex-grow: 1; @media screen and (max-width: 1200px) { flex-grow: 0; max-width: 100vw; box-sizing: border-box; } `; export const UserName = styled(Heading)` flex: 1; `; export const TD = styled.td` min-width: 220px; @media screen and (max-width: 1200px) { min-width: 100px; } `; export const TRow = styled(TableRow)` cursor: pointer; &:hover { background-color: ${props => props.isEditing ? '#fff' : '#eee'}; } border-bottom: 1px solid #eee; `; export const Input = styled.input` display: flex; flex: 1; margin-left: 20px !important; `; export const TextArea = styled.textarea` display: flex; flex: 1; margin-left: 20px !important; `; export const Label = styled(GrommetLabel)` width: 50px; margin: 5px; `; export const SelectBig = styled(GrommetSelect)` display: flex; flex: 1; margin-left: 20px; input { display: flex; flex: 1; } `;
JavaScript
0
@@ -717,16 +717,61 @@ er-box;%0A + padding-top: 40px;%0A padding-bottom: 40px;%0A %60;%0A%0Aexpo
5134bc1a387936dc7ea867c0bbcf66d600bfade9
Standardize on verify callback terminology.
lib/passport-browserid/strategy.js
lib/passport-browserid/strategy.js
/** * Module dependencies. */ var passport = require('passport') , https = require('https') , querystring = require('querystring') , util = require('util') /** * `Strategy` constructor. * * The BrowserID authentication strategy authenticates requests using the * BrowserID JavaScript API and Verified Email Protocol (VEP). * * BrowserID provides a federated and decentralized universal login system for * the web, based on email addresses as an identity token. Authenticating in * this this manner involves a sequence of events, including prompting the user, * via their user agent, for an assertion of email address ownership. Once this * assertion is obtained, it can be verified and the user can be authenticated. * * Applications must supply a `validate` callback which accepts an `email` * address, and then calls the `done` callback supplying a `user`, which should * be set to `false` if the credentials are not valid. If an exception occured, * `err` should be set. * * Options: * - `audience` the website requesting and verifying an identity assertion * - `assertionField` field name where the assertion is found, defaults to 'assertion' * * Examples: * * passport.use(new BrowserIDStrategy({ * audience: 'http://www.example.com' * }, * function(email, done) { * User.findByEmail(email, function (err, user) { * done(err, user); * }); * } * )); * * @param {Object} options * @param {Function} validate * @api public */ function Strategy(options, validate) { if (!options.audience) throw new Error('BrowserID authentication requires an audience option'); if (!validate) throw new Error('BrowserID authentication strategy requires a validate function'); passport.Strategy.call(this); this.name = 'browserid'; this._validate = validate; this._audience = options.audience; this._assertionField = options.assertionField || 'assertion'; // options used to inject mock objects for testing purposes this._https = options.transport || https; } /** * Inherit from `passport.Strategy`. */ util.inherits(Strategy, passport.Strategy); /** * Authenticate request by using browserid.org as a trusted secondary authority * for verifying email assertions. * * @param {Object} req * @api protected */ Strategy.prototype.authenticate = function(req) { var self = this; if (!req.body || !req.body[this._assertionField]) { return this.fail(); } var assertion = req.body[this._assertionField]; var query = querystring.stringify({ assertion: assertion, audience: this._audience }); var headers = {}; headers['Host'] = 'browserid.org'; headers['Content-Type'] = 'application/x-www-form-urlencoded'; headers['Content-Length'] = query.length; var options = { host: 'browserid.org', port: 443, path: '/verify', method: 'POST', headers: headers }; var req = this._https.request(options, function(res) { var data = ''; res.on('data', function(chunk) { data += chunk; }); res.on('end', function() { try { var result = JSON.parse(data); if (result.status === 'okay') { return verified(result) } else { // TODO: Implement a mechanism in Passport to provide errors when // authentication failures occur. // return self.fail(new Error(result.reason)); return self.fail(); } } catch(err) { return self.error(err); } }); res.on('error', function(err) { return self.error(err); }); }); req.end(query, 'utf8'); // TODO: Check that the audience matches this server, according to the Host // header. Also, implement an option to disable this check (defaulting // to false). function verified(result) { self._validate(result.email, function(err, user) { if (err) { return self.error(err); } if (!user) { return self.fail(); } self.success(user); }); } } /** * Expose `Strategy`. */ module.exports = Strategy;
JavaScript
0
@@ -767,23 +767,21 @@ ply a %60v -alidate +erify %60 callba @@ -1513,23 +1513,21 @@ ction%7D v -alidate +erify %0A * @api @@ -1566,23 +1566,21 @@ tions, v -alidate +erify ) %7B%0A if @@ -1681,23 +1681,21 @@ if (!v -alidate +erify ) throw @@ -1751,23 +1751,21 @@ ires a v -alidate +erify functio @@ -1844,26 +1844,22 @@ s._v -alidate = validate +erify = verify ;%0A @@ -3867,15 +3867,13 @@ f._v -alidate +erify (res
c7ad9bfdad0bb6c202081c0ce8041f0532513d42
Add 'getHomeServerName' util to client peg
src/MatrixClientPeg.js
src/MatrixClientPeg.js
/* Copyright 2015, 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; import Matrix from 'matrix-js-sdk'; import utils from 'matrix-js-sdk/lib/utils'; import EventTimeline from 'matrix-js-sdk/lib/models/event-timeline'; import EventTimelineSet from 'matrix-js-sdk/lib/models/event-timeline-set'; const localStorage = window.localStorage; interface MatrixClientCreds { homeserverUrl: string, identityServerUrl: string, userId: string, deviceId: string, accessToken: string, guest: boolean, } /** * Wrapper object for handling the js-sdk Matrix Client object in the react-sdk * Handles the creation/initialisation of client objects. * This module provides a singleton instance of this class so the 'current' * Matrix Client object is available easily. */ class MatrixClientPeg { constructor() { this.matrixClient = null; // These are the default options used when when the // client is started in 'start'. These can be altered // at any time up to after the 'will_start_client' // event is finished processing. this.opts = { initialSyncLimit: 20, }; } get(): MatrixClient { return this.matrixClient; } unset() { this.matrixClient = null; } /** * Replace this MatrixClientPeg's client with a client instance that has * Home Server / Identity Server URLs and active credentials */ replaceUsingCreds(creds: MatrixClientCreds) { this._createClient(creds); } start() { const opts = utils.deepCopy(this.opts); // the react sdk doesn't work without this, so don't allow opts.pendingEventOrdering = "detached"; this.get().startClient(opts); } getCredentials(): MatrixClientCreds { return { homeserverUrl: this.matrixClient.baseUrl, identityServerUrl: this.matrixClient.idBaseUrl, userId: this.matrixClient.credentials.userId, deviceId: this.matrixClient.getDeviceId(), accessToken: this.matrixClient.getAccessToken(), guest: this.matrixClient.isGuest(), }; } _createClient(creds: MatrixClientCreds) { var opts = { baseUrl: creds.homeserverUrl, idBaseUrl: creds.identityServerUrl, accessToken: creds.accessToken, userId: creds.userId, deviceId: creds.deviceId, timelineSupport: true, }; if (localStorage) { opts.sessionStore = new Matrix.WebStorageSessionStore(localStorage); } this.matrixClient = Matrix.createClient(opts); // we're going to add eventlisteners for each matrix event tile, so the // potential number of event listeners is quite high. this.matrixClient.setMaxListeners(500); this.matrixClient.setGuest(Boolean(creds.guest)); var notifTimelineSet = new EventTimelineSet(null, { timelineSupport: true }); // XXX: what is our initial pagination token?! it somehow needs to be synchronised with /sync. notifTimelineSet.getLiveTimeline().setPaginationToken("", EventTimeline.BACKWARDS); this.matrixClient.setNotifTimelineSet(notifTimelineSet); } } if (!global.mxMatrixClientPeg) { global.mxMatrixClientPeg = new MatrixClientPeg(); } module.exports = global.mxMatrixClientPeg;
JavaScript
0.000001
@@ -2669,24 +2669,486 @@ %7D;%0A %7D%0A%0A + /**%0A * Return the server name of the user's home server%0A * Throws an error if unable to deduce the home server name%0A * (eg. if the user is not logged in)%0A */%0A getHomeServerName() %7B%0A const matches = /%5E@.+:(.+)$/.exec(this.matrixClient.credentials.userId);%0A if (matches === null %7C%7C matches.length %3C 1) %7B%0A throw new Error(%22Failed to derive home server name fro user ID!%22);%0A %7D%0A return matches%5B1%5D;%0A %7D%0A%0A _createC
27b3f5f6b1fc544fad043bd8623c38c973e826a8
create a global notif timeline set for each client
src/MatrixClientPeg.js
src/MatrixClientPeg.js
/* Copyright 2015, 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; import Matrix from 'matrix-js-sdk'; import utils from 'matrix-js-sdk/lib/utils'; const localStorage = window.localStorage; interface MatrixClientCreds { homeserverUrl: string, identityServerUrl: string, userId: string, deviceId: string, accessToken: string, guest: boolean, } /** * Wrapper object for handling the js-sdk Matrix Client object in the react-sdk * Handles the creation/initialisation of client objects. * This module provides a singleton instance of this class so the 'current' * Matrix Client object is available easily. */ class MatrixClientPeg { constructor() { this.matrixClient = null; // These are the default options used when when the // client is started in 'start'. These can be altered // at any time up to after the 'will_start_client' // event is finished processing. this.opts = { initialSyncLimit: 20, }; } get(): MatrixClient { return this.matrixClient; } unset() { this.matrixClient = null; } /** * Replace this MatrixClientPeg's client with a client instance that has * Home Server / Identity Server URLs and active credentials */ replaceUsingCreds(creds: MatrixClientCreds) { this._createClient(creds); } start() { const opts = utils.deepCopy(this.opts); // the react sdk doesn't work without this, so don't allow opts.pendingEventOrdering = "detached"; this.get().startClient(opts); } getCredentials(): MatrixClientCreds { return { homeserverUrl: this.matrixClient.baseUrl, identityServerUrl: this.matrixClient.idBaseUrl, userId: this.matrixClient.credentials.userId, deviceId: this.matrixClient.getDeviceId(), accessToken: this.matrixClient.getAccessToken(), guest: this.matrixClient.isGuest(), }; } _createClient(creds: MatrixClientCreds) { var opts = { baseUrl: creds.homeserverUrl, idBaseUrl: creds.identityServerUrl, accessToken: creds.accessToken, userId: creds.userId, deviceId: creds.deviceId, timelineSupport: true, }; if (localStorage) { opts.sessionStore = new Matrix.WebStorageSessionStore(localStorage); } this.matrixClient = Matrix.createClient(opts); // we're going to add eventlisteners for each matrix event tile, so the // potential number of event listeners is quite high. this.matrixClient.setMaxListeners(500); this.matrixClient.setGuest(Boolean(creds.guest)); } } if (!global.mxMatrixClientPeg) { global.mxMatrixClientPeg = new MatrixClientPeg(); } module.exports = global.mxMatrixClientPeg;
JavaScript
0
@@ -656,16 +656,161 @@ /utils'; +%0Aimport EventTimeline from 'matrix-js-sdk/lib/models/event-timeline';%0Aimport EventTimelineSet from 'matrix-js-sdk/lib/models/event-timeline-set'; %0A%0Aconst @@ -3417,16 +3417,389 @@ guest)); +%0A%0A var notifTimelineSet = new EventTimelineSet(null, null, %7B%0A timelineSupport: true%0A %7D);%0A // XXX: what is our initial pagination token?! it somehow needs to be synchronised with /sync.%0A notifTimelineSet.getLiveTimeline().setPaginationToken(%22%22, EventTimeline.BACKWARDS);%0A this.matrixClient.setNotifTimelineSet(notifTimelineSet); %0A %7D%0A%7D
6dde7444c97385c05dd771b5813ade22a09fb7e1
Update put-spot.js
spots-api/api/put-spot.js
spots-api/api/put-spot.js
// put-spot.js module.exports = function(db) { return function(req, res) { var spots = db.collection('spots'); spots.update({_id: req.params.id}, {$set: req.body}, function(err, result) { if(err) throw err; res.json(result); }); } }
JavaScript
0.000012
@@ -209,17 +209,62 @@ rr) -throw err +return res.status(500).json(code: 'DbError', err: err) ;%0A%0A
26b5cae765777b83bc0b2cffc9302ef434ecc45e
clean up
content_scripts/entry.js
content_scripts/entry.js
let INTERVAL_ID = 'not_touched'; // the same members as storage.local's const SETTINGS = { update_check : true, update_check_interval : 14000, mute_by_key : false, block_by_key : false, }; const STORE_NAME = 'pptw_settings'; const pptw = { /** * click 'update' button, unless overlay appear in the topmost. */ clickUpdateButton : () => { let wk_elm = document.getElementById('permalink-overlay'); let goClick = true; if(wk_elm) { const computedStyle = window.getComputedStyle(wk_elm); if(computedStyle === undefined || computedStyle.display === undefined || computedStyle.display === 'block' || computedStyle.opacity === 1) { goClick = false; } } if(goClick) { wk_elm = document.getElementsByClassName('new-tweets-bar'); if(wk_elm && wk_elm.length > 0) { wk_elm[0].click(); } } }, getTweetList : () => { const root = document.getElementById('stream-items-id'); if(!root) { return; } const tweetTextArr = []; const tweetContainerList = root.querySelectorAll('.js-stream-item'); if(tweetContainerList && tweetContainerList.length > 0) { tweetContainerList.forEach(elm => { const textContainer = elm.querySelector('.tweet-text'); if(textContainer) { tweetTextArr.push(textContainer.textContent.trim()); } }); } return tweetTextArr; }, handleKeydown : (evt) => { if(SETTINGS.block_by_key === false && evt.key === 'b') { pptw.preventKeydown(evt); } else if(SETTINGS.mute_by_key === false && evt.key === 'u') { pptw.preventKeydown(evt); } }, preventKeydown : (evt) => { if(evt.target.isContentEditable || evt.target.nodeName.toUpperCase() === 'INPUT' || evt.target.nodeName.toUpperCase() === 'TEXTAREA') { return; } evt.preventDefault(); }, scrollToTweet : (ord) => { const tweetContainerList = document.querySelectorAll('#stream-items-id .js-stream-item'); if(tweetContainerList && tweetContainerList.length > 0 && ord < tweetContainerList.length) { tweetContainerList[ord].scrollIntoView(); } }, setUpdateCheck : (goEnable) => { if(INTERVAL_ID === 'not_touched') { if(goEnable) { INTERVAL_ID = setInterval(pptw.clickUpdateButton, SETTINGS.update_check_interval); } SETTINGS.update_check = goEnable; pptw.updatePageAction(); } else if(goEnable && SETTINGS.update_check === false) { INTERVAL_ID = setInterval(pptw.clickUpdateButton, SETTINGS.update_check_interval); SETTINGS.update_check = goEnable; pptw.updatePageAction(); } else if(goEnable === false && SETTINGS.update_check) { clearInterval(INTERVAL_ID); SETTINGS.update_check = goEnable; pptw.updatePageAction(); } }, updateSettings : (newSettings) => { if(newSettings) { Object.keys(newSettings).forEach(key => { if(SETTINGS.hasOwnProperty(key)) { SETTINGS[key] = newSettings[key]; } }); // console.log(`${JSON.stringify(SETTINGS, null, 2)}`); } pptw.setUpdateCheck(SETTINGS.update_check); }, updatePageAction : () => { browser.runtime.sendMessage({ task:'setIcon', icon: SETTINGS.update_check, }); }, }; const start = () => { browser.storage.local.get(STORE_NAME).then(store_obj => { const result = store_obj[STORE_NAME]; pptw.updateSettings(result); document.addEventListener('keydown', pptw.handleKeydown); }).catch(err => { console.log(`Error: start: ${err}`); }); }; browser.runtime.onMessage.addListener((message, _sender) => { if(message.task === 'tweetList' && message.from === 'popup') { browser.runtime.sendMessage({ task: message.task, replyTo: message.from, tweetList: pptw.getTweetList(), }); } else if(message.task === 'scrollToTweet' && message.from === 'popup') { pptw.scrollToTweet(message.ord); } else if(message.task === 'toggleUpdateCheck' && message.from === 'popup') { pptw.setUpdateCheck(!SETTINGS.update_check); } }); start(); // vim:expandtab ff=dos fenc=utf-8 sw=2
JavaScript
0.000887
@@ -3185,71 +3185,8 @@ );%0D%0A - // console.log(%60$%7BJSON.stringify(SETTINGS, null, 2)%7D%60);%0D%0A
343a6171fd419f76a6f94e6868b91b9e1b4baf08
Add example webpackDevServer config override.
packages/react-app-rewired/config-overrides.js
packages/react-app-rewired/config-overrides.js
/* DEFAULT */ module.exports = function override(config, env) { /* Modify the config as needed*/ return config; }; /* ALTERNATIVE */ /* module.exports = { webpack: function (config, env) { return config; }, jest: function (config) { return config; } } */
JavaScript
0
@@ -263,12 +263,1051 @@ ig;%0A + %7D,%0A // configFunction is the original react-scripts function that creates the%0A // Webpack Dev Server config based on the settings for proxy/allowedHost.%0A // react-scripts injects this into your function (so you can use it to%0A // create the standard config to start from), and needs to receive back a%0A // function that takes the same arguments as the original react-scripts%0A // function so that it can be used as a replacement for the original one.%0A devServer: function (configFunction) %7B%0A return function(proxy, allowedHost) %7B%0A const config = configFunction(proxy, allowedHost);%0A // Edit config here - example: set your own certificates.%0A //%0A // const fs = require('fs');%0A // config.https = %7B%0A // key: fs.readFileSync(process.env.REACT_HTTPS_KEY, 'utf8'),%0A // cert: fs.readFileSync(process.env.REACT_HTTPS_CERT, 'utf8'),%0A // ca: fs.readFileSync(process.env.REACT_HTTPS_CA, 'utf8'),%0A // passphrase: process.env.REACT_HTTPS_PASS%0A // %7D;%0A %0A return config;%0A %7D;%0A %7D%0A%7D%0A*/ @@ -1306,8 +1306,9 @@ %7D%0A%7D%0A*/ +%0A
1de5b5ad96f56676c1b0b62e2ec88e5a089e975c
use GraphQLID to represents object id's
schemas/twitter.js
schemas/twitter.js
import * as twitter from '../apis/twitter'; import { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLNonNull, GraphQLInt, GraphQLList, } from 'graphql'; let UserType = new GraphQLObjectType({ name: 'TwitterUser', description: 'Twitter user, or as we like to say in France: a \'tweetos\'', fields: () => ({ created_at: { type: GraphQLString }, description: { type: GraphQLString }, id: { type: GraphQLInt }, screen_name: { type: GraphQLString }, name: { type: GraphQLString }, profile_image_url: { type: GraphQLString }, url: { type: GraphQLString }, tweets_count: { type: GraphQLInt, resolve: ({ statuses_count: tweets_count }) => tweets_count }, followers_count: { type: GraphQLInt }, tweets: { type: new GraphQLList(TweetType), description: 'Get a list of tweets for current user', args: { limit: { type: GraphQLInt } }, // user args resolve: ({ id: user_id }, { limit = 10 }) => twitter.getTweets(user_id, limit) } }) }); let TweetType = new GraphQLObjectType({ name: 'Tweet', description: 'A tweet object', fields: () => ({ id: { type: GraphQLString }, id_str: { type: GraphQLString }, created_at: { type: GraphQLString }, text: { type: GraphQLString }, retweet_count: { type: GraphQLInt }, user: { type: UserType }, retweets: { type: new GraphQLList(RetweetType), description: 'Get a list of retweets', args: { limit: { type: GraphQLInt } }, resolve: ({ id_str: tweetId }, { limit = 5 }) => twitter.getRetweets(tweetId, limit) } }) }); let RetweetType = new GraphQLObjectType({ name: 'Retweet', description: 'Retweet of a tweet', fields: () => ({ id: { type: GraphQLString }, created_at: { type: GraphQLString }, in_reply_to_tweet_id: { type: GraphQLString, resolve: ({ in_reply_to_status_id }) => in_reply_to_status_id }, in_reply_to_user_id: { type: GraphQLInt }, in_reply_to_screen_name: { type: GraphQLString }, retweeted_status: { type: TweetType }, user: { type: UserType } }) }); let twitterType = new GraphQLObjectType({ name: 'TwitterAPI', description: 'The Twitter API', fields: { user: { type: UserType, args: { user_id: { description: 'ID of user account', type: GraphQLInt }, screen_name: { description: 'Screenname of the user', type: GraphQLString } }, resolve: (_, { user_id, screen_name }) => { const { getUser } = twitter; if (!user_id && !screen_name) { return getUser('user_id', 9533042); } else { if (isNaN(parseInt(user_id))) { return getUser('screen_name', screen_name); } else { return getUser('user_id', user_id); } } } }, tweet: { type: TweetType, args: { id: { type: new GraphQLNonNull(GraphQLString), description: 'Unique ID of tweet' } }, resolve: (_, { id: tweetId }) => twitter.getTweet(tweetId) }, search: { type: new GraphQLList(TweetType), description: "Returns a collection of relevant Tweets matching a specified query.", args: { q: { type: new GraphQLNonNull(GraphQLString), description: "A UTF-8, URL-encoded search query of 500 characters maximum, including operators. Queries may additionally be limited by complexity." }, count: { type: GraphQLInt, description: "The number of tweets to return per page, up to a maximum of 100. Defaults to 15. This was formerly the “rpp” parameter in the old Search API." }, result_type: { type: GraphQLString, description: `Specifies what type of search results you would prefer to receive. The current default is “mixed.” Valid values include: * mixed: Include both popular and real time results in the response. * recent: return only the most recent results in the response * popular: return only the most popular results in the response.` } }, resolve: (_, searchArgs) => twitter.searchFor(searchArgs) } } }); export const Schema = { query: { type: twitterType, resolve() { return {}; } } };
JavaScript
0
@@ -85,24 +85,39 @@ ObjectType,%0A + GraphQLID,%0A GraphQLS @@ -119,24 +119,24 @@ phQLString,%0A - GraphQLN @@ -472,37 +472,68 @@ %7B type: GraphQLI -nt %7D, +D %7D, // GraphQLInt would return null %0A screen_ @@ -1385,38 +1385,34 @@ %7B type: GraphQL -String +ID %7D,%0A id_s @@ -2083,38 +2083,34 @@ %7B type: GraphQL -String +ID %7D,%0A crea
db347219a260fc9bcf674c7e334e4b70877561bc
Fix Javascript
public/js/angular/modules/experience.js
public/js/angular/modules/experience.js
angular.module('experience', []).controller('ExperienceController', function($scope, $http) { $scope.companyname=''; $scope.companies = []; $scope.history = []; function loadLookupData(resourceName) { var responsePromise = $http.get('/api/lookup/' + resourceName); responsePromise.success(function(data, status, headers, config) { $scope.lookups[resourceName] = data._embedded[resourceName]; alert(JSON.stringify($scope.lookups[resourceName][0])); }); responsePromise.error(function(data, status, headers, config) { alert("Loading lookup data for " + resourceName + " failed."); }); } loadLookupData('jobstatus'); loadLookupData('committeerole'); loadLookupData('jobarea'); $scope.$watch(function() {return element.attr('class'); }, function(newValue){ alert(newValue);}); $scope.autocomplete = function() { var responsePromise = $http.get('/ajax/company/search?format=autocomplete&limit=200&name=' + this.companyname); var companies = $scope.companies; responsePromise.success(function(data, status, headers, config) { companies.length = 0; for (i=0; i<data.length; i++) { var companyDetails = data[i].source; companyDetails['arrayindex'] = i; companies.push(companyDetails); } }); responsePromise.error(function(data, status, headers, config) { alert("Autocomplete AJAX failed!"); }); }; function loadHistory() { var historyPromise = $http.get('/ajax/experience/history'); historyPromise.success(function(data, status, headers, config) { $scope.history = []; for (var i=0; i<data.length; i++) { $scope.history[i] = { 'companyid': data[i].companydirectoryid, 'name': data[i].name }; } }); historyPromise.error(function(data, status, headers, config) { alert("Load history AJAX failed!"); }); } function updateHistory() { var historyPromise = $http.post('/ajax/experience/history', $scope.history); historyPromise.success(function(data, status, headers, config) { }); historyPromise.error(function(data, status, headers, config) { alert("History AJAX failed!"); }); } $scope.select = function(arrayindex) { $scope.history.push($scope.companies[arrayindex]); var elementId = '#companyid-' + $scope.companies[arrayindex].companyid; setTimeout(function () { $(elementId).css('display', 'none'); $(elementId).fadeIn(1200, function () {}); setupDatepickers(); }, 0); $scope.companies = []; updateHistory(); } $scope.remove = function(companyId) { if (confirm('Do you wish to remove this company from your history?')) { var elementId = '#companyid-' + companyId; $(elementId).fadeOut('slow', function () { var foundIndex = -1; for (var i=0; i<$scope.history.length; i++) { if ($scope.history[i].companyid == companyId) { foundIndex = i; break; } } if (foundIndex != -1) { $scope.history.splice(foundIndex, 1); } setTimeout(function () { updateHistory(); }); }); } } function setupDatefields() { alert(1); $('.date-entry').datepicker( { changeYear: true, yearRange: "1920:2020", dateFormat: "yy-mm-dd", inline: true, defaultDate: 0, showOtherMonths: true, dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']} ); } loadHistory(); });
JavaScript
0.000009
@@ -417,74 +417,8 @@ me%5D; -%0A%0A %09alert(JSON.stringify($scope.lookups%5BresourceName%5D%5B0%5D)); %0A @@ -603,69 +603,195 @@ %7D%0A%0A%09 -loadLookupData('jobstatus');%0A%09loadLookupData('committeerole') +$scope.lookups = %5B%5D;%0A%09%0A%09$scope.lookups.jobstatus = %5B%5D;%0A%09loadLookupData('jobstatus');%0A%09%0A%09$scope.lookups.committeerole = %5B%5D;%0A%09loadLookupData('committeerole');%0A%09%0A%09$scope.lookups.jobarea = %5B%5D ;%0A%09l
ff1facbacbfea0f9072805d78ff2db4f4db81a28
Update schedule.js
script/schedule.js
script/schedule.js
/* var blocks = { "regular":[ {"start":"7:45","end":"9:06","name":"Block 1","bold":false,"startHour":7,"startMinute":45,"endHour":9,"endMinute":6}, {"start":"9:06","end":"9:16","name":"Break","bold":true,"startHour":9,"startMinute":6,"endHour":9,"endMinute":16}, {"start":"9:21","end":"10:53","name":"Block 2","bold":false,"startHour":9,"startMinute":21,"endHour":10,"endMinute":53}, {"start":"10:58","end":"12:19","name":"Block 3","bold":false,"startHour":10,"startMinute":58,"endHour":12,"endMinute":19}, {"start":"12:19","end":"12:44","name":"Intervention","bold":false,"startHour":12,"startMinute":19,"endHour":12,"endMinute":44}, {"start":"12:44","end":"1:14","name":"Lunch","bold":true,"startHour":12,"startMinute":44,"endHour":13,"endMinute":14}, {"start":"1:19","end":"2:40","name":"Block 4","bold":false,"startHour":13,"startMinute":19,"endHour":14,"endMinute":40} ], "articulation":[ {"start":"7:45","end":"8:53","name":"Block 1","bold":false,"startHour":7,"startMinute":45,"endHour":8,"endMinute":53}, {"start":"8:58","end":"10:14","name":"Block 2","bold":false,"startHour":8,"startMinute":58,"endHour":10,"endMinute":14}, {"start":"10:14","end":"10:34","name":"Break/Lunch","bold":true,"startHour":10,"startMinute":14,"endHour":10,"endMinute":34}, {"start":"10:39","end":"11:47","name":"Block 3","bold":false,"startHour":10,"startMinute":39,"endHour":11,"endMinute":47}, {"start":"11:52","end":"1:00","name":"Block 4","bold":false,"startHour":11,"startMinute":52,"endHour":13,"endMinute":0} ] }; */ // Maintenance Note: Change all `var data = blocks` to `var data = JSON.parse(blocks);` when editing code function getTimeAdv (date) { return [ date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds() ]; } function getNext () { var i; var cycle = true; var data = blocks; var days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ]; var date = new Date(); var render; var currentEvent; var time = getTimeAdv(date); if (date.getDay() !== 0 || date.getDay() !== 6) { if (date.getDay() === 1) { render = data.articulation; } else { render = data.regular; } var currentTime = 0; var nextTime = 0; var hoursLeft = 0; var minutesLeft = 0; for (i = 0; i < render.length; i++) { currentTime = (time[0] * 60) + time[1]; nextTime = (render[i].endHour * 60) + render[i].endMinute; if (currentTime < nextTime) { hoursLeft = Math.floor((nextTime - currentTime) / 60); minutesLeft = Math.floor((nextTime - (hoursLeft * 60)) - currentTime); if (hoursLeft === 0) { return minutesLeft + ' minutes until the end of ' + render[i].name; } else if (hoursLeft !== 0) { return hoursLeft + ' hours and ' + minutesLeft + ' minutes until the end of ' + render[i].name; } } } return 'School is over.'; } } $(document).ready(function () { var days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ]; var data = blocks; var i; var date = new Date(); var render; if (date.getDay() === 1) { render = data.articulation; for (i = 0; i < render.length; i++) { if (!render[i].bold) { $('#display').append('<tr><td>' + render[i].name + ':</td><td>' + render[i].start + '-' + render[i].end + '</td></tr>'); } else if (render[i].bold) { $('#display').append('<tr><td><strong>' + render[i].name + ':</strong></td><td><strong>' + render[i].start + '-' + render[i].end + '</strong></td></tr>'); } } document.getElementsByTagName('title')[0].innerHTML += ': ' + days[new Date().getDay()]; } else if (date.getDay() === 2 || date.getDay() === 3 || date.getDay() === 4 || date.getDay() === 5) { render = data.regular; for (i = 0; i < render.length; i++) { if (!render[i].bold) { $('#display').append('<tr><td>' + render[i].name + ':</td><td>' + render[i].start + '-' + render[i].end + '</td></tr>'); } else if (render[i].bold) { $('#display').append('<tr><td><strong>' + render[i].name + ':</strong></td><td><strong>' + render[i].start + '-' + render[i].end + '</strong></td></tr>'); } } document.getElementsByTagName('title')[0].innerHTML += ': ' + days[new Date().getDay()]; } else if (date.getDay() === 0 || date.getDay() === 6) { document.getElementsByTagName('title')[0].innerHTML += ': ' + days[new Date().getDay()]; $('#text').show(); $('#text').text("No school today, it's " + days[date.getDay()] + "!"); } }); var timeUpdate = setInterval(function () { $('#time').html('The time is currently ' + new Date().toLocaleTimeString() + '.'); $('#next').html(getNext()); }, 500);
JavaScript
0.000002
@@ -1795,16 +1795,159 @@ ) %5D;%0A%7D%0A%0A +function timeUpdate () %7B%0A $('#time').html('The time is currently ' + new Date().toLocaleTimeString() + '.');%0A $('#next').html(getNext());%0A%7D%0A%0A function @@ -4765,16 +4765,12 @@ %7D%0A -%7D);%0A%0Avar + %0A tim @@ -4776,16 +4776,34 @@ meUpdate +();%0A %0A var clock = setIn @@ -4829,121 +4829,26 @@ %7B%0A -$('#time').html('The time is currently ' + new Date().toLocaleTimeString() + '.');%0A $('#next').html(getNext());%0A + timeUpdate();%0A %7D, 5 @@ -4848,12 +4848,16 @@ %0A %7D, 500);%0A +%7D);%0A
010c6331820fcaebf552ef93a60e4be5fd19d2cd
add empty-option test check
specs/unit/patterns/behavioral/memento.spec.js
specs/unit/patterns/behavioral/memento.spec.js
/* globals expect, beforeEach, it, describe, jasmine, spyOn */ import mementoBuilder from '../../../../src/patterns/behavioral/memento.js'; import commandBuilder from '../../../../src/patterns/behavioral/command.js'; import chainOfResponsibilityBuilder from '../../../../src/patterns/behavioral/chainOfResponsibility.js'; import json from '../../../../src/helpers/json.js'; describe('memento', function() { var Memento; var memento; var history; var parsedHistory; var key; beforeEach(function() { spyOn(json, 'stringify').and.callThrough(); spyOn(json, 'parse').and.callThrough(); history = { test: 'testing' }; Memento = mementoBuilder().build(); memento = new Memento(); key = memento.add(history); parsedHistory = memento.get(key); }); it('should add an object', function() { expect(key).toBeDefined(); expect(key).toEqual(0); expect(json.stringify).toHaveBeenCalledWith(history); }); it('should return a parsed object', function() { expect(json.parse).toHaveBeenCalled(); expect(parsedHistory === history).not.toBeTruthy(); expect(parsedHistory).toEqual(history); }); describe('Advanced Level: Undo Redo using Memento, Command, and ChainOfResponsibility', function() { var chain; var UndoManager; var undoManager; var PointInTime; var runSpy; beforeEach(function() { PointInTime = function(index) { this.index = index; this.previous = null; this.next = null; }; chain = (...args) => { var ChainOfResponsibility = chainOfResponsibilityBuilder().build(); var overloader = new ChainOfResponsibility(); args.forEach(overloader.add.bind(overloader)); return overloader.run; }; UndoManager = mementoBuilder(commandBuilder({ constructor() { this.methods = {}; this.state = {}; this.pit = new PointInTime(this.add(this.state)); var execute = this.execute.bind(this); this.execute = chain( this._onExecute.bind(this), (next, ...args) => { execute(...args); next(); } ); var add = this.add.bind(this); this.add = chain( (_, o) => { add(o); }, (next, method, obj) => { if(typeof method !== 'string') { return next(); } this.methods[method] = obj; } ); }, publics: { _onExecute(next, _, ...args) { if(_ !== 'run') { return this.execute.apply(null, ['run', _].concat(args)); } var o = new PointInTime(this.add(this.state)); o.previous = this.pit; this.pit.next = o; this.pit = o; }, run(method, ...args) { return this.methods[method] && this.methods[method].apply(null, [this.state].concat(args)); }, undo() { if(this.pit.previous === null) { return; } this.pit = this.pit.previous; this._updateState(); }, redo() { if(this.pit.next === null) { return; } this.pit = this.pit.next; this._updateState(); }, _updateState() { this.state = this.get(this.pit.index); } } })).build(); undoManager = new UndoManager(); runSpy = jasmine.createSpy('run'); undoManager.add('test', (state, arg) => { runSpy(arg); state.test = arg; }); undoManager.execute('test', 'testing'); }); it('should run a method', function() { expect(runSpy).toHaveBeenCalledWith('testing'); expect(undoManager.state.test).toEqual('testing'); }); it('should undo a method', function() { undoManager.undo(); expect(undoManager.state.test).not.toEqual('testing'); }); it('should redo a method', function() { undoManager.redo(); expect(undoManager.state.test).toEqual('testing'); }); }); });
JavaScript
0.000002
@@ -778,32 +778,334 @@ get(key);%0A %7D);%0A + it('should allow empty options', function() %7B%0A var emptyOptions = undefined;%0A var Memento = mementoBuilder(emptyOptions).build();%0A var memento = new Memento();%0A var key = memento.add(%7Btest: 'testing'%7D);%0A var result = memento.get(key);%0A expect(result.test).toEqual('testing');%0A %7D);%0A it('should add
e865a38a96ab136fd5e91de4945a2af3d01052cb
allow non-object values in slots
js/app/interfaces/module.js
js/app/interfaces/module.js
/* exported Class, Module */ const GObject = imports.gi.GObject; const Lang = imports.lang; const Knowledge = imports.app.knowledge; /** * Class: Class * Counterpart to Lang.Class for modules * * To create a new module, use this metaclass as you would use Lang.Class to * create a regular class: * * > const MyModule = new Module.Class({ * > Name: 'MyModule', * > Extends: GObject.Object, * > }); * * The <Module.Module> interface is implemented automatically even if you don't * specify it, since all modules must implement this interface. */ const Class = new Lang.Class({ Name: 'Class', Extends: Knowledge.Class, _construct: function (props={}) { // Make sure Module is implemented before chaining props.Implements = props.Implements || []; if (props.Implements.indexOf(Module) === -1) props.Implements.unshift(Module); let slots = {}; // Looking for a 'Slots' property on the interface's prototype allows us // to get away with not defining a separate meta-interface for module // interfaces. If we need something more fancy, such as freezing the // interface's slots object, we can switch later. props.Implements.forEach(iface => Lang.copyProperties(iface.prototype.Slots, slots)); Lang.copyProperties(props.Extends.__slots__, slots); Lang.copyProperties(props.Slots, slots); delete props.Slots; if (Object.keys(slots).some(name => name.indexOf('.') !== -1)) throw new Error('Slot names should never contain a "."'); let module = this.parent(props); Object.defineProperties(module, { '__slots__': { writable: false, configurable: false, enumerable: false, value: _freeze_recurse(slots), }, }); /** * Method: get_slot_names * Class method for listing names of slots * * Returns an array containing the names of slots offered by this module. */ module.get_slot_names = function () { return Object.keys(this.__slots__); }; return module; }, }); function _freeze_recurse(o) { Object.getOwnPropertyNames(o).forEach(prop => _freeze_recurse(o[prop])); return Object.freeze(o); } /** * Interface: Module */ const Module = new Lang.Interface({ Name: 'Module', Requires: [ GObject.Object ], Properties: { /** * Property: factory * * The <ModuleFactory> widget that is used to construct and return * the module to its parent application. The type of this property * is flexible to allow for factory mocking in tests. */ 'factory': GObject.ParamSpec.object('factory', 'Factory', 'Factory', GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY, GObject.Object.$gtype), /** * Property: factory_name * * The factory_name is used to identify this module within the app.json. The * factory will use the factory_name to return the appropriate submodules * for this module's slots. */ 'factory-name': GObject.ParamSpec.string('factory-name', 'Module Name', 'Module Name', GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY, ''), }, /** * Method: create_submodule * Create a new instance of a submodule * * Creates an instance of a submodule through the factory, optionally adding * some construct properties. * This doesn't pack the submodule anywhere, just returns it. * * Properties: * slot - the slot for which to create the module (string) * extra_props - dictionary of construct properties */ create_submodule: function (slot, extra_props={}) { return this.factory.create_module_for_slot(this, slot, extra_props); }, });
JavaScript
0.000004
@@ -2256,24 +2256,73 @@ ecurse(o) %7B%0A + if (typeof o !== 'object')%0A return o;%0A Object.g
941be441335bb5dc706f123bbfa007f4e41cdd67
Throw error if indexed-db-configuration is not extended
addon/services/indexed-db-configuration.js
addon/services/indexed-db-configuration.js
import Ember from 'ember'; import computed from 'ember-computed'; const { Service, get, typeOf: getTypeOf, A: array } = Ember; /** * This service should be overwritten to configure IndexedDB. * Overwrite the `mapTable` property & add `versionX` properties to fit your application. * * @module Services * @class IndexedDbConfiguration * @extends Ember.Service * @public */ export default Service.extend({ /** * Increment this whenever you do a new database version. * Set it to 1 on your initial version. * * For every version, you should provide a `versionX` property. * Each of these properties should be an object with "stores" and/or "upgrade" properties. * * stores should be an object where the keys are dasherized, singular model names (e.g. task-item), * and the value is a string with the indexedable fields. * See https://github.com/dfahlander/Dexie.js/wiki/Version.stores() for detailed options. * * upgrade is a function that gets a transaction as parameter, which can be used to run database migrations. * See https://github.com/dfahlander/Dexie.js/wiki/Version.upgrade() for detailed options/examples. * * An example would be: * * ```js * version1: { * stores: { * 'task': '&id*,isRead', * 'task-item': '&id' * } * }, * * version2: { * stores: { * 'task-item': '&id,*isNew' * }, * upgrade: (transaction) => { * transaction['task-item'].each((taskItem, cursor) => { taskItem.isNew = 0; cursor.update(taskItem); }); * } * } * ``` * * The * You can also use upgrade/store without using the other option. * * @property currentVersion * @type {Number} * @public */ currentVersion: 0, /** * The map functions for the tables. * This should be an object with one key per table * where the value is a function that takes an object and returns an object to save in IndexedDB. * * This object NEEDS to contain at least the properties id & json. * It should also contain one property per queryable property on the database table. * * There are a few things to note here: * * 1. Always convert your IDs to strings. You can use the provided `this._toString(val)` function for this. * 2. Always clean up your json. You can use the provided `this._cleanObject(item)` for this. * 3. IndexedDB doesn't work with boolean queries. You need to convert booleans to 1/0 when inserting it into the Database. * You can use the provided `this._toZeroOne(val)` for this. * * For example, the following table config: * * ```js * { * task: '++id,isRead,status,[isRead+status]' * } * ``` * * should look something like this: * * ```js * return { * task: (item) => { * return { * id: this._toString(get(item, 'id')), * json: this._cleanObject(item), * isRead: this._toZeroOne(get(item, 'attributes.isRead')), * status: get(item, 'attributes.status') * }; * } * }; * ``` * * Note that if you do not specify anything here, it will default to * * ```js * return { * id: this._toString(get(item, 'id')), * json: this._cleanObject(item) * }; * ``` * * @property mapTable * @type {Object} * @protected */ mapTable: computed(function() { return {}; }), /** * Map a payload to a database table. * This will use the function provided in mapTable to get a payload to insert into IndexedDB. * Returns null if no map function is found for the type. * * @method mapItem * @param {String} type The type of object to map * @param {Object} item The data to map * @return {Object} * @public */ mapItem(type, item) { let tables = get(this, 'mapTable'); let mapFunc = get(tables, type); if (!item) { return null; } if (!mapFunc) { return { id: this._toString(get(item, 'id')), json: this._cleanObject(item) }; } return mapFunc(item); }, /** * Setup the database and do all necessary database migrations. * * @method setupDatabase * @param {Dexie} db * @return {Dexie} * @public */ setupDatabase(db) { let currentVersion = get(this, 'currentVersion'); for (let v = 1; v <= currentVersion; v++) { let version = get(this, `version${v}`); let stores = get(version, 'stores'); let upgrade = get(version, 'upgrade'); if (stores && upgrade) { db.version(v).stores(stores).upgrade(upgrade); } else if (stores) { db.version(v).stores(stores); } else if (upgrade) { db.version(v).upgrade(upgrade); } } return db; }, /** * Cleanup a json object. * This will convert array-like structures to actual arrays for saving. * It will strip out meta properties etc. * * @method _cleanObject * @param {Object} data * @return {{id, type, attributes: {}, relationships: {}}} * @private */ _cleanObject(data) { if (!data) { return null; } let obj = { id: get(data, 'id'), type: get(data, 'type'), attributes: {}, relationships: {} }; let attributes = get(data, 'attributes') || {}; let relationships = get(data, 'relationships') || {}; let isArray = (item) => { return getTypeOf(item) === 'array' || (getTypeOf(item) === 'instance' && getTypeOf(item.toArray) === 'function'); }; for (let i in attributes) { if (!attributes.hasOwnProperty(i)) { continue; } // Convert array-like structures to real arrays if (isArray(attributes[i])) { obj.attributes[i] = array(attributes[i]).toArray(); } else { obj.attributes[i] = attributes[i]; } } for (let i in relationships) { if (!relationships.hasOwnProperty(i)) { continue; } if (isArray(relationships[i].data)) { obj.relationships[i] = { data: array(relationships[i].data).toArray() }; } else { obj.relationships[i] = relationships[i]; } } return obj; }, /** * Convert a property to a string. * * @method _toString * @param {Mixed} val * @return {String} * @private */ _toString(val) { return `${val}`; }, /** * Convert a boolean to 1/0. * * @method _toZeroOne * @param val * @return {1|0} * @private */ _toZeroOne(val) { return val ? 1 : 0; } });
JavaScript
0.000001
@@ -4375,24 +4375,176 @@ Version');%0A%0A + if (!currentVersion) %7B%0A throw new Error('You need to override services/indexed-db-configuration.js and provide at least one version.');%0A %7D%0A%0A for (let
942dbe6f3f3505709d132a481f7cef2d0898d499
add more comment
js/directives/fileselect.js
js/directives/fileselect.js
// watches changes in the file upload control (input[file]) and // puts the files selected in an attribute var app = angular.module("webui.directives.fileselect", ["webui.services.deps"]); app.directive("indeterminate", [ "$parse", function syncInput (parse) { return { require : "ngModel", // Restrict the directive so it can only be used as an attribute restrict : "A", link : function link (scope, elem, attr, ngModelCtrl) { // Whenever the bound value of the attribute changes we update // use upward emit notification for change to prevent the performance penalty bring by $scope.$watch var getter = parse(attr["ngModel"]); var setter = getter.assign; var children = []; // cache children input var get = function () { return getter(scope); }; // the internal 'indeterminate' flag on the attached dom element var setIndeterminateState = function (newValue) { elem.prop("indeterminate", newValue); }; var setModelValueWithoutSideEffect = function (newVal) { setter(scope, newVal); ngModelCtrl.$modelValue = newVal; ngModelCtrl.$viewValue = newVal; ngModelCtrl.$render(); }; var setWithSideEffect = function (newVal) { ngModelCtrl.$setViewValue(newVal); ngModelCtrl.$render(); }; var passIfLeafChild = function (callback) { return function () { if (children.length > 0) { callback.apply(this, arguments); } }; }; var passIfNotIsLeafChild = function (callback) { return function () { if (children.length === 0) { callback.apply(this, arguments); } }; }; var passThroughThisScope = function (callback) { return function (event) { if (event.targetScope !== event.currentScope) { return callback.apply(this, arguments); } }; }; if (attr["indeterminate"] && parse(attr["indeterminate"]).constant && !scope.$eval(attr["indeterminate"])) { // is leaf input, Only receive parent change and emit child change event setIndeterminateState(scope.$eval(attr["indeterminate"])); ngModelCtrl.$viewChangeListeners.push(passIfNotIsLeafChild(function () { scope.$emit("childSelectedChange"); })); scope.$on("ParentSelectedChange", passThroughThisScope( function (event, newVal) { setWithSideEffect(newVal); })); scope.$emit("i'm child input", get); setWithSideEffect(get()); scope.$emit("childSelectedChange"); } else { // init first time and only once // establish parent-child's relation scope.$on("i'm child input", passThroughThisScope( function (event, child) { children.push(child); }) ); var updateBaseOnChildrenState = function () { var allSelected = children.every(function (child) { return child(); }); var anySeleted = children.some(function (child) { return child(); }); setIndeterminateState(allSelected !== anySeleted); setWithSideEffect(allSelected); }; // is not leaf input, Only receive child change and parent change event ngModelCtrl.$viewChangeListeners.push(passIfLeafChild(function () { if (!elem.prop("indeterminate")) { // emit when prop indeterminate is set to false scope.$broadcast("ParentSelectedChange", get()); } })); // reset input state base on children inputs scope.$on("childSelectedChange", passThroughThisScope(passIfLeafChild(updateBaseOnChildrenState))); } } }; } ]);
JavaScript
0
@@ -1164,293 +1164,8 @@ %7D;%0A - var setModelValueWithoutSideEffect = function (newVal) %7B%0A setter(scope, newVal);%0A ngModelCtrl.$modelValue = newVal;%0A ngModelCtrl.$viewValue = newVal;%0A ngModelCtrl.$render();%0A %7D;%0A @@ -1388,32 +1388,105 @@ ion (callback) %7B + // ensure to execute callback when this input have one or more subinputs %0A @@ -1747,32 +1747,94 @@ ion (callback) %7B + // ensure to execute callback when this input havent subinput %0A @@ -2105,16 +2105,73 @@ lback) %7B + // pass through the event from the scope where they sent %0A @@ -3077,138 +3077,259 @@ al); -%0A %7D));%0A scope.$emit(%22i'm child input%22, get);%0A setWithSideEffect( + // set value to parent's value; this will cause listener to emit childChange event; this won't be a infinite loop%0A %7D));%0A // init first time and only once%0A scope.$emit(%22i'm child input%22, get -() );%0A @@ -3386,142 +3386,236 @@ e%22); -%0A %7D else %7B%0A // init first time and only once%0A // establish parent-child's relatio + // force emitted, and force the parent change their state base on children at first time%0A %7D else %7B%0A // establish parent-child's relation%0A // listen for the child emitted toke n%0A @@ -4263,24 +4263,114 @@ anySeleted); + // if at least one is selected, but not all then set input property indeterminate to true %0A @@ -4645,90 +4645,198 @@ -if (!elem.prop(%22indeterminate%22)) %7B // emit when prop indeterminate is set to false +// emit when property indeterminate is set to false, prevent recursively emitting event from parent to children, children to parent%0A if (!elem.prop(%22indeterminate%22)) %7B %0A
8cc29bedaa9654ef17e1e40b2239e4f1c2f1f92b
fix CLI installation for NPM
slideshow-cli.js
slideshow-cli.js
/* ** slideshow -- Observe and Control Slideshow Applications ** Copyright (c) 2014 Ralf S. Engelschall <http://engelschall.com> ** ** This Source Code Form is subject to the terms of the Mozilla Public ** License (MPL), version 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/. ** ** File: slideshow-cli.js ** Purpose: Command Line Interface (CLI) ** Language: Node/JavaScript */ /* global require: false */ /* global console: false */ /* global process: false */ /* external requirements */ var readline = require("readline"); var chalk = require("chalk"); var slideshow = require("./slideshow-api"); /* define the known applications */ var apps = { "powerpoint": true, "keynote": true }; /* define the known commands (and their argument) */ var commands = { /* CLI-specific */ "help": [], "use": [ "application-type" ], /* API-derived */ "stat": [], "info": [], "boot": [], "quit": [], "open": [ "presentation-filename" ], "close": [], "start": [], "stop": [], "pause": [], "resume": [], "first": [], "last": [], "goto": [ "slide-number" ], "prev": [], "next": [] }; /* the interactive CLI variant */ var cliInteractive = function () { /* start with a non-existing slideshow */ var ss = null; /* create the stdin/stdout based readline interface */ var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); /* provide CLI */ rl.setPrompt("slideshow> "); rl.prompt(); rl.on("line", function (line) { /* determine command */ var argv = line.trim().split(/\s+/); var info = commands[argv[0]]; var prompt = true; if (typeof info === "undefined") console.log(chalk.red("ERROR: invalid command (use \"help\" for usage)")); else if (info.length !== (argv.length - 1)) console.log(chalk.red("ERROR: invalid number of arguments (expected: " + info.join(" ") + ")")); else { /* process CLI-specific commands */ if (argv[0] === "help") Object.keys(commands).forEach(function (cmd) { console.log(chalk.green(" " + cmd + " " + ( commands[cmd].map(function (arg) { return "<" + arg + ">"; }).join(" ") ))); }); else if (argv[0] === "use") { if (typeof apps[argv[1]] === "undefined") console.log(chalk.red("ERROR: invalid argument (expected: " + Object.keys(apps).join(", ") + ")")); else { if (ss !== null) ss.end(); ss = new slideshow(argv[1]); rl.setPrompt("slideshow(" + argv[1] + ")> "); } } /* process API-derived commands */ else { if (ss === null) console.log(chalk.red("ERROR: you have to choose with \"use\" an application first")); else { ss[argv[0]](argv[1]).then(function (response) { console.log(chalk.green(JSON.stringify(response, null, " "))); rl.prompt(); }, function (error) { console.log(chalk.red("ERROR: " + error)); rl.prompt(); }); prompt = false; } } } /* provide prompt for next iteration */ if (prompt) rl.prompt(); }); /* gracefully stop CLI */ rl.on("close", function() { console.log(""); process.exit(0); }); }; /* the batch CLI variant */ var cliBatch = function (argv) { if (argv.length === 1 && argv[0] === "help") { Object.keys(commands).forEach(function (cmd) { if (cmd !== "use" && cmd !== "help") { console.log(chalk.green("slideshow <application> " + cmd + " " + ( commands[cmd].map(function (arg) { return "<" + arg + ">"; }).join(" ") ))); } }); process.exit(0); } if (argv.length < 2) { console.log(chalk.red("ERROR: invalid number of arguments (use \"help\" for usage)")); process.exit(1); } if (typeof apps[argv[0]] === "undefined") { console.log(chalk.red("ERROR: invalid application (expected: " + Object.keys(apps).join(", ") + ")")); process.exit(1); } var ss = new slideshow(argv[0]); var info = commands[argv[1]]; if (typeof info === "undefined") { console.log(chalk.red("ERROR: invalid connector command (use \"help\" for usage)")); process.exit(1); } else if (info.length !== (argv.length - 2)) { console.log(chalk.red("ERROR: invalid number of connector arguments (expected: " + info.join(" ") + ")")); process.exit(1); } ss[argv[1]](argv[2]).then(function (response) { console.log(chalk.green(JSON.stringify(response, null, " "))); process.exit(0); }, function (error) { console.log(chalk.red("ERROR: " + error)); process.exit(1); }); }; /* dispatch according to type of operation */ if (process.argv.length === 2) cliInteractive(); else cliBatch(process.argv.splice(2));
JavaScript
0
@@ -1,8 +1,28 @@ +#!/usr/bin/env node%0A /*%0A** s
de72a7d3ef475d75033ce2c87b411d4fb326e77a
Fix CSP-headers
scripts/headers.js
scripts/headers.js
module.exports = { 'Content-Security-Policy-Report-Only': [ `default-src 'self'`, `script-src 'self' https://*.firebaseio.com/ https://unpkg.com`, `style-src 'self' 'unsafe-inline' blob: https://fonts.googleapis.com/`, `font-src 'self' https://fonts.gstatic.com/`, `img-src 'self' data blob: https://content.dropboxapi.com/ https://www.gravatar.com/avatar/`, `child-src 'self' blob`, `connect-src 'self' blob: wss://*.firebaseio.com/ https://*.googleapis.com/ https://*.dropboxapi.com/`, `frame-src 'self' https://*.firebaseio.com/`, `object-src 'none'`, `worker-src 'self' blob:`, `report-uri https://sjofartstidningen.report-uri.com/r/d/csp/reportOnly`, ].join('; '), 'X-Frame-Options': 'SAMEORIGIN', 'X-XSS-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer-when-downgrade', 'Expect-CT': 'max-age=0, report-uri="https://sjofartstidningen.report-uri.com/r/d/ct/reportOnly"', };
JavaScript
0.000002
@@ -300,16 +300,17 @@ lf' data +: blob: h @@ -401,16 +401,23 @@ lf' blob +: data: %60,%0A %60
bbbf40af14e7a187e563c2a6b0a9be46a89ca5ff
Fix #2 HTML templates not minified
gulp/tasks/scripts.js
gulp/tasks/scripts.js
const browserify = require('browserify'); const watchify = require('watchify'); const gulp = require('gulp'); const $ = require('gulp-load-plugins')(); const config = require('../config'); const source = require('vinyl-source-stream'); const buffer = require('vinyl-buffer'); let bundler = browserify(config.scripts.sources) .transform('babelify', { presets: ['es2015'] }) .transform('stringify', { appliesTo: { includeExtensions: ['.html'] }, }) .transform('browserify-ngannotate') .transform('browserify-css'); function bundle() { const stream = bundler.bundle() .pipe($.plumber()) .pipe(source(`${config.scripts.destinationName}.js`)) .pipe(buffer()) .pipe(gulp.dest(config.dist)); if (config.production) { stream .pipe($.sourcemaps.init({ loadMaps: true, })) .pipe($.uglify()) .pipe($.rename({ extname: '.min.js', })) .pipe($.rev()) .pipe($.sourcemaps.write('./')) .pipe(gulp.dest(config.dist)); } stream.pipe($.connect.reload()); return stream; } gulp.task('build:scripts', bundle); gulp.task('watch:scripts', () => { bundler = watchify(bundler); bundler.on('update', () => gulp.start('build:scripts')); });
JavaScript
0.000245
@@ -446,16 +446,47 @@ ml'%5D %7D,%0A + minify: config.production,%0A %7D)%0A .
1c25a5f71f43b66acc6acaefc3c1d6562b816ebf
Stop capturing stderr for the test resutls, so we can dump stuff in stderr and not have it mess up the json to xml conversion.
gulp/tasks/testing.js
gulp/tasks/testing.js
// Use the gulp-help plugin which defines a default gulp task // which lists what tasks are available. var gulp = require('gulp-help')(require('gulp')); // Process and file manipulation to capture stdout // from the Cucumber tests. var spawn = require('child_process').spawn; var fs = require('fs'); // Sequential Gulp tasks var runSequence = require('run-sequence').use(gulp); var projectPaths = require('../../package.json').paths; var path = require('path'); var cucumber = require('gulp-cucumber'); var jasmine = require('gulp-jasmine'); var jasmineReporters = require('jasmine-reporters'); // Parse any command line arguments ignoring // Node and the name of the calling script. var argv = require('minimist')(process.argv.slice(2)); // Extract arguments for the Cucumber tasks. var tags = argv.tags || false; var reporter = argv.reporter || false; // Create the reporters for Jamsine. var terminalReporter = new jasmineReporters.TerminalReporter({ color: true, verbosity: 3 }); var jUnitXmlReporter = new jasmineReporters.JUnitXmlReporter({ savePath: path.normalize(projectPaths['test-output-dir']), filePrefix: 'unitTests', consolidateAll: true }); function createCucumberOptions(tags, reporter) { return { support: projectPaths['cucumber-support-js'], tags: tags, format: reporter || 'summary' }; } // Run all the Cucumber features, doesn't start server gulp.task('test:cucumber', 'Run Cucumber alone, output to stdout', function() { return gulp.src(projectPaths['feature-files']) .pipe(cucumber(createCucumberOptions(tags, reporter))); }, { options: {'tags': 'Supports optional tags argument e.g.\n\t\t\t--tags @parsing\n\t\t\t--tags @tag1,orTag2\n\t\t\t--tags @tag1 --tags @andTag2\n\t\t\t--tags @tag1 --tags ~@andNotTag2'} }); // TODO convert the JSON output to XML output. // Write Cucumber JSON output to file. // Starting a new Cucumber process and captuting stdout is a work around // Until CucmberJS supports arbitrary plugins at which point I'd // hope a stream based reporter could be to gulp-cucumber and the // results could be put in file in the normal Gulp way // https://github.com/vgamula/gulp-cucumber/issues/17 gulp.task('test:cucumber:fileoutput', 'Run Cucumber, only output JSON to file.', function(done) { var baseEncoding = 'utf8'; var outPath = path.join(projectPaths['test-output-dir'], 'cucumber.json'); var fileStream = fs.createWriteStream(outPath, { encoding: baseEncoding }); // The command args to run. // Use Cucumber JSON reporter with the intent to feed it to the Cucumber XML converter. // Use the Gulp --silent option to reduce the output to Cucumber JSON only. var commandArgs = ['test:cucumber', '--silent', '--reporter', 'json']; // Pass through any tags arguments. // Can be string or array so use // concat to gaurantee array. if (tags) { tags = [].concat(tags); commandArgs = tags.reduce(function(previous, current) { return previous.concat(['--tags', current]); }, commandArgs); } var stream = spawn('./node_modules/.bin/gulp', commandArgs); stream.stdout.setEncoding(baseEncoding); stream.stderr.setEncoding(baseEncoding); stream.stderr.pipe(fileStream); stream.stdout.pipe(fileStream); stream.on('close', function(e) { fileStream.end(); done(e); }); }, { options: {'tags': 'Supports same optional tags arguments as \'test:cucumber\' task.'} }); // The default Cucumber test run requires the server to be running. gulp.task('test:features', 'Everything necessesary to test the features.', function(done) { runSequence('set-envs:test', 'server:start', 'test:cucumber', function () { runSequence('server:stop', done); }); }, { options: {'tags': 'Supports same optional tags arguments as \'test:cucumber\' task.'} }); // The default Cucumber test run requires server to be running. gulp.task('test:features:fileoutput', 'Everything necessesary to test the features and send the output to file.', function(done) { runSequence('set-envs:test', 'server:start', 'test:cucumber:fileoutput', function () { runSequence('server:stop', done); }); }, { options: {'tags': 'Supports same optional tags arguments as \'test:cucumber\' task.'} }); // Run the unit tests, report to terminal and disk. gulp.task('test:unit', 'Run the unit tests.', function () { return gulp.src(projectPaths['unit-test-js']) .pipe(jasmine({ reporter: [ terminalReporter, jUnitXmlReporter ] })); });
JavaScript
0
@@ -3130,85 +3130,8 @@ g);%0A - stream.stderr.setEncoding(baseEncoding);%0A stream.stderr.pipe(fileStream);%0A st
0bfd373e07efc1622bfe253c79d8a60810121cc2
Improve binary version verification error message (#409)
scripts/install.js
scripts/install.js
#!/usr/bin/env node 'use strict'; const fs = require('fs'); const http = require('http'); const os = require('os'); const path = require('path'); const HttpsProxyAgent = require('https-proxy-agent'); const fetch = require('node-fetch'); const ProgressBar = require('progress'); const Proxy = require('proxy-from-env'); const helper = require('../js/helper'); const pkgInfo = require('../package.json'); const CDN_URL = process.env.SENTRYCLI_LOCAL_CDNURL || process.env.npm_config_sentrycli_cdnurl || process.env.SENTRYCLI_CDNURL || 'https://github.com/getsentry/sentry-cli/releases/download'; function getDownloadUrl(platform, arch) { const releasesUrl = `${CDN_URL}/${pkgInfo.version}/sentry-cli`; const archString = arch.indexOf('64') > -1 ? 'x86_64' : 'i686'; switch (platform) { case 'darwin': return `${releasesUrl}-Darwin-x86_64`; case 'win32': return `${releasesUrl}-Windows-${archString}.exe`; case 'linux': case 'freebsd': return `${releasesUrl}-Linux-${archString}`; default: return null; } } function createProgressBar(name, total) { if (process.stdout.isTTY) { return new ProgressBar(`fetching ${name} :bar :percent :etas`, { complete: '█', incomplete: '░', width: 20, total, }); } if (/yarn/.test(process.env.npm_config_user_agent)) { let pct = null; let current = 0; return { tick: length => { current += length; const next = Math.round((current / total) * 100); if (next > pct) { pct = next; process.stdout.write(`fetching ${name} ${pct}%\n`); } }, }; } return { tick: () => {} }; } function downloadBinary() { const arch = os.arch(); const platform = os.platform(); const outputPath = path.resolve( __dirname, platform === 'win32' ? '../bin/sentry-cli.exe' : '../sentry-cli' ); if (fs.existsSync(outputPath)) { return Promise.resolve(); } const downloadUrl = getDownloadUrl(platform, arch); if (!downloadUrl) { return Promise.reject(new Error(`unsupported target ${platform}-${arch}`)); } const proxyUrl = Proxy.getProxyForUrl(downloadUrl); const agent = proxyUrl ? new HttpsProxyAgent(proxyUrl) : null; // temporary fix for https://github.com/TooTallNate/node-https-proxy-agent/pull/43 if (agent) { agent.defaultPort = 443; } return fetch(downloadUrl, { redirect: 'follow', agent }).then(response => { if (!response.ok) { throw new Error(`Received ${response.status}: ${response.statusText}`); } const name = downloadUrl.match(/.*\/(.*?)$/)[1]; const total = parseInt(response.headers.get('content-length'), 10); const progressBar = createProgressBar(name, total); return new Promise((resolve, reject) => { response.body .on('error', e => reject(e)) .on('data', chunk => progressBar.tick(chunk.length)) .pipe(fs.createWriteStream(outputPath, { mode: '0755' })) .on('error', e => reject(e)) .on('close', () => resolve()); }); }); } function checkVersion() { return helper.execute(['--version']).then(output => { const version = output.replace('sentry-cli ', '').trim(); const expected = process.env.SENTRYCLI_LOCAL_CDNURL ? 'DEV' : pkgInfo.version; if (version !== expected) { throw new Error(`Unexpected sentry-cli version: ${version}`); } }); } if (process.env.SENTRYCLI_LOCAL_CDNURL) { // For testing, mock the CDN by spawning a local server const server = http.createServer((request, response) => { const contents = fs.readFileSync(path.join(__dirname, '../js/__mocks__/sentry-cli')); response.writeHead(200, { 'Content-Type': 'application/octet-stream', 'Content-Length': String(contents.byteLength), }); response.end(contents); }); server.listen(8999); process.on('exit', () => server.close()); } downloadBinary() .then(() => checkVersion()) .then(() => process.exit(0)) .catch(e => { // eslint-disable-next-line no-console console.error(e.toString()); process.exit(1); });
JavaScript
0
@@ -3354,16 +3354,25 @@ w Error( +%0A %60Unexpec @@ -3393,18 +3393,18 @@ version -: +%22 $%7Bversio @@ -3405,17 +3405,48 @@ version%7D -%60 +%22, expected %22$%7Bexpected%7D%60%0A );%0A %7D
d7292a6243474324891caec88ef94d06f55cc009
Check routes before internal mappings to give full control over weird fact that Helma returns mappings as children (it should not...).
type/helma/Root/routes.js
type/helma/Root/routes.js
// Install UrlRouting in the root object, so other modules can install routes // for Root without having to define getChildElement again. UrlRouting.draw(this, {}); Root.inject({ getChildElement: function(name) { // TODO: Fix Helma bug where mappings are returned before subnodes. // e.g. this.get('Users') and this.users should not return the same! // WORKAROUND: Fetch from pure children list first, then if not found // try properties too (e.g. resources, etc) var obj = this.children.get(name); if (!obj) { obj = this.base(name); if (!obj) obj = UrlRouting.handle(this, name); } return obj; } });
JavaScript
0
@@ -526,48 +526,144 @@ %0A%09%09%09 -obj = this.base(name);%0A%09%09%09if (!obj) +// Try url routes first, this.base as last, to really offer multiple%0A%09%09%09// ways to interfere with Helma returning internal mappings. %0A%09%09%09 -%09 obj @@ -695,16 +695,56 @@ name);%0A +%09%09%09if (!obj)%0A%09%09%09%09obj = this.base(name);%0A %09%09%7D%0A%09%09re
76a414329558a780cb815f16ca56a0068cef9811
Update node version check and remove unneccesary steps in publish script (#1151)
scripts/publish.js
scripts/publish.js
#!/usr/bin/env node const shell = require('shelljs'); shell.set('-e'); shell.set('+v'); /* * Assumptions: * 0. You have shelljs installed globally using `npm install -g shelljs`. * 1. The script is running locally - it's not optimized for Travis workflow * yet. * 2. The script is running in the right branch (e.g., release/vxx.y.z) * * Instructions: * Run this script with SALESFORCEDX_VSCODE_VERSION as an environment variable * i.e. SALESFORCEDX_VSCODE_VERSION=x.y.z ./scripts/publish.js * */ // Checks that you are running this with Node v8.9.0 and above const [version, major, minor, patch] = process.version.match( /^v(\d+)\.?(\d+)\.?(\*|\d+)$/ ); if (parseInt(major) !== 8 || parseInt(minor) < 9) { console.log( 'You do not have the right version of node. We require version 8.9.0.' ); process.exit(-1); } // Checks that you have access to our bucket on AWS const awsExitCode = shell.exec( 'aws s3 ls s3://dfc-data-production/media/vscode/SHA256.md', { silent: true } ).code; if (awsExitCode !== 0) { console.log( 'You do not have the s3 command line installed or you do not have access to the aws s3 bucket.' ); process.exit(-1); } // Checks that you have access to the salesforce publisher const publishers = shell.exec('vsce ls-publishers', { silent: true }).stdout; if (!publishers.includes('salesforce')) { console.log( 'You do not have the vsce command line installed or you do not have access to the salesforce publisher id as part of vsce.' ); process.exit(-1); } // Checks that you have specified the next version as an environment variable, and that it's properly formatted. const nextVersion = process.env['SALESFORCEDX_VSCODE_VERSION']; if (!nextVersion) { console.log( 'You must specify the next version of the extension by setting SALESFORCEDX_VSCODE_VERSION as an environment variable.' ); process.exit(-1); } else { const [version, major, minor, patch] = nextVersion.match( /^(\d+)\.(\d+)\.(\d+)$/ ); const currentBranch = shell.exec('git rev-parse --abbrev-ref HEAD', { silent: true }).stdout; if (!currentBranch.includes('/v' + nextVersion)) { console.log( `You must execute this script in a release branch including SALESFORCEDX_VSCODE_VERSION (e.g, release/v${nextVersion} or hotfix/v${nextVersion})` ); process.exit(-1); } } // Checks that a tag of the next version doesn't already exist const checkTags = shell.exec('git tag', { silent: true }).stdout; if (checkTags.includes(nextVersion)) { console.log( 'There is a conflicting git tag. Reclone the repository and start fresh to avoid versioning problems.' ); process.exit(-1); } // Real-clean shell.exec('git clean -xfd -e node_modules'); // Install and bootstrap shell.exec('npm install'); // Compile shell.exec('npm run compile'); // lerna publish // --skip-npm to increment the version number in all packages but not publish to npmjs // This will still make a commit in Git with the tag of the version used shell.exec( `lerna publish --force-publish --exact --repo-version ${nextVersion} --yes --skip-npm` ); // Generate the .vsix files shell.exec(`npm run vscode:package`); // Generate the SHA256 and append to the file shell.exec(`npm run vscode:sha256`); // Concatenate the contents to the proper SHA256.md shell.exec('./scripts/concatenate-sha256.js'); // Remove the temp SHA256 file shell.rm('./SHA256'); // Push the SHA256 to AWS shell.exec( 'aws s3 cp ./SHA256.md s3://dfc-data-production/media/vscode/SHA256.md' ); // Add SHA256 to git shell.exec(`git add SHA256.md`); // Git commit shell.exec(`git commit -m "Updated SHA256"`); // Add formatting changes shell.exec(`git add .`); // Commit back changes after reformatting shell.exec(`git commit -m "Reformat for lerna"`); // Publish to VS Code Marketplace shell.exec(`npm run vscode:publish`);
JavaScript
0
@@ -553,19 +553,20 @@ h Node v -8.9 +10.2 .0 and a @@ -691,17 +691,18 @@ or) !== -8 +10 %7C%7C pars @@ -715,17 +715,17 @@ inor) %3C -9 +2 ) %7B%0A co @@ -806,11 +806,12 @@ ion -8.9 +10.2 .0.' @@ -3659,153 +3659,8 @@ );%0A%0A -// Add formatting changes%0Ashell.exec(%60git add .%60);%0A%0A// Commit back changes after reformatting%0Ashell.exec(%60git commit -m %22Reformat for lerna%22%60);%0A%0A // P
c455d73cba988361df5398fb4afb2face2779185
check for wrong input or arguments
treeJson.js
treeJson.js
var fs = require("fs"); var _ = require("underscore"); var pathModule = require("path"); function makeTree(directoryPath, parentName, nodeName, nodeChildren, exclude, allowedExtensions) { var excluded_nodes = exclude ? exclude : []; var allowed_extensions = allowedExtensions ? allowedExtensions : []; var path = directoryPath ? directoryPath : ""; if (!path) throw new Error("Invalid file Name or got undefined"); else { var pathArray = directoryPath.split("/"); var parentSplitIndex = pathArray.lastIndexOf("/"); var parent_name = parentName ? [] : pathArray.splice(parentSplitIndex+1, 1)[0]; var node_name = nodeName ? nodeName : "parent_node"; var node_children = nodeChildren ? nodeChildren : "child_nodes"; function createNode(nodeName) { var nodeObject = {}; nodeObject[node_name] = nodeName; nodeObject.type = "folder"; nodeObject[node_children] = []; return nodeObject; } function generateTree(path, currentObject, previousObject) { var stats = fs.statSync(path); if (stats.isDirectory()) { var files = fs.readdirSync(path); for (var index = 0; index < files.length; index++) { if (!_.includes(excluded_nodes, files[index])) { var newNode = createNode(files[index]); currentObject[node_children].push(newNode); generateTree(path + "/" + files[index], newNode, currentObject); } } } else if (stats.isFile()) { if (_.includes(allowed_extensions, pathModule.extname(currentObject[node_name]))) { delete currentObject[node_children]; currentObject.type = "file"; } else { var indexOFexludedFile = previousObject[node_children].indexOf(currentObject); previousObject[node_children].splice(indexOFexludedFile,1); } } return currentObject; } return JSON.stringify(generateTree(path, createNode(parent_name), null), 4); } }; module.exports = makeTree;
JavaScript
0.000001
@@ -122,66 +122,11 @@ th, -parentName, nodeName, nodeChildren, exclude, allowedExtens +opt ions @@ -155,16 +155,24 @@ nodes = +options. exclude @@ -173,16 +173,24 @@ clude ? +options. exclude @@ -225,16 +225,24 @@ sions = +options. allowedE @@ -253,16 +253,24 @@ sions ? +options. allowedE @@ -366,61 +366,71 @@ -throw new Error(%22Invalid file Name or got undefined%22) +return;%0D%0A else if (path.indexOf(%22/%22) === -1)%0D%0A return ;%0D%0A @@ -628,17 +628,19 @@ litIndex -+ + + 1, 1)%5B0%5D @@ -666,16 +666,24 @@ _name = +options. nodeName @@ -685,16 +685,24 @@ eName ? +options. nodeName @@ -748,16 +748,24 @@ ldren = +options. nodeChil @@ -771,16 +771,24 @@ ldren ? +options. nodeChil @@ -806,24 +806,26 @@ ld_nodes%22;%0D%0A +%0D%0A func @@ -1055,32 +1055,34 @@ ct;%0D%0A %7D%0D%0A +%0D%0A function @@ -1979,33 +1979,16 @@ else -%0D%0A %7B%0D%0A @@ -2027,17 +2027,16 @@ edFile = - previou @@ -2159,16 +2159,17 @@ dedFile, + 1);%0D%0A @@ -2344,16 +2344,26 @@ %0D%0A%7D;%0D%0A%0D%0A +%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A module.e
2843bdf40e5d3a1f40c61eab3eb8890488c691b8
Add source on NuGet push
scripts/release.js
scripts/release.js
#!/usr/local/bin/jbash /* Releases dbup-sqlserver-scripting This includes: building in release mode, packaging, and publishing on NuGet, creating a GitHub release, uploading .nupkg to GitHub release. Example: release.sh 2.0.0 "Fixed DOW bug causing exception" */ // Halt on an error set("-e"); // cd to root dir cd(`${__dirname}/../`); if (args.length != 2) { echo(` Usage: release.sh version "Release notes..." Example: release.js 2.0.0 "Fixed bug causing exception"`); exit(1); } if ($(`git status --porcelain`)) { echo(`All changes must be committed first.`); exit(1); } let projectId = "dbup-sqlserver-scripting"; let projectName = "DbUp.Support.SqlServer.Scripting"; let version = args[0]; let notes = args[1]; let preRelease = version.indexOf("-") > -1; // If version contains a '-' character (i.e. 2.0.0-alpha-1) we will consider this a pre-release let projectCopyright = `Copyright ${(new Date).getFullYear()}`; let ghRepo = "bradyholt/dbup-sqlserver-scripting"; let buildDirectory = "tmp"; // Restore NuGet pakcages and build in release mode eval(`nuget restore`); eval(`xbuild /property:Configuration=Release ${projectName}.sln`); // Create NuGet package eval(`mkdir -p ${buildDirectory}/pack/lib/net35`) eval(`cp dbup-sqlserver-scripting.nuspec tmp/pack`) eval(`cp -r tools dbup-sqlserver-scripting.nuspec ${buildDirectory}/pack/`) eval(`cp -r ${projectName}/bin/Release/${projectName}.* ${buildDirectory}/pack/lib/net35`) eval(`nuget pack ${buildDirectory}/pack/${projectId}.nuspec -Properties "version=${version};notes=v${version} - ${notes};copyright=${projectCopyright}" -OutputDirectory ${buildDirectory}`) let nupkgFile = `${buildDirectory}/${projectId}.${version}.nupkg`; // Push NuGet package eval(`nuget push ${nupkgFile}`) // Commit changes to project file eval(`git commit -am "New release: ${version}"`); // Create release tag eval(`git tag -a ${version} -m "${notes}"`); eval(`git push --follow-tags`); // Create release on GitHub let response = $(`curl -f -H "Authorization: token ${env.GITHUB_API_TOKEN}" \ -d '{"tag_name":"${version}", "name":"${version}","body":"${notes}","prerelease": ${preRelease}}' \ https://api.github.com/repos/${ghRepo}/releases` ); let releaseId = JSON.parse(response).id; // Get the release id and then upload the and upload the .nupkg eval(`curl -H "Authorization: token ${env.GITHUB_API_TOKEN}" -H "Content-Type: application/octet-stream" \ --data-binary @"${nupkgFile}" \ https://uploads.github.com/repos/${ghRepo}/releases/${releaseId}/assets?name=${nupkgFile}`); eval(`rm -r ${buildDirectory}`) echo(`DONE! Released version ${version} to NuGet and GitHub.`);
JavaScript
0.000001
@@ -1768,16 +1768,61 @@ pkgFile%7D + -Source https://www.nuget.org/api/v2/package %60)%0A%0A// C
adb4b475aeab362438bd4c4f19509ad91b6d4c30
Fix Complex.sqrt
Complex.js
Complex.js
/** @param {number} re * @param {number} im * @constructor */ function Complex(re, im) { this.re = re; this.im = im; } /** @return {number} */ Complex.prototype.abs = function() { return Math.sqrt(this.abs2()); }; /** @return {number} */ Complex.prototype.abs2 = function() { return this.re * this.re + this.im * this.im; }; /** @param {Complex} a * @param {Complex} b * @return {Complex} */ Complex.add = function(a, b) { return new Complex(a.re + b.re, a.im + b.im); }; /** @param {Complex} b * @return {Complex} */ Complex.prototype.add = function(b) { return Complex.add(this, b); }; /** @param {Complex} a * @param {Complex} b * @return {Complex} */ Complex.div = function(a, b) { var abs2 = b.abs2(); var re = a.re * b.re + a.im * b.im; var im = a.im * b.re - a.re * b.im; return new Complex(re / abs2, im / abs2); }; /** @param {Complex} z * @return {Complex} */ Complex.inv = function(z) { var abs2 = z.abs2(); return new Complex(z.re / abs2, -z.im / abs2); }; /** @param {Complex} a * @param {Complex} b * @return {Complex} */ Complex.mul = function(a, b) { return new Complex(a.re * b.re - a.im * b.im, a.re * b.im + a.im * b.re); }; /** @param {Complex} b * @return {Complex} */ Complex.prototype.mul = function(b) { return Complex.mul(this, b); }; /** @return {Complex} */ Complex.prototype.neg = function() { return new Complex(-this.re, -this.im); }; /** @type {Complex} */ Complex.one = new Complex(1, 0); /** @param {number} re * @return {Complex} */ Complex.real = function(re) { return new Complex(re, 0); }; /** @param {Complex} z * @return {Complex} */ Complex.sqrt = function(z) { var r = z.abs(); var s = Math.sign(z.im); return new Complex(Math.sqrt((r + z.re) * 0.5), s * Math.sqrt((r - z.re) * 0.5)); }; /** @param {Complex} a * @param {Complex} b * @return {Complex} */ Complex.sub = function(a, b) { return new Complex(a.re - b.re, a.im - b.im); }; /** @type {Complex} */ Complex.zero = new Complex(0, 0); Complex.prototype.zero = Complex.zero;
JavaScript
0.000143
@@ -1025,32 +1025,152 @@ im / abs2);%0A%7D;%0A%0A +/** @param %7BComplex%7D z%0A * @return %7Bboolean%7D */%0AComplex.isZero = function(z) %7B%0A return z.re === 0 && z.im === 0;%0A%7D;%0A%0A /** @param %7BComp @@ -1809,32 +1809,88 @@ = function(z) %7B%0A + if (Complex.isZero(z))%0A return Complex.zero;%0A var r = z.ab @@ -1921,16 +1921,21 @@ gn(z.im) + %7C%7C 1 ;%0A re
c51d5627131cf73e44bdc7f5bf9afc89b0c68651
change tilemap color
src/Preloader.js
src/Preloader.js
/** * * The Preloader state is used to preload assets before the MainMenu is displayed. Once assets have been loaded the Preloader state * will start the MainMenu state */ Game.Preloader = function(game) { }; Game.Preloader.prototype = { preload:function(){ var preloadBG = this.add.sprite((this.world.width-580)*0.5, (this.world.height+150)*0.5, 'loading-background'); var preloadProgress = this.add.sprite((this.world.width-540)*0.5, (this.world.height+170)*0.5, 'loading-progress'); this.load.setPreloadSprite(preloadProgress); this.preloadResources(); //this.load.script('webfont', '//ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js'); }, preloadResources: function() { var pack = Game.Preloader.resources; for(var method in pack) { pack[method].forEach(function(args){ var loader = this.load[method]; loader && loader.apply(this.load, args); }, this); } }, create:function(){ this.state.start('MainMenu'); } }; Game.Preloader.resources = { /* * Load all game resources */ 'image' : [ ['dot32', 'assets/img/dot32.png'], ['bigDot32', 'assets/img/bigDot32.png'], ['cTile32', 'assets/img/purpleTileset.png'], ['down', 'assets/img/down.png'], ['left', 'assets/img/left.png'], ['right', 'assets/img/right.png'], ['up', 'assets/img/up.png'], ['circle', 'assets/img/circle.png'], ['story-bg', 'assets/img/Packground.png'], ['bg-story', 'assets/img/StoryBackgroundBlur.png'], ['logo', 'assets/img/Logo.png'], ['instructions', 'assets/img/instructions.png'], ['overlay', 'assets/img/overlay.png'], ['ui-bg', 'assets/img/ui-bg.png'], ['particle', 'assets/img/particle.png'], ['black', 'assets/img/black.png'], ['cup', 'assets/img/trophy.png'], ['congrats', 'assets/img/congrats.png'], ['coupon-one', 'assets/img/dealercoupon.png'], ['coupon-two', 'assets/img/dealercoupontwo.png'], ['coupon-three', 'assets/img/dealercouponthree.png'] ], 'atlasXML': [ ['spark', 'assets/atlasXML/spark.png', 'assets/atlasXML/spark.xml'] ], 'audio': [ ['level_music', ['assets/audio/finalMainLoop.mp3', 'assets/audio/finalMainLoop.ogg']], ['menu_music', ['assets/audio/menuLoop.mp3', 'assets/audio/menuLoop.ogg']], ['big_eat_sfx', ['assets/audio/bigEat.mp3', 'assets/audio/bigEat.ogg']], ['ghost_eat_sfx', ['assets/audio/ghostEat.mp3','assets/audio/ghostEat.ogg']], ['lose', ['assets/audio/lose.mp3', 'assets/audio/lose.ogg']], ['win', ['assets/audio/win.mp3', 'assets/audio/win.ogg']] ], 'tilemap': [ ['pmap32', 'assets/maps/pmap32.csv'], ['pmapdesk', 'assets/maps/pmapdesk.csv'] ], 'spritesheet': [ ['csprites32','assets/img/chompersprites32.png', 32, 32], ['cSpTile32', 'assets/img/chompermazetiles32g.png', 32, 32], ['downs', 'assets/img/downs.png', 143,182], ['lefts', 'assets/img/lefts.png', 182, 143], ['rights', 'assets/img/rights.png', 182, 143], ['ups', 'assets/img/ups.png', 143,182], ['button-start', 'assets/img/button-start.png', 180, 180], ['button-rules', 'assets/img/rules-btn.png', 110, 40], ['button-play', 'assets/img/play-btn.png', 475, 140], ['button-continue', 'assets/img/button-continue.png', 180, 180], ['button-mainmenu', 'assets/img/button-mainmenu.png', 180, 180], ['button-restart', 'assets/img/button-tryagain.png', 180, 180], ['button-achievements', 'assets/img/button-achievements.png', 110, 110], ['button-pause', 'assets/img/button-pause.png', 80, 80], ['button-audio', 'assets/img/button-sound.png', 80, 80], ['button-back', 'assets/img/button-back.png', 70, 70], ['claim-prize-btn', 'assets/img/claimPrizes.png', 400, 60] ] };
JavaScript
0
@@ -1300,21 +1300,27 @@ img/ -purpleT +chompermazet iles -et +32g .png
26c63306f8260bcfd49ddf6ebdf57cc1ab41d18a
Fix a null bug and add a default element filter.
src/analytics.js
src/analytics.js
/** * analytics.js - Provides an abstraction over code that calls Google Analytics * for user tracking. Attaches to router:navigation:success event to track when * a page has been loaded. Registers a click event handler for elements that are defined * in the filter function to track clicks. */ 'use strict'; import {inject} from 'aurelia-dependency-injection'; import {EventAggregator} from 'aurelia-event-aggregator'; import * as LogManager from 'aurelia-logging'; /* .plugin('aurelia-google-analytics', config => { config.init('<Tracker ID here>'); config.attach({ logging: { enabled: true }, pageTracking: { enabled: true }, clickTracking: { enabled: true, filter: () => { return element instanceof HTMLElement && (element.nodeName.toLowerCase() === 'a' || element.nodeName.toLowerCase() === 'button'); } } }); }) */ const defaultOptions = { logging: { enabled: true }, pageTracking: { enabled: false }, clickTracking: { enabled: false } }; const criteria = { isElement: function(e) { return e instanceof HTMLElement; }, hasClass: function(cls) { return function(e) { return criteria.isElement(e) && e.classList.contains(cls); } }, hasTrackingInfo: function(e) { return criteria.isElement(e) && e.hasAttribute('data-analytics-category') && e.hasAttribute('data-analytics-action'); }, isOfType: function(e, type) { return criteria.isElement(e) && e.nodeName.toLowerCase() === type.toLowerCase(); }, isAnchor: function(e) { return criteria.isOfType(e, 'a'); }, isButton: function(e) { return criteria.isOfType(e, 'button'); } }; const delegate = function(criteria, listener) { return function(evt) { let el = evt.target; do { if(!criteria(el)) continue; evt.delegateTarget = el; listener.apply(this, arguments); return; } while( (el = el.parentNode) ); }; }; @inject(EventAggregator) export class Analytics { constructor(eventAggregator) { this._eventAggregator = eventAggregator; this._initialized = false; this._logger = LogManager.getLogger('analytics-plugin'); this._options = defaultOptions; this._trackClick = this._trackClick.bind(this); this._trackPage = this._trackPage.bind(this); } attach(options = defaultOptions) { this._options = Object.assign({}, defaultOptions, options); if(!this._initialized) { const errorMessage = "Analytics must be initialized before use."; this._log('error', errorMessage); throw new Error(errorMessage); } this._attachClickTracker(); this._attachPageTracker(); } init(id) { const script = document.createElement('script'); script.text = "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){" + "(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o)," + "m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)" + "})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');"; document.querySelector('body').appendChild(script); window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date; ga('create', id, 'auto'); this._initialized = true; } _attachClickTracker() { if(!this._options.clickTracking.enabled) { return; } document.querySelector('body') .addEventListener('click', delegate(this._options.clickTracking.filter, this._trackClick)); } _attachPageTracker() { if(!this._options.pageTracking.enabled) { return; } this._eventAggregator.subscribe('router:navigation:success', payload => this._trackPage(payload.instruction.fragment, payload.instruction.config.title)); } _log(level, message) { if(!this._options.logging.enabled) { return; } this._logger[level](message); } _trackClick(evt) { if(!this._initialized) { this._log('warn', "The component has not been initialized. Please call 'init()' before calling 'attach()'."); return; } if(!evt || !evt.delegateTarget || !criteria.hasTrackingInfo(evt.delegateTarget)) { return }; const element = evt.delegateTarget; const tracking = { category: element.getAttribute('data-analytics-category'), action: element.getAttribute('data-analytics-action'), label: element.getAttribute('data-analytics-label') }; this._log('debug', `click: category '${tracking.category}', action '${tracking.action}', label '${tracking.label}'`); ga('send', 'event', tracking.category, tracking.action, tracking.label); } _trackPage(path, title) { this._log('debug', `Tracking path = ${path}, title = ${title}`); if(!this._initialized) { this._log('warn', "Try calling 'init()' before calling 'attach()'."); return; } ga('set', { page: path, title: title }); ga('send', 'pageview'); } }
JavaScript
0
@@ -717,16 +717,23 @@ ilter: ( +element ) =%3E %7B%0A%09 @@ -1038,16 +1038,200 @@ d: false +,%0A filter: (element) =%3E %7B%0A%09%09%09%09%09%09return element instanceof HTMLElement &&%0A%09%09%09%09%09%09(element.nodeName.toLowerCase() === 'a' %7C%7C%0A%09%09%09%09%09%09%09element.nodeName.toLowerCase() === 'button');%0A%09%09%09%09%09%7D %0A%09%7D%0A%7D;%0A%0A @@ -1956,17 +1956,30 @@ %7B%0A%09%09%09if -( + (criteria && !criteri @@ -1984,16 +1984,24 @@ ria(el)) +%0A continu
633b3c1396cbcbb273860a78c4eba316ab298ab9
fix themeEngine config with a default config
lib/themeEngine/loadThemeConfig.js
lib/themeEngine/loadThemeConfig.js
var _ = require('lodash'); var path = require ('path'); var configCache = null; /** * Load project theme configs * * @param {String} projectPath * @return {object} project plugin configs */ module.exports = function loadThemeConfig(projectPath) { if (! _.isEmpty(configCache) ) return configCache; if (!projectPath) projectPath = process.cwd(); var config = {}; var p = path.resolve( projectPath, 'config', 'themes.js' ); // try to load database configs from project database config try { config = require( p ).themes; } catch(e) { if (e.code != 'MODULE_NOT_FOUND' ) { console.error('Unknow error on load theme configs:', e); } // project plugin config file not found throw new Error('Theme config not found in :', p); } configCache = config; return config; }
JavaScript
0
@@ -354,16 +354,17 @@ .cwd();%0A +%0A var co @@ -371,16 +371,86 @@ nfig = %7B +%0A app: 'we-theme-site-wejs',%0A admin: 'we-theme-admin-default'%0A %7D;%0A%0A va @@ -745,107 +745,8 @@ %7D%0A - // project plugin config file not found%0A throw new Error('Theme config not found in :', p);%0A %7D%0A
224153318d538792165be4526d0aace12a898b63
Rename function
src/javascript/binary/websocket_pages/user/new_account/account_type.js
src/javascript/binary/websocket_pages/user/new_account/account_type.js
const BinarySocket = require('../../socket'); const BinaryPjax = require('../../../base/binary_pjax'); const Client = require('../../../base/client'); const urlFor = require('../../../base/url').urlFor; const AccountType = (() => { let url_real, url_ico, container; const onLoad = () => { BinarySocket.wait('landing_company').then((response_lc) => { url_ico = `${urlFor('new_account/realws') }#ico`; url_real = urlFor(Client.getUpgradeInfo(response_lc).upgrade_link); container = document.getElementById('account_type_container'); if(Client.canOpenICO() && container) { container.setVisibility(1); addEventListener(); } else { BinaryPjax.load(url_real); } }); const addEventListener = () => { $(container) .find('#btn_submit') .off('click') .on('click', () => { const value = $(container).find('input[type=radio]:checked').val(); if (value === 'ico') { BinaryPjax.load(url_ico); } else { BinaryPjax.load(url_real); } }); }; }; return { onLoad, }; })(); module.exports = AccountType;
JavaScript
0.000005
@@ -721,32 +721,24 @@ -addEventListener +onSubmit ();%0A @@ -842,24 +842,16 @@ nst -addEventListener +onSubmit = (
a05c1ca5b880767e541ef234b49e4ed93fa6d933
Update twitter.js
src/main/content/jcr_root/apps/wcm/core/clientlibs/sites/js/twitter.js
src/main/content/jcr_root/apps/wcm/core/clientlibs/sites/js/twitter.js
(function(window, document, Granite, $) { "use strict"; var TWITTER_ACTIVATOR = ".cq-siteadmin-admin-actions-twitter-activator"; $(document).on("click", TWITTER_ACTIVATOR, function(e) { var selection = $(".foundation-collection").first().find(".foundation-selections-item").first(); var path = selection.data("foundationCollectionItemId") || selection.data("path"); var ui = $(window).adaptTo("foundation-ui"); var title = Granite.I18n.get("Publish to Twitter"); var message = Granite.I18n.get("Do you want to publish a link to this page to Twitter?"); ui.prompt(title, message, "notice", [ { text: Granite.I18n.get("Yes"), primary: true, id: "yes" }, { text: Granite.I18n.get("No"), id: "no" } ], function (btnId) { if (btnId === "yes") { var notificationSlider = new Granite.UI.NotificationSlider($(".endor-Page-content.endor-Panel.foundation-content")); notificationSlider.notify({ content: Granite.I18n.get("Page is being published to Twitter"), type: "info", closable: true, className: "notification-alert--absolute admin-notification" }); } }); }); })(window, document, Granite, Granite.$);
JavaScript
0.000002
@@ -1,8 +1,667 @@ +/*%0A * #%25L%0A * aem-admin-extension-customize-sites%0A * %25%25%0A * Copyright (C) 2014 Adobe%0A * %25%25%0A * Licensed under the Apache License, Version 2.0 (the %22License%22);%0A * you may not use this file except in compliance with the License.%0A * You may obtain a copy of the License at%0A * %0A * http://www.apache.org/licenses/LICENSE-2.0%0A * %0A * Unless required by applicable law or agreed to in writing, software%0A * distributed under the License is distributed on an %22AS IS%22 BASIS,%0A * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A * See the License for the specific language governing permissions and%0A * limitations under the License.%0A * #L%25%0A */%0A (functio
b96ee5313619f4fde00091b3c42306cb6c44037b
Implement the patchOnePhoto callback for listingController. Close #55
server/config/listings/listingController.js
server/config/listings/listingController.js
const db = require('../../../database/schemas.js'); module.exports = { getOne: (req, res) => { db.Post.findOne({ where: { id: req.params.listId, }, }) .then((listing) => { res.send(listing); }); }, getAll: (req, res) => { db.Post.findAll({}) .then((listings) => { res.send(listings); }); }, createOne: (req, res) => { db.Post.create({ body: req.body.body, tags: req.body.tags, user_id: req.params.id, }) .then((listing) => { res.send(listing); }); }, patchOne: (req, res) => { db.Post.update(req.body, { where: { id: req.params.listId, }, }) .then((status) => { res.send(status); }); }, deleteOne: (req, res) => { db.Post.destroy({ where: { id: req.params.listId, }, }) .then((status) => { if (status === 1) { res.send('listing deleted!'); } else { res.send('listing wasn\'t found'); } }); }, getAllPhotos: (req, res) => { db.Picture.findAll({ where: { post_id: req.params.listId, }, }) .then((photos) => { res.send(photos); }); }, createOnePhoto: (req, res) => { db.Picture.create({ img_name: req.body.img_name, img_path: req.body.img_path, post_id: req.params.listId, }) .then((photoData) => { res.send(photoData); }); }, patchOnePhoto: (req, res) => { }, deleteOnePhoto: (req, res) => { }, };
JavaScript
0
@@ -1476,24 +1476,267 @@ , res) =%3E %7B%0A + db.Picture.update(%0A %7B%0A img_name: req.body.img_name,%0A img_path: req.body.img_path,%0A %7D,%0A %7B%0A where: %7B%0A id: req.params.id,%0A %7D,%0A %7D)%0A .then((status) =%3E %7B%0A res.send(status);%0A %7D); %0A %7D,%0A%0A del
95a8974e002d3fc821b1755e7e60613a56983726
Fix a clash of kings (#273)
server/game/cards/plots/01/aclashofkings.js
server/game/cards/plots/01/aclashofkings.js
const PlotCard = require('../../../plotcard.js'); class AClashOfKings extends PlotCard { setupCardAbilities() { this.reaction({ when: { afterChallenge: (e, challenge) => ( challenge.winner === this.controller && challenge.challengeType === 'power' && challenge.loser.power > 0 ) }, handler: () => { var challenge = this.game.currentChallenge; this.game.addMessage('{0} uses {1} to move 1 power from {2}\'s faction card to their own', challenge.winner, this, challenge.loser); this.game.transferPower(challenge.winner, challenge.loser, 1); } }); } } AClashOfKings.code = '01001'; module.exports = AClashOfKings;
JavaScript
0.005419
@@ -361,16 +361,24 @@ e.loser. +faction. power %3E
ddfde6ef3daf887234148a20fbc23eca16df02ac
Add doc comments to thumbail.js
core/mixins/thumbnail.js
core/mixins/thumbnail.js
import { getThumbnailPath } from '@vue-storefront/core/helpers' export const thumbnail = { methods: { /** * Return thumbnail URL for specific base url and path * @param {string} relativeUrl * @param {number} width * @param {number} height * @param {string} pathType */ getThumbnail: (relativeUrl, width, height, pathType) => getThumbnailPath(relativeUrl, width, height, pathType), /** * Return thumbnail URL for specific base url using media path * @param {string} relativeUrl * @param {number} width * @param {number} height */ getMediaThumbnail: (relativeUrl, width, height) => getThumbnailPath(relativeUrl, width, height, 'media') } }
JavaScript
0
@@ -291,16 +291,41 @@ athType%0A + * @returns %7Bstring%7D%0A */%0A @@ -606,24 +606,49 @@ ber%7D height%0A + * @returns %7Bstring%7D%0A */%0A
53a1f72ccf74f807074486cf6b80d4f98177d42e
Add name length validation
models/Player.js
models/Player.js
/** * Module dependencies. */ const mongoose = require('mongoose'); const Schema = mongoose.Schema // create a schema const playerSchema = new Schema({ name: String, username: { type: String, required: true, unique: true, minlength: 1 }, team: Schema.Types.ObjectId, created_at: Date, }); // create a model using schema const Player = mongoose.model('Player', playerSchema); // on every save, add the date playerSchema.pre('save', (next) => { if (!this.created_at) { this.created_at = new Date(); } next(); }); // make this available to our users in our Node applications module.exports = Player;
JavaScript
0.000003
@@ -157,22 +157,46 @@ name: -String +%7B type: String, minlength: 1 %7D ,%0A user @@ -500,18 +500,16 @@ d_at) %7B%0A - this
29ea906aba94b153d439675b26a3f15094fe472e
Remove async/await from 'accordion-item-title'.
src/AccordionItemTitle/accordion-item-title.js
src/AccordionItemTitle/accordion-item-title.js
// @flow import React, { Component, type ElementProps } from 'react'; import classNames from 'classnames'; type AccordionItemTitleProps = ElementProps<'div'> & { hideBodyClassName: string, uuid: string | number, }; type AccordionItemTitleState = {}; class AccordionItemTitle extends Component< AccordionItemTitleProps, AccordionItemTitleState, > { static accordionElementName = 'AccordionItemTitle'; handleClick = async () => { const { uuid, accordionStore } = this.props; const { state } = accordionStore; const { accordion, onChange, items } = state; const foundItem = items.find(item => item.uuid === uuid); await accordionStore.setExpanded(foundItem.uuid, !foundItem.expanded); if (accordion) { onChange(foundItem.uuid); } else { onChange( accordionStore.state.items .filter(item => item.expanded) .map(item => item.uuid), ); } }; handleKeyPress = (evt: SyntheticKeyboardEvent<HTMLButtonElement>) => { if (evt.charCode === 13 || evt.charCode === 32) { this.handleClick(); } }; render() { const { state: { items, accordion }, } = this.props.accordionStore; const { uuid, className, hideBodyClassName, accordionStore, ...rest } = this.props; const foundItem = items.find(item => item.uuid === uuid); const { expanded, disabled } = foundItem; const id = `accordion__title-${uuid}`; const ariaControls = `accordion__body-${uuid}`; const role = accordion ? 'tab' : 'button'; const titleClassName = classNames(className, { [hideBodyClassName]: hideBodyClassName && !expanded, }); if (role === 'tab') { return ( <div id={id} aria-selected={expanded} aria-controls={ariaControls} className={titleClassName} onClick={disabled ? undefined : this.handleClick} role={role} tabIndex="0" // eslint-disable-line jsx-a11y/no-noninteractive-tabindex onKeyPress={this.handleKeyPress} disabled={disabled} {...rest} /> ); } return ( <div id={id} aria-expanded={expanded} aria-controls={ariaControls} className={titleClassName} onClick={disabled ? undefined : this.handleClick} role={role} tabIndex="0" // eslint-disable-line jsx-a11y/no-noninteractive-tabindex onKeyPress={this.handleKeyPress} disabled={disabled} {...rest} /> ); } } export default AccordionItemTitle;
JavaScript
0
@@ -439,14 +439,8 @@ ck = - async () @@ -440,24 +440,24 @@ k = () =%3E %7B%0A + cons @@ -672,14 +672,8 @@ -await acco @@ -682,16 +682,29 @@ ionStore +%0A .setExpa @@ -744,27 +744,57 @@ xpanded) -;%0A%0A +%0A .then(() =%3E %7B%0A if (acco @@ -781,24 +781,26 @@ + if (accordio @@ -800,24 +800,32 @@ ccordion) %7B%0A + @@ -858,16 +858,24 @@ + + %7D else %7B @@ -879,32 +879,40 @@ e %7B%0A + + onChange(%0A @@ -913,32 +913,40 @@ + + accordionStore.s @@ -956,16 +956,24 @@ e.items%0A + @@ -1035,16 +1035,24 @@ + + .map(ite @@ -1076,36 +1076,68 @@ -);%0A %7D + );%0A %7D%0A %7D); %0A %7D;%0A%0A
1cd11bbf96c5d4cf79b4fb15bc6712376991faf8
declare all attribute types
lib/adminService.js
lib/adminService.js
/* jslint node: true, esnext: true */ 'use strict'; const path = require('path'), process = require('process'), ssh2 = require('ssh2'), mat = require('model-attributes'), endpoint = require('kronos-endpoint'), service = require('kronos-service'); /** * */ class ServiceAdmin extends service.Service { static get name() { return 'admin'; } static get configurationAttributes() { return Object.assign(mat.createAttributes({ ssh: { description: 'ssh admin interface', attributes: { port: { description: 'listen port', needsRestart: true, type: 'integer' }, hostKeys: { description: 'server ssh private host key(s)', needsRestart: true } } } }), service.Service.configurationAttributes); } constructor(config, owner) { super(config, owner); this.addEndpoint(new endpoint.ReceiveEndpoint('software', this)).receive = request => Promise.resolve({ versions: process.versions, platform: process.platform }); } get autostart() { return true; } _start() { return super._start().then(() => { return service.ServiceConsumerMixin.defineServiceConsumerProperties(this, { listener: { name: 'koa-admin', type: 'koa' } }, this.owner, true).then(() => { if (this.config.ssh) { this.sshServer = require('./ssh')(this, this.config.ssh); } return this.owner.loadFlowFromFile(path.join(__dirname, '..', 'admin.flow')); }); }); } _stop() { if (this.sshServer) { return super._stop().then(new Promise((fullfill, reject) => { this.sshServer.close((err) => { if (err) { reject(err); return; } delete this.sshServer; fullfill(); }); })); } return super._stop(); } } module.exports.registerWithManager = manager => manager.registerServiceFactory(ServiceAdmin).then(admin => manager.declareService({ type: admin.name, name: admin.name }));
JavaScript
0.000002
@@ -591,14 +591,14 @@ : 'i -nteger +p-port '%0A%09%09 @@ -673,16 +673,36 @@ ey(s)',%0A +%09%09%09%09%09%09type: 'blob',%0A %09%09%09%09%09%09ne
6df0daebb8c4be95ba41a8cb10e3188121073d5a
Bump version of `bundle-visualizer` to 1.0.3.
packages/non-core/bundle-visualizer/package.js
packages/non-core/bundle-visualizer/package.js
Package.describe({ version: '1.0.2', summary: 'Meteor bundle analysis and visualization.', documentation: 'README.md', }); Npm.depends({ "d3-selection": "1.0.5", "d3-shape": "1.0.6", "d3-hierarchy": "1.1.4", "d3-transition": "1.0.4", "pretty-bytes": "4.0.2", }); Package.onUse(function(api) { api.use('isobuild:[email protected]'); api.use([ 'ecmascript', 'dynamic-import', ]); api.mainModule('server.js', 'server'); api.mainModule('client.js', 'client'); });
JavaScript
0
@@ -28,17 +28,17 @@ n: '1.0. -2 +3 ',%0A sum
ad98186afcbcc34cf89948e52ccba0b8f5f94b5a
remove redundant semicolons from export declarations
test/core/fixtures/generation/types/ExportDeclaration-ExportSpecifier-ExportBatchSpecifier/actual.js
test/core/fixtures/generation/types/ExportDeclaration-ExportSpecifier-ExportBatchSpecifier/actual.js
export default 42; export default {}; export default []; export default foo; export default function () {}; export default class {}; export default function foo() {} export default class Foo {} export * from "foo"; export { foo } from "foo"; export { foo, bar } from "foo"; export { foo as bar } from "foo"; export { foo as default } from "foo"; export { foo as default, bar } from "foo"; export { foo }; export { foo, bar }; export { foo as bar }; export { foo as default }; export { foo as default, bar }; export var foo = 1; export var foo2 = function () {}; export var foo3; export let foo4 = 2; export let foo5; export const foo6 = 3; export function foo7() {} export class foo8 {}
JavaScript
0.998592
@@ -91,33 +91,32 @@ t function () %7B%7D -; %0Aexport default @@ -123,17 +123,16 @@ class %7B%7D -; %0Aexport
be808b399ccfcb330d6a7c71c7c1d1e80dd3f993
Add asJS to immutableHelper
src/helper/immutableHelper.js
src/helper/immutableHelper.js
import { Iterable, fromJS } from 'immutable'; export const asImmutable = (obj) => (Iterable.isIterable(obj) ? obj : fromJS(obj));
JavaScript
0.000001
@@ -77,16 +77,19 @@ bj) =%3E ( +%0A Iterable @@ -124,11 +124,100 @@ mJS(obj) +%0A);%0A%0Aexport const asJS = (obj) =%3E (%0A obj && Iterable.isIterable(obj) ? obj.toJS() : obj%0A );%0A
8420b6cd3df03cb0f2e16293eb1d75f433b5fb4c
Update syntax for style on removal
modules/style.js
modules/style.js
var raf = requestAnimationFrame || setTimeout; var nextFrame = function(fn) { raf(function() { raf(fn); }); }; function setNextFrame(obj, prop, val) { nextFrame(function() { obj[prop] = val; }); } function updateStyle(oldVnode, vnode) { var cur, name, elm = vnode.elm, oldStyle = oldVnode.data.style || {}, style = vnode.data.style || {}; for (name in style) { cur = style[name]; if ((name[0] !== 'r' || name[0] !== '-') && cur !== oldStyle[name]) { if (name[0] === 'd' && name[1] === '-') { setNextFrame(elm.style, name.slice(2), cur); } else { elm.style[name] = cur; } } } } function applyRemoveStyle(vnode, rm) { var cur, name, elm = vnode.elm, idx, i = 0, maxDur = 0, compStyle, style = vnode.data.style || {}; var applied = []; for (name in style) { cur = style[name]; if (name[0] === 'r' && name[1] === '-') { name = name.slice(2); applied.push(name); setNextFrame(elm.style, name, cur); } } if (applied.length > 0) { compStyle = getComputedStyle(elm); var dels = compStyle['transition-delay'].split(', '); var durs = compStyle['transition-duration'].split(', '); var props = compStyle['transition-property'].split(', '); for (; i < applied.length; ++i) { idx = props.indexOf(applied[i]); if (idx !== -1) maxDur = Math.max(maxDur, parseFloat(dels[idx]) + parseFloat(durs[idx])); } setTimeout(rm, maxDur * 1000); // s to ms } else { rm(); } } module.exports = {create: updateStyle, update: updateStyle, remove: applyRemoveStyle};
JavaScript
0
@@ -408,45 +408,26 @@ if -( (name -%5B0%5D !== 'r -' %7C%7C name%5B0%5D !== '-') +emove' &&%0A @@ -663,24 +663,83 @@ node, rm) %7B%0A + var s = vnode.data.style;%0A if (!s %7C%7C !s.remove) return;%0A var cur, n @@ -809,38 +809,24 @@ style = -vnode.data.style %7C%7C %7B%7D +s.remove ;%0A var @@ -867,107 +867,8 @@ ) %7B%0A - cur = style%5Bname%5D;%0A if (name%5B0%5D === 'r' && name%5B1%5D === '-') %7B%0A name = name.slice(2);%0A @@ -895,51 +895,38 @@ - setNextFrame(elm. +elm.style%5Bname%5D = style -, +%5B name -, cur);%0A %7D +%5D; %0A %7D
fac44464f2958fb42e4593b17b0adbecfa0809d6
Update script2.js
scripts/script2.js
scripts/script2.js
var x_timer; $('#search').bind("keyup blur", function (event){ var exclud = [13,27,37,38,39,40]; clearTimeout(x_timer); //if (event.keyCode != '13' && event.keyCode != '40' && event.keyCode != '39' && event.keyCode != '38' && event.keyCode != '37') { x_timer = setTimeout(function(){ if (exclud.indexOf(event.which) === -1) { $.ajax({ url: "https://api.soundcloud.com/tracks.json?" + $('#search').serialize(), dataType: 'json', beforeSend: function(data){ $('#sounds').empty(); }, success: function(data){ $('#sounds').html('') var items = []; var i=0; $.each(data, function(key, val){ items.push("<div id='tracks_list'><li class='row-fluid'>"+check(val.artwork_url)+"<a class='go col-md-9' data-index='"+i+"' data-artist='"+val.user.username+"' data-title='"+val.title+ "' data-url=" + val.stream_url + " href='javascript:void();'><h2>"+val.title+"</h2>\ <span class='plays'>" + val.user.username + " - <b>" + msToTime(val.duration) + "</b></span></a></li></div>"); i++; }); $('#sounds').html(items.join(' ')); trackClick(); } }); } }, 300); }); window.onload = function() { document.getElementById("q").focus(); }; var clientid = 'client_id=2010872379d388118fe90f01ace38d03'; function msToTime(duration) { var milliseconds = parseInt((duration%1000)/100) , seconds = parseInt((duration/1000)%60) , minutes = parseInt((duration/(1000*60))%60) , hours = parseInt((duration/(1000*60*60))%24); hours = (hours < 10) ? "0" + hours : hours; minutes = (minutes < 10) ? "0" + minutes : minutes; seconds = (seconds < 10) ? "0" + seconds : seconds; if(hours == "00") return minutes + ":" + seconds; else return hours + ":" + minutes + ":" + seconds; } function trackClick(){ $('.go').click(function(){ var url= $(this).data('url') +"?"+ clientid; var title= $(this).data('title'); var artist = $(this).data('artist'); $(this).addClass('playedSong'); $('#navbar h2').html(title); var next = ($(this).data('index'))+1; var audioPlayer = document.getElementById('player'); audioPlayer.src = url; audioPlayer.load(); document.getElementById('player').play(); $("#player").bind("ended", function(){ playnext(next); }); document.title="Playing " + title; $(this).before(function() { $(".download").remove(); $(this).prev('img').remove(); return "<a class='download' href='"+url+"' target='_blank' download><i style='color:#fff;' class='fa fa-arrow-down'></i></a>"; }); return false; }); } function playnext(id){ var next = id+1; var url = $('a[data-index="'+id+'"]').data('url') +"?"+ clientid; var title= $('a[data-index="'+id+'"]').data('title'); $('a[data-index="'+id+'"]').addClass('playedSong'); $('#navbar h2').html(title); var audioPlayer = document.getElementById('player'); audioPlayer.src = url; audioPlayer.load(); $("#player").bind("ended", function(){ playnext(next); }); document.title="Playing " + title; document.getElementById('player').play(); } function check(kima){ if (kima === undefined || kima === null) { return ''; } else { return '<img class="pull-right" src="'+kima+'"/>'; } } /*$( "#pause" ).click(function() { $("#player").trigger('pause'); });*/ $('#pause').click(function() { var audioPlayer = document.getElementById('player'); if (audioPlayer.paused == false) { audioPlayer.pause(); $( ".icon" ).remove; $( ".icon" ).html('<i class="fa fa-play"></i>'); } else { audioPlayer.play(); $( ".icon" ).remove; $( ".icon" ).html('<i class="fa fa-pause"></i>'); } }); /*$("#volume").slider({ value : 75, step : 1, range : 'min', min : 0, max : 100, slide : function(){ var value = $("#volume").slider("value"); document.getElementById("#player").volume = (value / 100); } });*/
JavaScript
0.000001
@@ -2679,16 +2679,22 @@ ass='fa +fa-3x fa-arrow
aec0b918ac281761f5f843aa31f6afb146a1d1b8
change ref to element
src/collections/Form/Form.js
src/collections/Form/Form.js
import _ from 'lodash'; import $ from 'jquery'; import React, {Component, PropTypes} from 'react'; import classNames from 'classnames'; import META from 'src/utils/Meta'; export default class Form extends Component { static propTypes = { children: PropTypes.node, className: PropTypes.string, settings: PropTypes.object, }; componentDidMount() { this.element = $(this.refs.element); this.element.form(this.props.settings); } componentWillUnmount() { this.element.off(); } plugin() { return this.element.form(...arguments); } serializeJson = () => { const form = this.refs.form; const json = {}; _.each(['input', 'textarea', 'select'], (tag) => { _.each(form.getElementsByTagName(tag), (node, index, arr) => { const name = node.getAttribute('name'); switch (node.getAttribute('type')) { case 'checkbox': json[name] = {checked: node.checked}; break; case 'radio': json[name] = { value: _.find(arr, {name, checked: true}).value }; break; default: json[name] = {value: node.value}; break; } }); }); return json; }; static _meta = { library: META.library.semanticUI, name: 'Form', type: META.type.collection, }; render() { const classes = classNames( 'sd-form', 'ui', this.props.className, 'form' ); return ( <form {...this.props} className={classes} ref='element'> {this.props.children} </form> ); } }
JavaScript
0.000001
@@ -620,20 +620,23 @@ is.refs. -form +element ;%0A co
aa51cea25173b387201c833e34299803a226d3b5
Update Knex user model to create table properly (#233)
generators/service/templates/model/knex-user.js
generators/service/templates/model/knex-user.js
/* eslint-disable no-console */ // <%= name %>-model.js - A KnexJS // // See http://knexjs.org/ // for more of what you can do here. module.exports = function (app) { const db = app.get('knexClient'); db.schema.createTableIfNotExists('<%= kebabName %>', table => { table.increments('id'); <% if(authentication.strategies.indexOf('local') !== -1) { %> table.string('email').unique(); table.string('password'); <% } %> <% authentication.oauthProviders.forEach(provider => { %> table.string('<%= provider.name %>Id'); <% }); %> }) .then(() => console.log('Updated <%= kebabName %> table')) .catch(e => console.error('Error updating <%= kebabName %> table', e)); return db; };
JavaScript
0
@@ -199,16 +199,102 @@ ent');%0A%0A + db.schema.hasTable('%3C%25= kebabName %25%3E').then(exists =%3E %7B%0A if(!exists) %7B%0A db.sch @@ -312,19 +312,8 @@ able -IfNotExists ('%3C%25 @@ -336,24 +336,30 @@ table =%3E %7B%0A + table.in @@ -370,24 +370,30 @@ ents('id');%0A + %3C%25 if(auth @@ -440,24 +440,30 @@ == -1) %7B %25%3E%0A + table.st @@ -486,16 +486,22 @@ ique();%0A + tabl @@ -518,24 +518,30 @@ password');%0A + %3C%25 %7D %25%3E%0A @@ -538,16 +538,22 @@ %3C%25 %7D %25%3E%0A + %3C%25 aut @@ -600,24 +600,30 @@ der =%3E %7B %25%3E%0A + table.st @@ -654,16 +654,22 @@ %25%3EId');%0A + %3C%25 %7D); @@ -676,21 +676,44 @@ %25%3E%0A + %7D)%0A -.then( + .then(%0A () = @@ -763,19 +763,20 @@ le') -)%0A .catch( +,%0A e =%3E @@ -833,16 +833,41 @@ ble', e) +%0A );%0A %7D%0A %7D );%0A%0A re
f855ba861690d6ba954ffb7abdad509564428190
support ident log
gas-log.js
gas-log.js
(function () { /************************************************************************************** * * GasL - Google Apps Script Loging-framework * * Support log to Spreadsheet / Logger / LogEntries(next version) , * and very easy to extended to others. * * Github: https://github.com/zixia/gasl * * Example: ```javascript var gasLogLib='https://raw.githubusercontent.com/zixia/gasl/master/gas-log.js' var GasLog = eval(UrlFetchApp.fetch(gasLogLib).getContentText()) var log = new GasLog() log('Hello, %s!', 'World') ``` * ***************************************************************************************/ var PRIORITIES = { EMERG: 0 , ALERT: 1 , CRIT: 2 , ERR: 3 , WARNING: 4 , NOTICE: 5 , INFO: 6 , DEBUG: 7 } /**************************************************** * * GasLog Constructor * ****************************************************/ var gasLog_ = function (options) { var logPriority = PRIORITIES.INFO var logPrinter = new LoggerPrinter() if (options && options.priority) { logPriority = loadPriority(options.priority) } if (options && options.printer) { logPrinter = options.printer if (!logPrinter.isPrinter()) { throw Error('options.printer ' + printer + ' is not a GasLog printer!') } } /***************************************** * * Instance Methods Export * *****************************************/ for (var logName in PRIORITIES) { doLog[logName] = PRIORITIES[logName] } doLog.PRIORITIES = PRIORITIES doLog.getPriority = getPriority doLog.setPriority = setPriority /********************************** * * Constructor initialize finished * ***********************************/ return doLog ////////////////////////////////////////////////////////////// // Instance Methods Implementions ////////////////////////////////////////////////////////////// /** * * Log Level Getter & Setter * */ function getPriority() { return logPriority } function setPriority(priorityName) { logPriority = loadPriority(priorityName) return this } /** * * * log(priority, msg, params...) * or just log(msg) * * */ function doLog() { // make a shiftable array from arguments var args = Array.prototype.slice.call(arguments) var priority = logPriority // set to default before we parse params switch (typeof args[0]) { case 'number': /** * * determine priority. * if the 1st param is a valid log priority(a Integer), then use it as logPriority * otherwise, set logPriority to default(priority in instance) * */ priority = loadPriority(args.shift()) break; case 'string': break; default: throw Error('doLog(' + args[0] + ') need 1st param either be string or number!') break; } // no log for lower priority messages than logPriority if (priority > logPriority) return /** * * build log string & log * */ var message = '' try { message = Utilities.formatString.apply(null, args); } catch (e) { message = args.join(' !!! ') } logPrinter(priority, message) } } /******************************** * * Class Static Methods Export * *********************************/ gasLog_.Printer = {} gasLog_.Printer.Logger = LoggerPrinter gasLog_.Printer.Spreadsheet = SpreadsheetPrinter return gasLog_ /////////////////////////////////////////////////////////////////////////////// // Class Static Method Implementations /////////////////////////////////////////////////////////////////////////////// function LoggerPrinter() { var loggerPrinter_ = function (priority, message) { return Logger.log(message) } loggerPrinter_.isPrinter = function () { return 'Logger' } return loggerPrinter_ } /** * * @param Object options * options.id - Spreadsheet ID * options.url - Spreadsheet URL * options.sheetName - Tab name of a sheet * options.clear - true for clear all log sheet. default false * options.scroll - 'DOWN' or 'UP', default DOWN * */ function SpreadsheetPrinter(options) { if(typeof options != 'object') throw Error('options must set for Spreadsheet Printer') var sheetName = options.sheetName || 'GasLogs' var clear = options.clear || false var scroll = options.scroll || 'DOWN' var url = options.url var id = options.id var ss // Spreadsheet if (id) { ss = SpreadsheetApp.openById(id) } else if(url) { ss = SpreadsheetApp.openByUrl(url) } else { throw Error('options must set url or id! for get the spreadsheet') } if (!ss) throw Error('SpreadsheetPrinter open ' + id + url + ' failed!') // Sheet for logging var sheet = ss.getSheetByName(sheetName) if (!sheet) { sheet = ss.insertSheet(sheetName) if (!sheet) throw Error('SpreadsheetPrint insertSheet ' + sheetName + ' failed!') } /** * initialize headers if not exist in sheet */ var range = sheet.getRange(1, 1, 1, 4) var h = range.getValues()[0] if (!h[0] && !h[1] && !h[2]) { range.setValues([['Date', 'Level', 'Message', 'Powered by GasL - Google Apps Script Logging-framework - https://github.com/zixia/gasl']]) } if (clear) { // keep header row (the 1st row) sheet.getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn()).clearContent() } var spreadsheetPrinter_ = function (priority, message) { if (scroll=='UP') { sheet .insertRowBefore(2) .getRange(2, 1, 1, 3) .setValues([[new Date(), priority, message]]) } else { // scroll DOWN sheet.appendRow([new Date(), priority, message]) } } spreadsheetPrinter_.isPrinter = function () { return 'Spreadsheet' } return spreadsheetPrinter_ } /** * * */ function loadPriority(priority) { if (priority % 1 === 0) { return priority } else if (typeof priority == 'string') { priority = priority.toUpperCase() if (priority in PRIORITIES) { return PRIORITIES[priority] } } throw Error('options.priority[' + priority + '] illegel') } }())
JavaScript
0
@@ -1258,16 +1258,116 @@ rinter() +%0A var logIdent = 'GasL'%0A%0A if (options && options.ident) %7B%0A logIdent = options.ident%0A %7D %0A%0A if @@ -1626,17 +1626,20 @@ ter ' + -p +logP rinter + @@ -1657,17 +1657,17 @@ GasLog -p +P rinter!' @@ -3837,17 +3837,28 @@ gPrinter -( +.call(this, priority @@ -5855,17 +5855,17 @@ , 1, 1, -4 +5 )%0A va @@ -5922,16 +5922,25 @@ && !h%5B2%5D + && !h%5B3%5D ) %7B%0A @@ -5968,21 +5968,33 @@ Date', ' -Level +Ident', 'Priority ', 'Mess @@ -6428,17 +6428,17 @@ , 1, 1, -3 +4 )%0A @@ -6455,32 +6455,47 @@ es(%5B%5Bnew Date(), + this.logIdent, priority, messa
821282e6a6579eafefd70c305f9834fc3e645ffb
add minor spacing
scripts/scripts.js
scripts/scripts.js
'use strict' const date = new Date(); module.exports = { // Utility Functions for Bot.js /** * normalizes input from chat for grimoire card searches * - converts all characters to lowercase * - removes any colons found in chat input * - removes any spaces and replaces with slug "-" */ normalizeCardInput: function (msg) { let lowercaseify = msg.toLowerCase(); let removeColon = lowercaseify.replace(":", ""); let output = removeColon.replace(/\s+/g, "-"); return output; }, /** * Normalizes input from chat for item searches * - converts all characters to lower case * - removes any semi-colons * - removes any spaces and replaces with slug "-" */ normalizeItemInput: function (msg) { let lowercaseify = msg.toLowerCase(); let stripApostrophe = lowercaseify.replace("'", ""); let output = stripApostrophe.replace(/\s+/g, "-"); return output; }, /** * Reads array of quotes and picks one at random */ randomQuote: function (list) { return list[Math.round(Math.random()*(list.length-1))]; }, // Returns the current day of the week curDay: function() { return date.getDate(); }, // Returns the current of month of the year curMonth: function() { let month = date.getMonth(); const months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; return months[month]; } }
JavaScript
0.000022
@@ -1141,16 +1141,17 @@ e();%0A%7D,%0A +%0A // Retur
edb165ef17ea0c506bc85d283d578550e4e0e3e4
Add back Image.isImage property that got lost by accident
lib/assets/Image.js
lib/assets/Image.js
var util = require('util'), extendWithGettersAndSetters = require('../util/extendWithGettersAndSetters'), Asset = require('./Asset'); var dprMatcher = /(?:@(\d+(?:[\.,]\d+)?)x)?$/; function Image(config) { Asset.call(this, config); if (this._fileName) { var dpr = this._fileName.replace(this._extension, '').match(dprMatcher)[1]; if (dpr) { this.devicePixelRatio = dpr; } } } util.inherits(Image, Asset); extendWithGettersAndSetters(Image.prototype, { /** * image.isImage * =========== * * Property that's true for all Image instances. Avoids reliance on * the `instanceof` operator and enables you to query for all * image types: * * var imageAssets = assetGraph.findAssets({isImage: true}); */ notDefaultForContentType: true, // Avoid reregistering application/octet-stream defaultEncoding: null, get defaultDevicePixelRatio() { return 1; }, get devicePixelRatio() { if (typeof this._devicePixelRatio !== 'undefined') { return this._devicePixelRatio; } else { return this.defaultDevicePixelRatio; } }, set devicePixelRatio(ratio) { if (!/^\d+(?:[\.,]\d+)?$/.test(ratio.toString())) { throw new Error('Image device pixel ratio: May only contain digits, comma and dot'); } ratio = Number(ratio.toString().replace(',', '.')); if (ratio <= 0) { throw new Error('Image device pixel ratio: Must be a larger than 0'); } if (ratio === Infinity) { throw new Error('Image device pixel ratio: Cannot be infinite'); } this._devicePixelRatio = ratio; }, get fileName() { return Asset.prototype.__lookupGetter__('fileName').call(this); }, set fileName(fileName) { var dpr = fileName.replace(this._extension, '').match(dprMatcher)[1]; if (dpr) { this.devicePixelRatio = dpr; } Asset.prototype.__lookupSetter__('fileName').call(this, fileName); }, get url() { return Asset.prototype.__lookupGetter__('url').call(this); }, set url(url) { Asset.prototype.__lookupSetter__('url').call(this, url); var dpr = this._fileName.replace(this._extension, '').match(dprMatcher)[1]; if (dpr) { this.devicePixelRatio = dpr; } } }); module.exports = Image;
JavaScript
0
@@ -803,16 +803,35 @@ %0A */ +%0A isImage: true, %0A%0A no
c1368575ef26cd8c942719f66d0f9598c32d0ced
correct variable name
troposphere/static/js/stores/ProjectVolumeStore.js
troposphere/static/js/stores/ProjectVolumeStore.js
define( [ 'underscore', 'dispatchers/dispatcher', 'stores/store', 'rsvp', 'constants/ProjectVolumeConstants', 'controllers/notifications', 'models/volume', 'backbone', 'globals' ], function (_, Dispatcher, Store, RSVP, ProjectVolumeConstants, NotificationController, Volume, Backbone, globals) { var _projectVolumes = {}; var _isFetching = false; // // Project Volume Model // Mainly a helper for generating add/remove urls // var ProjectVolume = Backbone.Model.extend({ urlRoot: function() { return globals.API_ROOT + "/project/" + this.project.id + "/volume"; }, url: function () { var url = Backbone.Model.prototype.url.apply(this) + globals.slash(); return url; }, initialize: function(options){ this.volume = options.volume; this.project = options.project; this.set("id", this.volume.id); } }); var ProjectVolumeCollection = Backbone.Collection.extend({ model: Volume, url: function () { var url = globals.API_ROOT + "/project/" + this.project.id + "/volume" + globals.slash(); return url; }, initialize: function(models, options){ this.project = options.project; } }); // // CRUD Operations // var fetchProjectVolumes = function (project) { _isFetching = true; var promise = new RSVP.Promise(function (resolve, reject) { var projectVolumes = new ProjectVolumeCollection(null, { project: project }); projectVolumes.fetch().done(function () { _isFetching = false; _projectVolumes[project.id] = projectVolumes; resolve(); }); }); return promise; }; function addVolumeToProject(volume, project){ var projectVolume = new ProjectVolume({ volume: volume, project: project }); projectVolume.save().done(function(){ var successMessage = "Volume '" + volume.get('name') + "' added to Project '" + project.get('name') + "'"; NotificationController.success(message); }).fail(function(){ var failureMessage = "Error adding Volume '" + volume.get('name') + "' to Project '" + project.get('name') + "' :( Please let Support know."; NotificationController.danger(failureMessage); _projectVolumes[project.id].remove(volume); }); _projectVolumes[project.id].add(volume); } function removeVolumeFromProject(volume, project){ var projectVolume = new ProjectVolume({ volume: volume, project: project }); projectVolume.destroy().done(function(){ var successMessage = "Volume '" + volume.get('name') + "' removed from Project '" + project.get('name') + "'"; NotificationController.success(successMessage); }).fail(function(){ var failureMessage = "Error removing Volume '" + volume.get('name') + "' from Project '" + project.get('name') + "' :( Please let Support know."; NotificationController.danger(failureMessage); _projectVolumes[project.id].add(volume); }); _projectVolumes[project.id].remove(volume); } // // Project Volume Store // var ProjectVolumeStore = { getVolumesInProject: function (project) { var projectVolumes = _projectVolumes[project.id]; if(!projectVolumes) { fetchProjectVolumes(project).then(function(){ ProjectVolumeStore.emitChange(); }.bind(this)); } return projectVolumes; } }; Dispatcher.register(function (payload) { var action = payload.action; switch (action.actionType) { case ProjectVolumeConstants.ADD_VOLUME_TO_PROJECT: addVolumeToProject(action.volume, action.project); break; case ProjectVolumeConstants.REMOVE_VOLUME_FROM_PROJECT: removeVolumeFromProject(action.volume, action.project); break; default: return true; } ProjectVolumeStore.emitChange(); return true; }); _.extend(ProjectVolumeStore, Store); return ProjectVolumeStore; });
JavaScript
0.99653
@@ -2146,17 +2146,24 @@ success( -m +successM essage);
de151d5cb1f1e644e24f75dc66a9d06a5d045703
update w/new instance API
src/horizontal-pager/index.js
src/horizontal-pager/index.js
/** * Entry point to horizontal-pager example. * * Copyright (c) 2017 Alex Grant (@localnerve), LocalNerve LLC * Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms. */ /* global document */ /* eslint-disable import/no-unresolved */ import createHorizontalPager from './horizontal-pager'; /** * HorizontalPager callback to update the page indicator bubbles. * * @param {Number} direction - +1 for forward (left), -1 for back (right) */ function updateBubble (direction) { const selectedBbl = document.querySelector('.bbl.selected'); const nextSibling = direction > 0 ? selectedBbl.nextElementSibling : selectedBbl.previousElementSibling; selectedBbl.classList.remove('selected'); nextSibling.classList.add('selected'); } let horizontalPager; document.addEventListener('DOMContentLoaded', () => { horizontalPager = createHorizontalPager({ targetClass: 'page-item', willComplete: updateBubble }); }, { once: true }); document.addEventListener('unload', () => horizontalPager && horizontalPager.destroy(), { once: true });
JavaScript
0
@@ -960,16 +960,48 @@ e%0A %7D);%0A + horizontalPager.initialize();%0A %7D, %7B%0A o
1aa057ddd95028428ba19075360d3191da650693
update re landing page url
src/plugin/iframe_root/modules/widgets/genomes/kbaseGenomeRELineage.js
src/plugin/iframe_root/modules/widgets/genomes/kbaseGenomeRELineage.js
/** * Shows taxonomic lineage. * */ define(['jquery', 'uuid', 'kb_lib/html', 'kb_lib/jsonRpc/dynamicServiceClient', 'kbaseUI/widget/legacy/widget'], function ($, Uuid, html, DynamicServiceClient) { 'use strict'; const t = html.tag; const a = t('a'); const div = t('div'); const span = t('span'); const table = t('table'); const tr = t('tr'); const th = t('th'); const td = t('td'); $.KBWidget({ name: 'KBaseGenomeRELineage', parent: 'kbaseWidget', version: '1.0.0', options: { width: 600, genomeInfo: null, genomeID: null, timestamp: null }, genome: null, token: null, init: function (options) { this._super(options); if (!this.options.genomeInfo) { this.renderError('Genome information not supplied'); return; } this.genome = options.genomeInfo.data; this.genomeID = options.genomeID; this.render(); return this; }, renderLineageTable(lineage, taxonRef, scientificName) { const taxonURL = `/#review/taxonomy/${taxonRef.ns}/${taxonRef.id}/${taxonRef.ts}`; this.$elem.empty().append( table( { class: 'table table-bordered' }, [ tr([ th( { style: { width: '11em' } }, 'Scientific Name' ), td( { dataField: 'scientific-name', style: { fontStyle: 'italic' } }, a( { href: taxonURL, target: '_blank' }, scientificName ) ) ]), tr([th('Taxonomic Lineage'), td(this.buildLineage(lineage))]) ] ) ); }, fetchRELineage: function (genomeRef) { const taxonomyAPI = new DynamicServiceClient({ url: this.runtime.config('services.service_wizard.url'), module: 'taxonomy_re_api', token: this.runtime.service('session').getAuthToken() }); let timestamp = this.options.timestamp; // console.warn('ts?', timestamp, Date.now()); // TODO: important, remove the following line after the demo! Currently things // break due to the database being incomplete, so there is not complete // coverage over time, and queries which should never fail, do. // TODO: the actual timestamp should be ... based on the timestamp associated // with ... the taxon linked to the object? // ... the time the taxon was linked to the object? timestamp = Date.now(); // TODO: resolve the usage of 'ts' in 'get_taxon...'. It should not be necessary // since the taxon assignment to an object is not dependent upon some reference time, // it is fixed in that respect. return taxonomyAPI.callFunc('get_taxon_from_ws_obj', [{ obj_ref: genomeRef, ns: 'ncbi_taxonomy' }]) .then(([result]) => { if (result.results.length === 0) { throw new Error('No taxon found for this object'); } const [taxon] = result.results; const taxonRef = { ns: taxon.ns, id: taxon.id, ts: timestamp }; return Promise.all([ taxonomyAPI.callFunc('get_lineage', [taxonRef]), taxonomyAPI.callFunc('get_taxon', [taxonRef]) ]) .then(([[{results: lineageResults}], [{results: [taxon]}]]) => { if (!taxon) { throw new Error('Taxon not found'); } const {scientific_name: scientificName} = taxon; this.renderLineageTable(lineageResults, taxonRef, scientificName); }); }); }, buildLineage: function (lineage) { // Trim off the "root" which is always at the top of the lineage. lineage = lineage.slice(1); return div( { style: { whiteSpace: 'nowrap', overflowX: 'auto' } }, lineage.map((taxon) => { const url = `/#review/taxonomy/${taxon.ns}/${taxon.id}`; return div( a( { href: url, target: '_blank' }, taxon.scientific_name ) ); }) ); }, renderLoading: function () { this.$elem.empty(); this.$elem.append(div({ style: { textAlign: 'left', marginBottom: '10px', color: 'rgba(150, 150, 150, 1)' } }, [ span({ class: 'fa fa-spinner fa-pulse' }), span({ style: { marginLeft: '4px' } }, 'Loading lineage...') ])); }, renderError: function (error) { var errorMessage; if (typeof error === 'string') { errorMessage = error; } else if (error.error && error.error.message) { errorMessage = error.error.message; } else { errorMessage = 'Sorry, an unknown error occurred'; } var errorAlert = div( { class: 'alert alert-danger' }, [ span( { textWeight: 'bold' }, 'Error: ' ), span(errorMessage) ] ); this.$elem.empty(); this.$elem.append(errorAlert); }, render: function () { const {ws, id, ver} = this.options.genomeRef; const genomeRef = [ws, id, ver].join('/'); this.renderLoading(); this.fetchRELineage(genomeRef) .catch((err) => { console.error('ERROR', err); this.renderError('Error fetching lineage: ' + err.message); }); }, }); });
JavaScript
0
@@ -1193,33 +1193,24 @@ = %60/#review/ -taxonomy/ $%7BtaxonRef.n @@ -5478,17 +5478,8 @@ iew/ -taxonomy/ $%7Bta
0e759be3be2db0cc305ce63b43eea737a6a77b43
fix enterprise routing assertion (#6495)
ui/tests/acceptance/enterprise-replication-test.js
ui/tests/acceptance/enterprise-replication-test.js
import { click, fillIn, findAll, currentURL, find, visit, settled } from '@ember/test-helpers'; import { module, test } from 'qunit'; import { setupApplicationTest } from 'ember-qunit'; import authPage from 'vault/tests/pages/auth'; import { pollCluster } from 'vault/tests/helpers/poll-cluster'; import withFlash from 'vault/tests/helpers/with-flash'; const disableReplication = async (type, assert) => { // disable performance replication await visit(`/vault/replication/${type}`); if (findAll('[data-test-replication-link="manage"]').length) { await click('[data-test-replication-link="manage"]'); await click('[data-test-disable-replication] button'); await withFlash(click('[data-test-confirm-button]'), () => { if (assert) { assert.equal(currentURL(), `/vault/replication/${type}/manage`, 'redirects to the replication page'); assert.equal( // TODO better test selectors for flash messages find('[data-test-flash-message-body]').textContent.trim(), 'This cluster is having replication disabled. Vault will be unavailable for a brief period and will resume service shortly.', 'renders info flash when disabled' ); } }); await settled(); } }; module('Acceptance | Enterprise | replication', function(hooks) { setupApplicationTest(hooks); hooks.beforeEach(async function() { await authPage.login(); await disableReplication('dr'); return disableReplication('performance'); }); hooks.afterEach(async function() { await disableReplication('dr'); return disableReplication('performance'); }); test('replication', async function(assert) { const secondaryName = 'firstSecondary'; const mode = 'blacklist'; const mountType = 'kv'; let mountPath; await visit('/vault/replication'); assert.equal(currentURL(), '/vault/replication'); // enable perf replication await click('[data-test-replication-type-select="performance"]'); await fillIn('[data-test-replication-cluster-mode-select]', 'primary'); await withFlash(click('[data-test-replication-enable]')); await pollCluster(this.owner); // add a secondary with a mount filter config await click('[data-test-replication-link="secondaries"]'); await click('[data-test-secondary-add]'); await fillIn('[data-test-replication-secondary-id]', secondaryName); //expand the config await click('[data-test-replication-secondary-token-options]'); await fillIn('[data-test-replication-filter-mount-mode]', mode); await click(findAll(`[data-test-mount-filter="${mountType}"]`)[0]); mountPath = findAll(`[data-test-mount-filter-path-for-type="${mountType}"]`)[0].textContent.trim(); await click('[data-test-secondary-add]'); await pollCluster(this.owner); // click into the added secondary's mount filter config await click('[data-test-replication-link="secondaries"]'); await click('[data-test-popup-menu-trigger]'); await click('[data-test-replication-mount-filter-link]'); assert.equal(currentURL(), `/vault/replication/performance/secondaries/config/show/${secondaryName}`); assert.ok( find('[data-test-mount-config-mode]') .textContent.trim() .toLowerCase() .includes(mode), 'show page renders the correct mode' ); assert .dom('[data-test-mount-config-paths]') .hasText(mountPath, 'show page renders the correct mount path'); // click edit // delete config await click('[data-test-replication-link="edit-mount-config"]'); await click('[data-test-delete-mount-config] button'); await withFlash(click('[data-test-confirm-button]'), () => { assert.equal( findAll('[data-test-flash-message-body]')[0].textContent.trim(), `The performance mount filter config for the secondary ${secondaryName} was successfully deleted.`, 'renders success flash upon deletion' ); }); assert.equal( currentURL(), `/vault/replication/performance/secondaries`, 'redirects to the secondaries page' ); // nav to DR await visit('/vault/replication/dr'); await fillIn('[data-test-replication-cluster-mode-select]', 'secondary'); assert.ok( find('[data-test-replication-enable]:disabled'), 'dr secondary enable is disabled when other replication modes are on' ); // disable performance replication await disableReplication('performance', assert); await pollCluster(this.owner); // enable dr replication await visit('vault/replication/dr'); await fillIn('[data-test-replication-cluster-mode-select]', 'primary'); await withFlash(click('button[type="submit"]')); await pollCluster(this.owner); assert.ok( find('[data-test-replication-title]').textContent.includes('Disaster Recovery'), 'it displays the replication type correctly' ); assert.ok( find('[data-test-replication-mode-display]').textContent.includes('primary'), 'it displays the cluster mode correctly' ); // add dr secondary await click('[data-test-replication-link="secondaries"]'); await click('[data-test-secondary-add]'); await fillIn('[data-test-replication-secondary-id]', secondaryName); await click('[data-test-secondary-add]'); await pollCluster(this.owner); await pollCluster(this.owner); await click('[data-test-replication-link="secondaries"]'); assert .dom('[data-test-secondary-name]') .hasText(secondaryName, 'it displays the secondary in the list of known secondaries'); }); test('disabling dr primary when perf replication is enabled', async function(assert) { await visit('vault/replication/performance'); // enable perf replication await fillIn('[data-test-replication-cluster-mode-select]', 'primary'); await withFlash(click('[data-test-replication-enable]')); await pollCluster(this.owner); // enable dr replication await visit('/vault/replication/dr'); await fillIn('[data-test-replication-cluster-mode-select]', 'primary'); await withFlash(click('[data-test-replication-enable]')); await pollCluster(this.owner); await visit('/vault/replication/dr/manage'); assert.ok(findAll('[data-test-demote-warning]').length, 'displays the demotion warning'); }); });
JavaScript
0
@@ -811,23 +811,16 @@ /$%7Btype%7D -/manage %60, 'redi
b68d23487ca5c1d2c3fb52e0a13172dc75182c47
Update updateQuery params in TextField - pass object
packages/web/src/components/basic/TextField.js
packages/web/src/components/basic/TextField.js
import React, { Component } from "react"; import { connect } from "react-redux"; import { addComponent, removeComponent, watchComponent, updateQuery, setValue } from "@appbaseio/reactivecore/lib/actions"; import { isEqual, debounce, checkValueChange, checkPropChange } from "@appbaseio/reactivecore/lib/utils/helper"; import types from "@appbaseio/reactivecore/lib/utils/types"; import Input from "../../styles/Input"; import Title from "../../styles/Title"; class TextField extends Component { constructor(props) { super(props); this.type = "match"; this.state = { currentValue: "" }; } componentDidMount() { this.props.addComponent(this.props.componentId); this.setReact(this.props); if (this.props.selectedValue) { this.setValue(this.props.selectedValue, true); } else if (this.props.defaultSelected) { this.setValue(this.props.defaultSelected, true); } } componentWillReceiveProps(nextProps) { checkPropChange( this.props.react, nextProps.react, () => this.setReact(nextProps) ); if (this.props.defaultSelected !== nextProps.defaultSelected) { this.setValue(nextProps.defaultSelected, true, nextProps); } else if (this.state.currentValue !== nextProps.selectedValue) { this.setValue(nextProps.selectedValue || "", true, nextProps); } } componentWillUnmount() { this.props.removeComponent(this.props.componentId); } setReact(props) { if (props.react) { props.watchComponent(props.componentId, props.react); } } defaultQuery = (value) => { if (value && value.trim() !== "") { return { [this.type]: { [this.props.dataField]: value } }; } return null; } handleTextChange = debounce((value) => { this.updateQuery(value, this.props); }, 300); setValue = (value, isDefaultValue = false, props = this.props) => { const performUpdate = () => { this.setState({ currentValue: value }); if (isDefaultValue) { this.updateQuery(value, props); } else { // debounce for handling text while typing this.handleTextChange(value); } } checkValueChange( props.componentId, value, props.beforeValueChange, props.onValueChange, performUpdate ); }; updateQuery = (value, props) => { const query = props.customQuery || this.defaultQuery; let callback = null; if (props.onQueryChange) { callback = props.onQueryChange; } props.updateQuery(props.componentId, query(value, props), value, props.filterLabel, callback); // props.setValue(props.componentId, value); } render() { return ( <div> { this.props.title ? (<Title>{this.props.title}</Title>) : null } <Input type="text" placeholder={this.props.placeholder} onChange={(e) => this.setValue(e.target.value)} value={this.state.currentValue} /> </div> ); } } TextField.propTypes = { addComponent: types.addComponent, componentId: types.componentId, defaultSelected: types.string, react: types.react, removeComponent: types.removeComponent, dataField: types.dataField, title: types.title, beforeValueChange: types.beforeValueChange, onValueChange: types.onValueChange, customQuery: types.customQuery, onQueryChange: types.onQueryChange, updateQuery: types.updateQuery, placeholder: types.placeholder, selectedValue: types.selectedValue, setValue: types.setValue, filterLabel: types.string }; TextField.defaultProps = { placeholder: "Search" } const mapStateToProps = (state, props) => ({ selectedValue: state.selectedValues[props.componentId] && state.selectedValues[props.componentId].value || null }); const mapDispatchtoProps = (dispatch, props) => ({ addComponent: component => dispatch(addComponent(component)), removeComponent: component => dispatch(removeComponent(component)), watchComponent: (component, react) => dispatch(watchComponent(component, react)), updateQuery: (component, query, value, filterLabel, onQueryChange) => dispatch( updateQuery(component, query, value, filterLabel, onQueryChange) ), setValue: (component, value) => dispatch(setValue(component, value, props.filterLabel, true)) }); export default connect(mapStateToProps, mapDispatchtoProps)(TextField);
JavaScript
0
@@ -2299,24 +2299,29 @@ ;%0A%09%09let -callback +onQueryChange = null; @@ -2353,24 +2353,29 @@ e) %7B%0A%09%09%09 -callback +onQueryChange = props @@ -2414,16 +2414,34 @@ teQuery( +%7B%0A%09%09%09componentId: props.co @@ -2450,16 +2450,26 @@ onentId, +%0A%09%09%09query: query(v @@ -2481,23 +2481,36 @@ props), - +%0A%09%09%09 value, +%0A%09%09%09label: props.f @@ -2524,17 +2524,62 @@ bel, - callback +%0A%09%09%09showFilter: props.showFilter,%0A%09%09%09onQueryChange%0A%09%09%7D );%0A%09 @@ -3989,139 +3989,71 @@ y: ( -component, query, value, filterLabel, onQueryChange) =%3E dispatch(%0A%09%09updateQuery(component, query, value, filterLabel, onQueryChange +updateQueryObject) =%3E dispatch(%0A%09%09updateQuery(updateQueryObject )%0A%09)
a27475fbc72e838727bae0e6662bdb7de4502702
Fix a invalid variable name
lib/callback-end.js
lib/callback-end.js
module.exports = function blocklike(func){ return function(){ var args = Array.prototype.slice.apply(arguments); var callback = args[args.length - 1]; if (typeof callback === 'function') { while (args.length < func.length) { args.splice(args.length - 1, 0, undefined); } } return func.apply(this, args); }; };
JavaScript
0.999999
@@ -23,17 +23,19 @@ ion -blocklike +callbackEnd (fun
edbb9203fe8288b81e3ba3be970db365134c3c9a
Fix in TextPropertyEditor.
ui/TextPropertyEditor.js
ui/TextPropertyEditor.js
'use strict'; var Surface = require('./Surface'); var TextProperty = require('./TextPropertyComponent'); /** Editor for a text property (annotated string). Needs to be instantiated inside a {@link ui/Controller} context. @class @component @extends ui/Surface @prop {String} name unique editor name @prop {String[]} path path to a text property @prop {ui/SurfaceCommand[]} commands array of command classes to be available @example Create a `TextPropertyEditor` for the `name` property of an author object. Allow emphasis annotations. ```js $$(TextPropertyEditor, { name: 'authorNameEditor', path: ['author_1', 'name'], commands: [EmphasisCommand] }) ``` */ function TextPropertyEditor() { Surface.apply(this, arguments); } TextPropertyEditor.Prototype = function() { this.render = function($$) { var el = Surface.prototype.render.call(this); el.addClass("sc-text-property-editor"); el.append( $$(TextProperty, { tagName: "div", path: this.props.path }) ); if (this.isEditable()) { el.attr('contenteditable', true); } return el; }; /** Selects all text */ this.selectAll = function() { var doc = this.getDocument(); var path = this.props.path; var text = doc.get(path); var sel = doc.createSelection({ type: 'property', path: path, startOffset: 0, endOffset: text.length }); this.setSelection(sel); }; }; Surface.extend(TextPropertyEditor); module.exports = TextPropertyEditor;
JavaScript
0
@@ -885,16 +885,28 @@ der. -call(thi +apply(this, argument s);%0A
c050d0c76dab885c7afb2563577da2381a893547
Refactor Attributes to render array of trait names
src/components/Attributes.js
src/components/Attributes.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import Trait from './Trait'; const maxDots = 10; const rankDots = [7, 5, 3]; class Attributes extends Component { static propTypes = { attributes: PropTypes.object.isRequired, setRank: PropTypes.func.isRequired }; handleRankChange = (trait, dotsFromRank) => { this.props.setRank('attributes', trait, dotsFromRank); }; render() { const attributes = this.props.attributes; return ( <div> <h3>Attributes</h3> <Trait name="physical" maxDots={maxDots} rankDots={rankDots} traitState={attributes.physical} onRankChange={this.handleRankChange} /> <Trait name="social" maxDots={maxDots} rankDots={rankDots} traitState={attributes.social} onRankChange={this.handleRankChange} /> <Trait name="mental" maxDots={maxDots} rankDots={rankDots} traitState={attributes.mental} onRankChange={this.handleRankChange} /> <Link to="/skills">Skills</Link> </div> ); } } export default Attributes;
JavaScript
0
@@ -189,16 +189,69 @@ , 5, 3%5D; +%0Aconst traitNames = %5B'physical', 'social', 'mental'%5D; %0A%0Aclass @@ -529,16 +529,18 @@ const + %7B attribu @@ -542,16 +542,18 @@ tributes + %7D = this. @@ -561,323 +561,115 @@ rops -.attributes;%0A%0A return (%0A %3Cdiv%3E%0A %3Ch3%3EAttributes%3C/h3%3E%0A %3CTrait%0A name=%22physical%22%0A maxDots=%7BmaxDots%7D%0A rankDots=%7BrankDots%7D%0A +;%0A%0A const traits = traitNames.map(name =%3E (%0A -t +%3CT rait -State=%7Battributes.physical%7D%0A onRankChange=%7Bthis.handleRankChange%7D%0A /%3E%0A %3CTrait%0A name=%22social%22%0A +%0A key=%7Bname%7D%0A name=%7Bname%7D%0A max @@ -656,33 +656,32 @@ =%7Bname%7D%0A - maxDots=%7BmaxDots @@ -674,34 +674,32 @@ xDots=%7BmaxDots%7D%0A - rankDots @@ -710,34 +710,32 @@ nkDots%7D%0A - - traitState=%7Battr @@ -744,19 +744,16 @@ utes -.social%7D%0A +%5Bname%5D%7D%0A @@ -803,133 +803,58 @@ - /%3E%0A - - %3CTrait%0A name=%22mental%22%0A maxDots=%7BmaxDots%7D%0A rankDots=%7BrankDots%7D%0A traitState=%7Ba +));%0A%0A return (%0A %3Cdiv%3E%0A %3Ch3%3EA ttri @@ -862,16 +862,13 @@ utes -.mental%7D +%3C/h3%3E %0A @@ -876,57 +876,16 @@ - onRankChange=%7Bthis.handleRankChange%7D%0A /%3E +%7Btraits%7D %0A
cb5782ad188f8939d8df68b7d7b7c47bb4934b6d
set timeout when checkout the new version
lib/check-update.js
lib/check-update.js
/** * Created by axetroy on 17-2-15. */ const path = require('path'); const co = require('co'); const Promise = require('bluebird'); const axios = require('axios'); const semver = require('semver'); const log4js = require('log4js'); const logger = log4js.getLogger('CHECK'); const pkg = require(path.join(__dirname, '../package.json')); const npmRegistry = `http://registry.npm.taobao.org`; function checkNewVersion() { // check the update return axios.get(`${npmRegistry}/${pkg.name}/latest`) .then(function (resp) { const remotePkg = resp.data; if (semver.gt(remotePkg.version, pkg.version)) { logger.warn(`The current version ${remotePkg} is not the latest, please run [npm install -g ${pkg.name}] update to ${remotePkg.version}`); } }) .catch(err => Promise.resolve()); } module.exports = function () { return checkNewVersion(); };
JavaScript
0
@@ -494,16 +494,33 @@ /latest%60 +, %7Btimeout: 2000%7D )%0A .t
a0a5f459b26209deaa1d3faebc35b2c67cfa6e5e
Remove name property
lib/cmds/playing.js
lib/cmds/playing.js
'use strict'; exports.info = { name: 'playing', desc: 'Posts a list of members playing the specified game.', usage: '<game>', aliases: [], }; const utils = require('../utilities'); exports.run = (client, msg, params = []) => new Promise((resolve, reject) => { if (msg.channel.type === 'dm') { utils.dmDenied(msg).then(resolve).catch(reject); return; } // Exit if no 'question' was asked if (params.length === 0) { utils.usage(msg, exports.info).then(resolve).catch(reject); return; } const game = params.join(' '); const players = msg.guild.members .filter(m => m.user.presence.game && m.user.presence.game.name.toLowerCase().includes(game.toLowerCase())) .map(m => { return { name: m.user.username, modified: m.user.username.toLowerCase(), game: m.user.presence.game.name }; }) .sort((a, b) => { if (a.modified < b.modified) { return -1; } if (a.modified > b.modified) { return 1; } return 0; }) .map(p => `**${p.name}** (${p.game})`); if (players.length === 0) { msg.channel.sendMessage(`Nobody is playing \`\`${game}\`\``).then(resolve).catch(reject); } else { msg.channel.sendMessage(`\`\`\`qml\n${players.length} playing ${game}:\`\`\`\n${players.join('\n')}`) .then(resolve).catch(reject); } });
JavaScript
0.000013
@@ -28,27 +28,8 @@ = %7B%0A - name: 'playing',%0A de
6b9f3c38ba15a803331a1846fc1e1d81be729343
Raise error same to synchronous version
lib/command-line.js
lib/command-line.js
var program = require('commander'); var nroonga = require('./wrapped-nroonga'); var Domain = require('./database/domain').Domain; var version = require('../package').version; var path = require('path'); var awssum = require('awssum'); var amazon = awssum.load('amazon/amazon'); var CloudSearch = awssum.load('amazon/cloudsearch').CloudSearch; var defaultDatabasePath = exports.defaultDatabasePath = CommandLineInterface.defaultDatabasePath = process.env.GCS_DATABASE_PATH || process.env.HOME + '/.gcs/database/gcs'; var defaultPort = exports.defaultPort = CommandLineInterface.defaultPort = process.env.GCS_PORT || 7575; var defaultBaseHost = exports.defaultBaseHost = CommandLineInterface.defaultBaseHost = process.env.GCS_BASE_HOST || '127.0.0.1.xip.io:' + defaultPort; var defaultConfigurationHost = exports.defaultConfigurationHost = CommandLineInterface.defaultConfigurationHost = process.env.GCS_CONFIGURATION_HOST || '127.0.0.1.xip.io:' + defaultPort; var defaultPrivilegedRanges = exports.defaultPrivilegedRanges = CommandLineInterface.defaultPrivilegedRanges = process.env.GCS_PRIVILEGED_RANGES || '127.0.0.0/8'; function CommandLineInterface() { this.program = program; this.reservedUsage = null; this.reservedOptions = []; } CommandLineInterface.prototype = { get cloudSearch() { if (!this._couldSearch) { this._cloudSearch = new CloudSearch({ accessKeyId: 'dummy-access-key-id', secretAccessKey: 'dummy-access-key', }); var CLI = this; this._cloudSearch.host = function() { return CLI.options.baseHost.split(':')[0]; }; this._cloudSearch.addExtras = function(options, args) { options.protocol = 'http'; options.port = CLI.options.baseHost.split(':')[1] || CLI.options.port; }; } return this._cloudSearch; }, get domainName() { return this.options.domainName; }, get databasePath() { return this.options.databasePath || defaultDatabasePath; }, get context() { return this._context || (this._context = new nroonga.Context(this.databasePath)); }, get domain() { return this._domain || (this._domain = new Domain(this.options.domainName, this.context)); }, get options() { return this.program; }, parse: function() { this.program.version(version); if (this.reservedUsage) this.program.usage.apply(this.program, this.reservedUsage); else this.program.usage('[options]'); this.reservedOptions.forEach(function(optionArguments) { this.program.option.apply(this.program, optionArguments); }, this); this.program .option('--database-path <path>', 'database path' + '(GCS_DATABASE_PATH) ' + '[' + defaultDatabasePath + ']', String, defaultDatabasePath) .option('-p, --port <port>', 'specify port' + '(GCS_PORT) ' + '[' + defaultPort + ']', Number, defaultPort) .option('--base-host <hostname>', 'The base host name assigned to the service ' + '(GCS_BASE_HOST) ' + '[' + defaultBaseHost + ']', String, defaultBaseHost); this.program.parse(process.argv); return this; }, usage: function() { this.reservedUsage = Array.prototype.slice.call(arguments, 0) return this; }, option: function() { this.reservedOptions.push(Array.prototype.slice.call(arguments, 0)); return this; }, prompt: function() { return this.prompt.confirm.apply(this.program, arguments); }, confirm: function() { return this.program.confirm.apply(this.program, arguments); }, raiseFatalError: function(error) { if (typeof error != 'string') error = 'Unexpected error: ' + JSON.stringify(error); console.log(error); process.exit(1); }, assertHaveDomainName: function() { if (!this.domainName) this.raiseFatalError('You must specify the domain name.'); return this; }, getDomainStatus: function(domainName, callback) { var self = this; this.getDomainStatuses( { 'DomainNames.member.1' : domainName }, function(error, domainStatuses) { if (domainStatuses.length) { callback(null, domainStatuses[0]); } else { self.raiseFatalError('You must specify an existing domain name.'); } } ); }, getDomainStatuses: function(options, callback) { var self = this; var domainStatusesCallback = function(error, response) { if (error) self.raiseFatalError(error); var domainStatuses = response.Body .DescribeDomainsResponse .DescribeDomainsResult .DomainStatusList .member; (callback || options)(null, domainStatuses); }; if (callback) this.cloudSearch.DescribeDomains(options, domainStatusesCallback); else this.cloudSearch.DescribeDomains(domainStatusesCallback); }, getIndexFieldStatuses: function(domainName, callback) { var self = this; this.cloudSearch.DescribeIndexFields( { DomainName: domainName }, function(error, response) { if (error) self.raiseFatalError(error); var indexFields = response.Body .DescribeIndexFieldsResponse .DescribeIndexFieldsResult .IndexFields; indexFields = Array.isArray(indexFields.member) ? indexFields.member : []; callback(null, indexFields); } ); }, summarizeIndexFieldStatus: function(status) { var type = status.Options.TextOptions ? 'text' : status.Options.UIntOptions ? 'uint' : status.Options.LiteralOptions ? 'literal' : null; var options = status.Options.TextOptions || status.Options.UIntOptions || status.Options.LiteralOptions; var summarizedOptions = []; if (type == 'text' || type == 'uint' || options.SearchEnabled == 'true') summarizedOptions.push('Search'); if (type != 'uint' && options.FacetEnabled == 'true') summarizedOptions.push('Facet'); if (type == 'uint' || options.ResultEnabled == 'true') summarizedOptions.push('Result'); return status.Options.IndexFieldName + ' ' + status.Status.State + ' ' + type + ' (' + summarizedOptions.join(' ') + ')'; }, assertDomainExistsHTTP: function(callback) { this.getDomainStatus(this.domainName, function(error, domain) { callback(); }); }, assertDomainExists: function() { if (!this.domain.exists()) this.raiseFatalError('You must specify an existing domain name.'); return this; }, hasOption: function(option) { return this.program.rawArgs.indexOf('--' + option) > -1 || this.program.rawArgs.indexOf('-' + option) > -1; }, hasTooManyExclusiveOptions: function(options) { var havingOptions = options.map(function(option) { return this.option[option] ? '*' : '' ; }, this); return havingOptions.join('').length > 1; } }; exports.CommandLineInterface = CommandLineInterface; CommandLineInterface.resolve = function(possibleRelativePath) { return path.resolve(process.cwd(), possibleRelativePath); }; exports.Domain = CommandLineInterface.Domain = Domain;
JavaScript
0
@@ -6687,24 +6687,116 @@ , domain) %7B%0A + if (error)%0A self.raiseFatalError('You must specify an existing domain name.');%0A callba
5f45c42f6dac6c5c818e328b4c82ae6c1bcc5386
fix index off-by-one error.
search_last_occ.js
search_last_occ.js
var pattern = "Wor"; var m = pattern.length; var string = "Hello, World!"; var n = string.length; var last_occ = {}; for (var k = 0; k < m - 2; k++) { last_occ[pattern[k]] = m - 1 - k; } var i = 0; while (i <= n - m) { var j = 0; while (j < m && pattern[j] == string[i + j]) { j = j + 1; } if (j == m) { console.log("found match at " + i); } i = i + (last_occ[string[i + m - 1]] || m); }
JavaScript
0.000001
@@ -131,16 +131,17 @@ = 0; k %3C += m - 2;
7e0f8fc57bfffbce320d7bb896d271d3931d7bb9
handle skipped message as information_source.
services/logs2slack/src/readFromRabbitMQ.js
services/logs2slack/src/readFromRabbitMQ.js
// @flow const { logger } = require('@lagoon/commons/src/local-logging'); const { getSlackinfoForProject } = require('@lagoon/commons/src/api'); var IncomingWebhook = require('@slack/client').IncomingWebhook; export type ChannelWrapper = { ack: (msg: Object) => void, } export type RabbitMQMsg = { content: Buffer, fields: Object, properties: Object, }; export type Project = { slack: Object, name: string, }; async function readFromRabbitMQ (msg: RabbitMQMsg, channelWrapperLogs: ChannelWrapper): Promise<void> { const { content, fields, properties, } = msg; const logMessage = JSON.parse(content.toString()) const { severity, project, uuid, event, meta, message } = logMessage const appId = msg.properties.appId || "" logger.verbose(`received ${event}`, logMessage) switch (event) { case "github:pull_request:closed:handled": case "github:pull_request:opened:handled": case "github:pull_request:synchronize:handled": case "github:delete:handled": case "github:push:handled": case "bitbucket:repo:push:handled": case "gitlab:push:handled": case "rest:deploy:receive": case "rest:remove:receive": sendToSlack(project, message, '#E8E8E8', ':information_source:', channelWrapperLogs, msg, appId) break; case "task:deploy-openshift:finished": case "task:remove-openshift:finished": case "task:remove-openshift-resources:finished": case "task:builddeploy-openshift:complete": sendToSlack(project, message, 'good', ':white_check_mark:', channelWrapperLogs, msg, appId) break; case "task:deploy-openshift:retry": case "task:remove-openshift:retry": case "task:remove-openshift-resources:retry": sendToSlack(project, message, 'warning', ':warning:', channelWrapperLogs, msg, appId) break; case "task:deploy-openshift:error": case "task:remove-openshift:error": case "task:remove-openshift-resources:error": case "task:builddeploy-openshift:failed": sendToSlack(project, message, 'danger', ':bangbang:', channelWrapperLogs, msg, appId) break; case "github:pull_request:closed:CannotDeleteProductionEnvironment": case "github:push:CannotDeleteProductionEnvironment": case "bitbucket:repo:push:CannotDeleteProductionEnvironment": case "gitlab:push:CannotDeleteProductionEnvironment": case "rest:remove:CannotDeleteProductionEnvironment": sendToSlack(project, message, 'warning', ':warning:', channelWrapperLogs, msg, appId) break; case "unresolvedProject:webhooks2tasks": case "unhandledWebhook": case "webhooks:receive": case "task:deploy-openshift:start": case "task:remove-openshift:start": case "task:remove-openshift-resources:start": case "task:builddeploy-openshift:running": // known logs entries that should never go to slack channelWrapperLogs.ack(msg) break; default: logger.info(`unhandled log message ${event} ${JSON.stringify(logMessage)}`) return channelWrapperLogs.ack(msg) } } const sendToSlack = async (project, message, color, emoji, channelWrapperLogs, msg, appId) => { let projectSlacks; try { projectSlacks = await getSlackinfoForProject(project) } catch (error) { logger.error(`No Slack information found, error: ${error}`) return channelWrapperLogs.ack(msg) } projectSlacks.forEach(async (projectSlack) => { await new IncomingWebhook(projectSlack.webhook, { channel: projectSlack.channel, }).send({ attachments: [{ text: `${emoji} ${message}`, color: color, "mrkdwn_in": ["pretext", "text", "fields"], footer: appId }] }); }); channelWrapperLogs.ack(msg) return } module.exports = readFromRabbitMQ;
JavaScript
0
@@ -1198,24 +1198,56 @@ e:receive%22:%0A + case %22github:push:skipped%22:%0A sendTo
4dda3962aadb04d7e0e1dd0e2cd553963771b842
Update init.js
lib/console/init.js
lib/console/init.js
'use strict'; var pathFn = require('path'); var chalk = require('chalk'); var fs = require('hexo-fs'); var tildify = require('tildify'); var spawn = require('hexo-util/lib/spawn'); var assign = require('object-assign'); var Promise = require('bluebird'); var commandExistsSync = require('command-exists').sync; var ASSET_DIR = pathFn.join(__dirname, '../../assets'); var GIT_REPO_URL = 'https://github.com/hexojs/hexo-starter.git'; function initConsole(args) { args = assign({ install: true, clone: true }, args); var baseDir = this.base_dir; var target = args._[0] ? pathFn.resolve(baseDir, args._[0]) : baseDir; var log = this.log; var promise; var npmCommand; log.info('Cloning hexo-starter to', chalk.magenta(tildify(target))); if (args.clone) { promise = spawn('git', ['clone', '--recursive', GIT_REPO_URL, target], { stdio: 'inherit' }); } else { promise = copyAsset(target); } return promise.catch(function() { log.warn('git clone failed. Copying data instead'); return copyAsset(target); }).then(function() { return Promise.all([ removeGitDir(target), removeGitModules(target) ]); }).then(function() { if (!args.install) return; log.info('Install dependencies'); if (commandExistsSync('yarn')) { npmCommand = 'yarn'; } else { npmCommand = 'npm' } return spawn(npmCommand, ['install', '--production'], { cwd: target, stdio: 'inherit' }); }).then(function() { log.info('Start blogging with Hexo!'); }).catch(function() { log.warn('Failed to install dependencies. Please run \'npm install\' manually!'); }); } function copyAsset(target) { return fs.copyDir(ASSET_DIR, target, { ignoreHidden: false }); } function removeGitDir(target) { var gitDir = pathFn.join(target, '.git'); return fs.stat(gitDir).catch(function(err) { if (err.cause && err.cause.code === 'ENOENT') return; throw err; }).then(function(stats) { if (stats) { if (stats.isDirectory()) return fs.rmdir(gitDir); return fs.unlink(gitDir); } }).then(function() { return fs.readdir(target); }).map(function(path) { return pathFn.join(target, path); }).filter(function(path) { return fs.stat(path).then(function(stats) { return stats.isDirectory(); }); }).each(removeGitDir); } function removeGitModules(target) { return fs.unlink(pathFn.join(target, '.gitmodules')).catch(function(err) { if (err.cause && err.cause.code === 'ENOENT') return; throw err; }); } module.exports = initConsole;
JavaScript
0.000001
@@ -1263,20 +1263,16 @@ cies');%0A - %0A if @@ -1365,16 +1365,17 @@ = 'npm' +; %0A %7D%0A%0A
b0e22ec674173e449d3858565b254ec007b690bc
increase timeout to 4sec
cypress/support/index.js
cypress/support/index.js
export const DEBUG_FLAG = false; // *********************************************************** // This example support/index.js is processed and // loaded automatically before your test files. // // This is a great place to put global configuration and // behavior that modifies Cypress. // // You can change the location of this file or turn off // automatically serving support files with the // 'supportFile' configuration option. // // You can read more here: // https://on.cypress.io/configuration // *********************************************************** // Import commands.js using ES2015 syntax: // import './commands'; // Alternatively you can use CommonJS syntax: // require('./commands') // You can mock if needed. Example below // beforeEach(() => { // cy.server(); // cy.route('/countries*', {}); // }) /* returning false here prevents Cypress from failing the test */ Cypress.on('uncaught:exception', (err, runnable) => false); Cypress.Commands.overwrite( 'type', (originalFn, subject, string, options) => originalFn( subject, string, Object.assign({}, options, { delay: 100 }), ), ); function getItem(selector, counter) { cy.wait(50, { log: DEBUG_FLAG }) .get('#storybook-preview-iframe', { log: DEBUG_FLAG }) .then(($iframe) => { if (!$iframe.contents().find(selector).length && counter > 0) { return getItem(selector, --counter); } return cy.wrap($iframe.contents().find(selector)); }); } Cypress.Commands.add('iFrame', (selector) => { getItem(selector, 40); });
JavaScript
0.000044
@@ -1179,17 +1179,18 @@ cy.wait( -5 +10 0, %7B log
3cc730b9b5f98263b1c75a8d650144314617be3f
Add comments to PostsShow
src/components/posts_show.js
src/components/posts_show.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { fetchPost, deletePost } from '../actions'; class PostsShow extends Component { componentDidMount() { const { id } = this.props.match.params; this.props.fetchPost(id); } onDeleteClick() { const { id } = this.props.match.params; this.props.deletePost(id, () => { this.props.history.push('/'); }); } render() { const { post } = this.props; if (!post) { return <div>Loading...</div>; } return ( <div> <Link to="/">Back To Index</Link> <button className="btn btn-danger pull-xs-right" onClick={this.onDeleteClick.bind(this)} > Delete Post </button> <h3>{post.title}</h3> <h6>Categories: {post.categories}</h6> <p>{post.content}</p> </div> ); } } function mapStateToProps({ posts }, ownProps) { return { post: posts[ownProps.match.params.id] }; } export default connect(mapStateToProps, { fetchPost, deletePost })(PostsShow);
JavaScript
0
@@ -224,24 +224,85 @@ idMount() %7B%0A + // fetch post with id that matches ID param value in URL%0A const %7B @@ -396,47 +396,180 @@ -const %7B id %7D = this.props.match.params; +// delete post with id that matches ID param value in URL%0A const %7B id %7D = this.props.match.params;%0A // pass callback to action creator to redirect after post deletion %0A @@ -1181,60 +1181,284 @@ %7B%0A -return %7B post: posts%5BownProps.match.params.id%5D %7D;%0A%7D%0A +// in 'posts' state, find post with key/id that matches id param value in URL%0A // pass as prop%0A return %7B post: posts%5BownProps.match.params.id%5D %7D;%0A%7D%0A%0A// connect Redux state to PostsIndex component by having Redux pass%0A// necessary pieces of state and action creators as props %0Aexp
ae20245de42bfa980f46709b40d24fbf6772f547
fix lint error
src/components/switch-box.js
src/components/switch-box.js
import React from 'react'; export default class SwitchBox extends React.Component { constructor() { super(); this.state = { hasStarted: false, isComplete: false, hasClicked: false }; this.startTime = null; this.stopTime = null; } componentWillMount() { // setTimeout(() => {this._finish()}, 10000) } render() { let boxDiv = <div></div> let resultsDiv = <div></div> let actionButton = <div></div> if (this.state.isComplete) { if (this.state.hasClicked) { boxDiv = <div className='redBox'><p className='checked'>&#x2713;</p></div>; resultsDiv = <div className='results'><p>{this._latency()} ms</p></div> actionButton = <div><p><button onClick={this._reset.bind(this)}>TRY AGAIN!</button></p></div> } else { // wonder if should detect key press instead of click boxDiv = <div className='redBox' onClick={this._record_click.bind(this)}></div>; } } else { boxDiv = <div className='greenBox'></div>; if (this.state.hasStarted) { actionButton = <div></div> } else { actionButton = <div><p><button onClick={this._timeout.bind(this)}>GO!</button></p></div> } } return( <div> {boxDiv} {resultsDiv} {actionButton} </div> ); } _finish() { this.setState({ isComplete: true }); this._start_timer(); } _start_timer() { this.startTime = performance.now(); console.log('startTime:', this.startTime); } _stop_timer() { this.stopTime = performance.now(); console.log('stopTime', this.stopTime); } _reset() { this.startTime = null; this.stopTime = null; this.setState({ hasClicked: false, isComplete: false, hasStarted: false }); } _timeout() { // maybe have some random timeout between green and red states this.setState({ hasStarted: true }) let rand = Math.round(Math.random() * (3000 - 500)) + 500; setTimeout(() => { console.log("Wait for it..."); this._finish(); }, rand); } _countdown() { // maybe have a countdown before the test starts } _latency() { return (this.stopTime - this.startTime).toFixed(2) } _record_click() { this._stop_timer(); this.setState({ hasClicked: true }); } }
JavaScript
0.000006
@@ -1963,18 +1963,20 @@ %7D)%0A -le +cons t rand =
e1f23c0fee6cc3986bce73198105593f363ab730
Update RPC data encoding
src/conbo/net/HttpService.js
src/conbo/net/HttpService.js
/** * HTTP Service * * Base class for HTTP data services, default settings are designed for JSON * REST APIs; parseFunction required for XML data sources * * @class conbo.HttpService * @augments conbo.EventDispatcher * @author Neil Rackett */ conbo.HttpService = conbo.EventDispatcher.extend( /** @lends conbo.HttpService.prototype */ { constructor: function(options) { conbo.setValues(this, conbo.pick(options || {}, 'rootUrl', 'contentType', 'dataType', 'isRpc', 'headers', 'parseFunction', 'resultClass', 'makeObjectsBindable' )); conbo.EventDispatcher.prototype.constructor.apply(this, arguments); }, get rootUrl() { return this._rootUrl || ''; }, set rootUrl(value) { value = String(value); if (value && value.slice(-1) != '/') { value += '/'; } this._rootUrl = value; }, call: function(command, data, method, resultClass) { var contentType; data = conbo.clone(data) || {}; method || (method = 'GET'); resultClass || (resultClass = this.resultClass); contentType = this.contentType || (this.isRpc ? 'application/json' : 'application/x-www-form-urlencoded'); command = this.parseUrl(command, data); data = this.isRpc ? (method == 'GET' ? undefined : JSON.stringify(conbo.isFunction(data.toJSON) ? data.toJSON() : data)) : data; var promise = $.ajax ({ data: data, type: 'GET', headers: this.headers, url: this.rootUrl+command, contentType: contentType, dataType: this.dataType, dataFilter: this.parseFunction }); var token = new conbo.AsyncToken ({ promise: promise, resultClass: resultClass, makeObjectsBindable: this.makeObjectsBindable }); token.addResponder(new conbo.Responder(this.dispatchEvent, this.dispatchEvent, this)); return token; }, /** * Add one or more remote commands as methods of this class instance * @param {String} command * @param {String} method * @param {Class} resultClass */ addCommand: function(command, method, resultClass) { if (conbo.isObject(command)) { method = command.method; resultClass = command.resultClass; command = command.command; } this[conbo.toCamelCase(command)] = function(data) { return this.call(command, data, method, resultClass); }; return this; }, /** * Add multiple commands as methods of this class instance * @param {Array} commands */ addCommands: function(commands) { if (!conbo.isArray(commands)) { return this; } commands.forEach(function(command) { this.addCommand(command); }, this); return this; }, /** * Splice data into URL and remove spliced properties from data object */ parseUrl: function(url, data) { var parsedUrl = url, matches = parsedUrl.match(/:\b\w+\b/g); if (!!matches) { matches.forEach(function(key) { key = key.substr(1); if (!(key in data)) { throw new Error('Property "'+key+'" required but not found in data'); } }); } conbo.keys(data).forEach(function(key) { var regExp = new RegExp(':\\b'+key+'\\b', 'g'); if (regExp.test(parsedUrl)) { parsedUrl = parsedUrl.replace(regExp, data[key]); delete data[key]; } }); return parsedUrl; }, toString: function() { return 'conbo.HttpService'; } }).implement(conbo.IInjectable);
JavaScript
0.000001
@@ -1236,19 +1236,16 @@ data);%0A -%09%09%0A %09%09data = @@ -1259,118 +1259,32 @@ sRpc -%0A%09%09%09? (method == 'GET' ? undefined : JSON.stringify(conbo.isFunction(data.toJSON) ? data.toJSON() : data))%0A%09%09%09 + ? JSON.stringify(data) : da @@ -1342,21 +1342,22 @@ %09%09type: -'GET' +method ,%0A%09%09%09hea
b7a3bc6ff840a9a35b6718eb53f5209677e07c27
add log out const
src/constants/ActionTypes.js
src/constants/ActionTypes.js
export const USER_LOGGED_IN = 'USER_LOGGED_IN'
JavaScript
0.000001
@@ -40,8 +40,57 @@ GED_IN'%0A +export const USER_LOGGED_OUT = 'USER_LOGGED_OUT'%0A
f75b90291b98921094813c7cf7fd65ca01c2e51f
make it better
src/containers/search_bar.js
src/containers/search_bar.js
import React from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux' import {fetchWeather} from '../actions/index' function mapStateToProps(state) { return {}; } class SearchBar extends React.Component { constructor(props) { super(props); this.state = { term: '' }; this.onInputChange = this.onInputChange.bind(this); this.onSubmit = this.onSubmit.bind(this); } onInputChange(event) { event.preventDefault(); this.setState({term: event.target.value}) } onSubmit(e) { console.log('need to look for', this.state.term) e.preventDefault(); this.props.fetchWeather(this.state.term) this.setState({term: ''}); } componentDidMount() { var input = document.getElementById('pac-input'); var autocomplete = new google.maps.places.Autocomplete(input,{ types: ['geocode'] }); } render() { return ( <form onSubmit={this.onSubmit} className="input-group"> <div id="pac-container"> <input id="pac-input" placeholder="Select location" className="form-control" value={this.state.term} onChange={this.onInputChange}/> </div> <span className="input-group-btn"> <button className="btn btn-secondary" type="submit">Submit</button> </span> </form> ); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ fetchWeather }, dispatch) } //adding the fetchWeather to the props and binding it so when it changes, it will re-render my component export default connect(null, mapDispatchToProps)(SearchBar) // set first arg to null because i dont care about states for this component but only it's props
JavaScript
0.000086
@@ -875,16 +875,183 @@ de'%5D %7D); +%0A%0Agoogle.maps.event.addListener(autocomplete,'place_changed', ()=%3E%7B this.props.fetchWeather(autocomplete.getPlace().formatted_address); this.setState(%7Bterm: ''%7D) %7D); %0A %7D%0A%0A
ecc9a22b27f5163354f01b1b5b8ccf46da5b05ed
Add toggle cmd
src/core/group/group.view.js
src/core/group/group.view.js
import {View} from '../view'; import {Command} from '../command'; import {flatView as nodeFlatView} from '../node'; import {getFactory as valueFactory} from '../services/value'; export class GroupView extends View { constructor(model, commandManager) { super(model); this.valueFactory = valueFactory; this.toggleStatus = new Command({ execute: node => { if (!node) { node = model.navigation().cell.row; } node.state.expand = !node.state.expand; const view = model.view; const nodes = view().nodes; view({rows: nodeFlatView(nodes)}, {behavior: 'core', source: 'group.view'}); }, canExecute: node => { if (!node) { const cell = model.navigation().cell; if (cell && cell.column.type === 'group') { node = cell.row; } } return node && node.type === 'group'; }, shortcut: model.group().shortcut.toggle }); const shortcut = model.action().shortcut; shortcut.register(commandManager, [this.toggleStatus]); } count(node) { return node.children.length || node.rows.length; } status(node) { return node.state.expand ? 'expand' : 'collapse'; } offset(node) { const groupColumn = (this.model.view().columns[0] || []).find(c => c.model.type === 'group'); if (groupColumn) { return groupColumn.model.offset * node.level; } return 0; } value(node) { return node.key; } }
JavaScript
0.000001
@@ -420,24 +420,108 @@ row;%0A%09%09%09%09%7D%0A%0A +%09%09%09%09const toggle = model.group().toggle;%0A%09%09%09%09if (toggle.execute(node) !== false) %7B%0A%09 %09%09%09%09node.sta @@ -552,16 +552,17 @@ expand;%0A +%09 %09%09%09%09cons @@ -582,24 +582,25 @@ l.view;%0A%09%09%09%09 +%09 const nodes @@ -615,16 +615,17 @@ .nodes;%0A +%09 %09%09%09%09view @@ -697,16 +697,22 @@ iew'%7D);%0A +%09%09%09%09%7D%0A %09%09%09%7D,%0A%09%09 @@ -876,24 +876,65 @@ %09%09%09%7D%0A%09%09%09%09%7D%0A%0A +%09%09%09%09const toggle = model.group().toggle;%0A %09%09%09%09return n @@ -961,16 +961,43 @@ 'group' + && toggle.canExecute(node) ;%0A%09%09%09%7D,%0A
8c5922ff56feaf3891858e16d280803e74bc0aa8
Fix a few unlikely issues with empty trade iterations (Binance)
importers/exchanges/binance.js
importers/exchanges/binance.js
const moment = require('moment'); const util = require('../../core/util.js'); const _ = require('lodash'); const log = require('../../core/log'); var config = util.getConfig(); var dirs = util.dirs(); var Fetcher = require(dirs.exchanges + 'binance'); util.makeEventEmitter(Fetcher); var end = false; var done = false; var from = false; var fetcher = new Fetcher(config.watch); var fetch = () => { fetcher.import = true; fetcher.getTrades(from, handleFetch); }; var handleFetch = (unk, trades) => { if (trades.length > 0) { var last = moment.unix(_.last(trades).date); if (last < from) { log.debug( 'Skipping data, they are before from date (probably a programming error)', last.format() ); return fetch(); } } var next = from.add(1, 'd'); if (next >= end) { fetcher.emit('done'); var endUnix = end.unix(); trades = _.filter(trades, t => t.date <= endUnix); } from = next.clone(); fetcher.emit('trades', trades); }; module.exports = function(daterange) { from = daterange.from.clone(); end = daterange.to.clone(); return { bus: fetcher, fetch: fetch, }; };
JavaScript
0.000007
@@ -581,211 +581,189 @@ ate) +.utc() ;%0A -%0A if (last %3C from) %7B%0A log.debug(%0A 'Skipping data, they are before from date (probably a programming error)',%0A last.format()%0A );%0A return fetch();%0A %7D%0A %7D%0A%0A var next = + var next = last.clone();%0A %7D else %7B%0A var next = from.clone().add(1, 'd');%0A log.debug('Import step returned no results, moving to the next 24h period');%0A %7D%0A%0A if ( from @@ -778,20 +778,8 @@ 'd') -;%0A if (next %3E= @@ -1029,24 +1029,30 @@ from.clone() +.utc() ;%0A end = da @@ -1069,16 +1069,22 @@ .clone() +.utc() ;%0A%0A ret
36b73f8bbba1194cfeb222509b35e3d450601d42
add space between icon and autocomplete result
content/abAutoComplete.js
content/abAutoComplete.js
"use strict"; Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); //derived from https://dxr.mozilla.org/comm-central/source/mozilla/accessible/tests/mochitest/autocomplete.js var abAutoComplete = { tbSyncAutoCompleteSearch : null, /** * Register 'tbSyncAutoCompleteSearch' AutoCompleteSearch. */ init : function () { abAutoComplete.tbSyncAutoCompleteSearch = new abAutoComplete.Search("tbSyncAutoCompleteSearch"); abAutoComplete.register(abAutoComplete.tbSyncAutoCompleteSearch, "AutoCompleteSearch"); }, /** * Unregister 'tbSyncAutoCompleteSearch' AutoCompleteSearch. */ shutdown : function () { abAutoComplete.unregister(abAutoComplete.tbSyncAutoCompleteSearch); abAutoComplete.tbSyncAutoCompleteSearch.cid = null; abAutoComplete.tbSyncAutoCompleteSearch = null; }, /** * Register the given AutoCompleteSearch. * * @param aSearch [in] AutoCompleteSearch object * @param aDescription [in] description of the search object */ register : function (aSearch, aDescription) { var name = "@mozilla.org/autocomplete/search;1?name=" + aSearch.name; var uuidGenerator = Components.classes["@mozilla.org/uuid-generator;1"].getService(Components.interfaces.nsIUUIDGenerator); var cid = uuidGenerator.generateUUID(); var componentManager = Components.manager.QueryInterface(Components.interfaces.nsIComponentRegistrar); componentManager.registerFactory(cid, aDescription, name, aSearch); // Keep the id on the object so we can unregister later. aSearch.cid = cid; }, /** * Unregister the given AutoCompleteSearch. */ unregister : function (aSearch) { var componentManager = Components.manager.QueryInterface(Components.interfaces.nsIComponentRegistrar); componentManager.unregisterFactory(aSearch.cid, aSearch); }, /** * nsIAutoCompleteSearch implementation. * * @param aName [in] the name of autocomplete search */ Search : function (aName) { this.name = aName; }, /** * nsIAutoCompleteResult implementation. */ Result : function (aValues, aComments) { this.values = aValues; this.comments = aComments; if (this.values.length > 0) this.searchResult = Components.interfaces.nsIAutoCompleteResult.RESULT_SUCCESS; else this.searchResult = Components.interfaces.nsIAutoCompleteResult.NOMATCH; }, } abAutoComplete.Search.prototype = { constructor: abAutoComplete.Search, // nsIAutoCompleteSearch implementation startSearch : Task.async (function* (aSearchString, aSearchParam, aPreviousResult, aListener) { var result = yield this.getAutoCompleteResultFor(aSearchString); aListener.onSearchResult(this, result); }), stopSearch() {}, // nsISupports implementation QueryInterface: XPCOMUtils.generateQI(["nsIFactory", "nsIAutoCompleteSearch"]), //ChromeUtils // nsIFactory implementation createInstance(outer, iid) { return this.QueryInterface(iid); }, // Search name. Used by AutoCompleteController. name: null, /** * Return AutoCompleteResult for the given search string. */ getAutoCompleteResultFor : Task.async (function* (aSearchString) { //check each account and init server request let accounts = tbSync.db.getAccounts(); let requests = []; let values = []; let comments = []; if (aSearchString.length > 3) { for (let i=0; i<accounts.IDs.length; i++) { let account = accounts.IDs[i]; let provider = accounts.data[account].provider; let status = accounts.data[account].status; if (status == "disabled") continue; //start all requests parallel (do not wait till done here, no yield, push the promise) if (tbSync[provider].abServerSearch) { requests.push(tbSync[provider].abServerSearch (account, aSearchString)); } } //wait for all requests to finish (only have to wait for the slowest, all others are done) for (let r=0; r < requests.length; r++) { let results = yield requests[r]; for (let count=0; count < results.length; count++) { if (results[count].autocomplete) { values.push(results[count].autocomplete.value); comments.push(results[count].autocomplete.account); } } } } return new abAutoComplete.Result(values, comments); }) } abAutoComplete.Result.prototype = { constructor: abAutoComplete.Result, searchString: "", searchResult: null, defaultIndex: 0, get matchCount() { return this.values.length; }, getValueAt(aIndex) { return this.values[aIndex]; }, /** * This returns the string that is displayed in the dropdown */ getLabelAt(aIndex) { return this.getValueAt(aIndex) + " (" + this.getCommentAt(aIndex) + ")"; }, /** * Get the comment of the result at the given index */ getCommentAt(aIndex) { return this.comments[aIndex]; }, /** * Get the style hint for the result at the given index */ getStyleAt(aIndex) { return null; }, /** * Get the image of the result at the given index */ getImageAt(aIndex) { return "chrome://tbsync/skin/contacts16.png"; }, /** * Get the final value that should be completed when the user confirms * the match at the given index. */ getFinalCompleteValueAt(aIndex) { return this.getValueAt(aIndex); }, removeValueAt(aRowIndex, aRemoveFromDb) {}, // nsISupports implementation QueryInterface: XPCOMUtils.generateQI(["nsIAutoCompleteResult"]), //ChromeUtils // Data values: null, comments: null }
JavaScript
0.000006
@@ -5265,32 +5265,39 @@ %7B%0A return + %22 %22 + this.getValueAt
09f39fdc3cf1b13b0b36a770d516411e883b1d4b
add not valid file
01-syntax/08-regexp/numbersAgain.js
01-syntax/08-regexp/numbersAgain.js
// Your code here.
JavaScript
0.000019
@@ -12,8 +12,19 @@ e here.%0A + var iiiii%0A
15c1a8d179e0ea6ba8621008ee24fd6ce00a4f73
Use MessageService in TermApplication
src/core/term-application.js
src/core/term-application.js
import { AbstractApplication } from 'yabf' import program from 'commander' import { LogUtils } from '../shared/utils' import { MessageService } from '../services' import { Command } from './command' export class TermApplication extends AbstractApplication { get version() { return this._version || '0.0.0' } set version(semanticVersion) { this._version = semanticVersion } get description() { return this._desc } set description(text) { this._desc = text } constructor(injector, messageService) { super(injector) this.messageService = messageService } buildInstructions() { return [ { provide: TermApplication, dependencies: [MessageService] }, { provide: MessageService, dependencies: [] } ] } register(command, deps = []) { if (!(command.prototype instanceof Command)) { return null } this.commands = [command, ...(this.commands || [])] this.injectorService.provide(command, deps, false) } start() { if (!Array.isArray(this.commands) || this.commands.length < 1) { LogUtils.log({ message: `No command found in Term Application` }) this.messageService.printError('Application failed to initialize') return } program .version(this.version) .description(this.description) for (const commandClass of this.commands) { const controller = this.injectorService.get(commandClass) let command = program.command(controller.commandName) if (controller.alias != null) { command = command.alias(controller.alias) } if (controller.alias != null && controller.description.length > 0) { command = command.description(controller.description) } if (Array.isArray(controller.options)) { for (const [option, optionDesc] of controller.options) { command = command.option(option, optionDesc) } } if ('run' in controller && typeof controller.run === 'function') { const action = controller.run.bind(controller) const wrappedAction = this._wrapActions(action) command.action(wrappedAction) } } program.parse(process.argv) } _wrapActions(action) { return (...args) => { try { action(...args) } catch (error) { this.messageService.printError('Fail', 'An error occured.') } } } }
JavaScript
0
@@ -73,51 +73,8 @@ r'%0A%0A -import %7B LogUtils %7D from '../shared/utils'%0A impo @@ -1039,32 +1039,34 @@ -LogUtils.log(%7B message: +this.messageService.print( %60No @@ -1103,12 +1103,9 @@ ion%60 - %7D)%0A +) %0A
f4e5369fc11b698ada5fd26a301599962e06946b
Check existence of gamelist.xml
src/lib/utils.js
src/lib/utils.js
import config from 'config'; import fs from 'fs'; import path from 'path'; import md5File from 'md5-file'; import xml2js from 'xml2js'; export function uniqueID() { function chr4() { return Math.random().toString(16).slice(-4); } return chr4() + chr4() + '-' + chr4() + '-' + chr4() + '-' + chr4() + '-' + chr4() + chr4() + chr4(); } // Traitement d'une ligne du fichier readme.txt des BIOS const md5Rule = /^[a-f0-9]{32}$/i; const biosPath = config.get('recalbox.biosPath'); export function handleBiosLine(line) { let parts = line.split(' '); if (!parts[0].match(md5Rule)) { return null; } parts = parts.filter(Boolean); const md5 = parts.shift(); const name = parts.join(' ').trim(); const thisBiosPath = path.join(biosPath, name); return { md5: md5, name: name, valid: fs.existsSync(thisBiosPath) ? md5 === md5File.sync(thisBiosPath) : null }; } // Traitement des ROMs export async function getRoms(system, subpath = '') { const srcpath = path.join(config.get('recalbox.romsPath'), system, subpath); const esSystems = await getEsSystems(); const systemData = esSystems.find((s) => s.name === system); const romExtensions = systemData ? systemData.extensions : []; return fs.readdirSync(srcpath).filter((file) => { return fs.statSync(path.join(srcpath, file)).isFile() && -1 !== romExtensions.indexOf(path.extname(file)); }); } // Promise xml2json async function xmlToJson(file) { var promise = await new Promise((resolve, reject) => { const parser = new xml2js.Parser({ trim: true, explicitArray: false }); parser.parseString(fs.readFileSync(file), (jsError, jsResult) => { if (jsError) { reject(jsError); } else { resolve(jsResult); } }); }); return promise; } // Traitements des systèmes supportés par ES let esSystems; export async function getEsSystems() { if (esSystems) { return esSystems; } const json = await xmlToJson(config.get('recalbox.esSystemsCfgPath')); esSystems = []; json.systemList.system.forEach((system) => { esSystems.push({ name: system.name, fullname: system.fullname, path: system.path, extensions: system.extension ? system.extension.split(' ') : [], launchCommand: system.command, }); }); return esSystems; } // Traitement des fichiers gamelist.xml export function parseGameReleaseDate(releaseDate) { return { day: releaseDate.substring(6, 8), month: releaseDate.substring(4, 6), year: releaseDate.substring(0, 4), }; } export function getSystemRomsBasePath(system) { return path.join(config.get('recalbox.romsPath'), system); } export function getSystemGamelistPath(system) { return path.join(getSystemRomsBasePath(system), 'gamelist.xml'); } export async function getSystemGamelist(system, raw = false) { const json = await xmlToJson(getSystemGamelistPath(system)); if (raw) { return json; } let list = {}; let gameList = json.gameList.game || []; if (!Array.isArray(gameList)) { gameList = [gameList]; } gameList.forEach((game) => { list[game.path.substring(2)] = game; }); return list; }
JavaScript
0
@@ -2873,24 +2873,137 @@ = false) %7B%0A + const gameListPath = getSystemGamelistPath(system);%0A%0A if (!fs.existsSync(gameListPath)) %7B%0A return %7B%7D;%0A %7D%0A%0A const json @@ -3026,36 +3026,19 @@ on(g -etSystemG ame -l +L istPath -(system) );%0A%0A
4fd84db4c5c5572c973eb02a1c4c6eb339e9142d
remove JSON.stringify to properly serialize data
troposphere/static/js/actions/HelpActions.js
troposphere/static/js/actions/HelpActions.js
define( [ 'jquery', 'controllers/NotificationController', 'globals' ], function ($, NotificationController, globals) { return { sendFeedback: function (feedback) { var data = {}; // The message from the use data["message"] = feedback; // Size information for the user's browser and monitor data['resolution'] = { 'viewport': { 'width': $(window).width(), 'height': $(window).height() }, 'screen': { 'width': screen.width, 'height': screen.height } }; var feedbackUrl = globals.API_ROOT + '/email/feedback' + globals.slash(); $.ajax(feedbackUrl, { type: 'POST', data: JSON.stringify(data), success: function (data) { NotificationController.info("Thanks for your feedback!", "Support has been notified."); }, error: function (response_text) { var errorMessage = "Your feedback could not be submitted. If you'd like to send it directly to support, email <a href='mailto:[email protected]'>[email protected]</a>."; NotificationController.error("An error occured", errorMessage); } }); } }; });
JavaScript
0.000119
@@ -771,28 +771,12 @@ ta: -JSON.stringify( data -) ,%0A
7c61e09661c641bfdc868dbff3cdee23484efff4
create keyPressListener callback before using it
content/komodowakatime.js
content/komodowakatime.js
var komodoWakatime = { VERSION: '2.0.1', action_frequency: 2, time: 0, api_key: '', view: null, fileName: '', keyPressListener: null, onLoad: function (thisObject) { var prefs = Components.classes['@activestate.com/koPrefService;1'] .getService(Components.interfaces.koIPrefService) .prefs; var pref_name = 'wakatime_api_key'; komodoWakatime.initViewListener(komodoWakatime); if (!prefs.hasStringPref(pref_name) || prefs.getStringPref(pref_name) === '') { thisObject.api_key = thisObject.promptForAPIKey(); prefs.setStringPref('wakatime_api_key', thisObject.api_key); } else { thisObject.api_key = prefs.getStringPref(pref_name); } }, log: function(msg) { ko.logging.getLogger('').warn(msg); }, apiClientLocation: function () { var currProfPath = Components.classes["@mozilla.org/file/directory_service;1"] .getService(Components.interfaces.nsIProperties) .get("PrefD", Components.interfaces.nsILocalFile) .path; var plugin_dir = currProfPath + '/extensions/[email protected]'; return plugin_dir + '/components/wakatime/cli.py'; }, promptForAPIKey: function () { return ko.dialogs.prompt("[WakaTime] Enter your wakatime.com api key:"); }, getFileName: function (thisObject) { return thisObject.fileName; }, enoughTimePassed: function (thisObject) { var d = new Date(); if ((d.getTime() - thisObject.time) > thisObject.action_frequency * 60000) { thisObject.time = d.getTime(); return true; } return false; }, sendDataToAPI: function (thisObject, writeFlag) { writeFlag = typeof writeFlag !== 'undefined' ? writeFlag : false; var cmdWriteFlag = writeFlag ? '--write' : ''; var fileName = thisObject.getFileName(thisObject); var cmd = 'python ' + thisObject.apiClientLocation().replace(/(@)/g, "\\@").replace(/(\s)/g, "\\ ") + ' ' + cmdWriteFlag + ' --file ' + fileName + ' --plugin komodo-wakatime/'+ thisObject.VERSION + ' --key ' + thisObject.api_key; var runSvc = Components.classes["@activestate.com/koRunService;1"] .createInstance(Components.interfaces.koIRunService); var process = runSvc.RunAndNotify(cmd, '', '', ''); }, keyPressEvent: function (thisObject) { if (thisObject.enoughTimePassed(thisObject)) { thisObject.sendDataToAPI(thisObject); } }, fileSaveEvent: function (thisObject) { thisObject.sendDataToAPI(thisObject, true); }, initViewListener: function (thisObject) { if (thisObject.view !== null) { thisObject.view.removeEventListener('keypress', thisObject.keyPressListener, true); } thisObject.keyPressListener = function (event) { thisObject.keyPressEvent(thisObject, event); }; if (ko.views.manager.currentView !== null) { thisObject.view = ko.views.manager.currentView; thisObject.view.addEventListener('keypress', thisObject.keyPressListener, true); } }, fileChanged: function (thisObject, event) { thisObject.fileName = event.originalTarget.koDoc.file.displayPath; ko.views.manager.currentView.removeEventListener('keypress', thisObject.keyPressListener, true); thisObject.keyPressListener = function (event) { thisObject.keyPressEvent(thisObject, event); }; thisObject.view = event.originalTarget; thisObject.view.addEventListener('keypress', thisObject.keyPressListener, true); } }; window.addEventListener('file_saved', function (event) { komodoWakatime.fileSaveEvent(komodoWakatime, event); }, false); window.addEventListener('current_view_changed', function (event) { komodoWakatime.fileChanged(komodoWakatime, event); }, true); window.addEventListener('komodo-ui-started', function (event) { komodoWakatime.onLoad(komodoWakatime, event); }, true);
JavaScript
0
@@ -395,65 +395,8 @@ y';%0A - komodoWakatime.initViewListener(komodoWakatime);%0A @@ -699,32 +699,89 @@ ame);%0A %7D%0A + komodoWakatime.initViewListener(komodoWakatime);%0A %7D,%0A log: @@ -2744,32 +2744,157 @@ (thisObject) %7B%0A + thisObject.keyPressListener = function (event) %7B%0A thisObject.keyPressEvent(thisObject, event);%0A %7D;%0A if (this @@ -3027,133 +3027,8 @@ %7D%0A - thisObject.keyPressListener = function (event) %7B%0A thisObject.keyPressEvent(thisObject, event);%0A %7D;%0A @@ -3373,113 +3373,8 @@ th;%0A - ko.views.manager.currentView.removeEventListener('keypress', thisObject.keyPressListener, true);%0A @@ -3486,32 +3486,137 @@ nt);%0A %7D;%0A + ko.views.manager.currentView.removeEventListener('keypress', thisObject.keyPressListener, true);%0A thisObje
44e094541123d7fd08b68b05a0f9999d1ff0260e
Update apps.js
app/apps.js
app/apps.js
(function () { 'use strict'; angular .module('DeezerKids', [ // Angular modules. 'ngRoute', 'ngCookies', 'ngAnimate', 'ngMaterial', 'ngMessages' ]) .config(config) .run(run); config.$inject = ['$routeProvider', '$locationProvider', '$mdDateLocaleProvider', '$mdThemingProvider']; function config($routeProvider, $locationProvider, $mdDateLocaleProvider, $mdThemingProvider) { $routeProvider.otherwise({ redirectTo: '/login' }); $mdDateLocaleProvider.months = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember']; $mdDateLocaleProvider.shortMonths = ['Jan', 'Feb', 'Mrz', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez']; $mdDateLocaleProvider.days = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag']; $mdDateLocaleProvider.shortDays = ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa']; // Can change week display to start on Monday. $mdDateLocaleProvider.firstDayOfWeek = 1; // Example uses moment.js to parse and format dates. $mdDateLocaleProvider.parseDate = function (dateString) { var m = moment(dateString, 'DD.MM.YYYY', true); return m.isValid() ? m.toDate() : new Date(NaN); }; $mdDateLocaleProvider.formatDate = function (date) { return moment(date).format('DD.MM.YYYY'); }; $mdDateLocaleProvider.monthHeaderFormatter = function (date) { return $mdDateLocaleProvider.shortMonths[date.getMonth()] + ' ' + date.getFullYear(); }; // In addition to date display, date components also need localized messages // for aria-labels for screen-reader users. $mdDateLocaleProvider.weekNumberFormatter = function (weekNumber) { return 'Woche ' + weekNumber; }; $mdDateLocaleProvider.msgCalendar = 'Kalender'; $mdDateLocaleProvider.msgOpenCalendar = 'Kalender öffnen'; $mdThemingProvider .theme('default') .primaryPalette('green') .accentPalette('blue-grey'); } run.$inject = ['$rootScope', '$location', '$cookieStore', '$http']; function run($rootScope, $location, $cookieStore, $http) { // keep user logged in after page refresh $rootScope.globals = $cookieStore.get('globals') || {}; if ($rootScope.globals.currentUser) { $http.defaults.headers.common['Authorization'] = $rootScope.globals.currentUser.uid; } $rootScope.$on('$locationChangeStart', function (event, next, current) { // redirect to login page if not logged in and trying to access a restricted page var restrictedPage = $.inArray($location.path(), ['/login']) === -1; var loggedIn = $rootScope.globals.currentUser; if (restrictedPage && !loggedIn) { $location.path('/login'); } }); } })();
JavaScript
0.000002
@@ -553,21 +553,23 @@ ctTo: '/ -login +welcome '%0A @@ -2413,276 +2413,8 @@ ) %7B%0A - // keep user logged in after page refresh%0A $rootScope.globals = $cookieStore.get('globals') %7C%7C %7B%7D;%0A if ($rootScope.globals.currentUser) %7B%0A $http.defaults.headers.common%5B'Authorization'%5D = $rootScope.globals.currentUser.uid;%0A %7D%0A%0A @@ -2517,21 +2517,23 @@ rect to -login +welcome page if @@ -2539,58 +2539,20 @@ f no -t logged in and trying to access a restricted page + mode is set %0A @@ -2612,21 +2612,23 @@ h(), %5B'/ -login +welcome '%5D) === @@ -2647,24 +2647,20 @@ var -loggedIn +mode = $root @@ -2677,19 +2677,12 @@ als. -currentUser +mode ;%0A @@ -2718,16 +2718,12 @@ && ! -loggedIn +mode ) %7B%0A @@ -2759,13 +2759,15 @@ h('/ -login +welcome ');%0A
4be491ce4501ae04fadc75e86017b1700b0d15f9
Add defensive code to LastSensorDownload
src/widgets/SensorHeader/LastSensorDownload.js
src/widgets/SensorHeader/LastSensorDownload.js
import React, { useEffect, useRef } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { StyleSheet } from 'react-native'; import * as Animatable from 'react-native-animatable'; import moment from 'moment'; import { useIntervalReRender } from '../../hooks'; import { TextWithIcon } from '../Typography/index'; import { MILLISECONDS } from '../../utilities/index'; import { WifiIcon, WifiOffIcon } from '../icons'; import { MISTY_CHARCOAL } from '../../globalStyles/index'; import { selectIsDownloading, selectLastDownloadFailed, selectLastDownloadTime, } from '../../selectors/Bluetooth/sensorDownload'; import { vaccineStrings, generalStrings } from '../../localization'; import { selectSensorByMac } from '../../selectors/Entities/sensor'; const formatLastSyncDate = date => (date ? moment(date).fromNow() : generalStrings.not_available); const formatLogDelay = delay => `${vaccineStrings.logging_delayed_until}: ${moment(delay).format('DD/MM/YYYY @ HH:mm:ss')}`; export const LastSensorDownloadComponent = ({ isDownloading, lastDownloadFailed, lastDownloadTime, logDelay, }) => { useIntervalReRender(MILLISECONDS.TEN_SECONDS); const timeNow = new Date().getTime(); const isDelayed = logDelay > timeNow; const wifiRef = useRef(); useEffect(() => { if (isDownloading) wifiRef?.current.flash(MILLISECONDS.ONE_SECOND); else wifiRef?.current?.stopAnimation(); }, [isDownloading, wifiRef]); return ( <Animatable.View ref={wifiRef} animation="flash" easing="ease-out" iterationCount="infinite" style={{ justifyContent: 'center' }} > <TextWithIcon containerStyle={localStyles.headerTextWithIcon} margin={0} size="s" Icon={ lastDownloadFailed || isDelayed ? ( <WifiOffIcon size={20} color={MISTY_CHARCOAL} /> ) : ( <WifiIcon size={20} color={MISTY_CHARCOAL} /> ) } > {isDelayed ? formatLogDelay(logDelay) : formatLastSyncDate(lastDownloadTime)} </TextWithIcon> </Animatable.View> ); }; LastSensorDownloadComponent.defaultProps = { lastDownloadTime: null, logDelay: 0, }; LastSensorDownloadComponent.propTypes = { isDownloading: PropTypes.bool.isRequired, lastDownloadFailed: PropTypes.bool.isRequired, lastDownloadTime: PropTypes.instanceOf(Date), logDelay: PropTypes.number, }; const localStyles = StyleSheet.create({ headerTextWithIcon: { flex: 0, paddingHorizontal: 8, width: 150, justifyContent: 'flex-end', }, }); const stateToProps = (state, props) => { const { macAddress } = props; const lastDownloadTime = selectLastDownloadTime(state, macAddress); const lastDownloadFailed = selectLastDownloadFailed(state, macAddress); const isDownloading = selectIsDownloading(state, macAddress); const sensor = selectSensorByMac(state, macAddress); const { logDelay } = sensor; return { lastDownloadTime, lastDownloadFailed, isDownloading, logDelay }; }; export const LastSensorDownload = connect(stateToProps)(LastSensorDownloadComponent);
JavaScript
0
@@ -2963,16 +2963,22 @@ = sensor + ?? %7B%7D ;%0A%0A ret
bf7cea8a85ef7c4238c624505407d38cd5f6af58
Drop localStorage timeout
ui/js/app/LocalStorage.js
ui/js/app/LocalStorage.js
import { connect } from 'react-redux'; import _ from 'underscore'; const STATE_KEY = 'rippl_v1'; /** * Load saved state from local storage */ export function loadState() { try { const savedState = JSON.parse(localStorage.getItem(STATE_KEY)); if (savedState) { return { district: { id: savedState.district }, userCauses: savedState.userCauses, }; } } catch (e) {} // eslint-disable-line no-empty return {}; } /** * Save essential pieces of the current state to local storage */ const saveState = _.debounce((state) => { const essentialState = { district: state.district.id, userCauses: state.userCauses, }; localStorage.setItem(STATE_KEY, JSON.stringify(essentialState)); }, 5 * 1000); function StateSaverComponent(props) { setTimeout(() => saveState(props), 1); return props.children; } export const StateSaver = connect( state => state, )(StateSaverComponent);
JavaScript
0
@@ -739,9 +739,9 @@ %0A%7D, -5 +2 * 1
c5aa58931a2471c4ec1de9eefe0a8099d7dda885
resolve less dependencies recursively
source/application/transforms/less/index.js
source/application/transforms/less/index.js
import {resolve} from 'path'; import less from 'less'; import PatternImporterPlugin from 'less-plugin-pattern-import'; import NPMImporterPlugin from 'less-plugin-npm-import'; async function render (source, config) { return await less.render(source, config); } export default function lessTransformFactory (application) { return async function lessTransform (file, demo, configuration, forced = false) { const config = Object.assign({}, configuration); const patternPath = resolve(application.runtime.patterncwd || application.runtime.cwd, application.configuration.patterns.path); const dependencies = Object.keys(file.dependencies || {}).reduce(function getDependencyPaths (paths, dependencyName) { paths[dependencyName] = file.dependencies[dependencyName].path; return paths; }, {}); const plugins = Object.keys(config.plugins) .map((pluginName) => config.plugins[pluginName].enabled ? pluginName : false) .filter((item) => item); const pluginConfigs = plugins.reduce(function getPluginConfig (pluginResults, pluginName) { pluginResults[pluginName] = config.plugins[pluginName].opts || {}; return pluginResults; }, {}); config.opts.plugins = Array.isArray(config.opts.plugins) ? config.opts.plugins : []; config.opts.plugins = config.opts.plugins.concat( [ new NPMImporterPlugin(), new PatternImporterPlugin({'root': patternPath, 'patterns': dependencies}) ]); for (let pluginName of plugins) { let pluginConfig = pluginConfigs[pluginName]; if (pluginConfig) { let Plugin = require(`less-plugin-${pluginName}`); config.opts.plugins.push(new Plugin(pluginConfig)); } } let source = file.buffer.toString('utf-8'); var results = {}; var demoResults = {}; if (forced) { let injects = Object.keys(dependencies).map((dependency) => `@import '${dependency}';`); source = `${injects.join('\n')}\n${source}`; } results = await render(source, config.opts); if (demo) { let demoSource = demo.buffer.toString('utf-8'); let demoConfig = Object.assign({}, configuration); let demoDepdendencies = Object.assign({}, dependencies, {'Pattern': file.path}); demoConfig.opts.plugins.push(new PatternImporterPlugin({'root': patternPath, 'patterns': demoDepdendencies})); demoResults = await render(demoSource, demoConfig.opts); file.demoBuffer = new Buffer(demoResults.css || '', 'utf-8'); file.demoSource = demo.source; } file.buffer = new Buffer(results.css || '', 'utf-8'); file.in = config.inFormat; file.out = config.outFormat; return file; }; }
JavaScript
0.000024
@@ -49,17 +49,16 @@ 'less';%0A -%0A import P @@ -170,16 +170,17 @@ port';%0A%0A +%0A async fu @@ -315,24 +315,404 @@ lication) %7B%0A +%09// TODO: this is currently to permissive,%0A%09// forbid transitive access in the future%0A%09function getDependencies(file) %7B%0A%09%09return Object.entries(file.dependencies)%0A%09%09%09.reduce((paths, entry) =%3E %7B%0A%09%09%09%09const %5BdependencyName, dependencyFile%5D = entry;%0A%09%09%09%09return %7B%0A%09%09%09%09%09...paths,%0A%09%09%09%09%09...getDependencies(dependencyFile),%0A%09%09%09%09%09%5BdependencyName%5D: dependencyFile.path%0A%09%09%09%09%7D;%0A%09%09%09%7D, %7B%7D);%0A%09%7D%0A%0A %09return asyn @@ -766,24 +766,8 @@ tion -, forced = false ) %7B%0A @@ -817,17 +817,16 @@ ation);%0A -%0A %09%09const @@ -975,197 +975,28 @@ s = -Object.keys(file.dependencies %7C%7C %7B%7D).reduce(function getDependencyPaths (paths, dependencyName) %7B%0A%09%09%09paths%5BdependencyName%5D = file.dependencies%5BdependencyName%5D.path;%0A%09%09%09return paths;%0A%09%09%7D, %7B%7D +getDependencies(file );%0A%0A @@ -1618,18 +1618,20 @@ %0A%09%09for ( -le +cons t plugin @@ -1652,18 +1652,20 @@ s) %7B%0A%09%09%09 -le +cons t plugin @@ -1728,18 +1728,20 @@ ) %7B%0A%09%09%09%09 -le +cons t Plugin @@ -1853,632 +1853,63 @@ %0A%0A%09%09 -let source = file.buffer.toString('utf-8');%0A%09%09var results = %7B%7D;%0A%09%09var demoResults = %7B%7D;%0A%0A%09%09if (forced) %7B%0A%09%09%09let injects = Object.keys(dependencies).map((dependency) =%3E %60@import '$%7Bdependency%7D';%60);%0A%09%09%09source = %60$%7Binjects.join('%5Cn')%7D%5Cn$%7Bsource%7D%60;%0A%09%09%7D%0A%0A%09%09results = await render(source, config.opts);%0A%0A%09%09if (demo) %7B%0A%09%09%09let demoSource = demo.buffer.toString('utf-8');%0A%09%09%09let demoConfig = Object.assign(%7B%7D, configuration);%0A%09%09%09let demoDepdendencies = Object.assign(%7B%7D, dependencies, %7B'Pattern': file.path%7D);%0A%0A%09%09%09demoConfig.opts.plugins.push(new PatternImporterPlugin(%7B'root': patternPath, 'patterns': demoDepdendencies%7D));%0A%09%09%09demoR +const source = file.buffer.toString('utf-8');%0A%09%09const r esul @@ -1930,25 +1930,17 @@ der( -demoS +s ource, -demoC +c onfi @@ -1952,230 +1952,36 @@ s);%0A -%0A%09%09%09file.demoBuffer = new Buffer(demoResults.css %7C%7C '', 'utf-8');%0A%09%09%09file.demoSource = demo.source;%0A%09%09%7D%0A%0A%09%09file.buffer = new Buffer(results.css %7C%7C '', 'utf-8');%0A%0A%09%09file.in = config.inFormat;%0A%09%09file.out = config.outFormat;%0A +%09%09file.buffer = results.css; %0A%09%09r
319ffc13a3a533505201b340b0376b1e1995c880
Fix Hound linter comments and remove debugs
app/assets/javascripts/frontend/text-character-count.js
app/assets/javascripts/frontend/text-character-count.js
$.fn.charcount = function() { // Fixes label offset if ($(this).prev().is("label")) { $(this).prev().addClass("char-count-label"); } // Adds class to parent so that we can position the question and input closer var prevElement = this.closest(".question-group").prev(); if (prevElement.hasClass("clear")) { prevElement = prevElement.prev(); } prevElement.addClass("char-spacing"); if (prevElement.hasClass("errors-container")) { if (prevElement.prev().find(".char-space").size() <= 0) { prevElement.prev().append("<span class='char-space'></div>"); } } // Creates the character count elements this.wrap("<div class='char-count'></div>"); this.after("<div class='char-text'>Word count: <span class='current-count'>0</span></div>"); // Includes character limit if there is one this.each(function(){ var maxlength = parseInt($(this).attr("data-word-max"), 10); if (maxlength) { $(this).before("<div class='char-text-limit'>Word limit: <span class='total-count'>" +maxlength+ "</span></div>"); $(this).closest(".char-count").addClass("char-max-shift"); $(this).closest(".char-count").find(".char-text").append("/<span class='total-count'>" +maxlength+ "</span>"); // hard limit to word count var maxlengthlimit = maxlength *0.1; if (maxlengthlimit < 5) { maxlengthlimit = 5; } // Strict limit with no extra words if ($(this).closest(".word-max-strict").size() > 0) { maxlengthlimit = 0; } $(this).attr("data-word-max-limit", (maxlengthlimit)); } }); // If character count is over the limit then show error var characterOver = function(counter, textInput) { var lastLetter = textInput.val()[textInput.val().length - 1]; var maxWordCount = parseInt(textInput.attr("data-word-max"), 10); var maxWordCountLimit = parseInt(textInput.attr("data-word-max-limit"), 10); var maxWordCountTotal = maxWordCount + maxWordCountLimit; textInput.closest(".char-count").removeClass("char-over"); if (counter.words >= maxWordCount) { textInput.closest(".char-count").addClass("char-over"); } if (counter.words > maxWordCountTotal) { return true; } else if (counter.words == maxWordCountTotal && lastLetter == " ") { return true; } }; var cutOverChar = function(counter) { var textInput = $(this); var oldText = $(this).val(); var newText = ""; var wordMax = parseInt(textInput.attr("data-word-max"), 10); var wordMaxLimit = parseInt(textInput.attr("data-word-max-limit"), 10); var wordTotal = wordMax + wordMaxLimit; if (counter.words > wordTotal) { var oldTextArray = oldText.split(" "); var lastIndexOf = oldTextArray.length - 1; if (oldTextArray[oldTextArray.length - 1] === "") { lastIndexOf = oldTextArray.length - 2; } var lastIndex = oldText.split(" ", lastIndexOf).join(" ").length; if (oldText.lastIndexOf("\n") + 1 > lastIndex) { lastIndex = oldText.lastIndexOf("\n") + 1; } newText = oldText.substr(0, lastIndex) + " "; $(this).closest(".char-count").find(".char-text .current-count").text(wordTotal); } else { $(this).removeClass("char-over-cut"); newText = oldText; } if (newText[newText.length - 1] == " " && newText[newText.length - 2] == " ") { newText = $.trim(newText) + " "; } $(this).val(newText); }; var counting = function(counter) { var textInput = $(this); textInput.closest(".char-count").find(".char-text .current-count").text(counter.words); if (characterOver(counter, textInput)) { // hard limit to word count using maxlength if (((typeof(textInput.attr("maxlength")) !== typeof(undefined)) && textInput.attr("maxlength") !== false) === false) { // Set through typing var char_limit = textInput.val().length; textInput.attr("maxlength", char_limit); } } else { textInput.removeAttr("maxlength"); } $("textarea[maxlength]").each(function() { var text_events = $._data(this, "events"); if (text_events) { if (!("keydown" in text_events)) { $(this).on("keydown keyup", function (e) { $(this).addClass("char-over-cut"); while ($(this).hasClass("char-over-cut")) { Countable.once(this, cutOverChar); } }); } } }); }; var countText = function(counter) { $(this).attr("data-counted-words", counter.words); }; // Maxlength for pasting text $(this).on("paste", function (e) { var textInput = $(this); if ((e.originalEvent || e).clipboardData) { alert(1); var oldText = textInput.val(); var copyText = ((e.originalEvent || e).clipboardData.getData("text/plain")); if (!copyText.length > 0) { e.preventDefault(); textInput.after("<div id='oldText'>"+oldText+"</div>"); Countable.once($("#oldText")[0], countText); textInput.after("<div id='copyText'>"+copyText+"</div>"); Countable.once($("#copyText")[0], countText); var oldTextCount = parseInt($("#oldText").attr("data-counted-words"), 10); var copyTextCount = parseInt($("#copyText").attr("data-counted-words"), 10); $("#oldText").remove(); $("#copyText").remove(); var wordMax = parseInt(textInput.attr("data-word-max"), 10); var wordMaxLimit = parseInt(textInput.attr("data-word-max-limit"), 10); var wordTotal = wordMax + wordMaxLimit; var wordsNeeded = wordTotal - oldTextCount; var newCopytext = copyText; if (copyTextCount > wordsNeeded) { var copyPartIndex = copyText.split(" ", wordsNeeded).join(" ").length; newCopytext = $.trim(copyText.substr(0, copyPartIndex)) + " "; } if (newCopytext) { textInput.val(textInput.val() + newCopytext); Countable.once(this, counting); } } } else { setTimeout(function() { textInput.addClass("char-over-cut"); while (textInput.hasClass("char-over-cut")) { Countable.once(textInput[0], cutOverChar); } }, 10); } }); this.each(function() { // Makes word count dynamic Countable.live(this, counting); }); return this; }; // Gets character limit and allows no more $(function() { // Creates the character count elements $(".js-char-count").charcount(); }); $.fn.removeCharcountElements = function() { // Removes the character count elements $(this).unwrap(); $(".char-text, .char-text-limit", $(this).closest("li")).remove(); };
JavaScript
0
@@ -4091,26 +4091,25 @@ var text -_e +E vents = $._d @@ -4139,26 +4139,25 @@ if (text -_e +E vents) %7B%0A @@ -4188,10 +4188,9 @@ text -_e +E vent @@ -4235,33 +4235,32 @@ yup%22, function ( -e ) %7B%0A @@ -4709,24 +4709,8 @@ ) %7B%0A - alert(1);%0A @@ -4836,17 +4836,16 @@ if ( -! copyText
a58293b0928fb94cfa1a105d2aeb44a71a910b4f
fix calnedar storage bug
platforms/software/storage/calendar/storage.js
platforms/software/storage/calendar/storage.js
'use strict'; const path = require('path'); const _ = require('lodash'); const moment = require('moment'); const low = require('lowdb'); const storage = require('lowdb/file-sync'); const db = low(path.resolve(__dirname, './calendar.json'), { storage }); /* { date: 'time', //day date meetings: 'int' } */ const Calendar = { table: 'calendar', stamp: 'MM-DD-YYYY' }; Calendar.code = function(date){ return moment(date).format(Calendar.stamp); }; Calendar.decode = function(string){ return moment(string, Calendar.stamp).toDate(); }; Calendar.serialize = function(day){ day.date = Calendar.code(day.date); return day; }; Calendar.deserialize = function(day){ day.date = Calendar.decode(day.date); return day; }; Calendar.all = function(){ let days = db(Calendar.table) .chain() .value(); return _.map(days, Calendar.deserialize); }; Calendar.findByDate = function(date){ return _.find(db(Calendar.table).value(), { date: Calendar.code(date) }); }; Calendar.has = function(day){ return _.isUndefined(Calendar.findByDate(day.date)) === false; }; Calendar.save = function(day){ if(_.isUndefined(day)) return; if(Calendar.has(day) === false){ console.log('save not found:', day); db(Calendar.table).push(Calendar.serialize(day)); } else { Calendar.update(day); } }; Calendar.update = function(day){ console.log('update', day); return db(Calendar.table) .chain() .find({ date: Calendar.code(day.date) }) .assign({ meetings: day.meetings }) .value(); }; Calendar.filter = function(start){ if(_.isUndefined(start)) start = Date.now(); start = moment(Calendar.decode(Calendar.code(start))); let days = db(Calendar.table) .chain() .value(); days = _.filter(days, function(day){ let date = Calendar.decode(day.date); return start.isSameOrBefore(moment(date)) }); return _.map(days, Calendar.deserialize); }; Calendar.saveAll = function(days){ days.forEach(function(day){ Calendar.save(day); }); }; module.exports = Calendar;
JavaScript
0
@@ -602,34 +602,42 @@ ion(day)%7B%0A -day. +return %7B%0A date - = +: Calendar.co @@ -639,39 +639,77 @@ ar.code( -day.date);%0A return day +new Date(day.date.valueOf())),%0A meetings: day.meetings%0A %7D ;%0A%7D;%0A%0ACa @@ -750,18 +750,26 @@ %7B%0A -day. +return %7B%0A date - = +: Cal @@ -794,22 +794,40 @@ ate) -;%0A return day +,%0A meetings: day.meetings%0A %7D ;%0A%7D; @@ -1244,17 +1244,16 @@ return;%0A -%0A if(Cal @@ -1270,61 +1270,47 @@ day) - === false)%7B%0A console.log('save not found:', day); +)%7B%0A Calendar.update(day);%0A %7D else %7B %0A @@ -1364,45 +1364,8 @@ ));%0A - %7D else %7B%0A Calendar.update(day);%0A %7D%0A @@ -1405,39 +1405,8 @@ y)%7B%0A - console.log('update', day);%0A%0A re @@ -1747,17 +1747,29 @@ e();%0A%0A -d +let filteredD ays = _. @@ -1898,33 +1898,41 @@ %0A return _.map( -d +filteredD ays, Calendar.de
2efd2c476e24ed0b5e4ce70f5c7c5adf28687de0
Fix typo in `aria-labelledby`attribute
src/js/components/CheckBox.js
src/js/components/CheckBox.js
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component, PropTypes } from 'react'; const CLASS_ROOT = "check-box"; export default class CheckBox extends Component { set checked (value) { if ('refs' in this) { this.refs.input.checked = !!value; } } get checked () { return 'refs' in this ? this.refs.input.checked : null; } render () { var classes = [CLASS_ROOT]; var labelId = 'checkbox-label'; var hidden; if (this.props.toggle) { classes.push(CLASS_ROOT + "--toggle"); } if (this.props.disabled) { classes.push(CLASS_ROOT + "--disabled"); if (this.props.checked) { hidden = ( <input name={this.props.name} type="hidden" value="true"/> ); } } if (this.props.className) { classes.push(this.props.className); } return ( <label className={classes.join(' ')} aria-describedby={this.props.ariaDescribedby} aria-lebelledby={labelId}> <input tabIndex="0" className={CLASS_ROOT + "__input"} id={this.props.id} name={this.props.name} type="checkbox" disabled={this.props.disabled} checked={this.props.checked} defaultChecked={this.props.defaultChecked} onChange={this.props.onChange} ref="input" /> <span className={CLASS_ROOT + "__control"}> <svg className={CLASS_ROOT + "__control-check"} viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet"> <path fill="none" d="M6,11.3 L10.3,16 L18,6.2"></path> </svg> </span> {hidden} <span role="label" id={labelId} tabIndex="-1" className={CLASS_ROOT + "__label"}> {this.props.label} </span> </label> ); } } CheckBox.propTypes = { checked: PropTypes.bool, defaultChecked: PropTypes.bool, disabled: PropTypes.bool, id: PropTypes.string.isRequired, label: PropTypes.node.isRequired, name: PropTypes.string, onChange: PropTypes.func, ariaDescribedby: PropTypes.string, toggle: PropTypes.bool };
JavaScript
0.999756
@@ -993,17 +993,17 @@ aria-l -e +a belledby
351a7d8b6c1c709243496d067796a411d620df9a
Fix schedules passed down to DaySchedule
src/js/components/Schedule.js
src/js/components/Schedule.js
import React, { Component, PropTypes } from 'react'; import _ from 'lodash'; import DaySchedule from './DaySchedule'; import TimeColumn from './TimeColumn'; import StageColumn from './StageColumn'; export default class Schedule extends Component { static propTypes = { schedule: PropTypes.array.isRequired }; render() { const { schedule } = this.props; const groupedSchedules = _.groupBy(schedule, 'day'); return <div> <h1>Schedule</h1> <div> <a href='#'>Friday</a> <a href='#'>Saturday</a> <a href='#'>Sunday</a> </div> <TimeColumn times={[]} /> <StageColumn /> <DaySchedule day={'Friday'} schedule={schedule[0]}/> <DaySchedule day={'Saturday'} schedule={schedule[1]}/> <DaySchedule day={'Sunday'} schedule={schedule[2]}/> </div>; } }
JavaScript
0.000001
@@ -683,18 +683,37 @@ le=%7B -schedule%5B0 +groupedSchedules%5B'2016-08-05' %5D%7D/%3E @@ -763,18 +763,37 @@ le=%7B -schedule%5B1 +groupedSchedules%5B'2016-08-06' %5D%7D/%3E @@ -841,18 +841,37 @@ le=%7B -schedule%5B2 +groupedSchedules%5B'2016-08-07' %5D%7D/%3E
132a94c014b2b499a9951939d13586ba28f08dd8
fix generalized data fetching
src/js/services/timeseries.js
src/js/services/timeseries.js
angular.module('n52.core.timeseries', []) .service('timeseriesService', ['$rootScope', 'interfaceService', 'statusService', 'styleService', 'settingsService', 'utils', function($rootScope, interfaceService, statusService, styleService, settingsService, utils) { var defaultDuration = settingsService.timeseriesDataBuffer || moment.duration(2, 'h'); this.timeseries = {}; var tsData = {}; $rootScope.$on('timeExtentChanged', evt => { _loadAllData(this.timeseries); }); _loadAllData = function(timeseries) { // TODO evtl. erst wenn alle Daten da sind soll die Daten auch gesetzt werden??? angular.forEach(timeseries, ts => { _loadTsData(ts); }); }; _addTs = function(ts, timeseries) { ts.timebuffer = defaultDuration; styleService.createStylesInTs(ts); timeseries[ts.internalId] = ts; statusService.addTimeseries(ts); _loadTsData(ts); }; _loadTsData = function(ts) { var generalizeData = statusService.status.generalizeData || false; ts.loadingData = true; interfaceService.getTsData(ts.id, ts.apiUrl, utils.createBufferedCurrentTimespan(statusService.getTime(), ts.timebuffer, generalizeData)) .then(data => { _addTsData(data, ts); }); }; _createNewTimebuffer = function(data) { if (data.length >= 2) { var newDuration = moment.duration(data[1][0] - data[0][0]); if (newDuration > defaultDuration) { return newDuration; } else { return defaultDuration; } } return defaultDuration; }; _addTsData = function(data, ts) { ts.timebuffer = _createNewTimebuffer(data[ts.id].values); tsData[ts.internalId] = data[ts.id]; if (tsData[ts.internalId].values && tsData[ts.internalId].values.length) { ts.hasNoDataInCurrentExtent = false; } else { ts.hasNoDataInCurrentExtent = true; } $rootScope.$emit('timeseriesDataChanged', ts.internalId); ts.loadingData = false; }; this.getData = function(internalId) { return tsData[internalId]; }; this.getTimeseries = function(internalId) { return this.timeseries[internalId]; }; this.getAllTimeseries = function() { return this.timeseries; }; this.hasTimeseries = function(internalId) { return angular.isObject(this.timeseries[internalId]); }; this.getTimeseriesCount = function() { return Object.keys(this.timeseries).length; }; this.addTimeseriesById = function(id, apiUrl, params) { interfaceService.getTimeseries(id, apiUrl, params).then((data) => { if (angular.isArray(data)) { angular.forEach(data, ts => { _addTs(ts, this.timeseries); }); } else { _addTs(data, this.timeseries); } }); }; this.addTimeseries = function(ts) { _addTs(angular.copy(ts), this.timeseries); }; this.removeTimeseries = function(internalId) { styleService.deleteStyle(this.timeseries[internalId]); delete this.timeseries[internalId]; delete tsData[internalId]; statusService.removeTimeseries(internalId); $rootScope.$emit('timeseriesDataChanged', internalId); }; this.removeAllTimeseries = function() { angular.forEach(this.timeseries, elem => { this.removeTimeseries(elem.internalId); }); }; this.toggleReferenceValue = function(refValue, internalId) { refValue.visible = !refValue.visible; $rootScope.$emit('timeseriesDataChanged', internalId); }; this.isTimeseriesVisible = function(internalId) { return this.hasTimeseries(internalId) && this.timeseries[internalId].styles.visible; }; } ]);
JavaScript
0.000007
@@ -1416,16 +1416,23 @@ mebuffer +), null , genera @@ -1440,17 +1440,16 @@ izeData) -) %0A
624353fe9284a939c0864ad38be10c0ad03ba8c5
Fix unit-test
app/lib/readings-daily-aggregates-to-highcharts-data.js
app/lib/readings-daily-aggregates-to-highcharts-data.js
import {addIndex, findIndex, findLastIndex, map, memoize} from "ramda"; import moment from "moment"; const mapIndexed = addIndex(map); function getDailyAggregate (dailyAggregates, chartState) { const {sensorId, day, measurementType, source} = chartState; const date = [ moment.utc(day).subtract({day: 1}).format("YYYY-MM-DD"), day, moment.utc(day).add({day: 1}).format("YYYY-MM-DD") ]; const aggregates = date.map(dataDay => dailyAggregates.get( `${sensorId}-${dataDay}-${source}-${measurementType}` )); return aggregates.reduce((acc, aggregate) => { if (!aggregate) { return acc; } const times = aggregate.get("measurementTimes").split(","); const values = aggregate.get("measurementValues").split(","); return { values: [...acc.values, ...values], times: [...acc.times, ...times] }; }, {values: [], times: []}); } export default memoize((aggregates, chartsState) => { if (aggregates.isEmpty()) { return [{ data: [] }]; } const sortedAggregate = aggregates.sortBy(x => x.get("day")); const timeFromAggregate = !chartsState[0].period || chartsState[0].period === "day"; var result; if (timeFromAggregate) { const chartsData = map(chartState => { const {sensorId, day} = chartState; // Get daily aggregate with correct offset per timezone const aggregate = getDailyAggregate(sortedAggregate, chartState); const firstIndex = findIndex(time => parseInt(time) >= moment(day).valueOf() )(aggregate.times); var lastIndex = findLastIndex(time => parseInt(time) <= moment(day).endOf("day").valueOf() )(aggregate.times); if (lastIndex < 0 && firstIndex >= 0) { lastIndex = aggregate.values.length; } const values = aggregate.values.slice(firstIndex, lastIndex + 1); const times = aggregate.times.slice(firstIndex, lastIndex + 1); var data = []; data = mapIndexed((value, index) => { return { hour: moment.utc(parseInt(times[index])).add({minutes: moment().utcOffset()}).format("H"), value: parseFloat(value) }; }, values); return { toFill: sensorId.includes("-standby"), data }; }, chartsState); const filledChartsData = chartsData.map(chartData => { if (chartData.data.length == 0) { return []; } let filledChartData = []; for (var index = 0; index < 24; index++) { let measurements = chartData.data.filter(x => parseInt(x.hour) === index); let measurement = measurements.reduce((state, current) => { return { hour: current.hour, value: state ? state.value + current.value : current.value }; }, null); measurement ? filledChartData[index] = measurement : filledChartData[index] = { hour: index.toString(), value: chartData.toFill ? (filledChartData[index - 1] ? filledChartData[index - 1].value : chartData.data.find(x => x.value !== 0) ? chartData.data.find(x => x.value !== 0).value : 0) : 0 }; } return filledChartData; }); result = filledChartsData.map(data => { const chart = data.map(measurement => { return [measurement.hour, Math.round(measurement.value * 10) / 10]; }); const categories = data.map(measurement => { return [measurement.hour]; }); return { data: chart, categories: categories }; }); } else { const chartData = map(chartState => { const {sensorId, day, measurementType, source, period} = chartState; const time = moment.utc(day); const dayTime = moment.utc(day).startOf("year"); const aggregate = sortedAggregate.get( `${sensorId}-${dayTime.year()}-${source}-${measurementType}` ); var data = []; if (aggregate) { const values = aggregate.get("measurementValues").split(","); data = values.map((value, index) => { const obj = { period: dayTime.get(period), dayTime: dayTime, formatted: getFormat(period, dayTime), formattedTooltip: getFormatTooltip(period, dayTime), value: parseFloat(values[index]) || 0 }; dayTime.add(1, "day"); return obj; }).filter(x => x.period === time.get(period)); } if ("year" === period) { data = data.reduce((state, current) => { const finded = state.find(value => { return value.formattedTooltip === current.formattedTooltip; }); if (finded) { finded.value += current.value; return state; } else { return [ ...state, current ]; } }, []); } return data; }, chartsState); result = chartData.map(data => { const series = data.map(serie => { return [serie.formattedTooltip, Math.round(serie.value * 10) / 10]; }); const categories = data.map(serie => { return serie.formatted; }); const completedCategories = completeCategories(chartsState[0].period, categories); const completedSeries = completeChart(chartsState[0].period, series); return { data: completedSeries, categories: completedCategories }; }); } return result; }); function completeCategories (period, categories) { switch (period) { case "week": for (var x= categories.length; x<=6; x++) { categories.push(moment().weekday(x).format("ddd").substring(0, 1)); } break; case "month": var endOfMonth = moment().endOf("month").format("D")-1; for (x=categories.length; x<=endOfMonth; x++) { categories.push((x+1).toString()); } break; case "year": for (x= categories.length; x<=11; x++) { categories.push(moment().month(x).format("MMM").substring(0, 1).toUpperCase()); } break; } return categories; } function completeChart (period, chart) { switch (period) { case "week": for (var x= chart.length; x<=6; x++) { chart.push([x, 0]); } break; case "month": var endOfMonth = moment().endOf("month").format("D") -1; for (x=chart.length; x<=endOfMonth; x++) { chart.push([x, 0]); } break; case "year": for (x= chart.length; x<=11; x++) { chart.push([x, 0]); } break; } return chart; } function getFormat (period, dayTime) { switch (period) { case "week": return dayTime.format("ddd").substring(0, 1); case "month": return dayTime.format("D"); case "year": return dayTime.format("MMM").substring(0, 1).toUpperCase(); } } function getFormatTooltip (period, dayTime) { switch (period) { case "week": return dayTime.format("dddd"); case "month": return dayTime.format("D") + " " + dayTime.format("MMMM"); case "year": return dayTime.format("MMMM"); } }
JavaScript
0.000929
@@ -6591,17 +6591,20 @@ oment(). -w +ISOW eekday(x
5b2f89a0c754bb7b2c25bf4594fc4be371a60ed0
Change checkpoint interval to 10m
server/codecity.js
server/codecity.js
/** * @license * Code City: Server * * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview A virtual world of collaborative coding. * @author [email protected] (Neil Fraser) */ // Start with: node codecity.js <DB directory> 'use strict'; const fs = require('fs'); const path = require('path'); const Interpreter = require('./interpreter'); const Serializer = require('./serialize'); var CodeCity = {}; CodeCity.databaseDirectory = ''; CodeCity.interpreter = null; /** * Start a running instance of Code City. May be called on a command line. * @param {string=} opt_databaseDirectory Directory containing either a .city * database or startup files. If not present, look for the directory * as a command line parameter. */ CodeCity.startup = function(opt_databaseDirectory) { // process.argv is a list containing: ['node', 'codecity.js', 'databaseDir'] CodeCity.databaseDirectory = opt_databaseDirectory || process.argv[2]; // Check that the directory was specified and exists. try { var files = fs.readdirSync(CodeCity.databaseDirectory); } catch (e) { console.error('Database directory not found.\n' + 'Usage: node %s <DB directory>', process.argv[1]); if (CodeCity.databaseDirectory) { console.info(e); } process.exit(1); } // Find the most recent database file. files.sort(); for (var i = files.length - 1; i >= 0; i--) { if (files[i].match( /^\d{4}-\d\d-\d\dT\d\d\.\d\d\.\d\d(\.\d{1,3})?Z?\.city$/)) { break; } } // Load the interpreter. CodeCity.interpreter = new Interpreter({ trimEval: true, trimProgram: true, methodNames: true, }); CodeCity.initSystemFunctions(); if (i === -1) { // Database not found, load one or more startup files instead. console.log('Unable to find database file in %s, looking for startup ' + 'file(s) instead.', CodeCity.databaseDirectory); var fileCount = 0; for (var i = 0; i < files.length; i++) { if (files[i].match(/^(core|test).*\.js$/)) { var filename = path.join(CodeCity.databaseDirectory, files[i]); var contents = CodeCity.loadFile(filename); console.log('Loading startup file %s', filename); CodeCity.interpreter.createThreadForSrc(contents); fileCount++; } } if (fileCount === 0) { console.error('Unable to find startup file(s) in %s', CodeCity.databaseDirectory); process.exit(1); } console.log('Loaded %d startup file(s).', fileCount); } else { var filename = path.join(CodeCity.databaseDirectory, files[i]); var contents = CodeCity.loadFile(filename); // Convert from text to JSON. try { contents = JSON.parse(contents); } catch (e) { console.error('Syntax error in parsing JSON: %s', filename); console.info(e); process.exit(1); } Serializer.deserialize(contents, CodeCity.interpreter); console.log('Database loaded: %s', filename); } // Checkpoint at regular intervals. // TODO: Let the interval be configurable from the database. setInterval(CodeCity.checkpoint, 60 * 1000); console.log('Load complete. Starting Code City.'); CodeCity.interpreter.start(); }; /** * Open a file and read its contents. Die if there's an error. * @param {string} filename * @return {string} File contents. */ CodeCity.loadFile = function(filename) { // Load the specified file from disk. try { return fs.readFileSync(filename, 'utf8').toString(); } catch (e) { console.error('Unable to open file: %s\nCheck permissions.', filename); console.info(e); process.exit(1); } }; /** * Save the database to disk. * @param {boolean} sync True if Code City intends to shutdown afterwards. * False if Code City is running this in the background. */ CodeCity.checkpoint = function(sync) { console.log('Checkpointing...'); try { CodeCity.interpreter.pause(); var json = Serializer.serialize(CodeCity.interpreter); } finally { sync || CodeCity.interpreter.start(); } // JSON.stringify(json) would work, but adding linebreaks so that every // object is on its own line makes the output more readable. var text = []; for (var i = 0; i < json.length; i++) { text.push(JSON.stringify(json[i])); } text = '[' + text.join(',\n') + ']'; var filename = (new Date()).toISOString().replace(/:/g, '.') + '.city'; filename = path.join(CodeCity.databaseDirectory, filename); var tmpFilename = filename + '.partial'; try { fs.writeFileSync(tmpFilename, text); fs.renameSync(tmpFilename, filename); console.log('Checkpoint complete.'); } catch (e) { console.error('Checkpoint failed! ' + e); } finally { // Attempt to remove partially-written checkpoint if it still exists. try { fs.unlinkSync(tmpFilename); } catch (e) { } } }; /** * Shutdown Code City. Checkpoint the database before terminating. * Optional parameter is exit code (if numeric) or signal to (re-)kill * process with (if string). Re-killing after checkpointing allows * systemd to accurately determine cause of death. Defaults to 0. * @param {string|number=} code Exit code or signal. */ CodeCity.shutdown = function(code) { CodeCity.checkpoint(true); if (typeof code === 'string') { process.kill(process.pid, code); } else { process.exit(code || 0); } }; /** * Print one line to the log. Allows for interpolated strings. * @param {...*} var_args Arbitrary arguments for console.log. */ CodeCity.log = function(var_args) { console.log.apply(console, arguments); }; /** * Initialize user-callable system functions. * These are not part of any JavaScript standard. */ CodeCity.initSystemFunctions = function() { var intrp = CodeCity.interpreter; intrp.createNativeFunction('CC.log', CodeCity.log, false); intrp.createNativeFunction('CC.checkpoint', CodeCity.checkpoint, false); intrp.createNativeFunction('CC.shutdown', function(code) { CodeCity.shutdown(Number(code)); }, false); }; // If this file is executed form a command line, startup Code City. // Otherwise, if it is required as a library, do nothing. if (require.main === module) { CodeCity.startup(); // SIGTERM and SIGINT shut down server. process.once('SIGTERM', CodeCity.shutdown.bind(null, 'SIGTERM')); process.once('SIGINT', CodeCity.shutdown.bind(null, 'SIGINT')); // SIGHUP forces checkpoint. process.on('SIGHUP', CodeCity.checkpoint.bind(null, false)); } module.exports = CodeCity;
JavaScript
0.000023
@@ -3676,16 +3676,17 @@ oint, 60 +0 * 1000)
e37dc5bff5a33a11b13b937ab67d82c68206dcd0
Fix utils to get selection entities [ci skip]
app/scripts/RebooEditor/Toolbar/getSelectionEntities.js
app/scripts/RebooEditor/Toolbar/getSelectionEntities.js
import { Entity } from 'draft-js' const getSelectionEntities = (editorState, entityType) => { // Selection cursor const targetSelection = editorState.getSelection() const startOffset = targetSelection.getStartOffset() const endOffset = targetSelection.getEndOffset() const currentContent = editorState.getCurrentContent() const block = currentContent.getBlockForKey(targetSelection.getStartKey()) const entitiesSelection = [] block.findEntityRanges(character => { const entityKey = character.getEntity() return entityKey !== null && Entity.get(entityKey).getType() === entityType }, (start, end) => { if (start >= startOffset && end <= endOffset) { entitiesSelection.push({ blockKey: block.getKey(), entityKey: block.getEntityAt(start), start, end }) } }) return entitiesSelection } export default getSelectionEntities
JavaScript
0
@@ -168,63 +168,8 @@ n()%0A - const startOffset = targetSelection.getStartOffset()%0A co @@ -575,30 +575,42 @@ %3E %7B%0A +%0A -if (start %3E= start +const isSelected = end %3E= end Offs @@ -615,19 +615,21 @@ fset && -end +start %3C= endO @@ -633,16 +633,36 @@ ndOffset +%0A%0A if (isSelected ) %7B%0A
49a1d84c7d33b3061bb8a991586d27c957068765
handle beta version release notes
sources/background_scripts/configuration.js
sources/background_scripts/configuration.js
NTT.Configuration = {}; // Version operations: { // Creates a new version identifier. function create(major, minor = 0, patch = 0, beta = 0) { return { major: major, minor: minor, patch: patch, beta : beta }; } // Returns true iff the specified object is a (non-strict) positive integer. function is_positive_integer(obj) { return Number.isInteger(obj) && obj >= 0; } // Returns true iff the specified object is a valid version identifier. function is_valid(obj) { return ( is_positive_integer(obj.major) && is_positive_integer(obj.minor) && is_positive_integer(obj.patch) && is_positive_integer(obj.beta) ); } // Returns an Ordering relating two version identifiers. function compare(a, b) { const Ordering = NTT.Ordering; const components_a = [a.major, a.minor, a.patch, a.beta], components_b = [b.major, b.minor, b.patch, b.beta]; for (let i = 0; i < 4; ++i) { const component_a = components_a[i], component_b = components_b[i]; if (component_a > component_b) { return Ordering.Greater; } else if (component_a < component_b) { return Ordering.Less; } } return Ordering.Equal; } // Builds a string representation of the specified version identifier. function as_string(id, include_patch = true, include_beta = true) { let result = `${id.major}.${id.minor}`; if (include_patch) { result += `.${id.patch}`; } if (include_beta && id.beta > 0) { result += `b${id.beta}`; } return result; } NTT.Configuration.Version = { CURRENT: create(1, 6, 0, 1), HAS_RELEASE_NOTES: false, create: create, is_valid: is_valid, compare: compare, as_string: as_string }; } // Storage layout: { const Version = NTT.Configuration.Version; // Enumerates possible tab behaviors. const TabBehavior = { // Redirection to a specified URL. Redirect: "redirect", // Display of a custom page with user-specified background color and wallpaper image. DisplayCustomPage: "display-custom-page" }; NTT.Configuration.TabBehavior = TabBehavior; // Enumerates option-ui themes. const Theme = { Light: "light", Dark: "dark" }; NTT.Configuration.Theme = Theme; // The default configuration. NTT.Configuration.create_default = function() { return { version: Version.create(Version.CURRENT.major, Version.CURRENT.minor), notification: { new_features: true }, new_tab: { behavior: TabBehavior.DisplayCustomPage, redirect: { url: "" }, custom_page: { background: { color: "#2d2d2d", do_animate: true, animation_duration: 0.5 }, wallpaper: { is_enabled: false, urls: [], do_animate: true, animation_duration: 1.5 } } }, options_ui: { theme: Theme.Light } }; } } // Updates: { const Version = NTT.Configuration.Version; const migration = { "1.4": cfg => // migrates 1.4 to 1.5 { cfg.version = Version.create(1, 5); const page = cfg.new_tab.custom_page; const bg = page.background; const wp = page.wallpaper; bg.do_animate = bg.animation_duration > 0; bg.animation_duration = Math.max(bg.animation_duration, 0.1); wp.do_animate = wp.animation_duration > 0; wp.animation_duration = Math.max(wp.animation_duration, 0.1); cfg.options_ui = { theme: NTT.Configuration.Theme.Light }; } }; // Updates the configuration object layout. function update(cfg) { let version_string = Version.as_string(cfg.version, false, false); while (migration.hasOwnProperty(version_string)) { migration[version_string](cfg); version_string = Version.as_string(cfg.version, false, false); } cfg.version = Version.create( Version.CURRENT.major, Version.CURRENT.minor ); return cfg; } NTT.Configuration.update = update; } // Read/write: { // The key to the configuration object in local storage. const KEY = "configuration@new-tab-tweaker"; const storage = browser.storage.local; // Loads the configuration from storage asynchronously (returns a promise). // // Note: If no configuration object is detected, returns one with default values. function load() { return storage.get(KEY).then(item => { if (item.hasOwnProperty(KEY)) { return item[KEY]; } else { return NTT.Configuration.create_default(); } }); } // Saves a configuration to storage asynchronously (returns a promise). function save(cfg) { const item = {}; item[KEY] = cfg; return storage.set(item); } NTT.Configuration.Storage = { KEY: KEY, load: load, save: save }; } // Runtime event hookups: { const Configuration = NTT.Configuration, Storage = NTT.Configuration.Storage; browser.runtime.onInstalled.addListener(details => { if (details.reason === "install") { Storage.save(Configuration.create_default()); } else if (details.reason === "update") { Storage.load().then(cfg => { const Version = NTT.Configuration.Version; if (Version.HAS_RELEASE_NOTES && cfg.notification.new_features) { const v = Version.CURRENT; browser.tabs.create({ url: "https://rharel.github.io/webext-new-tab-tweaker/release-notes/" + `${v.major}-${v.minor}/` + `${v.major}-${v.minor}-${v.patch}.html`, active: true }); } Storage.save(Configuration.update(cfg)); }); } }); }
JavaScript
0
@@ -1597,20 +1597,19 @@ _NOTES: -fals +tru e,%0A%0A%09%09cr @@ -5364,16 +5364,49 @@ v.patch%7D +$%7Bv.beta %3E 0 ? %60b$%7Bv.beta%7D%60 : %22%22%7D .html%60,%0A
a4c26f044007d21b734c03e42f2e1c44c4bfbf24
add debug info
control/messagecontrol.js
control/messagecontrol.js
'use strict'; const CONVERSATION_SERVICE = 'conversation'; const CONVERSATION_VERSION_DATE = '2016-07-11'; const CONVERSATION_VERSION = 'v1'; var watson = require( 'watson-developer-cloud' ); // watson sdk var http = require('http'); var request = require('request'); function getConversationCredential() { if (process.env.VCAP_SERVICES) { var services = JSON.parse(process.env.VCAP_SERVICES); for (var service_name in services) { if (service_name.indexOf(CONVERSATION_SERVICE) === 0) { var service = services[service_name][0]; return { url: service.credentials.url, username: service.credentials.username, password: service.credentials.password, version_date:CONVERSATION_VERSION_DATE, version: CONVERSATION_VERSION }; } } } console.log("The runtime app has not bound conversation service yet!"); return { version_date: CONVERSATION_VERSION_DATE, version: CONVERSATION_VERSION }; }; var credential = getConversationCredential(); // Create the service wrapper var conversation = watson.conversation(credential); // var messageControl = { message: function messageControl(req, res) { var workspace = process.env.conversation_workspace_id; if ( !workspace || workspace === '' ) { return res.json( { 'output': { 'text': 'The app has not been configured with a <b>WORKSPACE_ID</b> environment variable. Please refer to the ' + '<a href="https://github.com/watson-developer-cloud/conversation-simple">README</a> documentation on how to set this variable. <br>' + 'Once a workspace has been defined the intents may be imported from ' + '<a href="https://github.com/watson-developer-cloud/conversation-simple/blob/master/training/car_workspace.json">here</a> in order to get a working application.' } } ); } var payload = { workspace_id: workspace, context: {}, input: {}, api_param:{} }; if ( req.body ) { if ( req.body.accessKey!== process.env.conversation_access_key) { return res.status( 403 ).json( { error: CONVERSATION_ACCESS_ERROR } ); } if ( req.body.input ) { payload.input = req.body.input; } if ( req.body.context ) { // The client must maintain context/state payload.context = req.body.context; } if ( req.body.api_param ) { payload.api_param = req.body.api_param; } } // Send the input to the conversation service conversation.message( payload, function(err, response) { if ( err ) { return res.status( err.code || 500 ).json( err ); } var message = updateMessage( payload, response ); console("!!!!!!!!!!Before send back..."); return res.json(message); } ); } }; /** * Updates the response text using the intent confidence * @param {Object} input The request to the Conversation service * @param {Object} response The response from the Conversation service * @return {Object} The response with the updated message */ function updateMessage(payload, response) { var responseText = null; var id = null; if ( !response.output ) { response.output = {}; } else { if ( response.intents && response.intents[0] ) { var intent = response.intents[0]; if ( intent.confidence >= 0.75 ) { responseText = 'I understood your intent was ' + intent.intent; } else if ( intent.confidence >= 0.5 ) { responseText = 'I think your intent was ' + intent.intent; } else { responseText = 'I did not understand your intent'; } } response.output.text = responseText; if (!response.output.api) { return response; } else { request(response.output.api, function (error, apiResponse, body) { if (!error && apiResponse.statusCode == 200) { console.log("*********** apiResponse:" + apiResponse); console.log("*********** body:" + body); response.output.specialContent = body; console.log("*********** response:" + response); return response; } else{ console.log("Got error on calling api: " + response.output.api); } }); // console.log('******** api calling:' + response.output.api); // http.get(response.output.api, function(apiRes){ // console.log('******** api response:' + JSON.stringify(apiRes)); // response.output.specialContent = "********"; // return response; // }).on('error', function(e) { // console.log("Got error: " + e.message); // }); //set API provider host info // var options = { // host: response.output.api_host, // path: response.output.api_path, // method: 'POST', // headers: { // 'Content-Type': 'application/x-www-form-urlencoded', // 'Content-Length': Buffer.byteLength(postData) // } // }; // //TODO call REST API, Dummy source first // // specialContent.data=[ // { // 'Name':'SMBC', // 'Info':'SMBC is a famous japan bank', // 'MimeType':'vedio','URL':'http://www.runoob.com/try/demo_source/movie.mp4' // } // ]; } } } module.exports = messageControl;
JavaScript
0.000001
@@ -3137,16 +3137,20 @@ console +.log (%22!!!!!!
485f2efbadd1818018611c1c3328895e3088a254
Work around pingdom API bug
cronjobs.js
cronjobs.js
var fs = require('fs'); require('date-utils'); var config = require('./config'); var async = require('async'); var cronJob = require('cron').CronJob; var pingdom = require('pingdom-api')(config.pingdom); function init(cb) { writeJSON(cb); new cronJob(config.cron, writeJSON.bind(undefined, cb), null, true); } module.exports = init; function writeJSON(cb) { cb = cb || function() {}; pingdom.checks(function(err, checks) { if(err) return cb(err); async.parallel(constructChecks(checks), function(err, data) { var d; if(err) return cb(err); d = structure(data); write(JSON.stringify(d), './public/data.json'); cb(null, d); }); }); } function constructChecks(checks) { return checks.map(function(check) { return function(cb) { var to = Date.today(); var from = to.clone().addMonths(-6); async.series([ getSummaries.bind(undefined, check, from, to), getDowntimes.bind(undefined, check, from, to) ], function(err, data) { if(err) return console.error(err); cb(err, { summaries: data[0], downtimes: data[1] }); }); }; }); } function getSummaries(check, from, to, cb) { // downtime info is in seconds, not accurate enough... pingdom['summary.performance'](function(err, data) { cb(err, { check: check, data: data }); // skip res }, { target: check.id, qs: { from: from, to: to, resolution: 'day' } }); } function getDowntimes(check, from, to, cb) { pingdom['summary.outage'](function(err, outages, res) { // skip res cb(err, outages && outages.states? calculateDowntimes(outages.states, from, to): []); }, { target: check.id, qs: { from: from, to: to } }); } function calculateDowntimes(data, from, to) { var ret = zeroes(from.getDaysBetween(to)); var downFrom, downTo, fromDelta, toDelta, next; // calculate downtimes per day and sum them up as ms data.filter(equals('status', 'down')).forEach(function(v) { downFrom = new Date(v.timefrom * 1000); downTo = new Date(v.timeto * 1000); fromDelta = from.getDaysBetween(downFrom); toDelta = from.getDaysBetween(downTo); if(fromDelta == toDelta) { ret[fromDelta] += downTo - downFrom; } else { next = downTo.clone().clearTime(); ret[fromDelta] += next - downFrom; ret[toDelta] += downTo - next; } }); return ret; } // TODO: move to some utility lib function zeroes(a) { var ret = []; var i; for(i = 0; i < a; i++) ret.push(0); return ret; } // TODO: move to some utility lib function equals(a, b) { return function(v) { return v[a] == b; }; } // TODO: move to some utility lib function prop(a) { return function(v) { return v[a]; }; } function structure(data) { var days = data[0].summaries.data.days; return { providers: data.map(function(d) { var summaries = d.summaries; var check = summaries.check; return { name: check.name, host: check.hostname, type: check.name.split(' ')[1].toLowerCase(), latency: parseLatency(summaries.data.days), downtime: d.downtimes }; }), firstDate: days[0].starttime, lastDate: days[days.length - 1].starttime }; function parseLatency(data) { return data.map(function(v) { return v.avgresponse; }); } } function write(data, target) { fs.writeFile(target, data, function(err) { if(err) return console.error(err); console.log('Wrote ' + target); }); }
JavaScript
0
@@ -931,11 +931,51 @@ hs(- -6 +5 ); + // XXX: work around pingdom bug for now %0A%0A
82c0bc6ac92b6eab2825df00974ff2e972bc4244
Support zoom/lat/long params from saved maps.
controllers/map-filter.js
controllers/map-filter.js
var settings = require('../helpers/settings') var fs = require('fs') var path = require('path') var moment = require('moment') const FILTERS_FOLDER = settings.getFiltersDirectory() function saveFilter (req, res, next) { var name = moment().format('YYYYMMDDHHmmss') var json = req.body fs.writeFile(path.join(FILTERS_FOLDER, name), JSON.stringify(json), function (err) { if (err) { res.json({error: true, code: 'save_failed', message: 'File did not save'}) } else { res.json({error: false, message: 'Save successful'}) } }) } function listFilters (req, res, next) { fs.readdir(FILTERS_FOLDER, function (err, files) { var names = [] for (var index in files) { names.push({id: files[index], name: JSON.parse(fs.readFileSync(path.join(FILTERS_FOLDER, files[index]), 'utf8')).name}) } res.json({filters: names}) }) } function config (req, res, next) { var data = { canSaveFilters: true, saveFilterTargets: [ { name: 'Local', path: '/mapfilter/filters/local', value: 'local' } ], bingProxy: '/bing-proxy', bingMetadata: '/bing-metadata', tiles: { url: '/tileLayers', tilesPath: '/monitoring-files/Maps/Tiles' } }; data['tracks'] = { url: '/tracks', soundsPath: '/sounds', iconPath: '/mapfilter' } if (process.env.mapLayer) data['baseLayer'] = process.env.mapLayer var mapFilterSettings = settings.getMapFilterSettings(); if (mapFilterSettings.mapZoom) { try { data['mapZoom'] = parseInt(mapFilterSettings.mapZoom, 10) } catch (e) {} } if (mapFilterSettings.mapCenterLat) { try { data['mapCenterLat'] = parseFloat(mapFilterSettings.mapCenterLat) } catch (e) {} } if (mapFilterSettings.mapCenterLong) { try { data['mapCenterLong'] = parseFloat(mapFilterSettings.mapCenterLong) } catch (e) {} } var filter = req.query.filter if (filter) { var file = path.join(settings.getFiltersDirectory(), filter) fs.access(file, fs.F_OK | fs.R_OK, function (err) { if (err) { res.json(data) } else { fs.readFile(file, 'utf8', function (err, contents) { var filterJson = JSON.parse(contents) data['filters'] = filterJson.value if (filterJson.baseLayer) data['baseLayer'] = filterJson.baseLayer res.json(data) }) } }) } else { res.json(data) } } function exists(path) { try { fs.accessSync(path, fs.F_OK | fs.R_OK); } catch (err) { return false; } return true; } module.exports = { listFilters: listFilters, saveFilter: saveFilter, config: config }
JavaScript
0
@@ -2337,16 +2337,276 @@ seLayer%0A + if (filterJson.zoom)%0A data%5B'mapZoom'%5D = filterJson.zoom%0A if (filterJson.latitude)%0A data%5B'mapCenterLat'%5D = filterJson.latitude%0A if (filterJson.longitude)%0A data%5B'mapCenterLong'%5D = filterJson.longitude%0A
e1a49fbbb0388dd10de3afc126b8d01abdd785d6
use the DocumentProperties for storage
src/libs/lib.utils.storage.js
src/libs/lib.utils.storage.js
// Copyright 2016 Joseph W. May. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * An object for assisting with the storage of strings and arrays in the * user properties of a Google Apps Script. * * @constructor */ var PropertyStore = function() { this.store = PropertiesService.getUserProperties(); }; /** * Set a property with the given key and value. An optional flag for storing * an array is available, which converts the array into a JSON string. * * @param {string} key The key that labels the stored data. * @param {string|array} value The value to be stored. * @param {boolean=} isArray Set to true if storing an array. */ PropertyStore.prototype.setProperty = function(key, value, isArray) { value = isArray === true ? JSON.stringify(value) : value; this.store.setProperty(key, value); }; /** * Get a property with the given key. An optional flag for retrieving an array * is available, which converts the JSON string into an array object. * * @param {string} key The key that labels the stored data. * @param {boolean=} isArray Set to true if retrieving a stored array. * @return A string if isArray set to false, otherwise, an array object. */ PropertyStore.prototype.getProperty = function(key, isArray) { var property = this.store.getProperty(key); property = isArray === true ? JSON.parse(property) : property; return property; }; /** * Deletes all properties in the current properties store. */ PropertyStore.prototype.clean = function() { this.store.deleteAllProperties(); };
JavaScript
0
@@ -692,12 +692,16 @@ %0A * -user +document pro @@ -830,12 +830,16 @@ .get -User +Document Prop
0190a2d5cafc5a6a9e2d70d58fd6ab5322dd2944
Move matrix calcs from webglshadows
src/lights/SpotLightShadow.js
src/lights/SpotLightShadow.js
import { LightShadow } from './LightShadow.js'; import { _Math } from '../math/Math.js'; import { PerspectiveCamera } from '../cameras/PerspectiveCamera.js'; /** * @author mrdoob / http://mrdoob.com/ */ function SpotLightShadow() { LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) ); } SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { constructor: SpotLightShadow, isSpotLightShadow: true, update: function ( light ) { var camera = this.camera; var fov = _Math.RAD2DEG * 2 * light.angle; var aspect = this.mapSize.width / this.mapSize.height; var far = light.distance || camera.far; if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { camera.fov = fov; camera.aspect = aspect; camera.far = far; camera.updateProjectionMatrix(); } } } ); export { SpotLightShadow };
JavaScript
0
@@ -452,15 +452,24 @@ e,%0A%0A -%09 + update +Matrices : fu @@ -482,20 +482,48 @@ ( light +, viewCamera, viewportIndex ) %7B + %0A%0A%09%09var @@ -542,16 +542,106 @@ s.camera +,%0A lookTarget = this._lookTarget,%0A lightPositionWorld = this._lightPositionWorld ;%0A%0A%09%09var @@ -972,17 +972,350 @@ ;%0A%0A%09%09%7D%0A%0A -%09 + lightPositionWorld.setFromMatrixPosition( light.matrixWorld );%0A%09%09camera.position.copy( lightPositionWorld );%0A%0A lookTarget.setFromMatrixPosition( light.target.matrixWorld );%0A%09%09camera.lookAt( lookTarget );%0A%09%09camera.updateMatrixWorld();%0A%0A LightShadow.prototype.updateMatrices.call( this, light, viewCamera, viewportIndex );%0A%0A %7D%0A%0A%7D );%0A
401dafc476e4103a22f54998c8889f389d49a6af
remove factory call in browser entry point
app/main.js
app/main.js
/** @jsx React.DOM */ var React = require('react/addons'); var ReactApp = React.createFactory(require('./components/ReactApp').ReactApp); var mountNode = document.getElementById("react-main-mount"); React.renderComponent(new ReactApp({}), mountNode);
JavaScript
0
@@ -76,28 +76,8 @@ p = -React.createFactory( requ @@ -108,18 +108,8 @@ pp') -.ReactApp) ;%0A%0Av @@ -185,17 +185,8 @@ nder -Component (new
38e234589eb0f23c3e977e850c542495bd917175
Remove about page click action, standard window is fine. Fixes #4
app/menu.js
app/menu.js
var Menu = require('menu'); var MenuItem = require('menu-item'); module.exports = { setup: function (app, host) { var name = app.getName(); var template = [{ label: name, submenu: [ { label: 'About ' + name, role: 'about', click: function() { var win = new BrowserWindow({ width: 915, height: 600, show: false }); win.on('closed', function() { win = null; }); win.webContents.on('will-navigate', function (e, url) { e.preventDefault(); Shell.openExternal(url); }); win.loadURL(host + '/about'); win.show(); } }, { type: 'separator' }, { label: 'Services', role: 'services', submenu: [] }, { type: 'separator' }, { label: 'Hide ' + name, accelerator: 'Command+H', role: 'hide' }, { label: 'Hide Others', accelerator: 'Command+Alt+H', role: 'hideothers' }, { label: 'Show All', role: 'unhide' }, { type: 'separator' }, { label: 'Quit', accelerator: 'Command+Q', click: function() { app.quit(); } }, ] }, { label: 'Edit', submenu: [ { label: 'Undo', accelerator: 'CmdOrCtrl+Z', role: 'undo' }, { label: 'Redo', accelerator: 'Shift+CmdOrCtrl+Z', role: 'redo' }, { type: 'separator' }, { label: 'Cut', accelerator: 'CmdOrCtrl+X', role: 'cut' }, { label: 'Copy', accelerator: 'CmdOrCtrl+C', role: 'copy' }, { label: 'Paste', accelerator: 'CmdOrCtrl+V', role: 'paste' }, { label: 'Select All', accelerator: 'CmdOrCtrl+A', role: 'selectall' }, ] }, { label: 'View', submenu: [ { label: 'Reload', accelerator: 'CmdOrCtrl+R', click: function(item, focusedWindow) { focusedWindow.webContents.reloadIgnoringCache(); } }, { label: 'Toggle Full Screen', accelerator: (function() { if (process.platform == 'darwin') { return 'Ctrl+Command+F'; } else { return 'F11'; } })(), click: function(item, focusedWindow) { if (focusedWindow) { focusedWindow.setFullScreen(!focusedWindow.isFullScreen()); } } }, { label: 'Toggle Developer Tools', accelerator: (function() { if (process.platform == 'darwin') { return 'Command+Alt+I'; } else { return 'Ctrl+Shift+I'; } })(), click: function(item, focusedWindow) { if (focusedWindow) { focusedWindow.toggleDevTools(); } } }, ] }, { label: 'History', id: 'history', submenu: [ { label: 'Back', accelerator: 'CmdOrCtrl+[', enabled: false, id: 'backMenu', click: function (item, focusedWindow) { focusedWindow.webContents.goBack(); } }, { label: 'Forward', accelerator: 'CmdOrCtrl+]', enabled: false, id: 'fwdMenu', click: function (item, focusedWindow) { focusedWindow.webContents.goForward(); } }, ] }, { label: 'Window', role: 'window', submenu: [ { label: 'Minimize', accelerator: 'CmdOrCtrl+M', role: 'minimize' }, { label: 'Close', accelerator: 'CmdOrCtrl+W', role: 'close' }, { type: 'separator' }, { label: 'Bring All to Front', role: 'front' }, ] }, { label: 'Help', role: 'help', submenu: [ { label: 'Github Repository', click: function() { require('electron').shell.openExternal('https://github.com/irccloud/irccloud-desktop'); } }, ] }]; var menu = Menu.buildFromTemplate(template); Menu.setApplicationMenu(menu); return menu; } };
JavaScript
0
@@ -269,465 +269,8 @@ out' -,%0A click: function() %7B%0A var win = new BrowserWindow(%7B width: 915, height: 600, show: false %7D);%0A win.on('closed', function() %7B%0A win = null;%0A %7D);%0A win.webContents.on('will-navigate', function (e, url) %7B%0A e.preventDefault();%0A Shell.openExternal(url);%0A %7D);%0A win.loadURL(host + '/about');%0A win.show();%0A %7D %0A
fd66728ba29f7f9b30e8b1f203eee863227caf98
create language and level storage objects
server/db/index.js
server/db/index.js
module.exports = function() { var db = require('./db.js'); var Users = require('./models/userModel.js'); var Languages = require('./models/languageModel.js'); var Levels = require('./models/levelModel.js'); var LanguagesLevels = require('./models/languageLevelModel.js'); var UsersLanguagesLevels = require('./models/userLanguageLevelModel.js'); var Messages = require('./models/messageModel.js'); var Rooms = require('./models/roomModel.js'); var UserRooms = require('./models/userRoomModel.js'); var Relationships = require('./models/relationshipModel.js'); var test = require('./controllers/getRoomIdsAndUserIdsGivenSelfId.js') Languages.belongsToMany(Levels, { through: 'languages_levels', foreignKey: 'language_id' }); Levels.belongsToMany(Languages, { through: 'languages_levels', foreignKey: 'level_id' }); Users.belongsToMany(LanguagesLevels, { through: 'users_languages_levels', foreignKey: 'user_id' }); LanguagesLevels.belongsToMany(Users, { through: 'users_languages_levels', foreignKey: 'language_level_id' }); Users.belongsToMany(Rooms, { through: 'users_rooms', foreignKey: 'user_id' }); Rooms.belongsToMany(Users, { through: 'users_rooms', foreignKey: 'room_id' }); Messages.belongsTo(Rooms, { foreignKey: 'room_id' }); Messages.belongsTo(Users, { foreignKey: 'user_id' }); Users.belongsToMany(Users, { as: 'User1', through: 'relationships', foreignKey: 'user1Id' }); Users.belongsToMany(Users, { as: 'User2', through: 'relationships', foreignKey: 'user2Id' }); db.sync({force: true}) .then(function() { return Rooms.bulkCreate([ { number_active_participants: 3 }, { number_active_participants: 2 }, ]); }) .then(function(rooms) { return Users.bulkCreate([ { facebook_id: 1234, first_name: 'Ash' }, { facebook_id: 3456, first_name: 'Mo' }, { facebook_id: 5678, first_name: 'Reina' }, ]) .then(function(users) { // console.log('USERS: ', users) // console.log('ROOMS: ', rooms) users.forEach((user) => { user.addRoom(rooms[0]); }); users[0].addRoom(rooms[1]); users[1].addRoom(rooms[1]); }); }) .then(function() { return Users.findOne({ where: { first_name: 'Ash' } }) .then(function(result) { return test(result.dataValues.id); }); }); //TODO: remove force true };
JavaScript
0.000001
@@ -2173,207 +2173,8 @@ %5D);%0A - %7D);%0A %7D)%0A .then(function() %7B%0A return Users.findOne(%7B where: %7B first_name: 'Ash' %7D %7D)%0A .then(function(result) %7B%0A return test(result.dataValues.id);%0A %7D);%0A %7D);%0A //
e9dadce167cf48f80d7f6d7347af4047d7e01143
refactor deckSpec to remove unneccessary verbosity / complexity
server/deckSpec.js
server/deckSpec.js
// all of the cards // verbose, but easily extendable for expansion packs // the key is the id-letter // the int in the array is part of the id, and represents how many // of a given card there is var deckSpec = { a: [0, 1], b: [0, 2, 3, 4], c: [0], d: [0, 1, 2, 3], e: [0, 1, 2, 3, 4], f: [0, 1], g: [0], h: [0, 1, 2], i: [0, 1], j: [0, 1, 2], k: [0, 1, 2], l: [0, 1, 2], m: [0, 1], n: [0, 1, 2], o: [0, 1], p: [0, 1, 2], q: [0], r: [0, 1, 2], s: [0, 1], t: [0], u: [0, 1, 2, 3, 4, 5, 6, 7], v: [0, 1, 2, 3, 4, 5, 6, 7, 8], w: [0, 1, 2, 3], x: [0] }; module.exports = deckSpec;
JavaScript
0.000014
@@ -219,385 +219,193 @@ a: -%5B0, 1%5D +2 ,%0A b: -%5B0, 2, 3, 4%5D +5 ,%0A c: -%5B0%5D +1 ,%0A d: -%5B0, 1, 2, 3%5D,%0A e: %5B0, 1, 2, 3, 4%5D +4,%0A e: 5 ,%0A f: -%5B0, 1%5D +2 ,%0A g: -%5B0%5D +1 ,%0A h: -%5B0, 1, 2%5D +3 ,%0A i: -%5B0, 1%5D +2 ,%0A j: -%5B0, 1, 2%5D,%0A k: %5B0, 1, 2%5D,%0A l: %5B0, 1, 2%5D +3,%0A k: 3,%0A l: 3 ,%0A m: -%5B0, 1%5D +2 ,%0A n: -%5B0, 1, 2%5D +3 ,%0A o: -%5B0, 1%5D +2 ,%0A p: -%5B0, 1, 2%5D +3 ,%0A q: -%5B0%5D +1 ,%0A r: -%5B0, 1, 2%5D +3 ,%0A s: -%5B0, 1%5D +2 ,%0A t: -%5B0%5D +1 ,%0A u: -%5B0, 1, 2, 3, 4, 5, 6, 7%5D,%0A v: %5B0, 1, 2, 3, 4, 5, 6, 7, 8%5D,%0A w: %5B0, 1, 2, 3%5D +8,%0A v: 9,%0A w: 4 ,%0A x: -%5B0%5D +1 %0A%7D;%0A
d58bf0080eba5d4447c510a681b78316ecfd87cc
Store numbers for cbgs, not strings
lib/dexcom/parse.js
lib/dexcom/parse.js
/* * == BSD2 LICENSE == * Copyright (c) 2014, Tidepool Project * * This program is free software; you can redistribute it and/or modify it under * the terms of the associated License, which is identical to the BSD 2-Clause * License as published by the Open Source Initiative at opensource.org. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the License for more details. * * You should have received a copy of the License along with this program; if * not, you can obtain one from Tidepool Project at tidepool.org. * == BSD2 LICENSE == */ 'use strict'; var dxcomParser; var es = require('event-stream'); var moment = require('moment'); var columns = { NA_1: 0, NA_2: 1, GlucoseInternalTime_1: 2, GlucoseDisplayTime_1: 3, GlucoseValue_1: 4, MeterInternalTime_2: 5, MeterDisplayTime_2: 6, MeterGlucoseValue_2: 7 }; var DEXCOM_TIME = 'YYYY-MM-DD HH:mm:ss'; var OUTPUT_TIME = 'YYYY-MM-DDTHH:mm:ss'; function reformatISO (str) { var m = moment(str, DEXCOM_TIME); return m.format(OUTPUT_TIME); } function validTime (str) { return moment(str, OUTPUT_TIME).isValid( ); } dxcomParser = function() { var responder, stream; stream = es.pipeline(es.split(), es.map(function(data, cb) { if(data){ var sugarsInRow = splitBGRecords(data); sugarsInRow.forEach(function(sugar){ var rec = { type: 'cbg', data: sugar }; stream.emit('type', rec); }); } return cb(); })); responder = function(filter) { var tr; tr = es.through(); stream.on('type', function(data) { if (data.type.match(filter)) { return tr.push(data.data); } }); return es.pipeline(stream, tr); }; return es.pipeline(responder('cbg'), es.map(parse), es.map(valid)); }; dxcomParser.desalinate = function( ) { return dxcomParser().desalinate( ); }; dxcomParser.sugars = function( ) { return dxcomParser().sugars( ); }; dxcomParser.cbg = function( ) { return dxcomParser().cbg( ); }; dxcomParser.columns = function() { return columns; }; dxcomParser.splitBGRecords =function(rawData){ return splitBGRecords(rawData); }; dxcomParser.isValidCbg = function(cbg){ return isValidCbg(cbg); }; function parse (rawData, callback) { var entryValues, processedSugar; var stringReadingToNum = function(value) { if (rawData.value.match(/lo./i)) { return "39"; } else if (rawData.value.match(/hi./i)) { return "401"; } } if ((rawData.value.match(/lo./i)) || rawData.value.match(/hi./i)) { processedSugar = { value: stringReadingToNum(rawData.value), type: 'cbg', deviceTime: reformatISO(rawData.displayTime), special: rawData.value }; } else { processedSugar = { value: rawData.value, type: 'cbg', deviceTime: reformatISO(rawData.displayTime) }; } return callback(null, processedSugar); } function valid (data, next) { if (isValidCbg(data)) { return next(null, data); } next( ); } function isValidCbg (cbg) { if (isNaN(parseInt(cbg.value))) { if (cbg.value.match(/lo./i) || cbg.value.match(/hi./i)) { return (cbg.type === 'cbg' && validTime(cbg.deviceTime)); } else { return false; } } else { return (!isNaN(parseInt(cbg.value)) && cbg.type === 'cbg' && validTime(cbg.deviceTime)); } }; var splitBGRecords = function(rawData){ var records, entryValues, sugarOne, sugarTwo; entryValues = rawData.split('\t'); sugarOne = {}; sugarOne.value = entryValues[columns['GlucoseValue_1']]; sugarOne.displayTime = entryValues[columns['GlucoseDisplayTime_1']]; records = [sugarOne]; return records; }; module.exports = dxcomParser;
JavaScript
0.000016
@@ -2728,16 +2728,23 @@ value: +Number( stringRe @@ -2768,16 +2768,17 @@ a.value) +) ,%0A @@ -2927,16 +2927,23 @@ value: +Number( rawData. @@ -2947,16 +2947,17 @@ ta.value +) ,%0A
820849bb2610ffe829b2e2d88094240b03829a6e
switch command order
server/evaluate.js
server/evaluate.js
var fs = require('fs') var tmp = require('tmp') var path = require('path') var exec = require('child_process').exec module.exports = function (dataset, values, cb) { function write (dir, cb) { fs.writeFile(path.join(dir, dataset + '.csv'), values, function (err) { if (err) return cb(err) else cb() }) } tmp.dir(function (err, dir) { write(dir, function () { var cmd = 'spikefinder evaluate ' + dir + '/' + dataset + '.csv ' + 'answers/' + dataset + '.csv' exec(cmd, function (err, stdout, stderr) { if (err) return cb(err) else if (stderr) return cb(err) else return cb(null, JSON.parse(stdout)) }) }) }) }
JavaScript
0.000009
@@ -430,15 +430,16 @@ ' + -dir + ' +'answers /' + @@ -455,32 +455,31 @@ + '.csv ' + -'answers +dir + ' /' + dataset
dcbb6609379d7ce892c88c18aa92233259516a58
fix hiding of no-events msg
imports/client/ui/pages/Map/EventsList/index.js
imports/client/ui/pages/Map/EventsList/index.js
import React, { Component, Fragment } from 'react' import PropTypes from 'prop-types' import { ListGroup } from 'reactstrap' import EventsListItem from './EventsListItem' import MinimizeButton from './MinimizeButton' import './styles.scss' class EventsList extends Component { state = { events: [], loading: true, noData: false, minimized: false } static getDerivedStateFromProps (nextProps, prevState) { // If we had an array of events but they were eith filtered/researched if (prevState.events[0] && !nextProps.events[0]) { return { events: [], noData: true, loading: nextProps.isFetching } } return { events: nextProps.events, loading: nextProps.isFetching } } componentDidMount () { const timeout = 5000 // try this for 5 seconds const startingTime = Date.now() this.interval = setInterval(() => { // if more than 5 seconds have passed if (this.interval && Date.now() - startingTime > timeout) { this.setState({ noData: true }) clearInterval(this.interval) } }, 1000) } componentWillUnmount () { clearInterval(this.interval) this.interval = null } render () { const { events, loading, noData, minimized } = this.state const { userLocation } = this.props return ( <Fragment> <div id='events-list' className={minimized ? 'minimized' : ''}> <div className='header'> {this.props.children} {/* Search Box */} </div> <ListGroup> {events && events.map((event, index) => { return ( <EventsListItem key={index} item={event} userLocation={userLocation} onItemClick={this.props.toggleInfoWindow} /> ) })} </ListGroup> {(loading || !noData) && ( <div className='va-center loader'> <div className='ball-beat'> <div /><div /><div /> </div> <div>looking for events near you...</div> </div> )} {noData && ( <div className='no-near-events va-center'> <div>Sorry, we couldn't find anything</div> <div>around you...</div> </div> )} </div> <MinimizeButton onMinimize={this.toggleMinimize} minimized={minimized} /> </Fragment> ) } toggleMinimize = () => { this.setState({ minimized: !this.state.minimized }) } } EventsList.propTypes = { events: PropTypes.array.isRequired, userLocation: PropTypes.object, isFetching: PropTypes.bool, toggleInfoWindow: PropTypes.func.isRequired } export default EventsList
JavaScript
0.000261
@@ -1385,16 +1385,49 @@ .props%0A%0A + const hasData = !!events%5B0%5D%0A%0A retu @@ -2281,16 +2281,17 @@ %7B +( noData & @@ -2291,16 +2291,29 @@ oData && + !hasData) && (%0A