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
1d5c7a84a3eb25d136b41881e4abe252032bb98d
rename Layer action prop names to on* to avoid clashes with actions themselves
src/components/Layer.js
src/components/Layer.js
import React from 'react'; import { connect } from 'react-redux'; import { playbackListenerAdd, playbackListenerRemove, layerClear, layerRemove, layerIncrementNote, layerSetMuted } from '../actions'; import Button from './Button'; function getOpacity(value) { const minimum = 0.2; return minimum + ((1 - minimum) * value); } class Layer extends React.Component { constructor(props) { super(props); this.setPlaybackElement = this.setPlaybackElement.bind(this); this.updatePlaybackIndex = this.updatePlaybackIndex.bind(this); } componentDidMount() { this.props.playbackListenerAdd(this.updatePlaybackIndex); } componentWillUnmount() { this.props.playbackListenerRemove(this.updatePlaybackIndex); } setPlaybackElement(element) { this.playbackElement = element; } updatePlaybackIndex(value) { const { layer } = this.props; const percentage = (value % layer.notes.length) * 100; this.playbackElement.style.transform = `translate3d(${percentage}%, -100%, 0)`; } render() { const { layer } = this.props; const { layerClear, layerRemove, layerSetMuted, layerIncrementNote } = this.props; const layerHasNotes = layer.notes.find(value => value > 0) !== undefined; return ( <div className="flex mb3" key={layer.id}> <Button onClick={() => layerHasNotes ? layerClear(layer.id) : layerRemove(layer.id)} > {layerHasNotes ? 'Clear' : 'Remove'} </Button> <div className="w1" /> <Button isDown={layer.isMuted} onClick={() => layerSetMuted(layer.id, !layer.isMuted)} > Mute </Button> <div className="w1" /> <div className="flex relative"> {layer.notes.map((note, index) => ( <div key={index} className="w2 h2 bg-white light-gray pointer ba" style={{opacity: getOpacity(note)}} onClick={() => layerIncrementNote(layer.id, index, note)} /> ))} <div ref={this.setPlaybackElement} className="w2 h1 bg-gold absolute left-0 top-0" /> </div> </div> ); } } export default connect(null, { playbackListenerAdd, playbackListenerRemove, layerClear, layerRemove, layerIncrementNote, layerSetMuted })(Layer);
JavaScript
0
@@ -72,58 +72,45 @@ t %7B -p lay -backListenerAdd +erClear , -p lay -backListenerRemov +erIncrementNot e, layer Clea @@ -109,61 +109,103 @@ ayer -Clear +Remove , layer -Remove, layerIncrementNote +SetMuted %7D from '../actions';%0Aimport %7B playbackListenerAdd , +p lay -erSetMuted +backListenerRemove %7D f @@ -604,33 +604,35 @@ %0A this.props. -p +onP laybackListenerA @@ -708,17 +708,19 @@ s.props. -p +onP laybackL @@ -1116,66 +1116,54 @@ t %7B -layer +on Clear, -layerRemove, layerSetMu +onIncrementNo te -d , -layerIncrementNo +onRemove, onSetMu te +d %7D = @@ -1373,21 +1373,18 @@ Notes ? -layer +on Clear(la @@ -1393,21 +1393,18 @@ r.id) : -layer +on Remove(l @@ -1593,21 +1593,18 @@ =%7B() =%3E -layer +on SetMuted @@ -1976,21 +1976,18 @@ =%7B() =%3E -layer +on Incremen @@ -2254,121 +2254,218 @@ %7B%0A -playbackListenerAdd,%0A playbackListenerRemove,%0A layerClear,%0A layerRemove,%0A layerIncrementNote,%0A layerSetMuted +onClear: layerClear,%0A onIncrementNote: layerIncrementNote,%0A onRemove: layerRemove,%0A onSetMuted: layerSetMuted,%0A onPlaybackListenerAdd: playbackListenerAdd,%0A onPlaybackListenerRemove: playbackListenerRemove %0A%7D)(
18b00a836df026013ffb9f05ec96a506f66eb26a
Add imdb link button
src/components/Movie.js
src/components/Movie.js
import React from 'react'; export const Movie = (props) => { let poster = props.Poster === 'N/A' ? <img src="" alt={props.Title} height="250" width="170" /> : <img src={props.Poster} alt={props.Title} height="250" width="170" /> return ( <div className="col-md-3"> {poster} <br/> {props.Title} - {props.Year} <br/> {props.Plot} <br/> <a href={props.tomatoURL} target="_blank"> <button className="btn btn-sm btn-success">Rotten Tomatoes</button> </a> <hr /> </div> ); }
JavaScript
0.000001
@@ -224,16 +224,79 @@ %22170%22 /%3E +;%0A let imdbURL = %60http://www.imdb.com/title/$%7Bprops.imdbID%7D/%60; %0A retur @@ -414,24 +414,127 @@ Plot%7D %3Cbr/%3E%0A + %3Ca href=%7BimdbURL%7D target=%22_blank%22%3E %3Cbutton className=%22btn btn-sm btn-success%22%3EIMDb%3C/button%3E %3C/a%3E%0A %3Ca hre
f64172c567edf05d6f46ee6eb16bf35a6a6a2ec6
Add link to event tickets
src/components/Movie.js
src/components/Movie.js
import React, { Component, PropTypes } from 'react'; import { Image, ScrollView, StyleSheet, Text, View } from 'react-native'; import FitImage from 'react-native-fit-image'; import moment from 'moment'; require('moment/locale/fi'); const styles = StyleSheet.create({ container: { paddingLeft: 10, paddingRight: 10, paddingTop: 65, }, detail: { color: 'white', fontSize: 18, }, detailBold: { color: 'white', fontSize: 18, fontWeight: 'bold', }, originalTitle: { color: 'white', fontSize: 18, fontStyle: 'italic', }, section: { paddingBottom: 10, }, sectionTitle: { flex: 1, paddingBottom: 10, paddingLeft: 10, }, thumbnailView: { paddingBottom: 10, }, title: { color: 'white', fontSize: 22, }, titleImage: { height: 146, width: 99, padding: 10, }, titleView: { flexDirection: 'row', flex: 1, paddingBottom: 10, }, }); export default class Movie extends Component { getActorList = () => { const actors = this.props.movie.Cast.Actor .map(actor => ` ${actor.FirstName} ${actor.LastName}`); return actors.toString().slice(1); } getDirectorList = () => { if (this.props.movie.Directors.Director.constructor === Array) { const directors = this.props.movie.Directors.Director .map(director => ` ${director.FirstName} ${director.LastName}`); return directors.toString().slice(1); } return ` ${this.props.movie.Directors.Director.FirstName} ${this.props.movie.Directors.Director.LastName}`; } getDuration = () => { const m = moment.duration(parseInt(this.props.movie.LengthInMinutes, 10), 'minutes'); return `${m.hours()} h ${m.minutes()} min`; } setUriAsHttps = () => this.props.movie.Images.EventSmallImagePortrait.replace(/^http:\/\//i, 'https://'); render() { return ( <ScrollView style={styles.container}> <View style={styles.titleView}> <Image style={styles.titleImage} source={{ uri: this.setUriAsHttps() }} /> <View style={styles.sectionTitle}> <Text style={styles.title}> {this.props.movie.Title} </Text> <Text style={styles.originalTitle}> {this.props.movie.OriginalTitle} </Text> <Text style={styles.originalTitle}> {this.props.movie.ProductionYear} </Text> </View> </View> <View style={styles.section}> <Text style={styles.detailBold}>{moment(this.props.show.dttmShowStart).format('HH:mm')} {this.props.show.Theatre} ({this.props.show.TheatreAuditorium})</Text> </View> <View style={styles.section}> <Text style={styles.detail}> Ensi-ilta: <Text style={styles.detailBold}> {moment(this.props.movie.dtLocalRelease).format('D.M.YYYY')}</Text> </Text> <Text style={styles.detail}> Kesto: <Text style={styles.detailBold}>{this.getDuration()}</Text> </Text> <Text style={styles.detail}>Ikäraja: <Text style={styles.detailBold}> {this.props.movie.RatingLabel}</Text> </Text> </View> <View style={styles.section}> <Text style={styles.detail}> Lajityyppi: {this.props.movie.Genres} </Text> <Text style={styles.detail}> Levittäjä: {this.props.movie.LocalDistributorName} </Text> </View> <View style={styles.section}> {this.props.movie.Directors.Director ? <Text style={styles.detail}> Ohjaus: <Text>{this.getDirectorList()}</Text> </Text> : null} {this.props.movie.Cast ? <Text style={styles.detail}> Pääosissa: {this.getActorList()} </Text> : null} </View> <View style={styles.section}> <Text style={styles.detail}> {this.props.movie.ShortSynopsis} </Text> </View> {this.props.movie.Gallery.GalleryImage ? this.props.movie.Gallery.GalleryImage.map((image, i) => <View key={i} style={styles.thumbnailView}> <FitImage style={styles.thumbnail} source={{ uri: image.Location }} /></View>) : null} </ScrollView> ); } } Movie.propTypes = { movie: PropTypes.object.isRequired, show: PropTypes.object.isRequired, };
JavaScript
0
@@ -64,16 +64,27 @@ Image,%0A + Linking,%0A Scroll @@ -89,16 +89,16 @@ llView,%0A - StyleS @@ -111,16 +111,36 @@ Text,%0A + TouchableOpacity,%0A View %7D @@ -775,24 +775,145 @@ m: 10,%0A %7D,%0A + link: %7B%0A color: '#ffc40c',%0A fontSize: 18,%0A fontWeight: 'bold',%0A paddingBottom: 10,%0A paddingTop: 5,%0A %7D,%0A title: %7B%0A @@ -2013,16 +2013,208 @@ ://');%0A%0A + openEventURL = () =%3E %7B%0A Linking.canOpenURL(this.props.show.EventURL).then((supported) =%3E %7B%0A if (supported) %7B%0A Linking.openURL(this.props.show.EventURL);%0A %7D%0A %7D);%0A %7D;%0A%0A render @@ -3046,32 +3046,32 @@ torium%7D)%3C/Text%3E%0A - %3C/View%3E%0A @@ -3063,32 +3063,180 @@ %3C/View%3E%0A%0A + %3CTouchableOpacity onPress=%7Bthis.openEventURL%7D%3E%0A %3CText style=%7Bstyles.link%7D%3EOsta tai varaa liput%3C/Text%3E%0A %3C/TouchableOpacity%3E%0A%0A %3CView st
a94c2743568513d055387bb96f412d3449b4c69a
Remove 'clear' due to unforseen consequences
src/components/apps/terminal/commands.js
src/components/apps/terminal/commands.js
import * as apps from '../../Applications.vue' let localforage = require('localforage') export default { data () { console.log('apps:', apps.comps) return { // apps: Object.keys(apps.comps) } }, cmd (vue, command) { let myCmd = command.split(' ') switch (myCmd[0]) { case 'test': return {type: 'string', data: 'success'} case 'touch': if (myCmd.length > 1) { localforage.setItem(myCmd[1], '') .then(() => { vue.results.push({dataType: 'string', data: myCmd[1], command: command}) }) .catch(function (e) { vue.results.push({dataType: 'string', data: e, command: command}) }) } else { // vue.results.push({dataType: 'string', data: 'Requires at least 1 argument', command: command}) return {dataType: 'string', data: 'Requires at least 1 argument'} } break case 'cat': if (myCmd.length > 1) { localforage.getItem(myCmd[1]) .then((data) => { vue.results.push({dataType: 'string', data: data, command: command}) }) .catch(function (e) { vue.results.push({dataType: 'string', data: e, command: command}) }) } else { return {dataType: 'string', data: 'Requires at least 1 argument'} } break case 'ls': let result = [] localforage.iterate((value, key, iterationNumber) => { result.push(key) }).then(() => { // console.log('files', result) vue.results.push({dataType: 'list', data: result, command: command}) // return {type: 'list', data: result} }) break case 'rm': if (myCmd.length > 1) { const args = myCmd.slice(1) args.map((arg) => ( localforage.getItem(arg) .then(async (data) => { await localforage.removeItem(arg) vue.results.push({dataType: 'string', data: '', command: command}) }) .catch(function (e) { vue.results.push({dataType: 'string', data: e, command: command}) }) )) } else { return {dataType: 'string', data: 'Requires at least 1 argument'} } break case 'clear': vue.results = [] break case 'help': return {type: 'string', data: 'Try help, ls, cat, touch, or any app name.'} default: // console.log('apps:', apps) // console.log('dispatch open:', command) vue.$dispatch('openApp', command) return true } } }
JavaScript
0.00069
@@ -2332,32 +2332,35 @@ break%0A + // case 'clear':%0A @@ -2360,26 +2360,29 @@ ear':%0A +// + vue.results @@ -2387,24 +2387,27 @@ s = %5B%5D%0A + // break%0A
842639dc43c46bba6ed9274813141e3890093690
Allow subtitles to box component
components/box.js
components/box.js
import React from 'react' import PropTypes from 'prop-types' const Box = ({ children, title, color }) => ( <div className='wrapper'> {title && <h3 className={color}>{title}</h3>} <div className='inner'> {children} </div> <style jsx>{` @import 'colors'; .wrapper { background-color: $white; box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.3); border-radius: 2px; margin-bottom: 20px; overflow: hidden; } h3 { font-size: 1.1em; margin: 0; padding: 0.6em 0.75em 0.55em; max-width: 100%; overflow: hidden; text-overflow: ellipsis; font-weight: normal; } .inner { padding: 1.5em 1.7em; @media (max-width: 551px) { padding: 1em; } } // Colors .grey { background-color: $lightgrey; } .blue { background-color: $blue; color: $white; } `}</style> </div> ) Box.propTypes = { children: PropTypes.node, title: PropTypes.string, color: PropTypes.oneOf([ 'grey', 'blue' ]) } Box.defaultProps = { color: 'grey' } export default Box
JavaScript
0.000001
@@ -86,16 +86,26 @@ , title, + subtitle, color %7D @@ -111,16 +111,16 @@ %7D) =%3E (%0A - %3Cdiv c @@ -148,51 +148,194 @@ %7B +( title -&& %3Ch3 className=%7Bcolor%7D%3E%7Btitle%7D%3C/h3%3E +%7C%7C subtitle) && (%0A %3Cdiv className=%7B%60header $%7Bcolor%7D%60%7D%3E%0A %7Btitle && %3Ch3%3E%7Btitle%7D%3C/h3%3E%7D%0A %7Bsubtitle && %3Cdiv className='subtitle'%3E%7Bsubtitle%7D%3C/div%3E%7D%0A %3C/div%3E%0A ) %7D%0A @@ -623,24 +623,87 @@ n;%0A %7D%0A%0A + .header %7B%0A padding: 0.6em 0.75em 0.55em;%0A %7D%0A%0A h3 %7B%0A @@ -750,46 +750,8 @@ 0;%0A - padding: 0.6em 0.75em 0.55em;%0A @@ -864,24 +864,77 @@ l;%0A %7D%0A%0A + .subtitle %7B%0A font-size: 0.9em;%0A %7D%0A%0A .inner @@ -1114,16 +1114,71 @@ ghtgrey; +%0A%0A .subtitle %7B%0A color: $grey;%0A %7D %0A %7D @@ -1244,24 +1244,93 @@ lor: $white; +%0A%0A .subtitle %7B%0A color: lighten($blue, 35%25);%0A %7D %0A %7D%0A @@ -1399,16 +1399,16 @@ s.node,%0A - title: @@ -1426,16 +1426,46 @@ string,%0A + subtitle: PropTypes.string,%0A color:
bf868f9ba4c1268ac1c70c0deebc99fff1a59c5e
Fix for uncaught null value in synchronize.js
src/conc/synchronize.js
src/conc/synchronize.js
/* * Copyright 2010 Jive Software * * 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. */ /*extern jive */ jive = this.jive || {}; jive.conc = jive.conc || {}; /** * A promise - an instance of jive.conc.Promise - is an object that represents * the eventual outcome of an asynchronous operation. This function takes an * object that has promises as property values and returns a new promise. Once * all of the promises on the given object are fulfilled `synchronize()` emits * success passing a copy of the original object with the success event with * any promise property values replaced with the outcomes of those promises. * * If any of the promises on the given object emits an error the same error * will be re-emitted by `synchronize()`. * * @function * @param {Object|Array} obj object referencing multiple promises * @returns {jive.conc.Promise} returns a promise that is fulfilled when all of the referenced promises have been fulfilled * @requires jive.conc.observable * @requires jive.conc.Promise */ jive.conc.synchronize = (function() { function isArray(o) { return Object.prototype.toString.call(o) === "[object Array]"; } function isPromise(prop) { return prop.addCallback && prop.addErrback && prop.addCancelback; } return function(obj) { var outcome, k, toBeFulfilled = 0, promise = new jive.conc.Promise(); function addCallbacks(name, prop) { prop.addCallback(function(val) { outcome[name] = val; toBeFulfilled -= 1; // Emit success when all promises are fulfilled. if (toBeFulfilled < 1) { promise.emitSuccess(outcome); } }).addErrback(function(/* args */) { promise.emitError.apply(promise, arguments); }).addCancelback(function(/* args */) { promise.cancel.apply(promise, arguments); }); toBeFulfilled += 1; } // Create a copy of the given object. Handle synchronizing both arrays // and objects. outcome = isArray(obj) ? [] : {}; for (k in obj) { if (obj.hasOwnProperty(k)) { if (isPromise(obj[k])) { addCallbacks(k, obj[k]); } else { outcome[k] = obj[k]; } } } return promise; }; })();
JavaScript
0
@@ -1726,24 +1726,32 @@ return + prop && prop.addCal
abbbac5f9bff32d5a2186125e9d57c847bc21ad7
fix this.action.primary being empty
frappe/public/js/frappe/ui/dialog.js
frappe/public/js/frappe/ui/dialog.js
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // MIT License. See license.txt frappe.provide('frappe.ui'); var cur_dialog; frappe.ui.open_dialogs = []; frappe.ui.Dialog = frappe.ui.FieldGroup.extend({ init: function(opts) { this.display = false; this.is_dialog = true; $.extend(this, { animate: true, size: null }, opts); this._super(); this.make(); }, make: function() { this.$wrapper = frappe.get_modal("", ""); this.wrapper = this.$wrapper.find('.modal-dialog') .get(0); if ( this.size == "small" ) $(this.wrapper).addClass("modal-sm"); else if ( this.size == "large" ) $(this.wrapper).addClass("modal-lg"); this.make_head(); this.body = this.$wrapper.find(".modal-body").get(0); this.header = this.$wrapper.find(".modal-header"); // make fields (if any) this._super(); // show footer this.action = this.action || { primary: { }, secondary: { } }; if(this.primary_action || this.action.primary.label) { this.set_primary_action(this.primary_action_label || this.action.primary.label || __("Submit"), this.primary_action || this.action.primary.click); } if (this.secondary_action_label || this.action.secondary.label) { this.get_close_btn().html(this.secondary_action_label || this.action.secondary.label); } var me = this; this.$wrapper .on("hide.bs.modal", function() { me.display = false; if(frappe.ui.open_dialogs[frappe.ui.open_dialogs.length-1]===me) { frappe.ui.open_dialogs.pop(); if(frappe.ui.open_dialogs.length) { cur_dialog = frappe.ui.open_dialogs[frappe.ui.open_dialogs.length-1]; } else { cur_dialog = null; } } me.onhide && me.onhide(); me.on_hide && me.on_hide(); }) .on("shown.bs.modal", function() { // focus on first input me.display = true; cur_dialog = me; frappe.ui.open_dialogs.push(me); me.focus_on_first_input(); me.on_page_show && me.on_page_show(); }) .on('scroll', function() { var $input = $('input:focus'); if($input.length && ['Date', 'Datetime', 'Time'].includes($input.attr('data-fieldtype'))) { $input.blur(); } }); }, get_primary_btn: function() { return this.$wrapper.find(".modal-header .btn-primary"); }, set_primary_action: function(label, click) { this.has_primary_action = true; var me = this; return this.get_primary_btn() .removeClass("hide") .html(label) .click(function() { me.primary_action_fulfilled = true; // get values and send it // as first parameter to click callback // if no values then return var values = me.get_values(); if(!values) return; click && click.apply(me, [values]); }); }, disable_primary_action: function() { this.get_primary_btn().addClass('disabled'); }, enable_primary_action: function() { this.get_primary_btn().removeClass('disabled'); }, make_head: function() { var me = this; this.set_title(this.title); }, set_title: function(t) { this.$wrapper.find(".modal-title").html(t); }, show: function() { // show it if ( this.animate ) { this.$wrapper.addClass('fade') } else { this.$wrapper.removeClass('fade') } this.$wrapper.modal("show"); this.primary_action_fulfilled = false; this.is_visible = true; }, hide: function(from_event) { this.$wrapper.modal("hide"); this.is_visible = false; }, get_close_btn: function() { return this.$wrapper.find(".btn-modal-close"); }, no_cancel: function() { this.get_close_btn().toggle(false); }, cancel: function() { this.get_close_btn().trigger("click"); } });
JavaScript
0.999999
@@ -940,32 +940,51 @@ imary_action %7C%7C +!frappe._.is_empty( this.action.prim @@ -986,22 +986,17 @@ .primary -.label +) ) %7B%0A%09%09%09t
4dcea40510a6381b6283fe69eff8c89df62e9c15
Add cypress-testing-library to cypress/support
frontend/cypress/support/commands.js
frontend/cypress/support/commands.js
// *********************************************** // This example commands.js shows you how to // create various custom commands and overwrite // existing commands. // // For more comprehensive examples of custom // commands please read more here: // https://on.cypress.io/custom-commands // *********************************************** // // // -- This is a parent command -- // Cypress.Commands.add("login", (email, password) => { ... }) // // // -- This is a child command -- // Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... }) // // // -- This is a dual command -- // Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... }) // // // -- This is will overwrite an existing command -- // Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... })
JavaScript
0.000005
@@ -1,28 +1,74 @@ +import 'cypress-testing-library/add-commands'%0A // *************************
96e346ef0cc0b62e4d91f4b7f7d4d1751275c6e8
Add empty plist key
src/config/ios/index.js
src/config/ios/index.js
const path = require('path'); const findProject = require('./findProject'); /** * Returns project config by analyzing given folder and applying some user defaults * when constructing final object */ exports.projectConfig = function projectConfigIOS(folder, userConfig) { const project = userConfig.project || findProject(folder); /** * No iOS config found here */ if (!project) { return null; } const projectPath = path.join(folder, project); return { sourceDir: path.dirname(projectPath), folder: folder, pbxprojPath: path.join(projectPath, 'project.pbxproj'), projectPath: projectPath, projectName: path.basename(projectPath), libraryFolder: userConfig.libraryFolder || 'Libraries', }; }; exports.dependencyConfig = exports.projectConfig;
JavaScript
0
@@ -731,16 +731,51 @@ aries',%0A + plist: userConfig.plist %7C%7C %5B%5D,%0A %7D;%0A%7D;%0A
33375f89e38df76232bd37359129cdf0c495ea99
remove 20
server/initial-state.js
server/initial-state.js
import getChannelModel from './models/channel'; import getMessageModel from './models/message'; import getUserModel from './models/user'; const User = getUserModel(); const Channel = getChannelModel(); const Message = getMessageModel(); export default function getInitState(sessionId) { return new Promise((resolve, reject) => { const state = {}; Promise.all([ Channel.getAll(), Message.getAll(), User.getAll(), User.findOne({ sessionId }).select({ sessionId: 1 }) ]).then((results) => { let channels = results[0]; let messages = results[1]; let users = results[2]; const currentUser = results[3]; const userId = currentUser.id; channels = channels.map((channel) => { const channelObj = channel.toObject(); channelObj.unreadMessagesCount = 20; return channelObj; }); messages = messages.map((message) => message.toObject()); users = users.map((user) => { const userObj = user.toObject(); userObj.isOnline = true; return userObj; }); state.users = users; state.channels = channels; state.messages = messages; state.local = { userId, sessionId, currentChannelId: channels[0].id, pendingMessages: [], }; resolve(state); }).catch((exeption) => { reject(exeption); }); }); }
JavaScript
0.000016
@@ -764,53 +764,8 @@ ();%0A - channelObj.unreadMessagesCount = 20;%0A
e4498737c2d860a617c9b0f1673f4df13052b0b5
Add map delete route
server/routes/routes.js
server/routes/routes.js
'use strict'; var Map = require('../models/map'); module.exports = function (app) { app.route('/api/maps') .get(function(req, res){ Map.find(function (error, doc) { res.send(doc); }); }) .post(function(req, res){ let map = req.body; let locationMap = new Map(map); locationMap.save(function (error, data) { res.status(300).send(); }); }); }
JavaScript
0
@@ -406,10 +406,211 @@ %7D);%0A + app.route('/api/maps/:id')%0A .delete(function(req, res) %7B%0A Map.findOne(%7B%0A _id: req.params.id%0A %7D).remove(function (error, result)%7B%0A res.status(300).send();%0A %7D);%0A %7D);%0A %7D%0A
172c70f4a4cb857222bccf6501e13b2b65aa32cb
Switch to template literals
src/controllers/components/cart-panel.js
src/controllers/components/cart-panel.js
import { searchItem, checkIn, searchModel } from '../../lib/api-client'; import { Dispatcher } from 'consus-core/flux'; export default class CartController { static checkInItem(id, itemAddress) { return checkIn(id, itemAddress).then(item => { Dispatcher.handleAction('CHECKIN_SUCCESS', { itemAddress: item.itemAddress }); }).catch(error => { Dispatcher.handleAction('ERROR', { error }); }); } static getItem(address) { return searchItem(address).then(item => { if (item.status === 'CHECKED_OUT') return Dispatcher.handleAction('ERROR', { error: 'This item is already checked out by another student.' }); Dispatcher.handleAction("CHECKOUT_ITEM_FOUND", item); }); } static getModel(address) { return searchModel(address).then(model => { if (model.inStock <= 0) return Dispatcher.handleAction('ERROR', { error: 'All ' + model.name + 's have been checked out.' }); if(!model.allowCheckout) return Dispatcher.handleAction('ERROR', { error: model.name + ' is not available for checkout.' }); Dispatcher.handleAction("CHECKOUT_MODEL_FOUND", model); }); } static incrementModel(address) { return searchModel(address).then(model => { Dispatcher.handleAction("CHECKOUT_DUPLICATE_MODEL", model); }); } static throwError(error){ Dispatcher.handleAction("ERROR", { error }); } }
JavaScript
0
@@ -1081,17 +1081,15 @@ or: -' +%60 All -' + +$%7B mode @@ -1094,20 +1094,17 @@ del.name - + ' +%7D s have b @@ -1115,25 +1115,25 @@ checked out. -' +%60 %0A @@ -1263,16 +1263,19 @@ error: +%60$%7B model.na @@ -1280,12 +1280,9 @@ name - + ' +%7D is @@ -1308,17 +1308,17 @@ heckout. -' +%60 %0A
9c27717ffa0e85f770e2b7d78c71f789c8e968a4
rewrite to return only one object
src/services/user/services/AdminUsers.js
src/services/user/services/AdminUsers.js
/* eslint-disable no-param-reassign */ /* eslint-disable class-methods-use-this */ const { BadRequest, Forbidden } = require('@feathersjs/errors'); const logger = require('../../../logger'); const { createMultiDocumentAggregation } = require('../../consent/utils/aggregations'); const { userModel } = require('../model'); const roleModel = require('../../role/model'); const getCurrentUserInfo = (id) => userModel.findById(id) .select('schoolId') .populate('roles') .lean() .exec(); const getRoles = () => roleModel.find() .select('name') .lean() .exec(); const getAllUsers = async (ref, schoolId, schoolYearId, role, clientQuery = {}) => { const query = { schoolId, roles: role, schoolYearId, consentStatus: clientQuery.consentStatus, sort: clientQuery.$sort || clientQuery.sort, select: [ 'consentStatus', 'consent', 'classes', 'firstName', 'lastName', 'email', 'createdAt', 'importHash', 'birthday', ], skip: clientQuery.$skip || clientQuery.skip, limit: clientQuery.$limit || clientQuery.limit, }; if (clientQuery.classes) query.classes = clientQuery.classes; if (clientQuery.createdAt) query.createdAt = clientQuery.createdAt; if (clientQuery.firstName) query.firstName = clientQuery.firstName; if (clientQuery.lastName) query.lastName = clientQuery.lastName; return userModel.aggregate(createMultiDocumentAggregation(query)).option({ collation: { locale: 'de', caseLevel: true }, }).exec(); }; const getCurrentYear = (ref, schoolId) => ref.app.service('schools') .get(schoolId, { query: { $select: ['currentYear'] }, }) .then(({ currentYear }) => currentYear.toString()); class AdminUsers { constructor(role) { this.role = role || {}; this.docs = {}; this.rolesThatCanAccess = ['teacher', 'administrator', 'superhero']; } async find(params) { try { const { query, account } = params; const currentUserId = account.userId.toString(); // fetch base data const [currentUser, roles] = await Promise.all([getCurrentUserInfo(currentUserId), getRoles()]); // permission check if (!currentUser.roles.some((role) => this.rolesThatCanAccess.includes(role.name))) { throw new Forbidden(); } const { schoolId } = currentUser; const currentYear = await getCurrentYear(this, schoolId); // fetch data that are scoped to schoolId const searchedRole = roles.find((role) => role.name === this.role); return getAllUsers(this, schoolId, currentYear, searchedRole._id, query); } catch (err) { logger.error(err); if ((err || {}).code === 403) { throw new Forbidden('You have not the permission to execute this.', err); } throw new BadRequest('Can not fetch data.', err); } } setup(app) { this.app = app; } } module.exports = AdminUsers;
JavaScript
0.000451
@@ -588,21 +588,16 @@ async ( -ref, schoolId @@ -1324,16 +1324,49 @@ %0A%09return + new Promise((resolve, reject) =%3E userMod @@ -1483,16 +1483,83 @@ %7D).exec( +(err, res) =%3E %7B%0A%09%09if (err) reject(err);%0A%09%09else resolve(res%5B0%5D);%0A%09%7D) );%0A%7D;%0A%0Ac @@ -2525,22 +2525,16 @@ llUsers( -this, schoolId
02dc5a74186029e334e4160c82cdf764ff56320a
tweak motion speeds
src/sm-img-controls/helpers/animation.js
src/sm-img-controls/helpers/animation.js
const easings = simpla.constants.easings; export default { listeners: { 'activated': '_animateIn', 'deactivated': '_animateOut' }, get _animateControls() { return { top: this.$['controls-top'], bottom: this.$['controls-bottom'] }; }, get _animateOptions() { return { 'in': { easing: easings.easeOutBack, fill: 'both', duration: 150 }, 'out': { easing: easings.easeInCubic, fill: 'both', duration: 120 } }; }, _animateIn() { let { top, bottom } = this._animateControls, opts = this._animateOptions; this.toggleAttribute('visible', true, top); this.toggleAttribute('visible', true, bottom); top.animate([ { transform: 'translateY(-100%)' }, { transform: 'translateY(0)' } ], opts.in); bottom.animate([ { transform: 'translateY(100%)' }, { transform: 'translateY(0)' } ], opts.in); }, _animateOut() { let { top, bottom } = this._animateControls, opts = this._animateOptions, topAnimate, bottomAnimate; topAnimate = top.animate([ { transform: 'translateY(0)' }, { transform: 'translateY(-100%)' } ], opts.out); bottomAnimate = bottom.animate([ { transform: 'translateY(0)' }, { transform: 'translateY(100%)' } ], opts.out); topAnimate.onfinish = () => { this.toggleAttribute('visible', false, top); } bottomAnimate.onfinish = () => { this.toggleAttribute('visible', false, bottom); } } };
JavaScript
0.000001
@@ -401,9 +401,9 @@ n: 1 -5 +8 0%0A @@ -506,9 +506,9 @@ n: 1 -2 +0 0%0A
764aced388be388f7ab3af14cc310b6b26012020
update to routes
app/js/Routes.js
app/js/Routes.js
'use strict' import React from 'react' import { Router, Route, IndexRoute, browserHistory } from 'react-router' import App from './App' import HomePage from './pages/HomePage' import SummitPage from './pages/SummitPage' import PapersPage from './pages/PapersPage' import TalksPage from './pages/TalksPage' import ArticlePage from './pages/ArticlePage' import NotFoundPage from './pages/NotFoundPage' import AboutPage from './pages/AboutPage' import DocsPage from './pages/DocsPage' import BlogPage from './pages/BlogPage' import BrowserPage from './pages/BrowserPage' import IntroPage from './pages/IntroPage' import BlogPostPage from './pages/BlogPostPage' import CareersPage from './pages/CareersPage' import TalkPage from './pages/TalkPage' import SignUpPage from './pages/SignUpPage' import DevSignUpPage from './pages/DevSignUpPage' import DownloadPage from './pages/DownloadPage' import FAQPage from './pages/FAQPage' import TutorialsPage from './pages/TutorialsPage' import TutorialPage from './pages/TutorialPage' import AuthPage from './pages/AuthPage' import RoadmapPage from './pages/RoadmapPage' import TokenSalePage from './pages/TokenSalePage' import Summit2017Page from './pages/Summit2017Page' export default ( <Router history={browserHistory} onUpdate={() => window.scrollTo(0, 0)}> <Route path="/" component={App}> <IndexRoute component={HomePage} /> <Route path="/" component={HomePage} /> <Route path="/users" component={SignUpPage} /> <Route path="/developers" component={DevSignUpPage} /> <Route path="/install" component={DownloadPage} /> <Route path="/intro" component={IntroPage} /> <Route path="/tutorials" component={TutorialsPage} /> <Route path="/tutorials/:docSection" component={TutorialPage} /> <Route path="/blog" component={BlogPage} /> <Route path="/blog/:docSection" component={BlogPostPage} /> <Route path="/papers" component={PapersPage} /> <Route path="/videos" component={TalksPage} /> <Route path="/videos/:slug" component={TalkPage} /> <Route path="/about" component={AboutPage} /> <Route path="/faq" component={FAQPage} /> <Route path="/careers" component={CareersPage} /> <Route path="/docs" component={DocsPage} /> <Route path="/summit" component={SummitPage} /> <Route path="/browser" component={BrowserPage} /> <Route path="/posts/:docSection" component={ArticlePage} /> <Route path="/docs/:docSection" component={ArticlePage} /> <Route path="/auth" component={AuthPage} /> <Route path="/roadmap" component={RoadmapPage} /> <Route path="/token" component={TokenSalePage} /> <Route path="*" component={NotFoundPage} /> </Route> </Router> )
JavaScript
0
@@ -3120,32 +3120,94 @@ okenSalePage%7D /%3E +%0A %3CRoute path=%22/summit2017%22 component=%7BSummit2017Page%7D /%3E %0A%0A %3CRoute p
b98a8d2e151c7c1db432bebee4ca191f63b1f960
Revert whitespace
app/lib/slack.js
app/lib/slack.js
/* * Slack message sending logic */ const Slack = require('node-slack'); const config = require('config'); const activities = require('../constants/activities'); module.exports = { /* * Post a given activity to Slack */ postActivity: function(activity) { obj = this.formatActivity(activity); this.postMessage(obj.msg, obj.attachmentArray); }, /* * Formats an activity based on the type to show in Slack */ formatActivity: function(activity) { var returnVal = ''; var attachmentArray = []; // declare common variables used across multiple activity types var userString = ''; var groupName = ''; var publicUrl = ''; var amount = null; var recurringAmount = null; var currency = ''; var tags = []; var description = ''; var linkifyTwitter = ''; var linkifyWebsite = ''; var eventType = ''; // get user data if (activity.data.user) { const userName = activity.data.user.username; const userEmail = activity.data.user.email; userString = userName ? userName + ' (' + userEmail + ')' : userEmail; const twitterHandle = activity.data.user.twitterHandle; linkifyTwitter = this.linkifyForSlack('http://www.twitter.com/'+twitterHandle, '@'+twitterHandle); linkifyWebsite = this.linkifyForSlack(activity.data.user.websiteUrl, null); } // get group data if (activity.data.group) { groupName = activity.data.group.name; publicUrl = activity.data.group.publicUrl; } // get transaction data if (activity.data.transaction) { amount = activity.data.transaction.amount; const interval = activity.data.transaction.interval; recurringAmount = amount + (interval ? '/' + interval : ''); currency = activity.data.transaction.currency; tags = JSON.stringify(activity.data.transaction.tags); description = activity.data.transaction.description; } // get event data if (activity.data.event) { eventType = activity.data.event.type; } switch (activity.type) { // Currently used for both new donation and expense case activities.GROUP_TRANSANCTION_CREATED: if (activity.data.transaction.isDonation) { // Ex: Aseem gave 1 USD/month to WWCode-Seattle returnVal += `Woohoo! ${userString} gave ${currency} ${recurringAmount} to ${this.linkifyForSlack(publicUrl, groupName)}!`; } else if (activity.data.transaction.isExpense) { // Ex: Aseem submitted a Foods & Beverage expense to WWCode-Seattle: USD 12.57 for 'pizza' returnVal += `Hurray! ${userString} submitted a ${tags} expense to ${this.linkifyForSlack(publicUrl, groupName)}: ${currency} ${amount} for ${description}!` } break; case activities.GROUP_TRANSANCTION_PAID: // Ex: Jon approved a transaction for WWCode-Seattle: USD 12.57 for 'pizza'; returnVal += `Expense approved on ${this.linkifyForSlack(publicUrl, groupName)}: ${currency} ${amount} for '${description}'`; break; case activities.USER_CREATED: // Ex: New user joined: Alice Walker ([email protected]) | @alicewalker | websiteUrl returnVal += `New user joined: ${userString} | ${linkifyTwitter} | ${linkifyWebsite}`; break; case activities.WEBHOOK_STRIPE_RECEIVED: returnVal += `Stripe event received: ${eventType}`; attachmentArray.push({title: 'Data', text: activity.data}); break; case activities.SUBSCRIPTION_CONFIRMED: // Ex: Confirmed subscription of 1 USD/month from Aseem to WWCode-Seattle! returnVal += `Yay! Confirmed subscription of ${currency} ${recurringAmount} from ${userString} to ${this.linkifyForSlack(publicUrl, groupName)}!`; break; default: returnVal += `Oops... I got an unknown activity type: ${activity.type}`; } return {msg: returnVal, attachmentArray: attachmentArray}; }, /* * Posts a message on slack */ postMessage: function(msg, attachmentArray, channel){ const slack = new Slack(config.slack.hookUrl,{}); return slack.send({ text: msg, channel: channel || config.slack.activityChannel, username: 'ActivityBot', icon_emoji: ':raising_hand:', attachments: attachmentArray || [] }) .catch((err)=>{ console.error(err); }); }, /** * Generates a url for Slack */ linkifyForSlack: function(link, text){ if (link && !text) { text = link; } else if (!link && text) { return text; } else if (!link && !text){ return ''; } return `<${link}|${text}>`; } }
JavaScript
0.000004
@@ -4016,11 +4016,8 @@ */%0A - %0A po
6d2b159ba0cd4c313f88321160c59504f40a0b18
add list cache
app/listcache.js
app/listcache.js
caches.open("$$$toolbox-cache$$$https://civic-data.github.io/opengov/$$$").then(function(x) { console.log(x.keys()); return x.keys(); }).then(function(z) { console.log(z); }) caches.keys().then(function(key){ caches.open(key).then(function(x) { //console.log(x.keys()); return x; }) }).then(function(z) { console.log(z); }) caches.keys().then(function(keys){ console.log('keys:',keys); for (String key: keys){ caches.open(key).then(function(x) { console.log('keys',x.keys()); return x.keys(); }) } }).then(function(z) { console.log('z',z); }) caches.open("$$$toolbox-cache$$$https://civic-data.github.io/opengov/$$$").then(function(x){console.log(x.keys()); return x.keys();}).then(function(z){console.log(z);}) caches.open("$$$toolbox-cache$$$https://civic-data.github.io/opengov/$$$").then(function(x) { console.log('keys:',x.keys()); return x.keys(); }).then(function(z) { console.log('z',z); }) caches.keys().then(function(response){ console.log('111:keys',typeof response); console.log('111:keys',response); response.forEach(function(element, index, array) { //cache.delete(element); console.log('element',element,index,array); }); caches.open(keys[0]).then(function(x) { console.log('keys',x.keys()); return x.keys(); }) }).then(function(z) { console.log('z',z); }) caches.keys().then(function(response) { console.log('111:keys', typeof response); console.log('111:keys', response); response.forEach(function(element, index, array) { //cache.delete(element); console.log('element', element, index, array); caches.open(element).then(function(x) { console.log('keys', x.keys()); return x.keys(); }).then(function(z) { console.log('z', element, z); }) }) }); caches.keys().then(function(response) { console.log('111:keys', typeof response); console.log('111:keys', response); response.forEach(function(element, index, array) { //cache.delete(element); console.log('element', element, index, array.length, array); caches.open(element).then(function(x) { console.log('keys', x.keys()); return x.keys(); }).then(function(z) { console.log('z', element, z); z.forEach(function(element, index, array) { console.log('z1', element, element.url, index, array.length); }) }) }) });
JavaScript
0.000001
@@ -2462,24 +2462,562 @@ %7D)%0A %7D)%0A %7D)%0A%7D);%0A +%0Acaches.keys().then(function(response) %7B%0A response.forEach(function(element, index, array) %7B%0A caches.open(element).then(function(x) %7B%0A return x.keys();%0A %7D).then(function(items) %7B%0A items.forEach(function(element, index, array) %7B%0A //console.log('item', element, element.url, index, array.length);%0A var div = document.createElement('div');%0A div.innerHTML='%3Ca href=%22'+element.url+'%22%3E'+element.url+'%3C/a%3E';%0A document.body.appendChild(div);%0A %7D)%0A %7D)%0A %7D)%0A%7D);%0A
a48ef6932d71541c14001713d079f984d1070317
Add global tools to an element when it's enabled
src/store/internals/addEnabledElement.js
src/store/internals/addEnabledElement.js
import { mouseEventListeners, mouseWheelEventListeners, touchEventListeners } from '../../eventListeners/index.js'; import { imageRenderedEventDispatcher, mouseToolEventDispatcher, newImageEventDispatcher, touchToolEventDispatcher } from '../../eventDispatchers/index.js'; import store from '../index.js'; /** * Element Enabled event. * * @event Cornerstone#ElementEnabled * @type {Object} * @property {string} type * @property {Object} detail * @property {HTMLElement} detail.element - The element being enabled. */ /* TODO: It would be nice if this automatically added "all tools" * To the enabledElement that already exist on all other tools. * A half-measure might be a new method to "duplicate" the tool * Configuration for an existing enabled element * We may need to also save/store the original class/constructor per tool * To accomplish this */ /** * Adds an enabledElement to our store. * @export @private @method * @name addEnabledElement * @param {Cornerstone#ElementEnabled} elementEnabledEvt * @listens Cornerstone#ElementEnabled */ export default function (elementEnabledEvt) { const enabledElement = elementEnabledEvt.detail.element; // Dispatchers imageRenderedEventDispatcher.enable(enabledElement); newImageEventDispatcher.enable(enabledElement); // Mouse if (store.modules.globalConfiguration.state.mouseEnabled) { mouseEventListeners.enable(enabledElement); mouseWheelEventListeners.enable(enabledElement); mouseToolEventDispatcher.enable(enabledElement); } // Touch if (store.modules.globalConfiguration.state.touchEnabled) { touchEventListeners.enable(enabledElement); touchToolEventDispatcher.enable(enabledElement); } // State _addEnabledElmenet(enabledElement); } /** * Adds the enabled element to the store. * @private @method * @param {HTMLElement} enabledElement */ const _addEnabledElmenet = function (enabledElement) { store.state.enabledElements.push(enabledElement); if (store.modules) { _initModulesOnElement(enabledElement); } }; /** * Iterate over our store's modules. If the module has an `enabledElementCallback` * call it and pass it a reference to our enabled element. * @private @method * @param {Object} enabledElement */ function _initModulesOnElement (enabledElement) { const modules = store.modules; Object.keys(modules).forEach(function (key) { if (typeof modules[key].enabledElementCallback === 'function') { modules[key].enabledElementCallback(enabledElement); } }); }
JavaScript
0
@@ -276,24 +276,77 @@ /index.js';%0A +import %7B addToolForElement %7D from './../addTool.js';%0A import store @@ -2107,16 +2107,60 @@ t);%0A %7D%0A + _addGlobalToolsToElement(enabledElement);%0A %7D;%0A%0A/**%0A @@ -2630,12 +2630,265 @@ %7D%0A %7D);%0A%7D%0A +%0Afunction _addGlobalToolsToElement (enabledElement) %7B%0A Object.keys(store.state.globalTools).forEach(function (key) %7B%0A const %7B tool, configuration %7D = store.state.globalTools%5Bkey%5D;%0A%0A addToolForElement(enabledElement, tool, configuration);%0A %7D);%0A%7D%0A
5d329062de1f903a05bb83101d81e4543cf993f6
Fix gulp server root (for some reason started defaulting to dist)
cu-build.config.js
cu-build.config.js
/** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ var name = 'cu-patcher-ui'; var config = { type: 'module', path: __dirname, name: name, bundle: { copy: [ 'src/**/!(*.js|*.jsx|*.ts|*.tsx|*.ui|*.styl|*.scss)', 'src/include/**' ] } }; // load user config and merge it with default config if it exists var extend = require('extend'); var fs = require('fs'); var userConfig = {}; if (fs.existsSync(__dirname + '/user-cu-build.config.js')) { userConfig = require(__dirname + '/user-cu-build.config.js'); } config = extend(true, config, userConfig); module.exports = config;
JavaScript
0
@@ -412,16 +412,91 @@ '%0A %5D%0A + %7D,%0A server: %7B%0A root: __dirname + %22/publish/interface/cu-patcher-ui/%22%0A %7D%0A%7D;%0A%0A
ffb1bfd3f0595c794a03b4385d56d1be45dd34f3
Fix examples
src/configs/examples.js
src/configs/examples.js
export const rao2014Gm12878Mbol1kbMresChr22Loops = { name: 'Loops in chromosome 22 of GM12878', data: 'Rao et al. (2014) GM12878 Mbol 1kb', url: 'https://rawgit.com/flekschas/8b0163f25fd4ffb067aaba2a595da447/raw/rao-2014-gm12878-mbol-1kb-mres-chr22-loops.json' }; export const rao2014Gm12878Mbol1kbMresChr4Tads = { name: 'TADs in chromosome 4 of GM12878', data: 'Rao et al. (2014) GM12878 Mbol 1kb', url: 'https://rawgit.com/flekschas/37b6293b82b5b3e5fb56de9827100797/raw/rao-2014-gm12878-mbol-1kb-mres-chr4-tads.json' }; export const rao2014Gm12878Mbol1kbMresTelomeres = { name: 'Telomere contacts of GM2878', data: 'Rao et al. (2014) GM12878 Mbol 1kb', url: 'https://rawgit.com/flekschas/3700ffa02aac69b52a2b10300299f967/raw/rao-2014-gm12878-mbol-1kb-mres-telomeres.json' }; export const rao2014Gm12878VsK562Mbol1kbMresTelomeres = { name: 'Telomere contacts of GM12878 vs K562', data: 'Rao et al. (2014) GM12878 and K562 Mbol 1kb', url: 'https://rawgit.com/flekschas/a397dded3694fc3984c6acdae6a837fd/raw/rao-2014-gm12878-vs-k562-mbol-1kb-mres-telomeres.json' }; export default [ rao2014Gm12878Mbol1kbMresChr22Loops, rao2014Gm12878Mbol1kbMresChr4Tads, rao2014Gm12878Mbol1kbMresTelomeres, rao2014Gm12878VsK562Mbol1kbMresTelomeres ];
JavaScript
0.000108
@@ -145,37 +145,53 @@ url: 'https:// -rawgi +gist.githubuserconten t.com/flekschas/ @@ -223,24 +223,65 @@ 95da447/raw/ +12316079e1adb63450ad38e21fdb51950440e917/ rao-2014-gm1 @@ -310,16 +310,29 @@ 22-loops +-hipiler-v140 .json'%0A%7D @@ -482,37 +482,53 @@ url: 'https:// -rawgi +gist.githubuserconten t.com/flekschas/ @@ -560,24 +560,65 @@ 7100797/raw/ +9d6f05d5b4dc783560337772a203d66f30a068aa/ rao-2014-gm1 @@ -645,16 +645,29 @@ hr4-tads +-hipiler-v140 .json'%0A%7D @@ -814,37 +814,53 @@ url: 'https:// -rawgi +gist.githubuserconten t.com/flekschas/ @@ -892,24 +892,65 @@ 299f967/raw/ +f0b93a08d0b3f2d7c7a6bcca31b502f1234d235e/ rao-2014-gm1 @@ -969,32 +969,45 @@ b-mres-telomeres +-hipiler-v140 .json'%0A%7D;%0A%0Aexpor @@ -1182,13 +1182,29 @@ s:// -rawgi +gist.githubuserconten t.co @@ -1252,16 +1252,57 @@ 7fd/raw/ +021bd894b0d84df8df05e65b442669b39f17b7c7/ rao-2014 @@ -1341,16 +1341,29 @@ elomeres +-hipiler-v140 .json'%0A%7D
5ff974986821c8c22aae508b5298afcc90b92af5
Reimplement changing entry value
src/container/ledger.js
src/container/ledger.js
import React, { Component } from 'react'; import style from './ledger.css'; import BookDateEntry from '../component/bookDateEntry'; import BookEntry from '../component/bookEntry'; import CachedForm from '../component/cachedForm'; import SearchBox from '../component/searchBox'; export default class Ledger extends Component { constructor(props) { super(props); this.state = { entries: Array.from({ length: 5 }).map(() => ({ id: '01234567', date: Date.now(), accounts: [ { id: '0abcd', value: 105400, note: '갸아악' }, { id: '0cdef', value: -236789, note: '' }, ], summary: '버튼 잘못 눌러서 돈 나감', })), accounts: { '0abcd': { id: '0abcd', name: '잡손실', type: 'expense', currency: 'KRW', // Current value is not known at the moment }, '0cdef': { id: '0cdef', name: '보통예금', type: 'asset', currency: 'KRW', }, }, selectedId: -1, selectedActive: false, // Maybe we need to use immutable.js? editingIds: {}, }; } handleEntryChange(value) { this.setState({ entry: value }); } handleEntryStatus(id, { edited }) { const { selectedId, editingIds } = this.state; if (selectedId !== id && !edited) { // Remove itself from editingIds // TODO Actually remove it this.setState({ editingIds: Object.assign({}, editingIds, { [id]: null, }), }); } if (selectedId === id) { this.setState({ selectedActive: edited }); } } handleEntrySelect(id) { const { selectedId, selectedActive, editingIds } = this.state; if (id === selectedId) return; this.setState({ selectedId: id, selectedActive: false, editingIds: Object.assign({}, editingIds, { [id]: true, [selectedId]: selectedActive, }), }); } render() { const { accounts, entries, selectedId, editingIds } = this.state; const renderAccountList = (account, onSelect) => ( <SearchBox selectedId={account.id} onSelect={onSelect} data={Object.keys(accounts).map(v => accounts[v])} /> ); return ( <div className={style.ledger}> <BookDateEntry date={Date.now()}> { entries.map((v, i) => ( <li key={i}> <CachedForm onChange={this.handleEntryChange.bind(this, i)} onStatus={this.handleEntryStatus.bind(this, i)} value={Object.assign({}, v, { accounts: v.accounts.map(info => Object.assign({}, info, { account: accounts[info.id] })), })} > <BookEntry focus={i === selectedId} editing={!!editingIds[i]} onSelect={this.handleEntrySelect.bind(this, i)} renderAccountList={renderAccountList} /> </CachedForm> </li> )) } </BookDateEntry> </div> ); } }
JavaScript
0
@@ -1159,16 +1159,20 @@ yChange( +id, value) %7B @@ -1180,36 +1180,123 @@ -this.setState(%7B entry: value +const %7B entries %7D = this.state;%0A this.setState(%7B%0A entries: entries.map((v, i) =%3E i === id ? value : v),%0A %7D);
74742b701bca088b0bf3834769dd10890d9d20e8
Update FontWatcher annotations.
src/core/fontwatcher.js
src/core/fontwatcher.js
goog.provide('webfont.FontWatcher'); goog.require('webfont.FontWatchRunner'); /** * @constructor * @param {webfont.UserAgent} userAgent * @param {webfont.DomHelper} domHelper * @param {webfont.EventDispatcher} eventDispatcher * @param {Object.<string, function(Object): webfont.Size>} fontSizer */ webfont.FontWatcher = function(userAgent, domHelper, eventDispatcher, fontSizer) { this.domHelper_ = domHelper; this.eventDispatcher_ = eventDispatcher; this.fontSizer_ = fontSizer; this.currentlyWatched_ = 0; this.last_ = false; this.success_ = false; this.hasWebKitFallbackBug_ = userAgent.getBrowserInfo().hasWebKitFallbackBug(); }; /** * @type {string} * @const */ webfont.FontWatcher.DEFAULT_VARIATION = 'n4'; goog.scope(function () { var FontWatcher = webfont.FontWatcher; /** * Watches a set of font families. * @param {Array.<string>} fontFamilies The font family names to watch. * @param {Object.<string, Array.<string>>} fontDescriptions The font variations * of each family to watch. Described with FVD. * @param {Object.<string, string>} fontTestStrings The font test strings for * each family. * @param {function(new:webfont.FontWatchRunner, function(string, string), * function(string, string), webfont.DomHelper, * Object.<string, function(Object): number>, * string, string, boolean, Object.<string,boolean>=, string=)} fontWatchRunnerCtor The font watch runner constructor. * @param {boolean} last True if this is the last set of families to watch. */ FontWatcher.prototype.watch = function(fontFamilies, fontDescriptions, fontTestStrings, fontWatchRunnerCtor, last) { var length = fontFamilies.length; if (length === 0) { this.eventDispatcher_.dispatchInactive(); return; } for (var i = 0; i < length; i++) { var fontFamily = fontFamilies[i]; if (!fontDescriptions[fontFamily]) { fontDescriptions[fontFamily] = [webfont.FontWatcher.DEFAULT_VARIATION]; } this.currentlyWatched_ += fontDescriptions[fontFamily].length; } if (last) { this.last_ = last; } for (var i = 0; i < length; i++) { var fontFamily = fontFamilies[i]; var descriptions = fontDescriptions[fontFamily]; var fontTestString = fontTestStrings[fontFamily]; for (var j = 0, len = descriptions.length; j < len; j++) { var fontDescription = descriptions[j]; this.eventDispatcher_.dispatchFontLoading(fontFamily, fontDescription); var activeCallback = goog.bind(this.fontActive_, this); var inactiveCallback = goog.bind(this.fontInactive_, this) var fontWatchRunner = new fontWatchRunnerCtor(activeCallback, inactiveCallback, this.domHelper_, this.fontSizer_, fontFamily, fontDescription, this.hasWebKitFallbackBug_, null, fontTestString); fontWatchRunner.start(); } } }; /** * Called by a FontWatchRunner when a font has been detected as active. * @param {string} fontFamily * @param {string} fontDescription * @private */ FontWatcher.prototype.fontActive_ = function(fontFamily, fontDescription) { this.eventDispatcher_.dispatchFontActive(fontFamily, fontDescription); this.success_ = true; this.decreaseCurrentlyWatched_(); }; /** * Called by a FontWatchRunner when a font has been detected as inactive. * @param {string} fontFamily * @param {string} fontDescription * @private */ FontWatcher.prototype.fontInactive_ = function(fontFamily, fontDescription) { this.eventDispatcher_.dispatchFontInactive(fontFamily, fontDescription); this.decreaseCurrentlyWatched_(); }; /** * @private */ FontWatcher.prototype.decreaseCurrentlyWatched_ = function() { if (--this.currentlyWatched_ == 0 && this.last_) { if (this.success_) { this.eventDispatcher_.dispatchActive(); } else { this.eventDispatcher_.dispatchInactive(); } } }; });
JavaScript
0
@@ -1335,14 +1335,20 @@ t): -number +webfont.Size %3E,%0A @@ -1395,16 +1395,17 @@ %3Cstring, + boolean%3E
edb5a75d43630b9902e4d6727e03a478657bc6a8
Update docstring in `get_choropleth_color.js`
src/utils/colors/get_choropleth_color.js
src/utils/colors/get_choropleth_color.js
/** compute getColor func special for choropleths * * @param color - * an Array, this will compute a d3 scaleQuantile * a callable - will just return as is **/ export default ({ color, features, yCol }) => { if (typeof color === 'function') return color else { const domain = d3.extent(features, d => d[yCol]) return d3.scaleQuantile() .domain(domain) .range(color) } }
JavaScript
0
@@ -1,9 +1,8 @@ -%0A /** comp @@ -64,16 +64,56 @@ color -%0A + * a callable - will just return as is%0A * an A @@ -159,48 +159,8 @@ ile%0A - * a callable - will just return as is%0A **/%0A
d4a9f191b16338aea350245537e4a635a5db359d
Add description and mark private methods
src/widgets/TextInputMenuSelectWidget.js
src/widgets/TextInputMenuSelectWidget.js
/** * Menu for a text input widget. * * This menu is specially designed to be positioned beneath a text input widget. The menu's position * is automatically calculated and maintained when the menu is toggled or the window is resized. * * @class * @extends OO.ui.MenuSelectWidget * * @constructor * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for * @param {Object} [config] Configuration options * @cfg {jQuery} [$container=input.$element] Element to render menu under */ OO.ui.TextInputMenuSelectWidget = function OoUiTextInputMenuSelectWidget( inputWidget, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( inputWidget ) && config === undefined ) { config = inputWidget; inputWidget = config.inputWidget; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.TextInputMenuSelectWidget.super.call( this, config ); // Properties this.inputWidget = inputWidget; this.$container = config.$container || this.inputWidget.$element; this.onWindowResizeHandler = this.onWindowResize.bind( this ); // Initialization this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.TextInputMenuSelectWidget, OO.ui.MenuSelectWidget ); /* Methods */ /** * Handle window resize event. * * @param {jQuery.Event} e Window resize event */ OO.ui.TextInputMenuSelectWidget.prototype.onWindowResize = function () { this.position(); }; /** * @inheritdoc */ OO.ui.TextInputMenuSelectWidget.prototype.toggle = function ( visible ) { visible = visible === undefined ? !this.isVisible() : !!visible; var change = visible !== this.isVisible(); if ( change && visible ) { // Make sure the width is set before the parent method runs. // After this we have to call this.position(); again to actually // position ourselves correctly. this.position(); } // Parent method OO.ui.TextInputMenuSelectWidget.super.prototype.toggle.call( this, visible ); if ( change ) { if ( this.isVisible() ) { this.position(); $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler ); } else { $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler ); } } return this; }; /** * Position the menu. * * @chainable */ OO.ui.TextInputMenuSelectWidget.prototype.position = function () { var $container = this.$container, pos = OO.ui.Element.static.getRelativePosition( $container, this.$element.offsetParent() ); // Position under input pos.top += $container.height(); this.$element.css( pos ); // Set width this.setIdealSize( $container.width() ); // We updated the position, so re-evaluate the clipping state this.clip(); return this; };
JavaScript
0.000001
@@ -4,54 +4,49 @@ %0A * -Menu for a text input widget.%0A *%0A * Th +TextInputMenuSelectWidget is +a menu +that is s @@ -87,18 +87,50 @@ beneath - a +%0A * a %7B@link OO.ui.TextInputWidget text in @@ -132,23 +132,23 @@ xt input - widget +%7D field . The me @@ -160,19 +160,16 @@ position -%0A * is auto @@ -177,16 +177,19 @@ atically +%0A * calcula @@ -258,16 +258,93 @@ esized.%0A + * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.%0A *%0A * @c @@ -1454,24 +1454,36 @@ e event.%0A *%0A + * @private%0A * @param %7Bj @@ -2420,19 +2420,31 @@ e menu.%0A - *%0A + * @private%0A * @chai
c120555b6b36bd4b54a19de8761208d4e506f9af
update jsdoc.js (#378)
packages/google-cloud-language/.jsdoc.js
packages/google-cloud-language/.jsdoc.js
// 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. // 'use strict'; module.exports = { opts: { readme: './README.md', package: './package.json', template: './node_modules/jsdoc-fresh', recurse: true, verbose: true, destination: './docs/' }, plugins: [ 'plugins/markdown', 'jsdoc-region-tag' ], source: { excludePattern: '(^|\\/|\\\\)[._]', include: [ 'build/src' ], includePattern: '\\.js$' }, templates: { copyright: 'Copyright 2018 Google, LLC.', includeDate: false, sourceFiles: false, systemName: '@google-cloud/language', theme: 'lumen' }, markdown: { idInHeadings: true } };
JavaScript
0
@@ -1040,9 +1040,9 @@ 201 -8 +9 Goo @@ -1161,16 +1161,71 @@ 'lumen' +,%0A default: %7B%0A %22outputSourceFiles%22: false%0A %7D %0A %7D,%0A
03e97267522321f16ac836bf0422774349e0f20e
add EE plugins to watchlist
grunt/config/watch.js
grunt/config/watch.js
module.exports = function(config, watchConf) { 'use strict'; var options = { livereload: false }; watchConf.cockpit_assets = { options: options, files: [ '<%= pkg.gruntConfig.cockpitSourceDir %>/{fonts,images}/**/*', '<%= pkg.gruntConfig.cockpitSourceDir %>/scripts/index.html', '<%= pkg.gruntConfig.cockpitSourceDir %>/scripts/favicon.ico' ], tasks: [ 'copy:cockpit_assets', 'copy:cockpit_index' ] }; watchConf.cockpit_styles = { options: options, files: [ '<%= pkg.gruntConfig.cockpitSourceDir %>/../node_modules/camunda-commons-ui/lib/**/*.less', '<%= pkg.gruntConfig.cockpitSourceDir %>/../node_modules/camunda-commons-ui/resources/less/**/*.less', '<%= pkg.gruntConfig.cockpitSourceDir %>/styles/**/*.{css,less}', '<%= pkg.gruntConfig.cockpitSourceDir %>/scripts/**/*.{css,less}' ], tasks: [ 'less:cockpit_styles' ] }; watchConf.cockpit_scripts = { options: options, files: [ '<%= pkg.gruntConfig.cockpitSourceDir %>/scripts/**/*.{js,html,json}' ], tasks: [ 'requirejs:cockpit_scripts' ] }; watchConf.cockpit_dependencies = { options: options, files: [ '<%= pkg.gruntConfig.cockpitSourceDir %>/../node_modules/camunda-commons-ui/lib/**/*.{js,html}', '<%= pkg.gruntConfig.cockpitSourceDir %>/../node_modules/camunda-commons-ui/{resources,lib/*}/locales/**/*.json', '<%= pkg.gruntConfig.cockpitSourceDir %>/../node_modules/camunda-commons-ui/node_modules/camunda-bpm-sdk-js/dist/**/*.js', ], tasks: [ 'requirejs:cockpit_scripts' ] }; watchConf.cockpit_dist = { options: { cwd: '<%= pkg.gruntConfig.cockpitBuildTarget %>/', livereload: config.livereloadPort || false }, files: '**/*.{css,html,js}' }; };
JavaScript
0
@@ -1635,24 +1635,139 @@ t/**/*.js',%0A + '../../camunda-bpm-platform-ee/webapps/camunda-webapp/plugins/target/classes/plugin-webapp/**/*.%7Bjs,html%7D'%0A %5D,%0A
fe752be0c1f02be11ae2feb53b4e730fee9d9d42
Update maxBuffer limit to 100Mib
packages/grpc-tools/bin/protoc_plugin.js
packages/grpc-tools/bin/protoc_plugin.js
#!/usr/bin/env node /* * * Copyright 2015 gRPC 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. * */ /** * This file is required because package.json cannot reference a file that * is not distributed with the package, and we use node-pre-gyp to distribute * the plugin binary */ 'use strict'; var path = require('path'); var execFile = require('child_process').execFile; var exe_ext = process.platform === 'win32' ? '.exe' : ''; var plugin = path.resolve(__dirname, 'grpc_node_plugin' + exe_ext); var child_process = execFile(plugin, process.argv.slice(2), {encoding: 'buffer', maxBuffer: 1024 * 1000}, function(error, stdout, stderr) { if (error) { throw error; } }); process.stdin.pipe(child_process.stdin); child_process.stdout.pipe(process.stdout); child_process.stderr.pipe(process.stderr);
JavaScript
0.000001
@@ -1123,16 +1123,22 @@ 024 * 10 +24 * 1 00%7D, fun
e8982dc47fccac3b0b96130ceaa534d5a8fc5c69
fix build progress
app/util/util.js
app/util/util.js
const type = obj => obj ? Object.prototype.toString.call(obj).slice(8, -1).toLowerCase() : 'undefined'; const trim = (str, chars = '\\s') => ('' + str).replace(new RegExp(`(^${chars}+)|(${chars}+$)`, 'g'), ''); const ltrim = (str, chars = '\\s') => ('' + str).replace(new RegExp(`^${chars}+`), ''); const rtrim = (str, chars = '\\s') => ('' + str).replace(new RegExp(`${chars}+$`), ''); const rand = (max, min = 0) => Math.floor(Math.random() * (max - min + 1) + min); const ucfirst = (s) => s.toLowerCase().replace(/\b([a-z])/gi, c => c.toUpperCase()); function isNumber (v) { if (typeof v === 'number') return true; if (typeof v !== 'string') return false; return (/^[\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?$/).test(v); } function formatNumber (num) { num = Math.round(0 + num * 100) / 100; return num.toLocaleString('en-GB', { minimumFractionDigits: 2 }); } function serialize (obj) { const keys = Object.keys(obj); if (!keys || !keys.length) return ''; return '?' + keys.reduce((a, k) => { a.push(k + '=' + encodeURIComponent(obj[k])); return a; }, []).join('&'); } function varToRealType (v) { if (isNumber(v)) { let originalv = v; v = parseFloat('' + v); if (('' + v) !== originalv) v = originalv; } else if (v === 'true') v = true; else if (v === 'false') v = false; if (v === '') v = undefined; if (type(v) === 'array') v = v.map(val => varToRealType(val)); return v; } function isObjectEmpty (x) { if (!x || typeof x !== 'object') return true; return Object.keys(x).length === 0; } function sanitize (v) { const div = document.createElement('DIV'); div.innerHTML = v || ''; return div.textContent || div.innerText || ''; } function fuzzy (hay, s) { s = ('' + s).toLowerCase(); hay = ('' + hay).toLowerCase(); let n = -1; for (let l of s) if (!~(n = hay.indexOf(l, n + 1))) return false; return true; } function parseUrl (url) { let urlt; try { urlt = new URL(url); } catch (e) { urlt = null; } return urlt; } function prettyDate (time) { const date = new Date((time || '').replace(/-/g, '/').replace(/[TZ]/g, ' ')); const diff = (((new Date()).getTime() - date.getTime()) / 1000); const day_diff = Math.floor(diff / 86400); if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) return date.toLocaleString(); return day_diff === 0 && ( diff < 60 && 'just now' || diff < 120 && '1 minute ago' || diff < 3600 && Math.floor(diff / 60) + ' minutes ago' || diff < 7200 && '1 hour ago' || diff < 86400 && Math.floor(diff / 3600) + ' hours ago' ) || day_diff === 1 && 'Yesterday' || day_diff < 7 && day_diff + ' days ago' || day_diff < 31 && Math.ceil(day_diff / 7) + ' weeks ago'; } function injectCSS (webview, path) { const readFile = require('fs').readFileSync; let css; try { css = readFile(path, 'utf8'); } catch (e) { css = ''; } webview[0].send('injectCss', css); } module.exports = { fuzzy, ltrim, rtrim, trim, ucfirst, type, rand, isNumber, formatNumber, varToRealType, isObjectEmpty, sanitize, serialize, parseUrl, months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], prettyDate, injectCSS, };
JavaScript
0
@@ -488,17 +488,24 @@ (s) =%3E -s +('' + s) .toLower
359b6c4f006a42e5c1ada2342b209f5f8d6854be
remove ramda on addFileTransport and change file log options variable name
server/utils/logging.js
server/utils/logging.js
const fs = require('fs') const winston = require('winston') const DailyRotateFile = require('winston-daily-rotate-file') const Stomp = require('stomp-client') const util = require('util') const R = require('ramda') const misc = require('./misc') const format = winston.format const path = require('path') const dir = process.env.NODE_LOGGING_DIR || path.join(__dirname, 'logs') const defaultLogOptions = { filename: dir + '/passport-%DATE%.log', handleExceptions: true, datePattern: 'YYYY-MM-DD', maxSize: '20m' } const flogOpts = { filename: dir + '/passport.log', maxSize: defaultLogOptions.maxSize, maxFiles: 5, options: { flags: 'w' } } const logger = winston.createLogger({ exitOnError: false, format: format.combine( format.splat(), format.padLevels(), format.timestamp(), format.printf(info => `${info.timestamp} [${info.level.toUpperCase()}] ${info.message}`) ) }) logger.stream = { write: (message) => log2('info', message.trim()) } let transport, fileTransport, consoleTransport let MQDetails, stompClient let prevConfigHash = 0 if (!fs.existsSync(dir)) { fs.mkdirSync(dir) } function addFileTransport (level) { fileTransport = new winston.transports.File(R.assoc('level', level, flogOpts)) logger.add(fileTransport, {}, true) } function configure (cfg) { const h = misc.hash(cfg) // Only makes recomputations if config data changed if (h !== prevConfigHash) { prevConfigHash = h const level = cfg.level || 'info' // Remove console log + rotary file transports R.forEach(l => logger.remove(l), R.filter(R.complement(R.isNil), [transport, consoleTransport])) if (R.propEq('consoleLogOnly', true, cfg)) { consoleTransport = new winston.transports.Console({ level: level }) logger.add(consoleTransport, {}, true) if (fileTransport) { logger.remove(fileTransport) fileTransport = undefined } } else { if (fileTransport) { fileTransport.level = level } else { addFileTransport(level) } transport = new DailyRotateFile(R.assoc('level', level, defaultLogOptions)) // eslint-disable-next-line no-unused-vars transport.on('rotate', function (oldFilename, newFilename) { // remove method flushes passport.log file logger.remove(fileTransport) addFileTransport(level) }) logger.add(transport, {}, true) } if (R.pathEq(['activeMQConf', 'enabled'], true, cfg)) { const mqSetUp = cfg.activeMQConf MQDetails = { CLIENT_QUEUE_NAME: 'oauth2.audit.logging', host: mqSetUp.host, port: mqSetUp.port, user: mqSetUp.username, password: mqSetUp.password, protocolVersion: '1.1', reconnectOpts: { retries: 10, delay: 5000 } } stompClient = new Stomp(MQDetails) stompClient.connect( // eslint-disable-next-line no-unused-vars sessionId => logger.info('Connected to STOMP server') //, The error callback is called successively until the connection succeeds... // e => logger.error(`Error connecting to STOMP server: ${e.message}`) ) } else { MQDetails = undefined if (stompClient) { stompClient.disconnect(() => { logger.info('Disconnected from STOMP server') }) } } log2('info', 'Loggers reconfigured') } } function sendMQMessage (msg) { if (MQDetails) { stompClient.publish('/' + MQDetails.CLIENT_QUEUE_NAME, msg) } } function log2 (level, msg) { // npm log levels (https://github.com/winstonjs/winston#logging-levels) const levels = ['error', 'warn', 'info', 'verbose', 'debug', 'silly'] level = level.toLowerCase() level = R.includes(level, levels) ? level : 'info' msg = msg || '' // Convert arguments to a real array (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments#Description) const args = [].slice.call(arguments) args[0] = level args[1] = msg // Log it to winston logger logger.log.apply(logger, args) // Log it to MQ args[1] = level + ': ' + args[1] args.shift() sendMQMessage(R.apply(util.format, args)) } module.exports = { logger: logger, configure: configure, log2: log2, sendMQMessage: sendMQMessage }
JavaScript
0.000002
@@ -521,21 +521,28 @@ '%0A%7D%0A +%0A const f -l +ileL ogOpt +ion s = @@ -659,16 +659,17 @@ 'w' %7D%0A%7D%0A +%0A const lo @@ -1168,24 +1168,120 @@ (level) %7B%0A + fileLogOptions.level = level%0A fileTransport = new winston.transports.File(fileLogOptions)%0A // fileTranspo
7263a1986a356dc5b7e2e5dab87b94da3bb174fd
move newrelic log files to /tmp
newrelic.js
newrelic.js
/** * New Relic agent configuration. * * See lib/config.defaults.js in the agent distribution for a more complete * description of configuration variables and their potential values. */ exports.config = { /** * Array of application names. */ app_name: ['salesforce-service'], /** * Your New Relic license key. */ license_key: 'e324a157f25bbf3798247087b714ac1291f7dc7d', logging: { /** * Verbosity of the module's logging. This module uses bunyan * (https://github.com/trentm/node-bunyan) for its logging, and as such the * valid logging levels are 'fatal', 'error', 'warn', 'info', 'debug' and * 'trace'. Logging at levels 'info' and higher is very terse. For support * requests, attaching logs captured at 'trace' level are extremely helpful * in chasing down bugs. * * @env NEW_RELIC_LOG_LEVEL */ level: 'info', /** * Where to put the log file -- by default just uses process.cwd + * 'newrelic_agent.log'. A special case is a filepath of 'stdout', * in which case all logging will go to stdout, or 'stderr', in which * case all logging will go to stderr. * * @env NEW_RELIC_LOG */ filepath: '/var/log/newrelic/cp/newrelic_agent_salesforce.log' } }
JavaScript
0
@@ -1215,26 +1215,10 @@ : '/ -var/log/newrelic/c +tm p/ne
acc628a75f2bb7b6f0eb5a45fa29bccde10af4f2
fix base URL of dbots
monitors/modules/guildCount/postToDiscordBots.js
monitors/modules/guildCount/postToDiscordBots.js
/** * @file postToDiscordBots * @author Sankarsan Kampa (a.k.a k3rn31p4nic) * @license GPL-3.0 */ const request = require('request-promise-native'); /** * Posts guild count to Discord Bots * @param {TesseractClient} Bastion Tesseract client object * @returns {void} */ module.exports = async Bastion => { try { if (!Bastion.methods.isPublicBastion(Bastion)) return; let requestBody = { guildCount: Bastion.guilds.size }; if (Bastion.shard) { requestBody.shardCount = Bastion.shard.count; requestBody.shardId = Bastion.shard.id; } let url = `https://adiscord.bots.gg/api/v1/bots/${BASTION_CLIENT_ID}/stats`; let options = { body: requestBody, headers: { 'Authorization': Bastion.credentials.discordBotsAPIToken, 'User-Agent': 'Bastion Discord Bot (https://bastionbot.org)' }, json: true }; return await request.post(url, options); } catch (e) { Bastion.log.error(e); } };
JavaScript
0
@@ -600,17 +600,16 @@ https:// -a discord.
6efa95584b32fd9b16ea9e81b61b1dcdb9c8fa55
Refactor frame page size specs to remove repeated code
sashimi-webapp/test/e2e/specs/pageRenderer/frame-page-size.spec.js
sashimi-webapp/test/e2e/specs/pageRenderer/frame-page-size.spec.js
const pagesModeActivation = require('./pages-mode-activation'); module.exports = { 'should activate Pages mode': pagesModeActivation['should activate Pages mode'], 'should have the same page size for reference and renderer frame ': (browser) => { browser .getElementSize('#reference-frame-of-viewer-container', (referenceResult) => { browser .getElementSize('.page-view', (renderResult) => { const referenceSize = referenceResult.value; const renderSize = renderResult.value; browser.assert.equal(referenceSize.width, renderSize.width); }); }) .getCssProperty('#reference-frame-of-viewer-container', 'padding-top', (referenceResult) => { browser .getCssProperty('.page-view', 'padding', (renderResult) => { const referenceStyle = referenceResult.value; const renderStyle = renderResult.value; browser.assert.equal(referenceStyle, renderStyle); }); }) .getCssProperty('#reference-frame-of-viewer-container', 'padding-bottom', (referenceResult) => { browser .getCssProperty('.page-view', 'padding', (renderResult) => { const referenceStyle = referenceResult.value; const renderStyle = renderResult.value; browser.assert.equal(referenceStyle, renderStyle); }); }) .getCssProperty('#reference-frame-of-viewer-container', 'padding-left', (referenceResult) => { browser .getCssProperty('.page-view', 'padding', (renderResult) => { const referenceStyle = referenceResult.value; const renderStyle = renderResult.value; browser.assert.equal(referenceStyle, renderStyle); }); }) .getCssProperty('#reference-frame-of-viewer-container', 'padding-right', (referenceResult) => { browser .getCssProperty('.page-view', 'padding', (renderResult) => { const referenceStyle = referenceResult.value; const renderStyle = renderResult.value; browser.assert.equal(referenceStyle, renderStyle); }); }); }, 'after': (browser) => { browser.end(); }, };
JavaScript
0
@@ -62,660 +62,263 @@ );%0A%0A -module.exports = %7B%0A 'should activate Pages mode': pagesModeActivation%5B'should activate Pages mode'%5D,%0A%0A 'should have the same page size for reference and renderer frame ': (browser) =%3E %7B%0A browser%0A .getElementSize('#reference-frame-of-viewer-container', (referenceResult) =%3E %7B%0A browser%0A .getElementSize('.page-view', (renderResult) =%3E %7B%0A const referenceSize = referenceResult.value;%0A const renderSize = renderResult.value;%0A browser.assert.equal(referenceSize.width, renderSize.width);%0A %7D);%0A %7D)%0A .getCssProperty('#reference-frame-of-viewer-container', 'padding-top', (reference +const CSS_SELECTOR_REFERENCE_FRAME = '#reference-frame-of-viewer-container';%0Aconst CSS_SELECTOR_RENDER_FRAME = '.page-view';%0A%0Aconst compareCssProperty = (browser, propertyName) =%3E %7B%0A browser.getCssProperty(CSS_SELECTOR_RENDER_FRAME, propertyName, (render Resu @@ -318,36 +318,32 @@ derResult) =%3E %7B%0A - browser%0A @@ -348,163 +348,106 @@ - - .getCssProperty('.page-view', 'padding', (renderResult) =%3E %7B%0A const referenceStyle = referenceResult.value;%0A const renderStyle = +.expect.element(CSS_SELECTOR_REFERENCE_FRAME)%0A .to.have.css(propertyName)%0A .which.equal( rend @@ -464,1249 +464,446 @@ alue +) ;%0A - browser.assert.equal(referenceStyle, renderStyle);%0A %7D);%0A %7D)%0A .getCssProperty('#reference-frame-of-viewer-container', 'padding-bottom', (referenceResult) =%3E %7B%0A browser%0A .getCssProperty('.page-view', 'padding', (renderResult) =%3E %7B%0A const referenceStyle = referenceResult.value;%0A const renderStyle = renderResult.value;%0A browser.assert.equal(referenceStyle, renderStyle);%0A %7D);%0A %7D)%0A .getCssProperty('#reference-frame-of-viewer-contain +%7D);%0A%7D;%0A%0Amodule.exports = %7B%0A 'should activate Pages mode': pagesModeActivation%5B'should activate Pages mode'%5D,%0A%0A 'should have the same page size for reference and renderer frame ': (browser) =%3E %7B%0A compareCssProperty(brows er -' , ' -padding-left', (referenceResult) =%3E %7B%0A browser%0A .getCssProperty('.page-view', 'padding', (renderResult) =%3E %7B%0A const referenceStyle = referenceResult.value;%0A const renderStyle = renderResult.value;%0A browser.assert.equal(referenceStyle, renderStyle);%0A %7D);%0A %7D)%0A .getCssProperty('#reference-frame-of-viewer-container', 'padding-right', (referenceResult) =%3E %7B%0A browser%0A .getCssProperty('.page-view', 'padding', (renderResult) =%3E %7B%0A const referenceStyle = referenceResult.value;%0A const rend +width');%0A compareCssProperty(browser, 'padding-top');%0A compareCssProperty(browser, 'padding-bottom');%0A compareCssProperty(browser, 'padding-left');%0A compareCssProp er -S ty -le = renderResult.value;%0A browser.assert.equal(referenceStyle, renderStyle);%0A %7D);%0A %7D +(browser, 'padding-right' );%0A
81f87af0114d35c9040f1e5e3ccd11ee62cf85be
fix filtering and selection
ooiui/static/js/views/aa/StatusAlertTableView.js
ooiui/static/js/views/aa/StatusAlertTableView.js
"use strict"; /* * ooiui/static/js/views/aa/StatusAlertTableView.js */ var StatusAlertTableView = Backbone.View.extend({ bindings: { }, events: { }, initialize: function() { _.bindAll(this, "render"); this.initialRender(); }, initialRender:function(){ this.$el.html('<i class="fa fa-spinner fa-spin" style="margin-top:50px;margin-left:50%;font-size:90px;color:#337ab7;"> </i>'); }, template: JST['ooiui/static/js/partials/StatusAlert.html'], deselectAll:function(){ this.pageableGrid.clearSelectedModels(); this.pageableGrid.collection.each(function (model, i) { model.trigger("backgrid:select", model, false); }); }, render:function(options){ var self = this; this.$el.html(this.template()); var PageableModels = Backbone.PageableCollection.extend({ model: StatusAlertModel, state: { pageSize: 20 }, mode: "client" // page entirely on the client side }); var pageableCollection = new PageableModels(); self.collection.each(function(model,i){ pageableCollection.add(model) }); var ClickableRow = Backgrid.Row.extend({ events: { "click": "onClick", }, onClick: function (ev) { if ($(ev.target.parentElement).hasClass('selected')){ this.model.trigger("backgrid:select", this.model,false); ooi.trigger('statusTable:rowDeselected',this.model); }else{ this.model.trigger("backgrid:select", this.model,true); ooi.trigger('statusTable:rowSelected',this.model); } } }); var HtmlCell = Backgrid.HtmlCell = Backgrid.Cell.extend({ className: "html-cell", initialize: function () { Backgrid.Cell.prototype.initialize.apply(this, arguments); }, render: function () { this.$el.empty(); var rawValue = this.model.get(this.column.get("name")); var formattedValue = this.formatter.fromRaw(rawValue, this.model); this.$el.append(formattedValue); this.delegateEvents(); return this; } }); var columns = [ { name: "Quick View", cell: "select-row", editable: false, }, { name: "longName", label: "Name", cell: "string", editable: false, }, { name: "asset_type", label: "Asset Type", cell: "string", editable: false, }, { name: "count", label: "Message Count", cell: "integer", editable: false, }, { name: "event_type", editable: false, label: "Event Type", cell: HtmlCell, formatter: _.extend({}, Backgrid.Cell.prototype, { fromRaw: function (rawValue, model) { //console.log(rawValue); //place holder right now for triggered events if(rawValue == "alert"){ //return "Active"; return "<i id='event_type_def' style='font-size:20px;padding-right: 0px;color:#004773;' class='fa fa-circle'> Alert</i>"; } else if(rawValue == "alarm"){ //return "Disabled"; return "<i id='event_type_def' style='font-size:20px;padding-right: 0px;color:#004773;' class='fa fa-circle'> Alarm</i>"; } else if(rawValue == "inactive"){ //return "Disabled"; return "<i id='event_type_def' style='font-size:20px;padding-right: 0px;color:steelblue;' class='fa fa-circle'> Healthy</i>"; } else if(rawValue == "unknown"){ //return "Disabled"; return "<i id='event_type_def' style='font-size:20px;padding-right: 0px;color:gray;' class='fa fa-circle'> Unknown</i>"; } } }) }, ]; // Initialize a new Grid instance /* var grid = new Backgrid.Grid({ row: FocusableRow, columns: columns, collection: self.collection }); */ // Set up a grid to use the pageable collection self.pageableGrid = new Backgrid.Grid({ row: ClickableRow, columns: columns, collection: pageableCollection }); // Initialize the paginator var paginator = new Backgrid.Extension.Paginator({ collection: pageableCollection }); var filter = new Backgrid.Extension.ClientSideFilter({ collection: pageableCollection, placeholder: "Search...", fields: ['longName'], wait: 150 }); // Render the filter this.$el.find("#sampleTable").before(filter.render().el); // Add some space to the filter and move it to the right $(filter.el).css({float: "right", margin: "20px", "margin-top": "5px"}); // Render the paginator this.$el.find("#sampleTable").before(paginator.render().el); // Render the grid and attach the root to your HTML document this.$el.find("#sampleTable").append(self.pageableGrid.render().el); } });
JavaScript
0
@@ -495,32 +495,97 @@ All:function()%7B%0A +%0A this.filter.searchBox().val(%22%22);%0A this.filter.search();%0A%0A this.pageabl @@ -2317,32 +2317,66 @@ ditable: false,%0A + headerCell: %22select-all%22,%0A %7D,%0A %7B @@ -4518,20 +4518,21 @@ );%0A%0A -var +self. filter = @@ -4767,16 +4767,21 @@ .before( +self. filter.r @@ -4861,16 +4861,21 @@ t%0A $( +self. filter.e @@ -5185,24 +5185,130 @@ %0A %0A +this.$el.find('#sampleTable %3E table %3E thead %3E tr %3E th.select-all-header-cell').css('visibility','hidden'); %0A%0A %7D
53170d8b8fc60002799f65bd0d8662c9b7102e62
Add hooks to OverviewDetailTab
src/js/pages/system/OverviewDetailTab.js
src/js/pages/system/OverviewDetailTab.js
import mixin from 'reactjs-mixin'; import {Link} from 'react-router'; /* eslint-disable no-unused-vars */ import React from 'react'; /* eslint-enable no-unused-vars */ import {StoreMixin} from 'mesosphere-shared-reactjs'; import Config from '../../config/Config'; import ConfigStore from '../../stores/ConfigStore'; import ConfigurationMap from '../../components/ConfigurationMap'; import ConfigurationMapHeading from '../../components/ConfigurationMapHeading'; import HashMapDisplay from '../../components/HashMapDisplay'; import Loader from '../../components/Loader'; import MetadataStore from '../../stores/MetadataStore'; import MarathonStore from '../../../../plugins/services/src/js/stores/MarathonStore'; import Page from '../../components/Page'; const ClusterDetailsBreadcrumbs = () => { const crumbs = [ <Link to="/cluster" key={-1}>Cluster</Link> ]; return <Page.Header.Breadcrumbs iconID="cluster" breadcrumbs={crumbs} />; }; class OverviewDetailTab extends mixin(StoreMixin) { constructor() { super(...arguments); this.state = { open: false }; this.store_listeners = [ { name: 'config', events: ['ccidSuccess'] }, { name: 'marathon', events: ['instanceInfoSuccess'] }, { name: 'metadata', events: ['dcosSuccess'] } ]; } componentDidMount() { super.componentDidMount(...arguments); ConfigStore.fetchCCID(); MarathonStore.fetchMarathonInstanceInfo(); } getLoading() { return <Loader size="small" type="ballBeat" />; } getClusterDetailsHash() { let ccid = ConfigStore.get('ccid'); let productVersion = MetadataStore.version; if (Object.keys(ccid).length) { ccid = ccid.zbase32_public_key; } else { ccid = this.getLoading(); } if (productVersion == null) { productVersion = this.getLoading(); } return { [`${Config.productName} Version`]: productVersion, 'Cryptographic Cluster ID': ccid }; } getMarathonDetailsHash() { const marathonDetails = MarathonStore.getInstanceInfo(); if (!Object.keys(marathonDetails).length) { return null; }; return { 'Marathon Details': { 'Version': marathonDetails.version, 'Framework ID': marathonDetails.frameworkId, 'Leader': marathonDetails.leader, 'Marathon Config': marathonDetails.marathon_config, 'ZooKeeper Config': marathonDetails.zookeeper_config } }; } render() { const marathonHash = this.getMarathonDetailsHash(); let marathonDetails = null; if (marathonHash) { marathonDetails = <HashMapDisplay hash={marathonHash} />; } return ( <Page> <Page.Header breadcrumbs={<ClusterDetailsBreadcrumbs />} /> <div className="container"> <ConfigurationMap> <ConfigurationMapHeading className="flush-top"> Cluster Details </ConfigurationMapHeading> <HashMapDisplay hash={this.getClusterDetailsHash()} /> {marathonDetails} </ConfigurationMap> </div> </Page> ); } }; OverviewDetailTab.routeConfig = { label: 'Overview', matches: /^\/cluster\/details/ }; module.exports = OverviewDetailTab;
JavaScript
0
@@ -28,16 +28,49 @@ mixin';%0A +import %7BHooks%7D from 'PluginSDK';%0A import %7B @@ -96,16 +96,16 @@ outer';%0A - /* eslin @@ -1144,16 +1144,70 @@ teners = + Hooks.applyFilter('OverviewDetailTab:StoreListeners', %5B%0A @@ -1436,16 +1436,17 @@ %7D%0A %5D +) ;%0A %7D%0A%0A @@ -1586,16 +1586,112 @@ eInfo(); +%0A%0A Hooks.applyFilter('OverviewDetailTab:DidMountCallbacks', %5B%5D)%0A .forEach((cb) =%3E cb()); %0A %7D%0A%0A @@ -2088,30 +2088,140 @@ %0A %7D%0A%0A -return +// Allow plugins to add to the cluster details hash%0A return Hooks.applyFilter('OverviewDetailTab:ClusterDetails', %7B%0A %5B%60$ @@ -2307,21 +2307,22 @@ ': ccid%0A - %7D +) ;%0A %7D%0A%0A
8db679cc1d3e48d8961e3012297028895273c28a
Fix SonarQube reported vulnerabilities
src/main/resources/static/awe.js
src/main/resources/static/awe.js
var client = new XMLHttpRequest(); client.onerror = function(e) { alert("Error: " + e.error); }; client.onload = function() { if (!this.response) return; var resp = JSON.parse(this.response); if (resp.status / 100 != 2) { alert(resp.path + ": " + resp.status + " " + resp.error); } }; function stackTrace() { return new Error().stack; } function elt(id) { return document.getElementById(id); } function val(id) { return elt(id).value; } function init() { elt("title").focus(); } function ensureText(field) { if (!field.value) { field.value = 'Enter text' field.select() } } function setStyle(element, visibility, display) { element.style.visibility = visibility; element.style.display = display; } function show(id) { setStyle(elt(id), "visible", "block"); } function hide(id) { setStyle(elt(id), "hidden", "none"); } var modalOkHandler; function cancel() { hide("modal"); } function ok() { if (modalOkHandler) { modalOkHandler(); modalOkHandler = null; } cancel(); } function modal(url, okHandler, formLoaded, formShown) { client.open("GET", url); client.setRequestHeader("Accept", "text/html"); client.onload = function() { elt("modal-content").innerHTML = this.response; if (formLoaded) { formLoaded(); } modalOkHandler = okHandler; show("modal"); if (formShown) { formShown(); } } client.send(); } function ask(question, defaultAnswer, handleAnswered) { modal("/static/prompt.html", function () { handleAnswered(elt("answer").value); }, function() { elt("question").textContent = question; elt("answer").value = defaultAnswer; }, function() { var answerField = elt("answer"); answerField.select(); answerField.focus(); }); } function fileNameFrom(title) { return title.toLowerCase().replace(/\s+/g, "-") + ".txt" } function titleFrom(fileName) { var result = fileName.replace(/-/g, " "); result = result.substring(0, result.lastIndexOf('.')); result = result.substring(0, 1).toUpperCase() + result.substring(1); return result; } function save() { var title = val("title"); var text = val("text"); ask("Save as", fileNameFrom(title), function(fileName) { client.onload = null; client.open("PUT", "/work/" + fileName); client.setRequestHeader("Content-Type", "text/plain"); client.send(text); elt("text").focus(); }); } function load() { ask("Load from", "", function(fileName) { client.onload = function() { elt("title").value = titleFrom(fileName); elt("text").value = this.response; }; client.open("GET", "/work/" + fileName); client.setRequestHeader("Accept", "text/plain"); client.send(); }); } function create() { modal("/create"); }
JavaScript
0
@@ -62,21 +62,27 @@ (e) %7B%0A -alert +console.log (%22Error: @@ -239,13 +239,19 @@ -alert +console.log (res
4130a95ba93056be33f9a924f284d217fdf8b499
update graphic classname (#751)
packages/idyll-components/src/graphic.js
packages/idyll-components/src/graphic.js
const React = require('react'); class Graphic extends React.Component { render() { const { idyll, updateProps, hasError, ...props } = this.props; return ( <div {...props} /> ); } } Graphic._idyll = { name: "Graphic", tagType: "open" } module.exports = Graphic;
JavaScript
0
@@ -161,20 +161,38 @@ urn -(%0A %3Cdiv +%3Cdiv className=%22idyll-graphic%22 %7B.. @@ -205,14 +205,8 @@ %7D /%3E -%0A ) ;%0A @@ -241,17 +241,17 @@ me: -%22 +' Graphic -%22 +' ,%0A @@ -263,16 +263,17 @@ pe: -%22 +' open -%22 +' %0A%7D +; %0A%0Amo
d35b365869a4273c593f05e4d477e3fe08ec13ee
kill log spew
view/view.js
view/view.js
var View = Backbone.View.extend({ events: { 'click #shutdown-app': '_onShutdownAppClicked', 'click #restart-app': '_onRestartAppClicked', 'click #shutdown-pc': '_onShutdownPcClicked', 'click #restart-pc': '_onRestartPcClicked', 'click #start-app': '_onStartClicked', 'click .update': '_onUpdateClicked', 'click .rollback': '_onRollbackClicked' }, _socket: null, initialize: function() { this._socket = io.connect(); this._socket.on('connect', _.bind(function() { this._socket.emit('appStateRequest'); }, this)); this._socket.on('appState', _.bind(function(message) { this._onAppState(message); this._socket.emit('appStateRequest'); }, this)); this._socket.on('config', _.bind(function(message) { this._onConfig(message); }, this)); }, _onAppState: function(message) { console.log(new Date().getTime()); $(document.body).show(); message.uptime = moment.duration(message.uptime, 'milliseconds').format('dd:hh:mm:ss'); message.fps = message.fps ? message.fps[message.fps.length - 1] : ''; message.cpu = message.cpu ? message.cpu[message.cpu.length - 1] : ''; message.memory = message.memory && message.memory.length ? humanize.filesize(message.memory[message.memory.length - 1]) : ''; message.logList = ''; _.each(message.logs, function(log) { message.logList += log.level + ': ' + log.msg + '\n'; }); message.eventList = ''; _.each(message.events, function(e) { message.eventList += JSON.stringify(e) + '\n'; }); var template = _.unescape($('#info-template').html()).trim(); $('#info').html(_.template(template, message)); $('#controls-updaters').toggle(!message.isUpdating && (message.updaters.app.source !== null || message.updaters.content.source !== null)); $('#shutdown-app').toggle(message.isRunning); $('#start-app').toggle(!message.isRunning); $('#restart-app').toggle(message.isRunning); $('#controls').prop('disabled', message.updaters.content.isUpdating || message.updaters.app.isUpdating); this._updateUpdater($('#controls-updaters-content'), message.updaters.content); this._updateUpdater($('#controls-updaters-app'), message.updaters.app); }, _updateUpdater: function(container, state) { container.toggle(state.source !== null); $('.rollback', container).toggle(state.canRollback); $('.current', container).html(state.source); $('.sources button', container).each(_.bind(function(index, value) { var button = $(value); button.toggle(!button.hasClass(state.source)); }, this)); }, _onConfig: function(message) { this._makeSources($('#controls-updaters-content .sources'), 'content', message.contentUpdater.remote); this._makeSources($('#controls-updaters-app .sources'), 'app', message.appUpdater.remote); }, _makeSources: function(buttons, updater, sources) { var template = _.unescape($('#update-button-template').html()).trim(); var click = _.bind(function(e) { var data = $(e.target).data(); this._onSetSourceClicked(e, data.updater, data.source); }, this); buttons.empty(); for (var source in sources) { var data = { updater: updater, source: source }; var button = $(_.template(template, data)); button.addClass(source); button.data(data); button.click(click); buttons.append(button); } }, _onShutdownAppClicked: function() { if (window.confirm('Are you sure you want to shut down the app? It will not restart automatically.')) { this._socket.emit('shutdown-app'); } }, _onRestartAppClicked: function() { if (window.confirm('Are you sure you want to shut down and restart the app?')) { this._socket.emit('restart-app'); } }, _onShutdownPcClicked: function() { if (window.confirm('Are you sure you want to shut down the computer? It will not restart automatically.')) { this._socket.emit('shutdown-pc'); } }, _onRestartPcClicked: function() { if (window.confirm('Are you sure you want to shut down and restart the computer?')) { this._socket.emit('restart-pc'); } }, _onStartClicked: function() { this._socket.emit('start'); }, _onSetSourceClicked: function(event, updater, source) { this._socket.emit('setUpdaterSource', updater, source); }, _onUpdateClicked: function(event) { var updater = $(event.target).parents('fieldset').first().attr('id').indexOf('content') != -1 ? 'content' : 'app'; this._socket.emit('updateUpdater', updater); }, _onRollbackClicked: function() { var updater = $(event.target).parents('fieldset').first().attr('id').indexOf('content') != -1 ? 'content' : 'app'; this._socket.emit('rollbackUpdater', updater); } });
JavaScript
0.000001
@@ -818,45 +818,8 @@ ) %7B%0A -%09%09console.log(new Date().getTime());%0A %09%09$(
e4354e8623da50536dd2931453542bda32795de5
fix whitespace
GulpFlow.js
GulpFlow.js
var _ = require("underscore"); var Class = require("yajscf"); var through = require("through2"); var gutil = require("gulp-util"); var PluginError = gutil.PluginError; var execFile = require("child_process").execFileSync; var flow = require("flow-bin"); const PLUGIN_NAME = "gulp-flow"; module.exports = Class.extend( { init: function() { this.options = [ "--json" ]; }, check: function() { var me = this; this.results = {}; return through.obj(function(file, encoding, callback) { if(file.isNull()) { callback(); return; } else if(file.isStream()) { this.emit("error", new PluginError(PLUGIN_NAME, "streams are not supported (yet?)")); } try { var output = execFile(flow, _.union(["check-contents"], me.options), { input: file.contents.toString("utf-8") }).toString("utf-8"); } catch(e) { // flow normally exits with a non-zero status if errors are found output = e.stdout.toString("utf-8"); } me.results[file.path] = output; this.push(file); callback(); }); }, reporter: function() { var me = this; return through.obj(function(file, encoding, callback) { _.forEach(me.results, gutil.log); }); } });
JavaScript
0.999999
@@ -1363,20 +1363,16 @@ %0A %7D,%0A - %0A rep
2f5924719ef207cc8b93717412e191e00da696f0
add log warning
elasticdump.js
elasticdump.js
var util = require("util"); var http = require("http"); var https = require("https"); var EventEmitter = require('events').EventEmitter; var elasticdump = function(input, output, options){ var self = this; self.input = input; self.output = output; self.options = options; if (!self.options.searchBody) { self.options.searchBody = {"query": { "match_all": {} } }; } self.validationErrors = self.validateOptions(); self.toLog = true; if(options.maxSockets){ self.log('globally setting maxSockets=' + options.maxSockets); http.globalAgent.maxSockets = options.maxSockets; https.globalAgent.maxSockets = options.maxSockets; } if(self.options.input){ if(self.options.input === "$"){ self.inputType = 'stdio'; }else if(self.options.input.indexOf(":") >= 0){ self.inputType = 'elasticsearch'; }else{ self.inputType = 'file'; } var InputProto = require(__dirname + "/lib/transports/" + self.inputType)[self.inputType]; self.input = (new InputProto(self, self.options.input)); } if(self.options.output){ if(self.options.output === "$"){ self.outputType = 'stdio'; self.toLog = false; }else if(self.options.output.indexOf(":") >= 0){ self.outputType = 'elasticsearch'; }else{ self.outputType = 'file'; } var OutputProto = require(__dirname + "/lib/transports/" + self.outputType)[self.outputType]; self.output = (new OutputProto(self, self.options.output)); } }; util.inherits(elasticdump, EventEmitter); elasticdump.prototype.log = function(message){ var self = this; if(typeof self.options.logger === 'function'){ self.options.logger(message); }else if(self.toLog === true){ self.emit("log", message); } }; elasticdump.prototype.validateOptions = function(){ var self = this; var validationErrors = []; var required = ['input', 'output']; required.forEach(function(v){ if(!self.options[v]){ validationErrors.push('`' + v + '` is a required input'); } }); return validationErrors; }; elasticdump.prototype.dump = function(callback, continuing, limit, offset, total_writes){ var self = this; if(self.validationErrors.length > 0){ self.emit('error', {errors: self.validationErrors}); }else{ if(!limit){ limit = self.options.limit; } if(!offset){ offset = self.options.offset; } if(!total_writes){ total_writes = 0; } if(continuing !== true){ self.log('starting dump'); } self.input.get(limit, offset, function(err, data){ if(err){ self.emit('error', err); } self.log("got " + data.length + " objects from source " + self.inputType + " (offset: "+offset+")"); self.output.set(data, limit, offset, function(err, writes){ var toContinue = true; if(err){ self.emit('error', err); if( self.options['ignore-errors'] === true || self.options['ignore-errors'] === 'true' ){ toContinue = true; }else{ toContinue = false; } }else{ total_writes += writes; self.log("sent " + data.length + " objects to destination " + self.outputType + ", wrote " + writes); offset = offset + data.length; } if(data.length > 0 && toContinue){ self.dump(callback, true, limit, offset, total_writes); }else if(toContinue){ self.log('dump complete'); if(typeof callback === 'function'){ callback(total_writes); } }else if(toContinue === false){ self.log('dump ended with error'); if(typeof callback === 'function'){ callback(total_writes); } } }); }); } }; exports.elasticdump = elasticdump;
JavaScript
0.000001
@@ -2491,16 +2491,254 @@ dump'); +%0A%0A if(self.options.skip)%7B%0A self.log('Warning: skipping ' + self.options.skip + ' rows.');%0A self.log(%22 * skipping doesn't guarantee that the skipped rows have already been written, please refer to the README.%22);%0A %7D %0A %7D%0A%0A
65daac4fd3e2e1a5fd6100f0c18aa9a05bc39973
Update Gulpfile.js (#32)
Gulpfile.js
Gulpfile.js
// Require the dependencies so that we can use their functionality var autoprefixer = require('autoprefixer'); var cssnano = require('cssnano'); var gulp = require('gulp'); var exec = require('gulp-exec'); var sass = require('gulp-sass'); var postcss = require('gulp-postcss'); var reporter = require('postcss-reporter'); var syntax_scss = require('postcss-scss'); var stylelint = require('stylelint'); var deploy = require('gulp-gh-pages'); // Fetch config var defaults = require('./config/butler.defaults.js'); // Add local config on top; this file should not define an empty defaults var. try { var overrides = require('../../conf/butler.defaults.js'); defaults = extend(defaults, overrides); } catch (e) {} // Helper function to merge to js objects. function extend(obj, src) { Object.keys(src).forEach(function(key) { obj[key] = src[key]; }); return obj; } // Just run linters gulp.task('lint', function() { console.log('Running linters...'); return gulp.src(defaults.scss) .pipe(postcss([ stylelint(defaults.stylelint), reporter({ clearMessages: true }) ], {syntax: syntax_scss})) .on('end', function(){ console.log('Linting complete'); }) }); // Compile Sass gulp.task('sass', function() { console.log('Running Sass and PostCSS...'); // Set what postcss plugins need to be run var processors = [ autoprefixer(defaults.autoprefixer), cssnano ]; // Run on all file defaults defined in var scsss return gulp.src(defaults.scss) // Run Sass on those files .pipe(postcss([ stylelint(defaults.stylelint), reporter({ clearMessages: true }) ], {syntax: syntax_scss})) .pipe(sass().on('error',sass.logError)) // Run postcss plugin functions .pipe(postcss(processors)) // Put the CSS in the destination dir .pipe(gulp.dest(defaults.css)); }); // Sculpin Development gulp.task('sculpin', function () { console.log('Building sculpin...'); gulp.src(defaults.sculpin) // Run the command line commands to watch sculpin .pipe(exec(defaults.sculpin_run + ' generate --watch --server --project-dir="' + defaults.sculpin + '"')); }); // Build Sculpin Production Artifact gulp.task('sculpin-prod', function () { console.log('Building production artifact...'); gulp.src(defaults.sculpin) // Run the command line commands to build sculpin production artifact .pipe(exec('sculpin generate --env=prod --project-dir="' + defaults.sculpin + '"')) .on('end', function(){ console.log('Your production artifact has been built'); }); }); // Watch for Changes gulp.task('watch', function() { return gulp // Watch the scss folder for change // and run `compile-sass` task when something happens .watch(defaults.scss, ['sass']) // When there is a change // log a message in the console .on('change', function (event) { console.log('File ' + event.path + ' was ' + event.type + ', running tasks...'); }); }); // Set Develop task gulp.task('develop', ['sass', 'sculpin', 'watch']); // Set a test task gulp.task('test', ['lint']); // Set a deploy task gulp.task('deploy', ['sculpin-prod'], function() { console.log('Beginning deploy to gh-pages for' + defaults.repo); return gulp.src(defaults.output_prod) .pipe(deploy(defaults.deploy)) .on('end', function(){ console.log('Your styleguide has been deployed to' + defaults.repo); }); }); // Set default task gulp.task('default', ['develop']);
JavaScript
0
@@ -1962,32 +1962,63 @@ .sculpin)%0A // + Kill process running on :8000. Run the command @@ -2049,16 +2049,67 @@ sculpin%0A + .pipe(exec('lsof -ti TCP:8000 %7C xargs kill'))%0A .pip
414b11cbe6607852f80d10adff126ffdea0c598a
Allow selector to disable start btn when no remaining imports
src/options/imports/selectors.js
src/options/imports/selectors.js
import { createSelector } from 'reselect' import { FILTERS, STATUS, DOC_SIZE_EST, DOC_TIME_EST, IMPORT_TYPE as TYPE, DOWNLOAD_STATUS as DL_STAT, } from './constants' export const entireState = state => state.imports export const importStatus = state => entireState(state).importStatus export const downloadData = state => entireState(state).downloadData const downloadDataFilter = state => entireState(state).downloadDataFilter export const fail = state => entireState(state).fail export const success = state => entireState(state).success export const totals = state => entireState(state).totals const completed = state => entireState(state).completed export const allowTypes = state => entireState(state).allowTypes const getImportStatusFlag = status => createSelector( importStatus, importStatus => importStatus === status, ) // Main import state selectors export const isInit = getImportStatusFlag(STATUS.INIT) export const isIdle = getImportStatusFlag(STATUS.IDLE) export const isRunning = getImportStatusFlag(STATUS.RUNNING) export const isPaused = getImportStatusFlag(STATUS.PAUSED) export const isStopped = getImportStatusFlag(STATUS.STOPPED) /** * Derives ready-to-use download details data (rendered into rows). * Performs a filter depending on the current projection selected in UI, * as well as map from store data to UI data. */ export const downloadDetailsData = createSelector( downloadData, downloadDataFilter, (downloadData, filter) => downloadData.filter(({ status }) => { switch (filter) { case FILTERS.SUCC: return status !== DL_STAT.FAIL case FILTERS.FAIL: return status === DL_STAT.FAIL case FILTERS.ALL: default: return true } }).map(({ url, status, error }) => ({ url, downloaded: status, error }) )) const getProgress = (success, fail, total) => ({ total, success, fail, complete: success + fail }) /** * Derives progress state from completed + total state counts. */ export const progress = createSelector( fail, success, totals, (fail, success, totals) => ({ [TYPE.HISTORY]: getProgress(success[TYPE.HISTORY], fail[TYPE.HISTORY], totals[TYPE.HISTORY]), [TYPE.BOOKMARK]: getProgress(success[TYPE.BOOKMARK], fail[TYPE.BOOKMARK], totals[TYPE.BOOKMARK]), }), ) // Util formatting functions for download time estimates const getHours = time => Math.floor(time / 60).toFixed(0) const getMins = time => (time - getHours(time) * 60).toFixed(0) const getPaddedMins = time => getMins(time) < 10 ? `0${getMins(time)}` : getMins(time) const getTimeEstStr = time => `${getHours(time)}:${getPaddedMins(time)} h` const getEstimate = (complete, remaining) => ({ complete, remaining, sizeCompleted: (complete * DOC_SIZE_EST).toFixed(2), sizeRemaining: (remaining * DOC_SIZE_EST).toFixed(2), timeRemaining: getTimeEstStr(remaining * DOC_TIME_EST), }) /** * Derives estimates state from completed + total state counts. */ export const estimates = createSelector( completed, totals, (completed, totals) => ({ [TYPE.HISTORY]: getEstimate(completed[TYPE.HISTORY], totals[TYPE.HISTORY]), [TYPE.BOOKMARK]: getEstimate(completed[TYPE.BOOKMARK], totals[TYPE.BOOKMARK]), }), ) export const isStartBtnDisabled = createSelector( allowTypes, (allowTypes) => { const allCheckboxesDisabled = !Object.values(allowTypes).reduce((prev, curr) => prev || curr) return allCheckboxesDisabled } )
JavaScript
0
@@ -3345,16 +3345,27 @@ owTypes, + estimates, %0A (al @@ -3372,16 +3372,27 @@ lowTypes +, estimates ) =%3E %7B%0A @@ -3427,16 +3427,22 @@ sabled = + () =%3E !Object @@ -3498,16 +3498,282 @@ %7C curr)%0A +%0A // Map-reduce the remaining estimates to disable button when they're all 0%0A const noImportsRemaining = () =%3E Object.values(TYPE)%0A .map(importType =%3E estimates%5BimportType%5D.remaining === 0)%0A .reduce((prev, curr) =%3E prev && curr)%0A%0A @@ -3800,17 +3800,44 @@ Disabled +() %7C%7C noImportsRemaining() %0A %7D +, %0A)%0A
98608cf45c1f3f3c018c14ac2badd6e3e64a60b6
add missing key attributes
source/pages/profile.js
source/pages/profile.js
import React from "react" import { connect } from "react-redux" import { FormattedMessage } from "react-intl" import { Tabs, Tab, List, ListItem } from "material-ui" import { pages } from "api" import { userPageFields } from "config" function mapStateToProps(state, props) { return { page: state.pages.get(props.params.pageId) || { data : {} } } } const Profile = React.createClass({ renderField(field, type) { let value = this.props.page.data[field]; let secondaryText; if (value) { switch (type) { case "string": secondaryText = <p>{this.props.page.data[field]}</p> default: } } else { secondaryText = <p><FormattedMessage id="texts.emptyField" /></p> } return ( <ListItem primaryText={<FormattedMessage id={`labels.userPageFields.${field}`} />} secondaryText={secondaryText} /> ) }, render() { const style = { fontFamily: "Roboto, sans-serif", zIndex: 2, background: "white", height: "100%", paddingTop: 12 } let tabs = [] for (let category in userPageFields) { let fields = [] for (let field in userPageFields[category]) { fields.push(this.renderField(field, userPageFields[category][field])) } tabs.push( <Tab label={<FormattedMessage id={`titles.userPageFields.${category}`} />}> <List> {fields} </List> </Tab> ) } return ( <div className="container-fluid" style={style}> <Tabs className="col-xs-12 col-sm-12 col-md-10 col-md-offset-1">{tabs}</Tabs> </div> ) } }) export default connect(mapStateToProps)(Profile)
JavaScript
0.000019
@@ -863,16 +863,71 @@ istItem%0A + key=%7B%60labels.userPageFields.$%7Bfield%7D%60%7D%0A @@ -1581,16 +1581,58 @@ %3CTab + key=%7B%60titles.userPageFields.$%7Bcategory%7D%60%7D label=%7B
dcd335f63462347f1e3ecd952a5e46da5db4f313
add parsing hooks
src/df-model-storage.js
src/df-model-storage.js
; (function() { 'use strict'; angular.module('dfModelStorage', []).directive('dfModelStorage', ['$window', '$parse', '$log', function($window, $parse, $log) { var defaultConfig = { onNoDataFound: angular.noop, onParseError: angular.noop, onSuccess: angular.identity }; return { require: '?ngModel', restrict: 'A', link: function dfModelStorage(scope, element, attrs, ngModel) { //priority to ngModel var watcher = ngModel ? function watchModel() {return ngModel.$modelValue;} : attrs.dfModelStorage; var itemName = attrs.ngModel || attrs.dfModelStorage; var prefix = attrs.dfPrefix || ""; var config = angular.extend({}, scope.dfConfig, defaultConfig); //we expect that the itemName is defined if(!angular.isString(itemName) || itemName.length < 1) { var errorMsg = 'Missing ngModel _OR_ model name in df-model-storage attribute'; $log.error(errorMsg, element); throw errorMsg; } // restore value from session storage var item = $window.sessionStorage.getItem(prefix + itemName); if(item) { try { var value = angular.fromJson(item); $parse(itemName).assign(scope, config.onSuccess(value)); } catch(e) { //$log.debug('error while parsing/assigning value', e); config.onParseError(itemName, e); } } else { config.onNoDataFound(itemName); } // save value in the session storage on change scope.$watch(watcher, function saveNewValInStorage(newValue) { //some browser in incognito mode block the session storage try { $window.sessionStorage.setItem(prefix + itemName, angular.toJson(newValue)); } catch(e) {} }, true); } } } ]); })();
JavaScript
0
@@ -188,16 +188,54 @@ fig = %7B%0A + onNotSupported: angular.noop,%0A @@ -1174,32 +1174,85 @@ session storage%0A + var sessionStorageKey = prefix + itemName;%0A var it @@ -1287,33 +1287,33 @@ getItem( -prefix + itemName +sessionStorageKey );%0A @@ -1596,24 +1596,33 @@ seError( -itemName +sessionStorageKey , e);%0A @@ -1685,24 +1685,33 @@ taFound( -itemName +sessionStorageKey );%0A @@ -2073,16 +2073,85 @@ tch(e) %7B +%0A config.onNotSupported(sessionStorageKey);%0A %7D%0A
16d6fb04e8d5ad618a218ea24983125b698b44dd
Add output.
entry/index.js
entry/index.js
module.exports = function (context, req) { var https = require('https'); var input = JSON.stringify(req.body); var command = input.split('&')[7].split('=')[1]; var userquery = input.split('&')[8].split('=')[1]; var callback = input.split('&')[9].split('=')[1]; var username = input.split('&')[6].split('=')[1]; // define function to call other Azure function to get the weather function getMetar(icaocode) { context.log(`https://dogithub.azurewebsites.net/api/metarSlackbot?icao=${icaocode}&callback=${callback}`); https.get(`https://dogithub.azurewebsites.net/api/metarSlackbot?icao=${icaocode}&callback=${callback}`, function (res) { var body = ''; // Will contain the final response // Received data is a buffer. // Adding it to our body res.on('data', function (data) { body += data; }); // After the response is completed, parse it and log it to the console res.on('end', function () { var parsed = JSON.parse(body); context.log(parsed); }); }) // If any error has occured, log error to console .on('error', function (e) { context.log("Got error: " + e.message); }); } function getFlightStatus(flightnumber) { context.log(`https://dogithub.azurewebsites.net/api/flightStatus?flightnumber=${flightnumber}&callback=${callback}`); }; context.log('Input was %s', userquery); if (command == '/metar') { context.bindings.response = `Hello ${username}, I am getting your weather for ${userquery}, try again if you have not heard back in 20s.`; getMetar(userquery); context.done(); } else if (command == '/flightstatus') { getFlightStatus(userquery); context.done(); } };
JavaScript
0.000308
@@ -1509,19 +1509,63 @@ );%0A %7D -; %0A%0A + context.log('Command was %25s', command); %0A cont @@ -1596,24 +1596,28 @@ userquery);%0A + %0A if (com
58c594d5693f2927fa4769758df927672dc5f749
Allow prettier to reformat
packages/provider/index.js
packages/provider/index.js
const debug = require("debug")("provider"); const Web3 = require("web3"); const { Web3Shim, InterfaceAdapter } = require("@truffle/interface-adapter"); const wrapper = require("./wrapper"); const DEFAULT_NETWORK_CHECK_TIMEOUT = 5000; module.exports = { wrap: function(provider, options) { return wrapper.wrap(provider, options); }, create: function(options) { const provider = this.getProvider(options); return this.wrap(provider, options); }, getProvider: function(options) { let provider; if (options.provider && typeof options.provider === "function") { provider = options.provider(); } else if (options.provider) { provider = options.provider; } else if (options.websockets) { provider = new Web3.providers.WebsocketProvider( "ws://" + options.host + ":" + options.port ); } else { provider = new Web3.providers.HttpProvider( `http://${options.host}:${options.port}`, { keepAlive: false } ); } return provider; }, testConnection: function(options) { const { networks, network } = options; let networkCheckTimeout; if (networks[network]) { networkCheckTimeout = networks[network].networkCheckTimeout || DEFAULT_NETWORK_CHECK_TIMEOUT; } else { networkCheckTimeout = DEFAULT_NETWORK_CHECK_TIMEOUT; } const provider = this.getProvider(options); const interfaceAdapter = new InterfaceAdapter(); const web3 = new Web3Shim({ provider }); return new Promise((resolve, reject) => { const noResponseFromNetworkCall = setTimeout(() => { const errorMessage = "There was a timeout while attempting to connect to the network." + "\n Check to see that your provider is valid.\n If you " + "have a slow internet connection, try configuring a longer " + "timeout in your Truffle config. Use the " + "networks.<networkName>.networkCheckTimeout property to do this."; throw new Error(errorMessage); }, networkCheckTimeout); web3.eth .getBlockNumber() .then(() => { clearTimeout(noResponseFromNetworkCall); resolve(true); }) .catch(error => { console.log( "> Something went wrong while attempting to connect " + "to the network. Check your network configuration." ); clearTimeout(noResponseFromNetworkCall); reject(error); }); }); } };
JavaScript
0.000003
@@ -1193,16 +1193,24 @@ imeout = +%0A network
239b508bfd64178402b66d5cd59a8b2c31a0b552
Improve wysihtml5.dom.resolveList
src/dom/resolve_list.js
src/dom/resolve_list.js
/** * Unwraps an unordered/ordered list * * @param {Element} element The list element which should be unwrapped * * @example * <!-- Assume the following dom: --> * <ul id="list"> * <li>eminem</li> * <li>dr. dre</li> * <li>50 Cent</li> * </ul> * * <script> * wysihtml5.dom.resolveList(document.getElementById("list")); * </script> * * <!-- Will result in: --> * eminem<br> * dr. dre<br> * 50 Cent<br> */ (function(dom) { function _isBlockElement(node) { return dom.getStyle("display").from(node) === "block"; } function _isLineBreak(node) { return node.nodeName === "BR"; } function _appendLineBreak(element) { var lineBreak = element.ownerDocument.createElement("br"); element.appendChild(lineBreak); } function resolveList(list) { if (list.nodeName !== "MENU" && list.nodeName !== "UL" && list.nodeName !== "OL") { return; } var doc = list.ownerDocument, fragment = doc.createDocumentFragment(), previousSibling = list.previousSibling, firstChild, lastChild, isLastChild, shouldAppendLineBreak, listItem; if (previousSibling && !_isBlockElement(previousSibling)) { _appendLineBreak(fragment); } while (listItem = list.firstChild) { lastChild = listItem.lastChild; while (firstChild = listItem.firstChild) { isLastChild = firstChild === lastChild; // This needs to be done before appending it to the fragment, as it otherwise will loose style information shouldAppendLineBreak = isLastChild && !_isBlockElement(firstChild) && !_isLineBreak(firstChild); fragment.appendChild(firstChild); if (shouldAppendLineBreak) { _appendLineBreak(fragment); } } listItem.parentNode.removeChild(listItem); } list.parentNode.replaceChild(fragment, list); } dom.resolveList = resolveList; })(wysihtml5.dom);
JavaScript
0.000009
@@ -1072,16 +1072,47 @@ ibling = + list.previousElementSibling %7C%7C list.pr
c0b7f3e02c32907de86888e4582e4f1ec0b79143
make aperture open install with --production
commands/open.js
commands/open.js
var purge = require('./purge') var bulk = require('./bulk') var link = require('./link') module.exports = init function init(root, config, events, done) { link(root, config, events, function(err) { if (err) return done(err) config.bulk = { command: 'npm' , args: [ 'install' , '--color=always' ] } bulk(root, config, events, function(err) { if (err) return done(err) purge(root, config, events, done) }) }) }
JavaScript
0
@@ -334,16 +334,41 @@ always'%0A + , '--production'%0A %5D%0A
0343c2d06a168648a44a0d1d87481c6706fc7625
Convert _id to string if for string property
src/entity/aggregate.js
src/entity/aggregate.js
'use strict' const _ = require('lodash') const _h = require('../_helpers') exports.handler = async (event, context) => { if (event.source === 'aws.events') { return _h.json({ message: 'OK' }) } if (!event.Records && event.Records.length === 0) { return } for (var i = 0; i < event.Records.length; i++) { const data = JSON.parse(event.Records[i].body) const entityId = _h.strToId(data.entity) const db = await _h.db(data.account) const entity = await db.collection('entity').findOne({ _id: entityId }, { projection: { _id: false, aggregated: true, 'private.name': true } }) if (entity && entity.aggregated && data.dt && entity.aggregated >= new Date(data.dt)) { console.log('Entity', entityId, '@', data.account, 'already aggregated at', entity.aggregated) continue } const properties = await db.collection('property').find({ entity: entityId, deleted: { $exists: false } }).toArray() if (properties.find(x => x.type === '_deleted')) { const deleteResponse = await db.collection('entity').deleteOne({ _id: entityId }) console.log('Entity', entityId, '@', data.account, 'deleted') continue } let newEntity = { aggregated: new Date() } for (var n = 0; n < properties.length; n++) { const prop = properties[n] let cleanProp = _.omit(prop, ['entity', 'type', 'created', 'search', 'public']) if (prop.reference && ['_viewer', '_expander', '_editor', '_owner'].includes(prop.type)) { if (!_.has(newEntity, 'access')) { _.set(newEntity, 'access', []) } newEntity.access.push(prop.reference) } if (prop.type === '_public' && prop.boolean === true) { if (!_.has(newEntity, 'access')) { _.set(newEntity, 'access', []) } newEntity.access.push('public') } if (!_.has(newEntity, ['private', prop.type])) { _.set(newEntity, ['private', prop.type], []) } if (prop.date) { const d = new Date(prop.date) cleanProp = { ...cleanProp, string: d.toISOString().substring(0, 9) } } if (prop.reference) { const referenceEntities = await db.collection('entity').findOne({ _id: prop.reference }, { projection: { 'private.name': true }}) if (_.has(referenceEntities, 'private.name')) { cleanProp = referenceEntities.private.name.map(x => { return { ...cleanProp, ...x } }) } else { cleanProp = { ...cleanProp, string: prop.reference } } } if (prop.formula) { const formulaResult = await formula(prop.formula, entityId, db) cleanProp = {...cleanProp, ...formulaResult} } if (!Array.isArray(cleanProp)) { cleanProp = [cleanProp] } newEntity.private[prop.type] = [...newEntity.private[prop.type], ...cleanProp] if (prop.public) { if (!_.has(newEntity, ['public', prop.type])) { _.set(newEntity, ['public', prop.type], []) } newEntity.public[prop.type] = [...newEntity.public[prop.type], ...cleanProp] } } const replaceResponse = await db.collection('entity').replaceOne({ _id: entityId }, newEntity) const name = _.get(entity, 'private.name', []).map(x => x.string || '') const newName = _.get(newEntity, 'private.name', []).map(x => x.string || '') if (!_.isEqual(_.sortBy(name), _.sortBy(newName))) { const referrers = await db.collection('property').aggregate([ { $match: { reference: entityId, deleted: { $exists: false } } }, { $group: { _id: '$entity' } } ]).toArray() const dt = data.dt ? new Date(data.dt) : newEntity.aggregated for (var i = 0; i < referrers.length; i++) { await _h.addEntityAggregateSqs(context, data.account, referrers[i]._id.toString(), dt) } console.log('Entity', entityId, '@', data.account, 'updated and added', referrers.length, 'entities to SQS') } else { console.log('Entity', entityId, '@', data.account, 'updated') } } } const formula = async (str, entityId, db) => { let func = formulaFunction(str) let data = formulaContent(str) if (!['CONCAT', 'COUNT', 'SUM', 'AVG'].includes(func)) { return { string: str } } if (data.includes('(') || data.includes(')')) { const f = await formula(data) data = f.string || f.integer || f.decimal || '' } if (func === null) { return { string: data } } const dataArray = data.split(',') let valueArray = [] for (let i = 0; i < dataArray.length; i++) { const value = await formulaField(dataArray[i], entityId, db) if (value !== null) { valueArray.push(value) } } switch (func) { case 'CONCAT': return { string: valueArray.join('') } break case 'COUNT': return { integer: valueArray.length } break case 'SUM': return { decimal: valueArray.reduce((a, b) => a + b, 0) } break case 'SUBTRACT': return { decimal: valueArray.reduce((a, b) => a - b, 0) + (a[0] * 2) } break case 'AVERAGE': return { decimal: valueArray.reduce((a, b) => a + b, 0) / arr.length } break case 'MIN': return { decimal: Math.min(valueArray) } break case 'MAX': return { decimal: Math.max(valueArray) } break } } const formulaFunction = (str) => { str = str.trim() if (!str.includes('(') || !str.includes(')')) { return null } else { return str.substring(0, str.indexOf('(')).toUpperCase() } } const formulaContent = (str) => { str = str.trim() if (!str.includes('(') || !str.includes(')')) { return str } else { return str.substring(str.indexOf('(') + 1, str.lastIndexOf(')')) } } const formulaField = async (str, entityId, db) => { str = str.trim() if ((str.startsWith("'") || str.startsWith('"')) && (str.endsWith("'") || str.endsWith('"'))) { return str.substring(1, str.length - 1) } let result switch (str.split('.').length) { case 1: const config = _.set({}, ['projection', `private.${str}.string`], true) const p = await db.collection('property').findOne({ entity: entityId, type: str, string: { $exists: true }, deleted: { $exists: false } }, { sort: { _id: 1 }, projection: { _id: false, string: true } }) result = _.get(p, ['string'], '') break default: result = null } return result }
JavaScript
0.999999
@@ -2527,16 +2527,27 @@ eference +.toString() %7D%0A
08e18c4118eb9ff59849f591c47b9de69e3ddebf
Fix for Actions when no data set.
src/foam/core/Action.js
src/foam/core/Action.js
/** * @license * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** Actions are high-level executable behaviours that are typically triggered by users and represented as buttons or menus. Actions are installed as methods on the class, but contain more meta-information than regular methods. Meta-information includes information needed to surface to action in a meaningful way to users, and includes things like the label to appear in the button or menu, a speech-label for i18n, help text, dynamic functions to enable or disable and hide or unhide the UI associated with this Action. Actions implement the Action Design Pattern. */ foam.CLASS({ package: 'foam.core', name: 'Action', documentation: 'An Action is a method with extra GUI support.', properties: [ { class: 'String', name: 'name', required: true }, { class: 'String', name: 'label', expression: function(name) { return foam.String.labelize(name); } }, { class: 'String', name: 'speechLabel', expression: function(label) { return label; } }, { name: 'icon' }, { class: 'Array', name: 'keyboardShortcuts' }, { class: 'String', name: 'help' }, { class: 'Boolean', name: 'isDefault', help: 'Indicates if this is the default action.', value: false }, { class: 'Function', name: 'isAvailable', label: 'Available', help: 'Function to determine if action is available.', value: null }, { class: 'Function', name: 'isEnabled', label: 'Enabled', help: 'Function to determine if action is enabled.', value: null }, { class: 'Function', name: 'code', required: true, value: null } ], methods: [ function isEnabledFor(data) { return this.isEnabled ? foam.Function.withArgs(this.isEnabled, data) : true; }, function createIsEnabled$(data$) { return foam.core.ExpressionSlot.create({ obj$: data$, code: this.isEnabled }); }, function isAvailableFor(data) { return this.isAvailable ? foam.Function.withArgs(this.isAvailable, data) : true ; }, function createIsAvailable$(data$) { return foam.core.ExpressionSlot.create({ obj$: data$, code: this.isAvailable }); }, function maybeCall(ctx, data) { if ( this.isEnabledFor(data) && this.isAvailableFor(data) ) { this.code.call(data, ctx, this); data.pub('action', this.name, this); return true; } return false; }, function installInClass(c) { c.installConstant(this.name, this); }, function installInProto(proto) { var action = this; proto[this.name] = function() { return action.maybeCall(this.__context__, this); }; } ] }); /** Add Action support to Model. */ foam.CLASS({ refines: 'foam.core.Model', properties: [ { class: 'AxiomArray', of: 'Action', name: 'actions', adaptArrayElement: function(o, prop) { return typeof o === 'function' ? foam.core.Action.create({name: o.name, code: o}) : foam.lookup(prop.of).create(o) ; } } ] });
JavaScript
0
@@ -3166,16 +3166,24 @@ %0A + data && data.pu
8889e69d169d1a6292eb95bbe07a93160e8bd29e
Add resetCurrentGame action
src/redux/modules/currentGame.js
src/redux/modules/currentGame.js
import { Record as record } from 'immutable'; import { checkSuccessStatus, toJSON } from 'redux/utils/api'; const NEW_GAME_REQUEST = 'NEW_GAME_REQUEST'; const NEW_GAME_SUCCESS = 'NEW_GAME_SUCCESS'; const NEW_GAME_FAILURE = 'NEW_GAME_FAILURE'; const UPDATE_HAS_OPPONENT = 'UPDATE_HAS_OPPONENT'; function newGameRequest() { return { type: NEW_GAME_REQUEST }; } function newGameSuccess({ gameId }) { return { gameId, type: NEW_GAME_SUCCESS, }; } function newGameFailure({ errors }) { return { errors, type: NEW_GAME_FAILURE, }; } function shouldFetchNewGame(state, force) { const { currentGame } = state; if (force) return true; if (currentGame.get('gameId')) return false; return true; } export function fetchNewGame(force = false) { return (dispatch, getState) => { if (!shouldFetchNewGame(getState(), force)) return Promise.resolve(); dispatch(newGameRequest()); return fetch('http://localhost:3000/api/game/new', { method: 'post' }) .then(checkSuccessStatus) .then(toJSON) .then(json => { dispatch(newGameSuccess(json)); return json.gameId; }) .catch(errors => { dispatch(newGameFailure({ errors })); }); }; } export function joinGame(gameId) { return newGameSuccess({ gameId }); } export function updateHasOpponent(hasOpponent) { return { hasOpponent, type: UPDATE_HAS_OPPONENT, }; } const initialState = record({ loading: false, gameId: '', hasOpponent: false, errors: [], }); export default function currentGameReducer(state = initialState(), action) { switch (action.type) { case NEW_GAME_REQUEST: return state.set('loading', true); case NEW_GAME_SUCCESS: return state.merge({ loading: false, gameId: action.gameId, errors: [], }); case NEW_GAME_FAILURE: return state.merge({ loading: false, gameId: '', errors: action.errors, }); case UPDATE_HAS_OPPONENT: return state.merge({ hasOpponent: action.hasOpponent, }); default: return state; } }
JavaScript
0
@@ -287,16 +287,65 @@ PONENT'; +%0Aconst RESET_CURRENT_GAME = 'RESET_CURRENT_GAME'; %0A%0Afuncti @@ -1451,16 +1451,102 @@ %7D;%0A%7D%0A%0A +export function resetCurrentGame() %7B%0A return %7B%0A type: RESET_CURRENT_GAME,%0A %7D;%0A%7D%0A%0A const in @@ -2191,24 +2191,80 @@ ,%0A %7D);%0A + case RESET_CURRENT_GAME:%0A return initialState;%0A default:
4c5820defc2332e0283eaea830c3b6bbaedc2bb4
Allow set value to accept a custom setter function
src/helpers/setValue.js
src/helpers/setValue.js
import { setPathValue } from './objectPath' import parseUrl from './parseUrl' export default function compile (path) { if (typeof path === 'string') { // check if the string is a url const url = parseUrl(path) if (url) { const urlPath = (url.path || '').split('.') if (url.scheme === 'output') { // add the value to the input object and pass it to output return function setOutputValue ({ input, output }, value) { const outputValue = (typeof value.toJS === 'function') ? value.toJS() : (value && value.constructor === Object && Object.isFrozen(value)) ? JSON.parse(JSON.stringify(value)) : value setPathValue(input, urlPath, outputValue) output(input) } } else if (url.scheme === 'state') { if (url.host === '.') { // set the value on the current module return function setLocalModuleStateValue ({ module }, value) { return module.state.set(urlPath, value) } } else if (url.host) { // set the value on the named module return function setModuleStateValue ({ modules }, value) { const module = modules[url.host] if (!module) { return console.error(`${path} : module was not found.`) } return module.state.set(urlPath, value) } } else { // set the value on the global state return function setStateValue ({ state }, value) { return state.set(urlPath, value) } } } else { return console.error(`${path} : scheme is not supported, expect "input" or "state".`) } } } // non-strings and non-urls (probably an array) are passed through to state.get return function set ({ state }, value) { return state.set(path, value) } }
JavaScript
0.000001
@@ -1724,16 +1724,75 @@ %7D%0A %7D%0A + %7D else if (typeof path === 'function') %7B%0A return path%0A %7D%0A //
04e29fcbd1d1e34ddc32ec36185b8f02eb63be40
Update the Issue title on changes on the reference.
src/issue/issue_view.js
src/issue/issue_view.js
"use strict"; var $$ = require ("substance-application").$$; var NodeView = require("../node/node_view"); var TextView = require("../text/text_view"); // Substance.Issue.View // ========================================================================== var IssueView = function(node, viewFactory) { NodeView.call(this, node, viewFactory); // This class is shared among all issue subtypes (errors, remarks) this.$el.addClass('issue'); this.childViews = { "title": null, "description": null }; }; IssueView.Prototype = function() { var __super__ = NodeView.prototype; this._updateTitle = function() { // var refs = this.node.getReferences(); // this.ref = refs[Object.keys(refs)[0]]; if (this.ref) { this.titleTextEl.innerHTML = this.ref.getContent(); } else { this.titleTextEl.innerHTML = ""; } }; // Rendering // ============================= // this.render = function() { NodeView.prototype.render.call(this); //Note: we decided to render the text of the reference instead of //the title property // this.childViews["title"] = new TextView(this.node, this.viewFactory, {property: "title"}); // var titleView = this.childViews["title"]; // this.content.appendChild(titleView.render().el); // var deleteButton = $$('a.delete-resource', { // href: '#', // text: "Delete", // contenteditable: false // Make sure this is not editable! // }); // titleView.el.appendChild(deleteButton); // titleView.el.setAttribute("contenteditable", "false"); //Note: we decided to render the text of the reference instead of //the title property var titleViewEl = $$('div') this.titleTextEl = $$('.text.title') var deleteButton = $$('a.delete-resource', { href: '#', text: "Delete", contenteditable: false // Make sure this is not editable! }); titleViewEl.appendChild(this.titleTextEl); titleViewEl.appendChild(deleteButton); titleViewEl.setAttribute("contenteditable", "false"); this.content.appendChild(titleViewEl); // Creator and date // -------- var creator = $$('div.creator', { text: (this.node.creator || "Anonymous") + ", " + jQuery.timeago(new Date(this.node.created_at)), contenteditable: false // Make sure this is not editable! }); // labelView.el.appendChild(creator); var descriptionView = this.childViews["description"] = new TextView(this.node, this.viewFactory, {property: "description"}); this.content.appendChild(descriptionView.render().el); return this; }; this.onNodeUpdate = function(op) { if (op.path[1] === "title") { this.childViews["title"].onNodeUpdate(op); return true; } else if (op.path[1] === "description") { this.childViews["description"].onNodeUpdate(op); return true; } else { return false; } }; this.onGraphUpdate = function(op) { if (__super__.onGraphUpdate.call(this, op)) { return true; } // Hack: lazily detecting references to this issue // by *only* checking 'create' ops with an object having this node as target else if (op.type === "create" && op.val["target"] === this.node.id) { this.ref = this.node.document.get(op.val.id); this._updateTitle(); return true; } // ... the same in inverse direction... else if (op.type === "delete" && op.val["target"] === this.node.id) { this.ref = null; this._updateTitle(); return true; } else { return false; } }; }; IssueView.Prototype.prototype = NodeView.prototype; IssueView.prototype = new IssueView.Prototype(); module.exports = IssueView;
JavaScript
0
@@ -3509,32 +3509,139 @@ return true;%0A + %7D%0A else if (this.ref && op.path%5B0%5D === this.ref.id) %7B%0A this._updateTitle();%0A return true;%0A %7D else %7B%0A
972652722a00fc1502bdbc2bb9ba328012cc9d30
Use dynamic require in NodeTraceurLoader.
src/runtime/NodeTraceurLoader.js
src/runtime/NodeTraceurLoader.js
// Copyright 2015 Traceur 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 import {TraceurLoader} from './TraceurLoader.js'; import {NodeLoaderCompiler} from '../node/NodeLoaderCompiler.js'; let fs = require('fs'); let path = require('path'); let fileloader = require('../node/nodeLoader.js'); export class NodeTraceurLoader extends TraceurLoader { constructor() { let url = (path.resolve('./') + '/').replace(/\\/g, '/'); super(fileloader, url, new NodeLoaderCompiler()); this.traceurMap_ = null; // optional cache for sourcemap } getSourceMap(filename) { var map = super.getSourceMap(filename); if (!map && filename.replace(/\\/g, '/').endsWith('/bin/traceur.js')) { if (!this.traceurMap_) { this.traceurMap_ = fs.readFileSync(filename + '.map', 'utf8'); } map = this.traceurMap_; } return map; } }
JavaScript
0
@@ -708,32 +708,85 @@ ';%0A%0A -let fs = require('fs');%0A +export class NodeTraceurLoader extends TraceurLoader %7B%0A constructor() %7B%0A let @@ -809,16 +809,20 @@ path');%0A + let file @@ -869,81 +869,8 @@ );%0A%0A -export class NodeTraceurLoader extends TraceurLoader %7B%0A constructor() %7B%0A @@ -1083,11 +1083,11 @@ -var +let map @@ -1222,24 +1222,56 @@ ceurMap_) %7B%0A + let fs = require('fs');%0A this
a31b7bad8fd0c25e9c5c41d9642bb491355d7689
reset first date on close
src/jquery.daterange.js
src/jquery.daterange.js
/** * jQuery UI Datepicker add-on which can help select date range * First click selects start date of range. Second click selects * end date of range and closes calendar. * * Plugin accept all Datepicker options except "onSelect" callback. * It will be overwritten by plugin. Also, plugin introduce one more * option -- rangeSeparator. * * http://noteskeeper.ru/38/ * * Copyright 2009-2013 Vladimir Kuznetsov <[email protected]> * Released under the MIT license * http://opensource.org/licenses/MIT * */ (function ($) { function compareDates(start, end, format) { var temp, dateStart, dateEnd; try { dateStart = $.datepicker.parseDate(format, start); dateEnd = $.datepicker.parseDate(format, end); if (dateEnd < dateStart) { temp = start; start = end; end = temp; } } catch (ex) {} return { start: start, end: end }; } $.fn.daterange = function (opts) { // defaults opts = $.extend({ "changeMonth": false, "changeYear": false, "numberOfMonths": 2, "rangeSeparator": " - " }, opts || {}); var onSelect = opts.onSelect || $.noop; var onClose = opts.onClose || $.noop; var beforeShowDay = opts.beforeShowDay; var lastDateRange; function storeLastDateRange(dateText, dateFormat) { var start, end; dateText = dateText.split(opts.rangeSeparator); if (dateText.length > 0) { start = $.datepicker.parseDate(dateFormat, dateText[0]); if (dateText.length > 1) { end = $.datepicker.parseDate(dateFormat, dateText[1]); } lastDateRange = {start: start, end: end}; } else { lastDateRange = null; } } opts.beforeShowDay = function (date) { var out = [true, ""], extraOut; if (lastDateRange && lastDateRange.start <= date) { if (lastDateRange.end && date <= lastDateRange.end) { out[1] = "ui-datepicker-range"; } } if (beforeShowDay) { extraOut = beforeShowDay.apply(this, arguments); out[0] = out[0] && extraOut[0]; out[1] = out[1] + " " + extraOut[1]; out[2] = extraOut[2]; } return out; }; // datepicker's select date event handler opts.onSelect = function (dateText, inst) { var textStart; if (!inst.rangeStart) { inst.inline = true; inst.rangeStart = dateText; } else { inst.inline = false; textStart = inst.rangeStart; if (textStart !== dateText) { var dateFormat = $(this).datepicker("option", "dateFormat"); var dateRange = compareDates(textStart, dateText, dateFormat); $(this).val(dateRange.start + opts.rangeSeparator + dateRange.end); inst.rangeStart = null; } } // call original callback for select event onSelect.apply(this, arguments); }; opts.onClose = function (dateText, inst) { // reset inline state inst.inline = false; // store dateText to highlight it latter var dateFormat = $(this).datepicker("option", "dateFormat"); storeLastDateRange(dateText, dateFormat); // call original callback for close event onClose.apply(this, arguments); }; return this.each(function () { var input = $(this); if (input.is("input")) { input.datepicker(opts); } }); }; }(jQuery));
JavaScript
0.000015
@@ -2979,20 +2979,43 @@ set -inline state +state%0A inst.rangeStart = null; %0A
b5b2b16cd29add2357670ac033b298878d397fa0
order start end end of selected dates
src/jquery.daterange.js
src/jquery.daterange.js
/** * jQuery UI Datepicker add-on which can help select date range * First click selects start date of range. Second click selects * end date of range and closes calendar. * * Plugin accept all Datepicker options except "onSelect" callback. * It will be overwritten by plugin. Also, plugin introduce one more * option -- rangeSeparator. * * http://noteskeeper.ru/38/ * * Copyright 2009-2013 Vladimir Kuznetsov <[email protected]> * Released under the MIT license * http://opensource.org/licenses/MIT * */ (function ($) { $.fn.daterange = function (opts) { // defaults opts = $.extend({ "changeMonth": false, "changeYear": false, "numberOfMonths": 2, "rangeSeparator": " - " }, opts || {}); var onSelect = opts.onSelect || $.noop; var onClose = opts.onClose || $.noop; // datepicker's select date event handler opts.onSelect = function (dateText, inst) { var textStart; if (!inst.rangeStart) { inst.inline = true; inst.rangeStart = dateText; } else { inst.inline = false; textStart = inst.rangeStart; if (textStart !== dateText) { $(this).val(textStart + opts.rangeSeparator + dateText); inst.rangeStart = null; } } // call original callback for select event onSelect.apply(this, arguments); }; opts.onClose = function (dateText, inst) { // reset inline state inst.inline = false; // call original callback for close event onClose.apply(this, arguments); }; return this.each(function () { var input = $(this); if (input.is("input")) { input.datepicker(opts); } }); }; }(jQuery));
JavaScript
0
@@ -533,16 +533,386 @@ ($) %7B%0A%0A + function compareDates(start, end, format) %7B%0A var temp, dateStart, dateEnd;%0A%0A try %7B%0A dateStart = $.datepicker.parseDate(format, start);%0A dateEnd = $.datepicker.parseDate(format, end);%0A if (dateEnd %3C dateStart) %7B%0A temp = start;%0A start = end;%0A end = temp;%0A %7D%0A %7D catch (ex) %7B%7D%0A%0A return %7B start: start, end: end %7D;%0A %7D%0A%0A $.fn.d @@ -1541,25 +1541,175 @@ -$(this).val(textS +var dateFormat = $(this).datepicker(%22option%22, %22dateFormat%22);%0A var dateRange = compareDates(textStart, dateText, dateFormat);%0A $(this).val(dateRange.s tart @@ -1737,20 +1737,25 @@ r + date -Text +Range.end );%0A
38253a81c8da3d4b7774138a4b712dab45a39856
Update screenUtils.js
src/scripts/scene/screenUtils.js
src/scripts/scene/screenUtils.js
module.exports.isSmall = isSmall; var smallSize = 768; // this is similar to `xs` size of bootstrap // determines whether screen size should be treated as "small" function isSmall() { if (typeof window === undefined) return false; return window.innerWidth <= smallSize; }
JavaScript
0.000001
@@ -1,8 +1,162 @@ +/**%0A * This is just a helper which checks whether screen should be treated as%0A * small. We change behavior of search results depending on screen size%0A */%0A module.e
cbe8d3f954971c9dc38a4449be49e2c2ce41ea9c
Fix toast.tvwindow.show args
src/sectv-tizen/tvwindowProxy.js
src/sectv-tizen/tvwindowProxy.js
/* * Copyright 2015 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var windowType = 'MAIN'; module.exports = { setSource: function (success, fail, args) { try { var match = -1; tizen.systeminfo.getPropertyValue('VIDEOSOURCE', function (videoSource) { var connectedVideoSources = videoSource.connected; for (var i = 0; i < connectedVideoSources.length; i++) { if (args[0].type == connectedVideoSources[i].type && args[0].number == connectedVideoSources[i].number) { match = i; break; } } if (match != -1) { tizen.tvwindow.setSource(connectedVideoSources[match], success, fail, windowType); } else { setTimeout(function () { fail(new Error('Fail to find source.')); }, 0); } }); } catch (e) { fail(e); } }, getSource: function (success, fail, args) { try { var source = tizen.tvwindow.getSource(windowType); setTimeout(function () { success(source); }, 0); } catch (e) { fail(e); } }, show: function (success, fail, args) { args[0][0] = args[0][0] + 'px'; args[0][1] = args[0][1] + 'px'; args[0][2] = args[0][2] + 'px'; args[0][3] = args[0][3] + 'px'; try { tizen.tvwindow.show(success, fail, args[0], windowType); } catch (e) { fail(e); } }, hide: function (success, fail, args) { try { tizen.tvwindow.hide(success, fail, windowType); } catch (e) { fail(e); } }, getRect: function (success, fail, args) { try { tizen.tvwindow.getRect(success, fail, 'px', windowType); } catch (e) { fail(e); } } }; require('cordova/exec/proxy').add('toast.tvwindow', module.exports);
JavaScript
0.000179
@@ -1969,23 +1969,44 @@ +v ar -gs%5B0%5D + rect = %5B%5D;%0A%0A rect %5B0%5D = ar @@ -2030,23 +2030,20 @@ -args%5B0%5D +rect %5B1%5D = ar @@ -2067,23 +2067,20 @@ -args%5B0%5D +rect %5B2%5D = ar @@ -2104,23 +2104,20 @@ -args%5B0%5D +rect %5B3%5D = ar @@ -2195,23 +2195,20 @@ , fail, -args%5B0%5D +rect , window
609698e9e1cbbc08b924e90ce9e6b60b46de7af2
Add z/y to help
src/js/app/view/help.js
src/js/app/view/help.js
'use strict'; var Backbone = require('backbone'); var $ = require('jquery'); var HELP_CONTENTS = [ ['j', 'go to next asset in collection'], ['k', 'go to previous asset in collection'], [''], ['right click', 'insert next available landmark'], ['snap + click', 'move snapped landmark'], ['snap + ctrl + move', 'lock snapped landmark'], [''], ['a', 'select all landmarks'], ['g', 'select all landmarks in the active group'], ['d', 'delete selected landmarks'], ['q / ESC', 'clear current selection'], ['click outside', 'clear current selection'], ['ctrl/cmd + click on landmark', 'select and deselect from current selection'], ['click on a landmark', 'select a landmark'], ['click + drag on a landmark', 'move landmark points'], ['shift + drag not on a landmark', 'draw a box to select multiple landmarks'], ['ctrl + shift + drag not on a landmark', 'draw a box to add multiple landmarks to current selection'], [''], ['l', 'toggle links (landmark connections)'], ['t', 'toggle textures (<i>mesh mode only</i>)'], ['c', 'change between orthographic and perspective rendering (<i>mesh mode only</i>)'], [''], ['r', 'reset the camera to default'], ['mouse wheel', 'zoom the camera in and out'], ['click + drag', 'rotate camera (<i>mesh mode only</i>)'], ['right click + drag', 'pan the camera'], [''], ['?', 'display this help'] ]; module.exports = Backbone.View.extend({ el: '#helpOverlay', events: { click: 'close' }, initialize: function() { this.listenTo(this.model, 'change:helpOverlayIsDisplayed', this.render); var $tbody = this.$el.children('table').children('tbody'); HELP_CONTENTS.forEach(function ([key, msg]) { $tbody.append( msg ? $(`<tr><td>${key}</td><td>${msg}</td></tr>`) : $(`<tr class='title'><td>${key}</td><td></td></tr>`) ); }); this.render(); }, render: function () { this.$el.toggleClass('Display', this.model.isHelpOverlayOn()); }, close: function () { this.model.toggleHelpOverlay(); } });
JavaScript
0.000002
@@ -529,32 +529,107 @@ nt selection'%5D,%0A + %5B'z', 'undo last operation'%5D,%0A %5B'y', 'redo last undone operation'%5D,%0A %5B'click outs
087dc1590b3b937a151c020264d5a2cdc0d46c7a
Fix name of provider
src/js/appController.js
src/js/appController.js
/** * Copyright (c) 2014, 2016, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ /* * Your application specific code will go here */ define(['ojs/ojcore', 'knockout', 'jso', 'ojs/ojrouter', 'ojs/ojknockout', 'ojs/ojarraytabledatasource', 'ojs/ojoffcanvas'], function (oj, ko, JSO) { function ControllerViewModel() { var self = this; // Check OAuth Token var location = window.location; self.jso = new JSO({ providerID: "google", client_id: "euregjug-admin-app", authorization: "https://euregjug.cfapps.io/oauth/authorize", redirect_uri: location.protocol + '//' + location.host + location.pathname, scopes: {request: ["read", "write"]} }); self.jso.callback(); // Media queries for repsonsive layouts var smQuery = oj.ResponsiveUtils.getFrameworkQuery(oj.ResponsiveUtils.FRAMEWORK_QUERY_KEY.SM_ONLY); self.smScreen = oj.ResponsiveKnockoutUtils.createMediaQueryObservable(smQuery); var mdQuery = oj.ResponsiveUtils.getFrameworkQuery(oj.ResponsiveUtils.FRAMEWORK_QUERY_KEY.MD_UP); self.mdScreen = oj.ResponsiveKnockoutUtils.createMediaQueryObservable(mdQuery); // Router setup self.router = oj.Router.rootInstance; self.router.configure({ 'dashboard': {label: oj.Translations.getTranslatedString('dashboard'), isDefault: true}, 'posts': {label: oj.Translations.getTranslatedString('posts')}, 'events': {label: oj.Translations.getTranslatedString('events')} }); oj.Router.defaults['urlAdapter'] = new oj.Router.urlParamAdapter(); // Navigation setup var navData = [ {name: oj.Translations.getTranslatedString('dashboard'), id: 'dashboard', iconClass: 'oj-navigationlist-item-icon demo-icon-font-24 demo-chart-icon-24'}, {name: oj.Translations.getTranslatedString('posts'), id: 'posts', iconClass: 'oj-navigationlist-item-icon demo-icon-font-24 demo-library-icon-24'}, {name: oj.Translations.getTranslatedString('events'), id: 'events', iconClass: 'oj-navigationlist-item-icon demo-icon-font-24 demo-fire-icon-24'} ]; self.navDataSource = new oj.ArrayTableDataSource(navData, {idAttribute: 'id'}); // Drawer // Called by nav drawer option change events so we can close drawer after selection self.navChangeHandler = function (event, data) { if (data.option === 'selection' && data.value !== self.router.stateId()) { self.toggleDrawer(); } }; // Close offcanvas on medium and larger screens self.mdScreen.subscribe(function () { oj.OffcanvasUtils.close(self.drawerParams); }); self.drawerParams = { displayMode: 'push', selector: '#navDrawer', content: '#pageContent' }; // Called by navigation drawer toggle button and after selection of nav drawer item self.toggleDrawer = function () { return oj.OffcanvasUtils.toggle(self.drawerParams); }; // Header // Application Name used in Branding Area self.appName = ko.observable("EuregJUG Admin App"); self.currentYear = ko.observable(new Date().getFullYear()); var token = self.jso.checkToken(); self.loggedIn = ko.observable(token !== null); self.labelButtonLogin = ko.pureComputed(function () { return oj.Translations.getTranslatedString(self.loggedIn() ? 'logout' : 'login'); }); self.login = function () { if (self.loggedIn()) { self.jso.wipeTokens(); self.loggedIn(false); } else { self.jso.getToken( function (token) {}, {} ); self.loggedIn(true); } }; // Footer function footerLink(name, id, linkTarget) { this.name = name; this.linkId = id; this.linkTarget = linkTarget; } self.footerLinks = ko.observableArray([ new footerLink('Sources', 'sources', 'https://github.com/euregJUG-Maas-Rhine/admin'), new footerLink('EuregJUG', 'euregjug', 'http://www.euregjug.eu') ]); } return new ControllerViewModel(); } );
JavaScript
0.000116
@@ -585,14 +585,16 @@ D: %22 -google +euregjug %22,%0D%0A
329abba80bf7a3c630748ea46f3bb02603ffbf33
Clear input[type=file] in imageDialog.
src/js/module/Dialog.js
src/js/module/Dialog.js
define('module/Dialog', function () { /** * Dialog * * @class */ var Dialog = function () { /** * toggle button status * * @param {jQuery} $btn * @param {Boolean} bEnable */ var toggleBtn = function ($btn, bEnable) { $btn.toggleClass('disabled', !bEnable); $btn.attr('disabled', !bEnable); }; /** * show image dialog * * @param {jQuery} $editable * @param {jQuery} $dialog * @return {Promise} */ this.showImageDialog = function ($editable, $dialog) { return $.Deferred(function (deferred) { var $imageDialog = $dialog.find('.note-image-dialog'); var $imageInput = $dialog.find('.note-image-input'), $imageUrl = $dialog.find('.note-image-url'), $imageBtn = $dialog.find('.note-image-btn'); $imageDialog.one('shown.bs.modal', function (event) { event.stopPropagation(); $imageInput.on('change', function () { $imageDialog.modal('hide'); deferred.resolve(this.files); }); $imageBtn.click(function (event) { event.preventDefault(); $imageDialog.modal('hide'); deferred.resolve($imageUrl.val()); }); $imageUrl.keyup(function () { toggleBtn($imageBtn, $imageUrl.val()); }).val('').focus(); }).one('hidden.bs.modal', function (event) { event.stopPropagation(); $editable.focus(); $imageInput.off('change'); $imageUrl.off('keyup'); $imageBtn.off('click'); }).modal('show'); }); }; /** * Show video dialog and set event handlers on dialog controls. * * @param {jQuery} $dialog * @param {Object} videoInfo * @return {Promise} */ this.showVideoDialog = function ($editable, $dialog, videoInfo) { return $.Deferred(function (deferred) { var $videoDialog = $dialog.find('.note-video-dialog'); var $videoUrl = $videoDialog.find('.note-video-url'), $videoBtn = $videoDialog.find('.note-video-btn'); $videoDialog.one('shown.bs.modal', function (event) { event.stopPropagation(); $videoUrl.val(videoInfo.text).keyup(function () { toggleBtn($videoBtn, $videoUrl.val()); }).trigger('keyup').trigger('focus'); $videoBtn.click(function (event) { event.preventDefault(); $videoDialog.modal('hide'); deferred.resolve($videoUrl.val()); }); }).one('hidden.bs.modal', function (event) { event.stopPropagation(); $editable.focus(); $videoUrl.off('keyup'); $videoBtn.off('click'); }).modal('show'); }); }; /** * Show link dialog and set event handlers on dialog controls. * * @param {jQuery} $dialog * @param {Object} linkInfo * @return {Promise} */ this.showLinkDialog = function ($editable, $dialog, linkInfo) { return $.Deferred(function (deferred) { var $linkDialog = $dialog.find('.note-link-dialog'); var $linkText = $linkDialog.find('.note-link-text'), $linkUrl = $linkDialog.find('.note-link-url'), $linkBtn = $linkDialog.find('.note-link-btn'), $openInNewWindow = $linkDialog.find('input[type=checkbox]'); $linkDialog.one('shown.bs.modal', function (event) { event.stopPropagation(); $linkText.val(linkInfo.text); $linkUrl.keyup(function () { toggleBtn($linkBtn, $linkUrl.val()); // display same link on `Text to display` input // when create a new link if (!linkInfo.text) { $linkText.val($linkUrl.val()); } }).val(linkInfo.url).trigger('focus'); $openInNewWindow.prop('checked', linkInfo.newWindow); $linkBtn.one('click', function (event) { event.preventDefault(); $linkDialog.modal('hide'); deferred.resolve($linkUrl.val(), $openInNewWindow.is(':checked')); }); }).one('hidden.bs.modal', function (event) { event.stopPropagation(); $editable.focus(); $linkUrl.off('keyup'); }).modal('show'); }).promise(); }; /** * show help dialog * * @param {jQuery} $dialog */ this.showHelpDialog = function ($editable, $dialog) { var $helpDialog = $dialog.find('.note-help-dialog'); $helpDialog.one('hidden.bs.modal', function (event) { event.stopPropagation(); $editable.focus(); }).modal('show'); }; }; return Dialog; });
JavaScript
0
@@ -944,27 +944,122 @@ -$imageInput +// Cloning imageInput to clear element.%0A $imageInput.replaceWith($imageInput.clone()%0A .on('cha @@ -1070,32 +1070,34 @@ , function () %7B%0A + $ima @@ -1112,32 +1112,34 @@ .modal('hide');%0A + defe @@ -1166,33 +1166,47 @@ les);%0A -%7D + %7D)%0A );%0A%0A $i
94c789f00e635af816ed40ed8002161aac615b60
save teacherIds in db
src/services/user-group/model.js
src/services/user-group/model.js
'use strict'; const mongoose = require('mongoose'); const Schema = mongoose.Schema; const getUserGroupSchema = (additional = {}) => { const schema = { name: {type: String, required: true}, schoolId: {type: Schema.Types.ObjectId, required: true}, createdAt: {type: Date, 'default': Date.now}, updatedAt: {type: Date, 'default': Date.now} }; return new Schema(Object.assign(schema, additional),{ timestamps: true }); }; const courseModel = mongoose.model('course', getUserGroupSchema({ classId: {type: Schema.Types.ObjectId, required: true} })); const classModel = mongoose.model('class', getUserGroupSchema()); const gradeModel = mongoose.model('grade', getUserGroupSchema()); module.exports = { courseModel, classModel, gradeModel };
JavaScript
0
@@ -550,16 +550,78 @@ d: true%7D +,%0A%09teacherIds: %5B%7Btype: Schema.Types.ObjectId, required: true%7D%5D %0A%7D));%0Aco @@ -677,24 +677,88 @@ GroupSchema( +%7B%0A%09teacherIds: %5B%7Btype: Schema.Types.ObjectId, required: true%7D%5D%0A%7D ));%0Aconst gr
4bab87c67416669a8929e73937754a8fdb03652c
remove console log
src/js/page-category.js
src/js/page-category.js
// Common modules import './common' // Page modules var urlParameter = require('./get-url-parameter') var accordion = require('./accordion') var FindHelp = require('./find-help') var apiRoutes = require('./api') // Lodash var sortBy = require('lodash/collection/sortBy') var forEach = require('lodash/collection/forEach') var findIndex = require('lodash/array/findIndex') var getApiData = require('./get-api-data') var templating = require('./template-render') var Spinner = require('spin.js') var analytics = require('./analytics') var socialShare = require('./social-share') // Spinner var spin = document.getElementById('spin') var loading = new Spinner().spin(spin) var findHelp = new FindHelp() findHelp.handleSubCategoryChange('sub-category', accordion) findHelp.buildCategories(apiRoutes.categoryServiceProviders, buildList) function buildList (url) { // Get API data using promise getApiData.data(url).then(function (result) { if (result.status === 'error') { window.location.replace('/find-help/') } var data = result.data var theTitle = data.name + ' - Street Support' document.title = theTitle var template = '' var callback = function () {} if (data.subCategories.length) { template = 'js-category-result-tpl' data.subCategories = sortBy(data.subCategories, function (item) { return item.name }) forEach(data.subCategories, function (subCat) { forEach(subCat.serviceProviders, function (provider) { if (provider.tags !== null) { provider.tags = provider.tags.join(', ') } }) }) var subCategoryIndexToOpen = findIndex(data.subCategories, function (subCat) { return subCat.key === urlParameter.parameter('sub-category') }) } else { template = 'js-category-no-results-result-tpl' } callback = function () { accordion.init(false, subCategoryIndexToOpen, findHelp.buildListener('category', 'sub-category')) loading.stop() console.log('callback') socialShare.init() } analytics.init(theTitle) templating.renderTemplate(template, findHelp.buildViewModel('category', data), 'js-category-result-output', callback) }) }
JavaScript
0.000003
@@ -2017,38 +2017,8 @@ p()%0A - console.log('callback')%0A
ee8db4b91daedbd93f3190555e74d67c8d6c7d2c
fix find help provider name
src/js/page-category.js
src/js/page-category.js
import './common' let accordion = require('./accordion') let FindHelp = require('./find-help') let apiRoutes = require('./api') let forEach = require('lodash/collection/forEach') let getApiData = require('./get-api-data') let templating = require('./template-render') let analytics = require('./analytics') let socialShare = require('./social-share') let browser = require('./browser') let findHelp = new FindHelp() findHelp.handleSubCategoryChange('sub-category', accordion) findHelp.buildCategories(apiRoutes.servicesByCategory, buildList) function buildList (url) { browser.loading() getApiData.data(url) .then(function (result) { if (result.status === 'error') { window.location.replace('/find-help/') } let theTitle = result.data.category.name + ' - Street Support' document.title = theTitle let template = '' let callback = function () { browser.loaded() socialShare.init() } let formattedProviders = [] let subCategories = [] if (result.data.providers.length > 0) { template = 'js-category-result-tpl' forEach(result.data.providers, function (provider) { let service = { info: provider.info, location: provider.location, openingTimes: provider.openingTimes } let match = formattedProviders.filter((p) => p.providerId === provider.providerId) if (match.length === 1) { match[0].services.push(service) } else { let newProvider = { providerId: provider.providerId, providerName: provider.providerName, services: [service] } if (provider.tags !== null) { newProvider.tags = provider.tags.join(', ') } if (provider.subCategories !== null) { provider.subCategories .forEach((sc) => { if (subCategories.filter((esc) => esc.id === sc.id).length === 0) { subCategories.push(sc) } }) newProvider.subCategories = provider.subCategories newProvider.subCategoryList = provider.subCategories .map((sc) => sc.name) .join(', ') } formattedProviders.push(newProvider) } }) callback = function () { accordion.init(true, 0, findHelp.buildListener('category', 'service-provider'), true) browser.loaded() socialShare.init() let providerItems = document.querySelectorAll('.js-item, .js-header') let filterItems = document.querySelectorAll('.js-filter-item') let filterClickHandler = (e) => { forEach(document.querySelectorAll('.js-filter-item'), (item) => { item.classList.remove('on') }) e.target.classList.add('on') forEach(providerItems, (item) => { item.classList.remove('hide') }) let id = e.target.getAttribute('data-id') if (id.length > 0) { forEach(providerItems, (item) => { if (item.getAttribute('data-subcats').indexOf(id) < 0) { item.classList.add('hide') } }) } } forEach(filterItems, (item) => { item.addEventListener('click', filterClickHandler) }) } } else { template = 'js-category-no-results-result-tpl' } analytics.init(theTitle) var formattedData = { category: result.data.category, providers: formattedProviders, subCategories: subCategories } let viewModel = findHelp.buildViewModel('category', formattedData) templating.renderTemplate(template, viewModel, 'js-category-result-output', callback) }) }
JavaScript
0.000012
@@ -1531,33 +1531,40 @@ derId: provider. -p +serviceP roviderId,%0A @@ -1589,25 +1589,32 @@ e: provider. -p +serviceP roviderName,
e9b99a2f391f70ef6adbb309e70fbf98f6c2e664
Change map key
src/shared/actions/MapActions.js
src/shared/actions/MapActions.js
import request from 'superagent' import { MAP_INITED, SET_MAP_PIN_STARTED, SET_MAP_PIN_COMPLETED, SET_MAP_GEO_COMPLETED, FIND_MAP_PLACE_COMPLETED, FIND_MAP_PLACE_FAILED } from 'shared/constants/ActionTypes' /* eslint-disable max-len */ async function searchForm (address) { return new Promise((resolve, reject) => { request .get('https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyAFZCD9PCbfA3qVdMX5a4qT3xFl4osxwzA&address=' + address) .set('Accept', 'application/json') .end(function (err, res) { if (!err && res.body) { resolve(res.body) } else { reject(err) } }) }) } export function init () { return async dispatch => { return dispatch({ type: MAP_INITED }) } } export function reload () { return async dispatch => { return dispatch({ type: SET_MAP_PIN_STARTED }) } } export function updateGeo ({ lat, lng }) { return async dispatch => { return dispatch({ type: SET_MAP_GEO_COMPLETED, lat_: lat, lng_: lng }) } } export function setPin ({ lat, lng, place }) { return async dispatch => { return dispatch({ type: SET_MAP_PIN_COMPLETED, lat: lat, lng: lng, place: place }) } } export function search (address) { return async dispatch => { try { const res = await searchForm(address) if (res && typeof res.results !== 'undefined') { const { lat, lng } = res.results[0].geometry.location return dispatch({ type: FIND_MAP_PLACE_COMPLETED, lat: lat, lng: lng, place: address }) } else { return dispatch({ type: FIND_MAP_PLACE_FAILED, errors: 'google data error' }) } } catch (err) { return dispatch({ type: FIND_MAP_PLACE_FAILED, errors: err }) } } }
JavaScript
0.000001
@@ -413,40 +413,40 @@ aSyA -FZCD9PCbfA3qVdMX5a4qT3xFl4osxwzA +OL2_DNy1xwxo2t1Lxif4r2gnBpDjOkn4 &add
0b3d6ec7d257ae203ed22a59bdd5ed3b46a3215c
add 'clone of:' to title of cloned recipes
src/js/recipe-detail.js
src/js/recipe-detail.js
;(function(){//IFEE angular.module('brewKeeper') .controller('recipeDetail', function($scope, $http, $location, $routeParams, $rootScope){ var id = $routeParams.id; var username = $routeParams.username; $scope.username = $routeParams.username; $scope.id = $routeParams.id; $(document).scrollTop(0); $http.get('https://brew-keeper-api.herokuapp.com/api/users/' + username + '/recipes/' + id + "/") .then(function(response){ $rootScope.detail = response.data; $rootScope.steps = response.data.steps; $rootScope.notes = response.data.brewnotes; var currentRating = $rootScope.detail.rating; $scope.rating = 0; $scope.ratings = [{ current: currentRating, max: 5 }]; }) //end http.get $scope.rateRecipe = function (rating) { var newRating = {"rating": rating} $http.patch("https://brew-keeper-api.herokuapp.com/api/users/"+ username + "/recipes/"+ id + "/", newRating) } $scope.Eliminate = function() { if (window.confirm("Are you sure you want to delete " + $scope.detail.title + "?")){ $http.delete('https://brew-keeper-api.herokuapp.com/api/users/' + username + '/recipes/' + id + '/').then(function(){ $location.path('/users/'+ username); }) }; }; //end Eliminate function $scope.showSteps = function(stepId){ stepId= "article." + stepId.toString() $(stepId).toggleClass("hidden") }; // $scope.showNotes = function(){ // $("div.notes").toggleClass("hidden") // }; $scope.deleteStep = function(stepNumber, stepId){ if (window.confirm("Are you sure you want to delete step " + stepNumber + "?")){ $http.delete("https://brew-keeper-api.herokuapp.com/api/users/"+ username +"/recipes/"+ id +"/steps/"+ stepId + "/").then(function(){ $http.get('https://brew-keeper-api.herokuapp.com/api/users/' + username + '/recipes/' + id +'/') .then(function(response){ $scope.steps = response.data.steps; }) }) } } //end deleteStep function $scope.showEditStep = function(stepId){ stepId = "div." + stepId.toString(); $(stepId).removeClass("hidden") } $scope.editStep = function(step){ $http.patch("https://brew-keeper-api.herokuapp.com/api/users/"+ username +"/recipes/"+ id +"/steps/"+ step.id + "/", step) .then($scope.hideEditStep(step.id)) } //end editStep function $scope.hideEditStep = function(stepId){ stepId = "div." + stepId.toString(); $(stepId).addClass("hidden") } $scope.step = { }//Might need to prepopulate this with empty strings for each key... Maybe... $scope.submit=function(){ $http.post("https://brew-keeper-api.herokuapp.com/api/users/"+ username +"/recipes/"+ id +"/steps/", $scope.step).then(function(){ $http.get('https://brew-keeper-api.herokuapp.com/api/users/' + username + '/recipes/' + id + '/') .then(function(response){ $scope.steps = response.data.steps; }) }) $scope.step= { }; } //end new step submit function $scope.showAddSteps = function(){ $("form.create-new-step").removeClass("hidden"); $("button.done-adding").removeClass("hidden"); };//Reveal "Add Step" when new recipe form is submitted. $scope.hideAddSteps = function(){ $("form.create-new-step").addClass("hidden"); $("button.done-adding").addClass("hidden"); }; //hides the add step form $('.edit-button').on('click', function(){ $('.edit-recipe').removeClass("hidden"); $('.recipe-view').addClass("hidden"); }); $scope.editRecipe = function(recipe){ $http.patch("https://brew-keeper-api.herokuapp.com/api/users/"+ username + "/recipes/"+ id + "/", recipe) .then( function () { $('.edit-recipe').addClass("hidden"); $('.recipe-view').removeClass("hidden"); }) } //end editRecipe function $('.cancel-recipe-edit').on('click', function(){ $('.recipe-view').removeClass("hidden"); $('.edit-recipe').addClass("hidden"); }); //Function for cloning recipes $scope.cloneRecipe = function(){ if (!window.confirm("Are you sure you want to clone "+ $scope.detail.title +" ?")){ return; }; var cloneData = {} cloneData.title = $scope.detail.title; cloneData.bean_name = $scope.detail.bean_name; cloneData.roast = $scope.detail.roast; cloneData.orientation = $scope.detail.orientation; cloneData.general_recipe_comment = $scope.detail.general_recipe_comment; cloneData.grind = $scope.detail.grind; cloneData.total_bean_amount = $scope.detail.total_bean_amount; cloneData.bean_units = $scope.detail.bean_units; cloneData.water_type = $scope.detail.water_type; cloneData.total_water_amount = $scope.detail.total_water_amount; cloneData.water_units = $scope.detail.water_units; cloneData.temp = $scope.detail.temp; cloneData.steps = []; $http.post("https://brew-keeper-api.herokuapp.com/api/users/"+ username +"/recipes/", cloneData).success(function(response){ newRecipeId = response.id; steps = []; for(step in $scope.detail.steps){ steps[step] = {}; steps[step].step_number = $scope.detail.steps[step].step_number; steps[step].step_title = $scope.detail.steps[step].step_title; steps[step].step_body = $scope.detail.steps[step].step_body; steps[step].duration = $scope.detail.steps[step].duration; steps[step].water_amount = $scope.detail.steps[step].water_amount; $http.post("https://brew-keeper-api.herokuapp.com/api/users/"+ username +"/recipes/"+ newRecipeId +"/steps/", steps[step]).success(function(){ $location.path("/users/"+ username +"/recipes/"+ newRecipeId) });//end step post };//end loop to clone steps });//end post new recipe }; //end recipe clone function }) //end recipDetail controller })();//END Angular IFEE
JavaScript
0.000007
@@ -4904,24 +4904,39 @@ Data.title = + %22Clone of: %22 + $scope.deta
f9727373d19d7498df92983f0a27f8db6ee9878a
Remove unnecessary divs
src/shared/components/Overlay.js
src/shared/components/Overlay.js
import React from "react"; import classNames from "classnames"; import {Link} from "@kchmck/redux-history-utils"; import {Provider, connect} from "react-redux"; import {sprintf} from "sprintf-js"; import {hsvToRgb} from "../util"; const Marker = ({loc, pos, active=false}) => ( <Link to={`/info/${loc.lkey}`} className={classNames("marker", {active})} style={{ background: calcBackground(loc.freqs[0].rxPower), left: pos.x, top: pos.y, }} /> ); const ActiveMarker = connect(({curLoc, proj}) => ({curLoc, proj}))( ({curLoc, proj}) => <div> {curLoc && <Marker loc={curLoc} pos={calcPos(curLoc, proj)} active={true} />} </div> ); function calcBackground(power) { let strength = calcSat(power); let sat = (Math.pow(20.0, strength) - 1.0) / (20.0 - 1.0); let val = 1.0 - 0.05 * sat; return sprintf("#%06x", hsvToRgb(0.0, sat, val)); } function calcSat(dbm) { return Math.min(Math.max((dbm + 127.0) / 54.0, 0.0), 1.0); } const Markers = connect(({locs, proj}) => ({locs, proj}))( ({locs, proj}) => <div> {locs.map(loc => <Marker key={loc.lkey} loc={loc} pos={calcPos(loc, proj)} />)} </div> ); function calcPos(loc, proj) { return proj.fromLatLngToDivPixel({ lat: () => loc.lat + loc.jitterLat, lng: () => loc.lng + loc.jitterLng, }); } const AllMarkers = () => <div> <Markers /> <ActiveMarker /> </div>; const Overlay = props => <Provider {...props}> <AllMarkers /> </Provider>; export default Overlay;
JavaScript
0.000008
@@ -605,32 +605,24 @@ =%3E -%3Cdiv%3E%0A %7BcurLoc && +curLoc ?%0A %3CMa @@ -683,27 +683,34 @@ true%7D /%3E -%7D%0A %3C/div + :%0A %3Cspan / %3E%0A);%0A%0Afu
f13419fca75819b283d746ec01fa0db601eaded4
Support hashbang URLs
src/js/routers/index.js
src/js/routers/index.js
/*jslint nomen: true */ /*globals define: true */ define([ 'jquery', 'lib/lodash', 'backbone', 'settings', 'api' ], function($, _, Backbone, settings, api) { 'use strict'; var IndexRouter = Backbone.Router.extend({ routes: { "": "home", "register": "register", "reset": "reset_password", "reset/:resetInfo": "change_password", "surveys/new": "new_survey", "surveys/:slug/dive": "dive", "surveys/:slug/dive/:oid": "objectDetails", "surveys/:slug/export": "survey_export", "surveys/:slug/design": "design", "surveys/:slug/review": "review", "surveys/:slug": "survey", "surveys/:slug/form/edit": "form_edit", "surveys/:slug/form": "form", "surveys/:slug/settings": "settings", 'embed/surveys/:slug': 'embed', // TODO: a multi-dataset view is a project that can reference multiple surveys, // so 'multi/survey/:slug' is not totally intuitive, but we're keeping it // around for now for backward compatibility. 'multi/surveys/:slug': 'multi', 'projects/:slug': 'multi', 'projects/:slug/dive': 'multiDetails', "*actions": "default_route" }, initialize: function(options) { this.controller = options.controller; this.route(/^login\/(.*)$/, "login", this.login); }, home: function() { console.log("Index"); this.controller.goto_home(); }, login: function(redirectTo) { console.log("Going to login view"); this.controller.goto_login(redirectTo); }, change_password: function (resetInfo) { this.controller.goto_change_password(resetInfo); }, reset_password: function () { this.controller.goto_reset_password(); }, new_survey: function() { api.getCurrentUser(function(user) { this.controller.goto_new(); }.bind(this)); }, survey: function(slug) { api.setSurveyIdFromSlug(slug, this.controller.goto_survey); }, dive: function(slug) { api.setSurveyIdFromSlug(slug, this.controller.goto_filters); }, objectDetails: function (slug, oid) { api.setSurveyIdFromSlug(slug, function (y) { this.controller.goto_filters(oid); }.bind(this)); }, settings: function(slug) { api.setSurveyIdFromSlug(slug, this.controller.goto_settings); }, form: function(slug) { api.setSurveyIdFromSlug(slug, this.controller.goto_form); }, survey_export: function(slug) { api.setSurveyIdFromSlug(slug, this.controller.goto_export); }, design: function(slug) { api.setSurveyIdFromSlug(slug, this.controller.goto_design); }, review: function(slug) { api.setSurveyIdFromSlug(slug, this.controller.goto_review); }, embed: function (slug) { api.setSurveyIdFromSlug(slug, this.controller.gotoSurveyEmbed); }, multi: function (slug) { this.controller.gotoMultiSurvey(slug); }, multiDetails: function (slug) { this.controller.gotoMultiSurvey(slug, { mode: 'deep-dive' }); }, default_route: function(actions) { // console.log(actions); } }); return IndexRouter; }); // End IndexRouter view module
JavaScript
0
@@ -265,16 +265,19 @@ %0A %22 +(!) register @@ -294,24 +294,27 @@ er%22,%0A %22 +(!) reset%22: %22res @@ -334,16 +334,19 @@ %0A %22 +(!) reset/:r @@ -375,32 +375,35 @@ sword%22,%0A%0A %22 +(!) surveys/new%22: %22n @@ -413,32 +413,35 @@ survey%22,%0A %22 +(!) surveys/:slug/di @@ -452,32 +452,35 @@ %22dive%22,%0A %22 +(!) surveys/:slug/di @@ -486,16 +486,29 @@ ive/:oid +(#:commentId) %22: %22obje @@ -518,32 +518,35 @@ etails%22,%0A %22 +(!) surveys/:slug/ex @@ -568,32 +568,35 @@ export%22,%0A %22 +(!) surveys/:slug/de @@ -611,32 +611,35 @@ design%22,%0A %22 +(!) surveys/:slug/re @@ -654,32 +654,35 @@ review%22,%0A %22 +(!) surveys/:slug%22: @@ -691,32 +691,35 @@ urvey%22,%0A%0A %22 +(!) surveys/:slug/fo @@ -740,32 +740,35 @@ m_edit%22,%0A %22 +(!) surveys/:slug/fo @@ -788,16 +788,19 @@ %0A %22 +(!) surveys/ @@ -836,16 +836,19 @@ %0A ' +(!) embed/su @@ -1095,16 +1095,19 @@ %0A ' +(!) multi/su @@ -1128,32 +1128,35 @@ 'multi',%0A ' +(!) projects/:slug': @@ -1172,16 +1172,19 @@ %0A ' +(!) projects
1a9e03fb91d65cc4a5c225fc1b22389cd1b3fe2c
Align DSL util comments
src/js/utils/DSLUtil.js
src/js/utils/DSLUtil.js
import DSLFilterTypes from '../constants/DSLFilterTypes'; import {CombinerNode, FilterNode} from '../structs/DSLASTNodes'; const ENDING_WHITESPACE = /\s+$/; const DSLUtil = { /** * Checks if the given expression can be processed by the UI * * @param {DSLExpression} expression - The expression to process * @returns {Boolean} Returns the expression state */ canFormProcessExpression(expression) { const hasGroups = (expression.value.indexOf('(') !== -1); const repeatingStatus = DSLUtil.reduceAstFilters(expression.ast, (memo, filter) => { if (memo.isRepeating) { return memo; } // Ignore fuzzy tokens if (filter.filterType === DSLFilterTypes.FUZZY) { return memo; } // Keep track of the tokens we have found so far const filterStr = DSLUtil.getNodeString(filter); if (memo.found[filterStr] == null) { memo.found[filterStr] = true; return memo; } // If we found a repeating token, mark repeating memo.isRepeating = true; return memo; }, {isRepeating: false, found: {}} ); // We can process an expression only if we have no groups if we // have groups and no repeating nodes return !hasGroups || !repeatingStatus.isRepeating; }, /** * This function checks if the given partFilters can create clean results * with the given AST sturcutre as input. * * @param {DSLExpression} expression - The parsed expression * @param {Array} partFilters - An array of `FilterNode` to use for match ref. * @returns {Boolean} Returns true if the expression can be handled by the UI */ canProcessParts(expression, partFilters) { const propNames = Object.keys(partFilters); return propNames.every((prop) => { const matchAgainst = partFilters[prop]; const matchingNodes = DSLUtil.findNodesByFilter( expression.ast, matchAgainst); // NOTE: Be aware that the entire form should be disabled if the // expression is difficult for the UI to process. This means // that if we have a grouping operator and at least one repeating // node, this code shouldn't be executed at all. // You can use `DSLUtil.canFormProcessExpression` for this. switch (matchAgainst.filterType) { // Attrib nodes can only handle 1 match case DSLFilterTypes.ATTRIB: return matchingNodes.length <= 1; // Exact nodes can only handle 1 match case DSLFilterTypes.EXACT: return matchingNodes.length <= 1; // We are concatenating all fuzzy-matching nodes into a string // so we have no problem if we have more than one. case DSLFilterTypes.FUZZY: return true; } }); }, /** * This function walks the given AST and extracts all the nodes matching the * given filter node. * * @param {ASTNode} ast - The AST node to walk on * @param {FilterNode} filter - The reference AST node to compare against * @returns {Array} Returns an array of FilterNodes tha match filter */ findNodesByFilter(ast, filter) { return DSLUtil.reduceAstFilters(ast, (memo, astFilter) => { const { filterParams, filterType } = astFilter; const { filterParams: compareFilterParams, filterType: compareFilterType } = filter; // Require types to match if (filterType !== compareFilterType) { return memo; } // Require only testing properties to match const compareParamNames = Object.keys(compareFilterParams); const comparePropMatches = compareParamNames.every((prop) => { return filterParams[prop] === compareFilterParams[prop]; }); if ((compareParamNames.length === 0) || comparePropMatches) { return memo.concat(astFilter); } return memo; }, []); }, /** * Get the string representation of the given AST node * * @param {ASTNode} node - The DSL AST Node * @returns {String} The string representation of the node */ getNodeString(node) { const {filterParams, filterType} = node; switch (filterType) { case DSLFilterTypes.ATTRIB: return `${filterParams.label}:${filterParams.text}`; case DSLFilterTypes.EXACT: return `"${filterParams.text}"`; case DSLFilterTypes.FUZZY: return filterParams.text; } }, /** * This function returns an object with the values for all the given * partFilters by analyzing the ast given as input. * * @param {DSLExpression} expression - The parsed expression * @param {Array} partFilters - An array of `FilterNode` to use for match ref. * @returns {Object} Returns an object with the propType keys and their values */ getPartValues(expression, partFilters) { const propNames = Object.keys(partFilters); // NOTE: We assume that `canProcessParts` is called before and this // function is called only after a positive answer. Therefore we are // safe to do some unsafe assumptions for this. return propNames.reduce((memo, prop) => { const matchAgainst = partFilters[prop]; const matchingNodes = DSLUtil.findNodesByFilter( expression.ast, matchAgainst); switch (matchAgainst.filterType) { // // Properties created through attribute filter will get a boolean value // case DSLFilterTypes.ATTRIB: memo[prop] = (matchingNodes.length === 1); return memo; // // Properties created through .exact filter will get a string value // case DSLFilterTypes.EXACT: if (matchingNodes.length === 0) { memo[prop] = null; return memo; } memo[prop] = matchingNodes[0].filterParams.text; return memo; // // Properties created through .fuzzy filter will get a string value, // composed by joining together any individual item in the string // case DSLFilterTypes.FUZZY: if (matchingNodes.length === 0) { memo[prop] = null; return memo; } memo[prop] = matchingNodes .map((ast) => ast.filterParams.text) .join(' '); // Also append whatever whitespace remains at the end of the raw value // // NOTE: This is a trick to allow dynamic updates of a React component // since white spaces at the end of the expression are not part // of a regular DSL expression and are trimmed. // const tailingWaitspace = ENDING_WHITESPACE.exec(expression.value); if (tailingWaitspace) { memo[prop] += tailingWaitspace[0]; } return memo; } }, {}); }, /** * This function walks the provided ast tree and calls back the given * callback function in the same way the `Array.reduce` function works. * * @param {ASTNode} ast - The AST node to walk on * @param {function} callback - The function to call for every filter * @param {any} memo - The AST node to walk on * @returns {any} Returns the result of the reduce operation */ reduceAstFilters(ast, callback, memo) { if (!ast) { return memo; } // Collect terminal nodes if (ast instanceof FilterNode) { return callback(memo, ast); } // Traverse children of combiner nodes if (ast instanceof CombinerNode) { return ast.children.reduce((curMemo, child) => { return DSLUtil.reduceAstFilters(child, callback, curMemo); }, memo); } return memo; } }; module.exports = DSLUtil;
JavaScript
0
@@ -5646,17 +5646,16 @@ through -. exact fi @@ -5974,17 +5974,16 @@ through -. fuzzy fi
fd7aea5186ede878cd55318d2a9bbf8650c7bf9b
bump saucelabs browser versions (#3469)
src/karma.sauce.conf.js
src/karma.sauce.conf.js
// Configuration used testing via Sauce Labs on Travis CI process.env.SAUCE_ACCESS_KEY = process.env.SAUCE_ACCESS_KEY.split('').reverse().join(''); const BROWSERS = { 'CHROME': { base: 'SauceLabs', browserName: 'chrome', version: 'latest' }, 'FIREFOX': { base: 'SauceLabs', browserName: 'firefox', version: 'latest' }, 'EDGE16': { base: 'SauceLabs', browserName: 'MicrosoftEdge', platform: 'Windows 10', version: '16.16299' }, 'EDGE17': { base: 'SauceLabs', browserName: 'MicrosoftEdge', platform: 'Windows 10', version: '17.17134' }, 'IE10': { base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 8', version: '10' }, 'IE11': { base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 10', version: '11' }, 'SAFARI11': { base: 'SauceLabs', browserName: 'safari', platform: 'macOS 10.13', version: '11' }, 'SAFARI12': { base: 'SauceLabs', browserName: 'safari', platform: 'macOS 10.13', version: '12' }, }; module.exports = function (config) { config.set({ basePath: '', files: ['../node_modules/bootstrap/dist/css/bootstrap.min.css'], frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-sauce-launcher'), require('@angular-devkit/build-angular/plugins/karma') ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, sauceLabs: { build: `TRAVIS #${process.env.TRAVIS_BUILD_NUMBER} (${process.env.TRAVIS_BUILD_ID})`, tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER, testName: 'ng-bootstrap', retryLimit: 3, startConnect: false, recordVideo: false, recordScreenshots: false, options: { commandTimeout: 600, idleTimeout: 600, maxDuration: 5400 } }, customLaunchers: BROWSERS, reporters: ['dots', 'saucelabs'], port: 9876, colors: true, logLevel: config.LOG_INFO, browsers: ['CHROME', 'FIREFOX', 'EDGE16', 'EDGE17', 'SAFARI11', 'SAFARI12'], singleRun: true, captureTimeout: 180000, browserDisconnectTimeout: 180000, browserDisconnectTolerance: 3, browserNoActivityTimeout: 300000 }); };
JavaScript
0
@@ -354,17 +354,17 @@ 'EDGE1 -6 +7 ': %7B%0A @@ -464,15 +464,15 @@ : '1 -6.16299 +7.17134 '%0A @@ -474,33 +474,33 @@ 4'%0A %7D,%0A 'EDGE1 -7 +8 ': %7B%0A base: ' @@ -580,39 +580,39 @@ %0A version: '1 -7.17134 +8.17763 '%0A %7D,%0A 'IE10': @@ -1050,33 +1050,33 @@ orm: 'macOS 10.1 -3 +4 ',%0A version: @@ -2140,17 +2140,17 @@ , 'EDGE1 -6 +7 ', 'EDGE @@ -2146,25 +2146,25 @@ E17', 'EDGE1 -7 +8 ', 'SAFARI11
f31e5aba5d118b3e589c6c373fc2fc5cd09bc6c7
implement require
src/simple-array-translations.js
src/simple-array-translations.js
import { isArray, camelCase } from './utils'; function letToVar(cmd, ...vars) { const varPairs = []; for (let i = 0; i < vars.length; i += 2) { let name = vars[ i ]; let val = vars[ i + 1 ]; if (name && val) { if (isArray(val)) { val = toJsString(val); } let statement = `${name} = ${val}`; varPairs.push(statement); } } if (varPairs.length < 1) { return ''; } else { return `var ${varPairs.join(', ')};`; } } function math_operator(operator, ...params) { const separator = ` ${operator} `; const statements = []; for (let i = 0; i < params.length; i++) { let statement = params[ i ]; if (isArray(statement)) { statement = toJsString(statement); } statements.push(statement); } return `(${statements.join(separator)})`; } function define_function(operator, name, params, ...body) { if (isArray(name)) { body.unshift(params); params = name; name = ""; } let statements = body.map(toJsString); let final = statements.pop(); statements = statements .map(s => s + ";") .join(' '); params = params.join(', '); return `(function ${name}(${params}) {${statements} return ${final};})`; } function define_module(operator, name, ...body) { const statements = body .map(toJsString) .map(s => s + ";") .join(' '); return `module('${name}', function (require, export) {${statements}})`; } function module_require(operator, moduleName, reqTokens) { return ""; } function module_export(operator, moduleName, statement) { return `export('${moduleName}', ${toJsString(statement)})`; } function function_call(fn, ...params) { const evaluated_params = params.map(p => toJsString(p)); return `${fn}( ${evaluated_params.join(', ')} )`; } export const toJsString = function (arr) { if (!isArray(arr)) { return arr; } switch(arr[0]) { case 'function': return define_function(...arr); case 'module': return define_module(...arr); case 'require': return module_require(...arr); case 'export': return module_export(...arr); case 'let': return letToVar(...arr); case '+': return math_operator(...arr); case '-': return math_operator(...arr); case '*': return math_operator(...arr); case '/': return math_operator(...arr); } return function_call(...arr); };
JavaScript
0.000001
@@ -1496,17 +1496,227 @@ %7B%0A -return %22%22 +const statements = reqTokens.map(token =%3E%0A %60var $%7Btoken%7D = $%7BmoduleName%7D%5B'$%7Btoken%7D'%5D%60);%0A statements.unshift(%60var $%7BmoduleName%7D = require('$%7BmoduleName%7D')%60);%0A%0A return statements%0A .map(s =%3E s + ';')%0A .join(' ') ;%0A%7D%0A
415f38e18cc144a6ad0d63f2f1823e94af71bda0
add missing test description
src/lib/luxPath.test.js
src/lib/luxPath.test.js
import luxPath from './luxPath'; function locationMock(str) { const query = str.match(/\?.*/); const pathname = str.replace(query, ''); return { pathname, query, toString: () => `${pathname}${query || ''}` }; } describe('Library: luxPath', function () { it('should be defined and be a function', function () { expect(typeof luxPath).toMatch(/function/i); }); describe('[Location Object]', function () { it('should return a string', function () { const pathname = '/path/to/resource'; const location = locationMock(`${pathname}`); const result = luxPath(location); expect(typeof result).toBe('string'); }); it('should return the pathname; if that is all that exists', function () { const pathname = '/path/to/resource'; const location = locationMock(`${pathname}`); const result = luxPath(location); expect(result).toBe(pathname); }); it('should return the pathname and queryString; when both are present', function () { const pathname = '/path/to/resource'; const location = locationMock(`${pathname}?abc=1234`); const result = luxPath(location); expect(result).toBe(`${pathname}?abc=1234`); }); it('should return the only queryString; when that\'s all there is', function () { const pathname = ''; const location = locationMock(`${pathname}?abc=1234`); const result = luxPath(location); expect(result).toBe(`${pathname}?abc=1234`); }); it('should return empty string', function () { const pathname = ''; const location = locationMock(`${pathname}`); const result = luxPath(location); expect(result).toBe(pathname); }); }); describe('[Location String]', function () { it('should return only a pathname when only a pathname exists', function () { const pathname = '/hello'; const location = `http://example.com${pathname}`; const result = luxPath(location); expect(result).toBe(pathname); }); it('should', function () { const querystring = '?zxy=123'; const location = `http://example.com${querystring}` const result = luxPath(location); expect(result).toBe(querystring); }); }); });
JavaScript
0.004552
@@ -2027,16 +2027,53 @@ ('should + parse partial with only query string ', funct
c9125f673743d26335fb358887879d3215087351
Improve loading ffmpeg from ffmpeg-binaries
src/transcoders/ffmpeg/Ffmpeg.js
src/transcoders/ffmpeg/Ffmpeg.js
const ChildProcess = require('child_process'); const FfmpegProcess = require('./FfmpegProcess'); const ffmpegSources = [ 'ffmpeg', 'avconv', './ffmpeg', './avconv', 'node_modules/ffmpeg-binaries/bin/ffmpeg', 'node_modules\\ffmpeg-binaries\\bin\\ffmpeg', ]; class FfmpegTranscoder { constructor(mediaTranscoder) { this.mediaTranscoder = mediaTranscoder; this.command = FfmpegTranscoder.selectFfmpegCommand(); this.processes = []; } static verifyOptions(options) { if (!options) throw new Error('Options not provided!'); if (!options.media) throw new Error('Media must be provided'); if (!options.ffmpegArguments || !(options.ffmpegArguments instanceof Array)) { throw new Error('FFMPEG Arguments must be an array'); } if (options.ffmpegArguments.includes('-i')) return options; if (typeof options.media === 'string') { options.ffmpegArguments = ['-i', `${options.media}`].concat(options.ffmpegArguments).concat(['pipe:1']); } else { options.ffmpegArguments = ['-i', '-'].concat(options.ffmpegArguments).concat(['pipe:1']); } return options; } /** * Transcodes an input using FFMPEG * @param {FfmpegTranscoderOptions} options the options to use * @returns {FfmpegProcess} the created FFMPEG process * @throws {FFMPEGOptionsError} */ transcode(options) { if (!this.command) this.command = FfmpegTranscoder.selectFfmpegCommand(); const proc = new FfmpegProcess(this, FfmpegTranscoder.verifyOptions(options)); this.processes.push(proc); return proc; } static selectFfmpegCommand() { for (const command of ffmpegSources) { if (!ChildProcess.spawnSync(command, ['-h']).error) return command; } throw new Error('FFMPEG not found'); } } module.exports = FfmpegTranscoder;
JavaScript
0.000001
@@ -95,181 +95,8 @@ );%0A%0A -const ffmpegSources = %5B%0A 'ffmpeg',%0A 'avconv',%0A './ffmpeg',%0A './avconv',%0A 'node_modules/ffmpeg-binaries/bin/ffmpeg',%0A 'node_modules%5C%5Cffmpeg-binaries%5C%5Cbin%5C%5Cffmpeg',%0A%5D;%0A%0A clas @@ -1424,24 +1424,110 @@ Command() %7B%0A + try %7B%0A return require('ffmpeg-binaries').ffmpegPath();%0A %7D catch (err) %7B%0A for (con @@ -1544,25 +1544,58 @@ of +%5B' ffmpeg -Sources +', 'avconv', './ffmpeg', './avconv'%5D ) %7B%0A + @@ -1664,26 +1664,30 @@ ommand;%0A -%7D%0A + %7D%0A throw ne @@ -1715,16 +1715,22 @@ ound');%0A + %7D%0A %7D%0A%7D%0A%0Am
e0afd563ace77581f7542250a7980726fdd8f67d
Add test coverage for Collapse wrapper ref (#6617)
src/transitions/Collapse.spec.js
src/transitions/Collapse.spec.js
// @flow weak import React from 'react'; import { assert } from 'chai'; import { spy, stub } from 'sinon'; import { createShallow } from 'src/test-utils'; import Collapse, { styleSheet } from './Collapse'; describe('<Collapse />', () => { let shallow; let classes; before(() => { shallow = createShallow(); classes = shallow.context.styleManager.render(styleSheet); }); it('should render a Transition', () => { const wrapper = shallow(<Collapse />); assert.strictEqual(wrapper.is('Transition'), true, 'is a Transition component'); }); it('should render a container around the wrapper', () => { const wrapper = shallow(<Collapse containerClassName="woof" />); assert.strictEqual(wrapper.childAt(0).is('div'), true, 'should be a div'); assert.strictEqual(wrapper.childAt(0).hasClass(classes.container), true, 'should have the container class'); assert.strictEqual(wrapper.childAt(0).hasClass('woof'), true, 'should have the user class'); }); it('should render a wrapper around the children', () => { const children = <h1>Hello</h1>; const wrapper = shallow(<Collapse>{children}</Collapse>); assert.strictEqual(wrapper.childAt(0).childAt(0).is('div'), true, 'should be a div'); assert.strictEqual(wrapper.childAt(0).childAt(0).children().equals(children), true, 'should wrap the children'); }); describe('event callbacks', () => { it('should fire event callbacks', () => { const events = [ 'onEnter', 'onEntering', 'onEntered', 'onExit', 'onExiting', 'onExited', ]; const handlers = events.reduce((result, n) => { result[n] = spy(); return result; }, {}); const wrapper = shallow(<Collapse {...handlers} />); events.forEach((n) => { const event = n.charAt(2).toLowerCase() + n.slice(3); wrapper.simulate(event, { style: {} }); assert.strictEqual(handlers[n].callCount, 1, `should have called the ${n} handler`); }); }); }); describe('transition lifecycle', () => { let wrapper; let instance; before(() => { wrapper = shallow(<Collapse />); instance = wrapper.instance(); }); describe('handleEnter()', () => { let element; before(() => { element = { style: { height: 32 } }; instance.handleEnter(element); }); it('should set element height to 0 initially', () => { assert.strictEqual(element.style.height, '0px', 'should set the height to 0'); }); }); describe('handleEntering()', () => { let element; before(() => { element = { style: { height: 0 } }; instance.wrapper = { clientHeight: 666 }; instance.handleEntering(element); }); it('should set element transition duration', () => { assert.strictEqual(element.style.transitionDuration, '300ms', 'should have the default 300ms duration'); }); it('should set height to the wrapper height', () => { assert.strictEqual(element.style.height, '666px', 'should have 666px height'); }); }); describe('handleEntered()', () => { let element; before(() => { element = { style: { height: 666, transitionDuration: '500ms' } }; instance.handleEntered(element); }); it('should set element transition duration to 0 to fix a safari bug', () => { assert.strictEqual(element.style.transitionDuration, '0ms', 'should have 0ms duration'); }); it('should set height to auto', () => { assert.strictEqual(element.style.height, 'auto', 'should have auto height'); }); }); describe('handleExit()', () => { let element; before(() => { element = { style: { height: 'auto' } }; instance.wrapper = { clientHeight: 666 }; instance.handleExit(element); }); it('should set height to the wrapper height', () => { assert.strictEqual(element.style.height, '666px', 'should have 666px height'); }); }); describe('handleExiting()', () => { let element; before(() => { element = { style: { height: 666 } }; instance.handleExiting(element); }); it('should set height to the 0', () => { assert.strictEqual(element.style.height, '0px', 'should have 0px height'); }); it('should call onExiting', () => { const onExitingStub = spy(); wrapper.setProps({ onExiting: onExitingStub }); instance = wrapper.instance(); instance.handleExiting(element); assert.strictEqual(onExitingStub.callCount, 1); assert.strictEqual(onExitingStub.calledWith(element), true); }); describe('transitionDuration', () => { let styleManagerMock; let transitionDurationMock; before(() => { styleManagerMock = wrapper.context('styleManager'); styleManagerMock.theme.transitions.getAutoHeightDuration = stub().returns('woof'); wrapper.setContext({ styleManager: styleManagerMock }); wrapper.setProps({ transitionDuration: 'auto' }); instance = wrapper.instance(); }); it('no wrapper', () => { instance.wrapper = false; instance.handleExiting(element); assert.strictEqual( element.style.transitionDuration, `${styleManagerMock.theme.transitions.getAutoHeightDuration(0)}ms`, ); }); it('has wrapper', () => { const clientHeightMock = 10; instance.wrapper = { clientHeight: clientHeightMock }; instance.handleExiting(element); assert.strictEqual( element.style.transitionDuration, `${styleManagerMock.theme.transitions.getAutoHeightDuration(clientHeightMock)}ms`, ); }); it('number should set transitionDuration to ms', () => { transitionDurationMock = 3; wrapper.setProps({ transitionDuration: transitionDurationMock }); instance = wrapper.instance(); instance.handleExiting(element); assert.strictEqual(element.style.transitionDuration, `${transitionDurationMock}ms`); }); it('string should set transitionDuration to string', () => { transitionDurationMock = 'woof'; wrapper.setProps({ transitionDuration: transitionDurationMock }); instance = wrapper.instance(); instance.handleExiting(element); assert.strictEqual(element.style.transitionDuration, transitionDurationMock); }); it('nothing should not set transitionDuration', () => { const elementBackup = element; wrapper.setProps({ transitionDuration: undefined }); instance = wrapper.instance(); instance.handleExiting(element); assert.strictEqual( element.style.transitionDuration, elementBackup.style.transitionDuration); }); }); }); }); });
JavaScript
0
@@ -123,16 +123,29 @@ eShallow +, createMount %7D from @@ -7079,13 +7079,377 @@ );%0A %7D); +%0A%0A describe('mount', () =%3E %7B%0A let mount;%0A let mountInstance;%0A%0A before(() =%3E %7B%0A mount = createMount();%0A mountInstance = mount(%3CCollapse /%3E).instance();%0A %7D);%0A%0A after(() =%3E %7B%0A mount.cleanUp();%0A %7D);%0A%0A it('instance should have a wrapper property', () =%3E %7B%0A assert.notStrictEqual(mountInstance.wrapper, undefined);%0A %7D);%0A %7D); %0A%7D);%0A
e72cfbfbd91544ecfc11ef75abc8f3bc91779ec9
Fix recursion
src/utils/filter_package_tree.js
src/utils/filter_package_tree.js
/** * @license Apache-2.0 * * Copyright (c) 2021 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. */ // MODULES // import reFromString from '@stdlib/utils/regexp-from-string'; // VARIABLES // var RE_FORWARD_SLASH = /\//g; // MAIN // /** * Applies a filter to a provide package tree. * * ## Notes * * - The filter may be a regular expression string. If unable to generate a regular expression from a provided `filter` string, the function returns `null`. * * @private * @param {ObjectArray} tree - package tree to filter * @param {string} filter - filter to apply * @param {ArrayLikeObject} [out] - output array for storing the list of matched packages * @returns {(ObjectArray|null)} filtered tree */ function filterTree( tree, filter, out ) { var matches; var node; var pkg; var tmp; var o; var i; try { filter = reFromString( '/'+filter.replace( RE_FORWARD_SLASH, '\\/' )+'/' ); } catch ( err ) { return null; } matches = []; for ( i = 0; i < tree.length; i++ ) { node = tree[ i ]; // Check if the current package satisfies the filter... if ( filter.test( node.name ) ) { // We found a match! We don't need to recurse any further... matches.push( node ); if ( out ) { out.push( node.name ); } continue; } // Check if the current package is a namespace (i.e., has children), and, if so, we need to continue descending down the tree to see if any child nodes satisfy the filter... if ( node.children ) { tmp = filterTree( node.children, filter, out ); // If we were able to resolve packages satisfying the filter, we need to copy the current (pruned) node in order to avoid mutation (we're modifying the `children` property)... if ( tmp ) { o = { 'key': node.key, 'name': node.name, 'children': tmp } matches.push( o ); if ( out ) { out.push( node.name ); } continue; } } } if ( matches.length === 0 ) { return null; } return matches; } // EXPORTS // export default filterTree;
JavaScript
0.998425
@@ -745,12 +745,17 @@ %0A// -MAIN +FUNCTIONS //%0A @@ -765,223 +765,82 @@ *%0A* -Applies a filter to a provide package tree.%0A*%0A* ## Notes%0A*%0A* - The filter may be a regular expression string. If unable to generate a regular expression from a provided %60filter%60 string, the function returns %60null%60 +Recursively applies a regular expression filter to a provided package tree .%0A*%0A @@ -913,22 +913,22 @@ @param %7B -string +RegExp %7D filter @@ -1093,25 +1093,22 @@ unction -filterTre +recurs e( tree, @@ -1190,130 +1190,8 @@ i;%0A%0A -%09try %7B%0A%09%09filter = reFromString( '/'+filter.replace( RE_FORWARD_SLASH, '%5C%5C/' )+'/' );%0A%09%7D catch ( err ) %7B%0A%09%09return null;%0A%09%7D%0A %09mat @@ -1719,25 +1719,22 @@ %09%09tmp = -filterTre +recurs e( node. @@ -2207,16 +2207,730 @@ es;%0A%7D%0A%0A%0A +// MAIN //%0A%0A/**%0A* Applies a filter to a provided package tree.%0A*%0A* ## Notes%0A*%0A* - The filter must be capable of being converted to a regular expression. If unable to generate a regular expression from a provided %60filter%60 string, the function returns %60null%60.%0A*%0A* @private%0A* @param %7BObjectArray%7D tree - package tree to filter%0A* @param %7Bstring%7D filter - filter to apply%0A* @param %7BArrayLikeObject%7D %5Bout%5D - output array for storing the list of matched packages%0A* @returns %7B(ObjectArray%7Cnull)%7D filtered tree%0A*/%0Afunction filterTree( tree, filter, out ) %7B%0A%09try %7B%0A%09%09filter = reFromString( '/'+filter.replace( RE_FORWARD_SLASH, '%5C%5C/' )+'/' );%0A%09%7D catch ( err ) %7B%0A%09%09return null;%0A%09%7D%0A%09return recurse( tree, filter, out );%0A%7D%0A%0A%0A // EXPOR
36f598451aa7525b738101255067b6e4fb50965e
fix map data
lib/fixtures/maps/map1.js
lib/fixtures/maps/map1.js
'use strict'; module.exports = { width: 16, height: 15, tiles: [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1], [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1], [1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1], [0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1], [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1], [1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1], [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1], [1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1], [1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ], respawnPoints: [ {y: 1, x: 1}, {y: 1, x: 14}, {y: 13, x: 1}, {y: 13, x: 14}, {y: 3, x: 3}, {y: 3, x: 10}, {y: 11, x: 5}, {y: 11, x: 10} ] };
JavaScript
0.000001
@@ -43,9 +43,9 @@ h: 1 -6 +5 ,%0A @@ -55,17 +55,17 @@ eight: 1 -5 +6 ,%0A ti @@ -1015,25 +1015,25 @@ %7By: 1, x: 1 -4 +3 %7D,%0A %7B @@ -1032,25 +1032,25 @@ %7By: 1 -3 +4 , x: 1%7D,%0A @@ -1063,16 +1063,16 @@ y: 1 -3 +4 , x: 1 -4 +3 %7D,%0A @@ -1111,17 +1111,17 @@ 3, x: 1 -0 +1 %7D,%0A @@ -1124,25 +1124,25 @@ %7By: 1 -1 +2 , x: 5%7D,%0A @@ -1155,16 +1155,15 @@ y: 1 -1 +2 , x: -10 +9 %7D%0A
a5957ecdd837d0d0b98e8ec2a4cc13ea9c3cca83
remove debugger statement
lib/forms/camunda-form.js
lib/forms/camunda-form.js
'use strict'; /* global CamSDK: false */ var $ = require('./dom-lib'), VariableManager = require('./variable-manager'), // BaseClass = require('./../base-class'), InputFieldHandler = require('./controls/input-field-handler'), ChoicesFieldHandler = require('./controls/choices-field-handler'); function CamundaForm(options) { if(!options) { throw new Error("CamundaForm need to be initialized with options."); } if (options.service) { this.service = options.service; } else { this.service = new CamSDK(options.serviceConfig || {}); } if (!options.taskId && !options.processDefinitionId && !options.processDefinitionKey) { throw new Error("Cannot initialize Taskform: either 'taskId' or 'processDefinitionId' or 'processDefinitionKey' must be provided"); } this.taskId = options.taskId; this.processDefinitionId = options.processDefinitionId; this.processDefinitionKey = options.processDefinitionKey; this.formElement = options.formElement; this.containerElement = options.containerElement; this.formUrl = options.formUrl; if(!this.formElement && !this.containerElement) { throw new Error("CamundaForm needs to be initilized with either 'formElement' or 'containerElement'"); } if(!this.formElement && !this.formUrl) { throw new Error("Camunda form needs to be intialized with either 'formElement' or 'formUrl'"); } this.variableManager = new VariableManager({ service: this.service }); this.formFieldHandlers = options.formFieldHandlers || [ InputFieldHandler, ChoicesFieldHandler ]; this.fields = []; this.initialize(options.initialized); } CamundaForm.prototype.initializeHandler = function(FieldHandler) { var self = this; var selector = FieldHandler.selector; $(selector, self.formElement).each(function() { self.fields.push(new FieldHandler(this, self.variableManager)); }); }; CamundaForm.prototype.initialize = function(done) { done = done || function() {}; var self = this; // check whether form needs to be loaded first if(this.formUrl) { this.service.http.load(this.formUrl, { done: function(err, result) { if(err) { return done(err); } self.renderForm(result); self.initializeForm(done); } }); } else { this.initializeForm(done); } }; CamundaForm.prototype.renderForm = function(formHtmlSource) { // apppend the form html to the container element, // we also wrap the formHtmlSource to limit the risks of breaking // the structure of the document $(this.containerElement).html('').append('<div class="injected-form-wrapper">'+formHtmlSource+'</div>'); // extract and validate form element this.formElement = $("form[cam-form]", this.containerElement); if(this.formElement.length !== 1) { throw new Error("Form must provide exaclty one element <form cam-form ..>"); } }; CamundaForm.prototype.initializeForm = function(done) { var self = this; for(var FieldHandler in this.formFieldHandlers) { this.initializeHandler(this.formFieldHandlers[FieldHandler]); } this.fetchVariables(function(err, result) { if (err) { throw err; } // merge the variables self.mergeVariables(result); // apply the variables to the form fields self.applyVariables(); /* jshint debug: true */ debugger; /* jshint debug: false */ // invoke callback done(); }); }; CamundaForm.prototype.submit = function(callback) { // get values from form fields this.retrieveVariables(); // submit the form variables this.submitVariables(function(err, result) { if(err) { return callback(err); } callback(null, result); }); }; CamundaForm.prototype.fetchVariables = function(done) { done = done || function(){}; var data = { names: this.variableManager.variableNames() }; // pass either the taskId, processDefinitionId or processDefinitionKey if (this.taskId) { data.id = this.taskId; this.service.resource('task').formVariables(data, done); } else { data.id = this.processDefinitionId; data.key = this.processDefinitionKey; this.service.resource('process-definition').formVariables(data, done); } }; CamundaForm.prototype.submitVariables = function(done) { done = done || function() {}; var vars = this.variableManager.variables; var variableData = {}; for(var v in vars) { // only submit dirty variables if(!!vars[v].isDirty) { variableData[v] = { value: vars[v].value, type: vars[v].type }; } } var data = { variables: variableData }; // pass either the taskId, processDefinitionId or processDefinitionKey if (this.taskId) { data.id = this.taskId; this.service.resource('task').submitForm(data, done); } else { data.id = this.processDefinitionId; data.key = this.processDefinitionKey; this.service.resource('process-definition').submitForm(data, done); } }; CamundaForm.prototype.mergeVariables = function(variables) { var vars = this.variableManager.variables; for (var v in variables) { if (vars[v]) { for (var p in variables[v]) { vars[v][p] = vars[v][p] || variables[v][p]; } } else { vars[v] = variables[v]; } } }; CamundaForm.prototype.applyVariables = function() { for (var i in this.fields) { this.fields[i].applyValue(); } }; CamundaForm.prototype.retrieveVariables = function() { for (var i in this.fields) { this.fields[i].getValue(); } }; CamundaForm.$ = $; module.exports = CamundaForm;
JavaScript
0.000117
@@ -3327,70 +3327,8 @@ );%0A%0A -/* jshint debug: true */%0Adebugger;%0A/* jshint debug: false */%0A%0A
101ec488baae88ef42ba89c769dd9c97743e4df4
Update bitboxPaths.js
src/wallets/bip44/bitboxPaths.js
src/wallets/bip44/bitboxPaths.js
import { ethereum, ethereumClassic, ropsten, singularDTV, expanse, ubiq, ellaism, etherGem, callisto, ethereumSocial, musicoin, goChain, eosClassic, akroma, etherSocialNetwork, pirl, ether1, atheios, tomoChain, mixBlockchain, iolite } from './paths'; export default [ ethereum, ethereumClassic, ropsten, singularDTV, expanse, ubiq, ellaism, etherGem, callisto, ethereumSocial, musicoin, goChain, eosClassic, akroma, etherSocialNetwork, pirl, ether1, atheios, tomoChain, mixBlockchain, iolite, solidum ];
JavaScript
0
@@ -572,19 +572,8 @@ lite -,%0A solidum %0A%5D;%0A
7268434334cb9e9ca1b182a11028e57e69c43f71
fix bug would insert instead of update
startup/client/companies/code.js
startup/client/companies/code.js
Meteor.subscribe('theCompanies'); Template.companies.helpers({ 'company': function(){ return Companies.find(); }, 'selectedClass': function(){ if(this._id == Session.get('selectedCompanyId')){ return "selected" } }, 'selectedCompany': function(){ return Companies.findOne({ _id: Session.get('selectedCompanyId') }); } }); Template.companies.onRendered(function () { cform = document.getElementById("companyForm"); }); function cleanCompanyForm() { cform.TaxId.value = ""; cform.Name.value = ""; cform.Rating.value = 0; } function showForm() { $( cform ).show(); } function hideForm() { $( cform ).hide(); } Template.companies.events({ 'click .company': function(){ Session.set('selectedCompanyId', this._id); hideForm(); }, 'click .create': function(){ cleanCompanyForm(); showForm(); Session.set('selectedCompanyId', null); }, 'click .edit': function(){ showForm(); var c = Template.companies.__helpers.get("selectedCompany").call(); document.getElementById("TaxId").value = c.TaxId; document.getElementById("Name").value = c.Name; document.getElementById("Rating").value = c.Rating; }, 'click .remove': function(){ var company = Company.findOne({_id: Session.get('selectedCompanyId')}); Meteor.call('removeCompany', company); hideForm(); } }); Template.editCompanyForm.events({ 'submit form': function(event){ event.preventDefault(); var company = new Company(); // TODO: make generic company.TaxId = cform.TaxId.value; company.Name = cform.Name.value; company.Rating = Number(cform.Rating.value); Meteor.call('saveCompany', company); hideForm(); cleanCompanyForm(); } });
JavaScript
0
@@ -717,16 +717,291 @@ ();%09%0A%7D%0A%0A +// return currently selected company object or if none a newly created one%0Afunction getCompany() %7B%0A if (Session.get('selectedCompanyId') == null) %7B %0A %09%09return new Company();%0A %7D else %7B%0A return Company.findOne(%7B_id: Session.get('selectedCompanyId')%7D);%0A %7D%0A%7D%0A%0A Template @@ -1585,88 +1585,8 @@ ()%7B%0A - var company = Company.findOne(%7B_id: Session.get('selectedCompanyId')%7D);%0A @@ -1610,39 +1610,44 @@ removeCompany', -c +getC ompany +() );%0A%09%09hideForm(); @@ -1782,20 +1782,19 @@ mpany = -new +get Company(
2158ef710d52118db7a57810c07d62160713ab63
Simplify syntax in nbconvert-css webpack config
packages/nbconvert-css/webpack.config.js
packages/nbconvert-css/webpack.config.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const path = require('path'); module.exports = { entry: './raw.css', output: { filename: 'index.js', path: path.resolve(__dirname, 'style') }, plugins: [ new MiniCssExtractPlugin({ filename: 'index.css' }) ], module: { rules: [ { test: /\.css$/, use: [ { loader: MiniCssExtractPlugin.loader }, 'css-loader' ] }, { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader' }, /* Use null-loader to drop resources that are not used in the CSS */ { test: /\.(jpg|png|gif)$/, use: 'null-loader' }, { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, use: 'null-loader' }, { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, use: 'null-loader' }, { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, use: 'null-loader' }, { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, use: 'null-loader' } ] } };
JavaScript
0.00004
@@ -375,41 +375,8 @@ e: %5B -%0A %7B%0A loader: Mini @@ -402,31 +402,9 @@ ader -%0A %7D,%0A +, 'cs @@ -412,25 +412,16 @@ -loader' -%0A %5D%0A
2e1c1adeddb2242c96e9ca87e1541f8ac48710b0
Use max-age=31536000 and immutable in Cache-Control (#177) (#182)
packages/@cra-express/static-loader/src/index.js
packages/@cra-express/static-loader/src/index.js
const express = require("express"); const bodyParser = require("body-parser"); const compression = require("compression"); function staticLoader(app, options) { const { clientBuildPath } = options; app.use(compression()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // Serve static assets if (process.env.NODE_ENV === "development") { // Connect proxy to Create React App dev server const proxy = require("http-proxy-middleware"); const craServiceName = process.env.CRA_SERVICE_NAME || 'localhost'; const craClientPort = process.env.CRA_CLIENT_PORT || 3000; app.use( ["**/*.*", "/static", "/sockjs-node"], proxy({ target: `http://${craServiceName}:${craClientPort}`, changeOrigin: true, ws: true }) ); console.log("Connected to CRA Client dev server"); } else { app.use(express.static(clientBuildPath, { index: false })); } return app; } export default staticLoader;
JavaScript
0.000001
@@ -933,24 +933,66 @@ index: false +, immutable: true, maxAge: 31536000 * 1000 %7D));%0A %7D%0A%0A
394a1bbb2f183e42393eab7e10cc9089bdd94f69
Add debug message to chromoting extension
remoting/client/extension/chromoting_tab.js
remoting/client/extension/chromoting_tab.js
// Copyright (c) 2010 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. // Message id so that we can identify (and ignore) message fade operations for // old messages. This starts at 1 and is incremented for each new message. chromoting.messageId = 1; function init() { // This page should only get one request, and it should be // from the chromoting extension asking for initial connection. // Later we may need to create a more persistent channel for // better UI communication. Then, we should probably switch // to chrome.extension.connect(). chrome.extension.onRequest.addListener(requestListener); } function submitLogin() { var username = document.getElementById("username").value; var password = document.getElementById("password").value; // Make the login panel invisible and submit login info. document.getElementById("login_panel").style.display = "none"; chromoting.plugin.submitLoginInfo(username, password); } /** * A listener function to be called when the extension fires a request. * * @param request The request sent by the calling script. * @param sender The MessageSender object with info about the calling script's * context. * @param sendResponse Function to call with response. */ function requestListener(request, sender, sendResponse) { console.log(sender.tab ? 'from a content script: ' + sender.tab.url : 'from the extension'); // Kick off the connection. var plugin = document.getElementById('chromoting'); chromoting.plugin = plugin; chromoting.username = request.username; chromoting.hostname = request.hostName; // Setup the callback that the plugin will call when the connection status // has changes and the UI needs to be updated. It needs to be an object with // a 'callback' property that contains the callback function. plugin.connectionInfoUpdate = pluginCallback; plugin.loginChallenge = pluginLoginChallenge; // TODO(garykac): Clean exit if |connect| isn't a funtion. if (typeof plugin.connect === 'function') { plugin.connect(request.username, request.hostJid, request.xmppAuth); } document.getElementById('title').innerText = request.hostName; // Send an empty response since we have nothing to say. sendResponse({}); } /** * This is the callback method that the plugin calls to request username and * password for logging into the remote host. */ function pluginLoginChallenge() { // Make the login panel visible. document.getElementById("login_panel").style.display = "block"; } /** * This is a callback that gets called when the desktop size contained in the * the plugin has changed. */ function desktopSizeChanged() { var width = chromoting.plugin.desktopWidth; var height = chromoting.plugin.desktopHeight; console.log('desktop size changed: ' + width + 'x' + height); chromoting.plugin.style.width = width + "px"; chromoting.plugin.style.height = height + "px"; } /** * Show a client message on the screen. * If duration is specified, the message fades out after the duration expires. * Otherwise, the message stays until the state changes. * * @param {string} message The message to display. * @param {number} duration Milliseconds to show message before fading. */ function showClientStateMessage(message, duration) { // Increment message id to ignore any previous fadeout requests. chromoting.messageId++; console.log('setting message ' + chromoting.messageId + '!'); // Update the status message. var msg = document.getElementById('status_msg'); msg.innerText = message; msg.style.opacity = 1; if (duration) { // Set message duration. window.setTimeout("fade('status_msg', " + chromoting.messageId + ", " + "100, 10, 200)", duration); } } /** * This is that callback that the plugin invokes to indicate that the * host/client connection status has changed. */ function pluginCallback() { var status = chromoting.plugin.status; var quality = chromoting.plugin.quality; if (status == chromoting.plugin.STATUS_UNKNOWN) { setClientStateMessage(''); } else if (status == chromoting.plugin.STATUS_CONNECTING) { setClientStateMessage('Connecting to ' + chromoting.hostname + ' as ' + chromoting.username); } else if (status == chromoting.plugin.STATUS_INITIALIZING) { setClientStateMessageFade('Initializing connection to ' + chromoting.hostname); } else if (status == chromoting.plugin.STATUS_CONNECTED) { desktopSizeChanged(); setClientStateMessageFade('Connected to ' + chromoting.hostname, 1000); } else if (status == chromoting.plugin.STATUS_CLOSED) { setClientStateMessage('Closed'); } else if (status == chromoting.plugin.STATUS_FAILED) { setClientStateMessage('Failed'); } } /** * Show a client message that stays on the screeen until the state changes. * * @param {string} message The message to display. */ function setClientStateMessage(message) { // Increment message id to ignore any previous fadeout requests. chromoting.messageId++; console.log('setting message ' + chromoting.messageId); // Update the status message. var msg = document.getElementById('status_msg'); msg.innerText = message; msg.style.opacity = 1; } /** * Show a client message for the specified amount of time. * * @param {string} message The message to display. * @param {number} duration Milliseconds to show message before fading. */ function setClientStateMessageFade(message, duration) { setClientStateMessage(message); // Set message duration. window.setTimeout("fade('status_msg', " + chromoting.messageId + ", " + "100, 10, 200)", duration); } /** * Fade the specified element. * For example, to have element 'foo' fade away over 2 seconds, you could use * either: * fade('foo', 100, 10, 200) * - Start at 100%, decrease by 10% each time, wait 200ms between updates. * fade('foo', 100, 5, 100) * - Start at 100%, decrease by 5% each time, wait 100ms between updates. * * @param {string} name Name of element to fade. * @param {number} id The id of the message associated with this fade request. * @param {number} val The new opacity value (0-100) for this element. * @param {number} delta Amount to adjust the opacity each iteration. * @param {number} delay Delay (in ms) to wait between each update. */ function fade(name, id, val, delta, delay) { // Ignore the fade call if it does not apply to the current message. if (id != chromoting.messageId) { return; } var e = document.getElementById(name); if (e) { var newVal = val - delta; if (newVal > 0) { // Decrease opacity and set timer for next fade event. e.style.opacity = newVal / 100; window.setTimeout("fade('status_msg', " + id + ", " + newVal + ", " + delta + ", " + delay + ")", delay); } else { // Completely hide the text and stop fading. e.style.opacity = 0; } } }
JavaScript
0.000011
@@ -2039,24 +2039,137 @@ Challenge;%0A%0A + console.log('connect request received: ' + chromoting.hostname + ' by ' +%0A chromoting.username);%0A%0A // TODO(ga @@ -2354,24 +2354,91 @@ ppAuth);%0A %7D + else %7B%0A console.log('ERROR: chromoting plugin not loaded');%0A %7D %0A%0A document
0e59566902448e5d646a1dd18bd57d784268fcc1
use destructuring import in example
example/App.js
example/App.js
/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow * @lint-ignore-every XPLATJSCOPYRIGHT1 */ import React, {Component} from 'react'; import {Platform, ScrollView, StyleSheet, Text, View, SafeAreaView} from 'react-native'; import DeviceInfo from 'react-native-device-info'; const instructions = Platform.select({ ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu', android: 'Double tap R on your keyboard to reload,\n' + 'Shake or press menu button for dev menu', }); type Props = {}; export default class App extends Component<Props> { constructor(props) { super(props); this.state = { deviceinfo: {}, }; } async componentDidMount() { let deviceJSON = {}; const ios = Platform.OS === 'ios'; try { deviceJSON.uniqueID = DeviceInfo.getUniqueID(); deviceJSON.manufacturer = DeviceInfo.getManufacturer(); deviceJSON.brand = DeviceInfo.getBrand(); deviceJSON.model = DeviceInfo.getModel(); deviceJSON.deviceId = DeviceInfo.getDeviceId(); deviceJSON.systemName = DeviceInfo.getSystemName(); deviceJSON.systemVersion = DeviceInfo.getSystemVersion(); deviceJSON.buildId = DeviceInfo.getBuildId(); deviceJSON.bundleId = DeviceInfo.getBundleId(); deviceJSON.isCameraPresent = ios ? -1 : await DeviceInfo.getCameraPresence(); deviceJSON.buildNumber = DeviceInfo.getBuildNumber(); deviceJSON.version = DeviceInfo.getVersion(); deviceJSON.readableVersion = DeviceInfo.getReadableVersion(); deviceJSON.deviceName = DeviceInfo.getDeviceName(); // needs android.permission.BLUETOOTH ? deviceJSON.userAgent = DeviceInfo.getUserAgent(); deviceJSON.deviceLocale = DeviceInfo.getDeviceLocale(); deviceJSON.preferredLocales = DeviceInfo.getPreferredLocales(); deviceJSON.deviceCountry = DeviceInfo.getDeviceCountry(); deviceJSON.timezone = DeviceInfo.getTimezone(); deviceJSON.instanceID = ios ? '' : DeviceInfo.getInstanceID(); deviceJSON.installReferrer = ios ? '' : DeviceInfo.getInstallReferrer(); deviceJSON.isEmulator = DeviceInfo.isEmulator(); deviceJSON.isTablet = DeviceInfo.isTablet(); deviceJSON.fontScale = DeviceInfo.getFontScale(); deviceJSON.hasNotch = DeviceInfo.hasNotch(); deviceJSON.firstInstallTime = ios ? -1 : DeviceInfo.getFirstInstallTime(); deviceJSON.lastUpdateTime = ios ? -1 : DeviceInfo.getLastUpdateTime(); deviceJSON.serialNumber = ios ? -1 : DeviceInfo.getSerialNumber(); deviceJSON.IPAddress = await DeviceInfo.getIPAddress(); deviceJSON.MACAddress = await DeviceInfo.getMACAddress(); // needs android.permission.ACCESS_WIFI_STATE ? deviceJSON.phoneNumber = ios ? '' : DeviceInfo.getPhoneNumber(); // needs android.permission.READ_PHONE_STATE ? deviceJSON.APILevel = ios ? -1 : DeviceInfo.getAPILevel(); deviceJSON.carrier = DeviceInfo.getCarrier(); deviceJSON.totalMemory = DeviceInfo.getTotalMemory(); deviceJSON.maxMemory = ios ? -1 : DeviceInfo.getMaxMemory(); deviceJSON.totalDiskCapacity = DeviceInfo.getTotalDiskCapacity(); // FIXME needs a patch for integer overflow on Android deviceJSON.freeDiskStorage = DeviceInfo.getFreeDiskStorage(); // FIXME needs a patch for integer overflow on Android deviceJSON.batteryLevel = await DeviceInfo.getBatteryLevel(); deviceJSON.isLandscape = DeviceInfo.isLandscape(); deviceJSON.isAirplaneMode = ios ? false : await DeviceInfo.isAirPlaneMode(); deviceJSON.isBatteryCharging = ios ? false : await DeviceInfo.isBatteryCharging(); deviceJSON.deviceType = DeviceInfo.getDeviceType(); deviceJSON.isPinOrFingerprintSet = 'unknown'; deviceJSON.supportedABIs = DeviceInfo.supportedABIs(); deviceJSON.hasSystemFeature = ios ? false : await DeviceInfo.hasSystemFeature('amazon.hardware.fire_tv'); deviceJSON.getSystemAvailableFeatures = ios ? [] : await DeviceInfo.getSystemAvailableFeatures(); deviceJSON.powerState = ios ? await DeviceInfo.getPowerState() : ''; deviceJSON.isLocationEnabled = await DeviceInfo.isLocationEnabled(); deviceJSON.getAvailableLocationProviders = await DeviceInfo.getAvailableLocationProviders(); deviceJSON.bootloader = ios ? '' : DeviceInfo.getBootloader(); deviceJSON.device = ios ? '' : DeviceInfo.getDevice(); deviceJSON.display = ios ? '' : DeviceInfo.getDisplay(); deviceJSON.fingerprint = ios ? '' : DeviceInfo.getFingerprint(); deviceJSON.hardware = ios ? '' : DeviceInfo.getHardware(); deviceJSON.host = ios ? '' : DeviceInfo.getHost(); deviceJSON.product = ios ? '' : DeviceInfo.getProduct(); deviceJSON.tags = ios ? '' : DeviceInfo.getTags(); deviceJSON.type = ios ? '' : DeviceInfo.getType(); deviceJSON.baseOS = ios ? '' : DeviceInfo.getBaseOS(); deviceJSON.previewSdkInt = ios ? -1 : DeviceInfo.getPreviewSdkInt(); deviceJSON.securityPatch = ios ? '' : DeviceInfo.getSecurityPatch(); deviceJSON.codename = ios ? '' : DeviceInfo.getCodename(); deviceJSON.incremental = ios ? '' : DeviceInfo.getIncremental(); deviceJSON.supported32BitAbis = ios ? [] : DeviceInfo.supported32BitAbis(); deviceJSON.supported64BitAbis = ios ? [] : DeviceInfo.supported64BitAbis(); } catch (e) { console.log('Trouble getting device info ', e); } DeviceInfo.isPinOrFingerprintSet()(this.keyguardCallback); console.log('loaded info'); this.setState({ deviceinfo: deviceJSON }); this.forceUpdate(); console.log(this.state.deviceinfo); } keyguardCallback = (pinSet) => { console.log('callback called with value: ' + pinSet); let deviceJSON = this.state.deviceinfo; deviceJSON.isPinOrFingerprintSet = pinSet; this.setState({ deviceinfo: deviceJSON }); this.forceUpdate(); }; render() { return ( <SafeAreaView style={styles.container}> <Text style={styles.welcome}>react-native-device-info example - info:</Text> <ScrollView> <Text style={styles.instructions}>{JSON.stringify(this.state.deviceinfo, null, '\t')}</Text> </ScrollView> </SafeAreaView> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'left', color: '#333333', marginBottom: 5, }, });
JavaScript
0.000001
@@ -315,16 +315,120 @@ e-info'; +%0Aimport %7BgetUniqueID, getManufacturer, getBrand, getModel, getDeviceId%7D from 'react-native-device-info'; %0A%0Aconst @@ -939,27 +939,16 @@ queID = -DeviceInfo. getUniqu @@ -986,27 +986,16 @@ turer = -DeviceInfo. getManuf @@ -1026,35 +1026,24 @@ SON.brand = -DeviceInfo. getBrand();%0A @@ -1067,27 +1067,16 @@ model = -DeviceInfo. getModel @@ -1107,27 +1107,16 @@ iceId = -DeviceInfo. getDevic
1a521561bf335b74af692f13c11ea112b4af0088
Remove readystate check - no longer using mongodb for sessions
web/index.js
web/index.js
const path = require('path') const config = require('../config.js') const TEST_ENV = process.env.NODE_ENV === 'test' if (!TEST_ENV) process.env.NODE_ENV = 'production' const morgan = require('morgan') const express = require('express') const session = require('express-session') const compression = require('compression') const RedisStore = require('connect-redis')(session) const discordAPIConstants = require('./constants/discordAPI.js') const apiRoutes = require('./routes/api/index.js') const storage = require('../util/storage.js') const mongoose = require('mongoose') const app = express() const http = require('http').Server(app) const log = require('../util/logger.js') const fetchUser = require('./util/fetchUser.js') const PORT = TEST_ENV ? 8081 : config.web.port const REDIRECT_URI = config.web.redirectUri const sharedSession = require('express-socket.io-session') const SCOPES = 'identify guilds' const tokenConfig = code => { return { code, redirect_uri: REDIRECT_URI, scope: SCOPES } } let httpIo = require('socket.io').listen(http) let https let httpsIo let httpsPort if (config.web && config.web.https && config.web.https.enabled === true) { const { privateKey, certificate, chain, port } = config.web.https if (!privateKey || !certificate || !chain) throw new Error('Missing private key, certificate, or chain file path for enabled https') const fs = require('fs') const key = fs.readFileSync(privateKey, 'utf8') const cert = fs.readFileSync(certificate, 'utf8') const ca = fs.readFileSync(chain, 'utf8') httpsPort = port https = require('https').Server({ key, cert, ca }, app) httpsIo = require('socket.io').listen(https) } const credentials = { client: { id: config.web.clientId, secret: config.web.clientSecret }, auth: discordAPIConstants.auth } const oauth2 = require('simple-oauth2').create(credentials) if (!TEST_ENV && (!config.web.clientId || !config.web.clientSecret || !config.web.port)) throw new Error('Missing Cient ID, Secret and/or Port for web UI') module.exports = () => { if (TEST_ENV) { mongoose.connect(config.database.uri, { useNewUrlParser: true }) mongoose.set('useCreateIndex', true) return start(mongoose.connection) } if (!storage.redisClient) throw new Error('Redis is not connected for Web UI') start() } function start (mongooseConnection = mongoose.connection) { // Middleware app.use(compression()) app.use(function mongoAndCORS (req, res, next) { // Make sure the database connection works on every API request if (!TEST_ENV && mongoose.connection.readyState !== 1) { console.log('Ingoring request due to mongoose readyState !== 1') return res.status(500).json({ status: 500, message: 'Internal Server Error' }) } // Disallow CORS // res.header('Access-Control-Allow-Origin', '*') // res.header('Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept') next() }) app.use(express.json()) // Sessions // app.set('trust proxy', 1) // trust first proxy const session = require('express-session')({ secret: config.web.sessionSecret, resave: false, saveUninitialized: false, cookie: { secure: false }, // Set secure to true for HTTPS - otherwise sessions will not be saved maxAge: 1 * 24 * 60 * 60, // 1 day store: new RedisStore({ client: storage.redisClient // Recycle connection }) }) app.use(session) if (!TEST_ENV) { // Logging app.use(morgan(function (tokens, req, res) { const custom = [] if (req.session && req.session.identity) custom.push(`(U: ${req.session.identity.id}, ${req.session.identity.username})`) if (req.guildRss) custom.push(`(G: ${req.guildRss.id}, ${req.guildRss.name})`) const arr = [ tokens['remote-addr'](req, res), ...custom, tokens.method(req, res), tokens.url(req, res), tokens.status(req, res), tokens.res(req, res, 'content-length'), '-', tokens['response-time'](req, res), 'ms' ] return arr.join(' ') })) httpIo.use(sharedSession(session, { autoSave: true })) require('./redis/index.js')(httpIo, httpsIo) require('./websockets/index.js')(httpIo, false) if (httpsIo) { httpsIo.use(sharedSession(session, { autoSave: true })) require('./websockets/index.js')(httpsIo, true) } } // Application-specific variables app.set('oauth2', oauth2) // Routes app.use(express.static(path.join(__dirname, 'client/build'))) app.use('/api', apiRoutes) app.get('/login', (req, res) => { const authorizationUri = oauth2.authorizationCode.authorizeURL({ redirect_uri: REDIRECT_URI, scope: SCOPES }) res.redirect(authorizationUri) }) app.get('/logout', async (req, res, next) => { try { await oauth2.accessToken.create(req.session.auth).revokeAll() req.session.destroy(err => err ? next(err) : res.redirect('/')) } catch (err) { next(err) } }) app.get('/authorize', async (req, res) => { try { const result = await oauth2.authorizationCode.getToken(tokenConfig(req.query.code)) const accessTokenObject = oauth2.accessToken.create(result) // class with properties access_token, token_type = 'Bearer', expires_in, refresh_token, scope, expires_at req.session.auth = accessTokenObject.token req.session.identity = await fetchUser.info(req.session.identity ? req.session.identity.id : null, req.session.auth.access_token) log.web.info(`(${req.session.identity.id}, ${req.session.identity.username}) Logged in`) res.redirect('/') } catch (err) { log.web.error(`Failed to authorize Discord`, err) res.redirect('/') } }) if (TEST_ENV) { app.post('/session', (req, res, next) => { req.session.auth = req.body.auth req.session.identity = req.body.identity res.end('ok') }) } // Redirect all other routes not handled app.get('*', async (req, res) => { res.sendFile(path.join(__dirname, 'client/build', 'index.html')) }) if (!TEST_ENV) { http.listen(PORT, () => log.web.success(`HTTP UI listening on port ${PORT}!`)) if (https) https.listen(httpsPort, () => log.web.success(`HTTPS UI listening on port ${httpsPort}!`)) } return app }
JavaScript
0
@@ -2456,299 +2456,8 @@ ) %7B%0A - // Make sure the database connection works on every API request%0A if (!TEST_ENV && mongoose.connection.readyState !== 1) %7B%0A console.log('Ingoring request due to mongoose readyState !== 1')%0A return res.status(500).json(%7B status: 500, message: 'Internal Server Error' %7D)%0A %7D%0A
1489c022e4aab0ebe051445174de2cd24e1e8519
Fix example.
example/app.js
example/app.js
require([ 'example/jquery.js', 'example/mustache.js', '../lunr.js', 'text!templates/question_view.mustache', 'text!templates/question_list.mustache', 'text!example_data.json', 'text!example_index.json' ], function (_, Mustache, lunr, questionView, questionList, data, indexDump) { var renderQuestionList = function (qs) { $("#question-list-container") .empty() .append(Mustache.to_html(questionList, {questions: qs})) } var renderQuestionView = function (question) { $("#question-view-container") .empty() .append(Mustache.to_html(questionView, question)) } window.profile = function (term) { console.profile('search') idx.search(term) console.profileEnd('search') } window.search = function (term) { console.time('search') idx.search(term) console.timeEnd('search') } var indexDump = JSON.parse(indexDump) console.time('load') window.idx = lunr.Index.load(indexDump) console.timeEnd('load') var questions = JSON.parse(data).questions.map(function (raw) { return { id: raw.question_id, title: raw.title, body: raw.body, tags: raw.tags.join(' ') } }) renderQuestionList(questions) renderQuestionView(questions[0]) $('a.all').bind('click', function () { renderQuestionList(questions) $('input').val('') }) var debounce = function (fn) { var timeout return function () { var args = Array.prototype.slice.call(arguments), ctx = this clearTimeout(timeout) timeout = setTimeout(function () { fn.apply(ctx, args) }, 100) } } $('input').bind('keyup', debounce(function () { if ($(this).val() < 2) return var query = $(this).val() var results = idx.search(query).map(function (result) { return questions.filter(function (q) { return q.id === parseInt(result.ref, 10) })[0] }) renderQuestionList(results) })) $("#question-list-container").delegate('li', 'click', function () { var li = $(this) var id = li.data('question-id') renderQuestionView(questions.filter(function (question) { return (question.id == id) })[0]) }) })
JavaScript
0.000004
@@ -2,24 +2,25 @@ equire(%5B%0A ' +/ example/jque @@ -30,16 +30,17 @@ js',%0A ' +/ example/
45a888a24b84f0db6f47e9ea86c73616a51b7935
Use --harmony_proxies
execjstests.js
execjstests.js
var childProcess = require('child_process'); var fs = require('fs'); var jstests = fs.readdirSync('./jstests/'); var success = 0; jstests.forEach(function(file) { console.log('\n\n------'); console.log('Executing: ' + file); try { childProcess.execSync('node --harmony index.js --file ./jstests/' + file); ++success; } catch(e) { console.log('Test failed: ' + e); } }); console.log('Passed: ' + success + '/' + jstests.length);
JavaScript
0
@@ -275,16 +275,34 @@ harmony +--harmony_proxies index.js
5d26c7493b4b2e59a26d38ed3572b7225c260f7c
fix jshint error
addon/components/drop-zone.js
addon/components/drop-zone.js
/* global Dropzone*/ import Ember from 'ember'; export default Ember.Component.extend({ classNames: ['dropzone'], myDropzone:undefined, element: null, dropzoneOptions: null, // Configuration Options url: '#', withCredentials: null, method: null, parallelUploads: null, maxFilesize: null, filesizeBase: null, paramName: null, uploadMultiple: null, headers: null, addRemoveLinks: null, previewsContainer: null, clickable: null, maxThumbnailsize: null, thumbnailWidth: null, thumbnailHeight: null, maxFiles: null, // resize: not available acceptedFiles: null, autoProcessQueue: null, forceFallback: null, previewTemplate: null, // Dropzone translations dictDefaultMessage: null, dictFallbackMessage: null, dictFallbackText: null, dictInvalidFileType: null, dictFileTooBig: null, dictResponseError: null, dictCancelUpload: null, dictCancelUploadConfirmation: null, dictRemoveFile: null, dictMaxFilesExceeded: null, // Events // All of these receive the event as first parameter: drop: null, dragstart: null, dragend: null, dragenter: null, dragover: null, dragleave: null, // All of these receive the file as first parameter: addedfile: null, removedfile: null, thumbnail: null, error: null, processing: null, uploadprogress: null, sending: null, success: null, complete: null, canceled: null, maxfilesreached: null, maxfilesexceeded: null, // All of these receive a list of files as first parameter and are only called if the uploadMultiple option is true: processingmultiple: null, sendingmultiple: null, successmultiple: null, completemultiple: null, canceledmultiple: null, // Special events: totaluploadprogress: null, reset: null, queuecomplete: null, files: null, // Callback functions accept: null, setEvents() { let myDropzone = this.get('myDropzone'); let events = { drop: this.drop, dragstart: this.dragstart, dragend: this.dragend, dragenter: this.dragenter, dragover: this.dragover, dragleave: this.dragleave, addedfile: this.addedfile, removedfile: this.removedfile, thumbnail: this.thumbnail, error: this.error, processing: this.processing, uploadprogress: this.uploadprogress, sending: this.sending, success: this.success, complete: this.complete, canceled: this.canceled, maxfilesreached: this.maxfilesreached, maxfilesexceeded: this.maxfilesexceeded, processingmultiple: this.processingmultiple, sendingmultiple: this.sendingmultiple, successmultiple: this.successmultiple, completemultiple: this.completemultiple, canceledmultiple: this.canceledmultiple, totaluploadprogress: this.totaluploadprogress, reset: this.reset, queuecomplete: this.queuecomplete, files: this.files, accept: this.accept, }; for (let e in events) { if (events[e] !== null) { myDropzone.on(e, events[e]); } } }, getDropzoneOptions() { const onDragEnterLeaveHandler = function(dropzoneInstance) { const onDrag = ( element => { let dragCounter = 0; return { enter(event) { event.preventDefault(); dragCounter++; element.classList.add('dz-drag-hover'); }, leave() { dragCounter--; if (dragCounter === 0) { element.classList.remove('dz-drag-hover'); } } }; })(dropzoneInstance.element); dropzoneInstance.on('dragenter', onDrag.enter); dropzoneInstance.on('dragleave', onDrag.leave); }; let dropzoneOptions = {}; let dropzoneConfig = { url: this.url, withCredentials: this.withCredentials, method: this.method, parallelUploads: this.parallelUploads, maxFilesize: this.maxFilesize, filesizeBase: this.filesizeBase, paramName: this.paramName, uploadMultiple: this.uploadMultiple, headers: this.headers, addRemoveLinks: this.addRemoveLinks, previewsContainer: this.previewsContainer, clickable: this.clickable, maxThumbnailsize: this.maxThumbnailsize, thumbnailWidth: this.thumbnailWidth, thumbnailHeight: this.thumbnailHeight, maxFiles: this.maxFiles, // resize: not available acceptedFiles: this.acceptedFiles, autoProcessQueue: this.autoProcessQueue, forceFallback: this.forceFallback, previewTemplate: this.previewTemplate, // Dropzone translations dictDefaultMessage: this.dictDefaultMessage, dictFallbackMessage: this.dictFallbackMessage, dictFallbackText: this.dictFallbackText, dictInvalidFileType: this.dictInvalidFileType, dictFileTooBig: this.dictFileTooBig, dictResponseError: this.dictResponseError, dictCancelUpload: this.dictCancelUpload, dictCancelUploadConfirmation: this.dictCancelUploadConfirmation, dictRemoveFile: this.dictRemoveFile, dictMaxFilesExceeded: this.dictMaxFilesExceeded, // Fix flickering dragging over child elements: https://github.com/enyo/dropzone/issues/438 dragenter: Ember.$.noop, dragleave: Ember.$.noop, init: function () { onDragEnterLeaveHandler(this); } }; for (let option in dropzoneConfig) { let data = dropzoneConfig[option]; if (data !== null) { dropzoneOptions[option] = data; } else if (option === 'thumbnailHeight' || option === 'thumbnailWidth') { dropzoneOptions[option] = data; } } this.set('dropzoneOptions', dropzoneOptions); }, createDropzone(element) { this.set('myDropzone', new Dropzone(element, this.dropzoneOptions)); }, insertDropzone: Ember.on('didInsertElement', function() { let _this = this; this.getDropzoneOptions(); Dropzone.autoDiscover = false; this.createDropzone(this.element); if (this.files && this.files.length > 0) { this.files.map(function(file) { let dropfile = { name: file.get('name'), type: file.get('type'), size: file.get('size'), status: Dropzone.ADDED, }; let thumbnail = file.get('thumbnail'); if (typeof (thumbnail) === 'string') { dropfile.thumbnail = thumbnail; } _this.myDropzone.emit('addedfile', dropfile); if (typeof (thumbnail) === 'string') { _this.myDropzone.emit('thumbnail', dropfile, thumbnail); } _this.myDropzone.emit('complete', dropfile); _this.myDropzone.files.push(file); }); } this.setEvents(); return this.myDropzone; }), });
JavaScript
0.000001
@@ -3219,25 +3219,17 @@ er = 0;%0A - %0A + @@ -3441,21 +3441,9 @@ --;%0A - %0A + @@ -3577,16 +3577,21 @@ %7D) +.call (dropzon @@ -3610,22 +3610,16 @@ ement);%0A - %0A d @@ -3726,20 +3726,16 @@ %0A %7D;%0A - %0A let @@ -5144,22 +5144,16 @@ ceeded,%0A - %0A /
7c8fd696ef514a493b4b95aa1abc0635dd314c5a
The tomorrow parameter should be optional
src/modules/guildwars2/commands/Daily.js
src/modules/guildwars2/commands/Daily.js
'use strict'; const Discord = require('discord.js'); const moment = require('moment-timezone'); const DiscordReplyMessage = require('../../../../bot/modules/DiscordReplyMessage'); const ApiBase = require('./ApiBase'); const dailyThumbnail = 'https://render.guildwars2.com/file/483E3939D1A7010BDEA2970FB27703CAAD5FBB0F/42684.png'; class CommandDaily extends ApiBase { constructor(bot) { super(bot, 'daily', ['daily :tomorrow']); } async onApiCommand(message, gw2Api, parameters) { const bot = this.getBot(); const l = bot.getLocalizer(); const nextReset = moment().utc().hour(0).minute(0).seconds(0); if (nextReset.isBefore(moment())) { nextReset.add(1, 'd'); } const timeRemaining = moment.duration(nextReset.unix() - moment().unix(), 's'); const embed = new Discord.RichEmbed() .setTitle(l.t('module.guildwars2:daily.response-title')) .setDescription(l.t('module.guildwars2:daily.response-description', { timeleft: timeRemaining.humanize() })) .setThumbnail(dailyThumbnail); let daily; if (parameters.tomorrow === 'tomorrow') { daily = await gw2Api.achievements().dailyTomorrow().get(); } else { daily = await gw2Api.achievements().daily().get(); } const filterLvl80 = d => d.level.max === 80; let allIds = []; for (const category of Object.keys(daily)) { allIds = allIds.concat(daily[category].filter(filterLvl80).map(d => d.id)); } const achievements = gw2Api.byId(await gw2Api.achievements().many(allIds)); for (const category of Object.keys(daily)) { const categoryOutput = this._formatCategory(category, daily, achievements); if (categoryOutput) { embed.addField(categoryOutput.title, categoryOutput.description); } } return new DiscordReplyMessage('', { embed }); } _filterLevel80(dailyCategory) { return dailyCategory.filter(d => d.level.max === 80); } _formatCategory(categoryId, daily, achievements) { const l = this.getBot().getLocalizer(); const title = l.t([`module.guildwars2:daily.category-${categoryId}`, 'module.guildwars2:daily.category-unknown'], { category: categoryId }); const result = [ ...new Set(this._filterLevel80(daily[categoryId]) .sort((a, b)=> achievements.has(a.id) && achievements.has(b.id) ? achievements.get(a.id).name.localeCompare(achievements.get(b.id).name) : -1) .map(a => this._formatAchievement(categoryId, a, achievements))).values() ]; if (result.length > 0) { return { title, description: result.join('\n') }; } return undefined; } _formatAchievement(categoryId, dailyAchievement, achievements) { const l = this.getBot().getLocalizer(); const longName = achievements.has(dailyAchievement.id) ? achievements.get(dailyAchievement.id).name : l.t('module.guildwars2:daily.achievement-unknown', { id: dailyAchievement.id }); const regex = new RegExp(l.t([`module.guildwars2:daily.${categoryId}-regex`, 'module.guildwars2:daily.daily-regex']), 'i'); let name = longName.match(regex); if (name) { name = name.slice(1).find(n => n !== undefined); } else { name = longName; } const access = dailyAchievement.required_access.map(a => l.t([`module.guildwars2:daily.access-${a}`, 'module.guildwars2:daily.access-unknown'], { access: a })).join(', '); return l.t('module.guildwars2:daily.response-achievement', { name, access }); } } module.exports = CommandDaily;
JavaScript
0.999698
@@ -435,16 +435,17 @@ tomorrow +? '%5D);%0A
cd152cca14f313d4148427e996d1d39ea9e5d4f7
Use a for loop instead of goog.array.forEach
src/ol/format/wmsgetfeatureinfoformat.js
src/ol/format/wmsgetfeatureinfoformat.js
goog.provide('ol.format.WMSGetFeatureInfo'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.dom.NodeType'); goog.require('goog.object'); goog.require('goog.string'); goog.require('ol.format.GML2'); goog.require('ol.format.XMLFeature'); goog.require('ol.xml'); /** * @classdesc * Format for reading WMSGetFeatureInfo format. It uses * {@link ol.format.GML2} to read features. * * @constructor * @extends {ol.format.XMLFeature} * @api */ ol.format.WMSGetFeatureInfo = function() { /** * @private * @type {string} */ this.featureNS_ = 'http://mapserver.gis.umn.edu/mapserver'; /** * @private * @type {ol.format.GML2} */ this.gmlFormat_ = new ol.format.GML2(); goog.base(this); }; goog.inherits(ol.format.WMSGetFeatureInfo, ol.format.XMLFeature); /** * @const * @type {string} * @private */ ol.format.WMSGetFeatureInfo.featureIdentifier_ = '_feature'; /** * @const * @type {string} * @private */ ol.format.WMSGetFeatureInfo.layerIdentifier_ = '_layer'; /** * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @return {Array.<ol.Feature>} Features. * @private */ ol.format.WMSGetFeatureInfo.prototype.readFeatures_ = function(node, objectStack) { node.namespaceURI = this.featureNS_; goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT, 'node.nodeType should be ELEMENT'); var localName = ol.xml.getLocalName(node); /** @type {Array.<ol.Feature>} */ var features = []; if (node.childNodes.length === 0) { return features; } if (localName == 'msGMLOutput') { goog.array.forEach(node.childNodes, function(layer) { if (layer.nodeType !== goog.dom.NodeType.ELEMENT) { return; } var context = objectStack[0]; goog.asserts.assert(goog.isObject(context), 'context should be an Object'); goog.asserts.assert(layer.localName.indexOf( ol.format.WMSGetFeatureInfo.layerIdentifier_) >= 0, 'localName of layer node should match layerIdentifier'); var featureType = goog.string.remove(layer.localName, ol.format.WMSGetFeatureInfo.layerIdentifier_) + ol.format.WMSGetFeatureInfo.featureIdentifier_; context['featureType'] = featureType; context['featureNS'] = this.featureNS_; var parsers = {}; parsers[featureType] = ol.xml.makeArrayPusher( this.gmlFormat_.readFeatureElement, this.gmlFormat_); var parsersNS = ol.xml.makeStructureNS( [context['featureNS'], null], parsers); layer.namespaceURI = this.featureNS_; var layerFeatures = ol.xml.pushParseAndPop( [], parsersNS, layer, objectStack, this.gmlFormat_); if (layerFeatures) { goog.array.extend(features, layerFeatures); } }, this); } if (localName == 'FeatureCollection') { var gmlFeatures = ol.xml.pushParseAndPop([], this.gmlFormat_.FEATURE_COLLECTION_PARSERS, node, [{}], this.gmlFormat_); if (gmlFeatures) { features = gmlFeatures; } } return features; }; /** * Read all features from a WMSGetFeatureInfo response. * * @function * @param {Document|Node|Object|string} source Source. * @param {olx.format.ReadOptions=} opt_options Options. * @return {Array.<ol.Feature>} Features. * @api stable */ ol.format.WMSGetFeatureInfo.prototype.readFeatures; /** * @inheritDoc */ ol.format.WMSGetFeatureInfo.prototype.readFeaturesFromNode = function(node, opt_options) { var options = { 'featureType': this.featureType, 'featureNS': this.featureNS }; if (opt_options) { goog.object.extend(options, this.getReadOptions(node, opt_options)); } return this.readFeatures_(node, [options]); };
JavaScript
0.999984
@@ -1613,61 +1613,105 @@ -goog.array.forEach(node.childNodes, function(layer) %7B +for (var i = 0, ii = node.childNodes.length; i %3C ii; i++) %7B%0A var layer = node.childNodes%5Bi%5D; %0A @@ -1773,22 +1773,24 @@ -return +continue ;%0A @@ -2859,16 +2859,8 @@ %7D -, this); %0A %7D
7054f4aa8620e658a6321e30a59b9165229a974c
Comment out tests depending on bug 935990
lib/gcli/test/testHelp.js
lib/gcli/test/testHelp.js
/* * Copyright 2012, Mozilla Foundation and contributors * * 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'; var assert = require('../testharness/assert'); var helpers = require('./helpers'); var mockCommands = require('./mockCommands'); var canon = require('../canon'); exports.setup = function(options) { mockCommands.setup(); }; exports.shutdown = function(options) { mockCommands.shutdown(); }; exports.testHelpStatus = function(options) { return helpers.audit(options, [ { skipRemainingIf: function commandHelpMissing() { return canon.getCommand('help') == null; }, setup: 'help', check: { typed: 'help', hints: ' [search]', markup: 'VVVV', status: 'VALID' } }, { setup: 'help ', check: { typed: 'help ', hints: '[search]', markup: 'VVVVV', status: 'VALID' } }, // From bug 779816 { setup: 'help<TAB>', check: { typed: 'help ', hints: '[search]', markup: 'VVVVV', status: 'VALID' } }, { setup: 'help foo', check: { typed: 'help foo', markup: 'VVVVVVVV', status: 'VALID', hints: '' } }, { setup: 'help foo bar', check: { typed: 'help foo bar', markup: 'VVVVVVVVVVVV', status: 'VALID', hints: '' } }, ]); }; exports.testHelpExec = function(options) { return helpers.audit(options, [ { skipRemainingIf: function commandHelpMissing() { return options.isNoDom || canon.getCommand('help') == null; }, setup: 'help', check: { args: { search: { value: undefined } } }, exec: { output: options.isFirefox ? [ /Available Commands/, /Get help/ ] : [ /GCLI is an experiment/, /Source \(Apache-2.0\)/, /Get help/ ] } }, { setup: 'help nomatch', check: { args: { search: { value: 'nomatch' } } }, exec: { output: /No commands starting with 'nomatch'$/ } }, { setup: 'help help', check: { args: { search: { value: 'help' } } }, exec: { output: [ /Synopsis:/, /Provide help either/, /\(string, optional\)/ ] } }, { setup: 'help a b', check: { args: { search: { value: 'a b' } } }, exec: { output: /No commands starting with 'a b'$/ } }, { setup: 'help hel', check: { args: { search: { value: 'hel' } } }, exec: { output: [ /Commands starting with 'hel':/, /Get help on the available commands/ ] } }, { setup: 'help tscook', check: { input: 'help tscook', hints: '', markup: 'VVVVVVVVVVV', status: 'VALID', }, exec: { output: [ /tscook\s*<key> <value> \[--path \.\.\.\] \[--domain \.\.\.\] \[--secure\]/, /[--secure]:? \(boolean, optional, default=false\)/, /tscookSecureDesc/ ], type: 'commandData', error: false } }, { setup: 'help tsn', check: { input: 'help tsn', hints: '', markup: 'VVVVVVVV', status: 'VALID', }, exec: { output: [ /tsn deep down/, /tsn extend/ ], type: 'commandData', error: false }, post: function(output, data) { if (data.indexOf('hidden') !== -1) { assert.ok(false, 'hidden is hidden'); } } }, { setup: 'help tsn hidden', check: { input: 'help tsn hidden', hints: '', markup: 'VVVVVVVVVVVVVVV', status: 'VALID', }, exec: { output: /tsn hidden/, type: 'commandData', error: false } }, { setup: 'help tsg', check: { status: 'VALID', }, exec: { output: [ /Options:/, /First:/, /Second:/, ], type: 'commandData', error: false } } ]); };
JavaScript
0
@@ -2871,17 +2871,69 @@ either/ -, +%0A // Commented out until bug 935990 is fixed %0A @@ -2934,16 +2934,19 @@ + // /%5C(stri @@ -3722,16 +3722,72 @@ + // Commented out until bug 935990 is fixed%0A // /%5B--sec
c136116a1df731dd029e264884b7722bad2963f6
fix pull api test
lib/github/PullApiTest.js
lib/github/PullApiTest.js
/** * Copyright 2010 Ajax.org B.V. * * This product includes software developed by * Ajax.org B.V. (http://www.ajax.org/). * * Author: Ryan Funduk <[email protected]> */ var assert = require("assert"); var sys = require("sys"); var GitHubApi = require("../github").GitHubApi; var username = 'ornicar'; var repo = 'php-github-api'; var test = module.exports = { setUp: function() { this.github = new GitHubApi(true); this.pullApi = this.github.getPullApi(); }, "test: list pull requests" : function(finished) { test.pullApi.getList(username, repo, function(err, pulls) { assert.ok(pulls.length); finished(); }); }, "test: show pull request" : function(finished) { test.pullApi.show(username, repo, 1, function(err, pull) { assert.ok(pull.number); finished(); }); } }; !module.parent && require("asyncjs").test.testcase(module.exports).exec();
JavaScript
0.000001
@@ -301,17 +301,17 @@ e = -'ornicar' +%22ajaxorg%22 ;%0Ava @@ -327,24 +327,13 @@ = -'php-github-api' +%22ace%22 ;%0A%0Av @@ -785,16 +785,18 @@ repo, 1 +57 , functi @@ -826,26 +826,29 @@ assert. -ok +equal (pull.number @@ -847,16 +847,21 @@ l.number +, 157 );%0A
cdf32e114f461b90b72f3f397751a8d916d852e4
fix none JSON response issue
lib/iso-execute-client.js
lib/iso-execute-client.js
var isoconfig = require('./iso-config'); var isoreq = require('./iso-request-core'); module.exports = { execute: function (name, cfg) { if (!name) { return Promise.reject(new Error('iso-execute-client without name!')); } return isoreq(Object.assign({}, { method: 'PUT', body: JSON.stringify(cfg), url: isoconfig.getBaseURL() + name, json: true, headers: { 'content-type': 'application/json' } })).then(function (R) { return R.body; }); } };
JavaScript
0.000007
@@ -407,32 +407,8 @@ me,%0A - json: true,%0A @@ -539,22 +539,127 @@ -return R.body; +try %7B%0A return JSON.parse(R.body);%0A %7D catch (E) %7B%0A return R.body;%0A %7D %0A
3b4fd806820d39bf163f20a22ddd49223031eb60
fix async part 2
discordJs/test.js
discordJs/test.js
/* A ping pong bot, whenever you send "ping", it replies "pong". */ // Import the discord.js module const DISCORD = require("discord.js"); const EXECFILE = require("child_process").execFile; const FS = require('fs'); const SLTS = require('./slots'); const EVENTS = require('./events'); const UTIL = require('./util'); // Create an instance of a Discord CLIENT const CLIENT = new DISCORD.Client(); // The TOKEN of your bot - https://discordapp.com/developers/applications/me const TOKEN = 'MzMxNzE3MTI1ODMwMDgyNTYw.DDznVA.CwWs-HqWVwuez-FeReIY9Y8aMYQ'; // The ready event is vital, it means that your bot will only start reacting to information // from Discord _after_ ready is emitted CLIENT.on('ready', () => { console.log('I am ready!'); }); // Create an event listener for messages CLIENT.on('message', message => { function slots(amount) { var path = '/tmp/' + message.author.id + '.json'; if (FS.existsSync(path) == false) { UTIL.addCoins(message); } var readFile = FS.readFile(path,'utf8', function(err){ if (err) { return console.log(err); } }); var obj = JSON.parse(readFile); if (SLTS.checkrequirements(obj, amount)) { console.log(amount[2]); obj.coins = Number(obj.coins) + sendSlotResults(SLTS.slotsLogic(SLTS.genSlotsNumbers(), Number(amount[2]), amount[1].toLowerCase())); FS.writeFile(path, JSON.stringify(obj), function(err){ if (err) { return console.log(err); } }); } else { console.log(obj.coins); message.channel.send("You don't have enough coins to play slots"); } } // Handles the display of the slots results function sendSlotResults(all) { message.channel.send(' S L O T S '); all.slotRows = SLTS.changeNrToEmo(all.slotRows); message.channel.send(all.slotRows[0] + ' ' + all.slotRows[1] + ' ' + all.slotRows[2] + '\n' + all.slotRows[3] + ' ' + all.slotRows[4] + ' ' + all.slotRows[5] + '\n' + all.slotRows[6] + ' ' + all.slotRows[7] + ' ' + all.slotRows[8]); if (all.coins > 0) { message.channel.send("You Won " + all.coins + "!\nYour coin multiplicator is " + all.mltipler); } else { message.channel.send("You Lost " + all.coins + '!'); } return all.coins; } function wage() { var ts = UTIL.getTimestamp(); var path = '/tmp/' + message.author.id + '.json'; var readFile; var obj; if (FS.existsSync(path)) { readFile = FS.readFile(path,'utf8', function(err){ if (err) { return console.log(err); } }); obj = JSON.parse(readFile,'utf8', function(err){ if (err) { return console.log(err); } }); if (ts > Number(obj.timestamp) + 54000) { UTIL.addCoins(message); UTIL.writeObjProperty(message,'timestamp', ts); } else { console.log(obj.timestamp); message.channel.send('Sorry!\nIt looks like you already got your daily reward.\nPlease try again in ' + UTIL.getHours(Number(obj.timestamp) + 54000 - ts)); } } else { UTIL.addCoins(message); } } function isSlots(strText) { strText = strText.toLowerCase(); if (strText.includes("mako slots") || strText.includes("mako multislots")) { return true; } } // If the message is "slots" if (isSlots(message.content) && message.author.id != 331717125830082560) { if (UTIL.readObjProperty(message, 'slotTimer') == null) { UTIL.writeObjProperty(message, 'slotTimer', UTIL.getTimestamp()); } else { if (Number(UTIL.readObjProperty(message, 'slotTimer')) + 4 < UTIL.getTimestamp()) { UTIL.writeObjProperty(message, 'slotTimer', UTIL.getTimestamp()); var str = message.content.toLowerCase().split(" ", 3); if (!isNaN(Number(str[2]))) { EVENTS.getRandomEvent(message); slots(str); } else { message.channel.send(message.author + ' you forgot to specify an ammount of coins\nThe command should look like this:\n<slots> <Coins>'); } } else { message.channel.send('You need to cool down a bit'); } } } if (message.content === 'mako wage') { // Send to the same channel EVENTS.getRandomEvent(message); wage(); } if (message.content === 'mako id') { // Send to the same channel message.channel.send(message.author.id); } if (message.content === 'patch') { // Send to the same channel EXECFILE("/root/makobot/MakoBot/discordJs/syncGitRepo.sh"); message.channel.send("patched git"); message.channel.send("restart now"); } if (message.content === 'mako credits') { UTIL.getCredits(message); } }); // Log our bot in CLIENT.login(TOKEN);
JavaScript
0.000003
@@ -2633,111 +2633,8 @@ File -,'utf8', function(err)%7B%0A if (err) %7B%0A return console.log(err);%0A %7D%0A %7D );%0A
4649caa0744d16f62b868fd912fb3c9f11c64cea
Fix error loading timeline
js/controllers/timeline-controller.js
js/controllers/timeline-controller.js
(function(global) { 'use strict'; var app = global.app || {}; var m = global.m; var util = global.util; var translateX = util.translateX; var TimelineController = function(option) { this.url = m.prop(option.url); this.state = m.prop(TimelineController.STATE_INITIALIZED); this.title = m.prop(option.title); this.type = m.prop(option.type); this.data = m.prop(option.data); this.daysAgo = m.prop(option.daysAgo); this.daysAfter = m.prop(option.daysAfter); this.pixelsPerDay = m.prop(option.pixelsPerDay); this.selectedIndex = selectedIndexProp(); this.titleElement = m.prop(null); }; TimelineController.prototype.fetch = function() { var url = this.url(); this.state(TimelineController.STATE_LOADING); return m.request({ method: 'GET', url: url, extract: requestExtract, }).then(requestSuccessCallback.bind(this), requestErrorCallback.bind(this)); }; TimelineController.prototype.scrollLeft = function(value) { var titleElement = this.titleElement(); if (titleElement) translateX(titleElement, value); }; TimelineController.prototype.dispatchEvent = function(event) { switch (event.type) { case 'init': this.titleElement(event.titleElement); break; case 'select': this.selectedIndex(event.selectedIndex); break; default: break; } }; var selectedIndexProp = function() { var selectedIndex = m.prop(null); return function(value) { if (typeof value === 'undefined') { value = selectedIndex(); var type = this.type(); if (value === null) return (type === TimelineController.TYPE_GANTT_CHART) ? [-1, -1] : -1; else return value; } selectedIndex(value); }; }; var requestExtract = function(xhr) { return xhr.status > 200 ? JSON.stringify(xhr.responseText) : xhr.responseText; }; var requestSuccessCallback = function(result) { var title = result.title; var type = result.type; var data = result.data; if (type === TimelineController.TYPE_GANTT_CHART) { data = data.map(function(item) { item.data = parseDateProperty(item.data); item.deadline = new Date(item.deadline); return item; }); } else { data = parseDateProperty(data); } this.title(title); this.type(type); this.data(data); this.state(TimelineController.STATE_LOAD_COMPLETE); return this; }; var requestErrorCallback = function() { this.state(TimelineController.STATE_LOAD_ERROR); return this; }; var parseDateProperty = function(array) { return array.map(function(item) { item.date = new Date(item.date); return item; }); }; TimelineController.STATE_INITIALIZED = 'initialized'; TimelineController.STATE_LOADING = 'loading'; TimelineController.STATE_LOAD_COMPLETE = 'load-complete'; TimelineController.STATE_LOAD_ERROR = 'load-error'; TimelineController.TYPE_LINE_CHART = 'line-chart'; TimelineController.TYPE_BAR_CHART = 'bar-chart'; TimelineController.TYPE_SCHEDULE = 'schedule'; TimelineController.TYPE_GANTT_CHART = 'gantt-chart'; app.TimelineController = TimelineController; global.app = app; })(this);
JavaScript
0.000002
@@ -831,32 +831,151 @@ -extract: requestExtract, +deserialize: function(value) %7B%0A try %7B%0A return JSON.parse(value);%0A %7D catch (e) %7B%0A return null;%0A %7D%0A %7D %0A @@ -1939,15 +1939,23 @@ uest -Extract +SuccessCallback = f @@ -1966,19 +1966,22 @@ ion( -xhr +result ) %7B%0A retu @@ -1980,106 +1980,41 @@ -return xhr.status %3E 200 ? JSON.stringify(xhr.responseText) : xhr.responseText;%0A %7D;%0A%0A var +if (!result)%0A return request Succ @@ -2005,39 +2005,37 @@ turn request -Success +Error Callback = function( @@ -2022,37 +2022,29 @@ Callback - = function(result) %7B +.call(this);%0A %0A var
cc3425b481609ac7fc754fdbd46b8d3b7bb301e7
Update bootstrap-datepicker.sv.js
js/locales/bootstrap-datepicker.sv.js
js/locales/bootstrap-datepicker.sv.js
/** * Swedish translation for bootstrap-datepicker * Patrik Ragnarsson <[email protected]> */ ;(function($){ $.fn.datepicker.dates['sv'] = { days: ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag"], daysShort: ["Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör", "Sön"], daysMin: ["Sö", "Må", "Ti", "On", "To", "Fr", "Lö", "Sö"], months: ["Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"], today: "Idag", format: "yyyy-mm-dd", weekStart: 1 }; }(jQuery));
JavaScript
0
@@ -653,16 +653,34 @@ Start: 1 +,%0A%09%09clear: %22Rensa%22 %0A%09%7D;%0A%7D(j
0108ed5f93c692d2c046a3319c76898c4c1f6835
Fix Ukrainian lang code
js/locales/bootstrap-datepicker.ua.js
js/locales/bootstrap-datepicker.ua.js
/** * Ukrainian translation for bootstrap-datepicker * Igor Polynets */ ;(function($){ $.fn.datepicker.dates['ru'] = { days: ["Неділя", "Понеділок", "Вівторок", "Середа", "Четверг", "П'ятница", "Субота", "Неділя"], daysShort: ["Нед", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Суб", "Нед"], daysMin: ["Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Нд"], months: ["Cічень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень"], monthsShort: ["Січ", "Лют", "Бер", "Квт", "Трв", "Чер", "Лип", "Сер", "Вер", "Жов", "Лис", "Грд"], today: "Сьогодні", weekStart: 1 }; }(jQuery));
JavaScript
0.99999
@@ -111,10 +111,10 @@ es%5B' -r u +a '%5D =
5114a47f6e6116647f4abfb23a588b45607543ed
clean up lost "this."
app/controllers/home.js
app/controllers/home.js
module.controller("Home", ['$scope'], function($scope) { }); module.controller("Reminder", ['$scope'], function($scope) { }); module.service('ReminderService', function() { this.reminders = [ { id: 1, heading: "Add Physicians", text: "Need to add the Physicians to the app", due: "10/10/2017", owner: 1 }, { id: 2, heading: "Add Patients", text: "Need to add the Patients to the app", due: "10/1/2017", owner: 2 } ] this.reminders = function() { return this.reminders } this. }); module.controller("ExpandItem", ['$scope'], function($scope) { }); module.controller("Info", ['$scope', 'WeatherService'], function($scope) { $scope.weather = WeatherService.weather() }); module.service('WeatherService', function() { this.data = "73 degrees and sunny" this.weather = function() { return this.data; } });
JavaScript
0.000004
@@ -579,18 +579,8 @@ %7D%0A - this.%0A %7D);%0A
3f23896e539be91be21bd8ac6b7031dbc2e4da85
Replace urls with S3 ones for the production on the donations page.
app/js/pages/donatii.js
app/js/pages/donatii.js
'use strict'; var Backbone = require('../shims/backbone'); var View = Backbone.View; var templates = require('../lib/templates'); var $ = require('../shims/jquery'); var donations = require('../lib/donations.json'); module.exports = View.extend({ pageTitle: 'Monica Macovei Presedinte | Susținere financiară', template: templates.pages.donatii, events: { 'click .paypal .btn': 'loadBtn', 'click #doneaza': 'doneaza' }, render: function () { var self = this; self.$el.html(self.template({ donations: donations })); self.$('.progress .progress-bar').attr('data-transitiongoal', self.$('.progress .progress-bar').attr('data-transitiongoal-backup')); self.$('.progress .progress-bar').progressbar({ display_text: 'center', use_percentage: false, amount_format: function (p) { self.amount = p + 5; var value = self.amount + ' / 300000 ' + donations.currency; return value; }, update: function(raised) { raised = self.amount; if (raised >= 20000) { self.$('.mile').removeClass('passed'); self.$('.mile-1').addClass('passed'); self.$('.value').removeClass('passed'); self.$('.value-1').addClass('passed'); } if (raised >= 50000) { self.$('.mile').removeClass('passed'); self.$('.mile-2').addClass('passed'); self.$('.value').removeClass('passed'); self.$('.value-2').addClass('passed'); } if(raised >= 100000) { self.$('.mile').removeClass('passed'); self.$('.mile-3').addClass('passed'); self.$('.value').removeClass('passed'); self.$('.value-3').addClass('passed'); } if (raised >= 200000) { self.$('.mile').removeClass('passed'); self.$('.mile-4').addClass('passed'); self.$('.value').removeClass('passed'); self.$('.value-4').addClass('passed'); } if (raised === 300000) { self.$('.mile').removeClass('passed'); self.$('.mile-5').addClass('passed'); self.$('.value').removeClass('passed'); self.$('.value-5').addClass('passed'); } } }); self.$('.progressbar-back-text').detach(); self.$('#raised').html(self.$('.progressbar-front-text')); return this; }, loadBtn: function (e) { var t = $(e.target); t.addClass('active'); t.html('<i class="fa fa-fw fa-spin fa-spinner"></i>'); }, doneaza: function () { $("body").animate({ scrollTop: this.$('#content').offset().top - 50 }, 200); } });
JavaScript
0
@@ -209,16 +209,88 @@ .json'); +%0Avar urlrepl = require('../lib/url-replace');%0Avar _ = require('lodash'); %0A%0Amodule @@ -548,16 +548,145 @@ = this;%0A + _.forEach(donations, function (entry) %7B%0A if (entry.image) %7B%0A entry.image = urlrepl(entry.image);%0A %7D%0A %7D);%0A self
313f169ff421fd7644a53686275c788e58a16a3f
Update ETH minConf
app/lib/wallet/index.js
app/lib/wallet/index.js
'use strict'; var work = require('webworkify') var IeWorker = require('./ie-worker.js'); var worker = window.isIE ? new IeWorker() : work(require('./worker.js')) var auth = require('./auth') var utils = require('./utils') var db = require('./db') var emitter = require('cs-emitter') var crypto = require('crypto') var AES = require('cs-aes') var denominations = require('cs-denomination') var BtcLtcWallet = require('cs-wallet') var validateSend = require('./validator') var rng = require('secure-random').randomBuffer var bitcoin = require('bitcoinjs-lib') var xhr = require('cs-xhr') var cache = require('memory-cache') var EthereumWallet = require('cs-ethereum-wallet'); var wallet = null var seed = null var mnemonic = null var id = null var availableTouchId = false var Wallet = { bitcoin: BtcLtcWallet, litecoin: BtcLtcWallet, testnet: BtcLtcWallet, ethereum: EthereumWallet } var uriRoot = window.location.origin if(window.buildType === 'phonegap') { uriRoot = process.env.PHONEGAP_URL } function createWallet(passphrase, network, callback) { var message = passphrase ? 'Decoding seed phrase' : 'Generating' emitter.emit('wallet-opening', message) var data = {passphrase: passphrase} if(!passphrase){ data.entropy = rng(128 / 8).toString('hex') } worker.onmessage = function(e) { assignSeedAndId(e.data.seed) mnemonic = e.data.mnemonic auth.exist(id, function(err, userExists){ if(err) return callback(err); callback(null, {userExists: userExists, mnemonic: mnemonic}) }) } worker.onerror = function(e) { return callback({message: e.message.replace("Uncaught Error: ", '')}) } worker.postMessage(data) } function callbackError(err, callbacks) { callbacks.forEach(function (fn) { if (fn != null) fn(err) }) } function setPin(pin, network, done, txSyncDone) { var callbacks = [done, txSyncDone] auth.register(id, pin, function(err, token){ if(err) return callbackError(err.error, callbacks); emitter.emit('wallet-auth', {token: token, pin: pin}) savePin(pin) var encrypted = AES.encrypt(seed, token) db.saveEncrypedSeed(id, encrypted, function(err){ if(err) return callbackError(err.error, callbacks); emitter.emit('wallet-opening', 'Synchronizing Wallet') initWallet(network, done, txSyncDone) }) }) } function disablePin(pin, callback) { auth.disablePin(id, pin, callback) } function openWalletWithPin(pin, network, done, txSyncDone) { var callbacks = [done, txSyncDone] db.getCredentials(function(err, credentials){ if(err) return callbackError(err, callbacks); var id = credentials.id var encryptedSeed = credentials.seed auth.login(id, pin, function(err, token){ if(err){ if(err.error === 'user_deleted') { return db.deleteCredentials(credentials, function(){ callbackError(err.error, callbacks); }) } return callbackError(err.error, callbacks); } savePin(pin) assignSeedAndId(AES.decrypt(encryptedSeed, token)) emitter.emit('wallet-auth', {token: token, pin: pin}) emitter.emit('wallet-opening', 'Synchronizing Wallet') initWallet(network, done, txSyncDone) }) }) } function savePin(pin){ if(availableTouchId) window.localStorage.setItem('_pin_cs', AES.encrypt(pin, 'pinCoinSpace')) } function setAvailableTouchId(){ availableTouchId = true } function getPin(){ var pin = window.localStorage.getItem('_pin_cs') return pin ? AES.decrypt(pin, 'pinCoinSpace') : null } function resetPin(){ window.localStorage.removeItem('_pin_cs') } function assignSeedAndId(s) { seed = s id = crypto.createHash('sha256').update(seed).digest('hex') emitter.emit('wallet-init', {seed: seed, id: id}) } function initWallet(networkName, done, txDone) { var options = { networkName: networkName, done: done, txDone: function(err) { if(err) return txDone(err) var txObjs = wallet.getTransactionHistory() txDone(null, txObjs.map(function(tx) { return parseHistoryTx(tx) })) } } if (networkName === 'ethereum') { options.seed = seed; } else if (networkName === 'bitcoin' || networkName === 'litecoin' || networkName === 'testnet') { var accounts = getDerivedAccounts(networkName) options.externalAccount = accounts.externalAccount options.internalAccount = accounts.internalAccount } wallet = new Wallet[networkName](options) wallet.denomination = denominations[networkName].default } function getDerivedAccounts(networkName) { if (wallet && wallet.externalAccount && wallet.internalAccount) { return { externalAccount: wallet.externalAccount, internalAccount: wallet.internalAccount } } var network = bitcoin.networks[networkName] var accountZero = bitcoin.HDNode.fromSeedHex(seed, network).deriveHardened(0) return { externalAccount: accountZero.derive(0), internalAccount: accountZero.derive(1) } } function parseHistoryTx(tx) { var networkName = wallet.networkName if (networkName === 'ethereum') { return utils.parseEthereumTx(tx) } else if (networkName === 'bitcoin' || networkName === 'litecoin' || networkName === 'testnet') { return utils.parseBtcLtcTx(tx) } } function sync(done, txDone) { initWallet(wallet.networkName, done, txDone) } function getWallet(){ return wallet } function walletExists(callback) { db.getCredentials(function(err, doc){ if(doc) return callback(true); return callback(false) }) } function reset(callback){ db.getCredentials(function(err, credentials){ if(err) return callback(err); db.deleteCredentials(credentials, function(deleteError){ callback(deleteError) }) }) } function getDynamicFees(callback) { var fees = cache.get('bitcoinFees') if (fees) { return callback({hourFeePerKb: fees.hour * 1000, fastestFeePerKb: fees.fastest * 1000}) } xhr({ uri: uriRoot + '/fees', method: 'GET' }, function(err, resp, body){ if(resp.statusCode !== 200) { console.error(body) return callback({}) } var data = JSON.parse(body) cache.put('bitcoinFees', {hour: data.hour, fastest: data.fastest}, 10 * 60 * 1000) callback({hourFeePerKb: data.hour * 1000, fastestFeePerKb: data.fastest * 1000}) }) } module.exports = { openWalletWithPin: openWalletWithPin, createWallet: createWallet, setPin: setPin, disablePin: disablePin, getWallet: getWallet, walletExists: walletExists, reset: reset, sync: sync, validateSend: validateSend, parseHistoryTx: parseHistoryTx, getPin: getPin, resetPin: resetPin, setAvailableTouchId: setAvailableTouchId, getDynamicFees: getDynamicFees }
JavaScript
0
@@ -4173,16 +4173,42 @@ = seed;%0A + options.minConf = 12;%0A %7D else
08e408dc82e109bcb53c42284dac3f3544df4566
set correct price state
app/reducers/players.js
app/reducers/players.js
import _ from 'lodash'; import { SAVE_SEARCH_RESULTS, ADD_PLAYER, REMOVE_PLAYER, SET_PRICE } from '../actions/players'; export function players(state = {}, action) { switch (action.type) { case SAVE_SEARCH_RESULTS: { const nextState = _.merge({}, state); _.set(nextState, 'search', action.results); return nextState; } case ADD_PLAYER: { const nextState = _.merge({}, state); _.set(nextState, `list.${action.player.id}`, action.player); return nextState; } case REMOVE_PLAYER: { const nextState = _.merge({}, state); _.unset(nextState, `list.${action.player.id}`); return nextState; } case SET_PRICE: { const nextState = _.merge({}, state); _.set(_.find(nextState.list, { id: action.id }), 'price', action.price); return nextState; } default: return state; } } export { players as default };
JavaScript
0.00045
@@ -741,15 +741,8 @@ set( -_.find( next @@ -750,21 +750,18 @@ tate -. +, %60 list -, %7B id: +.$%7B acti @@ -769,20 +769,16 @@ n.id - %7D), ' +%7D. price -' +%60 , ac
185d967089385d77b999c24829c97837c1533b6e
Improve noLoadingRequests methods handling
app/redux/AppReducer.js
app/redux/AppReducer.js
import {Map, OrderedMap} from 'immutable'; import { translate } from 'app/Translator'; const defaultState = Map({ requests: {}, loading: false, error: '', location: {}, notifications: null, notificounters: Map({ total: 0, feed: 0, reward: 0, send: 0, mention: 0, follow: 0, vote: 0, reply: 0, account_update: 0, message: 0, receive: 0 }) }); export default function reducer(state = defaultState, action) { if (action.type === '@@router/LOCATION_CHANGE') { return state.set('location', {pathname: action.payload.pathname}); } if (action.type === 'STEEM_API_ERROR') { return state.set('error', action.error).set('loading', false); } if (action.type === 'WS_CONNECTION_STATUS') { return state.updateIn(['ws_connection'], value => { if (value && value.status === action.payload.status) return value; return {status: action.payload.status, updated_at: new Date()}; }); } let res = state; if (action.type === 'RPC_REQUEST_STATUS') { const request_id = action.payload.id + ''; // console.log(new Date().getTime(), "RPC_REQUEST_STATUS:", action.payload.method); if (action.payload.event === 'BEGIN') { const noLoadingMethods = [ "get_dynamic_global_properties", "get_api_by_name", "get_followers", "get_following" ]; res = state.mergeDeep({ loading: noLoadingMethods.indexOf(action.payload.method) !== -1 ? false : true, requests: {[request_id]: Date.now()} }); } if (action.payload.event === 'END' || action.payload.event === 'ERROR') { res = res.deleteIn(['requests', request_id]); const loading = res.get('requests').size > 0; res = res.set('loading', loading); } } if (action.type === 'ADD_NOTIFICATION') { const n = { action: translate('dismiss'), dismissAfter: 10000, ...action.payload }; res = res.update('notifications', s => { return s ? s.set(n.key, n) : OrderedMap({[n.key]: n}); }); } if (action.type === 'REMOVE_NOTIFICATION') { res = res.update('notifications', s => s.delete(action.payload.key)); } if (action.type === 'UPDATE_NOTIFICOUNTERS' && action.payload) { const nc = action.payload; if (nc.follow > 0) { nc.total -= nc.follow; nc.follow = 0; } res = res.set('notificounters', Map(nc)); } return res; }
JavaScript
0.000001
@@ -204,16 +204,42 @@ : null,%0A + noLoadingRequests: 0,%0A noti @@ -1207,152 +1207,8 @@ '';%0A - // console.log(new Date().getTime(), %22RPC_REQUEST_STATUS:%22, action.payload.method);%0A if (action.payload.event === 'BEGIN') %7B%0A @@ -1246,29 +1246,25 @@ - -%22 +' get_dynamic_ @@ -1280,17 +1280,17 @@ operties -%22 +' ,%0A @@ -1291,29 +1291,25 @@ - - %22 +' get_api_by_n @@ -1311,17 +1311,17 @@ _by_name -%22 +' ,%0A @@ -1318,37 +1318,33 @@ e',%0A - %22 +' get_followers%22,%0A @@ -1340,17 +1340,17 @@ ollowers -%22 +' ,%0A @@ -1359,13 +1359,9 @@ - -%22 +' get_ @@ -1373,9 +1373,9 @@ wing -%22 +' %0A @@ -1383,14 +1383,143 @@ +%5D;%0A -%5D; + const noLoadMethod = noLoadingMethods.indexOf(action.payload.method) !== -1;%0A if (action.payload.event === 'BEGIN') %7B %0A @@ -1586,56 +1586,14 @@ Load -ing Method -s.indexOf(action.payload.method) !== -1 ? f @@ -1657,16 +1657,108 @@ e.now()%7D +,%0A noLoadingRequests: state.get('noLoadingRequests') + (noLoadMethod ? 1 : 0) %0A @@ -1874,51 +1874,265 @@ -res = res.deleteIn(%5B'requests', request_id%5D +const noLoadCount = state.get('noLoadingRequests') - (noLoadMethod ? 1 : 0);%0A res = res.deleteIn(%5B'requests', request_id%5D);%0A // console.log(%22RPC_REQUEST END:%22, action.payload.method, res.get('requests').size, %22noLoadCount%22, noLoadCount );%0A @@ -2158,16 +2158,17 @@ ading = +( res.get( @@ -2183,16 +2183,31 @@ s').size + - noLoadCount) %3E 0;%0A @@ -2230,30 +2230,105 @@ res. -set('loading', loading +mergeDeep(%7B%0A loading,%0A noLoadingRequests: noLoadCount%0A %7D );%0A