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
93be0904c1711176447fa758aab2d3c481a25e4b
add closing browser to getting purchased book
lib/amazon/getPurchasedBooks.js
lib/amazon/getPurchasedBooks.js
const parseUrl = require('url').parse; const URLSearchParams = require('url').URLSearchParams; const dig = require('object-dig'); const puppeteer = require('puppeteer'); const getPurchasedBooks = async (aid, apw) => { const browser = await puppeteer.launch({ args: ['--no-sandbox'], headless: false, /* [DEBUG] headless: false */ }); const page = await browser.newPage(); const targetURL = 'https://www.amazon.co.jp/mn/dcw/myx.html/#/home/content/booksAll/dateDsc/'; await visit(page, targetURL, { aid, apw }); let pageIndex = 0; const items = []; const asins = []; let isFinish = false; let isSuccess = true; let hasMoreItems = true; let isReverse = false; while (isSuccess && hasMoreItems && !isFinish) { const result = await getAllBooksByAPI(page, pageIndex, isReverse); isSuccess = dig(result, 'OwnershipData', 'success'); hasMoreItems = dig(result, 'OwnershipData', 'hasMoreItems'); if (isSuccess) { const rets = dig(result, 'OwnershipData', 'items'); const ids = rets.map(i => i.asin); console.log( 'Retrieving (page %s) %s..%s', pageIndex, ids[0], ids[ids.length - 1] ); for (const item of rets) { const asin = item.asin; if (!asins.includes(asin)) { items.push(item); asins.push(asin); } else { isFinish = true; break; } } pageIndex += 1; } else { const errorCode = dig(result, 'OwnershipData', 'error'); if (errorCode === 'GENERIC_ERROR') { pageIndex = 0; isSuccess = hasMoreItems = isReverse = true; } else { console.error(`Error: ${errorCode}`); } } } return items; }; module.exports = getPurchasedBooks; const regexpLoginURL = /^https:\/\/www\.amazon\.co\.jp\/ap\/signin\?openid\.return_to=/; const gotoAndWaitLoad = (page, url, options = {}) => ( page.goto(url, { waitUntil: 'load', ...options }) ); const login = async (page, id, pw) => { if (!regexpLoginURL.test(await page.url())) { return; } await page.click('#ap_signin_existing_radio'); await page.focus('#ap_email'); await page.type(id); await page.focus('#ap_password'); await page.type(pw); await page.click('#signInSubmit-input'); await page.waitForNavigation({ timeout: 10001 }); }; const isLoggedIn = async (page) => { const isNotLoginUrl = !regexpLoginURL.test(await page.url()); if (isNotLoginUrl) { const accountUrl = await page.evaluate(selector => { const elem = document.getElementById(selector); if (elem) { return elem.getAttribute('href'); } return false; }, 'nav-link-yourAccount'); const regexpAccountURL = /^\/gp\/css\/homepage\.html/; return regexpAccountURL.test(parseUrl(accountUrl).pathname); } return false; }; const visit = async (page, url, options = {}) => { const { aid, apw, ...opts } = options; if (url !== (await page.url())) { await gotoAndWaitLoad(page, url, opts); } else { return; } if (!await isLoggedIn(page)) { await login(page, aid, apw); } if (url !== (await page.url())) { await gotoAndWaitLoad(page, url, opts); } }; const getAllBooksByAPI = async (page, pageNo = 0, reverse = false) => { const endpoint = '/mn/dcw/myx/ajax-activity/ref=myx_ajax'; return await page.evaluate(async (endpoint, body) => { return await fetch(endpoint, { method: 'POST', credentials: 'same-origin', headers: { client: 'MYX', Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', }, body, }).then(res => res.json()); }, endpoint, await buildBodyParams(page, pageNo, reverse)); }; const buildBodyParams = async (page, pageNo = 0, reverse = false) => { const batchSize = 100; const startIndex = pageNo * batchSize; const sortOrder = reverse ? 'ASCENDING' : 'DESCENDING'; const csrfToken = await getCsrfToken(page); const data = { param: { OwnershipData: { contentType: 'Ebook', excludeExpiredItemsFor: [ 'KOLL', 'Purchase', 'Pottermore', 'FreeTrial', 'DeviceRegistration', 'ku', 'Sample', 'Prime', ], isExtendedMYK: false, itemStatus: [ 'Active', 'Expired' ], originType: [ 'Purchase', 'PublicLibraryLending', 'PersonalLending', 'KOLL', 'RFFLending', 'Pottermore', 'Rental', 'DeviceRegistration', 'FreeTrial', 'ku', 'Sample', 'Prime', ], sortIndex: 'DATE', sortOrder, batchSize, startIndex, }, }, }; const ret = new URLSearchParams({ csrfToken, data: JSON.stringify(data) }); return ret.toString(); }; // async function const getCsrfToken = async (page) => { return await page.evaluate(() => window.csrfToken); };
JavaScript
0
@@ -1680,24 +1680,43 @@ %7D%0A %7D%0A %7D%0A + browser.close();%0A return ite
a86b3efd5feca4fac036358c943b6a3b9edee317
Make _movie include the id
pages/_movie/index.js
pages/_movie/index.js
const hyperglue = require('hyperglue') const html = require('fs').readFileSync(__dirname + '/index.html') module.exports = function(movie) { return hyperglue(html, { '.name': movie.name, '.desc': movie.desc, '.movie': { 'data-id': movie.id.toString() } }) }
JavaScript
0.999998
@@ -103,16 +103,27 @@ x.html') +.toString() %0A%0Amodule @@ -270,16 +270,44 @@ String() +,%0A%09%09%09'data-name': movie.name %0A%09%09%7D%0A%09%7D)
76db63356074a3c77546e5b421cd78aa571b859e
fix bug with double arrays
lib/api/formtools/parse-form.js
lib/api/formtools/parse-form.js
'use strict'; /** * Parse a form field. * @param {Any} field A form field. * @param {String} [type='string'] The name of the type. * @param {Object} options The fields options. * @param {String} options.fieldType The field type. * @param {Object} options.form The form DSL. * @param {String} options.formType The form type (edit, create). * @returns {Any} The updated field. */ const parseField = (fieldName, data, options = {}) => { const field = data[fieldName]; const { fieldType, form, formType, } = options; let updatedField = field; const type = fieldType.toLowerCase(); if (type === 'array' || type === 'enum') { updatedField = [field]; } if (type === 'boolean') { let value = false; if (field) { value = true; } if (field.toLowerCase() === 'false') { value = false; } updatedField = value; } if (type === 'date' || type === 'datetime') { updatedField = new Date(field); } if (type === 'number') { updatedField = Number(field); } if (type === 'documentarray') { try { updatedField = JSON.parse(field); } catch (error) { throw error; } } const formItem = Object.assign({}, form[fieldName], form[fieldName][formType]); if (formItem.widget && formItem.widget.transform) { updatedField = formItem.widget.transform(fieldName, formItem, field, data); } if (formItem.transform) { updatedField = formItem.transform(field, 'beforeSave'); } return updatedField; }; /** * Parse form post data ready to be used by Linz. * @param {Object} model A mongoose model. * @param {Object} req The request object. * @param {Object} formDSL * @param {Object} options The optional options. * @param {Object} options.data Override the req.body data. * @param {Object} options.formType The form type to use, edit or create. * @returns {Promise} Resolves with the parsed data. */ const parseForm = (model, req, formDSL, options = {}) => new Promise((resolve, reject) => { model.getForm(req, (err, modelForm) => { if (err) { return reject(err); } const form = Object.assign({}, modelForm, formDSL); // Allow overriding the req.body with a provided data option. const { data = req.body, formType, } = options; Object.keys(data) // We only want keys that are provided in the formDSL. .filter(fieldName => Object.keys(form).includes(fieldName)) .forEach((fieldName) => { if (fieldName === '_id' || data[fieldName] === undefined) { return; } const fieldType = (formDSL[fieldName] && formDSL[fieldName].type && formDSL[fieldName].type.toLowerCase()) || 'string'; data[fieldName] = parseField(fieldName, data, { fieldType, form, formType, }); }); return resolve(data); }); }); module.exports = { parseField, parseForm, };
JavaScript
0
@@ -703,14 +703,23 @@ = %5B +%5D.concat( field -%5D +) ;%0A
4c38e3ed8ec402862ea6b42b02297f8c28ab9b53
fix typo (#17653)
examples/with-firebase/context/userContext.js
examples/with-firebase/context/userContext.js
import { useState, useEffect, createContext, useContext } from 'react' import firebase from '../firebase/clientApp' export const UserContext = createContext() export default function UserContextComp({ children }) { const [user, setUser] = useState(null) const [loadingUser, setLoadingUser] = useState(true) // Helpful, to update the UI accordingly. useEffect(() => { // Listen authenticated user const unsubscriber = firebase.auth().onAuthStateChanged(async (user) => { try { if (user) { // User is signed in. const { uid, displayName, email, photoURL } = user // You could also look for the user doc in your Firestore (if you have one): // const userDoc = await firebase.firestore().doc(`users/${uid}`).get() setUser({ uid, displayName, email, photoURL }) } else setUser(null) } catch (error) { // Most probably a connection error. Handle appropriately. } finally { setLoadingUser(false) } }) // Unsubscribe auth listener on unmount return () => unsubscriber() }, []) return ( <UserContext.Provider value={{ user, setUser, loadingUser }}> {children} </UserContext.Provider> ) } // Custom hook that shorhands the context! export const useUser = () => useContext(UserContext)
JavaScript
0.000069
@@ -1254,16 +1254,17 @@ hat shor +t hands th
cac3d2e92f44fd05093cbfcdb536f1d5aa9f2873
fix start index
experiments/documentpreview/scripts/viewer.js
experiments/documentpreview/scripts/viewer.js
!function (w) { PDFJS.getDocument("1609.01714.pdf").then(function (pdf) { var pageDivs = []; function createPage(n) { if (n >= pdf.numPages) { return; } var div = document.createElement("div"); pageDivs.push(div); var canvas = document.createElement("canvas"); div.appendChild(canvas); var context = canvas.getContext("2d"); canvas.width = 500; canvas.height = Math.round(Math.sqrt(2) * 500); pdf.getPage(n).then(function (page) { var viewport = page.getViewport(1); page.render({ canvasContext: context, viewport: viewport }); }) createPage(n + 1); } createPage(0); pageDivs.forEach(function (div) { document.body.appendChild(div); }); }); } (window);
JavaScript
0.000001
@@ -150,17 +150,16 @@ if (n %3E -= pdf.num @@ -839,17 +839,17 @@ atePage( -0 +1 );%0A
a11f26a564da9827846d4c366faf8ec0fb8d5028
Add username
challengers.js
challengers.js
// Welcome! // Add your github user if you accepted the challenge! var players = [ 'raphamorim', 'israelst', 'afonsopacifer', 'rafaelfragosom', 'paulinhoerry', 'enieber', 'alanrsoares', 'viniciusdacal', 'thiagosantana', 'brunodsgn', 'danilorb', 'douglasPinheiro', 'michelwilhelm', 'rafaelstz', 'andersonweb', 'luhad', 'pablobfonseca', 'willianjusten', 'vitorleal', 'IAMFELIPEMATTOS', 'JulianSansat', 'brenopolanski', 'Pompeu', 'filipedeschamps', 'felipesousa', 'gpedro', 'leaofelipe', 'wedneyyuri', 'jonathanveg', 'filipe1309', 'afgoulart', 'helquisson', 'vulcanobr', 'guilouro', 'pedropolisenso', 'jozadaquebatista', 'cyberglot', 'guilhermeepaixaoo', 'morvanabonin', 'andrecgro', 'thulioph', 'lucasviola', 'iceberg20', 'hugolnx', 'rafael-neri', 'chocsx', 'rtancman', 'welksonramos', 'igorsantos07', 'marabesi', 'diegosaraujo', 'mauriciojunior', 'Rodrigo54', 'woliveiras', 'AgtLucas', 'fredericksilva', 'theandersonn', 'jpklzm', 'edueo', 'vicnicius', 'jhonmike', 'fdaciuk', 'cesardeazevedo', 'vinimdocarmo', 'deseao', 'henriquebelfort', 'mabrasil', 'MacgyverMartins', 'jackmakiyama', 'hocraveiro', 'Gcampes', 'Nipher', 'lnlwd', 'mshmeirelles', 'altemberg', 'lucasmaiaesilva', 'zephyru5', 'afang', 'mvfsilva', 'anselmbradford', 'raulsenaferreira', 'leonardosoares', 'CruiseDevice', 'jianweichuah', 'andreabadesso', 'johnynogueira', 'karlpatrickespiritu', 'Molax', 'chroda', 'Adejair', 'gkal19', 'naltun', 'shyam12860', 'snaka', 'jeanbauer', 'PabloDinella', 'matheus-manoel', 'onlurking', 'lazarofl', 'ricardosllm', 'Dborah', 'cstipkovic', 'matheuswd', 'hevertoncastro', 'alexwbuschle', 'diogomoretti', 'willianschenkel', 'willianschenkel', 'gabrieldeveloper', 'hammy25', 'riquellopes', 'grvcoelho', 'sujcho', 'jakedex' ]; module.exports = players;
JavaScript
0
@@ -2167,16 +2167,37 @@ jakedex' +,%0A 'SambitAcharya' %0A%5D;%0A%0Amod
a4d0badaeb2a754163d24412a77855f019aa5bb1
Fix for bug introduced with r510. Only make the removeChild call if the parentNode is properly set. This way we can zap the grid div contents quickly with the div.innerHTML = "" but still have a valid good destroy() function.
lib/OpenLayers/Tile/Image.js
lib/OpenLayers/Tile/Image.js
// @require: OpenLayers/Tile.js /** * @class */ OpenLayers.Tile.Image = Class.create(); OpenLayers.Tile.Image.prototype = Object.extend( new OpenLayers.Tile(), { /** @type DOMElement img */ img:null, /** * @constructor * * @param {OpenLayers.Grid} layer * @param {OpenLayers.Pixel} position * @param {OpenLayers.Bounds} bounds * @param {String} url * @param {OpenLayers.Size} size */ initialize: function(layer, position, bounds, url, size) { OpenLayers.Tile.prototype.initialize.apply(this, arguments); }, destroy: function() { this.layer.div.removeChild(this.img); this.img = null; }, /** */ draw:function() { OpenLayers.Tile.prototype.draw.apply(this, arguments); this.img = OpenLayers.Util.createImage(null, this.position, this.size, this.url, "absolute"); this.layer.div.appendChild(this.img); }, /** @final @type String */ CLASS_NAME: "OpenLayers.Tile.Image" } );
JavaScript
0.000004
@@ -589,32 +589,89 @@ y: function() %7B%0A + if (this.img.parentNode == this.layer.div) %7B%0A this.lay @@ -696,24 +696,34 @@ (this.img);%0A + %7D%0A this
9f9d15528a13c6d75fb44bdb10db5505d5559a3f
remove comments
src/poll_sync_protocol.js
src/poll_sync_protocol.js
/* * Implementation of the ISyncProtocol * https://github.com/dfahlander/Dexie.js/wiki/Dexie.Syncable.ISyncProtocol */ export default function initSync(serverComm, isOnline) { return function sync( context, url, options, baseRevision, syncedRevision, changes, partial, applyRemoteChanges, onChangesAccepted, onSuccess, onError ) { const request = { // Will not be defined the first time we call the server clientIdentity: context.clientIdentity, baseRevision, partial, changes, syncedRevision, }; serverComm(url, request, options) .then((data) => { if (!data.success) { // Server didn't accept our changes. Stop trying to sync onError(data.errorMessage, Infinity); } else { // If we have no clientIdentity yet, then this was the first call // Make sure we save the clientIdentity and then schedule the next call if (!context.clientIdentity) { context.clientIdentity = data.clientIdentity; context.save() .then(() => { // TODO: we would have to catch an error here and not continue applyRemoteChanges(data.changes, data.currentRevision, data.partial, false); onChangesAccepted(); onSuccess({ again: options.pollInterval }); }).catch((e) => { // We failed to save the clientIdentity. Stop trying to sync // We would not be able to get/send any partial data onError(e, Infinity); }); // This is a subsequent call. // We already have a clientIdentity so we can just schedule the next call } else { // TODO: we would have to catch an error here and not continue applyRemoteChanges(data.changes, data.currentRevision, data.partial, false); onChangesAccepted(); onSuccess({ again: options.pollInterval }); } } }) .catch((e) => { isOnline(url) .then((status) => { if (status) { // We were temporarily offline -> retry onError(e, options.pollInterval); } else { // Was probably not just a temp thing -> stop retrying // Synable will automatically disconnect us with an ERROR // and we will have to manually reconnect onError(e, Infinity); } }); }); }; }
JavaScript
0
@@ -1149,91 +1149,8 @@ %3E %7B%0A - // TODO: we would have to catch an error here and not continue%0A @@ -1750,85 +1750,8 @@ e %7B%0A - // TODO: we would have to catch an error here and not continue%0A
7ddf989c553129c6c7e631d80ca800b26da7cd52
remove unused import
source/views/building-hours/detail/building.js
source/views/building-hours/detail/building.js
// @flow import * as React from 'react' import {ScrollView, StyleSheet, Platform, Image} from 'react-native' import {images as buildingImages} from '../../../../images/spaces' import type {BuildingType} from '../types' import moment from 'moment-timezone' import * as c from '@frogpond/colors' import {getShortBuildingStatus} from '../lib' import {SolidBadge as Badge} from '@frogpond/badge' import {Header} from './header' import {ScheduleTable} from './schedule-table' import {ListFooter} from '@frogpond/lists' const styles = StyleSheet.create({ container: { alignItems: 'stretch', backgroundColor: c.sectionBgColor, }, image: { width: null, height: 100, }, }) type Props = { info: BuildingType, now: moment, onProblemReport: () => any, } const BGCOLORS = { Open: c.moneyGreen, Closed: c.salmon, } export class BuildingDetail extends React.Component<Props> { shouldComponentUpdate(nextProps: Props) { return ( !this.props.now.isSame(nextProps.now, 'minute') || this.props.info !== nextProps.info || this.props.onProblemReport !== nextProps.onProblemReport ) } render() { const {info, now, onProblemReport} = this.props const headerImage = info.image && buildingImages.hasOwnProperty(info.image) ? buildingImages[info.image] : null const openStatus = getShortBuildingStatus(info, now) const schedules = info.schedule || [] return ( <ScrollView contentContainerStyle={styles.container}> {headerImage ? ( <Image accessibilityIgnoresInvertColors={true} resizeMode="cover" source={headerImage} style={styles.image} /> ) : null} <Header building={info} /> <Badge accentColor={BGCOLORS[openStatus]} status={openStatus} /> <ScheduleTable now={now} onProblemReport={onProblemReport} schedules={schedules} /> <ListFooter title={ 'Building hours subject to change without notice\n\nData collected by the humans of All About Olaf' } /> </ScrollView> ) } }
JavaScript
0.000001
@@ -69,18 +69,8 @@ eet, - Platform, Ima
e223f45bceb51dc7bc4e9c3b34fe0e10fc640ab2
fix [flathub] version error handling (#8500)
services/flathub/flathub.service.js
services/flathub/flathub.service.js
import Joi from 'joi' import { renderVersionBadge } from '../version.js' import { BaseJsonService } from '../index.js' const schema = Joi.object({ currentReleaseVersion: Joi.string().required(), }).required() export default class Flathub extends BaseJsonService { static category = 'version' static route = { base: 'flathub/v', pattern: ':packageName' } static examples = [ { title: 'Flathub', namedParams: { packageName: 'org.mozilla.firefox', }, staticPreview: renderVersionBadge({ version: '78.0.2' }), }, ] static defaultBadgeData = { label: 'flathub' } async handle({ packageName }) { const data = await this._requestJson({ schema, url: `https://flathub.org/api/v1/apps/${encodeURIComponent(packageName)}`, }) return renderVersionBadge({ version: data.currentReleaseVersion }) } }
JavaScript
0
@@ -90,16 +90,26 @@ nService +, NotFound %7D from @@ -137,16 +137,47 @@ schema = + Joi.alternatives()%0A .try(%0A Joi.obj @@ -182,16 +182,20 @@ bject(%7B%0A + curren @@ -236,18 +236,72 @@ ired(),%0A -%7D) + %7D).required(),%0A Joi.valid(null).required()%0A )%0A .require @@ -885,16 +885,168 @@ %0A %7D)%0A +%0A // the upstream API indicates %22not found%22%0A // by returning a 200 OK with a null body%0A if (data === null) %7B%0A throw new NotFound()%0A %7D%0A%0A retu
697f6da2422d182d3d3b133d3f36c64e82e7bf2c
work on client
spotify_client.js
spotify_client.js
JavaScript
0
@@ -0,0 +1,374 @@ +Meteor.loginWithSpotify = function(options, callback) %7B%0A // support a callback without options%0A if (! callback && typeof options === %22function%22) %7B%0A callback = options;%0A options = null;%0A %7D%0A%0A var credentialRequestCompleteCallback = Accounts.oauth.credentialRequestCompleteHandler(callback);%0A Spotify.requestCredential(options, credentialRequestCompleteCallback);%0A%7D;
34f55889d63aff827bd1d2660dd48fa9c1b344b0
Make perms write_roles actually work
_design/perms/validate_doc_update.js
_design/perms/validate_doc_update.js
/** * Based on: https://github.com/iriscouch/manage_couchdb/ * License: Apache License 2.0 **/ function(newDoc, oldDoc, userCtx, secObj) { var ddoc = this; secObj.admins = secObj.admins || {}; secObj.admins.names = secObj.admins.names || []; secObj.admins.roles = secObj.admins.roles || []; var IS_DB_ADMIN = false; if(~ userCtx.roles.indexOf('_admin')) IS_DB_ADMIN = true; if(~ secObj.admins.names.indexOf(userCtx.name)) IS_DB_ADMIN = true; for(var i = 0; i < userCtx.roles; i++) if(~ secObj.admins.roles.indexOf(userCtx.roles[i])) IS_DB_ADMIN = true; // check access.json's write_roles collection for(var i = 0; i < userCtx.roles; i++) if(~ ddoc.write_roles.indexOf(userCtx.roles[i])) IS_DB_ADMIN = true; if(ddoc.access && ddoc.access.read_only) if(IS_DB_ADMIN) log('Admin change on read-only db: ' + newDoc._id); else throw {'forbidden':'This database is read-only'}; }
JavaScript
0.000002
@@ -659,32 +659,39 @@ %3C userCtx.roles +.length ; i++)%0A if(~ @@ -695,16 +695,23 @@ (~ ddoc. +access. write_ro
70100471a9d81d6821d05c50a9ed56598b3e1457
send a status code
lib/authentication/routes.js
lib/authentication/routes.js
// app/routes.js var email = require('../messaging/email'); var sms = require('../messaging/sms'); var request = require('request'); module.exports = function(app, passport) { // ===================================== // HOME PAGE (with login links) ======== // ===================================== app.get('/', function(req, res) { res.send('Babies are cute, aren\'t they?'); }); app.get('/danger/:value', function (req, res) { var value = +req.params.value; if (value === 1) { email.send({ to: 'karanmatic@gmail.com', from: 'other@example.com', subject: 'Baby Warning', text: 'Baby is sleeping on chest. Get to him now.' }, function () { }); } else { email.send({ to: 'karanmatic@gmail.com', from: 'other@example.com', subject: 'Baby Warning Ended', text: 'Baby is fine now. You are a good parent!' }, function () { }); } var url = 'https://graph.api.smartthings.com/api/smartapps/installations/40f0fc12-7ea9-4b62-86e7-30588c71df64/babyincradle'; request({ url: url, method: 'PUT', headers: { "Authorization": "Bearer 8b35f1bd-d58d-41a2-89b1-4c4608fa4e54" }, body: { 'isPressure': value }, json: true, timeout: 500 }, function(err, resp, body) { if (err) { console.log(err); } else { console.log(resp.statusCode); } }); }); // ===================================== // JAWBONE ROUTES ===================== // ===================================== // route for jawbone authentication and login app.get('/auth/jawbone', passport.authenticate('jawbone', { scope : ['basic_read','extended_read','friends_read','move_read','sleep_read','meal_read','mood_write'] })); // handle the callback after jawbone has authenticated the user app.get('/auth/jawbone/callback', passport.authenticate('jawbone', { failureRedirect : '/auth/jawbone' })); // route middleware to make sure a user is logged in function isLoggedIn(req, res, next) { // if user is authenticated in the session, carry on if (req.isAuthenticated()) return next(); // if they aren't redirect them to the auth page res.redirect('/auth/jawbone'); }; }
JavaScript
0
@@ -1380,16 +1380,35 @@ %7D%0A%09 %7D); +%0A%0A%09 res.send(200); %0A%09%7D);%0A%0A%09
8f92815414f6969fd29a4d80b8547c64a3ba1121
Bug fix. Subdirectories are not correctly reflected on Azure blob.
lib/hexo-azure-blob-deployer.js
lib/hexo-azure-blob-deployer.js
var fs = require('fs'); var azure = require('azure-storage'); module.exports = function(args, configFile) { var config = { storageAccount:{ storageAccountName: args.storage_account_name, storageAccessKey: args.storage_access_key }, blobStorage: { containerName: args.azure_container_name } }; if (!args.storage_account_name || !args.storage_access_key || !args.azure_container_name) { var help = ''; help += 'You should configure deployment settings in _config.yml first!\n\n'; help += 'Example:\n'; help += ' deploy:\n'; help += ' type: azure\n'; help += ' [storage_account_name]: <storage_account_name> \n'; help += ' [storage_access_key]: <storage_access_key> \n'; help += ' [azure_container_name]: <azure_container_name>\n'; help += 'For more help, you can check the docs: https://github.com/thdotnet/hexo-deployer-azure-blob-storage'; console.log(help); return; } var blobService = azure.createBlobService(config.storageAccount.storageAccountName, config.storageAccount.storageAccessKey); var objAccessLevel = { publicAccessLevel: 'blob' }; var containerName = config.blobStorage.containerName; blobService.createContainerIfNotExists(containerName, objAccessLevel, function(error, result, response) { if(error) { console.log(error); return; } console.log('Uploading...'); var rootPath = configFile.public_dir; var files = []; var pathcomponent = require('path'); var getFiles = function(path, subpath, files) { fs.readdirSync(path).forEach(function(file) { if(!!file && file[0] == '.') return; var fileName = path + pathcomponent.sep + file; if(fs.lstatSync(fileName).isDirectory()) { getFiles(fileName, path, files); } else { var blobName = subpath.replace(rootPath,"").split(pathcomponent.sep).join("/") + '/' + file; var obj = { "file": fileName, "subpath": subpath, "blobName": blobName }; files.push(obj); } }); }; var uploadFiles = function(files, blobService) { if(!!files) { for(var i = 0; i < files.length; i++) { var obj = files[i]; blobService.createBlockBlobFromLocalFile(containerName, obj.blobName, obj.file, function(error, result, response) { if(error) { console.log(error); } }); } console.log("end"); } }; getFiles(rootPath, "", files); uploadFiles(files, blobService); }); };
JavaScript
0.998221
@@ -1647,15 +1647,8 @@ me = - path + pat @@ -1662,18 +1662,33 @@ ent. -sep + +join(path, subpath, file +) ;%0A%09%09 @@ -1766,20 +1766,18 @@ leName, -path +%22%22 , files) @@ -1839,22 +1839,29 @@ e = -sub path +component .re -p la -c +tiv e(ro @@ -1871,60 +1871,50 @@ ath, -%22%22).split(pathcomponent.sep).join(%22/%22) + '/' + file + fileName).replace(pathcomponent.sep, %22/%22) ;%0A%09%09
0dcb74e8ab4dfa62f74a59066d4eeb62b35eca25
Fix users duplicate
client/helpers/pages/userList.js
client/helpers/pages/userList.js
/** * Get total groups when page load */ Template.userList.onCreated(function(){ var temp = this; temp.total = new ReactiveVar(); /** * Recalculate if user searching */ Tracker.autorun(function(){ Meteor.call('countUser',{search: Session.get('userSearch')},function(err,rs){ temp.total.set(rs); }); }); }); // ==================================== ========= ====================================// // ==================================== Helper ====================================// // ==================================== ========= ====================================// Template.userList.helpers({ /** * List all user logged */ Users : function(){ var temp = Meteor.users.find({},{sort: {points:'desc'}}).fetch(); for(var i = 1; i<= temp.length; i++){ temp[i-1].pos = i; } return temp; }, /** * pagination */ paging: function(){ return paginationFunc('people', Template.instance().total.get()); } }); Template.userListItem.helpers({ /** * Get main email address */ email:function(){ return this.emails[0].address; }, /** * Check if user voted this before */ action: function(){ var target = this._id; var action = Votes.find({target_id:target}); var like = 0, dislike = 0; action.forEach(function(act){ if(act.action=='like') like++; if(act.action=='dislike') dislike++; }); if(like - dislike > 0) return 'dislike'; else return 'like'; } }); // ==================================== ========= ====================================// // ==================================== Events ====================================// // ==================================== ========= ====================================// Template.userListItem.events({ /** * Like event handle */ 'click .like': function(event){ Meteor.call('userVote', {like:true, targetId:this._id}, function(error,result){ if(error) throwError(error.message); if(result.message) throwError(result.message); }) }, /** * Dislike event handle */ 'click .dislike': function(event){ Meteor.call('userVote', {like:false, targetId:this._id}, function(error,result){ if(error) throwError(error.message); if(result.message) throwError(result.message); }) } });
JavaScript
0.000033
@@ -742,16 +742,43 @@ s.find(%7B +_id: %7B$ne: Meteor.userId()%7D %7D,%7Bsort:
34a103d769433851031d8327d9f38721883304cd
Implement getting of artists by their genre
controllers/genre-controller.js
controllers/genre-controller.js
var model = require('../models/index'); /* Returns a list of artists with the given genre (in the query string) */ exports.getArtistsByGenre = function(req, res) { return res.status(200).send('Success'); } /* Gets all of the genres stored in the database */ exports.getGenres = function(req, res) { return res.status(200).send('Success'); }
JavaScript
0.000002
@@ -32,16 +32,43 @@ index'); +%0Avar _ = require('lodash'); %0A%0A/* Ret @@ -178,32 +178,64 @@ on(req, res) %7B%0A + if (_.isEmpty(req.query.genre)) return res.stat @@ -229,33 +229,33 @@ turn res.status( -2 +4 00).send('Succes @@ -248,26 +248,704 @@ ).send(' -Success'); +No parameters given');%0A else %7B%0A model.Genre.findOne(%7B where: %7B genre: req.query.genre %7D %7D)%0A .then(function(genre) %7B%0A if (_.isEmpty(genre)) return res.status(400).send('Genre not found');%0A else %7B%0A model.Artist.findAll(%7B where: %7B genre: genre.values.id %7D, limit: 20 %7D)%0A .then(function(artists) %7B%0A if (_.isEmpty(artists)) return res.status(400).send('No artist with genre found');%0A else %7B%0A return res.status(200).send(artists);%0A %7D%0A %7D)%0A .catch(function(err) %7B%0A return res.status(400).send(err);%0A %7D);%0A %7D%0A %7D)%0A .catch(function(err) %7B%0A return res.status(400).send(err);%0A %7D);%0A %7D %0A%7D%0A%0A/* G
133e11200f004ca0dd796869acb73e6aff0de013
FIX Missing cast for integer addition
lib/plugins/expressionParser.js
lib/plugins/expressionParser.js
/* * Copyright 2016 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of fiware-iotagent-lib * * fiware-iotagent-lib is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * fiware-iotagent-lib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with fiware-iotagent-lib. * If not, seehttp://www.gnu.org/licenses/. * * For those usages not covered by the GNU Affero General Public License * please contact with::daniel.moranjimenez@telefonica.com */ 'use strict'; var Parser = require('jison').Parser, errors = require('../errors'), grammar = { lex: { rules: [ ['\\s+', '/* skip whitespace */'], ['[0-9]+(?:\\.[0-9]+)?\\b', 'return "NUMBER";'], ['\\*', 'return "*";'], ['\\/', 'return "/";'], ['-', 'return "-";'], ['\\+', 'return "+";'], ['\\^', 'return "^";'], ['\\(', 'return "(";'], ['\\)', 'return ")";'], [',', 'return ",";'], ['#', 'return "#";'], ['indexOf', 'return "INDEX";'], ['length', 'return "LENGTH";'], ['substr', 'return "SUBSTR";'], ['trim', 'return "TRIM";'], ['@[a-zA-Z]+\\b', 'return "VARIABLE";'], ['"[a-zA-Z0-9\\s,]+"', 'return "STRING";'], ['\'[a-zA-Z0-9\\s,]+\'', 'return "STRING";'], ['$', 'return "EOF";'] ] }, operators: [ ['left', '#', '+', '-'], ['left', '*', '/'], ['left', '^'], ['left', 'UMINUS'] ], bnf: { expressions: [['e EOF', 'return $1;']], e: [ ['e + e', '$$ = $1 + $3;'], ['e - e', '$$ = $1 - $3;'], ['e * e', '$$ = $1 * $3;'], ['e / e', '$$ = $1 / $3;'], ['e ^ e', '$$ = Math.pow($1, $3);'], ['e # e', '$$ = String($1) + String($3);'], ['- e', '$$ = -$2;', {'prec': 'UMINUS'}], ['INDEX ( e , e )', '$$ = String($3).indexOf($5)'], ['SUBSTR ( e , e , e )', '$$ = String($3).substr($5, $7)'], ['LENGTH ( e )', '$$ = String($3).length'], ['TRIM ( e )', '$$ = String($3).trim()'], ['( e )', '$$ = $2;'], ['NUMBER', '$$ = Number(yytext);'], ['VARIABLE', '$$ = yy[yytext.substr(1)];'], ['STRING', '$$ = yytext.substr(1, yytext.length -2);'], ['E', '$$ = Math.E;'], ['PI', '$$ = Math.PI;']] } }, parser = new Parser(grammar); function parse(expression, context, type, callback) { var result, error; if (type !== 'String' && type !== 'Number') { error = new errors.WrongExpressionType(type); if (callback) { callback(error); } else { throw error; } } else { parser.yy = context; try { result = parser.parse(expression); } catch (e) { error = new errors.InvalidExpression(expression); if (callback) { return callback(error); } else { throw error; } } if (callback) { callback(null, result); } else { return result; } } } function extractContext(attributeList) { var context = {}; for (var i = 0; i < attributeList.length; i++) { context[attributeList[i].name] = attributeList[i].value; } return context; } exports.parse = parse; exports.extractContext = extractContext;
JavaScript
0.000001
@@ -2258,15 +2258,31 @@ $ = +Number( $1 +) + +Number( $3 +) ;'%5D,
11f4a1abfc0cefc3c5db6200f0161168f77950f0
add not set data to the summary object
lib/plugins/html/htmlBuilder.js
lib/plugins/html/htmlBuilder.js
'use strict'; const fs = require('fs'), helper = require('./helper'), Promise = require('bluebird'), path = require('path'), merge = require('lodash.merge'), reduce = require('lodash.reduce'), get = require('lodash.get'), set = require('lodash.set'), renderer = require('./renderer'); Promise.promisifyAll(fs); const PAGES_DIRECTORY = 'pages'; class HTMLBuilder { constructor(storageManager) { this.storageManager = storageManager; this.summaryPages = {}; this.urlPages = {}; this.urlRunPages = {}; } addUrl(url) { this.urlPages[url] = { path: 'pages/' + this.storageManager.relativePathFromUrl(url), data: {} }; this.urlRunPages[url] = {}; } addErrorForUrl(url, data) { const errors = get(this.urlPages[url], 'errors', []); errors.push(data); set(this.urlPages[url], 'errors', errors); } addDataForUrl(url, typePath, data, runIndex) { if (runIndex !== undefined) { let runData = this.urlRunPages[url][runIndex] || { path: this.storageManager.relativePathFromUrl(url), runIndex, data: {} }; set(runData.data, typePath, data); this.urlRunPages[url][runIndex] = runData; } else { let values = get(this.urlPages[url].data, typePath); if (values && Array.isArray(values)) { values.push(data); } else { if (Array.isArray(data)) { set(this.urlPages[url].data, typePath, data); } else { set(this.urlPages[url].data, typePath, [data]); } } } } addDataForSummaryPage(name, data) { set(this.summaryPages, name, data); } renderHTML(options) { const errors = reduce(this.urlPages, (errors, urlInfo, url) => { if (urlInfo.errors) { errors[url] = urlInfo.errors; } return errors; }, {}); if (Object.keys(errors).length > 0) { this.addDataForSummaryPage('errors', {errors}); } this.addDataForSummaryPage('pages', {pages: this.urlPages}); this.addDataForSummaryPage('index', {pageTitle: 'Summary', menu: 'summary'}); const summaryRenders = Object.keys(this.summaryPages) .map((name) => this._renderSummaryPage(name, this.summaryPages[name])); const urlPageRenders = Promise.resolve(Object.keys(this.urlPages)) .map((url) => { const pageInfo = this.urlPages[url]; const runPages = this.urlRunPages[url]; return this._renderUrlPage(url, 'index', {url, pageInfo, options, runPages}) .tap(() => Promise.resolve(Object.keys(runPages)) .map((runIndex) => this._renderUrlRunPage(url, runIndex, {url, runIndex, pageInfo: runPages[runIndex], options}))); }); // Aggregate/summarize data and write additional files return Promise.all(summaryRenders) .then(() => Promise.all(urlPageRenders)) .then(() => this.storageManager.copy(path.join(__dirname, 'assets'))); } _renderUrlPage(url, name, locals) { // FIXME use path.relative to get link from page to index locals = merge({ JSON: JSON, run: 0, path: '../../', menu: 'pages', pageTitle: name + ' ' + url, pageDescription: '', helper: helper }, locals); return this.storageManager.writeDataForUrl(url, PAGES_DIRECTORY, name + '.html', '', renderer.renderTemplate('url/' + name, locals)); } _renderUrlRunPage(url, name, locals) { // FIXME use path.relative to get link from page to index locals = merge({ urlLink: './index.html', JSON: JSON, path: '../../', menu: 'pages', pageTitle: name + ' ' + url, pageDescription: '', helper: helper }, locals); return this.storageManager.writeDataForUrl(url, PAGES_DIRECTORY, name + '.html', '', renderer.renderTemplate('url/run', locals)); } _renderSummaryPage(name, locals) { // FIXME use path.relative to get link from page to index locals = merge({ path: '', menu: name, pageTitle: name, pageDescription: '', helper: helper }, locals); return this.storageManager.writeData(name + '.html', renderer.renderTemplate(name, locals)); } } module.exports = HTMLBuilder;
JavaScript
0.000008
@@ -1599,24 +1599,122 @@ me, data) %7B%0A + if (this.summaryPages%5Bname%5D) %7B%0A merge(this.summaryPages%5Bname%5D, data);%0A %7D%0A else %7B%0A set(this @@ -1741,16 +1741,22 @@ data);%0A + %7D%0A %7D%0A%0A r @@ -3902,17 +3902,16 @@ ml', '', - %0A r
db213e67c9f67f1efd07f0cca66888ea410e4969
Store total number of 3rd party request (#2468)
lib/plugins/thirdparty/index.js
lib/plugins/thirdparty/index.js
'use strict'; const { getEntity } = require('third-party-web'); const aggregator = require('./aggregator'); const urlParser = require('url'); const DEFAULT_THIRDPARTY_PAGESUMMARY_METRICS = [ 'category.*.requests.*', 'category.*.tools.*' ]; module.exports = { open(context, options) { this.metrics = {}; this.options = options; this.context = context; this.make = context.messageMaker('thirdparty').make; this.groups = {}; this.runsPerUrl = {}; if (options.thirdParty && options.thirdParty.cpu) { DEFAULT_THIRDPARTY_PAGESUMMARY_METRICS.push('tool.*'); } context.filterRegistry.registerFilterForType( DEFAULT_THIRDPARTY_PAGESUMMARY_METRICS, 'thirdparty.pageSummary' ); }, processMessage(message, queue) { const make = this.make; const thirdPartyAssetsByCategory = {}; const toolsByCategory = {}; const possibileMissedThirdPartyDomains = []; if (message.type === 'pagexray.run') { const firstPartyRegEx = message.data.firstPartyRegEx; for (let d of Object.keys(message.data.domains)) { const entity = getEntity(d); if (entity !== undefined) { // Here is a match } else { if (!d.match(firstPartyRegEx)) { possibileMissedThirdPartyDomains.push(d); } } } const byCategory = {}; this.groups[message.url] = message.group; let totalThirdPartyRequests = 0; for (let asset of message.data.assets) { const entity = getEntity(asset.url); if (entity !== undefined) { totalThirdPartyRequests++; if ( entity.name.indexOf('Google') > -1 || entity.name.indexOf('Facebook') > -1 || entity.name.indexOf('AMP') > -1 || entity.name.indexOf('YouTube') > -1 ) { if (!entity.categories.includes('survelliance')) { entity.categories.push('survelliance'); } } for (let category of entity.categories) { if (!toolsByCategory[category]) { toolsByCategory[category] = {}; } if (byCategory[category]) { byCategory[category] = byCategory[category] + 1; thirdPartyAssetsByCategory[category].push({ url: asset.url, entity }); } else { byCategory[category] = 1; thirdPartyAssetsByCategory[category] = []; thirdPartyAssetsByCategory[category].push({ url: asset.url, entity }); } toolsByCategory[category][entity.name] = 1; } } else { // We don't have a match for this request, check agains the regex if (!asset.url.match(firstPartyRegEx)) { if (byCategory['unknown']) { byCategory['unknown'] = byCategory['unknown'] + 1; } else { byCategory['unknown'] = 1; } } } } const cpuPerTool = {}; if (message.data.cpu && message.data.cpu.urls) { for (let ent of message.data.cpu.urls) { let entity = getEntity(ent.url); // fallback to domain if (!entity) { const hostname = urlParser.parse(ent.url).hostname; entity = { name: hostname }; } if (cpuPerTool[entity.name]) { cpuPerTool[entity.name] += ent.value; } else { cpuPerTool[entity.name] = ent.value; } } } aggregator.addToAggregate( message.url, byCategory, toolsByCategory, totalThirdPartyRequests, cpuPerTool ); const runData = { category: byCategory, assets: thirdPartyAssetsByCategory, toolsByCategory, possibileMissedThirdPartyDomains: possibileMissedThirdPartyDomains, requests: totalThirdPartyRequests, cpuPerTool }; queue.postMessage( make('thirdparty.run', runData, { url: message.url, group: message.group, runIndex: message.runIndex }) ); if (this.runsPerUrl[message.url]) { this.runsPerUrl[message.url].push(runData); } else { this.runsPerUrl[message.url] = [runData]; } } else if (message.type === 'sitespeedio.summarize') { let summary = aggregator.summarize(); for (let url of Object.keys(summary)) { summary[url].runs = this.runsPerUrl[url]; queue.postMessage( make('thirdparty.pageSummary', summary[url], { url, group: this.groups[url] }) ); } } } };
JavaScript
0
@@ -235,16 +235,30 @@ tools.*' +,%0A 'requests' %0A%5D;%0A%0Amod
dd0d21f04a0c4d2418bc6cd37e9df8e3e1877179
rename variable emph => email_invalid
frappe/public/js/frappe/form/controls/data.js
frappe/public/js/frappe/form/controls/data.js
frappe.ui.form.ControlData = frappe.ui.form.ControlInput.extend({ html_element: "input", input_type: "text", make_input: function() { if(this.$input) return; this.$input = $("<"+ this.html_element +">") .attr("type", this.input_type) .attr("autocomplete", "off") .addClass("input-with-feedback form-control") .prependTo(this.input_area); if (in_list(['Data', 'Link', 'Dynamic Link', 'Password', 'Select', 'Read Only', 'Attach', 'Attach Image'], this.df.fieldtype)) { this.$input.attr("maxlength", this.df.length || 140); } this.set_input_attributes(); this.input = this.$input.get(0); this.has_input = true; this.bind_change_event(); this.bind_focusout(); this.setup_autoname_check(); // somehow this event does not bubble up to document // after v7, if you can debug, remove this }, setup_autoname_check: function() { if (!this.df.parent) return; this.meta = frappe.get_meta(this.df.parent); if (this.meta && ((this.meta.autoname && this.meta.autoname.substr(0, 6)==='field:' && this.meta.autoname.substr(6) === this.df.fieldname) || this.df.fieldname==='__newname') ) { this.$input.on('keyup', () => { this.set_description(''); if (this.doc && this.doc.__islocal) { // check after 1 sec let timeout = setTimeout(() => { // clear any pending calls if (this.last_check) clearTimeout(this.last_check); // check if name exists frappe.db.get_value(this.doctype, this.$input.val(), 'name', (val) => { if (val) { this.set_description(__('{0} already exists. Select another name', [val.name])); } }, this.doc.parenttype ); this.last_check = null; }, 1000); this.last_check = timeout; } }); } }, set_input_attributes: function() { this.$input .attr("data-fieldtype", this.df.fieldtype) .attr("data-fieldname", this.df.fieldname) .attr("placeholder", this.df.placeholder || ""); if(this.doctype) { this.$input.attr("data-doctype", this.doctype); } if(this.df.input_css) { this.$input.css(this.df.input_css); } if(this.df.input_class) { this.$input.addClass(this.df.input_class); } }, set_input: function(value) { this.last_value = this.value; this.value = value; this.set_formatted_input(value); this.set_disp_area(value); this.set_mandatory && this.set_mandatory(value); }, set_formatted_input: function(value) { this.$input && this.$input.val(this.format_for_input(value)); }, get_input_value: function() { return this.$input ? this.$input.val() : undefined; }, format_for_input: function(val) { return val==null ? "" : val; }, validate: function(v) { if (!v){ return ''; } if(this.df.is_filter) { return v; } if(this.df.options == 'Phone') { this.df.invalid = !validate_phone(v) return v; } else if(this.df.options == 'Email') { var email_list = frappe.utils.split_emails(v); if (!email_list) { return ''; } else { let emph = false; email_list.forEach(function(email) { if (!validate_email(email)) { emph = emph || true; } }); this.df.invalid = emph; return v; } } else { return v; } } });
JavaScript
0.000051
@@ -2996,18 +2996,27 @@ %09%09let em -ph +ail_invalid = false @@ -3105,20 +3105,21 @@ %09%09em -ph = emph %7C%7C +ail_invalid = tru @@ -3160,18 +3160,27 @@ lid = em -ph +ail_invalid ;%0A%09%09%09%09re
44284005fa72d78d85ef07fcfc14adf6454a1218
Update budgeting-loans.js
lib/projects/budgeting-loans.js
lib/projects/budgeting-loans.js
{ "id":15, "name":"Apply for a Budgeting Loan", "description": "Lets users apply for a short-term cash loan so that they can afford to buy essential items or services.", "theme": "Working Age", "location": "Leeds", "phase":"private beta", "sro":"Derek Hobbs", "service_man":"Zoe Gould", "phase-history":{ "discovery": [ {"label":"Completed", "date": "May 2015"} ], "alpha": [ {"label":"Completed", "date": "November 2015"} ], "beta": [ {"label":"Started", "date": "November 2015"}, {"label":"Private beta predicted", "date": "January 2015"}, {"label":"Public beta predicted", "date": "March 2016"} ] }, "priority":"Low" }
JavaScript
0
@@ -233,16 +233,8 @@ e%22:%22 -private beta
fa17b6882ae114e3f58d940df76257bfa77073b1
Include port as a connection parameter for socket connections
lib/connection-parameters.js
lib/connection-parameters.js
var url = require('url'); var dns = require('dns'); var defaults = require(__dirname + '/defaults'); var val = function(key, config, envVar) { if (envVar === undefined) { envVar = process.env[ 'PG' + key.toUpperCase() ]; } else if (envVar === false) { // do nothing ... use false } else { envVar = process.env[ envVar ]; } return config[key] || envVar || defaults[key]; }; //parses a connection string var parse = function(str) { var config; //unix socket if(str.charAt(0) === '/') { config = str.split(' '); return { host: config[0], database: config[1] }; } // url parse expects spaces encoded as %20 if(/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(str)) { str = encodeURI(str).replace(/\%25(\d\d)/g, "%$1"); } var result = url.parse(str, true); config = {}; if (result.query.application_name) { config.application_name = result.query.application_name; } if (result.query.fallback_application_name) { config.fallback_application_name = result.query.fallback_application_name; } if(result.protocol == 'socket:') { config.host = decodeURI(result.pathname); config.database = result.query.db; config.client_encoding = result.query.encoding; return config; } config.host = result.hostname; config.database = result.pathname ? decodeURI(result.pathname.slice(1)) : null; var auth = (result.auth || ':').split(':'); config.user = auth[0]; config.password = auth[1]; config.port = result.port; var ssl = result.query.ssl; if (ssl === 'true' || ssl === '1') { config.ssl = true; } return config; }; var useSsl = function() { switch(process.env.PGSSLMODE) { case "disable": return false; case "prefer": case "require": case "verify-ca": case "verify-full": return true; } return defaults.ssl; }; var ConnectionParameters = function(config) { config = typeof config == 'string' ? parse(config) : (config || {}); this.user = val('user', config); this.database = val('database', config); this.port = parseInt(val('port', config), 10); this.host = val('host', config); this.password = val('password', config); this.binary = val('binary', config); this.ssl = config.ssl || useSsl(); this.client_encoding = val("client_encoding", config); //a domain socket begins with '/' this.isDomainSocket = (!(this.host||'').indexOf('/')); this.application_name = val('application_name', config, 'PGAPPNAME'); this.fallback_application_name = val('fallback_application_name', config, false); }; var add = function(params, config, paramName) { var value = config[paramName]; if(value) { params.push(paramName+"='"+value+"'"); } }; ConnectionParameters.prototype.getLibpqConnectionString = function(cb) { var params = []; add(params, this, 'user'); add(params, this, 'password'); add(params, this, 'port'); add(params, this, 'application_name'); add(params, this, 'fallback_application_name'); if(this.database) { params.push("dbname='" + this.database + "'"); } if(this.host) { params.push("host=" + this.host); } if(this.isDomainSocket) { return cb(null, params.join(' ')); } if(this.client_encoding) { params.push("client_encoding='" + this.client_encoding + "'"); } dns.lookup(this.host, function(err, address) { if(err) return cb(err, null); params.push("hostaddr=" + address); return cb(null, params.join(' ')); }); }; module.exports = ConnectionParameters;
JavaScript
0
@@ -1050,16 +1050,45 @@ e;%0A %7D%0A%0A + config.port = result.port;%0A if(res @@ -1494,37 +1494,8 @@ %5B1%5D; -%0A config.port = result.port; %0A%0A @@ -1748,17 +1748,16 @@ %0A case - %22verify-
01b5901c3fbe8510cb6118591c70312d0ed54f78
add action type
lib/constants/ActionTypes.js
lib/constants/ActionTypes.js
export const ADD_HISTORY = 'ADD_HISTORY';
JavaScript
0.000398
@@ -10,33 +10,39 @@ nst -ADD_HISTORY = 'ADD_HISTORY +UPDATE_SETTING = 'UPDATE_SETTING ';%0A
45961532c980116e2ee625ec6c4ecfc868e0dc4a
Remove extra variables
lib/core/build-suggestion.js
lib/core/build-suggestion.js
"use babel" // @flow import type { Info, Range, Suggestion } from '../types' const scopeSize = ({block: b}) => b.end - b.start function findClosestScope(scopes, start, end) { return scopes.reduce((closest, scope) => { const { block } = scope if (block.start <= start && block.end >= end && scopeSize(scope) < scopeSize(closest) ) { return scope } return closest }) } type SuggestionOptions = { jumpToImport?: boolean, } export default function buildSuggestion(info: Info, text: string, { start, end }: Range, options: SuggestionOptions = {}): ?Suggestion { if (info.parseError) throw info.parseError const { paths, scopes, externalModules } = info for (let i = 0; i < paths.length; i++) { const path = paths[i] if (path.range.start > end) { break } if (path.range.start <= start && path.range.end >= end) { if (path.imported !== 'default') { const tmp = { type: 'from-import', imported: path.imported, moduleName: path.moduleName, bindingStart: path.range.start, bindingEnd: path.range.end, } return tmp } return { type: 'path', imported: path.imported, moduleName: path.moduleName, range: path.range } } } const closestScope = findClosestScope(scopes, start, end) // Sometimes it reports it has a binding, but it can't actually get the // binding if (closestScope.hasBinding(text) && closestScope.getBinding(text)) { const binding = closestScope.getBinding(text) const { start: bindingStart, end: bindingEnd } = binding.identifier const clickedDeclaration = ( bindingStart <= start && bindingEnd >= end ) const crossFiles = !options.jumpToImport if (clickedDeclaration || crossFiles) { const targetModule = externalModules.find((m) => { const { start: bindingStart } = binding.identifier return m.local == text && m.start == bindingStart }) if (targetModule) { const tmp = { // ...targetModule, type: 'from-import', imported: targetModule.imported, moduleName: targetModule.moduleName, bindingStart, bindingEnd, } return tmp } } // Exit early if you clicked on where the variable is declared if (clickedDeclaration) { return null } return { type: 'binding', start: bindingStart, end: bindingEnd, moduleName: undefined, } } return null }
JavaScript
0.000336
@@ -990,35 +990,30 @@ -const tmp = +return %7B%0A @@ -1260,35 +1260,8 @@ %7D%0A - return tmp%0A @@ -2307,61 +2307,16 @@ -const tmp = %7B%0A // ...targetModule, +return %7B %0A @@ -2551,35 +2551,8 @@ %7D%0A - return tmp%0A
21b24d3fb61e50b404623491fb03995fc089ff22
set the timestamp as close as the iteration as possible
lib/core/engine/iteration.js
lib/core/engine/iteration.js
'use strict'; const Promise = require('bluebird'); const webdriver = require('selenium-webdriver'); const log = require('intel'); const merge = require('lodash.merge'); const SeleniumRunner = require('../seleniumRunner'); const preURL = require('../../support/preURL'); const setResourceTimingBufferSize = require('../../support/setResourceTimingBufferSize'); const filterWhitelisted = require('../../support/userTiming').filterWhitelisted; const engineUtils = require('../../support/engineUtils'); const Video = require('../../video/video'); const setOrangeBackground = require('../../video/screenRecording/setOrangeBackground'); const stop = require('../../support/stop'); const { createAndroidConnection, isAndroidConfigured } = require('../../android'); const delay = ms => new Promise(res => setTimeout(res, ms)); /** * Create a new Iteration instance. This is the iteration flow, what * Browsertime will do through one iteration of testing a URL. * @class */ class Iteration { constructor( storageManager, extensionServer, engineDelegate, scriptsByCategory, asyncScriptsByCategory, options ) { try { this.preScripts = engineUtils.loadPrePostScripts(options.preScript); this.postScripts = engineUtils.loadPrePostScripts(options.postScript); } catch (e) { log.error(e.message); throw e; } this.options = options; this.storageManager = storageManager; this.extensionServer = extensionServer; this.recordVideo = options.visualMetrics || options.video; this.engineDelegate = engineDelegate; this.scriptsByCategory = scriptsByCategory; this.asyncScriptsByCategory = asyncScriptsByCategory; this.myVideo = new Video(storageManager, options); } /** * Run one iteration for one url. Here are the whole flow of what we * do for one URL per iteration. * @param {*} url - The URL that will be tested * @param {*} index - Which iteration it is */ async run(url, index) { const options = this.options; const browser = new SeleniumRunner( this.storageManager.directory, this.options ); const extensionServer = this.extensionServer; const recordVideo = this.recordVideo; const combine = options.videoParams.combine; const video = this.myVideo; // The data we push to all pre/post tasks const taskOptions = { url, options, log, storageManager: this.storageManager, taskData: {}, index, webdriver, runWithDriver: function(driverScript) { return browser.runWithDriver(driverScript); } }; const result = { extraJson: {} }; if (recordVideo) { await video.setupDirs(index); } log.info('Testing url %s iteration %s', url, index + 1); try { await browser.start(); await setResourceTimingBufferSize(browser.getDriver(), 600); await extensionServer.setupExtension(url, browser); if (recordVideo && combine) { await video.record(); } // Run all the pre scripts await Promise.mapSeries(this.preScripts, preScript => preScript.run(taskOptions) ); if (options.preURL) { await preURL(browser, options); } await this.engineDelegate.onStartIteration(browser, index); result.timestamp = engineUtils.timestamp(); // By default start the video just before we start to // load the URL we wanna test if (recordVideo && !combine) { await setOrangeBackground(browser.getDriver()); await video.record(); // Give ffmpeg some time to settle await delay(400); } await browser.loadAndWait(url, options.pageCompleteCheck); // And stop the video when the URL is finished if (recordVideo && !combine) { await video.stop(); } // Collect all the metrics through JavaScript const syncScripts = this.scriptsByCategory ? await browser.runScripts(this.scriptsByCategory) : {}, asyncScripts = this.asyncScriptsByCategory ? await browser.runScripts(this.asyncScriptsByCategory, true) : {}; result.browserScripts = merge({}, syncScripts, asyncScripts); // Some sites has crazy amount of user timings: // strip them if you want if (options.userTimingWhitelist) { filterWhitelisted( result.browserScripts.timings.userTimings, options.userTimingWhitelist ); } if (options.screenshot) { try { result.screenshot = await browser.takeScreenshot(); } catch (e) { // not getting screenshots shouldn't result in a failed test. log.warning(e); } } if (options.chrome && options.chrome.collectConsoleLog) { result.extraJson[`console-${index}.json`] = await browser.getLogs( webdriver.logging.Type.BROWSER ); } if (isAndroidConfigured(options) && options.chrome.collectNetLog) { const android = createAndroidConnection(options); await android.initConnection(); await android.pullNetLog( `${this.storageManager.directory}/chromeNetlog-${index}.json` ); } await this.engineDelegate.onStopIteration(browser, index, result); // Run all the post scripts await Promise.mapSeries(this.postScripts, postScript => { taskOptions.results = result; return postScript.run(taskOptions); }); if (recordVideo && combine) { await video.stop(); } // maybe we should close the browser before? hmm if (recordVideo) { await video.postProcessing(result); } return result; } catch (e) { log.error(e); // In docker we can use a hardcore way to cleanup if (options.docker) { if (recordVideo) { await stop('ffmpeg'); } } result.error = e.name; return result; } finally { // Here we should also make sure FFMPEG is really killed/stopped // if something fails, we had bug reports where we miss it await browser.stop(); } } } module.exports = Iteration;
JavaScript
0.000044
@@ -3243,125 +3243,8 @@ %7D%0A - await this.engineDelegate.onStartIteration(browser, index);%0A result.timestamp = engineUtils.timestamp();%0A%0A @@ -3531,24 +3531,140 @@ 0);%0A %7D%0A + await this.engineDelegate.onStartIteration(browser, index);%0A result.timestamp = engineUtils.timestamp();%0A await
1f068a9c65f3bdfe5c9e30b6a0e2735e5c0da43d
validate meta tag usage
lib/report/validator/pasties.js
lib/report/validator/pasties.js
function validateWrapper(wrapper, report) { if (wrapper.css.position !== 'static' || wrapper.css.visability !== '') { report.error('Do not style outside bannercontainer, wrapper element has received som styling'); } } function validateBannerCSS(banner, data, report) { var pastieSize = data ? ('Pasties reported size width ' + data.frameOutput.width + ' x height ' + data.frameOutput.height) : ''; if (banner.found === false) { report.warn('Bannercontainer not found/identified. ' + pastieSize); return; } if (banner.name) { var css = banner.css; report.info('Bannercontainer found/identified, size width ' + css.width + ' x height ' + css.height + '. ' + pastieSize); if (css.height !== "225px") { report.error('Bannercontainer needs to be 225 high. Currently it is ' + css.height); } // should be viewport width if (css.width !== '980px'){ report.error('Bannercontainer should use 100% width. Currently it is ' + css.width); } if (css.display !== 'block'){ report.error('Bannercontainer should use display:block. Currently it is ' + css.display); } if (css.position !== 'static') { report.error('Bannercontainer should have position: "static", but instead it has position: "' + css.position + '". Please use a inner container if position "relative" or "absolute" is needed.'); } } } function findWindowOpenError(list){ return list.filter(function(entry){return entry.target !== 'new_window';}); } function windowOpenErrors(list, report){ var errors = findWindowOpenError(list); if (errors && errors.length > 0) { var message = 'Window open called with wrong target, check url' + errors[0].url + ' and target ' + errors[0].target; report.error(message, { trace: errors.map(function (entry) { return entry.trace; }) }); } return errors.length === 0; } var RE_WINDOW_OPEN = /.*(window\.open\()+(.*)(new_window)+/gmi; function validateBannerDom(banner, data, windowOpened, report){ if (banner.found === false) { return; } if (windowOpened && windowOpened.length > 0){ var noErrorsFound = windowOpenErrors(windowOpened, report); if (noErrorsFound){ // if window open was registered and no errors found, we do not need to check for clickhandler. return; } } if (!banner.clickHandler || banner.clickHandler === ''){ report.error('Missing clickhandler on banner html element/tag ' + banner.name + '.'); } else if (banner.clickHandler){ var matches = banner.clickHandler.match(RE_WINDOW_OPEN); if (!matches){ report.error('Missing onclick handler on banner wrapper element, and no click registered in simulation.'); } } } function validateRules(harvested, report, next) { var domData = harvested.pastiesDom; if (domData) { validateWrapper(domData.wrapper, report); validateBannerCSS(domData.banner, harvested.pastiesData, report); validateBannerDom(domData.banner, harvested.pastiesData, harvested.windowOpened, report); } next(); } module.exports = { validate: function (harvested, report, next) { if (harvested) { validateRules(harvested, report, next); } else { next(); } } };
JavaScript
0.000001
@@ -2206,32 +2206,197 @@ return;%0A %7D%0A%0A + if (banner.html && banner.html.indexOf('%3Ciframe')%3E-1)%7B%0A report.warn('Please do not use iframes inside iframe, pasties iframe is your sandbox.');%0A %7D%0A%0A%0A%0A if (windowOp @@ -2429,16 +2429,16 @@ h %3E 0)%7B%0A - @@ -3080,32 +3080,233 @@ %7D%0A %7D%0A%7D%0A%0A +function valdiateTags(illegal, report)%7B%0A if (illegal && illegal.length %3E 0)%7B%0A report.warn('Found illegal tags/usages', %7Blist: illegal.map(function(v)%7Breturn v.html.join(',%5Cn');%7D)%7D);%0A %7D%0A%7D%0A%0A function validat @@ -3515,32 +3515,32 @@ sData, report);%0A - validate @@ -3617,24 +3617,71 @@ d, report);%0A + valdiateTags(domData.illegal, report);%0A %7D%0A%0A n
52dba3223597793285950fb23871b20ee4f8dee3
add destination tag if there is any
lib/core/outgoing_payment.js
lib/core/outgoing_payment.js
var RippleRestClient = require('ripple-rest-client'); var uuid = require('node-uuid'); var async = require('async'); var gateway = require(__dirname+'/../../'); var hotWallet = gateway.config.get('HOT_WALLET'); function OutgoingPayment(outgoingPaymentRecord) { this.record = outgoingPaymentRecord; this.rippleRestClient = new RippleRestClient({ account: hotWallet.address, secret: hotWallet.secret }); } OutgoingPayment.prototype = { processOutgoingPayment: function(callback) { var self = this; async.waterfall([ function(next) { self._getRippleAddressRecord(next); }, function(address, next) { self._buildPayment(address, next); }, function(payment, next) { self._sendPayment(payment, next); }, function(response, next) { self._markRecordAsSent(response, next); }, function(response, next) { self._confirmSuccessfulPayment(response, next); } ], function(error) { if (error) { self._handleRippleRestFailure(error, function() { logger.error('payments:outgoing:failed', error, self.record.toJSON()); callback(error, self.record); }); } else { logger.info('payment:outgoing:succeeded', self.record.toJSON()); callback(error, self.record); } }); }, _recordAcceptanceOrRejectionStatus: function(payment, callback) { var self = this; self.record.transaction_state = payment.result; self.record.transaction_hash = payment.hash; switch(self.record.transaction_state) { case 'tesSUCCESS': self.record.state = 'succeeded'; break; default: self.record.state = 'failed'; } self.record.save().complete(function(error, record){ //depositCallbackJob.perform([self.record.id], console.log); callback(null, record); }); }, _confirmSuccessfulPayment: function(response, callback) { var statusUrl = response.status_url; var self = this; self.rippleRestClient.pollPaymentStatus(statusUrl, function(error, paymentStatus) { if (error) { return callback(error, null); } self._recordAcceptanceOrRejectionStatus(paymentStatus, function(error, record) { callback(null, record); }); }); }, _markRecordAsSent: function(response, callback) { var self = this; self.record.state = 'sent'; self.record.uid = response.client_resource_id; self.record.save().complete(function(){ callback(null, response); }); }, _handleRippleRestFailure: function(error, callback) { var self = this; if (error && typeof error === 'string' && error.match('No paths found')){ error = 'noPathFound'; } else if (error && typeof error === 'string' && error.match('No connection to rippled') || error.match('ECONNREFUSED') || error.match('try again') || error.match('Cannot connect to rippled') || error.match('RippledConnectionError')) { error = 'retry'; } switch(error) { case 'retry': self.record.state = 'outgoing'; break; case 'noPathFound': self.record.transaction_state = 'tecPATH_DRY'; self.record.state = 'failed'; break; default: self.record.state = 'failed'; } self.record.save().complete(function(){ //depositCallbackJob.perform([self.record.id], console.log); callback(); }); }, _getRippleAddressRecord: function(callback) { var self = this; gateway.data.rippleAddresses.read(self.record.to_address_id, callback); }, _buildPayment: function(address, callback) { var self = this; self.rippleRestClient.buildPayment({ amount: self.record.to_amount, currency: self.record.to_currency, issuer: self.record.to_issuer, account: hotWallet.address, recipient: address.address }, function(error, response) { if (error) { return callback(error.message, null); } if (response && response.success) { var payment = response.payments[0]; if (payment) { callback(null, payment); } else { callback('BuildPaymentError', null); } } else { callback(response.message, null); } }); }, _sendPayment: function(payment, callback) { var self = this; if (payment) { if (payment.source_tag) { payment.source_tag = self.record.from_address_id.toString(); } } else { return callback('no payment', null); } self.rippleRestClient.sendPayment({ payment: payment, client_resource_id: uuid.v4(), secret: hotWallet.secret }, function(error, response){ if (error) { callback(error, null); } else if (response.success){ callback(null, response); } else { callback(response.message, null); } }); } }; module.exports = OutgoingPayment;
JavaScript
0.000001
@@ -1915,32 +1915,31 @@ t: function( -response +payment , callback) @@ -1944,49 +1944,8 @@ ) %7B%0A - var statusUrl = response.status_url;%0A @@ -2009,17 +2009,15 @@ tus( -statusUrl +payment , fu @@ -4086,24 +4086,129 @@ (payment) %7B%0A + if (address.tag) %7B%0A payment.destination_tag = address.tag.toString();%0A %7D%0A ca
a4d20ed4dddb6fc02be879b73039ea7fc977a17c
Fix for tab control removing all extra css classes from tabs
framework/Web/Javascripts/source/prado/controls/tabpanel.js
framework/Web/Javascripts/source/prado/controls/tabpanel.js
Prado.WebUI.TTabPanel = jQuery.klass(Prado.WebUI.Control, { onInit : function(options) { this.views = options.Views; this.viewsvis = options.ViewsVis; this.hiddenField = jQuery("#"+options.ID+'_1').get(0); this.activeCssClass = options.ActiveCssClass; this.normalCssClass = options.NormalCssClass; var length = options.Views.length; for(var i = 0; i<length; i++) { var item = options.Views[i]; var element = jQuery("#"+item+'_0').get(0); if (element && options.ViewsVis[i]) { this.observe(element, "click", jQuery.proxy(this.elementClicked,this,item)); if (options.AutoSwitch) this.observe(element, "mouseenter", jQuery.proxy(this.elementClicked,this,item)); } if(element) { var view = jQuery("#"+options.Views[i]).get(0); if (view) if(this.hiddenField.value == i) { element.className=this.activeCssClass; jQuery(view).show(); } else { element.className=this.normalCssClass; jQuery(view).hide(); } } } }, elementClicked : function(viewID, event) { var length = this.views.length; for(var i = 0; i<length; i++) { var item = this.views[i]; if (jQuery("#"+item)) { if(item == viewID) { jQuery("#"+item+'_0').removeClass(this.normalCssClass).addClass(this.activeCssClass); jQuery("#"+item).show(); this.hiddenField.value=i; } else { jQuery("#"+item+'_0').removeClass(this.activeCssClass).addClass(this.normalCssClass); jQuery("#"+item).hide(); } } } } });
JavaScript
0
@@ -841,131 +841,213 @@ %09%09%09%09 -element.className=this.activeCssClass;%0A%09%09%09%09%09%09jQuery(view).show();%0A%09%09%09%09%09%7D else %7B%0A%09%09%09%09%09%09element.className=this.normalCssClass +jQuery(element).addClass(this.activeCssClass).removeClass(this.normalCssClass);%0A%09%09%09%09%09%09jQuery(view).show();%0A%09%09%09%09%09%7D else %7B%0A%09%09%09%09%09%09jQuery(element).addClass(this.normalCssClass).removeClass(this.activeCssClass) ;%0A%09%09
d9a917646526a352b29b2298b4ff6f089fc973cb
Allow setting arbitrary attributes on display sheets.
lib/depject/sheet/display.js
lib/depject/sheet/display.js
const h = require('mutant/h') const nest = require('depnest') exports.gives = nest('sheet.display') exports.create = function () { return nest('sheet.display', function (handler) { const { content, footer, classList, onMount } = handler(done) const container = h('div', { className: 'Sheet', classList }, [ h('section', [content]), h('footer', [footer]) ]) document.body.appendChild(container) if (onMount) onMount() function done () { document.body.removeChild(container) } }) }
JavaScript
0
@@ -225,16 +225,28 @@ onMount +, attributes %7D = han @@ -265,34 +265,28 @@ -const container = h('div', +let fullAttributes = %7B c @@ -315,16 +315,164 @@ ssList %7D +%0A if (attributes !== undefined) %7B%0A fullAttributes = %7B ...attributes, ...fullAttributes %7D%0A %7D%0A const container = h('div', fullAttributes , %5B%0A
0a9f090230047d6d82e4da56f95ed0433288df21
Change level version
canvas_move.js
canvas_move.js
document.getElementById("id_logic_level_version").innerHTML="Business level version 2017.11.15.6"; var canvas = document.getElementById("id_canvas"); var context = canvas.getContext("2d"); var rect_canvas = canvas.getBoundingClientRect(); var img = document.getElementById("id_img"); var top_x = 100; var top_y = 100; var img_width = 200; var img_height = 200; img.onload = function(){ context.drawImage(img, top_x, top_y, img_width, img_height); var rect_img = img.getBoundingClientRect(); } canvas.addEventListener("touchmove", on_touch_move); //----------------------------------------------- function on_touch_move(e) { e.preventDefault(); var touches = e.changedTouches; for (var i = 0; i < touches.length; i++){ if (touches[i].pageX - rect_canvas.left < top_x + img_width && touches[i].pageX - rect_canvas.left >= top_x && touches[i].pageY - rect_canvas.top< top_y + img_width && touches[i].pageY - rect_canvas.top >= top_y) { var offset_inside_image_x = (touches[i].pageX - rect_canvas.left) - top_x; var offset_inside_image_y = (touches[i].pageY - rect_canvas.top) - top_y; context.clearRect(0, 0, 800, 600); top_x = touches[i].pageX - rect_canvas.left; top_y = touches[i].pageY - rect_canvas.top; context.drawImage(img, top_x, top_y, img_width, img_height); } } } //-----------------------------------------------
JavaScript
0
@@ -88,17 +88,17 @@ 7.11.15. -6 +7 %22;%0D%0A%0D%0Ava
e3b7b5f3ffa851c449ada6c3b08b7ac3705517bb
send data on connection of clients
lib/server/dataSourceManager.js
lib/server/dataSourceManager.js
/*jlint node: true */ /*global require, console, module, process, __dirname */ /* * dataSourceManager.js * * Copyright (C) 2014 by James Jenner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ var MeltingPot = require('meltingpot'); var DataSource = require('../shared/dataSource.js'); var VersionOne = require('./versionOne.js'); var AgileSprint = require('../shared/agileSprint.js'); var Jenkins = require('./jenkins.js'); var JenkinsState = require('../shared/jenkinsState.js'); module.exports = DataSourceManager; function DataSourceManager(options) { this.clientComms = ((options.clientComms !== null && options.clientComms !== undefined) ? options.clientComms : null); this.dataSourceHandler = ((options.dataSourceHandler !== null && options.dataSourceHandler !== undefined) ? options.dataSourceHandler : null); this.widgetHandler = ((options.widgetHandler !== null && options.widgetHandler !== undefined) ? options.widgetHandler : null); this.connection = null; this.dataSources = {}; } DataSourceManager.prototype.start = function() { if(this.dataSourceHandler === null) { return; } for(var i = 0; i < this.dataSourceHandler.dataSources.length; i++) { switch(this.dataSourceHandler.dataSources[i].type) { case DataSource.TYPE_VERSION_ONE: this.__startVersionOne(this.dataSourceHandler.dataSources[i]); break; case DataSource.TYPE_JENKINS: this.__startJenkins(this.dataSourceHandler.dataSources[i]); break; case DataSource.TYPE_SALES_FORCE: break; case DataSource.TYPE_INTERNAL: break; } } }; DataSourceManager.prototype.__startVersionOne = function(dataSource) { // iterate through each widget to see if the data source is in use if(this.widgetHandler === null) { return; } var teamNames = []; for(var i = 0; i < this.widgetHandler.widgets.length; i++) { if(this.widgetHandler.widgets[i].dataSourceId === dataSource.id && this.widgetHandler.widgets[i].keyDataElement.length > 0 && teamNames.indexOf(this.widgetHandler.widgets[i].keyDataElement) < 0) { teamNames.push(this.widgetHandler.widgets[i].keyDataElement); } } for(i = 0; i < teamNames.length; i++) { this.dataSources[dataSource.id] = new VersionOne({ name: dataSource.name, timeZone: dataSource.timeZone, hostname: dataSource.hostname, instance: dataSource.instance, username: dataSource.username, password: dataSource.password, port: dataSource.port, protocol: dataSource.protocol, pollFrequencyMinutes: dataSource.pollFrequencyMinutes, teamName: teamNames[i] }); this.dataSources[dataSource.id].on(VersionOne.EVENT_SPRINT_DATA_RECEIVED, this._processAgileSprintDataReceived.bind(this)); this.dataSources[dataSource.id].startMonitor(VersionOne.ALL_MONITORS); } }; DataSourceManager.prototype.__startJenkins = function(dataSource) { // iterate through each widget to see if the data source is in use if(this.widgetHandler === null) { return; } var jenkinsName = []; for(var i = 0; i < this.widgetHandler.widgets.length; i++) { if(this.widgetHandler.widgets[i].dataSourceId === dataSource.id && this.widgetHandler.widgets[i].keyDataElement.length > 0 && jenkinsName.indexOf(this.widgetHandler.widgets[i].keyDataElement) < 0) { jenkinsName.push(this.widgetHandler.widgets[i].keyDataElement); } } for(i = 0; i < jenkinsName.length; i++) { this.dataSources[dataSource.id] = new Jenkins({ host: dataSource.hostname, name: jenkinsName[i], pollFrequencyMinutes: dataSource.pollFrequencyMinutes }); this.dataSources[dataSource.id].on(Jenkins.EVENT_DATA_RECEIVED, this.__processJenkinsDataReceived.bind(this)); this.dataSources[dataSource.id].startMonitor(); } }; DataSourceManager.prototype.stop = function() { if(this.dataSourceHandler === null) { return; } for(var dataSource in this.dataSources) { this.dataSources[dataSource].stopMonitor(); } this.dataSources = {}; }; DataSourceManager.prototype.add = function(dataSource) { }; DataSourceManager.prototype.remove = function(id) { if(this.dataSources[id] !== null && this.dataSources[id] !== undefined) { this.dataSources[id].stopMonitor(); // TODO: add remove logic } }; DataSourceManager.prototype.setupCommsListeners = function(comms) { comms.on(MeltingPot.Comms.NEW_CONNECTION_ACCEPTED, function (c) { // TODO: decide on action when connection accepted, possibly start polling at this time // comms.sendMessage(c, Panel.MESSAGE_PANELS, this.panels); // TODO: only sends to last connection, doesn't broardcast, is this correct behaviour? console.log("dataSourceManager, connection accepted"); var dataSourceKeys = Object.keys(this.dataSources); for(var i = 0; i < dataSourceKeys.length; i++) { console.log("\tprocess datasource " + dataSourceKeys[i]); } this.connection = c; }.bind(this)); }; DataSourceManager.prototype._processAgileSprintDataReceived = function(teamName, agileSprint) { if(this.connection !== null) { this.clientComms.sendMessage(this.connection, AgileSprint.MESSAGE_STATS, {keyDataElement: teamName, details: agileSprint}); } }; DataSourceManager.prototype.__processJenkinsDataReceived = function(name, data) { if(this.connection !== null) { this.clientComms.sendMessage(this.connection, JenkinsState.MESSAGE_STATS, {keyDataElement: name, details: data}); } };
JavaScript
0
@@ -5905,24 +5905,82 @@ taSources);%0A + console.log(%22dataSourceManager : %22 + dataSourceKeys);%0A %0A for @@ -6035,65 +6035,250 @@ -console.log(%22%5Ctprocess datasource %22 + dataSourceKeys%5Bi%5D); +if (this.dataSources%5BdataSourceKeys%5Bi%5D%5D instanceof VersionOne) %7B%0A console.log(%22%5Ctprocess datasource %22 + this.dataSources%5BdataSourceKeys%5Bi%5D%5D.sprintData);%0A %7D else if (this.dataSources%5BdataSourceKeys%5Bi%5D%5D instanceof Jenkins) %7B%0A %7D %0A
d54a3367ccf58d54e6e2ca9fda28a38416710006
remove alias'
generators/ng-route/index.js
generators/ng-route/index.js
'use strict'; var yeoman = require('yeoman-generator'), chalk = require('chalk'), yosay = require('yosay'), _ = require('lodash'), s = require('underscore.string'), fs = require('fs'), prompt = require('../../lib/option-or-prompt.js'); // TODO: Refactor to remove prompt logic since the cli handles it // now that generation code has been merged with the cli module.exports = yeoman.Base.extend({ _prompt: prompt, // The name `constructor` is important here constructor: function () { // Calling the super constructor is important so our generator is correctly set up yeoman.Base.apply(this, arguments); // This method adds support for a `--vulgarcli` flag this.option('vulgarcli', { type: Boolean, defaults: false, hide: true }); // This method adds support for a `--dest` flag this.option('dest', { type: String }); // This method adds support for a `--module` flag this.option('module', { type: String }); // This method adds support for a `--route-name` flag this.option('name', { type: String, alias:'n'}); // This method adds support for a `--route-path` flag this.option('path', { type: String, alias:'p'}); }, askForModuleName: function () { var done = this.async(); var modulesSource = 'src/'; var prompts = [{ type: 'list', name: 'module', default: 'app', message: 'Which module does this route belongs to?', choices: [] },{ type: 'input', name: 'name', message: 'What would you like to name this component?', default: '' }]; // Add module choices if (fs.existsSync(modulesSource)) { fs.readdirSync(modulesSource).forEach(function (folder) { var stat = fs.statSync(modulesSource + '/' + folder); if (stat.isDirectory() // Exclude the `assets` and `sass` directories && folder !== 'assets' && folder !== 'sass') { prompts[0].choices.push({ value: folder, name: folder }); } }); } // Use custom prompt function which skips the prompt if // an option has been passed in this._prompt(prompts, function(props) { this.props = props; // To access props later use this.props.someOption; this.moduleName = this.props.module; this.name = this.props.name || 'routable'; this.slugifiedName = s(this.name).humanize().slugify().value(); this.classifiedName = s(this.slugifiedName).classify().value(); this.humanizedName = s(this.slugifiedName).humanize().value(); this.camelizedName = s(this.slugifiedName).camelize().value(); this.decapitalizedName = s(this.name).humanize().decapitalize().value(); if (this.options.dest) { this.destination = this.options.dest; } else { this.destination = modulesSource + this.moduleName + '/' + this.decapitalizedName + '/'; } done(); }.bind(this)); }, askForRouteDetails: function() { var done = this.async(); this._prompt([{ type: 'input', name: 'path', message: 'What would you like the route path to be?', default: this.slugifiedName }], function(props) { this.props = props; // To access props later use this.props.someOption; this.path = this.props.path; this.slugifiedRoutePath = s(this.path).slugify().value(); done(); }.bind(this)); }, writing: function () { // For dummy test this.fs.copy( this.templatePath('dummyfile.txt'), this.destinationPath('dummyfile.txt') ); //** Generate `root` component this.fs.copyTpl( this.templatePath('components/_-root.component.ts'), this.destinationPath(this.destination + this.slugifiedName + '-root.component.ts'), { classifiedName: this.classifiedName, routePath: this.path, humanizedName: this.humanizedName, slugifiedName: this.slugifiedName } ); //** Generate `list` component this.fs.copyTpl( this.templatePath('components/list/_-list.component.ts'), this.destinationPath(this.destination + this.slugifiedName + '-list.component.ts'), { classifiedName: this.classifiedName, humanizedName: this.humanizedName, slugifiedName: this.slugifiedName, camelizedName: this.camelizedName } ); //** Generate `list` unit test this.fs.copyTpl( this.templatePath('components/list/_-list.component.spec.ts'), this.destinationPath(this.destination + this.slugifiedName + '-list.component.spec.ts'), { classifiedName: this.classifiedName, humanizedName: this.humanizedName, slugifiedName: this.slugifiedName } ); //** Generate `list` template this.fs.copyTpl( this.templatePath('components/list/_-list.component.html'), this.destinationPath(this.destination + this.slugifiedName + '-list.component.html'), { classifiedName: this.classifiedName, camelizedName: this.camelizedName } ); //** Generate `list` styles this.fs.copy( this.templatePath('components/list/_-list.component.scss'), this.destinationPath(this.destination + this.slugifiedName + '-list.component.scss') ); //** Generate `detail` component this.fs.copyTpl( this.templatePath('components/detail/_-detail.component.ts'), this.destinationPath(this.destination + this.slugifiedName + '-detail.component.ts'), { classifiedName: this.classifiedName, humanizedName: this.humanizedName, slugifiedName: this.slugifiedName, camelizedName: this.camelizedName } ); //** Generate `detail` unit test this.fs.copyTpl( this.templatePath('components/detail/_-detail.component.spec.ts'), this.destinationPath(this.destination + this.slugifiedName + '-detail.component.spec.ts'), { classifiedName: this.classifiedName, humanizedName: this.humanizedName, slugifiedName: this.slugifiedName } ); //** Generate `detail` template this.fs.copyTpl( this.templatePath('components/detail/_-detail.component.html'), this.destinationPath(this.destination + this.slugifiedName + '-detail.component.html'), { classifiedName: this.classifiedName, camelizedName: this.camelizedName } ); //** Generate `detail` styles this.fs.copy( this.templatePath('components/detail/_-detail.component.scss'), this.destinationPath(this.destination + this.slugifiedName + '-detail.component.scss') ); //** Generate `Angular` service this.fs.copyTpl( this.templatePath('services/_.service.ts'), this.destinationPath(this.destination + this.slugifiedName + '.service.ts'), { classifiedName: this.classifiedName } ); //** Generate `Angular` service unit test this.fs.copyTpl( this.templatePath('services/_.service.spec.ts'), this.destinationPath(this.destination + this.slugifiedName + '.service.spec.ts'), { classifiedName: this.classifiedName, slugifiedName: this.slugifiedName, humanizedName: this.humanizedName, camelizedName: this.camelizedName } ); }, end: function() { if(!this.options.vulgarcli) { // Terminate process if run from console process.exit(0); } else if(this.options.vulgarcli === true) { // `return 0` to let `vulgar-cli` know everything went okay on our end return 0; } } });
JavaScript
0
@@ -1093,19 +1093,9 @@ ring -, alias:'n' + %7D);%0A @@ -1195,19 +1195,9 @@ ring -, alias:'p' + %7D);%0A
b6c8f35299937fed37dbd7509eb1fdb92c46b81f
Refactor isRunning
lib/spotify-node-applescript.js
lib/spotify-node-applescript.js
var exec = require('child_process').exec, applescript = require('applescript'); // apple scripts var scripts = { state: [ 'tell application "Spotify"', 'set cstate to "{"', 'set cstate to cstate & "\\"volume\\": " & sound volume', 'set cstate to cstate & ",\\"position\\": \\"" & player position & "\\""', 'set cstate to cstate & ",\\"state\\": \\"" & player state & "\\""', 'set cstate to cstate & "}"', 'return cstate', 'end tell' ], volumeUp : [ 'tell application "Spotify" to set sound volume to (sound volume + 10)' ], volumeDown : [ 'tell application "Spotify" to set sound volume to (sound volume - 10)' ], setVolume : [ 'tell application "Spotify" to set sound volume to {{volume}}' ], play : [ 'tell application "Spotify" to play' ], playTrack : [ 'tell application "Spotify" to play track "{{track}}"' ], playPause : [ 'tell application "Spotify" to playpause' ], pause : [ 'tell application "Spotify" to pause' ], next : [ 'tell application "Spotify" to next track' ], previous : [ 'tell application "Spotify" to previous track' ], jumpTo : [ 'tell application "Spotify" to set player position to {{position}}' ], isRunning: [ 'tell application "System Events"', 'set ProcessList to name of every process', 'return "Spotify" is in ProcessList', 'end tell' ] }; var execScript = function(script, callback, transformer){ if (!callback) return null; script = scripts[script].join('\n'); if (transformer) script = transformer(script); applescript.execString(script, callback); }; var createJSONResponseHandler = function(callback){ if (!callback) return null; return function(error, result){ if (!error){ try { result = JSON.parse(result); } catch(e){ return callback(e); } return callback(null, result); } else { return callback(error); } }; }; exports.isRunning = function(callback) { execScript('isRunning', function(error, response) { if (!error) { return callback(null, response === 'true' ? true : false); } else { return callback(error); } }); }; exports.open = function(uri, callback){ return exec('open "'+uri+'"', callback); }; exports.play = function(callback){ execScript('play', callback); }; exports.playTrack = function(track, callback){ execScript('playTrack', callback, function(script){ return script.replace('{{track}}', track); }); }; exports.pause = function(callback){ return execScript('pause', callback); }; exports.playPause = function(callback){ return execScript('playPause', callback); }; exports.next = function(callback){ return execScript('next', callback); }; exports.previous = function(callback){ return execScript('previous', callback); }; exports.volumeUp = function(callback){ return execScript('volumeUp', callback); }; exports.volumeDown = function(callback){ return execScript('volumeDown', callback); }; exports.setVolume = function(volume, callback){ execScript('setVolume', callback, function(script){ return script.replace('{{volume}}', volume); }); }; exports.getTrack = function(callback){ return applescript.execFile( __dirname + '/scripts/get_track.applescript', createJSONResponseHandler(callback) ); }; exports.getState = function(callback){ return execScript('state', createJSONResponseHandler(callback)); }; exports.jumpTo = function(position, callback){ execScript('jumpTo', callback, function(script){ return script.replace('{{position}}', position); }); }; exports.getArtwork = function(callback){ return applescript.execFile(__dirname + '/scripts/get_artwork.applescript', callback); };
JavaScript
0.000025
@@ -1355,17 +1355,16 @@ %0A %5D,%0A -%0A isRu @@ -1385,158 +1385,44 @@ ' -tell application %22System Events%22',%0A 'set ProcessList to name of every process',%0A 'return %22Spotify%22 is in ProcessList',%0A 'end tell +get running of application %22Spotify%22 '%0A
01ab7b9b5c7722bacdbb2c782c1de2ae255ff9ff
refactor BaseServer.formatJsonError to help unit test
src/BaseServer.js
src/BaseServer.js
const Koa = require('koa'); const BaseError = require('./error/BaseError'); const Errors = require('./error/Errors'); const koaLogger = require('koa-logger'); const koaBody = require('koa-body'); const Http = require('http'); const CreateKoaRouter = require('koa-router'); class BaseServer { init() { this._initKoa(); this._start(); } _initKoa() { const koa = new Koa(); koa.use(this.formatJsonError.bind(this)); koa.use(koaLogger()); koa.use(koaBody({ jsonLimit: this._config.bodySizeLimit || '1kb' })); this._koa = koa; this._koaRouter = CreateKoaRouter(); } formatJsonError(ctx, next) { return next().catch(err => { this._logger.error(err); if (err instanceof BaseError) { ctx.body = err.build(); //TODO: locale ctx.status = (err.errorType === Errors.INTERNAL_ERROR) ? 500 : 400; } else { //TODO: other error such as 404 ctx.body = BaseError.staticBuild(Errors.INTERNAL_ERROR, err.message); //TODO: locale ctx.status = 500; } // Emit the error if we really care //ctx.app.emit('error', err, ctx); }); } _start() { this._logger.debug('starting %s server', this._name); this._starting(); const port = this._config.port; if (!port) throw new Error(`port NOT specified for ${this._name}`); Http.createServer(this._koa.callback()).listen(port); this._logger.info('%s server listening on %s', this._name, port); } _starting() { throw new Error('TODO'); } } module.exports = BaseServer;
JavaScript
0.000002
@@ -420,16 +420,53 @@ koa.use( + (ctx, next) =%3E next().catch( err =%3E this.for @@ -481,19 +481,20 @@ rror -.bind(this) +(ctx, err)) );%0A @@ -646,16 +646,25 @@ = koa;%0A + %0A @@ -736,65 +736,23 @@ tx, -next) %7B%0A return next().catch(err =%3E %7B%0A%0A +err) %7B%0A thi @@ -743,25 +743,24 @@ ) %7B%0A - this._logger @@ -769,28 +769,24 @@ rror(err);%0A%0A - if ( @@ -817,36 +817,32 @@ ) %7B%0A - - ctx.body = err.b @@ -856,36 +856,32 @@ //TODO: locale%0A - ctx. @@ -952,20 +952,16 @@ - %7D else %7B @@ -973,20 +973,16 @@ - - //TODO: @@ -1005,20 +1005,16 @@ as 404%0A - @@ -1106,36 +1106,32 @@ ale%0A - ctx.status = 500 @@ -1140,27 +1140,19 @@ - - %7D%0A%0A +%7D%0A%0A @@ -1195,20 +1195,16 @@ - //ctx.ap @@ -1234,20 +1234,8 @@ x);%0A - %7D);%0A
a2582e1e999c0c9d8fce3c3124d972234328514e
Add test to prove value bug
spec/FakeModuleSpec.js
spec/FakeModuleSpec.js
describe("FakeModule", function () { var FakeModule = require('../lib/FakeModule'); var angular; var module; beforeEach(function() { angular = { modules: {}, factories: {}, instances: {}, values: {} }; module = new FakeModule(angular, 'ngApp.testModule', []); }); describe('config', function () { it('should store and return the config callback', function () { var success = false; module.config(function () { success = true; }); module.config()(); expect(success).toBe(true); }); }); describe('factories', function () { it('should fail to create a non-existent factory', function () { var fail = function () { module.factory('does-not-exist'); }; expect(fail).toThrowError('No such factory: does-not-exist'); }); it('should fail to overwrite a factory', function () { var fail = function () { module.factory('factory', function () {}); module.factory('factory', function () {}); }; expect(fail).toThrowError('Attempt to overwrite factory: factory'); }); it('should create simple factories', function () { module.factory('factory', function () { return { name: 'factory' }; }); var first = module.factory('factory'); var second = module.factory('factory'); expect(second).toBe(first); }); it('should create simple factories with dependencies', function () { module.factory('$factory0', function () { return { name: '$factory0' }; }); module.factory('factory1', function ($factory0) { return { name: 'factory1', dependencies: [ $factory0 ] }; }); module.factory('factory2', function ($factory0, factory1) { return { name: 'factory2', dependencies: [ $factory0, factory1 ] }; }); var first = module.factory('factory2'); var second = module.factory('factory2'); var factory0 = module.factory('$factory0'); var factory1 = module.factory('factory1'); expect(second).toBe(first); expect(second.dependencies[0]).toBe(factory0); expect(second.dependencies[1]).toBe(factory1); }); it('should support $inject dependencies', function () { module.factory('$factory0', function () { return { name: '$factory0' }; }); var factory1 = function ($factory0) { return { name: 'factory1', dependencies: [ $factory0 ] }; }; factory1.$inject = ['$factory0']; module.factory('factory1', factory1); var first = module.factory('$factory0'); var second = module.factory('factory1'); expect(second.dependencies[0]).toBe(first); }); it('should create array factories', function () { module.factory('factory', [function () { return { name: 'factory' }; }]); var first = module.factory('factory'); var second = module.factory('factory'); expect(second).toBe(first); }); it('should create array factories with dependencies', function () { module.factory('factory1', [function () { return { name: 'factory1' }; }]); module.factory('factory2', ['factory1', function (factory1) { return { name: 'factory2', dependencies: [ factory1 ] }; }]); var first = module.factory('factory2'); var second = module.factory('factory2'); var factory1 = module.factory('factory1'); expect(second).toBe(first); expect(second.dependencies[0]).toBe(factory1); }); it('should die with circular dependencies', function () { module.factory('factory1', ['factory2', function (factory2) { return { name: 'factory1' }; }]); module.factory('factory2', ['factory1', function (factory1) { return { name: 'factory2' }; }]); var fail = function () { module.factory('factory1'); }; expect(fail).toThrowError('Circular dependency: factory1 <- factory2 <- factory1'); }); }); describe('values', function () { it('should fail to return a non-existent value', function () { var fail = function () { module.value('does-not-exist'); }; expect(fail).toThrowError('No such value: does-not-exist'); }); it('should support set and get for values', function () { var MyValue = { NAME: 'name' }; module.value('MyValue', MyValue); expect(module.value('MyValue')).toBe(MyValue); }); it ('should not allow values to be overwritten', function () { module.value('exists', true); var fail = function () { module.value('exists', 1); }; expect(fail).toThrowError('Attempt to overwrite value: exists'); }); }); });
JavaScript
0
@@ -5037,23 +5037,464 @@ s');%0A %7D); +%0A%0A it('should resolve values as dependencies', function () %7B%0A // Define an object so we know we got the same isntance back.%0A var value = %7B key: true %7D;%0A%0A // Define value and factory that depends on it.%0A module.value('MyValue', value);%0A module.factory('factory1', %5B'MyValue', function (MyValue) %7B%0A expect(MyValue).toBe(value);%0A %7D%5D);%0A%0A // Load the factory.%0A module.factory('factory1');%0A %7D); %0A %7D);%0A%7D);%0A
8d6e0a6fbcfff77dd4bc8b1cf5725ca79da86e3b
Fix demo notes - remove console.log
src/Oro/Bundle/FilterBundle/Resources/public/js/datafilter-builder.js
src/Oro/Bundle/FilterBundle/Resources/public/js/datafilter-builder.js
/*jshint browser:true*/ /*jslint nomen: true*/ /*global define, require*/ define(['jquery', 'underscore', 'oro/tools', 'oro/mediator', 'orofilter/js/map-filter-module-name', 'oro/datafilter/collection-filters-manager'], function ($, _, tools, mediator, mapFilterModuleName, FiltersManager) { 'use strict'; var initialized = false, methods = { initBuilder: function () { this.metadata = _.extend({state: {filters: []}, filters: {}}, this.$el.data('metadata')); console.log(this.metadata); this.modules = {}; methods.collectModules.call(this); tools.loadModules(this.modules, _.bind(methods.build, this)); }, /** * Collects required modules */ collectModules: function () { var modules = this.modules; _.each(this.metadata.filters || {}, function (filter) { var type = filter.type; modules[type] = mapFilterModuleName(type); }); }, build: function () { var options = methods.combineOptions.call(this); options.collection = this.collection; var filtersList = new FiltersManager(options); this.$el.prepend(filtersList.render().$el); mediator.trigger('datagrid_filters:rendered', this.collection); if (this.collection.length === 0 && this.metadata.state.filters.length === 0) { filtersList.$el.hide(); } }, /** * Process metadata and combines options for filters * * @returns {Object} */ combineOptions: function () { var filters= {}, modules = this.modules, collection = this.collection; _.each(this.metadata.filters, function (options) { if (_.has(options, 'name') && _.has(options, 'type')) { // @TODO pass collection only for specific filters if (options.type == 'selectrow') { options.collection = collection } var Filter = modules[options.type].extend(options); filters[options.name] = new Filter(); } }); return {filters: filters}; } }, initHandler = function (collection, $el) { methods.initBuilder.call({$el: $el, collection: collection}); initialized = true; }; return { init: function () { initialized = false; mediator.once('datagrid_collection_set_after', initHandler); mediator.once('hash_navigation_request:start', function() { if (!initialized) { mediator.off('datagrid_collection_set_after', initHandler); } }); } }; });
JavaScript
0
@@ -507,52 +507,8 @@ ));%0A - console.log(this.metadata);%0A
d01276f888a3069bf5460f24a4cb97b24368abb4
Enable passing className to component
src/Codemirror.js
src/Codemirror.js
var CM = require('codemirror'); var React = require('react'); var CodeMirror = React.createClass({ propTypes: { onChange: React.PropTypes.func, onFocusChange: React.PropTypes.func, options: React.PropTypes.object, path: React.PropTypes.string, value: React.PropTypes.string }, getInitialState () { return { isFocused: false }; }, componentDidMount () { var textareaNode = this.refs.textarea; this.codeMirror = CM.fromTextArea(textareaNode, this.props.options); this.codeMirror.on('change', this.codemirrorValueChanged); this.codeMirror.on('focus', this.focusChanged.bind(this, true)); this.codeMirror.on('blur', this.focusChanged.bind(this, false)); this._currentCodemirrorValue = this.props.value; this.codeMirror.setValue(this.props.value); }, componentWillUnmount () { // todo: is there a lighter-weight way to remove the cm instance? if (this.codeMirror) { this.codeMirror.toTextArea(); } }, componentWillReceiveProps (nextProps) { if (this.codeMirror && this._currentCodemirrorValue !== nextProps.value) { this.codeMirror.setValue(nextProps.value); } if (typeof nextProps.options === 'object') { for (var optionName in nextProps.options) { if (nextProps.options.hasOwnProperty(optionName)) { this.codeMirror.setOption(optionName, nextProps.options[optionName]); } } } }, getCodeMirror () { return this.codeMirror; }, focus () { if (this.codeMirror) { this.codeMirror.focus(); } }, focusChanged (focused) { this.setState({ isFocused: focused }); this.props.onFocusChange && this.props.onFocusChange(focused); }, codemirrorValueChanged (doc, change) { var newValue = doc.getValue(); this._currentCodemirrorValue = newValue; this.props.onChange && this.props.onChange(newValue); }, render () { var className = 'ReactCodeMirror'; if (this.state.isFocused) { className += ' ReactCodeMirror--focused'; } return ( <div className={className}> <textarea ref="textarea" name={this.props.path} defaultValue={''} autoComplete="off" /> </div> ); } }); module.exports = CodeMirror;
JavaScript
0.000001
@@ -54,16 +54,55 @@ react'); +%0Avar className = require('classnames'); %0A%0Avar Co @@ -318,16 +318,51 @@ s.string +,%0A%09%09className: React.PropTypes.any, %0A%09%7D,%0A%0A%09g @@ -1889,25 +1889,31 @@ () %7B%0A%09%09var -c +editorC lassName = ' @@ -1911,16 +1911,26 @@ sName = +className( 'ReactCo @@ -1938,17 +1938,41 @@ eMirror' -; +, this.props.className);%0A %0A%09%09if (t @@ -2073,17 +2073,23 @@ ssName=%7B -c +editorC lassName
e8492751405e3bbe0786a520e5e8a8d216fbd051
fix scope issue
core/js/directives/csBgImage.js
core/js/directives/csBgImage.js
/************************************************** * BGImage Directive * * Background images * **************************************************/ angular.module('cosmo').directive('csBgImage', ['Page', '$rootScope', 'Users', 'Responsive', 'Hooks', function(Page, $rootScope, Users, Responsive, Hooks) { return { link: function(scope, elm, attrs, ctrl) { function updateBGImage(){ if(Page.extras[attrs.csBgImage]){ Page.extras[attrs.csBgImage] = angular.fromJson(Page.extras[attrs.csBgImage]); if(Page.extras[attrs.csBgImage].responsive === 'yes') var imageURL = Hooks.imageHookNotify(Responsive.resize(Page.extras[attrs.csBgImage].src, Page.extras[attrs.csBgImage].size)); else var imageURL = Hooks.imageHookNotify(Page.extras[attrs.csBgImage].src); elm.css('background-image', 'url('+ imageURL +')'); } else if(Users.admin) elm.css('background-image', 'url(core/img/image.svg)'); } updateBGImage(); scope.$on('contentGet', function(){ updateBGImage(); }); // Check if user is an admin if(Users.admin) { // Double click image to edit elm.on('dblclick', function(){ $rootScope.$broadcast('editFiles', angular.toJson({ id: attrs.csBgImage, data: imageURL }) ); }); // Update page when another image is chosen scope.$on('choseFile', function(event, data){ if(data.id === attrs.csBgImage){ Page.extras[attrs.csBgImage] = data; elm.css('background-image', 'url('+ data.src +')'); } }); } } }; }]);
JavaScript
0
@@ -424,16 +424,43 @@ trl) %7B%0A%0A + var imageURL;%0A%0A
5eb2bbee8fc977aecb486e88ae602053604a52f6
allow mutliple 'filter' clauses in bool query
core/js/elastic/queries/bool.js
core/js/elastic/queries/bool.js
// Bool query function BoolQuery() { var _must = [], _mustNot = [], _should = [], _filter, _minimumMatches, _boost; this.getType = function() { return 'query'; }; this.getInfo = function() { return { 'name': 'Bool Query', 'text': 'The bool query is used to apply multiple queries', 'url': 'https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html', 'form': { 'minimum matches': { 'type': 'text', 'required': false, 'value': _minimumMatches }, 'boost': { 'type': 'text', 'required': false, 'value': _boost } } }; }; this.updateField = function(name, value) { switch(name) { case 'minimum matches': _minimumMatches = value; break; case 'boost': _boost = value; break; } }; this.addMust = function(query) { _must.push(query); }; this.removeMust = function(query) { var index = _must.indexOf(query); if (index > -1) { _must.splice(index, 1); } }; this.addMustNot = function(query) { _mustNot.push(query); }; this.removeMustNot = function(query) { var index = _mustNot.indexOf(query); if (index > -1) { _mustNot.splice(index, 1); } }; this.addShould = function(query) { _should.push(query); }; this.removeShould = function(query) { var index = _should.indexOf(query); if (index > -1) { _should.splice(index, 1); } }; this.addNesting = function(name, part) { switch(name) { case 'must': this.addMust(part); break; case 'mustNot': this.addMustNot(part); break; case 'should': this.addShould(part); break; case 'filter': _filter = part; break; } }; this.removeNesting = function(name, part) { switch(name) { case 'must': this.removeMust(part); break; case 'mustNot': this.removeMustNot(part); break; case 'should': this.removeShould(part); break; case 'filter': _filter = undefined; break; } }; this.getNestings = function() { return { 'must': { 'type': 'query', 'multiple': true }, 'mustNot': { 'type': 'query', 'multiple': true }, 'should': { 'type': 'query', 'multiple': true }, 'filter': { 'type': 'query', 'multiple': false } }; }; this.isSetUp = function() { return _must.length || _mustNot.length || _should.length || _filter; }; this.canRun = function() { var allOk = this.isSetUp(); if (allOk) { $.each(_must, function(i, query) { if (!query.canRun()) { allOk = false; return false; } }); } if (allOk) { $.each(_mustNot, function(i, query) { if (!query.canRun()) { allOk = false; return false; } }); } if (allOk) { $.each(_should, function(i, query) { if (!query.canRun()) { allOk = false; return false; } }); } if (allOk && _filter) { _filter.canRun(); } return allOk; }; this.toJson = function() { var jsonObject = { "bool": {} }; if (_must.length) { if (_must.length == 1) { jsonObject.bool.must = _must[0].toJson(); } else { jsonObject.bool.must = []; for (var i = 0; i < _must.length; i++) { jsonObject.bool.must.push( _must[ i ].toJson() ); } } } if (_mustNot.length) { if (_mustNot.length == 1) { jsonObject.bool.must_not = _mustNot[0].toJson(); } else { jsonObject.bool.must_not = []; for (var i = 0; i < _mustNot.length; i++) { jsonObject.bool.must_not.push( _mustNot[ i ].toJson() ); } } } if (_should.length) { if (_should.length == 1) { jsonObject.bool.should = _should[0].toJson(); } else { jsonObject.bool.should = []; for (var i = 0; i < _should.length; i++) { jsonObject.bool.should.push( _should[ i ].toJson() ); } } } if (_filter) { jsonObject.bool.filter = _filter.toJson(); } if (typeof(_minimumMatches) != 'undefined') { jsonObject.bool.minimum_should_match = _minimumMatches; } if (_boost) { jsonObject.bool.boost = _boost; } return jsonObject; } }
JavaScript
0.000024
@@ -2276,20 +2276,19 @@ tiple': -fals +tru e%0A%09%09%09%7D%0A%09
96223d1721e99d76508744e660bff7ac2dffdf96
Fix glob pattern to avoid matching directories (#175)
lib/install/config/shared.js
lib/install/config/shared.js
// Note: You must restart bin/webpack-watcher for changes to take effect const webpack = require('webpack') const path = require('path') const process = require('process') const glob = require('glob') const extname = require('path-complete-extname') let distDir = process.env.WEBPACK_DIST_DIR if (distDir === undefined) { distDir = 'packs' } const extensions = ['.js', '.coffee'] const extensionGlob = `*(${extensions.join('|')})*` const packPaths = glob.sync(path.join('app', 'javascript', 'packs', extensionGlob)) const config = { entry: packPaths.reduce( (map, entry) => { const basename = path.basename(entry, extname(entry)) const localMap = map localMap[basename] = path.resolve(entry) return localMap }, {} ), output: { filename: '[name].js', path: path.resolve('public', distDir) }, module: { rules: [ { test: /\.coffee(\.erb)?$/, loader: 'coffee-loader' }, { test: /\.js(\.erb)?$/, exclude: /node_modules/, loader: 'babel-loader', options: { presets: [ ['env', { modules: false }] ] } }, { test: /\.erb$/, enforce: 'pre', exclude: /node_modules/, loader: 'rails-erb-loader', options: { runner: 'DISABLE_SPRING=1 bin/rails runner' } } ] }, plugins: [ new webpack.EnvironmentPlugin(Object.keys(process.env)) ], resolve: { extensions, modules: [ path.resolve('app/javascript'), path.resolve('node_modules') ] }, resolveLoader: { modules: [path.resolve('node_modules')] } } module.exports = { distDir, config }
JavaScript
0
@@ -403,17 +403,17 @@ lob = %60* -( +%7B $%7Bextens @@ -427,13 +427,13 @@ in(' -%7C')%7D) +,')%7D%7D *%60%0Ac
0d96b9c0fb0d2211c2bcf2f2c145a262781ccb9e
Mark covid update link type as non-optional
source/views/covid/types.js
source/views/covid/types.js
// @flow export type UpdateType = { authors: string[], categories: string[], content: string, datePublished: ?string, excerpt: string, featuredImage: ?string, link: ?string, title: string, }
JavaScript
0.000172
@@ -166,17 +166,16 @@ %0A%09link: -? string,%0A
d9acf1fb9884c93401dca30ad75c285f0ee899f0
Revert "Run globallyUpdateMember synchronously"
src/DiscordBot.js
src/DiscordBot.js
const path = require('path') const Discord = require('discord.js-commando') const request = require('request-promise') const config = require('./data/client.json') const DiscordServer = require('./DiscordServer') module.exports = // The main Discord bot class, only one per shard. class DiscordBot { constructor() { this.initialize(); this.servers = {}; } // Initialize the bot, hook up events, and log in. initialize() { this.bot = new Discord.Client({ shardId: parseInt(process.env.SHARD_ID, 10), shardCount: parseInt(process.env.SHARD_COUNT, 10), apiRequestMethod: config.apiRequestMethod || 'sequential', disabledEvents: ['TYPING_START', 'VOICE_STATE_UPDATE', 'PRESENCE_UPDATE', 'MESSAGE_DELETE', 'MESSAGE_UPDATE'], owner: config.owner || '0', commandPrefix: config.commandPrefix || '!', unknownCommandResponse: false }); // Set a reference to this instance inside of the client // for use in Commando modules. Is this bad? Probably. this.bot.discordBot = this; // Events // We use .bind(this) so that the context remains within // the class and not the event. this.bot.on("ready", this.ready.bind(this)); this.bot.on("guildMemberAdd", this.guildMemberAdd.bind(this)); if (config.loud) this.bot.on("error", (message) => console.log(message)); // Only hook up if lockNicknames mode is enabled. if (config.lockNicknames) { this.bot.on("message", this.message.bind(this)); } // Register commands this.bot.registry .registerGroup('rover', 'RoVer') .registerDefaultTypes() .registerDefaultGroups() .registerDefaultCommands({ ping: false, commandState: false, prefix: false, help: false }) .registerCommandsIn(path.join(__dirname, 'commands')); // Login. this.bot.login(process.env.CLIENT_TOKEN); } // Called when the bot is ready and has logged in. ready() { console.log(`Shard ${process.env.SHARD_ID} is ready, serving ${this.bot.guilds.array().length} guilds.`); this.bot.user.setGame("http://eryn.io/RoVer"); } // This method is called when a user sends a message, but it's used // for setting their nickname back to what it should be if they've // changed it. Only active if lockNicknames is true in config. async message(message) { // Don't want to do anything if this is a DM or message was sent by the bot itself. if (!message.guild || message.author.id === this.bot.user.id) { return; } // We call discordMember.verify but we want to retain the cache // and we don't want it to post any announcements. let server = await this.getServer(message.guild.id); let member = await server.getMember(message.author.id); await member.verify({ announce: false, clearBindingsCache: false }); } // This is called when a user joins any Discord server. async guildMemberAdd(member) { let server = await this.getServer(member.guild.id); let action = await (await server.getMember(member.id)).verify(); if (action.status) { member.send(server.getWelcomeMessage(action)); } else { member.send("Welcome! Visit the following link to verify your Roblox account: https://verify.eryn.io"); } } // This is used to get the DiscordServer instance associated // with the specific guild id. async getServer(id) { if (!this.servers[id]) { this.servers[id] = new DiscordServer(this, id); await this.servers[id].loadSettings(); } return this.servers[id]; } // This is called by the update server when a user verifies // online. It updates the member in every DiscordServer they // are in. async globallyUpdateMember(id) { // Start off by clearing their global cache. DiscordServer.clearMemberCache(id); let firstRun = true; // Iterate through all of the guilds the bot is in. for (let guild of this.bot.guilds.array()) { let server = await this.getServer(guild.id); if (true) { // This only runs on the first iteration. We do this so that // we have time to cache the user information, so it only // sends out the request once. console.log(server.id); let action = await (await server.getMember(id)).verify({ // We want to clear the group rank bindings cache because // this is the first iteration. clearBindingsCache: firstRun, announce: false }); if (!action.status && !action.nonFatal) { // If there's a fatal error, don't continue with the rest. break; } else if (server.hasCustomWelcomeMessage()) { // It worked, checking if there's a custom welcome message. await this.bot.fetchUser(id); let member = await this.bot.guilds.get(guild.id).fetchMember(id); member.send(server.getWelcomeMessage(action)); } } else { // This is for all bit the first iteration. // We define an inline function and call it with the current // context so that we can run these commands synchronously // but still execute the requests all at the same time. (async function(){ try { let action = await (await server.getMember(id)).verify({ clearBindingsCache: false, announce: false }); if (action.status && server.hasCustomWelcomeMessage()) { await this.bot.fetchUser(id); let member = await this.bot.guilds.get(guild.id).fetchMember(id); member.send(server.getWelcomeMessage(action)); } } catch (e) { // Do nothing } }).apply(this); } firstRun = false; } } }
JavaScript
0
@@ -4491,20 +4491,24 @@ if ( -true +firstRun ) %7B%0A @@ -4707,49 +4707,8 @@ . %0A%0A - console.log(server.id);%0A%0A @@ -4946,24 +4946,20 @@ sCache: -firstRun +true ,%0A @@ -5903,38 +5903,8 @@ ()%7B%0A - try %7B%0A @@ -5992,36 +5992,32 @@ - clearBindingsCac @@ -6043,36 +6043,32 @@ - announce: false%0A @@ -6083,37 +6083,29 @@ - - %7D);%0A%0A - @@ -6161,36 +6161,32 @@ omeMessage()) %7B%0A - @@ -6243,33 +6243,25 @@ - %0A +%0A @@ -6354,36 +6354,32 @@ - - member.send(serv @@ -6413,106 +6413,8 @@ ));%0A - %7D%0A %7D catch (e) %7B%0A // Do nothing%0A
1b2a31964345d0481d43cdd3028f9c4b484364cc
use escaped line returns in docker regex escape
lib/manager/docker/update.js
lib/manager/docker/update.js
module.exports = { setNewValue, }; function setNewValue(currentFileContent, upgrade) { try { logger.debug(`setNewValue: ${upgrade.newFrom}`); const oldLine = new RegExp( `(^|\n)${upgrade.fromPrefix}(\\s+)${upgrade.depName}.*?(\\s?)${ upgrade.fromSuffix }\n` ); let newLine = `$1${upgrade.fromPrefix}$2${upgrade.newFrom}$3`; if (upgrade.fromSuffix.length) { newLine += `${upgrade.fromSuffix}`; } newLine += '\n'; const newFileContent = currentFileContent.replace(oldLine, newLine); return newFileContent; } catch (err) { logger.info({ err }, 'Error setting new Dockerfile value'); return null; } }
JavaScript
0.000009
@@ -187,16 +187,17 @@ %60(%5E%7C%5C +%5C n)$%7Bupgr @@ -239,11 +239,15 @@ ame%7D -.*? +%5B%5E%5C%5Cs%5D* (%5C%5Cs @@ -286,16 +286,17 @@ %7D%5C +%5C n%60%0A )
70a81486637b108d84944666c982a37485c10a6c
Use lodash _.endsWith function
lib/middleware/app-loader.js
lib/middleware/app-loader.js
var _ = require('lodash'); var async = require('async'); var publicSuffixList = require('psl'); var debug = require('debug')('4front:http-host:app-loader'); require('simple-errors'); exports = module.exports = function(settings) { return function(req, res, next) { debug('virtualAppLoader middleware'); if (_.isEmpty(req.hostname)) { return next(Error.http(404, 'Missing Host header')); } req.ext.virtualHost = req.hostname.toLowerCase(); // Check if request is using the shared virtual hostname. var loadFunc = req.ext.virtualHost.endsWith(settings.virtualHost) ? loadFromSharedDomain : loadFromCustomDomain; loadFunc(req, function(err, virtualApp) { if (err) { return next(err); } debug('virtualHost=%s virtualEnv=%s', req.ext.virtualHost, req.ext.virtualEnv); if (!virtualApp) { // TODO: Redirect logic. debug('virtual app %s not found', req.ext.virtualHost); return next(Error.http(404, 'Virtual application ' + req.ext.virtualHost + ' not found')); } // If this app requires SSL and this request is not secure, then redirect to the https // equivalent. if (virtualApp.requireSsl === true) { debug('app must be requested via SSL'); if (req.secure !== true) { var redirectUrl = 'https://' + req.hostname; if (req.url !== '/') { redirectUrl += req.url; } res.set('Cache-Control', 'no-cache'); return res.redirect(302, redirectUrl); } } // Get the environment variables specific to this virtual environment. // First take the global values and override with environment specific // values. if (_.isObject(virtualApp.env)) { req.ext.env = _.extend({}, virtualApp.env._global || {}, virtualApp.env[req.ext.virtualEnv] || {}); // Now that we have the environment variables delete virtualApp.env; } else { req.ext.env = {}; } // Store the app in the req object for subsequent middleware req.ext.virtualApp = virtualApp; // If this app belongs to an org, store the orgId on the extended request. if (virtualApp.orgId) { debug('orgId=%s', virtualApp.orgId); req.ext.orgId = virtualApp.orgId; } // Set a custom virtual-app-id header res.set('virtual-app-id', virtualApp.appId); debug('current virtual application is ' + virtualApp.appId); next(); }); }; function loadFromSharedDomain(req, callback) { // The app name is assumed to be the first part of the vhost, i.e. appname.virtualhost.com. var appName = req.ext.virtualHost.split('.')[0]; if (appName.indexOf('--') !== -1) { var parts = appName.split('--'); appName = parts[0]; req.ext.virtualEnv = parts[1]; req.ext.virtualHost = appName + '.' + settings.virtualHost; } else { req.ext.virtualEnv = settings.defaultVirtualEnvironment; } debug('find app by name %s', appName); settings.virtualAppRegistry.getByName(appName, callback); } function loadFromCustomDomain(req, callback) { var parsedDomain = publicSuffixList.parse(req.ext.virtualHost); var domainName = parsedDomain.domain; var subDomain = parsedDomain.subdomain || '@'; // If this is an apex domain, then it must be production env. if (subDomain === '@') { req.ext.apexDomain = true; req.ext.virtualEnv = settings.defaultVirtualEnvironment; return settings.virtualAppRegistry.getByDomain(domainName, '@', callback); } // If the subDomain contains "--" then it must be an app with a subDomain // and a virtualEnv like subdomain--test.domain.com. if (subDomain.indexOf('--') !== -1) { var parts = subDomain.split('--'); req.ext.virtualEnv = parts[1]; subDomain = parts[0]; req.ext.virtualHost = parts[0] + '.' + domainName; return settings.virtualAppRegistry.getByDomain(domainName, subDomain, callback); } // Tricky scenario is if there is a sub-domain without --. This could indicate either // an app with a subDomain or an apex domain where the subdomain is the virtualEnv, i.e. // test.domain.com. test.domain.com could be the production host for a website or 'test' // could be a virtual environment of domain.com. The production host, if it exists, takes // precedence. async.waterfall([ function(cb) { settings.virtualAppRegistry.getByDomain(domainName, subDomain, function(err, _app) { if (err) return callback(err); if (_app) { req.ext.virtualEnv = settings.defaultVirtualEnvironment; } cb(null, _app); }); }, function(app, cb) { if (app) return cb(null, app); settings.virtualAppRegistry.getByDomain(domainName, '@', function(err, _app) { if (err) return cb(err); if (_app) { req.ext.virtualEnv = subDomain; req.ext.virtualHost = domainName; } cb(null, _app); }); } ], callback); } };
JavaScript
0.000168
@@ -542,16 +542,27 @@ dFunc = +_.endsWith( req.ext. @@ -572,26 +572,18 @@ tualHost -.endsWith( +, settings
ef369ea6ac11c612920f649e3db807f5787b7e85
Revert "Set connected status when multiplex long poll starts instead of when it times out"
lib/multiplexed_long_poll.js
lib/multiplexed_long_poll.js
import LongPollTransport from "./long_poll_transport.js" export default class MultiplexedLongPoll extends LongPollTransport { constructor(args) { super(args); this.subscribe = this.subscribe.bind(this); this.unsubscribe = this.unsubscribe.bind(this); this._request = this._request.bind(this); this._updateLastMessageSequences = this._updateLastMessageSequences.bind(this); this._subscriptions = this._subscriptions.bind(this); this._success = this._success.bind(this); this._lastMessageSequence = {}; } subscribe(channel, opts) {} // nothing to be done unsubscribe(...channelNames) { // abort request if we've unregistered all the channels if (Object.keys(this.config.channels).length === 0) { try { this._lastRequest && this._lastRequest.abort(); } catch (e) {} delete this._lastRequest; } } _request() { // Stop requested if (this._stopRequestLoop) { return; } // No channels subscribed so skip this cycle if (Object.keys(this.config.channels).length === 0) { return this.connect(this._okInterval); } const data = this._subscriptions(); // Notify consumer that initial long poll connection established // Delay this to allow for immediate connection failues. // We do this upfront otherwise we don't get a connected event // until the long poll connects which is 20s const delayedSuccess = setTimeout(() => { if (this._needToNotifyOfReconnect || !this._succeeded) { this._needToNotifyOfReconnect = false; this._open(data); } }, 500); return this._lastRequest = $.ajax({ url: `${this._protocol()}:${this.config.uri}`, firehose: true, crossDomain: true, method: "POST", data, dataType: "json", timeout: this._timeout, success: this._success, error: (xhr, status, error) => { // Prevent success from triggering when failed clearTimeout(delayedSuccess); this._error(xhr, status, error); }, cache: false }); } _updateLastMessageSequences() { return (() => { const result = []; for (let channel in this.config.channels) { var seq; const opts = this.config.channels[channel]; if (seq = this._lastMessageSequence[channel]) { result.push(opts.last_sequence = seq); } else { if (!opts.last_sequence) { result.push(opts.last_sequence = 0); } else { result.push(undefined); } } } return result; })(); } _subscriptions() { this._updateLastMessageSequences(); const subs = {}; for (let channel in this.config.channels) { const opts = this.config.channels[channel]; subs[channel] = opts.last_sequence || 0; } return JSON.stringify(subs); } _success(data, status, jqXhr) { if (this._stopRequestLoop) { return; } if (jqXhr.status === 200) { // Of course, IE's XDomainRequest doesn't support non-200 success codes. const message = JSON.parse(jqXhr.responseText); if (!this._lastMessageSequence) { this._lastMessageSequence = {}; } this._lastMessageSequence[message.channel] = message.last_sequence; this.config.message(message); } return this.connect(this._okInterval); } }
JavaScript
0
@@ -1145,458 +1145,8 @@ );%0A%0A - // Notify consumer that initial long poll connection established%0A // Delay this to allow for immediate connection failues.%0A // We do this upfront otherwise we don't get a connected event%0A // until the long poll connects which is 20s%0A const delayedSuccess = setTimeout(() =%3E %7B%0A if (this._needToNotifyOfReconnect %7C%7C !this._succeeded) %7B%0A this._needToNotifyOfReconnect = false;%0A this._open(data);%0A %7D%0A %7D, 500);%0A%0A @@ -1181,16 +1181,16 @@ .ajax(%7B%0A + ur @@ -1457,175 +1457,19 @@ -(xhr, status, error) =%3E %7B%0A // Prevent success from triggering when failed%0A clearTimeout(delayedSuccess);%0A this._error(xhr, status, error);%0A %7D +this._error ,%0A @@ -2299,24 +2299,24 @@ subs);%0A %7D%0A%0A - _success(d @@ -2333,24 +2333,160 @@ s, jqXhr) %7B%0A + if (this._needToNotifyOfReconnect %7C%7C !this._succeeded) %7B%0A this._needToNotifyOfReconnect = false;%0A this._open(data);%0A %7D%0A if (this
561b992fbd379c5115388b7a9bc8fdd71f728fe9
make profile panel can work with express 4.
lib/panels/profile/inject.js
lib/panels/profile/inject.js
"use strict"; var injections = module.exports, utils = require('../../utils'), _EDT_HIDDEN = { EDT_hidden: true }; var ProfileTime = function(action, name) { this.action = action; this.name = name; }; ProfileTime.prototype.toJSON = function() { var str = this.name + ' fn() { args: ' + this.action.handler.length; str += ', name: ' + this.action.handler.name + ' }'; str += ' Time: ' + (this.time.seconds * 1000 + this.time.milliseconds).toFixed(2) + 'ms'; return str; }; var hijack = function(original, action, time_name) { // returns a wrapper that will replace any middleware/route function // following the pattern of 'function(req, x, next[, ...])' return function() { var args = Array.prototype.slice.apply(arguments), next = args[2], req = args[0], times = req.EDT.profile[time_name] = req.EDT.profile[time_name] || [], time = new ProfileTime(action, time_name + ' #' + times.length); times[times.length] = time; args[2] = function (err) { if (!time.time) { // end profiling var diff = process.hrtime(time.hr_start); time.time = { seconds: diff[0], milliseconds: utils.get_ms_from_ns(diff[1]) }; delete time.hr_start; } next.apply(this, arguments); }; // begin profiling time.hr_start = process.hrtime(); original.apply(this, args); }; }; // global request timer injections.middleware_profiler = function (app) { var stack = app.stack, original; for (var i = 0; i < stack.length; i++) { // skip middleware already covered, also // middleware with 4 params is error handling, do not wrap if (!stack[i].handler && stack[i].handle.length < 4) { original = stack[i].handle; stack[i].handler = original; stack[i].handle = hijack(original, stack[i], 'middleware'); stack[i].handle.EDT_hidden = true; } } }; injections.param_handlers = function (app) { var params = app._router.params, flat_params = []; Object.keys(params).forEach(function (key) { var key_params = utils.flatten(params[key]).map(function (item) { item.key = key; return item; }); flat_params = flat_params.concat(key_params); }); flat_params.forEach(function (fn) { var parent = fn.EDT_parent, i = fn.EDT_index; // skip already hijacked params if (!parent[i].EDT) { parent[i].EDT_hidden = true; parent[i] = hijack(fn, { param: fn.key, action: fn }, 'param'); parent[i].EDT = _EDT_HIDDEN; } }); }; injections.route_profiler = function(app) { Object.keys(app.routes).forEach(function(method) { var routes = app.routes[method]; routes.forEach(function(rt) { var current = utils.flatten(rt.callbacks); current.forEach(function (cb) { var parent = cb.EDT_parent, i = cb.EDT_index; if (!parent[i].EDT) { parent[i].EDT_hidden = true; var action = { method: method, route: rt.path, handler: cb }; parent[i] = hijack(cb, action, 'route'); parent[i].EDT = _EDT_HIDDEN; } }); }); }) }; // close any open 'timers' injections.finalize = function(req) { var now = process.hrtime(), times = req.EDT.profile; times.global = { seconds: now[0] - times.global[0], milliseconds: utils.get_ms_from_ns(now[1] - times.global[1]) }; times.global.toJSON = function() { return 'Time: ' + (this.seconds * 1000 + this.milliseconds).toFixed(2) + 'ms'; }; Object.keys(times).forEach(function(type) { if (times[type] instanceof Array) { times[type].forEach(function (profile) { if (!profile.time) { profile.time = { seconds: now[0] - profile.hr_start[0], milliseconds: utils.get_ms_from_ns(now[1] - profile.hr_start[1]) }; delete profile.hr_start; } }); } }); };
JavaScript
0
@@ -1673,26 +1673,125 @@ original -;%0A +,%0A type;%0A //for express 4%0A if(!app.stack)%7B%0A stack = app._router.stack;%0A %7D%0A %0A for (va @@ -2085,16 +2085,163 @@ iginal;%0A + if(stack%5Bi%5D.route) %7B%0A type = 'route';%0A %7D%0A else%7B%0A type = 'middleware';%0A %7D %0A @@ -2290,28 +2290,20 @@ ack%5Bi%5D, -'middleware' +type );%0A @@ -3119,24 +3119,89 @@ tion(app) %7B%0A + //for express 4%0A if(!app.routes) %7B%0A return;%0A %7D %0A Object.k @@ -3672,25 +3672,45 @@ dler: cb %7D;%0A + %0A - @@ -3853,22 +3853,23 @@ %7D);%0A - %7D) +; %0A%7D;%0A%0A//
fff97c9248c830911ee5de45651e681638bac5a9
use PropTypes.any on style props to support Stylesheet declarations
src/Icon/index.js
src/Icon/index.js
/* eslint-disable import/no-unresolved, import/extensions */ import VectorIcon from 'react-native-vector-icons/MaterialIcons'; import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; /* eslint-enable import/no-unresolved, import/extensions */ const propTypes = { name: PropTypes.string.isRequired, style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), size: PropTypes.number, color: PropTypes.string, }; const defaultProps = { size: null, color: null, style: null, }; const contextTypes = { uiTheme: PropTypes.object.isRequired, }; class Icon extends PureComponent { render() { const { name, style, size, color } = this.props; const { palette, spacing } = this.context.uiTheme; const iconColor = color || palette.secondaryTextColor; const iconSize = size || spacing.iconSize; return ( <VectorIcon name={name} size={iconSize} color={iconColor} style={style} /> ); } } Icon.propTypes = propTypes; Icon.defaultProps = defaultProps; Icon.contextTypes = contextTypes; export default Icon;
JavaScript
0
@@ -347,54 +347,11 @@ pes. -oneOfType(%5BPropTypes.object, PropTypes.array%5D) +any ,%0A
fe37328cfb4585bfb1812f3a8ef133e92868ab65
remove double call (#460)
lib/rest/routes/pipelines.js
lib/rest/routes/pipelines.js
const express = require('express'); module.exports = function ({config}) { const router = express.Router(); router.put('/:name', function (req, res, next) { let isUpdate; config.updateGatewayConfig(json => { json.pipelines = json.pipelines || {}; isUpdate = req.params.name in json.pipelines; json.pipelines[req.params.name] = req.body; return json; }) .then(() => res.status(isUpdate ? 204 : 201).send()) .catch(next); }); router.get('/:name', function (req, res) { const entity = config.gatewayConfig.pipelines[req.params.name]; if (!entity) { return res.status(404).send(); } res.json(entity); res.json(config.gatewayConfig.pipelines[req.params.name]); }); router.get('/', function (req, res) { res.json(config.gatewayConfig.pipelines); }); router.delete('/:name', function (req, res, next) { if (!config.gatewayConfig.pipelines[req.params.name]) { return res.status(404).send(); } config.updateGatewayConfig(json => { json.pipelines = json.pipelines || {}; delete json.pipelines[req.params.name]; return json; }) .then(() => res.status(204).send()) .catch(next); }); return router; };
JavaScript
0.000003
@@ -669,71 +669,8 @@ y);%0A - res.json(config.gatewayConfig.pipelines%5Breq.params.name%5D);%0A %7D)
a2fb5e33373e0404a5ef8965e4b9aabeeb435b43
fix GET/POST request to markup validator
lib/rules/validation/html.js
lib/rules/validation/html.js
/*jshint es5:true */ var sua = require("../../throttled-ua"); exports.name = "validation.html"; exports.check = function (sr, done) { var service = "http://validator.w3.org/check"; if (sr.config.skipValidation) { sr.warning(this.name, "skipped"); return done(); } if (!sr.url && !sr.source) { sr.warning(this.name, "no-source"); return done(); } var req; if (sr.url) { req = sua.get(service) .query({ uri: sr.url }); } else { req = sua.post(service) .set("Content-Type", "text/html") .send(sr.source); } req .query({ output: "json" }) .set("User-Agent", "Specberus/" + sr.version + " Node/" + process.version + " by sexy Robin") .end(function (res) { var json = res.body; if (!json) return sr.throw("No JSON input."); if (!res.ok) { sr.error(exports.name, "failure", { status: res.status }); } else if (!json) { sr.error(exports.name, "no-response"); } else { if (json.messages && json.messages.length) { for (var i = 0, n = json.messages.length; i < n; i++) { var msg = json.messages[i]; // { // "type": "error", // "lastLine": 26, // "lastColumn": 14, // "firstColumn": 7, // "message": "blah", // "extract": "er>\n <hgroup>\n ", // "hiliteStart": 10, // "hiliteLength": 8 // } if (msg.type === "error") { sr.error(exports.name, "error", { line: msg.lastLine , column: msg.lastColumn , message: msg.message }); } // { // "type": "info", // "url": "http://www.google.com/", // "subType": "warning", // "message": "blah" // } else if (msg.type === "info") { if (msg.subtype === "warning") { sr.warning(exports.name, "warning", { message: msg.message }); } } // { // "type":"non-document-error", // "subType":"io", // "message":"HTTP resource not retrievable. The HTTP status from the remote server was: 404." // } else if (msg.type === "non-document-error") { sr.error(exports.name, "non-document-error", { subType: msg.subType , message: msg.message }); } } } } done(); }) ; };
JavaScript
0.000001
@@ -404,16 +404,103 @@ var req +%0A , ua = %22Specberus/%22 + sr.version + %22 Node/%22 + process.version + %22 by sexy Robin%22 ;%0A if @@ -534,32 +534,72 @@ ua.get(service)%0A + .set(%22User-Agent%22, ua)%0A @@ -619,16 +619,32 @@ : sr.url +, output: %22json%22 %7D);%0A @@ -716,85 +716,76 @@ et(%22 -Content-Type%22, %22text/html%22)%0A .send(sr.source);%0A +User-Agent%22, ua)%0A .field('output', 'json')%0A -%7D%0A -req%0A @@ -793,144 +793,56 @@ . -query(%7B output: %22json%22 %7D)%0A .set(%22User-Agent%22, %22Specberus/%22 + sr.version + %22 Node/%22 + process.version + %22 by sexy Robin%22) +field('uploaded_file', sr.source); %0A +%7D%0A +req .end
4bd284612511b2db3739e7c71b80593147d4fee5
Update RemoteNode.js
src/RemoteNode.js
src/RemoteNode.js
class RemoteNode { constructor(peer, descriptor, options, bootstrappingNode, signalingNode, isCalled) { this.peer = peer; this.descriptor = descriptor; this.options = options; this.bootstrappingNode = bootstrappingNode; this.signalingNode = signalingNode; var self = this; this.connection = new RTCPeerConnection(options.configuration); this.connection.onicecandidate = function (event) { if(event.candidate) { self.sendToSignalingNode(new SignalingMessage(self.peer.descriptor, self.descriptor, new CandidateMessage(self.peer.descriptor, event.candidate))); } }; this.connection.ondatachannel = function(event) { self.datachannel = event.channel; self.datachannel.onmessage = function(event) { self.peer.onmessage(JSON.parse(event.data), self); }; self.datachannel.onclose = function (event) { self.peer.geobucket.remove(self); self.peer.emit("neighbors", self.peer.geobucket.descriptors()); }; }; if(isCalled) { this.datachannel = this.connection.createDataChannel(options.label, options.datachannel_options); this.datachannel.onmessage = function(event) { self.peer.onmessage(JSON.parse(event.data), self); }; this.datachannel.onclose = function (event) { self.peer.geobucket.remove(self); self.peer.emit("neighbors", self.peer.geobucket.descriptors()); }; } } isConnected() { return "open" === this.datachannel.readyState; } connect() { var self = this; this.connection.createOffer().then(function(offer) { return self.connection.setLocalDescription(offer); }).then(function() { self.sendToSignalingNode(new SignalingMessage(self.peer.descriptor, self.descriptor, new OfferMessage(self.peer.descriptor, self.connection.localDescription))); }).catch(function(reason) { // An error occurred, so handle the failure to connect }); } send(message) { this.datachannel.send(JSON.stringify(message)); console.log('Sent ' + message.type + ' to ' + this.descriptor.key); } sendToSignalingNode(message) { if(this.signalingNode.isConnected()) { this.signalingNode.send(message); } else { this.bootstrappingNode.send(message); } } disconnect() { if(this.isConnected()) { this.sendToSignalingNode(new SignalingMessage(this.peer.descriptor, this.descriptor, new LeaveMessage(this.peer.descriptor))); this.datachannel.close(); this.connection.close(); this.connection.onicecandidate = null; } } setSignalingNode(signalingNode) { this.signalingNode = signalingNode; } }
JavaScript
0.000001
@@ -293,16 +293,58 @@ ingNode; +%0A this.pendingMessages = new Set(); %0A%0A @@ -1161,32 +1161,404 @@ %0A %7D;%0A + %0A self.datachannel.onopen = function (event) %7B%0A self.pendingMessages.forEach(function(message) %7B%0A self.datachannel.send(JSON.stringify(message));%0A console.log('Sent ' + message.type + ' to ' + self.descriptor.key);%0A %7D);%0A self.pendingMessages.clear();%0A %7D;%0A %7D;%0A%0A @@ -2024,32 +2024,404 @@ %0A %7D;%0A + %0A this.datachannel.onopen = function (event) %7B%0A self.pendingMessages.forEach(function(message) %7B%0A self.datachannel.send(JSON.stringify(message));%0A console.log('Sent ' + message.type + ' to ' + self.descriptor.key);%0A %7D);%0A self.pendingMessages.clear();%0A %7D;%0A %7D%0A %7D%0A @@ -2456,16 +2456,38 @@ return +(this.datachannel && ( %22open%22 = @@ -2516,16 +2516,18 @@ adyState +)) ;%0A %7D%0A @@ -3029,32 +3029,69 @@ send(message) %7B%0A + if(this.isConnected()) %7B%0A this.dat @@ -3122,32 +3122,36 @@ gify(message));%0A + console. @@ -3206,24 +3206,98 @@ iptor.key);%0A + %7D else %7B%0A this.pendingMessages.add(message);%0A %7D%0A %7D%0A%0A s
2ae5c5f8a726dec6043475d82950d170320865fd
Clear prev touch event when fired touchend
src/ScrollLock.js
src/ScrollLock.js
/** * Created by laiff on 10.12.14. */ /** * Prevent default behavior for event * * @param e * @returns {boolean} */ var cancelScrollEvent = function (e) { e.stopImmediatePropagation(); e.preventDefault(); e.returnValue = false; return false; }; var addScrollEventListener = function (elem, handler) { elem.addEventListener('wheel', handler, false); }; var removeScrollEventListener = function (elem, handler) { elem.removeEventListener('wheel', handler, false); }; var addTouchStartEventListener = function(elem, handler) { elem.addEventListener('touchstart', handler, false); }; var removeTouchStartEventListener = function(elem, handler) { elem.removeEventListener('touchstart', handler, false); }; var addTouchMoveEventListener = function(elem, handler) { elem.addEventListener('touchmove', handler, false); }; var removeTouchMoveEventListener = function(elem, handler) { elem.removeEventListener('touchmove', handler, false); }; var previousTouchEvent = null; var deltaTouch = function(touchEvent, st) { if (previousTouchEvent) { var delta = -(touchEvent.touches[0].screenY - previousTouchEvent.touches[0].screenY); previousTouchEvent = touchEvent; return delta; } previousTouchEvent = touchEvent; return 0; }; /** * @extends ReactCompositeComponentInterface * * @mixin ScrollLock */ var ScrollLock = { componentDidMount: function () { this.scrollLock(); this.touchLock(); }, componentDidUpdate: function () { this.scrollLock(); this.touchLock(); }, componentWillUnmount: function () { this.scrollRelease(); this.touchRelease(); }, scrollLock: function () { var elem = this.getDOMNode(); if (elem) { addScrollEventListener(elem, this.onScrollHandler); } }, scrollRelease: function () { var elem = this.getDOMNode(); if (elem) { removeScrollEventListener(elem, this.onScrollHandler); } }, touchLock: function () { var elem = this.getDOMNode(); if (elem) { addTouchMoveEventListener(elem, this.onTouchHandler); addTouchStartEventListener(elem, this.onTouchStartHandler); } }, touchRelease: function () { var elem = this.getDOMNode(); if (elem) { removeTouchMoveEventListener(elem, this.onTouchHandler); removeTouchStartEventListener(elem, this.onTouchStartHandler); } }, onScrollHandler: function (e) { var elem = this.getDOMNode(); var scrollTop = elem.scrollTop; var scrollHeight = elem.scrollHeight; var height = elem.clientHeight; var wheelDelta = e.deltaY; var isDeltaPositive = wheelDelta > 0; if (isDeltaPositive && wheelDelta > scrollHeight - height - scrollTop) { elem.scrollTop = scrollHeight; return cancelScrollEvent(e); } else if (!isDeltaPositive && -wheelDelta > scrollTop) { elem.scrollTop = 0; return cancelScrollEvent(e); } }, onTouchStartHandler: function(e) { deltaTouch(e, this.getDOMNode().scrollTop); }, onTouchHandler: function(e) { var elem = this.getDOMNode(); var scrollTop = elem.scrollTop; var scrollHeight = elem.scrollHeight; var height = elem.clientHeight; var wheelDelta = deltaTouch(e, elem.scrollTop); var isDeltaPositive = wheelDelta > 0; if (isDeltaPositive && wheelDelta >= scrollHeight - height - scrollTop) { elem.scrollTop = scrollTop; return cancelScrollEvent(e); } else if (!isDeltaPositive && -wheelDelta >= scrollTop) { elem.scrollTop = 0; return cancelScrollEvent(e); } } }; module.exports = ScrollLock;
JavaScript
0
@@ -982,16 +982,254 @@ e);%0A%7D;%0A%0A +var addTouchEndEventListener = function(elem, handler) %7B%0A elem.addEventListener('touchend', handler, false);%0A%7D;%0A%0Avar removeTouchEndEventListener = function(elem, handler) %7B%0A elem.removeEventListener('touchend', handler, false);%0A%7D;%0A%0A %0Avar pre @@ -1545,16 +1545,94 @@ 0;%0A%7D;%0A%0A +var clearPreviousTouchEvent = function() %7B%0A previousTouchEvent = null;%0A%7D;%0A%0A %0A/**%0A * @@ -2506,32 +2506,36 @@ em, this.onTouch +Move Handler);%0A @@ -2592,32 +2592,100 @@ hStartHandler);%0A + addTouchEndEventListener(elem, this.onTouchEndHandler);%0A %7D%0A %7D, @@ -2831,24 +2831,28 @@ this.onTouch +Move Handler);%0A @@ -2916,32 +2916,103 @@ hStartHandler);%0A + removeTouchEndEventListener(elem, this.onTouchEndHandler);%0A %7D%0A %7D, @@ -3716,32 +3716,32 @@ llTop);%0A %7D,%0A%0A - onTouchHandl @@ -3735,16 +3735,100 @@ onTouch +EndHandler: function(e) %7B%0A clearPreviousTouchEvent();%0A %7D,%0A%0A onTouchMove Handler:
04bf179c82a2c422817419097330962429b06452
Add a wrapper so that nodejs tests catch uncaught exceptions.
src/addTestAPI.js
src/addTestAPI.js
import { isNil } from 'substance' export default function addTestAPI (tape) { const Test = tape.Test Test.prototype.nil = Test.prototype.isNil = function (value, msg, extra) { this._assert(isNil(value), { message: msg, operator: 'nil', expected: true, actual: value, extra: extra }) } Test.prototype.notNil = Test.prototype.isNotNil = function (value, msg, extra) { this._assert(!isNil(value), { message: msg, operator: 'nil', expected: true, actual: value, extra: extra }) } }
JavaScript
0
@@ -7,16 +7,26 @@ %7B isNil +, platform %7D from @@ -108,16 +108,278 @@ e.Test%0A%0A + if (platform.inNodeJS) %7B%0A const _run = Test.prototype.run%0A Test.prototype.run = function () %7B%0A try %7B%0A _run.apply(this, arguments)%0A %7D catch (err) %7B%0A this.fail('Uncaught error: ' + String(err))%0A this.end()%0A %7D%0A %7D%0A %7D%0A%0A Test.p
ae036f54fe31bfa7efa99ff9ecfdd835874c707f
Remove Object.assign and use spread
src/animate.me.js
src/animate.me.js
export default class AnimateMe { constructor(selector = '.animate-me', options = {}) { this.options = Object.assign( {}, { offset: 0.5, reverse: true, animatedIn: 'animate-me--in', offsetAttr: 'data-offset', animationAttr: 'data-animation', touchDisabled: true }, options ); this.win = window; this.offsets = []; this.animated = document.querySelectorAll(selector); this.isTouchDevice = 'ontouchstart' in this.win || navigator.msMaxTouchPoints > 0 || navigator.maxTouchPoints > 0; if (this.options.offset > 1) { this.options.offset = 1; } if (this.options.offset < 0) { this.options.offset = 0; } this.getCurrentScroll(); this.getWindowDimensions(); this.start(); return this; } start() { this.updateOffsets(); this.bind(); } getCurrentScroll() { this.winO = this.win.pageYOffset; } getWindowDimensions() { this.winH = this.win.innerHeight; this.winW = this.win.innerWidth; } bind() { this.getCurrentScroll(); this.updateOffsets(); this.animate(); this.win.addEventListener( 'scroll', () => { this.getCurrentScroll(); this.animate(); }, false ); this.win.addEventListener( 'resize', () => { this.getWindowDimensions(); this.updateOffsets(); }, false ); } animate() { const app = this; const opts = app.options; [].forEach.call(this.animated, (element, i) => { const animationName = element.getAttribute(opts.animationAttr) || ''; if (opts.touchDisabled && app.isTouchDevice) { element.classList.add(opts.animatedIn); } else { const shouldAnimate = app.winO + app.winH * opts.offset > app.offsets[i]; if (opts.reverse) { element.classList.toggle(opts.animatedIn, shouldAnimate); animationName && element.classList.toggle(animationName, shouldAnimate); } else { if (shouldAnimate) { element.classList.add(opts.animatedIn); animationName && element.classList.add(animationName); } } } }); } updateOffsets() { const app = this; app.offsets = [].map.call(app.animated, element => { const elementOffset = element.getBoundingClientRect().top + app.win.pageYOffset; const offsetDelay = parseFloat(element.getAttribute(app.options.offsetAttr)) || 0; return elementOffset + offsetDelay; }); } }
JavaScript
0
@@ -105,43 +105,10 @@ s = -Object.assign(%0A %7B%7D,%0A %7B%0A +%7B%0A @@ -122,18 +122,16 @@ t: 0.5,%0A - re @@ -145,26 +145,24 @@ true,%0A - - animatedIn: @@ -181,26 +181,24 @@ -in',%0A - offsetAttr: @@ -214,26 +214,24 @@ set',%0A - - animationAtt @@ -247,26 +247,24 @@ animation',%0A - touchD @@ -276,32 +276,24 @@ ed: true -%0A %7D ,%0A options%0A @@ -284,16 +284,19 @@ ,%0A +... options%0A @@ -295,27 +295,26 @@ options%0A -);%0A +%7D; %0A this.wi
95765577b665010a15c6b0696517e904df6752a6
Add separator in context menu between items
src/background.js
src/background.js
const menuItems = { family: { contextMenu: null, value: '', defaultValue: 'Please' }, weight: { contextMenu: null, value: '', defaultValue: 'reload' }, size: { contextMenu: null, value: '', defaultValue: 'the' }, color: { contextMenu: null, value: '', defaultValue: 'page' }, letterSpacing: { contextMenu: null, value: '', defaultValue: '(•‿•)' }, variants: { contextMenu: null, value: '', defaultValue: '(•‿•)' }, featureSettings: { contextMenu: null, value: '', defaultValue: '(•‿•)' }, variationSettings: { contextMenu: null, value: '', defaultValue: '(•‿•)' }, }; function copyTextToClipboard(text) { const textarea = document.createElement('textarea'); textarea.value = text; document.body.appendChild(textarea); textarea.select(); document.execCommand('copy'); document.body.removeChild(textarea); } function firstFontFamily(fontFamily) { const quotes = /"/g; return fontFamily.split(',')[0].replace(quotes, ''); } function RGBToHex(RGB) { const RGBParts = RGB.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); const HexArr = []; delete RGBParts[0]; RGBParts.forEach((value) => { let hex = parseInt(value, 10).toString(16); if (hex.length === 1) { hex = `0${hex}`; } HexArr.push(hex); }); return `#${HexArr.join('')}`; } function isRGB(value) { return !!value.match(/^rgb\(/); } function round(num, decimals) { return +num.toFixed(decimals); } function unitlessLineHeight(size, lineHeight) { return round(parseFloat(lineHeight, 10) / parseFloat(size, 10), 3); } function fontSizeAndLineHeight(size, lineHeight) { const part1 = `${size} / ${lineHeight}`; const part2 = unitlessLineHeight(size, lineHeight); return `${part1}${part2 ? ` (${part2})` : ''}`; } function resetContextMenus() { Object.keys(menuItems).forEach((key) => { chrome.contextMenus.update(menuItems[key].contextMenu, { title: menuItems[key].defaultValue, enabled: false, }); }); } const fontWeights = { 100: '100 (thin)', 200: '200 (extra light)', 300: '300 (light)', 400: '400 (normal)', 500: '500 (medium)', 600: '600 (semi bold)', 700: '700 (bold)', 800: '800 (extra bold)', 900: '900 (black)', normal: '400 (normal)', bold: '700 (bold)', }; Object.keys(menuItems).forEach((key) => { menuItems[key].contextMenu = chrome.contextMenus.create({ title: menuItems[key].defaultValue, contexts: ['all'], onclick: () => { copyTextToClipboard(menuItems[key].value); }, }); }); chrome.runtime.onMessage.addListener((fontData) => { menuItems.family.value = firstFontFamily(fontData.family); menuItems.weight.value = fontWeights[fontData.weight]; menuItems.size.value = fontSizeAndLineHeight(fontData.size, fontData.lineHeight); menuItems.color.value = isRGB(fontData.color) ? RGBToHex(fontData.color) : fontData.color; menuItems.letterSpacing.value = `${fontData.letterSpacing} (letter-spacing)`; menuItems.variants.value = `${fontData.variants} (variants)`; menuItems.featureSettings.value = `${fontData.featureSettings} (features)`; menuItems.variationSettings.value = `${fontData.variationSettings} (variables)`; Object.keys(menuItems).forEach((key) => { chrome.contextMenus.update(menuItems[key].contextMenu, { title: menuItems[key].value, enabled: true, }); }); }); chrome.tabs.onActivated.addListener(() => resetContextMenus()); chrome.windows.onFocusChanged.addListener(() => resetContextMenus());
JavaScript
0.000001
@@ -576,16 +576,198 @@ )' %7D,%0A%7D; +%0Aconst menuSections = %5B%0A %5B%0A 'family',%0A 'weight',%0A 'size',%0A 'color',%0A %5D,%0A %5B%0A 'letterSpacing',%0A 'variants',%0A 'featureSettings',%0A 'variationSettings',%0A %5D,%0A%5D; %0A%0Afuncti @@ -2432,38 +2432,173 @@ )',%0A%7D;%0A%0A -Object.keys(menuItems) +menuSections.forEach((items, i) =%3E %7B%0A if (i !== 0) %7B%0A chrome.contextMenus.create(%7B%0A type: 'separator',%0A contexts: %5B'all'%5D,%0A %7D);%0A %7D%0A%0A items .forEach @@ -2605,24 +2605,26 @@ ((key) =%3E %7B%0A + menuItems%5B @@ -2671,24 +2671,26 @@ reate(%7B%0A + title: menuI @@ -2713,24 +2713,26 @@ tValue,%0A + + contexts: %5B' @@ -2742,16 +2742,18 @@ '%5D,%0A + onclick: @@ -2757,24 +2757,26 @@ ck: () =%3E %7B%0A + copyTe @@ -2816,18 +2816,28 @@ e);%0A -%7D, + %7D,%0A %7D); %0A %7D);%0A%7D
7fa53a2db3efd4c2ff9e2ca956109bacf5b664c9
Allow chaining of Size setters.
src/basic/Size.js
src/basic/Size.js
var Size = this.Size = Base.extend({ initialize: function() { if (arguments.length == 2) { this.width = arguments[0]; this.height = arguments[1]; } else if (arguments.length == 1) { var arg = arguments[0]; if (arg == null) { this.width = this.height = 0; } else if (arg.width !== undefined) { this.width = arg.width; this.height = arg.height; } else if (arg.x !== undefined) { this.width = arg.x; this.height = arg.y; } else if (Array.isArray(arg)) { this.width = arg[0]; this.height = arg.length > 1 ? arg[1] : arg[0]; } else if (typeof arg === 'number') { this.width = this.height = arg; } else { this.width = this.height = 0; } } else { this.width = this.height = 0; } }, set: function(width, height) { this.width = width; this.height = height; }, add: function() { var size = Size.read(arguments); return Size.create(this.width + size.width, this.height + size.height); }, subtract: function() { var size = Size.read(arguments); return Size.create(this.width - size.width, this.height - size.height); }, multiply: function() { var size = Size.read(arguments); return Size.create(this.width * size.width, this.height * size.height); }, divide: function() { var size = Size.read(arguments); return Size.create(this.width / size.width, this.height / size.height); }, modulo: function() { var size = Size.read(arguments); return Size.create(this.width % size.width, this.height % size.height); }, negate: function() { return Size.create(-this.width, -this.height); }, equals: function() { var size = Size.read(arguments); return this.width == size.width && this.height == size.height; }, isNaN: function() { return isNaN(this.width) || isNaN(this.height); }, round: function() { return Size.create(Math.round(this.width), Math.round(this.height)); }, ceil: function() { return Size.create(Math.ceil(this.width), Math.ceil(this.height)); }, floor: function() { return Size.create(Math.floor(this.width), Math.floor(this.height)); }, abs: function() { return Size.create(Math.abs(this.width), Math.abs(this.height)); }, dot: function(Size) { return this.width * size.width + this.height * size.height; }, toString: function() { return '{ x: ' + this.width + ', y: ' + this.height + ' }'; }, statics: { // See Point.create() create: function(width, height) { var size = new Size(Size.dont); size.width = width; size.height = height; return size; }, min: function(Size1, Size2) { return Size.create( Math.min(Size1.width, Size2.width), Math.min(Size1.height, Size2.height)); }, max: function(Size1, Size2) { return Size.create( Math.max(Size1.width, Size2.width), Math.max(Size1.height, Size2.height)); }, random: function() { return Size.create(Math.random(), Math.random()); } } });
JavaScript
0
@@ -822,24 +822,39 @@ t = height;%0A +%09%09return this;%0A %09%7D,%0A%0A%09add: f
4601e47cecd01d344fe9cc9a05a2a036ad7d60f4
remove news hook
src/scenes/SplashScene.js
src/scenes/SplashScene.js
"use strict"; import React, {Component} from 'react'; import { AsyncStorage, StyleSheet, Image, } from 'react-native'; import CONFIG from './../config'; import _ from './../l10n'; import Items from './../Items'; import { Layout, } from './../components'; import Scene from './Scene'; export class SplashScene extends Scene { constructor(props, context, updater) { super(props, context, updater); } componentDidMount() { super.componentDidMount(); CONFIG.initialize().then(() => { Items.initialize().then(async () => { const TIPS_SHOWN = await AsyncStorage.getItem('TIPS_SHOWN'); if (TIPS_SHOWN !== 'true') { await AsyncStorage.setItem('TIPS_SHOWN', 'true'); this.navigateTo('WelcomeScene', {type: 'tips',}); return; } if (CONFIG.SHOW_NEWS) { const VERSION = await AsyncStorage.getItem('VERSION'); if (VERSION !== CONFIG.VERSION) { await AsyncStorage.setItem('VERSION', CONFIG.VERSION); // if (VERSION) { this.navigateTo('WelcomeScene'); return; // } } } this.navigateTo('MainScene'); }); }); } navigateTo(scene, props = {}) { if (!CONFIG.CLOUD_SYNCHRONIZATION && !__DEV__) { setTimeout(() => this.navigator.resetTo({name: scene, props: props,}), 1500); return; } this.navigator.resetTo({name: scene, props: props,}); } render() { return ( <Layout background={CONFIG.COLORS.DARK_BLUE} disablePadding={true} styles={styles.layout}> <Image source={require('./../assets/loader.gif')} style={styles.loader}/> </Layout> ); } } const styles = StyleSheet.create({ layout: { justifyContent: 'center', alignItems: 'center', }, loader: { height: 96, width: 96, resizeMode: 'contain', }, });
JavaScript
0
@@ -699,24 +699,99 @@ = 'true') %7B%0A + await AsyncStorage.setItem('VERSION', CONFIG.VERSION);%0A @@ -1240,19 +1240,16 @@ - // if (VER @@ -1381,11 +1381,8 @@ - // %7D%0A
62d59b5e7b07c2763ce9ad1c9561bb1919bdd1ab
Fix some empty cards showing up
src/search-result-item.js
src/search-result-item.js
import { PolymerElement } from '@polymer/polymer/polymer-element.js'; import './shared-styles.js'; import '@polymer/paper-card/paper-card.js'; import './discussions/discussions-topic-post-item.js'; import './discussions/discussions-forum-item.js'; import './discussions/discussions-topic.js'; import './user/user-card.js'; import './content/content-activity-item.js'; import './content/content-module-card.js'; import './courses/course-item.js'; import './activities/user-activity-usage.js'; import './discussions/discussions-topic-post-reply-item.js'; import './updates/update-item.js'; import './updates/update-item-grades.js'; import { html } from '@polymer/polymer/lib/utils/html-tag.js'; class SearchResultItem extends PolymerElement { static get template() { return html` <style include="shared-styles"> :host { display: block; } </style> <div> <template is="dom-if" if="{{isThread}}"> <d2l-discussions-topic-post-item href="{{result.href}}" token="{{result.token}}"></d2l-discussions-topic-post-item> </template> <template is="dom-if" if="{{isForum}}"> <d2l-discussions-forum-item href="{{result.href}}" token="{{result.token}}"></d2l-discussions-forum-item> </template> <template is="dom-if" if="{{isTopic}}"> <d2l-discussions-topic href="{{result.href}}" token="{{result.token}}"></d2l-discussions-topic> </template> <template is="dom-if" if="{{isCourseOffering}}"> <d2l-course-item href="{{result.href}}" token="{{result.token}}"></d2l-course-item> </template> <template is="dom-if" if="{{isUser}}"> <d2l-user-card href="{{result.href}}" token="{{result.token}}"></d2l-user-card> </template> <template is="dom-if" if="{{isActivity}}"> <d2l-user-activity-usage href="{{result.href}}" token="{{result.token}}"></d2l-user-activity-usage> </template> <template is="dom-if" if="{{isPost}}"> <d2l-discussions-topic-post-reply-item href="{{result.href}}" token="{{result.token}}"></d2l-discussions-topic-post-reply-item> </template> <template is="dom-if" if="{{isGrade}}"> <d2l-update-item-grades href="{{result.href}}" token="{{result.token}}"><!--<d2l-update-item-grades --> </d2l-update-item-grades></template> <template is="dom-if" if="{{isNews}}"> <d2l-update-item href="{{result.href}}" token="{{result.token}}"><!--<d2l-update-item --> </d2l-update-item></template> <template is="dom-if" if="{{isModule}}"> <d2l-content-module-card href="{{result.href}}" token="{{result.token}}"><!--<d2l-content-module-card--> </d2l-content-module-card></template> <template is="dom-if" if="{{isContent}}"> <d2l-content-activity-item href="{{result.href}}" token="{{result.token}}"><!--<d2l-content-activity-item --> </d2l-content-activity-item></template> <template is="dom-if" if="{{isNote}}"> <d2l-note href="{{result.href}}" token="{{result.token}}"><!--<d2l-note --> </d2l-note></template> <template is="dom-if" if="{{isAMystery}}"> What the HYPERMEDIA is this? </template> </div> `; } static get is() { return 'd2l-search-result-item'; } static get properties() { return { result: Object, isThread: Boolean, isForum: Boolean, isTopic: Boolean, isCourseOffering: Boolean, isUser: Boolean, isActivity: Boolean, isPost: Boolean, isGrade: Boolean, isNews: Boolean, isContent: Boolean, isModule: Boolean, isNote: Boolean, isAMystery: Boolean }; } static get observers() { return [ '_resultChanged(result)' ]; } _resultChanged(result) { this.isAMystery = false; this.isThread = this.isForum = this.isTopic = this.isCourseOffering = this.isUser = this.isActivity = this.isPost = false; switch (result.type) { case 'thread': this.isThread = true; break; case 'forum': this.isForum = true; break; case 'topic': this.isTopic = true; break; case 'course-offering': this.isCourseOffering = true; break; case 'user': this.isUser = true; break; case 'activity': this.isActivity = true; break; case 'post': this.isPost = true; break; case 'grade': this.isGrade = true; break; case 'news': this.isNews = true; break; case 'content': this.isContent = true; break; case 'module': this.isModule = true; break; case 'note': this.isNote = true; break; default: this.isAMystery = true; } } } window.customElements.define(SearchResultItem.is, SearchResultItem);
JavaScript
0.000001
@@ -4076,21 +4076,13 @@ ring -%0A = + =%0A%09%09 this @@ -4122,16 +4122,94 @@ isPost = + this.isGrade = this.isNews =%0A%09%09this.isContent = this.isModule = this.isNote = false;%0A
5cf34901158f745cadbbb3f4f4578857bf73caaa
test for null in url.parse results for port
src/server/builds/node.js
src/server/builds/node.js
'use strict'; // This is the Node.JS entry point module.exports = algoliasearch; var debug = require('debug')('algoliasearch:nodejs'); var crypto = require('crypto'); var inherits = require('inherits'); var Promise = global.Promise || require('es6-promise').Promise; var semver = require('semver'); var AlgoliaSearchServer = require('./AlgoliaSearchServer'); var errors = require('../../errors'); // does not work on node < 0.8 if (semver.satisfies(process.version, '<=0.7')) { throw new errors.AlgoliaSearchError('Node.js version ' + process.version + ' is not supported'); } debug('loaded the Node.js client'); function algoliasearch(applicationID, apiKey, opts) { var cloneDeep = require('lodash-compat/lang/cloneDeep'); var reduce = require('lodash-compat/collection/reduce'); if (!opts) { opts = {}; } var httpAgent = opts.httpAgent; opts = cloneDeep(reduce(opts, allButHttpAgent, {})); // as an httpAgent is an object with methods etc, we take a reference to // it rather than cloning it like other values function allButHttpAgent(filteredOpts, val, keyName) { if (keyName !== 'httpAgent') { filteredOpts[keyName] = val; } return filteredOpts; } opts.httpAgent = httpAgent; // inactivity timeout if (opts.timeout === undefined) { opts.timeout = 15000; } if (opts.protocol === undefined) { opts.protocol = 'https:'; } opts._ua = opts._ua || algoliasearch.ua; opts._useCache = false; return new AlgoliaSearchNodeJS(applicationID, apiKey, opts); } algoliasearch.version = require('../../version.json'); algoliasearch.ua = 'Algolia for Node.js ' + algoliasearch.version; function AlgoliaSearchNodeJS(applicationID, apiKey, opts) { var getAgent = require('./get-agent'); // call AlgoliaSearchServer constructor AlgoliaSearchServer.apply(this, arguments); this._Agent = opts.httpAgent || getAgent(opts.protocol); } inherits(AlgoliaSearchNodeJS, AlgoliaSearchServer); AlgoliaSearchNodeJS.prototype._request = function request(rawUrl, opts) { var http = require('http'); var https = require('https'); var url = require('url'); var client = this; return new Promise(function doReq(resolve, reject) { opts.debug('url: %s, method: %s, timeout: %d', rawUrl, opts.method, opts.timeout); var body = opts.body; var debugInterval; var parsedUrl = url.parse(rawUrl); var requestOptions = { hostname: parsedUrl.hostname, port: parsedUrl.port, method: opts.method, path: parsedUrl.path, agent: client._Agent }; var timedOut = false; var req; if (parsedUrl.protocol === 'https:') { // we do not rely on any "smart" port computing by either node.js // or a custom http agent, because: // https://github.com/TooTallNate/node-https-proxy-agent/issues/7#issuecomment-119539690 if (requestOptions.port === undefined) { requestOptions.port = 443; } req = https.request(requestOptions); } else { // same reason to set the port as `https:` if (requestOptions.port === undefined) { requestOptions.port = 80; } req = http.request(requestOptions); } req.setHeader('connection', 'keep-alive'); req.setHeader('accept', 'application/json'); Object.keys(opts.headers).forEach(function setRequestHeader(headerName) { req.setHeader(headerName, opts.headers[headerName]); }); // socket inactivity timeout // this is not a global timeout on the request req.setTimeout(opts.timeout); req.once('error', error); req.once('timeout', timeout); req.once('response', response); if (body) { req.setHeader('content-type', 'application/json'); req.setHeader('content-length', Buffer.byteLength(body, 'utf8')); req.write(body); // debug request body/sent // only when DEBUG=debugBody is found if (process.env.DEBUG && process.env.DEBUG.indexOf('debugBody') !== -1) { req.once('socket', function gotSocket() { debugBytesSent(); debugInterval = setInterval(debugBytesSent, 100); req.socket.once('end', stopDebug); req.socket.once('close', stopDebug); }); } } req.end(); function response(res) { var chunks = []; res.on('data', onData); res.once('end', onEnd); function onData(chunk) { chunks.push(chunk); } function onEnd() { var data = Buffer.concat(chunks).toString(); var out; try { out = { body: JSON.parse(data), statusCode: res.statusCode, headers: res.headers }; } catch (e) { out = new errors.UnparsableJSON({ more: data }); } if (out instanceof errors.UnparsableJSON) { reject(out); } else { resolve(out); } } } function error(err) { opts.debug('error: %j - %s', err, rawUrl); if (timedOut) { opts.debug('request had already timedout'); return; } reject(new errors.Network(err.message, err)); } function timeout() { timedOut = true; opts.debug('timeout %s', rawUrl); req.abort(); reject(new errors.RequestTimeout()); } function debugBytesSent() { var remaining = Buffer.byteLength(body) + Buffer.byteLength(req._header); var sent = req.socket.bytesWritten; opts.debug('sent/remaining bytes: %d/%d', sent, remaining); } function stopDebug() { req.socket.removeListener('end', stopDebug); req.socket.removeListener('close', stopDebug); opts.debug('socket end'); debugBytesSent(); clearInterval(debugInterval); } }); }; AlgoliaSearchNodeJS.prototype._promise = { reject: function reject(val) { return Promise.reject(val); }, resolve: function resolve(val) { return Promise.resolve(val); }, delay: function delayPromise(ms) { return new Promise(function resolveOnTimeout(resolve/*, reject*/) { setTimeout(resolve, ms); }); } }; AlgoliaSearchNodeJS.prototype.destroy = function destroy() { if (typeof this._Agent.destroy === 'function') { this._Agent.destroy(); } }; /* * Generate a secured and public API Key from a list of tagFilters and an * optional user token identifying the current user * * @param privateApiKey your private API Key * @param tagFilters the list of tags applied to the query (used as security) * @param userToken an optional token identifying the current user */ AlgoliaSearchNodeJS.prototype.generateSecuredApiKey = function generateSecuredApiKey(privateApiKey, tagFilters, userToken) { if (Array.isArray(tagFilters)) { var strTags = []; for (var i = 0; i < tagFilters.length; ++i) { if (Array.isArray(tagFilters[i])) { var oredTags = []; for (var j = 0; j < tagFilters[i].length; ++j) { oredTags.push(tagFilters[i][j]); } strTags.push('(' + oredTags.join(',') + ')'); } else { strTags.push(tagFilters[i]); } } tagFilters = strTags.join(','); } return crypto.createHmac('sha256', privateApiKey).update(tagFilters + (userToken || '')).digest('hex'); };
JavaScript
0.000002
@@ -2883,33 +2883,28 @@ ns.port === -undefined +null ) %7B%0A @@ -3073,33 +3073,28 @@ ns.port === -undefined +null ) %7B%0A
b5f002293685577770d46be1d1780ad12f29a5ed
add comma
src/angular/Services/reviews.js
src/angular/Services/reviews.js
var services = angular.module('services'); services.factory('Reviews', function() { var factory = {}; var reviews = [ { id: 1, rating: 4, comment: 'This place rocks!!', serviceId: 949606869, }, { id: 2, rating: 1, comment: 'This place sucks!!', serviceId: 213577289, }, { id: 3, rating: 5, comment: 'This place rocks!!', serviceId: 949606869, }, { id: 4, rating: 2, comment: 'This place sucks!!', serviceId: 213577289, }, ]; /** * Returns a review given its id. * GET /reviews/:reviewId */ factory.getReview = function(reviewId) { var review = _.find(reviews, function(review) { return review.id === reviewId; }); return review; }; /** * Returns a list of reviews of a service * GET /services/:serviceId/reviews */ factory.getReviewsByServiceId = function(serviceId) { var reviews = _.filter(reviews, function(review) { return review.serviceId === serviceId; }); return reviews; }; /** * Returns the average rating of a service. */ factory.getAverageRatingByServiceId = function(serviceId) { var average = 0; var reviews = _.filter(reviews, function(review) { return review.serviceId === serviceId; }); _.each(reviews, function(review) { average += review.rating; }); return average/reviews.length; }; /** * Adds a review for a service. * POST /services/:serviceId */ factory.addReview = function(serviceId, rating, comment) { var review = { id: 5 rating: rating, comment: comment, serviceId: serviceId, }; reviews.push(review); return review; }; return factory; });
JavaScript
0.999953
@@ -1880,16 +1880,17 @@ id: 5 +, %0A
d006b3e09f53865d0b56497f96f5921661b724d6
move panel to top when opening
src/app/components/Misc/Pane.js
src/app/components/Misc/Pane.js
import React from 'react'; import Rnd from 'react-rnd'; import { Icon } from '../index'; import { closePane, openPane } from '../../utils/index'; import {movePaneToTop, setPaneConfig} from "../../utils/actions"; import { debounce } from 'lodash'; class Pane extends React.Component { close() { const { dispatch, handle } = this.props; dispatch(closePane(handle)); } updatePositionToStore(x, y, width, height) { const { handle, dispatch, container } = this.props; const containerSize = container.getBoundingClientRect(); const newConfig = { width: width, height: height, x: x, y: y, alignRight: (width + x) >= containerSize.width, alignBottom: (height + y) >= containerSize.height, fullHeight: height >= containerSize.height, fullWidth: width >= containerSize.width }; dispatch(setPaneConfig(handle, newConfig)); } onResizeStop(e, dir, refToElement, delta, position) { const rect = refToElement.getBoundingClientRect(); this.updatePositionToStore(position.x, position.y, rect.width, rect.height); } onDragStop(e, data) { const rect = data.node.getBoundingClientRect(); this.updatePositionToStore(data.x, data.y, rect.width, rect.height); } /** * Make sure that none of the panes go out of bounds when the window is resized * * @type {Function} */ onWindowResize = debounce(() => { const { config, container } = this.props; const containerSize = container.getBoundingClientRect(); const sizeUpdates = { width: config.fullWidth ? containerSize.width : config.width, height: config.fullHeight ? containerSize.height : config.height }; const positionUpdates = { x: config.alignRight && !config.fullWidth ? containerSize.width - config.width : config.x, y: config.alignBottom && !config.fullHeight ? containerSize.height - config.height : config.y }; if (config.fullWidth) { // When we want the full width anyway, it becomes very simple sizeUpdates.width = containerSize.width; } else if ((config.width + config.x) > containerSize.width) { // It won't fit, resize or reposition if (config.width <= containerSize.width) { // It can fit if we reposition it, get the highest possible 'x' positionUpdates.x = containerSize.width - config.width; } else { // It won't fit by only repositioning, we also need to resize positionUpdates.x = 0; sizeUpdates.width = containerSize.width; } } if (config.fullHeight) { // When we want the full height anyway, it becomes very simple sizeUpdates.height = containerSize.height; } else if ((config.height + config.y) > containerSize.height) { // It won't fit, resize or reposition if (config.height <= containerSize.height) { // It can fit if we reposition it, get the highest possible 'y' positionUpdates.y = containerSize.height - config.height; } else { // It won't fit by only repositioning, we also need to resize positionUpdates.y = 0; sizeUpdates.height = containerSize.height; } } this.rnd.updateSize(sizeUpdates); this.rnd.updatePosition(positionUpdates); this.updatePositionToStore(positionUpdates.x, positionUpdates.y, sizeUpdates.width, sizeUpdates.height); }, 300); componentDidMount() { window.addEventListener('resize', () => this.onWindowResize()); } componentDidUpdate(prevProps) { const { config } = this.props; if (prevProps.config.zIndex !== config.zIndex) { this.rnd.updateZIndex(config.zIndex); } } moveToTop() { const { dispatch, handle } = this.props; dispatch(movePaneToTop(handle)); } render() { const { handle, children, name, description, top, container, config } = this.props; const isOpen = config.open; const containerSize = container.getBoundingClientRect(); let descriptionEl = null; if (description) { descriptionEl = <span className="description">{description}</span>; } let style = {}; if (top) { style.top = top + 'px'; } let rndStyle = {}; if (!isOpen) { rndStyle.display = 'none'; } let height; if (config.fullHeight) { height = containerSize.height; } else { height = config.height; } let width; if (config.fullWidth) { width = containerSize.width; } else { width = config.width; } let x; if (config.alignRight) { x = containerSize.width - width; } else { x = config.x; } let y; if (config.alignBottom) { y = containerSize.height - height; } else { y = config.y; } return ( <Rnd default={{ x: x, y: y, width: width, height: height }} minWidth={config.minWidth} minHeight={config.minHeight} bounds=".main" dragHandleClassName=".pane-header" onResizeStop={this.onResizeStop.bind(this)} onDragStop={this.onDragStop.bind(this)} style={rndStyle} ref={rnd => this.rnd = rnd} > <div className={`pane ${handle}`} style={style} onMouseDown={this.moveToTop.bind(this)}> <div className="container-fluid"> <div className="row pane-header"> <div className="col-md-12"> {name} {descriptionEl} <Icon onClick={this.close.bind(this)} name="ion-ios-close shut"/> </div> </div> <div className="row"> <div className="col-md-12 pane-holder"> <div className="col-md-12 pane-content"> {isOpen ? children : null} </div> </div> </div> </div> </div> </Rnd> ); } } export default Pane;
JavaScript
0
@@ -4025,24 +4025,118 @@ );%0A %7D +%0A%0A if (!prevProps.config.open && config.open) %7B%0A this.moveToTop();%0A %7D %0A %7D%0A%0A
0037ecb732976d6f50535b8f3df01ee1338ec7a8
Fix issue with inlines
filer/static/filer/js/addons/dropzone.init.js
filer/static/filer/js/addons/dropzone.init.js
// #DROPZONE# // This script implements the dropzone settings /* globals Dropzone, django */ 'use strict'; if (Dropzone) { Dropzone.autoDiscover = false; } /* globals Dropzone, django */ django.jQuery(function ($) { var dropzoneTemplateSelector = '.js-filer-dropzone-template'; var previewImageSelector = '.js-img-preview'; var dropzoneSelector = '.js-filer-dropzone'; var dropzones = $(dropzoneSelector); var messageSelector = '.js-filer-dropzone-message'; var lookupButtonSelector = '.js-related-lookup'; var progressSelector = '.js-filer-dropzone-progress'; var previewImageWrapperSelector = '.js-img-wrapper'; var filerClearerSelector = '.filerClearer'; var fileChooseSelector = '.js-file-selector'; var fileIdInputSelector = '.vForeignKeyRawIdAdminField'; var dragHoverClass = 'dz-drag-hover'; var hiddenClass = 'hidden'; var mobileClass = 'filer-dropzone-mobile'; var objectAttachedClass = 'js-object-attached'; // var dataMaxFileSize = 'max-file-size'; var minWidth = 500; var checkMinWidth = function (element) { element.toggleClass(mobileClass, element.width() < minWidth); }; var showError = function (message) { try { window.parent.CMS.API.Messages.open({ message: message }); } catch (e) { if (window.filerShowError) { window.filerShowError(message); } else { alert(message); } } }; var createDropzone = function () { var dropzone = $(this); var dropzoneUrl = dropzone.data('url'); var inputId = dropzone.find(fileIdInputSelector); var isImage = inputId.is('[name="image"]'); var lookupButton = dropzone.find(lookupButtonSelector); var message = dropzone.find(messageSelector); var clearButton = dropzone.find(filerClearerSelector); var fileChoose = dropzone.find(fileChooseSelector); if (this.dropzone) { return; } $(window).on('resize', function () { checkMinWidth(dropzone); }); new Dropzone(this, { url: dropzoneUrl, paramName: 'file', maxFiles: 1, // for now disabled as we don't have the correct file size limit // maxFilesize: dropzone.data(dataMaxFileSize) || 20, // MB previewTemplate: $(dropzoneTemplateSelector).html(), clickable: false, addRemoveLinks: false, init: function () { checkMinWidth(dropzone); this.on('removedfile', function () { fileChoose.show(); dropzone.removeClass(objectAttachedClass); this.removeAllFiles(); clearButton.trigger('click'); }); $('img', this.element).on('dragstart', function (event) { event.preventDefault(); }); clearButton.on('click', function () { dropzone.removeClass(objectAttachedClass); inputId.trigger('change'); }); }, maxfilesexceeded: function () { this.removeAllFiles(true); }, drop: function () { this.removeAllFiles(true); fileChoose.hide(); lookupButton.addClass('related-lookup-change'); message.addClass(hiddenClass); dropzone.removeClass(dragHoverClass); dropzone.addClass(objectAttachedClass); }, success: function (file, response) { $(progressSelector).addClass(hiddenClass); if (file && file.status === 'success' && response) { if (response.file_id) { inputId.val(response.file_id); inputId.trigger('change'); } if (response.thumbnail_180) { if (isImage) { $(previewImageSelector).css({ 'background-image': 'url(' + response.thumbnail_180 + ')' }); $(previewImageWrapperSelector).removeClass(hiddenClass); } } } else { if (response && response.error) { showError(file.name + ': ' + response.error); } this.removeAllFiles(true); } $('img', this.element).on('dragstart', function (event) { event.preventDefault(); }); }, error: function (file, response) { showError(file.name + ': ' + response.error); this.removeAllFiles(true); }, reset: function () { if (isImage) { $(previewImageWrapperSelector).addClass(hiddenClass); $(previewImageSelector).css({'background-image': 'none'}); } dropzone.removeClass(objectAttachedClass); inputId.val(''); lookupButton.removeClass('related-lookup-change'); message.removeClass(hiddenClass); inputId.trigger('change'); } }); }; if (dropzones.length && Dropzone) { if (!window.filerDropzoneInitialized) { window.filerDropzoneInitialized = true; Dropzone.autoDiscover = false; } dropzones.each(createDropzone); $('.add-row a').on('click', function () { var dropzones = $(dropzoneSelector); dropzones.each(createDropzone); }); } });
JavaScript
0
@@ -5741,31 +5741,35 @@ $( -'.add-row a').on('click +document).on('formset:added ', f @@ -5769,32 +5769,39 @@ ded', function ( +ev, row ) %7B%0A @@ -5810,32 +5810,42 @@ r dropzones = $( +row).find( dropzoneSelector
7cf40d2a11adea34ca1c152b9285031775a7f461
add matchMaker lib
src/collection.js
src/collection.js
var _ = require('lodash'); var Parser = require('query-parser'); var parse = new Parser(); var defaultFilterName = '__default'; module.exports = function(parent) { var FilteredCollection = parent.extend({ constructor: function(){ parent.apply(this, arguments); this._filters = {}; if(this.superset === true){ this.superset = this.toJSON(); } }, matchMaker: matchMaker, /* jshint: -W071 -W074 */ setFilter: function (filterName, filter) { if (filter === undefined) { filter = filterName; filterName = defaultFilterName; } if (!filter) { return this.removeFilter(filterName); } this._filters[filterName] = { string: filter, query : _.isString(filter) ? parse(filter) : filter }; this.trigger('filtered:set'); if(this.superset){ return this.supersetFetch(); } if(this._filterOptions && this._filterOptions.xhr){ debugger; } this._filterOptions = {data: {filter: this.getFilterOptions()}}; return this.fetch(this._filterOptions); }, /* jshint: +W071 +W074 */ removeFilter: function (filterName) { if (!filterName) { filterName = defaultFilterName; } delete this._filters[filterName]; this.trigger('filtered:remove'); if(this.superset){ return this.supersetFetch(); } return this.fetch({data: {filter: this.getFilterOptions()}}); }, resetFilters: function () { this._filters = {}; this.trigger('filtered:reset'); if(this.superset){ return this.reset(this.superset); } this.reset(); return this.fetch(); }, getFilters: function (name) { if (name) { return this._filters[name]; } return this._filters; }, hasFilter: function (name) { return _.includes(_.keys(this.getFilters()), name); }, hasFilters: function () { return _.size(this.getFilters()) > 0; }, getFilterOptions: function () { if (this.hasFilters()) { var fields = _.isArray(this.fields) ? this.fields.join(',') : this.fields; return {q: this.getFilterQueries(), fields: fields}; } }, getFilterQueries: function () { var queries = _(this.getFilters()).map('query').flattenDeep().value(); // compact if (queries.length > 1) { queries = _.reduce(queries, function (result, next) { if (!_.some(result, function (val) { return _.isEqual(val, next); })) { result.push(next); } return result; }, []); } // extra compact for common simple query if (queries.length === 1 && _.get(queries, [0, 'type']) === 'string') { queries = _.get(queries, [0, 'query']); } return queries; }, supersetFetch: function(){ var self = this; var models = _.filter(this.superset, function(model){ return matchMaker(model, self.getFilterQueries(), {fields: self.fields}); }); return this.reset(models); } }); return FilteredCollection; };
JavaScript
0
@@ -83,16 +83,56 @@ arser(); +%0Avar matchMaker = require('json-query'); %0A%0Avar de
a34c0920c4224f65bb8ac26989c48ecbd817546e
Add OpenCollective gold sponsors manually (#13806)
docs/src/modules/components/HomeBackers.js
docs/src/modules/components/HomeBackers.js
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import NoSsr from '@material-ui/core/NoSsr'; import MarkdownElement from '@material-ui/docs/MarkdownElement'; const styles = theme => ({ root: { backgroundColor: theme.palette.background.paper, minHeight: 600, }, markdownElement: { maxWidth: theme.spacing.unit * 110, margin: 'auto', padding: theme.spacing.unit * 2, }, }); function HomeBackers(props) { const classes = props.classes; return ( <div className={classes.root}> <NoSsr> <MarkdownElement className={classes.markdownElement} text={` ## Supporting Material-UI Material-UI is an MIT-licensed open source project. It's an independent project with ongoing development made possible entirely thanks to the support of these awesome [backers](/discover-more/backers/). ### Gold Sponsors Gold Sponsors are those who have pledged $500/month and more to Material-UI. via [Patreon](https://www.patreon.com/oliviertassinari) <p style="display: flex;"> <a href="https://www.creative-tim.com/?utm_source=material-ui&utm_medium=docs&utm_campaign=homepage" rel="noopener" target="_blank"><img width="126" src="https://avatars1.githubusercontent.com/u/20172349?s=378" alt="creative-tim" title="Premium Themes"></a> <a href="https://bitsrc.io" rel="noopener" target="_blank"><img width="96" src="https://avatars1.githubusercontent.com/u/24789812?s=192" alt="bitsrc" title="The fastest way to share code"></a> </p> via [OpenCollective](https://opencollective.com/material-ui) <p style="max-width: 80vw; overflow: auto;"> <object type="image/svg+xml" data="https://opencollective.com/material-ui/tiers/gold-sponsors.svg?avatarHeight=80&width=600">Gold Sponsors</object> </p> ### There is more! See the full list of [our backers](/discover-more/backers/). `} /> </NoSsr> </div> ); } HomeBackers.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(HomeBackers);
JavaScript
0
@@ -1087,16 +1087,41 @@ y: flex; + justify-content: center; %22%3E%0A %3Ca @@ -1240,33 +1240,65 @@ target=%22_blank%22 -%3E + style=%22margin-right: 8px;%22%3E%0A %3Cimg width=%22126%22 @@ -1402,16 +1402,19 @@ Themes%22%3E +%0A %3C/a%3E%0A %3C @@ -1470,17 +1470,49 @@ %22_blank%22 -%3E + style=%22margin-right: 8px;%22%3E%0A %3Cimg wid @@ -1632,16 +1632,19 @@ e code%22%3E +%0A %3C/a%3E%0A%3C/p @@ -1722,78 +1722,161 @@ le=%22 -max-width: 80vw; overflow: auto;%22%3E%0A %3Cobject typ +display: flex; justify-content: center;%22%3E%0A %3Ca href=%22https://www.call-em-all.com%22 rel=%22noopener%22 target=%22_blank%22 styl e=%22 -i ma -ge/svg+xml%22 data +rgin-right: 8px;%22%3E%0A %3Cimg src =%22ht @@ -1873,32 +1873,39 @@ mg src=%22https:// +images. opencollective.c @@ -1911,92 +1911,441 @@ com/ -material-ui/tiers/gold-sponsors.svg?avatarHeight=80&width=600%22%3EGold Sponsors%3C/object +proxy/images?src=https%253A%252F%252Fopencollective-production.s3-us-west-1.amazonaws.com%252Ff4053300-e0ea-11e7-acf0-0fa7c0509f4e.png&height=100%22%3E%0A %3C/a%3E%0A %3Ca href=%22https://localizejs.com%22 rel=%22noopener%22 target=%22_blank%22 style=%22margin-right: 8px;%22%3E%0A %3Cimg src=%22https://images.opencollective.com/proxy/images?src=https%253A%252F%252Fopencollective-production.s3-us-west-1.amazonaws.com%252F629dea80-f1ae-11e8-b356-a5942970e22b.png&height=70%22%3E%0A %3C/a %3E%0A%3C/
c37d736b7c6c43416a5c3305a3b0531b380b8b26
Add a couple of spoiler emotes
addon/bpm-alttext.js
addon/bpm-alttext.js
// Known spoiler "emotes" to avoid expanding alt-text on. Not all of these are // known to BPM, and it's not really worth moving this to a data file somewhere. // - /spoiler is from r/mylittlepony (and copied around like mad) // - /s is from r/falloutequestria (and r/mylittleanime has a variant) // - #s is from r/doctorwho // - /b and /g are from r/dresdenfiles var spoiler_links = ["/spoiler", "/s", "#s", "/b", "/g"]; /* * Sets the sourceinfo hover on an emote element. */ function add_sourceinfo(element, state, is_emote, is_unknown) { var name = element.getAttribute("href"); var title = ""; if(is_emote) { var subreddit = element.getAttribute("data-bpm_srname"); if(state.indexOf("d") > -1) { title = "Disabled "; if(state.indexOf("n") > -1) { title += "NSFW "; } title += "emote "; } title += name + " from " + subreddit; } else if(is_unknown) { title = "Unknown emote " + name; } element.title = title; } /* * Decides whether or not the alt-text on this element needs to be processed. * Returns bpm_state if yes, null if no. */ function should_convert_alt_text(element, state, is_emote) { // Already processed? Avoid doing silly things like expanding things again // (or our sourceinfo hover) if(state.indexOf("a") > -1) { return false; } // Avoid spoiler links. We can't rely on any emote data to exist, as // of them aren't known as emotes var href = element.getAttribute("href"); if(href && spoiler_links.indexOf(href.split("-")[0]) > -1) { return false; } if(is_emote) { // Emotes require a sourceinfo hover, no matter what return true; } if(!element.title) { // Note, we don't bother setting state="a" in this case return false; } // Work around RES putting tag links and other things with alt-text on // them in the middle of posts- we don't want to expand those. if(element.classList.contains("userTagLink") || element.classList.contains("voteWeight")) { return false; } return true; } /* * Generates the actual alt-text element. Handles embedded links. */ function generate_alt_text(title, container) { // Split on links, so we can turn those into real links. These are rare, // but worth handling nicely. Also prepend a space for formatting- it makes // the most difference on non-emote elements. // (\b doesn't seem to be working when I put it at the end, here?? // Also, note that we do grab the space at the end for formatting) // http:// < domain name > /url?params#stuff var parts = (" " + title).split(/\b(https?:\/\/[a-zA-Z0-9\-.]+(?:\/[a-zA-Z0-9\-_.~'();:+\/?%#]*)?(?:\s|$))/); // Handle items in pairs: one chunk of text and one link at a time for(var j = 0; j < Math.floor(parts.length / 2); j += 2) { if(parts[j]) { container.appendChild(document.createTextNode(parts[j])); } var link_element = document.createElement("a"); link_element.textContent = parts[j + 1]; link_element.href = parts[j + 1]; container.appendChild(link_element); } // The last bit is just text. (And likely the only chunk there is, anyway.) if(parts[parts.length - 1]) { container.appendChild(document.createTextNode(parts[parts.length - 1])); } } function convert_alt_text(element, is_emote, is_unknown) { // If this is an image link, try to put the alt-text on the other side // of the RES expando button. It looks better that way. var before = element.nextSibling; // Thing to put alt-text before while(before && before.className !== undefined && before.classList.contains("expando-button")) { before = before.nextSibling; } // As a note: alt-text kinda has to be a block-level element, in order // to go in the same place as the emote it's attached to. The chief // exception is -in emotes, so as a bit of a hack, we assume the // converter has already run and check for known -in flags. The other // possibility is that this is just a normal link of some kind, so // treat those as special too. var element_type = "div"; if(element.classList.contains("bpflag-in") || element.classList.contains("bpflag-inp") || (!is_emote && !is_unknown)) { element_type = "span"; } // Do the actual conversion var container = document.createElement(element_type); container.classList.add("bpm-alttext"); generate_alt_text(element.title, container); element.parentNode.insertBefore(container, before); } /* * Converts alt-text on an <a> element as appropriate. Will respond to the emote * converter if it has already run on this element. */ function process_alt_text(element) { var state = element.getAttribute("data-bpm_state") || ""; var is_emote = state.indexOf("e") > -1; var is_unknown = state.indexOf("u") > -1; // Early exit- some elements we just ignore completely if(!should_convert_alt_text(element, state, is_emote)) { return; } // Actual alt-text conversion if(element.title) { convert_alt_text(element, is_emote, is_unknown); } // Special support for emotes- replace the alt-text with source info if(is_emote || is_unknown) { add_sourceinfo(element, state, is_emote, is_unknown); } // Mark as handled, so we don't ever run into it again. element.setAttribute("data-bpm_state", state + "a"); }
JavaScript
0.000001
@@ -378,16 +378,21 @@ inks = %5B +%0A %22/spoile @@ -399,30 +399,316 @@ r%22, -%22/s%22, %22#s%22, %22/b%22, %22/g%22 +// r/mylittlepony and many other subreddits%0A %22/s%22, // r/falloutequestria, and a variant in r/mylittleanime%0A %22/g%22, // r/dresdenfiles%0A %22/b%22, // r/dresdenfiles%0A %22#s%22, // r/doctorwho and r/gameofthrones%0A %22#g%22, // r/gameofthrones%0A %22#b%22, // r/gamofthrones%0A %5D;%0A%0A
120a0d2c9ecdec5f47ce0e18e658f345c74d9b33
Update fichaReme.js
app/pdf/fichaReme.js
app/pdf/fichaReme.js
var PdfPrinter = require('pdfmake/src/printer'); var path = require('path'); module.exports = { pdf: function(Ficha) { // PDF Content var dd= { info: { title: Ficha.titulo, author: Ficha.User.facebookname, subject: Ficha.titulo, keywords: 'scouts', creator: 'http://uhluscout.com' }, content: [ { text: '"'+Ficha.titulo+'"', style: 'header'}, { layout: 'headerLineOnly', table: { headerRows: 1, widths: [ 'auto', 'auto', 'auto', '*' ], body: [ [ 'NOMBRE DE LA ACTIVIDAD', 'SECCIÓN', 'ÁREA DE DESARROLLO', 'PARTICIPANTES' ], [ '"'+Ficha.nombreactividad+'"', '"'+Ficha.seccion+'"', '"'+Ficha.areadedesarrollo+'"', '"'+Ficha.participantes+'"' ] ] }, style: 'marginBot' }, { layout: 'headerLineOnly', table: { headerRows: 1, widths: [ '*'], body: [ [ 'DESCRIPCIÓN DE LA ACTIVIDAD'], [ '"'+Ficha.descripcion+'"'] ] }, style: 'marginBot' }, { layout: 'headerLineOnly', table: { headerRows: 1, widths: [ '*'], body: [ [ 'RECOMENDACIONES'], [ '"'+Ficha.recomendaciones+'"'] ] }, style: 'marginBot' }, { layout: 'headerLineOnly', table: { headerRows: 1, widths: [ '*'], body: [ [ 'MATERIALES'], [ { // to treat a paragraph as a bulleted list, set an array of items under the ul key ul: [ 'Item 1', 'Item 2', 'Item 3', ] }, ] ] }, style: 'marginBot' }, { layout: 'headerLineOnly', table: { headerRows: 1, widths: [ '*', '*', '*'], body: [ [ 'TIEMPOS', 'AUTOR', 'FECHA'], [ '"'+Ficha.tiempos+'"', '"'+Ficha.User.facebookname+'"', '"'+Ficha.created_at+'"'] ] }, style: 'marginBot' }, { text: 'Ficha Elaborada y descargada desde http://uhluscout.com', link: 'http://uhluscout.com', style: 'footer'} ], styles: { header: { fontSize: 22, bold: true, alignment: 'right', margin: [ 0, 0, 0, 25 ] }, marginBot:{ margin: [ 0, 0, 0, 25 ] }, footer: { bold: true, alignment: 'right' }, } }//end dd var fontDescriptors = { Roboto: { normal: path.join(__dirname, '/fonts/Roboto-Regular.ttf'), bold: path.join(__dirname, '/fonts/Roboto-Medium.ttf'), italics: path.join(__dirname, '/fonts/Roboto-Italic.ttf'), bolditalics: path.join(__dirname, '/fonts/Roboto-MediumItalic.ttf') } }; var printer = new PdfPrinter(fontDescriptors); return printer.createPdfKitDocument(dd); } };
JavaScript
0
@@ -117,24 +117,284 @@ n(Ficha) %7B%0D%0A + // Parsear materiales string a array%0D%0A var materiales =%5B%5D;%0D%0A Ficha.materiales.split(%22%3Cbr%3E%22).slice(0,Ficha.materiales.split('%3Cbr%3E').length - 1).forEach(function(material)%7B%0D%0A materiales.push(%7B%22material%22:material%7D);%0D%0A %7D);%0D%0A // P @@ -468,28 +468,43 @@ title: +''+ Ficha. -titulo +nombreactividad+'' ,%0D%0A @@ -522,16 +522,19 @@ author: +''+ Ficha.Us @@ -548,16 +548,19 @@ bookname ++'' ,%0D%0A @@ -579,28 +579,43 @@ ubject: +''+ Ficha. -titulo +nombreactividad+'' ,%0D%0A @@ -760,25 +760,24 @@ text: ' -%22 '+Ficha. titulo+' @@ -772,17 +772,25 @@ cha. -titulo +nombreactividad +' -%22 ', s @@ -1200,33 +1200,32 @@ %5B ' -%22 '+Ficha.nombreac @@ -1233,22 +1233,20 @@ ividad+' -%22 ', ' -%22 '+Ficha. @@ -1254,22 +1254,20 @@ eccion+' -%22 ', ' -%22 '+Ficha. @@ -1284,22 +1284,20 @@ rrollo+' -%22 ', ' -%22 '+Ficha. @@ -1311,17 +1311,16 @@ pantes+' -%22 ' %5D%0D%0A @@ -1749,33 +1749,32 @@ %5B ' -%22 '+Ficha.descripc @@ -1778,17 +1778,16 @@ ipcion+' -%22 '%5D%0D%0A @@ -2203,33 +2203,32 @@ %5B ' -%22 '+Ficha.recomend @@ -2236,17 +2236,16 @@ ciones+' -%22 '%5D%0D%0A @@ -2856,185 +2856,18 @@ ul: -%5B%0D%0A 'Item 1',%0D%0A 'Item 2',%0D%0A 'Item 3',%0D%0A %5D +materiales %0D%0A @@ -3380,17 +3380,16 @@ %5B ' -%22 '+Ficha. @@ -3397,22 +3397,20 @@ iempos+' -%22 ', ' -%22 '+Ficha. @@ -3432,14 +3432,12 @@ me+' -%22 ', ' -%22 '+Fi @@ -3452,17 +3452,16 @@ ted_at+' -%22 '%5D%0D%0A
56a7d8befffa48399981c626e9ebdfd2e38e1842
Add fragments to merged props
breezy/lib/utils/react.js
breezy/lib/utils/react.js
import { visit, remote, saveAndProcessPage, copyPage, } from '../action_creators' import { urlToPageKey } from './url' export function mapStateToProps( state = { pages: {}, breezy: {} }, ownProps ) { let pageKey = ownProps.pageKey let params = ownProps const csrfToken = state.breezy.csrfToken pageKey = urlToPageKey(pageKey) const { data, flash } = state.pages[pageKey] || { data: {}, flash: {}, } return { ...data, ...params, pageKey, csrfToken, flash } } export const mapDispatchToProps = { saveAndProcessPage, copyPage, } export const mapDispatchToPropsIncludingVisitAndRemote = { visit, remote, saveAndProcessPage, copyPage, }
JavaScript
0.000001
@@ -361,16 +361,27 @@ a, flash +, fragments %7D = sta @@ -432,16 +432,35 @@ sh: %7B%7D,%0A + fragments: %5B%5D,%0A %7D%0A re @@ -511,16 +511,27 @@ n, flash +, fragments %7D%0A%7D%0A%0Aex
cbf4b01cf2c850a66858145ce6e2c8093f271d9c
Remove obsolete import of handleRequest function.
apps/storage/main.js
apps/storage/main.js
import('helma.webapp', 'webapp'); import('model'); var handleRequest = webapp.handleRequest; // the main action is invoked for http://localhost:8080/ // this also shows simple skin rendering function index_action(req, res) { if (req.params.save) { createBook(req, res); } if (req.params.remove) { removeBook(req, res); } var books = model.Book.all(); res.render('skins/index.html', { title: 'Storage Demo', books: function(/*tag, skin, context*/) { var buffer = []; for (var i in books) { var book = books[i] buffer.push(book.getFullTitle(), getDeleteLink(book), "<br>\r\n"); } return buffer.join(' '); } }); } function createBook(req, res) { var author = new model.Author({name: req.params.author}); var book = new model.Book({author: author, title: req.params.title}); // author is saved transitively book.save(); res.redirect('/'); } function removeBook(req, res) { var book = model.Book.get(req.params.remove); // author is removed through cascading delete book.remove(); res.redirect('/'); } function getDeleteLink(book) { return '<a href="/?remove=' + book._id + '">delete</a>'; } if (__name__ == "__main__") { webapp.start(); }
JavaScript
0.999826
@@ -49,51 +49,8 @@ );%0A%0A -var handleRequest = webapp.handleRequest;%0A%0A // t
5963ffe36b2bfdb5c0294546ba33c0a00e29bfe4
Fix eslint issue
assets/js/scripts.js
assets/js/scripts.js
$(function(){ // Helper function to show all except filtered sites // Accepts a function which returns true for $(".site-block") elements // matching desired qualifications function hideFilteredSites(filterFunction) { var $sites = $(".sites section"); $sites.show().filter(filterFunction).hide(); if ( ! $(".site-block").is(":visible")) { $(".no-results").show(); } } function setWindowHash(value) { window.location.hash = value; } function getDecodedWindowHash() { return decodeURIComponent(window.location.hash); } // Search function function updateSearch() { if ($(".no-results").is(":visible")) { $(".no-results").hide(); } var hash = getDecodedWindowHash(); var term = hash.substr(1); hideFilteredSites(function() { var siteHeader = $(this).find(".site-header")[0]; var siteTitle = siteHeader.innerText.trim().toLowerCase(); var siteUrl = siteHeader.href.toLowerCase(); var lowerTerm = term.toLowerCase(); // returns true if lowerTerm isn"t found in site title or URL return Math.max(siteTitle.indexOf(lowerTerm), siteUrl.indexOf(lowerTerm)) === -1; }); // Insert the term into the search field // (sometimes this is missed if the hash is changed directly) $("#search").val(term); } $("body").addClass("js-on"); // A - Z filtering $(".alpha-sort a").click(function(e){ e.preventDefault(); var term = $(this).text().toLowerCase(); hideFilteredSites(function() { var text = $(this).find(".site-header").text().trim().toLowerCase().substr(1,1); return !~text.indexOf(term); }); }); // Difficulty filtering $(".diff-sort a").click(function(e){ e.preventDefault(); var term = $(this).text().toLowerCase(); hideFilteredSites(function() { var text = $(this).find(".site-difficulty").text().trim().toLowerCase(); return !~text.indexOf(term); }); }); // Popular filtering $("button.popular").click(function(e){ e.preventDefault(); var term = "popular"; hideFilteredSites(function() { return typeof $(this)[0].dataset["popular"] === "undefined"; }); }); // Clear search and filtering $("button.reset").click(function(e){ var $sites = $(".sites section"); $sites.show(); $(".no-results").hide(); $("input").val(""); if (window.location.href.includes("#") && getDecodedWindowHash()) { setWindowHash(""); } }); // Toggle visibility of site info boxes $(".contains-info").click(function(e) { e.preventDefault(); if ($(this).prev().hasClass("toggled")) { $(this).prev().slideToggle().removeClass("toggled"); } else { $(".toggled").slideToggle().removeClass("toggled"); $(this).prev().slideToggle().addClass("toggled"); } }); // When the search field changes, update the hash var hashUpdateTimer; $("input").on("input", function(){ window.clearTimeout(hashUpdateTimer); hashUpdateTimer = setTimeout(setWindowHash, 250, $(this).val()); }); // Call updateSearch when hash changes $(window).on("hashchange", function() { updateSearch(); }); // Update search results on page load (if there is a hash) if (getDecodedWindowHash() && getDecodedWindowHash() !== "#") { // Insert the term into the field $("#search").val(getDecodedWindowHash().substr(1)); // Update the results updateSearch(); } // jQuery ScrollTo plugin from http://lions-mark.com/jquery/scrollTo/ $.fn.scrollTo = function(target, options, callback ) { if(typeof options === "function" && arguments.length === 2){ callback = options; options = target; } var settings = $.extend({ scrollTarget : target, offsetTop : 50, duration : 500, easing : "swing" }, options); return this.each(function() { var scrollPane = $(this); var scrollTarget = (typeof settings.scrollTarget === "number") ? settings.scrollTarget : $(settings.scrollTarget); var scrollY = (typeof scrollTarget === "number") ? scrollTarget : scrollTarget.offset().top + scrollPane.scrollTop() - parseInt(settings.offsetTop); scrollPane.animate({scrollTop : scrollY }, parseInt(settings.duration), settings.easing, function(){ if (typeof callback === "function") { callback.call(this); } }); }); } // Banner scroll to bottom $(".banner").click(function(e) { e.preventDefault(); $("body,html").scrollTo(".banner-block"); }); $(".info").click(function(e) { e.preventDefault(); $("body,html").scrollTo(".about"); }); });
JavaScript
0.000003
@@ -4812,32 +4812,33 @@ %7D);%0A %7D +; %0A%0A // Banner
9b61fd6f366d82c2d6233ce070f32d2edd382889
Update startup.js
assets/js/startup.js
assets/js/startup.js
/*global Modernizr, FileReaderJS, MFAApp MFAAppView, TimelineView */ // test to see if we can do cool download or fallback style. Modernizr .addTest("blobbuilder", !!(window.BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder)) .addTest("bloburls", !!(window.URL && window.URL.createObjectURL || window.webkitURL && window.webkitURL.createObjectURL)) .addTest("download", "download" in document.createElement("a")) .addTest("formdata", !!(window.FormData && "append" in window.FormData.prototype)); if(!Modernizr.download && $('#saveasbro').length == 0) { var iframe = document.createElement("iframe"); iframe.src = "http://saveasbro.com/gif/"; iframe.setAttribute('style', 'position: absolute; visibility: hidden; left: -999em;'); iframe.id = "saveasbro"; document.body.appendChild(iframe); } // Bail out if the browser doesn't support required features // blobbuilder and a[download] are not required, as there is a fallback var support = FileReaderJS.enabled && Modernizr.draganddrop && document.querySelector && Modernizr.postmessage && window.JSON; if (!support) { $("body").addClass("disabled"); var caniscript = document.createElement('script'); caniscript.src = 'http://api.html5please.com/json+filereader+draganddrop+querySelector+postmessage.json?callback=canicallback&texticon&html&readable'; document.body.appendChild(caniscript); } else { window.appView = new MFAAppView({model: new MFAApp()}); // drag and drop file setup. var opts = { accept: 'image/*', on: { beforestart: function(file) { if (file.size > MFAApp.MAX_BYTES) { return false; } }, error: function(file) { $('div#inimglist').trigger('filedroperror', file); }, load: function(e, file) { $('div#inimglist').trigger('filedropsuccess', [e.target.result, file]); } } }; // the library handles most of the dnd bits. FileReaderJS.setupDrop(document.body, opts); FileReaderJS.setupClipboard(document.body, opts); } function canicallback(data) { $('#dropArea').html(data.html); }
JavaScript
0
@@ -536,16 +536,68 @@ ));%0A%0Aif( + ( !Modernizr.bloburls %7C%7C !Modernizr.blobbuilder %7C%7C !Moderni @@ -607,16 +607,18 @@ download + ) && $('#
75da26cfcd068a9f1e15e07289e8250df3aab165
Check `custom_scripts + 1` instead of itself
packages/react-app-rewired/config/paths.js
packages/react-app-rewired/config/paths.js
// @remove-on-eject-begin /** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ // @remove-on-eject-end var path = require('path'); var fs = require('fs'); //try to detect if user is using a custom scripts version var custom_scripts = process.argv.indexOf('--scripts-version'); if(custom_scripts > -1 && custom_scripts <= process.argv.length){ custom_scripts = process.argv[custom_scripts + 1]; } const scriptVersion = custom_scripts || 'react-scripts'; const projectDir = path.resolve(fs.realpathSync(process.cwd())); const scriptVersionDir = path.join(projectDir, 'node_modules', scriptVersion); // Make sure any symlinks in the project folder are resolved: // https://github.com/facebookincubator/create-react-app/issues/637 var appDirectory = fs.realpathSync(process.cwd()); function resolveApp(relativePath) { return path.resolve(appDirectory, relativePath); } // We support resolving modules according to `NODE_PATH`. // This lets you use absolute paths in imports inside large monorepos: // https://github.com/facebookincubator/create-react-app/issues/253. // It works similar to `NODE_PATH` in Node itself: // https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders // We will export `nodePaths` as an array of absolute paths. // It will then be used by Webpack configs. // Jest doesn’t need this because it already handles `NODE_PATH` out of the box. // Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored. // Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims. // https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421 var nodePaths = (process.env.NODE_PATH || '') .split(process.platform === 'win32' ? ';' : ':') .filter(Boolean) .filter(folder => !path.isAbsolute(folder)) .map(resolveApp); // config after eject: we're in ./config/ module.exports = { scriptVersion:scriptVersion, projectDir:projectDir, scriptVersionDir:scriptVersionDir, appBuild: resolveApp('build'), appPublic: resolveApp('public'), appHtml: resolveApp('public/index.html'), appIndexJs: resolveApp('src/index.js'), appPackageJson: resolveApp('package.json'), appSrc: resolveApp('src'), yarnLockFile: resolveApp('yarn.lock'), testsSetup: resolveApp('src/setupTests.js'), appNodeModules: resolveApp('node_modules'), ownNodeModules: resolveApp('node_modules'), nodePaths: nodePaths }; // @remove-on-eject-begin function resolveOwn(relativePath) { return path.resolve(__dirname, relativePath); } // config before eject: we're in ./node_modules/react-scripts/config/ module.exports = { scriptVersion:scriptVersion, projectDir:projectDir, scriptVersionDir:scriptVersionDir, appBuild: resolveApp('build'), appPublic: resolveApp('public'), appHtml: resolveApp('public/index.html'), appIndexJs: resolveApp('src/index.js'), appPackageJson: resolveApp('package.json'), appSrc: resolveApp('src'), yarnLockFile: resolveApp('yarn.lock'), testsSetup: resolveApp('src/setupTests.js'), appNodeModules: resolveApp('node_modules'), // this is empty with npm3 but node resolution searches higher anyway: ownNodeModules: resolveOwn('../node_modules'), nodePaths: nodePaths }; // config before publish: we're in ./packages/react-scripts/config/ if (__dirname.indexOf(path.join('packages', 'react-scripts', 'config')) !== -1) { module.exports = { scriptVersion:scriptVersion, projectDir:projectDir, scriptVersionDir:scriptVersionDir, appBuild: resolveOwn('../../../build'), appPublic: resolveOwn('../template/public'), appHtml: resolveOwn('../template/public/index.html'), appIndexJs: resolveOwn('../template/src/index.js'), appPackageJson: resolveOwn('../package.json'), appSrc: resolveOwn('../template/src'), yarnLockFile: resolveOwn('../template/yarn.lock'), testsSetup: resolveOwn('../template/src/setupTests.js'), appNodeModules: resolveOwn('../node_modules'), ownNodeModules: resolveOwn('../node_modules'), nodePaths: nodePaths }; } // @remove-on-eject-end
JavaScript
0
@@ -571,16 +571,20 @@ scripts ++ 1 %3C= proce
36da171a3dbfeb632fab044e2996a7b9ff6babf8
Set status button in serial no
erpnext/stock/doctype/serial_no/serial_no.js
erpnext/stock/doctype/serial_no/serial_no.js
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt cur_frm.add_fetch("customer", "customer_name", "customer_name") cur_frm.add_fetch("supplier", "supplier_name", "supplier_name") cur_frm.add_fetch("item_code", "item_name", "item_name") cur_frm.add_fetch("item_code", "description", "description") cur_frm.add_fetch("item_code", "item_group", "item_group") cur_frm.add_fetch("item_code", "brand", "brand") cur_frm.cscript.onload = function() { cur_frm.set_query("item_code", function() { return erpnext.queries.item({"is_stock_item": "Yes", "has_serial_no": "Yes"}) }); }; frappe.ui.form.on("Serial No", "refresh", function(frm) { frm.toggle_enable("item_code", frm.doc.__islocal); });
JavaScript
0.000045
@@ -764,12 +764,292 @@ local);%0A -%7D); +%0A%09if(frm.doc.status == %22Sales Returned%22 && frm.doc.warehouse)%0A%09%09cur_frm.add_custom_button(__('Set Status as Available'), cur_frm.cscript.set_status_as_available);%0A%7D);%0A%0Acur_frm.cscript.set_status_as_available = function() %7B%0A%09cur_frm.set_value(%22status%22, %22Available%22);%0A%09cur_frm.save()%0A%7D %0A
445da8c78045265c9183038aa81a5b0b897942a8
update examples for checkbox and radiobutton
examples/simple-form/src/containers/index.js
examples/simple-form/src/containers/index.js
import React from 'react'; import styled from 'styled-components'; import { Form, Button, Checkbox, Date, Datetime, Email, Number, Password, Phonenumber, Radio, Text, Textarea, Time, } from '../../../../lib/index'; const Wrapper = styled.section` position: relative; width: 50%; left: 25%; font-family: sans-serif; text-align: center; border-radius: 1.5em; background: #FFF; border: 1px solid #AAA; margin: 2em; `; const Title = styled.h1` position: relative; color: #AAA; `; class Index extends React.Component { constructor(props) { super(props); this.state = { results: [], }; } handleOnClick(results) { this.setState({ results, }); } render() { return ( <div > <Wrapper> <Title> Redux Valid Form </Title> <Form id="1"> <Checkbox id="checkbox" value="Vehicle" name="Vehicle" required="true" /> <Radio id="radio-1" value="Car" name="vehicle" checked /> <Radio id="radio-2" value="Bicycle" name="vehicle" /> {/* <Date id="date" required="true" /> <Datetime id="datetime" required="true" /> <Email id="email" required="true" /> <Number id="number" required="true" min={2} max={4} /> <Password id="password" required="true" min={8} max={12} /> <Phonenumber id="phonenumber" required="true" /> <Text id="text" required="true" min={5} max={20} /> <Textarea id="textarea" required="true" /> <Time id="time" required="true" />*/} <Button value="Click me!" onClick={(results) => this.handleOnClick(results)} /> </Form> </Wrapper> <Wrapper> {'results: {'} {Object.keys(this.state.results).map((keyName) => ( <div key={`item-${keyName}`}> {`${keyName}: ${this.state.results[keyName]},`} </div> ))} {'}'} </Wrapper> </div> ); } } export default Index;
JavaScript
0
@@ -940,39 +940,40 @@ ehicle%22 required -=%22true%22 + checked /%3E%0A @@ -1112,11 +1112,77 @@ -%7B/* +%3CRadio id=%22radio-3%22 value=%22Rollerblade%22 name=%22vehicle%22 /%3E%0A %3CDa @@ -1194,39 +1194,32 @@ =%22date%22 required -=%22true%22 /%3E%0A @@ -1242,39 +1242,32 @@ tetime%22 required -=%22true%22 /%3E%0A @@ -1284,39 +1284,32 @@ %22email%22 required -=%22true%22 /%3E%0A @@ -1327,32 +1327,16 @@ %22number%22 - required=%22true%22 min=%7B2%7D @@ -1343,16 +1343,25 @@ max=%7B4%7D + required /%3E%0A @@ -1391,32 +1391,16 @@ assword%22 - required=%22true%22 min=%7B8%7D @@ -1408,16 +1408,25 @@ max=%7B12%7D + required /%3E%0A @@ -1463,39 +1463,32 @@ number%22 required -=%22true%22 /%3E%0A @@ -1506,41 +1506,34 @@ ext%22 - required=%22true%22 min=%7B -5 +4 %7D max=%7B -2 +1 0%7D + required /%3E%0A @@ -1572,76 +1572,36 @@ ea%22 -required=%22true%22 /%3E%0A %3CTime id=%22time%22 required=%22true%22 /%3E*/%7D +min=%7B4%7D max=%7B10%7D required /%3E %0A
bebe5e6e02c651c614c9ff19b7ef074009b7a5c8
use more hooks and correct options
examples/with-devcert-https/razzle.config.js
examples/with-devcert-https/razzle.config.js
'use strict'; module.exports = { modifyWebpackOptions(opts) { const options = opts.webpackOptions; return new Promise(async (resolve) => { const httpsCredentials = await devcert.certificateFor('localhost'); const stringHttpsCredentials = { key: httpsCredentials.key.toString(), cert: httpsCredentials.cert.toString() }; if (opts.env.target === 'node' && opts.env.dev) { options.definePluginOptions.HTTPS_CREDENTIALS = JSON.stringify(stringHttpsCredentials); } if (opts.env.target === 'web' && opts.env.dev) { options.HTTPS_CREDENTIALS = httpsCredentials; } resolve(options); }); }, modifyWebpackConfig(opts) { const config = opts.webpackConfig; const options = opts.webpackOptions; if (opts.env.target === 'web' && opts.env.dev) { config.devServer.https = options.HTTPS_CREDENTIALS; } return config; }, };
JavaScript
0.000001
@@ -35,23 +35,16 @@ modify -Webpack Options( @@ -42,32 +42,86 @@ yOptions(opts) %7B + // use modifyOptions so certificateFor is called once %0A const optio @@ -122,39 +122,46 @@ options = opts. -webpack +options.razzle Options;%0A ret @@ -422,87 +422,9 @@ -if (opts.env.target === 'node' && opts.env.dev) %7B%0A options.definePluginO +o ptio @@ -450,23 +450,8 @@ S = -JSON.stringify( stri @@ -472,21 +472,126 @@ ials +;%0A resolve(options );%0A +%7D);%0A %7D +, %0A +modifyWebpackOptions(opts) %7B%0A const options = opts.options.razzleOptions;%0A @@ -607,35 +607,36 @@ env.target === ' -web +node ' && opts.env.de @@ -642,34 +642,32 @@ ev) %7B%0A - options. HTTPS_CREDEN @@ -658,84 +658,115 @@ ons. -HTTPS_CREDENTIALS = httpsCredentials +definePluginOptions.HTTPS_CREDENTIALS = JSON.stringify(options.HTTPS_CREDENTIALS) ;%0A - %7D%0A - - re -solve( +turn options -);%0A %7D) ;%0A @@ -818,24 +818,32 @@ nfig = opts. +options. webpackConfi @@ -870,23 +870,30 @@ = opts. -webpack +options.razzle Options;
9b5023be5bf43b06720966dce7aabf1d015709cd
Update dropzone-directive.js
frontend/app/directives/dropzone-directive.js
frontend/app/directives/dropzone-directive.js
define(['./module','dropzone'], function(directives,Dropzone){ directives.directive('drop', function(){ return function(scope,element,attrs){ var config, drop; config = scope[attrs.drop]; //create a Dropzone for the element with the given options drop = new Dropzone(element[0], config.options); var submitButton = document.querySelector("#btn-submit"); var myDropzone = drop; var counter = 0; submitButton.addEventListener("click", function() { if (myDropzone.files.length > 0) { myDropzone.processQueue(); } else { myDropzone.uploadFile({name:"",length:0}); //send empty } }); myDropzone.on("addedfile", function(file) { var arr = document.getElementsByClassName("dz-preview"); for (var i = counter; i < arr.length; i++){ arr[i].addEventListener('click', function(e) { e.stopPropagation(); e.preventDefault(); }); } counter++; // Add the button to the file preview element. var removeButton = Dropzone.createElement("<div class='remove_btn'></div>"); var commentField = Dropzone.createElement("<textarea type='text' name='description" + "' class='comment_field' placeholder='Додайте опіс до фото...' maxlength='200'></textarea>"); file.previewElement.appendChild(removeButton); file.previewElement.appendChild(commentField); removeButton.addEventListener("click", myFunction); function myFunction(e) { myDropzone.removeFile(file); counter--; e.stopPropagation(); }; }); myDropzone.on('successmultiple', function() { if(scope.isLoggedIn()){ scope.submitProblem(); scope.swipeHide("dropzone"); window.location.href="#/map"; } else { scope.swipeHide("dropzone"); window.location.href="#/map"; alert('Ви не зареєстрований користувач, тому проблема спочатку пройде модерацію і потім буде додана на карту.'); } }); //bind the given event handlers angular.forEach(config.eventHandlers,function (handler, event){ drop.on(event, handler); }); }; }); });
JavaScript
0
@@ -621,24 +621,417 @@ gth %3E 0) %7B%0D%0A + for(var i=0;i%3Cdocument.upload_photo.description.length;i++)%7B%0D%0A console.log(upload_photo.description%5Bi%5D.value);%0D%0A if( document.upload_photo.description%5Bi%5D.value==%22%22)%7B%0D%0A document.upload_photo.description%5Bi%5D.value = %22 %22;%0D%0A %0D%0A %7D%0D%0A %7D%0D%0A
439b2293cd687fedfaede3b70e3879f282fa28bd
Fix exception when no service UUIDs are advertised
src/BluetoothDevice.js
src/BluetoothDevice.js
const EventTarget = require('./EventTarget'); const {fromNobleUuid, uuidToName} = require('./utils'); const BluetoothRemoteGATTServer = require('./BluetoothRemoteGATTServer'); /* events [X] gattserverdisconnected [ ] serviceadded [ ] servicechanged [ ] serviceremoved [ ] characteristicvaluechanged */ class BluetoothDevice extends EventTarget { constructor(peripheral) { super(); this._peripheral = peripheral; this._uuids = this._peripheral.advertisement.serviceUuids.map(fromNobleUuid); this._gatt = new BluetoothRemoteGATTServer(this); } _updateFromDuplicate(device) { if (this._uuids.length > device.uuids.length) return; this._peripheral = device._peripheral; this._uuids = device._uuids; } get id() { return this._peripheral.id; // this._peripheral.uuid } get name() { return this._peripheral.name || this._peripheral.advertisement.localName; } get uuids() { return this._uuids; } get gatt() { return this._gatt; } get rssiNonStandard() { return this._peripheral.rssi; } watchAdvertisements() { throw new Error('watchAdvertisements is not yet implemented'); } unwatchAdvertisements() { throw new Error('unwatchAdvertisements is not yet implemented'); } get watchingAdvertisements() { throw new Error('watchingAdvertisements is not yet implemented'); } toJSON() { return { id: this.id, name: this.name, uuids: this.uuids, rssi: this.rssiNonStandard }; } toString() { const name = this.name || 'No name'; const rssi = this.rssiNonStandard + 'dB'; const services = this.uuids.length ? JSON.stringify(this.uuids.map(uuidToName)) : '[no services advertised]'; return rssi + ' - ' + name + ' ' + services; } } module.exports = BluetoothDevice;
JavaScript
0.000016
@@ -433,22 +433,56 @@ uuids = -this._ +peripheral.advertisement.serviceUuids ? peripher @@ -529,16 +529,21 @@ bleUuid) + : %5B%5D ;%0A%09%09this
cd6b678b5181388641609424f7c91c323f872801
add support for exportdeclarations to constants
lib/6to5/transformation/transformers/es6-constants.js
lib/6to5/transformation/transformers/es6-constants.js
var traverse = require("../../traverse"); var t = require("../../types"); var _ = require("lodash"); exports.Program = exports.BlockStatement = exports.ForInStatement = exports.ForOfStatement = exports.ForStatement = function (node, parent, file) { var hasConstants = false; var constants = {}; /** * Check the results of `util.getIds` as `names` generated from a * node against it's parent. */ var check = function (parent, names, scope) { for (var name in names) { var nameNode = names[name]; if (!_.has(constants, name)) continue; if (parent && t.isBlockStatement(parent) && parent !== constants[name]) continue; if (scope) { var defined = scope.get(name); if (defined && defined === nameNode) continue; } throw file.errorWithNode(nameNode, name + " is read-only"); } }; var getIds = function (node) { return t.getIds(node, true, ["MemberExpression"]); }; /** * Collect all constants in this scope. */ _.each(node.body, function (child, parent) { if (child && t.isVariableDeclaration(child, { kind: "const" })) { for (var i in child.declarations) { var declar = child.declarations[i]; var ids = getIds(declar); for (var name in ids) { var nameNode = ids[name]; var names = {}; names[name] = nameNode; check(parent, names); constants[name] = parent; hasConstants = true; } declar._ignoreConstant = true; } child._ignoreConstant = true; child.kind = "let"; } }); if (!hasConstants) return; traverse(node, function (child, parent, scope) { if (child._ignoreConstant) return; if (t.isVariableDeclaration(child)) return; if (t.isVariableDeclarator(child) || t.isDeclaration(child) || t.isAssignmentExpression(child)) { check(parent, getIds(child), scope); } }); };
JavaScript
0
@@ -1074,17 +1074,88 @@ if ( -child && +t.isExportDeclaration(child)) %7B%0A child = child.declaration;%0A %7D%0A%0A if ( t.is
de06ff832a26302b5df088ab602070c45e7efe5f
Remove copying of options
lib/node_modules/@stdlib/types/ndarray/lib/ndarray.js
lib/node_modules/@stdlib/types/ndarray/lib/ndarray.js
'use strict'; // MODULES // var shape2strides = require( '@stdlib/types/ndarray/base/shape2strides' ); var strides2offset = require( '@stdlib/types/ndarray/base/strides2offset' ); var validate = require( './validate.js' ); var defaults = require( './defaults.json' ); var getType = require( './dtype.js' ); var createBuffer = require( './create_buffer.js' ); var castBuffer = require( './cast_buffer.js' ); var ctor = require( './get_ctor.js' ); // MAIN // /** * Returns a multidimensional array. * * @param {Options} options - function options * @param {(ArrayLikeObject|TypedArrayLike|Buffer)} [options.buffer] - underlying data buffer * @param {string} [options.dtype="float64"] - underlying storage data type (if the input data is not of the same type, this option specifies the data type to which to cast the input data) * @param {string} [options.order="row-major"] - specifies whether an array is row-major (C-style) or column-major (Fortran-style) * @param {NonNegativeIntegerArray} [options.shape] - array shape * @param {IntegerArray} [options.strides] - index strides which specify how to access data along corresponding array dimensions * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {Error} must provide either a `shape` or `buffer` option * @throws {Error} number of strides must match number of dimensions * @throws {RangeError} buffer size must be compatible with desired array shape * @returns {ndarray} ndarray instance * * @example * TODO */ function ndarray( options ) { var strides; var offset; var buffer; var dtype; var shape; var ndims; var opts; var err; var len; var i; opts = {}; opts.order = defaults.order; // TODO: consider punting validation to constructor for certain options err = validate( opts, options ); if ( err ) { throw err; } // If not provided a shape, infer from a provided data buffer... if ( opts.shape ) { ndims = opts.shape.length; len = 1; // Compute the total number of elements... shape = new Array( ndims ); for ( i = 0; i < ndims; i++ ) { shape[ i ] = opts.shape[ i ]; len *= opts.shape[ i ]; } } else if ( opts.buffer ) { ndims = 1; len = opts.buffer.length; // Assume a 1-dimensional array (vector): opts.shape = new Array( 1 ); opts.shape[ 0 ] = len; } else { throw new Error( 'invalid input argument. Must provide either a `shape` or `buffer` option. Value: `' + JSON.stringify( options ) + '`.' ); } // If not provided strides, compute them... if ( opts.strides ) { strides = new Array( ndims ); for ( i = 0; i < ndims; i++ ) { strides[ i ] = opts.strides[ i ]; } } else { // TODO: if not provided an order, infer the order (see strides2order)... strides = shape2strides( shape, opts.order ); } // Determine the index "offset": offset = strides2offset( shape, strides ); // TODO: if provided an order differing from that inferred from strides, need to convert to that order. See https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.array.html#numpy.array. // TODO: support a `copy` option? // If not provided a data buffer, create it; otherwise, see if we need to cast a provided buffer to another data type... dtype = opts.dtype || defaults.dtype; if ( opts.buffer ) { if ( getType( opts.buffer ) === dtype ) { buffer = opts.buffer; } else { buffer = castBuffer( opts.buffer, len, dtype ); } } else { buffer = createBuffer( len, dtype ); } // Return a new ndarray: return ctor( dtype, ndims )( buffer, shape, strides, offset, opts.order ); } // end FUNCTION ndarray() // EXPORTS // module.exports = ndarray;
JavaScript
0
@@ -171,24 +171,83 @@ 2offset' );%0A +var numel = require( '@stdlib/types/ndarray/base/numel' );%0A var validate @@ -1727,16 +1727,8 @@ len; -%0A%09var i; %0A%0A%09o @@ -1999,219 +1999,75 @@ %7B%0A%09%09 -ndims = opts.shape.length;%0A%09%09len = 1;%0A%0A%09%09// Compute the total number of elements...%0A%09%09shape = new Array( ndims );%0A%09%09for ( i = 0; i %3C ndims; i++ ) %7B%0A%09%09%09shape%5B i %5D = opts.shape%5B i %5D +shape = opts.shape;%0A%09%09ndims = shape.length ;%0A%09%09 -%09 len -* = -opts.shape%5B i %5D;%0A%09%09%7D +numel( shape ); %0A%09%7D @@ -2180,21 +2180,16 @@ tor):%0A%09%09 -opts. shape = @@ -2206,21 +2206,16 @@ 1 );%0A%09%09 -opts. shape%5B 0 @@ -2463,112 +2463,22 @@ s = -new Array( ndims );%0A%09%09for ( i = 0; i %3C ndims; i++ ) %7B%0A%09%09%09strides%5B i %5D = opts.strides%5B i %5D;%0A%09%09%7D%0A%09%7D else %7B +opts.strides;%0A %0A%09%09/ @@ -2550,16 +2550,26 @@ der)...%0A +%09%7D else %7B%0A %09%09stride
e2da074956e910febeaf83f3cbf2a19034f29937
Remove react resolver from webpack config
SingularityUI/webpack.config.js
SingularityUI/webpack.config.js
var webpack = require('webpack'); var path = require('path'); dest = path.resolve(__dirname, '../SingularityService/target/generated-resources/assets'); module.exports = { entry: { app: './app/initialize.coffee', vendor: [ 'react', 'jquery', 'underscore', 'clipboard', 'select2', 'handlebars', 'moment', 'messenger', 'bootstrap', 'classnames', 'react-interval', 'backbone-react-component', 'react-dom', 'fuzzy', 'datatables', 'sortable', 'juration', 'backbone', 'vex-js' ], }, output: { path: dest, filename: 'app.js' }, debug: true, devtool: 'source-map', module: { loaders: [ { test: /\.cjsx$/, loaders: ['coffee', 'cjsx']}, { test: /\.coffee$/, loader: 'coffee'}, { test: /\.hbs/, loader: "handlebars-template-loader" }, { test: /[\/]messenger\.js$/, loader: 'exports?Messenger'}, { test: /[\/]sortable\.js$/, loader: 'exports?Sortable'} ] }, resolve: { root: path.resolve('./app'), extensions: ['', '.js', '.cjsx', '.coffee', '.hbs'], alias: { 'vex': 'vex-js/js/vex.js', 'vex.dialog': 'vex-helper.coffee', 'handlebars': 'handlebars/runtime.js', 'sortable': 'sortable/js/sortable.js', 'datatables': 'datatables/media/js/jquery.dataTables.js', 'bootstrap': 'bootstrap/dist/js/bootstrap.js', 'react': path.join(__dirname, 'node_modules', 'react') } }, plugins: [ new webpack.ProvidePlugin({ $: 'jquery', '_': 'underscore', jQuery: 'jquery', 'window.jQuery': 'jquery' }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"production"' }), new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'), ] };
JavaScript
0.000001
@@ -1428,70 +1428,8 @@ .js' -,%0A 'react': path.join(__dirname, 'node_modules', 'react') %0A
be49d7669cf3fa6f61a0f41fd9334f52303e1f86
correct state structure in Draggable
src/Draggable.react.js
src/Draggable.react.js
import React from 'react'; import raf from 'raf'; import isFunction from 'lodash/isFunction'; import merge from 'lodash/merge'; import computePosition from './computePosition'; import computeDeltas from './computeDeltas'; const T = React.PropTypes; const ZERO_DELTAS = { dx: 0, dy: 0 }; const DEFAULT_TOUCH = { initial: null, current: null, deltas: ZERO_DELTAS }; class Draggable extends React.Component { static propTypes = { children: T.oneOfType([T.func, T.element]).isRequired, style: T.objectOf(T.oneOfType([T.number, T.object])).isRequired, }; state = { component: { initial: { ...computePosition(this.props.style, ZERO_DELTAS), ...ZERO_DELTAS }, current: { ...computePosition(this.props.style, ZERO_DELTAS), ...ZERO_DELTAS }, }, touch: DEFAULT_TOUCH, }; _handleTouchMove = e => this.handleTouchMove(e); _handleTouchEnd = e => this.handleTouchEnd(e); _updatePosition(touchPosition) { this._updatingPosition = false; const { touch, component } = this.state; const deltas = computeDeltas(touch.current, touchPosition); const componentPosition = computePosition(component.current, deltas); this.setState(merge({}, this.state, { touch: { current: { ...touchPosition, ...deltas } }, component: {current: { ...componentPosition, ...deltas } }, })); } _resetTouch() { this.setState(merge({}, this.state, { touch: DEFAULT_TOUCH })); } passThroughState() { return { ...this.state.component.current }; } handleTouchStart(e, child) { // add event handlers to the body document.addEventListener('touchmove', this._handleTouchMove); document.addEventListener('touchend', this._handleTouchEnd); // call child's and own callback from props since we're overwriting it child.props.onTouchStart && child.props.onTouchStart(e); this.props.onTouchStart && this.props.onTouchStart(e); const { clientX, clientY } = e.nativeEvent.touches[0]; const dimensions = { x: clientX, y: clientY }; // set initial conditions for the touch event this.setState(merge({}, this.state, { touch: { initial: dimensions, current: dimensions } })); } handleTouchMove(e) { e.preventDefault(); if (!this._updatingPosition) { const { clientX: x, clientY: y } = e.touches[0]; raf(() => this._updatePosition({x, y})); } this._updatingPosition = true; } handleTouchEnd(e) { document.removeEventListener('touchmove', this._handleTouchMove); document.removeEventListener('touchend', this._handleTouchEnd); this._resetTouch(); } render() { const { children, __passThrough } = this.props; const passThrough = { ...__passThrough, ...this.passThroughState() }; const child = isFunction(children) ? children({ ...passThrough }) : children; return React.cloneElement(React.Children.only(child), { onTouchStart: e => this.handleTouchStart(e, child), __passThrough: passThrough, }); } } export default Draggable;
JavaScript
0.000028
@@ -1224,21 +1224,16 @@ urrent: -%7B ... touchPos @@ -1235,35 +1235,30 @@ chPosition, -... deltas - %7D %7D,%0A co @@ -1267,16 +1267,17 @@ onent: %7B + current: @@ -1273,29 +1273,24 @@ %7B current: -%7B ... componentPos @@ -1298,21 +1298,8 @@ tion -, ...deltas %7D %7D,%0A @@ -1426,24 +1426,69 @@ ate() %7B%0A +const %7B component, touch %7D = this.state;%0A return %7B ... @@ -1490,19 +1490,8 @@ %7B .. -.this.state .com @@ -1504,16 +1504,33 @@ .current +, ...touch.deltas %7D;%0A %7D%0A
870ab40c43215cdcf1ee112a4ca87f7bc379b0db
修复 FormControl 初始化数据 Bug
src/FormControl.jsx.js
src/FormControl.jsx.js
import _omit from 'lodash/omit'; import {PropTypes} from 'react'; import {fireEvent, isInputEventSupported} from './event'; import FormState from './FormState'; import DataSet from './DataSet.jsx'; import FormChild from './FormChild.jsx'; const {vajs} = FormState; export default class FormControl extends FormChild { static propTypes = { name: PropTypes.string, // 设置 defaultValue 表示把组件声明成 uncontrolled 组件 // 注意,defaultValue 和 value 只使用其中一个 defaultValue: PropTypes.any, // 设置 value 表示把组件声明成 controlled 组件 value: PropTypes.any }; static defaultProps = { defaultValue: null } /** * 扩展 FormControl 的静态对象属性,比如 propTypes, defaultProps * @param {String} propertyName 要扩展的属性名 * @param {Object} update 更新的值 * @return {Object} 新的属性值 */ static extendsStatic(propertyName, update) { return Object.assign({}, FormControl[propertyName] || {}, update); } constructor(props) { super(props); this._dataSetState = null; this._isCollectData = false; this._validator = null; this._initialized = false; } initState() { if (this._initialized) return; let value; const {name} = this.props; if (this._isCollectData) { this._dataSetState = new FormState({ data: this.value, validator: this.validator, onStateChange: this.onDataSetChange }); this.form.data[name] = this._dataSetState; value = this._dataSetState; } else if (this.validator) { value = this.validator.validate(this.value); } if (value) { this.form.data[name] = value; if (value.isValid) { this.form._invalidSet.delete(name); } else { this.form._invalidSet.add(name); } } this._initialized = true; } get value() { return this.props.value || this.formValue; } get validator() { if (this._isCollectData && this._validator && this._validator.size && this.props.validator && this.props.validator.size ) { this._validator.merge(this.props.validator); return this._validator; } return this.props.validator || this._validator; } pickProps() { const {defaultValue} = this.props; // React 要求 value 和 defaultValue 只能有一个。。。 if (defaultValue) { return _omit(this.props, ['validator']); } else { return _omit(this.props, ['validator', 'defaultValue']); } } // 继承时可覆盖,设置联合校验等逻辑 onDataSetChange = (state) => { this.triggerChange(state); } /** * 自主触发 * @param {Any} value dataset 数据`{data, isValid, result}`或者其它数据 * @param {DomEventLike} srcEvent 原始对象 * @return {undefined} */ triggerChange = (value, srcEvent) => { srcEvent && srcEvent.stopPropagation && srcEvent.stopPropagation(); const {_input} = this.refs; if (_input) { const eventType = isInputEventSupported ? 'input' : 'change'; _input.isFormControl = true; // 注意!不能用`_input.value = value`或者`_input.dataset.value = value`。 // 赋值后值会变成`value.toString()`。 _input.formControlValue = value; if (!this._isCollectData && this.validator) { _input.formControlValue = this.validator.validate(value); } fireEvent(_input, eventType); // 以下代码已经废弃,留作知识保留 // React 0.14.x 的 SyntheticEvent 是单例,如果执行流不中断会继续触发 srcEvent // // !!!!这里有个很大的坑 // 如果组件中存在 input 输入中文需求时,不能使用 stateless 组件 // 因为 FormControl 的自定义事件是在 setTimeout 后触发的,这个阶段重置 input 的 value 属性 // 会破坏输入法的判断,导致重复输入的问题。 // https://segmentfault.com/q/1010000003974633 // setTimeout(() => fireEvent(_input, eventType), 0); } }; renderFormControl() { return null; } render() { const {className, name, children} = this.props; const inputAttrs = {name, ref: '_input', type: 'text'}; let customChildren = this.renderFormControl(); if (!customChildren && children) { this._isCollectData = true; customChildren = children; } // 依赖 this._isCollectData 所以不能放在最前面 this.initState(); const formControlAttrs = { className: 'form-control ' + (className || '') }; return ( <div {...formControlAttrs}> <input hidden {...inputAttrs} /> {this._isCollectData && customChildren ? <DataSet name={name} state={this._dataSetState}>{customChildren}</DataSet> : customChildren} </div> ); } }
JavaScript
0
@@ -1278,16 +1278,17 @@ data: +( this.val @@ -1289,16 +1289,42 @@ is.value + && this.value.data) %7C%7C %7B%7D ,%0A
d1d4ca7676ebf491d08755e58ae0bcc342b668cd
Add upload prop to skipped
src/DropzoneS3Uploader.js
src/DropzoneS3Uploader.js
import React, {PropTypes} from 'react' import S3Upload from 'react-s3-uploader/s3upload' import Dropzone from 'react-dropzone' export default class DropzoneS3Uploader extends React.Component { static propTypes = { filename: PropTypes.string, s3Url: PropTypes.string.isRequired, notDropzoneProps: PropTypes.array.isRequired, isImage: PropTypes.func.isRequired, passChildrenProps: PropTypes.bool, imageComponent: PropTypes.func, fileComponent: PropTypes.func, progressComponent: PropTypes.func, errorComponent: PropTypes.func, children: PropTypes.oneOfType([ PropTypes.node, PropTypes.func ]), onDrop: PropTypes.func, onError: PropTypes.func, onProgress: PropTypes.func, onFinish: PropTypes.func, // Passed to react-s3-uploader upload: PropTypes.object.isRequired, // Default styles for react-dropzone className: PropTypes.oneOfType([ PropTypes.string, PropTypes.object, ]), style: PropTypes.object, activeStyle: PropTypes.object, rejectStyle: PropTypes.object, } static defaultProps = { upload: {}, className: 'react-dropzone-s3-uploader', passChildrenProps: true, isImage: filename => filename && filename.match(/\.(jpeg|jpg|gif|png|svg)/i), notDropzoneProps: ['onFinish', 's3Url', 'filename', 'host', 'upload', 'isImage', 'notDropzoneProps'], style: { width: 200, height: 200, border: 'dashed 2px #999', borderRadius: 5, position: 'relative', cursor: 'pointer', overflow: 'hidden', }, activeStyle: { borderStyle: 'solid', backgroundColor: '#eee', }, rejectStyle: { borderStyle: 'solid', backgroundColor: '#ffdddd', }, } constructor(props) { super() const uploadedFiles = [] const {filename} = props if (filename) { uploadedFiles.push({ filename, fileUrl: this.fileUrl(props.s3Url, filename), default: true, file: {}, }) } this.state = {uploadedFiles} } componentWillMount = () => this.setUploaderOptions(this.props) componentWillReceiveProps = props => this.setUploaderOptions(props) setUploaderOptions = props => { this.setState({ uploaderOptions: Object.assign({ signingUrl: '/s3/sign', contentDisposition: 'auto', uploadRequestHeaders: {'x-amz-acl': 'public-read'}, onFinishS3Put: this.handleFinish, onProgress: this.handleProgress, onError: this.handleError, }, props.upload), }) } handleProgress = (progress, textState, file) => { this.props.onProgress && this.props.onProgress(progress, textState, file) this.setState({progress}) } handleError = err => { this.props.onError && this.props.onError(err) this.setState({error: err, progress: null}) } handleFinish = (info, file) => { const uploadedFile = Object.assign({ file, fileUrl: this.fileUrl(info.filename), }, info) const uploadedFiles = this.state.uploadedFiles uploadedFiles.push(uploadedFile) this.setState({uploadedFiles, error: null, progress: null}, () => { this.props.onFinish && this.props.onFinish(uploadedFile) }) } handleDrop = (files, rejectedFiles) => { this.setState({uploadedFiles: [], error: null, progress: null}) const options = { files, ...this.state.uploaderOptions, } new S3Upload(options) // eslint-disable-line this.props.onDrop && this.props.onDrop(files, rejectedFiles) } fileUrl = (s3Url, filename) => `${s3Url.endsWith('/') ? s3Url.slice(0, -1) : s3Url}/${filename}` renderImage = ({uploadedFile}) => (<div className="rdsu-image"><img src={uploadedFile.fileUrl} /></div>) renderFile = ({uploadedFile}) => ( <div className="rdsu-file"> <div className="rdsu-file-icon"><span className="fa fa-file-o" style={{fontSize: '50px'}} /></div> <div className="rdsu-filename">{uploadedFile.file.name}</div> </div> ) renderProgress = ({progress}) => (progress ? (<div className="rdsu-progress">{progress}</div>) : null) renderError = ({error}) => (error ? (<div className="rdsu-error small">{error}</div>) : null) render() { const { s3Url, passChildrenProps, children, imageComponent, fileComponent, progressComponent, errorComponent, ...dropzoneProps, } = this.props const ImageComponent = imageComponent || this.renderImage const FileComponent = fileComponent || this.renderFile const ProgressComponent = progressComponent || this.renderProgress const ErrorComponent = errorComponent || this.renderError const {uploadedFiles} = this.state const childProps = {s3Url, ...this.state} this.props.notDropzoneProps.forEach(prop => delete dropzoneProps[prop]) let content = null if (children) { content = passChildrenProps ? React.Children.map(children, child => React.cloneElement(child, childProps)) : this.props.children } else { content = ( <div> {uploadedFiles.map(uploadedFile => { const props = { key: uploadedFile.filename, uploadedFile: uploadedFile, ...childProps } return this.props.isImage(uploadedFile.fileUrl) ? (<ImageComponent {...props} />) : (<FileComponent {...props} />) })} <ProgressComponent {...childProps} /> <ErrorComponent {...childProps} /> </div> ) } return ( <Dropzone onDrop={this.handleDrop} {...dropzoneProps}> {content} </Dropzone> ) } }
JavaScript
0
@@ -638,16 +638,17 @@ pes.func +, %0A %5D),
bca1864375577f5ce557bc64bfcd31bc1752e79a
Add more docs to Translator
src/structs/Translator.js
src/structs/Translator.js
const fs = require('fs') const path = require('path') const config = require('../config.js') const log = require('../util/logger.js') const defaultLocale = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'locales', config.bot.locale + '.json'))) const localesData = new Map() const fileList = fs.readdirSync(path.join(__dirname, '..', 'locales')) for (const file of fileList) { const read = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'locales', file))) localesData.set(file.replace('.json', ''), read) } function escapeRegExp (str) { return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&') } class Translator { constructor (locale = config.bot.locale) { /** * Locale string * @type {string} */ this.locale = locale } /** * Default locale parsed json * @constant {object} */ static get DEFAULT_LOCALE () { return defaultLocale } /** * Map of locales parsed jsons * @constant {Map<string, object>} */ static get LOCALES_DATA () { return localesData } /** * Convert a string according to the translator's locale * @param {string} string - Accessor * @param {Object.<string, number|string>} params - Keys to replace in string */ translate (string, params) { return Translator.translate(string, this.locale, params) } static createLocaleTranslator (locale) { return (string, params) => this.translate(string, locale, params) } /** * Check if a locale exists * @param {string} locale * @returns {boolean} */ static hasLocale (locale) { return this.LOCALES_DATA.has(locale) } /** * Get list of defined locales * @returns {string[]} */ static getLocales () { return Array.from(this.LOCALES_DATA.keys()).sort() } /** * Get command descriptions used for rsshelp * @param {string} locale */ static getCommandDescriptions (locale = config.bot.locale) { return this.LOCALES_DATA.get(locale).commandDescriptions } /** * Convert a string according to the given locale * @param {string} string - Accessor * @param {string} locale - Locale * @param {Object.<string, number|string>} [params] - Keys to replace in the string * @returns {string} */ static translate (string, locale = config.bot.locale, params) { if (typeof string !== 'string') { throw new TypeError('string is not a string') } if (typeof locale !== 'string') { throw new TypeError('locale is not a string') } if (!this.LOCALES_DATA.has(locale)) { throw new Error('Unknown locale: ' + locale) } const properties = string.split('.') let accessedSoFar = this.LOCALES_DATA.get(locale) let reference = this.DEFAULT_LOCALE for (const property of properties) { accessedSoFar = accessedSoFar[property] reference = reference[property] if (accessedSoFar === undefined) { log.general.error(`Invalid locale accessor ("${string}" stopped at "${property}") for locale ${locale}`) throw new Error(`Invalid locale accessor (stopped at "${property}") for locale ${locale}`) } if (!reference) { log.general.error(`Invalid locale accessor (no en-US locale reference of "${string}" at "${property}") for locale ${locale}`) throw new Error(`Invalid locale accessor (no en-US locale reference at "${property}") for locale ${locale}`) } } if (typeof accessedSoFar !== 'string') { log.general.error(`Invalid locale accessor that stopped with a non-string value ("${string}") for locale ${locale}`) throw new Error(`Invalid locale accessor that stopped with a non-string value for locale ${locale}`) } if (accessedSoFar.length === 0) { accessedSoFar = reference // Use the reference if the original locale is an empty string } if (params) { for (const param in params) { const term = escapeRegExp(`{{${param}}}`) const regex = new RegExp(term, 'g') accessedSoFar = accessedSoFar.replace(regex, params[param]) } } return accessedSoFar } } module.exports = Translator
JavaScript
0
@@ -1211,24 +1211,47 @@ e in string%0A + * @returns %7Bstring%7D%0A */%0A tran @@ -1341,16 +1341,129 @@ s)%0A %7D%0A%0A + /**%0A * Returns a translator function for a locale%0A * @param %7Bstring%7D locale%0A * @returns %7Bfunction%7D%0A */%0A static @@ -1974,24 +1974,64 @@ ing%7D locale%0A + * @returns %7BObject.%3Cstring, object%3E%7D%0A */%0A stat
46f1d11ebc32c53fbd6920090491bd5605cd48ca
Fix Sparkpost influxService method name
modules/sparkpost/server/controllers/sparkpost-webhooks.server.controller.js
modules/sparkpost/server/controllers/sparkpost-webhooks.server.controller.js
'use strict'; /** * This module is used to receive incoming SparkPost events * * Note that `bodyParser.json()` has a default limit of 100kb. * If you need to process larger requets, you need to change that. * @link https://github.com/expressjs/body-parser#bodyparserjsonoptions */ /** * Module dependencies. */ var _ = require('lodash'), path = require('path'), async = require('async'), basicAuth = require('basic-auth'), speakingurl = require('speakingurl'), errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')), influxService = require(path.resolve('./modules/core/server/services/influx.server.service')), config = require(path.resolve('./config/config')); /** * Receive Sparkpost events webhook batch * * From SparkPost's view: * - Any webhook batch that does not receive an HTTP 200 response will * be retried for a total of 4 hours before the data is discarded. * - Webhooks posting to this endpoint will timeout after 10 seconds. * - Each webhook batch contains the header X-MessageSystems-Batch-ID, which * is useful for auditing and prevention of processing duplicate batches. * * @link https://www.sparkpost.com/blog/webhooks-beyond-the-basics/ * @link https://developers.sparkpost.com/api/webhooks.html * @link https://support.sparkpostelite.com/customer/en/portal/articles/2232381-sparkpost-event-and-metrics-definitions * * @todo Prevent processing duplicate batches. */ exports.receiveBatch = function(req, res) { if (!_.isArray(req.body) || !req.body.length) { return res.status(400).send({ message: errorHandler.getErrorMessageByKey('bad-request') }); } async.map(req.body, exports.processAndSendMetrics, function() { res.status(200).end(); }); }; /** * Process event and send it to InfluxDB */ exports.processAndSendMetrics = function(event, callback) { // When adding a webhook, Sparkpost sends us `[{"msys":{}}]` if (!event.hasOwnProperty('msys') || _.isEmpty(event.msys)) { return callback(); } var fields = { time: new Date(), country: '', campaignId: '' }; var tags = {}; // Validate against these event categories // E.g. `{ msys: message_event: { } }` var eventCategories = [ 'message_event', 'relay_event', 'track_event', 'gen_event', 'unsubscribe_event' ]; // Validate against these event types // E.g. `{ msys: message_event: { type: 'bounce' } }` var eventTypes = [ 'injection', 'delivery', 'policy_Rejection', 'delay', 'bounce', 'out_of_band', 'spam_complaint', 'generation_failure', 'generation_rejection', 'policy_rejection', 'sms_status', 'link_unsubscribe', 'list_unsubscribe', 'relay_delivery', 'relay_injection', 'relay_rejection', 'relay_tempfail', 'relay_permfail', 'open', 'click' ]; // Get what's in first key of `msys` object var eventCategory = _.keys(event.msys)[0]; // Get what's the `type` of that event var eventType = _.get(event, 'msys.' + eventCategory + '.type'); // Validate event category tags.category = _.find(eventCategories, function(category) { // Returns first match from array return category === eventCategory; }); // Validate event type tags.type = _.find(eventTypes, function(type) { // Returns first match from array return type === eventType; }); // Didn't validate, don't continue if (!tags.category || !tags.type) { console.error('Could not validate SparkPost event webhook (type: ' + eventType + ', category: ' + eventCategory + ')'); return callback(); } // Add campaign id to fields if present var campaignId = _.get(event, 'msys.' + eventCategory + '.campaign_id'); if (_.isString(campaignId) && campaignId.length > 0) { // "Slugify" `campaignId` to ensure we don't get any carbage // Allows only `A-Za-z0-9_-` fields.campaignId = speakingurl(campaignId, { separator: '-', // char that replaces the whitespaces maintainCase: false, // don't maintain case truncate: 255 // truncate to 255 chars }); } // Add country if present var country = _.get(event, 'msys.' + eventCategory + '.geo_ip.country'); if (_.isString(country) && country.length > 0 && country.length <= 3) { fields.country = country.replace(/\W/g, '').toUpperCase(); } // Set `time` field to event's timestamp var timestamp = _.get(event, 'msys.' + eventCategory + '.timestamp'); if (timestamp) { fields.time = new Date(parseInt(timestamp, 10) * 1000); } influxService.writePoint('transactionalEmailEvent', fields, tags, callback); }; /** * Basic authentication middleware */ exports.basicAuthenticate = function(req, res, next) { // Get the basic auth credentials from the request. // The Authorization header is parsed and if the header is invalid, // undefined is returned, otherwise an object with name and pass properties. var credentials = basicAuth(req); var enabled = _.get(config, 'sparkpostWebhook.enabled'); // Access denied if (!credentials || enabled !== true || credentials.name !== config.sparkpostWebhook.username || credentials.pass !== config.sparkpostWebhook.password) { res.set('WWW-Authenticate', 'Basic realm="Knock Knock"'); return res.status(401).send({ message: 'Access denied' }); } // Access granted return next(); };
JavaScript
0.000001
@@ -4612,11 +4612,17 @@ rite -Poi +Measureme nt('
b1bafd05277065febff4b84b8f58484afc4269fd
Fix special write problem
src/u-popper.vue/index.js
src/u-popper.vue/index.js
import Vue from 'vue'; import Popper from '@vusion/popper.js'; import event from '../base/utils/event'; export default { name: 'u-popper', props: { open: { type: Boolean, default: false }, trigger: { type: String, default: 'click', validator: (value) => ['click', 'hover', 'right-click', 'double-click', 'manual'].includes(value) }, placement: { type: String, default: 'bottom-start', validator: (value) => /^(top|bottom|left|right)(-start|-end)?$/.test(value), }, reference: HTMLElement, offset: { type: String, default: '0' }, hoverDelay: { type: Number, default: 0 }, hideDelay: { type: Number, default: 0 }, appendTo: { type: String, default: 'body', validator: (value) => ['body', 'reference'].includes(value) }, boundariesElement: { default: 'window' }, escapeWithReference: { type: Boolean, default: true }, arrowElement: { type: String, default: '[u-arrow]' }, options: { type: Object, default() { return { modifiers: { offset: {}, }, }; }, }, disabled: { type: Boolean, default: false }, }, data() { return { currentOpen: this.open, }; }, watch: { open(value) { this.currentOpen = value; }, currentOpen(value) { // 不直接用样式的显隐,而用popper的create和destroy,popper有可能是从不同的地方触发的,reference对象会变 value ? this.createPopper() : this.destroyPopper(); }, }, render() { return this.$slots.default && this.$slots.default[0]; }, mounted() { // 虽然 Vue 中一般子组件比父组件先 mounted, // 但这里必须放到 mounted。不然可能在 v-if 的情况下出不来。。 /* eslint-disable consistent-this */ const parentVM = this; this.childVM = new Vue({ name: 'u-popper-child', parent: parentVM, render(h) { return parentVM.$slots.popper && parentVM.$slots.popper[0]; }, }); this.childVM.parentVM = parentVM; this.childVM.$mount(); const referenceEl = this.reference || this.$el; const popperEl = this.childVM.$el; // 绑定事件 const offEvents = this.offEvents = []; let timer = null; if (this.trigger === 'click') offEvents.push(event.on(referenceEl, 'click', () => this.toggle())); else if (this.trigger === 'hover') { offEvents.push(event.on(referenceEl, 'mouseenter', () => { clearTimeout(timer); timer = null; setTimeout(() => this.toggle(true), this.hoverDelay); })); if (this.hideDelay) { offEvents.push(event.on(popperEl, 'mouseenter', () => { clearTimeout(timer); timer = null; })); } offEvents.push(event.on(document, 'mouseover', (e) => { // !referenceEl.contains(e.target) && !popperEl.contains(e.target) && this.toggle(false); if (this.currentOpen && !timer && !referenceEl.contains(e.target) && !popperEl.contains(e.target)) timer = setTimeout(() => this.toggle(false), this.hideDelay); })); } else if (this.trigger === 'double-click') offEvents.push(event.on(referenceEl, 'dblclick', () => this.toggle())); else if (this.trigger === 'right-click') { offEvents.push(event.on(referenceEl, 'contextmenu', (e) => { e.preventDefault(); this.toggle(); })); } // @TODO: 有没有必要搞 focus-in offEvents.push(event.on(document, 'mousedown', (e) => { !referenceEl.contains(e.target) && !popperEl.contains(e.target) && this.toggle(false); })); this.currentOpen && this.createPopper(); }, beforeUpdate() { // 先 update 子组件 this.childVM.$forceUpdate(); }, beforeDestroy() { this.destroyPopper(); // 先 destroy 子组件 this.childVM = this.childVM && this.childVM.$destroy(); // 取消绑定事件 this.offEvents.forEach((off) => off()); }, methods: { getOptions() { const options = Object.assign({}, this.options, { placement: this.placement, }); options.modifiers.offset.offset = this.offset; options.escapeWithReference = this.escapeWithReference; options.modifiers.arrow = { element: this.arrowElement }; options.modifiers.preventOverflow = { boundariesElement: this.boundariesElement }; return options; }, createPopper() { const referenceEl = this.reference || this.$el; const popperEl = this.childVM.$el; if (this.appendTo === 'body') document.body.appendChild(popperEl); else if (this.appendTo === 'reference') referenceEl.appendChild(popperEl); const options = this.getOptions(); this.popper = new Popper(referenceEl, popperEl, options); }, update() { this.popper && this.popper.update(); }, destroyPopper() { const referenceEl = this.reference || this.$el; const popperEl = this.childVM.$el; if (this.appendTo === 'body') popperEl.parentElement === document.body && document.body.removeChild(popperEl); else if (this.appendTo === 'reference') popperEl.parentElement === referenceEl && referenceEl.removeChild(popperEl); this.popper && this.popper.destroy(); this.popper = undefined; }, toggle(open) { if (this.disabled) return; const oldOpen = this.currentOpen; if (open === undefined) open = !this.currentOpen; if (open === oldOpen) return; let cancel = false; this.$emit('before-toggle', { open, preventDefault: () => cancel = true, }); if (cancel) return; this.currentOpen = open; this.$emit('update:open', open); this.$emit('toggle', { open, }); }, }, };
JavaScript
0.000003
@@ -4461,54 +4461,401 @@ -options.modifiers.offset.offset = this.offset; +// %E8%BF%99%E9%87%8C%E7%94%A8%E6%88%B7%E8%87%AA%E5%AE%9A%E4%B9%89op%08tions%08 %E4%B9%9F%E5%8F%AF%E8%83%BD%E4%BC%A0%E5%85%A5offset%E5%8F%82%E6%95%B0%0A if (options.modifiers.offset && !options.modifiers.offset.offset)%0A options.modifiers.offset.offset = this.offset;%0A%0A // %E8%87%AA%E5%AE%9A%E4%B9%89options %E4%BC%A0%E5%85%A5offset%E5%80%BC%E6%83%85%E5%86%B5%0A if (!options.modifiers.offset && this.offset) %7B%0A options.modifiers.offset = %7B%0A offset: this.offset,%0A %7D;%0A %7D%0A %0A
486b326c71d5e1a11bd2cb317193c2fe62f9bff9
fix isTest
packages/teraslice/lib/cluster/services/cluster/backends/kubernetes/utils.js
packages/teraslice/lib/cluster/services/cluster/backends/kubernetes/utils.js
'use strict'; const fs = require('fs'); const path = require('path'); const barbe = require('barbe'); const isTest = require('@terascope/utils'); function makeTemplate(folder, fileName) { const filePath = path.join(__dirname, folder, `${fileName}.hbs`); const templateData = fs.readFileSync(filePath, 'utf-8'); const templateKeys = ['{{', '}}']; return (config) => { const templated = barbe(templateData, templateKeys, config); return JSON.parse(templated); }; } // Convert bytes to MB and reduce by 10% function getMaxOldSpace(memory) { return Math.round(0.9 * (memory / 1024 / 1024)); } function setMaxOldSpaceViaEnv(envArr, jobEnv, memory) { const envObj = {}; if (memory && memory > -1) { // Set NODE_OPTIONS to override max-old-space-size const maxOldSpace = getMaxOldSpace(memory); envObj.NODE_OPTIONS = `--max-old-space-size=${maxOldSpace}`; } Object.assign(envObj, jobEnv); Object.entries(envObj).forEach(([name, value]) => { envArr.push({ name, value }); }); } const MAX_RETRIES = isTest ? 2 : 3; const RETRY_DELAY = isTest ? 50 : 1000; // time in ms function getRetryConfig() { return { retries: MAX_RETRIES, delay: RETRY_DELAY }; } module.exports = { getMaxOldSpace, getRetryConfig, makeTemplate, setMaxOldSpaceViaEnv };
JavaScript
0.999308
@@ -102,23 +102,27 @@ ;%0A%0Aconst + %7B isTest + %7D = requi
110c41f6a401482978291f3e771a7f46203854d5
Add elements field to section proptypes
src/ui/react/Container.js
src/ui/react/Container.js
import React, { Component } from 'react' import Head from './Head' import Plugin from './Plugin' import Section from './Section' import Contact from './Contact' export default class Container extends Component { renderHead() { return <Head head={this.props.generic.head} /> } renderContact() { const { generic } = this.props if (generic.contact) return <Contact contact={generic.contact} /> return null } renderSectionsAndPlugins () { //TODO: renderSectionsAndPlugins return null } render() { return ( <div> {this.renderHead()} {this.renderSectionsAndPlugins()} {this.renderContact()} </div> ) } } Container.propTypes = { generic: React.PropTypes.shape({ // Required head: React.PropTypes.shape({ title: React.PropTypes.string.isRequired, logo: React.PropTypes.string, subtitle: React.PropTypes.string, description: React.PropTypes.string, }).isRequired, // Optional contact: React.PropTypes.shape({ mail: React.PropTypes.string, facebook: React.PropTypes.string, twitter: React.PropTypes.string, github: React.PropTypes.string, }), style: React.PropTypes.shape({ accentColor: React.PropTypes.string, theme: React.PropTypes.string, }), sections: React.PropTypes.arrayOf(React.PropTypes.shape({ rank: React.PropTypes.number.isRequired, title: React.PropTypes.string, description: React.PropTypes.string, color: React.PropTypes.string, })), plugins: React.PropTypes.arrayOf(React.PropTypes.shape({ rank: React.PropTypes.number.isRequired, component: React.PropTypes.string.isRequired, })), }).isRequired } Container.defaultProps = { generic: { style: { accentColor: 'grey' } } }
JavaScript
0
@@ -1538,24 +1538,249 @@ pes.string,%0A + elements: React.PropTypes.arrayOf(React.PropTypes.shape(%7B%0A title: React.PropTypes.string,%0A logo: React.PropTypes.string,%0A link: React.PropTypes.string,%0A alt: React.PropTypes.string%0A %7D))%0A %7D)),%0A
0d93e732731dfa1e24bfc8f9c6686af4b53de60a
make summary use pipeline query values when rendering
src/ui/results/Summary.js
src/ui/results/Summary.js
import React from "react"; import PropTypes from "prop-types"; import { Tracking } from "sajari"; import { Pipeline, resultsReceivedEvent, errorReceivedEvent, Values } from "../../controllers"; class Summary extends React.Component { /** * propTypes * @property {Pipeline} pipeline Pipeline object. * @property {Values} values Values object. * @property {Sajari.Tracking} filter Tracking object from sajari package. * @property {string} [time] Query time. Usually supplied by Response. * @property {string} [totalResults] Number of results. Usually supplied by Response. * @property {string} [error] Error from search. Usually supplied by Response. */ static get propTypes() { return { pipeline: PropTypes.instanceOf(Pipeline).isRequired, values: PropTypes.instanceOf(Values).isRequired, tracking: PropTypes.instanceOf(Tracking).isRequired, time: PropTypes.string, totalResults: PropTypes.string, error: PropTypes.string }; } constructor(props) { super(props); this.state = { error: null, results: null, responseValues: null }; } componentDidMount() { const { pipeline } = this.props; this.setState({ error: pipeline.getError(), results: pipeline.getResults(), responseValues: pipeline.getResponseValues() }); this.removeErrorListener = pipeline.listen( errorReceivedEvent, this.errorChanged ); this.removeResultsListener = pipeline.listen( resultsReceivedEvent, this.resultsChanged ); } componentWillUnmount() { this.removeErrorListener(); this.removeResultsListener(); } errorChanged = error => { this.setState({ error }); }; resultsChanged = (results, responseValues) => { this.setState({ results, responseValues, error: null }); }; runOverride = event => { event.preventDefault(); this.props.values.set({ q: this.values.get()["q"], "q.override": "true" }); this.props.pipeline.search(this.props.values, this.props.tracking); }; render() { const { values, pipeline, tracking } = this.props; const { error, results, responseValues = {} } = this.state; const queryValues = values.get() || {}; if (error || !results) { return null; } const text = responseValues["q"] || queryValues["q"]; const page = parseInt(queryValues.page, 10); const pageNumber = page && page > 1 ? `Page ${page} of ` : ""; const override = responseValues["q"] && responseValues["q"].toLowerCase() !== queryValues["q"].toLowerCase() ? <span className="sj-result-summary-autocomplete-override"> {`search instead for `} <a onClick={this.runOverride} href=""> {" "}{queryValues["q"]}{" "} </a> </span> : null; return ( <div className="sj-result-summary"> <span className="sj-result-summary-text"> {`${pageNumber}${results.totalResults} results for `} "<strong>{text}</strong>"{" "} </span> <span className="sj-result-summary-query-`time`">{`(${results.time}) `}</span> {override} </div> ); } } export default Summary;
JavaScript
0.000001
@@ -2097,16 +2097,8 @@ st %7B - values, pip @@ -2217,26 +2217,39 @@ alues = -values.get +pipeline.getQueryValues () %7C%7C %7B%7D
d9b1e485eff18205e42e17c2aa3cab2a88ed1825
fix request compatibility export, closes extplug/rollover-blurb#1
src/util/compatibility.js
src/util/compatibility.js
import * as meld from 'meld'; import Plugin from '../Plugin'; import settings from '../store/settings'; import * as request from './request'; import getUserClasses from './getUserClasses'; import Style from './Style'; window.define('meld', () => meld); window.define('extplug/Plugin', () => Plugin); window.define('extplug/store/settings', () => settings); window.define('extplug/util/request', () => request); window.define('extplug/util/getUserClasses', () => getUserClasses); window.define('extplug/util/Style', () => Style);
JavaScript
0
@@ -104,21 +104,16 @@ %0Aimport -* as request
d7e0ed5eedd80137343ce3f42efad9cec3c3ca65
Fix lru unload performance
src/utilities/LRUCache.js
src/utilities/LRUCache.js
// TODO: can we remove the use of `indexOf` here because it's potentially slow? Possibly use time and sort as needed? // Keep a used list that we can sort as needed when it's dirty, a map of item to last used time, and a binary search // of the array to find an item that needs to be removed class LRUCache { constructor() { // options this.maxSize = 800; this.minSize = 600; this.unloadPercent = 0.2; this.usedSet = new Set(); this.itemSet = new Set(); this.itemList = []; this.callbacks = new Map(); } // Returns whether or not the cache has reached the maximum size isFull() { return this.itemSet.size >= this.maxSize; } add( item, removeCb ) { const itemSet = this.itemSet; if ( itemSet.has( item ) ) { return false; } if ( this.isFull() ) { return false; } const usedSet = this.usedSet; const itemList = this.itemList; const callbacks = this.callbacks; itemList.push( item ); usedSet.add( item ); itemSet.add( item ); callbacks.set( item, removeCb ); return true; } remove( item ) { const usedSet = this.usedSet; const itemSet = this.itemSet; const itemList = this.itemList; const callbacks = this.callbacks; if ( itemSet.has( item ) ) { callbacks.get( item )( item ); const index = itemList.indexOf( item ); itemList.splice( index, 1 ); usedSet.delete( item ); itemSet.delete( item ); callbacks.delete( item ); return true; } return false; } markUsed( item ) { const itemSet = this.itemSet; const usedSet = this.usedSet; if ( itemSet.has( item ) && ! usedSet.has( item ) ) { const itemList = this.itemList; const index = itemList.indexOf( item ); itemList.splice( index, 1 ); itemList.push( item ); usedSet.add( item ); } } markAllUnused() { this.usedSet.clear(); } // TODO: this should be renamed because it's not necessarily unloading all unused content // Maybe call it "cleanup" or "unloadToMinSize" unloadUnusedContent( prioritySortCb ) { const unloadPercent = this.unloadPercent; const targetSize = this.minSize; const itemList = this.itemList; const itemSet = this.itemSet; const usedSet = this.usedSet; const callbacks = this.callbacks; const unused = itemList.length - usedSet.size; if ( itemList.length > targetSize && unused > 0 ) { // TODO: sort by priority let nodesToUnload = Math.max( itemList.length - targetSize, targetSize ) * unloadPercent; nodesToUnload = Math.ceil( nodesToUnload ); nodesToUnload = Math.min( unused, nodesToUnload ); const removedItems = itemList.splice( 0, nodesToUnload ); for ( let i = 0, l = removedItems.length; i < l; i ++ ) { const item = removedItems[ i ]; callbacks.get( item )( item ); itemSet.delete( item ); callbacks.delete( item ); } } } scheduleUnload( prioritySortCb, markAllUnused = true ) { if ( ! this.scheduled ) { this.scheduled = true; Promise.resolve().then( () => { this.scheduled = false; this.unloadUnusedContent( prioritySortCb ); if ( markAllUnused ) { this.markAllUnused(); } } ); } } } export { LRUCache };
JavaScript
0.000002
@@ -284,16 +284,155 @@ removed +%0A%0A// Fires at the end of the frame and before the next one%0Afunction enqueueMicrotask( callback ) %7B%0A%0A%09Promise.resolve().then( callback );%0A%0A%7D %0Aclass L @@ -546,9 +546,10 @@ = 0. -2 +05 ;%0A%0A%09 @@ -2407,23 +2407,32 @@ t.size;%0A -%0A %09%09 -if ( +const excess = itemLis @@ -2440,17 +2440,17 @@ .length -%3E +- targetS @@ -2452,16 +2452,36 @@ rgetSize +;%0A%0A%09%09if ( excess %3E 0 && unus @@ -2555,114 +2555,45 @@ th.m -ax( itemList.length - targetSize, targetSize ) * unloadPercent;%0A%09%09%09nodesToUnload = Math.ceil( nodesToUnloa +in( targetSize * unloadPercent, unuse d ); @@ -2621,20 +2621,13 @@ ath. -min( unused, +ceil( nod @@ -2900,17 +2900,16 @@ %0A%0A%09%09%09%7D%0A%0A -%0A %09%09%7D%0A%0A%09%7D%0A @@ -3026,38 +3026,32 @@ rue;%0A%09%09%09 -Promise.resolve().then +enqueueMicrotask ( () =%3E
01a92b22056d988b2667fbfc03e28094e8ad36b3
Update scene module
src/visual-novel.scene.js
src/visual-novel.scene.js
( function( VN ) { /** * Function: initSceneContainer * * Initialize the container for the scenes */ VN.prototype.initSceneContainer = function initSceneContainer() { // TODO : needs refactoring this.screenSceneId = document.getElementById( this.novelId + "-screen-scene" ); var result = this.createSceneContainer( this.screenSceneId, this.sceneFloorWidth, this.sceneFloorHeight ); // Store for reference this.sceneContainer = result.floorContainer; this.sceneFloor = result.floor; }; /** * Function: createSceneContainer * * Create the container for the scenes * * @param element = dom container for scenes * @param width = width of container * @param height = height of container */ VN.prototype.createSceneContainer = function createSceneContainer( element, width, height ) { var objectFactory = this.objectFactory; // build scene container var sceneContainer = objectFactory( "SpriteContainer", element ); var stage = sceneContainer.children[ 0 ]; // build scene floor var sceneFloor = objectFactory( "SceneFloor", width, height ); var sceneFloorContainer = objectFactory( "SceneFloorContainer" ); sceneFloorContainer.addChild( sceneFloor.sprite ); stage.addChild( sceneFloorContainer ); // Return floor container and floor var result = { "floorContainer": sceneFloorContainer, "floor": sceneFloor }; return result; }; VN.prototype.rotateScene = function rotateScene( axis, angle, speed, loop ) { var self = this; function eventToAdd() { self.sceneFloor.rotate( axis, angle, speed, loop ); } this.eventTracker.addEvent( "nowait", eventToAdd ); }; VN.prototype.moveScene = function moveScene( x, y, z, speed ) { var self = this; function eventToAdd() { self.sceneFloor.move( x, y, z, speed ); } this.eventTracker.addEvent( "nowait", eventToAdd ); }; VN.prototype.resetScenes = function resetScenes() { var scenes = this.sceneContainer ? this.sceneContainer.children : []; var totalScenes = scenes.length; if ( totalScenes > 1 ) { for( var i = totalScenes - 1; i--; ) { // Don't include 0 since it is the scene floor this.sceneContainer.removeChildAt( i + 1 ); } } }; } )( window.VisualNovel = window.VisualNovel || {} );
JavaScript
0
@@ -17,505 +17,8 @@ %7B%0A%0A -%09/**%0A%09 * Function: initSceneContainer%0A%09 *%0A%09 * Initialize the container for the scenes%0A%09 */%0A%09VN.prototype.initSceneContainer = function initSceneContainer() %7B%0A%0A%09%09// TODO : needs refactoring%0A%0A%09%09this.screenSceneId = document.getElementById( this.novelId + %22-screen-scene%22 );%0A%0A%09%09var result = this.createSceneContainer( this.screenSceneId, this.sceneFloorWidth, this.sceneFloorHeight );%0A%09%09%0A%09%09// Store for reference%0A%09%09this.sceneContainer = result.floorContainer;%0A%09%09this.sceneFloor = result.floor;%0A%0A%09%7D;%0A%0A %09/** @@ -1393,36 +1393,453 @@ %7D;%0A%0A -%09VN.prototype.reset +%0A%09/**%0A%09 * Attach module to namespace%0A%09 */%0A%09VN.prototype.modules.push(%0A%09%09%7B%0A%09%09%09%22init%22: function init( novelId ) %7B%0A%0A%09%09%09%09this.screen Scene -s +Id = +document.getElementById( this.novelId + %22-screen-scene%22 );%0A%0A%09%09%09%09var result = this.createSceneContainer( this.screenSceneId, this.sceneFloorWidth, this.sceneFloorHeight );%0A%09%09%09%09%0A%09%09%09%09// Store for reference%0A%09%09%09%09this.sceneContainer = result.floorContainer;%0A%09%09%09%09this.sceneFloor = result.floor;%0A%0A%09%09%09%7D,%0A%09%09%09%22reset%22: func @@ -1852,20 +1852,16 @@ eset -Scenes () %7B%0A%0A +%09%09 %09%09va @@ -1928,16 +1928,18 @@ n : %5B%5D;%0A +%09%09 %09%09var to @@ -1968,16 +1968,18 @@ gth;%0A%0A%09%09 +%09 +%09 if ( tot @@ -1998,17 +1998,21 @@ ) %7B%0A%09%09%09 -%0A +%09%09%0A%09%09 %09%09%09for( @@ -2049,21 +2049,25 @@ ) %7B%0A%09%09%09%09 +%09%09 %0A%09%09%09%09 +%09%09 // Don't @@ -2105,16 +2105,18 @@ e floor%0A +%09%09 %09%09%09%09this @@ -2163,18 +2163,35 @@ %0A%09%09%09 +%09%09 %7D%0A%0A%09%09 +%09 +%09 %7D%0A -%0A%09%7D +%09%09%09%09%0A%09%09%09%7D%0A%09%09%7D%0A%09) ;%0A%0A%7D
c34f4b5be778357eac20be23f5b2783751163ce9
Add view mode to UI store
src/web/stores/UIStore.js
src/web/stores/UIStore.js
import { Store, toImmutable } from 'nuclear-js' import actionTypes from '~/actions/actionTypes' const { TOGGLE_LICENSE_MODAL, TOGGLE_ABOUT_MODAL } = actionTypes export default Store({ getInitialState() { return toImmutable({ licenseModalOpened: false, aboutModalOpened: false }) }, initialize() { this.on(TOGGLE_LICENSE_MODAL, toggleLicenseModal) this.on(TOGGLE_ABOUT_MODAL, toggleAboutModal) } }) function toggleLicenseModal(state) { return state.set('licenseModalOpened', !state.get('licenseModalOpened')) } function toggleAboutModal(state) { return state.set('aboutModalOpened', !state.get('aboutModalOpened')) }
JavaScript
0.000001
@@ -98,16 +98,19 @@ const %7B +%0A TOGGLE_L @@ -122,16 +122,18 @@ E_MODAL, +%0A TOGGLE_ @@ -143,17 +143,38 @@ UT_MODAL - +,%0A VIEW_MODE_CHANGED%0A %7D = acti @@ -314,16 +314,36 @@ d: false +,%0A viewMode: -1 %0A %7D)%0A @@ -469,16 +469,64 @@ tModal)%0A + this.on(VIEW_MODE_CHANGED, viewModeChanged)%0A %7D%0A%7D)%0A%0A @@ -667,32 +667,32 @@ tModal(state) %7B%0A - return state.s @@ -732,24 +732,119 @@ ('aboutModalOpened'))%0A%7D%0A +%0Afunction viewModeChanged(state, %7B mode %7D) %7B%0A return state.set('viewMode', mode.toString())%0A%7D%0A
13da204061d0f8e02533332007d10cf7b431f5c0
use mockPackage and injector
ngdoc/spec/processors/generateComponentGroups.spec.js
ngdoc/spec/processors/generateComponentGroups.spec.js
var processorFactory = require('../../processors/generateComponentGroups'); describe("generateComponentGroupsProcessor", function() { it("should create a new doc for each group of components (by docType) in each module", function() { var docs = []; var modules = [{ id: 'mod1', name: 'mod1', components: [ { docType: 'a', id: 'a1' }, { docType: 'a', id: 'a2' }, { docType: 'a', id: 'a3' }, { docType: 'a', id: 'a4' }, { docType: 'b', id: 'b1' }, { docType: 'b', id: 'b2' }, { docType: 'b', id: 'a3' } ] }]; var mockApiDocsProcessor = { apiDocsPath: 'partials' }; var processor = processorFactory(modules, mockApiDocsProcessor); processor.$process(docs); expect(docs.length).toEqual(2); expect(docs[0].name).toEqual('a components in mod1'); expect(docs[0].moduleName).toEqual('mod1'); expect(docs[0].moduleDoc).toEqual(jasmine.objectContaining({ id: 'mod1' })); }); });
JavaScript
0
@@ -1,138 +1,421 @@ var -processorFactory = require('../../processors/generateComponentGroups');%0A%0Adescribe(%22generateComponentGroupsProcessor%22, function() %7B +mockPackage = require('dgeni-packages/ngdoc/spec/mockPackage');%0Avar Dgeni = require('dgeni');%0A%0Adescribe(%22generateComponentGroupsProcessor%22, function() %7B%0A var processor, moduleMap;%0A%0A beforeEach(function() %7B%0A var dgeni = new Dgeni(%5BmockPackage()%5D);%0A var injector = dgeni.configureInjector();%0A processor = injector.get('generateComponentGroupsProcessor');%0A moduleMap = injector.get('moduleMap');%0A %7D);%0A %0A i @@ -540,23 +540,30 @@ -var module -s = %5B +Map.set('mod1', %7B%0A @@ -886,148 +886,8 @@ %7D -%5D;%0A var mockApiDocsProcessor = %7B%0A apiDocsPath: 'partials'%0A %7D;%0A%0A var processor = processorFactory(modules, mockApiDocsProcessor );%0A @@ -1139,16 +1139,1284 @@ d1' %7D)); +%0A%0A expect(docs%5B1%5D.name).toEqual('b components in mod1');%0A expect(docs%5B1%5D.moduleName).toEqual('mod1');%0A expect(docs%5B1%5D.moduleDoc).toEqual(jasmine.objectContaining(%7B id: 'mod1' %7D));%0A %7D);%0A%0A it(%22should not generate componentGroup docs for the 'overview' docType%22, function() %7B%0A%0A moduleMap.set('mod1', %7B%0A id: 'mod1',%0A name: 'mod1',%0A components: %5B%0A %7B docType: 'overview', id: 'a1' %7D,%0A %7B docType: 'a', id: 'a1' %7D%0A %5D%0A %7D);%0A var docs = %5B%5D;%0A processor.$process(docs);%0A expect(docs.length).toEqual(1);%0A%0A expect(docs%5B0%5D.name).toEqual('a components in mod1');%0A%0A %7D);%0A%0A it(%22should attach the componentGroup to its module%22, function() %7B%0A%0A moduleMap.set('mod1', %7B%0A id: 'mod1',%0A name: 'mod1',%0A components: %5B%0A %7B docType: 'a', id: 'a1' %7D,%0A %7B docType: 'a', id: 'a2' %7D,%0A %7B docType: 'a', id: 'a3' %7D,%0A %7B docType: 'a', id: 'a4' %7D,%0A %7B docType: 'b', id: 'b1' %7D,%0A %7B docType: 'b', id: 'b2' %7D,%0A %7B docType: 'b', id: 'a3' %7D%0A %5D%0A %7D);%0A var docs = %5B%5D;%0A processor.$process(docs);%0A var componentGroups = moduleMap.get('mod1').componentGroups;%0A expect(componentGroups.length).toEqual(2);%0A expect(componentGroups%5B0%5D.name).toEqual('a components in mod1'); %0A %7D);%0A%7D
48d4ceedb5a1b66d98e3e7a2b07a0e4b11eaf84a
Use the .caller property to test tail-calls instead of trying to cause stackoverflow errors
src/test/scripts/suite/objects/Realm/direct_eval_fallback_tailcall.js
src/test/scripts/suite/objects/Realm/direct_eval_fallback_tailcall.js
/* * Copyright (c) 2012-2014 André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ const { assertSame } = Assert; // Invalid direct eval call and tail calls: // - direct eval fallback and 'wrong' eval function have both tail calls enabled // - chaining them should preserve the tail call property const stackLimit = (function() { let limit = 0; try { (function f(){ f(limit++) })(); } catch (e) { } return limit; })(); function gauss(n) { return (n * n + n) / 2; } let callCount; let realm = new Realm({ directEval: { fallback(thisArgument, callee, ...args) { "use strict"; callCount += 1; return callee(...args); } } }); realm.eval(` function sum(n, acc) { "use strict"; if (n === 0) return acc; return eval(n - 1, acc + n); } eval = sum; `); for (let v of [1, 10, 100, 1000, 10000, stackLimit * 10]) { callCount = 0; assertSame(gauss(v), realm.eval(`sum(${v}, 0)`)); assertSame(v, callCount); }
JavaScript
0
@@ -389,209 +389,8 @@ ty%0A%0A -const stackLimit = (function() %7B%0A let limit = 0;%0A try %7B%0A (function f()%7B f(limit++) %7D)();%0A %7D catch (e) %7B%0A %7D%0A return limit;%0A%7D)();%0A%0Afunction gauss(n) %7B%0A return (n * n + n) / 2;%0A%7D%0A%0Alet callCount;%0A let @@ -495,30 +495,8 @@ t%22;%0A - callCount += 1;%0A @@ -563,68 +563,163 @@ ion -sum(n, acc) %7B%0A %22use strict%22;%0A if (n === 0) return acc; +returnCaller() %7B%0A return returnCaller.caller;%0A %7D%0A%0A function tailCall() %7B%0A %22use strict%22;%0A return returnCaller();%0A %7D%0A%0A function testFunction() %7B %0A @@ -735,29 +735,21 @@ val( -n - 1, acc + n +%22123%22 );%0A %7D%0A +%0A ev @@ -757,173 +757,88 @@ l = -sum;%0A%60);%0A%0Afor (let v of %5B1, 10, 100, 1000, 10000, stackLimit * 10%5D) %7B%0A callCount = 0;%0A assertSame(gauss(v), realm.eval(%60sum($%7Bv%7D, 0)%60));%0A assertSame(v, callCount);%0A%7D +tailCall;%0A%60);%0A%0AassertSame(realm.global.testFunction, realm.eval(%60testFunction()%60)); %0A
a0566f6673dcfeb3c8567b65978df2d22741a7c2
Fix typo
src/core/index.js
src/core/index.js
/** * Identity Desk * Copyright(c) 2017 Faraz Syed * MIT Licensed */ 'use strict'; export default main; /** * Module dependencies. */ import { clone, flow, map, mapKeys } from 'lodash'; import CoreFramework from './framework'; import CorePlugin from './plugin'; import ExpressFramework from '../frameworks/express'; import capitalize from 'capitalize'; import config from './config'; import database from './database'; import models from './models'; const debug = require('debug')('identity-desk:core'); class IdentityDesk { /** * Create Identity Desk middleware * * @param {Object} options * @param {string|Object} options.config Path to the configuration YAML/JSON file or configuration object * @param {Array|Object} options.framework Array with structure: `[framework, dependencies]`. Can also pass a framework module directly if there are no dependencies * @param {Array[]|Object[]} [options.plugins] Array with structure `...[plugin, dependencies]`. Can also pass a plugin module directly in the array if there are no dependencies */ constructor(options) { debug('initializing'); this.options = clone(options); // default to Express framework support this.options.framework = this.options.framework || ExpressFramework; // transform inputs into structure: `[module, dependencies = {}]` // and expose the underlying class to gain access to defaults and validators const transform = value => (Array.isArray(value) ? value : [value, {}]); this.options.framework = flow(transform, ([module, dependencies]) => [ module(CoreFramework), dependencies, ])(this.options.framework); this.options.plugins = options.plugins.map( flow(transform, ([module, dependencies]) => [ module(CorePlugin), dependencies, ]), ); const [Framework] = this.options.framework; // configure const defaults = [ Framework.defaults(), ...this.options.plugins.map(([Plugin]) => ({ plugins: { [Plugin.name()]: Plugin.defaults() }, })), ].filter(Boolean); const validators = [ Framework.validateConfig, ...this.options.plugins.map(([Plugin]) => Plugin.validateConfig), ].filter(Boolean); this.config = config.load(this.options.config, { defaults, validators, }); if (this.config.isValid) { // load Core and Plugin models this.models = {}; Object.keys(models).forEach( name => (this.models[`core$${name}`] = models[name]), ); // plugins are passed their config to let them dynamically generate models this.options.plugins.forEach(([Plugin]) => map( Plugin.models(this.config.plugins[Plugin.name()]), (model, name) => { this.models[`${Plugin.name()}$${name}`] = model; }, ), ); // Convert the model names into camel$Case, which is camelCase but with `$` to denote namespaces this.models = mapKeys(this.models, (model, key) => flow( key => key.split('$'), pieces => [pieces[0], ...pieces.slice(1).map(capitalize)].join('$'), )(key), ); this.database = database.load(this.config.database, this.models); } debug(require('util').inspect(this.config, false, null)); // initialize this.plugins = this.options.plugins.map(([Plugin, dependencies]) => { // TODO document that plugin dependencies will already contain a `database` property, which will overwrite whatever is provided dependencies.database = this.database; return new Plugin( Object.assign(this.config.plugins[Plugin.name()], { isValid: this.config.isValid, }), dependencies, ); }); this.framework = new Framework(this.config, this.database, this.plugins); } /** * Example usage: * * - Express: app.use(identityDesk.app); * * @return {Object} */ get app() { return this.framework.app; } shutdown() { debug('shutting down'); this.database.close(); } } /** * Create Identity Desk middleware * * @param {Object} options * @param {string|Object} options.config Path to the configuration YAML/JSON file or configuration object * @param {Array|Object} options.framework Array with structure: `[framework, dependencies]`. Can also pass a framework module directly if there are no dependencies * @param {Array[]|Object[]} [options.plugins] Array with structure `...[plugin, dependencies]`. Can also pass a plugin module directly in the array if there are no dependencies * @return {Object} */ function main(options) { return new IdentityDesk(options); }
JavaScript
0.999999
@@ -53,17 +53,17 @@ %0A * MIT -L +l icensed%0A
4f0c2c275842eaa5ec2540a93a097a1ad238faa3
Support sending numbers over rpc in wireFriendly
src/core/utils.js
src/core/utils.js
// Requires var Q = require('q'); var _ = require('underscore'); var cp = require('child_process'); // Generate callbacks for exec functions function _execHandler(deffered) { return function(error, stdout, stderr) { if(error) { return deffered.reject(Error(error)); } return deffered.resolve({ stdout: stdout, stderr: stderr, }); }; } // Execution stuff function simpleExecBuilder(execFunction) { return function(command) { var deffered = Q.defer(); var args = _.toArray(arguments).concat(_execHandler(deffered)); // Call exec function execFunction.apply(null, args); return deffered.promise; }; } var exec = simpleExecBuilder(cp.exec); var execFile = simpleExecBuilder(cp.execFile); // Builds a function that always returns value no matter the input function constant(value) { return function() { return value; }; } // Transform a promise returning function // to support dnode function qnode(func) { return function() { var args = _.toArray(arguments); var cb = args.pop(); var endFunc = _.partial(func, args); return endFunc() .then( _.partilal(cb, null) ) .fail(cb); }; } // Create a failed promise from an error function qfail(error) { var d = Q.defer(); d.reject(error); return d.promise; } // Takes an object with methods // and builds a new object // with the same methods (bound to the source) // but without the attributes // // This is useful for exposing things // in our module system // // !!! This is not recursive (not needed) function methodObj(obj) { var methods = _.methods(obj); var newObj = {}; methods.forEach(function(method) { newObj[method] = obj[method].bind(obj); }); return newObj; } function wireFriendly(obj) { if(_.isArray(obj)) { return _.map(obj, wireFriendly); } else if(_.isString(obj)) { return obj; } var newObj = {}; var pairs = _.pairs(obj); pairs.forEach(function(pair) { var key = pair[0], value = pair[1]; // Skip functions and keys starting with a lower dash if(_.isFunction(value) || key[0] == '_') { return; } // Set newObj[key] = value; }); return newObj; } // Return a timestamp of the curent time function timestamp() { return Math.floor(Date.now() / 1000); } // Does the string str start with toCheck function startsWith(str, toCheck) { return str.indexOf(toCheck) === 0; } // Exports exports.exec = exec; exports.qnode = qnode; exports.qfail = qfail; exports.execFile = execFile; exports.constant = constant; exports.methodObj = methodObj; exports.wireFriendly = wireFriendly; exports.timestamp = timestamp; exports.startsWith = startsWith;
JavaScript
0
@@ -1997,24 +1997,43 @@ sString(obj) + %7C%7C _.isNumber(obj) ) %7B%0A
d1085e08f52ad7abce25d957e82be7330b093a6c
fix jshint
addon/components/html-select.js
addon/components/html-select.js
import Ember from 'ember'; import layout from '../templates/components/html-select'; export default Ember.Component.extend({ layout: layout, didReceiveAttrs(/*attrs*/) { this._super(...arguments); var content = this.get('content'); if (!content) { this.set('content', []); // TODO ember warn no content set } // set it to the correct value of the selection this.selectedValue = Ember.computed('mainComponent.model.' + this.get('mainComponent.property'), function() { return this.get('mainComponent.model.' + this.get('mainComponent.property')); }); }, actions: { change() { const selectedEl = this.$('select')[0]; let selectedIndex = selectedEl.selectedIndex; // check whether we show prompt the the correct to show index is one less // when selecting prompt don't change anything if(this.get('mainComponent.prompt')){ if(selectedIndex != 0){ selectedIndex--; } else{ return; } } const content = this.get('mainComponent.content'); const selectedValue = content[selectedIndex]; const selectedID = selectedValue[this.get('mainComponent.optionValuePath')]; this.set('mainComponent.model.' + this.get('mainComponent.property'), selectedID); const changeAction = this.get('action'); if(changeAction){ changeAction(selectedID); } else{ // TODO make deprecate here so everyone switches to new action syntax } } } });
JavaScript
0.000002
@@ -940,16 +940,17 @@ Index != += 0)%7B%0A
caf25a2e33c0acc893708b420c3e2026661700c4
Allow 0 as a number if allowZero is true
addon/components/imput-money.js
addon/components/imput-money.js
import Ember from 'ember'; export default Ember.TextField.extend({ prefix: '', suffix: '', affixesStay: false, thousands: ',', decimal: '.', precision: 2, allowZero: true, allowNegative: false, allowDecimal: true, options: Ember.computed('prefix', 'suffix', 'affixesStay', 'thousands', 'decimal', 'precision', 'allowZero', 'allowNegative', 'allowDecimal', function() { return { prefix: this.get('prefix'), suffix: this.get('suffix'), affixesStay: this.get('affixesStay'), thousands: this.get('thousands'), decimal: this.get('decimal'), precision: this.get('precision'), allowZero: this.get('allowZero'), allowNegative: this.get('allowNegative'), allowDecimal: this.get('allowDecimal') }; }), initializeMask: Ember.on('didInsertElement', function() { let self =this; Ember.run.once(() => { self.$().maskMoney(self.get('options')); if(self.get('number')){ self.propertyDidChange('number'); } }); }), teardownMask: Ember.on('willDestroyElement', function() { this.$().maskMoney('destroy'); }), setMask: Ember.observer('options', function(){ this.$().maskMoney('destroy'); this.$().maskMoney(this.get('options')); }), setMaskedValue: Ember.observer('number', 'precision', 'decimal', function(){ let number = parseFloat(this.get('number') || 0).toFixed(this.get('precision')); let val = number.toString().replace('.', this.get('decimal')); this.$().val(val); this.$().maskMoney('mask'); }), setUnmaskedValue: Ember.observer('value', 'allowDecimal', function() { if(this.get('allowDecimal')){ this.set('number', this.$().maskMoney('unmasked')[0]); } else { this.set('number', this.get('value').replace(/[^0-9]/g, '')); } }) });
JavaScript
0.999985
@@ -935,16 +935,81 @@ if( +(self.get('allowZero') && (self.get('number') !== undefined)) %7C%7C self.get @@ -1016,24 +1016,26 @@ ('number'))%7B + %0A sel
20d90a2af4a374530ab14f77f6a8f58bde2297fe
support property changes where get mutates self
addon/document/internal/base.js
addon/document/internal/base.js
import Ember from 'ember'; import ModelMixin from './-model-mixin'; import { isInternal } from 'documents/util/internal'; const { assert } = Ember; const types = [ 'document', 'model', 'shoebox' ]; export const empty = {}; export default ModelMixin(class InternalBase { constructor(store, parent) { this.store = store; this.parent = parent; } get isDocument() { return false; } _document() { let target = this; while(target) { if(target.isDocument) { return target; } target = target.parent; } } // _assertType(type) { assert(`type must be one of the following [${types.join(', ')}] not '${type}'`, types.includes(type)); } _assertChanged(changed) { assert(`changed must be function not ${changed}`, typeof changed === 'function'); } // _invokeOnParents(cb) { let target = this.parent; while(target) { cb(target); target = target.parent; } } _willEndPropertyChanges(changed) { changed('serialized'); } _didEndPropertyChanges() { this._invokeOnParents(parent => parent.withPropertyChanges(changed => changed('serialized'), true)); } withPropertyChanges(cb, notify) { assert(`withPropertyChanges notify argument must be boolean`, typeof notify === 'boolean'); let model; if(notify) { model = this.model(false); } if(model && notify) { model.beginPropertyChanges(); } let changes = []; let changed = key => { if(model && notify) { model.notifyPropertyChange(key); } if(!changes.includes(key)) { changes.push(key); } } let result = cb(changed); if(notify && changes.length) { this._willEndPropertyChanges(changed); } if(model && notify) { model.endPropertyChanges(); } if(notify && changes.length) { this._didEndPropertyChanges(); } return result; } // isDetached() { return !this.parent; } _detach() { this.parent = null; } _attach(parent) { if(this.parent === parent) { return; } assert(`internal is already attached`, !this.parent); this.parent = parent; } _detachInternal(value) { if(isInternal(value)) { value._detach(); } } _attachInternal(value) { if(isInternal(value)) { value._attach(this); } } // _dirty(changed) { if(this.isDocument) { this.state.onDirty(changed); } else { let document = this._document(); if(document) { document.withPropertyChanges(changed => document.state.onDirty(changed), true); } } } // shouldSerialize() { return true; } serialize(type) { this._assertType(type); if(!this.shouldSerialize(type)) { return; } return this._serialize(type); } deserialize(values, type, changed) { this._assertType(type); this._assertChanged(changed); this._deserialize(values, type, changed); return this; } });
JavaScript
0
@@ -1196,24 +1196,32 @@ s(cb, notify +, except ) %7B%0A asse @@ -1305,24 +1305,60 @@ boolean');%0A%0A + console.log('except', except);%0A%0A let mode @@ -1553,32 +1553,70 @@ (model && notify + && (!except %7C%7C !except.includes(key)) ) %7B%0A mode
86f23dc53d53d2f8dafe61b4ae5e783128a89a7c
Add userId var and setMentorId function
server/public/scripts/controllers/nav.controller.js
server/public/scripts/controllers/nav.controller.js
app.controller('NavController', ['$http', '$firebaseAuth', '$mdDialog', 'AuthFactory', function($http, $firebaseAuth, $mdDialog, AuthFactory) { console.log('NavController running'); var auth = $firebaseAuth(); var self = this; self.logInModal = function(ev) { $mdDialog.show({ controller: 'LoginController as login', templateUrl: '../../views/login-modal.html', targetEvent: ev, clickOutsideToClose: true }) .then(function(answer) { // logIn(); }); }; }]); // $scope.showAdvanced = function(ev) { // $mdDialog.show({ // controller: DialogController, // templateUrl: 'dialog1.tmpl.html', // parent: angular.element(document.body), // targetEvent: ev, // clickOutsideToClose:true, // fullscreen: $scope.customFullscreen // Only for -xs, -sm breakpoints. // }) // .then(function(answer) { // $scope.status = 'You said the information was "' + answer + '".'; // }, function() { // $scope.status = 'You cancelled the dialog.'; // }); // };
JavaScript
0
@@ -79,16 +79,30 @@ actory', + 'BioFactory', functio @@ -147,16 +147,28 @@ hFactory +, BioFactory ) %7B%0A co @@ -253,16 +253,64 @@ this;%0A%0A + var userId = AuthFactory.userStatus.userId;%0A%0A%0A self.l @@ -591,14 +591,111 @@ %7D);%0A - %7D;%0A%0A + self.setMentorId = function()%7B%0A BioFactory.setMentorId(AuthFactory.userStatus.userId);%0A %7D%0A%0A %7D%5D);
35c6cd64325619aa81968947324841c8558f1ab5
Switch Button to TouchableRipple
src/button.js
src/button.js
import React, { PropTypes } from 'react' import { TouchableWithoutFeedback, View } from 'react-native-universal' import ps from 'react-native-ps' import Uranium from 'uranium' import Color from 'color' import connectTheme from './connectTheme' import Shadows from './styles/Shadows' import { Breakpoints } from './styles/Grid' import { Body1 } from 'carbon-ui/lib/Type' import Ripple from './Ripple' const Button = ({ children, style, disabled, flat, raised, fab, icon, theme, ...other, }) => { // Themed styles const tStyles = styles(theme) // Uppercase and style if the child is a string // Otherwise it's probably an icon or image, so let it through const formattedChildren = typeof children === 'string' ? <Body1>{children.toUpperCase()}</Body1> : children return ( <TouchableWithoutFeedback css={[ tStyles.base, flat && tStyles.flat, raised && tStyles.raised, fab && tStyles.fab, icon && tStyles.icon, disabled && flat && tStyles.flat.disabled, disabled && raised && tStyles.raised.disabled, disabled && fab && tStyles.fab.disabled, disabled && icon && tStyles.icon.disabled, style, ]} style={tStyles.touchable} hitSlop={{ top: 12, right: 12, bottom: 12, left: 12 }} {...other}> <View> {formattedChildren} <Ripple /> </View> </TouchableWithoutFeedback> ) } Button.propTypes = { children: PropTypes.node, style: PropTypes.object, disabled: PropTypes.bool, flat: PropTypes.bool, raised: PropTypes.bool, fab: PropTypes.bool, icon: PropTypes.bool, theme: PropTypes.object.isRequired, } const styles = theme => ps({ base: { height: 36, paddingHorizontal: 16, paddingVertical: 10, marginHorizontal: 8, [Breakpoints.ml]: { height: 32, }, }, flat: { color: theme.primary, active: { backgroundColor: theme.button.flat.pressed, }, disabled: { backgroundColor: theme.button.flat.disabled, }, }, raised: { minWidth: 88, ...Shadows.dp2, active: { ...Shadows.dp4, }, focus: { backgroundColor: Color(theme.primary).darken(0.12).hexString(), }, disabled: { color: theme.button.raised.disabledText, backgroundColor: theme.button.raised.disabled, }, [Breakpoints.ml]: { ...Shadows.none, hover: { ...Shadows.dp2, }, }, }, fab: { }, icon: { width: 40, height: 40, paddingVertical: 12, fontSize: 16, lineHeight: 16, textAlign: 'center', [Breakpoints.ml]: { height: 40, paddingVertical: 16, fontSize: 16, lineHeight: 16, }, }, web: { base: { cursor: 'pointer', }, }, }) export default connectTheme(Uranium(Button))
JavaScript
0
@@ -46,34 +46,8 @@ rt %7B - TouchableWithoutFeedback, Vie @@ -308,17 +308,17 @@ t %7B Body -1 +2 %7D from @@ -345,16 +345,25 @@ %0Aimport +Touchable Ripple f @@ -369,16 +369,25 @@ from './ +Touchable Ripple'%0A @@ -737,17 +737,38 @@ %3CBody -1 +2 style=%7BtStyles.text%7D %3E%7Bchildr @@ -790,17 +790,17 @@ )%7D%3C/Body -1 +2 %3E :%0A @@ -838,24 +838,104 @@ able -WithoutFeedback%0A +Ripple%0A hitSlop=%7B%7B top: 6, right: 6, bottom: 6, left: 6 %7D%7D%0A %7B...other%7D%3E%0A %3CView%0A @@ -951,16 +951,18 @@ + + tStyles. @@ -964,24 +964,26 @@ yles.base,%0A%0A + flat @@ -1000,16 +1000,18 @@ s.flat,%0A + @@ -1044,16 +1044,18 @@ + fab && t @@ -1066,16 +1066,18 @@ es.fab,%0A + @@ -1099,32 +1099,34 @@ .icon,%0A%0A + disabled && flat @@ -1144,32 +1144,34 @@ .flat.disabled,%0A + disabled @@ -1209,32 +1209,34 @@ sabled,%0A + + disabled && fab @@ -1252,32 +1252,34 @@ s.fab.disabled,%0A + disabled @@ -1325,157 +1325,38 @@ - -style,%0A %5D%7D%0A style=%7BtStyles.touchable%7D%0A hitSlop=%7B%7B top: 12, right: 12, bottom: 12, left: 12 %7D%7D%0A %7B...other%7D%3E%0A %3CView%3E%0A + style,%0A %5D%7D%3E%0A - %7Bfor @@ -1375,27 +1375,8 @@ en%7D%0A - %3CRipple /%3E%0A @@ -1404,23 +1404,14 @@ able -WithoutFeedback +Ripple %3E%0A @@ -1694,24 +1694,67 @@ %7B%0A base: %7B%0A + flex: 1,%0A justifyContent: 'center',%0A height: @@ -1788,33 +1788,8 @@ 16,%0A - paddingVertical: 10,%0A @@ -1865,16 +1865,52 @@ ,%0A %7D,%0A%0A + text: %7B%0A lineHeight: 16,%0A %7D,%0A%0A flat: