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
f07aacbefc4270196f49e8e7308e13d7fe8d6634
update array/uneek -- format and lint
src/array/uneek.js
src/array/uneek.js
// uniq <https://github.com/mikolalysenko/uniq> // Copyright (c) 2013 Mikola Lysenko (MIT) "use strict" function unique (list, compare, sorted) { if(list.length === 0) return list if(compare) { if(!sorted) list.sort(compare) return unique_pred(list, compare) } if(!sorted) list.sort() return unique_eq(list) } function unique_pred (list, compare) { var ptr = 1 var len = list.length var a = list[0] var b = list[0] for(var i = 1; i < len; ++i) { b = a a = list[i] if(compare(a, b)) { if(i === ptr) { ptr++ continue } list[ptr++] = a } } list.length = ptr return list } function unique_eq (list) { var ptr = 1 var len = list.length var a = list[0] var b = list[0] for(var i = 1; i < len; ++i) { b = a a = list[i] if(a !== b) { if(i === ptr) { ptr++ continue } list[ptr++] = a } } list.length = ptr return list } module.exports = unique
JavaScript
0
@@ -85,17 +85,17 @@ (MIT)%0A%0A -%22 +' use stri @@ -100,9 +100,9 @@ rict -%22 +' %0A%0Afu @@ -145,16 +145,17 @@ ) %7B%0A if + (list.le @@ -179,24 +179,25 @@ n list%0A%0A if + (compare) %7B%0A @@ -198,24 +198,25 @@ re) %7B%0A if + (!sorted) li @@ -279,16 +279,17 @@ %7D%0A%0A if + (!sorted @@ -441,32 +441,33 @@ = list%5B0%5D%0A%0A for + (var i = 1; i %3C @@ -511,16 +511,17 @@ %0A%0A if + (compare @@ -530,32 +530,33 @@ , b)) %7B%0A if + (i === ptr) %7B%0A @@ -770,16 +770,17 @@ %5D%0A%0A for + (var i = @@ -832,16 +832,17 @@ %0A%0A if + (a !== b @@ -853,16 +853,17 @@ if + (i === p @@ -1000,9 +1000,10 @@ = unique +; %0A
ffb165d7974ed6d168148f4e86b38824bf2e6dcb
Put word in subject
words-short.js
words-short.js
(function() { "use strict"; var R = require('ramda'); var w = require('./get-word'); var mail = require('./sendmail'); // custom R functions var r = {}; // make function that tests if a word contains a character r.strContains = R.curry(function(ch, word) { return R.strIndexOf(ch, word) >= 0; }); // create random function r.random = function(n) { return Math.floor(Math.random() * n); }; // load the words array var words = w.getWords(); // make function to test if a word os a particular length var isLengthN = R.curry(function(n, w) { return w.length === n; }); var isLength3 = isLengthN(3); // test for j,k, q & x var hasValuableChar = R.anyPredicates([r.strContains('j'), r.strContains('k'), r.strContains('q'), r.strContains('x') ]); // want 3-letter words with a valuable character var pick = R.and(isLength3, hasValuableChar); // get short valuable words var w3valuable = R.filter(pick, words); // dump all // console.log(w3valuable); // console.log(w3valuable.length); // pick one at random var word = w3valuable[r.random(w3valuable.length)]; console.log(word); mail.send('[email protected]', '[email protected]', 'Word of the day', word); }());
JavaScript
0.750936
@@ -1312,18 +1312,21 @@ the day -', +: ' + word);%0A
af7d3b465af7c4c46177e2e3e038488b87b13699
improve wizard prop
src/components/props/wizard-prop.js
src/components/props/wizard-prop.js
import SchemaProp from './schema-prop.js' import findIndex from 'lodash-es/findIndex' import { getWidget } from '@/utils' import objectMixin from '../mixins/object-mixin' export default { name: 'wizard-prop', mixins: [objectMixin], methods: { getSteps (steps) { return Object.keys(steps).map(step => { return { label: steps[step].title, slot: step, } }) }, extractPagesProps (steps) { return Object.keys(steps).map(step => { if (step.includes('ui:others')) { return this.props } else { const index = findIndex(this.props, {name: step}) return this.props.splice(index, 1) } }) } }, render (h) { let steps, pages if (this.uiOptions && this.uiOptions['ui:steps']) { steps = this.getSteps(this.uiOptions['ui:steps']) pages = this.extractPagesProps(this.uiOptions['ui:steps']) } else { steps = this.props.map(prop => { return { label: this.schema.properties[prop.name].title || prop.name, slot: prop.name, } }) pages = this.props } return h(getWidget(this.schema, this.uiOptions.widget || 'wizard', this.registry.widgets), { props: { id: this.idSchema.$id, steps, ...this.uiOptions, } }, pages.map((page, index) => { return h('div', { slot: steps[index].slot, }, page.map(prop => { return h(SchemaProp, { props: { name: prop.name, schema: prop.schema, uiSchema: prop.uiSchema, errorSchema: prop.errorSchema, idSchema: prop.idSchema, required: this.isRequired(prop.name), value: prop.value, registry: this.registry, onUpload: prop.onUpload, onPreview: prop.onPreview, }, on: { input: propVal => { this.$emit('input', Object.assign({}, this.value, {[prop.name]: propVal})) }, blur: propVal => { this.$emit('blur', Object.assign({}, this.value, {[prop.name]: propVal})) } } }) }) ) }) ) }, }
JavaScript
0.000001
@@ -411,24 +411,285 @@ %7D)%0A %7D,%0A + getPageProps (props) %7B%0A return props.map(prop =%3E %7B%0A const removedProps = this.props.splice(findIndex(this.props, %7Bname: prop%7D), 1)%0A if (removedProps && removedProps.length %3E 0) %7B%0A return removedProps%5B0%5D%0A %7D%0A %7D)%0A %7D,%0A extractP @@ -843,69 +843,105 @@ lse -%7B%0A const index = findIndex(this.props, %7Bname: step%7D) +if (step.includes('ui')) %7B%0A return this.getPageProps(steps%5Bstep%5D.props)%0A %7D else %7B %0A @@ -972,21 +972,51 @@ .splice( +f ind -ex +Index(this.props, %7Bname: step%7D) , 1)%0A @@ -1040,51 +1040,41 @@ %7D +, %0A -%7D,%0A%0A render + chooseStepsStrategy ( -h ) %7B%0A - let steps, pages%0A @@ -1123,32 +1123,40 @@ teps'%5D) %7B%0A + const steps = this.get @@ -1187,32 +1187,40 @@ :steps'%5D)%0A + const pages = this.ext @@ -1258,24 +1258,56 @@ ui:steps'%5D)%0A + return %7Bsteps, pages%7D%0A %7D else %7B @@ -1309,24 +1309,32 @@ lse %7B%0A + const steps = this @@ -1354,32 +1354,34 @@ op =%3E %7B%0A + return %7B%0A @@ -1365,32 +1365,34 @@ return %7B%0A + label: @@ -1452,24 +1452,26 @@ ,%0A + slot: prop.n @@ -1475,34 +1475,38 @@ p.name,%0A + + %7D%0A + %7D)%0A p @@ -1504,16 +1504,24 @@ )%0A + const pages = @@ -1535,17 +1535,131 @@ ops%0A -%7D + return %7Bsteps, pages%7D%0A %7D%0A %7D,%0A %7D,%0A%0A render (h) %7B%0A const %7Bsteps, pages%7D = this.chooseStepsStrategy() %0A%0A re
fb4baf66624373964ff885f0d696d25d20a1df44
Update schedule.js
utils/scripts/schedule.js
utils/scripts/schedule.js
/** * schedule.js: Fetch your UoG schedule from WebAdvisor. * * Author: Nick Presta * Copyright: Copyright 2012 * License: GPL * Version: 0.0.1 * Maintainer: Nick Presta * Email: [email protected] */ var casper = require('casper').create(); var fs = require('fs'), input = fs.open('/dev/stdin', 'r'); if (!casper.cli.options.hasOwnProperty('semester')) { var date = new Date(); var month = date.getMonth(); var year = date.getYear().toString().substr(1); if (month <= 3) { // Winter semester - January to April casper.cli.options.semester = 'W' + year; } else if (month <= 7) { // Summer semseter - May to August casper.cli.options.semseter = 'S' + year; } else { // Fall semester - September to December casper.cli.options.semseter = 'F' + year; } } if (!casper.cli.options.hasOwnProperty('username') || !casper.cli.options.hasOwnProperty('password')) { casper.cli.options.username = input.readLine(); casper.cli.options.password = input.readLine(); if (!casper.cli.options.username || !casper.cli.options.password) { casper.echo("You must provide a username and password argument (--username, --password)."); casper.echo("You may also input the arguments on command line (username first line, password next."); casper.exit(); } } // Login casper.start('https://webadvisor.uoguelph.ca/WebAdvisor/WebAdvisor?TOKENIDX=1631421451&SS=LGRQ', function() { this.evaluate(function(username, password) { document.querySelector('input#USER_NAME').value = username; document.querySelector('input#CURR_PWD').value = password; document.querySelector('input[name="SUBMIT2"]').click(); }, { username: casper.cli.options.username, password: casper.cli.options.password }); }); // Click on "Students" casper.then(function() { this.click('h3 + ul li a.WBST_Bars'); }); // Click on "Class Schedule" casper.then(function() { this.click('a[href$="ST-WESTS13A"]'); }); // Set dropdown to "W12" and submit form casper.then(function() { this.fill('form[name="datatelform"]', { 'VAR4': casper.cli.options.semester }, true); }); // Grab schedule data casper.then(function() { var data = this.evaluate(function() { return window.delimitedMeetingInfo; }); this.echo(data); }); casper.run(function() { casper.exit(); });
JavaScript
0.000002
@@ -125,11 +125,11 @@ se: -GPL +MIT %0A *
97b66042ba678c862052987438e18fad8514eb0d
fix bad use of PropTypes
src/components/vis/Word2VecChart.js
src/components/vis/Word2VecChart.js
import PropTypes from 'prop-types'; import React from 'react'; import * as d3 from 'd3'; import ReactFauxDOM from 'react-faux-dom'; import { injectIntl, FormattedHTMLMessage } from 'react-intl'; import fontSizeComputer from '../../lib/visUtil'; import { WarningNotice } from '../common/Notice'; const localMessages = { word2vecTerm: { id: 'word2vec.rollover.term', defaultMessage: '{term}' }, noData: { id: 'word2vec.noData', defaultMessage: 'Not enough data to show.' }, }; const DEFAULT_WIDTH = 530; const DEFAULT_HEIGHT = 320; const DEFAULT_MIN_FONT_SIZE = 10; const DEFAULT_MAX_FONT_SIZE = 30; const DEFAULT_MIN_COLOR = '#d9d9d9'; const DEFAULT_MAX_COLOR = '#000000'; function Word2VecChart(props) { const { words, scaleWords, width, height, minFontSize, maxFontSize, minColor, maxColor, showTooltips, alreadyNormalized, fullExtent, domId, xProperty, yProperty, noDataMsg } = props; const { formatMessage } = props.intl; // bail if the properties aren't there const wordsWithXYCount = words.filter(w => (w[xProperty] !== undefined) && (w[yProperty] !== undefined)).length; const missingDataMsg = noDataMsg || localMessages.noData; if (wordsWithXYCount === 0) { return ( <WarningNotice> <FormattedHTMLMessage {...missingDataMsg} /> </WarningNotice> ); } const options = { scaleWords, width, height, minFontSize, maxFontSize, minColor, maxColor, showTooltips, alreadyNormalized, fullExtent, }; if (width === undefined) { options.width = DEFAULT_WIDTH; } if (height === undefined) { options.height = DEFAULT_HEIGHT; } if (minFontSize === undefined) { options.minFontSize = DEFAULT_MIN_FONT_SIZE; } if (maxFontSize === undefined) { options.maxFontSize = DEFAULT_MAX_FONT_SIZE; } if (minColor === undefined) { options.minColor = DEFAULT_MIN_COLOR; } if (maxColor === undefined) { options.maxColor = DEFAULT_MAX_COLOR; } if (showTooltips === undefined) { options.showTooltips = false; } if (alreadyNormalized === undefined) { options.alreadyNormalized = false; } options.xProperty = xProperty || 'x'; options.yProperty = yProperty || 'y'; // alternative list of words used to set scales and margins options.scaleWords = scaleWords || words; // add in tf normalization const allSum = d3.sum(words, term => parseInt(term.count, 10)); if (!options.alreadyNormalized) { words.forEach((term, idx) => { words[idx].tfnorm = term.count / allSum; }); } // start layout const node = ReactFauxDOM.createElement('svg'); d3.select(node) .attr('width', options.width) .attr('height', options.height); const rollover = d3.select('body').append('div') .attr('class', 'word2vec-chart-tooltip') .style('opacity', 0); // determine appropriate margins const maxLengthWord = options.scaleWords.sort((a, b) => b.term.length - a.term.length)[0].term; const maxWordWidth = d3.select('body').append('span') .attr('class', 'word-width-span') .text(maxLengthWord) .style('font-size', `${options.maxFontSize}px`) .node() .getBoundingClientRect() .width; d3.select('.word-width-span').remove(); const margin = { top: options.maxFontSize, right: maxWordWidth / 2, bottom: options.maxFontSize, left: maxWordWidth / 2, }; // Define Scales const xScale = d3.scaleLinear() .domain([d3.min(options.scaleWords, d => d[options.xProperty]), d3.max(options.scaleWords, d => d[options.xProperty])]) .range([margin.left, options.width - margin.right]); const yScale = d3.scaleLinear() .domain([d3.min(options.scaleWords, d => d[options.yProperty]), d3.max(options.scaleWords, d => d[options.yProperty])]) .range([options.height - margin.top, margin.bottom]); // Add Text Labels const sizeRange = { min: options.minFontSize, max: options.maxFontSize }; if (fullExtent === undefined) { options.fullExtent = d3.extent(words, d => d.tfnorm); } const colorScale = d3.scaleLinear() .domain(options.fullExtent) .range([options.minColor, options.maxColor]); const sortedWords = words.sort((a, b) => a.tfnorm - b.tfnorm); // important to sort so z order is right const text = d3.select(node).selectAll('text') .data(sortedWords) .enter() .append('text') .attr('text-anchor', 'middle') .text(d => d.term) .attr('x', d => xScale(d[options.xProperty])) .attr('y', d => yScale(d[options.yProperty])) .attr('fill', d => colorScale(d.tfnorm)) .attr('font-size', (d) => { const fs = fontSizeComputer(d, options.fullExtent, sizeRange); return `${fs}px`; }); // tool-tip text.on('mouseover', (d) => { rollover.transition().duration(200).style('opacity', 0.9); rollover.text(formatMessage(localMessages.word2vecTerm, { term: d.term })) .style('left', `${d3.event.pageX}px`) .style('top', `${d3.event.pageY}px`); }) .on('mouseout', () => { rollover.transition().duration(500).style('opacity', 0); }); return ( <div className="word2vec-chart" id={domId}> {node.toReact()} </div> ); } Word2VecChart.propTypes = { // from parent words: PropTypes.array.isRequired, scaleWords: React.PropTypes.array, width: PropTypes.number, height: PropTypes.number, minFontSize: PropTypes.number, maxFontSize: PropTypes.number, minColor: PropTypes.string, maxColor: PropTypes.string, fullExtent: PropTypes.array, showTooltips: PropTypes.bool, alreadyNormalized: PropTypes.bool, domId: PropTypes.string.isRequired, xProperty: PropTypes.string, yProperty: PropTypes.string, noDataMsg: PropTypes.object, // from composition chain intl: PropTypes.object.isRequired, }; export default injectIntl( Word2VecChart );
JavaScript
0.000113
@@ -5284,14 +5284,8 @@ ds: -React. Prop
744af911f4f28669a2f477145d93e63db951f0ec
Deploy Flow v0.85 to www
src/model/immutable/SampleDraftInlineStyle.js
src/model/immutable/SampleDraftInlineStyle.js
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @format * @flow strict-local * @emails oncall+draft_js */ 'use strict'; const {OrderedSet} = require('immutable'); module.exports = { BOLD: OrderedSet.of('BOLD'), BOLD_ITALIC: OrderedSet.of('BOLD', 'ITALIC'), BOLD_ITALIC_UNDERLINE: OrderedSet.of('BOLD', 'ITALIC', 'UNDERLINE'), BOLD_UNDERLINE: OrderedSet.of('BOLD', 'UNDERLINE'), CODE: OrderedSet.of('CODE'), ITALIC: OrderedSet.of('ITALIC'), ITALIC_UNDERLINE: OrderedSet.of('ITALIC', 'UNDERLINE'), NONE: OrderedSet(), STRIKETHROUGH: OrderedSet.of('STRIKETHROUGH'), UNDERLINE: OrderedSet.of('UNDERLINE'), };
JavaScript
0
@@ -450,404 +450,2164 @@ %7B%0A -BOLD: OrderedSet.of('BOLD'),%0A BOLD_ITALIC: OrderedSet.of('BOLD', 'ITALIC'),%0A BOLD_ITALIC_UNDERLINE: OrderedSet.of('BOLD', 'ITALIC', 'UNDERLINE'),%0A BOLD_UNDERLINE: OrderedSet.of('BOLD', 'UNDERLINE'),%0A CODE: OrderedSet.of('CODE'),%0A ITALIC: OrderedSet.of('ITALIC'),%0A ITALIC_UNDERLINE: OrderedSet.of('ITALIC', 'UNDERLINE'),%0A NONE: OrderedSet(),%0A STRIKETHROUGH: OrderedSet.of('STRIKETHROUGH'), +/* $FlowFixMe(%3E=0.85.0 site=www,mobile) This comment suppresses an error%0A * found when Flow v0.85 was deployed. To see the error, delete this comment%0A * and run Flow. */%0A BOLD: OrderedSet.of('BOLD'),%0A /* $FlowFixMe(%3E=0.85.0 site=www,mobile) This comment suppresses an error%0A * found when Flow v0.85 was deployed. To see the error, delete this comment%0A * and run Flow. */%0A BOLD_ITALIC: OrderedSet.of('BOLD', 'ITALIC'),%0A /* $FlowFixMe(%3E=0.85.0 site=www,mobile) This comment suppresses an error%0A * found when Flow v0.85 was deployed. To see the error, delete this comment%0A * and run Flow. */%0A BOLD_ITALIC_UNDERLINE: OrderedSet.of('BOLD', 'ITALIC', 'UNDERLINE'),%0A /* $FlowFixMe(%3E=0.85.0 site=www,mobile) This comment suppresses an error%0A * found when Flow v0.85 was deployed. To see the error, delete this comment%0A * and run Flow. */%0A BOLD_UNDERLINE: OrderedSet.of('BOLD', 'UNDERLINE'),%0A /* $FlowFixMe(%3E=0.85.0 site=www,mobile) This comment suppresses an error%0A * found when Flow v0.85 was deployed. To see the error, delete this comment%0A * and run Flow. */%0A CODE: OrderedSet.of('CODE'),%0A /* $FlowFixMe(%3E=0.85.0 site=www,mobile) This comment suppresses an error%0A * found when Flow v0.85 was deployed. To see the error, delete this comment%0A * and run Flow. */%0A ITALIC: OrderedSet.of('ITALIC'),%0A /* $FlowFixMe(%3E=0.85.0 site=www,mobile) This comment suppresses an error%0A * found when Flow v0.85 was deployed. To see the error, delete this comment%0A * and run Flow. */%0A ITALIC_UNDERLINE: OrderedSet.of('ITALIC', 'UNDERLINE'),%0A /* $FlowFixMe(%3E=0.85.0 site=www,mobile) This comment suppresses an error%0A * found when Flow v0.85 was deployed. To see the error, delete this comment%0A * and run Flow. */%0A NONE: OrderedSet(),%0A /* $FlowFixMe(%3E=0.85.0 site=www,mobile) This comment suppresses an error%0A * found when Flow v0.85 was deployed. To see the error, delete this comment%0A * and run Flow. */%0A STRIKETHROUGH: OrderedSet.of('STRIKETHROUGH'),%0A /* $FlowFixMe(%3E=0.85.0 site=www,mobile) This comment suppresses an error%0A * found when Flow v0.85 was deployed. To see the error, delete this comment%0A * and run Flow. */ %0A U
22a2270702def2540f2f5055168ff8ed21c46297
add 'whoami' API
js/common.js
js/common.js
/* Generate random string */ function generateString(len) { var string = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < len; i++) { string += possible.charAt(Math.floor(Math.random() * possible.length)); } // Done. return string; } /* Show/Hide DIV section. */ function toggleDiv(divelem, blockornone) { if (null == divelem) return ; if (blockornone) { divelem.style.display = blockornone; } else { if (divelem.style.display === "none") { divelem.style.display = "block"; } else { divelem.style.display = "none"; } } } /* Set cookie function. */ function setCookie(cname, cvalue, exdays) { var cookie = cname + "=" + cvalue; if (0 < exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); var expires = "expires="+d.toUTCString(); cookie += ";" + expires; } cookie += ";path=/"; // Set the cookie. document.cookie = cookie; } /* Get cookie function. */ function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } /* HTTP GET function. */ function httpGet(url, callback) { var xmlHttp = new XMLHttpRequest(); if (null == xmlHttp ) return ; xmlHttp.onreadystatechange = function() { if ((4 == xmlHttp.readyState) && (200 == xmlHttp.status)) callback(xmlHttp.responseText); } xmlHttp.open("GET", url, true); xmlHttp.send(null); }
JavaScript
0.000241
@@ -1682,12 +1682,13 @@ nd(null);%0A%7D%0A +%0A
dd8b0cc1ac6d266f720eb30b03b71d4762270f05
change ak sk
config.example.js
config.example.js
// # Ghost Configuration // Setup your Ghost install for various [environments](http://support.ghost.org/config/#about-environments). // Ghost runs in `development` mode by default. Full documentation can be found at http://support.ghost.org/config/ var path = require('path'), config; config = { // ### Production // When running Ghost in the wild, use the production environment. // Configure your URL and mail settings here production: { url: 'http://my-ghost-blog.com', mail: {}, database: { client: 'sqlite3', connection: { filename: path.join(__dirname, '/content/data/ghost.db') }, debug: false }, server: { host: '127.0.0.1', port: '2368' } }, // ### Development **(default)** development: { // The url to use when providing links to the site, E.g. in RSS and email. // Change this to your Ghost blogs published URL. url: 'http://transing.duapp.com/', // Example mail config // Visit http://support.ghost.org/mail for instructions // ``` // mail: { // transport: 'SMTP', // options: { // service: 'Mailgun', // auth: { // user: '', // mailgun username // pass: '' // mailgun password // } // } // }, // ``` // #### Database // Ghost supports sqlite3 (default), MySQL & PostgreSQL database: { client: 'sqlite3', connection: { filename: path.join(__dirname, '/content/data/ghost-dev.db') }, debug: false }, // #### Server // Can be host & port (default), or socket server: { // Host to be passed to node's `net.Server#listen()` host: '127.0.0.1', // Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT` port: '18080' }, // #### Paths // Specify where your content directory lives paths: { contentPath: path.join(__dirname, '/content/') } }, // **Developers only need to edit below here** // ### Testing // Used when developing Ghost to run tests and check the health of Ghost // Uses a different port number testing: { url: 'http://127.0.0.1:2369', database: { client: 'sqlite3', connection: { filename: path.join(__dirname, '/content/data/ghost-test.db') } }, server: { host: '127.0.0.1', port: '2369' }, logging: false }, // ### Testing MySQL // Used by Travis - Automated testing run through GitHub 'testing-mysql': { url: 'http://127.0.0.1:2369', database: { client: 'mysql', connection: { host : '127.0.0.1', user : 'root', password : '', database : 'ghost_testing', charset : 'utf8' } }, server: { host: '127.0.0.1', port: '2369' }, logging: false }, // ### Testing pg // Used by Travis - Automated testing run through GitHub 'testing-pg': { url: 'http://127.0.0.1:2369', database: { client: 'pg', connection: { host : '127.0.0.1', user : 'postgres', password : '', database : 'ghost_testing', charset : 'utf8' } }, server: { host: '127.0.0.1', port: '2369' }, logging: false } }; if (process.env.SERVER_SOFTWARE == 'bae/3.0') { config.development.database = { client: 'mysql', connection: { host : 'sqld.duapp.com', port : '4050', user : '01e5d6a04c35477b840f57e0784e9568', password : '6210dd278617490982a9009e5013e131', database : 'QfaOCnZqSKEDTmhGXMpG', charset : 'utf8' }, debug: false, pool: { min: 0, max: 0 } }; console.log('####### database switch to mysql for BAE'); } config.development.storage = { active: 'baidu-bce', //active: 'aliyun-oss', config: { baiduBce: { credentials: { ak: 'b2c13c638be641ea98bd7bd335a7e3b4', sk: 'ab948346d10e4226a3df6e4e389b96df' }, endpoint: 'http://bj.bcebos.com', bucket: 'transing', objectUrlPrefix: 'http://transing.bj.bcebos.com' }, aliyunOss: { accessKeyId: "B5XbMzCAn484ATTL", secretAccessKey: "ROyNOrsE6IztYiTM8qUe4V3PYIxKp2", endpoint: 'http://oss-cn-shenzhen.aliyuncs.com', apiVersion: '2013-10-15', bucket: 'xtrans', objectUrlPrefix: 'http://xtrans.oss-cn-shenzhen.aliyuncs.com' } } } module.exports = config;
JavaScript
0.000017
@@ -4097,90 +4097,90 @@ : ' -01e5d6a04c35477b840f57e0784e9568',%0A%09%09%09password : '6210dd278617490982a9009e5013e131 +471e718af6ac492f80a14112beb46b27',%0A%09%09%09password : '38a60ebc773c40718bc1484da8ecd187 ',%0A%09 @@ -4510,84 +4510,84 @@ k: ' -b2c13c638be641ea98bd7bd335a7e3b4',%0A%09%09%09%09sk: 'ab948346d10e4226a3df6e4e389b96df +471e718af6ac492f80a14112beb46b27',%0A%09%09%09%09sk: '38a60ebc773c40718bc1484da8ecd187 '%0A%09%09
0f62c0fff3e29bb56e1a450330cb024fd9cf3f36
add barpolar mock to svg mock list
test/jasmine/assets/mock_lists.js
test/jasmine/assets/mock_lists.js
// list of mocks that should include *all* plotly.js trace modules var svgMockList = [ ['1', require('@mocks/1.json')], ['4', require('@mocks/4.json')], ['5', require('@mocks/5.json')], ['10', require('@mocks/10.json')], ['11', require('@mocks/11.json')], ['17', require('@mocks/17.json')], ['21', require('@mocks/21.json')], ['22', require('@mocks/22.json')], ['airfoil', require('@mocks/airfoil.json')], ['annotations-autorange', require('@mocks/annotations-autorange.json')], ['axes_enumerated_ticks', require('@mocks/axes_enumerated_ticks.json')], ['axes_visible-false', require('@mocks/axes_visible-false.json')], ['bar_and_histogram', require('@mocks/bar_and_histogram.json')], ['basic_error_bar', require('@mocks/basic_error_bar.json')], ['binding', require('@mocks/binding.json')], ['cheater_smooth', require('@mocks/cheater_smooth.json')], ['finance_style', require('@mocks/finance_style.json')], ['geo_first', require('@mocks/geo_first.json')], ['layout_image', require('@mocks/layout_image.json')], ['layout-colorway', require('@mocks/layout-colorway.json')], ['polar_categories', require('@mocks/polar_categories.json')], ['polar_direction', require('@mocks/polar_direction.json')], ['range_selector_style', require('@mocks/range_selector_style.json')], ['range_slider_multiple', require('@mocks/range_slider_multiple.json')], ['sankey_energy', require('@mocks/sankey_energy.json')], ['scattercarpet', require('@mocks/scattercarpet.json')], ['shapes', require('@mocks/shapes.json')], ['splom_iris', require('@mocks/splom_iris.json')], ['table_wrapped_birds', require('@mocks/table_wrapped_birds.json')], ['ternary_fill', require('@mocks/ternary_fill.json')], ['text_chart_arrays', require('@mocks/text_chart_arrays.json')], ['transforms', require('@mocks/transforms.json')], ['updatemenus', require('@mocks/updatemenus.json')], ['violin_side-by-side', require('@mocks/violin_side-by-side.json')], ['world-cals', require('@mocks/world-cals.json')], ['typed arrays', { data: [{ x: new Float32Array([1, 2, 3]), y: new Float32Array([1, 2, 1]) }] }] ]; var glMockList = [ ['gl2d_heatmapgl', require('@mocks/gl2d_heatmapgl.json')], ['gl2d_line_dash', require('@mocks/gl2d_line_dash.json')], ['gl2d_parcoords_2', require('@mocks/gl2d_parcoords_2.json')], ['gl2d_pointcloud-basic', require('@mocks/gl2d_pointcloud-basic.json')], ['gl3d_annotations', require('@mocks/gl3d_annotations.json')], ['gl3d_set-ranges', require('@mocks/gl3d_set-ranges.json')], ['gl3d_world-cals', require('@mocks/gl3d_world-cals.json')], ['gl3d_cone-autorange', require('@mocks/gl3d_cone-autorange.json')], ['gl3d_streamtube-simple', require('@mocks/gl3d_streamtube-simple.json')], ['glpolar_style', require('@mocks/glpolar_style.json')], ]; var mapboxMockList = [ ['scattermapbox', require('@mocks/mapbox_bubbles-text.json')] ]; module.exports = { svg: svgMockList, gl: glMockList, mapbox: mapboxMockList, all: svgMockList.concat(glMockList).concat(mapboxMockList) };
JavaScript
0
@@ -1269,32 +1269,97 @@ ection.json')%5D,%0A + %5B'polar_wind-rose', require('@mocks/polar_wind-rose.json')%5D,%0A %5B'range_sele
e06a75327f6a7fe9c706d72d3d92b50ca4d0c0b3
use PhetFont(20)
js/bucket/BucketFront.js
js/bucket/BucketFront.js
// Copyright 2002-2013, University of Colorado Boulder /* * The front of a bucket (does not include the hole) */ define( function( require ) { 'use strict'; // Includes var Color = require( 'SCENERY/util/Color' ); var inherit = require( 'PHET_CORE/inherit' ); var LinearGradient = require( 'SCENERY/util/LinearGradient' ); var Matrix3 = require( 'DOT/Matrix3' ); var Node = require( 'SCENERY/nodes/Node' ); var Path = require( 'SCENERY/nodes/Path' ); var PhetFont = require( 'SCENERY_PHET/PhetFont' ); var Text = require( 'SCENERY/nodes/Text' ); /** * Constructor. * * @param {Bucket} bucket - Model of a bucket, type definition found in phetcommon/model as of this writing. * @param {ModelViewTransform2} modelViewTransform * @param {Object} [options] * @constructor */ var BucketFront = function BucketFront( bucket, modelViewTransform, options ) { // Invoke super constructor. Node.call( this, { cursor: 'pointer' } ); options = _.extend( { labelFont: new PhetFont( { size: 20 } ) }, options ); var scaleMatrix = Matrix3.scaling( modelViewTransform.getMatrix().m00(), modelViewTransform.getMatrix().m11() ); var transformedShape = bucket.containerShape.transformed( scaleMatrix ); var baseColor = new Color( bucket.baseColor ); var frontGradient = new LinearGradient( transformedShape.bounds.getMinX(), 0, transformedShape.bounds.getMaxX(), 0 ); frontGradient.addColorStop( 0, baseColor.colorUtilsBrighter( 0.5 ).toCSS() ); frontGradient.addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ).toCSS() ); this.addChild( new Path( transformedShape, { fill: frontGradient } ) ); // Create and add the label, centered on the front. var label = new Text( bucket.captionText, { font: options.labelFont, fill: bucket.captionColor } ); // Scale the label to fit if too large. label.scale( Math.min( 1, Math.min( ( ( transformedShape.bounds.width * 0.75 ) / label.width ), ( transformedShape.bounds.height * 0.8 ) / label.height ) ) ); label.centerX = transformedShape.bounds.getCenterX(); label.centerY = transformedShape.bounds.getCenterY(); this.addChild( label ); // Set initial position. this.translation = modelViewTransform.modelToViewPosition( bucket.position ); }; // Inherit from base type. inherit( Node, BucketFront ); return BucketFront; } );
JavaScript
0
@@ -1036,20 +1036,10 @@ nt( -%7B size: 20 %7D +20 )%0A
5360d7e4d1d3b81920a72a76193e3a2fdc465f18
Update oauth_authenticator.js
lib/auth/oauth_authenticator.js
lib/auth/oauth_authenticator.js
var util = require('util'); var Bluebird = require('bluebird'); var Authenticator = require('./authenticator'); /** * Creates an authenticator that uses Oauth for authentication. * * @param {Object} options Configure the authenticator; must specify one * of `flow` or `credentials`. * @option {App} app The app being authenticated for. * @option {OauthFlow} [flow] The flow to use to get credentials * when needed. * @option {String|Object} [credentials] Initial credentials to use. This can * be either the object returned from an access token request (which * contains the token and some other metadata) or just the `access_token` * field. * @constructor */ function OauthAuthenticator(options) { Authenticator.call(this); if (typeof(options.credentials) === 'string') { this.credentials = { 'access_token': options.credentials }; } else { this.credentials = options.credentials || null; } this.flow = options.flow || null; this.app = options.app; this.refreshCredentialsCallback = options.refreshCredentialsCallback || null; } util.inherits(OauthAuthenticator, Authenticator); /** * @param {Object} request The request to modify, for the `request` library. * @return {Object} The `request` parameter, modified to include authentication * information using the stored credentials. */ OauthAuthenticator.prototype.authenticateRequest = function(request) { /* jshint camelcase: false */ if (this.credentials === null) { throw new Error( 'Cannot authenticate a request without first obtaining credentials'); } // When browserify-d, the `auth` component of the `request` library // doesn't work so well, so we just manually set the bearer token instead. request.headers = request.headers || {}; request.headers.Authorization = 'Bearer ' + this.credentials.access_token; return request; }; /** * Requests new credentials, discarding any that it may already have. * @return {Promise} Resolves when credentials have been successfully * established and `authenticateRequests` can expect to succeed. */ OauthAuthenticator.prototype.establishCredentials = function() { /* jshint camelcase: false */ var me = this; if (me.flow) { // Request new credentials me.credentials = null; return me.flow.run().then(function(credentials) { me.credentials = credentials; }); } else { if (me.credentials.access_token) { // Assume what we have is ok. return Bluebird.resolve(); } else if (me.credentials.refresh_token) { // We were given a refresh token but NOT an access token. Get access. return me.refreshCredentials(); } else { // What kind of credentials did we get anyway? return Bluebird.reject(new Error('Invalid credentials')); } } }; /** * Attempts to refresh credentials, if possible, given the current credentials. * @return {Promise} Resolves to `true` if credentials have been successfully * established and `authenticateRequests` can expect to succeed, else * resolves to `false`. */ OauthAuthenticator.prototype.refreshCredentials = function() { /* jshint camelcase: false */ var me = this; if (me.credentials && me.credentials.refresh_token) { // We have a refresh token. Use it to get a new access token. // Only have one outstanding request, any simultaneous requests waiting on // refresh should gate on this promise. if (!me.refreshPromise) { var refreshToken = me.credentials.refresh_token; me.refreshPromise = me.app.accessTokenFromRefreshToken(refreshToken).then( function(credentials) { // Update credentials, but hang on to refresh token. if (!credentials.refresh_token) { credentials.refresh_token = refreshToken; } me.credentials = credentials; me.refreshPromise = null; if (me.refreshCredentialsCallback != null) { me.refreshCredentialsCallback(me.credentials); } return true; }); } return me.refreshPromise; } else if (me.flow) { // Try running the flow again to get credentials. return this.establishCredentials().then(function(credentials) { return credentials !== null; }); } else { // We are unable to refresh credentials automatically. return Bluebird.resolve(false); } }; module.exports = OauthAuthenticator;
JavaScript
0.000001
@@ -3978,16 +3978,17 @@ lback != += null) %7B @@ -4466,20 +4466,21 @@ OauthAuthenticator; +%0A
edfa54776dca8dbae2dc274c222c3b22be17dace
Fix typo from prev. commit.
lib/waterline/utils/query/transform-uniqueness-error.js
lib/waterline/utils/query/transform-uniqueness-error.js
/** * Module dependencies */ var util = require('util'); var _ = require('@sailshq/lodash'); var getModel = require('../ontology/get-model'); /** * transformUniquenessError() * * Given a raw uniqueness error from the adapter, examine its `footprint` property in order * to build a new, normalized Error instance. The new Error has an `attrNames` array, as well * as a `.toJSON()` method, and `code: 'E_UNIQUE'`. * * > For more info on the lower-level driver specification, from whence this error originates, see: * > https://github.com/treelinehq/waterline-query-docs/blob/a0689b6a6536a3c196dff6a9528f2ef72d4f6b7d/docs/errors.md#notunique * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * * @param {Ref} rawUniquenessError * @param {Function} stackFrameFloorFn [used purely for improving the quality of the stack trace] * @param {String} modelIdentity * @param {Ref} orm * * @returns {Error} the new error * @property {String} code [E_UNIQUE] * @property {String} modelIdentity * @property {Array} attrNames * @of {String} * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ module.exports = function transformUniquenessError (rawUniquenessError, stackFrameFloorFn, modelIdentity, orm){ // Sanity checks if (!_.isObject(rawUniquenessError.footprint) || !_.isString(rawUniquenessError.footprint.identity)) { throw new Error('Consistency violation: Should never call this utility unless the provided error is a uniqueness error. But the provided error has a missing or invalid `footprint`: '+util.inspect(rawUniquenessError.footprint, {depth:5})+''); } if (rawUniquenessError.footprint.identity !== 'notUnique') { throw new Error('Consistency violation: Should never call this utility unless the provided error is a uniqueness error. But the footprint of the provided error has an unexpected `identity`: '+util.inspect(rawUniquenessError.footprint.identity, {depth:5})+''); } // Verify that all the stuff is there if (!_.isArray(rawUniquenessError.keys)) { throw new Error('Malformed uniqueness error sent back from adapter: Footprint should have an array of `keys`! But instead, `footprint.keys` is: '+util.inspect(rawUniquenessError.footprint.keys, {depth:5})+''); } var WLModel = getModel(modelIdentity, orm); var newUniquenessError = flaverr({ code: 'E_UNIQUE', modelIdentity: modelIdentity, attrNames: _.reduce(rawUniquenessError.footprint.keys, function(memo, key){ // Find matching attr name. var matchingAttrName; _.any(WLModel.schema, function(wlsAttr, attrName) { if (!wlsAttr.columnName) { console.warn( 'Warning: Malformed ontology: The normalized `schema` of model `'+modelIdentity+'` has an '+ 'attribute (`'+attrName+'`) with no `columnName`. But at this point, every WLS-normalized '+ 'attribute should have a column name!\n'+ '(If you are seeing this error, the model definition may have been corrupted in-memory-- '+ 'or there might be a bug in WL schema.)' ); } if (wlsAttr.columnName === key) { matchingAttrName = attrName; return true; } }); // Push it on, if it could be found. if (matchingAttrName) { memo.push(matchingAttrName); } // Otherwise log a warning and silently ignore this item. else { console.warn( 'Warning: Adapter sent back a uniqueness error, but one of the unique constraints supposedly '+ 'violated references a key (`'+key+'`) which cannot be matched up with any attribute. This probably '+ 'means there is a bug in this model\'s adapter, or even in the underlying driver. (Note for adapter '+ 'implementors: If your adapter doesn\'t support granular reporting of the keys violated in uniqueness '+ 'errors, then just use an empty array for the `keys` property of this error.)' ); } return memo; }, []),//</_.reduce()> toJSON: function (){ return { code: this.code, message: this.message, modelIdentity: this.modelIdentity, attrNames: this.attrNames, }; } }, new Error( 'Would violate uniqueness constraint-- a record already exists with conflicting value(s).' )); // Adjust stack trace. Error.captureStackTrace(newUniquenessError, stackFrameFloorFn); // Return the new uniqueness error. return newUniquenessError; };
JavaScript
0.000001
@@ -2166,16 +2166,26 @@ ssError. +footprint. keys)) %7B
a2ed81716fb7d6d38f92154e0b79b4e91b5e0f61
Fix task test
test/js/unit/tasks/routes_test.js
test/js/unit/tasks/routes_test.js
pavlov.specify('Project Task List Route Tests', function() { describe('App.ProjectTaskListRoute Class', function () { it('should be an Ember.Route', function() { assert(App.ProjectTaskListRoute).isDefined(); assert(Ember.Route.detect(App.ProjectTaskListRoute)).isTrue(); }); }); describe('App.ProjectTaskListRoute Instance', function () { var route; before(function () { Ember.run( function () { route = App.ProjectTaskListRoute.create(); }); }); it('should have an empty model property', function() { var model = route.model(); assert(model).isEmptyArray(); }); it('should add project tasks to controller when calling setupController'); }); });
JavaScript
0.999999
@@ -80,28 +80,30 @@ .ProjectTask -List +sIndex Route Class' @@ -200,28 +200,30 @@ .ProjectTask -List +sIndex Route).isDef @@ -279,28 +279,30 @@ .ProjectTask -List +sIndex Route)).isTr @@ -514,28 +514,30 @@ .ProjectTask -List +sIndex Route.create
edc3fe89d10802fc1f08a72629cf7f1a4f95aef6
Remove done TODO
middleware/process-aoi.js
middleware/process-aoi.js
'use strict' const fork = require('child_process').fork const path = require('path') const async = require('async') const queue = require('../lib/queue') const redis = require('../lib/redis') const UPLOAD_PATH = path.join(__dirname,'../uploaded_aois') exports.runner = function (options){ return function (req, res, next) { var project_id = req.body.project_id var subject_set_id = req.body.subject_set_id var repeat = req.body.repeat var interval = req.body.interval var redirect_uri = req.query.redirect if (options.useQueue) { // Create job data var jobInfo = { aoi_file: path.join(UPLOAD_PATH, req.file.filename), project_id: project_id, subject_set_id: subject_set_id, user_id: req.user.get('id') } // Send job to redis queue queue.push(jobInfo, repeat, interval, function(err, job_ids) { console.log('jobs sent', job_ids) // Create records for each repeat of job async.map(job_ids, (job_id, done) => { var job = Object.assign({}, { id: job_id }, jobInfo) redis.set('job:'+job_id, JSON.stringify(job), done) }, (err, jobs) => { if (err) return next(err) // Add job id to user's job list // TODO get oauth working so we know which user this is redis.rpush('user:'+req.user.get('id')+':jobs', job_ids, (err, status) => { if (err) return next(err) res.redirect(redirect_uri) }) }) }) // send job to message queue } else { res.redirect(redirect_uri) var script = 'generate-subjects' //'build-status-simulator' //'generate-subjects' var aoi_file = req.file.path var job = fork(script, [ '--job-id', 'jobid.'+Math.floor(Math.random()*(9999-1000)+1000), // generate a random job id '--mosaics', // TO DO: these probably shouldn't be hard-coded // 'https://api.planet.com/v0/mosaics/nepal_unrestricted_mosaic/quads/', // 'https://api.planet.com/v0/mosaics/nepal_3mo_pre_eq_mag_6_mosaic/quads/', 'https://api.planet.com/v0/mosaics/open_california_re_20131201_20140228/quads/', 'https://api.planet.com/v0/mosaics/open_california_re_20141201_20150228/quads/', '--project', project_id, '--subject-set', subject_set_id, '--user-id', req.user.get('id'), aoi_file ]) } } }
JavaScript
0.000009
@@ -1282,74 +1282,8 @@ ist%0A - // TODO get oauth working so we know which user this is%0A
8dce649933212445a8210ed9d53a64b972ad4b9e
Use last_value as a fallback if model value isn't set - Did this to avoid repeated value set of datetime value which causes browser to freeze. This happens only with the datetime control is used in filters (with a default value) and is not linked with a form.
frappe/public/js/frappe/form/controls/datetime.js
frappe/public/js/frappe/form/controls/datetime.js
frappe.ui.form.ControlDatetime = class ControlDatetime extends frappe.ui.form.ControlDate { set_formatted_input(value) { if (this.timepicker_only) return; if (!this.datepicker) return; if (!value) { this.datepicker.clear(); return; } else if (value === "Today") { value = this.get_now_date(); } value = this.format_for_input(value); this.$input && this.$input.val(value); this.datepicker.selectDate(frappe.datetime.user_to_obj(value)); } get_start_date() { let value = frappe.datetime.convert_to_user_tz(this.value); return frappe.datetime.str_to_obj(value); } set_date_options() { super.set_date_options(); this.today_text = __("Now"); let sysdefaults = frappe.boot.sysdefaults; this.date_format = frappe.defaultDatetimeFormat; let time_format = sysdefaults && sysdefaults.time_format ? sysdefaults.time_format : 'HH:mm:ss'; $.extend(this.datepicker_options, { timepicker: true, timeFormat: time_format.toLowerCase().replace("mm", "ii") }); } get_now_date() { return frappe.datetime.now_datetime(true); } parse(value) { if (value) { value = frappe.datetime.user_to_str(value, false); if (!frappe.datetime.is_system_time_zone()) { value = frappe.datetime.convert_to_system_tz(value, true); } return value; } } format_for_input(value) { if (!value) return ""; return frappe.datetime.str_to_user(value, false); } set_description() { const description = this.df.description; const time_zone = this.get_user_time_zone(); if (!this.df.hide_timezone) { // Always show the timezone when rendering the Datetime field since the datetime value will // always be in system_time_zone rather then local time. if (!description) { this.df.description = time_zone; } else if (!description.includes(time_zone)) { this.df.description += '<br>' + time_zone; } } super.set_description(); } get_user_time_zone() { return frappe.boot.time_zone ? frappe.boot.time_zone.user : frappe.sys_defaults.time_zone; } set_datepicker() { super.set_datepicker(); if (this.datepicker.opts.timeFormat.indexOf('s') == -1) { // No seconds in time format const $tp = this.datepicker.timepicker; $tp.$seconds.parent().css('display', 'none'); $tp.$secondsText.css('display', 'none'); $tp.$secondsText.prev().css('display', 'none'); } } get_model_value() { let value = super.get_model_value(); return frappe.datetime.get_datetime_as_string(value); } };
JavaScript
0
@@ -2408,16 +2408,77 @@ alue();%0A +%09%09if (!value && !this.doc) %7B%0A%09%09%09value = this.last_value;%0A%09%09%7D%0A %09%09return
a70fadfdc93a0bb67433fe1c102c1f236fc9593e
Add support for other numbers
components/prism-haskell.js
components/prism-haskell.js
Prism.languages.haskell= { 'comment': { pattern: /(^|[^-!#$%*+=\?&@|~.:<>^\\])(--[^-!#$%*+=\?&@|~.:<>^\\].*(\r?\n|$)|{-[\w\W]*?-})/gm, lookbehind: true }, 'string': /("|')(\\?.)*?\1/g, 'keyword' : /\b(case|class|data|deriving|do|else|if|in|infixl|infixr|instance|let|module|newtype|of|primitive|then|type|where)\b/g, 'import_statement' : { // The imported or hidden names are not included in this import // statement. This is because we want to highlight those exactly like // we do for the names in the program. pattern: /(\n|^)\s*(import)\s+(qualified\s+)?(([A-Z][_a-zA-Z0-9']*)(\.[A-Z][_a-zA-Z0-9']*)*)(\s+(as)\s+(([A-Z][_a-zA-Z0-9']*)(\.[A-Z][_a-zA-Z0-9']*)*))?(\s+hiding\b)?/gm, inside: { 'keyword': /\b(import|qualified|as|hiding)\b/g } }, // These are builtin variables only. Constructors are highlighted later as a constant. 'builtin': /\b(abs|acos|acosh|all|and|any|appendFile|approxRational|asTypeOf|asin|asinh|atan|atan2|atanh|basicIORun|break|catch|ceiling|chr|compare|concat|concatMap|const|cos|cosh|curry|cycle|decodeFloat|denominator|digitToInt|div|divMod|drop|dropWhile|either|elem|encodeFloat|enumFrom|enumFromThen|enumFromThenTo|enumFromTo|error|even|exp|exponent|fail|filter|flip|floatDigits|floatRadix|floatRange|floor|fmap|foldl|foldl1|foldr|foldr1|fromDouble|fromEnum|fromInt|fromInteger|fromIntegral|fromRational|fst|gcd|getChar|getContents|getLine|group|head|id|inRange|index|init|intToDigit|interact|ioError|isAlpha|isAlphaNum|isAscii|isControl|isDenormalized|isDigit|isHexDigit|isIEEE|isInfinite|isLower|isNaN|isNegativeZero|isOctDigit|isPrint|isSpace|isUpper|iterate|last|lcm|length|lex|lexDigits|lexLitChar|lines|log|logBase|lookup|map|mapM|mapM_|max|maxBound|maximum|maybe|min|minBound|minimum|mod|negate|not|notElem|null|numerator|odd|or|ord|otherwise|pack|pi|pred|primExitWith|print|product|properFraction|putChar|putStr|putStrLn|quot|quotRem|range|rangeSize|read|readDec|readFile|readFloat|readHex|readIO|readInt|readList|readLitChar|readLn|readOct|readParen|readSigned|reads|readsPrec|realToFrac|recip|rem|repeat|replicate|return|reverse|round|scaleFloat|scanl|scanl1|scanr|scanr1|seq|sequence|sequence_|show|showChar|showInt|showList|showLitChar|showParen|showSigned|showString|shows|showsPrec|significand|signum|sin|sinh|snd|sort|span|splitAt|sqrt|subtract|succ|sum|tail|take|takeWhile|tan|tanh|threadToIOResult|toEnum|toInt|toInteger|toLower|toRational|toUpper|truncate|uncurry|undefined|unlines|until|unwords|unzip|unzip3|userError|words|writeFile|zip|zip3|zipWith|zipWith3)\b/g, // Most of this is needed because of the meaning of a single '.'. // If it stands alone freely, it is the function composition. // It may also be a separator between a module name and an identifier => no // operator. If it comes together with other special characters it is an // operator too. 'operator' : /\s\.\s|([-!#$%*+=\?&@|~:<>^\\]*\.[-!#$%*+=\?&@|~:<>^\\]+)|([-!#$%*+=\?&@|~:<>^\\]+\.[-!#$%*+=\?&@|~:<>^\\]*)|[-!#$%*+=\?&@|~:<>^\\]+|(`([A-Z][_a-zA-Z0-9']*\.)*[_a-z][_a-zA-Z0-9']*`)/g, // In Haskell, nearly everything is a variable, do not highlight these. 'hvariable': /\b([A-Z][_a-zA-Z0-9']*\.)*[_a-z][_a-zA-Z0-9']*\b/g, 'constant': /\b([A-Z][_a-zA-Z0-9']*\.)*[A-Z][_a-zA-Z0-9']*\b/g, 'number' : /\b-?\d*(\.?\d+)\b/g, 'punctuation' : /[{}[\];(),.:]/g };
JavaScript
0
@@ -2533,24 +2533,191 @@ With3)%5Cb/g,%0A +%09// decimal integers and floating point numbers %7C octal integers %7C hexadecimal integers%0A%09'number' : /%5Cb(%5Cd+(%5C.%5Cd+)?(%5BeE%5D%5B+-%5D?%5Cd+)?%7C0%5BOo%5D%5B0-7%5D+%7C0%5BXx%5D%5B0-9a-fA-F%5D+)%5Cb/g,%0A %09// Most of @@ -3412,42 +3412,8 @@ /g,%0A -%09'number' : /%5Cb-?%5Cd*(%5C.?%5Cd+)%5Cb/g,%0A %09'pu
9bf9699084a6c32aa4dc7b9b9cd65362501f628b
fix site title typo
config/env/all.js
config/env/all.js
'use strict'; module.exports = { app: { title: 'BraverHerder', description: 'Brave Frontier Unit Database with MongoDB, Express, AngularJS, and Node.js', keywords: 'Brave Frontier, Units, Characters, Database, Team Building, BraverHerder' }, port: process.env.PORT || 3000, templateEngine: 'swig', sessionSecret: 'MEAN', sessionCollection: 'sessions', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.css', ], js: [ 'public/lib/angular/angular.js', 'public/lib/angular-resource/angular-resource.js', 'public/lib/angular-cookies/angular-cookies.js', 'public/lib/angular-animate/angular-animate.js', 'public/lib/angular-touch/angular-touch.js', 'public/lib/angular-sanitize/angular-sanitize.js', 'public/lib/angular-ui-router/release/angular-ui-router.js', 'public/lib/angular-ui-utils/ui-utils.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.js', 'public/js/lazy.js', ] }, css: [ 'public/modules/**/css/*.css' ], js: [ 'public/config.js', 'public/application.js', 'public/modules/*/*.js', 'public/modules/*/*[!tests]*/*.js' ], tests: [ 'public/lib/angular-mocks/angular-mocks.js', 'public/modules/*/tests/*.js' ] } };
JavaScript
0.000098
@@ -46,25 +46,24 @@ itle: 'Brave -r Herder',%0A%09%09d
0b8b1fbe670286777d741d5a27b88629ebff4220
Fix hero background for firefox
components/sections/hero.js
components/sections/hero.js
import Button from '../Button' import Confetti from 'react-dom-confetti' import Logo from '../../static/images/kap.svg' import KapWindowImage from '../../static/images/[email protected]' import colors from '../../lib/colors' const Info = () => ( <div> <a href="https://github.com/wulkano/kap">View and contribute on GitHub</a> <span> macOS 10.12 or later required</span> <style jsx>{` div { max-width: 390px; width: 100%; margin: 0 32px; margin-top: 32px; } a { font-size: 12px; font-weight: bold; font-style: normal; color: #ffffff; float: left; } a:hover { text-decoration: underline; } span { opacity: 0.8; font-size: 12px; font-weight: normal; float: right; clearfix: both; } @media only screen and (max-width: 460px) { div { display: block; margin: 0 16px; width: 100vw; margin-top: 32px; } span { padding-top: 8px; } a, span { display: block; float: none; } } `}</style> </div> ) const KapWindow = () => ( <div className="window"> <img src={KapWindowImage} alt="The Kap Window" /> <style jsx>{` img { width: 320px; height: 180px; opacity: 1; } .window { z-index: 100; width: 320px; height: 180px; box-shadow: 0 20px 40px 0 rgba(0, 0, 0, 0.1); background-color: white; border-radius: 4px; position: relative; margin-bottom: -88px; } @media only screen and (max-width: 420px) { .window, img { width: 288px !important; height: 163px !important; } } `}</style> </div> ) export default () => ( <section className="hero"> <div className="curve-container"> <div className="curve" /> </div> <header className="header grid"> <Logo /> {/* Download Button */} <Button theme="light" href="https://kap-updates.now.sh/download"> <img src={require('../../static/images/download.svg')} /> <span>Get kap</span> </Button> </header> <div className="hero__content"> <h1>Capture your screen</h1> <h3>An open-source screen recorder built with web technology.</h3> <Info /> </div> <KapWindow /> <style jsx>{` @keyframes bg { 0% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } 100% { background-position: 0% 50%; } } .hero { flex: 1; max-height: calc(100vh - 320px); min-height: 64rem; color: white; display: flex; flex-direction: column; align-items: center; position: relative; padding: 0 32px; background-image: radial-gradient( farthest-corner at -0% 100%, ${colors.purple} 30%, ${colors.teal} 95% ); background-size: 150% 150%; animation: bg 12s ease-in infinite alternate; will-change: transform; transform-style: preserve-3d; } .curve-container { overflow: hidden; position: absolute; top: 0; bottom: 0; left: 0; width: 100%; } .curve { position: absolute; bottom: 0; left: 50%; transform: translateX(-50%); width: 190vw; padding-bottom: 4%; background: url('../../static/images/curve-mobile.svg') center bottom; background-size: cover; margin-bottom: -3px; } .hero__content { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; z-index: 100; padding-top: 128px; padding-bottom: 128px; text-align: center; width: 48rem; max-width: 100%; } .header { display: flex; flex-direction: row; justify-content: space-between; margin-top: 64px; } @media only screen and (max-width: 1200px) { .header { margin-top: 32px; } .center { display: block; text-align: center; } } @media only screen and (min-width: 600px) { .header__content { margin-top: 112px; padding-top: 64px; } .hero { min-height: 56rem; } } @media only screen and (max-width: 600px) { .header__content { margin-top: 64px; } } @media only screen and (max-width: 500px) { .header__content { font-size: 32px; max-width: 200px; line-height: 1.25; display: inline-block; margin-top: 32px; } h2 { max-width: 288px; line-height: 1.2; font-size: 2rem; } .gradient { padding: 0 16px; } .header { margin-top: 16px; } } `}</style> </section> )
JavaScript
0.000001
@@ -3580,17 +3580,16 @@ (-50%25);%0A -%0A @@ -4592,63 +4592,8 @@ %7D%0A - .hero %7B%0A min-height: 56rem;%0A %7D%0A
ee6368d20cf9b9fc296c4cc9207d2b13c48d6d4c
Test cases for constructor.
test/patterns/constructor.test.js
test/patterns/constructor.test.js
/* global describe, it, expect */ var Constructor = require('../../lib/patterns/constructor'); describe('Constructor', function() { describe('instantiated with too many arguments', function() { function Animal(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { } var ctor = new Constructor('animal', [], Animal); it('should throw an error', function() { expect(function() { ctor.instantiate('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10') }).to.throw(Error, "Constructor for object 'animal' requires too many arguments"); }); }); });
JavaScript
0
@@ -134,21 +134,330 @@ %7B%0A -%0A describe(' +function Animal(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) %7B%0A this._a0 = a0;%0A this._a1 = a1;%0A this._a2 = a2;%0A this._a3 = a3;%0A this._a4 = a4;%0A this._a5 = a5;%0A this._a6 = a6;%0A this._a7 = a7;%0A this._a8 = a8;%0A this._a9 = a9;%0A %7D%0A %0A var ctor = new Constructor('animal', Animal);%0A %0A %0A it('should inst @@ -467,23 +467,15 @@ iate -d with -too many +1 arg @@ -479,17 +479,16 @@ argument -s ', funct @@ -503,138 +503,470 @@ -function Animal(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) %7B%0A %7D%0A var ctor = new Constructor('animal', %5B%5D, Animal);%0A %0A +var inst = ctor.instantiate('0')%0A %0A expect(inst).to.be.an('object');%0A expect(inst._a0).to.equal('0');%0A expect(inst._a1).to.be.undefined;%0A expect(inst._a2).to.be.undefined;%0A expect(inst._a3).to.be.undefined;%0A expect(inst._a4).to.be.undefined;%0A expect(inst._a5).to.be.undefined;%0A expect(inst._a6).to.be.undefined;%0A expect(inst._a7).to.be.undefined;%0A expect(inst._a8).to.be.undefined;%0A expect(inst._a9).to.be.undefined;%0A %7D);%0A %0A it @@ -1008,18 +1008,16 @@ ) %7B%0A - expect(f @@ -1034,18 +1034,16 @@ %7B%0A - - ctor.ins @@ -1106,19 +1106,18 @@ ', '10') +; %0A - %7D).t @@ -1199,16 +1199,8 @@ %22);%0A - %7D);%0A %7D)
7432f216bb357c2aeba176d0a47eeabd974a3056
add handler for missing configuration errors
js/controllers/signin.js
js/controllers/signin.js
'use strict'; angular.module('copay.signin').controller('SigninController', function($scope, $rootScope, $location, walletFactory, controllerUtils, Passphrase) { var cmp = function(o1, o2){ var v1 = o1.show.toLowerCase(), v2 = o2.show.toLowerCase(); return v1 > v2 ? 1 : ( v1 < v2 ) ? -1 : 0; }; $rootScope.videoInfo = {}; $scope.loading = $scope.failure = false; $scope.wallets = walletFactory.getWallets().sort(cmp); $scope.selectedWalletId = $scope.wallets.length ? $scope.wallets[0].id : null; $scope.openPassword = ''; $scope.open = function(form) { if (form && form.$invalid) { $rootScope.$flashMessage = { message: 'Please, enter required fields', type: 'error'}; return; } $scope.loading = true; var password = form.openPassword.$modelValue; console.log('## Obtaining passphrase...'); Passphrase.getBase64Async(password, function(passphrase){ console.log('## Passphrase obtained'); var w = walletFactory.open($scope.selectedWalletId, { passphrase: passphrase}); if (!w) { $scope.loading = $scope.failure = false; $rootScope.$flashMessage = { message: 'Wrong password', type: 'error'}; $rootScope.$digest(); return; } installStartupHandlers(w); controllerUtils.startNetwork(w); }); }; $scope.join = function(form) { if (form && form.$invalid) { $rootScope.$flashMessage = { message: 'Please, enter required fields', type: 'error'}; return; } $scope.loading = true; walletFactory.network.on('badSecret', function() { }); Passphrase.getBase64Async($scope.joinPassword, function(passphrase){ walletFactory.joinCreateSession($scope.connectionId, $scope.nickname, passphrase, function(err,w) { $scope.loading = false; if (err || !w) { if (err === 'joinError') $rootScope.$flashMessage = { message: 'Can not find peer'}; else if (err === 'walletFull') $rootScope.$flashMessage = { message: 'The wallet is full', type: 'error'}; else if (err === 'badSecret') $rootScope.$flashMessage = { message: 'Bad secret secret string', type: 'error'}; else $rootScope.$flashMessage = { message: 'Unknown error', type: 'error'}; controllerUtils.onErrorDigest(); } else { controllerUtils.startNetwork(w); installStartupHandlers(w); } }); }); }; function installStartupHandlers(wallet) { wallet.on('connectionError', function(err) { $scope.failure = true; }); wallet.on('ready', function() { $scope.loading = false; }); } });
JavaScript
0.000001
@@ -1000,16 +1000,54 @@ ined');%0A + var w, errMsg;%0A try%7B%0A @@ -1122,24 +1122,87 @@ ssphrase%7D);%0A + %7D catch (e)%7B%0A errMsg = e.message;%0A %7D;%0A%0A if ( @@ -1250,32 +1250,32 @@ ailure = false;%0A - $rootS @@ -1305,16 +1305,26 @@ message: + errMsg %7C%7C 'Wrong
372991c7efb80d2b04c3c6a09d600d512769b959
Capitalize a character in a string
lib/commands/ember-cli-jsdoc.js
lib/commands/ember-cli-jsdoc.js
'use strict'; module.exports = { name: 'ember-cli-jsdoc', run: function() { var exec = require( 'child_process' ).exec; var rsvp = require( 'rsvp' ); var path = require( 'path' ); var chalk = require( 'chalk' ); var cmdPath = ( Number( process.version.match( /^v(\d+)/ )[1] ) >= 5 ) ? path.join( 'node_modules', '.bin', 'jsdoc' ) : path.join( 'node_modules', 'ember-cli-jsdoc', 'node_modules', '.bin', 'jsdoc' ); return new rsvp.Promise( function( resolve, reject ) { exec( cmdPath + ' -c jsdoc.json', { cwd: process.cwd() }, function( error, stdout, stderr ) { console.log( stderr ); var shouldReject = false; if ( error ) { console.log( chalk.red( 'EMBER-CLI-JSDOC: ERRORs have occurred during documentation generation' ) ); shouldReject = true; } if ( /WARNING/.test( stderr ) ) { console.log( chalk.yellow( 'EMBER-CLI-JSDOC: WARNINGS have occurred during documentation generation' ) ); } if ( shouldReject ) { reject(); } else { console.log( chalk.green( 'EMBER-CLI-JSDOC: Documentation was successfully generated' ) ); resolve(); } }); }); } }
JavaScript
1
@@ -831,17 +831,17 @@ C: ERROR -s +S have oc
21ef434850c956e3df1ff655c94853c56b0200d3
add allStepsCompleted prop to component
components/progressTracker/ProgressTracker.js
components/progressTracker/ProgressTracker.js
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import theme from './theme.css'; import Box from '../box'; import ProgressStep from './ProgressStep'; class ProgressTracker extends PureComponent { render() { const { color, children, activeStep } = this.props; const classNames = cx(theme['progress-tracker']); return ( <Box className={classNames}> {React.Children.map(children, (child, index) => { const currentActiveStep = activeStep < 0 ? 0 : activeStep; return React.cloneElement(child, { active: index === currentActiveStep, completed: index < currentActiveStep, color, }); })} </Box> ); } } ProgressTracker.propTypes = { /** The number of the step which is currently active */ activeStep: PropTypes.number.isRequired, /** The steps to display inside the progress tracker */ children: PropTypes.node, /** Color theme of the progress tracker. */ color: PropTypes.oneOf(['neutral', 'mint', 'aqua', 'violet', 'gold', 'ruby']), }; ProgressTracker.defaultProps = { activeStep: 0, color: 'neutral', }; ProgressTracker.ProgressStep = ProgressStep; export default ProgressTracker;
JavaScript
0
@@ -306,16 +306,35 @@ tiveStep +, allStepsCompleted %7D = thi @@ -638,16 +638,44 @@ active: + allStepsCompleted ? false : index = @@ -718,16 +718,37 @@ mpleted: + allStepsCompleted %7C%7C index %3C @@ -869,16 +869,101 @@ pes = %7B%0A + /** Whether or not all steps are completed */%0A allStepsCompleted: PropTypes.bool,%0A /** Th
ea76a4b3f63f0d6ddddca7c428ea497ed7da0f6a
Test attribute is set correctly for Nam = Val
tests/commands/sgaTests.js
tests/commands/sgaTests.js
var sga = require("__buttercup/classes/commands/command.sga.js"); module.exports = { setUp: function(cb) { this.command = new sga(); (cb)(); }, errors: { groupNotFoundForId: function(test) { var fakeSearching = { findGroupByID: function(a, b) { return false; } }; this.command.injectSearching(fakeSearching); var errorThrown = false; try { this.command.execute({ }, 0, '', ''); } catch (e) { if (e.message === 'Group not found for ID') { errorThrown = true; } } finally { test.strictEqual(errorThrown, true, 'Error thrown'); test.done(); } } }, };
JavaScript
0.000261
@@ -689,12 +689,640 @@ %7D%0A %7D, +%0A%0A setAttribute: %7B%0A setsAttributeValueValForNameNam: function(test) %7B%0A var attributeName = 'Nam',%0A attributeValue = 'Val';%0A%0A var fakeGroup = %7B%0A attributes: %7B%7D%0A %7D;%0A%0A var fakeSearching = %7B%0A findGroupByID: function(a, b) %7B%0A return fakeGroup;%0A %7D%0A %7D;%0A%0A this.command.injectSearching(fakeSearching);%0A%0A this.command.execute(%7B %7D, 0, attributeName, attributeValue);%0A%0A test.strictEqual(fakeGroup.attributes%5BattributeName%5D, attributeValue, 'Attribute value is correctly set. (%5B' + attributeName + '%5D = ' + attributeValue + ')');%0A test.done();%0A %7D%0A %7D %0A%7D;%0A
f20f7aa9f6708bf1a7171d76136737f3009df032
fix theatre mode
common/content/theatre-mode.js
common/content/theatre-mode.js
(function (){ var theatreBtnSelector = '.qa-theatre-mode-button'; const MAX_TRIES = 400; function waitUntilVisible(selector, callback){ var tries = 0; var tm = setInterval(function (){ var el = document.querySelector(selector); if ( ++tries > MAX_TRIES ) { clearInterval(tm); callback("timeout error"); } if ( el && el.offsetHeight > 0 ) { clearInterval(tm); callback(); } }, 50) } function wait(fn, callback){ if ( fn() ) { return callback(); } else { setTimeout(function (){ wait(fn, callback) }, 250); } } function turnOn(){ var turnOnBtn = document.querySelector(theatreBtnSelector); if ( turnOnBtn ) { turnOnBtn.click(); } } document.addEventListener("DOMContentLoaded", function (){ var hash = window.location.search; // no iframes var ref = document.referrer || ""; //inside player's iframe if ( /mode=theater/i.test(ref) || /mode=theater/i.test(hash) ) { waitUntilVisible(theatreBtnSelector, function (err){ if ( !err ) { turnOn(); } }) } }) })();
JavaScript
0.000001
@@ -40,11 +40,30 @@ = ' -.qa +%5Bdata-a-target=%22player -the @@ -78,16 +78,18 @@ e-button +%22%5D ';%0A con @@ -986,34 +986,34 @@ if ( /mode=theat -e r +e /i.test(ref) %7C%7C @@ -1023,18 +1023,18 @@ de=theat -e r +e /i.test(
d9a98bb71830aab192d2e37368bb69dbbf04b07d
Add application started global var
www/lib/global.js
www/lib/global.js
var recipes = null; var recipe_images = null; var favs = []; var interval_ready_id = null; var registered = false; var last_updated = "1984-01-01"; Storage.prototype.setObj = function(key, obj) { return this.setItem(key, JSON.stringify(obj)); }; Storage.prototype.getObj = function(key) { return JSON.parse(this.getItem(key)); };
JavaScript
0
@@ -140,16 +140,49 @@ -01-01%22; +%0Avar application_started = false; %0A%0AStorag
d279fd6705936c8d944a49612a9415d7b876c606
package script updates
package-scripts.js
package-scripts.js
const { series, crossEnv, concurrent, rimraf } = require('nps-utils'); const { config: { port: E2E_PORT } } = require('./test/protractor.conf'); module.exports = { scripts: { default: 'nps webpack', test: { default: 'nps test.jest', jest: { default: crossEnv('BABEL_TARGET=node jest'), accept: crossEnv('BABEL_TARGET=node jest -u'), watch: crossEnv('BABEL_TARGET=node jest --watch') }, karma: { default: series( rimraf('test/coverage-karma'), 'karma start test/karma.conf.js' ), watch: 'karma start test/karma.conf.js --auto-watch --no-single-run', debug: 'karma start test/karma.conf.js --auto-watch --no-single-run --debug' }, lint: { default: 'eslint .', fix: 'eslint --fix' }, react: { default: crossEnv('BABEL_TARGET=node jest --no-cache --config jest.React.json --notify'), accept: crossEnv('BABEL_TARGET=node jest -u --no-cache --config jest.React.json --notify'), watch: crossEnv('BABEL_TARGET=node jest --watch --no-cache --config jest.React.json --notify') }, all: concurrent({ browser: series.nps('test.karma', 'e2e'), jest: 'nps test.jest', lint: 'nps test.lint' }) }, e2e: { default: `${concurrent({ webpack: `webpack-dev-server --inline --port=${E2E_PORT}`, protractor: 'nps e2e.whenReady' })} --kill-others --success first`, protractor: { install: 'webdriver-manager update', default: series( 'nps e2e.protractor.install', 'protractor test/protractor.conf.js' ), debug: series( 'nps e2e.protractor.install', 'protractor test/protractor.conf.js --elementExplorer' ) }, whenReady: series( `wait-on --timeout 120000 http-get://localhost:${E2E_PORT}/index.html`, 'nps e2e.protractor' ) }, build: 'nps webpack.build', webpack: { default: 'nps webpack.server', build: { before: rimraf('dist'), default: 'nps webpack.build.production', development: { default: series( 'nps webpack.build.before', 'webpack --progress -d' ), extractCss: series( 'nps webpack.build.before', 'webpack --progress -d --env.extractCss' ), serve: series.nps( 'webpack.build.development', 'serve' ) }, production: { inlineCss: series( 'nps webpack.build.before', crossEnv('NODE_ENV=production webpack --progress -p --env.production') ), default: series( 'nps webpack.build.before', crossEnv('NODE_ENV=production webpack --progress -p --env.production --env.extractCss') ), serve: series.nps( 'webpack.build.production', 'serve' ) } }, server: { default: 'webpack-dev-server -d --inline --env.server', extractCss: 'webpack-dev-server -d --inline --env.server --env.extractCss', hmr: 'webpack-dev-server -d --inline --hot --env.server' } }, serve: 'pushstate-server dist' } };
JavaScript
0.000001
@@ -265,32 +265,90 @@ default: + series(%0A rimraf('test/coverage-jest'),%0A crossEnv('BABEL @@ -362,24 +362,34 @@ =node jest') +%0A ) ,%0A ac @@ -490,16 +490,17 @@ -watch') +, %0A %7D
d4eda0963cc512bf46005f89ce9e5e0e78ee15ad
Deal with more complex wrappings, get first three tests passing.
wapper.js
wapper.js
var Wapper = { split: function(range) { var startParent = range.startContainer var endParent = range.endContainer if (startParent == endParent) { // Achtung! Zero-length selection. if (range.startOffset == range.endOffset) return endParent.splitText(range.endOffset) var middle = startParent.splitText(range.startOffset) return [middle] } else { var commonAncestor = range.commonAncestorContainer var between = [] if (commonAncestor == startParent.parentNode) { // Common scenario where selection contains a few text and element // nodes within a block-level element - a <p> for instance. var current = startParent.splitText(range.startOffset) var after = endParent.splitText(range.endOffset) for (current; current != after; current = current.nextSibling) { between.push(current) } } else { // More complex scenario where the selection spans multiple elements. endParent.splitText(range.endOffset) var start = startParent.splitText(range.startOffset) var end = endParent // Ascend DOM until parent is a child of the common ancestor. function rootNode(node) { while (node.parentNode.parentNode != commonAncestor) { node = node.parentNode } return node } var startRoot = rootNode(start) var endRoot = rootNode(end) var current current = startRoot for (current; current; current = current.nextSibling) { between.push(current) } var tail = [] current = endRoot for (current; current; current = current.previousSibling) { tail.unshift(current) } current = startRoot.parentNode while(current.nextSibling != endRoot.parentNode) { between.push(current = current.nextSibling) } between = between.concat(tail) } return between } }, wrap: function(range) { var elems = this.split(range) function createWrapper() { return document.createElement("span") } for (var i = 0; i < elems.length; i++) { var wrapper = createWrapper() var elem = elems[i] wrapper.appendChild(elem.cloneNode(true)) elem.parentNode.replaceChild(wrapper, elem) } } }
JavaScript
0
@@ -2079,16 +2079,58 @@ t(range) +%0A var currentParent%0A var groups = %5B%5D %0A%0A fu @@ -2201,24 +2201,71 @@ an%22)%0A %7D%0A%0A + // Group contained nodes by shared parent.%0A for (var @@ -2311,157 +2311,490 @@ var -wrapper = createWrapper()%0A var elem = elems%5Bi%5D%0A wrapper.appendChild(elem.cloneNode(true))%0A elem.parentNode.replaceChild(wrapper, elem) +elem = elems%5Bi%5D%0A%0A if (elem.parentNode == currentParent) %7B%0A groups%5Bgroups.length - 1%5D.push(elem)%0A %7D else %7B%0A groups.push(%5Belem%5D)%0A %7D%0A%0A currentParent = elem.parentNode%0A %7D%0A%0A for (var g = 0; g %3C groups.length; g++) %7B%0A var children = groups%5Bg%5D%0A var wrapper = createWrapper()%0A%0A children%5B0%5D.parentNode.insertBefore(wrapper, children%5B0%5D)%0A%0A for (var c = 0; c %3C children.length; c++) %7B%0A wrapper.appendChild(children%5Bc%5D)%0A %7D %0A
aba326e0f9ed0ba8b1708532ec80dc95ede7f89d
add support for inlined view-kind definitions in application kinds
source/kernel/ViewController.js
source/kernel/ViewController.js
//*@public /** The _enyo.ViewController_ is an abstract class designed to allow a controller to own a _view_ and designate its state rather than the other way around. It has the ability to render its _view_ into the DOM on demand. */ enyo.kind({ //*@public name: "enyo.ViewController", //*@public kind: "enyo.Controller", //*@public /** The _view_ property can be assigned a string path or a reference to a _view_ that this controller will use when its _render_ or _renderInto_ methods are called. */ view: null, //*@public /** The _renderTarget_ can be a string representation such as _document.body_ (a special case in JavaScript) or a node's id attribute e.g. `#mydiv`. */ renderTarget: "document.body", //*@protected constructor: function () { this.inherited(arguments); }, //*@protected create: function () { var ctor = this.get("viewKind"); this.view = new ctor(); this.inherited(arguments); }, //*@public /** Call this method to render the selected _view_ into the designated _renderTarget_. */ render: function () { var target = this.get("target"); var view = this.get("view"); view.renderInto(target); }, //*@public /** Pass this method the target node to render the _view_ into immediately. */ renderInto: function (target) { this.set("renderTarget", target); this.render(); }, //*@protected target: enyo.Computed(function () { var target = this.renderTarget; if ("string" === typeof target) { if ("#" === target[0]) { target = target.slice(1); target = enyo.dom.byId(target); } else { target = enyo.getPath(target); } if (!target) { target = enyo.dom.byId(target); } } if (!target) { throw "Cannot find requested render target!"; } return target; }, "renderTarget"), //*@protected viewKind: enyo.Computed(function () { var view = this.view; if ("string" === typeof view) { view = enyo.getPath(view); } if (!view) { throw "Cannot find the requested view!"; } return view; }, "view") });
JavaScript
0
@@ -835,99 +835,8 @@ ted%0A - constructor: function () %7B%0A this.inherited(arguments);%0A %7D,%0A //*@protected%0A @@ -2150,32 +2150,128 @@ iew;%0A if +(%22object%22 === typeof view && view.kind) %7B%0A view = enyo.kind(view);%0A %7D else if (%22string%22 === ty
6748773551c629d82338978c47544334fa31e5a5
debug events in drawbot
communication/communication.js
communication/communication.js
var root = require('../root'), fs = require('fs'), util = require('util'), events = require('events'), serialport = require("serialport"), SerialPort = serialport.SerialPort; // localize object constructor /** * Communication class to talk with the drawbot */ var Communication = function() { var firstArrow = true, index = 0, EOF = false, serial, self = this, isConnected = false, emitEventOnFinish = false, cmdBuffer = fs.readFileSync(root.path + '/communication/setup.gcode').toString().split('\n'); //init the buffer with setup code this.EVENT = { CONNECTED: 'connected', PORT_OPENED: 'portOpened', DISCONNECTED: 'disconnected', LOG: 'log', DRAW_STARTED: 'drawStarted', DRAW_FINISHED: 'drawFinished' }; this.isDrawing = false; /** * get serial ports available * @param callback this will be called with ports as parameters */ this.getSerialPortList = function(callback) { serialport.list(function(err, ports) { callback(ports); }); }; /** * Connect to drawbot on given port comName * @param portComName */ this.connect = function(portComName) { if(!isConnected) { if(!portComName) { util.error('Called connect but no port defined'); return; } isConnected = true; self.emit(self.EVENT.CONNECTED); serial = new SerialPort(portComName, { parser: serialport.parsers.readline("\n"), baudrate: 57600 }); serial.on("open", function () { self.emit(self.EVENT.PORT_OPENED); //get data and log self.log('-- [COMM] communication opened on ' + portComName); serial.on('data', function(data) { //path is clear if(data.length > 2){ self.log('IN: ' + data); }else if(data.indexOf(">") >= 0) // TODO : better string { //roger if(!firstArrow) { self.write(); // send next line }else { firstArrow = false; } } }); serial.on('error', function(error) { self.emit(self.EVENT.DISCONNECTED); self.Log.error('ERROR + serial error - disconnected \n' + error); isConnected = false; }); }); } }; this.disconnect = function() { if(serial && isConnected) { self.emit(self.EVENT.DISCONNECTED); serial.close(); isConnected = false; } }; /** * Send a line to a robot and add a \n * @param string */ this.writeLine = function(string) { cmdBuffer.push(string); }; /** * send the next line to the robot */ this.write = function() { if(serial) { var cmd = cmdBuffer.splice(0, 1); if(cmd.length){ if(cmd === 'M200') { self.isDrawing = true; self.log(self.EVENT.DRAW_STARTED); self.emit(self.EVENT.DRAW_STARTED); } else if(cmd === 'M201') { self.isDrawing = false; self.emit(self.EVENT.DRAW_FINISHED); } else { self.Log.debug('SENDING : ' + cmd); serial.write(cmd + '\n', function(err, results) { if(err) self.Log.error('ERROR ' + err); }); } } } }; /** * read batch and push in buffer */ this.batch = function(text) { emitEventOnFinish = true; var oldSize = cmdBuffer.length; cmdBuffer = cmdBuffer.concat(text.split('\n')); self.Log.debug("commands : " + text); self.Log.debug(text.split('\n').length); self.Log.debug('Pushed ' + (cmdBuffer.length - oldSize) + ' new command in Buffer'); }; /** * Move the robot around * @param direction {'up', 'down', 'left', 'right'} */ this.jog = function(direction) { this.writeLine('G91'); if(direction === 'up') { this.writeLine('G00 F2000 Y20'); } else if(direction === 'down') { this.writeLine('G00 F2000 Y-20'); } else if(direction === 'left') { this.writeLine('G00 F2000 X-20'); } else if(direction === 'right') { this.writeLine('G00 F2000 X20'); } this.writeLine('G90'); }; /** * Check if we're connected to drawbot. * Useful when a user connects, so we can * directly tell him the state of the robot * @returns {boolean} */ this.isSerialConnected = function() { return isConnected; }; /** * Logging * * trace: for output purpose * error: for errors (displayed in red on web page) * debug: only for debugging, temporary logs (displayed in blue on web page) */ this.Log = { trace: function(string) { util.log(string); self.emit(self.EVENT.LOG, string, 'trace'); }, error: function(string) { util.error(string); self.emit(self.EVENT.LOG, string, 'error'); }, debug: function(string) { util.debug(string); self.emit(self.EVENT.LOG, string, 'debug'); } }; // proxy method for confort this.log = function(string) { this.Log.trace(string); } }; /** * Prototype inheritance for EventEmitter */ util.inherits(Communication, events.EventEmitter); module.exports = Communication;
JavaScript
0.000001
@@ -2819,20 +2819,25 @@ (cmd - === +.indexOf( 'M200') +) %7B%0A @@ -2984,20 +2984,25 @@ (cmd - === +.indexOf( 'M201') +) %7B%0A
5d640ae55adb74fc72cf751ae4bc2fdb7db6e231
print user's ip
UIServer.js
UIServer.js
var express = require('express'); var http = require('http'); var path = require('path'); var fs = require('fs'); var favicon = require('serve-favicon'); var bodyParser = require('body-parser'); var config = require('./config.json'); var db = require('./model/db.js'); var log = require('./model/log.js'); /* * Project Name: Kevin's Personal Website * Author: Kevin Song * Date : 2015/7/27 * Reference: * 1. How to use bodyparser? https://github.com/expressjs/body-parser * 2. ... */ // program mode, default set as production var mode = "production"; if (process.argv && process.argv[2]) { // production to be passed as param mode = process.argv[2]; } log.info("mode: " + mode); // express app config here var app = module.exports = express(); // express middle ware app.use(favicon(__dirname + '/public/favicon.ico')); app.use(express.static(path.join(__dirname, 'public'))); // create application/json parser, this will parse the json form data from the req var jsonParser = bodyParser.json(); // read the mock data if (mode === "development") { // read the mock data var mockArticleListData = require('./mock/article_list'); var mockArticleListData2 = require('./mock/article_list_previous'); var mockArticleData = require('./mock/article_data'); var mockArticleDataContent = fs.readFileSync('./mock/article_data_content.html', 'utf-8'); mockArticleData.data.article_content = mockArticleDataContent; } // http response data var successResponse = { "result": "success", "data": {} }; var failResponse = { "result": "fail", "error": "" }; // API: get_article_list app.post('/get_article_list', jsonParser, function(req, res) { res.writeHeader(200, {"Content-Type": "text/html"}); // get the form data var currentPage = req.body.current_page; var articleNumPerPage = req.body.article_num_per_page; log.info("currentPage: " + currentPage + ", articleNumPerPage: " + articleNumPerPage); //return the mock mock if (mode === "development") { // return the data according to the num if (currentPage === 0) { res.write(JSON.stringify(mockArticleListData)); } else if (currentPage === 1) { res.write(JSON.stringify(mockArticleListData2)); } else { failResponse.error = "we don't have these data, begin: " + begin + ", end: " + end; res.write(JSON.stringify(failResponse)); } } else { /* query data from mongodb * here we will use mongoose to get data from mongodb. * and sort api can let us sort the data in mongodb before search. We sort as the date. * and skip, limit api can let us achieve the range query when user query different page's data. */ db.find({}, function(err, data) { if (err) { log.info("Database Error: get data from collection. Error: " + err); failResponse.error = err; res.write(JSON.stringify(failResponse)); res.end(); } else { log.info("Database: get data success. data.length: " + data.length); // get the number of the all articles db.count(function(err, count) { if (err) { log.info("Database Error: count articles number. Error: " + err); failResponse.error = err; res.write(JSON.stringify(failResponse)); } else { log.info("articles total number: " + count); successResponse.data = {}; successResponse.data.total_aritcle_num = count; successResponse.data.article_list = data; // return response res.write(JSON.stringify(successResponse)); } res.end(); }); } }).select(db.show_fields).sort({'article_time':'desc'}).skip((currentPage-1) * articleNumPerPage).limit(articleNumPerPage); } }); // API: get_article app.post('/get_article', jsonParser, function(req, res) { res.writeHeader(200, {"Content-Type": "text/html"}); // get the article id var id = req.body._id; //log.info("id: " + id); //return the mock mock if (mode === "development") { // return the data according to the num if (id == 1) { res.write(JSON.stringify(mockArticleData)); } else { failResponse.error = "we don't have this article, id: " + id; res.write(JSON.stringify(failResponse)); } res.end(); } else { // query data from mongodb db.findById(id, function(err, data) { if (err) { log.info("Database Error: get data from collection. Error: " + err); failResponse.error = err; res.write(JSON.stringify(failResponse)); } else { log.info("Database: get data success. Article title: " + data.article_title); successResponse.data = data; res.write(JSON.stringify(successResponse)); } res.end(); }); } }); // get port var port = config.server.port; log.info("Server listening on port: " + port); // create server http.createServer(app).listen(port);
JavaScript
0.000388
@@ -1635,16 +1635,194 @@ %22%22%0A%7D;%0A%0A +// get IP%0Aapp.use(function(req, res, next) %7B%0A var ip = req.headers%5B'x-forwarded-for'%5D %7C%7C req.connection.remoteAddress;%0A log.info(%22New request, ip: %22 + ip);%0A next();%0A%7D);%0A %0A// API:
92a922c89bae8cf188ef160ac0023f4592a9fc7d
Support params when deriving mark:set commands
defaultschema.js
defaultschema.js
import {SchemaSpec, Schema, Block, Textblock, Inline, Text, Attribute, MarkType} from "./schema" // ;; The default top-level document node type. export class Doc extends Block { static get kinds() { return "doc" } } // ;; The default blockquote node type. export class BlockQuote extends Block {} // ;; The default ordered list node type. Has a single attribute, // `order`, which determines the number at which the list starts // counting, and defaults to 1. export class OrderedList extends Block { get contains() { return "list_item" } get isList() { return true } get attrs() { return {order: new Attribute({default: "1"})} } } // ;; The default bullet list node type. export class BulletList extends Block { get contains() { return "list_item" } get isList() { return true } } // ;; The default list item node type. export class ListItem extends Block { static get kinds() { return "list_item" } } // ;; The default horizontal rule node type. export class HorizontalRule extends Block { get contains() { return null } } // ;; The default heading node type. Has a single attribute // `level`, which indicates the heading level, and defaults to 1. export class Heading extends Textblock { get attrs() { return {level: new Attribute({default: "1"})} } } // ;; The default code block / listing node type. Only // allows unmarked text nodes inside of it. export class CodeBlock extends Textblock { get contains() { return "text" } get containsMarks() { return false } get isCode() { return true } } // ;; The default paragraph node type. export class Paragraph extends Textblock { get defaultTextblock() { return true } } // ;; The default inline image node type. Has these // attributes: // // - **`src`** (required): The URL of the image. // - **`alt`**: The alt text. // - **`title`**: The title of the image. export class Image extends Inline { get attrs() { return { src: new Attribute, alt: new Attribute({default: ""}), title: new Attribute({default: ""}) } } } // ;; The default hard break node type. export class HardBreak extends Inline { get selectable() { return false } get isBR() { return true } } // ;; The default emphasis mark type. export class EmMark extends MarkType { static get rank() { return 51 } } // ;; The default strong mark type. export class StrongMark extends MarkType { static get rank() { return 52 } } // ;; The default link mark type. Has these attributes: // // - **`href`** (required): The link target. // - **`title`**: The link's title. export class LinkMark extends MarkType { static get rank() { return 53 } get attrs() { return { href: new Attribute, title: new Attribute({default: ""}) } } } // ;; The default code font mark type. export class CodeMark extends MarkType { static get rank() { return 101 } get isCode() { return true } } // :: SchemaSpec // The specification for the default schema. const defaultSpec = new SchemaSpec({ doc: Doc, blockquote: BlockQuote, ordered_list: OrderedList, bullet_list: BulletList, list_item: ListItem, horizontal_rule: HorizontalRule, paragraph: Paragraph, heading: Heading, code_block: CodeBlock, text: Text, image: Image, hard_break: HardBreak }, { em: EmMark, strong: StrongMark, link: LinkMark, code: CodeMark }) // :: Schema // ProseMirror's default document schema. export const defaultSchema = new Schema(defaultSpec)
JavaScript
0
@@ -543,39 +543,8 @@ %22 %7D%0A - get isList() %7B return true %7D%0A ge @@ -731,39 +731,8 @@ %22 %7D%0A - get isList() %7B return true %7D%0A %7D%0A%0A/
bc8f0f74ac71dc24ba1f074da63890da6d6628b6
Fix calendar rendering and for loops
js/cowCal.js
js/cowCal.js
/* * cowCal Javascript calendar plugin * Author: Dave Russell Jr (drussell393) * License: MIT */ /* * Here's something fun to blow minds. Below is the conversion function for timezones. * Because the server (this was originally built for WordPress) has a different saved * timezone from our local timezone in some cases, we want to be able to change everything * to the remote timezone. Here's the problem with that: * * - PHP uses seconds using the DateTimeZone class. * - Javascript uses seconds, minutes, and milliseconds mixed in. Date.prototype.getTime() * is using milliseconds, while Date.prototype.getTimezoneOffset() uses minutes. In order * to keep everything sane, we're going to convert everything to milliseconds. */ function convertTimezone(remoteUTCOffset) { // Handle our local time var localTime = new Date(); var localUTC = localTime.getTime() + (localTime.getTimezoneOffset() * 60000); // Handle our desired time (from our settings page) var remoteTime = new Date(localUTC + (remoteUTCOffset * 1000)); // Return our converted time return remoteTime; } function cowCal(remoteUTCOffset, month, year, firstDayofWeek) { // Get our current date/time var currentTime = convertTimezone(remoteUTCOffset); // Defining calendar presets this.namesOfDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; var cowNamesOfMonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; this.month = ((isNaN(month) || month == null) ? currentTime.getMonth() : month); this.year = ((isNaN(year) || year == null) ? currentTime.getFullYear() : year); this.firstDayofWeek = ((isNaN(firstDayofWeek) || firstDayofWeek == null) ? 0 : firstDayofWeek); // Check for leap years if (((this.year % 4) == 0) || ((this.year % 100) == 0) && ((this.year % 400) == 0)) { var cowDaysInMonths = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; } else { var cowDaysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; } this.firstDayofMonth = new Date(this.year, this.month, 1).getDay(); this.daysInMonth = cowDaysInMonths[this.month]; this.nameOfMonth = cowNamesOfMonths[this.month]; } cowCal.prototype.cowMonth = function() { var htmlOutput = '<table class="cowCal-month">'; htmlOutput += '<tr>'; var i = this.firstDayofWeek; // Generate our labels for the days of the week if (i > 0) { for (i < 7; i++;) { htmlOutput += '<th>' + this.namesOfDays[i] + '</th>'; } var i = 0; for (i < this.firstDayofWeek; i++;) { htmlOutput += '<th>' + this.namesOfDays[i] + '</th>'; } } else { console.log(i); htmlOutput += '<th>' + this.namesOfDays[i] + '</th>'; } htmlOutput += '</tr>'; // Generate our actual days in the month var dayNumber = 1; var week = 0; var dayPosition = 0; for (week < 9; week++;) { htmlOutput += '<tr>'; for (dayPosition <= 6; dayPosition++;) { htmlOutput += '<td>'; if ((dayNumber <= this.daysInMonth) && (week > 0 || dayPosition >= this.firstDayofWeek)) { htmlOutput += dayNumber; dayNumber++; } htmlOutput += '</td>'; } if (dayNumber > this.daysInMonth) { break; } else { htmlOutput += '</tr>'; htmlOutput += '<tr>'; } } htmlOutput += '</tr>'; htmlOutput += '</table>'; return htmlOutput; }
JavaScript
0
@@ -2397,41 +2397,8 @@ r%3E'; -%0A var i = this.firstDayofWeek; %0A%0A @@ -2473,24 +2473,53 @@ for ( +var i = this.firstDayofWeek; i %3C 7; i++;) @@ -2512,25 +2512,24 @@ ; i %3C 7; i++ -; ) %7B%0A @@ -2600,24 +2600,29 @@ %7D%0A +for ( var i = 0;%0A @@ -2619,30 +2619,17 @@ r i = 0; -%0A for ( + i %3C this @@ -2648,17 +2648,16 @@ eek; i++ -; ) %7B%0A @@ -2761,24 +2761,60 @@ -console.log(i);%0A +for (var i = this.firstDayofWeek; i %3C 7; i++) %7B%0A @@ -2867,24 +2867,34 @@ + '%3C/th%3E';%0A + %7D%0A %7D%0A ht @@ -2987,20 +2987,26 @@ er = 1;%0A +%0A +for ( var week @@ -3014,44 +3014,9 @@ = 0; -%0A var dayPosition = 0;%0A%0A for ( + week @@ -3027,17 +3027,16 @@ ; week++ -; ) %7B%0A @@ -3074,16 +3074,37 @@ for ( +var dayPosition = 0; dayPosit @@ -3126,17 +3126,16 @@ sition++ -; ) %7B%0A @@ -3258,20 +3258,21 @@ rstDayof -Week +Month )) %7B%0A
6e60a0f7b169abe358a88b10d83fbde15ccf79de
修复html-loader解析错误问题
lib/config/genConfig/mp/html.js
lib/config/genConfig/mp/html.js
'use strict' let _ = require('lodash'); let path = require('path'); let glob = require('glob'); let webpack = require('webpack'); let HtmlWebpackPlugin = require('html-webpack-plugin'); let WebpackSrcmapPlugin = require('webpack-srcmap-plugin'); let FaviconsWebpackPlugin = require('favicons-webpack-plugin'); let HtmlWebpackPluginReplaceurl = require('html-webpack-plugin-replaceurl'); let HtmlWebpackPluginHtmlhint = require('html-webpack-plugin-htmlhint'); const ENV = require('../../../constants').env; module.exports = function(config) { // html configuration const CONFIG_HTML = config.html; let preLoaders = []; let loaders = []; let postLoaders = []; let plugins = []; let dependencies = []; let extras = null; /// 如果用户配置了webpack loaders,则沿袭用户的配置 CONFIG_HTML.webpackConfig && ((options) => { // check preLoader & preLoaders options.preLoader && _.isPlainObject(options.preLoader) && preLoaders.push(Object.assign({}, CONFIG_HTML.webpackConfig.preLoader)); options.preLoaders && _.isArray(options.preLoaders) && (preLoaders = preLoaders.concat( options.preLoaders)); // check loader & loaders options.loader && _.isPlainObject(options.loader) && loaders.push(Object.assign({}, CONFIG_HTML.webpackConfig.loader)); options.loaders && _.isArray(options.loaders) && (preLoaders = loaders.concat(options.loaders)); // check postloader & postloaders options.postloader && _.isPlainObject(options.postloader) && postLoaders.push(Object.assign({}, CONFIG_HTML.webpackConfig.postloader)); options.postloaders && _.isArray(options.postloaders) && (postLoaders = postLoaders.concat( options.postloaders)); // check plugins options.plugins && (plugins = plugins.concat(options.plugins)); // check extras extras = utils.mapWpExtras(options); })(CONFIG_HTML.webpackConfig); /** * @desc 生成默认配置 * @return none */ (() => { // 文件后缀 const EXTTYPE = CONFIG_HTML.extType || 'html'; // 匹配正则 const REG_EXTTYPE = _.isArray(EXTTYPE) ? new RegExp('\\.(' + EXTTYPE.join('|') + ')$') : new RegExp('\\.' + EXTTYPE + '$'); const REG_WITHEXT = new RegExp(CONFIG_HTML.srcDir + '\/' + CONFIG_HTML.mainFilePrefix + '\\.[\\w+\\.-]*' + EXTTYPE + '$'); let _srcDir = path.posix.join(process.cwd(), config.basic.localPath.src, CONFIG_HTML.srcDir); let _files = (CONFIG_HTML.files && CONFIG_HTML.files !== '*') || glob.sync(path.posix.join( _srcDir, '**', '*.' + EXTTYPE)); // 每个index.*.html主文件创建独立的HtmlWebpackPlugin对象 if (_files && _files.length !== 0) { _files.forEach(function(file) { plugins = plugins.concat([ new HtmlWebpackPlugin({ // filename必须写相对路径,以output path为root filename: REG_WITHEXT.exec(file)[0], template: file, inject: false, xhtml: true, minify: false, hash: false }) ]); }); } // let _cdn = global.boi_deploy_cdn && global.boi_deploy_cdn.default; // // HtmlWebpackPluginReplaceurl自动替换url // let _urlPrefix = _cdn && _cdn.domain && _cdn.domain.replace(/^(http(s)?\:)?\/*/, '//') || // null; plugins.push(new HtmlWebpackPluginReplaceurl({ js: { mainFilePrefix: config.js.files ? '' : config.js.mainFilePrefix, useHash: process.env.BOI_ENV !== ENV.development && config.js.useHash || false }, style: { mainFilePrefix: config.style.files ? '' : config.style.mainFilePrefix, useHash: process.env.BOI_ENV !== ENV.development && config.style.useHash || false }, vendor: config.js.mutiEntriesVendor || (config.js.files && config.js.files.vendor) ? 'vendor.js' : null, urlTimestamp: config.basic.urlTimestamp || false, // urlPrefix: _urlPrefix })); // 根据用户配置是否输出manifest文件 if (CONFIG_HTML.staticSrcmap) { plugins.push(new WebpackSrcmapPlugin({ outputfile: 'manifest.json', nameWithHash: true })); } // 根据用户配置是否编译favicon文件 if (CONFIG_HTML.favicon) { plugins.push(new FaviconsWebpackPlugin({ logo: path.posix.join(process.cwd(), CONFIG_HTML.favicon), inject: true, prefix: path.posix.join(config.image.destDir + '/favicons/'), statsFilename: 'iconstats.json', persistentCache: false, icons: { android: false, appleIcon: false, appleStartup: false, coast: false, favicons: true, firefox: false, opengraph: false, twitter: false, yandex: false, windows: false } })); } /** * lint插件 * @see https://github.com/boijs/html-webpack-plugin-htmlhint */ process.env.BOI_ENV !== ENV.development && CONFIG_HTML.lint && ((options) => { let _configFile = ''; if (options.lintConfigFile) { _configFile = path.isAbsolute(options.lintConfigFile) ? options.lintConfigFile : path.posix.join(process.cwd(), options.lintConfigFile); } else { try { _configFile = require.resolve(path.posix.join(process.cwd(), 'node_modules', 'boi-aux-rule-htmlhint')); } catch (e) { exec('npm install boi-aux-rule-htmlhint --save-dev'); _configFile = require.resolve(path.posix.join(process.cwd(), 'node_modules', 'boi-aux-rule-htmlhint')); } } plugins.push(new HtmlWebpackPluginHtmlhint({ configFile: _configFile })); })(CONFIG_HTML); // 如果loader为空,则使用默认的html-loader loaders.length === 0 && loaders.push(Object.assign({}, { test: REG_EXTTYPE, loader: 'html', query: { // I don't what this configuration for,but it just works... // @see https://github.com/webpack/webpack/issues/752 "minimize": false, // 保留html注释 "removeComments": false, // 不压缩 "collapseWhitespace": false } })); })(); return { preLoaders, postLoaders, loaders, plugins, extras, dependencies }; }
JavaScript
0.000001
@@ -5722,16 +5722,23 @@ r: 'html +-loader ',%0A
78789e7b62e11c1e242037481b03dc03185eca93
Add vote results back to entries
voting-server/src/core.js
voting-server/src/core.js
import {List, Map} from 'immutable'; export function setEntries(state, entries) { return state.set('entries', List(entries)); } export function next(state) { const entries = state.get('entries'); return state.merge({ vote: Map({pair: entries.take(2)}), entries: entries.skip(2) }); } export function vote(state, entry) { // Pretty accessor syntax for updating a value inside a nested dictionary return state.updateIn(['vote', 'tally', entry], 0, tally => tally + 1); }
JavaScript
0
@@ -123,24 +123,445 @@ tries));%0A%7D%0A%0A +function getWinners(vote) %7B%0A if (!vote) %7B%0A return %5B%5D;%0A %7D%0A%0A const %5BmovieA, movieB%5D = vote.get('pair');%0A const movieAVotes = vote.getIn(%5B'tally', movieA%5D, 0);%0A const movieBVotes = vote.getIn(%5B'tally', movieB%5D, 0);%0A%0A if (movieAVotes %3E movieBVotes) %7B%0A return %5BmovieA%5D;%0A %7D else if (movieAVotes %3C movieBVotes) %7B%0A return %5BmovieB%5D;%0A %7D else %7B%0A return %5BmovieA, movieB%5D;%0A %7D%0A%7D%0A%0A export funct @@ -618,16 +618,54 @@ ntries') +.concat(getWinners(state.get('vote'))) ;%0A re
7863ee5594e25a757c685179d5f86032721fed69
Add google analythics and facebook pixel widget
js/custom.js
js/custom.js
(function($){ "use strict"; // ______________ SUPERFISH jQuery('#navigation').superfish({ speed : 1, animation: false, animationOut: false }); // ______________ MOBILE MENU $(function(){ $('#navigation').slicknav({ label: "", closedSymbol: "&#8594;", openedSymbol: "&#8595;" }); }); // ______________ HOME PAGE WORDS ROTATOR $("#js-rotating").Morphext({ animation: "bounceInLeft", separator: ",", speed: 6000 }); $('#js-rotating').show(); // ______________ ANIMATE EFFECTS var wow = new WOW( { boxClass: 'wow', animateClass: 'animated', offset: 0, mobile: false } ); wow.init(); // SMOOTH SCROLL________________________// $(function() { $('a[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 }, 1000); return false; } } }); }); // ______________ BACK TO TOP BUTTON $(window).scroll(function () { if ($(this).scrollTop() > 300) { $('#back-to-top').fadeIn('slow'); } else { $('#back-to-top').fadeOut('slow'); } }); $('#back-to-top').click(function(){ $("html, body").animate({ scrollTop: 0 }, 600); return false; }); var googleforms_popup = new Foundation.Reveal($('#googleforms-modal')); $('#googleforms-action').click(function(){ googleforms_popup.open(); }); $('.close-googleforms-modal').click(function(){ googleforms_popup.close(); }); var video_popup = new Foundation.Reveal($('#video-modal')); $('#video-action').click(function(){ video_popup.open(); }); $('.close-video-modal').click(function(){ video_popup.close(); }); })(jQuery);
JavaScript
0
@@ -2066,8 +2066,877 @@ jQuery); +%0A%0A// Google Analytics%0A(function(i,s,o,g,r,a,m)%7Bi%5B'GoogleAnalyticsObject'%5D=r;i%5Br%5D=i%5Br%5D%7C%7Cfunction()%7B%0A(i%5Br%5D.q=i%5Br%5D.q%7C%7C%5B%5D).push(arguments)%7D,i%5Br%5D.l=1*new Date();a=s.createElement(o),%0Am=s.getElementsByTagName(o)%5B0%5D;a.async=1;a.src=g;m.parentNode.insertBefore(a,m)%0A%7D)(window,document,'script','https://www.google-analytics.com/analytics.js','ga');%0A%0Aga('create', 'UA-86896105-1', 'auto');%0Aga('send', 'pageview');%0A%0A%0A// Facebook Pixel Code%0A!function(f,b,e,v,n,t,s)%7Bif(f.fbq)return;n=f.fbq=function()%7Bn.callMethod?%0An.callMethod.apply(n,arguments):n.queue.push(arguments)%7D;if(!f._fbq)f._fbq=n;%0An.push=n;n.loaded=!0;n.version='2.0';n.queue=%5B%5D;t=b.createElement(e);t.async=!0;%0At.src=v;s=b.getElementsByTagName(e)%5B0%5D;s.parentNode.insertBefore(t,s)%7D(window,%0Adocument,'script','https://connect.facebook.net/en_US/fbevents.js');%0Afbq('init', '663531177160564');%0Afbq('track', 'PageView');%0A
7e89d60fb7f4c5f99f2e1793d086303949968ab3
Add `large` to the size prop values
src/components/iconButton/IconButton.js
src/components/iconButton/IconButton.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Box from '../box'; import Icon from '../icon'; import cx from 'classnames'; import buttonTheme from '../button/theme.css'; import theme from './theme.css'; class IconButton extends Component { handleMouseUp = (event) => { this.blur(); if (this.props.onMouseUp) { this.props.onMouseUp(event); } }; handleMouseLeave = (event) => { this.blur(); if (this.props.onMouseLeave) { this.props.onMouseLeave(event); } }; blur() { if (this.buttonNode.blur) { this.buttonNode.blur(); } } render() { const { children, className, disabled, element, icon, size, color, selected, type, ...others } = this.props; const classNames = cx( buttonTheme['button-base'], theme['icon-button'], theme[`is-${size}`], { [theme['is-disabled']]: disabled, [theme['is-selected']]: selected, }, className, ); const props = { ...others, ref: (node) => { this.buttonNode = node; }, className: classNames, disabled: element === 'button' ? disabled : null, element: element, onMouseUp: this.handleMouseUp, onMouseLeave: this.handleMouseLeave, type: element === 'button' ? type : null, 'data-teamleader-ui': 'button', }; return ( <Box {...props}> <Icon color={color === 'white' ? 'neutral' : color} tint={color === 'white' ? 'lightest' : 'darkest'}> {icon} </Icon> {children} </Box> ); } } IconButton.propTypes = { children: PropTypes.node, className: PropTypes.string, disabled: PropTypes.bool, /** A custom element to be rendered */ element: PropTypes.oneOfType([PropTypes.element, PropTypes.string]), icon: PropTypes.element, onMouseLeave: PropTypes.func, onMouseUp: PropTypes.func, /** If true, component will be shown in a selected state */ selected: PropTypes.bool, size: PropTypes.oneOf(['small', 'medium']), color: PropTypes.oneOf(['neutral', 'white', 'mint', 'violet', 'ruby', 'gold', 'aqua']), type: PropTypes.string, }; IconButton.defaultProps = { className: '', element: 'button', size: 'medium', color: 'neutral', type: 'button', }; export default IconButton;
JavaScript
0.000006
@@ -2042,16 +2042,25 @@ 'medium' +, 'large' %5D),%0A co
9739dd717a7a284f15814ec0fe52a77efb1f2856
Move stylesheet to react-atlas package when building for production.
scripts/buildPackages.js
scripts/buildPackages.js
var fs = require("fs"); var path = require("path"); var spawn = require("cross-spawn"); var glob = require("glob"); var path = require("path"); // get packages paths var packages = glob.sync(path.join(__dirname, "../packages/react-atlas*/"), { realpath: true }); packages.push(packages.shift()); packages.forEach(function(pack) { // ensure path has package.json if(!fs.existsSync(path.join(pack, "package.json"))) return; if(process.env.NODE_ENV === 'production') { spawn.sync(pack + '/node_modules/webpack/bin/webpack.js', ['-p'], { env: process.env, cwd: pack, stdio: "inherit" }); } else { spawn.sync(pack + '/node_modules/webpack/bin/webpack.js', { env: process.env, cwd: pack, stdio: "inherit" }); } });
JavaScript
0
@@ -764,12 +764,405 @@ );%0A %7D%0A %7D);%0A +%0A /* If we are building for production move the stylesheet from react-atlas-default-theme/lib to react-atlas/lib */%0A if(process.env.NODE_ENV === 'production') %7B%0A var oldPath = path.join(__dirname, %22../packages/react-atlas-default-theme/lib/atlasThemes.min.css%22);%0A var newPath = path.join(__dirname, %22../packages/react-atlas/lib/atlasThemes.min.css%22)%0A fs.renameSync(oldPath, newPath);%0A %7D%0A
cdee4b6c176d0e59a7882a9801256ab7a4211071
add some classic rules, fix typo
src/components/profile/profile.style.js
src/components/profile/profile.style.js
import styled, { css } from 'styled-components'; import Portrait from '../portrait'; import baseTheme from '../../style/themes/base'; import { THEMES } from '../../style/themes'; const portraitSizes = { 'extra-small': { dimensions: 24, nameSize: '13px', emailSize: '12px', lineHeight: '12px', marginLeft: '16px' }, small: { dimensions: 32, nameSize: '14px', emailsize: '12px', lineHeight: '16px', marginLeft: '16px' }, 'medium-small': { dimensions: 40, nameSize: '14px', emailSize: '14px', lineHeight: '16px', marginLeft: '16px' }, medium: { dimensions: 56, nameSize: '14px', emailSize: '14px', lineHeight: '20px', marginLEft: '24px' }, 'medium-large': { dimensions: 72, nameSize: '20px', emailSize: '14px', lineHeight: '22px', marginLeft: '24px' }, large: { dimensions: 104, nameSize: '24px', emailSize: '20px', lineHeight: '26px', marginLeft: '32px' }, 'extra-large': { dimensions: 128, nameSize: '24px', emailSize: '20px', lineHeight: '30px', marginLeft: '40px' } }; const ProfileNameStyle = styled.span` font-weight: bold; display: inline-block; font-size: ${props => portraitSizes[props.size].nameSize}; `; const ProfileEmailStyle = styled.span` font-size: ${({ size }) => portraitSizes[size].emailSize}; `; const ProfileStyle = styled.div` white-space: nowrap; color: ${({ theme }) => theme.text.color}; ${({ large }) => large && css` ${ProfileNameStyle} { font-size: 20px; font-weight: 400; line-height: 21px; } `} ${({ theme }) => theme.name === THEMES.classic && css` color: rgba(0, 0, 0, 0.85); `}; `; const ProfileDetailsStyle = styled.div` margin-left: 14px; vertical-align: middle; display: inline-block; line-height: 16px; line-height: ${({ size }) => portraitSizes[size].lineHeight}; margin-left: ${({ size }) => portraitSizes[size].marginLeft}; `; const ProfileAvatarStyle = styled(Portrait)` display: inline-block; `; ProfileStyle.defaultProps = { theme: baseTheme }; ProfileNameStyle.defaultProps = { size: 'medium-small' }; ProfileEmailStyle.defaultProps = { size: 'medium-small' }; ProfileDetailsStyle.defaultProps = { size: 'medium-small' }; export { ProfileStyle, ProfileNameStyle, ProfileDetailsStyle, ProfileAvatarStyle, ProfileEmailStyle };
JavaScript
0.000022
@@ -710,17 +710,17 @@ marginL -E +e ft: '24p @@ -1279,24 +1279,115 @@ %5D.nameSize%7D; +%0A%0A $%7B(%7B theme %7D) =%3E theme.name === THEMES.classic && css%60%0A display: inline;%0A %60%7D; %0A%60;%0A%0Aconst P @@ -1480,16 +1480,107 @@ ilSize%7D; +%0A%0A $%7B(%7B theme %7D) =%3E theme.name === THEMES.classic && css%60%0A font-size: 14px;%0A %60%7D; %0A%60;%0A%0Acon @@ -1678,24 +1678,120 @@ xt.color%7D;%0A%0A + $%7B(%7B theme %7D) =%3E theme.name === THEMES.classic && css%60%0A color: rgba(0, 0, 0, 0.85);%0A%0A $%7B(%7B lar @@ -1951,105 +1951,14 @@ + %60%7D%0A%0A - $%7B(%7B theme %7D) =%3E theme.name === THEMES.classic && css%60%0A color: rgba(0, 0, 0, 0.85);%0A @@ -2009,29 +2009,8 @@ iv%60%0A - margin-left: 14px;%0A ve @@ -2060,30 +2060,8 @@ ck;%0A - line-height: 16px;%0A%0A li @@ -2183,16 +2183,132 @@ inLeft%7D; +%0A%0A $%7B(%7B theme %7D) =%3E theme.name === THEMES.classic && css%60%0A line-height: 16px;%0A margin-left: 14px;%0A %60%7D; %0A%60;%0A%0Acon @@ -2479,32 +2479,52 @@ : 'medium-small' +,%0A theme: baseTheme %0A%7D;%0A%0AProfileEmai @@ -2565,24 +2565,44 @@ edium-small' +,%0A theme: baseTheme %0A%7D;%0A%0AProfile @@ -2653,16 +2653,36 @@ m-small' +,%0A theme: baseTheme %0A%7D;%0A%0Aexp
f3c23239c7bb29640de1f658c5a21b87f94ba493
update etl for dim supplier
src/etl/dim-supplier-etl-manager.js
src/etl/dim-supplier-etl-manager.js
'use strict' // external deps var ObjectId = require("mongodb").ObjectId; var BaseManager = require('module-toolkit').BaseManager; var moment = require("moment"); var startedDate = new Date(); // internal deps require('mongodb-toolkit'); var SupplierManager = require('../managers/master/supplier-manager'); module.exports = class DimSupplierEtlManager extends BaseManager { constructor(db, user, sql) { super(db, user); this.sql = sql; this.supplierManager = new SupplierManager(db, user); this.migrationLog = this.db.collection("migration-log"); } run() { this.migrationLog.insert({ description: "Dim Supplier from MongoDB to Azure DWH", start: startedDate, }) return this.getTimeStamp() .then((data) => this.extract(data)) .then((data) => this.transform(data)) .then((data) => this.load(data)) .then(() => { var finishedDate = new Date(); var spentTime = moment(finishedDate).diff(moment(startedDate), "minutes"); var updateLog = { description: "Dim Supplier from MongoDB to Azure DWH", start: startedDate, finish: finishedDate, executionTime: spentTime + " minutes", status: "Successful" }; this.migrationLog.updateOne({ start: startedDate }, updateLog); }) .catch((err) => { var finishedDate = new Date(); var spentTime = moment(finishedDate).diff(moment(startedDate), "minutes"); var updateLog = { description: "Dim Supplier from MongoDB to Azure DWH", start: startedDate, finish: finishedDate, executionTime: spentTime + " minutes", status: err }; this.migrationLog.updateOne({ start: startedDate }, updateLog); }); } getTimeStamp() { return this.migrationLog.find({ description: "Dim Supplier from MongoDB to Azure DWH", status: "Successful" }).sort({ finishedDate: -1 }).limit(1).toArray() } extract(time) { var timestamp = new Date(time[0].finish); return this.supplierManager.collection.find({ _deleted: false, _createdBy: { "$nin": ["dev", "unit-test"], }, _updatedDate: { "$gt": timestamp } }).toArray(); } transform(data) { var result = data.map((item) => { return { supplierCode: item.code ? `'${item.code}'` : null, supplierName: item.name ? `'${item.name.replace(/'/g, '"')}'` : null }; }); return Promise.resolve([].concat.apply([], result)); } insertQuery(sql, query) { return new Promise((resolve, reject) => { sql.query(query, function (err, result) { if (err) { reject(err); } else { resolve(result); } }) }) } load(data) { return new Promise((resolve, reject) => { this.sql.startConnection() .then(() => { var transaction = this.sql.transaction(); transaction.begin((err) => { var request = this.sql.transactionRequest(transaction); var command = []; var sqlQuery = ''; var count = 1; for (var item of data) { if (item) { var queryString = `insert into DL_Dim_Supplier_Temp(ID_Dim_Supplier, Kode_Supplier, Nama_Supplier) values(${count}, ${item.supplierCode}, ${item.supplierName});\n`; sqlQuery = sqlQuery.concat(queryString); if (count % 1000 == 0) { command.push(this.insertQuery(request, sqlQuery)); sqlQuery = ""; } console.log(`add data to query : ${count}`); count++; } } if (sqlQuery !== "") command.push(this.insertQuery(request, `${sqlQuery}`)); this.sql.multiple = true; return Promise.all(command) .then((results) => { request.execute("DL_UPSERT_DIM_SUPPLIER").then((execResult) => { request.execute("DL_INSERT_DIMTIME").then((execResult) => { transaction.commit((err) => { if (err) reject(err); else resolve(results); }); }).catch((error) => { transaction.rollback((err) => { console.log("rollback") if (err) reject(err) else reject(error); }); }) }).catch((error) => { transaction.rollback((err) => { console.log("rollback") if (err) reject(err) else reject(error); }); }) }) .catch((error) => { transaction.rollback((err) => { console.log("rollback"); if (err) reject(err) else reject(error); }); }); }) }) .catch((err) => { reject(err); }) }) .catch((err) => { reject(err); }) } }
JavaScript
0
@@ -2372,22 +2372,21 @@ time%5B0%5D. -finish +start );%0A
77a94a27b989a9887df099353af9cc843afa75a9
Fix error when showing "add moderator" dialog in ACP
client/admin/forum/section/index.js
client/admin/forum/section/index.js
'use strict'; const _ = require('lodash'); const Bloodhound = require('corejs-typeahead/dist/bloodhound.js'); let $moderatorSelectDialog; let bloodhound; require('jqtree'); N.wire.on('navigate.done:' + module.apiPath, function page_setup() { $('.aforum-index__scontent').tree({ data: N.runtime.page_data.sections, autoOpen: true, dragAndDrop: true, onCreateLi(section, $li) { $li .addClass('aforum-index__slist-item') .find('.jqtree-element') .html(N.runtime.render('admin.forum.section.blocks.sections_tree_item', { section, users: N.runtime.page_data.users })); } }).on('tree.move', event => { // Wait next tick to ensure node update setTimeout(() => { let node = event.move_info.moved_node; let request = { _id: node._id, parent: node.parent._id || null, sibling_order: node.parent.children.map(child => child._id) }; N.io.rpc('admin.forum.section.update_order', request).catch(err => N.wire.emit('error', err)); }, 0); }); }); N.wire.before('admin.forum.section.destroy', function confirm_section_destroy(data) { return N.wire.emit( 'admin.core.blocks.confirm', t('message_confim_section_delete', { title: data.$this.data('title') }) ); }); N.wire.on('admin.forum.section.destroy', function section_destroy(data) { let $container = data.$this.closest('.aforum-index__slist-item'); return N.io.rpc('admin.forum.section.destroy', { _id: data.$this.data('id') }) .then(() => { // Remove all destroyed elements from DOM. $container.prev('._placeholder').remove(); $container.remove(); }) .catch(err => N.wire.emit('notify', err.message)); }); N.wire.on('admin.forum.section.select_moderator_nick', function section_select_moderator(data) { let sectionId = data.$this.data('section_id'); // Render dialog window. $moderatorSelectDialog = $(N.runtime.render('admin.forum.section.blocks.moderator_select_dialog', { section_id: sectionId })); if (!bloodhound) { bloodhound = new Bloodhound({ remote: { url: 'unused', // bloodhound throws if it's not defined prepare(nick) { return nick; }, // Reroute request to rpc transport(req, onSuccess, onError) { N.io.rpc('admin.core.user_lookup', { nick: req.url, strict: false }) .then(onSuccess) .catch(onError); } }, datumTokenizer(d) { return Bloodhound.tokenizers.whitespace(d.nick); }, queryTokenizer: Bloodhound.tokenizers.whitespace }); bloodhound.initialize(); } $moderatorSelectDialog.find('input[name=nick]').typeahead( { highlight: true }, { source: bloodhound.ttAdapter(), display: 'nick', templates: { suggestion(user) { return '<div>' + _.escape(user.name) + '</div>'; } } } ); $moderatorSelectDialog.on('shown.bs.modal', function () { $(this).find('input[name=nick]').focus(); }); $moderatorSelectDialog.on('hidden.bs.modal', function () { $(this).remove(); }); // Show dialog. $moderatorSelectDialog.appendTo('#content').modal({ backdrop: false }); }); N.wire.on('admin.forum.section.create_moderator', function section_add_moderator(data) { let nick = data.fields.nick; return N.io.rpc('admin.core.user_lookup', { nick, strict: true }).then(res => { if (res.length === 0) { N.wire.emit('notify', t('error_no_user_with_such_nick', { nick })); return; } $moderatorSelectDialog.on('hidden.bs.modal', () => { N.wire.emit('navigate.to', { apiPath: 'admin.forum.moderator.edit', params: { section_id: data.fields.section_id, user_id: res[0]._id } }); }).modal('hide'); }); });
JavaScript
0.000001
@@ -3253,16 +3253,30 @@ false %7D) +.modal('show') ;%0A%7D);%0A%0A%0A
263e0d66b54185067d1f48b491315347c17b9219
Add cookie policy link to menu (#112)
components/GlobalMenu/index.js
components/GlobalMenu/index.js
// @flow /** * Part of GDL gdl-frontend. * Copyright (C) 2018 GDL * * See LICENSE */ import React, { Fragment } from 'react'; import { withRouter } from 'next/router'; import { Trans } from '@lingui/react'; import Link from 'next/link'; import config from '../../config'; import type { Language, ReadingLevel } from '../../types'; import { fetchLanguages, fetchCategories } from '../../fetch'; import { Link as RouteLink } from '../../routes'; import { getTokenFromLocalCookie } from '../../lib/auth/token'; import Menu, { MenuItem } from '../Menu'; import CreativeCommonsLogo from './cc-logo.svg'; import LanguageMenu from '../LanguageMenu'; import CategoriesMenu from './CategoriesMenu'; type Props = {| onClose(): void, languageCode: string, router: any |}; export type Categories = { classroom_books?: Array<ReadingLevel>, library_books?: Array<ReadingLevel> }; type State = { languages: Array<Language>, categories: Categories, showLanguageMenu: boolean, showCategoriesMenu: boolean }; type Cache = {| languages: Array<Language>, categories: Categories, languageCode: ?string |}; const stateCache: Cache = { languages: [], categories: {}, languageCode: null }; class GlobalMenu extends React.Component<Props, State> { constructor(props: Props) { super(props); if (stateCache.language && stateCache.languageCode === props.languageCode) { this.state = { languages: stateCache.languages, categories: stateCache.categories, showLanguageMenu: false, showCategoriesMenu: false }; } else { this.state = { languages: [], categories: {}, showLanguageMenu: false, showCategoriesMenu: false }; } } componentDidMount() { // Only fetch if we haven't already set stuff from the cache in the constructor if (this.state.languages.length === 0) { this.getMenuData(); } // Remember the last language we mounted with in the cache stateCache.languageCode = this.props.languageCode; } componentWillReceiveProps(nextProps) { if (this.props.router !== nextProps.router) { nextProps.onClose(); } } /** * When unmounting, we keep the langauge and level results so we won't have to refetch it on a different page if the langauge is the same */ componentWillUnmount() { stateCache.languages = this.state.languages; stateCache.categories = this.state.categories; } getMenuData = async () => { const [languagesRes, categoriesRes] = await Promise.all([ fetchLanguages(), fetchCategories(this.props.languageCode) ]); // TODO: Handle error case by notifying user? if (languagesRes.isOk && categoriesRes.isOk) { this.setState({ categories: categoriesRes.data, languages: languagesRes.data }); } }; toggleShowLanguageMenu = () => this.setState(state => ({ showLanguageMenu: !state.showLanguageMenu })); toggleShowCategoriesMenu = () => this.setState(state => ({ showCategoriesMenu: !state.showCategoriesMenu })); render() { const { languageCode, onClose } = this.props; return ( <Fragment> {this.state.showLanguageMenu && ( <LanguageMenu isNestedMenu selectedLanguageCode={languageCode} languages={this.state.languages} onClose={this.toggleShowLanguageMenu} /> )} {this.state.showCategoriesMenu && ( <CategoriesMenu languageCode={languageCode} categories={this.state.categories} onClose={this.toggleShowCategoriesMenu} /> )} <Menu heading={<Trans>Menu</Trans>} onClose={onClose} hasOpenNestedMenu={ this.state.showCategoriesMenu || this.state.showLanguageMenu } > <MenuItem showKeyLine hasNestedMenu onClick={this.toggleShowLanguageMenu} > <Trans>Book language</Trans> </MenuItem> <MenuItem showKeyLine hasNestedMenu onClick={this.toggleShowCategoriesMenu} > <Trans>Categories</Trans> </MenuItem> {config.TRANSLATION_PAGES && ( <Fragment> {getTokenFromLocalCookie() == null ? ( <Link passHref href="/auth/sign-in"> <MenuItem> <Trans>Log in</Trans> </MenuItem> </Link> ) : ( <Link passHref href="/auth/sign-off"> <MenuItem> <Trans>Log out</Trans> </MenuItem> </Link> )} <RouteLink passHref route="translations"> <MenuItem> <Trans>My translations</Trans> </MenuItem> </RouteLink> </Fragment> )} <MenuItem href="https://home.digitallibrary.io/about/"> <Trans>About Global Digital Library</Trans> </MenuItem> <MenuItem href="https://blog.digitallibrary.io/cc/"> <Trans>Licensing and reuse</Trans> </MenuItem> <MenuItem href={config.zendeskUrl}> <Trans>Report issues</Trans> </MenuItem> <MenuItem> <CreativeCommonsLogo aria-label="Creative Commons" style={{ width: '25%' }} /> </MenuItem> </Menu> </Fragment> ); } } export default withRouter(GlobalMenu);
JavaScript
0
@@ -5266,32 +5266,195 @@ %3C/MenuItem%3E%0A + %3CMenuItem href=%22https://home.digitallibrary.io/the-global-digital-library-uses-cookies/%22%3E%0A %3CTrans%3ECookie policy%3C/Trans%3E%0A %3C/MenuItem%3E%0A %3CMenuI
73372fbc0dba9520484c94550e4519977ad0070d
Update characteristic.js
RC/ble/characteristic.js
RC/ble/characteristic.js
var util = require('util'); var bleno = require('bleno'); var redis = require("redis"); var BlenoCharacteristic = bleno.Characteristic; var DBCCharacteristic = function() { EchoCharacteristic.super_.call(this, { uuid: 'ac5636ee-3d36-4afe-9662-ec47fbfe1dd0', properties: ['read', 'write', 'notify'], value: null }); this._value = new Buffer(0); this._updateValueCallback = null; }; util.inherits(DBCCharacteristic, BlenoCharacteristic); DBCCharacteristic.prototype.onReadRequest = function(offset, callback) { console.log('EchoCharacteristic - onReadRequest: value = ' + this._value.toString('hex')); callback(this.RESULT_SUCCESS, this._value); }; DBCCharacteristic.prototype.onWriteRequest = function(data, offset, withoutResponse, callback) { this._value = data; //console.log('EchoCharacteristic - onWriteRequest: value = ' + this._value.toString('hex')); console.log('EchoCharacteristic - onWriteRequest: value = ' + this._value); client.send(this._value, 0, this._value.length, 41234, "localhost"); if (this._updateValueCallback) { console.log('EchoCharacteristic - onWriteRequest: notifying'); this._updateValueCallback(this._value); } callback(this.RESULT_SUCCESS); }; DBCCharacteristic.prototype.onSubscribe = function(maxValueSize, updateValueCallback) { console.log('EchoCharacteristic - onSubscribe'); this._updateValueCallback = updateValueCallback; }; DBCCharacteristic.prototype.onUnsubscribe = function() { console.log('EchoCharacteristic - onUnsubscribe'); this._updateValueCallback = null; }; module.exports = DBCCharacteristic;
JavaScript
0.000001
@@ -132,16 +132,75 @@ istic;%0A%0A +var characterID = '9a10ba1d-cd1c-4f00-9cca-1f3178d5fe8a';%0A%0A var DBCC @@ -230,20 +230,19 @@ n() %7B%0A -Echo +DBC Characte @@ -282,46 +282,19 @@ id: -'ac5636ee-3d36-4afe-9662-ec47fbfe1dd0' +characterID ,%0A @@ -566,36 +566,35 @@ %0A console.log(' -Echo +DBC Characteristic - @@ -831,36 +831,35 @@ //console.log(' -Echo +DBC Characteristic - @@ -924,36 +924,35 @@ %0A console.log(' -Echo +DBC Characteristic - @@ -1109,36 +1109,35 @@ console.log(' -Echo +DBC Characteristic - @@ -1348,36 +1348,35 @@ %0A console.log(' -Echo +DBC Characteristic - @@ -1523,12 +1523,11 @@ og(' -Echo +DBC Char
78bca165ffd99ba50f04369f314f7baeb54e05fe
update views for Crunch Lab user and capability selection
src/foam/u2/crunch/lab/CrunchLab.js
src/foam/u2/crunch/lab/CrunchLab.js
/** * @license * Copyright 2020 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.u2.crunch', name: 'CrunchLab', extends: 'foam.u2.Controller', implements: [ 'foam.mlang.Expressions' ], css: ` ^ svg { height: calc(100% - 40px); /* temp */ } `, imports: [ 'userCapabilityJunctionDAO' ], requires: [ 'foam.graph.GraphBuilder', 'foam.nanos.crunch.UserCapabilityJunction', 'foam.u2.svg.graph.RelationshipGridPlacementStrategy', 'foam.u2.svg.graph.IdPropertyPlacementPlanDecorator', 'foam.u2.svg.TreeGraph', 'foam.u2.Tab', 'foam.u2.Tabs' ], messages: [ { name: 'ALL_TAB', message: 'All Capabilities' }, { name: 'UCJ_TAB', message: 'User-Capability Junction' }, ], properties: [ { name: 'rootCapability', class: 'Reference', of: 'foam.nanos.crunch.Capability' }, { name: 'crunchUser', class: 'Reference', of: 'foam.nanos.auth.User' }, { name: 'relation', class: 'String', value: 'prerequisites' } ], methods: [ function initE() { var self = this; this .addClass(this.myClass()) .start(this.Tabs) .start(this.Tab, { label: this.ALL_TAB, selected: true, }) .add(this.ROOT_CAPABILITY) .add(this.getGraphSlot()) .end() .start(this.Tab, { label: this.UCJ_TAB, }) .add(this.ROOT_CAPABILITY) .add(this.CRUNCH_USER) .add(this.getGraphSlot(true)) .end() .end() ; }, function getGraphSlot(replaceWithUCJ) { var self = this; return this.slot(function (rootCapability, crunchUser, relation) { if ( ! rootCapability ) return this.E(); var graphBuilder = self.GraphBuilder.create(); // Having these variables here makes promise returns cleaner var rootCapabilityObj = null; var placementPlan = null; var graph = null; return self.rootCapability$find .then(o => { rootCapabilityObj = o; return graphBuilder.fromRelationship(o, self.relation) }) .then(() => { graph = graphBuilder.build(); return self.RelationshipGridPlacementStrategy.create({ graph: graph, }).getPlan(); }) .then(placementPlan_ => { placementPlan = placementPlan_; if ( replaceWithUCJ ) { capabilityIds = Object.keys(graph.data); return self.userCapabilityJunctionDAO.where(self.AND( self.IN(self.UserCapabilityJunction.TARGET_ID, capabilityIds), self.EQ(self.UserCapabilityJunction.SOURCE_ID, crunchUser) )).select().then(r => { r.array.forEach(ucj => { console.log('replacing', ucj.targetId, ucj); let capability = graph.data[ucj.targetId].data; graph.data[ucj.targetId].data = [ capability, ucj ]; }) }) } }) .then(() => { placementPlan = this.IdPropertyPlacementPlanDecorator.create({ delegate: placementPlan, targetProperty: 'id' }); return this.E() .tag(self.TreeGraph, { nodePlacementPlan: placementPlan, graph: graph, size: 200, nodeView: 'foam.u2.crunch.lab.CapabilityGraphNodeView' // nodeView: 'foam.u2.svg.graph.ZoomedOutFObjectGraphNodeView' }) ; }) }); } ], });
JavaScript
0
@@ -336,16 +336,93 @@ /%0A %7D%0A + %5E .foam-u2-view-RichChoiceView-selection-view %7B%0A width: 30vw;%0A %7D%0A %60,%0A%0A @@ -1011,106 +1011,641 @@ ity' -%0A %7D,%0A %7B%0A name: 'crunchUser',%0A class: 'Reference',%0A of: 'foam.nanos.auth.User' +,%0A view: function(_, X) %7B%0A return %7B%0A class: 'foam.u2.view.RichChoiceView',%0A search: true,%0A sections: %5B%0A %7B%0A heading: 'Services',%0A dao: X.capabilityDAO%0A %7D%0A %5D%0A %7D;%0A %7D%0A %7D,%0A %7B%0A name: 'crunchUser',%0A class: 'Reference',%0A of: 'foam.nanos.auth.User',%0A view: function(_, X) %7B%0A return %7B%0A class: 'foam.u2.view.RichChoiceView',%0A search: true,%0A sections: %5B%0A %7B%0A heading: 'Services',%0A dao: X.userDAO%0A %7D%0A %5D%0A %7D;%0A %7D, %0A
e9e9987070099eeff6614316675596cfeabdf42b
fix month issue
lib/entities/banktransaction.js
lib/entities/banktransaction.js
var _ = require('lodash') , Entity = require('./entity') , logger = require('../logger') , ContactSchema = require('./contact').ContactSchema , Contact = require('./contact') , LineItemSchema = require('./shared').LineItemSchema var BankTransactionSchema = new Entity.SchemaObject({ Contact: { type: ContactSchema , toObject: 'always'}, Date: {type: Date, toObject: 'always'}, LineAmountTypes: {type: String, toObject: 'always'}, LineItems: {type: Array, arrayType: LineItemSchema, toObject: 'always'}, SubTotal: {type: Number}, TotalTax: {type: Number}, Total: {type: Number}, UpdatedDateUTC: {type: Date}, FullyPaidOnDate: {type: Date}, BankTransactionID: {type: String}, IsReconciled: {type: Boolean, toObject: 'always'}, CurrencyCode: {type: String, toObject: 'always'}, Url: {type: String, toObject: 'always'}, Reference: {type: String, toObject: 'always'}, BankAccount: { type: { AccountID: {type: String, toObject: 'always'} }, toObject: 'always'}, Type: {type: String, toObject: 'always'} }); var BankTransaction = Entity.extend(BankTransactionSchema, { constructor: function (application, data, options) { logger.debug('BankTransaction::constructor'); this.Entity.apply(this, arguments); }, initialize: function (data, options) { }, changes: function (options) { return this._super(options); }, _toObject: function (options) { return this._super(options); }, fromXmlObj: function (obj) { var self = this; _.extend(self, _.omit(obj, 'LineItems','Contact')); if (obj.LineItems) { var lineItems = this.application.asArray(obj.LineItems.LineItem); _.each(lineItems, function (lineItem) { self.LineItems.push(lineItem); }) } if (obj.Contact) _.extend(self.Contact, new Contact().fromXmlObj(obj.Contact)) return this; }, toXml: function () { var transaction = _.omit(this.toObject(),'Contact','LineItems'); transaction.BankAccount = this.BankAccount.toObject(); transaction.Date = this.Date.getFullYear()+'-'+this.Date.getMonth()+'-'+this.Date.getDate(); transaction.Contact = this.Contact.toObject(); transaction.LineItems = []; this.LineItems.forEach(function (lineItem){ transaction.LineItems.push({LineItem: lineItem.toObject()}); }); return this.application.js2xml(transaction, 'BankTransaction'); }, save:function(cb) { var xml = '<BankTransactions>' + this.toXml() + '</BankTransactions>'; //console.log(xml); //cb(); return this.application.putOrPostEntity('put', 'BankTransactions', xml, {}, cb); } }); module.exports = BankTransaction;
JavaScript
0.000001
@@ -2273,24 +2273,25 @@ lYear()+'-'+ +( this.Date.ge @@ -2299,16 +2299,19 @@ Month()+ +1)+ '-'+this
65695cf8b0356d5f290ba75d2830e0998368ead2
add missing type field
components/SentenTree/index.js
components/SentenTree/index.js
import { select } from 'd3-selection'; import VisComponent from '../../VisComponent'; import { SentenTreeBuilder, SentenTreeVis } from 'sententree/dist/SentenTree'; export default class SentenTree extends VisComponent { static get options () { return [ { name: 'data', description: 'The data table.', type: 'table', format: 'objectlist' }, { name: 'id', description: 'The field containing the identifier of each row.', type: 'string', domain: { mode: 'field', from: 'data', fieldTypes: ['string', 'integer', 'number'] } }, { name: 'text', description: 'The field containing the text sample.', domain: { mode: 'field', from: 'data', fieldTypes: ['string'] } }, { name: 'count', description: 'The field containing the count for each text sample.', type: 'string', domain: { mode: 'field', from: 'data', fieldTypes: ['integer'] } }, { name: 'graphs', description: 'The number of graphs to compute and render.', type: 'integer', format: 'integer', default: 3 } ]; } constructor (el, {data, id = null, text = 'text', count = 'count', graphs = 3}) { super(el); // Empty element. select(el) .selectAll('*') .remove(); // Transform input data into correct form. this.data = data.map((d, i) => ({ id: id ? d[id] : i, text: d[text], count: d[count] !== undefined ? d[count] : 1 })); const model = new SentenTreeBuilder() .buildModel(this.data); this.vis = new SentenTreeVis(el) .data(model.getRenderedGraphs(graphs)); } render () {} }
JavaScript
0.000001
@@ -743,32 +743,56 @@ text sample.',%0A + type: 'string',%0A domain:
096063db0de5ce44725c8ec10993af3521b7f3d2
Add update to dataTableStyles for more verbose styling
src/globalStyles/dataTableStyles.js
src/globalStyles/dataTableStyles.js
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import { Dimensions } from 'react-native'; import { BACKGROUND_COLOR, BLUE_WHITE, LIGHT_GREY, WARM_GREY, DARK_GREY, SUSSOL_ORANGE, } from './colors'; import { APP_FONT_FAMILY } from './fonts'; export const dataTableColors = { checkableCellDisabled: LIGHT_GREY, checkableCellChecked: SUSSOL_ORANGE, checkableCellUnchecked: WARM_GREY, editableCellUnderline: WARM_GREY, }; export const dataTableStyles = { text: { fontFamily: APP_FONT_FAMILY, fontSize: Dimensions.get('window').width / 100, color: DARK_GREY, }, header: { backgroundColor: 'white', }, headerCell: { height: 40, borderRightWidth: 2, borderBottomWidth: 2, backgroundColor: 'white', borderColor: BLUE_WHITE, }, row: { backgroundColor: BACKGROUND_COLOR, }, expansion: { padding: 15, borderTopWidth: 2, borderBottomWidth: 2, borderColor: BLUE_WHITE, }, expansionWithInnerPage: { padding: 2, paddingBottom: 5, borderTopWidth: 2, borderBottomWidth: 2, borderColor: BLUE_WHITE, }, cell: { borderRightWidth: 2, borderColor: BLUE_WHITE, }, rightMostCell: { borderRightWidth: 0, }, checkableCell: { justifyContent: 'center', alignItems: 'center', }, button: { alignItems: 'center', justifyContent: 'center', height: 30, borderWidth: 1, borderRadius: 4, padding: 15, margin: 5, borderColor: SUSSOL_ORANGE, }, };
JavaScript
0
@@ -650,16 +650,42 @@ white',%0A + flexDirection: 'row',%0A %7D,%0A h @@ -829,57 +829,309 @@ ,%0A -%7D,%0A row: %7B%0A backgroundColor: BACKGROUND_COLOR + flexDirection: 'row',%0A alignItems: 'center',%0A justifyContent: 'space-between',%0A %7D,%0A row: %7B%0A backgroundColor: BACKGROUND_COLOR,%0A flex: 1,%0A flexDirection: 'row',%0A height: 45,%0A %7D,%0A alternateRow: %7B%0A backgroundColor: 'white',%0A flex: 1,%0A flexDirection: 'row',%0A height: 45 ,%0A @@ -1457,24 +1457,67 @@ BLUE_WHITE,%0A + flex: 1,%0A justifyContent: 'center',%0A %7D,%0A right @@ -1832,11 +1832,1504 @@ E,%0A %7D,%0A + cellContainer: %7B%0A left: %7B%0A borderRightWidth: 2,%0A borderColor: '#ecf3fc',%0A flex: 1,%0A justifyContent: 'center',%0A %7D,%0A right: %7B%0A borderRightWidth: 2,%0A borderColor: '#ecf3fc',%0A flex: 1,%0A justifyContent: 'center',%0A %7D,%0A center: %7B borderRightWidth: 2, borderColor: '#ecf3fc', flex: 1, justifyContent: 'center' %7D,%0A %7D,%0A cellText: %7B%0A left: %7B%0A marginLeft: 20,%0A textAlign: 'left',%0A fontFamily: APP_FONT_FAMILY,%0A fontSize: Dimensions.get('window').width / 100,%0A color: DARK_GREY,%0A %7D,%0A right: %7B%0A marginRight: 20,%0A textAlign: 'right',%0A fontFamily: APP_FONT_FAMILY,%0A fontSize: Dimensions.get('window').width / 100,%0A color: DARK_GREY,%0A %7D,%0A center: %7B%0A textAlign: 'center',%0A fontFamily: APP_FONT_FAMILY,%0A fontSize: Dimensions.get('window').width / 100,%0A color: DARK_GREY,%0A %7D,%0A %7D,%0A touchableCellContainer: %7B%0A borderRightWidth: 2,%0A borderColor: '#ecf3fc',%0A flex: 1,%0A alignItems: 'center',%0A justifyContent: 'center',%0A %7D,%0A editableCellTextView: %7B%0A borderBottomColor: '#cbcbcb',%0A borderBottomWidth: 1,%0A flex: 1,%0A flexDirection: 'row',%0A width: '88%25',%0A maxHeight: '65%25',%0A justifyContent: 'center',%0A alignItems: 'center',%0A alignSelf: 'center',%0A marginRight: 20,%0A %7D,%0A editableCellText: %7B%0A textAlign: 'right',%0A fontFamily: APP_FONT_FAMILY,%0A fontSize: Dimensions.get('window').width / 100,%0A color: DARK_GREY,%0A %7D,%0A %7D;%0A
5416fc7e98d1cfc1fe841536c363433807f7f602
load results sooner
ReleaseDisplay/js/app.js
ReleaseDisplay/js/app.js
function moreHeadlines(strAPI) { "use strict"; //Call StellBioTech NewsRelease $.getJSON(strAPI, function (pressReleases) { pressReleases.news.forEach(function (headline) { var $panel = $('<div class="panel panel-default">'), $h2 = $("<h2>"), $p = $("<p>"); $panel.hide(); $h2.text(headline.title); $p.text(headline.published); $panel.append($h2); $panel.append($p); $(".releases").append($panel); $panel.fadeIn(); }); }); } var main = function () { "use strict"; //control api output with limit & offset var limit = 10, offset = 0, didScroll = false, $win = $(window), url = "http://www.stellarbiotechnologies.com/media/press-releases/json?limit=" + limit.toString() + "&offset=" + offset.toString(); moreHeadlines(url); //on end of document, load more headlines $win.scroll(function () { didScroll = true; }); setInterval(function() { //check if near end of dom if ( didScroll ) { didScroll = false; if ($win.scrollTop() + $win.height() > $(document).height() - 200) { offset += 10; limit = 10; url = "http://www.stellarbiotechnologies.com/media/press-releases/json?limit=" + limit.toString() + "&offset=" + offset.toString(); //request more headlines at new offset moreHeadlines(url); } } //end if }, 100); }; $(document).ready(main);
JavaScript
0
@@ -1261,17 +1261,17 @@ ght() - -2 +5 00) %7B%0A
d82cd9b7bd03708f4940b4508acd0394713b8869
fix post order when new posts appear between loading index and expanding
js/expand.js
js/expand.js
/* *expand.js * https://github.com/savetheinternet/Tinyboard/blob/master/js/expand.js * * Released under the MIT license * Copyright (c) 2012 Michael Save <[email protected]> * * Usage: * $config['additional_javascript'][] = 'js/jquery.min.js'; * $config['additional_javascript'][] = 'js/expand.js'; * */ $(document).ready(function(){ if($('div.banner').length != 0) return; // not index $('div.post.op span.omitted').each(function() { $(this) .html($(this).text().replace(/Click reply to view\./, '<a href="javascript:void(0)">Click to expand</a>.')) .find('a').click(function() { var thread = $(this).parent().parent().parent(); var id = thread.attr('id').replace(/^thread_/, ''); $.ajax({ url: thread.find('p.intro a.post_no:first').attr('href'), context: document.body, success: function(data) { var last_expanded = false; $(data).find('div.post.reply').each(function() { if(thread.find('#' + $(this).attr('id')).length == 0) { if(last_expanded) { $(this).addClass('expanded').insertAfter(last_expanded).before('<br class="expanded">'); } else { $(this).addClass('expanded').insertAfter(thread.find('div.post:first')).after('<br class="expanded">'); } last_expanded = $(this); } }); $('<span class="omitted"><a href="javascript:void(0)">Hide expanded replies</a>.</span>') .insertAfter(thread.find('span.omitted').css('display', 'none')) .click(function() { thread.find('.expanded').remove(); $(this).prev().css('display', ''); $(this).remove(); }); } }); }); }); });
JavaScript
0
@@ -957,19 +957,34 @@ %0A%09%09%09%09%09%09%09 -if( +var post_in_doc = thread.f @@ -1012,16 +1012,39 @@ r('id')) +;%0A%09%09%09%09%09%09%09if(post_in_doc .length @@ -1364,24 +1364,84 @@ %09%09%0A%09%09%09%09%09%09%09%7D%0A +%09%09%09%09%09%09%09else %7B%0A%09%09%09%09%09%09%09%09last_expanded = post_in_doc;%0A%09%09%09%09%09%09%09%7D%0A %09%09%09%09%09%09%7D);%0A%09%09
9a3dc17fae2b4806402c54fd28b78e796a2c92a0
Update spec/unit/BridgedClient.spec.js
spec/unit/BridgedClient.spec.js
spec/unit/BridgedClient.spec.js
"use strict"; const { BridgedClient, BridgedClientStatus } = require("../../lib/irc/BridgedClient.js"); const STATE_DISC = { status: BridgedClientStatus.DISCONNECTED } const STATE_CONN = { status: BridgedClientStatus.CONNECTED, client: {} } const STATE_CONN_MAX5 = { status: BridgedClientStatus.CONNECTED, client: { supported: { nicklength: 5 } } } describe("BridgedClient", function() { describe("getValidNick", function() { it("should not change a valid nick", function() { expect(BridgedClient.getValidNick("foobar", true, STATE_DISC)).toBe("foobar"); }); it("should remove invalid characters", function() { expect(BridgedClient.getValidNick("f+/\u3052oobar", false, STATE_DISC)).toBe("foobar"); }); it("nick must start with letter of special character", function() { expect(BridgedClient.getValidNick("foo-bar", false, STATE_DISC)).toBe("foo-bar"); expect(BridgedClient.getValidNick("[foobar]", false, STATE_DISC)).toBe("[foobar]"); expect(BridgedClient.getValidNick("{foobar}", false, STATE_DISC)).toBe("{foobar}"); expect(BridgedClient.getValidNick("-foobar", false, STATE_DISC)).toBe("M-foobar"); expect(BridgedClient.getValidNick("12345", false, STATE_DISC)).toBe("M12345"); }); it("throw if nick invalid", function() { expect(() => BridgedClient.getValidNick("f+/\u3052oobar", true, STATE_DISC)).toThrowError(); expect(() => BridgedClient.getValidNick("a".repeat(20), true, STATE_CONN)).toThrowError(); expect(() => BridgedClient.getValidNick("-foobar", true, STATE_CONN)).toThrowError(); }); it("don't truncate nick if disconnected", function() { expect(BridgedClient.getValidNick("a".repeat(20), false, STATE_DISC)).toBe("a".repeat(20)); }); it("truncate nick", function() { expect(BridgedClient.getValidNick("a".repeat(20), false, STATE_CONN)).toBe("a".repeat(9)); }); it("truncate nick with custom max", function() { expect(BridgedClient.getValidNick("a".repeat(20), false, STATE_CONN_MAX5)).toBe("a".repeat(5)); }); }); });
JavaScript
0
@@ -828,16 +828,28 @@ it(%22 -nick mus +will allow nicks tha t st @@ -861,17 +861,9 @@ ith -letter of +a spe
79f55be52a77d67f4daf63bcfb83f1c6795966c1
Handle secondary commands when creating the keyboardControlMap in popup
src/core/pages/popup/event-callbacks.js
src/core/pages/popup/event-callbacks.js
/* Main DOM event-handlers */ import keyboard, { TAB_NEXT } from 'core/keyboard'; import { injectTabsInList, addHeadTabListNodeSelectedStyle, } from './utils/dom'; import { navigateResults } from './utils/keyboard'; import { switchActiveTab, restoreClosedTab, deleteTab, openBookmark, openHistoryItem, } from './utils/browser'; import { deleteButton, searchInput, tabList, SESSION_TYPE, HISTORY_TYPE, BOOKMARK_TYPE, TAB_TYPE, OTHER_WINDOW_TAB_TYPE, TAB_DELETE_BTN_CLASSNAME, } from './constants'; import { updateLastQuery } from './actions'; import filterResults from './search'; export function configureSearch(store) { const { getState, tabQueryPromise, currentWindowId } = store; const { fuzzy, general } = getState(); return function updateSearchResults(event = { currentTarget: { value: '' } }) { const isSearchEmpty = event.currentTarget.value.length === 0; // If input is empty hide the button if (isSearchEmpty) { deleteButton.classList.add('hidden'); } else { deleteButton.classList.remove('hidden'); } // isSearchEmpty isn't based on this var so we can show delete button with // just spaces const query = event.currentTarget.value.trim().toLowerCase(); return Promise.resolve(tabQueryPromise()) .then(filterResults(query, fuzzy, general, currentWindowId)) .then(injectTabsInList(getState)) .then((results) => { // Apply the selected style to the head of the tabList to suggest // pressing <Enter> from the search input activates this tab if (results.length > 0 && !isSearchEmpty) { addHeadTabListNodeSelectedStyle(); // Scroll to the top tabList.firstElementChild.scrollIntoView(true); } return results; }); }; } export function clearInput(event) { event.target.value = ''; tabList.childNodes[0].focus(); } // Given an object returns a Map with the keys and values swapped function swapKeyValueMap(obj, func = x => x) { return Object.keys(obj) .reduce((acc, key) => acc.set(func(obj[key]), key), new Map()); } function isModifierSingle(event) { const modifiers = [ 'Control', 'Ctrl', 'Alt', 'Shift', 'Meta', 'Shift', ]; return modifiers.some(m => event.key === m); } export function keydownHandler(store) { const { keyboard: keyboardControls } = store.getState(); // The keyboard object is an object with the mapping { [ACTION]: kbdcommand } // Mirror the keys and values so we have a Map: // {[kbdCommand]: ACTION} const kbdControlMap = swapKeyValueMap(keyboardControls, x => x.command); return function handleKeyDown(event) { if (isModifierSingle(event)) { event.preventDefault(); } // Handle preventing default // Delete, Backspace, Tab, ArrowUp, Arrowdown, Enter switch (event.key) { case 'Tab': // // Change it so tab no longer focuses the entire popup window // // and behaves like a TAB_NEXT command // // This could break the tab-fix if the popup focus bug occurs // // so remove this if someone complains // case 'ArrowUp': case 'ArrowDown': case 'Enter': event.preventDefault(); break; default: break; } if (keyboard.isValid(event)) { const cmd = keyboard.command(event); const key = [...kbdControlMap.keys()].find(x => keyboard.isEqual(x, cmd)); return navigateResults(kbdControlMap.get(key), store.getState); } if (event.key === 'Tab') { return navigateResults(TAB_NEXT, store.getState); } const shouldJustFocusSearchBar = (event.key === 'Backspace' && !isModifierSingle(event)) || (/^([A-Za-z]|\d)$/.test(event.key) && !isModifierSingle(event)); if (shouldJustFocusSearchBar) { searchInput.focus(); } return noop(); }; } function noop() {} export function handleTabClick(getState) { return function doHandleTabClick(event) { const generalSettings = getState().general; const { currentTarget, ctrlKey, target } = event; if (target.nodeName === 'IMG' && target.classList.contains(TAB_DELETE_BTN_CLASSNAME)) { return deleteTab(currentTarget, generalSettings, true); } const { dataset } = currentTarget; const { type } = dataset; // Decide what to do depending if ctrl is held switch (type) { case OTHER_WINDOW_TAB_TYPE: case TAB_TYPE: { if (ctrlKey) { return deleteTab(currentTarget, generalSettings, true); } return switchActiveTab(dataset); } case SESSION_TYPE: { if (ctrlKey) { return noop(); } return restoreClosedTab(dataset); } case BOOKMARK_TYPE: { if (ctrlKey) { return noop(); } return openBookmark(dataset); } case HISTORY_TYPE: { if (ctrlKey) { return noop(); } return openHistoryItem(dataset); } default: return noop(); } }; } export function updateLastQueryOnKeydown(store) { const { dispatch } = store; return (event) => { const { value } = event.currentTarget; dispatch(updateLastQuery(value.trim())); }; }
JavaScript
0
@@ -1900,16 +1900,327 @@ s();%0A%7D%0A%0A +// Merges maps into the one specified in target%0Afunction mapAssign(target, ...sources) %7B%0A return sources.reduce(%0A (acc, map) =%3E %7B%0A // eslint-disable-next-line no-restricted-syntax%0A for (const %5Bkey, value%5D of map) %7B%0A acc.set(key, value);%0A %7D%0A return acc;%0A %7D,%0A target,%0A );%0A%7D%0A%0A // Given @@ -2308,19 +2308,16 @@ p(obj, f -unc = x =%3E @@ -2359,16 +2359,23 @@ .reduce( +%0A (acc, ke @@ -2379,16 +2379,31 @@ key) =%3E + (f(obj%5Bkey%5D) ? acc.set @@ -2404,19 +2404,16 @@ cc.set(f -unc (obj%5Bkey @@ -2420,17 +2420,30 @@ %5D), key) -, + : acc),%0A new Map @@ -2444,16 +2444,22 @@ ew Map() +,%0A );%0A%7D%0A%0Afu @@ -2924,16 +2924,31 @@ rolMap = + mapAssign(%0A swapKey @@ -2988,16 +2988,85 @@ .command +),%0A swapKeyValueMap(keyboardControls, x =%3E x.secondaryCommand),%0A );%0A ret
6ddd8d83c51ef1610f334e856ae3dc9551142643
Noting event that should be emitted
src/core/pipelines/pipeline-executor.js
src/core/pipelines/pipeline-executor.js
'use strict' let connection = require('../../db/connection') let logger = require('tracer').colorConsole() let extensionRegistry = require('../../extensions/registry') let Stage = require('./stage').Stage /** * @prop {int|string} executionId * @prop {object} execution * @prop {object} config * @prop {object} config.pipeline * @prop {array} config.stages */ class PipelineExecutor { /** * Set up and fulfill a pipeline execution * * @param {int|string} pipelineExecutionId * @param {function} callback A callback to be called when the execution process is complete */ constructor(pipelineExecutionId, callback) { this.executionId = pipelineExecutionId // Assume no stage has failed until we find out otherwise this.anyStageHasFailed = false this.loadPipelineExecution() .then(this.markPipelineExecutionAsRunning.bind(this)) .then(this.executeStages.bind(this)) .then(this.markPipelineAsComplete.bind(this)) .then( // Mark the queue job as complete, and move onto the next callback() ) } /** * Load the pipeline execution data * * @returns {Promise} */ loadPipelineExecution() { return connection.first() .where('id', this.executionId) .from('pipeline_executions') .catch(err => logger.error(err)) .then((execution) => { this.execution = execution this.config = JSON.parse(execution.config_snapshot) }) } /** * Mark the pipeline execution as running * * @returns {Promise} */ markPipelineExecutionAsRunning() { return connection('pipeline_executions') .where('id', this.executionId) .update({ status: 'running', started_at: new Date(), updated_at: new Date() }).catch(err => logger.error(err)) } /** * Executes the stages of the pipeline * * @returns {Promise} */ executeStages() { return new Promise(resolve => { // TODO: emit event for pipeline_execution update // Clone the stages, so we can pick them off one at a time this.stagesRemaining = this.config.stages.slice(0) this.runNextStage(() => { resolve() }) }) } runNextStage(callback) { if (this.stagesRemaining.length > 0) { let stageConfig = this.stagesRemaining.shift() if (this.anyStageHasFailed) { // TODO: allow for option to "run step even if a previous step has failed" this.createStageAsSkipped(stageConfig.id, () => { this.runNextStage(callback) }) } else { this.createStageAsStarted(stageConfig.id, () => { this.executeStage(stageConfig, () => { this.runNextStage(callback) }) }) } } else { callback() } } executeStage(stageConfig, onComplete) { let successCallback = () => { connection('pipeline_stage_executions') .where('pipeline_execution_id', this.executionId) .where('stage_config_id', stageConfig.id) .update({ status: 'succeeded', finished_at: new Date(), updated_at: new Date() }) .then(() => { onComplete() }) } let failureCallback = () => { this.anyStageHasFailed = true connection('pipeline_stage_executions') .where('pipeline_execution_id', this.executionId) .where('stage_config_id', stageConfig.id) .update({ status: 'failed', finished_at: new Date(), updated_at: new Date() }) .then(() => { onComplete() }) onComplete() } // state we pass must contain, stage options, pipeline variables, etc let stage = new Stage(successCallback, failureCallback) // TODO: pass state // stage.type == 'mc.basics.stages.pause_execution_for_x_seconds' //extensionRegistry.getStageType(stageConfig.type).execute(stage) let fakeStageType = { execute: function(stage) { stage.log('Starting pause for 2 seconds') setTimeout(() => { stage.log('Completed pause for 2 seconds') stage.succeed() }, 2000) } } try { fakeStageType.execute(stage) } catch (err) { stage.fail() } } /** * Record that a stage was started * * @param stageConfigId * @param callback */ createStageAsStarted(stageConfigId, callback) { connection('pipeline_stage_executions') .insert({ pipeline_execution_id: this.executionId, stage_config_id: stageConfigId, status: 'running', created_at: new Date(), updated_at: new Date(), started_at: new Date() }).catch(err => { logger.error(err) }).then(callback) } /** * Record that a stage was skipped * * @param stageConfigId * @param callback */ createStageAsSkipped(stageConfigId, callback) { connection('pipeline_stage_executions') .insert({ pipeline_execution_id: this.executionId, stage_config_id: stageConfigId, status: 'skipped', created_at: new Date(), updated_at: new Date(), skipped_at: new Date() }).catch(err => { logger.error(err) }).then(callback) } /** * Mark the pipeline execution as complete */ markPipelineAsComplete() { let status = (this.anyStageHasFailed) ? 'failed' : 'succeeded' connection('pipeline_executions') .where('id', this.executionId) .update({ status: status, finished_at: new Date(), updated_at: new Date() }) .catch(err => logger.error(err)) .then(() => { // TODO: emit event for pipeline_execution update }) } } module.exports = PipelineExecutor
JavaScript
0.999323
@@ -2236,24 +2236,79 @@ allback) %7B%0A%0A + // TODO: emit event for pipeline_execution update%0A%0A if (this
2abce000bee32d936ce36d3440b0211fd19cc642
Add timestamp to location messages
vor-backend/app/index.js
vor-backend/app/index.js
'use strict'; const Rx = require('rx'); const Cache = require('app/cache'); const viewRoute = require('app/views/routes'); const views = require('app/views'); module.exports = function (app, router, configs, sharedConfigs) { // listen socket connections const socketConnectionSource$ = Rx.Observable.fromEvent(app.io.sockets, 'connection'); // listen socket messages const socketMessageSource$ = socketConnectionSource$ .flatMap(socket => Rx.Observable.fromEvent(socket, 'message')); // split location messages let [ deviceSource$, messageSource$ ] = socketMessageSource$ .partition(message => message.type === 'location'); // listen socket 'init' messages const socketInitSource$ = socketConnectionSource$ .flatMap(socket => Rx.Observable.fromEvent( socket, 'init', event => socket // we need socket to emit cache content only to one client ) ); // Post interface for messages // TODO: At the moment Arduinos' have limited websocket support. Remove when unnecessary. const postMessageSubject = new Rx.Subject(); const postMessageRoute = router.post('/messages', (req, res) => { try { const json = JSON.parse(req.body); postMessageSubject.onNext(json); res.send('OK'); } catch (error) { res.status(500).send(`Error: ${error}`); } }); app.use('/messages', postMessageRoute); // set up cache storage const cache = new Cache(configs.CACHE_PREFIX, configs.CACHE_TTL); // subscribe init socketInitSource$ .flatMap(socket => { return Rx.Observable.zip(Rx.Observable.return(socket), cache.getAll()); }) .subscribe( ([socket, messages]) => { socket.emit('init', { beacons: sharedConfigs.BEACONS, // send configured beacons data messages: messages }); console.log(`Server - fetched ${messages.length} messages from cache : ${new Date}`); }, error => console.error(`Error - init stream: ${error} : ${new Date}`) ); // subscribe messages postMessageSubject .merge(messageSource$) .flatMap(message => cache.store(message)) .do(message => console.log(`Server - stored ${message.type} : ${new Date}`)) .merge(deviceSource$) // merge location without storing it .subscribe( message => { app.io.emit('message', message); console.log(`Server - emit ${message.type} : ${new Date}`); }, error => console.error(`Error - message stream: ${error} : ${new Date}`) ); // the test page app.use('/', viewRoute(router)); views.renderTestPage(app); return app; };
JavaScript
0.000015
@@ -634,32 +634,155 @@ = 'location');%0A%0A + // Add timestamp to every location message.%0A deviceSource$.subscribe(message =%3E message.date = (new Date()).toJSON());%0A%0A // listen sock
0ace2f6aed942796df6c9a8b4fa1abe349bc7fd8
Fix some lint
opentreemap/treemap/js/src/mapManager.js
opentreemap/treemap/js/src/mapManager.js
"use strict"; var $ = require('jquery'), _ = require('underscore'), OL = require('OpenLayers'), makeLayerFilterable = require('./makeLayerFilterable'); exports.ZOOM_DEFAULT = 11; exports.ZOOM_PLOT = 18; exports.init = function(options) { var config = options.config, map = createMap($(options.selector)[0], config), plotLayer = createPlotTileLayer(config), allPlotsLayer = createPlotTileLayer(config), boundsLayer = createBoundsTileLayer(config), utfLayer = createPlotUTFLayer(config); allPlotsLayer.setOpacity(0.3); exports.map = map; exports.updateGeoRevHash = function(geoRevHash) { if (geoRevHash !== config.instance.rev) { config.instance.rev = geoRevHash; plotLayer.url = getPlotLayerURL(config, 'png'); allPlotsLayer.url = getPlotLayerURL(config, 'png'); utfLayer.url = getPlotLayerURL(config, 'grid.json'); plotLayer.redraw({force: true}); utfLayer.redraw({force: true}); } }; exports.setFilter = function (filter) { plotLayer.setFilter(filter); if (!allPlotsLayer.map) { map.addLayers([allPlotsLayer]); } if (_.isEmpty(filter)) { map.removeLayer(allPlotsLayer); } }; var setCenterAndZoomIn = exports.setCenterAndZoomIn = function(location, zoom) { // I could not find a documented way of getting the max // zoom level allowed by the current base layer so // I am using isValidZoomLevel to find it. while (zoom > 1 && !map.isValidZoomLevel(zoom)) { zoom -= 1; } map.setCenter(new OL.LonLat(location.x, location.y), Math.max(map.getZoom(), zoom)); }; // Bing maps uses a 1-based zoom so XYZ layers on the base map have // a zoom offset that is always one less than the map zoom: // > map.setCenter(center, 11) // > map.zoom // 12 // So this forces the tile requests to use the correct Z offset if (config.instance.basemap.type === 'bing') { plotLayer.zoomOffset = 1; utfLayer.zoomOffset = 1; } map.addLayer(plotLayer); map.addLayer(utfLayer); map.addLayer(boundsLayer); var center = options.center || config.instance.center, zoom = options.zoom || exports.ZOOM_DEFAULT; setCenterAndZoomIn(center, zoom); }; function createMap(elmt, config) { OL.ImgPath = "/static/img/"; var map = new OL.Map({ theme: null, div: elmt, projection: 'EPSG:3857', layers: getBasemapLayers(config) }); var switcher = new OL.Control.LayerSwitcher(); map.addControls([switcher]); return map; } function getBasemapLayers(config) { var layers; if (config.instance.basemap.type === 'bing') { layers = [ new OL.Layer.Bing({ name: 'Road', key: config.instance.basemap.bing_api_key, type: 'Road', isBaseLayer: true }), new OL.Layer.Bing({ name: 'Aerial', key: config.instance.basemap.bing_api_key, type: 'Aerial', isBaseLayer: true }), new OL.Layer.Bing({ name: 'Hybrid', key: config.instance.basemap.bing_api_key, type: 'AerialWithLabels', isBaseLayer: true })]; } else if (config.instance.basemap.type === 'tms') { layers = [new OL.Layer.XYZ( 'xyz', config.instance.basemap.data)]; } else { layers = [ new OL.Layer.Google( "Google Streets", {numZoomLevels: 20}), new OL.Layer.Google( "Google Hybrid", {type: google.maps.MapTypeId.HYBRID, numZoomLevels: 20}), new OL.Layer.Google( "Google Satellite", {type: google.maps.MapTypeId.SATELLITE, numZoomLevels: 22})]; } return layers; } function createPlotTileLayer(config) { var url = getPlotLayerURL(config, 'png'), layer = new OL.Layer.XYZ( 'tiles', url, { isBaseLayer: false, sphericalMercator: true, displayInLayerSwitcher: false }); makeLayerFilterable(layer, url, config.urls.filterQueryArgumentName); return layer; } function createPlotUTFLayer(config) { var url = getPlotLayerURL(config, 'grid.json'), layer = new OL.Layer.UTFGrid({ url: url, utfgridResolution: 4, displayInLayerSwitcher: false }); return layer; } // The ``url`` property of the OpenLayers XYZ layer supports a single // string or an array of strings. ``getPlotLayerURL`` looks at // ``config.tileHosts`` and returns a single string if only one host // is defined, or an array of strings if multiple hosts are defined. function getPlotLayerURL(config, extension) { var urls = [], // Using an array with a single undefined element when // ``config.tileHosts`` is falsy allows us to always // use an ``_.each`` loop to generate the url string, // simplifying the code path hosts = config.tileHosts || [undefined]; _.each(hosts, function(host) { var prefix = host ? '//' + host : ''; urls.push(prefix + '/tile/' + config.instance.rev + '/database/otm/table/treemap_plot/${z}/${x}/${y}.' + extension + '?instance_id=' + config.instance.id); }); return urls.length === 1 ? urls[0] : urls; } function createBoundsTileLayer(config) { return new OL.Layer.XYZ( 'bounds', getBoundsLayerURL(config, 'png'), { isBaseLayer: false, sphericalMercator: true, displayInLayerSwitcher: false }); } function getBoundsLayerURL(config, extension) { return '/tile/' + config.instance.rev + '/database/otm/table/treemap_boundary/${z}/${x}/${y}.' + extension + '?instance_id=' + config.instance.id; }
JavaScript
0.018536
@@ -62,24 +62,60 @@ derscore'),%0A + google = require('googlemaps'),%0A OL = req @@ -3521,16 +3521,25 @@ %7D) +%0A %5D;%0A %7D @@ -4127,16 +4127,25 @@ ls: 22%7D) +%0A %5D;%0A %7D
d601aa88189b3dfed546c196f40e3df7566a596c
Update app.js
web/app.js
web/app.js
//core libraries var express = require('express'); var http = require('http'); var path = require('path'); var connect = require('connect'); var app = express(); //this route will serve as the data api (whether it is the api itself or a proxy to one) var api = require('./routes/api'); //express configuration //Eexpress.js intended for use as data style api so we don't need jade, only going to load index html file, everything else will be handled by angular.js //app.set('views', __dirname + '/views'); //app.set('view engine', 'jade'); app.set('port', process.env.PORT || 3000); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); //make sure content is properly gzipped app.use(connect.compress()); //setup url mappings app.use('/components', express.static(__dirname + '/components')); app.use('/app', express.static(__dirname + '/app')); app.use('/json', express.static(__dirname + '/json')); app.use('/source_files', express.static(__dirname + '/source_files')); app.use(app.router); //include the routes for the internal api require('./api-setup.js').setup(app, api); app.get('*', function(req, res) { res.sendfile("index.html"); }); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
JavaScript
0.000002
@@ -578,11 +578,11 @@ %7C%7C 3 -000 +857 );%0A%0A
55822ac3a8ce0d762d38c76583b1e63dcb869397
Fix `environment.js`
tests/dummy/config/environment.js
tests/dummy/config/environment.js
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'ember-app', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created backendUrl: 'http://flexberry-ember-dummy.azurewebsites.net/odata' } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
JavaScript
0.000029
@@ -59,16 +59,79 @@ ment) %7B%0A + var backendUrl = 'https://northwindodata.azurewebsites.net';%0A var EN @@ -136,16 +136,16 @@ ENV = %7B%0A - modu @@ -522,9 +522,12 @@ ted%0A -%09 + ba @@ -540,68 +540,2043 @@ rl: -'http://flexberry-ember-dummy.azurewebsites.net/odata'%0A %7D +backendUrl,%0A%0A // It's a custom property, used to prevent duplicate backend urls in sources.%0A backendUrls: %7B%0A root: backendUrl,%0A api: backendUrl + '/odata'%0A %7D,%0A%0A // Custom property with components settings.%0A components: %7B%0A // Settings for flexberry-file component.%0A flexberryFile: %7B%0A // URL of file upload controller.%0A uploadUrl: backendUrl + '/api/File',%0A%0A // Max file size in bytes for uploading files.%0A maxUploadFileSize: null,%0A%0A // Flag: indicates whether to upload file on controllers modelPreSave event.%0A uploadOnModelPreSave: true,%0A%0A // Flag: indicates whether to show upload button or not.%0A showUploadButton: true,%0A%0A // Flag: indicates whether to show modal dialog on upload errors or not.%0A showModalDialogOnUploadError: true,%0A%0A // Flag: indicates whether to show modal dialog on download errors or not.%0A showModalDialogOnDownloadError: true,%0A %7D%0A %7D,%0A%0A // Enable flexberryAuthService.%0A flexberryAuthService: true%0A %7D%0A %7D;%0A%0A // Read more about CSP:%0A // http://www.ember-cli.com/#content-security-policy%0A // https://github.com/rwjblue/ember-cli-content-security-policy%0A // http://content-security-policy.com%0A ENV.contentSecurityPolicy = %7B%0A 'style-src': %22'self' 'unsafe-inline' https://fonts.googleapis.com%22,%0A 'font-src': %22'self' data: https://fonts.gstatic.com%22,%0A 'connect-src': %22'self' %22 + ENV.APP.backendUrls.root%0A %7D;%0A%0A // Read more about ember-i18n: https://github.com/jamesarosen/ember-i18n.%0A ENV.i18n = %7B%0A // Should be defined to avoid ember-i18n deprecations.%0A // Locale will be changed then to navigator current locale (in instance initializer).%0A defaultLocale: 'en'%0A %7D;%0A%0A // Read more about ember-moment: https://github.com/stefanpenner/ember-moment.%0A // Locale will be changed then to same as ember-i18n locale (and will be changed every time when i18n locale changes).%0A ENV.moment = %7B%0A outputFormat: 'L' %0A %7D
a7a96eba4982b7ee6c1bac4921daac913a915531
Update backend URLs
tests/dummy/config/environment.js
tests/dummy/config/environment.js
/* jshint node: true */ module.exports = function (environment) { var backendUrl = 'http://bi-vm1.cloudapp.net:12001'; if (environment === 'development-loc') { // Use `ember server --environment=development-loc` command for local backend usage. backendUrl = 'http://localhost:63138'; } if (environment === 'mssql-backend') { // Use `ember server --environment=mssql-backend` command for mssql backend usage. backendUrl = 'https://flexberry-ember-gis.azurewebsites.net'; } if (environment === 'production') { if (process.argv.indexOf('--postfix=-mssql') >= 0) { backendUrl = 'https://flexberry-ember-gis.azurewebsites.net'; } } var ENV = { repositoryName: 'ember-flexberry-gis', modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created backendUrl: backendUrl, // It's a custom property, used to prevent duplicate backend urls in sources. backendUrls: { root: backendUrl, api: backendUrl + '/odata' }, // Log service settings. log: { // Flag: indicates whether log service is enabled or not. enabled: false }, // Flag: indicates whether to use user settings service or not. useUserSettingsService: false, // Custom property with offline mode settings. offline: { dbName: 'ember-flexberry-gis-dummy', // Flag that indicates whether offline mode in application is enabled or not. offlineEnabled: false, // Flag that indicates whether to switch to offline mode when got online connection errors or not. modeSwitchOnErrorsEnabled: false, // Flag that indicates whether to sync down all work with records when online or not. // This let user to continue work without online connection. syncDownWhenOnlineEnabled: false, }, }, userSettings: { // Max opacity values for geometries maxGeometryOpacity: 0.65, maxGeometryFillOpacity: 0.2 } }; // Read more about ember-i18n: https://github.com/jamesarosen/ember-i18n. ENV.i18n = { // Should be defined to avoid ember-i18n deprecations. // Locale will be changed then to navigator current locale (in instance initializer). defaultLocale: 'en' }; // Read more about ember-moment: https://github.com/stefanpenner/ember-moment. // Locale will be changed then to same as ember-i18n locale (and will be changed every time when i18n locale changes). ENV.moment = { outputFormat: 'L' }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // Keep test console output quieter. ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { // Configure production version settings here. } // Read more about CSP: // http://www.ember-cli.com/#content-security-policy // https://github.com/rwjblue/ember-cli-content-security-policy // http://content-security-policy.com ENV.contentSecurityPolicy = { 'style-src': "'self' 'unsafe-inline' https://fonts.googleapis.com", 'font-src': "'self' data: https://fonts.gstatic.com", 'connect-src': "'self' " + ENV.APP.backendUrls.root }; // Change paths to application assets if build has been started with the following parameters: // ember build --gh-pages --brunch=<brunch-to-publish-on-gh-pages>. if (process.argv.indexOf('--gh-pages') >= 0) { var brunch; var postfix = ""; // Retrieve brunch name and postfix from process arguments. process.argv.forEach(function(value, index) { if (value.indexOf('--brunch=') >=0) { brunch=value.split('=')[1]; return; } if (value.indexOf('--postfix=') >=0) { postfix=value.split('=')[1]; return; } }); // Change base URL to force paths to application assets be relative. ENV.baseURL = '/' + ENV.repositoryName + '/' + brunch + postfix + '/'; ENV.locationType = 'hash'; } return ENV; };
JavaScript
0.000001
@@ -288,12 +288,11 @@ st:6 -3138 +500 ';%0A @@ -455,33 +455,38 @@ //flexberry- -ember-gis +gis-test-stand .azurewebsit @@ -636,17 +636,22 @@ rry- -ember-gis +gis-test-stand .azu @@ -2175,17 +2175,16 @@ ,%0A %7D, - %0A%0A us
f9ca52fbc5bf431bd81dc7991cc258ec85872546
Fix shields down crashing Brave
js/state/siteSettings.js
js/state/siteSettings.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ const Immutable = require('immutable') const urlParse = require('url').parse module.exports.braveryDefaults = (appState, appConfig) => { let defaults = {} Object.keys(appConfig.resourceNames).forEach((name) => { let value = appConfig.resourceNames[name] let enabled = appState.getIn([value, 'enabled']) defaults[value] = enabled === undefined ? appConfig[value].enabled : enabled }) let replaceAds = defaults[appConfig.resourceNames.AD_INSERTION] || false let blockAds = defaults[appConfig.resourceNames.ADBLOCK] || false let blockTracking = defaults[appConfig.resourceNames.TRACKING_PROTECTION] || false let blockCookies = defaults[appConfig.resourceNames.COOKIEBLOCK] || false defaults.adControl = 'allowAdsAndTracking' if (blockAds && replaceAds && blockTracking) { defaults.adControl = 'showBraveAds' } else if (blockAds && !replaceAds && blockTracking) { defaults.adControl = 'blockAds' } defaults.cookieControl = blockCookies ? 'block3rdPartyCookie' : 'allowAllCookies' // TODO(bridiver) this should work just like the other bravery settings let fingerprintingProtection = appState.get('settings').get('privacy.block-canvas-fingerprinting') if (typeof fingerprintingProtection !== 'boolean') { fingerprintingProtection = appConfig.defaultSettings['privacy.block-canvas-fingerprinting'] } defaults.fingerprintingProtection = fingerprintingProtection return defaults } module.exports.activeSettings = (siteSettings, appState, appConfig) => { let defaults = module.exports.braveryDefaults(appState, appConfig) let settings = {} settings.shieldsUp = (() => { if (siteSettings) { if (typeof siteSettings.get('shieldsUp') === 'boolean') { return siteSettings.get('shieldsUp') } } return true })() Object.keys(appConfig.resourceNames).forEach((resourceName) => { let name = appConfig.resourceNames[resourceName] settings[name] = (() => { if (settings.shieldsUp === false && appConfig[resourceName].shields !== false) { return false } if (siteSettings) { if (typeof siteSettings.get(name) === 'boolean') { return siteSettings.get(name) } } return defaults[name] })() }) settings.adControl = (() => { if (settings.shieldsUp === false) { return 'allowAdsAndTracking' } if (siteSettings) { if (typeof siteSettings.get('adControl') === 'string') { return siteSettings.get('adControl') } } return defaults.adControl })() settings.cookieControl = (() => { if (settings.shieldsUp === false) { return 'allowAllCookies' } if (siteSettings) { if (typeof siteSettings.get('cookieControl') === 'string') { return siteSettings.get('cookieControl') } } return defaults.cookieControl })() settings.fingerprintingProtection = (() => { if (settings.shieldsUp === false) { return false } if (siteSettings) { if (typeof siteSettings.get('fingerprintingProtection') === 'boolean') { return siteSettings.get('fingerprintingProtection') } } return defaults.fingerprintingProtection })() settings.adInsertion = { enabled: settings.adControl === 'showBraveAds', url: appConfig.adInsertion.url } return Object.assign(defaults, settings) } /** * Obtains a squashed settings object of all matching host patterns with more exact matches taking precedence * @param {Object} siteSettings - The top level app state site settings indexed by hostPattern. * @param {string} location - The current page location to get settings for. * @return {Object} A merged settings object for the specified site setting or undefined */ module.exports.getSiteSettingsForURL = (siteSettings, location) => { if (!location || !siteSettings) { return undefined } // Example: https://www.brianbondy.com:8080/projects // parsedUrl.host: www.brianbondy.com:8080 // parsedUrl.hostname: www.brianbondy.com // parsedUrl.protocol: https: // Stores all related settingObjs with the most specific ones first // They will be reduced to a single setting object. let settingObjs = [] const parsedUrl = urlParse(location) if (!parsedUrl.host || !parsedUrl.hostname || !parsedUrl.protocol) { return undefined } settingObjs.push( `${parsedUrl.protocol}//${parsedUrl.host}`, `${parsedUrl.protocol}//${parsedUrl.hostname}:*`, `${parsedUrl.protocol}//*` ) if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') { settingObjs.push(`https?://${parsedUrl.host}`, `https?://${parsedUrl.hostname}:*`) } let host = parsedUrl.host while (host.length > 0) { const parsedUrl = urlParse(location) host = host.split('.').slice(1).join('.') location = `${parsedUrl.protocol}//${host}` settingObjs.push( `${parsedUrl.protocol}//*.${parsedUrl.host}`, `${parsedUrl.protocol}//*.${parsedUrl.hostname}:*` ) if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') { settingObjs.push(`https?://*.${parsedUrl.host}`, `https?://*.${parsedUrl.hostname}:*`) } } settingObjs.push('*') settingObjs = settingObjs.map((hostPattern) => siteSettings.get(hostPattern)) // Merge all the settingObj with the more specific first rules taking precedence const settingObj = settingObjs.reduce((mergedSettingObj, settingObj) => (settingObj || Immutable.Map()).merge(mergedSettingObj), Immutable.Map()) if (settingObj.size === 0) { return undefined } return Immutable.fromJS(settingObj) } /** * Obtains the site settings stored for a specific pattern. * @param {Object} siteSettings - The top level app state site settings indexed by hostPattern. * @param {string} hostPattern - The host pattern to lookup. * Supported hostPattern values are of the form: protocol|(https[?])://[*.]<hostname>[:*] * @return {Object} The exact setting object for the specified host pattern or undefined. */ module.exports.getSiteSettingsForHostPattern = (siteSettings, hostPattern) => siteSettings.get(hostPattern) /** * Merges the settings for the specified host pattern. * @param {Object} siteSettings - The top level app state site settings indexed by hostPattern. * @param {string} hostPattern - The host pattern to merge into * @param {string} key - A setting key * @param {string|number} value - A setting value */ module.exports.mergeSiteSetting = (siteSettings, hostPattern, key, value) => (siteSettings || Immutable.Map()).mergeIn([hostPattern], { [key]: value }) /** * Remove all site settings for the specified hostPattern. * @param {Object} siteSettings - The top level app state site settings indexed by hostPattern. * @param {string} hostPattern - The host pattern to remove all settings for. */ module.exports.removeSiteSettings = (siteSettings, hostPattern) => siteSettings.delete(hostPattern) /** * Removes one site setting for the specified hostPattern. * @param {Object} siteSettings - The top level app state site settings indexed by hostPattern. * @param {string} hostPattern - The host pattern to remove all settings for. * @param {string} key - The site setting name */ module.exports.removeSiteSetting = (siteSettings, hostPattern, key) => { if (siteSettings.get(hostPattern)) { return siteSettings.set(hostPattern, siteSettings.get(hostPattern).delete(key)) } else { return siteSettings } }
JavaScript
0
@@ -2204,25 +2204,17 @@ pConfig%5B -resourceN +n ame%5D.shi
70e1e3c920ccd1a127c2ba2081afffec30f2cd8f
Remove unused utility functions
js/helper.js
js/helper.js
(function(app) { 'use strict'; var helper = {}; helper.encodePath = function(str) { return str.split('/').map(function(s) { return encodeURIComponent(s); }).join('/'); }; helper.clamp = function(number, lower, upper) { return Math.min(Math.max(number, lower), upper); }; helper.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true, }, }); return ctor; }; helper.toArray = function(value) { return Array.prototype.slice.call(value); }; helper.extend = function(obj, src) { Object.keys(src).forEach(function(key) { obj[key] = src[key]; }); return obj; }; helper.omit = function(obj, keys) { return Object.keys(obj).reduce(function(ret, key) { if (keys.indexOf(key) === -1) { ret[key] = obj[key]; } return ret; }, {}); }; helper.sortBy = function(array, iteratee) { return array.sort(function(a, b) { var l = iteratee(a); var r = iteratee(b); if (l < r) { return -1; } if (l > r) { return 1; } return 0; }); }; helper.remove = function(array, item) { var index = array.indexOf(item); if (index < 0 || index >= array.length) { throw new RangeError('Invalid index'); } array.splice(index, 1); }; helper.moveToBack = function(array, item) { helper.remove(array, item); array.push(item); }; helper.findIndex = function(array, callback) { for (var i = 0, len = array.length; i < len; i++) { if (callback(array[i], i, array)) { return i; } } return -1; }; helper.findLastIndex = function(array, callback) { for (var i = array.length - 1; i >= 0; i--) { if (callback(array[i], i, array)) { return i; } } return -1; }; helper.find = function(array, callback) { var index = helper.findIndex(array, callback); return (index !== -1 ? array[index] : null); }; helper.findLast = function(array, callback) { var index = helper.findLastIndex(array, callback); return (index !== -1 ? array[index] : null); }; helper.flatten = function(array) { return Array.prototype.concat.apply([], array); }; helper.wrapper = function() { var Wrapper = function(self, wrapper) { return Object.defineProperty(wrapper, 'unwrap', { value: Wrapper.unwrap.bind(self) }); }; Wrapper.unwrap = function(key) { return (key === Wrapper.KEY ? this : null); }; Wrapper.KEY = {}; return Wrapper; }; if (typeof module !== 'undefined' && module.exports) { module.exports = helper; } else { app.helper = helper; } })(this.app || (this.app = {}));
JavaScript
0.000001
@@ -302,393 +302,8 @@ %7D;%0A%0A - helper.inherits = function(ctor, superCtor) %7B%0A ctor.super_ = superCtor;%0A ctor.prototype = Object.create(superCtor.prototype, %7B%0A constructor: %7B%0A value: ctor,%0A enumerable: false,%0A writable: true,%0A configurable: true,%0A %7D,%0A %7D);%0A return ctor;%0A %7D;%0A%0A helper.toArray = function(value) %7B%0A return Array.prototype.slice.call(value);%0A %7D;%0A%0A he
3cd80d3f1e182320713ec51f51d10f2fd85b2f20
Remove tool tip from unregistered user errors
js/views/message_view.js
js/views/message_view.js
/* * vim: ts=4:sw=4:expandtab */ (function () { 'use strict'; window.Whisper = window.Whisper || {}; var URL_REGEX = /(^|[\s\n]|<br\/?>)((?:https?|ftp):\/\/[\-A-Z0-9\u00A0-\uD7FF\uE000-\uFDCF\uFDF0-\uFFFD+\u0026\u2019@#\/%?=()~_|!:,.;]*[\-A-Z0-9+\u0026@#\/%=~()_|])/gi; var ErrorIconView = Whisper.View.extend({ templateName: 'error-icon', className: 'error-icon-container', render_attributes: function() { var message; if (this.model.name === 'UnregisteredUserError') { message = i18n('unregisteredUser'); this.$el.addClass('unregistered-user-error'); } return { message: message }; } }); var NetworkErrorView = Whisper.View.extend({ tagName: 'span', className: 'hasRetry', templateName: 'hasRetry', render_attributes: { messageNotSent: i18n('messageNotSent'), resend: i18n('resend') } }); Whisper.MessageView = Whisper.View.extend({ tagName: 'li', templateName: 'message', initialize: function() { this.listenTo(this.model, 'change:errors', this.onErrorsChanged); this.listenTo(this.model, 'change:body', this.render); this.listenTo(this.model, 'change:delivered', this.renderDelivered); this.listenTo(this.model, 'change', this.renderSent); this.listenTo(this.model, 'change:flags change:group_update', this.renderControl); this.listenTo(this.model, 'destroy', this.remove); this.listenTo(this.model, 'pending', this.renderPending); this.listenTo(this.model, 'done', this.renderDone); this.timeStampView = new Whisper.ExtendedTimestampView(); }, events: { 'click .retry': 'retryMessage', 'click .error-icon': 'select', 'click .timestamp': 'select', 'click .status': 'select', 'click .error-message': 'select' }, retryMessage: function() { var retrys = _.filter(this.model.get('errors'), function(e) { return (e.name === 'MessageError' || e.name === 'OutgoingMessageError' || e.name === 'SendMessageNetworkError'); }); _.map(retrys, 'number').forEach(function(number) { this.model.resend(number); }.bind(this)); }, select: function(e) { this.$el.trigger('select', {message: this.model}); e.stopPropagation(); }, className: function() { return ['entry', this.model.get('type')].join(' '); }, renderPending: function() { this.$el.addClass('pending'); }, renderDone: function() { this.$el.removeClass('pending'); }, renderSent: function() { if (this.model.isOutgoing()) { this.$el.toggleClass('sent', !!this.model.get('sent')); } }, renderDelivered: function() { if (this.model.get('delivered')) { this.$el.addClass('delivered'); } }, onErrorsChanged: function() { if (this.model.isIncoming()) { this.render(); } else { this.renderErrors(); } }, renderErrors: function() { var errors = this.model.get('errors'); if (_.size(errors) > 0) { if (this.model.isIncoming()) { this.$('.content').text(this.model.getDescription()).addClass('error-message'); } var view = new ErrorIconView({ model: errors[0] }); view.render().$el.appendTo(this.$('.bubble')); } else { this.$('.error-icon-container').remove(); } if (this.model.hasNetworkError()) { this.$('.meta').prepend(new NetworkErrorView().render().el); } else { this.$('.meta .hasRetry').remove(); } }, renderControl: function() { if (this.model.isEndSession() || this.model.isGroupUpdate()) { this.$el.addClass('control'); this.$('.content').text(this.model.getDescription()); } else { this.$el.removeClass('control'); } }, render: function() { var contact = this.model.isIncoming() ? this.model.getContact() : null; this.$el.html( Mustache.render(_.result(this, 'template', ''), { message: this.model.get('body'), timestamp: this.model.get('sent_at'), sender: (contact && contact.getTitle()) || '', avatar: (contact && contact.getAvatar()), }, this.render_partials()) ); this.timeStampView.setElement(this.$('.timestamp')); this.timeStampView.update(); this.renderControl(); twemoji.parse(this.el, { attributes: function(icon, variant) { var colon = emoji_util.get_colon_from_unicode(icon); if (colon) { return {title: ":" + colon + ":"}; } else { return {}; } }, base: '/images/twemoji/', size: 16 }); var content = this.$('.content'); var escaped = content.html(); content.html(escaped.replace(/\n/g, '<br>').replace(URL_REGEX, "$1<a href='$2' target='_blank'>$2</a>")); this.renderSent(); this.renderDelivered(); this.renderErrors(); this.loadAttachments(); return this; }, loadAttachments: function() { this.model.get('attachments').forEach(function(attachment) { var view = new Whisper.AttachmentView({ model: attachment }); this.listenTo(view, 'update', function() { this.trigger('beforeChangeHeight'); this.$('.attachments').append(view.el); this.trigger('afterChangeHeight'); }); view.render(); }.bind(this)); } }); })();
JavaScript
0
@@ -416,64 +416,32 @@ -render_attributes: function() %7B%0A var message; +initialize: function() %7B %0A @@ -504,60 +504,8 @@ ) %7B%0A - message = i18n('unregisteredUser');%0A @@ -554,32 +554,32 @@ d-user-error');%0A + %7D%0A @@ -580,49 +580,8 @@ %7D%0A - return %7B message: message %7D;%0A
0d41b41ed9f7a5114804c462b4fca17195f599eb
Rename command db to command store
xpl-db.js
xpl-db.js
/*jslint node: true, vars: true, nomen: true */ 'use strict'; var Xpl = require("xpl-api"); var commander = require('commander'); var os = require('os'); var debug = require('debug')('xpl-db'); var Mysql = require('./lib/mysql'); var Server = require('./lib/server'); commander.version(require("./package.json").version); commander.option("-a, --deviceAliases <aliases>", "Devices aliases"); commander.option("--httpPort <port>", "REST server port", parseInt); Mysql.fillCommander(commander); Xpl.fillCommander(commander); var Store = Mysql; commander.command("create").action(() => { var store = new Store(commander); store.create(function(error) { if (error) { console.error(error); return; } }); }); commander.command("rest").action(() => { var server = new Server(commander, store); server.listen((error) => { if (error) { console.error(error); } }); }); commander.command("db").action(() => { var deviceAliases = Xpl.loadDeviceAliases(commander.deviceAliases); var store = new Store(commander, deviceAliases); store.connect((error) => { if (error) { console.error(error); return; } try { if (!commander.xplSource) { var hostName = os.hostname(); if (hostName.indexOf('.') > 0) { hostName = hostName.substring(0, hostName.indexOf('.')); } commander.xplSource = "db." + hostName; } var xpl = new Xpl(commander); xpl.on("error", (error) => { console.error("XPL error", error); }); xpl.bind((error) => { if (error) { console.error("Can not open xpl bridge ", error); process.exit(2); return; } console.log("Xpl bind succeed "); var processMessage = (message) => { if (message.bodyName === "sensor.basic") { store.save(message, (error) => { if (error) { console.error('error connecting: ', error, error.stack); return; } }); return; } } xpl.on("xpl:xpl-trig", processMessage); xpl.on("xpl:xpl-stat", processMessage); xpl.on("message", function(message, packet, address) { }); }); } catch (x) { console.error(x); } }); }); commander.parse(process.argv);
JavaScript
0.999251
@@ -928,18 +928,21 @@ ommand(%22 -db +store %22).actio
9157ef7be18368030ebd69e7d9e5bd519e2be159
fix resolving node_modules
src/defaults/compiler_config_factory.js
src/defaults/compiler_config_factory.js
// @flow export default function defaultConfigFactory(env: string): WebpackConfig { const config = { output: { filename: '[name].[chunkhash].js', path: '~public/assets', chunkFilename: '[name].[chunkhash].chunk.js', }, resolve: { modules: [ '~app/assets', '~lib/assets', ], extensions: ['.js', '.json', '.jsx'] }, devtool: '', target: 'web', }; if (env === 'development') { config.output.filename = '[name].js'; config.output.chunkFilename = '[name].chunk.js'; } return config; }
JavaScript
0.000008
@@ -273,16 +273,40 @@ ules: %5B%0A + 'node_modules',%0A
05ab1f5f7daed94b2527c62b74c2cafe6a896963
Fix merging tests
tests/integration/mergingTests.js
tests/integration/mergingTests.js
var lib = require("../../source/module.js"); var Workspace = lib.Workspace, Archive = lib.Archive, createCredentials = lib.createCredentials; //var Comparator = require(GLOBAL.root + "/system/ArchiveComparator.js"); module.exports = { setUp: function(cb) { var diffArchiveA = new Archive(), diffArchiveB = new Archive(), commonCommands = [ 'cgr 0 1', 'tgr 1 "Main Group"', 'pad 1', 'cgr 1 2', 'tgr 2 "Secondary Group', 'pad 2', 'cen 1 1', 'sep 1 title "My first entry"', 'cgr 0 4', 'pad 10', 'dgr 4', 'pad 3', 'sep 1 username "anonymous"', 'sep 1 password "retro"', 'sea 1 "test" "test"', 'pad 4', 'cmm "after pad"' ], diffCommandsA = [ 'cgr 1 3', 'tgr 3 "Third group"', 'pad 5', 'cmm "diff a"', 'dgr 3', 'pad 8', 'dgr 1', 'pad 9' ], diffCommandsB = [ 'cen 1 2', 'sep 2 title "My second entry"', 'pad 6', 'sem 2 "country" "AU"', 'pad 7' ]; commonCommands.concat(diffCommandsA).forEach(function(command) { diffArchiveA._getWestley().execute(command); }); commonCommands.concat(diffCommandsB).forEach(function(command) { diffArchiveB._getWestley().execute(command); }); this.diffArchiveA = diffArchiveA; this.diffArchiveB = diffArchiveB; this.diffWorkspace = new Workspace(); this.diffWorkspace.setPrimaryArchive( diffArchiveB, { load: function() { return Promise.resolve(diffArchiveA); } }, createCredentials.fromPassword("fake") ); cb(); }, testMock: function(test) { var diffArchiveA = this.diffArchiveA; this.diffWorkspace.primary.datasource.load().then(function(archive) { test.strictEqual(archive, diffArchiveA, "Mock should return correct archive"); test.done(); }) .catch(function(err) { console.error("Error:", err); }); }, testNonDeletion: function(test) { var workspace = this.diffWorkspace; workspace.mergeSaveablesFromRemote() .then(function() { var mergedHistory = workspace.primary.archive._getWestley().getHistory(); test.ok(mergedHistory.indexOf('tgr 3 "Third group"') > 0, "Merged from group A"); test.ok(mergedHistory.indexOf('sep 2 title "My second entry"') > 0, "Merged from group B"); test.ok(mergedHistory.indexOf('pad 4') > 0, "Merged base"); test.ok(mergedHistory.indexOf('dgr 1') < 0, "Filtered out deletion commands"); test.ok(mergedHistory.indexOf('dgr 4') > 0, "Shared deletion commands persist"); test.done(); }) .catch(function(err) { console.error("Error:", err); }); } };
JavaScript
0.000047
@@ -145,83 +145,92 @@ ials -;%0A%0A//var Comparator = require(GLOBAL.root + %22/system/ArchiveComparator.js%22) +,%0A encodingTools = lib.tools.encoding;%0A%0Aconst E = encodingTools.encodeStringValue ;%0A%0Am @@ -545,16 +545,17 @@ ry Group +%22 ',%0A @@ -2812,17 +2812,17 @@ indexOf( -' +%60 tgr 3 %22T @@ -2832,17 +2832,17 @@ d group%22 -' +%60 ) %3E 0, %22 @@ -2910,17 +2910,17 @@ indexOf( -' +%60 sep 2 ti @@ -2940,17 +2940,17 @@ d entry%22 -' +%60 ) %3E 0,%0A
808436f17334010440b414cf82b01e8049f5b63b
Delete obsolete todo.
features/opensocial-current/jsonperson.js
features/opensocial-current/jsonperson.js
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * Base interface for json based person objects. * * @private * @constructor */ var JsonPerson = function(opt_params) { opt_params = opt_params || {}; // TODO: doesn't handle drinker, smoker, or gender yet JsonPerson.constructObject(opt_params, "bodyType", opensocial.BodyType); JsonPerson.constructObject(opt_params, "currentLocation", opensocial.Address); JsonPerson.constructObject(opt_params, "dateOfBirth", Date); JsonPerson.constructObject(opt_params, "name", opensocial.Name); JsonPerson.constructObject(opt_params, "profileSong", opensocial.Url); JsonPerson.constructObject(opt_params, "profileVideo", opensocial.Url); JsonPerson.constructArrayObject(opt_params, "addresses", opensocial.Address); JsonPerson.constructArrayObject(opt_params, "emails", opensocial.Email); JsonPerson.constructArrayObject(opt_params, "jobs", opensocial.Organization); JsonPerson.constructArrayObject(opt_params, "phoneNumbers", opensocial.Phone); JsonPerson.constructArrayObject(opt_params, "schools", opensocial.Organization); JsonPerson.constructArrayObject(opt_params, "urls", opensocial.Url); JsonPerson.constructEnum(opt_params, "gender"); JsonPerson.constructEnum(opt_params, "smoker"); JsonPerson.constructEnum(opt_params, "drinker"); JsonPerson.constructEnum(opt_params, "networkPresence"); JsonPerson.constructEnumArray(opt_params, "lookingFor"); opensocial.Person.call(this, opt_params, opt_params['isOwner'], opt_params['isViewer']); }; JsonPerson.inherits(opensocial.Person); // Converts the fieldName into an instance of an opensocial.Enum JsonPerson.constructEnum = function(map, fieldName) { var fieldValue = map[fieldName]; if (fieldValue) { map[fieldName] = new opensocial.Enum(fieldValue.key, fieldValue.displayValue); } } // Converts the fieldName into an array of instances of an opensocial.Enum JsonPerson.constructEnumArray = function(map, fieldName) { var fieldValue = map[fieldName]; if (fieldValue) { for (var i = 0; i < fieldValue.length; i++) { fieldValue[i] = new opensocial.Enum(fieldValue[i].key, fieldValue[i].displayValue); } } } // Converts the fieldName into an instance of the specified object JsonPerson.constructObject = function(map, fieldName, className) { var fieldValue = map[fieldName]; if (fieldValue) { map[fieldName] = new className(fieldValue); } } JsonPerson.constructArrayObject = function(map, fieldName, className) { var fieldValue = map[fieldName]; if (fieldValue) { for (var i = 0; i < fieldValue.length; i++) { fieldValue[i] = new className(fieldValue[i]); } } } JsonPerson.prototype.getDisplayName = function() { return this.getField("displayName"); }
JavaScript
0.001851
@@ -970,65 +970,8 @@ %7D;%0A%0A - // TODO: doesn't handle drinker, smoker, or gender yet%0A Js
f4560a20abc3d1259674b4d1f18319fc8eeafc57
update cta copy
client/app/views/pages/home.tmpl.js
client/app/views/pages/home.tmpl.js
// TODO-3 move copy to content directory const { div, header, img, hgroup, h1, h2, h3, h5, h6, p, a, strong, ul, ol, li, iframe, footer, span, section, } = require('../../modules/tags') const icon = require('../components/icon.tmpl') const spinner = require('../components/spinner.tmpl') const previewSubjectHead = require('../components/preview_subject_head.tmpl') const { getIsLoggedIn } = require('../../selectors/base') // TODO-1 Include unique CTAs throughout module.exports = data => { if (getIsLoggedIn(data) === null) { return spinner() } const cta = a( { href: '/sign_up', className: 'home__cta-button' }, icon('sign-up'), ' Sign Up' ) const w = n => span({ className: 'home__icon-wrap' }, n) return div( { id: 'home', className: 'page' }, header( img({ src: '/astrolabe.svg', className: 'home__logo' }), hgroup( h1('Sagefy'), h3('Learn anything, customized for you.'), h6('...and always free.') ), getIsLoggedIn(data) ? p( 'Logged in. ', a({ href: '/my_subjects' }, 'My Subjects ', icon('next')) ) : p( a({ href: '/log_in' }, icon('log-in'), ' Log In'), ' or ', a({ href: '/sign_up' }, icon('sign-up'), ' Sign Up') ) ), getIsLoggedIn(data) ? null : div( section( hgroup( h2('What is Sagefy?'), h5('Sagefy is an open-content adaptive learning platform.') ), p( strong('Adaptive Learning.'), ' Get the most out of your time and effort spent. Sagefy optimizes based on what you already know and what your goal is.' ), p( strong('Open-Content.'), ' Anyone can view, share, create, and edit content. Open-content means that Sagefy reaches a range of learning subjects.' ), cta ), section( h2('How do I learn with Sagefy?'), ol( { className: 'home__ul--how' }, li( img({ src: 'https://i.imgur.com/2QSMPNs.png' }), 'Create an account.' ), li( img({ src: 'https://i.imgur.com/xKRaoff.png' }), 'Find and add a subject.' ), li( img({ src: 'https://i.imgur.com/MYTGawz.png' }), 'Choose your unit.' ), li(img({ src: 'https://i.imgur.com/yjeVPiq.png' }), 'Learn.') ), cta ), section( h2('Popular Subjects'), ul( { className: 'home__ul--popular-subjects' }, li( previewSubjectHead({ url: '/subjects/UIe3mx3UTQKHDG2zLyHI5w/landing', name: 'An Introduction to Electronic Music', body: 'A small taste of the basics of electronic music. Learn the concepts behind creating and modifying sounds in an electronic music system. Learn the ideas behind the tools and systems we use to create electronic music.', }) ) ), cta ), section( h2('Why learn with Sagefy?'), ul( { className: 'home__ul--why' }, li(w(icon('learn')), span(strong('Learn'), ' any subject.')), li( w(icon('fast')), span(strong('Skip'), ' what you already know.') ), li( w(icon('grow')), span(strong('Build up'), ' to where you need to be.') ), li(w(icon('search')), span(strong('Choose'), ' your own path.')), li( w(icon('learn')), span( 'Learn ', strong('deeply'), ', instead of skimming the top.' ) ), li( w(icon('follow')), span( 'Stay ', strong('motiviated'), ' with different types of cards.' ) ), li( w(icon('good')), span( 'Focus on what you want to learn with ', strong('no distractions.') ) ), li( w(icon('create')), span('Create and edit ', strong('any'), ' content.') ), li( w(icon('topic')), span(strong('Discuss'), ' anything as you learn.') ) ), cta ), section( h2('What does Sagefy provide?'), iframe({ width: '560', height: '315', src: 'https://www.youtube.com/embed/gFn4Q9tx7Qs', frameborder: '0', allowfullscreen: true, }), p( 'Also check out the in-detail ', a( { href: 'https://stories.sagefy.org/why-im-building-sagefy-731eb0ceceea', }, 'article on Medium' ), '.' ), cta ), // TODO-1 third party validation section( h2('Comparison'), ul( li( strong('Classroom'), ': When we adapt the content to what you already know, we keep the motivation going and reduce effort and time. Classrooms are a difficult place to get personal. Sagefy optimizes for what you already know, every time.' ), li( strong('Learning Management Systems'), ': Great cost and time savings come from using technology. LMSs are designed to support the classroom model. With Sagefy, you get both the benefits of online learning and a highly personalized experience.' ), li( strong('Closed Adaptive Systems'), ': Pursue your own goals. Closed systems means only select topics are available. An open-content system like Sagefy reaches a range of topics.' ), li( strong('Massive Online Courses'), ': MOOCs reach a large range, but offer little adaption and only support expert-created content. Sagefy has no deadlines -- learn when you see fit.' ), li( strong('Flash Cards'), ': Flash cards are great for memorizing content. But what about integration and application of knowledge? Sagefy goes deeper than flash cards.' ) ), cta ) ), footer( ul( li('© Copyright 2018 Sagefy.'), li(a({ href: 'https://docs.sagefy.org/' }, 'Docs')), li(a({ href: 'https://stories.sagefy.org/' }, 'Stories (Blog)')), li(a({ href: 'https://sgef.cc/devupdates' }, 'Updates')), li( a( { href: 'https://sagefy.uservoice.com/forums/233394-general/', }, icon('contact'), ' Support' ) ), li(a({ href: '/terms' }, icon('terms'), ' Privacy & Terms')) ) ) ) }
JavaScript
0
@@ -688,26 +688,31 @@ '),%0A -' Sign Up' +%22 Let's Learn!%22 %0A )%0A%0A
3e433a2eb63e552f5d8b83dc978852cafa6ef371
Use https for images on home
client/app/views/pages/home.tmpl.js
client/app/views/pages/home.tmpl.js
/* eslint-disable */ // TODO-3 move copy to content directory const {div, header, img, hgroup, h1, h2, h3, h4, h5, h6, p, a, hr, strong, ul, ol, li, iframe, br, footer, span, em, section} = require('../../modules/tags') const icon = require('../components/icon.tmpl') // TODO-1 Include unique CTAs throughout module.exports = data => { const cta = a({href: '/sign_up', className: 'home__cta-button'}, icon('sign-up'), ' Sign Up') const w = (n) => span({className: 'home__icon-wrap'}, n) return div( {id: 'home', className: 'page'}, header( img( {src: '/astrolabe.svg', className: 'home__logo'} ), hgroup( h1('Sagefy'), h3('Learn anything, customized for you.'), h6('...and always free.') ), data.currentUserID ? p( 'Logged in. ', a( {href: '/my_sets'}, 'My Sets ', icon('next') ) ) : null, data.currentUserID ? null : p( a({href: '/log_in'}, icon('log-in'), ' Log In'), ' or ', a({href: '/sign_up'}, icon('sign-up'), ' Sign Up') ) ), data.currentUserID ? null : div( section( hgroup( h2('What is Sagefy?'), h5('Sagefy is an open-content adaptive learning platform.') ), p( strong('Adaptive Learning.'), ' Get the most out of your time and effort spent. Sagefy optimizes based on what you already know and what your goal is.' ), p( strong('Open-Content.'), ' Anyone can view, share, create, and edit content. Open-content means that Sagefy reaches a range of learning subjects.' ), cta ), section( h2('Why learn with Sagefy?'), ul( {className: 'home__ul--why'}, li(w(icon('learn')), em(' Learn any subject.')), li(w(icon('create')), em(' Create and edit any content.')), li(w(icon('fast')), em(' Skip what you already know.')), li(w(icon('grow')), em(' Build up to where you need to be.')), li(w(icon('search')), em(' Choose your own path.')), li(w(icon('topic')), em(' Discussion built in.')) ), cta ), section( h2('How do I learn with Sagefy?'), ol( {className: 'home__ul--how'}, li(img({src: 'http://i.imgur.com/qrPmvzZ.png'}), 'Create an account.'), li(img({src: 'http://i.imgur.com/9KJdaFl.png'}), 'Find and add a set.'), li(img({src: 'http://i.imgur.com/uLJstC1.png'}), 'Choose your unit.'), li(img({src: 'http://i.imgur.com/BlUMbif.png'}), 'Learn.') ), iframe({ width: "560", height: "315", src: "https://www.youtube.com/embed/HVwfwTOdnOE", frameborder: "0", allowfullscreen: true }), p( 'Also check out the in-detail ', a({href: 'https://stories.sagefy.org/why-im-building-sagefy-731eb0ceceea'}, 'article on Medium'), '.' ), cta ), section( h2('Popular Sets'), ul( li( a({href: 'https://sagefy.org/sets/CgDRJPfzJuTR916HdmosA3A8'}, 'An Introduction to Electronic Music - Foundation'), br(), 'A small taste of the basics of electronic music. These units serve as the basis for topics on creating and changing sound.' ) ), cta ), // TODO-1 third party validation section( h2('Features'), ul( {className: 'home__ul--features'}, li(w(icon('unit')), strong('Simple'), ' organization. The only kinds of things are: ', ul( li('Sets -- or courses,'), li('Units -- or learning goals, and'), li('Cards -- small learning experiences.') ) ), li(w(icon('search')), strong('Choose'), ' your path along the way. Sagefy recommends, but never requires.'), li(w(icon('reply')), 'Keep up to speed with ', strong('review'), ' reminders.'), li(w(icon('follow')), strong('Variety'), ' of types of cards, so you can stay motivated.'), li(w(icon('good')), 'Focus on what you want to learn with ', strong('no distractions.')), li(w(icon('fast')), strong('Skip'), ' content you already know.'), li(w(icon('learn')), 'Learn ', strong('deeply'), ', instead of skimming the top.') ), cta ), section( h2('Comparison'), ul( li( strong('Classroom'), ': When we adapt the content to what the learner already knows, we keep the motivation going and reduce effort and time. Classrooms are a difficult place to get personal. Sagefy optimizes for what you already know, every time.' ), li( strong('Learning Management Systems'), ': Great cost and time savings come from using technology. LMSs are designed to support the classroom model. With Sagefy, you get both online and highly personalized.' ), li( strong('Closed Adaptive Systems'), ': Learners should be able to pursue their own goals. Closed systems means only select topics are available. An open-content system like Sagefy reaches a range of topics.' ), li( strong('Massive Online Courses'), ': MOOCs reach a large range, but offer little adaption and only support expert-created content. Sagefy has no deadlines -- learn when you see fit.' ), li( strong('Flash Cards'), ': Flash cards are great for memorizing content. But what about integration and application of knowledge? Sagefy goes deeper than flash cards.' ) ), cta ) ), footer( ul( li('© Copyright 2016 Sagefy.'), li(a({href: 'https://docs.sagefy.org/'}, 'Docs')), li(a({href: 'https://stories.sagefy.org/'}, 'Stories (Blog)')), li(a({href: 'https://sagefy.uservoice.com/forums/233394-general/'}, icon('contact'), ' Support')), li(a({href: '/terms'}, icon('terms'), ' Privacy & Terms')) ) ) ) };
JavaScript
0
@@ -2623,32 +2623,33 @@ (img(%7Bsrc: 'http +s ://i.imgur.com/q @@ -2710,32 +2710,33 @@ (img(%7Bsrc: 'http +s ://i.imgur.com/9 @@ -2798,32 +2798,33 @@ (img(%7Bsrc: 'http +s ://i.imgur.com/u @@ -2892,16 +2892,17 @@ c: 'http +s ://i.img
b88216b42291988a767e9e2be8c6e3f931ed549a
Use MinimalModule in testModuleFactory
tests/js/app/testModuleFactory.js
tests/js/app/testModuleFactory.js
// Copyright 2015 Endless Mobile, Inc. const Lang = imports.lang; const GObject = imports.gi.GObject; const ModuleFactory = imports.app.moduleFactory; const Module = imports.app.interfaces.module; const MOCK_APP_JSON = { version: 2, modules: { 'test': { type: 'TestModule' }, }, }; const TestModule = new Lang.Class({ Name: 'TestModule', Extends: GObject.Object, Implements: [ Module.Module ], Properties: { 'factory': GObject.ParamSpec.override('factory', Module.Module), 'factory-name': GObject.ParamSpec.override('factory-name', Module.Module), }, _init: function (props={}) { this.parent(props); }, }); const MockWarehouse = new Lang.Class({ Name: 'MockWarehouse', Extends: GObject.Object, _init: function (props={}) { this.parent(props); }, type_to_class: function (module_name) { return TestModule; }, }); describe('Module factory', function () { let module_factory; let warehouse; beforeEach(function () { warehouse = new MockWarehouse(); module_factory = new ModuleFactory.ModuleFactory({ app_json: MOCK_APP_JSON, warehouse: warehouse, }); }); it ('constructs', function () {}); it ('returns correct module constructor', function () { spyOn(warehouse, 'type_to_class').and.callThrough(); module_factory.create_named_module('test'); expect(warehouse.type_to_class).toHaveBeenCalledWith('TestModule'); }); });
JavaScript
0
@@ -97,16 +97,55 @@ bject;%0A%0A +const Minimal = imports.tests.minimal;%0A const Mo @@ -188,54 +188,8 @@ ory; -%0Aconst Module = imports.app.interfaces.module; %0A%0Aco @@ -316,388 +316,8 @@ %7D;%0A%0A -const TestModule = new Lang.Class(%7B%0A Name: 'TestModule',%0A Extends: GObject.Object,%0A Implements: %5B Module.Module %5D,%0A%0A Properties: %7B%0A 'factory': GObject.ParamSpec.override('factory', Module.Module),%0A 'factory-name': GObject.ParamSpec.override('factory-name', Module.Module),%0A %7D,%0A%0A _init: function (props=%7B%7D) %7B%0A this.parent(props);%0A %7D,%0A%7D);%0A%0A cons @@ -536,20 +536,31 @@ return -Test +Minimal.Minimal Module;%0A
ce7997b12500a10b8d82d6181b92c422c0ebcb52
Repair attachments tests
server/api/send-mail/send-mail-actions.spec.js
server/api/send-mail/send-mail-actions.spec.js
'use strict'; import sinon from 'sinon'; import proxyquire from 'proxyquire'; require('sinon-as-promised'); describe('Send Mail Actions', function() { describe('sendMailNotificationAgent', function() { let sendMailSpy = sinon.spy(); const SendMailAction = proxyquire('./send-mail-actions', { './send-mail.controller': { sendMail: sendMailSpy } }); let fakeRequest = { shortId: '1234' }; let fakeEmail = '[email protected]'; it('should send the correct email to the correct adress', function(done) { SendMailAction .sendMailNotificationAgent(fakeRequest, fakeEmail) .then(function() { sendMailSpy.calledOnce.should.equal(true); sendMailSpy.args[0][0].email.should.equal(fakeEmail); sendMailSpy.args[0][0].title.should.equal('Vous avez reçu une nouvelle demande'); sendMailSpy.args[0][0].body.should.containEql('Référence de la demande: 1234'); done(); }) .catch(function(e) { done(e); }); }); }); describe('sendMailReceivedTransmission', function() { let sendMailSpy = sinon.spy(); let fakePath = 'toto/lol/'; const PdfMakerStub = sinon.stub().resolves(fakePath); const SendMailAction = proxyquire('./send-mail-actions', { './send-mail.controller': { sendMail: sendMailSpy }, '../../components/pdf-maker': { default: PdfMakerStub } }); let fakeOptions = { request: { shortId: '1234', }, replyTo: '[email protected]', email: '[email protected]', }; it('should send the correct email to the correct adress', function(done) { SendMailAction.sendMailReceivedTransmission(fakeOptions) .then(function() { sendMailSpy.calledOnce.should.equal(true); sendMailSpy.args[0][0].email.should.equal(fakeOptions.email); sendMailSpy.args[0][0].title.should.equal('Votre demande a bien été transmise'); sendMailSpy.args[0][0].body.should.containEql('Votre demande à été transmise à votre MDPH. Vous pouvez trouver ci-joint un récapitulatif de votre demande au format PDF.'); sendMailSpy.args[0][0].replyTo.should.containEql('[email protected]'); sendMailSpy.args[0][0].attachments[0].filename.should.containEql(fakeOptions.request.shortId); sendMailSpy.args[0][0].attachments[0].path.should.equal(fakePath); done(); }) .catch(function(e) { done(e); }); }); }); describe('sendConfirmationMail', function() { let sendMailSpy = sinon.spy(); const SendMailAction = proxyquire('./send-mail-actions', { './send-mail.controller': { sendMail: sendMailSpy } }); let fakeEmail = '[email protected]'; let fakeURL = 'www.toto.com'; it('should send the correct email to the correct adress', function(done) { SendMailAction.sendConfirmationMail(fakeEmail, fakeURL) .then(function() { sendMailSpy.calledOnce.should.equal(true); sendMailSpy.args[0][0].email.should.equal(fakeEmail); sendMailSpy.args[0][0].title.should.equal('Veuillez confirmer votre adresse e-mail'); sendMailSpy.args[0][0].body.should.containEql(fakeURL); done(); }) .catch(function(e) { done(e); }); }); }); describe('sendMailCompletude', function() { let sendMailSpy = sinon.spy(); const SendMailAction = proxyquire('./send-mail-actions', { './send-mail.controller': { sendMail: sendMailSpy } }); let fakeRequest = { shortId: '1234', mdph: '11', user: { email: '[email protected]' } }; let fakeOptions = { url: 'www.toto.com' }; it('should send the correct email to the correct adress', function(done) { SendMailAction.sendMailCompletude(fakeRequest, fakeOptions) .then(function() { sendMailSpy.calledOnce.should.equal(true); sendMailSpy.args[0][0].email.should.equal(fakeRequest.user.email); sendMailSpy.args[0][0].title.should.equal('Accusé de réception de votre MDPH'); sendMailSpy.args[0][0].body.should.containEql(fakeRequest.mdph); sendMailSpy.args[0][0].body.should.containEql(fakeOptions.url); done(); }) .catch(function(e) { done(e); }); }); }); describe('sendMailRenewPassword', function() { let sendMailSpy = sinon.spy(); const SendMailAction = proxyquire('./send-mail-actions', { './send-mail.controller': { sendMail: sendMailSpy } }); let fakeEmail = '[email protected]'; let fakeURL = 'www.toto.com'; it('should send the correct email to the correct adress', function(done) { SendMailAction .sendMailRenewPassword(fakeEmail, fakeURL) .then(function() { sendMailSpy.calledOnce.should.equal(true); sendMailSpy.args[0][0].email.should.equal(fakeEmail); sendMailSpy.args[0][0].title.should.equal('Nouveau mot de passe'); sendMailSpy.args[0][0].body.should.containEql(fakeURL); done(); }) .catch(function(e) { done(e); }); }); }); });
JavaScript
0
@@ -1233,24 +1233,32 @@ esolves( +%7B path: fakePath );%0A%0A @@ -1249,16 +1249,18 @@ fakePath + %7D );%0A%0A
5fb1af1d75789e3ade3c83982c644c049ed55b8e
Fix bug in haversine distance calculator.
client/js/services/route-service.js
client/js/services/route-service.js
"use strict"; angular.module("hikeio"). factory("route", ["$q", function($q) { var parseXml = function(xmlStr) { if (typeof window.DOMParser !== "undefined") { return (new window.DOMParser()).parseFromString(xmlStr, "text/xml"); } else if (typeof window.ActiveXObject !== "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) { var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.loadXML(xmlStr); return xmlDoc; } else { return null; } }; // Calculates the distance between two points on a sphere // http://www.codecodex.com/wiki/Calculate_Distance_Between_Two_Points_on_a_Globe var haversineDistance = function(lat1, lng1, elv1, lat2, lng2, elv2) { var radius = 6371; // km var dLat = (lat2 - lat1) * Math.PI / 180; var dLon = (lng2 - lng1) * Math.PI / 180; var a = Math.sin(dLat / 2) * Math.sin(dLat/2) + Math.cos(lat1 * Math.PI/180) * Math.cos(lat2 * Math.PI/180) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var c = 2 * Math.asin(Math.sqrt(a)); var horizontalDistance = radius * c; // Modification from classic Haversine. Take into account elevation and use the Pythagorean theorem // to calculate the real distance traveled (i.e. the hypotenuse). This is what tools like Adze use. if (elv1 && elv2) { var elevationGain = Math.abs(elv1 - elv2) / 1000.0; var realDistanceTraveled = Math.sqrt(d * d + elevationGain * elevationGain); return realDistanceTraveled; } else { return horizontalDistance; } }; var RouteService = function() { }; RouteService.prototype.fileToGeoJSON = function(file) { var deferred = $q.defer(); var routeReader = new FileReader(); routeReader.onload = function (e) { /* global toGeoJSON: true */ var name = file.name || ""; var routeString = e.target.result; if (name.toLowerCase().endsWith(".geojson")) { deferred.resolve(JSON.parse(routeString)); } else if (name.toLowerCase().endsWith(".gpx")) { var doc = parseXml(routeString); var geoJSON = toGeoJSON.gpx(doc); if (geoJSON) { deferred.resolve(geoJSON); } else { deferred.reject("Unable to find tracks or routes in GPX."); } } else { deferred.reject("Unsupported format, try .gpx or .geojson"); } }; routeReader.readAsText(file); return deferred.promise; }; RouteService.prototype.getAggregateDataFromGeoJSON = function(geoJSON) { console.log(geoJSON) var result = {}; if (!geoJSON.features || !geoJSON.features[0] || !geoJSON.features[0].geometry || !geoJSON.features[0].geometry.coordinates || geoJSON.features[0].geometry.coordinates.length === 0) { result.error = "Unable to parse route file."; } else { var coordinates = geoJSON.features[0].geometry.coordinates; var totalDistance = 0; var elevationMax = coordinates[0][2]; var totalElevationGain = 0; for (var i = 1; i < coordinates.length; i++) { var distanceBetweenCoordinates = haversineDistance(coordinates[i][1], coordinates[i][0], coordinates[i][2], coordinates[i-1][1], coordinates[i-1][0], coordinates[i-1][2]); totalDistance += distanceBetweenCoordinates; if (coordinates[i][2] > elevationMax) { elevationMax = coordinates[i][2]; } var elevationGain = coordinates[i][2] - coordinates[i-1][2]; if (elevationGain > 0) { totalElevationGain += elevationGain; } } result.firstLatLng = { latitude: coordinates[0][1], longitude: coordinates[0][0] }; result.distance = totalDistance; result.elevationMax = elevationMax; result.elevationGain = totalElevationGain; } return result; }; return new RouteService(); }]);
JavaScript
0
@@ -1431,13 +1431,47 @@ qrt( -d * d +horizontalDistance * horizontalDistance + e @@ -1533,18 +1533,16 @@ raveled; -%09%09 %0A%09%09%09%7D el @@ -2506,32 +2506,8 @@ ) %7B%0A -%09%09%09console.log(geoJSON)%0A %09%09%09v
7e6902ca10f94d61df0df348bdda937b89aff8b6
update to make sure that sub-classed binding kinds will have the appropriate values
source/kernel/AutoBindingSupport.js
source/kernel/AutoBindingSupport.js
(function () { var remapped = { bindFrom: "from", bindTo: "to", bindTransform: "transform", bindOneWay: "oneWay", bindAutoSync: "autoSync", bindDebug: "debug" }; var defaults = { to: ".content", transform: null, oneWay: true, autoSync: false, debug: false }; enyo.kind({ // ........................... // PUBLIC PROPERTIES //*@public name: "enyo.AutoBindingSupport", //*@public kind: "enyo.Mixin", // ........................... // PROTECTED PROPERTIES //*@protected _did_setup_auto_bindings: false, // ........................... // COMPUTED PROPERTIES // ........................... // PUBLIC METHODS // ........................... // PROTECTED METHODS //*@protected create: function () { var cache = this._auto_cache = {}; var ctor = this._binding_ctor = enyo.getPath(this.defaultBindingKind); var keys = enyo.keys(defaults); if (ctor !== enyo.Binding) { cache.defaults = enyo.mixin(enyo.clone(defaults), enyo.only(keys, ctor.prototype)); } else cache.defaults = defaults; this.setupAutoBindings(); }, //*@protected autoBinding: function () { var bind = this.binding.apply(this, arguments); bind.autoBindingId = enyo.uid("autoBinding"); }, //*@protected autoBindings: enyo.Computed(function () { return enyo.filter(this.bindings || [], function (bind) { return bind && bind.autoBindingId; }); }), //*@protected setupAutoBindings: function () { if (this._did_setup_auto_bindings) return; if (!this.controller) return; var controls = this.get("bindableControls"); var idx = 0; var len = controls.length; var controller = this.controller; var control; var props; for (; idx < len; ++idx) { control = controls[idx]; props = this.bindProperties(control); this.autoBinding(props, {source: controller, target: control}); } this._did_setup_auto_bindings = true; }, //*@protected bindProperties: function (control) { var cache = this._auto_cache.defaults; return enyo.mixin(enyo.clone(cache), enyo.remap(remapped, control)); }, //*@protected bindableControls: enyo.Computed(function (control) { var cache = this._auto_cache["bindableControls"]; if (cache) return enyo.clone(cache); var bindable = []; var control = control || this; var controls = control.controls || []; var idx = 0; var len = controls.length; for (; idx < len; ++idx) { bindable = bindable.concat(this.bindableControls(controls[idx])); } if ("bindFrom" in control) bindable.push(control); if (this === control) this._auto_cache["bindableControls"] = enyo.clone(bindable); return bindable; }), //*@protected controllerDidChange: enyo.Observer(function () { this.inherited(arguments); if (this.controller) { if (!this._did_setup_auto_bindings) { this.setupAutoBindings(); } } }, "controller") // ........................... // OBSERVERS }); }());
JavaScript
0
@@ -1332,16 +1332,22 @@ rototype +, true ));%0A
583e57d876f683e9b77ff9df19611b38f0d77740
Add Keyelems method to Map
web/client/scripts/map.js
web/client/scripts/map.js
/*--------------------------------------------------------------------------- Copyright 2013 Microsoft Corporation. This is free software; you can redistribute it and/or modify it under the terms of the Apache License, Version 2.0. A copy of the License can be found in the file "license.txt" at the root of this distribution. ---------------------------------------------------------------------------*/ if (typeof define !== 'function') { var define = require('amdefine')(module) } define([],function() { var Map = (function() { function Map() { }; Map.prototype.clear = function() { var self = this; self.forEach( function(name,value) { self.remove(name); }); } Map.prototype.persist = function() { return this; }; Map.prototype.copy = function() { var self = this; var map = new Map(); self.forEach( function(name,value) { map.set(name,value); }); return map; } Map.prototype.set = function( name, value ) { this["/" + name] = value; } Map.prototype.get = function( name ) { return this["/" + name]; } Map.prototype.getOrCreate = function( name, def ) { var self = this; if (!self.contains(name)) self.set(name,def); return self.get(name); } Map.prototype.contains = function( name ) { return (this.get(name) !== undefined); } Map.prototype.remove = function( name ) { delete this["/" + name]; } // apply action to each element. breaks early if action returns "false". Map.prototype.forEach = function( action ) { var self = this; for (var key in self) { if (key.substr(0,1) === "/") { var res = action(key.substr(1), self[key]); if (res===false) return; } }; } // return a new map where action is applied to every element Map.prototype.map = function( action ) { var self = this; var res = new Map(); self.forEach( function(name,elem) { res.set(name,action(elem)); }); return res; } Map.prototype.elems = function() { var self = this; var res = []; self.forEach( function(name,elem) { res.push(elem); }); return res; } return Map; })(); return Map; });
JavaScript
0
@@ -2381,24 +2381,238 @@ ;%0D%0A %7D%0D%0A%0D%0A + Map.prototype.keyElems = function() %7B%0D%0A var self = this;%0D%0A var res = %5B%5D;%0D%0A self.forEach( function(name,elem) %7B%0D%0A res.push( %7Bkey:name,value:elem%7D );%0D%0A %7D);%0D%0A return res;%0D%0A %7D%0D%0A%0D%0A return M
6bb997cda18613a56a02e7c22bee4844642c5fc0
allow extension properties on any chat type
src/extplug/plugins/custom-chat-type.js
src/extplug/plugins/custom-chat-type.js
define(function (require, exports, module) { const { around } = require('meld'); const Events = require('plug/core/Events'); const ChatView = require('plug/views/rooms/chat/ChatView'); const util = require('plug/util/util'); const emoji = require('plug/util/emoji'); const settings = require('plug/store/settings'); const Plugin = require('../Plugin'); /** * The ChatType Plugin adds a "custom" chat type. Any chat messages * passed through the ChatView "onReceived" handler will be affected, * so in particular all "chat:receive" events are handled properly. * * A chat message with "custom" in its type property can take a few * additional options: * * * the "badge" property can contain an emoji name (eg ":eyes:") or * an icon class (eg "icon-plugdj") as well as the standard badge * names. * * the "color" property takes a CSS colour, which will be used for * the message text. * * the "timestamp" property always defaults to the current time if * it is left empty. * * This is especially useful for showing notifications in chat. * The "type" property can be a list of CSS class names, if it contains * "custom", (eg `{ type: "custom inline my-notification" }`) so you * can use those classes to style your message as well. Note that you * cannot add additional classes for the other message types. */ const ChatTypePlugin = Plugin.extend({ enable() { // chatView.onReceived will still be the old method after adding advice // so the event listener should also be swapped out let chatView = this.ext.appView.room.chat; if (chatView) { Events.off('chat:receive', chatView.onReceived); } this._chatTypeAdvice = around(ChatView.prototype, 'onReceived', this.onReceived); if (chatView) { Events.on('chat:receive', chatView.onReceived, chatView); } }, disable() { // remove custom chat type advice, and restore // the original event listener let chatView = this.ext.appView.room.chat; if (chatView) { Events.off('chat:receive', chatView.onReceived); } this._chatTypeAdvice.remove(); if (chatView) { Events.on('chat:receive', chatView.onReceived, chatView); } }, // bound to the ChatView instance onReceived(joinpoint) { let message = joinpoint.args[0]; if (message.type.split(' ').indexOf('custom') !== -1) { // plug.dj has some nice default styling on "update" messages message.type += ' update'; if (!message.timestamp) { message.timestamp = util.getChatTimestamp(settings.settings.chatTimestamps === 24); } // insert the chat message element joinpoint.proceed(); if (message.badge) { // emoji badge if (/^:(.*?):$/.test(message.badge)) { let badgeBox = this.$chatMessages.children().last().find('.badge-box'); let emojiName = message.badge.slice(1, -1); if (emoji.map[emojiName]) { badgeBox.find('i').remove(); badgeBox.append( $('<span />').addClass('emoji-glow extplug-badji').append( $('<span />').addClass('emoji emoji-' + emoji.map[emojiName]) ) ); } } // icon badge else if (/^icon-(.*?)$/.test(message.badge)) { let badgeBox = this.$chatMessages.children().last().find('.badge-box'); badgeBox.find('i') .removeClass() .addClass('icon').addClass(message.badge); } } if (message.color) { this.$chatMessages.children().last().find('.msg .text').css('color', message.color); } } else { joinpoint.proceed(); } } }); module.exports = ChatTypePlugin; });
JavaScript
0
@@ -2569,24 +2569,30 @@ update';%0A + %7D%0A if (!m @@ -2607,26 +2607,24 @@ imestamp) %7B%0A - mess @@ -2705,30 +2705,26 @@ 24);%0A - %7D%0A +%7D%0A // ins @@ -2754,26 +2754,24 @@ ement%0A - joinpoint.pr @@ -2779,24 +2779,23 @@ ceed();%0A - +%0A - if (mess @@ -2815,18 +2815,16 @@ - // emoji @@ -2834,26 +2834,24 @@ dge%0A - - if (/%5E:(.*?) @@ -2869,34 +2869,32 @@ ssage.badge)) %7B%0A - let ba @@ -2965,26 +2965,24 @@ ;%0A - - let emojiNam @@ -3019,26 +3019,24 @@ ;%0A - if (emoji.ma @@ -3055,34 +3055,32 @@ ) %7B%0A - - badgeBox.find('i @@ -3088,26 +3088,24 @@ ).remove();%0A - @@ -3127,34 +3127,32 @@ (%0A - $('%3Cspan /%3E').ad @@ -3186,34 +3186,32 @@ badji').append(%0A - @@ -3290,14 +3290,10 @@ - )%0A +)%0A @@ -3305,38 +3305,34 @@ );%0A - %7D%0A +%7D%0A %7D%0A @@ -3321,26 +3321,24 @@ %7D%0A %7D%0A - // i @@ -3343,26 +3343,24 @@ icon badge%0A - else @@ -3404,34 +3404,32 @@ e)) %7B%0A - let badgeBox = t @@ -3486,34 +3486,32 @@ ox');%0A - badgeBox.find('i @@ -3525,18 +3525,16 @@ - .removeC @@ -3540,18 +3540,16 @@ Class()%0A - @@ -3599,38 +3599,34 @@ e);%0A - %7D%0A +%7D%0A %7D%0A if ( @@ -3609,26 +3609,24 @@ %7D%0A %7D%0A - if (me @@ -3644,26 +3644,24 @@ ) %7B%0A - - this.$chatMe @@ -3737,68 +3737,8 @@ r);%0A - %7D%0A %7D%0A else %7B%0A joinpoint.proceed();%0A
baea3ec33de2a1fda2ff5ba224d67a7b4952c608
Fix referror in leveling script.
scripts/player/player.js
scripts/player/player.js
'use strict'; var LevelUtil = require('../../src/levels').LevelUtil, Skills = require('../../src/skills').Skills, CommandUtil = require('../../src/command_util').CommandUtil, util = require('util'); exports.listeners = { //// Function wrappers needed to access "this" (Player obj) //TODO: Do regenHealth, regenSanity, and regenActions regen: function(l10n) { return function(bonus) { bonus = bonus || 1; const self = this; const regenInterval = 2000; const regen = setInterval(() => { const health = self.getAttribute('health'); let regenerated = Math.floor(Math.random() * self.getAttribute('stamina') + bonus); regenerated = Math.min(self.getAttribute('max_health'), health + regenerated); util.log(self.getName() + ' has regenerated up to ' + regenerated + ' health.'); self.setAttribute('health', regenerated); if (regenerated === self.getAttribute('max_health')) { clearInterval(regen); } }, regenInterval); } }, experience: function(l10n) { return function(experience) { const maxLevel = 60; if (this.getAttribute('level') >= maxLevel) { return; } util.log(this.getName() + ' has gained ' + experience + ' XP.'); this.sayL10n(l10n, 'EXPGAIN', experience); const tnl = LevelUtil.expToLevel(this.getAttribute('level')) - this.getAttribute('experience'); if (experience >= tnl) { return this.emit('level'); } this.setAttribute('experience', this.getAttribute('experience') + experience); } }, level: function(l10n) { return function() { const name = this.getName(); const newLevel = this.getAttribute('level') + 1; const healthGain = Math.ceil(this.getAttribute('max_health') * 1.10); const gainedMutation = newLevel % 2 === 0; let mutationPoints = this.getAttribute('mutagens'); util.log(name + ' is now level ' + newLevel); this.sayL10n(l10n, 'LEVELUP'); if (gainedMut) { this.sayL10n(l10n, 'MUTAGEN_GAIN'); mutationPoints++; this.setAttribute('mutagens', mutationPoints); } this.setAttribute('level', newLevel); this.setAttribute('experience', 0); this.setAttribute('attrPoints', (this.getAttribute('attrPoints') || 0) + 1); // Do whatever you want to do here when a player levels up... this.setAttribute('max_health', healthGain); this.setAttribute('health', this.getAttribute('max_health')); util.log(name + ' now has ' + healthGain + ' max health.'); // Add points for skills const skillGain = LevelUtil.getTrainingTime(newLevel); const newTrainingTime = this.getTraining('time') + skillGain; util.log(name + ' can train x', newTrainingTime); this.setTraining('time', newTrainingTime); } }, //TODO: Permadeath, add it. die: function(l10n) { return function() { // they died, move then back to the start... you can do whatever you want instead of this this.setLocation(1); this.emit('regen'); util.log(this.getName() + ' died.'); this.setAttribute('experience', this.getAttribute('experience') - Math.ceil((this.getAttribute('experience') * 0.10))); } }, changeTime: function(l10n) { return function (wasDaytime, rooms) { const playerIsOutside = rooms.getAt(this.getLocation()).biome === 'outdoors'; if (playerIsOutside) { if (wasDaytime) { this.sayL10n(l10n, "SUN_SETTING"); setTimeout(() => this.sayL10n(l10n, "SUN_SET"), 5000); } else { this.sayL10n(l10n, "SUN_RISING"); setTimeout(() => this.sayL10n(l10n, "SUN_UP"), 5000); } } else if (wasDaytime) { this.sayL10n(l10n, "SUN_SETTING_INDOORS"); } else { this.sayL10n(l10n, "SUN_UP_INDOORS"); } } } };
JavaScript
0
@@ -2036,16 +2036,21 @@ ainedMut +ation ) %7B%0A
ac260edac48a842054e8c49d3d8c0df157b83e6b
fix publish script
scripts/publish-to-s3.js
scripts/publish-to-s3.js
require('dotenv').config() const AWS = require('aws-sdk') const path = require('path') const fs = require('fs') const { promisify } = require('util') const pkg = require('../package.json') const getVersionTypes = version => [ version, version.replace(/^(\d+\.\d+)\.\d+/, '$1.x'), version.replace(/^(\d+)\.\d+\.\d+/, '$1.x') ] const BASE_PATH = 'widget/' const VERSION_TYPES = getVersionTypes(pkg.version) const BUCKET = process.env.BUCKET const ACCESS_KEY = process.env.ACCESS_KEY const SECRET_KEY = process.env.SECRET_KEY if (!BUCKET || !ACCESS_KEY || !SECRET_KEY) { console.log("don't found credentials skip publish to s3") process.exit(0) } const UPLOAD_CONFIG = { ACL: 'public-read', Bucket: BUCKET, ContentType: 'application/javascript; charset=utf-8' } const S3 = new AWS.S3({ credentials: new AWS.Credentials(ACCESS_KEY, SECRET_KEY) }) const baseS3upload = promisify(S3.upload.bind(S3)) const readFilePr = promisify(fs.readFile) const readFile = filePath => { const absolutePath = path.resolve(__dirname, '../', filePath) return readFilePr(absolutePath, 'utf-8') } const uploadToS3 = (data, path, { dry } = {}) => { let promise = Promise.resolve() if (dry) { console.log('DRY RUN.') } else { promise = baseS3upload( Object.assign({}, UPLOAD_CONFIG, { Body: data, Key: path }) ) } console.log(`uploading ${data.length}B to ${path}`) return promise } const uploadFile = (data, fileName, options) => { return Promise.all( VERSION_TYPES.map(version => uploadToS3(data, `${BASE_PATH}${version}/uploadcare/${fileName}`, options) ) ) } // main part starts here Promise.all(pkg.files.map(name => Promise.all([readFile(name), name]))) .then(files => Promise.all(files.map(([data, name]) => uploadFile(data, name, { dry: false }))) ) .catch(error => { console.error('Error: \n', error.message) process.exit(1) })
JavaScript
0.000013
@@ -1651,16 +1651,19 @@ ise.all( +%0A pkg.file @@ -1672,15 +1672,73 @@ map( -name =%3E +filePath =%3E %7B%0A const name = path.basename(filePath)%0A return Pro @@ -1769,17 +1769,22 @@ , name%5D) -) +%0A %7D)%0A )%0A .the @@ -1810,16 +1810,23 @@ ise.all( +%0A files.ma @@ -1884,16 +1884,21 @@ alse %7D)) +%0A )%0A )%0A
d660ae21cc4e3879eab0b2b0b8cef35e41c2e3c0
update to grab continuous values on midi
js/myMIDI.js
js/myMIDI.js
var midi = null; // global MIDIAccess object var midiIn = null; var midiOut = null; var midiData = Array.apply(null, Array(128)).map(function() { return 0; }); function onMIDISuccess(midiAccess) { console.log("MIDI ready!"); midi = midiAccess; // store in the global (in real usage, would probably keep in an object instance) // midi.onstatechange = do something here like assign a function listInputsAndOutputs(midi); } function onMIDIFailure(msg) { console.log("Failed to get MIDI access - " + msg); } function populateMIDIInSelect() { $('#selectMIDIIn').find('option').remove().end(); $('#selectMIDIIn').selectmenu('refresh'); for (var entry of midi.inputs) { var input = entry[1]; if (midiIn && midiIn == input.name) { $('#selectMIDIIn').append('<option val="' + input.id + '" selected="selected">' + input.name + '</option>'); } else { $('#selectMIDIIn').append('<option val="' + input.id + '">' + input.name + '</option>'); } } $('#selectMIDIIn').selectmenu('refresh'); } function midiConnectionStateChange(e) { console.log("connection: " + e.port.name + " " + e.port.connection + " " + e.port.state); populateMIDIInSelect(); } function listInputsAndOutputs(midiAccess) { for (var entry of midiAccess.inputs) { var input = entry[1]; console.log("Input port [type:'" + input.type + "'] id:'" + input.id + "' manufacturer:'" + input.manufacturer + "' name:'" + input.name + "' version:'" + input.version + "'"); } for (var entry of midiAccess.outputs) { var output = entry[1]; console.log("Output port [type:'" + output.type + "'] id:'" + output.id + "' manufacturer:'" + output.manufacturer + "' name:'" + output.name + "' version:'" + output.version + "'"); } } function onMIDIMessage(event) { var str = "MIDI message received at timestamp " + event.timestamp + "[" + event.data.length + " bytes]: "; for (var i = 0; i < event.data.length; i++) { str += "0x" + event.data[i].toString(16) + " "; } // console.log(str); // Mask off the lower nibble (MIDI channel, which we don't care about) // var channel = ev.data[0] & 0xf; switch (event.data[0] & 0xf0) { case 0x90: if (event.data[2] != 0) { // if velocity != 0, this is a note-on message // noteOn(event.data[1]); midiData[event.data[1]] = 1; break; } // if velocity == 0, fall thru: it's a note-off. MIDI's weird, y'all. case 0x80: // noteOff(event.data[1]); midiData[event.data[1]] = 0; break; } if ($('#oscPanel').length) //onscreen { $("#MIDIMessages").html(str); } } // function noteOn(noteNumber) { // } // function noteOff(noteNumber) { // } function startLoggingMIDIInput(indexOfPort) { if (midi) { for (var entry of midi.inputs) { var input = entry[1]; if (input.name == indexOfPort) { input.onmidimessage = onMIDIMessage; console.log("Connected to: " + input.name); midiIn = input.name; } else { input.onmidimessage = null; console.log("No connection to: " + input.name); } } createMIDIUniforms(); } } function sendMiddleC(midiAccess, portID) { var noteOnMessage = [0x90, 60, 0x7f]; // note on, middle C, full velocity var output = midiAccess.outputs.get(portID); output.send(noteOnMessage); //omitting the timestamp means send immediately. output.send([0x80, 60, 0x40], window.performance.now() + 1000.0); // Inlined array creation- note off, middle C, // release velocity = 64, timestamp = now + 1000ms. } window.addEventListener('load', function() { if (navigator.requestMIDIAccess) navigator.requestMIDIAccess().then(onMIDISuccess, onMIDIFailure); // System Exclusive? // navigator.requestMIDIAccess( { sysex: true } ).then( onMIDISuccess, onMIDIFailure ); });
JavaScript
0
@@ -2744,24 +2744,116 @@ break; +%0A%0A case 0xb0:%0A midiData%5Bevent.data%5B1%5D%5D = event.data%5B2%5D;%0A break; %0A %7D%0A%0A
62eed47760a012473a76a2c7a502f93099d85074
Fix a deprecation notice (#13904)
scripts/release-build.js
scripts/release-build.js
'use strict'; const fs = require('fs').promises; const path = require('path'); const directory = './build/'; const verbatimFiles = ['LICENSE', 'README.md', 'index.d.ts', 'types.d.ts']; // Returns a string representing data ready for writing to JSON file function createDataBundle() { const bcd = require('../index.js'); const string = JSON.stringify(bcd); return string; } // Returns a promise for writing the data to JSON file async function writeData() { const dest = path.resolve(directory, 'data.json'); const data = createDataBundle(); await fs.writeFile(dest, data); } async function writeIndex() { const dest = path.resolve(directory, 'index.js'); const content = `module.exports = require("./data.json");\n`; await fs.writeFile(dest, content); } // Returns an array of promises for copying of all files that don't need transformation async function copyFiles() { for (const file of verbatimFiles) { const src = path.join('./', file); const dest = path.join(directory, file); await fs.copyFile(src, dest); } } function createManifest() { const full = require('../package.json'); const minimal = { main: 'index.js' }; const minimalKeys = [ 'name', 'version', 'description', 'repository', 'keywords', 'author', 'license', 'bugs', 'homepage', 'types', ]; for (const key of minimalKeys) { if (key in full) { minimal[key] = full[key]; } else { throw `Could not create a complete manifest! ${key} is missing!`; } } return JSON.stringify(minimal); } async function writeManifest() { const dest = path.resolve(directory, 'package.json'); const manifest = createManifest(); await fs.writeFile(dest, manifest); } async function main() { // Remove existing files, if there are any await fs .rmdir(directory, { force: true, recursive: true, }) .catch(e => { // Missing folder is not an issue since we wanted to delete it anyway if (e.code !== 'ENOENT') throw e; }); // Crate a new directory await fs.mkdir(directory); await writeManifest(); await writeData(); await writeIndex(); await copyFiles(); console.log('Data bundle is ready'); } // This is needed because NodeJS does not support top-level await. // Also, make sure to log all errors and exit with failure code. main().catch(e => { console.error(e); process.exit(1); });
JavaScript
0.000207
@@ -1820,19 +1820,16 @@ %0A .rm -dir (directo
6a3548bedbe6722207d09d4ec9d9729c328c148e
Update values from curves.
editor/js/Properties.js
editor/js/Properties.js
var Properties = function ( editor ) { var container = new UI.Panel(); // signals var signals = editor.signals; editor.signals.elementSelected.add( function ( element ) { container.clear(); var elementPanel = new UI.Panel(); container.add( elementPanel ); elementPanel.add( new UI.Text( element.name ).setWidth( '90px' ).setId( 'name' ) ); elementPanel.add( new UI.HorizontalRule() ); var parameters = element.module.parameters.input; for ( var key in parameters ) { var parameter = parameters[ key ]; var parameterRow = new UI.Panel(); parameterRow.add( new UI.Text( parameter.name ).setWidth( '90px' ) ); ( function ( key ) { if ( parameter instanceof FRAME.ModuleParameter.Integer ) { var parameterValue = new UI.Integer() .setRange( parameter.min, parameter.max ) .setValue( element.parameters[ key ] ) .setWidth( '150px' ) .onChange( function () { element.parameters[ key ] = this.getValue(); signals.timelineElementChanged.dispatch( element ); } ); parameterRow.add( parameterValue ); } else if ( parameter instanceof FRAME.ModuleParameter.Float ) { var parameterValue = new UI.Number() .setRange( parameter.min, parameter.max ) .setValue( element.parameters[ key ] ) .setWidth( '150px' ) .onChange( function () { element.parameters[ key ] = this.getValue(); signals.timelineElementChanged.dispatch( element ); } ); parameterRow.add( parameterValue ); } else if ( parameter instanceof FRAME.ModuleParameter.Vector2 ) { var vectorX = new UI.Number() .setValue( element.parameters[ key ][1] ) .setWidth( '50px' ) .onChange( function () { element.parameters[ key ][0] = this.getValue(); signals.timelineElementChanged.dispatch( element ); } ); var vectorY = new UI.Number() .setValue( element.parameters[ key ][1] ) .setWidth( '50px' ) .onChange( function () { element.parameters[ key ][1] = this.getValue(); signals.timelineElementChanged.dispatch( element ); } ); parameterRow.add( vectorX ); parameterRow.add( vectorY ); } else if ( parameter instanceof FRAME.ModuleParameter.Vector3 ) { var vectorX = new UI.Number() .setValue( element.parameters[ key ][1] ) .setWidth( '50px' ) .onChange( function () { element.parameters[ key ][0] = this.getValue(); signals.timelineElementChanged.dispatch( element ); } ); var vectorY = new UI.Number() .setValue( element.parameters[ key ][1] ) .setWidth( '50px' ) .onChange( function () { element.parameters[ key ][1] = this.getValue(); signals.timelineElementChanged.dispatch( element ); } ); var vectorZ = new UI.Number() .setValue( element.parameters[ key ][2] ) .setWidth( '50px' ) .onChange( function () { element.parameters[ key ][2] = this.getValue(); signals.timelineElementChanged.dispatch( element ); } ); parameterRow.add( vectorX ); parameterRow.add( vectorY ); parameterRow.add( vectorZ ); } else if ( parameter instanceof FRAME.ModuleParameter.String ) { var parameterValue = new UI.Input() .setValue( element.parameters[ key ] ) .setWidth( '150px' ) .onKeyUp( function () { element.parameters[ key ] = this.getValue(); signals.timelineElementChanged.dispatch( element ); } ); parameterRow.add( parameterValue ); } else if ( parameter instanceof FRAME.ModuleParameter.Color ) { var parameterValue = new UI.Color() .setHexValue( element.parameters[ key ] ) .setWidth( '150px' ) .onChange( function () { element.parameters[ key ] = this.getHexValue(); signals.timelineElementChanged.dispatch( element ); } ); parameterRow.add( parameterValue ); } } )( key ); elementPanel.add( parameterRow ); }; } ); return container; }
JavaScript
0
@@ -112,16 +112,52 @@ gnals;%0A%0A +%09var selected = null;%0A%09var values;%0A%0A %09editor. @@ -227,24 +227,62 @@ r.clear();%0A%0A +%09%09selected = element;%0A%09%09values = %7B%7D;%0A%0A %09%09var elemen @@ -522,14 +522,8 @@ ters -.input ;%0A%0A%09 @@ -595,16 +595,56 @@ key %5D;%0A%0A +%09%09%09if ( parameter === null ) continue;%0A%0A %09%09%09var p @@ -1190,32 +1190,70 @@ ameterValue );%0A%0A +%09%09%09%09%09values%5B key %5D = parameterValue;%0A%0A %09%09%09%09%7D else if ( @@ -1658,32 +1658,70 @@ ameterValue );%0A%0A +%09%09%09%09%09values%5B key %5D = parameterValue;%0A%0A %09%09%09%09%7D else if ( @@ -4218,16 +4218,229 @@ %0A%09%7D );%0A%0A +%09editor.signals.timeChanged.add( function () %7B%0A%0A%09%09if ( selected !== null ) %7B%0A%0A%09%09%09var element = selected;%0A%0A%09%09%09for ( var key in values ) %7B%0A%0A%09%09%09%09values%5B key %5D.setValue( element.parameters%5B key%5D );%0A%0A%09%09%09%7D%0A%0A%09%09%7D%0A%0A%09%7D );%0A%0A %09return
231173a99ffe129efac872a6646e61684924c309
Fix babel always enabled HMR
src/internals/webpack/features/babel.js
src/internals/webpack/features/babel.js
import findCacheDir from 'find-cache-dir'; import findBabelConfig from 'find-babel-config'; import frameworkMetadata from '../../../shared/framework-metadata'; import { resolveProject } from '../../../shared/resolve'; import { getDefault } from '../../../shared/util/ModuleUtil'; import BaseFeature from '../BaseFeature'; export default class BabelFeature extends BaseFeature { getFeatureName() { return 'babel'; } visit(webpack) { webpack.injectRules({ test: BaseFeature.FILE_TYPE_JS, loader: 'babel-loader', exclude: /node_modules/, options: this.getTransformedBabelConfig(), }); } getTransformedBabelConfig() { const config = this.getBabelConfig(); // use the app's .babelrc if (!config) { return config; } if (this.isDev) { config.presets.push('react-hmre'); } // This is a feature of `babel-loader` for webpack (not Babel itself). // It enables caching build results in ./node_modules/.cache/reworkjs/babel // directory for faster rebuilds. We use findCacheDir() because of: // https://github.com/facebookincubator/create-react-app/issues/483 config.cacheDirectory = `${findCacheDir({ name: frameworkMetadata.name, })}/babel`; return config; } getBabelConfig() { // FIXME note: might break with Babel 7 due to new support for babelrc.js const { config } = findBabelConfig.sync(resolveProject('.')); if (config == null) { return getDefault(this.getOptionalDependency('@reworkjs/babel-preset-reworkjs'))(); } // no need to load it, babel will do it on its own. return null; } }
JavaScript
0
@@ -795,16 +795,18 @@ is.isDev +() ) %7B%0A
c980d16691cc1b13f9cbf76c2d3819cbe674df66
enable source maps on production
config/webpack.js
config/webpack.js
import path from './path' import * as Env from './env' import webpack from 'webpack' import ProgressPlugin from '../src/hacks/webpack-progress' let config = { context: path('src'), resolve: { alias: { bemuse: path('src'), }, extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx'] }, resolveLoader: { alias: { bemuse: path('src'), }, }, entry: { boot: './boot' }, output: { path: path('dist', 'build'), publicPath: 'build/', filename: '[name].js', chunkFilename: '[name]-[chunkhash].js', }, devServer: { contentBase: false, publicPath: '/build/', stats: { colors: true }, }, module: { loaders: [ { test: /\.jsx?$/, include: [path('src'), path('spec')], loader: 'babel?modules=common&experimental=true', }, { test: /\.pegjs$/, loader: 'pegjs', }, { test: /\.scss$/, loader: 'style!css!autoprefixer?browsers=last 2 version' + '!sass?outputStyle=expanded' + '!bemuse/hacks/sass-import-rewriter', }, { test: /\.css$/, loader: 'style!css!autoprefixer?browsers=last 2 version', }, { test: /\.jade$/, loader: 'jade', }, { test: /\.png$/, loader: 'url-loader?limit=100000&mimetype=image/png', }, { test: /\.jpg$/, loader: 'file-loader', }, { test: /\.(?:mp3|mp4|ogg|m4a)$/, loader: 'file-loader', }, { test: /\.(otf|eot|svg|ttf|woff|woff2)(?:$|\?)/, loader: 'url-loader?limit=8192' }, ], postLoaders: [], preLoaders: [], }, plugins: [ new CompileProgressPlugin(), new ProgressPlugin(), ], } function CompileProgressPlugin() { var old = '' return new webpack.ProgressPlugin(function(percentage, message) { var text = '[' for (var i = 0; i < 20; i++) text += percentage >= i / 20 ? '=' : ' ' text += '] ' + message var clear = '' for (i = 0; i < old.length; i++) clear += '\r \r' process.stderr.write(clear + text) old = text }) } if (process.env.SOURCE_MAPS === 'true') { config.devtool = 'source-map' } if (Env.test() || process.env.BEMUSE_COV === 'true') { config.module.preLoaders.push({ test: /\.js$/, include: [path('src')], exclude: [ path('src', 'test'), path('src', 'polyfill'), path('src', 'boot', 'loader.js'), ], loader: 'isparta-instrumenter', }) } if (Env.production()) { config.plugins.push( new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.OccurenceOrderPlugin() ) } export default config
JavaScript
0.000001
@@ -2186,16 +2186,17 @@ %0A %7D)%0A%7D%0A +%0A if (proc @@ -2217,32 +2217,52 @@ _MAPS === 'true' + %7C%7C Env.production() ) %7B%0A config.dev
abc24a1bf969fbac588078e056ffc238c8b04a3a
Revert "Apply eslint feedback to models/question.js."
models/question.js
models/question.js
function exports(sequelize, DataTypes) { const Question = sequelize.define('Question', { title: DataTypes.TEXT, }, { classMethods: { associate(models) { // associations can be defined here models.Question.hasMany(models.Choice); models.Question.hasMany(models.Response); }, }, }); return Question; } module.exports = exports;
JavaScript
0
@@ -1,12 +1,43 @@ +'use strict';%0Amodule.exports = function exp @@ -32,24 +32,16 @@ function - exports (sequeli @@ -63,13 +63,11 @@ %7B%0A -const +var Que @@ -130,17 +130,16 @@ pes.TEXT -, %0A %7D, %7B%0A @@ -173,16 +173,26 @@ ssociate +: function (models) @@ -348,16 +348,14 @@ %7D -, %0A %7D -, %0A %7D @@ -381,32 +381,6 @@ n;%0A%7D -%0A%0Amodule.exports = exports ;%0A
9eaa87d917bd85a0c17323ee471b71394ec91dca
Add content-length header information to file post
tasks/lib/servlet.js
tasks/lib/servlet.js
var fs = require("fs"); var path = require("path"); var util = require("util"); var request = require("request"); /** * Remove the trailing slash from a URL path. * @param {String} path The path to be normalized. * @return {String} The normalized path. */ function removeTrailingSlash(path) { if (path === "/") { return path; } if (path.slice(-1) === "/") { return path.slice(0, -1); } return path; } /** * Normalize properties to be sent to Sling via the POST Servlet. In * particular, for each array property, make sure that a "@TypeHint" exists to * create a JCR multi-value property on the server. * @param {Object} properties Properties to be normalized. * @return {Object} Normalized properties. */ function normalizeProperties(properties) { var arrays = Object.keys(properties).filter(function (name) { return util.isArray(properties[name]); }); var typeHints = arrays.map(function (name) { return name + "@TypeHint"; }); typeHints.forEach(function (typeHint) { if (!properties[typeHint]) { properties[typeHint] = "String[]"; } }); return properties; } /** * Append a property to the form. Ensures that property values and multi-value * properties are converted in the correct way. * @param {Object} form Form to append the properties to. * @param {String} name Name of the property. * @param {Object} value Value of the property. */ function appendProperty(form, name, value) { if (util.isArray(value)) { value.forEach(function (value) { form.append(name, value); }); } else if (typeof value === "boolean") { form.append(name, value ? "true" : "false"); } else { form.append(name, value); } } /** * Creates a wrapper around the Sling POST Servlet. * @param {Object} options Options containing the host and port of the Sling * instance and the user name and password to use to post content. */ function Post(options) { this.host = options.host; this.port = options.port; this.user = options.user; this.pass = options.pass; } exports.Post = Post; /** * Return the URL for a given path. The URL will have a correct protocol, host * and port. * @param {String} path Path to be added to the URL. * @return {String} A full URL targeting the given path on the configured * Sling instance. */ Post.prototype.getUrl = function (path) { return "http://" + this.host + ":" + this.port + path; }; /** * Create an authorization object to authorize the request. * @return {Object} Authorization object. */ Post.prototype.getAuth = function () { return { user: this.user, pass: this.pass }; }; /** * Create default options to add to each reqest. Default options include the * URL to post to, "Accept" header to always request a JSON response, proxy * configuration and authorization informtion. * @param {String} path Path to send the request to. * @return {Object} Options to be added to each request. */ Post.prototype.getDefaultOptions = function (path) { return { url: this.getUrl(removeTrailingSlash(path)), headers: { "Accept": "application/json" }, proxy: process.env.http_proxy, auth: this.getAuth() }; }; /** * Create a node in the Sling instance. * @param {String} path Path of the node to create. * @param {Object} properties Properties of the node. * @param {Function} callback Callback to be invoked when the creation is * complete. */ Post.prototype.create = function (path, properties, callback) { // Create the request var req = request.post(this.getDefaultOptions(path), callback); // Add request properties properties = normalizeProperties(properties); // Add form only if fields must be submitted var names = Object.keys(properties); if (names.length === 0) { return; } var form = req.form(); names.forEach(function (name) { appendProperty(form, name, properties[name]); }); }; /** * Create a file in the Sling instance. * @param {String} parent Path of the parent node of the newly created * file. * @param {String} file Path to a file on the local filesystem. * @param {Object} properties Properties to add to the file node. * @param {Function} callback Callback to be invoked when the creation is * complete. */ Post.prototype.createFile = function (parent, file, properties, callback) { var self = this; // Create the request var req = request.post(this.getDefaultOptions(parent), callback); // Add form var form = req.form(); // Add file content var name = path.basename(file); appendProperty(form, "./" + name, fs.createReadStream(file)); // Add request properties properties = normalizeProperties(properties); Object.keys(properties).forEach(function (key) { appendProperty(form, "./" + name + "/" + key, properties[key]); }); }; /** * Import content into the Sling instance. * @param {String} parent Path of the parent node of the subtree to import. * @param {String} name Name of the node to create, represented by the * content file. * @param {String} file Path to the content file. * @param {String} type Type of the import to perform. * @param {Object} properties Additional properties driving the import * operation. * @param {Function} callback Callback to invoke when the import is complete. */ Post.prototype.importContent = function (parent, name, file, type, properties, callback) { var self = this; // Create the request var req = request.post(this.getDefaultOptions(parent), callback); // Add form var form = req.form(); appendProperty(form, ":operation", "import"); // Add file content appendProperty(form, ":name", name); appendProperty(form, ":contentFile", fs.createReadStream(file)); appendProperty(form, ":contentType", type); // Add optional properties if (properties.checkin) { appendProperty(form, ":checkin", properties.checkin); } if (properties.autoCheckout) { appendProperty(form, ":autoCheckout", properties.autoCheckout); } if (properties.replace) { appendProperty(form, ":replace", properties.replace); } if (properties.replaceProperties) { appendProperty(form, ":replaceProperties", properties.replaceProperties); } };
JavaScript
0
@@ -1467,16 +1467,84 @@ operty.%0A + * @param %7BObject%7D %5Boptions%5D property for form element is optional%0A */%0Afunc @@ -1576,24 +1576,33 @@ name, value +, options ) %7B%0A if ( @@ -1861,24 +1861,33 @@ (name, value +, options );%0A %7D%0A%7D%0A%0A @@ -4913,16 +4913,66 @@ am(file) +, %7B%0A knownLength:fs.statSync(file).size%0A %7D );%0A%0A @@ -5174,32 +5174,96 @@ %5Bkey%5D);%0A %7D);%0A + req.setHeader('Content-Length', form.getLengthSync(false));%0A %7D;%0A%0A/**%0A * Impor
da8ac050226f835b0034b37f50c739718fd2aa20
Put emoji after numbers in decklist info
formatting.js
formatting.js
'use strict'; var colours = require('./colours.json'); var headings = [ ['Event', 'Hardware', 'Resource', 'Agenda', 'Asset', 'Upgrade', 'Operation'], ['Icebreaker', 'Program', 'ICE'] ]; var stats = [ ['baselink', ' :_link:'], ['cost', ':_credit:'], ['memoryunits', ' :_mu:'], ['strength', ' str'], ['trash', ' :_trash:'], ['advancementcost', ' :_advance:'], ['minimumdecksize', ' :_deck:'], ['influencelimit', '•'], ['agendapoints', ' :_agenda:'] ]; function influenceDots (influence) { var dots = ''; for (var i = 0; i < influence; i++) { dots += '•'; } return dots; } exports.formatDecklist = (decklist) => { var o = {text: '', attachments:[{mrkdwn_in: ['pretext', 'fields']}]}; var faction = decklist.cards.Identity[0].card.faction; var usedInfluence = 0; var decksize = 0; var agendapoints = 0; var fields = []; o.text = this.formatTitle(decklist.name, decklist.url); for (var f in headings) { fields[f] = {title: '', value: '', short: true}; for (var t in headings[f]) { var type = headings[f][t]; if (decklist.cards[type]) { if (t) { fields[f].value += '\n\n'; } fields[f].value += this.formatTitle(type); for (var i in decklist.cards[type]) { var card = decklist.cards[type][i]; fields[f].value += '\n' + card.quantity; fields[f].value += ' × ' + card.card.title; decksize += card.quantity; if (card.card.agendapoints) { agendapoints += card.card.agendapoints * card.quantity; } if (card.card.faction !== faction) { var inf = card.quantity * card.card.factioncost; fields[f].value += ' ' + influenceDots(inf); usedInfluence += inf; } } } } } o.attachments[0].color = colours[faction.replace(/[-\s].*/, '').toLowerCase()]; o.attachments[0].fields = fields; o.attachments[0].pretext = this.formatTitle(decklist.cards.Identity[0].card.title); o.attachments[0].pretext += '\n:_deck: ' + decksize + ' (min '; o.attachments[0].pretext += decklist.cards.Identity[0].card.minimumdecksize; o.attachments[0].pretext += ') - ' + usedInfluence + '/'; o.attachments[0].pretext += decklist.cards.Identity[0].card.influencelimit + '•'; o.attachments[0].pretext += ' - :_agenda: ' + agendapoints; return o; }; exports.formatCards = (cards) => { var o = {text:'', attachments:[]}; for (var i = 0; i < cards.length; i++) { var a = {pretext: '', mrkdwn_in: ['pretext', 'text']}; var faction = cards[i].faction.replace(/(\s|-).*/, '').toLowerCase(); var title = cards[i].title; if (cards[i].uniqueness){ title = '◆ ' + title; } if (i === 0) { o.text = this.formatTitle(title, cards[0].url); } else { a.pretext = this.formatTitle(title, cards[i].url) + '\n'; } a.pretext += '*\u200b' + cards[i].type; if (cards[i].subtype ) { a.pretext += ':\u200b* ' + cards[i].subtype; } else { a.pretext += '\u200b*'; } a.pretext += ' - :_' + faction + ':'; if (cards[i].factioncost) { a.pretext += influenceDots(cards[i].factioncost); } a.pretext += '\n'; var first = true; if (cards[i].type === 'Asset' || cards[i].type === 'Upgrade' || cards[i].type === 'ICE') { stats[1][1] = ':_rez:'; } else { stats[1][1] = ':_credit:'; } for (var j = 0; j < stats.length; j++) { if (cards[i][stats[j][0]] || cards[i][stats[j][0]] === 0) { if (!first) { a.pretext += ' - '; } a.pretext += cards[i][stats[j][0]] + stats[j][1]; first = false; } else if (cards[i].type === 'Identity' && stats[j][0] === 'influencelimit' && !cards[i].influencelimit) { a.pretext += ' - ∞•'; } } a.pretext = a.pretext.replace(/(\d|X)\s*:_mu:/gi, function (x) { return x.replace(/(.).*/, ':_$1mu:').toLowerCase(); }); a.color = colours[faction]; if (cards[i].text) { a.text = this.formatText(cards[i].text); } o.attachments.push(a); } return o; } exports.formatText = (text) => { if (!text) return text; text = text.replace(/\r\n/g, '\n'); text = text.replace(/\[Credits\]/g, ':_credit:'); text = text.replace(/\[Recurring Credits\]/g, ':_recurring-credit:'); text = text.replace(/\[Click\]/g, ':_click:'); text = text.replace(/\[Link\]/g, ':_link:'); text = text.replace(/\[Trash\]/g, ':_trash:'); text = text.replace(/\[Subroutine\]/g, ':_subroutine:'); text = text.replace(/(\d|X)\s*\[Memory Unit\]/gi, function (x) { return x.replace(/(.).*/, ':_$1mu:').toLowerCase(); }); text = text.replace(/\[Memory Unit\]/g, ':_mu:'); text = text.replace(/<strong>/g, '*\u200b'); text = text.replace(/<\/strong>/g, '\u200b*'); text = text.replace(/<sup>(?:\d|X)+<\/sup>/gi, function(x){ x = x.replace(/<sup>|<\/sup>/g, ''); x = x.replace(/X/i,'ˣ'); x = x.replace(/\d/g, function(d){ return ['⁰','¹','²','³','⁴','⁵','⁶','⁷','⁸','⁹'][parseInt(d)]; }); return x; }); text = text.replace(/&/g, '&amp;'); text = text.replace(/</g, '&lt;'); text = text.replace(/>/g, '&gt;'); return text; } exports.formatTitle = (title, url) => { title = '*\u200b' + title + '\u200b*'; if (url && url !== '') { return '<' + url + '|' + title + '>'; } return title; }
JavaScript
0.00002
@@ -2315,16 +2315,8 @@ '%5Cn -:_deck: ' + @@ -2327,16 +2327,24 @@ size + ' + :_deck: (min '; @@ -2609,26 +2609,16 @@ t += ' - - :_agenda: ' + age @@ -2626,16 +2626,31 @@ dapoints + + ' :_agenda:' ;%0A re
73f357e4ed6f4e62a196282ce74a9ce43dba0630
Update moves.js
mods/nuv2/moves.js
mods/nuv2/moves.js
exports.BattleMovedex = { "waterpulse": { inherit: true, basePower: 80 } }, "submission": { inherit: true, accuracy: 100, basePower: 120, category: "Physical", secondary: { chance: 10, volatileStatus: 'flinch' } }, "lunardance": { num: 461, accuracy: true, basePower: 0, category: "Status", desc: "The user faints and the Pokemon brought out to replace it has its HP and PP fully restored along with having any major status condition cured. Fails if the user is the last unfainted Pokemon in its party.", shortDesc: "User faints. Replacement is fully healed, with PP.", id: "lunardance", isViable: true, name: "Lunar Dance", pp: 20, priority: 0, isSnatchable: true, boosts: { spa: 1, spe: 1, }, secondary: false, target: "self", type: "Psychic" }, "airslash": { inherit: true, basePower: 90, } }, };
JavaScript
0.000001
@@ -949,17 +949,16 @@ %09%09spe: 1 -, %0A%09%09%7D,%0A%09%09
6fb1c4085b460c3e39c74f0d31ba45b8441d6df4
Properly forward NODE_ENV in as process.env.NODE_ENV
webpack/_common.config.js
webpack/_common.config.js
const { DefinePlugin, ProgressPlugin } = require("webpack"); const {CheckerPlugin} = require("awesome-typescript-loader"); const ScriptExtHtmlWebpackPlugin = require("script-ext-html-webpack-plugin"); const { root, DEFAULT_RESOLVE_EXTENSIONS, NODE_CONFIG, getHtmlTemplatePlugin, getLoaderOptionsPlugin, getPerformanceOptions, getDefaultContextReplacementPlugin, RULE_LIB_SOURCE_MAP_LOADING, RULE_TS_LOADING, RULE_HTML_LOADING, RULE_MAIN_SASS_LOADING, RULE_COMPONENT_SASS_LOADING } = require("./constants"); /** * It might seem a little bit suspicious to use a mode-specific parameterized function in a "common" * config part. However, there are some plugins (HTML, LoaderOptions, ...) that cannot be easily merged, * even if provided by different modes, since only the parameters passed to them differ and not the plugins * themselves. Thus, we're using the `isDev` parameter to determine the exact target mode and simplify the * option details this way. * @param isDev Indicates whether development mode was selected or not. * @param useAot Indicates whether aot mode was selected or not. */ module.exports = function (isDev, useAot) { const plugins = [ // HTML plugin to generate proper index.html files w.r.t. the output of this build. getHtmlTemplatePlugin(isDev), new ScriptExtHtmlWebpackPlugin({ defaultAttribute: "defer" }), // Plugin to provide options to our loaders. getLoaderOptionsPlugin(isDev), /** * Plugin to define several variables. * Note: Webpack is capable of conditionally dropping code w.r.t. these variables. * E.g. if a variable `ENV` is defined as `"whatever"`, and you have some code like: * * if (ENV !== "whatever") {...} * * Then the code inside the braces will be dropped during the bundle process. * We're using this for conditionally executing development / production code. */ new DefinePlugin({ ENV: JSON.stringify(process.env.NODE_ENV || "development") }), // Plugin for displaying bundle process stage. new ProgressPlugin(), // Plugin of atl. to improve build and type checking speed; Will be included by default in the next major version. new CheckerPlugin() ]; if (!useAot) { // Fix the angular2 context w.r.t. to webpack and the usage of System.import in their "load a component lazily" code. // Note: Since a version > 1.2.4 of the @ngtools/webpack plugin, the context replacement conflicts with it (seems to deal with it itself). // Thus, we only add this plugin in case we're NOT aiming at AoT compilation. plugins.push(getDefaultContextReplacementPlugin()); } return { entry: { bundle: root("src/main.ts") }, /** * Options affecting the resolving of modules. * * See: http://webpack.github.io/docs/configuration.html#resolve */ resolve: { /** * An array of extensions that should be used to resolve modules. * Note that this only affects files that are referenced <without> a particular extension. * * See: http://webpack.github.io/docs/configuration.html#resolve-extensions */ extensions: DEFAULT_RESOLVE_EXTENSIONS }, /** * Options affecting the normal modules. * * See: http://webpack.github.io/docs/configuration.html#module */ module: { /** * An array of rules to be applied.. * Note that the syntax has changed in 2.1.0-beta.24 : https://github.com/webpack/webpack/releases/tag/v2.1.0-beta.24 * Since this release, you no longer have to define preloaders and postloaders separately; just add * `enforce: "pre"` or `enforce: "post"` to a particular rule. * * See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders */ rules: [ RULE_LIB_SOURCE_MAP_LOADING, RULE_TS_LOADING, // This will get overridden by RULE_TS_AOT_LOADING if AoT mode is activated. RULE_HTML_LOADING, RULE_MAIN_SASS_LOADING(isDev), RULE_COMPONENT_SASS_LOADING ] }, /** * Include polyfills or mocks for various node stuff * * See: https://webpack.github.io/docs/configuration.html#node */ node: NODE_CONFIG, /** * Any plugins to be used in this build. * * See: http://webpack.github.io/docs/configuration.html#plugins */ plugins: plugins, performance: getPerformanceOptions(!isDev) }; };
JavaScript
0.998045
@@ -1669,32 +1669,272 @@ veral variables. + %22process.env.NODE_ENV%22 is forwarded so that libraries may%0A * react on it (e.g. by skipping some of their code). Please keep in mind that this is only possible%0A * since our node config enables shimming the %22process%22 variable.%0A * %0A * Note: We @@ -2409,16 +2409,120 @@ opment%22) +,%0A %22process.env%22: %7B%0A NODE_ENV: JSON.stringify(process.env.NODE_ENV %7C%7C %22development%22)%0A %7D %0A %7D),
db2f5186a6abf20b4bdab6628671ab5da38a0c3a
Make ships slower
src/common/Ship.js
src/common/Ship.js
'use strict'; const Serializer = require('incheon').serialize.Serializer; const DynamicObject = require('incheon').serialize.DynamicObject; const Point = require('incheon').Point; class Ship extends DynamicObject { static get netScheme() { return Object.assign({ showThrust: { type: Serializer.TYPES.INT32 } }, super.netScheme); } toString() { return `${this.isBot?'Bot':'Player'}::Ship::${super.toString()}`; } get bendingAngleLocalMultiple() { return 0.0; } copyFrom(sourceObj) { super.copyFrom(sourceObj); this.showThrust = sourceObj.showThrust; } syncTo(other) { super.syncTo(other); this.showThrust = other.showThrust; } constructor(id, gameEngine, x, y) { super(id, x, y); this.class = Ship; this.gameEngine = gameEngine; this.showThrust = 0; }; destroy() { if (this.fireLoop) { this.fireLoop.destroy(); } } get maxSpeed() { return 5.0; } attachAI() { this.isBot = true; this.gameEngine.on('preStep', ()=>{ this.steer(); }); let fireLoopTime = Math.round(250 + Math.random() * 100); this.fireLoop = this.gameEngine.timer.loop(fireLoopTime, () => { if (this.target && this.distanceToTarget(this.target) < 400) { this.gameEngine.makeMissile(this); } }); } distanceToTarget(target) { let dx = this.x - target.x; let dy = this.y - target.y; return Math.sqrt(dx * dx + dy * dy); } steer() { let closestTarget = null; let closestDistance = Infinity; for (let objId of Object.keys(this.gameEngine.world.objects)) { let obj = this.gameEngine.world.objects[objId]; let distance = this.distanceToTarget(obj); if (obj != this && distance < closestDistance) { closestTarget = obj; closestDistance = distance; } } this.target = closestTarget; if (this.target) { let desiredVelocity = new Point(); desiredVelocity.copyFrom(this.target).subtract(this.x, this.y); let turnRight = -shortestArc(Math.atan2(desiredVelocity.y, desiredVelocity.x), Math.atan2(Math.sin(this.angle*Math.PI/180), Math.cos(this.angle*Math.PI/180))); if (turnRight > 0.05) { this.isRotatingRight = true; } else if (turnRight < -0.05) { this.isRotatingLeft = true; } else { this.isAccelerating = true; this.showThrust = 5; } } } } function shortestArc(a, b) { if (Math.abs(b-a) < Math.PI) return b-a; if (b>a) return b-a-Math.PI*2; return b-a+Math.PI*2; } module.exports = Ship;
JavaScript
0.000301
@@ -1025,17 +1025,17 @@ return -5 +3 .0; %7D%0A%0A
075e1e2c933cfa30d41b124d08136a5c551ad363
Add percentage to sentiment
modules/concern.js
modules/concern.js
/** * concern.js * * !concern * Toggles whether the bot should interrupt charged conversations * with an unhelpful message. */ var isEmotional = require('emotional_alert') var nox = false var verbose = false // TODO: cvar module.exports = { commands: { sentiment: { help: 'Runs a phrase through very nuanced sentiment analysis', command: (bot, msg) => { let result = isEmotional(msg.body) if (result.bayes.prediction) return result.bayes.prediction return 'no sentiment found' } }, rawconcern: { help: 'Runs a phrase through the emotional alert system', command: (bot, msg) => { return JSON.stringify(isEmotional(msg.body)) } }, concern: { help: 'Toggles announcements of concern', command: function () { if (!nox) { nox = true return 'adopting air of unconcern' } nox = false return 'concerning myself with matters' } } }, events: { message: function (bot, nick, to, text) { if (!nox) { var x = isEmotional(text) if (x.emotional) { if (x.winner) { var adj = { 0: '', 1: 'slightly ', 2: 'rather ', 3: 'quite ', 4: 'very ', 5: 'extremely ', 6: 'copiously ', 7: 'agonizingly ' } x.adj = adj[x.emotional] === undefined ? 'a tad ' : adj[x.emotional] switch (x.winner) { case 'anger': x.hwinner = 'angry' break case 'stress': x.hwinner = 'stressed' break case 'sad': /* falls through */ default: x.hwinner = x.winner } bot.shout(to, nick + ': you seem ' + x.adj + x.hwinner + ' (score: ' + x.emotional + ')') } else if (verbose) { // danger phrase bot.shout(to, nick + ': that is a worrying thing to say') } } } } } }
JavaScript
0.999979
@@ -187,16 +187,51 @@ = false%0A +var colors = require('irc').colors%0A var verb @@ -256,16 +256,16 @@ O: cvar%0A - %0Amodule. @@ -478,51 +478,222 @@ ayes -.prediction) return result.bayes.prediction +) %7B%0A let percentage = (result.bayes.proba * 100).toFixed(2)%0A return %5B%0A result.bayes.prediction,%0A colors.wrap('light_gray', %60($%7Bpercentage%7D%25)%60)%0A %5D.join(' ')%0A %7D %0A
e594c41dc2a51be0b9aed0c23a64a39cb866c17b
Remove test.only
test.js
test.js
'use strict' var test = require('tape') var read = require('read-all-stream') var toStream = require('string-to-stream') var child = require('child_process') var htmlify = require('./') test.only('api', function (t) { t.plan(3) var html = toStream('var foo = "bar"').pipe(htmlify()) read(html, 'utf8', function (err, html) { if (err) return t.end(err) t.ok(/<html>/.test(html)) t.ok(~html.indexOf('var foo = "bar"')) t.notOk(~html.indexOf('inline')) }) }) test('cli', function (t) { t.plan(1) child.exec('echo "THESCRIPT" | node cli.js', function (err, stdout) { if (err) return t.end(err) t.ok(~stdout.indexOf('THESCRIPT')) }) })
JavaScript
0.000001
@@ -189,13 +189,8 @@ test -.only ('ap
e05f001cc78be58b3b126aed9878f74222127479
Check for property and value support for CSS custom properites (#2387)
feature-detects/css/customproperties.js
feature-detects/css/customproperties.js
/*! { "name": "CSS Custom Properties", "property": "customproperties", "caniuse": "css-variables", "tags": ["css"], "builderAliases": ["css_customproperties"], "notes": [{ "name": "MDN Docs", "href": "https://developer.mozilla.org/en-US/docs/Web/CSS/--*" },{ "name": "W3C Spec", "href": "https://drafts.csswg.org/css-variables/" }] } !*/ define(['Modernizr'], function(Modernizr) { var supportsFn = (window.CSS && window.CSS.supports.bind(window.CSS)) || (window.supportsCSS); Modernizr.addTest('customproperties', !!supportsFn && supportsFn('--f:0')); });
JavaScript
0
@@ -560,16 +560,17 @@ tsFn && +( supports @@ -580,15 +580,40 @@ '--f:0') + %7C%7C supportsFn('--f', 0)) );%0A%7D);%0A
b0c8d20c6e20db218c2a7afea4f18dada911aa70
document behaviour of entrypoint adder method
webpack/addEntrypoints.js
webpack/addEntrypoints.js
/** * Merge in `entry` array to a webpack config * * @see withEntry.js * * @package: Everledger JS Toolchain * @author: pospi <[email protected]> * @since: 2016-10-06 * @flow */ const { curry } = require('ramda'); const rConcatArrayKey = require('../helpers/rConcatArrayKey'); module.exports = curry(entryFile => rConcatArrayKey('entry', entryFile));
JavaScript
0
@@ -42,24 +42,410 @@ k config%0A *%0A + * :WARNING: the order in which you apply multiple calls to this method matters!%0A * Webpack is rather particular about the order of entrypoints.%0A * We do the concatenation in reverse so that entries added later come last, which%0A * means the final (app-specific) entrypoint can be added in the dependant project%0A * after all the core entrypoints have been injected in shared configs.%0A *%0A * @see with
2db35c8b61b5e50b5095747d016e78ddbdd10201
Remove console.log
scripts/build-data.js
scripts/build-data.js
"use strict"; const fs = require("fs"); const path = require("path"); const flatten = require("lodash/flatten"); const flattenDeep = require("lodash/flattenDeep"); const mapValues = require("lodash/mapValues"); const pluginFeatures = require("../data/plugin-features"); const builtInFeatures = require("../data/built-in-features"); const renameTests = (tests, getName) => tests.map((test) => Object.assign({}, test, { name: getName(test.name) })); const es6Data = require("compat-table/data-es6"); const es6PlusData = require("compat-table/data-es2016plus"); const envs = require("compat-table/environments"); const environments = [ "chrome", "opera", "edge", "firefox", "safari", "node", "ie", "android", "ios", "phantom" ]; const envMap = { safari51: "safari5", safari71_8: "safari8", safari10_1: "safari10.1", firefox3_5: "firefox3", firefox3_6: "firefox3", node010: "node0.10", node012: "node0.12", iojs: "node3.3", node64: "node6", node65: "node6.5", node76: "node7.6", android40: "android4.0", android41: "android4.1", android42: "android4.2", android43: "android4.3", android44: "android4.4", android50: "android5.0", android51: "android5.1", ios51: "ios5.1", }; const invertedEqualsEnv = Object.keys(envs) .filter((b) => envs[b].equals) .reduce((a, b) => { const checkEnv = envMap[envs[b].equals] || envs[b].equals; environments.some((env) => { const version = parseInt(checkEnv.replace(env, ""), 10); if (!isNaN(version)) { Object.keys(envs).forEach((equals) => { const equalsVersion = parseInt(equals.replace(env, ""), 10); if (equalsVersion <= version) { if (!a[equals]) a[equals] = []; a[equals].push(b); } }); return true; } }); return a; }, {}); invertedEqualsEnv.safari8 = ["ios9"]; const compatibilityTests = flattenDeep([ es6Data, es6PlusData, ].map((data) => data.tests.map((test) => { return test.subtests ? [test, renameTests(test.subtests, (name) => test.name + " / " + name)] : test; }) )); console.log(invertedEqualsEnv); const getLowestImplementedVersion = ({ features }, env) => { const tests = flatten(compatibilityTests .filter((test) => { return features.indexOf(test.name) >= 0 || // for features === ["DataView"] // it covers "DataView (Int8)" and "DataView (UInt8)" features.length === 1 && test.name.indexOf(features[0]) === 0; }) .map((test) => { const isBuiltIn = test.category === "built-ins" || test.category === "built-in extensions"; return test.subtests ? test.subtests.map((subtest) => ({ name: `${test.name}/${subtest.name}`, res: subtest.res, isBuiltIn })) : { name: test.name, res: test.res, isBuiltIn }; }) ); const envTests = tests .map(({ res: test, name, isBuiltIn }, i) => { // Babel itself doesn't implement the feature correctly, // don't count against it // only doing this for built-ins atm if (!test.babel && isBuiltIn) { return "-1"; } // `equals` in compat-table Object.keys(test).forEach((t) => { const invertedEnvs = invertedEqualsEnv[envMap[t] || t]; if (invertedEnvs) { invertedEnvs.forEach((inv) => { test[inv] = test[t]; }); } }); return Object.keys(test) .filter((t) => t.startsWith(env)) // Babel assumes strict mode .filter((test) => tests[i].res[test] === true || tests[i].res[test] === "strict") // normalize some keys .map((test) => envMap[test] || test) .filter((test) => !isNaN(parseInt(test.replace(env, "")))) .shift(); }); const envFiltered = envTests.filter((t) => t); if (envTests.length > envFiltered.length || envTests.length === 0) { // envTests.forEach((test, i) => { // if (!test) { // // print unsupported features // if (env === 'node') { // console.log(`ENV(${env}): ${tests[i].name}`); // } // } // }); return null; } return envTests .map((str) => Number(str.replace(env, ""))) .reduce((a, b) => { return (a < b) ? b : a; }); }; const generateData = (environments, features) => { return mapValues(features, (options) => { if (!options.features) { options = { features: [options] }; } const plugin = {}; environments.forEach((env) => { const version = getLowestImplementedVersion(options, env); if (version !== null) { plugin[env] = version; } }); // add opera if (plugin.chrome) { if (plugin.chrome >= 28) { plugin.opera = plugin.chrome - 13; } else if (plugin.chrome === 5) { plugin.opera = 12; } } return plugin; }); }; fs.writeFileSync( path.join(__dirname, "../data/plugins.json"), JSON.stringify(generateData(environments, pluginFeatures), null, 2) + "\n" ); fs.writeFileSync( path.join(__dirname, "../data/built-ins.json"), JSON.stringify(generateData(environments, builtInFeatures), null, 2) + "\n" );
JavaScript
0.000004
@@ -2123,41 +2123,8 @@ );%0A%0A -console.log(invertedEqualsEnv);%0A%0A cons
5ef67b34d911cb245c77d221a2358352a12d0910
Changing 409 to 400
features/step_definitions/mypassword.js
features/step_definitions/mypassword.js
const { defineSupportCode } = require('cucumber'); const chai = require('chai'); const dhis2 = require('../support/utils.js'); const assert = chai.assert; defineSupportCode(function ({Given, When, Then, Before, After}) { Before({tags: '@createUser'}, function () { this.userId = dhis2.generateUniqIds(); this.requestData = { id: this.userId, firstName: 'Bobby', surname: 'Tables', userCredentials: { username: 'bobby', password: '!XPTOqwerty1', userInfo: { id: this.userId } } }; this.userUsername = this.requestData.userCredentials.username; this.userPassword = this.requestData.userCredentials.password; return dhis2.sendApiRequest({ url: dhis2.generateUrlForResourceType(dhis2.resourceTypes.USER), requestData: this.requestData, method: 'post', onSuccess: function (response) { assert.equal(response.status, 200, 'Status should be 200'); } }); }); After({tags: '@createUser'}, function () { const world = this; return dhis2.sendApiRequest({ url: dhis2.generateUrlForResourceTypeWithId(dhis2.resourceTypes.USER, world.userId), method: 'delete', onSuccess: function (response) { assert.equal(response.status, 200, 'Status should be 200'); return dhis2.sendApiRequest({ url: dhis2.generateUrlForResourceTypeWithId(dhis2.resourceTypes.USER, world.userId), onError: function (error) { assert.equal(error.response.status, 404, 'Status should be 404'); } }); } }); }); When(/^I change my password to (.+)$/, function (password) { const world = this; world.oldPassword = world.userPassword; world.newPassword = password; return dhis2.sendApiRequest({ url: dhis2.apiEndpoint() + '/me', onSuccess: function (response) { assert.equal(response.status, 200, 'Status should be 200'); world.requestData = response.data; world.requestData.userCredentials.password = password; return dhis2.sendApiRequest({ url: dhis2.apiEndpoint() + '/me', requestData: world.requestData, method: 'put', onSuccess: function (response) { world.userPassword = password; }, preventDefaultOnError: true }, world); } }, world); }); Then(/^I should see a message that my password was successfully changed$/, function () { assert.equal(this.responseStatus, 200, 'Status should be 200'); }); Then(/^I should not be able to login using the old password$/, function () { this.userPassword = this.oldPassword; return dhis2.sendApiRequest({ url: dhis2.apiEndpoint() + '/me', onError: function (error) { assert.equal(error.response.status, 401, 'Authentication should have failed.'); } }, this); }); Then(/^I should be able to login using the new password$/, function () { this.userPassword = this.newPassword; return dhis2.sendApiRequest({ url: dhis2.apiEndpoint() + '/me', onSuccess: function (response) { assert.equal(response.status, 200, 'Response Status was not ok'); assert.isOk(response.data.id, 'User id should have been returned'); } }, this); }); Then(/^I should receive error message (.+)$/, function (errorMessage) { checkForErrorMessage(errorMessage, this); }); Given(/^My username is (.+)$/, function (username) { assert.equal(this.userUsername, username, 'Username should be: ' + username); }); }); const checkForErrorMessage = (message, world) => { assert.equal(world.responseStatus, 409, 'Status should be 409'); assert.equal(world.responseData.status, 'ERROR', 'Status should be ERROR'); assert.equal(world.responseData.message, message); };
JavaScript
0.999685
@@ -3689,17 +3689,17 @@ atus, 40 -9 +0 , 'Statu @@ -3716,9 +3716,9 @@ e 40 -9 +0 ');%0A
68815eec8a1ea5ac9aa022a305fcbfb5bf0e6ecf
Remove webpack process.env injection
webpack/webpack.config.js
webpack/webpack.config.js
const path = require('path'); const webpack = require('webpack'); const config = require('../config'); function contains(arr, val) { return arr.indexOf(val) > -1; } const DEBUG = !(process.env.NODE_ENV === 'production' || contains(process.argv, '-p')); const ENV = process.env.NODE_ENV || 'development'; const AUTOPREFIXER_BROWSERS = [ 'Android 2.3', 'Android >= 4', 'Chrome >= 35', 'Firefox >= 31', 'Explorer >= 9', 'iOS >= 7', 'Opera >= 12', 'Safari >= 7.1', ]; const webpackConfig = { context: path.resolve(__dirname, '..'), entry: [path.resolve(__dirname, '../client/index.jsx')], resolve: { modulesDirectories: ['node_modules', 'shared'], extensions: ['', '.js', '.jsx'], }, output: { path: config.buildLocation, filename: 'bundle.js', publicPath: '/public/', }, node: { __dirname: true, }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loaders: [ 'react-hot', `babel?plugins[]=${path.join(__dirname, '..', 'data', 'plugins', 'babelRelayPlugin')}`, ], }, { test: /\.css$/, loaders: [ 'isomorphic-style-loader', `css-loader?${JSON.stringify({ sourceMap: DEBUG, localIdentName: DEBUG ? '[name]_[local]_[hash:base64:3]' : '[hash:base64:4]', modules: true, minimize: !DEBUG, })}`, 'postcss-loader', ], }, { test: /\.less$/, loaders: [ 'isomorphic-style-loader', `css-loader?${JSON.stringify({ sourceMap: DEBUG, localIdentName: DEBUG ? '[name]_[local]_[hash:base64:3]' : '[hash:base64:4]', minimize: !DEBUG, })}`, 'less-loader', ], }, { test: /\.gif$/, loader: 'url-loader?limit=10000&mimetype=image/gif', }, { test: /\.jpg$/, loader: 'url-loader?limit=10000&mimetype=image/jpg', }, { test: /\.png$/, loader: 'url-loader?limit=10000&mimetype=image/png', }, { test: /\.svg/, loader: 'url-loader?limit=26000&mimetype=image/svg+xml', }, { test: /\.(woff|woff2|ttf|eot)/, loader: 'url-loader?limit=1&name=/[hash].[ext]', }, ], }, plugins: [ new webpack.DefinePlugin({ 'process.env': Object.assign({}, process.env, { NODE_ENV: JSON.stringify(ENV), }), }), ], devServer: { hot: true, proxy: { '*': `http://127.0.0.1:${(process.env.PORT || 3000)}`, }, host: '127.0.0.1', }, postcss() { /* eslint-disable global-require */ return [ // W3C variables, e.g. :root { --color: red; } div { background: var(--color); } // https://github.com/postcss/postcss-custom-properties require('postcss-simple-vars')({ variables() { const vars = require('../shared/theme').palette; vars['screen-xs'] = '480px'; vars['screen-sm'] = '768px'; vars['screen-md'] = '992px'; vars['screen-lg'] = '1200px'; vars['screen-xlg'] = '1600px'; vars['screen-xs-max'] = '479px'; vars['screen-sm-max'] = '767px'; vars['screen-md-max'] = '991px'; vars['screen-lg-max'] = '1199px'; vars['screen-xlg-max'] = '1599px'; return vars; }, }), // W3C CSS Custom Media Queries, e.g. @custom-media --small-viewport (max-width: 30em); // https://github.com/postcss/postcss-custom-media require('postcss-custom-media')(), // CSS4 Media Queries, e.g. @media screen and (width >= 500px) and (width <= 1200px) { } // https://github.com/postcss/postcss-media-minmax require('postcss-media-minmax')(), // W3C CSS Custom Selectors, e.g. @custom-selector :--heading h1, h2, h3, h4, h5, h6; // https://github.com/postcss/postcss-custom-selectors require('postcss-custom-selectors')(), // W3C calc() function, e.g. div { height: calc(100px - 2em); } // https://github.com/postcss/postcss-calc require('postcss-calc')(), // Allows you to nest one style rule inside another // https://github.com/jonathantneal/postcss-nesting require('postcss-nesting')(), // W3C color() function, e.g. div { background: color(red alpha(90%)); } // https://github.com/postcss/postcss-color-function require('postcss-color-function')(), // Generate pixel fallback for "rem" units, e.g. div { margin: 2.5rem 2px 3em 100%; } // https://github.com/robwierzbowski/node-pixrem require('pixrem')(), // Add vendor prefixes to CSS rules using values from caniuse.com // https://github.com/postcss/autoprefixer require('autoprefixer')({ browsers: AUTOPREFIXER_BROWSERS }), ]; /* eslint-enable global-require */ }, }; module.exports = webpackConfig;
JavaScript
0.000001
@@ -27,44 +27,8 @@ ');%0A -const webpack = require('webpack');%0A cons @@ -218,59 +218,8 @@ ));%0A -const ENV = process.env.NODE_ENV %7C%7C 'development';%0A cons @@ -2269,168 +2269,8 @@ %7D,%0A - plugins: %5B%0A new webpack.DefinePlugin(%7B%0A 'process.env': Object.assign(%7B%7D, process.env, %7B%0A NODE_ENV: JSON.stringify(ENV),%0A %7D),%0A %7D),%0A %5D,%0A de
7d5d327f1582ebd2b0569b4d01fb72e4b5a47a02
change build api name
newspaperjs/lib/source.js
newspaperjs/lib/source.js
const _ = require('lodash') const extractor = require('./extractor'); const article = require('./article'); const network = require('./network') const path = require('path') /** * * @param {string} url - News website url you want to build * @param {array} cateOfInterest - News categories you interested in * @return {promise} */ exports.getCategoriesUrl = async function(url, cateOfInterest) { return await extractor.getCategoryUrls(url, cateOfInterest); } /** * @param {array} categoriesUrl - Url of categories you interested in * @return {promise} */ exports.getArticleUrl = async function(categoriesUrl){ let obj = {}, finalResult = []; if(categoriesUrl.length > 0){ for(let cateUrl of categoriesUrl){ let result = eachCat(cateUrl); _.set(obj, 'category', extractor.getCategoryName(cateUrl)); _.set(obj, 'articlesUrl', await result); finalResult.push(obj); } return finalResult; }else{ return new Error("Unable to get categories url...") } } function eachCat(cateUrl){ return extractor.getArticlesUrl(cateUrl) }
JavaScript
0.000001
@@ -580,16 +580,17 @@ tArticle +s Url = as
c982f8cebf53ed624ab250f7051f4c924e692780
Use chat_random; add post command.
scripts/almanaccheler.js
scripts/almanaccheler.js
// Description: // Script per inviare carte del mercante in fiera // // Commands: // // Notes: // <optional notes required for the script> // // Author: // batt module.exports = function (robot) { var room = "G4GJDGVE3" var CronJob = require('cron').CronJob; var job = new CronJob('00 30 * * * 1-5', function() { var img_list = robot.brain.get('img_list') || null; if (img_list === null) { return; } var idx = robot.brain.get('img_idx'); var max_idx= robot.brain.get('img_cnt'); robot.messageRoom(room, img_list[idx]); idx++; if (idx >= max_idx) { idx = 0; } robot.brain.set('img_idx', idx); }, function () { /* This function is executed when the job stops */ }, true, /* Start the job right now */ "Europe/Rome" /* Time zone of this job. */ ); job.start(); var shuffle = function(a) { var j, x, i; for (i = a.length; i; i--) { j = Math.floor(Math.random() * i); x = a[i - 1]; a[i - 1] = a[j]; a[j] = x; } return a; } robot.respond(/load (.*)/i, function (res) { var url = res.match[1].trim() robot.http(url) .get()(function(err, resp, body) { if (err) { res.reply(err); } else { var img = body.split('\n'); img = shuffle(img); robot.brain.set('img_list', img); robot.brain.set('img_idx', 0); robot.brain.set('img_cnt', img.length); res.reply("Caricate " + img.length + " immagini:\n" + img.join('\n')); } }); }); var randomImg = function(res) { var img_list = robot.brain.get('img_list') || null; if (img_list === null) { res.reply("Immagini non impostate!"); return; } var rnd = Math.floor(Math.random()*img_list.length); res.reply(img_list[rnd]); } robot.respond(/pug bomb/i, function (res) { randomImg(res); }); robot.respond(/pug me/i, function (res) { randomImg(res); }); robot.respond(/ciao/i, function (res) { randomImg(res); }); robot.respond(/dici (.*)/i, function (res) { if (res.message.user.name == "batt") { robot.messageRoom(room, res.match[1].trim()); } }); };
JavaScript
0
@@ -216,18 +216,33 @@ = %22 -G4GJDGVE3%22 +C02AN2FPY%22 // chat_random %0A%0A @@ -311,17 +311,18 @@ ('00 30 -* +09 * * 1-5 @@ -1649,28 +1649,39 @@ function(res +, chat_room ) %7B%0A - var img_ @@ -1882,33 +1882,138 @@ -res.reply(img_list%5Brnd%5D); +if (chat_room != null) %7B%0A res.reply(img_list%5Brnd%5D);%0A %7D%0A else %7B%0A robot.messageRoom(chat_room, img_list%5Brnd%5D);%0A %7D %0A %7D @@ -2195,32 +2195,32 @@ unction (res) %7B%0A - randomImg(re @@ -2222,32 +2222,158 @@ mg(res);%0A %7D);%0A%0A + robot.respond(/post (.*)/i, function (res) %7B%0A var chat_room = res.match%5B1%5D.trim();%0A randomImg(res, chat_room);%0A %7D);%0A%0A robot.respond(
3b31d35d40b6d8740e1c4a4fa98ebf422ee05d12
disable DataTables pagination (task #2274)
webroot/js/data-tables.js
webroot/js/data-tables.js
(function($) { $(document).ready(function() { $('.table-datatable').DataTable(); }); })(jQuery);
JavaScript
0
@@ -83,16 +83,53 @@ taTable( +%7B%0A paging: false%0A %7D );%0A %7D
3af2befe99f43557426e5763f982ce0ce1875f5b
Update prices.js
js/prices.js
js/prices.js
var iphone4sLCD = 55; var iphone5sGlass = 45; var iphone5sLCD = 60; var iphone6Glass = 49; var iphone6LCD = 60; var iphone6PlusGlass = 60; var iphone6PlusLCD = 69; var iphone6SGlass = 60; var iphone6SLCD = 75; var iphone6SPlusGlass= 70; var iphone6SPlusLCD = 85; var iphone7Glass = 79; var iphone7LCD = 89; var iphone7PlusGlass = 90; var iphone7PlusLCD = 99; var iphone8Glass = 90; var iphone8LCD = 99; var iphone8PlusGlass = 100; var iphone8PlusLCD = 109; var iphoneXGlass = 140; var iphoneXLCD = 180; var iphoneXSGlass = 170; var iphoneXSLCD = 220; var iphoneXSMaxGlass = 370; var iphoneXSMaxLCD = 470; var ipad1Glass = 90; var ipad234Glass = 85; var ipadMiniGlass = 75; var ipadAirGlass = 90; var ipadAir2Glass = 170; var ipadAir2LCD = 200; //Samsung var galaxyS3LCD = 80; var galaxyS4Glass = 45; var galaxyS4LCD = 90; var galaxyS5Glass = 95; var galaxyS5LCD = 135; var galaxyS5NeoGlass = 85; var galaxyS5NeoLCD = 155; var galaxyS6Glass = 105; var galaxyS6LCD = 180; var galaxyS6EdgeLCD = 175; var galaxyS7Glass = 120; var galaxyS7LCD = 190; var galaxyS7EdgeLCD = 265; var galaxyS8Glass = 185; var galaxyS8LCD = 250; var galaxyS8PGlass = 230; var galaxyS8PLCD = 265; var galaxyS9Glass = 260; var galaxyS9LCD = 305; var galaxyNote3Glass = 80; var galaxyNote3LCD = 160; var galaxyNote4Glass = 79; var galaxyNote4LCD = 155; var galaxyNote5Glass = 120; var galaxyNote5LCD = 209; //LG //var nexus4Glass = 75; //correct this in page var nexus4LCD = 80; var nexus5LCD = 65; var nexus5XLCD = 70; var LGG2Glass = 85; var LGG2LCD = 95; var LGG3Glass = 75; var LGG3LCD = 80; var LGG4LCD = 75; var LGG5LCD = 80; var LGG6LCD = 135; var LGG6Glass = 155; var V20Glass = 130; var V20LCD = 140; //OnePlus var OnePlus1LCD = 110; var OnePlus2LCD = 120; var OnePlus3LCD = 165; var OnePlus5LCD = 160; var OnePlus5TLCD = 160; var OnePlusXLCD = 210; var OnePlus6LCD = 230; //Sony var Z3LCD = 100; var Z4LCD = 115; var Z5LCD = 120; //Blackberry var bbZ10 = 45; var bbZ30 = 105; var bbQ10 = 50; var bbQ20 = 80; var bbQ30 = 130; //HTC var M9LCD = 100; var M10LCD = 120; //Huawei var mate7LCD = 105; var mate8LCD = 110; var mate9LCD = 115; var mate10LCD = 155; var p9LCD = 105; var p10LCD = 125; var huaweiG7LCD = 105; var p20LCD= 170; var p20PROLCD= 370; var p20LiteLCD = 135; //Pixel var pixelLCD = 130; var pixelXLLCD = 155; var pixel2LCD = 165; var pixel2XLLCD = 250; var pixel3LCD = 190; var pixel3XLLCD = 210; var Nexus6LCD = 190; var Nexus6PLCD = 170; //Services var diagnostic = 25; var waterDamageL = 65; var waterDamageH = 75; var waterDamageSamsung = 75; var advancedDiagnostic = 60; var systemRestore = 50;
JavaScript
0.000001
@@ -1219,17 +1219,17 @@ LCD = 2 -6 +5 5;%0Avar g
4b54a10c64247b96f05cb274eb52ecfb6f40c02b
update frp.config.js v2.0.0
frp.config.js
frp.config.js
'use strict'; // https://github.com/frontainer/frontplate-cli/wiki/6.%E8%A8%AD%E5%AE%9A module.exports = function(production) { global.FRP_DEST = global.FRP_DEST || 'public'; return { clean: {}, html: {}, style: production ? {} : {}, script: production ? {} : {}, server: {}, copy: {}, sprite: [], test: {} } };
JavaScript
0
@@ -138,14 +138,22 @@ FRP_ -DEST = +SRC = 'src';%0A glo @@ -169,10 +169,9 @@ EST -%7C%7C += 'pu
d3cbed16f2bcdf087fc7109e037c48459d30b425
Fix ffmpeg path access (#847)
ffmpeg-convert-audio/functions/index.js
ffmpeg-convert-audio/functions/index.js
/** * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const functions = require('firebase-functions'); const { Storage } = require('@google-cloud/storage'); const path = require('path'); const os = require('os'); const fs = require('fs'); const ffmpeg = require('fluent-ffmpeg'); const ffmpeg_static = require('ffmpeg-static'); const gcs = new Storage(); // Makes an ffmpeg command return a promise. function promisifyCommand(command) { return new Promise((resolve, reject) => { command.on('end', resolve).on('error', reject).run(); }); } /** * When an audio is uploaded in the Storage bucket We generate a mono channel audio automatically using * node-fluent-ffmpeg. */ exports.generateMonoAudio = functions.storage.object().onFinalize(async (object) => { const fileBucket = object.bucket; // The Storage bucket that contains the file. const filePath = object.name; // File path in the bucket. const contentType = object.contentType; // File content type. // Exit if this is triggered on a file that is not an audio. if (!contentType.startsWith('audio/')) { functions.logger.log('This is not an audio.'); return null; } // Get the file name. const fileName = path.basename(filePath); // Exit if the audio is already converted. if (fileName.endsWith('_output.flac')) { functions.logger.log('Already a converted audio.'); return null; } // Download file from bucket. const bucket = gcs.bucket(fileBucket); const tempFilePath = path.join(os.tmpdir(), fileName); // We add a '_output.flac' suffix to target audio file name. That's where we'll upload the converted audio. const targetTempFileName = fileName.replace(/\.[^/.]+$/, '') + '_output.flac'; const targetTempFilePath = path.join(os.tmpdir(), targetTempFileName); const targetStorageFilePath = path.join(path.dirname(filePath), targetTempFileName); await bucket.file(filePath).download({destination: tempFilePath}); functions.logger.log('Audio downloaded locally to', tempFilePath); // Convert the audio to mono channel using FFMPEG. let command = ffmpeg(tempFilePath) .setFfmpegPath(ffmpeg_static.path) .audioChannels(1) .audioFrequency(16000) .format('flac') .output(targetTempFilePath); await promisifyCommand(command); functions.logger.log('Output audio created at', targetTempFilePath); // Uploading the audio. await bucket.upload(targetTempFilePath, {destination: targetStorageFilePath}); functions.logger.log('Output audio uploaded to', targetStorageFilePath); // Once the audio has been uploaded delete the local file to free up disk space. fs.unlinkSync(tempFilePath); fs.unlinkSync(targetTempFilePath); return functions.logger.log('Temporary files removed.', targetTempFilePath); });
JavaScript
0
@@ -2712,13 +2712,8 @@ atic -.path )%0A
d14e397c8bcd79cb72f18a579492ae7a37dcba61
Fix identing of include code
quickstarts/uppercase/functions/index.js
quickstarts/uppercase/functions/index.js
/** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // [START all] // [START import] const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); // [END import] // [START addMessage] // Take the text parameter passed to this HTTP endpoint and insert it into the // Realtime Database under the path /messages/:pushId/original // [START addMessageTrigger] exports.addMessage = functions.https.onRequest((req, res) => { // [END addMessageTrigger] // Grab the text parameter. const original = req.query.text; // Push it into the Realtime Database then send a response admin.database().ref('/messages').push({original: original}).then(snapshot => { // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console. res.redirect(303, snapshot.ref); }); }); // [END addMessage] // [START makeUppercase] // Listens for new messages added to /messages/:pushId/original and creates an // uppercase version of the message to /messages/:pushId/uppercase // [START makeUppercaseTrigger] exports.makeUppercase = functions.database.ref('/messages/{pushId}/original') .onWrite(event => { // [END makeUppercaseTrigger] // [START makeUppercaseBody] // Grab the current value of what was written to the Realtime Database. const original = event.data.val(); console.log('Uppercasing', event.params.pushId, original); const uppercase = original.toUpperCase(); // You must return a Promise when performing asynchronous tasks inside a Functions such as // writing to the Firebase Realtime Database. // Setting an "uppercase" sibling in the Realtime Database returns a Promise. return event.data.ref.parent.child('uppercase').set(uppercase); }); // [END makeUppercaseBody] // [END makeUppercase] // [END all]
JavaScript
0.000144
@@ -1803,16 +1803,22 @@ rigger%5D%0A + // %5BSTAR @@ -2377,20 +2377,18 @@ e);%0A -%7D);%0A + // %5BEND @@ -2406,16 +2406,24 @@ seBody%5D%0A + %7D);%0A // %5BEND
e7b61708bcfd9665ec20492fc272c87773627acb
Remove trailing whitespace
js/reddit.js
js/reddit.js
var Reddit = { downloadPost: function(name, callback) { // post factory, download from reddit console.log('Loading post ' + name); $.get('post.php', { name: name }, function(postList) { var post = postList.data.children[0].data; callback(new Reddit.Post(post)); }, 'json'); }, Post: function(data) { this.name = data.name; this.title = data.title; this.url = data.url; this.permalink = data.permalink; }, Channel: function(subreddits) { if (typeof subreddits == 'string') { subreddits = [subreddits]; } this.subreddits = subreddits; this.items = []; this.currentID = 0; this.limit = 25; this.onnewitemavailable = function() {}; this.onerror = function() {}; }, }; Reddit.Channel.prototype = { constructor: Reddit.Channel, getCurrent: function(callback) { var self = this; if (this.items.length > this.currentID) { // current item is already downloaded, return immediately return callback(this.items[this.currentID]); } // we don't yet have the current item; download it this.downloadNextPage(function() { callback(self.items[self.currentID]); }, this.onerror); }, downloadNextPage: function(ondone, onerror) { var after; var self = this; if (this.items.length == 0) { after = ''; } else { after = this.items[this.items.length - 1].name; } $.get('feed.php', { r: this.subreddits.join('+'), after: after, limit: this.limit }, function(feed) { var prevlength = self.items.length; // TODO: Optimize O(n^2) algorithm if (feed == null) { Render.invalid(); return; } feed.data.children = feed.data.children.map(function(item) { return new Reddit.Post(item.data); }).filter(function(item) { /* console.log('Filter: '); console.log(item); */ return true; // Go through all items that have already been displayed // and make sure we only inject new content // This is important, as pages in reddit may have changed // during ranking. for (var i = 0; i < self.items.length; ++i) { var loadedItem = self.items[i]; if (item.name === loadedItem.name) { console.log('Skipping already loaded item', item.name); return false; } } return true; }); self.items.push.apply(self.items, feed.data.children); var newlength = self.items.length; for (var i = 0; i < feed.data.children.length; ++i) { self.onnewitemavailable(feed.data.children[i]); } if (prevlength == newlength) { // we ran out of pages console.log('End of subreddit.'); self.onerror(); } else { ondone(); } }, 'json'); }, goNext: function(onerror) { if (typeof onerror == 'function') { this.onerror = onerror; } ++this.currentID; }, goPrevious: function(onerror) { if (this.currentID - 1 < 0) { if (typeof onerror == 'function') { return onerror(); } return; } --this.currentID; } };
JavaScript
0.999999
@@ -2634,36 +2634,16 @@ ems%5Bi%5D;%0A - %0A
94d0e3f5e07877cae2ac2e28b031890ba863c7d5
Fix incorrect executive rights on `test.js`
test.js
test.js
'use strict'; /** * Dependencies. */ var emoji, gemoji, assert; emoji = require('./data/emoji.json'); gemoji = require('./'); assert = require('assert'); /** * Tests for basic structure. */ describe('gemoji', function () { it('should have a `name` property', function () { assert( Object.prototype.toString.call(gemoji.name) === '[object Object]' ); }); it('should have an `unicode` property', function () { assert( Object.prototype.toString.call(gemoji.unicode) === '[object Object]' ); }); }); /** * Validate if a crawled gemoji is indeed (correctly) * present in this module. * * @param {Object} gemojiObject * @param {string} gemojiObject.emoji - Unicode * representation. * @param {string} gemojiObject.description - Human * description of the picture. * @param {Array.<string>} gemojiObject.aliases - List * of names used by GitHub. * @param {Array.<string>} gemojiObject.tags - List * of tags. */ function describeGemojiObject(gemojiObject) { var unicode, information, description, aliases, tags, name; unicode = gemojiObject.emoji; /** * Some gemoji, such as `octocat`, do not have a * unicode representation. Those are not present in * `gemoji`. Exit. */ if (!unicode) { return; } description = gemojiObject.description; aliases = gemojiObject.aliases; tags = gemojiObject.tags; name = aliases[0]; information = gemoji.unicode[unicode]; describe(unicode + ' ' + description, function () { aliases.forEach(function (alias) { it('should be accessible by name (' + alias + ' > object)', function () { assert(gemoji.name[alias].emoji === unicode); } ); }); it('should be accessible by emoji (' + unicode + ' > object)', function () { assert(gemoji.unicode[unicode].name === name); } ); describe('Information', function () { it('should have a `name` field', function () { assert(typeof information.name === 'string'); assert(information.name === name); }); it('should have an `emoji` field', function () { assert(typeof information.emoji === 'string'); assert(information.emoji === unicode); }); it('should have a `description` field', function () { assert(typeof information.description === 'string'); assert(information.description === description); }); it('should have a `names` list', function () { assert(Array.isArray(information.names) === true); assert(information.names.length >= 1); information.names.forEach(function (name) { assert(typeof name === 'string'); assert(aliases.indexOf(name) !== -1); }); aliases.forEach(function (name) { assert(information.names.indexOf(name) !== -1); }); }); it('should have a `tags` list', function () { assert(Array.isArray(information.tags) === true); information.tags.forEach(function (tag) { assert(typeof tag === 'string'); assert(tags.indexOf(tag) !== -1); }); tags.forEach(function (tag) { assert(information.tags.indexOf(tag) !== -1); }); }); }); }); } /** * Validate all crawled gemoji-objects. */ emoji.forEach(describeGemojiObject);
JavaScript
0.001299