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
|
---|---|---|---|---|---|---|---|
86c52e75447f9c8ba138f654bce6df3845f0ae8f
|
Add Underscore filter method
|
X.js
|
X.js
|
(function() {
// Save a reference to the global object (`window` in the browser, `exports' on the server).
var root = this;
// The top-level namespace. All public X classes and modules will
// be attached to this. Exported for both the browser and the server.
var X = typeof exports !== 'undefined' ? exports : root.X = {};
// Current version.
X.Version = 'b0.0.1';
// Use restful routes.
X.restful = true;
// Create private helper object.
var Helper = {
abstract: function ( func, data ) {
if ( typeof data[ func ] !== 'undefined' ) {
this[ func ] = data[ func ];
delete data[ func ];
}
},
destroy: function ( model ) {
return $.ajax({
url: Helper.restfulUrl( model ),
method: 'delete'
}).promise();
},
save: function ( model, method ) {
return $.ajax({
url: Helper.restfulUrl( model ),
method: method,
data: model.data || {}
}).promise();
},
fetch: function ( model ) {
return $.ajax({
url: Helper.restfulUrl( model )
}).promise();
},
restfulUrl: function ( model ) {
var url = model.url,
id = model.id;
if ( id && model.restful ) url = url + '/' + id;
else if ( id ) url = url + '?id=' + id;
return url;
}
};
// Simplify event handling.
var Events = {
on: function ( event, callback ) {
return $(this).on(event);
},
trigger: function ( event, message ) {
if ( event === 'error' && message ) throw new Error( message );
return $(this).trigger( event );
}
};
// Create a new model with the specified attributes.
var Model = X.Model = function ( data ) {
data = data || {};
this.restful = X.restful;
for ( var key in data ) if (
typeof data[ key ] === 'function' ||
key === 'url' ||
key === 'restful' ||
key === 'id'
) {
Helper.abstract.call( this, key, data );
}
this.data = $.extend({}, data);
if (this.created) Events.on.call(this, 'created');
if (this.deleted) Events.on.call(this, 'deleted');
if (this.fetched) Events.on.call(this, 'fetched');
if (this.updated) Events.on.call(this, 'updated');
};
// Attach all inheritable methods to the Model prototype.
$.extend(Model.prototype, Events, {
create: function ( callback ) {
var model = this;
function success ( res ) {
if (model.format) res = model.format( res );
if (callback) callback.call( model, res );
model.trigger('created');
}
Helper.save( model, 'post' ).then( success );
},
destroy: function ( callback ) {
var model = this;
if ( !model.id ) {
model.trigger('error', 'This model does not have an ID');
return;
}
function success ( res ) {
console.log( res );
model.trigger('destroyed');
}
Helper.destroy( model ).then( success );
},
fetch: function ( callback ) {
var model = this;
function success ( res ) {
if (res) {
if (model.format) res = model.format( res );
model.data = $.extend(model.data, res, true);
if (callback) callback.call( model, res );
model.trigger('fetched');
} else {
model.trigger('error', 'No response was returned');
}
}
Helper.fetch( model ).then( success );
},
get: function ( key ) {
return this.data[ key ];
},
set: function ( key, value ) {
this.data[ key ] = value;
return this.data[ key ];
},
update: function ( callback ) {
var model = this;
if ( !model.id ) {
model.trigger('error', 'This model does not have an ID');
return;
}
function success ( res ) {
if (model.format) res = model.format( res );
if (callback) callback.call( model, res );
model.trigger('updated');
}
Helper.save( model, 'put' ).then( success );
}
});
// Collections
var Collection = X.Collection = function ( data ) {
data = data || {};
for ( var key in data ) {
Helper.abstract.call( this, key, data );
}
this.list = [];
this.model = Model;
Events.on.call(this, function() {
this.count = this.count();
});
};
// Attach all inheritable methods to the Collection prototype.
$.extend(Collection.prototype, Events, {
add: function ( item ) {
return this.list.push(item);
},
count: function() {
return this.list.length;
},
fetch: function ( callback ) {
var collection = this;
function success ( res ) {
if (res) {
if (collection.format) res = collection.format( res );
for (var i = 0; i < res.length; i++) {
res[i].url = collection.url;
collection.add( new collection.model( res[i] ) );
}
if (callback) callback.call( collection, res );
collection.trigger('fetched');
} else {
collection.trigger('error', 'No response was returned');
}
}
Helper.fetch( collection ).then( success );
},
each: function( callback ) {
var i = 0;
for (; i < this.count(); i++) {
callback( this.list[ i ], i );
}
}
});
// Backbone extend method borrowed and modified.
Model.extend = Collection.extend = function(protoProps, staticProps) {
var parent = this;
var Surrogate;
var child = (protoProps && protoProps.hasOwnProperty('constructor')) ?
protoProps.constructor : function () {
return parent.apply(this, arguments);
};
$.extend(child, parent, staticProps);
Surrogate = function(){ this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate;
if (protoProps) $.extend(child.prototype, protoProps);
child.__super__ = parent.prototype;
return child;
};
})();
|
JavaScript
| 0 |
@@ -4728,16 +4728,96 @@
);%0A%09%09%7D,%0A
+%09%09filter: function ( callback ) %7B%0A%09%09%09return _.filter(this.list, callback);%0A%09%09%7D,%0A
%09%09each:
|
6d6058b0a02e509d6d2f1551b59dcf5a870f707b
|
Fix crash in state snapshots tab
|
src/State/BackupItem.js
|
src/State/BackupItem.js
|
import React, { Component } from "react"
import {
MDCreate as IconRename,
MDDelete as IconDelete,
MDFileUpload as IconUpload,
MDCallReceived as IconCopy,
} from "react-icons/md"
import AppStyles from "../Theme/AppStyles"
import Colors from "../Theme/Colors"
import Content from "../Shared/Content"
const Styles = {
container: {
overflow: "hidden",
borderBottom: `1px solid ${Colors.line}`,
},
row: {
...AppStyles.Layout.hbox,
padding: "15px 20px",
justifyContent: "space-between",
alignItems: "center",
cursor: "pointer",
},
name: {
color: Colors.tag,
textAlign: "left",
flex: 1,
},
iconSize: 24,
upload: {
paddingRight: 10,
cursor: "pointer",
},
button: {
cursor: "pointer",
paddingLeft: 10,
},
children: {
overflow: "hidden",
animation: "fade-up 0.25s",
willChange: "transform opacity",
padding: "0 40px 30px 40px",
},
}
export default class BackupItem extends Component {
state = {
isOpen: false,
}
handleToggle = event => {
event.stopPropagation()
this.setState(prevState => ({
isOpen: !prevState.isOpen,
}))
}
handleRemove = event => {
event.stopPropagation()
this.props.onRemove(this.props.backup)
}
handleRename = event => {
event.stopPropagation()
this.props.onRename(this.props.backup)
}
handleRestore = event => {
event.stopPropagation()
this.props.onRestore(this.props.backup)
}
handleExport = event => {
event.stopPropagation()
this.props.onExport(this.props.backup)
}
render() {
const {
backup: { name, state },
} = this.props
const { isOpen } = this.state
return (
<div style={Styles.container}>
<div style={Styles.row} onClick={this.handleToggle}>
<div style={Styles.name}>{name}</div>
<IconCopy size={Styles.iconSize} style={Styles.button} onClick={this.handleExport} />
<IconUpload size={Styles.iconSize} style={Styles.button} onClick={this.handleRestore} />
<IconRename size={Styles.iconSize} style={Styles.button} onClick={this.handleRename} />
<IconDelete size={Styles.iconSize} style={Styles.button} onClick={this.handleRemove} />
</div>
{isOpen && (
<div style={Styles.children}>
<Content value={state} />
</div>
)}
</div>
)
}
}
|
JavaScript
| 0.000001 |
@@ -46,17 +46,17 @@
rt %7B%0A M
-D
+d
Create a
@@ -72,17 +72,17 @@
ame,%0A M
-D
+d
Delete a
@@ -98,17 +98,17 @@
ete,%0A M
-D
+d
FileUplo
@@ -128,17 +128,17 @@
oad,%0A M
-D
+d
CallRece
|
fe5cf55bf4a7c96a175a58cf92add1e866b9eff7
|
trim trailing whitespace from output of JS client
|
frontend/js/cli.js
|
frontend/js/cli.js
|
#!/bin/env node
// Command-line interface for `rcomp` JS client
//
// In general this module (cli.js) is intended to be used as a NodeJS
// script in a terminal, not within a browser. Core implementation is
// in other files, in particular main.js, which can be used in other
// programs, whether NodeJS scripts or Web apps. cli.js is not
// necessary if you are embedding this client into JS code that is
// intended for use in a Web browser.
const main = require('./main.js');
// Defaults
var base_uri = undefined;
var ind = 2;
var print_help = false;
while (process.argv[ind]) {
if (process.argv[ind] == '-h' || process.argv[ind] == '--help') {
console.log('cli.js [-h] [-s URI] [COMMAND [ARG [ARG...]]]');
print_help = true;
break;
} else if (process.argv[ind] == '-s') {
if (process.argv.length - 1 <= ind) {
throw 'Missing parameter URI of switch `-s`';
}
base_uri = process.argv[ind+1];
ind += 1;
} else {
break;
}
ind += 1;
}
if (!print_help) {
if (process.argv[ind] == 'version') {
main.getServerVersion(function (res) {
console.log(res);
},
base_uri);
} else if (process.argv[ind] === undefined) {
main.getIndex(function (res) {
for (var command in res.commands) {
console.log(String(command) + '\t\t' + res.commands[command]['summary']);
}
},
base_uri);
} else {
const command = process.argv[ind];
main.find_files(command, process.argv.slice(ind+1), function (argv) {
main.callGeneric(command, argv,
function (res) {
if (res['output'].length > 0) {
console.log(res['output']);
}
process.exitCode = res['ec'];
},
base_uri);
});
}
}
|
JavaScript
| 0 |
@@ -1854,16 +1854,23 @@
output'%5D
+.trim()
);%0A
|
ce1fc28b743d518add5c89653108a287f6aa911d
|
Improve point.xRange and point.yRange performance (#5062)
|
src/elements/element.point.js
|
src/elements/element.point.js
|
'use strict';
var defaults = require('../core/core.defaults');
var Element = require('../core/core.element');
var helpers = require('../helpers/index');
var defaultColor = defaults.global.defaultColor;
defaults._set('global', {
elements: {
point: {
radius: 3,
pointStyle: 'circle',
backgroundColor: defaultColor,
borderColor: defaultColor,
borderWidth: 1,
// Hover
hitRadius: 1,
hoverRadius: 4,
hoverBorderWidth: 1
}
}
});
function xRange(mouseX) {
var vm = this._view;
return vm ? (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hitRadius, 2)) : false;
}
function yRange(mouseY) {
var vm = this._view;
return vm ? (Math.pow(mouseY - vm.y, 2) < Math.pow(vm.radius + vm.hitRadius, 2)) : false;
}
module.exports = Element.extend({
inRange: function(mouseX, mouseY) {
var vm = this._view;
return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
},
inLabelRange: xRange,
inXRange: xRange,
inYRange: yRange,
getCenterPoint: function() {
var vm = this._view;
return {
x: vm.x,
y: vm.y
};
},
getArea: function() {
return Math.PI * Math.pow(this._view.radius, 2);
},
tooltipPosition: function() {
var vm = this._view;
return {
x: vm.x,
y: vm.y,
padding: vm.radius + vm.borderWidth
};
},
draw: function(chartArea) {
var vm = this._view;
var model = this._model;
var ctx = this._chart.ctx;
var pointStyle = vm.pointStyle;
var radius = vm.radius;
var x = vm.x;
var y = vm.y;
var color = helpers.color;
var errMargin = 1.01; // 1.01 is margin for Accumulated error. (Especially Edge, IE.)
var ratio = 0;
if (vm.skip) {
return;
}
ctx.strokeStyle = vm.borderColor || defaultColor;
ctx.lineWidth = helpers.valueOrDefault(vm.borderWidth, defaults.global.elements.point.borderWidth);
ctx.fillStyle = vm.backgroundColor || defaultColor;
// Cliping for Points.
// going out from inner charArea?
if ((chartArea !== undefined) && ((model.x < chartArea.left) || (chartArea.right * errMargin < model.x) || (model.y < chartArea.top) || (chartArea.bottom * errMargin < model.y))) {
// Point fade out
if (model.x < chartArea.left) {
ratio = (x - model.x) / (chartArea.left - model.x);
} else if (chartArea.right * errMargin < model.x) {
ratio = (model.x - x) / (model.x - chartArea.right);
} else if (model.y < chartArea.top) {
ratio = (y - model.y) / (chartArea.top - model.y);
} else if (chartArea.bottom * errMargin < model.y) {
ratio = (model.y - y) / (model.y - chartArea.bottom);
}
ratio = Math.round(ratio * 100) / 100;
ctx.strokeStyle = color(ctx.strokeStyle).alpha(ratio).rgbString();
ctx.fillStyle = color(ctx.fillStyle).alpha(ratio).rgbString();
}
helpers.canvas.drawPoint(ctx, pointStyle, radius, x, y);
}
});
|
JavaScript
| 0 |
@@ -516,27 +516,27 @@
vm ? (Math.
-pow
+abs
(mouseX - vm
@@ -537,32 +537,20 @@
X - vm.x
-, 2
) %3C
-Math.pow(
vm.radiu
@@ -557,36 +557,32 @@
s + vm.hitRadius
-, 2)
) : false;%0A%7D%0A%0Afu
@@ -642,27 +642,27 @@
vm ? (Math.
-pow
+abs
(mouseY - vm
@@ -667,24 +667,12 @@
vm.y
-, 2
) %3C
-Math.pow(
vm.r
@@ -687,28 +687,24 @@
vm.hitRadius
-, 2)
) : false;%0A%7D
|
b5f7da2c86a476df90878285c119f308b69b3b82
|
add further translations / fix esxisting
|
client/js/i18n.js
|
client/js/i18n.js
|
var jsT= {
de:{
altitudep:'Höhenprofil',
altitude:'Höhenmeter',
freeBikes:'Freie Fahrräder',
freeCars:'Verfügbare Autos',
freeCharger:'Verfügbare Ladestationen',
charger:'Ladeplatz',
mountain_bike_adult:'Mountain bike',
city_bike_adult_with_gears:'City bike für Erwachsene',
mountain_bike_teenager:'Mountain bike für Jugendliche',
mountain_bike_child:'Mountain bike für Kinder',
city_bike_adult_without_gears:'City bike für Erwachsene ohne Gangschaltung',
chargingStates:{
1:'Verfügbar',
2:'Besetzt',
3:'Reserviert',
4:'Außer Dienst'
},
backtomap:'zur Kartenansicht',
chargerOnline:'Ladestation in Betrieb',
outOfOrder:'Ladestation momentan außer Betrieb',
paymentInfo:'Wie bezahle ich?',
book:'Reservieren',
deselectAll:'Alle ausblenden',
selectAll:'Alle anzeigen',
availableParkingSpaces:'Freie Parkplätze',
capacity:'Kapazität',
phone:'Tel.',
disabledtoilet:'Behindertentoilette verfügbar',
disabledcapacity:'Kapazität Behindertenparkplätze',
operator:'Betreiber',
startAddressLabel:'Startpunkt',
destinationHubLabel:'Ankuntshub',
pendularLabel:'Pendler',
arrivalTimeLabel:'Ankunft am Hub',
departureTimeLabel:'Rückfahrt vom Hub',
},
it:{
altitudep:'Profilo altimetrico',
altitude:'Altitudine',
freeBikes:'Bici disponibili',
freeCars:'Macchine disponibili',
freeCharger:'Posti di ricarica disponibili',
charger:'Posto di ricarica',
mountain_bike_adult:'Mountain bike',
city_bike_adult_with_gears:'City bike per adulti',
mountain_bike_teenager:'Mountain bike per adolescenti',
mountain_bike_child:'Mountain bike per bambini',
city_bike_adult_without_gears:'City bike per adulti senza cambio',
chargingStates:{
1:'Disponibile',
2:'Occupato',
3:'Prenotato',
4:'Fuori servizio'
},
backtomap:'Torna alla mappa',
chargerOnline:'Stazione di ricarica attiva',
outOfOrder:'Stazione fuori servizio',
paymentInfo:'Come posso pagare?',
book:'Prenota',
deselectAll:'Deseleziona tutti',
selectAll:'Seleziona tutti',
availableParkingSpaces:'Parcheggi liberi',
capacity:'Capienza',
phone:'T.',
disabledtoilet:'Bagno per disabili disponibile',
disabledcapacity:'Capienza parcheggi disabili',
operator:'Operatore',
startAddressLabel:'Indirizzo di partenza',
destinationHubLabel:'Hub di destinazione',
pendularLabel:'Pendolare',
arrivalTimeLabel:'Arrivo al hub',
departureTimeLabel:'Partenza dal hub',
},
en:{
altitudep:'Altitude profile',
altitude:'Altitude',
freeBikes:'Available bikes',
freeCars:'Available cars',
freeCharger:'Available Chargingstations',
charger:'Chargingslot',
mountain_bike_adult:'Mountain bike',
city_bike_adult_with_gears:'City bike for adults',
mountain_bike_teenager:'Mountain bike for teenager',
mountain_bike_child:'Mountain bike for children',
city_bike_adult_without_gears:'City bike for adults without gears',
chargingStates:{
1:'Available',
2:'Occupied',
3:'Reserved',
4:'Out of order'
},
backtomap:'Back to map',
chargerOnline:'Chargingstation online',
outOfOrder:'Currently out of order',
paymentInfo:'Payment info',
book:'Book',
deselectAll:'Deselect all',
selectAll:'Select all',
availableParkingSpaces:'Available parking spaces',
capacity:'Capacity',
phone:'Phone:',
disabledtoilet:'Disabled toilet available',
disabledcapacity:'Capacity disabled parking spaces',
operator:'Operator',
startAddressLabel:'Starting point',
destinationHubLabel:'Destination hub',
pendularLabel:'Pendular',
arrivalTimeLabel:'Arrival to hub',
departureTimeLabel:'Departure from hub',
}
}
|
JavaScript
| 0 |
@@ -1088,16 +1088,17 @@
l:'Ankun
+f
tshub',%0A
@@ -1148,22 +1148,16 @@
el:'
-Ankunft am Hub
+Hinfahrt
',%0A%09
@@ -1190,16 +1190,186 @@
ahrt
- vom Hub
+',%0A passengerRequests:'Mitfahrer Anfragen',%0A driverRequests:'Fahrer Anfragen',%0A driver:'Fahrer',%0A passenger:'Mitfahrer
',%0A%09
@@ -2471,27 +2471,15 @@
el:'
-Hub di destinazione
+Per hub
',%0A%09
@@ -2531,20 +2531,13 @@
l:'A
-rrivo al hub
+ndata
',%0A%09
@@ -2561,24 +2561,199 @@
el:'
-Partenza dal hub
+Ritorno',%0A passengerRequests:'Richiesta autisti',%0A driverRequests:'Richiesta passeggeri',%0A driver:'Autista',%0A passenger:'Passeggero
',%0A%09
@@ -3803,19 +3803,10 @@
el:'
-Destination
+To
hub
@@ -3860,22 +3860,23 @@
el:'
-Arrival to hub
+Planned arrival
',%0A%09
@@ -3900,26 +3900,197 @@
el:'
-Departure from hub
+Return trip',%0A passengerRequests:'Passenger requests',%0A driverRequests:'Driver requests',%0A driver:'Driver',%0A passenger:'Passenger
',%0A%09
|
29d6ce3928f38cb9f8f215c6eb0bb64536c1df76
|
fix typo in telnet client template
|
clients/telnet.js
|
clients/telnet.js
|
// Run this and then telnet to localhost:2000 and chat with the bot
var net = require("net");
var superscript = require("superscript");
var mongoose = require("mongoose");
var facts = require("sfacts");
var factSystem = facts.create('telnetFacts');
mongoose.connect('mongodb://localhost/superscriptDB');
var options = {};
var sockets = [];
var TopicSystem = require("superscriptlib/topics/index")(mongoose, factSystem);
options['factSystem'] = factSystem;
options['mongoose'] = mongoose;
var botHandle = function(err, bot) {
var receiveData = function(socket, bot, data) {
// Handle incoming messages.
var message = "" + data;
message = message.replace(/[\x0D\x0A]/g, "");
if (message.indexOf("/quit") == 0 || data.toString('hex',0,data.length) === "fff4fffd06") {
socket.end("Good-bye!\n");
return;
}
// Use the remoteIP as the name since the PORT changes on ever new connection.
bot.reply(socket.remoteAddress, message.trim(), function(err, reply){
// Find the right socket
var i = sockets.indexOf(socket);
var soc = sockets[i];
soc.write("\nBot> " + reply.string + "\n");
soc.write("You> ");
});
}
var closeSocket = function(socket, bot) {
var i = sockets.indexOf(socket);
var soc = sockets[i];
console.log("User '" + soc.name + "' has disconnected.\n");
if (i != -1) {
sockets.splice(i, 1);
}
}
var newSocket = function (socket) {
socket.name = socket.remoteAddress + ":" + socket.remotePort;
console.log("User '" + socket.name + "' has connected.\n");
sockets.push(socket);
// Send a welcome message.
socket.write('Welcome to the Telnet server!\n');
socket.write("Hello " + socket.name + "! " + "Type /quit to disconnect.\n\n");
// Send their prompt.
socket.write("You> ");
socket.on('data', function(data) {
receiveData(socket, bot, data);
});
// Handle disconnects.
socket.on('end', function() {
closeSocket(socket, bot);
});
};
// Start the TCP server.
var server = net.createServer(newSocket);
server.listen(2000);
console.log("TCP server running on port 2000.\n");
}
// This assumes the topics have been compiled to data.json first
// See superscript/bin/parse for information on how to do that.
// Main entry point
TopicSystem.importer('./data.json', function(){
new superscript(options, function(err, botInstance){
botHandle(null, botInstance);
});
});
|
JavaScript
| 0.000006 |
@@ -412,16 +412,17 @@
erscript
+/
lib/topi
|
0f8c435e05a18bca8d2456a3065ceac19d755564
|
Add ability to add dependencies in extractor
|
lib/processing/extractDocs.js
|
lib/processing/extractDocs.js
|
var path = require('path');
var _readFile = require('../utils/readFile');
function resolve(filepath) {
return path.resolve(this.source.absolutePath, filepath);
}
function addDependency(filepath) {
this.compilation.fileDependencies.push(filepath);
}
function readFile(filepath) {
return _readFile(filepath, this.fs);
}
/**
* @param {Source} source
* @param {Function} extractor
* @param {Object} options
* @param {Compilation} compilation
* @returns {Promise}
*/
function extractDocs(source, extractor, options, compilation) {
var context = {
source: source,
compilation: compilation,
compiler: compilation.compiler,
fs: compilation.compiler.inputFileSystem,
resolve: resolve,
addDependency: addDependency,
readFile: readFile
};
return extractor.call(context, source.content, options);
}
module.exports = extractDocs;
|
JavaScript
| 0.000001 |
@@ -201,27 +201,22 @@
%0A this.
-compilation
+module
.fileDep
@@ -679,16 +679,138 @@
eSystem,
+%0A module: compilation.modules.filter(function (module) %7B%0A return module.resource == source.absolutePath%0A %7D)%5B0%5D,
%0A%0A re
|
10facd118015c4e45a8ebabe8fbc288c08c448fe
|
Add the section parameter in the addTask url
|
lib/resources/gen/sections.js
|
lib/resources/gen/sections.js
|
/**
* This file is auto-generated by the `asana-api-meta` NodeJS package.
* We try to keep the generated code pretty clean but there will be lint
* errors that are just not worth fixing (like unused requires).
* TODO: maybe we can just disable those specifically and keep this code
* pretty lint-free too!
*/
/* jshint ignore:start */
var Resource = require('../resource');
var util = require('util');
var _ = require('lodash');
/**
* A _section_ is a subdivision of a project that groups tasks together. It can
* either be a header above a list of tasks in a list view or a column in a
* board view of a project.
* @class
* @param {Dispatcher} dispatcher The API dispatcher
*/
function Sections(dispatcher) {
Resource.call(this, dispatcher);
}
util.inherits(Sections, Resource);
/**
* Creates a new section in a project.
*
* Returns the full record of the newly created section.
* @param {String} project The project to create the section in
* @param {Object} data Data for the request
* @param {String} data.name The text to be displayed as the section name. This cannot be an empty string.
* @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request
* @return {Promise} The response from the API
*/
Sections.prototype.createInProject = function(
project,
data,
dispatchOptions
) {
var path = util.format('/projects/%s/sections', project);
return this.dispatchPost(path, data, dispatchOptions);
};
/**
* Returns the compact records for all sections in the specified project.
* @param {String} project The project to get sections from.
* @param {Object} [params] Parameters for the request
* @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request
* @return {Promise} The response from the API
*/
Sections.prototype.findByProject = function(
project,
params,
dispatchOptions
) {
var path = util.format('/projects/%s/sections', project);
return this.dispatchGet(path, params, dispatchOptions);
};
/**
* Returns the complete record for a single section.
* @param {String} section The section to get.
* @param {Object} [params] Parameters for the request
* @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request
* @return {Promise} The requested resource
*/
Sections.prototype.findById = function(
section,
params,
dispatchOptions
) {
var path = util.format('/sections/%s', section);
return this.dispatchGet(path, params, dispatchOptions);
};
/**
* A specific, existing section can be updated by making a PUT request on
* the URL for that project. Only the fields provided in the `data` block
* will be updated; any unspecified fields will remain unchanged. (note that
* at this time, the only field that can be updated is the `name` field.)
*
* When using this method, it is best to specify only those fields you wish
* to change, or else you may overwrite changes made by another user since
* you last retrieved the task.
*
* Returns the complete updated section record.
* @param {String} section The section to update.
* @param {Object} data Data for the request
* @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request
* @return {Promise} The response from the API
*/
Sections.prototype.update = function(
section,
data,
dispatchOptions
) {
var path = util.format('/sections/%s', section);
return this.dispatchPut(path, data, dispatchOptions);
};
/**
* A specific, existing section can be deleted by making a DELETE request
* on the URL for that section.
*
* Note that sections must be empty to be deleted.
*
* The last remaining section in a board view cannot be deleted.
*
* Returns an empty data block.
* @param {String} section The section to delete.
* @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request
* @return {Promise} The response from the API
*/
Sections.prototype.delete = function(
section,
dispatchOptions
) {
var path = util.format('/sections/%s', section);
return this.dispatchDelete(path, dispatchOptions);
};
/**
* Add a task to a specific, existing section. This will remove the task from other sections of the project.
*
* The task will be inserted at the top of a section unless an `insert_before` or `insert_after` parameter is declared.
*
* This does not work for separators (tasks with the `resource_subtype` of section).
* @param {String} task The task to add to this section
* @param {Object} data Data for the request
* @param {String} [data.insert_before] Insert the given task immediately before the task specified by this parameter. Cannot be provided together with `insert_after`.
* @param {String} [data.insert_after] Insert the given task immediately after the task specified by this parameter. Cannot be provided together with `insert_before`.
* @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request
* @return {Promise} The response from the API
*/
Sections.prototype.addTask = function(
task,
data,
dispatchOptions
) {
var path = util.format('/sections/%s/addTask', task);
return this.dispatchPost(path, data, dispatchOptions);
};
/**
* Move sections relative to each other in a board view. One of
* `before_section` or `after_section` is required.
*
* Sections cannot be moved between projects.
*
* At this point in time, moving sections is not supported in list views, only board views.
*
* Returns an empty data block.
* @param {String} project The project in which to reorder the given section
* @param {Object} data Data for the request
* @param {String} data.section The section to reorder
* @param {String} [data.before_section] Insert the given section immediately before the section specified by this parameter.
* @param {String} [data.after_section] Insert the given section immediately after the section specified by this parameter.
* @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request
* @return {Promise} The response from the API
*/
Sections.prototype.insertInProject = function(
project,
data,
dispatchOptions
) {
var path = util.format('/projects/%s/sections/insert', project);
return this.dispatchPost(path, data, dispatchOptions);
};
module.exports = Sections;
/* jshint ignore:end */
|
JavaScript
| 0.000001 |
@@ -4538,44 +4538,52 @@
ng%7D
-task The task to add to this section
+section The section in which to add the task
%0A
@@ -4618,32 +4618,95 @@
for the request%0A
+ * @param %7BString%7D data.task The task to add to this section%0A
* @param %7BStr
@@ -5219,20 +5219,23 @@
on(%0A
-task
+section
,%0A da
@@ -5311,20 +5311,23 @@
dTask',
-task
+section
);%0A%0A re
|
55aa0dadf0ccb7a95b5ad437ea993cf0a710f6d3
|
fix context resolve event $origin
|
lib/base/context.js
|
lib/base/context.js
|
"use strict";
var Base = require('./index.js')
var define = Object.defineProperty
/**
* @function $createContextGetter
* @memberOf Base#
* @param {string} key Key to create the context getter for
*/
exports.$createContextGetter = function( key, value ) {
if(!value) {
value = this[key]
}
if( value && value.$createContextGetter ) {
var privateKey = '_'+key
this[privateKey] = value
for( var val_key in value ) {
if( val_key[0] !== '_' && !value['_'+val_key] ) {
value.$createContextGetter( val_key )
}
}
define( this, key, {
get: function(){
var value = this[privateKey]
if( value instanceof Base ) {
if( !this.hasOwnProperty( privateKey ) ) {
value._$context = this
value._$contextLevel = 1
} else if( this._$context ) {
value._$contextLevel = this._$contextLevel + 1
value._$context = this._$context
} else {
value.$clearContext()
}
}
return value
},
set: function( val ) {
this[privateKey] = val
},
configurable:true
})
}
}
var cnt = 0
exports.$resolveContextSet = function( val, event, context ) {
var i = this._$contextLevel
var context = context || this._$context
if(!context) {
console.error('not context')
}
var iterator = this
var path = []
while( i ) {
var key = iterator.$key
path.unshift( key )
iterator = iterator._$parent
i--
}
for (i = 0; i < path.length; i++) {
context = context.$setKeyInternal(path[i],
i === path.length - 1 ? val : {},
context[path[i]],
event,
true);
}
return context;
}
exports.$clearContext = function() {
//this is cleaner else null will be added on base and some things
//dont use this
if( this._$context ) {
this._$contextLevel = null
this._$context = null
this._$contextKey = null
}
return this
}
/**
* Parent of base object
* @name $parent
* @memberOf Base#
* @type {base}
*/
exports.$parent = {
get:function() {
//like this is extra confuse!
if(this._$contextLevel === 1) {
return this._$context
} else if(this._$contextLevel) {
//set context on parent based on current context
if(this._$parent && !this._$parent._$context) {
// console.error('XXXXXXX???XXXXXX', this._$parent)
//find level from context
this._$parent._$context = this._$context
this._$parent._$contextLevel = this._$contextLevel-1
} else {
return this._$parent
}
} else {
return this._$parent
}
// return this._$contextLevel === 1
// ? this._$context
// : this._$parent
},
set:function( val ) {
this._$parent = val
}
}
exports.$clearContextPath = function() {
// if( this._$context ) {
// console.log('??', instance)
//
// var instance = this
// var length = this._$contextLevel;
// for( var i = 0; i < length; i++ ) {
// if(instance) {
// console.log('????', instance)
// instance.$clearContext()
// }
// instance = instance._$parent
// }
// // this.$clearContext()
// }
var parent = this
// this.$clearContext()
while( parent ) {
parent.$clearContext()
parent = parent._$parent
}
}
exports.$path = {
get:function() {
var path = []
var parent = this
while( parent && parent.$key !== void 0 ) {
path.unshift( parent._$contextKey || parent.$key )
parent = parent.$parent// || parent.$context
}
return path
}
}
|
JavaScript
| 0.000092 |
@@ -1513,16 +1513,97 @@
--%0A %7D%0A%0A
+ var resolveEventOrigin = event && event.$origin && event.$context === context%0A%0A
for (i
@@ -1774,16 +1774,103 @@
);%0A %7D%0A%0A
+ if (resolveEventOrigin) %7B%0A event.$context = null%0A event.$origin = context%0A %7D%0A%0A
return
|
0f1dcbd1eccd53a4014c28e7b37d93badb75530c
|
version bump
|
lib/bbop/version.js
|
lib/bbop/version.js
|
/*
* Package: version.js
*
* Namespace: bbop.version
*
* This package was automatically created during the release process
* and contains its version information--this is the release of the
* API that you have.
*/
bbop.core.namespace('bbop', 'version');
bbop.version = {};
/*
* Variable: revision
*
* Partial version for this library; revision (major/minor version numbers)
* information.
*/
bbop.version.revision = "0.9";
/*
* Variable: release
*
* Partial version for this library: release (date-like) information.
*/
bbop.version.release = "20130320";
|
JavaScript
| 0.000001 |
@@ -568,12 +568,12 @@
%222013032
-0
+1
%22;%0A
|
7a95011d0e6281fd79e342b4c1397dcca19a7d89
|
Update playing command
|
lib/cmds/playing.js
|
lib/cmds/playing.js
|
'use strict';
exports.info = {
name: 'playing',
desc: 'Posts a list of members playing the specified game.',
usage: '<game>',
aliases: [],
};
const logger = require('winston');
exports.run = (client, msg, params = []) => {
// Exit if no 'question' was asked
if (params.length === 0) {
logger.debug('No parameters passed to playing');
return;
}
const players = msg.guild.members
.filter(m => m.user.presence.game && m.user.presence.game.name.toLowerCase() === params[0].toLowerCase())
.map(m => {
return { name: m.user.username, mod: m.user.username.toLowerCase() };
})
.sort((a, b) => {
if (a.mod < b.mod) {
return -1;
}
if (a.mod > b.mod) {
return 1;
}
return 0;
})
.map(p => p.name);
if (players.length === 0) {
msg.channel.sendMessage(`Nobody is playing \`\`${params[0]}\`\``);
} else {
msg.channel.sendMessage(`\`\`\`qml\nPlaying ${params[0]}:\`\`\`\n${players.join('\n')}`);
}
};
|
JavaScript
| 0 |
@@ -361,16 +361,49 @@
rn;%0A %7D%0A
+ const game = params.join(' ');%0A
const
@@ -514,22 +514,22 @@
se()
- === params%5B0%5D
+.includes(game
.toL
@@ -539,16 +539,17 @@
rCase())
+)
%0A .ma
@@ -629,16 +629,49 @@
erCase()
+, game: m.user.presence.game.name
%7D;%0A
@@ -843,14 +843,31 @@
=%3E
+%60$%7B
p.name
+%7D ($%7Bp.game%7D)%60
);%0A
@@ -948,25 +948,20 @@
g %5C%60%5C%60$%7B
-params%5B0%5D
+game
%7D%5C%60%5C%60%60);
@@ -1026,17 +1026,12 @@
g $%7B
-params%5B0%5D
+game
%7D:%5C%60
|
c2c6a40a7a5c25357e34cb3591477be8895e5d79
|
Remove error from errors object.
|
lib/common/error.js
|
lib/common/error.js
|
/*
* Copyright (c) 2014 Modulus
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
var error = module.exports;
error.handlePromptError = function(err, cb) {
//Check if canceled by the user (CTRL+C)
if(err.message && err.message === 'canceled') {
console.log(''); //Extra space.
return cb('Canceled by user.');
}
return cb(err);
};
error.handleApiError = function(err, command, cb) {
var e = error.getError(err, command);
if(e.level < 2) {
cb(e.message);
return '';
} else {
return e.message;
}
};
error.getError = function(err, command) {
var id = 'DEFAULT';
var msg = '';
if(err.code) {
id = err.code;
} else if(err.errors && err.errors.length > 0) {
id = err.errors[0].id;
msg = err.errors[0].message;
}
for(var e in error.responseCodes) {
if(id === e) {
// If there is no message set,
// use the message from congress
if(error.responseCodes[e].message === null) {
var ret = error.responseCodes[e];
ret.message = msg;
return ret;
}
return error.responseCodes[e];
}
}
if(typeof command === 'string') {
for(var c in error.commandCodes) {
if(command === c) {
return error.commandCodes[c];
}
}
}
return error.responseCodes.DEFAULT;
};
/*--- Error Codes ---*/
// Level 0 - Something very bad happened, panic.
// Level 1 - Processing error, do not continue.
// Level 2 - Format/Input error, try again.
error.responseCodes = {
DEFAULT : {
id : 'DEFAULT',
level : 1,
message : 'There was an error processing your request.'
},
ECONNREFUSED : {
id : 'ECONNREFUSED',
level : 1,
message : 'Could not connect to Modulus.'
},
INVALID_AUTH : {
id : 'INVALID_AUTH',
level : 1,
message : 'Your session has expired. Please log in to continue.'
},
USERNAME_ALREADY_EXISTS : {
id : 'USERNAME_ALREADY_EXISTS',
level : 2,
message : null
},
EMAIL_ALREADY_EXISTS : {
id : 'EMAIL_ALREADY_EXISTS',
level : 2,
message : null
},
BETA_KEY_NOT_FOUND : {
id : 'BETA_KEY_NOT_FOUND',
level : 2,
message : null
},
BETA_KEY_ALEADY_USED : {
id : 'BETA_KEY_ALEADY_USED',
level : 2,
message : null
},
PROJECT_LIMIT_REACHED : {
id : 'PROJECT_LIMIT_REACHED',
level : 1,
message : null
},
NO_CAPACITY : {
id : 'NO_CAPACITY',
level : 2,
message : 'Not enough capacity for new project. New capacity is being added now. Please attempt the request again in a few minutes.'
},
PROJECT_ZIP_TOO_LARGE: {
id : 'PROJECT_ZIP_TOO_LARGE',
level : 1,
message : 'Your application must be less than 1gb in size.'
},
NO_MATCHING_NAME: {
id : 'NO_MATCHING_NAME',
level: 1,
message: 'No project found that matches specified name.'
},
NO_MATCHING_DB_NAME: {
id : 'NO_MATCHING_DB_NAME',
level: 1,
message: 'No database found that matches specified name.'
},
OAUTH_TOKEN_NOT_FOUND: {
id : 'OAUTH_TOKEN_NOT_FOUND',
level : 1,
message : 'Please link your account with GitHub using the web portal to use GitHub authentication.'
},
SINGLE_SIGN_ON_USER_NOT_FOUND: {
id : 'SINGLE_SIGN_ON_USER_NOT_FOUND',
level : 1,
message : 'GitHub account not found. Please link your account with GitHub using the web portal to use GitHub authentication.'
},
INVALID_ENV_VARIABLE_VALUE: {
id: 'INVALID_ENV_VARIABLE_VALUE',
level: 2,
message: 'Environment variable values cannot contain single quotes.'
},
INVALID_ENV_VARIABLE_NAME: {
id: 'INVALID_ENV_VARIABLE_NAME',
level: 2,
message: 'Variable names cannot start with numbers, can only contain alpha-numeric characters and underscores, and cannot contain quotes.'
},
INVALID_PROJECT_TYPE: {
id: 'INVALID_PROJECT_TYPE',
level: 1,
message: 'The project type you have provided was not recognized.'
},
API_KEY_NOT_FOUND: {
id: 'API_KEY_NOT_FOUND',
level: 1,
message: 'Token not found. Please ensure it was entered correctly and try again.'
},
INVALID_JSON: {
id: 'INVALID_JSON',
level: 1,
message: 'Invalid JSON content.'
},
INVALID_JSON_FILE: {
id: 'INVALID_JSON_FILE',
level: 1,
message: 'Invalid package.json file.'
},
UPDATE_JSON_FILE_FAIL: {
id: 'UPDATE_JSON_FILE_FAIL',
level: 1,
message: 'Error updating package.json file.'
},
INVALID_VALUE: {
id: 'INVALID_VALUE',
level: 1,
message: 'Failed to parse environment variable value.'
},
INVALID_FILE: {
id: 'INVALID_FILE',
level: 1,
message: 'The specified file is missing or invalid.'
},
INVALID_FLAGS: {
id: 'INVALID_FLAGS',
level: 1,
message: 'You must be verified to perform this action. Visit https://modulus.io/verify to verify your account.'
}
};
error.commandCodes = {
LOGIN : {
id : 'LOGIN',
level : 2,
message : 'Username or Password incorrect.\nFor Github users, use the --github option.'
},
CREATE_MONGO : {
id : 'CREATE_MONGO',
level : 1,
message : 'MongoDB database could not be created.'
},
GET_DATABASES : {
id : 'GET_DATABASES',
level : 1,
message : 'Could not retreive databases for user.'
}
};
|
JavaScript
| 0 |
@@ -5310,136 +5310,8 @@
%7D,%0A
- UPDATE_JSON_FILE_FAIL: %7B%0A id: 'UPDATE_JSON_FILE_FAIL',%0A level: 1,%0A message: 'Error updating package.json file.'%0A %7D,%0A
IN
|
85d11b6f162af3dd4cd0c2d24472f4c393004d6c
|
Make sure the secondary view has an id
|
src/views/FilesSidebarCallView.js
|
src/views/FilesSidebarCallView.js
|
/**
*
* @copyright Copyright (c) 2019, Daniel Calviño Sánchez <[email protected]>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* Helper class to wrap a Vue instance with a FilesSidebarCallViewApp component
* to be used as a secondary view in the Files sidebar.
*
* Although Vue instances/components can be added as tabs to the Files sidebar
* currently only legacy views can be added as secondary views to the Files
* sidebar. Those legacy views are expected to provide a root element, $el, with
* a "replaceAll" method that replaces the given element with the $el element,
* and a "setFileInfo" method that is called when the sidebar is opened or the
* current file changes.
*/
export default class FilesSidebarCallView {
constructor() {
this.callViewInstance = OCA.Talk.newCallView()
this.$el = document.createElement('div')
this.callViewInstance.$mount(this.$el)
this.$el = this.callViewInstance.$el
this.$el.replaceAll = function(target) {
target.replaceWith(this.$el)
}.bind(this)
}
setFileInfo(fileInfo) {
// The FilesSidebarCallViewApp is the first (and only) child of the Vue
// instance.
this.callViewInstance.$children[0].setFileInfo(fileInfo)
}
}
|
JavaScript
| 0 |
@@ -1531,16 +1531,51 @@
t('div')
+%0A%09%09this.id = 'FilesSidebarCallView'
%0A%0A%09%09this
|
9a55c0b36ad107699d5f3f4b70b668be8f870995
|
Fix for loop closure when adding event listeners; Added show and hide default to the list library
|
list.js
|
list.js
|
define(["github/adioo/bind/v0.2.0/bind", "/jquery.js"], function(Bind) {
function List(module) {
var self;
var config;
var container;
var template;
function processConfig(config) {
config.options = config.options || {};
config.template.binds = config.template.binds || [];
var optClasses = config.options.classes || {}
optClasses.item = optClasses.item || "item";
optClasses.selected = optClasses.selected || "selected";
config.options.classes = optClasses;
return config;
}
function init(conf) {
// initialize the globals
self = this;
config = processConfig(conf);
if (config.container) {
container = $(config.container, module.dom);
} else {
container = module.dom;
}
template = $(config.template.value, module.dom);
// **************************************
// generate general binds from the config
var binds = [];
for (var i in config.controls) {
switch (i) {
case "add":
binds.push({
target: ".create",
context: ".controls",
on: [{
name: "click",
emit: "requestNewItem"
}]
});
break;
case "delete":
binds.push({
target: ".delete",
context: ".controls",
on: [{
name: "click",
handler: "removeSelected"
}]
});
break;
}
}
// run the internal binds
for (var i in binds) {
Bind.call(self, binds[i]);
}
// run the binds
for (var i in config.binds) {
Bind.call(self, config.binds[i]);
}
self.on("newItem", createItem);
// for each module instance I listen to
for (var miid in config.listen) {
var miidEvents = config.listen[miid];
// for each event for this instance
for (var name in miidEvents) {
var handler = miidEvents[name];
// if the handler is a module function name
if (typeof handler === "string" && typeof self[handler] === "function") {
self.on(name, miid, function(data) {
self[handler].call(self, data);
});
continue;
}
// else it must be object
if (handler instanceof Object) {
// TODO
}
}
}
if (config.options.autofetch) {
self.read();
}
}
function render(item) {
switch (config.template.type) {
case "selector":
renderSelector.call(self, item);
case "html":
// TODO
case "url":
// TODO
}
}
function renderSelector(item) {
var newItem = $(template).clone();
newItem
.removeClass("template")
.addClass(config.options.classes.item)
.appendTo(container)
.show();
for (var i in config.template.binds) {
var bindObj = config.template.binds[i];
bindObj.context = newItem;
Bind.call(self, bindObj, item);
}
}
function clearList() {
$("." + config.options.classes.item, container).remove();
}
// ********************************
// Public functions ***************
// ********************************
function read(data) {
clearList();
self.link(config.crud.read, { data: data }, function(err, data) {
if (err) { return; }
for (var i in data) {
render.call(self, data[i]);
}
});
}
function createItem(itemData) {
self.link(config.crud.create, { data: itemData }, function(err, data) {
if (err) { return; }
});
}
function removeItem(itemData) {
self.link(config.crud.delete, { data: { id: itemData.id } }, function(err, data) {
if (err) { return; }
$("#" + itemData.id).remove();
});
}
function removeSelected() {
var ids = [];
var selectedClass = config.options.classes.selected;
$("." + selectedClass, container).each(function() {
ids.push($(this).attr("id"));
});
self.link(config.crud.delete, { data: { ids: ids } }, function(err, data) {
if (err) { return; }
$("." + selectedClass, container).remove();
});
}
function selectItem(dataItem) {
var selectedClass = config.options.classes.selected;
switch (config.options.selection) {
case "single":
var currentItem = $("#" + dataItem.id, container);
if (currentItem.hasClass(selectedClass)) {
break;
}
$("." + selectedClass, container).removeClass(selectedClass);
$("#" + dataItem.id, container).addClass(selectedClass);
self.emit("selectionChanged", dataItem);
break;
case "multiple":
$("#" + dataItem.id, module.dom).toggleClass(selectedClass);
break;
default: // none
}
}
return {
init: init,
read: read,
removeItem: removeItem,
removeSelected: removeSelected,
selectItem: selectItem
};
}
return function(module, config) {
var list = new List(module);
for (var i in list) {
list[i] = module[i] || list[i];
}
list = Object.extend(list, module);
list.init(config);
return list;
}
});
|
JavaScript
| 0 |
@@ -2422,24 +2422,25 @@
g.listen) %7B%0A
+%0A
@@ -2481,16 +2481,17 @@
%5Bmiid%5D;%0A
+%0A
@@ -2577,24 +2577,25 @@
idEvents) %7B%0A
+%0A
@@ -2634,16 +2634,17 @@
%5Bname%5D;%0A
+%0A
@@ -2789,24 +2789,72 @@
unction%22) %7B%0A
+%0A (function(handler) %7B%0A
@@ -2857,32 +2857,34 @@
+
self.on(name, mi
@@ -2896,32 +2896,36 @@
unction(data) %7B%0A
+
@@ -2984,35 +2984,77 @@
-%7D);
+ %7D);%0A %7D)(handler);%0A
%0A
@@ -6431,32 +6431,188 @@
%7D%0A %7D%0A%0A
+ function show() %7B%0A $(self.dom).parent().show();%0A %7D%0A%0A function hide() %7B%0A $(self.dom).parent().hide();%0A %7D%0A%0A
return
@@ -6771,24 +6771,72 @@
: selectItem
+,%0A show: show,%0A hide: hide
%0A %7D;%0A
|
2a548d36141a05e79c6709aa18b8cdb8e87a6069
|
Remove double newline
|
src/functions/music/player.js
|
src/functions/music/player.js
|
const streamy = require("stream");
const fs = require('fs');
const request = require("request");
const spawn = require("child_process").spawn
module.exports = Player;
function Player(message) {
var that = this;
this.message = message;
this.playlist = [];
this.current = {};
this.pid = {};
this.connection = null;
this.connect = function() {
console.log(`Message: Connecting to Voice Channel`);
this.message.member.voiceChannel
.join()
.then((connection) => {
this.connection = connection;
this.play();
});
}
this.play = function() {
console.log(`Message: Checking playlist length`);
if(this.playlist.length === 0) return this.message.member.voiceChannel.leave();
console.log(`Message: Shifting playlist`);
this.current = this.playlist.shift();
//Make an ffmpeg stream
console.log(`Message: Making FFMPEG stream`);
let ffmpeg = spawn('ffmpeg', [
'-i', 'pipe:0',
'-f', 'wav',
'pipe:1'
]);
//Set the PID of this.
this.pid.ffmpeg = ffmpeg.pid;
//Try it! If it fails, it skips it.
try {
console.log(`Message: Playing from ${this.current.type}`);
//Send the correct input to the ffmpeg stream
switch (this.current.type) {
//Stream from YouTube
case "youtube":
let youtube_dl = spawn('youtube-dl', [
"-o", "-",
this.current.url
]);
this.pid.youtube_dl = youtube_dl.pid;
youtube_dl.on("close", () => {
this.pid.youtube_dl = null;
});
youtube_dl.stdout.pipe(ffmpeg.stdin);
break;
//Stream from a local file
case "local":
fs.createReadStream(this.current.url)
.pipe(ffmpeg.stdin);
break;
//Stream from the internet!
case "http":
case "https":
request.get(this.current.url)
.on("error", (err) => {
this.message.channel.send(`A HTTP error occured. Congratulations!`);
this.play();
})
.pipe(ffmpeg.stdin);
break;
default:
console.log(`Failure: Incorrect audio type`);
this.message.channel.send(`${this.current.type} is not a valid audio provider.`);
this.play();
}
//Send FFMPEG's output to the connection
console.log(`Message: Piping FFMPEG to the connection`);
let dispatcher = this.connection.playStream(ffmpeg.stdout);
//Check for FFMPEG errors
ffmpeg.stderr.setEncoding('utf8');
ffmpeg.stderr.on('data', function(data) {
if(/^execvp\(\)/.test(data)) {
console.log('failed to start ' + argv.ffmpeg);
console.log(`Failure: FFMPEG`);
}
});
//The stream has ended, therefore it can go on to the next song
dispatcher.on("end", () => {
this.play();
});
ffmpeg.on("close", () => {
this.pid.ffmpeg = null;
});
} catch(e) {
console.log(`Failure: ${e.message}`);
this.message.channel.send(`${e.message} - Skipping...`);
this.play();
}
}
this.add = function(type, url, title, thumb) {
this.playlist.push({
type: type,
url: url,
title: title,
thumb_url: thumb
});
//If the bot is not playing, enter the channel and start playing
if (!this.message.member.voiceChannel.connection) {
this.connect();
}
}
this.skip = function() {
if(this.pid.ffmpeg) process.kill(this.pid.ffmpeg, "SIGINT");
if(this.pid.youtube_dl) process.kill(this.pid.youtube_dl);
this.pid = {};
}
this.stop = function() {
this.skip();
this.current = {};
this.playlist = [];
}
}
process.on("unhandledRejection", function(err) {
console.log("Uncaught Promise Error: \n" + err.stack);
});
process.on("uncaughtException", function(err) {
if(err.message != "read ECONNRESET") {
console.log(err.stack);
return process.exit(1)
};
});
|
JavaScript
| 0.00001 |
@@ -3641,13 +3641,12 @@
(1)%0A%09%7D;%0A%7D);%0A
-%0A
|
1b5c7392413d3976849357bcf31c0efee439fdf2
|
Use deepmerge on loaded inventory items
|
src/game-data/player-items.js
|
src/game-data/player-items.js
|
import devtools from '../devtools';
import { REALLY_BIG_NUMBER } from '../utils';
import { load } from '../save';
import merge from 'deepmerge';
import PineCone from '../sprites/object/PineCone';
const itemMax = 500;
const loadedItems = load('items') || {};
const defaultItems = {
'wood-axe': {
value: true,
rank: 0,
sellable: false,
},
bucket: {
value: false,
sellable: false,
},
water: {
value: 0,
max: itemMax,
sellable: false,
},
log: {
value: 0,
max: itemMax,
sellable: true,
},
'pine-cone': {
value: 0,
max: itemMax,
sellable: false,
},
};
let items = Object.assign(defaultItems, loadedItems);
items['pine-cone'].place = PineCone;
let money = load('money') || 0;
export { items, money };
|
JavaScript
| 0 |
@@ -636,21 +636,13 @@
s =
-Object.assign
+merge
(def
|
874cce97028a934067469c953f42703f653e3d44
|
fix focus blur event order test (#1077)
|
Gulpfile.js
|
Gulpfile.js
|
var babel = require('babel-core');
var gulpBabel = require('gulp-babel');
var del = require('del');
var eslint = require('gulp-eslint');
var fs = require('fs');
var gulp = require('gulp');
var qunitHarness = require('gulp-qunit-harness');
var mocha = require('gulp-mocha');
var mustache = require('gulp-mustache');
var rename = require('gulp-rename');
var webmake = require('gulp-webmake');
var Promise = require('pinkie');
var uglify = require('gulp-uglify');
var gulpif = require('gulp-if');
var util = require('gulp-util');
var ll = require('gulp-ll');
var path = require('path');
ll
.tasks('lint')
.onlyInDebug([
'server-scripts',
'client-scripts-bundle'
]);
var CLIENT_TESTS_SETTINGS = {
basePath: './test/client/fixtures',
port: 2000,
crossDomainPort: 2001,
scripts: [
{ src: '/hammerhead.js', path: './lib/client/hammerhead.js' },
{ src: '/before-test.js', path: './test/client/before-test.js' }
],
configApp: require('./test/client/config-qunit-server-app')
};
var CLIENT_TESTS_BROWSERS = [
{
platform: 'Windows 10',
browserName: 'MicrosoftEdge'
},
{
platform: 'Windows 10',
browserName: 'chrome'
},
{
platform: 'Windows 10',
browserName: 'chrome',
version: 'beta'
},
{
platform: 'Windows 10',
browserName: 'firefox'
},
{
platform: 'Windows 10',
browserName: 'internet explorer',
version: '11.0'
},
{
platform: 'Windows 8',
browserName: 'internet explorer',
version: '10.0'
},
{
platform: 'Windows 7',
browserName: 'internet explorer',
version: '9.0'
},
{
browserName: 'safari',
platform: 'OS X 10.10',
version: '8.0'
},
{
browserName: 'Safari',
deviceName: 'iPhone 6 Plus',
platformVersion: '9.3',
platformName: 'iOS'
},
{
browserName: 'Safari',
deviceName: 'iPhone 7 Plus Simulator',
platformVersion: '10.0',
platformName: 'iOS'
},
{
browserName: 'android',
platform: 'Linux',
version: '5.1',
deviceName: 'Android Emulator'
},
{
browserName: 'chrome',
platform: 'OS X 10.11'
},
{
browserName: 'firefox',
platform: 'OS X 10.11'
}
];
var SAUCELABS_SETTINGS = {
username: process.env.SAUCE_USERNAME,
accessKey: process.env.SAUCE_ACCESS_KEY,
build: process.env.TRAVIS_JOB_ID || '',
tags: [process.env.TRAVIS_BRANCH || 'master'],
browsers: CLIENT_TESTS_BROWSERS,
name: 'testcafe-hammerhead client tests',
timeout: 300
};
function hang () {
return new Promise(function () {
// NOTE: Hang forever.
});
}
// Build
gulp.task('clean', function (cb) {
del(['./lib'], cb);
});
gulp.task('templates', ['clean'], function () {
return gulp
.src('./src/client/task.js.mustache', { silent: false })
.pipe(gulp.dest('./lib/client'));
});
gulp.task('client-scripts', ['client-scripts-bundle'], function () {
return gulp.src('./src/client/index.js.wrapper.mustache')
.pipe(mustache({ source: fs.readFileSync('./lib/client/hammerhead.js').toString() }))
.pipe(rename('hammerhead.js'))
.pipe(gulpif(!util.env.dev, uglify()))
.pipe(gulp.dest('./lib/client'));
});
gulp.task('client-scripts-bundle', ['clean'], function () {
return gulp.src('./src/client/index.js')
.pipe(webmake({
sourceMap: false,
transform: function (filename, code) {
var transformed = babel.transform(code, {
sourceMap: false,
filename: filename,
ast: false,
// NOTE: force usage of client .babelrc for all
// files, regardless of their location
babelrc: false,
extends: path.join(__dirname, './src/client/.babelrc')
});
// HACK: babel-plugin-transform-es2015-modules-commonjs forces
// 'use strict' insertion. We need to remove it manually because
// of https://github.com/DevExpress/testcafe/issues/258
return { code: transformed.code.replace(/^('|")use strict('|");?/, '') };
}
}))
.pipe(rename('hammerhead.js'))
.pipe(gulp.dest('./lib/client'));
});
gulp.task('server-scripts', ['clean'], function () {
return gulp.src(['./src/**/*.js', '!./src/client/**/*.js'])
.pipe(gulpBabel())
.pipe(gulp.dest('lib/'));
});
gulp.task('lint', function () {
return gulp
.src([
'./src/**/*.js',
'./test/server/*.js',
'./test/client/fixtures/**/*.js',
'Gulpfile.js'
])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
gulp.task('build', ['client-scripts', 'server-scripts', 'templates', 'lint']);
// Test
gulp.task('test-server', ['build'], function () {
return gulp.src('./test/server/*-test.js', { read: false })
.pipe(mocha({
ui: 'bdd',
reporter: 'spec',
// NOTE: Disable timeouts in debug mode.
timeout: typeof v8debug === 'undefined' ? 2000 : Infinity
}));
});
gulp.task('test-client', ['build'], function () {
gulp.watch('./src/**', ['build']);
return gulp
.src('./test/client/fixtures/**/*-test.js')
.pipe(qunitHarness(CLIENT_TESTS_SETTINGS));
});
gulp.task('test-client-travis', ['build'], function () {
return gulp
.src('./test/client/fixtures/**/*-test.js')
.pipe(qunitHarness(CLIENT_TESTS_SETTINGS, SAUCELABS_SETTINGS));
});
gulp.task('playground', ['build'], function () {
require('./test/playground/server.js').start();
return hang();
});
gulp.task('travis', [process.env.GULP_TASK || '']);
|
JavaScript
| 0 |
@@ -2609,24 +2609,51 @@
'OS X 10.11'
+,%0A version: '51'
%0A %7D%0A%5D;%0A%0Av
|
c7cc3e2c404dce9a49a1333a3468256b369e12ce
|
remove yun dir from build
|
Gulpfile.js
|
Gulpfile.js
|
var gulp = require('gulp');
var del = require('del');
var zip = require('gulp-zip');
gulp.task('clean', function(cb){
del(['./build'], cb);
});
gulp.task('copy', ['clean'], function(){
return gulp.src('./**/*')
.pipe(gulp.dest('./build'));
});
gulp.task('thin', ['copy'], function(cb){
del([
'./build/update.sh',
'./build/Gulpfile.js',
'./build/package.json',
'./build/node_modules',
'./build/mqtt.zip',
'./build/CMakeLists.txt'
], cb);
})
gulp.task('compress', ['thin'], function () {
return gulp.src('build/**/*')
.pipe(zip('mqtt.zip'))
.pipe(gulp.dest('./'));
});
gulp.task('default', ['compress']);
|
JavaScript
| 0 |
@@ -458,16 +458,35 @@
sts.txt'
+,%0A './build/yun'
%0A %5D, cb
|
c99782353dcbb25f3e5a8216a63f85bbc388d47b
|
Remove unneeded path log
|
Gulpfile.js
|
Gulpfile.js
|
var
gulp = require('gulp'),
babel = require('gulp-babel'),
watch = require('gulp-watch'),
uglify = require('gulp-uglify'),
strip = require('gulp-strip-comments'),
rename = require('gulp-rename');
less = require('gulp-less');
minify = require('gulp-minify-css');
riot = require('riot');
// Transpile ES6 app to ES5 using babel
gulp.task('transpile-app', function () {
return gulp.src('app/main.es6.js')
.pipe(strip()) // Strip comments
.pipe(babel()) // Pipe the file into babel
.pipe(uglify()) // Pipe the file into babel
.pipe(rename('main.dist.js')) // rename to main.js
.pipe(gulp.dest('app')) // Save it in the same directory
});
// Transpile general ES6 javascripts
gulp.task('transpile-scripts', function () {
return gulp.src('browser/src/es6-js/**.es6.js')
.pipe(strip()) // Strip comments
.pipe(babel()) // Babel ES5 -> ES6
.pipe(uglify()) // uglify
.pipe(rename(function (path) { // Rename files so .es6.js -> .js
path.basename = path.basename.replace('es6', 'dist');
}))
.pipe(gulp.dest('browser/build/js'))
});
// Compile all of riot.js tag files
gulp.task('riot', function() {
return gulp.src('browser/src/riot-tags/**.tag')
.pipe(compileTAGtoJS()) // Custom Compile function
.pipe(babel()) // Babel ES5 -> ES6
.pipe(uglify()) // uglify
.pipe(rename(function (path) { // Rename files so .es6.js -> .js
console.log(path);
path.extname = '.tag.js';
}))
.pipe(gulp.dest('browser/build/js/riot-components'))
});
// Compile and compress LESS stylesheets
gulp.task('less', function() {
return gulp.src('browser/src/less/**.less')
.pipe(less({
paths: [ require('path').join(__dirname, 'less', 'includes') ]
}))
.pipe(minify())
.pipe(gulp.dest('browser/build/stylesheets'))
});
gulp.task('transpile', ['transpile-app', 'transpile-scripts'])
gulp.task('build', ['transpile', 'riot'])
gulp.task('default', ['build'])
/* ------------------------------------ */
// CUSTOM FUNCTIONS BELOW //
/* ------------------------------------ */
/* Converts Riotjs DSL to javascript */
function compileTAGtoJS() {
function transform(file, callback) {
file.contents = new Buffer(riot.compile(String(file.contents)));
callback(null, file);
}
return require('event-stream').map(transform);
}
|
JavaScript
| 0.000002 |
@@ -1681,33 +1681,8 @@
.js%0A
- console.log(path);%0A
|
ed4d47067e8efc35e52f8d0462ee7a318de4569d
|
fix correct version for self after appending a commit
|
lib/event_stream.js
|
lib/event_stream.js
|
var Promise = require('bluebird');
var Commit = require('./persistence/commit');
var _ = require('lodash');
// writeOnly - will never read entire stream from
var EventStream = function (eventPartition, streamId, writeOnly) {
if (streamId === undefined) {
throw new Error('StreamId must be defined!');
}
this._partition = eventPartition;
this._streamId = streamId;
this._writeOnly = writeOnly;
this._uncommittedEvents = [];
this._committedEvents = [];
this._version = 0;
}
EventStream.prototype._prepareStream = function (callback) {
this._committedEvents = [];
this._commitSequence = -1;
var self = this;
if (self._writeOnly === true && self._partition.getLatestCommit) {
// if stream should only be opened for appending commits, only really care about getting the correct commitSequence (from last commit)
return self._partition.getLatestCommit(self._streamId).then(function (commit) {
if (commit) {
self._commitSequence = commit.commitSequence;
}
// if no commit is found, assume its a new stream, and keep it at -1
}).then(function () {
return self;
});
} else {
return self._partition._queryStream(self._streamId, callback).then(function (commits) {
self._version = 0;
if (!commits || commits.length === 0) {
commits = [];
self._version = -1;
}
var version = 0
for (var i = 0; i < commits.length; i++) {
//console.log('found commit' + commit);
self._commitSequence++;
for (var j = 0; j < commits[i].events.length; j++) {
self._version++;
commits[i].events[j].version = version++;
self._committedEvents.push(commits[i].events[j]);
}
}
}).then(function () {
return self;
});
}
};
EventStream.prototype.getVersion = function () {
return this._version;
};
EventStream.prototype.append = function (event) {
this._uncommittedEvents.push(event);
};
EventStream.prototype.hasChanges = function () {
return this._uncommittedEvents.length > 0;
};
EventStream.prototype.commit = function (commitId, callback) {
var self = this;
if (!this.hasChanges()) {
//nothing to commit
return Promise.resolve().nodeify(callback);
} else {
var commit = this._buildCommit(commitId, this._uncommittedEvents);
return this._partition.append(commit, callback).then(function (commit) {
//rebuild local state
if (self._writeOnly === true) {
self._commitSequence++;
self._clearChanges();
} else {
var events = self._uncommittedEvents;
for (var i = 0; i < events.length; i++) {
self._version++;
self._committedEvents.push(events[i]);
}
self._clearChanges();
self._commitSequence++;
return self._prepareStream(callback);
}
});
}
}
EventStream.prototype._clearChanges = function () {
this._uncommittedEvents = [];
};
EventStream.prototype.revertChanges = function () {
//trunc the uncomitted events log
var arr = this._uncommittedEvents;
this._uncommittedEvents = [];
delete arr;
};
EventStream.prototype._buildCommit = function (commitId, events) {
var commitSequence = this._commitSequence;
var commit = new Commit(commitId, this._partition._partitionId, this._streamId, ++commitSequence, events);
var version = this._version == -1 ? 0 : this._version;
_.forEach(events, function (evt) {
evt.version = version++;
})
return commit;
};
EventStream.prototype.getCommittedEvents = function () {
return this._committedEvents.slice();
};
EventStream.prototype.getUncommittedEvents = function () {
return this._uncommittedEvents.slice();
};
module.exports = EventStream;
|
JavaScript
| 0.000002 |
@@ -2591,32 +2591,93 @@
Events;%0A
+self._version = events%5Bevents.length-1%5D.version + 1;%0A
for (var i = 0;
@@ -2705,35 +2705,8 @@
+) %7B
-%0A self._version++;
%0A
@@ -2846,33 +2846,8 @@
self
-._prepareStream(callback)
;%0A
|
c9b1253e54b9bd186fe5273ff2b7f66e572abb87
|
add reload to 'html' task
|
Gulpfile.js
|
Gulpfile.js
|
'use strict';
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var del = require('del');
var browserify = require('browserify');
var watchify = require('watchify');
var reactify = require('reactify');
var source = require('vinyl-source-stream');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var sourceFile = './src/scripts/index.js';
var destFolder = './build/scripts';
var destFileName = 'index.js';
gulp.task('html', function() {
// HTML
return gulp.src('src/*.html')
.pipe(gulp.dest('./build'));
});
gulp.task('styles', function () {
// styles: sass to css
gulp.src('./src/styles/*.scss')
.pipe(plugins.sourcemaps.init())
.pipe(plugins.sass())
.pipe(plugins.sourcemaps.write())
.pipe(gulp.dest('./build/styles'))
.pipe(reload({stream: true}));
});
gulp.task('browserify', function() {
// reactify+watchify+browserify
var bundler = browserify({
entries: ['./src/scripts/index.js'], // Only need initial file, browserify finds the deps
transform: [reactify], // Convert JSX to normal javascript
debug: true, cache: {}, packageCache: {}, fullPaths: true
});
var watcher = watchify(bundler);
return watcher
.on('update', function () { // When any files updates
var updateStart = Date.now();
plugins.util.log('Updating!');
watcher.bundle()
.pipe(source('index.js'))
// This is where you add uglifying etc.
.pipe(gulp.dest('./build/scripts/'))
.pipe(reload({stream: true}));
plugins.util.log('Updated!', (Date.now() - updateStart) + 'ms');
})
.bundle() // Create the initial bundle when starting the task
.pipe(source('index.js'))
.pipe(gulp.dest('./build/scripts/'))
.pipe(reload({stream: true}));
});
gulp.task('serve', function () {
browserSync({
server: {
baseDir: './build'
}
});
gulp.watch('src/*.html', ['html']);
gulp.watch('src/styles/*.scss', ['styles']);
});
gulp.task('default', ['html', 'styles', 'browserify', 'serve'], function () {});
|
JavaScript
| 0.000024 |
@@ -558,16 +558,50 @@
build'))
+%0A .pipe(reload(%7Bstream: true%7D))
;%0A%7D);%0A%0Ag
|
887401900bc0ef5b4758b4e2b2c97d6dc35c3273
|
Update gulp
|
Gulpfile.js
|
Gulpfile.js
|
var gulp = require('gulp'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename'),
watch = require('gulp-watch'),
sourcemaps = require('gulp-sourcemaps'),
minifyCSS = require('gulp-minify-css'),
livereload = require('gulp-livereload'),
del = require('del');
var paths = {
jsSrc: [
'path/to/a/file.js',
'oh/nice/globs/*.js',
'whoa/dude/**/*.js'
],
cssSrc: [
'path/to/css/file.css',
'css/stylin/on/*.css',
'path/**/*.css'
],
others: [
'path/to/some/html/*.html'
]
};
gulp.task('clean', function(cb) {
del(['dist/'], cb);
});
gulp.task('scripts', [], function() {
return gulp.src(paths.jsSrc)
.pipe(sourcemaps.init())
.pipe(concat('main.js'))
.pipe(gulp.dest('dist'))
.pipe(rename('main.min.js'))
.pipe(uglify({mangle: false}))
.pipe(sourcemaps.write())
.pipe(gulp.dest('dist'))
.pipe(livereload());
});
gulp.task('css', [], function() {
return gulp.src(paths.cssSrc)
.pipe(sourcemaps.init())
.pipe(concat('stylin.css'))
.pipe(gulp.dest('dist'))
.pipe(rename('stylin.min.css'))
.pipe(minifyCSS())
.pipe(sourcemaps.write())
.pipe(gulp.dest('dist'))
.pipe(livereload());
});
gulp.task('dev', function() {
livereload.listen();
gulp.watch(paths.jsSrc, ['default']);
gulp.watch(paths.cssSrc, ['default']);
gulp.watch(paths.others).on('change', livereload.changed);
});
gulp.task('default', ['clean', 'scripts', 'css']);
|
JavaScript
| 0.000001 |
@@ -252,24 +252,63 @@
nify-css'),%0A
+ nodemon = require('gulp-nodemon'),%0A
liverelo
@@ -401,162 +401,50 @@
'
-path/to/a/file.js',%0A 'oh/nice/globs/*.js',%0A 'whoa/dude/**/*.js'%0A %5D,%0A cssSrc: %5B%0A 'path/to/css/file.css',%0A 'css/stylin/on/*.css',%0A 'path/**
+src/js/*.js'%0A %5D,%0A cssSrc: %5B%0A 'src/css
/*.c
@@ -473,25 +473,21 @@
'
-path/to/some/html
+src/templates
/*.h
@@ -672,53 +672,42 @@
ipe(
-concat('main.js'))%0A .pipe(gulp.dest('dist'
+uglify(%7B%0A mangle: false%0A %7D
))%0A
@@ -719,20 +719,20 @@
ipe(
-rename('main
+concat('dist
.min
@@ -752,60 +752,101 @@
ipe(
-uglify(%7Bmangle: false%7D))%0A .pipe(sourcemaps.write(
+sourcemaps.write('./map', %7B%0A 'includeContent': true,%0A 'sourceRoot': 'src/js/'%0A %7D
))%0A
@@ -877,33 +877,8 @@
'))%0A
- .pipe(livereload());%0A
%7D);%0A
@@ -981,40 +981,27 @@
-
.pipe(
-concat('stylin.css'
+minifyCSS(
))%0A
-
@@ -1006,37 +1006,40 @@
.pipe(
-gulp.dest('dist
+concat('dist.min.css
'))%0A
-
.pip
@@ -1044,147 +1044,172 @@
ipe(
-rename('stylin.min.css'))%0A .pipe(minifyCSS())%0A .pipe(sourcemaps.write())%0A .pipe(gulp.dest('dist'))%0A .pipe(livereload());%0A%7D);%0A
+sourcemaps.write('./map', %7B%0A 'includeContent': true,%0A 'sourceRoot': 'src/css/'%0A %7D))%0A .pipe(gulp.dest('dist'))%0A%7D);%0A%0A// Rerun gulp when a file changes
%0Agul
@@ -1221,16 +1221,29 @@
k('dev',
+ %5B'default'%5D,
functio
@@ -1254,29 +1254,8 @@
%7B%0A
-livereload.listen();%0A
gu
@@ -1282,32 +1282,34 @@
, %5B'default'%5D);%0A
+
gulp.watch(pat
@@ -1339,71 +1339,284 @@
;%0A
-gulp.watch(paths.others).on('change', livereload.changed);%0A%7D);%0A
+ // Trigger livereload only when loadable assets are changed (new images, html updated.)%0A gulp.watch(paths.others).on('change', livereload.changed);%0A gulp.watch(%5B'dist/*'%5D).on('change', livereload.changed);%0A%7D);%0A%0A// The default task (called when you run %60gulp%60 from cli)
%0Agul
|
81ad933f3218579a075350077b21c65532195b9c
|
make second drush string a STRING.
|
src/tap/ingestion.js
|
src/tap/ingestion.js
|
/**
* ingestion.js
* expects:
* 1. path of directory (target)
* 2. parentpid
* 3. namespace
* 4. model
* (note: basic image,large image,audio,video, collection, pdf, binary -- all require
* the "ibsp" in the command string, book requires the "ibbp" part in the drush command.)
* output:
* log of drush run
* errors:
* if parameters missing
* if first command did not run
* if first command did run but did not prep ingest
* if first command ran with a good ingest but second command did not run
* (only if first command ran successfully)if second ran but did not ingest
*
* @param target directory path
* @param parentpid
* @param namespace
* @param model
* @return $message
*
*/
// for testing
//
var param = process.argv;
console.log('hi');
target = String(param[2]);
parentpid = String(param[3]);
namespace = String(param[4]);
model = String(param[5]);
function ingestion(target,parentpid,namespace,model) {
// build command pieces
// serveruri is the location of the drupal_home on the drupal server
var drupalhome = '/vhosts/dlwork/web/collections';
console.log('drupalhome = ',drupalhome);
var serveruri = 'http://dlwork.lib.utk.edu/dev/';
console.log('serveruri = ',serveruri);
console.log('parentpid = ',parentpid);
// namespace
console.log('namespace = ',namespace);
// target is the local directory holding the ingest files
console.log('target = ',target);
// make mongo connection
/*
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/ibu');
var conn = mongoose.connection;
*/
//
var $message = 'ingest did not happen';
var contentmodel = '';
if ((model)&& (model==='basic')) {
contentmodel = 'islandora:sp_basic_image';
}
if ((model)&&(model==='large')) {
contentmodel = 'islandora:sp_Large_image';
}
console.log('model = ',model);
// execute first drush command
var exec = require('child_process').exec;
var cmd = string('drush -r ',drupalhome,'-v -u=1 --uri=',serveruri,' ibsp --content_models=',contentmodel,' --type=directory --parent=',parentpid,' --namespace=',namespace,' --target=',target);
console.log('cmd=',cmd);
if ((target!='')&&(contentmodel!='')&&(parentpid!='')&&(namespace!='')) {
exec(cmd, function(error, stdout, stderr) {
// command output is in stdout
console.log(stdout);
// test command log for success indication
// test for substr in stdout
var cmd1bad = 1;
if (cmd1bad) {
$message = 'first ingest command failed!';
console.log($message);
return $message;
}
else {
$message = 'ingest prep drush command success';
console.log($message);
status.push("$message");
return $message;
}//end else
});// end exec
}// end if
else {
console.log('parameters for first command missing, ingest not started.\n');
$message = 'parameters for first command missing, ingest not started.';
return $message;
}
// exec second drush command
var cmd2 = 'drush -r ',drupalhome,'-v -u=1 --uri=',serveruri,' islandora_batch_ingest';
console.log('cmd2=',cmd2);
if ($message = 'ingest prep drush command success') {
exec(cmd2, function(error, stdout, stderr) {
// command output is in stdout
console.log(stdout);
// test command log for success indication
// test for substr in stdout
$message = 'ingest drush command success';
console.log($message);
status.push($message);
});
}// end if
return $message;
}// end function
//export default ingestion;
ingestion();
|
JavaScript
| 0.000349 |
@@ -3020,16 +3020,23 @@
cmd2 =
+string(
'drush -
@@ -3102,16 +3102,17 @@
_ingest'
+)
;%0A cons
|
389455decddd3153d222e26553927cf65a7cde17
|
fix spacing in exec string
|
src/tap/ingestion.js
|
src/tap/ingestion.js
|
/**
* ingestion.js
* expects:
* 1. path of directory (target)
* 2. parentpid
* 3. namespace
* 4. model
* (note: basic image,large image,audio,video, collection, pdf, binary -- all require
* the "ibsp" in the command string, book requires the "ibbp" part in the drush command.)
* output:
* log of drush run
* errors:
* if parameters missing
* if first command did not run
* if first command did run but did not prep ingest
* if first command ran with a good ingest but second command did not run
* (only if first command ran successfully)if second ran but did not ingest
*
* @param target directory path
* @param parentpid
* @param namespace
* @param model
* @return $message
*
*/
// for testing
//
var param = process.argv;
console.log('hi');
target = String(param[3]);
parentpid = String(param[4]);
namespace = String(param[5]);
model = String(param[6]);
var status=[];
function ingestion(target,parentpid,namespace,model) {
// build command pieces
// two drupalhomes one for testing on vagrant and one for server installation
var drupalhome = '/var/www/drupal';
//var drupalhome = '/vhosts/dlwork/web/collections';
console.log('drupalhome = ',drupalhome);
// serveruri is the location of the drupal_home on the drupal server
var serveruri = 'http://localhost/';
//var serveruri = 'http://dlwork.lib.utk.edu/dev/';
console.log('serveruri = ',serveruri);
console.log('parentpid = ',parentpid);
// namespace
console.log('namespace = ',namespace);
// target is the local directory holding the ingest files
console.log('target = ',target);
// make mongo connection
/*
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/ibu');
var conn = mongoose.connection;
*/
//
var $message = 'ingest did not happen';
var contentmodel = '';
if ((model)&& (model==='basic')) {
contentmodel = 'islandora:sp_basic_image';
}
if ((model)&&(model==='large')) {
contentmodel = 'islandora:sp_Large_image';
}
console.log('model = ',model);
// execute first drush command
var exec = require('child_process').exec;
var cmd = String('drush -r '+drupalhome+'-v -u=1 --uri='+serveruri+' ibsp --content_models='+contentmodel+' --type=directory --parent='+parentpid+' --namespace='+namespace+' --target='+target );
// show assembled command
console.log('cmd=',cmd);
if ((target !='')&&(contentmodel !='')&&(parentpid !='')&&(namespace !='')) {
exec(cmd, function(error, stdout, stderr) {
// command output is in stdout
console.log(stdout);
// test command log for success indication
// test for substr in stdout
if(stdout.indexOf('Command dispatch complete') > -1) {
$message = 'ingest prep drush command success';
console.log($message);
status.push("$message");
//return $message;
}// end if
else {
$message = 'first ingest command failed!';
console.log($message);
status.push("$message");
return $message;
}//end else
});// end exec
}// end if
else {
console.log('parameters for first command missing, ingest not started.\n');
$message = 'parameters for first command missing, ingest not started.';
status.push("$message");
return $message;
}// end else
// exec second drush command
var cmd2 = String('drush -r '+drupalhome+'-v -u=1 --uri='+serveruri+' islandora_batch_ingest');
console.log('cmd2=',cmd2);
if ($message = 'ingest prep drush command success') {
exec(cmd2, function(error, stdout, stderr) {
// command output is in stdout
console.log(stdout);
// test command log for success indication
// test for substr in stdout
$message = 'ingest drush command success';
console.log($message);
status.push($message);
});
}// end if
return $message;
}// end function
//export default ingestion;
ingestion(target,parentpid,namespace,model);
|
JavaScript
| 0.000682 |
@@ -2150,32 +2150,33 @@
r '+drupalhome+'
+
-v -u=1 --uri='+
|
962a0f12b0954971c22be88ce8558ef4008d4f9b
|
fix prop evaluation
|
src/toggle/Toggle.js
|
src/toggle/Toggle.js
|
import React from 'react';
import { pure, skinnable, props, t } from '../utils';
import cx from 'classnames';
import { getValueLink } from '../link-state';
import { warn } from '../utils/log';
/**
* A nice animated Toggle rendered using only CSS
*/
@pure
@skinnable()
@props({
/** The current value (`true` if checked) */
value: t.maybe(t.Boolean),
/** Callback called when user clicks on the Toggle */
onChange: t.maybe(t.Function),
/** To be used together with `linkState` */
valueLink: t.maybe(t.struct({
value: t.Boolean,
requestChange: t.Function
})),
/**
* The size for the Toggle in whatever unit (px, em, rem ...).
* It will be used to compute `width`, `height` and `border-radius` as follows:
* `width: size`, `height: size / 2`, `border-radius: size / 2`
*/
size: t.maybe(t.union([t.String, t.Number])),
className: t.maybe(t.String),
style: t.maybe(t.Object)
})
export default class Toggle extends React.Component {
componentDidMount() {
this.updateCheckbox(this.props);
}
updateCheckbox = (props) => {
const { value } = getValueLink(this, props);
const { checkbox } = this.refs;
const checkboxNode = checkbox.nodeType === 1 ?
checkbox :
checkbox.getDOMNode();
checkboxNode.checked = value;
}
getHalfSize(size) {
if (t.String.is(size)) {
const unitMatch = (/[a-z]+$/).exec(size); // only match characters at the end
const number = parseFloat(size, 10);
const unit = unitMatch ? unitMatch[0] : '';
if (isFinite(number)) { // we can still get NaN from parseFloat
return `${number / 2}${unit}`;
} else {
warn('Invalid size');
return 0;
}
} else {
return size / 2;
}
}
onButtonClick = () => {
const { value, requestChange } = getValueLink(this);
requestChange(!value);
}
getLocals() {
const {
props: { className, size, style },
onButtonClick
} = this;
const { value } = getValueLink(this);
return {
style,
value,
buttonProps: {
onClick: onButtonClick,
style: size ?
{ width: size, height: this.getHalfSize(size), borderRadius: this.getHalfSize(size) } :
undefined
},
className: cx('toggle', className)
};
}
template({ value, className, style, buttonProps }) {
return (
<div {...{ className, style }}>
<input className='toggle-input' type='checkbox' ref='checkbox' value={value} readOnly />
<label className='toggle-button' {...buttonProps} />
</div>
);
}
componentWillReceiveProps(nextProps) {
this.updateCheckbox(nextProps);
}
}
|
JavaScript
| 0.000001 |
@@ -528,16 +528,24 @@
value:
+t.maybe(
t.Boolea
@@ -545,16 +545,17 @@
.Boolean
+)
,%0A re
|
c181099a522f1c2f87d5a187e0a775ad169a3a5d
|
Use TS parser only for TS files
|
ts.js
|
ts.js
|
let base = require('./')
module.exports = {
...base,
parser: '@typescript-eslint/parser',
parserOptions: {
tsconfigRootDir: process.cwd(),
project: ['./tsconfig.json']
},
plugins: [...base.plugins, '@typescript-eslint'],
overrides: [
...base.overrides,
{
files: ['*.{ts,tsx}'],
rules: {
'@typescript-eslint/no-unnecessary-boolean-literal-compare': 'error',
'@typescript-eslint/no-non-null-asserted-optional-chain': 'error',
'@typescript-eslint/no-unnecessary-type-assertion': 'error',
'@typescript-eslint/adjacent-overload-signatures': 'error',
// '@typescript-eslint/no-confusing-void-expression': 'error',
'@typescript-eslint/lines-between-class-members': [
'error',
'always',
{
exceptAfterSingleLine: true
}
],
'@typescript-eslint/space-before-function-paren': ['error', 'always'],
'@typescript-eslint/strict-boolean-expressions': 'error',
'@typescript-eslint/prefer-namespace-keyword': 'error',
'@typescript-eslint/no-unnecessary-condition': 'error',
'@typescript-eslint/type-annotation-spacing': 'error',
'@typescript-eslint/member-delimiter-style': [
'error',
{
multiline: {
delimiter: 'none'
},
singleline: {
delimiter: 'semi'
}
}
],
'@typescript-eslint/restrict-plus-operands': 'error',
'@typescript-eslint/no-useless-constructor': 'error',
'@typescript-eslint/prefer-optional-chain': 'error',
'@typescript-eslint/no-dupe-class-members': 'error',
'@typescript-eslint/no-use-before-define': [
'error',
{
functions: false,
classes: false,
variables: false
}
],
'@typescript-eslint/no-empty-interface': 'error',
'@typescript-eslint/unified-signatures': 'error',
'@typescript-eslint/func-call-spacing': ['error', 'never'],
'@typescript-eslint/no-invalid-this': 'error',
'@typescript-eslint/no-for-in-array': 'error',
'@typescript-eslint/no-var-requires': 'error',
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/await-thenable': 'error',
'@typescript-eslint/dot-notation': [
'error',
{
allowKeywords: true
}
],
'@typescript-eslint/no-unused-expressions': [
'error',
{
allowShortCircuit: true,
allowTernary: true,
allowTaggedTemplates: true
}
],
'@typescript-eslint/array-type': 'error',
'import/extensions': ['error', 'always', { ignorePackages: true }],
'lines-between-class-members': 'off',
'no-useless-constructor': 'off',
'no-unused-expressions': 'off',
'no-dupe-class-members': 'off',
'no-use-before-define': 'off',
'func-callspacing': 'off',
'no-invalid-this': 'off',
'no-unused-vars': 'off',
'dot-notation': 'off'
}
},
{
files: '*.test.{ts,tsx}',
rules: {
'@typescript-eslint/no-explicit-any': 'off'
}
},
{
files: '*.d.ts',
rules: {
'unicorn/custom-error-definition': 'off'
}
}
]
}
|
JavaScript
| 0 |
@@ -56,260 +56,283 @@
%0A p
-arser: '@typescript-eslint/parser',%0A parserOptions: %7B
+lugins: %5B...base.plugins, '@typescript-eslint'%5D,%0A overrides: %5B
%0A
-tsconfigRootDir: process.cwd(),%0A project: %5B'./tsconfig.json
+...base.overrides,%0A %7B%0A files: %5B'*.ts', '*.tsx
'%5D
+,
%0A
-%7D,%0A plugins: %5B...base.plugins, '@typescript-eslint'%5D,%0A overrides: %5B
+ parser: '@typescript-eslint/parser',%0A parserOptions: %7B
%0A
-...base.overrides
+ tsconfigRootDir: process.cwd()
,%0A
- %7B%0A
- files: %5B'*.%7Bts,tsx%7D'%5D
+project: %5B'./tsconfig.json'%5D%0A %7D
,%0A
|
b5e5a07aee96a493fd78092e36e80cdc9420ecf7
|
reword the question for docker file
|
lib/workflow/questionnaire.js
|
lib/workflow/questionnaire.js
|
// For simplicity, all questions are selects.
// We use value 'none' as a convention for no feature selected,
// because enquirer doesn't support empty string '' as a value.
exports.pickPlugin = {
// add "plugin" to feature set for pluginFlow.
// because this only provides one choice (default choice), it
// is never prompted to end user.
choices: [{ value: 'plugin' }]
};
exports.askDocker = {
message: 'Do you like to add a Dockerfile?',
choices: [{
value: 'none', message: 'No'
}, {
value: 'docker', message: 'Sure, yes'
}]
};
exports.askBundler = {
message: 'Which bundler would you like to use?',
choices: [{
value: 'webpack',
message: 'Webpack',
hint: 'A powerful and popular bundler for JavaScript.',
if: '!plugin'
}, {
value: 'cli-bundler',
message: "CLI's built-in bundler with an AMD module loader",
hint: 'Provides similar capabilities but with much simpler configuration.'
}]
};
exports.askLoader = {
message: 'Which AMD module loader would you like to use?',
choices: [{
value: 'requirejs',
message: 'RequireJS',
hint: 'RequireJS is a mature and stable module loader for JavaScript.'
}, {
value: 'alameda',
message: 'Alameda',
hint: 'Alameda is a modern version of RequireJS using promises and native es6 features (modern browsers only).',
if: '!plugin'
}, {
value: 'systemjs',
message: 'SystemJS',
hint: 'SystemJS is Dynamic ES module loader, the most versatile module loader for JavaScript.',
if: '!plugin'
}],
// This if condition is not an enquirer feature.
// This is our convention, check ./applicable.js for acceptable expressions
if: 'cli-bundler'
};
exports.askHttp = {
message: 'Which HTTP Protocol do you wish the outputted Webpack bundle to be optimised for?',
choices: [{
value: 'http1',
message: 'HTTP/1.1',
hint: 'The legacy HTTP/1.1 protocol, max 6 parallel requests/connections.'
}, {
value: 'http2',
message: 'HTTP/2',
hint: 'The modern HTTP/2 Protocol, uses request multiplexing over a single connection.'
}],
// This if condition is not an enquirer feature.
// This is our convention, check ./applicable.js for acceptable expressions
if: 'webpack'
};
exports.askPlatform = {
message: 'What platform are you targeting?',
choices: [{
value: 'web',
message: 'Web',
hint: 'The default web platform setup.'
}, {
value: 'dotnet-core',
message: '.NET Core',
hint: 'A powerful, patterns-based way to build dynamic websites with .NET Core.',
if: '!plugin'
}]
};
exports.askTranspiler = {
message: 'What transpiler would you like to use?',
choices: [{
value: 'babel',
message: 'Babel',
hint: 'An open source, standards-compliant ES2015 and ESNext transpiler.'
}, {
value: 'typescript',
message: 'TypeScript',
hint: 'An open source, ESNext superset that adds optional strong typing.'
}]
};
exports.askMarkupProcessor = {
message: 'How would you like to setup your HTML template?',
choices: [{
value: 'none',
message: 'None',
hint: 'No markup processing'
}, {
value: 'htmlmin-min',
message: 'Minimum Minification',
hint: 'Removes comments and whitespace between block level elements such as div, blockquote, p, header, footer ...etc.'
}, {
value: 'htmlmin-max',
message: 'Maximum Minification',
hint: 'Removes comments, script & link element [type] attributes and all whitespace between all elements. Also remove attribute quotes where possible. Collapses boolean attributes.'
}]
};
exports.askCssProcessor = {
message: 'What css preprocessor would you like to use?',
choices: [{
value: 'none',
message: 'None',
hint: 'Use standard CSS with no pre-processor.'
}, {
value: 'less',
message: 'Less',
hint: 'Extends the CSS language, adding features that allow variables, mixins, functions and many other techniques.'
}, {
value: 'sass',
message: 'Sass',
hint: 'A mature, stable, and powerful professional grade CSS extension.'
}, {
value: 'stylus',
message: 'Stylus',
hint: 'Expressive, dynamic and robust CSS.'
}]
};
exports.askPostCss = {
message: 'Do you want to add PostCSS processing',
choices: [{
value: 'none',
message: 'None',
hint: 'No PostCSS processing'
}, {
value: 'postcss-basic',
message: 'Basic',
hint: 'With autoprefixer'
}, {
value: 'postcss-typical',
message: 'Typical',
hint: 'With autoprefixer, postcss-url to inline image/font resources, cssnano to minify',
if: 'cli-bundler'
}, {
value: 'postcss-typical',
message: 'Typical',
hint: 'With autoprefixer, plus cssnano to minify',
// don't need postcss-url for webpack, as webpack's css-loader does similar work
if: 'webpack'
}]
};
exports.askUnitTestRunner = {
message: 'Which unit test runner would you like to use?',
choices: [{
value: 'none',
message: 'None',
hint: 'Skip testing. My code is always perfect :-)'
}, {
value: 'karma',
message: 'Karma + Jasmine',
hint: 'Unit testing with Karma and Jasmine'
}, {
value: 'jest',
message: 'Jest',
hint: 'Unit testing with Jest'
}]
};
exports.askIntegrationTestRunner = {
message: 'Would you like to configure integration testing?',
choices: [{
value: 'none',
message: 'None',
hint: 'Skip testing. My code is always perfect :-)'
}, {
value: 'protractor',
message: 'Protractor',
hint: 'Integration testing with Protractor.'
}, {
value: 'cypress',
message: 'Cypress',
hint: "Integration testing with Cypress. Please note: If you've chosen a Typescript, Cypress will add webpack and ts-loader to dependencies due to limited availability of Cypress preprocessors at this point in time."
}]
};
exports.askEditor = {
message: 'What is your default code editor?',
choices: [{
value: 'none',
message: 'None',
hint: 'Skip any editor specific options.'
}, {
value: 'vscode',
message: 'Visual Studio Code',
hint: 'Code editing. Redefined. Free. Open source. Runs everywhere.'
}]
// Removed atom/sublime/webstorm from the editor list, because they are
// no-ops in cli.
};
exports.askScaffold = {
message: 'Which features do you want scaffolded into your project?',
choices: [{
value: 'scaffold-minimum',
message: 'Minimum',
hint: 'Just a bare minimum Aurelia app.'
}, {
value: 'scaffold-navigation',
message: 'Navigation App',
hint: 'Add a router and some sample routes, Bootstrap v3 and Font Awesome v4.'
}]
};
exports.askPluginScaffold = {
message: 'Which features do you want scaffolded into your Aurelia plugin project?',
choices: [{
value: 'plugin-scaffold-minimum',
message: 'None',
hint: 'Just a bare minimum Aurelia plugin with one custom element.'
}, {
value: 'plugin-scaffold-basic',
message: 'Basic',
hint: 'Show examples for custom element, attribute, value converter and binding behavior.'
}]
};
|
JavaScript
| 0.999999 |
@@ -407,26 +407,29 @@
message: '
-Do
+Would
you like to
|
dd1ef11b2aac180e0f62133e7d06d8e289876438
|
Check if a value is an object before using 'in'
|
lib/axiom/bindings/base.js
|
lib/axiom/bindings/base.js
|
// Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import AxiomError from 'axiom/core/error';
import AxiomEvent from 'axiom/core/event';
/**
* The base class for bindings, which includes the ability to mark the binding
* as 'ready'.
*
* A binding that is ready has had all of its event handlers attached such that
* it's able to communication with the underlying implementation.
*
* @param {Object} opt_descriptor Optional descriptor defining the "bindable"
* properties.
*/
export var BaseBinding = function(opt_descriptor) {
this.readyState = BaseBinding.state.WAIT;
this.isOpen = false;
this.readyValue = null;
this.closeReason = null;
this.closeValue = null;
this.onReady = new AxiomEvent(function(value) {
this.readyValue = value;
this.readyState = BaseBinding.state.READY;
this.isOpen = true;
}.bind(this));
this.onClose = new AxiomEvent(function(reason, value) {
this.closeReason = (reason == 'ok' ? 'ok' : 'error');
this.closeValue = value;
this.isOpen = false;
if (reason == 'ok') {
this.readyState = BaseBinding.state.CLOSED;
} else {
this.readyState = BaseBinding.state.ERROR;
}
}.bind(this));
if (opt_descriptor)
this.describe(opt_descriptor);
};
export default BaseBinding;
BaseBinding.state = {
WAIT: 'WAIT',
READY: 'READY',
ERROR: 'ERROR',
CLOSED: 'CLOSED'
};
BaseBinding.prototype.bind = function(self, obj) {
for (var name in obj) {
var target = this[name];
if (!target)
throw new AxiomError.NotFound('bind-target', name);
var impl = obj[name];
if (self && typeof impl == 'string')
impl = self[impl];
if (typeof target == 'function') {
if (!('impl' in target))
throw new AxiomError.Invalid('bind-target', name);
if (target.impl)
throw new AxiomError.Duplicate('bind-target', name);
if (typeof impl != 'function')
throw new AxiomError.TypeMismatch('function', impl);
if (self) {
target.impl = impl.bind(self);
} else {
target.impl = impl;
}
} else if (target instanceof AxiomEvent) {
target.addListener(impl, self);
}
}
};
BaseBinding.prototype.describe = function(descriptor) {
for (var name in descriptor) {
var entry = descriptor[name];
if (typeof entry == 'object') {
if (entry.type == 'method') {
this.describeMethod(name, entry.args);
} else if (entry.type == 'event') {
this[name] = new AxiomEvent();
} else if (entry.type == 'map') {
this[name] = new Map();
}
}
}
};
BaseBinding.prototype.describeMethod = function(name, args, opt_first) {
var f = function() {
if (!f.impl)
throw new Error('Unbound method: ' + name);
if (opt_first) {
return opt_first.apply(null, arguments).then(
function() {
return f.impl.apply(null, arguments);
});
}
return Promise.resolve(f.impl.apply(null, arguments));
};
f.impl = null;
this[name] = f;
};
BaseBinding.prototype.isReadyState = function(/* stateName , ... */) {
for (var i = 0; i < arguments.length; i++) {
var stateName = arguments[i];
if (!BaseBinding.state.hasOwnProperty(stateName))
throw new Error('Unknown state: ' + stateName);
if (this.readyState == BaseBinding.state[stateName])
return true;
}
return false;
};
BaseBinding.prototype.assertReady = function() {
if (this.readyState != BaseBinding.state.READY)
throw new Error('Invalid ready call: ' + this.readyState);
};
BaseBinding.prototype.assertReadyState = function(/* stateName , ... */) {
if (!this.isReadyState.apply(this, arguments))
throw new Error('Invalid ready call: ' + this.readyState);
};
BaseBinding.prototype.dependsOn = function(otherReady) {
otherReady.onClose.addListener(function() {
if (this.isReadyState('CLOSED', 'ERROR'))
return;
this.closeError('ParentClosed',
[otherReady.closeReason, otherReady.closeValue]);
}.bind(this));
};
/**
* Returns a promise that resolves when the binding is ready, or immediately
* if already ready.
*
* If the binding goes "unready", and you expect it to ever be ready again,
* you'll need to call this function again to register your interest.
*
* The promise will be rejected if the binding goes to some state other than
* ready.
*/
BaseBinding.prototype.whenReady = function() {
if (this.readyState == 'READY')
return Promise.resolve();
if (this.readyState != 'WAIT')
return Promise.reject(this.closeValue);
return new Promise(function(resolve, reject) {
var onClose = function(value) {
this.onReady.removeListener(resolve);
reject(value);
}.bind(this);
this.onReady.listenOnce(function(value) {
this.onClose.removeListener(onClose);
resolve(value);
}.bind(this));
this.onClose.listenOnce(onClose);
}.bind(this));
};
BaseBinding.prototype.reset = function() {
this.assertReadyState('WAIT', 'CLOSED', 'ERROR');
this.readyState = BaseBinding.state['WAIT'];
};
BaseBinding.prototype.ready = function(value) {
this.assertReadyState('WAIT');
this.onReady.fire(value);
};
BaseBinding.prototype.closeOk = function(value) {
this.assertReadyState('READY');
this.onClose.fire('ok', value);
};
BaseBinding.prototype.closeErrorValue = function(value) {
this.assertReadyState('READY', 'WAIT');
if (!(value instanceof AxiomError)) {
if (value instanceof Error) {
value = value.toString() + ' ' + value.stack;
} else if ('toString' in value) {
value = value.toString();
} else {
value = JSON.stringify(value);
}
value = new AxiomError.Unknown(value);
}
this.onClose.fire('error', value);
return value;
};
BaseBinding.prototype.closeError = function(name, arg) {
var proto = Object.create(AxiomError[name].prototype);
return this.closeErrorValue(AxiomError[name].apply(proto, arg));
};
|
JavaScript
| 0 |
@@ -5700,16 +5700,43 @@
lse if (
+value instanceof Object &&
'toStrin
|
115c9bcd488a49c3b8f0fbcd223022565a7859fe
|
remove comment
|
template/test/unit/karma.conf.js
|
template/test/unit/karma.conf.js
|
// Karma configuration
// Generated on Fri Aug 11 2017 00:15:18 GMT+0800 (CST)
var webpackConfig = require('../../build/webpack.test')
module.exports = function(config) {
config.set({
browsers: ['Chrome'],
frameworks: ['mocha', 'expect'],
reporters: ['spec', 'coverage'],
coverageReporter: {
dir: './coverage',
reporters: [
{ type: 'lcov', subdir: '.' },
{ type: 'text-summary' }
]
},
files: ['./index.js'],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'./index.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
singleRun: false,
concurrency: Infinity
})
}
|
JavaScript
| 0 |
@@ -1,83 +1,4 @@
-// Karma configuration%0A// Generated on Fri Aug 11 2017 00:15:18 GMT+0800 (CST)%0A
var
@@ -387,160 +387,8 @@
'%5D,%0A
- // preprocess matching files before serving them to the browser%0A // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor%0A
|
23bf8680923d359c83d818fe2b6ea79418b9fa2d
|
bring colors over to stash to fix it
|
commands/stash.js
|
commands/stash.js
|
var _ = require('lodash');
var async = require('async');
var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;
module.exports = {
name:'stash',
description:'Stashes any local changes across all repos',
example:'bosco stash -r <repoPattern>',
cmd:cmd
}
function cmd(bosco, args) {
var repoPattern = bosco.options.repo;
var repoRegex = new RegExp(repoPattern);
var repos = bosco.config.get('github:repos');
if(!repos) return bosco.error("You are repo-less :( You need to initialise bosco first, try 'bosco fly'.");
bosco.log("Running git stash across all repos ...");
var stashRepos = function(cb) {
var progressbar = bosco.config.get('progress') == 'bar',
total = repos.length;
var bar = progressbar ? new bosco.progress('Doing git stash [:bar] :percent :etas', {
complete: green,
incomplete: red,
width: 50,
total: total
}) : null;
async.mapSeries(repos, function repoStash(repo, repoCb) {
if(!repo.match(repoRegex)) return repoCb();
var repoPath = bosco.getRepoPath(repo);
stash(bosco, progressbar, bar, repoPath, repoCb);
}, function(err) {
cb();
});
}
stashRepos(function() {
bosco.log("Complete");
});
}
function stash(bosco, progressbar, bar, orgPath, next) {
if(!progressbar) bosco.log("Stashing "+ orgPath.blue);
if(!bosco.exists([orgPath,".git"].join("/"))) {
bosco.warn("Doesn't seem to be a git repo: "+ orgPath.blue);
return next();
}
exec('git stash', {
cwd: orgPath
}, function(err, stdout, stderr) {
if(progressbar) bar.tick();
if(err) {
if(progressbar) console.log("");
bosco.error(orgPath.blue + " >> " + stderr);
} else {
if(!progressbar && stdout) bosco.log(orgPath.blue + " >> " + stdout);
}
next(err);
});
}
|
JavaScript
| 0 |
@@ -143,16 +143,86 @@
').exec;
+%0Avar green = '%5Cu001b%5B42m %5Cu001b%5B0m';%0Avar red = '%5Cu001b%5B41m %5Cu001b%5B0m';
%0A%0Amodule
|
1abea62e6a8d3db43297507696b3839750ef10f3
|
Update commands\table.js
|
commands/table.js
|
commands/table.js
|
var cmd = module.exports = {};
cmd.type = "basic";
cmd.command = true;
cmd.help = "Help !";
cmd.args = '';
cmd.run = (msg) => {
var args = m.content.substring((bot.set.prefix).length+m.content.split(" ")[0].replace(bot.set.prefix, "").length+1);
m.channel.sendMessage(args);
};
|
JavaScript
| 0.000001 |
@@ -137,16 +137,18 @@
args = m
+sg
.content
@@ -183,16 +183,18 @@
length+m
+sg
.content
@@ -250,16 +250,18 @@
+1);%0A m
+sg
.channel
|
41dc4e7efdfb37a42e1067f1dc732a466afe34db
|
Add fullName computed property to user.
|
frontend/app/models/user.js
|
frontend/app/models/user.js
|
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
export default Model.extend({
username: attr('string'),
firstName: attr('string'),
lastName: attr('string'),
email: attr('string'),
});
|
JavaScript
| 0 |
@@ -99,18 +99,16 @@
tend(%7B%0A%0A
-
userna
@@ -129,18 +129,16 @@
ng'),%0A
-
-
firstNam
@@ -158,18 +158,16 @@
ng'),%0A
-
-
lastName
@@ -184,18 +184,16 @@
ring'),%0A
-
email:
@@ -209,15 +209,147 @@
ring'),%0A
+%0A
+fullName: Ember.computed('firstName', 'lastName', function() %7B%0A return %60$%7Bthis.get('firstName')%7D $%7Bthis.get('lastName')%7D%60;%0A %7D)%0A
%0A%7D);%0A
|
3bf372a642a43cb8c7cd1c2bb6ab793c0074d80c
|
Remove unused import from pages/login.js
|
frontend/src/pages/login.js
|
frontend/src/pages/login.js
|
import React from 'react';
import PropTypes from 'prop-types';
import withRoot from '../utils/withRoot';
import { withStyles } from 'material-ui/styles';
import Head from 'next/head';
import Paper from 'material-ui/Paper';
import Typography from 'material-ui/Typography';
import TextField from 'material-ui/TextField';
import { FormGroup, FormControl, FormControlLabel } from 'material-ui/Form';
import Switch from 'material-ui/Switch';
import Button from 'material-ui/Button';
import Divider from 'material-ui/Divider';
import AppContent from '../components/AppContent';
// import Link from '../components/Link';
const styles = theme => ({
loginContent: {
minHeight: '100vh',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
halfBg: {
height: '100vh',
backgroundColor: theme.palette.grey[300],
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
zIndex: -1,
'& div': {
backgroundColor: theme.palette.primary.main,
height: '50vh',
}
},
logo: {
fontFamily: theme.typography.fontFamily,
color: theme.palette.primary.contrastText,
'& h1': {
fontSize: theme.typography.display1.fontSize,
fontWeight: 400,
}
},
loginBox: {
position: 'relative',
width: 350,
maxHeight: 390,
padding: theme.spacing.unit * 4,
},
loginHead: {
marginBottom: theme.spacing.unit * 2,
textAlign: 'center',
},
loginButton: {
marginTop: theme.spacing.unit * 2,
}
});
function PageLogin(props) {
const { classes } = props;
return (
<React.Fragment>
<Head>
<title>Login - OliMAT</title>
</Head>
<section className={classes.halfBg}>
<div></div>
</section>
<section className={classes.loginContent}>
<div className={classes.logo}>
<h1>OliMAT</h1>
</div>
<Paper className={classes.loginBox}>
<Typography className={classes.loginHead} variant="headline">
Acesse sua Conta
</Typography>
<Divider />
<TextField
label="Email"
margin="normal"
fullWidth
/>
<TextField
label="Senha"
margin="normal"
fullWidth
/>
<FormGroup row>
<FormControlLabel
control={
<Switch
checked={false}
onChange={() => console.log('Switch clicked!')}
value="checkedB"
color="primary"
/>
}
label="Manter acesso"
/>
</FormGroup>
{/* <Typography variant="caption">
<Link href="#">Esqueceu a senha?</Link>
</Typography> */}
<Button
className={classes.loginButton}
fullWidth
variant="raised"
color="secondary"
size="large"
>
Entrar
</Button>
</Paper>
</section>
</React.Fragment>
)};
PageLogin.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withRoot(withStyles(styles)(PageLogin));
|
JavaScript
| 0 |
@@ -518,59 +518,8 @@
r';%0A
-import AppContent from '../components/AppContent';%0A
// i
|
45b99311c1b7b952eb4da9917157d1a7e6c4de38
|
Remove unnecessary variables
|
frontend/src/shogi/board.js
|
frontend/src/shogi/board.js
|
import Piece from './piece';
export default class Board {
constructor() {
this.setBoard(this.initialUsiBoard());
}
initialUsiBoard() {
return (
[
['l', 'n', 's', 'g', 'k', 'g', 's', 'n', 'l'],
['*', 'b', '*', '*', '*', '*', '*', 'r', '*'],
['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
['*', '*', '*', '*', '*', '*', '*', '*', '*'],
['*', '*', '*', '*', '*', '*', '*', '*', '*'],
['*', '*', '*', '*', '*', '*', '*', '*', '*'],
['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
['*', 'B', '*', '*', '*', '*', '*', 'R', '*'],
['L', 'N', 'S', 'G', 'K', 'G', 'S', 'N', 'L']
]
);
}
setBoard(board) {
this.board = this.createBoard(board);
}
createBoard(board) {
var _board = board.map((row, y) => {
var yCor = this.transposeToCorY(y);
var rows = row.map((type, x) => {
var xCor = this.transposeToCorX(x);
return (
new Piece({ type: type, x: xCor, y: yCor })
);
});
return(rows);
});
return _board;
}
movePiece(fromPiece, toPiece) {
// if piece of argument is not match piece in the board, throw exception
//
if (! this.matchPiece(fromPiece)) {
var pos = `xCor = ${fromPiece.x}, yCor = ${fromPiece.y}`;
throw new Error(`Does not match coordinates in board. ${pos}`);
}
this.enhanceMovablePoint(fromPiece);
var [toCorX, toCorY] = [toPiece.x, toPiece.y];
var [toIdxX, toIdxY] = this.invertCor(toCorX, toCorY);
var [fromCorX, fromCorY] = [fromPiece.x, fromPiece.y];
var [fromIdxX, fromIdxY] = this.invertCor(fromCorX, fromCorY);
var destPiece = this.board[toIdxY][toIdxX];
if (typeof destPiece === 'undefined' || ! destPiece.movable) {
return;
}
fromPiece.x = destPiece.x;
fromPiece.y = destPiece.y;
this.board[toIdxY][toIdxX] = fromPiece;
this.board[fromIdxY][fromIdxX].type = '*';
return;
}
enhanceMovablePoint(piece) {
var [xCor, yCor] = [piece.x, piece.y];
var moveDef = piece.moveDef();
// if piece of argument is not match piece in the board, throw exception
//
if (! this.matchPiece(piece)) {
var pos = `xCor = ${xCor}, yCor = ${yCor}`;
throw new Error(`Does not match coordinates in board. ${pos}`);
}
// if moveDef has just property, piece moves just coordinates on board.
//
if (moveDef.just) {
this.movablePointsByJust(piece);
}
// if moveDef has fly property, piece moves recursion on board.
//
if (moveDef.fly) {
this.movablePointsByFly(piece);
}
}
// if piece of argument is match in the board, return true, else return false
//
matchPiece(piece) {
var [xCor, yCor] = [piece.x, piece.y];
var [x, y] = this.invertCor(xCor, yCor);
var isUndefined = typeof this.findPiece(x, y) === 'undefined';
var isEqualPiece = this.findPiece(x, y).equals(
new Piece({
x: piece.x,
y: piece.y,
type: piece.type,
movable: piece.movable
})
);
return (isUndefined || isEqualPiece);
}
// if moveDef has just property, piece moves just coordinates on board.
//
movablePointsByJust(piece) {
var [xCor, yCor] = [piece.x, piece.y];
var moveDef = piece.moveDef();
var [x, y] = this.invertCor(xCor, yCor);
moveDef.just.forEach((def) => {
var [defX, defY] = def;
var piece = this.findPiece(x + defX, y + defY);
if (piece) { piece.movable = true; }
});
}
movablePointsByFly(piece) {
var [xCor, yCor] = [piece.x, piece.y];
var moveDef = piece.moveDef();
var [x, y] = this.invertCor(xCor, yCor);
moveDef.fly.forEach((def) => {
var [defX, defY] = def;
var dx, dy;
dx = x + defX;
dy = y + defY;
var piece = this.findPiece(dx, dy);
while (piece) {
piece.movable = true;
dx = dx + defX;
dy = dy + defY;
piece = this.findPiece(dx, dy);
if (piece && piece.type !== '*') {
piece.movable = true;
break;
}
}
});
}
transposeToCorX(xIndex) {
return 10 - xIndex - 1;
}
transposeToCorY(yIndex) {
return yIndex + 1;
}
invertToIndexX(xCor) {
return 9 - xCor;
}
invertToIndexY(yCor) {
return yCor - 1;
}
invertCor(xCor, yCor) {
return [this.invertToIndexX(xCor), this.invertToIndexY(yCor)];
}
findPiece(xIndex, yIndex) {
var row = this.board[yIndex];
return row ? row[xIndex] : undefined;
}
fetchPiece(piece) {
var [toCorX, toCorY] = [piece.x, piece.y];
var [toIdxX, toIdxY] = this.invertCor(toCorX, toCorY);
return this.findPiece(toIdxX, toIdxY);
}
toArray() {
return this.board.map((row) => {
return row.map((piece) => {
return piece.type;
});
});
}
};
|
JavaScript
| 0.000643 |
@@ -1999,51 +1999,8 @@
) %7B%0A
- var %5BxCor, yCor%5D = %5Bpiece.x, piece.y%5D;%0A
@@ -2177,20 +2177,23 @@
Cor = $%7B
-xCor
+piece.x
%7D, yCor
@@ -2196,20 +2196,23 @@
Cor = $%7B
-yCor
+piece.y
%7D%60;%0A
|
068dc6b7ddb0afb453dff8bbc63c18e0911f3fdf
|
Implement `transposeToCorX`, `transposeToCorY`
|
frontend/src/shogi/board.js
|
frontend/src/shogi/board.js
|
import Piece from './piece';
export default class Board {
constructor() {
this.setBoard(this.initialUsiBoard());
}
initialUsiBoard() {
return (
[
['l', 'n', 's', 'g', 'k', 'g', 's', 'n', 'l'],
['*', 'b', '*', '*', '*', '*', '*', 'r', '*'],
['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
['*', '*', '*', '*', '*', '*', '*', '*', '*'],
['*', '*', '*', '*', '*', '*', '*', '*', '*'],
['*', '*', '*', '*', '*', '*', '*', '*', '*'],
['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
['*', 'B', '*', '*', '*', '*', '*', 'R', '*'],
['L', 'N', 'S', 'G', 'K', 'G', 'S', 'N', 'L']
]
);
}
setBoard(board) {
this.board = this.createBoard(board);
}
createBoard(board) {
var _board = board.map((row, y) => {
var yCor = y + 1;
var rows = row.map((type, x) => {
var xCor = 10 - x - 1;
return (
new Piece({ type: type, x: xCor, y: yCor })
);
});
return(rows);
});
return _board;
}
movePiece(fromPiece, toPiece) {
// if piece of argument is not match piece in the board, throw exception
//
if (! this.matchPiece(fromPiece)) {
var pos = `xCor = ${fromPiece.x}, yCor = ${fromPiece.y}`;
throw new Error(`Does not match coordinates in board. ${pos}`);
}
this.enhanceMovablePoint(fromPiece);
var [toCorX, toCorY] = [toPiece.x, toPiece.y];
var [toIdxX, toIdxY] = this.invertCor(toCorX, toCorY);
var [fromCorX, fromCorY] = [fromPiece.x, fromPiece.y];
var [fromIdxX, fromIdxY] = this.invertCor(fromCorX, fromCorY);
var destPiece = this.board[toIdxY][toIdxX];
if (typeof destPiece === 'undefined' || ! destPiece.movable) {
return;
}
fromPiece.x = destPiece.x;
fromPiece.y = destPiece.y;
this.board[toIdxY][toIdxX] = fromPiece;
this.board[fromIdxY][fromIdxX].type = '*';
return;
}
enhanceMovablePoint(piece) {
var [xCor, yCor] = [piece.x, piece.y];
var moveDef = piece.moveDef();
// if piece of argument is not match piece in the board, throw exception
//
if (! this.matchPiece(piece)) {
var pos = `xCor = ${xCor}, yCor = ${yCor}`;
throw new Error(`Does not match coordinates in board. ${pos}`);
}
// if moveDef has just property, piece moves just coordinates on board.
//
if (moveDef.just) {
this.movablePointsByJust(piece);
}
// if moveDef has fly property, piece moves recursion on board.
//
if (moveDef.fly) {
this.movablePointsByFly(piece);
}
}
// if piece of argument is match in the board, return true, else return false
//
matchPiece(piece) {
var [xCor, yCor] = [piece.x, piece.y];
var [x, y] = this.invertCor(xCor, yCor);
var isUndefined = typeof this.findPiece(x, y) === 'undefined';
var isEqualPiece = this.findPiece(x, y).equals(
new Piece({
x: piece.x,
y: piece.y,
type: piece.type,
movable: piece.movable
})
);
return (isUndefined || isEqualPiece);
}
// if moveDef has just property, piece moves just coordinates on board.
//
movablePointsByJust(piece) {
var [xCor, yCor] = [piece.x, piece.y];
var moveDef = piece.moveDef();
var [x, y] = this.invertCor(xCor, yCor);
moveDef.just.forEach((def) => {
var [defX, defY] = def;
var piece = this.findPiece(x + defX, y + defY);
if (piece) { piece.movable = true; }
});
}
movablePointsByFly(piece) {
var [xCor, yCor] = [piece.x, piece.y];
var moveDef = piece.moveDef();
var [x, y] = this.invertCor(xCor, yCor);
moveDef.fly.forEach((def) => {
var [defX, defY] = def;
var dx, dy;
dx = x + defX;
dy = y + defY;
var piece = this.findPiece(dx, dy);
while (piece) {
piece.movable = true;
dx = dx + defX;
dy = dy + defY;
piece = this.findPiece(dx, dy);
if (piece && piece.type !== '*') {
piece.movable = true;
break;
}
}
});
}
invertToIndexX(xCor) {
return 9 - xCor;
}
invertToIndexY(yCor) {
return yCor - 1;
}
invertCor(xCor, yCor) {
return [this.invertToIndexX(xCor), this.invertToIndexY(yCor)];
}
findPiece(xIndex, yIndex) {
var row = this.board[yIndex];
return row ? row[xIndex] : undefined;
}
toArray() {
return this.board.map((row) => {
return row.map((piece) => {
return piece.type;
});
});
}
// transposeToCorX(xIndex) {
// }
// transposeToCorY(xIndex) {
// }
};
|
JavaScript
| 0.000722 |
@@ -827,13 +827,31 @@
r =
-y + 1
+this.transposeToCorY(y)
;%0A
@@ -911,18 +911,31 @@
r =
-10 - x - 1
+this.transposeToCorX(x)
;%0A
@@ -4110,24 +4110,141 @@
%7D);%0A %7D%0A%0A
+ transposeToCorX(xIndex) %7B%0A return 10 - xIndex - 1;%0A %7D%0A%0A transposeToCorY(yIndex) %7B%0A return yIndex + 1;%0A %7D%0A%0A
invertToIn
@@ -4679,86 +4679,8 @@
%0A %7D
-%0A%0A // transposeToCorX(xIndex) %7B%0A // %7D%0A%0A // transposeToCorY(xIndex) %7B%0A // %7D
%0A%7D;%0A
|
f6fafcd8c3e13c815fa6e7805ecfebf6019faadc
|
parametrize mq-worker
|
src/api/mq/mq-worker.js
|
src/api/mq/mq-worker.js
|
const amqp = require('amqplib');
// const amqpSugar = require('amqplib-sugar');
// const superagent = require('superagent-promise')(require('superagent'), Promise);
const uri = process.env.SAMMLER_RABBITMQ_URI;
// Todo: Remove, just a prototype
class MqWorker {
constructor() {
this.init();
}
init() {
this.listenFoo();
}
listenFoo() {
const ex = 'github.profile-sync';
const exchangeType = 'topic';
const queueProfileSync = 'queue-profile-sync';
amqp.connect(uri)
.then(conn => {
return conn.createChannel();
})
.then(channel => {
return Promise.all([
channel.assertExchange(ex, exchangeType),
channel.assertQueue(queueProfileSync, {exclusive: false}),
channel.bindQueue(queueProfileSync, ex, '#'),
channel.consume(queueProfileSync, msg => {
// eslint-disable-next-line quotes
console.log(" [x] %s - %s:'%s'", '#', msg.fields.routingKey, msg.content.toString());
// Mark job as running
// Run the job
// Mark job as finished
// Notify RabbitMQ
channel.ack(msg);
}, {noAck: false})
]);
});
}
}
module.exports = MqWorker;
|
JavaScript
| 0.998334 |
@@ -157,16 +157,153 @@
romise);
+%0Aconst GitHubProfile = require('./../modules/github/github.profile');%0Aconst gitHubProfileBL = require('./../modules/profile/profile.bl');
%0A%0Aconst
@@ -435,60 +435,140 @@
;%0A
-%7D%0A%0A init() %7B%0A this.listenFoo();%0A %7D%0A%0A listenFoo
+ this.gitHubProfile = new GitHubProfile();%0A %7D%0A%0A init() %7B%0A this.listenProfileSyncRequested();%0A %7D%0A%0A listenProfileSyncRequested
() %7B
@@ -675,17 +675,24 @@
= 'queue
--
+.github.
profile-
@@ -1015,17 +1015,30 @@
c, ex, '
-#
+sync.requested
'),%0A
@@ -1268,16 +1268,17 @@
unning%0A%0A
+%0A
@@ -1295,16 +1295,136 @@
the job
+%0A this.gitHubProfile.getProfile()%0A .then(result =%3E console.log('gh.getProfile.result', result));
%0A%0A
|
4a4b7308a9e90a6ac7774baba724043a14a50016
|
Fix build error
|
src/app/index.module.js
|
src/app/index.module.js
|
/* global malarkey:false, moment:false, Howl, Howler:false, SockJS:false*/
import { config } from './index.config';
import { routerConfig } from './index.route';
import { runBlock } from './index.run';
import MainController from './main/main.controller';
import AboutController from './about/about.controller';
import SelectController from './select/select.controller';
import LobbyController from './lobby/lobby.controller';
import LoadingController from './loading/loading.controller';
import GameController from './game/game.controller';
import NavbarDirective from './components/navbar/navbar.directive';
import AudioService from './services/audio.service';
import GameService from './services/game.service';
import SocketService from './services/socket.service';
import BroadcastService from './services/broadcast.service';
import ModeFactory from './factories/mode.factory.js';
import GameFactory from './factories/game.factory.js';
import ImageFactory from './factories/image.factory.js';
import baseURLConfig from './api.js';
import Player from './models/player.js';
var lodash = require('lodash');
angular.module('famousPlacesWeb', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngMessages', 'ngAria', 'angularScreenfull', 'ui.router', 'ui.bootstrap', 'toastr', 'ngStorage'])
.constant('malarkey', malarkey)
.constant('moment', moment)
.constant('_', lodash)
.constant('Howl', Howl)
.constant('Howler', Howler)
.constant('SockJS', SockJS)
//models
.constant('Player', Player)
//global strings
.constant('baseURLConfig', baseURLConfig)
.constant('baseMusic', "https://dl.dropboxusercontent.com/u/13188176/Famous%20Places/Music/Fingerpoppin%27%27.mp3")
.constant('lobbyMusic', 'https://dl.dropboxusercontent.com/u/13188176/Famous%20Places/Music/bensound-theelevatorbossanova.mp3')
.constant('audioOn', 'volume_up')
.constant('audioOff', 'volume_off')
.config(config)
.config(routerConfig)
.run(runBlock)
.controller('MainController', MainController)
.controller('AboutController', AboutController)
.controller('SelectController', SelectController)
.controller('LobbyController', LobbyController)
.controller('LoadingController', LoadingController)
.controller('GameController', GameController)
.directive('navbar', () => new NavbarDirective())
.service('AudioService', AudioService)
.service('GameService', GameService)
.service('SocketService', SocketService)
.service('BroadcastService', BroadcastService)
.factory('ModeFactory', ($http, baseURLConfig) => new ModeFactory($http, baseURLConfig))
.factory('GameFactory', ($http, baseURLConfig) => new GameFactory($http, baseURLConfig))
.factory('ImageFactory', ($http, baseURLConfig) => new ImageFactory($http, baseURLConfig));
|
JavaScript
| 0.000001 |
@@ -1035,49 +1035,8 @@
js';
-%0Aimport Player from './models/player.js';
%0A%0Ava
@@ -1430,50 +1430,8 @@
S)%0A%0A
- //models%0A .constant('Player', Player)%0A%0A
//
|
44b82684976be8de372e1c1a5a2078b371993ef4
|
make sure the logger only shows what is expected for a particular level
|
lib/haiku/logger.js
|
lib/haiku/logger.js
|
var colors = require('colors');
// this is a quick-and-dirty logger. there are other nicer loggers out there
// but the ones i found were also somewhat involved. this one has a Ruby
// logger type interface and color codes the console output
//
// we can easily replace this, provide the info, debug, etc. methods are the
// same. or, we can change Haiku to use a more standard node.js interface
var Logger = function(options) {
this.level = options.level;
this.colors = options.colors||this.colors;
switch(this.level){
case "debug":
this.debug = function(message) { this.log("warn",message); }
case "warn":
this.warn = function(message) { this.log("warn",message); }
break;
}
if (options.module) {
this.prefix = options.module + ": ";
} else { this.prefix = ""; }
}
Logger.prototype = {
log: function(level,message) {
console[level]((this.prefix+message)[this.colors[level]]);
},
info: function(message) { this.log("info",message); },
debug: function(message) {},
warn: function(message) {},
error: function(message) { this.log("error",message); },
colors: {
info: "green",
warn: "yellow",
debug: "orange",
error: "red"
}
};
module.exports = Logger;
|
JavaScript
| 0.000001 |
@@ -23,19 +23,51 @@
colors')
+%0A , _ = require('underscore')%0A
;%0A%0A
+%0A
// this
@@ -456,16 +456,38 @@
ions) %7B%0A
+ var logger = this;%0A%0A
this.l
@@ -553,16 +553,17 @@
colors;%0A
+%0A
switch
@@ -575,17 +575,16 @@
.level)%7B
-
%0A cas
@@ -656,24 +656,302 @@
,message); %7D
+%0A%0A _.each(%5B'info', 'warn'%5D, function(level)%7B%0A logger%5Blevel%5D = function(message)%7B logger.log(level, message) %7D%0A %7D);%0A case 'info':%0A _.each(%5B'info', 'warn'%5D, function(level)%7B%0A logger%5Blevel%5D = function(message)%7B logger.log(level, message) %7D%0A %7D);
%0A case %22w
@@ -1039,16 +1039,17 @@
ak;%0A %7D%0A
+%0A
if (op
@@ -1261,16 +1261,16 @@
);%0A %7D,%0A
+
info:
@@ -1292,35 +1292,8 @@
e) %7B
- this.log(%22info%22,message);
%7D,%0A
|
58889a2aec358e84e152af7ce2c279efedb9cfae
|
fix async error on lines response
|
src/helpers/lines-response.js
|
src/helpers/lines-response.js
|
import axios from 'axios'
import { API } from '../constants'
export default async function buildLinhasResponse (lines) {
const buildPromise = tripId =>
axios({
method: 'get',
url: `${API.server}/trips/${tripId}`
})
const parseShapeId = res =>
res.map(item =>
item.data[0] ? item.data[0].shape_id : null)
const getShapesIds = tripsIds => {
const promises = tripsIds.map(buildPromise)
return Promise.all(promises).then(parseShapeId)
}
const tripsIds = lines.map(item =>
`${item.lt}-${item.tl}-${item.sl - 1}`)
const shapesIds = await getShapesIds(tripsIds)
const response = lines.map((item, key) => ({
lineId: item.cl,
shapeId: shapesIds[key],
circular: item.lc,
displaySign: item.lt,
direction: item.sl,
type: item.tl,
mainTerminal: item.tp,
secondaryTerminal: item.ts,
}))
return response
}
|
JavaScript
| 0.000029 |
@@ -74,14 +74,8 @@
ult
-async
func
@@ -83,18 +83,12 @@
ion
-buildLinha
+line
sRes
@@ -269,22 +269,16 @@
(item =%3E
-%0A
item.da
@@ -546,31 +546,14 @@
%0A%0A
-const shapesIds = await
+return
get
@@ -575,28 +575,30 @@
Ids)
-%0A%0A const response =
+.then(shapesIds =%3E%0A
lin
@@ -622,16 +622,18 @@
) =%3E (%7B%0A
+
line
@@ -649,16 +649,18 @@
cl,%0A
+
shapeId:
@@ -680,16 +680,18 @@
y%5D,%0A
+
+
circular
@@ -701,16 +701,18 @@
tem.lc,%0A
+
disp
@@ -733,16 +733,18 @@
lt,%0A
+
directio
@@ -759,16 +759,18 @@
sl,%0A
+
+
type: it
@@ -776,16 +776,18 @@
tem.tl,%0A
+
main
@@ -805,16 +805,18 @@
tem.tp,%0A
+
seco
@@ -841,33 +841,16 @@
m.ts
-,
%0A
+
%7D))
-%0A%0A return response
+)
%0A%7D%0A
|
69486d0770790f19115676f26bfef45c7bb4d796
|
initialize a swiz instance
|
lib/cast-agent/managers.js
|
lib/cast-agent/managers.js
|
/*
* Licensed to Cloudkick, Inc ('Cloudkick') under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Cloudkick licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var async = require('async');
var sprintf = require('sprintf').sprintf;
var jobs = require('jobs');
/**
* ResourceManagers that should be instantiated, initialized and registered
* with the job manager.
*/
var RESOURCE_MANAGERS = [
{
module: 'security/ca',
type: 'SigningRequestManager'
}
];
/**
* The Cast Agent's JobManager.
*/
var jobManager = null;
/**
* Initialize the job manager and all resource managers.
* @param {Function} callback
*/
function initManagers(callback) {
// First we need a JobManager.
jobManager = new jobs.JobManager();
// Initialize an individual ResourceManager.
function initResourceManager(managerInfo, callback) {
var constructor = require(managerInfo.module)[managerInfo.type];
var manager = new constructor();
manager.init(function(err) {
if (!err) {
jobManager.registerResourceManager(manager);
}
callback(err);
});
}
// Initialize all of the managers.
async.forEachSeries(RESOURCE_MANAGERS, initResourceManager, callback);
}
/**
* Get the Cast JobManager;
*/
function getJobManager() {
return jobManager;
}
exports.initManagers = initManagers;
exports.getJobManager = getJobManager;
|
JavaScript
| 0.000088 |
@@ -861,16 +861,44 @@
sprintf;
+%0Avar swiz = require('swiz');
%0A%0Avar jo
@@ -1190,24 +1190,159 @@
r = null;%0A%0A%0A
+/**%0A * The Cast Agent's ResourceManagers.%0A */%0Avar managers = %7B%7D;%0A%0A%0A/**%0A * The Cast Agent's Swiz instance.%0A */%0Avar serializer = null;%0A%0A%0A
/**%0A * Initi
@@ -1458,16 +1458,38 @@
back) %7B%0A
+ var swizDefs = %7B%7D;%0A%0A
// Fir
@@ -1733,22 +1733,16 @@
var m
-anager
= new c
@@ -1761,22 +1761,16 @@
;%0A%0A m
-anager
.init(fu
@@ -1813,50 +1813,159 @@
-jobManager.registerResourceManager(manager
+managers%5BmanagerInfo.type%5D = m;%0A jobManager.registerResourceManager(m);%0A swizDefs%5Bm.resourceType.name%5D = m.resourceType.getSerializerDef(
);%0A
@@ -2104,24 +2104,134 @@
anager,
-callback
+function(err) %7B%0A if (err) %7B%0A callback(err);%0A return;%0A %7D%0A%0A serializer = new swiz.Swiz(swizDefs);%0A %7D
);%0A%7D%0A%0A%0A/
@@ -2259,17 +2259,17 @@
bManager
-;
+.
%0A */%0Afun
@@ -2317,16 +2317,198 @@
er;%0A%7D%0A%0A%0A
+/**%0A * Get a ResourceManager.%0A */%0Afunction getManager(name) %7B%0A return managers%5Bname%5D;%0A%7D%0A%0A%0A/**%0A * Get the Cast Swiz instance.%0A */%0Afunction getSerializer() %7B%0A return serializer;%0A%7D%0A%0A%0A
exports.
@@ -2536,16 +2536,49 @@
nagers;%0A
+exports.getManager = getManager;%0A
exports.
|
766db3a373e777ade402c09226f087a48f4fb627
|
recompile dom.svg.js in lib
|
lib/imba/dom.svg.js
|
lib/imba/dom.svg.js
|
(function(){
function idx$(a,b){
return (b && b.indexOf) ? b.indexOf(a) : [].indexOf.call(a,b);
};
tag$.SVG.defineTag('svgelement', function(tag){
tag.namespaceURI = function (){
return "http://www.w3.org/2000/svg";
};
var types = "circle defs ellipse g line linearGradient mask path pattern polygon polyline radialGradient rect stop svg text tspan".split(" ");
tag.buildNode = function (){
var dom = Imba.document().createElementNS(this.namespaceURI(),this._nodeType);
var cls = this._classes.join(" ");
if (cls) { dom.className.baseVal = cls };
return dom;
};
tag.inherit = function (child){
child._protoDom = null;
if (idx$(child._name,types) >= 0) {
child._nodeType = child._name;
return child._classes = [];
} else {
child._nodeType = this._nodeType;
var className = "_" + child._name.replace(/_/g,'-');
return child._classes = this._classes.concat(className);
};
};
Imba.attr(tag,'x');
Imba.attr(tag,'y');
Imba.attr(tag,'width');
Imba.attr(tag,'height');
Imba.attr(tag,'stroke');
Imba.attr(tag,'stroke-width');
});
tag$.SVG.defineTag('svg', function(tag){
Imba.attr(tag,'viewbox');
});
tag$.SVG.defineTag('g');
tag$.SVG.defineTag('defs');
tag$.SVG.defineTag('symbol', function(tag){
Imba.attr(tag,'preserveAspectRatio');
Imba.attr(tag,'viewBox');
});
tag$.SVG.defineTag('marker', function(tag){
Imba.attr(tag,'markerUnits');
Imba.attr(tag,'refX');
Imba.attr(tag,'refY');
Imba.attr(tag,'markerWidth');
Imba.attr(tag,'markerHeight');
Imba.attr(tag,'orient');
});
// Basic shapes
tag$.SVG.defineTag('rect', function(tag){
Imba.attr(tag,'rx');
Imba.attr(tag,'ry');
});
tag$.SVG.defineTag('circle', function(tag){
Imba.attr(tag,'cx');
Imba.attr(tag,'cy');
Imba.attr(tag,'r');
});
tag$.SVG.defineTag('ellipse', function(tag){
Imba.attr(tag,'cx');
Imba.attr(tag,'cy');
Imba.attr(tag,'rx');
Imba.attr(tag,'ry');
});
tag$.SVG.defineTag('path', function(tag){
Imba.attr(tag,'d');
Imba.attr(tag,'pathLength');
});
tag$.SVG.defineTag('line', function(tag){
Imba.attr(tag,'x1');
Imba.attr(tag,'x2');
Imba.attr(tag,'y1');
Imba.attr(tag,'y2');
});
tag$.SVG.defineTag('polyline', function(tag){
Imba.attr(tag,'points');
});
tag$.SVG.defineTag('polygon', function(tag){
Imba.attr(tag,'points');
});
tag$.SVG.defineTag('text', function(tag){
Imba.attr(tag,'dx');
Imba.attr(tag,'dy');
Imba.attr(tag,'text-anchor');
Imba.attr(tag,'rotate');
Imba.attr(tag,'textLength');
Imba.attr(tag,'lengthAdjust');
});
return tag$.SVG.defineTag('tspan', function(tag){
Imba.attr(tag,'dx');
Imba.attr(tag,'dy');
Imba.attr(tag,'rotate');
Imba.attr(tag,'textLength');
Imba.attr(tag,'lengthAdjust');
});
})()
|
JavaScript
| 0.000001 |
@@ -98,35 +98,41 @@
;%0A%09%7D;%0A%09%0A%09%0A%09tag$.
-SVG
+ns('svg')
.defineTag('svge
@@ -1131,35 +1131,41 @@
);%0A%09%7D);%0A%09%0A%09tag$.
-SVG
+ns('svg')
.defineTag('svg'
@@ -1214,35 +1214,41 @@
);%0A%09%7D);%0A%09%0A%09tag$.
-SVG
+ns('svg')
.defineTag('g');
@@ -1248,35 +1248,41 @@
g('g');%0A%09%0A%09tag$.
-SVG
+ns('svg')
.defineTag('defs
@@ -1285,35 +1285,41 @@
defs');%0A%09%0A%09tag$.
-SVG
+ns('svg')
.defineTag('symb
@@ -1411,35 +1411,41 @@
);%0A%09%7D);%0A%09%0A%09tag$.
-SVG
+ns('svg')
.defineTag('mark
@@ -1664,35 +1664,41 @@
shapes%0A%09%0A%09tag$.
-SVG
+ns('svg')
.defineTag('rect
@@ -1766,35 +1766,41 @@
);%0A%09%7D);%0A%09%0A%09tag$.
-SVG
+ns('svg')
.defineTag('circ
@@ -1892,35 +1892,41 @@
);%0A%09%7D);%0A%09%0A%09tag$.
-SVG
+ns('svg')
.defineTag('elli
@@ -2043,35 +2043,41 @@
);%0A%09%7D);%0A%09%0A%09tag$.
-SVG
+ns('svg')
.defineTag('path
@@ -2152,35 +2152,41 @@
);%0A%09%7D);%0A%09%0A%09tag$.
-SVG
+ns('svg')
.defineTag('line
@@ -2300,35 +2300,41 @@
);%0A%09%7D);%0A%09%0A%09tag$.
-SVG
+ns('svg')
.defineTag('poly
@@ -2387,35 +2387,41 @@
);%0A%09%7D);%0A%09%0A%09tag$.
-SVG
+ns('svg')
.defineTag('poly
@@ -2477,27 +2477,33 @@
%7D);%0A%09%0A%09tag$.
-SVG
+ns('svg')
.defineTag('
@@ -2717,11 +2717,17 @@
ag$.
-SVG
+ns('svg')
.def
|
fd556a246be26a4acb2089af498417e97f6a7e0e
|
Fix bug where config is over written when multiple plugins are installed
|
lib/android-cli.js
|
lib/android-cli.js
|
var path = require('path');
var fs = require('fs');
var mkdirp = require('mkdirp');
var rimraf = require('rimraf')
var cordova = require('cordova-lib');
var CONFIG_XML = "<?xml version='1.0' encoding='utf-8'?><widget xmlns='http://www.w3.org/ns/widgets' xmlns:cdv='http://cordova.apache.org/ns/1.0'></widget>";
var ANDROID_MANIFEST = '<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.cordova.reactnative.cordovaplugin"></manifest>';
var PLATFORM_DIR = path.resolve(__dirname, '../plugins/android');
function Android(projectRoot) {
this.projectRoot = projectRoot;
this.init();
}
Android.prototype.init = function() {
if (this.isInitialized) {
return;
}
console.log('Initializing Android resources');
var res = mkdirp.sync(path.resolve(PLATFORM_DIR, 'src'));
console.log('Created directory %s', res);
res = mkdirp.sync(path.resolve(PLATFORM_DIR, 'res/xml'));
console.log('Created directory for config - %s', res);
fs.writeFileSync(path.resolve(PLATFORM_DIR, 'res/xml/config.xml'), CONFIG_XML);
fs.writeFileSync(path.resolve(PLATFORM_DIR, 'AndroidManifest.xml'), ANDROID_MANIFEST);
};
Android.prototype.add = function(plugin) {
return cordova.plugman.raw.install(
'android',
PLATFORM_DIR,
plugin,
path.resolve(this.projectRoot, 'node_modules'), {
platformVersion: '4.0.0',
});
};
Android.prototype.remove = function(plugin) {
return cordova.plugman.raw.uninstall(
'android',
PLATFORM_DIR,
plugin,
path.resolve(this.projectRoot, 'node_modules'), {
platformVersion: '4.0.0',
});
};
module.exports = Android;
|
JavaScript
| 0 |
@@ -992,32 +992,32 @@
);%0A%0A
-fs.
write
-FileSync
+IfNotExists
(path.re
@@ -1080,24 +1080,24 @@
-fs.
write
-FileSync
+IfNotExists
(pat
@@ -1163,24 +1163,265 @@
IFEST);%0A%7D;%0A%0A
+function writeIfNotExists(filename, data) %7B%0A try %7B%0A if (!fs.lstatSync(filename).isFile()) %7B%0A throw('This is not a file, so write it anyway')%0A %7D%0A %7D catch (e) %7B%0A fs.writeFileSync(filename, data);%0A %7D%0A%7D%0A%0A
Android.prot
|
bdbd84e2a978322f3af12c21e729eb7b7cd4a3dc
|
Update message type for Managers
|
src/types/message.js
|
src/types/message.js
|
const ArgumentType = require('./base');
class MessageArgumentType extends ArgumentType {
constructor(client) {
super(client, 'message');
}
async validate(val, msg) {
if(!/^[0-9]+$/.test(val)) return false;
return Boolean(await msg.channel.messages.fetch(val).catch(() => null));
}
parse(val, msg) {
return msg.channel.messages.get(val);
}
}
module.exports = MessageArgumentType;
|
JavaScript
| 0.000001 |
@@ -336,16 +336,22 @@
essages.
+cache.
get(val)
|
51781f79218de6c0f011fafd9a5593bf1e7865c5
|
Fix incorrect delta calculation (#5286)
|
lib/client/clock-client.js
|
lib/client/clock-client.js
|
'use strict';
const browserSettings = require('./browser-settings');
var client = {};
client.settings = browserSettings(client, window.serverSettings, $);
// console.log('settings', client.settings);
// client.settings now contains all settings
client.query = function query () {
console.log('query');
var parts = (location.search || '?').substring(1).split('&');
var token = '';
parts.forEach(function (val) {
if (val.startsWith('token=')) {
token = val.substring('token='.length);
}
});
var secret = localStorage.getItem('apisecrethash');
var src = '/api/v1/entries.json?count=3&t=' + new Date().getTime();
if (secret) {
src += '&secret=' + secret;
} else if (token) {
src += '&token=' + token;
}
$.ajax(src, {
success: client.render
});
};
client.render = function render (xhr) {
console.log('got data', xhr);
let rec;
let delta;
xhr.forEach(element => {
if (element.sgv && !rec && !delta) {
rec = element;
}
else if (element.sgv && rec && !delta) {
delta = (rec.sgv - element.sgv)/((rec.date - element.date)/(5*60*1000));
}
});
let $errorMessage = $('#errorMessage');
// If no one measured value found => show "-?-"
if (!rec) {
if (!$errorMessage.length) {
$('#arrowDiv').append('<div id="errorMessage" title="No data found in DB">-?-</div>');
$('#arrow').hide();
} else {
$errorMessage.show();
}
return;
} else {
$errorMessage.length && $errorMessage.hide();
$('#arrow').show();
}
let last = new Date(rec.date);
let now = new Date();
// Convert BG to mmol/L if necessary.
if (window.serverSettings.settings.units === 'mmol') {
var displayValue = window.Nightscout.units.mgdlToMMOL(rec.sgv);
var deltaDisplayValue = window.Nightscout.units.mgdlToMMOL(delta);
} else {
displayValue = rec.sgv;
deltaDisplayValue = Math.round(delta);
}
if (deltaDisplayValue > 0) {
deltaDisplayValue = '+' + deltaDisplayValue;
}
// Insert the BG value text.
$('#bgnow').html(displayValue);
// Insert the trend arrow.
$('#arrow').attr('src', '/images/' + (!rec.direction || rec.direction === 'NOT COMPUTABLE' ? 'NONE' : rec.direction) + '.svg');
// Time before data considered stale.
let staleMinutes = 13;
let threshold = 1000 * 60 * staleMinutes;
// Toggle stale if necessary.
$('#bgnow').toggleClass('stale', (now - last > threshold));
// Generate and insert the clock.
let timeDivisor = parseInt(client.settings.timeFormat ? client.settings.timeFormat : 12, 10);
let today = new Date()
, h = today.getHours() % timeDivisor;
if (timeDivisor === 12) {
h = (h === 0) ? 12 : h; // In the case of 00:xx, change to 12:xx for 12h time
}
if (timeDivisor === 24) {
h = (h < 10) ? ("0" + h) : h; // Pad the hours with a 0 in 24h time
}
let m = today.getMinutes();
if (m < 10) m = "0" + m;
$('#clock').text(h + ":" + m);
// defined in the template this is loaded into
// eslint-disable-next-line no-undef
if (clockFace === 'clock-color') {
var bgHigh = window.serverSettings.settings.thresholds.bgHigh;
var bgLow = window.serverSettings.settings.thresholds.bgLow;
var bgTargetBottom = window.serverSettings.settings.thresholds.bgTargetBottom;
var bgTargetTop = window.serverSettings.settings.thresholds.bgTargetTop;
var bgNum = parseFloat(rec.sgv);
// These are the particular shades of red, yellow, green, and blue.
var red = 'rgba(213,9,21,1)';
var yellow = 'rgba(234,168,0,1)';
var green = 'rgba(134,207,70,1)';
var blue = 'rgba(78,143,207,1)';
var elapsedMins = Math.round(((now - last) / 1000) / 60);
// Insert the BG stale time text.
let staleTimeText;
if (elapsedMins == 0) {
staleTimeText = 'Just now';
}
else if (elapsedMins == 1) {
staleTimeText = '1 minute ago';
}
else {
staleTimeText = elapsedMins + ' minutes ago';
}
$('#staleTime').text(staleTimeText);
// Force NS to always show 'x minutes ago'
if (window.serverSettings.settings.showClockLastTime) {
$('#staleTime').css('display', 'block');
}
// Insert the delta value text.
$('#delta').html(deltaDisplayValue);
// Show delta
if (window.serverSettings.settings.showClockDelta) {
$('#delta').css('display', 'inline-block');
}
// Threshold background coloring.
if (bgNum < bgLow) {
$('body').css('background-color', red);
}
if ((bgLow <= bgNum) && (bgNum < bgTargetBottom)) {
$('body').css('background-color', blue);
}
if ((bgTargetBottom <= bgNum) && (bgNum < bgTargetTop)) {
$('body').css('background-color', green);
}
if ((bgTargetTop <= bgNum) && (bgNum < bgHigh)) {
$('body').css('background-color', yellow);
}
if (bgNum >= bgHigh) {
$('body').css('background-color', red);
}
// Restyle body bg, and make the "x minutes ago" visible too.
if (now - last > threshold) {
$('body').css('background-color', 'grey');
$('body').css('color', 'black');
$('#arrow').css('filter', 'brightness(0%)');
if (!window.serverSettings.settings.showClockLastTime) {
$('#staleTime').css('display', 'block');
}
} else {
$('body').css('color', 'white');
$('#arrow').css('filter', 'brightness(100%)');
if (!window.serverSettings.settings.showClockLastTime) {
$('#staleTime').css('display', 'none');
}
}
}
};
client.init = function init () {
console.log('init');
client.query();
setInterval(client.query, 1 * 60 * 1000);
};
module.exports = client;
|
JavaScript
| 0 |
@@ -947,26 +947,16 @@
&& !rec
- && !delta
) %7B%0A
@@ -1017,14 +1017,19 @@
&&
-!
delta
+==null
) %7B%0A
|
6391622fb3528059c2ba8b1f30c6ce3de024b2d5
|
Fix plugin export to extend Leaflet instead of exposing methods
|
leaflet.spin.js
|
leaflet.spin.js
|
(function (window) {
var SpinMapMixin = {
spin: function (state, options) {
if (!!state) {
// start spinning !
if (!this._spinner) {
this._spinner = new Spinner(options).spin(this._container);
this._spinning = 0;
}
this._spinning++;
}
else {
this._spinning--;
if (this._spinning <= 0) {
// end spinning !
if (this._spinner) {
this._spinner.stop();
this._spinner = null;
}
}
}
}
};
var SpinMapInitHook = function () {
this.on('layeradd', function (e) {
// If added layer is currently loading, spin !
if (e.layer.loading) this.spin(true);
if (typeof e.layer.on != 'function') return;
e.layer.on('data:loading', function () { this.spin(true); }, this);
e.layer.on('data:loaded', function () { this.spin(false); }, this);
}, this);
this.on('layerremove', function (e) {
// Clean-up
if (e.layer.loading) this.spin(false);
if (typeof e.layer.on != 'function') return;
e.layer.off('data:loaded');
e.layer.off('data:loading');
}, this);
};
// define an AMD module that relies on 'leaflet'
if (typeof define === 'function' && define.amd) {
define(['leaflet'], SpinMapMixin);
define(['leaflet'], SpinMapInitHook);
// define a Common JS module that relies on 'leaflet'
} else if (typeof exports === 'object') {
module.exports = {
SpinMapMixin: SpinMapMixin,
SpinMapInitHook: SpinMapInitHook
};
}
// attach your plugin to the global 'L' variable
if (typeof window !== 'undefined' && window.L) {
L.Map.include(SpinMapMixin);
L.Map.addInitHook(SpinMapInitHook);
}
}(window));
|
JavaScript
| 0 |
@@ -4,16 +4,25 @@
nction (
+factory,
window)
@@ -23,16 +23,673 @@
ndow) %7B%0A
+ // define an AMD module that relies on 'leaflet'%0A if (typeof define === 'function' && define.amd) %7B%0A define(%5B'leaflet'%5D, function (L) %7B%0A factory(L);%0A %7D);%0A%0A // define a Common JS module that relies on 'leaflet'%0A %7D else if (typeof exports === 'object') %7B%0A module.exports = function (L) %7B%0A if (L === undefined) %7B%0A L = require('leaflet');%0A %7D%0A factory(L);%0A return L;%0A %7D;%0A // attach your plugin to the global 'L' variable%0A %7D else if (typeof window !== 'undefined' && window.L) %7B%0A factory(window.L);%0A %7D%0A%7D(function leafletSpinFactory(L) %7B
%0A var
@@ -905,16 +905,41 @@
options)
+%0A
.spin(th
@@ -1619,32 +1619,33 @@
of e.layer.on !=
+=
'function') ret
@@ -1693,32 +1693,48 @@
', function () %7B
+%0A
this.spin(true)
@@ -1734,16 +1734,28 @@
n(true);
+%0A
%7D, this
@@ -1809,16 +1809,32 @@
ion () %7B
+%0A
this.sp
@@ -1843,16 +1843,28 @@
(false);
+%0A
%7D, this
@@ -2041,16 +2041,17 @@
er.on !=
+=
'functi
@@ -2174,544 +2174,8 @@
%7D;%0A%0A
- // define an AMD module that relies on 'leaflet'%0A if (typeof define === 'function' && define.amd) %7B%0A define(%5B'leaflet'%5D, SpinMapMixin);%0A define(%5B'leaflet'%5D, SpinMapInitHook);%0A%0A // define a Common JS module that relies on 'leaflet'%0A %7D else if (typeof exports === 'object') %7B%0A module.exports = %7B%0A SpinMapMixin: SpinMapMixin,%0A SpinMapInitHook: SpinMapInitHook%0A %7D;%0A %7D%0A // attach your plugin to the global 'L' variable%0A if (typeof window !== 'undefined' && window.L) %7B%0A
@@ -2203,20 +2203,16 @@
Mixin);%0A
-
L.Ma
@@ -2243,24 +2243,19 @@
tHook);%0A
- %7D%0A%7D(
+%7D,
window))
|
fc2af03a0711c37be8664dc6d5d4f9a8ff0715ce
|
Remove extraneous #EXISTING flagging
|
lib/install/node.js
|
lib/install/node.js
|
'use strict'
var defaultTemplate = {
package: {
dependencies: {},
devDependencies: {},
_requiredBy: [],
_phantomChildren: {}
},
loaded: false,
children: [],
requires: [],
missingDeps: {},
path: null,
realpath: null
}
var create = exports.create = function (node, template) {
if (!template) template = defaultTemplate
Object.keys(template).forEach(function (key) {
if (template[key] != null && typeof template[key] === 'object' && !(template[key] instanceof Array)) {
if (!node[key]) node[key] = {}
return create(node[key], template[key])
}
if (node[key] != null) return
node[key] = template[key]
})
return node
}
var reset = exports.reset = function (node) {
if (node.parent && !node.parent.parent && node.package && !node.package._requiredBy) node.package._requiredBy = ['#EXISTING']
var child = create(node)
child.package._requiredBy = child.package._requiredBy.filter(function (req) {
return req[0] === '#'
})
child.requires = []
child.package._phantomChildren = {}
child.missingDeps = {}
child.children.forEach(reset)
}
|
JavaScript
| 0.000075 |
@@ -726,136 +726,8 @@
) %7B%0A
- if (node.parent && !node.parent.parent && node.package && !node.package._requiredBy) node.package._requiredBy = %5B'#EXISTING'%5D%0A
va
|
c7e754e9f4c05db80f8e105db1da5542dd0b7240
|
change apn to apns
|
db.js
|
db.js
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var db_url = process.env.environmentVariable || "mongodb://localhost:27017/aerodeck",
db = mongoose.connect(db_url);
var boardState = new Schema({
one:{type:[Number]},
two:{type:[Number]},
three:{type:[Number]},
four:{type:[Number]},
five:{type:[Number]},
six:{type:[Number]},
seven:{type:[Number]}
})
var userSchema = new Schema({
id: ObjectId,
fullName: String,
username: String,
email: String,
password: String,
apn: {type:[String]},
gcm: {type:[String]},
created: String,
updated: String
})
var matchSchema = new Schema({
id: ObjectId,
participants: {type:[String]},
activeParticipants: Number,
board: [boardState],
created: String,
updated: String,
deleted:{type:[String]}
})
var user = db.model('user', userSchema);
var match = db.model('match', matchSchema);
|
JavaScript
| 0.003479 |
@@ -542,16 +542,17 @@
g,%0A apn
+s
: %7Btype:
|
3fe4d54749c69b32ebbb8072e4a45e7f702b35f3
|
enable notify database property change for hasMany
|
addon/properties/relations/has-many.js
|
addon/properties/relations/has-many.js
|
import Ember from 'ember';
import Relation from './relation';
import Ignore from './util/ignore';
import {
getInternalModel,
internalModelDidChangeIsDeleted,
internalModelDidChangeInternalWillDestroy
} from '../../internal-model';
const {
copy,
A
} = Ember;
const getDiff = (curr, next) => {
let remove = curr.filter(item => {
return !next.includes(item);
});
let add = next.filter(model => {
return !curr.includes(model);
});
return { remove, add };
};
export default class HasManyRelation extends Relation {
constructor() {
super(...arguments);
this.ignoreValueChanges = new Ignore();
}
dirty() {
this.withPropertyChanges(changed => {
super.dirty(changed);
});
}
//
inverseWillChange(internal) {
this.removeContentObject(internal, false);
}
inverseDidChange(internal) {
this.addContentObject(internal, false);
}
getContent() {
let content = this.content;
if(!content) {
content = A();
this.content = content;
}
return content;
}
//
willRemoveContentObject(internal, updateInverse=true) {
internal.removeObserver(this);
if(updateInverse) {
let inverse = this.getInverseRelation(internal);
if(inverse) {
inverse.inverseWillChange(this.internal);
}
}
}
didAddContentObject(internal, updateInverse=true) {
internal.addObserver(this);
if(updateInverse) {
let inverse = this.getInverseRelation(internal);
if(inverse) {
inverse.inverseDidChange(this.internal);
}
}
}
addContentObject(internal, updateInverse=true) {
if(!internal) {
return;
}
this.ignoreValueChanges.with(() => {
let content = this.getContent();
content.addObject(internal);
this.didAddContentObject(internal, updateInverse);
this.dirty();
});
}
removeContentObject(internal, updateInverse=true) {
if(!internal) {
return;
}
this.ignoreValueChanges.with(() => {
let content = this.getContent();
this.willRemoveContentObject(internal, updateInverse);
content.removeObject(internal);
this.dirty();
});
}
//
get valueObserverOptions() {
return {
willChange: this.valueWillChange,
didChange: this.valueDidChange
};
}
getValue() {
let value = this.value;
if(!value) {
let content = this.getContent();
let store = this.relationship.store;
value = this.createArrayProxy(store, content);
value.addEnumerableObserver(this, this.valueObserverOptions);
this.value = value;
}
return value;
}
setValue(value) {
this.ignoreValueChanges.with(() => {
let curr = this.getContent();
let next = A(value).map(model => getInternalModel(model));
let { remove, add } = getDiff(curr, next);
remove.forEach(internal => {
this.willRemoveContentObject(internal, true);
});
curr.removeObjects(remove);
curr.pushObjects(add);
add.forEach(internal => {
this.didAddContentObject(internal, true);
});
});
}
valueWillChange(proxy, removing) {
if(this.ignoreValueChanges.ignore()) {
return;
}
this.ignoreValueChanges.with(() => {
removing.forEach(model => {
let internal = getInternalModel(model);
this.willRemoveContentObject(internal, true);
});
});
}
valueDidChange(proxy, removeCount, adding) {
if(this.ignoreValueChanges.ignore()) {
return;
}
this.ignoreValueChanges.with(() => {
adding.forEach(model => {
let internal = getInternalModel(model);
this.didAddContentObject(internal, true);
});
this.dirty();
});
}
//
onInternalDeleted() {
}
onContentDeleted(internal) {
this.ignoreValueChanges.with(() => {
this.removeContentObject(internal, false);
});
}
onInternalDestroyed() {
let value = this.value;
if(value) {
value.removeEnumerableObserver(this, this.valueObserverOptions);
value.destroy();
this.value = null;
}
let content = this.content;
if(content) {
this.ignoreValueChanges.with(() => {
let content_ = copy(content);
content_.forEach(internal => this.removeContentObject(internal, false));
});
}
this.content = null;
super.onInternalDestroyed();
}
onContentDestroyed(internal) {
this.onContentDeleted(internal);
}
internalModelDidChange(internal, props) {
super.internalModelDidChange(...arguments);
if(internal === this.internal) {
if(internalModelDidChangeIsDeleted(internal, props)) {
this.onInternalDeleted();
} else if(internalModelDidChangeInternalWillDestroy(internal, props)) {
this.onInternalDestroyed();
}
} else {
if(internalModelDidChangeIsDeleted(internal, props)) {
this.onContentDeleted(internal);
} else if(internalModelDidChangeInternalWillDestroy(internal, props)) {
this.onContentDestroyed(internal);
}
}
}
//
internalModelFromModel(model) {
if(!model) {
return null;
}
return getInternalModel(model);
}
modelFromInternalModel(internal) {
if(!internal) {
return null;
}
return internal.getModel();
}
//
serializeInternalModelsToDocIds(content, type) {
return A(content.map(internal => {
return this.serializeInternalModelToDocId(internal, type);
})).compact();
}
deserializeDocIdsToModels(value) {
return A(A(value).map(docId => this.deserializeDocIdToInternalModel(docId))).compact();
}
//
valueWillDestroy() {
this.value = null;
this.withPropertyChanges(changed => {
this.propertyDidChange(changed);
});
}
}
|
JavaScript
| 0 |
@@ -625,24 +625,90 @@
ore();%0A %7D%0A%0A
+ get notifyInternalModelDidSetDatabase() %7B%0A return true;%0A %7D%0A%0A
dirty() %7B%0A
|
936fe05c2811ba5c7e4773f8b05b3e80fd011240
|
Remove unnecessary default value
|
src/bin/cli/harmonic.js
|
src/bin/cli/harmonic.js
|
require('gulp-6to5/node_modules/6to5/polyfill');
var program = require('commander');
import { version } from '../config';
import { cliColor } from '../helpers';
import logo from './logo';
import { init, config, newFile, run } from './util';
program
.version(version);
program
.command('init [path]')
.description('Init your static website')
// [BUG] https://github.com/jshint/jshint/issues/1849 - can't use arrow function
.action(function(path = '.') {
console.log(logo);
init(path);
});
program
.command('config [path]')
.description('Config your static website')
// [BUG] https://github.com/jshint/jshint/issues/1849 - can't use arrow function
.action(function(path = '.') {
console.log(logo);
config(path);
});
program
.command('build [path]')
.description('Build your static website')
// [BUG] https://github.com/jshint/jshint/issues/1849 - can't use arrow function
.action(function(path = '.') {
let core = require('../core');
core.init(path);
});
program
.command('new_post <title> [path]')
.option('--no-open', 'Don\'t open the markdown file(s) in editor')
.description('Create a new post')
// [BUG] https://github.com/jshint/jshint/issues/1849 - can't use arrow function
.action(function(title, path = '.', options = {}) {
newFile(path, 'post', title, options.open);
});
program
.command('new_page <title> [path]')
.option('--no-open', 'Don\'t open the markdown file(s) in editor')
.description('Create a new page')
// [BUG] https://github.com/jshint/jshint/issues/1849 - can't use arrow function
.action(function(title, path = '.', options = {}) {
newFile(path, 'page', title, options.open);
});
program
.command('run [port] [path]')
.option('--no-open', 'Don\'t open a new browser window')
.description('Run you static site locally. Port is optional')
// [BUG] https://github.com/jshint/jshint/issues/1849 - can't use arrow function
.action(function(port = 9356, path = '.', options = {}) {
let core = require('../core'),
build = core.init(path);
if (build) {
build.then(function() {
run(path, port, options.open);
});
}
});
program.on('*', (args) => {
let clc = cliColor();
console.error('Unknown command: ' + clc.error(args[0]));
process.exit(1);
});
program.parse(process.argv);
// Not enough arguments
if (!program.args.length) {
console.log(logo);
program.help();
}
|
JavaScript
| 0 |
@@ -1316,59 +1316,167 @@
-.action(function(title, path = '.', options = %7B%7D) %7B
+// %5BBUG%5D https://github.com/jshint/jshint/issues/1779#issuecomment-68985429%0A .action(function(title, path = '.', %7B open: autoOpen %7D) %7B // jshint ignore:line
%0A
@@ -1505,33 +1505,29 @@
st', title,
-options.o
+autoO
pen);%0A %7D)
@@ -1779,59 +1779,167 @@
-.action(function(title, path = '.', options = %7B%7D) %7B
+// %5BBUG%5D https://github.com/jshint/jshint/issues/1779#issuecomment-68985429%0A .action(function(title, path = '.', %7B open: autoOpen %7D) %7B // jshint ignore:line
%0A
@@ -1972,25 +1972,21 @@
title,
-options.o
+autoO
pen);%0A
@@ -2239,32 +2239,113 @@
arrow function%0A
+ // %5BBUG%5D https://github.com/jshint/jshint/issues/1779#issuecomment-68985429%0A
.action(func
@@ -2378,23 +2378,51 @@
.',
-options = %7B%7D) %7B
+%7B open: autoOpen %7D) %7B // jshint ignore:line
%0A
@@ -2587,17 +2587,13 @@
rt,
-options.o
+autoO
pen)
|
2e47c61860c0035e9b0b15cc47e5e6496944baad
|
Create resuable list of file extensions the app is interested in.
|
lib/configuration/index.js
|
lib/configuration/index.js
|
/**
* Factory for singleton Config data object for the app.
*/
'use strict';
var path = require('path');
var assign = require('lodash.assign');
var folderNames = {
dataStorage: 'project-data',
derived: 'derived',
projects: 'projects'
};
// Cached instance of Config.
var configInstance;
function Config(configuration) {
this.projectRoute = '/project';
this.allowInsecureSSL = false;
assign(this, configuration);
this.rootPath = path.normalize(this.rootPath);
this.dataStoragePath = path.join(this.rootPath, folderNames.dataStorage);
this.derivedDataPath = path.join(this.dataStoragePath, folderNames.derived);
this.projectsPath = path.join(this.dataStoragePath, folderNames.projects);
this.regex = {};
// Define which file types the application willl process and display.
this.regex['fileOfInterest'] = /\.(feature|md)/;
}
/**
* Get the config instance.
*/
function get() {
if (configInstance instanceof Config) {
return configInstance;
}
throw new TypeError('Please set the root path for the app with the set method before asking for the configuration.');
}
/*
* Create and cache the config instance. Return instance for convenience.
*/
function set(configuration) {
if (configInstance instanceof Config) {
throw new TypeError('Please only call the set mothod once.');
}
if (!configuration.rootPath) {
throw new TypeError('Please supply the app root path to the config set method.');
}
configInstance = new Config(configuration);
return configInstance;
}
module.exports = {
get: get,
set: set
};
|
JavaScript
| 0 |
@@ -241,16 +241,116 @@
ts'%0A%7D;%0A%0A
+// List of filename extensions the app cares about.%0Avar filesOfInterest = %5B%0A 'feature',%0A 'md'%0A%5D;%0A%0A
// Cache
@@ -936,24 +936,61 @@
%5D =
-/%5C.(feature%7Cmd)/
+new RegExp('%5C%5C.(' + filesOfInterest.join('%7C') + ')$')
;%0A%7D%0A
|
e8e9e1ec303aff3b6a06dbb54310a16c1b452c00
|
Add ticksService to core
|
src/botPage/bot/Core.js
|
src/botPage/bot/Core.js
|
import { tradeOptionToProposal } from './tools'
export default class Core {
constructor($scope) {
this.api = $scope.api.originalApi
this.activeProposals = []
this.observe()
this.isPurchaseStarted = false
this.isSellAvailable = false
this.forSellContractId = 0
this.token = ''
this.observer = $scope.observer
this.context = {}
this.promises = {
before() {},
during() {},
}
}
start(token, tradeOption) {
if (this.token) {
return
}
this.isSellAvailable = false
const symbol = tradeOption.symbol
this.api.authorize(token).then(() => {
this.token = token
this.proposalTemplates = tradeOptionToProposal(tradeOption)
this.requestProposals()
this.api.subscribeToTick(symbol)
})
}
requestPurchase(contractType) {
this.isPurchaseStarted = true
const requestedProposalIndex = this.activeProposals.findIndex(p => p.contract_type === contractType)
const toBuy = this.activeProposals[requestedProposalIndex]
const toForget = this.activeProposals[requestedProposalIndex ? 0 : 1]
this.api.buyContract(toBuy.id, toBuy.ask_price).then(r => {
this.api.subscribeToOpenContract(r.buy.contract_id)
this.api.unsubscribeByID(toForget.id).then(() => this.requestProposals())
this.execContext('between-before-and-during')
})
}
sellAtMarket() {
if (!this.isSold && this.isSellAvailable) {
this.api.sellContract(this.forSellContractId, 0).then(() => {
this.isSellAvailable = false
})
.catch(() => this.sellAtMarket())
}
}
setReady() {
this.expectedProposalCount = (this.expectedProposalCount + 1) % 2
}
checkReady() {
return this.activeProposals.length && !this.expectedProposalCount
}
requestProposals() {
this.activeProposals = []
this.proposalTemplates.forEach(proposal => {
this.api.subscribeToPriceForContractProposal(proposal).then(r => {
this.activeProposals.push(Object.assign({ contract_type: proposal.contract_type }, r.proposal))
this.setReady()
})
})
}
observe() {
this.listen('proposal_open_contract', t => {
const contract = t.proposal_open_contract
const { is_expired: isExpired, is_valid_to_sell: isValidToSell } = contract
if (!this.isSold && isExpired && isValidToSell) {
this.api.sellExpiredContracts()
}
this.isSold = !!contract.is_sold
if (this.isSold) {
this.isPurchaseStarted = false
} else {
this.forSellContractId = contract.contract_id
}
this.isSellAvailable = !this.isSold && !contract.is_expired && !!contract.is_valid_to_sell
this.execContext(this.isSold ? 'after' : 'during', contract)
})
this.listen('proposal', r => {
const proposal = r.proposal
const activeProposalIndex = this.activeProposals.findIndex(p => p.id === proposal.id)
if (activeProposalIndex >= 0) {
this.activeProposals[activeProposalIndex] = proposal
this.setReady()
}
})
this.listen('tick', () => {
if (!this.isPurchaseStarted && this.checkReady()) {
this.execContext('before', this.activeProposals)
}
})
}
execContext(scope) {
switch (scope) {
case 'before':
this.promises.before(true)
break
case 'between-before-and-during':
this.promises.before(false)
break
case 'during':
this.promises.during(true)
break
case 'after':
this.promises.during(false)
break
default:
break
}
this.scope = scope
this.observer.emit('CONTINUE')
}
isInside(scope) {
return this.scope === scope
}
watch(scope) {
return new Promise(resolve => {
this.promises[scope] = resolve
})
}
listen(n, f) {
this.api.events.on(n, f)
}
}
|
JavaScript
| 0 |
@@ -154,32 +154,59 @@
eProposals = %5B%5D%0A
+ this.tickListener = %7B%7D%0A
this.observe
@@ -563,46 +563,8 @@
lse%0A
- const symbol = tradeOption.symbol%0A
@@ -738,42 +738,464 @@
his.
-api.subscribeToTick(symbol)%0A %7D)
+monitorTickEvent(tradeOption.symbol)%0A %7D)%0A %7D%0A monitorTickEvent(symbol) %7B%0A if (this.tickListener.symbol !== symbol) %7B%0A this.ticksService.stopMonitor(this.tickListener.symbol, this.tickListener.key)%0A%0A const key = this.ticksService.monitor(symbol, () =%3E %7B%0A if (!this.isPurchaseStarted && this.checkReady()) %7B%0A this.execContext('before', this.activeProposals)%0A %7D%0A %7D)%0A%0A this.tickListener = %7B key, symbol %7D%0A %7D
%0A %7D
@@ -1289,32 +1289,38 @@
dProposalIndex =
+%0A
this.activeProp
@@ -2396,16 +2396,27 @@
ls.push(
+%0A
Object.a
@@ -2710,24 +2710,25 @@
= contract%0A
+%0A
if (!t
@@ -3027,16 +3027,24 @@
ilable =
+%0A
!this.i
@@ -3281,16 +3281,24 @@
lIndex =
+%0A
this.ac
@@ -3344,24 +3344,25 @@
roposal.id)%0A
+%0A
if (ac
@@ -3490,171 +3490,8 @@
%7D)
-%0A%0A this.listen('tick', () =%3E %7B%0A if (!this.isPurchaseStarted && this.checkReady()) %7B%0A this.execContext('before', this.activeProposals)%0A %7D%0A %7D)
%0A %7D
|
f31569272a8eaa4aec7ea39de58c2daad020662c
|
fix container bug
|
gallery/gallery.js
|
gallery/gallery.js
|
var d3 = require('d3');
var _ = require('lodash');
var templateHTML = require('./gallery.jade');
var ImageViz = require('../viz/image');
var GalleryViz = function(selector, data, images, opts) {
this.$el = $(selector).first();
this.selector = selector;
this.currentImage = 0;
this.images = images || [];
this.$el.append(templateHTML({
images: this.images,
currentImage: this.currentImage
}));
var self = this;
this.$el.find('.gallery-thumbnail').click(function() {
console.log(self.$el.find('.gallery-thumbnail').index(this));
self.setImage(self.$el.find('.gallery-thumbnail').index(this));
});
this.imageViz = new ImageViz(selector + ' .image-container', [], [this.images[0]], {width: this.$el.width()});
};
module.exports = GalleryViz;
GalleryViz.prototype.addImage = function(imageData) {
// this.images.push(imageData);
// this.$el.find('input.image-slider').attr('max', this.images.length - 1);
// this.setImage(this.images.length - 1);
};
GalleryViz.prototype.setImage = function(index) {
this.$el.find('.image-container').html();
this.imageViz = new ImageViz(this.selector + ' .image-container', [], [this.images[index]], {width: this.$el.width()});
};
GalleryViz.prototype.updateData = function(data) {
// in this case data should just be an image
this.addImage(data);
};
|
JavaScript
| 0.000001 |
@@ -664,24 +664,25 @@
);%0A %7D);%0A%0A
+%0A
this.ima
@@ -776,24 +776,31 @@
.$el.width()
+ %7C%7C 400
%7D);%0A%0A%7D;%0A%0A%0Amo
@@ -1142,16 +1142,18 @@
').html(
+''
);%0A t
|
e964bef212c5655415f67435c3e1e76e9feb262e
|
Use full path for import
|
mac/resources/open_dctb.js
|
mac/resources/open_dctb.js
|
define(['./open_wctb'], function(open_wctb) {
return open_wctb;
});
|
JavaScript
| 0 |
@@ -6,9 +6,21 @@
e(%5B'
-.
+mac/resources
/ope
|
19d5c3c4bd20961aa63037eb00c093ac3b205094
|
fix request.js
|
src/utils/request.js
|
src/utils/request.js
|
import Ajax from 'robe-ajax'
export default function request (url, options) {
if (options.cross) {
return Ajax.getJSON('http://query.yahooapis.com/v1/public/yql', {
q: `select * from json where url='${url}?${Ajax.param(options.data)}'`,
format: 'json',
})
}
return Ajax.ajax({
url,
method: options.method || 'get',
data: options.data || {},
dataType: 'JSON',
}).done((data) => {
return data
})
}
|
JavaScript
| 0.000002 |
@@ -373,16 +373,59 @@
%7C%7C %7B%7D,%0A
+ processData: options.method === 'get',%0A
data
|
65db2e6ecd1cb2c732a78e48a5390ab9e6c5cf03
|
исправить BEMHTML.apply(undefined)
|
lib/bemhtml/api.js
|
lib/bemhtml/api.js
|
var ometajs = require('ometajs'),
xjst = require('xjst'),
vm = require('vm'),
bemhtml = require('../ometa/bemhtml'),
BEMHTMLParser = bemhtml.BEMHTMLParser,
BEMHTMLToXJST = bemhtml.BEMHTMLToXJST,
BEMHTMLLogLocal = bemhtml.BEMHTMLLogLocal;
var api = exports;
//
// ### function translate (source)
// #### @source {String} BEMHTML Source code
// #### @options {Object} Compilation options **optional**
// Returns source translated to javascript
//
api.translate = function translate(source, options) {
var tree = BEMHTMLParser.matchAll(source, 'topLevel'),
xjstPre = BEMHTMLToXJST.match(tree, 'topLevel'),
vars = [];
options || (options = {});
options.exportName || (options.exportName = 'BEMHTML');
if (options.cache === true) {
var xjstCached = BEMHTMLLogLocal.match(xjstPre, 'topLevel');
vars = xjstCached[0];
xjstPre = xjstCached[1];
}
var xjstTree = xjst.translate(xjstPre);
try {
var xjstJS = options.devMode ?
xjst.compile(xjstTree, '', { 'no-opt': true })
:
xjst.compile(xjstTree, { engine: 'sort-group' });
} catch (e) {
throw new Error("xjst to js compilation failed:\n" + e.stack);
}
var exportName = options.exportName,
xjst_apply = options.async ?
'return xjst.applyAsync.call(' + (options.raw ? 'this' : '[this]') + ', options.callback);\n' :
'return xjst.apply.call(' + (options.raw ? 'this' : '[this]') + ');\n';
return 'var ' + exportName + ' = function() {\n' +
' var cache,\n' +
' xjst = ' + xjstJS + ';\n' +
' return function(options) {\n' +
' if (!options) options = {};\n' +
' cache = options.cache;\n' +
(vars.length > 0 ? ' var ' + vars.join(', ') + ';\n' : '') +
' ' + xjst_apply +
' };\n' +
'}();\n' +
'typeof exports === "undefined" || (exports.' + exportName + ' = ' + exportName + ');';
};
//
// ### function compile (source)
// #### @source {String} BEMHTML Source code
// #### @options {Object} Compilation options **optional**
// Returns generator function
//
api.compile = function compile(source, options) {
var body = exports.translate(source, options),
context = { exports: {} };
if (options && options.devMode) context.console = console;
vm.runInNewContext(body, context);
return context.BEMHTML;
};
|
JavaScript
| 0.000127 |
@@ -1352,38 +1352,44 @@
ions.raw ? '
-this' : '%5Bthis
+context' : '%5Bcontext
%5D') + ', opt
@@ -1467,22 +1467,28 @@
? '
-this' : '%5Bthis
+context' : '%5Bcontext
%5D')
@@ -1660,32 +1660,71 @@
options) %7B%5Cn' +%0A
+ ' var context = this;%5Cn' +%0A
' if
@@ -1792,24 +1792,127 @@
cache;%5Cn' +%0A
+ ' return function() %7B%5Cn' +%0A ' if (context === this) context = undefined;%5Cn' +%0A
(va
@@ -1986,16 +1986,18 @@
'
+
' + xjst
@@ -2005,16 +2005,49 @@
apply +%0A
+ ' %7D.call(null);%5Cn' +%0A
|
7e8d266a03556a39e3580bc61759c38ca7c3d0f0
|
Set require_delivery to true
|
lib/Facebook.js
|
lib/Facebook.js
|
/** @module facebook */
const Botkit = require('botkit');
const Config = require('../config/Config.js');
const Logger = require('./Logger.js');
const controller = Botkit.facebookbot({
debug: Config.debug,
log: true,
access_token: Config.facebookPageAccessToken,
verify_token: Config.facebookVerifyToken,
app_secret: Config.facebookAppSecret,
api_host: Config.facebookApiHost,
validate_requests: true,
stats_optout: true,
});
// Create a messenger profile API so that your bot seems more human.
// https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api
/**
* Set greeting text for the bot.
* [Facebook docs on Greeting Text]{@link https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/greeting}
* @param {string} greeting - greeting text
*/
function setGreeting(greeting) {
controller.api.messenger_profile.greeting(greeting);
}
/**
* Set the payload for the get started button.
* [Facebook docs on a Get Started Button ]{@link https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/get-started-button}
* @param {string} getStartedPayload - payload string
* button is clicked
*/
function setGetStarted(getStartedPayload) {
controller.api.messenger_profile.get_started(getStartedPayload);
}
/**
* Set a facebook messenger persistent menu.
* [Facebook docs on a Persistent Menu]{@link https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/persistent-menu}
* @param {object} menu - menu object
*/
function setMenu(menu) {
controller.api.messenger_profile.menu(menu);
}
/**
* Get the messenger user's facebook profile
* @param {string} fbMessengerId facebook messenger ID
* @return {promise} facebook profile consisting:
* first_name, last_name, profile_pic, locale, timezone, gender
* is_payment_enabled, last_ad_referral
*/
function getFacebookProfile(fbMessengerId) {
return controller.api.user_profile(fbMessengerId);
}
/**
* Start an express webserver for the bot.
* @param {object} bot - A bot object created by botkit
* @param {function} cb - A callback function to define routes
* @example
const myBot = facebookBot.controller.spawn({});
facebookBot.start(myBot, (err, webserver) => {
webserver.get('/', (req, res) => {
res.send('<h3>This is a bot</h3>');
});
webserver.get('/other', (req, res) => {
res.send('<h3>This is a bot at route /other</h3>');
});
});
*/
function start(bot, cb) {
controller.setupWebserver(Config.PORT, (err, webserver) => {
if (Config.sentryDSN) {
webserver.use(Logger.sentry.requestHandler());
}
cb(err, webserver);
controller.createWebhookEndpoints(webserver, bot, () => {
Logger.log('info', 'Your borq bot is online');
});
if (Config.sentryDSN) {
webserver.use(Logger.sentry.errorHandler());
}
});
controller.startTicking();
}
module.exports = {
controller,
setGetStarted,
getFacebookProfile,
setGreeting,
setMenu,
start,
};
|
JavaScript
| 0 |
@@ -185,104 +185,128 @@
%7B%0A
-debug: Config.debug,%0A log: true,%0A access_token: Config.facebookPageAccessToken
+log: true,%0A stats_optout: true,%0A debug: Config.debug,%0A require_delivery: true,%0A validate_requests: true
,%0A
+%0A
-verify_token
+api_host
: Co
@@ -322,19 +322,15 @@
book
-VerifyToken
+ApiHost
,%0A
@@ -369,24 +369,28 @@
cret,%0A
-api_host
+verify_token
: Config
@@ -402,64 +402,67 @@
book
-ApiHost,%0A validate_requests: true,%0A stats_optout: true
+VerifyToken,%0A access_token: Config.facebookPageAccessToken
,%0A%7D)
|
f4e839cf2596b03a4db9de90de62d024d3d37312
|
Replace fa with fna in match
|
lib/bionode-sam.js
|
lib/bionode-sam.js
|
var path = require('path')
var spawn = require('child_process').spawn
var through = require('through2')
fs = require('fs')
module.exports = exports = SAM
function SAM(command) {
var command = command || 'mem'
return samStream
function samStream(srcDest, callback) {
var stream = through.obj(transform)
if (srcDest) { stream.write(srcDest); stream.end() }
if (callback) {
stream.on('data', function(data) {
callback(null, data)
})
stream.on('error', callback)
}
return stream
function transform(obj, enc, next) {
var self = this
var multi = false
if (typeof obj === 'string') { obj = obj.split(' ') }
var samPath = path.join(__dirname, '../sam/samtools/samtools')
var bcfPath = path.join(__dirname, '../sam/bcftools/bcftools')
var vcfPath = path.join(__dirname, '../sam/bcftools/vcfutils.pl')
var Arg1Ext = obj[0] ? obj[0].replace(/.*\./, '') : null
var Arg2Ext = obj[1] ? obj[1].replace(/.*\./, '') : null
var Arg3Ext = obj[2] ? obj[2].replace(/.*\./, '') : null
if (Arg1Ext === 'sam') {
// sam to bam conversion
// samtools view -bS -o aln.bam aln.sam
obj[1] = obj[1] || obj[0].replace('.sam', '.bam')
multi = true
var samToBam = spawn(samPath, [ 'view', '-bS', '-o', obj[1].replace('.bam', '.unsorted.bam'), obj[0] ])
samToBam.stderr.on('data', function(data) { console.log(data.toString()) })
var sortBam
var indexBam
samToBam.on('close', function(code) {
if (code) { self.emit('error', new Error('Unknown error, check that "'+obj[0]+'" exists')) }
else {
sortBam = spawn(samPath, [ 'sort', obj[1].replace('.bam', '.unsorted.bam'), obj[1].replace('.bam', '') ])
sortBam.on('close', function(code) {
if (code) { self.emit('error', new Error('Unknown error, check that "'+obj[0]+'" exists')) }
else {
indexBam = spawn(samPath, [ 'index', obj[1] ])
indexBam.on('close', function(code) {
if (code) { self.emit('error', new Error('Unknown error, check that "'+obj[0]+'" exists')) }
else {
var output = {
sam: obj[0],
bam: obj[1],
operation: "sam -> bam"
}
self.push(output)
next()
}
})
}
})
}
})
}
else if (obj[0].indexOf('.fa') !== -1 && Arg2Ext === 'sam' && Arg3Ext === 'bam') {
// Broken, FIX
// sam to bam conversion with reference
// samtools faidx ref.fa
// samtools view -bt ref.fa.fai -o aln.bam aln.sam
// console.log('sam -> bam')
// multi = true
// var samToBam = spawn(samPath, [ 'view', '-bt', obj[0], '-o', obj[2], obj[1] ])
// samToBam.stderr.on('data', function(data) { console.log(data.toString()) })
// var sortBam
// var indexBam
// sam.on('close', function(code) {
// if (code) { self.emit('error', new Error('Unknown error, check that "'+obj[0]+'" exists')) }
// else {
// sortBam = spawn(samPath, [ 'view', '-bt', obj[0], '-o', obj[2], obj[1] ])
// }
// })
}
else if (Arg1Ext === 'bam' && Arg2Ext === 'sam') {
// bam to sam conversion
// samtools view -h -o out.sam in.bam
console.log('bam -> sam')
var sam = spawn(samPath, [ 'view', '-h', '-o', obj[1], obj[0] ])
}
// else if (Arg1Ext === 'bcf' && Arg2Ext === 'fq') {
// // bcf to fq conversion
// // samtools view -h -o out.sam in.bam
// console.log('bam -> sam')
// var sam = spawn(samPath, [ 'view', '-h', '-o', obj[1], obj[0] ])
//
// }
else if (obj[0].indexOf('.fa') !== -1 && Arg2Ext === 'bam' && Arg3Ext === 'bcf') {
// bam to bcf conversion with reference
// samtools mpileup -C50 -uf ref.fa aln.bam > aln.bcf
console.log('bam -> bcf')
var sam = spawn(samPath, [ 'mpileup', '-C50', '-uf', obj[0], obj[1] ])
var samOut = fs.createWriteStream(obj[2])
sam.stdout.on('data', function(data) { samOut.write(data) })
}
else if (Arg1Ext === 'bcf' && obj[1].indexOf('.consensus.fq') !== -1) {
console.log('bcf -> Confq')
multi = true
var bcf = spawn(bcfPath, [ 'view', '-c', obj[0] ])
var vcf2fq = spawn(vcfPath, [ 'vcf2fq', '-d', '5', '-D', '100' ])
var fqOut = fs.createWriteStream(obj[1])
bcf.stdout.pipe(vcf2fq.stdin)
bcf.stderr.pipe(process.stdout)
vcf2fq.stderr.pipe(process.stdout)
vcf2fq.stdout.pipe(fqOut)
// sam.stdout.on('data', function(data) { samOut.write(data) })
vcf2fq.on('close', next)
}
// var options
//
// options = [cmd, ref]
// if (reads) { options.push(reads) }
// console.log(options)
// var sam = spawn(bwaPath, options)
// if (sam) {
// var samOut = fs.createWriteStream(sam)
// sam.stdout.on('data', function(data) {
// // if (typeof)
// // console.log(data)
// samOut.write(data)
// })
// }
//
if (multi === false) {
sam.stderr.on('data', function(data) {
console.log(data.toString())
// self.emit('error', new Error(data.toString()))
// next()
})
sam.on('close', function(code) {
if (code) {
self.emit('error', new Error('Unknown error, check that "'+obj[0]+'" exists'))
}
else {
// self.push([obj[0], destination])
self.push(code)
next()
}
})
}
}
}
}
|
JavaScript
| 0.999912 |
@@ -3944,32 +3944,33 @@
j%5B0%5D.indexOf('.f
+n
a') !== -1 && Ar
|
75f281743c1f6d40584f88ce871077d966be558e
|
support deprecated appComponent, add warning message
|
lib/Fluxible.js
|
lib/Fluxible.js
|
/**
* Copyright 2014, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
'use strict';
var debug = require('debug')('Fluxible');
var async = require('async');
var FluxibleContext = require('./FluxibleContext');
var dispatcherClassFactory = require('dispatchr');
/**
* Provides a structured way of registering an application's configuration and
* resources.
* @class Fluxible
* @param {Object} [options]
* @param {Object} [options.component] The root application component
* @param {String} [options.pathPrefix] The path used for application calls
* @constructor
*
* @example
* var app = new Fluxible({
* component: require('./components/App.jsx'),
* plugins: [
* require('./plugins/Foo')
* ]
* });
*/
function Fluxible(options) {
debug('Fluxible instance instantiated', options);
options = options || {};
// Options
this._component = options.component;
this._plugins = [];
// Initialize dependencies
this._dispatcherClass = dispatcherClassFactory();
}
/**
* Creates an isolated context for a request/session
* @method createContext
* @param {Object} [options]
* @returns {FluxibleContext}
*/
Fluxible.prototype.createContext = function createContext(options) {
var self = this;
options = options || {};
options.app = self;
var context = new FluxibleContext(options);
// Plug context with app plugins that implement plugContext method
this._plugins.forEach(function eachPlugin(plugin) {
if (plugin.plugContext) {
var contextPlugin = plugin.plugContext(options, context, self);
contextPlugin.name = contextPlugin.name || plugin.name;
context.plug(contextPlugin);
}
});
return context;
};
/**
* Creates a new dispatcher instance using the application's dispatchr class. Used by
* FluxibleContext to create new dispatcher instance
* @method createDispatcherInstance
* @param {Object} context The context object to be provided to each store instance
* @returns {Dispatcher}
*/
Fluxible.prototype.createDispatcherInstance = function createDispatcherInstance(context) {
return new (this._dispatcherClass)(context);
};
/**
* Provides plugin mechanism for adding application level settings that are persisted
* between server/client and also modification of the FluxibleContext
* @method plug
* @param {Object} plugin
* @param {String} plugin.name Name of the plugin
* @param {Function} plugin.plugContext Method called after context is created to allow
* dynamically plugging the context
* @param {Object} [plugin.dehydrate] Method called to serialize the plugin settings to be persisted
* to the client
* @param {Object} [plugin.rehydrate] Method called to rehydrate the plugin settings from the server
*/
Fluxible.prototype.plug = function (plugin) {
if (!plugin.name) {
throw new Error('Application plugin must have a name');
}
this._plugins.push(plugin);
};
/**
* Provides access to a plugin instance by name
* @method getPlugin
* @param {String} pluginName The plugin name
* @returns {Object}
*/
Fluxible.prototype.getPlugin = function (pluginName) {
var plugin = null;
this._plugins.forEach(function (p) {
if (pluginName === p.name) {
plugin = p;
}
});
return plugin;
};
/**
* Getter for the top level react component for the application
* @method getComponent
* @returns {Object}
*/
Fluxible.prototype.getComponent = function getComponent() {
return this._component;
};
/**
* Registers a store to the dispatcher so it can listen for actions
* @method registerStore
*/
Fluxible.prototype.registerStore = function registerStore() {
debug(arguments[0].storeName + ' store registered');
this._dispatcherClass.registerStore.apply(this._dispatcherClass, arguments);
};
/**
* Creates a serializable state of the application and a given context for sending to the client
* @method dehydrate
* @param {FluxibleContext} context
* @returns {Object} Dehydrated state object
*/
Fluxible.prototype.dehydrate = function dehydrate(context) {
debug('dehydrate', context);
var self = this;
var state = {
context: context.dehydrate(),
plugins: {}
};
this._plugins.forEach(function (plugin) {
if ('function' === typeof plugin.dehydrate) {
// Use a namespace for storing plugin state and provide access to the application
state.plugins[plugin.name] = plugin.dehydrate(self);
}
});
return state;
};
/**
* Rehydrates the application and creates a new context with the state from the server
* @method rehydrate
* @param {Object} obj Raw object of dehydrated state
* @param {Object} obj.plugins Dehydrated app plugin state
* @param {Object} obj.context Dehydrated context state
* @param {Function} callback
* @async Rehydration may require more asset loading or async IO calls
*/
Fluxible.prototype.rehydrate = function rehydrate(obj, callback) {
debug('rehydrate', obj);
var self = this;
obj.plugins = obj.plugins || {};
var pluginTasks = this._plugins.filter(function (plugin) {
return 'function' === typeof plugin.rehydrate;
}).map(function (plugin) {
return function (asyncCallback) {
if (2 === plugin.rehydrate.length) { // Async plugin
plugin.rehydrate(obj.plugins[plugin.name], asyncCallback);
} else { // Sync plugin
try {
plugin.rehydrate(obj.plugins[plugin.name]);
} catch (e) {
asyncCallback(e);
return;
}
asyncCallback();
}
};
});
async.parallel(pluginTasks, function rehydratePluginTasks(err) {
if (err) {
callback(err);
return;
}
var context = self.createContext();
context.rehydrate(obj.context);
callback(null, context);
});
};
module.exports = Fluxible;
|
JavaScript
| 0 |
@@ -459,24 +459,79 @@
%7D %5Boptions%5D%0A
+ * @param %7BObject%7D %5Boptions.appComponent%5D (DEPRECATED)%0A
* @param %7BO
@@ -1045,16 +1045,40 @@
omponent
+ %7C%7C options.appComponent
;%0A th
@@ -1096,16 +1096,181 @@
= %5B%5D;%0A%0A
+ if (options.appComponent) %7B%0A console.warn(%22*** %60appComponent%60 is deprecated. %22 + %0A %22Please update your code to use %60component%60 ***%5Cn%22);%0A %7D%0A%0A
// I
@@ -3858,24 +3858,255 @@
ponent;%0A%7D;%0A%0A
+/**%0A * (DEPRECATED)%0A * Getter for the top level react component for the application%0A * @method getComponent%0A * @returns %7BObject%7D%0A */%0AFluxible.prototype.getAppComponent = function getAppComponent() %7B%0A return this._component;%0A%7D;%0A%0A
/**%0A * Regis
|
c76d5dc8187f34d6938640a4b2f8ef9ee17cefe3
|
update lib
|
lib/RcSelect.js
|
lib/RcSelect.js
|
/**
* Created by steve on 15/09/15.
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactSchemaFormLibComposedComponent = require('react-schema-form/lib/ComposedComponent');
var _reactSchemaFormLibComposedComponent2 = _interopRequireDefault(_reactSchemaFormLibComposedComponent);
var _rcSelect = require('rc-select');
var _rcSelect2 = _interopRequireDefault(_rcSelect);
var _jquery = require('jquery');
var _jquery2 = _interopRequireDefault(_jquery);
var RcSelect = (function (_React$Component) {
_inherits(RcSelect, _React$Component);
function RcSelect(props) {
_classCallCheck(this, RcSelect);
_get(Object.getPrototypeOf(RcSelect.prototype), 'constructor', this).call(this, props);
this.onSelect = this.onSelect.bind(this);
this.onDeselect = this.onDeselect.bind(this);
this.state = {
currentValue: [],
items: this.props.form.items
};
}
_createClass(RcSelect, [{
key: 'componentWillMount',
value: function componentWillMount() {
// load items if needed.
if (this.props.form.action) {
if (this.props.form.action.get) {
_jquery2['default'].ajax({
type: 'GET',
url: this.props.form.action.get.url
}).done((function (data) {
this.setState({ items: data });
}).bind(this)).fail(function (error) {
console.error('error', error);
});
} else if (this.props.form.action.post) {
_jquery2['default'].ajax({
type: 'POST',
url: this.props.form.action.post.url,
data: JSON.stringify(this.props.form.action.post.parameter),
contentType: 'application/json',
dataType: 'json'
}).done((function (data) {
this.setState({ items: data });
}).bind(this)).fail(function (error) {
console.error('error', error);
});
}
}
}
}, {
key: 'onSelect',
value: function onSelect(value, option) {
//console.log('RcSelect onSelect is called', value, option);
if (this.props.form.schema.type === 'array') {
// multiple select type array
var v = this.state.currentValue;
v.push(value);
this.setState({
currentValue: v
});
this.props.onChangeValidate(v);
} else {
// single select type string fake an event here.
this.setState({ currentValue: value });
this.props.onChangeValidate({ target: { value: value } });
}
}
}, {
key: 'onDeselect',
value: function onDeselect(value, option) {
//console.log('RcSelect onDeselect is called', value, option);
if (this.props.form.schema.type === 'array') {
var v = this.state.currentValue;
var index = v.indexOf(value);
if (index > -1) {
v.splice(index, 1);
}
this.setState({
currentValue: v
});
this.props.onChangeValidate(v);
}
}
}, {
key: 'render',
value: function render() {
//console.log("render", this.props, this.state);
var options = [];
if (this.state.items && this.state.items.length > 0) {
options = this.state.items.map(function (item, idx) {
return _react2['default'].createElement(
_rcSelect.Option,
{ key: idx, value: item.value },
item.label
);
});
}
var error = '';
if (this.props.error) {
error = _react2['default'].createElement(
'div',
{ style: { color: 'red' } },
this.props.error
);
}
return _react2['default'].createElement(
'div',
null,
_react2['default'].createElement(
'div',
null,
this.props.form.title
),
_react2['default'].createElement(
_rcSelect2['default'],
{
className: this.props.form.className,
dropdownClassName: this.props.form.dropdownClassName,
dropdownStyle: this.props.form.dropdownStyle,
dropdownMenuStyle: this.props.form.dropdownMenuStyle,
allowClear: this.props.form.allowClear,
tags: this.props.form.tags,
maxTagTextLength: this.props.form.maxTagTextLength,
multiple: this.props.form.multiple,
combobox: this.props.form.combobox,
disabled: this.props.form.disabled,
value: this.state.currentValue,
onSelect: this.onSelect,
onDeselect: this.onDeselect,
style: this.props.form.style || { width: "100%" } },
options
),
error
);
}
}]);
return RcSelect;
})(_react2['default'].Component);
exports['default'] = (0, _reactSchemaFormLibComposedComponent2['default'])(RcSelect);
module.exports = exports['default'];
|
JavaScript
| 0.000001 |
@@ -2964,18 +2964,32 @@
tValue:
-%5B%5D
+this.props.value
,%0A
|
60e8c09f7b23553d211ffb9b4e295dc23b3dc7bd
|
Update if ext up to changes in dom-ext
|
if.js
|
if.js
|
'use strict';
var d = require('es5-ext/lib/Object/descriptor')
, isFunction = require('es5-ext/lib/Function/is-function')
, isMutable = require('mutable/is')
, normalize = require('dom-ext/lib/Document/prototype/normalize')
, removeNode = require('dom-ext/lib/Node/prototype/remove')
, isNode = require('dom-ext/lib/Node/is-node')
, defineProperty = Object.defineProperty
, DOM, Attr;
DOM = function (document, value, onTrue, onFalse) {
var df = document.createDocumentFragment(), current;
this.document = document;
if (!isMutable(value)) {
this.normalize(value ? onTrue : onFalse).forEach(df.appendChild, df);
return df;
}
this.dom = document.createTextNode("");
this.onTrue = onTrue;
if (isNode(onTrue)) removeNode.call(onTrue);
this.onFalse = onFalse;
if (isNode(onFalse)) removeNode.call(onFalse);
value.on('change', function (value) {
var nu, old, container;
value = Boolean(value);
if (value === current) return;
old = value ? this.false : this.true;
nu = value ? this.true : this.false;
old.forEach(function (el) { removeNode.call(el); });
container = this.dom.parentNode;
current = value;
if (!container) return;
nu.forEach(function (el) { container.insertBefore(el, this.dom); }, this);
}.bind(this));
current = Boolean(value.value);
this[current ? 'true' : 'false'].forEach(df.appendChild, df);
df.appendChild(this.dom);
return df;
};
Object.defineProperties(DOM.prototype, {
resolve: d(function (value) {
return normalize.call(this.document, isFunction(value) ? value() : value);
}),
true: d.gs(function () {
defineProperty(this, 'true', d(this.resolve(this.onTrue)));
delete this.onTrue;
return this.true;
}),
false: d.gs(function () {
defineProperty(this, 'false', d(this.resolve(this.onFalse)));
delete this.onFalse;
return this.false;
})
});
Attr = function (document, name, value, onTrue, onFalse) {
var attr = document.createAttribute(name), current;
if (!isMutable(value)) {
attr.value = this.normalize(value ? onTrue : onFalse);
return attr;
}
this.onTrue = onTrue;
this.onFalse = onFalse;
value.on('change', function (value) {
var attrValue;
value = Boolean(value);
if (value === current) return;
attrValue = value ? this.true : this.false;
if ((attrValue != null) && attr.ownerElement) {
attr.ownerElement.setAttribute(attr.name, attrValue);
} else {
attr.value = attrValue;
}
current = value;
}.bind(this));
current = Boolean(value.value);
attr.value = this[current ? 'true' : 'false'];
return attr;
};
Object.defineProperties(Attr.prototype, {
resolve: d(function (value) {
if (isFunction(value)) value = value();
return (value == null) ? null : String(value);
}),
true: d.gs(function () {
defineProperty(this, 'true', d(this.resolve(this.onTrue)));
delete this.onTrue;
return this.true;
}),
false: d.gs(function () {
defineProperty(this, 'false', d(this.resolve(this.onFalse)));
delete this.onFalse;
return this.false;
})
});
module.exports = function (domjs) {
return function (value, onTrue, onFalse) {
var initialized;
return {
toDOM: function (document) {
if (initialized) throw new Error("Cannot convert to DOM twice");
initialized = true;
return new DOM(document, value, onTrue, onFalse);
},
toDOMAttr: function (document, name) {
if (initialized) throw new Error("Cannot convert to DOM twice");
initialized = true;
return new Attr(document, name, value, onTrue, onFalse);
}
};
};
};
|
JavaScript
| 0 |
@@ -1852,36 +1852,35 @@
ttr = function (
-docu
+ele
ment, name, valu
@@ -1910,54 +1910,26 @@
var
-attr = document.createAttribute(name), current
+current, attrValue
;%0A%09i
@@ -1954,26 +1954,25 @@
e)) %7B%0A%09%09attr
-.v
+V
alue = this.
@@ -2008,16 +2008,118 @@
False);%0A
+%09%09if (attrValue == null) element.removeAttribute(name);%0A%09%09else element.setAttribute(name, attrValue);%0A
%09%09return
@@ -2123,16 +2123,21 @@
urn attr
+Value
;%0A%09%7D%0A%09th
@@ -2347,17 +2347,16 @@
e;%0A%09%09if
-(
(attrVal
@@ -2362,17 +2362,17 @@
lue
-!
+=
= null)
&& a
@@ -2371,115 +2371,72 @@
ll)
-&& attr.ownerElement) %7B%0A%09%09%09attr.ownerElement.setAttribute(attr.name, attrValu
+element.removeAttribute(nam
e);%0A%09%09
-%7D
else
-%7B%0A%09%09%09attr.value =
+element.setAttribute(name,
att
@@ -2445,13 +2445,10 @@
alue
+)
;
-%0A%09%09%7D
%0A%09%09c
@@ -2517,18 +2517,17 @@
);%0A%09attr
-.v
+V
alue = t
@@ -2560,27 +2560,128 @@
lse'%5D;%0A%09
-return attr
+if (attrValue == null) element.removeAttribute(name);%0A%09else element.setAttribute(name, attrValue);%0A%09return value
;%0A%7D;%0AObj
@@ -3440,28 +3440,27 @@
: function (
-docu
+ele
ment, name)
@@ -3574,20 +3574,19 @@
ew Attr(
-docu
+ele
ment, na
|
561006ee5cef57268e08534981e406d579b8082b
|
Fix path backtracing on non-Windows systems
|
build/incrementBuild.js
|
build/incrementBuild.js
|
const fs = require("fs");
const path = require("path");
let thePath = path.format({
dir:__dirname + "\\..\\src",
base:"buildId.js"
});
let buildFile = fs.readFileSync(thePath) + "";
let ver = parseInt(buildFile.match(/\d+/g)[0]);
ver++;
fs.writeFileSync(thePath,"export default " + ver++ + ";")
|
JavaScript
| 0 |
@@ -99,15 +99,38 @@
e +
-%22%5C%5C..%5C%5C
+path.sep + %22..%22 + path.sep + %22
src%22
|
0d692f83a4bdcdd1c58d18f13b3095c209b7b5de
|
修改在非src 的目录里面 有require html的时候 出错
|
build/webpack.config.js
|
build/webpack.config.js
|
var path = require('path');
var webpack = require('webpack');
var merge = require('webpack-merge');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var ngAnnotatePlugin = require('ng-annotate-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var config = require('../config/build.config.js');
var webpackConfig;
var devtool;
var hash = chunkhash = contenthash = '';
// 公共類庫文件
var vendorFiles = [
'./dep/angular/angular.js',
'./dep/angular/angular-sanitize.js',
'./dep/angular/angular-resource.js',
'./dep/angular/angular-animate.js',
'./dep/angular/ui-bootstrap-tpls.js',
'./dep/angular/angular-locale_zh-cn.js',
'./dep/angular/angular-ui-router.js',
'./dep/bindonce.js',
'./dep/security.js',
'./dep/ng-lazy-image/lazy-image.js',
'./src/asset/css/index.js'
];
if (config.echarts.enabled) {
vendorFiles.push('echarts');
vendorFiles.push('zrender');
}
// 获取执行环境
var env = (process.env.NODE_ENV || '').trim();
if (env === 'dev') {
webpackConfig = require('./webpack-dev.js');
config = config.dev;
devtool = config.debug ? '#cheap-module-eval-source-map' : false;
} else if (env === 'production') {
webpackConfig = require('./webpack-production.js');
config = config.production;
devtool = config.debug ? '#source-map' : false;
hash = '[hash:8].';
chunkhash = '[chunkhash:8].';
contenthash = '[contenthash:8].';
}
// multiple extract instances
var extractCSS = new ExtractTextPlugin('css/[name].' + contenthash + 'css');
var extractLESS = new ExtractTextPlugin('css/less.[name].' + contenthash + 'css');
var extractSASS = new ExtractTextPlugin('css/sass.[name].' + contenthash + 'css');
console.log(__dirname);
module.exports = merge({
/**
* 源文件入口文件
* 这里的文件在使用html-webpack-plugin的时候会
* 自动将这些资源插入到html中
*/
entry: {
// 公共文件
vendor: vendorFiles,
entry: './src/main.js'
},
// 构建之后的文件目录配置
output: {
path: path.join(__dirname, '../dist'),
publicPath: config.assetsPublicPath, // html 中引用资源的位置
filename: 'js/[name].' + chunkhash + 'js',
chunkFilename: 'js/[name].' + chunkhash + 'js'
},
// webpack 开始执行之前的处理
resolve: {
// 配置别名
alias: {
'address': path.join(__dirname, '../config/address.config'),
'app': path.join(__dirname, '../src/app'),
'component': path.join(__dirname, '../src/component'),
'page': path.join(__dirname, '../src/page'),
'css': path.join(__dirname, '../src/asset/css'),
'controller': path.join(__dirname, '../src/controller')
},
fallback: [path.join(__dirname, './node_modules')],
// 配置哪些文件不需要后缀自动识别
extensions: ['', '.js', '.css']
},
//
module: {
loaders: [
// 处理angularjs 模版片段
{
test: /\.html$/,
loader: 'ngtemplate?module=ng&relativeTo='+(path.resolve(__dirname, '../'))+'!html?attrs=img:src img:img-error div:img-error li:img-error span:img-error a:img-error',
include: /(src|dep)/
},
// 配置css的抽取器、加载器。'-loader'可以省去
// 这里使用自动添加CSS3 浏览器前缀
{
test: /\.css$/i,
loader: extractCSS.extract('style-loader', 'css!postcss')
},
{
test: /\.less$/i,
loader: extractLESS.extract(['css', 'less!postcss'])
},
{
test: /\.scss$/i,
loader: extractSASS.extract(['css', 'sass!postcss'])
},
// 处理html图片
{
test: /\.(gif|jpe?g|png|woff|svg|eot|ttf)\??.*$/,
loader: 'file-loader?name=img/[name].' + hash + '[ext]'
}
]
},
postcss: function () {
return [
require('postcss-sprites')({
stylesheetPath: './src/css',
spritePath: './dist/img/sprite',
filterBy: function (image) {
//添加雪碧图规则 只有在sprite文件夹下的图片进行合并
if (!/\/sprite\//.test(image.url)) {
// console.log(image.url);
return Promise.reject();
}
return Promise.resolve();
},
groupBy: function (image) {
//添加雪碧图规则 在sprite下,如果包含文件夹则单独进行合并
var regex = /\/sprite\/([^/]+)\//g;
var m = regex.exec(image.url);
if (!m) {
return Promise.reject();
}
return Promise.resolve(m[1]); // 'sprite.' + icon + '.png'
},
spritesmith: {
padding: 20
}
}),
require('autoprefixer')({
browsers: ["last 6 version"]
})
];
},
// sourceMap
devtool: devtool,
// 插件
plugins: [
// 单独使用link标签加载css并设置路径,
// 相对于output配置中的publickPath
extractCSS,
extractLESS,
extractSASS,
new CopyWebpackPlugin([{
from: './dep/ie8support/ie8supports.js',
to: './dep'
}, {
from: './src/mock',
to: './mock'
}, {
from: './src/asset/img/system',
to: './img/system'
}, {
from: './src/component/ueditor',
to: './js'
}]),
// new HtmlWebpackPlugin(),
new HtmlWebpackPlugin({
// 生成title
title: 'webpack App',
favicon: './src/asset/img/system/favicon.ico',
assetsPublicPath: config.assetsPublicPath,
// 输出的文件名称 默认index.html 可以带有子目录
// filename: './dist/index.html',
filename: 'index.html',
// 源文件
// template: './src/index.ejs',
template: 'index.html',
// 注入资源
inject: true,
minify: {
// 合并多个空格
collapseWhitespace: true,
// 删除注释
removeComments: true,
// 删除冗余属性
removeRedundantAttributes: true
}
}),
new ngAnnotatePlugin({
add: true
})
]
}, webpackConfig);
|
JavaScript
| 0 |
@@ -1767,33 +1767,8 @@
);%0A%0A
-console.log(__dirname);%0A%0A
%0Amod
|
68f87435def2020fdc7c900f151d541fe34c9ba7
|
throw error if image is inaccessible (#1281)
|
lib/cli/options.js
|
lib/cli/options.js
|
/*
* Copyright 2016 resin.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const _ = require('lodash');
const fs = require('fs');
const yargs = require('yargs');
const utils = require('./utils');
const robot = require('../shared/robot');
const EXIT_CODES = require('../shared/exit-codes');
const errors = require('../shared/errors');
const packageJSON = require('../../package.json');
/**
* @summary The minimum required number of CLI arguments
* @constant
* @private
* @type {Number}
*/
const MINIMUM_NUMBER_OF_ARGUMENTS = 1;
/**
* @summary The index of the image argument
* @constant
* @private
* @type {Number}
*/
const IMAGE_PATH_ARGV_INDEX = 0;
/**
* @summary The first index that represents an actual option argument
* @constant
* @private
* @type {Number}
*
* @description
* The first arguments are usually the program executable itself, etc.
*/
const OPTIONS_INDEX_START = 2;
/**
* @summary Parsed CLI options and arguments
* @type {Object}
* @public
*/
module.exports = yargs
// Don't wrap at all
.wrap(null)
.demand(MINIMUM_NUMBER_OF_ARGUMENTS, 'Missing image')
// Usage help
.usage('Usage: $0 [options] <image>')
.epilogue([
'Exit codes:',
_.map(EXIT_CODES, (value, key) => {
const reason = _.map(_.split(key, '_'), _.capitalize).join(' ');
return ` ${value} - ${reason}`;
}).join('\n'),
'',
'If you need help, don\'t hesitate in contacting us at:',
'',
' GitHub: https://github.com/resin-io/etcher/issues/new',
' Gitter: https://gitter.im/resin-io/etcher'
].join('\n'))
// Examples
.example('$0 raspberry-pi.img')
.example('$0 --no-check raspberry-pi.img')
.example('$0 -d /dev/disk2 ubuntu.iso')
.example('$0 -d /dev/disk2 -y rpi.img')
// Help option
.help()
// Version option
.version(_.constant(packageJSON.version))
// Error reporting
.fail((message, error) => {
const errorObject = error || errors.createUserError(message);
if (robot.isEnabled(process.env)) {
robot.printError(errorObject);
} else {
yargs.showHelp();
utils.printError(errorObject);
}
process.exit(EXIT_CODES.GENERAL_ERROR);
})
// Assert that image exists
.check((argv) => {
fs.accessSync(argv._[IMAGE_PATH_ARGV_INDEX]);
return true;
})
.check((argv) => {
if (robot.isEnabled(process.env) && !argv.drive) {
throw errors.createUserError(
'Missing drive',
'You need to explicitly pass a drive when enabling robot mode'
);
}
return true;
})
.options({
help: {
describe: 'show help',
boolean: true,
alias: 'h'
},
version: {
describe: 'show version number',
boolean: true,
alias: 'v'
},
drive: {
describe: 'drive',
string: true,
alias: 'd'
},
check: {
describe: 'validate write',
boolean: true,
alias: 'c',
default: true
},
yes: {
describe: 'confirm non-interactively',
boolean: true,
alias: 'y'
},
unmount: {
describe: 'unmount on success',
boolean: true,
alias: 'u',
default: true
}
})
.parse(process.argv.slice(OPTIONS_INDEX_START));
|
JavaScript
| 0.999998 |
@@ -2754,22 +2754,26 @@
-fs.accessSync(
+const imagePath =
argv
@@ -2797,18 +2797,194 @@
V_INDEX%5D
-)
;
+%0A%0A try %7B%0A fs.accessSync(imagePath);%0A %7D catch (error) %7B%0A throw errors.createUserError('Unable to access file', %60The image $%7BimagePath%7D is not accessible%60);%0A %7D%0A
%0A ret
|
a3c75fd5f03e68b0fa5175cfecf824d0c6950388
|
add SkinDb.bson_serializer SkinDb.ObjectID
|
lib/mongoskin/db.js
|
lib/mongoskin/db.js
|
var __slice = Array.prototype.slice,
mongodb = require('mongodb'),
events = require('events'),
SkinAdmin = require('./admin').SkinAdmin,
SkinCollection = require('./collection').SkinCollection,
SkinGridStore = require('./gridfs').SkinGridStore,
Db = mongodb.Db,
Server = mongodb.Server,
STATE_CLOSE = 0,
STATE_OPENNING = 1,
STATE_OPEN = 2;
var _extend = function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
};
/**
* Construct SkinServer with native Server
*
* @param server
*/
var SkinServer = exports.SkinServer = function(server) {
this.server = server;
this._cache_ = [];
};
/**
* Create SkinDb from a SkinServer
*
* @param name database name
*
* @return SkinDb
*
* TODO add options
*/
SkinServer.prototype.db = function(name, username, password) {
var key = (username || '') + '@' + name;
var skinDb = this._cache_[key];
if (!skinDb || skinDb.fail) {
var db = new Db(name, this.server, {native_parser: !!mongodb.BSONNative});
skinDb = new SkinDb(db, username, password);
this._cache_[key] = skinDb;
}
return skinDb;
};
var SkinDb = exports.SkinDb = function(db, username, password) {
this.db = db;
this.username = username;
this.password = password;
this.state = STATE_CLOSE;
this.emitter = new events.EventEmitter();
this.admin = new SkinAdmin(this);
this._collections = {};
};
/**
* retrieve native_db
*
* @param fn function(err, native_db)
*
*/
SkinDb.prototype.open = function(fn) {
switch (this.state) {
case STATE_OPEN:
return fn(null, this.db);
case STATE_OPENNING:
// if call 'open' method multi times before opened
return this.emitter.addListener('open', fn);
case STATE_CLOSE:
default:
var that = this;
var onDbOpen = function(err, db) {
if (!err && db) {
that.state = STATE_OPEN;
that.db = db;
}else {
db = null;
that.state = STATE_CLOSE;
}
that.emitter.emit('open', err, db);
};
this.emitter.addListener('open', fn);
this.state = STATE_OPENNING;
this.db.open(function(err, db) {
if (db && that.username) {
//do authenticate
db.authenticate(that.username, that.password, function(err) {
onDbOpen(err, db);
});
} else {
onDbOpen(err, db);
}
});
}
};
/**
* Close skinDb
*/
SkinDb.prototype.close = function(callback) {
if (this.state === STATE_CLOSE) {
return callback && callback();
}else if (this.state === STATE_OPEN) {
this.state = STATE_CLOSE;
this.db.close(callback);
}else if (this.state === STATE_OPENNING) {
var that = this;
this.emitter.once('open', function(err, db) {
that.state = STATE_CLOSE;
db.close(callback);
});
}
};
/**
* create or retrieval skin collection
*/
SkinDb.prototype.collection = function(name) {
var collection = this._collections[name];
if (!collection) {
this._collections[name] = collection = new SkinCollection(this, name);
}
return collection;
};
/**
* gridfs
*/
SkinDb.prototype.gridfs = function() {
return this.skinGridStore || (this.skinGridStore = new SkinGridStore(this));
}
/**
* bind additional method to SkinCollection
*
* 1. collectionName
* 2. collectionName, extends1, extends2,... extendsn
* 3. collectionName, SkinCollection
*/
SkinDb.prototype.bind = function() {
var args = __slice.call(arguments),
name = args[0];
if (typeof name !== 'string' || name.length === 0) {
throw new Error('Must provide name parameter for bind.');
}
if (args.length === 1) {
return this.bind(name, this.collection(name));
}
if (args.length === 2 && args[1].constructor === SkinCollection) {
this._collections[name] = args[1];
Object.defineProperty(this, name, {
value: args[1],
writable: false,
enumerable: true
});
// support bind for system.js
var names = name.split('.');
if(names.length > 1){
var prev = this, next;
for(var i =0; i<names.length - 1; i++){
next = prev[names[i]];
if(!next){
next = {};
Object.defineProperty(prev, names[i], {
value : next
, writable : false
, enumerable : true
});
}
prev = next;
}
Object.defineProperty(prev, names[names.length - 1], {
value : args[1]
, writable : false
, enumerable : true
});
}
return args[1];
}
for (var i = 1, len = args.length; i < len; i++) {
if (typeof args[i] != 'object')
throw new Error('the arg' + i + ' should be object, but is ' + args[i]);
}
var coll = this.collection(name);
for (var i = 0, len = args.length; i < len; i++) {
_extend(coll, args[i]);
}
return this.bind(name, coll);
};
var bindSkin = function(name, method) {
return SkinDb.prototype[name] = function() {
var args = arguments.length > 0 ? __slice.call(arguments, 0) : [];
return this.open(function(err, db) {
if (err) {
return args[args.length - 1](err);
} else {
return method.apply(db, args);
}
});
};
};
//bind method of mongodb.Db to SkinDb
for (var name in Db.prototype) {
var method = Db.prototype[name];
if (name !== 'bind' && name !== 'open' && name !== 'collection' && name !== 'admin') {
bindSkin(name, method);
}
}
|
JavaScript
| 0.000003 |
@@ -1455,16 +1455,108 @@
s = %7B%7D;%0A
+ this.bson_serializer = db.bson_serializer;%0A this.ObjectID = db.bson_serializer.ObjectID;%0A
%7D;%0A%0A/**%0A
|
7b17b0610a99a4934e49f16e28b83b2ea3d10f2e
|
use Array.reduce for brevity
|
lib/arraySum.js
|
lib/arraySum.js
|
function arraySum(array) {
var finalSum = 0;
finalSum = array.reduce(function(sum, elem) {
if (typeof elem == "number" && !Number.isNaN(elem) && Number.isFinite(elem)) {
return sum + elem;
}
return sum;
});
return finalSum;
}
module.exports = arraySum;
|
JavaScript
| 0.000029 |
@@ -40,24 +40,8 @@
um =
- 0;%0A finalSum =
arr
@@ -205,16 +205,19 @@
sum;%0A %7D
+, 0
);%0A ret
|
55818dcb52c968ebfacfe2cadc9fef40f7e63ecf
|
disable survey_on field in edit survey modal
|
app/containers/Programs/EditProgram.js
|
app/containers/Programs/EditProgram.js
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import get from 'lodash.get';
import PropTypes from 'prop-types';
import Formsy from 'formsy-react';
import FRC from 'formsy-react-components';
import { DEFAULT_PARENT_ID } from 'config';
import isEmpty from 'lodash.isempty';
import { Loading } from '../../components/common';
import { Modal } from '../../components/Modal';
import {
saveProgram,
enableSubmitForm,
disableSubmitForm,
toggleEditProgramModal,
} from '../../actions';
import { SurveyOns } from '../../Data';
const { Input, Select } = FRC;
class EditProgramForm extends Component {
constructor(props) {
super(props);
this.submitForm = this.submitForm.bind(this);
}
getValue(value) {
return value || '';
}
getSurveyOns() {
return SurveyOns.map((survey) => {
return {
value: survey.id,
label: survey.label,
};
});
}
getPartners() {
return this.props.partners.map((partner) => {
return {
value: partner.char_id,
label: partner.name,
};
});
}
submitForm() {
const myform = this.myform.getModel();
const program = {
name: myform.programName,
description: myform.description,
status: 'AC',
partner: myform.partner,
lang_name: myform.lang_name,
admin0: DEFAULT_PARENT_ID,
};
// Save program
this.props.save(program);
}
render() {
const { isOpen, canSubmit, program, error } = this.props;
const partners = this.getPartners();
if (!program) {
return (
<div className="row text-center">
<Loading />
</div>
);
}
return (
<Modal
title="Edit Survey"
contentLabel="Edit Survey"
isOpen={isOpen}
canSubmit={canSubmit}
submitForm={this.submitForm}
onCloseModal={this.props.closeConfirmModal}
cancelBtnLabel="Cancel"
submitBtnLabel="Save"
>
<Formsy.Form
onValidSubmit={this.submitForm}
onValid={this.props.enableSubmitForm}
onInvalid={this.props.disableSubmitForm}
ref={(ref) => {
this.myform = ref;
}}
>
{!isEmpty(error) ? (
<div className="alert alert-danger">
{Object.keys(error).map((key) => {
const value = error[key];
return (
<p key={key}>
<strong>{key}:</strong> {value[0]}
</p>
);
})}
</div>
) : (
<span />
)}
<Input
name="programName"
id="programName"
value={this.getValue(program.name)}
label="Name"
type="text"
placeholder="Please enter the survey name"
help="This is a required field"
required
validations="minLength:1"
/>
<Input
name="lang_name"
id="lang_name"
value={this.getValue(program.lang_name)}
label="Name in local language"
type="text"
/>
<Input
name="description"
id="description"
value={this.getValue(program.description)}
label="Description"
type="text"
placeholder="Please enter the survey description (Optional)"
/>
<Select
name="partner"
label="Partners"
options={partners}
value={this.getValue(program.partner) || get(partners, '[0].value', '')}
required
/>
</Formsy.Form>
</Modal>
);
}
}
EditProgramForm.propTypes = {
isOpen: PropTypes.bool,
canSubmit: PropTypes.bool,
program: PropTypes.object,
save: PropTypes.func,
enableSubmitForm: PropTypes.func,
disableSubmitForm: PropTypes.func,
closeConfirmModal: PropTypes.func,
partners: PropTypes.array,
error: PropTypes.object,
};
const mapStateToProps = (state) => {
const { selectedProgram } = state.programs;
const { partners } = state.partners;
return {
isOpen: state.modal.editProgram,
canSubmit: state.appstate.enableSubmitForm,
program: get(state.programs.programs, selectedProgram),
partners,
error: state.programs.error,
};
};
const EditProgram = connect(mapStateToProps, {
save: saveProgram,
enableSubmitForm,
disableSubmitForm,
closeConfirmModal: toggleEditProgramModal,
})(EditProgramForm);
export { EditProgram };
|
JavaScript
| 0.000001 |
@@ -3670,32 +3670,264 @@
ed%0A /%3E%0A
+ %3CSelect%0A name=%22survey_on%22%0A label=%22Survey On Type%22%0A options=%7Bthis.getSurveyOns()%7D%0A value=%7Bthis.getValue(program.survey_on)%7D%0A required%0A disabled%0A /%3E%0A
%3C/Formsy
|
c4c3f8320b37d61555465311b989b690d0848a04
|
copy only arguments
|
lib/client/flow.js
|
lib/client/flow.js
|
var Stream = require('./stream');
var Socket = require('./socket');
var utils = require('./utils');
// export event emitter object (clone before use!)
module.exports = function (emitter) {
// merge flow emitter to existing object
if (emitter) {
for (var key in FlowEmitter) {
emitter[key] = FlowEmitter[key];
}
// create a new emitter
} else {
emitter = utils.clone(FlowEmitter);
}
emitter._flows = {};
return emitter;
};
var FlowEmitter = {
handlers: {
transform: require('./transform'),
link: Socket.stream,
load: engine.load
},
/**
* Call flow handlers which listen to event.
*
* @public
* @param {string} The event name.
*/
flow: function (eventName, context) {
var events = this._flows;
// create streams
var stream = createStream(this, context);
stream.pause();
// setup event stream directly if eventName is an object
if (typeof eventName === 'object') {
Flow(this, createStream(this, context, stream), eventName);
return stream;
}
// check if event exists
if (events[eventName] && events[eventName].length) {
// index for events that must be removed
var obsoleteEvents = [];
var i, l;
var config;
// call handlers
for (i = 0, l = events[eventName].length; i < l; ++i) {
if ((config = events[eventName][i])) {
// pass stream to flow to setup handlers
Flow(this, createStream(this, context, stream), config);
// remove from event buffer, if once is true
if (config['1']) {
config = undefined;
obsoleteEvents.push([eventName, i]);
}
}
}
// remove obsolete events
if (obsoleteEvents.length) {
for (i = 0, l = obsoleteEvents.length; i < l; ++i) {
// remove handler
events[obsoleteEvents[i][0]].splice(obsoleteEvents[i][1], 1);
// remove event
if (events[obsoleteEvents[i][0]].length === 0) {
delete events[obsoleteEvents[i][0]];
}
}
}
}
stream.resume();
// return transmitter to send and receive data
return stream;
},
/**
* Mind an an event.
*
* @public
* @param {string} The even name regular expression pattern.
* @param {object} The flow handler config.
*/
mind: function (config) {
var event = config[0];
var events = this._flows;
(this._access || (this._access = {}))[event] = true;
if (!events[event]) {
events[event] = [];
}
// copy and push the flow config
// TODO is coping necessary??
events[event].push(config.slice(1));
return this;
}
};
function createStream (instance, context, inputStream) {
var stream = Stream(instance, inputStream || (context && context.stream));
// merge context into steam
if (context) {
for (var prop in context) {
stream[prop] = context[prop];
}
}
return stream;
}
/**
* Create a new config event handler.
*
* @public
* @param {object} The module instance.
* @param {object} The "out" config.
* @param {object} The adapter object (optional).
*/
function Flow (instance, stream, config) {
var session = stream.session;
var role = (session || {})[engine.session_role];
for (var i = 0, l = config.length, flow, method, args; i < l; ++i) {
flow = config[i];
args = [stream];
if (flow instanceof Array) {
method = flow[0];
args = args.concat(flow.slice(1));
} else {
method = flow;
}
// call function directly
if (typeof method === 'function') {
return method.apply(instance, args);
}
method = parseMethodPath(method, instance);
if (typeof method[0] === 'string') {
// load instance
return engine.load(method[0], role, function (err, instance) {
if (err) {
return stream.write(err).resume();
}
method[0] = instance;
});
}
// check access
if (session && !utils.roleAccess(instance, role)) {
return stream.write(engine.log('E', new Error('Flow target instance "' + instance._name + '" is not found.')));
}
// get method
method[1] = getMethodFromPath(method[0], method[1]);
if (!method[1]) {
return;
}
// append as data handler
if (method[2]) {
stream.data(method[0], args);
// call stream handler
} else {
method[1].apply(method[0], args);
}
}
}
function parseMethodPath (path, instance) {
var method = [instance, path];
// check if path is a data handler
if (path[0] === ':') {
method[1] = path = path.substr(1);
method[2] = true;
}
if (path.indexOf('/') > 0) {
path = path.split('/');
method[0] = engine.instances[path[0]] || path[0];
method[1] = path[1];
}
return method;
}
/**
* Return a function or undefined.
*/
function getMethodFromPath (module_instance, path) {
if (typeof path === 'function') {
return path;
}
var _path = path;
if (
typeof path === 'string' &&
typeof (path = utils.path(path, [module_instance.handlers, module_instance, global])) !== 'function'
) {
engine.log('E', new Error('Flow method "' + _path + '" is not a function. Instance:' + module_instance._name));
return;
}
return path;
}
|
JavaScript
| 0 |
@@ -2804,16 +2804,29 @@
= config
+.splice(0, 1)
%5B0%5D;%0A
@@ -3045,46 +3045,8 @@
fig%0A
- // TODO is coping necessary??%0A
@@ -3074,25 +3074,16 @@
h(config
-.slice(1)
);%0A%0A
@@ -5131,32 +5131,41 @@
se %7B%0A
+ stream =
method%5B1%5D.apply
@@ -5173,32 +5173,42 @@
method%5B0%5D, args)
+ %7C%7C stream
;%0A %7D%0A
|
48c3b8231ec3c002e5b6d359328dd08738634b0a
|
fix little bug in node
|
lib/client/node.js
|
lib/client/node.js
|
// Dep: [KadOH]/core/stateeventemitter
// Dep: [KadOH]/core/deferred
// Dep: [KadOH]/globals
// Dep: [KadOH]/peer
// Dep: [KadOH]/reactor
// Dep: [KadOH]/routingtable
// Dep: [KadOH]/util/crypto
// Dep: [KadOH]/iterativefind
// Dep: [KadOH]/valuemanagement
(function(exports) {
var KadOH = exports,
StateEventEmitter = KadOH.core.StateEventEmitter,
Deferred = KadOH.core.Deferred,
globals = KadOH.globals,
Peer = KadOH.Peer,
Reactor = KadOH.Reactor,
RoutingTable = KadOH.RoutingTable,
Crypto = KadOH.util.Crypto,
IterativeFind = KadOH.IterativeFind,
ValueManagement = KadOH.ValueManagement;
KadOH.Node = StateEventEmitter.extend({
initialize: function(id, options) {
this.supr();
this.setState('initializing');
if (!id)
this._id = this._generateID();
else
this._id = id;
var config = this.config = {};
for (var option in options) {
config[option] = options[option];
}
// adding the reactor for network purposes
// adding the default routing table
this._routingTable = new RoutingTable(this, config.routing_table);
this._reactor = new Reactor(this, config.reactor);
this.setState('initialized');
},
// Network functions
connect: function() {
var self = this;
this._reactor.on('connected', function(address) {
self._me = new Peer(address, self._id);
self._address = address;
this._store = new ValueManagement(self, self.config.value_management);
self.setState('connected');
});
this._reactor.connectTransport();
return this;
},
join: function(bootstraps) {
var self = this;
if (!bootstraps || bootstraps.length === 0) {
throw new Error('No bootstrap to join the network');
}
bootstraps = bootstraps.map(function(address) {
return new Peer(address, null);
});
this.once('connected', function() {
// boostrapping process
var bootstrapping = Deferred.whenAtLeast(
self._reactor.sendRPCs(bootstraps, 'PING')
);
// joining lookup process
var join = function() {
self.emit('join started');
self.iterativeFindNode(self.getMe())
.then(function(response) {
self.emit('joined', response);
},
function(shortlist) {
self.emit('join failed', shortlist);
});
};
var cannotJoin = function() {
self.emit('join failed', 'no bootstrap');
};
bootstrapping.then(join, cannotJoin);
});
return this;
},
/**
* Iterative lookup used by kademlia
* See /doc papers for informations on the loose parallelism
* used in this implementation
* @param {String} id Identifier of the peer or objects
* @param {String} type The type of the lookup
* @return {Promise}
*/
_iterativeFind: function(peer, type) {
var lookup;
var self = this;
var success = function(response) {
self.emit('iterativeFind resolved', lookup, response);
};
var failure = function(error) {
self.emit('iterativeFind rejected', lookup, reject);
};
lookup = new IterativeFind(this, peer, type)
.then(success, failure);
this.emit('iterativeFind started', lookup);
lookup.startWith(this._routingTable.getClosePeers(peer.getID(), globals.ALPHA));
return lookup;
},
iterativeFindNode: function(peer) {
return this._iterativeFind(peer, 'NODE');
},
iterativeFindValue: function(value) {
var lookup = this._iterativeFind(peer, 'VALUE');
// @TODO
},
// RPCs
// These function may return promises
/**
* PING
*/
PING: function() {
return {
id: this.getID()
};
},
/**
* FIND_NODE
*/
FIND_NODE: function(params) {
var validations = (
typeof params === 'object' &&
typeof params.id === 'string' &&
typeof params.target === 'string' &&
globals.REGEX_NODE_ID.test(params.id) &&
globals.REGEX_NODE_ID.test(params.target)
);
if (!validations)
throw new TypeError();
var id = this.getID();
// retrieve the beta closest peer to the id
// exclude the id of the requestor
return {
id : id,
nodes : this._routingTable.getClosePeers(
params.id,
globals.BETA,
[new Peer(null, params.id)]
).getTripleArray()
};
},
FIND_VALUE: function(params) {
var validations = (
typeof params === 'object' &&
typeof params.id === 'string' &&
typeof params.value === 'string' &&
globals.REGEX_NODE_ID.test(params.id) &&
globals.REGEX_NODE_ID.test(params.target)
);
if (!validations)
throw new TypeError();
var id = this.getID();
var deferred = new Deferred();
// if the key exists, resolve the value
// with its expiration date
var success = function(value, exp) {
deferred.resolve({
id : id,
value : value,
expiration : exp
});
};
// if the retrieves is rejected, same as FIND_NODE
// send the beta closest peer to the id
// exclude the id of the requestor
var failure = function() {
deferred.resolve({
id : id,
nodes : this._routingTable.getClosePeers(
params.value,
globals.BETA,
[new Peer(null, params.id)]
).getTripleArray()
});
};
this.store.retrieve(params.value)
.then(success, failure);
return deferred;
},
STORE: function(params) {
var validations = (
typeof params === 'object' &&
typeof params.id === 'string' &&
(
(
typeof params.data === 'string' &&
typeof params.expiration === 'number'
) ||
(
typeof params.data === 'undefined' &&
typeof params.request === 'boolean' &&
typeof params.length === 'number'
)
) &&
globals.REGEX_NODE_ID.test(params.id) &&
globals.REGEX_NODE_ID.test(params.target)
);
if (!validations)
throw new TypeError();
// @TODO
// Manage a two-phase STORE with
// a request process
var deferred = new Deferred();
var success = function() {
deferred.resolve('OK');
};
var failure = function(error) {
deferred.reject(error);
};
this.store.save(
globals.digest(params.data),
params.data,
params.expiration
).then(success, failure);
return deferred;
},
// Value Mabagement
republish : function(key, value, exp) {
// @TODO
},
// Getters
reactor: function() {
return this._reactor;
},
getMe: function() {
return this._me;
},
getID: function() {
return this._id;
},
getAddress: function() {
return this._address;
},
// Private
_generateID: function() {
return Crypto.digest.randomSHA1();
}
});
})('object' === typeof module ? module.exports : (this.KadOH = this.KadOH || {}));
|
JavaScript
| 0.000001 |
@@ -3421,22 +3421,21 @@
lookup,
-reject
+error
);%0A
@@ -3855,20 +3855,14 @@
-var lookup =
+return
thi
|
dd375237d10e27205967fb9feab791d96d6e625c
|
Remove mixin function
|
src/js/charts/barTypeMixer.js
|
src/js/charts/barTypeMixer.js
|
/**
* @fileoverview barTypeMixer is mixer of bar type chart(bar, column).
* @author NHN Ent.
* FE Development Lab <[email protected]>
*/
'use strict';
var chartConst = require('../const'),
rawDataHandler = require('../helpers/rawDataHandler'),
predicate = require('../helpers/predicate');
/**
* barTypeMixer is mixer of bar type chart(bar, column).
* @mixin
*/
var barTypeMixer = {
/**
* Make minus values.
* @param {Array.<number>} data number data
* @returns {Array} minus values
* @private
*/
_makeMinusValues: function(data) {
return tui.util.map(data, function(value) {
return value < 0 ? 0 : -value;
});
},
/**
* Make plus values.
* @param {Array.<number>} data number data
* @returns {Array} plus values
* @private
*/
_makePlusValues: function(data) {
return tui.util.map(data, function(value) {
return value < 0 ? 0 : value;
});
},
/**
* Make normal diverging raw series data.
* @param {{data: Array.<number>}} rawSeriesData raw series data
* @returns {{data: Array.<number>}} changed raw series data
* @private
*/
_makeNormalDivergingRawSeriesData: function(rawSeriesData) {
rawSeriesData.length = Math.min(rawSeriesData.length, 2);
rawSeriesData[0].data = this._makeMinusValues(rawSeriesData[0].data);
if (rawSeriesData[1]) {
rawSeriesData[1].data = this._makePlusValues(rawSeriesData[1].data);
}
return rawSeriesData;
},
/**
* Make raw series data for stacked diverging option.
* @param {{data: Array.<number>, stack: string}} rawSeriesData raw series data
* @returns {{data: Array.<number>}} changed raw series data
* @private
*/
_makeRawSeriesDataForStackedDiverging: function(rawSeriesData) {
var self = this,
stacks = rawDataHandler.pickStacks(rawSeriesData, true),
result = [],
leftStack = stacks[0],
rightStack = stacks[1];
rawSeriesData = rawDataHandler.sortSeriesData(rawSeriesData, stacks);
tui.util.forEachArray(rawSeriesData, function(seriesDatum) {
var stack = seriesDatum.stack || chartConst.DEFAULT_STACK;
if (stack === leftStack) {
seriesDatum.data = self._makeMinusValues(seriesDatum.data);
result.push(seriesDatum);
} else if (stack === rightStack) {
seriesDatum.data = self._makePlusValues(seriesDatum.data);
result.push(seriesDatum);
}
});
return result;
},
/**
* Make raw series data for diverging.
* @param {{data: Array.<number>, stack: string}} rawSeriesData raw series data
* @param {?string} stackTypeOption stackType option
* @returns {{data: Array.<number>}} changed raw series data
* @private
*/
_makeRawSeriesDataForDiverging: function(rawSeriesData, stackTypeOption) {
if (predicate.isValidStackOption(stackTypeOption)) {
rawSeriesData = this._makeRawSeriesDataForStackedDiverging(rawSeriesData);
} else {
rawSeriesData = this._makeNormalDivergingRawSeriesData(rawSeriesData);
}
return rawSeriesData;
},
/**
* Sort raw series data from stacks.
* @param {Array.<{data: Array.<number>, stack: string}>} rawSeriesData raw series data
* @returns {Array.<{data: Array.<number>, stack: string}>}
* @private
*/
_sortRawSeriesData: function(rawSeriesData) {
var stacks = rawDataHandler.pickStacks(rawSeriesData);
return rawDataHandler.sortSeriesData(rawSeriesData, stacks);
},
/**
* Mix in.
* @param {function} func target function
* @ignore
*/
mixin: function(func) {
tui.util.extend(func.prototype, this);
}
};
module.exports = barTypeMixer;
|
JavaScript
| 0.005459 |
@@ -3752,183 +3752,8 @@
s);%0A
- %7D,%0A%0A /**%0A * Mix in.%0A * @param %7Bfunction%7D func target function%0A * @ignore%0A */%0A mixin: function(func) %7B%0A tui.util.extend(func.prototype, this);%0A
|
95f1e21e99f3abb2bec287542a5a1a202dc5b1e9
|
Optimize async composition
|
lib/composition.js
|
lib/composition.js
|
'use strict';
function Composition() {}
const compose = (
// Asynchronous functions composition
fns // array of functions, callback-last / err-first
// Returns: function, composed callback-last / err-first
) => {
const comp = function(data, callback) {
if (!callback) {
callback = data;
data = {};
}
comp.done = callback;
if (comp.canceled) {
if (callback) callback(new Error('metasync canceled'));
return;
}
if (comp.timeout) {
comp.timer = setTimeout(() => {
comp.timer = null;
if (callback) {
callback(new Error('metasync timed out'));
comp.done = null;
}
}, comp.timeout);
}
comp.context = data;
comp.arrayed = Array.isArray(comp.context);
comp.paused = false;
if (comp.len === 0) {
comp.finalize();
return;
}
if (comp.parallelize) comp.parallel();
else comp.sequential();
};
const parallelize = fns.length === 1;
if (parallelize) fns = fns[0];
const fields = {
fns,
parallelize,
context: null,
timeout: 0,
timer: null,
len: fns.length,
canceled: false,
paused: true,
arrayed: false,
done: null,
};
Object.setPrototypeOf(comp, Composition.prototype);
return Object.assign(comp, fields);
};
Composition.prototype.exec = function(fn, finish) {
if (Array.isArray(fn)) compose(fn)(this.context, finish);
else fn(this.context, finish);
};
Composition.prototype.finalize = function(err) {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
if (this.done) {
this.done(err, this.context);
this.done = null;
}
};
Composition.prototype.collect = function(err, result) {
if (err) {
if (this.done) this.done(err);
this.done = null;
return;
}
if (result !== this.context && result !== undefined) {
if (this.arrayed) this.context.push(result);
else if (typeof(result) === 'object') Object.assign(this.context, result);
}
};
Composition.prototype.parallel = function() {
let counter = 0;
const finish = (err, result) => {
this.collect(err, result);
if (++counter === this.len) this.finalize();
};
const fns = this.fns;
let i;
for (i = 0; i < this.len; i++) {
this.exec(fns[i], finish);
}
};
Composition.prototype.sequential = function() {
let counter = -1;
const fns = this.fns;
const next = (err, result) => {
if (err || result) this.collect(err, result);
if (++counter === this.len) {
this.finalize();
return;
}
this.exec(fns[counter], next);
};
next();
};
Composition.prototype.then = function(fulfill, reject) {
this((err, result) => {
if (err) reject(err);
else fulfill(result);
});
return this;
};
Composition.prototype.clone = function() {
return compose(this.fns.slice());
};
Composition.prototype.pause = function() {
if (!this.canceled) {
this.paused = true;
}
return this;
};
Composition.prototype.resume = function() {
if (!this.canceled) {
this.paused = false;
}
return this;
};
Composition.prototype.timeout = function(msec) {
this.timeout = msec;
return this;
};
Composition.prototype.cancel = function() {
if (!this.canceled && this.done) {
this.done(new Error('metasync canceled'));
this.done = null;
}
this.canceled = true;
return this;
};
module.exports = { compose };
|
JavaScript
| 0.001632 |
@@ -1307,157 +1307,8 @@
%7D;%0A%0A
-Composition.prototype.exec = function(fn, finish) %7B%0A if (Array.isArray(fn)) compose(fn)(this.context, finish);%0A else fn(this.context, finish);%0A%7D;%0A%0A
Comp
@@ -1348,24 +1348,24 @@
tion(err) %7B%0A
+
if (this.t
@@ -1920,22 +1920,20 @@
const
-finish
+next
= (err,
@@ -2061,13 +2061,73 @@
;%0A
-let i
+const len = this.len;%0A const context = this.context;%0A let i, fn
;%0A
@@ -2142,21 +2142,16 @@
0; i %3C
-this.
len; i++
@@ -2162,32 +2162,101 @@
-this.exec(fns%5Bi%5D, finish
+fn = fns%5Bi%5D;%0A if (Array.isArray(fn)) compose(fn)(context, next);%0A else fn(context, next
);%0A
@@ -2346,32 +2346,88 @@
fns = this.fns;%0A
+ const len = this.len;%0A const context = this.context;%0A
const next = (
@@ -2512,29 +2512,24 @@
counter ===
-this.
len) %7B%0A
@@ -2574,30 +2574,107 @@
-this.exec(fns%5B
+const fn = fns%5Bcounter%5D;%0A if (Array.isArray(fn)) compose(fn)(context, next);%0A else fn(
co
-u
nte
-r%5D
+xt
, ne
|
2e30756e9684c0bc3a5972890580d6eec8a6335e
|
Update TaskView.js
|
src/js/components/TaskView.js
|
src/js/components/TaskView.js
|
import classNames from 'classnames';
import mixin from 'reactjs-mixin';
import {StoreMixin} from 'mesosphere-shared-reactjs';
import React from 'react';
import FilterBar from './FilterBar';
import FilterButtons from './FilterButtons';
import FilterHeadline from './FilterHeadline';
import FilterInputText from './FilterInputText';
import MesosStateStore from '../stores/MesosStateStore';
import RequestErrorMsg from './RequestErrorMsg';
import SaveStateMixin from '../mixins/SaveStateMixin';
import StringUtil from '../utils/StringUtil';
import TaskStates from '../constants/TaskStates';
import TaskTable from './TaskTable';
const METHODS_TO_BIND = [
'handleSearchStringChange',
'handleStatusFilterChange',
'onStateStoreSuccess',
'onStateStoreError',
'resetFilter'
];
const STATUS_FILTER_BUTTONS = ['all', 'active', 'completed'];
class TaskView extends mixin(SaveStateMixin, StoreMixin) {
constructor() {
super();
this.state = {
mesosStateErrorCount: 0,
searchString: '',
filterByStatus: 'active'
};
this.saveState_properties = ['filterByStatus'];
this.store_listeners = [
{
name: 'state',
events: ['success', 'error'],
suppressUpdate: true
}
];
METHODS_TO_BIND.forEach(function (method) {
this[method] = this[method].bind(this);
}, this);
}
componentWillMount() {
this.saveState_key = `taskView#${this.props.itemID}`;
super.componentWillMount();
}
onStateStoreSuccess() {
if (this.state.mesosStateErrorCount !== 0) {
this.setState({mesosStateErrorCount: 0});
}
}
onStateStoreError() {
this.setState({mesosStateErrorCount: this.state.mesosStateErrorCount + 1});
}
handleSearchStringChange(searchString) {
this.setState({searchString});
}
handleStatusFilterChange(filterByStatus) {
this.setState({filterByStatus});
}
filterByCurrentStatus(tasks) {
let status = this.state.filterByStatus;
if (status === 'all') {
return tasks;
}
return tasks.filter(function (task) {
return TaskStates[task.state].stateTypes.includes(status);
});
}
hasLoadingError() {
return this.state.mesosStateErrorCount >= 5;
}
getLoadingScreen() {
if (this.hasLoadingError()) {
return <RequestErrorMsg />;
}
return (
<div className="container container-pod text-align-center vertical-center inverse">
<div className="row">
<div className="ball-scale">
<div />
</div>
</div>
</div>
);
}
getTaskTable(tasks) {
let {inverseStyle, parentRouter} = this.props;
let classSet = classNames({
'table table-borderless-outer table-borderless-inner-columns': true,
'flush-bottom': true,
'inverse': inverseStyle
});
return (
<TaskTable
className={classSet}
parentRouter={parentRouter}
tasks={tasks} />
);
}
resetFilter() {
this.setState({
searchString: '',
filterByStatus: 'all'
});
}
getButtonContent(filterName, count) {
return (
<span className="button-align-content">
<span className="label">{StringUtil.capitalize(filterName)}</span>
<span className="badge">{count || 0}</span>
</span>
);
}
getContent() {
let {inverseStyle, tasks} = this.props;
let {filterByStatus, searchString} = this.state;
let totalNumberOfTasks = tasks.length;
// Get task states based on TaskStates types
let taskStates = tasks.map(function (task) {
let {stateTypes} = TaskStates[task.state];
return stateTypes.find(function (state) {
return state === 'active' || state === 'completed';
});
});
if (searchString !== '') {
tasks = StringUtil.filterByString(tasks, 'name', searchString);
}
tasks = this.filterByCurrentStatus(tasks);
return (
<div className="flex-container-col flex-grow">
<FilterHeadline
inverseStyle={inverseStyle}
onReset={this.resetFilter}
name="Task"
currentLength={tasks.length}
totalLength={totalNumberOfTasks} />
<FilterBar>
<FilterInputText
className="flush-bottom"
searchString={searchString}
handleFilterChange={this.handleSearchStringChange}
inverseStyle={inverseStyle} />
<FilterButtons
renderButtonContent={this.getButtonContent}
filters={STATUS_FILTER_BUTTONS}
onFilterChange={this.handleStatusFilterChange}
inverseStyle={inverseStyle}
itemList={taskStates}
selectedFilter={filterByStatus} />
</FilterBar>
{this.getTaskTable(tasks)}
</div>
);
}
render() {
var showLoading = this.hasLoadingError() ||
Object.keys(MesosStateStore.get('lastMesosState')).length === 0;
if (showLoading) {
return this.getLoadingScreen();
} else {
return this.getContent();
}
}
}
TaskTable.defaultProps = {
inverseStyle: false,
itemID: '',
tasks: []
};
TaskView.propTypes = {
inverseStyle: React.PropTypes.bool,
itemID: React.PropTypes.string,
parentRouter: React.PropTypes.func,
tasks: React.PropTypes.array
};
module.exports = TaskView;
|
JavaScript
| 0.000001 |
@@ -61,24 +61,51 @@
tjs-mixin';%0A
+import React from 'react';%0A
import %7BStor
@@ -149,35 +149,8 @@
js';
-%0Aimport React from 'react';
%0A%0Aim
|
5242b9a14431e2ca0ce0bfaf06794d174bc6d4a0
|
fix login issue
|
src/js/controllers/session.js
|
src/js/controllers/session.js
|
'use strict';
/**
* @ngdoc function
* @name Pear2Pear.controller:SessionCtrl
* @description
* # SessionCtrl
* Controller of the Pear2Pear
*/
angular.module('Pear2Pear')
.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/session/new', {
templateUrl: 'session/new.html',
controller:'SessionCtrl'
})
.when('/session/userdata',{
templateUrl: 'session/userdata.html',
controller:'SessionCtrl'
});
}])
.controller('SessionCtrl', ['$scope', '$rootScope', '$location', '$route', 'pear', function($scope, $rootScope, $location, $route, pear) {
$scope.$parent.hideNavigation = true;
$scope.session = {};
$scope.loginRegexp = new RegExp('^[a-zA-Z0-9\.]+$');
$scope.login = function() {
$scope.$parent.hideNavigation = false;
var startSession = function(){
// TODO change password when register is available
pear.startSession(
$scope.name, '$password$',
function(){
console.log('success!');
pear.users.setCurrent($scope.name + '@' + SwellRTConfig.swellrtServerDomain);
$location.path('/communities');
},
function(error){
console.log(error);
}
);
};
pear.registerUser($scope.name, '$password$', startSession, startSession);
};
$scope.userData = function () {
_paq.push(['appendToTrackingUrl', 'new_visit=1']);
_paq.push(["deleteCookies"]);
_paq.push(['setCustomVariable', 1, 'gender', $scope.user.gender, 'visit']);
_paq.push(['setCustomVariable', 2, 'age', $scope.user.age, 'visit']);
_paq.push(['setCustomVariable', 3, 'role', $scope.user.role, 'visit']);
_paq.push(['setCustomVariable', 4, 'tech', $scope.user.tech, 'visit']);
_paq.push(['setCustomVariable', 5, 'community', $scope.user.community, 'visit']);
// tracker.storeCustomVariablesInCookie();
_paq.push(['trackEvent', 'UserQuestionaire', 'answer']);
_paq.push(['trackPageView']);
if ($route.current.params['redirect']) {
var redirect = $route.current.params['redirect'];
$location.path(redirect);
}
else if ($route.current.params['predirect']) {
window.location.href = $route.current.params['predirect'];
}
else {
$location.path('/timeline');
}
};
}]);
|
JavaScript
| 0.000001 |
@@ -563,16 +563,28 @@
'pear',
+ '$timeout',
functio
@@ -628,16 +628,26 @@
te, pear
+, $timeout
) %7B%0A
@@ -1044,33 +1044,31 @@
-console.log('success!');%0A
+$timeout(function()%7B%0A
@@ -1157,32 +1157,34 @@
n);%0A
+
$location.path('
@@ -1195,24 +1195,39 @@
munities');%0A
+ %7D)%0A
%7D,
|
7ab6c064830a88fd39a51777599ee6cdbe5f92db
|
test update
|
src/js/jquery.StorageTable.js
|
src/js/jquery.StorageTable.js
|
/* StorageTables v0.0.2 - Copyright 2015 by Anthony Fassett */
(function ($) {
"use strict";
$.fn.storageTable = function (options) {
var settings = $.extend({
// These are the defaults.
dataType: "json",
data: [],
editable: false,
deletable: false,
inputBy: true,
focus: false,
columns: [],
title: "test"
}, options);
if (this.is(':empty') && this.is(':not(table)')) {
_fnclickListern();
return this.append(_fnTableTemplate());
} else {
//TODO: attack handlers for ajax calls and other stuff.
//Add Inputs on clicks or
console.log("It already is a table!");
_fnclickListern(this);
return this;
}
//Editable Templates
function _fnTableTemplate(head, body) {
settings.title = typeof settings.title !== 'undefined' ? '<caption>' + settings.title + '</caption>' : "";
head = typeof head !== 'undefined' ? head : _fnCreateHeader();
body = typeof body !== 'undefined' ? body : _fnCreateColumn();
return '<table>' + settings.title + head + body + '</table>';
}
$.fn.storageTable.columns = function (template) {
template = typeof template !== 'undefined' ? template : "";
_fnCreateColumn();
};
function _fnclickListern(select) {
//TODO: Make this better!
$(select).children('table > tr > :empty(td)').append('<input type="text"/>');
}
function _fnCreateHeader() {
var colNum = 10;
var thead = '<thead><tr>';
for (var i = 1; i <= colNum; i++) {
thead += '<th>' + i + '</th>';
}
return thead + '</tr></thead>';
}
function _fnCreateColumn() {
var colNum = 10, tbody = '<tbody><tr>';
//NOTES: Chrome by default wrapping with tbody.
for (var t = 1; t <= colNum; t++) {
tbody += '<td>' + t + '</td>';
}
return tbody + '</tr></tbody>';
}
};
}(jQuery));
|
JavaScript
| 0.000001 |
@@ -684,29 +684,16 @@
r stuff.
-%0A
//Add In
@@ -716,16 +716,28 @@
r
+
%0A
@@ -779,16 +779,28 @@
able!%22);
+
%0A
@@ -820,20 +820,16 @@
Listern(
-this
);%0A
@@ -1498,22 +1498,16 @@
Listern(
-select
) %7B%0A
@@ -1558,49 +1558,17 @@
$(
-select).children('table %3E tr %3E
+'td
:empty
-(td)
').a
@@ -1598,16 +1598,91 @@
t%22/%3E');%0A
+ $(':input').change(function () %7B%0A%0A %7D);%0A %0A
@@ -2146,24 +2146,163 @@
Num; t++) %7B%0A
+ if (t === 5) %7B%0A tbody += '%3Ctd%3E%3C/td%3E';%0A %7D %0A else %7B %0A
@@ -2328,32 +2328,50 @@
+ t + '%3C/td%3E';%0A
+ %7D%0A
%7D%0A
|
a63106515ce84005d530501794b44dad4a81cf7e
|
add maxBuffer option
|
src/commands/restart.js
|
src/commands/restart.js
|
/**
* @file command `reload`
* @author zdying
*/
'use strict';
var path = require('path');
var childProcess = require('child_process');
var homedir = require('os-homedir');
var hiproxyDir = path.join(homedir(), '.hiproxy');
module.exports = {
command: 'restart',
describe: 'Restart the local proxy service (Only works in daemon mode)',
usage: 'restart',
fn: function () {
try {
var infoFile = path.join(hiproxyDir, 'hiproxy.json');
var info = require(infoFile);
var cmd = info.cmd;
childProcess.execSync([cmd[0], cmd[1], 'stop'].join(' '));
childProcess.execSync(cmd.join(' '));
console.log();
console.log('Service reloaded success :)');
console.log();
} catch (err) {
console.log();
console.log('Service reloaded failed :(');
console.log();
console.log('[Error] Command <restart> will only work in daemon mode.');
console.log();
}
}
};
|
JavaScript
| 0.000002 |
@@ -619,16 +619,42 @@
oin(' ')
+, %7BmaxBuffer: 5000 * 1024%7D
);%0A%0A
|
2e5d51e19174c3a3d0c3ec4e6d25eede1805f7ba
|
save cursor position in state
|
src/js/store/editorReducer.js
|
src/js/store/editorReducer.js
|
import R from 'ramda'
import fileStorage from './fileStorage'
export const CURSOR_POSITION_IN_FILE_EDITOR_CHANGED = 'CURSOR_POSITION_IN_FILE_EDITOR_CHANGED '
export const cursorPositionInFileEditorChanged = ({cursor, fileId}) => {
return {
type: CURSOR_POSITION_IN_FILE_EDITOR_CHANGED,
cursor,
fileId
}
}
export const CURSOR_POSITION_IN_FUNCTION_EDITOR_CHANGED = 'CURSOR_POSITION_IN_FUNCTION_EDITOR_CHANGED '
export const cursorPositionInFunctionEditorChanged = ({cursor, node}) => {
return {
type: CURSOR_POSITION_IN_FUNCTION_EDITOR_CHANGED,
cursor,
node
}
}
export const CLOSE_FUNCTION_EDITOR = 'CLOSE_FUNCTION_EDITOR '
export const closeFunctionEditor = ({id}) => {
return {
type: CLOSE_FUNCTION_EDITOR,
id
}
}
let setProp = R.curry((prop, value, obj) => R.set(R.lensProp(prop), value, obj));
let actionObject = {
[CURSOR_POSITION_IN_FILE_EDITOR_CHANGED]: setProp('focusedFunctionEditor', undefined),
[CURSOR_POSITION_IN_FUNCTION_EDITOR_CHANGED]: (state, action) => {
const {node} = action
return setProp('focusedFunctionEditor', node.customId, state)
},
[CLOSE_FUNCTION_EDITOR]: (state, action) => {
const {id} = action;
return setProp('functionEditorIds', R.filter((openFnId) => openFnId !== id, state.functionEditorIds), state);
}
}
let initialState = {
focusedFunctionEditor: undefined,
functionEditorIds: [3, 2],
fileStorage: fileStorage()
}
let reducer = (state = initialState, action) => {
let actionFunction = actionObject[action.type]
if (actionFunction) {
return actionFunction(state, action)
} else {
return {
...state,
fileStorage: fileStorage(state.fileStorage, action)
}
}
}
export default reducer;
|
JavaScript
| 0.000001 |
@@ -953,51 +953,201 @@
D%5D:
-setProp('focusedFunctionEditor', undefined)
+(state, action) =%3E %7B%0A const %7Bcursor%7D = action%0A return R.pipe(%0A setProp('focusedFunctionEditor', undefined),%0A setProp('cursor', cursor)%0A )(state)%0A %7D
,%0A
@@ -1234,16 +1234,24 @@
st %7Bnode
+, cursor
%7D = acti
@@ -1260,32 +1260,52 @@
%0A return
+R.pipe(%0A
setProp('focused
@@ -1334,18 +1334,67 @@
customId
-,
+),%0A setProp('cursor', cursor)%0A )(
state)%0A
@@ -1695,16 +1695,39 @@
%5B3, 2%5D,%0A
+ cursor: undefined,%0A
file
|
bb1f07ac634bb591d7cf68b54cce09700302cc28
|
Fix astral characters in youtube json output
|
lib/domains/youtube.com.js
|
lib/domains/youtube.com.js
|
/////////////////////////////////////////////////////////////////////////////
// YouTube
//
'use strict';
var encode = require('mdurl/encode');
var urlLib = require('url');
var EmbedzaError = require('../utils/error');
module.exports = {
match: [
/^https?:\/\/(?:www\.)?youtube\.com\/?watch\?(?:[^&]+&)*v=([a-zA-Z0-9_-]+)/i,
/^https?:\/\/www\.youtube\.com\/embed\/([a-zA-Z0-9_-]+)/i,
/^https?:\/\/www\.youtube\.com\/v\/([a-zA-Z0-9_-]+)/i,
/^https?:\/\/www\.youtube\.com\/user\/[a-zA-Z0-9_-]+\?v=([a-zA-Z0-9_-]+)/i,
/^https?:\/\/youtu.be\/([a-zA-Z0-9_-]+)/i,
/^https?:\/\/m\.youtube\.com\/#\/watch\?(?:[^&]+&)*v=([a-zA-Z0-9_-]+)/i,
/^https?:\/\/www\.youtube-nocookie\.com\/v\/([a-zA-Z0-9_-]+)/i
],
fetchers: [
function youtube_fetcher(env, callback) {
var urlObj = urlLib.parse(env.src, true);
// Drop playlist info because youtube returns wrong player url - playlist with missed video index
if (urlObj.query.list) {
delete urlObj.query.list;
}
delete urlObj.search;
var url = 'http://www.youtube.com/oembed?format=json&url=' + encode(urlLib.format(urlObj), encode.componentChars);
env.self.request(url, function (err, response, body) {
if (err) {
callback(err);
return;
}
if (response.statusCode !== 200) {
callback(new EmbedzaError('YouTube fetcher: Bad response code: ' + response.statusCode));
return;
}
try {
env.data.oembed = JSON.parse(body);
} catch (__) {
callback(new EmbedzaError('YouTube fetcher: Can\'t parse oembed JSON response'));
return;
}
callback();
});
}
],
mixins: [
'meta',
'oembed-player',
'oembed-thumbnail'
],
config: {
autoplay: 'autoplay=1'
}
};
|
JavaScript
| 0.999989 |
@@ -1496,16 +1496,585 @@
try %7B%0A
+ // YouTube is encoding astral characters in a non-standard way like %5CU0001f44d,%0A // so we replace them before body decoding.%0A //%0A // Example:%0A // https://www.youtube.com/oembed?format=json&url=http://www.youtube.com/watch?v=1DSmex4IPxg%0A //%0A body = body.replace(/(%5C%5C+)(U%5B0-9a-fA-F%5D%7B8%7D)/g, function (match, slashes, escape) %7B%0A return (slashes.length %25 2) ?%0A (slashes.slice(1) + String.fromCodePoint(parseInt(escape.slice(2), 16))) :%0A match;%0A %7D);%0A%0A
|
00d913e92d8a0d8f34b5df1b24a34a1db1f1839a
|
Capitalize all the headers
|
src/lib/mock/mockedRequest.js
|
src/lib/mock/mockedRequest.js
|
'use strict';
function MockedRequest(serverType, req, options) {
var module = this;
this.serverType = serverType === 'express' ? 'express' : 'restify';
if (!options) {
options = {};
}
this.params = req ? req.params : options.params || {};
this.query = req ? req.query : options.query || {};
this.headers = req ? req.headers : options.headers || {};
this.body = req ? req.body : options.body || {};
if (this.serverType === 'restify' && this.headers) {
this.capitalizeHeaders();
}
this.get = function(headerName) {
return module.headers[headerName];
};
}
MockedRequest.prototype.capitalizeHeaders = function() {
var newHeaders = {};
var module = this;
Object.keys(this.headers).forEach(function(key) {
var newKey = key.split('-').map(function(item) {
return item.charAt(0).toUpperCase() + item.slice(1);
}).join('-');
newHeaders[newKey] = module.headers[key];
});
this.headers = newHeaders;
};
module.exports = function(serverType, req, options) {
return new MockedRequest(serverType, req, options);
};
|
JavaScript
| 0.999999 |
@@ -431,48 +431,52 @@
his.
-serverType === 'restify' && this.headers
+headers && typeof(this.headers) === 'object'
) %7B%0A
|
29f1d06d2320dc05ba7d608a2bd37147dca72eb0
|
make __filename and __dirname undefined in REPL
|
lib/prelude/node.js
|
lib/prelude/node.js
|
process.argv = require('remote').process.argv
|
JavaScript
| 0.000436 |
@@ -39,8 +39,92 @@
ss.argv%0A
+%0A// in REPL these will be undefined%0Adelete global.__dirname%0Adelete global.__filename
|
0255a60dd6a5c2872a1f728fb4d40715b64b4c98
|
remove dead code
|
lib/preprocessor.js
|
lib/preprocessor.js
|
/**
* Module dependencies.
*/
var assert = require('assert');
var debug = require('debug')('icecast:preprocessor');
/**
* Module exports.
*/
module.exports = preprocessor;
/**
* The fake HTTP version to write when an "ICY" version is encountered.
*/
var HTTP10 = new Buffer('HTTP/1.0');
/**
* This all really... really.. sucks...
*/
function preprocessor (stream) {
// TODO: support new stream API once node's net.Socket supports it
stream.on('data', onData);
stream.realOn = stream.on;
stream.on = stream.addListener = on;
stream.realRemoveListener = stream.removeListener;
stream.removeListener = removeListener;
Object.defineProperty(stream, 'ondata', {
set: setOnData
});
}
/**
* This should be the *only* data listener on the "stream".
*/
function onData (chunk) {
debug('onData (chunk.length: %d)', chunk.length);
if (!this._preprocessedDone) {
// TODO: don't be lazy, buffer if needed...
assert(chunk.length >= 3, 'buffer too small! ' + chunk.length);
if (/icy/i.test(chunk.slice(0, 3))) {
debug('got ICY response!');
var b = new Buffer(chunk.length + HTTP10.length - 'icy'.length);
var i = 0;
i += HTTP10.copy(b);
i += chunk.copy(b, i, 3);
assert.equal(i, b.length);
chunk = b;
}
this._preprocessedDone = true;
}
this.emit('processedData', chunk);
}
function getOnData () {
debug('get "ondata"');
assert(0);
//return this._preprocessedOnData;
}
function setOnData (v) {
debug('set "ondata": %s', v && v.name);
if (this._preprocessedOnData) {
this.removeListener('data', this._preprocessedOnDataListener);
this._preprocessedOnData = null;
this._preprocessedOnDataListener = null;
}
this._preprocessedOnDataListener = function (chunk) {
this._preprocessedOnData(chunk, 0, chunk.length);
};
this.on('data', this._preprocessedOnDataListener);
return this._preprocessedOnData = v;
}
/**
* Overwrite the "on" function to rewrite "data" events to "processedData".
*/
function on (name, fn) {
debug('on: %s', name);
if ('data' == name) {
debug('remapping as "processedData" listener', fn);
name = 'processedData';
}
return this.realOn(name, fn);
}
/**
* Rewrites "data" listeners as "processedData".
*/
function removeListener (name, fn) {
debug('removeListener: %s', name);
if ('data' == name) {
debug('remapping as "processedData" listener', fn);
name = 'processedData';
}
return this.realRemoveListener(name, fn);
}
|
JavaScript
| 0.000619 |
@@ -1366,110 +1366,8 @@
%0A%7D%0A%0A
-function getOnData () %7B%0A debug('get %22ondata%22');%0A assert(0);%0A //return this._preprocessedOnData;%0A%7D%0A%0A
func
|
add769142b65300ae37fc620e5b440c6c6191743
|
Remove unnecessary loop.
|
src/lib/utils/series-utils.js
|
src/lib/utils/series-utils.js
|
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import AbstractSeries from '../plot/series/abstract-series';
import {DISCRETE_COLOR_RANGE, DEFAULT_OPACITY} from '../theme';
/**
* Check if the component is series or not.
* @param {React.Component} child Component.
* @returns {boolean} True if the child is series, false otherwise.
*/
export function isSeriesChild(child) {
const {prototype} = child.type;
return prototype instanceof AbstractSeries;
}
/**
* Get all series from the 'children' object of the component.
* @param {Object} children Children.
* @returns {Array} Array of children.
*/
export function getSeriesChildren(children) {
return React.Children.toArray(children).filter(child =>
child && isSeriesChild(child));
}
/**
* Collect the map of repetitions of the series type for all children.
* @param {Array} children Array of children.
* @returns {{}} Map of repetitions where sameTypeTotal is the total amount and
* sameTypeIndex is always 0.
*/
function collectSeriesTypesInfo(children) {
const result = {};
children.filter(isSeriesChild).forEach(child => {
const {displayName} = child.type;
if (!result[displayName]) {
result[displayName] = {
sameTypeTotal: 0,
sameTypeIndex: 0
};
}
result[displayName].sameTypeTotal++;
});
return result;
}
export function getStackedData(children, attr) {
const childData = [];
children.forEach((child, childIndex) => {
if (!child) {
childData.push(null);
return;
}
const {data} = child.props;
if (!attr || !data || !data.length) {
childData.push(data);
return;
}
const attr0 = `${attr}0`;
childData.push(data.map((d, dIndex) => {
let prevValue = 0;
let prevIndex = childIndex - 1;
while (prevIndex >= 0) {
if (childData[prevIndex]) {
break;
}
prevIndex--;
}
if (prevIndex >= 0) {
const prevD = childData[prevIndex][dIndex];
prevValue = prevD[attr0] + prevD[attr];
}
return {
[attr0]: prevValue,
...d
};
}));
});
return childData;
}
/**
* Get the list of series props for a child.
* @param {Array} children Array of all children.
* @returns {Array} Array of series props for each child. If a child is not a
* series, than it's undefined.
*/
export function getSeriesPropsFromChildren(children) {
const result = [];
const seriesTypesInfo = collectSeriesTypesInfo(children);
let seriesIndex = 0;
const _opacityValue = DEFAULT_OPACITY;
children.forEach(child => {
let props;
if (isSeriesChild(child)) {
const seriesTypeInfo = seriesTypesInfo[child.type.displayName];
const _colorValue = DISCRETE_COLOR_RANGE[seriesIndex %
DISCRETE_COLOR_RANGE.length];
props = {
...seriesTypeInfo,
seriesIndex,
ref: `series${seriesIndex}`,
_colorValue,
_opacityValue
};
seriesTypeInfo.sameTypeIndex++;
seriesIndex++;
}
result.push(props);
});
return result;
}
|
JavaScript
| 0.000001 |
@@ -2504,16 +2504,38 @@
a = %5B%5D;%0A
+ let prevIndex = -1;%0A
childr
@@ -2566,24 +2566,24 @@
Index) =%3E %7B%0A
-
if (!chi
@@ -2862,169 +2862,8 @@
0;%0A
- let prevIndex = childIndex - 1;%0A while (prevIndex %3E= 0) %7B%0A if (childData%5BprevIndex%5D) %7B%0A break;%0A %7D%0A prevIndex--;%0A %7D%0A
@@ -3055,24 +3055,24 @@
.d%0A %7D;%0A
-
%7D));%0A %7D
@@ -3068,16 +3068,44 @@
%7D));%0A
+ prevIndex = childIndex;%0A
%7D);%0A
|
4e0b1d36df37368fe3038fdf0aac2071c17cf730
|
add instrumenter options in confg
|
lib/preprocessor.js
|
lib/preprocessor.js
|
var istanbul = require('istanbul'),
ibrik = require('ibrik'),
ismailia = require('ismailia'),
minimatch = require('minimatch');
var createCoveragePreprocessor = function(logger, basePath, reporters, coverageReporter) {
var log = logger.create('preprocessor.coverage');
var instrumenterOverrides = (coverageReporter && coverageReporter.instrumenter) || {};
var instrumenters = {istanbul: istanbul, ibrik: ibrik, ismailia: ismailia};
// if coverage reporter is not used, do not preprocess the files
if (reporters.indexOf('coverage') === -1) {
return function(content, _, done) {
done(content);
};
}
// check instrumenter override requests
function checkInstrumenters() {
var literal;
for (var pattern in instrumenterOverrides) {
literal = String(instrumenterOverrides[pattern]).toLowerCase();
if (literal !== 'istanbul' && literal !== 'ibrik' && literal !== 'ismailia') {
log.error('Unknown instrumenter: %s', literal);
return false;
}
}
return true;
}
if (!checkInstrumenters()) {
return function(content, _, done) {
return done(1);
};
}
return function(content, file, done) {
log.debug('Processing "%s".', file.originalPath);
var jsPath = file.originalPath.replace(basePath + '/', './');
var instrumenterLiteral = jsPath.match(/\.coffee$/) ? 'ibrik' : 'istanbul';
for (var pattern in instrumenterOverrides) {
if (minimatch(file.originalPath, pattern, {dot: true})) {
instrumenterLiteral = String(instrumenterOverrides[pattern]).toLowerCase();
}
}
var instrumenter = new instrumenters[instrumenterLiteral].Instrumenter();
instrumenter.instrument(content, jsPath, function(err, instrumentedCode) {
if (err) {
log.error('%s\n at %s', err.message, file.originalPath);
}
if (instrumenterLiteral === 'ibrik') {
file.path = file.path.replace(/\.coffee$/, '.js');
}
done(instrumentedCode);
});
};
};
createCoveragePreprocessor.$inject = ['logger',
'config.basePath',
'config.reporters',
'config.coverageReporter'];
module.exports = createCoveragePreprocessor;
|
JavaScript
| 0 |
@@ -449,16 +449,315 @@
mailia%7D;
+%0A var instrumentersOptions = Object.keys(instrumenters).reduce(function getInstumenterOptions(memo, instrumenterName)%7B%0A memo%5BinstrumenterName%5D = (coverageReporter && coverageReporter.instrumenterOptions && coverageReporter.instrumenterOptions%5BinstrumenterName%5D) %7C%7C %7B%7D;%0A return memo;%0A %7D, %7B%7D);
%0A%0A // i
@@ -1981,16 +1981,57 @@
umenter(
+instrumentersOptions%5BinstrumenterLiteral%5D
);%0A%0A
|
aaaa183d119dcf39054b1aa6395878f75a78cae7
|
Make error passthrough explicit
|
lib/process-tree.js
|
lib/process-tree.js
|
// Copyright (c) 2017 The Regents of the University of Michigan.
// All Rights Reserved. Licensed according to the terms of the Revised
// BSD License. See LICENSE.txt for details.
let treeNode = (address, setUp) => new Promise(
function(resolveNode, rejectNode) {
let internal = {};
let payload = {};
let runnableNode = {};
internal.errors = [];
internal.children = [];
internal.addLogger = function(logger) {
payload.log = newAddressedLogFunction(address, logger);
};
payload.runBefore = () => {};
payload.run = () => {};
payload.runAfter = () => {};
payload.add = function(childSetUp) {
internal.children.push(
treeNode(address.concat(internal.children.length),
childSetUp))
};
runnableNode.run = logger => new Promise(
function(resolveRun, rejectRun) {
internal.addLogger(logger);
payload.log("begin");
let runningChildren = [];
let throwError = function() {
rejectRun({
description: "root",
children: {length: 2},
messages: []
});
};
Promise.resolve(payload.runBefore()).then(function() {
return Promise.resolve(payload.run());
}, function(error) {
rejectRun();
}).then(function() {
for (let child of runnableNode.children)
runningChildren.push(child.run(logger));
return Promise.all(runningChildren);
}, function(error) {
rejectRun();
}).then(function() {
return Promise.resolve(payload.runAfter());
}, function(error) {
let errorResolutions = [];
let childErrors = [];
for (let child of runningChildren) {
errorResolutions.push(new Promise(function(resolveError) {
child.then(function(value) {
resolveError();
}, function(childError) {
childErrors.push(childError);
resolveError();
});
}));
}
return new Promise(function(good, bad) {
Promise.all(errorResolutions).then(function(value) {
let result = {
description: "root",
children: childErrors,
messages: []
};
bad(result);
});
});
}).then(function() {
payload.log("done");
resolveRun();
}, passError(throwError));
});
runAndWait(function() { setUp(payload); }).then(function(value) {
return Promise.all(internal.children);
}, function(error) {
internal.errors.push(error);
return Promise.all(internal.children);
}).then(function(childIterator) {
runnableNode.children = [...childIterator];
runnableNode.getLogTree = function() {
let result = {};
if (payload.description)
result.d = payload.description;
result.c = [];
for (let leaf of runnableNode.children)
result.c.push(leaf.getLogTree());
return result;
};
if (internal.errors.length == 0)
resolveNode(runnableNode);
else
rejectNode({
description: payload.description,
messages: internal.errors,
children: []
});
}, function(error) {
let errorResolutions = [];
let childErrors = [];
for (let child of internal.children) {
errorResolutions.push(new Promise(function(resolveError) {
child.then(function(value) {
resolveError();
}, function(childError) {
childErrors.push(childError);
resolveError();
});
}));
}
Promise.all(errorResolutions).then(function(value) {
rejectNode({
description: payload.description,
messages: internal.errors,
children: childErrors
});
});
});
});
let newAddressedLogFunction = (address, logger) =>
(code, message) => new Promise((resolve, reject) => {
let fullMessage = [Date.now(), code].concat(address);
fullMessage.push(message || "");
Promise.resolve(logger.log(fullMessage)).then(value => {
resolve(value);
}, passError(reject));
});
let passError = function(reject) {
return function(error) {
reject(error);
};
};
let runAndWait = function(thingToRun) {
try {
return Promise.resolve(thingToRun());
} catch (error) {
return Promise.reject(error);
}
};
module.exports = (newLogger, setUp) => new Promise(
function(resolve, reject) {
treeNode([], setUp).then(function(root) {
let logger = newLogger(root.getLogTree());
logger.storeProcess(root.run(logger));
resolve(logger);
}, passError(reject));
});
|
JavaScript
| 0.000009 |
@@ -2273,29 +2273,55 @@
%7D,
-passError(throwError)
+function(error) %7B%0A rejectRun(error);%0A %7D
);%0A
|
42f31400e024492dce692a9590e67295734858e1
|
Fix break duration was null if start not set
|
lib/commands.js
|
lib/commands.js
|
'use strict'
// packages
const moment = require('moment')
// ours
const db = require('./db.js')
const helpers = require('./utils/helpers.js')
const spinner = require('./utils/spinner.js')
const configManager = require('./utils/configManager.js')
// constants
const TODAY = moment().format('YYYY-MM-DD')
const NOW = moment().format('HH:mm')
// constants has real un-changeable stuff, they are read-only
const constants = require('./constants.json')
// determine whether to setStart | setEnd | report
// based on entered information in database
const nextUndoneAction = (args, options, logger) => {
db.getDateReport(TODAY, db.knex)
.then((data) => {
if (data && !data.start) {
setStart(args, options, logger)
return
}
if (data && !data.end) {
setEnd(args, options, logger)
return
}
if (data && data.start && data.end) {
report(args, options, logger)
return
}
// this one is for when we don't even have the database
setStart(args, options, logger)
})
}
const setStart = (args, options, logger) => {
const start = args.start || NOW
configManager.configLoaded()
.then((config) => {
const payload = {
date: TODAY,
start,
breakDuration: config.BREAK_DEFAULT,
action: 'setStart'
}
// update database
db.updateDatabase(payload, db.knex)
.then(() => {
spinner.succeed(`Your start of the day registered as ${start}\n\n`).start()
helpers.shouldWorkUntil(start, config)
spinner.info('TIP: next time you run moro the end of your day will be set\n')
})
.catch(spinner.fail)
.finally(() => { process.exit(0) })
})
.catch(spinner.fail)
}
// set total duration of break for today
const setBreak = (args, options, logger) => {
const duration = args.duration
spinner.succeed(`Break took: ${duration} minutes and will be removed from your work hours\n`).start()
const payload = {
date: TODAY,
breakDuration: duration,
action: 'setBreakDuration'
}
db.updateDatabase(payload, db.knex)
.catch(spinner.fail)
.then(() => { report() })
}
// report functionality for both single and batch reporting
const report = (args, options, logger, date) => {
date = date || TODAY
configManager.configLoaded()
.then((config) => {
if (options && options.all) {
db
.getFullReport(db.knex, config)
.catch(spinner.fail)
.finally(() => { process.exit(0) })
return
}
db
.calculateWorkHours(date, db.knex)
.then((result) => {
db.getDateReport(TODAY, db.knex)
.then((data) => {
if (data && result) {
data.dayReport = helpers.formatWorkHours(result.workHours)
const table = helpers.printSingleDayReport(data)
spinner.info('Today looks like this so far:\n')
// renders the table
console.log(table)
spinner.info('Run moro --help if you need to edit your start, end or break duration for today\n')
process.exit(0)
}
})
.catch(spinner.fail)
})
.catch(spinner.fail)
})
}
// set the configuration in the config file
const setConfig = (args, options, logger) => {
configManager.configLoaded()
.then((config) => {
if (options.day) {
config.HOURS_IN_A_WORK_DAY = options.day
spinner.succeed(`Duration of full work day is set to ${options.day}\n`)
}
if (options.break) {
config.BREAK_DEFAULT = options.break
spinner.succeed(`Default break duration is set to ${options.break}\n`)
}
if (options.format) {
config.DATE_FORMAT = options.format
spinner.succeed(`Default date format pattern is set to ${options.format}\n`)
}
// check, if value is set ('' is falsy but denotes default path)
if (options.databasePath && options.databasePath.hasOwnProperty('value')) {
config.DB_FILE_MAIN = options.databasePath.value
// make sure the correct result is logged
const dbPath = options.databasePath.value !== ''
? options.databasePath.value
: 'default'
spinner.succeed(`Default database path is set to ${dbPath}\n`)
}
configManager.setConfig(config)
})
.catch(spinner.fail)
.finally(() => process.exit(0))
}
// set end of the work day
const setEnd = (args, options, logger) => {
const end = args.end || NOW
spinner.succeed(`Your end of the work day is set at: ${end}\n`)
const payload = {
date: TODAY,
end,
action: 'setEnd'
}
db
.updateDatabase(payload, db.knex)
.then(() => { report() })
}
const clearData = (args, options, logger, spinner) => {
if (options && options.yes) {
return db.removeDatabase()
}
spinner.warn('[BE CAREFUL] If you surely want to clear all data in moro run: moro clear --yes\n')
process.exit()
}
const addNote = (args, options, logger) => {
let note = args.note || '...'
note = note.join(' ')
const createdat = NOW
const payload = {
date: TODAY,
note,
createdat,
action: 'addNote'
}
db.updateDatabase(payload, db.knex)
.then(() => report())
.catch(spinner.fail)
.finally(() => {
spinner.succeed('Your note is added! You can see it in report \\o/ ').start()
})
}
const about = (args, options, logger) => {
spinner.stopAndPersist().start()
spinner.info(constants.TEXT.about)
process.exit()
}
module.exports = {
nextUndoneAction,
setConfig,
setEnd,
setStart,
setBreak,
addNote,
report,
clearData,
about
}
|
JavaScript
| 0.000004 |
@@ -5167,24 +5167,83 @@
tedat = NOW%0A
+ configManager.configLoaded()%0A .then((config) =%3E %7B%0A
const payl
@@ -5246,32 +5246,36 @@
payload = %7B%0A
+
+
date: TODAY,%0A
@@ -5279,14 +5279,22 @@
+
+
note,%0A
+
@@ -5304,24 +5304,28 @@
atedat,%0A
+
+
action: 'add
@@ -5329,21 +5329,74 @@
addNote'
-%0A %7D%0A
+,%0A breakDuration: config.BREAK_DEFAULT%0A %7D%0A
db.upd
@@ -5417,32 +5417,36 @@
yload, db.knex)%0A
+
.then(() =%3E
@@ -5455,16 +5455,20 @@
port())%0A
+
.cat
@@ -5480,32 +5480,36 @@
inner.fail)%0A
+
+
.finally(() =%3E %7B
@@ -5505,24 +5505,28 @@
lly(() =%3E %7B%0A
+
spinne
@@ -5597,25 +5597,56 @@
start()%0A
-%7D
+ %7D)%0A %7D).catch(spinner.fail
)%0A%7D%0A%0Aconst a
|
b07b8f7f7d0d773c146ef4ef7e8e4d9b81eecef4
|
add thought id to thought
|
app/facilitator/reciever.controller.js
|
app/facilitator/reciever.controller.js
|
(function () {
'use strict';
/**
* @ngdoc overview
* @name app
* @description
* # The...
*/
angular.module('app')
.controller('RecieverController', RecieverController);
RecieverController.$inject = ['$scope', '$modal', '$log', 'ThoughtSocket',
'UserService', '$location', '$routeParams', '$rootScope', '$timeout', 'toastr'];
function RecieverController($scope, $modal, $log, ThoughtSocket,
UserService, $location, $routeParams, $rootScope, $timeout, toastr) {
(function initController() {
$scope.participantThoughts = [];
// $scope.topic = '';
$scope.prompt = {};
//$scope.participantThoughts.length = 0;
$scope.numSubmitters = 0;
$scope.numConnected = 0;
$scope.dataLoading = true;
ThoughtSocket.emit('facilitator-join', {
groupId: $routeParams.groupId,
userId: UserService.user.id
});
// ThoughtSocket.emit('session-sync-req', {
// user: UserService.user,
// groupId: $routeParams.groupId,
// sessionId: $scope.sessionId
// });
})();
ThoughtSocket.on('facilitator-prompt', function (data) {
console.log('facilitator-prompt', data);
$scope.prompt = data;
toastr.success('', 'New Prompt Created');
});
ThoughtSocket.on('participant-join', function () {
console.log('participant-join');
$scope.numConnected++;
});
ThoughtSocket.on('participant-leave', function () {
console.log('participant-leave');
$scope.numConnected--;
});
ThoughtSocket.on('sessionsyncres', function (data) {
console.log("Recieved session sync response:", data);
// $scope.participantThoughts = data.prompt.get('thoughts'); //TODO: at somepoint sync should send us the existing thoughts if we're late joining
$scope.prompt = data.prompt;
$scope.sessionId = data.sessionId;
// $scope.numThoughts = data.prompt.thoughts.length();
// $scope.numSubmitters = ?
});
// $rootScope.$on("$routeChangeStart", function () {
// console.log('leaving fac');
// ThoughtSocket.emit('facilitator-leave');
// });
$scope.newSession = function () {
$scope.participantThoughts = [];
//$scope.numThoughts = 0;
$scope.numSubmitters = 0;
ThoughtSocket.emit('session-sync-req', {
user: UserService.user,
groupId: $routeParams.groupId,
sessionId: $scope.sessionId
});
newPrompt();
toastr.sucess('', 'Starting New Session');
};
function newPrompt() {
// $scope.topic = ''; //erase previous prompt
}
$scope.openPromptInput = function () {
// $scope.newSession();
var modalInstance = $modal.open({
animation: true,
templateUrl: 'facilitator/promptModal.html', // see script in reciever.html
controller: 'PromptModalController',
resolve: {
prompt: function() {
return $scope.prompt;
},
sessionId: function () {
return $scope.sessionId;
}
}
});
modalInstance.result.then(function (newPromptContent) {
$scope.prompt = {};
$scope.prompt.content = newPromptContent;
});
};
$scope.highlightForDeletion = function (idx) {
console.log('high', idx);
$scope.highlight = idx;
};
$scope.unHighlightForDeletion = function () {
console.log('unhigh');
$scope.highlight = -1;
};
ThoughtSocket.on('participant-thought', function (participantThought) {
$scope.participantThoughts.push(participantThought);
$scope.numThoughts++;
var submitters = [];
$scope.participantThoughts.forEach(function (thought) {
console.log(thought);
if (submitters.indexOf(thought.userId) < 0) {
submitters.push(thought.userId);
}
});
$scope.numSubmitters = submitters.length;
});
$scope.distribute = function () {
toastr.success('', 'Thoughts Distributed!');
console.log('should distribute in future NOT IMPLEMENTED!', $scope.prompt);
ThoughtSocket.emit('distribute', {
groupId: $routeParams.groupId,
promptId: $scope.prompt.id
});
};
$scope.deleteThought = function (thoughtIndex) {
console.log('i should delete the thought at position', thoughtIndex, 'in $scope.participantThoughts');
var removed = $scope.participantThoughts.splice(thoughtIndex, 1);
if (removed.length > 0) {
ThoughtSocket.emit('fac-delete-thought', {
thoughtId: removed[0].id
});
}
};
};
/**
* @ngdoc The controller for the modal that handles prompt input.
* @name PromptModal
* @description
* # From Docs: Please note that $modalInstance represents a modal
* window (instance) dependency. It is not the same as the $modal
* service used above.
* # Included within this controller file because it
* is tightly related to the above controller
*/
angular.module('app')
.controller('PromptModalController', PromptModalController);
PromptModalController.$inject = ['$scope', '$modalInstance', 'sessionId', 'ThoughtSocket', 'UserService', '$routeParams'];
function PromptModalController($scope, $modalInstance, sessionId, ThoughtSocket, UserService, $routeParams) {
// $scope.prompt = prompt;
$scope.newPromptContent = '';
$scope.sessionId = sessionId
$scope.submit = function () {
console.log("Submit works");
console.log('current user:', UserService.user);
$modalInstance.close($scope.newPromptContent);
ThoughtSocket.emit('new-prompt', {
prompt: $scope.newPromptContent,
userId: UserService.user.id,
groupId: $routeParams.groupId,
sessionId: $scope.sessionId
});
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
})();
|
JavaScript
| 0 |
@@ -3299,24 +3299,60 @@
tThought) %7B%0A
+%09%09%09console.log(participantThought);%0A
%09%09%09$scope.pa
@@ -4315,16 +4315,151 @@
%7D%0A%09%09%7D;%0A%0A
+%09%09$scope.displayThought = function (thought) %7B%0A%09%09%09return '%3Cspan class=%22thought-id%22%3E' + thought.id + '%3C/span%3E' + thought.content;%0A%09%09%7D;%0A%0A
%09%7D;%0A%0A%09/*
|
17da80fdb21d2828ac469e646d4237fdb41087ba
|
use Symbol to store event handlers
|
lib/eventtarget.js
|
lib/eventtarget.js
|
import { Assembler } from 'esmodule'
const { CustomEvent, EventTarget } = window
const { getTargetOf } = Assembler
/**
* @param {{capture,once,passive,context}|boolean|EventTargetAssembler|*} [options]
* @param {boolean} [options.capture]
* @param {boolean} [options.once]
* @param {boolean} [options.passive]
* @param {EventTargetAssembler} [options.context]
* @returns {{capture,once,passive,context}}
* @private
*/
function getOptions(options) {
if(options) {
if(typeof options === 'boolean') {
return { capture : true }
}
if(options instanceof EventTargetAssembler) {
return { context : options }
}
return Object.assign({}, options)
}
return {}
}
/**
* @see https://www.w3.org/TR/dom/#interface-eventtarget
*/
export class EventTargetAssembler extends Assembler {
/**
* @param {*} [init]
* @returns {EventTarget|*}
*/
assemble(init) {
Object.defineProperty(this, '__event_handlers__', {
value : { true : {}, false : {} }
})
return super.assemble(init)
}
/**
* @param {Event|string|*} eventOrType
* @param {CustomEventInit|{}} [eventInitDict]
* @param {boolean} [eventInitDict.bubbles]
* @param {boolean} [eventInitDict.cancelable]
* @param {*} [eventInitDict.detail]
* @returns {boolean}
*/
emit(eventOrType, eventInitDict) {
if(typeof eventOrType === 'string') {
eventOrType = new CustomEvent(eventOrType, eventInitDict)
}
return getTargetOf(this).dispatchEvent(eventOrType)
}
/**
* @param {string} type
* @param {function} callback
* @param {{capture,once,passive,context}|boolean|EventTargetAssembler|*} [options]
* @param {boolean} [options.capture]
* @param {boolean} [options.once]
* @param {boolean} [options.passive]
* @param {EventTargetAssembler} [options.context]
*/
on(type, callback, options) {
const { context = this, capture } = options = getOptions(options)
const handlers = context.__event_handlers__[Boolean(capture)]
const map = handlers[type] || (handlers[type] = new Map)
if(!map.has(callback)) {
delete options.context
map.set(callback, callback = callback.bind(context))
getTargetOf(this).addEventListener(type, callback, options)
}
}
/**
* @param {string} type
* @param {function} callback
* @param {{capture,context}|boolean|EventTargetAssembler|*} [options]
* @param {boolean} [options.capture]
* @param {EventTargetAssembler} [options.context]
*/
un(type, callback, options) {
const { context = this, capture } = options = getOptions(options)
const map = context.__event_handlers__[Boolean(capture)][type]
if(map && map.has(callback)) {
delete options.context
getTargetOf(this).removeEventListener(type, map.get(callback), options)
map.delete(callback)
}
}
/**
* @returns {EventTarget}
* @override
*/
static create() {
return new EventTarget
}
/**
* @returns {interface} EventTarget
* @override
*/
static get interface() {
return EventTarget
}
}
|
JavaScript
| 0.000001 |
@@ -108,16 +108,41 @@
ssembler
+%0Aconst storage = Symbol()
%0A%0A/**%0A *
@@ -981,79 +981,23 @@
-Object.defineProperty(this, '__event_handlers__', %7B%0A value :
+this%5Bstorage%5D =
%7B t
@@ -1023,19 +1023,8 @@
%7D %7D%0A
- %7D)%0A
@@ -2054,35 +2054,25 @@
context
-.__event_handlers__
+%5Bstorage%5D
%5BBoolean
@@ -2758,27 +2758,17 @@
text
-.__event_handlers__
+%5Bstorage%5D
%5BBoo
|
86cacd5938c50fe972c2edd4d6e9e4161eb1bc25
|
Update tests
|
test/CalendarMonthDropdownSpec.js
|
test/CalendarMonthDropdownSpec.js
|
import React from 'react';
import { findDOMNode } from 'react-dom';
import moment from 'moment';
import ReactTestUtils from 'react-dom/test-utils';
import MonthDropdown from '../src/Calendar/MonthDropdown';
describe('Calendar-MonthDropdown', () => {
it('Should output year and month ', () => {
const date = moment();
const size = (date.year() - 1950) + 6;
const instance = ReactTestUtils.renderIntoDocument(
<MonthDropdown date={date} />
);
const node = findDOMNode(instance);
assert.equal(node.querySelectorAll('.rs-picker-calendar-month-dropdown-year').length, size);
});
it('Should call `onSelect` callback ', (done) => {
const date = moment();
const doneOp = () => {
done();
};
const instance = ReactTestUtils.renderIntoDocument(
<MonthDropdown date={date} onSelect={doneOp} />
);
const instanceDOM = findDOMNode(instance);
ReactTestUtils.Simulate.click(instanceDOM.querySelector('.rs-picker-calendar-month-dropdown-cell'));
});
it('Should have a custom className', () => {
const instance = ReactTestUtils.renderIntoDocument(
<MonthDropdown className="custom" />
);
assert.ok(findDOMNode(instance).className.match(/\bcustom\b/));
});
it('Should have a custom style', () => {
const fontSize = '12px';
const instance = ReactTestUtils.renderIntoDocument(
<MonthDropdown style={{ fontSize }} />
);
assert.equal(findDOMNode(instance).style.fontSize, fontSize);
});
});
|
JavaScript
| 0.000001 |
@@ -323,51 +323,8 @@
t();
-%0A const size = (date.year() - 1950) + 6;
%0A%0A
@@ -555,12 +555,10 @@
th,
-size
+11
);%0A
|
589d8c59f60ca573bc4786e76a5033b35fb7452d
|
Use the axios base for opening the auth window
|
app/main-process/userAuthentication.js
|
app/main-process/userAuthentication.js
|
import axios from "axios"
import keytar from "keytar"
import { BrowserWindow, session } from "electron"
const { URL } = require("url")
const { trackEvent } = require("./analytics")
let authWindow
export function authorizeUser(mainWindowRef, protocolHandler) {
openAuthWindow(mainWindowRef, protocolHandler)
}
export async function setAccessTokenFromCode(code, mainWindow) {
if (authWindow) {
authWindow.destroy()
}
// TODO: Error handling
try {
const token = await fetchAccessToken(code)
await keytar.setPassword("Classroom-Assistant", "x-access-token", token)
global.accessToken = token
mainWindow.webContents.send("receivedAuthorization")
} catch (error) {
trackEvent("error", "userAuthentication", "fetchAccessToken", error)
}
}
export async function loadAccessToken() {
global.accessToken = await keytar.getPassword(
"Classroom-Assistant",
"x-access-token"
)
}
export async function deleteAccessToken() {
global.accessToken = null
await keytar.deletePassword("Classroom-Assistant", "x-access-token")
}
function openAuthWindow(mainWindow, protocolHandler) {
authWindow = new BrowserWindow({
height: 650,
width: 400,
show: false,
parent: mainWindow,
webPreferences: {
session: session.fromPartition("auth:session"),
nodeIntegration: false,
},
})
const authURL = new URL("/login/oauth/authorize")
authWindow.webContents.loadURL(authURL.toString())
authWindow.once("ready-to-show", () => {
if (authWindow) {
authWindow.show()
}
})
}
async function fetchAccessToken(code) {
const accessTokenURL = `/login/oauth/access_token?code=${code}`
const response = await axios.post(accessTokenURL, {
"Content-Type": "application/json; charset=utf-8",
Accept: "application/json",
})
return response.data.access_token
}
|
JavaScript
| 0 |
@@ -1370,17 +1370,42 @@
new URL(
-%22
+%60$%7Baxios.defaults.baseURL%7D
/login/o
@@ -1418,17 +1418,17 @@
uthorize
-%22
+%60
)%0A%0A aut
|
9b8be30405f4920df878478a1d6f1f646833cbbe
|
add assignee & priority on changelog schema
|
app/models/schemas/changelog_schema.js
|
app/models/schemas/changelog_schema.js
|
'use strict';
/**
* @module ChangeLog
* @name ChangeLog
* @description A record(log) of a changes on a service request(issue).
*
* It may be status, priority, assignee change, private or public
* comments etc.
*
* @see {@link Party}
* @see {@link ServiceRequest}
* @see {@link Status}
* @see {@link Priority}
* @author lally elias <[email protected]>
* @since 0.1.0
* @version 0.1.0
* @public
*/
//dependencies
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;
//constants
// const VISIBILITY_PUBLIC = 'Public';
// const VISIBILITY_PRIVATE = 'Private';
/**
* @name ChangeLogSchema
* @type {Schema}
* @since 0.1.0
* @version 0.1.0
* @private
*/
const ChangeLogSchema = new Schema({
/**
* @name status
* @description A current assigned status
* @type {Object}
* @see {@link Status}
* @private
* @since 0.1.0
* @version 0.1.0
*/
status: {
type: ObjectId,
ref: 'Status',
required: true,
index: true,
autoset: true,
exists: true,
autopopulate: true
},
/**
* @name priority
* @description A current assigned priority
* @type {Object}
* @see {@link Priority}
* @private
* @since 0.1.0
* @version 0.1.0
*/
priority: {
type: ObjectId,
ref: 'Priority',
required: true,
index: true,
autoset: true,
exists: true,
autopopulate: true
},
/**
* @name changer
* @description A party whose made changes
* @type {Object}
* @see {@link Party}
* @private
* @since 0.1.0
* @version 0.1.0
*/
changer: {
type: ObjectId,
ref: 'Party',
required: true,
index: true,
autoset: true,
exists: true,
autopopulate: {
select: 'name email phone'
}
},
/**
* @name remarks
* @description A note provided by a change when changing a status
* @type {Object}
* @private
* @since 0.1.0
* @version 0.1.0
*/
remarks: {
type: String,
index: true,
trim: true,
searchable: true
},
/**
* @name notify
* @description Signal to send remarks to a service request(issue) reporter
* using sms, email etc.
* @type {Object}
* @private
* @since 0.1.0
* @version 0.1.0
*/
notify: {
type: Boolean,
default: false
}
}, { timestamps: true, emitIndexErrors: true });
/**
* @name ChangeLogSchema
* @description exports duration schema
* @type {Schema}
* @since 0.1.0
* @version 0.1.0
* @public
*/
module.exports = exports = ChangeLogSchema;
|
JavaScript
| 0 |
@@ -1462,32 +1462,432 @@
te: true%0A %7D,%0A%0A%0A
+ /**%0A * @name assignee%0A * @description A current assigned party to work on service request(issue)%0A * @type %7BObject%7D%0A * @see %7B@link Priority%7D%0A * @private%0A * @since 0.1.0%0A * @version 0.1.0%0A */%0A assignee: %7B%0A type: ObjectId,%0A ref: 'Party',%0A required: true,%0A index: true,%0A autoset: true,%0A exists: true,%0A autopopulate: %7B%0A select: 'name email phone'%0A %7D%0A %7D,%0A%0A%0A
/**%0A * @name
@@ -1895,16 +1895,16 @@
changer%0A
-
* @de
@@ -2496,16 +2496,62 @@
e%0A %7D,%0A%0A
+ //TODO find best strategy for notifications%0A
/**%0A
@@ -2762,16 +2762,16 @@
0%0A */%0A
-
notify
@@ -2812,16 +2812,249 @@
: false%0A
+ %7D,%0A%0A /**%0A * @name isPublic%0A * @description Signal if service request(issue) is public viewable.%0A * @type %7BObject%7D%0A * @private%0A * @since 0.1.0%0A * @version 0.1.0%0A */%0A isPublic: %7B%0A type: Boolean,%0A default: false%0A
%7D%0A%0A%7D,
|
c7e98b0db1a309c5f8d50a6e2f557f1c3626bd03
|
Remove redundant TODO.
|
lib/query_parser.js
|
lib/query_parser.js
|
lunr.QueryParser = function (str, query) {
this.lexer = new lunr.QueryLexer (str)
this.query = query
this.currentClause = {}
this.lexemeIdx = 0
}
lunr.QueryParser.prototype.parse = function () {
this.lexer.run()
this.lexemes = this.lexer.lexemes
var state = lunr.QueryParser.parseFieldOrTerm
while (state) {
state = state(this)
}
return this.query
}
lunr.QueryParser.prototype.peekLexeme = function () {
return this.lexemes[this.lexemeIdx]
}
lunr.QueryParser.prototype.consumeLexeme = function () {
var lexeme = this.peekLexeme()
this.lexemeIdx += 1
return lexeme
}
lunr.QueryParser.prototype.nextClause = function () {
var completedClause = this.currentClause
this.query.clause(completedClause)
this.currentClause = {}
}
lunr.QueryParser.parseFieldOrTerm = function (parser) {
var lexeme = parser.peekLexeme()
if (lexeme == undefined) {
return
}
switch (lexeme.type) {
case lunr.QueryLexer.FIELD:
return lunr.QueryParser.parseField
case lunr.QueryLexer.TERM:
return lunr.QueryParser.parseTerm
default:
var errorMessage = "expected either a field or a term, found " + lexeme.type + " with value '" + lexeme.str + "'"
throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end)
}
}
lunr.QueryParser.parseField = function (parser) {
var lexeme = parser.consumeLexeme()
if (lexeme == undefined) {
return
}
// TODO: check for valid field name
if (parser.query.allFields.indexOf(lexeme.str) == -1) {
var possibleFields = parser.query.allFields.map(function (f) { return "'" + f + "'" }).join(),
errorMessage = "unrecognised field '" + lexeme.str + "', possible fields: " + possibleFields
throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end)
}
parser.currentClause.fields = [lexeme.str]
var nextLexeme = parser.peekLexeme()
if (nextLexeme == undefined) {
var errorMessage = "expecting term, found nothing"
throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end)
}
switch (nextLexeme.type) {
case lunr.QueryLexer.TERM:
return lunr.QueryParser.parseTerm
default:
throw "unexpected asdf"
}
}
lunr.QueryParser.parseTerm = function (parser) {
var lexeme = parser.consumeLexeme()
if (lexeme == undefined) {
return
}
parser.currentClause.term = lexeme.str
if (lexeme.str.indexOf("*") != -1) {
parser.currentClause.usePipeline = false
}
var nextLexeme = parser.peekLexeme()
if (nextLexeme == undefined) {
parser.nextClause()
return
}
switch (nextLexeme.type) {
case lunr.QueryLexer.TERM:
parser.nextClause()
return lunr.QueryParser.parseTerm
case lunr.QueryLexer.FIELD:
parser.nextClause()
return lunr.QueryParser.parseField
case lunr.QueryLexer.EDIT_DISTANCE:
return lunr.QueryParser.parseEditDistance
case lunr.QueryLexer.BOOST:
return lunr.QueryParser.parseBoost
default:
throw "unexepected"
}
}
lunr.QueryParser.parseEditDistance = function (parser) {
var lexeme = parser.consumeLexeme()
if (lexeme == undefined) {
return
}
var editDistance = parseInt(lexeme.str, 10)
if (isNaN(editDistance)) {
var errorMessage = "edit distance must be numeric, found '" + lexeme.str + "'"
throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end)
}
parser.currentClause.editDistance = editDistance
var nextLexeme = parser.peekLexeme()
if (nextLexeme == undefined) {
parser.nextClause()
return
}
switch (nextLexeme.type) {
case lunr.QueryLexer.TERM:
parser.nextClause()
return lunr.QueryParser.parseTerm
case lunr.QueryLexer.FIELD:
parser.nextClause()
return lunr.QueryParser.parseField
case lunr.QueryLexer.EDIT_DISTANCE:
return lunr.QueryParser.parseEditDistance
case lunr.QueryLexer.BOOST:
return lunr.QueryParser.parseBoost
default:
throw "unexepected"
}
}
lunr.QueryParser.parseBoost = function (parser) {
var lexeme = parser.consumeLexeme()
if (lexeme == undefined) {
return
}
var boost = parseInt(lexeme.str, 10)
if (isNaN(boost)) {
var errorMessage = "boost must be numeric, found '" + lexeme.str + "'"
throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end)
}
parser.currentClause.boost = boost
var nextLexeme = parser.peekLexeme()
if (nextLexeme == undefined) {
parser.nextClause()
return
}
switch (nextLexeme.type) {
case lunr.QueryLexer.TERM:
parser.nextClause()
return lunr.QueryParser.parseTerm
case lunr.QueryLexer.FIELD:
parser.nextClause()
return lunr.QueryParser.parseField
case lunr.QueryLexer.EDIT_DISTANCE:
return lunr.QueryParser.parseEditDistance
case lunr.QueryLexer.BOOST:
return lunr.QueryParser.parseBoost
default:
throw "unexepected"
}
}
|
JavaScript
| 0.000007 |
@@ -1423,46 +1423,8 @@
%7D%0A%0A
- // TODO: check for valid field name%0A
if
|
ebd87ae4a989d54ef98dd3493bec9743c77e2a70
|
Fix logic for disabling admin check in login
|
lib/fogin/index.js
|
lib/fogin/index.js
|
/*
Copyright 2013 Mozilla Foundation
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.
*/
/**
* A Fake Login server (i.e., Fogin). The idea is to simulate MongoDB
* while still retaining the routes and internal logic.
*
* This module exposes two functions, `start` and `stop`. These are used
* to control an instance of Fogin. The `start` function takes two args:
*
* Fogin.start( options, callback );
*
* where `options` should have a username, password, and port. The username
* and password pair are used for HTTP basic auth. You can also provide an
* array of logins, with data for users to be insterted into the fake login
* server:
*
* Fogin.start({
* port: 5555,
* username: "someone",
* password: "secret",
* logins: [
* {
* email: "[email protected]",
* subdomain: "admin",
* fullName: "An Admin",
* isAdmin: true
* },
* {
* email: "[email protected]",
* subdomain: "notadmin",
* fullName: "Not Admin",
* isAdmin: false
* }
* ]
* }, function() { ... });
*
*/
var express = require( "express" ),
server,
loginStore = {};
// Simulate login store. If you want to add items, do it in start().
function createLogin( user ) {
console.log('user', user);
var now = Date.now();
loginStore[ user.email ] = {
_id: user.email,
email: user.email,
subdomain: user.subdomain || "default",
fullName: user.fullName || "default",
displayName: user.fullName || "default",
createdAt: now,
updatedAt: now,
deletedAt: null,
isAdmin: !!user.isAdmin,
isSuspended: user.isSuspended === true,
sendNotifications: user.sendNotifications === true,
sendEngagements: user.sendEngagements === true
};
}
module.exports = {
start: function( options, callback ) {
options = options || {};
options.username = options.username || "username";
options.password = options.password || "password";
callback = callback || function(){};
var port = options.port || 5234,
app = express(),
defaultLogin = {
email: "[email protected]",
subdomain: "subdomain",
fullName: "John Smith",
isAdmin: true
},
isAdminCheck = options.isAdminCheck !== false,
logins = options.logins || [ defaultLogin ],
basicAuth = express.basicAuth( function ( username, password ) {
return (username === options.username && password === options.password);
});
app.use( express.logger( "dev" ) );
app.use( express.bodyParser() );
// App GET USER
app.get( '/user/:id', basicAuth, function ( req, res ) {
var id = req.params.id,
login = loginStore[ id ];
if ( !login ) {
res.json( 404, { error: "User not found for ID: " + id, user: null } );
} else {
res.json({ user: login });
}
});
// App isAdmin
app.get( '/isAdmin', basicAuth, function ( req, res ) {
var id = req.query.id,
login = loginStore[ id ];
// If we were asked to not perform admin check, always return true
if ( !isAdminCheck ) {
res.json({ error: null, isAdmin: true });
}
if ( !login ) {
res.json( 404, { error: "User not found for ID: " + id, user: null } );
} else {
res.json({ error: null, isAdmin: login.isAdmin });
}
});
server = app.listen( port, function( req, res ) {
logins.forEach( function( user ) {
createLogin( user );
});
callback();
});
},
stop: function( callback ) {
callback = callback || function(){};
if ( !server ) {
return;
}
server.close( function() {
server = null;
callback();
});
}
};
|
JavaScript
| 0 |
@@ -2768,18 +2768,8 @@
heck
- !== false
,%0A
|
dadcb10ea5ca0f6051ad9873d8987af6b102371d
|
Update form_chunks.js
|
lib/form_chunks.js
|
lib/form_chunks.js
|
/* form chunks */
module.exports = function form_chunks(size,no,arr){
let chunk = [],final = [], k = 0;
for(let i=0; i<no; i++){
chunk = [];
for(let j=0; j<size; j++){
chunk[j] = arr[k++];
if(k>=arr.length) k=0;
}
final.push(chunk);
}
return final;
}
|
JavaScript
| 0.000001 |
@@ -8,16 +8,17 @@
chunks
+
*/%0Amodul
@@ -316,8 +316,9 @@
final;%0A%7D
+%0A
|
b50a20acf321b52cc4a2f97447ffdbed482b44ed
|
Update cruncher.js
|
lib/cruncher.js
|
lib/cruncher.js
|
var _ = require('lodash')
var fs = require('fs')
var tonal = require('tonal')
var wav = require('node-wav')
var Pitchfinder = require('pitchfinder')
LSDJ = {
constants: {
SAMPLES_PER_FRAMES: 32,
FRAMES_PER_TABLE: 16,
FRAME_RESOLUTION: 16
}
}
module.exports = function(wave, note, options) {
// default options
options = options || {}
options = {
channel: options.channel || 0,
normalize: options.normalize,
linear: options.linear,
exp: options.exp
}
// get frequency
// auto-detect if argument is "auto"
if (note == "auto") {
const detectPitch = new Pitchfinder.YIN();
const freqbuffer = fs.readFileSync(wave);
const decoded = wav.decode(freqbuffer); // get audio data from file using `wav-decoder`
const float32Array = decoded.channelData[0]; // get a single channel of sound
note = detectPitch(float32Array); // null if pitch cannot be identified
// check for null value
if (!note) {
throw "Could not auto-detect frequency"
} else {
console.log("Frequency detected: " + parseFloat(note) + " Hz")
}
}
var freq = parseFloat(note) || tonal.toFreq(note)
if (note != freq) {
console.log(note + " equals " + freq + " Hz")
}
// check frequency
if (!freq || !_.isFinite(freq)) {
throw "Note frequency \"" + note + "\" is invalid."
}
// get original wav data
if (_.isString(wave)) {
// read file w/ filename
var buffer = fs.readFileSync(wave)
// get data
wave = wav.decode(buffer)
} else {
throw "Wav data is not legible."
}
// resample
// unused variable
// var samplingFreq = freq * LSDJ.constants.SAMPLES_PER_FRAMES
var n = LSDJ.constants.SAMPLES_PER_FRAMES * LSDJ.constants.FRAMES_PER_TABLE
var data = wave.channelData[options.channel]
// check for interpolation
if (options.linear || options.exp) {
var cycles = ~~((data.length * freq) / wave.sampleRate)
var cycleInterval = cycles/LSDJ.constants.FRAMES_PER_TABLE
console.log('Samples: ' + data.length + '\nSample rate: ' + wave.sampleRate + '\nCycles: ' + cycles)
var rangeList = []
var sample = 0
// linear interpolation
if (options.linear || cycles < 32) {
if (options.exp) {
console.log('Sample is too short. Reverting to linear interpolation')
options.exp = 0
}
console.log('Linear interpolation\nTaking frame every ' + ~~(cycleInterval) + ' cycles')
sample = 0
for (cycle = 0; cycle < 16; cycle++) {
sample = ~~(cycleInterval) * cycle * LSDJ.constants.SAMPLES_PER_FRAMES
for (nextSample=0; nextSample < 32; nextSample++) {
// console.log(sample)
rangeList.push(sample)
sample = sample + 1
}
}
// logarithmic interpolation
} else if (options.exp) {
console.log('Exponential interpolation')
cycle = 0
cycleLog = Math.pow(Math.E, (Math.log(cycles) / LSDJ.constants.FRAMES_PER_TABLE))
for (cyc = 0; cyc < 16; cyc++) {
// console.log('Cycle number ' + (cycle/LSDJ.constants.SAMPLES_PER_FRAMES))
for (nextSample=0; nextSample < 32; nextSample++) {
// console.log(cycle)
rangeList.push(~~(cycle))
cycle = cycle + 1
}
cycle = (Math.round(Math.pow(cycleLog,cyc*1.1)) * LSDJ.constants.SAMPLES_PER_FRAMES) + (cyc * LSDJ.constants.SAMPLES_PER_FRAMES)
}
}
} else {
var rangeList = _.range(n)
}
var samples = _.map(rangeList, function (i) {
// compute adequate time
var t = (i / (freq * LSDJ.constants.SAMPLES_PER_FRAMES))
// get sample number in original coordinates
var j = wave.sampleRate * t
// get value, return it (interpolated w/ next value, currently disabled)
return data[~~j]// + ((j - ~~j) * (data[1 + ~~j] || 0))
})
// normalize if required
if (options.normalize) {
var max = Math.abs(_.maxBy(samples, Math.abs))
samples = _.map(samples, function (i) { return i / max })
}
// bitcrush
samples = _.map(samples, function(float) {
return ~~((float + 1.0) * LSDJ.constants.FRAME_RESOLUTION * 0.5)
})
// return samples
return samples
}
|
JavaScript
| 0 |
@@ -1076,16 +1076,17 @@
)%0A %7D%0A
+
%7D%0A %0A
|
75007bee82d47f7ca08677bb27164361a4e86d3d
|
Add missing verifier API test
|
lib/referee.test.js
|
lib/referee.test.js
|
"use strict";
var referee = require("./referee");
var assert = require("assert");
describe("API", function() {
describe(".add", function() {
it("should be a binary Function named 'add'", function() {
assert.equal(typeof referee.add, "function");
assert.equal(referee.add.length, 2);
});
});
describe(".assert", function() {
it("should be a binary Function named 'assert'", function() {
assert.equal(typeof referee.assert, "function");
assert.equal(referee.assert.length, 2);
});
});
describe(".refute", function() {
it("should be a binary Function named 'refute'", function() {
assert.equal(typeof referee.refute, "function");
assert.equal(referee.refute.length, 2);
});
});
describe(".expect", function() {
it("should be a zero-arity Function named 'expect'", function() {
assert.equal(typeof referee.expect, "function");
assert.equal(referee.expect.length, 0);
});
});
describe(".fail", function() {
it("should be a binary Function named 'fail'", function() {
assert.equal(typeof referee.fail, "function");
assert.equal(referee.fail.length, 2);
});
});
describe(".pass", function() {
it("should be a unary Function named 'pass'", function() {
assert.equal(typeof referee.pass, "function");
assert.equal(referee.pass.length, 1);
});
});
// this prevents accidental expansions of the public API
it("should only have expected properties", function() {
var expectedProperties = JSON.stringify([
"add",
"assert",
"bind",
"captureException",
"emit",
"errback",
"errbacks",
"expect",
"fail",
"listeners",
"off",
"on",
"once",
"pass",
"refute",
"supervisors",
"verifier"
]);
var actualProperties = JSON.stringify(Object.keys(referee).sort());
assert.equal(actualProperties, expectedProperties);
});
});
|
JavaScript
| 0.000001 |
@@ -1523,24 +1523,277 @@
);%0A %7D);%0A%0A
+ describe(%22.verifier%22, function() %7B%0A it(%22should be a zero-arity Function named 'verifier'%22, function() %7B%0A assert.equal(typeof referee.verifier, %22function%22);%0A assert.equal(referee.verifier.length, 0);%0A %7D);%0A %7D);%0A%0A
// this
|
4c278911dbc198e1f08f09b9909846a4da30a4b2
|
fix bug with renderbuffer initialization from radius
|
lib/renderbuffer.js
|
lib/renderbuffer.js
|
var check = require('./util/check')
var values = require('./util/values')
var GL_RENDERBUFFER = 0x8D41
var GL_RGBA4 = 0x8056
var GL_RGB5_A1 = 0x8057
var GL_RGB565 = 0x8D62
var GL_DEPTH_COMPONENT16 = 0x81A5
var GL_STENCIL_INDEX8 = 0x8D48
var GL_DEPTH_STENCIL = 0x84F9
var GL_SRGB8_ALPHA8_EXT = 0x8C43
var GL_RGBA32F_EXT = 0x8814
var GL_RGBA16F_EXT = 0x881A
var GL_RGB16F_EXT = 0x881B
module.exports = function (gl, extensions, limits, stats) {
var formatTypes = {
'rgba4': GL_RGBA4,
'rgb565': GL_RGB565,
'rgb5 a1': GL_RGB5_A1,
'depth': GL_DEPTH_COMPONENT16,
'stencil': GL_STENCIL_INDEX8,
'depth stencil': GL_DEPTH_STENCIL
}
if (extensions.ext_srgb) {
formatTypes['srgba'] = GL_SRGB8_ALPHA8_EXT
}
if (extensions.ext_color_buffer_half_float) {
formatTypes['rgba16f'] = GL_RGBA16F_EXT
formatTypes['rgb16f'] = GL_RGB16F_EXT
}
if (extensions.webgl_color_buffer_float) {
formatTypes['rgba32f'] = GL_RGBA32F_EXT
}
var renderbufferCount = 0
var renderbufferSet = {}
function REGLRenderbuffer (renderbuffer) {
this.id = renderbufferCount++
this.refCount = 1
this.renderbuffer = renderbuffer
this.format = GL_RGBA4
this.width = 0
this.height = 0
}
REGLRenderbuffer.prototype.decRef = function () {
if (--this.refCount === 0) {
destroy(this)
}
}
function destroy (rb) {
var handle = rb.renderbuffer
check(handle, 'must not double destroy renderbuffer')
gl.bindRenderbuffer(GL_RENDERBUFFER, null)
gl.deleteRenderbuffer(handle)
rb.renderbuffer = null
rb.refCount = 0
delete renderbufferSet[rb.id]
stats.renderbufferCount--
}
function createRenderbuffer (a, b) {
var renderbuffer = new REGLRenderbuffer(gl.createRenderbuffer())
renderbufferSet[renderbuffer.id] = renderbuffer
stats.renderbufferCount++
function reglRenderbuffer (a, b) {
var w = 0
var h = 0
var format = GL_RGBA4
if (typeof a === 'object' && a) {
var options = a
if ('shape' in options) {
var shape = options.shape
check(Array.isArray(shape) && shape.length >= 2,
'invalid renderbuffer shape')
w = shape[0] | 0
h = shape[1] | 0
} else {
if ('radius' in options) {
w = h = options.radius | 0
}
if ('width' in options) {
w = options.width | 0
}
if ('height' in options) {
h = options.height | 0
}
}
if ('format' in options) {
check.parameter(options.format, formatTypes,
'invalid renderbuffer format')
format = formatTypes[options.format]
}
} else if (typeof a === 'number') {
w = a | 0
if (typeof b === 'number') {
h = b | 0
} else {
w = h
}
} else if (!a) {
w = h = 1
} else {
check.raise('invalid arguments to renderbuffer constructor')
}
// check shape
check(
w > 0 && h > 0 &&
w <= limits.maxRenderbufferSize && h <= limits.maxRenderbufferSize,
'invalid renderbuffer size')
if (w === renderbuffer.width &&
h === renderbuffer.height &&
format === renderbuffer.format) {
return
}
reglRenderbuffer.width = renderbuffer.width = w
reglRenderbuffer.height = renderbuffer.height = h
renderbuffer.format = format
gl.bindRenderbuffer(GL_RENDERBUFFER, renderbuffer.renderbuffer)
gl.renderbufferStorage(GL_RENDERBUFFER, format, w, h)
return reglRenderbuffer
}
reglRenderbuffer(a, b)
function resize (w_, h_) {
var w = w_ | 0
var h = (h_ | 0) || w
if (w === renderbuffer.width && h === renderbuffer.height) {
return
}
// check shape
check(
w > 0 && h > 0 &&
w <= limits.maxRenderbufferSize && h <= limits.maxRenderbufferSize,
'invalid renderbuffer size')
reglRenderbuffer.width = renderbuffer.width = w
reglRenderbuffer.height = renderbuffer.height = h
gl.bindRenderbuffer(GL_RENDERBUFFER, renderbuffer.renderbuffer)
gl.renderbufferStorage(GL_RENDERBUFFER, renderbuffer.format, w, h)
return reglRenderbuffer
}
reglRenderbuffer.resize = resize
reglRenderbuffer._reglType = 'renderbuffer'
reglRenderbuffer._renderbuffer = renderbuffer
reglRenderbuffer.destroy = function () {
renderbuffer.decRef()
}
return reglRenderbuffer
}
return {
create: createRenderbuffer,
clear: function () {
values(renderbufferSet).forEach(destroy)
}
}
}
|
JavaScript
| 0 |
@@ -2857,21 +2857,21 @@
-w = h
+h = w
%0A
@@ -3644,36 +3644,8 @@
%7D%0A%0A
- reglRenderbuffer(a, b)%0A%0A
@@ -4274,24 +4274,52 @@
ffer%0A %7D%0A%0A
+ reglRenderbuffer(a, b)%0A%0A
reglRend
|
217d14e78dd7448f274da1dbb29e167f56c5b1ee
|
Fix regression in initial query with dimensionsConfig
|
lib/resolveQuery.js
|
lib/resolveQuery.js
|
import * as regionUtil from './regionUtil'
import humanizeList from 'humanize-list'
const NO_NUMERIC = /\D/
function invalidYear(val) {
return NO_NUMERIC.test(val)
}
export default function resolveQuery(region, srcQuery, headerGroups, dimensionsConfig = {}) {
const targetQuery = Object.assign({}, {
unit: srcQuery.unit,
region: region.prefixedCode,
tableName: srcQuery.tableName,
comparisonRegions: srcQuery.comparisonRegions || [],
dimensions: srcQuery.dimensions.slice()
})
const regionHeaderKey = regionUtil.getHeaderKey(region)
const headerGroupsForRegion = headerGroups.filter(group => group.hasOwnProperty(regionHeaderKey))
const possibleValues = headerGroupsForRegion.find(headerGroup => {
return srcQuery.dimensions.every(dim => headerGroup.hasOwnProperty(dim.name))
})
if (!possibleValues) {
const combinationsForHeaderKey = headerGroupsForRegion
.map(headerGroup => Object.keys(headerGroup).join(', '))
.map(keys => `[${keys}]`)
const dimNames = srcQuery.dimensions.map(dim => dim.name)
throw new Error(
`Found no header group with values for the combination of [${humanizeList([regionHeaderKey, ...dimNames])}]. `
+ `Possible combinations for ${regionHeaderKey} are ${humanizeList(combinationsForHeaderKey, {conjugation: 'or'})}`
)
}
const {year = []} = srcQuery
if (typeof year === 'string') {
if (srcQuery.year === 'latest') {
targetQuery.year = possibleValues.aar.slice(-1)
} else if (srcQuery.year === 'all') {
targetQuery.year = 'all'
} else {
throw new Error(`The .year property of a query must be either 'latest', 'all' or an array of years. Got ${JSON.stringify(year)}`)
}
} else if (Array.isArray(year)) {
const invalidYears = year.filter(invalidYear)
if (invalidYears.length > 0) {
throw new Error(`Found invalid years in query.year: ${invalidYears.join(', ')}`)
}
targetQuery.year = year
} else {
throw new Error(`The .year property of a query must be either 'latest', 'all' or an array of years. Got ${JSON.stringify(year)}`)
}
targetQuery.dimensions = targetQuery.dimensions.map(dim => {
const config = dimensionsConfig[dim.name]
if (config && config.include) {
return Object.assign({}, dim, {
variables: config.include
})
}
return dim
})
return targetQuery
}
|
JavaScript
| 0.000018 |
@@ -2107,261 +2107,8 @@
%7D%0A%0A
- targetQuery.dimensions = targetQuery.dimensions.map(dim =%3E %7B%0A const config = dimensionsConfig%5Bdim.name%5D%0A if (config && config.include) %7B%0A return Object.assign(%7B%7D, dim, %7B%0A variables: config.include%0A %7D)%0A %7D%0A return dim%0A %7D)%0A%0A
re
|
39f28d7211baf8855dc1b6e4b07e964c5890ead7
|
Improve error handling of internal server
|
lib/routes/proxy.js
|
lib/routes/proxy.js
|
const pnut = require('pnut-butter')
module.exports = async ctx => {
const { method, state, params, query, request } = ctx
if (state.user) {
pnut.token = state.user.token
const resource = `/${params[0]}`
const body = method.toLowerCase() === 'get'
? query
: request.body
const url = resource + request.search
ctx.body = await pnut.custom(url, method, body)
.then(res => {
return res
}).catch(err => {
console.error(err)
})
}
// ctx.body = 'hello'
}
|
JavaScript
| 0.000001 |
@@ -118,16 +118,26 @@
%7D = ctx%0A
+ try %7B%0A
if (st
@@ -148,12 +148,34 @@
user
+ && state.user.token
) %7B%0A
+
@@ -204,16 +204,22 @@
r.token%0A
+ %7D%0A
cons
@@ -377,23 +377,24 @@
ch%0A c
-tx.body
+onst res
= await
@@ -436,16 +436,17 @@
.
-then(res
+catch(err
=%3E
@@ -459,105 +459,234 @@
-return res%0A %7D).
+console.error(err)%0A %7D)%0A ctx.status = res.meta.code%0A ctx.body = res%0A %7D
catch
+
(e
-rr =%3E
+)
%7B%0A
- console.error(err)%0A %7D)%0A %7D%0A // ctx.body = 'hello'
+ctx.status = 401%0A ctx.body = %7B%0A meta: %7B%0A code: ctx.status,%0A message: 'You have to login.'%0A %7D%0A %7D%0A %7D
%0A%7D%0A
|
89ad49cd0ef59dc6692f6be267565499bcb44e21
|
make sure _br.limit doesn't remove LineBreak if previous token is a comment. fixes #154
|
lib/lineBreak/lineBreak.js
|
lib/lineBreak/lineBreak.js
|
"use strict";
// Line break helpers
var _tk = require('rocambole-token');
var debug = require('debug');
var debugBefore = debug('esformatter:br:before');
var debugAfter = debug('esformatter:br:after');
var debugBetween = debug('esformatter:br:between');
// yeah, we use semver to parse integers. it's lame but works and will give
// more flexibility while still keeping a format that is easy to read
var semver = require('semver');
var _curOpts;
// ---
exports.setOptions = setOptions;
function setOptions(opts) {
_curOpts = opts;
}
exports.limit = limit;
function limit(token, type) {
limitBefore(token, type);
limitAfter(token, type);
}
exports.limitBefore = limitBefore;
function limitBefore(token, type) {
var expected = getExpect('before', type);
debugBefore('[limitBefore] type: %s, expected: %s', type, expected);
if (expected < 0) return; // noop
var start = getStartToken(token);
limitInBetween('before', start, token, expected);
}
exports.limitAfter = limitAfter;
function limitAfter(token, type) {
var expected = getExpect('after', type);
debugAfter('[limitAfter] type: %s, expected: %s', type, expected);
if (expected < 0) return; // noop
var end = getEndToken(token);
limitInBetween('after', token, end, expected);
}
function getExpect(location, type) {
var expected;
// we allow expected value (number) as 2nd argument or the node type (string)
if (typeof type === 'string') {
expected = _curOpts[location][type];
} else {
expected = type;
}
// default is noop, explicit is better than implicit
expected = expected != null? expected : -1;
if (typeof expected === 'boolean') {
// if user sets booleans by mistake we simply add one if missing (true)
// or remove all if false
expected = expected? '>=1' : 0;
}
if (expected < 0) {
// noop
return expected;
} else if (typeof expected === 'number') {
return String(expected);
} else {
return expected;
}
}
function limitInBetween(location, start, end, expected) {
var n = getDiff(start, end, expected);
debugBetween('[limitInBetween] diff: %d', n);
if (n) {
_tk.removeInBetween(start, end, 'WhiteSpace');
}
if (n < 0) {
_tk.removeInBetween(start, end, function(token){
return token.type === 'LineBreak' && n++ < 0;
});
} else if(n > 0) {
var target = location === 'after' ? start : end;
var insertNextTo = _tk[location];
while (n-- > 0) {
insertNextTo(target, {
type: 'LineBreak',
value: _curOpts.value
});
}
}
}
function getDiff(start, end, expected) {
// start will only be equal to end if it's start or file
if (start === end) return 0;
var count = countBrInBetween(start, end);
// yeah, it's ugly to strings to compare integers but was quickest solution
var vCount = String(count) +'.0.0';
if (semver.satisfies(vCount, expected)) {
return 0;
} else {
return getSatisfyingMatch(count, vCount, expected) - count;
}
}
function getSatisfyingMatch(count, vCount, expected) {
var result;
var diff = semver.gtr(vCount, expected)? -1 : 1;
count += diff;
while (result == null && count >= 0 && count < 100) {
if (semver.satisfies(String(count) + '.0.0', expected)) {
result = count;
}
count += diff;
}
return parseInt(result, 10);
}
function countBrInBetween(start, end) {
var count = 0;
_tk.eachInBetween(start, end, function(token){
if (_tk.isBr(token)) count++;
});
return count;
}
function getEndToken(token) {
var end = _tk.findNextNonEmpty(token);
if (shouldSkipToken(end)) {
end = _tk.findNextNonEmpty(end);
}
return end? end : token.root.endToken;
}
function shouldSkipToken(token) {
// if comment is at same line we skip it unless it has a specific rule that
// would add line breaks
var result = _tk.isComment(token) && !isOnSeparateLine(token);
return result && getExpect('before', token.type) <= 0;
}
function isOnSeparateLine(token) {
return _tk.isBr(token.prev) || (
_tk.isEmpty(token.prev) && _tk.isBr(token.prev.prev)
);
}
function getStartToken(token) {
var end = _tk.findPrevNonEmpty(token);
return end? end : token.root.startToken;
}
|
JavaScript
| 0.000001 |
@@ -2300,16 +2300,62 @@
n++ %3C 0
+ &&%0A !siblingIsComment(location, token)
;%0A %7D)
@@ -2592,32 +2592,172 @@
;%0A %7D%0A %7D%0A%7D%0A%0A%0A
+function siblingIsComment(location, token) %7B%0A var prop = location === 'before' ? 'prev' : 'next';%0A return _tk.isComment(token%5Bprop%5D);%0A%7D%0A%0A%0A
function getDiff
|
5dcc93224753a2545d9be48dfe490a42d3fef947
|
Refresh cache on changes and handle access to evicted peer
|
lib/server/swarm.js
|
lib/server/swarm.js
|
module.exports = Swarm
var debug = require('debug')('bittorrent-tracker')
var LRU = require('lru')
var randomIterate = require('random-iterate')
// Regard this as the default implementation of an interface that you
// need to support when overriding Server.createSwarm() and Server.getSwarm()
function Swarm (infoHash, server) {
this.peers = new LRU({
max: server.peersCacheLength || 10000,
maxAge: server.peersCacheTtl || 900 // 900s = 15 minutes
})
this.complete = 0
this.incomplete = 0
}
Swarm.prototype.announce = function (params, cb) {
var self = this
var id = params.type === 'ws' ? params.peer_id : params.addr
// Mark the source peer as recently used in cache
var peer = self.peers.get(id)
if (params.event === 'started') {
self._onAnnounceStarted(params, peer)
} else if (params.event === 'stopped') {
self._onAnnounceStopped(params, peer)
} else if (params.event === 'completed') {
self._onAnnounceCompleted(params, peer)
} else if (params.event === 'update') {
self._onAnnounceUpdate(params, peer)
} else {
cb(new Error('invalid event'))
return
}
cb(null, {
complete: self.complete,
incomplete: self.incomplete,
peers: self._getPeers(params.numwant, params.peer_id, !!params.socket)
})
}
Swarm.prototype.scrape = function (params, cb) {
cb(null, {
complete: this.complete,
incomplete: this.incomplete
})
}
Swarm.prototype._onAnnounceStarted = function (params, peer) {
if (peer) {
debug('unexpected `started` event from peer that is already in swarm')
return this._onAnnounceUpdate(params, peer) // treat as an update
}
if (params.left === 0) this.complete += 1
else this.incomplete += 1
var id = params.type === 'ws' ? params.peer_id : params.addr
peer = this.peers.set(id, {
type: params.type,
complete: params.left === 0,
peerId: params.peer_id, // as hex
ip: params.ip,
port: params.port,
socket: params.socket // only websocket
})
}
Swarm.prototype._onAnnounceStopped = function (params, peer) {
if (!peer) {
debug('unexpected `stopped` event from peer that is not in swarm')
return // do nothing
}
if (peer.complete) this.complete -= 1
else this.incomplete -= 1
var id = params.type === 'ws' ? params.peer_id : params.addr
this.peers.remove(id)
}
Swarm.prototype._onAnnounceCompleted = function (params, peer) {
if (!peer) {
debug('unexpected `completed` event from peer that is not in swarm')
return this._onAnnounceStarted(params, peer) // treat as a start
}
if (peer.complete) {
debug('unexpected `completed` event from peer that is already marked as completed')
return // do nothing
}
this.complete += 1
this.incomplete -= 1
peer.complete = true
}
Swarm.prototype._onAnnounceUpdate = function (params, peer) {
if (!peer) {
debug('unexpected `update` event from peer that is not in swarm')
return this._onAnnounceStarted(params, peer) // treat as a start
}
if (!peer.complete && params.left === 0) {
this.complete += 1
this.incomplete -= 1
peer.complete = true
}
}
Swarm.prototype._getPeers = function (numwant, ownPeerId, isWebRTC) {
var peers = []
var ite = randomIterate(Object.keys(this.peers.cache))
var peerId
while ((peerId = ite()) && peers.length < numwant) {
// Don't mark the peer as most recently used on announce
var peer = this.peers.peek(peerId)
if (isWebRTC && peer.peerId === ownPeerId) continue // don't send peer to itself
if ((isWebRTC && peer.type !== 'ws') || (!isWebRTC && peer.type === 'ws')) continue // send proper peer type
peers.push(peer)
}
return peers
}
|
JavaScript
| 0 |
@@ -720,16 +720,59 @@
et(id)%0A%0A
+ // Get the peer back in swarm if missing%0A
if (pa
@@ -791,24 +791,33 @@
== 'started'
+ %7C%7C !peer
) %7B%0A self
@@ -845,37 +845,35 @@
arams, peer)%0A %7D
- else
+%0A%0A
if (params.even
@@ -1113,16 +1113,48 @@
%7D else
+ if (params.event !== 'started')
%7B%0A c
@@ -2838,16 +2838,106 @@
= true%0A
+ var id = params.type === 'ws' ? params.peer_id : params.addr%0A this.peers.set(id, peer)%0A
%7D%0A%0ASwarm
@@ -3270,16 +3270,110 @@
= true%0A
+ var id = params.type === 'ws' ? params.peer_id : params.addr%0A this.peers.set(id, peer)%0A
%7D%0A%7D%0A%0AS
|
8350dbfdbc54f0c1496eefc2288292c58bfea7ba
|
Disable minify with `generate.minify: false`
|
lib/generate.js
|
lib/generate.js
|
'use strict'
import fs from 'fs-extra'
import pify from 'pify'
import _ from 'lodash'
import { resolve, join, dirname, sep } from 'path'
import { isUrl, promisifyRoute, waitFor } from './utils'
import { minify } from 'html-minifier'
const debug = require('debug')('nuxt:generate')
const copy = pify(fs.copy)
const remove = pify(fs.remove)
const writeFile = pify(fs.writeFile)
const mkdirp = pify(fs.mkdirp)
const defaults = {
dir: 'dist',
routes: [],
interval: 0,
minify: {
collapseBooleanAttributes: true,
collapseWhitespace: true,
decodeEntities: true,
minifyCSS: true,
minifyJS: true,
processConditionalComments: true,
removeAttributeQuotes: false,
removeComments: false,
removeEmptyAttributes: true,
removeOptionalTags: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: false,
removeStyleLinkTypeAttributes: false,
removeTagWhitespace: false,
sortAttributes: true,
sortClassName: true,
trimCustomFragments: true,
useShortDoctype: true
}
}
export default async function () {
const s = Date.now()
let errors = []
/*
** Set variables
*/
this.options.generate = _.defaultsDeep(this.options.generate, defaults)
var self = this
var srcStaticPath = resolve(this.srcDir, 'static')
var srcBuiltPath = resolve(this.dir, '.nuxt', 'dist')
var distPath = resolve(this.dir, this.options.generate.dir)
var distNuxtPath = join(distPath, (isUrl(this.options.build.publicPath) ? '' : this.options.build.publicPath))
/*
** Launch build process
*/
await self.build()
/*
** Clean destination folder
*/
try {
await remove(distPath)
debug('Destination folder cleaned')
} catch (e) {}
/*
** Copy static and built files
*/
if (fs.existsSync(srcStaticPath)) {
await copy(srcStaticPath, distPath)
}
await copy(srcBuiltPath, distNuxtPath)
debug('Static & build files copied')
if (this.options.router.mode !== 'hash') {
// Resolve config.generate.routes promises before generating the routes
try {
var generateRoutes = await promisifyRoute(this.options.generate.routes || [])
} catch (e) {
console.error('Could not resolve routes') // eslint-disable-line no-console
console.error(e) // eslint-disable-line no-console
process.exit(1)
throw e // eslint-disable-line no-unreachable
}
/*
** Generate html files from routes
*/
generateRoutes.forEach((route) => {
if (this.routes.indexOf(route) < 0) {
this.routes.push(route)
}
})
}
/*
** Generate only index.html for router.mode = 'hash'
*/
let routes = (this.options.router.mode === 'hash') ? ['/'] : this.routes
while (routes.length) {
let n = 0
await Promise.all(routes.splice(0, 500).map(async (route) => {
await waitFor(n++ * self.options.generate.interval)
try {
var { html, error } = await self.renderRoute(route, { _generate: true })
if (error) {
errors.push({ type: 'handled', route, error })
}
} catch (err) {
/* istanbul ignore next */
errors.push({ type: 'unhandled', route, error: err })
}
try {
var minifiedHtml = minify(html, self.options.generate.minify)
} catch (err) /* istanbul ignore next */ {
let minifyErr = new Error(`HTML minification failed. Make sure the route generates valid HTML. Failed HTML:\n ${html}`)
errors.push({ type: 'unhandled', route, error: minifyErr })
}
var path = join(route, sep, 'index.html') // /about -> /about/index.html
debug('Generate file: ' + path)
path = join(distPath, path)
// Make sure the sub folders are created
await mkdirp(dirname(path))
await writeFile(path, minifiedHtml, 'utf8')
}))
}
// Add .nojekyll file to let Github Pages add the _nuxt/ folder
// https://help.github.com/articles/files-that-start-with-an-underscore-are-missing/
const nojekyllPath = resolve(distPath, '.nojekyll')
writeFile(nojekyllPath, '')
const duration = Math.round((Date.now() - s) / 100) / 10
debug(`HTML Files generated in ${duration}s`)
if (errors.length) {
const report = errors.map(({ type, route, error }) => {
/* istanbul ignore if */
if (type === 'unhandled') {
return `Route: '${route}'\n${error.stack}`
} else {
return `Route: '${route}' thrown an error: \n` + JSON.stringify(error)
}
})
console.error('==== Error report ==== \n' + report.join('\n\n')) // eslint-disable-line no-console
}
}
|
JavaScript
| 0.000025 |
@@ -1221,26 +1221,8 @@
ts)%0A
- var self = this%0A
va
@@ -1545,20 +1545,20 @@
await
-self
+this
.build()
@@ -2808,20 +2808,20 @@
r(n++ *
-self
+this
.options
@@ -2850,41 +2850,46 @@
-try %7B%0A var %7B html, error %7D
+let html%0A try %7B%0A const res
= a
@@ -2893,20 +2893,20 @@
= await
-self
+this
.renderR
@@ -2946,20 +2946,48 @@
-if (
+html = res.html%0A if (res.
error) %7B
@@ -3040,16 +3040,27 @@
e, error
+: res.error
%7D)%0A
@@ -3202,35 +3202,69 @@
-try %7B%0A var minifiedH
+if (this.options.generate.minify) %7B%0A try %7B%0A h
tml
@@ -3282,12 +3282,12 @@
ml,
-self
+this
.opt
@@ -3308,16 +3308,18 @@
minify)%0A
+
%7D
@@ -3367,18 +3367,22 @@
-le
+ cons
t minify
@@ -3491,32 +3491,34 @@
html%7D%60)%0A
+
errors.push(%7B ty
@@ -3567,24 +3567,26 @@
)%0A
+
%7D%0A
var path
@@ -3577,19 +3577,27 @@
%7D%0A
-var
+%7D%0A let
path =
@@ -3843,17 +3843,9 @@
th,
-minifiedH
+h
tml,
|
220ea779b005c3eaa43eba27bf902cbdbe5c8c8e
|
fix missing lodash
|
lib/stopsOpacity.js
|
lib/stopsOpacity.js
|
export default function (stops, opacity) {
if (isNaN(opacity)) {
opacity = 1;
}
return _.reduce(stops, (ret, color, key) => {
ret[key] = color.alpha(color.alpha() * opacity).rgbaString();
return ret;
}, {});
}
|
JavaScript
| 0.999977 |
@@ -1,8 +1,32 @@
+import _ from 'lodash';%0A
export d
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.