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 |
|---|---|---|---|---|---|---|---|
44bffa075a61bb4e343fda9b1e23ffeb1db87dd8 | add capitalize function | js/data/util/format.js | js/data/util/format.js | /*
* == BSD2 LICENSE ==
* Copyright (c) 2014, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
* == BSD2 LICENSE ==
*/
var d3 = require('../../lib/').d3;
var format = {
MS_IN_24: 86400000,
fixFloatingPoint: function(n) {
return parseFloat(n.toFixed(3));
},
percentage: function(f) {
if (isNaN(f)) {
return '-- %';
}
else {
return parseInt(Math.round(f * 100), 10) + '%';
}
},
millisecondsAsTimeOfDay: function(i) {
var d = new Date(i);
return d3.time.format.utc('%-I:%M %p')(d);
}
};
module.exports = format;
| JavaScript | 0.999907 | @@ -773,16 +773,153 @@
00000,%0A%0A
+ capitalize: function(s) %7B%0A // transform the first letter of string s to uppercase%0A return s%5B0%5D.toUpperCase() + s.slice(1);%0A %7D,%0A%0A
fixFlo
|
bb47cda18b0feaa109aa119a74105d3a1e63f817 | update image position on init | js/jquery.parallaxy.js | js/jquery.parallaxy.js | /* ========================================================================
* [githublink here] [docs are here too!]
* ========================================================================
* Copyright 2013 Ivar Borthen.
*
* 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.
* Only supported by browsers that support CSS3 offset position ( elaborate )
* ======================================================================== */
+function ($) { "use strict";
// Utility
if ( typeof Object.create !== 'function' ) {
Object.create = function( obj ) {
function F() {}
F.prototype = obj;
return new F();
};
}
// init GLOBAL nailPluginCollection, used across all .nail plugins.
if (typeof window.nailPluginCollection !== 'object' && window.ignoreParallaxy !== true){
window.nailPluginCollection = Object.create({
'update' : function(){},
'resize' : function(){}
});
window.nailPluginCollectionResize = function(){
window.nailPluginCollection.resize();
}
$(window).on('resize', window.nailPluginCollectionResize);
}
// PARALLAXY CLASS DEFINITION
// ====================
var Parallaxy = function (element, ignoreupdate) {
this.element = element;
if(this.element.data('parallaxy-image')==true){
this.image = $(element).find('.parallaxy-element').addClass('parallaxy-image').find('img');
this.isdiv = false;
// Autospeed set or disabled?
if(this.element.data('parallaxy-speed')==undefined){
this.fixedSpeed=0.5; // 0 == fastest, 1 == standstill
} else {
this.fixedSpeed=this.element.data('parallaxy-speed');
}
} else {
this.image = $(element).find('.parallaxy-element');
this.isdiv = true;
this.translateX = 0;
if(this.element.data('parallaxy-speed')==undefined){
this.fixedSpeed=1; // 0 == fastest, 1 == standstill
} else {
this.fixedSpeed=this.element.data('parallaxy-speed');
}
}
this.pageFixedHeader = $(this.element.data('parallaxy-page-header'));
var _pageHeaderHeight = 0;
$.each(this.pageFixedHeader, function() {
_pageHeaderHeight += $(this).height();
});
this.pageHeaderHeight = _pageHeaderHeight;
this.resized();
this.scrolled($.fn.parallaxy.Viewport.windowPostionY, $.fn.parallaxy.Viewport.windowHeight);
}
Parallaxy.prototype.resized = function() {
this.elementHeight = this.element.outerHeight();
this.elementWidth = this.element.outerWidth();
var _pageHeaderHeight = 0;
$.each(this.pageFixedHeader, function() {
_pageHeaderHeight += $(this).height();
});
this.pageHeaderHeight = _pageHeaderHeight;
if(!this.isdiv){
this.imageHeight = (this.elementHeight)+(($.fn.parallaxy.Viewport.windowHeight-this.elementHeight)*this.fixedSpeed);
this.image.height(this.imageHeight)
.width('auto');
if(this.elementWidth/this.image.width() > 1){
this.image.width(this.elementWidth)
.height('auto');
this.imageHeight = this.image.outerHeight();
}
this.translateX = -(this.image.outerWidth()-this.element.outerWidth())/2;
}
this.elementY = this.element.offset().top;
}
Parallaxy.prototype.scrolled = function (windowPostionY, windowHeight) {
windowPostionY += this.pageHeaderHeight;
windowHeight -= this.pageHeaderHeight;
// only bother continue if view of parallax in within the viewport of the browser
if(this.elementY+this.elementHeight>windowPostionY && this.elementY<windowHeight+windowPostionY){
// calculate scroll value
var _scroll = -((this.elementY)-windowPostionY)*this.fixedSpeed;
this.image.css('transform', 'translate('+this.translateX+'px,'+_scroll+'px)');
this.element.removeClass("outside-of-bounds");
} else {
this.element.addClass("outside-of-bounds");
}
}
// PARALLAXY PLUGIN DEFINITION
// =====================
$.fn.parallaxy = function () {
$(this).data('parallaxy', 'enabled');
return $.fn.parallaxy.Elements.push(new Parallaxy(this));
}
$.fn.parallaxy.update = function( ){
// Add new parallaxy elements ( i.e. new content added via ajax )
$.fn.parallaxy.Elements = [];
if(window.ignoreParallaxy === true){
return false;
}
$('[data-parallaxy]').each(function() {
$(this).parallaxy();
});
}
$.fn.parallaxy.Constructor = Parallaxy
$.fn.parallaxy.Viewport = {
'windowPostionY' : $(window).scrollTop(),
'windowHeight' : (typeof window.innerHeight != 'undefined') ? window.innerHeight : document.documentElement.clientHeight
};
// EVENT LISTENERS
// ============
$.fn.parallaxy.resize = function(){
// update viewport, fallback on
if (typeof window.innerHeight != 'undefined') {
$.fn.parallaxy.Viewport.windowHeight = window.innerHeight;
} else {
$.fn.parallaxy.Viewport.windowHeight = document.documentElement.clientHeight;
}
// update all parallxy heights data
for(var i=0; i<$.fn.parallaxy.Elements.length; i++){
$.fn.parallaxy.Elements[i].resized();
$.fn.parallaxy.Elements[i].scrolled($.fn.parallaxy.Viewport.windowPostionY, $.fn.parallaxy.Viewport.windowHeight);
}
}
if(window.ignoreParallaxy !== true){
$(window).on('scroll', function(){
// update scroll position
$.fn.parallaxy.Viewport.windowPostionY = $(window).scrollTop();
// update all parallxy heights data
for(var i=0; i<$.fn.parallaxy.Elements.length; i++){
$.fn.parallaxy.Elements[i].scrolled($.fn.parallaxy.Viewport.windowPostionY, $.fn.parallaxy.Viewport.windowHeight);
}
});
}
// bind events and trigger first time.
$(document).on('parallaxy', $.fn.parallaxy.update).trigger('parallaxy');
// extend nailPluginCollection object with functions from zoombie
window.nailPluginCollection.resize = (function(_super) {
// return event
return function() {
_super.apply(this, arguments);
$.fn.parallaxy.resize();
return this;
};
// Pass control back to the original window.nailPluginCollection.resize
// by using .apply on `_super`
})(window.nailPluginCollection.resize);
}(jQuery);
| JavaScript | 0.000001 | @@ -2841,24 +2841,110 @@
owHeight);%0A%0A
+ // if image, update once more..%0A if(!this.isdiv)%7B%0A this.resized()%0A %7D;%0A%0A
%7D%0A%0A Paral
|
3664470d29557a8a16c1eb56054f383a5e5f32d2 | rename stray variable in Send confirm ctrl | src/js/modules/wallet/controllers/send-confirm/send-confirm.ctrl.js | src/js/modules/wallet/controllers/send-confirm/send-confirm.ctrl.js | (function() {
"use strict";
angular.module("blocktrail.wallet")
.controller("SendConfirmCtrl", SendConfirmCtrl);
function SendConfirmCtrl($scope) {
$scope.appControl.showPinInput = true;
/*-- simply a nested state for template control --*/
}
})();
| JavaScript | 0 | @@ -197,11 +197,14 @@
show
-Pin
+Unlock
Inpu
|
9e40efc321e61c7f8ff0e1381fc174a91ca7cc7f | update TransferList | src/_TransferList/TransferList.js | src/_TransferList/TransferList.js | /**
* @file TransferList component
* @author sunday(sunday.wei@derbysoft.com)
*/
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import TextField from '../TextField';
import Checkbox from '../Checkbox';
export default class TransferList extends Component {
static propTypes = {
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* Override the styles of the root element.
*/
listStyle: PropTypes.object,
/**
*
*/
data: PropTypes.array,
/**
*
*/
value: PropTypes.array
};
static defaultProps = {
className: '',
style: null
};
constructor(props, ...restArgs) {
super(props, ...restArgs);
this.state = {
filter: ''
};
this.select = ::this.select;
this.selectAllHandle = ::this.selectAllHandle;
this.filterChangeHandle = ::this.filterChangeHandle;
this.getItemValue = ::this.getItemValue;
}
select(item) {
if (!item.disabled) {
let data = _.cloneDeep(this.props.value);
let selectAll = this.state.selectAll;
let flag = false;
for (let i = 0; i < data.length; i++) {
if (data[i].id === item.id) {
flag = true;
break;
}
}
if (flag) {
let index = data.findIndex(function (value, index, arr) {
return value.id == item.id;
});
data.splice(index, 1);
selectAll = false;
} else {
data.push(item);
if (data.length == this.props.data.length) {
selectAll = true;
}
}
this.setState({
selectAll
}, () => {
this.props.onChange && this.props.onChange(data);
});
}
}
selectAllHandle() {
const {selectAll, filter} = this.state;
const {data} = this.props;
const filterList = this.getFilterList(data, filter);
let newData = [];
for (let i = 0; i < filterList.length; i++) {
if (!filterList[i]['disabled']) {
newData.push(filterList[i]);
}
}
let value = selectAll ? [] : newData;
this.setState({
selectAll: !selectAll
}, () => {
this.props.onChange && this.props.onChange(value);
});
}
filterChangeHandle(value) {
this.setState({
filter: value,
selectAll: false
}, () => {
this.props.onChange && this.props.onChange([]);
});
}
getItemValue(id) {
let data = this.props.value;
let flag = false;
for (let i = 0; i < data.length; i++) {
if (data[i].id === id) {
flag = true;
break;
} else {
flag = false;
}
}
return flag;
}
getFilterList(list, filter) {
return list.filter((value) => {
if (typeof value == 'object') {
return value.text.toUpperCase().indexOf(filter.toUpperCase()) != -1;
} else {
return value.toUpperCase().indexOf(filter.toUpperCase()) != -1;
}
});
}
componentWillReceiveProps(nextProps) {
if (nextProps.data.length !== this.props.data.length) {
this.setState({
selectAll: false
});
}
}
render() {
const {className, listStyle, data, value} = this.props,
{filter, selectAll} = this.state,
{filterChangeHandle, getItemValue, getFilterList, select, selectAllHandle} = this;
this.filterList = getFilterList(data, filter);
return (
<div className={`transfer-list ${className ? className : ''}`}
style={listStyle}>
<div className="transfer-header">
<Checkbox
label={value && value.length > 0 ? value.length + '/' + this.filterList.length + ' items' : this.filterList.length + ' items'}
checked={selectAll}
onChange={selectAllHandle}/>
</div>
<TextField className="search"
rightIconCls={'fa fa-search'}
onChange={filterChangeHandle}
placeholder={'Search here'}
value={filter}/>
<div ref="options"
className="options">
{
this.filterList.map((item, index) => {
let itemValue = getItemValue(item.id);
return (
<div key={item.text}
className={`option ${item.disabled ? 'disabled' : ''}`}>
<Checkbox label={item.text}
checked={itemValue}
disabled={item.disabled ? item.disabled : false}
onChange={() => {
select(item);
}}/>
</div>
);
})
}
</div>
</div>
);
}
}; | JavaScript | 0 | @@ -258,23 +258,8 @@
';%0A%0A
-export default
clas
@@ -298,482 +298,8 @@
%7B%0A%0A
- static propTypes = %7B%0A%0A /**%0A * The CSS class name of the root element.%0A */%0A className: PropTypes.string,%0A%0A /**%0A * Override the styles of the root element.%0A */%0A listStyle: PropTypes.object,%0A%0A /**%0A *%0A */%0A data: PropTypes.array,%0A%0A /**%0A *%0A */%0A value: PropTypes.array%0A%0A%0A %7D;%0A static defaultProps = %7B%0A className: '',%0A style: null%0A %7D;%0A%0A
@@ -5271,8 +5271,437 @@
%7D%0A%0A%7D;
+%0A%0ATransferList.propTypes = %7B%0A%0A /**%0A * The CSS class name of the root element.%0A */%0A className: PropTypes.string,%0A%0A /**%0A * Override the styles of the root element.%0A */%0A listStyle: PropTypes.object,%0A%0A /**%0A *%0A */%0A data: PropTypes.array,%0A%0A /**%0A *%0A */%0A value: PropTypes.array%0A%0A%0A%7D;%0A%0ATransferList.defaultProps = %7B%0A className: '',%0A style: null%0A%7D;%0A%0Aexport default TransferList;
|
4e2723a7511bd6e96c667a009abb62b42495f35d | Create notifications if window is not focused | js/panel_controller.js | js/panel_controller.js | /*global $, Whisper, Backbone, textsecure, extension*/
/*
* vim: ts=4:sw=4:expandtab
*/
// This script should only be included in background.html
(function () {
'use strict';
window.Whisper = window.Whisper || {};
window.setUnreadCount = function(count) {
if (count > 0) {
extension.navigator.setBadgeText(count);
} else {
extension.navigator.setBadgeText("");
}
};
window.notifyConversation = function(message) {
var conversationId = message.get('conversationId');
var conversation = ConversationController.get(conversationId);
if (!conversation) {
conversation = ConversationController.create({id: conversationId});
conversation.fetch();
}
if (inboxOpened) {
conversation.trigger('newmessages');
extension.windows.drawAttention(inboxWindowId);
if (!appWindow.isMinimized()) {
return;
}
}
if (Whisper.Notifications.isEnabled()) {
var sender = ConversationController.create({id: message.get('source')});
conversation.fetch().then(function() {
sender.fetch().then(function() {
sender.getNotificationIcon().then(function(iconUrl) {
Whisper.Notifications.add({
title : sender.getTitle(),
message : message.getNotificationText(),
iconUrl : iconUrl,
imageUrl : message.getImageUrl(),
conversationId: conversation.id
});
});
});
});
} else {
openConversation(conversation);
}
};
/* Inbox window controller */
var inboxOpened = false;
var inboxWindowId = 'inbox';
var appWindow = null;
window.openInbox = function() {
if (inboxOpened === false) {
inboxOpened = true;
extension.windows.open({
id: 'inbox',
url: 'index.html',
focused: true,
width: 580,
height: 440,
minWidth: 600,
minHeight: 360
}, function (windowInfo) {
inboxWindowId = windowInfo.id;
appWindow = windowInfo;
windowInfo.onClosed.addListener(function () {
inboxOpened = false;
appWindow = null;
});
// close the panel if background.html is refreshed
extension.windows.beforeUnload(function() {
// TODO: reattach after reload instead of closing.
extension.windows.remove(inboxWindowId);
});
});
} else if (inboxOpened === true) {
extension.windows.focus(inboxWindowId, function (error) {
if (error) {
inboxOpened = false;
openInbox();
}
});
}
};
var open;
window.openConversation = function(conversation) {
if (inboxOpened === true) {
var appWindow = chrome.app.window.get(inboxWindowId);
appWindow.contentWindow.openConversation(conversation);
} else {
open = conversation;
}
openInbox();
};
window.getOpenConversation = function() {
var o = open;
open = null;
return o;
};
})();
| JavaScript | 0 | @@ -858,122 +858,159 @@
-extension.windows.drawAttention(inboxWindowId);%0A if (!appWindow.isMinimized()) %7B%0A return
+if (inboxFocused) %7B%0A return;%0A %7D%0A if (inboxOpened) %7B%0A extension.windows.drawAttention(inboxWindowId)
;%0A
@@ -1891,16 +1891,46 @@
ller */%0A
+ var inboxFocused = false;%0A
var
@@ -2654,16 +2654,297 @@
%7D);%0A%0A
+ appWindow.contentWindow.addEventListener('blur', function() %7B%0A inboxFocused = false;%0A %7D);%0A appWindow.contentWindow.addEventListener('focus', function() %7B%0A inboxFocused = true;%0A %7D);%0A%0A
|
822e7fd7e67f79c7211777215f3821dea8641aac | Change param name `key` to `url` | src/Layers/FeatureLayer/FeatureLayer.js | src/Layers/FeatureLayer/FeatureLayer.js | L.esri.Layers.FeatureLayer = L.esri.Layers.FeatureManager.extend({
statics: {
EVENTS: 'click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose'
},
/**
* Constructor
*/
initialize: function (url, options) {
L.esri.Layers.FeatureManager.prototype.initialize.call(this, url, options);
options = L.setOptions(this, options);
this._layers = {};
this._leafletIds = {};
this._key = 'c'+(Math.random() * 1e9).toString(36).replace('.', '_');
},
/**
* Layer Interface
*/
onAdd: function(map){
return L.esri.Layers.FeatureManager.prototype.onAdd.call(this, map);
},
onRemove: function(map){
for (var i in this._layers) {
map.removeLayer(this._layers[i]);
}
return L.esri.Layers.FeatureManager.prototype.onRemove.call(this, map);
},
/**
* Feature Managment Methods
*/
createLayers: function(features){
for (var i = features.length - 1; i >= 0; i--) {
var geojson = features[i];
var layer = this._layers[geojson.id];
var newLayer;
if(layer && !this._map.hasLayer(layer)){
this._map.addLayer(layer);
}
if (layer && layer.setLatLngs) {
// @TODO Leaflet 0.8
//newLayer = L.GeoJSON.geometryToLayer(geojson, this.options);
var updateGeo = L.GeoJSON.geometryToLayer(geojson, this.options.pointToLayer, L.GeoJSON.coordsToLatLng, this.options);
layer.setLatLngs(updateGeo.getLatLngs());
}
if(!layer){
// @TODO Leaflet 0.8
//newLayer = L.GeoJSON.geometryToLayer(geojson, this.options);
newLayer = L.GeoJSON.geometryToLayer(geojson, this.options.pointToLayer, L.GeoJSON.coordsToLatLng, this.options);
newLayer.feature = geojson;
newLayer.defaultOptions = newLayer.options;
newLayer._leaflet_id = this._key + '_' + geojson.id;
this._leafletIds[newLayer._leaflet_id] = geojson.id;
// bubble events from layers to this
// @TODO Leaflet 0.8
// newLayer.addEventParent(this);
newLayer.on(L.esri.Layers.FeatureLayer.EVENTS, this._propagateEvent, this);
// bind a popup if we have one
if(this._popup && newLayer.bindPopup){
newLayer.bindPopup(this._popup(newLayer.feature, newLayer));
}
if(this.options.onEachFeature){
this.options.onEachFeature(newLayer.feature, newLayer);
}
// cache the layer
this._layers[newLayer.feature.id] = newLayer;
// style the layer
this.resetStyle(newLayer.feature.id);
this.fire('createfeature', {
feature: newLayer.feature
});
// add the layer if it is within the time bounds or our layer is not time enabled
if(!this.options.timeField || (this.options.timeField && this._featureWithinTimeRange(geojson)) ){
this._map.addLayer(newLayer);
}
}
}
},
addLayers: function(ids){
for (var i = ids.length - 1; i >= 0; i--) {
var layer = this._layers[ids[i]];
if(layer){
this.fire('addfeature', {
feature: layer.feature
});
this._map.addLayer(layer);
}
}
},
removeLayers: function(ids, permanent){
for (var i = ids.length - 1; i >= 0; i--) {
var id = ids[i];
var layer = this._layers[id];
if(layer){
this.fire('removefeature', {
feature: layer.feature,
permanent: permanent
});
this._map.removeLayer(layer);
}
if(layer && permanent){
delete this._layers[id];
}
}
},
/**
* Styling Methods
*/
resetStyle: function (id) {
var layer = this._layers[id];
if(layer){
layer.options = layer.defaultOptions;
this.setFeatureStyle(layer.feature.id, this.options.style);
}
return this;
},
setStyle: function (style) {
this.eachFeature(function (layer) {
this.setFeatureStyle(layer.feature.id, style);
}, this);
return this;
},
setFeatureStyle: function (id, style) {
var layer = this._layers[id];
if (typeof style === 'function') {
style = style(layer.feature);
}
if (layer.setStyle) {
layer.setStyle(style);
}
},
/**
* Popup Methods
*/
bindPopup: function (fn, options) {
this._popup = fn;
for (var i in this._layers) {
var layer = this._layers[i];
var popupContent = this._popup(layer.feature, layer);
layer.bindPopup(popupContent, options);
}
return this;
},
unbindPopup: function () {
this._popup = false;
for (var i in this._layers) {
this._layers[i].unbindPopup();
}
return this;
},
/**
* Utility Methods
*/
eachFeature: function (fn, context) {
for (var i in this._layers) {
fn.call(context, this._layers[i]);
}
return this;
},
getFeature: function (id) {
return this._layers[id];
},
// from https://github.com/Leaflet/Leaflet/blob/v0.7.2/src/layer/FeatureGroup.js
// @TODO remove at Leaflet 0.8
_propagateEvent: function (e) {
e.layer = this._layers[this._leafletIds[e.target._leaflet_id]];
e.target = this;
this.fire(e.type, e);
}
});
L.esri.FeatureLayer = L.esri.Layers.FeatureLayer;
L.esri.Layers.featureLayer = function(key, options){
return new L.esri.Layers.FeatureLayer(key, options);
};
L.esri.featureLayer = function(key, options){
return new L.esri.Layers.FeatureLayer(key, options);
}; | JavaScript | 0.000002 | @@ -5288,35 +5288,35 @@
ayer = function(
-key
+url
, options)%7B%0A re
@@ -5343,35 +5343,35 @@
rs.FeatureLayer(
-key
+url
, options);%0A%7D;%0A%0A
@@ -5401,19 +5401,19 @@
unction(
-key
+url
, option
@@ -5456,19 +5456,19 @@
reLayer(
-key
+url
, option
@@ -5453,28 +5453,29 @@
atureLayer(url, options);%0A%7D;
+%0A
|
dacf64c44ec9e8fe36b3d4e598f7f4570b7fadc0 | Fix /body test server | example/server.js | example/server.js | var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer')();
var cors = require('cors');
var app = express();
app.use(cors());
app.options('*', cors());
var parseJSON = bodyParser.json();
var parseUrlencoded = bodyParser.urlencoded({ extended: true });
app.use(function(req, res, next){
if ((req.header('Content-Type') || req.header('content-type')) === 'application/json') {
parseJSON(req, res, next);
} else if ((req.header('Content-Type') || req.header('content-type')) === 'application/x-www-form-urlencoded') {
parseUrlencoded(req, res, next);
} else if ((req.header('Content-Type') || req.header('content-type') || '').indexOf('multipart/form-data') >= 0) {
multer.array()(req, res, next);
} else {
req.body = '';
req.setEncoding('utf8');
req.on('data', function(chunk) {
req.body += chunk;
});
req.on('end', function() {
next();
});
}
});
app.use(express.static(__dirname));
app.use(express.static(path.join(__dirname, '..', 'dist')));
var id = 0;
var users = [
{id: ++id, name: 'Paul'},
{id: ++id, name: 'Alexandre'}
];
function find(id) {
return users.reduce(function (res, user) {
if (user.id === id) {
res = user;
}
return res;
}, undefined);
}
app.all('/status/:s', function (req, res) {
console.log(req.method, '/status/'+req.params.s);
res.status(req.params.s).end();
});
app.all('/body', function (req, res) {
console.log(req.method, '/body', req.body);
res.status(200).send(req.body);
});
app.all('/headers', function (req, res) {
console.log(req.method, '/headers', req.query);
var body = {};
for (var header in req.query) {
body[header] = req.header(header);
}
res.status(200).send(body);
});
app.all('/query', function (req, res) {
console.log(req.method, '/query', req.query);
var body = {};
for (var name in req.query) {
body[name] = req.query[name];
}
res.status(200).json(body);
})
app.all('/pending', function (req, res) {
console.log(req.method, '/pending', req.query.timeout || 2000, 'ms');
var timeout = parseInt(req.query.timeout, 10);
if (isNaN(timeout)) {
timeout = 2000;
}
setTimeout(function () {
res.status(200).end();
}, timeout);
});
app.get('/users', function (req, res) {
console.log('GET', '/users');
res.status(200).json(users);
});
app.post('/users', function (req, res) {
console.log('POST', '/users', req.body);
if (typeof req.body === 'object' && req.body.name) {
req.body.id = ++id;
users.push(req.body);
res.status(201).json(req.body);
} else {
res.status(400).end();
}
});
app.get('/users/:id', function (req, res) {
console.log('GET', '/users/'+req.params.id);
try {
var id = parseInt(req.params.id, 10);
var user = find(id);
if (user) {
res.status(200).json(user);
} else {
res.status(404).end();
}
} catch (e) {
res.status(400).send('Invalid ID');
}
})
app.listen(3000, function () {
console.log('Example server listening at port 3000');
});
| JavaScript | 0 | @@ -362,21 +362,34 @@
ext)%7B%0A
-if ((
+var contentType =
req.head
@@ -428,38 +428,66 @@
('content-type')
-) ===
+ %7C%7C '';%0A if (contentType.indexOf(
'application/jso
@@ -489,16 +489,22 @@
n/json')
+ %3E= 0)
%7B%0A p
@@ -546,71 +546,28 @@
if (
-(req.header('C
+c
ontent
--
Type
-') %7C%7C req.header('content-type')) ===
+.indexOf(
'app
@@ -598,16 +598,22 @@
ncoded')
+ %3E= 0)
%7B%0A p
@@ -661,72 +661,19 @@
if (
-(req.header('C
+c
ontent
--
Type
-') %7C%7C req.header('content-type') %7C%7C '')
.ind
|
938425628ca0f453620c042b3807b3557e4a4328 | Fix duration | share/spice/spotify/spotify.js | share/spice/spotify/spotify.js | (function (env) {
'use strict';
env.ddg_spice_spotify = function(api_result){
var query = DDG.get_query();
query = query.replace(/spotify/, ''); //replace trigger words from query
// Validate the response (customize for your Spice)
if (!api_result || api_result.tracks.items.length === 0) {
return Spice.failed('spotify');
}
// Render the response
Spice.add({
id: 'spotify',
// Customize these properties
name: 'Spotify',
data: api_result.tracks.items,
meta: {
sourceName: 'Spotify',
sourceUrl: 'https://play.spotify.com/search/' + query.trim(),
},
normalize: function(item) {
return {
title: item.name,
image: item.album.images[1].url, /* ~300x300px */
streamURL: '/audio?u=' + item.preview_url,
url: item.external_urls.spotify,
duration: 3000
};
},
templates: {
item: 'audio_item',
detail: false
}
});
};
}(this));
| JavaScript | 0 | @@ -1049,12 +1049,41 @@
on:
-3000
+Math.min(30000, item.duration_ms)
%0A
|
7d5c662bd27acf1a4922e015e313a86a0f8c4f28 | Update contributor list when a new revision is accepted | src/app/routes/ajax/privileged.js | src/app/routes/ajax/privileged.js | /** privileged.js
* @file: /src/app/routes/ajax/privileged.js
* @description: Handles express routing for the privileged ajax routes
* @parameters: Object(app), Object(resources)
* @returns: Express routes
*/
var ObjectID = require('mongodb').ObjectID
module.exports = function (app, resources) {
var functions = resources.functions
/** /ajax/admin/user/:user_id
* @type: GET
* @description: Ajax admin route for loading user info.
*/
app.get('/ajax/admin/user/:user_id', functions.isPrivileged, function (req, res) {
var usersdb = resources.collections.users
var user_id = req.params.user_id
usersdb.find({_id : new ObjectID(user_id)}).toArray(function(err, user) {
if(err) throw err
res.send(user[0])
})
})
app.get('/ajax/admin/block/:user_id', functions.isPrivileged, function (req, res) {
var usersdb = resources.collections.users
var user_id = req.params.user_id
usersdb.update({
_id : new ObjectID(user_id)
}, {
$set: {
"info.blocked": true,
}
}, function(err, status) {
if(err) throw err
res.json(status)
}
)
})
app.get('/ajax/admin/unblock/:user_id', functions.isPrivileged, function (req, res) {
var usersdb = resources.collections.users
var user_id = req.params.user_id
usersdb.update({
_id : new ObjectID(user_id)
}, {
$set: {
"info.blocked": false,
}
}, function(err, status) {
if(err) throw err
res.json(status)
}
)
})
app.get('/ajax/admin/revision/apply/:page_id/:revision_number', functions.isPrivileged, function (req, res, next) {
var pagesdb = resources.collections.pages
var revisionsdb = resources.collections.revisions
var page_id = req.params.page_id
var revision_number = req.params.revision_number
revisionsdb.find({ post_id: new ObjectID(page_id)}).toArray(function(err, docs) {
if(err) {
res.json({
success:false,
post: page_id,
message: 'Could not find an entry for the page\'s revisions in the database'
})
}
var doc = docs[0]
var revisions = doc.revisions
if(revision_number in revisions) {
//If this has not been moderated before, decrease the number of revisions pending revision
var pending = (revisions[revision_number].meta.accepted === null) ? (doc.pending -1) : doc.pending
var data = {
pending: pending,
revision: revision_number,
revisions: revisions
}
data.revisions[revision_number].meta.accepted = true
revisionsdb.findAndModify({
post_id: new ObjectID(page_id)
},
['_id','asc'], // sort order
{
$set: data
}, {
new: true,
upsert: true
},
function (err, result) {
if(err) {
res.json({
success:false,
post: page_id,
message:'Failed to update the page\'s revision'
})
}
var new_post = data.revisions[revision_number]
delete(new_post['meta'])
var isodate = functions.newISOdate(new Date(revision_number * 1000))
pagesdb.findAndModify({
_id: new ObjectID(page_id)
},
['_id','asc'], // sort order
{
$set: {
post: new_post,
"timestamp.updated": isodate
}
}, {
new: true,
upsert: true
}, function (err, result) {
if(err) {
res.json({
success:false,
post: page_id,
message: 'Failed to update the page\'s content'
})
}
res.json({
success:true,
post: page_id,
message: 'Successfully updated page to approved revision'
})
}
)
}
)
} else {
res.json({
success:false,
post: page_id,
message:'Could not find a revision with supplied id among the page\'s revisions'
})
}
})
})
app.get('/ajax/admin/revision/deny/:page_id/:revision_number', functions.isPrivileged, function (req, res, next) {
//TODO write this route similar to the apply one
})
app.get('/ajax/admin/revision/compare/:page_id/:revision_number', functions.isPrivileged, function (req, res, next) {
var pagesdb = resources.collections.pages
var revisionsdb = resources.collections.revisions
var page_id = req.params.page_id
var revision_number = req.params.revision_number
pagesdb.find({_id : new ObjectID(page_id)}).toArray(function(err, doc) {
var post = doc[0]
revisionsdb.find({ post_id : new ObjectID(page_id) }).toArray(function(err, docs) {
if(err) throw err
var revisions = docs[0].revisions
var contentPost = post.post.content
var contentRevision = revisions[revision_number].content
//Find <br> tags ("line breaks" - kind of) and compare line by line
var regex = /<br\s*[\/]?>/gi
var contentNow = contentPost.split(regex) ? contentPost.split(regex) : [contentPost]
var contentUpdated = contentRevision.split(regex) ? contentRevision.split(regex) : [contentRevision]
var loop = (contentNow.length > contentUpdated.length) ? contentNow : contentUpdated
/* TODO: loop over contentNow and in that loop compare contentNow[i] inside another loop against contentUpdated[i],
if both array's string matches and the [i] is the same, show muted,
if contentUpdated string matches a string in contentNow and [i] is different, show warning,
if contentUpdated is not matched and [i] is >= contentNow.length show success,
if contentNow string is not matched and [i] exists within contentUpdated, show danger,
*/
var diffs = []
for (var i = 0; i < loop.length; i++) {
if(i < contentNow.length && i < contentUpdated.length) {
if(contentNow[i] == contentUpdated[i]) {
diffs.push({status: 'muted', value: contentNow[i] + '<br>' })
} else {
diffs.push({status: 'success', value: contentUpdated[i] })
diffs.push({status: 'danger', value: contentNow[i] + '<br>' })
}
} else {
if(i < contentNow.length) {
diffs.push({status: 'danger', value: contentNow[i] + '<br>' })
} else if (i < contentUpdated.length) {
diffs.push({status: 'success', value: contentUpdated[i] + '<br>' })
}
}
}
var output = {
post: {
id: page_id,
created: post.created,
updated: post.updated
},
revision: {
number: revision_number,
created: revisions[revision_number].meta.timestamp.created,
accepted: revisions[revision_number].meta.accepted
},
diffs: diffs
}
res.json(output)
})
})
})
} | JavaScript | 0 | @@ -3183,16 +3183,153 @@
number%5D%0A
+ var contributors = (new_post%5B'meta'%5D.user_info instanceof Array) ? new_post%5B'meta'%5D.user_info : %5Bnew_post%5B'meta'%5D.user_info%5D%0A
@@ -3653,16 +3653,74 @@
w_post,%0A
+ %22user_info.contributors%22: contributors,%0A
|
01a87aa7d86e1662970726ce7e9119cd67d88f4c | Replace occurences of 'startCode' with 'code' | src/assess/assessmentValidator.js | src/assess/assessmentValidator.js | var validator = require('validator'),
iz = require('iz');
var assessmentValidator = {};
var validate = function (assessment) {
var toReturn = true;
var results = [
validator.isLength(assessment.id, 2),
validator.isLength(assessment.title, 2),
validator.isLength(assessment.instructions, 10),
iz(assessment.providedCompilationUnits).anArray().required().valid,
iz(assessment.compilationUnitsToSubmit).anArray().minLength(1).valid,
iz(assessment.tests).anArray().minLength(1).valid,
iz(assessment.tips).anArray().required().valid,
iz(assessment.guides).anArray().required().valid
];
// TODO Validate each individual element in arrays
// validator.contains(assessment.startCode, 'public class ' + assessment.className + ' {'),
// validator.isLength(assessment.className, 2)
results.forEach(function (result) {
if (!result) {
//console.log(results);
toReturn = false;
}
});
return toReturn;
};
assessmentValidator.validate = validate;
assessmentValidator.validateAll = function (assessments) {
var result = true;
assessments.forEach(function (assessment) {
if (!validate(assessment)) {
result = false;
}
});
return result;
};
module.exports = assessmentValidator; | JavaScript | 0.999999 | @@ -752,14 +752,9 @@
ent.
-startC
+c
ode,
|
c7d636fbdc7a3351d1d4d3e91a330f52a3f90276 | Update src/actions/Entities/NameNoteActions.js | src/actions/Entities/NameNoteActions.js | src/actions/Entities/NameNoteActions.js | import Ajv from 'ajv';
import { generateUUID } from 'react-native-database';
import moment from 'moment';
import { createRecord, UIDatabase } from '../../database/index';
import { selectCreatingNameNote } from '../../selectors/Entities/nameNote';
import { selectSurveySchemas } from '../../selectors/formSchema';
const ajvErrors = require('ajv-errors');
const ajvOptions = {
errorDataPath: 'property',
allErrors: true,
multipleOfPrecision: 8,
schemaId: 'auto',
jsonPointers: true,
};
export const NAME_NOTE_ACTIONS = {
SELECT: 'NAME_NOTE/select',
RESET: 'NAME_NOTE/reset',
UPDATE_DATA: 'NAME_NOTE/updateData',
CREATE: 'NAME_NOTE/create',
};
const ajv = new Ajv(ajvOptions);
ajvErrors(ajv);
const validateData = (jsonSchema, data) => {
if (!jsonSchema) return true;
const result = ajv.validate(jsonSchema, data);
return result;
};
const createDefaultNameNote = (nameID = '') => {
const [pcd] = UIDatabase.objects('PCDEvents');
return {
id: generateUUID(),
entryDate: new Date(),
data: {},
patientEventID: pcd?.id ?? '',
nameID,
};
};
const getMostRecentPCD = patient => {
const [pcdEvent] = UIDatabase.objects('PCDEvents');
if (!pcdEvent) return null;
const { id: pcdEventID } = pcdEvent;
const { nameNotes = [] } = patient ?? {};
if (!nameNotes.length) return null;
const filtered = nameNotes.filter(({ patientEventID }) => patientEventID === pcdEventID);
if (!filtered.length) return null;
const sorted = filtered.sort(
({ entryDate: entryDateA }, { entryDate: entryDateB }) =>
moment(entryDateB).valueOf() - moment(entryDateA).valueOf()
);
const [mostRecentPCD] = sorted;
return mostRecentPCD;
};
const createSurveyNameNote = patient => (dispatch, getState) => {
// Create the seed PCD, which is either their most recently filled survey or
// and empty object.
const seedPCD = getMostRecentPCD(patient) ?? createDefaultNameNote(patient.id);
// Get the survey schema as we need an initial validation to determine if
// the seed has any fields which are required to be filled.
const [surveySchema = {}] = selectSurveySchemas(getState);
const { jsonSchema } = surveySchema;
const isValid = validateData(jsonSchema, seedPCD.data);
if (seedPCD.toObject) {
// Only create name notes, never edit- ensure every new name note which is seeded has a new ID.
const id = generateUUID();
const asObject = { ...seedPCD.toObject(), id, entryDate: new Date().getTime() };
dispatch(select(asObject, isValid));
} else {
dispatch(select(seedPCD, isValid));
}
};
const select = (seed = createDefaultNameNote(), isValid) => ({
type: NAME_NOTE_ACTIONS.SELECT,
payload: { nameNote: seed, isValid },
});
const updateForm = (data, validator) => ({
type: NAME_NOTE_ACTIONS.UPDATE_DATA,
payload: { data, isValid: validator(data) },
});
const saveEditing = optionalNameID => (dispatch, getState) => {
const { nameID, patientEventID, ...nameNote } = selectCreatingNameNote(getState()) ?? {};
UIDatabase.write(() =>
createRecord(UIDatabase, 'NameNote', nameNote, patientEventID, nameID || optionalNameID)
);
dispatch(reset());
};
const createNotes = (nameNotes = []) => {
UIDatabase.write(() => {
nameNotes.forEach(nameNote => {
UIDatabase.update('NameNote', nameNote);
});
});
return { type: NAME_NOTE_ACTIONS.CREATE };
};
const reset = () => ({
type: NAME_NOTE_ACTIONS.RESET,
});
export const NameNoteActions = {
createNotes,
reset,
createSurveyNameNote,
updateForm,
saveEditing,
};
| JavaScript | 0 | @@ -3276,48 +3276,473 @@
-UIDatabase.update('NameNote', nameNote);
+const %7B patientEventID, nameID %7D = nameNote;%0A const name = UIDatabase.get('Name', nameID);%0A const patientEvent = UIDatabase.get('PatientEvent', patientEventID);%0A%0A if (name && patientEvent) %7B%0A const toSave = %7B%0A id: nameNote.id,%0A patientEvent,%0A name,%0A _data: JSON.stringify(nameNote?.data),%0A entryDate: new Date(nameNote?.entryDate),%0A %7D;%0A%0A UIDatabase.update('NameNote', toSave);%0A %7D
%0A
|
d9b00e90f3c690601edcfa20b276f245071f0bf1 | Remove line excess | bin/electron-osx-sign.js | bin/electron-osx-sign.js | #!/usr/bin/env node
var fs = require('fs')
var args = require('minimist')(process.argv.slice(2), {boolean: ['help', 'verbose']})
var usage = fs.readFileSync(__dirname + '/electron-osx-sign-usage.txt').toString()
var sign = require('../')
args.app = args._.shift()
args.binaries = args._
delete args._
if (!args.app || args.help) {
console.log(usage)
process.exit(0)
}
// Remove excess arguments
delete args._
delete args.help
sign(args, function done (err) {
if (err) {
console.error('Sign failed.')
if (err.message) console.error(err.message)
else console.error(err, err.stack)
process.exit(1)
}
console.log('Application signed:', args.app)
process.exit(0)
})
| JavaScript | 0.000002 | @@ -280,30 +280,16 @@
= args._
-%0Adelete args._
%0A%0Aif (!a
|
45a5cbf72f29ebc4ea6bdabb049f3276ee911f7a | use capitalised builder method | src/babel/traversal/path/lib/hoister.js | src/babel/traversal/path/lib/hoister.js | import * as react from "../../../transformation/helpers/react";
import * as t from "../../../types";
var referenceVisitor = {
ReferencedIdentifier(node, parent, scope, state) {
if (this.isJSXIdentifier() && react.isCompatTag(node.name)) {
return;
}
// direct references that we need to track to hoist this to the highest scope we can
var binding = scope.getBinding(node.name);
if (!binding) return;
// this binding isn't accessible from the parent scope so we can safely ignore it
// eg. it's in a closure etc
if (binding !== state.scope.getBinding(node.name)) return;
if (binding.constant) {
state.bindings[node.name] = binding;
} else {
for (var violationPath of (binding.constantViolations: Array)) {
state.breakOnScopePaths.push(violationPath.scope.path);
}
}
}
};
export default class PathHoister {
constructor(path, scope) {
this.breakOnScopePaths = [];
this.bindings = {};
this.scopes = [];
this.scope = scope;
this.path = path;
}
isCompatibleScope(scope) {
for (var key in this.bindings) {
var binding = this.bindings[key];
if (!scope.bindingIdentifierEquals(key, binding.identifier)) {
return false;
}
}
return true;
}
getCompatibleScopes() {
var scope = this.path.scope;
do {
if (this.isCompatibleScope(scope)) {
this.scopes.push(scope);
} else {
break;
}
if (this.breakOnScopePaths.indexOf(scope.path) >= 0) {
break;
}
} while(scope = scope.parent);
}
getAttachmentPath() {
var scopes = this.scopes;
var scope = scopes.pop();
if (!scope) return;
if (scope.path.isFunction()) {
if (this.hasOwnParamBindings(scope)) {
// should ignore this scope since it's ourselves
if (this.scope === scope) return;
// needs to be attached to the body
return scope.path.get("body").get("body")[0];
} else {
// doesn't need to be be attached to this scope
return this.getNextScopeStatementParent();
}
} else if (scope.path.isProgram()) {
return this.getNextScopeStatementParent();
}
}
getNextScopeStatementParent() {
var scope = this.scopes.pop();
if (scope) return scope.path.getStatementParent();
}
hasOwnParamBindings(scope) {
for (var name in this.bindings) {
if (!scope.hasOwnBinding(name)) continue;
var binding = this.bindings[name];
if (binding.kind === "param") return true;
}
return false;
}
run() {
var node = this.path.node;
if (node._hoisted) return;
node._hoisted = true;
this.path.traverse(referenceVisitor, this);
this.getCompatibleScopes();
var path = this.getAttachmentPath();
if (!path) return;
var uid = path.scope.generateUidIdentifier("ref");
path.insertBefore([
t.variableDeclaration("var", [
t.variableDeclarator(uid, this.path.node)
])
]);
var parent = this.path.parentPath;
if (parent.isJSXElement() && this.path.container === parent.node.children) {
// turning the `span` in `<div><span /></div>` to an expression so we need to wrap it with
// an expression container
uid = t.jSXExpressionContainer(uid);
}
this.path.replaceWith(uid);
}
}
| JavaScript | 0.000007 | @@ -3312,9 +3312,9 @@
= t.
-j
+J
SXEx
|
1fd95932c37a3175f04ed81a9ae2bae79d8f4dbd | update generated en_US locale | packages/@uppy/locales/src/en_US.js | packages/@uppy/locales/src/en_US.js | const en_US = {}
en_US.strings = {
addBulkFilesFailed: {
'0': 'Failed to add %{smart_count} file due to an internal error',
'1': 'Failed to add %{smart_count} files due to internal errors'
},
addMore: 'Add more',
addMoreFiles: 'Add more files',
addingMoreFiles: 'Adding more files',
allowAccessDescription: 'In order to take pictures or record video with your camera, please allow camera access for this site.',
allowAccessTitle: 'Please allow access to your camera',
authenticateWith: 'Connect to %{pluginName}',
authenticateWithTitle: 'Please authenticate with %{pluginName} to select files',
back: 'Back',
browse: 'browse',
cancel: 'Cancel',
cancelUpload: 'Cancel upload',
chooseFiles: 'Choose files',
closeModal: 'Close Modal',
companionError: 'Connection with Companion failed',
companionUnauthorizeHint: 'To unauthorize to your %{provider} account, please go to %{url}',
complete: 'Complete',
connectedToInternet: 'Connected to the Internet',
copyLink: 'Copy link',
copyLinkToClipboardFallback: 'Copy the URL below',
copyLinkToClipboardSuccess: 'Link copied to clipboard',
creatingAssembly: 'Preparing upload...',
creatingAssemblyFailed: 'Transloadit: Could not create Assembly',
dashboardTitle: 'File Uploader',
dashboardWindowTitle: 'File Uploader Window (Press escape to close)',
dataUploadedOfTotal: '%{complete} of %{total}',
done: 'Done',
dropHereOr: 'Drop files here or %{browse}',
dropHint: 'Drop your files here',
dropPaste: 'Drop files here, paste or %{browse}',
dropPasteImport: 'Drop files here, paste, %{browse} or import from:',
editFile: 'Edit file',
editing: 'Editing %{file}',
emptyFolderAdded: 'No files were added from empty folder',
encoding: 'Encoding...',
enterCorrectUrl: 'Incorrect URL: Please make sure you are entering a direct link to a file',
enterUrlToImport: 'Enter URL to import a file',
exceedsSize: 'This file exceeds maximum allowed size of',
exceedsSize2: '%{backwardsCompat} %{size}',
failedToFetch: 'Companion failed to fetch this URL, please make sure it’s correct',
failedToUpload: 'Failed to upload %{file}',
fileSource: 'File source: %{name}',
filesUploadedOfTotal: {
'0': '%{complete} of %{smart_count} file uploaded',
'1': '%{complete} of %{smart_count} files uploaded'
},
filter: 'Filter',
finishEditingFile: 'Finish editing file',
folderAdded: {
'0': 'Added %{smart_count} file from %{folder}',
'1': 'Added %{smart_count} files from %{folder}'
},
generatingThumbnails: 'Generating thumbnails...',
import: 'Import',
importFrom: 'Import from %{name}',
loading: 'Loading...',
logOut: 'Log out',
micDisabled: 'Microphone access denied by user',
myDevice: 'My Device',
noCameraDescription: 'In order to take pictures or record video with your camera, please connect or turn on your camera device',
noCameraTitle: 'Camera Not Available',
noDuplicates: 'Cannot add the duplicate file \'%{fileName}\', it already exists',
noFilesFound: 'You have no files or folders here',
noInternetConnection: 'No Internet connection',
noNewAlreadyUploading: 'Cannot add new files: already uploading',
openFolderNamed: 'Open folder %{name}',
pause: 'Pause',
pauseUpload: 'Pause upload',
paused: 'Paused',
poweredBy: 'Powered by',
poweredBy2: '%{backwardsCompat} %{uppy}',
processingXFiles: {
'0': 'Processing %{smart_count} file',
'1': 'Processing %{smart_count} files'
},
recording: 'Recording',
recordingLength: 'Recording length %{recording_length}',
recordingStoppedMaxSize: 'Recording stopped because the file size is about to exceed the limit',
removeFile: 'Remove file',
resetFilter: 'Reset filter',
resume: 'Resume',
resumeUpload: 'Resume upload',
retry: 'Retry',
retryUpload: 'Retry upload',
saveChanges: 'Save changes',
selectAllFilesFromFolderNamed: 'Select all files from folder %{name}',
selectFileNamed: 'Select file %{name}',
selectX: {
'0': 'Select %{smart_count}',
'1': 'Select %{smart_count}'
},
smile: 'Smile!',
startCapturing: 'Begin screen capturing',
startRecording: 'Begin video recording',
stopCapturing: 'Stop screen capturing',
stopRecording: 'Stop video recording',
streamActive: 'Stream active',
streamPassive: 'Stream passive',
submitRecordedFile: 'Submit captured video',
takePicture: 'Take a picture',
timedOut: 'Upload stalled for %{seconds} seconds, aborting.',
unselectAllFilesFromFolderNamed: 'Unselect all files from folder %{name}',
unselectFileNamed: 'Unselect file %{name}',
upload: 'Upload',
uploadComplete: 'Upload complete',
uploadFailed: 'Upload failed',
uploadPaused: 'Upload paused',
uploadXFiles: {
'0': 'Upload %{smart_count} file',
'1': 'Upload %{smart_count} files'
},
uploadXNewFiles: {
'0': 'Upload +%{smart_count} file',
'1': 'Upload +%{smart_count} files'
},
uploading: 'Uploading',
uploadingXFiles: {
'0': 'Uploading %{smart_count} file',
'1': 'Uploading %{smart_count} files'
},
xFilesSelected: {
'0': '%{smart_count} file selected',
'1': '%{smart_count} files selected'
},
xMoreFilesAdded: {
'0': '%{smart_count} more file added',
'1': '%{smart_count} more files added'
},
xTimeLeft: '%{time} left',
youCanOnlyUploadFileTypes: 'You can only upload: %{types}',
youCanOnlyUploadX: {
'0': 'You can only upload %{smart_count} file',
'1': 'You can only upload %{smart_count} files'
},
youHaveToAtLeastSelectX: {
'0': 'You have to select at least %{smart_count} file',
'1': 'You have to select at least %{smart_count} files'
}
}
en_US.pluralize = function (count) {
if (count === 1) {
return 0
}
return 1
}
if (typeof window !== 'undefined' && typeof window.Uppy !== 'undefined') {
window.Uppy.locales.en_US = en_US
}
module.exports = en_US
| JavaScript | 0.000001 | @@ -2810,33 +2810,16 @@
rd video
- with your camera
, please
@@ -2831,23 +2831,9 @@
ect
-or turn on your
+a
cam
|
678d607332622ca28fd0449e5e320b3cdd974fb1 | Fix remove and get of non-existent id | packages/binary-heap/binary-heap.js | packages/binary-heap/binary-heap.js | // Constructor of Heap
// - comparator - Function - given two items returns a number
// - initData - Array - the initial data in a format:
// Object:
// - id - String - unique id of the item
// - value - Any - the data value
// the contents of initData is retained
BinaryHeap = function (comparator, initData) {
if (! _.isFunction(comparator))
throw new Error('Passed comparator is invalid, should be a comparison function');
var self = this;
self._comparator = comparator;
self._heapIdx = {};
self._heap = [];
if (_.isArray(initData))
self._initFromData(initData);
};
var idStringify;
if (Package.minimongo) {
idStringify = Package.minimongo.LocalCollection._idStringify;
} else {
// XXX: These can't deal with special strings like '__proto__'
// XXX: or '{ looksLike: "object" }' or numbers.
idStringify = function (id) { return JSON.stringify(id); };
}
_.extend(BinaryHeap.prototype, {
_initFromData: function (data) {
var self = this;
self._heap = _.clone(data);
_.each(data, function (o, i) {
self._heapIdx[idStringify(o.id)] = i;
});
for (var i = parentIdx(data.length); i >= 0; i--)
self._heapify(i);
},
_heapify: function (idx) {
var self = this;
while (leftChildIdx(idx) < self.size()) {
var left = leftChildIdx(idx);
var right = rightChildIdx(idx);
var largest = idx;
if (left < self.size() &&
self._comparator(self._get(left), self._get(largest)) > 0) {
largest = left;
}
if (right < self.size() &&
self._comparator(self._get(right), self._get(largest)) > 0) {
largest = right;
}
if (largest === idx)
break;
self._swap(largest, idx);
idx = largest;
}
},
_upHeap: function (idx) {
var self = this;
var value = self._get(idx);
var ancestor = idx;
while (ancestor > 0) {
var parent = parentIdx(ancestor);
if (self._comparator(self._get(parent), value) < 0)
ancestor = parent;
else
break;
}
if (ancestor !== idx)
self._swap(ancestor, idx);
},
// Internal: gets raw data object placed on idxth place in heap
_get: function (idx) {
var self = this;
return self._heap[idx].value;
},
_swap: function (idxA, idxB) {
var self = this;
var A = self._heap[idxA];
var B = self._heap[idxB];
self._heapIdx[idStringify(A.id)] = idxB;
self._heapIdx[idStringify(B.id)] = idxA;
self._heap[idxA] = B;
self._heap[idxB] = A;
},
get: function (id) {
var self = this;
return self._get(self._heapIdx[idStringify(id)]);
},
set: function (id, value) {
var self = this;
if (self.has(id)) {
if (self.get(id) === value)
return;
else
self.remove(id);
}
self._heapIdx[idStringify(id)] = self._heap.length;
self._heap.push({ id: id, value: value });
self._upHeap(self._heap.length - 1);
},
remove: function (id) {
var self = this;
var strId = idStringify(id);
if (! self.has(id)) {
var last = self._heap.length - 1;
var idx = self._heapIdx[strId];
self._swap(idx, last);
self._heap.pop();
self._heapify(idx);
delete self._heapIdx[strId];
}
},
has: function (id) {
var self = this;
return self._heapIdx[idStringify(id)] !== undefined;
},
empty: function (id) {
var self = this;
return !self.size();
},
clear: function () {
var self = this;
self._heap = [];
self._heapIdx = {};
},
forEach: function (iterator) {
var self = this;
_.each(self._heap, function (obj) {
return iterator(obj.value, obj.id);
});
},
size: function () {
var self = this;
return self._heap.length;
},
setDefault: function (id, def) {
var self = this;
if (self.has(id))
return self.get(id);
self.set(id, def);
return def;
},
clone: function () {
var self = this;
var clone = new BinaryHeap(self._comparator);
clone._heap = EJSON.clone(self._heap);
clone._heapIdx = EJSON.clone(self._heapIdx);
},
maxElementId: function () {
var self = this;
return self.size() ? self._heap[0].id : null;
}
});
function leftChildIdx (i) { return i * 2 + 1; }
function rightChildIdx (i) { return i * i + 2; }
function parentIdx (i) { return (i - 1) >> 1; }
| JavaScript | 0.000005 | @@ -2584,32 +2584,75 @@
ar self = this;%0A
+ if (! self.has(id))%0A return null;%0A
return self.
@@ -3093,34 +3093,32 @@
y(id);%0A%0A if (
-!
self.has(id)) %7B%0A
@@ -3113,24 +3113,24 @@
.has(id)) %7B%0A
+
var la
@@ -3191,24 +3191,53 @@
Idx%5BstrId%5D;%0A
+%0A if (idx !== last) %7B%0A
self._
@@ -3251,32 +3251,34 @@
x, last);%0A
+
self._heap.pop()
@@ -3281,24 +3281,26 @@
op();%0A
+
+
self._heapif
@@ -3303,24 +3303,74 @@
apify(idx);%0A
+ %7D else %7B%0A self._heap.pop();%0A %7D%0A%0A
delete
|
ee24c0d2b12fd1e9c5b802c81c5ec76bc7cc6c88 | Remove console option | ui/src/data_explorer/components/Visualization.js | ui/src/data_explorer/components/Visualization.js | import React, {PropTypes} from 'react'
import buildInfluxQLQuery from 'utils/influxql'
import classNames from 'classnames'
import AutoRefresh from 'shared/components/AutoRefresh'
import LineGraph from 'shared/components/LineGraph'
import SingleStat from 'shared/components/SingleStat'
import MultiTable from './MultiTable'
const RefreshingLineGraph = AutoRefresh(LineGraph)
const RefreshingSingleStat = AutoRefresh(SingleStat)
const VIEWS = ['graph', 'table', 'console']
const {
arrayOf,
number,
shape,
string,
} = PropTypes
const Visualization = React.createClass({
propTypes: {
cellName: string,
cellType: string,
autoRefresh: number.isRequired,
timeRange: shape({
upper: string,
lower: string,
}).isRequired,
queryConfigs: arrayOf(shape({})).isRequired,
activeQueryIndex: number,
height: string,
heightPixels: number,
},
contextTypes: {
source: PropTypes.shape({
links: PropTypes.shape({
proxy: PropTypes.string.isRequired,
}).isRequired,
}).isRequired,
},
getInitialState() {
return {
view: 'graph',
}
},
handleToggleView(view) {
this.setState({view})
},
render() {
const {queryConfigs, timeRange, height, heightPixels} = this.props;
const {source} = this.context;
const proxyLink = source.links.proxy;
const {view} = this.state;
const statements = queryConfigs.map((query) => {
const text = query.rawText || buildInfluxQLQuery(timeRange, query);
return {text, id: query.id};
});
const queries = statements.filter((s) => s.text !== null).map((s) => {
return {host: [proxyLink], text: s.text, id: s.id};
});
return (
<div className={classNames("graph", {active: true})} style={{height}}>
<VisHeader views={VIEWS} view={view} onToggleView={this.handleToggleView} name={name || 'Graph'}/>
<div className={classNames({"graph-container": view === 'graph', "table-container": view === 'table'})}>
{this.renderVisualization(view, queries, heightPixels)}
</div>
</div>
);
},
renderVisualization(view, queries, heightPixels) {
switch (view) {
case 'graph':
return this.renderGraph(queries)
case 'table':
return <MultiTable queries={queries} height={heightPixels} />
case 'console':
return <div>I'm a console</div>
default:
this.renderGraph(queries)
}
},
renderGraph(queries) {
const {cellType, autoRefresh, activeQueryIndex} = this.props
const isInDataExplorer = true
if (cellType === 'single-stat') {
return <RefreshingSingleStat queries={[queries[0]]} autoRefresh={autoRefresh} />
}
const displayOptions = {
stepPlot: cellType === 'line-stepplot',
stackedGraph: cellType === 'line-stacked',
}
return (
<RefreshingLineGraph
queries={queries}
autoRefresh={autoRefresh}
activeQueryIndex={activeQueryIndex}
isInDataExplorer={isInDataExplorer}
showSingleStat={cellType === "line-plus-single-stat"}
displayOptions={displayOptions}
/>
)
},
})
export default Visualization
| JavaScript | 0.000002 | @@ -456,19 +456,8 @@
ble'
-, 'console'
%5D%0A%0Ac
@@ -2317,70 +2317,8 @@
/%3E%0A
- case 'console':%0A return %3Cdiv%3EI'm a console%3C/div%3E%0A
|
7f09f1d5347050f0d09835c44389cef79dcbb3d5 | Remove self-assignment in geneQuery() | src/client/services/server-api/index.js | src/client/services/server-api/index.js | const io = require('socket.io-client');
const qs = require('querystring');
const _ = require('lodash');
const socket = io.connect('/');
const defaultFetchOpts = {
method: 'GET', headers: {
'Content-type': 'application/json',
'Accept': 'application/json'
}
};
const ServerAPI = {
getGraphAndLayout(uri, version) {
return fetch(`/api/get-graph-and-layout?${qs.stringify({uri, version})}`, defaultFetchOpts).then(res => res.json());
},
pcQuery(method, params){
return fetch(`/pc-client/${method}?${qs.stringify(params)}`, defaultFetchOpts);
},
datasources(){
return fetch('/pc-client/datasources', defaultFetchOpts).then(res => res.json());
},
querySearch(query){
const queryClone=_.assign({},query);
if(/(uniprot:\w+|ncbi:[0-9]+|hgnc:\w+)$/.test(queryClone.q)){queryClone.q=queryClone.q.split(':')[1];}
return fetch(`/pc-client/querySearch?${qs.stringify(queryClone)}`, defaultFetchOpts).then(res => res.json());
},
geneQuery(query){
if(query.genes.length>=1){
query.genes= query.genes;
return fetch('/api/validation', {
method:'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body:JSON.stringify(query)
}).then(res => res.json());
}else{
return Promise.resolve({geneInfo:[],unrecognized:[]});
}
},
getGeneInformation(ids){
return fetch(`https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?retmode=json&db=gene&id=${ids.join(',')}`, {method: 'GET'}).then(res => res.json());
},
getUniprotnformation(ids){
return fetch(`https://www.ebi.ac.uk/proteins/api/proteins?offset=0&accession=${ids.join(',')}`, defaultFetchOpts).then(res => res.json());
},
// Send a diff in a node to the backend. The backend will deal with merging these diffs into
// a layout
submitNodeChange(uri, version, nodeId, bbox) {
socket.emit('submitDiff', {
uri: uri,
version: version.toString(),
diff: {
nodeID: nodeId,
bbox: bbox
}
});
},
submitLayoutChange(uri, version, layout) {
socket.emit('submitLayout', {
uri: uri,
version: version,
layout: layout
});
},
initReceiveLayoutChange(callback) {
socket.on('layoutChange', layoutJSON => {
callback(layoutJSON);
});
},
initReceiveNodeChange(callback) {
socket.on('nodeChange', nodeDiff => {
callback(nodeDiff);
});
},
};
module.exports = ServerAPI; | JavaScript | 0.000001 | @@ -1021,40 +1021,8 @@
1)%7B%0A
- query.genes= query.genes;%0A
|
f9f114f8386286f18482c8d0f9ab44d6efee2477 | Fix drag and drop style from toggling on and off | ui/src/data_explorer/components/WriteDataForm.js | ui/src/data_explorer/components/WriteDataForm.js | import React, {Component, PropTypes} from 'react'
import classnames from 'classnames'
import OnClickOutside from 'shared/components/OnClickOutside'
import WriteDataBody from 'src/data_explorer/components/WriteDataBody'
import WriteDataHeader from 'src/data_explorer/components/WriteDataHeader'
import {OVERLAY_TECHNOLOGY} from 'shared/constants/classNames'
class WriteDataForm extends Component {
constructor(props) {
super(props)
this.state = {
selectedDatabase: props.selectedDatabase,
inputContent: null,
uploadContent: '',
fileName: '',
progress: '',
isManual: false,
dragClass: 'drag-none',
}
this.handleSelectDatabase = ::this.handleSelectDatabase
this.handleSubmit = ::this.handleSubmit
this.handleClickOutside = ::this.handleClickOutside
this.handleKeyUp = ::this.handleKeyUp
this.handleEdit = ::this.handleEdit
this.handleFile = ::this.handleFile
this.toggleWriteView = ::this.toggleWriteView
this.handleFileOpen = ::this.handleFileOpen
}
toggleWriteView(isManual) {
this.setState({isManual})
}
handleSelectDatabase(item) {
this.setState({selectedDatabase: item.text})
}
handleClickOutside(e) {
// guard against clicking to close error notification
if (e.target.className === OVERLAY_TECHNOLOGY) {
const {onClose} = this.props
onClose()
}
}
handleKeyUp(e) {
e.stopPropagation()
if (e.key === 'Escape') {
const {onClose} = this.props
onClose()
}
}
async handleSubmit() {
const {onClose, source, writeLineProtocol} = this.props
const {inputContent, uploadContent, selectedDatabase, isManual} = this.state
const content = isManual ? inputContent : uploadContent
try {
await writeLineProtocol(source, selectedDatabase, content)
onClose()
window.location.reload()
} catch (error) {
console.error(error.data.error)
}
}
handleEdit(e) {
this.setState({inputContent: e.target.value.trim()})
}
handleFile(e, drop) {
// todo: expect this to be a File or Blob
let file
if (drop) {
file = e.dataTransfer.files[0]
this.setState({
dragClass: 'drag-none',
})
} else {
file = e.target.files[0]
}
e.preventDefault()
e.stopPropagation()
// async function run when loading of file is complete
const reader = new FileReader()
reader.readAsText(file)
reader.onload = loadEvent => {
this.setState({
uploadContent: loadEvent.target.result,
fileName: file.name,
})
}
}
handleDragOver(e) {
e.preventDefault()
e.stopPropagation()
}
handleDragClass(entering) {
return e => {
e.preventDefault()
if (entering) {
this.setState({
dragClass: 'drag-over',
})
} else {
this.setState({
dragClass: 'drag-none',
})
}
}
}
render() {
const {onClose, errorThrown} = this.props
const {dragClass} = this.state
return (
<div
onDrop={e => this.handleFile(e, true)}
onDragOver={this.handleDragOver}
onDragEnter={this.handleDragClass(true)}
onDragLeave={this.handleDragClass(false)}
className={classnames(OVERLAY_TECHNOLOGY, dragClass)}
>
<div className="write-data-form">
<WriteDataHeader
{...this.state}
handleSelectDatabase={this.handleSelectDatabase}
errorThrown={errorThrown}
toggleWriteView={this.toggleWriteView}
onClose={onClose}
/>
<WriteDataBody
{...this.state}
fileInput={el => this.fileInput = el}
handleEdit={this.handleEdit}
handleFile={this.handleFile}
handleKeyUp={this.handleKeyUp}
handleSubmit={this.handleSubmit}
handleFileOpen={this.handleFileOpen}
/>
</div>
<div className="write-data-form--drag-here">
Drag & Drop a File to Upload
</div>
</div>
)
}
}
const {func, shape, string} = PropTypes
WriteDataForm.propTypes = {
source: shape({
links: shape({
proxy: string.isRequired,
self: string.isRequired,
queries: string.isRequired,
}).isRequired,
}).isRequired,
onClose: func.isRequired,
writeLineProtocol: func.isRequired,
errorThrown: func.isRequired,
selectedDatabase: string,
}
export default OnClickOutside(WriteDataForm)
| JavaScript | 0 | @@ -351,16 +351,36 @@
ssNames'
+%0Alet dragCounter = 0
%0A%0Aclass
@@ -2956,16 +2956,338 @@
%7D%0A %7D%0A%0A
+ handleDragEnter(e) %7B%0A dragCounter += 1%0A e.preventDefault()%0A this.setState(%7BdragClass: 'drag-over'%7D)%0A %7D%0A%0A handleDragLeave(e) %7B%0A dragCounter -= 1%0A e.preventDefault()%0A if (dragCounter === 0) %7B%0A this.setState(%7BdragClass: 'drag-none'%7D)%0A %7D%0A %7D%0A%0A handleFileOpen() %7B%0A this.fileInput.click()%0A %7D%0A%0A
render
@@ -3287,24 +3287,24 @@
render() %7B%0A
-
const %7Bo
@@ -3502,24 +3502,29 @@
nDragEnter=%7B
+e =%3E
this.handleD
@@ -3530,17 +3530,14 @@
Drag
-Class(tru
+Enter(
e)%7D%0A
@@ -3557,16 +3557,21 @@
gLeave=%7B
+e =%3E
this.han
@@ -3581,18 +3581,14 @@
Drag
-Class(fals
+Leave(
e)%7D%0A
|
77656b31416213c38500ffb03cea9cea46331358 | Update dev connection | src/config/zoomdata-connections/development.js | src/config/zoomdata-connections/development.js | export const server = {
credentials: {
access_token: ''
},
application: {
secure: false,
host: 'localhost',
port: 8080,
path: '/zoomdata'
},
oauthOptions: {
client_id: "bmh0c2FfY2xpZW50MTQ1OTM0Nzc1NTg0MjQ4YzNiNzdmLTI1NTYtNGMyMS1iODYyLTg2NDRiYjA5ZDlmZA==",
redirect_uri: "http://localhost:3000/index.html",
auth_uri: "http://localhost:8080/zoomdata/oauth/authorize",
scope: ['read']
}
}; | JavaScript | 0 | @@ -107,12 +107,11 @@
re:
-fals
+tru
e,%0A
@@ -151,19 +151,19 @@
port: 8
-080
+443
,%0A
@@ -389,32 +389,33 @@
auth_uri: %22http
+s
://localhost:808
@@ -416,11 +416,11 @@
st:8
-080
+443
/zoo
|
9cb5c6c648937a09e9005fb82e2f91815ffab8ba | mark printed only if markprinted is chosen | src/containers/Thesis/components/ThesisList.js | src/containers/Thesis/components/ThesisList.js | import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { arrayOf, func, bool } from 'prop-types'
import { thesisType, agreementType, attachmentType } from '../../../util/types'
import LoadingIndicator from '../../LoadingIndicator'
class ThesisList extends Component {
constructor(props) {
super(props)
this.state = {
filteredTheses: props.theses,
formattedTheses: props.theses,
selectedThesesIds: [],
cover: true,
markDone: false
}
this.search = this.search.bind(this)
}
componentWillReceiveProps(newProps) {
if (newProps.theses) {
this.setState({
filteredTheses: newProps.theses,
formattedTheses: newProps.theses,
selectedThesesIds: []
})
}
}
toggleThesis = thesis => () => {
const selectedThesesIds = this.state.selectedThesesIds.includes(thesis.thesisId) ?
this.state.selectedThesesIds.filter(id => id !== thesis.thesisId) :
[...this.state.selectedThesesIds, thesis.thesisId]
this.setState({ selectedThesesIds })
};
search(event) {
if (!event.target.value) {
this.setState({ filteredTheses: this.state.formattedTheses })
return
}
const searchValue = event.target.value.toLowerCase()
// if searchTerm is empty set filteredTheses = theses, else filter theses based on searchTerm
const filteredTheses = this.state.filteredTheses
.filter(thesis => Object.keys(thesis)
.find(key => typeof thesis[key] === 'string' && thesis[key].toLowerCase().includes(searchValue)))
this.setState({ filteredTheses })
}
sendDownloadSelected = () => {
if (this.state.selectedThesesIds.length > 0) {
const attachmentIds = this.props.agreements.map((agreement) => {
if (this.state.selectedThesesIds.find(id => id === agreement.thesisId)) {
return this.props.attachments.filter((attachment) => {
if (attachment.agreementId === agreement.agreementId) {
// Pick correct files;
if (attachment.label === 'thesisFile' || attachment.label === 'reviewFile') {
return true
}
}
return false
})
.sort((a) => {
if (a.label === 'thesisFile') { // Thesis comes before review.
return -1
}
return 1
})
}
return false
}).reduce((acc, cur) => { // Flatten thesis, review pairs.
if (cur) {
return acc.concat(cur.map(attachment => attachment.attachmentId)) // Take only ids
}
return acc
}, this.state.cover ? ['cover'] : [] // Add cover if it's chosen.
)
this.props.downloadSelected(attachmentIds)
this.props.markPrinted(this.state.selectedThesesIds)
}
};
toggleAll = () => {
if (this.state.selectedThesesIds.length > 0) {
this.setState({ selectedThesesIds: [] })
} else {
this.setState({ selectedThesesIds: this.props.theses.map(thesis => thesis.thesisId) })
}
};
toggleCover = () => {
this.setState({ cover: !this.state.cover })
};
toggleMarkDone = () => {
this.setState({ markDone: !this.state.markDone })
};
renderButtons() {
if (!this.props.showButtons) {
return null
}
return (
<div className="ui form">
<div className="two fields" >
<div className="field">
<LoadingIndicator type="DOWNLOAD" />
<button className="ui orange button" onClick={this.sendDownloadSelected}>Download</button>
<div className="ui toggle checkbox">
<input
type="checkbox"
checked={this.state.cover ? 'true' : ''}
onChange={this.toggleCover}
/>
<label>Include cover</label>
</div>
<div className="ui toggle checkbox">
<input
type="checkbox"
checked={this.state.markDone ? 'true' : ''}
onChange={this.toggleMarkDone}
/>
<label>Mark print done</label>
</div>
</div>
<div className="field">
<button className="ui purple button" onClick={this.toggleAll}>Select all</button>
</div>
</div>
</div>
)
}
render() {
return (
<div>
{this.renderButtons()}
<div className="ui fluid category search">
<div className="ui icon input">
<input className="prompt" type="text" placeholder="Filter theses" onChange={this.search} />
<i className="search icon" />
</div>
</div>
<table className="ui celled table">
<thead>
<tr>
<th>Select</th>
<th>Author</th>
<th>Email</th>
<th>Title</th>
<th>Grade</th>
<th>Print Done</th>
</tr>
</thead>
<tbody>
{this.state.filteredTheses.map(thesis => (
<tr key={thesis.thesisId}>
<td>
<div className="ui fitted checkbox">
<input
type="checkbox"
checked={
this.state.selectedThesesIds.includes(thesis.thesisId) ? 'true' : ''
}
onChange={this.toggleThesis(thesis)}
/>
<label />
</div>
</td>
<td>
{thesis.authorLastname ? `${thesis.authorLastname}, ${thesis.authorFirstname}` : ''}
</td>
<td>{thesis.authorEmail}</td>
<td><Link to={`/thesis/${thesis.thesisId}`}>{thesis.title}</Link></td>
<td>{thesis.grade}</td>
<td>{thesis.printDone.toString()}</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
}
ThesisList.propTypes = {
theses: arrayOf(thesisType).isRequired,
downloadSelected: func.isRequired,
agreements: arrayOf(agreementType).isRequired,
attachments: arrayOf(attachmentType).isRequired,
showButtons: bool.isRequired,
markPrinted: func.isRequired
}
export default ThesisList
| JavaScript | 0.000001 | @@ -3217,24 +3217,67 @@
achmentIds)%0A
+ if (this.state.markDone) %7B%0A
@@ -3325,24 +3325,38 @@
dThesesIds)%0A
+ %7D%0A
%7D%0A
|
2ad47bfed526e41c450cbc0cc534e8f1df234d08 | Update affiliations on change. | src/editor/components/ContributorsComponent.js | src/editor/components/ContributorsComponent.js | import { NodeComponent } from 'substance'
import MetadataSection from './MetadataSection'
/*
Edit affiliations for a publication in this MetadataSection
*/
export default class ContributorsComponent extends NodeComponent {
getInitialState() {
return {
expanded: true
}
}
render($$) {
const contribGroup = this.props.node
const doc = contribGroup.getDocument()
let el = $$('div').addClass('sc-affiliations')
el.append(
$$(MetadataSection, {
label: 'Contributors',
expanded: this.state.expanded
}).on('click', this._toggle)
)
if (this.state.expanded) {
let affs = doc.findAll('article-meta > aff-group > aff')
contribGroup.getChildren().forEach((contrib) => {
el.append(
$$('div').addClass('se-metadata-contributor').append(
this._renderName($$, contrib),
this._renderAffiliations($$, contrib, affs)
)
)
})
el.append(
$$('button').addClass('se-metadata-contributor-add')
.append('Add Contributor')
.on('click', this._addContributor)
)
}
return el
}
_renderName($$, contrib) {
let TextPropertyEditor = this.getComponent('text-property-editor')
let stringContrib = contrib.find('string-contrib')
return $$('div').addClass('se-name').append(
$$('div').addClass('se-label').append('Name'),
$$(TextPropertyEditor, {
path: stringContrib.getTextPath(),
disabled: this.props.disabled
}).ref(stringContrib.id).addClass('se-text-input')
)
}
_renderAffiliations($$, contrib, affs) {
return $$('div').addClass('se-affiliations').append(
$$('div').addClass('se-label').append('Affiliations'),
this._renderAffChoices($$, contrib, affs)
)
}
_renderAffChoices($$, contrib, affs) {
let props = {
options: [],
selectedOptions: this._getAffReferences(contrib),
maxItems: 2
}
affs.forEach((aff) => {
let stringAff = aff.find('string-aff')
props.options.push({id: aff.id, label: stringAff.getText()})
})
let MultiSelect = this.getComponent('multi-select')
return $$(MultiSelect, props)
.ref(contrib.id + '_affs')
.on('click', this._updateAffiliations.bind(this, contrib.id))
}
_getAffReferences(contrib) {
let attrIds = contrib.getAttribute('aff-ids') || ''
return attrIds.split(' ')
}
_toggle() {
this.setState({
expanded: !this.state.expanded
})
}
_updateAffiliations(contribId) {
const editorSession = this.context.editorSession
let affSelector = this.refs[contribId + '_affs']
let affIds = affSelector.getSelectedOptions()
editorSession.transaction((doc) => {
let contrib = doc.get(contribId)
contrib.setAttribute('aff-ids', affIds.join(' '))
})
}
_addContributor() {
const nodeId = this.props.node.id
const editorSession = this.context.editorSession
editorSession.transaction((doc) => {
let contribGroup = doc.get(nodeId)
let contrib = doc.createElement('contrib').attr('aff-type', 'foo')
contrib.append(
doc.createElement('string-contrib')
)
contribGroup.append(contrib)
})
}
}
| JavaScript | 0 | @@ -2240,36 +2240,37 @@
s')%0A .on('c
-lick
+hange
', this._updateA
|
430ecd17e0e80cc35fb6b9ea5d8233f41ca944b1 | add comment | src/scripts/migrations/importFlowAnnotation.js | src/scripts/migrations/importFlowAnnotation.js | /**
* Import annotations by Flow AI Data Annotators.
* Ground truth: https://github.com/cofacts/ground-truth/blob/main/20200324_14908.zip
*
* Usage:
* 1. Connect to production DB via SSH tunnel
* 2. Specify INPUT_DIRECTORY in code
* 3. Run: node_modules/.bin/babel-node src/scripts/migrations/importFlowAnnotation.js
*/
import 'dotenv/config';
import fs from 'fs';
import path from 'path';
import { createArticleCategory } from 'graphql/mutations/CreateArticleCategory';
import { createOrUpdateArticleCategoryFeedback } from 'graphql/mutations/CreateOrUpdateArticleCategoryFeedback';
const INPUT_DIRECTORY = '../20200324_14908';
const RUMORS_AI_APPID = 'RUMORS_AI';
const FLOW_USER_ID = 'flow-annotator';
const REVIEWER_USER_ID = 'category-reviewer';
const FLOW_ID_TO_CAT_ID = [
// 0 = 中國影響力
'kj287XEBrIRcahlYvQoS',
// 1 = 性少數與愛滋病
'kz3c7XEBrIRcahlYxAp6',
// 2 = 女權與性別刻板印象
'lD3h7XEBrIRcahlYeQqS',
// 3 = 保健秘訣、食品安全
'lT3h7XEBrIRcahlYugqq',
// 4 = 基本人權問題
'lj2m7nEBrIRcahlY6Ao_',
// 5 = 農林漁牧政策
'lz2n7nEBrIRcahlYDgri',
// 6 = 能源轉型
'mD2n7nEBrIRcahlYLAr7',
// 7 = 環境生態保護
'mT2n7nEBrIRcahlYTArI',
// 8 = 優惠措施、新法規、政策宣導
'mj2n7nEBrIRcahlYdArf',
// 9 = 科技、資安、隱私
'mz2n7nEBrIRcahlYnQpz',
// 10 = 免費訊息詐騙
'nD2n7nEBrIRcahlYwQoW',
// 11 = 有意義但不包含在以上標籤
'nT2n7nEBrIRcahlY6QqF',
// 12 = 無意義
'nj2n7nEBrIRcahlY-gpc',
// 13 = 廣告
'nz2o7nEBrIRcahlYBgqQ',
// 14 = 只有網址其他資訊不足
'oD2o7nEBrIRcahlYFgpm',
// 15 = 政治、政黨
'oT2o7nEBrIRcahlYKQoM',
// 16 = 轉發協尋、捐款捐贈
'oj2o7nEBrIRcahlYRAox',
];
/**
* Process one article entry by adding article-category and add positive feedback to it
*
* @param {object} entry One article entry (parsed json file content) in ground truth
* @return {{tagCount: number; createdArticleCategoryCount: number; createdArticleCategoryFeedbackCount: number}}
*/
export async function processEntry({ id, tags }) {
let createdArticleCategoryCount = 0;
let createdArticleCategoryFeedbackCount = 0;
for (const flowId of tags) {
const categoryId = FLOW_ID_TO_CAT_ID[flowId];
try {
await createArticleCategory({
articleId: id,
categoryId,
user: {
id: FLOW_USER_ID,
appId: RUMORS_AI_APPID,
},
});
createdArticleCategoryCount += 1;
} catch (e) {
if (!e?.message?.startsWith('Cannot add articleCategory')) {
// Rethrow unexpected error
throw e;
}
// Someone else already added this category; do nothing
}
try {
await createOrUpdateArticleCategoryFeedback({
articleId: id,
categoryId,
vote: 1,
comment: '若水標記之分類',
user: {
id: REVIEWER_USER_ID,
appId: RUMORS_AI_APPID,
},
});
createdArticleCategoryFeedbackCount += 1;
} catch (e) {
if (!e?.message?.startsWith('Cannot article')) {
// Rethrow unexpected error
throw e;
}
// Someone else already added this category; do nothing
}
}
return {
tagCount: tags.length,
createdArticleCategoryCount,
createdArticleCategoryFeedbackCount,
};
}
/**
* Go through all files and process one by one
*/
async function main() {
const dir = await fs.promises.opendir(INPUT_DIRECTORY);
let idx = 0;
let createdArticleCategorySum = 0;
let createdArticleCategoryFeedbackSum = 0;
for await (const dirent of dir) {
if (!dirent.isFile()) continue;
idx += 1;
const entry = require(path.resolve(INPUT_DIRECTORY, dirent.name));
const {
createdArticleCategoryCount,
createdArticleCategoryFeedbackCount,
} = processEntry(entry);
createdArticleCategorySum += createdArticleCategoryCount;
createdArticleCategoryFeedbackSum += createdArticleCategoryFeedbackCount;
console.log(
`[${idx.toString().padStart(5)}] ${
entry.id
}\t: + ${createdArticleCategoryCount} categories & ${createdArticleCategoryFeedbackCount} feedbacks`
);
}
console.log('------');
console.log('Created article-categories: ', createdArticleCategorySum);
console.log('Created feedbacks: ', createdArticleCategoryFeedbackSum);
}
if (require.main === module) {
main().catch(console.error);
}
| JavaScript | 0 | @@ -2929,36 +2929,32 @@
%7D%0A //
-Someone else
+Reviewer
already add
@@ -2946,35 +2946,38 @@
wer already
-add
+upvnot
ed this
category; do
@@ -2964,36 +2964,98 @@
ed this
-category; do nothing
+article category (maybe during code rerun after error?).%0A // Can just ignore.
%0A %7D%0A
|
158a1e7e9dd5942465a5053a26fc92d5047ea3bd | Add features to QAS address page min/max and fixed the coutry types box not filling with data. | src/scripts/page_types/JazzeePageQASAddress.js | src/scripts/page_types/JazzeePageQASAddress.js | /**
* The JazzeePageQASAddress type
@extends JazzeePage
*/
function JazzeePageQASAddress(){}
JazzeePageQASAddress.prototype = new JazzeePage();
JazzeePageQASAddress.prototype.constructor = JazzeePageQASAddress;
/**
* Create a new RecommendersPage with good default values
* @param {String} id the id to use
* @returns {RecommendersPage}
*/
JazzeePageQASAddress.prototype.newPage = function(id,title,typeId,typeName,typeClass,status,pageBuilder){
var page = JazzeePage.prototype.newPage.call(this, id,title,typeId,typeName,typeClass,status,pageBuilder);
page.setVariable('wsdlAddress', '');
page.setVariable('validatedCountries', '');
return page;
};
JazzeePageQASAddress.prototype.workspace = function(){
JazzeePage.prototype.workspace.call(this);
$('#pageToolbar').append(this.pagePropertiesButton());
};
/**
* Create the page properties dropdown
*/
JazzeePageQASAddress.prototype.pageProperties = function(){
var div = $('<div>');
if(!this.isGlobal || this.pageBuilder.editGlobal) div.append(this.editQASVariablesButton());
return div;
};
/**
* Create the page properties dropdown
*/
JazzeePageQASAddress.prototype.editQASVariablesButton = function(){
var pageClass = this;
var obj = new FormObject();
var field = obj.newField({name: 'legend', value: 'Edit QAS Server Address'});
var element = field.newElement('TextInput', 'wsdlAddress');
element.label = 'Server Address';
element.required = true;
element.value = this.getVariable('wsdlAddress');
var element = field.newElement('TextInput', 'validatedCountries');
element.label = 'List of Countries to Validate';
element.format = 'USA,GBR';
element.instructions = 'Comma Seperated list of QAS country codes';
element.required = true;
// element.value = this.getVariable('validatedCountries');
var dialog = this.displayForm(obj);
$('form', dialog).bind('submit',function(e){
pageClass.setVariable('wsdlAddress', $('input[name="wsdlAddress"]', this).val());
pageClass.setVariable('validatedCountries', $('input[name="validatedCountries"]', this).val());
pageClass.workspace();
dialog.dialog("destroy").remove();
return false;
});//end submit
var button = $('<button>').html('Edit QAS Server Address').bind('click',function(){
$('.qtip').qtip('api').hide();
dialog.dialog('open');
}).button({
icons: {
primary: 'ui-icon-pencil'
}
});
return button;
}; | JavaScript | 0 | @@ -938,25 +938,90 @@
var
-div = $('%3Cdiv%3E');
+pageClass = this;%0A var div = $('%3Cdiv%3E');%0A%0A div.append(this.isRequiredButton());%0A
%0A i
@@ -1112,16 +1112,893 @@
ton());%0A
+ %0A var slider = $('%3Cdiv%3E');%0A slider.slider(%7B%0A value: this.min,%0A min: 0,%0A max: 20,%0A step: 1,%0A slide: function( event, ui ) %7B%0A pageClass.setProperty('min', ui.value);%0A $('#minValue').html(pageClass.min == 0?'No Minimum':pageClass.min);%0A %7D%0A %7D);%0A div.append($('%3Cp%3E').html('Minimum Answers Required ').append($('%3Cspan%3E').attr('id', 'minValue').html(this.min == 0?'No Minimum':this.min)));%0A div.append(slider);%0A%0A var slider = $('%3Cdiv%3E');%0A slider.slider(%7B%0A value: this.max,%0A min: 0,%0A max: 20,%0A step: 1,%0A slide: function( event, ui ) %7B%0A pageClass.setProperty('max', ui.value);%0A $('#maxValue').html(pageClass.max == 0?'No Maximum':pageClass.max);%0A %7D%0A %7D);%0A div.append($('%3Cp%3E').html('Maximum Answers Allowed ').append($('%3Cspan%3E').attr('id', 'maxValue').html(this.max == 0?'No Maximum':this.max)));%0A div.append(slider);%0A%0A%0A
return
@@ -2255,19 +2255,17 @@
ess'%7D);%0A
-
%0A
+
var el
@@ -2428,27 +2428,25 @@
lAddress');%0A
-
%0A
+
var elemen
@@ -2680,18 +2680,16 @@
= true;%0A
-//
elemen
@@ -2738,18 +2738,16 @@
ries');%0A
-
%0A var d
|
6066986b7d01f72fcec1fe85792dd43e5d775283 | allow jsdoc to fail silently | lib/actions/jsdoc.js | lib/actions/jsdoc.js | (function() {
'use strict';
var _ = require('lodash');
var chalk = require('chalk');
var fs = require('fs');
var path = require('path');
var Promise = require('bluebird');
var spork = require('spork');
/**
* Parse downloaded release(s) for JSDoc headers, and output markdown files with the parsed documentation.
*
* @param {object} [options] - The configuration options that specify the behavior.
* @param {*} [options.keep] - The location where the release files are kept. Defaults to the temp directory created by grm-download
* @param {boolean} [options.quiet] - Output nothing (suppress STDOUT and STDERR).
* @param {mixed} [options.verbose] - Output more information. Can be a boolean or number. true for more output; higher number (ie 2) for even more.
* @returns {bluebird Promise}
*
* @see https://developer.github.com/v3/git/tags/
* @see bluebirdjs.com/docs/api-reference.html
*/
function jsdoc(options) {
var releasesDir = options.keep || path.resolve(__dirname, './tmp');
var promises = [];
try {
var releases = fs.readdirSync(releasesDir);
} catch(err) {
return Promise.reject(err);
}
_.each(releases, function(release) {
promises.push(new Promise(function(resolve, reject) {
var args = [
releasesDir + '/' + release,
'--configure', 'jsdoc.conf.json',
'--destination', 'build/docs/' + release,
'--encoding', 'utf8',
'--recurse', true
];
spork('./node_modules/.bin/jsdoc', args, {quiet: options.quiet, verbose: (options.verbose > 1 ? options.verbose : false)})
.on('exit:code', function(code) {
if (code === 0) {
if (options.verbose) {
console.log(' -', chalk.bold.blue('[INFO]:'), 'Parsed documentation for release \'' + chalk.magenta(release) + '\'');
}
resolve();
} else {
reject(new Error('JSDoc failed'));
}
});
}));
});
if (options.verbose || !options.quiet) {
console.log(chalk.magenta('\nParsing documentation...'));
}
return Promise.all(promises).then(function() {
if (options.verbose || !options.quiet) {
console.log(chalk.magenta('Done'));
}
return options;
});
}
module.exports = jsdoc;
})();
| JavaScript | 0 | @@ -1560,86 +1560,48 @@
s, %7B
-quiet: options.quiet, verbose: (options.verbose %3E 1 ? options.
+exit: false, quiet: true,
verbose
-
: false
-)
%7D)%0A
@@ -1621,16 +1621,12 @@
n('e
-xit:code
+rror
', f
@@ -1633,20 +1633,19 @@
unction(
-code
+err
) %7B%0A
@@ -1655,31 +1655,85 @@
+
- if (code === 0
+reject(err);%0A %7D)%0A .on('exit:code', function(code
) %7B%0A
-
@@ -1761,26 +1761,24 @@
.verbose) %7B%0A
-
@@ -1910,31 +1910,27 @@
-
%7D%0A%0A
-
@@ -1946,98 +1946,8 @@
();%0A
- %7D else %7B%0A reject(new Error('JSDoc failed'));%0A %7D%0A
|
bf24ada3e5dfc798869a8988083573495617132d | use google-closure-compile instead of gcc | lib/build/js/pack.js | lib/build/js/pack.js |
module.exports = function(flow, startFn, doneFn){
var packages = flow.js.packages;
var queue = flow.files.queue;
var fconsole = flow.console;
if (flow.options.jsPack)
{
for (var i = 0, file; file = queue[i]; i++)
if (file.type == 'script' && file.htmlNode && file.outputContent)
{
fconsole.log('Init compression for ' + file.relOutputFilename);
runProcess(file, fconsole, startFn, doneFn);
}
}
else
{
fconsole.log('Skiped.')
fconsole.log('Use --js-pack or --pack to allow javascript file compess.');
}
}
module.exports.handlerName = '[js] Compress';
function runProcess(file, fconsole, startFn, doneFn){
var packStartTime = new Date;
var gcc = require('child_process').exec(
'gcc --charset UTF-8',
{
maxBuffer: 10 * 1024 * 1024
},
function(error, stdout, stderr){
fconsole.log(file.relOutputFilename + ' compressed in ' + ((new Date - packStartTime)/1000).toFixed(3) + 's');
if (stderr && stderr.length)
fconsole.log(stderr);
if (error !== null)
fconsole.log('exec error: ' + error);
else
file.outputContent = stdout.replace(/;[\r\n\s]*$/, '');
doneFn();
}
);
startFn();
gcc.stdin.write(file.outputContent);
gcc.stdin.end();
} | JavaScript | 0.000002 | @@ -773,18 +773,38 @@
%0D%0A 'g
-cc
+oogle-closure-compiler
--chars
|
0f809c87ec0a03e06d17d9d2ee2d398e751634d0 | update karma conf to run only one time as default | build/karma.conf.js | build/karma.conf.js | import webpackConfig from './webpack.config.js';
module.exports = function(config) {
config.set({
// project root
basePath: '../',
files: [{
pattern: `./test/test-bundler.js`,
watched: false,
served: true,
included: true
}
],
plugins: [
'karma-mocha',
'karma-mocha-reporter',
'karma-phantomjs-launcher',
'karma-webpack'
],
frameworks: ['mocha'],
preprocessors: {
'./test/test-bundler.js': ['webpack']
},
webpack: webpackConfig,
webpackServer: {
noInfo: true
},
reporters: ['mocha'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false,
concurrency: Infinity
})
};
| JavaScript | 0 | @@ -736,20 +736,19 @@
gleRun:
-fals
+tru
e,%0A c
|
ea0d916b50fdf7faa0534446a4bf672bedb0e344 | Convert _app.js to functional components (#10115) | examples/with-app-layout/pages/_app.js | examples/with-app-layout/pages/_app.js | import React from 'react'
import App from 'next/app'
class Layout extends React.Component {
render() {
const { children } = this.props
return <div className="layout">{children}</div>
}
}
export default class MyApp extends App {
render() {
const { Component, pageProps } = this.props
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
}
}
| JavaScript | 0.003005 | @@ -23,98 +23,25 @@
ct'%0A
-import App from 'next/app'%0A%0Aclass Layout extends React.Component %7B%0A render() %7B%0A const
+%0Aconst Layout = (
%7B ch
@@ -52,32 +52,12 @@
en %7D
+)
=
- this.props%0A return
+%3E
%3Cdi
@@ -93,22 +93,16 @@
n%7D%3C/div%3E
-%0A %7D%0A%7D
%0A%0Aexport
@@ -114,57 +114,9 @@
ult
-class MyApp extends App %7B%0A render() %7B%0A const
+(
%7B Co
@@ -139,39 +139,15 @@
ps %7D
+)
=
- this.props%0A return
+%3E
(%0A
-
%3CL
@@ -153,20 +153,16 @@
Layout%3E%0A
-
%3CCom
@@ -186,20 +186,16 @@
ops%7D /%3E%0A
-
%3C/Layo
@@ -202,16 +202,6 @@
ut%3E%0A
- )%0A %7D%0A%7D
+)
%0A
|
c7058a2a005d96afe8e26abfce3c2595deae618a | Add caching to FriendsData | src/react-chayns-personfinder/component/data/friends/FriendsData.js | src/react-chayns-personfinder/component/data/friends/FriendsData.js | class FriendsData {
#friendsList = [];
#friendsObject = {};
constructor() {
this.isFriend = this.isFriend.bind(this);
this.getFriendsList = this.getFriendsList.bind(this);
this.fetch = this.fetch.bind(this);
}
isFriend(personId) {
return this.#friendsObject[personId] || false;
}
getFriendsList() {
return this.#friendsList;
}
/* eslint-disable-next-line no-unused-vars */
async fetch(noCache = false) {
const config = {
method: 'GET',
headers: {
Authorization: `Bearer ${chayns.env.user.tobitAccessToken}`,
},
mode: 'cors',
};
const response = await fetch('https://webapi.tobit.com/AccountService/v1.0/chayns/friends', config);
if (response.status === 200) {
const json = await response.json();
this.#friendsList = json;
this.#friendsObject = {};
json.forEach((e) => {
this.#friendsObject[e.personId] = e;
});
return json;
}
this.#friendsList = [];
this.#friendsObject = {};
return [];
}
}
export default new FriendsData();
| JavaScript | 0 | @@ -1,8 +1,39 @@
+const CACHE_TIME = 10 * 1000;%0A%0A
class Fr
@@ -90,24 +90,78 @@
ject = %7B%7D;%0A%0A
+ #lastFetchTime = null;%0A%0A #activeFetch = null;%0A%0A
construc
@@ -490,86 +490,28 @@
-/* eslint-disable-next-line no-unused-vars */%0A async fetch(noCache = false)
+#fetch = async () =%3E
%7B%0A
@@ -879,154 +879,360 @@
-const json = await response.json();%0A%0A this.#friendsList = json;%0A this.#friendsObject = %7B%7D;%0A json.forEach((e) =%3E %7B
+this.#lastFetchTime = Date.now();%0A return response.json();%0A %7D%0A%0A return %5B%5D;%0A %7D;%0A%0A /* eslint-disable-next-line no-unused-vars */%0A async fetch(noCache = false) %7B%0A if (!noCache && ((this.#lastFetchTime && this.#lastFetchTime + CACHE_TIME %3C= Date.now()) %7C%7C this.#activeFetch)) %7B%0A return this.#activeFetch;
%0A
@@ -1228,32 +1228,35 @@
eFetch;%0A
+%7D%0A%0A
this.#fr
@@ -1257,91 +1257,165 @@
is.#
-friendsObject%5Be.personId%5D = e;%0A %7D);%0A%0A return json;%0A %7D%0A
+activeFetch = this.#fetch();%0A const friendsList = await this.#activeFetch;%0A%0A this.#friendsList = friendsList;%0A this.#friendsObject = %7B%7D;
%0A
@@ -1436,23 +1436,38 @@
endsList
- = %5B%5D;%0A
+.forEach((e) =%3E %7B%0A
@@ -1481,29 +1481,52 @@
riendsObject
- = %7B%7D
+%5Be.personId%5D = e;%0A %7D)
;%0A%0A r
@@ -1527,26 +1527,35 @@
return
-%5B%5D
+friendsList
;%0A %7D%0A%7D%0A%0Ae
|
27187cd15a011e67ae43ee0212c17313bbf0a0e9 | update tagline | docs/docusaurus.config.js | docs/docusaurus.config.js | const path = require('path');
const { remarkProgramOutput } = require('./plugins/program_output');
const {
rehypePlugins: themeRehypePlugins,
remarkPlugins: themeRemarkPlugins,
} = require('@rasahq/docusaurus-theme-tabula');
// FIXME: remove "next/" when releasing + remove the "next/" in
// http://github.com/RasaHQ/rasa-website/blob/master/netlify.toml
const BASE_URL = '/docs/rasa/next/';
const SITE_URL = 'https://rasa.com';
// NOTE: this allows switching between local dev instances of rasa/rasa-x
const isDev = process.env.NODE_ENV === 'development';
const SWAP_URL = isDev ? 'http://localhost:3001' : SITE_URL;
/* VERSIONING: WIP */
const routeBasePath = '/';
let versions = [];
try { versions = require('./versions.json'); } catch (ex) { console.info('no versions.json file found; assuming dev mode.') }
const legacyVersion = {
label: 'Legacy 1.x',
href: 'https://legacy-docs-v1.rasa.com',
target: '_self',
};
const allVersions = {
label: 'Versions',
to: '/', // "fake" link
position: 'left',
items: versions.length > 0 ? [
{
label: versions[0],
to: '/',
activeBaseRegex: versions[0],
},
...versions.slice(1).map((version) => ({
label: version,
to: `${version}/`,
activeBaseRegex: version,
})),
{
label: 'Master/Unreleased',
to: 'next/',
activeBaseRegex: `next`,
},
legacyVersion,
]
: [
{
label: 'Master/Unreleased',
to: '/',
activeBaseRegex: `/`,
},
legacyVersion,
],
}
module.exports = {
customFields: {
// NOTE: all non-standard options should go in this object
},
// FIXME: set this to fail in CI after launch
onBrokenLinks: 'warn',
title: 'Rasa Open Source Documentation',
tagline: 'Cras justo odio, dapibus ac facilisis in, egestas eget quam.',
url: SITE_URL,
baseUrl: BASE_URL,
favicon: '/img/favicon.ico',
organizationName: 'RasaHQ',
projectName: 'rasa',
themeConfig: {
colorMode: {
defaultMode: 'light',
disableSwitch: true,
},
navbar: {
hideOnScroll: false,
title: 'Rasa Open Source',
logo: {
alt: 'Rasa Logo',
src: `/img/rasa-logo.svg`,
href: SITE_URL,
},
items: [
{
label: 'Rasa Open Source',
to: path.join('/', BASE_URL),
position: 'left',
},
{
label: 'Rasa X',
position: 'left',
href: `${SWAP_URL}/docs/rasa-x/next/`,
target: '_self',
},
{
target: '_self',
href: 'http://blog.rasa.com/',
label: 'Blog',
position: 'right',
},
{
target: '_self',
href: `${SITE_URL}/community/join/`,
label: 'Community',
position: 'right',
},
],
},
footer: {
copyright: `Copyright © ${new Date().getFullYear()} Rasa Technologies GmbH`,
},
gtm: {
containerID: 'GTM-PK448GB',
},
},
themes: [
'@rasahq/docusaurus-theme-tabula',
path.resolve(__dirname, './themes/theme-custom')
],
plugins: [
['@docusaurus/plugin-content-docs/', {
routeBasePath,
sidebarPath: require.resolve('./sidebars.js'),
editUrl: 'https://github.com/rasahq/rasa/edit/master/docs/',
showLastUpdateTime: true,
showLastUpdateAuthor: true,
rehypePlugins: [
...themeRehypePlugins,
],
remarkPlugins: [
...themeRemarkPlugins,
remarkProgramOutput,
],
}],
['@docusaurus/plugin-content-pages', {}],
['@docusaurus/plugin-sitemap',
{
cacheTime: 600 * 1000, // 600 sec - cache purge period
changefreq: 'weekly',
priority: 0.5,
}],
isDev && ['@docusaurus/plugin-debug', {}],
[path.resolve(__dirname, './plugins/google-tagmanager'), {}],
].filter(Boolean),
};
| JavaScript | 0.000011 | @@ -1751,68 +1751,98 @@
e: '
-Cras justo odio, dapibus ac facilisis in, egestas eget quam.
+An open source machine learning framework for automated text and voice-based conversations
',%0A
|
ae4702d1eed8b650227eca9efa28d4750641c7ed | remove explicit proptype passing | RNPublisherBanner.js | RNPublisherBanner.js | import React, { Component } from 'react';
import {
NativeModules,
requireNativeComponent,
View,
NativeEventEmitter,
Platform,
UIManager,
findNodeHandle,
} from 'react-native';
class PublisherBanner extends Component {
constructor() {
super();
this.handleSizeChange = this.handleSizeChange.bind(this);
this.handleAdmobDispatchAppEvent = this.handleAdmobDispatchAppEvent.bind(this);
this.handleDidFailToReceiveAdWithError = this.handleDidFailToReceiveAdWithError.bind(this);
this.state = {
style: {},
};
}
componentDidMount() {
this.loadBanner();
}
loadBanner() {
UIManager.dispatchViewManagerCommand(
findNodeHandle(this._bannerView),
UIManager.RNAdMobDFP.Commands.loadBanner,
null,
);
}
handleSizeChange(event) {
const { height, width } = event.nativeEvent;
this.setState({ style: { width, height } });
if (this.props.onSizeChange) {
this.props.onSizeChange({ width, height });
}
}
handleAdmobDispatchAppEvent(event) {
if (this.props.onAdmobDispatchAppEvent) {
const { name, info } = event.nativeEvent;
this.props.onAdmobDispatchAppEvent({ name, info });
}
}
handleDidFailToReceiveAdWithError(event) {
if (this.props.onDidFailToReceiveAdWithError) {
this.props.onDidFailToReceiveAdWithError(event.nativeEvent.error);
}
}
render() {
return (
<RNAdMobDFP
{...this.props}
style={[this.props.style, this.state.style]}
onSizeChange={this.handleSizeChange}
onAdViewDidReceiveAd={this.props.onAdViewDidReceiveAd}
onDidFailToReceiveAdWithError={this.handleDidFailToReceiveAdWithError}
onAdViewWillPresentScreen={this.props.onAdViewWillPresentScreen}
onAdViewWillDismissScreen={this.props.onAdViewWillDismissScreen}
onAdViewDidDismissScreen={this.props.onAdViewDidDismissScreen}
onAdViewWillLeaveApplication={this.props.onAdViewWillLeaveApplication}
onAdmobDispatchAppEvent={this.handleAdmobDispatchAppEvent}
testDevices={this.props.testDevices}
adUnitID={this.props.adUnitID}
validAdSizes={this.props.validAdSizes}
adSize={this.props.adSize}
ref={el => (this._bannerView = el)}
/>
);
}
}
PublisherBanner.simulatorId = Platform.OS === 'android' ? 'EMULATOR' : NativeModules.RNAdMobDFPManager.simulatorId;
PublisherBanner.propTypes = {
...View.propTypes,
/**
* AdMob iOS library banner size constants
* (https://developers.google.com/admob/ios/banner)
* banner (320x50, Standard Banner for Phones and Tablets)
* largeBanner (320x100, Large Banner for Phones and Tablets)
* mediumRectangle (300x250, IAB Medium Rectangle for Phones and Tablets)
* fullBanner (468x60, IAB Full-Size Banner for Tablets)
* leaderboard (728x90, IAB Leaderboard for Tablets)
* smartBannerPortrait (Screen width x 32|50|90, Smart Banner for Phones and Tablets)
* smartBannerLandscape (Screen width x 32|50|90, Smart Banner for Phones and Tablets)
*
* banner is default
*/
adSize: React.PropTypes.string,
/**
* Optional array specifying all valid sizes that are appropriate for this slot.
*/
validAdSizes: React.PropTypes.arrayOf(React.PropTypes.string),
/**
* AdMob ad unit ID
*/
adUnitID: React.PropTypes.string,
/**
* Test device ID
*/
testDevices: React.PropTypes.arrayOf(React.PropTypes.string),
/**
* AdMob iOS library events
*/
onSizeChange: React.PropTypes.func,
onAdViewDidReceiveAd: React.PropTypes.func,
onDidFailToReceiveAdWithError: React.PropTypes.func,
onAdViewWillPresentScreen: React.PropTypes.func,
onAdViewWillDismissScreen: React.PropTypes.func,
onAdViewDidDismissScreen: React.PropTypes.func,
onAdViewWillLeaveApplication: React.PropTypes.func,
onAdmobDispatchAppEvent: React.PropTypes.func,
};
PublisherBanner.defaultProps = {
};
const RNAdMobDFP = requireNativeComponent('RNAdMobDFP', PublisherBanner, {
nativeOnly: {
onSizeChange: true,
onDidFailToReceiveAdWithError: true,
onAdmobDispatchAppEvent: true,
},
});
export default PublisherBanner;
| JavaScript | 0 | @@ -1546,71 +1546,8 @@
ge%7D%0A
- onAdViewDidReceiveAd=%7Bthis.props.onAdViewDidReceiveAd%7D%0A
@@ -1637,523 +1637,61 @@
onAd
-ViewWillPresentScreen=%7Bthis.props.onAdViewWillPresentScreen%7D%0A onAdViewWillDismissScreen=%7Bthis.props.onAdViewWillDismissScreen%7D%0A onAdViewDidDismissScreen=%7Bthis.props.onAdViewDidDismissScreen%7D%0A onAdViewWillLeaveApplication=%7Bthis.props.onAdViewWillLeaveApplication%7D%0A onAdmobDispatchAppEvent=%7Bthis.handleAdmobDispatchAppEvent%7D%0A testDevices=%7Bthis.props.testDevices%7D%0A adUnitID=%7Bthis.props.adUnitID%7D%0A validAdSizes=%7Bthis.props.validAdSizes%7D%0A adSize=%7Bthis.props.adSize
+mobDispatchAppEvent=%7Bthis.handleAdmobDispatchAppEvent
%7D%0A
@@ -2837,22 +2837,80 @@
*
-Test device ID
+Array of test devices. Use PublisherBanner.simulatorId for the simulator
%0A
@@ -3529,134 +3529,8 @@
nner
-, %7B%0A nativeOnly: %7B%0A onSizeChange: true,%0A onDidFailToReceiveAdWithError: true,%0A onAdmobDispatchAppEvent: true,%0A %7D,%0A%7D
);%0A%0A
|
850b0a85aa4ec454807981a207126023c092ab63 | Handle empty section.bendPoints (#84) | built/drawModule.js | built/drawModule.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var elkGraph_1 = require("./elkGraph");
var Skin_1 = require("./Skin");
var _ = require("lodash");
var onml = require("onml");
var WireDirection;
(function (WireDirection) {
WireDirection[WireDirection["Up"] = 0] = "Up";
WireDirection[WireDirection["Down"] = 1] = "Down";
WireDirection[WireDirection["Left"] = 2] = "Left";
WireDirection[WireDirection["Right"] = 3] = "Right";
})(WireDirection || (WireDirection = {}));
function drawModule(g, module) {
var nodes = module.nodes.map(function (n) {
var kchild = _.find(g.children, function (c) { return c.id === n.Key; });
return n.render(kchild);
});
removeDummyEdges(g);
var lines = _.flatMap(g.edges, function (e) {
var netId = elkGraph_1.ElkModel.wireNameLookup[e.id];
var netName = 'net_' + netId.slice(1, netId.length - 1);
return _.flatMap(e.sections, function (s) {
var startPoint = s.startPoint;
s.bendPoints = s.bendPoints || [];
var bends = s.bendPoints.map(function (b) {
var l = ['line', {
x1: startPoint.x,
x2: b.x,
y1: startPoint.y,
y2: b.y,
class: netName,
}];
startPoint = b;
return l;
});
if (e.junctionPoints) {
var circles = e.junctionPoints.map(function (j) {
return ['circle', {
cx: j.x,
cy: j.y,
r: 2,
style: 'fill:#000',
class: netName,
}];
});
bends = bends.concat(circles);
}
var line = [['line', {
x1: startPoint.x,
x2: s.endPoint.x,
y1: startPoint.y,
y2: s.endPoint.y,
class: netName,
}]];
return bends.concat(line);
});
});
var svgAttrs = Skin_1.default.skin[1];
svgAttrs.width = g.width.toString();
svgAttrs.height = g.height.toString();
var styles = ['style', {}, ''];
onml.t(Skin_1.default.skin, {
enter: function (node) {
if (node.name === 'style') {
styles[2] += node.full[2];
}
},
});
var elements = [styles].concat(nodes, lines);
var ret = ['svg', svgAttrs].concat(elements);
return onml.s(ret);
}
exports.default = drawModule;
function which_dir(start, end) {
if (end.x === start.x && end.y === start.y) {
throw new Error('start and end are the same');
}
if (end.x !== start.x && end.y !== start.y) {
throw new Error('start and end arent orthogonal');
}
if (end.x > start.x) {
return WireDirection.Right;
}
if (end.x < start.x) {
return WireDirection.Left;
}
if (end.y > start.y) {
return WireDirection.Down;
}
if (end.y < start.y) {
return WireDirection.Up;
}
throw new Error('unexpected direction');
}
function findBendNearDummy(net, dummyIsSource, dummyLoc) {
var candidates = net.map(function (edge) {
var bends = edge.sections[0].bendPoints || [null];
if (dummyIsSource) {
return _.first(bends);
}
else {
return _.last(bends);
}
}).filter(function (p) { return p !== null; });
return _.minBy(candidates, function (pt) {
return Math.abs(dummyLoc.x - pt.x) + Math.abs(dummyLoc.y - pt.y);
});
}
function removeDummyEdges(g) {
// go through each edge group for each dummy
var dummyNum = 0;
var _loop_1 = function () {
var dummyId = '$d_' + String(dummyNum);
// find all edges connected to this dummy
var edgeGroup = _.filter(g.edges, function (e) {
return e.source === dummyId || e.target === dummyId;
});
if (edgeGroup.length === 0) {
return "break";
}
var dummyIsSource;
var dummyLoc = void 0;
var firstEdge = edgeGroup[0];
if (firstEdge.source === dummyId) {
dummyIsSource = true;
dummyLoc = firstEdge.sections[0].startPoint;
}
else {
dummyIsSource = false;
dummyLoc = firstEdge.sections[0].endPoint;
}
var newEnd = findBendNearDummy(edgeGroup, dummyIsSource, dummyLoc);
for (var _i = 0, edgeGroup_1 = edgeGroup; _i < edgeGroup_1.length; _i++) {
var edge = edgeGroup_1[_i];
var e = edge;
var section = e.sections[0];
if (dummyIsSource) {
section.startPoint = newEnd;
if (section.bendPoints) {
section.bendPoints.shift();
}
}
else {
section.endPoint = newEnd;
if (section.bendPoints) {
section.bendPoints.pop();
}
}
}
// delete junction point if necessary
var directions = new Set(_.flatMap(edgeGroup, function (edge) {
var section = edge.sections[0];
if (dummyIsSource) {
// get first bend or endPoint
if (section.bendPoints) {
return [section.bendPoints[0]];
}
return section.endPoint;
}
else {
if (section.bendPoints) {
return [_.last(section.bendPoints)];
}
return section.startPoint;
}
}).map(function (pt) {
if (pt.x > newEnd.x) {
return WireDirection.Right;
}
if (pt.x < newEnd.x) {
return WireDirection.Left;
}
if (pt.y > newEnd.y) {
return WireDirection.Down;
}
return WireDirection.Up;
}));
if (directions.size < 3) {
// remove junctions at newEnd
edgeGroup.forEach(function (edge) {
if (edge.junctionPoints) {
edge.junctionPoints = edge.junctionPoints.filter(function (junct) {
return !_.isEqual(junct, newEnd);
});
}
});
}
dummyNum += 1;
};
// loop until we can't find an edge group or we hit 10,000
while (dummyNum < 10000) {
var state_1 = _loop_1();
if (state_1 === "break")
break;
}
}
exports.removeDummyEdges = removeDummyEdges;
| JavaScript | 0 | @@ -5498,32 +5498,65 @@
ction.bendPoints
+ && section.bendPoints.length %3E 0
) %7B%0A
@@ -5717,32 +5717,65 @@
ction.bendPoints
+ && section.bendPoints.length %3E 0
) %7B%0A
|
a9247e8d5565a34fbc487d421f8fe298b522d855 | localize gathering dates | lib/depject/message/html/render/gathering.js | lib/depject/message/html/render/gathering.js | const { h, computed, when, map, send } = require('mutant')
const nest = require('depnest')
const extend = require('xtend')
const moment = require('moment-timezone')
const localTimezone = moment.tz.guess()
exports.needs = nest({
'message.html.markdown': 'first',
'message.html.layout': 'first',
'message.html.decorate': 'reduce',
'message.async.publish': 'first',
'keys.sync.id': 'first',
'about.html.image': 'first',
'about.obs.latestValue': 'first',
'about.obs.socialValues': 'first',
'about.obs.valueFrom': 'first',
'about.obs.name': 'first',
'contact.obs.following': 'first',
'blob.sync.url': 'first',
'gathering.sheet.edit': 'first'
})
exports.gives = nest('message.html', {
canRender: true,
render: true
})
exports.create = function (api) {
let following = null
return nest('message.html', {
canRender: isRenderable,
render: function (msg, opts) {
if (!isRenderable(msg)) return
const yourId = api.keys.sync.id()
// passed in from sbot/public-feed/roots
const suppliedGathering = msg.gathering || {}
// allow override of resolved about messages for preview in modules/gathering/sheet/edit.js
const about = msg.key ? extend({
hidden: api.about.obs.valueFrom(msg.key, 'hidden', yourId),
image: suppliedGathering.image || api.about.obs.latestValue(msg.key, 'image'),
title: suppliedGathering.title || api.about.obs.latestValue(msg.key, 'title'),
description: suppliedGathering.description || api.about.obs.latestValue(msg.key, 'description'),
location: suppliedGathering.location || api.about.obs.latestValue(msg.key, 'location'),
startDateTime: suppliedGathering.startDateTime || api.about.obs.latestValue(msg.key, 'startDateTime')
}, msg.previewAbout) : msg.previewAbout
const attendees = msg.key ? computed([api.about.obs.socialValues(msg.key, 'attendee')], getAttendees) : []
const disableActions = !!msg.previewAbout
const attending = computed([attendees, yourId], (attendees, yourId) => attendees.includes(yourId))
if (!following) {
following = api.contact.obs.following(yourId)
}
const imageUrl = computed(about.image, (id) => api.blob.sync.url(id))
const imageId = computed(about.image, (link) => (link && link.link) || link)
const content = h('GatheringCard', [
h('div.title', [
h('a', {
href: msg.key
}, about.title),
h('button', {
disabled: disableActions,
'ev-click': send(api.gathering.sheet.edit, msg.key)
}, 'Edit Details')
]),
h('div.time', computed(about.startDateTime, formatTime)),
when(about.image, h('a.image', {
href: imageId,
style: {
'background-image': computed(imageUrl, (url) => `url(${url})`)
}
})),
h('div.attending', [
h('div.title', ['Attendees', ' (', computed([attendees], (x) => x.length), ')']),
h('div.attendees', [
map(attendees, (attendee) => {
return h('a.attendee', {
href: attendee,
title: nameAndFollowWarning(attendee)
}, api.about.html.image(attendee))
})
]),
h('div.actions', [
h('button -attend', {
disabled: computed([attending, disableActions], (...args) => args.some(Boolean)),
'ev-click': send(publishAttending, msg)
}, 'Attending'),
h('button -attend', {
disabled: disableActions,
'ev-click': send(publishNotAttending, msg)
}, 'Can\'t Attend')
])
]),
h('div.location', markdown(about.location)),
when(about.description, h('div.description', markdown(about.description)))
])
const editPreview = msg.previewAbout && msg.key
const element = api.message.html.layout(msg, extend({
content,
miniContent: editPreview ? 'Edited a gathering' : 'Added a gathering',
actions: !msg.previewAbout,
layout: 'mini'
}, opts))
return api.message.html.decorate(element, {
msg
})
}
})
function publishAttending (msg) {
const yourId = api.keys.sync.id()
const content = {
type: 'about',
about: msg.key,
attendee: {
link: yourId
}
}
// what starts in private, stays in private!
if (msg.value.content.recps) {
content.recps = msg.value.content.recps
}
// publish with confirm
api.message.async.publish(content)
}
function publishNotAttending (msg) {
const yourId = api.keys.sync.id()
const content = {
type: 'about',
about: msg.key,
attendee: {
link: yourId,
remove: true
}
}
// what starts in private, stays in private!
if (msg.value.content.recps) {
content.recps = msg.value.content.recps
}
// publish with confirm
api.message.async.publish(content)
}
function nameAndFollowWarning (id) {
const yourId = api.keys.sync.id()
return computed([api.about.obs.name(id), id, following], function nameAndFollowWarning (name, id, following) {
if (id === yourId) {
return `${name} (you)`
} else if (following.includes(id)) {
return `${name}`
} else {
return `${name} (not following)`
}
})
}
function markdown (obs) {
return computed(obs, (text) => {
if (typeof text === 'string') return api.message.html.markdown(text)
})
}
}
function formatTime (time) {
if (time && time.epoch) {
return moment(time.epoch).tz(localTimezone).format('LLLL zz')
}
}
function getAttendees (lookup) {
return Object.keys(lookup)
}
function isRenderable (msg) {
return (msg.value.content.type === 'gathering') ? true : undefined
}
| JavaScript | 0.999985 | @@ -198,16 +198,51 @@
.guess()
+%0Amoment.locale(navigator.languages)
%0A%0Aexport
|
cb370e544fbf2be6155a8b13d87e5f03cbed516c | Update concourse browser plugin for new version. | concourse/chrome_plugin/src/inject.user.js | concourse/chrome_plugin/src/inject.user.js | // ==UserScript==
// @name Remove concourse elements
// @namespace cloudpipeline.digital
// @description Strips away some of the cruft from the concourse pipeline view when showing it on monitoring screens.
// @include https://deployer.*.cloudpipeline.digital/*
// @include https://deployer.cloud.service.gov.uk/*
// @version 1
// @grant none
// ==/UserScript==
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
console.log("Monitor mode is go");
var element = document.getElementsByClassName("legend")[0];
element.parentNode.removeChild(element);
var element = document.getElementById("cli-downloads");
element.parentNode.removeChild(element);
var hostname = location.hostname.replace("deployer.", "").replace(".cloudpipeline.digital","")
var element = document.getElementsByTagName("nav")[0];
element.innerHTML = " <font size=5>" + hostname + "</font>";
}
}, 10);
| JavaScript | 0 | @@ -738,29 +738,43 @@
ment
+s
By
-Id(%22cli-downloads%22)
+ClassName(%22lower-right-info%22)%5B0%5D
;%0A
|
2d593501b4382816807db394c4ad98b5a2c9c1ae | Remove linter warning | lib/platforms/alexaSkill/gadgetController.js | lib/platforms/alexaSkill/gadgetController.js | 'use strict';
const _ = require('lodash');
/**
* Class GadgetController
*/
class GadgetController {
/**
* Constructor
* @param {Jovo} jovo
*/
constructor(jovo) {
this.response = jovo.alexaSkill().getResponse();
}
/**
* Sets animations
* @param {array} animationArray
* @return {GadgetController}
*/
setAnimations(animationArray) {
this.animations = this.animations || [];
_.forEach(animationArray, (animation) => {
if (animation instanceof AnimationsBuilder) {
this.animations.push(animation.build());
} else {
this.animations.push(animation);
}
});
return this;
}
/**
* Sets triggerEvent to buttonDown
* @return {GadgetController}
*/
setButtonDownTriggerEvent() {
this.triggerEvent = 'buttonDown';
return this;
}
/**
* Sets triggerEvent to buttonUp
* @return {GadgetController}
*/
setButtonUpTriggerEvent() {
this.triggerEvent = 'buttonUp';
return this;
}
/**
* Sets triggerEvent to none
* @return {GadgetController}
*/
setNoneTriggerEvent() {
this.triggerEvent = 'none';
return this;
}
/**
* Checks if triggerEvent is one of the possible values
* Throws error if not
* @param {string} triggerEvent Either 'buttonDown', 'buttonUp' or 'none'
* @return {GadgetController}
*/
setTriggerEvent(triggerEvent) {
let possibleTriggerEventValues = ['buttonDown', 'buttonUp', 'none'];
if (possibleTriggerEventValues.indexOf(triggerEvent) === -1) {
throw new Error('report has to be either \'buttonDown\', \'buttonUp\' or \'none\'');
}
this.triggerEvent = triggerEvent;
return this;
}
/**
* Gets AnimationsBuilder instance
* @return {AnimationsBuilder}
*/
getAnimationsBuilder() {
return new AnimationsBuilder();
}
/**
* Gets SequenceBuilder instance
* @return {SequenceBuilder}
*/
getSequenceBuilder() {
return new SequenceBuilder();
}
/**
* Sends GadgetController.StartInputHandler directive
* @param {array} targetGadgets ids that will receive the command
* @param {number} triggerEventTimeMs delay in milliseconds. Minimum: 0. Maximum: 65,535.
* @param {string} triggerEvent Either 'buttonDown', 'buttonUp' or 'none'
* @param {array} animations one or more animations.
*/
setLight(targetGadgets, triggerEventTimeMs, triggerEvent, animations) {
if (triggerEvent && animations) {
this.setTriggerEvent(triggerEvent).setAnimations(animations);
}
this.response.addDirective({
type: 'GadgetController.SetLight',
version: 1,
targetGadgets,
parameters: {
triggerEvent: this.triggerEvent,
triggerEventTimeMs,
animations: this.animations,
},
});
}
}
/**
* Class AnimationsBuilder
*/
class AnimationsBuilder {
/**
* Constructor
*/
constructor() {
this.animation = {};
}
/**
* Sets repeat
* @param {number} repeat number of times to play this animation. Minimum: 0. Maximum: 255.
* @return {AnimationsBuilder}
*/
repeat(repeat) {
this.animation.repeat = repeat;
return this;
}
/**
* Sets targetLights
* @param {array} targetLights
* @return {AnimationsBuilder}
*/
targetLights(targetLights) {
this.animation.targetLights = targetLights;
return this;
}
/**
* Sets sequence
* @param {array} sequence steps to render in order
* @return {AnimationsBuilder}
*/
sequence(sequence) {
this.animation.sequence = this.animation.sequence || [];
_.map(sequence, (item) => {
if (item instanceof SequenceBuilder) {
this.animation.sequence.push(item.build());
}
this.animation.sequence.push(item);
});
return this;
}
/**
* Returns events object
* @public
* @return {object}
*/
build() {
return this.animation;
}
}
/**
* Class SequenceBuilder
*/
class SequenceBuilder {
/**
* Constructor
*/
constructor() {
this.sequence = {};
}
/**
* Sets durationMs
* @param {number} durationMs in milliseconds to render this step. Minimum: 1. Maximum: 65,535.
* @return {SequenceBuilder}
*/
duration(durationMs) {
this.sequence.durationMs = durationMs;
return this;
}
/**
* Sets color
* @param {string} color
* @return {SequenceBuilder}
*/
color(color) {
this.sequence.color = color;
return this;
}
/**
* Sets blend
* @param {boolean} blend
* @return {SequenceBuilder}
*/
blend(blend) {
this.sequence.blend = blend;
return this;
}
/**
* Returns events object
* @public
* @return {object}
*/
build() {
return this.sequence;
}
}
module.exports.GadgetController = GadgetController;
| JavaScript | 0 | @@ -1858,17 +1858,16 @@
n this;%0A
-%0A
%7D%0A%0A
|
2a1cf8d00952c0e567f42ee7604a932eeafd1971 | Update Frig valueLink From Hue Slider | src/javascripts/components/color/hue_slider.js | src/javascripts/components/color/hue_slider.js | let React = require("react")
let draggable = require('./higher_order_components/draggable')
let {div} = React.DOM
@draggable
export default class extends React.Component {
static defaultProps = Object.assign(require("../../default_props.js"))
_updatePosition(clientX, clientY) {
let rect = React.findDOMNode(this).getBoundingClientRect()
let value = this.getScaledValue((rect.bottom - clientY) / rect.height)
this.props.valueLink.requestChange(value)
}
render() {
return div({
className: "slider vertical",
onMouseDown: this.startUpdates.bind(this),
onTouchStart: this.startUpdates.bind(this),
},
div({
className: "track",
}),
div({
className: "pointer",
style: {
"bottom": this.getPercentageValue(this.props.valueLink.value),
},
})
)
}
} | JavaScript | 0 | @@ -22,16 +22,43 @@
react%22)%0A
+let Colr = require('colr')%0A
let drag
@@ -289,26 +289,26 @@
ion(
-clientX, clientY)
+saturation, value)
%7B%0A
@@ -376,19 +376,17 @@
let
-val
+h
ue = thi
@@ -421,15 +421,13 @@
m -
-clientY
+value
) /
@@ -438,16 +438,69 @@
.height)
+%0A let color = Colr.fromHsv(hue, saturation, value)
%0A%0A th
@@ -532,21 +532,29 @@
tChange(
-value
+color.toHex()
)%0A %7D%0A%0A
@@ -565,16 +565,47 @@
der() %7B%0A
+ let %5Bhsv%5D = this.getHSV()%0A%0A
retu
@@ -934,34 +934,13 @@
lue(
-this.props.valueLink.value
+hsv.h
),%0A
|
f59383039d140378eca16ca44884ac52d2dfb5b9 | add repl to example | examples/basic.js | examples/basic.js | var arDrone = require('ar-drone');
var client = arDrone.createClient();
// make sure the client always calls disableEmergency() before taking off
var takeoff = client.takeoff;
client.takeoff = function (value) {
this.disableEmergency();
takeoff.call(this, value);
};
var cmds = [
'stop'
, 'takeoff'
, 'land'
, 'up'
, 'down'
, 'clockwise'
, 'counterClockwise'
, 'front'
, 'back'
, 'left'
, 'right'
, 'animate'
, 'animateLeds'
];
// basic example. Drone can hook in here (event triggers command)
var controller = require('../leap-remote');
// iterate over all the commands and bind them to the event listeners
cmds.forEach(function (cmd) {
controller.on(cmd, function (value) {
console.log(cmd, value);
client[cmd](value);
});
});
// once everything is ready, start the controller
controller.start();
| JavaScript | 0 | @@ -266,16 +266,63 @@
e);%0A%7D;%0A%0A
+// repl for emergency...%0Aclient.createRepl();%0A%0A
var cmds
@@ -476,16 +476,17 @@
eds'%0A%5D;%0A
+%0A
// basic
|
3449aa08e35c252a83a5c96629f26a383dc73191 | Refactor iconv example | examples/iconv.js | examples/iconv.js | /**
* Tips
* ====
* - Set `user-agent` and `accept` headers when sending requests. Some services will not respond as expected without them.
* - Set `pool` to false if you send lots of requests using "request" library.
*/
var request = require('request')
, FeedParser = require(__dirname+'/..')
, Iconv = require('iconv').Iconv;
function fetch(feed) {
// Define our streams
var req = request(feed, {timeout: 10000, pool: false});
req.setMaxListeners(50);
// Some feeds do not respond without user-agent and accept headers.
req.setHeader('user-agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36')
.setHeader('accept', 'text/html,application/xhtml+xml');
var feedparser = new FeedParser();
// Define our handlers
req.on('error', done);
req.on('response', function(res) {
var stream = this
, iconv
, charset;
if (res.statusCode != 200) return this.emit('error', new Error('Bad status code'));
charset = getParams(res.headers['content-type'] || '').charset;
// Use iconv if its not utf8 already.
if (!iconv && charset && !/utf-*8/i.test(charset)) {
try {
iconv = new Iconv(charset, 'utf-8');
console.log('Converting from charset %s to utf-8', charset);
iconv.on('error', done);
// If we're using iconv, stream will be the output of iconv
// otherwise it will remain the output of request
stream = this.pipe(iconv);
} catch(err) {
this.emit('error', err);
}
}
// And boom goes the dynamite
stream.pipe(feedparser);
});
feedparser.on('error', done);
feedparser.on('end', done);
feedparser.on('readable', function() {
var post;
while (post = this.read()) {
console.log(post);
}
});
}
function getParams(str) {
var params = str.split(';').reduce(function (params, param) {
var parts = param.split('=').map(function (part) { return part.trim(); });
if (parts.length === 2) {
params[parts[0]] = parts[1];
}
return params;
}, {});
return params;
}
function done(err) {
if (err) {
console.log(err, err.stack);
return process.exit(1);
}
server.close();
process.exit();
}
// Don't worry about this. It's just a localhost file server so you can be
// certain the "remote" feed is available when you run this example.
var server = require('http').createServer(function (req, res) {
var stream = require('fs').createReadStream(require('path').resolve(__dirname, '../test/feeds' + req.url));
res.setHeader('Content-Type', 'text/xml; charset=Windows-1251');
stream.pipe(res);
});
server.listen(0, function () {
fetch('http://localhost:' + this.address().port + '/iconv.xml');
});
| JavaScript | 0 | @@ -879,62 +879,8 @@
) %7B%0A
- var stream = this%0A , iconv%0A , charset;%0A%0A
@@ -963,21 +963,24 @@
ode'));%0A
-%0A
+var
charset
@@ -1039,496 +1039,47 @@
et;%0A
-%0A
-// Use iconv if its not utf8 already.%0A if (!iconv && charset && !/utf-*8/i.test(charset)) %7B%0A try %7B%0A iconv = new Iconv(charset, 'utf-8');%0A console.log('Converting from charset %25s to utf-8', charset);%0A iconv.on('error', done);%0A // If we're using iconv, stream will be the output of iconv%0A // otherwise it will remain the output of request%0A stream = this.pipe(iconv);%0A %7D catch(err) %7B%0A this.emit('error', err);%0A %7D%0A %7D%0A
+res = maybeTranslate(res, charset);
%0A
@@ -1113,22 +1113,19 @@
ite%0A
-stream
+res
.pipe(fe
@@ -1323,16 +1323,16 @@
;%0A %7D%0A
-
%7D);%0A%7D%0A
@@ -1328,24 +1328,551 @@
%7D%0A %7D);%0A%7D%0A%0A
+function maybeTranslate (res, charset) %7B%0A var iconv;%0A // Use iconv if its not utf8 already.%0A if (!iconv && charset && !/utf-*8/i.test(charset)) %7B%0A try %7B%0A iconv = new Iconv(charset, 'utf-8');%0A console.log('Converting from charset %25s to utf-8', charset);%0A iconv.on('error', done);%0A // If we're using iconv, stream will be the output of iconv%0A // otherwise it will remain the output of request%0A res = res.pipe(iconv);%0A %7D catch(err) %7B%0A res.emit('error', err);%0A %7D%0A %7D%0A return res;%0A%7D%0A%0A
function get
|
c90c472868aa7cdc8c55d05daf82a4e7fd6dbd55 | Add an update listener to update the preview area | examples/index.js | examples/index.js | import InfiniteTree from '../src';
import rowRenderer from './renderer';
import '../src/index.styl';
const data = [];
const source = '{"id":"<root>","label":"<root>","children":[{"id":"alpha","label":"Alpha"},{"id":"bravo","label":"Bravo","children":[{"id":"charlie","label":"Charlie","children":[{"id":"delta","label":"Delta","children":[{"id":"echo","label":"Echo"},{"id":"foxtrot","label":"Foxtrot"}]},{"id":"golf","label":"Golf"}]},{"id":"hotel","label":"Hotel","children":[{"id":"india","label":"India","children":[{"id":"juliet","label":"Juliet"}]}]},{"id":"kilo","label":"Kilo"}]}]}';
for (let i = 0; i < 1000; ++i) {
data.push(JSON.parse(source.replace(/"(id|label)":"([^"]*)"/g, '"$1": "$2.' + i + '"')));
}
const tree = new InfiniteTree({
autoOpen: true,
el: document.querySelector('#tree'),
rowRenderer: rowRenderer
});
tree.on('scrollProgress', (progress) => {
document.querySelector('#scrolling-progress').style = 'width: ' + progress + '%';
});
tree.on('openNode', (node) => {
console.log('openNode', node);
});
tree.on('closeNode', (node) => {
console.log('closeNode', node);
});
tree.on('selectNode', (node) => {
const el = document.querySelector('#preview');
if (node) {
el.innerHTML = JSON.stringify({
id: node.id,
label: node.label,
children: node.children ? node.children.length : 0,
parent: node.parent ? node.parent.id : null,
state: node.state
}, null, 2);
} else {
el.innerHTML = '';
}
});
tree.loadData(data);
window.tree = tree;
| JavaScript | 0 | @@ -848,306 +848,29 @@
);%0A%0A
-tree.on('scrollProgress', (progress) =%3E %7B%0A document.querySelector('#scrolling-progress').style = 'width: ' + progress + '%25';%0A%7D);%0A%0Atree.on('openNode', (node) =%3E %7B%0A console.log('openNode', node);%0A%7D);%0Atree.on('closeNode', (node) =%3E %7B%0A console.log('closeNode', node);%0A%7D);%0Atree.on('selectNode',
+const updatePreview =
(no
@@ -929,17 +929,16 @@
view');%0A
-%0A
if (
@@ -1257,14 +1257,449 @@
'';%0A
-
%7D%0A
+%7D;%0A%0Atree.on('scrollProgress', (progress) =%3E %7B%0A document.querySelector('#scrolling-progress').style = 'width: ' + progress + '%25';%0A%7D);%0Atree.on('update', () =%3E %7B%0A const node = tree.getSelectedNode();%0A updatePreview(node);%0A%7D);%0Atree.on('openNode', (node) =%3E %7B%0A console.log('openNode', node);%0A%7D);%0Atree.on('closeNode', (node) =%3E %7B%0A console.log('closeNode', node);%0A%7D);%0Atree.on('selectNode', (node) =%3E %7B%0A updatePreview(node);%0A
%7D);%0A
|
3364a844891b29e58fa463e370aa6b1989d10b3d | Remove the comment-out lines | MZ-700/client.js | MZ-700/client.js | window.jQuery = require("jquery");
(function($) {
require("jquery-ui");
require("fullscrn");
var MZ700Js = require("./index.js");
var dock_n_liquid = require("dock-n-liquid");
var BBox = require("b-box");
var container = $(".MZ-700-body");
var screen = container.find(".screen");
var resizeScreen = function() {
var bboxContainer = new BBox(container.get(0));
var bboxScreen = new BBox(screen.get(0));
var containerSize = bboxContainer.getSize();
containerSize._h -= bboxScreen.px("border-top-width");
containerSize._h -= bboxScreen.px("border-bottom-width");
var orgSize = new BBox.Size(320,200);
var innerSize = containerSize.getMaxInscribedSize(orgSize);
var margin = new BBox.Size(
(containerSize._w - innerSize._w) / 2,
(containerSize._h - innerSize._h) / 2);
screen
.css("margin-left", margin._w + "px")
.css("margin-top", margin._h + "px")
.css("width", innerSize._w + "px")
.css("height", innerSize._h + "px");
};
var liquidRootElement = $("#liquid-panel-MZ-700").get(0);
var liquidRoot = dock_n_liquid.select(liquidRootElement);
var dockPanelKb = $("#dock-panel-keyboard");
var mz700js = MZ700Js.create({
"urlPrefix" : "../",
"onKeyboardPanelOpen": function() {
dockPanelKb.css("height", "250px");
liquidRoot.layout();
resizeScreen();
},
"onKeyboardPanelClose": function() {
dockPanelKb.css("height", "50px");
liquidRoot.layout();
resizeScreen();
}
});
var fullscreenButton = $("<button/>")
.attr("id","fullscreenButton");
var fullscreenElement = document.getElementById("fullscrn-MZ-700");
var onFullscreenButtonClick = function() {
if(document.fullscreenElement === fullscreenElement) {
dock_n_liquid.exitFullscreen().then(function() {
resizeScreen();
});
//liquidRootElement.requestFullscreen();
} else {
dock_n_liquid.requestFullscreen(fullscreenElement).then(function() {
resizeScreen();
});
//document.exitFullscreen();
}
}
var onFullscreenChange = function() {
console.log("fullscreenchange");
if(document.fullscreenElement == null) {
$("#dock-panel-header").show();
$("#dock-panel-keyboard").show();
$("#dock-panel-bottom").show();
$("#dock-panel-right").show();
fullscreenButton.html("Fullscreen");
} else {
$("#dock-panel-header").hide();
$("#dock-panel-keyboard").hide();
$("#dock-panel-bottom").hide();
$("#dock-panel-right").hide();
fullscreenButton.html("Exit Fullscreen");
}
liquidRoot.layout();
resizeScreen();
liquidRoot.layout();
resizeScreen();
};
fullscreenButton.click(onFullscreenButtonClick);
$("#dock-panel-scrn-ctrl").append(fullscreenButton);
window.addEventListener("fullscreenchange", onFullscreenChange);
onFullscreenChange();
mz700js.reset();
screen.find("canvas").css("height", "calc(100% - 1px)");
dock_n_liquid.init(resizeScreen);
dock_n_liquid.select($(".MZ-700").get(0)).layout();
window.addEventListener(
"reseize", function() {
console.log("!!!");
resizeScreen(); });
resizeScreen();
}(window.jQuery));
| JavaScript | 0.000001 | @@ -2057,61 +2057,8 @@
%7D);%0A
- //liquidRootElement.requestFullscreen();%0A
@@ -2203,49 +2203,8 @@
%7D);%0A
- //document.exitFullscreen();%0A
|
d901e00c64418f61e80993389b5199cf977acb41 | Add links to dynamically created instances. | share/collection.js | share/collection.js | function format_instance(inst)
{
return ("<li class=\"instance\">" + inst.description + "</li>");
}
function format_instance_list(instances)
{
var ret = "<ul class=\"instance_list\">";
var i;
if (instances.length == 0)
return ("");
for (i = 0; i < instances.length; i++)
ret += format_instance (instances[i]);
ret += "</ul>";
return (ret);
}
function format_graph(graph)
{
return ("<li class=\"graph\">" + graph.title + format_instance_list (graph.instances) + "</li>");
}
$(document).ready(function() {
$("#search-input").keyup (function()
{
var term = $("#search-input").val ();
$.getJSON ("collection.fcgi",
{ "action": "list_graphs", "format": "json", "search": term},
function(data)
{
var i;
$("#search-output").html ("");
for (i = 0; i < data.length; i++)
{
var graph = data[i];
$("#search-output").append (format_graph (graph));
}
});
});
});
/* vim: set sw=2 sts=2 et fdm=marker : */
| JavaScript | 0 | @@ -60,16 +60,87 @@
tance%5C%22%3E
+%3Ca href=%5C%22%22 + location.pathname + %22?action=graph;%22 + inst.params + %22%5C%22%3E
%22 + inst
@@ -153,24 +153,28 @@
iption + %22%3C/
+a%3E%3C/
li%3E%22);%0A%7D%0A%0Afu
|
d30fca6b7df74d4c80a958c2f70fabf7649fb0f2 | fix document default path | client/assets/components/document/document_default/document_default.js | client/assets/components/document/document_default/document_default.js | (function () {
angular.module('fusionSeedApp.components.document', ['fusionSeedApp.services.config',
'fusionSeedApp.utils.docs', 'fusionSeedApp.services.signals'
])
.directive('documentDefault', documentDefault);
function documentDefault() {
'ngInject';
return {
templateUrl: 'assets/components/document_default/document_default.html',
scope: true,
controller: Controller,
controllerAs: 'dc',
bindToController: {
doc: '='
},
replace: true
};
}
function Controller($log, $scope, DocsHelper, ConfigService, SignalsService) {
'ngInject';
var dc = this;
dc.postSignal = SignalsService.postSignal;
activate();
///////////
function activate() {
dc.doc = processDocument(DocsHelper.concatMultivaluedFields(dc.doc));
$log.info('Doc Type: ' + dc.doc_type);
}
/**
* Processes a document prepares fields from the config for display.
* @param {object} doc A single document record
* @return {object} The document record with processed properties.
*/
function processDocument(doc) {
//Populate the additional fields to display
doc.fieldsToDisplay = DocsHelper.populateFieldLabels(
DocsHelper.selectFields(doc, ConfigService.getFieldsToDisplay()),
ConfigService.getFieldLabels()
);
doc.lw_head = getField('head', doc) ?
getField('head', doc) : 'Title Field Not Found';
doc.lw_subhead = getField('subhead', doc);
doc.lw_description = getField('description', doc);
doc.lw_image = getField('image', doc);
doc.lw_url = getField('head_url', doc);
$log.info(doc);
return doc;
}
/**
* Given a field type get the actual field value.
* @param {String} fieldType The Field type.
* @param {object} doc The document object
* @return {String|null} The field value.
*/
function getField(fieldType, doc) {
var fieldName = ConfigService.getFields.get(fieldType);
if (doc.hasOwnProperty(fieldName)) {
return doc[fieldName];
}
return null;
}
}
})();
| JavaScript | 0.000001 | @@ -322,32 +322,41 @@
ponents/document
+/document
_default/documen
|
39871e52df038a022c2bf2b6a86abed7969af06a | fix NPE | src/skins/vector/views/organisms/RightPanel.js | src/skins/vector/views/organisms/RightPanel.js | /*
Copyright 2015 OpenMarket 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 React = require('react');
var sdk = require('matrix-react-sdk')
var dis = require('matrix-react-sdk/lib/dispatcher');
var MatrixClientPeg = require("matrix-react-sdk/lib/MatrixClientPeg");
module.exports = React.createClass({
displayName: 'RightPanel',
Phase : {
MemberList: 'MemberList',
FileList: 'FileList',
},
getInitialState: function() {
return {
phase : this.Phase.MemberList
}
},
onMemberListButtonClick: function() {
if (this.props.collapsed) {
this.setState({ phase: this.Phase.MemberList });
dis.dispatch({
action: 'show_right_panel',
});
}
else {
dis.dispatch({
action: 'hide_right_panel',
});
}
},
render: function() {
var MemberList = sdk.getComponent('organisms.MemberList');
var buttonGroup;
var panel;
var filesHighlight;
var membersHighlight;
if (!this.props.collapsed) {
if (this.state.phase == this.Phase.MemberList) {
membersHighlight = <div className="mx_RightPanel_headerButton_highlight"></div>;
}
else if (this.state.phase == this.Phase.FileList) {
filesHighlight = <div className="mx_RightPanel_headerButton_highlight"></div>;
}
}
var membersBadge;
if (this.state.phase == this.Phase.MemberList && this.props.roomId) {
var cli = MatrixClientPeg.get();
var room = cli.getRoom(this.props.roomId);
// FIXME: presumably we need to subscribe to some event to refresh this count when it changes?
membersBadge = <div className="mx_RightPanel_headerButton_badge">{ room.getJoinedMembers().length }</div>;
}
if (this.props.roomId) {
buttonGroup =
<div className="mx_RightPanel_headerButtonGroup">
<div className="mx_RightPanel_headerButton" onClick={ this.onMemberListButtonClick }>
<img src="img/members.png" width="17" height="22" title="Members" alt="Members"/>
{ membersBadge }
{ membersHighlight }
</div>
<div className="mx_RightPanel_headerButton mx_RightPanel_filebutton">
<img src="img/files.png" width="17" height="22" title="Files" alt="Files"/>
{ filesHighlight }
</div>
</div>;
if (!this.props.collapsed && this.state.phase == this.Phase.MemberList) {
panel = <MemberList roomId={this.props.roomId} key={this.props.roomId} />
}
}
var classes = "mx_RightPanel";
if (this.props.collapsed) {
classes += " collapsed";
}
return (
<aside className={classes}>
<div className="mx_RightPanel_header">
{ buttonGroup }
</div>
{ panel }
</aside>
);
}
});
| JavaScript | 0.000013 | @@ -2285,16 +2285,44 @@
hanges?%0A
+ if (room) %7B%0A
@@ -2424,32 +2424,46 @@
length %7D%3C/div%3E;%0A
+ %7D%0A
%7D%0A%0A
|
f0c7a1e8138f16ac4afc20ffbd1c6efbd2a6e031 | remove unused var | lib/info-receiver.js | lib/info-receiver.js | 'use strict';
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var request = require('request');
var jsonParse = require('./safe-json-parse.js');
module.exports = InfoReceiver;
util.inherits(InfoReceiver, EventEmitter);
function InfoReceiver(base_url) {
process.nextTick(function () { this.doRequest(base_url); }.bind(this));
}
InfoReceiver.prototype.doRequest = function(base_url) {
var t0 = Date.now();
request({
url: base_url + '/info',
timeout: 8000, // copying the original SockJS client
}, function (err, response, text) {
if (err || response.statusCode !== 200) {
this.emit('finish');
} else {
this.emit('finish', getInfo(text), Date.now() - t0);
}
}.bind(this));
};
function getInfo(text) {
var info;
if (text) {
return jsonParse(text);
}
return {};
}
| JavaScript | 0.000002 | @@ -967,22 +967,8 @@
) %7B%0A
- var info;%0A
|
bad98aa9239e44fc1dece881b2db8f3ac014ea8b | Tweak Moon.update | Source/Scene/Moon.js | Source/Scene/Moon.js | /*global define*/
define([
'../Core/buildModuleUrl',
'../Core/Cartesian3',
'../Core/defaultValue',
'../Core/defined',
'../Core/defineProperties',
'../Core/destroyObject',
'../Core/Ellipsoid',
'../Core/IauOrientationAxes',
'../Core/Matrix3',
'../Core/Matrix4',
'../Core/Simon1994PlanetaryPositions',
'../Core/Transforms',
'./EllipsoidPrimitive',
'./Material'
], function(
buildModuleUrl,
Cartesian3,
defaultValue,
defined,
defineProperties,
destroyObject,
Ellipsoid,
IauOrientationAxes,
Matrix3,
Matrix4,
Simon1994PlanetaryPositions,
Transforms,
EllipsoidPrimitive,
Material) {
"use strict";
/**
* Draws the Moon in 3D.
* @alias Moon
* @constructor
*
* @param {Object} [options] Object with the following properties:
* @param {Boolean} [options.show=true] Determines whether the moon will be rendered.
* @param {String} [options.textureUrl=buildModuleUrl('Assets/Textures/moonSmall.jpg')] The moon texture.
* @param {Ellipsoid} [options.ellipsoid=Ellipsoid.MOON] The moon ellipsoid.
* @param {Boolean} [options.onlySunLighting=true] Use the sun as the only light source.
*
* @see Scene#moon
*
* @example
* scene.moon = new Cesium.Moon();
*/
var Moon = function(options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
var url = options.textureUrl;
if (!defined(url)) {
url = buildModuleUrl('Assets/Textures/moonSmall.jpg');
}
/**
* Determines if the moon will be shown.
*
* @type {Boolean}
* @default true
*/
this.show = defaultValue(options.show, true);
/**
* The moon texture.
* @type {String}
* @default buildModuleUrl('Assets/Textures/moonSmall.jpg')
*/
this.textureUrl = url;
this._ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.MOON);
/**
* Use the sun as the only light source.
* @type {Boolean}
* @default true
*/
this.onlySunLighting = defaultValue(options.onlySunLighting, true);
this._ellipsoidPrimitive = new EllipsoidPrimitive({
radii : this.ellipsoid.radii,
material : Material.fromType(Material.ImageType),
_owner : this
});
this._ellipsoidPrimitive.material.translucent = false;
this._axes = new IauOrientationAxes();
};
defineProperties(Moon.prototype, {
/**
* Get the ellipsoid that defines the shape of the moon.
*
* @memberof Moon.prototype
*
* @type {Ellipsoid}
* @readonly
*
* @default {@link Ellipsoid.MOON}
*/
ellipsoid : {
get : function() {
return this._ellipsoid;
}
}
});
var icrfToFixed = new Matrix3();
var rotationScratch = new Matrix3();
var translationScratch = new Cartesian3();
/**
* @private
*/
Moon.prototype.update = function(context, frameState, commandList) {
if (!this.show) {
return;
}
// XXX temporary hack
if (!defined(commandList)) {
commandList = [];
}
var ellipsoidPrimitive = this._ellipsoidPrimitive;
ellipsoidPrimitive.material.uniforms.image = this.textureUrl;
ellipsoidPrimitive.onlySunLighting = this.onlySunLighting;
var date = frameState.time;
if (!defined(Transforms.computeIcrfToFixedMatrix(date, icrfToFixed))) {
Transforms.computeTemeToPseudoFixedMatrix(date, icrfToFixed);
}
var rotation = this._axes.evaluate(date, rotationScratch);
Matrix3.transpose(rotation, rotation);
Matrix3.multiply(icrfToFixed, rotation, rotation);
var translation = Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame(date, translationScratch);
Matrix3.multiplyByVector(icrfToFixed, translation, translation);
Matrix4.fromRotationTranslation(rotation, translation, ellipsoidPrimitive.modelMatrix);
ellipsoidPrimitive.update(context, frameState, commandList);
// XXX temporary hack
return commandList.length === 1 ? commandList[0] : undefined;
};
/**
* Returns true if this object was destroyed; otherwise, false.
* <br /><br />
* If this object was destroyed, it should not be used; calling any function other than
* <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
*
* @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
*
* @see Moon#destroy
*/
Moon.prototype.isDestroyed = function() {
return false;
};
/**
* Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
* release of WebGL resources, instead of relying on the garbage collector to destroy this object.
* <br /><br />
* Once an object is destroyed, it should not be used; calling any function other than
* <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
* assign the return value (<code>undefined</code>) to the object as done in the example.
*
* @returns {undefined}
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
* @see Moon#isDestroyed
*
* @example
* moon = moon && moon.destroy();
*/
Moon.prototype.destroy = function() {
this._ellipsoidPrimitive = this._ellipsoidPrimitive && this._ellipsoidPrimitive.destroy();
return destroyObject(this);
};
return Moon;
}); | JavaScript | 0.000001 | @@ -3203,16 +3203,49 @@
sian3();
+%0A var scratchCommandList = %5B%5D;
%0A%0A /*
@@ -3326,29 +3326,16 @@
ameState
-, commandList
) %7B%0A
@@ -3391,116 +3391,8 @@
%7D%0A%0A
- // XXX temporary hack%0A if (!defined(commandList)) %7B%0A commandList = %5B%5D;%0A %7D%0A%0A
@@ -4250,16 +4250,64 @@
atrix);%0A
+ %0A scratchCommandList.length = 0;%0A
@@ -4353,17 +4353,24 @@
eState,
-c
+scratchC
ommandLi
@@ -4377,39 +4377,8 @@
st);
-%0A%0A // XXX temporary hack
%0A
@@ -4389,17 +4389,25 @@
return
-c
+(scratchC
ommandLi
@@ -4425,12 +4425,20 @@
== 1
+)
?
-c
+scratchC
omma
@@ -5924,8 +5924,9 @@
oon;%0A%7D);
+%0A
|
f9fd69a8ddd8f12d570b3bed3f5264a6845e583f | Add a default to juttle-engine module. | lib/juttle-engine.js | lib/juttle-engine.js | 'use strict';
var _ = require('underscore');
var express = require('express');
var service = require('juttle-service').service;
var logSetup = require('juttle-service').logSetup;
var getLogger = require('juttle-service').getLogger;
var WebsocketEndpoint = require('juttle-service').WebsocketEndpoint;
var viewer = require('juttle-viewer');
var daemonize = require('daemon');
var EndpointNotifier = require('./endpoint-notifier');
var app, server;
var endpoint_notifier = new EndpointNotifier();
function rendezvous_topic(ws, req) {
var ep = new WebsocketEndpoint({ws: ws});
endpoint_notifier.add_endpoint_to_topic(ep, req.params.topic);
}
function run(opts, ready) {
logSetup(_.defaults(opts, {'log-default-output': '/var/log/juttle-engine.log'}));
var logger = getLogger('juttle-engine')
if (opts.daemonize) {
daemonize();
}
logger.debug('initializing');
var service_opts = {
root_directory: opts.root,
config_path: opts.config
};
service.configure(service_opts);
app = express();
app.disable('x-powered-by');
service.addRoutes(app, service_opts);
app.use(viewer({juttleServiceHost: opts.host + ':' + opts.port}));
// Also add routes for rendezvous.
app.ws('/rendezvous/:topic',
rendezvous_topic);
server = app.listen(opts.port, opts.host, () => {
logger.info('Juttle engine listening at http://' + opts.host + ':' + opts.port
+ ' with root directory: ' + opts.root);
ready && ready();
});
}
function stop() {
server.close();
}
module.exports = {
run,
stop
}
| JavaScript | 0 | @@ -1125,24 +1125,65 @@
ice_opts);%0A%0A
+ opts.host = opts.host %7C%7C '0.0.0.0';%0A%0A
app.use(
|
8468dd72d2d872d460135a00795a856d263ad09b | Change from function to mongoose query to find existing work. Fixes #8 | Hive/Server/Request.js | Hive/Server/Request.js | //Import error handler
var Error = require('../../Utils/Error.js');
//Import AES library
var AES = require('simple-encryption').AES;
//Schema imports
var Worker = require('../MongoSchemas/Worker.js');
var WorkGroup = require('../MongoSchemas/WorkGroup.js');
var checkForSubmittedData = function(array, userID) {
//Loop through the workgroup array
for(var i = 0; i < array.length; i++) {
//Create a flag variable
var flag = true;
//Loop through the data in the workgroup array
for(var j = 0; j < array[i].data.length; j++) {
//If the current worker is not equal to
if(array[j].worker == userID) {
flag = false;
}
}
//Only if the worker wasn't found in the array
if(flag) {
return false;
}
}
return true;
}
//Export the request handler
module.exports = function(message, mongoose, socket, eventEmitter, key, userID, groupMax){
//Get encryption information
var payload = message.payload;
var tag = message.tag;
var iv = message.iv;
//Declare decrypted variable for try/catch
var decrypted;
//Try decrypting, otherwise pass error onto user
try {
decrypted = JSON.parse(AES.decrypt(key, iv, tag, payload));
} catch(e) {
Error.sendError(socket, 'SECURITY_DECRYPTION_FAILURE', true);
return;
}
if(!decrypted ||
!decrypted.request ||
decrypted.request.toUpperCase() !== 'REQUEST') {
//Stop execution, we cannot verify the user...
Error.sendError(socket, 'STAGE_HANDSHAKE_POST_COMPLETE_FAILURE', true);
return;
}
//Make sure that the user does not currently have a work group that they have
//not submitted work to
WorkGroup.find({workers: userID}, function(error, workgroups) {
//Pass database errors onto client
if(error) {
Error.sendError(socket, 'DATABASE_GENERIC', true);
//Stop execution
return;
}
//If the user has no pending work
if(workgroups.length == 0 || checkForSubmittedData(workgroups, userID)) {
//Set the user's lastActiveTime to now
Worker.findOne({_id: userID}, function(error, worker) {
//If error, tell the user and stop executing
if(error) {
Error.sendError(socket, 'DATABASE_GENERIC', true);
//Stop execution
return;
}
//Set the lastActiveTime to now
worker.lastActive = new Date();
worker.save(function(error) {
//If error, tell the user and stop executing
if(error) {
Error.sendError(socket, 'DATABASE_GENERIC', true);
return;
}
//Find non full work groups
WorkGroup.findOne(
{
//All conditions should be true
$and: [
//Only workgroups which are not full
{['workers.' + groupMax]: {$exists: false}},
//And not in the workers section of the work group
{'workers': {$ne: userID}}
]
},
function(error, workgroup) {
//Pass database errors onto the client
if(error) {
Error.sendError(socket, 'DATABASE_GENERIC', true);
//Stop execution
return;
}
//If there are no non full work groups, create a new work group
if(!workgroup) {
//Emit a create_work event and pass in a callback with a work
//argument
eventEmitter.emit('create_work', function(work) {
//If there's no work left
if(!work) {
Error.sendError(socket, 'STAGE_REQUEST_NO_WORK', true);
//Stop execution
return;
}
//Create and populate the new group
var newworkgroup = new WorkGroup();
newworkgroup.workers = [userID];
newworkgroup.data = [];
newworkgroup.work = JSON.stringify(work);
newworkgroup.save(function(error) {
//If database error, pass it onto the user
if(error) {
Error.sendError(socket, 'DATABASE_GENERIC', true);
//Stop execution
return;
}
//Prepare message for encryption
var jsonmsg = {
work: work
}
//Generate IV
var iv = AES.generateIV();
//Declare encrypted variable for try/catch
var encrypted;
//Try to encrypt, forward errors
try {
encrypted = AES.encrypt(key, iv, JSON.stringify(jsonmsg));
} catch(e) {
Error.sendError(socket, 'SECURITY_ENCRYPTION_FAILURE', true);
//Stop execution
return;
}
//Send work to client
try {
socket.sendMessage({'payload': encrypted.encrypted, 'tag': encrypted.tag,
'iv': iv});
} catch(e) {
//Destroy socket
socket.destroy();
return;
}
});
});
} else {
//A valid work group has been found, add the new worker
workgroup.workers.push(userID);
//Save immediately, so it updates for other clients
workgroup.save(function(error) {
//Pass database errors to user
if(error) {
Error.sendError(socket, 'DATABASE_GENERIC', true);
//stop execution
return;
}
//Prepare message for encryption
var jsonmsg = {
work: JSON.parse(workgroup.work)
}
//Generate IV
var iv = AES.generateIV();
//Declare encrypted variable for try/catch block
var encrypted;
//Attempt to encrypt, pass errors to user
try {
encrypted = AES.encrypt(key, iv, JSON.stringify(jsonmsg));
} catch(e) {
Error.sendError(socket, 'SECURITY_ENCRYPTION_FAILURE', true);
//Stop execution
return;
}
try {
socket.sendMessage({'payload': encrypted.encrypted, 'tag': encrypted.tag, 'iv': iv});
} catch(e) {
//Destroy socket
socket.destroy();
return;
}
});
}
}
);
});
});
} else {
//Pending work
Error.sendError(socket, 'STAGE_REQUEST_PENDING_WORK', true);
//Stop execution/return for consistency
return;
}
});
}
| JavaScript | 0 | @@ -257,528 +257,8 @@
);%0A%0A
-var checkForSubmittedData = function(array, userID) %7B%0A //Loop through the workgroup array%0A for(var i = 0; i %3C array.length; i++) %7B%0A //Create a flag variable%0A var flag = true;%0A //Loop through the data in the workgroup array%0A for(var j = 0; j %3C array%5Bi%5D.data.length; j++) %7B%0A //If the current worker is not equal to%0A if(array%5Bj%5D.worker == userID) %7B%0A flag = false;%0A %7D%0A %7D%0A //Only if the worker wasn't found in the array%0A if(flag) %7B%0A return false;%0A %7D%0A %7D%0A return true;%0A%7D%0A%0A
//Ex
@@ -1142,23 +1142,571 @@
nd(%7B
-workers: userID
+%0A //All conditions should be true%0A $and: %5B%0A //And in the workers section of the work group%0A %7B'workers': userID%7D,%0A //Only workgroups which the worker has not submitted data for%0A %7B%0A //In the data array%0A data: %7B%0A //Not equal to elemMatch (i.e, workgroups where data hasn't been submitted)%0A $not: %7B%0A //Match all documents with the the entry worker in the object array equal to the worker ID%0A $elemMatch: %7B%0A worker: userID%0A %7D%0A %7D%0A %7D%0A %7D%0A %5D%0A
%7D, f
|
c5d353fdc42a0ff58d77f8a64348c51b730f8121 | add servers when restarting master server | lib/master/master.js | lib/master/master.js | var starter = require('./starter');
var logger = require('pomelo-logger').getLogger('pomelo', __filename);
var crashLogger = require('pomelo-logger').getLogger('crash-log', __filename);
var adminLogger = require('pomelo-logger').getLogger('admin-log', __filename);
var admin = require('pomelo-admin');
var util = require('util');
var utils = require('../util/utils');
var moduleUtil = require('../util/moduleUtil');
var Constants = require('../util/constants');
var Server = function(app, opts) {
this.app = app;
this.masterInfo = app.getMaster();
this.registered = {};
this.modules = [];
opts = opts || {};
opts.port = this.masterInfo.port;
opts.env = this.app.get(Constants.RESERVED.ENV);
this.closeWatcher = opts.closeWatcher;
this.masterConsole = admin.createMasterConsole(opts);
};
module.exports = Server;
Server.prototype.start = function(cb) {
moduleUtil.registerDefaultModules(true, this.app, this.closeWatcher);
moduleUtil.loadModules(this, this.masterConsole);
var self = this;
// start master console
this.masterConsole.start(function(err) {
if(err) {
process.exit(0);
}
moduleUtil.startModules(self.modules, function(err) {
if(err) {
utils.invokeCallback(cb, err);
return;
}
if(self.app.get(Constants.RESERVED.MODE) !== Constants.RESERVED.STAND_ALONE) {
starter.runServers(self.app);
}
utils.invokeCallback(cb);
});
});
this.masterConsole.on('error', function(err) {
if(!!err) {
logger.error('masterConsole encounters with error: ' + err.stack);
return;
}
});
// monitor servers disconnect event
this.masterConsole.on('disconnect', function(id, type, info, reason) {
crashLogger.info(util.format('[%s],[%s],[%s],[%s]', type, id, Date.now(), reason || 'disconnect'));
var count = 0;
var time = 0;
var pingTimer = null;
var server = self.app.getServerById(id);
var stopFlags = self.app.get(Constants.RESERVED.STOP_SERVERS) || [];
if(!!server && (server[Constants.RESERVED.AUTO_RESTART] === 'true' || server[Constants.RESERVED.RESTART_FORCE] === 'true') && stopFlags.indexOf(id) < 0) {
var setTimer = function(time) {
pingTimer = setTimeout(function() {
utils.ping(server.host, function(flag) {
if(flag) {
handle();
} else {
count++;
if(count > 3) {
time = Constants.TIME.TIME_WAIT_MAX_PING;
} else {
time = Constants.TIME.TIME_WAIT_PING * count;
}
setTimer(time);
}
});
}, time);
};
setTimer(time);
var handle = function() {
clearTimeout(pingTimer);
utils.checkPort(server, function(status) {
if(status === 'error') {
utils.invokeCallback(cb, new Error('Check port command executed with error.'));
return;
} else if(status === 'busy') {
if(!!server[Constants.RESERVED.RESTART_FORCE]) {
starter.kill([info.pid], [server]);
} else {
utils.invokeCallback(cb, new Error('Port occupied already, check your server to add.'));
return;
}
}
setTimeout(function() {
starter.run(self.app, server, null);
}, Constants.TIME.TIME_WAIT_STOP);
});
};
}
});
// monitor servers register event
this.masterConsole.on('register', function(record) {
starter.bindCpu(record.id, record.pid, record.host);
});
this.masterConsole.on('admin-log', function(log, error) {
if(error) {
adminLogger.error(JSON.stringify(log));
} else {
adminLogger.info(JSON.stringify(log));
}
});
};
Server.prototype.stop = function(cb) {
this.masterConsole.stop();
process.nextTick(cb);
};
| JavaScript | 0.000001 | @@ -1598,32 +1598,127 @@
urn;%0A %7D%0A %7D);
+%0A %0A this.masterConsole.on('reconnect', function(info)%7B%0A self.app.addServers(%5Binfo%5D);%0A %7D);
%0A%0A // monitor s
|
61f791df8aa8dfce071638896d097d84a5327f01 | stop running when error | server/SampleQuery.js | server/SampleQuery.js | var sys = require('sys')
var exec = require('child_process').exec;
var canRun = true;
var counter = 1;
function onJavaReturn(error, stdout, stderr) {
console.log(stderr);
var result = JSON.parse(stdout);
var hit = 0;
for(var j = 0; j < result.length; j++){
var imageName = result[j];
var name = imageName.split(".")[0];
name = parseInt(name, 10);
if (name > 20*(counter-1) && name <= counter*20){
hit++;
}
}
var P = hit*1.0/result.length;
var R = hit*1.0/20;
var F1 = (2*P*R)/(P+R);
console.log(counter+"\t"+hit+"\t"+R.toFixed(3)+"\t"+P.toFixed(3)+"\t\t"+F1.toFixed(3));
counter ++;
if (counter <= 20) {
exec("java -Xmx4g -cp " + jarFile + ":lib/gson-2.2.4.jar cs3246/a2/web/WebServiceHandler " + imagePath + "query" + counter + ".jpg " + numResult, {cwd: cwd}, onJavaReturn);
}
}
console.log("Running SampleQuery.js \n");
// print process.argv
process.argv.forEach(function(val, index, array) {
console.log(index + ': ' + val);
});
var cwd = process.argv[2];
var jarFile = process.argv[3];
var imagePath = process.argv[4];
var numResult = process.argv[5];
console.log("Query\tHits\tRecall\tPrecision\tFi");
exec("java -Xmx4g -cp " + jarFile + ":lib/gson-2.2.4.jar cs3246/a2/web/WebServiceHandler " + imagePath + "query" + counter + ".jpg " + numResult, {cwd: cwd}, onJavaReturn);
| JavaScript | 0.000006 | @@ -163,28 +163,85 @@
%7B%0A
-console.log(stderr);
+if (stderr != null) %7B%0A console.log(%22Error: %5Cn%22 + stderr);%0A return;%0A %7D%0A
%0A v
|
af2df2b1b0844e7eca857a63e7c3e807ef3d9362 | Fix jshint errors in lib/nodesregistry.js | lib/nodesregistry.js | lib/nodesregistry.js | var INHERIT = require('inherit'),
ASSERT = require('assert'),
LOGGER = require('./logger'),
registry = {},
cache = {};
module.exports = {
/**
* Calls INHERIT for specified parameters set and put the result into cache.
*
* @param {String} nodeName Name of the node
* @param {Object|String} objectOrBaseName Object definition or name of the class to inherit from
* @param {Object|Object} objectOrStatic Object with static members definition|object definition
* @param {Object} staticObject Object with static members definition
* @return {Object} cache
* @private
*/
_decl: function(nodeName, objectOrBaseName, objectOrStatic, staticObject) {
var explicitBase = typeof objectOrBaseName === 'string',
baseName = explicitBase? objectOrBaseName : nodeName,
static = typeof objectOrBaseName !== 'string'? objectOrStatic: staticObject,
object = explicitBase? objectOrStatic : objectOrBaseName,
base = baseName;
if (typeof baseName === 'string') {
base = baseName == nodeName? cache[baseName] : this.getNodeClass(baseName);
}
if (typeof objectOrStatic === 'function') {
cache[nodeName] = objectOrStatic;
} else {
cache[nodeName] = base? INHERIT(base, object, static) : INHERIT(object, static);
}
return cache;
},
_inheritChain: function(nodeName) {
var stack = registry[nodeName];
ASSERT.ok(Array.isArray(stack), 'definition for class ' + nodeName + ' is not found in the registry');
for(var i = 0; i < stack.length; i++) {
this._decl.apply(this, stack[i]);
}
return cache[nodeName];
},
/**
* Stores specified arguments into registry for further processing with INHERIT.
*
* @param {String} nodeName Name of the node
* @param {Object|String} objectOrBaseName Object definition or name of the class to inherit from
* @param {Object|Object} objectOrStatic Object with static members definition|object definition
* @param {Object} staticObject Object with static members definition
*/
decl: function(nodeName, objectOrBaseName, objectOrStatic, staticObject) {
cache = {};
var stack = registry[nodeName] || [];
stack.push(Array.prototype.slice.call(arguments, 0));
registry[nodeName] = stack;
},
getRegistry: function(node) {
return node? registry[node] : registry;
},
getNodeClass: function(nodeName){
return cache[nodeName] || this._inheritChain(nodeName);
}
};
| JavaScript | 0.000025 | @@ -1,12 +1,27 @@
+'use strict';%0A%0A
var INHERIT
@@ -872,16 +872,19 @@
static
+Obj
= typeo
@@ -961,19 +961,16 @@
obj
-ect
= expli
@@ -1117,16 +1117,17 @@
eName ==
+=
nodeNam
@@ -1355,27 +1355,24 @@
ase, obj
-ect
, static
) : INHE
@@ -1363,16 +1363,19 @@
, static
+Obj
) : INHE
@@ -1385,19 +1385,16 @@
(obj
-ect
, static
);%0A
@@ -1389,16 +1389,19 @@
, static
+Obj
);%0A
|
3a2754199192ccfd0a29344e2160d91b3cf81b5b | Fix non-admins unable to update account | server/User/router.js | server/User/router.js | const db = require('sqlite')
const squel = require('squel')
const jwtSign = require('jsonwebtoken').sign
const bcrypt = require('../lib/bcrypt')
const KoaRouter = require('koa-router')
const router = KoaRouter({ prefix: '/api' })
const debug = require('debug')
const log = debug('app:user')
const Prefs = require('../Prefs')
// login
router.post('/login', async (ctx, next) => {
await _login(ctx, ctx.request.body)
})
// logout
router.get('/logout', async (ctx, next) => {
// @todo force socket room leave
ctx.cookies.set('kfToken', '')
ctx.status = 200
ctx.body = {}
})
// create
router.post('/account', async (ctx, next) => {
const { name, username, newPassword, newPasswordConfirm, roomId } = ctx.request.body
// check presence of all fields
if (!name || !username || !newPassword || !newPasswordConfirm) {
ctx.throw(422, 'All fields are required')
}
{
// check for duplicate username
const q = squel.select()
.from('users')
.where('username = ?', username.trim())
const { text, values } = q.toParam()
if (await db.get(text, values)) {
ctx.throw(401, 'Username already exists')
}
}
// check that passwords match
if (newPassword !== newPasswordConfirm) {
ctx.throw(422, 'Passwords do not match')
}
{
// insert user
const q = squel.insert()
.into('users')
.set('username', username.trim())
.set('password', await bcrypt.hash(newPassword, 12))
.set('name', name.trim())
.set('isAdmin', 0)
const { text, values } = q.toParam()
await db.run(text, values)
}
// log them in automatically
await _login(ctx, { username, password: newPassword, roomId })
})
// first-time setup
router.post('/setup', async (ctx, next) => {
const { name, username, newPassword, newPasswordConfirm } = ctx.request.body
let roomId
// must be first run
const prefs = await Prefs.get()
if (prefs.isFirstRun !== true) {
ctx.throw(403)
}
// check presence of all fields
if (!name || !username || !newPassword || !newPasswordConfirm) {
ctx.throw(422, 'All fields are required')
}
// check that passwords match
if (newPassword !== newPasswordConfirm) {
ctx.throw(422, 'Passwords do not match')
}
// create admin user
{
const q = squel.insert()
.into('users')
.set('username', username.trim())
.set('password', await bcrypt.hash(newPassword, 12))
.set('name', name.trim())
.set('isAdmin', 1)
const { text, values } = q.toParam()
await db.run(text, values)
}
// create default room
{
const q = squel.insert()
.into('rooms')
.set('name', 'Room 1')
.set('status', 'open')
.set('dateCreated', Math.floor(Date.now() / 1000))
const { text, values } = q.toParam()
const res = await db.run(text, values)
// sign in to room
roomId = res.stmt.lastID
}
// unset isFirstRun
{
const q = squel.update()
.table('prefs')
.where('key = ?', 'isFirstRun')
.set('data', squel.select().field(`json('false')`))
const { text, values } = q.toParam()
await db.run(text, values)
}
await _login(ctx, { username, password: newPassword, roomId })
})
// update account
router.put('/account', async (ctx, next) => {
let user
if (!ctx.user.isAdmin) {
ctx.throw(401)
}
// find user by id (from token)
{
const q = squel.select()
.from('users')
.where('userId = ?', ctx.user.userId)
const { text, values } = q.toParam()
user = await db.get(text, values)
}
if (!user) {
ctx.throw(401)
}
let { name, username, password, newPassword, newPasswordConfirm } = ctx.request.body
// check presence of required fields
if (!name || !username || !password) {
ctx.throw(422, 'Name, username and current password are required')
}
// validate current password
if (!await bcrypt.compare(password, user.password)) {
ctx.throw(401, 'Current password is incorrect')
}
// check for duplicate username
{
const q = squel.select()
.from('users')
.where('userId != ?', ctx.user.userId)
.where('username = ?', username.trim())
const { text, values } = q.toParam()
if (await db.get(text, values)) {
ctx.throw(401, 'Username already exists')
}
}
// begin update query
const q = squel.update()
.table('users')
.where('userId = ?', ctx.user.userId)
.set('name', name.trim())
.set('username', username.trim())
// changing password?
if (newPassword) {
if (newPassword !== newPasswordConfirm) {
ctx.throw(422, 'New passwords do not match')
}
q.set('password', await bcrypt.hash(newPassword, 10))
password = newPassword
}
const { text, values } = q.toParam()
await db.run(text, values)
// login again
await _login(ctx, { username, password, roomId: ctx.user.roomId })
})
module.exports = router
async function _login (ctx, creds) {
const { username, password, roomId } = creds
if (!username || !password) {
ctx.throw(422, 'Username/email and password are required')
}
// get user
const q = squel.select()
.from('users')
.where('username = ?', username.trim())
const { text, values } = q.toParam()
const user = await db.get(text, values)
if (!user) {
ctx.throw(401)
}
// validate password
if (!await bcrypt.compare(password, user.password)) {
ctx.throw(401)
}
// validate roomId (if not an admin)
if (!user.isAdmin) {
if (typeof roomId === 'undefined') {
ctx.throw(422, 'RoomId is required')
}
const q = squel.select()
.from('rooms')
.where('roomId = ?', roomId)
const { text, values } = q.toParam()
const row = await db.get(text, values)
if (!row || row.status !== 'open') {
ctx.throw(401, 'Invalid Room')
}
}
delete user.password
user.roomId = roomId
user.isAdmin = (user.isAdmin === 1)
// encrypt JWT based on subset of user object
const token = jwtSign({
userId: user.userId,
isAdmin: user.isAdmin === true,
name: user.name,
roomId: user.roomId,
}, ctx.jwtKey)
// set httpOnly cookie containing JWT
ctx.cookies.set('kfToken', token, {
httpOnly: true,
})
ctx.body = user
}
| JavaScript | 0 | @@ -3284,59 +3284,8 @@
er%0A%0A
- if (!ctx.user.isAdmin) %7B%0A ctx.throw(401)%0A %7D%0A%0A
//
|
7ff96f5850b19e74718927be8839e934752940d6 | Add file mapping to entry point chunks structure | server/build/index.js | server/build/index.js | import { join } from 'path'
import fs from 'mz/fs'
import uuid from 'uuid'
import webpack from './webpack'
import { build as buildServer } from '../../babel/index'
export default async function build (dir, server) {
const buildId = uuid.v4()
const buildDir = join(dir, '.next')
const compiler = await webpack(dir, { buildId })
const pages = (await fs.exists(`${dir}/pages`)) ? `${dir}/pages` : undefined
if (!pages) {
return buildServer([server], {
base: dir,
outDir: join(buildDir, 'server'),
staticDir: join(buildDir, 'bundles', '_static')
})
}
try {
const [stats] = await Promise.all([
runCompiler(compiler),
await buildServer([pages, server].filter(Boolean), {
base: dir,
outDir: join(buildDir, 'server'),
staticDir: join(buildDir, 'bundles', '_static')
})
])
await writeBuildStats(buildDir, stats)
await writeBuildId(buildDir, buildId)
} catch (err) {
console.error(`> Failed to build on ${buildDir}`)
throw err
}
}
function runCompiler (compiler) {
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
if (err) return reject(err)
const jsonStats = stats.toJson()
if (jsonStats.errors.length > 0) {
const error = new Error(jsonStats.errors[0])
error.errors = jsonStats.errors
error.warnings = jsonStats.warnings
return reject(error)
}
resolve(jsonStats)
})
})
}
async function writeBuildStats (dir, stats) {
const entrypoints = {}
Object.keys(stats.entrypoints).forEach(name => {
entrypoints[name] = {
chunks: stats.entrypoints[name].assets.filter(name => !/\.map$/.test(name))
}
})
const runtimePath = join(dir, 'webpack-entrypoints.json')
await fs.writeFile(runtimePath, JSON.stringify(entrypoints, undefined, 2), 'utf8')
const statsPath = join(dir, 'webpack-stats.json')
await fs.writeFile(statsPath, JSON.stringify(stats), 'utf8')
}
async function writeBuildId (dir, buildId) {
const buildIdPath = join(dir, 'BUILD_ID')
await fs.writeFile(buildIdPath, buildId, 'utf8')
}
| JavaScript | 0 | @@ -1703,16 +1703,51 @@
t(name))
+.map(name =%3E (%7B files: %5B name %5D %7D))
%0A %7D%0A
|
fb53937a89cea90048d4417ce6d531108670475c | Replace debug with console.log | lib/relationships.js | lib/relationships.js | 'use strict'
var _ = require('lodash')
var utils = require('./utils')
module.exports = function (app, options) {
// get remote methods.
// set strong-remoting for more information
// https://github.com/strongloop/strong-remoting
var remotes = app.remotes()
var id, data, model
remotes.before('**', function (ctx, next) {
if (utils.shouldNotApplyJsonApi(ctx, options)) {
return next()
}
var allowedMethodNames = ['updateAttributes', 'patchAttributes']
var methodName = ctx.method.name
if (allowedMethodNames.indexOf(methodName) === -1) return next()
id = ctx.req.params.id
data = options.data
model = utils.getModelFromContext(ctx, app)
relationships(id, data, model)
next()
})
// for create
remotes.after('**', function (ctx, next) {
if (utils.shouldNotApplyJsonApi(ctx, options)) {
return next()
}
if (ctx.method.name !== 'create') return next()
if (ctx.result && ctx.result.data) {
id = ctx.result.data.id
data = options.data
model = utils.getModelFromContext(ctx, app)
relationships(id, data, model)
}
next()
})
}
function relationships (id, data, model) {
if (!data || !data.data || !id || !model || !data.data.relationships) {
return
}
_.each(data.data.relationships, function (relationship, name) {
var serverRelation = model.relations[name]
if (!serverRelation) return
var type = serverRelation.type
// don't handle belongsTo in relationships function
if (type === 'belongsTo') return
var modelTo = serverRelation.modelTo
var fkName = serverRelation.keyTo
if (type === 'belongsTo') {
fkName = serverRelation.keyFrom
modelTo = serverRelation.modelFrom
}
if (!modelTo) {
return false
}
var setTo = {}
setTo[fkName] = null
var where = {}
where[fkName] = id
// remove all relations to the model (eg .: post/1)
if (type !== 'belongsTo') {
modelTo.updateAll(where, setTo, function (err, info) {
if (err) console.log(err)
})
}
var idToFind = null
if (_.isArray(relationship.data)) {
// find all instance from the relation data eg
// [{type: "comments", id: 1}, {type: "comments", id: 2}]
_.each(relationship.data, function (item) {
idToFind = item.id
if (type === 'belongsTo') {
where[fkName] = item.id
idToFind = id
}
updateRelation(modelTo, idToFind, where)
})
if (serverRelation.modelThrough) {
var modelThrough = serverRelation.modelThrough
var key = keyByModel(modelThrough, modelTo)
var data = {}
data[fkName] = id
var stringIds = false
var payloadIds = _.map(relationship.data, function (item) {
if (typeof item.id === 'string') {
stringIds = true
}
return item.id
})
modelThrough.find({where: data, fields: key}, function(err, instances) {
if (err) return
var serverIds = _.map(instances, function(instance) {
return stringIds ? instance[key].toString() : instance[key]
})
// to delete
var toDelete = _.difference(serverIds, payloadIds)
_.each(toDelete, function (id) {
data[key] = id
modelThrough.destroyAll(data)
})
// new
var newAssocs = _.difference(payloadIds, serverIds)
_.each(newAssocs, function (id) {
data[key] = id
modelThrough.create(data)
})
})
}
} else {
if (relationship.data === null) {
where[fkName] = null
updateRelation(model, id, where)
return
}
idToFind = relationship.data.id
if (type === 'belongsTo') {
idToFind = id
where[fkName] = relationship.data.id
}
// relationship: {data: {type: "comments": id: 1}}
updateRelation(modelTo, idToFind, where)
}
})
return
}
// if the instance exist, then update it (create relationship),
// according to JSON API spec we MUST NOT create new ones
function updateRelation (model, id, data) {
model.findById(id, function (err, instance) {
if (err) console.log(err)
if (instance) {
instance.updateAttributes(data)
}
})
}
function keyByModel (assocModel, model) {
var key = null
_.each(assocModel.relations, function (relation) {
if (relation.modelTo.modelName === model.modelName) {
key = relation.keyFrom
}
})
if (key === null) {
console.log('Can not find relation for ' + model.modelName)
}
return key
}
| JavaScript | 0.998953 | @@ -63,16 +63,75 @@
/utils')
+%0Avar debug = require('debug')('loopback-component-jsonapi')
%0A%0Amodule
@@ -4644,26 +4644,20 @@
) %7B%0A
-console.lo
+debu
g('Can n
|
950451086b787588faa039f677549a1b13980e1f | Set change reason in MyTime | JIRA-CSC-Utils.user.js | JIRA-CSC-Utils.user.js | // ==UserScript==
// @name JIRA Enhancements for CSC
// @namespace http://csc.com/
// @version 0.6
// @description Adds a description template to new JIRA tasks.
// @homepageURL https://github.com/scytalezero/JIRA-CSC-Utils
// @updateURL https://github.com/scytalezero/JIRA-CSC-Utils/raw/master/JIRA-CSC-Utils.user.js
// @downloadURL https://github.com/scytalezero/JIRA-CSC-Utils/raw/master/JIRA-CSC-Utils.user.js
// @author bcreel2@csc.com
// @match https://cscjranor004.csc-fsg.com/browse/*
// @match https://mytime.csc.com/*
// @grant none
// ==/UserScript==
switch(document.domain) {
case "cscjranor004.csc-fsg.com":
fixJira();
break;
case "mytime.csc.com":
fixMytime();
break;
}
function fixMytime() {
//Watch for a location box and set it if unset
window.setInterval(function() {
if ( ($("#location").length > 0) && ($("#location").val() === "") ) {
$("#location").val("WL01").selectmenu("refresh");
$("#timeInput").focus().select();
}
}, 500);
}
function fixJira() {
//Observe changes to the description section
Out("Adding description watcher");
jQuery("body").on('DOMSubtreeModified',function() {
if ( (jQuery("#description").length > 0) && (jQuery("#description").text().length === 0) ) {
Out("Adding description template");
jQuery("#description").text("*Business Impact:* \n\n*Description:* \n\n*Steps to Recreate:*\n# \n\n*Expected Results:* \n\n*Resolution Description:* \n\n*SVN Revision/s:* ");
}
})
}
function Out(buffer) {
console.log("[JIRA CSC] " + buffer);
}
| JavaScript | 0.000001 | @@ -113,9 +113,9 @@
0.
-6
+7
%0A//
@@ -1041,16 +1041,246 @@
;%0A %7D%0A
+ if ( ($(%22#change-reason%22).length %3E 0) && ($(%22#change-reason%22).val() === %22%22) ) %7B%0A $(%22#change-reason%22).val(%2201%22).selectmenu(%22refresh%22);%0A window.setTimeout(function() %7B $(%22#timeInput%22).focus().select(); %7D, 2000);%0A %7D%0A
%7D, 500
@@ -1776,12 +1776,265 @@
%7D%0A
-
%7D)
+;%0A%7D%0A%0Afunction actionOnAvailable(selector, action) %7B%0A var intervalId = window.setInterval(function() %7B%0A if ($(selector).length %3E 0) %7B%0A Out(%22Performing action on available%22);%0A action();%0A window.clearTimeout(intervalId);%0A %7D%0A %7D, 500);
%0A%7D%0A%0A
|
c8db41f95afa9c14652dfe15b4a44674a69369d8 | support display page number for PXCacheImageTouchable | src/components/PXCacheImageTouchable.js | src/components/PXCacheImageTouchable.js | import React, { Component } from 'react';
import Loader from './Loader';
import PXTouchable from './PXTouchable';
import PXCacheImage from './PXCacheImage';
import { globalStyleVariables } from '../styles';
class PXCacheImageTouchable extends Component {
constructor(props) {
const { initWidth, initHeight } = props;
super(props);
this.state = {
width: initWidth,
height: initHeight,
loading: true,
};
}
handleOnFoundImageSize = (width, height, url) => {
if (width && height) {
const newWidth = width > globalStyleVariables.WINDOW_WIDTH
? globalStyleVariables.WINDOW_WIDTH
: width;
const newHeight =
(width > globalStyleVariables.WINDOW_WIDTH
? globalStyleVariables.WINDOW_WIDTH
: width) *
height /
width;
this.setState({
width: newWidth,
height: newHeight,
loading: false,
});
if (this.props.onFoundImageSize) {
this.props.onFoundImageSize(newWidth, newHeight, url);
}
}
};
render() {
const { uri, style, imageStyle, onPress } = this.props;
const { width, height, loading } = this.state;
return (
<PXTouchable
style={[
style,
{
width,
height,
},
]}
onPress={onPress}
>
{loading && <Loader />}
<PXCacheImage
uri={uri}
style={imageStyle}
onFoundImageSize={this.handleOnFoundImageSize}
/>
</PXTouchable>
);
}
}
export default PXCacheImageTouchable;
| JavaScript | 0 | @@ -35,16 +35,71 @@
react';%0A
+import %7B View, Text, StyleSheet %7D from 'react-native';%0A
import L
@@ -121,16 +121,16 @@
oader';%0A
-
import P
@@ -256,16 +256,222 @@
yles';%0A%0A
+const styles = StyleSheet.create(%7B%0A pageNumberContainer: %7B%0A flex: 1,%0A alignItems: 'center',%0A justifyContent: 'center',%0A %7D,%0A pageNumberText: %7B%0A fontSize: 18,%0A fontWeight: 'bold',%0A %7D,%0A%7D);%0A%0A
class PX
@@ -1339,16 +1339,28 @@
t %7B uri,
+ pageNumber,
style,
@@ -1621,16 +1621,16 @@
%3E%0A
-
@@ -1640,16 +1640,214 @@
ading &&
+%0A pageNumber &&%0A %3CView style=%7Bstyles.pageNumberContainer%7D%3E%0A %3CText style=%7Bstyles.pageNumberText%7D%3E%7BpageNumber%7D%3C/Text%3E%0A %3C/View%3E%7D%0A %7Bloading && !pageNumber &&
%3CLoader
|
f32eff3a0e6c00b18855307bbbe9de743adb6141 | Add sprint goal label | src/components/TrelloCard/TrelloCard.js | src/components/TrelloCard/TrelloCard.js | // @flow
import React from 'react';
import { View, StyleSheet, Text } from 'react-native';
import * as Animatable from 'react-native-animatable';
import { Icon } from 'DailyScrum/src/components';
import appStyle from 'DailyScrum/src/appStyle';
import MemberIcon from './MemberIcon';
import PointsBadge from './PointsBadge';
import type { CardType } from '../../types';
export default (props: PropsType) => (
<View style={styles.container}>
<View style={styles.card}>
<View style={styles.labelsRow}>
{props.card &&
<View style={styles.idShortContainer}>
<Text style={styles.idShort}>#{props.card.idShort}</Text>
</View>}
</View>
{props.isSprintGoal &&
<Animatable.View animation="pulse" iterationCount="infinite" style={styles.iconContainer}>
<Icon name="star" size={30} color="#e6c60d" />
</Animatable.View>}
<Text style={[styles.title, props.isSprintGoal && { fontSize: appStyle.font.size.big, fontWeight: 'bold' }]}>
{props.card ? props.card.name : props.title}
</Text>
<View style={styles.membersRow}>
{props.card &&
props.card.points !== null &&
<View style={styles.pointsContainer}>
<PointsBadge points={(props.card.points || 0).toLocaleString()} />
</View>}
{props.card &&
<View style={styles.membersContainer}>
<View style={styles.members}>
{props.card.members.map(member => (
<View key={member.id} style={styles.member}><MemberIcon member={member} /></View>
))}
</View>
</View>}
</View>
</View>
</View>
);
const styles = StyleSheet.create({
container: {
marginHorizontal: 4, // shadow
marginVertical: 4, // shadow
},
card: {
minHeight: 20,
paddingVertical: 4,
paddingHorizontal: 8,
backgroundColor: '#fff',
borderBottomWidth: 1,
borderBottomColor: '#ccc',
borderRadius: 3,
elevation: 2,
shadowColor: appStyle.colors.darkGray,
shadowRadius: 2,
shadowOpacity: 0.5,
shadowOffset: { height: 1 },
},
labelsRow: {
flexDirection: 'row',
justifyContent: 'space-between',
},
membersRow: {
flexDirection: 'row',
},
iconContainer: {
alignItems: 'center',
marginTop: 10,
},
title: {
fontSize: appStyle.font.size.default,
color: appStyle.colors.text,
textAlign: 'center',
marginTop: 18,
marginBottom: 10,
},
membersContainer: {
flex: 5,
alignSelf: 'flex-end',
justifyContent: 'flex-end',
},
members: {
flexDirection: 'row',
alignSelf: 'flex-end',
justifyContent: 'flex-end',
right: -4,
},
member: {
marginLeft: 5,
},
idShortContainer: {
position: 'absolute',
top: -4,
left: -8,
zIndex: 1,
backgroundColor: 'gold',
justifyContent: 'center',
alignItems: 'center',
height: 16,
paddingHorizontal: 3,
borderRadius: 3,
},
idShort: {
fontSize: 11,
fontWeight: 'bold',
},
pointsContainer: {
flex: 1,
flexShrink: 1,
left: -4,
justifyContent: 'flex-end',
alignItems: 'flex-start',
},
});
type PropsType = {
title?: string,
isSprintGoal?: boolean,
card?: CardType,
};
| JavaScript | 0.008559 | @@ -705,24 +705,76 @@
rintGoal &&%0A
+ %3CView style=%7Bstyles.sprintGoalContainer%7D%3E%0A
%3CAni
@@ -870,16 +870,18 @@
+
%3CIcon na
@@ -927,16 +927,18 @@
+
%3C/Animat
@@ -943,24 +943,105 @@
atable.View%3E
+%0A %3CText style=%7Bstyles.sprintGoalText%7D%3ESprint Goal%3C/Text%3E%0A %3C/View%3E
%7D%0A %3CTex
@@ -3319,16 +3319,171 @@
',%0A %7D,%0A
+ sprintGoalContainer: %7B%0A alignItems: 'center',%0A %7D,%0A sprintGoalText: %7B%0A color: appStyle.primaryDark,%0A fontSize: 12,%0A fontWeight: '300',%0A %7D,%0A
%7D);%0A%0Atyp
|
a7476037d10241fda8afc9931b30491564ce2b26 | update -> push | NullTransport.js | NullTransport.js | /*
* NullTransport.js
*
* David Janes
* IOTDB.org
* 2015-08-17
*
* Copyright [2013-2015] [David P. Janes]
*
* 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 iotdb = require('iotdb');
var iotdb_transport = require('iotdb-transport');
var errors = iotdb_transport.errors;
var _ = iotdb._;
var path = require('path');
var util = require('util');
var url = require('url');
var logger = iotdb.logger({
name: 'iotdb-transport-proto',
module: 'NullTransport',
});
/* --- constructor --- */
/**
* Create a transport for Null.
*/
var NullTransport = function (initd, native) {
var self = this;
self.initd = _.defaults(
initd,
{
},
iotdb.keystore().get("/transports/NullTransport/initd"),
{
prefix: ""
}
);
self.native = native;
};
NullTransport.prototype = new iotdb_transport.Transport;
NullTransport.prototype._class = "NullTransport";
/* --- methods --- */
/**
* See {iotdb_transport.Transport#Transport} for documentation.
*/
NullTransport.prototype.list = function(paramd, callback) {
var self = this;
if (arguments.length === 1) {
paramd = {};
callback = arguments[0];
}
self._validate_list(paramd, callback);
callback({
end: true,
});
};
/**
* See {iotdb_transport.Transport#Transport} for documentation.
*/
NullTransport.prototype.added = function(paramd, callback) {
var self = this;
if (arguments.length === 1) {
paramd = {};
callback = arguments[0];
}
self._validate_added(paramd, callback);
};
/**
* See {iotdb_transport.Transport#Transport} for documentation.
*/
NullTransport.prototype.get = function(paramd, callback) {
var self = this;
self._validate_get(paramd, callback);
callback({
id: paramd.id,
band: paramd.band,
value: null,
error: new errors.NotFound(),
});
};
/**
* See {iotdb_transport.Transport#Transport} for documentation.
*/
NullTransport.prototype.update = function(paramd, callback) {
var self = this;
self._validate_update(paramd, callback);
callback({
id: paramd.id,
band: paramd.band,
error: new errors.NotImplemented(),
});
};
/**
* See {iotdb_transport.Transport#Transport} for documentation.
*/
NullTransport.prototype.updated = function(paramd, callback) {
var self = this;
if (arguments.length === 1) {
paramd = {};
callback = arguments[0];
}
self._validate_updated(paramd, callback);
};
/**
* See {iotdb_transport.Transport#Transport} for documentation.
*/
NullTransport.prototype.remove = function(paramd, callback) {
var self = this;
self._validate_remove(paramd, callback);
callback({
id: paramd.id,
band: paramd.band,
error: new errors.NotImplemented(),
});
};
/* --- internals --- */
/**
* API
*/
exports.NullTransport = NullTransport;
| JavaScript | 0 | @@ -2565,22 +2565,19 @@
ototype.
-update
+put
= funct
|
e00309ff557475ee1005c114f91b4de68e2b9bdd | Refactor functions order | src/assets/admin-scripts/img-upload/script.js | src/assets/admin-scripts/img-upload/script.js | $(function() {
$('#dropBox').click(function() {
$('#fileInput').click();
});
$(document).on('drop dragover', function (e) {
e.preventDefault();
});
$('#fileInput').on('change', fileUpload);
});
function fileUpload(e) {
$('#dropBox').html(e.target.value + ' uploading...');
var file = e.target.files[0];
if (!file.type.match('image.*')) {
$('#dropBox').html('Please choose an images file.');
} else {
var img = document.createElement('img');
img.src = window.URL.createObjectURL(file);
$('#thumbnail').html(img);
img.onload = function() {
var canvas = createCanvas(300, 300, img);
var fd = makeFormData(canvas);
makeRequest(fd);
};
}
}
function createCanvas(maxW, maxH, img) {
var canvas = document.createElement('canvas');
var width = img.width;
var height = img.height;
if (width > height) {
if (width > maxW) {
height *= maxW / width;
width = maxW;
}
} else {
if (height > maxH) {
width *= maxH / height;
height = maxH;
}
}
canvas.width = width;
canvas.height = height;
return drawFromCanvas(canvas, img, width, height);
}
function drawFromCanvas(canvas, img, w, h) {
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, w, h);
ctx.drawImage(img, 0, 0, w, h);
return canvas;
}
function makeFormData(canvas) {
var dataURL = canvas.toDataURL('image/jpeg', 0.9);
var blob = dataURItoBlob(dataURL);
var fd = new FormData();
fd.append('file', blob, 'blob.jpeg');
return fd;
}
function dataURItoBlob(dataURI) {
var splits = dataURI.split(',')[1];
var isBase64 = dataURI.split(',')[0].indexOf('base64') >= 0;
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var byteString = isBase64 ? atob(splits) : unescape(splits);
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
function makeRequest(fd) {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.send(fd);
xhr.onload = function () {
var response = JSON.parse(xhr.responseText);
replyToUser(xhr.status, response.status);
};
}
function replyToUser(status, response) {
var message = '';
if (status === 200 && response == 'ok') {
message = 'File has been uploaded successfully. Click to upload another.';
} else if (response == 'type_err') {
message = 'Please choose an images file. Click to upload another.';
} else {
message = 'Some problem occured, please try again.';
}
$('#dropBox').html(message);
}
| JavaScript | 0.000002 | @@ -1363,223 +1363,8 @@
%0A%7D%0A%0A
-function makeFormData(canvas) %7B%0A var dataURL = canvas.toDataURL('image/jpeg', 0.9);%0A var blob = dataURItoBlob(dataURL);%0A var fd = new FormData();%0A%0A fd.append('file', blob, 'blob.jpeg');%0A%0A return fd;%0A%7D%0A%0A
func
@@ -1823,24 +1823,239 @@
tring%7D);%0A%7D%0A%0A
+function makeFormData(canvas) %7B%0A var dataURL = canvas.toDataURL('image/jpeg', 0.9);%0A var blob = dataURItoBlob(dataURL);%0A var fd = new FormData();%0A%0A fd.append('file', blob, 'blob.jpeg');%0A%0A return fd;%0A%7D%0A%0A
function mak
|
edc0f512671a835cd066527fbc96b4a8ef3d8458 | Update ele changelog. | src/Parser/Shaman/Elemental/CHANGELOG.js | src/Parser/Shaman/Elemental/CHANGELOG.js | export default `
28-08-2017 - Added Flame Shock, Totem Mastery, Elemental Blast, Ascendance, Lightning Rod Uptimes (by fasib).
28-08-2017 - Fixed Maelstrom Tab (by fasib).
04-06-2017 - Added basic <span class="Shaman">Elemental Shaman</span> support by <b>@fasib</b>.
`;
| JavaScript | 0 | @@ -10,16 +10,66 @@
fault %60%0A
+26-10-2017 - Fix Totem Mastery Uptime (by fasib).%0A
28-08-20
|
fa331ef3d973afca91450144eba829c6025fc8a4 | fix of 9a test | deploy/post_deploy_testing/cypress/integration/09a_create_biosample.js | deploy/post_deploy_testing/cypress/integration/09a_create_biosample.js |
import { navUserAcctDropdownBtnSelector } from './../support/variables';
/**
* Test you can visit the Biosample create page.
*/
describe('Biosample create page', function () {
context('Cypress test user profile create biosample page', function () {
var testItemsToDelete = [];
it('Main page visit', function () {
cy.visit('/');
});
it('Ensure logged in, visit biosample create page ', function () {
//Login CypressTest user
cy.login4DN({ 'email': 'u4dntestcypress@gmail.com' }).end()
.get(navUserAcctDropdownBtnSelector).then((accountListItem) => {
expect(accountListItem.text()).to.contain('Cypress');
}).end();
cy.visit('/search/?type=Biosample').get(".above-results-table-row .btn").should('contain', 'Create New')
.get("a.btn.btn-primary.btn").should('contain', 'Create New').click().end().wait(10000);
//Submit create biosample data name
const identifier = ("bs-test-" + new Date().getTime());
cy.get('.modal-dialog input#aliasInput.form-control').focus().type(identifier).wait(100).end()
.get("button.btn-primary.btn").should('contain', 'Submit').click().end().wait(10000);
//Add biosources data file
cy.get(".field-row[data-field-name=biosource] .dropdown-toggle").click().wait(100)
.get(".field-row[data-field-name=biosource] .search-selection-menu-body .text-input-container input.form-control")
.type("0f011b1e-b772-4f2a-8c24-cc55de28a994").wait(10000)
.get(".field-row[data-field-name=biosource] .search-selection-menu-body .scroll-items .dropdown-item")
.should('have.length', 1).click().end();
//Click Validate button
cy.get(".action-buttons-container .btn").within(function () {
return cy.contains('Validate').click().end();
}).end()
//Click Submit button
.get(".action-buttons-container .btn").within(function () {
return cy.contains('Submit').click().end().wait(500);
}).end()
//Navigate new biosample data page
.get(".action-buttons-container .btn").within(function () {
return cy.contains('Skip').click().end().wait(1000);
}).end();
afterEach(function () {
cy.get('script[data-prop-name=context]').then(($context) => {
const context = $context.text();
const contextData = JSON.parse(context);
const atId = contextData['@id'];
testItemsToDelete.push(atId);//Test biosample data @id
});
});
});
it('Biosample delete data', function () {
// Log in _as admin_.
cy.visit('/').login4DN({ 'email': '4dndcic@gmail.com', 'useEnvToken': true }).wait(500);
// Delete item biosample data.
cy.wrap(testItemsToDelete).each(function (testItem) { // Synchronously process async stuff.
cy.window().then(function (w) {
const token = w.fourfront.JWT.get();
cy.request({
method: "DELETE",
url: testItem,
headers: {
'Authorization': 'Bearer ' + token,
"Content-Type": "application/json",
"Accept": "application/json"
}
}).end().request({
method: "PATCH",
url: testItem,
headers: {
'Authorization': 'Bearer ' + token,
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify({ "tags": ["deleted_by_cypress_test"] })
});
});
});
// Empty the array now that we're done.
testItemsToDelete = [];
});
});
});
| JavaScript | 0 | @@ -1967,24 +1967,35 @@
lick().end()
+.wait(1000)
;%0A
|
f9394a64d555068ee003629e7c83b56cefc15b97 | Make IDL extraction work with raw ReSpec documents (#3) | extract-webidl.js | extract-webidl.js | var jsdom = require('jsdom');
function extract(url, cb) {
jsdom.env(url, [],
function(err, window) {
if (err) return cb(err);
var generator = window.document.querySelector("meta[name='generator']");
if (generator && generator.content.match(/bikeshed/i)) {
return extractBikeshedIdl(window.document, cb);
}
if (window.document.getElementById('respecDocument')) {
return extractRespecIdl(window.document, cb);
}
return cb(new Error("Unrecognized generator of spec for " + url));
}
);
}
function extractBikeshedIdl(doc, cb) {
var idlHeading = doc.getElementById('idl-index');
if (idlHeading) {
var nextSibling = idlHeading.nextSibling;
while(nextSibling && nextSibling.nodeType != 1) {
nextSibling = nextSibling.nextSibling
}
return cb(null, nextSibling.textContent);
}
return cb(null, "");
}
function extractRespecIdl(doc, cb) {
var idlNodes = doc.querySelectorAll("pre.idl");
var idl = "";
for (var i = 0 ; i < idlNodes.length; i++) {
idl += "\n" + idlNodes[i].textContent;
}
cb(null, idl);
}
module.exports.extract = extract;
if (require.main === module) {
var url = process.argv[2];
if (!url) {
console.error("Required URL parameter missing");
process.exit(2);
}
extract(url, function(err, idl) {
if (err) {
console.error(err);
process.exit(64);
}
console.log(idl);
});
}
| JavaScript | 0 | @@ -70,30 +70,169 @@
env(
-url, %5B%5D,%0A
+%7B%0A url: url,%0A features: %7B%0A FetchExternalResources: %5B'script'%5D,%0A ProcessExternalResources: %5B'script'%5D%0A %7D,%0A done:
fun
@@ -248,30 +248,24 @@
, window) %7B%0A
-
@@ -301,22 +301,16 @@
-
-
var gene
@@ -382,30 +382,24 @@
-
-
if (generato
@@ -455,37 +455,24 @@
- return
extractBikes
@@ -516,33 +516,14 @@
- %7D%0A
+%7D else
if
@@ -591,28 +591,318 @@
+extractRespecIdl(window.document, cb);%0A %7D else if (window.respecConfig) %7B%0A if (!window.respecConfig.postProcess) %7B%0A window.respecConfig.postProcess = %5B%5D;%0A %7D%0A window.respecConfig.postProcess.push(function() %7B%0A
-return
extract
@@ -941,35 +941,35 @@
- %7D
+%7D);
%0A
@@ -965,28 +965,40 @@
+%7D else %7B%0A
-return
cb(new
@@ -1054,34 +1054,32 @@
));%0A
-
%7D%0A )
@@ -1072,21 +1072,23 @@
+%7D%0A
-
+%7D
);%0A%7D%0A%0Afu
|
78f2f7cfd03cc571ce3c48fd4fb1ecbb2a80fc22 | Add in voip mute video/audio code. Needs dev js-sdk | src/controllers/molecules/RoomHeader.js | src/controllers/molecules/RoomHeader.js | /*
Copyright 2015 OpenMarket 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';
/*
* State vars:
* this.state.call_state = the UI state of the call (see CallHandler)
*/
var React = require('react');
var dis = require("../../dispatcher");
var CallHandler = require("../../CallHandler");
module.exports = {
propTypes: {
room: React.PropTypes.object.isRequired,
editing: React.PropTypes.bool,
onSettingsClick: React.PropTypes.func,
onSaveClick: React.PropTypes.func,
},
getDefaultProps: function() {
return {
editing: false,
onSettingsClick: function() {},
onSaveClick: function() {},
};
},
componentDidMount: function() {
this.dispatcherRef = dis.register(this.onAction);
if (this.props.room) {
var call = CallHandler.getCallForRoom(this.props.room.roomId);
var callState = call ? call.call_state : "ended";
this.setState({
call_state: callState
});
}
},
componentWillUnmount: function() {
dis.unregister(this.dispatcherRef);
},
onAction: function(payload) {
// don't filter out payloads for room IDs other than props.room because
// we may be interested in the conf 1:1 room
if (payload.action !== 'call_state' || !payload.room_id) {
return;
}
var call = CallHandler.getCallForRoom(payload.room_id);
var callState = call ? call.call_state : "ended";
this.setState({
call_state: callState
});
},
onVideoClick: function() {
dis.dispatch({
action: 'place_call',
type: "video",
room_id: this.props.room.roomId
});
},
onVoiceClick: function() {
dis.dispatch({
action: 'place_call',
type: "voice",
room_id: this.props.room.roomId
});
},
onHangupClick: function() {
var call = CallHandler.getCallForRoom(this.props.room.roomId);
if (!call) { return; }
dis.dispatch({
action: 'hangup',
// hangup the call for this room, which may not be the room in props
// (e.g. conferences which will hangup the 1:1 room instead)
room_id: call.roomId
});
}
};
| JavaScript | 0.000006 | @@ -2840,21 +2840,673 @@
%7D);%0A
+ %7D,%0A onMuteAudioClick: function() %7B%0A var call = CallHandler.getCallForRoom(this.props.room.roomId);%0A if (!call) %7B%0A return;%0A %7D%0A var newState = !call.isMicrophoneMuted();%0A call.setMicrophoneMuted(newState);%0A this.setState(%7B%0A audioMuted: newState%0A %7D);%0A %7D,%0A onMuteVideoClick: function() %7B%0A var call = CallHandler.getCallForRoom(this.props.room.roomId);%0A if (!call) %7B%0A return;%0A %7D%0A var newState = !call.isLocalVideoMuted();%0A call.setLocalVideoMuted(newState);%0A this.setState(%7B%0A videoMuted: newState%0A %7D);%0A
%7D%0A%7D;%0A
|
db52b6526501060b7492e208e66c0e328e566dc0 | Fix rule deletion | src/mist/io/static/js/app/controllers/rules.js | src/mist/io/static/js/app/controllers/rules.js | define('app/controllers/rules', ['app/models/rule', 'ember'],
//
// Rules Controller
//
// @returns Class
//
function(Rule) {
'use strict';
return Ember.ArrayController.extend({
content: [],
command: null,
commandRule: null,
creationPending: false,
metricList: [
'load',
'cpu',
'ram',
'disk-write',
'network-tx'
],
operatorList: [{
'title': 'gt',
'symbol': '>'
}, {
'title': 'lt',
'symbol': '<'
}],
actionList: [
'alert',
'reboot',
'destroy',
'command'
],
setContent: function(rules) {
if (!rules) return;
var that = this;
Ember.run(function() {
for (var ruleId in rules) {
var rule = rules[ruleId];
rule.id = ruleId;
rule.actionToTake = rules[ruleId].action;
rule.operator = that.getOperatorByTitle(rules[ruleId].operator);
rule.metric = Mist.metricsController.getMetric(rules[ruleId].metric);
rule.machine = Mist.backendsController.getMachine(rule.machine, rule.backend) || rule.machine;
that.content.pushObject(Rule.create(rule));
}
});
},
getRuleById: function(ruleId) {
return this.content.findBy('id', ruleId);
},
getOperatorByTitle: function(ruleTitle) {
return this.operatorList.findBy('title', ruleTitle);
},
creationPendingObserver: function() {
if (this.creationPending)
$('#add-rule-button').addClass('ui-state-disabled');
else
$('#add-rule-button').removeClass('ui-state-disabled');
}.observes('creationPending'),
newRule: function(machine, metric, operator, value, actionToTake) {
this.set('creationPending', true);
var that = this;
Mist.ajax.POST('/rules', {
'backendId': machine.backend.id,
'machineId': machine.id,
'metric': metric,
'operator': operator.title,
'value': value,
'action': actionToTake
}).success(function(data) {
info('Successfully created rule ', data.id);
that.set('creationPending', false);
var rule = Rule.create({
'id': data.id,
'value': value,
'metric': Mist.metricsController.getMetric(metric),
'machine': machine,
'operator': operator,
'maxValue': data.max_value,
'actionToTake': actionToTake,
});
that.pushObject(rule);
that.redrawRules();
}).error(function(message) {
Mist.notificationController.notify('Error while creating rule: ' + message);
that.set('creationPending', false);
});
},
deleteRule: function (rule) {
var that = this;
rule.set('pendingAction', true);
Mist.ajax.DELETE('/rules/' + rule, {
}).success(function(){
Mist.rulesController.removeObject(rule);
Mist.rulesController.redrawRules();
}).error(function(message) {
Mist.notificationController.notify('Error while deleting rule: ' + message);
rule.set('pendingAction', false);
});
},
updateRule: function(id, metric, operator, value, actionToTake, command) {
var rule = this.getRuleById(id);
if (!rule) {
return false;
}
// Make sure parameters are not null
if (!value) { value = rule.value; }
if (!metric) { metric = rule.metric.id; }
if (!command) { command = rule.command; }
if (!operator) { operator = rule.operator; }
if (!actionToTake) { actionToTake = rule.actionToTake; }
// Check if anything changed
if (value == rule.value &&
metric == rule.metric.id &&
command == rule.command &&
actionToTake == rule.actionToTake &&
operator.title == rule.operator.title ) {
return false;
}
var that = this;
rule.set('pendingAction', true);
Mist.ajax.POST('/rules', {
'id': id,
'value': value,
'metric': metric,
'command': command,
'operator': operator.title,
'action': actionToTake,
}).success(function(data) {
info('Successfully updated rule ', id);
rule.set('pendingAction', false);
rule.set('value', value);
rule.set('metric', Mist.metricsController.getMetric(metric));
rule.set('command', command);
rule.set('operator', operator);
rule.set('actionToTake', actionToTake);
var maxvalue = parseInt(rule.maxValue);
var curvalue = parseInt(rule.value);
if (curvalue > maxvalue) {
rule.set('value', maxvalue);
}
}).error(function(message) {
Mist.notificationController.notify('Error while updating rule: ' + message);
rule.set('pendingAction', false);
});
},
changeRuleValue: function(event) {
var rule_id = $(event.currentTarget).attr('id');
var rule_value = $(event.currentTarget).find('.ui-slider-handle').attr('aria-valuenow');
this.updateRule(rule_id, null, null, rule_value);
},
setSliderEventHandlers: function() {
function showSlider(event) {
var rule_id = $(event.currentTarget).parent().attr('id');
var rule = Mist.rulesController.getRuleById(rule_id);
if (rule.metric.max_value) {
$(event.currentTarget).addClass('open');
$(event.currentTarget).find('.ui-slider-track').fadeIn();
}
}
function hideSlider(event) {
$(event.currentTarget).find('.ui-slider-track').fadeOut();
$(event.currentTarget).find('.ui-slider').removeClass('open');
Mist.rulesController.changeRuleValue(event);
}
$('.rules-container .ui-slider').on('tap', showSlider);
$('.rules-container .ui-slider').on('click', showSlider);
$('.rules-container .ui-slider').on('mouseover', showSlider);
$('#single-machine').on('tap', hideSlider);
$('.rules-container .rule-box').on('mouseleave', hideSlider);
},
removeSliderEventHandlers: function() {
$('.rules-container .ui-slider').off('tap');
$('.rules-container .ui-slider').off('click');
$('.rules-container .ui-slider').off('mouseover');
$('#single-machine').off('tap');
$('.rules-container .rule-box').off('mouseleave');
},
redrawRules: function() {
var that = this;
Ember.run.next(function() {
that.removeSliderEventHandlers();
$('.rule-box').trigger('create');
that.setSliderEventHandlers();
});
},
});
}
);
| JavaScript | 0.000132 | @@ -3736,16 +3736,19 @@
' + rule
+.id
, %7B%0A
|
1cd7e775f03a41f00e15f714f8af80716f3a49ce | Add missing fields for Threads for seeding | src/modules/content-seeding/content-seeding.js | src/modules/content-seeding/content-seeding.js | /* @flow */
/* eslint-disable no-param-reassign*/
import log from 'winston';
import fs from 'fs';
import uuid from 'node-uuid';
import template from 'lodash/template';
import { bus } from '../../core-server';
import Thread from '../../models/thread';
import { TYPE_ROOM,
TAG_ROOM_AREA,
TAG_ROOM_CITY,
TAG_ROOM_SPOT
} from '../../lib/Constants';
type ThreadTemplate = {
title: string;
body: string;
creator: string;
}
function tagStringToNumber(tag) {
switch (tag) {
case 'city':
return TAG_ROOM_CITY;
case 'area':
return TAG_ROOM_AREA;
case 'spot':
return TAG_ROOM_SPOT;
}
return '';
}
function seedContent(room) {
log.info('something:');
fs.readdir('./templates/seed-content', (err, files: any) => {
const changes = {
entities: {}
};
if (err || !files || files.length === 0) return;
/*
Split filenames into array of format: [tag, number, option]
Filter out files that doesn't belong to the current room's tags
*/
files = files.map(file => file.split('-'))
.filter(e => e.length === 3)
.filter(
e => room.tags.indexOf(tagStringToNumber(e[0])) > -1
);
/*
group templates into tags.
format: {
'area-1': [ ['area', 1, 'a.json'], ['area', 1, 'b.json']]
'area-2': [ ['area', 2, 'a.json'], ['area', 2, 'b.json']]
}
*/
files = files.reduce((prev, cur) => {
prev[cur[0] + '-' + cur[1]] = prev[cur[0] + '-' + cur[1]] || [];
prev[cur[0] + '-' + cur[1]].push(cur);
return prev;
}, {});
// randomly pick a file for each tag:
files = Object.keys(files).map(e => {
return files[e][Math.ceil(Math.random() * files[e].length) - 1];
})
.map(e => e.join('-')) // get the template filenames back
.map(e => fs.readFileSync('./templates/seed-content/' + e).toString())
.map(e => {
try {
return JSON.parse(e);
} catch (error) {
return null;
}
});
files.forEach((e:?ThreadTemplate) => {
const id = uuid.v4();
if (!e) return;
changes.entities[id] = new Thread({
id,
name: template(e.title)({
name: room.name
}),
parents: [ room.id ].concat(room.parents),
creator: e.creator
});
});
bus.emit('change', changes);
});
}
bus.on('postchange', (changes, next) => {
const entities = changes && changes.entities || {};
Object.keys(entities).filter(e => (
entities[e].type === TYPE_ROOM &&
entities[e].createTime === entities[e].updateTime
)).map(e => entities[e]).forEach(seedContent);
next();
});
log.info('Content seeding module ready.');
| JavaScript | 0 | @@ -264,16 +264,30 @@
E_ROOM,%0A
+%09TYPE_THREAD,%0A
%09TAG_ROO
@@ -1993,16 +1993,39 @@
%09%09%09%09id,%0A
+%09%09%09%09type: TYPE_THREAD,%0A
%09%09%09%09name
@@ -2075,16 +2075,74 @@
%09%09%09%09%7D),%0A
+%09%09%09%09body: template(e.body)(%7B%0A%09%09%09%09%09name: room.name%0A%09%09%09%09%7D),%0A
%09%09%09%09pare
@@ -2180,16 +2180,16 @@
rents),%0A
-
%09%09%09%09crea
@@ -2202,16 +2202,45 @@
.creator
+,%0A%09%09%09%09createTime: Date.now(),
%0A%09%09%09%7D);%0A
|
7e8a0f72129c424cfa5858aa0c05e8714eb8099e | use imported one | App/Components/Text.js | App/Components/Text.js | import React from 'react';
import ReactNative, {
Text,
StyleSheet,
} from 'react-native';
import cssVar from '../Lib/cssVar';
var _Text = React.createClass({
propTypes: Text.propTypes,
setNativeProps() {
var text = this.refs.text;
text.setNativeProps.apply(text, arguments);
},
render() {
return (
<React.Text
{...this.props}
ref="text"
style={[styles.text, this.props.style || {}]}
/>
);
}
})
var styles = StyleSheet.create({
text: {
fontFamily: cssVar('fontRegular'),
color: cssVar('gray90'),
fontSize: 8 // make it small to know it's not set
}
});
export default _Text;
| JavaScript | 0 | @@ -326,22 +326,16 @@
%0A %3C
-React.
Text%0A
|
f9f0c9daa53cf9d593cadfc10c427abaf348483c | Update brunch-config.js | installer/templates/static/brunch/brunch-config.js | installer/templates/static/brunch/brunch-config.js | exports.config = {
// See http://brunch.io/#documentation for docs.
files: {
javascripts: {
joinTo: "js/app.js"
// To use a separate vendor.js bundle, specify two files path
// http://brunch.io/docs/config#-files-
// joinTo: {
// "js/app.js": /^(web\/static\/js)/,
// "js/vendor.js": /^(web\/static\/vendor)|(deps)/
// }
//
// To change the order of concatenation of files, explicitly mention here
// order: {
// before: [
// "web/static/vendor/js/jquery-2.1.1.js",
// "web/static/vendor/js/bootstrap.min.js"
// ]
// }
},
stylesheets: {
joinTo: "css/app.css",
order: {
after: ["web/static/css/app.css"] // concat app.css last
}
},
templates: {
joinTo: "js/app.js"
}
},
conventions: {
// This option sets where we should place non-css and non-js assets in.
// By default, we set this to "/web/static/assets". Files in this directory
// will be copied to `paths.public`, which is "priv/static" by default.
assets: /^(web\/static\/assets)/
},
// Phoenix paths configuration
paths: {
// Dependencies and current project directories to watch
watched: [
"web/static",
"test/static"
],
// Where to compile files to
public: "priv/static"
},
// Configure your plugins
plugins: {
babel: {
// Do not use ES6 compiler in vendor code
ignore: [/web\/static\/vendor/]
}
},
modules: {
autoRequire: {
"js/app.js": ["web/static/js/app"]
}
},
npm: {
enabled: true
}
};
| JavaScript | 0.000001 | @@ -353,11 +353,19 @@
r)%7C(
-dep
+node_module
s)/%0A
|
ceedefec54b7f7a50308b07a2697a81ef1752fc8 | Update URL when paginating groups | app/assets/javascripts/groups/index.js | app/assets/javascripts/groups/index.js | /* global Flash */
import Vue from 'vue';
import GroupFilterableList from './groups_filterable_list';
import GroupsComponent from './components/groups.vue';
import GroupFolder from './components/group_folder.vue';
import GroupItem from './components/group_item.vue';
import GroupsStore from './stores/groups_store';
import GroupsService from './services/groups_service';
import eventHub from './event_hub';
document.addEventListener('DOMContentLoaded', () => {
const el = document.getElementById('dashboard-group-app');
// Don't do anything if element doesn't exist (No groups)
// This is for when the user enters directly to the page via URL
if (!el) {
return;
}
Vue.component('groups-component', GroupsComponent);
Vue.component('group-folder', GroupFolder);
Vue.component('group-item', GroupItem);
// eslint-disable-next-line no-new
new Vue({
el,
data() {
this.store = new GroupsStore();
this.service = new GroupsService(el.dataset.endpoint);
return {
store: this.store,
isLoading: true,
state: this.store.state,
loading: true,
};
},
computed: {
isEmpty() {
return Object.keys(this.state.groups).length === 0;
},
},
methods: {
fetchGroups(parentGroup) {
let parentId = null;
let getGroups = null;
let page = null;
let sort = null;
let pageParam = null;
let sortParam = null;
let filterGroups = null;
let filterGroupsParam = null;
if (parentGroup) {
parentId = parentGroup.id;
} else {
this.isLoading = true;
}
pageParam = gl.utils.getParameterByName('page');
if (pageParam) {
page = pageParam;
}
filterGroupsParam = gl.utils.getParameterByName('filter_groups');
if (filterGroupsParam) {
filterGroups = filterGroupsParam;
}
sortParam = gl.utils.getParameterByName('sort');
if (sortParam) {
sort = sortParam;
}
getGroups = this.service.getGroups(parentId, page, filterGroups, sort);
getGroups
.then(response => response.json())
.then((response) => {
this.isLoading = false;
this.updateGroups(response, parentGroup);
})
.catch(this.handleErrorResponse);
return getGroups;
},
fetchPage(page, filterGroups, sort) {
this.isLoading = true;
return this.service
.getGroups(null, page, filterGroups, sort)
.then((response) => {
this.isLoading = false;
$.scrollTo(0);
this.updateGroups(response.json());
this.updatePagination(response.headers);
})
.catch(this.handleErrorResponse);
},
toggleSubGroups(parentGroup = null) {
if (!parentGroup.isOpen) {
this.store.resetGroups(parentGroup);
this.fetchGroups(parentGroup);
}
this.store.toggleSubGroups(parentGroup);
},
leaveGroup(group, collection) {
this.service.leaveGroup(group.leavePath)
.then((response) => {
$.scrollTo(0);
this.store.removeGroup(group, collection);
// eslint-disable-next-line no-new
new Flash(response.json().notice, 'notice');
})
.catch((response) => {
let message = 'An error occurred. Please try again.';
if (response.status === 403) {
message = 'Failed to leave the group. Please make sure you are not the only owner';
}
// eslint-disable-next-line no-new
new Flash(message);
});
},
updateGroups(groups, parentGroup) {
this.store.setGroups(groups, parentGroup);
},
updatePagination(headers) {
this.store.storePagination(headers);
},
handleErrorResponse() {
this.isLoading = false;
$.scrollTo(0);
// eslint-disable-next-line no-new
new Flash('An error occurred. Please try again.');
},
},
created() {
eventHub.$on('fetchPage', this.fetchPage);
eventHub.$on('toggleSubGroups', this.toggleSubGroups);
eventHub.$on('leaveGroup', this.leaveGroup);
eventHub.$on('updateGroups', this.updateGroups);
eventHub.$on('updatePagination', this.updatePagination);
},
beforeMount() {
let groupFilterList = null;
const form = document.querySelector('form#group-filter-form');
const filter = document.querySelector('.js-groups-list-filter');
const holder = document.querySelector('.js-groups-list-holder');
const opts = {
form,
filter,
holder,
filterEndpoint: el.dataset.endpoint,
pagePath: el.dataset.path,
};
groupFilterList = new GroupFilterableList(opts);
groupFilterList.initSearch();
},
mounted() {
this.fetchGroups()
.then((response) => {
this.updatePagination(response.headers);
this.isLoading = false;
})
.catch(this.handleErrorResponse);
},
beforeDestroy() {
eventHub.$off('fetchPage', this.fetchPage);
eventHub.$off('toggleSubGroups', this.toggleSubGroups);
eventHub.$off('leaveGroup', this.leaveGroup);
eventHub.$off('updateGroups', this.updateGroups);
eventHub.$off('updatePagination', this.updatePagination);
},
});
});
| JavaScript | 0 | @@ -2659,32 +2659,248 @@
$.scrollTo(0);%0A%0A
+ const currentPath = gl.utils.mergeUrlParams(%7B page: page %7D, window.location.href);%0A window.history.replaceState(%7B%0A page: currentPath,%0A %7D, document.title, currentPath);%0A%0A
this
@@ -2930,16 +2930,17 @@
json());
+
%0A
|
f323054736f0156cd36f5d8ed3150dd57b096bec | fix invalid object reference | app/assets/js/factories/tab_manager.js | app/assets/js/factories/tab_manager.js | ficsClient.factory("TabManager", ["ActivityNotifier", function(ActivityNotifier) {
return function(tabs) {
this.tabs = _.reduce(tabs, function(memo, data, name) {
memo[name] = new ActivityNotifier(data);
return memo;
}, {});
this.isActiveTab = function(tabName) {
return tabName === activeTabName();
};
function activeTabName() {
return _.invert(_.reduce(this.tabs, function(memo, tabData, tabName) {
memo[tabName] = tabData.active;
return memo;
}, {}))[true];
}
};
}])
| JavaScript | 0.000029 | @@ -335,16 +335,37 @@
%7D;%0A%0A
+ var self = this;%0A
func
@@ -418,20 +418,20 @@
.reduce(
-this
+self
.tabs, f
|
6d1ba1c433d2d85c37908ecd6024241cf2869c65 | correct typo | generator/timeout.js | generator/timeout.js | "use strict";
const defer = require('../promise/defer');
const isNumber = require('mout/lang/isNumber');
module.exports = function(fn, timeout) {
if(!timeout)
return fn;
if(!isNumber(timeout))
throw "timeout must be a number";
var my = function* () {
var args = [].slice.call(arguments);
var self = this;
var defered = defer();
setTimeout(defered.reject.bind(defered, "timeout"), timeout);
yield [ function*() {
var response = yield fn.applay(self, args);
defered.resolve(response);
}, defered];
return defered;
}
return my;
} | JavaScript | 0.999967 | @@ -487,17 +487,16 @@
fn.appl
-a
y(self,
|
46960e2a7005ccc5c5dd722fca906a68b1170fa5 | Set the background color of the master UIView to black. | Resources/app.js | Resources/app.js | // this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#000');
// create tab group
var tabGroup = Titanium.UI.createTabGroup();
// get platform window size
var pWidth = Ti.Platform.displayCaps.platformWidth;
var pHeight = Ti.Platform.displayCaps.platformHeight;
//
// create base UI tab and root window
//
var win1 = Titanium.UI.createWindow({
width:pWidth,
height:pHeight,
top: 0,
left: 0,
backgroundImage: 'background.png',
url: 'recipes.js',
title: 'Recipes',
barImage: 'navbar.png'
});
var tab1 = Titanium.UI.createTab({
icon:'KS_nav_views.png',
title:'Recieps',
window:win1
});
//
// create controls tab and root window
//
//create the second window for settings tab
var win2 = Titanium.UI.createWindow({
width:pWidth,
height:pHeight,
top: 0,
left: 0,
backgroundImage: 'background.png',
url: 'favorites.js',
title: 'Favorites',
barImage: 'navbar.png'
});
var tab2 = Titanium.UI.createTab({
icon:'Img/favorites_icon.png',
title:'Favorites',
window:win2
});
var label2 = Titanium.UI.createLabel({
color:'#999',
text:'I am Window 2',
font:{fontSize:20,fontFamily:'Helvetica Neue'},
textAlign:'center',
width:'auto'
});
win2.add(label2);
//
// add tabs
//
tabGroup.addTab(tab1);
tabGroup.addTab(tab2);
// open tab group
tabGroup.open();
| JavaScript | 0 | @@ -130,11 +130,11 @@
r('#
-000
+FFF
');%0A
|
867b3f680375f30d0e58daa0b10ee641055adb4d | support array entry point | src/factories/createCompilerCallback.js | src/factories/createCompilerCallback.js | // @flow
import path from 'path';
import {
Compiler,
DllPlugin
} from 'webpack';
import createDebug from 'debug';
import findInstance from '../utilities/findInstance';
import createResourceMap from './createResourceMap';
const debug = createDebug('isomorphic-webpack');
export default (compiler: Compiler, callback: Function): Function => {
const dllPlugin = findInstance(compiler.options.plugins, DllPlugin);
const manifestPath = dllPlugin.options.path;
debug('manifestPath', manifestPath);
const outputFileSystem = compiler.outputFileSystem;
return (error: Object, stats: Object) => {
if (error) {
debug('compiler error:', error);
return;
}
if (stats.compilation.errors.length) {
debug('compilation error', stats.compilation.errors);
return;
}
if (stats.compilation.missingDependencies.length) {
debug('aborting compilation; missing dependencies', stats.compilation.missingDependencies);
return;
}
const manifest = JSON.parse(outputFileSystem.readFileSync(manifestPath));
debug('manifest', manifest);
const requestMap = createResourceMap(manifest.content);
debug('requestMap', requestMap);
const entryChunkName = Object.keys(compiler.options.entry)[0];
debug('entryChunkName', entryChunkName);
const absoluteEntryChunkName = path.resolve(compiler.options.output.path, entryChunkName + '.js');
const bundleCode = outputFileSystem.readFileSync(absoluteEntryChunkName, 'utf-8');
const bundleSourceMap = JSON.parse(outputFileSystem.readFileSync(absoluteEntryChunkName + '.map', 'utf-8'));
callback({
bundleCode,
bundleSourceMap,
requestMap
});
};
};
| JavaScript | 0.000011 | @@ -1199,28 +1199,145 @@
-const entryChunkName
+let entryChunkName;%0A%0A if (Array.isArray(compiler.options.entry)) %7B%0A entryChunkName = 'main';%0A %7D else %7B%0A const bundleNames
= O
@@ -1374,58 +1374,434 @@
try)
-%5B0%5D
;%0A%0A
-debug('entryChunkName', entryChunkName);
+ if (bundleNames.length === 0) %7B%0A throw new Error('Invalid %22entry%22 configuration.');%0A %7D else if (bundleNames.length %3E 1) %7B%0A // eslint-disable-next-line no-console%0A console.log('Multiple bundles are not supported. See https://github.com/gajus/isomorphic-webpack/issues/10.');%0A%0A throw new Error('Unsupported %22entry%22 configuration.');%0A %7D%0A%0A entryChunkName = bundleNames%5B0%5D;%0A %7D
%0A%0A
|
edf026c7d047c6723c291475cfd5ecd8bd449d5b | add basic form fields to registration component | src/common/components/RegisterWindow/index.js | src/common/components/RegisterWindow/index.js | import React from 'react';
import Dialog from 'material-ui/Dialog';
export default class UserMenu extends React.Component {
constructor(props) {
super(props);
}
handleClose = () => {
this.props.hideRegisterWindow();
};
render(){
return(
<div>
<Dialog
title="Create Account"
open={this.props.open}
onRequestClose={this.handleClose}>
This box is where the account creation form will go.
</Dialog>
</div>
)
}
}
| JavaScript | 0 | @@ -60,16 +60,165 @@
Dialog';
+%0Aimport TextField from 'material-ui/TextField';%0Aimport FlatButton from 'material-ui/FlatButton';%0Aimport RaisedButton from 'material-ui/RaisedButton';
%0A%0Aexport
@@ -386,17 +386,235 @@
%0A%0A
-render()%7B
+handleCreateAccount = () =%3E %7B%0A%0A %7D%0A%0A render()%7B%0A const actions = %5B%0A %3CFlatButton%0A label=%22Not right now%22%0A primary=%7Btrue%7D%0A keyboardFocused=%7Btrue%7D%0A onTouchTap=%7Bthis.handleClose%7D%0A /%3E,%0A %5D;%0A
%0A
@@ -658,16 +658,18 @@
+
+
title=%22C
@@ -678,17 +678,23 @@
ate
-A
+a new a
ccount%22%0A
@@ -689,16 +689,18 @@
ccount%22%0A
+
@@ -730,16 +730,18 @@
+
onReques
@@ -769,70 +769,573 @@
ose%7D
-%3E%0A This box is where the account creation form will go.
+%0A actions=%7Bactions%7D%0A contentStyle=%7B%7Bwidth: '320px'%7D%7D%0A %3E%0A This box is where the account creation form will go.%0A %3CTextField id=%22userName%22 floatingLabelText=%22Username%22%3E%3C/TextField%3E%0A %3CTextField id=%22email%22 floatingLabelText=%22Email%22%3E%3C/TextField%3E%0A %3CTextField id=%22password%22 type=%22password%22 floatingLabelText=%22Password%22%3E%3C/TextField%3E%0A %3Cdiv style=%7B%7Bmargin:'auto', textAlign: 'center'%7D%7D%3E%0A %3CRaisedButton label=%22Create Account%22 primary=%7Btrue%7D onTouchTap=%7Bthis.handleCreateAccount%7D /%3E%0A %3C/div%3E
%0A
|
4164f6265a2c8caadeeef484453eecdefa41aadc | use bundle.trace() when building export block | src/finalisers/shared/getExportBlock.js | src/finalisers/shared/getExportBlock.js | export default function getExportBlock ( bundle, exportMode, mechanism = 'return' ) {
if ( exportMode === 'default' ) {
const defaultExport = bundle.entryModule.exports.default;
const defaultExportName = bundle.entryModule.replacements.default ||
defaultExport.identifier;
return `${mechanism} ${defaultExportName};`;
}
return bundle.toExport
.map( name => {
const prop = name === 'default' ? `['default']` : `.${name}`;
name = bundle.entryModule.replacements[ name ] || name;
return `exports${prop} = ${name};`;
})
.join( '\n' );
}
| JavaScript | 0 | @@ -455,48 +455,41 @@
dle.
-entryModule.replacements%5B name %5D %7C%7C name
+trace( bundle.entryModule, name )
;%0A%09%09
|
2e497faf23f265f1db7c4d54a84ceb6e26d490b2 | fix #126 | site/theme/index.js | site/theme/index.js | const contentTmpl = './template/Content/index';
module.exports = {
categoryOrder: {},
typeOrder: {
APIS: 0,
COMPONENTS: 1,
},
docVersions: {
},
routes: {
path: '/',
component: './template/Layout/index',
indexRoute: { component: './template/Home/index' },
childRoutes: [{
path: '/docs/practice/:children',
component: contentTmpl,
}, {
path: '/docs/pattern/:children',
component: contentTmpl,
}, {
path: '/docs/react/:children',
component: contentTmpl,
}, {
path: '/changelog',
component: contentTmpl,
}, {
path: '/components/:children',
component: contentTmpl,
}],
},
};
| JavaScript | 0 | @@ -151,16 +151,62 @@
ions: %7B%0A
+ '0.7.x': 'http://07x.mobile.ant.design/',%0A
%7D,%0A r
|
5bb05433463b570f2d4de693fbe736dfd1be9b1d | Move package changes to method | node-module/index.js | node-module/index.js | 'use strict'
const Generator = require('yeoman-generator')
const sort = require('sort-package-json')
module.exports = class NodeModule extends Generator {
configuring () {
const {name, description, github, me} = this.options
const existing = this.fs.read(this.destionationPath('package.json'))
const result = merge(existing, {
name,
main: 'index.js',
version: '0.0.0',
description: this.options.description,
license: 'MIT',
repository: `${github.username}/${name}`,
author: me,
files: ['*.js']
})
this.fs.write('package.json', JSON.stringify(sort(result)))
}
} | JavaScript | 0.000001 | @@ -169,16 +169,59 @@
ng () %7B%0A
+ this._package()%0A %7D%0A %0A _package () %7B%0A
cons
@@ -672,8 +672,9 @@
))%0A %7D%0A%7D
+%0A
|
56e0e6da360396077aae2248a9c60df25c118647 | Improve testing for for..in loops. | src/compilation/processJavaScriptCode.spec.js | src/compilation/processJavaScriptCode.spec.js | import processJavaScriptCode from "./processJavaScriptCode"
describe("processJavaScriptCode", function(){
it("Wraps string literals with an object with an origin", function(){
var code = "var a = 'Hello';a"
code = processJavaScriptCode(code).code
expect(eval(code).origin.action).toBe("String Literal")
})
it("Doesn't break conditional operator when used with a tracked string", function(){
var code = "'' ? true : false"
code = processJavaScriptCode(code).code
expect(eval(code)).toBe(false)
})
it("Doesn't break if statements when used with a tracked string", function(){
var code = `
var a = false
if ("") {
a = true
};
a
`
code = processJavaScriptCode(code).code
expect(eval(code)).toBe(false)
})
it("Doesn't break normal OR expressions", function(){
var code = "var a = {} || false;a"
code = processJavaScriptCode(code).code
expect(eval(code)).toEqual({})
})
it("Returns the correct value from OR expressions on tracked strings", function(){
var code = "'' || 'hi'"
code = processJavaScriptCode(code).code
expect(eval(code).value).toBe("hi")
})
it("Returns the correct value from AND expressions on tracked strings", function(){
var code = "'hi' && ''"
code = processJavaScriptCode(code).code
expect(eval(code).value).toBe("")
})
it("Doesn't try to evaluate the second part of an AND expression if the first part is falsy", function(){
var code = "var obj = undefined;obj && obj.hi"
code = processJavaScriptCode(code).code
expect(eval(code)).toBe(undefined)
})
it("Converts value to boolean when using NOT operator", function(){
var code = "!''"
code = processJavaScriptCode(code).code
expect(eval(code)).toBe(true)
code = "!!''"
code = processJavaScriptCode(code).code
expect(eval(code)).toBe(false)
})
it("Works correctly when nesting AND and OR expressions", function(){
// I used to have suspicions that the cached value could break something like this,
// but it seems to work.
var code = "(1 && 2) || 3"
code = processJavaScriptCode(code).code
expect(eval(code)).toBe(2)
})
it("f__assign returns the assigned value", function(){
var obj = {};
var res = f__assign(obj, "prop", "value")
expect(res).toBe("value")
})
it("Gives access to the tracked property names in a for...in loop", function(){
var code = `
var obj = {"hi": "there"};
var key;
for (key in obj){};
key;
`
code = processJavaScriptCode(code).code;
var evalRes = eval(code)
expect(evalRes.value).toBe("hi")
expect(evalRes.origin.action).toBe("String Literal")
});
})
| JavaScript | 0 | @@ -2978,12 +2978,924 @@
%0A %7D);
+%0A%0A it(%22For...in loops work without a block statement body%22, function()%7B%0A var code = %60%0A var obj = %7B%22hi%22: %22there%22%7D;%0A var key;%0A for (key in obj) false ? %22cake%22: %22cookie%22;%0A key;%0A %60%0A code = processJavaScriptCode(code).code;%0A var evalRes = eval(code)%0A expect(evalRes.value).toBe(%22hi%22)%0A expect(evalRes.origin.action).toBe(%22String Literal%22)%0A %7D);%0A%0A it(%22For...in loops work when accessing a property name from a member expression%22, function()%7B%0A var code = %60%0A var obj = %7B%0A sth: %7B%22hi%22: %22there%22%7D%0A %7D%0A var key;%0A for (key in obj.sth) if (false) %7B%7D;%0A key;%0A %60%0A code = processJavaScriptCode(code).code;%0A var evalRes = eval(code)%0A expect(evalRes.value).toBe(%22hi%22)%0A expect(evalRes.origin.action).toBe(%22String Literal%22)%0A %7D);
%0A%7D)%0A
|
80e23ae801dbb967febc57e9ad177f552bd2cf26 | Remove action. | src/components/ContentRepositoryCard.react.js | src/components/ContentRepositoryCard.react.js | import React from 'react/addons';
import Router from 'react-router';
import shell from 'shell';
import ContentRepositoryActions from '../actions/ContentRepositoryActions';
var ContentRepositoryCard = React.createClass({
handlePreview: function () {
shell.openExternal(this.props.repository.publicURL());
},
handleSubmit: function () {
ContentRepositoryActions.prepareContent(this.props.repository);
ContentRepositoryActions.prepareControl(this.props.repository);
},
handleRemove: function() {
//
},
render: function () {
let repo = this.props.repository;
let nameElement, detailElement, submitElement;
if (repo.canPreview()) {
// Render the name as a link.
nameElement = (
<a className="preview" onClick={this.handlePreview}>{repo.name()}</a>
);
} else {
// Use a span instead.
nameElement = (
<span className="preview">{repo.name()}</span>
);
}
if (repo.canSubmit()) {
submitElement = (
<a classNames="btn btn-link" onClick={this.handleSubmit}>submit</a>
);
} else {
submitElement = (
<span>submit</span>
);
}
if (repo.error) {
detailElement = (
<p className="detail error">{repo.error.toString()}</p>
);
}
return (
<div className="content-repository-card">
<div className="headline">
{nameElement}
<span className="state">{repo.state}</span>
<ul className="controls">
<li>{submitElement}</li>
<li><Router.Link to="editRepository" params={{id: repo.id}} className="btn btn-link">edit</Router.Link></li>
<li><a classNames="btn btn-link" onClick={this.handleRemove}>remove</a></li>
</ul>
</div>
{detailElement}
</div>
)
}
})
module.exports = ContentRepositoryCard;
| JavaScript | 0 | @@ -515,18 +515,71 @@
) %7B%0A
-//
+ContentRepositoryActions.remove(this.props.repository);
%0A %7D,%0A%0A
|
190a12adf4900e515a4c810a8913f37fd515ac62 | Update testsA.js | nodejs_app/testsA.js | nodejs_app/testsA.js | var exec= require('child_process').exec;
var tt = 0;
var cmd ='./nodejs_app/nodeon.sh & tt=$!' ;
var t=exec(cmd,function (error,stdout, stderr){
tt=stdout.replace('\r\n','');
});
exec("./nodejs_app/nodeoff.sh");
if(tt=0)
return 0;
else return 1;
console.log(tt);
| JavaScript | 0.000001 | @@ -208,16 +208,32 @@
f.sh%22);%0A
+console.log(tt);
%0Aif(tt=0
@@ -241,17 +241,17 @@
%0Areturn
-0
+1
;%0Aelse r
@@ -260,24 +260,8 @@
urn
-1
+0
;%0A
-console.log(tt);
%0A
|
61314bf54dce540d477c0195c228058d56c7e649 | create RemoveTagFilter method | src/components/TagFilterForm/TagFilterForm.js | src/components/TagFilterForm/TagFilterForm.js | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Autosuggest from 'react-autosuggest';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import TagContainer from '../Tag/TagContainer';
import { generateTagList, getSuggestionValue, renderSuggestion } from '../../helpers/TagAutosuggestHelper';
import s from './TagFilterForm.scss';
// eslint-disable-next-line css-modules/no-unused-class
import autosuggestTheme from './TagFilterFormAutosuggest.scss';
// eslint-disable-next-line css-modules/no-undef-class
autosuggestTheme.input = 'form-control';
const returnTrue = () => true;
class TagFilterForm extends Component {
static propTypes = {
setFlipMove: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = {
autosuggestValue: '',
};
this.state.shown = !!props.addedTags.length;
}
componentDidUpdate(prevProps, prevState) {
if (this.state.shown !== prevState.shown && this.state.shown) {
this.autosuggest.input.focus();
}
this.props.setFlipMove(true);
}
setAutosuggestValue = (event, { newValue, method }) => {
if (method === 'up' || method === 'down') {
return;
}
this.setState(() => ({
autosuggestValue: newValue
}));
};
handleSuggestionSelected = (event, { suggestion, method }) => {
if (method === 'enter') {
event.preventDefault();
}
this.props.setFlipMove(false);
this.props.addTag(suggestion.id);
this.setState(() => ({
autosuggestValue: '',
}));
}
hideForm = () => {
this.props.clearTags();
this.props.setFlipMove(false);
this.setState(() => ({
autosuggestValue: '',
shown: false,
}));
}
showForm = () => {
this.setState(() => ({
shown: true,
}));
}
render() {
const {
addByName,
addedTags,
allTags,
exclude,
removeTag,
restaurantIds,
} = this.props;
const { autosuggestValue, shown } = this.state;
let form;
let showButton;
if (!allTags.length || !restaurantIds.length) {
return null;
}
if (shown) {
const tags = generateTagList(allTags, addedTags, autosuggestValue);
form = (
<form className={s.form} onSubmit={addByName}>
<Autosuggest
suggestions={tags}
focusInputOnSuggestionClick={false}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={{
placeholder: exclude ? 'exclude' : 'filter',
value: autosuggestValue,
onChange: this.setAutosuggestValue,
}}
theme={autosuggestTheme}
onSuggestionSelected={this.handleSuggestionSelected}
onSuggestionsFetchRequested={() => {}}
onSuggestionsClearRequested={() => {}}
shouldRenderSuggestions={returnTrue}
ref={a => { this.autosuggest = a; }}
/>
{addedTags.map(tag => (
<div
className={s.tagContainer}
key={exclude ? `tagExclusion_${tag}` : `tagFilter_${tag}`}
>
<TagContainer
id={tag}
showDelete
onDeleteClicked={() => {removeTag(tag); this.props.setFlipMove(false);}}
exclude={exclude}
/>
</div>
))}
<button
className="btn btn-default"
type="button"
onClick={this.hideForm}
>
cancel
</button>
</form>
);
} else {
showButton = (
<button className="btn btn-default" onClick={this.showForm}>
{exclude ? 'exclude tags' : 'filter by tag'}
</button>
);
}
return (
<div className={s.root}>{showButton}{form}</div>
);
}
}
TagFilterForm.propTypes = {
exclude: PropTypes.bool,
addByName: PropTypes.func.isRequired,
addTag: PropTypes.func.isRequired,
allTags: PropTypes.array.isRequired,
clearTags: PropTypes.func.isRequired,
removeTag: PropTypes.func.isRequired,
restaurantIds: PropTypes.array.isRequired,
addedTags: PropTypes.array.isRequired,
};
TagFilterForm.defaultProps = {
exclude: false
};
export const undecorated = TagFilterForm;
export default withStyles(s)(withStyles(autosuggestTheme)(TagFilterForm));
| JavaScript | 0 | @@ -1816,16 +1816,119 @@
);%0A %7D%0A%0A
+ removeTagFilter = (tag) =%3E %7B%0A this.props.removeTag(tag); %0A this.props.setFlipMove(false);%0A %7D%0A%0A
render
@@ -2012,25 +2012,8 @@
de,%0A
- removeTag,%0A
@@ -3382,17 +3382,21 @@
=%7B() =%3E
-%7B
+this.
removeTa
@@ -3400,46 +3400,19 @@
eTag
-(tag); this.props.setFlipMove(false);%7D
+Filter(tag)
%7D%0A
|
f03b0e3c28efce478669aca33349d74f9f907e97 | Correct returns annotation | src/queries/joining-queries/has-child-query.js | src/queries/joining-queries/has-child-query.js | 'use strict';
const isNil = require('lodash.isnil');
const JoiningQueryBase = require('./joining-query-base');
const ES_REF_URL =
'https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-has-child-query.html';
/**
* The `has_child` filter accepts a query and the child type to run against, and
* results in parent documents that have child docs matching the query.
*
* [Elasticsearch reference](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-has-child-query.html)
*
* @example
* // Scoring support
* const qry = bob.hasChildQuery(
* bob.termQuery('tag', 'something'),
* 'blog_tag'
* ).scoreMode('min');
*
* @example
* // Sort by child documents' `click_count` field
* const qry = bob.hasChildQuery()
* .query(
* bob.functionScoreQuery().function(
* bob.scriptScoreFunction("_score * doc['click_count'].value")
* )
* )
* .type('blog_tag')
* .scoreMode('max');
*
* @param {Query=} qry A valid `Query` object
* @param {string=} type The child type
*
* @extends JoiningQueryBase
*/
class HasChildQuery extends JoiningQueryBase {
// eslint-disable-next-line require-jsdoc
constructor(qry, type) {
super('has_child', ES_REF_URL, qry);
if (!isNil(type)) this._queryOpts.child_type = type;
}
/**
* Sets the child document type to search against.
* Alias for method `childType`.
*
* @param {string} type A valid doc type name
* @returns {HasChildQuery} returns `this` so that calls can be chained.
*/
type(type) {
return this.childType(type);
}
/**
* Sets the child document type to search against
*
* @param {string} type A valid doc type name
* @returns {HasChildQuery} returns `this` so that calls can be chained.
*/
childType(type) {
this._queryOpts.child_type = type;
return this;
}
/**
* Specify the minimum number of children are required to match
* for the parent doc to be considered a match
*
* @example
* const qry = bob.hasChildQuery(bob.termQuery('tag', 'something'), 'blog_tag')
* .minChildren(2)
* .maxChildren(10)
* .scoreMode('min');
*
* @param {number} limit A positive `integer` value.
* @returns {NestedQuery} returns `this` so that calls can be chained.
*/
minChildren(limit) {
this._queryOpts.min_children = limit;
return this;
}
/**
* Specify the maximum number of children are required to match
* for the parent doc to be considered a match
*
* @example
* const qry = bob.hasChildQuery(bob.termQuery('tag', 'something'), 'blog_tag')
* .minChildren(2)
* .maxChildren(10)
* .scoreMode('min');
*
* @param {number} limit A positive `integer` value.
* @returns {NestedQuery} returns `this` so that calls can be chained.
*/
maxChildren(limit) {
this._queryOpts.max_children = limit;
return this;
}
}
module.exports = HasChildQuery;
| JavaScript | 0 | @@ -2332,37 +2332,39 @@
* @returns %7B
-Neste
+HasChil
dQuery%7D returns
@@ -2911,13 +2911,15 @@
ns %7B
-Neste
+HasChil
dQue
|
58a680d5017428b3ae49ddbbe069000f43ef6708 | Fix bin shebang line | language-server/cli.js | language-server/cli.js | #!/usr/local/bin/node
require('./server.js');
| JavaScript | 0.000001 | @@ -4,18 +4,16 @@
usr/
-local/
bin/
+env
node
|
b50f2615b644934be4ddc52bf9dacd9d8459084c | add notes | Algorithms/JS/arrays/kthSmallestElementinArray.js | Algorithms/JS/arrays/kthSmallestElementinArray.js | // Kth Smallest Element in an Array
// Find the kth smallest element in an unsorted array. Note that it is the kth smallest element in the sorted order,
// not the kth distinct element.
// For example,
// Given [3,2,1,5,6,4] and k = 2, return 2.
// Note:
// You may assume k is always valid, 1 ≤ k ≤ array's length.
/**
* @param {arr[]} nums
* @param {number} k
* @return {number}
*/
var findKthSmallest = function(nums, k, l=0, r=nums[0]) {
if (k > 0 && k <= r - l + 1){
// Partition the array around a random element and
// get position of pivot element in sorted array
var pos = randomPartition(nums, l, r);
// If position is same as k
if (pos-l == k-1) return nums[pos];
// If position is more, recur for left subarray
if (pos-l > k-1) return findKthSmallest(nums, k, l, pos-1);
// Else recur for right subarray
return findKthSmallest(nums, k-pos+l-1, pos+1, r);
}
// helper method to swap arr[i] and arr[j]
function swap(arr, i, j){
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Standard partition process of QuickSort(). It considers
// the last element as pivot and moves all smaller element
// to left of it and greater elements to right. This function
// is used by randomPartition()
function partition(arr, l, r){
var x = arr[r], i = l;
for (var j = l; j <= r - 1; j++){
if (arr[j] <= x){
swap(arr, i, j);
i++;
}
}
swap(arr, i, r);
return i;
}
// Picks a random pivot element between l and r and
// partitions arr[l..r] arount the randomly picked
// element using partition()
function randomPartition(arr, l, r){
var n = r-l+1;
var pivot = arr[0];
swap(arr, l + pivot, r);
return partition(arr, l, r);
}
};
// ---------------------------------------------------------------------
// Naive solution
//
function findKthSmallest(arr, k){
var result = arr.sort(function(a, b){ return a - b });
return result[k-1];
}
| JavaScript | 0 | @@ -2037,18 +2037,48 @@
olution%0A
+%0A
//
+ 0(n logn) runtime 0(n) space
%0Afunctio
|
7a1253b2c44e4c56b0b0c9404ca8cf2748db953e | remove an extra line | src/redux/students/reducers/student-wrapper.js | src/redux/students/reducers/student-wrapper.js | import {
BEGIN_VALIDATE_SCHEDULES,
VALIDATE_SCHEDULES,
BEGIN_GET_STUDENT_DATA,
GET_STUDENT_DATA,
BEGIN_CHECK_GRADUATABILITY,
CHECK_GRADUATABILITY,
BEGIN_LOAD_STUDENT,
LOAD_STUDENT,
} from '../constants'
import studentReducer from './student'
const initialState = {
isChecking: false,
isFetching: false,
isLoading: false,
isValdiating: false,
data: {present: {}, past: [], future: []},
}
export default function studentWrapperReducer(state = initialState, action) {
const {type, payload} = action
switch (type) {
case BEGIN_LOAD_STUDENT: {
return {...state, isLoading: true}
}
case LOAD_STUDENT: {
return {
...state,
isLoading: false,
data: studentReducer({...state.data, present: payload}, action),
}
}
case BEGIN_GET_STUDENT_DATA: {
return {...state, isFetching: true}
}
case GET_STUDENT_DATA: {
return {
...state,
data: studentReducer({...state.data, present: payload}, action),
isFetching: false,
}
}
case BEGIN_CHECK_GRADUATABILITY: {
return {...state, isChecking: true}
}
case CHECK_GRADUATABILITY: {
return {
...state,
data: studentReducer({...state.data, present: payload}, action),
isChecking: false,
}
}
case BEGIN_VALIDATE_SCHEDULES: {
return {...state, isValdiating: true}
}
case VALIDATE_SCHEDULES: {
return {
...state,
data: studentReducer({...state.data, present: payload}, action),
isValdiating: false,
}
}
default: {
return {
...state,
data: studentReducer(state.data, action),
}
}
}
}
| JavaScript | 0.999724 | @@ -1455,17 +1455,16 @@
%09%7D%0A%09%09%7D%0A%0A
-%0A
%09%09defaul
|
3232a597438711fb6f7cc836c368cb2952b6a82b | Fix typo | src/renderers/shared/event/EventPropagators.js | src/renderers/shared/event/EventPropagators.js | /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventPropagators
*/
'use strict';
var EventConstants = require('EventConstants');
var EventPluginHub = require('EventPluginHub');
var warning = require('warning');
var accumulateInto = require('accumulateInto');
var forEachAccumulated = require('forEachAccumulated');
var PropagationPhases = EventConstants.PropagationPhases;
var getListener = EventPluginHub.getListener;
/**
* Some event types have a notion of different registration names for different
* "phases" of propagation. This finds listeners by a given phase.
*/
function listenerAtPhase(id, event, propagationPhase) {
var registrationName =
event.dispatchConfig.phasedRegistrationNames[propagationPhase];
return getListener(id, registrationName);
}
/**
* Tags a `SyntheticEvent` with dispatched listeners. Creating this function
* here, allows us to not have to bind or create functions for each event.
* Mutating the event's members allows us to not have to create a wrapping
* "dispatch" object that pairs the event with the listener.
*/
function accumulateDirectionalDispatches(domID, upwards, event) {
if (__DEV__) {
warning(
domID,
'Dispatching id must not be null'
);
}
var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured;
var listener = listenerAtPhase(domID, event, phase);
if (listener) {
event._dispatchListeners =
accumulateInto(event._dispatchListeners, listener);
event._dispatchIDs = accumulateInto(event._dispatchIDs, domID);
}
}
/**
* Collect dispatches (must be entirely collected before dispatching - see unit
* tests). Lazily allocate the array to conserve memory. We must loop through
* each event and perform the traversal for each one. We can not perform a
* single traversal for the entire collection of events because each event may
* have a different target.
*/
function accumulateTwoPhaseDispatchesSingle(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
EventPluginHub.injection.getInstanceHandle().traverseTwoPhase(
event.dispatchMarker,
accumulateDirectionalDispatches,
event
);
}
}
/**
* Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID.
*/
function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
EventPluginHub.injection.getInstanceHandle().traverseTwoPhaseSkipTarget(
event.dispatchMarker,
accumulateDirectionalDispatches,
event
);
}
}
/**
* Accumulates without regard to direction, does not look for phased
* registration names. Same as `accumulateDirectDispatchesSingle` but without
* requiring that the `dispatchMarker` be the same as the dispatched ID.
*/
function accumulateDispatches(id, ignoredDirection, event) {
if (event && event.dispatchConfig.registrationName) {
var registrationName = event.dispatchConfig.registrationName;
var listener = getListener(id, registrationName);
if (listener) {
event._dispatchListeners =
accumulateInto(event._dispatchListeners, listener);
event._dispatchIDs = accumulateInto(event._dispatchIDs, id);
}
}
}
/**
* Accumulates dispatches on an `SyntheticEvent`, but only for the
* `dispatchMarker`.
* @param {SyntheticEvent} event
*/
function accumulateDirectDispatchesSingle(event) {
if (event && event.dispatchConfig.registrationName) {
accumulateDispatches(event.dispatchMarker, null, event);
}
}
function accumulateTwoPhaseDispatches(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
}
function accumulateTwoPhaseDispatchesSkipTarget(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget);
}
function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) {
EventPluginHub.injection.getInstanceHandle().traverseEnterLeave(
fromID,
toID,
accumulateDispatches,
leave,
enter
);
}
function accumulateDirectDispatches(events) {
forEachAccumulated(events, accumulateDirectDispatchesSingle);
}
/**
* A small set of propagation patterns, each of which will accept a small amount
* of information, and generate a set of "dispatch ready event objects" - which
* are sets of events that have already been annotated with a set of dispatched
* listener functions/ids. The API is designed this way to discourage these
* propagation strategies from actually executing the dispatches, since we
* always want to collect the entire set of dispatches before executing event a
* single one.
*
* @constructor EventPropagators
*/
var EventPropagators = {
accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches,
accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget,
accumulateDirectDispatches: accumulateDirectDispatches,
accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches,
};
module.exports = EventPropagators;
| JavaScript | 1 | @@ -2039,17 +2039,16 @@
. We can
-
not perf
|
033296b2d648053765631e0fd59a0e0466c7d531 | make deriving the sort key for the incidencematrix easier to read | src/report/dependencyToIncidenceTransformer.js | src/report/dependencyToIncidenceTransformer.js | "use strict";
function compareOnSource(pOne, pTwo) {
return `${pOne.coreModule ? "1" : "0"}-${pOne.source}` >
`${pTwo.coreModule ? "1" : "0"}-${pTwo.source}`
? 1
: -1;
}
function determineIncidenceType(pFromListEntry) {
return pModule => {
let lDep = pModule.dependencies.find(
pDep => pDep.resolved === pFromListEntry.source
);
if (lDep) {
return lDep.valid
? {
incidence: "true"
}
: {
incidence: lDep.rules[0].severity,
rule: `${lDep.rules[0].name}${lDep.rules.length > 1 ? ` (+${lDep.rules.length - 1} others)` : ""}`
};
}
return {
incidence: "false"
};
};
}
function addIncidences(pFromList) {
return (pDependency) =>
Object.assign(
pDependency,
{
incidences: pFromList.map(pFromListEntry =>
Object.assign(
{
to: pFromListEntry.source
},
determineIncidenceType(pFromListEntry)(pDependency)
)
)
}
);
}
module.exports =
pFromList => pFromList.sort(compareOnSource).map(addIncidences(pFromList));
| JavaScript | 0.000001 | @@ -51,26 +51,56 @@
) %7B%0A
-%0A
-return %60$%7BpOn
+const deriveSortKey = (pModule) =%3E %60$%7BpModul
e.co
@@ -124,18 +124,21 @@
%220%22%7D-$%7Bp
-On
+Modul
e.source
@@ -143,66 +143,63 @@
ce%7D%60
- %3E
+;%0A
%0A
- %60$%7BpTwo.coreModule ? %221%22 : %220%22%7D-$%7BpTwo.source%7D%60
+return deriveSortKey(pOne) %3E deriveSortKey(pTwo)
%0A
|
df7d72d8eeaf7ce78c2e358c7cfcf683785f6c15 | update exam list | src/containers/discover/exam-list/ExamList.js | src/containers/discover/exam-list/ExamList.js | import React, { Component } from 'react';
import { ScrollView } from 'react-native';
import AppStyle from '../../../theme/styles';
import SimpleListItem from '../../../components/discover/view/SimpleListItem';
import EXAM_LIST from '../../../../assets/data/EXAM_LIST';
class ExamList extends Component {
static componentName = 'ExamList';
constructor(props) {
super(props);
this.state = {
rowData: EXAM_LIST,
};
}
render() {
const rows = this.state.rowData
.map((val, index) => (
<SimpleListItem text={val} key={val.concat(index)} />));
return (
<ScrollView style={AppStyle.detailBasisStyle}>
{rows}
</ScrollView>);
}
}
export default ExamList;
| JavaScript | 0 | @@ -214,59 +214,472 @@
ort
-EXAM_LIST from '../../../../assets/data/EXAM_LIST';
+Launch from '../../../components/discover/Launch';%0Aimport EXAM_LIST from '../../../../assets/data/EXAM_LIST';%0Aimport QUIZS from '../../../../assets/data/QUIZS';%0A%0Afunction swtichQuiz(name) %7B%0A switch (name) %7B%0A case 'HTML':%0A return QUIZS.html;%0A case 'CSS':%0A return QUIZS.css;%0A case 'JavaScript':%0A return QUIZS.javascript;%0A case '%E5%89%8D%E7%AB%AF':%0A return QUIZS.fe;%0A case 'Node.js':%0A return QUIZS.nodejs;%0A default:%0A return %5B%5D;%0A %7D%0A%7D
%0A%0Acl
@@ -956,19 +956,106 @@
Item
- text=%7Bval%7D
+%0A text=%7Bval%7D%0A click=%7B() =%3E (Launch.examDetail(swtichQuiz(val)))%7D%0A
key
@@ -1074,16 +1074,26 @@
(index)%7D
+%0A
/%3E));%0A%0A
|
b90b3ee7d0f293b5080a63ee5d09f61cb36d09a3 | Update event.manager.spec.js | src/core/infrastructure/event.manager.spec.js | src/core/infrastructure/event.manager.spec.js | import {EventManager} from './event.manager';
describe('EventManager', () => {
let test = {
arr: [1, 2, 3],
checkLength: function () {
return this.arr.length;
}
};
let test2 = {
arr: [1, 2, 3, 4, 5]
};
let eventManager = new EventManager(test2);
let result = eventManager.bind(test.checkLength);
describe('bind', () => {
it('should return 5 if checkLength function was bind to test2 object', () => {
expect(result()).to.equal(5);
});
});
});
| JavaScript | 0.000004 | @@ -389,17 +389,18 @@
on was b
-i
+ou
nd to te
|
c599a9e7e09af5bbefbd9c2bfdc601048ed11905 | Add payment routes | packages/shared/lib/api/payments.js | packages/shared/lib/api/payments.js | export const getSubscription = () => ({
url: 'payments/subscription',
method: 'get'
});
export const queryInvoices = ({ Page, PageSize, Owner, State, Type }) => ({
url: 'payments/invoices',
method: 'get',
params: { Page, PageSize, Owner, State, Type }
});
export const getInvoice = (ID) => ({
url: `payments/invoices/${ID}`,
method: 'get',
output: 'arrayBuffer'
});
export const queryPaymentMethods = () => ({
url: 'payments/methods',
method: 'get'
});
export const setPaymentMethod = (data) => ({
url: 'payments/methods',
method: 'post',
data
});
export const deletePaymentMethod = (ID) => ({
url: `payments/methods/${ID}`,
method: 'delete'
});
export const createBitcoinPayment = ({ Amount, Currency }) => ({
url: 'payments/bcinfo',
method: 'post',
data: { Amount, Currency }
});
| JavaScript | 0.000001 | @@ -849,12 +849,237 @@
rency %7D%0A%7D);%0A
+%0Aexport const payInvoice = (invoiceID, data) =%3E (%7B%0A url: %60payments/invoices/$%7BinvoiceID%7D%60,%0A method: 'post',%0A data%0A%7D);%0A%0Aexport const getPaymentMethodStatus = () =%3E (%7B%0A url: 'payments/status',%0A method: 'get'%0A%7D);%0A
|
ca9cfcc7037a68928293eada9b3a15d257019467 | Use strict comparison | bootstrap-tabcollapse.js | bootstrap-tabcollapse.js | !function ($) {
"use strict";
// TABCOLLAPSE CLASS DEFINITION
// ======================
var TabCollapse = function (el, options) {
this.options = options;
this.$tabs = $(el);
this._accordionVisible = false; //content is attached to tabs at first
this._initAccordion();
this._checkStateOnResize();
this.checkState();
};
TabCollapse.DEFAULTS = {
accordionClass: 'visible-xs',
tabsClass: 'hidden-xs',
accordionTemplate: function(heading, groupId, parentId, active){
return '<div class="panel panel-default">' +
' <div class="panel-heading">' +
' <h4 class="panel-title">' +
' <a class="' + (active ? '' : 'collapsed') + '" data-toggle="collapse" data-parent="#' + parentId + '" href="#' + groupId + '">' +
' ' + heading +
' </a>' +
' </h4>' +
' </div>' +
' <div id="' + groupId + '" class="panel-collapse collapse ' + (active ? 'in' : '') + '">' +
' <div class="panel-body js-tabcollapse-panel-body">' +
' </div>' +
' </div>' +
'</div>';
}
};
TabCollapse.prototype.checkState = function(){
if (this.$tabs.is(':visible') && this._accordionVisible){
this.showTabs();
this._accordionVisible = false;
} else if (this.$accordion.is(':visible') && !this._accordionVisible){
this.showAccordion();
this._accordionVisible = true;
}
};
TabCollapse.prototype.showTabs = function(){
this.$tabs.trigger($.Event('show-tabs.bs.tabcollapse'));
var $panelBodies = this.$accordion.find('.js-tabcollapse-panel-body');
$panelBodies.each(function(){
var $panelBody = $(this),
$tabPane = $panelBody.data('bs.tabcollapse.tabpane');
$tabPane.append($panelBody.children('*').detach());
});
this.$accordion.html('');
this.$tabs.trigger($.Event('shown-tabs.bs.tabcollapse'));
};
TabCollapse.prototype.showAccordion = function(){
this.$tabs.trigger($.Event('show-accordion.bs.tabcollapse'));
var $headings = this.$tabs.find('li:not(.dropdown) [data-toggle="tab"], li:not(.dropdown) [data-toggle="pill"]'),
view = this;
$headings.each(function(){
var $heading = $(this);
view.$accordion.append(view._createAccordionGroup(view.$accordion.attr('id'), $heading));
});
this.$tabs.trigger($.Event('shown-accordion.bs.tabcollapse'));
};
TabCollapse.prototype._checkStateOnResize = function(){
var view = this;
$(window).resize(function(){
clearTimeout(view._resizeTimeout);
view._resizeTimeout = setTimeout(function(){
view.checkState();
}, 100);
});
};
TabCollapse.prototype._initAccordion = function(){
this.$accordion = $('<div class="panel-group ' + this.options.accordionClass + '" id="' + this.$tabs.attr('id') + '-accordion' +'"></div>');
this.$tabs.after(this.$accordion);
this.$tabs.addClass(this.options.tabsClass);
this.$tabs.siblings('.tab-content').addClass(this.options.tabsClass);
};
TabCollapse.prototype._createAccordionGroup = function(parentId, $heading){
var tabSelector = $heading.attr('data-target'),
active = $heading.parent().is('.active');
if (!tabSelector) {
tabSelector = $heading.attr('href');
tabSelector = tabSelector && tabSelector.replace(/.*(?=#[^\s]*$)/, ''); //strip for ie7
}
var $tabPane = $(tabSelector),
groupId = $tabPane.attr('id') + '-collapse',
$panel = $(this.options.accordionTemplate($heading.html(), groupId, parentId, active));
$panel.find('.panel-body').append($tabPane.children('*').detach())
.data('bs.tabcollapse.tabpane', $tabPane);
return $panel;
};
// TABCOLLAPSE PLUGIN DEFINITION
// =======================
$.fn.tabCollapse = function (option) {
return this.each(function () {
var $this = $(this);
var data = $this.data('bs.tabcollapse');
var options = $.extend({}, TabCollapse.DEFAULTS, $this.data(), typeof option == 'object' && option);
if (!data) $this.data('bs.tabcollapse', new TabCollapse(this, options));
});
};
$.fn.tabCollapse.Constructor = TabCollapse;
}(window.jQuery);
| JavaScript | 0.000004 | @@ -4496,16 +4496,17 @@
ption ==
+=
'object
|
5905920c6c32deb65cc2c2e8d18a21bef716c6a7 | Fix syntax error | WebContent/muster.js | WebContent/muster.js | jQuery.noConflict() (function($) {
muster = function(options) {
/* TODO handle failed JSON requests */
var url = options.url;
var database = options.database;
this.query = function(options) {
return musterQuery(url, database, options);
}
function musterQuery(url, database, options) {
this.results = {};
/* construct and execute the query */
/* paramaterized JSONP request URI */
var uri = url + '?database=' + escape(database);
/* parameters which may be passed to Muster servlet */
var parameters = ['select', 'from', 'where', 'order'];
$.each(parameters, function() {
if (options[this] != null && options[this].length > 0) {
uri += '&' + this + '=' + options[this];
}
});
/* append jQuery callback */
uri += '&callback=?';
$.getJSON(uri, function(data) {
results = data;
results.toTable = function(className) {
return musterResultsToTable(results, className);
};
results.find = function(queries) {
return musterResultsFind(results, queries);
}
if (options.callback) {
options.callback(results);
}
if (options.results) {
options.results = results;
}
});
return results;
}
function musterResultsToTable(results, className) {
var className = className ? className : '';
var table = $('<table>').addClass('musterTable ' + className);
/* table headers */
var thead = $('<thead>');
table.append(thead);
var headersRow = $('<tr>');
thead.append(headersRow);
$.each(results.columns, function() {
headersRow.append('<th>' + this);
});
/* data rows */
var tbody = $('<tbody>');
table.append(tbody);
$.each(results.results, function() {
var tr = $('<tr>');
tbody.append(tr);
$.each(this, function() {
tr.append('<td>' + this);
});
});
return table;
}
return this;
}
})(jQuery)
| JavaScript | 0.000585 | @@ -12,16 +12,17 @@
nflict()
+;
(functi
|
19edacbcd245c7c315878df7cac7fe73a2389016 | Remove the context menu on user clicks and on browser history changes. | dxr/static_unhashed/js/context_menu.js | dxr/static_unhashed/js/context_menu.js | /* jshint devel:true, esnext: true */
/* globals nunjucks: true, $ */
$(function() {
'use strict';
// Get the file content container
var fileContainer = $('#file'),
queryField = $('#query'),
contentContainer = $('#content');
/**
* Highlight, or remove highlighting from, all symbols with the same class
* as the current node.
*
* @param Object [optional] currentNode The current symbol node.
*/
function toggleSymbolHighlights(currentNode) {
// First remove all highlighting
fileContainer.find('mark a').unwrap();
// Only add highlights if the currentNode is not undefined or null and
// is an anchor link, as symbols will always be links.
if (currentNode && currentNode[0].tagName === 'A') {
fileContainer.find('.' + currentNode.attr('class')).wrap('<mark />');
}
}
/**
* Populates the context menu template, positions and shows
* the widget. Also attached required listeners.
*
* @param {object} target - The target container to which the menu will be attached.
* @param {object} contextMenu - The context menu data object.
* @param {object} event - The event object returned in the handler callback.
*/
function setContextMenu(target, contextMenu, event) {
// Mouse coordinates
var top = event.clientY,
left = event.clientX;
// If we arrived at the page via a search result and there is a hash in the url,
// or the document has been scrolled, incorporate the scrollY amount for the
// top location of the context menu.
if (window.location.href.indexOf('#') > -1 || window.scrollY > 0) {
top += window.scrollY;
}
target.append(nunjucks.render('context_menu.html', contextMenu));
var currentContextMenu = $('#context-menu');
// Immediately after appending the context menu, position it.
currentContextMenu.css({
top: top,
left: left
});
// Move focus to the context menu
currentContextMenu[0].focus();
currentContextMenu.on('mousedown', function(event) {
// Prevent clicks on the menu to propagate
// to the window, so that the menu is not
// removed and links will be followed.
event.stopPropagation();
});
}
// Listen for clicks bubbling up from children of the content container,
// but only act if the element was an anchor with a data-path attribute.
contentContainer.on('click', 'a[data-path]', function(event) {
event.preventDefault();
var contextMenu = {},
path = $(this).data('path'),
baseSearchParams = '?limit=100&redirect=false&q=',
query = $.trim(queryField.val()),
browseUrl = dxr.wwwRoot + '/' + encodeURIComponent(dxr.tree) + '/source/' + path,
limitSearchUrl = dxr.searchUrl + baseSearchParams + encodeURIComponent(query) + '%20path%3A' + path + '%2F', // TODO: Escape path properly.
excludeSearchUrl = dxr.searchUrl + baseSearchParams + encodeURIComponent(query) + '%20-path%3A' + path + '%2F';
contextMenu.menuItems = [
{
html: 'Browse folder contents',
href: browseUrl,
icon: 'goto-folder'
},
{
html: 'Limit search to folder',
href: limitSearchUrl,
icon: 'path-search'
},
{
html: 'Exclude folder from search',
href: excludeSearchUrl,
icon: 'exclude-path'
}
];
setContextMenu(contentContainer, contextMenu, event);
});
// Listen and handle click events, but only if on
// a code element.
fileContainer.on('click', 'code', function(event) {
var selection = window.getSelection();
// First remove any context menu that might already exist
$('#context-menu').remove();
// Only show the context menu if the user did not make
// a text selection.
if (selection.isCollapsed) {
var offset = selection.focusOffset,
node = selection.anchorNode,
selectedTxtString = node.nodeValue,
startIndex = selectedTxtString.regexLastIndexOf(/[^A-Z0-9_]/i, offset) + 1,
endIndex = selectedTxtString.regexIndexOf(/[^A-Z0-9_]/i, offset),
word = '';
// If the regex did not find a start index, start from index 0
if (startIndex === -1) {
start = 0;
}
// If the regex did not find an end index, end at the position
// equal to the length of the string.
if (endIndex === -1) {
endIndex = selectedTxtString.length;
}
// If the offset is beyond the last word, no word was clicked on.
if (offset === endIndex) {
return;
}
word = selectedTxtString.substr(startIndex, endIndex - startIndex);
// No word was clicked on, nothing to search.
if (word === '') {
return;
}
// Build the Object needed for the context-menu template.
var contextMenu = {},
menuItems = [{
html: 'Search for the substring <strong>' + htmlEscape(word) + '</strong>',
href: dxr.wwwRoot + "/" + encodeURIComponent(dxr.tree) + "/search?q=" + encodeURIComponent(word) + "&case=true",
icon: 'search'
}];
var currentNode = $(node).closest('a');
// Only check for the data-menu attribute if the current node has an
// ancestor that is an anchor.
if (currentNode.length) {
toggleSymbolHighlights(currentNode);
var currentNodeData = currentNode.data('menu');
menuItems = menuItems.concat(currentNodeData);
}
contextMenu.menuItems = menuItems;
setContextMenu(fileContainer, contextMenu, event);
}
});
// Remove the menu when a user clicks outside it.
window.addEventListener('mousedown', function() {
toggleSymbolHighlights();
$('#context-menu').remove();
}, false);
onEsc(function() {
$('#context-menu').remove();
});
});
| JavaScript | 0 | @@ -6328,156 +6328,426 @@
-// Remove the menu when a user clicks outside it.%0A window.addEventListener('mousedown', function() %7B%0A toggleSymbolHighlights();%0A $(
+function removeContextMenu() %7B%0A toggleSymbolHighlights();%0A $('#context-menu').remove();%0A %7D%0A%0A // Remove the menu when a user clicks outside it, or when the page is loaded%0A // via backward and forward history moves to this page, or via reload.%0A $(window).on('mousedown pageshow', removeContextMenu);%0A%0A // Remove the menu when a user clicks on one of its links.%0A fileContainer.on('click',
'#co
@@ -6760,33 +6760,30 @@
menu
-').
+ a',
remove
-();%0A %7D, false
+ContextMenu
);%0A%0A
|
8d09d46c90dc3a41d6e15471a1db388e6c6e0e34 | remove leftover code | remix-simulator/src/provider.js | remix-simulator/src/provider.js | var Web3 = require('web3')
var RemixLib = require('remix-lib')
const log = require('fancy-log')
const Transactions = require('./methods/transactions.js')
const Whisper = require('./methods/whisper.js')
const merge = require('merge')
function jsonRPCResponse (id, result) {
return {'id': id, 'jsonrpc': '2.0', 'result': result}
}
var Provider = function () {
this.web3 = new Web3()
// TODO: make it random
this.accounts = [this.web3.eth.accounts.create(['abcd'])]
this.accounts[this.accounts[0].address.toLowerCase()] = this.accounts[0]
this.accounts[this.accounts[0].address.toLowerCase()].privateKey = Buffer.from(this.accounts[this.accounts[0].address.toLowerCase()].privateKey.slice(2), 'hex')
this.Transactions = ;
this.methods = {}
this.methods = merge(this.methods, (new Transactions(this.accounts)).methods())
this.methods = merge(this.methods, (new Whisper()).methods())
log.dir(this.methods)
}
Provider.prototype.sendAsync = function (payload, callback) {
const self = this
log.dir('payload method is ')
log.dir(payload.method)
if (payload.method === 'eth_accounts') {
log.dir('eth_accounts')
return callback(null, jsonRPCResponse(payload.id, this.accounts.map((x) => x.address)))
}
if (payload.method === 'eth_estimateGas') {
callback(null, jsonRPCResponse(payload.id, 3000000))
}
if (payload.method === 'eth_gasPrice') {
callback(null, jsonRPCResponse(payload.id, 1))
}
if (payload.method === 'web3_clientVersion') {
callback(null, jsonRPCResponse(payload.id, 'Remix Simulator/0.0.1'))
}
if (payload.method === 'eth_getBlockByNumber') {
let b = {
'difficulty': '0x0',
'extraData': '0x',
'gasLimit': '0x7a1200',
'gasUsed': '0x0',
'hash': '0xdb731f3622ef37b4da8db36903de029220dba74c41185f8429f916058b86559f',
'logsBloom': '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
'miner': '0x3333333333333333333333333333333333333333',
'mixHash': '0x0000000000000000000000000000000000000000000000000000000000000000',
'nonce': '0x0000000000000042',
'number': '0x0',
'parentHash': '0x0000000000000000000000000000000000000000000000000000000000000000',
'receiptsRoot': '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421',
'sha3Uncles': '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347',
'size': '0x1f8',
'stateRoot': '0xb7917653f92e62394d2207d0f39a1320ff1cb93d1cee80d3c492627e00b219ff',
'timestamp': '0x0',
'totalDifficulty': '0x0',
'transactions': [],
'transactionsRoot': '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421',
'uncles': []
}
callback(null, jsonRPCResponse(payload.id, b))
}
let method = this.methods[payload.method]
if (method) {
return method.call(method, payload, (err, result) => {
if (err) {
return callback({error: err})
}
callback(null, jsonRPCResponse(payload.id, result))
});
}
callback("unknown method " + payload.method);
}
Provider.prototype.isConnected = function () {
return true
}
module.exports = Provider
| JavaScript | 0.001174 | @@ -710,33 +710,8 @@
')%0A%0A
- this.Transactions = ;%0A%0A
th
|
9111b490ded229a5a386abff128b341462b04413 | Fix vagrant setup commands not all running in sequence | browser/model/vagrant.js | browser/model/vagrant.js | 'use strict';
let path = require('path');
let fs = require('fs-extra');
let ipcRenderer = require('electron').ipcRenderer;
import InstallableItem from './installable-item';
import Downloader from './helpers/downloader';
import Logger from '../services/logger';
import Installer from './helpers/installer';
import CygwinInstall from './cygwin';
import Util from './helpers/util';
import Version from './helpers/version';
class VagrantInstall extends InstallableItem {
constructor(installerDataSvc, downloadUrl, installFile, targetFolderName) {
super('vagrant',
'Vagrant',
'v1.7',
'A container provisioning tool.',
900,
downloadUrl,
installFile,
targetFolderName,
installerDataSvc);
this.downloadedFileName = 'vagrant.msi';
this.bundledFile = path.join(path.join(path.normalize(__dirname), "../../.."), this.downloadedFileName);
this.downloadedFile = path.join(this.installerDataSvc.tempDir(), this.downloadedFileName);
this.vagrantPathScript = path.join(this.installerDataSvc.tempDir(), 'set-vagrant-path.ps1');
this.detected = false;
this.minimumVersion = "1.7.4";
this.existingVersion = "";
}
static key() {
return 'vagrant';
}
detectExistingInstall(cb = new function(){}) {
let versionRegex = /Vagrant*\s(\d+\.\d+\.\d+)/,
command,
directory,
extension = '',
subfolder = path.sep + 'bin';
if (process.platform === 'win32') {
command = 'where vagrant';
extension = '.exe';
} else {
command = 'which vagrant';
}
Util.executeCommand(command, 1)
.then((output) => {
this.addOption('detected','',path.dirname(path.dirname(output)),false);
return Util.executeCommand(output + ' -v', 1)
}).then((output) => {
let version = versionRegex.exec(output)[1];
this.option['detected'].version = version;
this.selectedOption = 'detected';
this.validateVersion();
cb();
}).catch((error) => {
this.addOption('install','5.0.8',path.join(this.installerDataSvc.installRoot,'vagrant'),true);
this.addOption('different','','',false);
cb(error);
});
}
validateVersion() {
let installOption = this.option[this.selectedOption];
installOption.valid = true;
installOption.error = '';
installOption.warning = '';
if(Version.LT(installOption.version,this.minimumVersion)) {
installOption.valid = false;
installOption.error = 'oldVersion';
installOption.warning = '';
} else if(Version.GT(installOption.version,this.minimumVersion)) {
installOption.valid = true;
installOption.error = '';
installOption.warning = 'newerVersion';
}
}
validateSelectedFolder(selection) {
// should be called after path to vagrant changed
}
isDownloadRequired() {
return !this.hasExistingInstall() && !fs.existsSync(this.bundledFile);
}
downloadInstaller(progress, success, failure) {
progress.setStatus('Downloading');
if(this.isDownloadRequired() && this.selectedOption === "install") {
// Need to download the file
let writeStream = fs.createWriteStream(this.downloadedFile);
let downloadSize = 199819264;
let downloader = new Downloader(progress, success, failure, downloadSize);
downloader.setWriteStream(writeStream);
downloader.download(this.downloadUrl);
} else {
this.downloadedFile = this.bundledFile;
success();
}
}
install(progress, success, failure) {
let cygwinInstall = this.installerDataSvc.getInstallable(CygwinInstall.key());
if( cygwinInstall !== undefined && cygwinInstall.isInstalled() ) {
this.postCygwinInstall(progress, success, failure);
} else {
progress.setStatus('Waiting for Cygwin to finish installation');
ipcRenderer.on('installComplete', (event, arg) => {
if (arg == 'cygwin') {
this.postCygwinInstall(progress, success, failure);
}
});
}
}
postCygwinInstall(progress, success, failure) {
progress.setStatus('Installing');
if(this.selectedOption === "install") {
let installer = new Installer(VagrantInstall.key(), progress, success, failure);
installer.execFile('msiexec', [
'/i',
this.downloadedFile,
'VAGRANTAPPDIR=' + this.installerDataSvc.vagrantDir(),
'/qb!',
'/norestart',
'/Liwe',
path.join(this.installerDataSvc.installDir(), 'vagrant.log')
]).then((result) => {
return installer.succeed(result);
}).catch((error) => {
if(error.code == 3010) {
return installer.succeed(true);
}
return installer.fail(error);
});
} else {
success();
}
}
setup(progress, success, failure) {
progress.setStatus('Setting up');
let installer = new Installer(VagrantInstall.key(), progress, success, failure);
let data = [
'$vagrantPath = "' + path.join(this.installerDataSvc.vagrantDir(), 'bin') + '"',
'$oldPath = [Environment]::GetEnvironmentVariable("path", "User");',
'[Environment]::SetEnvironmentVariable("Path", "$vagrantPath;$oldPath", "User");',
'[Environment]::Exit(0)'
].join('\r\n');
let args = [
'-ExecutionPolicy',
'ByPass',
'-File',
this.vagrantPathScript
];
installer.writeFile(this.vagrantPathScript, data)
.then((result) => {
return installer.execFile('powershell', args, result);
}).then((result) => {
installer.exec('setx VAGRANT_DETECTED_OS "cygwin"')
}).then((result) => {
return installer.succeed(true);
}).catch((result) => {
return installer.fail(result);
});
}
}
export default VagrantInstall;
| JavaScript | 0.000015 | @@ -5561,24 +5561,31 @@
=%3E %7B%0A
+return
installer.ex
@@ -5623,16 +5623,17 @@
ygwin%22')
+;
%0A %7D).
|
7a0732a1b9de8e8bfa6474b32e3eac0d61a0b929 | move setupResponsiveChild to loadData | www/graphics/aca-enrollment-age/graphic.js | www/graphics/aca-enrollment-age/graphic.js | $(document).ready(function() {
var $graphic = $('#graphic');
var graphic_data_url = 'enrollment.csv';
var graphic_data;
function load_data() {
d3.csv(graphic_data_url, function(error, data) {
graphic_data = data;
draw_graphic();
sendHeightToParent();
});
}
function draw_graphic() {
var bar_height = 25;
var bar_gap = 10;
var num_bars = graphic_data.length;
var margin = {top: 0, right: 50, bottom: 25, left: 85};
var width = $graphic.width() - margin.left - margin.right;
var height = ((bar_height + bar_gap) * num_bars);
// clear out existing graphics
$graphic.empty();
// remove placeholder table if it exists
$graphic.find('table').remove();
var x = d3.scale.linear()
// .domain([0, d3.max(graphic_data, function(d) { return parseInt(d.pct_enrolled); })])
.domain([0, d3.max(graphic_data, function(d) {
var n = parseInt(d.pct_enrolled)
return Math.ceil(n/5) * 5; // round to next 5
})])
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(7);
var x_axis_grid = function() { return xAxis; }
var svg = d3.select('#graphic').append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis);
svg.append('g')
.attr('class', 'x grid')
.attr('transform', 'translate(0,' + height + ')')
.call(x_axis_grid()
.tickSize(-height, 0, 0)
.tickFormat('')
);
svg.append('g')
.attr('class', 'bars')
.selectAll('rect')
.data(graphic_data)
.enter().append('rect')
.attr("y", function(d, i) { return i * (bar_height + bar_gap); })
.attr("width", function(d){ return x(d.pct_enrolled); })
.attr("height", bar_height)
.attr('class', function(d) { return 'age-' + d.age_group.replace(/\s+/g, '-').toLowerCase() });
svg.append('g')
.attr('class', 'value')
.selectAll('text')
.data(graphic_data)
.enter().append('text')
.attr('x', function(d) { return x(parseInt(d.pct_enrolled)) })
.attr('y', function(d, i) { return i * (bar_height + bar_gap); })
.attr('dx', 6)
.attr('dy', 17)
.attr('text-anchor', 'start')
.attr('class', function(d) { return 'age-' + d.age_group.replace(/\s+/g, '-').toLowerCase() })
.text(function(d) { return d.pct_enrolled + '%' });
svg.append('g')
.attr('class', 'label')
.selectAll('text')
.data(graphic_data)
.enter().append('text')
.attr('x', 0)
.attr('y', function(d, i) { return i * (bar_height + bar_gap); })
.attr('dx', -6)
.attr('dy', 17)
.attr('text-anchor', 'end')
.attr('class', function(d) { return 'age-' + d.age_group.replace(/\s+/g, '-').toLowerCase() })
.text(function(d) { return d.age_group });
}
function on_resize() {
draw_graphic();
}
function setup() {
setupResponsiveChild();
if (Modernizr.svg) {
load_data();
$(window).on('resize', on_resize);
}
}
setup();
});
| JavaScript | 0 | @@ -143,26 +143,25 @@
unction load
-_d
+D
ata() %7B%0A
@@ -254,34 +254,33 @@
draw
-_g
+G
raphic();%0A
@@ -291,25 +291,73 @@
se
-ndHeightToParent(
+tupResponsiveChild();%0A $(window).on('resize', onResize
);%0A
@@ -391,26 +391,25 @@
unction draw
-_g
+G
raphic() %7B%0A
@@ -774,107 +774,8 @@
);%0A%0A
- // remove placeholder table if it exists%0A $graphic.find('table').remove();%0A %0A
@@ -3755,18 +3755,17 @@
ction on
-_r
+R
esize()
@@ -3778,18 +3778,17 @@
draw
-_g
+G
raphic()
@@ -3827,41 +3827,8 @@
) %7B%0A
- setupResponsiveChild();%0A%0A
@@ -3872,64 +3872,16 @@
load
-_d
+D
ata();%0A
- $(window).on('resize', on_resize);%0A
|
13e00e81ceb2007b35535109f57b5824f1f015cb | Update ignore list to add babel-core | tools/lib/ignoredPaths.js | tools/lib/ignoredPaths.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/. */
module.exports = [
'pre-commit',
'pre-push',
'test/',
'docs/',
'tools/',
'signcode-tf',
'rx',
'nslog',
'eslint',
'cppunitlite',
'caniuse-db',
'cross-env',
'spectron',
'\\.(0|13ctype|APACHE2|BSD|DOCS|DS_Store|LESSER|Makefile|a|ac|aff|after|am|arcconfig|arclint|babelrc|bat|before|bnf|brave-gyp|c|cardinalrc|cc|cfg|closure-compiler|cmake|cmd|covignore|cpp|csv|cxx|d|def|deps|dic|dll|dntrc|dockerignore|dsp|editorconfig|editorconfig~|el|enc|entitlements|eot|esprima|flow|flowconfig|gitattributes|githug|gitignore|gitattributes|gitignore|gitkeep|gitmodules|gnu|gradle|gyp|gypi|gz|h|hbs|hxx|idl|iml|in|inc|include|info|jade|java|jsfmtrc|jshint|jshintignore|jshintrc|jslintrc|jst|js~|keep|lint|lintignore|lock|log|ls|m4|mailmap|map|markdown|md|mdown|md~|mem|min-wd|mk|mkd|mm|mustache|myspell|myspell|name|nsh|nsi|nsprc|nuspec|nvmrc|o|old|orig|otf|param|patch|pegjs|post|pre|pro|py|rej|s|sage|scss|settings|sh|skip|source-map|stamp|swo|tap|targ|template|tern-port|tern-project|testignore|tm_properties|tmp|tpl|ts|txt|un~|vscode|xcf|xml|yaml|yml)$',
'/deps/',
'Release/obj',
'obj.target',
'ad-block/(node_modules|test|perf|sample|scripts|test|vendor|ABPFilterParserData.dat)',
'tracking-protection/(node_modules|test|data|scripts|vendor)',
'tracking-protection/build/node_modules',
'tracking-protection/build/Release/(sample.exe|test.exe)',
'sqlite3/src',
'nsp/node_modules',
'electron-installer-squirrel-windows',
'electron-chromedriver',
'electron-installer-debian',
'node-notifier/vendor',
'node-gyp',
'npm',
'jsdoc',
'docs',
'sinon',
'electron-download',
'electron-rebuild',
'electron-packager',
'electron-builder',
'electron-prebuilt',
'electron-rebuild',
'electron-winstaller-fixed',
'muon-winstaller',
'electron-installer-redhat',
'flow-bin',
'babel$',
'babel-(?!polyfill|regenerator-runtime|preset-env)',
'jsdom-global',
'react-addons-perf',
'react-addons-test-utils',
'enzyme',
'git-rev-sync',
'sqlite3',
'uglify-js',
'webdriverio',
'webpack-dev-server',
'Brave(.+)',
'brave-(.+)'
]
| JavaScript | 0 | @@ -2088,16 +2088,21 @@
eset-env
+%7Ccore
)',%0A 'j
|
940dde5edcef1f5fdd3b66b1ceb5e29f0aa0a422 | add better detail example | sp-list-table/sp-list-table.js | sp-list-table/sp-list-table.js | import template from './sp-list-table.stache';
import './sp-list-table.less';
import Component from 'can-component';
import ViewModel from './ViewModel';
import '../sp-dropdown/sp-dropdown';
import 'can-dom-data';
/**
* A table to hold an array of objects - one object per row
* <iframe src="../sp-list-table/demo/index.html" style="border: 1px solid #ccc; width:100%; height:300px;"></iframe>
* @module sp-list-table
* @example
*
* <!-- stache template -->
* <sp-list-table fields:from="fields" objects:from="objects" />
*
* // viewmodel data:
* {
* objects: [{
* field_name: 'test data',
* other_name: 'more data',
* }],
* fields: ['field_name', {
* name: 'other_name',
* displayComponent: '<strong>{{object[field.name]}}</strong>
* }]
* }
*/
export default Component.extend({
tag: 'sp-list-table',
ViewModel: ViewModel,
view: template
});
| JavaScript | 0.000008 | @@ -535,16 +535,29 @@
%0A * %0A *
+@example%0A * /
// viewm
@@ -565,17 +565,16 @@
del data
-:
%0A * %7B%0A *
|
654a540b6acf2e17806027699003f91ed4313581 | Fix race condition in GlobalConfig test. | spec/ParseGlobalConfig.spec.js | spec/ParseGlobalConfig.spec.js | 'use strict';
var request = require('request');
var Parse = require('parse/node').Parse;
let Config = require('../src/Config');
describe('a GlobalConfig', () => {
beforeEach(function (done) {
let config = new Config('test');
config.database.adaptiveCollection('_GlobalConfig')
.then(coll => coll.upsertOne({ '_id': 1 }, { $set: { params: { companies: ['US', 'DK'] } } }))
.then(done());
});
it('can be retrieved', (done) => {
request.get({
url : 'http://localhost:8378/1/config',
json : true,
headers: {
'X-Parse-Application-Id': 'test',
'X-Parse-Master-Key' : 'test'
}
}, (error, response, body) => {
expect(response.statusCode).toEqual(200);
expect(body.params.companies).toEqual(['US', 'DK']);
done();
});
});
it('can be updated when a master key exists', (done) => {
request.put({
url : 'http://localhost:8378/1/config',
json : true,
body : { params: { companies: ['US', 'DK', 'SE'] } },
headers: {
'X-Parse-Application-Id': 'test',
'X-Parse-Master-Key' : 'test'
}
}, (error, response, body) => {
expect(response.statusCode).toEqual(200);
expect(body.result).toEqual(true);
done();
});
});
it('fail to update if master key is missing', (done) => {
request.put({
url : 'http://localhost:8378/1/config',
json : true,
body : { params: { companies: [] } },
headers: {
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key' : 'rest'
}
}, (error, response, body) => {
expect(response.statusCode).toEqual(403);
expect(body.error).toEqual('unauthorized: master key is required');
done();
});
});
it('failed getting config when it is missing', (done) => {
let config = new Config('test');
config.database.adaptiveCollection('_GlobalConfig')
.then(coll => coll.deleteOne({ '_id': 1 }))
.then(() => {
request.get({
url : 'http://localhost:8378/1/config',
json : true,
headers: {
'X-Parse-Application-Id': 'test',
'X-Parse-Master-Key' : 'test'
}
}, (error, response, body) => {
expect(response.statusCode).toEqual(200);
expect(body.params).toEqual({});
done();
});
});
});
});
| JavaScript | 0 | @@ -174,24 +174,16 @@
Each
-(function
(done
-)
+ =%3E
%7B%0A
@@ -387,22 +387,33 @@
.then(
+() =%3E %7B
done()
+; %7D
);%0A %7D);
|
bdb5be5f959c683ea9921002a723978a0d06bb9e | Change port in e2e tests | spec/javascript/spec_helper.js | spec/javascript/spec_helper.js | var menuOptions = element.all(by.css(".dropdown"));
var courseMenu = menuOptions.last();
var peopleMenu = menuOptions.first();
function goHome(){
browser.get("http://localhost:92/app/");
}
function goTo(option){
if("addCourse" === option){
courseMenu.click();
courseMenu.element(by.id("addCourseOpt")).click();
} else if("listCourse" === option){
courseMenu.click();
courseMenu.element(by.id("listCourseOpt")).click();
} else if("addPeople" === option){
peopleMenu.click();
peopleMenu.element(by.id("addPeopleOpt")).click();
} else if("listPeople" === option){
peopleMenu.click();
peopleMenu.element(by.id("listPeopleOpt")).click();
}
}
function createStudent(studentName){
goTo("addPeople");
element(by.model("student.name")).sendKeys(studentName);
element(by.model("student.job")).sendKeys("Licenciado en Ingenieria");
element(by.model("student.marital_status_id")).sendKeys("C");
element(by.model("student.birthday")).sendKeys("06112008");
element(by.model("student.address")).sendKeys("Av. del Pirul 365, Xochimilco, D.F.");
element(by.model("student.email")).sendKeys("salsero2008@gmail.com");
element(by.id("createPersonBtn")).click();
expect(element(by.id("buscarPersonas")).isPresent()).toBe(true);
}
function selectLastCourse(){
goTo("listCourse");
var course = element.all(by.repeater("course in courses | filter:name")).last();
course.element(by.css(".panel-heading")).click();
return course;
}
function selectLastPerson(){
goTo("listPeople");
var student = element.all(by.repeater("student in students | filter:name")).last();
student.element(by.css(".panel-heading")).click();
return student;
}
function countPeopleListed(){
goTo("listPeople");
return element.all(by.repeater("student in students | filter:name")).count();
}
function countCoursesListed(){
goTo("listCourse");
return element.all(by.repeater("course in courses | filter:name")).count();
}
function createCourse(courseName){
goTo("addCourse");
// llenamos el fornulario
element(by.model("course.name")).sendKeys(courseName);
element(by.model("course.cost")).sendKeys("60");
element(by.model("course.hour")).sendKeys("1800");
element(by.model("course.begin")).sendKeys("01012014");
element(by.model("course.end")).sendKeys("12312014");
var prefix = courseName.substring(0,3).toUpperCase();
switch(new Date().getDay()){
case 0:
element(by.cssContainingText("option", "Domingo")).click();
element(by.model("course.code")).sendKeys(prefix + "-DOM");
break;
case 1:
element(by.cssContainingText("option", "Lunes")).click();
element(by.model("course.code")).sendKeys(prefix + "-LUN");
break;
case 2:
element(by.cssContainingText("option", "Martes")).click();
element(by.model("course.code")).sendKeys(prefix + "-MAR");
break;
case 3:
element(by.cssContainingText("option", "Miercoles")).click();
element(by.model("course.code")).sendKeys(prefix + "-MIE");
break;
case 4:
element(by.cssContainingText("option", "Jueves")).click();
element(by.model("course.code")).sendKeys(prefix + "-JUE");
break;
case 5:
element(by.cssContainingText("option", "Viernes")).click();
element(by.model("course.code")).sendKeys(prefix + "-VIE");
break;
case 6:
element(by.cssContainingText("option", "Sabado")).click();
element(by.model("course.code")).sendKeys(prefix + "-SAB");
break;
}
element(by.id("createPersonBtn")).click();
// checamos que se haya actualizado la pagina
expect(element.all(by.css(".attendance-panel")).first().getText()).toEqual("Asistencia");
expect(element.all(by.css(".scholarship-panel")).first().getText()).toEqual("Becas");
expect(element.all(by.css(".students-panel")).first().getText()).toEqual("Estudiantes");
//expect(element.all(by.css(".pendingPayments-panel")).first().getText()).toEqual("Pagos Pendientes");
// checamos que los datos del curso sean los esperados
expect(element(by.model("course.name")).getAttribute("value"), "Homeopatia");
expect(element(by.model("course.code")).getAttribute("value"), "HOM-JU");
expect(element(by.model("course.cost")).getAttribute("value"), "60");
expect(element(by.model("course.day")).getAttribute("value"), "Jueves");
expect(element(by.model("course.hour")).getAttribute("value"), "1800");
expect(element(by.model("course.begin")).getAttribute("value"), "01012014");
expect(element(by.model("course.end")).getAttribute("value"), "12312014");
}
// variables
exports.menuOptions = menuOptions;
exports.courseMenu = courseMenu;
exports.peopleMenu = peopleMenu;
//functions
exports.createStudent = createStudent;
exports.createCourse = createCourse;
exports.countCoursesListed = countCoursesListed;
exports.countPeopleListed = countPeopleListed;
exports.selectLastCourse = selectLastCourse;
exports.selectLastPerson = selectLastPerson;
exports.goHome = goHome;
| JavaScript | 0 | @@ -176,15 +176,12 @@
ost:
-92/app/
+1234
%22);%0A
|
a338c9fd0b950e3068fae8a560c96bff28bd9918 | normalize id on container set | src/Component/DependencyInjection/src/Container.js | src/Component/DependencyInjection/src/Container.js | const ContainerInterface = Jymfony.Component.DependencyInjection.ContainerInterface;
const ServiceNotFoundException = Jymfony.Component.DependencyInjection.Exception.ServiceNotFoundException;
const ServiceCircularReferenceException = Jymfony.Component.DependencyInjection.Exception.ServiceCircularReferenceException;
const FrozenParameterBag = Jymfony.Component.DependencyInjection.ParameterBag.FrozenParameterBag;
const ParameterBag = Jymfony.Component.DependencyInjection.ParameterBag.ParameterBag;
const underscoreMap = {'_': '', '.': '_', '\\': '_'};
/**
* @memberOf Jymfony.Component.DependencyInjection
*/
export default class Container extends implementationOf(ContainerInterface) {
/**
* Constructor.
*
* @param {Jymfony.Component.DependencyInjection.ParameterBag.ParameterBag} [parameterBag]
*/
__construct(parameterBag = undefined) {
/**
* @type {Jymfony.Component.DependencyInjection.ParameterBag.ParameterBag}
*
* @protected
*/
this._parameterBag = parameterBag || new ParameterBag();
/**
* @type {Object}
*
* @private
*/
this._services = {};
/**
* @type {Object}
*
* @private
*/
this._methodMap = {};
/**
* @type {Object}
*
* @private
*/
this._privates = {};
/**
* @type {Object}
*
* @private
*/
this._aliases = {};
/**
* @type {Object}
*
* @private
*/
this._loading = {};
/**
* @type {Array}
*
* @private
*/
this._shutdownCalls = [];
}
/**
* Compiles the container.
*/
compile() {
this._parameterBag.resolve();
this._parameterBag = new FrozenParameterBag(this._parameterBag.all());
}
/**
* True if parameter bag is frozen.
*
* @returns {boolean}
*/
get frozen() {
return this._parameterBag instanceof FrozenParameterBag;
}
/**
* Gets the container parameter bag.
*
* @returns {Jymfony.Component.DependencyInjection.ParameterBag.ParameterBag}
*/
get parameterBag() {
return this._parameterBag;
}
/**
* Gets a parameter.
*
* @param {string} name
*
* @returns {string}
*/
getParameter(name) {
return this.parameterBag.get(name);
}
/**
* Checks if a parameter exists.
*
* @param {string} name
*
* @returns {boolean}
*/
hasParameter(name) {
return this.parameterBag.has(name);
}
/**
* Sets a parameter.
*
* @param {string} name
* @param {string} value
*/
setParameter(name, value) {
this.parameterBag.set(name, value);
}
/**
* Sets a service.
*
* @param {string} id
* @param {*} service
*/
set(id, service) {
if ('service_container' === id) {
throw new InvalidArgumentException('A service with name "service_container" cannot be set');
}
if (this._privates[id]) {
throw new InvalidArgumentException('Unsetting/setting a private service is not allowed');
}
delete this._aliases[id];
this._services[id] = service;
if (undefined === service || null === service) {
delete this._services[id];
}
}
/**
* Checks if a service is defined.
*
* @param {string} id
*
* @returns {boolean}
*/
has(id) {
id = __self.normalizeId(id);
if ('service_container' === id || undefined !== this._aliases[id] || undefined !== this._services[id]) {
return true;
}
if (undefined !== this._methodMap[id]) {
return true;
}
if (this.constructor instanceof Jymfony.Component.DependencyInjection.ContainerBuilder) {
return this['get' + __jymfony.strtr(id, underscoreMap) + 'Service'] !== undefined;
}
return false;
}
/**
* Gets a service.
*
* @param {string} id
* @param {int} [invalidBehavior = Jymfony.Component.DependencyInjection.Container.EXCEPTION_ON_INVALID_REFERENCE]
*
* @returns {*}
*/
get(id, invalidBehavior = Container.EXCEPTION_ON_INVALID_REFERENCE) {
id = __self.normalizeId(id);
if ('service_container' === id) {
return this;
}
if (this._aliases[id]) {
id = this._aliases[id];
}
if (this._services.hasOwnProperty(id)) {
return this._services[id];
}
if (this._loading[id]) {
throw new ServiceCircularReferenceException(id, Object.keys(this._loading));
}
this._loading[id] = true;
try {
if (this._methodMap[id]) {
return __self.IGNORE_ON_UNINITIALIZED_REFERENCE === invalidBehavior ? undefined : this[this._methodMap[id]]();
}
} catch (e) {
delete this._services[id];
throw e;
} finally {
delete this._loading[id];
}
if (Container.EXCEPTION_ON_INVALID_REFERENCE === invalidBehavior) {
throw new ServiceNotFoundException(id);
}
return null;
}
/**
* Checks if a given service has been initialized.
*
* @param {string} id
*
* @returns {boolean}
*/
initialized(id) {
id = __self.normalizeId(id);
if ('service_container' === id) {
return false;
}
if (this._aliases[id]) {
id = this._aliases[id];
}
return undefined !== this._services[id];
}
/**
* Executes all the shutdown functions.
*
* @returns {Promise<any[]>}
*/
shutdown() {
return Promise.all(this._shutdownCalls);
}
/**
* Resets the container.
*/
async reset() {
await this.shutdown();
this._services = {};
}
/**
* Gets all service ids.
*
* @returns {string[]}
*/
getServiceIds() {
const set = new Set([ ...Object.keys(this._methodMap), ...Object.keys(this._services), 'service_container' ]);
return Array.from(set);
}
/**
* Register a function to call at shutdown.
*
* @param {AsyncFunction|Function} call
*/
registerShutdownCall(call) {
this._shutdownCalls.push(call);
}
/**
* Normalizes a class definition (Function) to its class name.
*
* @param {string} id
*
* @returns {string}
*/
static normalizeId(id) {
const value = id;
if (undefined === id || null === id) {
throw new InvalidArgumentException('Invalid service id.');
}
if (isFunction(id)) {
try {
id = (new ReflectionClass(id)).name;
} catch (e) { }
}
if (undefined === id || null === id) {
return Symbol.for(value).description;
}
return id;
}
/**
* Underscorizes a string.
*
* @param {string} id
*
* @returns {string}
*/
static underscore(id) {
return id
.replace(/_/g, '.')
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
.replace(/([a-z\d])([A-Z])/g, '$1_$2')
.toLowerCase()
;
}
/**
* Camelizes a string.
*
* @param {string} id
*
* @returns {string}
*/
static camelize(id) {
return __jymfony.strtr(__jymfony.ucwords(__jymfony.strtr(id, {'_': ' ', '.': '_ ', '\\': '_ '})), {' ': ''});
}
}
Container.EXCEPTION_ON_INVALID_REFERENCE = 1;
Container.NULL_ON_INVALID_REFERENCE = 2;
Container.IGNORE_ON_INVALID_REFERENCE = 3;
Container.IGNORE_ON_UNINITIALIZED_REFERENCE = 4;
| JavaScript | 0.000001 | @@ -3013,32 +3013,70 @@
(id, service) %7B%0A
+ id = __self.normalizeId(id);%0A%0A
if ('ser
|
ea9a7c8b7b985587b670e8afaeae3ebbd43db107 | update browsers | _develop/browsers.js | _develop/browsers.js | const desktop = {
'mac-chrome-latest': ['OS X 10.13', 'chrome', '63.0'],
'mac-firefox-latest': ['OS X 10.13', 'firefox', '57.0'],
'mac-safari-latest': ['OS X 10.13', 'safari', '11.0'],
'mac-chrome-previous': ['OS X 10.12', 'chrome', '62.0'],
'mac-firefox-previous': ['OS X 10.12', 'firefox', '56.0'],
'mac-safari-previous': ['OS X 10.12', 'safari', '10.1'],
'windows-chrome-latest': ['Windows 10', 'chrome', '63.0'],
'windows-firefox-latest': ['Windows 10', 'firefox', '57.0'],
'windows-edge-latest': ['Windows 10', 'microsoftedge', '15.15063'],
'windows-chrome-previous': ['Windows 8.1', 'chrome', '62.0'],
'windows-firefox-previous': ['Windows 8.1', 'firefox', '56.0'],
'windows-edge-previous': ['Windows 10', 'microsoftedge', '14.14393'],
};
const mobile = {
'ios-latest': ['iPhone X Simulator', 'iOS', '11.1', 'Safari'],
'ios-previous': ['iPhone 7 Plus Simulator', 'iOS', '10.3', 'Safari'],
'android-latest': ['Android GoogleAPI Emulator', 'Android', '7.1', 'Chrome'],
'android-previous': [
'Android GoogleAPI Emulator',
'Android',
'6.0',
'Chrome',
],
};
Object.keys(desktop).forEach(key => {
module.exports[key] = {
base: 'SauceLabs',
browserName: desktop[key][1],
version: desktop[key][2],
platform: desktop[key][0],
};
});
Object.keys(mobile).forEach(key => {
module.exports[key] = {
base: 'SauceLabs',
browserName: mobile[key][3],
appiumVersion: '1.7.1',
deviceName: mobile[key][0],
deviceOrientation: 'portrait',
platformVersion: mobile[key][2],
platformName: mobile[key][1],
};
});
| JavaScript | 0.000001 | @@ -53,33 +53,33 @@
3', 'chrome', '6
-3
+5
.0'%5D,%0A 'mac-fir
@@ -112,33 +112,33 @@
', 'firefox', '5
-7
+9
.0'%5D,%0A 'mac-saf
@@ -228,33 +228,33 @@
2', 'chrome', '6
-2
+4
.0'%5D,%0A 'mac-fir
@@ -289,33 +289,33 @@
', 'firefox', '5
-6
+8
.0'%5D,%0A 'mac-saf
@@ -418,17 +418,17 @@
ome', '6
-3
+5
.0'%5D,%0A
@@ -481,17 +481,17 @@
fox', '5
-7
+9
.0'%5D,%0A
@@ -551,15 +551,15 @@
, '1
-5.15063
+6.16299
'%5D,%0A
@@ -615,17 +615,17 @@
ome', '6
-2
+4
.0'%5D,%0A
@@ -681,17 +681,17 @@
fox', '5
-6
+8
.0'%5D,%0A
@@ -753,14 +753,14 @@
, '1
-4.1439
+5.1506
3'%5D,
@@ -831,17 +831,17 @@
S', '11.
-1
+2
', 'Safa
@@ -1441,17 +1441,17 @@
n: '1.7.
-1
+2
',%0A d
|
fcbfebbf5533a8a276f9f9a9a5f5f8b62e3b8683 | update links in webpack for vanilla | src/implementations/vanilla/webpack.config.js | src/implementations/vanilla/webpack.config.js | var ExtractTextPlugin = require('extract-text-webpack-plugin');
var OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
var path = require('path');
r = {
entry: './src/web/index.js',
output: {
filename: 'hig.js',
path: path.resolve(__dirname, 'dist'),
library: 'Hig',
libraryTarget: 'umd'
},
module: {
rules: [{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: [
'es2015'
],
plugins: [],
babelrc: false,
compact: false
},
exclude: [/node_modules/, /orion-ui\/packages\/hig\.web\/dist/]
},{
test: /\.scss$/,
loader: ExtractTextPlugin.extract({
fallbackLoader: "style-loader",
loader: "css-loader!sass-loader"
}),
},{
test: /\.html$/,
use: 'raw-loader'
}]
},
resolve: {
alias: {
"basics": path.resolve(__dirname, "src", "web", "basics"),
"helpers": path.resolve(__dirname, "src", "web", "helpers"),
"components": path.resolve(__dirname, "src", "web", "components"),
"interface.json": path.resolve( __dirname, 'src/interface/interface.json' ),
"_core.js": path.resolve( __dirname, 'src/web/helpers/js/_core.js' )
},
extensions: [ '.js', '.json' ]
},
plugins: [
new ExtractTextPlugin('hig.css'),
new OptimizeCssAssetsPlugin()
]
}
if(process.env.NODE_ENV != "production"){
r['devtool'] = "eval-source-map";
}
module.exports = r; | JavaScript | 0 | @@ -187,20 +187,16 @@
'./src/
-web/
index.js
@@ -1096,23 +1096,16 @@
, %22src%22,
- %22web%22,
%22basics
@@ -1161,23 +1161,16 @@
, %22src%22,
- %22web%22,
%22helper
@@ -1234,15 +1234,8 @@
rc%22,
- %22web%22,
%22co
@@ -1302,19 +1302,21 @@
rname, '
-src
+../..
/interfa
@@ -1395,12 +1395,8 @@
src/
-web/
help
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.