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
ecff51b1ad40715a121587dd790c443b474ce950
Fix test helpers in ember-cli-qunit 3.0 (#106)
addon/helpers/drag.js
addon/helpers/drag.js
import Ember from 'ember'; const { $ } = Ember; /** Drags elements by an offset specified in pixels. Examples drag( 'mouse', '.some-list li[data-item=uno]', function() { return { dy: 50, dx: 20 }; } ); @method drag @param {'mouse'|'touch'} [mode] event mode @param {String} [itemSelector] selector for the element to drag @param {Function} [offsetFn] function returning the offset by which to drag @param {Object} [callbacks] callbacks that are fired at the different stages of the interaction @return {Promise} */ export function drag(app, mode, itemSelector, offsetFn, callbacks = {}) { let start, move, end, which; const { andThen, findWithAssert, wait } = app.testHelpers; if (mode === 'mouse') { start = 'mousedown'; move = 'mousemove'; end = 'mouseup'; which = 1; } else if (mode === 'touch') { start = 'touchstart'; move = 'touchmove'; end = 'touchend'; } else { throw new Error(`Unsupported mode: '${mode}'`); } andThen(() => { let item = findWithAssert(itemSelector); let itemOffset = item.offset(); let offset = offsetFn(); let targetX = itemOffset.left + offset.dx; let targetY = itemOffset.top + offset.dy; triggerEvent(app, item, start, { pageX: itemOffset.left, pageY: itemOffset.top, which }); if (callbacks.dragstart) { andThen(callbacks.dragstart); } triggerEvent(app, item, move, { pageX: itemOffset.left, pageY: itemOffset.top }); if (callbacks.dragmove) { andThen(callbacks.dragmove); } triggerEvent(app, item, move, { pageX: targetX, pageY: targetY }); triggerEvent(app, item, end, { pageX: targetX, pageY: targetY }); if (callbacks.dragend) { andThen(callbacks.dragend); } }); return wait(); } function triggerEvent(app, el, type, props) { return app.testHelpers.andThen(() => { let event = $.Event(type, props); $(el).trigger(event); }); } export default Ember.Test.registerAsyncHelper('drag', drag);
JavaScript
0.000001
@@ -1189,24 +1189,180 @@ offsetFn();%0A + let itemElement = item.get(0);%0A let rect = itemElement.getBoundingClientRect();%0A let scale = itemElement.clientHeight / (rect.bottom - rect.top);%0A let targ @@ -1394,16 +1394,24 @@ ffset.dx + * scale ;%0A le @@ -1448,16 +1448,24 @@ ffset.dy + * scale ;%0A%0A t
28aa32752b8dff51ecb5a53f15f575f6c5f05808
update TipProvider
src/TipProvider/TipProvider.js
src/TipProvider/TipProvider.js
/** * @file TipProvider component * @author liangxiaojun([email protected]) */ import React, {Component, cloneElement} from 'react'; import PropTypes from 'prop-types'; import {findDOMNode} from 'react-dom'; import Tip from '../Tip'; import Theme from '../Theme'; import Util from '../_vendors/Util'; export default class TipProvider extends Component { static Position = Tip.Position; static Theme = Theme; constructor(props, ...restArgs) { super(props, ...restArgs); this.state = { tipVisible: false }; this.showTip = ::this.showTip; this.hideTip = ::this.hideTip; } showTip() { if (!this.state.tipVisible) { this.setState({ tipVisible: true }); } } hideTip() { this.setState({ tipVisible: false }); } componentDidMount() { this.refs.trigger && (this.triggerEl = findDOMNode(this.refs.trigger)); } render() { const {children, text, onTipRender, ...restProps} = this.props, {tipVisible} = this.state; if (!text) { return children; } return ( <div className="tip-provider"> <div ref="triggerWrapper" className="trigger-wrapper" onMouseEnter={this.showTip}> {cloneElement(children, { ref: 'trigger' })} </div> <Tip {...restProps} triggerEl={this.triggerEl} visible={tipVisible} onRender={onTipRender} onRequestClose={this.hideTip}> {text} </Tip> </div> ); } } TipProvider.propTypes = { /** * The CSS class name of the root element. */ className: PropTypes.string, /** * Override the styles of the root element. */ style: PropTypes.object, /** * This is the DOM element that will be used to set the position of the popover. */ triggerEl: PropTypes.object, /** * If true,the popover is visible. */ visible: PropTypes.bool, /** * If true,the popover will have a triangle on the top of the DOM element. */ hasTriangle: PropTypes.bool, triangle: PropTypes.element, /** * The popover theme.Can be primary,highlight,success,warning,error. */ theme: PropTypes.oneOf(Util.enumerateValue(Theme)), /** * The popover alignment.The value can be Menu.Position.LEFT or Menu.Position.RIGHT. */ position: PropTypes.oneOf(Util.enumerateValue(Tip.Position)), /** * If true, menu will have animation effects. */ isAnimated: PropTypes.bool, shouldPreventContainerScroll: PropTypes.bool, /** * The depth of Paper component. */ depth: PropTypes.number, isTriggerPositionFixed: PropTypes.bool, /** * The function of tip render. */ onTipRender: PropTypes.func, /** * Callback function fired when the popover is requested to be closed. */ onRequestClose: PropTypes.func, /** * Callback function fired when wrapper wheeled. */ onWheel: PropTypes.func, text: PropTypes.any }; TipProvider.defaultProps = { className: '', style: null, theme: Theme.DEFAULT, triggerEl: null, visible: false, hasTriangle: true, triangle: <div className="tip-triangle"></div>, position: Tip.Position.BOTTOM, isAnimated: true, depth: 6, shouldPreventContainerScroll: true, isTriggerPositionFixed: false, text: null };
JavaScript
0
@@ -314,23 +314,8 @@ ';%0A%0A -export default clas @@ -3733,12 +3733,41 @@ xt: null%0A%0A%7D; +%0A%0Aexport default TipProvider;
d3a1abeda45357c4cf32b28e6e63cc269d7d3bda
Change HOME env var to avoid cache
rctest.js
rctest.js
#!/usr/bin/env node // Set the platforms you want to test here. // Have the test device(s) connected when running ./test. var platforms = ['android']; var path = require('path'); var fs = require("fs"); var shelljs = require('shelljs'); var cordova_lib = require('cordova-lib'); var cdv = cordova_lib.cordova.raw; var projectDir = path.join(__dirname, 'CordovaProject'); var specDir = path.join(__dirname, 'cordova-mobile-spec'); var wwwDir = path.join(specDir, 'www'); // Config for cordova create. var cfg = { // Use www assets from mobilespec lib: {www: {url: wwwDir}}, // searchpath for unpublished testing plugins. plugin_search_path: [__dirname, specDir] }; // Set handlers to print log messages var events = cordova_lib.events; events.on('log', console.log); events.on('results', console.log); events.on('warn', console.warn); var appId = 'org.apache.cordova.example.rctest'; var appName = 'Cordova RC test'; cdv.create(projectDir, appId, appName, cfg) .then(function() { // Further Cordova commands must be run inside the cordova project dir. process.chdir(projectDir); }) .then(function() { return cdv.platform('add', platforms); }) .then(function() { // Dummy plugin depending on all the needed plugins return cdv.plugins('add', 'org.cordova.mobile-spec-dependencies'); }) .then(function() { // Install new style plugin tests from the nested plugins in a /tests // subdirectories inside plugins. // See https://github.com/apache/cordova-plugin-test-framework var pluginTestPaths = []; shelljs.ls('plugins').forEach(function(plugin) { var plugin_xml = path.join(projectDir, 'plugins', plugin, 'tests', 'plugin.xml'); if (fs.existsSync(plugin_xml)) { pluginTestPaths.push(path.dirname(plugin_xml)); } }); return cdv.plugins('add', pluginTestPaths); }) .then(function() { cdv.run(); }) .done();
JavaScript
0.000001
@@ -230,24 +230,152 @@ shelljs');%0A%0A +// Use fake home dir to avoid using cached versions of plugins and platforms.%0Aprocess.env.HOME = path.join(__dirname, 'home');%0A%0A var cordova_
113c9ffbad4d05523407c1bfe09a7233e0858a6a
Update trackers
torrentz-magnet.user.js
torrentz-magnet.user.js
// ==UserScript== // @name Torrentz magnet // @namespace memmie.lenglet.name // @author mems <[email protected]> // @homepageURL https://github.com/mems/torrentz-magnet // @description Add magnet link to torrentz download page. // @match *://*.torrentz2.eu/* // @match *://*.torrentz.com/* // @match *://*.torrentz.eu/* // @match *://*.torrentz.ch/* // @match *://*.torrentz.ph/* // @match *://*.torrentz.me/* // @match *://*.torrentz.in/* // @match *://*.torrentz.hk/* // @match *://*.torrentz.de/* // @match *://*.tz.ai/* // @match *://*.torrentz-proxy.com/* // @match *://*.torrentsmirror.com/* // @match *://*.torrentzeu.to/* // @updateURL https://openuserjs.org/install/mems/Torrentz_magnet.user.js // @version 1.1.4 // @grant none // ==/UserScript== var list = document.querySelector(".download"); var defaultTrackers = [ "http://pow7.com:80/announce", "udp://tracker.openbittorrent.com/announce", "udp://tracker.internetwarriors.net:1337/announce", "udp://tracker.sktorrent.net:6969/announce", "udp://tracker.opentrackr.org:1337/announce", "udp://tracker.coppersurfer.tk:6969/announce", "udp://tracker.leechers-paradise.org:6969/announce", "udp://zer0day.ch:1337/announce", "udp://explodie.org:6969/announce" ]; if(list){ let name = list.querySelector("h2 span").textContent.trim(); let hash = document.querySelector(".trackers > div, .trackers h2").textContent.trim().split(/:\s+|hash\s+/, 2)[1]; let trackers = Array.from(document.querySelectorAll(".trackers dl a")).map(node => node.textContent.trim()).concat(defaultTrackers); let trackersCmps = trackers.reduce((result, uri) => result + "&tr=" + encodeURIComponent(uri), ""); let uri = `magnet:?xt=urn:btih:${hash}&dn=${encodeURIComponent(name)}${trackersCmps}`; let magnetIcon = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAAZUlEQVQokc2RQQrAMAgE9+g/99/5yvaSWDUV0lMrDATMiIsAoIZVbV9jjEQVu/4HohZmAiCSLs63ZOa0Ivb6nThv9D5jkCNRcpHkJqqsXyGpe5VDMUVZ8uOAnCvl9yKpOCR+rsIFGyA1+Hqs6JoAAAAASUVORK5CYII=";// from https://commons.wikimedia.org/wiki/File:Magnet-icon.gif list.querySelector("dl:first-of-type").insertAdjacentHTML("beforebegin", ` <dl> <dt><a href="${uri}"><span class="${/(^|\.)torrentz2.eu$/.test(location.hostname) ? `j z s197"></span><span class="u"` : `u" style="background: transparent url('${magnetIcon}') no-repeat 5px center; color: red;"`}>Magnet</span> <span class="n">${name}</span></a></dt> <dd>Magnet</dd> </dl> `); }
JavaScript
0
@@ -737,17 +737,17 @@ on%09%091.1. -4 +5 %0A// @gra @@ -823,16 +823,267 @@ load%22);%0A +// Default list of track will be used in addition to trackers provided by torrentz%0A// Lists available (could be used to customize the following list):%0A// https://newtrackon.com/%0A// https://github.com/ngosang/trackerslist/blob/master/trackers_best.txt%0A var defa @@ -1111,19 +1111,24 @@ p:// -pow7.com:80 +tracker.tfile.me /ann @@ -1169,16 +1169,19 @@ rent.com +:80 /announc @@ -1369,32 +1369,66 @@ :6969/announce%22, +// http://tracker.coppersurfer.tk/ %0A%09%22udp://tracker @@ -1478,16 +1478,24 @@ p:// +tracker. zer0day. ch:1 @@ -1490,18 +1490,18 @@ zer0day. -ch +to :1337/an @@ -1512,29 +1512,286 @@ ce%22, -%0A%09%22udp://explodie.org +// http://zer0day.to/%0A%09%22udp://explodie.org:6969/announce%22,%0A%09%22udp://exodus.desync.com:6969/announce%22,%0A%09%22udp://tracker.pirateparty.gr:6969/announce%22,%0A%09%22udp://public.popcorn-tracker.org:6969/announce%22,%0A%09%22udp://tracker1.wasabii.com.tw:6969/announce%22,%0A%09%22udp://tracker2.wasabii.com.tw :696
8f2523d0ba24bae87522500f570c7484314236a9
update touch and background image
js/canvas.js
js/canvas.js
height= 270; width= 480; function startGame() { myGameArea.start(); } var myGameArea = { canvas : document.createElement("canvas"), start : function() { this.canvas.width = width; this.canvas.height = height; // this.canvas.style.cursor = "none"; //hide the original cursor this.context = this.canvas.getContext("2d"); document.body.insertBefore(this.canvas, document.body.childNodes[0]); this.frameNo = 0; this.interval = setInterval(updateGameArea, 20); window.addEventListener('keydown', function (e) { myGameArea.keys = (myGameArea.keys || []); myGameArea.keys[e.keyCode] = true; myGamePiece.image.src = "images/bird3.png"; accelerate(-0.25); }) window.addEventListener('keyup', function (e) { myGameArea.keys[e.keyCode] = false; myGamePiece.image.src = "images/bird2.png"; accelerate(0.05); }) }, clear : function() { this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); }, stop : function() { clearInterval(this.interval); mySound.stop(); mySound = new sound("death","sounds/die.mp3"); mySound.play(); } } function sound(val,src) { this.sound = document.createElement("audio"); this.sound.src = src; this.sound.setAttribute("preload", "auto"); if(val=="background"){ this.sound.setAttribute("loop", "loop"); } this.sound.setAttribute("controls", "none"); this.sound.style.display = "none"; document.body.appendChild(this.sound); this.play = function(){ this.sound.play(); } this.stop = function(){ this.sound.pause(); } }
JavaScript
0
@@ -72,18 +72,16 @@ ();%0D%0A%7D%0D%0A -%0D%0A var myGa @@ -528,24 +528,262 @@ Area, 20);%0D%0A + window.addEventListener('mousemove', function (e) %7B%0D%0A myGameArea.x = e.pageX;%0D%0A myGameArea.y = e.pageY;%0D%0A myGamePiece.image.src = %22images/bird3.png%22;%0D%0A // accelerate(-0.25);%0D%0A %7D)%0D%0A wind
9fb65748ab142949e7a06c70e5ff4745bd9fa303
Update status.js
js/status.js
js/status.js
// https://mcapi.ca/query/play.strongcraft.org/extensive ServerStatus('ilovebigdick.iceswag.com:36503');
JavaScript
0.000002
@@ -97,12 +97,13 @@ com: -36503 +64712 '); +%0A
0e0815f03b7dcd231673df1b2812bb42c8cc98b9
Set select value after init
client/app/components/ui-dropdown.js
client/app/components/ui-dropdown.js
import Ember from "ember"; export default Ember.Component.extend({ tagName: 'div', classNames: ['ui', 'selection', 'dropdown', 'fluid'], classNameBindings: ['multiple', 'search'], content: null, optionValuePath: null, optionLabelPath: null, allowAdditions: null, bindAttributes: ['optionValuePath', 'optionLabelPath', 'content', 'allowAdditions'], actions: {}, options: function () { var optionLabelPath = this.get('optionLabelPath'); var optionValuePath = this.get('optionValuePath'); var selectContent = this.get('content'); return selectContent ? selectContent.map(function (item, index, list) { return { value: optionValuePath ? item.get(optionValuePath) : item, label: optionLabelPath ? item.get(optionLabelPath) : item }; }, this) : []; }.property('content.@each'), setup: function () { this.$().dropdown({ allowAdditions: this.allowAdditions, onChange: Ember.run.bind(this, this.onChange) }); }.on('didInsertElement'), onChange: function (value, text, $choice) { if (this.optionValuePath) { value = this.get('content').findBy(this.optionValuePath, value); } if (this.get('multiple')) { var currentValue = this.get('value') || Ember.A([]); currentValue.pushObject(value); this.set('value', currentValue); } else { this.set('value', value); } } });
JavaScript
0
@@ -993,16 +993,60 @@ )%0A %7D) +.dropdown('set selected', this.get('value')) ;%0A %7D.on
cbf3875a640ee10a7529ede83b3147675f7f6f42
Test data removed
public/javascripts/app.js
public/javascripts/app.js
(function() { var socket = io.connect(); var SDebugger = angular.module('SDebugger', []); SDebugger.controller('MainCtrl', ['$scope' ,'$element' , function($scope, $element){ $scope.logsData = [{ logName : "Azhar", logs : JSON.stringify({name : "azhar"}) },{ logName : "Azhar", logs : JSON.stringify({name : "azhar"}) }]; socket.on("NEWS", function(data) { $scope.logsData.push(data); $scope.$apply(); }); $scope.subscribe = function(id) { var userName = $scope.sDebuggerId; if(userName) { socket.emit('SUBSCRIBE', { userName : userName }); //Storing userName into local storage window.localStorage.setItem('sDebuggerId', userName); } } $scope.deleteLog = function(index) { $scope.logsData.splice(index, 1) }; $scope.prettifyJSON = function($event) { var $target = $($event.currentTarget).closest('.logsArea'); var jsonText = $target.find("pre").text().trim(); if(jsonText) { jsonText = JSON.parse(jsonText); $target.find("pre").html(JSON.stringify(jsonText, null, 2)); } } $scope.sDebuggerId = window.localStorage.getItem('sDebuggerId') || ""; if($scope.sDebuggerId) { $scope.subscribe(); } }]); })(); $(document).ready(function() { $('[data-toggle="tooltip"]').tooltip(); });
JavaScript
0
@@ -203,151 +203,8 @@ = %5B -%7B%0A%09%09%09logName : %22Azhar%22,%0A%09%09%09logs : JSON.stringify(%7Bname : %22azhar%22%7D)%0A%09%09%7D,%7B%0A%09%09%09logName : %22Azhar%22,%0A%09%09%09logs : JSON.stringify(%7Bname : %22azhar%22%7D)%0A%09%09%7D %5D;%0A%09
58e2dd5ea46c65db1a9ada1fe711a2815231369d
fix path for handlebars template - fixes windows
appsrc/js/podcast-render.js
appsrc/js/podcast-render.js
var fs = require('fs'); var path = require('path'); var handlebars = require('handlebars'); import moment from 'moment'; const escape = { '&': '&#x26;', '<': '&#x3C;', '>': '&#x3E;' }; const badChars = /[&<>]/g; const possible = /[&<>]/; function escapeChar(chr) { return escape[chr]; } function customEscapeExpression(string) { if (typeof string !== 'string') { if (string && string.toHTML) { return string.toHTML(); } else if (string === null) { return ''; } else if (!string) { return String(string); } string = String(string); } if (!possible.test(string)) { return string; } return string.replace(badChars, escapeChar); } handlebars.Utils.escapeExpression = customEscapeExpression; function renderPodcastFile(directory, podcastState, filename) { var hbsPath = './app/podcast-template.hbs'; var hbsTemplate = handlebars.compile(fs.readFileSync(hbsPath, "utf8")); var DATE_RFC2822 = "ddd, DD MMM YYYY HH:mm:ss ZZ"; podcastState.buildDate = moment().format(DATE_RFC2822); var outPath = path.join(directory, filename); fs.writeFile(outPath, hbsTemplate(podcastState), function(err) { if (err !== null) { console.error(err); } }); } function renderLocal(directory, podcastState) { renderPodcastFile(directory, podcastState, '.podcast-local.xml'); } function renderRemote(directory, podcastState, prefixUrl) { if (!prefixUrl.endsWith('/')) { prefixUrl += '/'; } var podcastCopy = Object.assign({}, podcastState); podcastCopy.image = prefixUrl + path.basename(podcastCopy.image); renderPodcastFile(directory, podcastCopy, 'podcast.xml'); } export default function podcastRender(directory, podcastState, prefixUrl) { renderLocal(directory, podcastState); renderRemote(directory, podcastState, prefixUrl); }
JavaScript
0
@@ -830,15 +830,30 @@ h = -'./app/ +path.join(__dirname, ' podc @@ -869,16 +869,17 @@ ate.hbs' +) ;%0A var
8250846d39013dd9cd0bcacf4ddb3284fc3d76e2
hello world 1
js/client.js
js/client.js
/* global TrelloPowerUp */ var WHITE_ICON = './images/icon-white.svg'; var GRAY_ICON = './images/icon-gray.svg'; var parkMap = { acad: 'Acadia National Park', arch: 'Arches National Park', badl: 'Badlands National Park', brca: 'Bryce Canyon National Park', crla: 'Crater Lake National Park', dena: 'Denali National Park', glac: 'Glacier National Park', grca: 'Grand Canyon National Park', grte: 'Grand Teton National Park', olym: 'Olympic National Park', yell: 'Yellowstone National Park', yose: 'Yosemite National Park', zion: 'Zion National Park' }; var getBadges = function(t){ return t.card('name') .get('name') .then(function(cardName){ var badgeColor; var icon = GRAY_ICON; var lowercaseName = cardName.toLowerCase(); if(lowercaseName.indexOf('green') > -1){ badgeColor = 'green'; icon = WHITE_ICON; } else if(lowercaseName.indexOf('yellow') > -1){ badgeColor = 'yellow'; icon = WHITE_ICON; } else if(lowercaseName.indexOf('red') > -1){ badgeColor = 'red'; icon = WHITE_ICON; } if(lowercaseName.indexOf('dynamic') > -1){ // dynamic badges can have their function rerun after a set number // of seconds defined by refresh. Minimum of 10 seconds. return [{ dynamic: function(){ return { title: 'Detail Badge', // for detail badges only text: 'Dynamic ' + (Math.random() * 100).toFixed(0).toString(), icon: icon, // for card front badges only color: badgeColor, refresh: 10 } } }] } if(lowercaseName.indexOf('static') > -1){ // return an array of badge objects return [{ title: 'Detail Badge', // for detail badges only text: 'Static', icon: icon, // for card front badges only color: badgeColor }]; } else { return []; } }) }; var formatNPSUrl = function(t, url){ if(!/^https?:\/\/www\.nps\.gov\/[a-z]{4}\//.test(url)){ return null; } var parkShort = /^https?:\/\/www\.nps\.gov\/([a-z]{4})\//.exec(url)[1]; if(parkShort && parkMap[parkShort]){ return parkMap[parkShort]; } else{ return null; } }; var boardButtonCallback = function(t){ return t.popup({ title: 'Popup List Example', items: [ { text: 'Open Overlay', callback: function(t){ return t.overlay({ url: './overlay.html', args: { rand: (Math.random() * 100).toFixed(0) } }) .then(function(){ return t.closePopup(); }); } }, { text: 'Open Board Bar', callback: function(t){ return t.boardBar({ url: './board-bar.html', height: 200 }) .then(function(){ return t.closePopup(); }); } }, { text: 'Hello', callback: function(t){ return alert("hello world"); } ] }); }; var cardButtonCallback = function(t){ var items = Object.keys(parkMap).map(function(parkCode){ var urlForCode = 'http://www.nps.gov/' + parkCode + '/'; return { text: parkMap[parkCode], url: urlForCode, callback: function(t){ return t.attach({ url: urlForCode, name: parkMap[parkCode] }) .then(function(){ return t.closePopup(); }) } }; }); return t.popup({ title: 'Popup Search Example', items: items, search: { count: 5, placeholder: 'Search National Parks', empty: 'No parks found' } }); }; TrelloPowerUp.initialize({ 'attachment-sections': function(t, options){ // options.entries is a list of the attachments for this card // you can look through them and 'claim' any that you want to // include in your section. // we will just claim urls for Yellowstone var claimed = options.entries.filter(function(attachment){ return attachment.url.indexOf('http://www.nps.gov/yell/') == 0; }); // you can have more than one attachment section on a card // you can group items together into one section, have a section // per attachment, or anything in between. if(claimed && claimed.length > 0){ // if the title for your section requires a network call or other // potentially length operation you can provide a function for the title // that returns the section title. If you do so, provide a unique id for // your section return [{ id: 'Yellowstone', // optional if you aren't using a function for the title claimed: claimed, icon: GRAY_ICON, title: 'Example Attachment Section: Yellowstone', content: { type: 'iframe', url: t.signUrl('./section.html', { arg: 'you can pass your section args here' }), height: 230 } }]; } else { return []; } }, 'attachment-thumbnail': function(t, options){ var parkName = formatNPSUrl(t, options.url); if(parkName){ // return an object with some or all of these properties: // url, title, image, openText, modified (Date), created (Date), createdBy, modifiedBy return { url: options.url, title: parkName, image: { url: './images/nps.svg', logo: true // false if you are using a thumbnail of the content }, openText: 'Open in NPS' }; } else { throw t.NotHandled(); } }, 'board-buttons': function(t, options){ return [{ icon: WHITE_ICON, text: 'Template', callback: boardButtonCallback }]; }, 'card-badges': function(t, options){ return getBadges(t); }, 'card-buttons': function(t, options) { return [{ icon: GRAY_ICON, text: 'Template', callback: cardButtonCallback }]; }, 'card-detail-badges': function(t, options) { return getBadges(t); }, 'card-from-url': function(t, options) { var parkName = formatNPSUrl(t, options.url); if(parkName){ return { name: parkName, desc: 'An awesome park: ' + options.url }; } else { throw t.NotHandled(); } }, 'format-url': function(t, options) { var parkName = formatNPSUrl(t, options.url); if(parkName){ return { icon: GRAY_ICON, text: parkName }; } else { throw t.NotHandled(); } }, 'show-settings': function(t, options){ return t.popup({ title: 'Settings', url: './settings.html', height: 184 }); } });
JavaScript
0.999991
@@ -2998,16 +2998,26 @@ orld%22);%0A + %7D%0A %7D%0A
54fc54fce9b80e6b9d4322cfb8f2f5c9cd30a959
Fix var error in test
test/unit/modules/browser-auto-tracking-spec.js
test/unit/modules/browser-auto-tracking-spec.js
var assert = require('proclaim'); var config = require('../helpers/client-config'); var Keen = require('../../../lib/browser'); describe('Auto Tracking', function() { beforeEach(function() { this.client = new Keen({ projectId: config.projectId, writeKey: config.writeKey, requestType: 'xhr', host: config.host, protocol: config.protocol }); }); it('should capture "pageviews," "clicks," and "form submits"', function(done){ var aNode = document.createElement('A'); var bNode = document.createElement('BUTTON'); var fNode = document.createElement('FORM'); var iNode = document.createElement('INPUT'); var pNode = document.createElement('INPUT'); var inc = 0; this.client.on('recordEvent', function(stream, payload){ if (stream === 'pageviews') { assert.equal(stream, 'pageviews'); inc++; } else if (stream === 'clicks') { assert.equal(stream, 'clicks'); assert.equal(payload.element.id, 'test-auto-tracker-clicks'); assert.equal(payload.element.node_name, 'A'); aNode.outerHTML = ''; inc++; } else if (stream === 'form_submissions') { assert.equal(stream, 'form_submissions'); assert.equal(payload.element.id, 'test-auto-tracker-submits'); assert.equal(payload.element.node_name, 'FORM'); assert.equal(payload.form.fields.email, '[email protected]'); assert.notOk(payload.form.fields.password); fNode.outerHTML = ''; inc++; } if (inc === 3) { done(); } }); this.client.initAutoTracking(); /* Anchor Tag Listener */ aNode.id = 'test-auto-tracker-clicks'; aNode.href = 'javascript:void(0);'; aNode.onclick = function(e){ e.preventDefault(); return false; }; document.body.appendChild(aNode); /* Form Listener */ fNode.id = 'test-auto-tracker-submits'; fNode.action = 'javascript:void(0);'; fNode.onsubmit = function(e) { e.preventDefault(); return false; }; // fNode.style.display = 'none'; iNode.type = 'text'; iNode.name = 'email'; iNode.value = '[email protected]'; pNode.type = 'password'; pNode.name = 'password'; pNode.value = '**********'; bNode.type = 'submit'; fNode.appendChild(iNode); fNode.appendChild(pNode); fNode.appendChild(bNode); document.body.appendChild(fNode); /* Init Behavior */ if (aNode.click) { aNode.click(); bNode.click(); } else if(document.createEvent) { ev = document.createEvent('MouseEvent'); ev.initMouseEvent(click, true /* bubble */, true /* cancelable */, window, null, 0, 0, 0, 0, false, false, false, false, 0, null ); aNode.dispatchEvent(ev); bNode.dispatchEvent(ev); } }); });
JavaScript
0.000002
@@ -2668,21 +2668,23 @@ seEvent( +' click +' ,%0A
856ef4ddbb75aeefc136f9087129b396bfe8d949
Add related check on ready
src/main/web/florence/js/functions/_editRelated.js
src/main/web/florence/js/functions/_editRelated.js
function editRelated (collectionId, data, templateData, field, idField) { var list = templateData[field]; var dataTemplate = createRelatedTemplate(idField, list); var html = templates.editorRelated(dataTemplate); $('#'+ idField).replaceWith(html); initialiseRelated(collectionId, data, templateData, field, idField); } function refreshRelated(collectionId, data, templateData, field, idField) { var list = templateData[field]; var dataTemplate = createRelatedTemplate(idField, list); var html = templates.editorRelated(dataTemplate); $('#sortable-'+ idField).replaceWith($(html).find('#sortable-'+ idField)); initialiseRelated(collectionId, data, templateData, field, idField); } function createRelatedTemplate(idField, list) { var dataTemplate; if (idField === 'article') { dataTemplate = {list: list, idField: idField, idPlural: 'articles'}; } else if (idField === 'bulletin') { dataTemplate = {list: list, idField: idField, idPlural: 'bulletins'}; } else if (idField === 'dataset') { dataTemplate = {list: list, idField: idField, idPlural: 'datasets'}; } else if (idField === 'document') { dataTemplate = {list: list, idField: idField, idPlural: 'documents'}; } else if (idField === 'methodology') { dataTemplate = {list: list, idField: idField, idPlural: 'methodologies'}; } else { dataTemplate = {list: list, idField: idField}; } return dataTemplate; } function initialiseRelated(collectionId, data, templateData, field, idField) { // Load if (!data[field] || data[field].length === 0) { editRelated['lastIndex' + field] = 0; } else { $(data[field]).each(function (index, value) { editRelated['lastIndex' + field] = index + 1; // Delete $('#' + idField + '-delete_' + index).click(function () { var result = confirm("Are you sure you want to delete this link?"); if (result === true) { var position = $(".workspace-edit").scrollTop(); Florence.globalVars.pagePos = position; $(this).parent().remove(); data[field].splice(index, 1); templateData[field].splice(index, 1); postContent(collectionId, data.uri, JSON.stringify(data), success = function (response) { Florence.Editor.isDirty = false; refreshPreview(data.uri); refreshRelated(collectionId, data, templateData, field, idField) }, error = function (response) { if (response.status === 400) { alert("Cannot edit this file. It is already part of another collection."); } else if (response.status === 401) { alert("You are not authorised to update content."); } else { handleApiError(response); } } ); } }); }); } //Add $('#add-' + idField).off().one('click', function () { var latestCheck; var position = $(".workspace-edit").scrollTop(); Florence.globalVars.pagePos = position; var iframeEvent = document.getElementById('iframe').contentWindow; iframeEvent.removeEventListener('click', Florence.Handler, true); createWorkspace(data.uri, collectionId, '', true); $('#sortable-' + idField).append( '<div id="' + editRelated['lastIndex' + field] + '" class="edit-section__sortable-item">' + ' <textarea id="' + idField + '-uri_' + editRelated['lastIndex' + field] + '" placeholder="Go to the related data and click Get"></textarea>' + ' <div id="latest-container"></div>' + ' <button class="btn-page-get" id="' + idField + '-get_' + editRelated['lastIndex' + field] + '">Get</button>' + ' <button class="btn-page-cancel" id="' + idField + '-cancel_' + editRelated['lastIndex' + field] + '">Cancel</button>' + '</div>').trigger('create'); if (idField === 'article' || idField === 'bulletin' || idField === 'document') { $('#latest-container').append('<label for="latest">Latest</label>' + '<input id="latest" type="checkbox" value="value" checked/>'); } $('#' + idField + '-cancel_' + editRelated['lastIndex' + field]).one('click', function () { createWorkspace(data.uri, collectionId, 'edit'); }); $('#latest-container input:checkbox').on('change', function () { latestCheck = $(this).prop('checked'); }); $('#' + idField + '-get_' + editRelated['lastIndex' + field]).one('click', function () { var baseUrl = $('#' + idField + '-uri_'+editRelated['lastIndex' + field]).val(); if (!baseUrl) { baseUrl = getPathNameTrimLast(); } baseUrl = checkPathParsed(baseUrl); var dataUrlData = baseUrl + "/data"; var latestUrl; if (latestCheck) { var tempUrl = baseUrl.split('/'); tempUrl.pop(); tempUrl.push('latest'); latestUrl = tempUrl.join('/'); } else { latestUrl = baseUrl; } $.ajax({ url: dataUrlData, dataType: 'json', crossDomain: true, success: function (result) { if ((field === 'relatedBulletins' || field === 'statsBulletins') && result.type === 'bulletin') { if (!data[field]) { data[field] = []; } } else if (field === 'relatedArticles' && result.type === 'article') { if (!data[field]) { data[field] = []; } } else if ((field === 'relatedDocuments') && (result.type === 'article' || result.type === 'bulletin' || result.type === 'compendium_landing_page')) { if (!data[field]) { data[field] = []; } } else if ((field === 'relatedDatasets' || field === 'datasets') && (result.type === 'dataset' || result.type === 'reference_tables')) { if (!data[field]) { data[field] = []; } } else if ((field === 'items') && (result.type === 'timeseries')) { if (!data[field]) { data[field] = []; } } else if ((field === 'relatedData') && (result.type === 'timeseries' || result.type === 'dataset' || result.type === 'reference_tables')) { if (!data[field]) { data[field] = []; } } else if (field === 'relatedMethodology' && result.type === 'static_methodology') { if (!data[field]) { data[field] = []; } } else { alert("This is not a valid document"); return; } data[field].push({uri: latestUrl}); saveRelated(collectionId, data.uri, data, field, idField); }, error: function () { console.log('No page data returned'); } }); }); }); function sortable() { $('#sortable-' + idField).sortable(); } sortable(); }
JavaScript
0
@@ -4032,16 +4032,24 @@ atest%22%3EL +ink to l atest%3C/l @@ -4341,16 +4341,22 @@ x').on(' +ready change',
8696eb93e9d1ebb2557e4b419108d18f85c7cd73
add price
javascript/practice.js
javascript/practice.js
var array_of_items = {Tissues: "253-07-0129", Scissors: "081-22-0936", Glue: "081-06-1653", Crayons: "081-04-0343", Watercolor_Set: "081-04-0600", Markers: "081-04-1261", Pencils: "081-02-1857", Notebook: "081-01-1751", Erasers: "081-02-1505", Folders: "081-03-0706", Box: "081-06-2910", Soap: "049-00-1118", Bags: "253-01-0291"}; var api_call = function(dpci) { var url = 'http://api.target.com/items/v3/' + array_of_items[key] + '?id_type=dpci&store_id=530&fields=ids,descriptions,locations,pricing,images&mode=online&key=1Kfdqvy6wHmvJ4LDyAVOl7saCBoKHcSb' $(document).ready(function () { $('button').click(function() { $.ajax ({ url: url, consentType: "application/json", dataType: 'jsonp', success: function(data) { // console.log(data); // $("#output-2").html("Item: " + key) // $("#output-2").html("Description: " + data.product_composite_response.items[0].general_description) // $("#output-3").html(data.product_composite_response.items[0].online_price.current_price); var div_a = document.createElement("div"); div_a.innerHTML = key document.getElementById("output-4").appendChild(div_a); var div_b = document.createElement("div"); div_b.innerHTML = "Description: " + data.product_composite_response.items[0].general_description document.getElementById("output-4").appendChild(div_b); var img_tag = new Image(); img_tag.src = data.product_composite_response.items[0].image.internal_primary_image_url; img_tag.setAttribute("class", "thumb-img"); img_tag.setAttribute("alt", "effy"); document.getElementById("output-4").appendChild(img_tag); }, //end success function error: function(e) { console.log(e.message); } //end error function }); // end AJAX }); // end button.click }); // end ready }; // end api-call // ITERATES OVER ARRAY TO CALL API for (var key in array_of_items) { api_call(array_of_items[key]); };
JavaScript
0.000001
@@ -1038,24 +1038,25 @@ nt_price);%0A%0A +%0A var @@ -1059,17 +1059,17 @@ var div_ -a +b = docum @@ -1106,17 +1106,17 @@ div_ -a +b .innerHT @@ -1120,19 +1120,95 @@ rHTML = -key +%22Description: %22 + data.product_composite_response.items%5B0%5D.general_description; %0A @@ -1260,17 +1260,17 @@ ild(div_ -a +b );%0A%0A @@ -1273,33 +1273,33 @@ var div_ -b +a = document.crea @@ -1320,33 +1320,33 @@ %22);%0A div_ -b +a .innerHTML = %22De @@ -1339,35 +1339,29 @@ nnerHTML = %22 -Description +Price : %22 + data.p @@ -1395,35 +1395,43 @@ tems%5B0%5D. -general_description +online_price.current_price; %0A @@ -1475,37 +1475,38 @@ appendChild(div_ -b +a );%0A%0A +%0A var img_
405807e60dbaf8cef52395645161d0c4f74861f9
Use DisplayIf in the amount-input component.
client/components/ui/amount-input.js
client/components/ui/amount-input.js
import React from 'react'; import PropTypes from 'prop-types'; import { translate as $t, maybeHas as has } from '../../helpers'; function extractValueFromText(realValue, isCurrentlyNegative, allowToggleSign) { let valueWithPeriod = realValue ? realValue.trim().replace(',', '.') : ''; // Keep only the first period valueWithPeriod = valueWithPeriod .split('.') .splice(0, 2) .join('.'); // Get the period and the zeroes at the end of the input. // When the user types "10.05" char by char, when the value is "10.0", it // will be transformed to 10, so we must remember what is after the decimal // separator so that the user can add "5" at the end to type "10.05". let match = valueWithPeriod.match(/\.\d*0*$/); let afterPeriod = match ? match[0] : ''; let value = Number.parseFloat(valueWithPeriod); let isNegative = isCurrentlyNegative; if (typeof realValue === 'string' && allowToggleSign) { if (realValue[0] === '+') { isNegative = false; } else if (realValue[0] === '-') { isNegative = true; } } if (!Number.isNaN(value) && Number.isFinite(value) && 1 / value !== -Infinity) { // Change the sign only in case the user set a negative value in the input if (allowToggleSign && Math.sign(value) === -1) { isNegative = true; } value = Math.abs(value); } else { value = NaN; } return { isNegative, value, afterPeriod }; } export const testing = { extractValueFromText }; class AmountInput extends React.Component { state = { isNegative: this.props.initiallyNegative, value: Number.parseFloat(this.props.defaultValue), afterPeriod: '' }; getValue() { let { value } = this.state; return this.state.isNegative ? -value : value; } // Calls the parent listeners on onChange events. onChange = () => { if (typeof this.props.onChange === 'function') { this.props.onChange(this.getValue()); } }; // Calls the parent listeners on onBlur/onKey=Enter events. onInput = () => { if (typeof this.props.onInput === 'function') { this.props.onInput(this.getValue()); } }; // Handles onKey=enter. Note that onInput() will be called by the resulting // onBlur event. handleKeyUp = e => { if (e.key === 'Enter') { e.target.blur(); } }; handleInput = () => { this.onInput(); }; handleChange = e => { let { isNegative, value, afterPeriod } = extractValueFromText( e.target.value, this.state.isNegative, this.props.togglable ); this.setState( { isNegative, value, afterPeriod }, this.onChange ); }; handleChangeSign = () => { this.onChange(); this.onInput(); }; handleClick = () => { if (this.props.togglable) { this.setState({ isNegative: !this.state.isNegative }, this.handleChangeSign); } }; clear() { this.setState({ value: NaN, isNegative: this.props.initiallyNegative, afterPeriod: '' }); } reset() { this.setState({ value: Number.parseFloat(this.props.defaultValue), isNegative: this.props.initiallyNegative, afterPeriod: '' }); } render() { let maybeTitle, clickableClass; let togglable = this.props.togglable; if (togglable) { maybeTitle = $t('client.ui.toggle_sign'); clickableClass = 'clickable'; } else { clickableClass = 'not-clickable'; } let value = Number.isNaN(this.state.value) ? '' : this.state.value; // Add the period and what is after, if it exists. if (this.state.afterPeriod) { if (typeof value === 'number') { value = ~~value; } value += this.state.afterPeriod; } let signLabel = this.state.isNegative ? 'minus' : 'plus'; let signClass = this.state.isNegative ? 'fa-minus' : 'fa-plus'; let maybeClassName = this.props.className ? this.props.className : ''; let maybeInputClassName = this.props.checkValidity ? 'check-validity' : ''; let maybeCurrency = null; if (this.props.currencySymbol) { maybeCurrency = <span>{this.props.currencySymbol}</span>; } return ( <div className={`input-with-addon ${maybeClassName}`}> <button type="button" className={`btn ${clickableClass}`} onClick={this.handleClick} id={this.props.signId} title={maybeTitle}> <span className="screen-reader-text">{$t(`client.general.${signLabel}`)}</span> <i className={`fa ${signClass}`} aria-hidden="true" /> </button> <input type="text" className={maybeInputClassName} onChange={this.handleChange} aria-describedby={this.props.signId} value={value} onBlur={this.handleInput} onKeyUp={this.handleKeyUp} id={this.props.id} required={this.props.checkValidity} /> {maybeCurrency} </div> ); } } AmountInput.propTypes = { // Input id id: PropTypes.string, // Function to handle change in the input onChange: PropTypes.func, // Function to handle the validation of the input by the user: on blur, on // hitting 'Enter' or when the sign has changed. onInput: PropTypes.func, // Default value of the input, type string is necessary to set a default empty value. defaultValue: (props, propName, componentName) => { if ( !has(props, 'defaultValue') || (typeof props.defaultValue === 'number' && props.defaultValue < 0) ) { return new Error(`Invalid prop: ${componentName} should have prop ${propName} of type\ number or should be null`); } }, // Id for the sign span. signId: PropTypes.string.isRequired, // Default sign of the input. initiallyNegative: PropTypes.bool, // Whether the amount can be signed (true) or has to be non-negative (false). togglable: PropTypes.bool, // Extra class names to pass to the input. className: PropTypes.string, // Whether validity of the field value should be shown or not. checkValidity: PropTypes.bool }; AmountInput.defaultProps = { initiallyNegative: true, togglable: true, defaultValue: null }; export default AmountInput;
JavaScript
0
@@ -122,16 +122,54 @@ elpers'; +%0Aimport DisplayIf from './display-if'; %0A%0Afuncti @@ -4553,164 +4553,8 @@ ';%0A%0A - let maybeCurrency = null;%0A if (this.props.currencySymbol) %7B%0A maybeCurrency = %3Cspan%3E%7Bthis.props.currencySymbol%7D%3C/span%3E;%0A %7D%0A%0A @@ -5554,23 +5554,149 @@ -%7BmaybeCurrency%7D +%3CDisplayIf condition=%7B!!this.props.currencySymbol%7D%3E%0A %3Cspan%3E%7Bthis.props.currencySymbol%7D%3C/span%3E%0A %3C/DisplayIf%3E %0A
fc38898a94d52b623df8caf3ed604da35aaf58f1
Update position.js
src/shorthands/position.js
src/shorthands/position.js
// @flow import directionalProperty from '../helpers/directionalProperty' const positionMap = ['absolute', 'fixed', 'relative', 'static', 'sticky'] /** * The position shorthand accepts up to five values, including null to skip a value, and uses the directional-property mixin to map them to their respective directions. The first calue can optionally be a position keyword. * @example * // Styles as object usage * const styles = { * ...position('12px', '24px', '36px', '48px') * } * * // styled-components usage * const div = styled.div` * ${position('12px', '24px', '36px', '48px')} * ` * * // CSS as JS Output * * div { * 'top': '12px', * 'right': '24px', * 'bottom': '36px', * 'left': '48px' * } * * // Styles as object usage * const styles = { * ...position('absolute', 12px', '24px', '36px', '48px') * } * * // styled-components usage * const div = styled.div` * ${position('absolute', 12px', '24px', '36px', '48px')} * ` * * // CSS as JS Output * * div { * 'position': 'absolute', * 'top': '12px', * 'right': '24px', * 'bottom': '36px', * 'left': '48px' * } */ function position(positionKeyword: string|null, ...values: Array<?string>) { if (positionMap.includes(positionKeyword)) { return { position: positionKeyword, ...directionalProperty('', ...values), } } else { const firstValue = positionKeyword // in this case position is actually the first value return directionalProperty('', firstValue, ...values) } } export default position
JavaScript
0.000001
@@ -800,32 +800,33 @@ ion('absolute', +' 12px', '24px', ' @@ -933,16 +933,17 @@ olute', +' 12px', '
a6dfc1180e7c4ad8c039da2934fb7a2c00b91269
change site title
fragment.js
fragment.js
const config = require('./config.json'); module.exports = () => ` <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Full on</title> <link href="${config.font.url}" rel="stylesheet"> </head> <body> <div id="app"></div> </body> </html>`;
JavaScript
0.000001
@@ -324,18 +324,29 @@ le%3EFull -on +On Youth Camp %3C/title%3E
e78b1e4b366fabb95441f8afc71a93177edecea8
Enable loader to load stylesheets, too.
vizard/public/js/loader.js
vizard/public/js/loader.js
(function() { // TODO replace loader with DeferJS when it supports .css loading. function Parameters(search) { var pairs = search.slice(1).split('&'); var param, value; if (search === '') { return this; } for (var i = 0; i < pairs.length; i++) { param = pairs[i].split('=', 1); param = decodeURIComponent(param); value = pairs[i].split('=').slice(1).join('='); this[param] = decodeURIComponent(value); } return this; } Parameters.prototype['boot-uri'] = '/javascripts/vizard.boot.js'; var protocol = location.protocol; var host = location.pathname.split('/', 2)[1]; var params = new Parameters(location.search); // FIXME do not load jQuery from Google var src = protocol + '//ajax.googleapis.com'; src += '/ajax/libs/jquery/1.5.1/jquery.js'; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = src; document.body.appendChild(script); function require(src) { var script = $('<script type="text/javascript">').attr('src', src); $('body').append(script); return script; } function boot() { if (!window.jQuery) { return; } clearInterval(interval); require('/js/jquery.simple-toolbar.js'); require('/js/xhtml-0.3.min.js'); require('/js/jquery.vizard-0.4.core.js').ready(function() { var path = '/' + location.pathname.split('/').slice(2).join('/'); Vizard.location = { host: host, hostname: host.split(':', 1)[0], href: protocol + '//' + host + path, pathname: path, port: host.split(':', 2)[1], protocol: protocol, __proto__: location.__proto__ }; Vizard.params = params; require(protocol + '//' + host + params['boot-uri']); }); }; // set an interval because IEs readystatechange gets overwritten by jQuery var interval = setInterval(boot, 25); // export load function this.require = require; })();
JavaScript
0
@@ -932,44 +932,128 @@ ;%0A%0A%09 -function require(src) %7B%0A%09%09var script +var jsExtname = /%5C.js$/, cssExtname = /%5C/.css$/;%0A%09function require(src) %7B%0A%09%09var req;%0A%09%09if (jsExtname.test(src)) %7B%0A%09%09%09req = $ @@ -1108,16 +1108,17 @@ src);%0A%09%09 +%09 $('body' @@ -1126,24 +1126,177 @@ .append( -script); +req);%0A%09%09%7D else if (cssExtname.test(src)) %7B%0A%09%09%09req = $('%3Clink rel=%22stylesheet%22 type=%22text/css%22 charset=%22utf-8%22%3E').attr('href', src);%0A%09%09%09$('head').append(req);%0A%09%09%7D %0A%0A%09%09retu @@ -1298,22 +1298,19 @@ %09return -script +req ;%0A%09%7D%0A%0A%09f
d415358970c949157dbb5d3fea951c84b41976ba
fix percentile for collaborators
api/models/Package.js
api/models/Package.js
/** * Package.js * * @description :: TODO: You might write a short summary of how this model works and what it represents here. * @docs :: http://sailsjs.org/documentation/concepts/models-and-orm/models */ var Promise = require('bluebird'); module.exports = { attributes: { name: { type: Sequelize.STRING, unique: true, primaryKey: true, allowNull: false } }, associations: function() { Package.hasMany(PackageVersion, { as: 'versions', foreignKey: { name: 'package_name', as: 'versions' } } ); Package.belongsTo(PackageVersion, { as: 'latest_version', foreignKey: { name:'latest_version_id', as: 'latest_version' }, constraints: false } ); Package.belongsTo(Repository, { as: 'repository', foreignKey: { name:'type_id', allowNull: true, as: 'repository' } }); Package.belongsToMany(TaskView, { as: 'inViews', foreignKey: 'package_name', through: 'TaskViewPackages', timestamps: false }); Package.belongsToMany(PackageVersion, { as: 'reverse_dependencies', foreignKey: 'dependency_name', through: Dependency, constraints: false}); Package.hasOne(DownloadStatistic, { as: 'last_month_stats', foreignKey: { name: 'package_name', as: 'last_month_stats' } } ); Package.hasMany(Star, { as: 'stars', foreignKey: 'package_name' } ); }, options: { getterMethods: { api_uri: function() { return '/api/packages/:name' .replace(':name', encodeURIComponent(this.getDataValue('name'))); }, uri: function() { return '/packages/:name' .replace(':name', encodeURIComponent(this.getDataValue('name'))); } }, underscored: true, classMethods: { getLatestVersionNumber :function(package_name){ return Package.findOne({ include:[{ model:PackageVersion, as:'latest_version', attributes:['version'], required:true }], where:{ name:package_name } }); }, getAllNamesOfType:function(type){ return Package.findAll({ where:{type_id:type} }).then(function(packages){ return _.map(packages,function(package){ return package.dataValues.name; }) }) }, getPackagePercentile: function(name) { var lastMonthPercentiles = ElasticSearchService.cachedLastMonthPercentiles(); var lastMonthDownload = sails.controllers.packageversion._getDownloadStatistics(undefined, name); return Promise.join(lastMonthPercentiles, lastMonthDownload, function(percentilesResponse, downloads) { var total = downloads.total; var percentiles = _.omit(percentilesResponse, 'fromCache'); var percentile = _.findLastKey(percentiles, function(p) { return total >= p; }); return {total: total, percentile: Math.round(percentile * 100) / 100 }; }); } } } };
JavaScript
0.000001
@@ -2646,44 +2646,8 @@ s = -ElasticSearchService.cachedLastMonth Perc @@ -2652,17 +2652,24 @@ rcentile -s +.findAll ();%0A%0A @@ -2958,12 +2958,25 @@ = _. -omit +mapValues(_.keyBy (per @@ -2996,20 +2996,50 @@ nse, - 'fromCache' +%22percentile%22),function(a)%7Breturn a.value;%7D );%0A
0d3c9b6db7eee0379f86f62a2fdd3d4f2214fbdc
Convert version to numbers
src/capabilities.js
src/capabilities.js
export class Capabilities { constructor(versionStr) { this.QUERY_POST_ENDPOINTS = true; this.QUERY_BY_TAGS = true; this.QUERY_STATS_POST_ENDPOINTS = true; this.FETCH_ALL_TAGS = true; this.TAGS_QUERY_LANGUAGE = true; const regExp = new RegExp('([0-9]+)\.([0-9]+)\.(.+)'); if (versionStr.match(regExp)) { const versionInfo = regExp.exec(versionStr); const major = versionInfo[1]; const minor = versionInfo[2]; if (major === 0 && minor < 17) { this.QUERY_POST_ENDPOINTS = false; } if (major === 0 && minor < 20) { this.QUERY_STATS_POST_ENDPOINTS = false; this.QUERY_BY_TAGS = false; } if (major === 0 && minor < 22) { this.FETCH_ALL_TAGS = false; } if (major === 0 && minor < 24) { this.TAGS_QUERY_LANGUAGE = false; } } } }
JavaScript
0.999999
@@ -394,24 +394,25 @@ nst major = ++ versionInfo%5B @@ -435,16 +435,17 @@ minor = ++ versionI
76dca151caccbe275af39efaa6b0aa62a8359d7d
Indent fix
src/rednose-dialog/js/extensions/dialog-template.js
src/rednose-dialog/js/extensions/dialog-template.js
var Micro = Y.Template.Micro; function Template() {} Template.prototype = { // -- Public Properties ---------------------------------------------------- baseTemplate: '<form class="form-horizontal">' + '</form', tabTemplate: Micro.compile( '<fieldset>' + '<div id="<%= data.id %>">' + '</div>' + '</fieldset>' ), inputTemplate: Micro.compile( '<div class="control-group">' + '<label>' + '<span class="control-label"><%= data.title %> <small><%= data.sub_title %></small></span>' + '<div class="controls">' + '<input type="text" data-path="<%= data.id %>" id="<%= data.id %>" name="<%= data.id %>" placeholder="<%= data.title %>" value="<%= data.value %>">' + '</div>' + '</label>' + '</div>' ), selectTemplate: Micro.compile( '<div class="control-group">' + '<label class="control-label">' + '<span class="control-label"><%= data.title %> <small><%= data.sub_title %></small></span>' + '<div class="controls">' + '<select data-path="<%= data.id %>" id="<%= data.id %>" name="<%= data.id %>">' + '<% Y.Object.each(data.options, function (option, i) { %>' + '<option <%= option.selected ? \'selected="selected"\' : \'\' %> value="<%= option.value %>"><%= option.title %></option>' + '<% }); %>' + '</select>' + '</div>' + '</label>' + '</div>' ), textareaTemplate: Micro.compile( '<div class="control-group">' + '<label class="control-label">' + '<span class="control-label"><%= data.title %> <small><%= data.sub_title %></small></span>' + '<div class="controls">' + '<textarea data-path="<%= data.id %>" id="<%= data.id %>" name="<%= data.id %>" placeholder="<%= data.title %>"><%= data.value %></textarea>' + '</div>' + '</label>' + '</div>' ), // -- Lifecycle Methods ---------------------------------------------------- initializer: function () { this._TemplateEvents = [ Y.Do.before(this._beforeFocusInput, this, '_focusInput', this) ]; this.template = Y.Node.create(this.baseTemplate); }, destructor: function () { (new Y.EventHandle(this._TemplateEvents)).detach(); }, _beforeFocusInput: function () { var tabs = Y.Object.isEmpty(this.get('tabs')), properties = Y.Object.isEmpty(this.get('properties')); if (tabs === false) { this._createTabs(); } if (properties === false) { this._createTemplate(); } if (tabs === false) { this._renderTabs(); } if (tabs === false || properties === false) { this.panel.set('bodyContent', this.template); } }, _createTabs: function () { var self = this, tabs = this.get('tabs'); Y.Object.each(tabs, function (tab) { self.template.append(self.tabTemplate(tab)); }); }, _createTemplate: function () { var self = this, properties = this.get('properties'), tabs = Y.Object.isEmpty(this.get('tabs')), template; Y.Object.each(properties, function (property) { switch (property.type) { case 'input': template = self.inputTemplate; break; case 'select': template = self.selectTemplate; break; case 'textarea': template = self.textareaTemplate; break; default: template = function(){ console.error('Type "%s" in property "%s" is not supported.', property.type, property.title); }; break; } if (property.tab && tabs === false) { self.template.one('#' + property.tab).append(template(property)); } else { self.template.append(template(property)); } }); }, _renderTabs: function () { var container = this.template, tabs = this.get('tabs'); Y.Object.each(tabs, function (tab, i) { if (i === '0') { tab.active = true; } tab.container = container.one('div#' + tab.id); }); this.tabView = new Y.Rednose.TabView({ tabs: tabs }); this.tabView.render(container); } }; Template.ATTRS = { /** * @attribute tabs * @type Object [tabs] * @param {Array} * @param {String} [tabs.id] The element id. * @param {String} [tabs.title] The element title. */ tabs: { value: [] }, /** * @attribute properties * @type {Object} [properties] The following options can be specified: * @param {Array} * @param {String} [properties.type] The element type. input|select|textarea * @param {String} [properties.id] The element id. * @param {String} [properties.title] The element title. * @param {String} [properties.sub_title] The the element subtitle. * @param {String} [properties.value] The the element subtitle. * @param {Object} [properties.options] The select options if type is select. * @param {String} [properties.options.value] The option value. * @param {String} [properties.options.title] The option title. * @param {String} [properties.options.selected] True if selected. */ properties: { value: [] } }; // -- Namespace ---------------------------------------------------------------- Y.Rednose.Dialog.Template = Template; Y.Base.mix(Y.Rednose.Dialog, [Template]);
JavaScript
0.000001
@@ -153,20 +153,16 @@ -------%0A - %0A bas @@ -171,17 +171,16 @@ emplate: - %0A @@ -210,25 +210,24 @@ izontal%22%3E' + - %0A '%3C/ @@ -274,20 +274,16 @@ - - '%3Cfields @@ -288,20 +288,17 @@ dset%3E' + - %0A +%0A @@ -297,26 +297,24 @@ - '%3Cdiv id=%22%3C%25 @@ -323,36 +323,32 @@ data.id %25%3E%22%3E' +%0A - '%3C/d @@ -358,28 +358,24 @@ ' +%0A - '%3C/fieldset%3E @@ -382,18 +382,16 @@ '%0A ), - %0A%0A in @@ -4745,28 +4745,24 @@ - tabs: tabs%0A @@ -4760,20 +4760,16 @@ s: tabs%0A - @@ -4915,33 +4915,32 @@ @param %7BArray%7D - %0A * @par @@ -5217,17 +5217,16 @@ %7BArray%7D - %0A * @@ -6100,8 +6100,9 @@ plate%5D); +%0A
133229b148299ae3e984d3fad37adb5d010d3e25
Update menuController.js
js/menuController.js
js/menuController.js
var app = angular.module("ScarmaGames", []); app.controller("menuController", ['$scope','$location', function($scope, $location) { $scope.go=function(path){ $location.path( path ); } var linebreak="\n"; $scope.items = [{ label: "Warp Bird", link: "Warp Bird", desc : "A Bird Can Destroy"+linebreak+ "You are a cute little bird who can't fly. But you can collect bombs and hammers."+linebreak+ "Enter The Warp Zone!"+linebreak+ "The Warp Zone is useful for rest or trade with merchants."+linebreak+ "Infinite randomly generated levels!"+linebreak+ "Levels become more and more difficult. How far can you go without dying?"+linebreak+ "Play directly from your browser from any device!"+linebreak+ "You can play it using any browser with HTML5 support (Chrome recommended)."+linebreak+ "Now with online leaderboard!"+linebreak+ "Choose your username and password and when you die your score is automatically submitted online!"+linebreak+ "In-Game Controls"+linebreak+ "A / rotate left = Move left"+linebreak+ "D / rotate right = Move right"+linebreak+ "W / slide up = Jump"+linebreak+ "ESC = Restart level"+linebreak+ "Click / tap on a brick = Brick smash"+linebreak+ "Double click / tap = Drop a bomb", img : "WarpBirdGif.gif" }, { label: "Star In Black", link: "Star In Black", desc : "2 stars controlled by one player."+linebreak+ "20+ awesome levels."+linebreak+ "2D Platformer."+linebreak+ "2 hard to complete." , img : "starinblack.png" },{ label: "Rob - The Talking Robot", link: "Rob", desc : "Rob is a smart robot who can do different things such as:"+linebreak+ " - Read a text in many languages (tts)"+linebreak+ " - Repeat what you say"+linebreak+ " - Move along the screen"+linebreak+ " - Change colour"+linebreak+ " - Change sex"+linebreak+ " - Speak louder" , img : "rob.png" },{ label: "Chat & Shoot", link: "Chat & Shoot", desc : "A simple online multiplayer game."+linebreak+ "Chat with your friends while shooting to evil Monsters."+linebreak+ "Have fun in endless matches with a forever looping amazing soundtrack."+linebreak+linebreak+ "In-Game Controls"+linebreak+ "Click: Shoot."+linebreak+ "WASD or Arrows: Move"+linebreak , img : "chat&shoot.png" },{ label: "The Tutorial To Play This Game", link: "The Tutorial To Play This Game", desc : "What happens if the tutorial becomes the game?"+linebreak+ "The objective of the tutorial is to play this game."+linebreak+ "The game is quite a short game and is a little idea made concrete."+linebreak+ "Game made in less than 10 hours from scratch using Construct 2, Audacity and Photofiltre."+linebreak+ "Ending music generated with This Exquisite Music Engine."+linebreak+linebreak+linebreak+ "HINT: Words are meaningful."+linebreak, img: "thetutorialtoplaythisgame.gif" },{ label: "Webcam Effects", link: "Webcam Effects", desc : "Add many effects to your webcam and take picture of your beautiful face.", img : "webcameffects.png" },{ label: "Countdown Timer", link: "Countdown Timer", desc : "If you love time and music this is the app for you."+linebreak+ "Useful for new year countdowns."+linebreak+linebreak+linebreak+linebreak+linebreak , img : "countdowntimer.png" } ]; }]);
JavaScript
0.000001
@@ -135,18 +135,20 @@ %09$scope. -go +play =functio @@ -149,20 +149,23 @@ unction( -path +gameUrl )%7B%0A%09$loc @@ -180,21 +180,42 @@ th( -path +'./'+gameUrl+ '/index.html' );%0A %7D%0A -%09 var @@ -229,16 +229,17 @@ ak=%22%5Cn%22; +%09 %0A $scop
4eac48bcf9e49dda8402ab24fc1fc9198e6e8228
Update custom.js
js/custom.js
js/custom.js
/*------------------------------------------------------------------------------- PRE LOADER -------------------------------------------------------------------------------*/ $(document).ready(function(){ $( "#menu-tpl" ).load( "/mysite/templates/nav.html" ); $( "#portfolio-tpl" ).load( "/mysite/templates/portfolio.html" ); $( "#footer-tpl" ).load( "/mysite/templates/footer.html" ); }); $(window).load(function(){ $('.preloader').fadeOut(1000); // set duration in brackets });
JavaScript
0.000001
@@ -230,39 +230,61 @@ u-tpl%22 ).load( %22 -/mysite +http://filippoquacquarelli.it /templates/nav.h @@ -316,39 +316,61 @@ o-tpl%22 ).load( %22 -/mysite +http://filippoquacquarelli.it /templates/portf @@ -417,15 +417,37 @@ d( %22 -/mysite +http://filippoquacquarelli.it /tem
06d3b1990a46bec0fae5c1e8f1930663605dcdf4
Fix case
js/coffee.js
js/coffee.js
module.exports = { debug: 0, debugString: "200\n1. March 14:28:371", msgNoPots: 'Ingen kanner i dag', msgNoCoffee: 'Kaffen har ikke blitt satt på', msgFormatError: 'Feil i kaffeformat', msgConnectionError: 'Frakoblet fra kaffekanna', msgComforting: 'Så så, det er sikkert kaffe :)', msgNotification: 'Kaffen er satt på, straks klar :)', get: function(pretty, callback) { if (callback == undefined) { console.log('ERROR: Callback is required. In the callback you should insert the results into the DOM.'); return; } var Affiliation = require("./Affiliation.js"); var api = Affiliation.org["online"].hw.apis.coffee; // Receives the status for the coffee pot var self = this; var Ajaxer = require("./Ajaxer.js");//Makes an "instance" of Ajaxer Ajaxer.getPlainText({ url: api, success: function(data) { // If coffee debugging is enabled if (self.debug) { data = self.debugString; } try { // Split into pot number and age of last pot var pieces = data.split("\n"); var pots = Number(pieces[0]); var ageString = pieces[1]; // Coffee made today? if (self.isMadeToday(ageString)) { // Calculate minute difference from right now var now = new Date(); var coffeeTime = String(ageString.match(/\d+:\d+:\d+/)).split(':'); var then = new Date(now.getFullYear(), now.getMonth(), now.getDate(), coffeeTime[0], coffeeTime[1]); var age = self.minuteDiff(then); // If pretty strings are requested if (pretty) { age = self.prettyAgeString(age, coffeeTime); pots = self.prettyPotsString(pots); } // Call it back callback(pots, age); } else { // Coffee was not made today if (pretty) { callback(self.msgNoPots, self.msgNoCoffee); } else { callback(0, 0); } } } catch (err) { if (self.debug) console.log('ERROR: Coffee format is wrong:', err); callback(self.msgFormatError, self.msgComforting); } }, error: function(jqXHR, text, err) { if (self.debug) console.log('ERROR: Failed to get coffee pot status.'); callback(self.msgConnectionError, self.msgComforting); }, }); }, isMadeToday: function(ageString) { // Get now var now = new Date(); // Figure out which date the coffee was made var dateObject = ageString.match(/\d+\. [a-zA-Z]+/); var dateString = String(dateObject); dateString = dateString.replace('.', ''); // Remove period dateString = dateString + ', ' + now.getFullYear(); var coffeeDate = new Date(dateString); // Check if the coffee pots were made today return coffeeDate.getDate() == now.getDate(); }, minuteDiff: function(then) { // Get now var now = new Date(); var one_minute = 1000 * 60; // Calculate difference between the two dates, and convert to minutes return Math.floor(( now.getTime() - then.getTime() ) / one_minute); }, prettyAgeString: function(diff, coffeeTime) { // Create a proper time string from all the minutes if (0 <= diff && diff <= 9) return 'Kaffen ble <b>nettopp laget</b>'; else if (10 <= diff && diff <= 59) return 'Kaffen ble laget for '+diff+' min siden'; else if (60 <= diff) return 'Kaffen ble laget kl '+coffeeTime[0]+':'+coffeeTime[1]; else // time is negative, computer is likely in a timezone between GMT -12 and +1 return 'God reise! Håper de har kaffe! :)'; }, prettyPotsString: function(pots) { return (pots=='0'?'Ingen kanner':pots=='1'?'1 kanne':pots+' kanner') + ' i dag'; }, showNotification: function(pots, age) { // Parameters 'pots' and 'age' not in use yet. var demo = (typeof pots == 'undefined' && typeof age == 'undefined'); // If the computer has slept for a while and there are // suddenly four new coffeepots then they will all be // lined up for notifications, giving the user four // notifications at once. This is prevented here by not // allowing two consecutive notifications within 4 minutes // of each other. var showIt = true; try { var then = JSON.parse(localStorage.lastSubscriptionTime); if (this.minuteDiff(then) <= 4) { showIt = false; } } catch (err) { if (this.debug) console.log('ERROR: failed to calculate coffee subscription time difference'); } if (showIt || demo) { // Save timestamp if this was a real coffee notification if (!demo) localStorage.lastSubscriptionTime = JSON.stringify(new Date()); var key = localStorage.affiliationKey1; var memes = []; // Add regular memes var amount = MEME_AMOUNT; // Number of memes, in regular human numbers, not zero-indexed for (var i = 1; i <= amount; i++) { memes.push('./meme/'+i+'.jpg'); } // Add affiliation memes if (Affiliation.org[key].hw.memePath) { var amount = Affiliation.getMemeCount(key); var path = Affiliation.org[key].hw.memePath; for (var i = 1; i <= amount; i++) { memes.push(path+i+'.jpg'); } } // Randomize image var random = 1 + (Math.floor(Math.random() * memes.length)); if (this.debug) console.log('memes['+(random-1)+'] of '+0+'-'+(memes.length-1)+' is "'+memes[random-1]+'"'); var image = memes[random - 1]; // the list is zero-indexed // Create the notification item = { title: Affiliation.org[key].name + ' Notifier', description: this.msgNotification, image: image, link: 'options.html', feedKey: key, } if (!demo) Browser.createNotification(item); else // Need to run it by the background process because the event listeners are there Browser.getBackgroundProcess().Browser.createNotification(item); } else { if (this.debug) console.log('ERROR: coffee notification displayed less than four minutes ago'); } }, }
JavaScript
0.999965
@@ -581,17 +581,17 @@ uire(%22./ -A +a ffiliati @@ -751,17 +751,17 @@ uire(%22./ -A +a jaxer.js
42d601e214fff7c6909f5a3c8a923550c622e4f0
Fix exception with invalid fragment causing bogus extra scrollbars.
static/js/portico/help.js
static/js/portico/help.js
import * as google_analytics from './google-analytics.js'; import SimpleBar from 'simplebar'; import {activate_correct_tab} from './tabbed-instructions.js'; function registerCodeSection($codeSection) { const $li = $codeSection.find("ul.nav li"); const $blocks = $codeSection.find(".blocks div"); $li.click(function () { const language = this.dataset.language; $li.removeClass("active"); $li.filter("[data-language=" + language + "]").addClass("active"); $blocks.removeClass("active"); $blocks.filter("[data-language=" + language + "]").addClass("active"); }); } function highlight_current_article() { $('.help .sidebar a').removeClass('highlighted'); const path = window.location.pathname; if (!path) { return; } const hash = window.location.hash; let article = $('.help .sidebar a[href="' + path + hash + '"]'); if (!article.length) { // If there isn't an entry in the left sidebar that matches // the full url+hash pair, instead highlight an entry in the // left sidebar that just matches the url part. article = $('.help .sidebar a[href="' + path + '"]'); } // Highlight current article link and the heading of the same article.closest('ul').css('display', 'block'); article.addClass('highlighted'); } function render_code_sections() { $(".code-section").each(function () { activate_correct_tab($(this)); registerCodeSection($(this)); }); highlight_current_article(); common.adjust_mac_shortcuts(".markdown .content code", true); $("table").each(function () { $(this).addClass("table table-striped"); }); } function scrollToHash(simplebar) { const hash = window.location.hash; const scrollbar = simplebar.getScrollElement(); if (hash !== '') { const position = $(hash).position().top - $(scrollbar.firstChild).position().top; scrollbar.scrollTop = position; } else { scrollbar.scrollTop = 0; } } const html_map = new Map(); const loading = { name: null, }; const markdownSB = new SimpleBar($(".markdown")[0]); const fetch_page = function (path, callback) { $.get(path, (res) => { const $html = $(res).find(".markdown .content"); callback($html.html().trim()); render_code_sections(); }); }; const update_page = function (html_map, path) { if (html_map.has(path)) { $(".markdown .content").html(html_map.get(path)); render_code_sections(); scrollToHash(markdownSB); } else { loading.name = path; fetch_page(path, (res) => { html_map.set(path, res); $(".markdown .content").html(res); loading.name = null; scrollToHash(markdownSB); }); } google_analytics.config({page_path: path}); }; new SimpleBar($(".sidebar")[0]); $(".sidebar.slide h2").click((e) => { const $next = $(e.target).next(); if ($next.is("ul")) { // Close other article's headings first $('.sidebar ul').not($next).hide(); // Toggle the heading $next.slideToggle("fast", "swing"); } }); $(".sidebar a").click(function (e) { const path = $(this).attr("href"); const path_dir = path.split('/')[1]; const current_dir = window.location.pathname.split('/')[1]; // Do not block redirecting to external URLs if (path_dir !== current_dir) { return; } if (loading.name === path) { return; } history.pushState({}, "", path); update_page(html_map, path); $(".sidebar").removeClass("show"); e.preventDefault(); }); if (window.location.pathname === '/help/') { // Expand the Guides user docs section in sidebar in the /help/ homepage. $('.help .sidebar h2#guides + ul').show(); } // Remove ID attributes from sidebar links so they don't conflict with index page anchor links $('.help .sidebar h1, .help .sidebar h2, .help .sidebar h3').removeAttr('id'); // Scroll to anchor link when clicked $(document).on('click', '.markdown .content h1, .markdown .content h2, .markdown .content h3', function () { window.location.hash = $(this).attr("id"); scrollToHash(markdownSB); }); $(".hamburger").click(() => { $(".sidebar").toggleClass("show"); }); $(".markdown").click(() => { if ($(".sidebar.show").length) { $(".sidebar.show").toggleClass("show"); } }); render_code_sections(); // Finally, make sure if we loaded a window with a hash, we scroll // to the right place. scrollToHash(markdownSB); window.addEventListener("popstate", () => { const path = window.location.pathname; update_page(html_map, path); }); $('body').addClass('noscroll');
JavaScript
0
@@ -1848,16 +1848,38 @@ h !== '' + && $(hash).length %3E 0 ) %7B%0A
5c5d68f40f88a79675eeb9616068f1c001357192
implement isMinimal() and partitionMap()
src/dsymbols/properties.js
src/dsymbols/properties.js
'use strict'; var I = require('immutable'); var DS = require('./delaney'); var Partition = require('../common/partition'); var _fold = function _fold(partition, a, b, matchP, spreadFn) { var p = partition; var q = I.List().push(I.List([a, b])); while (!q.isEmpty()) { var _tmp = q.first(); var x = _tmp.get(0); var y = _tmp.get(1); q = q.rest(); if (!matchP(x, y)) return; else if (p.get(x) == p.get(y)) continue; else { p = p.union(x, y); q = q.concat(I.List(spreadFn(x, y)).map(I.List)); } } return p; }; var _typeMap = function _typeMap(ds) { var base = I.Map(ds.elements().map(function(D) { return [D, I.List()]; })); var idcs = DS.indices(ds); return base.withMutations(function(map) { idcs.zip(idcs.rest()).forEach(function(p) { var i = p[0]; var j = p[1]; DS.orbitReps2(ds, i, j).forEach(function(D) { var m = DS.m(ds, i, j, D); DS.orbit2(ds, i, j, D).forEach(function(E) { map.set(E, map.get(E).push(m)); }); }); }); }); }; if (require.main == module) { var ds = DS.parse('<1.1:3:1 2 3,1 3,2 3:4 4,3>'); var tm = _typeMap(ds); console.log(tm); console.log('' + _fold(Partition(), 1, 2, function(D, E) { return tm.get(D).equals(tm.get(E)); }, function(D, E) { return ds.indices().map(function(i) { return [ds.s(i, D), ds.s(i, E)]; }); })); }
JavaScript
0.001514
@@ -1084,16 +1084,890 @@ );%0A%7D;%0A%0A%0A +var isMinimal = function isMinimal(ds) %7B%0A var D0 = ds.elements().first();%0A var tm = _typeMap(ds);%0A%0A var match = function(D, E) %7B return tm.get(D).equals(tm.get(E)); %7D;%0A var spread = function(D, E) %7B%0A return ds.indices().map(function(i) %7B%0A return %5Bds.s(i, D), ds.s(i, E)%5D;%0A %7D);%0A %7D;%0A%0A return ds.elements().rest().every(function(D) %7B%0A return _fold(Partition(), D0, D, match, spread) === undefined;%0A %7D);%0A%7D;%0A%0A%0Avar typePartition = function typePartition(ds) %7B%0A var D0 = ds.elements().first();%0A var tm = _typeMap(ds);%0A%0A var match = function(D, E) %7B return tm.get(D).equals(tm.get(E)); %7D;%0A var spread = function(D, E) %7B%0A return ds.indices().map(function(i) %7B%0A return %5Bds.s(i, D), ds.s(i, E)%5D;%0A %7D);%0A %7D;%0A%0A return ds.elements().rest().reduce(%0A function(p, D) %7B%0A return _fold(p, D0, D, match, spread) %7C%7C p;%0A %7D,%0A Partition()%0A );%0A%7D;%0A%0A%0A if (requ @@ -2465,11 +2465,404 @@ %7D)); +%0A%0A var test = function(ds) %7B%0A console.log(ds+' is '+(isMinimal(ds) ? '' : 'not ')+'minimal.');%0A console.log(' '+typePartition(ds));%0A %7D;%0A%0A test(ds);%0A test(DS.withBranchings(ds, 0, %5B%5B2, 4%5D%5D));%0A test(DS.parse(%0A '%3C1.1:24:' +%0A '2 4 6 8 10 12 14 16 18 20 22 24,' +%0A '16 3 5 7 9 11 13 15 24 19 21 23,' +%0A '10 9 20 19 14 13 22 21 24 23 18 17:' +%0A '8 4,3 3 3 3%3E')); %0A%7D%0A
10ab4a2724511975c36453b95841014faa111fce
add log to confirm env var value
src/back/services/user_management.js
src/back/services/user_management.js
import knex from 'knex'; import yup from 'yup'; const db = knex({ client: 'pg', connection: { host: process.env.DATABASE_HOST, user: 'api', password: process.env.DATABASE_PASSWORD, database: 'app', }, }); export const registerSchema = yup.object().shape({ organization: yup .object() .shape({ name: yup.string().required(), org_type: yup.string().required(), }) .nullable(), user: yup .object() .shape({ organization_id: yup.number(), role: yup.string().required(), auth_provider: yup.string().required(), auth_id: yup.string().required(), email: yup.string().email().required(), first_name: yup.string().required(), last_name: yup.string().required(), phone: yup.string().required(), }) .required(), }); export const loginSchema = yup.object().shape({ auth_id: yup.string().required(), auth_provider: yup.string().required(), email: yup.string().email().required(), first_name: yup.string().required(), last_name: yup.string().required(), }); export async function isExistingUser({ auth_provider, auth_id }) { const rows = await db.select('*').from('users').where({ auth_provider, auth_id }); return rows.length > 0; } export async function registerUser(organization, user) { await db.transaction(async (transaction) => { const now = new Date(); let orgInsertResult; if (organization) { orgInsertResult = await transaction('organizations').insert(organization, 'id'); console.log('orgInsertResult', orgInsertResult); } await transaction('users').insert({ ...user, registered_date: now, last_logged_in: now, organization_id: orgInsertResult[0] ? orgInsertResult[0] : null, }); }); } export async function updateUser({ auth_id, auth_provider, email, first_name, last_name }) { await db('users').where({ auth_id, auth_provider }).update({ email, first_name, last_name, last_logged_in: new Date(), }); } export async function getUser(auth_id, auth_provider) { const rows = await db('users').select('*').where({ auth_provider, auth_id }); return rows[0]; }
JavaScript
0.000001
@@ -42,16 +42,85 @@ 'yup';%0A%0A +console.log('process.env.DATABASE_HOST', process.env.DATABASE_HOST);%0A const db
4d5642f182d0357b15e0c3c426232192e53659c9
Remove redundant placeholder.
client/src/new/editors/inputField.js
client/src/new/editors/inputField.js
import React from 'react' const inputField = ({ input, label, type, meta: { touched, error, warning } }) => ( <div> <label htmlFor={input.name}>{label}</label> <div> <input {...input} placeholder={label} type={type} /> {touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))} </div> </div> ) inputField.propTypes = { input: React.PropTypes.shape({ name: React.PropTypes.string, }).isRequired, label: React.PropTypes.string.isRequired, type: React.PropTypes.string.isRequired, meta: React.PropTypes.shape({ touched: React.PropTypes.bool.isRequired, error: React.PropTypes.string, warning: React.PropTypes.string, }).isRequired, } export default inputField
JavaScript
0.000001
@@ -197,28 +197,8 @@ put%7D - placeholder=%7Blabel%7D typ
b7ff586ca1459ba8351dfd766bcb944e085e0fd5
Inline the interval to frequency function
src/effects/PitchEffect.js
src/effects/PitchEffect.js
/** * A pitch change effect, which changes the playback rate of the sound in order * to change its pitch: reducing the playback rate lowers the pitch, increasing the rate * raises the pitch. The duration of the sound is also changed. * * Changing the value of the pitch effect by 10 causes a change in pitch by 1 semitone * (i.e. a musical half-step, such as the difference between C and C#) * Changing the pitch effect by 120 changes the pitch by one octave (12 semitones) * * The value of this effect is not clamped (i.e. it is typically between -120 and 120, * but can be set much higher or much lower, with weird and fun results). * We should consider what extreme values to use for clamping it. * * Note that this effect functions differently from the other audio effects. It is * not part of a chain of audio nodes. Instead, it provides a way to set the playback * on one SoundPlayer or a group of them. */ class PitchEffect { constructor () { this.value = 0; // effect value this.ratio = 1; // the playback rate ratio } /** * Set the effect value * @param {number} val - the new value to set the effect to * @param {object} players - a dictionary of SoundPlayer objects to apply the effect to, indexed by md5 */ set (val, players) { this.value = val; this.ratio = this.getRatio(this.value); this.updatePlayers(players); } /** * Change the effect value * @param {number} val - the value to change the effect by * @param {object} players - a dictionary of SoundPlayer objects indexed by md5 */ changeBy (val, players) { this.set(this.value + val, players); } /** * Compute the playback ratio for an effect value. * The playback ratio is scaled so that a change of 10 in the effect value * gives a change of 1 semitone in the ratio. * @param {number} val - an effect value * @returns {number} a playback ratio */ getRatio (val) { return this.intervalToFrequencyRatio(val / 10); } /** * Convert a musical interval to a frequency ratio. * With thanks to Tone.js: https://github.com/Tonejs/Tone.js * @param {number} interval - a musical interval, in semitones * @returns {number} a frequency ratio */ intervalToFrequencyRatio (interval) { return Math.pow(2, (interval / 12)); } /** * Update a sound player's playback rate using the current ratio for the effect * @param {object} player - a SoundPlayer object */ updatePlayer (player) { player.setPlaybackRate(this.ratio); } /** * Update a sound player's playback rate using the current ratio for the effect * @param {object} players - a dictionary of SoundPlayer objects to update, indexed by md5 */ updatePlayers (players) { if (!players) return; for (const md5 in players) { if (players.hasOwnProperty(md5)) { this.updatePlayer(players[md5]); } } } } module.exports = PitchEffect;
JavaScript
0.999978
@@ -1986,53 +1986,33 @@ -return this.intervalToFrequencyRatio( +const interval = val / 10 );%0A @@ -2007,39 +2007,28 @@ val / 10 -) ;%0A -%7D%0A%0A / -**%0A * +/ Convert @@ -2032,147 +2032,11 @@ ert -a musical interval to a frequency ratio.%0A * With thanks to Tone.js: https://github.com/Tonejs/Tone.js%0A * @param %7Bnumber%7D interval - a +the mus @@ -2048,17 +2048,16 @@ interval -, in semi @@ -2065,99 +2065,29 @@ ones -%0A * @returns %7Bnumber%7D a frequency ratio%0A */%0A intervalToFrequencyRatio (interval) %7B + to a frequency ratio %0A
253c10393d38292d828451aa15f1b027efea96e4
Use PanZoomBar instead of PanZoom.
public/javascripts/map.js
public/javascripts/map.js
var map; var markers; var popup; OpenLayers._getScriptLocation = function () { return "/openlayers/"; } function createMap(divName) { map = new OpenLayers.Map(divName); var mapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik", { displayOutsideMaxExtent: true }); map.addLayer(mapnik); var osmarender = new OpenLayers.Layer.OSM.Osmarender("Osmarender", { displayOutsideMaxExtent: true }); map.addLayer(osmarender); var maplint = new OpenLayers.Layer.OSM.Maplint("Maplint", { displayOutsideMaxExtent: true }); map.addLayer(maplint); var numZoomLevels = Math.max(mapnik.numZoomLevels, osmarender.numZoomLevels); markers = new OpenLayers.Layer.Markers("Markers", { displayInLayerSwitcher: false, numZoomLevels: numZoomLevels, maxExtent: new OpenLayers.Bounds(-20037508,-20037508,20037508,20037508), maxResolution: 156543, units: "m", projection: "EPSG:41001" }); map.addLayer(markers); map.addControl(new OpenLayers.Control.LayerSwitcher()); // map.addControl(new OpenLayers.Control.KeyboardDefaults()); return map; } function getArrowIcon() { var size = new OpenLayers.Size(25, 22); var offset = new OpenLayers.Pixel(-30, -27); var icon = new OpenLayers.Icon("/images/arrow.png", size, offset); return icon; } function addMarkerToMap(position, icon, description) { var marker = new OpenLayers.Marker(position, icon); markers.addMarker(marker); if (description) { marker.events.register("click", marker, function() { openMapPopup(marker, description) }); } return marker; } function openMapPopup(marker, description) { closeMapPopup(); popup = new OpenLayers.Popup.AnchoredBubble("popup", marker.lonlat, sizeMapPopup(description), "<p style='padding-right: 28px'>" + description + "</p>", marker.icon, true); popup.setBackgroundColor("#E3FFC5"); map.addPopup(popup); return popup; } function closeMapPopup() { if (popup) { map.removePopup(popup); delete popup; } } function sizeMapPopup(text) { var box = document.createElement("div"); box.innerHTML = text; box.style.visibility = "hidden"; box.style.position = "absolute"; box.style.top = "0px"; box.style.left = "0px"; box.style.width = "200px"; box.style.height = "auto"; document.body.appendChild(box); var width = box.offsetWidth; var height = box.offsetHeight; document.body.removeChild(box); return new OpenLayers.Size(width + 30, height + 24); } function removeMarkerFromMap(marker){ markers.removeMarker(marker); } function getMapLayers() { var layers = ""; for (var i=0; i< this.map.layers.length; i++) { var layer = this.map.layers[i]; if (layer.isBaseLayer) { layers += (layer == this.map.baseLayer) ? "B" : "0"; } else { layers += (layer.getVisibility()) ? "T" : "F"; } } return layers; } function setMapLayers(layers) { for (var i=0; i < layers.length; i++) { var layer = map.layers[i]; var c = layers.charAt(i); if (c == "B") { map.setBaseLayer(layer); } else if ( (c == "T") || (c == "F") ) { layer.setVisibility(c == "T"); } } } function mercatorToLonLat(merc) { var lon = (merc.lon / 20037508.34) * 180; var lat = (merc.lat / 20037508.34) * 180; lat = 180/Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180)) - Math.PI / 2); return new OpenLayers.LonLat(lon, lat); } function lonLatToMercator(ll) { var lon = ll.lon * 20037508.34 / 180; var lat = Math.log(Math.tan((90 + ll.lat) * Math.PI / 360)) / (Math.PI / 180); lat = lat * 20037508.34 / 180; return new OpenLayers.LonLat(lon, lat); } function scaleToZoom(scale) { return Math.log(360.0/(scale * 512.0)) / Math.log(2.0); }
JavaScript
0
@@ -170,16 +170,284 @@ (divName +, %7B%0A controls: %5B%0A new OpenLayers.Control.ArgParser(), %0A new OpenLayers.Control.Attribution(),%0A new OpenLayers.Control.LayerSwitcher(),%0A new OpenLayers.Control.Navigation(), %0A new OpenLayers.Control.PanZoomBar()%0A %5D%0A %7D );%0A%0A v @@ -1221,133 +1221,8 @@ );%0A%0A - map.addControl(new OpenLayers.Control.LayerSwitcher());%0A // map.addControl(new OpenLayers.Control.KeyboardDefaults());%0A%0A r
8b05199af6c4fa17d246ee3a40b432026cb68b3e
fix server configuration settings
server/config/app.js
server/config/app.js
import path from 'path'; import logger from 'morgan'; import bodyParser from 'body-parser'; import Routes from '../routes/index'; require('dotenv').config(); /* eslint-disable no-console */ const app = express(); const router = express.Router(); const compiler = webpack(config); app.use(require('webpack-dev-middleware')(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use(require('webpack-hot-middleware')(compiler)); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); Routes(router); // prefix /api for all routes app.use('/api/v1', router); app.get('*', (req, res) => res.status(200).sendFile(path.join( __dirname, '../../client', 'index.html') )); module.exports = app;
JavaScript
0.000001
@@ -85,16 +85,126 @@ arser';%0A +import express from 'express';%0Aimport webpack from 'webpack';%0Aimport config from '../../webpack.config.dev';%0A%0A import R
d74496807f4a7eb6352e9d912ca94717ae12fe8b
Update custom.js
js/custom.js
js/custom.js
(function($) { 'use strict'; /* Hide menu after click ----------------------------------------------*/ $('.navbar-nav li a').click(function(event) { $('.in').collapse('hide'); }); /* Smooth scroll to section ----------------------------------------------*/ $('a.scroll[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top-70 }, 500); return false; } } }); /* Team slideshow ----------------------------------------------*/ $("#team-carousel").owlCarousel({ autoplay:false, //Set AutoPlay to 5 seconds items : 3, }); /* Tooltip ----------------------------------------------*/ $('[data-toggle="tooltip"]').tooltip(); /* Lightbox ----------------------------------------------*/ $('.image-link').magnificPopup({ type:'image' }); /* Google map ----------------------------------------------*/ })(jQuery);
JavaScript
0.000001
@@ -999,16 +999,40 @@ ems : 3, +%0A lazyLoad : true %0A%0A %7D)
05b5a13e26d49368306c9c92847635dbbeebbb8c
remove console.log
js/common.js
js/common.js
;(function ($) { // Mode of the modern standard 'use strict'; // Preloader $(window).on('load', function () { $('.preloader').delay(350).fadeOut('slow'); console.log("window loaded"); }); // Function to execute when the DOM is fully loaded. $(function () { // Variables var dppx =''; // dppx value of retina display if (window.devicePixelRatio !== undefined) { dppx = window.devicePixelRatio + 'dppx'; } // If JavaScript enabled $('html').removeClass('no-js').addClass('js ' + dppx); // Remove class .error when receives focus $('.error').on('focus', function () { $(this).removeClass('error'); }); // Verification of support autofocus if (!('autofocus' in document.createElement('input'))) { $('.autofocus').focus(); } // JS for working with accordion $('.fk-accordion-switch').on('click', function () { var accordion = $('.fk-accordion'), this_accordion = $(this).closest(accordion); if (this_accordion.hasClass('js-opened')) { this_accordion.removeClass('js-opened'); } else { accordion.removeClass('js-opened'); this_accordion.addClass('js-opened'); } }); // Universal JavaScript for blocks with tabs $('.fk-tabs-list').on('click', 'li:not(.active)', function () { $(this) .addClass('active').siblings().removeClass('active') .closest('.fk-tabs').find('.fk-tab-item').removeClass('active').eq($(this).index()).addClass('active'); }); }); }(jQuery));
JavaScript
0.000006
@@ -165,42 +165,8 @@ ');%0A - console.log(%22window loaded%22);%0A %7D)
87850f7d6859bafcfbcac5362d493758e092d245
Remove inactive class for active signal bars
homedisplay/info_internet_connection/static/js/internet_connection.js
homedisplay/info_internet_connection/static/js/internet_connection.js
var ShowRealtimePing = function() { var ws4redis, container = $("#internet-connection .ping"), invalid_timeout; function noUpdates(warning_class) { warning_class = warning_class || "error"; container.html("<i class='fa fa-times-circle "+warning_class+"-message'></i>"); } function autoNoUpdates() { noUpdates("warning"); } function update(message) { if (message == "no_pings") { noUpdates(); return; } if (invalid_timeout) { invalid_timeout = clearTimeout(invalid_timeout); } container.html("<i class='fa fa-check-circle success-message'></i> "+(Math.round(parseFloat(message)*10)/10)+"ms"); invalid_timeout = setTimeout(autoNoUpdates, 10000); } function onReceiveItemWS(message) { console.log("ping: backend requests update"); update(message); } function startInterval() { ws4redis = new WS4Redis({ uri: websocket_root+'ping?subscribe-broadcast&publish-broadcast&echo', receive_message: onReceiveItemWS, heartbeat_msg: "--heartbeat--" }); } function stopInterval() { try { ws4redis.close(); } catch(e) { } } this.startInterval = startInterval; this.stopInterval = stopInterval; } var RefreshInternet = function() { var ws4redis, update_interval; function setSignal(level) { $("#internet-connection .signal-bars div").removeClass("active").addClass("inactive"); for (a = 1; a < level; a++) { $("#internet-connection .signal-bars .signal-"+a).addClass("active"); } } function update() { $.get("/homecontroller/internet_connection/status", function (data) { var data = data[0]; if (typeof data == "undefined") { console.log("!!! No internet connection information available"); return; } var output = $("#internet-connection"); var cs = data.fields.connect_status; var cs_out; if (cs == "connected") { cs_out = "<i class='fa fa-check-circle success-message'></i>"; } else if (cs == "connecting") { cs_out = "<i class='fa fa-spin fa-cog warning-message'></i>"; } else { cs_out = "<i class='fa fa-times error-message'></i>"; } output.find(".connected").html(cs_out); output.find(".mode").html(data.fields.mode); setSignal(data.fields.signal); var data_moment = moment(data.fields.timestamp); output.find(".age").html("("+data_moment.fromNow()+")"); }); } function onReceiveItemWS(message) { if (message == "updated") { console.log("internet: backend requests update"); update(); } } function startInterval() { stopInterval(); update(); update_interval = setInterval(update, 1800000); ws4redis = new WS4Redis({ uri: websocket_root+'internet?subscribe-broadcast&publish-broadcast&echo', receive_message: onReceiveItemWS, heartbeat_msg: "--heartbeat--" }); } function stopInterval() { if (update_interval) { update_interval = clearInterval(update_interval); } try { ws4redis.close(); } catch(e) { } } this.startInterval = startInterval; this.stopInterval = stopInterval; }; var refresh_internet, show_pings; $(document).ready(function() { refresh_internet = new RefreshInternet(); refresh_internet.startInterval(); show_pings = new ShowRealtimePing(); show_pings.startInterval(); $("#internet-connection").on("click", function() { var charts = [["idler", "Internet/idler_last_10800.png"], ["Google", "Internet/google_last_10800.png"], ["Saunalahti", "Internet/saunalahti_last_10800.png"], ["Funet", "Internet/funet_last_10800.png"], ["idler", "Internet/idler_last_108000.png"], ["Google", "Internet/google_last_108000.png"], ["Saunalahti", "Internet/saunalahti_last_108000.png"], ["Funet", "Internet/funet_last_108000.png"] ]; var content = ""; var timestamp = new Date() - 0; $.each(charts, function() { content += "<div class='smokeping-chart'><h4>"+this[0]+"</h4><img src='/smokeping/images/"+this[1]+"?"+timestamp+"'></div>"; }); $("#internet-connection-modal .smokeping-charts").html(content); switchVisibleContent("#internet-connection-modal"); }); $("#internet-connection-modal .close").on("click", function () { switchVisibleContent("#main-content"); }); });
JavaScript
0
@@ -1510,24 +1510,48 @@ ss(%22active%22) +.removeClass(%22inactive%22) ;%0A %7D%0A %7D%0A
61d31df4b128e8551b956f87e6ca1ed887864a4a
Use autoprefixer for css prefixing
server/css-bundle.js
server/css-bundle.js
'use strict'; var cssAid = require('css-aid') , getFiles = require('./css-bundle-get-files'); module.exports = function (indexPath, readFile) { return getFiles(indexPath, readFile)(function (data) { return cssAid(data.reduce(function (content, data) { return content + '/* ' + data.filename + ' */\n\n' + data.content + '\n'; }, '').slice(0, -1)); }); };
JavaScript
0
@@ -11,16 +11,64 @@ t';%0A%0Avar + autoprefixer = require('autoprefixer-core')%0A , cssAid @@ -69,16 +69,20 @@ ssAid + = requir @@ -91,18 +91,82 @@ 'css-aid -') +/process')%0A , cssAidRules = %5Brequire('css-aid/rules/variables')%5D %0A , get @@ -171,16 +171,20 @@ etFiles + = requir @@ -335,16 +335,37 @@ cssAid( +autoprefixer.process( data.red @@ -472,16 +472,16 @@ + '%5Cn';%0A - %09%09%7D, '') @@ -494,16 +494,34 @@ (0, -1)) +.css, cssAidRules) ;%0A%09%7D);%0A%7D
0d5303ace5730f31d5949f53b060fdc268719ba9
Add popup config to layer class
src/scripts/map/wfs-layer.js
src/scripts/map/wfs-layer.js
import ol from 'openlayers'; import OverlayLayer from './overlay-layer'; /** * Web Feature Service Layer * @extends OverlayLayer */ class WFSLayer extends OverlayLayer { /** * @param {Object} config - Configuration object * @param {String} [config.title='OverlayLayer'] - Layer title * @param {Boolean} [config.visible=false] - Layer initial status * @param {String} config.server - URL of map server * @param {String} config.layerName - Name of layer to display * @param {String} [config.attribution=''] - Layer data attribution * @param {Boolean} [config.exclusive=false] - If true, when the layer is shown, * all other overlay layers are hidden * @param {Object} config.style - Style configuration * @param {String} config.style.property - Property that defines the style to use * @param {Object} config.style.values - Object with possible values * and their corresponding style * @param {Object[]} [config.popup] - Data to show when user clicks * on a feature in the map * @param {String} config.popup[].property - Name of the field to show * @param {String} [config.popup[].title] - Text to show as field title */ constructor(config = {}) { super(config); this.server = `${config.server}/wfs/`; this.format = new ol.format.GeoJSON(); this.styleCache = {}; this.style = config.style; this.layer = new ol.layer.Vector({ title: this.title, visible: this.visible, exclusive: this.exclusive, }); this.layer.setStyle(this.setStyle.bind(this)); this.source = new ol.source.Vector({ loader: this.loadFeatures.bind(this), strategy: ol.loadingstrategy.tile(ol.tilegrid.createXYZ({ maxZoom: 19, })), attributions: [new ol.Attribution({ html: this.attribution, })], }); this.layer.popup = config.popup; this.loading = 0; } /** * Reloads layer data using current filters */ refresh() { this.source.clear(); } /** * Loads features from server via WFS service * @param {Number[]} extent - Array of numbers representing an extent: [minx, miny, maxx, maxy] * @private */ loadFeatures(extent) { this.loading += 1; const params = new URLSearchParams(); params.append('service', 'WFS'); params.append('version', '1.0.0'); params.append('request', 'GetFeature'); params.append('outputFormat', 'application/json'); params.append('format_options', 'CHARSET:UTF-8'); params.append('typename', this.layerName); params.append('srsname', this.manager.viewProjection.getCode()); params.append('cql_filter', this.buildCQLFilter(extent)); fetch(`${this.server}?${params.toString()}`, { mode: 'cors', }).then(response => response.json()) .catch(() => null) .then((data) => { if (data) { this.source.addFeatures(this.format.readFeatures(data)); } this.loading -= 1; if (this.loading === 0) { this.emit('loaded'); } }); } /** * Sets feature style * @param {Object} feature - Openlayers' [feature](https://openlayers.org/en/latest/apidoc/ol.Feature.html) object * @param {Number} resolution - Current map resolution * @private */ setStyle(feature, resolution) { const value = feature.get(this.style.property); if (!value || !this.style.values[value]) { return this.getDefaultStyle(); } if (!this.styleCache[value]) { this.styleCache[value] = {}; } if (!this.styleCache[value][resolution]) { const radius = Math.min(Math.max(3, Math.ceil(40 / Math.log(Math.ceil(resolution)))), 20); this.styleCache[value][resolution] = new ol.style.Style({ image: new ol.style.Circle({ fill: new ol.style.Fill({ color: ol.color.asArray(this.style.values[value].color), }), radius, stroke: this.getDefaultStroke(), }), }); } return [this.styleCache[value][resolution]]; } /** * Builds default stroke style * @returns {Object} Openlayers' [Stroke](https://openlayers.org/en/latest/apidoc/ol.style.Stroke.html) object * @private */ getDefaultStroke() { if (!this.defaultStroke) { this.defaultStroke = new ol.style.Stroke({ color: [0, 0, 0, 0.5], width: 1, }); } return this.defaultStroke; } /** * Builds default fill style * @returns {Object} Openlayers' [Fill](https://openlayers.org/en/latest/apidoc/ol.style.Fill.html) object * @private */ getDefaultFill() { if (!this.defaultFill) { this.defaultFill = new ol.style.Fill({ color: [255, 255, 255, 0.5], }); } return this.defaultFill; } /** * Builds default text style * @param {Number} radius * @returns {Object} Openlayers' [Text](https://openlayers.org/en/latest/apidoc/ol.style.Text.html) object * @private */ getDefaultText(radius) { if (!this.defaultText) { this.defaultText = new ol.style.Text({ offsetY: radius * 1.5, fill: new ol.style.Fill({ color: '#666', }), stroke: new ol.style.Stroke({ color: '#FFFFFF', width: 2, }), }); } return this.defaultText; } /** * Builds default style * @returns {Object} Openlayers' [Style](https://openlayers.org/en/latest/apidoc/ol.style.Style.html) object * @private */ getDefaultStyle() { if (!this.defaultStyle) { this.defaultStyle = new ol.style.Style({ fill: this.getDefaultFill(), stroke: this.getDefaultStroke(), image: new ol.style.Circle({ fill: this.getDefaultFill(), radius: 10, stroke: this.getDefaultStroke(), }), }); } return [this.defaultStyle]; } /** * Builds CQLFilter string based on current extent and dashboard filters * @param {Number[]} extent - Array of numbers representing an extent: [minx, miny, maxx, maxy] * @returns {String} * @private */ buildCQLFilter(extent) { let cqlFilter = `bbox(geom, ${extent.join(',')}, '${this.manager.viewProjection.getCode()}')`; if (this.manager.filterString) { cqlFilter = `${cqlFilter} AND ${this.manager.filterString}`; } return cqlFilter; } } export default WFSLayer;
JavaScript
0.000001
@@ -1367,16 +1367,47 @@ g.style; +%0A this.popup = config.popup; %0A%0A th
32e9027b96d91941eaca4629552ed6154bd4ad07
Fix -- Remove generator import.
src/action_controller/index.js
src/action_controller/index.js
module.exports = { Base: require('./base'), generator: require('./generator') }
JavaScript
0
@@ -41,44 +41,7 @@ se') -,%0A generator: require('./generator') %0A%7D%0A
8b850eb3b43fd518204186219babeb1842e73ef3
Fix fitlers issue
src/scripts/map/wms-layer.js
src/scripts/map/wms-layer.js
import Attribution from 'ol/attribution'; import Tile from 'ol/layer/tile'; import Image from 'ol/layer/image'; import TileWMS from 'ol/source/tilewms'; import ImageWMS from 'ol/source/imagewms'; import OverlayLayer from './overlay-layer'; /** * Web Map Service Layer * @extends OverlayLayer */ class WMSLayer extends OverlayLayer { /** * @param {Object} config - Configuration object * @param {String} [config.title='OverlayLayer'] - Layer title * @param {Boolean} [config.visible=false] - Layer initial status * @param {String} config.server - URL of map server * @param {String} config.layerName - Name of layer to display * @param {String} [config.attribution=''] - Layer data attribution * @param {Boolean} [config.exclusive=false] - If true, when the layer is shown, * all other overlay layers are hidden * @param {String} config.style - The style or styles to be used with the layer * @param {Boolean} [config.tiled=false] - Use tiles or single image WMS * @param {Boolean} [config.useCache=false] - Use GeoWebCache URL instead of direct WMS * @param {Filter[]} [config.filters] - Set of filters to apply to the layer. Overrides global dashboard filters. */ constructor(config = {}) { super(config); if (config.useCache) { this.server = `${config.server}/gwc/service/wms/`; } else { this.server = `${config.server}/wms/`; } this.style = config.style; const layerConfig = { title: this.title, visible: this.visible, exclusive: this.exclusive, zIndex: 1, opacity: this.opacity, }; const sourceConfig = { url: this.server, params: { LAYERS: this.layerName, STYLES: this.style, }, attributions: [new Attribution({ html: this.attribution, })], }; if (config.tiled) { this.layer = new Tile(layerConfig); this.source = new TileWMS(sourceConfig); } else { this.layer = new Image(layerConfig); this.source = new ImageWMS(sourceConfig); } } /** * Reloads layer data using current filters */ refresh() { const params = this.layer.getSource().getParams(); if (!params.srs) { params.srs = this.manager.view.getProjection().getCode(); } if (this.filters) { params.CQL_FILTER = this.filterString; this.source.updateParams(params); } else if (this.manager.filters.length) { params.CQL_FILTER = this.manager.filterString; this.source.updateParams(params); } } } export default WMSLayer;
JavaScript
0
@@ -2299,16 +2299,39 @@ .filters + && this.filters.length ) %7B%0A
66edd340c4aa976114de9b9204ee3de1cfd64c84
remove current active state on update
src/zbase/webui/widgets/zbase-main-menu/main_menu.js
src/zbase/webui/widgets/zbase-main-menu/main_menu.js
var ZBaseMainMenu = (function() { var render = function(path) { var tpl = $.getTemplate( "widgets/zbase-main-menu", "zbase_main_menu_tpl"); var menu = document.getElementById("zbase_main_menu"); $.replaceContent(menu, tpl); $.handleLinks(menu); setActiveMenuItem(path); var toggler = document.getElementById("menu_toggler"); if (toggler) { $.onClick(toggler, function() { menu.classList.toggle("hidden"); toggler.classList.toggle("closed"); }); } }; var hideMenu = function() { document.getElementById("zbase_main_menu").classList.add("hidden"); document.getElementById("menu_toggler").classList.add("closed"); }; var showMenu = function() { document.getElementById("zbase_main_menu").classList.remove("hidden"); document.getElementById("menu_toggler").classList.remove("closed"); }; var setActiveMenuItem = function(path) { var menu = document.getElementById("zbase_main_menu"); var items = menu.querySelectorAll("a"); var active_path_length = 0; var active_item; for (var i = 0; i < items.length; i++) { var current_path = items[i].getAttribute("href"); if (path.indexOf(current_path) == 0 && current_path.length > active_path_length) { active_item = items[i]; active_path_length = current_path.length; } } if (active_item) { active_item.setAttribute("data-active", "active"); } }; return { render: render, update: setActiveMenuItem, hide: hideMenu, show: showMenu } })();
JavaScript
0.000002
@@ -985,24 +985,162 @@ ain_menu%22);%0A + var current_active = $(%22a%5Bdata-active%5D%22, menu);%0A if (current_active) %7B%0A current_active.removeAttribute(%22data-active%22);%0A %7D%0A%0A var item
3706d4293b19738838b547f00238cd9d075993f0
Update adele.js
calc/adele.js
calc/adele.js
var calc = function () { Number.radix = parseInt(location.hash.slice(1)) || 10 calc.refresh() document.body === calc.display.parentNode || document.body.appendChild(calc.display) document.body === calc.keypad .parentNode || document.body.appendChild(calc.keypad) } !function () { var set = function (a) { e.value = a; e.data.textContent = a.toString() }, reset = function () { delete e.value; e.data.textContent = '0' }, bs = function () { var _ = e.data.textContent.slice(0, -1) e.data.textContent = _ === '' ? '0' : _ }, fix = function () { e.value = e.value || new Adele(parseInt(e.data.textContent, Number.radix)) }, focus = function () { e.classList.remove('focus') e = this e.classList.add('focus') }, makeCell = function () { var cell = html.tr(), data = html.td() cell.appendChild(data) data.textContent = '0' cell[touch] = cell.focus = focus cell.data = data return cell }, refresh = function () { var _ = calc.display.firstChild while (_) { _.value && (_.data.textContent = _.value.toString()) _ = _.nextSibling } }, push = function () { e.parentNode.insertBefore(makeCell(), e.nextSibling) e.nextSibling.focus() }, pop = function () { var _ = e.value if (e.previousSibling) { e.previousSibling.focus() e.parentNode.removeChild(e.nextSibling) } return _ }, numeric = function () { var _ = this.textContent, __ e.value && push() __ = e.data __.textContent = (__.textContent === '0' ? '' : __.textContent) + _ }, touch = document.createElement('div').hasOwnProperty('ontouchend') ? 'ontouchend' : 'onmouseup', html = {}, func = {}, e 10 .forEach(function (i) { func[i] = numeric }) func['.'] = function() { e.value && push() e.data.textContent += '.' } func['↑'] = function () { var _ = e.value _ ? push() : (_ = new Adele(parseInt(e.data.textContent, Number.radix))) set(_) } func['↓'] = function () { e.previousSibling ? pop() : reset() } func['←'] = function () { e.value ? reset() : bs() } func['ˆ'] = function () { var _ if (e.previousSibling) { fix(); _ = pop(); set(e.value ? e.value.pow(_) : _) } } func['↕'] = function () { fix() if (e.previousSibling) { e.parentNode.insertBefore(e, e.previousSibling) e.nextSibling.focus() } } func['↔'] = function () { Number.isLittle = ! Number.isLittle refresh() } func['/'] = function () { var _ fix(); _ = e.value _.isZero() || set(_.inv()) } func['−'] = function () { fix(); set(e.value.neg()) } func['\\'] = function () { var _ fix(); _ = e.value _.isUnit() || set(_.isZero() ? new Adele(_.n) : _.res()) } func[' '] = function () { var _ if (e.previousSibling) { fix(); _ = pop(); set(e.value ? e.value.mul(_) : _) } } func['+'] = function () { var _ if (e.previousSibling) { fix(); _ = pop(); set(e.value ? e.value.add(_) : _) } } func[':'] = function () { var _, __, p fix(); _ = e.value if (_.isZero() || _.isUnit()) { // do nothing } else if (_.isBody()) { // prime factorization __ = _.factor(); p = __[0]; _ = __[1] set(p) if (!_.isUnity()) { push(); set(_) } } else { // ub factorization set(_.body()); push(); set(_.unit()) } } func['..'] = function () { var _ fix(); _ = e.value if (_.n === 0) { // do nothing } else if (!_.isZero()) { set(new Adele(_.r, _.s)); push() set(new Adele(0, 1, _.n)) } } ;['tr', 'td', 'table'].forEach(function (a) { html[a] = function () { return document.createElement(a) } }) calc.display = html.table() calc.keypad = html.table() ;[ ['↑', '↓', '←', '7', '8', '9'], ['ˆ', '↕', '↔', '4', '5', '6'], [':', ' ', '/', '1', '2', '3'], ['..', '+', '−', '0', '.', '\\'] ].forEach(function (tds) { var tr = html.tr() tds.forEach(function (td) { var _ = html.td() _.textContent = td _[touch] = func[td] tr.appendChild(_) }) calc.keypad.appendChild(tr) }) calc.keypad.classList.add('keypad') e = makeCell() calc.display.appendChild(e) calc.display.classList.add('display') calc.refresh = refresh }() onload = onhashchange = calc
JavaScript
0
@@ -578,34 +578,28 @@ alue %7C%7C -new Adele( +Number. parse -Int (e.data. @@ -609,31 +609,16 @@ tContent -, Number.radix) )%0A%7D,%0Afoc @@ -1808,26 +1808,20 @@ _ = -new Adele( +Number. parse -Int (e.d @@ -1839,23 +1839,8 @@ tent -, Number.radix) ))%0A
b9fa4dc23413e36d5064e32faa6054786dc32399
Fix direct init
assets/datagrid-spinners.js
assets/datagrid-spinners.js
var dataGridRegisterExtension; if (typeof naja !== "undefined") { var isNaja2 = function () { return naja.version >= 2 }; dataGridRegisterExtension = function (name, extension) { var init = extension.init; var success = extension.success; var before = extension.before; var complete = extension.complete; var NewExtension = function NewExtension(naja, name) { this.name = name; this.initialize = function (naja) { if(init) { naja.addEventListener('init', function (params) { init(params.defaultOptions); }); } if(success) { naja.addEventListener('success', function (params) { var payload = isNaja2() ? params.payload : params.response; success(payload, params.options); }); } if(before) { naja.addEventListener('before', function (params) { before(params.xhr || params.request, params.options); }); } if(complete) { naja.addEventListener('complete', function (params) { complete(params.xhr || params.request, params.options); }); } } if (!naja.version || !isNaja2()) { extension.initialize(naja); } return this; } if (isNaja2()) { naja.registerExtension(new NewExtension(null, name)); } else { naja.registerExtension(NewExtension, name); } }; } else if ($.nette) { dataGridRegisterExtension = function (name, extension) { $.nette.ext(name, extension); }; } dataGridRegisterExtension('ublaboo-spinners', { before: function(xhr, settings) { var el, id, row_detail, spinner_template, grid_fullname; if (settings.nette) { el = settings.nette.el; spinner_template = $('<div class="ublaboo-spinner ublaboo-spinner-small"><i></i><i></i><i></i><i></i></div>'); if (el.is('.datagrid [name="group_action[submit]"]')) { return el.after(spinner_template); } else if (el.is('.datagrid a') && el.data('toggle-detail')) { id = settings.nette.el.attr('data-toggle-detail'); grid_fullname = settings.nette.el.attr('data-toggle-detail-grid-fullname'); row_detail = $('.item-detail-' + grid_fullname + '-id-' + id); if (!row_detail.hasClass('loaded')) { return el.addClass('ublaboo-spinner-icon'); } } else if (el.is('.datagrid .col-pagination a')) { return el.closest('.row-grid-bottom').find('.col-per-page').prepend(spinner_template); } else if (el.is('.datagrid .datagrid-per-page-submit')) { return el.closest('.row-grid-bottom').find('.col-per-page').prepend(spinner_template); } else if (el.is('.datagrid .reset-filter')) { return el.closest('.row-grid-bottom').find('.col-per-page').prepend(spinner_template); } } }, complete: function() { $('.ublaboo-spinner').remove(); return $('.ublaboo-spinner-icon').removeClass('ublaboo-spinner-icon'); } });
JavaScript
0.000027
@@ -1102,25 +1102,20 @@ ) %7B%0A%09%09%09%09 -extension +this .initial
8e4af4e199cad541daacfed3148a0d81b52fe834
Use schema so client state updates automatically
src/actions/AccountSettings.js
src/actions/AccountSettings.js
import { SubmissionError } from 'redux-form'; import { UPDATE_AVATAR_REQUEST, UPDATE_AVATAR_FAILURE, UPDATE_AVATAR_SUCCESS, UPDATE_USER_REQUEST, UPDATE_USER_FAILURE, UPDATE_USER_SUCCESS } from '../constants/ActionTypes'; import { CALL_API } from '../middleware/api'; const updateAvatarRequest = (formData) => ({ [CALL_API]: { types: [ UPDATE_AVATAR_REQUEST, UPDATE_AVATAR_SUCCESS, UPDATE_AVATAR_FAILURE ], endpoint: `account/avatar`, method: 'POST', body: formData } }); const updateUserRequest = ({username, first_name, last_name}) => ({ [CALL_API]: { types: [ UPDATE_USER_REQUEST, UPDATE_USER_SUCCESS, UPDATE_USER_FAILURE ], endpoint: `account/info`, method: 'POST', body: { username: username, first_name: first_name, last_name: last_name } } }); const updatePasswordRequest = ({current_password, new_password}) => ({ [CALL_API]: { types: [ UPDATE_USER_REQUEST, UPDATE_USER_SUCCESS, UPDATE_USER_FAILURE ], endpoint: `account/password`, method: 'POST', body: { current_password, new_password } } }); export const updateAvatar = (values) => (dispatch, getState) => { const file = values.avatar[0]; var formData = new FormData(); formData.append("avatar", file); return dispatch(updateAvatarRequest(formData)).then(response => { if(response.error){ throw new SubmissionError(response.response); } }); }; export const updateInfo = (values) => (dispatch, getState) => { return dispatch(updateUserRequest(values)).then(response => { if(response.error){ throw new SubmissionError(response.response); } }); }; export const updatePassword = (values) => (dispatch, getState) => { return dispatch(updatePasswordRequest(values)).then(response => { if(response.error){ throw new SubmissionError(response.response); } }); };
JavaScript
0
@@ -235,16 +235,25 @@ CALL_API +, Schemas %7D from @@ -273,16 +273,16 @@ e/api';%0A - %0A%0Aconst @@ -464,32 +464,58 @@ method: 'POST',%0A + schema: Schemas.USER,%0A body: formDa @@ -718,16 +718,16 @@ /info%60,%0A - meth @@ -730,32 +730,58 @@ method: 'POST',%0A + schema: Schemas.USER,%0A body: %7B%0A
627202df77b61e64676f487a8be3954bdee9948f
Fix ReferenceError
edwin/client/static/js/actions/TimelineActions.js
edwin/client/static/js/actions/TimelineActions.js
import Immutable from 'immutable'; import Dispatcher from '../dispatcher'; import TimelineConstants from '../constants/TimelineConstants'; import bzAPI from '../utils/bzAPI'; import githubAPI from '../utils/githubAPI.js'; import edwinAPI from '../utils/edwinAPI.js'; import BugStore from '../stores/BugStore.js'; import UserStore from '../stores/UserStore.js'; import PromiseExt from '../utils/PromiseExt.js'; import ProgressActions from '../actions/ProgressActions.js'; /** * Fetch bugs from the API, and dispatch an event to replace the bugs * in the store with the new bugs. * @param {Object} query Bugzilla API query. * @promises {undefined} Signals completion with no data. */ export function loadBugs(teamSlug, query) { const user = UserStore.getAll(); ProgressActions.startTask('Load bugs'); if (user.get('loggedIn')) { query.api_key = user.get('apiKey'); } return bzAPI.getBugs(query) .then(newBugs => { Dispatcher.dispatch({ type: TimelineConstants.ActionTypes.SET_RAW_BUGS, team: teamSlug, newBugs, }); let idsForCommentTags = BugStore.getAll(teamSlug) .filter(bug => bug.get('state') !== TimelineConstants.BugStates.NOT_READY) .map(bug => bug.get('id')); return loadCommentTags(idsForCommentTags); }) .then(() => { // Pull all the bug ids we need for blocker bugs return loadBlockerBugs(BugStore.getBlockerBugIds(teamSlug)); }) .then(() => ProgressActions.endTask('Load bugs')) // signal completion .then(() => undefined); } /** * Fetch PRs from the API, and dispatch an event to replace the PRs * in the store with the new PRs. * @param {string} repo A repo name like "mythmon/edwin". * @promises {undefined} Signals completion with no data. */ export function loadPRs(repos) { ProgressActions.startTask('Load PRs'); Promise.all(repos.map(repo => githubAPI.getPRs(repo))) .then(prLists => { let flattened = []; for (let prList of prLists) { flattened = flattened.concat(prList); } Dispatcher.dispatch({ type: TimelineConstants.ActionTypes.SET_RAW_PRS, newPRs: flattened, }); }) .then(() => ProgressActions.endTask('Load PRs')) // signal completion .then(() => undefined); } /** * Fetch Teams from the API, and dispatch an event to replace the teams * in the store with the new ones. * @promise {undefined} Signals copmletion with no data. */ export function loadTeams() { ProgressActions.startTask('Load teams'); return edwinAPI.getTeams() .then(newTeams => { Dispatcher.dispatch({ type: TimelineConstants.ActionTypes.SET_RAW_TEAMS, newTeams, }); }) .then(() => ProgressActions.endTask('Load teams')) // signal completion .then(() => undefined); } /** * Get all comment tags for all `bugs`, and fire events for each. * @param {Array<Immutable.Map>} An array of immutable.js objects representing * the bugs to get comment tags for. */ export function loadCommentTags(bugIds) { let params = {}; const user = UserStore.getAll(); ProgressActions.startTask('Load comments'); if (user.get('loggedIn')) { params.api_key = user.get('apiKey'); } let commentPromises = bugIds.map(bugId => ( bzAPI.getBugComments(bugId, params) .then(comments => { return {bugId, commentId: comments[0].id, tags: comments[0].tags}; }) )).toJS(); return PromiseExt.allResolves(commentPromises) .then(commentSpecs => { Dispatcher.dispatch({ type: TimelineConstants.ActionTypes.SET_COMMENT_TAGS, commentSpecs, }); }) .then(() => ProgressActions.endTask('Load comments')); } /** * Fetch data for blocker bugs. * @param {Array<Immutable.List>} List of bug ids */ export function loadBlockerBugs(bugIds) { if (bugIds.size > 0) { let bugQuery = {id: Array.from(bugIds).join(',')}; const user = UserStore.getAll(); ProgressActions.startTask('Load blockers'); if (user.get('loggedIn')) { query.api_key = user.get('apiKey'); } return bzAPI.getBugs(bugQuery) .then(newBugs => { Dispatcher.dispatch({ type: TimelineConstants.ActionTypes.SET_BLOCKER_BUGS, newBugs, }); }) .then(() => ProgressActions.endTask('Load blockers')); } else { return Promise.resolve(); } } export function grabBug(bugId) { const user = UserStore.getAll(); if (!user.get('loggedIn')) { throw new Error("Can't grab bugs without being loggd in."); } const assigned_to = user.get('username'); const api_key = user.get('apiKey'); bzAPI.modifyBug(bugId, { status: 'ASSIGNED', assigned_to, api_key, }) .then(() => { Dispatcher.dispatch({ type: TimelineConstants.ActionTypes.ASSIGN_BUG, assigned_to, bugId, }); }); } export function setInternalSort(bugId, sortOrder) { Dispatcher.dispatch({ type: TimelineConstants.ActionTypes.BUG_SET_INTERNAL_SORT, bugId, sortOrder, }); } export function commitSortOrder() { const user = UserStore.getAll(); if (!user.get('loggedIn')) { throw new Error("Can't sort bugs without being loggd in."); } const apiKey = user.get('apiKey'); const oldBugMap = BugStore.getMap(); Dispatcher.dispatch({ type: TimelineConstants.ActionTypes.BUGS_COMMIT_SORT_ORDER, }); /* `dispatch` is syncronous, so all the bugs have correct comment tags * now to represent the order they should be in. Compare the new comment * tags with the old comment tags, and commit any diffs to the server. * This would be easier if we could just directly update the comment * tags, but the bugzilla API doesn't work that way. */ let promises = []; const newBugMap = BugStore.getMap(); for (let [bugId, oldBug] of oldBugMap) { const newBug = newBugMap.get(bugId); const oldCommentTags = oldBug.get('comment_tags', new Immutable.Set()); const newCommentTags = newBug.get('comment_tags', new Immutable.Set()); const toAdd = newCommentTags.subtract(oldCommentTags); const toRemove = oldCommentTags.subtract(newCommentTags); if (toRemove.count() > 0 || toAdd.count() > 0) { promises.push(bzAPI.updateCommentTags({ commentId: oldBug.get('comment_zero_id'), add: toAdd.toJS(), remove: toRemove.toJS(), apiKey, })); } } return Promise.all(promises); } export default { loadBugs, loadPRs, loadTeams, loadCommentTags, grabBug, setInternalSort, commitSortOrder, };
JavaScript
0.000002
@@ -3949,25 +3949,28 @@ ')) %7B%0A -q +bugQ uery.api_key
650ac4091df37b2b6cba326b2904454b4f0239fe
Update Conference test for async responder.
compassion.counterfeiter/t/create.js
compassion.counterfeiter/t/create.js
module.exports = function (assert, reduced) { var Monotonic = require('monotonic').asString try { var Conference = require('../../compassion.conference/conference') } catch (e) { var Conference = require('../conference') } var cadence = require('cadence') var reactor = { responder: function (conference, header, queue) { assert(header.test, 'responder') queue.push(1) queue.push(null) }, bootstrap: cadence(function (async) { return null }), join: cadence(function (async, conference) { if (conference.id != 'fourth') { return [] } assert(conference.getProperties('fourth'), { key: 'value', url: 'http://127.0.0.1:8888/fourth/' }, 'get properties') // TODO Ideally this is an async call that returns a Procession on // replay that has the cached values. var shifter = conference.request('first', { test: true }).shifter() async(function () { shifter.dequeue(async()) }, function (envelope) { conference.boundary() if (conference.replaying) { assert(envelope, 1, 'request envelope') } }, function () { shifter.dequeue(async()) }, function (envelope) { if (conference.replaying) { assert(envelope, null, 'request eos') } }, function () { conference.record(function (callback) { callback(null, 'x') }, async()) }, function (result) { assert(result, 'x', 'record error-first callback') }) }), naturalized: cadence(function (async) { return null }), catalog: cadence(function (async, conference, value) { if (conference.replaying) { assert(value, 1, 'cataloged') } return [] }), message: cadence(function (async, conference, value) { return value - 1 }), government: cadence(function (async, conference) { if (conference.government.promise == '1/0') { assert(true, 'got a government') } }), messages: cadence(function (async, conference, reduction) { if (conference.id == 'third') { assert(reduction.request, 1, 'reduced request') assert(reduction.arrayed.sort(function (a, b) { return Monotonic.compare(a.promise, b.promise) }), [{ promise: '1/0', id: 'first', value: 0 }, { promise: '2/0', id: 'second', value: 0 }, { promise: '3/0', id: 'third', value: 0 }], 'reduced responses') console.log("REDUCED UNLATCH") reduced.unlatch() } }), exile: cadence(function (async, conference) { if (conference.id == 'third') { assert(conference.government.exile, { id: 'fourth', promise: '5/0', properties: { key: 'value', url: 'http://127.0.0.1:8888/fourth/' } }, 'exile') } }) } function createConference () { return new Conference(reactor, function (constructor) { constructor.responder() constructor.setProperties({ key: 'value' }) constructor.bootstrap() constructor.join() constructor.immigrate(cadence(function (async) {})) constructor.naturalized() constructor.exile() constructor.government() constructor.socket() constructor.receive('message') constructor.reduced('message', 'messages') constructor.method('catalog') }) } return createConference }
JavaScript
0
@@ -316,16 +316,24 @@ ponder: +cadence( function @@ -334,16 +334,23 @@ nction ( +async, conferen @@ -479,16 +479,17 @@ %7D +) ,%0A
700ec37817148fdb6df64e1ddbd1529c90987d5e
fix player hp is recovered upon death and then saved to database
app/classes/Player.js
app/classes/Player.js
import Prefab from './entityPrefab' import Weapon from './Weapon' import armorProperties from '../properties/armorProperties.json' import playerProperties from '../properties/playerProperties.json' import { socket } from '../sockets' import HealthBar from '../states/utils/HealthBar.js' /* global StackQuest, Phaser */ // client side class for Playable Characters export default class Player extends Prefab { constructor(game, name, player) { super(game, name, { x: player.x, y: player.y }, player.class) this.player = player this.anchor.set(0.5, 0.2) this.orientation = 4 // down this.absorbProperties(playerProperties[player.class]) this.stats.hp = player.hp this.setAnimationFrames(this) this.lootCount = 0 this.loadControls() this.movePlayer = this.movePlayer.bind(this) this.moveOther = this.moveOther.bind(this) this.equipWeapon = this.equipWeapon.bind(this) this.equipWeapon(this.weaponKey) this.attack = this.attack.bind(this) this.equipArmor = this.equipArmor.bind(this) this.equipArmor(this.armorKey) this.takeDamage = this.takeDamage.bind(this) this.respawn = this.respawn.bind(this) this.playerHealthBar = new HealthBar(game, { x: player.x, y: player.y - 10 }) this.computeLifeBar() this.recoverHp = this.recoverHp.bind(this) this.savePlayer = this.savePlayer.bind(this) } equipWeapon(weaponKey) { this.weapon = new Weapon(this.game, this, weaponKey) this.weapon.name = weaponKey return true } equipArmor(armorKey) { this.armor = armorProperties[armorKey] this.armor.name = armorKey return true } loadControls() { this.cursors = {} this.cursors.up = this.game.input.keyboard.addKey(Phaser.Keyboard.W) this.cursors.down = this.game.input.keyboard.addKey(Phaser.Keyboard.S) this.cursors.right = this.game.input.keyboard.addKey(Phaser.Keyboard.D) this.cursors.left = this.game.input.keyboard.addKey(Phaser.Keyboard.A) this.cursors.chat = this.game.input.keyboard.addKey(Phaser.Keyboard.TAB) this.cursors.click = this.game.input.activePointer } moveOther(targetX, targetY) { const xDirection = this.position.x - targetX const yDirection = this.position.y - targetY const absDirection = Math.abs(xDirection) * 2 - Math.abs(yDirection) this.playerHealthBar.setPosition(this.position.x, this.position.y - 10) if (yDirection > 0) { this.orientation = 2 } else if (yDirection < 0) { this.orientation = 4 } if (xDirection > 0) { this.orientation = 1 } else if (xDirection < 0) { this.orientation = 3 } this.animations.play(`walk_${this.orientationsDict[this.orientation]}`, null, true) if (this.game) { this.moveTween = this.game.add.tween(this.position).to({ x: targetX, y: targetY }) this.moveTween.onComplete.add(this.completeMovement, this) this.moveTween.start() } } completeMovement() { this.animations.stop() } takeDamage(damage) { const damageTaken = damage - (this.stats.defense + this.armor.defense) if (damageTaken > 0) { this.stats.hp -= damageTaken const damageText = StackQuest.game.add.text(this.x + Math.random() * 20, this.y + Math.random() * 20, damageTaken, { font: '32px Times New Roman', fill: '#ffa500' }) setTimeout(() => damageText.destroy(), 500) socket.emit('updateStats', this.stats) this.computeLifeBar() // check if dead if (this.stats.hp <= 0) this.respawn() } } respawn() { // make them move to set location this.position.x = 500 this.position.y = 500 // Revive setTimeout(this.recoverHp, 100) socket.emit('updatePlayer', { playerPos: this.position, lootCount: 0 }) this.savePlayer() const respawnText = this.game.add.text(this.position.x, this.position.y, 'YOU DIED', { font: '32px Times New Roman', fill: '#ff0000' }) setTimeout(() => respawnText.destroy(), 1000) } recoverHp() { this.stats.hp = this.stats.maxHp this.computeLifeBar() } movePlayer() { this.body.velocity.x = 0 this.body.velocity.y = 0 this.playerHealthBar.setPosition(this.position.x, this.position.y - 10) if (this.cursors.up.isDown) { this.body.velocity.y = -200 this.orientation = 2 socket.emit('updatePlayer', { playerPos: this.position, lootCount: this.lootCount }) } if (this.cursors.down.isDown) { this.body.velocity.y = 200 this.orientation = 4 socket.emit('updatePlayer', { playerPos: this.position, lootCount: this.lootCount }) } if (this.cursors.left.isDown) { this.body.velocity.x = -200 this.orientation = 1 socket.emit('updatePlayer', { playerPos: this.position, lootCount: this.lootCount }) } if (this.cursors.right.isDown) { this.body.velocity.x = 200 this.orientation = 3 socket.emit('updatePlayer', { playerPos: this.position, lootCount: this.lootCount }) } if (this.body.velocity.x + this.body.velocity.y !== 0) { this.animations.play(`walk_${this.orientationsDict[this.orientation]}`) } } attack() { if (this.cursors.click.isDown) { const targetX = this.game.input.worldX const targetY = this.game.input.worldY this.weapon.fire(null, targetX, targetY) socket.emit('fireProjectile', targetX, targetY) } } computeLifeBar() { if (this.stats.hp < 0) this.stats.hp = 0 const percent = Math.floor((this.stats.hp / this.stats.maxHp) * 100) this.playerHealthBar.setPercent(percent) } savePlayer() { this.player.x = this.x this.player.y = this.y this.player.hp = this.stats.hp socket.emit('savePlayer', this.player) } }
JavaScript
0
@@ -3666,30 +3666,76 @@ Timeout( -this.recoverHp +() =%3E %7B%0A this.recoverHp()%0A this.savePlayer()%0A %7D , 100)%0A @@ -3812,30 +3812,8 @@ 0 %7D) -%0A this.savePlayer() %0A%0A
ab305541283671398e90af37d56e834f8d700967
update TableHeader
src/_TableHeader/TableHeader.js
src/_TableHeader/TableHeader.js
/** * @file TableHeader component * @author liangxiaojun([email protected]) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import TableHeaderSortIcon from '../_TableHeaderSortIcon'; import PureRender from '../_vendors/PureRender'; @PureRender class TableHeader extends Component { constructor(props, ...restArgs) { super(props, ...restArgs); this.headerRenderer = ::this.headerRenderer; this.touchTapHandler = ::this.touchTapHandler; } headerRenderer() { const {header, colIndex} = this.props; switch (typeof header) { case 'function': return header(colIndex); default: return header; } } touchTapHandler(e) { e.preventDefault(); const {sortable, onSort} = this.props; sortable && onSort && onSort(); } render() { const { className, style, header, hidden, sortable, sortProp, sort, sortAscIconCls, sortDescIconCls } = this.props, finalHeader = this.headerRenderer(), tableHeaderClassName = classNames('table-header', { sortable: sortable, hidden: hidden, [className]: className }); return ( <th className={tableHeaderClassName} style={style} title={typeof header === 'string' ? header : null} onTouchTap={this.touchTapHandler}> <div className="table-header-inner"> {finalHeader} { sortable ? <TableHeaderSortIcon sort={sort} sortProp={sortProp} sortAscIconCls={sortAscIconCls} sortDescIconCls={sortDescIconCls}/> : null } </div> </th> ); } }; process.env.NODE_ENV !== 'production' && (TableHeader.propTypes = { className: PropTypes.string, style: PropTypes.object, header: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), colIndex: PropTypes.number, sortable: PropTypes.bool, sortProp: PropTypes.string, sort: PropTypes.object, sortAscIconCls: PropTypes.string, sortDescIconCls: PropTypes.string, hidden: PropTypes.bool, onSort: PropTypes.func }); TableHeader.defaultProps = { colIndex: 0, sortable: false, hidden: false }; export default TableHeader;
JavaScript
0
@@ -129,44 +129,8 @@ t';%0A -import PropTypes from 'prop-types';%0A impo @@ -2137,16 +2137,20 @@ %7D%0A%7D;%0A%0A +if ( process. @@ -2166,29 +2166,80 @@ ENV -! += == ' -production' && ( +development') %7B%0A%0A const PropTypes = require('prop-types');%0A%0A Tabl @@ -2261,24 +2261,28 @@ es = %7B%0A%0A + + className: P @@ -2298,24 +2298,28 @@ string,%0A + + style: PropT @@ -2332,16 +2332,20 @@ bject,%0A%0A + head @@ -2405,24 +2405,28 @@ func%5D),%0A + + colIndex: Pr @@ -2441,24 +2441,28 @@ number,%0A + + sortable: Pr @@ -2475,24 +2475,28 @@ s.bool,%0A + + sortProp: Pr @@ -2503,32 +2503,36 @@ opTypes.string,%0A + sort: PropTy @@ -2543,24 +2543,28 @@ object,%0A + + sortAscIconC @@ -2585,24 +2585,28 @@ string,%0A + + sortDescIcon @@ -2628,24 +2628,28 @@ string,%0A + + hidden: Prop @@ -2665,16 +2665,20 @@ l,%0A%0A + + onSort: @@ -2693,19 +2693,25 @@ s.func%0A%0A -%7D); + %7D;%0A%0A%7D %0A%0ATableH
18f193d829632681a81b48606279fb4f40dcabf9
Fix typo.
server/lib/logger.js
server/lib/logger.js
//module meant for logging to stdout and stderr to the user of immediate information var winston = require('winston'); var config = require('./config'); var cwl = require('./cwl'); let cloudWatchLogsEnabled = config.aws && config.aws.cloudWatchLogs; if (cloudWatchLogsEnabled) { cwl.setupCloudWatchLogs( config.aws.awsRegion, config.aws.cloudWatchLogs.logGroupName, config.aws.cloudWathLogs.logStreamName, function(err) { if (err) { cloudWatchLogsEnabled = false; return; } cwl.startLogging(10000); } ); } let logLevel = "debug"; if (config.logLevel === "ERROR") { logLevel = "error"; } else if (config.logLevel === "INFO") { logLevel = "info"; } const logger = new winston.Logger({ transports: [ new winston.transports.Console({ colorize: true, timestamp: true, level: logLevel }), new winston.transports.File({ level: logLevel, name: 'manticore', filename: 'manticore.log' }) ], exitOnError: false }); module.exports = { debug: function(msg) { logger.debug(msg); if (cloudWatchLogsEnabled) { cwl.queueLog(msg); } }, error: function(msg) { logger.error(msg); if (cloudWatchLogsEnabled) { cwl.queueLog(msg); } }, info: function(msg) { logger.info(msg); if (cloudWatchLogsEnabled) { cwl.queueLog(msg); } } }
JavaScript
0.001604
@@ -387,16 +387,17 @@ cloudWat +c hLogs.lo
e5d54001b5947008ebd6efa9a2cf16010c9a95f3
Rename inlineStyles to componentStyles.
src/start/DevAuthScreen.js
src/start/DevAuthScreen.js
/* @flow */ import { connect } from 'react-redux'; import React, { PureComponent } from 'react'; import { ActivityIndicator, View, StyleSheet, FlatList } from 'react-native'; import type { Auth, Context, DevUser, Dispatch } from '../types'; import { ErrorMsg, Label, Screen, ZulipButton } from '../common'; import { devListUsers, devFetchApiKey } from '../api'; import { getAuth } from '../selectors'; import { loginSuccess } from '../actions'; const inlineStyles = StyleSheet.create({ accountItem: { height: 10 }, heading: { flex: 0 }, heading2: { fontSize: 20, }, }); type Props = { auth: Auth, dispatch: Dispatch, }; type State = { progress: boolean, directAdmins: DevUser[], directUsers: DevUser[], error: string, }; class DevAuthScreen extends PureComponent<Props, State> { context: Context; props: Props; state: State = { progress: false, directAdmins: [], directUsers: [], error: '', }; static contextTypes = { styles: () => null, }; componentDidMount = () => { const { auth } = this.props; this.setState({ progress: true, error: undefined }); (async () => { try { const [directAdmins, directUsers] = await devListUsers(auth); this.setState({ directAdmins, directUsers, progress: false }); } catch (err) { this.setState({ error: err.message }); } finally { this.setState({ progress: false }); } })(); }; tryDevLogin = async (email: string) => { const { auth } = this.props; this.setState({ progress: true, error: undefined }); try { const apiKey = await devFetchApiKey(auth, email); this.props.dispatch(loginSuccess(auth.realm, email, apiKey)); this.setState({ progress: false }); } catch (err) { this.setState({ progress: false, error: err.message }); } }; render() { const { styles } = this.context; const { directAdmins, directUsers, error, progress } = this.state; return ( <Screen title="Pick a dev account"> <View style={styles.container}> {progress && <ActivityIndicator />} {!!error && <ErrorMsg error={error} />} <Label style={[styles.field, inlineStyles.heading2, inlineStyles.heading]} text="Administrators" /> {directAdmins.map(admin => ( <ZulipButton key={admin.email} text={admin.email} onPress={() => this.tryDevLogin(admin.email)} /> ))} <Label style={[styles.field, inlineStyles.heading2, inlineStyles.heading]} text="Normal users" /> <FlatList data={directUsers.map(user => user.email)} keyExtractor={(item, index) => item} ItemSeparatorComponent={() => <View style={inlineStyles.accountItem} />} renderItem={({ item }) => ( <ZulipButton key={item} text={item} secondary onPress={() => this.tryDevLogin(item)} /> )} /> </View> </Screen> ); } } export default connect(state => ({ auth: getAuth(state), }))(DevAuthScreen);
JavaScript
0
@@ -447,22 +447,25 @@ %0A%0Aconst -inline +component Styles = @@ -2211,38 +2211,41 @@ %7B%5Bstyles.field, -inline +component Styles.heading2, @@ -2237,38 +2237,41 @@ tyles.heading2, -inline +component Styles.heading%5D%7D @@ -2587,22 +2587,25 @@ .field, -inline +component Styles.h @@ -2613,22 +2613,25 @@ ading2, -inline +component Styles.h @@ -2867,14 +2867,17 @@ le=%7B -inline +component Styl
d64f305e97c14b1d9559be7acd9192ccb87cb78c
Remove unused props
app/components/Pin.js
app/components/Pin.js
import React, { Component, PropTypes } from 'react'; import { MODE_NAMES, MODES } from '../reducers/microcontrollerEnums'; import { intersection, propOr } from 'ramda'; import DigitalInput from './Pin/DigitalInput'; import AnalogInput from './Pin/AnalogInput'; import DigitalOutput from './Pin/DigitalOutput'; import AnalogOutput from './Pin/AnalogOutput'; import './Pin.sass'; export default class Pin extends Component { static propTypes = { name: PropTypes.string.isRequired, tags: PropTypes.array.isRequired, pin: PropTypes.object.isRequired, changeMode: PropTypes.func.isRequired, setEnabled: PropTypes.func.isRequired, listen: PropTypes.func.isRequired, digitalWrite: PropTypes.func.isRequired, analogWrite: PropTypes.func.isRequired, }; render() { const { changeMode, setEnabled, listen, digitalWrite, analogWrite, pin, name, tags } = this.props; const { id, mode, values } = pin; const supportedModes = intersection( pin.supportedModes, Object.keys(MODE_NAMES).map(k => parseInt(k, 10)) ); const getModeDescriptionForModeNumber = (num) => propOr('Not Set', num, MODE_NAMES); const modeSelector = ( <select defaultValue="{defaultMode}" onChange={event => changeMode(pin, event.target.value)} disabled={supportedModes.length === 0} > {supportedModes.map((supportedMode) => ( <option key={supportedMode} value={supportedMode}> {getModeDescriptionForModeNumber(supportedMode)} </option> ) )} </select> ); const pinClass = pin.isAnalogPin ? 'pin pin--analog' : 'pin pin--digital'; const pinControls = () => { switch (mode) { case MODES.INPUT: return ( <div className="pin__controls"> <DigitalInput listen={() => listen(id, mode, name)} values={values} /> </div> ); case MODES.ANALOG: return ( <div className="pin__controls"> <AnalogInput listen={() => listen(id, mode, name)} values={values} /> </div> ); case MODES.OUTPUT: return ( <div className="pin__controls"> <DigitalOutput write={(value) => digitalWrite(id, value)} /> </div> ); case MODES.PWM: return ( <div className="pin__controls"> <AnalogOutput write={(value) => analogWrite(id, value)} /> </div> ); default: return <div></div>; } }; return ( <div className={pinClass}> <div className="pin__header"> <h2 className="pin__name">{name}</h2> {tags.map((tag) => <div key={tag} className="pin__tag">{tag}</div> )} </div> <div className="pin__settings"> <input type="checkbox" name="Enabled" checked={pin.enabled} onChange={(e) => setEnabled(pin.id, e.target.checked)} /> Enabled {modeSelector} </div> {pinControls(mode)} </div> ); } }
JavaScript
0.000001
@@ -645,47 +645,8 @@ ed,%0A - listen: PropTypes.func.isRequired,%0A @@ -801,22 +801,8 @@ ed,%0A - listen,%0A @@ -1838,46 +1838,8 @@ nput - listen=%7B() =%3E listen(id, mode, name)%7D val @@ -2006,46 +2006,8 @@ nput - listen=%7B() =%3E listen(id, mode, name)%7D val
a8e2eb3d68dd38d4dd8a6f540caaac7a31763655
Remove useless return
components/catalog/harvests/index.js
components/catalog/harvests/index.js
import React from 'react' import PropTypes from 'prop-types' import { translate } from 'react-i18next' import Table from './table' const Harvests = ({ catalog, harvests, t }) => { return ( <section> <div> <Table catalog={catalog} harvests={harvests} /> </div> <div /> <style jsx>{` section { display: flex; } div { flex: 1 1; } `}</style> </section> ) } Harvests.propTypes = { catalog: PropTypes.shape({ _id: PropTypes.string.isRequired }).isRequired, harvests: PropTypes.arrayOf(PropTypes.shape({ })).isRequired, t: PropTypes.func.isRequired } export default translate('catalogs')(Harvests)
JavaScript
0.000219
@@ -176,24 +176,11 @@ ) =%3E - %7B%0A return (%0A - %3Cs @@ -195,18 +195,14 @@ - %3Cdiv%3E%0A - @@ -259,19 +259,15 @@ - %3C/div%3E%0A - @@ -279,18 +279,16 @@ /%3E%0A%0A - - %3Cstyle j @@ -293,18 +293,16 @@ jsx%3E%7B%60%0A - se @@ -317,18 +317,16 @@ - display: @@ -342,15 +342,11 @@ - - %7D%0A%0A - @@ -353,18 +353,16 @@ div %7B%0A - @@ -382,14 +382,10 @@ - %7D%0A +%7D%0A @@ -397,18 +397,16 @@ tyle%3E%0A - - %3C/sectio @@ -412,13 +412,9 @@ on%3E%0A - )%0A%7D +) %0A%0AHa
7b0eb086087ad24e164b6b76b8d409c522739e70
fix warning positioning
src/game/meteor_warning.js
src/game/meteor_warning.js
game.module('game.meteor_warning') .require('game.b2dvec') .body(function() { game.addAsset('warning.png'); game.createClass('MeteorWarning', { init: function(x, y, size, velocity) { this.sprite = new game.Sprite('warning.png', x, y, {width: size, height: size, anchor: {x: 0.5, y: 0.5}}); this.sprite.addTo(game.scene.stage); game.scene.addObject(this); this.velocity = velocity; this.size = size; this.blinkTime = 1800; this.blinkInterval = this.blinkTime / 10; this.blinkIntervalElapsed = 0; this.getEdgePos(); }, update: function() { this.blinkTime -= 1000 * game.system.delta; this.blinkIntervalElapsed += 1000 * game.system.delta; if (this.blinkTime <= 0) { this.sprite.remove(); game.scene.removeObject(this); } // if (this.blinkIntervalElapsed >= this.blinkInterval) { // this.blinkIntervalElapsed = 0; // this.sprite.visible = !this.sprite.visible; // } }, getEdgePos: function() { var pos = this.sprite.position; var fraction = 0; // if (pos.x < 0 && pos.y > 0) { // fraction = pos.x / this.velocity.x; // pos.y = this.velocity.y * fraction; // } else if (pos.x > game.system.width && pos.y > 0) { // fraction = (pos.x - game.system.width) / this.velocity.x; // pos.y = this.velocity.y * fraction; // } else if (pos.y < 0 && pos.x > 0 && pos.x < game.system.width) { // fraction = pos.y / this.velocity.y; // pos.x = this.velocity.x * fraction; // } if (pos.x < 0) { pos.x = 0; } else if (pos.x + this.size > game.system.width) { pos.x = game.system.width - this.size; } if (pos.y < 0) { pos.y = 0; } this.sprite.position.x = pos.x; this.sprite.position.y = pos.y; } }); });
JavaScript
0.000001
@@ -943,27 +943,24 @@ %0A - // if (this.bl @@ -1006,35 +1006,32 @@ l) %7B%0A - // this.blinkI @@ -1057,27 +1057,24 @@ %0A - // this.sp @@ -1121,19 +1121,16 @@ - // %7D%0A @@ -1255,19 +1255,16 @@ - // if (pos @@ -1270,200 +1270,21 @@ s.x -%3C 0 && pos.y %3E 0) %7B%0A // fraction = pos.x / this.velocity.x;%0A // pos.y = this.velocity.y * fraction;%0A // %7D else if (pos.x %3E game.system.width && pos.y %3E +- this.size %3C 0) @@ -1300,392 +1300,34 @@ - // -fraction = (pos.x - game.system.width) / this.velocity.x;%0A // pos.y = this.velocity.y * fraction;%0A // %7D else if (pos.y %3C 0 && pos.x %3E 0 && pos.x %3C game.system.width) %7B%0A // fraction = pos.y / this.velocity.y;%0A // pos.x = this.velocity.x * fraction;%0A // %7D%0A%0A if (pos.x %3C 0) %7B%0A pos.x = 0 +pos.x = 0 + this.size ;%0A @@ -1479,16 +1479,32 @@ (pos.y +- this.size / 2 %3C 0) %7B%0A @@ -1523,24 +1523,40 @@ pos.y = 0 + + this.size / 2 ;%0A
644d081af58a19aabcff04fcdc98c22e2cf2afb6
Update gatsby-browser.js (#3694)
examples/using-page-transitions/gatsby-browser.js
examples/using-page-transitions/gatsby-browser.js
/* eslint-disable react/prop-types */ /* globals window CustomEvent */ import React, { createElement } from "react" import { Transition } from "react-transition-group" import createHistory from "history/createBrowserHistory" import getTransitionStyle from "./src/utils/getTransitionStyle" const timeout = 250 const historyExitingEventType = `history::exiting` const getUserConfirmation = (pathname, callback) => { const event = new CustomEvent(historyExitingEventType, { detail: { pathname } }) window.dispatchEvent(event) setTimeout(() => { callback(true) }, timeout) } const history = createHistory({ getUserConfirmation }) // block must return a string to conform history.block((location, action) => location.pathname) exports.replaceHistory = () => history class ReplaceComponentRenderer extends React.Component { constructor(props) { super(props) this.state = { exiting: false, nextPageResources: {} } this.listenerHandler = this.listenerHandler.bind(this) } listenerHandler(event) { const nextPageResources = this.props.loader.getResourcesForPathname( event.detail.pathname, nextPageResources => this.setState({ nextPageResources }) ) || {} this.setState({ exiting: true, nextPageResources }) } componentDidMount() { window.addEventListener(historyExitingEventType, this.listenerHandler) } componentWillUnmount() { window.removeEventListener(historyExitingEventType, this.listenerHandler) } componentWillReceiveProps(nextProps) { if (this.props.location.key !== nextProps.location.key) { this.setState({ exiting: false, nextPageResources: {} }) } } render() { const transitionProps = { timeout: { enter: 0, exit: timeout, }, appear: true, in: !this.state.exiting, key: this.props.location.key, } return ( <Transition {...transitionProps}> { (status) => createElement(this.props.pageResources.component, { ...this.props, ...this.props.pageResources.json, transition: { status, timeout, style: getTransitionStyle({ status, timeout }), nextPageResources: this.state.nextPageResources, }, }) } </Transition> ) } } // eslint-disable-next-line react/display-name exports.replaceComponentRenderer = ({ props, loader }) => { if (props.layout) { return undefined } return createElement(ReplaceComponentRenderer, { ...props, loader }) }
JavaScript
0
@@ -430,12 +430,57 @@ t = -new +document.createEvent(%22CustomEvent%22);%0A event.init Cust @@ -511,16 +511,30 @@ entType, + false, false, %7B detai @@ -551,16 +551,17 @@ ame %7D %7D) +; %0A windo @@ -2589,8 +2589,9 @@ der %7D)%0A%7D +%0A
b26ad4bbee5b254d617945b22604f55effe9b238
Fix gameover score bug
src/game.js
src/game.js
Lettris.Game = function (game) { }; Lettris.Game.prototype = { create: function (game) { // Physics stuff game.physics.startSystem(Phaser.Physics.P2JS); game.physics.p2.setBoundsToWorld(true, true, false, true) game.physics.p2.gravity.y = 300; game.physics.p2.restitution = 0.05 game.world.setBounds(0, 0, game.width, game.height-80); this.gameData = {score: 0, karma: 0} this.gui = new GUI(game, this.gameData) this.bag = new Bag(game, 'let-eng-std', this.gameData, this.gui.boxClicked) this.boxes = game.add.group(); // Start box-droping loop game.time.events.loop(Phaser.Timer.SECOND * 2, this.spawn_box, this) }, spawn_box: function () { // check if any box is stuck above screen => game over this.boxes.forEach(function(box) { if( box.y < 0) this.state.start('GameOver', true, false, this.gui.score); }, this); // put out a new box var widthHalf = this.game.cache.getImage('box').width / 2; var pos = this.game.rnd.integerInRange( widthHalf + 1, this.game.width - widthHalf - 1); var box = this.bag.dropBox(pos) console.log(this.gameData.karma) this.boxes.add(box) }, };
JavaScript
0
@@ -856,18 +856,23 @@ , this.g -ui +ameData .score);
3661957bd2d7f416fdb5e22174d217d0a01ec93a
add fix hidden block for bulma.js
js/bulma.js
js/bulma.js
// The following code is based off a toggle menu by @Bradcomp // source: https://gist.github.com/Bradcomp/a9ef2ef322a8e8017443b626208999c1 (function() { var burger = document.querySelector('.nav-toggle'); var menu = document.querySelector('.nav-menu'); burger.addEventListener('click', function() { burger.classList.toggle('is-active'); menu.classList.toggle('is-active'); }); })(); $(document).ready(function(){ $("#menu").on("click","a", function (event) { event.preventDefault(); var id = $(this).attr('href'), top = $(id).offset().top; $('body,html').animate({scrollTop: top}, 1000); }); $(".show-auto-button").on('click', function () { console.log($('.auto-list').length); $('.auto-list').show(); $('.show-auto-button').hide(); }); }); $("#toyotaCamry-1").click(function() { $("#modalToyotaCamry").addClass("is-active"); }); $("#mercedesBenzE-1").click(function() { $("#modalMercedesBenzE").addClass("is-active"); }); $("#mercedesBenzSprinter-1").click(function() { $("#modalMercedesBenzSprinter").addClass("is-active"); }); $("#mercedesBenzS-1").click(function() { $("#modalMercedesBenzS").addClass("is-active"); }); $("#lexusLX570-1").click(function() { $("#modalLexusLX570").addClass("is-active"); }); $("#toyotaCamry-2").click(function() { $("#modalToyotaCamry").addClass("is-active"); }); $("#mercedesBenzE-2").click(function() { $("#modalMercedesBenzE").addClass("is-active"); }); $("#mercedesBenzS-2").click(function() { $("#modalMercedesBenzS").addClass("is-active"); }); $("#mercedesBenzSprinter-2").click(function() { $("#modalMercedesBenzSprinter").addClass("is-active"); }); $("#lexusLX570-2").click(function() { $("#modalLexusLX570").addClass("is-active"); }); $("#toyotaCamry-3").click(function() { $("#modalToyotaCamry").addClass("is-active"); }); $("#mercedesBenzE-3").click(function() { $("#modalMercedesBenzE").addClass("is-active"); }); $("#mercedesBenzS-3").click(function() { $("#modalMercedesBenzS").addClass("is-active"); }); $("#mercedesBenzSprinter-3").click(function() { $("#modalMercedesBenzSprinter").addClass("is-active"); }); $("#lexusLX570-3").click(function() { $("#modalLexusLX570").addClass("is-active"); }); $(".car-modal-close").click(function() { $(".modal").removeClass("is-active"); });
JavaScript
0
@@ -711,40 +711,40 @@ g($( -'.auto-list').length);%0A $ +this));%0A $(this).siblings ('.a
df9dec0bacd6687dbdaff3980e0698b240c1d8ae
rename noodle.js to long_noodle.js
web.js
web.js
// node.js server for long polling message passing // start with: // node web.js // // POST requests // ------------- // the post data is stored for the specified request path // a version number is incremented if there is no version request parameter // the version number is stored if it is in the request parameter // if dataType=json is specified the post data is considered to be valid json e.g. {message:'yomama'} // // GET requests // ------------ // the connection will be held open until there is a POST for the specified path // to wait based on a version number it can be specified e.g. version=99 // if you request version=99 and the current message version is 50 then the connection will remain open until the next message // if you request version=199 and the current message version is 150 then the message will be returned immediately // to get the last message sent for the path specify version=0 since the current message is undoubtedly higher // if callback=MYMETHOD is specified then the result is wrapped in a js function e.g. MYMETHOD( {body:'yomama', version:1} // or MYMETHOD( {json:{method:'yomama'}, version:1} // using a callback provides cross site support var http = require('http'); var fs = require('fs'); var PORT = process.env.PORT || 8000; var TOKEN = process.env.TOKEN || 'TOKEN'; var MAX_MESSAGE_LENGTH = 2048; require('./json2.js'); var Broadcast = require('./broadcast.js'); var server = http.createServer(function (request, response) { var parsed = require('url').parse( request.url, true ); var path = parsed.pathname; var params = parsed.query; var version = parseInt(params.version); var callback = params.callback; var dataType = params.dataType; if( request.method == "GET" ) { //get the current message for the path or wait for the next one console.log( "GET " + path); if( ['/test.html', '/json2.js','/noodle.js'].indexOf( path ) >= 0) { response.writeHead(200, {'Content-Type': 'text/html'}); response.write(fs.readFileSync(__dirname + path, 'utf8')); // <--- add this line response.end(); } else { response.writeHead(200, {'Content-Type': 'text/plain'}); Broadcast.add( path, version, response, callback ); } } else { //post data broadcasts to any listeners for the path console.log( "POST " + path); if( params.token != TOKEN ) { response.writeHead( 403, {'Content-Type': 'text/plain'}); response.end( "not authorized for posting messages without a valid 'token'\n" ); return; } var body = ''; request.on( 'data', function(data) { if( body.length > MAX_MESSAGE_LENGTH ) { return; } body += data.toString(); console.log( body ); if( body.length > MAX_MESSAGE_LENGTH ) { response.writeHead( 406, {'Content-Type': 'text/plain'}); response.end( "message length exceeds " + MAX_MESSAGE_LENGTH + " bytes\n" ); } }); request.on( 'end', function() { //once the whole message has been received then broadcast it Broadcast.send( path, body, dataType, version ); response.end('success\n'); console.log( 'end' ); }); } }); server.listen(PORT, "0.0.0.0"); console.log("Listening on " + PORT);
JavaScript
0.999999
@@ -1877,16 +1877,21 @@ 2.js','/ +long_ noodle.j
0d48bd1aad5271d3b4ca301a9946b533d5cb58f9
Add url of origin for Settings.BASE_URL
js/saiku/Settings.js
js/saiku/Settings.js
/* * Copyright 2012 OSBI Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Change settings here */ var Settings = { VERSION: "Saiku 3.0-SNAPSHOT", BIPLUGIN: false, BIPLUGIN5: false, BASE_URL: "", TOMCAT_WEBAPP: "/saiku", REST_MOUNT_POINT: "/rest/saiku/", DIMENSION_PREFETCH: true, DIMENSION_SHOW_ALL: true, DIMENSION_SHOW_REDUCED: false, ERROR_LOGGING: false, // number of erroneous ajax calls in a row before UI cant recover ERROR_TOLERANCE: 3, QUERY_PROPERTIES: { 'saiku.olap.query.automatic_execution': true, 'saiku.olap.query.nonempty': true, 'saiku.olap.query.nonempty.rows': true, 'saiku.olap.query.nonempty.columns': true, 'saiku.ui.render.mode' : 'table', 'saiku.olap.query.filter' : true, 'saiku.olap.result.formatter' : "flattened" }, TABLE_LAZY: true, // Turn lazy loading off / on TABLE_LAZY_SIZE: 1000, // Initial number of items to be rendered TABLE_LAZY_LOAD_ITEMS: 20, // Additional item per scroll TABLE_LAZY_LOAD_TIME: 20, // throttling call of lazy loading items /* Valid values for CELLSET_FORMATTER: * 1) flattened * 2) flat */ CELLSET_FORMATTER: "flattened", // limits the number of rows in the result // 0 - no limit RESULT_LIMIT: 0, MEMBERS_FROM_RESULT: true, MEMBERS_LIMIT: 3000, MEMBERS_SEARCH_LIMIT: 75, ALLOW_IMPORT_EXPORT: false, ALLOW_PARAMETERS: false, PLUGINS: [ "Chart" ], DEFAULT_VIEW_STATE: 'view', // could be 'edit' as well DEMO: false, TELEMETRY_SERVER: 'http://telemetry.analytical-labs.com:7000', LOCALSTORAGE_EXPIRATION: 10 * 60 * 60 * 1000 /* 10 hours, in ms */, UPGRADE: true }; /** * Extend settings with query parameters */ Settings.GET = function () { var qs = document.location.search; qs = qs.split("+").join(" "); var params = {}, tokens, re = /[?&]?([^=]+)=([^&]*)/g; while (tokens = re.exec(qs)) { var value = decodeURIComponent(tokens[2]); if (! isNaN(value)) value = parseInt(value); if (value === "true") value = true; if (value === "false") value = false; params[decodeURIComponent(tokens[1]).toUpperCase()] = value; } return params; }(); _.extend(Settings, Settings.GET); Settings.PARAMS = (function() { var p = {}; for (var key in Settings) { if (key.match("^PARAM")=="PARAM") { p[key] = Settings[key]; } } return p; }()); Settings.REST_URL = Settings.BASE_URL + Settings.TOMCAT_WEBAPP + Settings.REST_MOUNT_POINT; // lets assume we dont need a min width/height for table mode if (Settings.MODE == "table") { Settings.DIMENSION_PREFETCH = false; $('body, html').css('min-height',0); $('body, html').css('min-width',0); } if (Settings.BIPLUGIN5) { Settings.BIPLUGIN = true; } Settings.INITIAL_QUERY = false; if (document.location.hash) { var hash = document.location.hash; if (hash.length > 11 && hash.substring(1, 11) == "query/open") { Settings.INITIAL_QUERY = true; } } /** * < IE9 doesn't support Array.indexOf */ if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length >>> 0; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) { if (from in this && this[from] === elt) return from; } return -1; }; } var tagsToReplace = { '&': '&amp;', '<': '&lt;', '>': '&gt;' }; function replaceTag(tag) { return tagsToReplace[tag] || tag; } function safe_tags_replace(str) { return str.replace(/[&<>]/g, replaceTag); } if ($.blockUI) { $.blockUI.defaults.css = {}; $.blockUI.defaults.overlayCSS = {}; $.blockUI.defaults.blockMsgClass = 'processing'; $.blockUI.defaults.fadeOut = 0; $.blockUI.defaults.fadeIn = 0; $.blockUI.defaults.ignoreIfBlocked = false; } if (window.location.hostname && (window.location.hostname == "dev.analytical-labs.com" || window.location.hostname == "demo.analytical-labs.com" )) { Settings.USERNAME = "admin"; Settings.PASSWORD = "admin"; Settings.DEMO = true; Settings.UPGRADE = false; } var isIE = (function(){ var undef, v = 3; var dav = navigator.appVersion; if(dav.indexOf('MSIE') != -1) { v = parseFloat(dav.split('MSIE ')[1]); return v> 4 ? v : false; } return false; }());
JavaScript
0.000002
@@ -754,10 +754,30 @@ RL: -%22%22 +window.location.origin ,%0A @@ -3151,32 +3151,8 @@ RL = - Settings.BASE_URL%0A + Set
f482d820f30c0eb45fcca5cb6f7831204c77daba
Fix dashboard analytics for 'Used dashboard Scripts API'
src/apps/Script/ScriptStore.js
src/apps/Script/ScriptStore.js
import Reflux from 'reflux'; import _ from 'lodash'; import { SnackbarNotificationMixin, StoreFormMixin, WaitForStoreMixin } from '../../mixins'; import Actions from './ScriptActions'; import SessionStore from '../Session/SessionStore'; import SessionActions from '../Session/SessionActions'; export default Reflux.createStore({ listenables: Actions, mixins: [ SnackbarNotificationMixin, StoreFormMixin, WaitForStoreMixin ], scriptConfigValueTypes: [ { payload: 'string', text: 'String' }, { payload: 'integer', text: 'Integer' } ], sendScriptAnalytics(type, payload) { window.analytics.track('Used Dashboard Scripts API', { type, instance: payload.instanceName, scriptId: payload.id, sourceLength: payload.source.length, runtime: payload.runtimeName }); }, getInitialState() { return { currentScript: null, scriptConfig: [], traces: [], traceIsLoading: true, lastTraceResult: null, lastTraceStatus: null, lastTraceDuration: null, lastTraceReady: true, isLoading: true, configValueType: 'string' }; }, init() { this.data = this.getInitialState(); this.listenToForms(); this.waitFor( SessionActions.setInstance, this.refreshData ); }, refreshData() { const { scriptId } = SessionStore.getParams(); if (scriptId) { Actions.fetchScript(scriptId); Actions.fetchScriptTraces(scriptId); } }, mapConfig(originalConfig) { const config = _.map(originalConfig, (value, key) => ({ key, value, type: _.isNumber(value) ? 'integer' : 'string' })); return _.sortBy(config, 'key'); }, clearCurrentScript() { this.data.currentScript = null; }, onFetchScriptCompleted(script) { this.data.scriptConfig = this.mapConfig(script.config); this.data.currentScript = script; this.trigger(this.data); }, getEditorMode() { const { currentScript } = this.data; return currentScript ? this.langMap[currentScript.runtime_name] : 'python'; }, fetchTraces() { if (this.data.currentScriptId === null) { return; } Actions.fetchScriptTraces(this.data.currentScript.id); }, onFetchScriptTraces() { if (this.data.lastTraceReady) { this.data.traceIsLoading = true; } this.trigger(this.data); }, onFetchScriptTracesCompleted(traces) { this.data.traces = traces; this.data.isLoading = false; this.getScriptLastTraceResult(); }, onFetchScriptTracesFailure() { this.data.traceIsLoading = false; this.trigger(this.data); }, onRunScriptCompleted() { this.dismissSnackbarNotification(); this.refreshData(); this.sendScriptAnalytics('run', this.data.currentScript); }, onRunScriptFailure() { this.dismissSnackbarNotification(); this.sendScriptAnalytics('run_failure', this.data.currentScript); }, getScriptLastTraceResult() { this.data.lastTraceResult = null; this.data.lastTraceStatus = null; this.data.lastTraceDuration = null; if (this.data.traces && this.data.traces.length) { const lastTrace = this.data.traces[0]; if (lastTrace.status === 'pending' || lastTrace.status === 'processing') { this.data.lastTraceReady = false; setTimeout(() => { this.fetchTraces(); }, 300); } else { this.data.lastTraceResult = lastTrace.result.stdout !== '' ? lastTrace.result.stdout : 'Success'; if (lastTrace.result.stderr !== '') { this.data.lastTraceResult = lastTrace.result.stderr; } if (lastTrace.result.__error__) { this.data.lastTraceResult = lastTrace.result.__error__; } this.data.lastTraceStatus = lastTrace.status; this.data.lastTraceDuration = lastTrace.duration; this.data.lastTraceReady = true; } } this.data.traceIsLoading = false; this.trigger(this.data); }, getScriptConfigValueTypes() { return this.scriptConfigValueTypes; }, onUpdateScriptCompleted(script) { this.data.currentScript = script; this.dismissSnackbarNotification(); this.refreshData(); this.sendScriptAnalytics('edit', this.data.currentScript); }, onUpdateScriptFailure() { this.dismissSnackbarNotification(); this.sendScriptAnalytics('edit_failure', this.data.currentScript); }, onFetchScriptTraceCompleted(trace) { const traceIndex = _.findIndex(this.data.traces, { id: trace.id }); this.data.traces[traceIndex] = trace; this.trigger(this.data); } });
JavaScript
0
@@ -843,17 +843,18 @@ .runtime -N +_n ame%0A
24baa48baf3752f77448f1b1a25d601fc683ee36
add oncing
reqres.js
reqres.js
// Copyright (c) 2015 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. 'use strict'; var EventEmitter = require('events').EventEmitter; var inherits = require('util').inherits; var emptyTracing = Buffer(25); // TODO: proper tracing object var emptyBuffer = Buffer(0); // TODO: provide streams for arg2/3 function TChannelIncomingRequest(id, options) { if (!(this instanceof TChannelIncomingRequest)) { return new TChannelIncomingRequest(id, options); } options = options || {}; var self = this; EventEmitter.call(self); self.id = id || 0; self.ttl = options.ttl || 0; self.tracing = options.tracing || emptyTracing; self.service = options.service || ''; self.headers = options.headers || {}; self.checksumType = options.checksumType || 0; self.name = options.name || ''; self.arg2 = options.arg2 || emptyBuffer; self.arg3 = options.arg3 || emptyBuffer; } inherits(TChannelIncomingRequest, EventEmitter); function TChannelIncomingResponse(id, options) { if (!(this instanceof TChannelIncomingResponse)) { return new TChannelIncomingResponse(id, options); } options = options || {}; var self = this; EventEmitter.call(self); self.id = id || 0; self.code = options.code || 0; self.arg1 = options.arg1 || emptyBuffer; self.arg2 = options.arg2 || emptyBuffer; self.arg3 = options.arg3 || emptyBuffer; self.ok = self.code === 0; // TODO: probably okay, but a bit jank } inherits(TChannelIncomingResponse, EventEmitter); function TChannelOutgoingRequest(id, options, sendFrame) { if (!(this instanceof TChannelOutgoingRequest)) { return new TChannelOutgoingRequest(id, options, sendFrame); } options = options || {}; var self = this; EventEmitter.call(self); self.id = id || 0; self.ttl = options.ttl || 0; self.tracing = options.tracing || emptyTracing; self.service = options.service || ''; self.headers = options.headers || {}; self.checksumType = options.checksumType || 0; self.sendFrame = sendFrame; } inherits(TChannelOutgoingRequest, EventEmitter); TChannelOutgoingRequest.prototype.send = function send(arg1, arg2, arg3, callback) { var self = this; self.sendFrame(arg1, arg2, arg3); if (callback) self.hookupCallback(callback); return self; }; TChannelOutgoingRequest.prototype.hookupCallback = function hookupCallback(callback) { var self = this; self.once('error', onError); self.once('response', onResponse); function onError(err) { self.removeListener('response', onResponse); callback(err, null); } function onResponse(res) { self.removeListener('error', onError); callback(null, res); } return self; }; function TChannelOutgoingResponse(id, options, sendFrame) { if (!(this instanceof TChannelOutgoingResponse)) { return new TChannelOutgoingResponse(id, options, sendFrame); } options = options || {}; var self = this; EventEmitter.call(self); self.id = id || 0; self.code = options.code || 0; self.tracing = options.tracing || emptyTracing; self.headers = options.headers || {}; self.checksumType = options.checksumType || 0; self.ok = true; self.name = options.name || ''; self.arg2 = options.arg2 || emptyBuffer; self.arg3 = options.arg3 || emptyBuffer; self.sendFrame = sendFrame; } inherits(TChannelOutgoingResponse, EventEmitter); TChannelOutgoingResponse.prototype.send = function send(err, res1, res2) { var self = this; if (err) { self.ok = false; var errArg = isError(err) ? err.message : JSON.stringify(err); // TODO: better self.sendFrame(self.name, res1, errArg); } else { self.sendFrame(self.name, res1, res2); } }; module.exports.IncomingRequest = TChannelIncomingRequest; module.exports.IncomingResponse = TChannelIncomingResponse; module.exports.OutgoingRequest = TChannelOutgoingRequest; module.exports.OutgoingResponse = TChannelOutgoingResponse; function isError(obj) { return typeof obj === 'object' && ( Object.prototype.toString.call(obj) === '[object Error]' || obj instanceof Error); }
JavaScript
0.000001
@@ -3113,32 +3113,55 @@ me = sendFrame;%0A + self.sent = false;%0A %7D%0A%0Ainherits(TCha @@ -3307,46 +3307,8 @@ is;%0A - self.sendFrame(arg1, arg2, arg3);%0A @@ -3352,16 +3352,174 @@ lback);%0A + if (self.sent) %7B%0A throw new Error('request already sent');%0A %7D%0A self.sent = true;%0A self.sendFrame(arg1, arg2, arg3);%0A self.emit('end');%0A retu @@ -4611,16 +4611,39 @@ dFrame;%0A + self.sent = false;%0A %7D%0A%0Ainher @@ -4776,32 +4776,131 @@ ar self = this;%0A + if (self.sent) %7B%0A throw new Error('response already sent');%0A %7D%0A self.sent = true;%0A if (err) %7B%0A @@ -5119,22 +5119,44 @@ res2);%0A - %7D%0A + self.emit('end');%0A %7D;%0A%0Amodu
fee64d8bab8683db79dc0c41e32ed39cd70822f0
Fix show proper fields at rules service selector
frontend/app/js/components/rules/selectservice.js
frontend/app/js/components/rules/selectservice.js
import React from 'react' import {i18n} from 'app/utils/i18n' const SelectService=React.createClass({ propTypes:{ onChange: React.PropTypes.func.isRequired, services: React.PropTypes.array.isRequired, service: React.PropTypes.shape({ uuid: React.PropTypes.string }) }, find_service(uuid){ return this.props.services.find( (s) => s.uuid == uuid ) }, componentDidMount(){ let self=this $(this.refs.service).dropdown({ onChange(value, text, $el){ self.props.onChange(self.find_service(value)) } }) this.setService() }, setService(){ $(this.refs.service).dropdown('set selected', this.props.defaultValue) }, render(){ const {services, defaultValue}=this.props return ( <div ref="service" className="ui fluid search normal selection dropdown"> <input type="hidden" defaultValue={defaultValue && defaultValue.uuid} name="service"/> <i className="dropdown icon"></i> <div className="default text">{i18n("Select service")}</div> <div className="menu"> <div className="item" data-value="">{i18n("No service")}</div> {services.map( (sv) => ( <div key={sv.uuid} className="item" data-value={sv.uuid}> {i18n(sv.name)} <span style={{float: "right", paddingLeft: 10, fontStyle: "italic", color: "#aaa"}}> {Object.keys(sv.config).map((k) => sv.config[k]).join(', ')} </span> </div> ))} </div> </div> ) } }) export default SelectService
JavaScript
0
@@ -680,16 +680,261 @@ e)%0A %7D,%0A + get_value(field)%7B%0A if (field.type=='service')%7B%0A const uuid = field.value%0A const service = this.props.services.find( s =%3E s.uuid == uuid )%0A if (service)%0A return service.name%0A %7D%0A else%0A return field.value%0A %7D,%0A render @@ -1641,54 +1641,69 @@ %7B -Object.keys(sv.config +sv.fields.filter( f =%3E f.card ).map( -(k + (f ) =%3E -sv.config%5Bk%5D +this.get_value(f) ).jo
a62bc375a4d6cfda0089ade84537a746ec0ddc33
Fix bug logic แถมฟรี
app/helpers/global.js
app/helpers/global.js
import _ from 'lodash'; export const isEmpty = value => _.isUndefined(value) || _.isEmpty(value); export const isNotEmpty = value => !isEmpty(value); export const changeCoin = value => { const baht10 = Math.floor(value / 10); const baht5 = Math.floor((value - baht10 * 10) / 5); const baht1 = Math.floor((value - baht10 * 10 - baht5 * 5) / 1); return { baht1, baht5, baht10, }; }; export const createLog = (type = '', bgColor = 'green', color = '#fff') => { if (type === 'app') return 'background: #333; color: #fff'; if (type === 'client') return 'background: green; color: #fff'; return `background: ${bgColor}; color: ${color}`; }; export const getCashRemaining = (remain) => { return { oneBahtCount: _.get(remain, 'baht1', 0), fiveBahtCount: _.get(remain, 'baht5', 0), tenBahtCount: _.get(remain, 'baht10', 0), }; }; export const verifyLessThanThreshold = (remain, thresHold) => { return getCashRemainingAmount(remain) < thresHold; }; export const verifyDuplicatedDiscount = (discounts, code) => { console.log('verifyDuplicatedDiscount', discounts, code); const discountAlreadyExist = _.find(discounts, discount => discount.code === code); if (discountAlreadyExist) return true; return false; }; export const getCashRemainingAmount = (remain) => { const { oneBahtCount, fiveBahtCount, tenBahtCount } = getCashRemaining(remain); return ((tenBahtCount * 10) + (fiveBahtCount * 5) + oneBahtCount); }; export const getEventInputByChannel = (eventInputs, channel) => { const channelToInput = channel === 'SMS' ? 'MSISDN' : 'EMAIL'; return _.find(eventInputs, input => input.name === channelToInput); }; export const getPhysicalUsedSlotNo = (product) => { const physicals = product.physicals || []; const usedPhysical = _.find(physicals, physical => physical.canDrop === true); return usedPhysical.slotNo; }; export const verifyThisOrderShouldDropFreeProduct = (sumOrderAmount, activityFreeRule) => { switch (activityFreeRule) { case 'ODD': return sumOrderAmount % 2 === 1; case 'EVEN': return sumOrderAmount % 2 === 0; case 'ALL': return true; default: return false; } };
JavaScript
0.000003
@@ -1971,16 +1971,73 @@ e) =%3E %7B%0A + const currentOrderNumber = Number(sumOrderAmount) + 1;%0A switch @@ -2083,38 +2083,42 @@ return -sumOrderAmount +currentOrderNumber %25 2 === 1;%0A @@ -2147,30 +2147,34 @@ return -sumOrderAmount +currentOrderNumber %25 2 ===
0ae174f83620164b5cb966c0649a62bc158bd44b
Prepare for release
js/consts.js
js/consts.js
var consts = {}; consts.isBeta = true;
JavaScript
0
@@ -31,9 +31,10 @@ a = -tru +fals e;
7865426bcb9d62272f439b6a6b9660b355b8d2c6
fix test
tests/integration/components/g-grid-heading-test.js
tests/integration/components/g-grid-heading-test.js
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('g-grid-heading', 'Integration | Component | g grid heading', { integration: true }); test('it renders', function(assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... });" this.render(hbs`{{g-grid-heading}}`); assert.equal(this.$().text().trim(), ''); // Template block usage:" this.render(hbs` {{#g-grid-heading}} template block text {{/g-grid-heading}} `); assert.equal(this.$().text().trim(), 'template block text'); });
JavaScript
0.000002
@@ -378,17 +378,16 @@ .. %7D);%22%0A -%0A this.r @@ -414,25 +414,24 @@ eading%7D%7D%60);%0A -%0A assert.equ @@ -462,200 +462,9 @@ ), ' -');%0A%0A // Template block usage:%22%0A this.render(hbs%60%0A %7B%7B#g-grid-heading%7D%7D%0A template block text%0A %7B%7B/g-grid-heading%7D%7D%0A %60);%0A%0A assert.equal(this.$().text().trim(), 'template block text +%E2%96%B3 ');%0A
8b2b0a30584179ca406412e304fac929b39eeb07
Remove ad script
src/html.js
src/html.js
import React from 'react' import PropTypes from 'prop-types' const HTML = props => ( <html {...props.htmlAttributes} lang="en"> <head> <meta charSet="utf-8" /> <meta httpEquiv="x-ua-compatible" content="ie=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <link rel="dns-prefetch" href="//www.google-analytics.com" /> {/* <link rel="dns-prefetch" href="//vc.hotjar.io" /> */} <link rel="dns-prefetch" href="//pagead2.googlesyndication.com" /> {props.headComponents} </head> <body {...props.bodyAttributes}> {props.preBodyComponents} <div key={`body`} id="___gatsby" dangerouslySetInnerHTML={{ __html: props.body }} /> {props.postBodyComponents} <script async={true} src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" /> </body> </html> ) HTML.propTypes = { htmlAttributes: PropTypes.object, headComponents: PropTypes.array, bodyAttributes: PropTypes.object, preBodyComponents: PropTypes.array, body: PropTypes.string, postBodyComponents: PropTypes.array, } export default HTML
JavaScript
0.000001
@@ -477,24 +477,28 @@ /%3E */%7D%0A + %7B/* %3Clink rel=%22 @@ -544,32 +544,36 @@ dication.com%22 /%3E + */%7D %0A %7Bprops.he @@ -827,16 +827,20 @@ %7D%0A%0A + %7B/* %3Cscript @@ -936,24 +936,28 @@ js%22%0A /%3E + */%7D %0A %3C/body%3E
4afc6eec2eff44edb29e3aefdb17934dd33e19fb
Update Actor object structure.
base/objects/Objects.js
base/objects/Objects.js
/* =============================================================================== Class compilation defines in-game 3D objects. =============================================================================== */ function Objects() { if ( !(this instanceof Objects) ) return new Objects(); } /* ================= Actor Entity, that represents object in space. ================= */ Objects.prototype.Actor = function ( x, y, z ) { if ( !(this instanceof Objects.prototype.Actor) ) return new Objects.prototype.Actor(); this.x = x || 0; this.y = y || 0; this.z = z || 0; this.material = null; this.geometry = null; this.mesh = null; this.objects = null; // Can be overridden. // Should do all initial work, before adding to the scene. this.create = function ( objects ) { this.objects = objects || DOA.Engine._objects; this.objects.push( this ); if ( this.mesh instanceof THREE.Mesh ) { this.mesh.position.set( this.x, this.y, this.z ); } return this.mesh; }; // Can be overridden. // Should do all initial work, before removing from scene. this.clear = function () { this.objects.pop( this ); return this.mesh; }; // Method to animate mesh in the Engine cycle. this.animate = function ( args ) { }; this.setX = function ( x ) { this.x = x; this.mesh.position.x = x; }; this.setY = function ( y ) { this.y = y; this.mesh.position.y = y; }; this.setZ = function ( z ) { this.z = z; this.mesh.position.z = z; }; this.setPosition = function ( x, y, z ) { if ( typeof x === 'number' ) this.setX( x ); if ( typeof y === 'number' ) this.setY( y ); if ( typeof z === 'number' ) this.setZ( z ); }; }; /* ================= World Entity, that represents space, with a specific properties: gravity, world type (map, level), global lightning, etc. ================= */ Objects.prototype.World = function () { if ( !(this instanceof Objects.prototype.World) ) return new this.World(); };
JavaScript
0
@@ -780,32 +780,51 @@ g to the scene.%0A + // @deprecated%0A this.create @@ -844,24 +844,24 @@ objects ) %7B%0A - this @@ -1177,24 +1177,43 @@ from scene.%0A + // @deprecated%0A this.cle @@ -1295,24 +1295,216 @@ sh;%0A %7D;%0A%0A + // Enables object for renderer. Marks active.%0A this.enable = function () %7B%0A %7D;%0A%0A // Disables object for the renderer. Marks as suspended.%0A this.disable = function () %7B%0A %7D;%0A%0A // Metho @@ -1542,16 +1542,16 @@ cycle.%0A + this @@ -1581,17 +1581,16 @@ rgs ) %7B%0A -%0A %7D;%0A%0A
d33c5e50ca258278d0f9cba08dc6ae813efc5e82
Fix throughput calculation.
web/js/voltdb-dashboard.js
web/js/voltdb-dashboard.js
/* This file is part of VoltDB. Copyright (C) 2008-2013 VoltDB Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ var con; var chartIntervalId; var statsIntervalId; // initialize actions $(document).ready(function(){ $('#loadingModal').modal('show'); checkConnection(); }); function checkConnection() { VoltDB.TestConnection(location.hostname, 8080, false, null, null, false, function(connected){ if (connected) { $('#loadingModal').modal('hide'); connectToDatabase(); } else { checkConnection(); } }); } function connectToDatabase() { // connect to VoltDB HTTP/JSON interface con = VoltDB.AddConnection(location.hostname, 8080, false, null, null, false, (function(connection, success){})); // set the chart interval to 1 second default SetChartRefreshInterval(1); // set the stats interval to run every 1000 milliseconds statsIntervalId = setInterval(RefreshStats,1000); } // set/reset the chart interval function SetChartRefreshInterval(interval) { if (chartIntervalId != null) { clearInterval(chartIntervalId); chartIntervalId = null; } if(interval > 0) chartIntervalId = setInterval(RefreshData, interval*1000); } // Refresh drop-down $('#refresh-1').click(function(e) { e.preventDefault();// prevent the default anchor functionality SetChartRefreshInterval(1); }); $('#refresh-5').click(function(e) { e.preventDefault();// prevent the default anchor functionality SetChartRefreshInterval(5); }); $('#refresh-10').click(function(e) { e.preventDefault();// prevent the default anchor functionality SetChartRefreshInterval(10); }); $('#refresh-pause').click(function(e) { e.preventDefault();// prevent the default anchor functionality SetChartRefreshInterval(-1); }); // ----------------- Stats Charts ----------------- // this runs every second function RefreshStats() { con.BeginExecute('@Statistics', ['PROCEDUREPROFILE','0'], function(response) { DrawTPSChart(response,'#tps_chart'); } ); } var tpsVals = []; var prevTime = null; var tcount0 = null; function DrawTPSChart(response, someDiv) { var tables = response.results; var table0 = tables[0]; //var colcount = table0.schema.length; if (prevTime != null && table0.data[0][0] == prevTime) { // Skip cached old results return; } prevTime = table0.data[0][0]; var time = table0.data[0][0]/1000; var tcount1 = 0; for(var r=0;r<table0.data.length;r++){ // for each row //var time = table0.data[r][0]/1000; tcount1 += table0.data[r][3]; } var tps; if (tcount0 == null) { tps = 0; } else { tps = tcount1 - tcount0; } tcount0 = tcount1; tpsVals.push([time,tps]); var tpsline = { label: "TPS", data: tpsVals }; var options = { series: { lines: { show: true, fill: true }, //bars: { show: true, barWidth : 60*1000, fill: true}, points: { show: false } }, xaxis: { mode: "time" }, yaxis: { position: "right" }, legend: { position: 'nw' } }; $.plot($(someDiv), [tpsline], options); } // Draw a basic HTML table from a VoltTable function DrawTable(response, tableName, selectedRow) { try { var tables = response.results; var hmt = tables[0]; var colcount = hmt.schema.length; // the first time, initialize the table head if ($(tableName+' thead tr').length == 0) { var theadhtml = '<tr>'; for (var i=0; i<colcount; i++) { theadhtml += '<th>' + hmt.schema[i].name + '</th>'; } $(tableName).append('<thead></thead>'); $(tableName).append('<tbody></tbody>'); $(tableName).children('thead').html(theadhtml); } var tbodyhtml; for(var r=0;r<hmt.data.length;r++){ // for each row if (r==selectedRow) { tbodyhtml += '<tr class="success">'; } else { tbodyhtml += '<tr>'; } for (var c=0;c<colcount;c++) { // for each column var f = hmt.data[r][c]; // if type is DECIMAL if (hmt.schema[c].type == 22 || hmt.schema[c].type == 8) { f = formatDecimal(f); } if (hmt.schema[c].type == 11) { f = formatDate(f); } tbodyhtml += '<td>' + f + '</td>'; } tbodyhtml += '</tr>'; } $(tableName).children('tbody').html(tbodyhtml); } catch(x) {} } // Data Formatting Methods function formatDecimal(n) { return (Math.round(parseFloat(n) * 100) / 100).toFixed(2); } function formatDate(n) { //return new Date(n/1000).toLocaleDateString(); return new Date(n/1000).toUTCString(); } function formatDateAsTime(n) { //return new Date(n/1000).toLocaleDateString(); var d = new Date(n/1000).toUTCString(); var s = d.toString().substring(17,29); return s; }
JavaScript
0.000001
@@ -2994,19 +2994,19 @@ ar prevT -ime +sMs = null; @@ -3184,49 +3184,72 @@ -if (prevTime != null && table0.data%5B0%5D%5B0%5D +var cTsMs = table0.data%5B0%5D%5B0%5D;%0A if (prevTsMs != null && cTsMs == @@ -3253,19 +3253,19 @@ == prevT -ime +sMs ) %7B%0A @@ -3325,36 +3325,63 @@ -prevTime = table0.data%5B0%5D%5B0%5D +var durationMs = cTsMs - prevTsMs;%0A prevTsMs = cTsMs ;%0A%0A @@ -3671,16 +3671,17 @@ tps = +( tcount1 @@ -3689,16 +3689,33 @@ tcount0 +)*1000/durationMs ;%0A %7D%0A
ee6d6402a5fe0efcc6361ab3e2787e479d5268dd
Update cleanup function
spec/core/mailboxes/utils.js
spec/core/mailboxes/utils.js
var config = require('../../../config.js'); var db = config.db; var core = require('../../../core.js'); var _ = require('lodash'); var Promise = require('bluebird'); var utils = {}; var callId = "#1"; var args = { accountId: "[email protected]", ifInState: "", create: {}, update: {}, destroy: [] }; var validCreateObject = { id: "", parentId: null, role: null, totalMessages: 0, unreadMessages: 0, totalThread: "", unreadThread: "" }; // List of ids created, use for cleanup var created = []; utils.createMailboxes = function (number) { var res = []; for (var i = 0; i < number; i++) { args.create[i] = validCreateObject; } return core.setMailboxes(res, args, callId).then(function () { var ids = []; _.keys(res[0][1].created).forEach(function (key) { var id = res[0][1].created[key].id; ids.push(id); created.push(id); }); return ids; }); }; utils.cleanup = function () { var promises = []; created.forEach(function (id) { promises.push(db.get(id).then(function (doc) { return db.remove(doc); })); }); return Promise.all(promises); }; module.exports = utils;
JavaScript
0.000001
@@ -4,16 +4,17 @@ config + = requir @@ -49,16 +49,17 @@ db + = config @@ -74,16 +74,17 @@ core + = requir @@ -110,17 +110,63 @@ ');%0Avar -_ +models = require('../../../models.js');%0Avar _ = @@ -541,67 +541,8 @@ %7D;%0A%0A -// List of ids created, use for cleanup%0Avar created = %5B%5D;%0A%0A util @@ -914,38 +914,8 @@ d);%0A - created.push(id);%0A @@ -972,32 +972,41 @@ nup = function ( +accountId ) %7B%0A var prom @@ -1024,23 +1024,164 @@ -created.forEach +var opts = %7B%0A startkey: models.mailbox.startkey(accountId),%0A endkey: models.mailbox.endkey(accountId)%0A %7D;%0A%0A return db.allDocs(opts).then (fun @@ -1187,18 +1187,25 @@ nction ( -id +mailboxes ) %7B%0A @@ -1212,37 +1212,30 @@ -promises.push(db.get(id).then +mailboxes.rows.forEach (fun @@ -1241,19 +1241,23 @@ nction ( -doc +mailbox ) %7B%0A @@ -1268,28 +1268,79 @@ -return db.remove(doc +promises.push(db.remove(%7B'_id': mailbox.id, '_rev': mailbox.value.rev%7D) );%0A @@ -1352,19 +1352,14 @@ %7D) -) ;%0A -%7D);%0A @@ -1388,16 +1388,80 @@ mises);%0A + %7D).catch(function (err) %7B%0A console.log(err);%0A %7D);%0A %7D;%0A%0Amodu
d3cad8c978c9c7dbdce4c41de17f7330feb7d951
fix axis
src/compile/axis.js
src/compile/axis.js
'use strict'; require('../globals'); var util = require('../util'), setter = util.setter, getter = util.getter, time = require('./time'); var axis = module.exports = {}; axis.names = function(props) { return util.keys(util.keys(props).reduce(function(a, x) { var s = props[x].scale; if (s === X || s === Y) a[props[x].scale] = 1; return a; }, {})); }; axis.defs = function(names, encoding, layout, stats, opt) { return names.reduce(function(a, name) { a.push(axis.def(name, encoding, layout, stats, opt)); return a; }, []); }; axis.def = function(name, encoding, layout, stats, opt) { var type = name; var isCol = name == COL, isRow = name == ROW; var rowOffset = axisTitleOffset(encoding, layout, Y) + 20, cellPadding = layout.cellPadding; if (isCol) type = 'x'; if (isRow) type = 'y'; var def = { type: type, scale: name }; if (encoding.axis(name).grid) { def.grid = true; def.layer = 'back'; if (isCol) { // set grid property -- put the lines on the right the cell setter(def, ['properties', 'grid'], { x: { offset: layout.cellWidth * (1+ cellPadding/2.0), // default value(s) -- vega doesn't do recursive merge scale: 'col' }, y: { value: -layout.cellHeight * (cellPadding/2), }, stroke: { value: encoding.config('cellGridColor') }, opacity: { value: encoding.config('cellGridOpacity') } }); } else if (isRow) { // set grid property -- put the lines on the top setter(def, ['properties', 'grid'], { y: { offset: -layout.cellHeight * (cellPadding/2), // default value(s) -- vega doesn't do recursive merge scale: 'row' }, x: { value: rowOffset }, x2: { offset: rowOffset + (layout.cellWidth * 0.05), // default value(s) -- vega doesn't do recursive merge group: 'mark.group.width', mult: 1 }, stroke: { value: encoding.config('cellGridColor') }, opacity: { value: encoding.config('cellGridOpacity') } }); } else { setter(def, ['properties', 'grid'], { stroke: { value: encoding.config('gridColor') }, opacity: { value: encoding.config('gridOpacity') } }); } } if (encoding.axis(name).title) { def = axis_title(def, name, encoding, layout, opt); } if (isRow || isCol) { setter(def, ['properties', 'ticks'], { opacity: {value: 0} }); setter(def, ['properties', 'majorTicks'], { opacity: {value: 0} }); setter(def, ['properties', 'axis'], { opacity: {value: 0} }); } if (isCol) { def.orient = 'top'; } if (isRow) { def.offset = rowOffset; } if (name == X) { if (encoding.has(Y) && encoding.isOrdinalScale(Y) && encoding.cardinality(Y, stats) > 30) { def.orient = 'top'; } if (encoding.isDimension(X) || encoding.isType(X, T)) { setter(def, ['properties','labels'], { angle: {value: 270}, align: {value: 'right'}, baseline: {value: 'middle'} }); } else { // Q def.ticks = 5; } } def = axis_labels(def, name, encoding, layout, opt); return def; }; function axis_title(def, name, encoding, layout, opt) { // jshint unused:false var maxlength = null, fieldTitle = encoding.fieldTitle(name); if (name===X) { maxlength = layout.cellWidth / encoding.config('characterWidth'); } else if (name === Y) { maxlength = layout.cellHeight / encoding.config('characterWidth'); } def.title = maxlength ? util.truncate(fieldTitle, maxlength) : fieldTitle; if (name === ROW) { setter(def, ['properties','title'], { angle: {value: 0}, align: {value: 'right'}, baseline: {value: 'middle'}, dy: {value: (-layout.height/2) -20} }); } def.titleOffset = axisTitleOffset(encoding, layout, name); return def; } function axis_labels(def, name, encoding, layout, opt) { // jshint unused:false var fn; // add custom label for time type if (encoding.isType(name, T) && (fn = encoding.fn(name)) && (time.hasScale(fn))) { setter(def, ['properties','labels','text','scale'], 'time-'+ fn); } var textTemplatePath = ['properties','labels','text','template']; if (encoding.axis(name).format) { def.format = encoding.axis(name).format; } else if (encoding.isType(name, Q)) { setter(def, textTemplatePath, '{{data | number:\'.3s\'}}'); } else if (encoding.isType(name, T)) { if (!encoding.fn(name)) { setter(def, textTemplatePath, '{{data | time:"%Y-%m-%d"}}'); } else if (encoding.fn(name) === 'year') { setter(def, textTemplatePath, '{{data | number:"d"}}'); } } else if (encoding.isType(name, [N, O]) && encoding.axis(name).maxLabelLength) { setter(def, textTemplatePath, '{{data | truncate:' + encoding.axis(name).maxLabelLength + '}}'); } return def; } function axisTitleOffset(encoding, layout, name) { var value = encoding.axis(name).titleOffset; if (value) { return value; } switch (name) { case ROW: return 0; case COL: return 35; } return getter(layout, [name, 'axisTitleOffset']); }
JavaScript
0.000003
@@ -4665,17 +4665,18 @@ ime: -%22 +%5C' %25Y-%25m-%25d %22%7D%7D' @@ -4671,17 +4671,18 @@ %25Y-%25m-%25d -%22 +%5C' %7D%7D');%0A @@ -4783,11 +4783,13 @@ ber: -%22d%22 +%5C'd%5C' %7D%7D')
e21b5be6f6d34b8f1bc75bfab73fec67837b3bcf
remove unnecessary redirect in server
web/middleware/redirect.js
web/middleware/redirect.js
const config = require('../../config'); const { formatInAppUrl } = require('../../ui/util/url'); async function redirectMiddleware(ctx, next) { const requestHost = ctx.host; const path = ctx.path; const url = ctx.url; // Getting err: too many redirects on some urls because of this // Need a better solution // const decodedUrl = decodeURIComponent(url); // if (decodedUrl !== url) { // ctx.redirect(decodedUrl); // return; // } if (path.endsWith('/') && path.length > 1) { ctx.redirect(url.replace(/\/$/, '')); return; } if (!path.startsWith('/$/') && path.match(/^([^@/:]+)\/([^:/]+)$/)) { ctx.redirect(url.replace(/^([^@/:]+)\/([^:/]+)(:(\/.*))/, '$1:$2')); // test against path, but use ctx.url to retain parameters return; } if (requestHost === 'open.lbry.com' || requestHost === 'open.lbry.io') { const openQuery = '?src=open'; let redirectUrl = config.URL + formatInAppUrl(url, openQuery); if (redirectUrl.includes('?')) { redirectUrl = redirectUrl.replace('?', `${openQuery}&`); } else { redirectUrl += openQuery; } ctx.redirect(redirectUrl); return; } // No redirects needed await next(); } module.exports = redirectMiddleware;
JavaScript
0.000001
@@ -218,16 +218,17 @@ tx.url;%0A +%0A // Get @@ -454,114 +454,8 @@ %7D%0A%0A - if (path.endsWith('/') && path.length %3E 1) %7B%0A ctx.redirect(url.replace(/%5C/$/, ''));%0A return;%0A %7D%0A%0A if
2e10efe9480ee10c47add252ed1004fa9397175f
Add zoom-js plugin to initizalize
components/Deck/Presentation/Presentation.js
components/Deck/Presentation/Presentation.js
import React from 'react'; import ReactDOM from 'react-dom'; import {NavLink} from 'fluxible-router'; import {connectToStores} from 'fluxible-addons-react'; import PresentationSlide from './PresentationSlide'; import DeckTreeStore from '../../../stores/DeckTreeStore'; import PresentationStore from '../../../stores/PresentationStore'; import loadPresentation from '../../../actions/loadPresentation'; //if(process.env.BROWSER){ // require('../../../assets/css/PresentationDefaults.css'); //} let playerCss = { height: '100%', position: 'absolute', top: '0', }; let clearStyle = { clear: 'both' }; class Presentation extends React.Component{ constructor(props){ super(props); this.playerCss = playerCss; this.slides = []; this.startingSlide = this.props.PresentationStore.selector.sid; this.deck = this.props.PresentationStore.selector.id; this.revealDiv = null; } componentDidMount(){ if(process.env.BROWSER){ //loading reveal style //Hide the header and footer $('.ui.footer.sticky.segment').css({'display': 'none'}); $('.ui.inverted.blue.menu, .ui.inverted.menu .blue.active.item').css({'display': 'none'}); $('.ui.footer.sticky.segment').attr({'aria-hidden': 'hidden', 'hidden': 'hidden'}); $('.ui.inverted.blue.menu, .ui.inverted.menu .blue.active.item').attr({'aria-hidden': 'hidden', 'hidden': 'hidden'}); $('.ui.horizontal.segments.footer').css({'display': 'none'}); $('.ui.horizontal.segments.footer').attr({'aria-hidden': 'hidden', 'hidden': 'hidden'}); let styleName = this.props.PresentationStore.theme; this.revealDiv.style.display = 'inline'; let pptxwidth = $('.pptx2html').width(); let pptxheight = $('.pptx2html').height(); Reveal.initialize({ width: pptxwidth, height: pptxheight, transition: 'none', backgroundTransition: 'none', history: true, dependencies: [ { src: '/custom_modules/reveal.js/plugin/notes/notes.js', async: true } ] }); } } componentDidUpdate(){ } render(){ this.slides = this.getSlides(); return( <div> <div className="reveal" style={this.playerCss} ref={(refToDiv) => this.revealDiv = refToDiv} data-transition="none" data-background-transition="none"> <div className="slides"> {this.slides} </div> </div> <br style={clearStyle} /> </div> ); } getSlides(){ let slides = this.props.PresentationStore.content; let returnList = []; if(slides){ for (let i = 0; i < slides.length; i++) { let slide = slides[i]; let notes = ''; if(slide.speakernotes){ notes = '<aside class="notes">' + slide.speakernotes + '</aside>'; } let content = slide.content + notes; returnList.push(<PresentationSlide content={content} key={slide.id} id={'slide-' + slide.id} />); } return returnList; } else{ return (<section />); } } } Presentation.contextTypes = { executeAction: React.PropTypes.func.isRequired }; Presentation = connectToStores(Presentation, [PresentationStore], (context, props) => { return { PresentationStore: context.getStore(PresentationStore).getState() }; }); export default Presentation;
JavaScript
0
@@ -2206,16 +2206,111 @@ : true %7D +,%0A %7B src: '/custom_modules/reveal.js/plugin/zoom-js/zoom.js', async: true %7D, %0A
f29407616d4b8f37bba84b883bcedb4d7584d403
Update css
src/components/Articles/List/List.js
src/components/Articles/List/List.js
import React from "react"; import PropTypes from "prop-types"; import { Link } from "gatsby"; import Article from "./Article"; const ArticlesList = ({ articles, withLink = true }) => { return ( <ul className="flex flex-col h-full justify-between py-12 px-1 lg:overflow-y-auto article-list"> {articles.map(article => ( <li key={article.id} className="my-4"> <Article {...article} /> </li> ))} {withLink && ( <li className="my-4 w-14"> <Link to="/blog" className="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded inline-flex items-center justify-between" > <span> Voir tous mes articles</span> <svg className="fill-current h-6 ml-2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" > <path d="M16,4.96C9.913,4.96,4.96,9.912,4.96,16S9.913,27.04,16,27.04S27.04,22.088,27.04,16S22.087,4.96,16,4.96z M16,25.12 c-5.028,0-9.12-4.092-9.12-9.12S10.972,6.88,16,6.88s9.12,4.092,9.12,9.12S21.028,25.12,16,25.12z" /> <polygon points="13.098,11.368 17.966,16 13.098,20.632 14.421,22.022 20.753,16 14.421,9.977 " /> </svg> </Link> </li> )} </ul> ); }; ArticlesList.propTypes = { articles: PropTypes.array.isRequired, withLink: PropTypes.bool, }; export default ArticlesList;
JavaScript
0.000001
@@ -238,23 +238,22 @@ justify- -between +center py-12 p
2a6df2c3a6eda719fceb1f98d2631321172f5ed6
Fix enum
ex/04/src/schema/index.js
ex/04/src/schema/index.js
const { makeExecutableSchema } = require('graphql-tools') const { getItem, getUser, getTopStories } = require('../hnclient') const typeDefs = [` type User { about: String created: Int delay: Int, id: String! karma: Int! submitted: [Item] } enum ItemType { story } type Item { id: Int! by: User! kids: [Item] score: Int! time: Int title: String! type: ItemType url: String } type Query { item(id: Int!): Item stories: [Item] user(id: String!): User } schema { query: Query } `] const resolvers = { Query: { item (_, { id }) { return getItem(id) }, async stories () { const stories = await getTopStories() return stories.map(getItem) }, user (_, { id }) { return getUser(id) } }, Item: { by: function({ by }) { return getUser(by) }, kids: function ({ kids }) { return kids.map(getItem) } }, User: { submitted ({ submitted }) { return submitted.map(getItem) } } } module.exports = makeExecutableSchema({ typeDefs, resolvers })
JavaScript
0.000009
@@ -275,27 +275,69 @@ um I -temType %7B%0A story +TEM_TYPE %7B%0A JOB%0A STORY%0A COMMENT%0A POLL%0A POLLOPT %0A %7D @@ -460,15 +460,16 @@ e: I -temType +TEM_TYPE %0A @@ -994,32 +994,102 @@ ds.map(getItem)%0A + %7D,%0A type: function(%7B type %7D) %7B%0A return type.toUpperCase()%0A %7D%0A %7D,%0A Use
10c9bd7263d77b7d36ec5e03dd1fd6c12f694f02
update tag chart on hover node
web/public/js/loadGraph.js
web/public/js/loadGraph.js
$(document).ready(function() { var s = new sigma('graph-container'); var tagTemplateString = "<h3> {{noteTitle}} </h3> <ul> {{#each tags}} <li> {{title}}, {{weight}} </li> {{/each}} </ul>" var tagTemplate = Handlebars.compile(tagTemplateString); s.settings({ defaultLabelColor: '#000', defaultLabelSize: 10, drawEdges : true, batchEdgesDrawing : true, defaultLabelBGColor: '#fff', defaultLabelHoverColor: '#000', defaultEdgeColor:'#ddd', defaultNodeColor:'#00CCFF', labelThreshold: 7, defaultEdgeType: 'curve', minNodeSize: 1, maxNodeSize: 3, minEdgeSize: 0, maxEdgeSize: .1 }); s.bind('clickNode', function(e) { var tags = JSON.parse(e.data.node.tags) if (tags.length > 8) { tags = tags.slice(0,8); } tags.forEach(function(tag) { tag.weight = Math.round(tag.weight*100); }); tagNames = tags.map(function(tag) { return tag.title}); window.drawGraphForTags(tagNames); $('#tagList').html(tagTemplate({noteTitle : e.data.node.label, tags : tags})); }); sigma.parsers.gexf('./network.gexf', s, function (s) { $('#loading').remove(); s.refresh(); }); });
JavaScript
0
@@ -660,16 +660,25 @@ lickNode + overNode ', funct
3aeb775cf039ecf82e5a0cc2f9dccc24f47d78de
Set default language to English
src/i18n.js
src/i18n.js
// Localisation import Vue from 'vue' import VueI18n from 'vue-i18n' Vue.use(VueI18n) import locales from './locales' const i18n = new VueI18n({ locale: 'fr', fallbackLocale: 'en', messages: locales }) export default i18n
JavaScript
0.999578
@@ -150,18 +150,18 @@ ocale: ' -fr +en ',%0A fal
f97fa35269c4efc7bbd2621dca63f9e70d4da1d6
improve tests for string.prototype.@@iterator (#1667)
polyfills/String/prototype/@@iterator/tests.js
polyfills/String/prototype/@@iterator/tests.js
/* eslint-env mocha */ /* global proclaim */ it('returns a next-able object', function () { var str = 'ab'; var iterator = str[Symbol.iterator](); proclaim.isInstanceOf(iterator.next, Function); proclaim.deepEqual(iterator.next(), { value: 'a', done: false }); }); it('finally returns a done object', function () { var str = 'ab'; var iterator = str[Symbol.iterator](); iterator.next(); iterator.next(); proclaim.deepEqual(iterator.next(), { value: undefined, done: true }); });
JavaScript
0
@@ -25,16 +25,17 @@ * global +s proclai @@ -35,19 +35,474 @@ proclaim - */ +, Symbol */%0A%0Ait('is a function', function () %7B%0A%09proclaim.isFunction(String.prototype%5BSymbol.iterator%5D);%0A%7D);%0A%0Ait('has correct arity', function () %7B%0A%09proclaim.arity(String.prototype%5BSymbol.iterator%5D, 0);%0A%7D);%0A%0A// TODO: Look into this%0A// it('has correct name', function () %7B%0A// %09proclaim.hasName(String.prototype%5BSymbol.iterator%5D, '%5BSymbol.iterator%5D');%0A// %7D);%0A%0Ait('is not enumerable', function () %7B%0A%09proclaim.nonEnumerable(String.prototype, Symbol.iterator);%0A%7D); %0A%0Ait('re
e4d3704f02dd5abf0d92c2fe343e839755d76e5b
Use includes in place of indexOf
src/config/index.js
src/config/index.js
import path from 'path'; const config = new Map(); /* istanbul ignore next */ // Looks like you can't ignore a file but you can ignore a function, we don't want coverage here. (function defineConfig() { const NODE_ENV = process.env.NODE_ENV; // Default to production unless overridden. config.set('env', NODE_ENV || 'production'); config.set('basePath', path.resolve(__dirname, '../')); // This is the host / port for running as production. config.set('serverHost', process.env.SERVER_HOST || '127.0.0.1'); config.set('serverPort', process.env.SERVER_PORT || 4000); // This is the host / port for the development instance. config.set('devServerHost', process.env.SERVER_HOST || '127.0.0.1'); config.set('devServerPort', process.env.SERVER_PORT || 3000); // This is the host / port for the webpack dev server. config.set('webpackServerHost', process.env.WEBPACK_SERVER_HOST || '127.0.0.1'); config.set('webpackServerPort', process.env.WEBPACK_SERVER_PORT || 3001); config.set('apiHost', process.env.API_HOST || (NODE_ENV === 'development' ? 'https://addons-dev.allizom.org' : 'https://addons.mozilla.org')); config.set('apiPath', process.env.API_PATH || '/api/v3'); config.set('apiBase', config.get('apiHost') + config.get('apiPath')); const CSP = { directives: { connectSrc: ["'self'", config.get('apiHost')], defaultSrc: ["'self'"], scriptSrc: ["'self'"], styleSrc: ["'self'"], reportUri: '/__cspreport__', }, // Set to true if you only want browsers to report errors, not block them reportOnly: false, // Set to true if you want to blindly set all headers: Content-Security-Policy, // X-WebKit-CSP, and X-Content-Security-Policy. setAllHeaders: false, // Set to true if you want to disable CSP on Android where it can be buggy. disableAndroid: false, }; const WEBPACK_HOST = `http://${config.get('webpackServerHost')}:${config.get('webpackServerPort')}`; if (config.get('env') === 'development') { CSP.directives.scriptSrc.push(WEBPACK_HOST); CSP.directives.styleSrc.push('blob:'); CSP.directives.connectSrc.push(WEBPACK_HOST); CSP.reportOnly = true; } config.set('CSP', CSP); // This is the list of apps allowed to run. const validAppNames = ['search', 'disco']; config.set('validAppNames', validAppNames); // Create a list of apps to build targets for. const appName = process.env.APP_NAME; if (validAppNames.indexOf(appName) > -1) { config.set('appsBuildList', [appName]); config.set('currentApp', appName); } else { config.set('appsBuildList', validAppNames); config.set('currentApp', null); } }()); export default config;
JavaScript
0.000001
@@ -2491,13 +2491,14 @@ s.in -dexOf +cludes (app @@ -2506,13 +2506,8 @@ ame) - %3E -1 ) %7B%0A
2f21bfccf6537c7a6960e377acb01d27ca3753f6
update test of data processor to reflect new expected values of putting the line in the middle
__tests__/DataProcessor.js
__tests__/DataProcessor.js
import { expect } from 'chai'; import DataProcessor from '../src/DataProcessor'; describe('DataProcessor', () => { describe('dataToPoints', () => { it('should return an array', () => { expect(DataProcessor.dataToPoints([])).to.be.an('array') expect(DataProcessor.dataToPoints([], null, null, null)).to.be.an('array') expect(DataProcessor.dataToPoints([1, 2, 3], null, null, null)).to.be.an('array') expect(DataProcessor.dataToPoints([1, null, undefined], null, null, null)).to.be.an('array') }); it('should return only `limit` items', () => { expect(DataProcessor.dataToPoints([1,2,3,4,5])).to.have.length(5) expect(DataProcessor.dataToPoints([1,2,3,4,5], 2)).to.have.length(2) expect(DataProcessor.dataToPoints([1,2,3,4,5], 5)).to.have.length(5) }); it('should return proper values for 1 value', () => { expect(DataProcessor.dataToPoints([1])).to.eql([ {x: 0, y: 0} ]) }); it('should return proper values 2+ values', () => { expect(DataProcessor.dataToPoints([1,1])).to.eql([ {x: 0, y: 0}, {x: 1, y: 0} ]) expect(DataProcessor.dataToPoints([0,1])).to.eql([ {x: 0, y: 1}, {x: 1, y: 0} ]) expect(DataProcessor.dataToPoints([1,0])).to.eql([ {x: 0, y: 0}, {x: 1, y: 1} ]) expect(DataProcessor.dataToPoints([0,1,2])).to.eql([ {x: 0, y: 1}, {x: 0.5, y: 0.5}, {x: 1, y: 0} ]) }); it('should inerpolate values properly', () => { expect(DataProcessor.dataToPoints([0,1,2], null, 10, 10, 0)).to.eql([ {x: 0, y: 10}, {x: 5, y: 5}, {x: 10, y: 0} ]) }); it('should take min and max into account', () => { expect(DataProcessor.dataToPoints([1,2,3,4], null, 6, 10, 0, 2, 3)).to.eql([ {x: 0, y: -10}, {x: 2, y: 0}, {x: 4, y: 10}, {x: 6, y: 20} ]) }); it('should return y == height for 0 and null values', () => { expect(DataProcessor.dataToPoints([0])).to.eql([ {x: 0, y: 1} ]) expect(DataProcessor.dataToPoints([0, null, 0])).to.eql([ {x: 0, y: 1}, {x: 0.5, y: 1}, {x: 1, y: 1} ]) }); }); describe('avg', () => { it('should return average of values', () => { expect(DataProcessor.avg([0])).to.eq(0) expect(DataProcessor.avg([0, 1])).to.eq(0.5) expect(DataProcessor.avg([1, 2])).to.eq(3/2) expect(DataProcessor.avg([0, 1, 2])).to.eq(1) }); }) });
JavaScript
0
@@ -1015,24 +1015,26 @@ %7Bx: 0, y: 0 +.5 %7D%0A @@ -1193,32 +1193,34 @@ %7Bx: 0, y: 0 +.5 %7D,%0A @@ -1225,32 +1225,34 @@ %7Bx: 1, y: 0 +.5 %7D%0A %5D) @@ -2424,25 +2424,27 @@ %7Bx: 0, y: -1 +0.5 %7D%0A @@ -2536,33 +2536,35 @@ %7Bx: 0, y: -1 +0.5 %7D,%0A @@ -2574,25 +2574,27 @@ %7Bx: 0.5, y: -1 +0.5 %7D,%0A @@ -2602,33 +2602,35 @@ %7Bx: 1, y: -1 +0.5 %7D%0A %5D)
862c6d914ba24759d1251b5ba6811c8c61d24c89
Update 8x8_led_matrix.js
example/8x8_led_matrix.js
example/8x8_led_matrix.js
/** * Linkit 7688 範例 * 使用 GPIO 控制 8x8 LED Matrix (共陽) * * @author Abola Lee * @version 1.0 * @since 2016-01-10 * * @link http://www.gibar.co/2016/01/linkit-7688-duo-74hc595-led.html */ var mraa = require('mraa'); // 腳位命名參考 // _______ // Q1[1| U |16]Vcc // Q2[2| |15]Q0 // Q3[3| |14]DS // Q4[4| 595 |13]OE // Q5[5| |12]STCP // Q6[6| |11]SHCP // Q7[7| |10]MR // GND[8|_______| 9]Q7s // // 設定GPIO 接腳 var col = [ new mraa.Gpio(2), , new mraa.Gpio(16) , new mraa.Gpio(17) , new mraa.Gpio(44) , new mraa.Gpio(5) , new mraa.Gpio(46) , new mraa.Gpio(0) , new mraa.Gpio(1) ], row = [ new mraa.Gpio(37) , new mraa.Gpio(3) , new mraa.Gpio(13) , new mraa.Gpio(45) , new mraa.Gpio(14) , new mraa.Gpio(12) , new mraa.Gpio(15) , new mraa.Gpio(4) ]; // 預設全亮測試 for(var idx=0; idx<8; idx++) ((mraa.Gpio)col[idx]).dir(mraa.DIR_OUT_HIGH); for(var idx=0; idx<8; idx++) row[idx].dir(mraa.DIR_OUT_LOW); var offIndex=0; setInterval(function(){ if( offIndex<8 ) row[offIndex].write(1); },250);
JavaScript
0.000001
@@ -462,16 +462,18 @@ %E6%8E%A5%E8%85%B3%0Avar +my col = %5B%0A @@ -494,17 +494,16 @@ .Gpio(2) -, %0A , @@ -686,16 +686,18 @@ %5D,%0A +my row = %5B%0A @@ -969,16 +969,18 @@ aa.Gpio) +my col%5Bidx%5D @@ -1034,16 +1034,18 @@ idx++) +my row%5Bidx%5D @@ -1109,16 +1109,16 @@ tion()%7B%0A - if( of @@ -1128,16 +1128,18 @@ dex%3C8 ) +my row%5BoffI
23e2b45bcdc12e6f0179ed3568414f73c18fc9eb
fix missing semicolon
xhr.js
xhr.js
var xhr = { request: function(type, url, opts) { 'use strict'; var json = 'application/json'; var req = new XMLHttpRequest(), payload = ('payload' in opts) ? opts.payload : null, callback = (opts.callback || function() {}).bind(req), headers = opts.headers || (opts.raw ? {} : { 'Content-Type': json, 'Accept': json }); req.open(type, url); for (var k in headers) req.setRequestHeader(k, headers[k]); req.onerror = function() { callback(true) }; req.onload = function() { callback( null, opts.raw ? req.responseText : JSON.parse(req.responseText) ); }; if (!opts.raw) payload = JSON.stringify(opts); req.send(payload); return req; } }; xhr.post = xhr.request.bind(xhr, 'POST'); xhr.get = xhr.request.bind(xhr, 'GET');
JavaScript
0.999904
@@ -522,16 +522,17 @@ ck(true) +; %7D;%0A
b3e8f6203d2752dff2abdee0a1b13f08506f2dd6
fix for point interactions from layers not showing interaction data
components/map/components/popup/selectors.js
components/map/components/popup/selectors.js
import { createSelector, createStructuredSelector } from 'reselect'; import { getActiveDatasetsFromState, getInteractions, getInteractionSelected, } from 'components/map/selectors'; const getLatitude = (state) => state?.map?.data?.interactions?.latlng?.lat; const getLongitude = (state) => state?.map?.data?.interactions?.latlng?.lng; export const getShowPopup = createSelector( [getLatitude, getLongitude, getInteractionSelected], (lat, lng, interaction) => lat && lng && !interaction?.data?.cluster ); export const getInteractionsOptions = createSelector( getInteractions, (interactions) => interactions?.map((i) => ({ label: i?.layer?.name, value: i?.layer?.id })) ); export const getInteractionsOptionSelected = createSelector( getInteractionSelected, (selected) => ({ label: selected?.layer?.name, value: selected?.layer?.id }) ); export const getInteractionWithContext = createSelector( [getInteractionSelected], (interaction = {}) => { const { layer, geometry } = interaction || {}; const isAoi = layer?.name === 'Area of Interest'; const isArticle = !!layer?.interactionConfig?.article; const isBoundary = layer?.isBoundary; const isPoint = geometry?.type === 'Point'; return { ...interaction, isAoi, isArticle, isBoundary, isPoint, }; } ); export const getPopupProps = createStructuredSelector({ latitude: getLatitude, longitude: getLongitude, showPopup: getShowPopup, interactionsOptions: getInteractionsOptions, interactionOptionSelected: getInteractionsOptionSelected, selected: getInteractionWithContext, activeDatasets: getActiveDatasetsFromState, });
JavaScript
0
@@ -1220,16 +1220,26 @@ 'Point' + && !layer ;%0A%0A r
48cb611f7714330cc5a327ef09164a6435eea185
fix target of event label
js/datasf.js
js/datasf.js
--- --- $(function() { $('[data-toggle="tooltip"]').tooltip(); $('button.ext-sf-opendata').on('click', function(ev) { ga('send', 'event', 'Catalog', 'Search', $('#search-catalog .search-input').val(), 1); }); $('a.ext-sf-opendata').on('click', function(ev) { ga('send', 'event', 'Catalog', 'Click Link', 'From ' + window.location.pathname, 1) }); $('a.take-survey').on('click', function(ev) { ga('send', 'event', 'Take Survey', 'Click', 'Link', 1) }); $('a.download').on('click', function(ev) { ga('send', 'event', 'Download', $(ev.target).data('download-type'), $(ev.target).parent().data('download-name'), 1) }); // Set up custom validators to check for gov domains jQuery.validator.addMethod("matchGov", function(value, element) { return this.optional(element) || /[_a-z0-9-]+(\.[_a-z0-9-]+)*@(sfgov.org|sfmta.com|sfwater.org|sfmta.org|sfdph.org|sfport.com|flysfo.com|sfdpw.org|sfenvironment.org|sfpl.org|dcyf.org|first5sf.org)/.test(value); }, "Please enter a valid SFGov email address"); //Reset validator defaults to integrate with Bootstrap 3 conventions $.validator.setDefaults({ highlight: function(element) { $(element).closest('.form-group').addClass('has-error'); }, unhighlight: function(element) { $(element).closest('.form-group').removeClass('has-error'); }, errorElement: 'span', errorClass: 'help-block', errorPlacement: function(error, element) { if (element.parent('.input-group').length) { error.insertAfter(element.parent()); } else { error.insertAfter(element); } } }); $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); var $bodyMargin = $('body').css('margin-top').split("px")[0]; $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top - (+$bodyMargin + 10) }, 1000, 'easeInOutExpo'); event.preventDefault(); }); $('.navbar a').on('click touchend', function(e) { var el = $(this); var link = el.attr('href'); window.location = link; }); var $container = $('.isotope').isotope({ itemSelector: '.course-item', masonry: {}, filter: "*" }); // filter functions var filterFns = { // show if number is greater than 50 numberGreaterThan50: function() { var number = $(this).find('.number').text(); return parseInt(number, 10) > 50; }, // show if name ends with -ium ium: function() { var name = $(this).find('.name').text(); return name.match(/ium$/); } }; // bind filter button click $('#filters').on('click', 'button', function() { var filterValue = $(this).attr('data-filter'); // use filterFn if matches value filterValue = filterFns[filterValue] || filterValue; $container.isotope({ filter: filterValue }); }); // change is-checked class on buttons $('.btn-group').each(function(i, buttonGroup) { var $buttonGroup = $(buttonGroup); $buttonGroup.on('click', 'button', function() { $buttonGroup.find('.is-checked').removeClass('is-checked'); $(this).addClass('is-checked'); }); }); $("#mc-embedded-subscribe-form").validate({ rules: { EMAIL: { required: true, email: true, matchGov: true } }, submitHandler: function(form) { $.ajax({ url: $(form).attr('action'), method: $(form).attr('method'), data: $(form).serialize(), cache: false, dataType: "json", contentType: "application/json; charset=utf-8" }) .done(function(ret) { console.log(ret); if (ret.result != "success") { $('#mce-error-response').html(ret.msg); $('#mce-error-response').show(); $('#mce-success-response').hide(); } else { $('#mce-success-response').html(ret.msg + " Please check your junk folder if you do not receive the email."); $('#mce-error-response').hide(); $('#mce-success-response').show(); } }); } }); var table = $('#inventory').DataTable({ "columns": [{ "data": "department_or_division" }, { "data": "dataset_name" }, { "data": "dataset_description" }], "columnDefs": [{ "data": null, "defaultContent": "", "targets": -1 }] }); // Construct a SODA query string - I'm using the farmers market data for my experiment url = 'https://data.sfgov.org/resource/q6xv-9c3b.json'; $.getJSON(url, function(data, textstatus) { table.rows.add(data).draw(); }); // end $.getJSON }); // Highlight the top nav as scrolling occurs /*$('body').scrollspy({ target: '.navbar-fixed-top' })*/ // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function() { $('.navbar-toggle:visible').click(); }); var now = moment(); var dueDate = moment('2015-03-13'); var weeks = dueDate.diff(now, 'weeks'); $('.due-in').html('in ' + weeks + ' weeks on '); $('table').addClass('table table-striped');
JavaScript
0.999862
@@ -617,17 +617,8 @@ et). -parent(). data
205cfdafc933e0e93b70ce8b84692b1324edb167
append copy text area at correct element
src/context_menu.js
src/context_menu.js
import {UICorePlugin, Events, Styler, template} from 'Clappr' import pluginStyle from './public/context_menu.scss' import templateHtml from './public/context_menu.html' export default class ContextMenuPlugin extends UICorePlugin { get name() { return 'context_menu' } get attributes() { return { 'class': 'context-menu' } } get mediaControl() { return this.core.mediaControl } get template() { return template(templateHtml) } get exposeVersion() { return { label: `Clappr Player v${Clappr.version}`, name: 'version' } } get copyURL() { return { label: 'Copy URL', name: 'copyURL' } } get copyURLCurrentTime() { return { label: 'Copy URL on current time', name: 'copyURLCurrentTime' } } get loop() { return { label: 'Loop: ', name: 'loop', class: this.core.options.loop ? 'on' : 'off' } } get loopEnable() { return this.core.getCurrentPlayback().el.loop } get events() { return { 'click [data-copyURL]': 'onCopyURL', 'click [data-copyURLCurrentTime]': 'onCopyURLCurrentTime', 'click [data-loop]': 'onToggleLoop' } } constructor(core) { super(core) this.bindEvents() } bindEvents() { this.stopListening() if (this.mediaControl) { this.listenTo(this.mediaControl, Events.MEDIACONTROL_CONTAINERCHANGED, this.containerChanged) if (this.container) { this.listenTo(this.container, Events.CONTAINER_CONTEXTMENU, this.toggleContextMenu) this.listenTo(this.container, Events.CONTAINER_CLICK, this.hide) } } $('body').on('click', this.hide.bind(this)) } destroy() { $('body').off('click', this.hide.bind(this)) this.stopListening() super.destroy() } containerChanged() { this.container = this.core.getCurrentContainer() this.bindEvents() } toggleContextMenu(event) { event.preventDefault() this.show(event.offsetY, event.offsetX) } show(top, left) { !this.playerElement && this.calculateContextMenuLimit() let finalTop = top > this.maxHeight ? this.maxHeight : top let finalLeft = left > this.maxWidth ? this.maxWidth : left this.hide() this.$el.css({ top: finalTop, left: finalLeft}) this.$el.show() } calculateContextMenuLimit() { this.playerElement = document.querySelector('[data-player]') this.maxWidth = this.playerElement.clientWidth - 160 this.maxHeight = this.playerElement.clientHeight - 200 } hide() { this.$el.hide() } copyToClipboard(value, $el) { if (!$el) return let $copyTextarea = $('<textarea class="copytextarea"/>') $copyTextarea.text(value) $el.append($copyTextarea) let copyTextarea = document.querySelector('.copytextarea'); copyTextarea.select(); try { document.execCommand('copy'); } catch (err) { throw Error(err) } $copyTextarea.remove() } onCopyURL() { this.copyToClipboard(window.location.href, this.$el) } onCopyURLCurrentTime() { let url = window.location.href const current_time = Math.floor(this.container.getCurrentTime()) if (window.location.search == '') { url += `?s=${current_time}` } else { if (window.location.search.split(/[\?=&]/g).indexOf('s') == -1) { url += `&s=${current_time}` } else { let search = window.location.search.split(/s=\d+&*/g)[1] if (search == '') { url = `${window.location.href.replace(window.location.search, '')}${search}?s=${current_time}` } else { search = window.location.search.split(/s=\d+&*/g).join('') url = `${window.location.href.replace(window.location.search, '')}${search}&s=${current_time}` } } } this.copyToClipboard(url, this.$el) } onToggleLoop() { this.core.options.loop = !this.loopEnable this.core.getCurrentPlayback().el.loop = !this.loopEnable this.$el.find('[data-loop]').toggleClass('on', this.loopEnable) this.$el.find('[data-loop]').toggleClass('off', !this.loopEnable) } render() { this.menuOptions = [this.copyURL, this.copyURLCurrentTime, this.loop, this.exposeVersion] this.$el.html(this.template({options: this.menuOptions})) this.$el.append(Styler.getStyleFor(pluginStyle)) this.core.$el[0].append(this.$el[0]) this.hide() this.disable() return this } }
JavaScript
0.000002
@@ -2710,16 +2710,19 @@ Textarea +%5B0%5D )%0A%0A l @@ -2763,16 +2763,30 @@ lector(' +.context-menu .copytex
1a6fc339f6f610f05ed23cf9da34280430e52ddd
fix typo
src/tasks/games-winners.js
src/tasks/games-winners.js
// Database setup require('../../config/mongo-db')(); // Models const Game = require('../models/game'); const GameResponse = require('../models/game-response'); // Game Rules const gameRules = require('../slackbot/game-rules'); Game.find({}).lean().exec((err, results) => { results.forEach((game) => { GameResponse.find({ 'gameId': game._id }).lean().exec((err, results) => { if (game.playerIds.length !== results.length) return; const gameCounter = gameRules.processToGameCounter(results); const drawByAll = gameRules.dhrawByAllPossibilites(gameCounter); const drawByOne = gameRules.drawByOnlyOnePossibility(gameCounter); if (!drawByAll && !drawByOne) { const winners = gameRules.giveWinners(gameCounter, results).map(winner => winner.userId); Game.update({ _id: game._id }, { winners }); } }); }) });
JavaScript
0.999991
@@ -541,17 +541,16 @@ eRules.d -h rawByAll
8f4a1b63e252b53ffbaca036eca4d3de4c66b282
only parse timestamp once
generate.js
generate.js
const level = require('level'); const path = require('path'); const h = require('virtual-dom/h'); const createElement = require('virtual-dom/create-element'); const inline = require('html-inline'); const fromString = require('from2-string'); const process = require('process'); const moment = require('moment'); const wordcount = require('wordcount'); const roundTo = require('round-to'); const streamEach = require('stream-each'); const topUsers = require('./lib/top-users'); const mostQuestions = require('./lib/most-questions'); const db = level(path.resolve(__dirname, 'db'), {valueEncoding: 'json'}); const users = {}; function onData(data, next) { if (!users[data.user]) { users[data.user] = { lines: 0, avgWords: 0, quotes: [], latest: moment.utc(data.timestamp, moment.ISO_8601), questions: 0 }; } users[data.user].lines++; // Cumulative moving average of the number of words in this user's messages. var avg = users[data.user].avgWords; avg += (wordcount(data.message) - avg) / users[data.user].lines; users[data.user].avgWords = avg; users[data.user].quotes.push(data.message); if (moment.utc(data.timestamp, moment.ISO_8601).isAfter(users[data.user].latest)) { users[data.user].latest = moment.utc(data.timestamp, moment.ISO_8601); } if (data.message.indexOf('?') !== -1) { users[data.user].questions++; } next(); } function render() { const bigAsk = mostQuestions(users); const bigNumbers = h('table', [ h('thead', [ h('tr', [ h('th', 'big numbers') ]) ]), h('tbody', [ h('tr', [ h('td', `Why does ${bigAsk[0][0]} ask so many questions? ${roundTo(100 * bigAsk[0][1], 1)}% of their lines contained a question! ${bigAsk[1][0]} came in close second with ${roundTo(100 * bigAsk[1][1], 1)}% of their lines containing a question.`) ]) ]) ]); const content = h('div', [ h('p', `Stats generated on ${moment.utc().toISOString()}`), h('p', `In the last 31 days, a total of ${Object.keys(users).length} different nicks were represented on destiny.gg.`), topUsers(users), bigNumbers ]); const html = fromString(` <!doctype html> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> ${createElement(content).toString()} </body> </html> `); html.pipe(inline({ignoreImages: true})).pipe(process.stdout); } streamEach(db.createValueStream(), onData, render);
JavaScript
0.999999
@@ -651,16 +651,77 @@ next) %7B%0A + const time = moment.utc(data.timestamp, moment.ISO_8601);%0A%0A if (!u @@ -835,51 +835,12 @@ st: -moment.utc(data.timestamp, moment.ISO_8601) +time ,%0A @@ -1175,51 +1175,12 @@ if ( -moment.utc(data.timestamp, moment.ISO_8601) +time .isA @@ -1246,51 +1246,12 @@ t = -moment.utc(data.timestamp, moment.ISO_8601) +time ;%0A
786208ea15626ebc7769375e4b98bbb6fcd3428f
stop testing on latest Edge. (#31125)
js/tests/browsers.js
js/tests/browsers.js
/* eslint-env node */ /* eslint-disable camelcase */ const browsers = { safariMac: { base: 'BrowserStack', os: 'OS X', os_version: 'High Sierra', browser: 'Safari', browser_version: 'latest' }, chromeMac: { base: 'BrowserStack', os: 'OS X', os_version: 'High Sierra', browser: 'Chrome', browser_version: 'latest' }, firefoxMac: { base: 'BrowserStack', os: 'OS X', os_version: 'High Sierra', browser: 'Firefox', browser_version: 'latest' }, edgeWin10: { base: 'BrowserStack', os: 'Windows', os_version: '10', browser: 'Edge', browser_version: '16' }, edgeWin10Latest: { base: 'BrowserStack', os: 'Windows', os_version: '10', browser: 'Edge', browser_version: 'latest' }, chromeWin10: { base: 'BrowserStack', os: 'Windows', os_version: '10', browser: 'Chrome', browser_version: 'latest' }, firefoxWin10: { base: 'BrowserStack', os: 'Windows', os_version: '10', browser: 'Firefox', browser_version: 'latest' }, iphoneX: { base: 'BrowserStack', os: 'ios', os_version: '11.0', device: 'iPhone X', real_mobile: true }, pixel2: { base: 'BrowserStack', os: 'android', os_version: '8.0', device: 'Google Pixel 2', real_mobile: true } } const browsersKeys = Object.keys(browsers) module.exports = { browsers, browsersKeys }
JavaScript
0
@@ -644,152 +644,8 @@ %7D,%0A - edgeWin10Latest: %7B%0A base: 'BrowserStack',%0A os: 'Windows',%0A os_version: '10',%0A browser: 'Edge',%0A browser_version: 'latest'%0A %7D,%0A ch
97e8ac0bd8b88a585e77148561d20ffcaae2473c
Fix #15 Treat EISDIR like EPERM
rimraf.js
rimraf.js
module.exports = rimraf rimraf.sync = rimrafSync var path = require("path") , fs try { // optional dependency fs = require("graceful-fs") } catch (er) { fs = require("fs") } // for EMFILE handling var timeout = 0 exports.EMFILE_MAX = 1000 exports.BUSYTRIES_MAX = 3 function rimraf (p, cb) { if (!cb) throw new Error("No callback passed to rimraf()") var busyTries = 0 rimraf_(p, function CB (er) { if (er) { if (er.code === "EBUSY" && busyTries < exports.BUSYTRIES_MAX) { busyTries ++ var time = busyTries * 100 // try again, with the same exact callback as this one. return setTimeout(function () { rimraf_(p, CB) }, time) } // this one won't happen if graceful-fs is used. if (er.code === "EMFILE" && timeout < exports.EMFILE_MAX) { return setTimeout(function () { rimraf_(p, CB) }, timeout ++) } // already gone if (er.code === "ENOENT") er = null } timeout = 0 cb(er) }) } // Two possible strategies. // 1. Assume it's a file. unlink it, then do the dir stuff on EPERM // 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR // // Both result in an extra syscall when you guess wrong. However, there // are likely far more normal files in the world than directories. This // is based on the assumption that a the average number of files per // directory is >= 1. // // If anyone ever complains about this, then I guess the strategy could // be made configurable somehow. But until then, YAGNI. function rimraf_ (p, cb) { fs.unlink(p, function (er) { if (er && er.code === "ENOENT") return cb() if (er && er.code === "EPERM") return rmdir(p, cb) return cb(er) }) } function rmdir (p, cb) { fs.readdir(p, function (er, files) { if (er) return cb(er) var n = files.length if (n === 0) return fs.rmdir(p, cb) var errState files.forEach(function (f) { rimraf(path.join(p, f), function (er) { if (errState) return if (er) return cb(errState = er) if (--n === 0) fs.rmdir(p, cb) }) }) }) } // this looks simpler, and is strictly *faster*, but will // tie up the JavaScript thread and fail on excessively // deep directory trees. function rimrafSync (p) { try { fs.unlinkSync(p) } catch (er) { if (er.code === "ENOENT") return if (er.code !== "EPERM") throw er fs.readdirSync(p).forEach(function (f) { rimrafSync(path.join(p, f)) }) fs.rmdirSync(p) } }
JavaScript
0
@@ -1125,16 +1125,26 @@ on EPERM + or EISDIR %0A// 2. A @@ -1701,32 +1701,33 @@ )%0A if (er && +( er.code === %22EPE @@ -1721,32 +1721,57 @@ code === %22EPERM%22 + %7C%7C er.code === %22EISDIR%22) )%0A return r @@ -2515,16 +2515,40 @@ %22EPERM%22 + && er.code !== %22EISDIR%22 )%0A
ffa1a16ca5aeb94e7384e0d65faffd153b14523a
Update heights on page fully loaded
jquery.equal-height.js
jquery.equal-height.js
/*! * jQuery Equal Height v0.0.1 (https://github.com/Nikker/jquery.equal-height) * Copyright 2015-2016 Nikki DelRosso * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ if (typeof jQuery === 'undefined') { throw new Error('The jQuery equal height extension requires jQuery!'); } jQuery.fn.equalHeight = function() { var $ = jQuery; var that = this; var setHeights = function() { var elems = {}; var cont = $(that); // Reset the elements heights cont.each(function() { $(this).height(''); }); // Create a mapping of elements and the max height for all elements at that top offset cont.each(function() { var t = $(this).offset().top; if (typeof elems[t] == "undefined") elems[t] = {maxHeight: 0, e: []}; elems[t].e.push($(this)); elems[t].maxHeight = Math.max($(this).outerHeight(), elems[t].maxHeight); }); // Apply the max height to all elements in each offset class for (var t in elems) { var mh = elems[t].maxHeight; for (var i in elems[t].e) { var e = elems[t].e[i]; var padding = e.outerHeight() - e.height(); e.height(mh - padding); } } }; setHeights(); $(window).resize(setHeights); $(this).find('img').load(setHeights); };
JavaScript
0
@@ -25,17 +25,17 @@ ht v0.0. -1 +2 (https: @@ -1227,11 +1227,48 @@ ights);%0A +%09$(window).bind('load', setHeights);%0A %7D;%0A
41d7823227ccad99c666b8f77dd0c8a23ba3e68a
Drop table if exists
test/acceptance/batch/leader.job.query.order.test.js
test/acceptance/batch/leader.job.query.order.test.js
require('../../helper'); var assert = require('../../support/assert'); var TestClient = require('../../support/test-client'); var BatchTestClient = require('../../support/batch-test-client'); var JobStatus = require('../../../batch/job_status'); describe('multiple batch clients job query order', function() { before(function(done) { this.batchTestClient1 = new BatchTestClient({ name: 'consumerA' }); this.batchTestClient2 = new BatchTestClient({ name: 'consumerB' }); this.testClient = new TestClient(); this.testClient.getResult('create table ordered_inserts (status numeric)', done); }); after(function (done) { this.batchTestClient1.drain(function(err) { if (err) { return done(err); } this.batchTestClient2.drain(function(err) { if (err) { return done(err); } this.testClient.getResult('drop table ordered_inserts', done); }.bind(this)); }.bind(this)); }); function createJob(queries) { return { query: queries }; } it('should run job queries in order (multiple consumers)', function (done) { var jobRequest1 = createJob(["insert into ordered_inserts values(1)", "insert into ordered_inserts values(2)"]); var jobRequest2 = createJob(["insert into ordered_inserts values(3)"]); var self = this; this.batchTestClient1.createJob(jobRequest1, function(err, jobResult1) { if (err) { return done(err); } this.batchTestClient2.createJob(jobRequest2, function(err, jobResult2) { if (err) { return done(err); } jobResult1.getStatus(function (err, job1) { if (err) { return done(err); } jobResult2.getStatus(function(err, job2) { if (err) { return done(err); } assert.equal(job1.status, JobStatus.DONE); assert.equal(job2.status, JobStatus.DONE); self.testClient.getResult('select * from ordered_inserts', function(err, rows) { assert.ok(!err); assert.deepEqual(rows, [{ status: 1 }, { status: 2 }, { status: 3 }]); assert.ok( new Date(job1.updated_at).getTime() < new Date(job2.updated_at).getTime(), 'job1 (' + job1.updated_at + ') should finish before job2 (' + job2.updated_at + ')' ); done(); }); }); }); }); }.bind(this)); }); });
JavaScript
0.000002
@@ -565,17 +565,68 @@ tResult( -' +%0A 'drop table if exists ordered_inserts; create t @@ -664,21 +664,42 @@ meric)', - done +%0A done%0A );%0A %7D @@ -898,211 +898,12 @@ ain( -function(err) %7B%0A if (err) %7B%0A return done(err);%0A %7D%0A%0A this.testClient.getResult('drop table ordered_inserts', done);%0A %7D.bind(this) +done );%0A
07ec452e48a972eb3dd0e5d74436d477552266e2
stop interest form confirmation message from hiding
src/components/InterestSignupForm.js
src/components/InterestSignupForm.js
import React, { Component } from 'react'; import apiFetch from '../actions/index'; export class InterestSignupForm extends Component { constructor (props) { super(props); this.state = { message: null, success: null, email: "" }; } handleSubmit = (event) => { if(event) { //so tests don't get funky event.preventDefault(); event.stopPropagation(); } let d = new FormData(); let email = this.state.email; d.append('email', email); return apiFetch('interest/signup',{ method: 'POST', body: d }).then((response) => response.json()) .then((json) => { this.setState({success: json.success}); if(json.success === false) { this.setState({message: json.message}); let message = json.message; this.props.recordEvent("interestForm","submit_error", {message,email}); } else { this.setState({message: json.data}); //upon success, clear the form. this.setState({email: ""}); this.props.recordEvent("interestForm","submit_success", {email}) } }); }; changeEmail(event) { this.setState({email: event.target.value}); } render () { let canSubmit = (this.state.email.length > 3); return ( <div> <label htmlFor="email"><p className="white">Sign up for updates on when applications open!</p></label> <form className="interestForm"onSubmit={this.handleSubmit.bind(this)}> <input id="email" name="email" type="email" value={this.state.email} onChange={this.changeEmail.bind(this)} placeholder="Email"/> <button type="submit" disabled={!canSubmit}>Submit</button> <p>{this.state.message}</p> </form> </div> ); } } //now the redux integration layer import { recordEvent } from '../actions/users'; import { connect } from 'react-redux' function mapStateToProps (state) { return {}; } const mapDispatchToProps = (dispatch, ownProps) => ({ recordEvent: (event, subtitle, context) => { dispatch(recordEvent(event, subtitle, context)); } }); export default connect(mapStateToProps, mapDispatchToProps)(InterestSignupForm);
JavaScript
0
@@ -2001,16 +2001,34 @@ %3Cp + className=%22white%22 %3E%7Bthis.s
cab13ebdc160a5389e7457c5365e45872544f50b
add jQuery CDN host
js/global.js
js/global.js
// JavaScript Document // Avoid `console` errors in browsers that lack a console. if (!(window.console && console.log)) { (function() { var noop = function() {}; var methods = ['assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'markTimeline', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn']; var length = methods.length; var console = window.console = {}; while (length--) { console[methods[length]] = noop; } }()); } /** ##################################### # # # Project Namespace # # # ##################################### */ var Brandung = Brandung || {}; /** * set folder path * @type {string} */ Brandung.folderPath = '%%public%%/js/'; /** * IE <= 8 detection * feature detection for IE <= IE8 * @type {boolean} */ Brandung.IE8 = (document.all && !document.addEventListener) ? true : false; /** ##################################### # # # Load project dependencies and # # proceed # # # ##################################### */ // Check If we have an IE8, if so just create a new Deferred to be able to call $.then() // for all modern browsers load the main plugins via basket Brandung.DeferMainPlugins = Brandung.IE8 ? jQuery.Deferred() : basket.require( { url : Brandung.folderPath + 'libs/vendor/jquery/jquery.min.js', unique : '1.11.0' }, { url : Brandung.folderPath + 'libs/vendor/modernizr/modernizr.custom.min.js', unique : '2.8.1' } ); // Just resolve the main deferred if we have an ie8, because jquery and modernizr are already loaded if(Brandung.IE8) { Brandung.DeferMainPlugins.resolve(); } Brandung.DeferMainPlugins.then(function () { (function($) { // The same as above except that we are creating a real deferred by using the $.when method in IE8 // for all modern browsers load the load plugin via basket Brandung.DeferLoadPlugin = Brandung.IE8 ? $.when($.getScript(Brandung.folderPath + 'libs/bra/loadmodule/jquery.loadmodule.min.js')) : basket.require( { url : Brandung.folderPath + 'libs/bra/loadmodule/jquery.loadmodule.min.js', unique : '1.0.0' } ); Brandung.DeferLoadPlugin.then(function () { /** ##################################### # # # mobile stuff functions # # # ##################################### */ Brandung.Mobile = { init: function () { // Place here all functions that need to be invoked on every page load } }; /** * check orientation * * add orientation class to body tag */ Brandung.Mobile.checkOrientation = function () { if (window.orientation != 0) { $('body').removeClass('portrait').addClass('landscape'); } else { $('body').removeClass('landscape').addClass('portrait'); } }; /** * get media device selector */ if (Brandung.IE8) { Brandung.Mobile.mediaDevice = 'desktop'; } else { Brandung.Mobile.mediaDevice = window.getComputedStyle(document.body, ':after').getPropertyValue('content'); } Brandung.Mobile.getWindowWidth = function () { if (Brandung.IE8) { // feature detection for IE <= IE8 Brandung.Mobile.mediaDevice = 'desktop'; } else { Brandung.Mobile.mediaDevice = window.getComputedStyle(document.body, ':after').getPropertyValue('content'); } }; // add event listener $(window).load(function () { Brandung.Mobile.getWindowWidth(); Brandung.Mobile.checkOrientation(); }); $(window).resize(function () { // call function only on desktop devices if ((!Modernizr.touch && window.orientation != 0) || (Modernizr.touch && window.orientation != 0)) { Brandung.Mobile.getWindowWidth(); } }); $(window).bind('orientationchange', function () { Brandung.Mobile.checkOrientation(); }); /** ##################################### # # # jQuery plugins object # # # ##################################### */ Brandung.Plugins = { init: function () { // load plugin scripts Brandung.Plugins.loadScripts(); } }; /** * load scripts */ Brandung.Plugins.loadScripts = function () { /** Loading plugin * * @param {array} - List of dependency paths (js and css) * @param {function} - callback function, when all dependencies are available * @param {string|int} - if this parameter changes, the dependencies will be refetched * from the server */ // dummy call // $('[SELECTOR]').loadModule([ // Brandung.folderPath + '[PATH_TO_JS_SOURCE]' // ], // function () { // // do something after script has been loaded // }, 'unique'); // load hotfix files $('body').loadModule([ Brandung.folderPath + 'hotfix.js', '%%public%%/css/hotfix.css' ], function () { }, new Date().getTime()); // loader helper.js on mobile devices if(Brandung.Mobile.mediaDevice === 'smartphone') { $('body').loadModule([ Brandung.folderPath + 'libs/vendor/h5bp/helper.js' ], function () { // init MBP helper functions MBP.scaleFix(); MBP.hideUrlBar(); }, 'unique'); } }; /** ##################################### # # # helper functions # # # ##################################### */ Brandung.Helpers = { init: function () { // Place here all functions that need to be invoked on every page load } }; /** ##################################### # # # global functions # # # ##################################### */ Brandung.Functions = { init: function () { // Place here all functions that need to be invoked on every page load } }; // snippets placeholer // --- start|bra-pb: js --- // --- end|bra-pb: js --- /** ##################################### # # # document ready # # # ##################################### */ $(function () { // init objects Brandung.Mobile.init(); Brandung.Plugins.init(); Brandung.Helpers.init(); Brandung.Functions.init(); }); }, function(err) { console.error(err); }); })(jQuery); }, function(err) { console.error(err); });
JavaScript
0
@@ -1514,49 +1514,54 @@ l : -Brandung.folderPath + 'libs/vendor/jquery +'//ajax.googleapis.com/ajax/libs/jquery/1.11.0 /jqu
fdcd2d19f38df6dd12df939447d56820ac750edb
Remove console statements.
website/mcapp.projects/src/app/project/processes/process/services/process-edit.service.js
website/mcapp.projects/src/app/project/processes/process/services/process-edit.service.js
angular.module('materialscommons').factory("processEdit", processEdit); function processEdit() { /** * fillSetUp: will read all the setup values from process * and place inside template. * */ function setUp(template, process) { process.setup[0].properties.forEach(function(property) { var i = _.indexOf(template.setup[0].properties, function(template_property) { return template_property.property.attribute === property.attribute }); if (i > -1) { template.setup[0].properties[i].property.value = property.value; template.setup[0].properties[i].property.name = property.name; template.setup[0].properties[i].property.description = property.description; template.setup[0].properties[i].property.unit = property.unit; template.setup[0].properties[i].property.id = property.id; template.setup[0].properties[i].property.setup_id = property.setup_id; template.setup[0].properties[i].property._type = property._type; template.setup[0].properties[i].property.attribute = property.attribute; // If selection type then modify the choices when Other is selected, since the // user may have modified the value of other. We need to do this otherwise the // default other in the choices will update the value and the user will lose what // they set. if (property._type === 'selection') { if (property.value.name === 'Other') { let otherChoicesIndex = _.indexOf(template.setup[0].properties[i].property.choices, (c) => c.name === 'Other'); if (otherChoicesIndex !== -1) { template.setup[0].properties[i].property.choices[otherChoicesIndex].value = property.value.value; } } } } }); process.setup = template.setup; return process; } function samples(process) { //process.input_samples = process.input_samples; return process; } function files(process) { //process['input_files'] = process.input_files.map(function(file) { // return {id: file.id, name: file.name} //}); //process['output_files'] = process.output_files.map(function(file) { // return {id: file.id, name: file.name} //}); return process; } function addCompositionToMeasurements(prop, measurements) { for (let i = 0; i < measurements.length; i++) { let measurement = measurements[i]; if (measurement.property.attribute === 'composition') { measurement.property.unit = prop.unit; measurement.property.value = prop.value; break; } } } function setupMeasurements(process, templateMeasurements, template) { if (template.category === 'create_samples') { // Hack, just extract the composition from one of the samples to display as the measurements. let foundComposition = false; for (let i = 0; i < process.output_samples.length; i++) { let sample = process.output_samples[i]; for (let k = 0; k < sample.properties.length; k++) { let prop = sample.properties[k]; if (prop.attribute === 'composition') { addCompositionToMeasurements(prop.best_measure[0], templateMeasurements); foundComposition = true; } } if (foundComposition) { break; } } } process.measurements = templateMeasurements; } return { fillProcess: function(template, process) { process = setUp(template, process); process = samples(process); process = files(process); console.log("process-edit.service - fillProcess - just before setupMeasurements",process); setupMeasurements(process, template.measurements, template); console.log("process-edit.service - fillProcess - just after setupMeasurements",process); if (!('output_samples' in process)) { process.output_samples = []; } if (!('transformed_samples' in process)) { process.transformed_samples = []; } return process; }, addToSamplesFiles: function(files, process) { files.forEach(function(f) { var i = _.indexOf(process.samples_files, function(item) { return f.id === item.id && f.sample_id == item.sample_id; }); if (i !== -1) { process.samples_files.splice(i, 1); process.samples_files.push({ id: f.id, command: f.command, name: f.name, sample_id: f.sample_id }); } else { if (f.command) { process.samples_files.push({ id: f.id, command: f.command, name: f.name, sample_id: f.sample_id }); } } }); return process; }, refreshSample: function(files, sample) { files.forEach(function(f) { if (f.command) { var i = _.indexOf(sample.files, function(item) { return f.id === item.id && f.sample_id == sample.id; }); if (i !== -1) { sample.files.splice(i, 1); sample.files.push({ id: f.id, command: f.command, name: f.name, sample_id: f.sample_id, linked: f.linked }); } else { sample.files.push({ id: f.id, command: f.command, name: f.name, sample_id: f.sample_id, linked: f.linked }); } } }); return sample; } }; }
JavaScript
0.000001
@@ -4148,271 +4148,66 @@ -console.log(%22process-edit.service - fillProcess - just before setupMeasurements%22,process);%0A setupMeasurements(process, template.measurements, template);%0A console.log(%22process-edit.service - fillProcess - just after setupMeasurements%22,process +setupMeasurements(process, template.measurements, template );%0A
da6b7e6983c43d784310d683528c27c8146a128d
clear output before running
CoolToJS/scripts/demo.js
CoolToJS/scripts/demo.js
var CoolToJSDemo; (function (CoolToJSDemo) { 'use strict'; // faking the transpilation process for now var coolProgramExample = '\ class Main inherits IO {\n\ main() : Object {\n\ out_string("Hello, world.\\n")\n\ };\n\ };\ '; var coolProgramExampleForDebugging = '\ something here else\n\ if\n\ sdf45\n\ '; var generatedJavaScriptExample = '\ // note that this generated code (and its output)\n\ // is currently hardcoded while the transpiler\n\ // is being built\n\ \n\ function __outputFunction(output) {\n\ document.getElementById(\'output\').innerHTML += output;\n\ }\n\ \n\ __outputFunction("Hello, world.\\n");\ '; var outputExample = 'Hello, world.\n'; var coolEditor = CodeMirror(document.getElementById('cool-editor'), { value: coolProgramExampleForDebugging, mode: 'javascript', lineNumbers: true, indentUnit: 4, }); var generatedJavaScriptEditor = CodeMirror(document.getElementById('generated-javascript'), { mode: 'javascript', lineNumbers: true, indentUnit: 4, readOnly: true }); var hasBeenTranspiled = false; document.getElementById('transpile-button').onclick = function () { CoolToJS.Transpile({ coolProgramSources: coolEditor.getValue(), outputFunction: function (output) { document.getElementById('output').innerHTML += output; } }); generatedJavaScriptEditor.setValue(generatedJavaScriptExample); hasBeenTranspiled = true; }; document.getElementById('play-button').onclick = function () { if (hasBeenTranspiled) { eval(generatedJavaScriptEditor.getValue()); } }; })(CoolToJSDemo || (CoolToJSDemo = {}));
JavaScript
0.000008
@@ -1669,24 +1669,86 @@ anspiled) %7B%0A + document.getElementById('output').innerHTML = '';%0A
b6c9c36c016d4c9f51f4125830fa4e0c53f0395b
Add a noop pipe to ensure end is called
src/tasks/nuget-restore.js
src/tasks/nuget-restore.js
import gulp from 'gulp'; import nugetRestore from 'gulp-nuget-restore'; export default { /** * Task name * @type {String} */ name: 'sitecore:nuget-restore', /** * Task description * @type {String} */ description: 'Restore all nuget packages for solution.', /** * Task default configuration * @type {Object} */ config: { deps: [], }, /** * Task help options * @type {Object} */ help: { 'solution, -s': 'Solution file path', }, /** * Task function * @param {object} config * @param {Function} end * @param {Function} error */ fn(config, end, error) { if (!config.solution) { error('A solution file path was not set.'); return; } gulp.src(config.solution) .pipe(nugetRestore()) .on('end', end); }, };
JavaScript
0
@@ -18,16 +18,47 @@ 'gulp';%0A +import es from 'event-stream';%0A import n @@ -819,16 +819,52 @@ tore())%0A + .pipe(es.through(() =%3E %7B%7D))%0A .o
5b530b9545c4eb9428def5e85b0308edf3a145f8
move setting of headers to same place
lib/Agent.js
lib/Agent.js
"use strict"; var Promise = require('bluebird') , winston = require('winston') , _ = require('lodash') , os = require('os') , uuid = require('node-uuid') , config = require('config-url') , rp = require('request-promise') , request = require('request') , urljoin = require('url-join') , retry = require('bluebird-retry') // , net = require('net') , ip = require('ip') , Request = require('./Request') ; class Agent { constructor(pool) { this.pool = pool; if (!this.pool) { throw new Error('"type" param not defined or recognized'); } this.group = config.get('agent.group-id'); this.id = uuid.v4(); if (!this.group) { throw new Error('config error: "agent.group-id" is required for the agent to connect to the relay. make sure that your group id is unique uuid.'); } } initialize(cb) { return this.pool.initialize().asCallback(cb); } listen() { winston.info('agent connecting to', config.getUrl('relay')); let url = config.getUrl('relay'); this.socket = require('socket.io-client')(url); this.socket.on('connect', () => { winston.info('connected'); this.start_heartbeat(); }); this.socket.on('disconnect', () =>{ this.end_heartbeat(); winston.info('disconnected'); }); const http = require('http'); let proxy = http.createServer((req, res) => { // todo [akamel] we only parse this to get the request id out... seems we should be able to bypass it let r = new Request(JSON.parse(req.headers['__metadata'])); this.pool .run(r) .then((worker) => { return Promise.fromCallback((cb) => { worker.on('ready', (err, data, container) => { let port = data.NetworkSettings.Ports['80/tcp'][0].HostPort; // todo [akamel] rename doc to metadata let headers = { '__metadata' : JSON.stringify(r.doc) }; res.setHeader('RunOn-Agent', `${os.hostname()} (${ip.address()})`); // todo [akamel] consider moving these headers to worker? let pragma = _.get(r.doc, 'manual.pragma'); if (pragma) { res.setHeader('Manual-Pragma', JSON.stringify(pragma)); } let time = process.hrtime(); let count = 0; let url = `http://localhost:${port}`; retry(() => { count++; return rp.get(url); }, { interval : 10, timeout : 5000, max_tries : -1, backoff : 2, max_interval : 60 }) .then(() => Promise .fromCallback((cb) => { console.log('going to:', urljoin(url, req.url)) req .pipe(request({ url : urljoin(url, req.url), headers : headers })) .on('response', (res) => { let content_type = _.get(r.doc, 'manual.output["content-type"]'); if (content_type) { res.headers['content-type'] = content_type; } }) .on('error', (err) => { cb(new Error('request failed: ' + url)); }) .pipe(res) .on('error', (err) => { cb(new Error('response failed')); }); res.on('finish', cb); }) ) .then(() => { let diff = process.hrtime(time); winston.info(`needed ${count} retries to connect to container, in ${(diff[0] * 1e9 + diff[1]) / 1e6} seconds`); }) .asCallback(cb); }); }); }) .catch((err) => { res.statusCode = 500; res.write(err.toString()); res.end(); }); // todo [akamel] handle other worker events here }).listen(config.getUrlObject('agent').port); // server.on('clientError', (err, socket) => { // socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); // }); } start_heartbeat() { this.end_heartbeat(); var ping = () => { var data = { name : os.hostname() // todo [akamel] use machine name or url in production [agent specific] , run_url : config.getUrl('agent') , id : this.id , group : this.group , uptime : process.uptime() , totalmem : os.totalmem() , freemem : os.freemem() , loadavg : os.loadavg() , cpus : os.cpus() // , workers : this.pool.info() }; this.socket.emit('/ping', data); }; this.heartbeat_timer_token = setInterval(ping, 10 * 1000); ping(); } end_heartbeat() { if (this.heartbeat_timer_token) { clearInterval(this.heartbeat_timer_token); } } } module.exports = Agent;
JavaScript
0
@@ -2138,362 +2138,8 @@ %7D;%0A%0A - res.setHeader('RunOn-Agent', %60$%7Bos.hostname()%7D ($%7Bip.address()%7D)%60);%0A%0A // todo %5Bakamel%5D consider moving these headers to worker?%0A let pragma = _.get(r.doc, 'manual.pragma');%0A if (pragma) %7B%0A res.setHeader('Manual-Pragma', JSON.stringify(pragma));%0A %7D%0A%0A @@ -2177,24 +2177,24 @@ s.hrtime();%0A + @@ -2596,82 +2596,8 @@ %3E %7B%0A - console.log('going to:', urljoin(url, req.url))%0A @@ -2914,24 +2914,24 @@ ent_type) %7B%0A - @@ -3025,16 +3025,440 @@ %7D +%0A%0A res.headers%5B'RunOn-Agent'%5D = %60$%7Bos.hostname()%7D ($%7Bip.address()%7D)%60;%0A%0A // todo %5Bakamel%5D consider moving these headers to worker?%0A let pragma = _.get(r.doc, 'manual.pragma');%0A if (pragma) %7B%0A res.headers%5B'Manual-Pragma'%5D = JSON.stringify(pragma);%0A %7D %0A
b9d4bc092e00e00672b6cf235f4808ab7f1b2d6f
Drop next task output from queue
app/libs/queue/add.js
app/libs/queue/add.js
'use strict'; // Load requirements const assign = require('deep-assign'); // Load libraries const logger = require('../log'); // Variables let queueCache = []; // Send back the function module.exports = function(task) { return new Promise((resolve, reject) => { // Variables let added = [], promises = [], options = {}; // Exit without a task if ( ! task || typeof task !== 'object' ) { return reject('Missing or invalid task argument'); } // Loop through and assign the available jobs to the queue task.jobs.forEach((job) => { // Skip if already in queue if ( queueCache.includes(job.file) ) { return false; } // Add to cache to stop additional runs queueCache.push(job.file); this.total = queueCache.length; // Track files being added with this task added.push(job.basename); // Merge options for this task job.options = assign(options, job.options); // Add to the queue promises.push(this.items.add(() => { // Update queue length this.length = ( this.items.getQueueLength() + this.items.getPendingLength() ); // Update current task position this.current++; // Update overall counter task.overall = {total: this.total, current: this.current}; // DEBUG logger.info('Starting task {cyan:%s} of {green:%s}', this.current, this.total); // Queue data test if ( this.items.queue[0] ) { let next = this.items.queue[0].job; logger.info('Next task {green:' + next.basename + '}'); } // Send to conversion for processing return require('../conversion').run(job); })); // Add data to queue for lookup later this.items.queue[( this.items.queue.length - 1)].job = job; }); // DEBUG logger.info('Added:\n {green:' + added.join('\n ').trim() + '}'); // Unpause the queue this.items.maxPendingPromises = 1; this.items._dequeue(); // Wait for this task to complete to resolve Promise.all(promises).then((result) => { return resolve(result); }).catch((err) => { return reject(err); }); }); };
JavaScript
0.000001
@@ -1477,24 +1477,85 @@ est%0A +// Not needed, just keeping it for reference later%0A /* if ( this.it @@ -1688,24 +1688,26 @@ );%0A %7D +*/ %0A%0A //
e794b313b945f18b78ffd9454420c886bb7f87e0
change feed limit to 5 (#25)
src/infra/service/graph.js
src/infra/service/graph.js
// @flow const get = (url: string): Promise<any> => new Promise((resolve, reject) => { window.FB.api(url, fbRes => { if (fbRes.error) return reject(new Error(`${fbRes.error.code} - ${fbRes.error.message}` || fbRes.error)); return resolve(fbRes); }); }); class GraphList { url: string; data: {}[] = []; next: string = ''; previous: string = ''; fetch(url: string) { return get(url) .then(res => { this.data = [...this.data, ...res.data]; if (res.paging) { this.previous = res.paging.previous; this.next = res.paging.next; } else { this.previous = ''; this.next = ''; } }); } fetchForward(url: string, pages: number = 10, currentPage: number = 1) { return this.fetch(currentPage === 1 ? url : this.next) .then(() => { if (this.next && currentPage < pages) { return this.fetchForward(url, pages, currentPage + 1); } else { return this.data; } }); } getCommentBatch(postIds: string[], accessToken: string) { const commentUrl = postIds.map(id => ({ method: 'GET', relative_url: `${id}/comments?summary=1&filter=toplevel&fields=parent.fields(id),comments.summary(true),message,from,likes,created_time`, })); return fetch('https://graph.facebook.com', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ batch: commentUrl, access_token: accessToken, }), }) .then(res => res.json()) .then(data => { const comments = {}; (data || []).forEach((datum, index) => { comments[postIds[index]] = { comments: JSON.parse(datum.body), }; }); return comments; }); } } const login = () => new Promise((resolve, reject) => { window.FB.login(response => { if (response.authResponse) { resolve(response); } else { reject(new Error('User cancelled login or did not fully authorize.')); } }, { scope: 'public_profile, email' }); }); const logout = () => new Promise((resolve) => { window.FB.logout(); resolve(true); }); const getLoginStatus = () => new Promise((resolve, reject) => { window.FB.getLoginStatus((response) => { if (response.status === 'connected') { resolve(response); } else { reject(new Error('User not connected.')) } }); }); const getUser = () => get('/me?fields=id,name,email,picture') .then(res => { const user: UserProfile = { facebookId: res.id, name: res.name, email: res.email, picture: res.picture.data.url, }; return user; }); const getGroup = (groupId: string) => get(`/${groupId}?fields=id,name,privacy,cover,description,owner`) .then(res => { const group: Group = { id: res.id, name: res.name, privacy: res.privacy, cover: res.cover.source, description: res.description, owner: { id: res.owner.id, name: res.owner.name, }, } return group; }); const getGroupFeed = (groupId: string, pages: number): Promise<any> => { const url = `/${groupId}/feed?fields=created_time,id,message,updated_time,caption,story,description,from,link,name,picture,status_type,type,shares,permalink_url,likes.limit(10)&limit=10`; const list = new GraphList(); return list.fetchForward(url, pages); }; const getFeedComments = (commentId: string, accessToken: string): Promise<any> => { const url = `/${commentId}/comments?summary=1&filter=stream`; const list = new GraphList(); return list.fetchForward(url); }; const batchComments = (postIds: string[], accessToken: string) => { const list = new GraphList(); return list.getCommentBatch(postIds, accessToken); } export default { login, logout, getLoginStatus, getUser, getGroup, getGroupFeed, getFeedComments, batchComments, };
JavaScript
0
@@ -3394,18 +3394,17 @@ )&limit= -10 +5 %60;%0A con
1467608bef04b31c51b07b6225d47dca099e444e
Change timing on disqus loader animation
_assets/javascripts/app.js
_assets/javascripts/app.js
// // Sprockets Includes // //= require vendor/barba.min //= require vendor/web-animations.min // // var threadContainer = document.getElementById('disqus_thread'); var crossOnTrigger = document.querySelector('.comments__trigger__plus'); // http://dustindiaz.com/smallest-domready-ever function ready(cb) { /in/.test(document.readyState) // in = loadINg ? setTimeout(ready.bind(null, cb), 9) : cb(); } ready(function(){ // Page transitions Barba.Pjax.start(); var pageTransition = Barba.BaseTransition.extend({ start: function() { Promise.all([this.newContainerLoading, this.exit()]) .then(this.reveal.bind(this)) }, exit: function() { var _this = this; return new Promise(function(resolve, reject){ resolve(_this.oldContainer.animate({ opacity: [0.5, 0] }, 400)); }); }, reveal: function() { var _this = this; var newPage = this.newContainer; document.body.scrollTop = 0; this.oldContainer.style.display = 'none'; var fadeIn = newPage.animate({ opacity: [0.5, 1] }, 400); fadeIn.onfinish = function(e){ _this.done(); } } }); Barba.Pjax.getTransition = function() { return pageTransition; }; }); // Barba Pjax Page Load Listener Barba.Dispatcher.on('transitionCompleted', function() { // TypeSet MathJax MathJax.Hub.Queue(["Typeset",MathJax.Hub]); // Share Post dropdown var shareBtn = document.getElementById('shareDropdown'); if(shareBtn){ shareBtn.addEventListener('click', function(e){ var dropDown = document.querySelector('.post__sharelinks'); dropDown.style.display = dropDown.style.display == 'block' ? 'none' : 'block'; }); } // Progressive Reading Bar var bar = document.querySelector('.scroll-progress'); var rootElement = typeof InstallTrigger !== 'undefined' ? document.documentElement : document.body; if(bar){ document.addEventListener("scroll", function(e){ var dw = document.body.scrollWidth, dh = document.body.scrollHeight, wh = window.innerHeight, disqusHeight = threadContainer.clientHeight, bottomContentHeight = 700; pos = (rootElement).scrollTop, bw = ((pos / ((dh - (bottomContentHeight + disqusHeight)) - wh)) * 100); bar.style.width = bw+'%'; }); } // Show/Hide Disqus comments var commentTrigger = document.querySelector('.js-toggleComments'); if(commentTrigger){ commentTrigger.addEventListener('click', function() { console.log(threadContainer); var threadVisibility = threadContainer.style.display; threadContainer.style.display = threadVisibility == 'none' ? 'block' : 'none'; disqusComments(); }); } // Date for copyright var presentDate = new Date(), showDate = document.querySelector('.thisYear'); showDate.innerHTML = presentDate.getFullYear(); }); // Disqus Init function disqusComments() { var disqus_shortname = 'josephrexme'; var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; if(typeof(DISQUS) === 'undefined'){ crossOnTrigger.classList.add('comments__trigger--animated'); } if(crossOnTrigger.classList.contains('comments__trigger--xclose')){ crossOnTrigger.classList.remove('comments__trigger--xclose'); crossOnTrigger.classList.remove('comments__trigger--animated'); }else{ if(typeof(DISQUS) === 'undefined'){ setTimeout(function() { crossOnTrigger.classList.remove('comments__trigger--animated'); crossOnTrigger.classList.add('comments__trigger--xclose'); (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); },2000); }else{ crossOnTrigger.classList.add('comments__trigger--xclose'); } } }
JavaScript
0
@@ -2518,44 +2518,8 @@ ) %7B%0A - console.log(threadContainer);%0A @@ -3748,9 +3748,9 @@ %7D, -2 +3 000)
60cc903d531e6463335baf0cd1fb857491f67094
add Node and Base add size() and this.first this.N
src/structure/linked/Base.js
src/structure/linked/Base.js
class Base { constructor() { this.items = [] } add() { } remove() { } isEmpty() { return this.items.length === 0 } size() { return this.items.length } interator() { return this.items.entries() } } module.exports = Base
JavaScript
0
@@ -1,17 +1,17 @@ class -Bas +Nod e %7B%0A co @@ -41,109 +41,134 @@ item -s = -%5B%5D%0A %7D%0A add() %7B%0A %7D%0A remove() %7B%0A %7D%0A isEmpty() %7B%0A return this.items.length === 0%0A %7D%0A size +null;%0A this.next = null;%0A %7D%0A%7D%0A%0Aclass Base %7B%0A constructor() %7B%0A this.first = new Node();%0A this.N = 1%0A %7D%0A isEmpty () %7B @@ -183,25 +183,35 @@ urn +( this. -items.length +first.next === null); %0A %7D @@ -233,37 +233,38 @@ %7B%0A - return this.items.entries() +%7D%0A size() %7B%0A return this.N %0A %7D @@ -283,13 +283,27 @@ xports = + %7B%0A Node,%0A Base +%0A%7D
17cbf752e71c8207a441d6ffb9325f029104ea31
Update setLBound.js
mainRPi/sockets/serverSocket/setLBound.js
mainRPi/sockets/serverSocket/setLBound.js
JavaScript
0
@@ -1 +1,894 @@ +var mongoose=require('mongoose');%0Avar Monitor=require('../models/monitor.js');%0Avar envVariables=require('../../envVariables.js');%0Avar errors=require('../../errors.js');%0A%0Amodule.exports=function(socket)%7B%0A socket.on('editLBound',function(data,fn)%7B%0A if(Monitor.find(%7B_id:data.monitorID%7D,function(err,docs)%7B%0A if(err)%7B%0A throw err;%0A %7D%0A if(docs.length!=0)%7B%0A var monitorIndex=envVariables.monitorIDs.indexOf(data.monitorID);%0A if(monitorIndex!=-1)%7B%0A envVariables.monitors%5BmonitorIndex%5D.emit('editLBound',data,function(res,err)%7B%0A if(err)%7B%0A fn(null,err);%0A %7D%0A //success!%0A fn(res);%0A %7D);%0A %7D%0A else%7B%0A //monitor not connected%0A fn(null,errors.m001);%0A %7D%0A %7D%0A else%7B%0A //unidentified monitor%0A fn(null,errors.m003);%0A %7D%0A %7D);%0A %7D);%0A%7D %0A
a7d75b42f6fbcaee6ae226267d3c2c8d0779fbb8
Increase telnet timeout for seowon frequencies command.
config/custom_commands/seowon_frequencies.js
config/custom_commands/seowon_frequencies.js
// Change frequency plans for Seowon devices. // Args format: 3532500 5000,3537500 5000,3542500 5000,3547500 5000,3552500 5000,3557500 5000,3505000 10000,3515000 10000,3525000 10000,3535000 10000,3545000 10000,3555000 10000 var net = require('net'); var PORT = 23; var USERNAME = 'admin'; var PASSWORD = 'admin'; var FREQUENCIES_REGEX = /\s*([\d]+)\.\s*Frequency\s*:\s*([\d]+)\s\(KHz\),\s*Bandwidth\s*:\s*([\d\.]+)\s*\(MHz\)/gm var telnetConnect = function(host, callback) { var client = net.connect(PORT, host, function() { // enter username telnetExecute(USERNAME, client, "Password: ", function(err, response) { if (err) return callback(err, client); if (!timeout) return; // enter password telnetExecute(PASSWORD, client, "MT7109> ", function(err, response) { if (!timeout) return; clearTimeout(timeout); return callback(err, client); }); }); }); var timeout = setTimeout(function() { timeout = null; return callback('timeout', client); }, 2000); } var telnetExecute = function(command, connection, prompt, callback) { command += "\n"; var response = ''; var listener = function(chunk) { response += chunk.toString(); if (response.slice(0 - prompt.length) == prompt) { if (!timeout) return; clearTimeout(timeout); connection.removeListener('data', listener); return callback(null, response.slice(command.length, 0 - prompt.length)); } }; var end = function() { if (!timeout) return; clearTimeout(timeout); connection.removeListener('end', end); return callback(null, response.slice(command.length)); }; var timeout = setTimeout(function() { timeout = null; return callback('timeout', response); }, 2000); if (prompt) connection.on('data', listener); else connection.on('end', end); if (command) connection.write(command); } var parseFrequencies = function(frequenciesString) { var a = frequenciesString.split(',') var l = []; for (i in a) { var sp = a[i].trim().split(' '); var frequency = parseInt(sp[0]); var bandwidth = parseFloat(sp[1]); l.push([frequency, bandwidth]); } return l; } var findFrequency = function(haystack, needle) { for (i in haystack) { if (haystack[i][0] == needle[0] && haystack[i][1] == needle[1]) return i; } return -1; } var getDeviceIp = function(deviceId, callback) { var db = require('../../db'); var URL = require('url'); db.devicesCollection.findOne({_id : deviceId}, {'InternetGatewayDevice.ManagementServer.ConnectionRequestURL._value' : 1}, function(err, device) { var connectionRequestUrl = device.InternetGatewayDevice.ManagementServer.ConnectionRequestURL._value; var url = URL.parse(connectionRequestUrl); return callback(url.hostname); }); }; exports.init = function(deviceId, args, callback) { return exports.get(deviceId, args, callback); }; exports.get = function(deviceId, args, callback) { var currentFrequencies = []; getDeviceIp(deviceId, function(ip) { telnetConnect(ip, function(err, client) { // enter privileged mode telnetExecute("enable", client, "MT7109# ", function(err, response) { if (err) return callback(err); // show frequencies telnetExecute("show wmx freq", client, "MT7109# ", function(err, response) { if (err) return callback(err); while (f = FREQUENCIES_REGEX.exec(response)) { var frequency = parseInt(f[2]); var bandwidth = Math.floor(parseFloat(f[3]) * 1000); var freqStr = String(frequency) + ' ' + String(bandwidth); currentFrequencies.push(freqStr); } // log out telnetExecute("logout", client, null, function(err, response) { return callback(err, currentFrequencies.join(',')); }); }); }); }); }); }; exports.set = function(deviceId, args, callback) { var newFrequencies = parseFrequencies(args); var addFrequencies = []; var delFrequencies = []; getDeviceIp(deviceId, function(ip) { telnetConnect(ip, function(err, client) { // enter privileged mode telnetExecute("enable", client, "MT7109# ", function(err, response) { if (err) return callback(err); // show frequencies telnetExecute("show wmx freq", client, "MT7109# ", function(err, response) { if (err) return callback(err); while (f = FREQUENCIES_REGEX.exec(response)) { var index = parseInt(f[1]); var frequency = parseInt(f[2]); var bandwidth = Math.floor(parseFloat(f[3])); var i = findFrequency(newFrequencies, [frequency, bandwidth * 1000]); if (i == -1) delFrequencies.push(index); else newFrequencies.splice(i, 1); } for (f in newFrequencies) addFrequencies.push(newFrequencies[f]); if (addFrequencies.length == 0 && delFrequencies.length == 0) { // log out telnetExecute("logout", client, null, function(err, response) { return callback(err, args); }); return; } telnetExecute("wimax", client, "MT7109 (WiMax)# ", function(err, response) { if (err) return callback(err); var add, del; del = function() { if (delFrequencies.length == 0) { add(); return; } var i = delFrequencies.pop(); telnetExecute("wmx freq del " + i, client, "MT7109 (WiMax)# ", function(err, response) { if (err) return callback(err); del(); }); }; add = function() { if (addFrequencies.length == 0) { // commit telnetExecute("commit", client, "MT7109 (WiMax)# ", function(err, response) { if (err) return callback(err); // log out telnetExecute("logout", client, null, function(err, response) { return callback(null, args); }); }); return; } var i = addFrequencies.pop(); telnetExecute("wmx freq add " + i[0] + ' ' + i[1]/1000, client, "MT7109 (WiMax)# ", function(err, response) { if (err) return callback(err); add(); }); }; del(); }); }); }); }); }); };
JavaScript
0
@@ -1017,25 +1017,25 @@ ient);%0A %7D, -2 +4 000);%0A%7D%0A%0Avar
7ed6e321bef98af8c76a89f0ff401cfe286f3766
Fix LinkTo with query params
client/src/components/LinkTo.js
client/src/components/LinkTo.js
import React, { Component } from 'react' import {Link} from 'react-router-dom' import PropTypes from 'prop-types' import decodeQuery from 'querystring/decode' import utils from 'utils' import * as Models from 'models' const MODEL_NAMES = Object.keys(Models).map(key => { let camel = utils.camelCase(key) if (camel === 'location') { camel = 'anetLocation' } Models[camel] = Models[key] return camel }) export default class LinkTo extends Component { static propTypes = { componentClass: PropTypes.oneOfType([ PropTypes.string, PropTypes.func, ]), edit: PropTypes.bool, // Configures this link to look like a button. Set it to true to make it a button, // or pass a string to set a button type button: PropTypes.oneOfType([ PropTypes.bool, PropTypes.string, ]), target: PropTypes.string, } render() { let {componentClass, children, edit, button, className, ...componentProps} = this.props if (button) { componentProps.className = [className, 'btn', `btn-${button === true ? 'default' : button}`].join(' ') } else { componentProps.className = className } let modelName = Object.keys(componentProps).find(key => MODEL_NAMES.indexOf(key) !== -1) if (!modelName) { console.error('You called LinkTo without passing a Model as a prop') return null } let modelInstance = this.props[modelName] if (!modelInstance) return null let modelClass = Models[modelName] let to = modelInstance if (typeof to === 'string') { if (to.indexOf('?')) { let components = to.split('?') to = {pathname: components[0], query: decodeQuery(components[1])} } } else { to = edit ? modelClass.pathForEdit(modelInstance) : modelClass.pathFor(modelInstance) } componentProps = Object.without(componentProps, modelName) let Component = componentClass || Link return <Component to={to} {...componentProps}> {children || modelClass.prototype.toString.call(modelInstance)} </Component> } } MODEL_NAMES.forEach(key => LinkTo.propTypes[key] = PropTypes.oneOfType([ PropTypes.instanceOf(Models[key]), PropTypes.object, PropTypes.string, ]))
JavaScript
0
@@ -1584,27 +1584,16 @@ 0%5D, -query: decodeQuery( +search: comp @@ -1601,17 +1601,16 @@ nents%5B1%5D -) %7D%0A%09%09%09%7D%0A%09
c0850bcdc476584739481b918570a6908e11b438
factored out colors
js/view/Paginator.js
js/view/Paginator.js
// Copyright 2002-2014, University of Colorado Boulder /** * View for a paginator in 'Fraction Matcher' sim. * * @author Andrey Zelenkov (Mlearner) */ define( function( require ) { "use strict"; // modules var inherit = require( 'PHET_CORE/inherit' ); var Node = require( 'SCENERY/nodes/Node' ); var StringUtils = require( 'PHETCOMMON/util/StringUtils' ); var mixedNumbersTitleString = require( 'string!FRACTION_MATCHER/mixedNumbersTitle' ); var PaginatorNode = require( 'FRACTION_COMMON/paginator/PaginatorNode' ); // strings var patternLevelString = require( 'string!FRACTION_COMMON/patternLevel' ); function Paginator( model, options ) { var mixedNumber = (model.game === mixedNumbersTitleString); Node.call( this, options ); var shapes = ['PIES', 'HORIZONTAL_BARS', 'VERTICAL_BARS', 'LETTER_L_SHAPES', 'POLYGON', 'FLOWER', 'RING_OF_HEXAGONS', 'NINJA_STAR']; var shapeColors = [model.CONSTANTS.COLORS.LIGHT_RED, model.CONSTANTS.COLORS.LIGHT_GREEN, model.CONSTANTS.COLORS.LIGHT_BLUE, model.CONSTANTS.COLORS.ORANGE, model.CONSTANTS.COLORS.PINK, model.CONSTANTS.COLORS.YELLOW, model.CONSTANTS.COLORS.LIGHT_PINK, model.CONSTANTS.COLORS.GREEN]; var firstPageChildren = []; shapes.forEach( function( shape, index ) { firstPageChildren.push( { value: index + 1, shape: {type: shape, numerator: mixedNumber ? index + 2 : index + 1, denominator: index + 1, value: index + 1, fill: shapeColors[index]}, height: (mixedNumber ? 100 : null), label: StringUtils.format( patternLevelString, index + 1 ) } ); } ); this.addChild( new PaginatorNode( {x: 150, y: 90}, [firstPageChildren], model.currentLevelProperty, model.highScores ) ); } return inherit( Node, Paginator ); } );
JavaScript
0.999656
@@ -909,22 +909,17 @@ var -shapeC +c olors = %5Bmod @@ -914,17 +914,16 @@ olors = -%5B model.CO @@ -940,239 +940,158 @@ LORS -.LIGHT_RED, model.CONSTANTS.COLORS.LIGHT_GREEN, model.CONSTANTS.COLORS.LIGHT_BLUE, model.CONSTANTS.COLORS.ORANGE, model.CONSTANTS.COLORS.PINK, model.CONSTANTS.COLORS.YELLOW, model.CONSTANTS.COLORS.LIGHT_PINK, model.CONSTANTS.COLORS +;%0A var shapeColors = %5Bcolors.LIGHT_RED, colors.LIGHT_GREEN, colors.LIGHT_BLUE, colors.ORANGE, colors.PINK, colors.YELLOW, colors.LIGHT_PINK, colors .GRE