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
853a3f6409a6b8cd94d3f950377930a4989214cc
Validate config.websocket
src/helpers/validate.js
src/helpers/validate.js
const defaultConfig = require('./default-config'); module.exports = (config) => { if (!config) { return defaultConfig; } config.title = (typeof config.title === 'string') ? config.title : defaultConfig.title; config.path = (typeof config.path === 'string') ? config.path : defaultConfig.path; config.spans = (typeof config.spans === 'object') ? config.spans : defaultConfig.spans; return config; };
JavaScript
0.000008
@@ -393,16 +393,104 @@ spans;%0A%0A + config.websocket = (typeof config.websocket === 'object') ? config.websocket : null;%0A%0A return
3267ae695c7c3879861a0f8bc2e438b20c33269b
Make a skeleton of drag event listeners of sidebar-module
js/components/sidebar-module.js
js/components/sidebar-module.js
(function(app) { 'use strict'; var helper = app.helper || require('../helper.js'); var dom = app.dom || require('../dom.js'); var Component = app.Component || require('./component.js'); var SidebarModule = helper.inherits(function(props) { SidebarModule.super_.call(this, props); this.title = this.prop(props.title); this.content = this.prop(props.content); this.parentElement = this.prop(null); }, Component); SidebarModule.prototype.headerElement = function() { return dom.child(this.element(), 0); }; SidebarModule.prototype.contentElement = function() { return dom.child(this.element(), 1); }; SidebarModule.prototype.makeCloneElement = function() { var element = dom.clone(this.element()); dom.addClass(element, 'clone'); return element; }; SidebarModule.prototype.render = function() { var element = dom.el('<div>'); dom.addClass(element, 'module'); dom.html(element, SidebarModule.TEMPLATE_HTML); return element; }; SidebarModule.prototype.redraw = function() { var element = this.element(); var parentElement = this.parentElement(); if (!parentElement && !element) { return; } // add element if (parentElement && !element) { this.element(this.render()); this.redraw(); dom.append(parentElement, this.element()); return; } // remove element if (!parentElement && element) { dom.remove(element); this.element(null); this.cache({}); return; } // update element this.redrawTitle(); this.redrawContent(); }; SidebarModule.prototype.redrawTitle = function() { var title = this.title(); var cache = this.cache(); if (title === cache.title) { return; } dom.text(this.headerElement(), title); cache.title = title; }; SidebarModule.prototype.redrawContent = function() { var content = this.content(); var cache = this.cache(); if (content === cache.content) { return; } dom.text(this.contentElement(), content); cache.content = content; }; SidebarModule.TEMPLATE_HTML = [ '<div class="module-header"></div>', '<div class="module-content"></div>', ].join(''); if (typeof module !== 'undefined' && module.exports) { module.exports = SidebarModule; } else { app.SidebarModule = SidebarModule; } })(this.app || (this.app = {}));
JavaScript
0.000001
@@ -418,16 +418,54 @@ (null);%0A + this.draggable = this.prop(null);%0A %7D, Com @@ -473,16 +473,16 @@ onent);%0A - %0A Sideb @@ -671,32 +671,478 @@ nt(), 1);%0A %7D;%0A%0A + SidebarModule.prototype.registerDragListener = function() %7B%0A this.draggable(new dom.Draggable(%7B%0A element: this.element(),%0A onstart: SidebarModule.prototype.onstart.bind(this),%0A onmove: SidebarModule.prototype.onmove.bind(this),%0A onend: SidebarModule.prototype.onend.bind(this),%0A %7D));%0A %7D;%0A%0A SidebarModule.prototype.unregisterDragListener = function() %7B%0A this.draggable().destroy();%0A this.draggable(null);%0A %7D;%0A%0A SidebarModule. @@ -1763,24 +1763,59 @@ .render());%0A + this.registerDragListener();%0A this.r @@ -1948,24 +1948,61 @@ element) %7B%0A + this.unregisterDragListener();%0A dom.re @@ -2625,24 +2625,24 @@ , content);%0A - cache.co @@ -2656,32 +2656,345 @@ content;%0A %7D;%0A%0A + SidebarModule.prototype.onstart = function(x, y, event) %7B%0A /* TODO: handle dragstart event */%0A %7D;%0A%0A SidebarModule.prototype.onmove = function(dx, dy, event) %7B%0A /* TODO: handle dragmove event */%0A %7D;%0A%0A SidebarModule.prototype.onend = function(dx, dy, event) %7B%0A /* TODO: handle dragend event */%0A %7D;%0A%0A SidebarModule.
c0bb8ac0241dafd9f9d81086b5a343cd4056d08c
add support to obj[attrs][]
lib/assets/javascripts/esphinx/attribute.js
lib/assets/javascripts/esphinx/attribute.js
//= require ./main "use strict"; var esPhinx; (function ($) { $.extend({ prototype: { removeAttr: function (attrName) { var self = this; self.each(function (node) { node.removeAttribute(attrName); }); return self; }, attr: function (attrName, value) { var self = this, first = self.first(); if (self.length === 0) { return self; } if (typeof value === "boolean" || value || value === "") { self.each(function (node) { node.setAttribute(attrName, value); }); return self; } else { if (first.attributes[attrName]) { return first.attributes[attrName].value; } } return undefined; }, property: function (propertyName, value) { var self = this, first = self.first(); if (self.length === 0) { return self; } if (typeof value === "boolean" || value || value === "") { self.each(function (node) { node[propertyName] = value; }); return self; } else { if (first[propertyName] || typeof first[propertyName] === "boolean") { return first[propertyName]; } } return undefined; }, value: function (value) { var self = this; if (value || value === "") { self.property("value", value); return self; } return self.property("value"); }, checked: function () { return this.property("checked"); }, check: function () { var self = this; if (!self.checked()) { self.property("checked", true); } return self; }, uncheck: function () { var self = this; return self.property("checked", false); }, data: function (attrName, value) { return this.attr("data-" + attrName, value); }, params: function () { var self = this, resolvedParams = {}, index, name, param, key, merged, attr, nested_attr, resolveParam = function (name, value) { value = value || ""; var structure = name, parsed; // it's missing attr[] // obj[nested_attr][][attr] if (/.+\[.+\]\[\]\[.+\]/.test(name)) { structure = "{\"" + structure .replace(/\]\[\]\[/, "\":[{\"") .replace(/\[(?![\{])/g, "\":{\"") .replace(/\]$/g, "\":\"" + value + "\"}]}}"); // obj[nested_attr][0-9+][attr] } else if (/.+\[.+\]\[[0-9]+\]\[.+\]/.test(name)) { index = name.split("][")[1]; structure = "{\"" + structure .replace(/\[(?![0-9]+])/g, "\":{\"") .replace(/\]\[[0-9]+\]/g, "\":{\"" + index) .replace(/\]$/g, "\":\"" + value + "\"}}}}"); // obj[attr] } else if (/.+\[.+\]/.test(name)) { structure = "{\"" + structure .replace(/\[/g, "\":{\"") .replace(/\]$/g, "\":\"" + value + "\"}}"); // attr } else { structure = "{\"" + name + "\":\"" + value + "\"}"; } if (parsed = JSON.parse(structure)) { return parsed; } return false; }; self.each(function (form) { if (form instanceof HTMLFormElement) { $.each(form.elements, function (e, i) { if (name = e.name) { if (param = resolveParam(e.name, e.value)) { key = Object.keys(param)[0]; if (resolvedParams[key]) { attr = Object.keys(param[key])[0]; if (resolvedParams[key][attr] instanceof Array) { index = Object .keys(resolvedParams[key][attr]) .last(); nested_attr = Object .keys(param[key][attr][0])[0]; if (resolvedParams[key][attr][index][nested_attr]) { param[key][attr] = resolvedParams[key][attr] .concat(param[key][attr]); } else { resolvedParams[key][attr][index] = $.merge(resolvedParams[key][attr][index], param[key][attr][0]); param[key][attr] = resolvedParams[key][attr]; } } else if (resolvedParams[key][attr] instanceof Object) { param[key][attr][index] = $.merge(resolvedParams[key][attr][index], param[key][attr][index]); param[key][attr] = $.merge(resolvedParams[key][attr], param[key][attr]); } param[key] = $.merge(resolvedParams[key], param[key]); } resolvedParams = $.merge(resolvedParams, param); } } }); } }); return resolvedParams; }, } }); }(esPhinx));
JavaScript
0
@@ -3329,30 +3329,38 @@ -// it's missing attr%5B%5D +structure = %22%7B%5C%22%22 + structure; %0A @@ -3506,32 +3506,24 @@ structure = - %22%7B%5C%22%22 + structure%0A @@ -3954,32 +3954,24 @@ structure = - %22%7B%5C%22%22 + structure%0A @@ -4188,24 +4188,372 @@ %22%5C%22%7D%7D%7D%7D%22);%0A + // obj%5Battr%5D%5B%5D%0A %7D else if (/.+%5C%5B.+%5C%5D%5C%5B%5C%5D(?!.)/.test(name)) %7B%0A structure = structure%0A .replace(/%5C%5D%5C%5B/, %22%5C%22:%5B%5C%22%22)%0A .replace(/%5C%5B(?!%5C%22)/g, %22%5C%22:%7B%5C%22%22)%0A .replace(/%5C%5D$/g, value + %22%5C%22%5D%7D%7D%22);%0A @@ -4672,32 +4672,24 @@ structure = - %22%7B%5C%22%22 + structure%0A @@ -4928,24 +4928,10 @@ ure -= %22%7B%5C%22%22 + name + += %22%5C%22
a6b57a6070cc2105d501f57017b7f24d3aa0ffbb
Add test for facilityconfigpage
kolibri/plugins/facility_management/assets/test/views/facility-config-page.spec.js
kolibri/plugins/facility_management/assets/test/views/facility-config-page.spec.js
import { mount } from '@vue/test-utils'; import ConfigPage from '../../src/views/FacilityConfigPage'; import makeStore from '../makeStore'; function makeWrapper(propsData = {}) { const store = makeStore(); store.commit('facilityConfig/SET_STATE', { settings: { learner_can_edit_username: false, }, }); return mount(ConfigPage, { propsData, store }); } function getElements(wrapper) { return { cancelResetButton: () => wrapper.find('button[name="cancel"]'), checkbox: () => wrapper.find('input[class="k-checkbox-input"]'), confirmResetButton: () => wrapper.find('button[name="submit"]'), resetButton: () => wrapper.find('button[name="reset-settings"]'), saveButton: () => wrapper.find('button[name="save-settings"]'), confirmResetModal: () => wrapper.find({ name: 'KModal' }), form: () => wrapper.find('form'), }; } describe('facility config page view', () => { function assertModalIsUp(wrapper) { const { confirmResetModal } = getElements(wrapper); expect(confirmResetModal().exists()).toEqual(true); } function assertModalIsDown(wrapper) { const { confirmResetModal } = getElements(wrapper); expect(!confirmResetModal().exists()).toEqual(true); } it('clicking checkboxes dispatches a modify action', () => { const wrapper = makeWrapper(); const { checkbox } = getElements(wrapper); checkbox().trigger('click'); expect(wrapper.vm.$store.state.facilityConfig.settings.learner_can_edit_username).toEqual(true); }); it('clicking save button dispatches a save action', async () => { const wrapper = makeWrapper(); const mock = (wrapper.vm.$store.dispatch = jest.fn().mockResolvedValue()); const { saveButton } = getElements(wrapper); saveButton().trigger('click'); expect(mock).toHaveBeenCalledTimes(1); expect(mock).toHaveBeenCalledWith('facilityConfig/saveFacilityConfig'); }); it('clicking reset button brings up the confirmation modal', () => { const wrapper = makeWrapper(); const { resetButton } = getElements(wrapper); assertModalIsDown(wrapper); resetButton().trigger('click'); assertModalIsUp(wrapper); }); it('canceling reset tears down the modal', () => { const wrapper = makeWrapper(); const { resetButton, cancelResetButton } = getElements(wrapper); assertModalIsDown(wrapper); resetButton().trigger('click'); assertModalIsUp(wrapper); cancelResetButton().trigger('click'); assertModalIsDown(wrapper); }); it('confirming reset calls the reset action and closes modal', () => { const wrapper = makeWrapper(); const { resetButton, confirmResetModal } = getElements(wrapper); const mock = (wrapper.vm.$store.dispatch = jest.fn().mockResolvedValue()); resetButton().trigger('click'); assertModalIsUp(wrapper); confirmResetModal().vm.$emit('submit'); expect(mock).toHaveBeenCalledTimes(1); expect(mock).toHaveBeenCalledWith('facilityConfig/resetFacilityConfig'); assertModalIsDown(wrapper); }); // not tested: notifications });
JavaScript
0
@@ -1224,16 +1224,732 @@ );%0A %7D%0A%0A + it('has all of the settings', () =%3E %7B%0A const wrapper = makeWrapper();%0A const checkboxes = wrapper.findAll(%7B name: 'KCheckbox' %7D);%0A expect(checkboxes.length).toEqual(7);%0A const labels = %5B%0A 'Allow learners and coaches to edit their username',%0A 'Allow learners and coaches to change their password when signed in',%0A 'Allow learners and coaches to edit their full name',%0A 'Allow learners to create accounts',%0A 'Allow learners to sign in with no password',%0A %22Show 'download' button with content%22,%0A 'Allow users to access content without signing in',%0A %5D;%0A labels.forEach((label, idx) =%3E %7B%0A expect(checkboxes.at(idx).props().label).toEqual(label);%0A %7D);%0A %7D);%0A%0A it('cl
a55df66db4c205bad9a06709bd537969c64c5bc9
Fix incorrect usage of Boom for server/service unavailable error; remove handling of error in separate "if" block of code for Bcrypt compare
server/auth/basic/basicValidation.js
server/auth/basic/basicValidation.js
/** * Created by Omnius on 6/18/16. */ 'use strict'; const Async = require('async'); const Bcrypt = require('bcryptjs'); const Boom = require('boom'); const generateToken = require(process.cwd() + '/server/helpers/hkdfTokenGenerator').generateToken; const internals = {}; exports.validate = (request, usernameOrEmail, password, callback) => { const redis = request.redis; const server = request.server; const methods = server.methods; const userDao = methods.dao.userDao; Async.autoInject({ readUserId: (cb) => { userDao.readUserId(redis, usernameOrEmail, (err, userId) => { if (err || !userId) { return cb(err || 'invalid'); } return cb(null, userId); }); }, compareHashAndRealm: (readUserId, cb) => { const userId = readUserId; internals.compareHashAndRealm(request, userId, password, (err, isSame) => { if (err || !isSame) { return cb(err || 'invalid'); } return cb(null, userId); }); }, generateCredentials: (compareHashAndRealm, cb) => { const userId = compareHashAndRealm; internals.generateCredentials(request, userId, (err, credentials) => { if (err) { return cb(err); } credentials.userId = userId; return cb(null, credentials); }); } }, (err, results) => { if (err) { server.log(err); return callback(err === 'invalid' ? null : Boom.serverUnavailable(err), false); } return callback(err, true, results.generateCredentials); }); }; internals.compareHashAndRealm = (request, userId, password, cb) => { const redis = request.redis; const server = request.server; const methods = server.methods; const userDao = methods.dao.userDao; userDao.readUserHashAndRealm(redis, userId, (err, dbHashAndRealm) => { if (err || !dbHashAndRealm) { return cb(err, false); } const clientRealm = request.headers.realm || 'My Realm'; const dbHashedPw = dbHashAndRealm[0]; const dbRealm = dbHashAndRealm[1]; if (clientRealm !== dbRealm) { return cb(null, false); } Bcrypt.compare(password, dbHashedPw, (err, isSame) => { if (err) { return cb(err, false); } return cb(null, isSame); }); }); }; internals.generateCredentials = (request, userId, cb) => { const server = request.server; const redis = request.redis; const methods = server.methods; const userCredentialDao = methods.dao.userCredentialDao; generateToken(request.info.host + '/hawkSessionToken', null, (sessionId, authKey, token) => { userCredentialDao.createUserCredential(redis, sessionId, { hawkSessionToken: token, userId: userId, id: sessionId, key: authKey, algorithm: 'sha256' }, (err) => { if (err) { return cb(err); } const credentials = { hawkSessionToken: token, algorithm: 'sha256', id: sessionId }; return cb(null, credentials); }); }); };
JavaScript
0
@@ -537,24 +537,25 @@ : (cb) =%3E %7B%0A +%0A @@ -1329,32 +1329,33 @@ edentials) =%3E %7B%0A +%0A @@ -1678,25 +1678,16 @@ oom. -serverUnavailable +internal (err @@ -1690,24 +1690,30 @@ (err), false +, null );%0A %7D @@ -1738,19 +1738,20 @@ allback( -err +null , true, @@ -2079,24 +2079,25 @@ Realm) =%3E %7B%0A +%0A if ( @@ -2477,111 +2477,34 @@ %3E %7B%0A - if (err) %7B%0A return cb(err, false);%0A %7D%0A%0A return cb(null +%0A return cb(err , is
0d72db9e350b4335e8615fc915454b230701025a
Remove unused header prop
source/views/calendar/event-detail.ios.js
source/views/calendar/event-detail.ios.js
// @flow import React from 'react' import {Text, ScrollView, StyleSheet, Share} from 'react-native' import {Cell, Section, TableView} from 'react-native-tableview-simple' import type {EventType} from './types' import type {TopLevelViewPropsType} from '../types' import {ShareButton} from '../components/nav-buttons' import openUrl from '../components/open-url' import {cleanEvent, getTimes, getLinksFromEvent} from './clean-event' import {ButtonCell} from '../components/cells/button' import {addToCalendar} from './calendar-util' import delay from 'delay' const styles = StyleSheet.create({ chunk: { paddingVertical: 10, }, }) const shareItem = (event: EventType) => { const summary = event.summary ? event.summary : '' const times = getTimes(event) ? getTimes(event) : '' const location = event.location ? event.location : '' const message = `${summary}\n\n${times}\n\n${location}` Share.share({message}) .then(result => console.log(result)) .catch(error => console.log(error.message)) } function MaybeSection({header, content}: {header: string, content: string}) { return content.trim() ? <Section header={header}> <Cell cellContentView={ <Text selectable={true} style={styles.chunk}> {content} </Text> } /> </Section> : null } function Links({header, event}: {header: string, event: EventType}) { const links = getLinksFromEvent(event) return links.length ? <Section header={header}> {links.map(url => <Cell key={url} title={url} accessory="DisclosureIndicator" onPress={() => openUrl(url)} />, )} </Section> : null } export class EventDetail extends React.PureComponent { static navigationOptions = ({navigation}) => { const {event} = navigation.state.params return { title: event.summary, headerRight: <ShareButton onPress={() => shareItem(event)} />, } } props: TopLevelViewPropsType & { navigation: {state: {params: {event: EventType}}}, } state: { message: string, disabled: boolean, } = { message: '', disabled: false, } addPressed = async ({event}: {event: EventType}) => { const start = Date.now() this.setState(() => ({message: 'Adding event to calendar…'})) // wait 0.5 seconds – if we let it go at normal speed, it feels broken. const elapsed = start - Date.now() if (elapsed < 500) { await delay(500 - elapsed) } await addToCalendar(event).then(result => { if (result) { this.setState({ message: 'Event has been added to your calendar', disabled: true, }) } else { this.setState({ message: 'Could not add event to your calendar', disabled: false, }) } }) } CalendarButton = ({event}: {event: EventType}) => { return ( <Section header="" footer={this.state.message}> <ButtonCell title="Add to calendar" disabled={this.state.disabled} onPress={() => this.addPressed({event})} /> </Section> ) } render() { const event = cleanEvent(this.props.navigation.state.params.event) return ( <ScrollView> <TableView> <MaybeSection header="EVENT" content={event.title} /> <MaybeSection header="TIME" content={event.times} /> <MaybeSection header="LOCATION" content={event.location} /> <MaybeSection header="DESCRIPTION" content={event.rawSummary} /> <Links header="LINKS" event={event} /> {this.CalendarButton({event})} </TableView> </ScrollView> ) } }
JavaScript
0
@@ -2971,18 +2971,8 @@ tion - header=%22%22 foo
6ecf14a495a215d1920ce1b2c389ac61efad5ef7
update layer name
plugins/basemap-kartverket.js
plugins/basemap-kartverket.js
// @author johnd0e // @name Kartverket.no maps (Norway) // @category Map Tiles // @version 0.2.0 // @description Add Kartverket.no map layers. function setup () { L.TileLayer.Kartverket = L.TileLayer.extend({ baseUrl: 'https://opencache{s}.statkart.no/gatekeeper/gk/gk.open_gmaps?' + 'layers={layer}&zoom={z}&x={x}&y={y}', options: { maxNativeZoom: 18, attribution: '&copy; <a href="http://kartverket.no">Kartverket</a>', subdomains: ['', '2', '3'] }, mappings: { kartdata2: 'topo4', norgeskart_bakgrunn: 'topo4', sjo_hovedkart2: 'sjokartraster', toporaster: 'toporaster3', topo2: 'topo4', topo2graatone: 'topo4graatone' }, layers: { matrikkel_bakgrunn: 'Matrikkel bakgrunn', topo4: 'Topografisk norgeskart', topo4graatone: 'Topografisk norgeskart gråtone', europa: 'Europakart', toporaster3: 'Topografisk norgeskart, raster', sjokartraster: 'Sjøkart hovedkartserien', norges_grunnkart: 'Norges Grunnkart', norges_grunnkart_graatone: 'Norges grunnkart gråtone', egk: 'Europeiske grunnkart', terreng_norgeskart: 'Terreng', havbunn_grunnkart: 'Havbunn grunnkart', bakgrunnskart_forenklet: null }, initialize: function (layer, options) { if (typeof this.layers[layer] === 'undefined') { if (this.mappings[layer]) { layer = this.mappings[layer]; } else { throw new Error('Unknown layer "' + layer + '"'); } } L.TileLayer.prototype.initialize.call(this, this.baseUrl, options); this.options.layer = layer; this._name = this.layers[layer] || layer; } }); L.tileLayer.kartverket = function (layer, options) { return new L.TileLayer.Kartverket(layer, options); }; L.tileLayer.kartverket.getLayers = function () { return L.extend({},L.TileLayer.Kartverket.prototype.layers); }; var l, layer; for (layer in L.tileLayer.kartverket.getLayers()) { l = L.tileLayer.kartverket(layer); layerChooser.addBaseLayer(l, l._name); } }
JavaScript
0
@@ -120,17 +120,17 @@ 0.2. -0 +1 %0A// @des @@ -567,24 +567,73 @@ 2: 'topo4',%0A + matrikkel_bakgrunn: 'matrikkel_bakgrunn2',%0A norges @@ -833,18 +833,18 @@ bakgrunn +2 : - 'Matrikk
c90c33bc6edb3d20500ef894a7eef852e29a5f1a
support inline-style with camel case
jDollarX.js
jDollarX.js
void function (root, factory) { if (typeof define === 'function' && define.amd) { define(['jquery'], factory) } else if (typeof module === 'object' && module.exports) { module.exports = factory(require('jquery')) } else { root.J$X = factory(root.jQuery) } } (this, function ($) { var KEY_ALIASES = { className: 'class', htmlFor: 'for' } var slice = Array.prototype.slice var ownProp = Object.prototype.hasOwnProperty function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]' } function ClearObject(obj) { for (var key in obj) if (ownProp.call(obj, key)) { this[key] = obj[key] } } ClearObject.prototype = null function append($el, content) { if (content == null) { return } else if (typeof content === 'object') { $el.append(content) } else { var $dummy = $('<div>').text(content.toString()) $el.append($dummy.html()) } } var J$X = function (name, props/*, children... */) { var children = slice.call(arguments, 2) var _props = new ClearObject(props) if (children.length > 1) { _props.children = children } else if (children.length === 1) { _props.children = children[0] } if (typeof name === 'string') { // tag name return J$X.dom(name, _props) } else if (typeof name === 'function') { // element constructor return name(_props) } throw new Error( 'Invalid element name, either tag name or element constructor' ) } J$X.dom = function (name, props) { var $el = $('<' + name + '>') for (var key in props) { var value = props[key] key = KEY_ALIASES[key] || key if (key === 'children') { if (!isArray(value)) { append($el, value) } else { for (var i = 0, l = value.length; i < l; i++) { append($el, value[i]) } } } else if (key === 'style') { $el.css(value) } else { $el.attr(key, value) } } return $el } return J$X })
JavaScript
0
@@ -1965,20 +1965,203 @@ -$el.css(valu +var style = %7B%7D%0A for (var k in value) %7B%0A style%5Bk.replace(/%5BA-Z%5D/g, function (val) %7B%0A return '-'+val.toLowerCase()%0A %7D)%5D = value%5Bk%5D%0A %7D%0A $el.css(styl e)%0A
c31cb63168da019716a943336b0eee6b45b791f1
Add HTML mapping test for empty attributes.
src/htmlMapping.spec.js
src/htmlMapping.spec.js
import {enableTracing, disableTracing} from "./tracing/tracing" import getRootOriginAtChar from "./getRootOriginAtChar" import {disableProcessHTMLOnInitialLoad} from "./tracing/processElementsAvailableOnInitialLoad" disableProcessHTMLOnInitialLoad() fdescribe("HTML Mapping", function(){ beforeEach(function(){ enableTracing() }) afterEach(function(){ disableTracing() }) it("Traces a basic string assignment", function(){ var el = document.createElement("div") el.innerHTML = "Hello" // <[d]iv>Hello</div> expect(getRootOriginAtChar(el, 1).origin.action).toBe("createElement") // <div>[H]ello</div> var originAndChar = getRootOriginAtChar(el, 5); expect(originAndChar.origin.action).toBe("Assign InnerHTML") expect(originAndChar.origin.value[originAndChar.characterIndex]).toBe("H") }) it("Traces nested HTML assignments", function(){ var el = document.createElement("div") el.innerHTML = 'Hello <b>World</b>!' var bTag = el.children[0] // <b>[W]orld</b> var originAndChar = getRootOriginAtChar(bTag, 3); expect(originAndChar.origin.action).toBe("Assign InnerHTML") expect(originAndChar.origin.value[originAndChar.characterIndex]).toBe("W") }) })
JavaScript
0
@@ -112,16 +112,76 @@ nAtChar%22 +%0Aimport whereDoesCharComeFrom from %22./whereDoesCharComeFrom%22 %0A%0Aimport @@ -1372,12 +1372,1032 @@ )%0A %7D) +%0A%0A it(%22Traces nested HTML assignments%22, function(done)%7B%0A var el = document.createElement(%22div%22)%0A el.innerHTML = '%3Cspan hello%3EHi%3C/span%3E'%0A var span = el.children%5B0%5D%0A%0A disableTracing()%0A // just to clarify what's going on, Chrome is adding the %22%22 to the attribute%0A expect(el.innerHTML).toBe('%3Cspan hello=%22%22%3EHi%3C/span%3E')%0A%0A // %3Cspan hello=%22%22%3E%5BH%5Di%3C/span%3E%0A var originAndChar = getRootOriginAtChar(span, 15);%0A expect(originAndChar.origin.action).toBe(%22Assign InnerHTML%22)%0A expect(originAndChar.origin.value%5BoriginAndChar.characterIndex%5D).toBe(%22H%22)%0A%0A whereDoesCharComeFrom(originAndChar.origin, originAndChar.characterIndex, function(steps)%7B%0A var value = steps%5B1%5D.originObject.value;%0A var characterIndex = steps%5B1%5D.characterIndex%0A // correctly traces back to assigned string%0A expect(value).toBe(%22%3Cspan hello%3EHi%3C/span%3E%22)%0A expect(value%5BcharacterIndex%5D).toBe(%22H%22)%0A done()%0A %7D)%0A %7D) %0A%7D)%0A
322d244ac54a7de25eb8d7470c6454cd7480228b
rename to radius
renderer/SvgLineSelection.js
renderer/SvgLineSelection.js
import React, {Component, PropTypes} from 'react' const P_COLOR = '#FFEB3B' const Q_COLOR = '#FF9800' const LINE_COLOR = '#9C27B0' const SELECTION_WIDTH = 10 export default class LineSelection extends Component { static get propTypes() { return { viewport: PropTypes.shape({ w: PropTypes.number.isRequired, h: PropTypes.number.isRequired, x: PropTypes.number.isRequired, y: PropTypes.number.isRequired, z: PropTypes.number.isRequired }).isRequired, lines: PropTypes.arrayOf(PropTypes.object).isRequired } } getArcs(id, p, q, vec, length, norm, dx, dy, z) { let d = { x: -dx, y: -dy } let width = SELECTION_WIDTH let offset = Math.sqrt(width * width - Math.pow(length * 0.5 / z, 2)) * z let middle = vec.clone().mulS(0.5).add(p) let a = norm.clone().mulS(offset).add(middle).mulS(1/z).add(d) let b = norm.clone().mulS(-offset).add(middle).mulS(1/z).add(d) return [ <path key={-2 * id - 1} fill={P_COLOR} d={`M${a.x} ${a.y} A ${width} ${width} 0 1 1 ${b.x} ${b.y}`} />, <path key={-2 * id - 2} fill={Q_COLOR} d={`M${a.x} ${a.y} A ${width} ${width} 0 1 0 ${b.x} ${b.y}`} /> ] } render() { let {x, y, z, w, h} = this.props.viewport let [dx, dy] = [x / z - w / 2, y / z - h / 2] let width = SELECTION_WIDTH return ( <svg style={{position: 'absolute'}} viewBox={`0 0 ${w} ${h}`}> <g style={{opacity: 0.7}}> {this.props.lines.map(({id, x1, y1, x2, y2, length}) => <line key={id} strokeWidth={width * 2} stroke={LINE_COLOR} x1={x1 / z - dx} y1={y1 / z - dy} x2={x2 / z - dx} y2={y2 / z - dy} /> )} {this.props.lines.map(({id, p, q, vec, length, norm}) => length * 0.5 / z < (SELECTION_WIDTH - 0.1) ? this.getArcs(id, p, q, vec, length, norm, dx, dy, z) : [ <circle key={-2 * id - 1} fill={P_COLOR} r={width} cx={p.x / z - dx} cy={p.y / z - dy} />, <circle key={-2 * id - 2} fill={Q_COLOR} r={width} cx={q.x / z - dx} cy={q.y / z - dy} /> ]).reduce((cs, c) => cs.concat(c), []) } {this.props.lines.map(({id, p, vec, length}) => length * 0.5 / z < (SELECTION_WIDTH * 1.5) ? <circle key={id} fill={LINE_COLOR} r={width / 2} cx={(p.x + 0.5 * vec.x) / z - dx} cy={(p.y + 0.5 * vec.y) / z - dy} /> : null) } </g> </svg> ) } }
JavaScript
0.99997
@@ -141,21 +141,22 @@ LECTION_ -WIDTH +RADIUS = 10%0A%0Ae @@ -700,21 +700,22 @@ LECTION_ -WIDTH +RADIUS %0A%0A le @@ -1390,21 +1390,22 @@ LECTION_ -WIDTH +RADIUS %0A ret @@ -1956,21 +1956,22 @@ LECTION_ -WIDTH +RADIUS - 0.1) @@ -2587,13 +2587,14 @@ ION_ -WIDTH +RADIUS * 1
936978aea7894c0aca2d28025de3c75353b6e797
Remove old MySQL connection settings
parse-vk.js
parse-vk.js
/*================================= = Bootstrap = =================================*/ 'use strict'; const fetch = require('node-fetch'); const fs = require('fs'); // https://github.com/mysqljs/mysql const mysql = require('mysql'); const config = require('./db.config.js'); const connection = mysql.createConnection(config); const mongoose = require('mongoose'); const Question = require('./models/questions.js'); const DB = require('./db.connect.js'); DB.connect(); /*===== End of Bootstrap ======*/ /*=================================== = VK requests = ===================================*/ // https://new.vk.com/questions_of_chgk const groupId = 62655504; const URL = `https://api.vk.com/method/wall.get?owner_id=-${groupId}&offset=1&count=10`; // const headers = new Headers(); const options = { method: 'GET', // headers: headers, cache: 'default' }; const replacer = (key, value) => { const removeFields = /comments|reposts|attachments/i; if (removeFields.test(key)) { return undefined; }; return value; } fetch(URL, options).then(res => { const contentType = res.headers.get('content-type'); if(contentType && contentType.includes('application/json')) { return res.json().then(json => { if (json && json.response) { // in case of bad format try { const records = json.response.slice(1); let questions = records.filter(record => record.text.toLowerCase().includes('#вопрос') && record); questions = questions.map(question => { const reg = new RegExp(/\] (.*?)\[/); question.question = question.text.match(reg)[1]; question.answer = question.attachment.photo.text; question.likes = question.likes.count; delete question.attachment; delete question.text; return question; }); // fs.writeFile("./questions.json", JSON.stringify(questions, replacer, 2), e => // e ? console.log(e) : console.log("The file was saved!") // ); const promises = []; questions.map((q, index) => { const question = new Question( q ); question.id = question._id; // http://mongoosejs.com/docs/api.html#model_Model-save const promise = question.save(e => { e ? console.log(e) : console.log("The question was saved!"); }); promises.push(promise); }); Promise.all( promises ).then(() => mongoose.connection.close()); } catch(e) { console.log(e); } } }); } else { console.log('Oops, we haven\'t got JSON!'); } }); /*===== End of VK requests ======*/ /*=============================== = MySQL = ===============================*/ // connection.connect(e => { // if (e) { // console.log('error in DB connection'); // connection.end(); // } // }); // const question = { question: 'Hello MySQL', answer: 'Test' }; // const query = connection.query( // 'INSERT INTO questions SET ?', // question, // (e, result) => { // console.log('Result: ', result); // console.log('Error: ', e); // } // ); // console.log(query.sql); // INSERT INTO questions SET `id` = int (AUTO INCREMENT), `question` = 'Hello MySQL' // connection.end(); /*===== End of MySQL ======*/
JavaScript
0.000001
@@ -230,16 +230,19 @@ s/mysql%0A +// const my @@ -266,24 +266,27 @@ e('mysql');%0A +// const config @@ -315,24 +315,27 @@ onfig.js');%0A +// const connec
8a7544e4ffd26fc3d04cdbc709c477c40a83f92d
Support rendering values when no backing data source is present.
js/controls/KendoMultiSelect.js
js/controls/KendoMultiSelect.js
define([ 'underscore', 'react', '../ReactCommon', '../ImmutableOptimizations' ], function (_, React, Common, ImmutableOptimizations) { 'use strict'; var PropTypes = React.PropTypes; function rawValue(props) { var value = props.value; if (_.isEmpty(value)) { return value; } value = _.isArray(value) ? value : [value]; return value.map(function (val) { return _.isObject(val) ? val[props.valueField] : val; }); } function toPlainObject(data) { return data.toJSON(); } var KendoMultiSelect = React.createClass({ mixins: [ImmutableOptimizations(['onChange', 'dataSource'])], statics: { fieldClass: function () { return 'formFieldMultiselect'; } }, propTypes: { value: PropTypes.array, onChange: PropTypes.func, id: PropTypes.string, dataSource: PropTypes.oneOfType([PropTypes.array.isRequired, PropTypes.object.isRequired]), displayField: PropTypes.string, valueField: PropTypes.string, disabled: PropTypes.bool, readonly: PropTypes.bool, options: PropTypes.object, placeholder: PropTypes.string, template: PropTypes.any }, getDefaultProps: function() { return { disabled: false, readonly: false, value: [], onChange: _.noop }; }, /*jshint ignore:start */ render: function () { return (<select id={this.props.id} multiple="multiple" />); }, /*jshint ignore:end */ componentDidMount: function () { var $el = Common.findWidget(this); var widgetOptions = _.defaults({ dataTextField: this.props.displayField, dataValueField: this.props.valueField, dataSource: this.props.dataSource, placeholder: this.props.placeholder, itemTemplate: this.props.template, change: this.onChange }, this.props.options); var kendoWidget = $el.kendoMultiSelect(widgetOptions).data('kendoMultiSelect'); // the 'value' method is a getter/setter that gets/sets the valueField. It will look up the record // in the store via the value set here. if (this.props.value) { kendoWidget.value(rawValue(this.props)); } if (this.props.disabled) { // disabled beats readonly kendoWidget.enable(false); } else if (this.props.readonly) { kendoWidget.readonly(true); } }, componentWillUnmount: function () { Common.findWidget(this, 'kendoMultiSelect').destroy(); }, componentWillReceiveProps: function (nextProps) { var cantChange = ['template', 'dataSource', 'valueField', 'displayField', 'placeholder']; console.assert(_.isEqual(_.pick(nextProps, cantChange), _.pick(this.props, cantChange)), 'these props cant change after mount'); }, componentDidUpdate: function (prevProps) { var kendoWidget = Common.findWidget(this, 'kendoMultiSelect'); if (prevProps.dataSource !== this.props.dataSource) { kendoWidget.setDataSource(this.props.dataSource); } if (this.props.value !== prevProps.value) { kendoWidget.value(rawValue(this.props)); } if (this.props.disabled !== prevProps.disabled) { kendoWidget.enable(!this.props.disabled); } else if (this.props.readonly !== prevProps.readonly) { kendoWidget.readonly(this.props.readonly); } }, onChange: function (event) { var kendoWidget = event.sender; var values = _.clone(kendoWidget.value()); var dataItems = kendoWidget.dataItems().map(toPlainObject); // Before we update the value, we need to clear the filter or some values may not // be recognized as being in the data source. if (kendoWidget.dataSource.filter()) { kendoWidget.dataSource.filter(null); } // To keep the "Flux" loop, we need to reset the widget value to props so that data flows down. kendoWidget.value(rawValue(this.props)); // Provide both scalar and object values for clients this.props.onChange(values, dataItems); } }); return KendoMultiSelect; });
JavaScript
0
@@ -348,17 +348,21 @@ value = -_ +Array .isArray @@ -584,24 +584,248 @@ N();%0A %7D%0A%0A + function dataSource(props) %7B%0A if (!_.isEmpty(props.dataSource)) %7B%0A return props.dataSource;%0A %7D%0A return Array.isArray(props.value) ? Array.from(props.value) : Array.of(props.value);%0A %7D%0A%0A var Kend @@ -1996,25 +1996,24 @@ dget(this);%0A -%0A @@ -2020,24 +2020,62 @@ var -widgetOptions = +props = this.props;%0A%0A $el.kendoMultiSelect( _.de @@ -2110,29 +2110,24 @@ aTextField: -this. props.displa @@ -2166,21 +2166,16 @@ eField: -this. props.va @@ -2212,27 +2212,16 @@ Source: -this.props. dataSour @@ -2222,16 +2222,23 @@ taSource +(props) ,%0A @@ -2260,21 +2260,16 @@ holder: -this. props.pl @@ -2309,21 +2309,16 @@ mplate: -this. props.te @@ -2378,21 +2378,16 @@ %7D, -this. props.op @@ -2392,16 +2392,17 @@ options) +) ;%0A%0A @@ -2434,40 +2434,8 @@ $el. -kendoMultiSelect(widgetOptions). data @@ -2628,37 +2628,32 @@ if ( -this. props.value) %7B%0A @@ -2686,37 +2686,32 @@ .value(rawValue( -this. props));%0A @@ -2726,37 +2726,32 @@ if ( -this. props.disabled) @@ -2865,37 +2865,32 @@ else if ( -this. props.readonly) @@ -3632,37 +3632,38 @@ aSource( -this.props.dataSource +dataSource(this.props) );%0A
3c54301b65b43034a5555904f54bc795742f3ddd
Translate to AAP prefered month abreviations
client/app/translations.js
client/app/translations.js
angular.module('gettext').run(['gettextCatalog', function (gettextCatalog) { gettextCatalog.setStrings('en', { "URGENCY": "NEWS VALUE", "Urgency": "News Value", "urgency": "news value", "Urgency stats": "News Value stats", "SERVICE": "CATEGORY" }); }]);
JavaScript
0.999999
@@ -281,16 +281,141 @@ ATEGORY%22 +,%0A %22Mar%22: %22March%22,%0A %22Apr%22: %22April%22,%0A %22Jun%22: %22June%22,%0A %22Jul%22: %22July%22,%0A %22Sep%22: %22Sept%22 %0A %7D);
f98e013aa10ed21af39c3d08b119107602683128
Complete insertion sort
sort/insertion_sort.js
sort/insertion_sort.js
var insert = function(array, rightIndex, value) { for(var index = rightIndex; index >= 0 && array[index] > value; index--){ array[index + 1] = array[index]; } array[index + 1] = value; };
JavaScript
0.000001
@@ -207,8 +207,313 @@ alue;%0A%7D; +%0A%0Avar insertionSort = function(array) %7B%0A for(var i = 1; i %3C array.length; i++)%7B%0A var value = array%5Bi%5D;%0A var rightIndex = i - 1;%0A insert(array, rightIndex, value);%0A %7D%0A%7D;%0A%0Avar array = %5B22, 11, 99, 88, 9, 7, 42%5D;%0AinsertionSort(array);%0Aconsole.log(%22Array after sorting: %22 + array);
0acb35dc23b2d14d6782bce624017ee6f1b0f13b
Update end to end tests
test/end-to-end-tests/src/usecases/signup.js
test/end-to-end-tests/src/usecases/signup.js
/* Copyright 2018 New Vector Ltd Copyright 2019 The Matrix.org Foundation C.I.C. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ const assert = require('assert'); module.exports = async function signup(session, username, password, homeserver) { session.log.step("signs up"); await session.goto(session.url('/#/register')); // change the homeserver by clicking the advanced section if (homeserver) { const advancedButton = await session.query('.mx_ServerTypeSelector_type_Advanced'); await advancedButton.click(); // depending on what HS is configured as the default, the advanced registration // goes the HS/IS entry directly (for matrix.org) or takes you to the user/pass entry (not matrix.org). // To work with both, we look for the "Change" link in the user/pass entry but don't fail when we can't find it // As this link should be visible immediately, and to not slow down the case where it isn't present, // pick a lower timeout of 5000ms try { const changeHsField = await session.query('.mx_AuthBody_editServerDetails', 5000); if (changeHsField) { await changeHsField.click(); } } catch (err) {} const hsInputField = await session.query('#mx_ServerConfig_hsUrl'); await session.replaceInputText(hsInputField, homeserver); const nextButton = await session.query('.mx_Login_submit'); // accept homeserver await nextButton.click(); } //fill out form const usernameField = await session.query("#mx_RegistrationForm_username"); const passwordField = await session.query("#mx_RegistrationForm_password"); const passwordRepeatField = await session.query("#mx_RegistrationForm_passwordConfirm"); await session.replaceInputText(usernameField, username); await session.replaceInputText(passwordField, password); await session.replaceInputText(passwordRepeatField, password); //wait 300ms because Registration/ServerConfig have a 250ms //delay to internally set the homeserver url //see Registration::render and ServerConfig::props::delayTimeMs await session.delay(300); /// focus on the button to make sure error validation /// has happened before checking the form is good to go const registerButton = await session.query('.mx_Login_submit'); await registerButton.focus(); // Password validation is async, wait for it to complete before submit await session.query(".mx_Field_valid #mx_RegistrationForm_password"); //check no errors const errorText = await session.tryGetInnertext('.mx_Login_error'); assert.strictEqual(errorText, null); //submit form //await page.screenshot({path: "beforesubmit.png", fullPage: true}); await registerButton.click(); //confirm dialog saying you cant log back in without e-mail const continueButton = await session.query('.mx_QuestionDialog button.mx_Dialog_primary'); await continueButton.click(); //find the privacy policy checkbox and check it const policyCheckbox = await session.query('.mx_InteractiveAuthEntryComponents_termsPolicy input'); await policyCheckbox.click(); //now click the 'Accept' button to agree to the privacy policy const acceptButton = await session.query('.mx_InteractiveAuthEntryComponents_termsSubmit'); await acceptButton.click(); //plow through cross-signing setup by entering arbitrary details //TODO: It's probably important for the tests to know the passphrase const xsigningPassphrase = 'a7eaXcjpa9!Yl7#V^h$B^%dovHUVX'; // https://xkcd.com/221/ let passphraseField = await session.query('.mx_CreateSecretStorageDialog_passPhraseField input'); await session.replaceInputText(passphraseField, xsigningPassphrase); await session.delay(1000); // give it a second to analyze our passphrase for security let xsignContButton = await session.query('.mx_CreateSecretStorageDialog .mx_Dialog_buttons .mx_Dialog_primary'); await xsignContButton.click(); //repeat passphrase entry passphraseField = await session.query('.mx_CreateSecretStorageDialog_passPhraseField input'); await session.replaceInputText(passphraseField, xsigningPassphrase); await session.delay(1000); // give it a second to analyze our passphrase for security xsignContButton = await session.query('.mx_CreateSecretStorageDialog .mx_Dialog_buttons .mx_Dialog_primary'); await xsignContButton.click(); //ignore the recovery key //TODO: It's probably important for the tests to know the recovery key const copyButton = await session.query('.mx_CreateSecretStorageDialog_recoveryKeyButtons_copyBtn'); await copyButton.click(); //acknowledge that we copied the recovery key to a safe place const copyContinueButton = await session.query('.mx_CreateSecretStorageDialog .mx_Dialog_primary'); await copyContinueButton.click(); //acknowledge that we're done cross-signing setup and our keys are safe const doneOkButton = await session.query('.mx_CreateSecretStorageDialog .mx_Dialog_primary'); await doneOkButton.click(); //wait for registration to finish so the hash gets set //onhashchange better? const foundHomeUrl = await session.poll(async () => { const url = session.page.url(); return url === session.url('/#/home'); }); assert(foundHomeUrl); session.log.done(); };
JavaScript
0
@@ -3896,946 +3896,68 @@ // -plow through cross-signing setup by entering arbitrary details%0A //TODO: It's probably important for the tests to know the passphrase%0A const xsigningPassphrase = 'a7eaXcjpa9!Yl7#V%5Eh$B%5E%25dovHUVX'; // https://xkcd.com/221/%0A let passphraseField = await session.query('.mx_CreateSecretStorageDialog_passPhraseField input');%0A await session.replaceInputText(passphraseField, xsigningPassphrase);%0A await session.delay(1000); // give it a second to analyze our passphrase for security%0A let xsignContButton = await session.query('.mx_CreateSecretStorageDialog .mx_Dialog_buttons .mx_Dialog_primary');%0A await xsignContButton.click();%0A%0A //repeat passphrase entry%0A passphraseField = await session.query('.mx_CreateSecretStorageDialog_passPhraseField input');%0A await session.replaceInputText(passphraseField, xsigningPassphrase);%0A await session.delay(1000); // give it a second to analyze our passphrase for security%0A + Continue with the default (generate a security key)%0A let xsi @@ -4502,209 +4502,15 @@ log_ -primary');%0A await copyContinueButton.click();%0A%0A //acknowledge that we're done cross-signing setup and our keys are safe%0A const doneOkButton = await session.query('.mx_CreateSecretStorageDialog +buttons .mx @@ -4542,14 +4542,20 @@ ait -doneOk +copyContinue Butt
74e2f38d427a77cfcfb7bec1a8557d9033ea576d
increase timeout again
jest.env.js
jest.env.js
jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
JavaScript
0.000001
@@ -32,9 +32,9 @@ L = -3 +6 0000
9d2597660f1b42e217e37481007db9cb300fb87a
Allow transition chaining.
monster.js
monster.js
// vim: tw=79 cc=+1 var EventEmitter = require('events').EventEmitter, util = require('util'); function InvalidTransition (msg) { this.message = msg; } InvalidTransition.prototype.toString = function () { return this.message; }; function State (name) { this.name = name; } util.inherits(State, EventEmitter); State.prototype.leave = function leave() { this.emit('leave'); }; State.prototype.enter = function enter() { this.emit('enter'); }; State.prototype.toString = function () { return 'State: ' + this.name; }; var Uninitialized = new State('uninitialized'); function Transition (name, from, to) { this.name = name; if (from) { if (from instanceof Array) { this.from = from; } else { this.from = [from]; } } else { this.from = [Uninitialized]; } this.to = to; } util.inherits(Transition, EventEmitter); Transition.prototype.transition = function transition(from, to) { from.leave(); this.emit('transition', from, to); to.enter(); }; Transition.prototype.toString = function () { return 'Transition: ' + this.name; }; function Monster (initial) { this.state = initial || Uninitialized; this._states = {}; } util.inherits(Monster, EventEmitter); Monster.prototype.isFinal = function isFinal() { return !(this.state.name in this._states); }; Monster.prototype.transition = function mTransition(name) { var cur = this.state; if (!this.isFinal() && name in this._states[cur.name]) { this.state = this._states[cur.name][name]; } else { throw new InvalidTransition('Transition not valid from current state.'); } this.emit('transition', cur, this.state); this.emit(name); if (this.isFinal()) { this.emit('final'); } }; Monster.prototype.addTransition = function addTransition(trans) { var self = this; for (var i = 0; i < trans.from.length; i++ ) { var from = trans.from[i].name; this._states[from] = this._states[from] || []; this._states[from][trans.name] = trans.to; } this[trans.name] = function() { self.transition(trans.name); }; }; exports.State = State; exports.Transition = Transition; exports.Monster = Monster; exports.Uninitialized = Uninitialized; exports.InvalidTransition = InvalidTransition;
JavaScript
0
@@ -1809,16 +1809,33 @@ ;%0A %7D%0A + return this;%0A %7D;%0A%0AMons @@ -2163,16 +2163,23 @@ +return self.tra @@ -2206,16 +2206,33 @@ %0A %7D;%0A + return this;%0A %7D;%0A%0Aexpo
59fb97c2f21a37e2c9033791f53552d2c26732d7
Revert "unexpectedAlertBehaviour: accept"
test/acceptance/index.js
test/acceptance/index.js
// Docs aren't that great to find. Mostly JAVA based. Here are few helpful resources: // - https://www.browserstack.com/automate/node#testing-frameworks // - http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/firefox/index_exports_Driver.html // - https://github.com/SeleniumHQ/selenium/blob/8f988e07cc316a48e0ff94d8ff823c95142532e9/javascript/webdriver/webdriver.js // - https://github.com/SeleniumHQ/selenium/blob/c10e8a955883f004452cdde18096d70738397788/javascript/node/selenium-webdriver/test/upload_test.js // // - https://github.com/SeleniumHQ/selenium/wiki/WebDriverJs // - http://seleniumhq.github.io/selenium/docs/api/javascript/ // - http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/firefox/index.html // - http://selenium.googlecode.com/git/docs/api/javascript/namespace_webdriver_By.html // - http://selenium.googlecode.com/git/docs/api/javascript/class_webdriver_WebElement.html require('babel-register') var webdriver = require('selenium-webdriver') var remote = require('selenium-webdriver/remote') // The Travis Sauce Connect addon exports the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables, // and relays connections to the hub URL back to Sauce Labs. // See: https://docs.travis-ci.com/user/gui-and-headless-browsers/#Using-Sauce-Labs var username = process.env.SAUCE_USERNAME var accessKey = process.env.SAUCE_ACCESS_KEY var remoteHost = 'http://uppy.io' var localHost = 'http://localhost:4000' // if accessKey is supplied as env variable, this is a remote Saucelabs test var isTravisTest = process.env.TRAVIS === 'true' var isRemoteTest = !!accessKey var host = localHost if (isTravisTest) { // @todo This should become localhost to utilize the Travis saucelabs addon tunnel // But it seems Edge and Safari fail on that right now, so targeting uppy.io instead. // That is unideal, as we are then testing a previous deploy, and not the current build // host = localHost host = remoteHost } else if (isRemoteTest) { // We're not too sure about a working tunnel otherwise, best just test uppy.io host = remoteHost } else { // If we don't have any access keys set, we'll assume you'll be playing around with a local // firefox webdriver. host = localHost } console.log('Acceptance tests will be targetting: ' + host) var platforms = [ // { browser: 'Safari', version: '8.0', os: 'OS X 10.10' }, // { browser: 'MicrosoftEdge', version: '13.10586', os: 'Windows 10' }, { browser: 'Firefox', version: '38.0', os: 'Linux' }, { browser: 'Internet Explorer', version: '10.0', os: 'Windows 8' }, { browser: 'Internet Explorer', version: '11.103', os: 'Windows 10' }, { browser: 'Chrome', version: '48.0', os: 'Windows XP' }, { browser: 'Firefox', version: '34.0', os: 'Windows 7' } ] var tests = [ require('./multipart.spec.js'), require('./i18n.spec.js') // require('./dragdrop.spec.js') ] function buildDriver (platform) { var driver if (isRemoteTest) { var capabilities = { 'browserName': platform.browser, 'platform': platform.os, 'version': platform.version, 'username': username, 'accessKey': accessKey, 'unexpectedAlertBehaviour': 'accept' } if (isTravisTest) { // @todo Do we need a hub_url = "%s:%s@localhost:4445" % (username, access_key) // as mentioned in https://docs.travis-ci.com/user/gui-and-headless-browsers/#Using-Sauce-Labs ? capabilities['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER capabilities['build'] = process.env.TRAVIS_BUILD_NUMBER capabilities['name'] = 'Travis ##' + process.env.TRAVIS_JOB_NUMBER capabilities['tags'] = [process.env.TRAVIS_NODE_VERSION, 'CI'] } driver = new webdriver .Builder() .withCapabilities(capabilities) .usingServer('http://' + username + ':' + accessKey + '@ondemand.saucelabs.com:80/wd/hub') .build() driver.setFileDetector(new remote.FileDetector()) } else { driver = new webdriver .Builder() .forBrowser('firefox') .build() } return driver } var customTests = { fallback: function () { var ancientPlatform = { browser: 'internet explorer', version: '6.0', os: 'Windows XP' } var driver = buildDriver({ browser: 'internet explorer', version: '6.0', os: 'Windows XP' }) var test = require('./fallback.spec.js') test(driver, ancientPlatform, host) } } // RUN TESTS function runAllTests () { if (isRemoteTest) { // run all tests for all platforms platforms.forEach(function (platform) { tests.forEach(function (test) { var driver = buildDriver(platform) test(driver, platform, host) }) }) // run custom platform-specific tests here // fallback test customTests.fallback() } else { // run tests just for local Firefox tests.forEach(function (test) { var driver = buildDriver() test(driver, { browser: 'Firefox', version: 'Version', os: 'Local' }, host) }) } } runAllTests()
JavaScript
0
@@ -3179,52 +3179,8 @@ sKey -,%0A 'unexpectedAlertBehaviour': 'accept' %0A
75c2f7f3dd2663219dfe6ea78af6ee529e5f0a74
Update comment
source/scripts/main.js
source/scripts/main.js
// App Main Entry // ============== // // Import Modules // -------------- // // ### NPM Modules import 'babel-core/polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; // Define <App/> // ------------- class App extends React.Component { render () { return ( <div>Hello, world!</div> ); } } // Render <App/> // ------------- ReactDOM.render(<App/>, document.getElementById('app'));
JavaScript
0
@@ -1,14 +1,17 @@ // +%3C App +/%3E Main En @@ -13,20 +13,43 @@ in Entry -%0A// + Component%0A// ============= ========
64fd4c8a73d4d05c7b602b1946d56984d16a034b
tweak the test controller to test github ssh access
demo/testcontroller.js
demo/testcontroller.js
JavaScript
0
@@ -1 +1,84 @@ %0A +LOG = %5B%5D;%0A%0Aonfetch = function(event) %7B%0A LOG.push(%5B%22Fetch event: %22, event%5D);%0A%0A%7D;%0A
3ef856b79d54dec416d7180e408ad76cddb0ec2e
switch to use include_geometry: false
app/isochrones/route.js
app/isochrones/route.js
import Ember from 'ember'; import setLoading from 'mobility-playground/mixins/set-loading'; export default Ember.Route.extend(setLoading, { queryParams: { isochrone_mode: { replace: true, refreshModel: true, }, pin: { replace: true, refreshModel: true }, departure_time: { replace: true, refreshModel: true }, include_operators: { replace: true, refreshModel: true }, exclude_operators: { replace: true, refreshModel: true }, include_routes: { replace: true, refreshModel: true }, exclude_routes: { replace: true, refreshModel: true }, stop: { replace: true, refreshModel: true } }, setupController: function (controller, model) { if (controller.get('bbox') !== null){ var coordinateArray = []; var bboxString = controller.get('bbox'); var tempArray = []; var boundsArray = []; coordinateArray = bboxString.split(','); for (var i = 0; i < coordinateArray.length; i++){ tempArray.push(parseFloat(coordinateArray[i])); } var arrayOne = []; var arrayTwo = []; arrayOne.push(tempArray[1]); arrayOne.push(tempArray[0]); arrayTwo.push(tempArray[3]); arrayTwo.push(tempArray[2]); boundsArray.push(arrayOne); boundsArray.push(arrayTwo); controller.set('leafletBounds', boundsArray); } controller.set('leafletBbox', controller.get('bbox')); this._super(controller, model); }, model: function(params){ this.store.unloadAll('data/transitland/operator'); this.store.unloadAll('data/transitland/stop'); this.store.unloadAll('data/transitland/route'); this.store.unloadAll('data/transitland/route_stop_pattern'); if (params.isochrone_mode){ var pinLocation = params.pin; if (typeof(pinLocation)==="string"){ var pinArray = pinLocation.split(','); pinLocation = pinArray; } var mode = params.isochrone_mode; var url = 'https://matrix.mapzen.com/isochrone?api_key=mapzen-jLrDBSP&json='; var linkUrl = 'https://matrix.mapzen.com/isochrone?json='; var json = { locations: [{"lat":pinLocation[0], "lon":pinLocation[1]}], costing: mode, denoise: 0.3, polygons: true, generalize: 50, costing_options: {"pedestrian":{"use_ferry":0}}, contours: [{"time":15},{"time":30},{"time":45},{"time":60}], }; if (json.costing === "multimodal"){ json.denoise = 0; // transit_start_end_max_distance default is 2145 or about 1.5 miles for start/end distance: // transit_transfer_max_distance default is 800 or 0.5 miles for transfer distance: // exclude - exclude all of the ids listed in the filter // include - include only the ids listed in the filter // Once /routes?operated_by= accepts a comma-separated list: // Only query for routes operated by selected operators. json.costing_options.pedestrian = { "use_ferry":0, "transit_start_end_max_distance":100000, "transit_transfer_max_distance":100000 }; json.costing_options["transit"]={}; json.costing_options.transit["filters"]={}; if (params.include_operators.length > 0) { json.costing_options.transit.filters["operators"] = { "ids": params.include_operators, "action":"include" }; } else if (params.exclude_operators.length > 0) { json.costing_options.transit.filters["operators"] = { "ids": params.exclude_operators, "action":"exclude" }; } if (params.include_routes.length > 0) { json.costing_options.transit.filters["routes"] = { "ids": params.include_routes, "action":"include" }; } else if (params.exclude_routes.length > 0) { json.costing_options.transit.filters["routes"] = { "ids": params.exclude_routes, "action":"exclude" }; } if (params.departure_time){ json.date_time = {"type": 1, "value": params.departure_time}; } } url = encodeURI(url + JSON.stringify(json)); linkUrl = encodeURI(linkUrl + JSON.stringify(json)); var isochrones = Ember.$.ajax({ url }); var operators = this.store.query('data/transitland/operator', {bbox: params.bbox}); var routes; if (params.include_operators.length > 0){ // change routes query to be only for the selected operator(s) routes var includeOperators = ""; for (var j = 0; j < params.include_operators.length; j++){ if (j > 0){ includeOperators += ","; } includeOperators += params.include_operators[j]; } routes = this.store.query('data/transitland/route', {bbox: params.bbox, operated_by: includeOperators, exclude_geometry: true}); } else { routes = this.store.query('data/transitland/route', {bbox: params.bbox, exclude_geometry: true}); } return Ember.RSVP.hash({ operators: operators, routes: routes, isochrones: isochrones, linkUrl: linkUrl }); } }, actions: { } });
JavaScript
0.999939
@@ -4584,18 +4584,18 @@ rators, -ex +in clude_ge @@ -4594,35 +4594,36 @@ clude_geometry: -tru +fals e%7D);%0A%09%09%09%7D else %7B @@ -4699,18 +4699,18 @@ s.bbox, -ex +in clude_ge @@ -4717,19 +4717,20 @@ ometry: -tru +fals e%7D);%0A%09%09%09
4da081a66e905a93f2623c229f6a5d08ef9ee3b7
Reset joint source view in explore when updated
scripts/explore/ExploreJointSourceController.js
scripts/explore/ExploreJointSourceController.js
var ExploreJointSourceController = JointSourceController.createComponent("ExploreJointSourceController"); ExploreJointSourceController.createViewFragment = function () { return cloneTemplate("#template-explore-jointsource"); }; ExploreJointSourceController.defineAlias("model", "jointSource"); ExploreJointSourceController.defineMethod("initView", function initView() { if (!this.view) return; setElementProperty(this.view, "jointsource-id", this.jointSource.jointSourceId); this.view.style.order = - this.jointSource.jointSourceId; this.view.querySelector("[data-ica-action='edit-jointsource']").addEventListener("click", function (e) { e.preventDefault(); e.stopPropagation(); var fragment = PublisherJointSourceController.createViewFragment(); var element = fragment.querySelector(".publisher"); document.body.appendChild(fragment); new PublisherJointSourceController(this.controller.jointSource, element); }.bind(this.view)); this.view.addEventListener("click", function (e) { e.preventDefault(); e.stopPropagation(); var map = new Map([this.controller.jointSource]); var fragment = MapController.createViewFragment(); var element = fragment.querySelector(".map"); document.body.appendChild(fragment); new MapController(map, element); }.bind(this.view)); new TokensController(this.jointSource.metaParticipantsHandler, this.view.querySelector("[data-ica-jointsource-meta='participants']")).componentOf = this; new TokensController(this.jointSource.metaThemesHandler, this.view.querySelector("[data-ica-jointsource-meta='themes']")).componentOf = this; }); ExploreJointSourceController.defineMethod("updateView", function updateView() { if (!this.view) return; this.view.querySelectorAll("[data-ica-jointsource-meta-predicate]").forEach(function (element) { var metaPredicate = getElementProperty(element, "jointsource-meta-predicate"); if (empty(this.jointSource.meta[metaPredicate])) { element.style.display = "none"; } else { element.style.display = ""; } }.bind(this)); this.view.querySelectorAll("[data-ica-jointsource-meta]").forEach(function (element) { element.textContent = this.jointSource.meta[getElementProperty(element, "jointsource-meta")]; }.bind(this)); var featuredSource = this.jointSource.sources[Object.keys(this.jointSource.sources)[0]]; switch (featuredSource.constructor) { case ImageSource: setElementProperty(this.view, "jointsource-feature", "image"); this.view.style.backgroundImage = featuredSource.content ? "url(" + ( featuredSource.blobHandler.blob instanceof Blob ? featuredSource.blobHandler.url : featuredSource.blobHandler.url + "?width=" + (this.view.offsetWidth * this.devicePixelRatio) ) + ")" : ""; break; } }); ExploreJointSourceController.defineMethod("uninitView", function uninitView() { if (!this.view) return; removeElementProperty(this.view, "jointsource-id"); }); /*****/ function empty(value) { if (Array.isArray(value)) return value.length == 0; return !value; }
JavaScript
0
@@ -1740,16 +1740,303 @@ eturn;%0A%0A + // Reset view%0A var parentNode = this.view.parentNode;%0A var fragment = this.constructor.createViewFragment();%0A var element = fragment.querySelector(%22.jointsource%22);%0A parentNode.replaceChild(fragment, this.view);%0A this.uninitView();%0A this._view = element;%0A this.initView(false);%0A%0A this.v
b5f577438d5593a82f69e5e01ede4e9914f35fd9
Support falsy expressions
jquery.k.js
jquery.k.js
/** * Lightweight Jade/HAML-like DOM builder for jQuery. */ (function() { var re = { tag: /^(\w+)/, id: /#(\w+)/, cls: /\.([^#]+)/ }; $.K = function(s) { var tag = (re.tag.exec(s)||[,'div'])[1]; var el = document.createElement(tag); var id = re.id.exec(s); var cls = re.cls.exec(s); if (id) (el.id = id[1]); if (cls) (el.className = cls[1].replace('.', ' ')); var ret = $(el); for (var i=1; i < arguments.length; i++) { var child = arguments[i]; if (typeof child == 'string') child = document.createTextNode(child); ret.append(child); } return ret; }; $.fn.K = function(s) { var ret = $.K.apply(this, arguments); this.append(ret); ret.prevObject = this; return ret; }; $.fn.X = function() { return $.fn.K.apply(this.end(), arguments); }; })();
JavaScript
0.000004
@@ -183,16 +183,20 @@ g.exec(s +%7C%7C'' )%7C%7C%5B,'di
c6215ff8cef5329d4f48fc43d15a68dbf1c29974
优化和密度分析测试案例,将真实请求服务改为mork review by sunxiaoyu
test/leaflet/services/DensityAnalysisSpec.js
test/leaflet/services/DensityAnalysisSpec.js
import {spatialAnalystService} from '../../../src/leaflet/services/SpatialAnalystService'; import {DensityKernelAnalystParameters} from '../../../src/common/iServer/DensityKernelAnalystParameters'; import request from 'request'; var spatialAnalystURL = GlobeParameter.spatialAnalystURL_Changchun; var options = { serverType: 'iServer' }; describe('leaflet_SpatialAnalystService_densityAnalysis', () => { var serviceResult; var originalTimeout; beforeEach(() => { originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000; serviceResult = null; }); afterEach(() => { jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; }); var resultDataset = "KernelDensity_leafletTest"; //点密度分析 it('densityAnalysis', (done) => { var densityAnalystParameters = new DensityKernelAnalystParameters({ //指定数据集 dataset: "Railway@Changchun", //指定范围 bounds: L.bounds([3800, -3800], [8200, -2200]), //指定数据集中用于核密度分析的字段 fieldName: "SmLength", searchRadius: 50, //Railway@Changchun的单位是米 // 结果数据集名称 resultGridName: resultDataset, deleteExistResultDataset: true }); var densityAnalystService = spatialAnalystService(spatialAnalystURL, options); densityAnalystService.densityAnalysis(densityAnalystParameters, (densityServiceResult) => { serviceResult = densityServiceResult; }); setTimeout(() => { try { expect(densityAnalystService).not.toBeNull(); expect(serviceResult).not.toBeNull(); expect(serviceResult.type).toBe("processCompleted"); var result = serviceResult.result; expect(result).not.toBeNull(); expect(result.dataset).toEqual(resultDataset + "@Changchun"); expect(result.succeed).toBe(true); densityAnalystService.destroy(); done(); } catch (exception) { console.log("'densityAnalysis'案例失败" + exception.name + ":" + exception.message); densityAnalystService.destroy(); expect(false).toBeTruthy(); done(); } }, 5000); }); // 删除测试过程中产生的测试数据集 it('delete test resources', (done) => { var testResult = GlobeParameter.datachangchunURL + resultDataset; request.delete(testResult); done(); }); });
JavaScript
0
@@ -221,16 +221,71 @@ equest'; +%0Aimport %7BFetchRequest%7D from %22@supermap/iclient-common%22; %0A%0Avar sp @@ -1429,320 +1429,711 @@ -densityAnalystService.densityAnalysis(densityAnalystParameters, (densityServiceResult) =%3E %7B%0A serviceResult = densityServiceResult;%0A %7D);%0A setTimeout(() =%3E %7B%0A try %7B%0A expect(densityAnalystService).not.toBeNull();%0A expect(serviceResult).not.toBeNull( +spyOn(FetchRequest, 'commit').and.callFake((method, testUrl, params, options) =%3E %7B%0A expect(method).toBe(%22POST%22);%0A expect(testUrl).toBe(spatialAnalystURL + %22/datasets/Railway@Changchun/densityanalyst/kernel.json?returnContent=true%22);%0A var expectParams = %60%7B'bounds':%7B'left':3800,'bottom':-3800,'right':8200,'top':-2200,'centerLonLat':null%7D,'fieldName':%22SmLength%22,'resultGridDatasetResolution':null,'searchRadius':50,'targetDatasource':null,'resultGridName':%22KernelDensity_leafletTest%22,'deleteExistResultDataset':true%7D%60;%0A expect(params).toBe(expectParams);%0A expect(options).not.toBeNull();%0A return Promise.resolve(new Response(expectParams) );%0A @@ -2135,32 +2135,36 @@ ));%0A +%7D);%0A expect(servi @@ -2155,89 +2155,97 @@ -expect(serviceResult.type).toBe(%22processCompleted%22);%0A var result = +densityAnalystService.densityAnalysis(densityAnalystParameters, (result) =%3E %7B%0A ser @@ -2258,17 +2258,19 @@ sult -. + = result;%0A @@ -2261,24 +2261,81 @@ t = result;%0A + %7D);%0A setTimeout(() =%3E %7B%0A try %7B%0A @@ -2341,25 +2341,32 @@ expect( -r +serviceR esult).not.t @@ -2403,60 +2403,51 @@ ect( -result.dataset).toEqual(resultDataset + %22@Changchun%22 +serviceResult.type).toBe('processCompleted' );%0A @@ -2468,16 +2468,30 @@ expect( +serviceResult. result.s @@ -2506,13 +2506,15 @@ toBe -(true +Truthy( );%0A @@ -2878,208 +2878,7 @@ );%0A%0A - // %E5%88%A0%E9%99%A4%E6%B5%8B%E8%AF%95%E8%BF%87%E7%A8%8B%E4%B8%AD%E4%BA%A7%E7%94%9F%E7%9A%84%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE%E9%9B%86%0A it('delete test resources', (done) =%3E %7B%0A var testResult = GlobeParameter.datachangchunURL + resultDataset;%0A request.delete(testResult);%0A done();%0A %7D);%0A %7D);
cb91df43b84ec38ecbc88dc8b5a534e814a899f4
Stop tracking session if not logged in
client/js/app/auth/auth.js
client/js/app/auth/auth.js
angular.module('auth', ['flash']) .controller("LoginCtrl", ["$scope", "authentication", function ($scope, authentication) { $scope.login = function () { authentication.login($scope.username, $scope.password); }; }]) .controller("LogoutCtrl", ["authentication", function (authentication) { authentication.logout(); }]) .config(['$httpProvider', function($httpProvider) { $httpProvider.interceptors.push('authHttpResponseInterceptor'); }]) .factory('authHttpResponseInterceptor',['$q','$location', '$injector', '$rootScope', function($q, $location, $injector, $rootScope) { return { request: function(config) { var authentication = $injector.get('authentication'); var user = authentication.getUserInfo(); var apiCall = _.startsWith(config.url, '/api/'); if (user && apiCall) { config.headers['X-Access-Token'] = user.token; } console.log("DOING REQUEST: ", config); return config || $q.when(config); }, response: function(response){ if (response.headers('X-Access-Token-Renewed')) { var authentication = $injector.get('authentication'); authentication.registerActivity(); } return response || $q.when(response); }, responseError: function(rejection) { if (rejection.status === 401) { $rootScope.$broadcast("auth:unauthorized"); } return $q.reject(rejection); } } }]) .run(["$rootScope", "$location", function ($rootScope, $location) { $rootScope.$on("auth:unauthorized", function () { $location.path("/login"); }); $rootScope.$on("auth:login", function () { $location.path("/"); }); $rootScope.$on("auth:logout", function () { $location.path("/login"); }); }]) .factory("authentication", ["$http", "$q", "$window", 'flash', '$rootScope', '$timeout', 'config', function ($http, $q, $window, flash, $rootScope, $timeout, config) { var userInfo; var lastActivity; function login(username, password) { $http({ method: "POST", url: "/api/auth/token", data: { username: username, password: password } }).then(function (result) { userInfo = result.data; $window.sessionStorage["userInfo"] = JSON.stringify(userInfo); flash.clear(); $rootScope.$broadcast('auth:login', {userInfo: userInfo}); trackSession(); console.log("LOGIN SUCCESS: ", userInfo); }, function (error) { if (error.status === 401) { flash.error("Login failed: bad username or password"); console.log("LOGIN FAILED: ", error); } else { throw error; } }); } function logout() { $http({ method: "DELETE", url: "/api/auth/token" }).then(function (result) { clearUserInfo(); $rootScope.$broadcast('auth:logout'); console.log("LOGGED OUT"); }, function (error) { console.error("NOT LOGGED OUT: ", error); }); } function trackSession() { $timeout(function () { var tokenAge = new Date() - lastActivity; if (tokenAge > config.accessTokenTTL) { logout(); } else { console.log(tokenAge); trackSession(); } }, 1000) } function getUserInfo() { return userInfo; } function clearUserInfo() { userInfo = null; $window.sessionStorage["userInfo"] = null; } function registerActivity() { lastActivity = new Date(); } function init() { userInfo = JSON.parse($window.sessionStorage["userInfo"]); if (userInfo) { registerActivity(); trackSession(); } } init(); $rootScope.$on("auth:unauthorized", function () { clearUserInfo(); }); return { login: login, logout: logout, getUserInfo: getUserInfo, registerActivity: registerActivity }; }]);
JavaScript
0
@@ -4035,16 +4035,37 @@ timeout( +%0A function @@ -4062,32 +4062,140 @@ function () %7B%0A + if (!userInfo) %7B%0A return;%0A %7D%0A%0A @@ -4256,24 +4256,28 @@ + + if (tokenAge @@ -4324,24 +4324,28 @@ + logout();%0A @@ -4354,32 +4354,36 @@ + + %7D else %7B%0A @@ -4383,51 +4383,8 @@ - console.log(tokenAge);%0A @@ -4431,34 +4431,42 @@ -%7D%0A + %7D%0A
42bf745ad768637698bb8682bb08b7a0cb549234
handle local templates correctly
src/init/init-custom.js
src/init/init-custom.js
import debug from 'debug'; import fs from 'fs-promise'; import glob from 'glob'; import resolvePackage from 'resolve-package'; import ora from 'ora'; import path from 'path'; import { copy } from './init-starter-files'; import asyncOra from '../util/ora-handler'; import installDepList from '../util/install-dependencies'; const d = debug('electron-forge:init:custom'); export default async (dir, template, lintStyle) => { let templateModulePath; await asyncOra(`Locating custom template: "${template}"`, async () => { try { templateModulePath = await resolvePackage(`electron-forge-template-${template}`); d('using global template'); } catch (err) { try { templateModulePath = require(`electron-forge-template-${template}`); d('using local template'); } catch (err2) { throw `Failed to locate custom template: "${template}"\n\nTry \`npm install -g electron-forge-template-${template}\``; } } }); let templateModule = require(templateModulePath); templateModule = templateModule.default || templateModule; await asyncOra('Installing Template Dependencies', async () => { d('installing dependencies'); await installDepList(dir, templateModule.dependencies || []); d('installing devDependencies'); await installDepList(dir, templateModule.devDependencies || [], true); }); await asyncOra('Copying Template Files', async () => { const templateDirectory = templateModule.templateDirectory; if (templateDirectory) { const tmplPath = templateDirectory; if (!path.isAbsolute(templateDirectory)) { throw `Custom template path needs to be absolute, this is an issue with "electron-forge-template-${template}"`; } const files = glob.sync(path.resolve(tmplPath, '**/*')); for (const file of files) { if ((await fs.stat(file)).isFile()) { await copy(file, path.resolve(dir, path.relative(tmplPath, file).replace(/^_/, '.'))); } } } }); if (typeof templateModule.postCopy === 'function') { await Promise.resolve(templateModule.postCopy(dir, ora.ora, lintStyle)); } };
JavaScript
0
@@ -719,16 +719,24 @@ require +.resolve (%60electr
57a783df7c6e25d9e7a3b25a8b39811f27df01a0
remove TODO for instancing tests.
test/batch-attributes.js
test/batch-attributes.js
var tape = require('tape') var createContext = require('./util/create-context') var createREGL = require('../regl') tape('batch mode attributes', function (t) { var gl = createContext(5, 5) var regl = createREGL(gl) var command = regl({ frag: [ 'precision mediump float;', 'void main() {', 'gl_FragColor = vec4(1, 1, 1, 1);', '}' ].join('\n'), vert: [ 'precision mediump float;', 'attribute vec2 position;', 'varying vec4 fragColor;', 'void main() {', 'gl_Position=vec4(2.0 * (position + 0.5) / 5.0 - 1.0, 0, 1);', '}' ].join('\n'), attributes: { position: regl.prop('position') }, depth: {enable: false, mask: false}, primitive: regl.prop('primitive'), count: regl.prop('count'), offset: regl.prop('offset'), instances: regl.prop('instances') }) function checkPixmap (args, expected, remark) { regl.clear({ color: [0, 0, 0, 0] }) command(args) var pixels = regl.read() var actual = new Array(25) for (var i = 0; i < 25; ++i) { actual[i] = Math.min(pixels[4 * i], 1) } t.same(actual, expected, remark) } // point checkPixmap({ position: regl.buffer([0, 0]), primitive: 'points', count: 1, offset: 0, instances: -1 }, [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], 'point simple') // point checkPixmap({ position: regl.buffer([3, 1]), primitive: 'points', count: 1, offset: 0, instances: -1 }, [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], 'point 3,1') // point batch checkPixmap([{ position: regl.buffer([0, 0]), primitive: 'points', count: 1, offset: 0, instances: -1 }, { position: regl.buffer([2, 2, 2, 4]), primitive: 'points', count: 2, offset: 0, instances: -1 }], [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ], 'batch points') checkPixmap([{ position: {buffer: regl.buffer([0, 0, 4, 0, 4, 4, -1, 4]), offset: 0}, primitive: 'line strip', count: 4, offset: 0, instances: -1 }], [ 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 ], 'line strip') // check offsets checkPixmap({ position: regl.buffer([0, 0, 1, 0]), primitive: 'point', count: 1, offset: 1, instances: -1 }, [ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], 'offset') checkPixmap([{ position: regl.buffer([0, 0, 1, 0]), primitive: 'point', count: 1, offset: 1, instances: -1 }], [ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], 'offset - batch') // check instancing if (gl.getExtension('angle_instanced_arrays')) { // todo } regl.destroy() createContext.destroy(gl) t.end() })
JavaScript
0
@@ -2880,98 +2880,8 @@ ')%0A%0A - // check instancing%0A if (gl.getExtension('angle_instanced_arrays')) %7B%0A // todo%0A %7D%0A%0A re
04ea890098808c05d870a74779c9d8d697404ad3
add requestAnimationFrame polyfill test cases
test/polyfills/requestAnimationFrame.spec.js
test/polyfills/requestAnimationFrame.spec.js
/* global describe, it, expect */ import requestAnimationFrame from '../../src/polyfills/requestAnimationFrame'; describe('Polyfills', () => { describe('requestAnimationFrame()', () => { it('should be function', () => { const result = requestAnimationFrame; expect(result).to.be.a('function'); }); // it('should throttle callback calls', () => { // // ... // }); }); });
JavaScript
0
@@ -23,16 +23,23 @@ , expect +, sinon */%0Aimpo @@ -41,37 +41,28 @@ %0Aimport -requestAnimationFrame +%7B polyfill %7D from '. @@ -230,85 +230,236 @@ -const result = requestAnimationFrame;%0A expect(result).to.be.a('function' +expect(polyfill).to.be.a('function');%0A %7D);%0A%0A it('should invoke callback when called', () =%3E %7B%0A const spy = sinon.spy();%0A polyfill(spy);%0A setTimeout(() =%3E %7B%0A expect(spy).to.have.been.called;%0A %7D, 0 );%0A @@ -469,19 +469,16 @@ %7D);%0A%0A - // it('sho @@ -499,20 +499,26 @@ allback -call +invocation s', () = @@ -529,26 +529,185 @@ -// // ...%0A // + const spy = sinon.spy();%0A polyfill(spy);%0A polyfill(spy);%0A polyfill(spy);%0A setTimeout(() =%3E %7B%0A expect(spy).to.have.been.calledOnce;%0A %7D, 75);%0A %7D);
f943a4be1d2e3185004305ec0d036be20a823264
Implement #jump, #kick, #toggle methods
src/interdimensional.js
src/interdimensional.js
!(function(window, document) { 'use strict'; var isCharged = false; var isOn = false; var lastAlpha; var lastBeta; var control; var settings = { speed: 150, insensitivity: 5 }; function calcShift(lastAngle, newAngle) { var diff = newAngle - lastAngle; var absDiff = Math.abs(diff); var sign = diff === 0 ? 0 : diff / absDiff; return absDiff > settings.insensitivity ? settings.speed * ((newAngle - sign * settings.insensitivity) / lastAngle - 1) : 0; } function handleTouchStartEvent() { isOn = !isOn; control.classList.toggle('interdimensional-control-is-active'); } function handleDeviceOrientationEvent(e) { if (!isOn) { lastAlpha = e.alpha; lastBeta = e.beta; } else { window.scrollBy( calcShift(lastAlpha, e.alpha), calcShift(lastBeta, e.beta) ); } } function Interdimensional() {} Interdimensional.charge = function() { if (isCharged) { return this; } isCharged = true; control = document.createElement('div'); control.className = 'interdimensional-control'; document.body.appendChild(control); // Add event listeners control.addEventListener('touchstart', handleTouchStartEvent, false); window.addEventListener('deviceorientation', handleDeviceOrientationEvent, false); return this; }; Interdimensional.jump = function() { if (!isCharged) { return this; } return this; }; Interdimensional.kick = function() { if (!isCharged) { return this; } return this; }; Interdimensional.discharge = function() { if (!isCharged) { return this; } return this; }; window.Interdimensional = Interdimensional; })(window, document);
JavaScript
0.000001
@@ -545,87 +545,32 @@ -isOn = !isOn;%0A control.classList.toggle('interdimensional-control-is-active' +Interdimensional.toggle( );%0A @@ -1392,32 +1392,115 @@ rn this;%0A %7D%0A%0A + isOn = true;%0A control.classList.add('interdimensional-control-is-active');%0A%0A return this; @@ -1593,35 +1593,238 @@ %0A %7D%0A%0A -return this +isOn = false;%0A control.classList.remove('interdimensional-control-is-active');%0A%0A return this;%0A %7D;%0A%0A Interdimensional.toggle = function() %7B%0A return isOn ? Interdimensional.kick() : Interdimensional.jump() ;%0A %7D;%0A%0A In
4beceae6d8e821d8520657a3eda924c75821355f
Update the GMail message producer to support the new tokenstore.
lib/producers/gmail/GMailMessageProducer.js
lib/producers/gmail/GMailMessageProducer.js
var base = require( '../ProducerBase.js' ); var ImapService = require( '../imap/ImapService.js' ); function GMailMessageProducer( fetcher ) { this.fetcher = fetcher; base.init( this ); } base.inherit( GMailMessageProducer ); GMailMessageProducer.prototype.getMatchPatterns = function() { return [ '^acct:((imap)|(gmail)):.+', '/message/x-gm-msgid/[0-9]+$' ]; } GMailMessageProducer.prototype.attemptRequest = function( uri, owner, source, resource, keys, callback ) { var self = this; var parsedResource = resource.match( /\/message\/x-gm-msgid\/([0-9]+)$/ ); var messageId = parseInt( parsedResource[1] ); ImapService.searchForMessages( owner, keys, "[Gmail]/All Mail", [ [ 'X-GM-MSGID', messageId ] ], function( error, data ){ if( error ) callback( error, null ); else if( data[0] ) { callback( null, { 'uri': uri, 'data': data[0] }); } else { var error = new Error( '(GMailMessageProducer) Undefined message data[0] for uri: ' + uri ); error.data = data; error.uri = uri; callback( error, null ); } } ); }; module.exports = exports = GMailMessageProducer;
JavaScript
0
@@ -422,16 +422,28 @@ unction( + tokenStore, uri, ow @@ -627,16 +627,257 @@ %5B1%5D );%0A%0A + try %7B%0A tokenStore.getUserTokens( owner, source, function( error, data ) %7B%0A if( error )%0A %7B%0A callback( error );%0A %7D%0A else%0A %7B%0A try %7B%0A %09ImapSer @@ -907,20 +907,35 @@ owner, -keys +data.connectionData , %22%5BGmai @@ -982,16 +982,32 @@ d %5D %5D, %0A + @@ -1039,36 +1039,68 @@ -if( error )%0A + if( error )%0A @@ -1136,24 +1136,40 @@ + + else if( dat @@ -1179,34 +1179,66 @@ %5D )%0A -%7B%0A + %7B%0A @@ -1275,16 +1275,32 @@ + + 'uri': u @@ -1324,16 +1324,32 @@ + + 'data': @@ -1372,16 +1372,32 @@ + + %7D);%0A @@ -1396,34 +1396,56 @@ %7D);%0A + -%7D%0A + %7D%0A else @@ -1432,32 +1432,42 @@ + else%0A @@ -1459,34 +1459,66 @@ lse%0A -%7B%0A + %7B%0A @@ -1606,24 +1606,40 @@ ' + uri );%0A + @@ -1673,24 +1673,40 @@ + + error.uri = @@ -1710,16 +1710,32 @@ = uri;%0A + @@ -1783,22 +1783,223 @@ -%7D%0A %7D ); + %7D%0A %7D );%0A %7D catch( err ) %7B%0A callback( err );%0A %7D%0A %7D%0A %7D );%0A%0A %7D catch( err ) %7B%0A callback( err );%0A %7D %0A%7D;%0A
43d25fdb280957ec382c88404b1a81c3101825ec
Remove body styles on unmount
src/components/Modal.js
src/components/Modal.js
import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import { CSSTransitionGroup } from 'react-transition-group'; import blacklist from 'blacklist'; import classNames from 'classnames'; import createReactClass from 'create-react-class'; import { canUseDOM } from '../constants'; const TransitionPortal = createReactClass({ displayName: 'TransitionPortal', componentDidMount () { if (!canUseDOM) return; let p = document.createElement('div'); document.body.appendChild(p); this.portalElement = p; this.componentDidUpdate(); }, componentDidUpdate () { if (!canUseDOM) return; ReactDOM.render(<CSSTransitionGroup {...this.props}>{this.props.children}</CSSTransitionGroup>, this.portalElement); }, componentWillUnmount () { if (!canUseDOM) return; document.body.removeChild(this.portalElement); }, portalElement: null, render: () => null, }); const Modal = createReactClass({ displayName: 'Modal', propTypes: { autoFocusFirstElement: PropTypes.bool, backdropClosesModal: PropTypes.bool, className: PropTypes.string, isOpen: PropTypes.bool, onCancel: PropTypes.func, width: PropTypes.oneOfType([ PropTypes.oneOf(['small', 'medium', 'large']), PropTypes.number, ]), }, getDefaultProps () { return { width: 'medium', }; }, componentWillReceiveProps: function (nextProps) { if (!canUseDOM) return; const target = document.body; const scrollbarWidth = window.innerWidth - document.body.clientWidth; // 1. if (!this.props.isOpen && nextProps.isOpen) { // setTimeout(() => this.handleAccessibility()); target.style.overflow = 'hidden'; target.style.paddingRight = scrollbarWidth + 'px'; } else if (this.props.isOpen && !nextProps.isOpen) { // setTimeout(() => this.removeAccessibilityHandlers()); target.style.overflow = ''; target.style.paddingRight = ''; } }, /* handleAccessibility () { // Remember the element that was focused before we opened the modal // so we can return focus to it once we close the modal. this.focusedElementBeforeModalOpened = document.activeElement; // We're using a transition to reveal the modal, // so wait until the element is visible, before // finding the first keyboard focusable element // and passing focus to it, otherwise the browser // might scroll the document to reveal the element // receiving focus if (this.props.autoFocusFirstElement) { ally.when.visibleArea({ context: this.modalElement, callback: function(context) { // the modal is visible on screen, so find the first // keyboard focusable element (giving any element with // autoFocus attribute precendence). If the modal does // not contain any keyboard focusabe elements, focus will // be given to the modal itself. var element = ally.query.firstTabbable({ context: context, defaultToContext: true, }); element.focus(); }, }); } // Make sure that no element outside of the modal // can be interacted with while the modal is visible. this.disabledHandle = ally.maintain.disabled({ filter: this.modalElement, }); // Make sure that no element outside of the modal // is exposed via the Accessibility Tree, to prevent // screen readers from navigating to content it shouldn't // be seeing while the modal is open. this.hiddenHandle = ally.maintain.hidden({ filter: this.modalElement, }); // React to escape keys as mandated by ARIA Practices this.keyHandle = ally.when.key({ escape: this.handleClose, }); }, removeAccessibilityHandlers () { // undo listening to keyboard this.keyHandle && this.keyHandle.disengage(); // undo hiding elements outside of the modal this.hiddenHandle && this.hiddenHandle.disengage(); // undo disabling elements outside of the modal this.disabledHandle && this.disabledHandle.disengage(); // return focus to where it was before we opened the modal this.focusedElementBeforeModalOpened && this.focusedElementBeforeModalOpened.focus(); }, handleModalClick (event) { if (event.target.dataset.modal) this.handleClose(); }, */ handleClose () { const { backdropClosesModal, onCancel } = this.props; console.log('handleClose', backdropClosesModal); if (backdropClosesModal) onCancel(); }, handleDialogClick (event) { event.stopPropagation(); }, renderDialog () { const { children, isOpen, width } = this.props; if (!isOpen) return; const style = (width && !isNaN(width)) ? { width: width + 20 } : null; const dialogClassname = classNames('Modal-dialog', (width && isNaN(width)) ? 'Modal-dialog--' + width : null); return ( <div className={dialogClassname} style={style} onClick={this.handleDialogClick}> <div ref={r => (this.modalElement = r)} className="Modal-content"> {children} </div> </div> ); }, renderBackdrop () { const { isOpen } = this.props; if (!isOpen) return; return <div className="Modal-backdrop" />; }, render () { const className = classNames('Modal', { 'is-open': this.props.isOpen, }, this.props.className); const props = blacklist(this.props, 'backdropClosesModal', 'className', 'isOpen', 'onCancel'); return ( <div> <TransitionPortal {...props} className={className} data-modal="true" onClick={this.handleClose} transitionEnterTimeout={260} transitionLeaveTimeout={140} transitionName="Modal-dialog" > {this.renderDialog()} </TransitionPortal> <TransitionPortal transitionName="Modal-background" transitionEnterTimeout={140} transitionLeaveTimeout={240} > {this.renderBackdrop()} </TransitionPortal> </div> ); }, }); // expose the children to the top level export Modal.Body = require('./ModalBody'); Modal.Footer = require('./ModalFooter'); Modal.Header = require('./ModalHeader'); export default Modal;
JavaScript
0
@@ -1884,16 +1884,180 @@ %09%09%7D%0A%09%7D,%0A +%09componentWillUnmount: function () %7B%0A%09%09if (!canUseDOM) return;%0A%0A%09%09const target = document.body;%0A%09%09target.style.overflow = '';%0A%09%09target.style.paddingRight = '';%0A%09%7D,%0A %09/*%0A%09han
19becb72112efcc3df23c75a120ddca053e18b08
Add a primary key to JavaDemo
test/browser/JavaDemo.js
test/browser/JavaDemo.js
foam.CLASS({ package: 'com.example', name: 'Person', properties: [ { class: 'String', name: 'name' }, { class: 'Boolean', name: 'employed' } ] }); var cls = foam.java.Class.create(); com.example.Person.buildJavaClass(cls); var output = foam.java.Outputter.create(); output.out(cls); foam.u2.Element.create().setNodeName('pre').add(output.buf_).write()
JavaScript
0.000001
@@ -51,16 +51,33 @@ erson',%0A + ids: %5B'name'%5D,%0A proper
ea3fc2d83744be6306bf3ba9d7147aa957613f20
test written for max temp during power save
spec/thermostatSpec.js
spec/thermostatSpec.js
describe("Thermostat", function(){ var thermostat; beforeEach(function(){ thermostat = new Thermostat(); }); describe("by default", function(){ it("thermostat should start at 20 degrees", function(){ expect(thermostat.temperature).toEqual(20) }); }); describe("changing temperature", function(){ it("should be able to increase temperature", function(){ thermostat.increaseTemp(1) expect(thermostat.temperature).toEqual(21) }); it("should be able to decrease temperature", function(){ thermostat.decreaseTemp(1) expect(thermostat.temperature).toEqual(19) }); }); describe("maximum and minimum temperature", function(){ it("should have a maximum temperature of 32 degrees", function(){ expect(thermostat.maxTemp).toEqual(32) }); it("should have a minimum temperature of 10 degrees", function(){ expect(thermostat.minTemp).toEqual(10) }); it("temperature should not be able to go above 32 degrees", function(){ thermostat.increaseTemp(25) expect(thermostat.temperature).toEqual(32) }); it("temperature should not be able to go below 10 degrees", function(){ thermostat.decreaseTemp(40) expect(thermostat.temperature).toEqual(10) }); }); describe("reset capabilities", function(){ it("should go back to 20 degrees after being reset", function(){ thermostat.increaseTemp(5) expect(thermostat.temperature).toEqual(25) thermostat.resetButton() expect(thermostat.temperature).toEqual(20) }); }); });
JavaScript
0
@@ -1502,12 +1502,224 @@ ;%0A%0A%7D);%0A%0A +describe(%22power save mode%22, function()%7B%0A%0A it(%22should have a maximum temperature of 25 degrees when power save is on%22, function()%7B%0A thermostat.powerSave()%0A expect(thermostat.maxTemp).toEqual(25)%0A %7D);%0A%7D);%0A%0A %0A%7D);
4bc117d042b072a5cb791dd83eaab925b1700d8e
add two test for childNodeType and rootNodeType attributes
jasmine/spec/NotesPresenterSpec.js
jasmine/spec/NotesPresenterSpec.js
describe("NotePresenter", function(){ beforeEach(function() { dummyNote = { noteTime: "0:30", noteContent: "I'm a dummy note" }; notePresenter = new PinPoint.NotePresenter(dummyNote); }); it("should be defined.", function(){ expect(notePresenter).toBeDefined(); }); it("should contain a note when instantiated",function(){ expect(notePresenter.note).toBeDefined; expect(notePresenter.note).not.toEqual(undefined); expect(notePresenter.note).not.toEqual(null); }) });
JavaScript
0
@@ -511,12 +511,248 @@ ;%0A %7D)%0A%0A + it(%22should contain a rootNodeType of 'tr'%22,function() %7B%0A expect(notePresenter.rootNodeType).toEqual('tr');%0A %7D)%0A it(%22should contain a childNodeType of 'td'%22,function() %7B%0A expect(notePresenter.childNodeType).toEqual('td');%0A %7D)%0A%0A %7D); -%0A
e458fb231a811e748c0b20d281caf770e2164c4a
Add week-begins-on-monday option
src/ionic-datepicker.js
src/ionic-datepicker.js
//By Rajeshwar Patlolla //https://github.com/rajeshwarpatlolla 'use strict'; angular.module('ionic-datepicker', ['ionic', 'ionic-datepicker.templates']) .directive('ionicDatepicker', ['$ionicPopup', function ($ionicPopup) { return { restrict: 'AE', replace: true, scope: { value: '=value' }, link: function (scope, element, attrs) { var currentDate = angular.copy(scope.value) || new Date(); // Date for the UI calendar display scope.selectedDate = currentDate; // Temporary selected date before the 'Set' or 'Today' is pressed scope.dayInitials = ['S', 'M', 'T', 'W', 'T', 'F', 'S']; scope.calendarRows = new Array(6); scope.calendarCols = new Array(7); var refreshCalendar = function (currentDate) { scope.dayList = []; var firstDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1).getDate(); var lastDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0).getDate(); for (var i = firstDay; i <= lastDay; i++) { var tempDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), i); scope.dayList.push({ date: tempDate, day: tempDate.getDate() }); } // Offset the first of the month to match the week day firstDay = scope.dayList[0].date.getDay(); for (var j = 0; j < firstDay; j++) { scope.dayList.unshift(undefined); } scope.currentMonth = currentDate.getMonth(); scope.currentYear = currentDate.getFullYear(); }; // Go to previous month scope.prevMonth = function () { currentDate.setMonth(currentDate.getMonth() - 1); scope.currentMonth = currentDate.getMonth(); scope.currentYear = currentDate.getFullYear(); refreshCalendar(currentDate) }; // Go to next month scope.nextMonth = function () { currentDate.setMonth(currentDate.getMonth() + 1); scope.currentMonth = currentDate.getMonth(); scope.currentYear = currentDate.getFullYear(); refreshCalendar(currentDate) }; scope.setDate = function (date) { if (typeof date !== 'undefined') { scope.selectedDate = date.date; } }; // Check if the day is valid (for CSS class) scope.isValidDay = function (rowIndex, colIndex) { var day = scope.dayList[rowIndex * 7 + colIndex]; return (typeof day !== 'undefined'); }; // Check if the day should be selected (for CSS class) scope.isSelected = function (rowIndex, colIndex) { if (scope.isValidDay(rowIndex, colIndex)) { var day = scope.dayList[rowIndex * 7 + colIndex] return (day.date.toDateString() === scope.selectedDate.toDateString()); } return false; }; // Check if the day is today (for CSS class) scope.isToday = function (rowIndex, colIndex) { if (scope.isValidDay(rowIndex, colIndex)) { return (scope.dayList[rowIndex * 7 + colIndex].date.toDateString() === new Date().toDateString()); } return false; } element.on('click', function () { refreshCalendar(currentDate); $ionicPopup.show({ templateUrl: 'date-picker-modal.html', title: '<strong>Select Date</strong>', subTitle: '', scope: scope, buttons: [ { text: 'Close' }, { text: 'Today', onTap: function () { var now = new Date(); scope.setDate({ date: now }); scope.value = now; } }, { text: 'Set', type: 'button-positive', onTap: function () { scope.value = scope.selectedDate; } } ] }) }) } } }]);
JavaScript
0.999975
@@ -309,21 +309,49 @@ alue: '= -value +',%0A weekBeginsOnMonday: '@ '%0A @@ -676,16 +676,136 @@ ', 'S'%5D; +%0A if (scope.weekBeginsOnMonday %7C%7C false) %7B%0A scope.dayInitials.push(scope.dayInitials.shift());%0A %7D %0A%0A @@ -1559,24 +1559,111 @@ e.getDay();%0A + if (scope.weekBeginsOnMonday %7C%7C false) %7B%0A firstDay--;%0A %7D%0A fo
7c7f56293f24e63060fc1912c97a135567e2e347
Improve getQueueBindings() comments
lib/RabbitManagement.js
lib/RabbitManagement.js
'use strict'; require('isomorphic-fetch'); const URL = require('url'); class RabbitManagement { constructor({ protocol, hostname, port, username, password, vhost }) { this.baseURL = URL.format({ protocol, hostname, port, // Plugin rabbitmq_management API always lives under /api/ pathname: '/api', }); // Create basic auth header. this.authHeader = Buffer(`${username}:${password}`).toString('base64'); // Expose AMQP vhost for building correct API endpoints. this.vhost = vhost; } async getQueueInfo(queue) { const endpoint = `/queues/${this.vhost}/${queue.name}`; let response = {}; try { response = await this.get(endpoint); } catch (error) { // Wrap HTTP exceptions in meaningful response. throw new Error(`Incorrect RabbitManagement.getQueueInfo() response for GET ${endpoint}: ${error.message}`); } return response; } async getQueueBindings(queue) { const endpoint = `/bindings/${this.vhost}/e/${queue.exchange.name}/q/${queue.name}`; const response = await this.get(endpoint); // Response always returns 200 and valid JSON. // Return false when not bindings found. if (response.length < 1) { return false; } return response; } async get(endpoint) { const options = this.getFetchDefaults(); const fullUrl = this.fullUri(endpoint); const response = await fetch(fullUrl, options); return RabbitManagement.handleFetchResponse(response); } static handleFetchResponse(response) { // Tolerate "200 OK" responses only. if (response.status !== 200) { throw new Error(`RabbitManagement.handleFetchResponse(): HTTP status ${response.status}: ${response.statusText}`); } // Always expect correct 200 response to have JSON body. return response.json(); } fullUri(endpoint) { return `${this.baseURL}${endpoint}`; } getFetchDefaults() { return { headers: { Authorization: `Basic ${this.authHeader}`, }, }; } } module.exports = RabbitManagement;
JavaScript
0
@@ -1108,23 +1108,11 @@ // -Response always +API ret @@ -1128,47 +1128,27 @@ and -valid JSON.%0A // Return false +empty array when no t bi @@ -1143,17 +1143,16 @@ when no -t binding @@ -1187,24 +1187,162 @@ ngth %3C 1) %7B%0A + // Return false if queue is not bound to its exchange:%0A // by design of this app a queue should have at least one valid route.%0A return
d0a1118bf64348e234dc5d932654b98a3d8e2308
Use absolute URL
ideascube/static/ideascube/js/ideascube.js
ideascube/static/ideascube/js/ideascube.js
/*global document window Pikaday console gettext*/ /* eslint new-cap:0, strict:0, quotes:[2, "single"] global-strict:0, no-underscore-dangle:0, curly:0, consistent-return:0, no-new:0, no-console:0, space-before-function-paren:[2, "always"] */ 'use strict'; ID.http = { _ajax: function (settings) { var xhr = new window.XMLHttpRequest(); xhr.open(settings.verb, settings.uri, true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { settings.callback.call(settings.context || xhr, xhr.status, xhr.responseText, xhr); } }; xhr.send(settings.data); return xhr; }, get: function (uri, options) { options.verb = 'GET'; options.uri = uri; return ID.http._ajax(options); }, queryString: function (params) { var queryString = []; for (var key in params) { queryString.push(encodeURIComponent(key) + '=' + encodeURIComponent(params[key])); } return queryString.join('&'); } }; ID.PROVIDERS = { '^(http(s)?://)?(www\.)?(youtube\.com|youtu\.be)': 'http://www.youtube.com/oembed', '^(http(s)?://)?(www\.)?dailymotion\.com': 'http://www.dailymotion.com/services/oembed', '^(https?://)?vimeo.com/': 'http://vimeo.com/api/oembed.json', '^(https?://)?(www\.)?flickr.com/': 'https://www.flickr.com/services/oembed/' }; ID.matchProvider = function (value) { ID.PROVIDERS['^(https?://)?((www\.)?' + ID.DOMAIN + '/|localhost)'] = window.location.origin + window.location.pathname.slice(0, 3) + '/mediacenter/oembed/'; for (var provider in ID.PROVIDERS) { if (value.match(provider)) return ID.PROVIDERS[provider]; } }; ID.image_url_resolver = function(data, resolve, reject) { var callback = function (status, resp) { if (status === 200) { try { resp = JSON.parse(resp); } catch (e) { reject({msg: ''}); return; } if (resp.type === 'photo') { var img = document.createElement('IMG'); img.setAttribute('src', resp.url); resolve({html: img.html}); } else if (resp.type === 'video' || resp.type === 'rich') { resolve({html: resp.html}); } else { reject({msg: 'Media type not supported'}); } } }; var providerUrl = ID.matchProvider(data.url); if (providerUrl) { var finalUrl = providerUrl + '?' + ID.http.queryString({url: data.url, format: 'json', maxwidth: '800'}); var proxyUrl = '/ajax-proxy/?' + ID.http.queryString({url: finalUrl}); ID.http.get(proxyUrl, { callback: callback }); } else { reject({msg: 'Media provider not supported'}); } }; ID.initDatepicker = function (name) { new Pikaday({ field: document.querySelector('[name="' + name + '"]'), format: 'YYYY-MM-DD', i18n: { previousMonth: gettext('Previous Month'), nextMonth: gettext('Next Month'), months: [gettext('January'), gettext('February'), gettext('March'), gettext('April'), gettext('May'), gettext('June'), gettext('July'), gettext('August'), gettext('September'), gettext('October'), gettext('November'), gettext('December')], weekdays: [gettext('Sunday'), gettext('Monday'), gettext('Tuesday'), gettext('Wednesday'), gettext('Thursday'), gettext('Friday'), gettext('Saturday')], weekdaysShort: [gettext('Sun'), gettext('Mon'), gettext('Tue'), gettext('Wed'), gettext('Thu'), gettext('Fri'), gettext('Sat')] } }); }; ID.focusOn = function (selector) { var element = document.querySelector(selector); if (element) element.focus(); }; ID.endswith = function (str, suffix) { return str.indexOf(suffix, str.length - suffix.length) !== -1; }; ID.stopEnterKey = function (name) { var el = document.querySelector('[name="' + name + '"]'); if (!el) return; var stop = function (e) { if (e.keyCode === 13) e.preventDefault(); }; el.addEventListener('keydown', stop, false); }; ID.confirmClick = function (selector) { var el = document.querySelector(selector); if (!el) return; var ask = function (e) { if (!confirm(gettext('Are you sure?'))) { e.preventDefault(); return false; } }; el.addEventListener('click', ask, false); }; ID.initWifiList = function (item_selector, popup_selector, urlroot) { var elements = document.querySelectorAll(item_selector); for (var i = 0; i < elements.length; ++i) { var element = elements[i]; var known = element.getAttribute('data-known') === 'True'; var secure = element.getAttribute('data-secure') === 'True'; if (known || !secure) { var ssid = element.getAttribute('data-ssid'); element.setAttribute('href', urlroot + ssid); } else { element.setAttribute('href', popup_selector); element.addEventListener('click', function (evt) { var ssid = this.getAttribute('data-ssid'); var form = document.querySelector(popup_selector + ' form'); form.setAttribute('action', urlroot + ssid); }.bind(element), true); } } }; ID.viewablePassword = function () { var el = document.querySelector('input[type="password"]'); if (!el) return; var wrapper = document.createElement('div'), button = document.createElement('i'), form = el.form; el.parentNode.insertBefore(wrapper, el); wrapper.appendChild(el); el.className = el.className + ' showable-password'; button.className = 'fa fa-eye show-password'; wrapper.appendChild(button); var show = function (e) { el.type = 'text'; window.setTimeout(hide, 1000); }; var hide = function (e) { el.type = 'password'; }; button.addEventListener('click', show, false); form.addEventListener('submit', hide, false); }; ID.initEditors = function () { var editors = document.querySelectorAll(".tinymce-editor"); for (var i = 0; i < editors.length; i++) { var editor = editors[i]; var use_media = editor.hasAttribute('data-tinymce-use-media'); var options = { target : editor, inline: true, theme: "inlite", hidden_input: false, menubar: false, toolbar: false, selection_toolbar: "numlist bullist bold italic | quicklink h1 h2 h3 blockquote", language: editor.getAttribute('data-tinymce-language-code'), media_url_resolver: ID.image_url_resolver, media_alt_source: false, media_poster: false, insert_toolbar: "numlist bullist bold italic | quicklink h1 h2 h3 blockquote", contextmenu: "link", plugins: "autolink textpattern contextmenu lists" }; if ( use_media ) { options['insert_toolbar'] += " media"; options['contextmenu'] += " media"; options['plugins'] += " media"; } tinymce.init(options); } };
JavaScript
0.999999
@@ -6811,24 +6811,59 @@ age-code'),%0A + relative_urls : false,%0A
0e6844dd45078377bac659169117fa382dc66091
Make Net Change first widget of Forest Change tab
components/widgets/forest-change/net-change/index.js
components/widgets/forest-change/net-change/index.js
import { getNetChange } from 'services/analysis-cached'; import { getYearsRangeFromData } from 'components/widgets/utils/data'; import { POLITICAL_BOUNDARIES_DATASET, NET_CHANGE_DATASET, } from 'data/datasets'; import { DISPUTED_POLITICAL_BOUNDARIES, POLITICAL_BOUNDARIES, NET_CHANGE, } from 'data/layers'; import getWidgetProps from './selectors'; const getGlobalLocation = (params) => ({ adm0: params.type === 'global' ? null : params.adm0, adm1: params.type === 'global' ? null : params.adm1, adm2: params.type === 'global' ? null : params.adm2, }); export default { widget: 'netChange', title: { default: 'Components of net change in tree cover in {location}', global: 'Components of net change in tree cover globally', }, categories: ['summary', 'forest-change'], subCategory: 'net-change', types: ['global', 'country', 'geostore', 'aoi', 'wdpa', 'use'], admins: ['global', 'adm0', 'adm1', 'adm2'], caution: { text: 'Would you like to help us understand how to present this data in more helpful ways? {Click here to fill out a survey}', visible: [ 'country', 'geostore', 'aoi', 'wdpa', 'use', 'dashboard', 'global', ], linkText: 'Click here to fill out a survey', link: 'https://survey.alchemer.com/s3/7062032/Provide-feedback-for-Global-Forest-Watch-s-Net-Change-in-Tree-Cover-data-layer', }, large: true, visible: ['dashboard', 'analysis'], chartType: 'pieChart', colors: 'netChange', dataType: 'netChange', metaKey: 'umd_adm0_net_tree_cover_change', datasets: [ { dataset: POLITICAL_BOUNDARIES_DATASET, layers: [DISPUTED_POLITICAL_BOUNDARIES, POLITICAL_BOUNDARIES], boundary: true, }, { dataset: NET_CHANGE_DATASET, layers: [NET_CHANGE], }, ], sortOrder: { summary: -2, forestChange: 1, }, sentence: { globalInitial: 'From 2000 to 2020, the world experienced a net change of {netChange} ({netChangePerc}) change in tree cover.', initial: 'From 2000 to 2020, {location} experienced a net change of {netChange} ({netChangePerc}) change in tree cover.', // noLoss: // 'Fires were responsible for {lossFiresPercentage} of tree cover loss in {location} between {startYear} and {endYear}.', }, getData: (params = {}) => { const { adm0, adm1, adm2, type } = params || {}; const globalLocation = { adm0: type === 'global' ? null : adm0, adm1: type === 'global' ? null : adm1, adm2: type === 'global' ? null : adm2, }; const netChangeFetch = getNetChange({ ...params, ...globalLocation }); return netChangeFetch.then((netChange) => { let data = {}; if (netChange && netChange.data) { data = { netChange: netChange.data.data, }; } const { startYear, endYear, range } = (data.netChange && getYearsRangeFromData(data.netChange)) || {}; return { ...data, settings: { startYear, endYear, yearsRange: range, chartHeight: 230, }, options: { years: range, }, }; }); }, getDataURL: (params) => { const globalLocation = getGlobalLocation(params); return [getNetChange({ ...params, ...globalLocation, download: true })]; }, getWidgetProps, };
JavaScript
0
@@ -1878,17 +1878,18 @@ Change: -1 +-2 ,%0A %7D,%0A
1da96b1a2ea97cb3f482dc07b22c346b3017b601
change comments styling
src/components/Topic.js
src/components/Topic.js
import React from 'react-native'; import relativeDate from '../utils/relative-date'; import Api from '../api'; let { View, Text, StyleSheet, Image, ListView, ScrollView } = React; var styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'white', flexDirection: 'column' }, detail: { flex: 1, alignItems: 'center', backgroundColor: 'white', flexDirection: 'row', padding: 10 }, comments: { padding: 10 }, nested: { marginLeft: 10 }, textContainer: { flex: 1 }, cellImage: { height: 60, borderRadius: 30, marginRight: 10, width: 60 }, title: { flex: 1, fontSize: 16, fontWeight: 'bold', marginBottom: 2 }, info: { flex: 1, flexDirection: 'row', justifyContent: 'space-between' }, domain: { color: '#999999', fontSize: 12 }, time: { fontSize: 12, color: '#cccccc' } }); class Topic extends React.Component { constructor(props) { super(props); let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => { return r1 !== r2; } }); this.state = { dataSource: ds.cloneWithRows([]), loading: true }; Api.getComments(this.props.data.subreddit, this.props.data.id).then((result) => { this.setState({ detail: result.detail, dataSource: this.state.dataSource.cloneWithRows(result.comments), loading: false }); }); } renderComment(item) { var nested = null; if (item.comments && item.comments.length) { nested = ( <View style={styles.nested}> {item.comments.map(this.renderComment.bind(this))} </View> ); } return ( <View style={styles.row} key={item.id}> <View style={styles.textContainer}> <Text style={styles.domain}> {item.author} </Text> <Text style={styles.title}> {item.text} </Text> </View> {nested} <View style={styles.cellBorder} /> </View> ); } render() { if (this.state.loading) { return <Text>Loading</Text>; } let item = this.state.detail; let image = item.image ? ( <Image source={ { uri: item.image } } style={styles.cellImage} /> ) : null; return ( <View style={styles.container}> <ScrollView> <View> <View style={styles.detail}> {image} <View style={styles.textContainer}> <Text style={styles.title}> {item.title} </Text> <View style={styles.info}> <Text style={styles.domain} numberOfLines={1}> {item.domain} </Text> <Text style={styles.time} numberOfLines={1}> {relativeDate(item.created)} </Text> </View> </View> </View> </View> <View style={styles.comments}> <ListView dataSource={this.state.dataSource} renderRow={this.renderComment.bind(this)} /> </View> </ScrollView> </View> ); } } module.exports = Topic;
JavaScript
0
@@ -156,30 +156,32 @@ ,%0A -ListView,%0A ScrollView +ScrollView,%0A PixelRatio %0A%7D = @@ -449,35 +449,188 @@ %0A%0A -comments: %7B%0A padding: 10 +row: %7B%0A paddingTop: 5,%0A paddingBottom: 5%0A %7D,%0A%0A comments: %7B%0A padding: 10%0A %7D,%0A%0A cellBorder: %7B%0A backgroundColor: 'rgba(0, 0, 0, 0.3)',%0A height: 1 / PixelRatio.get() %0A %7D @@ -801,20 +801,19 @@ %7D,%0A t -itle +ext : %7B%0A @@ -888,16 +888,85 @@ 2%0A %7D,%0A + comment: %7B%0A flex: 1,%0A fontSize: 16,%0A marginBottom: 2%0A %7D,%0A info: @@ -1103,16 +1103,72 @@ 12%0A %7D,%0A + author: %7B%0A color: '#999999',%0A fontSize: 12%0A %7D,%0A time: @@ -1305,178 +1305,41 @@ -let ds = new ListView.DataSource(%7B%0A rowHasChanged: (r1, r2) =%3E %7B%0A return r1 !== r2;%0A %7D%0A %7D);%0A%0A this.state = %7B%0A dataSource: ds.cloneWithRows( +this.state = %7B%0A comments: %5B%5D -) ,%0A @@ -1515,56 +1515,18 @@ -dataSource: this.state.dataSource.cloneWithRows( +comments: resu @@ -1536,17 +1536,16 @@ comments -) ,%0A @@ -1604,24 +1604,105 @@ ent(item) %7B%0A + if (item.more) %7B%0A return %3CText key=%7Bitem.id%7D%3EMORE BUTTON%3C/Text%3E;%0A %7D%0A%0A var nest @@ -2042,22 +2042,22 @@ %7Bstyles. -domain +author %7D%3E%0A @@ -2117,37 +2117,39 @@ t style=%7Bstyles. -title +comment %7D%3E%0A %7B @@ -2197,25 +2197,8 @@ ew%3E%0A - %7Bnested%7D%0A @@ -2232,24 +2232,41 @@ lBorder%7D /%3E%0A + %7Bnested%7D%0A %3C/View @@ -3281,92 +3281,33 @@ -%3CListView%0A dataSource=%7Bthis.state.dataSource%7D%0A renderRow=%7B +%7Bthis.state.comments.map( this @@ -3335,24 +3335,10 @@ his) +) %7D -%0A /%3E %0A
48f9cf93deb6f6629ab026d205376045dec0db5b
Fix clone example to use new api
examples/clone.js
examples/clone.js
// Bootstrap the platform to run on node.js require('../lib/platform.js')(require('./node')); // Load the libraries var fsDb = require('../lib/fs-db.js'); var wrap = require('../lib/repo.js'); var each = require('../helpers/each.js'); var autoProto = require('../protocols/auto.js'); var urlParse = require('url').parse; var url = process.argv[2] || "git://github.com/creationix/conquest.git"; var opts = urlParse(url); if (!opts.protocol) { opts = urlParse("ssh://" + url); } var path = opts.pathname.match(/[^\/]*$/)[0]; var connection = autoProto(opts); var repo = wrap(fsDb(path, true)); connection.discover(function (err, result) { if (err) throw err; var refs = result.refs; var wants = []; each(refs, function (name, hash) { if (name === "HEAD" || name.indexOf('^') > 0) return; wants.push("want " + hash); }); connection.negotiate(wants, { serverCaps: result.caps, includeTag: true, // onProgress: onProgress, onError: function (data) { process.stderr.write(data); } }, function (err, packStream) { if (err) throw err; repo.init(function (err) { if (err) throw err; repo.importRefs(refs, function (err) { if (err) throw err; repo.unpack(packStream, { // onProgress: onProgress, }, function (err) { if (err) throw err; console.log("DONE"); }); }); }); }); }); function onProgress(data) { process.stdout.write(data); }
JavaScript
0
@@ -853,17 +853,13 @@ ion. -negotiate +fetch (wan
b6cd3888c64556bafcba9bf9978cdd0b93db3280
remove console
client/src/utils/hightChartOptionsFactory.js
client/src/utils/hightChartOptionsFactory.js
export const hightChartCommon = ( subject, yName, year, data, handleHoverDate = () => {} ) => ({ title: { text: `${year} ${subject}`, x: -20 // center }, subtitle: { text: '', x: -20 }, yAxis: { title: { text: yName }, plotLines: [ { value: 0, width: 1, color: '#808080' } ] }, xAxis: { type: 'datetime', labels: { format: '{value:%m/%d}', rotation: 45, align: 'left' } }, rangeSelector: { selected: 5 }, tooltip: { valueSuffix: '', useHTML: true, formatter() { console.log(this) handleHoverDate(this.points[0].point.date, `${year} ${subject}`) let html = `<span>日期:<span>${this.points[0].point.date}<br>` + `<span>${yName}: <span>${this.points[0].point.y}<br>` if (this.points[0].point.is_settle === true) { html += '<span style="color: red">結算日<span>' } return html } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle', borderWidth: 0 }, series: [ { turboThreshold: 0, name: subject, data } ] }) export const temp = () => { console.log(123) }
JavaScript
0.000002
@@ -611,32 +611,8 @@ ) %7B%0A - console.log(this)%0A
cee6009e13a9c8ed1d089f9b036f88f58dc8d247
Fix for Issue #7: Remove any padding set directly on the table as part of init.
js/jquery.stickytableheaders.js
js/jquery.stickytableheaders.js
/*! Copyright (c) 2011 by Jonas Mosbech - https://github.com/jmosbech/StickyTableHeaders MIT license info: https://github.com/jmosbech/StickyTableHeaders/blob/master/license.txt */ (function ($) { $.StickyTableHeaders = function (el, options) { // To avoid scope issues, use 'base' instead of 'this' // to reference this class from internal events and functions. var base = this; // Access to jQuery and DOM versions of element base.$el = $(el); base.el = el; // Cache DOM refs for performance reasons base.$window = $(window); base.$clonedHeader = null; base.$originalHeader = null; // Add a reverse reference to the DOM object base.$el.data('StickyTableHeaders', base); base.init = function () { base.options = $.extend({}, $.StickyTableHeaders.defaultOptions, options); base.$el.each(function () { var $this = $(this); $this.wrap('<div class="divTableWithFloatingHeader" style="position:relative"></div>'); base.$originalHeader = $('thead:first', this); base.$clonedHeader = base.$originalHeader.clone(); base.$clonedHeader.addClass('tableFloatingHeader'); base.$clonedHeader.css({ 'position': 'fixed', 'top': 0, 'left': $this.css('margin-left'), 'display': 'none' }); base.$originalHeader.addClass('tableFloatingHeaderOriginal'); base.$originalHeader.before(base.$clonedHeader); // enabling support for jquery.tablesorter plugin // forward clicks on clone to original $('th', base.$clonedHeader).click(function(e){ var index = $('th', base.$clonedHeader).index(this); $('th', base.$originalHeader).eq(index).click(); }); $this.bind('sortEnd', base.updateCloneFromOriginal ); }); base.updateTableHeaders(); base.$window.scroll(base.updateTableHeaders); base.$window.resize(base.updateTableHeaders); }; base.updateTableHeaders = function () { base.$el.each(function () { var $this = $(this); var fixedHeaderHeight = isNaN(base.options.fixedOffset) ? base.options.fixedOffset.height() : base.options.fixedOffset; var offset = $this.offset(); var scrollTop = base.$window.scrollTop() + fixedHeaderHeight; var scrollLeft = base.$window.scrollLeft(); if ((scrollTop > offset.top) && (scrollTop < offset.top + $this.height())) { base.$clonedHeader.css({ 'top': fixedHeaderHeight, 'margin-top': 0, 'left': offset.left - scrollLeft, 'display': 'block' }); base.updateCloneFromOriginal(); } else { base.$clonedHeader.css('display', 'none'); } }); }; base.updateCloneFromOriginal = function () { // Copy cell widths and classes from original header $('th', base.$clonedHeader).each(function (index) { var $this = $(this); var origCell = $('th', base.$originalHeader).eq(index); $this.removeClass().addClass(origCell.attr('class')); $this.css('width', origCell.width()); }); // Copy row width from whole table base.$clonedHeader.css('width', base.$originalHeader.width()); }; // Run initializer base.init(); }; $.StickyTableHeaders.defaultOptions = { fixedOffset: 0 }; $.fn.stickyTableHeaders = function (options) { return this.each(function () { (new $.StickyTableHeaders(this, options)); }); }; })(jQuery);
JavaScript
0
@@ -885,24 +885,108 @@ = $(this);%0D%0A +%0D%0A%09%09%09%09// remove padding on %3Ctable%3E to fix issue #7%0D%0A%09%09%09%09$this.css('padding', 0);%0D%0A%0D%0A %09%09%09%09$this.wr
97f0404f592b406fff42a4718ddd995b45af5762
Update main.js
data/main.js
data/main.js
/*@pjs preload="data/images/logo1.png";*/ var sketchProc=function(processingInstance){ with (processingInstance){ //Setup var wi = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var he = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; size(wi*0.9,he*0.9); frameRate(60); setup = function() { mainfont = createFont("Times New Roman"); logo = loadImage("data/images/logo1.png"); keys = []; page = 0; chapter1 = []; m = false; md = false; flevel = 255; bw = width/6; bh = width/12; prim = color(15,15,15); sec = color(100,30,30); tert = color(150,150,150); backg = color(55,55,55); fade = function() { flevel -= 10; fill(55,55,55,flevel); noStroke(); rectMode(CORNER); rect(-1,-1,width+1,height+1); }; loadpanels = function(name,number,target) { for (i = 0; i < number;) { target[i] = loadImage("data/images/panels/"+name+i+".png"); i ++; } }; buttons = { start:{x:width*(3/4),y:height/2,w:bw,h:bh,text:"Enter"}, next:{x:width*(8/9),y:height*(1/2),w:bw,h:bh,text:"Next"}, prev:{x:width*(1/9),y:height*(1/2),w:bw,h:bh,text:"Previous"}, }; displaypanel = function(img,x,y) { imageMode(CENTER); pushMatrix(); translate(x,y); scale(0.001*height,0.001*height); image(img,0,0); popMatrix(); }; button = function(con) { bux = con.x buy = con.y buw = con.w buh = con.h butext = con.text con.pressed = false; rectMode(CENTER); if (mouseX>bux-buw/2&&mouseX<bux+buw/2 && mouseY>buy-buh/2&&mouseY<buy+buh/2) { fill(prim); } else { fill(sec); } stroke(prim); strokeWeight(buh/10); rect(bux,buy,buw,buh,buh/3); if (mouseX>bux-buw/2&&mouseX<bux+buw/2 && mouseY>buy-buh/2&&mouseY<buy+buh/2) { fill(sec); } else { fill(prim); } textFont(mainfont,buh/2); textAlign(CENTER,CENTER); text(butext,bux,buy); if ("/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i".test(navigator.userAgent)) && (mouseX>bux-buw/2&&mouseX<bux+buw/2 && mouseY>buy-buh/2&&mouseY<buy+buh/2)) { con.pressed = true; return con.pressed; } if (mouseX>bux-buw/2&&mouseX<bux+buw/2 && mouseY>buy-buh/2&&mouseY<buy+buh/2 && m) { con.pressed = true; return con.pressed; } return con.pressed; }; loadpanels("chap1/",1,chapter1); standardbuttons = function() { button(buttons.next); if (buttons.next.pressed) { page += 1; flevel = 255; }; button(buttons.prev); if (buttons.prev.pressed) { page -= 1; flevel = 255; }; }; pages = [ function() { background(backg) displaypanel(logo,width/4,height/2) button(buttons.start) if (buttons.start.pressed==true) { page += 1 } }, function() { background(backg) displaypanel(chapter1[0],width/2,height/2); standardbuttons(); fade(); }, ]; }; keyPressed = function() { keys[keyCode] = true; }; keyReleased = function() { keys[keyCode] = false; }; mousePressed = function() { m = true; }; mouseReleased = function() { m = false; }; draw = function() { pages[page](); fill(0,0,0); text(mouseX+", "+mouseY,width/2,height/2); }; }};
JavaScript
0.000001
@@ -1943,116 +1943,50 @@ %09%0A%09%09 -if (%22/Android%7CwebOS%7CiPhone%7CiPad%7CiPod%7CBlackBerry%7CBB%7CPlayBook%7CIEMobile%7CWindows Phone%7CKindle%7CSilk%7COpera Mini +var isMobile = /iPhone%7CiPad%7CiPod%7CAndroid /i -%22 .tes @@ -2007,17 +2007,32 @@ erAgent) -) +;%0A%09%09if (isMobile && (mou @@ -2104,16 +2104,20 @@ uh/2)) %7B +%09%09 %0A%09%09%09con.
a54c1399a7d74af798af0132c56bcbb531b702d5
fix test description
test/commandLineTests.js
test/commandLineTests.js
var shelljs = require('shelljs'); var path = require('path'); describe('Command Line', function () { describe('searchForExecutable', function () { it('Should run ./commandTest.sh', function (done) { var cliTestCommand = 'echo "Hello\nWorld" | ' + path.join('./', 'bin', 'index.js') + ' --reporter gitdiff --outdir ./test commandlineTest'; shelljs.exec(cliTestCommand, {async:true}, function (code, output) { if (code !== 0) { console.error('code:', code, 'output:', output); throw "cli script failed"; } done(); }); }); }); });
JavaScript
0.002419
@@ -102,89 +102,58 @@ %0A%0A -describe('searchForExecutable', function () %7B%0A it('Should run ./commandTest.sh +it('Should run approvals CLI with basic text input ', f @@ -165,26 +165,24 @@ on (done) %7B%0A - var cliT @@ -318,18 +318,16 @@ ';%0A%0A - - shelljs. @@ -393,18 +393,16 @@ %7B%0A - if (code @@ -419,18 +419,16 @@ - - console. @@ -468,18 +468,16 @@ utput);%0A - @@ -513,14 +513,10 @@ - %7D%0A +%7D%0A @@ -529,18 +529,8 @@ ();%0A - %7D);%0A
de7245c2ad454aed3d5f1f899d3462660b2d8f15
remove unecessary code
src/strings/trim/trim.js
src/strings/trim/trim.js
/** * Removes whitespace from both ends of a string. * @param {String} str The string to trim. */ function trim(str) { 'use strict'; return String.prototype.trim ? str.trim() : str.replace(/(^\s*|\s*$)/g, ''); } // Required for building process. // You can ommit if just need the function. if (typeof module !== 'undefined' && module.exports) { module.exports = trim; }
JavaScript
0.999992
@@ -237,167 +237,4 @@ ;%0A%7D%0A -%0A// Required for building process.%0A// You can ommit if just need the function.%0Aif (typeof module !== 'undefined' && module.exports) %7B%0A module.exports = trim;%0A%7D%0A
c230098a3f8098d34d8473431f1f85660987fbe6
Configure logo
src/js/app.constants.js
src/js/app.constants.js
//Copyright ©2013-2014 Memba® Sarl. All rights reserved. /*jslint browser:true*/ /*jshint browser:true*/ (function ($, undefined) { "use strict"; var fn = Function, global = fn('return this')(), app = global.app = global.app || {}; /** * IMPORTANT: Nothing in this file should be language specific (localized) */ /** * Constants * @type {*} */ app.constants = $.extend(app.constants || {}, { URN: 'urn:', COLON: ':', DEFAULT_GUID: '00000000-0000-0000-0000-000000000000', MARKDOWN_EXT: '.md', PATH_SEP: '/', PAGE_SIZE: 'pageSize', DEFAULT_PAGE_SIZE: 5, DATE_FORMAT: 'dd MMM yyyy', MAX_THUMBNAILS: 4 }); /** * Types * @type {*} */ app.types = $.extend(app.types || {}, { BOOLEAN: 'boolean', DATE: 'date', FUNCTION: 'function', NUMBER: 'number', OBJECT: 'object', STRING: 'string', UNDEFINED: 'undefined' }); /** * HREFs * @type {*} */ app.hrefs = $.extend(app.hrefs || {}, { ARCHIVE: './posts/', RSS: 'index.rss', INDEX: './index.html', HEADER: './header.tmpl.html', FOOTER: './footer.tmpl.html', CONFIG: './config.json', THUMBNAIL: './styles/images/blog{0}.jpg' }); /** * Routes * @type {*} */ app.routes = $.extend(app.routes || {}, { HASH: '#', HOME: '/', CATEGORY: '/category/:category', CATEGORY_PARAMETER: ':category', ARCHIVE: '/archive/:period', PERIOD_PARAMETER: ':period', BLOG: '/blog/:year/:month/:slug', YEAR_PARAMETER: ':year', MONTH_PARAMETER: ':month', SLUG_PARAMETER: ':slug', GUID: '/guid/:guid', GUID_PARAMETER: ':guid', SEARCH: '/search', PAGES: '/pages/:page' }); /** * Events * @type {*} */ app.events = $.extend(app.events || {}, { CHANGE: 'change', CLICK: 'click', DBLCLICK: 'dblclick', DRAGSTART: 'dragstart', DRAGENTER: 'dragenter', DRAGOVER: 'dragover', DROP: 'drop', INITIALIZE: 'initialize', KEYUP: 'keyup' }); /** * Html tags and attributes * @type {*} */ app.tags = $.extend(app.tags || {}, { BODY: 'body', DATA_COLUMNS: 'data-columns', DIV: 'div', DIV_ELEMENT: '<div/>', HREF: 'href', ID: 'id', INPUT: 'input', INPUT_ELEMENT: '<input/>', PLACEHOLDER: 'placeholder', SPAN: 'span', SPAN_ELEMENT: '<span/>', TEXTAREA: 'textarea', TEXTAREA_ELEMENT: '<textarea/>' //TBODY: 'tbody', //TBODY_ELEMENT: '<tbody/>', //DISABLED: 'disabled', //DRAGGABLE: 'draggable', //TYPE: 'type', //URL: 'url', //COLOR: 'color', //DATA_ID: 'data-id', //DATA_BIND: 'data-bind', //DATA_BIND_VALUE: 'value: ', //DATA_SELECTED: 'data-selected', }); /** * HTML Elements * @type {*} */ app.elements = $.extend(app.elements || {}, { /** * Strip the element id from the # prefix * @param id * @returns {*} */ strip: function(id) { if ((typeof id === app.types.STRING) && (id.charAt(0) === '#')) { return id.substr(1); } else { return id; } }, //Application layout APPLICATION_ROOT: '#application', APPLICATION_LAYOUT: '#application-layout', APPLICATION_HEADER: '#header', APPLICATION_CONTAINER: '#container', APPLICATION_CONTENT: '#content', APPLICATION_SIDE: '#side', APPLICATION_FOOTER: '#footer', //Header HEADER_VIEW: '#header-view', //HEADER_VIEW_NAVBAR_BRAND: '#header-view-navbar-brand', HEADER_VIEW_SEARCH_INPUT: '#header-view-navbar-search-input', HEADER_VIEW_SEARCH_BUTTON: '#header-view-navbar-search-button', //Header - Navigation Bar HEADER_VIEW_NAVBAR_TOGGLE: '#header-view-navbar-toggle', HEADER_VIEW_NAVBAR_SEARCH_INPUT: '#header-view-navbar-search-input', HEADER_VIEW_NAVBAR_SEARCH_BUTTON: '#header-view-navbar-search-button', HEADER_VIEW_NAVBAR_MENU: '#header-view-navbar-menu', //Footer FOOTER_VIEW: '#footer-view', FOOTER_VIEW_COPYRIGHT: '#footer-view-copyright', //FAQs View PAGE_VIEW: '#page-view', //Search View SEARCH_VIEW: '#search-view', //Error View ERROR_VIEW: '#error-view', ERROR_VIEW_TITLE: 'h1', ERROR_VIEW_MESSAGE: 'div.alert', //Blog side navigation BLOG_NAVIGATION_VIEW: '#blog-navigation-view', ALL_POSTS_SECTION: '#all-posts', ALL_POSTS_SECTION_TITLE: '#all-posts-title > a', CATEGORIES_SECTION: '#categories', CATEGORIES_SECTION_TITLE: '#categories-title', ARCHIVE_SECTION: '#archive', ARCHIVE_SECTION_TITLE: '#archive-title', RSS_SECTION: '#rss', RSS_SECTION_TITLE: '#rss-title > a', //Blog list View BLOG_LIST_VIEW: '#blog-list-view', BLOG_LIST_TEMPLATE: '#blog-list-template', BLOG_PAGER: '#blog-pager', BLOG_PAGER_SIZES: 'span.k-pager-sizes select', BLOG_POST_READMORE: 'div.readmore > div.pull-right > a', //Blog Post View DETAIL_VIEW: '#detail-view', DUMMY: 'dummy' }); }(jQuery));
JavaScript
0.000001
@@ -2381,32 +2381,52 @@ p.tags %7C%7C %7B%7D, %7B%0A + ALT: 'alt',%0A BODY: 'b @@ -2427,24 +2427,24 @@ DY: 'body',%0A - DATA @@ -2556,24 +2556,44 @@ ID: 'id',%0A + IMG: 'img',%0A INPU @@ -2693,24 +2693,24 @@ AN: 'span',%0A - SPAN @@ -2726,24 +2726,44 @@ '%3Cspan/%3E',%0A + SRC: 'src',%0A TEXT @@ -4235,16 +4235,79 @@ ion Bar%0A + HEADER_VIEW_NAVBAR_BRAND: '#header-view-navbar-brand',%0A
b14a115ea445cf11fa268a505450c081a8fa994c
Update to use receiveDishonorToken
server/game/cards/08-MotC/MakerOfKeepsakes.js
server/game/cards/08-MotC/MakerOfKeepsakes.js
const DrawCard = require('../../drawcard.js'); const AbilityDsl = require('../../abilitydsl'); class MakerOfKeepsakes extends DrawCard { setupCardAbilities() { this.persistentEffect({ effect: AbilityDsl.effects.cardCannot('becomeDishonored') }); } } MakerOfKeepsakes.id = 'maker-of-keepsakes'; module.exports = MakerOfKeepsakes;
JavaScript
0
@@ -245,13 +245,14 @@ ot(' -becom +receiv eDis @@ -260,10 +260,13 @@ onor -ed +Token ')%0A
a14740957979d5fa3e093bd064c6561ed9b10669
Disable qtip while dropdown is open
indico/htdocs/js/indico/jquery/dropdown.js
indico/htdocs/js/indico/jquery/dropdown.js
/* This file is part of Indico. * Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN). * * Indico is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of the * License, or (at your option) any later version. * * Indico 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 * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Indico; if not, see <http://www.gnu.org/licenses/>. */ (function($) { 'use strict'; $.widget('indico.dropdown', { options: { selector: '.i-button[data-toggle]', effect_on: 'slideDown', effect_off: 'fadeOut', time_on: 200, time_off: 200, positioning: {}, relative_to: undefined, always_listen: false // if set to true, will trigger 'menu_select' event even when there is a valid href }, _close: function(elem, effect) { var ul = elem.next('ul'); elem.removeClass('open'); this._effect('off', ul, effect); ul.find('ul').hide(); elem.data('on', false); elem.parent().removeClass('selected'); elem.siblings('ul').find('a').data('on', false); }, _close_all: function(effect) { var self = this; this.element.find('a, button').each(function() { self._close($(this), effect); }); }, _open: function(elem) { var self = this; var sibl = elem.next('ul.dropdown'); var positionReference = this.options.relative_to || elem; elem.addClass('open'); this._effect('on', sibl); elem.data('on', true); elem.parent().addClass('selected'); sibl.position($.extend({of: positionReference}, this.options.positioning[sibl.data('level')] || {my: 'left top', at: 'left bottom', offset: '0px 0px'})); this.element.find('a').each(function() { if (this !== elem.get(0)) { self._close($(this)); } }); }, _menuize: function(elem) { var self = this; elem.find(this.options.selector).each(function() { var $this = $(this); if (!$this.attr('href') || $this.attr('href') === "#" || $this.data('ignore-href') !== undefined || self.options.always_listen) { $this.click(function(e) { if ($this.data('toggle') === 'dropdown') { if ($this.data('on')) { self._close($this); } else if (!$this.hasClass('disabled')) { self._open($this); } e.preventDefault(); } else { var result = $this.triggerHandler('menu_select', self.element); if (!result) { self._close_all(); } e.preventDefault(); } }); } }); elem.find('ul.dropdown > li > a').each(function() { var $this = $(this); if (!$this.attr('href') || $this.attr('href') === "#" || $this.data('ignore-href') !== undefined || self.options.always_listen) { $this.click(function(e) { e.preventDefault(); if ($this.hasClass('disabled')) { return; } var result = $this.triggerHandler('menu_select', self.element); if (!result) { self._close_all(); } }); } }); elem.find('ul.dropdown > li.toggle').each(function() { var li = $(this); var link = $('<a>', { href: '#', text: li.text(), class: 'icon-checkmark ' + (li.data('state') ? '' : 'inactive'), click: function(e) { e.preventDefault(); var $this = $(this); var newState = !li.data('state'); $this.toggleClass('inactive', !newState); li.data('state', newState); li.triggerHandler('menu_toggle', [newState]); } }); li.html(link); }); }, _create: function() { var self = this; this._menuize(this.element); $(document).on('click', function(e) { // click outside? close menus. if ($(self.element).has(e.target).length === 0) { self._close_all(); } }); }, _effect: function(st, elem, effect) { var func = effect === undefined ? this.options['effect_' + st] : effect; if (func === null) { // no pretty effects elem.hide(); } else if (typeof func == 'function') { func.call(elem, this); } else { elem[func].call(elem, this.options['time_' + st]); } }, close: function() { this._close_all(null); } }); })(jQuery);
JavaScript
0
@@ -1302,32 +1302,80 @@ veClass('open'); +%0A elem.removeData('no-auto-tooltip'); %0A%0A th @@ -2018,16 +2018,99 @@ 'open'); +%0A elem.data('no-auto-tooltip', true).trigger('indico:closeAutoTooltip'); %0A%0A
61f6ee4436732297508d8af2fbeda8b91bf21b29
fix tooltip so it does not get cut off by tree
src/Umbraco.Web.UI.Client/src/common/directives/components/umbtooltip.directive.js
src/Umbraco.Web.UI.Client/src/common/directives/components/umbtooltip.directive.js
(function() { 'use strict'; function TooltipDirective($timeout) { function link(scope, el, attr, ctrl) { scope.tooltipStyles = {}; scope.tooltipStyles.left = 0; scope.tooltipStyles.top = 0; function activate() { $timeout(function() { setTooltipPosition(scope.event); }); } function setTooltipPosition(event) { var viewportWidth = null; var viewportHeight = null; var elementHeight = null; var elementWidth = null; var position = { right: "inherit", left: "inherit", top: "inherit", bottom: "inherit" }; // viewport size viewportWidth = $(window).innerWidth(); viewportHeight = $(window).innerHeight(); // element size elementHeight = el.context.clientHeight; elementWidth = el.context.clientWidth; position.left = event.pageX - (elementWidth / 2); position.top = event.pageY; // check to see if element is outside screen // outside right if (position.left + elementWidth > viewportWidth) { position.right = 0; position.left = "inherit"; } // outside bottom if (position.top + elementHeight > viewportHeight) { position.bottom = 0; position.top = "inherit"; } scope.tooltipStyles = position; } activate(); } var directive = { restrict: 'E', transclude: true, replace: true, templateUrl: 'views/components/umb-tooltip.html', scope: { event: "=" }, link: link }; return directive; } angular.module('umbraco.directives').directive('umbTooltip', TooltipDirective); })();
JavaScript
0
@@ -436,68 +436,305 @@ var -viewportWidth = null;%0A var viewportHeight = null; +container = $(%22#contentwrapper%22);%0A var containerLeft = container%5B0%5D.offsetLeft;%0A var containerRight = containerLeft + container%5B0%5D.offsetWidth;%0A var containerTop = container%5B0%5D.offsetTop;%0A var containerBottom = containerTop + container%5B0%5D.offsetHeight;%0A %0A @@ -984,144 +984,8 @@ %7D;%0A%0A - // viewport size%0A viewportWidth = $(window).innerWidth();%0A viewportHeight = $(window).innerHeight();%0A%0A @@ -1353,21 +1353,22 @@ h %3E -viewportWidth +containerRight ) %7B%0A @@ -1395,24 +1395,25 @@ ion.right = +1 0;%0A @@ -1541,89 +1541,444 @@ t %3E -viewportHeight) %7B%0A position.bottom = 0;%0A position.top +containerBottom) %7B%0A position.bottom = 10;%0A position.top = %22inherit%22;%0A %7D%0A%0A // outside left%0A if (position.left %3C containerLeft) %7B%0A position.left = containerLeft + 10;%0A position.right = %22inherit%22;%0A %7D%0A%0A // outside top%0A if (position.top %3C containerTop) %7B%0A position.top = 10;%0A position.bottom = %22 @@ -2047,16 +2047,47 @@ ition;%0A%0A + el.css(position);%0A%0A
a6dcb0869c559614ee95a5d8a2f2717198a21068
Use base directory only
fetch-data.js
fetch-data.js
#!/usr/bin/env node // vim: set ft=javascript ts=2 sts=2 sw=2 et tw=80: if (process.argv.length != 6) { console.log('Usage: ' + [ process.argv[0], process.argv[1], '<remote>', '<start>', '<end>', '<out>' ].join(' ')); process.exit(1); } var fs = require('fs'); var q = require('q'); var request = require('request'); var remote = process.argv[2].replace(/\/?$/, ''); var repo = /\/([^\/]+)$/.exec(remote)[1]; var pushlog_url = remote + '/json-pushes'; var info_url = remote + '/json-info'; var builds_url = 'http://tbpl.mozilla.org/php/getRevisionBuilds.php'; var start = process.argv[3]; var end = process.argv[4]; var outfile = process.argv[5]; function do_request(options) { var deferred = q.defer(); request(options, function(error, response, body) { if (error) { deferred.reject(error); } else if (response.statusCode !== 200) { deferred.reject(new Error('Bad status: ' + request.statusCode)); } else { deferred.resolve(body); } }); return deferred.promise; } // Match valid commit messages var commit_msg_regexp = /(bug|b=)\s*\d{4,}/i; // Match valid revision numbers var rev_regexp = /[0-9a-fA-F]{10,}/; var results = {}; function aggregateFiles(push) { var files = {}; push.changesets.forEach(function(cset) { cset.files.forEach(function(file) { files[file.slice(0, file.lastIndexOf('/') + 1)] |= 1; }); }); return files; } function process_pushes(pushes) { // Process each push in pushes sequentially. return pushes.map(function(push) { // Return a function that produces a promise. return function() { var last_cset = push.changesets[push.changesets.length - 1]; var rev = last_cset.node.substr(0, 12); return do_request({ url: builds_url, qs: { branch: repo, rev: rev }, json: true }).then(function(builds) { builds.forEach(function(build) { var builder = build.buildername.replace(repo, '').replace(' ', ' '); build.notes.forEach(function(note) { // A rev in the note means the changeset was backed out. var backouts = note.note.trim().match(rev_regexp); if (!backouts) { return; } backouts.forEach(function(backout) { backout = backout.substr(0, 12); results[backout] = results[backout] || {}; results[backout][builder] = 1; }); }); }); // Delay 10s before the next network request. return q.delay(10000); }); }; // Run the functions sequentially }).reduce(q.when, q()); } do_request({ url: pushlog_url, qs: { full: '1', startID: start, endID: end }, json: true }).then(function(pushes) { var all_pushes = Object.keys(pushes).filter(function(id) { // Only count changesets corresponding to actual bugs. var push = pushes[id]; var last_cset = push.changesets[push.changesets.length - 1]; return last_cset.desc.trim().search(commit_msg_regexp) > -1; }).map(function(id) { return pushes[id]; }); var requests = []; var chunk = Math.ceil(all_pushes.length / 10); for (var i = 0; i < all_pushes.length; i += chunk) { requests.push(process_pushes(all_pushes.slice(i, i + chunk))); } return q.all(requests).then(function() { var csets = {}; Object.keys(pushes).forEach(function(id) { var push = pushes[id]; var last_cset = push.changesets[push.changesets.length - 1]; csets[last_cset.node.substr(0, 12)] = push; }); return [csets, results]; }); }).spread(function(csets, results) { // Get info about csets we've not seen before. return Object.keys(results).filter(function(cset) { return !(cset in csets); }).map(function(unknown_cset) { return function() { return do_request({ url: info_url, qs: { node: unknown_cset }, json: true }).then(function(info) { csets[unknown_cset] = { changesets: Object.keys(info).map(function(cset) { return info[cset]; }) }; // Delay 1s before the next network request. return q.delay(1000); }); }; // Fetch unknown csets sequentially. }).reduce(q.when, q()).then(function() { return [csets, results]; }); }).spread(function(csets, results) { var output = Object.keys(results).filter(function(cset) { if (cset in csets) { return true; } console.log('Warning: changeset ' + cset + ' not found!'); return false; }).map(function(cset) { return { input: aggregateFiles(csets[cset]), output: results[cset] }; }); return q.nfcall(fs.writeFile, outfile, JSON.stringify(output, null, 2)); }).done();
JavaScript
0
@@ -1340,41 +1340,51 @@ le.s -lice(0, file.lastIndexOf('/') + 1 +plit('/').slice(0, -1).slice(0, 1).join('/' )%5D %7C
d82e7fe7595b2ea1344fd45e96eca692973b8f13
Revert "js: target-init: write to screen for feedback in slow network conditions"
share/js/dochazka-www/target-init.js
share/js/dochazka-www/target-init.js
// ************************************************************************* // Copyright (c) 2014-2017, SUSE LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of SUSE LLC nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ************************************************************************* // // app/target-init.js // // Initialization of targets (round one) // "use strict"; define ([ 'jquery', 'target', 'app/act-lib', 'app/daction-init', 'app/dform-init', 'app/dmenu-init', 'app/dbrowser-init', 'app/dnotice-init', 'app/dtable-init', 'app/drowselect-init', 'init2', 'stack' ], function ( $, target, actLib, dactionInitRoundOne, dformInitRoundOne, dmenuInitRoundOne, dbrowserInitRoundOne, dnoticeInitRoundOne, dtableInitRoundOne, drowselectInitRoundOne, initRoundTwo, stack ) { return function () { // round one - set up the targets console.log("dochazka-www/target-init.js: round one"); $('#mainarea').html("Loading dactions"); dactionInitRoundOne(); $('#mainarea').html("Loading dforms"); dformInitRoundOne(); $('#mainarea').html("Loading dmenus"); dmenuInitRoundOne(); $('#mainarea').html("Loading dbrowsers"); dbrowserInitRoundOne(); $('#mainarea').html("Loading dnotices"); dnoticeInitRoundOne(); $('#mainarea').html("Loading dtables"); dtableInitRoundOne(); $('#mainarea').html("Loading drowselects"); drowselectInitRoundOne(); // round two - add 'source' and 'start' properties // (widget targets only) console.log("dochazka-www/target-init.js: round two"); $('#mainarea').html("Initializing dforms"); initRoundTwo('dform'); $('#mainarea').html("Initializing dmenus"); initRoundTwo('dmenu'); $('#mainarea').html("Initializing dbrowsers"); initRoundTwo('dbrowser'); $('#mainarea').html("Initializing dnotices"); initRoundTwo('dnotice'); $('#mainarea').html("Initializing dtables"); initRoundTwo('dtable'); $('#mainarea').html("Initializing drowselects"); initRoundTwo('drowselect'); // populate activities cache actLib.populateActivitiesCache(); // fire up the main menu stack.push('mainMenu'); }; });
JavaScript
0
@@ -1802,22 +1802,8 @@ (%5B%0A - 'jquery',%0A @@ -2041,15 +2041,8 @@ n (%0A - $,%0A @@ -2411,1195 +2411,530 @@ -$('#mainarea').html(%22Loading dactions%22);%0A dactionInitRoundOne();%0A $('#mainarea').html(%22Loading dforms%22);%0A dformInitRoundOne();%0A $('#mainarea').html(%22Loading dmenus%22);%0A dmenuInitRoundOne();%0A $('#mainarea').html(%22Loading dbrowsers%22);%0A dbrowserInitRoundOne();%0A $('#mainarea').html(%22Loading dnotices%22);%0A dnoticeInitRoundOne();%0A $('#mainarea').html(%22Loading dtables%22);%0A dtableInitRoundOne();%0A $('#mainarea').html(%22Loading drowselects%22);%0A drowselectInitRoundOne();%0A%0A // round two - add 'source' and 'start' properties%0A // (widget targets only)%0A console.log(%22dochazka-www/target-init.js: round two%22);%0A $('#mainarea').html(%22Initializing dforms%22);%0A initRoundTwo('dform');%0A $('#mainarea').html(%22Initializing dmenus%22);%0A initRoundTwo('dmenu');%0A $('#mainarea').html(%22Initializing dbrowsers%22);%0A initRoundTwo('dbrowser');%0A $('#mainarea').html(%22Initializing dnotices%22);%0A initRoundTwo('dnotice');%0A $('#mainarea').html(%22Initializing dtables%22);%0A initRoundTwo('dtable');%0A $('#mainarea').html(%22Initializing drowselects%22 +dactionInitRoundOne();%0A dformInitRoundOne();%0A dmenuInitRoundOne();%0A dbrowserInitRoundOne();%0A dnoticeInitRoundOne();%0A dtableInitRoundOne();%0A drowselectInitRoundOne();%0A%0A // round two - add 'source' and 'start' properties%0A // (widget targets only)%0A console.log(%22dochazka-www/target-init.js: round two%22);%0A initRoundTwo('dform');%0A initRoundTwo('dmenu');%0A initRoundTwo('dbrowser');%0A initRoundTwo('dnotice');%0A initRoundTwo('dtable' );%0A
459a95838c4e8136d87b8ca0d97791b19672e040
Tweak comment.
js/jsfunfuzz/error-reporting.js
js/jsfunfuzz/error-reporting.js
function confused(s) { if (jsshell) { // Magic string that jsInteresting.py looks for print("jsfunfuzz broke its own scripting environment: " + s); quit(); } } function foundABug(summary, details) { // Magic pair of strings that jsInteresting.py looks for // Break up "Found a bug: " so internal js functions do not print this string deliberately printImportant("Found" + " a bug: " + summary); if (details) { printImportant(details); } if (jsshell) { dumpln("jsfunfuzz stopping due to finding a bug."); quit(); } } function errorToString(e) { try { return ("" + e); } catch (e2) { return "Can't toString the error!!"; } } function errorstack() { print("EEE"); try { void ([].qwerty.qwerty); } catch(e) { print(e.stack); } }
JavaScript
0
@@ -286,23 +286,28 @@ up -%22Found a bug: %22 +the following string so @@ -345,19 +345,10 @@ int +i t -his string del
9029c164eed86adf903b020b25b9b2c03291d004
Revert "Trying to catch Node 0.10.x bug"
predefined_rules/blacklist.js
predefined_rules/blacklist.js
var _ = require("lodash"); var ipaddr = require('ipaddr.js'); function IP_MATCH_ALL(list, rangeList, ip) { if(!list) return false; // Stored Parsed IP var _IP_ = ipaddr.parse(ip); // Simple Compare of Provided, Valid & Normalized version of IP with Address List if( (list.indexOf(ip) !== -1) || (list.indexOf(_IP_.toString()) !== -1) || ( (_IP_.kind() === 'ipv6') && (list.indexOf(_IP_.toNormalizedString()) !== -1) ) ) { return true; }else if( (rangeList) && (rangeList.length >= 1) ){ // Range Matching If Rangelist has items var match = false; // Expensive Matching Function _.each(rangeList, function(range) { // Unfortunately ipaddr.js likes to throw too often try { match = _IP_.match(ipaddr.parseCIDR(range)); if(match === true) return false; }catch(e) { console.log("Warning", e) } }) return match; }else{ return false; } } module.exports = { name: 'blacklist', description: 'Limits Sessions Based on IP Address of the Client. If a matching IP Address or Range is found the session will be terminated otherwise it will be let through. Ranges are based on CIDR http://wikipedia.org/wiki/Classless_Inter-Domain_Routing', func: function(options, local, callback){ if(!options.get('blacklist')) return callback(null, true); // IF IP CAN'T BE VALIDATED if((!this.information.ip) || (!ipaddr.isValid(this.information.ip))) { return callback("IP Address is invalid"); } // Process Mapped ipv4 mapped ipv6 ips to ipv4 ips e.g. (::ffff:127.0.0.1 to 127.0.0.1) if(this.information.process === true) this.information.ip = ipaddr.process(this.information.ip).toString(); if(IP_MATCH_ALL(options.get('blacklist.address'), options.get('blacklist.range'), this.information.ip)) { callback("IP is Blacklisted!"); }else{ callback(null, true); } } }
JavaScript
0
@@ -1012,63 +1012,8 @@ e) %7B -%0A console.log(%22Warning%22, e)%0A %7D%0A
955bfa49711ab3b0d13b081a2d016c3dcf9ce218
Remove redundant code
share/qbs/modules/cpp/setuprunenv.js
share/qbs/modules/cpp/setuprunenv.js
/**************************************************************************** ** ** Copyright (C) 2017 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qbs. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ var FileInfo = require("qbs.FileInfo"); var ModUtils = require("qbs.ModUtils"); // TODO: append/prepend functionality should go to qbs.Environment function addNewElement(list, elem) { if (!list.contains(elem)) list.push(elem); } function artifactDir(artifact, product) { if (!artifact.qbs.install) return FileInfo.path(artifact.filePath); var installBaseDir = FileInfo.joinPaths(artifact.qbs.installRoot, artifact.qbs.installPrefix, artifact.qbs.installDir); var installSourceBase = artifact.qbs.installSourceBase; if (!installSourceBase) return installBaseDir; if (!FileInfo.isAbsolutePath(installSourceBase)) installSourceBase = FileInfo.joinPaths(product.sourceDirectory, installSourceBase); var relativeInstallDir = FileInfo.path(FileInfo.relativePath(installSourceBase, artifact.filePath)); return FileInfo.joinPaths(installBaseDir, relativeInstallDir); } function gatherPaths(product, libPaths, frameworkPaths) { // Heuristic: If any rpaths are set, assume environment paths should not be set up. // Let's not try to be super fancy, evaluating all the rpaths, expanding $ORIGIN, relative paths // and whatnot. if (product.cpp.useRPaths && product.cpp.rpaths && product.cpp.rpaths.length > 0) return; // Gather explicitly given library paths. if (product.cpp.libraryPaths) product.cpp.libraryPaths.forEach(function(p) { addNewElement(libPaths, p); }); if (product.cpp.frameworkPaths) product.cpp.frameworkPaths.forEach(function(p) { addNewElement(frameworkPaths, p); }); // Extract paths from dynamic libraries, if they are given as file paths. if (product.cpp.dynamicLibraries) { product.cpp.dynamicLibraries.forEach(function(dll) { if (FileInfo.isAbsolutePath(dll)) addNewElement(libPaths, FileInfo.path(dll)); }); } // Traverse library dependencies. for (var i = 0; i < product.dependencies.length; ++i) { var dep = product.dependencies[i]; var dllSymlinkArtifacts = dep.artifacts["bundle.symlink.executable"]; if (dllSymlinkArtifacts) { var addArtifact = function(artifact) { addNewElement(frameworkPaths, FileInfo.path(artifactDir(artifact, dep))); }; dllSymlinkArtifacts.forEach(addArtifact); // TODO: Will also catch applications. Can we prevent that? } else { addArtifact = function(artifact) { addNewElement(libPaths, artifactDir(artifact, dep)); }; var dllArtifacts = dep.artifacts["dynamiclibrary"]; if (dllArtifacts) dllArtifacts.forEach(addArtifact); var loadableModuleArtifacts = dep.artifacts["loadablemodule"]; if (loadableModuleArtifacts) loadableModuleArtifacts.forEach(addArtifact); } if (!dep.hasOwnProperty("present")) // Recurse if the dependency is a product. TODO: Provide non-heuristic way to decide whether dependency is a product. gatherPaths(dep, libPaths, frameworkPaths); } } function setupRunEnvironment(product, config) { if (config.contains("ignore-lib-dependencies")) return; // TODO: Uncomment once the property is available // if (product.qbs.hostPlatform != product.qbs.targetPlatform) // return; var libPaths = []; var frameworkPaths = []; gatherPaths(product, libPaths, frameworkPaths); var runPaths = product.cpp.systemRunPaths; if (runPaths && runPaths.length > 0) { var filterFunc = function(p) { return !runPaths.contains(p); }; libPaths = libPaths.filter(filterFunc); frameworkPaths = frameworkPaths.filter(filterFunc); } if (libPaths.length > 0) { var envVarName; if (product.qbs.targetOS.contains("windows")) envVarName = "PATH"; else if (product.qbs.targetOS.contains("macos")) envVarName = "DYLD_LIBRARY_PATH"; else envVarName = "LD_LIBRARY_PATH"; var envVar = new ModUtils.EnvironmentVariable(envVarName, product.qbs.pathListSeparator, product.qbs.hostOS.contains("windows")); libPaths.forEach(function(p) { envVar.prepend(p); }); envVar.set(); } if (product.qbs.targetOS.contains("macos") && frameworkPaths.length > 0) { envVar = new ModUtils.EnvironmentVariable("DYLD_FRAMEWORK_PATH", ':', false); frameworkPaths.forEach(function(p) { envVar.prepend(p); }); envVar.set(); } }
JavaScript
0
@@ -1780,19 +1780,10 @@ fact -, product )%0A + %7B%0A @@ -1868,670 +1868,73 @@ -var installBaseDir = FileInfo.joinPaths(artifact.qbs.installRoot, artifact.qbs.installPrefix,%0A artifact.qbs.installDir);%0A var installSourceBase = artifact.qbs.installSourceBase;%0A if (!installSourceBase)%0A return installBaseDir;%0A if (!FileInfo.isAbsolutePath(installSourceBase))%0A installSourceBase = FileInfo.joinPaths(product.sourceDirectory, installSourceBase);%0A var relativeInstallDir = FileInfo.path(FileInfo.relativePath(installSourceBase,%0A artifact.filePath));%0A return FileInfo.joinPaths(installBaseDir, relativeInstallDir +return FileInfo.path(ModUtils.artifactInstalledFilePath(artifact) );%0A%7D @@ -3294,21 +3294,16 @@ artifact -, dep )));%0A @@ -3556,13 +3556,8 @@ fact -, dep ));%0A
14d500f9f3d7decc183b6e2530154df2159308c7
Reset drag node position on drag start
services/controllers/calibration/js/Handle.js
services/controllers/calibration/js/Handle.js
class Handle { constructor(parent, x, y) { this.parent = parent; this._x = x; this._y = y; this.bounds = null; this.radius = 4; this.rootNode; this.dragNode; this.lastX, this.lastY; this.dragX = x; this.dragY = y; } get x() { return this._x; } set x(value) { if (value !== this._x) { if (this.bounds !== null && this.bounds !== undefined) { let right = this.bounds.x + this.bounds.width; if (this.bounds.x <= value && value < right) { this._x = value; } else { this._x = Math.max(this.bounds.x, Math.min(value, right)); } } else { this._x = value; } this.rootNode.setAttributeNS(null, "cx", this._x); } } get y() { return this._y; } set y(value) { if (value !== this._y) { if (this.bounds !== null && this.bounds !== undefined) { let bottom = this.bounds.y + this.bounds.height; if (this.bounds.y <= value && value < bottom) { this._y = value; } else { this._y = Math.max(this.bounds.y, Math.min(value, bottom)); } } else { this._y = value; } this.rootNode.setAttributeNS(null, "cy", this._y); } } attach(node) { this.createDragNode(node); let handle = document.createElementNS(svgns, "circle"); handle.setAttributeNS(null, "cx", this.x); handle.setAttributeNS(null, "cy", this.y); handle.setAttributeNS(null, "r", 4); handle.setAttributeNS(null, "pointer-events", "fill"); handle.setAttributeNS(null, "class", "handle"); handle.addEventListener("mousedown", this); this.rootNode = handle; node.appendChild(this.rootNode); } detach() { if (this.rootNode !== null) { this.rootNode.removeEventListener("mousedown", this); this.rootNode.parentNode.removeChild(this.rootNode); this.rootNode = null; } if (this.dragNode !== null) { this.dragNode.parentNode.removeChild(this.dragNode); this.dragNode = null; } } createDragNode(node) { let dragger = document.createElementNS(svgns, "circle"); dragger.setAttributeNS(null, "cx", this.x); dragger.setAttributeNS(null, "cy", this.y); dragger.setAttributeNS(null, "r", 50); dragger.setAttributeNS(null, "fill", "none"); // dragger.setAttributeNS(null, "fill", "white"); // dragger.setAttributeNS(null, "fill-opacity", 0.25); dragger.setAttributeNS(null, "pointer-events", "none"); this.dragNode = dragger; node.appendChild(this.dragNode); } handleEvent(e) { this[e.type](e); } mousedown(e) { this.lastX = e.x; this.lastY = e.y; this.rootNode.setAttributeNS(null, "class", "handle-selected"); this.rootNode.removeEventListener("mousedown", this); this.rootNode.setAttributeNS(null, "pointer-events", "none"); this.dragNode.setAttributeNS(null, "pointer-events", "fill"); this.dragNode.addEventListener("mousemove", this); this.dragNode.addEventListener("mouseup", this); } mousemove(e) { let dx = e.x - this.lastX; let dy = e.y - this.lastY; this.lastX = e.x; this.lastY = e.y; this.x += dx; this.y += dy; this.dragX += dx; this.dragY += dy this.rootNode.setAttributeNS(null, "cx", this.x); this.rootNode.setAttributeNS(null, "cy", this.y); this.dragNode.setAttributeNS(null, "cx", this.dragX); this.dragNode.setAttributeNS(null, "cy", this.dragY); this.parent.onhandlemove(this); } mouseup(e) { this.dragX = this.x; this.dragY = this.y; this.mousemove(e); this.rootNode.setAttributeNS(null, "class", "handle"); this.dragNode.removeEventListener("mousemove", this); this.dragNode.removeEventListener("mouseup", this); this.dragNode.setAttributeNS(null, "pointer-events", "none"); this.rootNode.addEventListener("mousedown", this); this.rootNode.setAttributeNS(null, "pointer-events", "fill"); } }
JavaScript
0
@@ -3156,32 +3156,215 @@ s.lastY = e.y;%0A%0A + this.dragX = this.x;%0A this.dragY = this.y;%0A this.dragNode.setAttributeNS(null, %22cx%22, this.dragX);%0A this.dragNode.setAttributeNS(null, %22cy%22, this.dragY);%0A%0A this.roo
7a1010d337e94f553874dbc307089d6703fb4b86
load single chart data from the show chart restful route
app/main.js
app/main.js
var css = require('!css!sass!autoprefixer!./css/main.scss'); // => returns compiled css code from file.scss, resolves imports and url(...)s // require('!style!css!sass!./main.scss'); require('!style!css!sass!autoprefixer!./css/main.scss'); import React from 'react' import App from './components/app.js' import Fluxxor from 'fluxxor' import SnapShotStore from './stores/snapshotstore' import PublisherStore from './stores/publisherstore' import routeService from './services/routeservice' import requestManager from './services/requestManager' var actions = { loadPublishers: function() { var route = '/publishers' var success = function(err, resp){ var data = JSON.parse(resp.text); this.dispatch("LOAD_PUBLISHERS", data) }.bind(this) requestManager.get(route, success) }, loadCharts: function() { var route = '/users/1/charts' var success = function(err, resp){ var charts = JSON.parse(resp.text).map(function(chart) { var publishersWithNames = this.flux.store("PublisherStore").getPublishers().map(function(pub) { var pub = pub; var found; chart.chart_params.publishers.forEach(function(pubID) { if (pubID = pub.id) { found = pub } }) return pub }) return { chartID: chart.id, chartType: chart.chart_params.chart_type, title: chart.chart_params.title, keywords: chart.chart_params.keywords, publishers: publishersWithNames } }.bind(this)) this.dispatch("LOAD_CHARTS", charts) }.bind(this) requestManager.get(route, success) }, addChart: function(type) { var chart = { chartID: 8, title: "Election", chartType: type, keywords: ["election"], publishers: [{id: 1, domain: "theglobeandmail.com"}, {id: 2, domain: "nationalpost.com"}, {id: 3, domain: "cbc.ca"}] } this.dispatch("LOAD_CHARTS", [chart]) var chartID = chart.chartID var keywordsList = chart.keywords var publishersList = chart.publishers var publisherIds = publishersList.map(function(publisher) { return publisher.id }) var route = routeService.apiUrl(keywordsList, publisherIds) var success = function(err, resp) { var dataRows = JSON.parse(resp.text); this.dispatch("LOAD_CHART_DATA", {id: chartID, data: dataRows}) this.dispatch("UPDATE_CHART", chartID) }.bind(this) requestManager.get(route, success) }, loadChartData: function(chartID) { var keywordsList = this.flux.store("SnapShotStore").getKeywords(chartID) var publishersList = this.flux.store("SnapShotStore").getPublishers(chartID) var publisherIds = publishersList.map(function(publisher) { return publisher.id }) var route = routeService.apiUrl(keywordsList, publisherIds) var success = function(err, resp) { var dataRows = JSON.parse(resp.text); this.dispatch("LOAD_CHART_DATA", {id: chartID, data: dataRows}) this.dispatch("UPDATE_CHART", chartID) }.bind(this) requestManager.get(route, success) }, updateChart: function(chartID) { this.dispatch("UPDATE_CHART", chartID) }, addKeyword: function(chartID, keyword) { var keywordsList = this.flux.store("SnapShotStore").getKeywords(chartID) var publishersList = this.flux.store("SnapShotStore").getPublishers(chartID).map(function(publisher) { return publisher.id }) if (keywordsList.indexOf(keyword) < 0) { var route = routeService.apiUrl(keywordsList.concat(keyword), publishersList) var success = function(err, resp) { var dataRows = JSON.parse(resp.text); this.dispatch("LOAD_CHART_DATA", {id: chartID, data: dataRows}) this.dispatch("ADD_KEYWORD", {id: chartID, data: keyword}) }.bind(this) requestManager.get(route, success) } }, removeKeyword: function(chartID, keywordIndex) { this.dispatch("REMOVE_KEYWORD", {id: chartID, data: keywordIndex}) }, addPublisher: function(chartID, publisherID) { var publisherList = this.flux.store("PublisherStore").getPublishers() var keywordsList = this.flux.store("SnapShotStore").getKeywords(chartID) var activePublisherIDs = this.flux.store("SnapShotStore").getPublishers(chartID).map(function(publisher) { return publisher.id }) var addedPublisher = publisherList.filter(function(publisher) { if (publisher.id == publisherID) { return publisher } })[0] if (activePublisherIDs.indexOf(addedPublisher.id) < 0) { var route = routeService.apiUrl(keywordsList, activePublisherIDs.concat(addedPublisher.id)) var success = function(err, resp) { var dataRows = JSON.parse(resp.text); this.dispatch("LOAD_CHART_DATA", {id: chartID, data: dataRows}) this.dispatch("ADD_PUBLISHER", {id: chartID, data: addedPublisher}) }.bind(this) requestManager.get(route, success) } }, removePublisher: function(chartID, publisher) { this.dispatch("REMOVE_PUBLISHER", {id: chartID, data: publisher}) }, // this takes an array of index values // ie [0, 2] which corresponds to the first // and third dates in the store's list changeDateRange: function(chartID, dates) { this.dispatch("CHANGE_DATE_RANGE", {id: chartID, data: dates}) } } var stores = { SnapShotStore: new SnapShotStore(), PublisherStore: new PublisherStore(), } var flux = new Fluxxor.Flux(stores, actions); React.render(<App flux={flux} />, document.getElementById('content'))
JavaScript
0
@@ -2576,319 +2576,41 @@ var -keywordsList = this.flux.store(%22SnapShotStore%22).getKeywords(chartID)%0A var publishersList = this.flux.store(%22SnapShotStore%22).getPublishers(chartID) %0A var publisherIds = publishersList.map(function(publisher) %7B%0A return publisher.id%0A %7D)%0A var route = routeService.apiUrl(keywordsList, publisherIds) +route = '/charts/show/' + chartID %0A
e2a2661aad044b91f14cd5feff84d94ab2318c05
Update resource to use public url (temporary)
js/services/skl-api-resource.js
js/services/skl-api-resource.js
angular.module('SceneSkeleton') .factory("Scene", function($resource) { return $resource("http://dockervm:8081/scene/:id"); });
JavaScript
0
@@ -97,21 +97,58 @@ p:// -dockervm:8081 +skl-api-426627428.ap-southeast-2.elb.amazonaws.com /sce
cb675c3393a437146ceac96ce28d099dea7c2bcc
edit doc and long line, https://github.com/phetsims/scenery-phet/issues/515
js/util/colorProfileProperty.js
js/util/colorProfileProperty.js
// Copyright 2021, University of Colorado Boulder /** * Singleton Property<string> which chooses between the available color profiles of a simulation, such as 'default', 'project', 'basics', etc. * * The color profile names available to a simulation are specified in package.json under phet.colorProfiles (or, if not * specified, defaults to [ "default" ]. The first listed color profile is one that appears in the sim * on startup, unless overridden by the sim or a query parameter. * * @author Sam Reid (PhET Interactive Simulations) */ import StringProperty from '../../../axon/js/StringProperty.js'; import Tandem from '../../../tandem/js/Tandem.js'; import scenery from '../scenery.js'; // Use the color profile specified in query parameters, or default to 'default' const initialProfileName = _.hasIn( window, 'phet.chipper.queryParameters.colorProfile' ) ? phet.chipper.queryParameters.colorProfile : 'default'; // List of all supported colorProfiles for this simulation const colorProfiles = _.hasIn( window, 'phet.chipper.colorProfiles' ) ? phet.chipper.colorProfiles : [ 'default' ]; // @public {Property.<string>} // The current profile name. Change this Property's value to change which profile is currently active. const colorProfileProperty = new StringProperty( initialProfileName, { // TODO: Should we move global.view.colorProfile.profileNameProperty to global.view.colorProfileProperty ? https://github.com/phetsims/scenery-phet/issues/515 tandem: Tandem.GLOBAL_VIEW.createTandem( 'colorProfile' ).createTandem( 'profileNameProperty' ), validValues: colorProfiles } ); scenery.register( 'colorProfileProperty', colorProfileProperty ); export default colorProfileProperty;
JavaScript
0
@@ -164,16 +164,19 @@ efault', +%0A * 'projec @@ -373,15 +373,8 @@ rst -listed colo @@ -387,27 +387,34 @@ ile -is one that +that is listed will appear -s in @@ -420,19 +420,16 @@ the sim -%0A * on star @@ -432,16 +432,19 @@ startup, +%0A * unless @@ -468,17 +468,32 @@ sim or -a +the colorProfile query p
2b7adf2dab8ba8b131ea2cf1313ac6e97f8e285e
Add material loader and replace semantic segment by material paper to Catalog component
src/Catalog/Catalog.js
src/Catalog/Catalog.js
import React, { Component } from 'react' import { Link } from 'react-router' import LastHarvesting from '../LastHarvesting/LastHarvesting' import Statistics from '../Statistics/Statistics' import Percent from '../Statistics/Percent/Percent' import './Catalog.css' class Catalog extends Component { constructor(props) { super(props) this.state = {metrics: undefined} this.getMetrics() } getMetrics() { if (!this.state.metrics) { return fetch(`https://inspire.data.gouv.fr/api/geogw/catalogs/${this.props.catalog.id}/metrics`) .then((response) => response.json()) .then((metrics) => { this.setState({metrics}) }) .catch((err) => { console.error(err) }) } } render() { const loader = <div className="ui active big loader"></div> const openness = this.state.metrics ? <Percent metrics={this.state.metrics} label="openness" icon="users" size="small" /> : loader const download = this.state.metrics ? <Percent metrics={this.state.metrics} label="download" icon="download" size="small" /> : loader return ( <Link to={`catalog/${this.props.catalog.id}`}> <div className="ui segment"> <LastHarvesting harvest={this.props.catalog.lastHarvesting}/> <div className="ui grid container"> <div className="six wide column"> <span className="ui large header">{this.props.catalog.name}</span> </div> <div className="ten wide column"> <div className="ui equal width grid"> <div className="column">{openness}</div> <div className="column">{download}</div> <div className="column"><Statistics value={this.props.catalog.lastHarvesting.recordsFound} size="small" label="Entries" /></div> </div> </div> </div> </div> </Link> ) } } export default Catalog
JavaScript
0
@@ -34,16 +34,114 @@ 'react'%0A +import Paper from 'material-ui/Paper'%0Aimport CircularProgress from 'material-ui/CircularProgress'%0A import %7B @@ -164,24 +164,24 @@ act-router'%0A - import LastH @@ -883,51 +883,37 @@ r = -%3Cdiv className=%22ui active big loader%22%3E%3C/div + %3CCircularProgress size=%7B1%7D / %3E%0A @@ -1020,12 +1020,28 @@ n=%22u -sers +nlock alternate icon %22 si @@ -1281,35 +1281,63 @@ %7D%3E%0A %3C -div +Paper rounded=%7Btrue%7D zDepth=%7B2%7D className=%22ui s @@ -2081,35 +2081,37 @@ %3E%0A %3C/ -div +Paper %3E%0A %3C/Li
b92bbe5b1232dcfe0d2eff369ffe226c0a628436
Add gray transition to level end
client/src/level-ending.js
client/src/level-ending.js
'use strict'; const eventBus = require('./event-bus'); const totalTime = 3000, // ms intensity = 0.75; class LevelEnding { constructor(stage, renderer) { this._stage = stage; this._renderer = renderer; this._timeLeft = 0; } start() { console.log('LevelEnding.start()'); // The last frame of the level should still be visible let snapshotTexture = new PIXI.RenderTexture(this._renderer, this._renderer.width, this._renderer.height); snapshotTexture.render(this._stage); this._thingy = new PIXI.Sprite(snapshotTexture); this._stage.addChild(this._thingy); let grayFilter = new PIXI.filters.GrayFilter(); this._thingy.filters = [ grayFilter ]; this._timeLeft = totalTime; } step(elapsed) { this._timeLeft -= elapsed; if (this._timeLeft <= 0) { console.log('LevelEnding.step()'); let idx = this._stage.getChildIndex(this._thingy); this._stage.removeChildAt(idx); eventBus.fire({name: 'event.level.ending.readyfornext'}); } } } module.exports = LevelEnding;
JavaScript
0.000001
@@ -68,22 +68,38 @@ -totalTime = 30 +TOTAL_GRAY_TRANSITION_TIME = 5 00, @@ -112,17 +112,22 @@ -intensity +GRAY_INTENSITY = 0 @@ -679,20 +679,22 @@ -let +this._ grayFilt @@ -729,16 +729,51 @@ lter();%0A + this._grayFilter.gray = 0;%0A @@ -797,16 +797,22 @@ ers = %5B +this._ grayFilt @@ -847,17 +847,34 @@ t = -totalTime +TOTAL_GRAY_TRANSITION_TIME ;%0A @@ -1194,16 +1194,134 @@ next'%7D); +%0A%0A %7D else %7B%0A this._grayFilter.gray = GRAY_INTENSITY - (this._timeLeft / TOTAL_GRAY_TRANSITION_TIME); %0A
16e56917c247a464ae1b21154a43c6e6a07c5419
debug layer: default to off
code/map_data_debug.js
code/map_data_debug.js
// MAP DATA DEBUG ////////////////////////////////////// // useful bits to assist debugging map data tiles window.RenderDebugTiles = function() { this.debugTileLayer = L.layerGroup(); window.addLayerGroup("DEBUG Data Tiles", this.debugTileLayer); this.debugTileToRectangle = {}; } window.RenderDebugTiles.prototype.reset = function() { this.debugTileLayer.clearLayers(); this.debugTileToRectangle = {}; } window.RenderDebugTiles.prototype.create = function(id,bounds) { var s = {color: '#666', weight: 2, opacity: 0.4, fillColor: '#666', fillOpacity: 0.1, clickable: false}; var bounds = new L.LatLngBounds(bounds); bounds = bounds.pad(-0.02); var l = L.rectangle(bounds,s); this.debugTileToRectangle[id] = l; this.debugTileLayer.addLayer(l); } window.RenderDebugTiles.prototype.setColour = function(id,bordercol,fillcol) { var l = this.debugTileToRectangle[id]; if (l) { var s = {color: bordercol, fillColor: fillcol}; l.setStyle(s); } } window.RenderDebugTiles.prototype.setState = function(id,state) { var col = '#f0f'; var fill = '#f0f'; switch(state) { case 'ok': col='#0f0'; fill='#0f0'; break; case 'error': col='#f00'; fill='#f00'; break; case 'cache-fresh': col='#0f0'; fill='#ff0'; break; case 'cache-stale': col='#f00'; fill='#ff0'; break; case 'requested': col='#66f'; fill='#66f'; break; case 'retrying': col='#666'; fill='#666'; break; case 'request-fail': col='#a00'; fill='#666'; break; case 'tile-fail': col='#f00'; fill='#666'; break; case 'tile-timeout': col='#ff0'; fill='#666'; break; } this.setColour (id, col, fill); }
JavaScript
0.000003
@@ -243,16 +243,23 @@ ileLayer +, false );%0A%0A th
a074025768c4bb56ba17213292f60e3cdec39d36
Add code comments to src/tasks/sitemap-xml.js module
src/tasks/sitemap-xml.js
src/tasks/sitemap-xml.js
var util = require('util'), _ = require('lodash'), vow = require('vow'), js2xml = require('js2xmlparser'), config = require('../config'), logger = require('../logger'), levelDb = require('../level-db'); module.exports = function(target) { logger.info('Start to build "sitemap.xml" file', module); var hosts = config.get('hosts') || {}; if(!target.getChanges().areModified()) { logger.warn('No changes were made during this synchronization. This step will be skipped', module); return vow.resolve(target); } if(!Object.keys(hosts).length) { logger.warn('No hosts were configured for creating sitemap.xml file. This step will be skipped', module); return vow.resolve(target); } return levelDb .getByCriteria(function(record) { var key = record.key, value = record.value; if(key.indexOf(target.KEY.NODE_PREFIX) < 0) { return false; } return value.hidden && _.isString(value.url) && !/^(https?:)?\/\//.test(value.url); }) .then(function(records) { records = records .map(function(record) { return _.pick(record.value, 'url', 'hidden', 'search'); }) .reduce(function(prev, item) { Object.keys(hosts).forEach(function(lang) { if(!item.hidden[lang]) { prev.push(_.extend({ loc: hosts[lang] + item.url }, item.search)); } }); return prev; }, []); return levelDb.put('sitemapXml', js2xml('urlset', { url: records })); }) .then(function() { logger.info('Successfully create sitemap.xml file', module); return vow.resolve(target); }) .fail(function(err) { logger.error(util.format('Creation of sitemap.xml file failed with error %s', err.message), module); return vow.reject(err); }); };
JavaScript
0
@@ -365,16 +365,132 @@ %7C%7C %7B%7D;%0A%0A + // check if any changes were collected during current synchronization%0A // otherwise we should skip this task%0A if(! @@ -522,24 +522,24 @@ dified()) %7B%0A - logg @@ -673,24 +673,142 @@ et);%0A %7D%0A%0A + // check if any hosts were configured in application configuration file%0A // otherwise we should skip this task%0A if(!Obje @@ -985,24 +985,74 @@ et);%0A %7D%0A%0A + // get all nodes from db that have inner urls%0A return l @@ -1415,16 +1415,141 @@ cords) %7B +%0A%0A // convert data set to sitemap format%0A // left only data fields that are needed for sitemap.xml file %0A @@ -2069,16 +2069,63 @@ , %5B%5D);%0A%0A + //convert json model to xml format%0A
f3e85916887a96d89ace44aba50fe3b212cd9949
Save XHR object for reuse in retry func
src/jquery.ajaxretry.js
src/jquery.ajaxretry.js
/**! * jQuery Ajax Retry * * project-site: http://plugins.jquery.com/project/jquery-ajax-retry * repository: http://github.com/execjosh/jquery-ajax-retry * * @author execjosh * * Copyright (c) 2010 execjosh, http://execjosh.blogspot.com * Licenced under the terms of the MIT License * (http://github.com/execjosh/jquery-ajax-retry/blob/master/LICENSE) */ (function($) { var NOP_FUNC = function(){}, MIN_ATTEMPTS = 1, MAX_ATTEMPTS = 1024, MAX_CUTOFF = 1024, MIN_CUTOFF = 1, MAX_SLOT_TIME = 10000, MIN_SLOT_TIME = 10, DEF_ATTEMPTS = 16, DEF_CUTOFF = 5, DEF_DELAY_FUNC = function(i){ return Math.floor(Math.random() * ((2 << i) - 1)); }, DEF_SLOT_TIME = 1000, DEF_OPTS = { attempts: DEF_ATTEMPTS, cutoff: DEF_CUTOFF, delay_func: DEF_DELAY_FUNC, slot_time: DEF_SLOT_TIME, tick: NOP_FUNC }, original_ajax_func = $.ajax, ajaxWithRetry = function(settings){ settings = $.extend(true, {}, $.ajaxSettings, settings); if (!settings.retry) { return original_ajax_func(settings); } var failures = 0, opts = settings.retry, orig_err_func = settings.error || NOP_FUNC; function retry_delay(time) { if (0 > time) { original_ajax_func(settings); } else { // Send tick event to listener window.setTimeout(function(){opts.tick(time)}, 0); // Wait for slot_time window.setTimeout(function(){retry_delay(time - 1)}, opts.slot_time); } } // Clamp options opts.attempts = Math.max(MIN_ATTEMPTS, Math.min(opts.attempts, MAX_ATTEMPTS)), opts.cutoff = Math.max(MIN_CUTOFF, Math.min(opts.cutoff, MAX_CUTOFF)), opts.slot_time = Math.max(MIN_SLOT_TIME, Math.min(opts.slot_time, MAX_SLOT_TIME)), opts.tick = opts.tick || NOP_FUNC; opts.delay_func = opts.delay_func || DEF_DELAY_FUNC; // Override error function settings.error = function(xhr_obj, textStatus, errorThrown){ failures++; if (failures >= opts.attempts) { // Give up and call the original error function window.setTimeout(function(){orig_err_func(xhr_obj, textStatus, errorThrown)}, 0); } else { var i = ((failures >= opts.cutoff) ? opts.cutoff : failures) - 1; window.setTimeout(function(){retry_delay(opts.delay_func(i))}, 0); } }; return original_ajax_func(settings); }; ajaxWithRetry.retrySetup = function(opts){ DEF_OPTS = $.extend(true, DEF_OPTS, opts || {}); return DEF_OPTS; }; $['ajaxWithRetry'] = ajaxWithRetry; })(jQuery); // vim: ts=4:sw=4:sts=4:noet:
JavaScript
0
@@ -2270,43 +2270,151 @@ %0A%09%09%09 -return original_ajax_func(settings) +// Save the XHR object for reuse!%0A%09%09%09var xhr = original_ajax_func(settings);%0A%09%09%09settings.xhr = function()%7B%0A%09%09%09%09return xhr;%0A%09%09%09%7D;%0A%0A%09%09%09return xhr ;%0A%09%09
489b9ed3f4f54ca5e995c9fecbe2c1ac06550c6b
Add base components to Race dashboard
src/client/react/stages/Race/Dashboard.js
src/client/react/stages/Race/Dashboard.js
import React from 'react'; import { connect } from 'react-redux'; import { Redirect } from 'react-router-dom'; import Base from '../components/Base'; import HelpMenu from '../components/HelpMenu'; const mapStateToProps = (state, ownProps) => { return { authenticated: state.auth.login.authenticated } } @connect(mapStateToProps) class Dashboard extends React.Component { render() { if (!this.props.authenticated) { return <Redirect to={{ pathname: '/', state: { next: '/dashboard' } }}/>; } return ( <div> <Base/> <HelpMenu/> </div> ); } } export default Dashboard;
JavaScript
0
@@ -20,16 +20,58 @@ react';%0A +import %7B Route %7D from 'react-router-dom';%0A import %7B @@ -109,16 +109,24 @@ import %7B + Switch, Redirec @@ -240,16 +240,236 @@ pMenu';%0A +import Home from '../pages/Home';%0Aimport Help from '../pages/Help';%0Aimport Instructions from '../pages/Instructions';%0Aimport ImageUploaderTest from '../pages/ImageUploaderTest';%0Aimport NotFound from '../pages/NotFound';%0A %0A%0Aconst @@ -789,52 +789,520 @@ %0A%0A%09%09 -return (%0A%09%09%09%3Cdiv%3E%0A%09%09%09%09%3CBase/%3E%0A%09%09%09%09%3CHelpMenu/ +const %7B url %7D = this.props.match;%0A%0A%09%09return (%0A%09%09%09%3Cdiv className='pt-dark'%3E%0A%09%09%09%09%3CBase/%3E%0A%09%09%09%09%3CHelpMenu/%3E%0A%09%09%09%09%3CSwitch%3E%0A%09%09%09%09%09%3CRoute exact path=%7B%60$%7Burl%7D%60%7D component=%7BHome%7D/%3E%0A%09%09%09%09%09%3CRoute path=%7B%60$%7Burl%7D/instructions%60%7D component=%7BInstructions%7D/%3E%0A%09%09%09%09%09%3CRoute path=%7B%60$%7Burl%7D/feed%60%7D component=%7Bnull%7D/%3E%0A%09%09%09%09%09%3CRoute path=%7B%60$%7Burl%7D/challenges%60%7D component=%7Bnull%7D/%3E%0A%09%09%09%09%09%3CRoute path=%7B%60$%7Burl%7D/help%60%7D component=%7BHelp%7D/%3E%0A%09%09%09%09%09%3CRoute path=%7B%60$%7Burl%7D/image%60%7D component=%7BImageUploaderTest%7D/%3E%0A%09%09%09%09%09%3CRoute component=%7BNotFound%7D/%3E%0A%09%09%09%09%3C/Switch %3E%0A%09%09
d300d0402ebc0695eb295531effccc1a64acecf0
fix missing var in modelist
lib/ace/ext/modelist.js
lib/ace/ext/modelist.js
define(function(require, exports, module) { "use strict"; var modes = []; /** * Suggests a mode based on the file extension present in the given path * @param {string} path The path to the file * @returns {object} Returns an object containing information about the * suggested mode. */ function getModeForPath(path) { var mode = modesByName.text; var fileName = path.split(/[\/\\]/).pop(); for (var i = 0; i < modes.length; i++) { if (modes[i].supportsFile(fileName)) { mode = modes[i]; break; } } return mode; } var Mode = function(name, caption, extensions) { this.name = name; this.caption = caption; this.mode = "ace/mode/" + name; this.extensions = extensions; if (/\^/.test(extensions)) { var re = extensions.replace(/\|(\^)?/g, function(a, b){ return "$|" + (b ? "^" : "^.*\\."); }) + "$"; } else { var re = "^.*\\.(" + extensions + ")$"; } this.extRe = new RegExp(re, "gi"); }; Mode.prototype.supportsFile = function(filename) { return filename.match(this.extRe); }; // todo firstlinematch var supportedModes = { ABAP: ["abap"], ActionScript:["as"], AsciiDoc: ["asciidoc"], AutoHotKey: ["ahk"], BatchFile: ["bat|cmd"], C9Search: ["c9search_results"], C_Cpp: ["c|cc|cpp|cxx|h|hh|hpp"], Clojure: ["clj"], coffee: ["^Cakefile|coffee|cf|cson"], ColdFusion: ["cfm"], CSharp: ["cs"], CSS: ["css"], Curly: ["curly"], Dart: ["dart"], Diff: ["diff|patch"], Dot: ["dot"], Erlang: ["erl|hrl"], Forth: ["frt|fs|ldr"], FreeMarker: ["ftl"], Glsl: ["glsl|frag|vert"], golang: ["go"], Groovy: ["groovy"], HAML: ["haml"], Haskell: ["hs"], haXe: ["hx"], HTML: ["htm|html|xhtml"], Ini: ["Ini|conf"], Jade: ["jade"], Java: ["java"], JavaScript: ["js"], JSON: ["json"], JSONiq: ["jq"], JSP: ["jsp"], JSX: ["jsx"], Julia: ["jl"], LaTeX: ["latex|tex|ltx|bib"], LESS: ["less"], Liquid: ["liquid"], Lisp: ["lisp"], LiveScript: ["ls"], LogiQL: ["logic|lql"], LSL: ["lsl"], Lua: ["lua"], LuaPage: ["lp"], Lucene: ["lucene"], Makefile: ["^GNUmakefile|^makefile|^Makefile|^OCamlMakefile|make"], Markdown: ["md|markdown"], MUSHCode: ["mc|mush"], ObjectiveC: ["m"], OCaml: ["ml|mli"], Pascal: ["pas|p"], Perl: ["pl|pm"], pgSQL: ["pgsql"], PHP: ["php|phtml"], Powershell: ["ps1"], Prolog: ["plg|prolog"], Properties: ["properties"], Python: ["py"], R: ["r"], RDoc: ["Rd"], RHTML: ["Rhtml"], Ruby: ["ru|gemspec|rake|rb"], Rust: ["rs"], SASS: ["sass"], SCAD: ["scad"], Scala: ["scala"], Scheme: ["scm|rkt"], SCSS: ["scss"], SH: ["sh|bash"], snippets: ["snippets"], SQL: ["sql"], Stylus: ["styl|stylus"], SVG: ["svg"], Tcl: ["tcl"], Tex: ["tex"], Text: ["txt"], Textile: ["textile"], Toml: ["toml"], Typescript: ["typescript|ts|str"], VBScript: ["vbs"], Velocity: ["vm"], XML: ["xml|rdf|rss|wsdl|xslt|atom|mathml|mml|xul|xbl"], XQuery: ["xq"], YAML: ["yaml"] }; var nameOverrides = { ObjectiveC: "Objective-C", CSharp: "C#", golang: "Go", C_Cpp: "C/C++", coffee: "CoffeeScript" }; var modesByName = {}; for (var name in supportedModes) { var data = supportedModes[name]; var displayName = nameOverrides[name] || name; var filename = name.toLowerCase(); mode = new Mode(filename, displayName, data[0]); modesByName[filename] = mode; modes.push(mode); } module.exports = { getModeForPath: getModeForPath, modes: modes, modesByName: modesByName }; });
JavaScript
0.000003
@@ -3988,24 +3988,28 @@ Case();%0A +var mode = new M
efde9777bdf9666959ce26ac6a89536295d602f3
Remove web stuff, we are no longer making a web app.
app/main.js
app/main.js
'use strict' require('babel-polyfill') const crypto = require('crypto') const querystring = require('querystring') require('isomorphic-fetch') // remove leading # from urlHash let urlHash = window.location.hash if (urlHash.charAt(0) === '#') urlHash = urlHash.substr(1) urlHash = querystring.parse(urlHash) if ('state' in urlHash) { // check if state matches dom storage /** * success params: * access_token * token_type * expires_in * state */ for (let param in urlHash) { window.localStorage.setItem(param, urlHash[param]) } /** * fail params: * error * state */ } else { } const accessToken = window.localStorage.getItem('access_token') if (accessToken) { console.log(' we have an access token ') console.log('getting user\'s saved tracks') collectTracks().then(organizeTracks).then(createPlaylists) } // returns a Promise function getTracks(offset) { const getTracksURL = 'https://api.spotify.com/v1/me/tracks' const headers = new Headers() headers.set('Authorization', `Bearer ${accessToken}`) const qs = querystring.stringify({ limit: 50, offset }) return fetch(`${getTracksURL}?${qs}`, { headers }).then(r => r.json()) } let tracksArr = [] // takes an HTTP response, returns total number of tracks function storeTracks(response) { tracksArr = tracksArr.concat(response.items) return response.total } function collectTracks() { return getTracks(0).then(r => { let totalTracks = storeTracks(r) let offset = 50 const promises = [] for (let offset = 50; offset < totalTracks; offset += 50) { promises.push(getTracks(offset)) } return Promise.all(promises).then(responses => { responses.forEach(curr => { storeTracks(curr) }) return Promise.resolve() }) }).catch(e => { // TODO: handle error gracefully throw e }) } /** * returns a promise with artistMap parameter * tracks * genres */ function organizeTracks() { const artistIDs = new Set() const artistMap = new Map() tracksArr.forEach(c => { artistIDs.add(c.track.artists[0].id) if (artistMap.has(c.track.artists[0].id)) { artistMap.get(c.track.artists[0].id).tracks.push(c.track.id) } else { artistMap.set(c.track.artists[0].id, { tracks: [c.track.id], genres: [] }) } }) const promises = [] promises.push(getGenres(artistIDs).then(responses => { let populated = 0 responses.forEach(r => { r.artists.forEach(c => { // NOTE: c.genres is empty on all entries!!! if (c.genres.length) populated++ artistMap.get(c.id).genres = c.genres }) }) console.log(populated, '/', artistIDs.size) return Promise.resolve(artistMap) })) promises.push(getTerms(artistIDs).then(rArr => { let populated = 0 rArr.forEach(r => { populated++ console.log(r.id()) artistMap.get(r.id()).terms = r.response.terms }) console.log(populated, '/', artistIDs.size) return Promise.resolve(artistMap) })) return Promise.all(promises) } function getGenres(artists) { const artistsURL = 'https://api.spotify.com/v1/artists' const artistsArr = Array.from(artists) const promises = [] const headers = new Headers() headers.set('Authorization', `Bearer ${accessToken}`) for (let i = 0; i < artistsArr.length; i += 50) { const qs = querystring.stringify({ ids: artistsArr.slice(i, i + 50).join() }) promises.push(fetch(`${artistsURL}?${qs}`, { headers }).then(r => r.json())) } return Promise.all(promises) } function getTerms(artists) { const termsURL = 'http://developer.echonest.com/api/v4/artist/terms' const ECHONEST_API_KEY = process.env.ECHONEST_API_KEY const artistsArr = Array.from(artists).splice(0, 5) const promises = [] artistsArr.forEach(a => { const qs = querystring.stringify({ api_key: ECHONEST_API_KEY, id: `spotify:artist:${a}`, }) promises.push(fetch(`${termsURL}?${qs}`).then(r => r.json()).then(r => { const r2 = r // enclose a r2.id = (retVal => () => retVal)(a) return Promise.resolve(r2) })) }) return Promise.all(promises) } let playlists = new Map() function createPlaylists(map) { console.log(map) map[0].forEach(v => { try { // organize by genre v.genres.forEach(g => { v.tracks.forEach(t => { if (playlists.has(g)) { playlists.get(g).push(t) } else { playlists.set(g, [t]) } }) }) // organize by terms if (v.terms && v.terms.length) { const term = v.terms[0].name v.tracks.forEach(t => { if (playlists.has(term)) { playlists.get(term).push(t) } else { playlists.set(term, [t]) } }) console.log(term) } } catch (e) { console.error(e) console.error('failed on', v) } }) console.log(playlists) } const authURL = 'https://accounts.spotify.com/authorize' const stateString = crypto.randomBytes(64).toString('hex') const authParams = { client_id: process.env.CLIENT_ID, response_type: 'token', redirect_uri: 'http://localhost:8080', state: stateString, scope: 'playlist-modify-public user-library-read', // show_dialog } const authButton = document.getElementById('auth') authButton.addEventListener('click', () => { window.location.assign(`${authURL}?${querystring.stringify(authParams)}`) }) //got(authURL, {query: authParams}).then(response => { // console.log(response.body) //}).catch(e => { // console.error(e) //})
JavaScript
0
@@ -1,18 +1,4 @@ -'use strict'%0A%0A requ @@ -129,559 +129,25 @@ )%0A%0A%0A -// remove leading # from urlHash%0Alet urlHash = window.location.hash%0Aif (urlHash.charAt(0) === '#') urlHash = urlHash.substr(1)%0AurlHash = querystring.parse(urlHash)%0A%0Aif ('state' in urlHash) %7B%0A // check if state matches dom storage%0A%0A /**%0A * success params:%0A * access_token%0A * token_type%0A * expires_in%0A * state%0A */%0A for (let param in urlHash) %7B%0A window.localStorage.setItem(param, urlHash%5Bparam%5D)%0A %7D%0A /**%0A * fail params:%0A * error%0A * state%0A */%0A%7D else %7B%0A%0A%7D%0A%0A%0Aconst accessToken = window.localStorage.getItem('access_token') +const accessToken %0Aif @@ -4749,184 +4749,8 @@ %0A%7D%0A%0A -const authButton = document.getElementById('auth')%0AauthButton.addEventListener('click', () =%3E %7B%0A window.location.assign(%60$%7BauthURL%7D?$%7Bquerystring.stringify(authParams)%7D%60)%0A%7D)%0A%0A //go
8f107bb966c44262b36ccef7eeda9fb7e44c3000
Add code to handle cases where zIndex returns -Infinity.
jquery.easyModal.js
jquery.easyModal.js
/** * easyModal.js v1.3.0 * A minimal jQuery modal that works with your CSS. * Author: Flavius Matis - http://flaviusmatis.github.com/ * URL: https://github.com/flaviusmatis/easyModal.js */ /*jslint browser: true*/ /*global jQuery*/ (function ($) { "use strict"; var methods = { init: function (options) { var defaults = { top: 'auto', autoOpen: false, overlayOpacity: 0.5, overlayColor: '#000', overlayClose: true, overlayParent: 'body', closeOnEscape: true, closeButtonClass: '.close', onOpen: false, onClose: false, zIndex: function () { return 1 + Math.max.apply(Math, $.makeArray($('*').map(function () { return $(this).css('z-index'); }).filter(function () { return $.isNumeric(this); }).map(function () { return parseInt(this, 10); }))); }, updateZIndexOnOpen: true }; options = $.extend(defaults, options); return this.each(function () { var o = options, $overlay = $('<div class="lean-overlay"></div>'), $modal = $(this); $overlay.css({ 'display': 'none', 'position': 'fixed', // When updateZIndexOnOpen is set to true, we avoid computing the z-index on initialization, // because the value would be replaced when opening the modal. 'z-index': (o.updateZIndexOnOpen ? 0 : o.zIndex()), 'top': 0, 'left': 0, 'height': '100%', 'width': '100%', 'background': o.overlayColor, 'opacity': o.overlayOpacity, 'overflow': 'auto' }).appendTo(o.overlayParent); $modal.css({ 'display': 'none', 'position' : 'fixed', // When updateZIndexOnOpen is set to true, we avoid computing the z-index on initialization, // because the value would be replaced when opening the modal. 'z-index': (o.updateZIndexOnOpen ? 0 : o.zIndex() + 1), 'left' : 50 + '%', 'top' : parseInt(o.top, 10) > -1 ? o.top + 'px' : 50 + '%' }); $modal.bind('openModal', function () { var overlayZ = o.updateZIndexOnOpen ? o.zIndex() : parseInt($overlay.css('z-index'), 10), modalZ = overlayZ + 1; $modal.css({ 'display' : 'block', 'margin-left' : -($modal.outerWidth() / 2) + 'px', 'margin-top' : (parseInt(o.top, 10) > -1 ? 0 : -($modal.outerHeight() / 2)) + 'px', 'z-index': modalZ }); $overlay.css({'z-index': overlayZ, 'display': 'block'}); if (o.onOpen && typeof o.onOpen === 'function') { // onOpen callback receives as argument the modal window o.onOpen($modal[0]); } }); $modal.bind('closeModal', function () { $modal.css('display', 'none'); $overlay.css('display', 'none'); if (o.onClose && typeof o.onClose === 'function') { // onClose callback receives as argument the modal window o.onClose($modal[0]); } }); // Close on overlay click $overlay.click(function () { if (o.overlayClose) { $modal.trigger('closeModal'); } }); $(document).keydown(function (e) { // ESCAPE key pressed if (o.closeOnEscape && e.keyCode === 27) { $modal.trigger('closeModal'); } }); // Close when button pressed $modal.on('click', o.closeButtonClass, function (e) { $modal.trigger('closeModal'); e.preventDefault(); }); // Automatically open modal if option set if (o.autoOpen) { $modal.trigger('openModal'); } }); } }; $.fn.easyModal = function (method) { // Method calling logic if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } $.error('Method ' + method + ' does not exist on jQuery.easyModal'); }; }(jQuery));
JavaScript
0
@@ -17,17 +17,17 @@ js v1.3. -0 +1 %0A* A min @@ -772,12 +772,118 @@ urn -1 + +(function (value) %7B%0A return value === -Infinity ? 0 : value + 1;%0A %7D( Math @@ -1201,16 +1201,18 @@ %7D))) +)) ;%0A
dee445515947d115616d94cfbda09cfbd4b308c0
fix confusion again
mods/linked/statuses.js
mods/linked/statuses.js
'use strict'; exports.BattleStatuses = { slp: { inherit: true, onBeforeMove: function (pokemon, target, move) { if (this.effectData.timerDecreased !== this.turn) { this.effectData.timerDecreased = this.turn; if (pokemon.getAbility().isHalfSleep) { pokemon.statusData.time--; } pokemon.statusData.time--; if (pokemon.statusData.time <= 0) { pokemon.cureStatus(); return; } this.add('cant', pokemon, 'slp'); } if (move.sleepUsable) { return; } return false; } }, frz: { inherit: true, onBeforeMove: function (pokemon, target, move) { if (move.flags['defrost']) return; if (this.effectData.durationRolled !== this.turn && this.random(5) === 0) { pokemon.cureStatus(); return; } if (this.effectData.durationRolled !== this.turn) { // Display the `frozen` message only once per turn. this.effectData.durationRolled = this.turn; this.add('cant', pokemon, 'frz'); } return false; } }, par: { inherit: true, onStart: function (target, source, sourceEffect) { if (sourceEffect && sourceEffect.effectType === 'Ability') { this.add('-status', target, 'par', '[from] ability: ' + sourceEffect.name, '[of] ' + source); } else { this.add('-status', target, 'par'); } this.effectData.lastCheckTurn = this.turn; }, onBeforeMove: function (pokemon) { if (this.effectData.lastCheckTurn !== this.turn) { // Check for `par` only once per turn. this.effectData.lastCheckTurn = this.turn; this.effectData.lastCheck = (this.random(4) === 0); if (this.effectData.lastCheck) { this.add('cant', pokemon, 'par'); return false; } } if (this.effectData.lastCheckTurn === this.turn && this.effectData.lastCheck) { // this.add('cant', pokemon, 'par'); return false; } }, }, confusion: { inherit: true, onStart: function (target, source, sourceEffect) { if (sourceEffect && sourceEffect.id === 'lockedmove') { this.add('-start', target, 'confusion', '[fatigue]'); } else { this.add('-start', target, 'confusion'); } this.effectData.time = this.random(2, 6); this.effectData.timerDecreased = this.turn; }, onBeforeMove: function (pokemon) { if (this.effectData.movePrevented) return false; if (this.effectData.timerDecreased !== this.turn) { this.effectData.movePrevented = false; this.effectData.timerDecreased = this.turn; pokemon.volatiles.confusion.time--; if (!pokemon.volatiles.confusion.time) { pokemon.removeVolatile('confusion'); return; } this.add('-activate', pokemon, 'confusion'); if (this.random(2) === 0) { return; } this.damage(this.getDamage(pokemon, pokemon, 40), pokemon, pokemon, { id: 'confused', effectType: 'Move', type: '???', }); this.effectData.movePrevented = true; return false; } } }, flinch: { inherit: true, onBeforeMove: function (pokemon) { if (this.effectData.movePrevented) return false; if (!this.runEvent('Flinch', pokemon)) { return; } if (!this.effectData.movePrevented) { // no need to display the flinch message twice this.effectData.movePrevented = true; this.add('cant', pokemon, 'flinch'); } return false; } }, mustrecharge: { inherit: true, onBeforeMove: function (pokemon) { if (!this.effectData.movePrevented) { // no need to display the recharge message twice this.effectData.movePrevented = true; this.add('cant', pokemon, 'recharge'); } if (!pokemon.moveThisTurn) pokemon.removeVolatile('mustrecharge'); return false; } }, /** * Gems and Auras * Make sure that they only boost a single move * */ gem: { inherit: true, onBeforeMove: function (pokemon) { if (pokemon.moveThisTurn) pokemon.removeVolatile('gem'); } }, aura: { inherit: true, onBeforeMove: function (pokemon) { if (pokemon.moveThisTurn) pokemon.removeVolatile('aura'); } } };
JavaScript
0.00004
@@ -2260,32 +2260,80 @@ ta.movePrevented + && this.effectData.timerDecreased === this.turn ) return false;%0A
ffe30e25ea73738a0a633cf48c284f6e5047496a
Remove unused method `checkTextIsEqual`
tests/nightwatch/modules/common-functions.js
tests/nightwatch/modules/common-functions.js
'use strict'; var util = require('util'); var _ = require('lodash'); var SAVINGS_QUESTIONS = require('../modules/constants').SAVINGS_QUESTIONS; SAVINGS_QUESTIONS.ALL = SAVINGS_QUESTIONS.MONEY.concat(SAVINGS_QUESTIONS.VALUABLES); module.exports = { setAllSavingsFieldsToValue: function(client, val) { SAVINGS_QUESTIONS.ALL.forEach(function(item) { client .clearValue(util.format('input[name="%s"]', item.name)) .setValue(util.format('input[name="%s"]', item.name), val) ; }); }, // check specific field group for error text submitAndCheckForFieldError: function(client, fields, tag) { tag = tag || "input"; client .submitForm('form', function() { console.log(' ⟡ Form submitted'); }) .waitForElementPresent('.alert-error', 3000, ' - Form has errors summary') .useXpath() ; fields.forEach(function(field) { client.assert.containsText(util.format('//%s[@name="%s"]/ancestor::*[contains(@class, "form-group")]', tag, field.name), field.errorText, util.format(' - `%s` has error message: `%s`', field.name, field.errorText)); }); client.useCss(); }, checkTextIsEqual: function(client, field, expectedText, xpath) { if(xpath) { // this may come in handy using CSS selectors later on client.useXpath(); } client.getText(field, function(result) { this.assert.equal(result.value, expectedText, util.format('Text of <%s> exactly matches "%s"', field, expectedText)); }); if(xpath) { client.useCss(); } }, checkAttributeIsNotPresent: function(client, selector, attribute) { client .getAttribute(selector, attribute, function(result) { this.assert.equal(result.value, null, util.format('Checking selector %s does NOT have attribute %s: %s', selector, attribute, (result.value === null))); }) ; }, humaniseValue: function(value) { var yesNo = { '1': 'Yes', '0': 'No' }; return yesNo[value] || value; }, formatMoneyInputs: function(prefix, inputs) { var result = {}; _.each(inputs, function(v, k) { if(_.isObject(v)) { _.map(v, function(value, period) { result[util.format('%s%s-per_interval_value', prefix, k)] = value; result[util.format('%s%s-interval_period', prefix, k)] = period; }); } else { result[util.format('%s%s', prefix, k)] = v; } }); return result; }, fillInMoneyForm: function(client, inputs, type) { _.each(inputs, function(v, k) { var selector = util.format('[name="%s"]', k); client.elements('css selector', selector, function(result) { if(!result.value.length) { return; } if(typeof v === 'number') { client .clearValue(selector) .setValue(selector, v, function() { console.log(' • %s: %s is £%d', type, k, v); }); } else { selector += util.format(' [value="%s"]', v); client.click(selector, function() { console.log(' • %s selected', v); }); } }); }); } };
JavaScript
0
@@ -1181,405 +1181,8 @@ %7D,%0A%0A - checkTextIsEqual: function(client, field, expectedText, xpath) %7B%0A if(xpath) %7B // this may come in handy using CSS selectors later on%0A client.useXpath();%0A %7D%0A client.getText(field, function(result) %7B%0A this.assert.equal(result.value, expectedText, util.format('Text of %3C%25s%3E exactly matches %22%25s%22', field, expectedText));%0A %7D);%0A if(xpath) %7B%0A client.useCss();%0A %7D%0A %7D,%0A%0A ch
26b249ad2dd04372aa56103ac59f9ece2eb58f0c
Fix short number formatting for numbers above million in web UI
app/javascript/flavours/glitch/util/numbers.js
app/javascript/flavours/glitch/util/numbers.js
import React, { Fragment } from 'react'; import { FormattedNumber } from 'react-intl'; export const shortNumberFormat = number => { if (number < 1000) { return <FormattedNumber value={number} />; } else { return <Fragment><FormattedNumber value={number / 1000} maximumFractionDigits={1} />K</Fragment>; } };
JavaScript
0.000005
@@ -204,16 +204,38 @@ %7D else + if (number %3C 1000000) %7B%0A r @@ -331,15 +331,131 @@ gment%3E;%0A + %7D else %7B%0A return %3CFragment%3E%3CFormattedNumber value=%7Bnumber / 1000000%7D maximumFractionDigits=%7B1%7D /%3EM%3C/Fragment%3E;%0A %7D%0A%7D;%0A
46c93d8b244a8ddea9706d567ece3723e59fe0d2
Update choprifier.js
production_site/choprifier.js
production_site/choprifier.js
var Data = { starts : [ "Experiential truth ", "Coffee ", "Absinthe ", "The physical world ", "Non-judgment ", "Parsimony ", "Clarity ", "Erudition ", "Primacy ", "Apostasy ", "Infinity ", "Calamity ", "Honesty ", "Aperture science ", "Temporal quaquaversality ", "Derrida ", "Prosody ", "Calamity ", "Selectivity ", "Unity ", "Good health ", "A quantum leap ", // thanks Francis Veilleux-Gaboury "A clean brain ", "Entreaty ", "Brusque temperment ", "A flexible thought pattern ", "Insightful visage ", "Mindfulness in action ", "Automated translation ", "Facebook ", "Compassion ", "Altruism ", "Totality ", "Insoucinace ", "Dynamic mutative creation ", "The graspably non-considerable ", "Social science ", "Stone age philosophy ", "Interpretive dance ", "Meditative physics ", "Rambunctious cause ", "Biology ", "Multitudinality ", "Nascent luminence ", "True randomness ", "Deconstrutionist wisdom ", "Science intersecting religion ", "The role of a leader ", "The soul of a calm person ", "The idea of God ", "Mechanistic reaction ", "Semiotic involvement ", "Quantum physics ", "Cerebrolinguistics ", "Dubstep as a metaphor for liberty " ], middles : [ "nurtures ", "unifies ", "stymies ", "separates ", "distributes widely ", "appreciates ", "deprecates ", "conglomerates ", "gives meaning to ", "displays ", "permeates ", "clarifies ", "asceticizes ", "recapitulates ", "satisfies ", "sanctifies via ", "trivializes ", "justifies with ", "rarifies ", "codifies ", "socializes by way of ", "reclaims ", "disintegrates ", "integrates ", "reduces ", "explores ", "dissociates from within ", "exposes ", "builds, using ", "teaches through ", "projects onto ", "imparts reality to ", "constructs with " ], qualifiers : [ "abundance of ", "ostentatious ", "the barrier of ", "self-righteous ", "collective ", "species specific ", "heterodynamic ", "epistemological ", "synchronistic ", "timely ", "unpredictable ", "unassailable ", "dishonest ", "factual ", "highly descriptive ", "location based ", "describably pure ", "bounded ", "unbounded ", "trans-boundary ", "expedient ", "ontogenous ", "geopolitical ", "popular ", "advocatory ", "pluripotentialistic ", "rhythmatic ", "dimensional ", "sophist ", "reliquary ", "escapist ", "anarchist ", "conformist ", "erudite ", "miniscule ", "Manichean ", "Hadrean ", "media driven ", "global ", "local ", "post-", "hyper-", "trans-", "extra-", "super-", "supra-", "world regarding ", "provably optimal ", "potential " ], finishes : [ "marvel.", "choices.", "harmony.", "phylogeny.", "disharmony.", "traversal.", "ostracism.", "semiotics.", "deconstructionism.", "post-logic.", "escapism.", "criarchy.", "platitudinality.", "creosophy.", "journalism.", "preternaturality.", "glossolalia.", "idolatry.", "conscience confluence.", "hapto-ergonomics.", "mental rigor.", "spiritual fortitude.", "wisdom.", "secret genius.", "inner brilliance.", "unseen internal gift.", "combobulation.", "transdoctrinal inference.", "creativity.", "significance.", "materialization.", "generosity.", "infinitude.", "plurality.", "asceticism.", "truism.", "monopoly.", "temerity.", "monosophism.", "polyarchy.", "togetherness.", "voluminous reaction.", "joyous revelation.", "stimulation.", "numbing.", "intuition.", "actions." ] }; function randFrom(X) { return X[Math.floor(Math.random() * X.length)]; } function makeDC() { return randFrom(Data.starts) + randFrom(Data.middles) + randFrom(Data.qualifiers) + randFrom(Data.finishes); } function go() { document.getElementById('txt').innerHTML = '"' + makeDC() + '"'; }
JavaScript
0
@@ -157,24 +157,45 @@ %22Clarity %22,%0A + %22Heterodoxity %22,%0A %22Eruditi
0c2e7c68b6f7c62c2d279acbb2536fa0933bbbc0
Update choprifier.js
production_site/choprifier.js
production_site/choprifier.js
var Data = { starts : [ "Experiential truth ", "The physical world ", "Non-judgment ", "Infinity ", "Unity ", "Good health ", "A clean brain ", "A flexible thought pattern ", "Insightful visage ", "Mindfulness in action ", "Totality ", "Dynamic mutative creation ", "The graspably non-considerable ", "Social science ", "Stone age philosophy ", "Meditative physics ", "Rambunctious cause ", "Multitudinality ", "Nascent luminence ", "True randomness ", "Deconstrutionist wisdom ", "Science intersecting religion ", "The role of a leader ", "The soul of a calm person ", "The idea of God ", "Mechanistic reaction ", "Semiotic involvement ", "Quantum physics ", "Cerebrolinguistics ", "Dubstep as a metaphor for liberty " ], middles : [ "nurtures ", "unifies ", "separates ", "distributes widely ", "appreciates ", "deprecates ", "conglomerates ", "gives meaning to ", "displays ", "permeates ", "clarifies ", "asceticizes ", "recapitulates ", "sanctifies via ", "trivializes ", "justifies with ", "rarifies ", "codifies ", "reduces ", "explores ", "dissociates from within ", "exposes ", "builds, using ", "teaches through ", "projects onto ", "imparts reality to ", "constructs with " ], qualifiers : [ "abundance of ", "ostentatious ", "the barrier of ", "self-righteous ", "species specific ", "heterodynamic ", "epistemological ", "synchronistic ", "timely ", "unpredictable ", "unassailable ", "dishonest ", "factual ", "highly descriptive ", "location based ", "describably pure ", "bounded ", "unbounded ", "trans-boundary ", "expedient ", "ontogenous ", "geopolitical ", "popular ", "advocatory ", "pluripotentialistic ", "rhythmatic ", "dimensional ", "sophist ", "escapist ", "anarchist ", "conformist ", "erudite ", "manichean ", "media driven ", "global ", "local ", "post-", "hyper-", "trans-", "extra-", "super-", "supra-", "world regarding ", "provably optimal ", "potential " ], finishes : [ "marvel.", "choices.", "harmony.", "phylogeny.", "disharmony.", "traversal.", "ostracism.", "semiotics.", "deconstructionism.", "post-logic.", "escapism.", "criarchy.", "platitudinality.", "creosophy.", "journalism.", "preternaturality.", "glossolalia.", "idolatry.", "conscience confluence.", "hapto-ergonomics.", "mental rigor.", "spiritual fortitude.", "wisdom.", "secret genius.", "inner brilliance.", "unseen internal gift.", "combobulation.", "transdoctrinal inference.", "creativity.", "significance.", "materialization.", "generosity.", "infinitude.", "plurality.", "asceticism.", "truism.", "monopoly.", "monosophism.", "polyarchy.", "togetherness.", "voluminous reaction.", "joyous revelation.", "stimulation.", "numbing.", "intuition.", "actions." ] }; function randFrom(X) { return X[Math.floor(Math.random() * X.length)]; } function makeDC() { return randFrom(Data.starts) + randFrom(Data.middles) + randFrom(Data.qualifiers) + randFrom(Data.finishes); } function go() { document.getElementById('txt').innerHTML = '"' + makeDC() + '"'; }
JavaScript
0
@@ -272,24 +272,44 @@ Totality %22,%0A + %22Insoucinace %22,%0A %22Dynamic
fcb3346d4cd6839293f7bb12bc3a1fcc7abbba4f
fix up tests
test/enterprise/index.js
test/enterprise/index.js
var Code = require('code'), Lab = require('lab'), lab = exports.lab = Lab.script(), describe = lab.experiment, before = lab.before, after = lab.after, it = lab.test, expect = Code.expect; var server; before(function(done) { require('../mocks/server')(function(obj) { server = obj; done(); }); }); after(function(done) { server.stop(done); }); describe('Getting to the enterprise page', function() { it('gets there, no problem', function(done) { var opts = { url: '/enterprise' }; server.inject(opts, function(resp) { expect(resp.statusCode).to.equal(200); var source = resp.request.response.source; expect(source.template).to.equal('enterprise/index'); expect(source.context.title).to.equal('npm On-Site'); done(); }); }); });
JavaScript
0.000007
@@ -394,25 +394,21 @@ to the -enterpris +onsit e page', @@ -499,25 +499,21 @@ url: '/ -enterpris +onsit e'%0A %7D
cdcc4e39a8c2ad558a994ed698fadcf1dd90d338
remove unnecessary error notification
webapps/ui/tasklist/client/scripts/api/index.js
webapps/ui/tasklist/client/scripts/api/index.js
'use strict'; var angular = require('camunda-commons-ui/vendor/angular'), CamSDK = require('camunda-commons-ui/vendor/camunda-bpm-sdk-angular'); var apiModule = angular.module('cam.tasklist.client', []); apiModule.value('HttpClient', CamSDK.Client); apiModule.value('CamForm', CamSDK.Form); apiModule.run([ '$rootScope', 'Notifications', '$translate', function($rootScope, Notifications, $translate) { $rootScope.$on('authentication.login.required', function() { $translate([ 'SESSION_EXPIRED', 'SESSION_EXPIRED_MESSAGE' ]).then(function(translations) { Notifications.addError({ status: translations.SESSION_EXPIRED, message: translations.SESSION_EXPIRED_MESSAGE }); }); }); }]); apiModule.factory('camAPI', [ 'camAPIHttpClient', '$window', 'Uri', function(camAPIHttpClient, $window, Uri) { var conf = { apiUri: 'engine-rest/api/engine', HttpClient: camAPIHttpClient, engine: Uri.appUri(':engine') }; if ($window.tasklistConf) { for (var c in $window.tasklistConf) { conf[c] = $window.tasklistConf[c]; } } return new CamSDK.Client(conf); }]); module.exports = apiModule;
JavaScript
0
@@ -296,454 +296,8 @@ );%0A%0A -apiModule.run(%5B '$rootScope', 'Notifications', '$translate', function($rootScope, Notifications, $translate) %7B%0A $rootScope.$on('authentication.login.required', function() %7B%0A $translate(%5B%0A 'SESSION_EXPIRED',%0A 'SESSION_EXPIRED_MESSAGE'%0A %5D).then(function(translations) %7B%0A Notifications.addError(%7B%0A status: translations.SESSION_EXPIRED,%0A message: translations.SESSION_EXPIRED_MESSAGE%0A %7D);%0A %7D);%0A %7D);%0A%7D%5D);%0A%0A apiM
0c30aa74feb27379e668f9331338920803258b44
configure profile and gitstamp schemas
db/schema.js
db/schema.js
JavaScript
0
@@ -0,0 +1,592 @@ +// requiring mongoose dependency%0Avar mongoose = require('mongoose')%0A%0A// instantiate a name space for our Schema constructor defined by mongoose.%0Avar Schema = mongoose.Schema,%0A ObjectId = Schema.ObjectId%0A%0A// defining schema for reminders%0Avar GitstampSchema = new Schema(%7B%0A data: Float%0A%7D)%0A%0A// defining schema for authors.%0Avar ProfileSchema = new Schema(%7B%0A name: String,%0A gitstamps: %5BGitstampSchema%5D%0A%7D)%0A%0A// setting models in mongoose utilizing schemas defined above%0Avar ProfileModel = mongoose.model(%22Profile%22, ProfileSchema)%0Avar GitstampModel = mongoose.model(%22Gitstamp%22, GitstampSchema)%0A
a3bf004a4763b43901fa6400ae77556a85f6a70d
Fix ListHeading
js/components/ListHeading.react.js
js/components/ListHeading.react.js
import React from "react"; import { Link } from "react-router"; import styled from 'styled-components'; const Wrapper = styled.div` padding: 1em; margin: 0; border-bottom: 1px solid $light-grey; text-align: center; width: 100%; position: relative; > h2 { padding: 0; margin: 0; } `; const Icon = styled.svg` height: 1.5em; width: 1.5em; `; const ListHeading = ({text}) => { return( <Wrapper> <Link to="/" className="search__heading-back"> <Icon width="24" height="24" viewBox="0 0 24 24"> <g stroke="#000" strokeLinecap="round" strokeLinejoin="round" strokeMiterlimit="10" fill="none"> <path d="M.5.5h10v10h-10zM13.5.5h10v10h-10zM.5 13.5h10v10h-10zM13.5 13.5h10v10h-10z"/> </g> </Icon> </Link> <h2>{text}</h2> </Wrapper> ); } export default ListHeading;
JavaScript
0.000001
@@ -98,16 +98,55 @@ ents';%0A%0A +import constants from %22../constants%22;%0A%0A const Wr @@ -220,18 +220,29 @@ id $ +%7Bconstants. light --g +G rey +%7D ;%0Ate
0d8e44a3039084008c5cc3a4033a0f85709fd538
remove useless code
src/js/jump-to-const.js
src/js/jump-to-const.js
__$__.JumpToConstruction = { ClickElementContext: {}, ClickElement: {}, GraphData: {nodes: [], edges: []} }; /** * if you click on a node or edge, this function is executed. */ __$__.JumpToConstruction.ClickEventFunction = function(param) { // choose node if (param.nodes.length) { __$__.JumpToConstruction.ClickElement.node = param.nodes[0]; } // choose edge else if (param.edges.length) { var edgeId = param.edges[0]; __$__.JumpToConstruction.ClickElement.edge = __$__.network.body.data.edges._data[edgeId]; } // no choose else return; __$__.Context.SwitchContext(true); document.getElementById('context').textContent = 'Use Context'; if (__$__.JumpToConstruction.ClickElement.node) __$__.JumpToConstruction.GraphData.nodes.forEach(nodeData => { if (__$__.JumpToConstruction.ClickElement.node == nodeData.id) { __$__.Context.LoopContext[nodeData.loopId] = nodeData.count; __$__.Context.ChangeInnerAndParentContext(nodeData.loopId); __$__.editor.moveCursorToPosition({row: nodeData.pos.line - 1, column: nodeData.pos.column}); } }); else __$__.JumpToConstruction.GraphData.edges.forEach(edgeData => { if (__$__.JumpToConstruction.ClickElement.edge.from == edgeData.from && __$__.JumpToConstruction.ClickElement.edge.to == edgeData.to && __$__.JumpToConstruction.ClickElement.edge.label == edgeData.label) { __$__.Context.LoopContext[edgeData.loopId] = edgeData.count; __$__.Context.ChangeInnerAndParentContext(edgeData.loopId); __$__.editor.moveCursorToPosition({row: edgeData.pos.line - 1, column: edgeData.pos.column}); } }); if (__$__.editor.getSelection().isEmpty()) { __$__.Update.ContextUpdate(); } else { __$__.editor.getSelection().clearSelection(); } __$__.JumpToConstruction.ClickElementContext = {}; __$__.JumpToConstruction.ClickElement = {}; };
JavaScript
0.006635
@@ -649,77 +649,8 @@ e);%0A - document.getElementById('context').textContent = 'Use Context';%0A%0A %0A
b6cb27534eac0073c369223eb87b173c52340c88
Remove getInitialData method #56
mixins/data-fetch.js
mixins/data-fetch.js
Cosmos.mixins.DataFetch = { /** * Bare functionality for fetching server-side JSON data inside a Component. * * Props: * - dataUrl: A URL to fetch data from. Once data is received it will be * set inside the Component's state, under the data key, and * will cause a reactive re-render. * - pollInterval: An interval in milliseconds for polling the data URL. * Defaults to 0, which means no polling. * * Context properties: * - initialData: The initial value of state.data, before receiving and data * from the server (see dataUrl prop.) Defaults to an empty * object `{}` - TODO: make this a method with props at hand * Context methods: * - getDataUrl: The data URL can be generated dynamically by composing it * using other props, inside a custom method that receives * the next props as arguments and returns the data URL. The * expected method name is "getDataUrl" and overrides the * dataUrl prop when implemented. */ fetchDataFromServer: function(url, onSuccess) { var request = $.ajax({ url: url, // Even though not recommended, some $.ajaxSettings might default to POST // requests. See http://api.jquery.com/jquery.ajaxsetup/ type: 'GET', dataType: 'json', complete: function() { this.xhrRequests = _.without(this.xhrRequests, request); }.bind(this), success: onSuccess, error: function(xhr, status, err) { console.error(url, status, err.toString()); }.bind(this) }); this.xhrRequests.push(request); }, receiveDataFromServer: function(data) { this.setState({data: data}); }, getInitialData: function() { // The default data object is an empty Object. A List Component would // override initialData with an empty Array and other Components might want // some defaults inside the initial data return this.initialData !== undefined ? this.initialData : {}; }, resetData: function(props) { // The data URL can be generated dynamically by composing it through other // props, inside a custom method that receives the next props as arguments // and returns the data URL. The expected method name is "getDataUrl" and // overrides the dataUrl prop when implemented var dataUrl = typeof(this.getDataUrl) == 'function' ? this.getDataUrl(props) : this.props.dataUrl; if (dataUrl == this.dataUrl) { return; } this.dataUrl = dataUrl; // Clear any on-going polling when data is reset. Even if polling is still // enabled, we need to reset the interval to start from now this.clearDataRequests(); if (dataUrl) { this.fetchDataFromServer(dataUrl, this.receiveDataFromServer); if (props.pollInterval) { this.pollInterval = setInterval(function() { this.fetchDataFromServer(dataUrl, this.receiveDataFromServer); }.bind(this), props.pollInterval); } } }, clearDataRequests: function() { // Cancel any on-going request and future polling while (!_.isEmpty(this.xhrRequests)) { this.xhrRequests.pop().abort(); } if (this.pollInterval) { clearInterval(this.pollInterval); } }, getDefaultProps: function() { return { // Enable polling by setting a value bigger than zero, in ms pollInterval: 0 }; }, componentWillMount: function() { this.xhrRequests = []; // The dataUrl prop points to a source of data than will extend the initial // state of the component, once it will be fetched this.resetData(this.props); }, componentWillReceiveProps: function(nextProps) { // A Component can have its configuration replaced at any time this.resetData(nextProps); }, componentWillUnmount: function() { this.clearDataRequests(); } };
JavaScript
0
@@ -1785,310 +1785,8 @@ %7D,%0A - getInitialData: function() %7B%0A // The default data object is an empty Object. A List Component would%0A // override initialData with an empty Array and other Components might want%0A // some defaults inside the initial data%0A return this.initialData !== undefined ? this.initialData : %7B%7D;%0A %7D,%0A re
343d0c0dd1bd5497d5581cf4ca6b91a35ff9c858
Remove firebase details
src/config/constants.js
src/config/constants.js
import * as firebase from 'firebase'; import FirebaseImageUploader from 'firebase-image-uploader' const config = { apiKey: "AIzaSyDMkJOU44LTPfwIHDNYaG7SihfeQnYhvMw", authDomain: "mixmeals-144307.firebaseapp.com", databaseURL: "https://mixmeals-144307.firebaseio.com", storageBucket: "mixmeals-144307.appspot.com", messagingSenderId: "411842349083" }; firebase.initializeApp(config) export const ref = firebase.database().ref() export const firebaseAuth = firebase.auth
JavaScript
0
@@ -124,201 +124,66 @@ y: %22 -AIzaSyDMkJOU44LTPfwIHDNYaG7SihfeQnYhvMw%22,%0A authDomain: %22mixmeals-144307.firebaseapp.com%22,%0A databaseURL: %22https://mixmeals-144307.firebaseio.com%22,%0A storageBucket: %22mixmeals-144307.appspot.com +%22,%0A authDomain: %22%22,%0A databaseURL: %22%22,%0A storageBucket: %22 %22,%0A @@ -207,20 +207,8 @@ d: %22 -411842349083 %22%0A%7D;
a19deb5728c60e9b5fbc3f69c3b0a896172f0043
Add comment explaining funky math
shared/chat/conversation/list/index.native.js
shared/chat/conversation/list/index.native.js
// @flow import * as Constants from '../../../constants/chat' import React, {Component} from 'react' import {withPropsOnChange} from 'recompose' import messageFactory from '../messages' import {Box, NativeScrollView} from '../../../common-adapters/index.native' // $FlowIssue import FlatList from '../../../fixme/Lists/FlatList' import type {Props} from '.' class ConversationList extends Component <void, Props, void> { _scrollRef: ?any; _onAction = (message: Constants.ServerMessage, event: any) => { this.props.onMessageAction(message) } // This is handled slightly differently on mobile, leave this blank _onShowEditor = (message: Constants.Message, event: any) => { } // This is handled slightly differently on mobile, leave this blank _measure = () => {} _renderItem = ({item: messageKey, index}) => { const prevMessageKey = this.props.messageKeys.get(index + 1) const isSelected = false return ( // We ahve to invert transform the message or else it will look flipped <Box style={verticallyInvertedStyle}> {messageFactory(messageKey, prevMessageKey, this._onAction, this._onShowEditor, isSelected, this._measure)} </Box> ) } _keyExtractor = messageKey => messageKey _onEndReached = () => { this.props.onLoadMoreMessages() } componentDidUpdate (prevProps: Props) { // TODO do we need this? I think the list may work how we want w/o this if (this.props.listScrollDownCounter !== prevProps.listScrollDownCounter && this._scrollRef) { this._scrollRef.scrollTo({animated: false, y: 0}) } } _renderScrollComponent = (props) => ( <NativeScrollView {...props} ref={this._captureScrollRef} style={[verticallyInvertedStyle, props.style]} /> ) _captureScrollRef = r => { this._scrollRef = r } render () { return ( <FlatList data={this.props.messageKeys.toArray()} renderItem={this._renderItem} renderScrollComponent={this._renderScrollComponent} onEndReached={this._onEndReached} onEndReachedThreshold={0} keyExtractor={this._keyExtractor} /> ) } } const verticallyInvertedStyle = { flex: 1, transform: [ {scaleY: -1}, ], } // Reverse the order of messageKeys to compensate for vertically reversed display const withReversedMessageKeys = withPropsOnChange( ['messageKeys'], ({messageKeys, ...rest}) => ({messageKeys: messageKeys.reverse(), ...rest}) ) export default withReversedMessageKeys(ConversationList)
JavaScript
0
@@ -891,16 +891,76 @@ dex + 1) + // adding instead of subtracting because of reversed index %0A con
53e659241d925ba89e1469461c970f20819d6372
Update docs
source/decorators/EntryCollection.js
source/decorators/EntryCollection.js
"use strict"; var instanceSearching = require("../tools/searching-instance.js"); /** * Find entries by searching properties/meta * When used within a group, that group's entries are also searched' * @param {Archive|Group} groupParent The target archive or group * @param {string} check Information to check (id/property/meta) * @param {string} key The key (property/meta-value) to search with * @param {RegExp|string} value The value to search for * @returns {Array.<Entry>} An array of found entries * @private * @static * @memberof EntryCollection */ function findEntriesByCheck(groupParent, check, key, value) { // If the groupParent object is a Group, use it as the only search group, // otherwise just take the children groups (groupParent is probably an // Archive instance): let groups = (groupParent.getEntries) ? [groupParent] : groupParent.getGroups(); return instanceSearching.findEntriesByCheck( groups, function(entry) { var itemValue; switch(check) { case "property": { itemValue = entry.getProperty(key) || ""; break; } case "meta": { itemValue = entry.getMeta(key) || ""; break; } case "id": { return value === entry.getID(); } default: throw new Error(`Unknown check instruction: ${check}`); } if (value instanceof RegExp) { return value.test(itemValue); } else { return itemValue.indexOf(value) >= 0; } } ); } /** * @typedef {Object} EntryCollection * @mixin */ module.exports = { decorate: function(inst) { inst.findEntryByID = function findEntryByID(id) { let entries = findEntriesByCheck(inst, "id", null, id); return (entries && entries.length === 1) ? entries[0] : null; }; /** * Find entries that match a certain meta property * @name findEntriesByMeta * @param {string} metaName The meta property to search for * @param {RegExp|string} value The value to search for * @returns {Array.<Entry>} An array of found entries * @memberof EntryCollection */ inst.findEntriesByMeta = function findEntriesByMeta(metaName, value) { return findEntriesByCheck(inst, "meta", metaName, value); }; /** * Find all entries that match a certain property * @name findEntriesByProperty * @param {string} property The property to search with * @param {RegExp|string} value The value to search for * @returns {Array.<Entry>} An array of found extries * @memberof EntryCollection */ inst.findEntriesByProperty = function findEntriesByProperty(property, value) { return findEntriesByCheck(inst, "property", property, value); }; } };
JavaScript
0.000001
@@ -392,16 +392,42 @@ rch with + (not needed for check=id) %0A * @par @@ -1857,24 +1857,245 @@ on(inst) %7B%0A%0A + /**%0A * Find an entry by its ID%0A * @param %7BString%7D id The ID to search for%0A * @returns %7Bnull%7CEntry%7D Null if not found, or the Entry instance%0A * @memberof EntryCollection%0A */%0A inst @@ -2415,25 +2415,25 @@ * @param %7B -s +S tring%7D metaN
04e08b23e8d6f35b23bca9d0362681a21507fe49
Allow omitting options for tilize
modules/tilize-image.js
modules/tilize-image.js
'use strict'; var os = require('os') var fs = require('fs') var im = require('imagemagick') var path = require('path') var gdal = require('gdal') var async = require('async') var imgMeta = require('./image-meta') var geoCoords = require('./geo-coords') /** * Splits an image into tiles * @param {String} filename input image * @param {Number} tileSize Square size for the resultant tiles (in pixels) * @param {Number} overlap Amount by which to overlap tiles in x and y (in pixels) * @param {String} label A label to overlay on the image * @param {Number} labelPos Where to anchor label (e.g. "south", "northwest" etc) * @param {Function} callback */ function tilizeImage (filename, tileSize, overlap, options, callback){ var tile_wid = tileSize; var tile_hei = tileSize; var step_x = tile_wid - overlap; var step_y = tile_hei - overlap; var basename = path.basename(filename).split('.')[0] var dirname = path.dirname(filename) var ds = gdal.open(filename) var metadata = geoCoords.getMetadata(ds) var size = metadata.size // Tile creator var create_tile_task = function (task, done) { var row = task.row var col = task.col var offset_x = task.offset_x var offset_y = task.offset_y var outfile = dirname + '/' + basename + '_' + row + '_' + col + '.jpeg' /* Convert corner and center pixel coordinates to geo */ var coords = { upper_left : geoCoords.pxToWgs84(ds, offset_x, offset_y), upper_right : geoCoords.pxToWgs84(ds, offset_x + tile_wid, offset_y), bottom_right : geoCoords.pxToWgs84(ds, offset_x + tile_wid, offset_y + tile_hei), bottom_left : geoCoords.pxToWgs84(ds, offset_x, offset_y + tile_hei), center : geoCoords.pxToWgs84(ds, offset_x + tile_wid / 2, offset_y + tile_hei / 2) } // base tilizing arguments var convertArgs = [ `${filename}[0]`, '-crop', `${tile_wid}x${tile_hei}+${offset_x}+${offset_y}`, '-extent', `${tile_wid}x${tile_hei}`, '-background', 'black', '-compose', 'copy', '+repage' ]; // equalize image histogram (contrast stretch) if(options.equalize) { convertArgs = convertArgs.concat(['-equalize']); } // add label-generating arguments if(options.label) { convertArgs = convertArgs.concat([ '-gravity', 'south', '-stroke', 'black', '-strokewidth', 2, '-pointsize', 14, '-annotate', 0, options.label, '-stroke', 'none', '-fill', 'white', '-annotate', 0, options.label ]); } // lastly, concatenate output file name convertArgs = [ convertArgs.concat([outfile]) ]; async.eachSeries(convertArgs, im.convert, (err, results) => { if (err) return done(err); imgMeta.write(outfile, '-userComment', coords, done) // write coordinates to tile image metadata }); } // Init task queue var concurrency = os.cpus().length / 2 var queue = async.queue(create_tile_task, concurrency) // Completion callback queue.drain = function (error) { callback(error, files) } // Push tile tasks into queue var files = []; for( var offset_x=0, row=0; offset_x<=size.x; offset_x+=step_x, row+=1) { for( var offset_y=0, col=0; offset_y<=size.y; offset_y+=step_y, col+=1) { queue.push({ row: row, col: col, offset_x: offset_x, offset_y: offset_y }, function (err, file) { files.push(file); }) } } // end outer for loop } /** * Tilizes a set of images into a flat list of tiles. Assumes the source files are of the exactly same geographic bounds (i.e. same space, different time) * @param {Array<String>} files files * @param {Number} tileSize tile size * @param {Number} tileOverlap tile overlap size (x and y) * @param {String} label A label to overlay on the image * @param {Number} labelPos Where to anchor label (1 = top left, 2 = top center, 3 = top right, etc) * @param {Function} callback */ function tilizeImages(files, tileSize, tileOverlap, options, callback) { var tasks = []; for (var file of files) { tasks.push(async.apply(tilizeImage, file, tileSize, tileOverlap, options)); } async.series(tasks, (err, tilesBySrc) => { var allTiles = []; for (var tiles of tilesBySrc) { allTiles = allTiles.concat(tiles); } callback(err, allTiles.sort()); }); } module.exports = { tilize: tilizeImage, tilizeMany: tilizeImages };
JavaScript
0.000004
@@ -826,16 +826,43 @@ lback)%7B%0A + options = options %7C%7C %7B%7D;%0A var ti
a2082abdaa31fd023d111a787733bb71055cbdd6
Trim slug before inserting dashes
src/config/constants.js
src/config/constants.js
export const liveRootUrl = 'https://bolg-app.herokuapp.com/posts/'; export const states = { LOADING: 0, EDITING: 1, SAVED: 2, ERROR: 3, EDITING_OFFLINE: 4, SAVED_OFFLINE: 5, PUBLISHED: 6, }; export const mapsAPIKey = 'AIzaSyBADvjevyMmDkHb_xjjh3FOltkO2Oa8iAQ'; export const sizes = [ { width: 2560, height: 1440, }, { width: 1920, height: 1080, }, { width: 1024, height: 576, }, { width: 640, height: 360, }, ]; export const slugger = str => str .toLowerCase() .replace(/ä/g, 'ae') .replace(/ö/g, 'oe') .replace(/ü/g, 'ue') .replace(/[^\w ]+/g, ' ') .replace(/ +/g, '-');
JavaScript
0.000001
@@ -628,16 +628,28 @@ g, ' ')%0A + .trim()%0A .rep
6b1661f1e26189ef25f39d2c6394d69531d2fd9e
Remove double slash from path
src/js/h5p-overwrite.js
src/js/h5p-overwrite.js
H5P.getLibraryPath = function (library) { return H5PIntegration.url + '/' + library.split('-')[0]; }; H5P.getPath = function (path, contentId) { var hasProtocol = function (path) { return path.match(/^[a-z0-9]+:\/\//i); }; if (hasProtocol(path)) { return path; } var prefix; if (contentId !== undefined) { prefix = H5PIntegration.url + '/content/'; } else if (window.H5PEditor !== undefined) { prefix = H5PEditor.filesPath; } else { return; } // if (!hasProtocol(prefix)) { // // Use absolute urls // prefix = window.location.protocol + "//" + window.location.host + prefix; // } return prefix + '/' + path; };
JavaScript
0
@@ -367,17 +367,16 @@ /content -/ ';%0A %7D%0A
a94583dd77e3b4a982d734a016b96802c9b4ab17
Fix icons order, and warnings about svg properties
shared/components/grid-overlay/GridOverlay.js
shared/components/grid-overlay/GridOverlay.js
/* eslint-disable react/no-array-index-key */ import React, { Component, PropTypes } from 'react'; import autobind from 'core-decorators/lib/autobind'; import s from './GridOverlay.scss'; // Key to store visibility state of the grid overlay const LOCAL_STORAGE_KEY_HORIZONTAL = '_devtoolsHorizontalGridVisible'; const LOCAL_STORAGE_KEY_VERTICAL = '_devtoolsVerticalGridVisible'; /** * Grid Overlay component */ export default class GridOverlay extends Component { static propTypes = { columns: PropTypes.number, }; static defaultProps = { columns: 12, baseline: 16, }; // Initial state state = { horizontalIsVisible: false, verticalIsVisible: false, }; /** * Fired when component is mounted on the client * Should setup the grid overlay correctly. * @return {void} */ componentDidMount() { this.setup(); } /** * Fired column count is changed on the fly. * Re-initialize the component. * @param {object} Properties * @return {void} */ componentWillReceiveProps(props) { this.setup(props); } /** * Fired when the horizontal grid is meant to be toggled. * @return {void} */ @autobind onToggleHorizontal() { const isVisible = !this.state.horizontalIsVisible; localStorage.setItem(LOCAL_STORAGE_KEY_HORIZONTAL, isVisible); this.setState({ horizontalIsVisible: isVisible }); } /** * Fired when the vertical grid is meant to be toggled. * @return {void} */ @autobind onToggleVertical() { const isVisible = !this.state.verticalIsVisible; localStorage.setItem(LOCAL_STORAGE_KEY_VERTICAL, isVisible); this.setState({ verticalIsVisible: isVisible }); } /** * Setup will set correct column count and check if it should be visible or not. * @param {object} Properties, if other than this.props * @return {void} */ setup(props = null) { const { columns, baseline } = props || this.props; const horizontalIsVisible = (localStorage.getItem(LOCAL_STORAGE_KEY_HORIZONTAL) === 'true'); const verticalIsVisible = (localStorage.getItem(LOCAL_STORAGE_KEY_VERTICAL) === 'true'); this.setState({ horizontalIsVisible, verticalIsVisible, }); this.grid.style.setProperty('--grid-column-count', columns); this.grid.style.setProperty('--grid-baseline', `${baseline}px`); this.grid.style.setProperty('--grid-baseline-calc', baseline); } /** * Render the grid and button to toggle * @return {Component} */ render() { const { columns } = this.props; const { horizontalIsVisible, verticalIsVisible } = this.state; return ( <div className={s('grid', { horizontalIsVisible }, { verticalIsVisible })} ref={el => (this.grid = el)} > <div className={s.grid__container}> <div className={s.grid__row} data-columns={columns}> {Array(columns).fill(0).map((_, i) => ( <div key={`grid_column_${i}`} className={s.grid__column}> <div className={s.grid__visualize} /> </div> ))} </div> </div> <button className={s('grid__button', { verticalIsVisible })} onClick={this.onToggleVertical}> <svg className={s.grid__button__svg} width="14px" height="14px" viewBox="0 0 14 14"> <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" transform="translate(7.000000, 7.000000) rotate(-270.000000) translate(-7.000000, -7.000000)"> <rect x="0" y="0" width="2" height="14" /> <rect x="4" y="0" width="2" height="14" /> <rect x="8" y="0" width="2" height="14" /> <rect x="12" y="0" width="2" height="14" /> </g> </svg> </button> <button className={s('grid__button', { horizontalIsVisible })} onClick={this.onToggleHorizontal}> <svg className={s.grid__button__svg} width="14px" height="14px" viewBox="0 0 14 14"> <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <rect x="0" y="0" width="2" height="14" /> <rect x="4" y="0" width="2" height="14" /> <rect x="8" y="0" width="2" height="14" /> <rect x="12" y="0" width="2" height="14" /> </g> </svg> </button> </div> ); } }
JavaScript
0
@@ -3339,34 +3339,33 @@ ke=%22none%22 stroke --w +W idth=%221%22 fill=%22n @@ -3365,34 +3365,33 @@ fill=%22none%22 fill --r +R ule=%22evenodd%22 tr @@ -3391,102 +3391,8 @@ odd%22 - transform=%22translate(7.000000, 7.000000) rotate(-270.000000) translate(-7.000000, -7.000000)%22 %3E%0A @@ -3911,10 +3911,9 @@ roke --w +W idth @@ -3937,10 +3937,9 @@ fill --r +R ule= @@ -3939,32 +3939,126 @@ llRule=%22evenodd%22 + transform=%22translate(7.000000, 7.000000) rotate(-270.000000) translate(-7.000000, -7.000000)%22 %3E%0A
a1395312115ac68d7ebc2eab7d4b57cb642ee635
Update FacebookLocales.js
src/FacebookLocales.js
src/FacebookLocales.js
"use strict" import * as Facebook from "../src/Facebook.js" import _ from 'lodash' // Facebook blanket locales. List of countries is generated by common sense. // @see <a href="https://developers.facebook.com/docs/internationalization#locales">Locales and Languages Supported by Facebook</a> let facebookVirtualLocales = { "es_LA": [ // Spanish (Latin America)... overriding the non-exitent Spanish (Laos) "es_AR", // Argentina "es_PE", // Peru "es_EC", // Ecuador, "es_GT", // Guatemala "es_CU", // Cuba "es_BO", // Bolivia "es_DO", // Dominican Republic "es_HN", // Honduras "es_PY", // Paraguay "es_SV", // El Salvador "es_NI", // Nicaragua "es_CR", // Costa Rica "es_PR", // Puerto Rico "es_PA", // Panama "es_UY", // Uruguay "es_GQ" // Equatorial Guinea ], "ar_AR": [ // Arabic... overriding the non-existent Arabic (Argentina) "ar_DZ", // Algeria "ar_BH", // Bahrain "ar_TD", // Chad "ar_KM", // Comoros "ar_DJ", // Djibouti "ar_EG", // Egypt "ar_ER", // Eritrea "ar_GM", // The Gambia "ar_IQ", // Iraq "ar_IL", // Israel "ar_JO", // Jordan "ar_KW", // Kuwait "ar_LB", // Lebanon "ar_LY", // Libya "ar_MR", // Mauritania "ar_MA", // Morocco "ar_OM", // Oman "ar_PS", // State of Palestine "ar_QA", // Qatar "ar_SA", // Saudi Arabia "ar_SO", // Somalia "ar_SD", // Sudan "ar_SY", // Syria "ar_TN", // Tunisia "ar_AE", // United Arab Emirates "ar_YE" // Yemen ] } // Inverse facebookVirtualLocales (map real locales to Facebook virtual locales) let localesToNonStandardFacebookLocales = _(facebookVirtualLocales) .map((locales, facebookNonStandardLocale) => { return _.map(locales, (locale) => { return [locale, facebookNonStandardLocale]}) }) .flatten() .zipObject() .value() export function bestFacebookLocaleFor(locale) { // Standard supported locales if (_.includes(Facebook.supportedLocales, locale)) { return locale } // Locales that are supported in a non-standard way let nonStandardFacebookLocale = localesToNonStandardFacebookLocales[locale] if (nonStandardFacebookLocale) { return nonStandardFacebookLocale } // Unsupported locale, make an effort and return some supported locale with same langauge let language = locale.substring(0, 2) let supportedLocaleInLanguage = _.find(_.toArray(Facebook.supportedLocales), (supportedLocale) => { return _.startsWith(supportedLocale, language) }) if (supportedLocaleInLanguage) { return supportedLocaleInLanguage } // Fallback to English (United States) return "en_US" }
JavaScript
0
@@ -114,40 +114,32 @@ ales -. List of countries is generated +, mapped to real locales by
db76dac37ebeb7cd7e349cf7bd1c9dc2b2fb9291
remove chars
lib/base.js
lib/base.js
module.exports = Base function Base() {} Base.prototype._getAll = function (mw) { return mw.stack.map(function (fn) { return fn.$of }) } Base.prototype._disableAll = function (mw) { mw.stack.forEach(function (fn) { fn.$of.disable() }) return this } Base.prototype._remove = function (mw, name) { var item = this._searchInStack(mw, name) if (item) { mw.remove(item) return true } return false } Base.prototype._callMethod = function (mw, action, name) { var item = this._searchInStack(mw, name) if (item) { return item.$of[action]() } return false } Base.prototype._getDirective = function (mw, name) { var item = this._searchInStack(mw, name) if (item) { return item.$of || item } return null } Base.prototype._searchInStack = function (mw, name) { var stack = mw.stack for (var i = 0, l = stack.length; i < l; i += 1) { var node = stack[i] if (node.$name === name || node.$of === name || node.name === name || node === name) { return node } } return false }
JavaScript
0.000008
@@ -723,17 +723,17 @@ item.$of -%C2%A0 + %7C%7C item%0A @@ -961,17 +961,16 @@ me%0A - %7C%7C node. @@ -1004,9 +1004,9 @@ ame) -%C2%A0 + %7B%0A
679cebec7b720ab5368b618495b96d3022d95680
Fix an error on admin UI due to improper variable handling
solr/webapp/web/js/angular/controllers/index.js
solr/webapp/web/js/angular/controllers/index.js
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ solrAdminApp.controller('IndexController', function($scope, System, Cores, Constants) { $scope.resetMenu("index", Constants.IS_ROOT_PAGE); $scope.reload = function() { System.get(function(data) { $scope.system = data; if (username in data.security) { // Needed for Kerberos, since this is the only place from where // Kerberos username can be obtained. sessionStorage.setItem("auth.username", data.security.username); } // load average, unless its negative (means n/a on windows, etc) if (data.system.systemLoadAverage >= 0) { $scope.load_average = data.system.systemLoadAverage.toFixed(2); } // physical memory var memoryMax = parse_memory_value(data.system.totalPhysicalMemorySize); $scope.memoryTotal = parse_memory_value(data.system.totalPhysicalMemorySize - data.system.freePhysicalMemorySize); $scope.memoryPercentage = ($scope.memoryTotal / memoryMax * 100).toFixed(1)+ "%"; $scope.memoryMax = pretty_print_bytes(memoryMax); $scope.memoryTotalDisplay = pretty_print_bytes($scope.memoryTotal); // swap space var swapMax = parse_memory_value(data.system.totalSwapSpaceSize); $scope.swapTotal = parse_memory_value(data.system.totalSwapSpaceSize - data.system.freeSwapSpaceSize); $scope.swapPercentage = ($scope.swapTotal / swapMax * 100).toFixed(1)+ "%"; $scope.swapMax = pretty_print_bytes(swapMax); $scope.swapTotalDisplay = pretty_print_bytes($scope.swapTotal); // file handles $scope.fileDescriptorPercentage = (data.system.openFileDescriptorCount / data.system.maxFileDescriptorCount *100).toFixed(1) + "%"; // java memory var javaMemoryMax = parse_memory_value(data.jvm.memory.raw.max || data.jvm.memory.max); $scope.javaMemoryTotal = parse_memory_value(data.jvm.memory.raw.total || data.jvm.memory.total); $scope.javaMemoryUsed = parse_memory_value(data.jvm.memory.raw.used || data.jvm.memory.used); $scope.javaMemoryTotalPercentage = ($scope.javaMemoryTotal / javaMemoryMax *100).toFixed(1) + "%"; $scope.javaMemoryUsedPercentage = ($scope.javaMemoryUsed / $scope.javaMemoryTotal *100).toFixed(1) + "%"; $scope.javaMemoryPercentage = ($scope.javaMemoryUsed / javaMemoryMax * 100).toFixed(1) + "%"; $scope.javaMemoryTotalDisplay = pretty_print_bytes($scope.javaMemoryTotal); $scope.javaMemoryUsedDisplay = pretty_print_bytes($scope.javaMemoryUsed); // @todo These should really be an AngularJS Filter: {{ javaMemoryUsed | bytes }} $scope.javaMemoryMax = pretty_print_bytes(javaMemoryMax); // no info bar: $scope.noInfo = !( data.system.totalPhysicalMemorySize && data.system.freePhysicalMemorySize && data.system.totalSwapSpaceSize && data.system.freeSwapSpaceSize && data.system.openFileDescriptorCount && data.system.maxFileDescriptorCount); // command line args: $scope.commandLineArgs = data.jvm.jmx.commandLineArgs.sort(); }); }; $scope.reload(); }); var parse_memory_value = function( value ) { if( value !== Number( value ) ) { var units = 'BKMGTPEZY'; var match = value.match( /^(\d+([,\.]\d+)?) (\w).*$/ ); var value = parseFloat( match[1] ) * Math.pow( 1024, units.indexOf( match[3].toUpperCase() ) ); } return value; }; var pretty_print_bytes = function(byte_value) { var unit = null; byte_value /= 1024; byte_value /= 1024; unit = 'MB'; if( 1024 <= byte_value ) { byte_value /= 1024; unit = 'GB'; } return byte_value.toFixed( 2 ) + ' ' + unit; };
JavaScript
0
@@ -994,24 +994,25 @@ if ( +%22 username in data @@ -1003,16 +1003,17 @@ username +%22 in data
139998a09acff48252000ca319150c3d0670371f
migrate vendor module
modules/vendor/index.js
modules/vendor/index.js
const fs = require('fs-extra') const path = require('path') const path = require('path') module.exports = function nuxtAxios(options) { // Register plugin this.addPlugin({src: path.resolve(__dirname, 'plugin.js'), options}) } module.exports.meta = require('./package.json') module.exports = (nuxt) => { if (!nuxt.vendor) { return } const vendorDir = path.resolve(nuxt.rootDir, 'static', 'vendor') const nodeModulesDir = path.resolve(nuxt.rootDir, 'node_modules') // Ensure static/vendor directory exists fs.ensureDirSync(vendorDir) // Link vendors nuxt.vendor.forEach(vendor => { const src = path.resolve(nodeModulesDir, vendor) const dst = path.resolve(vendorDir, vendor) /* eslint-disable no-console */ console.log('[vendor]', src, '->', dst) fs.ensureSymlinkSync(src, dst, 'junction') }) } module.exports.meta = { name: 'nuxt-vendor' }
JavaScript
0.000002
@@ -58,38 +58,8 @@ ')%0A%0A -const path = require('path')%0A%0A modu @@ -107,192 +107,25 @@ %7B%0A -// Register plugin%0A this.addPlugin(%7Bsrc: path.resolve(__dirname, 'plugin.js'), options%7D)%0A%0A%7D%0A%0Amodule.exports.meta = require('./package.json')%0A%0A%0Amodule.exports = (nuxt) =%3E %7B%0A if (!nuxt +if (!this.options .ven @@ -172,36 +172,44 @@ = path.resolve( -nuxt +this.options .rootDir, 'stati @@ -260,20 +260,28 @@ resolve( -nuxt +this.options .rootDir @@ -299,18 +299,16 @@ ules')%0A%0A - // Ens @@ -373,18 +373,16 @@ orDir)%0A%0A - // Lin @@ -393,20 +393,28 @@ ndors%0A -nuxt +this.options .vendor. @@ -696,30 +696,30 @@ a = -%7B%0A name: 'nuxt-vendor'%0A%7D +require('./package.json') %0A
94c101296ff5920179664558300271be645871ac
change mobile controller to use a mobile service
src/js/helper/mobile.js
src/js/helper/mobile.js
angular.module('n52.core.mobile', []) .controller('IsMobileCtrl', ['$scope', function ($scope) { var check = false; (function (a) { if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true; })(navigator.userAgent || navigator.vendor || window.opera); $scope.isMobile = check; }]);
JavaScript
0
@@ -78,16 +78,175 @@ scope', +'isMobile',%0A function ($scope, isMobile) %7B%0A $scope.isMobile = isMobile();%0A %7D%5D)%0A .constant('isMobile', %0A function @@ -247,22 +247,16 @@ nction ( -$scope ) %7B%0A @@ -2423,33 +2423,22 @@ -$scope.isMobile = +return check;%0A @@ -2450,11 +2450,10 @@ %7D -%5D );
12c75f5b0b686cf1bd4739163eeb8b01b3731fb9
bump distribution for dist/snuggsi.min.es.js
dist/snuggsi.min.es.js
dist/snuggsi.min.es.js
const HTMLLinkElement=function(e){const t={},n=document.querySelector("link#"+e+"[rel=import], link[href*="+e+"][rel=import]"),s=(e,t)=>HTMLImports&&!HTMLImports.useNative?HTMLImports.whenReady(e=>t({target:n})):n.addEventListener(e,t);return Object.defineProperties(t,{addEventListener:{writable:!1,value:function(e,o){n?s(e,o):o({target:t})}}}),t};class TokenList{constructor(e){this.sift(e).map(this.tokenize,this)}tokenize(e){const t=e=>t=>(this[t]=this[t]||[]).push(e);(e.text=e.textContent).match(/([^{]*?)(\w|#)(?=\})/g).map(t(e))}sift(e){const t=[],n=/{(\w+|#)}/,s=e=>e.nodeType===Node.TEXT_NODE?o(e):r(e.attributes)&&NodeFilter.FILTER_REJECT,o=e=>n.test(e.textContent)&&t.push(e),r=e=>Array.from(e).map(e=>n.test(e.value)&&t.push(e)),i=document.createNodeIterator(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,s);for(;i.nextNode(););return t}bind(e){const t=e=>this[e].map(t=>(t.textContent=t.text)&&e),n=(t,n="{"+t+"}")=>s=>s.textContent=s.textContent.replace(n,e[t]);Object.keys(this).map(t);for(let e in this)this[e].map(n(e))}}const HTMLTemplateElement=Template=function(e){return Object.assign(document.querySelector("template[name="+e+"]"),{bind:function(e){contexts=[].concat(...[e]);let t,n=this.cloneNode(!1);return n.innerHTML=contexts.map(e=>e).map((e,n)=>(e="object"==typeof e?e:{self:e},e["#"]=n,t=this.cloneNode(!0),new TokenList(t.content).bind(e),t.innerHTML)).join(""),(this.dependents||[]).map(e=>e.remove()),this.dependents=Array.from(n.content.childNodes),this.after(n.content),this}})},EventTarget=e=>class extends e{on(e,t){this.addEventListener(e,this.renderable(t))}renderable(e){return(t,n=!0)=>(t.prevent=(e=>(n=!1)&&t.preventDefault()))&&!1!==e.call(this,t)&&n&&this.render()}},ParentNode=e=>class extends e{selectAll(e){return this.querySelectorAll(e)}select(e){return this.selectAll(e)[0]}},GlobalEventHandlers=e=>class extends e{onconnect(e,t){(t=e.target.import)&&this.parse(t.querySelector("template")),super.onconnect&&super.onconnect(),this.render()}introspect(e,t){(t=(e.match(/^on(.+)$/)||[])[1])&&Object.keys(HTMLElement.prototype).includes(e)&&this.on(t,this[e])}reflect(e){const t=(t,n)=>(n=/{\s*(\w+)\s*}/.exec(e[t]))&&(n=this[(n||[])[1]])&&(e[t]=this.renderable(n));Array.from(e.attributes).map(e=>e.name).filter(e=>/^on/.test(e)).map(t)}},Component=e=>class extends(EventTarget(ParentNode(GlobalEventHandlers(e)))){constructor(t){super();let n=Object.getOwnPropertyDescriptors(e.prototype),s=e=>!["constructor","initialize"].includes(e)&&"function"==typeof n[e].value&&(this[e]=this[e].bind(this));Object.keys(n).map(s),Object.getOwnPropertyNames(e.prototype).map(this.introspect,this),this.context=this.context||{},this.tokens=new TokenList(this),this.initialize&&this.initialize()}connectedCallback(){HTMLLinkElement(this.tagName.toLowerCase()).addEventListener("load",this.onconnect.bind(this))}render(){this.tokens.bind(this),Array.from(this.selectAll("template[name]")).map(e=>e.getAttribute("name")).map(e=>new Template(e).bind(this[e])),Array.from(this.selectAll("*")).concat([this]).map(this.reflect,this),super.onidle&&super.onidle()}parse(e,t){e=e.cloneNode(!0),t=((t,n,s)=>(n=t.getAttribute("slot"))&&(s=e.content.querySelector("slot[name="+n+"]")).parentNode.replaceChild(t,s));for(let e of this.selectAll("[slot]"))t(e);Array.from(e.attributes).map(e=>this.setAttribute(e.name,e.value)),this.innerHTML=e.innerHTML}},ElementPrototype=window.Element.prototype,Element=(e,t=window.customElements)=>n=>t.define(...e,Component(n));Element.prototype=ElementPrototype;
JavaScript
0
@@ -314,17 +314,17 @@ n(e, -o +r )%7Bn?s(e, o):o @@ -323,12 +323,12 @@ s(e, -o):o +r):r (%7Bta @@ -601,14 +601,14 @@ ODE? -o +r (e): -r +o (e.a @@ -644,17 +644,17 @@ _REJECT, -o +r =e=%3En.te @@ -682,17 +682,17 @@ push(e), -r +o =e=%3EArra @@ -3428,20 +3428,14 @@ ent= -(e,t=window. +e=%3Et=%3E cust @@ -3448,15 +3448,8 @@ ents -)=%3En=%3Et .def @@ -3467,17 +3467,17 @@ mponent( -n +t ));Eleme
411675e4cc68d4510dc0fc208df035cef6fc452f
Fix mistake in title of rate control
source/js/components/rate-control.js
source/js/components/rate-control.js
'use strict'; /** * @file rate-control.js * * Rate control */ import $ from 'jquery'; import Control from './control'; import ControlText from './control-text'; import Cookie from '../utils/cookie'; /** * @param {Player} player Main player * @class RateControl */ class RateControl extends Control { constructor (player, options={}) { options = $.extend({}, { className : 'control-container' }, options); super(player, options); let video = this.player.video; this.downControl.element.on('click', e => { video.rate -= this.player.options.rate.step; }) this.upControl.element.on('click', e => { video.rate += this.player.options.rate.step; }); } createElement() { super.createElement(); this.downControl = new Control(this.player, { className : 'rate-down', iconName : 'backward', title : 'Уменьшить скорость проигрывания' }); this.upControl = new Control(this.player, { className : 'rate-up', iconName : 'forward', title : 'Увеличить скоросить проигрывания' }); this.currentRate = new ControlText({ className : 'rate-current'}); this.element .append(this.downControl.element) .append(this.currentRate.element) .append(this.upControl.element); } buildCSSClass() { return this.options.className; } set value (value) { let video = this.player.video; let options = this.player.options; if (this.disabled) { return false; } this.upControl.element.removeClass('disabled'); this.downControl.element.removeClass('disabled'); if (video.rate <= options.rate.min) this.downControl.element.addClass('disabled'); else if (video.rate >= options.rate.max) this.upControl.element.addClass('disabled'); this.show(); } disable() { this.disabled = true; this.downControl.disable.apply(this.down, arguments); this.upControl.disable.apply(this.up, arguments); } init () { let rate = Cookie.get('rate', this.player.options.rate.default); this.show(rate); } show (value) { let video = this.player.video; value = value || video.rate; value = parseFloat(value) .toFixed(2) .toString() .replace(/,/g, '.'); this.currentRate.text = '×' + value; } } export default RateControl;
JavaScript
0.091741
@@ -998,17 +998,16 @@ %D1%8C %D1%81%D0%BA%D0%BE%D1%80%D0%BE%D1%81 -%D0%B8 %D1%82%D1%8C %D0%BF%D1%80%D0%BE%D0%B8%D0%B3
54f320c1227423a7000de6c2668e3b7d300cd6cc
set inital state
src/components/Rankinglist/Rankinglist.js
src/components/Rankinglist/Rankinglist.js
import React from 'react'; import styles from './Rankinglist.less'; import withStyles from '../../decorators/withStyles'; import CircleSpinner from '../CircleSpinner/CircleSpinner'; @withStyles(styles) class Rankinglist extends React.Component { constructor() { super(); } render() { const playersList = this.state.ranking.map((player) => { return ( <a href="#" className="list-group-item">{player.place} {player.name} {player.points}</a> ); }); return ( <section className="rankinglist"> <h3 className="header-rankinglist">Ranking Herrer, 2015 </h3> <button className="btn btn-default dropdown-toggle" id="rankinglistDropdown" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> <span className="caret"></span> </button> <CircleSpinner /> <ul className="dropdown-menu" aria-labelledby="rankinglistDropdown"> <li><a href="#">Kvinner, 2015</a></li> <li><a href="#" className="disabled">Herrer, 2014</a></li> <li><a href="#" className="disabled">Kvinner, 2014</a></li> </ul> <div className="list-group"> {{playersList}} </div> </section> ); } } export default Rankinglist;
JavaScript
0.000002
@@ -272,16 +272,435 @@ uper();%0A + this.state = %7B%0A ranking: %5B%7B%0A place: 1,%0A name: 'Sindre %C3%98ye Svendby',%0A points: 237%0A %7D,%0A %7B%0A place: 2,%0A name: 'H%C3%A5kon Tveitan',%0A points: 236%0A %7D,%0A %7B%0A place: 2,%0A name: 'Stian Hagen',%0A points: 230%0A %7D,%0A %7B%0A place: 4,%0A name: 'Johan Wathne',%0A points: 142%0A %7D%0A %5D%0A %7D;%0A %7D%0A%0A r
15c4dd56990130d3e753c705d6d035d1e8167f86
Update dynamic-simple-topedge-hints.js (#741)
showcase/axes/dynamic-simple-topedge-hints.js
showcase/axes/dynamic-simple-topedge-hints.js
// Copyright (c) 2016 - 2017 Uber Technologies, Inc. // // 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. import React from 'react'; import { XYPlot, XAxis, YAxis, VerticalGridLines, HorizontalGridLines, LineSeries, MarkSeries, Hint } from 'index'; const CHART_MARGINS = {left: 50, right: 10, top: 10, bottom: 25}; const DATA = [ {x: 1, y: 5}, {x: 2, y: 10}, {x: 3, y: 10}, {x: 4, y: 15} ]; const YMAX = 15; export default class Example extends React.Component { constructor(props) { super(props); this.state = { value: null }; this._rememberValue = this._rememberValue.bind(this); } _rememberValue(value) { this.setState({value}); } render() { const {value} = this.state; return ( <XYPlot width={300} height={300} margin={CHART_MARGINS}> <VerticalGridLines /> <HorizontalGridLines /> <XAxis /> <YAxis /> <MarkSeries onNearestX={ this._rememberValue} data={DATA}/> {value ? <LineSeries data={[{x: value.x, y: value.y}, {x: value.x, y: YMAX}]} stroke="black" /> : null } {value ? <Hint value={value} align={ {horizontal: Hint.AUTO, vertical: Hint.ALIGN.TOP_EDGE} } > <div className="rv-hint__content"> { `(${value.x}, ${value.y})` } </div> </Hint> : null } </XYPlot> ); } }
JavaScript
0
@@ -2306,16 +2306,22 @@ l: Hint. +ALIGN. AUTO, ve
2178ed2b83bdd46bb5a5e7e595735842c6b783e9
Tweak a couple test things
test/features/plugins.js
test/features/plugins.js
import test from 'ava'; import mix from '../../src/index'; import WebpackConfig from '../../src/builder/WebpackConfig'; import sinon from 'sinon'; test('mix can be extended with new functionality as a callback', t => { let registration = sinon.spy(); mix.extend('foobar', registration); let config = new WebpackConfig().build(); mix.foobar(); t.true(registration.called); }); test('mix can be extended with new functionality as a class', t => { mix.extend( 'foobar', new class { register(val) { t.is('baz', val); } }() ); let config = new WebpackConfig().build(); mix.foobar('baz'); }); test('dependencies can be requested for download', t => { let Verify = require('../../src/Verify'); Verify.dependency = sinon.spy(); mix.extend( 'foobar', new class { dependencies() { return ['some-package']; t.pass(); } register() {} }() ); let config = new WebpackConfig().build(); mix.foobar('baz'); Mix.dispatch('init'); t.true(Verify.dependency.calledWith('some-package')); }); test('webpack rules can be added', t => { let rule = { test: /\.ext/, loaders: ['stub'] }; mix.extend( 'foobar', new class { register() {} webpackRules() { return rule; } }() ); mix.foobar(); let config = new WebpackConfig().build(); t.deepEqual(rule, config.module.rules.pop()); }); test('webpack plugins can be added', t => { let plugin = sinon.stub(); mix.extend( 'foobar', new class { register() {} webpackPlugins() { return plugin; } }() ); mix.foobar(); let config = new WebpackConfig().build(); t.is(plugin, config.plugins.pop()); });
JavaScript
0
@@ -295,55 +295,8 @@ );%0A%0A - let config = new WebpackConfig().build();%0A%0A @@ -571,55 +571,8 @@ );%0A%0A - let config = new WebpackConfig().build();%0A%0A @@ -846,20 +846,19 @@ eturn %5B' -some +npm -package @@ -864,35 +864,8 @@ e'%5D; -%0A%0A t.pass(); %0A @@ -926,55 +926,8 @@ );%0A%0A - let config = new WebpackConfig().build();%0A%0A @@ -937,21 +937,16 @@ .foobar( -'baz' );%0A%0A @@ -1013,12 +1013,11 @@ th(' -some +npm -pac @@ -1050,19 +1050,19 @@ k rules -can +may be adde @@ -1088,16 +1088,24 @@ rule = %7B +%0A test: / @@ -1111,16 +1111,24 @@ /%5C.ext/, +%0A loaders @@ -1135,14 +1135,28 @@ : %5B' -stub'%5D +example-loader'%5D%0A %7D;%0A @@ -1415,14 +1415,8 @@ ual( -rule, conf @@ -1432,24 +1432,30 @@ .rules.pop() +, rule );%0A%7D);%0A%0Atest @@ -1472,19 +1472,19 @@ plugins -can +may be adde
79b56b4c6a86c450681d1866c6b78515d16ff926
Update it for JQuery 3.x the selector issue
jquery.scrolling.js
jquery.scrolling.js
/* * jquery.scrollIntoView * * Version: 0.1.20150317 * * Copyright (c) 2015 Darkseal/Ryadel * based on the work of Andrey Sidorov * licensed under MIT license. * * Project Home Page: * http://darkseal.github.io/jquery.scrolling/ * * GitHub repository: * https://github.com/darkseal/jquery.scrolling/ * * Project Home Page on Ryadel.com: * http://www.ryadel.com/ * */ (function ($) { var selectors = []; var checkBound = false; var checkLock = false; var extraOffsetTop = 0; var extraOffsetLeft = 0; var optionsAttribute = 'scrolling-options'; var defaults = { interval: 250, checkScrolling: false, // set it to "true" to perform an element "scroll-in" check immediately after startup offsetTop: 0, offsetLeft: 0, offsetTopAttribute: 'offset-top', offsetLeftAttribute: 'offset-left', window: null // set a custom window object or leave it null to use current window. // pass "top" to use the topmost frame. } var $window; var $wasInView; function process() { checkLock = false; for (var index in selectors) { var $inView = $(selectors.join(", ")).filter(function() { return $(this).is(':scrollin'); }); } $inView.trigger('scrollin', [$inView]); if ($wasInView) { var $notInView = $wasInView.not($inView); $notInView.trigger('scrollout', [$notInView]); } $wasInView = $inView; } // "scrollin" custom filter $.expr[':']['scrollin'] = function(element) { var $element = $(element); if (!$element.is(':visible')) { return false; } var opts = $element.data(optionsAttribute); var windowTop = $window.scrollTop(); var windowLeft = $window.scrollLeft(); var offset = $element.offset(); var top = offset.top + extraOffsetTop; var left = offset.left + extraOffsetLeft; if (top + $element.height() >= windowTop && top - ($element.data(opts.offsetTopAttribute) || opts.offsetTop) <= windowTop + $window.height() && left + $element.width() >= windowLeft && left - ($element.data(opts.offsetLeftAttribute) || opts.offsetLeft) <= windowLeft + $window.width()) { return true; } else { return false; } } $.fn.extend({ // watching for element's presence in browser viewport scrolling: function(options) { var opts = $.extend({}, defaults, options || {}); var selector = this.selector || this; if (!checkBound) { checkBound = true; var onCheck = function() { if (checkLock) { return; } checkLock = true; setTimeout(process, opts.interval); }; $window = $(opts.window || window); if ($window.get(0) != top) { var $b = $($window.get(0).document.body); if ($b) { extraOffsetTop = $b.scrollTop(); extraOffsetLeft = $b.scrollLeft(); } } $window.scroll(onCheck).resize(onCheck); } var $el = $(selector); $el.data(optionsAttribute, opts); if (opts.checkScrolling) { setTimeout(process, opts.interval); } selectors.push(selector); return $el; } }); $.extend({ // force "scroll-in" check for the given element checkScrolling: function() { if (checkBound) { process(); return true; }; return false; } }); })(jQuery);
JavaScript
0
@@ -1025,17 +1025,447 @@ InView;%0A + %0A //https://stackoverflow.com/a/46078814%0A //JQuery 3.x didn't send selector %0A //$arsalanshah%0A %0A $.fn._init = $.fn.init%0A $.fn.init = function( selector, context, root ) %7B%0A return (typeof selector === 'string') ? new $.fn._init(selector, context, root).data('selector', selector) : new $.fn._init( selector, context, root );%0A %7D;%0A $.fn.getSelector = function() %7B%0A return $(this).data('selector');%0A %7D; %0A - functi @@ -1970,16 +1970,56 @@ ement);%0A +%09/* make it work with hidden pagination%0A if ( @@ -2068,24 +2068,71 @@ alse;%0A %7D%0A +%09*/%0A%09if (!$element) %7B%0A %09return false;%0A %7D%0A var opts @@ -2167,16 +2167,77 @@ ibute);%0A +%09if (typeof opts === 'undefined') %7B%0A %09return false;%0A %7D%0A var @@ -2989,51 +2989,268 @@ %7D);%0A - var selector = this.selector %7C%7C this; +%09%0A%09 //Jquery %3C 3.0 shows a string as of $(%3Cselector%3E) in 3.x it return JQuery object%0A%09 //so to get a selector as of 2.x %0A%09 //https://stackoverflow.com/a/46078814%0A // var selector = this.selector %7C%7C this;%0A var selector = this.getSelector() %7C%7C this;%0A%09 %0A
17dc2fe95ab3c13ece4856d2d6937388f3beda1a
Rename Base Class
lib/base.js
lib/base.js
/*! Copyright (c) 2016 Mikal Stordal | MIT Licensed */ 'use strict' /** * The base of all connections. * * @private */ class Connection { constructor () { // Add instance properties this.id = undefined this.channel = undefined this._started = false this._options = {} } /** * Sets an option in options. * * @param {String} path * @param {Any} value * @param {Boolean} [overwrite] * @return {self} for chaining * @public */ set (path, value, overwrite) { let keys, key, cur, idx, len, obj, rec, set // Split path into keys keys = path.split('.') // Offset 1 to get parent len = keys.length - 1 // Sets the `value` on `obj` under `key` set = (obj, key) => { // Only if we don't have the key OR `overwrite` is true do we set value. if (obj[key] === undefined || Boolean(overwrite !== undefined ? overwrite : true)) { obj[key] = value } } // If we have a straight path, set `value` under `path`. if (!len) { set(this._options, path) // Return self to be chainable return this } // Set index now (after we ckeched path) idx = 0 // Recuurs until path is reached rec = (obj) => { if (idx >= len) return obj key = keys[idx++] cur = obj[key] if (cur === undefined) { cur = obj[key] = {} } else if (cur === null) { return } return rec(cur) } // Get desired path's end's parent obj = rec(this._options) // Only set value if we finished the recurring search properly if (idx >= len && obj) { set(obj, keys[idx]) } // Return self to be chainable return this } /** * Gets an option from options. * If option is not found, returns `def` or undefined. * * @param {String} path * @param {Any} [def] * @public */ get (path, def) { let keys, key, cur, idx, len, obj, rec // Split path into keys keys = path.split('.') len = keys.length // If we still only have one key, return option for key. if (!(len - 1)) { if (this._options[path] === undefined) { return def } return this._options[path] } // Set index now (after we ckeched path) idx = 0 rec = (obj) => { if (idx >= len) return obj key = keys[idx++] cur = obj[key] if (cur === undefined || cur === null) return return rec(cur) } // Get desired path's end value obj = rec(this._options) // If we didn't finish our search properly, explicly return `def` if (obj === undefined || idx < len) { return def } // Return value return obj } /** * Check if `option` is enabled (truthy). * * @param {String} option * @return {Boolean} enabled * @public */ enabled (option) { return Boolean(this.get(option)) } /** * Check if `option` is disabled. * * @param {String} option * @return {Boolean} disabled * @public */ disabled (option) { return !this.get(option) } /** * Enables `option`. Possible overwrite. * * @param {String} option * @param {Boolean} [overwrite] * @return {self} for chaining * @public */ enable (option, overwrite) { return this.set(option, true, overwrite) } /** * Disables `option`. Possible overwrite. * * @param {String} option * @param {Boolean} [overwrite] * @return {self} for chaining * @public */ disable (option, overwrite) { return this.set(option, false, overwrite) } /** * Sets all keys from `options`. * * @param {Object} options * @param {Boolean} [overwrite] * @returns {Object} options * @public */ options (options, overwrite) { if (!arguments.length) return this._options if (typeof options === 'object') { let keys, idx keys = Object.keys(options) idx = keys.length while (idx--) { this.set(keys[idx], options[keys[idx]], overwrite) } } return this._options } /** * Same as options, but chainable. * * @param {Object} options * @param {Boolean} [overwrite] * @return {self} for chaining * @public */ init (options, overwrite) { this.options(options, overwrite) return this } /** * Starts the work for connection. Will be overwritten. * * @return {Boolean} continue * @public */ start () { if (this._started) return false this._started = true return true } } // Export class module.exports = Connection
JavaScript
0.000001
@@ -101,16 +101,41 @@ ons.%0A *%0A + * @class BaseConnection%0A * @priv @@ -148,16 +148,20 @@ /%0Aclass +Base Connecti @@ -4613,16 +4613,20 @@ ports = +Base Connecti
8ebef2bfcadadffcc9f767e047d1a9143627c1be
fix stats command not working when owner id was invalid
commands/misc/stats.js
commands/misc/stats.js
/** * @file stats command * @author Sankarsan Kampa (a.k.a k3rn31p4nic) * @license GPL-3.0 */ exports.exec = async (Bastion, message) => { let owners = []; for (let userID of Bastion.credentials.ownerId) { let user = await Bastion.fetchUser(userID).catch(() => {}); owners.push(user.tag); } let shardStats = Bastion.shard ? await Bastion.shard.broadcastEval('this.uptime') : 'None'; if (shardStats instanceof Array) { shardStats = shardStats.length === Bastion.shard.count ? 'All shards online' : `Launched ${shardStats.length} / ${Bastion.shard.count} shards`; } let uptime = Bastion.shard ? await Bastion.shard.broadcastEval('this.uptime') : Bastion.uptime; if (uptime instanceof Array) { uptime = uptime.reduce((max, cur) => Math.max(max, cur), -Infinity); } let seconds = uptime / 1000; let days = parseInt(seconds / 86400); seconds = seconds % 86400; let hours = parseInt(seconds / 3600); seconds = seconds % 3600; let minutes = parseInt(seconds / 60); seconds = parseInt(seconds % 60); uptime = `${seconds}s`; if (days) { uptime = `${days}d ${hours}h ${minutes}m ${seconds}s`; } else if (hours) { uptime = `${hours}h ${minutes}m ${seconds}s`; } else if (minutes) { uptime = `${minutes}m ${seconds}s`; } let guilds = Bastion.shard ? await Bastion.shard.broadcastEval('this.guilds.size') : Bastion.guilds.size; if (guilds instanceof Array) { guilds = guilds.reduce((sum, val) => sum + val, 0); } let textChannels = Bastion.shard ? await Bastion.shard.broadcastEval('this.channels.filter(channel => channel.type === \'text\').size') : Bastion.channels.filter(channel => channel.type === 'text').size; if (textChannels instanceof Array) { textChannels = textChannels.reduce((sum, val) => sum + val, 0); } let voiceChannels = Bastion.shard ? await Bastion.shard.broadcastEval('this.channels.filter(channel => channel.type === \'voice\').size') : Bastion.channels.filter(channel => channel.type === 'voice').size; if (voiceChannels instanceof Array) { voiceChannels = voiceChannels.reduce((sum, val) => sum + val, 0); } let rss = Bastion.shard ? await Bastion.shard.broadcastEval('process.memoryUsage().rss') : process.memoryUsage().rss; if (rss instanceof Array) { rss = rss.reduce((sum, val) => sum + val, 0); } let heapUsed = Bastion.shard ? await Bastion.shard.broadcastEval('process.memoryUsage().heapUsed') : process.memoryUsage().heapUsed; if (heapUsed instanceof Array) { heapUsed = heapUsed.reduce((sum, val) => sum + val, 0); } await message.channel.send({ embed: { color: Bastion.colors.BLUE, author: { name: `Bastion ${Bastion.package.version}` }, url: Bastion.package.url, fields: [ { name: 'Author', value: `[${Bastion.package.author}](${Bastion.package.authorUrl})`, inline: true }, { name: 'BOT ID', value: Bastion.credentials.botId, inline: true }, { name: `Owner${Bastion.credentials.ownerId.length > 1 ? 's' : ''}`, value: owners.join('\n'), inline: true }, { name: `Owner ID${Bastion.credentials.ownerId.length > 1 ? 's' : ''}`, value: Bastion.credentials.ownerId.join('\n'), inline: true }, { name: 'Default Prefixes', value: Bastion.configurations.prefix.join(' '), inline: true }, { name: 'Uptime', value: uptime, inline: true }, { name: 'Shards', value: Bastion.shard ? `${Bastion.shard.count} Shards` : 'None', inline: true }, { name: 'Shard Status', value: shardStats, inline: true }, { name: 'Presence', value: `${guilds.toHumanString()} Servers\n` + `${textChannels.toHumanString()} Text Channels\n` + `${voiceChannels.toHumanString()} Voice Channels`, inline: true }, { name: 'Memory', value: `${(rss / 1024 / 1024).toFixed(2)} MB RSS\n` + `${(heapUsed / 1024 / 1024).toFixed(2)} MB Heap`, inline: true } ], thumbnail: { url: Bastion.user.displayAvatarURL }, footer: { text: `${Bastion.shard ? `Shard: ${Bastion.shard.id} • ` : ''}WebSocket PING: ${parseInt(Bastion.ping)}ms` }, timestamp: new Date() } }); }; exports.config = { aliases: [ 'info' ], enabled: true }; exports.help = { name: 'stats', description: 'Shows detailed stats and info of %bastion%.', botPermission: '', userTextPermission: '', userVoicePermission: '', usage: 'stats', example: [] };
JavaScript
0.000132
@@ -275,16 +275,26 @@ %7B%7D);%0A + if (user) owners. @@ -3152,32 +3152,39 @@ wners.join('%5Cn') + %7C%7C '-' ,%0A inli
f223aa83ef10b7db3f703b9f17ed696e268e7410
Clear timeout in NotificationView on hide.
source/Vibrato/views/panels/NotificationView.js
source/Vibrato/views/panels/NotificationView.js
// -------------------------------------------------------------------------- \\ // File: NotificationView.js \\ // Module: View \\ // Requires: Core, Foundation, View.js \\ // Author: Neil Jenkins \\ // License: © 2010–2012 Opera Software ASA. All rights reserved. \\ // -------------------------------------------------------------------------- \\ "use strict"; ( function ( NS, undefined ) { var hiddenLayout = { top: 0 }; var NotificationView = NS.Class({ Extends: NS.View, Mixin: NS.AnimatableView, animateLayerDuration: 200, className: function () { return 'NotificationView' + ( this.get( 'userMayClose' ) ? ' closable' : '' ); }.property( 'userMayClose' ), destroyOnClose: true, isShowing: false, userMayClose: true, precedence: 0, timeout: 0, text: '', html: '', show: function ( notificationsContainer ) { notificationsContainer.insertView( this ); this.set( 'layout', { top: this.get( 'pxHeight' ) }); var timeout = this.get( 'timeout' ); if ( timeout ) { NS.RunLoop.invokeAfterDelay( this.hide, timeout, this ); } return this; }, hide: function () { return this.set( 'layout', hiddenLayout ); }, willAnimate: function () {}, didAnimate: function () { if ( this.get( 'layout' ) === hiddenLayout ) { this.get( 'parentView' ) .removeView( this ) .notificationDidHide( this ); if ( this.get( 'destroyOnClose' ) ) { this.destroy(); } } }, zIndex: 10000, layout: hiddenLayout, draw: function ( layer ) { this.drawNotification( layer ); if ( this.get( 'userMayClose' ) ) { layer.appendChild( NS.Element.create( 'a.close', [ NS.loc( 'Close' ) ]) ); } }, drawNotification: function ( layer ) { var text = this.get( 'text' ), html = this.get( 'html' ); if ( text || html ) { layer.appendChild( NS.Element.create( 'span', { text: text || undefined, html: text ? undefined : html }) ); } }, hideOnClick: function ( event ) { if ( event.target.className === 'close' ) { event.preventDefault(); this.hide(); } }.on( 'click' ) }); var NotificationContainerView = NS.Class({ Extends: NS.View, showing: null, init: function ( options ) { this._waiting = []; NotificationContainerView.parent.init.call( this, options ); }, positioning: 'absolute', layout: { bottom: '100%', left: '50%' }, willShow: function ( notification ) { var showing = this.get( 'showing' ); if ( showing ) { if ( notification !== showing && notification.get( 'precedence' ) >= showing.get( 'precedence' ) ) { this._waiting.push( notification ); this.hide( showing ); } return false; } return true; }, show: function ( notification ) { if ( this.willShow( notification ) ) { this.set( 'showing', notification ); notification.show( this ); } }, hide: function ( notification ) { var showing = this.get( 'showing' ); if ( showing && ( !notification || notification === showing ) ) { showing.hide(); } }, notificationDidHide: function ( notification ) { this.set( 'showing', null ); var nextNotification = this._waiting.pop(); if ( nextNotification ) { this.show( nextNotification ); } } }); NS.NotificationContainerView = NotificationContainerView; NS.NotificationView = NotificationView; }( this.O ) );
JavaScript
0
@@ -1066,16 +1066,35 @@ l: '',%0A%0A + _timer: null,%0A%0A show @@ -1328,32 +1328,62 @@ f ( timeout ) %7B%0A + this._timer =%0A NS.R @@ -1490,32 +1490,149 @@ : function () %7B%0A + if ( this._timer ) %7B%0A NS.RunLoop.cancel( this._timer );%0A this._timer = null;%0A %7D%0A return t @@ -1678,20 +1678,19 @@ %7D,%0A%0A -will +did Animate: @@ -1707,40 +1707,92 @@ () %7B -%7D, %0A -didAnimate: function () %7B + this.increment( 'animating', -1 );%0A if ( !this.get( 'animating' ) && %0A @@ -1788,36 +1788,39 @@ g' ) &&%0A -if ( + this.get( 'layo @@ -2073,24 +2073,42 @@ %7D%0A %7D +.queue( 'render' ) ,%0A%0A zInde
cd57827f754b9b66bf125feb1313440a374d1ef7
Fix WFS service metadata handling
lib/helpers/convertDataset/iso19139/services.js
lib/helpers/convertDataset/iso19139/services.js
const { get, pick, chain } = require('lodash'); const { getAllKeywords, getAllOnLineResources } = require('./'); const { OnlineResource } = require('./onlineResources'); function isWFSService(record) { const title = get(record, 'identificationInfo.citation.title', '').toLowerCase(); const keywordsStr = getAllKeywords(record).join('').toLowerCase(); const serviceType = get(record, 'identificationInfo.serviceType', '').toLowerCase(); return serviceType === 'download' || serviceType.includes('wfs') || title.includes('wfs') || keywordsStr.includes('wfs') || keywordsStr.includes('infofeatureaccessservice'); } function getWFSServiceLocation(record) { const onlineResources = getAllOnLineResources(record); const candidateResources = chain(onlineResources) .map(resource => { try { resource = new OnlineResource(resource); } catch (err) { return; } const hasWfsInLocation = resource.sourceLocation && resource.sourceLocation.toLowerCase().includes('wfs'); const hasWfsInProtocol = resource.sourceProtocol && resource.sourceProtocol.toLowerCase().includes('wfs'); if (hasWfsInLocation || hasWfsInProtocol) { return resource; } }) .compact() .value(); if (candidateResources.length === 0) { return; } else if (candidateResources.length > 1) { return; } return candidateResources[0].getNormalizedWfsServiceLocation(); } function getCoupledResources(record) { return get(record, 'identificationInfo.coupledResource', []) .filter(cr => (cr.identifier && cr.scopedName)) .map(cr => pick(cr, 'identifier', 'scopedName')); } module.exports = { isWFSService, getWFSServiceLocation, getCoupledResources, };
JavaScript
0.000004
@@ -736,16 +736,127 @@ (record) +.map(resource =%3E (%7B%0A name: resource.name,%0A href: resource.linkage,%0A protocol: resource.protocol,%0A %7D)) ;%0A%0A con