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
c551bd235273609103a9e8ff99902cccc6cf2169
Use static keyword to identify static member
lib/epp-factory-es6.js
lib/epp-factory-es6.js
var winston = require('winston'); var EPP = require('../lib/epp-es6.js'); var EPPExtension = require('../lib/epp-extension-es6.js'); var SecDnsExtension = require('../lib/secdns-extension-es6.js'); var HexonetExtension = require('../lib/hexonet-extension-es6.js'); var AfiliasExtension = require('../lib/afilias-extension-es6.js'); var nconf = require('./utilities/config.js').getConfig(); var logger = require('./utilities/logging.js').getLogger(nconf); /* * Compose extension classes into the main EPP library as needed. As * different registries have different extensions, and some, but not all may * use DNSSEC, use the registry config to determine which ones need to go in. **/ class EppFactory { constructor() { } generate(registry, config) { var epp = new EPP(registry, config); config.extensionClasses && config.extensionClasses.forEach((extensionClass) => { var extension = extensionClass.extension; var className = extensionClass.className; var mixer, mapper; switch (className) { case 'SecDnsExtension': logger.debug("Applying secDNS mixin"); mixer = SecDnsExtension; mapper = SecDnsExtension.mixinMapper(); break; case 'HexonetExtension': mixer = HexonetExtension; logger.debug("Applying hexonet mixin"); mapper = HexonetExtension.mixinMapper(); break; case 'AfiliasExtension': mixer = AfiliasExtension; logger.debug("Applying afilias mixin"); mapper = AfiliasExtension.mixinMapper(); break; default: } // Complicated kludge to map the epp command to the extension command that // should be executed. See mapping in respective mixin class. mapper.forEach((mapping) => { for (var eppCommand in mapping) { var fn = mapping[eppCommand]; epp[fn] = mixer.prototype[fn]; EppFactory.pushExtensionCommandMap(epp, eppCommand, extension, fn); } }); }); return epp; } pushExtensionCommandMap(epp, command, extension, extensionFunction) { logger.debug("Adding " + command + ":" + extension + ":" + extensionFunction + " to epp object "); if (!epp.extensionCommandMap[command]) { epp.extensionCommandMap[command] = {}; } epp.extensionCommandMap[command][extension] = extensionFunction; } } module.exports = EppFactory;
JavaScript
0
@@ -729,16 +729,23 @@ %0A %7D%0A%0A +static generate
81f5ad04ef96262197b9986eb89951e112d02bed
Update to callback
actions/auth_github.js
actions/auth_github.js
passport = require('passport'); exports.auth_github = { name: 'auth_github', description: 'endpoint callback for GitHub authentication', inputs: { 'required' : [], 'optional' : [] }, // authorisedGroups: void(0), blockedConnectionTypes: [], outputExample: { }, run: function(api, connection, next) { // api.log(connection); passport.authorize('github', { failureRedirect: '/login' })(connection.rawConnection.req, connection.rawConnection.res, function(err) { if (err instanceof Error) { connection.error = err; } next(connection, true); }); // api.session.delete(connection, next); } };
JavaScript
0
@@ -309,19 +309,16 @@ xt) %7B%0A%09%09 -// api.log( @@ -327,16 +327,52 @@ nnection +.params);%0A%09%09// next(connection, true );%0A%09%09pas @@ -509,16 +509,100 @@ (err) %7B%0A +%09%09%09api.log(%22This is the callback for the github authorize%22);%0A%09%09%09api.log(arguments);%0A %09%09%09if (e
1adf660c46bc59fc9fbb1d1c5d4c10a04cdd3c17
Rename app.
src/common/intl/messages/en.js
src/common/intl/messages/en.js
export default { app: { footer: { madeBy: 'written by CjK based on Daniel Steigerwald\'s Este.js' }, links: { firebase: 'Firebase', home: 'Home', login: 'Login', me: 'Me', todos: 'Todos' } }, auth: { form: { button: { login: 'Login', signup: 'Sign up' }, hint: 'Hint: pass1', legend: 'Classic XMLHttpRequest Login', placeholder: { email: 'your@email.com', password: 'password' }, wrongPassword: 'Wrong password.' }, logout: { button: 'Logout' }, login: { title: 'Login' }, validation: { email: 'Email address is not valid.', password: 'Password must contain at least {minLength} characters.', required: `Please fill out {prop, select, email {email} password {password} other {'{prop}'} }.` } }, home: { // // TODO: Android text. // androidInfoText: ``, infoHtml: '<a href="https://github.com/este/este">Este.js</a> dev stack.', iosInfoText: ` Este.js dev stack Press CMD+R to reload Press CMD+D for debug menu `, title: 'Este.js', toCheck: { andMuchMore: 'And much more :-)', h2: 'Things to Check', isomorphicPage: 'Isomorphic page', // Localized ordered list. list: [ 'Server rendering', 'Hot reloading', 'Performance and size of production build (<code>gulp -p</code>)' ] } }, fermenter: { title: 'Fermenter-Closet' }, me: { title: 'Me', welcome: 'Hi {email}. This is your secret page.' }, notFound: { continueMessage: 'Continue here please.', header: 'This page isn\'t available', message: 'The link may be broken, or the page may have been removed.', title: 'Page Not Found' }, todos: { add100: 'Add 100 Todos', clearAll: 'Clear All', clearCompleted: 'Clear Completed', empty: 'It\'s rather empty here...', leftList: `{size, plural, =0 {Nothing, enjoy} one {You are almost done} other {You have {size} tasks to go} }`, newTodoPlaceholder: 'What needs to be done?', title: 'Todos' }, profile: { title: 'Profile' }, settings: { title: 'Settings' } };
JavaScript
0
@@ -1184,23 +1184,33 @@ title: ' -Este.js +CjK%5C's smart-home ',%0A t
35b1bee50dafcb0c683e2ea7cf273fb261efcbfe
Use custom root for S3 paths
admin/server/api/s3.js
admin/server/api/s3.js
/* TODO: Needs Review and Spec */ module.exports = { upload: function (req, res) { var knox = require('knox-s3'); var keystone = req.keystone; var Types = keystone.Field.Types; if (!keystone.security.csrf.validate(req, req.body.authenticity_token)) { return res.status(403).send({ error: { message: 'invalid csrf' } }); } if (req.files && req.files.file) { var s3Config = keystone.get('s3 config'); var file = req.files.file; var path = s3Config.s3path ? s3Config.s3path + '/' : ''; var headers = Types.S3File.prototype.generateHeaders.call({ s3config: s3Config, options: {} }, null, file); var s3Client = knox.createClient(s3Config); s3Client.putFile(file.path, path + file.name, headers, function (err, s3Response) { var sendResult = function () { if (err) { return res.send({ error: { message: err.message } }); } if (s3Response) { if (s3Response.statusCode !== 200) { return res.send({ error: { message: 'Amazon returned Http Code: ' + s3Response.statusCode } }); } else { var region = 's3'; if (s3Config.region && s3Config.region !== 'us-east-1') { region = 's3-' + s3Config.region; } return res.send({ image: { url: 'https://' + region + '.amazonaws.com/' + s3Config.bucket + '/' + file.name } }); } } }; res.format({ html: sendResult, json: sendResult, }); }); } else { res.json({ error: { message: 'No image selected' } }); } }, };
JavaScript
0
@@ -1058,16 +1058,139 @@ else %7B%0A +%09%09%09%09%09%09%09if (s3Config.root) %7B%0A%09%09%09%09%09%09%09%09return res.send(%7B image: %7B url: s3Config.root + '/' + file.name %7D %7D);%0A%09%09%09%09%09%09%09%7D else %7B%0A%09 %09%09%09%09%09%09%09v @@ -1207,16 +1207,17 @@ = 's3';%0A +%09 %09%09%09%09%09%09%09i @@ -1281,16 +1281,17 @@ %09%09%09%09%09%09%09%09 +%09 region = @@ -1319,26 +1319,28 @@ ion;%0A%09%09%09%09%09%09%09 +%09 %7D%0A +%09 %09%09%09%09%09%09%09retur @@ -1444,24 +1444,33 @@ .name %7D %7D);%0A +%09%09%09%09%09%09%09%7D%0A %09%09%09%09%09%09%7D%0A%09%09%09%09
80eea18352a3eb64aca85e1600f1748f5081705a
rename facebook-share to facebook-simple as socialite now has a facebook-share
extensions/socialite.facebook-share.js
extensions/socialite.facebook-share.js
/*! * Socialite v2.0 - Plain FB Share Extension * Copyright (c) 2013 Dan Drinkard * Dual-licensed under the BSD or MIT licenses: http://socialitejs.com/license.txt */ (function(window, document, Socialite, undefined) { /** * FB Share is no longer supported, but params are: * u | data-url | URL to share * t | data-title | Title to share * * Others may work, but that will come later. For now just set OG tags. * */ var addEvent = function(obj, evt, fn, capture) { if (window.attachEvent) { obj.attachEvent("on" + evt, fn); } else { if (!capture) capture = false; // capture obj.addEventListener(evt, fn, capture); } }, facebookGetCount = function(instance, options) { var params = getParams(instance), counturl = params['counturl'] || params['url'], callback = 'socialiteFacebookShare' + instance.uid, endpoint = "https://graph.facebook.com/fql?q=" + encodeURIComponent("select total_count from link_stat where url = '") + counturl + "'&callback=" + callback, options = options || {}, scriptTag = document.createElement('script'); scriptTag.src = endpoint; document.getElementsByTagName('script')[0].insertBefore(scriptTag); window[callback] = function(data){ instance.el.querySelectorAll('.counter')[0].innerHTML = data.data[0].total_count; delete window[callback]; scriptTag.parentNode.removeChild(scriptTag); } }, getParams = function(instance) { return parseQS(Socialite.getDataAttributes(instance.el, true)); }, parseQS = function(qs) { var hsh = {}, parts = qs.split(/[&=]/); for(var i in parts) { if (i%2) { hsh[parts[i-1]] = parts[i]; }; }; return hsh; }, appendStyleSheet = function() { (document.querySelectorAll('style.custom-count-widgets').length || (function(){ var styleTag = document.createElement('style'); styleTag.className = 'custom-count-widgets'; styleTag.innerHTML = '.socialite .counter { border-radius: 2px; background:#fff; position:relative; margin-left: 5px; vertical-align: middle; display:inline-block; min-width:6px; border:1px solid #e6e5e3; padding:6px 7px; font-family:"helvetica neue", helvetica, arial, sans-serif; font-size:13px; line-height:1.2; color:#222; text-decoration: none; }' + '.socialite .counter:before { content:""; position:absolute; left: -5px; top: 10px; background:#fff; border:1px solid #e6e5e3; border-right:none; border-top:none; display:block; width:7px; height:6px; -webkit-transform: rotate(61deg) skewX(35deg); -moz-transform: rotate(61deg) skewX(35deg); -o-transform: rotate(61deg) skewX(35deg); -ms-transform: rotate(61deg) skewX(35deg); transform: rotate(61deg) skewX(35deg); }' + '.socialite img { vertical-align: middle; }'; document.getElementsByTagName('head')[0].appendChild(styleTag); })()); } Socialite.widget('facebook', 'share', { init: function(instance) { var el = document.createElement('a'), href = "//www.facebook.com/share.php?", attrs = Socialite.getDataAttributes(instance.el, true, true); el.className = instance.widget.name; Socialite.copyDataAttributes(instance.el, el); if(attrs.url) href += 'u=' + encodeURIComponent(attrs.url); if(attrs['title']) href += '&t=' + encodeURIComponent(attrs['title']); href += '&' + Socialite.getDataAttributes(el, true); el.setAttribute('href', href); el.setAttribute('data-lang', instance.el.getAttribute('data-lang') || Socialite.settings.facebook.lang); if (instance.el.getAttribute('data-image')) { var imgTag = document.createElement('img'); imgTag.src = instance.el.getAttribute('data-image'); el.appendChild(imgTag); } if (instance.el.getAttribute('data-sficon')) { var iconTag = document.createElement('span'); iconTag.className = instance.el.getAttribute('data-sficon'); el.appendChild(iconTag); } if (instance.el.getAttribute('data-show-counts') == 'true') { var counterTag = document.createElement('span') counterTag.className = 'counter'; counterTag.innerHTML = '&hellip;'; el.appendChild(counterTag); } addEvent(el, 'click', function(e){ var t = e? e.target : window.event.srcElement; e.preventDefault(); var counter = el.querySelectorAll('.counter'); counter.length && (function(){ var count = parseFloat(counter[0].innerHTML); counter[0].innerHTML = count + 1; })(); window.open(el.getAttribute('href'), 'fb-share', 'left=' + (screen.availWidth/2 - 350) + ',top=' + (screen.availHeight/2 - 163) + ',height=325,width=700,menubar=0,resizable=0,status=0,titlebar=0'); }); instance.el.appendChild(el); }, activate: function(instance){ if (getParams(instance)['show-counts'] == 'true') { appendStyleSheet(); facebookGetCount(instance); } } }); })(window, window.document, window.Socialite);
JavaScript
0.001485
@@ -3243,19 +3243,20 @@ ook', 's -har +impl e', %7B%0A
7495f7aa55dee962108ad588663b8ff2e747fd4a
add localstorage for state holding
src/component/header/Header.js
src/component/header/Header.js
import React, { useState } from "react" import { Link } from "gatsby" import '../../styles/header.scss' import "../../styles/background.scss" const cycleVisualization = (current) =>{ if(current === 'square'){ return 'Krzywinski' } else if(current === 'Krzywinski'){ return 'square' } return 'square' } const Header = (props) => { const [expand,setExpand] = useState(false) const [visualization, setVisualization] = useState('square') const mainDigits = ['3.',1,4,1,5,9] return ( <> <section id="background" className={visualization}></section> <header> <section className={visualization}> {mainDigits.map((d,i)=>(<div key={'MainDigit'+i} onClick={()=>setVisualization(cycleVisualization(visualization))}><p className={`digit${parseInt(d)}`}>{d}</p></div>))} </section> <div id="burger" onClick={()=>setExpand(!expand)}>=</div> <nav> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/projects">Projects</Link></li> <li><Link to="/tech">Technologies</Link></li> </ul> </nav> </header> <aside className={expand?"expanded":undefined}> <div id="burger-menu" onClick={()=>setExpand(!expand)}>=</div> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/projects">Projects</Link></li> <li><Link to="/tech">Technologies</Link></li> </ul> </aside> </> ) } export default Header
JavaScript
0
@@ -210,24 +210,86 @@ 'square')%7B%0D%0A + localStorage.setItem('visualization', 'Krzywinski');%0D%0A retu @@ -348,24 +348,82 @@ ywinski')%7B%0D%0A + localStorage.setItem('visualization', 'square');%0D%0A retu @@ -497,16 +497,97 @@ ) =%3E %7B%0D%0A + const loadedVisualization = localStorage.getItem('visualization') %7C%7C 'square' %0D%0A co @@ -684,24 +684,35 @@ seState( -'square' +loadedVisualization )%0D%0A c
ccc23b2f835d561acd654efbb09293030e120900
replace style with st
src/components/NavBar/index.js
src/components/NavBar/index.js
import React from 'react' import style from './style.module.css' import Link from 'gatsby-link' export const NavBar = () => ( <div className={style.header}> <nav className={style.wrapper}> <Link to="/" className={style.logo}> <img src="http://galernaya20.com/wp-content/uploads/2015/06/Logo-Galernaya-201.png" alt="Galernaya 20 - студия звукозаписи, аренда оборудования, продюсерский центр, аранжировка песен" className={style.logoImg} /> </Link> <ul className={style.menu}> <li className={style.menuItem}> <Link to="/">Студия</Link> </li> <li className={style.menuItem}> <Link to="/production">Продакшн</Link> </li> <li className={style.menuItem}> <Link to="/equipment">Оборудование</Link> </li> <li className={style.menuItem}> <Link to="/school">Школа</Link> </li> <li className={style.menuItem}> <Link to="/team">Команда</Link> </li> <li className={style.menuItem}> <Link to="/price">Цены</Link> </li> <li className={style.menuItem}> <Link to="/contacts">Контакты</Link> </li> </ul> <div className={style.contacts}>8 (812) 994 54 97</div> </nav> </div> )
JavaScript
0.003423
@@ -28,19 +28,16 @@ mport st -yle from '. @@ -137,19 +137,16 @@ Name=%7Bst -yle .header%7D @@ -169,19 +169,16 @@ Name=%7Bst -yle .wrapper @@ -208,27 +208,24 @@ lassName=%7Bst -yle .logo%7D%3E%0A @@ -455,19 +455,16 @@ Name=%7Bst -yle .logoImg @@ -510,27 +510,24 @@ lassName=%7Bst -yle .menu%7D%3E%0A @@ -539,35 +539,32 @@ li className=%7Bst -yle .menuItem%7D%3E%0A @@ -627,35 +627,32 @@ li className=%7Bst -yle .menuItem%7D%3E%0A @@ -727,35 +727,32 @@ li className=%7Bst -yle .menuItem%7D%3E%0A @@ -830,35 +830,32 @@ li className=%7Bst -yle .menuItem%7D%3E%0A @@ -923,35 +923,32 @@ li className=%7Bst -yle .menuItem%7D%3E%0A @@ -1016,35 +1016,32 @@ li className=%7Bst -yle .menuItem%7D%3E%0A @@ -1115,19 +1115,16 @@ Name=%7Bst -yle .menuIte @@ -1225,19 +1225,16 @@ Name=%7Bst -yle .contact
ec0dd5696d0afd3160538d5b54d09b447761a4c5
Update Notification.js
src/components/Notification.js
src/components/Notification.js
'use strict'; import React from 'react'; const PERMISSION_GRANTED = 'granted'; const PERMISSION_DENIED = 'denied'; const seqGen = () => { let i = 0; return () => { return i++; }; }; const seq = seqGen(); class Notification extends React.Component { constructor(props) { super(props); let supported = false; let granted = false; if (('Notification' in window) && window.Notification) { supported = true; if (window.Notification.permission === PERMISSION_GRANTED) { granted = true; } } else { supported = false; } this.state = { supported: supported, granted: granted }; // Do not save Notification instance in state this.notifications = {}; this.windowFocus = true; this.onWindowFocus = this._onWindowFocus.bind(this); this.onWindowBlur = this._onWindowBlur.bind(this); } _onWindowFocus(){ this.windowFocus = true; } _onWindowBlur(){ this.windowFocus = false; } _askPermission(){ window.Notification.requestPermission((permission) => { let result = permission === PERMISSION_GRANTED; this.setState({ granted: result }, () => { if (result) { this.props.onPermissionGranted(); } else { this.props.onPermissionDenied(); } }); }); } componentDidMount(){ if (this.props.disableActiveWindow) { if (window.addEventListener){ window.addEventListener('focus', this.onWindowFocus); window.addEventListener('blur', this.onWindowBlur); } else if (window.attachEvent){ window.attachEvent('focus', this.onWindowFocus); window.attachEvent('blur', this.onWindowBlur); } } if (!this.state.supported) { this.props.notSupported(); } else if (this.state.granted) { this.props.onPermissionGranted(); } else { if (window.Notification.permission === PERMISSION_DENIED){ if (this.props.askAgain){ this._askPermission(); } else { this.props.onPermissionDenied(); } } else { this._askPermission(); } } } componentWillUnmount(){ if (this.props.disableActiveWindow) { if (window.removeEventListner){ window.removeEventListener('focus', this.onWindowFocus); window.removeEventListener('blur', this.onWindowBlur); } else if (window.detachEvent){ window.detachEvent('focus', this.onWindowFocus); window.detachEvent('blur', this.onWindowBlur); } } } render() { let doNotShowOnActiveWindow = this.props.disableActiveWindow && this.windowFocus; if (!this.props.ignore && this.props.title && this.state.supported && this.state.granted && !doNotShowOnActiveWindow) { let opt = this.props.options; if (typeof opt.tag !== 'string') { opt.tag = 'web-notification-' + seq(); } if (!this.notifications[opt.tag]) { let n = new window.Notification(this.props.title, opt); n.onshow = (e) => { this.props.onShow(e, opt.tag); setTimeout(() => { this.close(opt.tag); }, this.props.timeout); }; n.onclick = (e) => {this.props.onClick(e, opt.tag); }; n.onclose = (e) => {this.props.onClose(e, opt.tag); }; n.onerror = (e) => {this.props.onError(e, opt.tag); }; this.notifications[opt.tag] = n; } } // return null cause // Error: Invariant Violation: Notification.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object. return ( <input type='hidden' name='dummy-for-react-web-notification' style={{display: 'none'}} /> ); } close(tag) { if (this.notifications[tag] && typeof this.notifications[tag].close === 'function') { this.notifications[tag].close(); } } // for debug _getNotificationInstance(tag) { return this.notifications[tag]; } } Notification.propTypes = { ignore: React.PropTypes.bool, disableActiveWindow: React.PropTypes.bool, askAgain: React.PropTypes.bool, notSupported: React.PropTypes.func, onPermissionGranted: React.PropTypes.func, onPermissionDenied: React.PropTypes.func, onShow: React.PropTypes.func, onClick: React.PropTypes.func, onClose: React.PropTypes.func, onError: React.PropTypes.func, timeout: React.PropTypes.number, title: React.PropTypes.string.isRequired, options: React.PropTypes.object }; Notification.defaultProps = { ignore: false, disableActiveWindow: false, askAgain: false, notSupported: () => {}, onPermissionGranted: () => {}, onPermissionDenied: () => {}, onShow: () => {}, onClick: () => {}, onClose: () => {}, onError: () => {}, timeout: 5000, options: {} }; export default Notification;
JavaScript
0
@@ -543,46 +543,8 @@ %7D - else %7B%0A supported = false;%0A %7D %0A%0A
a49c9dc05f770f0bb09d000d454e020196ff5eb3
update duration
src/components/ScaffoldItem.js
src/components/ScaffoldItem.js
import React from 'react'; import { Icon } from 'antd'; import { Link } from 'dva/router'; import Overdrive from 'react-overdrive'; import styles from './ScaffoldItem.less'; export default function ScaffoldItem({ name, description, stargazers_count, coverPicture }) { return ( <li className={styles.card}> <Link to={`/templates/${name}`}> <Overdrive id={`cover-${name}`} duration={300}> <img className={styles.picture} src={coverPicture} alt="" /> </Overdrive> <div className={styles.detail}> <h2 className={styles.title}> {name} </h2> <div className={styles.description} title={description}> {description} </div> <div> <Icon type="star" className={styles.star} />{stargazers_count} </div> </div> </Link> </li> ); }
JavaScript
0
@@ -399,9 +399,9 @@ on=%7B -3 +4 00%7D%3E
3623e7b2c3b70ef9a1ed8a14301aab1685a9b197
Break words on long streamer titles
src/components/StreamerCard.js
src/components/StreamerCard.js
import React, { Component } from "react"; import { observer } from "mobx-react"; import styled from "styled-components"; import { Card, CardTitle, CardActions, CardText } from "react-toolbox/lib/card"; import Button from "react-toolbox/lib/button/Button"; import axios from "axios"; const OnlineCard = styled(Card)` background: #555555; color: #ecf0f1; margin: 10px; width: calc(100% - 20px); flex: 0 0 auto; `; const OfflineCard = styled(Card)` background: #444; color: #c3c8c9; margin: 10px; width: calc(100% - 20px); flex: 0 0 auto; `; const StyledCardTitle = styled(CardTitle)` & * { text-align: left; } & p { color: #b9c0c0 !important; } `; const MaterialCard = ({ streamer, onClick, picture, status, onRemove, game }) => { const children = ( <div> <StyledCardTitle title={streamer} avatar={picture ? picture : null} subtitle={onClick ? game : null} /> <CardText> {status} </CardText> <CardActions> {onClick ? <Button raised primary label="Watch" value={streamer} onClick={onClick} /> : null} <Button accent label="Remove" value={streamer} onClick={onRemove} /> </CardActions> </div> ); // Return appropriate online or offline card based on // ... whether or not a link to watch the stream was provided if (onClick) { return ( <OnlineCard raised> {children} </OnlineCard> ); } else { return ( <OfflineCard raised> {children} </OfflineCard> ); } }; @observer class StreamerCard extends Component { constructor() { super(); this.state = { channelData: null, loading: true, error: null }; this.handleFavoriteClick = this.handleFavoriteClick.bind(this); this.handleRemoveClick = this.handleRemoveClick.bind(this); this.fetchInformation = this.fetchInformation.bind(this); } handleFavoriteClick(e) { this.props.store.setChannel(e.target.value); } handleRemoveClick(e) { this.props.store.removeFavorite(e.target.value); } fetchInformation() { const { streamer } = this.props; const config = { headers: { "Client-ID": "gc6rul66vivvwv6qwj98v529l9mpyo" } }; axios .get(`https://api.twitch.tv/kraken/channels/${streamer}`, config) .then(res => { this.setState({ channelsData: res.data, loading: false }); }) .catch(error => { console.error( `An error occurred fetching channel data for ${streamer}`, error ); this.setState({ error: JSON.stringify(error) }); }); } componentDidMount() { this.fetchInformation(); } render() { const { streamer, isOnline } = this.props; if (this.state.error) { return ( <div> <h3>Error: {this.state.error}</h3> </div> ); } if (this.state.loading) { return ( <MaterialCard streamer={streamer} status="Loading..." onRemove={this.handleRemoveClick} /> ); } return ( <MaterialCard streamer={streamer} picture={this.state.channelsData.logo} status={this.state.channelsData.status} game={this.state.channelsData.game} onClick={isOnline ? this.handleFavoriteClick : null} onRemove={this.handleRemoveClick} /> ); } } export default StreamerCard;
JavaScript
0
@@ -195,16 +195,67 @@ /card%22;%0A +import %7B Avatar %7D from %22react-toolbox/lib/avatar%22;%0A import B @@ -300,16 +300,16 @@ utton%22;%0A - import a @@ -726,24 +726,236 @@ nt;%0A %7D%0A%60;%0A%0A +const StyledAvatar = styled(Avatar)%60%0A flex-shrink: 0;%0A%60;%0A%0Aconst StyledTitle = styled.h5%60%0A margin: 0;%0A padding: 0;%0A font-size: 1.4rem;%0A font-weight: 400;%0A word-wrap: break-word;%0A word-break: break-all;%0A%60;%0A%0A const Materi @@ -1106,24 +1106,53 @@ title=%7B -streamer +%3CStyledTitle%3E%7Bstreamer%7D%3C/StyledTitle%3E %7D%0A @@ -1171,23 +1171,48 @@ cture ? +%3CStyledAvatar image=%7B picture +%7D /%3E : null%7D
9c756b635de6dc42cdbefb63874102fcee977a92
remove colorPicker import
src/components/action/index.js
src/components/action/index.js
import React, { Component } from 'react'; import Button from '../button'; import Switch from '../switch'; import Dropdown from '../dropdown'; import ColorPicker from '../color-picker'; import ActionTypes from 'butter-component-action-types'; export default class Action extends Component { constructor (props) { super() let {id, settings} = props this.apply = (value) => settings.set(id, value) } render() { let {type, settings, id, t, ...props} = this.props let value = settings[id] return ( (type === ActionTypes.BUTTON)?(<Button title={t(props.title)}/>): (type === ActionTypes.TEXT)?(<input type="text" value={value} onChange={this.apply}/>): (type === ActionTypes.PASSWORD)?(<input type="password"/>): (type === ActionTypes.DROPDOWN)?(<Dropdown apply={this.apply} selected={value} type="text" {...props}/>): (type === ActionTypes.COLOR)?(<Dropdown apply={this.apply} selected={value} type="color" {...props}/>): (type === ActionTypes.SWITCH)?(<Switch apply={this.apply} selected={value}/>): (<b className="error">Couldn't find an apropiate action type {console.log('Could not find action', type, props)}</b>) ) } }
JavaScript
0
@@ -140,52 +140,8 @@ n';%0A -import ColorPicker from '../color-picker';%0A%0A impo
a12fbaca5a6fbe08298fccc2d969799bcbaa6e2f
Update Hero.js
src/components/general/Hero.js
src/components/general/Hero.js
import React from 'react' import styled from 'styled-components' import Img from 'gatsby-image' const Hero = styled.div` position: relative; div { height: 61.8vh !important; width: 100%; object-fit: cover !important; } box-shadow: 0px 5px 15px var(--color-secondary-50), 0px 10px 25px var(--color-secondary-25), 0px 15px 30px var(--color-secondary-15); ` const HomeHero = props => { return ( <Hero> <Img fluid={props.image.fluid} /> </Hero> ) } export default HomeHero
JavaScript
0.000001
@@ -149,16 +149,20 @@ v %7B%0A +max- height:
92c111db8be36be2452fa3ce429d15c45f477b35
Fix register form
src/containers/RegisterForm.js
src/containers/RegisterForm.js
import React, { Component } from 'react' import { Button, Panel } from 'react-bootstrap' import { connect } from 'react-redux' import { Field, reduxForm } from 'redux-form' import { postRegistration } from '../actions/register' import TextInput from '../components/controls/TextInput' class RegisterForm extends Component { render () { const { handleSubmit, invalid, register } = this.props return ( <form onSubmit={handleSubmit(register)}> <Panel> <h3>Your Details</h3> <Field component={TextInput} label='First name' name='firstName' /> <Field component={TextInput} label='Last name' name='lastName' /> <Field component={TextInput} label='Phone number' name='phone' type='tel' /> <Field component={TextInput} label='Email' name='email' type='email' /> <p> Click submit to find out more about your ideal home. We’ll also show you what it might look like. </p> <p> Even better, we’ll take into account your preferences when designing future projects and give you the opportunity to buy before releasing the project to the public. </p> </Panel> </form> ) } } const validate = values => { const errors = {} if (!values.firstName) { errors.firstName = 'Required' } else if (values.firstName.length > 15) { errors.firstName = 'Must be 15 characters or less' } if (!values.lastName) { errors.lastName = 'Required' } else if (values.lastName.length > 15) { errors.lastName = 'Must be 15 characters or less' } if (!values.phone) { errors.phone = 'Required' } if (!values.email) { errors.email = 'Required' } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) { errors.email = 'Invalid email address' } return errors } export default connect( state => { const register = state.form.registry || {} return { values: register.values } }, dispatch => { return { register: values => dispatch(postRegistration(values)) } } )( reduxForm({ destroyOnUnmount: false, form: 'register', initialValues: { email: '', firstName: '', lastName: '', phone: '' }, validate })(RegisterForm) )
JavaScript
0.000003
@@ -46,16 +46,8 @@ rt %7B - Button, Pan @@ -353,27 +353,8 @@ bmit -, invalid, register %7D = @@ -416,18 +416,8 @@ bmit -(register) %7D%3E%0A
37315bec07a4daac32a9146fa55d656c9b3037e9
Fix accidental eval call
froide/problem/static/js/moderation.js
froide/problem/static/js/moderation.js
(function() { const HEARTBEAT_INVERAL = 30 * 1000; let socket, retryInterval, heartBeatInterval function connectSocket() { socket = createSocket(); if (retryInterval) { window.clearInterval(retryInterval); retryInterval = undefined; } socket.onopen = () => { heartBeatInterval = setInterval(() => { if (socket && socket.readyState === 1) { socket.send(JSON.stringify({type: 'heartbeat'})); } else { window.clearInterval(heartBeatInterval); heartBeatInterval = undefined; } }, HEARTBEAT_INVERAL); }; socket.onmessage = (e) => { const data = JSON.parse(e.data) if (data.userlist) { document.getElementById('moderators').innerText = data.userlist.join(', ') } }; socket.onclose = () => { console.error('Chat socket closed unexpectedly'); window.clearInterval(heartBeatInterval); heartBeatInterval = undefined; if (retryInterval === undefined) { retryInterval = window.setInterval(this.connectSocket, 3000); } }; } function createSocket() { let prot = 'ws'; if (document.location.protocol === 'https:') { prot = 'wss'; } return new WebSocket( `${prot}://${window.location.host}/ws/moderation/`); } function ready(fn) { if (document.readyState != 'loading'){ fn(); } else { document.addEventListener('DOMContentLoaded', fn); } } ready(connectSocket) }())
JavaScript
0.00001
@@ -996,13 +996,8 @@ val( -this. conn
905eed0de17cdfee070bb7ca6dc0e444a1dceece
introduce format for `many2one_reference` for form view
addons/web/static/src/js/fields/field_registry.js
addons/web/static/src/js/fields/field_registry.js
odoo.define('web.field_registry', function (require) { "use strict"; var Registry = require('web.Registry'); return new Registry(); }); odoo.define('web._field_registry', function (require) { "use strict"; var AbstractField = require('web.AbstractField'); var basic_fields = require('web.basic_fields'); var relational_fields = require('web.relational_fields'); var registry = require('web.field_registry'); var special_fields = require('web.special_fields'); // Basic fields registry .add('abstract', AbstractField) .add('input', basic_fields.InputField) .add('integer', basic_fields.FieldInteger) .add('boolean', basic_fields.FieldBoolean) .add('date', basic_fields.FieldDate) .add('datetime', basic_fields.FieldDateTime) .add('daterange', basic_fields.FieldDateRange) .add('domain', basic_fields.FieldDomain) .add('text', basic_fields.FieldText) .add('list.text', basic_fields.ListFieldText) .add('html', basic_fields.FieldText) .add('float', basic_fields.FieldFloat) .add('char', basic_fields.FieldChar) .add('link_button', basic_fields.LinkButton) .add('handle', basic_fields.HandleWidget) .add('email', basic_fields.FieldEmail) .add('phone', basic_fields.FieldPhone) .add('url', basic_fields.UrlWidget) .add('CopyClipboardText', basic_fields.TextCopyClipboard) .add('CopyClipboardChar', basic_fields.CharCopyClipboard) .add('image', basic_fields.FieldBinaryImage) .add('kanban.image', basic_fields.KanbanFieldBinaryImage) .add('binary', basic_fields.FieldBinaryFile) .add('pdf_viewer', basic_fields.FieldPdfViewer) .add('monetary', basic_fields.FieldMonetary) .add('percentage', basic_fields.FieldPercentage) .add('priority', basic_fields.PriorityWidget) .add('attachment_image', basic_fields.AttachmentImage) .add('label_selection', basic_fields.LabelSelection) .add('kanban_label_selection', basic_fields.LabelSelection) // deprecated, use label_selection .add('state_selection', basic_fields.StateSelectionWidget) .add('kanban_state_selection', basic_fields.StateSelectionWidget) // deprecated, use state_selection .add('boolean_favorite', basic_fields.FavoriteWidget) .add('boolean_toggle', basic_fields.BooleanToggle) .add('statinfo', basic_fields.StatInfo) .add('percentpie', basic_fields.FieldPercentPie) .add('float_time', basic_fields.FieldFloatTime) .add('float_factor', basic_fields.FieldFloatFactor) .add('float_toggle', basic_fields.FieldFloatToggle) .add('progressbar', basic_fields.FieldProgressBar) .add('toggle_button', basic_fields.FieldToggleBoolean) .add('dashboard_graph', basic_fields.JournalDashboardGraph) .add('ace', basic_fields.AceEditor) .add('color', basic_fields.FieldColor); // Relational fields registry .add('selection', relational_fields.FieldSelection) .add('radio', relational_fields.FieldRadio) .add('selection_badge', relational_fields.FieldSelectionBadge) .add('many2one', relational_fields.FieldMany2One) .add('many2one_barcode', relational_fields.Many2oneBarcode) .add('list.many2one', relational_fields.ListFieldMany2One) .add('kanban.many2one', relational_fields.KanbanFieldMany2One) .add('many2many', relational_fields.FieldMany2Many) .add('many2many_binary', relational_fields.FieldMany2ManyBinaryMultiFiles) .add('many2many_tags', relational_fields.FieldMany2ManyTags) .add('many2many_tags_avatar', relational_fields.FieldMany2ManyTagsAvatar) .add('form.many2many_tags', relational_fields.FormFieldMany2ManyTags) .add('kanban.many2many_tags', relational_fields.KanbanFieldMany2ManyTags) .add('many2many_checkboxes', relational_fields.FieldMany2ManyCheckBoxes) .add('one2many', relational_fields.FieldOne2Many) .add('statusbar', relational_fields.FieldStatus) .add('reference', relational_fields.FieldReference) .add('font', relational_fields.FieldSelectionFont); // Special fields registry .add('timezone_mismatch', special_fields.FieldTimezoneMismatch) .add('report_layout', special_fields.FieldReportLayout); });
JavaScript
0.000011
@@ -2785,16 +2785,74 @@ ldColor) +%0A .add('many2one_reference', basic_fields.FieldInteger) ;%0A%0A// Re
3a073b0644d1c82b58c7db47402e90be367defc8
Fix frontend bug in submit handler.
frontend/scripts/components/in-game.js
frontend/scripts/components/in-game.js
"use strict"; var React = require('react/addons') , TestOutput = require('./test-output') , Ide = require('./ide') , InGameChat = require('./in-game-chat') , InGameNav = require('./in-game-nav') , Problem = require('./problem') , Team = require('../team') , moment = require('moment') , request = require('superagent'); var InGameComponent = React.createClass({ teams: {ours: new Team('ours'), opponents: new Team('opponents')}, getInitialState: function () { return { current: this.teams.ours, showTestOutput: false, testOutput: null, isMyTurn: false, showProblem: true, problem: null }; }, componentDidMount: function () { this.props.socket.emit('game/didJoin'); this.props.socket.on('game/update', this.update); this.props.socket.on('game/chat', this.updateChat); this.props.socket.on('game/code', this.updateCode); this.props.socket.on('game/problem', this.updateProblem); this.props.socket.on('game/start', this.start); }, update: function (data) { this.teams.ours.users = data.ours.users; this.teams.opponents.users = data.opponents.users; var isMyTurn = data.ours.users.filter(function (user) { return user.me && user.current; }).length > 0; this.setState({ current: this.teams[this.state.current.side], isMyTurn: isMyTurn }); if (isMyTurn) { this.switchTo('ours'); } }, updateChat: function (data) { data.chat.datetime = moment().format('h:mm A'); this.teams[data.side].chatLogs = this.teams[data.side].chatLogs.concat([data.chat]); if (this.state.current.side === data.side) { this.setState({current: this.teams[this.state.current.side]}); } }, updateCode: function (data) { this.teams[data.side].code = data.code; if (this.state.current.side === data.side) { this.setState({current: this.teams[this.state.current.side]}); } }, updateProblem: function (data) { this.setState({problem: data}); }, start: function () { this.switchTo('ours'); }, render: function () { var shouldDisableIde = this.state.current.side !== this.teams.ours.side || !this.state.isMyTurn; var shouldDisableChat = this.state.current.side !== this.teams.ours.side || this.state.isMyTurn; var shouldDisableSubmit = !this.state.isMyTurn; var navTab = this.state.showProblem ? 'problem' : this.state.current.side; return ( <div id='in-game'> <div className='content'> <InGameNav runTest={this.runTest} tab={navTab} switchTo={this.switchTo} showProblem={this.showProblem} submit={this.submit} disableSubmit={shouldDisableSubmit} /> <div className='area-left'> <InGameChat disable={shouldDisableChat} users={this.state.current.users} chatLogs={this.state.current.chatLogs} chatHandler={this.sendChat} /> </div> <div className='area-right'> <Ide disable={shouldDisableIde} code={this.state.current.code} onChange={this.onIdeChange} /> <TestOutput show={this.state.showTestOutput} output={this.state.testOutput} close={this.closeTest} /> <Problem show={this.state.showProblem} problem={this.state.problem} /> </div> </div> </div> ); }, runTest: function () { var that = this; request .post('/test') .send({code: this.teams.ours.code}) .type('json') .end(function (res) { if (res.status === 200) { that.setState({showTestOutput: true, testOutput: res.body}); } }); }, switchTo: function (side) { this.setState({current: this.teams[side], showProblem: false}); }, showProblem: function () { this.setState({showProblem: true}); }, submit: function () { this.props.socket.emit('game/submit', {code: code}); }, closeTest: function () { this.setState({showTestOutput: false}); }, onIdeChange: function (code) { this.props.socket.emit('game/code', {code: code}); this.teams.ours.code = code; }, sendChat: function (text) { this.props.socket.emit('game/chat', {text: text}); } }); module.exports = InGameComponent;
JavaScript
0
@@ -4102,32 +4102,48 @@ submit', %7Bcode: +this.teams.ours. code%7D);%0A %7D,%0A c
148481a8941c168d5018fb74c77a54dc9f2c6c87
Fix problem where overwriteStyle fail if source is empty
sashimi-webapp/src/helpers/domUtils.js
sashimi-webapp/src/helpers/domUtils.js
export default { /** * Get computed style of an element. * @param {Element} element * @return {Object} computerd style object */ getComputedStyle(element) { return element.currentStyle || getComputedStyle(element); }, /** * Overwrite existing node's style with the given style */ overwriteStyle(target, source) { Object.keys(source).forEach((styleKey) => { target[styleKey] = source[styleKey]; }); }, computeElementHeight(element) { const nodeStyle = this.getComputedStyle(element); // Get node's height const nodeStyleHeight = parseFloat(nodeStyle.height, 10) || 0; const nodeHeight = Math.max( element.clientHeight, element.offsetHeight, nodeStyleHeight ); // Get node's margin const nodeMargin = parseFloat(nodeStyle.marginTop, 10) + parseFloat(nodeStyle.marginBottom, 10); const totalHeight = nodeHeight + nodeMargin; if (isNaN(totalHeight)) { throw new Error('Error calculating element\'s height'); } return totalHeight; }, };
JavaScript
0.000028
@@ -335,24 +335,51 @@ , source) %7B%0A + source = source %7C%7C %7B%7D;%0A Object.k
613d33a36f90be6d764f19f725b790acacf3a5f9
Revert "changed path stuff for deployment"
poerelief/static/javascripts/app.js
poerelief/static/javascripts/app.js
$( document ).ready(function() { $(".text-navigation a").on("click", function(e) { e.preventDefault(); var current = $("a.active"); current.removeClass("active"); /* Maybe change such as here for animation? http://jqueryui.com/removeClass/ */ $(current.data("target")).hide(); $(this).addClass("active"); $($(this).data("target")).show(); }); }); /* var S = require('string'); */ function getDoc(docid) { $.getJSON('/doc/' + docid, function( data ) { /* Name, date and pictures work quite well, though sometimes I have seen that there is no name and pictures are very different from each other */ /* The rest of the text however is a problem ... translation works best (except it needs whitespace stripped, or something ... I alread strip ab/lb tags that were still in the source date, but it's not enough) hebrew is more of a problem, as it is not always pure hebrew ... according to Thomas from the institute, recto/verso (as the original is called in the source) should almost always be hebrew. That is not always true though, sometimes it also is mixed with german ... (and either one can be empty) */ /* Also, if a a specific record is requested, that should be injected instead of a random one ... though not sure how to pass that through atm. In the template it is {{ret}} but not sure how to inser that into javascript */ var translation = S(data.translation).stripTags().trim(); $('#translation').text(translation); $('#original').html(data.edition); $('.left').html(data.edition); $('.right').text(translation); /*$('#original').append();*/ $('.center-cropped').css('background-image', "url("+data.graphicsurl+")"); $('#pname').html(data.pname + " [" + data.date + "]"); /* window.history.pushState({}, "Poetic Relief", "/" + data.locid); */ window.history.pushState({}, "Poetic Relief", data.locid); }); };
JavaScript
0
@@ -444,16 +444,26 @@ tJSON('/ +poerelief/ doc/' + @@ -1881,16 +1881,32 @@ Relief%22, + %22/poerelief/%22 + data.lo
dfd1be57fe0277fb884fd4fb512a27622196663b
fix perf data dialog scrolling
src/debug/DebugCommandHandlers.js
src/debug/DebugCommandHandlers.js
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, $, window */ define(function (require, exports, module) { 'use strict'; var Commands = require("command/Commands"), CommandManager = require("command/CommandManager"), Editor = require("editor/Editor").Editor, JSLintUtils = require("language/JSLintUtils"), PerfUtils = require("utils/PerfUtils"), NativeApp = require("utils/NativeApp"); function _handleEnableJSLint() { JSLintUtils.setEnabled(!JSLintUtils.getEnabled()); JSLintUtils.run(); $("#menu-debug-jslint").toggleClass("selected", JSLintUtils.getEnabled()); } // Implements the 'Run Tests' menu to bring up the Jasmine unit test window var _testWindow = null; function _handleRunUnitTests() { if (_testWindow) { try { _testWindow.location.reload(); } catch (e) { _testWindow = null; // the window was probably closed } } if (!_testWindow) { _testWindow = window.open("../test/SpecRunner.html"); _testWindow.location.reload(); // if it was opened before, we need to reload because it will be cached } } function _handleShowPerfData() { var $perfHeader = $("<div class='modal-header' />") .append("<a href='#' class='close'>&times;</a>") .append("<h1 class='dialog-title'>Performance Data</h1>") .append("<div align=right>Raw data (copy paste out): <textarea rows=1 style='width:30px; height:8px; overflow: hidden; resize: none' id='brackets-perf-raw-data'>" + PerfUtils.getDelimitedPerfData() + "</textarea></div>"); var $perfBody = $("<div class='modal-body' style='padding: 0' />"); var $data = $("<table class='zebra-striped condensed-table' style='max-height: 600px; overflow: auto;'>") .append("<thead><th>Operation</th><th>Time (ms)</th></thead>") .append("<tbody />") .appendTo($perfBody); var makeCell = function (content) { return $("<td/>").text(content); }; var getValue = function (entry) { // entry is either an Array or a number if (Array.isArray(entry)) { // For Array of values, return: minimum/average/maximum/last var i, e, avg, sum = 0, min = Number.MAX_VALUE, max = 0; for (i = 0; i < entry.length; i++) { e = entry[i]; min = Math.min(min, e); sum += e; max = Math.max(max, e); } avg = Math.round(sum / entry.length); return String(min) + "/" + String(avg) + "/" + String(max) + "/" + String(e); } else { return entry; } }; var testName; var perfData = PerfUtils.perfData; for (testName in perfData) { if (perfData.hasOwnProperty(testName)) { // Add row to error table $("<tr/>") .append(makeCell(testName)) .append(makeCell(getValue(perfData[testName]))) .appendTo($data); } } $("<div class='modal hide' />") .append($perfHeader) .append($perfBody) .appendTo(window.document.body) .modal({ backdrop: "static", show: true }); // Select the raw perf data field on click since select all doesn't // work outside of the editor $("#brackets-perf-raw-data").click(function () { $(this).focus().select(); }); } function _handleNewBracketsWindow() { window.open(window.location.href); } function _handleCloseAllLiveBrowsers() { NativeApp.closeAllLiveBrowsers().always(function () { console.log("all live browsers closed"); }); } function _handleUseTabChars() { Editor.setUseTabChar(!Editor.getUseTabChar()); $("#menu-experimental-usetab").toggleClass("selected", Editor.getUseTabChar()); } // Register all the command handlers CommandManager.register(Commands.DEBUG_JSLINT, _handleEnableJSLint); CommandManager.register(Commands.DEBUG_RUN_UNIT_TESTS, _handleRunUnitTests); CommandManager.register(Commands.DEBUG_SHOW_PERF_DATA, _handleShowPerfData); CommandManager.register(Commands.DEBUG_NEW_BRACKETS_WINDOW, _handleNewBracketsWindow); CommandManager.register(Commands.DEBUG_CLOSE_ALL_LIVE_BROWSERS, _handleCloseAllLiveBrowsers); CommandManager.register(Commands.DEBUG_USE_TAB_CHARS, _handleUseTabChars); });
JavaScript
0.000001
@@ -3098,16 +3098,52 @@ dding: 0 +; max-height: 500px; overflow: auto; ' /%3E%22);%0A @@ -3214,51 +3214,8 @@ ble' - style='max-height: 600px; overflow: auto;' %3E%22)%0A
2d1aa1ce4607836be97283e6ffaf3ad35e70ffcc
Refactored the code
src/astroprint/static/js/app/views/automatic-preheat.js
src/astroprint/static/js/app/views/automatic-preheat.js
/********************************* * Code by Kanishka Mohan Madhuni * **********************************/ var TempFilamentLoadPreheat = TempBarView.extend({ containerDimensions: null, scale: null, // array of the values coming from the printer profile type: null, dragging: false, // adding 'value' property to hold the object when the temperature updates value: null, events: _.extend(TempBarView.prototype.events, { 'click button.temp-off': 'turnOff' }), setHandle: function(value){ if (!this.dragging) { var handle = this.$el.find('.temp-target'); handle.find('span.target-value').text(value); } }, renderTemps: function(actual, target){ if (actual !== null) { this.$el.find('.current-temp-top').html(Math.round(actual)+'&deg;'); } if (target !== null) { this.setHandle(Math.min(Math.round(target), this.scale[1])); } }, }); var TempFilamentLoadPreheatView = Backbone.View.extend({ el: '#filament-load-wizard__temp-control', nozzleTempBar: null, initialize: function() { console.log("Yo Bro I am working fine yo"); // creating the new instance for controlling the nozzle temp-bar this.nozzleTempBar = new TempBarVerticalView({ scale: [0, app.printerProfile.get('max_nozzle_temp')], el: this.$el.find('.temp-control-cont.nozzle'), type: 'tool0' }); this.render(); }, render: function(){ var profile = app.printerProfile.toJSON(); // here we are setting the nozzleTempBar temperature to the max-nozzle-temp from the 'printerProfile' this.nozzleTempBar.setMax(profile.max_nozzle_temp); }, // this function is responsible for setting the nozzle and bed temperature updateBars: function(value) { if (value.extruder) { this.nozzleTempBar.setTemps(value.extruder.actual, value.extruder.target); } } }); var TempFilamentUnloadPreheatView = Backbone.View.extend({ el: '#filament-unload-wizard__temp-control', nozzleTempBar: null, initialize: function(){ console.log("Yo Bro I am working fine yo"); // creating the new instance for controlling the nozzle temp-bar this.nozzleTempBar = new TempBarVerticalView({ scale: [0, app.printerProfile.get('max_nozzle_temp')], el: this.$el.find('.temp-control-cont.nozzle'), type: 'tool0' }); this.render(); }, render: function(){ var profile = app.printerProfile.toJSON(); // here we are setting the nozzleTempBar temperature to the max-nozzle-temp from the 'printerProfile' this.nozzleTempBar.setMax(profile.max_nozzle_temp); }, // this function is responsible for setting the nozzle and bed temperature updateBars: function(value){ if (value.extruder) { this.nozzleTempBar.setTemps(value.extruder.actual, value.extruder.target); } } });
JavaScript
0.668927
@@ -104,807 +104,8 @@ */%0A%0A -var TempFilamentLoadPreheat = TempBarView.extend(%7B%0A containerDimensions: null,%0A scale: null, // array of the values coming from the printer profile%0A type: null,%0A dragging: false,%0A // adding 'value' property to hold the object when the temperature updates%0A value: null,%0A events: _.extend(TempBarView.prototype.events, %7B%0A 'click button.temp-off': 'turnOff'%0A %7D),%0A setHandle: function(value)%7B%0A if (!this.dragging) %7B%0A var handle = this.$el.find('.temp-target');%0A handle.find('span.target-value').text(value);%0A %7D%0A %7D,%0A renderTemps: function(actual, target)%7B%0A if (actual !== null) %7B%0A this.$el.find('.current-temp-top').html(Math.round(actual)+'&deg;');%0A %7D%0A if (target !== null) %7B%0A this.setHandle(Math.min(Math.round(target), this.scale%5B1%5D));%0A %7D%0A %7D,%0A%7D);%0A%0A var @@ -253,60 +253,11 @@ on() -%0A %7B %0A %09console.log(%22Yo Bro I am working fine yo%22); +%7B %0A %0A @@ -883,19 +883,16 @@ n(value) -%0A %7B%0A if @@ -997,24 +997,25 @@ );%0A %7D%0A %7D +, %0A%7D);%0A%0Avar Te @@ -1168,55 +1168,8 @@ )%7B %0A - %09console.log(%22Yo Bro I am working fine yo%22);%0A
7851faac17ebec683fa48c2dd265e472356c7a3e
Make iFrame size correctly when loaded
src/frontend/components/Survey.js
src/frontend/components/Survey.js
import React from 'react'; import Relay from 'react-relay'; class Survey extends React.Component { styles = { frame: { display: 'block', border: 'none', width: '100%', height: '100%', }, container: { width: '100%', height: '800px', } } render() { return ( <div style={this.styles.container}> <iframe scrolling="no" src={this.props.viewer.survey.BSDData.fullURL} style={this.styles.frame} /> </div> ) } } export default Relay.createContainer(Survey, { initialVariables: { id: null }, prepareVariables: (prev) => { return {id: prev.id} }, fragments: { viewer: () => Relay.QL` fragment on Viewer { survey(id:$id) { BSDData { fullURL } } } ` } })
JavaScript
0.000001
@@ -53,16 +53,53 @@ relay';%0A +import Radium from 'radium';%0A%0A@Radium %0Aclass S @@ -298,32 +298,687 @@ - height: '800px',%0A %7D +%7D%0A %7D%0A%0A handleMessageEvent = (event) =%3E %7B%0A if (event.origin !== this.iframeHost())%0A return;%0A%0A if (typeof event.data === 'number') %7B%0A this.setState(%7BiframeHeight: %7Bheight: event.data + 'px'%7D%7D)%0A %7D%0A %7D%0A%0A componentDidMount() %7B%0A window.addEventListener('message', this.handleMessageEvent)%0A %7D%0A%0A componentWillUnmount() %7B%0A window.removeEventListener('message', this.handleMessageEvent);%0A %7D%0A%0A state = %7B%0A iframeHeight : %7Bheight: '200px'%7D%0A %7D%0A%0A iframeHost() %7B%0A return this.props.viewer.survey.BSDData.fullURL.split('/').slice(0, 3).join('/');%0A %7D%0A%0A iframeLoaded = (event) =%3E %7B%0A event.target.contentWindow.postMessage('getHeight', this.iframeHost()) %0A %7D @@ -1015,32 +1015,33 @@ %3Cdiv style=%7B +%5B this.styles.cont @@ -1045,16 +1045,42 @@ ontainer +, this.state.iframeHeight%5D %7D%3E%0A @@ -1104,12 +1104,12 @@ ing= -%22no%22 +'no' src @@ -1177,16 +1177,43 @@ s.frame%7D + onLoad=%7Bthis.iframeLoaded%7D /%3E%0A
f79f76e63219a517712126f4186b2626704c7ef4
Remove debug console output.
src/html/js/angular/navigation.js
src/html/js/angular/navigation.js
/* Raspberry Pi Dasboard * ===================== * Copyright 2014 Domen Ipavec <domen.ipavec@z-v.si> * * 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. */ rpiDashboard.factory('Navigation', function($location, User) { var ads = {}; var menu = {}; return { register: function(path, accessDependencies, menuName, menuTitle) { ads[path] = accessDependencies; if (menuTitle == undefined) { menuTitle = ""; } menu[path] = { name: menuName, title: menuTitle, path: path }; }, registerDependencies: function(path, accessDependencies) { ads[path] = accessDependencies; }, getDependencies: function() { return ads[$location.path()]; }, getMenu: function() { var curMenu = []; angular.forEach(menu, function(entry) { if (User.checkDependencies(ads[entry.path])) { curMenu.push(entry); } }); return curMenu; }, getMenuEntry: function(path) { return menu[path]; } }; }); rpiDashboard.controller('NavigationController', function($scope, $location, User, Navigation) { $scope.loggedIn = false; $scope.menu = []; $scope.$on('USER_STATUS_CHANGED', function() { $scope.loggedIn = User.loggedIn; $scope.menu = Navigation.getMenu(); }); $scope.menuClass = function(page) { var current = $location.path().substring(1); return page.substring(1) === current ? "active" : ""; }; $scope.logout = function() { User.logout(); } }); rpiDashboard.controller('TitleDescriptionController', function($scope, $location, Navigation, $rootScope) { $scope.description = ""; $scope.title = ""; var refresh = function() { console.log("refresh"); var entry = Navigation.getMenuEntry($location.path()); if (entry == undefined) { $scope.titleShow = false; $scope.descriptionShow = false; } else { if (entry.name == undefined) { $scope.titleShow = false; } else { $scope.titleShow = true; $scope.title = entry.name; } if (entry.title == undefined) { $scope.descriptionShow = false; } else { $scope.descriptionShow = true; $scope.description = entry.title; } } }; refresh(); $rootScope.$on('$routeChangeStart', function() { refresh(); }); });
JavaScript
0
@@ -2467,40 +2467,8 @@ ) %7B%0A - console.log(%22refresh%22);%0A
2fd5a7977156c178ca69c51d8f4286a8e048946d
stop trying to detect indexeddb
src/start-things/system-requirements.js
src/start-things/system-requirements.js
function supportsIndexedDB() { // from http://bl.ocks.org/nolanlawson/c83e9039edf2278047e9 return new Promise((resolve, reject) => { let req = indexedDB.open('test', 1) req.onupgradeneeded = e => { let db = e.target.result db.createObjectStore('one', { keyPath: 'key', }) db.createObjectStore('two', { keyPath: 'key', }) } req.onerror = reject req.onsuccess = e => { let db = e.target.result let tx try { tx = db.transaction(['one', 'two'], 'readwrite') } catch (err) { reject(err) return } tx.oncomplete = () => { db.close() resolve(true) } let req = tx.objectStore('two').put({ 'key': 'true', }) req.onsuccess = () => {} req.onerror = reject } }) } function supportsFlexbox() { return document && 'flex' in document.body.style } export default function checkSystemReqirements() { let indexedDB = false try { supportsIndexedDB() indexedDB = true } catch (err) { indexedDB = false } const flexbox = supportsFlexbox() return indexedDB && flexbox }
JavaScript
0
@@ -884,16 +884,19 @@ ts() %7B%0A%09 +// let inde @@ -910,23 +910,29 @@ false%0A%09 +// try %7B%0A%09 +// %09support @@ -945,16 +945,19 @@ edDB()%0A%09 +// %09indexed @@ -967,19 +967,25 @@ = true%0A%09 -%7D%0A%09 +// %7D%0A%09// catch (e @@ -991,16 +991,19 @@ err) %7B%0A%09 +// %09indexed @@ -1014,19 +1014,25 @@ false%0A%09 -%7D%0A%09 +// %7D%0A%09// const fl @@ -1065,16 +1065,24 @@ %0A%09return + true // indexed
ee53b17c34ba92c51790b96ce2d3991527954c02
update href
src/controllers/replacement.js
src/controllers/replacement.js
var boom = require('boom') var braveHapi = require('../brave-hapi') var bson = require('bson') var Joi = require('joi') var underscore = require('underscore') var v1 = {} /* GET /v1/users/{userId}/replacement?... */ v1.get = { handler: function (runtime) { return async function (request, reply) { var ad, tag, count, href, img, result, url var debug = braveHapi.debug(module, request) var host = request.headers.host var protocol = request.url.protocol || 'http' var sessionId = request.query.sessionId var height = request.query.height var width = request.query.width var userId = request.params.userId var adUnits = runtime.db.get('ad_units') var sessions = runtime.db.get('sessions') var users = runtime.db.get('users') count = await users.update({ userId: userId }, { $inc: { statAdReplaceCount: 1 } }, { upsert: true }) if (typeof count === 'object') { count = count.nMatched } if (count === 0) { return reply(boom.notFound('user entry does not exist: ' + userId)) } ad = runtime.oip.adUnitForIntents([], width, height) if (ad) { debug('serving ' + ad.category + ': ' + ad.name) href = ad.lp img = '<img src="' + ad.url + '" />' tag = ad.name } else { href = 'https://brave.com/' img = '<img src="https://placeimg.com/' + width + '/' + height + '/any" />' tag = 'Use Brave' } result = await adUnits.insert(underscore.extend(request.query, { href: href, img: img } , underscore.omit(ad || {}, 'lp', 'url'))) url = 'data:text/html,<html><body style="width: ' + width + 'px; height: ' + height + 'px; padding: 0; margin: 0;">' + '<a href="' + protocol + '://' + host + '/v1/ad-clicks/' + result._id + '" target="_blank">' + img + '</a>' + '<div style="background-color:blue; color: white; font-weight: bold; position: absolute; top: 0;">' + tag + '</div></body></html>' // NB: X-Brave: header is just for debugging reply.redirect(url).header('x-brave', protocol + '://' + host + '/v1/ad-clicks/' + result._id) try { await sessions.update({ sessionId: sessionId }, { $currentDate: { timestamp: { $type: 'timestamp' } }, $set: { activity: 'ad' }, $inc: { statAdReplaceCount: 1 } }, { upsert: true }) } catch (ex) { debug('update failed', ex) } } }, description: 'Retrieves an ad replacement', notes: 'Returns a replacement ad, via a 301 to <pre>data:text/html;charset=utf-8,&lt;html&gt;...&lt;a href="https:.../v1/ad-clicks/{adUnitId}"&gt;&lt;img src="..." /&gt;&lt;/a&gt;...&lt;/html&gt;</pre>', tags: ['api'], validate: { query: { sessionId: Joi.string().guid().required().description('the identify of the session'), tagName: Joi.string().required().description('at present, always "IFRAME" (for the &lt;iframe/&gt; tag)'), width: Joi.number().positive().required().description('the width in pixels of the replacement ad'), height: Joi.number().positive().required().description('the height in pixels of the replacement ad') }, params: { userId: Joi.string().guid().required().description('the identity of the user entry') } }, response: { /* status: { 301: Joi.object({ location: Joi.string().required().description('redirection URL') }), 404: Joi.object({ boomlet: Joi.string().required().description('user entry does not exist') }) } */ } } /* GET /v1/ad-clicks/{adUnitId} */ v1.getClicks = { handler: function (runtime) { return async function (request, reply) { var result var debug = braveHapi.debug(module, request) var adUnitId = request.params.adUnitId var adUnits = runtime.db.get('ad_units') result = await adUnits.findOne({ _id: adUnitId }) if (!result) { return reply(boom.notFound('adUnitId does not refer to a replacement ad: ' + adUnitId)) } reply.redirect(result.href) try { await adUnits.update({ _id: adUnitId } , { $currentDate: { timestamp: { $type: 'timestamp' } } } , { upsert: true }) } catch (ex) { debug('update failed', ex) } } }, description: 'Performs an ad replacement click-through', notes: 'Returns a 301 redirect to the site associated with the replacement ad. This endpoint is returned via 301 by the <a href="/documentation#!/v1/v1usersuserIdreplacement_get_14" target="_blank">GET /v1/users/{userId}/replacement</a> operation.', tags: ['api'], validate: { params: { adUnitId: Joi.string().hex().description('ad replacement identifier').required() } }, response: { /* status: { 301: Joi.object({ location: Joi.string().required().description('redirection URL') }), 404: Joi.object({ boomlet: Joi.string().required().description('adUnitId does not refer to a replacement ad') }) } */ } } module.exports.routes = [ braveHapi.routes.async().path('/v1/users/{userId}/replacement').config(v1.get), braveHapi.routes.async().path('/v1/ad-clicks/{adUnitId}').config(v1.getClicks) ] module.exports.initialize = async function (debug, runtime) { runtime.db.checkIndices(debug, [ { category: runtime.db.get('ad_units'), name: 'ad_units', property: 'sessionId', empty: { sessionId: '' }, others: [ { sessionId: 1 } ] }, { category: runtime.db.get('sessions'), name: 'sessions', property: 'sessionId', empty: { userId: '', sessionId: '', timestamp: bson.Timestamp.ZERO, intents: [] }, unique: [ { sessionId: 1 } ], others: [ { userId: 0 }, { timestamp: 1 } ] } ]) }
JavaScript
0
@@ -4636,17 +4636,17 @@ nt_get_1 -4 +5 %22 target
e4ff2b2296967e604e700b1381b7979fbf4d23eb
Use relative paths for signing to avoid weird 7z error
script/lib/create-windows-installer.js
script/lib/create-windows-installer.js
'use strict' const downloadFileFromGithub = require('./download-file-from-github') const electronInstaller = require('electron-winstaller') const fs = require('fs-extra') const glob = require('glob') const os = require('os') const path = require('path') const spawnSync = require('./spawn-sync') const CONFIG = require('../config') module.exports = function (packagedAppPath, codeSign) { const options = { appDirectory: packagedAppPath, authors: 'GitHub Inc.', iconUrl: `https://raw.githubusercontent.com/atom/atom/master/resources/app-icons/${CONFIG.channel}/atom.ico`, loadingGif: path.join(CONFIG.repositoryRootPath, 'resources', 'win', 'loading.gif'), outputDirectory: CONFIG.buildOutputPath, remoteReleases: `https://atom.io/api/updates?version=${CONFIG.appMetadata.version}`, setupIcon: path.join(CONFIG.repositoryRootPath, 'resources', 'app-icons', CONFIG.channel, 'atom.ico') } const certPath = path.join(os.tmpdir(), 'win.p12') const signing = codeSign && process.env.WIN_P12KEY_URL if (signing) { downloadFileFromGithub(process.env.WIN_P12KEY_URL, certPath) var signParams = [] signParams.push(`/f ${certPath}`) // Signing cert file signParams.push(`/p ${process.env.WIN_P12KEY_PASSWORD}`) // Signing cert password signParams.push('/fd sha256') // File digest algorithm signParams.push('/tr http://timestamp.digicert.com') // Time stamp server signParams.push('/td sha256') // Times stamp algorithm options.signWithParams = signParams.join(' ') } else { console.log('Skipping code-signing. Specify the --code-sign option and provide a WIN_P12KEY_URL environment variable to perform code-signing'.gray) } const cleanUp = function () { if (fs.existsSync(certPath)) { console.log(`Deleting certificate at ${certPath}`) fs.removeSync(certPath) } for (let nupkgPath of glob.sync(`${CONFIG.buildOutputPath}/*.nupkg`)) { if (!nupkgPath.includes(CONFIG.appMetadata.version)) { console.log(`Deleting downloaded nupkg for previous version at ${nupkgPath} to prevent it from being stored as an artifact`) fs.removeSync(nupkgPath) } } } // Squirrel signs its own copy of the executables but we need them for the portable ZIP const extractSignedExes = function() { if (signing) { for (let nupkgPath of glob.sync(`${CONFIG.buildOutputPath}/*-full.nupkg`)) { if (nupkgPath.includes(CONFIG.appMetadata.version)) { console.log(`Extracting signed executables from ${nupkgPath} for use in portable zip`) const appPath = path.normalize(packagedAppPath) spawnSync('7z.exe', ['e', nupkgPath, 'lib\\net45\\*.exe', '-aoa', `-o"${appPath}"`]) spawnSync(process.env.COMSPEC, ['/c', `move /y "${path.join(appPath, 'squirrel.exe')}" "${path.join(appPath, 'update.exe')}"`]) return } } } } console.log(`Creating Windows Installer for ${packagedAppPath}`) return electronInstaller.createWindowsInstaller(options) .then(extractSignedExes, function (error) { console.log(`Extracting signed executables failed:\n${error}`) cleanUp() }) .then(cleanUp, function (error) { console.log(`Windows installer creation failed:\n${error}`) cleanUp() }) }
JavaScript
0
@@ -2586,33 +2586,91 @@ nst -appPath = path.normalize( +outPath = path.dirname(nupkgPath)%0A const appPath = path.relative(outPath, pack @@ -2717,16 +2717,39 @@ ', %5B'e', + path.relative(outPath, nupkgPa @@ -2750,16 +2750,17 @@ upkgPath +) , 'lib%5C%5C @@ -2785,17 +2785,16 @@ oa', %60-o -%22 $%7BappPat @@ -2795,19 +2795,35 @@ appPath%7D -%22 %60%5D +, %7B cwd:outPath %7D )%0A @@ -2873,17 +2873,16 @@ move /y -%22 $%7Bpath.j @@ -2914,11 +2914,9 @@ e')%7D -%22 %22 + $%7Bpa @@ -2950,11 +2950,27 @@ e')%7D -%22 %60%5D +, %7B cwd:outPath %7D )%0A
1142561532c66295ac172d4c9837a6f35e5d4b95
Improve config-parser JSON handling
ghost/admin/app/utils/config-parser.js
ghost/admin/app/utils/config-parser.js
var isNumeric = function (num) { return !isNaN(num); }, _mapType = function (val) { if (val === '') { return null; } else if (val === 'true') { return true; } else if (val === 'false') { return false; } else if (isNumeric(val)) { return +val; } else if (val.indexOf('{') === 0) { return JSON.parse(val); } else { return val; } }, parseConfiguration = function () { var metaConfigTags = $('meta[name^="env-"]'), propertyName, config = {}, value, key, i; for (i = 0; i < metaConfigTags.length; i += 1) { key = $(metaConfigTags[i]).prop('name'); value = $(metaConfigTags[i]).prop('content'); propertyName = key.substring(4); // produce config name ignoring the initial 'env-'. config[propertyName] = _mapType(value); // map string values to types if possible } return config; }; export default parseConfiguration;
JavaScript
0
@@ -374,24 +374,46 @@ ') === 0) %7B%0A + try %7B%0A @@ -436,16 +436,125 @@ e(val);%0A + %7D catch (e) %7B%0A /*jshint unused:false */%0A return val;%0A %7D%0A
aa549934b48dfb36fb4d3d9a28665df46df4e800
Add missing article
lib/node_modules/@stdlib/assert/is-json/test/test.js
lib/node_modules/@stdlib/assert/is-json/test/test.js
'use strict'; // MODULES // var tape = require( 'tape' ); var isJSON = require( './../lib' ); // TESTS // tape( 'main export is a function', function test( t ) { t.ok( true, __filename ); t.equal( typeof isJSON, 'function', 'main export is a function' ); t.end(); }); tape( 'function returns `true` if provided a parseable JSON string', function test( t ) { var bool; bool = isJSON( '{"a":5}' ); t.ok( bool ); bool = isJSON( '{}' ); t.ok( bool ); bool = isJSON( '[]' ); t.ok( bool ); t.end(); }); tape( 'function returns `false` if not provided a parseable JSON string', function test( t ) { var values; var i; values = [ 5, '5', 'true', 'null', 'NaN', '[', '{', ']', '}', '[{', ']}', '{[', '}]', null, undefined, true, NaN, function noop() {}, [], {}, '{a":5}', new String( '{"a":5}' ) ]; for ( i = 0; i < values.length; i++ ) { t.equal( isJSON( values[i] ), false, 'returns false when provided '+values[i] ); } t.end(); });
JavaScript
0.99986
@@ -269,32 +269,36 @@ ();%0A%7D);%0A%0Atape( ' +the function returns @@ -522,16 +522,20 @@ %0Atape( ' +the function
2cc934432f6e7c8c5b652789c4280967fd749a42
Fix joining/quitting server from server menu.
waartaa/client/chat/chat_connections/server.js
waartaa/client/chat/chat_connections/server.js
function serverRoomSelectHandler (event) { var $target = $(event.target); // Return if clicked on a server menu item if ($target.parents('.btn-group').length > 0) return; var prev_room = Session.get('room') || {}; var roomtypes = { 'channel': true, 'server': true, 'pm': true }; // Show loader if selected room is not yet active if (!$target.parent().hasClass('active')) { if ( ( roomtypes[$target.data('roomtype')] && $target.data('id') == prev_room.room_id ) || ( roomtypes[$target.data('roomtype')] && $target.data('roomid') == prev_room.room_id ) ) $target.parent().addClass('active'); else $('#chatlogs-loader').show(); } event.stopPropagation(); // Close any open menu $('.dropdown.open, .btn-group.open').removeClass('open'); if (prev_room.roomtype == 'server') Session.set( 'user_server_log_count_' + prev_room.server_id, DEFAULT_LOGS_COUNT); else if (prev_room.roomtype == 'channel') Session.set( 'user_channel_log_count_' + prev_room.channel_id, DEFAULT_LOGS_COUNT); else if (prev_room.roomtype == 'pm') Session.set( 'pmLogCount-' + prev_room.room_id, DEFAULT_LOGS_COUNT); Meteor.setTimeout(function () { if ($target.data('roomtype') == 'channel') { var server_id = $target.parents('.server').data('server-id'); var channel_id = $(event.target).data('id'); var channel = UserChannels.findOne({_id: channel_id}) || {}; waartaa.chat.helpers.setCurrentRoom({ roomtype: 'channel', server_id: server_id, channel_id: channel_id, channel_name: channel.name, server_name: channel.user_server_name }); } else if ($target.data('roomtype') == 'pm') { var server_id = $target.parents('.server').data('server-id'); var nick = $target.data('nick'); var server = UserServers.findOne({_id: server_id}); waartaa.chat.helpers.setCurrentRoom({ roomtype: 'pm', server_id: server_id, room_id: $target.data('roomid'), server_name: server.name, nick: nick }); } else if ( $target.data('roomtype') == 'server' || $target.parent().data('roomtype') == 'server') { var server_id = $target.parent().data('server-id') || $target.data('server-id'); var server = UserServers.findOne({_id: server_id}); waartaa.chat.helpers.setCurrentRoom({ roomtype: 'server', server_id: server_id, server_name: server.name }); } }, 200); } Template.chat_connection_server.events({ 'click .server-room': serverRoomSelectHandler, 'click .server-link': serverRoomSelectHandler }); Template.chat_connection_server.created = function () { Session.set("lastAccessedServer-" + this.data._id, new Date()); }; Template.chat_connection_server.helpers({ isServerActive: function () { if ((Session.get('room') || {}).server_id === this._id) return true; } }); Template.server_menu.events({ 'click .serverEditLink': function (e) { e.preventDefault(); e.stopPropagation(); var $this = $(e.target); var server_id = $this.data('server-id'); var $modal_content = $('#editServerModal-' + server_id); $this.parents('.open').removeClass('open'); $modal_content.modal().on('shown.bs.modal', function (e) { $modal_content.find('[name="nick"]').focus(); }) .on('hidden.bs.modal', function (e) { $('#chat-input').focus(); }); }, 'click .addChannelLink': function (e) { e.preventDefault(); e.stopPropagation(); var $this = $(e.target); var server_id = $this.data('server-id'); var $modal_content = $('#addServerChannel-' + server_id); $this.parents('.open').removeClass('open'); $modal_content.modal().on('shown.bs.modal', function (e) { $modal_content.find('input[name="names"]').focus(); }) .on('hidden.bs.modal', function (e) { $('#chat-input').focus(); }); }, 'click .server-remove': function (e) { var server_id = $(e.target).data("server-id"); var server = UserServers.findOne({_id: server_id}); Meteor.call( "quit_user_server", server.name, true); }, 'click .toggleJoinServer': function (e) { e.preventDefault(); e.stopPropagation(); var $this = $(e.target); var server_id = $this.data('server-id'); var server = UserServers.findOne({_id: server_id}); if (!server) return; var status = $this.data('status'); if (status == 'connected') Meteor.call( "quit_user_server", server.name, false); else Meteor.call('join_user_server', server.name); } }); Template.add_server_channel.events({ 'submit form': function (e) { e.preventDefault(); e.stopPropagation(); var $form = $(e.target); var data = {}; var server_id = $form.parents('.modal').data('server-id'); $.each($form.serializeArray(), function (index, value) { data[value.name] = value.value; }); var server = UserServers.findOne({_id: server_id}); Meteor.call('join_user_channel', server.name, data.names); var $modal_content = $('#addServerChannel-' + server_id); $modal_content.modal('hide'); } }); updateUnreadLogsCount = function (unread_logs_count_key, last_accessed_key, last_updated, update_session) { var last_accessed = Session.get(last_accessed_key); var count = 0; if (last_updated > last_accessed) { var unread_logs_count = Session.get(unread_logs_count_key) || 0; unread_logs_count += 1; count += 1; if (update_session) Session.set(unread_logs_count_key, unread_logs_count); } return count; }; updateUnreadMentionsCount = function ( unread_mentions_count_key, last_accessed_key, last_updated, update_session) { var last_accessed = Session.get(last_accessed_key); var count = 0; if (last_updated > last_accessed) { var unread_mentions_count = Session.get(unread_mentions_count_key) || 0; unread_mentions_count += 1; count += 1; if (update_session) Session.set(unread_mentions_count_key, unread_mentions_count); } return count; };
JavaScript
0
@@ -4424,33 +4424,40 @@ var $this = $(e. -t +currentT arget);%0A var @@ -4603,22 +4603,27 @@ = $this. +attr(' data -(' +- status')
de56c8fb6af535040dcf6a5852b1a789954d7570
Patch mismatch methods
modern/src/maki-interpreter/objectData/stdPatched.js
modern/src/maki-interpreter/objectData/stdPatched.js
const std = require("./std.json"); // Between myself and the author of the decompiler, a number of manual tweaks // have been made to our current object definitions. This function recreates // those tweaks so we can have an apples to apples comparison. /* * From object.js * * > The std.mi has this set as void, but we checked in Winamp and confirmed it * > returns 0/1 */ std["5D0C5BB67DE14b1fA70F8D1659941941"].functions[5].result = "boolean"; /* * From Object.pm * * > note, std.mi does not have this parameter! */ std.B4DCCFFF81FE4bcc961B720FD5BE0FFF.functions[0].parameters[0][1] = "onoff"; module.exports = std;
JavaScript
0.000001
@@ -29,16 +29,267 @@ son%22);%0A%0A +const NAME_TO_DEF = %7B%7D;%0A%0AObject.values(std).forEach(value =%3E %7B%0A NAME_TO_DEF%5Bvalue.name%5D = value;%0A%7D);%0A%0Afunction getMethod(className, methodName) %7B%0A return NAME_TO_DEF%5BclassName%5D.functions.find((%7B name %7D) =%3E %7B%0A return name === methodName;%0A %7D);%0A%7D%0A%0A // Betwe @@ -628,60 +628,39 @@ */%0A -std%5B%225D0C5BB67DE14b1fA70F8D1659941941%22%5D.functions%5B5%5D +getMethod(%22Timer%22, %22isRunning%22) .res @@ -757,57 +757,252 @@ */%0A -std.B4DCCFFF81FE4bcc961B720FD5BE0FFF.functions%5B0%5D +getMethod(%22ToggleButton%22, %22onToggle%22).parameters%5B0%5D%5B1%5D = %22onoff%22;%0A%0A// Some methods are not compatible with the type signature of their parent class%0AgetMethod(%22GuiTree%22, %22onChar%22).parameters%5B0%5D%5B0%5D = %22string%22;%0AgetMethod(%22GuiList%22, %22onSetVisible%22) .par @@ -1012,29 +1012,798 @@ ters%5B0%5D%5B -1 +0 %5D = %22 -onoff%22; +boolean%22;%0A%0A// I'm not sure how to get these to match%0AgetMethod(%22Wac%22, %22onNotify%22).parameters = getMethod(%0A %22Object%22,%0A %22onNotify%22%0A).parameters;%0AgetMethod(%22Wac%22, %22onNotify%22).result = %22int%22;%0A%0A/*%0A%0AHere's the error we get without that patch:%0A%0Amodern/__generated__/makiInterfaces.ts:254:18 - error TS2430: Interface 'Wac' incorrectly extends interface 'MakiObject'.%0A Types of property 'onnotify' are incompatible.%0A Type '(notifstr: string, a: number, b: number) =%3E void' is not assignable to type '(command: string, param: string, a: number, b: number) =%3E number'.%0A Types of parameters 'a' and 'param' are incompatible.%0A Type 'string' is not assignable to type 'number'.%0A%0A254 export interface Wac extends MakiObject %7B%0A ~~~%0A%0A%0AFound 1 error.%0A%0A */ %0A%0Amodule
1566f8d6003f413aedb52ed336b2bd19a45bd0ac
fix #949
app/controllers/money/report/transactionReport.js
app/controllers/money/report/transactionReport.js
Alloy.Globals.extendsBaseViewController($, arguments[0]); var title="收支汇总",interval="日",intervalQuery, d = new Date(), queryOptions = { dateFrom : d.getUTCTimeOfDateStart().toISOString(), dateTo : d.getUTCTimeOfDateEnd().toISOString(), transactionDisplayType : Alloy.Models.User.xGet("defaultTransactionDisplayType") }; function setTitle(){ if(!intervalQuery){ intervalQuery = interval === "查询" ? "(查询)" : ""; } if(queryOptions.transactionDisplayType === "Personal"){ $.titleBar.setTitle("个人" + (interval !== "查询" ? interval : "") + title + intervalQuery); } else { $.titleBar.setTitle("项目" + (interval !== "查询" ? interval : "") + title + intervalQuery); } } $.onWindowOpenDo(function() { if ($.getCurrentWindow().$attrs.queryOptions) { _.extend(queryOptions, $.getCurrentWindow().$attrs.queryOptions); } interval = "日"; exports.refresh(); }); function onFooterbarTap(e) { if (e.source.id === "personalStat") { queryOptions.transactionDisplayType = "Personal"; exports.refresh(); } else if (e.source.id === "projectStat") { queryOptions.transactionDisplayType = "Project"; exports.refresh(); } else if (e.source.id === "dateTransactions") { dateTransactions(); } else if (e.source.id === "weekTransactions") { weekTransactions(); } else if (e.source.id === "monthTransactions") { monthTransactions(); } else if (e.source.id === "transactionsSummuryQuery") { Alloy.Globals.openWindow("money/moneyQuery", { selectorCallback : doQuery, queryOptions : queryOptions }); } } function dateTransactions() { var dat = new Date(); queryOptions.dateFrom = dat.getUTCTimeOfDateStart().toISOString(); queryOptions.dateTo = dat.getUTCTimeOfDateEnd().toISOString(); interval = "日"; exports.refresh(); } function weekTransactions() { queryOptions.dateFrom = d.getUTCTimeOfWeekStart().toISOString(); queryOptions.dateTo = d.getUTCTimeOfWeekEnd().toISOString(); interval = "周"; exports.refresh(); } function monthTransactions() { queryOptions.dateFrom = d.getUTCTimeOfMonthStart().toISOString(); queryOptions.dateTo = d.getUTCTimeOfMonthEnd().toISOString(); interval = "月"; exports.refresh(); } exports.getQueryString = function(prefix, notPersonalData) { var filterStr = ""; prefix = prefix || "main"; for (var f in queryOptions) { var value = queryOptions[f]; if (_.isNull(value)) { continue; } if (f === "transactionDisplayType") { if (value === "Personal" && !notPersonalData) { filterStr += " AND " + prefix + ".ownerUserId = '" + Alloy.Models.User.id + "'"; } continue; } if (filterStr) { filterStr += " AND "; } f = prefix + "." + f; if (_.isNumber(value)) { filterStr += f + " = " + value + " "; } else if (value !== undefined) { if (f === prefix + ".dateFrom") { filterStr += prefix + ".date >= '" + value + "' "; } else if (f === prefix + ".dateTo") { filterStr += prefix + ".date <= '" + value + "' "; } else if (f === prefix + ".project") { filterStr += prefix + ".projectId = '" + value.id + "' "; } else { filterStr += f + " = '" + value + "' "; } } } return filterStr; }; function doQuery(queryController) { queryOptions = queryController.queryOptions; interval = "查询"; exports.refresh(); } exports.refresh = function() { setTitle(); var queryStr = exports.getQueryString(); $.moneyIncomeTotal.query(queryStr); $.moneyExpenseTotal.query(queryStr); $.moneyBorrowTotal.query(queryStr); $.moneyReturnTotal.query(queryStr); $.moneyLendTotal.query(queryStr); $.moneyPaybackTotal.query(queryStr); $.moneyReturnInterestTotal.query(queryStr); $.moneyPaybackInterestTotal.query(queryStr); if(queryOptions.transactionDisplayType === "Personal"){ $.moneyExpenseApportionTotalContainer.setHeight(42); $.moneyIncomeApportionTotalContainer.setHeight(42); queryStr = exports.getQueryString("mi", true); $.moneyExpenseApportionTotal.query(queryStr); $.moneyIncomeApportionTotal.query(queryStr); } else { $.moneyExpenseApportionTotalContainer.setHeight(0); $.moneyIncomeApportionTotalContainer.setHeight(0); } calculateTotalBalance(); }; function calculateTotalBalance() { var totalBalance = 0; // totalBalance = $.moneyIncomeTotal.getValue() - $.moneyExpenseTotal.getValue() + // $.moneyBorrowTotal.getValue() - $.moneyReturnTotal.getValue() - // $.moneyLendTotal.getValue() + $.moneyPaybackTotal.getValue() - // $.moneyReturnInterestTotal.getValue() + $.moneyPaybackInterestTotal.getValue(); totalBalance = $.moneyIncomeTotal.getValue() - $.moneyExpenseTotal.getValue() + $.moneyReturnInterestTotal.getValue() + $.moneyPaybackInterestTotal.getValue(); // if(queryOptions.transactionDisplayType === "Personal"){ // totalBalance += $.moneyIncomeApportionTotal.getValue() - $.moneyExpenseApportionTotal.getValue(); // } $.totalBalance.setText(totalBalance.toUserCurrency()); } $.incomeTotalCurrencySymbol.UIInit($, $.getCurrentWindow()); $.expenseTotalCurrencySymbol.UIInit($, $.getCurrentWindow()); $.borrowTotalCurrencySymbol.UIInit($, $.getCurrentWindow()); $.returnTotalCurrencySymbol.UIInit($, $.getCurrentWindow()); $.lendTotalCurrencySymbol.UIInit($, $.getCurrentWindow()); $.paybackTotalCurrencySymbol.UIInit($, $.getCurrentWindow()); $.balanceTotalCurrencySymbol.UIInit($, $.getCurrentWindow()); $.paybackInterestTotalCurrencySymbol.UIInit($, $.getCurrentWindow()); $.returnInterestTotalCurrencySymbol.UIInit($, $.getCurrentWindow()); $.moneyExpenseApportionCurrencySymbol.UIInit($, $.getCurrentWindow()); $.moneyIncomeApportionCurrencySymbol.UIInit($, $.getCurrentWindow()); $.titleBar.UIInit($, $.getCurrentWindow());
JavaScript
0
@@ -4550,17 +4550,17 @@ Value() -+ +%EF%BC%8D %0A%09%09%09%09%09$
418caa66775967a5799a1b15f796ce4c9fbf8d42
Fix issue #24
table/static/js/bootstrap.dataTables.js
table/static/js/bootstrap.dataTables.js
/* Set the defaults for DataTables initialisation */ $.extend( true, $.fn.dataTable.defaults, { "sDom": "<'row'<'col-xs-6'l><'col-xs-6'f>r>t<'row'<'col-xs-6'i><'col-xs-6'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_", "sSearch": "", "sInfoFiltered": "", "sProcessing": "加载中", }, "bAutoWidth": false, "fnPreDrawCallback": function(oSettings, json) { $('.dataTables_filter input').addClass('form-control input'); $('.dataTables_length select').addClass('form-control input'); $('.dataTables_info').addClass('form-control'); } }); /* Default class modification */ $.extend( $.fn.dataTableExt.oStdClasses, { "sWrapper": "dataTables_wrapper form-inline", "sFilterInput": "form-control input-sm", "sLengthSelect": "form-control input-sm" }); /* API method to get hidden rows */ $.fn.dataTableExt.oApi.fnGetHiddenNodes = function ( oSettings ) { /* Note the use of a DataTables 'private' function thought the 'oApi' object */ // DataTables 1.10 var api = new jQuery.fn.dataTable.Api( oSettings ); var anNodes = api.rows().nodes().toArray(); // var anNodes = this.oApi._fnGetTrNodes( oSettings ); var anDisplay = $('tbody tr', oSettings.nTable); /* Remove nodes which are being displayed */ for ( var i=0 ; i<anDisplay.length ; i++ ) { var iIndex = jQuery.inArray( anDisplay[i], anNodes ); if ( iIndex != -1 ) { anNodes.splice( iIndex, 1 ); } } /* Fire back the array to the caller */ return anNodes; }; /* API method to get paging information */ $.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings ) { return { "iStart": oSettings._iDisplayStart, "iEnd": oSettings.fnDisplayEnd(), "iLength": oSettings._iDisplayLength, "iTotal": oSettings.fnRecordsTotal(), "iFilteredTotal": oSettings.fnRecordsDisplay(), "iPage": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ), "iTotalPages": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength ) }; }; /* Bootstrap style pagination control */ $.extend( $.fn.dataTableExt.oPagination, { "bootstrap": { "fnInit": function( oSettings, nPaging, fnDraw ) { var oLang = oSettings.oLanguage.oPaginate; var fnClickHandler = function ( e ) { e.preventDefault(); if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) { fnDraw( oSettings ); } }; $(nPaging).append( '<ul class="pagination">'+ '<li class="prev disabled"><a href="#">'+oLang.sPrevious+'</a></li>'+ '<li class="next disabled"><a href="#">'+oLang.sNext+'</a></li>'+ '</ul>' ); var els = $('a', nPaging); $(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler ); $(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler ); }, "fnUpdate": function ( oSettings, fnDraw ) { var iListLength = 5; var oPaging = oSettings.oInstance.fnPagingInfo(); var an = oSettings.aanFeatures.p; var i, ien, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2); if ( oPaging.iTotalPages < iListLength) { iStart = 1; iEnd = oPaging.iTotalPages; } else if ( oPaging.iPage <= iHalf ) { iStart = 1; iEnd = iListLength; } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) { iStart = oPaging.iTotalPages - iListLength + 1; iEnd = oPaging.iTotalPages; } else { iStart = oPaging.iPage - iHalf + 1; iEnd = iStart + iListLength - 1; } for ( i=0, ien=an.length ; i<ien ; i++ ) { // Remove the middle elements $('li:gt(0)', an[i]).filter(':not(:last)').remove(); // Add the new list items and their event handlers for ( j=iStart ; j<=iEnd ; j++ ) { sClass = (j==oPaging.iPage+1) ? 'class="active"' : ''; $('<li '+sClass+'><a href="#">'+j+'</a></li>') .insertBefore( $('li:last', an[i])[0] ) .bind('click', function (e) { e.preventDefault(); oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength; fnDraw( oSettings ); } ); } // Add / remove disabled classes from the static elements if ( oPaging.iPage === 0 ) { $('li:first', an[i]).addClass('disabled'); } else { $('li:first', an[i]).removeClass('disabled'); } if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) { $('li:last', an[i]).addClass('disabled'); } else { $('li:last', an[i]).removeClass('disabled'); } } } } } ); /* * TableTools Bootstrap compatibility * Required TableTools 2.1+ */ if ( $.fn.DataTable.TableTools ) { // Set the classes that TableTools uses to something suitable for Bootstrap $.extend( true, $.fn.DataTable.TableTools.classes, { "container": "DTTT btn-group", "buttons": { "normal": "btn btn-default", "disabled": "disabled" }, "collection": { "container": "DTTT_dropdown dropdown-menu", "buttons": { "normal": "", "disabled": "disabled" } }, "print": { "info": "DTTT_print_info modal" }, "select": { "row": "active" } } ); // Have the collection use a bootstrap compatible dropdown $.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, { "collection": { "container": "ul", "button": "li", "liner": "a" } } ); }
JavaScript
0
@@ -341,11 +341,15 @@ %22: %22 -%E5%8A%A0%E8%BD%BD%E4%B8%AD +Loading %22,%0A
d8d0bf8d4947b038418d7950c3c86bf1948d4c6e
add @pingy/cli to deps for install
packages/cli/init.js
packages/cli/init.js
'use strict'; const inquirer = require('inquirer'); const ora = require('ora'); const fs = require('fs'); const chalk = require('chalk'); const path = require('path'); const validFilename = require('valid-filename'); const spawn = require('child_process').spawn; const compilerMap = require('./compilerMap'); const dotPingyTmpl = require('./dotPingyTmpl'); const createChoices = (type) => [ type, ...compilerMap[type].map(x => x.name) ] const nameToModule = (type, prettyName) => (compilerMap[type].find(x => x.name === prettyName) || {}).module; const stage1 = [ { type: 'list', name: 'html', message: 'What document format do you wish to use', choices: createChoices('HTML'), }, { type: 'list', name: 'styles', message: 'What styles format do you wish to use', choices: createChoices('CSS'), }, { type: 'list', name: 'scripts', message: 'What scripts format do you wish to use', choices: createChoices('JS'), }, { type: 'input', name: 'exportDir', message: 'Choose the folder name to export compiled files to', default: 'dist', validate: (input) => { if (!validFilename(input)) return 'Invalid folder name'; return true; } }, ]; function prepare() { inquirer.prompt(stage1).then((answers) => { const modules = { html: nameToModule('HTML', answers.html), css: nameToModule('CSS', answers.styles), js: nameToModule('JS', answers.scripts), } // TODO: add '@pingy/cli' below const deps = [modules.html, modules.css, modules.js].filter(x => !!x); const pkgJsonPath = path.join(process.cwd(), 'package.json') const pkgJsonExists = fs.existsSync(pkgJsonPath); if (!pkgJsonExists) { const npmInit = spawn('npm', ['init'], { stdio: 'inherit' }); npmInit.on('exit', (code) => { if (code === 0) { updatePkgScripts(pkgJsonPath, answers); installDeps(deps); } else ora().fail(`npm init failed with code: ${code}`); }); } else { updatePkgScripts(pkgJsonPath, answers); installDeps(deps) } }); } function installDeps(deps) { if (deps.length === 0) { console.log(`\nNo dependencies needed. ${chalk.green('Done!')}`); return; } console.log('\nReady to install dependencies.'); console.log('\nCommand that will now be run:'); console.log( ' > ' + chalk.bold.underline(`npm install --save-dev ${deps.join(' ')}\n`) ); inquirer.prompt([{ type: 'confirm', name: 'installDeps', message: 'Run this command now?', default: true }]).then(({ installDeps }) => { if (installDeps) { const npmInstall = spawn( 'npm', ['install', '--save-dev', ...deps], { stdio: 'inherit' } ); npmInstall.on('exit', (code) => { if (code === 0) ora().succeed('Dependencies installed'); else ora().fail(`Dependency install failed with code: ${code}`); }); } else { console.log( `OK, you should run the ${chalk.bold.underline('underlined')} command above manually.` ) } }); } function updatePkgScripts(pkgJsonPath, answers) { const spinner = ora('Adding pingy scripts to package.json').start(); try { const pkgJson = require(pkgJsonPath); pkgJson.scripts.start = 'pingy serve'; pkgJson.scripts.export = 'pingy export'; fs.writeFileSync(pkgJsonPath, JSON.stringify(pkgJson)); spinner.succeed(`Pingy scripts added to package.json`); createDotPingy(pkgJson.name, answers.exportDir); } catch(e) { spinner.fail(err); return; } } function createDotPingy(name) { const filename = '.pingy.json'; const spinner = ora(`Creating ${filename}`).start(); try { fs.writeFileSync(path.join(process.cwd(), filename), dotPingyTmpl(name), 'utf8'); } catch(e) { spinner.fail(err); return; } spinner.succeed(`Created ${filename}`); } module.exports = () => prepare();
JavaScript
0
@@ -1475,62 +1475,48 @@ %7D%0A +%0A -// TODO: add '@pingy/cli' below%0A const deps = %5B +const deps = %5B%0A '@pingy/cli', modu @@ -1548,16 +1548,21 @@ dules.js +%0A %5D.filter
6c9fce93ee7f95b7c2f01800a92d196a92da72ba
Fix protocol fee
www/js/controllers/exchange/TradeController.js
www/js/controllers/exchange/TradeController.js
angular.module("omniControllers") .controller("ExchangeTradeController",["$scope", "PropertyManager","MIN_MINER_FEE","PROTOCOL_FEE", function ExchangeTradeController($scope, PropertyManager,MIN_MINER_FEE,PROTOCOL_FEE) { $scope.minersFee = MIN_MINER_FEE; $scope.protocolFee = PROTOCOL_FEE; //init and use global to pass data around $scope.global = {} $scope.onTradeView = true $scope.history = '/views/wallet/history.html'; $scope.inactive = $scope.account.getSetting("filterdexdust"); $scope.setView = function(view, data) { if (view != 'tradeInfo'){ if (view == 'saleOffer') { $scope.onSaleView = true; $scope.saleView = $scope.tradeTemplates[view]; $scope.onTradeView = false; } else { $scope.tradeView = $scope.tradeTemplates[view]; $scope.onSaleView = false; $scope.onTradeView = false; } } else { $scope.tradeView = $scope.tradeTemplates[view]; $scope.onTradeView = true; $scope.onSaleView = false; $scope.showNoCoinAlert = false; } $scope.global[view] = data; } $scope.hideNoCoinAlert = function() { $scope.showNoCoinAlert = false; } $scope.$on("setView", function(event, args){ $scope.setView(args.view,args.data); }); $scope.tradeTemplates = { 'tradeInfo': '/views/wallet/partials/exchange_overview.html', 'simpleSend': '/views/wallet/send.html', 'buyOffer': '/views/wallet/partials/buy.html', 'saleOffer': '/views/wallet/partials/sale.html' }; //initialize the data used in the template $scope.currPairs = [] PropertyManager.getProperty(1).then(function(result){ var omni = result.data; omni.symbol = "MSC";//"OMNI"; $scope.currPairs.splice(0,0,{0:$scope.wallet.getAsset(0),1:omni,view:"/views/wallet/partials/trade.html",active:true}); $scope.setActiveCurrencyPair(); }) if ( $scope.account.getSetting("showtesteco") === 'true'){ PropertyManager.getProperty(2).then(function(result){ var tomni = result.data; tomni.symbol = "TMSC"; //"T-OMNI"; $scope.currPairs.splice(1,0,{0:$scope.wallet.getAsset(0),1:tomni,view:"/views/wallet/partials/trade.html"}); }) } //Get the active currency pair $scope.activeCurrencyPair = [] $scope.setActiveCurrencyPair = function(currencyPair) { //DEBUG console.log(currencyPair); if (!currencyPair) $scope.activeCurrencyPair = $scope.currPairs[0] else $scope.activeCurrencyPair = currencyPair $scope.hasCoins = $scope.wallet.getAsset($scope.activeCurrencyPair[1].propertyid) != undefined; $scope.selectedAsset = $scope.wallet.getAsset($scope.activeCurrencyPair[1].propertyid); var random = Math.random(); $scope.saleView = '/views/wallet/partials/sale.html?r='+random; $scope.showNoCoinAlert = false; } }])
JavaScript
0.000003
@@ -112,16 +112,21 @@ R_FEE%22,%22 +OMNI_ PROTOCOL @@ -126,19 +126,20 @@ ROTOCOL_ -FEE +COST %22,%0A%09%09fun
96d2679556b9707cfd0640f853ffa7cf50401049
Remove setVersion from storage isolation test
chrome/test/data/extensions/platform_apps/web_view_isolation/storage.js
chrome/test/data/extensions/platform_apps/web_view_isolation/storage.js
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This method initializes the two types of DOM storage. function initDomStorage(value) { window.localStorage.setItem('foo', 'local-' + value); window.sessionStorage.setItem('bar', 'session-' + value); } // The code below is used for testing IndexedDB isolation. // The test uses three basic operations -- open, read, write -- to verify proper // isolation across webview tags with different storage partitions. // Each of the basic functions below sets document.title to a specific text, // which the main browser test is waiting for. This is needed because all // the functions get their results through callbacks and cannot return the // values directly. var isolation = {}; window.indexedDB = window.indexedDB || window.webkitIndexedDB; isolation.db = null; isolation.onerror = function(e) { document.title = "error"; }; // This method opens the database and creates the objectStore if it doesn't // exist. It sets the document.title to a string referring to which // operation has been performed - open vs create. function initIDB() { var request = indexedDB.open("isolation"); request.onsuccess = function(e) { var v = 3; isolation.db = e.target.result; if (v != isolation.db.version) { var setVrequest = isolation.db.setVersion(v); setVrequest.onerror = isolation.onerror; setVrequest.onsuccess = function(e) { var store = isolation.db.createObjectStore( "partitions", {keyPath: "id"}); e.target.transaction.oncomplete = function() { document.title = "idb created"; } }; } else { document.title = "idb open"; } }; request.onerror = isolation.onerror; } // This method adds a |value| to the database identified by |id|. function addItemIDB(id, value) { var trans = isolation.db.transaction(["partitions"], "readwrite"); var store = trans.objectStore("partitions"); var data = { "partition": value, "id": id }; var request = store.put(data); request.onsuccess = function(e) { document.title = "addItemIDB complete"; }; request.onerror = isolation.onerror; }; var storedValue = null; // This method reads an item from the database, identified by |id|. Since // the value cannot be returned directly, it is saved into the global // "storedValue" variable, which is then read through getValueIDB(). function readItemIDB(id) { storedValue = null; var trans = isolation.db.transaction(["partitions"], "readwrite"); var store = trans.objectStore("partitions"); var request = store.get(id); request.onsuccess = function(e) { if (!!e.target.result != false) { storedValue = request.result.partition; } document.title = "readItemIDB complete"; }; request.onerror = isolation.onerror; } function getValueIDB() { return storedValue; }
JavaScript
0.000002
@@ -1222,46 +1222,374 @@ var -request = indexedDB.open(%22isolation%22); +v = 3;%0A var ranVersionChangeTransaction = false;%0A var request = indexedDB.open(%22isolation%22, v);%0A request.onupgradeneeded = function(e) %7B%0A isolation.db = e.target.result;%0A var store = isolation.db.createObjectStore(%0A %22partitions%22, %7BkeyPath: %22id%22%7D);%0A e.target.transaction.oncomplete = function() %7B%0A ranVersionChangeTransaction = true;%0A %7D%0A %7D %0A r @@ -1625,23 +1625,8 @@ ) %7B%0A - var v = 3;%0A @@ -1669,327 +1669,35 @@ if ( -v != isolation.db.version) %7B%0A var setVrequest = isolation.db.setVersion(v);%0A setVrequest.onerror = isolation.onerror;%0A setVrequest.onsuccess = function(e) %7B%0A var store = isolation.db.createObjectStore(%0A %22partitions%22, %7BkeyPath: %22id%22%7D);%0A e.target.transaction.oncomplete = function( +ranVersionChangeTransaction ) %7B%0A @@ -1702,20 +1702,16 @@ %7B%0A - - document @@ -1738,27 +1738,8 @@ d%22;%0A - %7D%0A %7D;%0A @@ -1789,24 +1789,24 @@ %0A %7D%0A %7D;%0A - request.on @@ -1832,16 +1832,57 @@ nerror;%0A + request.onblocked = isolation.onerror;%0A %7D%0A%0A// Th
0227e4d849b907d4aaa59d2b8f69467badf7a741
update to new browserify script style
app/templates/assets/src/js/_script-browserify.js
app/templates/assets/src/js/_script-browserify.js
/* Author: <%= devNames %> <%= projectName %> */ // --------------------------------------------- // // DEFINE GLOBAL LIBS // // --------------------------------------------- // <% if (jsLibs.indexOf('jquery1') != -1 || jsLibs.indexOf('jquery2') != -1) {%>window.jQuery = window.$ = require('../../../node_modules/jquery/dist/jquery.js'); <% } else { %>// Uncomment the line below to expose jQuery as a global object to the usual places // window.jQuery = window.$ = require('../../../node_modules/jquery/dist/jquery.js'); <% } %> // force compilation of global libs that don't return a value. require("./helpers/log"); <% if (shims === true) {%>require("./helpers/shims");<% } %> //initialise <%= jsNamespace.toUpperCase() %> object var <%= jsNamespace.toUpperCase() %> = {}; <%= jsNamespace.toUpperCase() %>.Config = { init : function () { console.debug('Kickoff is running'); // Example module include <%= jsNamespace.toUpperCase() %>.UI = require('./modules/UI'); <%= jsNamespace.toUpperCase() %>.UI.init(); } }; <%= jsNamespace.toUpperCase() %>.Config.init();
JavaScript
0
@@ -1,215 +1,337 @@ /* -%09Author: %3C%25= devNames %25%3E%0A%09%09%3C%25= projectName %25%3E%0A*/%0A%0A// --------------------------------------------- //%0A// DEFINE GLOBAL LIBS //%0A// --------------------------------------------- //%0A%3C%25 +*%0A * Project Name: %3C%25= projectName %25%3E%0A * Client:%0A * Author: %3C%25= devNames %25%3E%0A * Company:%0A */%0A%0A'use-strict';%0A%0A// npm modules%0Avar ready = require('lite-ready');%3C%25%0Aif (jsLibs.indexOf('swiftclick') != -1) %7B%25%3E%0Avar SwiftClick = require('swiftclick');%3C%25 %7D %25%3E%3C%25%0Aif (jsLibs.indexOf('trak') != -1) %7B%25%3E%0Avar trak = require('trak.js');%3C%25 %7D %25%3E%3C%25%0A if ( @@ -401,16 +401,17 @@ -1) %7B%25%3E +%0A window.j @@ -442,271 +442,163 @@ re(' -../../../node_modules/jquery/dist/jquery.js +jquery '); -%0A %3C%25 %7D -else %7B %25%3E// Uncomment the line below to expose jQuery as a global object to the usual places%0A// window.jQuery = window.$ = require('../../../node_modules/jquery/dist/jquery.js');%0A%3C%25 %7D %25%3E%0A%0A// force compilation of +%25%3E%0A%0A%0A// Our own modules%0A// var browserifyTest = require('./modules/browserifyTest'); // this is a test module, uncomment to try it%0A%0A// Bundle glo @@ -631,17 +631,16 @@ a value -. %0Arequire @@ -644,29 +644,22 @@ ire( -%22./helpers/log%22 +'console' ); -%0A %3C%25 - +%0A if ( @@ -719,401 +719,313 @@ %0A%0A// -initialise %3C%25= jsNamespace.toUpperCase() %25%3E object%0Avar %3C%25= jsNamespace.toUpperCase() %25%3E = %7B%7D;%0A%0A%3C%25= jsNamespace.toUpperCase() %25%3E.Config = %7B%0A%0A%09init : function () %7B%0A%09%09console.debug('Kickoff is running');%0A%0A%09%09// Example module include%0A%09%09%3C%25= jsNamespace.toUpperCase() %25%3E.UI = require('./modules/UI');%0A%09%09%3C%25= jsNamespace.toUpperCase() %25%3E.UI.init();%0A%09%7D%0A%7D;%0A%0A%0A%3C%25= jsNamespace.toUpperCase() %25%3E.Config.init( + DOM ready code goes in here%0Aready(function () %7B%3C%25%0Aif (jsLibs.indexOf('trak') != -1) %7B%25%3E%0A%09trak.start();%3C%25 %7D %25%3E%3C%25%0Aif (jsLibs.indexOf('swiftclick') != -1) %7B%25%3E%0A%09var swiftclick = SwiftClick.attach(document.body);%3C%25 %7D %25%3E%0A%0A%09// browserifyTest(); // this is a test, uncomment this line & the line above to try it%0A%7D );%0A
617eaf7930cbfa93e479dc8ea3501ae2d2768fc3
Fix prefetch path
Azkfile.js
Azkfile.js
systems({ 'web': { depends: ['db', 'memcached', 'redis'], image: {'docker': 'azukiapp/node:5'}, provision: [ 'npm install' ], workdir: '/azk/#{manifest.dir}', shell: '/bin/bash', command: "node --use_strict src/web/web.js", wait: 20, mounts: { '/azk/#{manifest.dir}': sync('.'), '/azk/#{manifest.dir}/node_modules': persistent('./node_modules'), }, scalable: {'default': 1}, http: { domains: ['#{manifest.dir}-#{system.name}.#{azk.default_domain}'] }, ports: { http: '2708/tcp' }, envs: { NODE_ENV: 'dev', PORT: '2708', }, }, 'collector': { depends: ['redis'], image: {'docker': 'azukiapp/node:5'}, provision: [ 'npm install' ], workdir: '/azk/#{manifest.dir}', shell: '/bin/bash', command: "node --use_strict src/collector/collector.js", wait: 20, mounts: { '/azk/#{manifest.dir}': sync('.'), '/azk/#{manifest.dir}/node_modules': persistent('./node_modules'), }, scalable: {'default': 1}, envs: { NODE_ENV: 'dev', }, }, 'processor': { depends: ['redis', 'db'], image: {'docker': 'azukiapp/node:5'}, provision: [ 'npm install' ], workdir: '/azk/#{manifest.dir}', shell: '/bin/bash', command: "node --use_strict src/processor/processor.js", wait: 20, mounts: { '/azk/#{manifest.dir}': sync('.'), '/azk/#{manifest.dir}/node_modules': persistent('./node_modules'), }, scalable: {'default': 1}, envs: { NODE_ENV: 'dev', }, }, 'prefetch': { depends: ['redis', 'db', 'memcached'], image: {'docker': 'azukiapp/node:5'}, provision: [ 'npm install' ], workdir: '/azk/#{manifest.dir}', shell: '/bin/bash', command: "node --use_strict src/prefetch/processor.js", wait: 20, mounts: { '/azk/#{manifest.dir}': sync('.'), '/azk/#{manifest.dir}/node_modules': persistent('./node_modules'), }, scalable: {'default': 1}, envs: { NODE_ENV: 'dev', }, }, 'db': { image: {'docker': 'azukiapp/mongodb'}, scalable: false, wait: {'retry': 20, 'timeout': 1000}, mounts: { '/data/db': persistent('mongodb-#{manifest.dir}'), }, ports: { http: '28017:28017/tcp', }, http: { domains: ['#{manifest.dir}-#{system.name}.#{azk.default_domain}'], }, export_envs: { MONGODB_URI: 'mongodb://#{net.host}:#{net.port[27017]}/#{manifest.dir}_development' }, }, 'memcached': { image: {'docker': 'memcached'}, scalable: false, wait: {'retry': 20, 'timeout': 1000}, ports: { http: '11211:11211/tcp' }, http: { domains: ['#{manifest.dir}-#{system.name}.#{azk.default_domain}'] }, export_envs: { MEMCACHED_HOST: '#{net.host}', MEMCACHED_PORT: '#{net.port[11211]}' } }, 'redis': { image: { docker: 'redis' }, ports: { http: '6379:6379/tcp' }, http: { domains: ['#{manifest.dir}-#{system.name}.#{azk.default_domain}'] }, export_envs: { REDIS_URL: 'redis://#{manifest.dir}-#{system.name}.#{azk.default_domain}:#{net.port[6379]}', REDIS_HOST: '#{net.host}', REDIS_PORT: '#{net.port[6379]}' } } });
JavaScript
0.000013
@@ -2152,23 +2152,22 @@ fetch/pr -ocessor +efetch .js%22,%0A
1d123ef6226700b84d13a4242d660ad098517307
Add dockblock for EventBridge
web/assets/js/browser/services/event-bridge.js
web/assets/js/browser/services/event-bridge.js
/* global define */ /* jshint indent:2 */ define([ 'app' ], function(app) { 'use strict'; app.service('mbEventBridge', ['$rootScope', function($rootScope){ $rootScope.$on('browser.load', function() { $rootScope.$broadcast('_browser.load'); }); $rootScope.$on('browser.loaded', function() { $rootScope.$broadcast('_browser.loaded'); }); $rootScope.$on('$stateChangeSuccess', function(evt, toState, toParams, fromState, fromParams){ if (toState.name === 'workspace' && fromState.name !== 'workspace') { // open a workspace coming from repositories ou repository route $rootScope.$broadcast('workspace.open.success', toParams.repository, toParams.workspace); } else if(toState.name === 'workspace' && toState.name === fromState.name && (toParams.repository !== fromParams.repository || toParams.workspace !== fromParams.workspace)) { // open a workspace coming from another workspace $rootScope.$broadcast('workspace.open.success', toParams.repository, toParams.workspace); } else if(toState.name === fromState.name && (toParams.repository !== fromParams.repository || toParams.workspace !== fromParams.workspace)) { // open a repository $rootScope.$broadcast('repository.open.success', toParams.repository, toParams.workspace); } else if(toState.name === fromState.name && toState.name === 'workspace' && toParams.repository === fromParams.repository && toParams.workspace === fromParams.workspace && toParams.path !== fromParams.path) { // open a node in a workspace $rootScope.$broadcast('node.open.success', toParams.repository, toParams.workspace, toParams.path); } }); $rootScope.$on('$stateChangeStart', function(evt, toState, toParams, fromState, fromParams){ if (toState.name === 'workspace' && fromState.name !== 'workspace') { // open a workspace coming from repositories ou repository route $rootScope.$broadcast('workspace.open.start', toParams.repository, toParams.workspace); } else if(toState.name === 'workspace' && toState.name === fromState.name && (toParams.repository !== fromParams.repository || toParams.workspace !== fromParams.workspace)) { // open a workspace coming from another workspace $rootScope.$broadcast('workspace.open.start', toParams.repository, toParams.workspace); } else if(toState.name === fromState.name && (toParams.repository !== fromParams.repository || toParams.workspace !== fromParams.workspace)) { // open a repository $rootScope.$broadcast('repository.open.start', toParams.repository, toParams.workspace); } else if(toState.name === fromState.name && toState.name === 'workspace' && toParams.repository === fromParams.repository && toParams.workspace === fromParams.workspace && toParams.path !== fromParams.path) { // open a node in a workspace $rootScope.$broadcast('node.open.start', toParams.repository, toParams.workspace, toParams.path); } }); }]); });
JavaScript
0
@@ -89,16 +89,119 @@ rict';%0A%0A + /**%0A * EventBridge is in charge of broadcasting some custom events and forwarding some ones.%0A */%0A app.se @@ -259,16 +259,67 @@ tScope)%7B +%0A%0A /**%0A * Forward browser.load event%0A */ %0A $ro @@ -406,32 +406,84 @@ oad');%0A %7D);%0A%0A + /**%0A * Forward browser.loaded event%0A */%0A $rootScope.$ @@ -565,32 +565,139 @@ ded');%0A %7D);%0A%0A + /**%0A * Broadcast repository.open.success, workspace.open.success, node.open.success events%0A */%0A $rootScope.$ @@ -2079,24 +2079,125 @@ %7D%0A %7D);%0A%0A + /**%0A * Broadcast repository.open.start, workspace.open.start, node.open.start events%0A */%0A $rootSco
20780c7c4b61e8ed8f1f4ab8c4be01925b9490dc
build agenda tree UI components
web/src/main/webapp/krms/scripts/agendaTree.js
web/src/main/webapp/krms/scripts/agendaTree.js
function ajaxCall(controllerMethod, collectionGroupId) { var elementToBlock = jq('#' + collectionGroupId + '_div'); var selectedItemId = jq('input[name="agenda_item_selected"]').val(); if (selectedItemId) { var updateCollectionCallback = function(htmlContent){ var component = jq('#' + collectionGroupId + '_div', htmlContent); elementToBlock.unblock({onUnblock: function(){ //replace component if(jq('#' + collectionGroupId + '_div').length){ jq('#' + collectionGroupId + '_div').replaceWith(component); } runHiddenScripts(collectionGroupId + '_div'); } }); }; ajaxSubmitForm(controllerMethod, updateCollectionCallback, {reqComponentId: collectionGroupId, skipViewInit: 'true', agenda_item_selected: selectedItemId}, elementToBlock); } else { alert('Please select an agenda item first.'); } }
JavaScript
0
@@ -947,16 +947,78 @@ else %7B%0A + // TODO: refactor to disabled buttons, or externalize%0A
a224cccd2e8841c9d25c6e0261f2176b7aadb73e
Remove floating text edit toolbar
website/mosaicportfolio/static/js/app/views.js
website/mosaicportfolio/static/js/app/views.js
var RepositoryView = Backbone.View.extend({ projectUri: null, applicationState: null, initialize: function(options) { this.id = this.$('.repository-id').val(); this.projectModel = options.projectModel; this.applicationState = options.applicationState; this.applicationState.on('change', this.render, this); this.projectModel.on('save', this.save, this); }, render: function() { if (this.applicationState.get('editMode')) { this.$el.show(); } else { this.$el.hide(); } }, save: function() { if (this.$('.repository-url').val() == '' || this.$('.repository-login').val() == '') { return; } console.log('saving'); console.log(this.projectModel.get('resource_uri')); var repository = new Repository({ url: this.$('.repository-url').val(), concrete_type: this.$('.repository-type').val(), login: this.$('.repository-login').val(), project: this.projectModel.get('resource_uri') }); if (this.id != undefined) { repository.set('resource_uri', '/api/rest/v1/repository/' + this.id + '/'); repository.set('id', this.id); } repository.save(); repository.fetch(); } }); var ProjectView = Backbone.View.extend({ userModel: null, initialize: function(options) { this.userModel = options.userModel; this.applicationState = options.applicationState; this.applicationState.on('save', this.save, this); this.applicationState.on('change', this.render, this); var id = this.$('.project-id').val(); if (id != undefined && id != '') { this.model = new Project({ id: id, resource_uri: '/api/rest/v1/project/' + id + '/' }); var graphid = this.$('.graph').attr('id'); ActivityGraphing().drawProjectGraph(id, 100, 260, graphid, true); } else { this.model = new Project(); } var that = this; this.$('.repository').each(function(index, elm) { repository = new RepositoryView({ el: $(elm), applicationState: that.applicationState, projectModel: that.model }); repository.render(); }); repository = new RepositoryView({ el: this.$('.repository-sample'), applicationState: that.applicationState, projectModel: that.model }); repository.render(); }, render: function() { }, save: function() { this.model.set('name', this.$('.project-name').html()); this.model.set('tag_line', this.$('.project-tagline').html()); this.model.set('description', this.$('.project-description').html()); this.model.set('user', this.userModel.get('resource_uri')); var that = this; this.model.save().success(function() { that.model.trigger('save'); }); } }); var ProjectsView = Backbone.View.extend({ applicationState: null, userModel: null, events: { 'click .newProject': 'newProject' }, initialize: function(options) { this.applicationState = options.applicationState; this.applicationState.on('change', this.render, this); this.userModel = options.userModel; $('.project-sample').hide(); var that = this; $('.project').each(function(index, elm) { new ProjectView({ el: $(elm), applicationState: that.applicationState, userModel: that.userModel }).render(); }); }, render: function() { var count = this.$('.project').length; this.$('.project-count').html(count); if (count > 0) { this.$('.no-project-message').hide(); } if (this.applicationState.get('editMode') == false) { this.$('.newProject').hide(); } else { this.$('.newProject').show(); } }, newProject: function() { var projectDom = $('.project-sample').clone(); projectDom.removeClass('project-sample'); projectDom.addClass('project'); projectDom.show(); new ProjectView({ el: projectDom, applicationState: this.applicationState, userModel: this.userModel }).render(); $('.project-list').prepend(projectDom); this.render(); } }); var PortfolioPage = Backbone.View.extend({ applicationState: null, events: { 'click .doEdit': 'editHandler', 'click .doSave': 'saveHandler' }, initialize: function(options) { this.applicationState = options.applicationState; this.userModel = options.userModel; this.applicationState.on('change', this.render, this); this.applicationState.on('save', this.save, this); $('.editable').hallo({ plugins: { 'halloformat': {}, 'halloblock': {}, 'hallolists': {}, 'halloreundo': {}, 'hallolink': {} }, editable: false }) new ProjectsView({ el: $('.projects'), applicationState: this.applicationState, userModel: this.userModel }).render(); }, render: function() { var editBtn = $('.doEdit'); var saveBtn = $('.doSave'); if (this.applicationState.get('editMode')) { editBtn.hide(); saveBtn.show(); } else { editBtn.show(); saveBtn.hide(); } var that = this; $('.editable').each(function(index, element) { $(element).hallo({editable: that.applicationState.get('editMode')}); if (that.applicationState.get('editMode')) { $(element).addClass('editable-enabled'); } else { $(element).removeClass('editable-enabled'); } }); }, editHandler: function() { this.applicationState.set('editMode', true); this.applicationState.change(); }, saveHandler: function() { this.applicationState.set('editMode', false); this.applicationState.change(); this.applicationState.trigger('save'); }, save: function() { var profile = this.userModel.get('profile'); profile['tag_line'] = $('.portfolio-tagline').html(); profile['about'] = $('.portfolio-about').html(); this.userModel.set('first_name', $('.portfolio-name').html()); this.userModel.set('profile', profile); this.userModel.save(); } });
JavaScript
0.000001
@@ -5157,24 +5157,26 @@ +// 'halloformat @@ -5194,24 +5194,26 @@ +// 'halloblock' @@ -5226,32 +5226,34 @@ +// 'hallolists': %7B%7D @@ -5266,24 +5266,26 @@ +// 'halloreundo @@ -5307,16 +5307,18 @@ +// 'halloli
a1d68d4f11e6328979b1e0c01c776459356e9878
Fix resolution of the control element associated with a label element
tools/docs/api/build-docs/static/js/script.js
tools/docs/api/build-docs/static/js/script.js
/* eslint-disable strict */ (function script() { // eslint-disable-line no-restricted-syntax 'use strict'; main(); /** * Main execution sequence. * * @private */ function main() { var state; var links; var el; var i; // Initialize the browser history state: if ( history && history.replaceState ) { state = { 'url': location.href }; history.replaceState( state, '', location.href ); } // Add an event listener for whenever the active history changes: if ( window.addEventListener ) { window.addEventListener( 'popstate', onPopState ); } else if ( window.attachEvent ) { // Non-standard IE8 and previous versions: el.attachEvent( 'onpopstate', onPopState ); } // The goal is to intercept all navigation links so we can manually manage how content is loaded into the current page. This allows us to prevent fresh page loads each time a user clicks on a menu link. el = document.querySelector( '.slideout-menu' ); links = el.querySelectorAll( 'a' ); // For each link, add a `click` listener we'll use to intercept requests for new resources... for ( i = 0; i < links.length; i++ ) { addClickListener( links[ i ], onClick ); } } // end FUNCTION main() /** * Callback invoked upon a change in the active history. * * @private * @param {Object} evt - event object */ function onPopState( evt ) { if ( evt.state && evt.state.url ) { load( evt.state.url, false ); } } // end FUNCTION onPopState() /** * Adds a `click` event listener. * * @private * @param {DOMElement} el - DOM element to which to attach the listener * @param {Callback} clbk - callback invoked upon a `click` event */ function addClickListener( el, clbk ) { if ( el.addEventListener ) { el.addEventListener( 'click', clbk ); } else if ( el.attachEvent ) { // Non-standard IE8 and previous versions: el.attachEvent( 'onclick', clbk ); } } // end FUNCTION addClickListener() /** * Callback invoked upon a `click` event. * * @private * @param {Object} evt - event object */ function onClick( evt ) { var parent; var target; var href; // Prevent the browser from doing its default behavior (e.g., navigating to a new page): evt.preventDefault(); // Get the target element: target = evt.target || evt.srcElement; // Get the parent node: parent = target.parentNode; // Update the status of the parent input element: parent.previousSibling.checked = true; // Extract the resource name to we can request it manually: href = target.getAttribute( 'href' ); // Load the resource: load( href, true ); } // end FUNCTION onClick() /** * Loads a resource. * * @private * @param {string} url - URL (relative or absolute) * @param {boolean} bool - boolean indicating whether to update the browser history */ function load( url, bool ) { var xhttp; // Request the resource... xhttp = new XMLHttpRequest(); // TODO: account for older IE browsers xhttp.onreadystatechange = onReady; xhttp.open( 'GET', url, true ); xhttp.send(); /** * Callback invoked upon a state change in the HTTP request. * * @private */ function onReady() { var container; var state; var tmp; var el; // Process the request once the request is complete and successful... if ( this.readyState === 4 && this.status === 200 ) { // eslint-disable-line no-invalid-this // Create a temporary DOM element into which we can insert the request HTML page (note: we don't have to worry about the requested HTML containing script tags, as script content is not executed when using `innerHTML`): container = document.createElement( 'div' ); container.innerHTML = this.responseText; // eslint-disable-line no-invalid-this // Extract the content we want to load into the existing page: tmp = container.querySelector( '.readme' ); // Insert the content into the page: el = document.querySelector( '.readme' ); el.innerHTML = tmp.innerHTML; // Update the top navigation: tmp = container.querySelector( '.top-nav' ); el = document.querySelector( '.top-nav' ); el.innerHTML = tmp.innerHTML; // Reset the scroll position: document.querySelector( 'body' ).scrollTop = 0; // Update the document title: document.title = container.querySelector( 'title' ).innerHTML; // Update browser history (note: browser history API available IE10+): if ( bool && history && history.pushState ) { state = { 'url': url }; history.pushState( state, '', url ); } } } // end FUNCTION onReady() } // end FUNCTION load() })();
JavaScript
0
@@ -2323,16 +2323,55 @@ ent node + (we expect it to be a %60label%60 element) :%0A%09%09pare @@ -2429,28 +2429,31 @@ the -parent +control %60 input +%60 element :%0A%09%09 @@ -2452,34 +2452,134 @@ ment -:%0A%09%09parent.previousSibling + associated with the %60label%60 (see https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control):%0A%09%09parent.control .che
29b23a29b8b7f15ffdcc74430fbb3b8fc9f9af47
Add error-handling to fuzzy search and fix render
src/scenes/home/codeSchools/stateSortedSchools/stateSortedSchools.js
src/scenes/home/codeSchools/stateSortedSchools/stateSortedSchools.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Section from 'shared/components/section/section'; import SchoolCard from 'shared/components/schoolCard/schoolCard'; import FormInput from 'shared/components/form/formInput/formInput'; import styles from './stateSortedSchools.css'; import stateCodes from '../stateCodes.json'; class StateSortedSchools extends Component { constructor(props) { super(props); this.state = { query: null, schoolsByState: null }; } onSearchChange = (value) => { if (value.length > 1) { // Prevent query with just one character in search field this.setState({ query: value }); this.setState({ schoolsByState: this.searchState(value) }); } else { // Clear results when search field is 1 char or blank this.setState({ query: null }); this.setState({ schoolsByState: null }); } } searchState = (string) => { const userInput = string.replace(/\w\S*/g, txt => txt.toUpperCase()); const schools = []; // Return true if input matches state code or name (ex: "CA or California") function matchesState(school, input) { const stateName = stateCodes[school.state].toUpperCase(); return school.state.includes(input) || stateName.includes(input); } this.props.schools.forEach((school) => { school.locations.filter(_school => matchesState(_school, userInput)).forEach((location) => { schools.push({ name: school.name, url: school.url, address: location.address1, city: location.city, state: location.state, zip: location.zip, logo: school.logo, va_accepted: location.va_accepted, full_time: school.full_time, hardware_included: school.hardware_included }); }); }); return schools; }; render() { const stateSchools = !this.state.schoolsByState ? null : this.state.schoolsByState .map(school => ( <SchoolCard key={school.address} alt={school.name} schoolName={school.name} link={school.url} schoolAddress={school.address} schoolCity={school.city} schoolState={school.state} logo={school.logo} GI={school.va_accepted ? 'Yes' : 'No'} fullTime={school.full_time ? 'Full-Time' : 'Flexible'} hardware={school.hardware_included ? 'Yes' : 'No'} /> ) ); return ( <Section id="schoolsByState" title="Schools by State" theme="white" headingLines={false} margin > <FormInput placeholder="Start typing a state..." onChange={this.onSearchChange} id="search" /> <div className={styles.stateSchools}> {stateSchools} </div> </Section> ); } } StateSortedSchools.propTypes = { schools: PropTypes.array.isRequired // eslint-disable-line }; export default StateSortedSchools;
JavaScript
0
@@ -1029,17 +1029,25 @@ const -s +matchingS chools = @@ -1074,17 +1074,21 @@ true if -i +thisI nput mat @@ -1092,16 +1092,29 @@ matches +thisCampus's state co @@ -1179,25 +1179,47 @@ ate( -school, input) +thisInput, thisCampus) %7B%0A try %7B%0A + @@ -1249,22 +1249,26 @@ teCodes%5B -school +thisCampus .state%5D. @@ -1288,29 +1288,35 @@ ;%0A + return -school +thisCampus .state.i @@ -1319,25 +1319,29 @@ te.includes( -i +thisI nput) %7C%7C sta @@ -1360,16 +1360,294 @@ des( -i +thisI nput);%0A + %7D catch (e) %7B%0A if (e instanceof TypeError) %7B%0A console.log('Error: Typo in code_schools.yaml on the back-end under the %60state%60 field');%0A console.log(e);%0A return false;%0A %7D%0A // Unknown error issue%0A return e;%0A %7D%0A @@ -1724,23 +1724,24 @@ .filter( -_school +location =%3E matc @@ -1753,17 +1753,8 @@ ate( -_school, user @@ -1758,16 +1758,26 @@ serInput +, location )).forEa @@ -1780,24 +1780,22 @@ orEach(( -location +campus ) =%3E %7B%0A @@ -1797,25 +1797,33 @@ %3E %7B%0A -s +matchingS chools.push( @@ -1899,24 +1899,22 @@ ddress: -location +campus .address @@ -1932,24 +1932,22 @@ city: -location +campus .city,%0A @@ -1962,24 +1962,22 @@ state: -location +campus .state,%0A @@ -1991,24 +1991,22 @@ zip: -location +campus .zip,%0A @@ -2055,24 +2055,22 @@ cepted: -location +campus .va_acce @@ -2210,17 +2210,25 @@ return -s +matchingS chools;%0A
7f0ca4caa8d44f037eae77792e32587e16310876
Allow admin users to edit/update all of their attributes during profile edit. On successful edit/update, reload the UI to reflect the changes in the name and corresponding letter avatar.
www/app/modules/administrative/user/addedit.js
www/app/modules/administrative/user/addedit.js
angular.module('os.administrative.user.addedit', ['os.administrative.models']) .controller('UserAddEditCtrl', function( $scope, $rootScope, $state, $stateParams, user, users, currentUser, User, Institute, AuthDomain, Util, TimeZone, LocationChangeListener) { var instituteSites = {}, prevInstitute; function init() { prevInstitute = user.instituteName; $scope.user = user; $scope.signedUp = false; loadPvs(); $scope.disabledFields = {fields: {}}; if (user.$$editProfile && !user.admin) { [ 'firstName', 'lastName', 'emailAddress', 'domainName', 'loginName', 'instituteName', 'primarySite', 'type', 'manageForms' ].forEach(function(f) { $scope.disabledFields.fields['user.' + f] = true; }); } } function loadPvs() { $scope.domains = []; AuthDomain.getDomainNames().then( function(domains) { $scope.domains = domains; if (!$scope.user.id && $scope.domains.length == 1) { $scope.user.domainName = $scope.domains[0]; } } ); if (!currentUser) { return; } $scope.timeZones = []; TimeZone.query().then( function(timeZones) { $scope.timeZones = timeZones; } ); } function loadSites(instituteName, siteName) { if (!instituteName || instituteName.length == 0) { $scope.sites = []; return; } var sites = instituteSites[instituteName]; if (sites && sites.length < 100) { $scope.sites = sites; return; } Institute.getSites(instituteName, siteName).then( function(sites) { $scope.sites = sites.map(function(site) { return site.name }); if (!siteName) { instituteSites[instituteName] = $scope.sites; } } ); } function saveUser() { var user = angular.copy($scope.user); user.$saveOrUpdate().then( function(savedUser) { if ($scope.user.$$editProfile) { LocationChangeListener.back(); } else { $state.go('user-detail.overview', {userId: savedUser.id}); } } ); } function bulkUpdate() { var userIds = users.map(function(user) { return user.id; }); User.bulkUpdate({detail: $scope.user, ids: userIds}).then( function(savedUsers) { $state.go('user-list'); } ); } $scope.onInstituteSelect = function(instituteName) { $scope.user.primarySite = undefined; loadSites(instituteName); } $scope.searchSites = function(siteName) { if (!$scope.user.instituteName) { return; } loadSites($scope.user.instituteName, siteName); } $scope.onContactTypeSelect = function() { $scope.user.manageForms = false; $scope.user.domainName = undefined; $scope.user.loginName = undefined; } $scope.createUser = function() { if (!$scope.user.id || $scope.user.instituteName == prevInstitute) { saveUser(); return; } Util.showConfirm({ isWarning: true, title: 'user.confirm_institute_update_title', confirmMsg: 'user.confirm_institute_update_q', input: {count: 1, users: [$scope.user]}, ok: saveUser }); }; $scope.signup = function() { var user = angular.copy($scope.user); User.signup(user).then( function(resp) { if (resp.status == 'ok') { $scope.signedUp = true; } } ) }; $scope.bulkUpdate = function() { var instituteChange = users.some(function(u) { return u.instituteName != $scope.user.instituteName; }); if (!instituteChange) { bulkUpdate(); return; } Util.showConfirm({ isWarning: true, title: 'user.confirm_institute_update_title', confirmMsg: 'user.confirm_institute_update_q', input: {count: users.length, users: users}, ok: bulkUpdate }); } init(); });
JavaScript
0
@@ -492,16 +492,17 @@ s: %7B%7D%7D;%0A +%0A if @@ -529,19 +529,28 @@ && -! user. -admin +type != 'SUPER' ) %7B%0A @@ -2088,36 +2088,96 @@ -LocationChangeListener.back( +angular.extend(currentUser, savedUser);%0A $state.go('home', %7B%7D, %7Breload: true%7D );%0A
f1891c9e6409d719f7bc2ae8bba837ff6f6542d0
Improve notification animation
yeoman/app/scripts/directives/triggerListen.js
yeoman/app/scripts/directives/triggerListen.js
'use strict'; yeomanApp.directive('triggerListen' , ['$rootScope', 'UIEvents' , function($rootScope, UIEvents) { var highlightColor = "hsl(195,46%,70%)"; //blue highlightColor = "hsl(48,83%,76%)"; // yellow var highlightDuration = 6000; return { restrict: 'A', link: function postLink(scope, element, attrs) { $rootScope.$on(UIEvents.PusherData, function(event, data) { if (scope.trigger.Options.data === data.DA) { // This trigger is being actuated // element.stop(true, true).effect("highlight", { color: highlightColor}, highlightDuration); element.stop(true, false); element.animate({backgroundColor: '#e59191'}, 100).spectrum(["#edecb2", "#daeaba", "transparent"], [60000, 60000, 60000]); var lastActuated = new moment(data.timestamp); // lastActuated = lastActuated.format("YYYY-MM-DD h:mm:ssa"); element.find(".lastActuated").html(lastActuated.fromNow()); } }); } }; }]);
JavaScript
0.000002
@@ -702,15 +702,24 @@ r: ' -#e59191 +hsl(353,77%25,57%25) '%7D, @@ -733,16 +733,27 @@ ectrum(%5B +%22#e59191%22, %22#edecb2 @@ -783,16 +783,21 @@ ent%22%5D, %5B +100, 60000, 6 @@ -1015,15 +1015,35 @@ ed.f -romNow( +ormat(%22YYYY-MM-DD h:mm:ssa%22 ));%0A
69e433bac8e5ef78ed85e8b6d6d7b4d4a7e3a76c
Clarify translation string context.
assets/js/components/setup-wizard/wizard-steps.js
assets/js/components/setup-wizard/wizard-steps.js
/** * WizardSteps data map. * * Site Kit by Google, Copyright 2019 Google LLC * * 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 * * https://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. */ /** * WordPress dependencies */ import { __, _x } from '@wordpress/i18n'; const STEPS = { authentication: { title: __( 'Authenticate', 'google-site-kit' ), required: true, isApplicable: () => true, isCompleted: ( props ) => props.isSiteKitConnected && props.isAuthenticated && ! props.needReauthenticate, Component: WizardStepAuthentication, }, verification: { title: __( 'Verify URL', 'google-site-kit' ), required: true, isApplicable: () => true, isCompleted: ( props ) => props.isSiteKitConnected && props.isAuthenticated && props.isVerified, Component: WizardStepVerification, }, seachConsoleProperty: { title: __( 'Connect Search Console', 'google-site-kit' ), required: true, isApplicable: () => true, isCompleted: ( props ) => props.isSiteKitConnected && props.isAuthenticated && props.isVerified && props.hasSearchConsoleProperty, Component: WizardStepSearchConsoleProperty, }, completeSetup: { title: _x( 'Finish', 'action', 'google-site-kit' ), required: false, isApplicable: () => true, isCompleted: ( props ) => props.isSiteKitConnected && props.isAuthenticated && props.isVerified && props.hasSearchConsoleProperty, Component: WizardStepCompleteSetup, }, }; /** * Internal dependencies */ import WizardStepAuthentication from '../../components/setup-wizard/wizard-step-authentication'; import WizardStepVerification from '../../components/setup-wizard/wizard-step-verification'; import WizardStepSearchConsoleProperty from '../../components/setup-wizard/wizard-step-search-console-property'; import WizardStepCompleteSetup from '../../components/setup-wizard/wizard-step-complete-setup'; export default STEPS;
JavaScript
0.000128
@@ -1609,14 +1609,29 @@ ', ' -action +complete module setup ', '
ecb27913f5da77ad2c4259607ce9f7649fd346f9
Remove useless field.
lib/formidable-grid.js
lib/formidable-grid.js
var _ = require('underscore'); var debug = require('debug')('formidable-grid'); var formidable = require('formidable'); var onPart = function(part) { var done = function(err) { debug('-- done: err = ' + err); stream.removeAllListeners(); if (err) { this._error(err); } else { this.emit('file', part.name, file); this._flushing--; this._maybeEnd(); } }; var on_data = function(data) { debug('-- on_data: length = ' + data.length); this.pause(); stream.write(data); }; var on_end = function() { debug('-- store write end'); part.removeAllListeners(); stream.end(); }; var on_aborted = function() { debug('-- request aborted'); stream.removeAllListeners(); stream.end(); this.mongo.GridStore.unlink(this.db, file.id, function() { debug('-- file removed'); }); }; // this is set to the formidable.IncomingForm object if (! part.filename) { return this.handlePart(part); } if (! this.accept(part.mime)) { return this._error(_.extend( new Error('Unsupported Media Type'), {status: 415} )); } // used by formidable in order to determine if the end is reached this._flushing++; var file = { id: new this.mongo.ObjectID, lastModified: new Date, name: part.filename, mime: part.mime, }; var grid_store = new this.mongo.GridStore(this.db, file.id, file.name, 'w', { content_type: file.mime, filename: file.name, }); var stream = grid_store.stream(); this.emit('fileBegin', file); stream .on('drain', this.callback(this.resume)) .once('error', this.callback(done)) .once('end', this.callback(done)); part .on('data', this.callback(on_data)) .once('end', this.callback(on_end)); this .once('aborted', this.callback(on_aborted)); }; var formidableGrid = function(db, mongo, options) { if (! db) throw new Error('Missing db!'); if (! mongo) throw new Error('Missing mongodb driver!'); var accept_ = _.filter( (options ? options.accept : []) || [], function(item) { return _.isString(item) || _.isRegExp(item); } ); return Object.create( new formidable.IncomingForm, { mongo: { get: function() { return mongo; }, configurable: false }, db: { get: function() { return db; }, configurable: false }, accept: { value: function(type) { if (_.isString(type)) { if (accept_.length > 0) { return _.some(accept_, function(filter) { return type.match(filter); }); } return true; } }, configurable: false }, onPart: { value: onPart, configurable: false }, callback: { value: function(fn) { return fn.bind(this); }, configurable: false } } ); }; module.exports = formidableGrid;
JavaScript
0
@@ -1632,38 +1632,8 @@ mime -,%0A filename: file.name, %0A
854aea33d5783bcde53ef59355ca932a5aa6bbd5
Set an explicitly high quality for split jpg images.
lib/frame-converter.js
lib/frame-converter.js
var cuid = require('cuid') , fs = require('fs') , concat = require('concat-stream') , rimraf = require('rimraf') , child = require('child_process') var TMP_DIR = __dirname + '/../tmp/' var fileExtensions = { 'image/jpeg': '.jpg', 'video/webm': '.webm', 'video/mp4': '.mp4', } var videoCodecs = { 'webm': { type: 'ffmpeg', ext: '.webm', vcodec: '-vcodec libvpx' }, 'x264': { type: 'ffmpeg', ext: '.mp4', vcodec: '-vcodec libx264 -pix_fmt yuv420p' }, 'jpg': { // "filmstrip" jpg view type: 'other', ext: '.jpg', command: 'convert -append' }, } module.exports = function(frames, format, ffmpegRunner, cb) { if (!fileExtensions[format]) { return cb(new Error('Invalid input format')) } var id = cuid() , folder = TMP_DIR + id , imgExtension = fileExtensions[format] writeTempFiles() function writeTempFiles() { fs.mkdir(folder, err => { if (err) { return done(err) } var count = 0 for (var i = 0; i < frames.length; i++) { fs.createWriteStream(folder + '/' + i + imgExtension) .on('error', done) .end(frames[i], fileDone) } function fileDone() { count++ if (count == frames.length) { convert() } } }) } function convert() { var results = {} , outstanding = 0 , firstErr Object.keys(videoCodecs).forEach(codec => { let info = videoCodecs[codec] outstanding++ if (info.type == 'ffmpeg') { doFfmpeg(ffmpegRunner, folder, imgExtension, info.vcodec, info.ext, (err, data) => { if (err) { firstErr = firstErr || err } else { results[codec] = data } outstanding-- maybeFinish() }) } else { doOtherCommand(folder, imgExtension, info.command, info.ext, (err, data) => { if (err) { firstErr = firstErr || err } else { results[codec] = data } outstanding-- maybeFinish() }) } }) function maybeFinish() { if (outstanding) return if (firstErr) { done(firstErr) } else { done(null, results) } } } function done(err, video) { cb(err, video) deleteFiles() } function deleteFiles() { rimraf(folder, err => { if (err) { console.error('Error deleting folder: ' + folder + '\n' + err) } }) } } module.exports.forMeatspaceProxy = function(video, ffmpegRunner, cb) { // take a video, split it into its requisite frames, and then output to a jpeg let id = cuid() , folder = TMP_DIR + id , inputExtension = fileExtensions[video.type] writeTempFiles() function writeTempFiles() { fs.mkdir(folder, err => { if (err) { return done(err) } fs.createWriteStream(`${folder}/vid${inputExtension}`) .on('error', done) .end(video, split) }) } let splitExtension = '.jpg' function split() { let command = `-i "${folder}/vid${inputExtension}" ` + `-filter:v "setpts=0.4*PTS" "${folder}/frame%02d${splitExtension}"` ffmpegRunner(command, { timeout: 3000 }, (err, stdout, stderr) => { if (err) { return done(err) } let info = videoCodecs.jpg doOtherCommand(folder, splitExtension, info.command, info.ext, done) }) } function done(err, video) { cb(err, video) deleteFiles() } function deleteFiles() { rimraf(folder, err => { if (err) { console.error('Error deleting folder: ' + folder + '\n' + err) } }) } } function doFfmpeg(ffmpegRunner, folder, imgExtension, vcodecArgs, vidExtension, cb) { var command = `-i "${folder}/%d${imgExtension}" -filter:v "setpts=2.5*PTS" ${vcodecArgs} ` + `-an "${folder}/vid${vidExtension}"` ffmpegRunner(command, { timeout: 3000 }, (err, stdout, stderr) => { if (err) { return cb(err) } fs.createReadStream(`${folder}/vid${vidExtension}`) .pipe(concat(data => cb(null, data))) .on('error', err => cb(err)) }) } function doOtherCommand(folder, imgExtension, command, outputExtension, cb) { let toRun = `${command} "${folder}/*${imgExtension}" "${folder}/output${outputExtension}"` child.exec(toRun, (err, stdout, stderr) => { if (err) { return cb(err) } fs.createReadStream(`${folder}/output${outputExtension}`) .pipe(concat(data => cb(null, data))) .on('error', err => cb(err)) }) }
JavaScript
0
@@ -3139,16 +3139,28 @@ 0.4*PTS%22 + -qscale:v 1 %22$%7Bfold
eae6ea26ffc832ffb80acaafa4e8e7b2892947d9
Remove unnecessary comments
lib/frequency-entry.js
lib/frequency-entry.js
/** Represents a single frequency entry */ import React, {Component, PropTypes} from 'react' import TimetableEntry from './timetable-entry' import SelectTrip from './select-trip' import SelectPatterns from './select-patterns' import {Text} from './components/input' import Icon from './components/icon' import {Button} from './components/buttons' export default class FrequencyEntry extends Component { static propTypes = { feed: PropTypes.object.isRequired, index: PropTypes.number, replaceTimetable: PropTypes.func.isRequired, removeTimetable: PropTypes.func.isRequired, setActiveTrips: PropTypes.func.isRequired, timetable: PropTypes.object.isRequired, routes: PropTypes.array.isRequired, trip: PropTypes.string } changeTrip = (sourceTrip) => { this.props.replaceTimetable(Object.assign({}, this.props.timetable, { sourceTrip })) } selectPattern = ({ trips }) => { this.props.setActiveTrips(trips) this.props.replaceTimetable(Object.assign({}, this.props.timetable, { patternTrips: trips, sourceTrip: trips[0] })) } changeName = (e) => { this.props.replaceTimetable(Object.assign({}, this.props.timetable, { name: e.target.value })) } setActiveTrips = (e) => { this.props.setActiveTrips(this.props.timetable.patternTrips) } render () { const {feed, removeTimetable, replaceTimetable, routes, timetable} = this.props const routePatterns = feed && routes[0] && feed.routesById[routes[0]].patterns return ( <div className='panel panel-default inner-panel' onFocus={this.setActiveTrips}> <div className='panel-heading clearfix'> <strong>{timetable.name}</strong> <Button className='pull-right' onClick={removeTimetable} size='sm' style='danger' title='Delete frequency entry' > <Icon type='close' /> </Button> </div> <div className='panel-body'> <Text name='Name' onChange={this.changeName} value={timetable.name} /> {routePatterns && <SelectPatterns onChange={this.selectPattern} routePatterns={routePatterns} trips={timetable.patternTrips} /> } <SelectTrip feed={feed} onChange={this.changeTrip} patternTrips={timetable.patternTrips} routes={routes} trip={timetable.sourceTrip} /> <TimetableEntry replaceTimetable={replaceTimetable} timetable={timetable} /> </div> </div> ) } } export function create () { return { sourceTrip: null, headwaySecs: 600, // TODO this causes the backend to break, and it's unclear what it's used for //patterns: [], patternTrips: [], startTime: 7 * 3600, endTime: 22 * 3600, // active every day monday: true, tuesday: true, wednesday: true, thursday: true, friday: true, saturday: true, sunday: true } }
JavaScript
0.000043
@@ -2797,110 +2797,8 @@ 00,%0A - // TODO this causes the backend to break, and it's unclear what it's used for%0A //patterns: %5B%5D,%0A
3071fb4aa4a65e2f7216bfaef8f1a2d376a7dd83
Change default configuration in the tests and make one failing test pass
d3/test/helpers/defaultConf.js
d3/test/helpers/defaultConf.js
var defaultConf = { linear: { drawAllLinks: false, startLineColor: "#49006a", endLineColor: "#1d91c0", }, circular: { tickSize: 5 }, graphicalParameters: { width: 1000, height: 1000, karyoHeight: 30, karyoDistance: 10, linkKaryoDistance: 10, tickDistance: 100, treeWidth: 300, genomeLabelWidth: 150 }, minLinkIdentity: 40, maxLinkIdentity: 100, midLinkIdentity: 60, minLinkIdentityColor: "#D21414", maxLinkIdentityColor: "#1DAD0A", midLinkIdentityColor: "#FFEE05", minLinkLength: 100, maxLinkLength: 5000, layout: "linear", tree: { drawTree: false, orientation: "left" }, features: { showAllFeatures: false, supportedFeatures: { gen: { form: "rect", color: "#E2EDFF", height: 30, visible: false, pattern: "lines" }, invertedRepeat: { form: "arrow", color: "#e7d3e2", height: 30, visible: false, }, nStretch: { form: "rect", color: "#000000", height: 30, visible: false, pattern: "woven" }, repeat: { form: "arrow", color: "#56cd0f", height: 30, visible: false, pattern: "crosslines" } }, fallbackStyle: { form: "rect", color: "#787878", height: 30, visible: false } }, labels: { showAllLabels: false, chromosome: { showChromosomeLabels: true }, genome: { showGenomeLabels: true }, features: { showFeatureLabels: false } } };
JavaScript
0
@@ -802,37 +802,15 @@ se,%0A -%09%09%09%09%09pattern: %22lines%22%0A %09%09%09%09%7D,%0A + %09%09%09%09 @@ -900,32 +900,54 @@ visible: false,%0A +%09%09%09%09%09pattern: %22woven%22%0A %09%09%09%09%7D,%0A%09%09%09%09nStre @@ -1040,37 +1040,37 @@ %0A%09%09%09%09%09pattern: %22 -woven +lines %22%0A%09%09%09%09%7D,%0A%09%09%09%09rep @@ -1176,18 +1176,13 @@ n: %22 -crosslines +woven %22%0A%09%09
bf326d33d19ab88fd8084e33657f813a7dc71050
remove log statement
xbrowse_server/staticfiles/js/base/igv_view.js
xbrowse_server/staticfiles/js/base/igv_view.js
window.IgvView = Backbone.View.extend({ className: 'igv-container', initialize: function (options) { this.individuals = options.individuals; var tracks = []; for (var i = 0; i < this.individuals.length; i += 1) { var indiv = this.individuals[i]; console.log(indiv) if(indiv.cnv_bed_file) { var bedTrack = { url: '/static/igv/' + indiv.cnv_bed_file, indexed: false, name: '<i style="font-family: FontAwesome; font-style: normal; font-weight: normal;" class="' + utils.getPedigreeIcon(indiv) + '"></i> ' + indiv.indiv_id + ' CNVs', } console.log('Adding bed track: ', bedTrack) tracks.push(bedTrack); } if (indiv.read_data_is_available) { var alignmentTrack = null if (indiv.read_data_format == 'cram') { options.genome = "hg38" //this is a temporary hack - TODO add explicit support for grch38 alignmentTrack = { url: "/project/" + indiv.project_id + "/igv-track/" + indiv.indiv_id, sourceType: 'pysam', alignmentFile: '/placeholder.cram', referenceFile: '/placeholder.fa', type: "bam", alignmentShading: 'strand', name: '<i style="font-family: FontAwesome; font-style: normal; font-weight: normal;" class="' + utils.getPedigreeIcon(indiv) + '"></i> ' + indiv.indiv_id, //name: 'test' } } else { alignmentTrack = { url: "/project/" + indiv.project_id + "/igv-track/" + indiv.indiv_id, type: "bam", indexed: true, alignmentShading: 'strand', name: '<i style="font-family: FontAwesome; font-style: normal; font-weight: normal;" class="' + utils.getPedigreeIcon(indiv) + '"></i> ' + indiv.indiv_id, height: 300, minHeight: 300, autoHeight: false, //samplingDepth: 100, } } tracks.push(alignmentTrack); } } //initialize IGV.js browser if (options.genome == "hg38" || options.genome == "GRCh38") { if (!options.gencodeUrl) { options.gencodeVersion = "gencode GRCh38v27"; options.gencodeUrl = 'https://storage.googleapis.com/seqr-reference-data/GRCh38/gencode/gencode.v27.annotation.sorted.gtf.gz'; } } else { if (!options.genome) { options.genome = "hg19" } if (!options.gencodeUrl) { options.gencodeVersion = "gencode GRCh37v27"; options.gencodeUrl = 'https://storage.googleapis.com/seqr-reference-data/GRCh37/gencode/gencode.v27lift37.annotation.sorted.gtf.gz'; } } tracks.push({ url: options.gencodeUrl, name: options.gencodeVersion, //displayMode: "EXPANDED", displayMode: "SQUISHED", }); var igvOptions = { showCommandBar: true, locus: options.locus, //reference: { // id: options.genome, //}, genome: options.genome, showKaryo: false, showIdeogram: true, showNavigation: true, showRuler: true, tracks: tracks, showCenterGuide: true, showCursorTrackingGuide: true, }; console.log('IGV options:', igvOptions); igv.createBrowser(this.el, igvOptions); //igv.CoverageMap.threshold = 0.1; //igv.browser.pixelPerBasepairThreshold = function () { // return 28.0; //allow zooming in further - default is currently 14.0 //}; }, jump_to_locus: function (locus) { //locus must be a string like : 'chr1:12345-54321' try { if(igv.browser.genome) { igv.browser.search(locus); } } catch(e) { console.log(e) } } });
JavaScript
0.000002
@@ -290,32 +290,8 @@ i%5D;%0A -%09 console.log(indiv)%0A
f3ecdc5af4e1eb3545ae717fa1ab1a67720839b3
fix influxdb annotation query
public/app/plugins/datasource/influxdb/datasource.js
public/app/plugins/datasource/influxdb/datasource.js
define([ 'angular', 'lodash', 'app/core/utils/datemath', './influx_series', './query_builder', './directives', './query_ctrl', ], function (angular, _, dateMath, InfluxSeries, InfluxQueryBuilder) { 'use strict'; var module = angular.module('grafana.services'); module.factory('InfluxDatasource', function($q, backendSrv, templateSrv) { function InfluxDatasource(datasource) { this.type = 'influxdb'; this.urls = _.map(datasource.url.split(','), function(url) { return url.trim(); }); this.username = datasource.username; this.password = datasource.password; this.name = datasource.name; this.database = datasource.database; this.basicAuth = datasource.basicAuth; this.supportAnnotations = true; this.supportMetrics = true; } InfluxDatasource.prototype.query = function(options) { var timeFilter = getTimeFilter(options); var queryTargets = []; var i, y; var allQueries = _.map(options.targets, function(target) { if (target.hide) { return []; } queryTargets.push(target); // build query var queryBuilder = new InfluxQueryBuilder(target); var query = queryBuilder.build(); query = query.replace(/\$interval/g, (target.interval || options.interval)); return query; }).join("\n"); // replace grafana variables allQueries = allQueries.replace(/\$timeFilter/g, timeFilter); // replace templated variables allQueries = templateSrv.replace(allQueries, options.scopedVars); return this._seriesQuery(allQueries).then(function(data) { if (!data || !data.results) { return []; } var seriesList = []; for (i = 0; i < data.results.length; i++) { var result = data.results[i]; if (!result || !result.series) { continue; } var alias = (queryTargets[i] || {}).alias; if (alias) { alias = templateSrv.replace(alias, options.scopedVars); } var targetSeries = new InfluxSeries({ series: data.results[i].series, alias: alias }).getTimeSeries(); for (y = 0; y < targetSeries.length; y++) { seriesList.push(targetSeries[y]); } } return { data: seriesList }; }); }; InfluxDatasource.prototype.annotationQuery = function(annotation, rangeUnparsed) { var timeFilter = getTimeFilter({ range: rangeUnparsed }); var query = annotation.query.replace('$timeFilter', timeFilter); query = templateSrv.replace(query); return this._seriesQuery(query).then(function(data) { if (!data || !data.results || !data.results[0]) { throw { message: 'No results in response from InfluxDB' }; } return new InfluxSeries({ series: data.results[0].series, annotation: annotation }).getAnnotations(); }); }; InfluxDatasource.prototype.metricFindQuery = function (query) { var interpolated; try { interpolated = templateSrv.replace(query); } catch (err) { return $q.reject(err); } return this._seriesQuery(interpolated).then(function (results) { if (!results || results.results.length === 0) { return []; } var influxResults = results.results[0]; if (!influxResults.series) { return []; } var series = influxResults.series[0]; if (query.indexOf('SHOW MEASUREMENTS') === 0) { return _.map(series.values, function(value) { return { text: value[0], expandable: true }; }); } var flattenedValues = _.flatten(series.values); return _.map(flattenedValues, function(value) { return { text: value, expandable: true }; }); }); }; InfluxDatasource.prototype._seriesQuery = function(query) { return this._influxRequest('GET', '/query', {q: query, epoch: 'ms'}); }; InfluxDatasource.prototype.testDatasource = function() { return this.metricFindQuery('SHOW MEASUREMENTS LIMIT 1').then(function () { return { status: "success", message: "Data source is working", title: "Success" }; }); }; InfluxDatasource.prototype._influxRequest = function(method, url, data) { var self = this; var currentUrl = self.urls.shift(); self.urls.push(currentUrl); var params = { u: self.username, p: self.password, }; if (self.database) { params.db = self.database; } if (method === 'GET') { _.extend(params, data); data = null; } var options = { method: method, url: currentUrl + url, params: params, data: data, precision: "ms", inspect: { type: 'influxdb' }, }; options.headers = options.headers || {}; if (self.basicAuth) { options.headers.Authorization = self.basicAuth; } return backendSrv.datasourceRequest(options).then(function(result) { return result.data; }, function(err) { if (err.status !== 0 || err.status >= 300) { if (err.data && err.data.error) { throw { message: 'InfluxDB Error Response: ' + err.data.error, data: err.data, config: err.config }; } else { throw { messsage: 'InfluxDB Error: ' + err.message, data: err.data, config: err.config }; } } }); }; function getTimeFilter(options) { var from = getInfluxTime(options.rangeRaw.from, false); var until = getInfluxTime(options.rangeRaw.to, true); var fromIsAbsolute = from[from.length-1] === 's'; if (until === 'now()' && !fromIsAbsolute) { return 'time > ' + from; } return 'time > ' + from + ' and time < ' + until; } function getInfluxTime(date, roundUp) { if (_.isString(date)) { if (date === 'now') { return 'now()'; } if (date.indexOf('now-') >= 0 && date.indexOf('/') === -1) { return date.replace('now', 'now()').replace('-', ' - '); } date = dateMath.parse(date, roundUp); } return (date.valueOf() / 1000).toFixed(0) + 's'; } return InfluxDatasource; }); });
JavaScript
0.001098
@@ -2472,16 +2472,19 @@ (%7B range +Raw : rangeU
c1d3edb55ce5d1021cf57672c9c53ad677309101
change from rollup run script to simpler config generator
rollup/rollup-build-es6-flow.js
rollup/rollup-build-es6-flow.js
/** * Mostly taken from `generator-javascript` * * @package: Everledger JS Toolchain * @author: pospi <sam@everledger.io> * @since: 2016-10-13 * @flow */ const { curry } = require('ramda'); const fs = require('fs'); const path = require('path'); const del = require('del'); const rollup = require('rollup'); const babel = require('rollup-plugin-babel'); function runRollup(pkg, destDir, entrypoint) { let promise = Promise.resolve(); const extension = path.extname(entrypoint); const filename = path.basename(entrypoint, extension); // Compile source code into a distributable format with Babel for (const format of ['es6', 'cjs']) { promise = promise.then(() => rollup.rollup({ entry: entrypoint, external: Object.keys(pkg.dependencies), plugins: [babel(Object.assign(pkg.babel, { babelrc: false, exclude: 'node_modules/**', runtimeHelpers: true, presets: pkg.babel.presets.map(x => (x === 'es2015' ? 'es2015-rollup' : x)), }))], }).then(bundle => bundle.write({ dest: path.resolve(destDir, format === 'cjs' ? `${filename}.js` : `${filename}.${format}.js`), format, sourceMap: true, moduleName: format === 'umd' ? pkg.name : undefined, }))); } return promise.catch(err => console.error(err, err.stack)); // eslint-disable-line no-console } function cleanOutputDirectory(destDir) { return del([path.resolve(destDir, '*')]); } module.exports = { compileES6Module: curry(runRollup), cleanOutputDirectory, };
JavaScript
0
@@ -198,34 +198,8 @@ ');%0A -const fs = require('fs');%0A cons @@ -256,42 +256,8 @@ ');%0A -const rollup = require('rollup');%0A cons @@ -308,25 +308,32 @@ unction -run +make Rollup +Config (pkg, de @@ -357,44 +357,8 @@ ) %7B%0A - let promise = Promise.resolve();%0A%0A co @@ -463,162 +463,17 @@ %0A%0A -// Compile source code into a distributable format with Babel%0A for (const format of %5B'es6', 'cjs'%5D) %7B%0A promise = promise.then(() =%3E rollup.rollup(%7B%0A +return %7B%0A @@ -491,18 +491,16 @@ ypoint,%0A - exte @@ -536,18 +536,16 @@ ncies),%0A - plug @@ -589,18 +589,16 @@ %7B%0A - babelrc: @@ -605,18 +605,16 @@ false,%0A - ex @@ -645,18 +645,16 @@ ,%0A - - runtimeH @@ -663,26 +663,24 @@ pers: true,%0A - preset @@ -754,18 +754,16 @@ )),%0A - - %7D))%5D,%0A @@ -768,135 +768,101 @@ -%7D).then(bundle =%3E bundle.write(%7B%0A dest: path.resolve(destDir, format === 'cjs' ? %60$%7Bfilename%7D.js%60 : %60$%7Bfilename%7D.$%7Bformat%7D +targets: %5B%0A %7B%0A format: 'es',%0A dest: path.resolve(destDir, %60$%7Bfilename%7D.es6 .js%60 @@ -874,22 +874,17 @@ -format +%7D ,%0A sour @@ -883,194 +883,108 @@ -sourceMap: true,%0A moduleName: format === 'umd' ? pkg.name : undefined,%0A %7D)));%0A %7D%0A%0A return promise.catch(err =%3E console.error(err, err.stack)); // eslint-disable-line no-console +%7B%0A format: 'cjs',%0A dest: path.resolve(destDir, %60$%7Bfilename%7D.js%60),%0A %7D,%0A %5D,%0A %7D; %0A%7D%0A%0A @@ -1096,32 +1096,32 @@ %7B%0A -compileES6Module +makeRollupConfig : curry( runR @@ -1120,17 +1120,24 @@ rry( -run +make Rollup +Config ),%0A
2f99fd78755c8987f6217bdb770d3ba6935be6a2
add download ability
src/bots/actions.js
src/bots/actions.js
var template = require('./template.js'); var taskGet = require('./taskGet.js'); var request = require('./request.js'); var timeoutDuration = 30000; var assertion = require('./assertion.js').assertion(casper); var actions = { assert: function (params) { var output; try { if (params.attribute) { assertion.attribute(params); } else if (params.variable) { assertion.variable(params); } else { log('no assertion found', 'ERROR'); } } catch (err) { output = 'FAILED: expected \'' + err.expected + '\' but got \'' + err.actual + '\''; return log(output, 'TEST_FAILED'); } output = 'PASS: got \'' + params.expected + '\''; return log(output, 'TEST_SUCCESS'); }, capture: function (params) { log('capture', params.name, 'INFO_BAR'); return casper.capture('./captures/' + pid + '/' + params.name); }, request: function (params) { // Control what's needed to pursue if (!params || !params.url) { return log('missing `url` params for the request action', params, 'ERROR'); } // Get the data from the request. var data = casper.evaluate(request.xhr, params); // And store it if needed later. if (params.store) { if (!params.store.key) { log('missing params for store', 'ERROR'); return; } request.handleStore(template, taskGet, params.store, data); } // Return it. return data; }, get: function (params) { var returnValue; if (params.attribute) { returnValue = taskGet.getAttribute(casper, params); if (returnValue !== undefined) { log('got', params.attribute + ' of ' + params.selector, returnValue, 'SUCCESS'); return returnValue; } return log('no attribute "' + params.attribute + '" found for selector "' + params.selector + '" and ' + (params.modifier || 'whithout') + ' modifier', 'ERROR'); } else if (params.variable) { returnValue = taskGet.getVariable(casper, params.variable); if (returnValue !== undefined) { log('got global variable: ' + params.variable, 'SUCCESS'); return returnValue; } return log('no value found for: ' + params.variable, 'ERROR'); } return log('no action found for ', params, 'ERROR'); }, wait: function (params) { var vals = ['wait for']; Object.keys(params).forEach(function (key) { vals.push(key + ': ' + params[key]); }); vals.push('INFO_BAR'); log.apply(this, vals); if (params.url) { return casper.waitForUrl(params.url, function () { log('got', params.url, 'SUCCESS'); }, function () { log('timeout', 'WARNING'); }, timeoutDuration); } else if (params.selector) { return casper.waitForSelector(params.selector, function () { log('got ', params.selector, 'SUCCESS'); }, function () { log('timeout', 'WARNING'); }, timeoutDuration); } else if (params.visible) { return casper.waitUntilVisible(params.visible, function () { log('got ', params.visible, 'SUCCESS'); }, function () { log('timeout', 'WARNING'); }, timeoutDuration); } else if (params.hidden) { return casper.waitWhileVisible(params.hidden, function () { log('got ', params.hidden, 'SUCCESS'); }, function () { log('timeout', 'WARNING'); }, timeoutDuration); } else if (params.time) { return casper.wait(params.time, function () { log('waited for ', params.time, 'SUCCESS'); }); } return log('no action found for ', params, 'ERROR'); }, dom: function (params) { log('dom action', params.do, params.selector, 'INFO_BAR'); var domActions = { fill: function (opts) { return casper.sendKeys(opts.selector, opts.text); }, click: function (opts) { return casper.click(opts.selector); } }; if (params.selector) { log('waiting for', params.selector, 'INFO_BAR'); return casper.waitForSelector(params.selector, function () { log('got', params.selector, 'SUCCESS'); if (domActions[params.do]) { return domActions[params.do](params); } return log('no dom action found for ' + params.do, 'ERROR'); }); } } }; var config = function (casper, pid) { return { execute: function (task) { if (task.type && actions[task.type]) { var response; task = template.parse(task); log('starting task', task, 'INFO_BAR'); response = actions[task.type](task.params); if (task.type === 'get') { template.store(task.params.key, response); } return response; } else { log('no task found for: ', task, 'ERROR'); } }, navigate: function (url, next) { log('navigate to', url, 'INFO_BAR'); var loadSuccess = function (status) { log('load success', url, 'SUCCESS'); casper.removeListener('load.failed', loadFailed); casper.removeListener('load.finished', loadSuccess); if (status === 'fail') { next('fail'); } else { next(); } }; var loadFailed = function (err) { log('load failed', url, 'ERROR'); casper.removeListener('load.failed', loadFailed); casper.removeListener('load.finished', loadSuccess); next(err); }; casper.on('load.failed', loadFailed); casper.on('load.finished', loadSuccess); return casper.start(url); } }; }; module.exports = { config: config };
JavaScript
0
@@ -1692,16 +1692,329 @@ n data;%0A + %7D,%0A download: function (params) %7B%0A%0A casper.click(params.selector);%0A%0A casper.waitForResource(params.filename, function () %7B%0A return log(params.filename + ' has been received', 'SUCCESS');%0A %7D, function () %7B%0A log('timeout', 'WARNING');%0A %7D, timeoutDuration);%0A%0A %7D,%0A
3e1a05ab1932d0fe5077b4513a5044f9263dbe64
Allow overlap between response groups
plugins/jspsych-multi-stim-multi-response.js
plugins/jspsych-multi-stim-multi-response.js
/** * jspsych-muli-stim-multi-response * Josh de Leeuw * * plugin for displaying a set of stimuli and collecting a set of responses * via the keyboard * * documentation: docs.jspsych.org * **/ (function($) { jsPsych["multi-stim-multi-response"] = (function() { var plugin = {}; plugin.create = function(params) { var trials = new Array(params.stimuli.length); for (var i = 0; i < trials.length; i++) { trials[i] = {}; trials[i].stimuli = params.stimuli[i]; trials[i].choices = params.choices; // option to show image for fixed time interval, ignoring key responses // true = image will keep displaying after response // false = trial will immediately advance when response is recorded trials[i].response_ends_trial = (typeof params.response_ends_trial === 'undefined') ? true : params.response_ends_trial; // timing parameters var default_timing_array = []; for (var j = 0; j < params.stimuli[i].length; j++) { default_timing_array.push(1000); } trials[i].timing_stim = params.timing_stim || default_timing_array; trials[i].timing_response = params.timing_response || -1; // if -1, then wait for response forever // optional parameters trials[i].is_html = (typeof params.is_html === 'undefined') ? false : params.is_html; trials[i].prompt = (typeof params.prompt === 'undefined') ? "" : params.prompt; } return trials; }; plugin.trial = function(display_element, trial) { // if any trial variables are functions // this evaluates the function and replaces // it with the output of the function trial = jsPsych.pluginAPI.evaluateFunctionParameters(trial); // this array holds handlers from setTimeout calls // that need to be cleared if the trial ends early var setTimeoutHandlers = []; // array to store if we have gotten a valid response for // all the different response types var validResponses = []; for (var i = 0; i < trial.choices.length; i++) { validResponses[i] = false; } // array for response times for each of the different response types var responseTimes = []; for (var i = 0; i < trial.choices.length; i++) { responseTimes[i] = -1; } // array for response keys for each of the different response types var responseKeys = []; for (var i = 0; i < trial.choices.length; i++) { responseKeys[i] = -1; } // function to check if all of the valid responses are received function checkAllResponsesAreValid() { for (var i = 0; i < validResponses.length; i++) { if (validResponses[i] == false) { return false; } } return true; } // function to end trial when it is time var end_trial = function() { // kill any remaining setTimeout handlers for (var i = 0; i < setTimeoutHandlers.length; i++) { clearTimeout(setTimeoutHandlers[i]); } // kill keyboard listeners jsPsych.pluginAPI.cancelKeyboardResponse(keyboardListener); // gather the data to store for the trial var trial_data = { "rt": JSON.stringify(responseTimes), "stimulus": JSON.stringify(trial.stimuli), "key_press": JSON.stringify(responseKeys) }; jsPsych.data.write(trial_data); // clear the display display_element.html(''); // move on to the next trial jsPsych.finishTrial(); }; // function to handle responses by the subject var after_response = function(info) { var whichResponse; for (var i = 0; i < trial.choices.length; i++) { for (var j = 0; j < trial.choices[i].length; j++) { keycode = (typeof trial.choices[i][j] == 'string') ? jsPsych.pluginAPI.convertKeyCharacterToKeyCode(trial.choices[i][j]) : trial.choices[i][j]; if (info.key == keycode) { whichResponse = i; break; } } if (typeof whichResponse !== 'undefined') { break; } } if (validResponses[whichResponse] != true) { validResponses[whichResponse] = true; responseTimes[whichResponse] = info.rt; responseKeys[whichResponse] = info.key; } if (trial.response_ends_trial) { if (checkAllResponsesAreValid()) { end_trial(); } } }; // flattened version of the choices array var allchoices = []; for (var i = 0; i < trial.choices.length; i++) { allchoices = allchoices.concat(trial.choices[i]); } var whichStimulus = 0; function showNextStimulus() { // display stimulus if (!trial.is_html) { display_element.append($('<img>', { src: trial.stimuli[whichStimulus], id: 'jspsych-multi-stim-multi-response-stimulus' })); } else { display_element.append($('<div>', { html: trial.stimuli[whichStimulus], id: 'jspsych-multi-stim-multi-response-stimulus' })); } //show prompt if there is one if (trial.prompt !== "") { display_element.append(trial.prompt); } if (typeof trial.timing_stim[whichStimulus] !== 'undefined' && trial.timing_stim[whichStimulus] > 0) { var t1 = setTimeout(function() { // clear the display, or hide the display if (typeof trial.stimuli[whichStimulus + 1] !== 'undefined') { display_element.html(''); // show the next stimulus whichStimulus++; showNextStimulus(); } else { $('#jspsych-multi-stim-multi-response-stimulus').css('visibility', 'hidden'); } }, trial.timing_stim[whichStimulus]); setTimeoutHandlers.push(t1); } } // show first stimulus showNextStimulus(); // start the response listener var keyboardListener = jsPsych.pluginAPI.getKeyboardResponse({ callback_function: after_response, valid_responses: allchoices, rt_method: 'date', persist: true, allow_held_key: false }); // end trial if time limit is set if (trial.timing_response > 0) { var t2 = setTimeout(function() { end_trial(); }, trial.timing_response); setTimeoutHandlers.push(t2); } }; return plugin; })(); })(jQuery);
JavaScript
0.000008
@@ -3820,16 +3820,146 @@ ; i++) %7B +%0A %09%0A // allow overlap between response groups%0A if (validResponses%5Bi%5D) %7B%0A continue;%0A %7D %0A%0A
0a5aa52dd3f41ed5c2a1caa03655e3044b3207b3
Fix linux only path strings.
server/utils/utils.js
server/utils/utils.js
var path = require('path') , fs = require('fs') ; /** * Reads all the JavaScript files within a directory, assuming they are all * proper node.js modules, and loads them. * @return {Array} Modules loaded. */ function initializeModulesWithin(dir, exclusions) { var output = {} , fullDir = path.join(__dirname, '..', '..', dir) , requirePath = '../' + fullDir.split('server/').pop() + '/' ; fs.readdirSync(fullDir).forEach(function(fileName) { var moduleName = fileName.split('.').shift() , excluded = false; if (exclusions != undefined && exclusions.indexOf(moduleName) > -1) { excluded = true; } if(! excluded && fileName.charAt(0) != "." && fileName.substr(fileName.length - 3) == ".js") { output[moduleName] = require(requirePath + moduleName); } }); return output; } module.exports = { initializeModulesWithin: initializeModulesWithin };
JavaScript
0.000001
@@ -366,15 +366,23 @@ h = -'../' + +path.join('..', ful @@ -403,17 +403,16 @@ rver -/ ').pop() + ' @@ -411,14 +411,9 @@ op() - + '/' +) %0A @@ -854,16 +854,26 @@ require( +path.join( requireP @@ -879,10 +879,10 @@ Path +, -+ mod @@ -889,16 +889,17 @@ uleName) +) ;%0A
d31e2a4261112babcc14e04aea69463f22b8b1f1
Change order of perf test URL hash to have the implementation first.
perf/create-tests.js
perf/create-tests.js
function createTests(Renderer, tests, impls) { var patch = IncrementalDOM.patch; var eo = IncrementalDOM.elementOpen; var ec = IncrementalDOM.elementClose; var tx = IncrementalDOM.text; var currentTest; var currentImpl; var currentRenderer; var results; var running; var container = document.createElement('div'); var testContainer = document.createElement('div'); container.id = 'container'; document.body.appendChild(container); document.body.appendChild(testContainer); document.head.insertAdjacentHTML('beforeEnd', ` <style> #container [aria-selected="true"] { color: white; background-color: blue; } #container button { margin: 4px 4px; } </style> `); function update() { patch(container, render); } function setTestAndImpl(test, impl) { currentTest = test; currentImpl = impl; currentRenderer = new Renderer(testContainer, impl.obj); running = true; update(); run(); window.location.hash = tests.indexOf(test) + ',' + impls.indexOf(impl); } function setTest(test) { setTestAndImpl(test, currentImpl); } function setImpl(impl) { setTestAndImpl(currentTest, impl); } function render() { eo('div'); impls.forEach(function(impl) { eo('button', null, null, 'disabled', running || undefined, 'aria-selected', currentImpl === impl, 'onclick', function() { setImpl(impl); }); tx(impl.name); ec('button'); }); ec('div'); eo('div'); tests.forEach(function(test) { eo('button', null, null, 'disabled', running || undefined, 'aria-selected', currentTest === test, 'onclick', function() { setTest(test); }); tx(test.name); ec('button'); }); ec('div'); eo('div'); if (running) { tx('running'); } else { tx(results); } ec('div'); } function delay(time) { return new Promise(function(resolve) { setTimeout(resolve, time); }); } function run() { delay(100) .then(function() { return currentTest.fn.run(currentRenderer) }) .then(function(samples) { return Stats.avg(Stats.filterOutliers(samples)) }) .then(function(avg) { results = `time per iteration: ${avg.toFixed(3)}ms`; running = false; update(); }); } var parts = window.location.hash.split(','); var test = Number(parts[0]) || 0; var impl = Number(parts[1]) || 0; setTestAndImpl(tests[test], impls[impl]); }
JavaScript
0
@@ -1024,20 +1024,20 @@ .hash = -test +impl s.indexO @@ -1038,20 +1038,20 @@ indexOf( -test +impl ) + ',' @@ -1052,20 +1052,20 @@ + ',' + -impl +test s.indexO @@ -1066,20 +1066,20 @@ indexOf( -impl +test );%0A %7D%0A%0A @@ -2454,16 +2454,29 @@ on.hash. +substring(1). split(', @@ -2485,20 +2485,20 @@ ;%0A var -test +impl = Numbe @@ -2513,36 +2513,36 @@ 0%5D) %7C%7C 0;%0A var -impl +test = Number(parts%5B
de03c1f77c1bf8bfc75807a259e7bd78d08167f2
use Ember.keys instead of Object.keys for older browsers support
addon/service.js
addon/service.js
import Ember from 'ember'; import { request } from 'ic-ajax'; import { get as readFromConfig } from './config'; export default Ember.Object.extend({ onAjaxComplete: function() { var _this = this; Ember.$(document).on("ajaxComplete", function(event, xhr, settings) { var csrf_param = xhr.getResponseHeader('X-CSRF-Param'), csrf_token = xhr.getResponseHeader('X-CSRF-Token'); if (csrf_param && csrf_token) { _this.setData({csrf_param: csrf_token}); } }); }.on('init'), setPrefilter: function() { var token = this.get('data').token; var preFilter = function(options, originalOptions, jqXHR) { return jqXHR.setRequestHeader('X-CSRF-Token', token ); }; $.ajaxPrefilter(preFilter); }, setData: function(data) { var param = Object.keys(data)[0]; this.set('data', { param: param, token: data[param] }); this.setPrefilter(); return this.get('data'); }, fetchToken: function() { var promise; var _this = this; if (this.get('data')) { promise = Ember.RSVP.resolve(this.get('data')); } else { var token = Ember.$('meta[name="csrf-token"]').attr('content'); if (!Ember.isEmpty(token)) { promise = Ember.RSVP.resolve({'authenticity_token': token }); } else { promise = request(readFromConfig('url')); } promise = promise.then(function(data) { return _this.setData(data); }); } return promise; } });
JavaScript
0
@@ -792,22 +792,21 @@ param = -Object +Ember .keys(da
ee206ed6bdabe5eb1bf1ad3741f41382d6e6dce5
fix for map not moving the second time the extend button is pressed (#39)
src/component/searchTab/BackgroundMap.js
src/component/searchTab/BackgroundMap.js
import React from 'react' import MapView from 'react-native-maps' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { View, StatusBar, ActivityIndicator } from 'react-native' import _ from 'lodash' import supercluster from 'supercluster' import { MultilineText } from '../DefaultText' import { updateMapViewport, selectBusiness } from '../../store/reducer/business' import { shouldBeDisplayed, isIncorrectLocation } from '../../util/business' import merge from '../../util/merge' import style from './BackgroundMapStyle' import MapMarker from './MapMarker' class BackgroundMap extends React.Component { onRegionChangeComplete = () => {} constructor(props) { super() this.state = ({ loading: true, markerArray: [] }) this.forceRegion = merge(props.forceRegion) this.currentRegion = merge(props.forceRegion) this.supercluster = supercluster({ radius: 60 }) this.mapRef = null } componentDidMount() { // To prevent the user seeing the centre of the earth when opening the app // and to prevent phony region changes setTimeout(() => { this.onRegionChangeComplete = (region) => { this.currentRegion = merge(region) this.props.updateMapViewport(region) this.updateMarkers() } if (this.props.businessList) { this.populateSupercluster() } this.setState({ loading: false }) }, 1500) } componentWillUpdate(nextProps) { if (!_.isEqual(nextProps.forceRegion, this.props.forceRegion)) { this.forceRegion = merge(nextProps.forceRegion) this.currentRegion = merge(nextProps.forceRegion) this.updateMarkers() } else { this.forceRegion = undefined } } componentDidUpdate(lastProps) { if (lastProps.businessList !== this.props.businessList) { this.populateSupercluster() } else if (lastProps.forceRegion !== this.props.forceRegion || lastProps.selectedBusinessId !== this.props.selectedBusinessId) { this.updateMarkers() } } populateSupercluster() { this.supercluster.load(_.filter(this.props.businessList, b => b.address.location) .map((b) => ({ geometry: { coordinates: [ b.address.location.longitude, b.address.location.latitude ] }, properties: {}, id: b.id }))) this.updateMarkers() } getZoomLevel(region = this.currentRegion) { // http://stackoverflow.com/a/6055653 const angle = region.longitudeDelta // 0.95 for finetuning zoomlevel grouping return Math.max(0, Math.min(Math.round(Math.log(360 / angle) / Math.LN2), 17)) } updateMarkers(props = this.props) { const clusteredMarkers = this.supercluster.getClusters([ this.currentRegion.longitude - this.currentRegion.longitudeDelta * 0.5, this.currentRegion.latitude - this.currentRegion.latitudeDelta * 0.5, this.currentRegion.longitude + this.currentRegion.longitudeDelta * 0.5, this.currentRegion.latitude + this.currentRegion.latitudeDelta * 0.5, ], this.getZoomLevel()) this.setState({ markerArray: clusteredMarkers.map(this.renderClusteredMarker(props)) }) } isSelected(business) { return business.id === this.props.selectedBusinessId } zoomToCluster = (coordinate) => { const region = { longitude: coordinate.longitude, latitude: coordinate.latitude, longitudeDelta: this.currentRegion.longitudeDelta * 0.5, latitudeDelta: this.currentRegion.latitudeDelta * 0.5 } this.mapRef.animateToRegion(region, 300) } renderClusteredMarker = ({ selectBusiness, selectedBusinessId }) => ({ geometry, properties, id }) => { const coordinate = { longitude: geometry.coordinates[0], latitude: geometry.coordinates[1] } let onPress = null let selected = null if ( id && (properties.point_count === 1 || !properties.point_count) ) { onPress = () => selectBusiness(id) selected = id === selectedBusinessId } else if (properties.point_count > 1 ) { if(selectedBusinessId) { var points = this.supercluster.getLeaves(properties.cluster_id, this.getZoomLevel(), Infinity) var pt = points.find(point => point.id === selectedBusinessId) selected = pt !== undefined } onPress = () => this.zoomToCluster(coordinate) } return isIncorrectLocation(coordinate) ? undefined : <MapMarker key={coordinate.latitude.toString()+coordinate.longitude.toString()} selected={selected} coordinate={coordinate} onPress={onPress} pointCount={properties.point_count}/> } render() { return ( <View style={style.mapContainer}> <StatusBar backgroundColor='rgba(255, 255, 255, 0.5)' barStyle="dark-content" /> {this.state.loading ? undefined : <View style={style.warningContainer}> <MultilineText style={{textAlign: 'center'}}> Google Play Services is out of date. You can get the latest version from the Play Store </MultilineText> </View>} <MapView style={style.map} region={this.forceRegion || this.currentRegion} ref={(ref) => { this.mapRef = ref }} showsPointsOfInterest={false} showsUserLocation={true} showsCompass={false} rotateEnabled={false} pitchEnabled={false} scrollEnabled={!this.state.loading} zoomEnabled={!this.state.loading} onRegionChangeComplete={(region) => this.onRegionChangeComplete(region)} loadingEnabled={false} moveOnMarkerPress={false}> {this.state.markerArray} </MapView> {this.state.loading ? <View style={style.loadingOverlay}> <ActivityIndicator size='large' style={{ alignItems: 'center', justifyContent: 'center' }} /> </View> : undefined} </View> ) } } const mapStateToProps = (state) => ({ selectedBusinessId: state.business.selectedBusinessId, businessList: state.business.filteredBusinesses.length > 0 ? state.business.filteredBusinesses : state.business.businessList, forceRegion: state.business.forceRegion }) const mapDispatchToProps = (dispatch) => bindActionCreators({ updateMapViewport, selectBusiness }, dispatch) export default connect(mapStateToProps, mapDispatchToProps)(BackgroundMap)
JavaScript
0
@@ -1466,68 +1466,530 @@ -if (!_.isEqual(nextProps.forceRegion, this.props.forceRegion +/*%0A if we press on goToLocation from the same business twice in a row, %0A nextProps.forceRegion and this.props.forceRegion would be the same, %0A even if the map moved in the meantime%0A in this case, the second component of the OR check is met,%0A fixing https://github.com/ScottLogic/BristolPound/issues/1009%0A */%0A if (!_.isEqual(nextProps.forceRegion, this.props.forceRegion) %7C%7C (!_.isEqual(nextProps.mapViewport, this.props.mapViewport) && _.isEqual(nextProps.forceRegion, nextProps.mapViewport) )) %7B @@ -6907,16 +6907,59 @@ ceRegion +,%0A mapViewport: state.business.mapViewport %0A%7D)%0A%0Acon
02eb783dfd233f8e5684d09f43c1a39650d475f7
Add toggle all function
example/mongotodo/main.js
example/mongotodo/main.js
var PromisePipe = require('promise-pipe')(); var Promise = require('es6-promise').Promise; var MongoPipeApi = require('mongo-pipe-api'); PromisePipe.use('db', MongoPipeApi('test', ['items']), {_env:"server"}); var ENV = 'CLIENT'; //set up server if(typeof(window) !== 'object'){ PromisePipe.setEnv('server'); ENV = 'SERVER'; } var prepareItem = doOnServer(function addItem(data, context){ var item = { uid: context.session.id, name: data, done: false } return item; }) var forMe = doOnServer(function(data, context){ return { uid: context.session.id }; }); var toggleModifyItem = doOnServer(function(data, context){ return { query:{ uid: context.session.id, _id:data[0]._id }, update:{ $set: { done: !data[0].done } } }; }); var byId = doOnServer(function(data, context){ return { uid: context.session.id, _id: MongoPipeApi.ObjectId(data) }; }); var byDoneTrue = doOnServer(function(data, context){ return { uid: context.session.id, done: true }; }); module.exports = { PromisePipe: PromisePipe, addItem: PromisePipe() .then(prepareItem) .db.insert.items() .then(forMe) .db.find.items() .then(buildHtml) .then(renderItems), removeItem: PromisePipe() .then(byId) .db.remove.items() .then(forMe) .db.find.items() .then(buildHtml) .then(renderItems), getItems: PromisePipe() .then(forMe) .db.find.items() .then(buildHtml) .then(renderItems), doneItem: PromisePipe() .then(byId) .db.findOne.items() .then(toggleModifyItem) .db.findAndModify.items() .then(forMe) .db.find.items() .then(buildHtml) .then(renderItems), clearDoneItems: PromisePipe() .then(byDoneTrue) .db.remove.items() .then(forMe) .db.find.items() .then(buildHtml) .then(renderItems) } function buildHtml(data){ data = data || []; result = renderTodoApp(renderAppHeader() + renderAppMain("<ul id='todo-list'>" + data.map(function(item, i){ var result = '<input class="toggle" type="checkbox" ' +(item.done?'checked':'')+ ' onclick="main.doneItem(\''+item._id+'\')"></input>'; result+= "<label>" + item.name + "</label>"; result+='<button class="destroy" onclick="main.removeItem(\''+item._id+'\')"></button>'; result = '<div class="view">'+result+'</div>' result = '<li class="'+(item.done?'completed':'')+'">'+result+'</li>' return result; }).join('') + "</ul>" ) + renderAppFooter(data)); return result; } function renderItems(data){ document.getElementById('todoapp').innerHTML = data; return data; } function renderAppHeader(){ return '<header id="header"><h1>todos</h1><input id="new-todo" placeholder="What needs to be done?" autofocus onkeyup="event.which == 13 && main.addItem(this.value);"></header>'; } function renderAppMain(wrap){ return '<section id="main"><input id="toggle-all" type="checkbox"><label for="toggle-all">Mark all as complete</label>' + wrap + '</section>'; } function renderAppFooter(data){ return '<footer id="footer"><span id="todo-count">' +(data?data.length:0)+ ' items</span><button id="clear-completed" onclick="main.clearDoneItems()">Clear completed</button></footer>'; } function renderTodoApp(wrap){ return '<section id="todoapp">' + wrap + '</section>'; } function doOnServer(fn){ fn._env = 'server'; return fn }
JavaScript
0.000001
@@ -800,24 +800,227 @@ %7D%0A %7D;%0A%7D);%0A%0A +var toggleAllItem = doOnServer(function(data, context)%7B%0A return %5B%0A %7B%0A uid: context.session.id%0A %7D,%0A %7B%0A $set: %7B%0A done: data%0A %7D%0A %7D,%0A %7B%0A multi: true%0A %7D%0A %5D%0A%7D);%0A%0A var byId = d @@ -1046,32 +1046,32 @@ data, context)%7B%0A - return %7B%0A u @@ -1308,16 +1308,17 @@ sePipe,%0A +%0A addIte @@ -1463,16 +1463,17 @@ Items),%0A +%0A remove @@ -1614,16 +1614,17 @@ Items),%0A +%0A getIte @@ -1724,16 +1724,17 @@ Items),%0A +%0A doneIt @@ -1932,16 +1932,178 @@ Items),%0A +%0A doneAllItem: PromisePipe()%0A .then(toggleAllItem)%0A .db.update.items()%0A .then(forMe)%0A .db.find.items()%0A .then(buildHtml)%0A .then(renderItems),%0A%0A clearD @@ -2291,13 +2291,9 @@ a)%7B%0A - %0A + @@ -2936,16 +2936,22 @@ %22%0A +, data )%0A @@ -3362,79 +3362,285 @@ wrap -)%7B%0A return '%3Csection id=%22main%22%3E%3Cinput id=%22toggle-all%22 type=%22checkbox +, items)%7B%0A var allChecked = items.reduce(function(result, item)%7B%0A if(!item.done) return false;%0A return result;%0A %7D, true);%0A return '%3Csection id=%22main%22%3E%3Cinput id=%22toggle-all%22 '+(allChecked?'checked':'')+' type=%22checkbox%22 onclick=%22main.doneAllItem(this.checked) %22%3E%3Cl
2f2c95e30566d4d988c206f6551aee6d91d6c072
Remove junks.
lib/ieditor/ieditor.js
lib/ieditor/ieditor.js
var IEditor = (function() { /* * Input is idea of document body */ function IEditor(editorPlace, terminalPlace) { function clone(obj) { // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { var copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { var copy = []; for (var i = 0, var len = obj.length; i < len; ++i) { copy[i] = clone(obj[i]); } return copy; } // Handle Object if (obj instanceof Object) { var copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); } function or(func1, func2) { return function(change) { } } function jsFunc(ch, line) { return new function() { this.ch = ch; this.line = line; this.getCoord = function() { return {ch: this.ch, line: this.line}; } this.parse = function (change) { }; }; } function jsStmtList() { } /* * parse only one change. * Change AST accordingly */ function parseOneChange(astRoot, change) { // TODO: locate first node impacted by change.from // TODO: insert/replace/delete part of ast by using higher order function } /* * Assume: changes contains at least one change */ function parse(astRoot, changes) { parseOneChange(changes); while (changes.hasOwnProperty('next')) { changes = changes[next]; parseOneChange(changes); } } function editorOnChange(editor, changes) { // TODO: console.log("editorOnChange"); console.log(changes); } function terminalOnChange(terminal, changes) { // TODO: console.log("terminalOnChange"); console.log(changes); } var editorTextArea = document.getElementById(editorPlace); var terminalTextArea = document.getElementById(terminalPlace); if (!editorTextArea) { console.log("editor element doesn't exist."); return; } if (!terminalTextArea) { console.log("terminal element doesn't exist."); return; } CodeMirror.fromTextArea(editorTextArea, { mode: "javascript", indentUnit: 4, lineNumbers: true, onChange: editorOnChange }); CodeMirror.fromTextArea(terminalTextArea, { mode: "javascript", onChange: terminalOnChange }); } return IEditor; })();
JavaScript
0
@@ -142,1635 +142,8 @@ -%0A %0A function clone(obj) %7B%0A // Handle the 3 simple types, and null or undefined%0A if (null == obj %7C%7C %22object%22 != typeof obj) return obj;%0A %0A // Handle Date%0A if (obj instanceof Date) %7B%0A var copy = new Date();%0A copy.setTime(obj.getTime());%0A return copy;%0A %7D%0A %0A // Handle Array%0A if (obj instanceof Array) %7B%0A var copy = %5B%5D;%0A for (var i = 0, var len = obj.length; i %3C len; ++i) %7B%0A copy%5Bi%5D = clone(obj%5Bi%5D);%0A %7D%0A return copy;%0A %7D%0A %0A // Handle Object%0A if (obj instanceof Object) %7B%0A var copy = %7B%7D;%0A for (var attr in obj) %7B%0A if (obj.hasOwnProperty(attr)) copy%5Battr%5D = clone(obj%5Battr%5D);%0A %7D%0A return copy;%0A %7D%0A %0A throw new Error(%22Unable to copy obj! Its type isn't supported.%22);%0A %7D%0A %0A %0A function or(func1, func2) %7B%0A return function(change) %7B%0A %0A %7D%0A %7D%0A %0A function jsFunc(ch, line) %7B%0A return new function() %7B%0A this.ch = ch;%0A this.line = line;%0A this.getCoord = function() %7B%0A return %7Bch: this.ch, line: this.line%7D;%0A %7D%0A this.parse = function (change) %7B%0A %0A %7D; %0A %7D;%0A %7D%0A %0A function jsStmtList() %7B%0A %0A %7D%0A
5032a7f897f34d8365f8df3b1db55fd3eb14c009
Remove jshint ignore
test/02.IV/ContractCommon.js
test/02.IV/ContractCommon.js
/* Copyright 2016 - 2018 by Jan Dockx 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. */ /* eslint-env mocha */ 'use strict' const testUtil = require('../_util/testUtil') const stack = require('../../lib/_private/stack') const is = require('../../lib/_private/is') const common = require('./AbstractContractCommon') const Contract = require('../../lib/IV/Contract') function expectInvariants (subject) { subject.must.be.an.instanceof(Contract) common.expectInvariants(subject) is.stackLocation(subject.location).must.be.true() // this strengthening implies the same for the location of subject.abstract, since the locations have to be the same // noinspection JSUnresolvedFunction, JSUnresolvedVariable Contract.isAContractFunction(subject.abstract) subject.implementation.must.be.a.function() } // noinspection FunctionNamingConventionJS function generatePrototypeMethodsDescriptions (oneSubjectGenerator, allSubjectGenerators) { common.generatePrototypeMethodsDescriptions(oneSubjectGenerator, allSubjectGenerators) const self = this // jshint ignore:line describe('#implementation', function () { function expectPost (contract, implFunction, location, result) { contract.isImplementedBy(result).must.be.true() // noinspection JSUnresolvedFunction Contract.isAContractFunction(result).must.be.true() Object.getPrototypeOf(result.contract).must.equal(contract) result.implementation.must.equal(implFunction) testUtil.mustBeCallerLocation(result.location, location) self.expectInvariants(contract) } it('returns an Contract function that is configured as expected', function () { const subject = oneSubjectGenerator() const impl = function () {} const result = subject.implementation(impl) expectPost(subject, impl, stack.location(), result) }) it('returns a different Contract function when called with the same implementation', function () { const subject = oneSubjectGenerator() const impl = function () {} const result = subject.implementation(impl) const result2 = subject.implementation(impl) expectPost(subject, impl, stack.location(), result2) result2.must.not.equal(result) }) it('returns a different Contract function with a different implementation', function () { const subject = oneSubjectGenerator() const impl = function () {} const impl2 = function () {} const result = subject.implementation(impl) const result2 = subject.implementation(impl2) expectPost(subject, impl2, stack.location(), result2) result2.must.not.equal(result) result2.implementation.must.not.equal(result.implementation) }) }) } const test = { expectInvariants: expectInvariants, generatePrototypeMethodsDescriptions: generatePrototypeMethodsDescriptions } Object.setPrototypeOf(test, common) module.exports = test
JavaScript
0.000001
@@ -1539,30 +1539,8 @@ this - // jshint ignore:line %0A%0A
e019ead2e9b9b764a0bea25f705ea9d45d82c5c4
fix variable config in task linux dist
grunt-tasks/register/createLinuxApp.js
grunt-tasks/register/createLinuxApp.js
/** * createLinuxApp */ module.exports = function (grunt) { grunt.registerTask('createLinuxApp', 'Create linux distribution.', function (version) { var done = this.async(); var childProcess = require('child_process'); var exec = childProcess.exec; var path = './' + (version === 'Linux64' ? config.distLinux64 : config.distLinux32); exec('mkdir -p ' + path + '; cp resources/node-webkit/' + version + '/nw.pak ' + path + ' && cp resources/node-webkit/' + version + '/nw ' + path + '/node-webkit && cp resources/node-webkit/' + version + '/icudtl.dat ' + path + '/icudtl.dat', function (error, stdout, stderr) { var result = true; if (stdout) { grunt.log.write(stdout); } if (stderr) { grunt.log.write(stderr); } if (error !== null) { grunt.log.error(error); result = false; } done(result); }); }); };
JavaScript
0.000007
@@ -258,16 +258,63 @@ s.exec;%0A + var config = grunt.config.get(%5B'config'%5D);%0A var @@ -952,8 +952,9 @@ %7D);%0A%0A%7D; +%0A
22aab4846bbcc10e33b028c11cd65fa3cca9e3bc
Fix new_untitled notebook creation from notebook edit
public/ipython/notebook/js/kernelselector.js
public/ipython/notebook/js/kernelselector.js
// Copyright (c) IPython Development Team. // Distributed under the terms of the Modified BSD License. define([ 'jquery', 'base/js/namespace', 'base/js/dialog', 'base/js/utils', ], function($, IPython, dialog, utils) { "use strict"; var KernelSelector = function(selector, notebook) { var that = this; this.selector = selector; this.notebook = notebook; this.notebook.set_kernelselector(this); this.events = notebook.events; this.current_selection = null; this.kernelspecs = {}; if (this.selector !== undefined) { this.element = $(selector); this.request_kernelspecs(); } this.bind_events(); // Make the object globally available for user convenience & inspection IPython.kernelselector = this; this._finish_load = null; this.loaded = new Promise(function(resolve, reject) { that._finish_load = resolve; }); Object.seal(this); }; KernelSelector.prototype.request_kernelspecs = function() { var url = utils.url_join_encode(this.notebook.base_url, 'api/kernelspecs'); utils.promising_ajax(url).then($.proxy(this._got_kernelspecs, this)); }; KernelSelector.prototype._got_kernelspecs = function(data) { var that = this; this.kernelspecs = data.kernelspecs; var change_kernel_submenu = $("#menu-change-kernel-submenu"); var new_notebook_submenu = $("#menu-new-notebook-submenu"); var keys = Object.keys(data.kernelspecs).sort(function (a, b) { // sort by display_name var da = data.kernelspecs[a].spec.display_name; var db = data.kernelspecs[b].spec.display_name; if (da === db) { return 0; } else if (da > db) { return 1; } else { return -1; } }); keys.map(function (key) { // Create the Kernel > Change kernel submenu var ks = data.kernelspecs[key]; change_kernel_submenu.append( $("<li>").attr("id", "kernel-submenu-"+ks.name).append( $('<a>') .attr('href', '#') .click( function () { that.set_kernel(ks.name); }) .text(ks.spec.display_name) ) ); // Create the File > New Notebook submenu new_notebook_submenu.append( $("<li>").attr("id", "new-notebook-submenu-"+ks.name).append( $('<a>') .attr('href', '#') .click( function () { that.new_notebook(ks.name); }) .text(ks.spec.display_name) ) ); }); // trigger loaded promise this._finish_load(); }; KernelSelector.prototype._spec_changed = function (event, ks) { /** event handler for spec_changed */ // update selection this.current_selection = ks.name; // put the current kernel at the top of File > New Notebook var cur_kernel_entry = $("#new-notebook-submenu-" + ks.name); var parent = cur_kernel_entry.parent(); // do something only if there is more than one kernel if (parent.children().length > 1) { // first, sort back the submenu parent.append( parent.children("li[class!='divider']").sort( function (a,b) { var da = $("a",a).text(); var db = $("a",b).text(); if (da === db) { return 0; } else if (da > db) { return 1; } else { return -1; }})); // then, if there is no divider yet, add one if (!parent.children("li[class='divider']").length) { parent.prepend($("<li>").attr("class","divider")); } // finally, put the current kernel at the top parent.prepend(cur_kernel_entry); } // load logo var logo_img = this.element.find("img.current_kernel_logo"); $("#kernel_indicator").find('.kernel_indicator_name').text(ks.spec.display_name); if (ks.resources['logo-64x64']) { logo_img.attr("src", ks.resources['logo-64x64']); logo_img.show(); } else { logo_img.hide(); } // load kernel css var css_url = ks.resources['kernel.css']; if (css_url) { $('#kernel-css').attr('href', css_url); } else { $('#kernel-css').attr('href', ''); } // load kernel js if (ks.resources['kernel.js']) { require([ks.resources['kernel.js']], function (kernel_mod) { if (kernel_mod && kernel_mod.onload) { kernel_mod.onload(); } else { console.warn("Kernel " + ks.name + " has a kernel.js file that does not contain "+ "any asynchronous module definition. This is undefined behavior "+ "and not recommended."); } }, function (err) { console.warn("Failed to load kernel.js from ", ks.resources['kernel.js'], err); } ); } }; KernelSelector.prototype.set_kernel = function (kernel_name) { /** set the kernel by name, ensuring kernelspecs have been loaded, first */ var that = this; return this.loaded.then(function () { that._set_kernel(kernel_name); }); }; KernelSelector.prototype._set_kernel = function (kernel_name) { /** Actually set the kernel (kernelspecs have been loaded) */ if (kernel_name === this.current_selection) { // only trigger event if value changed return; } var ks = this.kernelspecs[kernel_name]; if (this.notebook._session_starting) { console.error("Cannot change kernel while waiting for pending session start."); return; } this.current_selection = kernel_name; this.events.trigger('spec_changed.Kernel', ks); }; KernelSelector.prototype.new_notebook = function (kernel_name) { var w = window.open(); // Create a new notebook in the same path as the current // notebook's path. var that = this; var parent = utils.url_path_split(that.notebook.notebook_path)[0]; that.notebook.contents.new_untitled(parent, {type: "notebook"}).then( function (data) { var url = utils.url_join_encode( that.notebook.base_url, 'notebooks', data.path ); url += "?kernel_name=" + kernel_name; w.location = url; }, function(error) { w.close(); dialog.modal({ title : 'Creating Notebook Failed', body : "The error was: " + error.message, buttons : {'OK' : {'class' : 'btn-primary'}} }); } ); }; KernelSelector.prototype.lock_switch = function() { // should set a flag and display warning+reload if user want to // re-change kernel. As UI discussion never finish // making that a separate PR. console.warn('switching kernel is not guaranteed to work !'); }; KernelSelector.prototype.bind_events = function() { var that = this; this.events.on('spec_changed.Kernel', $.proxy(this._spec_changed, this)); this.events.on('kernel_created.Session', function (event, data) { that.set_kernel(data.kernel.name); }); var logo_img = this.element.find("img.current_kernel_logo"); logo_img.on("load", function() { logo_img.show(); }); logo_img.on("error", function() { logo_img.hide(); }); }; return {'KernelSelector': KernelSelector}; });
JavaScript
0.000007
@@ -7058,16 +7058,29 @@ otebook%22 +, custom: %7B%7D %7D).then(
d16bc548a9bfa38123674cdd5109592ad25001d7
return post deferred from scorer
examples/dscore/Scorer.js
examples/dscore/Scorer.js
define(['jquery','app/API','underscore','./computeD','./msgCat','./parcelMng'],function($,API,_,computeData,msgMan,parcelMng){ var Scorer = {}; //comment $.extend(Scorer, { /* Function: Void addSettings. Input: settings object. Output: set the settings in computeD object or msgCat according to input Description: Settings for computeD or msgCat */ addSettings: function(type,Obj){ if (type =="compute"){ computeData.setComputeObject(Obj); }else{ if (type =="message") msgMan.setMsgObject(Obj); } }, /* Function: Void init. Input: none. Output: none Description: make sure console.log is safe among all browsers. */ init: function(){ console || (console = {}); console.log || (console.log = function(){}); }, /* Function: Void computeD. Input: none. Output: final score. Description: Calculate the score returns an object that hold the score an an error msg. */ computeD: function(){ Scorer.init(); computeData.setDataArray(); console.log('started computeD'); console.log(computeData); console.log(msgMan); parcelMng.Init(computeData); parcelMng.avgAll(computeData); //parcelMng.diffAll(computeData); parcelMng.varianceAll(computeData); parcelMng.scoreAll(computeData); var scoreObj = parcelMng.scoreData; console.log('the score from new scoree is: '+scoreObj.score ); //var oldScore = parcelMng.simulateOldCode(computeData);//for testing only //console.log('the score from old scoree is: '+oldScore ); return scoreObj; //return score.toFixed(2); }, getInfo: function(){ //return computeData; }, /* Function: Void postToServer. Input: score, a message a key to be used. Output: Ajax send to server. Description: post to server the score and the message. */ postToServer: function(score,msg,scoreKey,msgKey){ var postSettings = computeData.postSettings; var url = postSettings.url; if (scoreKey == null || scoreKey == undefined) scoreKey = postSettings.score; if (msgKey == null || msgKey == undefined) msgKey = postSettings.msg; var data = {}; data[scoreKey] =score; data[msgKey] = msg; $.post(url,JSON.stringify(data)); }, // get message according to user input getFBMsg: function(DScore){ var msg = msgMan.getMsg(DScore); return msg; } }); return Scorer; });
JavaScript
0
@@ -2171,16 +2171,23 @@ %0A%0A %09%09 +return $.post(u
d4ad95c9c433b5d959c69e900fe4732b3514e7a2
Set user online on touch events too
client/client.js
client/client.js
var timer, status; UserPresence = { awayTime: 60000, //1 minute awayOnWindowBlur: false, onSetUserStatus: function() {}, startTimer: function() { UserPresence.stopTimer(); timer = setTimeout(UserPresence.setAway, UserPresence.awayTime); }, stopTimer: function() { clearTimeout(timer); }, restartTimer: function() { UserPresence.startTimer(); }, setAway: function() { if (status !== 'away') { status = 'away'; Meteor.call('UserPresence:away'); } UserPresence.stopTimer(); }, setOnline: function() { if (status !== 'online') { status = 'online'; Meteor.call('UserPresence:online'); } UserPresence.startTimer(); }, start: function() { Deps.autorun(function() { var user = Meteor.user(); status = user && user.statusConnection; UserPresence.startTimer(); }); Meteor.methods({ 'UserPresence:setDefaultStatus': function(status) { Meteor.users.update({_id: Meteor.userId()}, {$set: {status: status, statusDefault: status}}); }, 'UserPresence:online': function() { var user = Meteor.user(); if (user && user.statusDefault === 'online') { Meteor.users.update({_id: Meteor.userId()}, {$set: {status: 'online'}}); } UserPresence.onSetUserStatus(user, 'online'); }, 'UserPresence:away': function() { var user = Meteor.user(); UserPresence.onSetUserStatus(user, 'away'); } }); document.addEventListener('mousemove', UserPresence.setOnline); document.addEventListener('mousedown', UserPresence.setOnline); document.addEventListener('keydown', UserPresence.setOnline); window.addEventListener('focus', UserPresence.setOnline); if (UserPresence.awayOnWindowBlur === true) { window.addEventListener('blur', UserPresence.setAway); } } }
JavaScript
0
@@ -1499,32 +1499,97 @@ nce.setOnline);%0A +%09%09document.addEventListener('touchend', UserPresence.setOnline);%0A %09%09document.addEv
066863a1f2e261a1beb7792e4bb4b72b11af6913
remove one of duplicate $filter
grails-app/assets/javascripts/streama/controllers/admin-reports-ctrl.js
grails-app/assets/javascripts/streama/controllers/admin-reports-ctrl.js
//= wrapped angular.module('streama').controller('adminReportsCtrl', [ 'apiService', '$state', '$rootScope', '$filter', '$filter', function (apiService, $state, $rootScope, $filter) { var vm = this; var selectedReports = []; vm.maxPerPage = 15; vm.pagination = {}; vm.sortAndOrderBy = { sort: 'dateCreated', order: 'DESC' }; var currentOffset = 0; vm.resolveMultiple = resolveMultiple; vm.resolve = resolve; vm.unresolve = unresolve; vm.pageChanged = pageChanged; vm.refreshList = refreshList; vm.addOrRemoveFromSelection = addOrRemoveFromSelection; function pageChanged () { currentOffset = vm.maxPerPage*(vm.pagination.currentPage-1); loadReports({max: vm.maxPerPage, filter: vm.listFilter, offset: currentOffset, sort: vm.sortAndOrderBy.sort, order: vm.sortAndOrderBy.order}); } function refreshList (filter) { if (filter) { vm.listFilter = filter; } loadReports({max: vm.maxPerPage, filter: vm.listFilter, offset: currentOffset, sort: vm.sortAndOrderBy.sort, order: vm.sortAndOrderBy.order}); } function loadReports (params) { vm.reports = []; vm.reportsCount = 0; apiService.report.list(params) .then(function (response) { vm.reports = response.data.reports; vm.reportsCount = response.data.count; }, function () { alertify.error('An error occurred.'); }); } function addOrRemoveFromSelection($event, report) { if($event.target.checked && report.resolved === false) { selectedReports.push(report.id); } else { _.remove(selectedReports, function(id) { return id === report.id; }); } } function resolve(oldReport) { apiService.report.resolve(oldReport.id).then (function (response) { var newReport = response.data; oldReport.resolved = newReport.resolved; oldReport.lastUpdated = newReport.lastUpdated; alertify.success('Selected report has been resolved.'); }, function () { alertify.error('Report could not be resolved.'); }); } function unresolve(oldReport) { apiService.report.unresolve(oldReport.id).then (function (response) { var newReport = response.data; oldReport.resolved = newReport.resolved; oldReport.lastUpdated = newReport.lastUpdated; alertify.success('Selected report has been unresolved.'); }, function () { alertify.error('Report could not be unresolved.'); }); } function resolveMultiple() { if(selectedReports.length > 0) { var confirmText = "This will resolve all selected reports. Do you want to proceed?"; alertify.set({ buttonReverse: true, labels: {ok: "Yes", cancel : "Cancel"}}); alertify.confirm(confirmText, function (confirmed) { if(confirmed){ apiService.report.resolveMultiple(selectedReports).then (function (response) { var newReports = response.data; _.forEach(newReports, function (newReport) { _.forEach(vm.reports, function (oldReport) { if (newReport.id === oldReport.id) { oldReport.resolved = newReport.resolved; oldReport.lastUpdated = newReport.lastUpdated; } }); }); selectedReports = []; alertify.success('Selected reports have been resolved.'); }, function () { alertify.error('Reports could not be resolved.'); }); } }); } else alertify.error('No reports selected.'); } refreshList('all'); }]);
JavaScript
0.000018
@@ -115,27 +115,16 @@ filter', - '$filter', functio
3df70b37b62270abf5d3ed5867c60b519a9ea099
send testing infos to content for notifications
src/js/background/notification.js
src/js/background/notification.js
/* eslint no-unused-vars: 0 */ var Notification = { create: function(message, onClickCallback) { var formNotificationId = null; chrome.notifications.create(Math.random().toString(), { "iconUrl": chrome.runtime.getURL("images/icon_48.png"), "type": "basic", "title": "Form-O-Fill", "message": message, "isClickable": true }, function(notificationId) { formNotificationId = notificationId; }); chrome.notifications.onClicked.addListener(function (notificationId) { if(notificationId === formNotificationId) { onClickCallback(); } }); } };
JavaScript
0
@@ -1,11 +1,37 @@ /* - +global Testing, Utils */%0A/* eslint n @@ -49,9 +49,27 @@ rs: -0 +%5B2, %22Notification%22%5D */%0A @@ -428,24 +428,235 @@ cationId) %7B%0A + if(!Utils.isLiveExtension()) %7B%0A Testing.setVar(%22notification-html%22, message, %22Last Notification HTML%22);%0A Testing.setVar(%22notification-status%22, %22visible%22, %22Last Notification status%22);%0A %7D%0A formNo @@ -816,24 +816,161 @@ cationId) %7B%0A + if(!Utils.isLiveExtension()) %7B%0A Testing.setVar(%22notification-status%22, %22clicked%22, %22Last Notification status%22);%0A %7D%0A onCl
3529c25395ca9dea338ea5e4006909e42a1565cb
fix color
sample/jasmine-inclass9.spec.js
sample/jasmine-inclass9.spec.js
describe('Jasmine In Class Exercise', function() { beforeEach(function() { $('#fixture').remove(); var html = '<span>This is a span with some color changing text</span>' // add a checkbox to html $('body').append('<div id="fixture">' + html + '</div>') // this function was defined in jasmine-inclass9.js window.setupHandlers($('#fixture')) }) it('should test that 1 is 1', function() { expect(1).toBe(1) }) it('should set the span text color to blue on load', function() { expect($('span', $('#fixture'))[0].color).toBe('blue') }) it('should set span text color to red when checked', function() { // use jQuery to check the box // then examine the text color of the span expect(1).toBe(1) // remove this line }) it('should set span text color to green when unchecked', function() { // check the box, then uncheck the box // examine the text color fo the span expect(1).toBe(1) // remove this line }) //*************************************************// // now we do some non-DOM JavaScript testing it('should compute the trajectory after 1 second', function() { var obj = { x: 5, y: 10, vx: 1, vy: 2, ay: -0.1 } moveObject(obj, 1.0) // expect object at [ 6, 11.95 ] moveObject(obj, 1.0); // expect object at [ 7, 13.80 ] obj.ax = 0.5; obj.ay = -0.4; moveObject(obj, 1.0); // expect object at [ 8.25, 15.40 ] expect(1).toBe(1) // remove this line }) })
JavaScript
0.000002
@@ -581,16 +581,22 @@ e'))%5B0%5D. +style. color).t
f9f2c10deda6bf8610bf1c106211248df26c48e8
Remove debug output
client/js/app.js
client/js/app.js
console.log('AI Lovers'); $(function () { var runGameBtn = $('#runGame'); var host = window.document.location.host.replace(/:.*/, ''); var ws = new WebSocket('ws://' + host + ':8000'); runGameBtn.click(function () { ws.send(JSON.stringify({ commands: _.map(_.range(4), function (i) { return $('#ai' + i).val(); }) })); $('#log').html('Running a game...'); }); ws.onmessage = function (event) { var gameResult = JSON.parse(event.data); showLog(gameResult.log); loadReplayer(gameResult.replay); }; function showLog(rawLog) { var htmlLog = _.map(rawLog, function (log) { return log.message.replace(/\n/g, '<br />'); }, this).join('<br />'); $('#log').html(htmlLog); } function loadReplayer(replay) { console.log('/replayer?' + JSON.stringify(replay)); $('#replayer').attr('src', '/replayer/?replay=' + JSON.stringify(replay)); } });
JavaScript
0.000037
@@ -863,68 +863,8 @@ ) %7B%0A - console.log('/replayer?' + JSON.stringify(replay));%0A
2768f8fba6e78042c0fcca86ed24f91c1c855d8b
Fix test about validation errors
test/batch-processor.test.js
test/batch-processor.test.js
var utils = require('./test-utils'); var assert = require('chai').assert; var fs = require('fs'); var path = require('path'); var nroonga = require('nroonga'); var Processor = require('../lib/batch/processor').Processor; var schemeDump = fs.readFileSync(__dirname + '/fixture/companies/ddl.grn', 'UTF-8').replace(/\s+$/, ''); var loadDump = fs.readFileSync(__dirname + '/fixture/companies/data.grn', 'UTF-8').replace(/\s+$/, ''); var temporaryDatabase; suiteSetup(function() { temporaryDatabase = utils.createTemporaryDatabase(); }); suiteTeardown(function() { temporaryDatabase.teardown(); temporaryDatabase = undefined; }); suite('batch/processor/Processor (instance methods)', function() { var processor; var database; setup(function() { database = temporaryDatabase.get(); utils.loadDumpFile(database, __dirname + '/fixture/companies/ddl.grn'); utils.loadDumpFile(database, __dirname + '/fixture/companies/data.grn'); processor = new Processor({ databasePath: temporaryDatabase.path, database: database, // we must reuse the existing connection! domain: 'companies', }); }); teardown(function() { processor = undefined; database.commandSync('table_remove', { name: 'BigramTerms' }); database.commandSync('table_remove', { name: 'companies' }); }); test('initialize', function() { assert.equal(processor.databasePath, temporaryDatabase.path); assert.equal(processor.domain, 'companies'); }); test('getColumns', function(done) { processor.getColumns() .next(function(columns) { var expected = ['name', 'address', 'email_address', 'description']; assert.deepEqual(columns.sort(), expected.sort()); done(); }) .error(function(error) { done(error); }); }); test('process add-batches', function(done) { var batches = fs.readFileSync(__dirname + '/fixture/companies/add.sdf.json', 'UTF-8'); batches = JSON.parse(batches); processor.process(batches) .next(function(results) { var expected = { status: 'success', adds: 10, deletes: 0 }; assert.deepEqual(results, expected); var dump = database.commandSync('dump', { tables: 'companies' }); assert.equal(dump, schemeDump + '\n' + loadDump); done(); }) .error(function(error) { done(error); }); }); test('process invalid batches', function(done) { var batches = fs.readFileSync(__dirname + '/fixture/companies/invalid.sdf.json', 'UTF-8'); batches = JSON.parse(batches); processor.process(batches) .next(function(results) { var error = new Error('no validation error: ' + results); done(error); }) .error(function(error) { if (error.message == Processor.INVALID_BATCH) { assert.deepEqual(error.errors, []); done(); } else { done(error); } }); }); });
JavaScript
0.000011
@@ -2961,69 +2961,477 @@ %5B -%5D);%0A done();%0A %7D else %7B%0A done +'invalidfield: The field %22unknown1%22 is unknown.',%0A 'invalidfield: The field %22unknown2%22 is unknown.',%0A 'invalidfield: The field %22name%22 is null.',%0A 'nofields: You must specify %22fields%22.',%0A 'emptyfields: You must specify one or more fields to %22fields%22.'%5D);%0A done();%0A %7D else %7B%0A throw error;%0A %7D%0A %7D)%0A .error(function (error) -; + %7B %0A @@ -3427,33 +3427,44 @@ rror) %7B%0A -%7D +done(error); %0A %7D);%0A %7D);
bf785db0b019be1a2d9ab9893cb6b1b75ae1b29f
change default maxlen to 999
avalon/ui/form/textarea/td.textarea.js
avalon/ui/form/textarea/td.textarea.js
define(['avalon', 'text!./td.textarea.html', 'css!./td.textarea.css'], function(avalon, template) { var _interface = function () { }; avalon.component("td:textarea", { //外部属性 label: '', value: '', name: 'textarea', maxlen: -1, //最大长度 width: '100%', must: false, html: false, disabled: false, //外部参数 onchanged: null, onclicked: null, //view属性 isValid: true, validInfo: '', //view接口 validValue: _interface, doClick: _interface, $template: template, // hooks : 定义component中的属性 //vmOpts : 引用component时的js配置$opt //eleOpts: 使用component时标签中的属性 $construct: function (hooks, vmOpts, elemOpts) { if(typeof elemOpts.must == 'number') { elemOpts.maxlen = elemOpts.must; } var options = avalon.mix(hooks, vmOpts, elemOpts); return options; }, $dispose: function (vm, elem) { elem.innerHTML = elem.textContent = ''; }, $init: function(vm, elem) { //内部方法 vm._trigger = function(ev, type) { switch (type) { case 'clicked': if(typeof vm.onclicked == 'function') { vm.onclicked(ev, vm); } break; case 'changed': if(typeof vm.onchanged == 'function') { vm.onchanged(ev, vm); } break; default: break; } } //接口方法 vm.doClick = function(ev) { vm._trigger(ev, 'clicked'); } vm.validValue = function(ev) { vm.isValid = true; if(vm.must && vm.value == '') { vm.validInfo = '该字段不允许为空'; vm.isValid = false; } //禁止输入html内容 if(!vm.html && vm.isValid) { vm.isValid = !/<[^>]+>/.test(vm.value); vm.validInfo = vm.isValid ? '' : '不允许输入标签'; } } //对外方法 vm.getData = function() { var data = {}; data[vm.name] = vm.value; return data; } vm.getValue = function() { return vm.value; } vm.setValue = function(val) { if(val != vm.value) { vm.value = val; vm.validValue(null); } } vm.$watch('value', function(newVal, oldVal) { vm._trigger({newVal: newVal, oldVal: oldVal}, 'changed'); }); }, $ready: function (vm) { vm.validValue(null); } }); var widget = avalon.components["td:textarea"]; widget.regionals = {}; })
JavaScript
0.000482
@@ -233,10 +233,11 @@ en: --1 +999 ,
adc1222ba14fb635f77463c4b87bd390a140c876
Fix class name
src/components/VerifyRegistrationInfo.js
src/components/VerifyRegistrationInfo.js
import React, {Component, PropTypes} from 'react' import Grid from 'react-bootstrap/lib/Grid' import Row from 'react-bootstrap/lib/Row' import Col from 'react-bootstrap/lib/Col' export default class RegistrationForm extends Component { static propTypes = { formUpdate: PropTypes.func } constructor(props) { super(props); this.state = props.state || {} } render() { const { state } = this.props return ( <Grid> <Row> <Col md={12} id='title'>Verify Registration Information</Col> </Row> <Row> <Col md={6}>Name</Col> <Col md={6} id='userName'>{state.userName}</Col> </Row> <Row> <Col md={6}>Email</Col> <Col md={6} id='email'>{state.email}</Col> </Row> <Row> <Col md={12}> <button id='edit'>Edit</button> <button id='confirm'>Confirm</button> </Col> </Row> </Grid> ) } }
JavaScript
0.001772
@@ -193,16 +193,22 @@ t class +Verify Registra @@ -215,12 +215,12 @@ tion -Form +Info ext
49ab20456ea6f2393edea2c4f4b9229f251c94d7
Update player view
client/player.js
client/player.js
function Player(parent){ parent.innerHTML += '<div id="dialog-player" title="Controller" style="width:100%;"></div>'; var audio_html = '<audio id="audio_player"> \ <source src="/stream/" type="audio/wav" /> \ </audio> \ <span id="state" style="text-align:center;width:100%;">State</span><br> \ Local: \ <select id="audio_selection">\ <option value="/stream/">stream.ogg</option>\ </select><br>\ <div id="remote_div">Remote: <input type="text" id="remote_url" value="http://doppler.media.mit.edu:8000/impoundment.ogg" style="width:350px;"><input type="button" id="remote_button" value="Load"></div>\ <br>\ <div id="results">Results</div>\ <img src="/fft" id="img_fft">\ '; this.dialog = $( '#dialog-player' ).dialog({ autoOpen: true, width: 690, modal: false, open:function(){ socket.emit('sys', JSON.stringify( {sys:{streams:''}} )); }, buttons: { Update: function(){ socket.emit('sys', JSON.stringify( {sys:{streams:''}} )); }, Mute: function(){ if (document.getElementById('audio_player' ).paused == false) $( '#audio_player' ).trigger('pause'); else $('#audio_player' ).trigger('play'); }, Resume: function(){ socket.emit('sys', JSON.stringify( {sys:{control:'resume'}} )); $( '#audio_player' ).load(); $( '#audio_player' ).trigger('play'); }, Play: function(){ if(!document.getElementById('audio_player').paused && !document.getElementById('audio_player').played.length) $( '#audio_player' ).attr('src', '/stream/?time='+ ((new Date()).getTime())); $( '#audio_player' ).load(); $( '#audio_player' ).trigger('play'); socket.emit('sys', JSON.stringify( {sys:{control:'play'}} )) }, Pause: function(){ socket.emit('sys', JSON.stringify( {sys:{control:'pause'}} )) }, Prev: function(){ $( '#audio_player' ).attr('src', '/stream/?time='+ ((new Date()).getTime())); $( '#audio_player' ).load(); $( '#audio_player' ).trigger('play'); socket.emit('sys', JSON.stringify( {sys:{control:'prev'}} )) }, Next: function(){ $( '#audio_player' ).attr('src', '/stream/?time='+ ((new Date()).getTime())); $( '#audio_player' ).load(); $( '#audio_player' ).trigger('play'); socket.emit('sys', JSON.stringify( {sys:{control:'next'}} )) } } }); $('#dialog-player').html(audio_html); function check_audio(){ var audio = document.getElementById("audio_player"); if(!audio.paused) if (isNaN(audio.duration)){ $( '#audio_player' ).attr('src', '/stream/?time='+ ((new Date()).getTime())); $( '#audio_player' ).load(); $( '#audio_player' ).trigger('play'); } setTimeout(check_audio, 250); } check_audio(); /****/ socket.on('sys', function(msg){ try { obj = JSON.parse(msg); if (! obj.sys) throw "not a sys object"; $('#state').html('State: ' + obj.sys.state + ' sample-id ' + obj.sys.sample_count); } catch (err){ console.log("WARNING: player socket error " + err); } }); $( '#audio_player' ).on('ended', function(){ $( '#audio_player' ).attr('src', '/stream/?time='+ ((new Date()).getTime())); $( '#audio_player' ).load(); $( '#audio_player' ).trigger('play'); }); $( '#audio_selection' ).on('change', function(ev, ui){ if (socket || 0){ $( '#remote_div' ).show(); socket.emit('sys', '{ "sys": { "url": "' + $( '#audio_selection option:selected' ).val() + '" } }'); socket.emit('sys', JSON.stringify( {sys:{control:'resume'}} )); $( '#audio_player' ).load(); $( '#audio_player' ).trigger('play'); } else console.log("no socket"); }); $( '#remote_button' ).click(function(){ socket.emit('sys', '{ "sys": { "url": "' + $( '#remote_url' ).val() + '" } }'); }); /****/ this.show = function(){ this.dialog.dialog('open'); socket.emit('sys', JSON.stringify( {sys:{streams:''}} )); } this.process = function(json){ if (json.analysis && json.chan){ document.getElementById('img_fft').src = '/fft?time='+((new Date()).getTime()); if (json.analysis.result.indexOf('->') == -1) $( '#results' ).html( ''+ json.chan + ' - ' +json.analysis.result); } if(json.sys) // Reload source selector and add default options: Icecast, Microphone and server streams if (json.sys.streams){ $( '#audio_selection' ).empty(); $( '#audio_selection' ).append($("<option></option>").attr("value", " ")); $( '#audio_selection' ).append($("<option>Microphone (server)</option>").attr("value", "microphone")); for (var i=0; i < json.sys.streams.length; i++) $( '#audio_selection' ).append($("<option></option>").attr("value", json.sys.streams[i]).text(json.sys.streams[i])); } /****/ } }
JavaScript
0
@@ -3247,18 +3247,18 @@ + ' - sample-id +%3Cbr%3ECount: ' + @@ -3278,16 +3278,35 @@ le_count + +'%3Cbr%3E%3Cbr%3ESource:' );%0A %7D
e44539d76e42e444106e44630f3407864455fca7
hacker news relevancy, normalize
share/spice/hacker_news/hacker_news.js
share/spice/hacker_news/hacker_news.js
function ddg_spice_hacker_news(api_result) { // Check for at least 1 result if (!api_result.results.length) { return; } var script = $('[src*="/js/spice/hacker_news/"]')[0]; var source = $(script).attr("src"); var query = source.match(/hacker_news\/([^\/]+)/)[1]; var source_url = 'https://www.hnsearch.com/search#request/all&q=' + query; var items = api_result.results.map(function(result){ var item = result.item; item.url = (item.url) ? item.url : 'http://news.ycombinator.com/item?id=' + item.id; item.points = item.points || 0; item.pointsLabel = (item.points == 1) ? 'Point' : 'Points'; item.num_comments = item.num_comments || 0; item.commentsLabel = (item.numComments == 1) ? 'Comment' : 'Comments'; item.domain = item.domain || 'news.ycombinator.com'; return item; }); Spice.render({ id: 'hacker_news', name: 'Hacker News', data: items, meta: { sourceName: 'Hacker News', sourceUrl: source_url, sourceIcon: true, count: items.length, total: api_result.hits, itemType: 'Results' }, templates: { item: 'hacker_news' } }); // Add click event. $("a.hn_showHide").click(function(){ if ($(this).data("target")){ var target = $(this).data("target"); $(target).toggle(); } }); }
JavaScript
0.999369
@@ -42,104 +42,8 @@ ) %7B%0A - // Check for at least 1 result%0A if (!api_result.results.length) %7B%0A return;%0A %7D%0A%0A @@ -282,535 +282,17 @@ -var items = api_result.results.map(function(result)%7B%0A var item = result.item;%0A item.url = (item.url) ? item.url : 'http://news.ycombinator.com/item?id=' + item.id;%0A%0A item.points = item.points %7C%7C 0;%0A item.pointsLabel = (item.points == 1) ? 'Point' : 'Points';%0A item.num_comments = item.num_comments %7C%7C 0;%0A item.commentsLabel = (item.numComments == 1) ? 'Comment' : 'Comments';%0A%0A item.domain = item.domain %7C%7C 'news.ycombinator.com';%0A%0A return item;%0A %7D);%0A%0A Spice.render +Spice.add (%7B%0A @@ -363,20 +363,33 @@ data: -item +api_result.result s,%0A%0A @@ -508,41 +508,8 @@ ue,%0A - count: items.length,%0A @@ -596,62 +596,970 @@ -templates: %7B%0A item: 'hacker_news'%0A %7D +normalize: function(o) %7B%0A // perhaps if o.numComments %3C a threshold return null;%0A return %7B%0A // could create a Date object from o.item.create_ts for display, sorting by date%0A title: o.item.title,%0A url: (o.item.url) ? o.item.url : 'http://news.ycombinator.com/item?id=' + o.item.id,%0A points: o.item.points %7C%7C 0,%0A pointsLabel: (o.item.points == 1) ? 'Point' : 'Points',%0A num_comments: o.item.num_comments %7C%7C 0,%0A commentsLabel: (o.item.numComments == 1) ? 'Comment' : 'Comments',%0A domain: o.item.domain %7C%7C 'news.ycombinator.com'%0A %7D;%0A %7D,%0A%0A templates: %7B%0A item: Spice.hacker_news.hacker_news%0A %7D,%0A%0A relevancy: %7B%0A primary: %5B%0A %7B required: 'item.title' %7D,%0A %7B key: 'item.title'%7D,%0A %7B key: 'item.text'%7D%0A %5D%0A %7D,%0A %0A
29b8196468fb68a5240148c3685424ef5e0cbfad
make deploy depend on build
gulp/tasks/deploy.js
gulp/tasks/deploy.js
var gulp = require('gulp'); var deploy = require("gulp-gh-pages"); gulp.task('deploy', function () { gulp.src("./build/**/*") .pipe(deploy({})); });
JavaScript
0.000001
@@ -80,16 +80,27 @@ deploy', + %5B'build'%5D, functio
e3fae01274a1f370dd70395b6ff87147abcbe217
disable test until genesis hash updated
test/common/genesishashes.js
test/common/genesishashes.js
var genesisData = require('../../../tests/genesishashestest.json'), assert = require('assert'), Blockchain = require('../../lib/blockchain.js'), Block = require('../../lib/block.js'), levelup = require('levelup'); var blockDB = levelup('', { db: require('memdown') }), detailsDB = levelup('/does/not/matter', { db: require('memdown') }), blockchain; describe('[Common]: genesis hashes tests', function () { it('should create a new block chain', function (done) { blockchain = new Blockchain(blockDB, detailsDB); blockchain.init(done); }); it('should have added the genesis correctly', function () { var blockGenesis = new Block(), rlpGenesis; blockGenesis.header.stateRoot = genesisData.genesis_state_root; rlpGenesis = blockGenesis.serialize(); assert(rlpGenesis.toString('hex') === genesisData.genesis_rlp_hex, 'rlp hex mismatch'); blockchain.addBlock(blockGenesis, function() { assert(blockchain.meta.genesis === genesisData.genesis_hash); }); }); });
JavaScript
0.000001
@@ -569,18 +569,87 @@ %7D);%0A%0A -it +// TODO: activate when test data has the correct genesis hash%0A it.skip ('should
4a26698e487e63002ed2c9351bd89e8b2661bff8
Fix deprecation warning
plugins/templates.js
plugins/templates.js
const each = require("async/each"); const extend = require("extend"); const fs = require("fs"); const match = require("multimatch"); const nunjucks = require("nunjucks"); const nunjucksDate = require("nunjucks-date"); /** * Applies the nunjucks template engine. Code has been copied from the * metalsmith-templates plugin but slightly modified to only support nunjucks * The metalsmith-templates plugin is released under the MIT license. * https://github.com/segmentio/metalsmith-templates */ function templates(opts) { opts = opts || {}; let dir = opts.directory || 'templates'; let pattern = opts.pattern; let inPlace = opts.inPlace; let dev = opts.dev; return function(files, metalsmith, done) { let metadata = metalsmith.metadata(); each(Object.keys(files), convert, done); function check(file) { if (pattern && !match(file, pattern)[0]) { return false; } let data = files[file]; let tmpl = data.template; if (!inPlace && !tmpl) { return false; } return true; } function convert(file, done) { if (!check(file)) { return done(); } let data = files[file]; let str; if (inPlace) { str = data.contents.toString(); } else { str = fs.readFileSync(metalsmith.path(dir, data.template)); str = str.toString(); } let clone = extend({}, metadata, data); let env = new nunjucks.Environment(new nunjucks.FileSystemLoader(dir, { noCache: dev })); nunjucksDate.install(env); env.renderString(str, clone, function(err, str) { if (err) { return done(err); } data.contents = new Buffer(str); done(); }); } }; } module.exports = templates;
JavaScript
0.000099
@@ -1945,19 +1945,20 @@ ts = - new Buffer +.from (str
ce6af00514513c5dd501a5b285c9887fd99225c0
add update policy endpoint
lib/models/Policies.js
lib/models/Policies.js
"use strict"; const ShareTempusMethod = require('../ShareTempusMethod'); class Policies extends ShareTempusMethod { constructor() { super({ quote: { method : 'POST', path : '/policies/quote' }, create: { method : 'POST', path : '/policies/create' }, retrieve: { method : 'GET', path : '/policies/{policy}', params : ['policy'] } }); } } module.exports = Policies;
JavaScript
0
@@ -379,16 +379,17 @@ %7D,%0A +%0A @@ -392,16 +392,120 @@ +update: %7B%0A method : 'POST',%0A path : '/policies/update'%0A %7D,%0A %0A
e42c13f9ced0225543334f57bd27cff48c96b8b5
handle anonymous stations for splays
src/js/viewer/walls/buildAlpha.js
src/js/viewer/walls/buildAlpha.js
import { FACE_ALPHA, LEG_SPLAY, FACE_WALLS, LEG_CAVE } from '../../core/constants'; import { WorkerPool } from '../../core/WorkerPool'; import { Walls } from './Walls'; import { Float32BufferAttribute } from '../../Three'; function getSplays( survey, segments ) { const stations = survey.stations; const splayLineSegments = survey.getFeature( LEG_SPLAY ); const splays = splayLineSegments.geometry.vertices; var i, j; for ( i = 0; i < splays.length; i += 2 ) { const v1 = splays[ i ]; const v2 = splays[ i + 1 ]; const s1 = stations.getStation( v1 ); const s2 = stations.getStation( v2 ); let linkedSegments; if ( s1 === undefined || s2 === undefined ) continue; if ( v1.connections === 0 ) { linkedSegments = s2.linkedSegments; } else { linkedSegments = s1.linkedSegments; } // console.log( station.name, segments ); for ( j = 0; j < linkedSegments.length; j++ ) { const s = linkedSegments[ j ]; if ( segments[ s ] === undefined ) segments[ s ] = new Set(); segments[ s ].add( v1 ); segments[ s ].add( v2 ); } } } function getWalls( survey, segments ) { const stations = survey.stations; const walls = survey.getFeature( FACE_WALLS ); const centerLines = survey.getFeature( LEG_CAVE ); const lrudVertices = walls.vertices; const centerLineVertices = centerLines.geometry.vertices; // drop vertices after use walls.vertices = null; var i, j, k; for ( i = 0; i < centerLineVertices.length; i++ ) { const vertex = centerLineVertices[ i ]; const station = stations.getStation( vertex ); const lrudInfo = vertex.lrudInfo; if ( lrudInfo === undefined ) continue; let linkedSegments = station.linkedSegments; for ( j = 0; j < linkedSegments.length; j++ ) { const s = linkedSegments[ j ]; if ( segments[ s ] === undefined ) segments[ s ] = new Set(); const start = lrudInfo.start; const end = start + lrudInfo.count; for ( k = start; k < end; k++ ) { segments[ s ].add( lrudVertices[ k ] ); } } } } function buildAlpha ( survey ) { const vertices = []; const indices = []; const segments = []; var points; var tasks = 0; var pending = 0; var i; // allocate splays to segments if ( survey.hasFeature( LEG_SPLAY ) ) getSplays( survey, segments ); if ( survey.hasFeature( FACE_WALLS ) ) getWalls( survey, segments ); survey.dispatchEvent( { type: 'progress', name: 'start' } ); // submit each set of segment points to Worker const workerPool = new WorkerPool( 'alphaWorker.js' ); for ( i = 0; i < segments.length; i++ ) { const segment = segments[ i ]; if ( segment === undefined ) continue; const segmentPointSet = segment; points = []; segmentPointSet.forEach( _addPoints ); pending++; tasks++; workerPool.queueWork( { segment: i, points: points, alpha: 0.08 }, _wallsLoaded ); } const mesh = new Walls(); mesh.ready = false; survey.addFeature( mesh, FACE_ALPHA, 'CV.Survey:faces:alpha' ); return; function _wallsLoaded ( event ) { const cells = event.data.cells; const worker = event.currentTarget; const segment = event.data.segment; const offset = vertices.length / 3; // console.log( 'alpha walls loaded:', segment, cells.length ); workerPool.putWorker( worker ); var i; // populate vertices and indices in order of worker completion const segmentPointSet = segments[ segment ]; segmentPointSet.forEach( _addVertices ); for ( i = 0; i < cells.length; i++ ) { const c = cells[ i ]; indices.push( c[ 0 ] + offset, c[ 1 ] + offset, c[ 2 ] + offset ); } pending--; survey.dispatchEvent( { type: 'progress', name: 'set', progress: 100 * ( tasks - pending ) / tasks } ); if ( pending > 0 ) return; console.log( 'loading complete alpha walls' ); // build geometry const geometry = mesh.geometry; geometry.setIndex( indices ); geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); geometry.computeVertexNormals(); mesh.ready = true; survey.dispatchEvent( { type: 'changed', name: 'changed' } ); survey.dispatchEvent( { type: 'progress', name: 'end' } ); // finished with all workers workerPool.dispose(); } function _addPoints ( point ) { points.push( [ point.x, point.y, point.z ] ); } function _addVertices ( point ) { vertices.push( point.x, point.y, point.z ); } } export { buildAlpha }; // EOF
JavaScript
0
@@ -657,10 +657,10 @@ ned -%7C%7C +&& s2 @@ -714,16 +714,36 @@ s === 0 +%7C%7C s1 === undefined ) %7B%0A%0A%09%09%09 @@ -840,53 +840,8 @@ %09%7D%0A%0A -%09%09// console.log( station.name, segments );%0A%0A %09%09fo
2f1af4046157331738e63de86fd50c724252779b
Make error message more explicit
lib/parseLdapFilter.js
lib/parseLdapFilter.js
const ldap = require("ldapjs"); const parseLdapFilter = function (filterString) { try { const filter = ldap.parseFilter(filterString); return { filter: filter, isValid: true }; } catch (err) { console.log(err.message); return { filter: null, isValid: false }; } }; module.exports = parseLdapFilter;
JavaScript
0.998785
@@ -215,16 +215,60 @@ ole.log( +%60Invalid filter: $%7BfilterString%7D. Reason: $%7B err.mess @@ -270,16 +270,18 @@ .message +%7D%60 );%0A r
8e3a9169739a5b8c5740e1aa12a3aa1f40cd8729
Fix assertions
lib/node_modules/@stdlib/math/base/complex/ceiln/benchmark/benchmark.js
lib/node_modules/@stdlib/math/base/complex/ceiln/benchmark/benchmark.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var bench = require( '@stdlib/bench' ); var randu = require( '@stdlib/random/base/randu' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var ceiln = require( '@stdlib/math/base/special/ceiln' ); var pkg = require( './../package.json' ).name; var cceiln = require( './../lib' ); // MAIN // bench( pkg, function benchmark( b ) { var re; var im; var y; var i; b.tic(); for ( i = 0; i < b.iterations; i++ ) { re = ( randu()*1000.0 ) - 500.0; im = ( randu()*1000.0 ) - 500.0; y = cceiln( re, im, -2 ); if ( y.length === 0 ) { b.fail( 'should not be empty' ); } } b.toc(); if ( isnan( y ) ) { b.fail( 'should not return NaN' ); } b.pass( 'benchmark finished' ); b.end(); }); bench( pkg+'::memory_reuse', function benchmark( b ) { var out; var re; var im; var y; var i; out = new Array( 2 ); b.tic(); for ( i = 0; i < b.iterations; i++ ) { re = ( randu()*1000.0 ) - 500.0; im = ( randu()*1000.0 ) - 500.0; y = cceiln( out, re, im, -2 ); if ( y.length === 0 ) { b.fail( 'should not be empty' ); } } b.toc(); if ( isnan( y ) ) { b.fail( 'should not return NaN' ); } b.pass( 'benchmark finished' ); b.end(); }); bench( pkg+'::manual', function benchmark( b ) { var re; var im; var y; var i; b.tic(); for ( i = 0; i < b.iterations; i++ ) { re = ( randu()*1000.0 ) - 500.0; im = ( randu()*1000.0 ) - 500.0; y = [ ceiln( re, -2 ), ceiln( im, -2 ) ]; if ( y.length === 0 ) { b.fail( 'should not be empty' ); } } b.toc(); if ( isnan( y ) ) { b.fail( 'should not return NaN' ); } b.pass( 'benchmark finished' ); b.end(); }); bench( pkg+'::manual,memory_reuse', function benchmark( b ) { var re; var im; var y; var i; y = new Array( 2 ); b.tic(); for ( i = 0; i < b.iterations; i++ ) { re = ( randu()*1000.0 ) - 500.0; im = ( randu()*1000.0 ) - 500.0; y[ 0 ] = ceiln( re, -2 ); y[ 1 ] = ceiln( im, -2 ); if ( y.length === 0 ) { b.fail( 'should not be empty' ); } } b.toc(); if ( isnan( y ) ) { b.fail( 'should not return NaN' ); } b.pass( 'benchmark finished' ); b.end(); });
JavaScript
0.000102
@@ -739,19 +739,21 @@ ;%0Avar is -nan +Array = requi @@ -765,26 +765,16 @@ @stdlib/ -math/base/ assert/i @@ -775,19 +775,21 @@ sert/is- -nan +array ' );%0Avar @@ -1238,37 +1238,40 @@ %09b.toc();%0A%09if ( +! is -nan +Array ( y ) ) %7B%0A%09%09b.fa @@ -1278,38 +1278,39 @@ il( 'should -not return -NaN +an array ' );%0A%09%7D%0A%09b.p @@ -1707,37 +1707,40 @@ %09b.toc();%0A%09if ( +! is -nan +Array ( y ) ) %7B%0A%09%09b.fa @@ -1747,38 +1747,39 @@ il( 'should -not return -NaN +an array ' );%0A%09%7D%0A%09b.p @@ -2147,37 +2147,40 @@ %09b.toc();%0A%09if ( +! is -nan +Array ( y ) ) %7B%0A%09%09b.fa @@ -2187,38 +2187,39 @@ il( 'should -not return -NaN +an array ' );%0A%09%7D%0A%09b.p @@ -2646,13 +2646,16 @@ f ( +! is -nan +Array ( y @@ -2682,22 +2682,23 @@ uld -not return -NaN +an array ' );
c679a9e75c9405ba5bf037489804d175f16631b9
Rename variable
lib/node_modules/@stdlib/math/fast/special/int32-log2/examples/index.js
lib/node_modules/@stdlib/math/fast/special/int32-log2/examples/index.js
'use strict'; var llog2 = require( './../lib' ); var v; var i; for ( i = 1; i < 101; i++ ) { v = llog2( i ); console.log( 'llog2(%d) ≈ %d', i, v ); }
JavaScript
0.000003
@@ -12,21 +12,22 @@ ';%0A%0Avar -l log2 +ul = requi @@ -99,17 +99,24 @@ v = -l log2 +ul ( i +%3E%3E%3E 0 );%0A%09 @@ -129,17 +129,16 @@ e.log( ' -l log2(%25d)
be5c20c690ff03322f31d1e84028a30975245fc7
Fix DeferredWrapper utility module used for async store testing
test/data/DeferredWrapper.js
test/data/DeferredWrapper.js
define(["dojo/_base/lang", "dojo/_base/Deferred"],function(lang, Deferred){ // summary: // Creates a store that wraps the delegate store's query results and total in Deferred // instances. If delay is set, the Deferreds will be resolved asynchronously after delay +/-50% // milliseconds to simulate network requests that may come back out of order. return function(store, delay){ return lang.delegate(store, { fetch: function(){ if(!this.data || !this.data.then){ var results = store.fetch.call(this); var resultsDeferred = this.data = new Deferred(); var totalDeferred = this.total = new Deferred(); var resolveTotal = function(){ totalDeferred.resolve(results.length); }; var resolveResults = function(){ resultsDeferred.resolve(results); }; if(delay){ setTimeout(resolveTotal, delay * (Math.random() + 0.5)); setTimeout(resolveResults, delay * (Math.random() + 0.5)); } else{ resolveTotal(); resolveResults(); } } return this.data; } }); }; });
JavaScript
0
@@ -365,16 +365,17 @@ function + (store, @@ -376,24 +376,25 @@ tore, delay) + %7B%0A%09%09return l @@ -437,18 +437,20 @@ tion + () + %7B%0A%09%09%09%09if (!th @@ -445,16 +445,17 @@ %7B%0A%09%09%09%09if + (!this.d @@ -481,29 +481,16 @@ hen) + %7B%0A%09%09%09%09%09 -var results = stor @@ -506,24 +506,93 @@ all(this);%0A%0A +%09%09%09%09%09var actualData = this.data;%0A%09%09%09%09%09var actualTotal = this.total;%0A%0A %09%09%09%09%09var res @@ -713,34 +713,36 @@ Total = function + () + %7B%0A%09%09%09%09%09%09totalDef @@ -759,22 +759,19 @@ lve( -results.length +actualTotal );%0A%09 @@ -777,16 +777,17 @@ %09%09%09%09%09%7D;%0A +%0A %09%09%09%09%09var @@ -812,18 +812,20 @@ function + () + %7B%0A%09%09%09%09%09%09 @@ -848,23 +848,26 @@ resolve( -results +actualData );%0A%09%09%09%09%09 @@ -881,15 +881,17 @@ %09%09if + (delay) + %7B%0A%09%09 @@ -1026,18 +1026,14 @@ %09%09%09%7D -%0A%09%09%09%09%09 + else + %7B%0A%09%09
af3f21f5a8fbec882f52b87b6444eb649f15fd1c
Remove margin around highlighted search match
lib/preview-element.js
lib/preview-element.js
/* @flow */ const LINE_BREAKS_REGEX = /(?:\r\n|\r|\n)/g export default document.registerElement('textual-velocity-preview', { prototype: Object.assign(Object.create(HTMLElement.prototype), { updatePreview (path: string, content: string, searchRegex?: RegExp) { this._path = path if (searchRegex) { const globalRegex = new RegExp(searchRegex, 'gi') content = content.replace(globalRegex, match => `<span class="inline-block highlight-success">${match}</span>`) } this.innerHTML = content.replace(LINE_BREAKS_REGEX, '<br />') }, attachedCallback () { this._clickListener = () => { if (this._path) { atom.workspace.open(this._path) } } this.addEventListener('click', this._clickListener) }, detachedCallback () { this.removeEventListener('click', this._clickListener) }, clear () { this._path = null this.innerHTML = '' }, getTitle () { return 'Preview (Textual Velocity)' }, getLongTitle () { return this.getTitle() }, getPath () { return this._path }, scrollToFirstHighlightedItem () { const el = this.querySelector('span') if (el) { el.scrollIntoViewIfNeeded() } }, dispose () { this.remove() } }) })
JavaScript
0
@@ -445,21 +445,8 @@ ss=%22 -inline-block high
b914d7ec327907ced15be879293bb6d4efebfd66
Fix last linter error
lib/preview-element.js
lib/preview-element.js
/* @flow */ const LINE_BREAKS_REGEX = /(?:\r\n|\r|\n)/g export default document.registerElement('textual-velocity-preview', { prototype: Object.assign(Object.create(HTMLElement.prototype), { attachedCallback () {}, attributeChangedCallback () {}, createdCallback () {}, detachedCallback () {}, updatePreview (path: string, content: string, searchRegex?: RegExp) { this._path = path if (typeof content === 'string') { // on update check for @copy syntax and copy to the clipboard var copyArray=content.match(/@copy\(([\S\s]*)\)/) if (copyArray != null) { atom.clipboard.write(copyArray[1]) // console.log('copied to clipboard: '+copyArray[1]); } // else {console.log('nothing to copy');} if (searchRegex) { const globalRegex = new RegExp(searchRegex, 'gi') content = content.replace(globalRegex, match => `<span class="highlight-success">${match}</span>`) } this.innerHTML = content.replace(LINE_BREAKS_REGEX, '<br />') } }, getTitle () { return 'Preview (Textual Velocity)' }, getLongTitle () { return this.getTitle() }, getPath () { return this._path }, scrollToFirstHighlightedItem () { const el = this.querySelector('span') if (el) { el.scrollIntoViewIfNeeded() } }, dispose () { this.remove() } }) })
JavaScript
0.000012
@@ -540,17 +540,19 @@ opyArray -= + = content.
a77ca1dc69408be83e80c1bed7fe7cfedb0b7b69
Add test for Fastify POST
test/fastify/fastify-test.js
test/fastify/fastify-test.js
const fastify = require('fastify'); const chai = require('chai'), expect = chai.expect, chaiSinon = require('sinon-chai'); chai.use(chaiSinon); const inputValidation = require('../../src/middleware'); describe('fastify plugin', () => { let app; before(() => { inputValidation.init('test/pet-store-swagger.yaml', { framework: 'fastify' }); }); beforeEach(async () => { app = fastify({ logger: true }); app.register(inputValidation.validate()); app.setErrorHandler(async (err, req, reply) => { if (err instanceof inputValidation.InputValidationError) { return reply.status(400).send({ more_info: JSON.stringify(err.errors) }); } reply.status(500); reply.send(); }); app.get('/pets', (req, reply) => { reply.status(204).send(); }); await app.ready(); }); afterEach(() => { return app.close(); }); it('Accepts simple GET', async () => { const response = await app.inject() .headers({ 'api-version': '1.0' }) .query({ page: 1 }) .get('/pets'); expect(response.statusCode).to.equal(204); expect(response.body).to.eql(''); }); it('Returns an error on invalid GET request with multiple errors', async () => { const response = await app.inject().get('/pets'); expect(response.statusCode).to.equal(400); expect(response.json()).to.eql({ more_info: "[{\"keyword\":\"required\",\"dataPath\":\".headers\",\"schemaPath\":\"#/properties/headers/required\",\"params\":{\"missingProperty\":\"api-version\"},\"message\":\"should have required property 'api-version'\"},{\"keyword\":\"required\",\"dataPath\":\".query\",\"schemaPath\":\"#/properties/query/required\",\"params\":{\"missingProperty\":\"page\"},\"message\":\"should have required property 'page'\"}]" }); }); it('Returns an error on invalid GET request with single error', async () => { const response = await app.inject() .headers({ 'api-version': '1.0' }) .get('/pets'); expect(response.statusCode).to.equal(400); expect(response.json()).to.eql({ more_info: "[{\"keyword\":\"required\",\"dataPath\":\".query\",\"schemaPath\":\"#/properties/query/required\",\"params\":{\"missingProperty\":\"page\"},\"message\":\"should have required property 'page'\"}]" }); }); it('Correctly matches endpoint with query params', async () => { const response = await app.inject() .headers({ 'api-version': '1.0' }) .query({ dummy: 1 }) .get('/pets'); expect(response.statusCode).to.equal(400); expect(response.json()).to.eql({ more_info: "[{\"keyword\":\"additionalProperties\",\"dataPath\":\".query\",\"schemaPath\":\"#/properties/query/additionalProperties\",\"params\":{\"additionalProperty\":\"dummy\"},\"message\":\"should NOT have additional properties\"},{\"keyword\":\"required\",\"dataPath\":\".query\",\"schemaPath\":\"#/properties/query/required\",\"params\":{\"missingProperty\":\"page\"},\"message\":\"should have required property 'page'\"}]" }); }); });
JavaScript
0
@@ -896,32 +896,127 @@ );%0A %7D);%0A%0A + app.post('/pets', (req, reply) =%3E %7B%0A reply.status(201).send();%0A %7D);%0A%0A await ap @@ -3522,13 +3522,1034 @@ %0A %7D); +%0A%0A it('Accepts a valid POST request', async () =%3E %7B%0A const response = await app.inject(%7B%0A headers: %7B%0A // %22api-version%22: %221.0%22,%0A // %22request-id%22: 10,%0A // %22content-type%22: %22application/json%22,%0A %7D,%0A payload: %7B%0A name: 'A new pet',%0A test: %7B field1: 'enum1' %7D%0A %7D,%0A method: 'POST',%0A url: '/pets'%0A %7D);%0A expect(response.statusCode).to.equal(201);%0A %7D);%0A%0A it('Returns an error on invalid POST request with error', async () =%3E %7B%0A const response = await app.inject(%7B%0A headers: %7B%0A 'api-version': '1.0',%0A 'request-id': 10%0A // %22content-type%22: %22application/json%22,%0A %7D,%0A payload: %7B%0A name: 'A new pet',%0A test: 'field1'%0A %7D,%0A method: 'POST',%0A url: '/pets'%0A %7D);%0A expect(response.statusCode).to.equal(400);%0A %7D); %0A%7D);%0A
226751cd7ed9aa0e601f6dfd59bcd997153dcba9
Make getFilePath private.
lib/resource-mapper.js
lib/resource-mapper.js
const fs = require('fs') const URL = require('url') const { promisify } = require('util') const { types, extensions } = require('mime-types') const readdir = promisify(fs.readdir) const HTTPError = require('./http-error') // A ResourceMapper maintains the mapping between HTTP URLs and server filenames, // following the principles of the “sweet spot” discussed in // https://www.w3.org/DesignIssues/HTTPFilenameMapping.html class ResourceMapper { constructor ({ rootUrl, rootPath, includeHost = false, defaultContentType = 'application/octet-stream', indexFilename = 'index.html', overrideTypes = { acl: 'text/turtle', meta: 'text/turtle' }, fileSuffixes = ['.acl', '.meta'] }) { this._rootUrl = this._removeTrailingSlash(rootUrl) this._rootPath = this._removeTrailingSlash(rootPath) this._includeHost = includeHost this._readdir = readdir this._defaultContentType = defaultContentType this._types = { ...types, ...overrideTypes } this._indexFilename = indexFilename this._indexContentType = this._getContentTypeByExtension(indexFilename) this._isControlFile = new RegExp(`(?:${fileSuffixes.map(fs => fs.replace('.', '\\.')).join('|')})$`) // If the host needs to be replaced on every call, pre-split the root URL if (includeHost) { const { protocol, port, pathname } = URL.parse(rootUrl) this._protocol = protocol this._port = port === null ? '' : `:${port}` this._rootUrl = this._removeTrailingSlash(pathname) } } get rootPath () { return this._rootPath } // Maps the request for a given resource and representation format to a server file // When searchIndex is true and the URL ends with a '/', and contentType includes 'text/html' indexFilename will be matched. async mapUrlToFile ({ url, contentType, createIfNotExists, searchIndex = true }) { let fullFilePath = this.getFilePath(url) let isIndex = searchIndex && fullFilePath.endsWith('/') let path // Append index filename if the URL ends with a '/' if (isIndex) { if (createIfNotExists && contentType !== this._indexContentType) { throw new Error(`Index file needs to have ${this._indexContentType} as content type`) } if (contentType && contentType.includes(this._indexContentType)) { fullFilePath += this._indexFilename } } // Create the path for a new file if (createIfNotExists) { path = fullFilePath // If the extension is not correct for the content type, append the correct extension if (searchIndex && this._getContentTypeByExtension(path) !== contentType) { path += `$${contentType in extensions ? `.${extensions[contentType][0]}` : '.unknown'}` } // Determine the path of an existing file } else { // Read all files in the corresponding folder const filename = fullFilePath.substr(fullFilePath.lastIndexOf('/') + 1) const folder = fullFilePath.substr(0, fullFilePath.length - filename.length) // Find a file with the same name (minus the dollar extension) let match = searchIndex ? await this._getMatchingFile(folder, filename, isIndex, contentType) : '' if (match === undefined) { // Error if no match was found, // unless the URL ends with a '/', // in that case we fallback to the folder itself. if (isIndex) { match = '' } else { throw new HTTPError(404, `File not found: ${fullFilePath}`) } } path = `${folder}${match}` contentType = this._getContentTypeByExtension(match) } return { path, contentType: contentType || this._defaultContentType } } async _getMatchingFile (folder, filename, isIndex, contentType) { const files = await this._readdir(folder) // Search for files with the same name (disregarding a dollar extension) if (!isIndex) { return files.find(f => this._removeDollarExtension(f) === filename) // Check if the index file exists } else if (files.includes(this._indexFilename) && contentType && contentType.includes(this._indexContentType)) { return this._indexFilename } } async getRepresentationUrlForResource (resourceUrl) { let fullFilePath = this.getFilePath(resourceUrl) let isIndex = fullFilePath.endsWith('/') // Append index filename if the URL ends with a '/' if (isIndex) { fullFilePath += this._indexFilename } // Read all files in the corresponding folder const filename = fullFilePath.substr(fullFilePath.lastIndexOf('/') + 1) const folder = fullFilePath.substr(0, fullFilePath.length - filename.length) const files = await this._readdir(folder) // Find a file with the same name (minus the dollar extension) let match = (files.find(f => this._removeDollarExtension(f) === filename || (isIndex && f.startsWith(this._indexFilename + '.')))) return `${resourceUrl}${match || ''}` } // Maps a given server file to a URL async mapFileToUrl ({ path, hostname }) { // Determine the URL by chopping off everything after the dollar sign let pathname = this._removeDollarExtension(path.substring(this._rootPath.length)) pathname = this._replaceBackslashes(pathname) const url = `${this.resolveUrl(hostname)}${encodeURI(pathname)}` return { url, contentType: this._getContentTypeByExtension(path) } } // Gets the base file path for the given hostname getBasePath (hostname) { return !this._includeHost ? this._rootPath : `${this._rootPath}/${hostname}` } // Returns the URL for the given HTTP request getRequestUrl (req) { const { hostname, pathname } = this._parseUrl(req) return this.resolveUrl(hostname, pathname) } // Returns the URL for the relative path on the pod resolveUrl (hostname, pathname = '') { return !this._includeHost ? `${this._rootUrl}${pathname}` : `${this._protocol}//${hostname}${this._port}${this._rootUrl}${pathname}` } // Determine the full file path corresponding to a URL getFilePath (url) { const { pathname, hostname } = this._parseUrl(url) const fullFilePath = decodeURIComponent(`${this.getBasePath(hostname)}${pathname}`) if (fullFilePath.indexOf('/..') >= 0) { throw new Error('Disallowed /.. segment in URL') } return fullFilePath } // Parses a URL into a hostname and pathname _parseUrl (url) { // URL specified as string if (typeof url === 'string') { return URL.parse(url) } // URL specified as Express request object if (!url.pathname && url.path) { const { hostname, path } = url return { hostname, pathname: path.replace(/[?#].*/, '') } } // URL specified as object return url } // Gets the expected content type based on the extension of the path _getContentTypeByExtension (path) { const extension = /\.([^/.]+)$/.exec(path) return extension && this._types[extension[1].toLowerCase()] || this._defaultContentType } // Removes a possible trailing slash from a path _removeTrailingSlash (path) { const lastPos = path.length - 1 return lastPos < 0 || path[lastPos] !== '/' ? path : path.substr(0, lastPos) } // Removes everything beyond the dollar sign from a path _removeDollarExtension (path) { const dollarPos = path.lastIndexOf('$') return dollarPos < 0 ? path : path.substr(0, dollarPos) } _replaceBackslashes (path) { return path.replace(/\\/g, '/') } } module.exports = ResourceMapper
JavaScript
0
@@ -1888,32 +1888,33 @@ FilePath = this. +_ getFilePath(url) @@ -4256,16 +4256,17 @@ = this. +_ getFileP @@ -6039,16 +6039,17 @@ a URL%0A +_ getFileP
14b93b2550c4cb82bdefc97fc9381b54e050d4cd
update default lang value while format
lib/rules/html-lang.js
lib/rules/html-lang.js
/** * @file rule: html-lang * @author nighca<nighca@live.cn> */ module.exports = { name: 'html-lang', desc: 'Attribute "lang" of <html> recommended to be set.', lint: function (enable, document, reporter) { if (!enable) { return; } var html = document.querySelector('html'); if (!html) { return; } if (!html.getAttribute('lang')) { reporter.warn(html, '010', 'Attribute "lang" of <html> recommended to be set.'); } }, format: function (enable, document, options) { if (!enable) { return; } var html = document.querySelector('html'); if (!html) { return; } if (!html.getAttribute('lang')) { html.setAttribute('lang', 'zh-CN'); } } };
JavaScript
0
@@ -774,32 +774,91 @@ bute('lang')) %7B%0A + // %E9%BB%98%E8%AE%A4%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87 ( http://tools.ietf.org/html/bcp47 )%0A html @@ -887,10 +887,16 @@ 'zh- -CN +cmn-Hans ');%0A
1699b735afe14bef74d32853f623c1fb728000e8
fix path to configure file
src/helpers/resolveEndpoint.js
src/helpers/resolveEndpoint.js
import { config } from './configure' const resolveEndpoint = (endpoint) => { if (!config.baseURL || /^http|^\//.test(endpoint)) { return endpoint } else { return config.baseURL + endpoint } } export default resolveEndpoint
JavaScript
0
@@ -18,16 +18,17 @@ from '. +. /configu
9f1be88529680baa48a3bc2d46c0b5ba411bd1df
add policy subsystem
lib/rules/subsystem.js
lib/rules/subsystem.js
'use strict' const id = 'subsystem' const validSubsystems = [ 'benchmark' , 'build' , 'bootstrap' , 'deps' , 'doc' , 'errors' , 'etw' , 'esm' , 'inspector' , 'lib' , 'loader' , 'meta' , 'msi' , 'node' , 'n-api' , 'perfctr' , 'src' , 'test' , 'tools' , 'win' // core libs , 'assert' , 'async_hooks' , 'buffer' , 'child_process' , 'cluster' , 'console' , 'constants' , 'crypto' , 'debugger' , 'dgram' , 'dns' , 'domain' , 'events' , 'fs' , 'http' , 'http2' , 'https' , 'inspector' , 'module' , 'net' , 'os' , 'path' , 'perf_hooks' , 'process' , 'punycode' , 'querystring' , 'readline' , 'repl' , 'stream' , 'string_decoder' , 'sys' , 'timers' , 'tls' , 'trace_events' , 'tty' , 'url' , 'util' , 'v8' , 'vm' , 'worker' , 'zlib' ] module.exports = { id: id , meta: { description: 'enforce subsystem validity' , recommended: true } , defaults: { subsystems: validSubsystems } , options: { subsystems: validSubsystems } , validate: (context, rule) => { const subs = rule.options.subsystems const parsed = context.toJSON() if (!parsed.subsystems.length) { if (!parsed.release && !parsed.working) { // Missing subsystem context.report({ id: id , message: 'Missing subsystem.' , string: parsed.title , line: 0 , column: 0 , level: 'fail' , wanted: subs }) } else { context.report({ id: id , message: 'Release commits do not have subsystems' , string: '' , level: 'skip' }) } } else { var failed = false for (const sub of parsed.subsystems) { if (!~subs.indexOf(sub)) { failed = true // invalid subsystem const column = parsed.title.indexOf(sub) context.report({ id: id , message: `Invalid subsystem: "${sub}"` , string: parsed.title , line: 0 , column: column , level: 'fail' , wanted: subs }) } } if (!failed) { context.report({ id: id , message: 'valid subsystems' , string: parsed.subsystems.join(',') , level: 'pass' }) } } } }
JavaScript
0.000001
@@ -220,16 +220,27 @@ erfctr'%0A +, 'policy'%0A , 'src'%0A
8d5814131c62e395d039a20a750349e2f901ea83
trim whitespaces for local datatips (line)
lib/runtime/datatip.js
lib/runtime/datatip.js
/** @babel */ /** * @FIXME? * Use `component` property instaed of `markedStrings` and reuse exisiting our full-featured * components in ../ui/views.coffee. * Code in https://github.com/TypeStrong/atom-typescript/blob/master/dist/main/atom-ide/datatipProvider.js * can be helpful. */ import { client } from '../connection' import modules from './modules' import { isValidScopeToInspect } from '../misc/scopes' import { getWord, isValidWordToInspect } from '../misc/words' import { getLocalContext } from '../misc/blocks' const datatip = client.import('datatip') const grammar = atom.grammars.grammarForScopeName('source.julia') class DatatipProvider { providerName = 'julia-client-datatip-provider' priority = 100 grammarScopes = atom.config.get('julia-client.juliaSyntaxScopes') useAtomIDEUI = false async datatip(editor, bufferPosition) { // If Julia is not running, do nothing if (!client.isActive()) return // If the scope at `bufferPosition` is not valid code scope, do nothing if (!isValidScopeToInspect(editor, bufferPosition)) return // Check the validity of code to be inspected const { range, word } = getWord(editor, bufferPosition) if (!isValidWordToInspect(word)) return const { main, sub } = await modules.getEditorModule(editor, bufferPosition) const mod = main ? (sub ? `${main}.${sub}` : main) : 'Main' const { column, row } = bufferPosition const { context, startRow } = getLocalContext(editor, row) try { const result = await datatip({ word, mod, path: editor.getPath(), column: column + 1, row: row + 1, startRow, context }) if (result.error) return if (this.useAtomIDEUI) { if (result.line) { return { range, markedStrings: [{ type: 'snippet', value: editor.lineTextForBufferRow(result.line), grammar }] } } else if (result.strings) { return { range, markedStrings: result.strings.map(string => { return { type: string.type, value: string.value, grammar: string.type === 'snippet' ? grammar : null } }) } } } else { if (result.line) { return { range, markedStrings: [{ type: 'snippet', value: editor.lineTextForBufferRow(result.line), grammar }] } } else if (result.strings) { // @NOTE: atom-ide-datatip can't render multiple `snippet`s in `markedStrings` correctly return { range, markedStrings: result.strings.map(string => { return { type: 'markdown', value: string.type === 'snippet' ? `\`\`\`julia\n${string.value}\n\`\`\`` : string.value, grammar: string.type === 'snippet' ? grammar : null } }) } } } } catch (error) { return } } } export default new DatatipProvider()
JavaScript
0
@@ -1764,32 +1764,104 @@ (result.line) %7B%0A + const value = editor.lineTextForBufferRow(result.line).trim()%0A return @@ -1966,50 +1966,8 @@ alue -: editor.lineTextForBufferRow(result.line) ,%0A @@ -2396,32 +2396,104 @@ (result.line) %7B%0A + const value = editor.lineTextForBufferRow(result.line).trim()%0A return @@ -2598,50 +2598,8 @@ alue -: editor.lineTextForBufferRow(result.line) ,%0A
e824debad946f13374ea749a708acb5c64c49d88
Fix furball test
test/integration/composer.js
test/integration/composer.js
// Load modules var Chai = require('chai'); var Hapi = require('../..'); // Declare internals var internals = {}; // Test shortcuts var expect = Chai.expect; describe('Composer', function () { it('composes pack', function (done) { var options = { servers: { ren: { port: 0, labels: ['api', 'nasty'], config: { cache: 'memory' } }, stimpy: { host: 'localhost', port: 0, labels: ['api', 'nice'] } }, plugins: { furball: { version: false, plugins: '/' } }, permissions: { ext: true } }; var composer = new Hapi.Composer(options); composer.compose(function (err) { expect(err).to.not.exist; composer.start(function (err) { expect(err).to.not.exist; composer.stop(); composer.packs[0].servers[0].inject({ method: 'GET', url: '/' }, function (res) { expect(res.result).to.deep.equal([{ "name": "furball", "version": "0.1.0" }]); done(); }); }); }); }); });
JavaScript
0.000006
@@ -1347,67 +1347,36 @@ sult -).to.deep.equal(%5B%7B %22name%22: %22furball%22, %22version%22: %220.1.0%22 %7D%5D +%5B0%5D.name).to.equal('furball' );%0D%0A
1221dacb8e9b4a576414def6ca17e8bf4fe1f7ba
use query.sql more consequently
lib/sequelize/query.js
lib/sequelize/query.js
var Utils = require("./utils") var Query = module.exports = function(databaseConfig, callee, options) { this.config = databaseConfig this.callee = callee this.options = options || {} } Utils.addEventEmitter(Query) Query.prototype.run = function(query) { var self = this var client = new (require("mysql").Client)({ user: this.config.username, password: this.config.password, host: this.config.host, port: this.config.port, database: this.config.database }) // Save the query text for testing and debugging. this.sql = query if(this.options.logging) console.log('Executing: ' + query) client.connect() client.query(query, function(err, results, fields) { err ? self.onFailure(err) : self.onSuccess(query, results, fields) }) client.on('error', function(err) { self.onFailure(err) }) client.end() return this } Query.prototype.onSuccess = function(query, results, fields) { var result = this.callee , self = this // add the inserted row id to the instance if (this.callee && !this.callee.options.hasPrimaryKeys && (query.indexOf('INSERT INTO') == 0) && (results.hasOwnProperty('insertId'))) this.callee.id = results.insertId // transform results into real model instances // return the first real model instance if options.plain is set (e.g. Model.find) if (query.indexOf('SELECT') == 0) { result = results.map(function(result) { return self.callee.build(result, {isNewRecord: false}) }) if(this.options.plain) result = (result.length == 0) ? null : result[0] } this.emit('success', result) } Query.prototype.onFailure = function(err) { this.emit('failure', err, this.callee) }
JavaScript
0
@@ -486,61 +486,8 @@ %7D) -%0A%0A // Save the query text for testing and debugging. %0A t @@ -562,21 +562,24 @@ ng: ' + -query +this.sql )%0A%0A cli @@ -607,21 +607,24 @@ t.query( -query +this.sql , functi @@ -697,21 +697,24 @@ Success( -query +self.sql , result
9c8c89ef8aaee49e7f0d2b454c4e5a5d3ad7bc35
add auth check to settings
src/javascript/app_2/routes.js
src/javascript/app_2/routes.js
import React from 'react'; import { Route, NavLink } from 'react-router-dom'; import PropTypes from 'prop-types'; import Client from '../_common/base/client_base'; import { redirectToLogin } from '../_common/base/login'; import { localize } from '../_common/localize'; import Portfolio from './pages/portfolio/portfolio.jsx'; import TradeApp from './pages/trading/trade_app.jsx'; import Settings from './pages/settings/settings.jsx'; import Statement from './pages/statement/statement.jsx'; // Settings Routes import AccountPassword from './pages/settings/sections/account_password.jsx'; import ApiToken from './pages/settings/sections/api_token.jsx'; import AuthorizedApplications from './pages/settings/sections/authorized_applications.jsx'; import CashierPassword from './pages/settings/sections/cashier_password.jsx'; import FinancialAssessment from './pages/settings/sections/financial_assessment.jsx'; import Limits from './pages/settings/sections/limits.jsx'; import LoginHistory from './pages/settings/sections/login_history.jsx'; import PersonalDetails from './pages/settings/sections/personal_details.jsx'; import SelfExclusion from './pages/settings/sections/self_exclusion.jsx'; const routes = [ { path: '/', component: TradeApp, exact: true }, { path: '/portfolio', component: Portfolio, is_authenticated: true }, { path: '/statement', component: Statement, is_authenticated: true }, { path : '/settings', component: Settings, routes : [ { path: 'personal', component: PersonalDetails }, { path: 'financial', component: FinancialAssessment }, { path: 'account_password', component: AccountPassword }, { path: 'cashier_password', component: CashierPassword }, { path: 'exclusion', component: SelfExclusion }, { path: 'limits', component: Limits }, { path: 'history', component: LoginHistory }, { path: 'token', component: ApiToken }, { path: 'apps', component: AuthorizedApplications }, ], }, ]; const RouteWithSubRoutes = route => ( <Route exact={route.exact} path={route.path} render={props => ( (route.is_authenticated && !Client.isLoggedIn()) ? // TODO: update styling of the message below <a href='javascript:;' onClick={redirectToLogin}>{localize('Please login to view this page.')}</a> : <route.component {...props} routes={route.routes} /> )} /> ); export const BinaryRoutes = () => routes.map((route, idx) => ( <RouteWithSubRoutes key={idx} {...route} /> )); const normalizePath = (path) => /^\//.test(path) ? path : `/${path || ''}`; // Default to '/' const getRouteInfo = (path) => routes.find(r => r.path === normalizePath(path)); export const isRouteVisible = (path, route = getRouteInfo(path)) => !(route && route.is_authenticated && !Client.isLoggedIn()); export const BinaryLink = ({ to, children, ...props }) => { const path = normalizePath(to); const route = getRouteInfo(path); if (!route) { throw new Error(`Route not found: ${to}`); } return ( to ? <NavLink to={path} activeClassName='active' exact={route.exact} {...props}> {children} </NavLink> : <a href='javascript:;' {...props}> {children} </a> ); }; BinaryLink.propTypes = { children: PropTypes.object, to : PropTypes.string, };
JavaScript
0.000001
@@ -1642,16 +1642,48 @@ ttings,%0A + is_authenticated: true,%0A
014624a0f5d8e3844536bab4dc626d202a892858
Handle ENOENT errors in codemod
src/codemod-repo.js
src/codemod-repo.js
import fs from 'fs'; import Promise from 'promise'; import github from 'github-basic'; import gethub from 'gethub'; import rimraf from 'rimraf'; import lsr from 'lsr'; import throat from 'throat'; import {pushError} from './db'; const client = github({version: 3, auth: process.env.GITHUB_BOT_TOKEN}); const readFile = Promise.denodeify(fs.readFile); const rm = Promise.denodeify(rimraf); const directory = __dirname + '/../temp'; // TODO: client.exists doesn't work because http-basic does not work with head requests that also support gzip client.exists = function (owner, repo) { return this.get('/repos/:owner/:repo', {owner, repo}).then( () => true, () => false, ); }; const blackList = ['qdot/gecko-hg']; function codemodRepo(fullName) { if (blackList.includes(fullName)) { return Promise.resolve(null); } const [owner, name] = fullName.split('/'); return client.exists('npmcdn-to-unpkg-bot', name).then(exists => { if (exists) { return; } console.log('Code modding ' + fullName); return rm(directory).then(() => { console.log('downloading ' + fullName); return gethub(owner, name, 'master', directory); }).then(() => { console.log('fetched ' + fullName); return lsr(directory); }).then(entries => { return Promise.all(entries.map(entry => { if (entry.isFile()) { return readFile(entry.fullPath, 'utf8').then(content => { const newContent = content.replace(/\bnpmcdn\b/g, 'unpkg'); if (newContent !== content) { return { path: entry.path.substr(2), // remove the `./` that entry paths start with content: newContent, }; } }); } })); }).then(updates => { updates = updates.filter(Boolean); if (updates.length === 0) { console.log('codemod resulted in no changes'); return; } console.log('forking ' + fullName); return client.fork(owner, name).then(() => { return new Promise(resolve => setTimeout(resolve, 10000)); }).then(() => { console.log('branching ' + fullName); return client.branch('npmcdn-to-unpkg-bot', name, 'master', 'npmcdn-to-unpkg'); }).then(() => { console.log('committing ' + fullName); return client.commit('npmcdn-to-unpkg-bot', name, { branch: 'npmcdn-to-unpkg', message: 'Replace npmcdn.com with unpkg.com', updates, }); }).then(() => { console.log('submitting pull request ' + fullName); return client.pull( {user: 'npmcdn-to-unpkg-bot', repo: name, branch: 'npmcdn-to-unpkg'}, {user: owner, repo: name}, { title: 'Replace npmcdn.com with unpkg.com', body: ( 'To avoid potential naming conflicts with npm, npmcdn.com is being renamed to unpkg.com. This is an ' + 'automated pull request to update your project to use the new domain.' ), }, ); }).then(() => { console.log('codemod complete'); }); }); }).then(null, err => { console.error('Error processing ' + fullName); console.error(err.stack); return pushError(owner, name, err.message || err); }); } // only allow codemodding one repo at a time export default throat(Promise)(1, codemodRepo);
JavaScript
0
@@ -1720,24 +1720,146 @@ %7D%0A + %7D, err =%3E %7B%0A if (err.code === 'ENOENT') %7B%0A return;%0A %7D%0A throw err;%0A %7D)
e9f4a7825bc0a61d7d094b5a85c8c354bd10384f
Update storage.js
lib/storage/storage.js
lib/storage/storage.js
/* * slack-bot * https://github.com/usubram/slack-bot * * Copyright (c) 2016 Umashankar Subramanian * Licensed under the MIT license. */ 'use strict'; const fs = require('fs'); const _ = require('lodash'); const path = require('path'); const root = '..'; const botLogger = require(path.join(root, 'utils/logger')); const internals = { STORAGE_DIRECTORY: path.join(process.cwd(), 'data'), EVENT_FILE_PATH: '' }; internals.EVENT_FILE_PATH = path.join(internals.STORAGE_DIRECTORY, 'events.json'); exports = module.exports.createEventDirectory = function () { fs.mkdir(internals.STORAGE_DIRECTORY, function (e) { if (!e || (e && e.code === 'EEXIST')) { botLogger.logger.debug('storage: directory already exist'); } else { botLogger.logger.error('storage: unable create storage for ' + 'persitance, check if you write permission'); } }); }; exports = module.exports.updateEvents = function (botName, eventType, data) { return Promise.resolve(internals.readFile(eventType)) .then((eventsData) => { if (data && data.parsedMessage && data.channels) { eventsData = eventsData ? eventsData : {}; eventsData[botName] = eventsData[botName] ? eventsData[botName] : {}; _.forEach(data.channels, function (channel) { eventsData[botName][channel + '_' + data.parsedMessage.message.command] = data; }); return internals.writeFile('events', eventsData); } }).then((responseData) => { botLogger.logger.info('storage: events updates successfully'); botLogger.logger.debug('storage: events updated successfully for ', responseData); return Promise.resolve(responseData); }).catch((err) => { botLogger.logger.info('storage: events update failed'); botLogger.logger.debug('storage: error updating events for ', err); return Promise.reject(err); }); }; exports = module.exports.removeEvents = function (botName, eventType, data) { return Promise.resolve({ then: (onFulfill, onReject) => { console.log('came to readh'); internals.readFile(eventType) .then((eventsData) => { if (_.get(data, 'channels', []).length) { _.forEach(data.channels, function (channel) { let eventPath = [botName, channel + '_' + _.get(data, 'commandToKill')]; if (!_.unset(eventsData, eventPath)) { botLogger.logger.info('storage: events updates successfully'); } }); } return eventsData; }).then((rData) => { return internals.writeFile('events', rData); }).then((responseData) => { botLogger.logger.info('storage: events updates successfully'); botLogger.logger.debug('storage: events updated successfully for ', responseData); onFulfill(responseData); }).catch((err) => { botLogger.logger.info('storage: events update failed'); botLogger.logger.debug('storage: error updating events for ', err); onReject(err); }); } }); }; exports = module.exports.getEvents = function (eventType) { return internals.readFile(eventType); }; internals.readFile = function (fileType) { var path = ''; var fileData = ''; if (fileType === 'events') { path = internals.EVENT_FILE_PATH; } return Promise.resolve({ then: (onFulfill, onReject) => { fs.readFile(path, { encoding: 'utf8', flag: 'a+' }, function (err, data) { if (err) { return onReject(err); } try { fileData = data ? JSON.parse(data) : ''; } catch (parseErr) { botLogger.logger.info('storage: read file failed'); botLogger.logger.debug('storage: read file failed', parseErr, path); return onReject(parseErr); } onFulfill(fileData); }); } }); }; internals.writeFile = function (fileType, data) { var path = ''; var fileData = JSON.stringify(data, null, 2); if (fileType === 'events') { path = internals.EVENT_FILE_PATH; } return Promise.resolve({ then: (onFulfill, onReject) => { fs.writeFile(path, fileData, { encoding: 'utf8', flag: 'w+' }, function (err) { if (err) { botLogger.logger.info('storage: write file failed'); botLogger.logger.debug('storage: write file failed', err, path); return onReject(err); } onFulfill(data); }); } }); };
JavaScript
0.000001
@@ -2038,44 +2038,8 @@ %3E %7B%0A - console.log('came to readh');%0A
0b8ef104cebbc526ec750fbac652a48e3487d21f
Change ref in broken test.
test/src/combat_util.spec.js
test/src/combat_util.spec.js
'use strict'; const expect = require('chai').expect; const Player = require('../../src/player.js').Player; const Npc = require('../../src/npcs.js').Npc; const CombatUtil = require('../../src/combat_util.js').CombatUtil; const CombatHelper = require('../../src/combat_util.js').CombatHelper; describe('Player/NPC Combat Helper', () => { const testPlayer = new Player(); it('should create a new instance', () => { expect(testPlayer.combat instanceof CombatHelper).to.be.true; }); describe('combat modifiers: speed', () => { it('should be able to add and remove modifiers', () => { testPlayer.combat.addSpeedMod({ name: 'haste', effect: speed => speed / 2 }); const numberOfSpeedMods = Object.keys(testPlayer.combat.speedMods).length; expect(numberOfSpeedMods).to.equal(1); }); it('should be able to apply modifiers', () => { const speed = testPlayer.combat.getAttackSpeed(); const expected = 4375; expect(speed).to.equal(expected); }); it('should stack modifiers', () => { testPlayer.combat.addSpeedMod({ name: 'slow', effect: speed => speed * 2 }); const speed = testPlayer.combat.getAttackSpeed(); const expected = 4375 * 2; expect(speed).to.equal(expected); }); it('can remove mods, has a maximum for speed mod', () => { testPlayer.combat.removeSpeedMod('haste'); const speed = testPlayer.combat.getAttackSpeed(); const maximum = 10 * 1000; expect(speed).to.equal(maximum); }); it('should still work without any mods', () => { testPlayer.combat.removeSpeedMod('slow'); const speed = testPlayer.combat.getAttackSpeed(); const expected = 4375 * 2; expect(speed).to.equal(expected); }); }); describe('weapon/damage helpers', () => { const sword = { getAttribute: () => '5-40', getShortDesc: () => 'Yey' }; const warrior = { getEquipped: () => sword, getAttribute: () => 1, }; const testWarrior = new CombatHelper(warrior); it('should be able to get damage within a range', () => { let i = 0; let limit = 100; while(i < limit) { const damage = testWarrior.getDamage(); expect(damage >= 5).to.be.true; expect(damage <= 40).to.be.true; i++; } }); it('should also be able to use modifiers', () => { testWarrior.addDamageMod({ name: 'berserk', effect: damage => damage * 2 }); let i = 0; let limit = 100; while(i < limit) { const damage = testWarrior.getDamage(); expect(damage >= 10).to.be.true; expect(damage <= 80).to.be.true; i++; } }); describe('weapon helpers', () => { it('should be able to get weapon desc', () => { const attackName = testWarrior.getPrimary(); expect(attackName).to.equal('Yey'); }); }); }); });
JavaScript
0
@@ -2907,16 +2907,26 @@ tPrimary +AttackName ();%0A
89027f32620fba6edbbd15e2a6f156ba8f671620
Fix object destructuring
src/js/classes/InputHandler.js
src/js/classes/InputHandler.js
import config from '../config'; // ############################################## // # Private functions ########################## // ############################################## const controls = { playerAccelerate: false, playerDecelerate: false, playerTurnLeft: false, playerTurnRight: false, rotateLeft: false, rotateRight: false, zoomIn: false, zoomOut: false, }; const mapping = { /* W */ 87: 'playerAccelerate', /* S */ 83: 'playerDecelerate', /* A */ 65: 'playerTurnLeft', /* D */ 68: 'playerTurnRight', /* ↑ */ 38: 'cameraUp', /* ← */ 40: 'cameraDown', /* ↓ */ 37: 'cameraLeft', /* → */ 39: 'cameraRight', /* Q */ 81: null, /* E */ 69: null, /* R */ 82: null, /* F */ 70: null, }; function onKeyDown(event) { if (!mapping[event.keyCode]) return; controls[mapping[event.keyCode]] = true; } // ############################################## function onKeyUp(event) { if (!mapping[event.keyCode]) return; controls[mapping[event.keyCode]] = false; } // ############################################## function showDirectionalVectors(event) { config.showDirectionalVectors = event.target.checked; } // ############################################## function cameraMovement(cameraObject) { // Shorthands const [rotation] = cameraObject.camera.rotation; const [position] = cameraObject.camera.position; const [target] = cameraObject.controls.target; const [movementSpeed] = config.camera.movementSpeed; if (controls.cameraUp && !controls.cameraDown) { position.x -= Math.sin(rotation.z) * movementSpeed; target.x -= Math.sin(rotation.z) * movementSpeed; position.z -= Math.cos(rotation.z) * movementSpeed; target.z -= Math.cos(rotation.z) * movementSpeed; } if (controls.cameraDown && !controls.cameraUp) { position.x += Math.sin(rotation.z) * movementSpeed; target.x += Math.sin(rotation.z) * movementSpeed; position.z += Math.cos(rotation.z) * movementSpeed; target.z += Math.cos(rotation.z) * movementSpeed; } if (controls.cameraLeft && !controls.cameraRight) { position.x -= Math.cos(rotation.z) * movementSpeed; target.x -= Math.cos(rotation.z) * movementSpeed; position.z -= -Math.sin(rotation.z) * movementSpeed; target.z -= -Math.sin(rotation.z) * movementSpeed; } if (controls.cameraRight && !controls.cameraLeft) { position.x += Math.cos(rotation.z) * movementSpeed; target.x += Math.cos(rotation.z) * movementSpeed; position.z += -Math.sin(rotation.z) * movementSpeed; target.z += -Math.sin(rotation.z) * movementSpeed; } } // ############################################## function playerMovement(player) { if (controls.playerAccelerate && !controls.playerDecelerate) { player.accelerate(); } if (controls.playerDecelerate && !controls.playerAccelerate) { player.decelerate(); } if (controls.playerTurnLeft && !controls.playerTurnRight) { player.turnLeft(); } if (controls.playerTurnRight && !controls.playerTurnLeft) { player.turnRight(); } } // ############################################## class InputHandler { // ############################################## // # Constructor ################################ // ############################################## constructor(scene, camera, player) { this.scene = scene; this.camera = camera; this.player = player; // Add event listeners document.addEventListener('keydown', onKeyDown, false); document.addEventListener('keyup', onKeyUp, false); document.getElementById('ShowDirectionalVectors') .addEventListener('change', showDirectionalVectors, false); } // ############################################## // # Public functions ########################### // ############################################## checkInput() { if (this.camera) { cameraMovement(this.camera); } if (this.player) { playerMovement(this.player); } } } export default InputHandler;
JavaScript
0.000549
@@ -1351,75 +1351,28 @@ nst -%5Brotation%5D = cameraObject.camera.rotation;%0A const %5B +%7B rotation, position %5D @@ -1367,22 +1367,18 @@ position -%5D +%7D = camer @@ -1395,17 +1395,8 @@ mera -.position ;%0A @@ -1407,16 +1407,23 @@ nst -%5B +%7B target -%5D + %7D @@ -1449,23 +1449,16 @@ controls -.target ;%0A co @@ -1461,17 +1461,18 @@ const -%5B +%7B movement @@ -1476,17 +1476,23 @@ entSpeed -%5D + %7D = confi @@ -1503,22 +1503,8 @@ mera -.movementSpeed ;%0A%0A
d8f128d2880db5039a362e323a2b4a924bc23ef1
countdown component
src/js/components/countdown.js
src/js/components/countdown.js
import Class from '../mixin/class'; import { $, empty, html } from 'uikit-util'; export default { mixins: [Class], props: { date: String, clsWrapper: String, }, data: { date: '', clsWrapper: '.uk-countdown-%unit%', }, computed: { date({ date }) { return Date.parse(date); }, days({ clsWrapper }, $el) { return $(clsWrapper.replace('%unit%', 'days'), $el); }, hours({ clsWrapper }, $el) { return $(clsWrapper.replace('%unit%', 'hours'), $el); }, minutes({ clsWrapper }, $el) { return $(clsWrapper.replace('%unit%', 'minutes'), $el); }, seconds({ clsWrapper }, $el) { return $(clsWrapper.replace('%unit%', 'seconds'), $el); }, units() { return ['days', 'hours', 'minutes', 'seconds'].filter((unit) => this[unit]); }, }, connected() { this.start(); }, disconnected() { this.stop(); this.units.forEach((unit) => empty(this[unit])); }, events: [ { name: 'visibilitychange', el() { return document; }, handler() { if (document.hidden) { this.stop(); } else { this.start(); } }, }, ], update: { write() { const timespan = getTimeSpan(this.date); if (timespan.total <= 0) { this.stop(); timespan.days = timespan.hours = timespan.minutes = timespan.seconds = 0; } for (const unit of this.units) { let digits = String(Math.floor(timespan[unit])); digits = digits.length < 2 ? `0${digits}` : digits; const el = this[unit]; if (el.textContent !== digits) { digits = digits.split(''); if (digits.length !== el.children.length) { html(el, digits.map(() => '<span></span>').join('')); } digits.forEach((digit, i) => (el.children[i].textContent = digit)); } } }, }, methods: { start() { this.stop(); if (this.date && this.units.length) { this.$emit(); this.timer = setInterval(() => this.$emit(), 1000); } }, stop() { if (this.timer) { clearInterval(this.timer); this.timer = null; } }, }, }; function getTimeSpan(date) { const total = date - Date.now(); return { total, seconds: (total / 1000) % 60, minutes: (total / 1000 / 60) % 60, hours: (total / 1000 / 60 / 60) % 24, days: total / 1000 / 60 / 60 / 24, }; }
JavaScript
0.99975
@@ -44,15 +44,8 @@ %7B $, - empty, htm @@ -68,16 +68,72 @@ util';%0A%0A +const units = %5B'days', 'hours', 'minutes', 'seconds'%5D;%0A%0A export d @@ -326,238 +326,16 @@ co -mputed: %7B%0A date(%7B date %7D) %7B%0A return Date.parse(date);%0A %7D,%0A%0A days(%7B clsWrapper %7D, $el) %7B%0A return $(clsWrapper.replace('%25unit%25', 'days'), $el);%0A %7D,%0A%0A hours(%7B clsWrapper %7D, $el +nnected( ) %7B%0A @@ -346,459 +346,42 @@ - - return $(clsWrapper.replace('%25unit%25', 'hours'), $el);%0A %7D,%0A%0A minutes(%7B clsWrapper %7D, $el) %7B%0A return $(clsWrapper.replace('%25unit%25', 'minutes'), $el);%0A %7D,%0A%0A seconds(%7B clsWrapper %7D, $el) %7B%0A return $(clsWrapper.replace('%25unit%25', 'seconds'), $el);%0A %7D,%0A%0A units() %7B%0A return %5B'days', 'hours', 'minutes', 'seconds'%5D.filter((unit) =%3E this%5Bunit%5D);%0A %7D,%0A %7D,%0A%0A connected() %7B +this.date = Date.parse(this.date); %0A @@ -453,65 +453,8 @@ ();%0A - this.units.forEach((unit) =%3E empty(this%5Bunit%5D));%0A @@ -803,29 +803,238 @@ -update: %7B%0A wri +methods: %7B%0A start() %7B%0A this.stop();%0A this.update();%0A this.timer = setInterval(this.update, 1000);%0A %7D,%0A%0A stop() %7B%0A clearInterval(this.timer);%0A %7D,%0A%0A upda te() @@ -1106,16 +1106,30 @@ if ( +!this.date %7C%7C timespan @@ -1309,21 +1309,16 @@ unit of -this. units) %7B @@ -1314,24 +1314,182 @@ of units) %7B%0A + const el = $(this.clsWrapper.replace('%25unit%25', unit), this.$el);%0A%0A if (!el) %7B%0A continue;%0A %7D%0A%0A @@ -1615,47 +1615,8 @@ s;%0A%0A - const el = this%5Bunit%5D;%0A @@ -2014,399 +2014,8 @@ %7D, -%0A%0A methods: %7B%0A start() %7B%0A this.stop();%0A%0A if (this.date && this.units.length) %7B%0A this.$emit();%0A this.timer = setInterval(() =%3E this.$emit(), 1000);%0A %7D%0A %7D,%0A%0A stop() %7B%0A if (this.timer) %7B%0A clearInterval(this.timer);%0A this.timer = null;%0A %7D%0A %7D,%0A %7D, %0A%7D;%0A
b504f02c2b0d30d1cd1af0b851efd10920066d9e
remove alert from status code
src/js/oseam-views-register.js
src/js/oseam-views-register.js
// ------------------------------------------------------------------------------------------------- // OpenSeaMap Water Depth - Web frontend for depth data handling. // // Written in 2012 by Dominik Fässler dfa@bezono.org // // To the extent possible under law, the author(s) have dedicated all copyright // and related and neighboring rights to this software to the public domain // worldwide. This software is distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along // with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // ------------------------------------------------------------------------------------------------- OSeaM.views.Register = OSeaM.View.extend({ isValid: true, events: { 'click .btn-link' : 'renewCaptcha', 'submit form' : 'onFormSubmit' }, initialize: function() { this.model.bind('createSuccess', this.onCreateSuccess, this); this.model.bind('createFailure', this.onCreateFailure, this); }, render: function() { var template = OSeaM.loadTemplate('register'); this.renderParams = { captchaUrl : this.model.getCaptchaUrl(), idUsername : OSeaM.id(), idPassword1 : OSeaM.id(), idPassword2 : OSeaM.id(), idCaptcha : OSeaM.id(), // idLicense : OSeaM.id(), idSubmit : OSeaM.id() }; var content = $(template(this.renderParams)); OSeaM.frontend.translate(content); this.$el.html(content); this.fieldUsername = this.$el.find('#' + this.renderParams.idUsername); this.fieldPassword1 = this.$el.find('#' + this.renderParams.idPassword1); this.fieldPassword2 = this.$el.find('#' + this.renderParams.idPassword2); this.fieldCaptcha = this.$el.find('#' + this.renderParams.idCaptcha); // this.fieldLicense = this.$el.find('#' + this.renderParams.idLicense); this.buttonSubmit = this.$el.find('#' + this.renderParams.idSubmit); var fn = function(data) { this.replaceCaptcha(data); }; jQuery.ajax({ type: 'POST', url: OSeaM.apiUrl + 'users/captcha', contentType: "application/json", dataType: 'json', // xhrFields: { // withCredentials: true // }, success: jQuery.proxy(fn, this) }); return this; }, replaceCaptcha: function(data) { this.$el.find('#captcha').removeClass('loading').append('<img id="captcha" src="data:image/png;base64,' + data.imageBase64 + '"/>') }, validateForm: function() { this.removeAlerts(); var errors = []; if (OSeaM.utils.Validation.username(this.fieldUsername.val()) !== true) { this.markInvalid(this.fieldUsername, '1010:Invalid Email format.'); //what is this for? errors.push('1004:Email'); } if (this.fieldPassword1.val() !== this.fieldPassword2.val()) { this.markInvalid(this.fieldPassword2, '1011:Verification is different.'); errors.push('1017:Password verification'); } if (this.fieldPassword1.val().length < 8) { this.markInvalid(this.fieldPassword1, '1012:At least 8 characters.'); errors.push('1005:Password'); } if (this.fieldPassword2.val().length < 8) { this.markInvalid(this.fieldPassword2, '1012:At least 8 characters.'); errors.push('1017:Password verification'); } if (this.fieldCaptcha.val().length !== 6) { this.markInvalid(this.fieldCaptcha, '1013:Invalid captcha.'); errors.push('1007:Captcha'); } // if (this.fieldLicense.is(':checked') !== true) { // this.markInvalid(this.fieldLicense, ''); // errors.push('1014:License'); // } if (this.isValid !== true) { var template = OSeaM.loadTemplate('alert'); var content = $(template({ title:'1027:Validation error occured', errors:errors })); OSeaM.frontend.translate(content); this.$el.find('legend').after(content); } return this.isValid; }, markInvalid: function(field, text) { field.parents('.control-group').addClass('error'); field.next('.help-inline').attr('data-trt', text); OSeaM.frontend.translate(this.$el); this.isValid = false; }, removeAlerts: function() { this.$el.find('.alert').remove(); this.$el.find('.control-group').removeClass('error'); this.$el.find('.help-inline').removeAttr('data-trt'); this.$el.find('.help-inline').html(''); this.isValid = true; }, onFormSubmit: function(evt) { evt.preventDefault(); this.buttonSubmit.button('loading'); if (this.validateForm() !== true) { this.buttonSubmit.button('reset'); return; } var params = { username : this.fieldUsername.val(), password : this.fieldPassword1.val(), captcha : this.fieldCaptcha.val() }; params.password = jQuery.encoding.digests.hexSha1Str(params.password).toLowerCase(); // TODO : license accept this.model.create(params); return false; }, onCreateSuccess: function(data) { var template = OSeaM.loadTemplate('alert-success'); var content = $(template({ title:'1028:Account created!', msg:'1029:Your account has been created successfully.' })); OSeaM.frontend.translate(content); this.$el.find('form').remove(); this.$el.find('legend').after(content); }, onCreateFailure: function(jqXHR) { var template = OSeaM.loadTemplate('alert'); var msg = ''; alert(jqXHR.status); if (jqXHR.status === 409) { this.markInvalid(this.fieldUsername, '9103:Username already exists.'); this.fieldUsername.focus(); } else if(response.code === 400) { this.markInvalid(this.fieldCaptcha, '1013:Invalid captcha.'); this.fieldCaptcha.val('').focus(); } else { msg = '1031:Unknown error. Please try again.' } var content = $(template({ title:'1030:Server error occured', msg:msg })); OSeaM.frontend.translate(content); this.$el.find('legend').after(content); this.buttonSubmit.button('reset'); }, renewCaptcha: function(evt) { this.$el.find('img').attr('src', this.model.getCaptchaUrl()) } });
JavaScript
0.000001
@@ -5969,37 +5969,8 @@ '';%0A - alert(jqXHR.status);%0A
76968503f1f0b3c0753376c6415aeee0dc75e10f
Add a hasTS property to the build config, which defaults to true if the project has a tsconfig.json file
src/config/build.js
src/config/build.js
// External const mem = require('mem'); // Ours const { BUILD_DIRECTORY_NAME } = require('../constants'); const { combine } = require('../utils/structures'); const { getProjectConfig } = require('./project'); const PROJECT_TYPES_CONFIG = { svelte: { useCSSModules: false } }; module.exports.getBuildConfig = mem(() => { const { build: projectBuildConfig, type } = getProjectConfig(); return combine( { entry: 'index.js', from: 'src', to: BUILD_DIRECTORY_NAME, staticDir: 'public', addModernJS: false, extractCSS: false, useCSSModules: true, showDeprecations: false }, PROJECT_TYPES_CONFIG[type], projectBuildConfig ); });
JavaScript
0
@@ -1,8 +1,91 @@ +// Global%0Aconst %7B existsSync %7D = require('fs');%0Aconst %7B join %7D = require('path');%0A%0A // Exter @@ -361,16 +361,150 @@ e%0A %7D%0A%7D; +%0Aconst DEFAULT_ENTRY_FILE_NAME = 'index';%0Aconst DEFAULT_SOURCE_DIRECTORY_NAME = 'src';%0Aconst DEFAULT_STATIC_DIRECTORY_NAME = 'public'; %0A%0Amodule @@ -577,16 +577,22 @@ dConfig, + root, type %7D @@ -617,75 +617,169 @@ ();%0A -%0A return combine(%0A %7B%0A entry: 'index.js',%0A from: 'src' + const hasTS = existsSync(join(root, 'tsconfig.json'));%0A%0A return combine(%0A %7B%0A entry: DEFAULT_ENTRY_FILE_NAME,%0A from: DEFAULT_SOURCE_DIRECTORY_NAME ,%0A @@ -825,24 +825,58 @@ ticDir: -'public' +DEFAULT_STATIC_DIRECTORY_NAME,%0A hasTS ,%0A